feat: 카카오 계정의 본인 복구와 인증 후 연결 교체를 추가한다

This commit is contained in:
Hide_D committed 2026-11-07 21:31:16 +09:00
1 parent d1cdf8a85f
commit c81d304073
22 files changed
+1338 -199

No files matched your search

@@ -103,6 +103,7 @@ const EXPENSIVE_ACTIONS = new Set([
'auth.bootstrapLocal',
'auth.kakaoExchange',
'auth.kakaoResolveAccount',
'auth.kakaoLinkWithPassword',
'auth.kakaoSetPassword',
'auth.register',
'auth.registerLocal',
@@ -1,3 +1,6 @@
import { authorizeKakaoLink, matchesKakaoLinkSnapshot } from './kakaoLinkPolicy.js';
import { assertLoginAllowed } from './deletionRecovery.js';
import type { CompleteKakaoLinkInput } from './userRepository.js';
import { randomUUID } from 'node:crypto';
import { createPasswordHasher, type PasswordHasher } from './passwordHasher.js';
@@ -29,6 +32,7 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
const usersByOauthId = new Map<string, UserRecord>();
const usersByEmail = new Map<string, UserRecord>();
const retiredKakaoIds = new Set<string>();
const detachedKakaoOwners = new Map<string, string>();
const iconsById = new Map<string, UserIconRecord>();
const specialAccessGrantsById = new Map<string, SpecialAccountAccessGrantRecord>();
@@ -42,6 +46,62 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
).toISOString();
return {
async findDetachedKakaoOwner(oauthId: string): Promise<string | null> {
return detachedKakaoOwners.get(oauthId) ?? null;
},
async completeKakaoIdentityLink(userId: string, input: CompleteKakaoLinkInput): Promise<UserRecord> {
const password = input.password ? await hasher.hash(input.password) : undefined;
const user = [...usersByName.values()].find((row) => row.id === userId);
if (!user || !matchesKakaoLinkSnapshot(user, input.expected))
throw new Error('Kakao recovery account changed.');
assertLoginAllowed(user);
if (
authorizeKakaoLink(
user,
input.email,
input.authorization === 'PASSWORD',
input.firstUserId,
input.verifiedAt
) !== input.authorization
)
throw new Error('Kakao recovery authorization changed.');
const email = input.email.toLowerCase();
const owner = usersByOauthId.get(`KAKAO:${input.oauthId}`);
const emailOwner = usersByEmail.get(email);
const detached = detachedKakaoOwners.get(input.oauthId);
if (
retiredKakaoIds.has(input.oauthId) ||
(detached && detached !== userId) ||
(owner && owner.id !== userId) ||
(emailOwner && emailOwner.id !== userId)
)
throw new Error('Kakao recovery identity ownership changed.');
if (user.passwordResetRequired && !password) throw new Error('A new password is required.');
if (user.oauthId && user.oauthId !== input.oauthId) {
detachedKakaoOwners.set(user.oauthId, userId);
usersByOauthId.delete(`KAKAO:${user.oauthId}`);
}
if (user.email) usersByEmail.delete(user.email.toLowerCase());
Object.assign(user, {
oauthType: 'KAKAO',
oauthId: input.oauthId,
email,
oauthInfo: input.oauthInfo,
kakaoVerifiedAt: input.verifiedAt.toISOString(),
kakaoTalkVerifiedUntil: input.talkVerifiedUntil.toISOString(),
authRevision: (user.authRevision ?? 0) + 1,
sessionRevokedBefore: input.verifiedAt.toISOString(),
kakaoReplacementApprovedUntil: undefined,
kakaoReplacementApprovedByUserId: undefined,
kakaoReplacementReason: undefined,
...(password
? { passwordHash: password.hash, passwordSalt: password.salt, passwordResetRequired: false }
: {}),
});
usersByOauthId.set(`KAKAO:${input.oauthId}`, user);
usersByEmail.set(email, user);
return user;
},
async findById(id: string): Promise<UserRecord | null> {
for (const user of usersByName.values()) {
if (user.id === id) {
@@ -103,6 +163,7 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
if (
input.oauth &&
(retiredKakaoIds.has(input.oauth.id) ||
detachedKakaoOwners.has(input.oauth.id) ||
usersByOauthId.has(`${input.oauth.type}:${input.oauth.id}`) ||
usersByEmail.has(input.oauth.email.toLowerCase()))
) {
@@ -204,9 +265,19 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
}
throw new Error('User not found.');
},
async markKakaoTalkVerified(userId: string, validUntil: Date): Promise<UserRecord> {
async markKakaoTalkVerified(
userId: string,
validUntil: Date,
authRevision?: number,
oauthId?: string
): Promise<UserRecord> {
for (const user of usersByName.values()) {
if (user.id === userId) {
if (
(authRevision !== undefined && (user.authRevision ?? 0) !== authRevision) ||
(oauthId && user.oauthId !== oauthId)
)
throw new Error('Kakao identity changed.');
user.kakaoTalkVerifiedUntil = validUntil.toISOString();
return user;
}
@@ -305,6 +376,7 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
!user.kakaoReplacementApprovedByUserId ||
!user.kakaoReplacementReason ||
retiredKakaoIds.has(input.oauthId) ||
(detachedKakaoOwners.has(input.oauthId) && detachedKakaoOwners.get(input.oauthId) !== userId) ||
(oauthOwner && oauthOwner.id !== userId) ||
(emailOwner && emailOwner.id !== userId)
) {
@@ -194,16 +194,17 @@ export const requireKakaoTalkProof = async (options: {
kakaoClient: KakaoOAuthClient;
oauthSessions: OAuthSessionStore;
publicBaseUrl: string;
oauthSessionId?: string;
now?: Date;
}): Promise<KakaoOtpRequired | null> => {
const now = options.now ?? new Date();
const validUntil = parseDate(options.user.kakaoTalkVerifiedUntil);
if (validUntil && isAfter(validUntil, now)) {
if (!options.oauthSessionId && validUntil && isAfter(validUntil, now)) {
return null;
}
const active = await options.oauthSessions.getLoginChallengeForUser(options.user.id);
if (active) {
if (active && active.oauthSessionId === options.oauthSessionId) {
return {
status: 'otp',
challengeId: active.id,
@@ -215,6 +216,9 @@ export const requireKakaoTalkProof = async (options: {
const expiresAt = addSeconds(now, KAKAO_OTP_TTL_SECONDS);
const challenge = await options.oauthSessions.createLoginChallenge({
userId: options.user.id,
authRevision: options.user.authRevision ?? 0,
...(options.user.oauthId ? { oauthId: options.user.oauthId } : {}),
...(options.oauthSessionId ? { oauthSessionId: options.oauthSessionId } : {}),
code: String(randomInt(1000, 10_000)),
attemptsRemaining: KAKAO_OTP_ATTEMPTS,
expiresAt: expiresAt.toISOString(),
@@ -246,7 +250,7 @@ export const verifyKakaoTalkChallenge = async (options: {
oauthSessions: OAuthSessionStore;
users: UserRepository;
now?: Date;
}): Promise<{ user: UserRecord; validUntil: string }> => {
}): Promise<{ user: UserRecord; validUntil: string; pendingLinkSessionId?: string }> => {
const now = options.now ?? new Date();
const result = await options.oauthSessions.verifyLoginChallenge(options.challengeId, options.code, now);
if (result.status === 'expired') {
@@ -268,11 +272,27 @@ export const verifyKakaoTalkChallenge = async (options: {
}
const user = await options.users.findById(result.userId);
if (!user || user.oauthType !== 'KAKAO' || !user.oauthId) {
if (!user || (!result.oauthSessionId && (user.oauthType !== 'KAKAO' || !user.oauthId))) {
throw new KakaoVerificationError('REAUTH_REQUIRED', '카카오 계정 연결 정보를 찾지 못했습니다.');
}
if (
result.authRevision === undefined ||
result.authRevision !== (user.authRevision ?? 0) ||
(result.oauthId && result.oauthId !== user.oauthId)
)
throw new KakaoVerificationError('REAUTH_REQUIRED', '계정 인증 정보가 변경되었습니다. 다시 로그인해 주세요.');
const proofValidUntil = addDays(now, KAKAO_TALK_VERIFICATION_DAYS);
const verified = await options.users.markKakaoTalkVerified(user.id, proofValidUntil);
if (result.oauthSessionId)
return { user, validUntil: proofValidUntil.toISOString(), pendingLinkSessionId: result.oauthSessionId };
const verified = await options.users
.markKakaoTalkVerified(user.id, proofValidUntil, result.authRevision, result.oauthId)
.catch((error: unknown) => {
throw new KakaoVerificationError(
'REAUTH_REQUIRED',
'계정 인증 정보가 변경되었습니다. 다시 로그인해 주세요.',
{ cause: error }
);
});
return { user: verified, validUntil: proofValidUntil.toISOString() };
};
@@ -0,0 +1,62 @@
import { createHash } from 'node:crypto';
import { TRPCError } from '@trpc/server';
import type { UserRecord } from './userRepository.js';
export type KakaoLinkAuthorization = 'EMAIL' | 'PASSWORD' | 'ADMIN';
export interface KakaoLinkSnapshot {
authRevision: number;
oauthType: UserRecord['oauthType'];
oauthId?: string;
email?: string;
passwordFingerprint: string;
}
export const snapshotKakaoLink = (user: UserRecord): KakaoLinkSnapshot => ({
authRevision: user.authRevision ?? 0,
oauthType: user.oauthType,
oauthId: user.oauthId,
email: user.email,
passwordFingerprint: createHash('sha256').update(user.passwordHash).digest('hex'),
});
export const matchesKakaoLinkSnapshot = (user: UserRecord, expected: KakaoLinkSnapshot): boolean =>
(user.authRevision ?? 0) === expected.authRevision &&
user.oauthType === expected.oauthType &&
user.oauthId === expected.oauthId &&
user.email === expected.email &&
createHash('sha256').update(user.passwordHash).digest('hex') === expected.passwordFingerprint;
export const authorizeKakaoLink = (
user: UserRecord,
email: string,
passwordVerified: boolean,
firstUserId: string | undefined,
now = new Date()
): KakaoLinkAuthorization => {
const privileged =
user.id === firstUserId ||
user.roles.some((role) => role === 'superuser' || role === 'admin' || role.startsWith('admin.'));
const approved = Boolean(
user.kakaoReplacementApprovedByUserId &&
user.kakaoReplacementReason &&
user.kakaoReplacementApprovedUntil &&
new Date(user.kakaoReplacementApprovedUntil) > now
);
if (privileged && user.oauthType === 'KAKAO' && user.oauthId) {
if (approved) return 'ADMIN';
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '관리자 계정의 카카오 교체에는 관리자 승인이 필요합니다.',
});
}
if (passwordVerified) return 'PASSWORD';
if (privileged)
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '관리자 계정의 최초 카카오 연결은 기존 비밀번호를 확인해야 합니다.',
});
if (!privileged && user.email?.toLowerCase() === email.toLowerCase()) return 'EMAIL';
if (approved) return 'ADMIN';
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '이메일이 다른 계정은 기존 비밀번호로 확인하거나 관리자에게 복구를 요청해 주세요.',
});
};
+30 -4
View File
@@ -1,5 +1,7 @@
import { randomUUID } from 'node:crypto';
import { parseJson } from '@sammo-ts/common';
import type { KakaoLinkAuthorization, KakaoLinkSnapshot } from './kakaoLinkPolicy.js';
import type { PasswordEnvelopeInput } from './passwordEnvelope.js';
export type OAuthMode = 'login' | 'change_pw' | 'verify';
@@ -22,7 +24,12 @@ export interface OAuthPendingState {
export interface OAuthSession {
id: string;
mode: OAuthMode;
intent?: 'register' | 'link_existing' | 'rejoin' | 'password_setup';
intent?: 'register' | 'link_existing' | 'rejoin' | 'password_setup' | 'identity_link';
identityLink?: {
expected: KakaoLinkSnapshot;
authorization: KakaoLinkAuthorization;
credential?: PasswordEnvelopeInput;
};
targetUserId?: string;
kakaoId: string;
email: string;
@@ -34,6 +41,9 @@ export interface OAuthSession {
}
export interface KakaoLoginChallenge {
authRevision?: number;
oauthId?: string;
oauthSessionId?: string;
id: string;
userId: string;
code: string;
@@ -43,7 +53,7 @@ export interface KakaoLoginChallenge {
}
export type KakaoLoginChallengeResult =
| { status: 'verified'; userId: string }
| { status: 'verified'; userId: string; oauthSessionId?: string; authRevision?: number; oauthId?: string }
| { status: 'mismatch'; attemptsRemaining: number; expiresAt: string }
| { status: 'locked'; expiresAt: string }
| { status: 'expired' };
@@ -55,6 +65,7 @@ export interface OAuthSessionStore {
consumePendingState(state: string): Promise<OAuthPendingState | null>;
createSession(session: Omit<OAuthSession, 'id'>): Promise<OAuthSession>;
consumeSession(sessionId: string): Promise<OAuthSession | null>;
getSession(sessionId: string): Promise<OAuthSession | null>;
getLoginChallengeForUser(userId: string): Promise<KakaoLoginChallenge | null>;
createLoginChallenge(challenge: Omit<KakaoLoginChallenge, 'id'>): Promise<KakaoLoginChallenge>;
verifyLoginChallenge(challengeId: string, code: string, now?: Date): Promise<KakaoLoginChallengeResult>;
@@ -100,7 +111,7 @@ local userKey = ARGV[2] .. challenge.userId
if redis.call('GET', userKey) == challenge.id then
redis.call('DEL', userKey)
end
return cjson.encode({ status = 'verified', userId = challenge.userId })
return cjson.encode({ status = 'verified', userId = challenge.userId, oauthSessionId = challenge.oauthSessionId, authRevision = challenge.authRevision, oauthId = challenge.oauthId })
`;
const consumeOnceScript = `
@@ -188,6 +199,11 @@ export class RedisOAuthSessionStore implements OAuthSessionStore {
return stored;
}
async getSession(sessionId: string): Promise<OAuthSession | null> {
const raw = await this.client.get(this.sessionKey(sessionId));
return raw ? parseJson<OAuthSession>(raw) : null;
}
async consumeSession(sessionId: string): Promise<OAuthSession | null> {
const key = this.sessionKey(sessionId);
const raw = await this.client.eval(consumeOnceScript, { keys: [key], arguments: [] });
@@ -296,6 +312,10 @@ export class InMemoryOAuthSessionStore implements OAuthSessionStore {
return stored;
}
async getSession(sessionId: string): Promise<OAuthSession | null> {
return this.sessions.get(sessionId) ?? null;
}
async consumeSession(sessionId: string): Promise<OAuthSession | null> {
const session = this.sessions.get(sessionId) ?? null;
if (session) {
@@ -357,6 +377,12 @@ export class InMemoryOAuthSessionStore implements OAuthSessionStore {
if (this.userLoginChallenges.get(challenge.userId) === challengeId) {
this.userLoginChallenges.delete(challenge.userId);
}
return { status: 'verified', userId: challenge.userId };
return {
status: 'verified',
userId: challenge.userId,
...(challenge.authRevision !== undefined ? { authRevision: challenge.authRevision } : {}),
...(challenge.oauthId ? { oauthId: challenge.oauthId } : {}),
...(challenge.oauthSessionId ? { oauthSessionId: challenge.oauthSessionId } : {}),
};
}
}
@@ -0,0 +1,144 @@
import { TRPCError } from '@trpc/server';
import type { GatewayApiContext } from '../context.js';
import type { OAuthSession } from './oauthSessionStore.js';
import type { UserRecord } from './userRepository.js';
import { assertLoginAllowed, completeGatewayLogin } from './deletionRecovery.js';
import { authorizeKakaoLink, snapshotKakaoLink } from './kakaoLinkPolicy.js';
import { KakaoVerificationError, readVerifiedKakaoProfile, requireKakaoTalkProof } from './kakaoAccountVerification.js';
import { openPassword } from './registrationInput.js';
const LINK_TTL_MS = 300_000;
const firstUserId = async (ctx: GatewayApiContext): Promise<string | undefined> =>
(await ctx.prisma.appUser.findFirst({ orderBy: { createdAt: 'asc' }, select: { id: true } }))?.id;
export const validatePendingKakaoProfile = async (ctx: GatewayApiContext, session: OAuthSession): Promise<void> => {
const createdAt = Date.parse(session.createdAt);
if (!Number.isFinite(createdAt) || Date.now() - createdAt > LINK_TTL_MS || createdAt > Date.now()) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: '카카오 연결 확인이 만료되었습니다. 카카오 로그인을 다시 진행해 주세요.',
});
}
const profile = await ctx.kakaoClient
.getMe(session.accessToken)
.then(readVerifiedKakaoProfile)
.catch((error: unknown) => {
if (error instanceof KakaoVerificationError)
throw new TRPCError({ code: 'UNAUTHORIZED', message: error.message, cause: error });
throw error;
});
if (profile.kakaoId !== session.kakaoId || profile.email !== session.email.toLowerCase()) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: '카카오 계정 정보가 변경되었습니다. 처음부터 다시 진행해 주세요.',
});
}
};
export const requestPendingKakaoOtp = async (ctx: GatewayApiContext, session: OAuthSession, user: UserRecord) => {
assertLoginAllowed(user);
const challenge = await requireKakaoTalkProof({
user,
accessToken: session.accessToken,
kakaoClient: ctx.kakaoClient,
oauthSessions: ctx.oauthSessions,
publicBaseUrl: ctx.publicBaseUrl,
oauthSessionId: session.id,
}).catch((error: unknown) => {
if (error instanceof KakaoVerificationError)
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: error.message, cause: error });
throw error;
});
if (!challenge) throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR' });
return { ...challenge, successStatus: session.mode === 'verify' ? ('verified' as const) : ('login' as const) };
};
export const beginPendingKakaoLink = async (
ctx: GatewayApiContext,
user: UserRecord,
oauth: OAuthSession,
passwordVerified = false
) => {
await validatePendingKakaoProfile(ctx, oauth);
assertLoginAllowed(user);
const authorization = authorizeKakaoLink(user, oauth.email, passwordVerified, await firstUserId(ctx));
const [owner, detached] = await Promise.all([
ctx.users.findByOauthId('KAKAO', oauth.kakaoId),
ctx.users.findDetachedKakaoOwner(oauth.kakaoId),
]);
if (
(owner && owner.id !== user.id) ||
(detached && detached !== user.id) ||
(await ctx.users.isKakaoIdentityRetired(oauth.kakaoId))
) {
throw new TRPCError({
code: 'CONFLICT',
message: '다른 계정에 귀속된 카카오 계정입니다. 관리자에게 문의해 주세요.',
});
}
const session = await ctx.oauthSessions.createSession({
...oauth,
intent: 'identity_link',
targetUserId: user.id,
createdAt: new Date().toISOString(),
identityLink: { expected: snapshotKakaoLink(user), authorization },
});
if (user.passwordResetRequired) {
return {
status: 'password_setup' as const,
oauthSessionId: session.id,
email: session.email,
successStatus: session.mode === 'verify' ? ('verified' as const) : ('login' as const),
};
}
return requestPendingKakaoOtp(ctx, session, user);
};
export const finishPendingKakaoLink = async (
ctx: GatewayApiContext,
sessionId: string,
userId: string,
validUntil: string
) => {
const pending = await ctx.oauthSessions.consumeSession(sessionId);
if (!pending || pending.intent !== 'identity_link' || !pending.identityLink || pending.targetUserId !== userId) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: '카카오 연결 확인이 만료되었습니다. 다시 로그인해 주세요.',
});
}
await validatePendingKakaoProfile(ctx, pending);
let user: UserRecord;
try {
user = await ctx.users.completeKakaoIdentityLink(userId, {
...pending.identityLink,
oauthId: pending.kakaoId,
email: pending.email,
oauthInfo: {
accessToken: pending.accessToken,
refreshToken: pending.refreshToken,
accessTokenValidUntil: pending.accessTokenValidUntil,
refreshTokenValidUntil: pending.refreshTokenValidUntil,
},
verifiedAt: new Date(),
talkVerifiedUntil: new Date(validUntil),
firstUserId: await firstUserId(ctx),
...(pending.identityLink.credential
? { password: openPassword(ctx.passwordEnvelope, pending.identityLink.credential) }
: {}),
});
} catch (error) {
if (error instanceof TRPCError) throw error;
throw new TRPCError({
code: 'CONFLICT',
message: '계정 연결 상태가 변경되었습니다. 카카오 로그인을 다시 진행해 주세요.',
cause: error,
});
}
try {
await ctx.flushPublisher.publishUserFlush(user.id, 'kakao-account-relinked');
} catch {
// DB의 인증 revision은 이미 증가했다. 다음 접속의 재검증을 유지하고 저장 성공을 반환한다.
}
return { ...(await completeGatewayLogin(ctx, user, 'login')), validUntil };
};
@@ -1,3 +1,6 @@
import { authorizeKakaoLink, matchesKakaoLinkSnapshot } from './kakaoLinkPolicy.js';
import { assertLoginAllowed } from './deletionRecovery.js';
import type { CompleteKakaoLinkInput } from './userRepository.js';
import { GatewayPrisma, type GatewayPrismaClient } from '@sammo-ts/infra';
import { createPasswordHasher, type PasswordHasher } from './passwordHasher.js';
@@ -175,6 +178,91 @@ export const createPostgresUserRepository = (
hasher: PasswordHasher = createPasswordHasher()
): UserRepository => {
return {
async findDetachedKakaoOwner(oauthId: string): Promise<string | null> {
const row = await prisma.kakaoIdentityLinkHistory.findFirst({
where: { previousOauthId: oauthId },
orderBy: { createdAt: 'desc' },
select: { userId: true },
});
return row?.userId ?? null;
},
async completeKakaoIdentityLink(userId: string, input: CompleteKakaoLinkInput): Promise<UserRecord> {
const password = input.password ? await hasher.hash(input.password) : undefined;
return prisma.$transaction(
async (tx) => {
const row = await tx.appUser.findUnique({ where: { id: userId } });
if (!row) throw new Error('Kakao recovery account no longer exists.');
const user = mapUser(row);
assertLoginAllowed(user);
if (!matchesKakaoLinkSnapshot(user, input.expected))
throw new Error('Kakao recovery account changed.');
const first = await tx.appUser.findFirst({ orderBy: { createdAt: 'asc' }, select: { id: true } });
if (
authorizeKakaoLink(
user,
input.email,
input.authorization === 'PASSWORD',
first?.id,
input.verifiedAt
) !== input.authorization
)
throw new Error('Kakao recovery authorization changed.');
if (user.passwordResetRequired && !password) throw new Error('A new password is required.');
const [owner, emailOwner, retired, detached] = await Promise.all([
tx.appUser.findUnique({ where: { oauthId: input.oauthId }, select: { id: true } }),
tx.appUser.findUnique({ where: { email: input.email.toLowerCase() }, select: { id: true } }),
tx.retiredKakaoIdentity.findUnique({ where: { oauthId: input.oauthId }, select: { id: true } }),
tx.kakaoIdentityLinkHistory.findFirst({
where: { previousOauthId: input.oauthId, userId: { not: userId } },
}),
]);
if (
retired ||
detached ||
(owner && owner.id !== userId) ||
(emailOwner && emailOwner.id !== userId)
)
throw new Error('Kakao recovery identity ownership changed.');
if (user.oauthId && user.oauthId !== input.oauthId) {
await tx.kakaoIdentityLinkHistory.create({
data: {
userId,
previousOauthId: user.oauthId,
nextOauthId: input.oauthId,
authorization: input.authorization,
},
});
}
// OTP까지 확인한 새 연결과 비밀번호/인증 revision을 하나의 transaction에 저장한다.
return mapUser(
await tx.appUser.update({
where: { id: userId },
data: {
oauthType: 'KAKAO',
oauthId: input.oauthId,
email: input.email.toLowerCase(),
oauthInfo: input.oauthInfo as GatewayPrisma.JsonObject,
kakaoVerifiedAt: input.verifiedAt,
kakaoTalkVerifiedUntil: input.talkVerifiedUntil,
authRevision: { increment: 1 },
sessionRevokedBefore: input.verifiedAt,
kakaoReplacementApprovedUntil: null,
kakaoReplacementApprovedByUserId: null,
kakaoReplacementReason: null,
...(password
? {
passwordHash: password.hash,
passwordSalt: password.salt,
passwordResetRequired: false,
}
: {}),
},
})
);
},
{ isolationLevel: 'Serializable' }
);
},
async findById(id: string): Promise<UserRecord | null> {
const row = await prisma.appUser.findUnique({
where: {
@@ -286,6 +374,12 @@ export const createPostgresUserRepository = (
if (retired) {
throw new Error('Kakao identity is permanently retired.');
}
if (
await tx.kakaoIdentityLinkHistory.findFirst({
where: { previousOauthId: input.oauth!.id },
})
)
throw new Error('Kakao identity belongs to a former service account.');
return tx.appUser.create({ data });
},
{ isolationLevel: 'Serializable' }
@@ -340,9 +434,18 @@ export const createPostgresUserRepository = (
});
return mapUser(row);
},
async markKakaoTalkVerified(userId: string, validUntil: Date): Promise<UserRecord> {
async markKakaoTalkVerified(
userId: string,
validUntil: Date,
authRevision?: number,
oauthId?: string
): Promise<UserRecord> {
const row = await prisma.appUser.update({
where: { id: userId },
where: {
id: userId,
...(authRevision !== undefined ? { authRevision } : {}),
...(oauthId ? { oauthId } : {}),
},
data: { kakaoTalkVerifiedUntil: validUntil },
});
return mapUser(row);
@@ -357,6 +460,12 @@ export const createPostgresUserRepository = (
if (retired) {
throw new Error('Kakao identity is permanently retired.');
}
if (
await tx.kakaoIdentityLinkHistory.findFirst({
where: { previousOauthId: input.oauthId, userId: { not: userId } },
})
)
throw new Error('Kakao identity belongs to another service account.');
const row = await tx.appUser.update({
where: { id: userId },
data: {
@@ -384,6 +493,12 @@ export const createPostgresUserRepository = (
if (retired) {
throw new Error('Kakao identity is permanently retired.');
}
if (
await tx.kakaoIdentityLinkHistory.findFirst({
where: { previousOauthId: input.oauthId, userId: { not: userId } },
})
)
throw new Error('Kakao identity belongs to another service account.');
const updated = await tx.appUser.updateMany({
where: {
id: userId,
@@ -444,13 +559,17 @@ export const createPostgresUserRepository = (
throw new Error('Kakao account replacement is not approved.');
}
const normalizedEmail = input.email.toLowerCase();
const [oauthOwner, emailOwner, retired] = await Promise.all([
const [oauthOwner, emailOwner, retired, detached] = await Promise.all([
tx.appUser.findUnique({ where: { oauthId: input.oauthId }, select: { id: true } }),
tx.appUser.findUnique({ where: { email: normalizedEmail }, select: { id: true } }),
tx.retiredKakaoIdentity.findUnique({ where: { oauthId: input.oauthId }, select: { id: true } }),
tx.kakaoIdentityLinkHistory.findFirst({
where: { previousOauthId: input.oauthId, userId: { not: userId } },
}),
]);
if (
retired ||
detached ||
(oauthOwner && oauthOwner.id !== userId) ||
(emailOwner && emailOwner.id !== userId)
) {
+21 -1
View File
@@ -1,3 +1,4 @@
import type { KakaoLinkAuthorization, KakaoLinkSnapshot } from './kakaoLinkPolicy.js';
export interface UserRecord {
id: string;
username: string;
@@ -155,7 +156,21 @@ export interface CreateUserInput {
};
}
export interface CompleteKakaoLinkInput {
firstUserId?: string;
expected: KakaoLinkSnapshot;
authorization: KakaoLinkAuthorization;
oauthId: string;
email: string;
oauthInfo: UserOAuthInfo;
verifiedAt: Date;
talkVerifiedUntil: Date;
password?: string;
}
export interface UserRepository {
findDetachedKakaoOwner(oauthId: string): Promise<string | null>;
completeKakaoIdentityLink(userId: string, input: CompleteKakaoLinkInput): Promise<UserRecord>;
findById(id: string): Promise<UserRecord | null>;
findByIds(ids: string[]): Promise<UserRecord[]>;
findByUsername(username: string): Promise<UserRecord | null>;
@@ -168,7 +183,12 @@ export interface UserRepository {
updatePassword(userId: string, password: string): Promise<void>;
updateOAuthInfo(userId: string, oauthInfo: UserOAuthInfo): Promise<void>;
syncKakaoIdentity(userId: string, email: string, oauthInfo: UserOAuthInfo): Promise<UserRecord>;
markKakaoTalkVerified(userId: string, validUntil: Date): Promise<UserRecord>;
markKakaoTalkVerified(
userId: string,
validUntil: Date,
authRevision?: number,
oauthId?: string
): Promise<UserRecord>;
linkKakao(
userId: string,
input: {