Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81e101ffef | ||
|
|
bc54b157c1 | ||
|
|
087517821e | ||
|
|
c81d304073 | ||
|
|
d1cdf8a85f | ||
|
|
dcecb32ef4 | ||
|
|
257a2bea10 | ||
|
|
f16d33e34c |
No files matched your search
@@ -58,8 +58,13 @@ Gateway 자체 릴리스는 Gateway 프로세스 밖의 `release-controller`가
|
||||
Kakao 계정은 OAuth callback과 일반 비밀번호 로그인 모두에서 Kakao 고유 ID와
|
||||
현재 인증 이메일을 다시 확인합니다. 로컬 고유 ID 연결이 없지만 영구 보존된
|
||||
이메일 계정이 있으면 자동 로그인하지 않고 그 계정에 연결할지 묻습니다. 기존
|
||||
계정 연결을 확인하면 이전 Kakao ID와 과거 talk proof를 교체하고 새
|
||||
“나와의 채팅” 숫자 코드로 다시 증명한 뒤에만 Gateway session을 발급합니다.
|
||||
계정 연결은 새 “나와의 채팅” 숫자 코드 인증까지 끝난 뒤에만 저장하며, 그 전에는
|
||||
이전 연결과 비밀번호를 유지합니다. 일반 계정은 카카오가 인증한 동일 이메일로
|
||||
관리자 승인 없이 복구하고, 기존 서비스 비밀번호로 확인하면 이메일이 달라도
|
||||
새 카카오에 연결할 수 있습니다. 관리자 계정 교체에는 승인을 유지하며 다른 계정과의
|
||||
연결·이메일 충돌은 자동 처리하지 않습니다. 새 교체부터 이전 Kakao ID는 원래 계정의
|
||||
복구 이력으로 보존하여 같은 계정에만 다시 연결할 수 있습니다. 기존에 영구 폐기된
|
||||
ID는 계속 차단합니다.
|
||||
Kakao가 `already registered`를 반환했지만 보존 이메일 계정도 없으면 재가입
|
||||
확인 뒤 신규 가입 form을 엽니다. 이미 로컬에 연결된 stable ID의 변경 이메일이
|
||||
다른 계정에 있으면 기존처럼 충돌을 거부합니다.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { toSafeInteger } from '@sammo-ts/common';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -281,7 +282,7 @@ export const auctionRouter = router({
|
||||
callerAlias,
|
||||
remainPoint: point?.value ?? 0,
|
||||
recentLogs: recentLogs.map((log) => ({
|
||||
id: log.id,
|
||||
id: toSafeInteger(log.id),
|
||||
text: log.text,
|
||||
createdAt: log.createdAt.toISOString(),
|
||||
})),
|
||||
@@ -444,7 +445,10 @@ export const auctionRouter = router({
|
||||
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
||||
const nextCloseAt = new Date(result.closeAt);
|
||||
await ctx.redis.zAdd(timerKeys.timerKey, [
|
||||
{ score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)), value: String(auction.id) },
|
||||
{
|
||||
score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)),
|
||||
value: String(auction.id),
|
||||
},
|
||||
]);
|
||||
|
||||
return { ok: true };
|
||||
@@ -521,7 +525,10 @@ export const auctionRouter = router({
|
||||
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
||||
const nextCloseAt = new Date(result.closeAt);
|
||||
await ctx.redis.zAdd(timerKeys.timerKey, [
|
||||
{ score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)), value: String(auction.id) },
|
||||
{
|
||||
score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)),
|
||||
value: String(auction.id),
|
||||
},
|
||||
]);
|
||||
|
||||
return { ok: true };
|
||||
@@ -659,7 +666,10 @@ export const auctionRouter = router({
|
||||
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
||||
const nextCloseAt = new Date(result.closeAt);
|
||||
await ctx.redis.zAdd(timerKeys.timerKey, [
|
||||
{ score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)), value: String(auction.id) },
|
||||
{
|
||||
score: resolveAuctionTimerScore(gameTime, nextCloseAt, BigInt(result.closeTick)),
|
||||
value: String(auction.id),
|
||||
},
|
||||
]);
|
||||
|
||||
return { ok: true };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { CLOCK_OPERATION_PERSISTENCE_LOCK, GamePrisma, acquireGameSchemaAdvisoryXactLock } from '@sammo-ts/infra';
|
||||
import { z } from 'zod';
|
||||
@@ -223,7 +224,7 @@ export const bettingRouter = router({
|
||||
world.currentMonth,
|
||||
`${input.amount} 포인트를 베팅에 사용`
|
||||
);
|
||||
await ctx.db.rankData.upsert({
|
||||
await upsertWithoutSequence(ctx.db.rankData, {
|
||||
where: {
|
||||
generalId_type: {
|
||||
generalId: general.id,
|
||||
@@ -245,7 +246,7 @@ export const bettingRouter = router({
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.nationBet.upsert({
|
||||
await upsertWithoutSequence(ctx.db.nationBet, {
|
||||
where: {
|
||||
bettingId_userId_selectionKey: {
|
||||
bettingId: input.bettingId,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { getBillByLevel, LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
import { asRecord, readOfficeRequest, type RankDataType } from '@sammo-ts/common';
|
||||
import { asRecord, readOfficeRequest, toSafeInteger, withSafeIntegerId, type RankDataType } from '@sammo-ts/common';
|
||||
|
||||
import type { GameApiContext } from '../../context.js';
|
||||
import {
|
||||
@@ -588,10 +588,7 @@ export const getGeneralContext = async (ctx: GameApiContext) => {
|
||||
recentWar: general.recentWarTime?.toISOString() ?? null,
|
||||
defenceTrain: settings.defence_train,
|
||||
killTurn: readNumber(metaRecord.killturn ?? metaRecord.killTurn, 0),
|
||||
remainingMinutes: resolveRemainingMinutes(
|
||||
general.turnTime,
|
||||
gameTime.now
|
||||
),
|
||||
remainingMinutes: resolveRemainingMinutes(general.turnTime, gameTime.now),
|
||||
crewTypeId: general.crewTypeId,
|
||||
crewTypeName: crewTypeDetails.get(general.crewTypeId)?.name ?? '-',
|
||||
crewTypeInfo: crewTypeDetails.get(general.crewTypeId) ?? null,
|
||||
@@ -916,7 +913,7 @@ export const generalRouter = router({
|
||||
return {
|
||||
type: input.type,
|
||||
logs: logs.map((entry) => ({
|
||||
id: entry.id,
|
||||
id: toSafeInteger(entry.id),
|
||||
text: entry.text,
|
||||
})),
|
||||
};
|
||||
@@ -966,9 +963,9 @@ export const generalRouter = router({
|
||||
]);
|
||||
|
||||
return {
|
||||
global: trimRecentRecords(global, input.lastGeneralRecordId),
|
||||
general: trimRecentRecords(general, input.lastGeneralRecordId),
|
||||
history: trimRecentRecords(history, input.lastWorldHistoryId),
|
||||
global: trimRecentRecords(global.map(withSafeIntegerId), input.lastGeneralRecordId),
|
||||
general: trimRecentRecords(general.map(withSafeIntegerId), input.lastGeneralRecordId),
|
||||
history: trimRecentRecords(history.map(withSafeIntegerId), input.lastWorldHistoryId),
|
||||
};
|
||||
}),
|
||||
// 메인 화면은 SSE invalidation, 탭 복귀와 직접 갱신이 같은 read model을
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { withSafeIntegerId } from '@sammo-ts/common';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -38,7 +39,6 @@ const BUFF_KEYS: InheritBuffType[] = [
|
||||
|
||||
const UNIQUE_ITEM_SLOT_ORDER: readonly ItemSlot[] = ['horse', 'weapon', 'book', 'item'];
|
||||
|
||||
const POSTGRES_INTEGER_MAX = 2_147_483_647;
|
||||
const MIN_INHERIT_BUFF_LEVEL = 1;
|
||||
const MAX_INHERIT_BUFF_LEVEL = 5;
|
||||
|
||||
@@ -283,7 +283,7 @@ export const inheritRouter = router({
|
||||
getLogs: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
lastId: z.number().int().min(1).max(POSTGRES_INTEGER_MAX).optional(),
|
||||
lastId: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
@@ -300,7 +300,7 @@ export const inheritRouter = router({
|
||||
take: 30,
|
||||
select: { id: true, year: true, month: true, text: true, createdAt: true },
|
||||
});
|
||||
return logs;
|
||||
return logs.map(withSafeIntegerId);
|
||||
}),
|
||||
buyHiddenBuff: engineAuthedProcedure
|
||||
.input(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { toSafeInteger } from '@sammo-ts/common';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -77,7 +78,7 @@ export const getGeneralLog = accessLimitAuthedInputProcedure(
|
||||
type: input.type,
|
||||
generalId: target.id,
|
||||
logs: logs.map((entry) => ({
|
||||
id: entry.id,
|
||||
id: toSafeInteger(entry.id),
|
||||
text: entry.text,
|
||||
year: entry.year,
|
||||
month: entry.month,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { withSafeIntegerId } from '@sammo-ts/common';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
@@ -129,6 +130,6 @@ export const getNationInfo = authedProcedure.query(async ({ ctx }) => {
|
||||
name: city.name,
|
||||
capital: city.id === nation.capitalCityId,
|
||||
})),
|
||||
history,
|
||||
history: history.map(withSafeIntegerId),
|
||||
};
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { toSafeInteger, withSafeIntegerId } from '@sammo-ts/common';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld } from './shared.js';
|
||||
@@ -53,8 +54,8 @@ export const generalLogs = auditProcedure
|
||||
...world,
|
||||
type: input.type,
|
||||
coverage: world.serverId ? ('IDENTIFIED_LOGS_ONLY' as const) : ('IDENTITY_MISSING' as const),
|
||||
items: rows.slice(0, input.limit),
|
||||
nextCursor: rows.length > input.limit ? rows[input.limit - 1]!.id : null,
|
||||
items: rows.slice(0, input.limit).map(withSafeIntegerId),
|
||||
nextCursor: rows.length > input.limit ? toSafeInteger(rows[input.limit - 1]!.id) : null,
|
||||
};
|
||||
})
|
||||
);
|
||||
@@ -1,5 +1,5 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||
import { asNumber, asRecord, withSafeIntegerId } from '@sammo-ts/common';
|
||||
import { LEGACY_DEFAULT_MAX_LEVEL, LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -306,7 +306,7 @@ export const publicRouter = router({
|
||||
}
|
||||
const snapshot = {
|
||||
...map,
|
||||
history,
|
||||
history: history.map(withSafeIntegerId),
|
||||
};
|
||||
await ctx.redis.set(cacheKey, JSON.stringify(snapshot), { EX: PUBLIC_CACHE_TTL_SECONDS });
|
||||
return snapshot;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
|
||||
import { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit } from '@sammo-ts/common';
|
||||
@@ -94,7 +95,13 @@ export const enqueueDeferredGeneralAccess = async (
|
||||
}
|
||||
await redis.eval(ENQUEUE_SCRIPT, {
|
||||
keys: [activeKey(profileName)],
|
||||
arguments: [String(generalId), auth.user.id, String(weight), String(now.getTime()), String(ACTIVE_BATCH_TTL_MS)],
|
||||
arguments: [
|
||||
String(generalId),
|
||||
auth.user.id,
|
||||
String(weight),
|
||||
String(now.getTime()),
|
||||
String(ACTIVE_BATCH_TTL_MS),
|
||||
],
|
||||
});
|
||||
return true;
|
||||
};
|
||||
@@ -258,9 +265,10 @@ export const flushDeferredGeneralAccessBatch = async (
|
||||
),
|
||||
missing_periods AS (
|
||||
INSERT INTO "traffic_period" (
|
||||
"world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
|
||||
"id", "world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
|
||||
)
|
||||
SELECT
|
||||
${existingRowIdOrNext('traffic_period', GamePrisma.sql`stable_id.world_state_id = ${worldState.id} AND stable_id.year = (missing_key / 12)::INTEGER AND stable_id.month = (missing_key % 12 + 1)::INTEGER`)},
|
||||
${worldState.id},
|
||||
(missing_key / 12)::INTEGER,
|
||||
(missing_key % 12 + 1)::INTEGER,
|
||||
@@ -281,9 +289,10 @@ export const flushDeferredGeneralAccessBatch = async (
|
||||
),
|
||||
period_upsert AS (
|
||||
INSERT INTO "traffic_period" (
|
||||
"world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
|
||||
"id", "world_state_id", "year", "month", "started_at", "last_refresh", "refresh", "online"
|
||||
)
|
||||
SELECT
|
||||
${existingRowIdOrNext('traffic_period', GamePrisma.sql`stable_id.world_state_id = ${worldState.id} AND stable_id.year = ${worldState.currentYear} AND stable_id.month = ${worldState.currentMonth}`)},
|
||||
${worldState.id},
|
||||
${worldState.currentYear},
|
||||
${worldState.currentMonth},
|
||||
@@ -343,10 +352,11 @@ export const flushDeferredGeneralAccessBatch = async (
|
||||
),
|
||||
access_updates AS (
|
||||
INSERT INTO "general_access_log" (
|
||||
"general_id", "user_id", "last_refresh", "refresh", "refresh_total",
|
||||
"id", "general_id", "user_id", "last_refresh", "refresh", "refresh_total",
|
||||
"refresh_score", "refresh_score_total"
|
||||
)
|
||||
SELECT
|
||||
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = resolved."general_id"`)},
|
||||
resolved."general_id",
|
||||
resolved."user_id",
|
||||
resolved."last_refresh",
|
||||
@@ -471,11 +481,9 @@ export class DeferredGeneralAccessWorker {
|
||||
await this.redis.del(key);
|
||||
return;
|
||||
}
|
||||
await this.redis.set(
|
||||
key,
|
||||
JSON.stringify({ nextAccessAt: state.nextAccessAt.toISOString() }),
|
||||
{ PX: Math.max(1, state.nextAccessAt.getTime() - now.getTime()) }
|
||||
);
|
||||
await this.redis.set(key, JSON.stringify({ nextAccessAt: state.nextAccessAt.toISOString() }), {
|
||||
PX: Math.max(1, state.nextAccessAt.getTime() - now.getTime()),
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit, type AccessLimitLevel } from '@sammo-ts/common';
|
||||
import { acquireGameSchemaAdvisoryXactLock, GENERAL_ACCESS_PERSISTENCE_LOCK, GamePrisma } from '@sammo-ts/infra';
|
||||
|
||||
@@ -230,7 +231,7 @@ export const upsertGeneralAccess = async (
|
||||
await db.$transaction(async (transaction) => {
|
||||
await acquireGameSchemaAdvisoryXactLock(transaction, GENERAL_ACCESS_PERSISTENCE_LOCK);
|
||||
const periodKey = input.year * 12 + input.month - 1;
|
||||
const periodRows = await transaction.$queryRaw<Array<{ id: number }>>(
|
||||
const periodRows = await transaction.$queryRaw<Array<{ id: bigint }>>(
|
||||
GamePrisma.sql`
|
||||
WITH latest_period AS (
|
||||
SELECT MAX(year * 12 + month - 1)::INTEGER AS period_key
|
||||
@@ -269,6 +270,7 @@ export const upsertGeneralAccess = async (
|
||||
RETURNING id
|
||||
)
|
||||
INSERT INTO traffic_period (
|
||||
id,
|
||||
world_state_id,
|
||||
year,
|
||||
month,
|
||||
@@ -277,6 +279,7 @@ export const upsertGeneralAccess = async (
|
||||
refresh
|
||||
)
|
||||
VALUES (
|
||||
${existingRowIdOrNext('traffic_period', GamePrisma.sql`stable_id.world_state_id = ${input.worldStateId} AND stable_id.year = ${input.year} AND stable_id.month = ${input.month}`)},
|
||||
${input.worldStateId},
|
||||
${input.year},
|
||||
${input.month},
|
||||
@@ -341,6 +344,7 @@ export const upsertGeneralAccess = async (
|
||||
await transaction.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO general_access_log (
|
||||
id,
|
||||
general_id,
|
||||
user_id,
|
||||
last_refresh,
|
||||
@@ -350,6 +354,7 @@ export const upsertGeneralAccess = async (
|
||||
refresh_score_total
|
||||
)
|
||||
VALUES (
|
||||
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = ${input.generalId}`)},
|
||||
${input.generalId},
|
||||
${input.userId},
|
||||
${input.now},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
|
||||
import type { GameApiContext } from '../context.js';
|
||||
@@ -20,11 +21,13 @@ export const recordGeneralActivity = async (
|
||||
const written = await ctx.db.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO general_access_log (
|
||||
id,
|
||||
general_id,
|
||||
user_id,
|
||||
last_action_at
|
||||
)
|
||||
SELECT
|
||||
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = "general".id`)},
|
||||
id,
|
||||
${user.id},
|
||||
${now}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
import {
|
||||
@@ -132,7 +133,7 @@ export const setInheritancePoint = async (
|
||||
key: InheritPointKey,
|
||||
value: number
|
||||
): Promise<void> => {
|
||||
await db.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(db.inheritancePoint, {
|
||||
where: {
|
||||
userId_key: {
|
||||
userId,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
DeferredGeneralAccessWorker,
|
||||
flushDeferredGeneralAccessBatch,
|
||||
enqueueDeferredGeneralAccess,
|
||||
getDeferredGeneralAccessLimit,
|
||||
} from '../src/services/deferredGeneralAccess.js';
|
||||
@@ -91,7 +92,7 @@ liveIntegration('deferred general access with PostgreSQL and Redis', () => {
|
||||
await redis.disconnect();
|
||||
}
|
||||
if (db) {
|
||||
await db.generalAccessBatch.deleteMany({ where: { id: batchId } });
|
||||
await db.generalAccessBatch.deleteMany({ where: { id: { startsWith: batchId } } });
|
||||
await db.generalAccessLog.deleteMany({ where: { generalId } });
|
||||
await db.general.deleteMany({ where: { id: generalId } });
|
||||
await db.worldState.deleteMany({ where: { id: worldStateId } });
|
||||
@@ -153,9 +154,19 @@ liveIntegration('deferred general access with PostgreSQL and Redis', () => {
|
||||
nextAccessAt,
|
||||
});
|
||||
|
||||
const counters =
|
||||
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`;
|
||||
const accessId = (await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id;
|
||||
await flushDeferredGeneralAccessBatch(workerDb as never, `${batchId}-second`, [
|
||||
{ generalId, userId, weight: 1, lastRefresh: now },
|
||||
]);
|
||||
expect(
|
||||
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`
|
||||
).toEqual(counters);
|
||||
expect((await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id).toBe(accessId);
|
||||
await worker.flushOnce();
|
||||
await expect(db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).resolves.toMatchObject({
|
||||
refreshTotal: 2,
|
||||
refreshTotal: 3,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,7 @@ const deferredBatchId = `deferred-access-${endpointGeneralId}`;
|
||||
|
||||
const endpointAuth = (roles = ['user']): GameSessionTokenPayload => ({
|
||||
version: 1,
|
||||
profile: `${yearbookProfile}:default`,
|
||||
profile: yearbookProfile,
|
||||
issuedAt: '2026-07-26T00:00:00.000Z',
|
||||
expiresAt: '2026-07-27T00:00:00.000Z',
|
||||
sessionId: `access-session-${endpointGeneralId}`,
|
||||
@@ -167,6 +167,9 @@ integration('general access tracking persistence', () => {
|
||||
scoreStartedAt: new Date('2026-07-26T03:00:00.000Z'),
|
||||
};
|
||||
await upsertGeneralAccess(db, { ...firstWindow, weight: 2 });
|
||||
const counters =
|
||||
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`;
|
||||
const accessId = (await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id;
|
||||
await Promise.all(
|
||||
Array.from({ length: 20 }, (_, index) =>
|
||||
upsertGeneralAccess(db, {
|
||||
@@ -177,6 +180,10 @@ integration('general access tracking persistence', () => {
|
||||
)
|
||||
);
|
||||
|
||||
expect(
|
||||
await db.$queryRaw`SELECT 'access' AS kind,last_value FROM general_access_log_id_seq UNION ALL SELECT 'period',last_value FROM traffic_period_id_seq`
|
||||
).toEqual(counters);
|
||||
expect((await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).id).toBe(accessId);
|
||||
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).toMatchObject({
|
||||
userId: 'access-user-a',
|
||||
refresh: 22,
|
||||
|
||||
@@ -108,7 +108,7 @@ const buildContext = (options: {
|
||||
inheritancePoint?: number;
|
||||
inheritanceRows?: Array<{ key: string; value: number }>;
|
||||
rankRows?: Array<{ type: string; value: number }>;
|
||||
inheritanceLogs?: Array<{ id: number; year: number; month: number; text: string; createdAt: Date }>;
|
||||
inheritanceLogs?: Array<{ id: number | bigint; year: number; month: number; text: string; createdAt: Date }>;
|
||||
configConst?: Record<string, unknown>;
|
||||
scenarioCode?: string;
|
||||
configMap?: Record<string, unknown>;
|
||||
@@ -460,11 +460,11 @@ describe('inherit router actor and permission boundaries', () => {
|
||||
it('loads the first inheritance-log page without an out-of-range integer cursor', async () => {
|
||||
const createdAt = new Date('2026-07-26T00:00:00Z');
|
||||
const fixture = buildContext({
|
||||
inheritanceLogs: [{ id: 2_147_483_647, year: 200, month: 4, text: '경계 로그', createdAt }],
|
||||
inheritanceLogs: [{ id: 2_147_483_648n, year: 200, month: 4, text: '경계 로그', createdAt }],
|
||||
});
|
||||
|
||||
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({})).resolves.toEqual([
|
||||
{ id: 2_147_483_647, year: 200, month: 4, text: '경계 로그', createdAt },
|
||||
{ id: 2_147_483_648, year: 200, month: 4, text: '경계 로그', createdAt },
|
||||
]);
|
||||
expect(fixture.inheritanceLogFindMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-1' },
|
||||
@@ -478,23 +478,26 @@ describe('inherit router actor and permission boundaries', () => {
|
||||
const fixture = buildContext({ inheritanceLogs: [] });
|
||||
const caller = appRouter.createCaller(fixture.context);
|
||||
|
||||
await expect(caller.inherit.getLogs({ lastId: 2_147_483_647 })).resolves.toEqual([]);
|
||||
await expect(caller.inherit.getLogs({ lastId: 2_147_483_648 })).resolves.toEqual([]);
|
||||
expect(fixture.inheritanceLogFindMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-1', id: { lt: 2_147_483_647 } },
|
||||
where: { userId: 'user-1', id: { lt: 2_147_483_648 } },
|
||||
orderBy: { id: 'desc' },
|
||||
take: 30,
|
||||
select: { id: true, year: true, month: true, text: true, createdAt: true },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([0, -1, 1.5, 2_147_483_648])('rejects an invalid inheritance-log cursor: %s', async (lastId) => {
|
||||
it.each([0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])(
|
||||
'rejects an invalid inheritance-log cursor: %s',
|
||||
async (lastId) => {
|
||||
const fixture = buildContext({});
|
||||
|
||||
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({ lastId })).rejects.toMatchObject({
|
||||
code: 'BAD_REQUEST',
|
||||
});
|
||||
expect(fixture.inheritanceLogFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
it('delegates the authenticated actor and maps a missing-general daemon rejection', async () => {
|
||||
const fixture = buildContext({
|
||||
|
||||
@@ -33,7 +33,7 @@ type LogQuery = {
|
||||
select: { id: true; text: true; createdAt: true };
|
||||
};
|
||||
|
||||
const buildContext = (findMany: (query: LogQuery) => Promise<Array<{ id: number; text: string }>>) =>
|
||||
const buildContext = (findMany: (query: LogQuery) => Promise<Array<{ id: number | bigint; text: string }>>) =>
|
||||
({
|
||||
auth,
|
||||
profile: { id: 'che', name: 'che:default', scenario: 'default' },
|
||||
@@ -94,6 +94,22 @@ describe('general.getRecentRecords', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns exact numeric JSON cursors above int4 and trims a bigint cursor row', async () => {
|
||||
const findMany = vi.fn(async () => [
|
||||
{ id: 2_147_483_650n, text: '최신' },
|
||||
{ id: 2_147_483_648n, text: '이전 cursor' },
|
||||
]);
|
||||
const caller = appRouter.createCaller(buildContext(findMany));
|
||||
const result = await caller.general.getRecentRecords({
|
||||
lastGeneralRecordId: 2_147_483_648,
|
||||
lastWorldHistoryId: 2_147_483_648,
|
||||
});
|
||||
expect(result.global).toEqual([{ id: 2_147_483_650, text: '최신' }]);
|
||||
expect(result.general).toEqual(result.global);
|
||||
expect(result.history).toEqual(result.global);
|
||||
expect(() => JSON.stringify(result)).not.toThrow();
|
||||
});
|
||||
|
||||
it('caps an initial bucket at the legacy 15-row limit', async () => {
|
||||
const rows = Array.from({ length: 16 }, (_, index) => ({
|
||||
id: 100 - index,
|
||||
|
||||
@@ -38,8 +38,8 @@ const buildContext = () => {
|
||||
},
|
||||
logEntry: {
|
||||
findMany: vi.fn(async () => [
|
||||
{ id: 9, text: '<Y>최근 정세</>' },
|
||||
{ id: 8, text: '이전 정세' },
|
||||
{ id: 9n, text: '<Y>최근 정세</>' },
|
||||
{ id: 8n, text: '이전 정세' },
|
||||
]),
|
||||
},
|
||||
$queryRaw: vi
|
||||
|
||||
@@ -69,8 +69,7 @@ const buildDb = (autorunLimit: number | null = null) => {
|
||||
},
|
||||
createMany: async ({ data }: GeneralTurnCreateManyArgs) => {
|
||||
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
|
||||
const rows: GeneralTurnRow[] = dataList.map((row, index: number) => ({
|
||||
id: index + 1,
|
||||
const rows: GeneralTurnRow[] = dataList.map((row) => ({
|
||||
generalId: row.generalId as number,
|
||||
turnIdx: row.turnIdx as number,
|
||||
actionCode: row.actionCode as string,
|
||||
@@ -136,8 +135,7 @@ const buildDb = (autorunLimit: number | null = null) => {
|
||||
},
|
||||
createMany: async ({ data }: NationTurnCreateManyArgs) => {
|
||||
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
|
||||
const rows: NationTurnRow[] = dataList.map((row, index: number) => ({
|
||||
id: index + 1,
|
||||
const rows: NationTurnRow[] = dataList.map((row) => ({
|
||||
nationId: row.nationId as number,
|
||||
officerLevel: row.officerLevel as number,
|
||||
turnIdx: row.turnIdx as number,
|
||||
@@ -203,9 +201,10 @@ const buildDb = (autorunLimit: number | null = null) => {
|
||||
|
||||
describe('reservedTurns', () => {
|
||||
it('loads multiple nation officer queues with two batched queries and preserves defaults', async () => {
|
||||
const findTurns = vi.fn(async () => [
|
||||
const findTurns = vi.fn(
|
||||
async () =>
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
nationId: 4,
|
||||
officerLevel: 12,
|
||||
turnIdx: 1,
|
||||
@@ -214,7 +213,6 @@ describe('reservedTurns', () => {
|
||||
createdAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
nationId: 4,
|
||||
officerLevel: 10,
|
||||
turnIdx: 0,
|
||||
@@ -222,7 +220,8 @@ describe('reservedTurns', () => {
|
||||
arg: {},
|
||||
createdAt: new Date(),
|
||||
},
|
||||
] satisfies NationTurnRow[]);
|
||||
] satisfies NationTurnRow[]
|
||||
);
|
||||
const findRevisions = vi.fn(async () => [
|
||||
{ nationId: 4, officerLevel: 12, revision: 7, updatedAt: new Date() },
|
||||
]);
|
||||
@@ -411,7 +410,6 @@ describe('reservedTurns', () => {
|
||||
nationRevisions.set('6:12', 2);
|
||||
nationTurns.set('6:12', [
|
||||
{
|
||||
id: 1,
|
||||
nationId: 6,
|
||||
officerLevel: 12,
|
||||
turnIdx: 0,
|
||||
@@ -420,7 +418,6 @@ describe('reservedTurns', () => {
|
||||
createdAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
nationId: 6,
|
||||
officerLevel: 12,
|
||||
turnIdx: 1,
|
||||
|
||||
@@ -901,7 +901,6 @@ describe('appRouter', () => {
|
||||
const general = buildGeneralRow({ id: 11, meta: { autorun_limit: 2408 } });
|
||||
const generalTurns: GeneralTurnRow[] = [
|
||||
{
|
||||
id: 1,
|
||||
generalId: 11,
|
||||
turnIdx: 0,
|
||||
actionCode: 'che_화계',
|
||||
@@ -922,7 +921,6 @@ describe('appRouter', () => {
|
||||
const general = buildGeneralRow({ id: 12, nationId: 3, officerLevel: 5 });
|
||||
const nationTurns: NationTurnRow[] = [
|
||||
{
|
||||
id: 1,
|
||||
nationId: 3,
|
||||
officerLevel: 5,
|
||||
turnIdx: 0,
|
||||
@@ -1008,7 +1006,6 @@ describe('appRouter', () => {
|
||||
general,
|
||||
generalTurns: [
|
||||
{
|
||||
id: 1,
|
||||
generalId: general.id,
|
||||
turnIdx: 0,
|
||||
actionCode: 'che_훈련',
|
||||
@@ -1016,7 +1013,6 @@ describe('appRouter', () => {
|
||||
createdAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
generalId: general.id,
|
||||
turnIdx: 1,
|
||||
actionCode: 'che_사기진작',
|
||||
|
||||
@@ -969,7 +969,7 @@ integration('game API security over HTTP transport', () => {
|
||||
const telemetryAfter = await readAccessTelemetryState();
|
||||
expect(telemetryAfter.periods).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
id: expect.any(BigInt),
|
||||
worldStateId: fixtureWorldId,
|
||||
year: 190,
|
||||
month: 1,
|
||||
@@ -992,7 +992,7 @@ integration('game API security over HTTP transport', () => {
|
||||
]);
|
||||
expect(telemetryAfter.accessLogs).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
id: expect.any(BigInt),
|
||||
generalId,
|
||||
userId,
|
||||
lastRefresh: trafficPeriod.lastRefresh,
|
||||
@@ -1548,8 +1548,8 @@ integration('game API security over HTTP transport', () => {
|
||||
arg,
|
||||
}))
|
||||
).toEqual(databaseAfter.generalTurns);
|
||||
expect(new Set(committedGeneralTurns.map(({ id }) => id)).size).toBe(30);
|
||||
expect(committedGeneralTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
|
||||
expect(new Set(committedGeneralTurns.map(({ generalId, turnIdx }) => `${generalId}:${turnIdx}`)).size).toBe(30);
|
||||
expect(committedGeneralTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
|
||||
expect(allowedTablesAfter.generalTurnRevisions.filter((row) => row.generalId !== generalId)).toEqual(
|
||||
allowedTablesBefore.generalTurnRevisions.filter((row) => row.generalId !== generalId)
|
||||
);
|
||||
@@ -1567,7 +1567,7 @@ integration('game API security over HTTP transport', () => {
|
||||
);
|
||||
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
id: expect.any(BigInt),
|
||||
generalId,
|
||||
userId,
|
||||
lastRefresh: null,
|
||||
@@ -1733,8 +1733,14 @@ integration('game API security over HTTP transport', () => {
|
||||
arg,
|
||||
}))
|
||||
).toEqual(expectedTurns);
|
||||
expect(new Set(committedNationTurns.map(({ id }) => id)).size).toBe(12);
|
||||
expect(committedNationTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
|
||||
expect(
|
||||
new Set(
|
||||
committedNationTurns.map(
|
||||
({ nationId, officerLevel, turnIdx }) => `${nationId}:${officerLevel}:${turnIdx}`
|
||||
)
|
||||
).size
|
||||
).toBe(12);
|
||||
expect(committedNationTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
|
||||
expect(
|
||||
allowedTablesAfter.nationTurnRevisions.filter(
|
||||
(row) => row.nationId !== ownerNationId || row.officerLevel !== 5
|
||||
@@ -1763,7 +1769,7 @@ integration('game API security over HTTP transport', () => {
|
||||
);
|
||||
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === sameNationGeneralId)).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
id: expect.any(BigInt),
|
||||
generalId: sameNationGeneralId,
|
||||
userId: sameNationUserId,
|
||||
lastRefresh: null,
|
||||
@@ -1880,8 +1886,14 @@ integration('game API security over HTTP transport', () => {
|
||||
arg,
|
||||
}))
|
||||
).toEqual(committed.nationTurns);
|
||||
expect(new Set(committedNationTurns.map(({ id }) => id)).size).toBe(12);
|
||||
expect(committedNationTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
|
||||
expect(
|
||||
new Set(
|
||||
committedNationTurns.map(
|
||||
({ nationId, officerLevel, turnIdx }) => `${nationId}:${officerLevel}:${turnIdx}`
|
||||
)
|
||||
).size
|
||||
).toBe(12);
|
||||
expect(committedNationTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
|
||||
expect(
|
||||
allowedTablesAfter.nationTurnRevisions.filter(
|
||||
(row) => row.nationId !== ownerNationId || row.officerLevel !== 12
|
||||
@@ -1910,7 +1922,7 @@ integration('game API security over HTTP transport', () => {
|
||||
);
|
||||
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
id: expect.any(BigInt),
|
||||
generalId,
|
||||
userId,
|
||||
lastRefresh: null,
|
||||
@@ -2868,7 +2880,7 @@ integration('game API security over HTTP transport', () => {
|
||||
result: {
|
||||
data: {
|
||||
coverage: 'IDENTIFIED_LOGS_ONLY',
|
||||
items: [{ id: ownLogs[index]!.id }],
|
||||
items: [{ id: Number(ownLogs[index]!.id) }],
|
||||
nextCursor: null,
|
||||
},
|
||||
},
|
||||
@@ -2877,17 +2889,19 @@ integration('game API security over HTTP transport', () => {
|
||||
}
|
||||
expect(
|
||||
(await get('generalLogs', admin, { generalId: logGeneralId, type: 'generalHistory', limit: 1 })).body
|
||||
).toMatchObject({ result: { data: { items: [{ id: latest.id }], nextCursor: latest.id } } });
|
||||
).toMatchObject({
|
||||
result: { data: { items: [{ id: Number(latest.id) }], nextCursor: Number(latest.id) } },
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await get('generalLogs', admin, {
|
||||
generalId: logGeneralId,
|
||||
type: 'generalHistory',
|
||||
limit: 1,
|
||||
cursor: latest.id,
|
||||
cursor: Number(latest.id),
|
||||
})
|
||||
).body
|
||||
).toMatchObject({ result: { data: { items: [{ id: ownLogs[0]!.id }], nextCursor: null } } });
|
||||
).toMatchObject({ result: { data: { items: [{ id: Number(ownLogs[0]!.id) }], nextCursor: null } } });
|
||||
for (const invalid of [
|
||||
{ limit: 201 },
|
||||
{ cursor: 0 },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
@@ -580,8 +581,8 @@ export const createAuctionBidder = async (options: {
|
||||
}
|
||||
await tx.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO rank_data (nation_id, general_id, type, value)
|
||||
SELECT nation_id, id, 'inherit_spent_dyn', ${morePoint}
|
||||
INSERT INTO rank_data (id, nation_id, general_id, type, value)
|
||||
SELECT ${existingRowIdOrNext('rank_data', GamePrisma.sql`stable_id.general_id = "general".id AND stable_id.type = 'inherit_spent_dyn'`)}, nation_id, id, 'inherit_spent_dyn', ${morePoint}
|
||||
FROM general
|
||||
WHERE id = ${command.generalId}
|
||||
ON CONFLICT (general_id, type)
|
||||
@@ -598,8 +599,9 @@ export const createAuctionBidder = async (options: {
|
||||
}
|
||||
await tx.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO inheritance_point (user_id, key, value, updated_at)
|
||||
INSERT INTO inheritance_point (id, user_id, key, value, updated_at)
|
||||
VALUES (
|
||||
${existingRowIdOrNext('inheritance_point', GamePrisma.sql`stable_id.user_id = ${prevUserId} AND stable_id.key = 'previous'`)},
|
||||
${prevUserId},
|
||||
'previous',
|
||||
${highestBid.amount},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||
import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra';
|
||||
import { ActionLogger, ItemLoader, LogFormat, isItemKey, type MessageDraft } from '@sammo-ts/logic';
|
||||
@@ -212,8 +213,8 @@ const refundInheritancePoint = async (options: {
|
||||
}
|
||||
await prisma.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO inheritance_point (user_id, key, value, updated_at)
|
||||
VALUES (${userId}, 'previous', ${amount}, ${new Date()})
|
||||
INSERT INTO inheritance_point (id, user_id, key, value, updated_at)
|
||||
VALUES (${existingRowIdOrNext('inheritance_point', GamePrisma.sql`stable_id.user_id = ${userId} AND stable_id.key = 'previous'`)}, ${userId}, 'previous', ${amount}, ${new Date()})
|
||||
ON CONFLICT (user_id, key)
|
||||
DO UPDATE SET
|
||||
value = inheritance_point.value + EXCLUDED.value,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { asRecord, JosaUtil } from '@sammo-ts/common';
|
||||
@@ -289,8 +290,8 @@ const openUniqueAuction = async (
|
||||
});
|
||||
await db.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO rank_data (nation_id, general_id, type, value)
|
||||
VALUES (${general.nationId}, ${general.id}, 'inherit_spent_dyn', ${command.amount})
|
||||
INSERT INTO rank_data (id, nation_id, general_id, type, value)
|
||||
VALUES (${existingRowIdOrNext('rank_data', GamePrisma.sql`stable_id.general_id = ${general.id} AND stable_id.type = 'inherit_spent_dyn'`)}, ${general.nationId}, ${general.id}, 'inherit_spent_dyn', ${command.amount})
|
||||
ON CONFLICT (general_id, type)
|
||||
DO UPDATE SET
|
||||
nation_id = EXCLUDED.nation_id,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, type GamePrisma, type InputJsonValue } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
@@ -424,7 +425,7 @@ const cancelGameInTransaction = async (
|
||||
earnedPointRetentionPercent: request.earnedPointRetentionPercent,
|
||||
});
|
||||
const currentPoint = pointsByUser.get(userId)?.get('previous') ?? 0;
|
||||
await prisma.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
update: { value: calculated.finalPoint },
|
||||
create: { userId, key: 'previous', value: calculated.finalPoint },
|
||||
@@ -470,7 +471,7 @@ const cancelGameInTransaction = async (
|
||||
}
|
||||
for (const general of activeGenerals) {
|
||||
if (!general.userId || general.npcState >= 2) continue;
|
||||
await prisma.oldGeneral.upsert({
|
||||
await upsertWithoutSequence(prisma.oldGeneral, {
|
||||
where: { by_no: { serverId, generalNo: general.id } },
|
||||
update: {
|
||||
owner: general.userId,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { prunePreviousAuditBatch } from '../playAudit/retention.js';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
@@ -497,7 +498,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
);
|
||||
}
|
||||
}
|
||||
await prisma.gameHistory.upsert({
|
||||
await upsertWithoutSequence(prisma.gameHistory, {
|
||||
where: { serverId: worldMeta.serverId },
|
||||
create: {
|
||||
serverId: worldMeta.serverId,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { areSeasonRecordsFinalized } from '../turn/seasonRecords.js';
|
||||
import { JosaUtil, asRecord } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, type GamePrisma } from '@sammo-ts/infra';
|
||||
@@ -256,7 +257,7 @@ export const createTournamentRewardFinalizer = async (options: {
|
||||
|
||||
const recordsFinalized = await areSeasonRecordsFinalized(db, world.getState().meta.serverId);
|
||||
for (const entry of recordsFinalized ? [] : pointUpdates) {
|
||||
await db.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(db.inheritancePoint, {
|
||||
where: {
|
||||
userId_key: { userId: entry.userId!, key: 'tournament' },
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { persistAuditDecisions } from '../playAudit/decisionPersistence.js';
|
||||
import { collectPlayAudit, markAuditGap } from '../playAudit/bestEffort.js';
|
||||
import { persistAuditDiplomacyEvents, withPlayAuditSavepoint } from '@sammo-ts/infra';
|
||||
@@ -119,7 +120,7 @@ export interface RealtimeReadModelBaseline {
|
||||
}
|
||||
|
||||
export type PersistedVisibleLogRow = {
|
||||
id: number;
|
||||
id: number | bigint;
|
||||
scope: LogScope;
|
||||
category: LogCategory;
|
||||
generalId: number | null;
|
||||
@@ -697,12 +698,12 @@ const persistNationBettingFinish = async (
|
||||
});
|
||||
const previousPoint = existing?.value ?? 0;
|
||||
const nextPoint = previousPoint + reward.amount;
|
||||
await prisma.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||
where: { userId_key: { userId: reward.userId, key: 'previous' } },
|
||||
update: { value: nextPoint },
|
||||
create: { userId: reward.userId, key: 'previous', value: nextPoint },
|
||||
});
|
||||
await prisma.rankData.upsert({
|
||||
await upsertWithoutSequence(prisma.rankData, {
|
||||
where: {
|
||||
generalId_type: {
|
||||
generalId: reward.generalId,
|
||||
@@ -831,17 +832,28 @@ const buildPersistedGeneralMeta = (
|
||||
|
||||
const RANK_DATA_UPSERT_BATCH_SIZE = 1_000;
|
||||
|
||||
const upsertRankRows = async (
|
||||
export const upsertRankRows = async (
|
||||
prisma: GamePrisma.TransactionClient,
|
||||
rows: Array<{ generalId: number; nationId: number; type: string; value: number }>
|
||||
): Promise<void> => {
|
||||
for (let offset = 0; offset < rows.length; offset += RANK_DATA_UPSERT_BATCH_SIZE) {
|
||||
const batch = rows.slice(offset, offset + RANK_DATA_UPSERT_BATCH_SIZE);
|
||||
// Ref와 같은 (장수, 항목) 값을 저장한다. 이미 있는 행의 ID를 재사용해
|
||||
// 매 턴 44종 갱신마다 nextval을 소비하지 않고, 신규 행만 시퀀스를 사용한다.
|
||||
// 동시 신규 insert 경합은 기존 ON CONFLICT 계약으로 처리한다.
|
||||
await prisma.$executeRaw(GamePrisma.sql`
|
||||
INSERT INTO "rank_data" ("general_id", "nation_id", "type", "value")
|
||||
VALUES ${GamePrisma.join(
|
||||
batch.map((row) => GamePrisma.sql`(${row.generalId}, ${row.nationId}, ${row.type}, ${row.value})`)
|
||||
)}
|
||||
INSERT INTO "rank_data" ("id", "general_id", "nation_id", "type", "value")
|
||||
SELECT
|
||||
COALESCE(existing."id", nextval(pg_get_serial_sequence('rank_data', 'id'))),
|
||||
incoming."general_id", incoming."nation_id", incoming."type", incoming."value"
|
||||
FROM (VALUES ${GamePrisma.join(
|
||||
batch.map(
|
||||
(row) =>
|
||||
GamePrisma.sql`(${row.generalId}::integer, ${row.nationId}::integer, ${row.type}::text, ${row.value}::integer)`
|
||||
)
|
||||
)}) AS incoming("general_id", "nation_id", "type", "value")
|
||||
LEFT JOIN "rank_data" AS existing
|
||||
ON existing."general_id" = incoming."general_id" AND existing."type" = incoming."type"
|
||||
ON CONFLICT ("general_id", "type") DO UPDATE
|
||||
SET
|
||||
"nation_id" = EXCLUDED."nation_id",
|
||||
@@ -1129,7 +1141,7 @@ export const createDatabaseTurnHooks = async (
|
||||
const persistChanges = async (
|
||||
transaction?: GamePrisma.TransactionClient,
|
||||
commandCompletion?: { requestId: string; result: TurnDaemonCommandResult },
|
||||
directLogFloor?: number
|
||||
directLogFloor?: number | bigint
|
||||
): Promise<{
|
||||
acknowledge: () => void;
|
||||
readModelChanges: RealtimeReadModelChanges;
|
||||
@@ -1563,7 +1575,7 @@ export const createDatabaseTurnHooks = async (
|
||||
}
|
||||
}
|
||||
for (const entry of grouped.values()) {
|
||||
await prisma.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||
where: { userId_key: { userId: entry.userId, key: entry.key } },
|
||||
update: { value: { increment: entry.amount } },
|
||||
create: { userId: entry.userId, key: entry.key, value: entry.amount },
|
||||
@@ -1631,7 +1643,7 @@ export const createDatabaseTurnHooks = async (
|
||||
}
|
||||
await Promise.all(
|
||||
deletedNationSnapshots.map((snapshot) =>
|
||||
prisma.oldNation.upsert({
|
||||
upsertWithoutSequence(prisma.oldNation, {
|
||||
where: {
|
||||
serverId_nation_sourceId: {
|
||||
serverId,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { GamePrisma, type TurnEngineGeneralUpdateInput } from '@sammo-ts/infra';
|
||||
|
||||
// Fixed schema identifiers only; all row values remain bound parameters.
|
||||
@@ -91,8 +92,8 @@ export const persistGeneralAccessScores = async (
|
||||
for (let offset = 0; offset < updates.length; offset += GENERAL_UPDATE_BATCH_SIZE) {
|
||||
const batch = updates.slice(offset, offset + GENERAL_UPDATE_BATCH_SIZE);
|
||||
await database.$executeRaw(GamePrisma.sql`
|
||||
INSERT INTO "general_access_log" ("general_id", "user_id", "refresh_score_total")
|
||||
VALUES ${GamePrisma.join(batch.map((row) => GamePrisma.sql`(${row.generalId}, ${row.userId}, ${row.refreshScoreTotal})`))}
|
||||
INSERT INTO "general_access_log" ("id", "general_id", "user_id", "refresh_score_total")
|
||||
VALUES ${GamePrisma.join(batch.map((row) => GamePrisma.sql`(${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = ${row.generalId}`)}, ${row.generalId}, ${row.userId}, ${row.refreshScoreTotal})`))}
|
||||
ON CONFLICT ("general_id") DO UPDATE
|
||||
SET "refresh_score_total" = EXCLUDED."refresh_score_total"
|
||||
`);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||
import {
|
||||
asRecord,
|
||||
@@ -77,7 +78,7 @@ const persistPostRetirementRankValues = async (
|
||||
return;
|
||||
}
|
||||
for (const row of buildPersistedRankRows(event.after)) {
|
||||
await prisma.rankData.upsert({
|
||||
await upsertWithoutSequence(prisma.rankData, {
|
||||
where: { generalId_type: { generalId: row.generalId, type: row.type } },
|
||||
update: { nationId: row.nationId, value: row.value },
|
||||
create: row,
|
||||
@@ -142,7 +143,7 @@ const settleInheritance = async (
|
||||
);
|
||||
const total = Math.trunc(previous + refund + settlement.totalEarned);
|
||||
|
||||
await prisma.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
update: { value: total },
|
||||
create: { userId, key: 'previous', value: total },
|
||||
@@ -152,7 +153,7 @@ const settleInheritance = async (
|
||||
([key, value]) => key === 'max_belong' || points.has(key) || value !== 0
|
||||
);
|
||||
for (const [key, value] of retainedEntries) {
|
||||
await prisma.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||
where: { userId_key: { userId, key } },
|
||||
update: { value },
|
||||
create: { userId, key, value },
|
||||
@@ -367,7 +368,7 @@ const archiveGeneral = async (
|
||||
records: { battleResult: battleResults },
|
||||
availability: { battleResultLogs: true },
|
||||
};
|
||||
await prisma.oldGeneral.upsert({
|
||||
await upsertWithoutSequence(prisma.oldGeneral, {
|
||||
where: { by_no: { serverId, generalNo: event.generalId } },
|
||||
update: {
|
||||
owner: event.before.userId ?? null,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||
import { asNumber, asRecord, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||
import { acquireGameSchemaAdvisoryXactLock, GamePrisma } from '@sammo-ts/infra';
|
||||
@@ -246,7 +247,7 @@ const applyInheritanceUser = async (
|
||||
};
|
||||
|
||||
const setInheritancePoint = async (db: DatabaseClient, userId: string, value: number): Promise<void> => {
|
||||
await db.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(db.inheritancePoint, {
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
update: { value },
|
||||
create: { userId, key: 'previous', value },
|
||||
@@ -860,7 +861,7 @@ export const createGeneralFromJoin = async (options: {
|
||||
await db.generalTurnRevision.create({
|
||||
data: { generalId, revision: 0 },
|
||||
});
|
||||
await db.generalAccessLog.upsert({
|
||||
await upsertWithoutSequence(db.generalAccessLog, {
|
||||
where: { generalId },
|
||||
update: { userId: input.userId, lastRefresh: operationalAcceptedAt },
|
||||
create: {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { randomInt } from 'node:crypto';
|
||||
|
||||
import { asNumber, asRecord, GAME_TICKS_PER_TURN, JosaUtil, LiteHashDRBG, RandUtil, type RNG } from '@sammo-ts/common';
|
||||
@@ -337,18 +338,12 @@ export const reserveNpcPossessionCandidates = async (options: {
|
||||
}
|
||||
return toReservation(inFlightToken, options.createdGameTick, ticksPerSecond);
|
||||
}
|
||||
if (
|
||||
existing &&
|
||||
(existing.validUntilTick === null || Number(existing.validUntilTick) < options.createdGameTick)
|
||||
) {
|
||||
if (existing && (existing.validUntilTick === null || Number(existing.validUntilTick) < options.createdGameTick)) {
|
||||
await db.npcSelectionToken.deleteMany({
|
||||
where: {
|
||||
ownerUserId: userId,
|
||||
nonce: existing.nonce,
|
||||
OR: [
|
||||
{ validUntilTick: null },
|
||||
{ validUntilTick: { lt: BigInt(options.createdGameTick) } },
|
||||
],
|
||||
OR: [{ validUntilTick: null }, { validUntilTick: { lt: BigInt(options.createdGameTick) } }],
|
||||
},
|
||||
});
|
||||
existing = null;
|
||||
@@ -425,9 +420,7 @@ export const reserveNpcPossessionCandidates = async (options: {
|
||||
const validUntilTick = options.createdGameTick + Math.round(validSeconds * ticksPerSecond);
|
||||
const pickMoreFromTick = options.createdGameTick + Math.round(pickMoreSeconds * ticksPerSecond);
|
||||
const validUntil = new Date(now.getTime() + validSeconds * 1000);
|
||||
const refreshedPickMoreFrom = new Date(
|
||||
now.getTime() + pickMoreSeconds * 1000
|
||||
);
|
||||
const refreshedPickMoreFrom = new Date(now.getTime() + pickMoreSeconds * 1000);
|
||||
const nonce = randomInt(0, 0x10000000);
|
||||
|
||||
if (existing) {
|
||||
@@ -566,7 +559,7 @@ export const possessNpcGeneral = async (options: {
|
||||
},
|
||||
});
|
||||
|
||||
await db.generalAccessLog.upsert({
|
||||
await upsertWithoutSequence(db.generalAccessLog, {
|
||||
where: { generalId },
|
||||
update: {
|
||||
userId,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { asNumber, asRecord, GAME_TICKS_PER_TURN, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||
@@ -567,11 +568,7 @@ const assertGeneralIdSnapshotMatches = async (db: DatabaseClient, world: InMemor
|
||||
}
|
||||
};
|
||||
|
||||
const clearUnusedReservations = async (
|
||||
db: DatabaseClient,
|
||||
userId: string,
|
||||
nowTick: number
|
||||
): Promise<void> => {
|
||||
const clearUnusedReservations = async (db: DatabaseClient, userId: string, nowTick: number): Promise<void> => {
|
||||
await db.selectPoolEntry.updateMany({
|
||||
where: {
|
||||
generalId: null,
|
||||
@@ -914,7 +911,7 @@ export const createGeneralFromSelectionPool = async (options: {
|
||||
if (occupied.count === 0) {
|
||||
throw new Error('장수 등록 중 선택 후보 점유에 실패했습니다.');
|
||||
}
|
||||
await db.generalAccessLog.upsert({
|
||||
await upsertWithoutSequence(db.generalAccessLog, {
|
||||
where: { generalId },
|
||||
update: { userId, lastRefresh: options.operationalAcceptedAt },
|
||||
create: { generalId, userId, lastRefresh: options.operationalAcceptedAt },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||
import { asRecord, HALL_OF_FAME_TYPES, resolveLegacyTextColor, type HallOfFameType } from '@sammo-ts/common';
|
||||
@@ -209,12 +210,12 @@ const cancelPendingUniqueAuctions = async (
|
||||
if (!bidder?.userId || bidder.userId !== dbBidder?.userId) {
|
||||
throw new Error(`Unification auction refund owner is unavailable: ${planned.auctionId}.`);
|
||||
}
|
||||
await transaction.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(transaction.inheritancePoint, {
|
||||
where: { userId_key: { userId: bidder.userId, key: 'previous' } },
|
||||
update: { value: { increment: highest.amount } },
|
||||
create: { userId: bidder.userId, key: 'previous', value: highest.amount },
|
||||
});
|
||||
await transaction.rankData.upsert({
|
||||
await upsertWithoutSequence(transaction.rankData, {
|
||||
where: {
|
||||
generalId_type: { generalId: bidder.id, type: 'inherit_spent_dyn' },
|
||||
},
|
||||
@@ -345,7 +346,7 @@ export const persistUnificationFinalization = async (
|
||||
) as Record<(typeof ALL_MERGED_INHERITANCE_KEYS)[number], number>;
|
||||
const total = Math.floor(previous + Object.values(mergedPoints).reduce((sum, value) => sum + value, 0));
|
||||
|
||||
await transaction.inheritancePoint.upsert({
|
||||
await upsertWithoutSequence(transaction.inheritancePoint, {
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
update: { value: total },
|
||||
create: { userId, key: 'previous', value: total },
|
||||
@@ -508,7 +509,7 @@ export const persistUnificationFinalization = async (
|
||||
}),
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
await transaction.oldNation.upsert({
|
||||
await upsertWithoutSequence(transaction.oldNation, {
|
||||
where: { serverId_nation_sourceId: { serverId, nation: input.winnerNationId, sourceId: 0 } },
|
||||
update: { data: asJson(winnerData), date: input.completedAt },
|
||||
create: {
|
||||
@@ -525,7 +526,7 @@ export const persistUnificationFinalization = async (
|
||||
generals: neutralGenerals.map((general) => general.id),
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
await transaction.oldNation.upsert({
|
||||
await upsertWithoutSequence(transaction.oldNation, {
|
||||
where: { serverId_nation_sourceId: { serverId, nation: 0, sourceId: 0 } },
|
||||
update: { data: neutralData, date: input.completedAt },
|
||||
create: { serverId, nation: 0, sourceId: 0, data: neutralData, date: input.completedAt },
|
||||
@@ -572,7 +573,7 @@ export const persistUnificationFinalization = async (
|
||||
availability: { battleResultLogs: true },
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
await transaction.oldGeneral.upsert({
|
||||
await upsertWithoutSequence(transaction.oldGeneral, {
|
||||
where: { by_no: { serverId, generalNo: general.id } },
|
||||
update: {
|
||||
owner: general.userId ?? null,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||
import { handleCityOfficeRequest, settleCityOfficeRequests } from './cityOfficeRequests.js';
|
||||
import type {
|
||||
TurnDaemonCommandHandler,
|
||||
@@ -2864,8 +2865,8 @@ const insertVoteSelection = async (
|
||||
}
|
||||
const createdAt = new Date();
|
||||
const rows = await ctx.commandDb.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
||||
INSERT INTO vote (vote_id, general_id, nation_id, selection, created_at)
|
||||
SELECT poll.id,
|
||||
INSERT INTO vote (id, vote_id, general_id, nation_id, selection, created_at)
|
||||
SELECT ${existingRowIdOrNext('vote', GamePrisma.sql`stable_id.vote_id = poll.id AND stable_id.general_id = ${general.id}`)}, poll.id,
|
||||
${general.id},
|
||||
${general.nationId},
|
||||
CAST(${JSON.stringify(selection)} AS jsonb),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||
@@ -44,7 +45,7 @@ export const persistYearbookSnapshot = async (
|
||||
globalAction,
|
||||
});
|
||||
|
||||
await transaction.yearbookHistory.upsert({
|
||||
await upsertWithoutSequence(transaction.yearbookHistory, {
|
||||
where: {
|
||||
profileName_year_month_sourceId: {
|
||||
profileName: snapshot.serverId,
|
||||
|
||||
@@ -198,6 +198,23 @@ integration('general batch persistence', () => {
|
||||
);
|
||||
});
|
||||
expect(writes).toBe(2);
|
||||
const originalIds = (
|
||||
await db.generalAccessLog.findMany({
|
||||
where: { generalId: { gte: firstId, lte: firstId + GENERAL_UPDATE_BATCH_SIZE } },
|
||||
orderBy: { generalId: 'asc' },
|
||||
})
|
||||
).map((row) => row.id);
|
||||
const sequence = await db.$queryRaw`SELECT last_value FROM general_access_log_id_seq`;
|
||||
await db.$transaction((tx) => persistGeneralAccessScores(tx, updates));
|
||||
expect(
|
||||
(
|
||||
await db.generalAccessLog.findMany({
|
||||
where: { generalId: { gte: firstId, lte: firstId + GENERAL_UPDATE_BATCH_SIZE } },
|
||||
orderBy: { generalId: 'asc' },
|
||||
})
|
||||
).map((row) => row.id)
|
||||
).toEqual(originalIds);
|
||||
expect(await db.$queryRaw`SELECT last_value FROM general_access_log_id_seq`).toEqual(sequence);
|
||||
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId: firstId } })).toMatchObject({
|
||||
userId: 'original-owner',
|
||||
lastRefresh: at,
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GamePrisma } from '@sammo-ts/infra';
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
import { persistGeneralLifecycleEvents } from '../src/turn/generalTurnLifecyclePersistence.js';
|
||||
import type { GeneralLifecycleEvent } from '../src/turn/inMemoryWorld.js';
|
||||
import type { TurnGeneral } from '../src/turn/types.js';
|
||||
|
||||
// This harness begins without the durable archive/point row.
|
||||
const missingRecordUpdate = async (): Promise<never> => {
|
||||
throw new GamePrisma.PrismaClientKnownRequestError('fixture record missing', {
|
||||
code: 'P2025',
|
||||
clientVersion: 'fixture',
|
||||
});
|
||||
};
|
||||
|
||||
const archivedGeneral = (): TurnGeneral => ({
|
||||
id: 91,
|
||||
userId: null,
|
||||
@@ -65,12 +73,13 @@ describe('general lifecycle archive history', () => {
|
||||
]),
|
||||
},
|
||||
rankData: {
|
||||
update: missingRecordUpdate,
|
||||
findMany: vi.fn(async () => [
|
||||
{ type: 'warnum', value: 2 },
|
||||
{ type: 'killnum', value: 1 },
|
||||
]),
|
||||
},
|
||||
oldGeneral: { upsert },
|
||||
oldGeneral: { update: missingRecordUpdate, upsert },
|
||||
} as unknown as GamePrisma.TransactionClient;
|
||||
const event: GeneralLifecycleEvent = {
|
||||
generalId: general.id,
|
||||
@@ -137,6 +146,7 @@ describe('general lifecycle archive history', () => {
|
||||
updateMany: vi.fn(async () => ({ count: 1 })),
|
||||
},
|
||||
rankData: {
|
||||
update: missingRecordUpdate,
|
||||
findMany: vi.fn(async () => [
|
||||
{ type: 'warnum', value: 10 },
|
||||
{ type: 'inherit_earned', value: 123 },
|
||||
@@ -156,6 +166,7 @@ describe('general lifecycle archive history', () => {
|
||||
update: vi.fn(async () => undefined),
|
||||
},
|
||||
inheritancePoint: {
|
||||
update: missingRecordUpdate,
|
||||
findMany: vi.fn(async () => [{ key: 'previous', value: 0 }]),
|
||||
upsert: vi.fn(async () => undefined),
|
||||
deleteMany: vi.fn(async () => ({ count: 0 })),
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
|
||||
|
||||
import { upsertRankRows } from '../src/turn/databaseHooks.js';
|
||||
|
||||
const databaseUrl = process.env.IMMEDIATE_ACTION_DATABASE_URL;
|
||||
|
||||
// The conditional runner owns this schema and runs integration files serially.
|
||||
describe.skipIf(!databaseUrl)('rank data bigint PostgreSQL persistence', () => {
|
||||
let db: GamePrismaClient;
|
||||
let disconnect: () => Promise<void>;
|
||||
const generalId = 7_319;
|
||||
|
||||
beforeAll(async () => {
|
||||
const schema = new URL(databaseUrl!).searchParams.get('schema');
|
||||
if (!schema?.endsWith('immediate_action_integration')) {
|
||||
throw new Error('Refusing to mutate a non-dedicated rank persistence schema');
|
||||
}
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||
await connector.connect();
|
||||
db = connector.prisma;
|
||||
disconnect = () => connector.disconnect();
|
||||
await db.rankData.deleteMany({ where: { generalId } });
|
||||
// Even conflict-update on an existing row used to exhaust int4 IDs.
|
||||
await db.$executeRaw`SELECT setval(pg_get_serial_sequence('rank_data', 'id'), 2147483647)`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (db) await db.rankData.deleteMany({ where: { generalId } });
|
||||
await disconnect?.();
|
||||
});
|
||||
|
||||
it('reuses IDs across batches, updates ownership and values, and allocates bigint IDs only for new rows', async () => {
|
||||
const rows = Array.from({ length: 1_001 }, (_, index) => ({
|
||||
generalId,
|
||||
nationId: 10,
|
||||
type: `rank_fixture_${index}`,
|
||||
value: index,
|
||||
}));
|
||||
await db.$transaction((tx) => upsertRankRows(tx, rows));
|
||||
const original = await db.rankData.findMany({ where: { generalId }, orderBy: { type: 'asc' } });
|
||||
expect(original).toHaveLength(rows.length);
|
||||
expect(original.every((row) => row.id > 2_147_483_647n)).toBe(true);
|
||||
const sequenceBefore = await db.$queryRaw<
|
||||
Array<{ last_value: bigint }>
|
||||
>`SELECT last_value FROM rank_data_id_seq`;
|
||||
for (let count = 0; count < 3; count++) {
|
||||
await db.$transaction((tx) =>
|
||||
upsertRankRows(
|
||||
tx,
|
||||
rows.map((row) => ({ ...row, nationId: 20, value: row.value + 3 }))
|
||||
)
|
||||
);
|
||||
}
|
||||
const updated = await db.rankData.findMany({ where: { generalId }, orderBy: { type: 'asc' } });
|
||||
expect(updated.map((row) => row.id)).toEqual(original.map((row) => row.id));
|
||||
expect(updated.map((row) => [row.nationId, row.value])).toEqual(original.map((row) => [20, row.value + 3]));
|
||||
expect(await db.$queryRaw`SELECT last_value FROM rank_data_id_seq`).toEqual(sequenceBefore);
|
||||
await db.$transaction((tx) =>
|
||||
upsertRankRows(tx, [rows[0]!, { generalId, nationId: 30, type: 'new_rank', value: 17 }])
|
||||
);
|
||||
expect(await db.rankData.count({ where: { generalId } })).toBe(1_002);
|
||||
expect(await db.$queryRaw`SELECT last_value FROM rank_data_id_seq`).toEqual([
|
||||
{ last_value: sequenceBefore[0]!.last_value + 1n },
|
||||
]);
|
||||
});
|
||||
|
||||
it('reloads bigint IDs for high churn queues, logs, upserts and the traffic foreign key', async () => {
|
||||
const tables = [
|
||||
'general_access_log',
|
||||
'diplomacy',
|
||||
'inheritance_point',
|
||||
'log_entry',
|
||||
'error_log',
|
||||
'inheritance_log',
|
||||
'traffic_period',
|
||||
];
|
||||
for (const table of tables) {
|
||||
await db.$executeRaw`SELECT setval(pg_get_serial_sequence(${table}, 'id'), 2147483647)`;
|
||||
}
|
||||
await expect(
|
||||
db.$transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
const world = await tx.worldState.create({
|
||||
data: {
|
||||
scenarioCode: 'bigint-fixture',
|
||||
currentYear: 200,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
},
|
||||
});
|
||||
const rows = await Promise.all([
|
||||
tx.generalAccessLog.create({ data: { generalId } }),
|
||||
tx.diplomacy.create({ data: { srcNationId: 3, destNationId: 4, stateCode: 0 } }),
|
||||
tx.inheritancePoint.create({ data: { userId: 'bigint-fixture', key: 'previous', value: 123 } }),
|
||||
tx.logEntry.create({
|
||||
data: { scope: 'SYSTEM', category: 'HISTORY', year: 200, month: 1, text: 'fixture' },
|
||||
}),
|
||||
tx.errorLog.create({ data: { category: 'fixture', message: 'fixture' } }),
|
||||
tx.inheritanceLog.create({
|
||||
data: { userId: 'bigint-fixture', year: 200, month: 1, text: 'fixture' },
|
||||
}),
|
||||
]);
|
||||
expect(rows.every((row) => row.id > 2_147_483_647n)).toBe(true);
|
||||
const generalQueue = await tx.generalTurn.create({
|
||||
data: { generalId, turnIdx: 0, actionCode: 'fixture' },
|
||||
});
|
||||
const nationQueue = await tx.nationTurn.create({
|
||||
data: { nationId: 3, officerLevel: 12, turnIdx: 0, actionCode: 'fixture' },
|
||||
});
|
||||
expect(generalQueue).not.toHaveProperty('id');
|
||||
expect(nationQueue).not.toHaveProperty('id');
|
||||
const period = await tx.trafficPeriod.create({
|
||||
data: {
|
||||
worldStateId: world.id,
|
||||
year: 200,
|
||||
month: 1,
|
||||
startedAt: now,
|
||||
lastRefresh: now,
|
||||
generals: { create: { generalId, lastRefresh: now } },
|
||||
},
|
||||
include: { generals: true },
|
||||
});
|
||||
expect(period.id).toBeGreaterThan(2_147_483_647n);
|
||||
expect(period.generals[0]?.periodId).toBe(period.id);
|
||||
expect((await tx.logEntry.findUniqueOrThrow({ where: { id: rows[3]!.id } })).text).toBe('fixture');
|
||||
throw new Error('high churn fixture rollback');
|
||||
})
|
||||
).rejects.toThrow('high churn fixture rollback');
|
||||
});
|
||||
|
||||
it('rolls value updates back atomically and retains the logical unique constraint', async () => {
|
||||
const where = { generalId_type: { generalId, type: 'new_rank' } };
|
||||
const before = await db.rankData.findUniqueOrThrow({ where });
|
||||
await expect(
|
||||
db.$transaction(async (tx) => {
|
||||
await upsertRankRows(tx, [{ generalId, nationId: 99, type: 'new_rank', value: 999 }]);
|
||||
throw new Error('fixture rollback');
|
||||
})
|
||||
).rejects.toThrow('fixture rollback');
|
||||
expect(await db.rankData.findUniqueOrThrow({ where })).toEqual(before);
|
||||
await expect(
|
||||
db.rankData.create({ data: { generalId, nationId: 99, type: 'new_rank', value: 999 } })
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,21 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { normalizeArchivedGeneral, type ArchivedJsonValue } from '@sammo-ts/common';
|
||||
import type { GamePrisma } from '@sammo-ts/infra';
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope, type City, type Nation } from '@sammo-ts/logic';
|
||||
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import { persistUnificationFinalization, resolveStoredInheritancePoint } from '../src/turn/unificationPersistence.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
|
||||
// This harness begins without the durable archive/point row.
|
||||
const missingRecordUpdate = async (): Promise<never> => {
|
||||
throw new GamePrisma.PrismaClientKnownRequestError('fixture record missing', {
|
||||
code: 'P2025',
|
||||
clientVersion: 'fixture',
|
||||
});
|
||||
};
|
||||
|
||||
const buildWorld = (): InMemoryTurnWorld => {
|
||||
const turnTime = new Date('0190-07-01T00:00:00.000Z');
|
||||
const general: TurnGeneral = {
|
||||
@@ -206,6 +214,7 @@ describe('persistUnificationFinalization', () => {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
inheritancePoint: {
|
||||
update: missingRecordUpdate,
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{ userId: 'user-1', key: 'previous', value: 100 },
|
||||
{ userId: 'user-1', key: 'unifier', value: 7 },
|
||||
@@ -216,6 +225,7 @@ describe('persistUnificationFinalization', () => {
|
||||
inheritanceResult: { create: inheritanceResultCreate },
|
||||
inheritanceLog: { create: inheritanceLogCreate },
|
||||
rankData: {
|
||||
update: missingRecordUpdate,
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{ generalId: 1, type: 'warnum', value: 15 },
|
||||
{ generalId: 1, type: 'killnum', value: 9 },
|
||||
@@ -251,10 +261,11 @@ describe('persistUnificationFinalization', () => {
|
||||
),
|
||||
},
|
||||
oldNation: {
|
||||
update: missingRecordUpdate,
|
||||
upsert: oldNationUpsert,
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
oldGeneral: { upsert: oldGeneralUpsert },
|
||||
oldGeneral: { update: missingRecordUpdate, upsert: oldGeneralUpsert },
|
||||
emperor: { create: emperorCreate },
|
||||
});
|
||||
await expect(persistUnificationFinalization(transaction, input, buildWorld())).resolves.toEqual({
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GamePrisma } from '@sammo-ts/infra';
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
import { persistYearbookSnapshot } from '../src/turn/yearbookPersistence.js';
|
||||
|
||||
// This harness begins without the durable archive/point row.
|
||||
const missingRecordUpdate = async (): Promise<never> => {
|
||||
throw new GamePrisma.PrismaClientKnownRequestError('fixture record missing', {
|
||||
code: 'P2025',
|
||||
clientVersion: 'fixture',
|
||||
});
|
||||
};
|
||||
|
||||
describe('persistYearbookSnapshot', () => {
|
||||
it('archives canonical summary logs and compatible action logs together in descending ID order', async () => {
|
||||
const findMany = vi
|
||||
@@ -14,7 +22,7 @@ describe('persistYearbookSnapshot', () => {
|
||||
const upsert = vi.fn().mockResolvedValue(undefined);
|
||||
const transaction = {
|
||||
logEntry: { findMany },
|
||||
yearbookHistory: { upsert },
|
||||
yearbookHistory: { update: missingRecordUpdate, upsert },
|
||||
} as unknown as GamePrisma.TransactionClient;
|
||||
|
||||
await persistYearbookSnapshot(transaction, {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
import type { trpc } from '../src/utils/trpc.js';
|
||||
|
||||
import { gameProfile, gameTrpcRoute } from './gameTestPaths.js';
|
||||
import { expectLumenButtonStates } from './lumenButton.js';
|
||||
@@ -306,7 +309,11 @@ const personnelFixture = (state: FixtureState) => {
|
||||
};
|
||||
};
|
||||
|
||||
const install = async (page: Page, state: FixtureState): Promise<void> => {
|
||||
const install = async (
|
||||
page: Page,
|
||||
state: FixtureState,
|
||||
overviewCities?: Awaited<ReturnType<typeof trpc.nation.getCityOverview.query>>['cities']
|
||||
): Promise<void> => {
|
||||
await page.addInitScript((profile) => {
|
||||
localStorage.setItem('sammo-game-token', 'ga_city_office');
|
||||
localStorage.setItem('sammo-game-profile', profile);
|
||||
@@ -316,7 +323,10 @@ const install = async (page: Page, state: FixtureState): Promise<void> => {
|
||||
if (operation === 'auth.status') return response({ ok: true });
|
||||
if (operation === 'lobby.info') return response({ myGeneral: { id: 20, name: '순욱' } });
|
||||
if (operation === 'join.getConfig') return response({});
|
||||
if (operation === 'nation.getCityOverview') return response(overviewFixture(state));
|
||||
if (operation === 'nation.getCityOverview') {
|
||||
const overview = overviewFixture(state);
|
||||
return response({ ...overview, cities: overviewCities ?? overview.cities });
|
||||
}
|
||||
if (operation === 'nation.getSecretGeneralList') {
|
||||
return state.secretForbidden
|
||||
? errorResponse(
|
||||
@@ -491,3 +501,88 @@ test('NPC prefixes stay single in city names and linked secret rows', async ({ p
|
||||
await page.screenshot({ path: testInfo.outputPath(`npc-city-prefix-${width}.png`), fullPage: true });
|
||||
}
|
||||
});
|
||||
|
||||
for (const width of [1200, 500]) {
|
||||
test(`세력도시 기본 정렬은 지역별로 묶고 같은 지역 안에서 규모순으로 표시한다 (${width}px)`, async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const state: FixtureState = { role: 'head', appointed: false, appointmentInputs: [] };
|
||||
const baseCity = overviewFixture(state).cities[0]!;
|
||||
// ID·시세·규모순이 지역 우선 정렬과 서로 다르게 되는 입력이다.
|
||||
const overviewCities = [
|
||||
{ id: 10, name: '허창', region: 2, level: 8, trade: 60 },
|
||||
{ id: 20, name: '상당', region: 1, level: 5, trade: 130 },
|
||||
{ id: 30, name: '진류', region: 2, level: 5, trade: 110 },
|
||||
{ id: 40, name: '업', region: 1, level: 8, trade: 80 },
|
||||
{ id: 50, name: '북평', region: 1, level: 8, trade: 90 },
|
||||
].map((city) => ({ ...baseCity, ...city }));
|
||||
await install(page, state, overviewCities);
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.goto('nation/cities');
|
||||
const tables = page.locator('.city');
|
||||
await expect(tables).toHaveCount(5);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
const cityOrder = () => tables.evaluateAll((elements) => elements.map((el) => Number(el.dataset.cityId)));
|
||||
const regionStarts = () =>
|
||||
page
|
||||
.locator('.city.region-break')
|
||||
.evaluateAll((elements) => elements.map((el) => Number(el.dataset.cityId)));
|
||||
const expectedOrder = [40, 50, 20, 10, 30];
|
||||
const select = page.locator('#nation-city-sort');
|
||||
const submit = page.getByRole('button', { name: '정렬하기' });
|
||||
|
||||
await page.screenshot({ path: testInfo.outputPath('default-region-order.png'), fullPage: true });
|
||||
await writeFile(
|
||||
testInfo.outputPath('default-region-order.html'),
|
||||
await page.locator('main').evaluate((el) => el.outerHTML)
|
||||
);
|
||||
const geometry = await tables.evaluateAll((elements) =>
|
||||
elements.map((el) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const style = getComputedStyle(el);
|
||||
return {
|
||||
id: Number(el.dataset.cityId),
|
||||
title: el.querySelector('.city-title')?.textContent?.trim(),
|
||||
x: rect.x,
|
||||
y: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
marginTop: style.marginTop,
|
||||
fontSize: style.fontSize,
|
||||
borderCollapse: style.borderCollapse,
|
||||
};
|
||||
})
|
||||
);
|
||||
await writeFile(
|
||||
testInfo.outputPath('default-region-order.json'),
|
||||
JSON.stringify({ url: page.url(), width, geometry }, null, 2)
|
||||
);
|
||||
await expect(select).toHaveValue('1');
|
||||
expect(await cityOrder()).toEqual(expectedOrder);
|
||||
expect(await regionStarts()).toEqual([40, 10]);
|
||||
expect(geometry.map((city) => city.marginTop)).toEqual(['18px', '0px', '0px', '18px', '0px']);
|
||||
await expect(tables.locator('.city-title')).toContainText(['하북', '하북', '하북', '중원', '중원']);
|
||||
|
||||
// 선택만으로는 적용하지 않고 submit 뒤에만 기존 명시적 정렬을 적용한다.
|
||||
await select.selectOption('12');
|
||||
expect(await cityOrder()).toEqual(expectedOrder);
|
||||
await submit.click();
|
||||
expect(await cityOrder()).toEqual([40, 50, 10, 20, 30]);
|
||||
expect(await regionStarts()).toEqual([]);
|
||||
await page.getByRole('button', { name: '시세 기준 정렬' }).first().click();
|
||||
await expect(select).toHaveValue('10');
|
||||
expect(await cityOrder()).toEqual([20, 30, 50, 40, 10]);
|
||||
expect(await regionStarts()).toEqual([]);
|
||||
for (const sort of ['11', '1']) {
|
||||
await select.selectOption(sort);
|
||||
await submit.click();
|
||||
expect(await cityOrder()).toEqual(expectedOrder);
|
||||
expect(await regionStarts()).toEqual([40, 10]);
|
||||
}
|
||||
await page.reload();
|
||||
await expect(select).toHaveValue('1');
|
||||
await expect(tables).toHaveCount(5);
|
||||
expect(await cityOrder()).toEqual(expectedOrder);
|
||||
expect(state.appointmentInputs).toEqual([]);
|
||||
});
|
||||
}
|
||||
@@ -34,8 +34,8 @@ const integrationError = ref('');
|
||||
const secretLoading = ref(false);
|
||||
const personnelLoading = ref(false);
|
||||
const pendingAppointment = ref('');
|
||||
const sort = ref<Sort>(10);
|
||||
const selectedSort = ref<Sort>(10);
|
||||
const sort = ref<Sort>(1);
|
||||
const selectedSort = ref<Sort>(1);
|
||||
const extraSort = ref<
|
||||
| 'name'
|
||||
| 'populationRate'
|
||||
@@ -95,7 +95,7 @@ const cities = computed(() => {
|
||||
}
|
||||
return values.sort((a, b) => {
|
||||
const key = sort.value;
|
||||
if (key === 1) return a.id - b.id;
|
||||
if (key === 1 || key === 11) return a.region - b.region || b.level - a.level;
|
||||
if (key === 2) return b.population - a.population;
|
||||
if (key === 3) return b.population / b.populationMax - a.population / a.populationMax;
|
||||
if (key === 4) return b.trust - a.trust;
|
||||
@@ -105,7 +105,6 @@ const cities = computed(() => {
|
||||
if (key === 8) return b.defence - a.defence;
|
||||
if (key === 9) return b.wall - a.wall;
|
||||
if (key === 10) return (b.trade ?? -1) - (a.trade ?? -1);
|
||||
if (key === 11) return a.region - b.region || b.level - a.level;
|
||||
return b.level - a.level || a.region - b.region;
|
||||
});
|
||||
});
|
||||
@@ -148,7 +147,9 @@ const developmentClass = (
|
||||
return ratio > 0.8 ? 'development-high' : ratio > 0.4 ? 'development-mid' : 'development-low';
|
||||
};
|
||||
const isRegionBreak = (city: City, index: number) =>
|
||||
sort.value === 10 && extraSort.value === null && (index === 0 || cities.value[index - 1]?.region !== city.region);
|
||||
(sort.value === 1 || sort.value === 11) &&
|
||||
extraSort.value === null &&
|
||||
(index === 0 || cities.value[index - 1]?.region !== city.region);
|
||||
const officer = (city: City, level: 2 | 3 | 4) => city.officers[level]?.name ?? '-';
|
||||
const officerIsStationed = (city: City, level: OfficerLevel): boolean =>
|
||||
secretData.value !== null && city.officers[level]?.cityId === city.id;
|
||||
|
||||
@@ -1161,6 +1161,31 @@ export const adminRouter = router({
|
||||
await ctx.flushPublisher.publishUserFlush(input.userId, 'admin-scheduled-withdrawal');
|
||||
return { ok: true, deleteAfter: deleteAfter.toISOString() };
|
||||
}),
|
||||
cancelDeletion: userAdminProcedure
|
||||
.input(z.object({ userId: z.string().min(1), reason: z.string().trim().min(3).max(200) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const user = await ctx.users.findById(input.userId);
|
||||
if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found.' });
|
||||
assertTargetUserManageable(requireAdminAuth(ctx), user);
|
||||
if (!user.deleteAfter) {
|
||||
throw new TRPCError({ code: 'CONFLICT', message: '탈퇴 예약이 없는 계정입니다.' });
|
||||
}
|
||||
// 관리자 복구는 보존 기한과 무관하게 허용하되, 조회한 예약만 해제한다.
|
||||
// revision 증가로 이전 session과 사용자 복구 증명의 재사용을 막는다.
|
||||
if (!(await ctx.users.cancelDeletion(user.id, user.deleteAfter, user.authRevision ?? 0))) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '계정 상태가 변경되었습니다. 다시 조회해 주세요.',
|
||||
});
|
||||
}
|
||||
let flushPublished = true;
|
||||
try {
|
||||
await ctx.flushPublisher.publishUserFlush(user.id, 'admin-cancelled-withdrawal');
|
||||
} catch {
|
||||
flushPublished = false;
|
||||
}
|
||||
return { ok: true, deleteAfter: null, flushPublished };
|
||||
}),
|
||||
forceDelete: userAdminProcedure
|
||||
.input(
|
||||
z.object({
|
||||
|
||||
@@ -103,10 +103,12 @@ const EXPENSIVE_ACTIONS = new Set([
|
||||
'auth.bootstrapLocal',
|
||||
'auth.kakaoExchange',
|
||||
'auth.kakaoResolveAccount',
|
||||
'auth.kakaoLinkWithPassword',
|
||||
'auth.kakaoSetPassword',
|
||||
'auth.register',
|
||||
'auth.registerLocal',
|
||||
'auth.login',
|
||||
'auth.cancelDeletion',
|
||||
'auth.kakaoOtp',
|
||||
'account.changePassword',
|
||||
'account.scheduleDeletion',
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { isLoginBanned } from '@sammo-ts/common/auth/sanctions';
|
||||
|
||||
import type { GatewayApiContext } from '../context.js';
|
||||
import { toPublicUser, type UserRecord } from './userRepository.js';
|
||||
|
||||
// 이전 서비스의 장기 보존 탈퇴 계정만 복구한다. 날짜는 한국 시간 기준이다.
|
||||
export const LEGACY_DELETION_RECOVERY_CUTOFF = new Date('2026-07-01T00:00:00+09:00');
|
||||
|
||||
export const canCancelDeletion = (user: UserRecord, now = new Date()): boolean => {
|
||||
if (!user.deleteAfter) return false;
|
||||
const deadline = new Date(user.deleteAfter).getTime();
|
||||
return (
|
||||
Number.isFinite(deadline) &&
|
||||
(deadline > now.getTime() ||
|
||||
(Number.isSafeInteger(user.legacyMemberNo) &&
|
||||
(user.legacyMemberNo ?? 0) > 0 &&
|
||||
deadline - 30 * 24 * 60 * 60 * 1000 < LEGACY_DELETION_RECOVERY_CUTOFF.getTime()))
|
||||
);
|
||||
};
|
||||
|
||||
export const assertLoginAllowed = (user: UserRecord): void => {
|
||||
if (isLoginBanned(user.sanctions)) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: 'Account login is blocked.' });
|
||||
}
|
||||
if (user.deleteAfter && !canCancelDeletion(user)) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '계정 보존 기간이 지나 탈퇴를 취소할 수 없습니다.' });
|
||||
}
|
||||
};
|
||||
|
||||
export const completeGatewayLogin = async <T extends 'login' | 'verified'>(
|
||||
ctx: GatewayApiContext,
|
||||
user: UserRecord,
|
||||
status: T
|
||||
) => {
|
||||
assertLoginAllowed(user);
|
||||
if (user.deleteAfter) {
|
||||
// 비밀번호와 필요한 Kakao/OTP 검증을 모두 마친 뒤에만, 접근 권한 없는 일회용 증명을 발급한다.
|
||||
const recovery = await ctx.oauthSessions.createDeletionRecovery({
|
||||
userId: user.id,
|
||||
deleteAfter: user.deleteAfter,
|
||||
authRevision: user.authRevision ?? 0,
|
||||
expiresAt: new Date(Date.now() + 300_000).toISOString(),
|
||||
});
|
||||
return { status: 'deletion_pending' as const, recoveryId: recovery.id, deleteAfter: user.deleteAfter };
|
||||
}
|
||||
const session = await ctx.sessions.createSession(user);
|
||||
return { status, user: toPublicUser(user), sessionToken: session.sessionToken, issuedAt: session.issuedAt };
|
||||
};
|
||||
@@ -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)
|
||||
) {
|
||||
@@ -558,6 +630,20 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
||||
}
|
||||
throw new Error('User not found.');
|
||||
},
|
||||
async cancelDeletion(userId: string, deleteAfter: string, authRevision: number): Promise<boolean> {
|
||||
for (const user of usersByName.values()) {
|
||||
if (
|
||||
user.id === userId &&
|
||||
user.deleteAfter === deleteAfter &&
|
||||
(user.authRevision ?? 0) === authRevision
|
||||
) {
|
||||
user.deleteAfter = undefined;
|
||||
user.authRevision = authRevision + 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
async deleteUser(userId: string): Promise<void> {
|
||||
for (const [username, user] of usersByName.entries()) {
|
||||
if (user.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: '이메일이 다른 계정은 기존 비밀번호로 확인하거나 관리자에게 복구를 요청해 주세요.',
|
||||
});
|
||||
};
|
||||
@@ -1,8 +1,18 @@
|
||||
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';
|
||||
|
||||
export interface DeletionRecovery {
|
||||
id: string;
|
||||
userId: string;
|
||||
deleteAfter: string;
|
||||
authRevision: number;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export interface OAuthPendingState {
|
||||
state: string;
|
||||
mode: OAuthMode;
|
||||
@@ -14,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;
|
||||
@@ -26,6 +41,9 @@ export interface OAuthSession {
|
||||
}
|
||||
|
||||
export interface KakaoLoginChallenge {
|
||||
authRevision?: number;
|
||||
oauthId?: string;
|
||||
oauthSessionId?: string;
|
||||
id: string;
|
||||
userId: string;
|
||||
code: string;
|
||||
@@ -35,16 +53,19 @@ 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' };
|
||||
|
||||
export interface OAuthSessionStore {
|
||||
createDeletionRecovery(recovery: Omit<DeletionRecovery, 'id'>): Promise<DeletionRecovery>;
|
||||
consumeDeletionRecovery(id: string): Promise<DeletionRecovery | null>;
|
||||
createPendingState(mode: OAuthMode, scopes: string[], userId?: string): Promise<OAuthPendingState>;
|
||||
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>;
|
||||
@@ -90,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 = `
|
||||
@@ -106,6 +127,20 @@ export class RedisOAuthSessionStore implements OAuthSessionStore {
|
||||
private readonly prefix: string;
|
||||
private readonly ttlSeconds: number;
|
||||
|
||||
async createDeletionRecovery(recovery: Omit<DeletionRecovery, 'id'>): Promise<DeletionRecovery> {
|
||||
const stored = { ...recovery, id: randomUUID() };
|
||||
await this.client.set(`${this.prefix}:deletion-recovery:${stored.id}`, JSON.stringify(stored), { EX: 300 });
|
||||
return stored;
|
||||
}
|
||||
|
||||
async consumeDeletionRecovery(id: string): Promise<DeletionRecovery | null> {
|
||||
const raw = await this.client.eval(consumeOnceScript, {
|
||||
keys: [`${this.prefix}:deletion-recovery:${id}`],
|
||||
arguments: [],
|
||||
});
|
||||
return typeof raw === 'string' ? parseJson<DeletionRecovery>(raw) : null;
|
||||
}
|
||||
|
||||
constructor(client: RedisClientLike, prefix: string, ttlSeconds: number) {
|
||||
this.client = client;
|
||||
this.prefix = prefix;
|
||||
@@ -164,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: [] });
|
||||
@@ -225,6 +265,19 @@ export class RedisOAuthSessionStore implements OAuthSessionStore {
|
||||
|
||||
// 테스트용 인메모리 OAuth 세션 저장소.
|
||||
export class InMemoryOAuthSessionStore implements OAuthSessionStore {
|
||||
private readonly deletionRecoveries = new Map<string, DeletionRecovery>();
|
||||
|
||||
async createDeletionRecovery(recovery: Omit<DeletionRecovery, 'id'>): Promise<DeletionRecovery> {
|
||||
const stored = { ...recovery, id: randomUUID() };
|
||||
this.deletionRecoveries.set(stored.id, stored);
|
||||
return stored;
|
||||
}
|
||||
|
||||
async consumeDeletionRecovery(id: string): Promise<DeletionRecovery | null> {
|
||||
const recovery = this.deletionRecoveries.get(id) ?? null;
|
||||
this.deletionRecoveries.delete(id);
|
||||
return recovery && new Date(recovery.expiresAt).getTime() > Date.now() ? recovery : null;
|
||||
}
|
||||
private readonly pendingStates = new Map<string, OAuthPendingState>();
|
||||
private readonly sessions = new Map<string, OAuthSession>();
|
||||
private readonly loginChallenges = new Map<string, KakaoLoginChallenge>();
|
||||
@@ -259,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) {
|
||||
@@ -320,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)
|
||||
) {
|
||||
@@ -789,6 +908,14 @@ export const createPostgresUserRepository = (
|
||||
data: { deleteAfter },
|
||||
});
|
||||
},
|
||||
async cancelDeletion(userId: string, deleteAfter: string, authRevision: number): Promise<boolean> {
|
||||
// 인증한 탈퇴 예약만 취소하고, 이전 session과 복구 증명은 revision으로 무효화한다.
|
||||
const result = await prisma.appUser.updateMany({
|
||||
where: { id: userId, deleteAfter: new Date(deleteAfter), authRevision },
|
||||
data: { deleteAfter: null, authRevision: { increment: 1 } },
|
||||
});
|
||||
return result.count === 1;
|
||||
},
|
||||
async deleteUser(userId: string): Promise<void> {
|
||||
await prisma.appUser.delete({
|
||||
where: { id: userId },
|
||||
|
||||
@@ -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: {
|
||||
@@ -249,6 +269,7 @@ export interface UserRepository {
|
||||
resetProfileIcon(userId: string, requestedAt: Date): Promise<string | null>;
|
||||
setThirdPartyUse(userId: string, allowed: boolean): Promise<void>;
|
||||
scheduleDeletion(userId: string, deleteAfter: Date): Promise<void>;
|
||||
cancelDeletion(userId: string, deleteAfter: string, authRevision: number): Promise<boolean>;
|
||||
deleteUser(userId: string): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
+136
-157
@@ -23,6 +23,13 @@ import { openPassword, zDisplayName, zPasswordEnvelope, zRegistrationUsername }
|
||||
import { resolveEffectiveAccountIcon } from './auth/accountIconProjection.js';
|
||||
import { isGatewaySessionCurrent } from './auth/sessionValidity.js';
|
||||
import { GameSessionLimitError } from './auth/sessionService.js';
|
||||
import { assertLoginAllowed, canCancelDeletion, completeGatewayLogin } from './auth/deletionRecovery.js';
|
||||
import {
|
||||
beginPendingKakaoLink,
|
||||
finishPendingKakaoLink,
|
||||
requestPendingKakaoOtp,
|
||||
validatePendingKakaoProfile,
|
||||
} from './auth/pendingKakaoLink.js';
|
||||
import { purifyGatewayNoticeHtml } from './security/gatewayNoticeHtml.js';
|
||||
import type { GatewayApiContext } from './context.js';
|
||||
import { listScenarioPreviews } from './scenario/scenarioCatalog.js';
|
||||
@@ -73,6 +80,7 @@ const finishKakaoLogin = async <T extends 'login' | 'verified'>(
|
||||
accessToken: string,
|
||||
successStatus: T
|
||||
) => {
|
||||
assertLoginAllowed(user);
|
||||
try {
|
||||
const challenge = await requireKakaoTalkProof({
|
||||
user,
|
||||
@@ -87,13 +95,7 @@ const finishKakaoLogin = async <T extends 'login' | 'verified'>(
|
||||
} catch (error) {
|
||||
throwKakaoVerificationError(error);
|
||||
}
|
||||
const session = await ctx.sessions.createSession(user);
|
||||
return {
|
||||
status: successStatus,
|
||||
user: toPublicUser(user),
|
||||
sessionToken: session.sessionToken,
|
||||
issuedAt: session.issuedAt,
|
||||
};
|
||||
return completeGatewayLogin(ctx, user, successStatus);
|
||||
};
|
||||
|
||||
const finishKakaoLoginOrRequestPasswordSetup = async <T extends 'login' | 'verified'>(
|
||||
@@ -102,6 +104,7 @@ const finishKakaoLoginOrRequestPasswordSetup = async <T extends 'login' | 'verif
|
||||
accessToken: string,
|
||||
successStatus: T
|
||||
) => {
|
||||
assertLoginAllowed(user);
|
||||
if (!user.passwordResetRequired) {
|
||||
return finishKakaoLogin(ctx, user, accessToken, successStatus);
|
||||
}
|
||||
@@ -397,57 +400,30 @@ export const appRouter = router({
|
||||
});
|
||||
}
|
||||
const oauthInfo = oauthInfoFromToken(token, tokenIssuedAt, localUser.oauthInfo);
|
||||
let verified: UserRecord;
|
||||
const replacingKakao =
|
||||
localUser.oauthType === 'KAKAO' &&
|
||||
Boolean(localUser.oauthId) &&
|
||||
localUser.oauthId !== profile.kakaoId;
|
||||
if (replacingKakao) {
|
||||
try {
|
||||
verified = await ctx.users.replaceKakaoWithApprovedIdentity(localUser.id, {
|
||||
oauthId: profile.kakaoId,
|
||||
if (localUser.oauthType !== 'KAKAO' || localUser.oauthId !== profile.kakaoId) {
|
||||
const stored = await ctx.oauthSessions.createSession({
|
||||
mode: pending.mode,
|
||||
intent: 'link_existing',
|
||||
targetUserId: localUser.id,
|
||||
kakaoId: profile.kakaoId,
|
||||
email: profile.email,
|
||||
oauthInfo,
|
||||
verifiedAt: new Date(),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '관리자의 카카오 계정 교체 승인이 없거나 만료되었습니다.',
|
||||
cause: error,
|
||||
accessToken: token.accessToken,
|
||||
refreshToken: token.refreshToken,
|
||||
accessTokenValidUntil: oauthInfo.accessTokenValidUntil!,
|
||||
refreshTokenValidUntil: oauthInfo.refreshTokenValidUntil,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
return {
|
||||
status: 'account_recovery' as const,
|
||||
action: 'link_existing' as const,
|
||||
oauthSessionId: stored.id,
|
||||
email: stored.email,
|
||||
passwordRequired: localUser.email?.toLowerCase() !== profile.email,
|
||||
};
|
||||
}
|
||||
} else if (existingById?.id !== localUser.id && localUser.oauthType !== 'KAKAO') {
|
||||
try {
|
||||
verified = await ctx.users.linkKakao(localUser.id, {
|
||||
oauthId: profile.kakaoId,
|
||||
email: profile.email,
|
||||
oauthInfo,
|
||||
verifiedAt: new Date(),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '이미 다른 계정에 연결된 카카오 계정입니다.',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
verified = await ctx.users.syncKakaoIdentity(localUser.id, profile.email, oauthInfo);
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '이미 다른 계정에서 사용 중인 카카오 이메일입니다. 관리자에게 문의해 주세요.',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
const verified = await ctx.users.syncKakaoIdentity(localUser.id, profile.email, oauthInfo);
|
||||
const refreshed = (await ctx.users.findById(verified.id)) ?? verified;
|
||||
await ctx.flushPublisher.publishUserFlush(
|
||||
refreshed.id,
|
||||
replacingKakao ? 'kakao-account-replaced' : 'kakao-verified'
|
||||
);
|
||||
await ctx.flushPublisher.publishUserFlush(refreshed.id, 'kakao-verified');
|
||||
return finishKakaoLoginOrRequestPasswordSetup(ctx, refreshed, token.accessToken, 'verified');
|
||||
}
|
||||
|
||||
@@ -518,8 +494,20 @@ export const appRouter = router({
|
||||
return finishKakaoLoginOrRequestPasswordSetup(ctx, synced, token.accessToken, 'login');
|
||||
}
|
||||
|
||||
const detachedOwnerId = await ctx.users.findDetachedKakaoOwner(profile.kakaoId);
|
||||
const detachedOwner = detachedOwnerId ? await ctx.users.findById(detachedOwnerId) : null;
|
||||
if (
|
||||
detachedOwnerId &&
|
||||
(!detachedOwner || (existingByEmail && existingByEmail.id !== detachedOwnerId))
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '이전 계정에 귀속된 카카오 계정입니다. 관리자에게 복구를 요청해 주세요.',
|
||||
});
|
||||
}
|
||||
const recoveryTarget = detachedOwner ?? existingByEmail;
|
||||
const joinOauthInfo = oauthInfoFromToken(token, tokenIssuedAt);
|
||||
const recoveryIntent = existingByEmail
|
||||
const recoveryIntent = recoveryTarget
|
||||
? ('link_existing' as const)
|
||||
: alreadyRegisteredWithKakao
|
||||
? ('rejoin' as const)
|
||||
@@ -527,7 +515,7 @@ export const appRouter = router({
|
||||
const stored = await ctx.oauthSessions.createSession({
|
||||
mode: pending.mode,
|
||||
intent: recoveryIntent,
|
||||
targetUserId: existingByEmail?.id,
|
||||
targetUserId: recoveryTarget?.id,
|
||||
kakaoId: profile.kakaoId,
|
||||
email: profile.email,
|
||||
accessToken: token.accessToken,
|
||||
@@ -543,6 +531,9 @@ export const appRouter = router({
|
||||
action: recoveryIntent,
|
||||
oauthSessionId: stored.id,
|
||||
email: stored.email,
|
||||
passwordRequired: recoveryTarget
|
||||
? recoveryTarget.email?.toLowerCase() !== profile.email
|
||||
: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -560,7 +551,7 @@ export const appRouter = router({
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const oauthSession = await ctx.oauthSessions.consumeSession(input.oauthSessionId);
|
||||
const oauthSession = await ctx.oauthSessions.getSession(input.oauthSessionId);
|
||||
if (!oauthSession) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
@@ -574,6 +565,8 @@ export const appRouter = router({
|
||||
});
|
||||
}
|
||||
|
||||
if (!(await ctx.oauthSessions.consumeSession(input.oauthSessionId)))
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED', message: '카카오 계정 확인이 이미 사용되었습니다.' });
|
||||
if (input.action === 'rejoin') {
|
||||
const [oauthOwner, emailOwner] = await Promise.all([
|
||||
ctx.users.findByOauthId('KAKAO', oauthSession.kakaoId),
|
||||
@@ -614,7 +607,7 @@ export const appRouter = router({
|
||||
ctx.users.findByEmail(oauthSession.email),
|
||||
ctx.users.findByOauthId('KAKAO', oauthSession.kakaoId),
|
||||
]);
|
||||
if (!targetUser || emailOwner?.id !== targetUser.id) {
|
||||
if (!targetUser || (emailOwner && emailOwner.id !== targetUser.id)) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message:
|
||||
@@ -627,59 +620,42 @@ export const appRouter = router({
|
||||
message: '이미 다른 계정에 연결된 카카오 계정입니다.',
|
||||
});
|
||||
}
|
||||
if (targetUser.deleteAfter) {
|
||||
throw new TRPCError({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '탈퇴 처리 중인 계정에는 카카오 계정을 다시 연결할 수 없습니다.',
|
||||
});
|
||||
}
|
||||
if (isLoginBanned(targetUser.sanctions)) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Account login is blocked.',
|
||||
});
|
||||
}
|
||||
assertLoginAllowed(targetUser);
|
||||
|
||||
const oauthInfo: UserOAuthInfo = {
|
||||
accessToken: oauthSession.accessToken,
|
||||
refreshToken: oauthSession.refreshToken,
|
||||
accessTokenValidUntil: oauthSession.accessTokenValidUntil,
|
||||
refreshTokenValidUntil: oauthSession.refreshTokenValidUntil,
|
||||
};
|
||||
let linked: UserRecord;
|
||||
try {
|
||||
const replacement =
|
||||
targetUser.oauthType === 'KAKAO' &&
|
||||
Boolean(targetUser.oauthId) &&
|
||||
targetUser.oauthId !== oauthSession.kakaoId;
|
||||
linked = replacement
|
||||
? await ctx.users.replaceKakaoWithApprovedIdentity(targetUser.id, {
|
||||
oauthId: oauthSession.kakaoId,
|
||||
email: oauthSession.email,
|
||||
oauthInfo,
|
||||
verifiedAt: new Date(),
|
||||
})
|
||||
: await ctx.users.relinkKakaoByEmail(targetUser.id, {
|
||||
oauthId: oauthSession.kakaoId,
|
||||
email: oauthSession.email,
|
||||
oauthInfo,
|
||||
verifiedAt: new Date(),
|
||||
});
|
||||
} catch (error) {
|
||||
return beginPendingKakaoLink(ctx, targetUser, oauthSession);
|
||||
}),
|
||||
kakaoLinkWithPassword: procedure
|
||||
.input(z.object({ oauthSessionId: z.string().uuid(), username: zUsername, credential: zPasswordEnvelope }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const oauth = await ctx.oauthSessions.getSession(input.oauthSessionId);
|
||||
if (!oauth || !['register', 'rejoin', 'link_existing'].includes(oauth.intent ?? 'register'))
|
||||
throw new TRPCError({
|
||||
code: targetUser.oauthType === 'KAKAO' ? 'PRECONDITION_FAILED' : 'CONFLICT',
|
||||
message:
|
||||
targetUser.oauthType === 'KAKAO'
|
||||
? '기존 카카오 계정 교체에는 관리자 승인이 필요합니다.'
|
||||
: '카카오 계정 연결 상태가 변경되었습니다. 처음부터 다시 진행해 주세요.',
|
||||
cause: error,
|
||||
code: 'UNAUTHORIZED',
|
||||
message: '카카오 연결 확인이 만료되었습니다. 다시 로그인해 주세요.',
|
||||
});
|
||||
}
|
||||
await ctx.flushPublisher.publishUserFlush(
|
||||
linked.id,
|
||||
targetUser.oauthType === 'KAKAO' ? 'kakao-account-replaced' : 'kakao-account-relinked'
|
||||
);
|
||||
return finishKakaoLoginOrRequestPasswordSetup(ctx, linked, oauthSession.accessToken, 'login');
|
||||
await validatePendingKakaoProfile(ctx, oauth);
|
||||
const user = await ctx.users.findByUsername(input.username);
|
||||
const password = openPassword(ctx.passwordEnvelope, input.credential);
|
||||
if (
|
||||
!user ||
|
||||
!(await ctx.users.verifyPassword(user, password)) ||
|
||||
(oauth.targetUserId && oauth.targetUserId !== user.id)
|
||||
)
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: '기존 계정명 또는 비밀번호가 일치하지 않습니다.',
|
||||
});
|
||||
const emailOwner = await ctx.users.findByEmail(oauth.email);
|
||||
if (emailOwner && emailOwner.id !== user.id)
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '새 카카오 이메일이 다른 계정에 연결되어 있습니다. 관리자에게 문의해 주세요.',
|
||||
});
|
||||
if (!(await ctx.oauthSessions.consumeSession(oauth.id)))
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED', message: '카카오 연결 확인이 이미 사용되었습니다.' });
|
||||
const refreshed = await ctx.users.findById(user.id);
|
||||
if (!refreshed) throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
return beginPendingKakaoLink(ctx, refreshed, oauth, true);
|
||||
}),
|
||||
kakaoSetPassword: procedure
|
||||
.input(
|
||||
@@ -690,6 +666,19 @@ export const appRouter = router({
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const password = openPassword(ctx.passwordEnvelope, input.credential);
|
||||
const staged = await ctx.oauthSessions.getSession(input.oauthSessionId);
|
||||
if (staged?.intent === 'identity_link' && staged.identityLink && staged.targetUserId) {
|
||||
await validatePendingKakaoProfile(ctx, staged);
|
||||
const user = await ctx.users.findById(staged.targetUserId);
|
||||
if (!user) throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
if (!(await ctx.oauthSessions.consumeSession(staged.id)))
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
const next = await ctx.oauthSessions.createSession({
|
||||
...staged,
|
||||
identityLink: { ...staged.identityLink, credential: input.credential },
|
||||
});
|
||||
return requestPendingKakaoOtp(ctx, next, user);
|
||||
}
|
||||
const oauthSession = await ctx.oauthSessions.consumeSession(input.oauthSessionId);
|
||||
if (!oauthSession || oauthSession.intent !== 'password_setup' || !oauthSession.targetUserId) {
|
||||
throw new TRPCError({
|
||||
@@ -710,12 +699,7 @@ export const appRouter = router({
|
||||
message: '카카오 계정 연결 상태가 변경되었습니다. 처음부터 다시 진행해 주세요.',
|
||||
});
|
||||
}
|
||||
if (user.deleteAfter) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: 'Account deletion is pending.' });
|
||||
}
|
||||
if (isLoginBanned(user.sanctions)) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: 'Account login is blocked.' });
|
||||
}
|
||||
assertLoginAllowed(user);
|
||||
let verifiedProfile;
|
||||
try {
|
||||
verifiedProfile = readVerifiedKakaoProfile(await ctx.kakaoClient.getMe(oauthSession.accessToken));
|
||||
@@ -931,12 +915,6 @@ export const appRouter = router({
|
||||
message: 'Invalid username or password.',
|
||||
});
|
||||
}
|
||||
if (user.deleteAfter) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Account deletion is pending.',
|
||||
});
|
||||
}
|
||||
const password = openPassword(ctx.passwordEnvelope, input.credential);
|
||||
const ok = await ctx.users.verifyPassword(user, password);
|
||||
if (!ok) {
|
||||
@@ -945,22 +923,11 @@ export const appRouter = router({
|
||||
message: 'Invalid username or password.',
|
||||
});
|
||||
}
|
||||
if (isLoginBanned(user.sanctions)) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Account login is blocked.',
|
||||
});
|
||||
}
|
||||
assertLoginAllowed(user);
|
||||
if (user.oauthType === 'KAKAO') {
|
||||
const specialAccessGrants = await ctx.users.listSpecialAccessGrants(user.id);
|
||||
if (hasOperatorSpecialAccess(user) || hasActiveSpecialAccountGrant(specialAccessGrants)) {
|
||||
const session = await ctx.sessions.createSession(user);
|
||||
return {
|
||||
status: 'login' as const,
|
||||
user: toPublicUser(user),
|
||||
sessionToken: session.sessionToken,
|
||||
issuedAt: session.issuedAt,
|
||||
};
|
||||
return completeGatewayLogin(ctx, user, 'login');
|
||||
}
|
||||
const ready = await verifyStoredKakaoIdentity({
|
||||
user,
|
||||
@@ -969,13 +936,34 @@ export const appRouter = router({
|
||||
}).catch((error: unknown) => throwKakaoVerificationError(error));
|
||||
return finishKakaoLogin(ctx, ready.user, ready.accessToken, 'login');
|
||||
}
|
||||
const session = await ctx.sessions.createSession(user);
|
||||
return {
|
||||
status: 'login' as const,
|
||||
user: toPublicUser(user),
|
||||
sessionToken: session.sessionToken,
|
||||
issuedAt: session.issuedAt,
|
||||
};
|
||||
return completeGatewayLogin(ctx, user, 'login');
|
||||
}),
|
||||
cancelDeletion: procedure
|
||||
.input(z.object({ recoveryId: z.string().uuid() }).strict())
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const recovery = await ctx.oauthSessions.consumeDeletionRecovery(input.recoveryId);
|
||||
if (!recovery || new Date(recovery.expiresAt).getTime() <= Date.now()) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: '복구 인증이 만료되었습니다. 다시 로그인해 주세요.',
|
||||
});
|
||||
}
|
||||
const user = await ctx.users.findById(recovery.userId);
|
||||
if (!user) throw new TRPCError({ code: 'UNAUTHORIZED', message: '계정을 찾지 못했습니다.' });
|
||||
assertLoginAllowed(user);
|
||||
if (
|
||||
!canCancelDeletion(user) ||
|
||||
!(await ctx.users.cancelDeletion(user.id, recovery.deleteAfter, recovery.authRevision))
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '계정 상태가 변경되었습니다. 다시 로그인해 주세요.',
|
||||
});
|
||||
}
|
||||
await ctx.flushPublisher.publishUserFlush(user.id, 'account-deletion-cancelled');
|
||||
const restored = await ctx.users.findById(user.id);
|
||||
if (!restored) throw new TRPCError({ code: 'UNAUTHORIZED', message: '계정을 찾지 못했습니다.' });
|
||||
return completeGatewayLogin(ctx, restored, 'login');
|
||||
}),
|
||||
kakaoOtp: procedure
|
||||
.input(
|
||||
@@ -991,24 +979,15 @@ export const appRouter = router({
|
||||
oauthSessions: ctx.oauthSessions,
|
||||
users: ctx.users,
|
||||
}).catch((error: unknown) => throwKakaoVerificationError(error));
|
||||
if (verified.user.deleteAfter) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Account deletion is pending.',
|
||||
});
|
||||
}
|
||||
if (isLoginBanned(verified.user.sanctions)) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Account login is blocked.',
|
||||
});
|
||||
}
|
||||
const session = await ctx.sessions.createSession(verified.user);
|
||||
if (verified.pendingLinkSessionId)
|
||||
return finishPendingKakaoLink(
|
||||
ctx,
|
||||
verified.pendingLinkSessionId,
|
||||
verified.user.id,
|
||||
verified.validUntil
|
||||
);
|
||||
return {
|
||||
status: 'login' as const,
|
||||
user: toPublicUser(verified.user),
|
||||
sessionToken: session.sessionToken,
|
||||
issuedAt: session.issuedAt,
|
||||
...(await completeGatewayLogin(ctx, verified.user, 'login')),
|
||||
validUntil: verified.validUntil,
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -12,7 +12,11 @@ export const procedure = t.procedure.use(async ({ ctx, path, getRawInput, next }
|
||||
const raw: unknown = await getRawInput();
|
||||
const input = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
||||
const resolveSubject = async (): Promise<string | undefined> => {
|
||||
if (path === 'auth.login' && typeof input.username === 'string' && input.username.length <= 64) {
|
||||
if (
|
||||
(path === 'auth.login' || path === 'auth.kakaoLinkWithPassword') &&
|
||||
typeof input.username === 'string' &&
|
||||
input.username.length <= 64
|
||||
) {
|
||||
return `login:${input.username.trim().toLocaleLowerCase('en-US')}`;
|
||||
}
|
||||
if (
|
||||
|
||||
@@ -2,12 +2,15 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createGatewayPostgresConnector, type GatewayPrismaClient } from '@sammo-ts/infra';
|
||||
|
||||
import { snapshotKakaoLink } from '../src/auth/kakaoLinkPolicy.js';
|
||||
import { createPostgresUserRepository } from '../src/auth/postgresUserRepository.js';
|
||||
|
||||
const databaseUrl = process.env.GATEWAY_RUNTIME_ACTION_DATABASE_URL;
|
||||
const integration = describe.skipIf(!databaseUrl);
|
||||
const firstUserId = 'f28aa8ce-6bd0-45e5-a127-056de53e3161';
|
||||
const secondUserId = '8f610116-64bd-4f18-bf7f-eae1737b227c';
|
||||
const bootstrapId = '00000000-0000-4000-8000-000000000042';
|
||||
const selfUserId = '00000000-0000-4000-8000-000000000043';
|
||||
const oldKakaoId = 'account-identity-old-kakao';
|
||||
const newKakaoId = 'account-identity-new-kakao';
|
||||
|
||||
@@ -30,9 +33,34 @@ integration('account identity PostgreSQL transaction', () => {
|
||||
db = connector.prisma;
|
||||
closeDb = () => connector.disconnect();
|
||||
await db.retiredKakaoIdentity.deleteMany({ where: { oauthId: { in: [oldKakaoId, newKakaoId] } } });
|
||||
await db.appUser.deleteMany({ where: { id: { in: [firstUserId, secondUserId] } } });
|
||||
await db.kakaoIdentityLinkHistory.deleteMany({
|
||||
where: { userId: { in: [firstUserId, secondUserId, selfUserId] } },
|
||||
});
|
||||
await db.appUser.deleteMany({ where: { id: { in: [firstUserId, secondUserId, bootstrapId, selfUserId] } } });
|
||||
await db.appUser.createMany({
|
||||
data: [
|
||||
{
|
||||
id: bootstrapId,
|
||||
loginId: 'identity-bootstrap',
|
||||
displayName: '복구통합관리자',
|
||||
passwordHash: 'not-used',
|
||||
passwordSalt: 'not-used',
|
||||
roles: ['superuser'],
|
||||
sanctions: {},
|
||||
createdAt: new Date('2000-01-01'),
|
||||
},
|
||||
{
|
||||
id: selfUserId,
|
||||
loginId: 'identity-self',
|
||||
displayName: '직접복구계정',
|
||||
passwordHash: 'not-used',
|
||||
passwordSalt: 'not-used',
|
||||
roles: ['user'],
|
||||
sanctions: {},
|
||||
oauthType: 'KAKAO',
|
||||
oauthId: 'self-db-old',
|
||||
email: 'self-db@example.test',
|
||||
},
|
||||
{
|
||||
id: firstUserId,
|
||||
loginId: 'identity-integration-one',
|
||||
@@ -63,7 +91,10 @@ integration('account identity PostgreSQL transaction', () => {
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.retiredKakaoIdentity.deleteMany({ where: { oauthId: { in: [oldKakaoId, newKakaoId] } } });
|
||||
await db?.appUser.deleteMany({ where: { id: { in: [firstUserId, secondUserId] } } });
|
||||
await db?.kakaoIdentityLinkHistory.deleteMany({
|
||||
where: { userId: { in: [firstUserId, secondUserId, selfUserId] } },
|
||||
});
|
||||
await db?.appUser.deleteMany({ where: { id: { in: [firstUserId, secondUserId, bootstrapId, selfUserId] } } });
|
||||
await closeDb?.();
|
||||
});
|
||||
|
||||
@@ -139,4 +170,114 @@ integration('account identity PostgreSQL transaction', () => {
|
||||
})
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it('cancels only the authenticated deletion snapshot once and persists the new auth revision', async () => {
|
||||
const users = createPostgresUserRepository(db);
|
||||
const deadline = new Date(Date.now() + 86400000);
|
||||
await users.scheduleDeletion(firstUserId, deadline);
|
||||
const before = await users.findById(firstUserId);
|
||||
const revision = before?.authRevision ?? 0;
|
||||
expect(await users.cancelDeletion(firstUserId, new Date(deadline.getTime() - 1).toISOString(), revision)).toBe(
|
||||
false
|
||||
);
|
||||
expect(await users.cancelDeletion(firstUserId, deadline.toISOString(), revision + 1)).toBe(false);
|
||||
const results = await Promise.all([
|
||||
users.cancelDeletion(firstUserId, deadline.toISOString(), revision),
|
||||
users.cancelDeletion(firstUserId, deadline.toISOString(), revision),
|
||||
]);
|
||||
expect(results.filter(Boolean)).toHaveLength(1);
|
||||
const restored = await users.findById(firstUserId);
|
||||
expect(restored?.deleteAfter).toBeUndefined();
|
||||
expect(restored?.authRevision).toBe(revision + 1);
|
||||
expect(restored?.oauthId).toBe(before?.oauthId);
|
||||
expect(restored?.sanctions).toEqual(before?.sanctions);
|
||||
});
|
||||
it('commits identity, imported password, proof and history together, and restricts former identities to their owner', async () => {
|
||||
const users = createPostgresUserRepository(db);
|
||||
await db.appUser.update({ where: { id: selfUserId }, data: { passwordResetRequired: true } });
|
||||
const before = await users.findById(selfUserId);
|
||||
const now = new Date();
|
||||
const input = {
|
||||
expected: snapshotKakaoLink(before!),
|
||||
authorization: 'EMAIL' as const,
|
||||
oauthId: 'self-db-new',
|
||||
email: 'self-db@example.test',
|
||||
oauthInfo: {},
|
||||
verifiedAt: now,
|
||||
talkVerifiedUntil: new Date(now.getTime() + 86400000),
|
||||
password: 'new-self-password',
|
||||
};
|
||||
const restored = await users.completeKakaoIdentityLink(selfUserId, input);
|
||||
expect(restored).toMatchObject({
|
||||
oauthId: 'self-db-new',
|
||||
passwordResetRequired: false,
|
||||
authRevision: (before?.authRevision ?? 0) + 1,
|
||||
});
|
||||
expect(await users.verifyPassword(restored, 'new-self-password')).toBe(true);
|
||||
expect(await users.findDetachedKakaoOwner('self-db-old')).toBe(selfUserId);
|
||||
expect(await users.isKakaoIdentityRetired('self-db-old')).toBe(false);
|
||||
expect(await db.kakaoIdentityLinkHistory.count({ where: { userId: selfUserId } })).toBe(1);
|
||||
await expect(users.completeKakaoIdentityLink(selfUserId, input)).rejects.toThrow();
|
||||
await expect(
|
||||
users.createUser({
|
||||
username: 'identity-history-claim',
|
||||
password: 'secretpass',
|
||||
oauth: { type: 'KAKAO', id: 'self-db-old', email: 'claim@example.test', info: {} },
|
||||
})
|
||||
).rejects.toThrow();
|
||||
const prior = await users.findById(selfUserId);
|
||||
await users.completeKakaoIdentityLink(selfUserId, {
|
||||
...input,
|
||||
expected: snapshotKakaoLink(prior!),
|
||||
oauthId: 'self-db-old',
|
||||
});
|
||||
expect((await users.findById(selfUserId))?.oauthId).toBe('self-db-old');
|
||||
const snapshot = await users.findById(selfUserId);
|
||||
const conflicting = await users.findById(secondUserId);
|
||||
await expect(
|
||||
users.completeKakaoIdentityLink(selfUserId, {
|
||||
...input,
|
||||
expected: snapshotKakaoLink(snapshot!),
|
||||
oauthId: conflicting!.oauthId!,
|
||||
password: 'must-not-be-saved',
|
||||
})
|
||||
).rejects.toThrow();
|
||||
expect((await users.findById(selfUserId))?.passwordHash).toBe(snapshot?.passwordHash);
|
||||
expect(await db.kakaoIdentityLinkHistory.count({ where: { userId: selfUserId } })).toBe(2);
|
||||
await expect(
|
||||
users.markKakaoTalkVerified(selfUserId, new Date(Date.now() + 10000), 0, 'self-db-old')
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('allows only one concurrent recovery against the same PostgreSQL snapshot', async () => {
|
||||
const users = createPostgresUserRepository(db);
|
||||
const user = await users.findById(selfUserId);
|
||||
const input = {
|
||||
expected: snapshotKakaoLink(user!),
|
||||
authorization: 'EMAIL' as const,
|
||||
email: 'self-db@example.test',
|
||||
oauthInfo: {},
|
||||
verifiedAt: new Date(),
|
||||
talkVerifiedUntil: new Date(Date.now() + 86400000),
|
||||
};
|
||||
const results = await Promise.allSettled(
|
||||
['self-db-race-one', 'self-db-race-two'].map((oauthId) =>
|
||||
users.completeKakaoIdentityLink(selfUserId, { ...input, oauthId })
|
||||
)
|
||||
);
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(results.filter((r) => r.status === 'rejected')).toHaveLength(1);
|
||||
expect((await users.findById(selfUserId))?.authRevision).toBe((user?.authRevision ?? 0) + 1);
|
||||
});
|
||||
it('keeps former identity ownership after the service account is deleted', async () => {
|
||||
const users = createPostgresUserRepository(db);
|
||||
await users.deleteUser(selfUserId);
|
||||
expect(await users.findDetachedKakaoOwner('self-db-old')).toBe(selfUserId);
|
||||
await expect(
|
||||
users.createUser({
|
||||
username: 'deleted-owner-claim',
|
||||
password: 'secretpass',
|
||||
oauth: { type: 'KAKAO', id: 'self-db-old', email: 'deleted-owner-claim@example.test', info: {} },
|
||||
})
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GatewayPrismaClient } from '@sammo-ts/infra';
|
||||
|
||||
@@ -25,6 +25,7 @@ const buildCaller = async (
|
||||
createOperation: GatewayProfileRepository['createOperation'],
|
||||
options: {
|
||||
adminRoles?: string[];
|
||||
flushError?: Error;
|
||||
firstUserIsAdmin?: boolean;
|
||||
runtimeActionCreateError?: unknown;
|
||||
initialNotice?: string;
|
||||
@@ -242,6 +243,7 @@ const buildCaller = async (
|
||||
sessions,
|
||||
flushPublisher: {
|
||||
publishUserFlush: async (userId, reason, metadata) => {
|
||||
if (options.flushError) throw options.flushError;
|
||||
flushes.push({
|
||||
userId,
|
||||
reason,
|
||||
@@ -2216,6 +2218,94 @@ describe('Gateway administrator account controls', () => {
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
});
|
||||
|
||||
it.each([new Date('2020-01-01T00:00:00Z'), new Date('2099-01-01T00:00:00Z')])(
|
||||
'lets a user administrator cancel deletion dated %s with an audited reason',
|
||||
async (deadline) => {
|
||||
const harness = await buildCaller(unusedCreateOperation, {
|
||||
adminRoles: ['user', 'admin.users.manage'],
|
||||
firstUserIsAdmin: false,
|
||||
});
|
||||
const target = await harness.users.createUser({ username: 'restore-target', password: 'secretpass' });
|
||||
await harness.users.updateSanctions(target.id, { bannedUntil: '2099-01-01T00:00:00Z' });
|
||||
await harness.users.scheduleDeletion(target.id, deadline);
|
||||
const before = structuredClone(await harness.users.findById(target.id));
|
||||
expect(
|
||||
await harness.caller.admin.users.cancelDeletion({
|
||||
userId: target.id,
|
||||
reason: '고객 본인 확인 후 탈퇴 취소',
|
||||
})
|
||||
).toEqual({ ok: true, deleteAfter: null, flushPublished: true });
|
||||
const after = await harness.users.findById(target.id);
|
||||
expect(after?.deleteAfter).toBeUndefined();
|
||||
expect(after?.authRevision).toBe((before?.authRevision ?? 0) + 1);
|
||||
expect(after?.sanctions).toEqual(before?.sanctions);
|
||||
expect(after?.passwordHash).toBe(before?.passwordHash);
|
||||
expect(after?.oauthId).toBe(before?.oauthId);
|
||||
expect(harness.flushes).toContainEqual({ userId: target.id, reason: 'admin-cancelled-withdrawal' });
|
||||
expect(harness.auditEvents.map((event) => event.outcome)).toEqual(['STARTED', 'SUCCEEDED']);
|
||||
expect(harness.auditEvents[1]).toMatchObject({
|
||||
action: 'admin.users.cancelDeletion',
|
||||
capability: 'admin.users.manage',
|
||||
actorUserId: harness.admin.id,
|
||||
targetId: target.id,
|
||||
reason: '고객 본인 확인 후 탈퇴 취소',
|
||||
});
|
||||
await expect(
|
||||
harness.caller.admin.users.cancelDeletion({ userId: target.id, reason: '중복 취소 요청' })
|
||||
).rejects.toMatchObject({ code: 'CONFLICT' });
|
||||
expect(harness.auditEvents.at(-1)).toMatchObject({ outcome: 'FAILED', errorCode: 'CONFLICT' });
|
||||
}
|
||||
);
|
||||
|
||||
it('denies missing scope, protected root targets, bad reasons and missing targets without mutation', async () => {
|
||||
for (const roles of [['admin.notice.manage'], ['admin.users.manage']]) {
|
||||
const h = await buildCaller(unusedCreateOperation, { adminRoles: roles, firstUserIsAdmin: false });
|
||||
const target = await h.users.createUser({ username: 'protected-restore', password: 'secretpass' });
|
||||
await h.users.updateRoles(target.id, ['superuser']);
|
||||
await h.users.scheduleDeletion(target.id, new Date('2020-01-01'));
|
||||
const cancel = vi.spyOn(h.users, 'cancelDeletion');
|
||||
await expect(
|
||||
h.caller.admin.users.cancelDeletion({ userId: target.id, reason: '권한 없는 복구 시도' })
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
expect(cancel).not.toHaveBeenCalled();
|
||||
expect(h.flushes).toHaveLength(0);
|
||||
expect(h.auditEvents.at(-1)).toMatchObject({ outcome: 'FAILED', errorCode: 'FORBIDDEN' });
|
||||
}
|
||||
const h = await buildCaller(unusedCreateOperation);
|
||||
await expect(h.caller.admin.users.cancelDeletion({ userId: h.admin.id, reason: ' ' })).rejects.toMatchObject({
|
||||
code: 'BAD_REQUEST',
|
||||
});
|
||||
await expect(
|
||||
h.caller.admin.users.cancelDeletion({ userId: 'missing-user', reason: '없는 계정 복구' })
|
||||
).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
||||
});
|
||||
|
||||
it('keeps a newer deletion reservation when compare-and-swap fails', async () => {
|
||||
const h = await buildCaller(unusedCreateOperation);
|
||||
const target = await h.users.createUser({ username: 'rescheduled-restore', password: 'secretpass' });
|
||||
await h.users.scheduleDeletion(target.id, new Date('2020-01-01'));
|
||||
vi.spyOn(h.users, 'cancelDeletion').mockImplementation(async () => {
|
||||
await h.users.scheduleDeletion(target.id, new Date('2099-01-01'));
|
||||
return false;
|
||||
});
|
||||
await expect(
|
||||
h.caller.admin.users.cancelDeletion({ userId: target.id, reason: '재예약 충돌 확인' })
|
||||
).rejects.toMatchObject({ code: 'CONFLICT' });
|
||||
expect((await h.users.findById(target.id))?.deleteAfter).toBe('2099-01-01T00:00:00.000Z');
|
||||
expect(h.flushes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('reports a committed cancellation as success when flush delivery fails', async () => {
|
||||
const h = await buildCaller(unusedCreateOperation, { flushError: new Error('synthetic flush failure') });
|
||||
const target = await h.users.createUser({ username: 'flush-restore', password: 'secretpass' });
|
||||
await h.users.scheduleDeletion(target.id, new Date('2020-01-01'));
|
||||
expect(
|
||||
await h.caller.admin.users.cancelDeletion({ userId: target.id, reason: '고객 요청 복구' })
|
||||
).toMatchObject({ ok: true, flushPublished: false });
|
||||
expect((await h.users.findById(target.id))?.deleteAfter).toBeUndefined();
|
||||
expect(h.auditEvents.at(-1)).toMatchObject({ outcome: 'SUCCEEDED' });
|
||||
});
|
||||
|
||||
it('prevents a delegated administrator from changing a root administrator', async () => {
|
||||
const harness = await buildCaller(unusedCreateOperation, {
|
||||
adminRoles: ['user', 'admin.users.manage'],
|
||||
|
||||
@@ -505,4 +505,46 @@ describe('admin security over HTTP transport', () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
it('requires a valid authorized administrator to cancel deletion over HTTP and invalidates prior sessions', async () => {
|
||||
const h = await createHarness();
|
||||
await h.users.scheduleDeletion(h.target.id, new Date('2020-01-01'));
|
||||
const input = { userId: h.target.id, reason: '본인 확인 후 관리자 복구' };
|
||||
expect((await postTrpc(h.baseUrl, 'admin.users.cancelDeletion', input)).response.status).toBe(401);
|
||||
expect(
|
||||
(await postTrpc(h.baseUrl, 'admin.users.cancelDeletion', input, h.targetSessionToken)).response.status
|
||||
).toBe(403);
|
||||
expect(
|
||||
(await postTrpc(h.baseUrl, 'admin.users.cancelDeletion', { ...input, reason: ' ' }, h.adminSessionToken))
|
||||
.response.status
|
||||
).toBe(400);
|
||||
await h.users.updateRoles(h.target.id, ['superuser']);
|
||||
expect(
|
||||
(await postTrpc(h.baseUrl, 'admin.users.cancelDeletion', input, h.adminSessionToken)).response.status
|
||||
).toBe(403);
|
||||
expect(h.flushes).toHaveLength(0);
|
||||
expect((await h.users.findById(h.target.id))?.deleteAfter).toBeDefined();
|
||||
await h.users.updateRoles(h.target.id, ['user']);
|
||||
expect(
|
||||
(await postTrpc(h.baseUrl, 'admin.users.cancelDeletion', input, h.adminSessionToken)).response.status
|
||||
).toBe(200);
|
||||
expect((await h.users.findById(h.target.id))?.deleteAfter).toBeUndefined();
|
||||
const me = await fetch(`${h.baseUrl}/trpc/me`, { headers: { 'x-session-token': h.targetSessionToken } });
|
||||
expect(await me.json()).toMatchObject({ result: { data: null } });
|
||||
expect(
|
||||
(await postTrpc(h.baseUrl, 'admin.users.cancelDeletion', input, h.adminSessionToken)).response.status
|
||||
).toBe(409);
|
||||
const noScope = await createHarness(['user', 'admin.notice.manage']);
|
||||
await noScope.users.scheduleDeletion(noScope.target.id, new Date('2020-01-01'));
|
||||
expect(
|
||||
(
|
||||
await postTrpc(
|
||||
noScope.baseUrl,
|
||||
'admin.users.cancelDeletion',
|
||||
{ userId: noScope.target.id, reason: '사용자 관리 권한 없음' },
|
||||
noScope.adminSessionToken
|
||||
)
|
||||
).response.status
|
||||
).toBe(403);
|
||||
expect((await noScope.users.findById(noScope.target.id))?.deleteAfter).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import fastify from 'fastify';
|
||||
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
|
||||
import { trpcJsonBodyHttpServerOptions } from '@sammo-ts/common';
|
||||
import { canCancelDeletion } from '../src/auth/deletionRecovery.js';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -228,8 +232,7 @@ const buildCaller = (
|
||||
).toString('base64'),
|
||||
};
|
||||
};
|
||||
const caller = appRouter.createCaller(
|
||||
createGatewayApiContext({
|
||||
const context = createGatewayApiContext({
|
||||
users,
|
||||
sessions,
|
||||
flushPublisher,
|
||||
@@ -255,9 +258,10 @@ const buildCaller = (
|
||||
findFirst: async () => null,
|
||||
},
|
||||
} as unknown as GatewayPrismaClient,
|
||||
})
|
||||
);
|
||||
});
|
||||
const caller = appRouter.createCaller(context);
|
||||
return {
|
||||
context,
|
||||
caller,
|
||||
oauthSessions,
|
||||
users,
|
||||
@@ -265,6 +269,7 @@ const buildCaller = (
|
||||
flushPublisher,
|
||||
userIconUpload,
|
||||
kakaoProfile,
|
||||
kakaoClient,
|
||||
sentTalkMessages,
|
||||
refreshTokenCalls,
|
||||
sealPassword,
|
||||
@@ -636,11 +641,17 @@ describe('gateway auth flow', () => {
|
||||
});
|
||||
setSessionHeader(register.sessionToken);
|
||||
const start = await caller.auth.kakaoStart({ mode: 'verify' });
|
||||
const verified = await caller.auth.kakaoExchange({
|
||||
const choice = await caller.auth.kakaoExchange({
|
||||
code: 'oauth-code',
|
||||
state: start.state,
|
||||
});
|
||||
|
||||
if (choice.status !== 'account_recovery') throw new Error('Expected link confirmation.');
|
||||
const verified = await caller.auth.kakaoLinkWithPassword({
|
||||
oauthSessionId: choice.oauthSessionId,
|
||||
username: 'verify-user',
|
||||
credential: sealPassword('verify-password'),
|
||||
});
|
||||
expect(verified.status).toBe('otp');
|
||||
if (verified.status !== 'otp') {
|
||||
throw new Error('Expected Kakao OTP challenge.');
|
||||
@@ -648,6 +659,7 @@ describe('gateway auth flow', () => {
|
||||
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||
expect(code).toBeTruthy();
|
||||
const completed = await caller.auth.kakaoOtp({ challengeId: verified.challengeId, code: code! });
|
||||
if (completed.status !== 'login') throw new Error('Expected login.');
|
||||
expect(completed.user.kakaoVerified).toBe(true);
|
||||
const stored = await users.findByUsername('verify-user');
|
||||
expect(stored).toMatchObject({
|
||||
@@ -680,11 +692,6 @@ describe('gateway auth flow', () => {
|
||||
});
|
||||
emailOwner.passwordResetRequired = true;
|
||||
await users.markKakaoTalkVerified(emailOwner.id, new Date(Date.now() + 60_000));
|
||||
await users.setKakaoReplacementApproval(emailOwner.id, {
|
||||
until: new Date(Date.now() + 60_000),
|
||||
approvedByUserId: 'admin-user-id',
|
||||
reason: '이메일 보존 계정의 교체 승인',
|
||||
});
|
||||
kakaoProfile.id = 'different-kakao-id';
|
||||
|
||||
const start = await caller.auth.kakaoStart({ mode: 'login' });
|
||||
@@ -710,15 +717,16 @@ describe('gateway auth flow', () => {
|
||||
});
|
||||
expect(passwordSet.status).toBe('otp');
|
||||
expect(sentTalkMessages).toHaveLength(1);
|
||||
expect(await users.findByOauthId('KAKAO', 'original-kakao-id')).toMatchObject({ id: emailOwner.id });
|
||||
expect((await users.findById(emailOwner.id))?.passwordResetRequired).toBe(true);
|
||||
if (passwordSet.status !== 'otp') throw new Error('Expected OTP.');
|
||||
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||
await caller.auth.kakaoOtp({ challengeId: passwordSet.challengeId, code: code! });
|
||||
expect(await users.findByOauthId('KAKAO', 'original-kakao-id')).toBeNull();
|
||||
expect(await users.isKakaoIdentityRetired('original-kakao-id')).toBe(true);
|
||||
expect(await users.findByOauthId('KAKAO', 'different-kakao-id')).toMatchObject({
|
||||
id: emailOwner.id,
|
||||
username: 'email-owner',
|
||||
email: 'tester@example.com',
|
||||
});
|
||||
expect(flushPublisher.publishUserFlush).toHaveBeenCalledWith(emailOwner.id, 'kakao-account-replaced');
|
||||
expect(flushPublisher.publishUserFlush).toHaveBeenCalledWith(emailOwner.id, 'password-changed');
|
||||
expect(await users.isKakaoIdentityRetired('original-kakao-id')).toBe(false);
|
||||
expect(await users.findDetachedKakaoOwner('original-kakao-id')).toBe(emailOwner.id);
|
||||
expect(await users.findByOauthId('KAKAO', 'different-kakao-id')).toMatchObject({ id: emailOwner.id });
|
||||
expect(flushPublisher.publishUserFlush).toHaveBeenCalledWith(emailOwner.id, 'kakao-account-relinked');
|
||||
});
|
||||
|
||||
it('requires a one-time password setup before an imported Kakao account can receive a session', async () => {
|
||||
@@ -891,42 +899,41 @@ describe('gateway auth flow', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('replaces an approved Kakao identity, retires the old ID, and invalidates older sessions', async () => {
|
||||
const { caller, users, sessions, kakaoProfile, setSessionHeader } = buildCaller({
|
||||
kakaoId: 'new-kakao-id',
|
||||
kakaoEmail: 'new-kakao@example.com',
|
||||
});
|
||||
const user = await users.createUser({
|
||||
it('completes an approved administrator replacement only after fresh talk proof and keeps old-ID ownership', async () => {
|
||||
const f = buildCaller({ kakaoId: 'new-kakao-id', kakaoEmail: 'new-kakao@example.com' });
|
||||
const user = await f.users.createUser({
|
||||
username: 'approved-replacement-user',
|
||||
password: 'replacement-password',
|
||||
oauth: { type: 'KAKAO', id: 'old-kakao-id', email: 'old-kakao@example.com', info: {} },
|
||||
});
|
||||
const oldSession = await sessions.createSession(user);
|
||||
setSessionHeader(oldSession.sessionToken);
|
||||
await users.setKakaoReplacementApproval(user.id, {
|
||||
until: new Date(Date.now() + 60_000),
|
||||
approvedByUserId: 'admin-user-id',
|
||||
reason: '사용자 본인 확인 완료',
|
||||
await f.users.updateRoles(user.id, ['admin']);
|
||||
await f.users.setKakaoReplacementApproval(user.id, {
|
||||
until: new Date(Date.now() + 60000),
|
||||
approvedByUserId: 'operator',
|
||||
reason: '본인 확인 완료',
|
||||
});
|
||||
|
||||
const start = await caller.auth.kakaoStart({ mode: 'verify', sessionToken: oldSession.sessionToken });
|
||||
const result = await caller.auth.kakaoExchange({ code: 'oauth-code', state: start.state });
|
||||
expect(result).toMatchObject({ status: 'otp', successStatus: 'verified' });
|
||||
expect(await users.findById(user.id)).toMatchObject({
|
||||
const old = await f.sessions.createSession(user);
|
||||
f.setSessionHeader(old.sessionToken);
|
||||
const start = await f.caller.auth.kakaoStart({ mode: 'verify' });
|
||||
const choice = await f.caller.auth.kakaoExchange({ code: 'code', state: start.state });
|
||||
if (choice.status !== 'account_recovery') throw new Error('Expected confirmation.');
|
||||
const otp = await f.caller.auth.kakaoResolveAccount({
|
||||
oauthSessionId: choice.oauthSessionId,
|
||||
action: 'link_existing',
|
||||
});
|
||||
if (otp.status !== 'otp') throw new Error('Expected OTP.');
|
||||
expect((await f.users.findById(user.id))?.oauthId).toBe('old-kakao-id');
|
||||
expect(await f.caller.auth.me({ sessionToken: old.sessionToken })).not.toBeNull();
|
||||
const code = f.sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||
await f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: code! });
|
||||
expect(await f.users.findById(user.id)).toMatchObject({
|
||||
oauthId: 'new-kakao-id',
|
||||
email: 'new-kakao@example.com',
|
||||
kakaoReplacementApprovedUntil: undefined,
|
||||
authRevision: 1,
|
||||
kakaoReplacementApprovedUntil: undefined,
|
||||
});
|
||||
await expect(users.isKakaoIdentityRetired('old-kakao-id')).resolves.toBe(true);
|
||||
await expect(caller.auth.me({ sessionToken: oldSession.sessionToken })).resolves.toBeNull();
|
||||
|
||||
kakaoProfile.id = 'old-kakao-id';
|
||||
kakaoProfile.email = 'old-kakao@example.com';
|
||||
const retiredStart = await caller.auth.kakaoStart({ mode: 'login' });
|
||||
await expect(
|
||||
caller.auth.kakaoExchange({ code: 'oauth-code', state: retiredStart.state })
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN', message: expect.stringContaining('영구 폐기') });
|
||||
expect(await f.users.isKakaoIdentityRetired('old-kakao-id')).toBe(false);
|
||||
expect(await f.users.findDetachedKakaoOwner('old-kakao-id')).toBe(user.id);
|
||||
expect(await f.caller.auth.me({ sessionToken: old.sessionToken })).toBeNull();
|
||||
});
|
||||
|
||||
it('synchronizes a changed email by stable Kakao ID during Kakao login', async () => {
|
||||
@@ -1128,22 +1135,12 @@ describe('gateway auth flow', () => {
|
||||
});
|
||||
|
||||
it('blocks Kakao login while a ban is active', async () => {
|
||||
const { caller, users, sealPassword, setSessionHeader } = buildCaller();
|
||||
const register = await caller.auth.registerLocal({
|
||||
const { caller, users } = buildCaller();
|
||||
await users.createUser({
|
||||
username: 'kakao-banned-user',
|
||||
credential: sealPassword('kakao-banned-password'),
|
||||
displayName: '카카오제재유저',
|
||||
termsAgreed: true,
|
||||
privacyAgreed: true,
|
||||
thirdPartyUse: false,
|
||||
password: 'kakao-banned-password',
|
||||
oauth: { type: 'KAKAO', id: '1', email: 'tester@example.com', info: {} },
|
||||
});
|
||||
setSessionHeader(register.sessionToken);
|
||||
const verifyStart = await caller.auth.kakaoStart({ mode: 'verify' });
|
||||
await caller.auth.kakaoExchange({
|
||||
code: 'oauth-code',
|
||||
state: verifyStart.state,
|
||||
});
|
||||
|
||||
const stored = await users.findByUsername('kakao-banned-user');
|
||||
expect(stored).not.toBeNull();
|
||||
if (stored) {
|
||||
@@ -1223,6 +1220,7 @@ describe('gateway auth flow', () => {
|
||||
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||
expect(code).toBeTruthy();
|
||||
const completed = await caller.auth.kakaoOtp({ challengeId: register.challengeId, code: code! });
|
||||
if (completed.status !== 'login') throw new Error('Expected login.');
|
||||
expect(completed.user.username).toBe('tester');
|
||||
expect(completed.sessionToken).toBeTruthy();
|
||||
|
||||
@@ -1785,3 +1783,387 @@ describe('account self service', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('account deletion cancellation', () => {
|
||||
const pendingLogin = async () => {
|
||||
const f = buildCaller();
|
||||
const user = await f.users.createUser({ username: 'recover-user', password: 'secretpass' });
|
||||
const other = await f.users.createUser({ username: 'other-recover-user', password: 'secretpass' });
|
||||
const oldSession = await f.sessions.createSession(user);
|
||||
const deadline = new Date(Date.now() + 30 * 86400000);
|
||||
await f.caller.account.scheduleDeletion({
|
||||
sessionToken: oldSession.sessionToken,
|
||||
currentCredential: f.sealPassword('secretpass'),
|
||||
});
|
||||
const result = await f.caller.auth.login({ username: user.username, credential: f.sealPassword('secretpass') });
|
||||
if (result.status !== 'deletion_pending') throw new Error('Expected deletion confirmation.');
|
||||
return { ...f, user, other, oldSession, deadline, result };
|
||||
};
|
||||
|
||||
it('authenticates before offering cancellation and restores only the proved account once', async () => {
|
||||
const f = await pendingLogin();
|
||||
await expect(
|
||||
f.caller.auth.login({ username: f.user.username, credential: f.sealPassword('wrongpass') })
|
||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
||||
expect(f.result).not.toHaveProperty('sessionToken');
|
||||
expect(await f.sessions.getSession(f.oldSession.sessionToken)).toBeNull();
|
||||
const restored = await f.caller.auth.cancelDeletion({ recoveryId: f.result.recoveryId });
|
||||
expect(restored.status).toBe('login');
|
||||
if (restored.status !== 'login') throw new Error('Expected login.');
|
||||
expect((await f.users.findById(f.user.id))?.deleteAfter).toBeUndefined();
|
||||
expect((await f.users.findById(f.user.id))?.authRevision).toBe(1);
|
||||
expect((await f.sessions.getSession(restored.sessionToken))?.userId).toBe(f.user.id);
|
||||
expect((await f.users.findById(f.other.id))?.authRevision).toBe(0);
|
||||
expect(f.flushPublisher.publishUserFlush).toHaveBeenCalledWith(f.user.id, 'account-deletion-cancelled');
|
||||
await expect(f.caller.auth.cancelDeletion({ recoveryId: f.result.recoveryId })).rejects.toMatchObject({
|
||||
code: 'UNAUTHORIZED',
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['rescheduled', 'expired-proof', 'sanctioned', 'deleted'] as const)(
|
||||
'rejects a %s recovery without clearing deletion',
|
||||
async (kind) => {
|
||||
const f = await pendingLogin();
|
||||
if (kind === 'rescheduled') await f.users.scheduleDeletion(f.user.id, new Date(Date.now() + 60 * 86400000));
|
||||
if (kind === 'sanctioned')
|
||||
await f.users.updateSanctions(f.user.id, {
|
||||
bannedUntil: new Date(Date.now() + 86400000).toISOString(),
|
||||
});
|
||||
if (kind === 'deleted') await f.users.deleteUser(f.user.id);
|
||||
if (kind === 'expired-proof') vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 301000);
|
||||
try {
|
||||
await expect(f.caller.auth.cancelDeletion({ recoveryId: f.result.recoveryId })).rejects.toBeDefined();
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
if (kind !== 'deleted') expect((await f.users.findById(f.user.id))?.deleteAfter).toBeDefined();
|
||||
expect(f.flushPublisher.publishUserFlush).not.toHaveBeenCalledWith(f.user.id, 'account-deletion-cancelled');
|
||||
}
|
||||
);
|
||||
|
||||
it('requires a proof, rejects actor injection and verifies actual HTTP transport', async () => {
|
||||
const f = await pendingLogin();
|
||||
const app = fastify();
|
||||
await app.register(fastifyTRPCPlugin, {
|
||||
prefix: '/gateway/api/trpc',
|
||||
trpcOptions: { router: appRouter, ...trpcJsonBodyHttpServerOptions, createContext: () => f.context },
|
||||
});
|
||||
try {
|
||||
const address = await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const post = (input: object) =>
|
||||
fetch(`${address}/gateway/api/trpc/auth.cancelDeletion`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
expect((await post({})).status).toBe(400);
|
||||
expect((await post({ recoveryId: 'not-a-uuid' })).status).toBe(400);
|
||||
expect((await post({ recoveryId: '11111111-1111-4111-8111-111111111111' })).status).toBe(401);
|
||||
expect((await post({ recoveryId: f.result.recoveryId, userId: f.other.id })).status).toBe(400);
|
||||
expect((await post({ recoveryId: f.result.recoveryId })).status).toBe(200);
|
||||
expect((await post({ recoveryId: f.result.recoveryId })).status).toBe(401);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
[false, false],
|
||||
[true, false],
|
||||
[false, true],
|
||||
[true, true],
|
||||
])(
|
||||
'supports pending Kakao accounts after existing-email linking=%s, legacy=%s and OTP proof',
|
||||
async (linkByEmail, legacy) => {
|
||||
const f = buildCaller();
|
||||
const user = await f.users.createUser({
|
||||
username: 'kakao-recover',
|
||||
password: 'secretpass',
|
||||
oauth: { type: 'KAKAO', id: linkByEmail ? 'former-id' : '1', email: 'tester@example.com', info: {} },
|
||||
});
|
||||
if (linkByEmail)
|
||||
await f.users.setKakaoReplacementApproval(user.id, {
|
||||
until: new Date(Date.now() + 60000),
|
||||
approvedByUserId: 'operator',
|
||||
reason: '본인 확인 완료',
|
||||
});
|
||||
if (legacy) {
|
||||
user.legacyMemberNo = 42;
|
||||
user.passwordResetRequired = true;
|
||||
}
|
||||
await f.users.scheduleDeletion(
|
||||
user.id,
|
||||
legacy ? new Date('2026-07-30T14:59:59.999Z') : new Date(Date.now() + 86400000)
|
||||
);
|
||||
const start = await f.caller.auth.kakaoStart({ mode: 'login' });
|
||||
let result = await f.caller.auth.kakaoExchange({ code: 'test-code', state: start.state });
|
||||
if (linkByEmail) {
|
||||
if (result.status !== 'account_recovery') throw new Error('Expected account link confirmation.');
|
||||
result = await f.caller.auth.kakaoResolveAccount({
|
||||
oauthSessionId: result.oauthSessionId,
|
||||
action: 'link_existing',
|
||||
});
|
||||
}
|
||||
if (legacy) {
|
||||
if (result.status !== 'password_setup') throw new Error('Expected migrated password setup.');
|
||||
result = await f.caller.auth.kakaoSetPassword({
|
||||
oauthSessionId: result.oauthSessionId,
|
||||
credential: f.sealPassword('restoredpass'),
|
||||
});
|
||||
}
|
||||
if (result.status !== 'otp') throw new Error('Expected OTP proof.');
|
||||
expect((await f.users.findById(user.id))?.deleteAfter).toBeDefined();
|
||||
const code = f.sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||
const verified = await f.caller.auth.kakaoOtp({ challengeId: result.challengeId, code: code! });
|
||||
if (verified.status !== 'deletion_pending') throw new Error('Expected deletion confirmation.');
|
||||
expect(verified).not.toHaveProperty('sessionToken');
|
||||
expect((await f.users.findById(user.id))?.deleteAfter).toBeDefined();
|
||||
expect((await f.caller.auth.cancelDeletion({ recoveryId: verified.recoveryId })).status).toBe('login');
|
||||
}
|
||||
);
|
||||
|
||||
it('applies the pre-July legacy request exception at the exact Korean-time boundary', async () => {
|
||||
const f = buildCaller();
|
||||
const user = await f.users.createUser({ username: 'legacy-recover', password: 'secretpass' });
|
||||
user.legacyMemberNo = 42;
|
||||
const cutoffDeadline = new Date('2026-07-31T00:00:00+09:00');
|
||||
await f.users.scheduleDeletion(user.id, new Date(cutoffDeadline.getTime() - 1));
|
||||
const legacy = await f.users.findById(user.id);
|
||||
expect(canCancelDeletion(legacy!, new Date('2026-11-07'))).toBe(true);
|
||||
const result = await f.caller.auth.login({ username: user.username, credential: f.sealPassword('secretpass') });
|
||||
if (result.status !== 'deletion_pending') throw new Error('Expected legacy restoration.');
|
||||
await f.caller.auth.cancelDeletion({ recoveryId: result.recoveryId });
|
||||
await f.users.scheduleDeletion(user.id, cutoffDeadline);
|
||||
await expect(
|
||||
f.caller.auth.login({ username: user.username, credential: f.sealPassword('secretpass') })
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
expect(canCancelDeletion({ ...legacy!, legacyMemberNo: undefined }, new Date('2026-11-07'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('staged Kakao self recovery', () => {
|
||||
const prepare = async (
|
||||
options: { differentEmail?: boolean; resetPassword?: boolean; privileged?: boolean } = {}
|
||||
) => {
|
||||
const f = buildCaller({
|
||||
kakaoId: 'new-self-kakao',
|
||||
kakaoEmail: options.differentEmail ? 'new@example.test' : 'owner@example.test',
|
||||
});
|
||||
const user = await f.users.createUser({
|
||||
username: 'self-recover',
|
||||
password: 'originalpass',
|
||||
oauth: { type: 'KAKAO', id: 'old-self-kakao', email: 'owner@example.test', info: {} },
|
||||
});
|
||||
if (options.privileged) await f.users.updateRoles(user.id, ['admin']);
|
||||
user.passwordResetRequired = options.resetPassword ?? false;
|
||||
user.kakaoTalkVerifiedUntil = new Date(Date.now() + 86400000).toISOString();
|
||||
const old = await f.sessions.createSession(user);
|
||||
const start = await f.caller.auth.kakaoStart({ mode: 'login' });
|
||||
const choice = await f.caller.auth.kakaoExchange({ code: 'code', state: start.state });
|
||||
return { ...f, user, old, choice };
|
||||
};
|
||||
const otpCode = (f: { sentTalkMessages: string[] }): string =>
|
||||
f.sentTalkMessages.at(-1)!.match(/인증 코드는 (\d{4})/)![1]!;
|
||||
|
||||
it('recovers an ordinary matching-email account without approval and only commits after fresh OTP', async () => {
|
||||
const f = await prepare();
|
||||
if (f.choice.status !== 'account_recovery') throw new Error('Expected confirmation.');
|
||||
const oldChallenge = await f.oauthSessions.createLoginChallenge({
|
||||
userId: f.user.id,
|
||||
code: '1111',
|
||||
attemptsRemaining: 3,
|
||||
expiresAt: new Date(Date.now() + 180000).toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
authRevision: 0,
|
||||
oauthId: 'old-self-kakao',
|
||||
});
|
||||
const otp = await f.caller.auth.kakaoResolveAccount({
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
action: 'link_existing',
|
||||
});
|
||||
if (otp.status !== 'otp') throw new Error('Expected fresh OTP despite a cached proof.');
|
||||
expect((await f.users.findById(f.user.id))?.oauthId).toBe('old-self-kakao');
|
||||
expect(await f.caller.auth.me({ sessionToken: f.old.sessionToken })).not.toBeNull();
|
||||
expect(await f.users.findDetachedKakaoOwner('old-self-kakao')).toBeNull();
|
||||
await expect(f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: '0000' })).rejects.toBeDefined();
|
||||
expect((await f.users.findById(f.user.id))?.oauthId).toBe('old-self-kakao');
|
||||
expect((await f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: otpCode(f) })).status).toBe('login');
|
||||
expect(await f.caller.auth.me({ sessionToken: f.old.sessionToken })).toBeNull();
|
||||
await expect(f.caller.auth.kakaoOtp({ challengeId: oldChallenge.id, code: '1111' })).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
});
|
||||
expect(await f.users.findDetachedKakaoOwner('old-self-kakao')).toBe(f.user.id);
|
||||
expect(await f.users.isKakaoIdentityRetired('old-self-kakao')).toBe(false);
|
||||
await expect(f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: otpCode(f) })).rejects.toBeDefined();
|
||||
f.kakaoProfile.id = 'old-self-kakao';
|
||||
const start = await f.caller.auth.kakaoStart({ mode: 'login' });
|
||||
const choice = await f.caller.auth.kakaoExchange({ code: 'code', state: start.state });
|
||||
if (choice.status !== 'account_recovery') throw new Error('Expected same-owner recovery.');
|
||||
const back = await f.caller.auth.kakaoResolveAccount({
|
||||
oauthSessionId: choice.oauthSessionId,
|
||||
action: 'link_existing',
|
||||
});
|
||||
if (back.status !== 'otp') throw new Error('Expected OTP.');
|
||||
await f.caller.auth.kakaoOtp({ challengeId: back.challengeId, code: otpCode(f) });
|
||||
expect((await f.users.findById(f.user.id))?.oauthId).toBe('old-self-kakao');
|
||||
await expect(
|
||||
f.users.createUser({
|
||||
username: 'claim-other',
|
||||
password: 'secretpass',
|
||||
oauth: { type: 'KAKAO', id: 'new-self-kakao', email: 'other@example.test', info: {} },
|
||||
})
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('accepts the old password for a different email, keeps retries possible and verifies new talk ownership', async () => {
|
||||
const f = await prepare({ differentEmail: true });
|
||||
if (f.choice.status !== 'join') throw new Error('Expected no email match.');
|
||||
await expect(
|
||||
f.caller.auth.kakaoLinkWithPassword({
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
username: f.user.username,
|
||||
credential: f.sealPassword('wrongpass'),
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
||||
const otp = await f.caller.auth.kakaoLinkWithPassword({
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
username: f.user.username,
|
||||
credential: f.sealPassword('originalpass'),
|
||||
});
|
||||
if (otp.status !== 'otp') throw new Error('Expected OTP.');
|
||||
expect((await f.users.findById(f.user.id))?.email).toBe('owner@example.test');
|
||||
await f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: otpCode(f) });
|
||||
expect(await f.users.findById(f.user.id)).toMatchObject({
|
||||
oauthId: 'new-self-kakao',
|
||||
email: 'new@example.test',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps migrated passwords and old identities intact until the final OTP commit', async () => {
|
||||
const f = await prepare({ resetPassword: true });
|
||||
if (f.choice.status !== 'account_recovery') throw new Error('Expected recovery.');
|
||||
const setup = await f.caller.auth.kakaoResolveAccount({
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
action: 'link_existing',
|
||||
});
|
||||
if (setup.status !== 'password_setup') throw new Error('Expected password setup.');
|
||||
const hash = f.user.passwordHash;
|
||||
const otp = await f.caller.auth.kakaoSetPassword({
|
||||
oauthSessionId: setup.oauthSessionId,
|
||||
credential: f.sealPassword('new-valid-pass'),
|
||||
});
|
||||
if (otp.status !== 'otp') throw new Error('Expected OTP.');
|
||||
expect(f.user.passwordHash).toBe(hash);
|
||||
expect(f.user.passwordResetRequired).toBe(true);
|
||||
await f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: otpCode(f) });
|
||||
expect(f.user.passwordResetRequired).toBe(false);
|
||||
expect(await f.users.verifyPassword(f.user, 'new-valid-pass')).toBe(true);
|
||||
});
|
||||
|
||||
it('still requires approval for privileged accounts even with the password', async () => {
|
||||
const f = await prepare({ privileged: true });
|
||||
if (f.choice.status !== 'account_recovery') throw new Error('Expected recovery.');
|
||||
await expect(
|
||||
f.caller.auth.kakaoLinkWithPassword({
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
username: f.user.username,
|
||||
credential: f.sealPassword('originalpass'),
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
|
||||
expect(f.user.oauthId).toBe('old-self-kakao');
|
||||
});
|
||||
|
||||
it.each(['roles', 'password', 'sanction', 'identity', 'expired', 'provider'] as const)(
|
||||
'does not commit if %s changes during OTP',
|
||||
async (change) => {
|
||||
const f = await prepare();
|
||||
if (f.choice.status !== 'account_recovery') throw new Error('Expected recovery.');
|
||||
const otp = await f.caller.auth.kakaoResolveAccount({
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
action: 'link_existing',
|
||||
});
|
||||
if (otp.status !== 'otp') throw new Error('Expected OTP.');
|
||||
if (change === 'roles') await f.users.updateRoles(f.user.id, ['admin']);
|
||||
if (change === 'password') await f.users.updatePassword(f.user.id, 'changed-elsewhere');
|
||||
if (change === 'sanction')
|
||||
await f.users.updateSanctions(f.user.id, {
|
||||
bannedUntil: new Date(Date.now() + 86400000).toISOString(),
|
||||
});
|
||||
if (change === 'identity') f.user.authRevision = 1;
|
||||
if (change === 'expired') {
|
||||
const challenge = await f.oauthSessions.getLoginChallengeForUser(f.user.id);
|
||||
const pending = await f.oauthSessions.getSession(challenge!.oauthSessionId!);
|
||||
pending!.createdAt = new Date(Date.now() - 301000).toISOString();
|
||||
}
|
||||
if (change === 'provider') f.kakaoProfile.id = 'another-kakao';
|
||||
await expect(
|
||||
f.caller.auth.kakaoOtp({ challengeId: otp.challengeId, code: otpCode(f) })
|
||||
).rejects.toBeDefined();
|
||||
expect(f.user.oauthId).toBe('old-self-kakao');
|
||||
expect(await f.users.findDetachedKakaoOwner('old-self-kakao')).toBeNull();
|
||||
}
|
||||
);
|
||||
|
||||
it('does not change any identity when sending the new talk challenge fails', async () => {
|
||||
const f = await prepare();
|
||||
if (f.choice.status !== 'account_recovery') throw new Error('Expected recovery.');
|
||||
vi.spyOn(f.kakaoClient, 'sendTalkMessage').mockRejectedValue(new Error('synthetic provider failure'));
|
||||
await expect(
|
||||
f.caller.auth.kakaoResolveAccount({ oauthSessionId: f.choice.oauthSessionId, action: 'link_existing' })
|
||||
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED', message: '카카오톡 인증 코드를 보내지 못했습니다.' });
|
||||
expect(f.user.oauthId).toBe('old-self-kakao');
|
||||
expect(await f.caller.auth.me({ sessionToken: f.old.sessionToken })).not.toBeNull();
|
||||
});
|
||||
|
||||
it('checks password-based recovery over real HTTP before issuing the new challenge', async () => {
|
||||
const f = await prepare({ differentEmail: true });
|
||||
if (f.choice.status !== 'join') throw new Error('Expected join fallback.');
|
||||
const app = fastify();
|
||||
await app.register(fastifyTRPCPlugin, {
|
||||
prefix: '/gateway/api/trpc',
|
||||
trpcOptions: { router: appRouter, ...trpcJsonBodyHttpServerOptions, createContext: () => f.context },
|
||||
});
|
||||
try {
|
||||
const address = await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const post = (name: string, input: object) =>
|
||||
fetch(`${address}/gateway/api/trpc/${name}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await post('auth.kakaoLinkWithPassword', {
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
username: f.user.username,
|
||||
credential: f.sealPassword('incorrect'),
|
||||
})
|
||||
).status
|
||||
).toBe(401);
|
||||
expect(
|
||||
(
|
||||
await post('auth.kakaoLinkWithPassword', {
|
||||
oauthSessionId: 'invalid',
|
||||
username: f.user.username,
|
||||
credential: f.sealPassword('originalpass'),
|
||||
})
|
||||
).status
|
||||
).toBe(400);
|
||||
const response = await post('auth.kakaoLinkWithPassword', {
|
||||
oauthSessionId: f.choice.oauthSessionId,
|
||||
username: f.user.username,
|
||||
credential: f.sealPassword('originalpass'),
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
const data = (await response.json()) as { result: { data: { status: string; challengeId: string } } };
|
||||
expect(data.result.data.status).toBe('otp');
|
||||
expect(f.user.oauthId).toBe('old-self-kakao');
|
||||
expect(
|
||||
(await post('auth.kakaoOtp', { challengeId: data.result.data.challengeId, code: otpCode(f) })).status
|
||||
).toBe(200);
|
||||
expect(f.user.oauthId).toBe('new-self-kakao');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -82,6 +82,56 @@ describe.skipIf(!redisUrl)('RedisOAuthSessionStore Kakao state', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('consumes an isolated deletion proof once with a five-minute TTL', async () => {
|
||||
const recovery = await store.createDeletionRecovery({
|
||||
userId: randomUUID(),
|
||||
deleteAfter: new Date().toISOString(),
|
||||
authRevision: 2,
|
||||
expiresAt: new Date(Date.now() + 300000).toISOString(),
|
||||
});
|
||||
const key = `${prefix}:deletion-recovery:${recovery.id}`;
|
||||
try {
|
||||
expect(await client.ttl(key)).toBeGreaterThan(0);
|
||||
expect(await client.ttl(key)).toBeLessThanOrEqual(300);
|
||||
const results = await Promise.all([
|
||||
store.consumeDeletionRecovery(recovery.id),
|
||||
store.consumeDeletionRecovery(recovery.id),
|
||||
]);
|
||||
expect(results.filter(Boolean)).toEqual([recovery]);
|
||||
expect(await store.consumeSession(recovery.id)).toBeNull();
|
||||
} finally {
|
||||
await client.del(key);
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves the exact pending OAuth session and old identity revision in a one-use challenge', async () => {
|
||||
const challenge = await store.createLoginChallenge({
|
||||
userId: randomUUID(),
|
||||
code: '1234',
|
||||
attemptsRemaining: 3,
|
||||
expiresAt: new Date(Date.now() + 180000).toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
oauthSessionId: randomUUID(),
|
||||
authRevision: 7,
|
||||
oauthId: 'identity-before-change',
|
||||
});
|
||||
userIds.add(challenge.userId);
|
||||
challengeIds.add(challenge.id);
|
||||
const results = await Promise.all([
|
||||
store.verifyLoginChallenge(challenge.id, '1234'),
|
||||
store.verifyLoginChallenge(challenge.id, '1234'),
|
||||
]);
|
||||
expect(results.filter((r) => r.status === 'verified')).toEqual([
|
||||
{
|
||||
status: 'verified',
|
||||
userId: challenge.userId,
|
||||
oauthSessionId: challenge.oauthSessionId,
|
||||
authRevision: 7,
|
||||
oauthId: 'identity-before-change',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('atomically consumes a successful code once', async () => {
|
||||
const challenge = await createChallenge();
|
||||
|
||||
|
||||
@@ -38,8 +38,8 @@ describe('readReleaseManifest', () => {
|
||||
|
||||
await expect(readReleaseManifest(workspaceRoot)).resolves.toMatchObject({
|
||||
controllerProtocol: RELEASE_CONTROLLER_PROTOCOL,
|
||||
gatewaySchemaHead: '20261022000000_add_open_requests',
|
||||
gameSchemaHead: '20260916080000_index_play_audit_decision_month',
|
||||
gatewaySchemaHead: '20261107000000_kakao_identity_link_history',
|
||||
gameSchemaHead: '20261114020000_reserved_turn_slot_primary_keys',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { generateKeyPairSync } from 'node:crypto';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
|
||||
const { publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
|
||||
const pending = {
|
||||
status: 'deletion_pending',
|
||||
recoveryId: '11111111-1111-4111-8111-111111111111',
|
||||
deleteAfter: '2026-07-30T14:59:59.999Z',
|
||||
};
|
||||
const otp = {
|
||||
status: 'otp',
|
||||
successStatus: 'login',
|
||||
challengeId: '22222222-2222-4222-8222-222222222222',
|
||||
expiresAt: '2026-11-07T12:00:00Z',
|
||||
attemptsRemaining: 3,
|
||||
};
|
||||
const installFixture = async (page: Page, entry: 'password' | 'kakao' | 'kakao-link', fail = false) => {
|
||||
const calls: string[] = [];
|
||||
let restored = false;
|
||||
let complete: (() => void) | undefined;
|
||||
await page.route('**/gateway/api/trpc/**', async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const names = decodeURIComponent(url.pathname.split('/trpc/')[1]!).split(',');
|
||||
const results = [];
|
||||
for (const name of names) {
|
||||
calls.push(name);
|
||||
let data: unknown;
|
||||
if (name === 'me')
|
||||
data = restored
|
||||
? {
|
||||
id: 'fixture-user',
|
||||
username: 'fixture-user',
|
||||
displayName: '복구계정',
|
||||
roles: ['user'],
|
||||
kakaoVerified: true,
|
||||
}
|
||||
: null;
|
||||
else if (name === 'lobby.profiles') data = [];
|
||||
else if (name === 'lobby.notice') data = '';
|
||||
else if (name === 'auth.passwordKey')
|
||||
data = { keyId: 'fixture-key', publicKeyPem, algorithm: 'RSA-OAEP-256' };
|
||||
else if (name === 'auth.login') data = pending;
|
||||
else if (name === 'auth.kakaoExchange')
|
||||
data =
|
||||
entry === 'kakao-link'
|
||||
? {
|
||||
status: 'account_recovery',
|
||||
action: 'link_existing',
|
||||
oauthSessionId: 'fixture-link-session',
|
||||
email: 'retained@example.test',
|
||||
}
|
||||
: pending;
|
||||
else if (name === 'auth.kakaoResolveAccount') data = otp;
|
||||
else if (name === 'auth.kakaoOtp') data = { ...pending, validUntil: '2026-11-08T12:00:00Z' };
|
||||
else if (name === 'auth.cancelDeletion') {
|
||||
const input = route.request().postDataJSON() as Record<string, { recoveryId: string }>;
|
||||
expect(Object.values(input)).toEqual([{ recoveryId: pending.recoveryId }]);
|
||||
await new Promise<void>((resolve) => {
|
||||
complete = resolve;
|
||||
});
|
||||
if (fail) {
|
||||
results.push({
|
||||
error: {
|
||||
message: '복구 인증이 만료되었습니다. 다시 로그인해 주세요.',
|
||||
code: -32001,
|
||||
data: { code: 'UNAUTHORIZED', httpStatus: 401 },
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
restored = true;
|
||||
data = {
|
||||
status: 'login',
|
||||
sessionToken: 'fixture-restored-session',
|
||||
user: { id: 'fixture-user' },
|
||||
issuedAt: '2026-11-07T12:00:00Z',
|
||||
};
|
||||
} else throw new Error(`Unhandled recovery operation: ${name}`);
|
||||
results.push({ result: { data } });
|
||||
}
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(results) });
|
||||
});
|
||||
return {
|
||||
calls,
|
||||
complete: () => {
|
||||
expect(complete).toBeDefined();
|
||||
complete!();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1200, height: 900 },
|
||||
{ name: 'mobile', width: 390, height: 844 },
|
||||
]) {
|
||||
for (const entry of ['password', 'kakao', 'kakao-link'] as const) {
|
||||
test(`restores a pending account through ${entry} on ${viewport.name}`, async ({ page }, testInfo) => {
|
||||
await page.setViewportSize(viewport);
|
||||
const f = await installFixture(page, entry);
|
||||
await page.goto(
|
||||
entry === 'password' ? '/gateway/' : '/gateway/oauth/callback?code=fixture-code&state=fixture-state'
|
||||
);
|
||||
if (entry === 'password') {
|
||||
await page.getByLabel('계정명', { exact: true }).fill('fixture-user');
|
||||
await page.getByLabel('비밀번호', { exact: true }).fill('fixture-password');
|
||||
await page.getByRole('button', { name: '로그인', exact: true }).click();
|
||||
}
|
||||
if (entry === 'kakao-link') {
|
||||
await expect(page.getByRole('group', { name: '카카오 계정 연결 확인' })).toBeVisible();
|
||||
await page.getByRole('button', { name: '기존 계정에 연결' }).click();
|
||||
const dialog = page.getByRole('dialog', { name: '인증 코드 필요' });
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.locator('input').fill('1234');
|
||||
await dialog.getByRole('button', { name: '제출', exact: true }).click();
|
||||
}
|
||||
const panel = page.getByRole('group', { name: '탈퇴 취소', exact: true });
|
||||
await expect(panel).toBeVisible();
|
||||
expect(f.calls).not.toContain('auth.cancelDeletion');
|
||||
expect(await page.evaluate(() => localStorage.getItem('sammo-session-token'))).toBeNull();
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
const geometry = await panel.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
x: rect.x,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
textAlign: style.textAlign,
|
||||
fontSize: style.fontSize,
|
||||
html: element.outerHTML,
|
||||
};
|
||||
});
|
||||
expect(geometry.x).toBeGreaterThanOrEqual(0);
|
||||
expect(geometry.width).toBeLessThan(viewport.width);
|
||||
expect(geometry.textAlign).toBe('center');
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(viewport.width);
|
||||
const button = panel.getByRole('button', { name: '탈퇴 취소', exact: true });
|
||||
await button.hover();
|
||||
expect(await button.evaluate((el) => getComputedStyle(el).backgroundColor)).toBe('rgb(47, 77, 108)');
|
||||
await page.mouse.down();
|
||||
expect(await button.evaluate((el) => el.matches(':active'))).toBe(true);
|
||||
await page.mouse.move(0, 0);
|
||||
await page.mouse.up();
|
||||
await button.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(button).toBeFocused();
|
||||
expect(await button.evaluate((el) => getComputedStyle(el).outlineStyle)).toBe('solid');
|
||||
await writeFile(testInfo.outputPath('panel-dom-geometry-style.json'), JSON.stringify(geometry, null, 2));
|
||||
await writeFile(testInfo.outputPath('panel.html'), geometry.html);
|
||||
await testInfo.attach('panel-dom-geometry-style', {
|
||||
body: JSON.stringify(geometry, null, 2),
|
||||
contentType: 'application/json',
|
||||
});
|
||||
await page.screenshot({ path: testInfo.outputPath('deletion-confirmation.png'), fullPage: true });
|
||||
await button.click();
|
||||
await expect(panel.getByRole('button', { name: '처리 중...' })).toBeDisabled();
|
||||
await expect(panel.getByRole('button', { name: '돌아가기' })).toBeDisabled();
|
||||
await expect.poll(() => f.calls.filter((call) => call === 'auth.cancelDeletion').length).toBe(1);
|
||||
f.complete();
|
||||
await expect(page).toHaveURL(/\/gateway\/lobby$/);
|
||||
expect(await page.evaluate(() => localStorage.getItem('sammo-session-token'))).toBe(
|
||||
'fixture-restored-session'
|
||||
);
|
||||
await page.reload();
|
||||
await expect(page).toHaveURL(/\/gateway\/lobby$/);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('keeps deletion unchanged when leaving confirmation or when recovery expires', async ({ page }) => {
|
||||
const f = await installFixture(page, 'kakao', true);
|
||||
await page.goto('/gateway/oauth/callback?code=fixture-code&state=fixture-state');
|
||||
const panel = page.getByRole('group', { name: '탈퇴 취소', exact: true });
|
||||
await panel.getByRole('button', { name: '돌아가기' }).click();
|
||||
await expect(page).toHaveURL(/\/gateway\/$/);
|
||||
expect(f.calls).not.toContain('auth.cancelDeletion');
|
||||
await page.goto('/gateway/oauth/callback?code=fixture-code&state=fixture-state');
|
||||
await panel.getByRole('button', { name: '탈퇴 취소' }).click();
|
||||
await expect.poll(() => f.calls.filter((call) => call === 'auth.cancelDeletion').length).toBe(1);
|
||||
f.complete();
|
||||
await expect(panel.getByRole('alert')).toContainText('다시 로그인');
|
||||
expect(await page.evaluate(() => localStorage.getItem('sammo-session-token'))).toBeNull();
|
||||
});
|
||||
@@ -7,7 +7,7 @@ const operationNames = (route: Route): string[] => {
|
||||
return decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/trpc/') + 6)).split(',');
|
||||
};
|
||||
|
||||
const installFixture = async (page: Page) => {
|
||||
const installFixture = async (page: Page, approved = true) => {
|
||||
const requests: Array<{ operation: string; body: string }> = [];
|
||||
await page.addInitScript(() => {
|
||||
window.localStorage.setItem('sammo-session-token', 'kakao-replacement-session');
|
||||
@@ -33,7 +33,7 @@ const installFixture = async (page: Page) => {
|
||||
nextRetireAt: null,
|
||||
thirdPartyUse: false,
|
||||
deleteAfter: null,
|
||||
kakaoReplacementApprovedUntil: new Date(Date.now() + 86_400_000).toISOString(),
|
||||
kakaoReplacementApprovedUntil: approved ? new Date(Date.now() + 86_400_000).toISOString() : null,
|
||||
});
|
||||
}
|
||||
if (operation === 'account.notifications.get') {
|
||||
@@ -63,7 +63,7 @@ const installFixture = async (page: Page) => {
|
||||
return requests;
|
||||
};
|
||||
|
||||
test('starts an approved Kakao replacement with explicit permanent-retirement confirmation', async ({
|
||||
test('starts a Kakao replacement with confirmation before authenticating the new account', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const requests = await installFixture(page);
|
||||
@@ -88,7 +88,7 @@ test('starts an approved Kakao replacement with explicit permanent-retirement co
|
||||
|
||||
await button.click();
|
||||
await expect(page).toHaveURL(/replacement=started/);
|
||||
expect(confirmation).toContain('기존 카카오 계정은 영구 폐기');
|
||||
expect(confirmation).toContain('새 카카오톡 인증을 완료하면');
|
||||
const startRequest = requests.find(({ operation }) => operation === 'auth.kakaoStart');
|
||||
expect(startRequest?.body).toContain('verify');
|
||||
expect(startRequest?.body).toContain('kakao-replacement-session');
|
||||
@@ -105,3 +105,13 @@ test('starts an approved Kakao replacement with explicit permanent-retirement co
|
||||
await writeFile(testInfo.outputPath('account-kakao-replacement-mobile-geometry.json'), JSON.stringify(geometry));
|
||||
await page.screenshot({ path: testInfo.outputPath('account-kakao-replacement-mobile.png'), fullPage: true });
|
||||
});
|
||||
|
||||
test('offers ordinary users account replacement without an administrator approval', async ({ page }) => {
|
||||
const requests = await installFixture(page, false);
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
await page.goto('account');
|
||||
await expect(page.getByText(/교체 승인 .*까지/)).toHaveCount(0);
|
||||
await page.getByRole('button', { name: '새 카카오 계정으로 교체', exact: true }).click();
|
||||
await expect(page).toHaveURL(/replacement=started/);
|
||||
expect(requests.some(({ operation }) => operation === 'auth.kakaoStart')).toBe(true);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { formatRoleGroups } from '../src/utils/roleDisplay';
|
||||
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
const operationNames = (route: Route): string[] => {
|
||||
@@ -7,9 +8,24 @@ const operationNames = (route: Route): string[] => {
|
||||
return decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/trpc/') + 6)).split(',');
|
||||
};
|
||||
|
||||
const installFixture = async (page: Page) => {
|
||||
const installFixture = async (
|
||||
page: Page,
|
||||
scopes = ['*'],
|
||||
deletion: {
|
||||
deleteAfter?: string;
|
||||
cancelFails?: boolean;
|
||||
flushPublished?: boolean;
|
||||
beforeCancel?: () => Promise<void>;
|
||||
} = {}
|
||||
) => {
|
||||
const requests: Array<{ operation: string; body: unknown }> = [];
|
||||
let deleteAfter: string | null = null;
|
||||
let roles = [
|
||||
'user',
|
||||
'admin.profiles.runtime:che:default',
|
||||
'admin.profiles.runtime:kwe:default',
|
||||
'admin.profiles.runtime:pwe:default',
|
||||
];
|
||||
let deleteAfter: string | null = deletion.deleteAfter ?? null;
|
||||
let graceUntil: string | null = null;
|
||||
let username = 'target';
|
||||
let displayName = '대상 사용자';
|
||||
@@ -33,8 +49,9 @@ const installFixture = async (page: Page) => {
|
||||
await page.route('**/gateway/api/trpc/**', async (route) => {
|
||||
const operations = operationNames(route);
|
||||
const body = route.request().postDataJSON() as unknown;
|
||||
for (const operation of operations) requests.push({ operation, body });
|
||||
if (operations.includes('admin.users.cancelDeletion')) await deletion.beforeCancel?.();
|
||||
const results = operations.map((operation) => {
|
||||
requests.push({ operation, body });
|
||||
if (operation === 'me') {
|
||||
return response({
|
||||
id: 'admin-user',
|
||||
@@ -59,6 +76,7 @@ const installFixture = async (page: Page) => {
|
||||
description: '지정 profile의 시작, 정지와 실행 상태를 관리합니다.',
|
||||
risk: 'HIGH',
|
||||
scope: 'PROFILE',
|
||||
scopes,
|
||||
},
|
||||
{
|
||||
permission: 'admin.audit.read',
|
||||
@@ -70,6 +88,15 @@ const installFixture = async (page: Page) => {
|
||||
]);
|
||||
}
|
||||
if (operation === 'admin.audit.list') return response(auditHistory);
|
||||
if (operation === 'account.notifications.get')
|
||||
return response({
|
||||
capability: { enabled: false, publicKey: null },
|
||||
eventTypes: [],
|
||||
profiles: [],
|
||||
preferences: [],
|
||||
subscriptionCount: 0,
|
||||
currentDeviceSubscribed: false,
|
||||
});
|
||||
if (operation === 'admin.users.getLocalAccountStatus') return response({ enabled: false });
|
||||
if (operation === 'admin.users.list') {
|
||||
return response({
|
||||
@@ -111,12 +138,20 @@ const installFixture = async (page: Page) => {
|
||||
if (operation === 'admin.profiles.listNavigation') return response([]);
|
||||
if (operation === 'admin.profiles.list') return response([]);
|
||||
if (operation === 'admin.profiles.listScenarios') return response([]);
|
||||
if (operation === 'admin.users.updateRoles') {
|
||||
const input = (body as Record<string, { roles: string[]; mode: string }>)['0'];
|
||||
roles =
|
||||
input.mode === 'grant'
|
||||
? [...new Set([...roles, ...input.roles])]
|
||||
: roles.filter((role) => !input.roles.includes(role));
|
||||
return response({ roles });
|
||||
}
|
||||
if (operation === 'admin.users.lookup') {
|
||||
return response({
|
||||
id: 'target-user',
|
||||
username,
|
||||
displayName,
|
||||
roles: ['user'],
|
||||
roles,
|
||||
sanctions: {},
|
||||
oauthType: 'KAKAO',
|
||||
oauthId: 'fixture-kakao-stable-id',
|
||||
@@ -222,6 +257,25 @@ const installFixture = async (page: Page) => {
|
||||
});
|
||||
return response({ ok: true, deleteAfter });
|
||||
}
|
||||
if (operation === 'admin.users.cancelDeletion') {
|
||||
if (deletion.cancelFails)
|
||||
return {
|
||||
error: {
|
||||
message: '계정 상태가 변경되었습니다. 다시 조회해 주세요.',
|
||||
code: -32009,
|
||||
data: { code: 'CONFLICT', httpStatus: 409 },
|
||||
},
|
||||
};
|
||||
deleteAfter = null;
|
||||
const input = (body as Record<string, { reason: string }>)['0'];
|
||||
auditHistory.unshift({
|
||||
...auditHistory[0],
|
||||
id: 'audit-cancel-deletion',
|
||||
action: 'admin.users.cancelDeletion',
|
||||
reason: input.reason,
|
||||
});
|
||||
return response({ ok: true, deleteAfter: null, flushPublished: deletion.flushPublished ?? true });
|
||||
}
|
||||
throw new Error(`Unhandled tRPC operation: ${operation}`);
|
||||
});
|
||||
const isBatch = new URL(route.request().url()).searchParams.get('batch') === '1';
|
||||
@@ -329,3 +383,276 @@ test('operates OAuth grace and scheduled deletion with reasoned audit history',
|
||||
);
|
||||
await page.screenshot({ path: testInfo.outputPath('gateway-admin-account-controls-mobile.png'), fullPage: true });
|
||||
});
|
||||
|
||||
for (const width of [1365, 390]) {
|
||||
test(`groups server roles and applies all-server action at ${width}px`, async ({ page }, testInfo) => {
|
||||
const requests = await installFixture(page);
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.goto('admin/users');
|
||||
await page.getByRole('button', { name: /target.*대상 사용자/ }).click();
|
||||
const summary = page.getByLabel('보유 권한');
|
||||
await expect(summary).toContainText('admin.profiles.runtime:{che, kwe, pwe}:default');
|
||||
await page.getByRole('button', { name: /접근 · 권한/ }).click();
|
||||
await page.getByLabel('관리 기능 권한').selectOption('admin.profiles.runtime');
|
||||
const server = page.getByLabel('권한 대상 서버');
|
||||
await server.selectOption('*');
|
||||
await expect(server).toHaveValue('*');
|
||||
await expect(page.getByText(/선택한 행동만 현재와 앞으로 추가되는 모든 서버에 허용/)).toBeVisible();
|
||||
await server.focus();
|
||||
await server.click();
|
||||
await page.screenshot({ path: testInfo.outputPath('all-servers-selected.png'), fullPage: true });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.getByRole('button', { name: '선택 반영', exact: true }).click();
|
||||
const input = page.getByPlaceholder('admin, moderator 등');
|
||||
await expect(input).toHaveValue('admin.profiles.runtime:*');
|
||||
await page.getByPlaceholder('권한·제재·복구·탈퇴 조치 사유 (필수)').fill('모든 서버 실행 관리 허용');
|
||||
const apply = page.getByRole('button', { name: '적용', exact: true });
|
||||
await apply.hover();
|
||||
await apply.focus();
|
||||
await expect(apply).toBeFocused();
|
||||
await apply.click();
|
||||
await expect(summary).toContainText('admin.profiles.runtime:* (모든 서버)');
|
||||
const update = requests.find(({ operation }) => operation === 'admin.users.updateRoles');
|
||||
expect(update?.body).toMatchObject({
|
||||
'0': { roles: ['admin.profiles.runtime:*'], mode: 'grant' },
|
||||
});
|
||||
// 전역 기능은 서버 선택이 없고, 다른 서버로 범위를 암묵적으로 옮기지 않는다.
|
||||
await page.getByLabel('관리 기능 권한').selectOption('admin.users.manage');
|
||||
await expect(server).toHaveCount(0);
|
||||
await page.getByLabel('관리 기능 권한').selectOption('admin.profiles.runtime');
|
||||
await expect(server).toHaveValue('');
|
||||
await page.getByRole('button', { name: '선택 반영', exact: true }).click();
|
||||
await expect(page.getByText('대상 서버를 선택하세요.', { exact: true }).first()).toBeVisible();
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
const geometry = await summary.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
left: rect.left,
|
||||
right: rect.right,
|
||||
width: rect.width,
|
||||
viewportWidth: innerWidth,
|
||||
overflowWrap: style.overflowWrap,
|
||||
documentOverflow: document.documentElement.scrollWidth - innerWidth,
|
||||
text: element.textContent,
|
||||
};
|
||||
});
|
||||
await writeFile(testInfo.outputPath('permission-geometry.json'), JSON.stringify(geometry, null, 2));
|
||||
expect(geometry.right).toBeLessThanOrEqual(width);
|
||||
expect(geometry.documentOverflow).toBe(0);
|
||||
await writeFile(testInfo.outputPath('permissions.html'), await page.content());
|
||||
await page.screenshot({ path: testInfo.outputPath('permissions.png'), fullPage: true });
|
||||
});
|
||||
}
|
||||
|
||||
test('limits the server selector to the administrators own action scope', async ({ page }) => {
|
||||
await installFixture(page, ['che:default']);
|
||||
await page.goto('admin/users');
|
||||
await page.getByRole('button', { name: /target.*대상 사용자/ }).click();
|
||||
await page.getByRole('button', { name: /접근 · 권한/ }).click();
|
||||
await page.getByLabel('관리 기능 권한').selectOption('admin.profiles.runtime');
|
||||
const server = page.getByLabel('권한 대상 서버');
|
||||
await expect(server.locator('option[value="*"]')).toHaveCount(0);
|
||||
await server.selectOption('che:default');
|
||||
await page.getByRole('button', { name: '선택 반영', exact: true }).click();
|
||||
await expect(page.getByPlaceholder('admin, moderator 등')).toHaveValue('admin.profiles.runtime:che:default');
|
||||
});
|
||||
|
||||
test('keeps action and instance boundaries when formatting explicit grants', () => {
|
||||
const roles = [
|
||||
'user',
|
||||
'admin.profiles.runtime:che:default',
|
||||
'admin.profiles.runtime:kwe:default',
|
||||
'admin.profiles.runtime:che:season2',
|
||||
'admin.profiles.runtime:hwe:season2',
|
||||
'admin.playAudit.read:che:default',
|
||||
'admin.playAudit.accounts',
|
||||
'admin.profiles.deploy',
|
||||
'admin.profiles.deploy:*',
|
||||
];
|
||||
expect(formatRoleGroups(roles)).toEqual([
|
||||
'user',
|
||||
'admin.profiles.runtime:{che, kwe}:default',
|
||||
'admin.profiles.runtime:{che, hwe}:season2',
|
||||
'admin.playAudit.read:che:default',
|
||||
'admin.playAudit.accounts',
|
||||
'admin.profiles.deploy',
|
||||
'admin.profiles.deploy:* (모든 서버)',
|
||||
]);
|
||||
expect(roles[1]).toBe('admin.profiles.runtime:che:default');
|
||||
expect(formatRoleGroups([])).toEqual([]);
|
||||
});
|
||||
|
||||
test('shows grouped roles on the account page after direct navigation and refresh', async ({ page }, testInfo) => {
|
||||
await installFixture(page);
|
||||
let showGroupedRoles = false;
|
||||
await page.route('**/gateway/api/trpc/account.get*', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify([
|
||||
response({
|
||||
id: 'target-user',
|
||||
username: 'target',
|
||||
displayName: '대상 사용자',
|
||||
roles: showGroupedRoles
|
||||
? [
|
||||
'user',
|
||||
...['che', 'kwe', 'pwe', 'hwe', 'twe', 'nya', 'pya'].flatMap((profile) => [
|
||||
`admin.profiles.runtime:${profile}:default`,
|
||||
`admin.playAudit.read:${profile}:default`,
|
||||
]),
|
||||
'admin.profiles.deploy:*',
|
||||
]
|
||||
: ['user'],
|
||||
oauthType: 'NONE',
|
||||
createdAt: '2026-07-20T00:00:00.000Z',
|
||||
thirdPartyUse: false,
|
||||
icons: [],
|
||||
maxActiveIcons: 5,
|
||||
deleteAfter: null,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto('account');
|
||||
await expect(page.getByLabel('보유 권한')).toHaveText('user');
|
||||
const baselineOverflow = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
|
||||
showGroupedRoles = true;
|
||||
await page.reload();
|
||||
const summary = page.getByLabel('보유 권한');
|
||||
await expect(summary).toContainText('admin.profiles.runtime:{che, kwe, pwe, hwe, twe, nya, pya}:default');
|
||||
await expect(summary).toContainText('admin.profiles.deploy:* (모든 서버)');
|
||||
await expect(summary).not.toContainText('admin.playAudit.accounts');
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
const geometry = await summary.evaluate((element) => ({
|
||||
right: element.getBoundingClientRect().right,
|
||||
viewport: innerWidth,
|
||||
cellRight: element.closest('td')!.getBoundingClientRect().right,
|
||||
documentOverflow: document.documentElement.scrollWidth - innerWidth,
|
||||
overflowWrap: getComputedStyle(element).overflowWrap,
|
||||
}));
|
||||
expect(geometry.right).toBeLessThanOrEqual(geometry.cellRight);
|
||||
expect(geometry.documentOverflow).toBe(baselineOverflow);
|
||||
await writeFile(testInfo.outputPath('account-permissions-geometry.json'), JSON.stringify(geometry, null, 2));
|
||||
await writeFile(testInfo.outputPath('account-permissions.html'), await page.content());
|
||||
await page.screenshot({ path: testInfo.outputPath('account-permissions.png'), fullPage: true });
|
||||
});
|
||||
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1200, height: 900 },
|
||||
{ name: 'mobile', width: 390, height: 844 },
|
||||
]) {
|
||||
test(`cancels an expired deletion with a reason, confirmation and audit on ${viewport.name}`, async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
await page.setViewportSize(viewport);
|
||||
let complete: (() => void) | undefined;
|
||||
const requests = await installFixture(page, ['*'], {
|
||||
deleteAfter: '2020-01-01T00:00:00Z',
|
||||
beforeCancel: () =>
|
||||
new Promise<void>((resolve) => {
|
||||
complete = resolve;
|
||||
}),
|
||||
});
|
||||
await page.goto('admin/users');
|
||||
const target = page.getByRole('button', { name: /target.*대상 사용자/ });
|
||||
await target.click();
|
||||
await page.getByRole('button', { name: /탈퇴 · 이력/ }).click();
|
||||
const panel = page.getByRole('heading', { name: '관리자 탈퇴 예약', exact: true }).locator('..');
|
||||
const cancel = panel.getByRole('button', { name: '탈퇴 취소', exact: true });
|
||||
await expect(cancel).toBeEnabled();
|
||||
await cancel.click();
|
||||
expect(requests.filter(({ operation }) => operation === 'admin.users.cancelDeletion')).toHaveLength(0);
|
||||
await page.getByPlaceholder('권한·제재·복구·탈퇴 조치 사유 (필수)').fill('본인 확인 후 탈퇴 취소');
|
||||
page.once('dialog', (dialog) => dialog.dismiss());
|
||||
await cancel.click();
|
||||
expect(requests.filter(({ operation }) => operation === 'admin.users.cancelDeletion')).toHaveLength(0);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await cancel.hover();
|
||||
await expect
|
||||
.poll(() => cancel.evaluate((el) => getComputedStyle(el).backgroundColor))
|
||||
.toBe('oklch(0.546 0.245 262.881)');
|
||||
await page.mouse.down();
|
||||
expect(await cancel.evaluate((el) => el.matches(':active'))).toBe(true);
|
||||
await page.mouse.move(1, 1);
|
||||
await page.mouse.up();
|
||||
await cancel.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(cancel).toBeFocused();
|
||||
const geometry = await panel.evaluate((el) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
const button = el.querySelectorAll('button')[1]!;
|
||||
const buttonRect = button.getBoundingClientRect();
|
||||
const style = getComputedStyle(button);
|
||||
return {
|
||||
x: rect.x,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
viewport: innerWidth,
|
||||
right: rect.right,
|
||||
buttonWidth: buttonRect.width,
|
||||
buttonHeight: buttonRect.height,
|
||||
textAlign: style.textAlign,
|
||||
fontSize: style.fontSize,
|
||||
focus: button.matches(':focus-visible'),
|
||||
html: el.outerHTML,
|
||||
documentOverflow: document.documentElement.scrollWidth - innerWidth,
|
||||
};
|
||||
});
|
||||
expect(geometry.documentOverflow).toBe(0);
|
||||
expect(geometry.right).toBeLessThanOrEqual(viewport.width);
|
||||
expect(geometry.buttonHeight).toBeGreaterThanOrEqual(40);
|
||||
expect(geometry.focus).toBe(true);
|
||||
await writeFile(testInfo.outputPath('admin-deletion-geometry-style.json'), JSON.stringify(geometry, null, 2));
|
||||
await writeFile(testInfo.outputPath('admin-deletion-panel.html'), geometry.html);
|
||||
await page.screenshot({ path: testInfo.outputPath('admin-deletion-before.png'), fullPage: true });
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
await cancel.click();
|
||||
await expect(cancel).toBeDisabled();
|
||||
await expect(panel.getByRole('button', { name: '보존 기간 후 탈퇴 예약' })).toBeDisabled();
|
||||
await expect
|
||||
.poll(() => requests.filter(({ operation }) => operation === 'admin.users.cancelDeletion').length)
|
||||
.toBe(1);
|
||||
expect(complete).toBeDefined();
|
||||
complete!();
|
||||
await expect(panel.getByRole('status')).toHaveText('탈퇴 예약을 취소했습니다.');
|
||||
await expect(cancel).toBeDisabled();
|
||||
await expect(target).not.toContainText('탈퇴 예약');
|
||||
await expect(page.getByText('SUCCEEDED · admin.users.cancelDeletion').first()).toBeVisible();
|
||||
const request = requests.find(({ operation }) => operation === 'admin.users.cancelDeletion');
|
||||
expect(Object.values(request!.body as Record<string, unknown>)).toEqual([
|
||||
{ userId: 'target-user', reason: '본인 확인 후 탈퇴 취소' },
|
||||
]);
|
||||
await page.reload();
|
||||
await target.click();
|
||||
await page.getByRole('button', { name: /탈퇴 · 이력/ }).click();
|
||||
await expect(cancel).toBeDisabled();
|
||||
await page.screenshot({ path: testInfo.outputPath('admin-deletion-after.png'), fullPage: true });
|
||||
});
|
||||
}
|
||||
|
||||
test('keeps the pending deletion visible on failure and reports delayed flush as committed success', async ({
|
||||
page,
|
||||
}) => {
|
||||
const requests = await installFixture(page, ['*'], { deleteAfter: '2020-01-01T00:00:00Z', cancelFails: true });
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
await page.goto('admin/users');
|
||||
await page.getByRole('button', { name: /target.*대상 사용자/ }).click();
|
||||
await page.getByRole('button', { name: /탈퇴 · 이력/ }).click();
|
||||
const panel = page.getByRole('heading', { name: '관리자 탈퇴 예약', exact: true }).locator('..');
|
||||
await page.getByPlaceholder('권한·제재·복구·탈퇴 조치 사유 (필수)').fill('본인 확인 후 복구');
|
||||
await panel.getByRole('button', { name: '탈퇴 취소', exact: true }).click();
|
||||
await expect(panel.getByRole('status')).toContainText('다시 조회해 주세요.');
|
||||
await expect(panel.getByRole('button', { name: '탈퇴 취소', exact: true })).toBeEnabled();
|
||||
expect(requests.filter(({ operation }) => operation === 'admin.users.cancelDeletion')).toHaveLength(1);
|
||||
await installFixture(page, ['*'], { deleteAfter: '2020-01-01T00:00:00Z', flushPublished: false });
|
||||
await page.reload();
|
||||
await page.getByRole('button', { name: /target.*대상 사용자/ }).click();
|
||||
await page.getByRole('button', { name: /탈퇴 · 이력/ }).click();
|
||||
await page.getByPlaceholder('권한·제재·복구·탈퇴 조치 사유 (필수)').fill('본인 확인 후 복구');
|
||||
await panel.getByRole('button', { name: '탈퇴 취소', exact: true }).click();
|
||||
await expect(panel.getByRole('status')).toContainText('탈퇴 예약은 취소되었습니다.');
|
||||
await expect(panel.getByRole('button', { name: '탈퇴 취소', exact: true })).toBeDisabled();
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { generateKeyPairSync } from 'node:crypto';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
|
||||
@@ -98,6 +99,7 @@ const verifyRecoveryChoice = async (page: Page, action: 'link_existing' | 'rejoi
|
||||
await expect(group).toContainText(
|
||||
action === 'link_existing' ? '이 계정에 카카오 로그인을 연결해드릴까요?' : '새 계정으로 재가입하시겠습니까?'
|
||||
);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
const geometry = await group.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
@@ -171,3 +173,174 @@ for (const viewport of [
|
||||
expect(geometry.right).toBeLessThanOrEqual(viewport.width);
|
||||
});
|
||||
}
|
||||
|
||||
const installSelfRecoveryFixture = async (page: Page, byPassword: boolean) => {
|
||||
const calls: string[] = [];
|
||||
let loggedIn = false;
|
||||
let passwordAttempts = 0;
|
||||
let release: (() => void) | undefined;
|
||||
await page.route('**/gateway/api/trpc/**', async (route) => {
|
||||
const results = [];
|
||||
for (const operation of operationNames(route)) {
|
||||
calls.push(operation);
|
||||
let data: unknown;
|
||||
if (operation === 'me')
|
||||
data = loggedIn
|
||||
? {
|
||||
id: 'self-user',
|
||||
username: 'self-user',
|
||||
displayName: '복구 사용자',
|
||||
roles: ['user'],
|
||||
kakaoVerified: true,
|
||||
}
|
||||
: null;
|
||||
else if (operation === 'lobby.notice') data = '';
|
||||
else if (operation === 'lobby.profiles') data = [];
|
||||
else if (operation === 'auth.passwordKey')
|
||||
data = { keyId: 'self-link-key', publicKeyPem, algorithm: 'RSA-OAEP-256' };
|
||||
else if (operation === 'auth.kakaoExchange')
|
||||
data = byPassword
|
||||
? {
|
||||
status: 'join',
|
||||
oauthSessionId: '33333333-3333-4333-8333-333333333333',
|
||||
email: 'new@example.test',
|
||||
}
|
||||
: {
|
||||
status: 'account_recovery',
|
||||
action: 'link_existing',
|
||||
oauthSessionId: '33333333-3333-4333-8333-333333333333',
|
||||
email: 'retained@example.test',
|
||||
passwordRequired: false,
|
||||
};
|
||||
else if (operation === 'auth.kakaoLinkWithPassword') {
|
||||
const input = Object.values(
|
||||
route.request().postDataJSON() as Record<
|
||||
string,
|
||||
{ username: string; credential: { ciphertext: string } }
|
||||
>
|
||||
)[0]!;
|
||||
expect(input.username).toBe('self-user');
|
||||
expect(input.credential.ciphertext).not.toBe('fixture-password');
|
||||
passwordAttempts++;
|
||||
if (passwordAttempts === 1) {
|
||||
results.push({
|
||||
error: {
|
||||
message: '기존 계정명 또는 비밀번호가 일치하지 않습니다.',
|
||||
code: -32001,
|
||||
data: { code: 'UNAUTHORIZED', httpStatus: 401 },
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
data = {
|
||||
status: 'otp',
|
||||
successStatus: 'login',
|
||||
challengeId: '44444444-4444-4444-8444-444444444444',
|
||||
expiresAt: '2099-01-01T00:00:00Z',
|
||||
attemptsRemaining: 3,
|
||||
};
|
||||
} else if (operation === 'auth.kakaoResolveAccount')
|
||||
data = {
|
||||
status: 'otp',
|
||||
successStatus: 'login',
|
||||
challengeId: '44444444-4444-4444-8444-444444444444',
|
||||
expiresAt: '2099-01-01T00:00:00Z',
|
||||
attemptsRemaining: 3,
|
||||
};
|
||||
else if (operation === 'auth.kakaoOtp') {
|
||||
loggedIn = true;
|
||||
data = { status: 'login', sessionToken: 'fixture-self-recovered', validUntil: '2099-01-01T00:00:00Z' };
|
||||
} else throw new Error(`Unhandled self recovery operation: ${operation}`);
|
||||
results.push(response(data));
|
||||
}
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(results) });
|
||||
});
|
||||
return {
|
||||
calls,
|
||||
release: () => {
|
||||
expect(release).toBeDefined();
|
||||
release!();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1200, height: 900 },
|
||||
{ name: 'mobile', width: 390, height: 844 },
|
||||
]) {
|
||||
for (const byPassword of [false, true]) {
|
||||
test(`self-recovers by ${byPassword ? 'existing password' : 'matching email'} and new talk OTP on ${viewport.name}`, async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
await page.setViewportSize(viewport);
|
||||
const f = await installSelfRecoveryFixture(page, byPassword);
|
||||
await page.goto('/gateway/oauth/callback?code=fixture-code&state=fixture-state');
|
||||
if (byPassword) {
|
||||
await page.getByText('기존 계정 비밀번호로 연결', { exact: true }).click();
|
||||
const form = page.getByRole('form', { name: '기존 비밀번호로 카카오 연결' });
|
||||
await form.getByLabel('기존 계정명').fill('self-user');
|
||||
await form.getByLabel('기존 비밀번호').fill('wrong-password');
|
||||
const button = form.getByRole('button', { name: '비밀번호 확인 후 연결' });
|
||||
await button.click();
|
||||
await expect(page.getByRole('alert')).toContainText('일치하지 않습니다.');
|
||||
await form.getByLabel('기존 비밀번호').fill('fixture-password');
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await button.hover();
|
||||
expect(await button.evaluate((el) => getComputedStyle(el).backgroundColor)).toBe('rgb(47, 77, 108)');
|
||||
await page.mouse.down();
|
||||
expect(await button.evaluate((el) => el.matches(':active'))).toBe(true);
|
||||
await page.mouse.move(1, 1);
|
||||
await page.mouse.up();
|
||||
await button.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(button).toBeFocused();
|
||||
const geometry = await form.evaluate((el) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left,
|
||||
right: rect.right,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
viewport: innerWidth,
|
||||
fontSize: getComputedStyle(el).fontSize,
|
||||
html: el.outerHTML,
|
||||
overflow: document.documentElement.scrollWidth - innerWidth,
|
||||
};
|
||||
});
|
||||
expect(geometry.overflow).toBe(0);
|
||||
expect(geometry.right).toBeLessThanOrEqual(viewport.width);
|
||||
await writeFile(testInfo.outputPath('self-link-geometry.json'), JSON.stringify(geometry, null, 2));
|
||||
await writeFile(testInfo.outputPath('self-link-panel.html'), geometry.html);
|
||||
await testInfo.attach('self-link-geometry', {
|
||||
body: JSON.stringify(geometry),
|
||||
contentType: 'application/json',
|
||||
});
|
||||
await page.screenshot({ path: testInfo.outputPath('self-link-password.png'), fullPage: true });
|
||||
await button.click();
|
||||
await expect(form.getByRole('button')).toBeDisabled();
|
||||
await expect.poll(() => f.calls.filter((call) => call === 'auth.kakaoLinkWithPassword').length).toBe(2);
|
||||
f.release();
|
||||
} else {
|
||||
await page.getByRole('button', { name: '기존 계정에 연결', exact: true }).click();
|
||||
}
|
||||
const dialog = page.getByRole('dialog', { name: '인증 코드 필요' });
|
||||
await expect(dialog).toBeVisible();
|
||||
expect(await page.evaluate(() => localStorage.getItem('sammo-session-token'))).toBeNull();
|
||||
await page.screenshot({ path: testInfo.outputPath('self-link-before-commit.png'), fullPage: true });
|
||||
await dialog.locator('input').fill('1234');
|
||||
await dialog.getByRole('button', { name: '제출', exact: true }).click();
|
||||
await expect(page).toHaveURL(/\/gateway\/lobby$/);
|
||||
expect(await page.evaluate(() => localStorage.getItem('sammo-session-token'))).toBe(
|
||||
'fixture-self-recovered'
|
||||
);
|
||||
expect(f.calls).not.toContain('auth.register');
|
||||
expect(f.calls).not.toContain('admin.users.setKakaoReplacementApproval');
|
||||
await page.reload();
|
||||
await expect(page).toHaveURL(/\/gateway\/lobby$/);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,7 @@ const verifyDialog = async (page: Page, artifactName: string) => {
|
||||
await expect(submit).toBeFocused();
|
||||
await page.waitForTimeout(200);
|
||||
expect(await submit.evaluate((element) => getComputedStyle(element).boxShadow)).toMatch(
|
||||
/^rgba\(85, 115, 146, 0\.49\d\) 0px 0px 0px 4px$/
|
||||
/^rgba\(85, 115, 146, 0\.(?:49\d|5)\) 0px 0px 0px 4px$/
|
||||
);
|
||||
|
||||
if (artifactRoot) {
|
||||
|
||||
@@ -60,8 +60,8 @@ const loginGame = async (username: string, password: string) => {
|
||||
).toString('base64'),
|
||||
};
|
||||
const login = await gateway.auth.login.mutate({ username, credential });
|
||||
if (login.status === 'otp') {
|
||||
throw new Error('Live lifecycle fixture requires a currently verified KakaoTalk login.');
|
||||
if (login.status !== 'login') {
|
||||
throw new Error(`Live lifecycle fixture requires login; received ${login.status}.`);
|
||||
}
|
||||
gatewaySession.token = login.sessionToken;
|
||||
const issued = await gateway.auth.issueGameSession.mutate({
|
||||
|
||||
@@ -21,6 +21,7 @@ export default defineConfig({
|
||||
'gateway-notice-html.spec.ts',
|
||||
'kakao-otp.spec.ts',
|
||||
'kakao-account-recovery.spec.ts',
|
||||
'account-deletion-recovery.spec.ts',
|
||||
'public-map-tabs.spec.ts',
|
||||
'runtime-navigation.spec.ts',
|
||||
'open-suggestion.spec.ts',
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { formatServerDateTime } from '@sammo-ts/common/time/ServerDateTime';
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
export interface DeletionPending {
|
||||
recoveryId: string;
|
||||
deleteAfter: string;
|
||||
}
|
||||
const props = defineProps<{ recovery: DeletionPending }>();
|
||||
const emit = defineEmits<{ restored: [sessionToken: string]; cancel: [] }>();
|
||||
const submitting = ref(false);
|
||||
const errorMessage = ref('');
|
||||
const restore = async (): Promise<void> => {
|
||||
if (submitting.value) return;
|
||||
submitting.value = true;
|
||||
errorMessage.value = '';
|
||||
try {
|
||||
const result = await trpc.auth.cancelDeletion.mutate({ recoveryId: props.recovery.recoveryId });
|
||||
if (result.status !== 'login') throw new Error('계정 상태가 변경되었습니다. 다시 로그인해 주세요.');
|
||||
emit('restored', result.sessionToken);
|
||||
} catch (error) {
|
||||
errorMessage.value = error instanceof Error ? error.message : '탈퇴를 취소하지 못했습니다.';
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="deletion-recovery" role="group" aria-label="탈퇴 취소">
|
||||
<p>탈퇴 신청된 계정입니다.</p>
|
||||
<p>삭제 예정일: {{ formatServerDateTime(recovery.deleteAfter) }}</p>
|
||||
<p>계정을 계속 사용하려면 탈퇴를 취소해 주세요.</p>
|
||||
<div class="actions">
|
||||
<button type="button" :disabled="submitting" @click="restore">
|
||||
{{ submitting ? '처리 중...' : '탈퇴 취소' }}
|
||||
</button>
|
||||
<button type="button" :disabled="submitting" @click="emit('cancel')">돌아가기</button>
|
||||
</div>
|
||||
<p v-if="errorMessage" class="recovery-error" role="alert">{{ errorMessage }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.deletion-recovery {
|
||||
padding: 18px;
|
||||
text-align: center;
|
||||
color: #fff;
|
||||
}
|
||||
.deletion-recovery p {
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.actions button {
|
||||
min-height: 42px;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid #2f4d6c;
|
||||
border-radius: 4px;
|
||||
background: #375a7f;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
.actions button:hover,
|
||||
.actions button:active {
|
||||
background: #2f4d6c;
|
||||
}
|
||||
.actions button:focus-visible {
|
||||
outline: 2px solid #f39c12;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.actions button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
.recovery-error {
|
||||
color: #ff8a80;
|
||||
margin-top: 12px !important;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue';
|
||||
|
||||
import type { DeletionPending } from './DeletionRecoveryPanel.vue';
|
||||
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -10,6 +12,7 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
verified: [sessionToken: string, validUntil: string];
|
||||
cancel: [];
|
||||
deletionPending: [recovery: DeletionPending];
|
||||
}>();
|
||||
|
||||
const code = ref('');
|
||||
@@ -36,6 +39,10 @@ const submit = async (): Promise<void> => {
|
||||
challengeId: props.challengeId,
|
||||
code: code.value,
|
||||
});
|
||||
if (result.status === 'deletion_pending') {
|
||||
emit('deletionPending', result);
|
||||
return;
|
||||
}
|
||||
emit('verified', result.sessionToken, result.validUntil);
|
||||
} catch (error) {
|
||||
errorMessage.value = error instanceof Error ? error.message : '인증 코드를 확인하지 못했습니다.';
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { formatRoleGroups } from '../utils/roleDisplay';
|
||||
|
||||
const props = defineProps<{ roles: readonly string[] }>();
|
||||
const groups = computed(() => formatRoleGroups(props.roles));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="role-summary" aria-label="보유 권한">
|
||||
<template v-for="(group, index) in groups" :key="index">
|
||||
<span v-if="index">, </span><span class="role-group">{{ group }}</span>
|
||||
</template>
|
||||
<template v-if="!groups.length">-</template>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.role-summary {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.role-group {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,26 @@
|
||||
/** 표시만 묶는다. 명시적인 서버 권한을 모든 서버 권한으로 승격하지 않는다. */
|
||||
export const formatRoleGroups = (roles: readonly string[]): string[] => {
|
||||
const groups = new Map<string, { permission: string; instance: string; profiles: string[] }>();
|
||||
const entries: Array<string | { permission: string; instance: string; profiles: string[] }> = [];
|
||||
for (const role of roles) {
|
||||
const match = /^(admin\.[^:]+):([^:]+):([^:]+)$/u.exec(role);
|
||||
if (!match) {
|
||||
entries.push(role.endsWith(':*') ? `${role} (모든 서버)` : role);
|
||||
continue;
|
||||
}
|
||||
const [, permission, profile, instance] = match;
|
||||
const key = `${permission}:${instance}`;
|
||||
let group = groups.get(key);
|
||||
if (!group) {
|
||||
group = { permission, instance, profiles: [] };
|
||||
groups.set(key, group);
|
||||
entries.push(group);
|
||||
}
|
||||
if (!group.profiles.includes(profile)) group.profiles.push(profile);
|
||||
}
|
||||
return entries.map((entry) => {
|
||||
if (typeof entry === 'string') return entry;
|
||||
const profiles = entry.profiles.length > 1 ? `{${entry.profiles.join(', ')}}` : entry.profiles[0];
|
||||
return `${entry.permission}:${profiles}:${entry.instance}`;
|
||||
});
|
||||
};
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from 'vue-router';
|
||||
|
||||
import { useToast } from '../composables/useToast';
|
||||
import DefaultLayout from '../layouts/DefaultLayout.vue';
|
||||
import RoleSummary from '../components/RoleSummary.vue';
|
||||
import { createGameTrpc } from '../utils/gameTrpc';
|
||||
import { trpc } from '../utils/trpc';
|
||||
import { sealPassword } from '../utils/passwordEnvelope';
|
||||
@@ -86,11 +87,6 @@ const currentProfile = computed(() =>
|
||||
const notificationEventTypes = computed(
|
||||
() => (notificationState.value?.eventTypes ?? []) as readonly WebPushEventType[]
|
||||
);
|
||||
const kakaoReplacementApproved = computed(
|
||||
() =>
|
||||
Boolean(account.value?.kakaoReplacementApprovedUntil) &&
|
||||
new Date(account.value!.kakaoReplacementApprovedUntil!).getTime() > Date.now()
|
||||
);
|
||||
|
||||
const sessionToken = (): string | null => window.localStorage.getItem('sammo-session-token');
|
||||
|
||||
@@ -320,7 +316,7 @@ const changePassword = async (): Promise<void> => {
|
||||
const startKakaoReplacement = async (): Promise<void> => {
|
||||
if (
|
||||
!window.confirm(
|
||||
'새 카카오 계정 연결이 끝나면 기존 카카오 계정은 영구 폐기되어 다시 가입하거나 연결할 수 없습니다. 계속하시겠습니까?'
|
||||
'새 카카오톡 인증을 완료하면 로그인에 사용할 카카오 계정이 바뀌고 기존 세션이 종료됩니다. 계속하시겠습니까?'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
@@ -640,7 +636,7 @@ onBeforeUnmount(() => {
|
||||
<tr>
|
||||
<th class="legacy-bg1">등급</th>
|
||||
<td colspan="2">{{ gradeLabel }}</td>
|
||||
<td colspan="3">{{ account.roles.join(', ') || '-' }}</td>
|
||||
<td colspan="3"><RoleSummary :roles="account.roles" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th class="legacy-bg1">가입일시</th>
|
||||
@@ -666,7 +662,7 @@ onBeforeUnmount(() => {
|
||||
· 교체 승인 {{ formatServerDateTime(account.kakaoReplacementApprovedUntil) }}까지
|
||||
</template>
|
||||
<button
|
||||
v-if="kakaoReplacementApproved"
|
||||
v-if="account.oauthType === 'KAKAO'"
|
||||
class="skin-button compact"
|
||||
type="button"
|
||||
:disabled="busy"
|
||||
@@ -831,7 +827,9 @@ onBeforeUnmount(() => {
|
||||
현재 아이콘 서버 적용
|
||||
</button>
|
||||
</p>
|
||||
<p class="warning">탈퇴시 1개월간 정보가 보존되며, 1개월간 재가입이 불가능합니다.</p>
|
||||
<p class="warning">
|
||||
탈퇴시 1개월간 정보가 보존되며, 보존 기간에는 로그인 후 탈퇴를 취소할 수 있습니다.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { gatewayProfileCapabilities, type GatewayProfileStatus } from '@sammo-ts/common/gateway/profileStatus';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import ServerProfileTabs from '../components/ServerProfileTabs.vue';
|
||||
import RoleSummary from '../components/RoleSummary.vue';
|
||||
import ProfileRuntimeDiagnostics from '../components/ProfileRuntimeDiagnostics.vue';
|
||||
import AdminConsoleLayout from '../layouts/AdminConsoleLayout.vue';
|
||||
import { useToast } from '../composables/useToast';
|
||||
@@ -366,6 +367,13 @@ type AdminClient = {
|
||||
deleteAfter: string;
|
||||
}>;
|
||||
};
|
||||
cancelDeletion: {
|
||||
mutate: (input: { userId: string; reason: string }) => Promise<{
|
||||
ok: boolean;
|
||||
deleteAfter: null;
|
||||
flushPublished: boolean;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
profiles: {
|
||||
list: {
|
||||
@@ -603,6 +611,18 @@ const hasCapability = (permission: string, profileName?: string): boolean =>
|
||||
});
|
||||
const selectedCapability = ref('');
|
||||
const capabilityProfile = ref('');
|
||||
const selectedCapabilityDefinition = computed(() =>
|
||||
capabilities.value.find((entry) => entry.permission === selectedCapability.value)
|
||||
);
|
||||
const canSelectAllServers = computed(() => selectedCapabilityDefinition.value?.scopes?.includes('*') ?? false);
|
||||
const capabilityProfiles = computed(() =>
|
||||
kakaoPolicies.value.filter((policy) =>
|
||||
selectedCapabilityDefinition.value?.scopes?.some((scope) => scope === '*' || scope === policy.profileName)
|
||||
)
|
||||
);
|
||||
watch(selectedCapability, () => {
|
||||
capabilityProfile.value = '';
|
||||
});
|
||||
const userActionReason = ref('');
|
||||
|
||||
const banUntil = ref('');
|
||||
@@ -619,6 +639,7 @@ const restrictionNotes = ref('');
|
||||
const restrictionStatus = ref('');
|
||||
|
||||
const forceDeleteStatus = ref('');
|
||||
const deletionActionBusy = ref(false);
|
||||
const deletionRetentionDays = ref(30);
|
||||
const kakaoGraceUntil = ref('');
|
||||
const kakaoGraceStatus = ref('');
|
||||
@@ -1160,6 +1181,13 @@ const applyCapabilitySelection = () => {
|
||||
rolesStatus.value = '대상 서버를 선택하세요.';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
capability.scope === 'PROFILE' &&
|
||||
!capability.scopes?.some((scope) => scope === '*' || scope === capabilityProfile.value)
|
||||
) {
|
||||
rolesStatus.value = '부여 가능한 서버 범위를 확인하세요.';
|
||||
return;
|
||||
}
|
||||
rolesInput.value =
|
||||
capability.scope === 'PROFILE'
|
||||
? `${capability.permission}:${capabilityProfile.value.trim()}`
|
||||
@@ -1465,7 +1493,7 @@ const clearRestriction = async () => {
|
||||
};
|
||||
|
||||
const scheduleDeleteUser = async () => {
|
||||
if (!userResult.value) {
|
||||
if (!userResult.value || deletionActionBusy.value) {
|
||||
return;
|
||||
}
|
||||
const reason = requireUserActionReason();
|
||||
@@ -1476,6 +1504,7 @@ const scheduleDeleteUser = async () => {
|
||||
return;
|
||||
}
|
||||
}
|
||||
deletionActionBusy.value = true;
|
||||
try {
|
||||
const result = await adminClient.users.scheduleDeletion.mutate({
|
||||
userId: userResult.value.id,
|
||||
@@ -1487,6 +1516,33 @@ const scheduleDeleteUser = async () => {
|
||||
await Promise.all([refreshUserHistory(), loadUserDirectory()]);
|
||||
} catch (error) {
|
||||
forceDeleteStatus.value = '탈퇴 예약 실패';
|
||||
} finally {
|
||||
deletionActionBusy.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const cancelDeleteUser = async (): Promise<void> => {
|
||||
const target = userResult.value;
|
||||
if (!target?.deleteAfter || deletionActionBusy.value) return;
|
||||
const reason = requireUserActionReason();
|
||||
if (!reason || !window.confirm('선택한 계정의 탈퇴 예약을 취소하시겠습니까?')) return;
|
||||
deletionActionBusy.value = true;
|
||||
try {
|
||||
const result = await adminClient.users.cancelDeletion.mutate({ userId: target.id, reason });
|
||||
if (userResult.value?.id === target.id) {
|
||||
userResult.value = { ...userResult.value, deleteAfter: undefined };
|
||||
forceDeleteStatus.value = result.flushPublished
|
||||
? '탈퇴 예약을 취소했습니다.'
|
||||
: '탈퇴 예약은 취소되었습니다. 게임 접속 정보 갱신이 지연되고 있습니다.';
|
||||
await refreshUserHistory();
|
||||
}
|
||||
await loadUserDirectory();
|
||||
} catch (error) {
|
||||
if (userResult.value?.id === target.id) {
|
||||
forceDeleteStatus.value = error instanceof Error ? error.message : '탈퇴 예약 취소 실패';
|
||||
}
|
||||
} finally {
|
||||
deletionActionBusy.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1574,7 +1630,7 @@ onMounted(() => {
|
||||
</section>
|
||||
|
||||
<div class="space-y-8">
|
||||
<section v-if="section === 'users'" class="grid min-w-0 items-start gap-6 xl:grid-cols-2">
|
||||
<section v-if="section === 'users'" class="grid min-w-0 grid-cols-1 items-start gap-6 xl:grid-cols-2">
|
||||
<div class="bg-zinc-900 border border-zinc-800 rounded-lg p-5 space-y-4 xl:col-span-2">
|
||||
<div class="flex flex-wrap items-end justify-between gap-2">
|
||||
<div>
|
||||
@@ -1700,7 +1756,7 @@ onMounted(() => {
|
||||
<div class="text-xs text-zinc-500">{{ userResult.id }}</div>
|
||||
</div>
|
||||
<div class="text-xs text-zinc-400">표시명: {{ userResult.displayName }}</div>
|
||||
<div class="text-xs text-zinc-400">권한: {{ userResult.roles.join(', ') || '-' }}</div>
|
||||
<div class="text-xs text-zinc-400">권한: <RoleSummary :roles="userResult.roles" /></div>
|
||||
<div class="text-xs text-zinc-500">
|
||||
OAuth: {{ userResult.oauthType }} {{ userResult.email ?? '' }}
|
||||
</div>
|
||||
@@ -1913,6 +1969,7 @@ onMounted(() => {
|
||||
<div class="grid gap-2 md:grid-cols-[1fr_1fr_auto]">
|
||||
<select
|
||||
v-model="selectedCapability"
|
||||
aria-label="관리 기능 권한"
|
||||
class="bg-zinc-950 border border-zinc-700 rounded px-3 py-2 text-sm text-white"
|
||||
:disabled="!hasUser"
|
||||
>
|
||||
@@ -1925,14 +1982,16 @@ onMounted(() => {
|
||||
</option>
|
||||
</select>
|
||||
<select
|
||||
v-if="selectedCapabilityDefinition?.scope === 'PROFILE'"
|
||||
v-model="capabilityProfile"
|
||||
class="bg-zinc-950 border border-zinc-700 rounded px-3 py-2 text-sm text-white"
|
||||
:disabled="!hasUser || !kakaoPolicies.length"
|
||||
:disabled="!hasUser"
|
||||
aria-label="권한 대상 서버"
|
||||
>
|
||||
<option value="">대상 서버 선택</option>
|
||||
<option v-if="canSelectAllServers" value="*">모든 서버</option>
|
||||
<option
|
||||
v-for="policy in kakaoPolicies"
|
||||
v-for="policy in capabilityProfiles"
|
||||
:key="policy.profileName"
|
||||
:value="policy.profileName"
|
||||
>
|
||||
@@ -1947,6 +2006,10 @@ onMounted(() => {
|
||||
선택 반영
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="capabilityProfile === '*'" class="text-xs text-amber-300">
|
||||
선택한 행동만 현재와 앞으로 추가되는 모든 서버에 허용합니다. 계정 조사 등 다른 권한은
|
||||
포함하지 않습니다.
|
||||
</p>
|
||||
<div v-if="selectedCapability" class="text-xs text-zinc-500">
|
||||
{{ capabilities.find((item) => item.permission === selectedCapability)?.description }}
|
||||
</div>
|
||||
@@ -2265,6 +2328,9 @@ onMounted(() => {
|
||||
class="bg-zinc-900 border border-zinc-800 rounded-lg p-5 space-y-4"
|
||||
>
|
||||
<h4 class="text-base font-semibold text-red-400">관리자 탈퇴 예약</h4>
|
||||
<p v-if="userResult?.deleteAfter" class="text-sm text-zinc-300">
|
||||
삭제 예정일: {{ formatServerDateTime(userResult.deleteAfter) }}
|
||||
</p>
|
||||
<input
|
||||
v-model.number="deletionRetentionDays"
|
||||
type="number"
|
||||
@@ -2272,16 +2338,25 @@ onMounted(() => {
|
||||
max="90"
|
||||
class="w-full bg-zinc-950 border border-zinc-700 rounded px-3 py-2 text-sm text-white"
|
||||
aria-label="탈퇴 전 보존 일수"
|
||||
:disabled="!hasUser"
|
||||
:disabled="!hasUser || deletionActionBusy"
|
||||
/>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
class="bg-red-700 hover:bg-red-600 text-white font-semibold px-4 py-2 rounded"
|
||||
:disabled="!hasUser"
|
||||
:disabled="!hasUser || deletionActionBusy"
|
||||
@click="scheduleDeleteUser"
|
||||
>
|
||||
보존 기간 후 탈퇴 예약
|
||||
</button>
|
||||
<div class="text-xs text-zinc-500">{{ forceDeleteStatus }}</div>
|
||||
<button
|
||||
class="bg-blue-700 hover:bg-blue-600 text-white font-semibold px-4 py-2 rounded disabled:opacity-50"
|
||||
:disabled="!userResult?.deleteAfter || deletionActionBusy"
|
||||
@click="cancelDeleteUser"
|
||||
>
|
||||
탈퇴 취소
|
||||
</button>
|
||||
</div>
|
||||
<div class="text-xs text-zinc-500" role="status">{{ forceDeleteStatus }}</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
|
||||
@@ -7,6 +7,7 @@ import { gatewayProfileCapabilities } from '@sammo-ts/common/gateway/profileStat
|
||||
|
||||
import MapPreview from '../components/MapPreview.vue';
|
||||
import KakaoOtpDialog from '../components/KakaoOtpDialog.vue';
|
||||
import DeletionRecoveryPanel, { type DeletionPending } from '../components/DeletionRecoveryPanel.vue';
|
||||
import DefaultLayout from '../layouts/DefaultLayout.vue';
|
||||
import { createGameTrpc, type GameRouter } from '../utils/gameTrpc';
|
||||
import { trpc } from '../utils/trpc';
|
||||
@@ -27,6 +28,12 @@ const username = ref('');
|
||||
const password = ref('');
|
||||
const loginError = ref('');
|
||||
const loginLoading = ref(false);
|
||||
const deletionPending = ref<DeletionPending | null>(null);
|
||||
const handleDeletionPending = (recovery: DeletionPending): void => {
|
||||
otpChallenge.value = null;
|
||||
password.value = '';
|
||||
deletionPending.value = recovery;
|
||||
};
|
||||
const otpChallenge = ref<{ challengeId: string; expiresAt: string; attemptsRemaining: number } | null>(null);
|
||||
const statusLoading = ref(false);
|
||||
const statusError = ref('');
|
||||
@@ -101,6 +108,10 @@ const handleLogin = async (): Promise<void> => {
|
||||
username: username.value,
|
||||
credential,
|
||||
});
|
||||
if (result.status === 'deletion_pending') {
|
||||
handleDeletionPending(result);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'otp') {
|
||||
otpChallenge.value = result;
|
||||
return;
|
||||
@@ -148,7 +159,13 @@ const handlePasswordReset = async (): Promise<void> => {
|
||||
|
||||
<section id="login_card" class="login-card">
|
||||
<h3>로그인</h3>
|
||||
<form id="main_form" @submit.prevent="handleLogin">
|
||||
<DeletionRecoveryPanel
|
||||
v-if="deletionPending"
|
||||
:recovery="deletionPending"
|
||||
@restored="handleOtpVerified"
|
||||
@cancel="deletionPending = null"
|
||||
/>
|
||||
<form v-else id="main_form" @submit.prevent="handleLogin">
|
||||
<label for="username">계정명</label>
|
||||
<input
|
||||
id="username"
|
||||
@@ -214,6 +231,7 @@ const handlePasswordReset = async (): Promise<void> => {
|
||||
v-if="otpChallenge"
|
||||
:challenge-id="otpChallenge.challengeId"
|
||||
@verified="handleOtpVerified"
|
||||
@deletion-pending="handleDeletionPending"
|
||||
@cancel="otpChallenge = null"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -4,12 +4,18 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import DefaultLayout from '../layouts/DefaultLayout.vue';
|
||||
import KakaoOtpDialog from '../components/KakaoOtpDialog.vue';
|
||||
import DeletionRecoveryPanel, { type DeletionPending } from '../components/DeletionRecoveryPanel.vue';
|
||||
import { trpc } from '../utils/trpc';
|
||||
import { sealPassword } from '../utils/passwordEnvelope';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const loading = ref(true);
|
||||
const deletionPending = ref<DeletionPending | null>(null);
|
||||
const handleDeletionPending = (recovery: DeletionPending): void => {
|
||||
otpChallenge.value = null;
|
||||
deletionPending.value = recovery;
|
||||
};
|
||||
const submitting = ref(false);
|
||||
const errorMessage = ref('');
|
||||
const infoMessage = ref('');
|
||||
@@ -20,12 +26,19 @@ const email = ref('');
|
||||
const username = ref('');
|
||||
const password = ref('');
|
||||
const confirmPassword = ref('');
|
||||
const linkUsername = ref('');
|
||||
const linkPassword = ref('');
|
||||
const passwordLinkOpen = ref(false);
|
||||
const handlePasswordLinkToggle = (event: Event): void => {
|
||||
if (event.currentTarget instanceof HTMLDetailsElement) passwordLinkOpen.value = event.currentTarget.open;
|
||||
};
|
||||
const displayName = ref('');
|
||||
const termsAgreed = ref(false);
|
||||
const privacyAgreed = ref(false);
|
||||
const thirdPartyUse = ref(false);
|
||||
const accountRecovery = ref<{
|
||||
action: 'link_existing' | 'rejoin';
|
||||
passwordRequired?: boolean;
|
||||
oauthSessionId: string;
|
||||
email: string;
|
||||
} | null>(null);
|
||||
@@ -43,6 +56,10 @@ const completeExchange = async (): Promise<void> => {
|
||||
}
|
||||
try {
|
||||
const result = await trpc.auth.kakaoExchange.mutate({ code, state });
|
||||
if (result.status === 'deletion_pending') {
|
||||
handleDeletionPending(result);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'otp') {
|
||||
otpChallenge.value = result;
|
||||
otpSuccessStatus.value = result.successStatus;
|
||||
@@ -97,11 +114,6 @@ const resolveAccount = async (): Promise<void> => {
|
||||
otpSuccessStatus.value = result.successStatus;
|
||||
return;
|
||||
}
|
||||
if (result.status === 'login') {
|
||||
window.localStorage.setItem('sammo-session-token', result.sessionToken);
|
||||
await router.replace('/lobby');
|
||||
return;
|
||||
}
|
||||
if (result.status === 'password_setup') {
|
||||
passwordSetupSessionId.value = result.oauthSessionId;
|
||||
passwordSetupSuccessStatus.value = result.successStatus;
|
||||
@@ -117,6 +129,36 @@ const resolveAccount = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
const linkWithPassword = async (): Promise<void> => {
|
||||
const sessionId = accountRecovery.value?.oauthSessionId || oauthSessionId.value;
|
||||
if (!sessionId || submitting.value) return;
|
||||
submitting.value = true;
|
||||
errorMessage.value = '';
|
||||
try {
|
||||
const credential = await sealPassword(linkPassword.value);
|
||||
const result = await trpc.auth.kakaoLinkWithPassword.mutate({
|
||||
oauthSessionId: sessionId,
|
||||
username: linkUsername.value,
|
||||
credential,
|
||||
});
|
||||
linkPassword.value = '';
|
||||
accountRecovery.value = null;
|
||||
oauthSessionId.value = '';
|
||||
if (result.status === 'otp') {
|
||||
otpChallenge.value = result;
|
||||
otpSuccessStatus.value = result.successStatus;
|
||||
} else {
|
||||
passwordSetupSessionId.value = result.oauthSessionId;
|
||||
passwordSetupSuccessStatus.value = result.successStatus;
|
||||
email.value = result.email;
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage.value = error instanceof Error ? error.message : '기존 계정 비밀번호를 확인하지 못했습니다.';
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const setMigratedPassword = async (): Promise<void> => {
|
||||
errorMessage.value = '';
|
||||
if (password.value !== confirmPassword.value) {
|
||||
@@ -133,6 +175,10 @@ const setMigratedPassword = async (): Promise<void> => {
|
||||
password.value = '';
|
||||
confirmPassword.value = '';
|
||||
passwordSetupSessionId.value = '';
|
||||
if (result.status === 'deletion_pending') {
|
||||
handleDeletionPending(result);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'otp') {
|
||||
otpChallenge.value = result;
|
||||
otpSuccessStatus.value = passwordSetupSuccessStatus.value;
|
||||
@@ -169,6 +215,10 @@ const register = async (): Promise<void> => {
|
||||
privacyAgreed: true,
|
||||
thirdPartyUse: thirdPartyUse.value,
|
||||
});
|
||||
if (result.status === 'deletion_pending') {
|
||||
handleDeletionPending(result);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'otp') {
|
||||
otpChallenge.value = result;
|
||||
otpSuccessStatus.value = result.successStatus;
|
||||
@@ -202,7 +252,11 @@ onMounted(() => {
|
||||
<section class="oauth-card">
|
||||
<h2>
|
||||
{{
|
||||
accountRecovery
|
||||
passwordLinkOpen && (oauthSessionId || accountRecovery)
|
||||
? '기존 계정 연결'
|
||||
: deletionPending
|
||||
? '탈퇴 취소'
|
||||
: accountRecovery
|
||||
? '카카오 계정 연결 확인'
|
||||
: passwordSetupSessionId
|
||||
? '새 비밀번호 설정'
|
||||
@@ -211,17 +265,38 @@ onMounted(() => {
|
||||
</h2>
|
||||
<p v-if="loading" class="oauth-message">카카오 인증을 확인하는 중...</p>
|
||||
<p v-else-if="infoMessage" class="oauth-message" role="status">{{ infoMessage }}</p>
|
||||
<div v-else-if="accountRecovery" class="recovery-panel" role="group" aria-label="카카오 계정 연결 확인">
|
||||
<p v-if="accountRecovery.action === 'link_existing'">
|
||||
<DeletionRecoveryPanel
|
||||
v-else-if="deletionPending"
|
||||
:recovery="deletionPending"
|
||||
@restored="handleOtpVerified"
|
||||
@cancel="router.replace('/')"
|
||||
/>
|
||||
<div
|
||||
v-else-if="accountRecovery && !passwordLinkOpen"
|
||||
class="recovery-panel"
|
||||
role="group"
|
||||
aria-label="카카오 계정 연결 확인"
|
||||
>
|
||||
<p v-if="accountRecovery.action === 'link_existing' && !accountRecovery.passwordRequired">
|
||||
<strong>{{ accountRecovery.email }}</strong> 이메일로 보존된 기존 계정이 있습니다. 이 계정에
|
||||
카카오 로그인을 연결해드릴까요?
|
||||
</p>
|
||||
<p v-else-if="accountRecovery.passwordRequired">
|
||||
새 카카오 이메일로 기존 연결을 확인했습니다. 이메일이 다르거나 추가 확인이 필요한 계정은
|
||||
아래에서 기존 계정 비밀번호를 확인해 주세요. 비밀번호를 모르면 관리자에게 복구를 요청해 주세요.
|
||||
</p>
|
||||
<p v-else>
|
||||
<strong>{{ accountRecovery.email }}</strong> 이메일은 카카오에 이미 가입된 연결이 있지만 이
|
||||
서비스에서 연결할 계정을 찾지 못했습니다. 새 계정으로 재가입하시겠습니까?
|
||||
</p>
|
||||
<div class="recovery-actions">
|
||||
<button class="register-button" type="button" :disabled="submitting" @click="resolveAccount">
|
||||
<button
|
||||
v-if="!accountRecovery.passwordRequired"
|
||||
class="register-button"
|
||||
type="button"
|
||||
:disabled="submitting"
|
||||
@click="resolveAccount"
|
||||
>
|
||||
{{
|
||||
submitting
|
||||
? '처리 중...'
|
||||
@@ -273,7 +348,7 @@ onMounted(() => {
|
||||
</button>
|
||||
<RouterLink class="back-link" to="/">취소</RouterLink>
|
||||
</form>
|
||||
<form v-else-if="oauthSessionId" @submit.prevent="register">
|
||||
<form v-else-if="oauthSessionId && !passwordLinkOpen" @submit.prevent="register">
|
||||
<div class="form-row">
|
||||
<label for="oauth-email">카카오 이메일</label>
|
||||
<input id="oauth-email" :value="email" readonly />
|
||||
@@ -328,8 +403,41 @@ onMounted(() => {
|
||||
{{ submitting ? '가입 중...' : '가입' }}
|
||||
</button>
|
||||
</form>
|
||||
<details
|
||||
v-if="oauthSessionId || accountRecovery"
|
||||
class="password-link-panel"
|
||||
:open="accountRecovery?.passwordRequired || passwordLinkOpen"
|
||||
@toggle="handlePasswordLinkToggle"
|
||||
>
|
||||
<summary>기존 계정 비밀번호로 연결</summary>
|
||||
<form aria-label="기존 비밀번호로 카카오 연결" @submit.prevent="linkWithPassword">
|
||||
<p>
|
||||
기존 카카오 인증을 사용할 수 없어도, 기존 계정 비밀번호와 새 카카오톡 인증으로 연결할 수
|
||||
있습니다.
|
||||
</p>
|
||||
<div class="form-row">
|
||||
<label for="link-username">기존 계정명</label>
|
||||
<input id="link-username" v-model="linkUsername" autocomplete="username" required />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="link-password">기존 비밀번호</label>
|
||||
<input
|
||||
id="link-password"
|
||||
v-model="linkPassword"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button class="register-button" type="submit" :disabled="submitting">
|
||||
{{ submitting ? '확인 중...' : '비밀번호 확인 후 연결' }}
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
<p v-if="errorMessage" class="oauth-error" role="alert">{{ errorMessage }}</p>
|
||||
<RouterLink v-if="!loading && !oauthSessionId" class="back-link" to="/">돌아가기</RouterLink>
|
||||
<RouterLink v-if="!loading && !oauthSessionId && !deletionPending" class="back-link" to="/"
|
||||
>돌아가기</RouterLink
|
||||
>
|
||||
</section>
|
||||
</main>
|
||||
</DefaultLayout>
|
||||
@@ -337,6 +445,7 @@ onMounted(() => {
|
||||
v-if="otpChallenge"
|
||||
:challenge-id="otpChallenge.challengeId"
|
||||
@verified="handleOtpVerified"
|
||||
@deletion-pending="handleDeletionPending"
|
||||
@cancel="otpChallenge = null"
|
||||
/>
|
||||
</template>
|
||||
@@ -377,6 +486,17 @@ onMounted(() => {
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.password-link-panel {
|
||||
margin: 18px;
|
||||
}
|
||||
.password-link-panel summary {
|
||||
cursor: pointer;
|
||||
color: #6db9ff;
|
||||
}
|
||||
.password-link-panel p {
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.recovery-panel {
|
||||
padding: 18px;
|
||||
text-align: center;
|
||||
|
||||
@@ -77,6 +77,24 @@ Lease를 잃은 process는 fencing 검사에서 commit하지 못합니다.
|
||||
`InMemoryTurnWorld`에서 읽습니다. 따라서 flush 실패 뒤 다음 run도 복원된
|
||||
checkpoint에서 시작합니다.
|
||||
|
||||
## 내부 ID와 처리 순서
|
||||
|
||||
예약턴의 순서는 `turnIdx`, 변경 감지는 revision, 실행 권한은 lease/fencing으로
|
||||
판정합니다. `GeneralTurn`은 `(generalId, turnIdx)`, `NationTurn`은
|
||||
`(nationId, officerLevel, turnIdx)` 기본키를 사용합니다. 기존 transaction 안의
|
||||
삭제·재삽입 순서를 유지하면서 사용하지 않는 자동 ID/sequence를 제거했습니다.
|
||||
|
||||
접속 기록·현재 월 통계·랭킹·유산 포인트·베팅·보존 기록/연감은 갱신 시 기존 ID를
|
||||
유지하고 신규 업무 키에만 ID를 발급합니다. Prisma 갱신은
|
||||
`packages/infra/src/stableRowId.ts`의 `upsertWithoutSequence()`가 먼저 UPDATE하고,
|
||||
미존재 결과인 P2025에서만 원래 upsert로 생성합니다. 제약 위반·다른 오류는 그대로
|
||||
전파하고, 새 키의 동시 생성 경합은 ON CONFLICT가 처리합니다. raw SQL은 같은
|
||||
module의 `existingRowIdOrNext()`로 기존 ID를 재사용합니다.
|
||||
|
||||
`input_event.sequence`, 외교 감사 sequence, outbox/log ID는 실행 순서·cursor·
|
||||
claim/완료 식별자이므로 자동 증가를 유지합니다. 새 행 생성의 rollback이나 동시
|
||||
생성 경합에서 생기는 sequence gap은 정상이며 번호를 되감지 않습니다.
|
||||
|
||||
## 저장 위치
|
||||
|
||||
| 상태 | 기준 |
|
||||
|
||||
@@ -24,6 +24,19 @@ capability로 분리되며 포괄 운영 권한은 사용하지 않습니다. Ga
|
||||
profile 범위 권한과 별개인 전역 `admin.releases.manage` 권한이 필요합니다.
|
||||
일반 사용자와 권한이 없는 관리자는 Gateway 릴리스 영역을 사용할 수 없습니다.
|
||||
|
||||
사용자 관리의 `접근 · 권한`에서 PROFILE 기능은 개별 서버 또는 `모든 서버`를
|
||||
선택합니다. 모든 서버는 기존 `<permission>:*` 역할로 저장하며, 현재 및 앞으로
|
||||
추가되는 서버에 해당 행동만 허용합니다. 기능 목록의 `scopes`에 `*`가 있는
|
||||
관리자만 전체 범위를 선택할 수 있고, 서버별 관리자에게는 보유 범위만 표시합니다.
|
||||
실제 변경에는 `admin.users.manage`와 변경할 역할에 대한 기존 검사가 모두 적용됩니다.
|
||||
예를 들어 `admin.playAudit.read:*`는 플레이 감사 조회만 허용하며,
|
||||
계정 조사에는 별도 전역 `admin.playAudit.accounts`가 필요합니다.
|
||||
|
||||
계정과 관리자 계정 상세의 권한 표시는 같은 행동·instance의 명시적 서버 목록을
|
||||
`admin.profiles.runtime:{che, kwe, pwe}:default`처럼 묶습니다. 이 표기는 읽기용이며
|
||||
저장 역할과 API 입력은 기존 문자열을 유지합니다. 명시적인 모든 현 서버 목록도
|
||||
자동으로 `*`로 바꾸지 않습니다. instance가 다르면 별도로 표시합니다.
|
||||
|
||||
### 일괄 업데이트
|
||||
|
||||
일괄 업데이트는 새 종류의 배포 엔진이 아니라 기존 Gateway release와 profile
|
||||
@@ -103,8 +116,11 @@ server build는 기존 Turbo cache를 재사용할 수 있지만, 자원 보호
|
||||
profile frontend release task의 `NODE_OPTIONS`만 덮어쓰며 server package Turbo
|
||||
build와 배포 후 PM2 process의 heap은 바꾸지 않습니다. 전용 heap을 늘릴 때는
|
||||
runtime container hard limit과 전체 process RSS를 먼저 확인합니다.
|
||||
- migration 이후 이전 애플리케이션으로 돌아갈 때 schema 하위 호환성이
|
||||
유지됩니다.
|
||||
- migration 이후 이전 애플리케이션으로 돌아갈 때 schema 하위 호환성을
|
||||
버전별로 확인합니다. `20261114020000_reserved_turn_slot_primary_keys`는 미사용
|
||||
예약턴 ID/sequence를 제거하므로 구형 Prisma client로 단독 rollback할 수 없습니다.
|
||||
Profile의 모든 구형 game process를 정지한 뒤 matching client로 전환하며,
|
||||
복구는 forward fix 또는 검증한 사전 DB backup의 restore 경로를 사용합니다.
|
||||
|
||||
## Commit worktree 자동 정리
|
||||
|
||||
|
||||
@@ -208,6 +208,32 @@ no-op, unique/FK/index, runtime query와 reload를 확인합니다. 기존 migra
|
||||
파일과 checksum은 수정하지 않습니다. `prisma db push`는 격리 fixture의
|
||||
일시적 schema 준비에만 사용합니다.
|
||||
|
||||
### 랭킹·고빈도 저장 ID 확장 회귀
|
||||
|
||||
격리된 개발 DB URL을 환경으로 주입해 `RANK_DATA_MIGRATION_TEST_DATABASE_URL=...`
|
||||
`pnpm --filter @sammo-ts/infra verify:migration:rank-data`를 실행합니다. URL은 출력하지
|
||||
않습니다. 검증기는 소유한 UUID schema에서 INT 시퀀스 소진을 재현하고 10개 대상의 기존 데이터·
|
||||
인덱스·접속 통계 FK 보존, BIGINT 전환, 전체 migration과 두 번째 deploy의 no-op을 검사합니다.
|
||||
실제 턴 저장 SQL은 조건부 runner의 `IMMEDIATE_ACTION_DATABASE_URL`과
|
||||
`rankDataPersistence.integration.test.ts`가 batch 경계, ID 재사용, 32비트 초과 ID의
|
||||
Prisma reload, 유일성 및 transaction rollback을 검증합니다. `log_entry`·`inheritance_log`의 API 숫자 cursor는
|
||||
`Number.MAX_SAFE_INTEGER`까지 정확성을 보장하며 그 이상은 명시적으로 거부합니다.
|
||||
|
||||
### 예약턴 복합키와 일반 갱신 ID 회귀
|
||||
|
||||
`RESERVED_TURN_MIGRATION_TEST_DATABASE_URL`을 격리 개발 DB에 주입해
|
||||
`pnpm --filter @sammo-ts/infra verify:migration:reserved-turn-keys`를 실행합니다.
|
||||
기존 기수의 명령·인자·시간·revision·lease 보존, 자연키 유일성, queue 교체 rollback,
|
||||
sequence 제거, 새 schema 전체 migration과 deploy 재실행을 확인합니다.
|
||||
이전 `verify:migration:rank-data`는 64비트 확장 당시의 migration head까지만
|
||||
검사합니다. 이후 예약턴 ID를 제거한 현재 전체 chain은 새 검증기가 소유합니다.
|
||||
|
||||
`stableRowId.integration.test.ts`는 `IMMEDIATE_ACTION_DATABASE_URL` 전용 schema에서
|
||||
실제 Prisma의 기존 ID 보존, 원자적 increment, 신규 키 동시 생성, 미존재 fallback의
|
||||
transaction 생존, 제약 위반 전파와 rollback을 검사합니다. 접속량/지연 접속량 및
|
||||
batch 저장 test는 같은 행을 갱신할 때 sequence가 증가하지 않는지도 확인합니다.
|
||||
예약 API의 실제 HTTP 권한 행렬과 daemon/API lease 통합 검증도 함께 실행합니다.
|
||||
|
||||
## 결과 기록
|
||||
|
||||
Report에는 실행 명령, commit, 서비스와 fixture, pass/fail/skip 수, baseline
|
||||
|
||||
@@ -86,3 +86,17 @@ export const parseJson = <T>(raw: string | null): T | null => {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** Preserve numeric API cursors beyond int4 without silently rounding a bigint. */
|
||||
export const toSafeInteger = (value: bigint | number): number => {
|
||||
const result = Number(value);
|
||||
if (!Number.isSafeInteger(result)) {
|
||||
throw new RangeError('Integer exceeds the exact numeric transport range');
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const withSafeIntegerId = <Row extends { id: bigint | number }>(row: Row): Omit<Row, 'id'> & { id: number } => ({
|
||||
...row,
|
||||
id: toSafeInteger(row.id),
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { toSafeInteger, withSafeIntegerId } from '../src/util/parse.js';
|
||||
|
||||
describe('exact numeric ID transport', () => {
|
||||
it('preserves IDs above int4 through the maximum exact JS integer', () => {
|
||||
expect(toSafeInteger(2_147_483_648n)).toBe(2_147_483_648);
|
||||
expect(toSafeInteger(9_007_199_254_740_991n)).toBe(Number.MAX_SAFE_INTEGER);
|
||||
expect(withSafeIntegerId({ id: 2_147_483_648n, text: 'record' })).toEqual({
|
||||
id: 2_147_483_648,
|
||||
text: 'record',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects silent precision loss, fractional and nonfinite IDs', () => {
|
||||
for (const value of [9_007_199_254_740_992n, 9_007_199_254_740_993n, 1.5, NaN, Infinity]) {
|
||||
expect(() => toSafeInteger(value)).toThrow(RangeError);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,8 @@
|
||||
"verify:migration:account-icon": "sh scripts/verify-account-icon-migration.sh",
|
||||
"verify:migration:kakao-talk": "sh scripts/verify-kakao-talk-migration.sh",
|
||||
"verify:migration:npc-selection": "sh scripts/verify-npc-selection-token-migration.sh",
|
||||
"verify:migration:reserved-turn-keys": "node scripts/verify-reserved-turn-key-migration.mjs",
|
||||
"verify:migration:rank-data": "node scripts/verify-rank-data-bigint-migration.mjs",
|
||||
"verify:migration:outbox-utc": "sh scripts/verify-game-outbox-utc-wall-migration.sh",
|
||||
"verify:migration:time-domains": "sh scripts/verify-time-domain-migration.sh",
|
||||
"coverage:activate:game": "node scripts/activate-read-model-coverage.mjs",
|
||||
|
||||
@@ -372,7 +372,7 @@ model NpcSelectionToken {
|
||||
}
|
||||
|
||||
model GeneralAccessLog {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
generalId Int @unique @map("general_id")
|
||||
userId String? @map("user_id")
|
||||
lastRefresh DateTime? @map("last_refresh")
|
||||
@@ -396,7 +396,7 @@ model GeneralAccessBatch {
|
||||
}
|
||||
|
||||
model TrafficPeriod {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
worldStateId Int @map("world_state_id")
|
||||
year Int
|
||||
month Int
|
||||
@@ -414,7 +414,7 @@ model TrafficPeriod {
|
||||
}
|
||||
|
||||
model TrafficPeriodGeneral {
|
||||
periodId Int @map("period_id")
|
||||
periodId BigInt @map("period_id")
|
||||
generalId Int @map("general_id")
|
||||
userId String? @map("user_id")
|
||||
refresh Int @default(0)
|
||||
@@ -482,7 +482,7 @@ model MessageAction {
|
||||
}
|
||||
|
||||
model RankData {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
nationId Int @default(0) @map("nation_id")
|
||||
generalId Int @map("general_id")
|
||||
type String @db.VarChar(20)
|
||||
@@ -679,14 +679,13 @@ model Troop {
|
||||
}
|
||||
|
||||
model GeneralTurn {
|
||||
id Int @id @default(autoincrement())
|
||||
generalId Int @map("general_id")
|
||||
turnIdx Int @map("turn_idx")
|
||||
actionCode String @map("action_code")
|
||||
arg Json @default(dbgenerated("'{}'::jsonb"))
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@unique([generalId, turnIdx])
|
||||
@@id([generalId, turnIdx])
|
||||
@@map("general_turn")
|
||||
}
|
||||
|
||||
@@ -701,7 +700,6 @@ model GeneralTurnRevision {
|
||||
}
|
||||
|
||||
model NationTurn {
|
||||
id Int @id @default(autoincrement())
|
||||
nationId Int @map("nation_id")
|
||||
officerLevel Int @map("officer_level")
|
||||
turnIdx Int @map("turn_idx")
|
||||
@@ -709,7 +707,7 @@ model NationTurn {
|
||||
arg Json @default(dbgenerated("'{}'::jsonb"))
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@unique([nationId, officerLevel, turnIdx])
|
||||
@@id([nationId, officerLevel, turnIdx])
|
||||
@@map("nation_turn")
|
||||
}
|
||||
|
||||
@@ -726,7 +724,7 @@ model NationTurnRevision {
|
||||
}
|
||||
|
||||
model Diplomacy {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
srcNationId Int @map("src_nation_id")
|
||||
destNationId Int @map("dest_nation_id")
|
||||
stateCode Int @map("state_code")
|
||||
@@ -790,7 +788,7 @@ model Event {
|
||||
}
|
||||
|
||||
model LogEntry {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
serverId String? @map("server_id")
|
||||
scope LogScope
|
||||
category LogCategory
|
||||
@@ -812,7 +810,7 @@ model LogEntry {
|
||||
}
|
||||
|
||||
model ErrorLog {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
category String
|
||||
source String? @map("source")
|
||||
message String
|
||||
@@ -825,7 +823,7 @@ model ErrorLog {
|
||||
}
|
||||
|
||||
model InheritancePoint {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
userId String @map("user_id")
|
||||
key String
|
||||
value Float @default(0)
|
||||
@@ -878,7 +876,7 @@ model NationBet {
|
||||
}
|
||||
|
||||
model InheritanceLog {
|
||||
id Int @id @default(autoincrement())
|
||||
id BigInt @id @default(autoincrement())
|
||||
legacyId Int? @unique @map("legacy_id")
|
||||
userId String @map("user_id")
|
||||
serverId String? @map("server_id")
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE "kakao_identity_link_history" (
|
||||
"id" TEXT NOT NULL,
|
||||
"user_id" TEXT NOT NULL,
|
||||
"previous_oauth_id" TEXT NOT NULL,
|
||||
"next_oauth_id" TEXT NOT NULL,
|
||||
"authorization" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "kakao_identity_link_history_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
CREATE INDEX "kakao_identity_link_history_previous_oauth_id_created_at_idx" ON "kakao_identity_link_history"("previous_oauth_id", "created_at");
|
||||
CREATE INDEX "kakao_identity_link_history_user_id_created_at_idx" ON "kakao_identity_link_history"("user_id", "created_at");
|
||||
@@ -126,6 +126,20 @@ model AppUser {
|
||||
@@map("app_user")
|
||||
}
|
||||
|
||||
// 교체 이력을 보존하며 이전 ID는 같은 서비스 계정만 다시 연결할 수 있다.
|
||||
model KakaoIdentityLinkHistory {
|
||||
id String @id @default(uuid())
|
||||
userId String @map("user_id")
|
||||
previousOauthId String @map("previous_oauth_id")
|
||||
nextOauthId String @map("next_oauth_id")
|
||||
authorization String
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@index([previousOauthId, createdAt])
|
||||
@@index([userId, createdAt])
|
||||
@@map("kakao_identity_link_history")
|
||||
}
|
||||
|
||||
model RetiredKakaoIdentity {
|
||||
id String @id @default(uuid())
|
||||
oauthId String @unique @map("oauth_id")
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Keep all existing row IDs and the current sequence position, including an
|
||||
-- exhausted int4 sequence. Widen both ends; changing the sequence alone leaves
|
||||
-- INSERTs failing with integer overflow. Never rewind or cycle production IDs.
|
||||
BEGIN;
|
||||
ALTER TABLE "rank_data" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "rank_data_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- High churn queues/upserts and append-only logs need lifetime IDs, independent
|
||||
-- of live row count. Keep logical keys, values and sequence positions intact.
|
||||
BEGIN;
|
||||
ALTER TABLE "general_turn" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "general_turn_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "nation_turn" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "nation_turn_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "general_access_log" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "general_access_log_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "diplomacy" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "diplomacy_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "inheritance_point" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "inheritance_point_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "log_entry" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "log_entry_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "error_log" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "error_log_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "inheritance_log" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "inheritance_log_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "traffic_period" ALTER COLUMN "id" TYPE BIGINT;
|
||||
ALTER SEQUENCE "traffic_period_id_seq" AS BIGINT NO MAXVALUE NO CYCLE;
|
||||
ALTER TABLE "traffic_period_general" ALTER COLUMN "period_id" TYPE BIGINT;
|
||||
COMMIT;
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
-- Queue position and revision/lease are the domain identity. The unused ID was
|
||||
-- regenerated on every transactional delete/create, consuming 30/12 numbers.
|
||||
-- Reuse the existing proven unique indexes; keep every command and timestamp.
|
||||
BEGIN;
|
||||
ALTER TABLE "general_turn" DROP CONSTRAINT "general_turn_pkey";
|
||||
ALTER TABLE "general_turn" ADD CONSTRAINT "general_turn_pkey"
|
||||
PRIMARY KEY USING INDEX "general_turn_general_id_turn_idx_key";
|
||||
ALTER TABLE "general_turn" DROP COLUMN "id";
|
||||
ALTER TABLE "nation_turn" DROP CONSTRAINT "nation_turn_pkey";
|
||||
ALTER TABLE "nation_turn" ADD CONSTRAINT "nation_turn_pkey"
|
||||
PRIMARY KEY USING INDEX "nation_turn_nation_id_officer_level_turn_idx_key";
|
||||
ALTER TABLE "nation_turn" DROP COLUMN "id";
|
||||
COMMIT;
|
||||
@@ -0,0 +1,173 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import pg from 'pg';
|
||||
|
||||
const sourceUrl = process.env.RANK_DATA_MIGRATION_TEST_DATABASE_URL;
|
||||
if (!sourceUrl) throw new Error('RANK_DATA_MIGRATION_TEST_DATABASE_URL is required (isolated development DB only)');
|
||||
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const targets = ['20261114000000_rank_data_bigint_id', '20261114010000_high_churn_bigint_ids'];
|
||||
const fixtures = [
|
||||
['rank_data', 'general_id, nation_id, type, value', "7, 3, 'warnum', 19"],
|
||||
['general_turn', 'general_id, turn_idx, action_code', "7, 0, 'fixture'"],
|
||||
['nation_turn', 'nation_id, officer_level, turn_idx, action_code', "3, 12, 0, 'fixture'"],
|
||||
[
|
||||
'traffic_period',
|
||||
'world_state_id, year, month, started_at, last_refresh',
|
||||
"1, 200, 1, '2026-11-14', '2026-11-14'",
|
||||
],
|
||||
['general_access_log', 'general_id', '7'],
|
||||
['diplomacy', 'src_nation_id, dest_nation_id, state_code', '3, 4, 0'],
|
||||
['inheritance_point', 'user_id, key, value', "'fixture-user', 'previous', 123"],
|
||||
['log_entry', 'scope, category, year, month, text', "'SYSTEM', 'HISTORY', 200, 1, 'fixture'"],
|
||||
['error_log', 'category, message', "'fixture', 'fixture'"],
|
||||
['inheritance_log', 'user_id, year, month, text', "'fixture-user', 200, 1, 'fixture'"],
|
||||
];
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'rank-bigint-migration-'));
|
||||
const schema = `rank_bigint_upgrade_${randomUUID().replaceAll('-', '')}`;
|
||||
const freshSchema = `${schema}_fresh`;
|
||||
const client = new pg.Client({ connectionString: sourceUrl });
|
||||
const config = path.join(packageRoot, `.rank-bigint-${process.pid}.config.mjs`);
|
||||
const url = new URL(sourceUrl);
|
||||
const deploy = (schemaName) => {
|
||||
url.searchParams.set('schema', schemaName);
|
||||
const result = spawnSync('pnpm', ['exec', 'prisma', 'migrate', 'deploy', '--config', config], {
|
||||
cwd: packageRoot,
|
||||
env: { ...process.env, DATABASE_URL: url.href },
|
||||
encoding: 'utf8',
|
||||
});
|
||||
if (result.status !== 0) throw new Error(`Migration failed (exit ${result.status}); datasource output suppressed`);
|
||||
};
|
||||
const snapshots = new Map();
|
||||
const readIndexes = async (table) =>
|
||||
(
|
||||
await client.query(
|
||||
'SELECT indexname, indexdef FROM pg_indexes WHERE schemaname=$1 AND tablename=$2 ORDER BY indexname',
|
||||
[schema, table]
|
||||
)
|
||||
).rows;
|
||||
try {
|
||||
await fs.cp(path.join(packageRoot, 'prisma'), path.join(temp, 'prisma'), { recursive: true });
|
||||
for (const name of await fs.readdir(path.join(temp, 'prisma', 'migrations'))) {
|
||||
if (/^\d/.test(name) && name > targets.at(-1)) {
|
||||
await fs.rm(path.join(temp, 'prisma', 'migrations', name), { recursive: true });
|
||||
}
|
||||
}
|
||||
for (const target of targets) await fs.rm(path.join(temp, 'prisma', 'migrations', target), { recursive: true });
|
||||
await fs.writeFile(
|
||||
config,
|
||||
`export default { schema: ${JSON.stringify(path.join(temp, 'prisma/game.prisma'))}, datasource: { url: process.env.DATABASE_URL } };\n`
|
||||
);
|
||||
await client.connect();
|
||||
// UUID schemas belong only to this invocation; caller's schema is never changed.
|
||||
await client.query(`CREATE SCHEMA "${schema}"`);
|
||||
await client.query(`CREATE SCHEMA "${freshSchema}"`);
|
||||
deploy(schema);
|
||||
await client.query(`SET search_path TO "${schema}", public`);
|
||||
await client.query(`INSERT INTO world_state(id, scenario_code, current_year, current_month, tick_seconds, updated_at)
|
||||
VALUES(1, 'fixture', 200, 1, 600, CURRENT_TIMESTAMP)`);
|
||||
for (const [table, columns, values] of fixtures) {
|
||||
await client.query(`INSERT INTO "${table}" (id, ${columns}) VALUES(2147483647, ${values})`);
|
||||
await client.query(`SELECT setval('${table}_id_seq', 2147483647)`);
|
||||
await assert.rejects(client.query(`SELECT nextval('${table}_id_seq')`), { code: '2200H' });
|
||||
snapshots.set(table, {
|
||||
rows: (await client.query(`SELECT * FROM "${table}" ORDER BY id`)).rows,
|
||||
indexes: await readIndexes(table),
|
||||
});
|
||||
}
|
||||
await client.query(`INSERT INTO traffic_period_general(period_id, general_id, refresh, last_refresh)
|
||||
VALUES(2147483647, 7, 2, CURRENT_TIMESTAMP)`);
|
||||
const trafficMembers = (await client.query('SELECT * FROM traffic_period_general')).rows;
|
||||
for (const target of targets)
|
||||
await fs.cp(
|
||||
path.join(packageRoot, 'prisma', 'migrations', target),
|
||||
path.join(temp, 'prisma', 'migrations', target),
|
||||
{ recursive: true }
|
||||
);
|
||||
deploy(schema);
|
||||
for (const [table] of fixtures) {
|
||||
const before = snapshots.get(table);
|
||||
const after = (await client.query(`SELECT * FROM "${table}" ORDER BY id`)).rows;
|
||||
assert.deepEqual(
|
||||
after.map((row) => ({ ...row, id: Number(row.id) })),
|
||||
before.rows
|
||||
);
|
||||
assert.deepEqual(await readIndexes(table), before.indexes);
|
||||
assert.equal((await client.query(`SELECT last_value FROM "${table}_id_seq"`)).rows[0].last_value, '2147483647');
|
||||
assert.equal(
|
||||
(
|
||||
await client.query(
|
||||
"SELECT data_type FROM information_schema.columns WHERE table_schema=$1 AND table_name=$2 AND column_name='id'",
|
||||
[schema, table]
|
||||
)
|
||||
).rows[0].data_type,
|
||||
'bigint'
|
||||
);
|
||||
assert.deepEqual(
|
||||
(
|
||||
await client.query(
|
||||
'SELECT data_type, max_value::text, cycle FROM pg_sequences WHERE schemaname=$1 AND sequencename=$2',
|
||||
[schema, `${table}_id_seq`]
|
||||
)
|
||||
).rows[0],
|
||||
{ data_type: 'bigint', max_value: '9223372036854775807', cycle: false }
|
||||
);
|
||||
assert.equal((await client.query(`SELECT nextval('${table}_id_seq')`)).rows[0].nextval, '2147483648');
|
||||
}
|
||||
assert.equal(
|
||||
(await client.query("INSERT INTO rank_data(general_id, type) VALUES(8, 'warnum') RETURNING id")).rows[0].id,
|
||||
'2147483649'
|
||||
);
|
||||
await assert.rejects(client.query("INSERT INTO rank_data(general_id, type) VALUES(8, 'warnum')"), {
|
||||
code: '23505',
|
||||
});
|
||||
assert.deepEqual(
|
||||
(await client.query('SELECT * FROM traffic_period_general')).rows.map((row) => ({
|
||||
...row,
|
||||
period_id: Number(row.period_id),
|
||||
})),
|
||||
trafficMembers
|
||||
);
|
||||
await assert.rejects(
|
||||
client.query(`INSERT INTO traffic_period_general(period_id, general_id, last_refresh)
|
||||
VALUES(999, 8, CURRENT_TIMESTAMP)`),
|
||||
{ code: '23503' }
|
||||
);
|
||||
await client.query('BEGIN');
|
||||
await client.query('DELETE FROM traffic_period WHERE id=2147483647');
|
||||
assert.equal((await client.query('SELECT * FROM traffic_period_general')).rowCount, 0);
|
||||
await client.query('ROLLBACK');
|
||||
const migrations = (
|
||||
await client.query('SELECT migration_name, checksum FROM _prisma_migrations ORDER BY migration_name')
|
||||
).rows;
|
||||
deploy(schema);
|
||||
assert.deepEqual(
|
||||
(await client.query('SELECT migration_name, checksum FROM _prisma_migrations ORDER BY migration_name')).rows,
|
||||
migrations
|
||||
);
|
||||
deploy(freshSchema);
|
||||
await client.query(`SET search_path TO "${freshSchema}", public`);
|
||||
await client.query(`INSERT INTO world_state(id, scenario_code, current_year, current_month, tick_seconds, updated_at)
|
||||
VALUES(1, 'fixture', 200, 1, 600, CURRENT_TIMESTAMP)`);
|
||||
for (const [table, columns, values] of fixtures) {
|
||||
assert.equal(
|
||||
(await client.query(`INSERT INTO "${table}" (${columns}) VALUES(${values}) RETURNING id`)).rows[0].id,
|
||||
'1'
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`PASS: ${fixtures.length} exhausted int4 tables upgraded; rows/IDs/indexes preserved, bigint allocation, unique constraint, deploy no-op, fresh full migration`
|
||||
);
|
||||
} finally {
|
||||
await client.query('SET search_path TO public').catch(() => {});
|
||||
await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`).catch(() => {});
|
||||
await client.query(`DROP SCHEMA IF EXISTS "${freshSchema}" CASCADE`).catch(() => {});
|
||||
await client.end();
|
||||
await fs.rm(config, { force: true });
|
||||
await fs.rm(temp, { recursive: true });
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import pg from 'pg';
|
||||
|
||||
const sourceUrl = process.env.RESERVED_TURN_MIGRATION_TEST_DATABASE_URL;
|
||||
if (!sourceUrl) throw new Error('RESERVED_TURN_MIGRATION_TEST_DATABASE_URL is required (isolated development DB only)');
|
||||
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const target = '20261114020000_reserved_turn_slot_primary_keys';
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'reserved-slot-migration-'));
|
||||
const schema = `reserved_slot_${randomUUID().replaceAll('-', '')}`;
|
||||
const fresh = `${schema}_fresh`;
|
||||
const config = path.join(packageRoot, `.reserved-slot-${process.pid}.config.mjs`);
|
||||
const client = new pg.Client({ connectionString: sourceUrl });
|
||||
const url = new URL(sourceUrl);
|
||||
const deploy = (name) => {
|
||||
url.searchParams.set('schema', name);
|
||||
const result = spawnSync('pnpm', ['exec', 'prisma', 'migrate', 'deploy', '--config', config], {
|
||||
cwd: packageRoot,
|
||||
env: { ...process.env, DATABASE_URL: url.href },
|
||||
encoding: 'utf8',
|
||||
});
|
||||
if (result.status !== 0) throw new Error(`Migration failed (exit ${result.status}); datasource output suppressed`);
|
||||
};
|
||||
const snapshot = async () => ({
|
||||
general: (
|
||||
await client.query(
|
||||
'SELECT general_id,turn_idx,action_code,arg,created_at FROM general_turn ORDER BY general_id,turn_idx'
|
||||
)
|
||||
).rows,
|
||||
nation: (
|
||||
await client.query(
|
||||
'SELECT nation_id,officer_level,turn_idx,action_code,arg,created_at FROM nation_turn ORDER BY nation_id,officer_level,turn_idx'
|
||||
)
|
||||
).rows,
|
||||
generalRevision: (await client.query('SELECT * FROM general_turn_revision ORDER BY general_id')).rows,
|
||||
nationRevision: (await client.query('SELECT * FROM nation_turn_revision ORDER BY nation_id,officer_level')).rows,
|
||||
});
|
||||
const assertKeys = async (name) => {
|
||||
assert.equal(
|
||||
(
|
||||
await client.query(
|
||||
"SELECT count(*)::int AS n FROM information_schema.columns WHERE table_schema=$1 AND table_name IN ('general_turn','nation_turn') AND column_name='id'",
|
||||
[name]
|
||||
)
|
||||
).rows[0].n,
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await client.query(
|
||||
"SELECT count(*)::int AS n FROM pg_sequences WHERE schemaname=$1 AND sequencename IN ('general_turn_id_seq','nation_turn_id_seq')",
|
||||
[name]
|
||||
)
|
||||
).rows[0].n,
|
||||
0
|
||||
);
|
||||
assert.deepEqual(
|
||||
(
|
||||
await client.query(
|
||||
"SELECT t.relname,pg_get_constraintdef(c.oid) AS definition FROM pg_constraint c JOIN pg_class t ON c.conrelid=t.oid JOIN pg_namespace n ON t.relnamespace=n.oid WHERE n.nspname=$1 AND c.contype='p' AND t.relname IN ('general_turn','nation_turn') ORDER BY t.relname",
|
||||
[name]
|
||||
)
|
||||
).rows,
|
||||
[
|
||||
{ relname: 'general_turn', definition: 'PRIMARY KEY (general_id, turn_idx)' },
|
||||
{ relname: 'nation_turn', definition: 'PRIMARY KEY (nation_id, officer_level, turn_idx)' },
|
||||
]
|
||||
);
|
||||
};
|
||||
try {
|
||||
await fs.cp(path.join(packageRoot, 'prisma'), path.join(temp, 'prisma'), { recursive: true });
|
||||
await fs.rm(path.join(temp, 'prisma', 'migrations', target), { recursive: true });
|
||||
await fs.writeFile(
|
||||
config,
|
||||
`export default { schema: ${JSON.stringify(path.join(temp, 'prisma/game.prisma'))}, datasource: { url: process.env.DATABASE_URL } };\n`
|
||||
);
|
||||
await client.connect();
|
||||
await client.query(`CREATE SCHEMA "${schema}"`);
|
||||
await client.query(`CREATE SCHEMA "${fresh}"`);
|
||||
deploy(schema);
|
||||
await client.query(`SET search_path TO "${schema}", public`);
|
||||
await client.query(
|
||||
`INSERT INTO general_turn(id,general_id,turn_idx,action_code,arg,created_at) VALUES(3000000001,7,0,'che_훈련','{"x":1}','2026-11-14'),(3000000002,7,1,'휴식','{}','2026-11-14')`
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO nation_turn(id,nation_id,officer_level,turn_idx,action_code,arg,created_at) VALUES(3000000003,3,12,0,'che_포상','{"amount":10}','2026-11-14'),(3000000004,3,10,0,'휴식','{}','2026-11-14')`
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO general_turn_revision(general_id,revision,lease_owner,lease_expires_at,updated_at) VALUES(7,29,'fixture-daemon','2026-11-15','2026-11-14')`
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO nation_turn_revision(nation_id,officer_level,revision,lease_owner,lease_expires_at,updated_at) VALUES(3,12,41,'fixture-daemon','2026-11-15','2026-11-14')`
|
||||
);
|
||||
const before = await snapshot();
|
||||
await fs.cp(
|
||||
path.join(packageRoot, 'prisma', 'migrations', target),
|
||||
path.join(temp, 'prisma', 'migrations', target),
|
||||
{ recursive: true }
|
||||
);
|
||||
deploy(schema);
|
||||
assert.deepEqual(await snapshot(), before);
|
||||
await assertKeys(schema);
|
||||
await assert.rejects(
|
||||
client.query("INSERT INTO general_turn(general_id,turn_idx,action_code) VALUES(7,0,'duplicate')"),
|
||||
{ code: '23505' }
|
||||
);
|
||||
await assert.rejects(
|
||||
client.query(
|
||||
"INSERT INTO nation_turn(nation_id,officer_level,turn_idx,action_code) VALUES(3,12,0,'duplicate')"
|
||||
),
|
||||
{ code: '23505' }
|
||||
);
|
||||
await client.query('BEGIN');
|
||||
await client.query('DELETE FROM general_turn WHERE general_id=7');
|
||||
await client.query("INSERT INTO general_turn(general_id,turn_idx,action_code) VALUES(7,0,'replacement')");
|
||||
await client.query('ROLLBACK');
|
||||
assert.deepEqual(await snapshot(), before);
|
||||
const migrations = (
|
||||
await client.query('SELECT migration_name,checksum FROM _prisma_migrations ORDER BY migration_name')
|
||||
).rows;
|
||||
deploy(schema);
|
||||
assert.deepEqual(
|
||||
(await client.query('SELECT migration_name,checksum FROM _prisma_migrations ORDER BY migration_name')).rows,
|
||||
migrations
|
||||
);
|
||||
deploy(fresh);
|
||||
await client.query(`SET search_path TO "${fresh}", public`);
|
||||
await assertKeys(fresh);
|
||||
await client.query("INSERT INTO general_turn(general_id,turn_idx,action_code) VALUES(7,0,'휴식')");
|
||||
await client.query("INSERT INTO nation_turn(nation_id,officer_level,turn_idx,action_code) VALUES(3,12,0,'휴식')");
|
||||
console.log(
|
||||
'PASS: populated predecessor and fresh migration, command/arg/timestamp/revision/lease preservation, natural PK uniqueness, queue replacement rollback, removed sequences, deploy no-op'
|
||||
);
|
||||
} finally {
|
||||
await client.query('SET search_path TO public').catch(() => {});
|
||||
await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`).catch(() => {});
|
||||
await client.query(`DROP SCHEMA IF EXISTS "${fresh}" CASCADE`).catch(() => {});
|
||||
await client.end();
|
||||
await fs.rm(config, { force: true });
|
||||
await fs.rm(temp, { recursive: true });
|
||||
}
|
||||
@@ -16,3 +16,4 @@ export * from './messageEnvelope.js';
|
||||
export * from './webPushOutbox.js';
|
||||
export * from './playAuditBestEffort.js';
|
||||
export * from './playAuditDecisionCodec.js';
|
||||
export * from './stableRowId.js';
|
||||
@@ -0,0 +1,29 @@
|
||||
import { GamePrisma } from './gamePrisma.js';
|
||||
|
||||
/** Internal natural-key records retain their identity across ordinary updates. */
|
||||
export const upsertWithoutSequence = async <Where, Update, Create>(
|
||||
delegate: {
|
||||
update(args: { where: Where; data: Update }): PromiseLike<object>;
|
||||
upsert(args: { where: Where; update: Update; create: Create }): PromiseLike<object>;
|
||||
},
|
||||
args: { where: Where; update: Update; create: Create }
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await delegate.update({ where: args.where, data: args.update });
|
||||
} catch (error) {
|
||||
if (!(error instanceof GamePrisma.PrismaClientKnownRequestError) || error.code !== 'P2025') throw error;
|
||||
// A missing row is an application-level Prisma result, not a failed SQL
|
||||
// statement. The surrounding transaction remains usable. A competing
|
||||
// creator is still handled atomically by the original native upsert.
|
||||
await delegate.upsert(args);
|
||||
}
|
||||
};
|
||||
|
||||
export type StableIdTable = 'general_access_log' | 'traffic_period' | 'rank_data' | 'inheritance_point' | 'vote';
|
||||
|
||||
/** Only new natural keys allocate an ID; values and identifiers stay separate. */
|
||||
export const existingRowIdOrNext = (table: StableIdTable, predicate: GamePrisma.Sql): GamePrisma.Sql =>
|
||||
GamePrisma.sql`COALESCE(
|
||||
(SELECT stable_id."id" FROM ${GamePrisma.raw(`"${table}"`)} AS stable_id WHERE ${predicate}),
|
||||
nextval(pg_get_serial_sequence(${table}, 'id'))
|
||||
)`;
|
||||
@@ -0,0 +1,151 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createGamePostgresConnector, GamePrisma, type GamePrismaClient } from '../src/gamePrisma.js';
|
||||
import { existingRowIdOrNext, upsertWithoutSequence } from '../src/stableRowId.js';
|
||||
|
||||
const databaseUrl = process.env.IMMEDIATE_ACTION_DATABASE_URL;
|
||||
const generalId = 7_329;
|
||||
const userId = 'stable-id-fixture';
|
||||
|
||||
describe.skipIf(!databaseUrl)('natural-key ID persistence on PostgreSQL', () => {
|
||||
let db: GamePrismaClient;
|
||||
let close: () => Promise<void>;
|
||||
const sequence = async (table: 'rank_data' | 'inheritance_point'): Promise<bigint> =>
|
||||
(
|
||||
await db.$queryRaw<
|
||||
Array<{ value: bigint }>
|
||||
>`SELECT pg_sequence_last_value(pg_get_serial_sequence(${table}, 'id')::regclass) AS value`
|
||||
)[0]!.value;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!new URL(databaseUrl!).searchParams.get('schema')?.endsWith('immediate_action_integration')) {
|
||||
throw new Error('Dedicated immediate action schema is required');
|
||||
}
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||
await connector.connect();
|
||||
db = connector.prisma;
|
||||
close = () => connector.disconnect();
|
||||
await db.rankData.deleteMany({ where: { generalId } });
|
||||
await db.inheritancePoint.deleteMany({ where: { userId } });
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (db) {
|
||||
await db.rankData.deleteMany({ where: { generalId } });
|
||||
await db.inheritancePoint.deleteMany({ where: { userId } });
|
||||
}
|
||||
await close?.();
|
||||
});
|
||||
|
||||
it('creates missing rows inside the transaction and retains identity on replace and increment', async () => {
|
||||
await db.$transaction(async (tx) => {
|
||||
await upsertWithoutSequence(tx.rankData, {
|
||||
where: { generalId_type: { generalId, type: 'stable_rank' } },
|
||||
update: { value: 11 },
|
||||
create: { generalId, type: 'stable_rank', value: 11 },
|
||||
});
|
||||
await upsertWithoutSequence(tx.inheritancePoint, {
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
update: { value: 100 },
|
||||
create: { userId, key: 'previous', value: 100 },
|
||||
});
|
||||
});
|
||||
const original = await db.rankData.findUniqueOrThrow({
|
||||
where: { generalId_type: { generalId, type: 'stable_rank' } },
|
||||
});
|
||||
const before = await sequence('rank_data');
|
||||
for (let index = 0; index < 5; index++)
|
||||
await db.$transaction((tx) =>
|
||||
upsertWithoutSequence(tx.rankData, {
|
||||
where: { generalId_type: { generalId, type: 'stable_rank' } },
|
||||
update: { value: { increment: 1 }, nationId: 3 },
|
||||
create: { generalId, type: 'stable_rank', value: 1, nationId: 3 },
|
||||
})
|
||||
);
|
||||
expect(await db.rankData.findUniqueOrThrow({ where: { id: original.id } })).toMatchObject({
|
||||
id: original.id,
|
||||
value: 16,
|
||||
nationId: 3,
|
||||
});
|
||||
expect(await sequence('rank_data')).toBe(before);
|
||||
});
|
||||
|
||||
it('serializes concurrent updates without losing increments or allocating IDs', async () => {
|
||||
const before = await sequence('rank_data');
|
||||
await Promise.all(
|
||||
Array.from({ length: 12 }, () =>
|
||||
db.$transaction((tx) =>
|
||||
upsertWithoutSequence(tx.rankData, {
|
||||
where: { generalId_type: { generalId, type: 'stable_rank' } },
|
||||
update: { value: { increment: 1 } },
|
||||
create: { generalId, type: 'stable_rank', value: 1 },
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
expect(
|
||||
(await db.rankData.findUniqueOrThrow({ where: { generalId_type: { generalId, type: 'stable_rank' } } }))
|
||||
.value
|
||||
).toBe(28);
|
||||
expect(await sequence('rank_data')).toBe(before);
|
||||
// New-key races still converge through the original ON CONFLICT upsert.
|
||||
await Promise.all(
|
||||
Array.from({ length: 6 }, () =>
|
||||
db.$transaction((tx) =>
|
||||
upsertWithoutSequence(tx.rankData, {
|
||||
where: { generalId_type: { generalId, type: 'stable_race' } },
|
||||
update: { value: { increment: 1 } },
|
||||
create: { generalId, type: 'stable_race', value: 1 },
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
expect(
|
||||
(await db.rankData.findUniqueOrThrow({ where: { generalId_type: { generalId, type: 'stable_race' } } }))
|
||||
.value
|
||||
).toBe(6);
|
||||
});
|
||||
|
||||
it('keeps raw refund increments atomic and does not consume an ID for an existing point row', async () => {
|
||||
const point = await db.inheritancePoint.findUniqueOrThrow({
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
});
|
||||
const before = await sequence('inheritance_point');
|
||||
await Promise.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
db.$executeRaw(GamePrisma.sql`
|
||||
INSERT INTO inheritance_point(id,user_id,key,value,updated_at)
|
||||
VALUES(${existingRowIdOrNext('inheritance_point', GamePrisma.sql`stable_id.user_id=${userId} AND stable_id.key='previous'`)},${userId},'previous',1,CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(user_id,key) DO UPDATE SET value=inheritance_point.value+EXCLUDED.value
|
||||
`)
|
||||
)
|
||||
);
|
||||
expect(await db.inheritancePoint.findUniqueOrThrow({ where: { id: point.id } })).toMatchObject({ value: 108 });
|
||||
expect(await sequence('inheritance_point')).toBe(before);
|
||||
});
|
||||
|
||||
it('preserves rollback and propagates validation/constraint errors without creating a replacement row', async () => {
|
||||
const where = { generalId_type: { generalId, type: 'stable_rank' } };
|
||||
const before = await db.rankData.findUniqueOrThrow({ where });
|
||||
const counter = await sequence('rank_data');
|
||||
await expect(
|
||||
db.$transaction(async (tx) => {
|
||||
await upsertWithoutSequence(tx.rankData, {
|
||||
where,
|
||||
update: { value: 99 },
|
||||
create: { generalId, type: 'stable_rank', value: 99 },
|
||||
});
|
||||
throw new Error('fixture abort');
|
||||
})
|
||||
).rejects.toThrow('fixture abort');
|
||||
expect(await db.rankData.findUniqueOrThrow({ where })).toEqual(before);
|
||||
await expect(
|
||||
upsertWithoutSequence(db.rankData, {
|
||||
where,
|
||||
update: { type: 'stable_race' },
|
||||
create: { generalId, type: 'stable_rank' },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'P2002' });
|
||||
expect(await sequence('rank_data')).toBe(counter);
|
||||
expect(await db.rankData.count({ where: { generalId } })).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"controllerProtocol": 2,
|
||||
"gatewaySchemaHead": "20261022000000_add_open_requests",
|
||||
"gameSchemaHead": "20261109000000_compact_play_audit_storage",
|
||||
"gatewaySchemaHead": "20261107000000_kakao_identity_link_history",
|
||||
"gameSchemaHead": "20261114020000_reserved_turn_slot_primary_keys",
|
||||
"components": ["gateway-api", "gateway-frontend", "release-controller", "game-api", "game-engine", "game-frontend"]
|
||||
}
|
||||
@@ -114,7 +114,7 @@ const loginAdminWithToken = async () => {
|
||||
username: requiredEnv('INITIAL_ADMIN_USERNAME'),
|
||||
credential,
|
||||
});
|
||||
if (result.status === 'otp') throw new Error('Admin login unexpectedly requires OTP.');
|
||||
if (result.status !== 'login') throw new Error(`Admin login requires ${result.status}.`);
|
||||
session.token = result.sessionToken;
|
||||
return { gateway, sessionToken: result.sessionToken };
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user