Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81e101ffef | ||
|
|
bc54b157c1 | ||
|
|
087517821e | ||
|
|
f36bc2c8d7 | ||
|
|
fd8145d6eb | ||
|
|
79de6d484c | ||
|
|
078b9aa205 | ||
|
|
c81d304073 | ||
|
|
d1cdf8a85f | ||
|
|
dcecb32ef4 | ||
|
|
257a2bea10 | ||
|
|
f16d33e34c | ||
|
|
da79013226 | ||
|
|
6a23e4ca08 | ||
|
|
8c877b4a6f |
No files matched your search
@@ -91,6 +91,9 @@ DAEMON_REQUEST_TIMEOUT_MS=5000
|
|||||||
# realtime은 벽시계 경과를 game tick으로 투영합니다. manual은 daemon이
|
# realtime은 벽시계 경과를 game tick으로 투영합니다. manual은 daemon이
|
||||||
# 다음 월 snapshot을 대기 없이 실행하며 테스트/장기 시뮬레이션에 사용합니다.
|
# 다음 월 snapshot을 대기 없이 실행하며 테스트/장기 시뮬레이션에 사용합니다.
|
||||||
GAME_CLOCK_MODE=realtime
|
GAME_CLOCK_MODE=realtime
|
||||||
|
# Optional Windows host boot identity. Key is a private file, never a VITE_* value.
|
||||||
|
# TURN_HOST_BOOT_URL=http://windows-private-address:17781/v1/boot-id
|
||||||
|
# TURN_HOST_BOOT_KEY_FILE=/run/secrets/host_boot_key
|
||||||
TRPC_PATH=/trpc
|
TRPC_PATH=/trpc
|
||||||
|
|
||||||
# Frontend public URLs
|
# Frontend public URLs
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ GAME_API_HOST=0.0.0.0
|
|||||||
GAME_API_PORT=14000
|
GAME_API_PORT=14000
|
||||||
PROFILE=hwe
|
PROFILE=hwe
|
||||||
SCENARIO=default
|
SCENARIO=default
|
||||||
|
# Optional Windows observation; unavailable or unconfigured service never blocks gameplay.
|
||||||
|
# TURN_HOST_BOOT_URL=http://windows-private-address:17781/v1/boot-id
|
||||||
|
# TURN_HOST_BOOT_KEY_FILE=/run/sammo-host-recovery/host_boot.key
|
||||||
KAKAO_REST_KEY=your-kakao-rest-key
|
KAKAO_REST_KEY=your-kakao-rest-key
|
||||||
KAKAO_ADMIN_KEY=your-kakao-admin-key
|
KAKAO_ADMIN_KEY=your-kakao-admin-key
|
||||||
KAKAO_REDIRECT_URI=https://example.com/oauth/kakao/callback
|
KAKAO_REDIRECT_URI=https://example.com/oauth/kakao/callback
|
||||||
@@ -89,6 +89,7 @@ web_modules/
|
|||||||
.env.local
|
.env.local
|
||||||
.env.ci
|
.env.ci
|
||||||
.env.ops
|
.env.ops
|
||||||
|
tools/host-recovery/*.key
|
||||||
tools/legacy-db-migration/migration-plan.json
|
tools/legacy-db-migration/migration-plan.json
|
||||||
tools/legacy-db-migration/secrets/
|
tools/legacy-db-migration/secrets/
|
||||||
|
|
||||||
|
|||||||
@@ -58,8 +58,13 @@ Gateway 자체 릴리스는 Gateway 프로세스 밖의 `release-controller`가
|
|||||||
Kakao 계정은 OAuth callback과 일반 비밀번호 로그인 모두에서 Kakao 고유 ID와
|
Kakao 계정은 OAuth callback과 일반 비밀번호 로그인 모두에서 Kakao 고유 ID와
|
||||||
현재 인증 이메일을 다시 확인합니다. 로컬 고유 ID 연결이 없지만 영구 보존된
|
현재 인증 이메일을 다시 확인합니다. 로컬 고유 ID 연결이 없지만 영구 보존된
|
||||||
이메일 계정이 있으면 자동 로그인하지 않고 그 계정에 연결할지 묻습니다. 기존
|
이메일 계정이 있으면 자동 로그인하지 않고 그 계정에 연결할지 묻습니다. 기존
|
||||||
계정 연결을 확인하면 이전 Kakao ID와 과거 talk proof를 교체하고 새
|
계정 연결은 새 “나와의 채팅” 숫자 코드 인증까지 끝난 뒤에만 저장하며, 그 전에는
|
||||||
“나와의 채팅” 숫자 코드로 다시 증명한 뒤에만 Gateway session을 발급합니다.
|
이전 연결과 비밀번호를 유지합니다. 일반 계정은 카카오가 인증한 동일 이메일로
|
||||||
|
관리자 승인 없이 복구하고, 기존 서비스 비밀번호로 확인하면 이메일이 달라도
|
||||||
|
새 카카오에 연결할 수 있습니다. 관리자 계정 교체에는 승인을 유지하며 다른 계정과의
|
||||||
|
연결·이메일 충돌은 자동 처리하지 않습니다. 새 교체부터 이전 Kakao ID는 원래 계정의
|
||||||
|
복구 이력으로 보존하여 같은 계정에만 다시 연결할 수 있습니다. 기존에 영구 폐기된
|
||||||
|
ID는 계속 차단합니다.
|
||||||
Kakao가 `already registered`를 반환했지만 보존 이메일 계정도 없으면 재가입
|
Kakao가 `already registered`를 반환했지만 보존 이메일 계정도 없으면 재가입
|
||||||
확인 뒤 신규 가입 form을 엽니다. 이미 로컬에 연결된 stable ID의 변경 이메일이
|
확인 뒤 신규 가입 form을 엽니다. 이미 로컬에 연결된 stable ID의 변경 이메일이
|
||||||
다른 계정에 있으면 기존처럼 충돌을 거부합니다.
|
다른 계정에 있으면 기존처럼 충돌을 거부합니다.
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export class ReadModelOutboxWorker implements ReadModelOutboxWakeup {
|
|||||||
this.leaseMs = normalizePositiveInteger(options.leaseMs, 30_000);
|
this.leaseMs = normalizePositiveInteger(options.leaseMs, 30_000);
|
||||||
this.retentionMs = normalizePositiveInteger(options.retentionMs, 24 * 60 * 60 * 1_000);
|
this.retentionMs = normalizePositiveInteger(options.retentionMs, 24 * 60 * 60 * 1_000);
|
||||||
this.pruneIntervalMs = normalizePositiveInteger(options.pruneIntervalMs, 60_000);
|
this.pruneIntervalMs = normalizePositiveInteger(options.pruneIntervalMs, 60_000);
|
||||||
this.pruneLimit = normalizePositiveInteger(options.pruneLimit, 100);
|
this.pruneLimit = Math.min(500, normalizePositiveInteger(options.pruneLimit, 500));
|
||||||
this.owner = options.owner ?? `game-api:${profileName}:${process.pid}:${randomUUID()}`;
|
this.owner = options.owner ?? `game-api:${profileName}:${process.pid}:${randomUUID()}`;
|
||||||
this.now = options.now ?? (() => new Date());
|
this.now = options.now ?? (() => new Date());
|
||||||
this.onError = options.onError ?? (() => undefined);
|
this.onError = options.onError ?? (() => undefined);
|
||||||
@@ -109,11 +109,17 @@ export class ReadModelOutboxWorker implements ReadModelOutboxWakeup {
|
|||||||
|
|
||||||
const now = this.now();
|
const now = this.now();
|
||||||
if (now.getTime() >= this.nextPruneAt) {
|
if (now.getTime() >= this.nextPruneAt) {
|
||||||
this.nextPruneAt = now.getTime() + this.pruneIntervalMs;
|
// backlog가 있으면 다음 dispatch에서도 이어서 정리한다. 평상시에는 낮은 빈도로 확인한다.
|
||||||
await pruneDeliveredReadModelOutbox(this.db, {
|
// 한 호출은 최대 10 batch/50ms이며 각 SQL도 최대 500행이다.
|
||||||
|
const started = performance.now();
|
||||||
|
for (let batch = 0; batch < 10; batch += 1) {
|
||||||
|
const deleted = await pruneDeliveredReadModelOutbox(this.db, {
|
||||||
deliveredBefore: new Date(now.getTime() - this.retentionMs),
|
deliveredBefore: new Date(now.getTime() - this.retentionMs),
|
||||||
limit: this.pruneLimit,
|
limit: this.pruneLimit,
|
||||||
});
|
});
|
||||||
|
this.nextPruneAt = deleted < this.pruneLimit ? now.getTime() + this.pruneIntervalMs : 0;
|
||||||
|
if (deleted < this.pruneLimit || performance.now() - started >= 50) break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { toSafeInteger } from '@sammo-ts/common';
|
||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -281,7 +282,7 @@ export const auctionRouter = router({
|
|||||||
callerAlias,
|
callerAlias,
|
||||||
remainPoint: point?.value ?? 0,
|
remainPoint: point?.value ?? 0,
|
||||||
recentLogs: recentLogs.map((log) => ({
|
recentLogs: recentLogs.map((log) => ({
|
||||||
id: log.id,
|
id: toSafeInteger(log.id),
|
||||||
text: log.text,
|
text: log.text,
|
||||||
createdAt: log.createdAt.toISOString(),
|
createdAt: log.createdAt.toISOString(),
|
||||||
})),
|
})),
|
||||||
@@ -444,7 +445,10 @@ export const auctionRouter = router({
|
|||||||
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
||||||
const nextCloseAt = new Date(result.closeAt);
|
const nextCloseAt = new Date(result.closeAt);
|
||||||
await ctx.redis.zAdd(timerKeys.timerKey, [
|
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 };
|
return { ok: true };
|
||||||
@@ -521,7 +525,10 @@ export const auctionRouter = router({
|
|||||||
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
||||||
const nextCloseAt = new Date(result.closeAt);
|
const nextCloseAt = new Date(result.closeAt);
|
||||||
await ctx.redis.zAdd(timerKeys.timerKey, [
|
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 };
|
return { ok: true };
|
||||||
@@ -659,7 +666,10 @@ export const auctionRouter = router({
|
|||||||
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
const timerKeys = buildAuctionTimerKeys(ctx.profile.name);
|
||||||
const nextCloseAt = new Date(result.closeAt);
|
const nextCloseAt = new Date(result.closeAt);
|
||||||
await ctx.redis.zAdd(timerKeys.timerKey, [
|
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 };
|
return { ok: true };
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
import { CLOCK_OPERATION_PERSISTENCE_LOCK, GamePrisma, acquireGameSchemaAdvisoryXactLock } from '@sammo-ts/infra';
|
import { CLOCK_OPERATION_PERSISTENCE_LOCK, GamePrisma, acquireGameSchemaAdvisoryXactLock } from '@sammo-ts/infra';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
@@ -223,7 +224,7 @@ export const bettingRouter = router({
|
|||||||
world.currentMonth,
|
world.currentMonth,
|
||||||
`${input.amount} 포인트를 베팅에 사용`
|
`${input.amount} 포인트를 베팅에 사용`
|
||||||
);
|
);
|
||||||
await ctx.db.rankData.upsert({
|
await upsertWithoutSequence(ctx.db.rankData, {
|
||||||
where: {
|
where: {
|
||||||
generalId_type: {
|
generalId_type: {
|
||||||
generalId: general.id,
|
generalId: general.id,
|
||||||
@@ -245,7 +246,7 @@ export const bettingRouter = router({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
await ctx.db.nationBet.upsert({
|
await upsertWithoutSequence(ctx.db.nationBet, {
|
||||||
where: {
|
where: {
|
||||||
bettingId_userId_selectionKey: {
|
bettingId_userId_selectionKey: {
|
||||||
bettingId: input.bettingId,
|
bettingId: input.bettingId,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { TRPCError } from '@trpc/server';
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { getBillByLevel, LogCategory, LogScope } from '@sammo-ts/logic';
|
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 type { GameApiContext } from '../../context.js';
|
||||||
import {
|
import {
|
||||||
@@ -588,10 +588,7 @@ export const getGeneralContext = async (ctx: GameApiContext) => {
|
|||||||
recentWar: general.recentWarTime?.toISOString() ?? null,
|
recentWar: general.recentWarTime?.toISOString() ?? null,
|
||||||
defenceTrain: settings.defence_train,
|
defenceTrain: settings.defence_train,
|
||||||
killTurn: readNumber(metaRecord.killturn ?? metaRecord.killTurn, 0),
|
killTurn: readNumber(metaRecord.killturn ?? metaRecord.killTurn, 0),
|
||||||
remainingMinutes: resolveRemainingMinutes(
|
remainingMinutes: resolveRemainingMinutes(general.turnTime, gameTime.now),
|
||||||
general.turnTime,
|
|
||||||
gameTime.now
|
|
||||||
),
|
|
||||||
crewTypeId: general.crewTypeId,
|
crewTypeId: general.crewTypeId,
|
||||||
crewTypeName: crewTypeDetails.get(general.crewTypeId)?.name ?? '-',
|
crewTypeName: crewTypeDetails.get(general.crewTypeId)?.name ?? '-',
|
||||||
crewTypeInfo: crewTypeDetails.get(general.crewTypeId) ?? null,
|
crewTypeInfo: crewTypeDetails.get(general.crewTypeId) ?? null,
|
||||||
@@ -916,7 +913,7 @@ export const generalRouter = router({
|
|||||||
return {
|
return {
|
||||||
type: input.type,
|
type: input.type,
|
||||||
logs: logs.map((entry) => ({
|
logs: logs.map((entry) => ({
|
||||||
id: entry.id,
|
id: toSafeInteger(entry.id),
|
||||||
text: entry.text,
|
text: entry.text,
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
@@ -966,9 +963,9 @@ export const generalRouter = router({
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
global: trimRecentRecords(global, input.lastGeneralRecordId),
|
global: trimRecentRecords(global.map(withSafeIntegerId), input.lastGeneralRecordId),
|
||||||
general: trimRecentRecords(general, input.lastGeneralRecordId),
|
general: trimRecentRecords(general.map(withSafeIntegerId), input.lastGeneralRecordId),
|
||||||
history: trimRecentRecords(history, input.lastWorldHistoryId),
|
history: trimRecentRecords(history.map(withSafeIntegerId), input.lastWorldHistoryId),
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
// 메인 화면은 SSE invalidation, 탭 복귀와 직접 갱신이 같은 read model을
|
// 메인 화면은 SSE invalidation, 탭 복귀와 직접 갱신이 같은 read model을
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { withSafeIntegerId } from '@sammo-ts/common';
|
||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -38,7 +39,6 @@ const BUFF_KEYS: InheritBuffType[] = [
|
|||||||
|
|
||||||
const UNIQUE_ITEM_SLOT_ORDER: readonly ItemSlot[] = ['horse', 'weapon', 'book', 'item'];
|
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 MIN_INHERIT_BUFF_LEVEL = 1;
|
||||||
const MAX_INHERIT_BUFF_LEVEL = 5;
|
const MAX_INHERIT_BUFF_LEVEL = 5;
|
||||||
|
|
||||||
@@ -283,7 +283,7 @@ export const inheritRouter = router({
|
|||||||
getLogs: authedProcedure
|
getLogs: authedProcedure
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
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 }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
@@ -300,7 +300,7 @@ export const inheritRouter = router({
|
|||||||
take: 30,
|
take: 30,
|
||||||
select: { id: true, year: true, month: true, text: true, createdAt: true },
|
select: { id: true, year: true, month: true, text: true, createdAt: true },
|
||||||
});
|
});
|
||||||
return logs;
|
return logs.map(withSafeIntegerId);
|
||||||
}),
|
}),
|
||||||
buyHiddenBuff: engineAuthedProcedure
|
buyHiddenBuff: engineAuthedProcedure
|
||||||
.input(
|
.input(
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { toSafeInteger } from '@sammo-ts/common';
|
||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -77,7 +78,7 @@ export const getGeneralLog = accessLimitAuthedInputProcedure(
|
|||||||
type: input.type,
|
type: input.type,
|
||||||
generalId: target.id,
|
generalId: target.id,
|
||||||
logs: logs.map((entry) => ({
|
logs: logs.map((entry) => ({
|
||||||
id: entry.id,
|
id: toSafeInteger(entry.id),
|
||||||
text: entry.text,
|
text: entry.text,
|
||||||
year: entry.year,
|
year: entry.year,
|
||||||
month: entry.month,
|
month: entry.month,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { withSafeIntegerId } from '@sammo-ts/common';
|
||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
|
|
||||||
import { asRecord } from '@sammo-ts/common';
|
import { asRecord } from '@sammo-ts/common';
|
||||||
@@ -129,6 +130,6 @@ export const getNationInfo = authedProcedure.query(async ({ ctx }) => {
|
|||||||
name: city.name,
|
name: city.name,
|
||||||
capital: city.id === nation.capitalCityId,
|
capital: city.id === nation.capitalCityId,
|
||||||
})),
|
})),
|
||||||
history,
|
history: history.map(withSafeIntegerId),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import type { GamePrisma } from '@sammo-ts/infra';
|
import { decodeAuditDecisionSteps, type GamePrisma } from '@sammo-ts/infra';
|
||||||
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld, zAuditMonth } from './shared.js';
|
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld, zAuditMonth } from './shared.js';
|
||||||
|
|
||||||
const zEffectivePolicy = z.object({
|
const zEffectivePolicy = z.object({
|
||||||
@@ -275,7 +275,7 @@ export const decisionDetail = auditProcedure
|
|||||||
decision: project(row),
|
decision: project(row),
|
||||||
chunks: chunks.slice(0, input.limit).map((chunk) => ({
|
chunks: chunks.slice(0, input.limit).map((chunk) => ({
|
||||||
ordinal: chunk.ordinal,
|
ordinal: chunk.ordinal,
|
||||||
steps: z.array(zStep).max(128).parse(chunk.steps),
|
steps: z.array(zStep).max(128).parse(decodeAuditDecisionSteps(chunk.steps)),
|
||||||
})),
|
})),
|
||||||
nextCursor:
|
nextCursor:
|
||||||
chunks.length && chunks.at(-1)!.ordinal + 1 < Math.ceil(row.stepCount / 128)
|
chunks.length && chunks.at(-1)!.ordinal + 1 < Math.ceil(row.stepCount / 128)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { toSafeInteger, withSafeIntegerId } from '@sammo-ts/common';
|
||||||
import { TRPCError } from '@trpc/server';
|
import { TRPCError } from '@trpc/server';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld } from './shared.js';
|
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld } from './shared.js';
|
||||||
@@ -53,8 +54,8 @@ export const generalLogs = auditProcedure
|
|||||||
...world,
|
...world,
|
||||||
type: input.type,
|
type: input.type,
|
||||||
coverage: world.serverId ? ('IDENTIFIED_LOGS_ONLY' as const) : ('IDENTITY_MISSING' as const),
|
coverage: world.serverId ? ('IDENTIFIED_LOGS_ONLY' as const) : ('IDENTITY_MISSING' as const),
|
||||||
items: rows.slice(0, input.limit),
|
items: rows.slice(0, input.limit).map(withSafeIntegerId),
|
||||||
nextCursor: rows.length > input.limit ? rows[input.limit - 1]!.id : null,
|
nextCursor: rows.length > input.limit ? toSafeInteger(rows[input.limit - 1]!.id) : null,
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { TRPCError } from '@trpc/server';
|
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 { LEGACY_DEFAULT_MAX_LEVEL, LogCategory, LogScope } from '@sammo-ts/logic';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -306,7 +306,7 @@ export const publicRouter = router({
|
|||||||
}
|
}
|
||||||
const snapshot = {
|
const snapshot = {
|
||||||
...map,
|
...map,
|
||||||
history,
|
history: history.map(withSafeIntegerId),
|
||||||
};
|
};
|
||||||
await ctx.redis.set(cacheKey, JSON.stringify(snapshot), { EX: PUBLIC_CACHE_TTL_SECONDS });
|
await ctx.redis.set(cacheKey, JSON.stringify(snapshot), { EX: PUBLIC_CACHE_TTL_SECONDS });
|
||||||
return snapshot;
|
return snapshot;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { createHash, randomUUID } from 'node:crypto';
|
import { createHash, randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
import { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit } from '@sammo-ts/common';
|
import { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit } from '@sammo-ts/common';
|
||||||
@@ -94,7 +95,13 @@ export const enqueueDeferredGeneralAccess = async (
|
|||||||
}
|
}
|
||||||
await redis.eval(ENQUEUE_SCRIPT, {
|
await redis.eval(ENQUEUE_SCRIPT, {
|
||||||
keys: [activeKey(profileName)],
|
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;
|
return true;
|
||||||
};
|
};
|
||||||
@@ -258,9 +265,10 @@ export const flushDeferredGeneralAccessBatch = async (
|
|||||||
),
|
),
|
||||||
missing_periods AS (
|
missing_periods AS (
|
||||||
INSERT INTO "traffic_period" (
|
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
|
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},
|
${worldState.id},
|
||||||
(missing_key / 12)::INTEGER,
|
(missing_key / 12)::INTEGER,
|
||||||
(missing_key % 12 + 1)::INTEGER,
|
(missing_key % 12 + 1)::INTEGER,
|
||||||
@@ -281,9 +289,10 @@ export const flushDeferredGeneralAccessBatch = async (
|
|||||||
),
|
),
|
||||||
period_upsert AS (
|
period_upsert AS (
|
||||||
INSERT INTO "traffic_period" (
|
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
|
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.id},
|
||||||
${worldState.currentYear},
|
${worldState.currentYear},
|
||||||
${worldState.currentMonth},
|
${worldState.currentMonth},
|
||||||
@@ -343,10 +352,11 @@ export const flushDeferredGeneralAccessBatch = async (
|
|||||||
),
|
),
|
||||||
access_updates AS (
|
access_updates AS (
|
||||||
INSERT INTO "general_access_log" (
|
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"
|
"refresh_score", "refresh_score_total"
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT
|
||||||
|
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = resolved."general_id"`)},
|
||||||
resolved."general_id",
|
resolved."general_id",
|
||||||
resolved."user_id",
|
resolved."user_id",
|
||||||
resolved."last_refresh",
|
resolved."last_refresh",
|
||||||
@@ -471,11 +481,9 @@ export class DeferredGeneralAccessWorker {
|
|||||||
await this.redis.del(key);
|
await this.redis.del(key);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await this.redis.set(
|
await this.redis.set(key, JSON.stringify({ nextAccessAt: state.nextAccessAt.toISOString() }), {
|
||||||
key,
|
PX: Math.max(1, state.nextAccessAt.getTime() - now.getTime()),
|
||||||
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 { asRecord, resolveAccessLimitLevel, resolveAccessRefreshLimit, type AccessLimitLevel } from '@sammo-ts/common';
|
||||||
import { acquireGameSchemaAdvisoryXactLock, GENERAL_ACCESS_PERSISTENCE_LOCK, GamePrisma } from '@sammo-ts/infra';
|
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 db.$transaction(async (transaction) => {
|
||||||
await acquireGameSchemaAdvisoryXactLock(transaction, GENERAL_ACCESS_PERSISTENCE_LOCK);
|
await acquireGameSchemaAdvisoryXactLock(transaction, GENERAL_ACCESS_PERSISTENCE_LOCK);
|
||||||
const periodKey = input.year * 12 + input.month - 1;
|
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`
|
GamePrisma.sql`
|
||||||
WITH latest_period AS (
|
WITH latest_period AS (
|
||||||
SELECT MAX(year * 12 + month - 1)::INTEGER AS period_key
|
SELECT MAX(year * 12 + month - 1)::INTEGER AS period_key
|
||||||
@@ -269,6 +270,7 @@ export const upsertGeneralAccess = async (
|
|||||||
RETURNING id
|
RETURNING id
|
||||||
)
|
)
|
||||||
INSERT INTO traffic_period (
|
INSERT INTO traffic_period (
|
||||||
|
id,
|
||||||
world_state_id,
|
world_state_id,
|
||||||
year,
|
year,
|
||||||
month,
|
month,
|
||||||
@@ -277,6 +279,7 @@ export const upsertGeneralAccess = async (
|
|||||||
refresh
|
refresh
|
||||||
)
|
)
|
||||||
VALUES (
|
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.worldStateId},
|
||||||
${input.year},
|
${input.year},
|
||||||
${input.month},
|
${input.month},
|
||||||
@@ -341,6 +344,7 @@ export const upsertGeneralAccess = async (
|
|||||||
await transaction.$executeRaw(
|
await transaction.$executeRaw(
|
||||||
GamePrisma.sql`
|
GamePrisma.sql`
|
||||||
INSERT INTO general_access_log (
|
INSERT INTO general_access_log (
|
||||||
|
id,
|
||||||
general_id,
|
general_id,
|
||||||
user_id,
|
user_id,
|
||||||
last_refresh,
|
last_refresh,
|
||||||
@@ -350,6 +354,7 @@ export const upsertGeneralAccess = async (
|
|||||||
refresh_score_total
|
refresh_score_total
|
||||||
)
|
)
|
||||||
VALUES (
|
VALUES (
|
||||||
|
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = ${input.generalId}`)},
|
||||||
${input.generalId},
|
${input.generalId},
|
||||||
${input.userId},
|
${input.userId},
|
||||||
${input.now},
|
${input.now},
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { GamePrisma } from '@sammo-ts/infra';
|
import { GamePrisma } from '@sammo-ts/infra';
|
||||||
|
|
||||||
import type { GameApiContext } from '../context.js';
|
import type { GameApiContext } from '../context.js';
|
||||||
@@ -20,11 +21,13 @@ export const recordGeneralActivity = async (
|
|||||||
const written = await ctx.db.$executeRaw(
|
const written = await ctx.db.$executeRaw(
|
||||||
GamePrisma.sql`
|
GamePrisma.sql`
|
||||||
INSERT INTO general_access_log (
|
INSERT INTO general_access_log (
|
||||||
|
id,
|
||||||
general_id,
|
general_id,
|
||||||
user_id,
|
user_id,
|
||||||
last_action_at
|
last_action_at
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT
|
||||||
|
${existingRowIdOrNext('general_access_log', GamePrisma.sql`stable_id.general_id = "general".id`)},
|
||||||
id,
|
id,
|
||||||
${user.id},
|
${user.id},
|
||||||
${now}
|
${now}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||||
import { GamePrisma } from '@sammo-ts/infra';
|
import { GamePrisma } from '@sammo-ts/infra';
|
||||||
import {
|
import {
|
||||||
@@ -132,7 +133,7 @@ export const setInheritancePoint = async (
|
|||||||
key: InheritPointKey,
|
key: InheritPointKey,
|
||||||
value: number
|
value: number
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
await db.inheritancePoint.upsert({
|
await upsertWithoutSequence(db.inheritancePoint, {
|
||||||
where: {
|
where: {
|
||||||
userId_key: {
|
userId_key: {
|
||||||
userId,
|
userId,
|
||||||
|
|||||||
@@ -472,8 +472,10 @@ const sanitizeLegacyTurnArgString = (value: string): string => {
|
|||||||
if (stripped === '' || stripped === '0') {
|
if (stripped === '' || stripped === '0') {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
// Core의 Vue text와 formatLegacyLogHtml이 출력 시 &를 escape한다.
|
||||||
|
// Ref의 입력 단계 & 변환까지 적용하면 국호/예약 인자에 entity가 저장된다.
|
||||||
|
// <, > 중화는 로그의 legacy markup과 사용자 입력을 구분하기 위해 유지한다.
|
||||||
return stripped
|
return stripped
|
||||||
.replaceAll('&', '&')
|
|
||||||
.replaceAll('<', '<')
|
.replaceAll('<', '<')
|
||||||
.replaceAll('>', '>')
|
.replaceAll('>', '>')
|
||||||
.replace(/^[\p{Z}\p{C}]+|[\p{Z}\p{C}]+$/gu, '');
|
.replace(/^[\p{Z}\p{C}]+|[\p{Z}\p{C}]+$/gu, '');
|
||||||
|
|||||||
@@ -152,7 +152,29 @@ describe('turn command argument input', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('recursively sanitizes reserved command strings like Ref before command parsing', async () => {
|
it('preserves ampersands through reservation parsing and repeated sanitization', async () => {
|
||||||
|
const args = { nationName: '풍년F&B', nested: ['A&B', '&', '<img>'] };
|
||||||
|
expect(sanitizeReservedTurnArgs(args)).toEqual(args);
|
||||||
|
expect(sanitizeReservedTurnArgs(sanitizeReservedTurnArgs(args))).toEqual(args);
|
||||||
|
await expect(parseReservedTurnArgs('nation', 'che_국호변경', args)).resolves.toEqual({
|
||||||
|
nationName: '풍년F&B',
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
parseReservedTurnArgs('general', 'che_건국', {
|
||||||
|
nationName: '풍년F&B',
|
||||||
|
nationType: 'che_도적',
|
||||||
|
colorType: 0,
|
||||||
|
})
|
||||||
|
).resolves.toMatchObject({ nationName: '풍년F&B' });
|
||||||
|
// 반각 18자 판정에 &의 저장 길이가 끼어들지 않는다.
|
||||||
|
const maxWidthName = '가나다라마바사아&B';
|
||||||
|
expect(() => assertReservedTurnArgsPassLegacyBasicValidation({ nationName: maxWidthName })).not.toThrow();
|
||||||
|
await expect(parseReservedTurnArgs('nation', 'che_국호변경', { nationName: maxWidthName })).resolves.toEqual({
|
||||||
|
nationName: maxWidthName,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retains Ref character removal and angle-bracket neutralization before command parsing', async () => {
|
||||||
expect(
|
expect(
|
||||||
sanitizeReservedTurnArgs({
|
sanitizeReservedTurnArgs({
|
||||||
nationName: ' <신-국># ',
|
nationName: ' <신-국># ',
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
DeferredGeneralAccessWorker,
|
DeferredGeneralAccessWorker,
|
||||||
|
flushDeferredGeneralAccessBatch,
|
||||||
enqueueDeferredGeneralAccess,
|
enqueueDeferredGeneralAccess,
|
||||||
getDeferredGeneralAccessLimit,
|
getDeferredGeneralAccessLimit,
|
||||||
} from '../src/services/deferredGeneralAccess.js';
|
} from '../src/services/deferredGeneralAccess.js';
|
||||||
@@ -91,7 +92,7 @@ liveIntegration('deferred general access with PostgreSQL and Redis', () => {
|
|||||||
await redis.disconnect();
|
await redis.disconnect();
|
||||||
}
|
}
|
||||||
if (db) {
|
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.generalAccessLog.deleteMany({ where: { generalId } });
|
||||||
await db.general.deleteMany({ where: { id: generalId } });
|
await db.general.deleteMany({ where: { id: generalId } });
|
||||||
await db.worldState.deleteMany({ where: { id: worldStateId } });
|
await db.worldState.deleteMany({ where: { id: worldStateId } });
|
||||||
@@ -153,9 +154,19 @@ liveIntegration('deferred general access with PostgreSQL and Redis', () => {
|
|||||||
nextAccessAt,
|
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 worker.flushOnce();
|
||||||
await expect(db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).resolves.toMatchObject({
|
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 => ({
|
const endpointAuth = (roles = ['user']): GameSessionTokenPayload => ({
|
||||||
version: 1,
|
version: 1,
|
||||||
profile: `${yearbookProfile}:default`,
|
profile: yearbookProfile,
|
||||||
issuedAt: '2026-07-26T00:00:00.000Z',
|
issuedAt: '2026-07-26T00:00:00.000Z',
|
||||||
expiresAt: '2026-07-27T00:00:00.000Z',
|
expiresAt: '2026-07-27T00:00:00.000Z',
|
||||||
sessionId: `access-session-${endpointGeneralId}`,
|
sessionId: `access-session-${endpointGeneralId}`,
|
||||||
@@ -167,6 +167,9 @@ integration('general access tracking persistence', () => {
|
|||||||
scoreStartedAt: new Date('2026-07-26T03:00:00.000Z'),
|
scoreStartedAt: new Date('2026-07-26T03:00:00.000Z'),
|
||||||
};
|
};
|
||||||
await upsertGeneralAccess(db, { ...firstWindow, weight: 2 });
|
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(
|
await Promise.all(
|
||||||
Array.from({ length: 20 }, (_, index) =>
|
Array.from({ length: 20 }, (_, index) =>
|
||||||
upsertGeneralAccess(db, {
|
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({
|
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).toMatchObject({
|
||||||
userId: 'access-user-a',
|
userId: 'access-user-a',
|
||||||
refresh: 22,
|
refresh: 22,
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ const buildContext = (options: {
|
|||||||
inheritancePoint?: number;
|
inheritancePoint?: number;
|
||||||
inheritanceRows?: Array<{ key: string; value: number }>;
|
inheritanceRows?: Array<{ key: string; value: number }>;
|
||||||
rankRows?: Array<{ type: 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>;
|
configConst?: Record<string, unknown>;
|
||||||
scenarioCode?: string;
|
scenarioCode?: string;
|
||||||
configMap?: Record<string, unknown>;
|
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 () => {
|
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 createdAt = new Date('2026-07-26T00:00:00Z');
|
||||||
const fixture = buildContext({
|
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([
|
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({
|
expect(fixture.inheritanceLogFindMany).toHaveBeenCalledWith({
|
||||||
where: { userId: 'user-1' },
|
where: { userId: 'user-1' },
|
||||||
@@ -478,23 +478,26 @@ describe('inherit router actor and permission boundaries', () => {
|
|||||||
const fixture = buildContext({ inheritanceLogs: [] });
|
const fixture = buildContext({ inheritanceLogs: [] });
|
||||||
const caller = appRouter.createCaller(fixture.context);
|
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({
|
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' },
|
orderBy: { id: 'desc' },
|
||||||
take: 30,
|
take: 30,
|
||||||
select: { id: true, year: true, month: true, text: true, createdAt: true },
|
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({});
|
const fixture = buildContext({});
|
||||||
|
|
||||||
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({ lastId })).rejects.toMatchObject({
|
await expect(appRouter.createCaller(fixture.context).inherit.getLogs({ lastId })).rejects.toMatchObject({
|
||||||
code: 'BAD_REQUEST',
|
code: 'BAD_REQUEST',
|
||||||
});
|
});
|
||||||
expect(fixture.inheritanceLogFindMany).not.toHaveBeenCalled();
|
expect(fixture.inheritanceLogFindMany).not.toHaveBeenCalled();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
it('delegates the authenticated actor and maps a missing-general daemon rejection', async () => {
|
it('delegates the authenticated actor and maps a missing-general daemon rejection', async () => {
|
||||||
const fixture = buildContext({
|
const fixture = buildContext({
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ type LogQuery = {
|
|||||||
select: { id: true; text: true; createdAt: true };
|
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,
|
auth,
|
||||||
profile: { id: 'che', name: 'che:default', scenario: 'default' },
|
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 () => {
|
it('caps an initial bucket at the legacy 15-row limit', async () => {
|
||||||
const rows = Array.from({ length: 16 }, (_, index) => ({
|
const rows = Array.from({ length: 16 }, (_, index) => ({
|
||||||
id: 100 - index,
|
id: 100 - index,
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import { afterAll, beforeAll, expect, it } from 'vitest';
|
|||||||
import fastify from 'fastify';
|
import fastify from 'fastify';
|
||||||
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
|
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
|
||||||
import { asRecord } from '@sammo-ts/common';
|
import { asRecord } from '@sammo-ts/common';
|
||||||
import { createGamePostgresConnector, createRedisConnector, GamePrisma } from '@sammo-ts/infra';
|
import {
|
||||||
|
decodeAuditDecisionSteps,
|
||||||
|
createGamePostgresConnector,
|
||||||
|
createRedisConnector,
|
||||||
|
GamePrisma,
|
||||||
|
} from '@sammo-ts/infra';
|
||||||
import { createTurnDaemonRuntime, seedScenarioToDatabase, type TurnDaemonRuntime } from '@sammo-ts/game-engine';
|
import { createTurnDaemonRuntime, seedScenarioToDatabase, type TurnDaemonRuntime } from '@sammo-ts/game-engine';
|
||||||
import { appRouter } from '../src/router.js';
|
import { appRouter } from '../src/router.js';
|
||||||
import { DatabaseTurnDaemonTransport } from '../src/daemon/databaseTransport.js';
|
import { DatabaseTurnDaemonTransport } from '../src/daemon/databaseTransport.js';
|
||||||
@@ -255,12 +260,10 @@ integration(
|
|||||||
include: { chunks: { orderBy: { ordinal: 'asc' } } },
|
include: { chunks: { orderBy: { ordinal: 'asc' } } },
|
||||||
});
|
});
|
||||||
const procedures = nationDecision.chunks.flatMap((chunk) =>
|
const procedures = nationDecision.chunks.flatMap((chunk) =>
|
||||||
Array.isArray(chunk.steps)
|
decodeAuditDecisionSteps(chunk.steps)
|
||||||
? chunk.steps
|
|
||||||
.map(asRecord)
|
.map(asRecord)
|
||||||
.filter((step) => step.kind === 'PROCEDURE_START')
|
.filter((step) => step.kind === 'PROCEDURE_START')
|
||||||
.map((step) => step.procedure)
|
.map((step) => step.procedure)
|
||||||
: []
|
|
||||||
);
|
);
|
||||||
expect(procedures).toEqual(['NPC포상']);
|
expect(procedures).toEqual(['NPC포상']);
|
||||||
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(withoutRecruitment));
|
expect(configuration(await call('getPolicy', {}))).toEqual(configuration(withoutRecruitment));
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ const buildContext = () => {
|
|||||||
},
|
},
|
||||||
logEntry: {
|
logEntry: {
|
||||||
findMany: vi.fn(async () => [
|
findMany: vi.fn(async () => [
|
||||||
{ id: 9, text: '<Y>최근 정세</>' },
|
{ id: 9n, text: '<Y>최근 정세</>' },
|
||||||
{ id: 8, text: '이전 정세' },
|
{ id: 8n, text: '이전 정세' },
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
$queryRaw: vi
|
$queryRaw: vi
|
||||||
|
|||||||
@@ -45,6 +45,28 @@ const createFixture = (rows: readonly object[]) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
describe('ReadModelOutboxWorker', () => {
|
describe('ReadModelOutboxWorker', () => {
|
||||||
|
it('drains more than one full retention batch rather than leaving a permanent 100-per-minute backlog', async () => {
|
||||||
|
let now = new Date('2026-11-09T00:00:00Z');
|
||||||
|
const fixture = createFixture([]);
|
||||||
|
fixture.queryRaw
|
||||||
|
.mockReset()
|
||||||
|
.mockResolvedValueOnce([])
|
||||||
|
.mockResolvedValueOnce([{ id: 1n }, { id: 2n }])
|
||||||
|
.mockResolvedValueOnce([{ id: 3n }, { id: 4n }])
|
||||||
|
.mockResolvedValueOnce([]);
|
||||||
|
const worker = new ReadModelOutboxWorker(fixture.db, fixture.redis, 'che:default', {
|
||||||
|
intervalMs: 60000,
|
||||||
|
pruneLimit: 2,
|
||||||
|
now: () => now,
|
||||||
|
});
|
||||||
|
now = new Date('2026-11-09T00:01:00Z');
|
||||||
|
worker.start();
|
||||||
|
await vi.waitFor(() => expect(fixture.queryRaw).toHaveBeenCalledTimes(4));
|
||||||
|
await worker.stop();
|
||||||
|
const query = fixture.queryRaw.mock.calls[1]?.[0] as { sql: string };
|
||||||
|
expect(query.sql).toContain('FOR UPDATE SKIP LOCKED');
|
||||||
|
expect(query.sql).toContain('ORDER BY "delivered_at", "available_at", "id"');
|
||||||
|
});
|
||||||
it('publishes a survey-style global front-status invalidation without a turn daemon', async () => {
|
it('publishes a survey-style global front-status invalidation without a turn daemon', async () => {
|
||||||
const fixture = createFixture([{ id: 10n, payload: payload('front.global'), attempts: 1 }]);
|
const fixture = createFixture([{ id: 10n, payload: payload('front.global'), attempts: 1 }]);
|
||||||
const worker = new ReadModelOutboxWorker(fixture.db, fixture.redis, 'che:default', {
|
const worker = new ReadModelOutboxWorker(fixture.db, fixture.redis, 'che:default', {
|
||||||
|
|||||||
@@ -69,8 +69,7 @@ const buildDb = (autorunLimit: number | null = null) => {
|
|||||||
},
|
},
|
||||||
createMany: async ({ data }: GeneralTurnCreateManyArgs) => {
|
createMany: async ({ data }: GeneralTurnCreateManyArgs) => {
|
||||||
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
|
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
|
||||||
const rows: GeneralTurnRow[] = dataList.map((row, index: number) => ({
|
const rows: GeneralTurnRow[] = dataList.map((row) => ({
|
||||||
id: index + 1,
|
|
||||||
generalId: row.generalId as number,
|
generalId: row.generalId as number,
|
||||||
turnIdx: row.turnIdx as number,
|
turnIdx: row.turnIdx as number,
|
||||||
actionCode: row.actionCode as string,
|
actionCode: row.actionCode as string,
|
||||||
@@ -136,8 +135,7 @@ const buildDb = (autorunLimit: number | null = null) => {
|
|||||||
},
|
},
|
||||||
createMany: async ({ data }: NationTurnCreateManyArgs) => {
|
createMany: async ({ data }: NationTurnCreateManyArgs) => {
|
||||||
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
|
const dataList = (Array.isArray(data) ? data : [data]) as Record<string, unknown>[];
|
||||||
const rows: NationTurnRow[] = dataList.map((row, index: number) => ({
|
const rows: NationTurnRow[] = dataList.map((row) => ({
|
||||||
id: index + 1,
|
|
||||||
nationId: row.nationId as number,
|
nationId: row.nationId as number,
|
||||||
officerLevel: row.officerLevel as number,
|
officerLevel: row.officerLevel as number,
|
||||||
turnIdx: row.turnIdx as number,
|
turnIdx: row.turnIdx as number,
|
||||||
@@ -203,9 +201,10 @@ const buildDb = (autorunLimit: number | null = null) => {
|
|||||||
|
|
||||||
describe('reservedTurns', () => {
|
describe('reservedTurns', () => {
|
||||||
it('loads multiple nation officer queues with two batched queries and preserves defaults', async () => {
|
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,
|
nationId: 4,
|
||||||
officerLevel: 12,
|
officerLevel: 12,
|
||||||
turnIdx: 1,
|
turnIdx: 1,
|
||||||
@@ -214,7 +213,6 @@ describe('reservedTurns', () => {
|
|||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
|
||||||
nationId: 4,
|
nationId: 4,
|
||||||
officerLevel: 10,
|
officerLevel: 10,
|
||||||
turnIdx: 0,
|
turnIdx: 0,
|
||||||
@@ -222,7 +220,8 @@ describe('reservedTurns', () => {
|
|||||||
arg: {},
|
arg: {},
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
},
|
},
|
||||||
] satisfies NationTurnRow[]);
|
] satisfies NationTurnRow[]
|
||||||
|
);
|
||||||
const findRevisions = vi.fn(async () => [
|
const findRevisions = vi.fn(async () => [
|
||||||
{ nationId: 4, officerLevel: 12, revision: 7, updatedAt: new Date() },
|
{ nationId: 4, officerLevel: 12, revision: 7, updatedAt: new Date() },
|
||||||
]);
|
]);
|
||||||
@@ -411,7 +410,6 @@ describe('reservedTurns', () => {
|
|||||||
nationRevisions.set('6:12', 2);
|
nationRevisions.set('6:12', 2);
|
||||||
nationTurns.set('6:12', [
|
nationTurns.set('6:12', [
|
||||||
{
|
{
|
||||||
id: 1,
|
|
||||||
nationId: 6,
|
nationId: 6,
|
||||||
officerLevel: 12,
|
officerLevel: 12,
|
||||||
turnIdx: 0,
|
turnIdx: 0,
|
||||||
@@ -420,7 +418,6 @@ describe('reservedTurns', () => {
|
|||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
|
||||||
nationId: 6,
|
nationId: 6,
|
||||||
officerLevel: 12,
|
officerLevel: 12,
|
||||||
turnIdx: 1,
|
turnIdx: 1,
|
||||||
|
|||||||
@@ -901,7 +901,6 @@ describe('appRouter', () => {
|
|||||||
const general = buildGeneralRow({ id: 11, meta: { autorun_limit: 2408 } });
|
const general = buildGeneralRow({ id: 11, meta: { autorun_limit: 2408 } });
|
||||||
const generalTurns: GeneralTurnRow[] = [
|
const generalTurns: GeneralTurnRow[] = [
|
||||||
{
|
{
|
||||||
id: 1,
|
|
||||||
generalId: 11,
|
generalId: 11,
|
||||||
turnIdx: 0,
|
turnIdx: 0,
|
||||||
actionCode: 'che_화계',
|
actionCode: 'che_화계',
|
||||||
@@ -922,7 +921,6 @@ describe('appRouter', () => {
|
|||||||
const general = buildGeneralRow({ id: 12, nationId: 3, officerLevel: 5 });
|
const general = buildGeneralRow({ id: 12, nationId: 3, officerLevel: 5 });
|
||||||
const nationTurns: NationTurnRow[] = [
|
const nationTurns: NationTurnRow[] = [
|
||||||
{
|
{
|
||||||
id: 1,
|
|
||||||
nationId: 3,
|
nationId: 3,
|
||||||
officerLevel: 5,
|
officerLevel: 5,
|
||||||
turnIdx: 0,
|
turnIdx: 0,
|
||||||
@@ -1008,7 +1006,6 @@ describe('appRouter', () => {
|
|||||||
general,
|
general,
|
||||||
generalTurns: [
|
generalTurns: [
|
||||||
{
|
{
|
||||||
id: 1,
|
|
||||||
generalId: general.id,
|
generalId: general.id,
|
||||||
turnIdx: 0,
|
turnIdx: 0,
|
||||||
actionCode: 'che_훈련',
|
actionCode: 'che_훈련',
|
||||||
@@ -1016,7 +1013,6 @@ describe('appRouter', () => {
|
|||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
|
||||||
generalId: general.id,
|
generalId: general.id,
|
||||||
turnIdx: 1,
|
turnIdx: 1,
|
||||||
actionCode: 'che_사기진작',
|
actionCode: 'che_사기진작',
|
||||||
@@ -1110,7 +1106,10 @@ describe('appRouter', () => {
|
|||||||
expect(nationWrites).toHaveLength(2);
|
expect(nationWrites).toHaveLength(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('stores Ref-sanitized nation command strings in the reserved queue', async () => {
|
it.each([
|
||||||
|
[' <신-국># ', '<신국>'],
|
||||||
|
['풍년F&B', '풍년F&B'],
|
||||||
|
])('stores the sanitized nation name %s in the reserved queue as %s', async (input, stored) => {
|
||||||
const general = buildGeneralRow({ id: 19, nationId: 3, officerLevel: 12 });
|
const general = buildGeneralRow({ id: 19, nationId: 3, officerLevel: 12 });
|
||||||
const nationWrites: unknown[] = [];
|
const nationWrites: unknown[] = [];
|
||||||
const caller = appRouter.createCaller(
|
const caller = appRouter.createCaller(
|
||||||
@@ -1121,16 +1120,14 @@ describe('appRouter', () => {
|
|||||||
generalId: general.id,
|
generalId: general.id,
|
||||||
turnIndex: 0,
|
turnIndex: 0,
|
||||||
action: 'che_국호변경',
|
action: 'che_국호변경',
|
||||||
args: { nationName: ' <신-국># ' },
|
args: { nationName: input },
|
||||||
expectedRevision: 0,
|
expectedRevision: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(response.turns[0]?.args).toEqual({ nationName: '<신국>' });
|
expect(response.turns[0]?.args).toEqual({ nationName: stored });
|
||||||
expect(nationWrites).toHaveLength(1);
|
expect(nationWrites).toHaveLength(1);
|
||||||
expect(nationWrites[0]).toMatchObject({
|
expect(nationWrites[0]).toMatchObject({
|
||||||
data: expect.arrayContaining([
|
data: expect.arrayContaining([expect.objectContaining({ turnIdx: 0, arg: { nationName: stored } })]),
|
||||||
expect.objectContaining({ turnIdx: 0, arg: { nationName: '<신국>' } }),
|
|
||||||
]),
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
|||||||
import { encryptGameSessionToken, type GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
import { encryptGameSessionToken, type GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||||
import {
|
import {
|
||||||
createGamePostgresConnector,
|
createGamePostgresConnector,
|
||||||
|
encodeAuditDecisionSteps,
|
||||||
GamePrisma,
|
GamePrisma,
|
||||||
hashAuditDiplomacyDocument,
|
hashAuditDiplomacyDocument,
|
||||||
createRedisConnector,
|
createRedisConnector,
|
||||||
@@ -968,7 +969,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
const telemetryAfter = await readAccessTelemetryState();
|
const telemetryAfter = await readAccessTelemetryState();
|
||||||
expect(telemetryAfter.periods).toEqual([
|
expect(telemetryAfter.periods).toEqual([
|
||||||
{
|
{
|
||||||
id: expect.any(Number),
|
id: expect.any(BigInt),
|
||||||
worldStateId: fixtureWorldId,
|
worldStateId: fixtureWorldId,
|
||||||
year: 190,
|
year: 190,
|
||||||
month: 1,
|
month: 1,
|
||||||
@@ -991,7 +992,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
]);
|
]);
|
||||||
expect(telemetryAfter.accessLogs).toEqual([
|
expect(telemetryAfter.accessLogs).toEqual([
|
||||||
{
|
{
|
||||||
id: expect.any(Number),
|
id: expect.any(BigInt),
|
||||||
generalId,
|
generalId,
|
||||||
userId,
|
userId,
|
||||||
lastRefresh: trafficPeriod.lastRefresh,
|
lastRefresh: trafficPeriod.lastRefresh,
|
||||||
@@ -1547,8 +1548,8 @@ integration('game API security over HTTP transport', () => {
|
|||||||
arg,
|
arg,
|
||||||
}))
|
}))
|
||||||
).toEqual(databaseAfter.generalTurns);
|
).toEqual(databaseAfter.generalTurns);
|
||||||
expect(new Set(committedGeneralTurns.map(({ id }) => id)).size).toBe(30);
|
expect(new Set(committedGeneralTurns.map(({ generalId, turnIdx }) => `${generalId}:${turnIdx}`)).size).toBe(30);
|
||||||
expect(committedGeneralTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
|
expect(committedGeneralTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
|
||||||
expect(allowedTablesAfter.generalTurnRevisions.filter((row) => row.generalId !== generalId)).toEqual(
|
expect(allowedTablesAfter.generalTurnRevisions.filter((row) => row.generalId !== generalId)).toEqual(
|
||||||
allowedTablesBefore.generalTurnRevisions.filter((row) => row.generalId !== generalId)
|
allowedTablesBefore.generalTurnRevisions.filter((row) => row.generalId !== generalId)
|
||||||
);
|
);
|
||||||
@@ -1566,7 +1567,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
);
|
);
|
||||||
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
|
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
|
||||||
{
|
{
|
||||||
id: expect.any(Number),
|
id: expect.any(BigInt),
|
||||||
generalId,
|
generalId,
|
||||||
userId,
|
userId,
|
||||||
lastRefresh: null,
|
lastRefresh: null,
|
||||||
@@ -1732,8 +1733,14 @@ integration('game API security over HTTP transport', () => {
|
|||||||
arg,
|
arg,
|
||||||
}))
|
}))
|
||||||
).toEqual(expectedTurns);
|
).toEqual(expectedTurns);
|
||||||
expect(new Set(committedNationTurns.map(({ id }) => id)).size).toBe(12);
|
expect(
|
||||||
expect(committedNationTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
|
new Set(
|
||||||
|
committedNationTurns.map(
|
||||||
|
({ nationId, officerLevel, turnIdx }) => `${nationId}:${officerLevel}:${turnIdx}`
|
||||||
|
)
|
||||||
|
).size
|
||||||
|
).toBe(12);
|
||||||
|
expect(committedNationTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
|
||||||
expect(
|
expect(
|
||||||
allowedTablesAfter.nationTurnRevisions.filter(
|
allowedTablesAfter.nationTurnRevisions.filter(
|
||||||
(row) => row.nationId !== ownerNationId || row.officerLevel !== 5
|
(row) => row.nationId !== ownerNationId || row.officerLevel !== 5
|
||||||
@@ -1762,7 +1769,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
);
|
);
|
||||||
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === sameNationGeneralId)).toEqual([
|
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === sameNationGeneralId)).toEqual([
|
||||||
{
|
{
|
||||||
id: expect.any(Number),
|
id: expect.any(BigInt),
|
||||||
generalId: sameNationGeneralId,
|
generalId: sameNationGeneralId,
|
||||||
userId: sameNationUserId,
|
userId: sameNationUserId,
|
||||||
lastRefresh: null,
|
lastRefresh: null,
|
||||||
@@ -1879,8 +1886,14 @@ integration('game API security over HTTP transport', () => {
|
|||||||
arg,
|
arg,
|
||||||
}))
|
}))
|
||||||
).toEqual(committed.nationTurns);
|
).toEqual(committed.nationTurns);
|
||||||
expect(new Set(committedNationTurns.map(({ id }) => id)).size).toBe(12);
|
expect(
|
||||||
expect(committedNationTurns.every(({ id, createdAt }) => id > 0 && createdAt instanceof Date)).toBe(true);
|
new Set(
|
||||||
|
committedNationTurns.map(
|
||||||
|
({ nationId, officerLevel, turnIdx }) => `${nationId}:${officerLevel}:${turnIdx}`
|
||||||
|
)
|
||||||
|
).size
|
||||||
|
).toBe(12);
|
||||||
|
expect(committedNationTurns.every(({ createdAt }) => createdAt instanceof Date)).toBe(true);
|
||||||
expect(
|
expect(
|
||||||
allowedTablesAfter.nationTurnRevisions.filter(
|
allowedTablesAfter.nationTurnRevisions.filter(
|
||||||
(row) => row.nationId !== ownerNationId || row.officerLevel !== 12
|
(row) => row.nationId !== ownerNationId || row.officerLevel !== 12
|
||||||
@@ -1909,7 +1922,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
);
|
);
|
||||||
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
|
expect(allowedTablesAfter.generalAccessLogs.filter((row) => row.generalId === generalId)).toEqual([
|
||||||
{
|
{
|
||||||
id: expect.any(Number),
|
id: expect.any(BigInt),
|
||||||
generalId,
|
generalId,
|
||||||
userId,
|
userId,
|
||||||
lastRefresh: null,
|
lastRefresh: null,
|
||||||
@@ -2345,7 +2358,8 @@ integration('game API security over HTTP transport', () => {
|
|||||||
{
|
{
|
||||||
decisionId: decisionIds[0]!,
|
decisionId: decisionIds[0]!,
|
||||||
ordinal: 0,
|
ordinal: 0,
|
||||||
steps: Array.from({ length: 128 }, (_, sequence) =>
|
steps: encodeAuditDecisionSteps(
|
||||||
|
Array.from({ length: 128 }, (_, sequence) =>
|
||||||
sequence === 127
|
sequence === 127
|
||||||
? {
|
? {
|
||||||
...step,
|
...step,
|
||||||
@@ -2389,6 +2403,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
: { ...step, sequence }
|
: { ...step, sequence }
|
||||||
|
)
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2865,7 +2880,7 @@ integration('game API security over HTTP transport', () => {
|
|||||||
result: {
|
result: {
|
||||||
data: {
|
data: {
|
||||||
coverage: 'IDENTIFIED_LOGS_ONLY',
|
coverage: 'IDENTIFIED_LOGS_ONLY',
|
||||||
items: [{ id: ownLogs[index]!.id }],
|
items: [{ id: Number(ownLogs[index]!.id) }],
|
||||||
nextCursor: null,
|
nextCursor: null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -2874,17 +2889,19 @@ integration('game API security over HTTP transport', () => {
|
|||||||
}
|
}
|
||||||
expect(
|
expect(
|
||||||
(await get('generalLogs', admin, { generalId: logGeneralId, type: 'generalHistory', limit: 1 })).body
|
(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(
|
expect(
|
||||||
(
|
(
|
||||||
await get('generalLogs', admin, {
|
await get('generalLogs', admin, {
|
||||||
generalId: logGeneralId,
|
generalId: logGeneralId,
|
||||||
type: 'generalHistory',
|
type: 'generalHistory',
|
||||||
limit: 1,
|
limit: 1,
|
||||||
cursor: latest.id,
|
cursor: Number(latest.id),
|
||||||
})
|
})
|
||||||
).body
|
).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 [
|
for (const invalid of [
|
||||||
{ limit: 201 },
|
{ limit: 201 },
|
||||||
{ cursor: 0 },
|
{ cursor: 0 },
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
@@ -580,8 +581,8 @@ export const createAuctionBidder = async (options: {
|
|||||||
}
|
}
|
||||||
await tx.$executeRaw(
|
await tx.$executeRaw(
|
||||||
GamePrisma.sql`
|
GamePrisma.sql`
|
||||||
INSERT INTO rank_data (nation_id, general_id, type, value)
|
INSERT INTO rank_data (id, nation_id, general_id, type, value)
|
||||||
SELECT nation_id, id, 'inherit_spent_dyn', ${morePoint}
|
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
|
FROM general
|
||||||
WHERE id = ${command.generalId}
|
WHERE id = ${command.generalId}
|
||||||
ON CONFLICT (general_id, type)
|
ON CONFLICT (general_id, type)
|
||||||
@@ -598,8 +599,9 @@ export const createAuctionBidder = async (options: {
|
|||||||
}
|
}
|
||||||
await tx.$executeRaw(
|
await tx.$executeRaw(
|
||||||
GamePrisma.sql`
|
GamePrisma.sql`
|
||||||
INSERT INTO inheritance_point (user_id, key, value, updated_at)
|
INSERT INTO inheritance_point (id, user_id, key, value, updated_at)
|
||||||
VALUES (
|
VALUES (
|
||||||
|
${existingRowIdOrNext('inheritance_point', GamePrisma.sql`stable_id.user_id = ${prevUserId} AND stable_id.key = 'previous'`)},
|
||||||
${prevUserId},
|
${prevUserId},
|
||||||
'previous',
|
'previous',
|
||||||
${highestBid.amount},
|
${highestBid.amount},
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||||
import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra';
|
import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra';
|
||||||
import { ActionLogger, ItemLoader, LogFormat, isItemKey, type MessageDraft } from '@sammo-ts/logic';
|
import { ActionLogger, ItemLoader, LogFormat, isItemKey, type MessageDraft } from '@sammo-ts/logic';
|
||||||
@@ -212,8 +213,8 @@ const refundInheritancePoint = async (options: {
|
|||||||
}
|
}
|
||||||
await prisma.$executeRaw(
|
await prisma.$executeRaw(
|
||||||
GamePrisma.sql`
|
GamePrisma.sql`
|
||||||
INSERT INTO inheritance_point (user_id, key, value, updated_at)
|
INSERT INTO inheritance_point (id, user_id, key, value, updated_at)
|
||||||
VALUES (${userId}, 'previous', ${amount}, ${new Date()})
|
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)
|
ON CONFLICT (user_id, key)
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
value = inheritance_point.value + EXCLUDED.value,
|
value = inheritance_point.value + EXCLUDED.value,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
import { asRecord, JosaUtil } from '@sammo-ts/common';
|
import { asRecord, JosaUtil } from '@sammo-ts/common';
|
||||||
@@ -289,8 +290,8 @@ const openUniqueAuction = async (
|
|||||||
});
|
});
|
||||||
await db.$executeRaw(
|
await db.$executeRaw(
|
||||||
GamePrisma.sql`
|
GamePrisma.sql`
|
||||||
INSERT INTO rank_data (nation_id, general_id, type, value)
|
INSERT INTO rank_data (id, nation_id, general_id, type, value)
|
||||||
VALUES (${general.nationId}, ${general.id}, 'inherit_spent_dyn', ${command.amount})
|
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)
|
ON CONFLICT (general_id, type)
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
nation_id = EXCLUDED.nation_id,
|
nation_id = EXCLUDED.nation_id,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export * from './scenario/databaseUrl.js';
|
|||||||
export * from './scenario/mapLoader.js';
|
export * from './scenario/mapLoader.js';
|
||||||
export * from './scenario/scenarioSeeder.js';
|
export * from './scenario/scenarioSeeder.js';
|
||||||
export * from './scenario/gameCancellation.js';
|
export * from './scenario/gameCancellation.js';
|
||||||
|
export * from './playAudit/retention.js';
|
||||||
export * from './turn/types.js';
|
export * from './turn/types.js';
|
||||||
export * from './turn/worldLoader.js';
|
export * from './turn/worldLoader.js';
|
||||||
export * from './turn/inMemoryWorld.js';
|
export * from './turn/inMemoryWorld.js';
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|||||||
import { performance } from 'node:perf_hooks';
|
import { performance } from 'node:perf_hooks';
|
||||||
|
|
||||||
import { createGamePostgresConnector, GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
|
import { createGamePostgresConnector, GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
|
||||||
|
import type { HostBootMonitor } from '../turn/hostBootMonitor.js';
|
||||||
|
|
||||||
export interface TurnDaemonLeaseToken {
|
export interface TurnDaemonLeaseToken {
|
||||||
profile: string;
|
profile: string;
|
||||||
@@ -14,6 +15,7 @@ export interface DatabaseTurnDaemonLeaseOptions {
|
|||||||
ownerId?: string;
|
ownerId?: string;
|
||||||
leaseDurationMs?: number;
|
leaseDurationMs?: number;
|
||||||
heartbeat?: boolean;
|
heartbeat?: boolean;
|
||||||
|
hostBootMonitor?: HostBootMonitor;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TurnDaemonLeaseUnavailableError extends Error {
|
export class TurnDaemonLeaseUnavailableError extends Error {
|
||||||
@@ -45,6 +47,7 @@ export class DatabaseTurnDaemonLease {
|
|||||||
private readonly ownerId: string;
|
private readonly ownerId: string;
|
||||||
private readonly leaseDurationMs: number;
|
private readonly leaseDurationMs: number;
|
||||||
private readonly heartbeatEnabled: boolean;
|
private readonly heartbeatEnabled: boolean;
|
||||||
|
private readonly hostBootMonitor?: HostBootMonitor;
|
||||||
private token: TurnDaemonLeaseToken | null = null;
|
private token: TurnDaemonLeaseToken | null = null;
|
||||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||||
private expiryTimer: NodeJS.Timeout | null = null;
|
private expiryTimer: NodeJS.Timeout | null = null;
|
||||||
@@ -63,6 +66,7 @@ export class DatabaseTurnDaemonLease {
|
|||||||
this.ownerId = options.ownerId ?? randomUUID();
|
this.ownerId = options.ownerId ?? randomUUID();
|
||||||
this.leaseDurationMs = normalizeLeaseDuration(options.leaseDurationMs);
|
this.leaseDurationMs = normalizeLeaseDuration(options.leaseDurationMs);
|
||||||
this.heartbeatEnabled = options.heartbeat ?? true;
|
this.heartbeatEnabled = options.heartbeat ?? true;
|
||||||
|
this.hostBootMonitor = options.hostBootMonitor;
|
||||||
}
|
}
|
||||||
|
|
||||||
static async connect(
|
static async connect(
|
||||||
@@ -75,6 +79,8 @@ export class DatabaseTurnDaemonLease {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async acquire(): Promise<TurnDaemonLeaseToken | null> {
|
async acquire(): Promise<TurnDaemonLeaseToken | null> {
|
||||||
|
await this.checkHostBoot();
|
||||||
|
if (this.lost) throw this.getLossError();
|
||||||
const requestStartedAt = performance.now();
|
const requestStartedAt = performance.now();
|
||||||
const rows = await this.db.$queryRaw<LeaseRow[]>(GamePrisma.sql`
|
const rows = await this.db.$queryRaw<LeaseRow[]>(GamePrisma.sql`
|
||||||
INSERT INTO "turn_daemon_lease" (
|
INSERT INTO "turn_daemon_lease" (
|
||||||
@@ -145,6 +151,12 @@ export class DatabaseTurnDaemonLease {
|
|||||||
return new TurnDaemonLeaseLostError(this.profile, this.lossReason);
|
return new TurnDaemonLeaseLostError(this.profile, this.lossReason);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async checkHostBoot(): Promise<void> {
|
||||||
|
if (!this.lost && (await this.hostBootMonitor?.hasChanged())) {
|
||||||
|
this.markLost('Host boot identity changed; restart with a fresh database snapshot.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async renew(): Promise<boolean> {
|
async renew(): Promise<boolean> {
|
||||||
const token = this.token;
|
const token = this.token;
|
||||||
if (!token || this.lost || this.renewalInFlight) {
|
if (!token || this.lost || this.renewalInFlight) {
|
||||||
@@ -153,6 +165,8 @@ export class DatabaseTurnDaemonLease {
|
|||||||
const requestStartedAt = performance.now();
|
const requestStartedAt = performance.now();
|
||||||
this.renewalInFlight = true;
|
this.renewalInFlight = true;
|
||||||
try {
|
try {
|
||||||
|
await this.checkHostBoot();
|
||||||
|
if (this.lost) return false;
|
||||||
const rows = await this.db.$queryRaw<LeaseRow[]>(GamePrisma.sql`
|
const rows = await this.db.$queryRaw<LeaseRow[]>(GamePrisma.sql`
|
||||||
UPDATE "turn_daemon_lease"
|
UPDATE "turn_daemon_lease"
|
||||||
SET
|
SET
|
||||||
@@ -180,6 +194,7 @@ export class DatabaseTurnDaemonLease {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async assertActive(transaction?: GamePrisma.TransactionClient): Promise<void> {
|
async assertActive(transaction?: GamePrisma.TransactionClient): Promise<void> {
|
||||||
|
await this.checkHostBoot();
|
||||||
const token = this.token;
|
const token = this.token;
|
||||||
if (!token || this.lost) {
|
if (!token || this.lost) {
|
||||||
throw this.getLossError();
|
throw this.getLossError();
|
||||||
@@ -207,12 +222,13 @@ export class DatabaseTurnDaemonLease {
|
|||||||
this.stopExpiryWatchdog();
|
this.stopExpiryWatchdog();
|
||||||
const token = this.token;
|
const token = this.token;
|
||||||
this.token = null;
|
this.token = null;
|
||||||
if (!token || this.lost) {
|
if (!token) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await this.db.$executeRaw(GamePrisma.sql`
|
await this.db.$executeRaw(GamePrisma.sql`
|
||||||
UPDATE "turn_daemon_lease"
|
UPDATE "turn_daemon_lease"
|
||||||
SET "lease_until" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC',
|
SET "clock_ready" = FALSE,
|
||||||
|
"lease_until" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC',
|
||||||
"heartbeat_at" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC'
|
"heartbeat_at" = CURRENT_TIMESTAMP AT TIME ZONE 'UTC'
|
||||||
WHERE
|
WHERE
|
||||||
"profile" = ${token.profile}
|
"profile" = ${token.profile}
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ export interface TurnDaemonLifecycleDeps {
|
|||||||
commandResponder?: TurnDaemonCommandResponder;
|
commandResponder?: TurnDaemonCommandResponder;
|
||||||
pauseGate?: () => Promise<boolean>;
|
pauseGate?: () => Promise<boolean>;
|
||||||
stateManager?: Pick<EngineStateManager, 'transaction'>;
|
stateManager?: Pick<EngineStateManager, 'transaction'>;
|
||||||
|
runErrorRetry?: { wait(error: unknown): Promise<boolean>; reset(): void };
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TurnDaemonLifecycle {
|
export class TurnDaemonLifecycle {
|
||||||
@@ -59,6 +60,7 @@ export class TurnDaemonLifecycle {
|
|||||||
private readonly commandResponder?: TurnDaemonCommandResponder;
|
private readonly commandResponder?: TurnDaemonCommandResponder;
|
||||||
private readonly pauseGate?: () => Promise<boolean>;
|
private readonly pauseGate?: () => Promise<boolean>;
|
||||||
private readonly stateManager?: Pick<EngineStateManager, 'transaction'>;
|
private readonly stateManager?: Pick<EngineStateManager, 'transaction'>;
|
||||||
|
private readonly runErrorRetry?: TurnDaemonLifecycleDeps['runErrorRetry'];
|
||||||
private readonly options: TurnDaemonLifecycleOptions;
|
private readonly options: TurnDaemonLifecycleOptions;
|
||||||
|
|
||||||
private status: TurnDaemonStatus;
|
private status: TurnDaemonStatus;
|
||||||
@@ -79,6 +81,7 @@ export class TurnDaemonLifecycle {
|
|||||||
this.commandResponder = deps.commandResponder;
|
this.commandResponder = deps.commandResponder;
|
||||||
this.pauseGate = deps.pauseGate;
|
this.pauseGate = deps.pauseGate;
|
||||||
this.stateManager = deps.stateManager;
|
this.stateManager = deps.stateManager;
|
||||||
|
this.runErrorRetry = deps.runErrorRetry;
|
||||||
this.options = options;
|
this.options = options;
|
||||||
this.status = {
|
this.status = {
|
||||||
state: 'idle',
|
state: 'idle',
|
||||||
@@ -192,8 +195,9 @@ export class TurnDaemonLifecycle {
|
|||||||
// 수동 실행 요청도 가오픈·정지·재조정의 턴 실행 gate를 통과해야 한다.
|
// 수동 실행 요청도 가오픈·정지·재조정의 턴 실행 gate를 통과해야 한다.
|
||||||
// 사용자 명령 처리는 루프 시작에서 계속하되 시간 진행은 여기서 분리한다.
|
// 사용자 명령 처리는 루프 시작에서 계속하되 시간 진행은 여기서 분리한다.
|
||||||
if (this.pendingRun) {
|
if (this.pendingRun) {
|
||||||
await this.runOnce(this.pendingRun);
|
const pending = this.pendingRun;
|
||||||
this.pendingRun = null;
|
this.pendingRun = null;
|
||||||
|
await this.runOnce(pending);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -447,6 +451,15 @@ export class TurnDaemonLifecycle {
|
|||||||
};
|
};
|
||||||
result = this.stateManager ? await this.stateManager.transaction(runAndFlush) : await runAndFlush();
|
result = this.stateManager ? await this.stateManager.transaction(runAndFlush) : await runAndFlush();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
// savepoint 복원이 성공한 획득 충돌만 대기한다. 복원 실패/AggregateError나
|
||||||
|
// 저장 중 소유권 상실을 자동 재실행하면 중복 효과를 숨길 수 있다.
|
||||||
|
if (this.stateManager && (await this.runErrorRetry?.wait(error))) {
|
||||||
|
this.status.running = false;
|
||||||
|
this.status.state = 'idle';
|
||||||
|
this.pendingRun = pending;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.runErrorRetry?.reset();
|
||||||
this.status.running = false;
|
this.status.running = false;
|
||||||
this.status.state = 'paused';
|
this.status.state = 'paused';
|
||||||
this.status.paused = true;
|
this.status.paused = true;
|
||||||
@@ -459,6 +472,7 @@ export class TurnDaemonLifecycle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.applyRunResult(result, startMs);
|
await this.applyRunResult(result, startMs);
|
||||||
|
this.runErrorRetry?.reset();
|
||||||
this.status.state = 'idle';
|
this.status.state = 'idle';
|
||||||
try {
|
try {
|
||||||
await this.hooks?.publishEvents?.(result);
|
await this.hooks?.publishEvents?.(result);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
import { encodeAuditDecisionSteps, type GamePrisma, type InputJsonValue } from '@sammo-ts/infra';
|
||||||
import { auditPolicyHash } from './policy.js';
|
import { auditPolicyHash } from './policy.js';
|
||||||
import type { PendingAuditDecision } from './decision.js';
|
import type { PendingAuditDecision } from './decision.js';
|
||||||
|
|
||||||
@@ -50,7 +50,9 @@ export const persistAuditDecisions = async (
|
|||||||
chunks.push({
|
chunks.push({
|
||||||
decisionId: decision.id,
|
decisionId: decision.id,
|
||||||
ordinal: start / AUDIT_DECISION_CHUNK_STEPS,
|
ordinal: start / AUDIT_DECISION_CHUNK_STEPS,
|
||||||
steps: decision.steps.slice(start, start + AUDIT_DECISION_CHUNK_STEPS) as InputJsonValue,
|
steps: encodeAuditDecisionSteps(
|
||||||
|
decision.steps.slice(start, start + AUDIT_DECISION_CHUNK_STEPS) as InputJsonValue[]
|
||||||
|
),
|
||||||
});
|
});
|
||||||
if (chunks.length === BATCH) {
|
if (chunks.length === BATCH) {
|
||||||
await tx.playAuditDecisionChunk.createMany({ data: chunks, skipDuplicates: true });
|
await tx.playAuditDecisionChunk.createMany({ data: chunks, skipDuplicates: true });
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { asRecord } from '@sammo-ts/common';
|
import { asRecord } from '@sammo-ts/common';
|
||||||
import type { GamePrismaClient } from '@sammo-ts/infra';
|
import { GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
|
||||||
|
|
||||||
export const AUDIT_RETENTION_BATCH_SIZE = 200;
|
export const AUDIT_RETENTION_BATCH_SIZE = 200;
|
||||||
export type AuditRetentionResult = { status: 'progress' | 'complete' | 'busy' | 'identityChanged'; deleted: number };
|
export type AuditRetentionResult = { status: 'progress' | 'complete' | 'busy' | 'identityChanged'; deleted: number };
|
||||||
@@ -13,6 +13,7 @@ export const prunePreviousAuditBatch = async (
|
|||||||
return db.$transaction(
|
return db.$transaction(
|
||||||
async (tx) => {
|
async (tx) => {
|
||||||
await tx.$executeRaw`SET LOCAL statement_timeout = '2000ms'`;
|
await tx.$executeRaw`SET LOCAL statement_timeout = '2000ms'`;
|
||||||
|
await tx.$executeRaw`SET LOCAL lock_timeout = '250ms'`;
|
||||||
// seeder와 동일한 잠금이다. RESET을 기다리게 하지 않고 다음 batch에서 재시도한다.
|
// seeder와 동일한 잠금이다. RESET을 기다리게 하지 않고 다음 batch에서 재시도한다.
|
||||||
const [lock] = await tx.$queryRaw<{ locked: boolean }[]>`
|
const [lock] = await tx.$queryRaw<{ locked: boolean }[]>`
|
||||||
SELECT pg_try_advisory_xact_lock(hashtextextended(current_schema(), 0)) AS locked
|
SELECT pg_try_advisory_xact_lock(hashtextextended(current_schema(), 0)) AS locked
|
||||||
@@ -32,29 +33,43 @@ export const prunePreviousAuditBatch = async (
|
|||||||
});
|
});
|
||||||
return { status: 'progress', deleted: deleted.count };
|
return { status: 'progress', deleted: deleted.count };
|
||||||
}
|
}
|
||||||
const [decision] = await tx.$queryRaw<{ id: string }[]>`
|
// 이미 있는 (server_id,nation_id,tick,id) 인덱스 순서로 여러 부모를 잠근다.
|
||||||
SELECT id FROM play_audit_decision WHERE id = COALESCE(
|
// chunk 총량과 빈 header 삭제량의 합도 BATCH 이하로 제한한다.
|
||||||
(SELECT id FROM play_audit_decision WHERE server_id < ${expectedServerId}
|
let decisions = await tx.$queryRaw<{ id: string }[]>`
|
||||||
ORDER BY server_id, general_id, tick, id LIMIT 1),
|
SELECT id FROM play_audit_decision WHERE server_id < ${expectedServerId}
|
||||||
(SELECT id FROM play_audit_decision WHERE server_id > ${expectedServerId}
|
ORDER BY server_id, nation_id, tick, id LIMIT ${AUDIT_RETENTION_BATCH_SIZE} FOR UPDATE
|
||||||
ORDER BY server_id, general_id, tick, id LIMIT 1)
|
`;
|
||||||
) FOR UPDATE
|
if (!decisions.length) {
|
||||||
|
decisions = await tx.$queryRaw<{ id: string }[]>`
|
||||||
|
SELECT id FROM play_audit_decision WHERE server_id > ${expectedServerId}
|
||||||
|
ORDER BY server_id, nation_id, tick, id LIMIT ${AUDIT_RETENTION_BATCH_SIZE} FOR UPDATE
|
||||||
`;
|
`;
|
||||||
if (decision) {
|
|
||||||
const chunks = await tx.playAuditDecisionChunk.findMany({
|
|
||||||
where: { decisionId: decision.id },
|
|
||||||
orderBy: { ordinal: 'asc' },
|
|
||||||
take: AUDIT_RETENTION_BATCH_SIZE,
|
|
||||||
select: { ordinal: true },
|
|
||||||
});
|
|
||||||
if (chunks.length) {
|
|
||||||
const deleted = await tx.playAuditDecisionChunk.deleteMany({
|
|
||||||
where: { decisionId: decision.id, ordinal: { in: chunks.map((row) => row.ordinal) } },
|
|
||||||
});
|
|
||||||
return { status: 'progress', deleted: deleted.count };
|
|
||||||
}
|
}
|
||||||
await tx.playAuditDecision.delete({ where: { id: decision.id } });
|
if (decisions.length) {
|
||||||
return { status: 'progress', deleted: 1 };
|
const ids = decisions.map(({ id }) => id);
|
||||||
|
const [chunks] = await tx.$queryRaw<{ deleted: number }[]>(GamePrisma.sql`
|
||||||
|
WITH batch AS (
|
||||||
|
SELECT decision_id, ordinal FROM play_audit_decision_chunk
|
||||||
|
WHERE decision_id IN (${GamePrisma.join(ids)})
|
||||||
|
ORDER BY decision_id, ordinal LIMIT ${AUDIT_RETENTION_BATCH_SIZE}
|
||||||
|
), removed AS (
|
||||||
|
DELETE FROM play_audit_decision_chunk c USING batch b
|
||||||
|
WHERE c.decision_id=b.decision_id AND c.ordinal=b.ordinal RETURNING 1
|
||||||
|
) SELECT count(*)::integer AS deleted FROM removed
|
||||||
|
`);
|
||||||
|
const count = chunks?.deleted ?? 0;
|
||||||
|
const remaining = AUDIT_RETENTION_BATCH_SIZE - count;
|
||||||
|
if (!remaining) return { status: 'progress', deleted: count };
|
||||||
|
const empty = await tx.playAuditDecision.findMany({
|
||||||
|
where: { id: { in: ids }, chunks: { none: {} } },
|
||||||
|
select: { id: true },
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
take: remaining,
|
||||||
|
});
|
||||||
|
const headers = await tx.playAuditDecision.deleteMany({
|
||||||
|
where: { id: { in: empty.map(({ id }) => id) } },
|
||||||
|
});
|
||||||
|
return { status: 'progress', deleted: count + headers.count };
|
||||||
}
|
}
|
||||||
const policies = await tx.playAuditPolicy.findMany({
|
const policies = await tx.playAuditPolicy.findMany({
|
||||||
where: { serverId: { not: expectedServerId } },
|
where: { serverId: { not: expectedServerId } },
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ export const startAuditRetentionWorker = (options: {
|
|||||||
timer.unref();
|
timer.unref();
|
||||||
};
|
};
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
let delay = 1000;
|
let delay = 100;
|
||||||
try {
|
try {
|
||||||
const result = await options.prune();
|
const result = await options.prune();
|
||||||
if (result.status === 'complete' || result.status === 'identityChanged') stopped = true;
|
if (result.status === 'complete' || result.status === 'identityChanged') stopped = true;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { asRecord } from '@sammo-ts/common';
|
import { asRecord } from '@sammo-ts/common';
|
||||||
import { createGamePostgresConnector, type GamePrisma, type InputJsonValue } from '@sammo-ts/infra';
|
import { createGamePostgresConnector, type GamePrisma, type InputJsonValue } from '@sammo-ts/infra';
|
||||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||||
@@ -424,7 +425,7 @@ const cancelGameInTransaction = async (
|
|||||||
earnedPointRetentionPercent: request.earnedPointRetentionPercent,
|
earnedPointRetentionPercent: request.earnedPointRetentionPercent,
|
||||||
});
|
});
|
||||||
const currentPoint = pointsByUser.get(userId)?.get('previous') ?? 0;
|
const currentPoint = pointsByUser.get(userId)?.get('previous') ?? 0;
|
||||||
await prisma.inheritancePoint.upsert({
|
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||||
where: { userId_key: { userId, key: 'previous' } },
|
where: { userId_key: { userId, key: 'previous' } },
|
||||||
update: { value: calculated.finalPoint },
|
update: { value: calculated.finalPoint },
|
||||||
create: { userId, key: 'previous', value: calculated.finalPoint },
|
create: { userId, key: 'previous', value: calculated.finalPoint },
|
||||||
@@ -470,7 +471,7 @@ const cancelGameInTransaction = async (
|
|||||||
}
|
}
|
||||||
for (const general of activeGenerals) {
|
for (const general of activeGenerals) {
|
||||||
if (!general.userId || general.npcState >= 2) continue;
|
if (!general.userId || general.npcState >= 2) continue;
|
||||||
await prisma.oldGeneral.upsert({
|
await upsertWithoutSequence(prisma.oldGeneral, {
|
||||||
where: { by_no: { serverId, generalNo: general.id } },
|
where: { by_no: { serverId, generalNo: general.id } },
|
||||||
update: {
|
update: {
|
||||||
owner: general.userId,
|
owner: general.userId,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { prunePreviousAuditBatch } from '../playAudit/retention.js';
|
import { prunePreviousAuditBatch } from '../playAudit/retention.js';
|
||||||
import { randomBytes } from 'node:crypto';
|
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 },
|
where: { serverId: worldMeta.serverId },
|
||||||
create: {
|
create: {
|
||||||
serverId: worldMeta.serverId,
|
serverId: worldMeta.serverId,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { areSeasonRecordsFinalized } from '../turn/seasonRecords.js';
|
import { areSeasonRecordsFinalized } from '../turn/seasonRecords.js';
|
||||||
import { JosaUtil, asRecord } from '@sammo-ts/common';
|
import { JosaUtil, asRecord } from '@sammo-ts/common';
|
||||||
import { createGamePostgresConnector, type GamePrisma } from '@sammo-ts/infra';
|
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);
|
const recordsFinalized = await areSeasonRecordsFinalized(db, world.getState().meta.serverId);
|
||||||
for (const entry of recordsFinalized ? [] : pointUpdates) {
|
for (const entry of recordsFinalized ? [] : pointUpdates) {
|
||||||
await db.inheritancePoint.upsert({
|
await upsertWithoutSequence(db.inheritancePoint, {
|
||||||
where: {
|
where: {
|
||||||
userId_key: { userId: entry.userId!, key: 'tournament' },
|
userId_key: { userId: entry.userId!, key: 'tournament' },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { createTurnDaemonMemoryReporter } from './turnDaemonMemoryReporter.js';
|
|||||||
import { createGatewayProfileGate } from './gatewayProfileGate.js';
|
import { createGatewayProfileGate } from './gatewayProfileGate.js';
|
||||||
import { retryTurnDaemonLeaseStartup } from './leaseStartupRetry.js';
|
import { retryTurnDaemonLeaseStartup } from './leaseStartupRetry.js';
|
||||||
import { TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js';
|
import { TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js';
|
||||||
|
import { loadHostBootMonitor } from './hostBootMonitor.js';
|
||||||
|
|
||||||
export interface TurnDaemonCliOptions {
|
export interface TurnDaemonCliOptions {
|
||||||
profile?: string;
|
profile?: string;
|
||||||
@@ -80,6 +81,7 @@ export const runTurnDaemonCli = async (options: TurnDaemonCliOptions = {}): Prom
|
|||||||
throw new Error(`GAME_CLOCK_MODE must be realtime or manual: ${rawGameClockMode}`);
|
throw new Error(`GAME_CLOCK_MODE must be realtime or manual: ${rawGameClockMode}`);
|
||||||
}
|
}
|
||||||
const gameClockMode = rawGameClockMode as GameClockMode | undefined;
|
const gameClockMode = rawGameClockMode as GameClockMode | undefined;
|
||||||
|
const hostBootMonitor = await loadHostBootMonitor(env);
|
||||||
|
|
||||||
const runtime = await retryTurnDaemonLeaseStartup(() =>
|
const runtime = await retryTurnDaemonLeaseStartup(() =>
|
||||||
createTurnDaemonRuntime({
|
createTurnDaemonRuntime({
|
||||||
@@ -95,6 +97,7 @@ export const runTurnDaemonCli = async (options: TurnDaemonCliOptions = {}): Prom
|
|||||||
pauseGateIntervalMs,
|
pauseGateIntervalMs,
|
||||||
adminActionIntervalMs,
|
adminActionIntervalMs,
|
||||||
gameClockMode,
|
gameClockMode,
|
||||||
|
hostBootMonitor,
|
||||||
})
|
})
|
||||||
).catch(async (error: unknown) => {
|
).catch(async (error: unknown) => {
|
||||||
// 중복 starter가 정상 owner를 멈추면 안 된다. 그 밖의 초기화 실패는
|
// 중복 starter가 정상 owner를 멈추면 안 된다. 그 밖의 초기화 실패는
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { persistAuditDecisions } from '../playAudit/decisionPersistence.js';
|
import { persistAuditDecisions } from '../playAudit/decisionPersistence.js';
|
||||||
import { collectPlayAudit, markAuditGap } from '../playAudit/bestEffort.js';
|
import { collectPlayAudit, markAuditGap } from '../playAudit/bestEffort.js';
|
||||||
import { persistAuditDiplomacyEvents, withPlayAuditSavepoint } from '@sammo-ts/infra';
|
import { persistAuditDiplomacyEvents, withPlayAuditSavepoint } from '@sammo-ts/infra';
|
||||||
@@ -119,7 +120,7 @@ export interface RealtimeReadModelBaseline {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type PersistedVisibleLogRow = {
|
export type PersistedVisibleLogRow = {
|
||||||
id: number;
|
id: number | bigint;
|
||||||
scope: LogScope;
|
scope: LogScope;
|
||||||
category: LogCategory;
|
category: LogCategory;
|
||||||
generalId: number | null;
|
generalId: number | null;
|
||||||
@@ -697,12 +698,12 @@ const persistNationBettingFinish = async (
|
|||||||
});
|
});
|
||||||
const previousPoint = existing?.value ?? 0;
|
const previousPoint = existing?.value ?? 0;
|
||||||
const nextPoint = previousPoint + reward.amount;
|
const nextPoint = previousPoint + reward.amount;
|
||||||
await prisma.inheritancePoint.upsert({
|
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||||
where: { userId_key: { userId: reward.userId, key: 'previous' } },
|
where: { userId_key: { userId: reward.userId, key: 'previous' } },
|
||||||
update: { value: nextPoint },
|
update: { value: nextPoint },
|
||||||
create: { userId: reward.userId, key: 'previous', value: nextPoint },
|
create: { userId: reward.userId, key: 'previous', value: nextPoint },
|
||||||
});
|
});
|
||||||
await prisma.rankData.upsert({
|
await upsertWithoutSequence(prisma.rankData, {
|
||||||
where: {
|
where: {
|
||||||
generalId_type: {
|
generalId_type: {
|
||||||
generalId: reward.generalId,
|
generalId: reward.generalId,
|
||||||
@@ -831,17 +832,28 @@ const buildPersistedGeneralMeta = (
|
|||||||
|
|
||||||
const RANK_DATA_UPSERT_BATCH_SIZE = 1_000;
|
const RANK_DATA_UPSERT_BATCH_SIZE = 1_000;
|
||||||
|
|
||||||
const upsertRankRows = async (
|
export const upsertRankRows = async (
|
||||||
prisma: GamePrisma.TransactionClient,
|
prisma: GamePrisma.TransactionClient,
|
||||||
rows: Array<{ generalId: number; nationId: number; type: string; value: number }>
|
rows: Array<{ generalId: number; nationId: number; type: string; value: number }>
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
for (let offset = 0; offset < rows.length; offset += RANK_DATA_UPSERT_BATCH_SIZE) {
|
for (let offset = 0; offset < rows.length; offset += RANK_DATA_UPSERT_BATCH_SIZE) {
|
||||||
const batch = rows.slice(offset, 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`
|
await prisma.$executeRaw(GamePrisma.sql`
|
||||||
INSERT INTO "rank_data" ("general_id", "nation_id", "type", "value")
|
INSERT INTO "rank_data" ("id", "general_id", "nation_id", "type", "value")
|
||||||
VALUES ${GamePrisma.join(
|
SELECT
|
||||||
batch.map((row) => GamePrisma.sql`(${row.generalId}, ${row.nationId}, ${row.type}, ${row.value})`)
|
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
|
ON CONFLICT ("general_id", "type") DO UPDATE
|
||||||
SET
|
SET
|
||||||
"nation_id" = EXCLUDED."nation_id",
|
"nation_id" = EXCLUDED."nation_id",
|
||||||
@@ -1079,6 +1091,7 @@ export const createDatabaseTurnHooks = async (
|
|||||||
profileName?: string;
|
profileName?: string;
|
||||||
reservedTurns?: InMemoryReservedTurnStore;
|
reservedTurns?: InMemoryReservedTurnStore;
|
||||||
turnDaemonLease?: DatabaseTurnDaemonLease;
|
turnDaemonLease?: DatabaseTurnDaemonLease;
|
||||||
|
transactionMaxWaitMs?: number;
|
||||||
transactionTimeoutMs?: number;
|
transactionTimeoutMs?: number;
|
||||||
}
|
}
|
||||||
): Promise<DatabaseTurnHooks> => {
|
): Promise<DatabaseTurnHooks> => {
|
||||||
@@ -1089,7 +1102,13 @@ export const createDatabaseTurnHooks = async (
|
|||||||
// Prisma's 5-second default matches the normal turn execution budget too
|
// Prisma's 5-second default matches the normal turn execution budget too
|
||||||
// closely. A populated season can finish the turn but expire while flushing
|
// closely. A populated season can finish the turn but expire while flushing
|
||||||
// it, which rolls the transaction back and marks the profile PAUSED.
|
// it, which rolls the transaction back and marks the profile PAUSED.
|
||||||
const transactionOptions = { timeout: options?.transactionTimeoutMs ?? 30_000 };
|
// 실행 timeout과 연결 획득 대기는 별도 제한이다. 기본 maxWait 2초는
|
||||||
|
// 일시적인 DB 지연에도 callback 시작 전에 턴을 영구 PAUSED로 만들었다.
|
||||||
|
// 대기를 유한하게 늘리되 callback 재실행이나 lease/fencing 우회는 하지 않는다.
|
||||||
|
const transactionOptions = {
|
||||||
|
maxWait: options?.transactionMaxWaitMs ?? 10_000,
|
||||||
|
timeout: options?.transactionTimeoutMs ?? 30_000,
|
||||||
|
};
|
||||||
const readModelBaseline = createRealtimeReadModelBaseline(world);
|
const readModelBaseline = createRealtimeReadModelBaseline(world);
|
||||||
let worldReadModelBaseline = createWorldReadModelSignature(world);
|
let worldReadModelBaseline = createWorldReadModelSignature(world);
|
||||||
let persistedTickSeconds = world.getState().tickSeconds;
|
let persistedTickSeconds = world.getState().tickSeconds;
|
||||||
@@ -1122,7 +1141,7 @@ export const createDatabaseTurnHooks = async (
|
|||||||
const persistChanges = async (
|
const persistChanges = async (
|
||||||
transaction?: GamePrisma.TransactionClient,
|
transaction?: GamePrisma.TransactionClient,
|
||||||
commandCompletion?: { requestId: string; result: TurnDaemonCommandResult },
|
commandCompletion?: { requestId: string; result: TurnDaemonCommandResult },
|
||||||
directLogFloor?: number
|
directLogFloor?: number | bigint
|
||||||
): Promise<{
|
): Promise<{
|
||||||
acknowledge: () => void;
|
acknowledge: () => void;
|
||||||
readModelChanges: RealtimeReadModelChanges;
|
readModelChanges: RealtimeReadModelChanges;
|
||||||
@@ -1556,7 +1575,7 @@ export const createDatabaseTurnHooks = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const entry of grouped.values()) {
|
for (const entry of grouped.values()) {
|
||||||
await prisma.inheritancePoint.upsert({
|
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||||
where: { userId_key: { userId: entry.userId, key: entry.key } },
|
where: { userId_key: { userId: entry.userId, key: entry.key } },
|
||||||
update: { value: { increment: entry.amount } },
|
update: { value: { increment: entry.amount } },
|
||||||
create: { userId: entry.userId, key: entry.key, value: entry.amount },
|
create: { userId: entry.userId, key: entry.key, value: entry.amount },
|
||||||
@@ -1624,7 +1643,7 @@ export const createDatabaseTurnHooks = async (
|
|||||||
}
|
}
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
deletedNationSnapshots.map((snapshot) =>
|
deletedNationSnapshots.map((snapshot) =>
|
||||||
prisma.oldNation.upsert({
|
upsertWithoutSequence(prisma.oldNation, {
|
||||||
where: {
|
where: {
|
||||||
serverId_nation_sourceId: {
|
serverId_nation_sourceId: {
|
||||||
serverId,
|
serverId,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { GamePrisma, type TurnEngineGeneralUpdateInput } from '@sammo-ts/infra';
|
import { GamePrisma, type TurnEngineGeneralUpdateInput } from '@sammo-ts/infra';
|
||||||
|
|
||||||
// Fixed schema identifiers only; all row values remain bound parameters.
|
// 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) {
|
for (let offset = 0; offset < updates.length; offset += GENERAL_UPDATE_BATCH_SIZE) {
|
||||||
const batch = updates.slice(offset, offset + GENERAL_UPDATE_BATCH_SIZE);
|
const batch = updates.slice(offset, offset + GENERAL_UPDATE_BATCH_SIZE);
|
||||||
await database.$executeRaw(GamePrisma.sql`
|
await database.$executeRaw(GamePrisma.sql`
|
||||||
INSERT INTO "general_access_log" ("general_id", "user_id", "refresh_score_total")
|
INSERT INTO "general_access_log" ("id", "general_id", "user_id", "refresh_score_total")
|
||||||
VALUES ${GamePrisma.join(batch.map((row) => GamePrisma.sql`(${row.generalId}, ${row.userId}, ${row.refreshScoreTotal})`))}
|
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
|
ON CONFLICT ("general_id") DO UPDATE
|
||||||
SET "refresh_score_total" = EXCLUDED."refresh_score_total"
|
SET "refresh_score_total" = EXCLUDED."refresh_score_total"
|
||||||
`);
|
`);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||||
import {
|
import {
|
||||||
asRecord,
|
asRecord,
|
||||||
@@ -77,7 +78,7 @@ const persistPostRetirementRankValues = async (
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (const row of buildPersistedRankRows(event.after)) {
|
for (const row of buildPersistedRankRows(event.after)) {
|
||||||
await prisma.rankData.upsert({
|
await upsertWithoutSequence(prisma.rankData, {
|
||||||
where: { generalId_type: { generalId: row.generalId, type: row.type } },
|
where: { generalId_type: { generalId: row.generalId, type: row.type } },
|
||||||
update: { nationId: row.nationId, value: row.value },
|
update: { nationId: row.nationId, value: row.value },
|
||||||
create: row,
|
create: row,
|
||||||
@@ -142,7 +143,7 @@ const settleInheritance = async (
|
|||||||
);
|
);
|
||||||
const total = Math.trunc(previous + refund + settlement.totalEarned);
|
const total = Math.trunc(previous + refund + settlement.totalEarned);
|
||||||
|
|
||||||
await prisma.inheritancePoint.upsert({
|
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||||
where: { userId_key: { userId, key: 'previous' } },
|
where: { userId_key: { userId, key: 'previous' } },
|
||||||
update: { value: total },
|
update: { value: total },
|
||||||
create: { userId, key: 'previous', 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
|
([key, value]) => key === 'max_belong' || points.has(key) || value !== 0
|
||||||
);
|
);
|
||||||
for (const [key, value] of retainedEntries) {
|
for (const [key, value] of retainedEntries) {
|
||||||
await prisma.inheritancePoint.upsert({
|
await upsertWithoutSequence(prisma.inheritancePoint, {
|
||||||
where: { userId_key: { userId, key } },
|
where: { userId_key: { userId, key } },
|
||||||
update: { value },
|
update: { value },
|
||||||
create: { userId, key, value },
|
create: { userId, key, value },
|
||||||
@@ -367,7 +368,7 @@ const archiveGeneral = async (
|
|||||||
records: { battleResult: battleResults },
|
records: { battleResult: battleResults },
|
||||||
availability: { battleResultLogs: true },
|
availability: { battleResultLogs: true },
|
||||||
};
|
};
|
||||||
await prisma.oldGeneral.upsert({
|
await upsertWithoutSequence(prisma.oldGeneral, {
|
||||||
where: { by_no: { serverId, generalNo: event.generalId } },
|
where: { by_no: { serverId, generalNo: event.generalId } },
|
||||||
update: {
|
update: {
|
||||||
owner: event.before.userId ?? null,
|
owner: event.before.userId ?? null,
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { performance } from 'node:perf_hooks';
|
||||||
|
import { isRecord } from '@sammo-ts/common';
|
||||||
|
|
||||||
|
export interface HostBootMonitor {
|
||||||
|
hasChanged(): Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mac = (key: Buffer, value: string): string => createHmac('sha256', key).update(value).digest('hex');
|
||||||
|
|
||||||
|
/** 부팅 세대는 첫 인증 응답에 고정한다. 통신 실패는 기존 lease 복구를 막지 않는다. */
|
||||||
|
export const createHostBootMonitor = (options: {
|
||||||
|
url: string;
|
||||||
|
key: Buffer;
|
||||||
|
pollMs?: number;
|
||||||
|
timeoutMs?: number;
|
||||||
|
now?: () => number;
|
||||||
|
wallNow?: () => number;
|
||||||
|
onUnavailable?: () => void;
|
||||||
|
onVerified?: () => void;
|
||||||
|
}): HostBootMonitor => {
|
||||||
|
const url = new URL(options.url);
|
||||||
|
if (
|
||||||
|
!['http:', 'https:'].includes(url.protocol) ||
|
||||||
|
url.username ||
|
||||||
|
url.password ||
|
||||||
|
url.search ||
|
||||||
|
url.hash ||
|
||||||
|
url.pathname !== '/v1/boot-id'
|
||||||
|
) {
|
||||||
|
throw new Error('Host boot URL must use HTTP(S) and /v1/boot-id without credentials or query.');
|
||||||
|
}
|
||||||
|
if (options.key.length !== 32) throw new Error('Host boot key must contain exactly 32 bytes.');
|
||||||
|
const now = options.now ?? (() => performance.now());
|
||||||
|
const wallNow = options.wallNow ?? (() => Date.now());
|
||||||
|
let baseline: string | null = null;
|
||||||
|
let changed = false;
|
||||||
|
let lastAttempt = -Infinity;
|
||||||
|
let lastWall = 0;
|
||||||
|
let lastWarning = -Infinity;
|
||||||
|
let inFlight: Promise<boolean> | null = null;
|
||||||
|
const sample = async (): Promise<boolean> => {
|
||||||
|
const nonce = randomBytes(32).toString('hex');
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'GET',
|
||||||
|
redirect: 'error',
|
||||||
|
signal: AbortSignal.timeout(options.timeoutMs ?? 1_000),
|
||||||
|
headers: {
|
||||||
|
'x-sammo-challenge': nonce,
|
||||||
|
'x-sammo-signature': mac(options.key, `sammo-host-boot-request-v1\n${nonce}`),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!response.ok || !response.body) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
throw new Error('Host boot response unavailable.');
|
||||||
|
}
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const chunks: Uint8Array[] = [];
|
||||||
|
let size = 0;
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
size += value.length;
|
||||||
|
if (size > 2_048) throw new Error('Host boot response exceeds its limit.');
|
||||||
|
chunks.push(value);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await reader.cancel();
|
||||||
|
}
|
||||||
|
const body: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||||
|
if (
|
||||||
|
!isRecord(body) ||
|
||||||
|
body.version !== 1 ||
|
||||||
|
body.challenge !== nonce ||
|
||||||
|
typeof body.bootId !== 'string' ||
|
||||||
|
!/^[a-f0-9]{64}$/.test(body.bootId) ||
|
||||||
|
typeof body.signature !== 'string' ||
|
||||||
|
!/^[a-f0-9]{64}$/.test(body.signature)
|
||||||
|
) {
|
||||||
|
throw new Error('Host boot response is invalid.');
|
||||||
|
}
|
||||||
|
const expected = mac(options.key, `sammo-host-boot-response-v1\n${nonce}\n${body.bootId}`);
|
||||||
|
if (!timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(body.signature, 'hex'))) {
|
||||||
|
throw new Error('Host boot response signature is invalid.');
|
||||||
|
}
|
||||||
|
if (baseline === null) {
|
||||||
|
baseline = body.bootId;
|
||||||
|
options.onVerified?.();
|
||||||
|
}
|
||||||
|
changed ||= body.bootId !== baseline;
|
||||||
|
return changed;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
hasChanged(): Promise<boolean> {
|
||||||
|
if (changed) return Promise.resolve(true);
|
||||||
|
if (inFlight) return inFlight;
|
||||||
|
const current = now();
|
||||||
|
const wall = wallNow();
|
||||||
|
const discontinuity = Math.abs(wall - lastWall - (current - lastAttempt)) > 1_000;
|
||||||
|
if (current - lastAttempt < (options.pollMs ?? 2_000) && !discontinuity) return Promise.resolve(false);
|
||||||
|
lastAttempt = current;
|
||||||
|
lastWall = wall;
|
||||||
|
inFlight = sample()
|
||||||
|
.catch(() => {
|
||||||
|
if (current - lastWarning >= 60_000) {
|
||||||
|
options.onUnavailable?.();
|
||||||
|
lastWarning = current;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
inFlight = null;
|
||||||
|
});
|
||||||
|
return inFlight;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const loadHostBootMonitor = async (env: NodeJS.ProcessEnv): Promise<HostBootMonitor | undefined> => {
|
||||||
|
const url = env.TURN_HOST_BOOT_URL?.trim();
|
||||||
|
const keyFile = env.TURN_HOST_BOOT_KEY_FILE?.trim();
|
||||||
|
if (!url && !keyFile) return undefined;
|
||||||
|
try {
|
||||||
|
if (!url || !keyFile) throw new Error('Incomplete optional configuration.');
|
||||||
|
const encoded = (await readFile(keyFile, 'utf8')).trim();
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(encoded)) throw new Error('Invalid optional key file.');
|
||||||
|
return createHostBootMonitor({
|
||||||
|
url,
|
||||||
|
key: Buffer.from(encoded, 'hex'),
|
||||||
|
onVerified: () => console.info('[turn-daemon] host boot identity verified.'),
|
||||||
|
onUnavailable: () => {
|
||||||
|
console.warn('[turn-daemon] host boot identity unavailable; ordinary lease recovery remains active.');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// 보조 관측기의 설정/파일 부재도 게임 기동의 필수 의존성이 되지 않는다.
|
||||||
|
console.warn('[turn-daemon] host boot observation disabled; check optional configuration and key file.');
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||||
import { asNumber, asRecord, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
import { asNumber, asRecord, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||||
import { acquireGameSchemaAdvisoryXactLock, GamePrisma } from '@sammo-ts/infra';
|
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> => {
|
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' } },
|
where: { userId_key: { userId, key: 'previous' } },
|
||||||
update: { value },
|
update: { value },
|
||||||
create: { userId, key: 'previous', value },
|
create: { userId, key: 'previous', value },
|
||||||
@@ -860,7 +861,7 @@ export const createGeneralFromJoin = async (options: {
|
|||||||
await db.generalTurnRevision.create({
|
await db.generalTurnRevision.create({
|
||||||
data: { generalId, revision: 0 },
|
data: { generalId, revision: 0 },
|
||||||
});
|
});
|
||||||
await db.generalAccessLog.upsert({
|
await upsertWithoutSequence(db.generalAccessLog, {
|
||||||
where: { generalId },
|
where: { generalId },
|
||||||
update: { userId: input.userId, lastRefresh: operationalAcceptedAt },
|
update: { userId: input.userId, lastRefresh: operationalAcceptedAt },
|
||||||
create: {
|
create: {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { randomInt } from 'node:crypto';
|
import { randomInt } from 'node:crypto';
|
||||||
|
|
||||||
import { asNumber, asRecord, GAME_TICKS_PER_TURN, JosaUtil, LiteHashDRBG, RandUtil, type RNG } from '@sammo-ts/common';
|
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);
|
return toReservation(inFlightToken, options.createdGameTick, ticksPerSecond);
|
||||||
}
|
}
|
||||||
if (
|
if (existing && (existing.validUntilTick === null || Number(existing.validUntilTick) < options.createdGameTick)) {
|
||||||
existing &&
|
|
||||||
(existing.validUntilTick === null || Number(existing.validUntilTick) < options.createdGameTick)
|
|
||||||
) {
|
|
||||||
await db.npcSelectionToken.deleteMany({
|
await db.npcSelectionToken.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
ownerUserId: userId,
|
ownerUserId: userId,
|
||||||
nonce: existing.nonce,
|
nonce: existing.nonce,
|
||||||
OR: [
|
OR: [{ validUntilTick: null }, { validUntilTick: { lt: BigInt(options.createdGameTick) } }],
|
||||||
{ validUntilTick: null },
|
|
||||||
{ validUntilTick: { lt: BigInt(options.createdGameTick) } },
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
existing = null;
|
existing = null;
|
||||||
@@ -425,9 +420,7 @@ export const reserveNpcPossessionCandidates = async (options: {
|
|||||||
const validUntilTick = options.createdGameTick + Math.round(validSeconds * ticksPerSecond);
|
const validUntilTick = options.createdGameTick + Math.round(validSeconds * ticksPerSecond);
|
||||||
const pickMoreFromTick = options.createdGameTick + Math.round(pickMoreSeconds * ticksPerSecond);
|
const pickMoreFromTick = options.createdGameTick + Math.round(pickMoreSeconds * ticksPerSecond);
|
||||||
const validUntil = new Date(now.getTime() + validSeconds * 1000);
|
const validUntil = new Date(now.getTime() + validSeconds * 1000);
|
||||||
const refreshedPickMoreFrom = new Date(
|
const refreshedPickMoreFrom = new Date(now.getTime() + pickMoreSeconds * 1000);
|
||||||
now.getTime() + pickMoreSeconds * 1000
|
|
||||||
);
|
|
||||||
const nonce = randomInt(0, 0x10000000);
|
const nonce = randomInt(0, 0x10000000);
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
@@ -566,7 +559,7 @@ export const possessNpcGeneral = async (options: {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await db.generalAccessLog.upsert({
|
await upsertWithoutSequence(db.generalAccessLog, {
|
||||||
where: { generalId },
|
where: { generalId },
|
||||||
update: {
|
update: {
|
||||||
userId,
|
userId,
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { performance } from 'node:perf_hooks';
|
||||||
|
import { setTimeout } from 'node:timers/promises';
|
||||||
|
import { ReservedTurnLeaseBusyError } from './reservedTurnStore.js';
|
||||||
|
|
||||||
|
/** rollback 완료 뒤에만 대기한다. 다음 loop에서 pause/lease gate와 최신 큐를 다시 읽는다. */
|
||||||
|
export const createReservedTurnLeaseRetry = (
|
||||||
|
options: {
|
||||||
|
now?: () => number;
|
||||||
|
sleep?: (ms: number) => Promise<void>;
|
||||||
|
maxWaitMs?: number;
|
||||||
|
onWait?: (queueKey: string) => void;
|
||||||
|
} = {}
|
||||||
|
) => {
|
||||||
|
const now = options.now ?? (() => performance.now());
|
||||||
|
const sleep = options.sleep ?? ((ms: number) => setTimeout(ms));
|
||||||
|
const maxWaitMs = options.maxWaitMs ?? 5 * 60_000 + 1_000;
|
||||||
|
let startedAt: number | null = null;
|
||||||
|
let lastReportedAt = -Infinity;
|
||||||
|
return {
|
||||||
|
reset(): void {
|
||||||
|
startedAt = null;
|
||||||
|
lastReportedAt = -Infinity;
|
||||||
|
},
|
||||||
|
async wait(error: unknown): Promise<boolean> {
|
||||||
|
if (!(error instanceof ReservedTurnLeaseBusyError)) return false;
|
||||||
|
const current = now();
|
||||||
|
startedAt ??= current;
|
||||||
|
const remaining = maxWaitMs - (current - startedAt);
|
||||||
|
if (remaining <= 0) return false;
|
||||||
|
if (current - lastReportedAt >= 30_000) {
|
||||||
|
options.onWait?.(error.queueKey);
|
||||||
|
lastReportedAt = current;
|
||||||
|
}
|
||||||
|
await sleep(Math.min(1_000, remaining));
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -129,6 +129,14 @@ export class ReservedTurnLeaseConflictError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 실행 전 획득 충돌만 재시도한다. flush/finalize의 소유권 상실과 구분한다. */
|
||||||
|
export class ReservedTurnLeaseBusyError extends ReservedTurnLeaseConflictError {
|
||||||
|
constructor(queueKey: string) {
|
||||||
|
super(queueKey);
|
||||||
|
this.name = 'ReservedTurnLeaseBusyError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class InMemoryReservedTurnStore {
|
export class InMemoryReservedTurnStore {
|
||||||
private readonly generalTurns = new Map<number, ReservedTurnEntry[]>();
|
private readonly generalTurns = new Map<number, ReservedTurnEntry[]>();
|
||||||
private readonly nationTurns = new Map<string, ReservedTurnEntry[]>();
|
private readonly nationTurns = new Map<string, ReservedTurnEntry[]>();
|
||||||
@@ -249,11 +257,7 @@ export class InMemoryReservedTurnStore {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
pruneNationKeys(Array.from(this.nationTurns.keys()), (key) => this.nationTurns.delete(key));
|
pruneNationKeys(Array.from(this.nationTurns.keys()), (key) => this.nationTurns.delete(key));
|
||||||
for (const keys of [
|
for (const keys of [this.dirtyNationKeys, this.pendingNationInitializationKeys, this.leasedNationKeys]) {
|
||||||
this.dirtyNationKeys,
|
|
||||||
this.pendingNationInitializationKeys,
|
|
||||||
this.leasedNationKeys,
|
|
||||||
]) {
|
|
||||||
for (const key of Array.from(keys)) {
|
for (const key of Array.from(keys)) {
|
||||||
const nationId = Number(key.split(':', 1)[0]);
|
const nationId = Number(key.split(':', 1)[0]);
|
||||||
if (deletedNations.has(nationId)) {
|
if (deletedNations.has(nationId)) {
|
||||||
@@ -376,7 +380,7 @@ export class InMemoryReservedTurnStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (claimed.count !== 1) {
|
if (claimed.count !== 1) {
|
||||||
throw new ReservedTurnLeaseConflictError(`general:${generalId}`);
|
throw new ReservedTurnLeaseBusyError(`general:${generalId}`);
|
||||||
}
|
}
|
||||||
this.leasedGeneralIds.add(generalId);
|
this.leasedGeneralIds.add(generalId);
|
||||||
return !retainedExistingLease;
|
return !retainedExistingLease;
|
||||||
@@ -427,7 +431,7 @@ export class InMemoryReservedTurnStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (claimed.count !== 1) {
|
if (claimed.count !== 1) {
|
||||||
throw new ReservedTurnLeaseConflictError(`nation:${nationId}:${officerLevel}`);
|
throw new ReservedTurnLeaseBusyError(`nation:${nationId}:${officerLevel}`);
|
||||||
}
|
}
|
||||||
this.leasedNationKeys.add(buildNationKey(nationId, officerLevel));
|
this.leasedNationKeys.add(buildNationKey(nationId, officerLevel));
|
||||||
return !retainedExistingLease;
|
return !retainedExistingLease;
|
||||||
@@ -904,6 +908,24 @@ export class InMemoryReservedTurnStore {
|
|||||||
await this.persistChanges(this.prisma, changes);
|
await this.persistChanges(this.prisma, changes);
|
||||||
this.acknowledgeDirtyState(changes);
|
this.acknowledgeDirtyState(changes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 실행 루프 종료 뒤 호출한다. rollback으로 journal에서 빠진 DB 임대도 해제한다. */
|
||||||
|
async releaseOwnedLeases(): Promise<void> {
|
||||||
|
const results = await Promise.allSettled([
|
||||||
|
this.prisma.generalTurnRevision?.updateMany({
|
||||||
|
where: { leaseOwner: this.leaseOwner },
|
||||||
|
data: { leaseOwner: null, leaseExpiresAt: null },
|
||||||
|
}),
|
||||||
|
this.prisma.nationTurnRevision?.updateMany({
|
||||||
|
where: { leaseOwner: this.leaseOwner },
|
||||||
|
data: { leaseOwner: null, leaseExpiresAt: null },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []));
|
||||||
|
if (errors.length) throw new AggregateError(errors, 'Reserved turn lease cleanup failed.');
|
||||||
|
this.leasedGeneralIds.clear();
|
||||||
|
this.leasedNationKeys.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createReservedTurnStore = async (options: ReservedTurnStoreOptions): Promise<ReservedTurnStoreHandle> => {
|
export const createReservedTurnStore = async (options: ReservedTurnStoreOptions): Promise<ReservedTurnStoreHandle> => {
|
||||||
@@ -918,6 +940,12 @@ export const createReservedTurnStore = async (options: ReservedTurnStoreOptions)
|
|||||||
await store.loadAll();
|
await store.loadAll();
|
||||||
return {
|
return {
|
||||||
store,
|
store,
|
||||||
close: () => connector.disconnect(),
|
close: async () => {
|
||||||
|
try {
|
||||||
|
await store.releaseOwnedLeases();
|
||||||
|
} finally {
|
||||||
|
await connector.disconnect();
|
||||||
|
}
|
||||||
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -2,7 +2,7 @@ import type { GameClockPhase } from '@sammo-ts/common';
|
|||||||
|
|
||||||
/** Gateway의 실행 gate와 durable 시계를 명령 claim 전에 맞춘다. */
|
/** Gateway의 실행 gate와 durable 시계를 명령 claim 전에 맞춘다. */
|
||||||
export const createRuntimePauseGate = (options: {
|
export const createRuntimePauseGate = (options: {
|
||||||
assertLease(): void;
|
assertLease(): void | Promise<void>;
|
||||||
shouldPause(): Promise<boolean>;
|
shouldPause(): Promise<boolean>;
|
||||||
getPhase(): GameClockPhase;
|
getPhase(): GameClockPhase;
|
||||||
isExplicitlyPaused(): boolean;
|
isExplicitlyPaused(): boolean;
|
||||||
@@ -11,7 +11,7 @@ export const createRuntimePauseGate = (options: {
|
|||||||
}): (() => Promise<boolean>) => {
|
}): (() => Promise<boolean>) => {
|
||||||
let lastPaused: boolean | null = null;
|
let lastPaused: boolean | null = null;
|
||||||
return async () => {
|
return async () => {
|
||||||
options.assertLease();
|
await options.assertLease();
|
||||||
const paused = await options.shouldPause();
|
const paused = await options.shouldPause();
|
||||||
const phase = options.getPhase();
|
const phase = options.getPhase();
|
||||||
// 오류 정지는 Gateway 상태만 PAUSED로 바꿀 수 있다. 그대로 두면 가입은
|
// 오류 정지는 Gateway 상태만 PAUSED로 바꿀 수 있다. 그대로 두면 가입은
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { asNumber, asRecord, GAME_TICKS_PER_TURN, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
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 (
|
const clearUnusedReservations = async (db: DatabaseClient, userId: string, nowTick: number): Promise<void> => {
|
||||||
db: DatabaseClient,
|
|
||||||
userId: string,
|
|
||||||
nowTick: number
|
|
||||||
): Promise<void> => {
|
|
||||||
await db.selectPoolEntry.updateMany({
|
await db.selectPoolEntry.updateMany({
|
||||||
where: {
|
where: {
|
||||||
generalId: null,
|
generalId: null,
|
||||||
@@ -914,7 +911,7 @@ export const createGeneralFromSelectionPool = async (options: {
|
|||||||
if (occupied.count === 0) {
|
if (occupied.count === 0) {
|
||||||
throw new Error('장수 등록 중 선택 후보 점유에 실패했습니다.');
|
throw new Error('장수 등록 중 선택 후보 점유에 실패했습니다.');
|
||||||
}
|
}
|
||||||
await db.generalAccessLog.upsert({
|
await upsertWithoutSequence(db.generalAccessLog, {
|
||||||
where: { generalId },
|
where: { generalId },
|
||||||
update: { userId, lastRefresh: options.operationalAcceptedAt },
|
update: { userId, lastRefresh: options.operationalAcceptedAt },
|
||||||
create: { generalId, userId, lastRefresh: options.operationalAcceptedAt },
|
create: { generalId, userId, lastRefresh: options.operationalAcceptedAt },
|
||||||
|
|||||||
@@ -108,6 +108,8 @@ import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lif
|
|||||||
import { EngineStateManager } from './engineStateManager.js';
|
import { EngineStateManager } from './engineStateManager.js';
|
||||||
import { applyRuntimeClockShift } from './runtimeClockShift.js';
|
import { applyRuntimeClockShift } from './runtimeClockShift.js';
|
||||||
import { applyRuntimeGameSettings } from './runtimeGameSettings.js';
|
import { applyRuntimeGameSettings } from './runtimeGameSettings.js';
|
||||||
|
import { createReservedTurnLeaseRetry } from './reservedTurnLeaseRetry.js';
|
||||||
|
import type { HostBootMonitor } from './hostBootMonitor.js';
|
||||||
|
|
||||||
export interface TurnDaemonRuntimeOptions {
|
export interface TurnDaemonRuntimeOptions {
|
||||||
profile: string;
|
profile: string;
|
||||||
@@ -134,11 +136,13 @@ export interface TurnDaemonRuntimeOptions {
|
|||||||
leaseDurationMs?: number;
|
leaseDurationMs?: number;
|
||||||
leaseOwnerId?: string;
|
leaseOwnerId?: string;
|
||||||
enableLeaseHeartbeat?: boolean;
|
enableLeaseHeartbeat?: boolean;
|
||||||
|
hostBootMonitor?: HostBootMonitor;
|
||||||
/**
|
/**
|
||||||
* Isolated, single-process fixture acceleration only. Reserved turns are
|
* Isolated, single-process fixture acceleration only. Reserved turns are
|
||||||
* loaded once and no concurrent API writer may touch this database.
|
* loaded once and no concurrent API writer may touch this database.
|
||||||
*/
|
*/
|
||||||
exclusiveFastForward?: boolean;
|
exclusiveFastForward?: boolean;
|
||||||
|
databaseTransactionMaxWaitMs?: number;
|
||||||
databaseTransactionTimeoutMs?: number;
|
databaseTransactionTimeoutMs?: number;
|
||||||
onActionResolved?: NonNullable<Parameters<typeof createReservedTurnHandler>[0]['onActionResolved']>;
|
onActionResolved?: NonNullable<Parameters<typeof createReservedTurnHandler>[0]['onActionResolved']>;
|
||||||
}
|
}
|
||||||
@@ -933,6 +937,7 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
profileName: options.profileName ?? options.profile,
|
profileName: options.profileName ?? options.profile,
|
||||||
reservedTurns: reservedTurnStoreHandle?.store,
|
reservedTurns: reservedTurnStoreHandle?.store,
|
||||||
turnDaemonLease: turnDaemonLease ?? undefined,
|
turnDaemonLease: turnDaemonLease ?? undefined,
|
||||||
|
transactionMaxWaitMs: options.databaseTransactionMaxWaitMs,
|
||||||
transactionTimeoutMs: options.databaseTransactionTimeoutMs,
|
transactionTimeoutMs: options.databaseTransactionTimeoutMs,
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
@@ -983,6 +988,7 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
prepareClockRecovery = dbHooks.prepareRealtimeRecovery;
|
prepareClockRecovery = dbHooks.prepareRealtimeRecovery;
|
||||||
prunePreviousAudit = dbHooks.prunePreviousAudit;
|
prunePreviousAudit = dbHooks.prunePreviousAudit;
|
||||||
close = async () => {
|
close = async () => {
|
||||||
|
await adminActionConsumer?.stop();
|
||||||
if (auctionBidder) {
|
if (auctionBidder) {
|
||||||
await auctionBidder.close();
|
await auctionBidder.close();
|
||||||
}
|
}
|
||||||
@@ -993,12 +999,15 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
await tournamentRewardFinalizer.close();
|
await tournamentRewardFinalizer.close();
|
||||||
}
|
}
|
||||||
await dbHooks.close();
|
await dbHooks.close();
|
||||||
if (reservedTurnStoreHandle) {
|
try {
|
||||||
await reservedTurnStoreHandle.close();
|
await reservedTurnStoreHandle?.close();
|
||||||
}
|
} finally {
|
||||||
|
try {
|
||||||
await gatewayGate?.close();
|
await gatewayGate?.close();
|
||||||
await adminActionConsumer?.stop();
|
} finally {
|
||||||
await turnDaemonLease?.close();
|
await turnDaemonLease?.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
} else if (reservedTurnStoreHandle) {
|
} else if (reservedTurnStoreHandle) {
|
||||||
hooks = {
|
hooks = {
|
||||||
@@ -1007,9 +1016,12 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
close = async () => {
|
close = async () => {
|
||||||
await reservedTurnStoreHandle.close();
|
|
||||||
await gatewayGate?.close();
|
|
||||||
await adminActionConsumer?.stop();
|
await adminActionConsumer?.stop();
|
||||||
|
try {
|
||||||
|
await reservedTurnStoreHandle.close();
|
||||||
|
} finally {
|
||||||
|
await gatewayGate?.close();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
} else if (gatewayGate) {
|
} else if (gatewayGate) {
|
||||||
hooks = {
|
hooks = {
|
||||||
@@ -1068,12 +1080,17 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
const baseClose = close;
|
const baseClose = close;
|
||||||
close = async () => {
|
close = async () => {
|
||||||
stopClockProjectionWorker();
|
stopClockProjectionWorker();
|
||||||
await baseClose();
|
const baseResults = await Promise.allSettled([baseClose()]);
|
||||||
await neutralAuctionRegistrar.close();
|
// queue 임대 정리 실패도 다른 연결/worker의 종료를 막지 않게 한다.
|
||||||
if (redisConnector) {
|
const results = await Promise.allSettled([
|
||||||
await redisConnector.disconnect();
|
neutralAuctionRegistrar.close(),
|
||||||
}
|
redisConnector?.disconnect(),
|
||||||
await commandConnector?.disconnect();
|
commandConnector?.disconnect(),
|
||||||
|
]);
|
||||||
|
const failures = [...baseResults, ...results].flatMap((result) =>
|
||||||
|
result.status === 'rejected' ? [result.reason] : []
|
||||||
|
);
|
||||||
|
if (failures.length) throw new AggregateError(failures, 'Turn daemon connection cleanup failed.');
|
||||||
};
|
};
|
||||||
|
|
||||||
const resolvedControlQueue = options.controlQueue ?? databaseCommandQueue ?? controlQueue;
|
const resolvedControlQueue = options.controlQueue ?? databaseCommandQueue ?? controlQueue;
|
||||||
@@ -1107,7 +1124,8 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
processor,
|
processor,
|
||||||
hooks,
|
hooks,
|
||||||
pauseGate: createRuntimePauseGate({
|
pauseGate: createRuntimePauseGate({
|
||||||
assertLease: () => {
|
assertLease: async () => {
|
||||||
|
await turnDaemonLease?.checkHostBoot();
|
||||||
if (turnDaemonLease?.isLost()) throw turnDaemonLease.getLossError();
|
if (turnDaemonLease?.isLost()) throw turnDaemonLease.getLossError();
|
||||||
},
|
},
|
||||||
shouldPause: async () => (await pauseGate?.()) ?? false,
|
shouldPause: async () => (await pauseGate?.()) ?? false,
|
||||||
@@ -1125,6 +1143,9 @@ const createTurnDaemonRuntimeWithLease = async (
|
|||||||
// accumulated world before every due tick in that isolated mode;
|
// accumulated world before every due tick in that isolated mode;
|
||||||
// production and gateway-managed runtimes keep rollback savepoints.
|
// production and gateway-managed runtimes keep rollback savepoints.
|
||||||
stateManager: options.exclusiveFastForward ? undefined : stateManager,
|
stateManager: options.exclusiveFastForward ? undefined : stateManager,
|
||||||
|
runErrorRetry: createReservedTurnLeaseRetry({
|
||||||
|
onWait: (queueKey) => console.info(`[turn-daemon] waiting for reserved turn lease: ${queueKey}`),
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
{ profile: options.profile, defaultBudget }
|
{ profile: options.profile, defaultBudget }
|
||||||
);
|
);
|
||||||
@@ -1177,6 +1198,7 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
|
|||||||
ownerId: options.leaseOwnerId,
|
ownerId: options.leaseOwnerId,
|
||||||
leaseDurationMs: options.leaseDurationMs,
|
leaseDurationMs: options.leaseDurationMs,
|
||||||
heartbeat: options.enableLeaseHeartbeat,
|
heartbeat: options.enableLeaseHeartbeat,
|
||||||
|
hostBootMonitor: options.hostBootMonitor,
|
||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
if (turnDaemonLease && !(await turnDaemonLease.acquire())) {
|
if (turnDaemonLease && !(await turnDaemonLease.acquire())) {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||||
import { asRecord, HALL_OF_FAME_TYPES, resolveLegacyTextColor, type HallOfFameType } from '@sammo-ts/common';
|
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) {
|
if (!bidder?.userId || bidder.userId !== dbBidder?.userId) {
|
||||||
throw new Error(`Unification auction refund owner is unavailable: ${planned.auctionId}.`);
|
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' } },
|
where: { userId_key: { userId: bidder.userId, key: 'previous' } },
|
||||||
update: { value: { increment: highest.amount } },
|
update: { value: { increment: highest.amount } },
|
||||||
create: { userId: bidder.userId, key: 'previous', value: highest.amount },
|
create: { userId: bidder.userId, key: 'previous', value: highest.amount },
|
||||||
});
|
});
|
||||||
await transaction.rankData.upsert({
|
await upsertWithoutSequence(transaction.rankData, {
|
||||||
where: {
|
where: {
|
||||||
generalId_type: { generalId: bidder.id, type: 'inherit_spent_dyn' },
|
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>;
|
) as Record<(typeof ALL_MERGED_INHERITANCE_KEYS)[number], number>;
|
||||||
const total = Math.floor(previous + Object.values(mergedPoints).reduce((sum, value) => sum + value, 0));
|
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' } },
|
where: { userId_key: { userId, key: 'previous' } },
|
||||||
update: { value: total },
|
update: { value: total },
|
||||||
create: { userId, key: 'previous', value: total },
|
create: { userId, key: 'previous', value: total },
|
||||||
@@ -508,7 +509,7 @@ export const persistUnificationFinalization = async (
|
|||||||
}),
|
}),
|
||||||
generationKey: input.generationKey,
|
generationKey: input.generationKey,
|
||||||
};
|
};
|
||||||
await transaction.oldNation.upsert({
|
await upsertWithoutSequence(transaction.oldNation, {
|
||||||
where: { serverId_nation_sourceId: { serverId, nation: input.winnerNationId, sourceId: 0 } },
|
where: { serverId_nation_sourceId: { serverId, nation: input.winnerNationId, sourceId: 0 } },
|
||||||
update: { data: asJson(winnerData), date: input.completedAt },
|
update: { data: asJson(winnerData), date: input.completedAt },
|
||||||
create: {
|
create: {
|
||||||
@@ -525,7 +526,7 @@ export const persistUnificationFinalization = async (
|
|||||||
generals: neutralGenerals.map((general) => general.id),
|
generals: neutralGenerals.map((general) => general.id),
|
||||||
generationKey: input.generationKey,
|
generationKey: input.generationKey,
|
||||||
};
|
};
|
||||||
await transaction.oldNation.upsert({
|
await upsertWithoutSequence(transaction.oldNation, {
|
||||||
where: { serverId_nation_sourceId: { serverId, nation: 0, sourceId: 0 } },
|
where: { serverId_nation_sourceId: { serverId, nation: 0, sourceId: 0 } },
|
||||||
update: { data: neutralData, date: input.completedAt },
|
update: { data: neutralData, date: input.completedAt },
|
||||||
create: { serverId, nation: 0, sourceId: 0, 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 },
|
availability: { battleResultLogs: true },
|
||||||
generationKey: input.generationKey,
|
generationKey: input.generationKey,
|
||||||
};
|
};
|
||||||
await transaction.oldGeneral.upsert({
|
await upsertWithoutSequence(transaction.oldGeneral, {
|
||||||
where: { by_no: { serverId, generalNo: general.id } },
|
where: { by_no: { serverId, generalNo: general.id } },
|
||||||
update: {
|
update: {
|
||||||
owner: general.userId ?? null,
|
owner: general.userId ?? null,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { existingRowIdOrNext } from '@sammo-ts/infra';
|
||||||
import { handleCityOfficeRequest, settleCityOfficeRequests } from './cityOfficeRequests.js';
|
import { handleCityOfficeRequest, settleCityOfficeRequests } from './cityOfficeRequests.js';
|
||||||
import type {
|
import type {
|
||||||
TurnDaemonCommandHandler,
|
TurnDaemonCommandHandler,
|
||||||
@@ -2864,8 +2865,8 @@ const insertVoteSelection = async (
|
|||||||
}
|
}
|
||||||
const createdAt = new Date();
|
const createdAt = new Date();
|
||||||
const rows = await ctx.commandDb.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
const rows = await ctx.commandDb.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
||||||
INSERT INTO vote (vote_id, general_id, nation_id, selection, created_at)
|
INSERT INTO vote (id, vote_id, general_id, nation_id, selection, created_at)
|
||||||
SELECT poll.id,
|
SELECT ${existingRowIdOrNext('vote', GamePrisma.sql`stable_id.vote_id = poll.id AND stable_id.general_id = ${general.id}`)}, poll.id,
|
||||||
${general.id},
|
${general.id},
|
||||||
${general.nationId},
|
${general.nationId},
|
||||||
CAST(${JSON.stringify(selection)} AS jsonb),
|
CAST(${JSON.stringify(selection)} AS jsonb),
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { upsertWithoutSequence } from '@sammo-ts/infra';
|
||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
|
|
||||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||||
@@ -44,7 +45,7 @@ export const persistYearbookSnapshot = async (
|
|||||||
globalAction,
|
globalAction,
|
||||||
});
|
});
|
||||||
|
|
||||||
await transaction.yearbookHistory.upsert({
|
await upsertWithoutSequence(transaction.yearbookHistory, {
|
||||||
where: {
|
where: {
|
||||||
profileName_year_month_sourceId: {
|
profileName_year_month_sourceId: {
|
||||||
profileName: snapshot.serverId,
|
profileName: snapshot.serverId,
|
||||||
|
|||||||
@@ -198,6 +198,23 @@ integration('general batch persistence', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
expect(writes).toBe(2);
|
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({
|
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId: firstId } })).toMatchObject({
|
||||||
userId: 'original-owner',
|
userId: 'original-owner',
|
||||||
lastRefresh: at,
|
lastRefresh: at,
|
||||||
|
|||||||
@@ -1,12 +1,20 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
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 { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||||
|
|
||||||
import { persistGeneralLifecycleEvents } from '../src/turn/generalTurnLifecyclePersistence.js';
|
import { persistGeneralLifecycleEvents } from '../src/turn/generalTurnLifecyclePersistence.js';
|
||||||
import type { GeneralLifecycleEvent } from '../src/turn/inMemoryWorld.js';
|
import type { GeneralLifecycleEvent } from '../src/turn/inMemoryWorld.js';
|
||||||
import type { TurnGeneral } from '../src/turn/types.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 => ({
|
const archivedGeneral = (): TurnGeneral => ({
|
||||||
id: 91,
|
id: 91,
|
||||||
userId: null,
|
userId: null,
|
||||||
@@ -65,12 +73,13 @@ describe('general lifecycle archive history', () => {
|
|||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
rankData: {
|
rankData: {
|
||||||
|
update: missingRecordUpdate,
|
||||||
findMany: vi.fn(async () => [
|
findMany: vi.fn(async () => [
|
||||||
{ type: 'warnum', value: 2 },
|
{ type: 'warnum', value: 2 },
|
||||||
{ type: 'killnum', value: 1 },
|
{ type: 'killnum', value: 1 },
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
oldGeneral: { upsert },
|
oldGeneral: { update: missingRecordUpdate, upsert },
|
||||||
} as unknown as GamePrisma.TransactionClient;
|
} as unknown as GamePrisma.TransactionClient;
|
||||||
const event: GeneralLifecycleEvent = {
|
const event: GeneralLifecycleEvent = {
|
||||||
generalId: general.id,
|
generalId: general.id,
|
||||||
@@ -137,6 +146,7 @@ describe('general lifecycle archive history', () => {
|
|||||||
updateMany: vi.fn(async () => ({ count: 1 })),
|
updateMany: vi.fn(async () => ({ count: 1 })),
|
||||||
},
|
},
|
||||||
rankData: {
|
rankData: {
|
||||||
|
update: missingRecordUpdate,
|
||||||
findMany: vi.fn(async () => [
|
findMany: vi.fn(async () => [
|
||||||
{ type: 'warnum', value: 10 },
|
{ type: 'warnum', value: 10 },
|
||||||
{ type: 'inherit_earned', value: 123 },
|
{ type: 'inherit_earned', value: 123 },
|
||||||
@@ -156,6 +166,7 @@ describe('general lifecycle archive history', () => {
|
|||||||
update: vi.fn(async () => undefined),
|
update: vi.fn(async () => undefined),
|
||||||
},
|
},
|
||||||
inheritancePoint: {
|
inheritancePoint: {
|
||||||
|
update: missingRecordUpdate,
|
||||||
findMany: vi.fn(async () => [{ key: 'previous', value: 0 }]),
|
findMany: vi.fn(async () => [{ key: 'previous', value: 0 }]),
|
||||||
upsert: vi.fn(async () => undefined),
|
upsert: vi.fn(async () => undefined),
|
||||||
deleteMany: vi.fn(async () => ({ count: 0 })),
|
deleteMany: vi.fn(async () => ({ count: 0 })),
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { createHmac, randomBytes } from 'node:crypto';
|
||||||
|
import { once } from 'node:events';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { createHostBootMonitor, loadHostBootMonitor } from '../src/turn/hostBootMonitor.js';
|
||||||
|
|
||||||
|
const cleanups: Array<() => Promise<void>> = [];
|
||||||
|
afterEach(async () => {
|
||||||
|
await Promise.all(cleanups.splice(0).map((cleanup) => cleanup()));
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = async () => {
|
||||||
|
const key = randomBytes(32);
|
||||||
|
let bootId = 'a'.repeat(64);
|
||||||
|
let replay: string | null = null;
|
||||||
|
let mode: 'valid' | 'replay' | 'forged' | 'oversized' | 'offline' | 'hang' = 'valid';
|
||||||
|
const requests: string[] = [];
|
||||||
|
const server = createServer((request, response) => {
|
||||||
|
const nonce = String(request.headers['x-sammo-challenge']);
|
||||||
|
requests.push(nonce);
|
||||||
|
expect(request.headers['x-sammo-signature']).toBe(
|
||||||
|
createHmac('sha256', key).update(`sammo-host-boot-request-v1\n${nonce}`).digest('hex')
|
||||||
|
);
|
||||||
|
if (mode === 'hang') return;
|
||||||
|
if (mode === 'offline') {
|
||||||
|
response.writeHead(503).end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (mode === 'oversized') {
|
||||||
|
response.end('x'.repeat(4096));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (mode === 'replay') {
|
||||||
|
response.end(replay);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body = JSON.stringify({
|
||||||
|
version: 1,
|
||||||
|
challenge: nonce,
|
||||||
|
bootId,
|
||||||
|
signature:
|
||||||
|
mode === 'forged'
|
||||||
|
? '0'.repeat(64)
|
||||||
|
: createHmac('sha256', key)
|
||||||
|
.update(`sammo-host-boot-response-v1\n${nonce}\n${bootId}`)
|
||||||
|
.digest('hex'),
|
||||||
|
});
|
||||||
|
replay ??= body;
|
||||||
|
response.end(body);
|
||||||
|
});
|
||||||
|
server.listen(0, '127.0.0.1');
|
||||||
|
await once(server, 'listening');
|
||||||
|
cleanups.push(
|
||||||
|
() =>
|
||||||
|
new Promise<void>((resolve) => {
|
||||||
|
server.close(() => resolve());
|
||||||
|
server.closeAllConnections();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const address = server.address();
|
||||||
|
if (!address || typeof address === 'string') throw new Error('Missing fixture listener');
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
requests,
|
||||||
|
url: `http://127.0.0.1:${address.port}/v1/boot-id`,
|
||||||
|
setBoot: (value: string) => {
|
||||||
|
bootId = value;
|
||||||
|
},
|
||||||
|
setMode: (value: typeof mode) => {
|
||||||
|
mode = value;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('Windows boot observation', () => {
|
||||||
|
it('uses a stable baseline, survives outages, and latches a signed boot change', async () => {
|
||||||
|
const f = await fixture();
|
||||||
|
const monitor = createHostBootMonitor({ ...f, pollMs: 0 });
|
||||||
|
expect(await monitor.hasChanged()).toBe(false);
|
||||||
|
f.setMode('offline');
|
||||||
|
expect(await monitor.hasChanged()).toBe(false);
|
||||||
|
f.setBoot('b'.repeat(64));
|
||||||
|
f.setMode('valid');
|
||||||
|
expect(await monitor.hasChanged()).toBe(true);
|
||||||
|
f.setMode('offline');
|
||||||
|
expect(await monitor.hasChanged()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['replay', 'forged', 'oversized', 'hang'] as const)(
|
||||||
|
'rejects %s without changing the baseline',
|
||||||
|
async (mode) => {
|
||||||
|
const f = await fixture();
|
||||||
|
const onUnavailable = vi.fn();
|
||||||
|
const monitor = createHostBootMonitor({ ...f, pollMs: 0, timeoutMs: 100, onUnavailable });
|
||||||
|
expect(await monitor.hasChanged()).toBe(false);
|
||||||
|
f.setBoot('b'.repeat(64));
|
||||||
|
f.setMode(mode);
|
||||||
|
expect(await monitor.hasChanged()).toBe(false);
|
||||||
|
expect(onUnavailable).toHaveBeenCalledOnce();
|
||||||
|
f.setMode('valid');
|
||||||
|
expect(await monitor.hasChanged()).toBe(true);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
it('samples immediately after a wall-clock jump despite a frozen monotonic cache and coalesces requests', async () => {
|
||||||
|
const f = await fixture();
|
||||||
|
let wall = 10_000;
|
||||||
|
const monitor = createHostBootMonitor({ ...f, now: () => 0, wallNow: () => wall });
|
||||||
|
expect(await monitor.hasChanged()).toBe(false);
|
||||||
|
expect(await monitor.hasChanged()).toBe(false);
|
||||||
|
expect(f.requests).toHaveLength(1);
|
||||||
|
wall += 300_000;
|
||||||
|
f.setBoot('b'.repeat(64));
|
||||||
|
expect(await Promise.all([monitor.hasChanged(), monitor.hasChanged()])).toEqual([true, true]);
|
||||||
|
expect(f.requests).toHaveLength(2);
|
||||||
|
expect(new Set(f.requests).size).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not block game startup when optional configuration or its key file is absent', async () => {
|
||||||
|
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
expect(await loadHostBootMonitor({})).toBeUndefined();
|
||||||
|
expect(await loadHostBootMonitor({ TURN_HOST_BOOT_URL: 'http://host/v1/boot-id' })).toBeUndefined();
|
||||||
|
expect(
|
||||||
|
await loadHostBootMonitor({
|
||||||
|
TURN_HOST_BOOT_URL: 'http://host/v1/boot-id',
|
||||||
|
TURN_HOST_BOOT_KEY_FILE: '/nonexistent-host-boot-key',
|
||||||
|
})
|
||||||
|
).toBeUndefined();
|
||||||
|
expect(() =>
|
||||||
|
createHostBootMonitor({ url: 'http://user:password@host/v1/boot-id', key: randomBytes(32) })
|
||||||
|
).toThrow('without credentials');
|
||||||
|
warning.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { writeFile } from 'node:fs/promises';
|
import { writeFile } from 'node:fs/promises';
|
||||||
import { performance } from 'node:perf_hooks';
|
import { performance } from 'node:perf_hooks';
|
||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
|
import {
|
||||||
|
decodeAuditDecisionSteps,
|
||||||
|
createGamePostgresConnector,
|
||||||
|
type GamePrisma,
|
||||||
|
type GamePrismaClient,
|
||||||
|
} from '@sammo-ts/infra';
|
||||||
import { persistAuditDecisions } from '../src/playAudit/decisionPersistence.js';
|
import { persistAuditDecisions } from '../src/playAudit/decisionPersistence.js';
|
||||||
import { buildAuditDecisionFixture } from './fixtures/playAuditDecision.js';
|
import { buildAuditDecisionFixture } from './fixtures/playAuditDecision.js';
|
||||||
|
|
||||||
@@ -61,11 +66,15 @@ describe.skipIf(!databaseUrl)('decision storage cost probe', () => {
|
|||||||
>`
|
>`
|
||||||
SELECT
|
SELECT
|
||||||
(SELECT count(*) FROM play_audit_decision) AS headers,
|
(SELECT count(*) FROM play_audit_decision) AS headers,
|
||||||
(SELECT sum(jsonb_array_length(steps)) FROM play_audit_decision_chunk) AS steps,
|
(SELECT sum(step_count) FROM play_audit_decision) AS steps,
|
||||||
(SELECT sum(pg_column_size(d)) FROM play_audit_decision d) AS "headerBytes",
|
(SELECT sum(pg_column_size(d)) FROM play_audit_decision d) AS "headerBytes",
|
||||||
(SELECT sum(pg_column_size(c)) FROM play_audit_decision_chunk c) AS "chunkBytes"
|
(SELECT sum(pg_column_size(c)) FROM play_audit_decision_chunk c) AS "chunkBytes"
|
||||||
`;
|
`;
|
||||||
expect(Number(storage!.steps)).toBe(201 * 302);
|
expect(Number(storage!.steps)).toBe(201 * 302);
|
||||||
|
const chunks = await db.playAuditDecisionChunk.findMany({ select: { steps: true } });
|
||||||
|
expect(chunks.reduce((total, chunk) => total + decodeAuditDecisionSteps(chunk.steps).length, 0)).toBe(
|
||||||
|
201 * 302
|
||||||
|
);
|
||||||
const relations = await db.$queryRaw<
|
const relations = await db.$queryRaw<
|
||||||
{ name: string; tableBytes: bigint; indexBytes: bigint; totalBytes: bigint }[]
|
{ name: string; tableBytes: bigint; indexBytes: bigint; totalBytes: bigint }[]
|
||||||
>`
|
>`
|
||||||
@@ -99,7 +108,8 @@ describe.skipIf(!databaseUrl)('decision storage cost probe', () => {
|
|||||||
`;
|
`;
|
||||||
const metrics = {
|
const metrics = {
|
||||||
scope: 'synthetic 201 decisions, 302 steps each; isolated schema, warm local reads',
|
scope: 'synthetic 201 decisions, 302 steps each; isolated schema, warm local reads',
|
||||||
limitations: 'Not production p95; no gameplay baseline, WAL or retained heap measurement. SQL counts cover only the persistence transaction. Repetitive synthetic steps compress well. Relation allocation can retain space from previous runs.',
|
limitations:
|
||||||
|
'Not production p95; no gameplay baseline, WAL or retained heap measurement. SQL counts cover only the persistence transaction. Repetitive synthetic steps compress well. Relation allocation can retain space from previous runs.',
|
||||||
decisions: 201,
|
decisions: 201,
|
||||||
steps: Number(storage!.steps),
|
steps: Number(storage!.steps),
|
||||||
chunks: 603,
|
chunks: 603,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
|
import { decodeAuditDecisionSteps, createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
|
||||||
import { persistAuditDecisions } from '../src/playAudit/decisionPersistence.js';
|
import { persistAuditDecisions } from '../src/playAudit/decisionPersistence.js';
|
||||||
import { buildAuditExecutionFixture, buildAuditDecisionFixture as draft } from './fixtures/playAuditDecision.js';
|
import { buildAuditExecutionFixture, buildAuditDecisionFixture as draft } from './fixtures/playAuditDecision.js';
|
||||||
import { prunePreviousAuditBatch } from '../src/playAudit/retention.js';
|
import { prunePreviousAuditBatch } from '../src/playAudit/retention.js';
|
||||||
@@ -36,7 +36,40 @@ integration('decision persistence and bounded retention', () => {
|
|||||||
});
|
});
|
||||||
it('rolls back gameplay/header/chunks on insert failure, retries and rejects divergent replay', async () => {
|
it('rolls back gameplay/header/chunks on insert failure, retries and rejects divergent replay', async () => {
|
||||||
const decision = draft('decision-one');
|
const decision = draft('decision-one');
|
||||||
if (decision.steps[0]?.kind === 'DECISION_START') decision.steps[0].effectivePolicy = {"schemaVersion":1,"general":{"priority":["징병"],"flags":{"징병":true,"출병":false}},"nation":{"priority":["천도"],"flags":{"천도":true},"values":{"reqNationGold":4321,"reqNationRice":100,"reqHumanWarUrgentGold":100,"reqHumanWarUrgentRice":100,"reqHumanWarRecommandGold":100,"reqHumanWarRecommandRice":100,"reqHumanDevelGold":100,"reqHumanDevelRice":100,"reqNpcWarGold":100,"reqNpcWarRice":100,"reqNpcDevelGold":100,"reqNpcDevelRice":100,"minimumResourceActionAmount":100,"maximumResourceActionAmount":100,"minNpcWarLeadership":100,"minWarCrew":100,"minNpcRecruitCityPopulation":100,"safeRecruitCityPopulationRatio":100,"properWarTrainAtmos":100,"cureThreshold":100},"combatForce":{"1":[2,3]},"supportForce":[4],"developForce":[5]}};
|
if (decision.steps[0]?.kind === 'DECISION_START')
|
||||||
|
decision.steps[0].effectivePolicy = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
general: { priority: ['징병'], flags: { 징병: true, 출병: false } },
|
||||||
|
nation: {
|
||||||
|
priority: ['천도'],
|
||||||
|
flags: { 천도: true },
|
||||||
|
values: {
|
||||||
|
reqNationGold: 4321,
|
||||||
|
reqNationRice: 100,
|
||||||
|
reqHumanWarUrgentGold: 100,
|
||||||
|
reqHumanWarUrgentRice: 100,
|
||||||
|
reqHumanWarRecommandGold: 100,
|
||||||
|
reqHumanWarRecommandRice: 100,
|
||||||
|
reqHumanDevelGold: 100,
|
||||||
|
reqHumanDevelRice: 100,
|
||||||
|
reqNpcWarGold: 100,
|
||||||
|
reqNpcWarRice: 100,
|
||||||
|
reqNpcDevelGold: 100,
|
||||||
|
reqNpcDevelRice: 100,
|
||||||
|
minimumResourceActionAmount: 100,
|
||||||
|
maximumResourceActionAmount: 100,
|
||||||
|
minNpcWarLeadership: 100,
|
||||||
|
minWarCrew: 100,
|
||||||
|
minNpcRecruitCityPopulation: 100,
|
||||||
|
safeRecruitCityPopulationRatio: 100,
|
||||||
|
properWarTrainAtmos: 100,
|
||||||
|
cureThreshold: 100,
|
||||||
|
},
|
||||||
|
combatForce: { '1': [2, 3] },
|
||||||
|
supportForce: [4],
|
||||||
|
developForce: [5],
|
||||||
|
},
|
||||||
|
};
|
||||||
decision.summary.codeVersion = 'a'.repeat(40);
|
decision.summary.codeVersion = 'a'.repeat(40);
|
||||||
decision.summary.executionCoverage = 'ATTEMPTS';
|
decision.summary.executionCoverage = 'ATTEMPTS';
|
||||||
decision.steps.push({ ...decision.steps[0]!, ...buildAuditExecutionFixture(), sequence: 302 });
|
decision.steps.push({ ...decision.steps[0]!, ...buildAuditExecutionFixture(), sequence: 302 });
|
||||||
@@ -85,7 +118,7 @@ integration('decision persistence and bounded retention', () => {
|
|||||||
orderBy: { ordinal: 'asc' },
|
orderBy: { ordinal: 'asc' },
|
||||||
});
|
});
|
||||||
expect(chunks).toHaveLength(3);
|
expect(chunks).toHaveLength(3);
|
||||||
expect(chunks.flatMap((chunk) => chunk.steps)).toEqual(decision.steps);
|
expect(chunks.flatMap((chunk) => decodeAuditDecisionSteps(chunk.steps))).toEqual(decision.steps);
|
||||||
await expect(
|
await expect(
|
||||||
db.$transaction((tx) =>
|
db.$transaction((tx) =>
|
||||||
persistAuditDecisions(tx, [{ ...decision, summary: { ...decision.summary, completed: true } }])
|
persistAuditDecisions(tx, [{ ...decision, summary: { ...decision.summary, completed: true } }])
|
||||||
@@ -109,10 +142,34 @@ integration('decision persistence and bounded retention', () => {
|
|||||||
expect(await db.playAuditDecisionChunk.count({ where: { decisionId: 'decision-one' } })).toBe(204);
|
expect(await db.playAuditDecisionChunk.count({ where: { decisionId: 'decision-one' } })).toBe(204);
|
||||||
expect(await db.playAuditDecision.count({ where: { id: 'decision-one' } })).toBe(1);
|
expect(await db.playAuditDecision.count({ where: { id: 'decision-one' } })).toBe(1);
|
||||||
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 200 });
|
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 200 });
|
||||||
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 4 });
|
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 5 });
|
||||||
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 1 });
|
|
||||||
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'complete', deleted: 0 });
|
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'complete', deleted: 0 });
|
||||||
expect(await db.playAuditDecision.count()).toBe(1);
|
expect(await db.playAuditDecision.count()).toBe(1);
|
||||||
expect(await db.playAuditDecisionChunk.count()).toBe(3);
|
expect(await db.playAuditDecisionChunk.count()).toBe(3);
|
||||||
});
|
});
|
||||||
|
it('removes many small decisions in one bounded batch and rolls chunks back on header failure', async () => {
|
||||||
|
const decisions = Array.from({ length: 100 }, (_, index) => {
|
||||||
|
const row = draft(`batch-old-${index}`, 'batch-old');
|
||||||
|
return { ...row, steps: [row.steps[0]!, row.steps.at(-1)!] };
|
||||||
|
});
|
||||||
|
await db.$transaction((tx) => persistAuditDecisions(tx, decisions));
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
`CREATE OR REPLACE FUNCTION decision_header_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'header fixture rollback'; END $$`
|
||||||
|
);
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
`CREATE TRIGGER decision_header_failure BEFORE DELETE ON play_audit_decision FOR EACH ROW EXECUTE FUNCTION decision_header_failure()`
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
await expect(prunePreviousAuditBatch(db, 'decision-current')).rejects.toThrow();
|
||||||
|
expect(
|
||||||
|
await db.playAuditDecisionChunk.count({ where: { decisionId: { in: decisions.map(({ id }) => id) } } })
|
||||||
|
).toBe(100);
|
||||||
|
} finally {
|
||||||
|
await db.$executeRawUnsafe('DROP TRIGGER decision_header_failure ON play_audit_decision');
|
||||||
|
await db.$executeRawUnsafe('DROP FUNCTION decision_header_failure()');
|
||||||
|
}
|
||||||
|
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'progress', deleted: 200 });
|
||||||
|
expect(await db.playAuditDecision.count()).toBe(1);
|
||||||
|
expect(await prunePreviousAuditBatch(db, 'decision-current')).toEqual({ status: 'complete', deleted: 0 });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -20,7 +20,7 @@ describe('audit retention scheduling', () => {
|
|||||||
expect(prune).toHaveBeenCalledTimes(1);
|
expect(prune).toHaveBeenCalledTimes(1);
|
||||||
await vi.advanceTimersByTimeAsync(30_001);
|
await vi.advanceTimersByTimeAsync(30_001);
|
||||||
expect(prune).toHaveBeenCalledTimes(3);
|
expect(prune).toHaveBeenCalledTimes(3);
|
||||||
await vi.advanceTimersByTimeAsync(1000);
|
await vi.advanceTimersByTimeAsync(100);
|
||||||
expect(prune).toHaveBeenCalledTimes(4);
|
expect(prune).toHaveBeenCalledTimes(4);
|
||||||
await vi.advanceTimersByTimeAsync(600_000);
|
await vi.advanceTimersByTimeAsync(600_000);
|
||||||
expect(prune).toHaveBeenCalledTimes(4);
|
expect(prune).toHaveBeenCalledTimes(4);
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,9 @@ import { createGamePostgresConnector } from '@sammo-ts/infra';
|
|||||||
import {
|
import {
|
||||||
InMemoryReservedTurnStore,
|
InMemoryReservedTurnStore,
|
||||||
ReservedTurnLeaseConflictError,
|
ReservedTurnLeaseConflictError,
|
||||||
|
createReservedTurnStore,
|
||||||
} from '../src/turn/reservedTurnStore.js';
|
} from '../src/turn/reservedTurnStore.js';
|
||||||
|
import { createReservedTurnLeaseRetry } from '../src/turn/reservedTurnLeaseRetry.js';
|
||||||
|
|
||||||
const databaseUrl = process.env.RESERVED_TURN_DATABASE_URL;
|
const databaseUrl = process.env.RESERVED_TURN_DATABASE_URL;
|
||||||
const describeIntegration = databaseUrl ? describe : describe.skip;
|
const describeIntegration = databaseUrl ? describe : describe.skip;
|
||||||
@@ -132,4 +134,98 @@ describeIntegration('reserved turn daemon/API lease integration', () => {
|
|||||||
});
|
});
|
||||||
expect(after.map((turn) => turn.actionCode)).toEqual(before.map((turn) => turn.actionCode));
|
expect(after.map((turn) => turn.actionCode)).toEqual(before.map((turn) => turn.actionCode));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('cleans persisted ownership after rollback loses the journal, preserves other writers, and reloads once', async () => {
|
||||||
|
if (!connector || !databaseUrl) throw new Error('integration connector is unavailable');
|
||||||
|
await connector.prisma.generalTurnRevision.update({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
data: { leaseOwner: null, leaseExpiresAt: null },
|
||||||
|
});
|
||||||
|
const before = await connector.prisma.generalTurn.findMany({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
orderBy: { turnIdx: 'asc' },
|
||||||
|
});
|
||||||
|
const revision = await connector.prisma.generalTurnRevision.findUniqueOrThrow({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
});
|
||||||
|
const old = await createReservedTurnStore({ databaseUrl, leaseOwner: 'interrupted-daemon' });
|
||||||
|
const savepoint = old.store.captureTransactionState();
|
||||||
|
await old.store.prepareTurnsForExecution(GENERAL_ID);
|
||||||
|
old.store.shiftGeneralTurns(GENERAL_ID, -1);
|
||||||
|
old.store.restoreState(savepoint);
|
||||||
|
expect(old.store.getQueueCounts().leasedGeneralQueues).toBe(0);
|
||||||
|
const next = await createReservedTurnStore({ databaseUrl, leaseOwner: 'new-daemon' });
|
||||||
|
try {
|
||||||
|
await expect(next.store.prepareTurnsForExecution(GENERAL_ID)).rejects.toBeInstanceOf(
|
||||||
|
ReservedTurnLeaseConflictError
|
||||||
|
);
|
||||||
|
await old.close();
|
||||||
|
const released = await connector.prisma.generalTurnRevision.findUniqueOrThrow({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
});
|
||||||
|
expect(released).toMatchObject({ leaseOwner: null, leaseExpiresAt: null, revision: revision.revision });
|
||||||
|
await next.store.prepareTurnsForExecution(GENERAL_ID);
|
||||||
|
// A delayed close of an old owner cannot clear the new owner's lease.
|
||||||
|
const delayedCleaner = new InMemoryReservedTurnStore(connector.prisma, {
|
||||||
|
maxGeneralTurns: 2,
|
||||||
|
maxNationTurns: 1,
|
||||||
|
leaseOwner: 'interrupted-daemon',
|
||||||
|
});
|
||||||
|
await delayedCleaner.releaseOwnedLeases();
|
||||||
|
expect(
|
||||||
|
await connector.prisma.generalTurnRevision.findUniqueOrThrow({ where: { generalId: GENERAL_ID } })
|
||||||
|
).toMatchObject({ leaseOwner: 'new-daemon', revision: revision.revision });
|
||||||
|
await next.store.releaseOwnedLeases();
|
||||||
|
const actual = await connector.prisma.generalTurn.findMany({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
orderBy: { turnIdx: 'asc' },
|
||||||
|
});
|
||||||
|
expect(actual.map((row) => row.actionCode)).toEqual(before.map((row) => row.actionCode));
|
||||||
|
} finally {
|
||||||
|
await next.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waits out an orphaned lease without deleting it and reloads an intervening API edit', async () => {
|
||||||
|
if (!connector) throw new Error('integration connector is unavailable');
|
||||||
|
await connector.prisma.generalTurnRevision.update({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
data: { leaseOwner: 'killed-daemon', leaseExpiresAt: new Date(Date.now() + 300_000) },
|
||||||
|
});
|
||||||
|
const store = new InMemoryReservedTurnStore(connector.prisma, {
|
||||||
|
maxGeneralTurns: 2,
|
||||||
|
maxNationTurns: 1,
|
||||||
|
leaseOwner: 'recovery-daemon',
|
||||||
|
});
|
||||||
|
await store.loadAll();
|
||||||
|
const retry = createReservedTurnLeaseRetry({
|
||||||
|
sleep: async () => {
|
||||||
|
// Simulate the recorded expiry, then an authorized API edit before the next claim.
|
||||||
|
expect(
|
||||||
|
await connector.prisma.generalTurnRevision.findUniqueOrThrow({ where: { generalId: GENERAL_ID } })
|
||||||
|
).toMatchObject({ leaseOwner: 'killed-daemon' });
|
||||||
|
await connector.prisma.generalTurnRevision.update({
|
||||||
|
where: { generalId: GENERAL_ID },
|
||||||
|
data: { leaseExpiresAt: new Date(0) },
|
||||||
|
});
|
||||||
|
await connector.prisma.generalTurn.updateMany({
|
||||||
|
where: { generalId: GENERAL_ID, turnIdx: 0 },
|
||||||
|
data: { actionCode: 'che_수련' },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
let failure: unknown;
|
||||||
|
try {
|
||||||
|
await store.prepareTurnsForExecution(GENERAL_ID);
|
||||||
|
} catch (error) {
|
||||||
|
failure = error;
|
||||||
|
}
|
||||||
|
expect(await retry.wait(failure)).toBe(true);
|
||||||
|
await store.prepareTurnsForExecution(GENERAL_ID);
|
||||||
|
expect(store.getGeneralTurns(GENERAL_ID)[0]?.action).toBe('che_수련');
|
||||||
|
} finally {
|
||||||
|
await store.releaseOwnedLeases();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -169,6 +169,18 @@ const buildHarness = (initialRevision: RevisionRow | null = null) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
describe('reserved turn daemon lease', () => {
|
describe('reserved turn daemon lease', () => {
|
||||||
|
it('cleans both persisted lease kinds even after their journal is rolled back', async () => {
|
||||||
|
const harness = buildHarness();
|
||||||
|
const snapshot = harness.store.captureTransactionState();
|
||||||
|
await harness.store.prepareTurnsForExecution(7, { nationId: 3, officerLevel: 12 });
|
||||||
|
harness.store.restoreState(snapshot);
|
||||||
|
expect(harness.store.getQueueCounts()).toMatchObject({ leasedGeneralQueues: 0, leasedNationQueues: 0 });
|
||||||
|
await harness.store.releaseOwnedLeases();
|
||||||
|
expect(harness.getRevision()).toMatchObject({ leaseOwner: null, leaseExpiresAt: null, revision: 0 });
|
||||||
|
expect(harness.getNationRevision()).toMatchObject({ leaseOwner: null, leaseExpiresAt: null, revision: 0 });
|
||||||
|
expect(harness.generalDeleteMany).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('prunes deleted general and nation queues together with their journal state', () => {
|
it('prunes deleted general and nation queues together with their journal state', () => {
|
||||||
const harness = buildHarness();
|
const harness = buildHarness();
|
||||||
harness.store.ensureGeneralTurns(7);
|
harness.store.ensureGeneralTurns(7);
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { createReservedTurnLeaseRetry } from '../src/turn/reservedTurnLeaseRetry.js';
|
||||||
|
import { ReservedTurnLeaseBusyError, ReservedTurnLeaseConflictError } from '../src/turn/reservedTurnStore.js';
|
||||||
|
|
||||||
|
describe('reserved turn acquisition retry', () => {
|
||||||
|
it('bounds the entire contention episode across different queues and resets after progress', async () => {
|
||||||
|
let now = 0;
|
||||||
|
const onWait = vi.fn();
|
||||||
|
const retry = createReservedTurnLeaseRetry({
|
||||||
|
now: () => now,
|
||||||
|
sleep: async (ms) => {
|
||||||
|
now += ms;
|
||||||
|
},
|
||||||
|
maxWaitMs: 2_500,
|
||||||
|
onWait,
|
||||||
|
});
|
||||||
|
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:1'))).toBe(true);
|
||||||
|
expect(await retry.wait(new ReservedTurnLeaseBusyError('nation:2:12'))).toBe(true);
|
||||||
|
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:3'))).toBe(true);
|
||||||
|
expect(now).toBe(2_500);
|
||||||
|
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:1'))).toBe(false);
|
||||||
|
expect(onWait).toHaveBeenCalledTimes(1);
|
||||||
|
retry.reset();
|
||||||
|
expect(await retry.wait(new ReservedTurnLeaseBusyError('general:1'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never retries flush ownership loss, calculation errors, or failed savepoint restoration', async () => {
|
||||||
|
const sleep = vi.fn();
|
||||||
|
const retry = createReservedTurnLeaseRetry({ sleep });
|
||||||
|
for (const error of [
|
||||||
|
new ReservedTurnLeaseConflictError('general:1'),
|
||||||
|
new Error('calculation failed'),
|
||||||
|
new AggregateError([new ReservedTurnLeaseBusyError('general:1')], 'restore failed'),
|
||||||
|
])
|
||||||
|
expect(await retry.wait(error)).toBe(false);
|
||||||
|
expect(sleep).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,12 +3,36 @@ import type { GameClockPhase } from '@sammo-ts/common';
|
|||||||
import { createRuntimePauseGate } from '../src/turn/runtimePauseGate.js';
|
import { createRuntimePauseGate } from '../src/turn/runtimePauseGate.js';
|
||||||
|
|
||||||
describe('runtime pause clock boundary', () => {
|
describe('runtime pause clock boundary', () => {
|
||||||
|
it('awaits a host authority check before reading profile state or changing the clock', async () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const gate = createRuntimePauseGate({
|
||||||
|
assertLease: async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
calls.push('host');
|
||||||
|
throw new Error('host changed');
|
||||||
|
},
|
||||||
|
shouldPause: async () => {
|
||||||
|
calls.push('profile');
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
isExplicitlyPaused: () => false,
|
||||||
|
getPhase: () => 'RUNNING',
|
||||||
|
prepareRecovery: async () => {
|
||||||
|
calls.push('recovery');
|
||||||
|
},
|
||||||
|
synchronize: async () => {},
|
||||||
|
});
|
||||||
|
await expect(gate()).rejects.toThrow('host changed');
|
||||||
|
expect(calls).toEqual(['host']);
|
||||||
|
});
|
||||||
it('freezes a live error pause before commands, resumes without restart, and does not freeze twice', async () => {
|
it('freezes a live error pause before commands, resumes without restart, and does not freeze twice', async () => {
|
||||||
let phase: GameClockPhase = 'RUNNING';
|
let phase: GameClockPhase = 'RUNNING';
|
||||||
let paused = true;
|
let paused = true;
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
const gate = createRuntimePauseGate({
|
const gate = createRuntimePauseGate({
|
||||||
assertLease: () => calls.push('lease'),
|
assertLease: () => {
|
||||||
|
calls.push('lease');
|
||||||
|
},
|
||||||
shouldPause: async () => paused,
|
shouldPause: async () => paused,
|
||||||
isExplicitlyPaused: () => paused,
|
isExplicitlyPaused: () => paused,
|
||||||
getPhase: () => phase,
|
getPhase: () => phase,
|
||||||
|
|||||||
@@ -207,6 +207,39 @@ integration('database turn daemon lease and fencing', () => {
|
|||||||
expect(row.ownerId).toBe(firstToken ? 'owner-a' : 'owner-b');
|
expect(row.ownerId).toBe(firstToken ? 'owner-a' : 'owner-b');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('fences a host boot change inside a transaction before mutation, without expiring the DB lease', async () => {
|
||||||
|
const profile = `${profilePrefix}host-boot`;
|
||||||
|
let changed = false;
|
||||||
|
const lease = await DatabaseTurnDaemonLease.connect(databaseUrl!, {
|
||||||
|
profile,
|
||||||
|
ownerId: 'saved-vm-owner',
|
||||||
|
heartbeat: false,
|
||||||
|
leaseDurationMs: 60_000,
|
||||||
|
hostBootMonitor: { hasChanged: async () => changed },
|
||||||
|
});
|
||||||
|
leases.push(lease);
|
||||||
|
await lease.acquire();
|
||||||
|
await lease.markClockReady();
|
||||||
|
changed = true;
|
||||||
|
let committed = false;
|
||||||
|
await expect(
|
||||||
|
db.$transaction(async (transaction) => {
|
||||||
|
await lease.assertActive(transaction);
|
||||||
|
committed = true;
|
||||||
|
})
|
||||||
|
).rejects.toBeInstanceOf(TurnDaemonLeaseLostError);
|
||||||
|
expect(committed).toBe(false);
|
||||||
|
expect(lease.isLost()).toBe(true);
|
||||||
|
expect(await lease.renew()).toBe(false);
|
||||||
|
// The monitor does not force-clear ownership or bypass the successor's fencing.
|
||||||
|
expect((await db.turnDaemonLease.findUniqueOrThrow({ where: { profile } })).ownerId).toBe('saved-vm-owner');
|
||||||
|
const next = await createLease(profile, 'fresh-vm-owner');
|
||||||
|
expect(await next.acquire()).toBeNull();
|
||||||
|
await lease.release();
|
||||||
|
expect((await db.turnDaemonLease.findUniqueOrThrow({ where: { profile } })).clockReady).toBe(false);
|
||||||
|
expect((await next.acquire())?.fencingEpoch).toBe(2n);
|
||||||
|
});
|
||||||
|
|
||||||
it('persists and evaluates lease wall time as UTC under a non-UTC database session', async () => {
|
it('persists and evaluates lease wall time as UTC under a non-UTC database session', async () => {
|
||||||
const profile = `${profilePrefix}utc-wall`;
|
const profile = `${profilePrefix}utc-wall`;
|
||||||
const zonedUrl = new URL(databaseUrl!);
|
const zonedUrl = new URL(databaseUrl!);
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { ManualClock } from '@sammo-ts/common';
|
import { ManualClock } from '@sammo-ts/common';
|
||||||
import { TurnDaemonLeaseLostError } from '../src/lifecycle/databaseTurnDaemonLease.js';
|
import { TurnDaemonLeaseLostError } from '../src/lifecycle/databaseTurnDaemonLease.js';
|
||||||
|
import { ReservedTurnLeaseBusyError } from '../src/turn/reservedTurnStore.js';
|
||||||
|
import { createReservedTurnLeaseRetry } from '../src/turn/reservedTurnLeaseRetry.js';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
InMemoryControlQueue,
|
InMemoryControlQueue,
|
||||||
@@ -15,6 +17,68 @@ import {
|
|||||||
const addMinutes = (time: Date, minutes: number): Date => new Date(time.getTime() + minutes * 60_000);
|
const addMinutes = (time: Date, minutes: number): Date => new Date(time.getTime() + minutes * 60_000);
|
||||||
|
|
||||||
describe('TurnDaemonLifecycle', () => {
|
describe('TurnDaemonLifecycle', () => {
|
||||||
|
it('rolls back a busy queue, checks the operator gate, and retries an explicit run exactly once', async () => {
|
||||||
|
const now = new Date('2026-11-12T00:00:00Z');
|
||||||
|
const queue = new InMemoryControlQueue();
|
||||||
|
queue.enqueue({ type: 'run', reason: 'manual', targetTime: now.toISOString() });
|
||||||
|
let resource = 10;
|
||||||
|
let runs = 0;
|
||||||
|
const stateManager = new EngineStateManager();
|
||||||
|
stateManager.register('resource', {
|
||||||
|
capture: () => resource,
|
||||||
|
restore: (value) => {
|
||||||
|
resource = value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const onRunError = vi.fn();
|
||||||
|
const flushChanges = vi.fn();
|
||||||
|
const gate = vi.fn(async () => false);
|
||||||
|
const retry = createReservedTurnLeaseRetry({
|
||||||
|
sleep: async () => {
|
||||||
|
expect(resource).toBe(10);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const lifecycle = new TurnDaemonLifecycle(
|
||||||
|
{
|
||||||
|
clock: new ManualClock(now.getTime()),
|
||||||
|
controlQueue: queue,
|
||||||
|
stateManager,
|
||||||
|
runErrorRetry: retry,
|
||||||
|
getNextTickTime: (value) => addMinutes(value, 5),
|
||||||
|
pauseGate: gate,
|
||||||
|
stateStore: {
|
||||||
|
loadLastTurnTime: async () => now,
|
||||||
|
loadNextGeneralTurnTime: async () => null,
|
||||||
|
saveLastTurnTime: async () => {},
|
||||||
|
loadCheckpoint: async () => undefined,
|
||||||
|
saveCheckpoint: async () => {},
|
||||||
|
},
|
||||||
|
processor: {
|
||||||
|
run: async () => {
|
||||||
|
resource -= 2;
|
||||||
|
if (++runs === 1) throw new ReservedTurnLeaseBusyError('general:7');
|
||||||
|
queue.enqueue({ type: 'shutdown' });
|
||||||
|
return {
|
||||||
|
lastTurnTime: now.toISOString(),
|
||||||
|
processedGenerals: 1,
|
||||||
|
processedTurns: 0,
|
||||||
|
durationMs: 0,
|
||||||
|
partial: false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
hooks: { onRunError, flushChanges },
|
||||||
|
},
|
||||||
|
{ profile: 'che', defaultBudget: { budgetMs: 100, maxGenerals: 1, catchUpCap: 1 } }
|
||||||
|
);
|
||||||
|
await lifecycle.start();
|
||||||
|
expect(runs).toBe(2);
|
||||||
|
expect(resource).toBe(8);
|
||||||
|
expect(gate.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(flushChanges).toHaveBeenCalledOnce();
|
||||||
|
expect(onRunError).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it.each([false, true])('reports a fatal lease gate and exits even if reporting fails (%s)', async (reportFails) => {
|
it.each([false, true])('reports a fatal lease gate and exits even if reporting fails (%s)', async (reportFails) => {
|
||||||
const now = new Date('2026-09-09T17:30:00Z');
|
const now = new Date('2026-09-09T17:30:00Z');
|
||||||
const error = new TurnDaemonLeaseLostError('che:default');
|
const error = new TurnDaemonLeaseLostError('che:default');
|
||||||
|
|||||||
@@ -135,3 +135,106 @@ integration('turn failure personal-record persistence', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
integration('turn persistence connection acquisition', () => {
|
||||||
|
let connector: ReturnType<typeof createGamePostgresConnector>;
|
||||||
|
let hooks: DatabaseTurnHooks;
|
||||||
|
const fixtureWorldId = worldId + 10;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||||
|
await connector.connect();
|
||||||
|
await connector.prisma.worldState.create({
|
||||||
|
data: {
|
||||||
|
id: fixtureWorldId,
|
||||||
|
scenarioCode: 'transaction-acquisition',
|
||||||
|
currentYear: state.currentYear,
|
||||||
|
currentMonth: state.currentMonth,
|
||||||
|
tickSeconds: state.tickSeconds,
|
||||||
|
clockBaseTime: turnTime,
|
||||||
|
clockWallAnchor: turnTime,
|
||||||
|
clockMode: 'manual',
|
||||||
|
clockPhase: 'MANUAL',
|
||||||
|
clockTick: 0n,
|
||||||
|
lastTurnTick: 0n,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
hooks = await createDatabaseTurnHooks(
|
||||||
|
databaseUrl!,
|
||||||
|
new InMemoryTurnWorld({ ...state, id: fixtureWorldId }, snapshot, { schedule }),
|
||||||
|
{ transactionTimeoutMs: 1_000 }
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await hooks?.close();
|
||||||
|
await connector?.prisma.worldState.deleteMany({ where: { id: fixtureWorldId } });
|
||||||
|
await connector?.disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
const occupyPool = async () => {
|
||||||
|
let release!: () => void;
|
||||||
|
const held = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
const started: Promise<void>[] = [];
|
||||||
|
const blockers = Array.from({ length: connector.getPoolStats().max }, () => {
|
||||||
|
let markStarted!: () => void;
|
||||||
|
started.push(new Promise<void>((resolve) => (markStarted = resolve)));
|
||||||
|
return connector.prisma.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT 1`;
|
||||||
|
markStarted();
|
||||||
|
await held;
|
||||||
|
},
|
||||||
|
{ maxWait: 10_000, timeout: 20_000 }
|
||||||
|
);
|
||||||
|
});
|
||||||
|
// Attach handlers immediately so a setup failure cannot leak transactions.
|
||||||
|
const settled = Promise.allSettled(blockers);
|
||||||
|
try {
|
||||||
|
await Promise.all(started);
|
||||||
|
} catch (error) {
|
||||||
|
release();
|
||||||
|
await settled;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return { release, settled };
|
||||||
|
};
|
||||||
|
|
||||||
|
it('waits beyond Prisma default without spending the callback execution budget', async () => {
|
||||||
|
const held = await occupyPool();
|
||||||
|
const sync = hooks.synchronizeClockAuthority();
|
||||||
|
// Observe the result immediately; the old 2-second default rejects here.
|
||||||
|
const outcome = sync.then(
|
||||||
|
(value) => ({ ok: true, value }),
|
||||||
|
(error: unknown) => ({ ok: false, error })
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const deadline = Date.now() + 1_000;
|
||||||
|
while (!connector.getPoolStats().waiting && Date.now() < deadline) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||||
|
}
|
||||||
|
expect(connector.getPoolStats().waiting).toBeGreaterThan(0);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2_500));
|
||||||
|
held.release();
|
||||||
|
expect(await outcome).toMatchObject({ ok: true });
|
||||||
|
} finally {
|
||||||
|
held.release();
|
||||||
|
await held.settled;
|
||||||
|
await outcome;
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
|
||||||
|
it('still rejects sustained connection exhaustion at the finite acquisition limit', async () => {
|
||||||
|
const held = await occupyPool();
|
||||||
|
try {
|
||||||
|
await expect(hooks.synchronizeClockAuthority()).rejects.toMatchObject({ code: 'P2028' });
|
||||||
|
} finally {
|
||||||
|
held.release();
|
||||||
|
await held.settled;
|
||||||
|
}
|
||||||
|
// Timed-out acquisition must not prevent the next normal operation.
|
||||||
|
await expect(hooks.synchronizeClockAuthority()).resolves.toBeTypeOf('boolean');
|
||||||
|
}, 15_000);
|
||||||
|
});
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { normalizeArchivedGeneral, type ArchivedJsonValue } from '@sammo-ts/common';
|
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 { LogCategory, LogScope, type City, type Nation } from '@sammo-ts/logic';
|
||||||
|
|
||||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||||
import { persistUnificationFinalization, resolveStoredInheritancePoint } from '../src/turn/unificationPersistence.js';
|
import { persistUnificationFinalization, resolveStoredInheritancePoint } from '../src/turn/unificationPersistence.js';
|
||||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.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 buildWorld = (): InMemoryTurnWorld => {
|
||||||
const turnTime = new Date('0190-07-01T00:00:00.000Z');
|
const turnTime = new Date('0190-07-01T00:00:00.000Z');
|
||||||
const general: TurnGeneral = {
|
const general: TurnGeneral = {
|
||||||
@@ -206,6 +214,7 @@ describe('persistUnificationFinalization', () => {
|
|||||||
create: vi.fn().mockResolvedValue({}),
|
create: vi.fn().mockResolvedValue({}),
|
||||||
},
|
},
|
||||||
inheritancePoint: {
|
inheritancePoint: {
|
||||||
|
update: missingRecordUpdate,
|
||||||
findMany: vi.fn().mockResolvedValue([
|
findMany: vi.fn().mockResolvedValue([
|
||||||
{ userId: 'user-1', key: 'previous', value: 100 },
|
{ userId: 'user-1', key: 'previous', value: 100 },
|
||||||
{ userId: 'user-1', key: 'unifier', value: 7 },
|
{ userId: 'user-1', key: 'unifier', value: 7 },
|
||||||
@@ -216,6 +225,7 @@ describe('persistUnificationFinalization', () => {
|
|||||||
inheritanceResult: { create: inheritanceResultCreate },
|
inheritanceResult: { create: inheritanceResultCreate },
|
||||||
inheritanceLog: { create: inheritanceLogCreate },
|
inheritanceLog: { create: inheritanceLogCreate },
|
||||||
rankData: {
|
rankData: {
|
||||||
|
update: missingRecordUpdate,
|
||||||
findMany: vi.fn().mockResolvedValue([
|
findMany: vi.fn().mockResolvedValue([
|
||||||
{ generalId: 1, type: 'warnum', value: 15 },
|
{ generalId: 1, type: 'warnum', value: 15 },
|
||||||
{ generalId: 1, type: 'killnum', value: 9 },
|
{ generalId: 1, type: 'killnum', value: 9 },
|
||||||
@@ -251,10 +261,11 @@ describe('persistUnificationFinalization', () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
oldNation: {
|
oldNation: {
|
||||||
|
update: missingRecordUpdate,
|
||||||
upsert: oldNationUpsert,
|
upsert: oldNationUpsert,
|
||||||
findMany: vi.fn().mockResolvedValue([]),
|
findMany: vi.fn().mockResolvedValue([]),
|
||||||
},
|
},
|
||||||
oldGeneral: { upsert: oldGeneralUpsert },
|
oldGeneral: { update: missingRecordUpdate, upsert: oldGeneralUpsert },
|
||||||
emperor: { create: emperorCreate },
|
emperor: { create: emperorCreate },
|
||||||
});
|
});
|
||||||
await expect(persistUnificationFinalization(transaction, input, buildWorld())).resolves.toEqual({
|
await expect(persistUnificationFinalization(transaction, input, buildWorld())).resolves.toEqual({
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
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 { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||||
|
|
||||||
import { persistYearbookSnapshot } from '../src/turn/yearbookPersistence.js';
|
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', () => {
|
describe('persistYearbookSnapshot', () => {
|
||||||
it('archives canonical summary logs and compatible action logs together in descending ID order', async () => {
|
it('archives canonical summary logs and compatible action logs together in descending ID order', async () => {
|
||||||
const findMany = vi
|
const findMany = vi
|
||||||
@@ -14,7 +22,7 @@ describe('persistYearbookSnapshot', () => {
|
|||||||
const upsert = vi.fn().mockResolvedValue(undefined);
|
const upsert = vi.fn().mockResolvedValue(undefined);
|
||||||
const transaction = {
|
const transaction = {
|
||||||
logEntry: { findMany },
|
logEntry: { findMany },
|
||||||
yearbookHistory: { upsert },
|
yearbookHistory: { update: missingRecordUpdate, upsert },
|
||||||
} as unknown as GamePrisma.TransactionClient;
|
} as unknown as GamePrisma.TransactionClient;
|
||||||
|
|
||||||
await persistYearbookSnapshot(transaction, {
|
await persistYearbookSnapshot(transaction, {
|
||||||
|
|||||||
@@ -710,6 +710,106 @@ test('trait and injury explanations appear on pointer hover and keyboard focus',
|
|||||||
await page.screenshot({ path: testInfo.outputPath('directory-trait-injury-tooltips.png'), fullPage: true });
|
await page.screenshot({ path: testInfo.outputPath('directory-trait-injury-tooltips.png'), fullPage: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
for (const width of [1200, 500]) {
|
||||||
|
test(`catalog description line breaks stay safe on hover and focus at ${width}px`, async ({ page }, testInfo) => {
|
||||||
|
await page.setViewportSize({ width, height: 900 });
|
||||||
|
const warInfo =
|
||||||
|
'[계략] 화계·탈취·파괴·선동 : 성공률 +10%p<br>[전투] 계략 시도 확률 +20%p, 계략 성공 확률 +20%p';
|
||||||
|
const literalMarkup = '<img src=x onerror="alert(1)"><b>설명</b>';
|
||||||
|
const directoryRows = generals.map((general) =>
|
||||||
|
general.id === 10
|
||||||
|
? {
|
||||||
|
...general,
|
||||||
|
specialDomestic: {
|
||||||
|
...general.specialDomestic,
|
||||||
|
info: `상업 특기<br/>수익 증가<BR />매매 효율\r\n${literalMarkup}`,
|
||||||
|
},
|
||||||
|
specialWar: { key: 'che_신산', name: '신산', info: warInfo },
|
||||||
|
}
|
||||||
|
: general
|
||||||
|
);
|
||||||
|
await install(page, 'general', [], [], directoryRows);
|
||||||
|
await page.goto('general-list');
|
||||||
|
await page.reload();
|
||||||
|
const prefix = width <= 600 ? 'card-' : '';
|
||||||
|
const container = page
|
||||||
|
.locator(width <= 600 ? '[data-general-card-id="10"]' : 'tr[data-general-id="10"]')
|
||||||
|
.first();
|
||||||
|
await expect(container).toBeVisible();
|
||||||
|
await expect(page.getByRole('button', { name: '갱 신' })).not.toHaveAttribute('aria-busy');
|
||||||
|
await page.evaluate(async () => {
|
||||||
|
await document.fonts.ready;
|
||||||
|
await Promise.all(Array.from(document.images, (image) => image.decode().catch(() => undefined)));
|
||||||
|
});
|
||||||
|
const before = await container.boundingBox();
|
||||||
|
const evidence: Record<string, unknown> = { width, url: page.url(), before };
|
||||||
|
for (const [kind, expected] of [
|
||||||
|
['special-domestic', ['상업 특기', '수익 증가', '매매 효율', literalMarkup]],
|
||||||
|
['special-war', warInfo.split('<br>')],
|
||||||
|
] as const) {
|
||||||
|
const trigger = page.locator(`[data-directory-tooltip="${prefix}${kind}-10"]`);
|
||||||
|
const tooltip = trigger.getByRole('tooltip');
|
||||||
|
await page.mouse.move(0, 0);
|
||||||
|
await trigger.hover();
|
||||||
|
await expect(tooltip).toBeVisible();
|
||||||
|
await trigger.focus();
|
||||||
|
await expect(tooltip).toBeVisible();
|
||||||
|
await expect(trigger).toHaveCSS('text-decoration-line', 'none');
|
||||||
|
await expect(trigger).toHaveCSS('outline-style', 'solid');
|
||||||
|
const description = tooltip.locator('.directory-tooltip__description');
|
||||||
|
await expect(description.locator('br')).toHaveCount(expected.length - 1);
|
||||||
|
await expect(description.locator('img, b, script')).toHaveCount(0);
|
||||||
|
expect(await description.innerText()).not.toMatch(/<br\s*\/?\s*>/iu);
|
||||||
|
const metrics = await description.evaluate((element) => {
|
||||||
|
const lines = Array.from(element.childNodes).filter(
|
||||||
|
(node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim()
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
lines: lines.map((node) => {
|
||||||
|
const range = document.createRange();
|
||||||
|
range.selectNodeContents(node);
|
||||||
|
return { text: node.textContent?.trim(), top: range.getBoundingClientRect().top };
|
||||||
|
}),
|
||||||
|
html: element.outerHTML,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
expect(metrics.lines.map((line) => line.text)).toEqual(expected);
|
||||||
|
for (let index = 1; index < metrics.lines.length; index += 1) {
|
||||||
|
expect(metrics.lines[index]!.top).toBeGreaterThan(metrics.lines[index - 1]!.top);
|
||||||
|
}
|
||||||
|
const geometry = await tooltip.evaluate((element) => {
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
const style = getComputedStyle(element);
|
||||||
|
return {
|
||||||
|
left: rect.left,
|
||||||
|
right: rect.right,
|
||||||
|
top: rect.top,
|
||||||
|
bottom: rect.bottom,
|
||||||
|
font: style.font,
|
||||||
|
background: style.backgroundColor,
|
||||||
|
position: style.position,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
expect(geometry.left).toBeGreaterThanOrEqual(8);
|
||||||
|
expect(geometry.right).toBeLessThanOrEqual(width - 8);
|
||||||
|
expect(geometry.top).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(geometry.bottom).toBeLessThanOrEqual(900);
|
||||||
|
expect(await container.boundingBox()).toEqual(before);
|
||||||
|
evidence[kind] = { ...metrics, geometry };
|
||||||
|
await page.screenshot({ path: testInfo.outputPath(`catalog-${kind}-${width}.png`), fullPage: true });
|
||||||
|
await trigger.blur();
|
||||||
|
}
|
||||||
|
const empty = page.locator(`[data-directory-tooltip="${prefix}special-war-20"]`);
|
||||||
|
await expect(empty).not.toHaveAttribute('tabindex');
|
||||||
|
await expect(empty.getByRole('tooltip')).toHaveCount(0);
|
||||||
|
await writeFile(testInfo.outputPath('catalog-description.json'), JSON.stringify(evidence, null, 2));
|
||||||
|
await writeFile(
|
||||||
|
testInfo.outputPath('catalog-description.html'),
|
||||||
|
await page.locator('main').evaluate((element) => element.outerHTML)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
test('npc directory reuses the dark sort controls and sorts from a table header', async ({ page }, testInfo) => {
|
test('npc directory reuses the dark sort controls and sorts from a table header', async ({ page }, testInfo) => {
|
||||||
await install(page);
|
await install(page);
|
||||||
await page.goto('npc-list');
|
await page.goto('npc-list');
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ const history = [
|
|||||||
id: 3,
|
id: 3,
|
||||||
text: '이번 수입은 금 <C>158</>입니다.',
|
text: '이번 수입은 금 <C>158</>입니다.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
text: '<D><b>풍년F&B</b></> <img src=x onerror=globalThis.__legacyLogXss=4>',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const publicResponse = (operation: string): unknown => {
|
const publicResponse = (operation: string): unknown => {
|
||||||
@@ -36,7 +40,12 @@ const publicResponse = (operation: string): unknown => {
|
|||||||
return response({ year: 200, month: 1, cityList: [], nationList: [], history });
|
return response({ year: 200, month: 1, cityList: [], nationList: [], history });
|
||||||
}
|
}
|
||||||
if (operation === 'public.getWorldTrend') return response({ year: 200, month: 1, turnTerm: 10 });
|
if (operation === 'public.getWorldTrend') return response({ year: 200, month: 1, turnTerm: 10 });
|
||||||
if (operation === 'public.getNationList' || operation === 'public.getGeneralList') return response([]);
|
if (operation === 'public.getNationList') {
|
||||||
|
return response([
|
||||||
|
{ id: 13, name: '풍년F&B', color: '#330000', level: 1, capitalCityId: 0, generalCount: 1, cityCount: 0 },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
if (operation === 'public.getGeneralList') return response([]);
|
||||||
throw new Error(`Unhandled legacy log fixture operation: ${operation}`);
|
throw new Error(`Unhandled legacy log fixture operation: ${operation}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -64,12 +73,15 @@ for (const viewport of [
|
|||||||
await page.goto('public');
|
await page.goto('public');
|
||||||
|
|
||||||
const lines = page.locator('.recent-log-line');
|
const lines = page.locator('.recent-log-line');
|
||||||
await expect(lines).toHaveCount(3);
|
await expect(lines).toHaveCount(4);
|
||||||
await expect(lines.nth(0).locator('b')).toHaveText('안전 강조');
|
await expect(lines.nth(0).locator('b')).toHaveText('안전 강조');
|
||||||
await expect(lines.nth(1).locator('.small_war_log .war_type_attack')).toHaveText('→');
|
await expect(lines.nth(1).locator('.small_war_log .war_type_attack')).toHaveText('→');
|
||||||
await expect(lines.nth(1).locator('.ev_highlight')).toHaveText('강조');
|
await expect(lines.nth(1).locator('.ev_highlight')).toHaveText('강조');
|
||||||
await expect(lines.nth(2)).toHaveText('이번 수입은 금 158입니다.');
|
await expect(lines.nth(2)).toHaveText('이번 수입은 금 158입니다.');
|
||||||
await expect(lines.nth(2)).not.toContainText('157.5');
|
await expect(lines.nth(2)).not.toContainText('157.5');
|
||||||
|
await expect(lines.nth(3).locator('b')).toHaveText('풍년F&B');
|
||||||
|
await expect(lines.nth(3)).toContainText('<img');
|
||||||
|
await expect(page.getByRole('cell', { name: '풍년F&B', exact: true })).toBeVisible();
|
||||||
await expect(lines.locator('script, img, svg, a, [onerror], [onclick], [style*="url"]')).toHaveCount(0);
|
await expect(lines.locator('script, img, svg, a, [onerror], [onclick], [style*="url"]')).toHaveCount(0);
|
||||||
await expect(lines.nth(0)).toContainText('<img src=x onerror=');
|
await expect(lines.nth(0)).toContainText('<img src=x onerror=');
|
||||||
await expect(lines.nth(1)).toContainText('<span class="name" onclick=');
|
await expect(lines.nth(1)).toContainText('<span class="name" onclick=');
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
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 { gameProfile, gameTrpcRoute } from './gameTestPaths.js';
|
||||||
import { expectLumenButtonStates } from './lumenButton.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) => {
|
await page.addInitScript((profile) => {
|
||||||
localStorage.setItem('sammo-game-token', 'ga_city_office');
|
localStorage.setItem('sammo-game-token', 'ga_city_office');
|
||||||
localStorage.setItem('sammo-game-profile', profile);
|
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 === 'auth.status') return response({ ok: true });
|
||||||
if (operation === 'lobby.info') return response({ myGeneral: { id: 20, name: '순욱' } });
|
if (operation === 'lobby.info') return response({ myGeneral: { id: 20, name: '순욱' } });
|
||||||
if (operation === 'join.getConfig') return response({});
|
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') {
|
if (operation === 'nation.getSecretGeneralList') {
|
||||||
return state.secretForbidden
|
return state.secretForbidden
|
||||||
? errorResponse(
|
? 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 });
|
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([]);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
defineProps<{
|
import { computed } from 'vue';
|
||||||
|
import { splitLegacyLineBreaks } from '../../utils/legacyDescription';
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
title: string;
|
title: string;
|
||||||
description?: string | null;
|
description?: string | null;
|
||||||
testId?: string;
|
testId?: string;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
const descriptionLines = computed(() => splitLegacyLineBreaks(props.description ?? ''));
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -16,7 +21,10 @@ defineProps<{
|
|||||||
<slot />
|
<slot />
|
||||||
<span v-if="description" class="directory-tooltip__content" role="tooltip">
|
<span v-if="description" class="directory-tooltip__content" role="tooltip">
|
||||||
<strong>{{ title }}</strong>
|
<strong>{{ title }}</strong>
|
||||||
<span>{{ description }}</span>
|
<span class="directory-tooltip__description"
|
||||||
|
><template v-for="(line, index) in descriptionLines" :key="index"
|
||||||
|
>{{ line }}<br v-if="index < descriptionLines.length - 1" /></template
|
||||||
|
></span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useSlots, watch } from 'vue';
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useSlots, watch } from 'vue';
|
||||||
|
import { splitLegacyLineBreaks } from '../../utils/legacyDescription';
|
||||||
import tippy, { type Instance, type Placement } from 'tippy.js';
|
import tippy, { type Instance, type Placement } from 'tippy.js';
|
||||||
import 'tippy.js/dist/tippy.css';
|
import 'tippy.js/dist/tippy.css';
|
||||||
|
|
||||||
@@ -28,7 +29,7 @@ let instance: Instance | null = null;
|
|||||||
const descriptionLines = computed(() => {
|
const descriptionLines = computed(() => {
|
||||||
const source = Array.isArray(props.description) ? props.description : [props.description ?? ''];
|
const source = Array.isArray(props.description) ? props.description : [props.description ?? ''];
|
||||||
return source
|
return source
|
||||||
.flatMap((line) => line.split(/<br\s*\/?\s*>|\r?\n/giu))
|
.flatMap(splitLegacyLineBreaks)
|
||||||
.map((line) => line.trim())
|
.map((line) => line.trim())
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
/**
|
||||||
|
* 카탈로그 설명의 Ref 줄바꿈만 해석한다. 반환값은 반드시 text interpolation으로
|
||||||
|
* 렌더링하며 HTML로 삽입하지 않는다. 빈 줄과 공백의 표시 정책은 소비자가 정한다.
|
||||||
|
*/
|
||||||
|
export const splitLegacyLineBreaks = (value: string): string[] => value.split(/<br\s*\/?\s*>|\r\n?|\n/giu);
|
||||||
@@ -4,6 +4,7 @@ import { usePageExit } from '../composables/usePageExit';
|
|||||||
import { formatServerDateTime } from '@sammo-ts/common/time/ServerDateTime';
|
import { formatServerDateTime } from '@sammo-ts/common/time/ServerDateTime';
|
||||||
import { JosaUtil } from '@sammo-ts/common/util/JosaUtil';
|
import { JosaUtil } from '@sammo-ts/common/util/JosaUtil';
|
||||||
import { computed, onMounted, reactive, ref } from 'vue';
|
import { computed, onMounted, reactive, ref } from 'vue';
|
||||||
|
import { splitLegacyLineBreaks } from '../utils/legacyDescription';
|
||||||
import { trpc } from '../utils/trpc';
|
import { trpc } from '../utils/trpc';
|
||||||
import { useGameFeedback } from '../composables/useGameFeedback';
|
import { useGameFeedback } from '../composables/useGameFeedback';
|
||||||
|
|
||||||
@@ -207,7 +208,6 @@ const specialNameMap = computed(() => {
|
|||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
});
|
});
|
||||||
const splitLegacyLineBreaks = (value: string): string[] => value.split(/<br\s*\/?\s*>|\r?\n/giu);
|
|
||||||
const selectedSpecialWarInfo = computed(
|
const selectedSpecialWarInfo = computed(
|
||||||
() => status.value?.availableSpecialWar.find((entry) => entry.key === nextSpecialKey.value)?.info ?? ''
|
() => status.value?.availableSpecialWar.find((entry) => entry.key === nextSpecialKey.value)?.info ?? ''
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ const integrationError = ref('');
|
|||||||
const secretLoading = ref(false);
|
const secretLoading = ref(false);
|
||||||
const personnelLoading = ref(false);
|
const personnelLoading = ref(false);
|
||||||
const pendingAppointment = ref('');
|
const pendingAppointment = ref('');
|
||||||
const sort = ref<Sort>(10);
|
const sort = ref<Sort>(1);
|
||||||
const selectedSort = ref<Sort>(10);
|
const selectedSort = ref<Sort>(1);
|
||||||
const extraSort = ref<
|
const extraSort = ref<
|
||||||
| 'name'
|
| 'name'
|
||||||
| 'populationRate'
|
| 'populationRate'
|
||||||
@@ -95,7 +95,7 @@ const cities = computed(() => {
|
|||||||
}
|
}
|
||||||
return values.sort((a, b) => {
|
return values.sort((a, b) => {
|
||||||
const key = sort.value;
|
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 === 2) return b.population - a.population;
|
||||||
if (key === 3) return b.population / b.populationMax - a.population / a.populationMax;
|
if (key === 3) return b.population / b.populationMax - a.population / a.populationMax;
|
||||||
if (key === 4) return b.trust - a.trust;
|
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 === 8) return b.defence - a.defence;
|
||||||
if (key === 9) return b.wall - a.wall;
|
if (key === 9) return b.wall - a.wall;
|
||||||
if (key === 10) return (b.trade ?? -1) - (a.trade ?? -1);
|
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;
|
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';
|
return ratio > 0.8 ? 'development-high' : ratio > 0.4 ? 'development-mid' : 'development-low';
|
||||||
};
|
};
|
||||||
const isRegionBreak = (city: City, index: number) =>
|
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 officer = (city: City, level: 2 | 3 | 4) => city.officers[level]?.name ?? '-';
|
||||||
const officerIsStationed = (city: City, level: OfficerLevel): boolean =>
|
const officerIsStationed = (city: City, level: OfficerLevel): boolean =>
|
||||||
secretData.value !== null && city.officers[level]?.cityId === city.id;
|
secretData.value !== null && city.officers[level]?.cityId === city.id;
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import { splitLegacyLineBreaks } from '../src/utils/legacyDescription.ts';
|
||||||
|
|
||||||
|
void describe('legacy catalog description line breaks', () => {
|
||||||
|
void it('accepts catalog br variants and platform newlines', () => {
|
||||||
|
assert.deepEqual(splitLegacyLineBreaks('가<br>나<BR/>다<br />라\r\n마\n바\r사'), [
|
||||||
|
'가',
|
||||||
|
'나',
|
||||||
|
'다',
|
||||||
|
'라',
|
||||||
|
'마',
|
||||||
|
'바',
|
||||||
|
'사',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
void it('preserves empty lines, whitespace, and unformatted descriptions', () => {
|
||||||
|
assert.deepEqual(splitLegacyLineBreaks(''), ['']);
|
||||||
|
assert.deepEqual(splitLegacyLineBreaks(' 일반 설명 '), [' 일반 설명 ']);
|
||||||
|
assert.deepEqual(splitLegacyLineBreaks('<br>첫 줄<br><br>끝 줄\n'), ['', '첫 줄', '', '끝 줄', '']);
|
||||||
|
});
|
||||||
|
|
||||||
|
void it('leaves other markup, attributes, and entities as literal text', () => {
|
||||||
|
const text = '<img src=x onerror="alert(1)"><b>문구</b><br><br onclick="alert(1)">';
|
||||||
|
assert.deepEqual(splitLegacyLineBreaks(text), [text]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1161,6 +1161,31 @@ export const adminRouter = router({
|
|||||||
await ctx.flushPublisher.publishUserFlush(input.userId, 'admin-scheduled-withdrawal');
|
await ctx.flushPublisher.publishUserFlush(input.userId, 'admin-scheduled-withdrawal');
|
||||||
return { ok: true, deleteAfter: deleteAfter.toISOString() };
|
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
|
forceDelete: userAdminProcedure
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
|
|||||||
@@ -103,10 +103,12 @@ const EXPENSIVE_ACTIONS = new Set([
|
|||||||
'auth.bootstrapLocal',
|
'auth.bootstrapLocal',
|
||||||
'auth.kakaoExchange',
|
'auth.kakaoExchange',
|
||||||
'auth.kakaoResolveAccount',
|
'auth.kakaoResolveAccount',
|
||||||
|
'auth.kakaoLinkWithPassword',
|
||||||
'auth.kakaoSetPassword',
|
'auth.kakaoSetPassword',
|
||||||
'auth.register',
|
'auth.register',
|
||||||
'auth.registerLocal',
|
'auth.registerLocal',
|
||||||
'auth.login',
|
'auth.login',
|
||||||
|
'auth.cancelDeletion',
|
||||||
'auth.kakaoOtp',
|
'auth.kakaoOtp',
|
||||||
'account.changePassword',
|
'account.changePassword',
|
||||||
'account.scheduleDeletion',
|
'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 { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
import { createPasswordHasher, type PasswordHasher } from './passwordHasher.js';
|
import { createPasswordHasher, type PasswordHasher } from './passwordHasher.js';
|
||||||
@@ -29,6 +32,7 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
|||||||
const usersByOauthId = new Map<string, UserRecord>();
|
const usersByOauthId = new Map<string, UserRecord>();
|
||||||
const usersByEmail = new Map<string, UserRecord>();
|
const usersByEmail = new Map<string, UserRecord>();
|
||||||
const retiredKakaoIds = new Set<string>();
|
const retiredKakaoIds = new Set<string>();
|
||||||
|
const detachedKakaoOwners = new Map<string, string>();
|
||||||
const iconsById = new Map<string, UserIconRecord>();
|
const iconsById = new Map<string, UserIconRecord>();
|
||||||
const specialAccessGrantsById = new Map<string, SpecialAccountAccessGrantRecord>();
|
const specialAccessGrantsById = new Map<string, SpecialAccountAccessGrantRecord>();
|
||||||
|
|
||||||
@@ -42,6 +46,62 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
|||||||
).toISOString();
|
).toISOString();
|
||||||
|
|
||||||
return {
|
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> {
|
async findById(id: string): Promise<UserRecord | null> {
|
||||||
for (const user of usersByName.values()) {
|
for (const user of usersByName.values()) {
|
||||||
if (user.id === id) {
|
if (user.id === id) {
|
||||||
@@ -103,6 +163,7 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
|||||||
if (
|
if (
|
||||||
input.oauth &&
|
input.oauth &&
|
||||||
(retiredKakaoIds.has(input.oauth.id) ||
|
(retiredKakaoIds.has(input.oauth.id) ||
|
||||||
|
detachedKakaoOwners.has(input.oauth.id) ||
|
||||||
usersByOauthId.has(`${input.oauth.type}:${input.oauth.id}`) ||
|
usersByOauthId.has(`${input.oauth.type}:${input.oauth.id}`) ||
|
||||||
usersByEmail.has(input.oauth.email.toLowerCase()))
|
usersByEmail.has(input.oauth.email.toLowerCase()))
|
||||||
) {
|
) {
|
||||||
@@ -204,9 +265,19 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
|||||||
}
|
}
|
||||||
throw new Error('User not found.');
|
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()) {
|
for (const user of usersByName.values()) {
|
||||||
if (user.id === userId) {
|
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();
|
user.kakaoTalkVerifiedUntil = validUntil.toISOString();
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
@@ -305,6 +376,7 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
|||||||
!user.kakaoReplacementApprovedByUserId ||
|
!user.kakaoReplacementApprovedByUserId ||
|
||||||
!user.kakaoReplacementReason ||
|
!user.kakaoReplacementReason ||
|
||||||
retiredKakaoIds.has(input.oauthId) ||
|
retiredKakaoIds.has(input.oauthId) ||
|
||||||
|
(detachedKakaoOwners.has(input.oauthId) && detachedKakaoOwners.get(input.oauthId) !== userId) ||
|
||||||
(oauthOwner && oauthOwner.id !== userId) ||
|
(oauthOwner && oauthOwner.id !== userId) ||
|
||||||
(emailOwner && emailOwner.id !== userId)
|
(emailOwner && emailOwner.id !== userId)
|
||||||
) {
|
) {
|
||||||
@@ -558,6 +630,20 @@ export const createInMemoryUserRepository = (hasher: PasswordHasher = createPass
|
|||||||
}
|
}
|
||||||
throw new Error('User not found.');
|
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> {
|
async deleteUser(userId: string): Promise<void> {
|
||||||
for (const [username, user] of usersByName.entries()) {
|
for (const [username, user] of usersByName.entries()) {
|
||||||
if (user.id === userId) {
|
if (user.id === userId) {
|
||||||
|
|||||||
@@ -194,16 +194,17 @@ export const requireKakaoTalkProof = async (options: {
|
|||||||
kakaoClient: KakaoOAuthClient;
|
kakaoClient: KakaoOAuthClient;
|
||||||
oauthSessions: OAuthSessionStore;
|
oauthSessions: OAuthSessionStore;
|
||||||
publicBaseUrl: string;
|
publicBaseUrl: string;
|
||||||
|
oauthSessionId?: string;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
}): Promise<KakaoOtpRequired | null> => {
|
}): Promise<KakaoOtpRequired | null> => {
|
||||||
const now = options.now ?? new Date();
|
const now = options.now ?? new Date();
|
||||||
const validUntil = parseDate(options.user.kakaoTalkVerifiedUntil);
|
const validUntil = parseDate(options.user.kakaoTalkVerifiedUntil);
|
||||||
if (validUntil && isAfter(validUntil, now)) {
|
if (!options.oauthSessionId && validUntil && isAfter(validUntil, now)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const active = await options.oauthSessions.getLoginChallengeForUser(options.user.id);
|
const active = await options.oauthSessions.getLoginChallengeForUser(options.user.id);
|
||||||
if (active) {
|
if (active && active.oauthSessionId === options.oauthSessionId) {
|
||||||
return {
|
return {
|
||||||
status: 'otp',
|
status: 'otp',
|
||||||
challengeId: active.id,
|
challengeId: active.id,
|
||||||
@@ -215,6 +216,9 @@ export const requireKakaoTalkProof = async (options: {
|
|||||||
const expiresAt = addSeconds(now, KAKAO_OTP_TTL_SECONDS);
|
const expiresAt = addSeconds(now, KAKAO_OTP_TTL_SECONDS);
|
||||||
const challenge = await options.oauthSessions.createLoginChallenge({
|
const challenge = await options.oauthSessions.createLoginChallenge({
|
||||||
userId: options.user.id,
|
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)),
|
code: String(randomInt(1000, 10_000)),
|
||||||
attemptsRemaining: KAKAO_OTP_ATTEMPTS,
|
attemptsRemaining: KAKAO_OTP_ATTEMPTS,
|
||||||
expiresAt: expiresAt.toISOString(),
|
expiresAt: expiresAt.toISOString(),
|
||||||
@@ -246,7 +250,7 @@ export const verifyKakaoTalkChallenge = async (options: {
|
|||||||
oauthSessions: OAuthSessionStore;
|
oauthSessions: OAuthSessionStore;
|
||||||
users: UserRepository;
|
users: UserRepository;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
}): Promise<{ user: UserRecord; validUntil: string }> => {
|
}): Promise<{ user: UserRecord; validUntil: string; pendingLinkSessionId?: string }> => {
|
||||||
const now = options.now ?? new Date();
|
const now = options.now ?? new Date();
|
||||||
const result = await options.oauthSessions.verifyLoginChallenge(options.challengeId, options.code, now);
|
const result = await options.oauthSessions.verifyLoginChallenge(options.challengeId, options.code, now);
|
||||||
if (result.status === 'expired') {
|
if (result.status === 'expired') {
|
||||||
@@ -268,11 +272,27 @@ export const verifyKakaoTalkChallenge = async (options: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const user = await options.users.findById(result.userId);
|
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', '카카오 계정 연결 정보를 찾지 못했습니다.');
|
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 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() };
|
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 { randomUUID } from 'node:crypto';
|
||||||
import { parseJson } from '@sammo-ts/common';
|
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 type OAuthMode = 'login' | 'change_pw' | 'verify';
|
||||||
|
|
||||||
|
export interface DeletionRecovery {
|
||||||
|
id: string;
|
||||||
|
userId: string;
|
||||||
|
deleteAfter: string;
|
||||||
|
authRevision: number;
|
||||||
|
expiresAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface OAuthPendingState {
|
export interface OAuthPendingState {
|
||||||
state: string;
|
state: string;
|
||||||
mode: OAuthMode;
|
mode: OAuthMode;
|
||||||
@@ -14,7 +24,12 @@ export interface OAuthPendingState {
|
|||||||
export interface OAuthSession {
|
export interface OAuthSession {
|
||||||
id: string;
|
id: string;
|
||||||
mode: OAuthMode;
|
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;
|
targetUserId?: string;
|
||||||
kakaoId: string;
|
kakaoId: string;
|
||||||
email: string;
|
email: string;
|
||||||
@@ -26,6 +41,9 @@ export interface OAuthSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface KakaoLoginChallenge {
|
export interface KakaoLoginChallenge {
|
||||||
|
authRevision?: number;
|
||||||
|
oauthId?: string;
|
||||||
|
oauthSessionId?: string;
|
||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
code: string;
|
code: string;
|
||||||
@@ -35,16 +53,19 @@ export interface KakaoLoginChallenge {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type KakaoLoginChallengeResult =
|
export type KakaoLoginChallengeResult =
|
||||||
| { status: 'verified'; userId: string }
|
| { status: 'verified'; userId: string; oauthSessionId?: string; authRevision?: number; oauthId?: string }
|
||||||
| { status: 'mismatch'; attemptsRemaining: number; expiresAt: string }
|
| { status: 'mismatch'; attemptsRemaining: number; expiresAt: string }
|
||||||
| { status: 'locked'; expiresAt: string }
|
| { status: 'locked'; expiresAt: string }
|
||||||
| { status: 'expired' };
|
| { status: 'expired' };
|
||||||
|
|
||||||
export interface OAuthSessionStore {
|
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>;
|
createPendingState(mode: OAuthMode, scopes: string[], userId?: string): Promise<OAuthPendingState>;
|
||||||
consumePendingState(state: string): Promise<OAuthPendingState | null>;
|
consumePendingState(state: string): Promise<OAuthPendingState | null>;
|
||||||
createSession(session: Omit<OAuthSession, 'id'>): Promise<OAuthSession>;
|
createSession(session: Omit<OAuthSession, 'id'>): Promise<OAuthSession>;
|
||||||
consumeSession(sessionId: string): Promise<OAuthSession | null>;
|
consumeSession(sessionId: string): Promise<OAuthSession | null>;
|
||||||
|
getSession(sessionId: string): Promise<OAuthSession | null>;
|
||||||
getLoginChallengeForUser(userId: string): Promise<KakaoLoginChallenge | null>;
|
getLoginChallengeForUser(userId: string): Promise<KakaoLoginChallenge | null>;
|
||||||
createLoginChallenge(challenge: Omit<KakaoLoginChallenge, 'id'>): Promise<KakaoLoginChallenge>;
|
createLoginChallenge(challenge: Omit<KakaoLoginChallenge, 'id'>): Promise<KakaoLoginChallenge>;
|
||||||
verifyLoginChallenge(challengeId: string, code: string, now?: Date): Promise<KakaoLoginChallengeResult>;
|
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
|
if redis.call('GET', userKey) == challenge.id then
|
||||||
redis.call('DEL', userKey)
|
redis.call('DEL', userKey)
|
||||||
end
|
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 = `
|
const consumeOnceScript = `
|
||||||
@@ -106,6 +127,20 @@ export class RedisOAuthSessionStore implements OAuthSessionStore {
|
|||||||
private readonly prefix: string;
|
private readonly prefix: string;
|
||||||
private readonly ttlSeconds: number;
|
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) {
|
constructor(client: RedisClientLike, prefix: string, ttlSeconds: number) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.prefix = prefix;
|
this.prefix = prefix;
|
||||||
@@ -164,6 +199,11 @@ export class RedisOAuthSessionStore implements OAuthSessionStore {
|
|||||||
return stored;
|
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> {
|
async consumeSession(sessionId: string): Promise<OAuthSession | null> {
|
||||||
const key = this.sessionKey(sessionId);
|
const key = this.sessionKey(sessionId);
|
||||||
const raw = await this.client.eval(consumeOnceScript, { keys: [key], arguments: [] });
|
const raw = await this.client.eval(consumeOnceScript, { keys: [key], arguments: [] });
|
||||||
@@ -225,6 +265,19 @@ export class RedisOAuthSessionStore implements OAuthSessionStore {
|
|||||||
|
|
||||||
// 테스트용 인메모리 OAuth 세션 저장소.
|
// 테스트용 인메모리 OAuth 세션 저장소.
|
||||||
export class InMemoryOAuthSessionStore implements OAuthSessionStore {
|
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 pendingStates = new Map<string, OAuthPendingState>();
|
||||||
private readonly sessions = new Map<string, OAuthSession>();
|
private readonly sessions = new Map<string, OAuthSession>();
|
||||||
private readonly loginChallenges = new Map<string, KakaoLoginChallenge>();
|
private readonly loginChallenges = new Map<string, KakaoLoginChallenge>();
|
||||||
@@ -259,6 +312,10 @@ export class InMemoryOAuthSessionStore implements OAuthSessionStore {
|
|||||||
return stored;
|
return stored;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getSession(sessionId: string): Promise<OAuthSession | null> {
|
||||||
|
return this.sessions.get(sessionId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
async consumeSession(sessionId: string): Promise<OAuthSession | null> {
|
async consumeSession(sessionId: string): Promise<OAuthSession | null> {
|
||||||
const session = this.sessions.get(sessionId) ?? null;
|
const session = this.sessions.get(sessionId) ?? null;
|
||||||
if (session) {
|
if (session) {
|
||||||
@@ -320,6 +377,12 @@ export class InMemoryOAuthSessionStore implements OAuthSessionStore {
|
|||||||
if (this.userLoginChallenges.get(challenge.userId) === challengeId) {
|
if (this.userLoginChallenges.get(challenge.userId) === challengeId) {
|
||||||
this.userLoginChallenges.delete(challenge.userId);
|
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 { GatewayPrisma, type GatewayPrismaClient } from '@sammo-ts/infra';
|
||||||
|
|
||||||
import { createPasswordHasher, type PasswordHasher } from './passwordHasher.js';
|
import { createPasswordHasher, type PasswordHasher } from './passwordHasher.js';
|
||||||
@@ -175,6 +178,91 @@ export const createPostgresUserRepository = (
|
|||||||
hasher: PasswordHasher = createPasswordHasher()
|
hasher: PasswordHasher = createPasswordHasher()
|
||||||
): UserRepository => {
|
): UserRepository => {
|
||||||
return {
|
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> {
|
async findById(id: string): Promise<UserRecord | null> {
|
||||||
const row = await prisma.appUser.findUnique({
|
const row = await prisma.appUser.findUnique({
|
||||||
where: {
|
where: {
|
||||||
@@ -286,6 +374,12 @@ export const createPostgresUserRepository = (
|
|||||||
if (retired) {
|
if (retired) {
|
||||||
throw new Error('Kakao identity is permanently 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 });
|
return tx.appUser.create({ data });
|
||||||
},
|
},
|
||||||
{ isolationLevel: 'Serializable' }
|
{ isolationLevel: 'Serializable' }
|
||||||
@@ -340,9 +434,18 @@ export const createPostgresUserRepository = (
|
|||||||
});
|
});
|
||||||
return mapUser(row);
|
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({
|
const row = await prisma.appUser.update({
|
||||||
where: { id: userId },
|
where: {
|
||||||
|
id: userId,
|
||||||
|
...(authRevision !== undefined ? { authRevision } : {}),
|
||||||
|
...(oauthId ? { oauthId } : {}),
|
||||||
|
},
|
||||||
data: { kakaoTalkVerifiedUntil: validUntil },
|
data: { kakaoTalkVerifiedUntil: validUntil },
|
||||||
});
|
});
|
||||||
return mapUser(row);
|
return mapUser(row);
|
||||||
@@ -357,6 +460,12 @@ export const createPostgresUserRepository = (
|
|||||||
if (retired) {
|
if (retired) {
|
||||||
throw new Error('Kakao identity is permanently 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({
|
const row = await tx.appUser.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: {
|
data: {
|
||||||
@@ -384,6 +493,12 @@ export const createPostgresUserRepository = (
|
|||||||
if (retired) {
|
if (retired) {
|
||||||
throw new Error('Kakao identity is permanently 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({
|
const updated = await tx.appUser.updateMany({
|
||||||
where: {
|
where: {
|
||||||
id: userId,
|
id: userId,
|
||||||
@@ -444,13 +559,17 @@ export const createPostgresUserRepository = (
|
|||||||
throw new Error('Kakao account replacement is not approved.');
|
throw new Error('Kakao account replacement is not approved.');
|
||||||
}
|
}
|
||||||
const normalizedEmail = input.email.toLowerCase();
|
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: { oauthId: input.oauthId }, select: { id: true } }),
|
||||||
tx.appUser.findUnique({ where: { email: normalizedEmail }, select: { id: true } }),
|
tx.appUser.findUnique({ where: { email: normalizedEmail }, select: { id: true } }),
|
||||||
tx.retiredKakaoIdentity.findUnique({ where: { oauthId: input.oauthId }, select: { id: true } }),
|
tx.retiredKakaoIdentity.findUnique({ where: { oauthId: input.oauthId }, select: { id: true } }),
|
||||||
|
tx.kakaoIdentityLinkHistory.findFirst({
|
||||||
|
where: { previousOauthId: input.oauthId, userId: { not: userId } },
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
if (
|
if (
|
||||||
retired ||
|
retired ||
|
||||||
|
detached ||
|
||||||
(oauthOwner && oauthOwner.id !== userId) ||
|
(oauthOwner && oauthOwner.id !== userId) ||
|
||||||
(emailOwner && emailOwner.id !== userId)
|
(emailOwner && emailOwner.id !== userId)
|
||||||
) {
|
) {
|
||||||
@@ -789,6 +908,14 @@ export const createPostgresUserRepository = (
|
|||||||
data: { deleteAfter },
|
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> {
|
async deleteUser(userId: string): Promise<void> {
|
||||||
await prisma.appUser.delete({
|
await prisma.appUser.delete({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { KakaoLinkAuthorization, KakaoLinkSnapshot } from './kakaoLinkPolicy.js';
|
||||||
export interface UserRecord {
|
export interface UserRecord {
|
||||||
id: string;
|
id: string;
|
||||||
username: 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 {
|
export interface UserRepository {
|
||||||
|
findDetachedKakaoOwner(oauthId: string): Promise<string | null>;
|
||||||
|
completeKakaoIdentityLink(userId: string, input: CompleteKakaoLinkInput): Promise<UserRecord>;
|
||||||
findById(id: string): Promise<UserRecord | null>;
|
findById(id: string): Promise<UserRecord | null>;
|
||||||
findByIds(ids: string[]): Promise<UserRecord[]>;
|
findByIds(ids: string[]): Promise<UserRecord[]>;
|
||||||
findByUsername(username: string): Promise<UserRecord | null>;
|
findByUsername(username: string): Promise<UserRecord | null>;
|
||||||
@@ -168,7 +183,12 @@ export interface UserRepository {
|
|||||||
updatePassword(userId: string, password: string): Promise<void>;
|
updatePassword(userId: string, password: string): Promise<void>;
|
||||||
updateOAuthInfo(userId: string, oauthInfo: UserOAuthInfo): Promise<void>;
|
updateOAuthInfo(userId: string, oauthInfo: UserOAuthInfo): Promise<void>;
|
||||||
syncKakaoIdentity(userId: string, email: string, oauthInfo: UserOAuthInfo): Promise<UserRecord>;
|
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(
|
linkKakao(
|
||||||
userId: string,
|
userId: string,
|
||||||
input: {
|
input: {
|
||||||
@@ -249,6 +269,7 @@ export interface UserRepository {
|
|||||||
resetProfileIcon(userId: string, requestedAt: Date): Promise<string | null>;
|
resetProfileIcon(userId: string, requestedAt: Date): Promise<string | null>;
|
||||||
setThirdPartyUse(userId: string, allowed: boolean): Promise<void>;
|
setThirdPartyUse(userId: string, allowed: boolean): Promise<void>;
|
||||||
scheduleDeletion(userId: string, deleteAfter: Date): Promise<void>;
|
scheduleDeletion(userId: string, deleteAfter: Date): Promise<void>;
|
||||||
|
cancelDeletion(userId: string, deleteAfter: string, authRevision: number): Promise<boolean>;
|
||||||
deleteUser(userId: string): Promise<void>;
|
deleteUser(userId: string): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+136
-157
@@ -23,6 +23,13 @@ import { openPassword, zDisplayName, zPasswordEnvelope, zRegistrationUsername }
|
|||||||
import { resolveEffectiveAccountIcon } from './auth/accountIconProjection.js';
|
import { resolveEffectiveAccountIcon } from './auth/accountIconProjection.js';
|
||||||
import { isGatewaySessionCurrent } from './auth/sessionValidity.js';
|
import { isGatewaySessionCurrent } from './auth/sessionValidity.js';
|
||||||
import { GameSessionLimitError } from './auth/sessionService.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 { purifyGatewayNoticeHtml } from './security/gatewayNoticeHtml.js';
|
||||||
import type { GatewayApiContext } from './context.js';
|
import type { GatewayApiContext } from './context.js';
|
||||||
import { listScenarioPreviews } from './scenario/scenarioCatalog.js';
|
import { listScenarioPreviews } from './scenario/scenarioCatalog.js';
|
||||||
@@ -73,6 +80,7 @@ const finishKakaoLogin = async <T extends 'login' | 'verified'>(
|
|||||||
accessToken: string,
|
accessToken: string,
|
||||||
successStatus: T
|
successStatus: T
|
||||||
) => {
|
) => {
|
||||||
|
assertLoginAllowed(user);
|
||||||
try {
|
try {
|
||||||
const challenge = await requireKakaoTalkProof({
|
const challenge = await requireKakaoTalkProof({
|
||||||
user,
|
user,
|
||||||
@@ -87,13 +95,7 @@ const finishKakaoLogin = async <T extends 'login' | 'verified'>(
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
throwKakaoVerificationError(error);
|
throwKakaoVerificationError(error);
|
||||||
}
|
}
|
||||||
const session = await ctx.sessions.createSession(user);
|
return completeGatewayLogin(ctx, user, successStatus);
|
||||||
return {
|
|
||||||
status: successStatus,
|
|
||||||
user: toPublicUser(user),
|
|
||||||
sessionToken: session.sessionToken,
|
|
||||||
issuedAt: session.issuedAt,
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const finishKakaoLoginOrRequestPasswordSetup = async <T extends 'login' | 'verified'>(
|
const finishKakaoLoginOrRequestPasswordSetup = async <T extends 'login' | 'verified'>(
|
||||||
@@ -102,6 +104,7 @@ const finishKakaoLoginOrRequestPasswordSetup = async <T extends 'login' | 'verif
|
|||||||
accessToken: string,
|
accessToken: string,
|
||||||
successStatus: T
|
successStatus: T
|
||||||
) => {
|
) => {
|
||||||
|
assertLoginAllowed(user);
|
||||||
if (!user.passwordResetRequired) {
|
if (!user.passwordResetRequired) {
|
||||||
return finishKakaoLogin(ctx, user, accessToken, successStatus);
|
return finishKakaoLogin(ctx, user, accessToken, successStatus);
|
||||||
}
|
}
|
||||||
@@ -397,57 +400,30 @@ export const appRouter = router({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
const oauthInfo = oauthInfoFromToken(token, tokenIssuedAt, localUser.oauthInfo);
|
const oauthInfo = oauthInfoFromToken(token, tokenIssuedAt, localUser.oauthInfo);
|
||||||
let verified: UserRecord;
|
if (localUser.oauthType !== 'KAKAO' || localUser.oauthId !== profile.kakaoId) {
|
||||||
const replacingKakao =
|
const stored = await ctx.oauthSessions.createSession({
|
||||||
localUser.oauthType === 'KAKAO' &&
|
mode: pending.mode,
|
||||||
Boolean(localUser.oauthId) &&
|
intent: 'link_existing',
|
||||||
localUser.oauthId !== profile.kakaoId;
|
targetUserId: localUser.id,
|
||||||
if (replacingKakao) {
|
kakaoId: profile.kakaoId,
|
||||||
try {
|
|
||||||
verified = await ctx.users.replaceKakaoWithApprovedIdentity(localUser.id, {
|
|
||||||
oauthId: profile.kakaoId,
|
|
||||||
email: profile.email,
|
email: profile.email,
|
||||||
oauthInfo,
|
accessToken: token.accessToken,
|
||||||
verifiedAt: new Date(),
|
refreshToken: token.refreshToken,
|
||||||
});
|
accessTokenValidUntil: oauthInfo.accessTokenValidUntil!,
|
||||||
} catch (error) {
|
refreshTokenValidUntil: oauthInfo.refreshTokenValidUntil,
|
||||||
throw new TRPCError({
|
createdAt: new Date().toISOString(),
|
||||||
code: 'PRECONDITION_FAILED',
|
|
||||||
message: '관리자의 카카오 계정 교체 승인이 없거나 만료되었습니다.',
|
|
||||||
cause: error,
|
|
||||||
});
|
});
|
||||||
|
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') {
|
const verified = await ctx.users.syncKakaoIdentity(localUser.id, profile.email, oauthInfo);
|
||||||
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 refreshed = (await ctx.users.findById(verified.id)) ?? verified;
|
const refreshed = (await ctx.users.findById(verified.id)) ?? verified;
|
||||||
await ctx.flushPublisher.publishUserFlush(
|
await ctx.flushPublisher.publishUserFlush(refreshed.id, 'kakao-verified');
|
||||||
refreshed.id,
|
|
||||||
replacingKakao ? 'kakao-account-replaced' : 'kakao-verified'
|
|
||||||
);
|
|
||||||
return finishKakaoLoginOrRequestPasswordSetup(ctx, refreshed, token.accessToken, 'verified');
|
return finishKakaoLoginOrRequestPasswordSetup(ctx, refreshed, token.accessToken, 'verified');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -518,8 +494,20 @@ export const appRouter = router({
|
|||||||
return finishKakaoLoginOrRequestPasswordSetup(ctx, synced, token.accessToken, 'login');
|
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 joinOauthInfo = oauthInfoFromToken(token, tokenIssuedAt);
|
||||||
const recoveryIntent = existingByEmail
|
const recoveryIntent = recoveryTarget
|
||||||
? ('link_existing' as const)
|
? ('link_existing' as const)
|
||||||
: alreadyRegisteredWithKakao
|
: alreadyRegisteredWithKakao
|
||||||
? ('rejoin' as const)
|
? ('rejoin' as const)
|
||||||
@@ -527,7 +515,7 @@ export const appRouter = router({
|
|||||||
const stored = await ctx.oauthSessions.createSession({
|
const stored = await ctx.oauthSessions.createSession({
|
||||||
mode: pending.mode,
|
mode: pending.mode,
|
||||||
intent: recoveryIntent,
|
intent: recoveryIntent,
|
||||||
targetUserId: existingByEmail?.id,
|
targetUserId: recoveryTarget?.id,
|
||||||
kakaoId: profile.kakaoId,
|
kakaoId: profile.kakaoId,
|
||||||
email: profile.email,
|
email: profile.email,
|
||||||
accessToken: token.accessToken,
|
accessToken: token.accessToken,
|
||||||
@@ -543,6 +531,9 @@ export const appRouter = router({
|
|||||||
action: recoveryIntent,
|
action: recoveryIntent,
|
||||||
oauthSessionId: stored.id,
|
oauthSessionId: stored.id,
|
||||||
email: stored.email,
|
email: stored.email,
|
||||||
|
passwordRequired: recoveryTarget
|
||||||
|
? recoveryTarget.email?.toLowerCase() !== profile.email
|
||||||
|
: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -560,7 +551,7 @@ export const appRouter = router({
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
.mutation(async ({ ctx, input }) => {
|
.mutation(async ({ ctx, input }) => {
|
||||||
const oauthSession = await ctx.oauthSessions.consumeSession(input.oauthSessionId);
|
const oauthSession = await ctx.oauthSessions.getSession(input.oauthSessionId);
|
||||||
if (!oauthSession) {
|
if (!oauthSession) {
|
||||||
throw new TRPCError({
|
throw new TRPCError({
|
||||||
code: 'UNAUTHORIZED',
|
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') {
|
if (input.action === 'rejoin') {
|
||||||
const [oauthOwner, emailOwner] = await Promise.all([
|
const [oauthOwner, emailOwner] = await Promise.all([
|
||||||
ctx.users.findByOauthId('KAKAO', oauthSession.kakaoId),
|
ctx.users.findByOauthId('KAKAO', oauthSession.kakaoId),
|
||||||
@@ -614,7 +607,7 @@ export const appRouter = router({
|
|||||||
ctx.users.findByEmail(oauthSession.email),
|
ctx.users.findByEmail(oauthSession.email),
|
||||||
ctx.users.findByOauthId('KAKAO', oauthSession.kakaoId),
|
ctx.users.findByOauthId('KAKAO', oauthSession.kakaoId),
|
||||||
]);
|
]);
|
||||||
if (!targetUser || emailOwner?.id !== targetUser.id) {
|
if (!targetUser || (emailOwner && emailOwner.id !== targetUser.id)) {
|
||||||
throw new TRPCError({
|
throw new TRPCError({
|
||||||
code: 'CONFLICT',
|
code: 'CONFLICT',
|
||||||
message:
|
message:
|
||||||
@@ -627,59 +620,42 @@ export const appRouter = router({
|
|||||||
message: '이미 다른 계정에 연결된 카카오 계정입니다.',
|
message: '이미 다른 계정에 연결된 카카오 계정입니다.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (targetUser.deleteAfter) {
|
assertLoginAllowed(targetUser);
|
||||||
throw new TRPCError({
|
|
||||||
code: 'PRECONDITION_FAILED',
|
|
||||||
message: '탈퇴 처리 중인 계정에는 카카오 계정을 다시 연결할 수 없습니다.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (isLoginBanned(targetUser.sanctions)) {
|
|
||||||
throw new TRPCError({
|
|
||||||
code: 'FORBIDDEN',
|
|
||||||
message: 'Account login is blocked.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const oauthInfo: UserOAuthInfo = {
|
return beginPendingKakaoLink(ctx, targetUser, oauthSession);
|
||||||
accessToken: oauthSession.accessToken,
|
}),
|
||||||
refreshToken: oauthSession.refreshToken,
|
kakaoLinkWithPassword: procedure
|
||||||
accessTokenValidUntil: oauthSession.accessTokenValidUntil,
|
.input(z.object({ oauthSessionId: z.string().uuid(), username: zUsername, credential: zPasswordEnvelope }))
|
||||||
refreshTokenValidUntil: oauthSession.refreshTokenValidUntil,
|
.mutation(async ({ ctx, input }) => {
|
||||||
};
|
const oauth = await ctx.oauthSessions.getSession(input.oauthSessionId);
|
||||||
let linked: UserRecord;
|
if (!oauth || !['register', 'rejoin', 'link_existing'].includes(oauth.intent ?? 'register'))
|
||||||
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) {
|
|
||||||
throw new TRPCError({
|
throw new TRPCError({
|
||||||
code: targetUser.oauthType === 'KAKAO' ? 'PRECONDITION_FAILED' : 'CONFLICT',
|
code: 'UNAUTHORIZED',
|
||||||
message:
|
message: '카카오 연결 확인이 만료되었습니다. 다시 로그인해 주세요.',
|
||||||
targetUser.oauthType === 'KAKAO'
|
|
||||||
? '기존 카카오 계정 교체에는 관리자 승인이 필요합니다.'
|
|
||||||
: '카카오 계정 연결 상태가 변경되었습니다. 처음부터 다시 진행해 주세요.',
|
|
||||||
cause: error,
|
|
||||||
});
|
});
|
||||||
}
|
await validatePendingKakaoProfile(ctx, oauth);
|
||||||
await ctx.flushPublisher.publishUserFlush(
|
const user = await ctx.users.findByUsername(input.username);
|
||||||
linked.id,
|
const password = openPassword(ctx.passwordEnvelope, input.credential);
|
||||||
targetUser.oauthType === 'KAKAO' ? 'kakao-account-replaced' : 'kakao-account-relinked'
|
if (
|
||||||
);
|
!user ||
|
||||||
return finishKakaoLoginOrRequestPasswordSetup(ctx, linked, oauthSession.accessToken, 'login');
|
!(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
|
kakaoSetPassword: procedure
|
||||||
.input(
|
.input(
|
||||||
@@ -690,6 +666,19 @@ export const appRouter = router({
|
|||||||
)
|
)
|
||||||
.mutation(async ({ ctx, input }) => {
|
.mutation(async ({ ctx, input }) => {
|
||||||
const password = openPassword(ctx.passwordEnvelope, input.credential);
|
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);
|
const oauthSession = await ctx.oauthSessions.consumeSession(input.oauthSessionId);
|
||||||
if (!oauthSession || oauthSession.intent !== 'password_setup' || !oauthSession.targetUserId) {
|
if (!oauthSession || oauthSession.intent !== 'password_setup' || !oauthSession.targetUserId) {
|
||||||
throw new TRPCError({
|
throw new TRPCError({
|
||||||
@@ -710,12 +699,7 @@ export const appRouter = router({
|
|||||||
message: '카카오 계정 연결 상태가 변경되었습니다. 처음부터 다시 진행해 주세요.',
|
message: '카카오 계정 연결 상태가 변경되었습니다. 처음부터 다시 진행해 주세요.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (user.deleteAfter) {
|
assertLoginAllowed(user);
|
||||||
throw new TRPCError({ code: 'FORBIDDEN', message: 'Account deletion is pending.' });
|
|
||||||
}
|
|
||||||
if (isLoginBanned(user.sanctions)) {
|
|
||||||
throw new TRPCError({ code: 'FORBIDDEN', message: 'Account login is blocked.' });
|
|
||||||
}
|
|
||||||
let verifiedProfile;
|
let verifiedProfile;
|
||||||
try {
|
try {
|
||||||
verifiedProfile = readVerifiedKakaoProfile(await ctx.kakaoClient.getMe(oauthSession.accessToken));
|
verifiedProfile = readVerifiedKakaoProfile(await ctx.kakaoClient.getMe(oauthSession.accessToken));
|
||||||
@@ -931,12 +915,6 @@ export const appRouter = router({
|
|||||||
message: 'Invalid username or password.',
|
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 password = openPassword(ctx.passwordEnvelope, input.credential);
|
||||||
const ok = await ctx.users.verifyPassword(user, password);
|
const ok = await ctx.users.verifyPassword(user, password);
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
@@ -945,22 +923,11 @@ export const appRouter = router({
|
|||||||
message: 'Invalid username or password.',
|
message: 'Invalid username or password.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (isLoginBanned(user.sanctions)) {
|
assertLoginAllowed(user);
|
||||||
throw new TRPCError({
|
|
||||||
code: 'FORBIDDEN',
|
|
||||||
message: 'Account login is blocked.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (user.oauthType === 'KAKAO') {
|
if (user.oauthType === 'KAKAO') {
|
||||||
const specialAccessGrants = await ctx.users.listSpecialAccessGrants(user.id);
|
const specialAccessGrants = await ctx.users.listSpecialAccessGrants(user.id);
|
||||||
if (hasOperatorSpecialAccess(user) || hasActiveSpecialAccountGrant(specialAccessGrants)) {
|
if (hasOperatorSpecialAccess(user) || hasActiveSpecialAccountGrant(specialAccessGrants)) {
|
||||||
const session = await ctx.sessions.createSession(user);
|
return completeGatewayLogin(ctx, user, 'login');
|
||||||
return {
|
|
||||||
status: 'login' as const,
|
|
||||||
user: toPublicUser(user),
|
|
||||||
sessionToken: session.sessionToken,
|
|
||||||
issuedAt: session.issuedAt,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
const ready = await verifyStoredKakaoIdentity({
|
const ready = await verifyStoredKakaoIdentity({
|
||||||
user,
|
user,
|
||||||
@@ -969,13 +936,34 @@ export const appRouter = router({
|
|||||||
}).catch((error: unknown) => throwKakaoVerificationError(error));
|
}).catch((error: unknown) => throwKakaoVerificationError(error));
|
||||||
return finishKakaoLogin(ctx, ready.user, ready.accessToken, 'login');
|
return finishKakaoLogin(ctx, ready.user, ready.accessToken, 'login');
|
||||||
}
|
}
|
||||||
const session = await ctx.sessions.createSession(user);
|
return completeGatewayLogin(ctx, user, 'login');
|
||||||
return {
|
}),
|
||||||
status: 'login' as const,
|
cancelDeletion: procedure
|
||||||
user: toPublicUser(user),
|
.input(z.object({ recoveryId: z.string().uuid() }).strict())
|
||||||
sessionToken: session.sessionToken,
|
.mutation(async ({ ctx, input }) => {
|
||||||
issuedAt: session.issuedAt,
|
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
|
kakaoOtp: procedure
|
||||||
.input(
|
.input(
|
||||||
@@ -991,24 +979,15 @@ export const appRouter = router({
|
|||||||
oauthSessions: ctx.oauthSessions,
|
oauthSessions: ctx.oauthSessions,
|
||||||
users: ctx.users,
|
users: ctx.users,
|
||||||
}).catch((error: unknown) => throwKakaoVerificationError(error));
|
}).catch((error: unknown) => throwKakaoVerificationError(error));
|
||||||
if (verified.user.deleteAfter) {
|
if (verified.pendingLinkSessionId)
|
||||||
throw new TRPCError({
|
return finishPendingKakaoLink(
|
||||||
code: 'FORBIDDEN',
|
ctx,
|
||||||
message: 'Account deletion is pending.',
|
verified.pendingLinkSessionId,
|
||||||
});
|
verified.user.id,
|
||||||
}
|
verified.validUntil
|
||||||
if (isLoginBanned(verified.user.sanctions)) {
|
);
|
||||||
throw new TRPCError({
|
|
||||||
code: 'FORBIDDEN',
|
|
||||||
message: 'Account login is blocked.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const session = await ctx.sessions.createSession(verified.user);
|
|
||||||
return {
|
return {
|
||||||
status: 'login' as const,
|
...(await completeGatewayLogin(ctx, verified.user, 'login')),
|
||||||
user: toPublicUser(verified.user),
|
|
||||||
sessionToken: session.sessionToken,
|
|
||||||
issuedAt: session.issuedAt,
|
|
||||||
validUntil: verified.validUntil,
|
validUntil: verified.validUntil,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -12,7 +12,11 @@ export const procedure = t.procedure.use(async ({ ctx, path, getRawInput, next }
|
|||||||
const raw: unknown = await getRawInput();
|
const raw: unknown = await getRawInput();
|
||||||
const input = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
const input = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
||||||
const resolveSubject = async (): Promise<string | undefined> => {
|
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')}`;
|
return `login:${input.username.trim().toLocaleLowerCase('en-US')}`;
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -2,12 +2,15 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|||||||
|
|
||||||
import { createGatewayPostgresConnector, type GatewayPrismaClient } from '@sammo-ts/infra';
|
import { createGatewayPostgresConnector, type GatewayPrismaClient } from '@sammo-ts/infra';
|
||||||
|
|
||||||
|
import { snapshotKakaoLink } from '../src/auth/kakaoLinkPolicy.js';
|
||||||
import { createPostgresUserRepository } from '../src/auth/postgresUserRepository.js';
|
import { createPostgresUserRepository } from '../src/auth/postgresUserRepository.js';
|
||||||
|
|
||||||
const databaseUrl = process.env.GATEWAY_RUNTIME_ACTION_DATABASE_URL;
|
const databaseUrl = process.env.GATEWAY_RUNTIME_ACTION_DATABASE_URL;
|
||||||
const integration = describe.skipIf(!databaseUrl);
|
const integration = describe.skipIf(!databaseUrl);
|
||||||
const firstUserId = 'f28aa8ce-6bd0-45e5-a127-056de53e3161';
|
const firstUserId = 'f28aa8ce-6bd0-45e5-a127-056de53e3161';
|
||||||
const secondUserId = '8f610116-64bd-4f18-bf7f-eae1737b227c';
|
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 oldKakaoId = 'account-identity-old-kakao';
|
||||||
const newKakaoId = 'account-identity-new-kakao';
|
const newKakaoId = 'account-identity-new-kakao';
|
||||||
|
|
||||||
@@ -30,9 +33,34 @@ integration('account identity PostgreSQL transaction', () => {
|
|||||||
db = connector.prisma;
|
db = connector.prisma;
|
||||||
closeDb = () => connector.disconnect();
|
closeDb = () => connector.disconnect();
|
||||||
await db.retiredKakaoIdentity.deleteMany({ where: { oauthId: { in: [oldKakaoId, newKakaoId] } } });
|
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({
|
await db.appUser.createMany({
|
||||||
data: [
|
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,
|
id: firstUserId,
|
||||||
loginId: 'identity-integration-one',
|
loginId: 'identity-integration-one',
|
||||||
@@ -63,7 +91,10 @@ integration('account identity PostgreSQL transaction', () => {
|
|||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await db?.retiredKakaoIdentity.deleteMany({ where: { oauthId: { in: [oldKakaoId, newKakaoId] } } });
|
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?.();
|
await closeDb?.();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -139,4 +170,114 @@ integration('account identity PostgreSQL transaction', () => {
|
|||||||
})
|
})
|
||||||
).rejects.toThrow();
|
).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';
|
import type { GatewayPrismaClient } from '@sammo-ts/infra';
|
||||||
|
|
||||||
@@ -25,6 +25,7 @@ const buildCaller = async (
|
|||||||
createOperation: GatewayProfileRepository['createOperation'],
|
createOperation: GatewayProfileRepository['createOperation'],
|
||||||
options: {
|
options: {
|
||||||
adminRoles?: string[];
|
adminRoles?: string[];
|
||||||
|
flushError?: Error;
|
||||||
firstUserIsAdmin?: boolean;
|
firstUserIsAdmin?: boolean;
|
||||||
runtimeActionCreateError?: unknown;
|
runtimeActionCreateError?: unknown;
|
||||||
initialNotice?: string;
|
initialNotice?: string;
|
||||||
@@ -242,6 +243,7 @@ const buildCaller = async (
|
|||||||
sessions,
|
sessions,
|
||||||
flushPublisher: {
|
flushPublisher: {
|
||||||
publishUserFlush: async (userId, reason, metadata) => {
|
publishUserFlush: async (userId, reason, metadata) => {
|
||||||
|
if (options.flushError) throw options.flushError;
|
||||||
flushes.push({
|
flushes.push({
|
||||||
userId,
|
userId,
|
||||||
reason,
|
reason,
|
||||||
@@ -2216,6 +2218,94 @@ describe('Gateway administrator account controls', () => {
|
|||||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
).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 () => {
|
it('prevents a delegated administrator from changing a root administrator', async () => {
|
||||||
const harness = await buildCaller(unusedCreateOperation, {
|
const harness = await buildCaller(unusedCreateOperation, {
|
||||||
adminRoles: ['user', 'admin.users.manage'],
|
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 { 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 fs from 'node:fs/promises';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
@@ -228,8 +232,7 @@ const buildCaller = (
|
|||||||
).toString('base64'),
|
).toString('base64'),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
const caller = appRouter.createCaller(
|
const context = createGatewayApiContext({
|
||||||
createGatewayApiContext({
|
|
||||||
users,
|
users,
|
||||||
sessions,
|
sessions,
|
||||||
flushPublisher,
|
flushPublisher,
|
||||||
@@ -255,9 +258,10 @@ const buildCaller = (
|
|||||||
findFirst: async () => null,
|
findFirst: async () => null,
|
||||||
},
|
},
|
||||||
} as unknown as GatewayPrismaClient,
|
} as unknown as GatewayPrismaClient,
|
||||||
})
|
});
|
||||||
);
|
const caller = appRouter.createCaller(context);
|
||||||
return {
|
return {
|
||||||
|
context,
|
||||||
caller,
|
caller,
|
||||||
oauthSessions,
|
oauthSessions,
|
||||||
users,
|
users,
|
||||||
@@ -265,6 +269,7 @@ const buildCaller = (
|
|||||||
flushPublisher,
|
flushPublisher,
|
||||||
userIconUpload,
|
userIconUpload,
|
||||||
kakaoProfile,
|
kakaoProfile,
|
||||||
|
kakaoClient,
|
||||||
sentTalkMessages,
|
sentTalkMessages,
|
||||||
refreshTokenCalls,
|
refreshTokenCalls,
|
||||||
sealPassword,
|
sealPassword,
|
||||||
@@ -636,11 +641,17 @@ describe('gateway auth flow', () => {
|
|||||||
});
|
});
|
||||||
setSessionHeader(register.sessionToken);
|
setSessionHeader(register.sessionToken);
|
||||||
const start = await caller.auth.kakaoStart({ mode: 'verify' });
|
const start = await caller.auth.kakaoStart({ mode: 'verify' });
|
||||||
const verified = await caller.auth.kakaoExchange({
|
const choice = await caller.auth.kakaoExchange({
|
||||||
code: 'oauth-code',
|
code: 'oauth-code',
|
||||||
state: start.state,
|
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');
|
expect(verified.status).toBe('otp');
|
||||||
if (verified.status !== 'otp') {
|
if (verified.status !== 'otp') {
|
||||||
throw new Error('Expected Kakao OTP challenge.');
|
throw new Error('Expected Kakao OTP challenge.');
|
||||||
@@ -648,6 +659,7 @@ describe('gateway auth flow', () => {
|
|||||||
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||||
expect(code).toBeTruthy();
|
expect(code).toBeTruthy();
|
||||||
const completed = await caller.auth.kakaoOtp({ challengeId: verified.challengeId, code: code! });
|
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);
|
expect(completed.user.kakaoVerified).toBe(true);
|
||||||
const stored = await users.findByUsername('verify-user');
|
const stored = await users.findByUsername('verify-user');
|
||||||
expect(stored).toMatchObject({
|
expect(stored).toMatchObject({
|
||||||
@@ -680,11 +692,6 @@ describe('gateway auth flow', () => {
|
|||||||
});
|
});
|
||||||
emailOwner.passwordResetRequired = true;
|
emailOwner.passwordResetRequired = true;
|
||||||
await users.markKakaoTalkVerified(emailOwner.id, new Date(Date.now() + 60_000));
|
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';
|
kakaoProfile.id = 'different-kakao-id';
|
||||||
|
|
||||||
const start = await caller.auth.kakaoStart({ mode: 'login' });
|
const start = await caller.auth.kakaoStart({ mode: 'login' });
|
||||||
@@ -710,15 +717,16 @@ describe('gateway auth flow', () => {
|
|||||||
});
|
});
|
||||||
expect(passwordSet.status).toBe('otp');
|
expect(passwordSet.status).toBe('otp');
|
||||||
expect(sentTalkMessages).toHaveLength(1);
|
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.findByOauthId('KAKAO', 'original-kakao-id')).toBeNull();
|
||||||
expect(await users.isKakaoIdentityRetired('original-kakao-id')).toBe(true);
|
expect(await users.isKakaoIdentityRetired('original-kakao-id')).toBe(false);
|
||||||
expect(await users.findByOauthId('KAKAO', 'different-kakao-id')).toMatchObject({
|
expect(await users.findDetachedKakaoOwner('original-kakao-id')).toBe(emailOwner.id);
|
||||||
id: emailOwner.id,
|
expect(await users.findByOauthId('KAKAO', 'different-kakao-id')).toMatchObject({ id: emailOwner.id });
|
||||||
username: 'email-owner',
|
expect(flushPublisher.publishUserFlush).toHaveBeenCalledWith(emailOwner.id, 'kakao-account-relinked');
|
||||||
email: 'tester@example.com',
|
|
||||||
});
|
|
||||||
expect(flushPublisher.publishUserFlush).toHaveBeenCalledWith(emailOwner.id, 'kakao-account-replaced');
|
|
||||||
expect(flushPublisher.publishUserFlush).toHaveBeenCalledWith(emailOwner.id, 'password-changed');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('requires a one-time password setup before an imported Kakao account can receive a session', async () => {
|
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 () => {
|
it('completes an approved administrator replacement only after fresh talk proof and keeps old-ID ownership', async () => {
|
||||||
const { caller, users, sessions, kakaoProfile, setSessionHeader } = buildCaller({
|
const f = buildCaller({ kakaoId: 'new-kakao-id', kakaoEmail: 'new-kakao@example.com' });
|
||||||
kakaoId: 'new-kakao-id',
|
const user = await f.users.createUser({
|
||||||
kakaoEmail: 'new-kakao@example.com',
|
|
||||||
});
|
|
||||||
const user = await users.createUser({
|
|
||||||
username: 'approved-replacement-user',
|
username: 'approved-replacement-user',
|
||||||
password: 'replacement-password',
|
password: 'replacement-password',
|
||||||
oauth: { type: 'KAKAO', id: 'old-kakao-id', email: 'old-kakao@example.com', info: {} },
|
oauth: { type: 'KAKAO', id: 'old-kakao-id', email: 'old-kakao@example.com', info: {} },
|
||||||
});
|
});
|
||||||
const oldSession = await sessions.createSession(user);
|
await f.users.updateRoles(user.id, ['admin']);
|
||||||
setSessionHeader(oldSession.sessionToken);
|
await f.users.setKakaoReplacementApproval(user.id, {
|
||||||
await users.setKakaoReplacementApproval(user.id, {
|
until: new Date(Date.now() + 60000),
|
||||||
until: new Date(Date.now() + 60_000),
|
approvedByUserId: 'operator',
|
||||||
approvedByUserId: 'admin-user-id',
|
reason: '본인 확인 완료',
|
||||||
reason: '사용자 본인 확인 완료',
|
|
||||||
});
|
});
|
||||||
|
const old = await f.sessions.createSession(user);
|
||||||
const start = await caller.auth.kakaoStart({ mode: 'verify', sessionToken: oldSession.sessionToken });
|
f.setSessionHeader(old.sessionToken);
|
||||||
const result = await caller.auth.kakaoExchange({ code: 'oauth-code', state: start.state });
|
const start = await f.caller.auth.kakaoStart({ mode: 'verify' });
|
||||||
expect(result).toMatchObject({ status: 'otp', successStatus: 'verified' });
|
const choice = await f.caller.auth.kakaoExchange({ code: 'code', state: start.state });
|
||||||
expect(await users.findById(user.id)).toMatchObject({
|
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',
|
oauthId: 'new-kakao-id',
|
||||||
email: 'new-kakao@example.com',
|
|
||||||
kakaoReplacementApprovedUntil: undefined,
|
|
||||||
authRevision: 1,
|
authRevision: 1,
|
||||||
|
kakaoReplacementApprovedUntil: undefined,
|
||||||
});
|
});
|
||||||
await expect(users.isKakaoIdentityRetired('old-kakao-id')).resolves.toBe(true);
|
expect(await f.users.isKakaoIdentityRetired('old-kakao-id')).toBe(false);
|
||||||
await expect(caller.auth.me({ sessionToken: oldSession.sessionToken })).resolves.toBeNull();
|
expect(await f.users.findDetachedKakaoOwner('old-kakao-id')).toBe(user.id);
|
||||||
|
expect(await f.caller.auth.me({ sessionToken: old.sessionToken })).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('영구 폐기') });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('synchronizes a changed email by stable Kakao ID during Kakao login', async () => {
|
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 () => {
|
it('blocks Kakao login while a ban is active', async () => {
|
||||||
const { caller, users, sealPassword, setSessionHeader } = buildCaller();
|
const { caller, users } = buildCaller();
|
||||||
const register = await caller.auth.registerLocal({
|
await users.createUser({
|
||||||
username: 'kakao-banned-user',
|
username: 'kakao-banned-user',
|
||||||
credential: sealPassword('kakao-banned-password'),
|
password: 'kakao-banned-password',
|
||||||
displayName: '카카오제재유저',
|
oauth: { type: 'KAKAO', id: '1', email: 'tester@example.com', info: {} },
|
||||||
termsAgreed: true,
|
|
||||||
privacyAgreed: true,
|
|
||||||
thirdPartyUse: false,
|
|
||||||
});
|
});
|
||||||
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');
|
const stored = await users.findByUsername('kakao-banned-user');
|
||||||
expect(stored).not.toBeNull();
|
expect(stored).not.toBeNull();
|
||||||
if (stored) {
|
if (stored) {
|
||||||
@@ -1223,6 +1220,7 @@ describe('gateway auth flow', () => {
|
|||||||
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
const code = sentTalkMessages.at(-1)?.match(/인증 코드는 (\d{4})/)?.[1];
|
||||||
expect(code).toBeTruthy();
|
expect(code).toBeTruthy();
|
||||||
const completed = await caller.auth.kakaoOtp({ challengeId: register.challengeId, code: code! });
|
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.user.username).toBe('tester');
|
||||||
expect(completed.sessionToken).toBeTruthy();
|
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 () => {
|
it('atomically consumes a successful code once', async () => {
|
||||||
const challenge = await createChallenge();
|
const challenge = await createChallenge();
|
||||||
|
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ describe('readReleaseManifest', () => {
|
|||||||
|
|
||||||
await expect(readReleaseManifest(workspaceRoot)).resolves.toMatchObject({
|
await expect(readReleaseManifest(workspaceRoot)).resolves.toMatchObject({
|
||||||
controllerProtocol: RELEASE_CONTROLLER_PROTOCOL,
|
controllerProtocol: RELEASE_CONTROLLER_PROTOCOL,
|
||||||
gatewaySchemaHead: '20261022000000_add_open_requests',
|
gatewaySchemaHead: '20261107000000_kakao_identity_link_history',
|
||||||
gameSchemaHead: '20260916080000_index_play_audit_decision_month',
|
gameSchemaHead: '20261114020000_reserved_turn_slot_primary_keys',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user