A motion design toolkit for coding agents.
JavaScript
Prevent script injection through sim configs and captions
whaley6f80380b9185
diff --git a/package.json b/package.jsonindex 3c523a7..ac6ad27 100644--- a/package.json+++ b/package.json@@ -16,6 +16,7 @@"cover": "remotion still ArticleCover out/article-cover.png","gif": "ffmpeg -loglevel error -y -i out/effort.mp4 -vf \"fps=12,scale=420:-1:flags=lanczos,hqdn3d=4:4:6:6,split[a][b];[a]palettegen=max_colors=64:stats_mode=diff[p];[b][p]paletteuse=dither=none:diff_mode=rectangle\" media/preview.gif","typecheck": "tsc",+ "test:sims": "node --test sims/kit/runtime.test.mjs","sims": "node sims/build.mjs","capture": "node sims/capture.mjs"},diff --git a/sims/README.md b/sims/README.mdindex 0975ee2..8ea8d41 100644--- a/sims/README.md+++ b/sims/README.md@@ -59,6 +59,18 @@ Other flags: `--config post.json` (merged over the sim's `DEFAULTS`),Every example has `watermark` in its `DEFAULTS`. Set it to your own handle,or to `''`, in the sim or in a `--config` file.+Full configs are trusted input: examples can include HTML in them. Use+`capture.mjs --config` or edit the sim's defaults; `?config=` in shared URLs+is ignored, including in capture mode. The simple URL options (`title`,+`accent`, `seed`, `theme`, `duration`, `nodirector`) still work.+Story captions treat `tag` and `text` as plain text, with `*word*` highlighting;+`kind` supports `hero` and `num` (other values fall back to `hero`).++Run the config and caption security tests with `npm run test:sims` (requires+the same Chromium installation or `$CHROMIUM` as capture). After updating+the kit, run `npm run sims` and replace any hosted HTML with the rebuilt+files from `sims/dist/`; existing copies do not update automatically.+## Making a new simCopy the example closest to what you want and change it. The contract:diff --git a/sims/kit/director.js b/sims/kit/director.jsindex aacf2d9..184314c 100644--- a/sims/kit/director.js+++ b/sims/kit/director.js@@ -1,4 +1,4 @@-import {clamp01, easeOutExpo, fmt, hash, smooth} from './util.js';+import {clamp01, easeOutExpo, esc, fmt, hash, smooth} from './util.js';/*** The director edits a sim to the music: hard cuts between wide and tight@@ -116,7 +116,7 @@ export function createDirector(app, cfg) {const b0 = before(beats, start + 0.02);const hold = s.hold ?? 8;const end = s.end ?? beats[Math.min(beats.length - 1, b0 + hold)] ?? start + hold * spb;- return {...s, i, start, end, b0};+ return {...s, kind: s.kind === 'num' ? 'num' : 'hero', i, start, end, b0};});// ---- DOM layers@@ -234,8 +234,8 @@ export function createDirector(app, cfg) {if (built !== cur.i) {built = cur.i;const words = (cur.text || '').split(/\s+/).filter(Boolean);- storyEl.innerHTML = `<div class="cap ${cur.kind || 'hero'}">- ${cur.tag ? `<div class="cap-tag">${cur.tag}</div>` : ''}+ storyEl.innerHTML = `<div class="cap ${cur.kind}">+ ${cur.tag ? `<div class="cap-tag">${esc(cur.tag)}</div>` : ''}<div class="cap-main">${cur.kind === 'num'? `<span class="w"><span class="n"></span></span>`@@ -249,7 +249,7 @@ export function createDirector(app, cfg) {if (open) on = true;const hl = on;if (close) on = false;- return `<span class="w${hl ? ' hl' : ''}">${w.replace(/^\*|\*$/g, '')}</span>`;+ return `<span class="w${hl ? ' hl' : ''}">${esc(w.replace(/^\*|\*$/g, ''))}</span>`;}).join(' ');})()diff --git a/sims/kit/runtime.js b/sims/kit/runtime.jsindex 82b6044..15318a6 100644--- a/sims/kit/runtime.js+++ b/sims/kit/runtime.js@@ -27,24 +27,16 @@ export const BASE = {beats: null,};-const fromBase64 = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));-/*** Config sources, later wins: BASE, the sim's defaults, window.__SIM_CONFIG- * (injected by the capture script), ?config=<base64 json>, and a few plain- * query params (?title= ?accent= ?seed= ?theme= ?duration=).+ * (injected by the capture script), and a few plain query params+ * (?title= ?accent= ?seed= ?theme= ?duration=).+ * Full configs may contain trusted HTML; never accept them from a URL.*/export function loadConfig(defaults) {let cfg = merge(BASE, defaults);if (window.__SIM_CONFIG) cfg = merge(cfg, window.__SIM_CONFIG);const q = new URLSearchParams(location.search);- if (q.get('config')) {- try {- cfg = merge(cfg, JSON.parse(fromBase64(q.get('config'))));- } catch (e) {- console.warn('bad ?config', e);- }- }if (q.get('title')) cfg = merge(cfg, {hud: {title: q.get('title')}});if (q.get('accent')) cfg.accent = '#' + q.get('accent').replace('#', '');if (q.get('seed')) cfg.seed = Number(q.get('seed'));diff --git a/sims/kit/runtime.test.mjs b/sims/kit/runtime.test.mjsnew file mode 100644index 0000000..733f07f--- /dev/null+++ b/sims/kit/runtime.test.mjs@@ -0,0 +1,116 @@+import assert from 'node:assert/strict';+import {after, before, test} from 'node:test';+import {existsSync} from 'node:fs';+import {fileURLToPath} from 'node:url';+import {build} from 'esbuild';+import {chromium} from 'playwright';++let browser;+let html;++before(async () => {+ const result = await build({+ stdin: {+ contents: `import {runSim} from './runtime.js';+ runSim({hud: {enabled: false}}, () => ({render() {}}));`,+ resolveDir: fileURLToPath(new URL('.', import.meta.url)),+ },+ bundle: true,+ write: false,+ format: 'iife',+ });+ html = `<div id="app"></div><script>${result.outputFiles[0].text}</script>`;+ browser = await chromium.launch({+ executablePath: process.env.CHROMIUM || (existsSync('/usr/bin/chromium') ? '/usr/bin/chromium' : undefined),+ });+});++after(async () => browser?.close());++async function openSim(t, config = {}, query = '', capture = true) {+ const page = await browser.newPage();+ t.after(() => page.close());+ const errors = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.route('http://sim.test/**', (route) =>+ route.request().isNavigationRequest()+ ? route.fulfill({contentType: 'text/html', body: html})+ : route.abort(),+ );+ await page.addInitScript(({cfg, capture}) => {+ window.__CAPTURE = capture;+ window.__SIM_CONFIG = cfg;+ }, {cfg: config, capture});+ await page.goto(`http://sim.test/${query}`);+ await page.waitForFunction(() => window.SIM?.ready);+ assert.deepEqual(errors, []);+ return page;+}++const attack = '<img src=x onerror="window.__captionXss=true">';++test('URL config cannot override trusted config or supply HTML to sims', async (t) => {+ const queryConfig = {+ story: [{at: 0, end: 20, tag: attack}],+ director: {enabled: true},+ pages: [{html: attack}],+ title: attack,+ watermark: attack,+ };+ const encoded = Buffer.from(JSON.stringify(queryConfig)).toString('base64url');+ for (const mode of ['', 'capture&']) {+ const page = await openSim(t, {watermark: 'trusted'}, `?${mode}config=${encoded}`, false);+ assert.deepEqual(await page.evaluate(() => ({+ story: window.SIM.cfg.story,+ watermark: window.SIM.cfg.watermark,+ hasPages: 'pages' in window.SIM.cfg,+ hasTitle: 'title' in window.SIM.cfg,+ })), {story: [], watermark: 'trusted', hasPages: false, hasTitle: false});+ }+});++test('simple URL options still work', async (t) => {+ const page = await openSim(t, {}, '?title=Demo&accent=abcdef&seed=12&theme=light&duration=10&nodirector');+ assert.deepEqual(await page.evaluate(() => {+ const cfg = window.SIM.cfg;+ return [cfg.hud.title, cfg.accent, cfg.seed, cfg.theme, cfg.duration, cfg.director.enabled];+ }), ['Demo', '#abcdef', 12, 'light', 10, false]);+});++for (const field of ['tag', 'text']) {+ test(`story ${field} renders markup literally`, async (t) => {+ const value = `Hello ${attack} & < > " ' < Привет`;+ const page = await openSim(t, {story: [{at: 0, end: 20, [field]: value}]});+ const selector = field === 'tag' ? '.cap-tag' : '.cap-main';+ assert.equal((await page.locator(selector).textContent()).trim(), value);+ assert.equal(await page.locator('.dir-story img, .dir-story script, .dir-story [onerror]').count(), 0);+ assert.equal(await page.evaluate(() => window.__captionXss), undefined);+ });+}++test('invalid caption kinds fall back to hero without adding attributes or elements', async (t) => {+ for (const kind of [`hero">${attack}<div class="`, 'hero extra', 'custom', null]) {+ const page = await openSim(t, {story: [{at: 0, end: 20, kind, text: 'Hello'}]});+ assert.equal(await page.locator('.cap').getAttribute('class'), 'cap hero');+ assert.equal(await page.locator('.dir-story img, .dir-story [onerror]').count(), 0);+ assert.equal(await page.evaluate(() => window.__captionXss), undefined);+ }+});++test('hero captions keep multi-word highlighting and plain text', async (t) => {+ const page = await openSim(t, {story: [{at: 0, end: 20, kind: 'hero', text: 'Hello *bright & bold* world'}]});+ assert.deepEqual(await page.locator('.w.hl').allTextContents(), ['bright', '&', 'bold']);+ assert.equal((await page.locator('.cap-main').textContent()).trim(), 'Hello bright & bold world');+});++test('numeric captions and subtitles still render as text', async (t) => {+ const page = await openSim(t, {story: [{+ at: 0, end: 20, kind: 'num', from: 0, to: 42, roll: 1,+ prefix: attack, suffix: ' & done', sub: attack,+ }]});+ await page.evaluate(() => window.SIM.render(10));+ assert.equal(await page.locator('.cap').getAttribute('class'), 'cap num');+ assert.equal(await page.locator('.n').textContent(), `${attack}42 & done`);+ assert.equal(await page.locator('.cap-sub').textContent(), attack);+ assert.equal(await page.locator('.dir-story img').count(), 0);+});diff --git a/sims/kit/util.js b/sims/kit/util.jsindex 1dbf9d0..90be113 100644--- a/sims/kit/util.js+++ b/sims/kit/util.js@@ -67,6 +67,10 @@ export const fmt = (n, d = 0) =>Number(n).toLocaleString('en-US', {minimumFractionDigits: d, maximumFractionDigits: d});export const pad = (n, w) => String(Math.max(0, Math.floor(n))).padStart(w, '0');+/** Escape plain text before interpolating it into HTML. */+export const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''})[c]);+/** Deep merge plain objects; arrays and scalars from `b` replace `a`. */export const merge = (a, b) => {if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b;