Merge branch 'main' into feature/dynasty-list-parity

This commit is contained in:
2026-07-26 06:09:17 +00:00
73 changed files with 3146 additions and 564 deletions
+308
View File
@@ -0,0 +1,308 @@
import { describe, expect, it, vi } from 'vitest';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import type { GamePrisma, RedisConnector } from '@sammo-ts/infra';
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
import { InMemoryFlushStore } from '../src/auth/flushStore.js';
import type { DatabaseClient, GameApiContext, GeneralRow } from '../src/context.js';
import type { TurnDaemonTransport } from '../src/daemon/transport.js';
import { appRouter } from '../src/router.js';
const buildGeneral = (overrides: Partial<GeneralRow> = {}): GeneralRow => ({
id: 7,
userId: 'user-1',
name: '유비',
nationId: 1,
cityId: 1,
troopId: 0,
npcState: 0,
affinity: null,
bornYear: 180,
deadYear: 300,
picture: null,
imageServer: 0,
leadership: 50,
strength: 50,
intel: 50,
injury: 0,
experience: 0,
dedication: 0,
officerLevel: 1,
gold: 10_000,
rice: 10_000,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
weaponCode: 'None',
bookCode: 'None',
horseCode: 'None',
itemCode: 'None',
turnTime: new Date('2026-07-26T00:00:00Z'),
recentWarTime: null,
age: 20,
startAge: 20,
personalCode: 'None',
specialCode: 'None',
special2Code: 'None',
lastTurn: {},
meta: {},
penalty: {},
createdAt: new Date('2026-07-26T00:00:00Z'),
updatedAt: new Date('2026-07-26T00:00:00Z'),
...overrides,
});
const buildAuth = (userId = 'user-1'): GameSessionTokenPayload => ({
version: 1,
profile: 'che:default',
issuedAt: '2026-07-26T00:00:00.000Z',
expiresAt: '2026-07-27T00:00:00.000Z',
sessionId: `session-${userId}`,
user: {
id: userId,
username: userId,
displayName: userId,
roles: [],
},
sanctions: {},
});
const sqlText = (query: GamePrisma.Sql): string => query.strings.join(' ');
const buildContext = (options: {
auth?: GameSessionTokenPayload | null;
general?: GeneralRow | null;
auctions?: Array<Record<string, unknown>>;
queryRaw?: (query: GamePrisma.Sql) => Promise<unknown>;
}) => {
const auth = options.auth === undefined ? buildAuth() : options.auth;
const general = options.general === undefined ? buildGeneral() : options.general;
const requestCommand = vi.fn(async (command: { type: string }) => {
if (command.type === 'auctionOpen') {
return {
type: 'auctionOpen' as const,
ok: true as const,
auctionId: 91,
closeAt: '2026-07-27T00:00:00.000Z',
};
}
return {
type: 'auctionBid' as const,
ok: true as const,
auctionId: 91,
closeAt: '2026-07-27T00:00:00.000Z',
};
});
const queryRaw = vi.fn(options.queryRaw ?? (async () => []));
const worldState = {
id: 1,
scenarioCode: 'default',
currentYear: 200,
currentMonth: 1,
tickSeconds: 3600,
config: {
const: {
auctionName: ['청룡', '백호', '주작', '현무'],
allItems: { weapon: { che_무기_12_칠성검: 1 } },
},
},
meta: { hiddenSeed: 'auction-hidden-seed' },
updatedAt: new Date('2026-07-26T00:00:00Z'),
};
const db = {
$queryRaw: queryRaw,
general: {
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
general?.userId === where.userId ? general : null
),
findMany: vi.fn(async ({ where }: { where: { id: { in: number[] } } }) =>
where.id.in.map((id) => ({ id, name: id === 88 ? '관우' : '조조' }))
),
},
auction: {
findMany: vi.fn(async () => options.auctions ?? []),
findFirst: vi.fn(async () => null),
},
worldState: {
findFirst: vi.fn(async () => worldState),
},
inheritancePoint: {
findUnique: vi.fn(async () => ({ value: 10_000 })),
},
logEntry: {
findMany: vi.fn(async () => []),
},
};
const redis = {
zAdd: vi.fn(async () => 1),
};
const accessTokenStore = new RedisAccessTokenStore(
{
get: async () => null,
set: async () => null,
},
'che:default'
);
const context: GameApiContext = {
db: db as unknown as DatabaseClient,
redis: redis as unknown as RedisConnector['client'],
turnDaemon: { requestCommand } as unknown as TurnDaemonTransport,
battleSim: {} as GameApiContext['battleSim'],
profile: { id: 'che', scenario: 'default', name: 'che:default' },
auth,
uploadDir: 'uploads',
uploadPath: '/uploads',
uploadPublicUrl: null,
accessTokenStore,
flushStore: new InMemoryFlushStore(),
gameTokenSecret: 'test-secret',
};
return { context, db, queryRaw, redis, requestCommand };
};
describe('auction router actor and permission boundaries', () => {
it('rejects unauthenticated auction reads', async () => {
const fixture = buildContext({ auth: null });
await expect(appRouter.createCaller(fixture.context).auction.getOverview()).rejects.toMatchObject({
code: 'UNAUTHORIZED',
});
});
it('rejects reads and mutations when the authenticated user owns no general', async () => {
const fixture = buildContext({
auth: buildAuth('user-2'),
general: buildGeneral({ userId: 'user-1' }),
});
const caller = appRouter.createCaller(fixture.context);
await expect(caller.auction.getOverview()).rejects.toMatchObject({
code: 'UNAUTHORIZED',
message: 'General not found.',
});
await expect(
caller.auction.openBuyRice({
amount: 1000,
closeTurnCnt: 3,
startBidAmount: 500,
finishBidAmount: 2000,
})
).rejects.toMatchObject({
code: 'UNAUTHORIZED',
message: 'General not found.',
});
expect(fixture.requestCommand).not.toHaveBeenCalled();
});
it('derives the daemon actor from the session-owned general and ignores a forged generalId field', async () => {
const fixture = buildContext({ general: buildGeneral({ id: 7, userId: 'user-1' }) });
const input = {
amount: 1000,
closeTurnCnt: 3,
startBidAmount: 500,
finishBidAmount: 2000,
generalId: 999,
};
await appRouter.createCaller(fixture.context).auction.openBuyRice(input);
expect(fixture.requestCommand).toHaveBeenCalledWith({
type: 'auctionOpen',
auctionType: 'BUY_RICE',
generalId: 7,
amount: 1000,
closeTurnCnt: 3,
startBidAmount: 500,
finishBidAmount: 2000,
});
});
it('redacts real unique-auction identities while preserving caller markers', async () => {
const openedAt = new Date('2026-07-26T01:00:00Z');
const fixture = buildContext({
auctions: [
{
id: 31,
type: 'UNIQUE_ITEM',
targetCode: 'che_무기_12_칠성검',
hostGeneralId: 7,
hostName: null,
detail: { title: '칠성검 경매', startBidAmount: 5000 },
status: 'OPEN',
closeAt: new Date('2026-07-27T00:00:00Z'),
bids: [
{
id: 41,
generalId: 88,
amount: 5500,
eventAt: openedAt,
},
],
},
],
});
const result = await appRouter.createCaller(fixture.context).auction.getOverview();
const unique = result.uniqueAuctions[0];
expect(unique).toMatchObject({
id: 31,
hostGeneralId: null,
isCallerHost: true,
highestBid: { amount: 5500, isCaller: false },
});
expect(unique?.hostName).not.toBe('유비');
expect(unique?.highestBid?.bidderName).not.toBe('관우');
expect(JSON.stringify(unique)).not.toContain('"generalId"');
expect(JSON.stringify(unique)).not.toContain('"hostGeneralId":7');
});
it('keeps the legacy default of no requested close extension for a unique bid', async () => {
const fixture = buildContext({
queryRaw: async (query) => {
const text = sqlText(query);
if (text.includes('FROM auction') && text.includes('WHERE id =')) {
return [
{
id: 31,
type: 'UNIQUE_ITEM',
targetCode: 'che_무기_12_칠성검',
hostGeneralId: 88,
detail: { startBidAmount: 100, isReverse: false },
status: 'OPEN',
closeAt: new Date('2026-07-27T00:00:00Z'),
},
];
}
if (text.includes('FROM auction_bid') && text.includes('general_id =')) {
return [];
}
if (text.includes('SELECT bid.auction_id')) {
return [{ auctionId: 31, generalId: 88, amount: 100 }];
}
if (text.includes('FROM auction_bid')) {
return [{ id: 41, generalId: 88, amount: 100, meta: {} }];
}
if (text.includes('SELECT id, target_code')) {
return [{ id: 31, targetCode: 'che_무기_12_칠성검' }];
}
return [];
},
});
await appRouter.createCaller(fixture.context).auction.bidUnique({
auctionId: 31,
amount: 110,
});
expect(fixture.requestCommand).toHaveBeenCalledWith({
type: 'auctionBid',
auctionId: 31,
generalId: 7,
amount: 110,
tryExtendCloseDate: false,
});
});
});
@@ -0,0 +1,71 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { upsertGeneralAccess } from '../src/services/generalAccess.js';
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const generalId = 9_980_071;
integration('general access tracking persistence', () => {
let db: GamePrismaClient;
let closeDb: (() => Promise<void>) | undefined;
beforeAll(async () => {
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
closeDb = () => connector.disconnect();
await db.generalAccessLog.deleteMany({ where: { generalId } });
});
afterAll(async () => {
await db.generalAccessLog.deleteMany({ where: { generalId } });
await closeDb?.();
});
it('atomically increments concurrent requests and resets only windowed counters', async () => {
const firstWindow = {
generalId,
userId: 'access-user-a',
now: new Date('2026-07-26T03:05:00.000Z'),
dayStartedAt: new Date('2026-07-26T00:00:00.000Z'),
scoreStartedAt: new Date('2026-07-26T03:00:00.000Z'),
};
await upsertGeneralAccess(db, { ...firstWindow, weight: 2 });
await Promise.all(
Array.from({ length: 20 }, (_, index) =>
upsertGeneralAccess(db, {
...firstWindow,
now: new Date(firstWindow.now.getTime() + index + 1),
weight: 1,
})
)
);
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).toMatchObject({
userId: 'access-user-a',
refresh: 22,
refreshTotal: 22,
refreshScore: 22,
refreshScoreTotal: 22,
});
await upsertGeneralAccess(db, {
generalId,
userId: 'access-user-b',
now: new Date('2026-07-27T00:05:00.000Z'),
dayStartedAt: new Date('2026-07-27T00:00:00.000Z'),
scoreStartedAt: new Date('2026-07-27T00:00:00.000Z'),
weight: 1,
});
expect(await db.generalAccessLog.findUniqueOrThrow({ where: { generalId } })).toMatchObject({
userId: 'access-user-b',
refresh: 1,
refreshTotal: 23,
refreshScore: 1,
refreshScoreTotal: 23,
});
});
});
@@ -0,0 +1,100 @@
import { describe, expect, it, vi } from 'vitest';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import type { DatabaseClient } from '../src/context.js';
import { recordGeneralAccess, resolveAccessWindows } from '../src/services/generalAccess.js';
const auth = (roles = ['user']): GameSessionTokenPayload => ({
version: 1,
profile: 'che:default',
issuedAt: '2026-07-26T00:00:00.000Z',
expiresAt: '2026-07-27T00:00:00.000Z',
sessionId: 'access-session',
user: {
id: 'user-7',
username: 'user7',
displayName: '사용자7',
roles,
},
sanctions: {},
});
const buildDb = (meta: Record<string, unknown> = {}) => {
const executeRaw = vi.fn(async (_query: unknown) => 1);
const findGeneral = vi.fn(async () => ({ id: 7, userId: 'user-7' }));
const findWorld = vi.fn(async () => ({
tickSeconds: 600,
meta: {
opentime: '2026-07-25T00:00:00.000Z',
lastTurnTime: '2026-07-26T03:00:00.000Z',
...meta,
},
}));
const db = {
$executeRaw: executeRaw,
general: { findFirst: findGeneral },
worldState: { findFirst: findWorld },
} as unknown as DatabaseClient;
return { db, executeRaw, findGeneral, findWorld };
};
describe('general access tracking', () => {
it('resolves the UTC day and latest processed turn windows', () => {
expect(
resolveAccessWindows(new Date('2026-07-26T03:14:15.000Z'), 600, {
lastTurnTime: '2026-07-26T03:10:00.000Z',
})
).toEqual({
dayStartedAt: new Date('2026-07-26T00:00:00.000Z'),
scoreStartedAt: new Date('2026-07-26T03:10:00.000Z'),
});
});
it('uses the session user actor and the legacy page weight in one atomic upsert', async () => {
const { db, executeRaw, findGeneral } = buildDb();
const now = new Date('2026-07-26T03:05:00.000Z');
await expect(recordGeneralAccess({ auth: auth(), db }, 'npc-list', now)).resolves.toBe(true);
expect(findGeneral).toHaveBeenCalledWith({
where: { userId: 'user-7' },
orderBy: { id: 'asc' },
select: { id: true, userId: true },
});
expect(executeRaw).toHaveBeenCalledTimes(1);
const statement = executeRaw.mock.calls[0]![0] as { sql: string; values: unknown[] };
expect(statement.sql).toContain('ON CONFLICT (general_id) DO UPDATE');
expect(statement.sql).toContain('general_access_log.refresh + EXCLUDED.refresh');
expect(statement.values).toEqual([
7,
'user-7',
now,
2,
2,
2,
2,
new Date('2026-07-26T00:00:00.000Z'),
new Date('2026-07-26T03:00:00.000Z'),
]);
});
it('does not write for anonymous/admin users, a future opening, or a finished world', async () => {
const anonymous = buildDb();
await expect(recordGeneralAccess({ auth: null, db: anonymous.db }, 'traffic')).resolves.toBe(false);
expect(anonymous.findGeneral).not.toHaveBeenCalled();
const admin = buildDb();
await expect(recordGeneralAccess({ auth: auth(['admin']), db: admin.db }, 'traffic')).resolves.toBe(false);
expect(admin.findGeneral).not.toHaveBeenCalled();
const future = buildDb({ opentime: '2026-07-27T00:00:00.000Z' });
await expect(
recordGeneralAccess({ auth: auth(), db: future.db }, 'traffic', new Date('2026-07-26T03:05:00.000Z'))
).resolves.toBe(false);
expect(future.executeRaw).not.toHaveBeenCalled();
const united = buildDb({ isUnited: 2 });
await expect(recordGeneralAccess({ auth: auth(), db: united.db }, 'traffic')).resolves.toBe(false);
expect(united.executeRaw).not.toHaveBeenCalled();
});
});
+28 -3
View File
@@ -9,6 +9,7 @@ import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.j
import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js';
import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js';
import { appRouter } from '../src/router.js';
import { formatLegacyRankingNumber, resolveLegacyTextColor } from '../src/router/ranking/index.js';
const profile: GameProfile = {
id: 'che',
@@ -40,7 +41,7 @@ const generalRows = [
npcState: 0,
picture: '1.jpg',
imageServer: 0,
meta: { ownerName: '공개소유자' },
meta: { ownerName: '공개소유자', dex1: 120 },
experience: 1200,
dedication: 900,
horseCode: 'che_명마_15_적토마',
@@ -56,7 +57,7 @@ const generalRows = [
npcState: 1,
picture: null,
imageServer: 0,
meta: { owner_name: '빙의소유자' },
meta: { owner_name: '빙의소유자', dex1: 80 },
experience: 1100,
dedication: 800,
horseCode: 'None',
@@ -72,7 +73,7 @@ const generalRows = [
npcState: 2,
picture: null,
imageServer: 0,
meta: {},
meta: { dex1: 200 },
experience: 1300,
dedication: 1000,
horseCode: 'None',
@@ -122,6 +123,9 @@ const buildContext = (options?: {
{ generalId: 1, type: 'firenum', value: 10 },
{ generalId: 2, type: 'firenum', value: 20 },
{ generalId: 3, type: 'firenum', value: 30 },
{ generalId: 1, type: 'dex1', value: 999 },
{ generalId: 2, type: 'dex1', value: 999 },
{ generalId: 3, type: 'dex1', value: 999 },
],
},
auction: {
@@ -218,6 +222,27 @@ describe('ranking.getBestGeneral', () => {
const result = await appRouter.createCaller(buildContext()).ranking.getBestGeneral({ view: 'npc' });
expect(result.sections[0]?.entries.map((entry) => entry.id)).toEqual([3]);
});
it('uses the general dex columns as the legacy source of truth instead of mirrored rank rows', async () => {
const result = await appRouter.createCaller(buildContext()).ranking.getBestGeneral({ view: 'user' });
const dex = result.sections.find((section) => section.title === '보 병 숙 련 도');
expect(dex?.entries.map((entry) => [entry.id, entry.value, entry.printValue])).toEqual([
[1, 120, '120'],
[2, 80, '80'],
]);
expect(dex?.entries[0]).toMatchObject({
bgColor: '#006400',
fgColor: '#000000',
});
});
it('matches PHP number_format rounding and the legacy fixed color table', () => {
expect(formatLegacyRankingNumber(1.005, 2)).toBe('1.01');
expect(formatLegacyRankingNumber(12345.6, 2)).toBe('12,345.60');
expect(resolveLegacyTextColor('#006400')).toBe('#000000');
expect(resolveLegacyTextColor('#330000')).toBe('#ffffff');
});
});
describe('ranking hall of fame', () => {