fix: purify nation-authored HTML at server boundaries

This commit is contained in:
2026-07-31 06:41:09 +00:00
parent 71ec02d091
commit 243f58be9a
16 changed files with 898 additions and 55 deletions
+2
View File
@@ -26,6 +26,7 @@
"typecheck": "tsc -b"
},
"devDependencies": {
"@types/sanitize-html": "2.16.1",
"tsdown": "^0.18.4",
"vite-tsconfig-paths": "^6.0.3",
"vitest": "^4.0.16"
@@ -42,6 +43,7 @@
"es-toolkit": "^1.43.0",
"fastify": "^5.6.2",
"redis": "^5.10.0",
"sanitize-html": "2.17.6",
"sharp": "^0.34.4",
"zod": "^4.3.5"
}
+2 -1
View File
@@ -20,6 +20,7 @@ import {
RejectedNpcPossessionCommandError,
} from '../../daemon/databaseTransport.js';
import { NpcPossessionError, reserveNpcPossessionCandidates } from '@sammo-ts/game-engine';
import { resolveNationScoutMessage } from '../nation/shared.js';
const resolveSelectionCommandResult = (
result: Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>> | null,
@@ -302,7 +303,7 @@ export const joinRouter = router({
id: nation.id,
name: nation.name,
color: nation.color,
scoutMessage: typeof meta.infoText === 'string' ? meta.infoText : null,
scoutMessage: resolveNationScoutMessage(meta) || null,
};
});
@@ -3,6 +3,7 @@ import { z } from 'zod';
import { asRecord } from '@sammo-ts/common';
import { purifyNationHtml } from '../../../security/nationHtml.js';
import { authedProcedure } from '../../../trpc.js';
import { getMyGeneral } from '../../shared/general.js';
import { assertNationAccess, assertNationEditable, updateNationMeta } from '../shared.js';
@@ -10,7 +11,7 @@ import { assertNationAccess, assertNationEditable, updateNationMeta } from '../s
export const setNotice = authedProcedure
.input(
z.object({
msg: z.string().max(16384),
msg: z.string().min(1).max(16384),
})
)
.mutation(async ({ ctx, input }) => {
@@ -25,13 +26,14 @@ export const setNotice = authedProcedure
}
assertNationEditable(me, nation.meta);
const nationMeta = asRecord(nation.meta);
const msg = purifyNationHtml(input.msg);
await updateNationMeta(
ctx,
me.nationId,
{
notice: input.msg,
notice: msg,
},
nationMeta
);
return { ok: true };
return { ok: true, msg };
});
@@ -3,6 +3,7 @@ import { z } from 'zod';
import { asRecord } from '@sammo-ts/common';
import { purifyNationHtml } from '../../../security/nationHtml.js';
import { authedProcedure } from '../../../trpc.js';
import { getMyGeneral } from '../../shared/general.js';
import { assertNationAccess, assertNationEditable, updateNationMeta } from '../shared.js';
@@ -10,7 +11,7 @@ import { assertNationAccess, assertNationEditable, updateNationMeta } from '../s
export const setScoutMsg = authedProcedure
.input(
z.object({
msg: z.string().max(1000),
msg: z.string().min(1).max(1000),
})
)
.mutation(async ({ ctx, input }) => {
@@ -25,13 +26,14 @@ export const setScoutMsg = authedProcedure
}
assertNationEditable(me, nation.meta);
const nationMeta = asRecord(nation.meta);
const msg = purifyNationHtml(input.msg);
await updateNationMeta(
ctx,
me.nationId,
{
infoText: input.msg,
infoText: msg,
},
nationMeta
);
return { ok: true };
return { ok: true, msg };
});
+3 -2
View File
@@ -27,6 +27,7 @@ import {
} from '@sammo-ts/logic';
import type { GameApiContext, InputJsonValue, WorldStateRow } from '../../context.js';
import { purifyNationHtml } from '../../security/nationHtml.js';
import { resolveSecretPermission } from '../shared/secretPermission.js';
export type PermissionKind = 'normal' | 'ambassador' | 'auditor';
@@ -268,10 +269,10 @@ export const resolveNationBlockScout = (meta: Record<string, unknown>): boolean
readMetaBool(meta, 'scout', readMetaBool(meta, 'blockScout', false));
export const resolveNationNotice = (meta: Record<string, unknown>): string =>
typeof meta.notice === 'string' ? meta.notice : '';
purifyNationHtml(typeof meta.notice === 'string' ? meta.notice : '');
export const resolveNationScoutMessage = (meta: Record<string, unknown>): string =>
typeof meta.infoText === 'string' ? meta.infoText : '';
purifyNationHtml(typeof meta.infoText === 'string' ? meta.infoText : '');
export const resolveWarSettingRemain = (meta: Record<string, unknown>): number => {
const legacy = readMetaNumber(meta, 'available_war_setting_cnt', -1);
+98
View File
@@ -0,0 +1,98 @@
import sanitizeHtml from 'sanitize-html';
const safeIframeSource = /^(?:https?:)?\/\/(?:www\.youtube(?:-nocookie)?\.com\/embed\/|player\.vimeo\.com\/video\/)/;
const unsafeUrlScheme = /^(?:javascript|data|vbscript):/i;
const unsafeSourceMarker = 'data-sammo-unsafe-source';
const normalizeUrlScheme = (value: string): string =>
Array.from(value)
.filter((character) => {
const codePoint = character.codePointAt(0) ?? 0;
return codePoint > 0x20 && (codePoint < 0x7f || codePoint > 0x9f);
})
.join('');
const options: sanitizeHtml.IOptions = {
allowedTags: [...sanitizeHtml.defaults.allowedTags, 'img', 'iframe'],
allowedAttributes: {
...sanitizeHtml.defaults.allowedAttributes,
'*': ['class', 'style', 'title', 'lang', 'dir', 'align', 'data-flip'],
a: ['href', 'name', 'title', 'data-flip'],
img: ['src', 'srcset', 'alt', 'title', 'width', 'height', 'data-flip', unsafeSourceMarker],
iframe: ['src', 'width', 'height', 'title', 'frameborder', 'data-flip'],
table: ['width', 'border', 'cellpadding', 'cellspacing', 'summary', 'data-flip'],
td: ['width', 'height', 'colspan', 'rowspan', 'headers', 'data-flip'],
th: ['width', 'height', 'colspan', 'rowspan', 'scope', 'headers', 'data-flip'],
col: ['width', 'span', 'data-flip'],
colgroup: ['width', 'span', 'data-flip'],
},
allowedSchemes: ['http', 'https', 'ftp', 'mailto', 'tel'],
allowProtocolRelative: true,
allowedStyles: {
'*': {
color: [/^#[0-9a-f]{3,8}$/i, /^rgba?\([\d\s.,%]+\)$/i, /^hsla?\([\d\s.,%]+\)$/i, /^[a-z]+$/i],
'background-color': [/^#[0-9a-f]{3,8}$/i, /^rgba?\([\d\s.,%]+\)$/i, /^hsla?\([\d\s.,%]+\)$/i, /^[a-z]+$/i],
'font-family': [/^[\w\s"',.-]+$/],
'font-size': [
/^\d+(?:\.\d+)?(?:px|pt|em|rem|%)$/i,
/^(?:xx-small|x-small|small|medium|large|x-large|xx-large)$/i,
],
'font-style': [/^(?:normal|italic|oblique)$/i],
'font-weight': [/^(?:normal|bold|bolder|lighter|[1-9]00)$/i],
'text-align': [/^(?:left|right|center|justify|start|end)$/i],
'text-decoration': [/^[\w\s-]+$/i],
'vertical-align': [
/^(?:baseline|sub|super|top|text-top|middle|bottom|text-bottom|-?\d+(?:\.\d+)?(?:px|em|rem|%))$/i,
],
width: [/^(?:auto|\d+(?:\.\d+)?(?:px|em|rem|%))$/i],
height: [/^(?:auto|\d+(?:\.\d+)?(?:px|em|rem|%))$/i],
'max-width': [/^(?:none|\d+(?:\.\d+)?(?:px|em|rem|%))$/i],
'max-height': [/^(?:none|\d+(?:\.\d+)?(?:px|em|rem|%))$/i],
'min-width': [/^\d+(?:\.\d+)?(?:px|em|rem|%)$/i],
'min-height': [/^\d+(?:\.\d+)?(?:px|em|rem|%)$/i],
margin: [/^(?:auto|-?\d+(?:\.\d+)?(?:px|em|rem|%))(?:\s+(?:auto|-?\d+(?:\.\d+)?(?:px|em|rem|%))){0,3}$/i],
padding: [/^\d+(?:\.\d+)?(?:px|em|rem|%)(?:\s+\d+(?:\.\d+)?(?:px|em|rem|%)){0,3}$/i],
'line-height': [/^(?:normal|\d+(?:\.\d+)?(?:px|em|rem|%)?)$/i],
float: [/^(?:none|left|right)$/i],
},
},
transformTags: {
img: (tagName, attribs) => {
if (typeof attribs.src === 'string' && unsafeUrlScheme.test(normalizeUrlScheme(attribs.src))) {
return { tagName, attribs: { [unsafeSourceMarker]: 'true' } };
}
if (attribs.alt !== undefined || !attribs.src) {
return { tagName, attribs };
}
const filename = attribs.src.split('/').filter(Boolean).at(-1);
return {
tagName,
attribs: filename ? { ...attribs, alt: filename } : attribs,
};
},
iframe: (tagName, attribs) => {
const source = typeof attribs.src === 'string' ? attribs.src.trim() : undefined;
if (source && !safeIframeSource.test(source)) {
const { src: _unsafeSource, ...safeAttribs } = attribs;
return { tagName, attribs: safeAttribs };
}
return {
tagName,
attribs: source === undefined ? attribs : { ...attribs, src: source },
};
},
},
exclusiveFilter: (frame) => frame.tag === 'img' && frame.attribs[unsafeSourceMarker] === 'true',
};
/**
* Ref's WebUtil::htmlPurify boundary for nation notice and recruitment HTML.
* Writes are canonicalized and reads are purified again so pre-existing rows
* cannot execute markup.
*/
export const purifyNationHtml = (value: string | null | undefined): string => {
if (!value) {
return '';
}
return sanitizeHtml(value, options);
};
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it } from 'vitest';
import { purifyNationHtml } from '../src/security/nationHtml.js';
describe('nation HTML purification', () => {
it('removes executable markup and unsafe URL/CSS vectors', () => {
const dirty = [
'<script>globalThis.__nationXss = true</script>',
'<img src="javascript:alert(1)" onerror="globalThis.__nationXss = true">',
'<img src="jav&#x09;ascript:alert(1)" srcset="data:image/svg+xml,attack 2x">',
'<a href="javascript:alert(2)" onclick="alert(3)">unsafe link</a>',
'<p style="background-image:url(javascript:alert(4));color:#fff" onmouseover="alert(5)">notice</p>',
'<iframe src="https://attacker.example/embed/1" onload="alert(6)"></iframe>',
'<iframe src="//www.youtube.com.evil.example/embed/1" srcdoc="<script>alert(7)</script>"></iframe>',
'<svg><a xlink:href="javascript:alert(8)">svg</a></svg>',
].join('');
const clean = purifyNationHtml(dirty);
expect(clean).not.toMatch(/script|onerror|onclick|onmouseover|onload|javascript:|background-image|attacker/i);
expect(clean).not.toContain('<img');
expect(clean).toContain('<a>unsafe link</a>');
expect(clean).toContain('<p style="color:#fff">notice</p>');
expect(clean).toContain('<iframe></iframe>');
});
it('does not throw on malformed escaped filenames and preserves the raw basename as alt text', () => {
expect(purifyNationHtml('<img src="/image/%E0%A4%A">')).toBe('<img src="/image/%E0%A4%A" alt="%E0%A4%A" />');
expect(purifyNationHtml('<img src="/image/a%20b.png"><img src="/image/a.png?x/y"><img src="x" alt="">')).toBe(
'<img src="/image/a%20b.png" alt="a%20b.png" /><img src="/image/a.png?x/y" alt="y" /><img src="x" alt="" />'
);
});
it('matches Ref iframe whitespace and case handling', () => {
expect(
purifyNationHtml(
[
'<iframe src=" https://www.youtube.com/embed/x "></iframe>',
'<iframe src="https://WWW.YouTube.COM/embed/x"></iframe>',
'<iframe src="https://www.youtube.com/Embed/x"></iframe>',
].join('')
)
).toBe('<iframe src="https://www.youtube.com/embed/x"></iframe><iframe></iframe><iframe></iframe>');
});
it('preserves Ref-compatible formatting, data-flip, images, and safe video embeds', () => {
const source = [
'<div class="notice" data-flip="horizontal" style="text-align:center;color:#00ffff">',
'<strong>북벌</strong><br>',
'<a href="https://example.com/path" target="_blank">계획</a>',
'<img src="/image/icons/default.jpg" srcset="javascript:alert(1) 2x, /image/icons/default.jpg 1x" alt="장수" width="64" height="64">',
'<iframe src="//www.youtube-nocookie.com/embed/abc123" width="560" height="315" allowfullscreen></iframe>',
'<iframe src="https://player.vimeo.com/video/1234" title="video"></iframe>',
'</div>',
].join('');
const clean = purifyNationHtml(source);
expect(clean).toContain('class="notice"');
expect(clean).toContain('data-flip="horizontal"');
expect(clean).toContain('style="text-align:center;color:#00ffff"');
expect(clean).toContain('<strong>북벌</strong><br />');
expect(clean).toContain('href="https://example.com/path"');
expect(clean).not.toContain('target="_blank"');
expect(clean).toContain('src="/image/icons/default.jpg"');
expect(clean).toContain('alt="장수"');
expect(clean).toContain('srcset="/image/icons/default.jpg 1x"');
expect(clean).toContain('//www.youtube-nocookie.com/embed/abc123');
expect(clean).toContain('https://player.vimeo.com/video/1234');
});
it('is idempotent for already-purified stored values', () => {
const first = purifyNationHtml('<p style="color:red"><b>방침</b></p>');
expect(purifyNationHtml(first)).toBe(first);
});
});
+161
View File
@@ -0,0 +1,161 @@
import { describe, expect, it, vi } from 'vitest';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import type { 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';
import { resolveNationNotice, resolveNationScoutMessage } from '../src/router/nation/shared.js';
const general: 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: 50,
strength: 50,
intel: 50,
injury: 0,
experience: 0,
dedication: 0,
officerLevel: 5,
gold: 1_000,
rice: 1_000,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
weaponCode: 'None',
bookCode: 'None',
horseCode: 'None',
itemCode: 'None',
turnTime: new Date('2026-01-01T00:00:00.000Z'),
recentWarTime: null,
age: 20,
startAge: 20,
personalCode: 'None',
specialCode: 'None',
special2Code: 'None',
lastTurn: {},
meta: {},
penalty: {},
createdAt: new Date('2026-01-01T00:00:00.000Z'),
updatedAt: new Date('2026-01-01T00:00:00.000Z'),
};
const auth: GameSessionTokenPayload = {
version: 1,
profile: 'che:default',
issuedAt: '2026-01-01T00:00:00.000Z',
expiresAt: '2026-01-02T00:00:00.000Z',
sessionId: 'session-1',
user: {
id: 'user-1',
username: 'tester',
displayName: 'Tester',
roles: [],
},
sanctions: {},
};
const buildContext = () => {
const requestCommand = vi.fn(async (command: unknown) => ({
type: 'setNationMeta',
ok: true,
updatedAt: '2026-01-01T00:00:01.000Z',
command,
}));
const db = {
general: {
findFirst: vi.fn(async () => general),
},
nation: {
findUnique: vi.fn(async () => ({ meta: {} })),
},
};
const redisClient = {
get: async () => null,
set: async () => null,
};
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: new RedisAccessTokenStore(redisClient, 'che:default'),
flushStore: new InMemoryFlushStore(),
gameTokenSecret: 'test-secret',
};
return { caller: appRouter.createCaller(context), requestCommand };
};
describe('nation HTML API boundary', () => {
it.each([
{
procedure: 'setNotice',
metaKey: 'notice',
limit: 16_384,
},
{
procedure: 'setScoutMsg',
metaKey: 'infoText',
limit: 1_000,
},
] as const)('purifies $procedure before daemon persistence', async ({ procedure, metaKey, limit }) => {
const fixture = buildContext();
const dirty = `<p data-flip="x">안전</p><img src=x onerror="alert(1)"><script>alert(2)</script>`;
const msg = '<p data-flip="x">안전</p><img src="x" alt="x" />';
await expect(fixture.caller.nation[procedure]({ msg: dirty.slice(0, limit) })).resolves.toEqual({
ok: true,
msg,
});
expect(fixture.requestCommand).toHaveBeenCalledWith({
type: 'setNationMeta',
nationId: 1,
updates: {
[metaKey]: msg,
},
expectedUpdatedAt: undefined,
});
});
it.each(['setNotice', 'setScoutMsg'] as const)(
'rejects an empty $procedure value like Ref required validation',
async (procedure) => {
await expect(buildContext().caller.nation[procedure]({ msg: '' })).rejects.toMatchObject({
code: 'BAD_REQUEST',
});
}
);
it('purifies legacy stored values on every read resolver', () => {
expect(
resolveNationNotice({
notice: '<strong>방침</strong><svg onload="alert(1)"></svg>',
})
).toBe('<strong>방침</strong>');
expect(
resolveNationScoutMessage({
infoText: '<a href="javascript:alert(1)">임관</a>',
})
).toBe('<a>임관</a>');
});
});
@@ -0,0 +1,202 @@
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { type GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import {
createGamePostgresConnector,
createRedisConnector,
resolveRedisConfigFromEnv,
type GamePrismaClient,
type RedisConnector,
} from '@sammo-ts/infra';
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
import { createGameApiServer } from '../src/server.js';
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl || !process.env.REDIS_URL);
const profileId = process.env.POSTGRES_SCHEMA ?? 'conditional_integration';
const profileName = `che:nation-html-${process.pid}`;
const userId = `nation-html-user-${process.pid}`;
const fixtureId = 900_000 + (process.pid % 50_000);
const secret = 'nation-html-http-secret';
const redisPrefix = `sammo:nation-html:${process.pid}`;
const envKeys = [
'PROFILE',
'SCENARIO',
'GAME_PROFILE_NAME',
'GAME_API_HOST',
'GAME_API_PORT',
'GAME_TOKEN_SECRET',
'GATEWAY_REDIS_PREFIX',
'GAME_UPLOAD_DIR',
'DATABASE_URL',
] as const;
const originalEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
type RunningServer = Awaited<ReturnType<typeof createGameApiServer>>;
let server: RunningServer | null = null;
let baseUrl = '';
let uploadDir = '';
let db: GamePrismaClient;
let disconnectDb: (() => Promise<void>) | null = null;
let redis: RedisConnector | null = null;
let accessToken = '';
const restoreEnv = (): void => {
for (const [key, value] of originalEnv) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
};
integration('nation HTML purification over HTTP transport', () => {
beforeAll(async () => {
uploadDir = await fs.mkdtemp(path.join(os.tmpdir(), 'sammo-nation-html-http-'));
process.env.PROFILE = profileId;
process.env.SCENARIO = 'nation-html';
process.env.GAME_PROFILE_NAME = profileName;
process.env.GAME_API_HOST = '127.0.0.1';
process.env.GAME_API_PORT = '0';
process.env.GAME_TOKEN_SECRET = secret;
process.env.GATEWAY_REDIS_PREFIX = redisPrefix;
process.env.GAME_UPLOAD_DIR = uploadDir;
process.env.DATABASE_URL = databaseUrl;
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
disconnectDb = () => connector.disconnect();
await db.general.deleteMany({ where: { id: fixtureId } });
await db.nation.deleteMany({ where: { id: fixtureId } });
await db.worldState.deleteMany({ where: { id: fixtureId } });
await db.worldState.create({
data: {
id: fixtureId,
scenarioCode: 'nation-html',
currentYear: 200,
currentMonth: 1,
tickSeconds: 600,
meta: {
lastTurnTime: '2026-07-31T00:00:00.000Z',
},
},
});
await db.nation.create({
data: {
id: fixtureId,
name: '정화국',
color: '#00ffff',
meta: {
notice: [
'<p data-flip="horizontal" style="color:#00ffff">안전한 방침</p>',
'<img src="/image/icons/default.jpg" onerror="globalThis.__nationXss=1">',
'<script>globalThis.__nationXss=2</script>',
'<iframe src="https://attacker.example/embed/1"></iframe>',
].join(''),
infoText: '<strong>임관 권유</strong><svg onload="globalThis.__nationScoutXss=1"></svg>',
},
},
});
await db.general.create({
data: {
id: fixtureId,
userId,
name: '정화담당',
nationId: fixtureId,
turnTime: new Date('2026-07-31T00:00:00.000Z'),
},
});
redis = createRedisConnector(resolveRedisConfigFromEnv());
await redis.connect();
const store = new RedisAccessTokenStore(redis.client, profileName);
const payload: GameSessionTokenPayload = {
version: 1,
profile: profileName,
issuedAt: new Date(Date.now() - 1_000).toISOString(),
expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(),
sessionId: `nation-html-session-${process.pid}`,
user: {
id: userId,
username: 'nation-html-user',
displayName: 'Nation HTML User',
roles: ['user'],
createdAt: '2026-07-31T00:00:00.000Z',
},
sanctions: {},
};
const created = await store.create(payload);
if (!created) {
throw new Error('failed to seed nation HTML access token');
}
accessToken = created.accessToken;
server = await createGameApiServer();
baseUrl = await server.app.listen({ host: server.config.host, port: server.config.port });
}, 30_000);
afterAll(async () => {
await server?.app.close();
await db?.general.deleteMany({ where: { id: fixtureId } });
await db?.nation.deleteMany({ where: { id: fixtureId } });
await db?.worldState.deleteMany({ where: { id: fixtureId } });
await disconnectDb?.();
await redis?.disconnect();
if (uploadDir) {
await fs.rm(uploadDir, { recursive: true, force: true });
}
restoreEnv();
}, 30_000);
it('removes pre-existing executable nation notice markup before serialization', async () => {
const response = await fetch(`${baseUrl}/trpc/general.getFrontStatus`, {
headers: {
authorization: `Bearer ${accessToken}`,
},
});
const body = (await response.json()) as {
result?: {
data?: {
nationNotice?: string;
};
};
};
expect(response.status, JSON.stringify(body)).toBe(200);
expect(body.result?.data?.nationNotice).toBe(
'<p data-flip="horizontal" style="color:#00ffff">안전한 방침</p><img src="/image/icons/default.jpg" alt="default.jpg" /><iframe></iframe>'
);
});
it('removes executable stored recruitment markup from join configuration serialization', async () => {
const response = await fetch(`${baseUrl}/trpc/join.getConfig`, {
headers: {
authorization: `Bearer ${accessToken}`,
},
});
const body = (await response.json()) as {
result?: {
data?: {
nations?: Array<{
id: number;
scoutMessage: string | null;
}>;
};
};
};
expect(response.status, JSON.stringify(body)).toBe(200);
expect(body.result?.data?.nations?.find(({ id }) => id === fixtureId)?.scoutMessage).toBe(
'<strong>임관 권유</strong>'
);
});
});
+66
View File
@@ -32,6 +32,7 @@ type FixtureState = {
dieOnPrestartInputs?: Array<Record<string, unknown>>;
generalMeQueries?: number;
generalLogQueries?: number;
nationNoticeInput?: string;
settingMutations: Array<Record<string, unknown>>;
accessPages: string[];
};
@@ -170,6 +171,15 @@ const install = async (page: Page, state: FixtureState) => {
available: false,
availableAt: state.dieOnPrestartAvailableAt ?? null,
});
if (operation === 'general.getFrontStatus')
return response({
onlineUserCount: 1,
onlineNations: '【위】',
onlineGenerals: '검증장수',
nationNotice: state.nationNoticeInput ?? '',
lastExecuted: '2026-01-01T00:00:00.000Z',
latestVote: null,
});
if (operation === 'world.getState')
return response({
currentYear: 185,
@@ -190,6 +200,36 @@ const install = async (page: Page, state: FixtureState) => {
autorun_user: {},
},
});
if (operation === 'world.getMapLayout')
return response({ mapName: 'che', cityList: [], regionMap: {}, levelMap: {} });
if (operation === 'world.getMap')
return response({
year: 185,
month: 1,
startYear: 180,
cityList: [],
nationList: [],
myCity: 1,
myNation: 1,
});
if (operation === 'turns.getCommandTable') return response({ general: [], nation: [] });
if (operation === 'turns.reserved.getGeneral' || operation === 'turns.reserved.getNation')
return response({ turns: [], revision: 0 });
if (operation === 'messages.getRecent')
return response({
private: [],
national: [],
public: [],
diplomacy: [],
sequence: -1,
hasMore: { private: false, national: false, public: false, diplomacy: false },
latestRead: { private: 0, national: 0, public: 0, diplomacy: 0 },
canRespondDiplomacy: false,
});
if (operation === 'messages.getContacts') return response({ nation: [] });
if (operation === 'general.getRecentRecords') return response({ global: [], general: [], history: [] });
if (operation === 'board.getAccess') return response({ permission: 4, canMeeting: true, canSecret: true });
if (operation === 'tournament.getState') return response({ stage: 0 });
if (operation === 'public.getTraffic')
return response({
history: [
@@ -273,6 +313,32 @@ const install = async (page: Page, state: FixtureState) => {
});
};
test('정화된 국가 방침은 실행 가능한 속성 없이 Chromium에 표시된다', async ({ page }) => {
const state: FixtureState = {
permission: 'head',
myset: 0,
nationNoticeInput: [
'<p data-flip="horizontal" style="color:#00ffff">안전한 방침</p>',
'<img src="/image/icons/default.jpg" />',
'<a>위험 링크</a>',
].join(''),
settingMutations: [],
accessPages: [],
};
await install(page, state);
await page.goto('');
const notice = page.locator('.nation-notice-body');
await expect(notice).toContainText('안전한 방침');
await expect(notice.locator('[data-flip="horizontal"]')).toHaveCSS('color', 'rgb(0, 255, 255)');
await expect(notice.locator('script, svg, [onerror], [onload], [onclick]')).toHaveCount(0);
await expect(notice.locator('a', { hasText: '위험 링크' })).not.toHaveAttribute('href');
await expect
.poll(() => page.evaluate(() => (globalThis as typeof globalThis & { __nationXss?: number }).__nationXss))
.toBeUndefined();
});
test('접속량정보 keeps the legacy public 1016px chart geometry', async ({ page }) => {
const state: FixtureState = { permission: 'member', myset: 0, settingMutations: [], accessPages: [] };
await install(page, state);
+73 -10
View File
@@ -10,8 +10,19 @@ type FixtureState = {
failPersonnelLoad?: boolean;
rate: number;
appointedGeneralId?: number;
noticeMutationInput?: string;
scoutMutationInput?: string;
};
type TrpcRequestPayload = {
json?: Record<string, unknown>;
input?: { json?: Record<string, unknown> };
};
const purifiedNoticeResponse =
'<p data-flip="horizontal" style="color:#00ffff">서버 정화 방침</p><img src="/image/icons/default.jpg" alt="default.jpg" />';
const purifiedScoutResponse = '<strong>서버 정화 임관문</strong><a>위험 링크</a>';
const artifactRoot = process.env.OFFICE_PARITY_ARTIFACT_DIR ? resolve(process.env.OFFICE_PARITY_ARTIFACT_DIR) : null;
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
const imageRoots = [
@@ -190,7 +201,17 @@ const installFixture = async (page: Page, state: FixtureState) => {
);
await page.route('**/che/api/trpc/**', async (route) => {
const operations = operationName(route).split(',');
const results = operations.map((operation) => {
const rawRequestBody: unknown = route.request().postData() ? route.request().postDataJSON() : {};
const requestBody =
rawRequestBody && typeof rawRequestBody === 'object' ? (rawRequestBody as Record<string, unknown>) : {};
const results = operations.map((operation, operationIndex) => {
const rawPayload =
requestBody[String(operationIndex)] ?? (operations.length === 1 ? requestBody : undefined);
const payload =
rawPayload && typeof rawPayload === 'object' ? (rawPayload as TrpcRequestPayload) : undefined;
const jsonInput =
payload?.json ?? payload?.input?.json ?? (payload as Record<string, unknown> | undefined) ?? {};
if (operation === 'auth.status') return response({ ok: true });
if (operation === 'lobby.info') return response({ myGeneral: { id: 1, name: '조조' } });
if (operation === 'join.getConfig') return response({});
if (operation === 'nation.getPersonnelInfo') {
@@ -212,15 +233,15 @@ const installFixture = async (page: Page, state: FixtureState) => {
state.rate = 25;
return response({ ok: true });
}
if (
[
'nation.setNotice',
'nation.setScoutMsg',
'nation.setBill',
'nation.setSecretLimit',
'nation.setBlockScout',
].includes(operation)
)
if (operation === 'nation.setNotice') {
state.noticeMutationInput = typeof jsonInput.msg === 'string' ? jsonInput.msg : undefined;
return response({ ok: true, msg: purifiedNoticeResponse });
}
if (operation === 'nation.setScoutMsg') {
state.scoutMutationInput = typeof jsonInput.msg === 'string' ? jsonInput.msg : undefined;
return response({ ok: true, msg: purifiedScoutResponse });
}
if (['nation.setBill', 'nation.setSecretLimit', 'nation.setBlockScout'].includes(operation))
return response({ ok: true });
if (operation === 'nation.setBlockWar') return response({ availableCnt: 4 });
return errorResponse(operation, `Unhandled fixture operation: ${operation}`);
@@ -426,3 +447,45 @@ test('finance enforces edit permissions and preserves the old value across an AP
await expect(readOnly.locator('.policy-cell').getByRole('button', { name: '변경' })).toHaveCount(0);
await expect(readOnly.getByRole('checkbox', { name: '전쟁 금지' })).toBeDisabled();
});
test('finance adopts the server-purified notice and scout message before rendering the saved preview', async ({
page,
}) => {
const state: FixtureState = { role: 'head', rate: 20 };
await installFixture(page, state);
await gotoOffice(page, 'nation/finance');
const dirtyNotice =
'<script>globalThis.__nationNoticeXss=1</script><img src=x onerror="globalThis.__nationNoticeXss=2"><p data-flip="horizontal" style="color:#00ffff">원문</p>';
await page.getByRole('button', { name: '국가방침 수정' }).click();
await page.getByRole('textbox', { name: '국가 방침' }).fill(dirtyNotice);
await page.locator('#notice-form').getByRole('button', { name: '저장' }).click();
const noticePreview = page.locator('#notice-form .message-preview');
await expect(noticePreview).toContainText('서버 정화 방침');
expect(state.noticeMutationInput).toBe(dirtyNotice);
await expect(noticePreview.locator('[data-flip="horizontal"]')).toHaveCSS('color', 'rgb(0, 255, 255)');
await expect(noticePreview.locator('script, svg, [onerror], [onload], [onclick]')).toHaveCount(0);
await expect
.poll(() =>
page.evaluate(() => (globalThis as typeof globalThis & { __nationNoticeXss?: number }).__nationNoticeXss)
)
.toBeUndefined();
const dirtyScout =
'<svg onload="globalThis.__nationScoutXss=1"></svg><a href="javascript:alert(1)" onclick="globalThis.__nationScoutXss=2">원문</a>';
await page.getByRole('button', { name: '임관 권유문 수정' }).click();
await page.getByRole('textbox', { name: '임관 권유' }).fill(dirtyScout);
await page.locator('#scout-message-form').getByRole('button', { name: '저장' }).click();
const scoutPreview = page.locator('#scout-message-form .message-preview');
await expect(scoutPreview).toContainText('서버 정화 임관문');
expect(state.scoutMutationInput).toBe(dirtyScout);
await expect(scoutPreview.locator('a', { hasText: '위험 링크' })).not.toHaveAttribute('href');
await expect(scoutPreview.locator('script, svg, [onerror], [onload], [onclick]')).toHaveCount(0);
await expect
.poll(() =>
page.evaluate(() => (globalThis as typeof globalThis & { __nationScoutXss?: number }).__nationScoutXss)
)
.toBeUndefined();
});
@@ -141,8 +141,10 @@ const saveNationMsg = async () => {
if (!editable.value) return;
errorMessage.value = null;
try {
await trpc.nation.setNotice.mutate({ msg: nationMsg.value });
originalNationMsg.value = nationMsg.value;
const result = await trpc.nation.setNotice.mutate({ msg: nationMsg.value });
nationMsg.value = result.msg;
originalNationMsg.value = result.msg;
editor.value?.commands.setContent(result.msg || '');
editingNationMsg.value = false;
editor.value?.setEditable(false);
} catch (err) {
@@ -63,15 +63,21 @@ const resolveDiplomacyEnd = (term: number | null): string => {
const formatDiplomacyTerm = (term: number | null): string => (term ? `${term}개월` : '-');
const diplomacyInfo = (nation: NationEntry) => resolveDiplomacyInfo(nation.diplomacy.state);
const mutation = async (action: () => Promise<unknown>, message: string, rollback?: () => void) => {
const mutation = async <T,>(
action: () => Promise<T>,
message: string,
rollback?: () => void
): Promise<T | undefined> => {
error.value = null;
status.value = null;
try {
await action();
const result = await action();
status.value = message;
return result;
} catch (err) {
rollback?.();
error.value = resolveErrorMessage(err);
return undefined;
}
};
@@ -85,9 +91,13 @@ const rollbackNationMsg = () => {
editingNationMsg.value = false;
};
const saveNationMsg = async () => {
await mutation(() => trpc.nation.setNotice.mutate({ msg: nationMsgDraft.value }), '국가 방침을 변경했습니다.');
if (!error.value) {
nationMsg.value = nationMsgDraft.value;
const result = await mutation(
() => trpc.nation.setNotice.mutate({ msg: nationMsgDraft.value }),
'국가 방침을 변경했습니다.'
);
if (result) {
nationMsg.value = result.msg;
nationMsgDraft.value = result.msg;
editingNationMsg.value = false;
}
};
@@ -101,9 +111,13 @@ const rollbackScoutMsg = () => {
editingScoutMsg.value = false;
};
const saveScoutMsg = async () => {
await mutation(() => trpc.nation.setScoutMsg.mutate({ msg: scoutMsgDraft.value }), '임관 권유문을 변경했습니다.');
if (!error.value) {
scoutMsg.value = scoutMsgDraft.value;
const result = await mutation(
() => trpc.nation.setScoutMsg.mutate({ msg: scoutMsgDraft.value }),
'임관 권유문을 변경했습니다.'
);
if (result) {
scoutMsg.value = result.msg;
scoutMsgDraft.value = result.msg;
editingScoutMsg.value = false;
}
};
@@ -117,8 +117,10 @@ const saveScoutMsg = async () => {
if (!editable.value) return;
errorMessage.value = null;
try {
await trpc.nation.setScoutMsg.mutate({ msg: scoutMsg.value });
originalScoutMsg.value = scoutMsg.value;
const result = await trpc.nation.setScoutMsg.mutate({ msg: scoutMsg.value });
scoutMsg.value = result.msg;
originalScoutMsg.value = result.msg;
editor.value?.commands.setContent(result.msg || '');
editing.value = false;
editor.value?.setEditable(false);
} catch (err) {