fix: purify nation-authored HTML at server boundaries
This commit is contained in:
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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	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);
|
||||
});
|
||||
});
|
||||
@@ -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>'
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user