fix: purify nation-authored HTML at server boundaries
This commit is contained in:
@@ -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