Merge branch 'main' into feature/board-rooms-parity
# Conflicts: # app/game-frontend/e2e/playwright.config.mjs # app/game-frontend/src/views/MainView.vue
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||
import type { RedisConnector } from '@sammo-ts/infra';
|
||||
|
||||
import { InMemoryFlushStore } from '../src/auth/flushStore.js';
|
||||
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
|
||||
import type { DatabaseClient, GameApiContext, GeneralRow } from '../src/context.js';
|
||||
import { appRouter } from '../src/router.js';
|
||||
|
||||
const now = new Date('2026-01-01T00:00:00Z');
|
||||
const general = (overrides: Partial<GeneralRow> = {}): GeneralRow => ({
|
||||
id: 1,
|
||||
userId: 'user-1',
|
||||
name: '아군',
|
||||
nationId: 1,
|
||||
cityId: 1,
|
||||
troopId: 0,
|
||||
npcState: 0,
|
||||
affinity: null,
|
||||
bornYear: 180,
|
||||
deadYear: 300,
|
||||
picture: null,
|
||||
imageServer: 0,
|
||||
leadership: 70,
|
||||
strength: 60,
|
||||
intel: 50,
|
||||
injury: 0,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
officerLevel: 1,
|
||||
gold: 1000,
|
||||
rice: 1000,
|
||||
crew: 500,
|
||||
crewTypeId: 1,
|
||||
train: 90,
|
||||
atmos: 90,
|
||||
weaponCode: 'None',
|
||||
bookCode: 'None',
|
||||
horseCode: 'None',
|
||||
itemCode: 'None',
|
||||
turnTime: now,
|
||||
recentWarTime: null,
|
||||
age: 20,
|
||||
startAge: 20,
|
||||
personalCode: 'None',
|
||||
specialCode: 'None',
|
||||
special2Code: 'None',
|
||||
lastTurn: {},
|
||||
meta: { defence_train: 80 },
|
||||
penalty: {},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
...overrides,
|
||||
});
|
||||
const auth = (roles: string[] = []): GameSessionTokenPayload => ({
|
||||
version: 1,
|
||||
profile: 'che:default',
|
||||
issuedAt: now.toISOString(),
|
||||
expiresAt: new Date(now.getTime() + 86400000).toISOString(),
|
||||
sessionId: 'session',
|
||||
user: { id: 'user-1', username: 'tester', displayName: 'Tester', roles },
|
||||
sanctions: {},
|
||||
});
|
||||
const city = (id: number, nationId: number) => ({
|
||||
id,
|
||||
name: `도시${id}`,
|
||||
level: 6,
|
||||
nationId,
|
||||
supplyState: 1,
|
||||
frontState: 0,
|
||||
population: 1000,
|
||||
populationMax: 2000,
|
||||
agriculture: 10,
|
||||
agricultureMax: 20,
|
||||
commerce: 11,
|
||||
commerceMax: 21,
|
||||
security: 12,
|
||||
securityMax: 22,
|
||||
trust: 50,
|
||||
trade: 100,
|
||||
defence: 13,
|
||||
defenceMax: 23,
|
||||
wall: 14,
|
||||
wallMax: 24,
|
||||
region: 2,
|
||||
conflict: {},
|
||||
meta: {},
|
||||
});
|
||||
|
||||
const context = (options: { me?: GeneralRow; roles?: string[]; nationMeta?: Record<string, unknown> } = {}) => {
|
||||
const me = options.me ?? general();
|
||||
const cities = [city(1, 1), city(2, 2), city(3, 2), city(80, 1)];
|
||||
const foreign = general({ id: 2, userId: 'user-2', name: '적군', nationId: 2, cityId: 2, crew: 777 });
|
||||
const db = {
|
||||
general: {
|
||||
findFirst: vi.fn(async () => me),
|
||||
findMany: vi.fn(async (args: { where?: Record<string, unknown>; select?: Record<string, boolean> }) => {
|
||||
if (args.where?.nationId === 1 && args.select?.cityId) return [{ cityId: me.cityId }];
|
||||
if (args.where?.cityId === 2) return [foreign];
|
||||
if (args.where?.cityId === 3) return [foreign];
|
||||
if (args.where?.officerLevel) return [];
|
||||
return [];
|
||||
}),
|
||||
},
|
||||
nation: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 1,
|
||||
name: '아국',
|
||||
color: '#008000',
|
||||
level: 1,
|
||||
capitalCityId: 1,
|
||||
meta: options.nationMeta ?? {},
|
||||
})),
|
||||
findMany: vi.fn(async () => [
|
||||
{ id: 1, name: '아국', color: '#008000', level: 1, capitalCityId: 1, meta: { power: 100 } },
|
||||
{ id: 2, name: '적국', color: '#800000', level: 1, capitalCityId: 2, meta: { power: 90 } },
|
||||
]),
|
||||
},
|
||||
city: { findMany: vi.fn(async () => cities) },
|
||||
worldState: { findFirst: vi.fn(async () => ({ meta: { turntime: '2026-01-01' } })) },
|
||||
generalTurn: { findMany: vi.fn(async () => []) },
|
||||
diplomacy: { findMany: vi.fn(async () => []) },
|
||||
};
|
||||
const redis = { get: vi.fn(async () => null), set: vi.fn(async () => null) } as unknown as RedisConnector['client'];
|
||||
const accessTokenStore = new RedisAccessTokenStore(redis, 'che:default');
|
||||
return {
|
||||
db: db as unknown as DatabaseClient,
|
||||
redis,
|
||||
turnDaemon: {} as GameApiContext['turnDaemon'],
|
||||
battleSim: {} as GameApiContext['battleSim'],
|
||||
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
||||
auth: auth(options.roles),
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
accessTokenStore,
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
gameTokenSecret: 'secret',
|
||||
} satisfies GameApiContext;
|
||||
};
|
||||
|
||||
describe('in-game information permissions', () => {
|
||||
it('does not expose nation-only pages to a wandering general', async () => {
|
||||
const caller = appRouter.createCaller(context({ me: general({ nationId: 0, officerLevel: 0 }) }));
|
||||
await expect(caller.nation.getNationInfo()).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
|
||||
await expect(caller.nation.getCityOverview()).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
|
||||
});
|
||||
|
||||
it('lets a wandering general select only the current city', async () => {
|
||||
const caller = appRouter.createCaller(context({ me: general({ nationId: 0, officerLevel: 0 }) }));
|
||||
const result = await caller.world.getCurrentCity({ cityId: 2 });
|
||||
expect(result.city.id).toBe(2);
|
||||
expect(result.options.map((entry) => entry.id)).toEqual([1]);
|
||||
expect(result.visibility.full).toBe(false);
|
||||
expect(result.city.population).toBeNull();
|
||||
expect(result.generals).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps adjacent foreign detail redacted and never reveals military fields', async () => {
|
||||
const result = await appRouter
|
||||
.createCaller(context({ me: general({ cityId: 80 }) }))
|
||||
.world.getCurrentCity({ cityId: 2 });
|
||||
expect(result.visibility).toEqual({ full: false, detailed: true });
|
||||
expect(result.city.agriculture).toBeNull();
|
||||
expect(result.city.defence).toBeNull();
|
||||
expect(result.generals[0]).toMatchObject({ crew: null, train: null, atmos: null, crewTypeId: null });
|
||||
});
|
||||
|
||||
it('allows a spied city in full but still redacts foreign-general private details', async () => {
|
||||
const result = await appRouter
|
||||
.createCaller(context({ nationMeta: { spy: { 2: 2 } } }))
|
||||
.world.getCurrentCity({ cityId: 2 });
|
||||
expect(result.visibility.full).toBe(true);
|
||||
expect(result.city.population).toBe(1000);
|
||||
expect(result.generals[0]).toMatchObject({ crew: 777, train: null, atmos: null, crewTypeId: null });
|
||||
});
|
||||
|
||||
it('allows administrative roles to inspect all city and general fields', async () => {
|
||||
const result = await appRouter.createCaller(context({ roles: ['admin'] })).world.getCurrentCity({ cityId: 3 });
|
||||
expect(result.options).toHaveLength(4);
|
||||
expect(result.visibility.full).toBe(true);
|
||||
expect(result.generals[0]).toMatchObject({ crew: 777, train: 90, atmos: 90, crewTypeId: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
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 poll = {
|
||||
id: 1,
|
||||
title: '선호하는 병종',
|
||||
body: '',
|
||||
options: ['보병', '기병'],
|
||||
multiple_options: 1,
|
||||
reveal_mode: 'after_vote',
|
||||
opener_general_id: 1,
|
||||
opener_name: '관리자',
|
||||
start_at: new Date('2026-07-26T00:00:00Z'),
|
||||
end_at: null,
|
||||
closed_at: null,
|
||||
};
|
||||
|
||||
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: 1000,
|
||||
rice: 1000,
|
||||
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 = (roles: string[] = [], 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;
|
||||
myVote?: number[] | null;
|
||||
voteRows?: Array<{ selection: number[]; cnt: number }>;
|
||||
pollRow?: typeof poll;
|
||||
configConst?: Record<string, unknown>;
|
||||
auctionTargets?: string[];
|
||||
}) => {
|
||||
const auth = options.auth === undefined ? buildAuth() : options.auth;
|
||||
const general = options.general === undefined ? buildGeneral() : options.general;
|
||||
const requestCommand = vi.fn(async () => ({
|
||||
type: 'voteReward' as const,
|
||||
ok: true as const,
|
||||
voteId: 1,
|
||||
generalId: general?.id ?? 0,
|
||||
awardedUnique: false,
|
||||
}));
|
||||
const queryRaw = vi.fn(async (query: GamePrisma.Sql) => {
|
||||
const text = sqlText(query);
|
||||
if (text.includes('FROM vote_poll') && text.includes('LIMIT 1')) {
|
||||
return [options.pollRow ?? poll];
|
||||
}
|
||||
if (text.includes('INSERT INTO vote (')) {
|
||||
return [{ id: 11 }];
|
||||
}
|
||||
if (text.includes('FROM vote_comment')) {
|
||||
return [];
|
||||
}
|
||||
if (text.includes('SELECT selection') && text.includes('general_id')) {
|
||||
return options.myVote ? [{ selection: options.myVote }] : [];
|
||||
}
|
||||
if (text.includes('GROUP BY selection')) {
|
||||
return options.voteRows ?? [{ selection: [0], cnt: 2 }];
|
||||
}
|
||||
if (text.includes('INSERT INTO vote_comment')) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const db = {
|
||||
$queryRaw: queryRaw,
|
||||
worldState: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 1,
|
||||
scenarioCode: 'default',
|
||||
currentYear: 200,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 3600,
|
||||
config: { const: { develCost: 18, allItems: {}, ...(options.configConst ?? {}) } },
|
||||
meta: {
|
||||
hiddenSeed: 'seed',
|
||||
scenarioId: 200,
|
||||
initYear: 180,
|
||||
initMonth: 1,
|
||||
scenarioMeta: { startYear: 180 },
|
||||
},
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
},
|
||||
general: {
|
||||
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
|
||||
general?.userId === where.userId ? general : null
|
||||
),
|
||||
findMany: vi.fn(async () => [
|
||||
{
|
||||
horseCode: general?.horseCode ?? 'None',
|
||||
weaponCode: general?.weaponCode ?? 'None',
|
||||
bookCode: general?.bookCode ?? 'None',
|
||||
itemCode: general?.itemCode ?? 'None',
|
||||
},
|
||||
]),
|
||||
count: vi.fn(async () => 2),
|
||||
},
|
||||
nation: {
|
||||
findFirst: vi.fn(async () => ({ name: '촉' })),
|
||||
},
|
||||
auction: {
|
||||
findMany: vi.fn(async () => (options.auctionTargets ?? []).map((targetCode) => ({ targetCode }))),
|
||||
},
|
||||
};
|
||||
const accessTokenStore = new RedisAccessTokenStore(
|
||||
{
|
||||
get: async () => null,
|
||||
set: async () => null,
|
||||
},
|
||||
'che:default'
|
||||
);
|
||||
const context: GameApiContext = {
|
||||
db: db as unknown as DatabaseClient,
|
||||
redis: {} 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, requestCommand, queryRaw, db };
|
||||
};
|
||||
|
||||
describe('vote router actor and permission boundaries', () => {
|
||||
it('rejects unauthenticated survey access', async () => {
|
||||
const fixture = buildContext({ auth: null });
|
||||
|
||||
await expect(appRouter.createCaller(fixture.context).vote.getVoteList()).rejects.toMatchObject({
|
||||
code: 'UNAUTHORIZED',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses only the general owned by the authenticated user for voting and reward dispatch', async () => {
|
||||
const owned = buildGeneral({ id: 7, userId: 'user-1', name: '유비' });
|
||||
const fixture = buildContext({ general: owned });
|
||||
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).vote.submitVote({ voteId: 1, selection: [0] })
|
||||
).resolves.toEqual({ ok: true, wonLottery: false });
|
||||
expect(fixture.requestCommand).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'voteReward',
|
||||
voteId: 1,
|
||||
generalId: 7,
|
||||
goldReward: 90,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('includes active unique auctions in the API-side reward expectation', async () => {
|
||||
const fixture = buildContext({
|
||||
configConst: {
|
||||
allItems: { weapon: { che_무기_12_칠성검: 1 } },
|
||||
maxUniqueItemLimit: [[-1, 1]],
|
||||
uniqueTrialCoef: 10,
|
||||
maxUniqueTrialProb: 10,
|
||||
minMonthToAllowInheritItem: 0,
|
||||
},
|
||||
auctionTargets: ['che_무기_12_칠성검'],
|
||||
});
|
||||
|
||||
await appRouter.createCaller(fixture.context).vote.submitVote({ voteId: 1, selection: [0] });
|
||||
|
||||
expect(fixture.requestCommand).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
unique: { expected: false, itemKey: null },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects voting and comments 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.vote.submitVote({ voteId: 1, selection: [0] })).rejects.toMatchObject({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'General not found',
|
||||
});
|
||||
await expect(caller.vote.addComment({ voteId: 1, text: '댓글' })).rejects.toMatchObject({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'General not found',
|
||||
});
|
||||
expect(fixture.requestCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects duplicate selections before persisting a vote', async () => {
|
||||
const fixture = buildContext({ pollRow: { ...poll, multiple_options: 2 } });
|
||||
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).vote.submitVote({ voteId: 1, selection: [0, 0] })
|
||||
).rejects.toMatchObject({
|
||||
code: 'BAD_REQUEST',
|
||||
message: '선택한 항목이 올바르지 않습니다.',
|
||||
});
|
||||
expect(fixture.requestCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows legacy-compatible aggregate results before the current general votes', async () => {
|
||||
const fixture = buildContext({ myVote: null, voteRows: [{ selection: [0], cnt: 2 }] });
|
||||
|
||||
const result = await appRouter.createCaller(fixture.context).vote.getVoteDetail({ voteId: 1 });
|
||||
|
||||
expect(result.myVote).toBeNull();
|
||||
expect(result.votes).toEqual([{ selection: [0], count: 2 }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['global survey permission', ['admin.survey.open'], true],
|
||||
['wildcard survey permission', ['admin.survey.open:*'], true],
|
||||
['matching profile permission', ['admin.survey.open:che:default'], true],
|
||||
['different profile permission', ['admin.survey.open:hwe:default'], false],
|
||||
['ordinary user', ['user'], false],
|
||||
])('%s controls the administrator panel', async (_label, roles, allowed) => {
|
||||
const fixture = buildContext({ auth: buildAuth(roles) });
|
||||
const request = appRouter.createCaller(fixture.context).vote.getAdminStatus();
|
||||
|
||||
if (allowed) {
|
||||
await expect(request).resolves.toEqual({ ok: true });
|
||||
} else {
|
||||
await expect(request).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user