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 -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);
};