commit f02df937d0bb027d70e0c9fb85088f327d7d258c
parent 226d1b3295f4b705106444314c5ac061f7d66940
Author: triesap <tyson@radroots.org>
Date: Mon, 5 Oct 2026 00:51:52 +0000
web: enforce production imports and executable string boundaries
- Resolve imports and reject native, private and test dependencies.
- Validate URL sinks and admit bounded timer and model operations.
- Add hostile and compilable positive boundary regressions.
- Preserve native graphs, locks, compatibility and the public Lib pin.
Diffstat:
4 files changed, 3809 insertions(+), 144 deletions(-)
diff --git a/web/src/lib/navigation-url.ts b/web/src/lib/navigation-url.ts
@@ -0,0 +1,71 @@
+const maximumBytes = 8192;
+const sentinel = 'https://navigation.invalid';
+
+function text(value: unknown): value is string {
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length > maximumBytes ||
+ !value.isWellFormed() ||
+ /\s/u.test(value)
+ )
+ return false;
+ if (new TextEncoder().encode(value).length > maximumBytes) return false;
+ for (const character of value) {
+ const code = character.charCodeAt(0);
+ if (code <= 32 || (code >= 127 && code <= 159) || character === '\\')
+ return false;
+ }
+ try {
+ const decoded = decodeURIComponent(value);
+ for (const character of decoded) {
+ const code = character.charCodeAt(0);
+ if (code < 32 || (code >= 127 && code <= 159) || character === '\\')
+ return false;
+ }
+ } catch {
+ return false;
+ }
+ return true;
+}
+
+export function internalHref(value: unknown): string | undefined {
+ if (!text(value)) return undefined;
+ if (!(
+ (value[0] === '/' && value[1] !== '/') ||
+ value[0] === '?' ||
+ value[0] === '#'
+ ))
+ return undefined;
+ try {
+ const url = new URL(value, sentinel);
+ if (url.origin !== sentinel || url.username || url.password)
+ return undefined;
+ return value;
+ } catch {
+ return undefined;
+ }
+}
+
+export function navigationHref(value: unknown): string | undefined {
+ if (!text(value)) return undefined;
+ const internal = internalHref(value);
+ if (internal !== undefined) return internal;
+ if (!/^(https:\/\/|mailto:|tel:)/i.test(value)) return undefined;
+ if (/^https:/i.test(value) && !/^https:\/\/[^/?#]/i.test(value))
+ return undefined;
+ try {
+ const url = new URL(value, sentinel);
+ if (url.username || url.password || /^https:\/\/[^/?#]*@/i.test(value))
+ return undefined;
+ if (url.protocol === 'https:' && !url.hostname) return undefined;
+ if (
+ (url.protocol === 'mailto:' || url.protocol === 'tel:') &&
+ (!url.pathname || url.host !== '')
+ )
+ return undefined;
+ return value;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs
@@ -0,0 +1,1652 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import {
+ copyFile,
+ link,
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ symlink,
+ writeFile
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test } from 'node:test';
+
+const root = fileURLToPath(new URL('../../', import.meta.url));
+/** @typedef {{directory: string, put: (name: string, content: string | Uint8Array) => Promise<void>, execute: (args?: string[]) => import('node:child_process').SpawnSyncReturns<string>, pkg: Record<string, unknown>}} Fixture */
+/** @param {(context: Fixture) => Promise<void>} run */
+async function fixture(run) {
+ const directory = await realpath(
+ await mkdtemp(path.join(tmpdir(), 'hcr010 source '))
+ );
+ /** @type {Fixture['put']} */
+ const put = async (name, content) => {
+ await mkdir(path.dirname(path.join(directory, name)), { recursive: true });
+ await writeFile(path.join(directory, name), content);
+ };
+ try {
+ await mkdir(path.join(directory, 'tools'));
+ await mkdir(path.join(directory, 'src/routes'), { recursive: true });
+ for (const name of [
+ 'package.json',
+ 'tsconfig.json',
+ 'vite.config.ts',
+ 'tools/check-source.mjs',
+ 'tools/source-boundaries.mjs'
+ ])
+ await copyFile(path.join(root, name), path.join(directory, name));
+ await symlink(
+ path.join(root, 'node_modules'),
+ path.join(directory, 'node_modules')
+ );
+ await put(
+ 'src/lib/navigation-url.ts',
+ await readFile(path.join(root, 'src/lib/navigation-url.ts'), 'utf8')
+ );
+ await put('src/routes/+page.ts', 'export const value = 1;');
+ const execute = (args = ['tools/check-source.mjs']) => {
+ const result = spawnSync(process.execPath, args, {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 8000
+ });
+ assert.equal(result.error, undefined);
+ return result;
+ };
+ const pkg = JSON.parse(
+ await readFile(path.join(directory, 'package.json'), 'utf8')
+ );
+ await run({ directory, put, execute, pkg });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+}
+/** @param {string} directory */
+async function confineSvelte(directory) {
+ await rm(path.join(directory, 'node_modules'));
+ await mkdir(path.join(directory, 'node_modules'));
+ await symlink(
+ path.join(root, 'node_modules/typescript'),
+ path.join(directory, 'node_modules/typescript')
+ );
+ const { cp } = await import('node:fs/promises');
+ await cp(
+ await realpath(path.join(root, 'node_modules/svelte')),
+ path.join(directory, 'node_modules/svelte'),
+ { recursive: true }
+ );
+ const svelteRoot = await realpath(path.join(root, 'node_modules/svelte'));
+ const sveltePackage = JSON.parse(
+ await readFile(path.join(svelteRoot, 'package.json'), 'utf8')
+ );
+ for (const dependency of Object.keys(sveltePackage.dependencies)) {
+ const destination = path.join(directory, 'node_modules', dependency);
+ await mkdir(path.dirname(destination), { recursive: true });
+ await symlink(path.join(path.dirname(svelteRoot), dependency), destination);
+ }
+}
+
+/** @param {import('node:child_process').SpawnSyncReturns<string>} result @param {RegExp} diagnostic */
+const reject = (result, diagnostic) => {
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(result.stderr, diagnostic);
+};
+
+for (const [name, content, diagnostic] of [
+ [
+ 'native extension import',
+ "import '../../../core/Cargo.toml';",
+ /forbidden production import/
+ ],
+ [
+ 'native dynamic import',
+ "void import('../../../core/native.js');",
+ /forbidden production import/
+ ],
+ [
+ 'test reexport',
+ "export * from '../../tests/e2e/harness/provider';",
+ /forbidden production import/
+ ],
+ [
+ 'dynamic test signer',
+ "void import('../../tests/signer');",
+ /forbidden production import/
+ ],
+ [
+ 'NDK dynamic client',
+ "void import('@nostr-dev-kit/ndk');",
+ /forbidden production import/
+ ],
+ [
+ 'nostr-tools dynamic client',
+ "void import('nostr-tools/pool');",
+ /forbidden production import/
+ ],
+ [
+ 'computed import',
+ "const name = 'nostr-tools'; void import(name);",
+ /computed production imports/
+ ],
+ [
+ 'template computed import',
+ 'const name = "client"; void import(`./${name}`);',
+ /computed production imports/
+ ],
+ [
+ 'glob import',
+ "const files = import.meta.glob('./*.ts');",
+ /computed production imports/
+ ],
+ [
+ 'require loader',
+ "const client = require('nostr-tools');",
+ /loader\/provider\/credential/
+ ],
+ [
+ 'raw socket',
+ "const socket = new WebSocket('wss://example.invalid');",
+ /loader\/provider\/credential/
+ ],
+ [
+ 'indirect socket',
+ "const socket = new globalThis['WebSocket']('wss://example.invalid');",
+ /indirect production loaders/
+ ],
+ [
+ 'secret generation',
+ 'export const key = generateSecretKey();',
+ /credential API/
+ ],
+ [
+ 'copied test marker',
+ "export const marker = 'HC_TEST_ONLY_PROVIDER';",
+ /test provider code/
+ ],
+ [
+ 'unknown package',
+ "import 'some-unresolved-package';",
+ /forbidden production import/
+ ],
+ ['unknown local', "import './missing';", /unresolved production import/],
+ ['query loader', "import './safe.ts?raw';", /unsafe production import/],
+ [
+ 'escaped POSIX filename',
+ "import '..\\\\tests\\\\signer';",
+ /unsafe production import/
+ ],
+ [
+ 'Applesauce outside adapter',
+ "import 'applesauce-core';",
+ /Applesauce imports/
+ ],
+ [
+ 'removed Kit3 alias',
+ "import '$lib/signer';",
+ /forbidden production import/
+ ],
+ [
+ 'source reference',
+ '/// <reference path="../../tests/signer.ts" />\nexport {};',
+ /reference directives/
+ ]
+])
+ test(`rejects ${name}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ if (typeof content !== 'string' || !(diagnostic instanceof RegExp))
+ throw new Error('Invalid mutation case');
+ await put('src/routes/+page.ts', content);
+ reject(execute(), diagnostic);
+ });
+ });
+
+test('follows extension and directory-index reexports to test provider', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', "export * from '../lib/bridge.js';");
+ await put('src/lib/bridge.ts', "export * from './client';");
+ await put(
+ 'src/lib/client/index.ts',
+ "export * from '../../../tests/e2e/harness/provider';"
+ );
+ reject(execute(), /forbidden production import/);
+ });
+});
+test('local cycles, emitted extensions and test-only harnesses pass', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', "export * from '../lib/bridge.js';");
+ await put(
+ 'src/lib/bridge.ts',
+ "export * from './client'; export const bridge = 1;"
+ );
+ await put('src/lib/client/index.ts', "export { bridge } from '../bridge';");
+ await put(
+ 'tests/harness/provider.ts',
+ "export const testSigner = new WebSocket('ws://127.0.0.1');"
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
+for (const kind of ['package', 'conditional package', 'Vite', 'TypeScript'])
+ test(`rejects test reachability through ${kind} aliases`, async () => {
+ await fixture(async ({ directory, put, execute, pkg }) => {
+ await put('src/routes/+page.ts', "export * from '#bridge';");
+ if (kind.includes('package')) {
+ pkg.imports = {
+ '#bridge':
+ kind === 'package'
+ ? './tests/signer.ts'
+ : { browser: './tests/signer.ts', default: './src/lib/safe.ts' }
+ };
+ await put('package.json', JSON.stringify(pkg));
+ await put('src/lib/safe.ts', 'export const safe = 1;');
+ } else if (kind === 'Vite') {
+ const vite = await readFile(
+ path.join(directory, 'vite.config.ts'),
+ 'utf8'
+ );
+ await put(
+ 'vite.config.ts',
+ vite.replace(
+ 'plugins: [',
+ "resolve: { alias: { '#bridge': './tests/signer.ts' } }, plugins: ["
+ )
+ );
+ } else
+ await put(
+ 'tsconfig.json',
+ JSON.stringify({
+ extends: '$app/tsconfig',
+ compilerOptions: {
+ strict: true,
+ paths: { '#bridge': ['./tests/signer.ts'] }
+ }
+ })
+ );
+ reject(execute(), /forbidden production import/);
+ });
+ });
+test('valid Kit3 package wildcard aliases resolve local index modules', async () => {
+ await fixture(async ({ put, execute, pkg }) => {
+ pkg.imports = { '#modules/*': './src/lib/*' };
+ await put('package.json', JSON.stringify(pkg));
+ await put('src/routes/+page.ts', "export * from '#modules/client';");
+ await put('src/lib/client/index.ts', 'export const client = 1;');
+ assert.equal(execute().status, 0);
+ });
+});
+test('npm package alias cannot conceal forbidden dependency identity', async () => {
+ await fixture(async ({ put, execute, pkg }) => {
+ pkg.dependencies = { innocent: 'npm:nostr-tools@2.0.0' };
+ await put('package.json', JSON.stringify(pkg));
+ await put('src/routes/+page.ts', "export * from 'innocent/pool';");
+ reject(execute(), /forbidden production import/);
+ });
+});
+for (const [name, content, diagnostic] of [
+ [
+ 'component.svelte',
+ '<p>bad</p><style>p { color: red }</style>',
+ /component CSS/
+ ],
+ ['inline.svelte', '<p style="color: red">bad</p>', /inline styles/],
+ ['directive.svelte', '<p style:color="red">bad</p>', /inline styles/],
+ ['extra.css', 'p { color: red }', /handwritten CSS/],
+ [
+ 'app.html',
+ '<body style="color: red">%sveltekit.body%</body>',
+ /inline styles/
+ ]
+])
+ test(`rejects ${name} style violation`, async () => {
+ await fixture(async ({ put, execute }) => {
+ if (typeof content !== 'string' || !(diagnostic instanceof RegExp))
+ throw new Error('Invalid mutation case');
+ await put(`src/${name}`, content);
+ reject(execute(), diagnostic);
+ });
+ });
+test('two CSS paths must be imported once in order by root layout', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/theme.css', ':root { --color: black }');
+ await put('src/app.css', 'p { color: var(--color) }');
+ await put(
+ 'src/routes/+layout.svelte',
+ '<script>import "../theme.css"; import "../app.css";</script><p>good</p>'
+ );
+ assert.equal(execute().status, 0);
+ await put(
+ 'src/routes/+layout.svelte',
+ '<script>import "../app.css"; import "../theme.css";</script><p>bad</p>'
+ );
+ reject(execute(), /exactly once/);
+ });
+});
+for (const kind of ['symlink', 'hardlink', 'invalid UTF8', 'oversize', 'FIFO'])
+ test(`rejects ${kind} before parsers`, async () => {
+ await fixture(async ({ directory, put, execute }) => {
+ const target = path.join(directory, 'src/unsafe.ts');
+ if (kind === 'symlink')
+ await symlink(path.join(root, 'tests/e2e/harness/provider.ts'), target);
+ else if (kind === 'hardlink')
+ await link(path.join(directory, 'src/routes/+page.ts'), target);
+ else if (kind === 'invalid UTF8')
+ await put('src/unsafe.ts', Buffer.from([0xff]));
+ else if (kind === 'oversize')
+ await put('src/unsafe.ts', Buffer.alloc(8 * 1024 * 1024 + 1, 32));
+ else assert.equal(spawnSync('mkfifo', [target]).status, 0);
+ reject(execute(), /symlinks|nonregular|Unsafe source|encoded data/);
+ });
+ });
+for (const script of ['check', 'lint', 'build', 'test:unit', 'dev'])
+ test(`actual ${script} stops on unsafe production edge`, async () => {
+ await fixture(async ({ directory, put }) => {
+ await put('src/routes/+page.ts', "void import('nostr-tools');");
+ const result = spawnSync('corepack', ['pnpm', 'run', script], {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 8000
+ });
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(result.stderr, /forbidden production import nostr-tools/);
+ assert.doesNotMatch(
+ result.stdout,
+ /svelte-check found|vite v.*building|RUN\s+v/
+ );
+ });
+ });
+
+test('Svelte template expressions cannot dynamically load forbidden clients', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ '<button onclick={() => import("nostr-tools")}>bad</button>'
+ );
+ reject(execute(), /forbidden production import/);
+ });
+});
+test('app.html inline executable scripts cannot bypass source graph', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/app.html',
+ '<script type="module">import "nostr-tools";</script>'
+ );
+ reject(execute(), /external scripts/);
+ });
+});
+for (const css of [
+ '@import "../../tests/styles.css";',
+ 'p { background: url(../../core/native) }',
+ '@\\69mport "../../tests/styles.css";',
+ 'p { background: u/**/rl(../../tests/data) }'
+])
+ test(`rejects CSS loader ${css}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/theme.css', css);
+ reject(execute(), /CSS import\/url loading/);
+ });
+ });
+test('JS style assignment cannot bypass two CSS files', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', 'document.body.style.color = "red";');
+ reject(execute(), /JS-generated inline styles/);
+ });
+});
+test('configuration execution and alternate configs fail closed', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('vite.config.js', 'export default {}');
+ reject(execute(), /competing source configuration/);
+ });
+});
+test('actual pinned Svelte exports and Kit3 framework modules pass in confined fixture', async () => {
+ await fixture(async ({ directory, put, execute }) => {
+ await confineSvelte(directory);
+ await put(
+ 'src/routes/+page.ts',
+ 'import { writable } from "svelte/store"; export { writable }; export { goto } from "$app/navigation";'
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ await put('src/routes/+page.ts', 'import "svelte/nonexistent-export";');
+ reject(execute(), /unresolved production import/);
+ });
+});
+
+test('type imports and Vite URL references cannot hide test reachability', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ 'export type Client = typeof import("../../tests/signer");'
+ );
+ reject(execute(), /forbidden production import/);
+ await put(
+ 'src/routes/+page.ts',
+ 'export const client = new URL("../../tests/signer", import.meta.url);'
+ );
+ reject(execute(), /forbidden production import/);
+ });
+});
+test('production package imports exclude compiler and server tooling', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ 'import "svelte/compiler"; import "@sveltejs/kit/node";'
+ );
+ reject(execute(), /forbidden production import/);
+ });
+});
+
+test('npm aliases cannot hide compiler/server subpaths', async () => {
+ await fixture(async ({ put, execute, pkg }) => {
+ pkg.dependencies = {
+ view: 'npm:svelte@5.57.1',
+ framework: 'npm:@sveltejs/kit@3.0.0'
+ };
+ await put('package.json', JSON.stringify(pkg));
+ await put(
+ 'src/routes/+page.ts',
+ 'import "view/compiler"; import "framework/node";'
+ );
+ reject(execute(), /forbidden production import view\/compiler/);
+ assert.match(
+ execute().stderr,
+ /forbidden production import framework\/node/
+ );
+ });
+});
+
+for (const [name, markup] of [
+ [
+ 'nested external script',
+ '<svelte:head><script src="/tests/provider.js"></script></svelte:head>'
+ ],
+ [
+ 'nested inline script',
+ '<svelte:head><script>import("nostr-tools")</script></svelte:head>'
+ ],
+ [
+ 'nested module script',
+ '<div><script type="module">import "nostr-tools"</script></div>'
+ ],
+ [
+ 'nested style',
+ '<svelte:head><style>p { color: red }</style></svelte:head>'
+ ],
+ [
+ 'nested CSS import',
+ '<div><style>@import "/tests/style.css";</style></div>'
+ ],
+ [
+ 'stylesheet link',
+ '<svelte:head><link rel="stylesheet" href="/native.css" /></svelte:head>'
+ ],
+ [
+ 'alternate stylesheet tokens',
+ '<link rel="alternate stylesheet" href="/native.css" />'
+ ],
+ [
+ 'entity stylesheet token',
+ '<link rel="stylesheet" href="/native.css" />'
+ ],
+ [
+ 'modulepreload link',
+ '<link rel="modulepreload" href="/tests/provider.js" />'
+ ],
+ [
+ 'script preload',
+ '<link rel="preload" as="script" href="/tests/provider.js" />'
+ ],
+ ['computed link relation', '<link rel={relation} href="/favicon.ico" />'],
+ ['computed resource href', '<link rel="icon" href={resource} />'],
+ [
+ 'computed resource type',
+ '<link rel="icon" type={resourceType} href="/favicon.ico" />'
+ ],
+ ['spread link loader', '<link {...attributes} />'],
+ ['spread style/event attributes', '<div {...attributes}>content</div>'],
+ [
+ 'computed element tag',
+ '<svelte:element this={tag} src="/tests/provider.js" />'
+ ],
+ [
+ 'static resource element tag',
+ '<svelte:element this="script" src="/tests/provider.js" />'
+ ],
+ ['frame document', '<iframe src="/tests/provider.html"></iframe>'],
+ [
+ 'frame srcdoc',
+ '<iframe srcdoc="<script>import(\'nostr-tools\')</script>"></iframe>'
+ ],
+ ['object resource', '<object data="/tests/provider.html"></object>'],
+ ['embed resource', '<embed src="/tests/provider.html" />'],
+ ['raw HTML injection', '<div>{@html markup}</div>'],
+ [
+ 'executable link URL',
+ '<a href="java	script:import(\'nostr-tools\')">bad</a>'
+ ],
+ [
+ 'remote favicon resource',
+ '<link rel="icon" href="https://foreign.invalid/favicon.ico" />'
+ ]
+])
+ test(`markup guard rejects ${name}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.svelte', markup);
+ const result = execute();
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(result.stderr, /markup|favicon resources/);
+ });
+ });
+
+for (const markup of [
+ '<html><head><script src="/tests/provider.js"></script></head></html>',
+ '<html><head><script type="module">import "nostr-tools"</script></head></html>',
+ '<html><head><style>p { color: red }</style></head></html>',
+ '<html><head><link rel="stylesheet" href="/tests/style.css" /></head></html>',
+ '<html><head><link rel="modulepreload" href="/tests/provider.js" /></head></html>',
+ '<HTML><HEAD><SCRIPT src="/tests/provider.js"></SCRIPT></HEAD></HTML>',
+ '<HTML><HEAD><LINK REL="stylesheet" HREF="/tests/style.css" /></HEAD></HTML>',
+ '<html><body><iframe srcdoc="<script>import(\'nostr-tools\')</script>"></iframe></body></html>',
+ '<html><body onload="import(\'nostr-tools\')"></body></html>',
+ '<html><head><link rel={relation} href="/favicon.ico" /></head></html>'
+])
+ test(`HTML template rejects active resource ${markup}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/app.html', markup);
+ reject(execute(), /markup/);
+ });
+ });
+
+test('legitimate shell modules, metadata and owned favicon links pass', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ '<script lang="ts">const title: string = "HarvestCircle";</script><svelte:head><title>{title}</title><meta name="description" content="Public food listings" /><link rel="icon" href="/favicon.ico" /></svelte:head><svelte:element this="main"><p>{title}</p></svelte:element>'
+ );
+ await put(
+ 'src/app.html',
+ '<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><link rel="icon" href="%sveltekit.assets%/favicon.ico" />%sveltekit.head%</head><body><div>%sveltekit.body%</div></body></html>'
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
+
+for (const script of ['check', 'lint', 'build', 'test:unit', 'dev'])
+ test(`actual ${script} stops on nested markup loader`, async () => {
+ await fixture(async ({ directory, put }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ '<svelte:head><script src="/tests/provider.js"></script></svelte:head>'
+ );
+ const result = spawnSync('corepack', ['pnpm', 'run', script], {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 8000
+ });
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(result.stderr, /raw markup scripts/);
+ assert.doesNotMatch(
+ result.stdout,
+ /svelte-check found|vite v.*building|RUN\s+v/
+ );
+ });
+ });
+
+for (const source of [
+ 'const script = document.createElement("script");',
+ 'const stylesheet = document.createElement("link");',
+ 'const tag = "script"; const script = document.createElement(tag);',
+ 'const script = document.createElementNS("http://www.w3.org/2000/svg", "script");',
+ 'document.body.innerHTML = "<script src=/tests/provider.js></script>";',
+ 'document.body.insertAdjacentHTML("beforeend", "<style>body{color:red}</style>");',
+ 'document.body["outerHTML"] = "<iframe srcdoc=unsafe></iframe>";',
+ 'document.write("<script src=/tests/provider.js></script>");'
+])
+ test(`JS cannot construct raw resource markup: ${source}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ reject(execute(), /markup/);
+ });
+ });
+
+test('supported direct UI focus remains allowed', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ 'export function focusLabel() { document.getElementById("label")?.focus(); }'
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
+
+for (const source of [
+ '/** @type {import("../../tests/signer").Signer} */\nexport const signer = {};',
+ '/** @import { Signer } from "../../tests/signer" */\nexport const signer = {};'
+])
+ test(`JSDoc type edges cannot reach test artifacts: ${source}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.js', source);
+ reject(execute(), /forbidden production import/);
+ });
+ });
+test('Svelte const declarations cannot hide client imports', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ '{#if true}{@const client = import("nostr-tools")}<p>{client}</p>{/if}'
+ );
+ reject(execute(), /forbidden production import/);
+ });
+});
+for (const source of [
+ 'const script = document["createElement"]("script");',
+ 'const create = document.createElement; const script = create("script");',
+ 'const script = document.createElement.call(document, "script");',
+ 'const method = "createElement"; const script = document[method]("script");'
+])
+ test(`indirect DOM constructors cannot load client markup: ${source}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ reject(execute(), /markup/);
+ });
+ });
+
+const resourceHandle =
+ 'const link = document.querySelector<HTMLLinkElement>("link[rel=icon]"); if (!link) throw new Error("missing");';
+for (const mutation of [
+ 'link.rel = "stylesheet"; link.href = "https://example.invalid/extra.css";',
+ 'link["rel"] = "stylesheet"; link["href"] = "/extra.css";',
+ 'const field = "href"; link[field] = "/tests/provider.js";',
+ 'link.setAttribute("rel", "stylesheet"); link.setAttribute("href", "/extra.css");',
+ 'link.setAttributeNS(null, "href", "/extra.css");',
+ 'link.toggleAttribute("rel", true);',
+ 'link.relList.add("stylesheet");',
+ 'const alias = link; alias.href = "../../../core/native";',
+ 'const setter = link.setAttribute; setter.call(link, "href", "/extra.css");',
+ 'link.setAttribute.bind(link)("href", "/extra.css");',
+ 'Object.assign(link, { rel: "stylesheet", href: "/extra.css" });',
+ 'Object.defineProperty(link, "href", { value: "/extra.css" });',
+ 'Object.defineProperties(link, { href: { value: "/extra.css" } });',
+ 'Reflect.set(link, "href", "/extra.css");',
+ 'Reflect.defineProperty(link, "href", { value: "/extra.css" });',
+ 'const patch = Object.assign; patch(link, { href: "/extra.css" });',
+ 'const attribute = link.getAttributeNode("href"); if(attribute) attribute.value = "/extra.css";',
+ 'const attribute = document.createAttribute("href"); attribute.value = "/extra.css"; link.setAttributeNode(attribute);',
+ 'link.attributes.setNamedItem(document.createAttribute("href"));',
+ 'link.sheet?.replaceSync("@import /tests/style.css");',
+ 'delete link.rel;',
+ '[link.href] = ["/extra.css"];'
+])
+ test(`opaque resource mutations fail closed: ${mutation}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', resourceHandle + mutation);
+ reject(execute(), /DOM|mutation|reflection|model/);
+ });
+ });
+
+for (const source of [
+ 'export function rewrite(opaque: unknown) { (opaque as { href: string }).href = "/tests/provider.js"; }',
+ 'const model = { href: "/safe" }; function rewrite(model: { href: string }) { model.href = "/tests/provider.js"; }',
+ 'const model = { href: "/safe" }; const shadow = (model: { href: string }) => Object.assign(model, { href: "/extra.css" });',
+ 'const reflect = Reflect; reflect.set(window.document, "adoptedStyleSheets", []);',
+ 'const { document: dom } = window; const link = dom.querySelector("link"); link.href = "/extra.css";',
+ 'const selector = document.querySelector; const link = selector("link"); link.href = "/extra.css";',
+ 'const capability = (event: Event) => { const link = event.currentTarget; Object.assign(link, { rel: "stylesheet" }); };',
+ 'const data = { link: { href: "/safe" } }; data.link = (window as unknown as { evil: { href: string } }).evil;',
+ 'const prototype = ({}).constructor.constructor; prototype("return document")();'
+])
+ test(`unmanaged or indirect mutation capabilities fail closed: ${source}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ reject(execute(), /DOM|capability|reflection|model/);
+ });
+ });
+
+for (const markup of [
+ '<link bind:this={link} rel="icon" href="/favicon.ico" />',
+ '<div use:mutate>content</div>',
+ '<div {@attach mutate}>content</div>',
+ '<div transition:mutate>content</div>'
+])
+ test(`markup cannot expose unmanaged DOM handles: ${markup}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ '<script lang="ts">let link; const mutate = (node) => node;</script>' +
+ markup
+ );
+ reject(execute(), /DOM bindings\/actions\/attachments/);
+ });
+ });
+
+test('owned plain model mutations, lexical aliases, reflection and UI leaf operations remain admitted', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ 'const model = { href: "/home", rel: "icon", counter: 0, style: { color: "description" } }; const alias = model; alias.href = "/search"; model["rel"] = "metadata"; model.counter++; Object.assign(alias, { href: "/sell" }); Reflect.set(model, "rel", "model"); Object.defineProperty(model, "label", { value: "HarvestCircle" }); model.style.color = "plain data"; export function focus() { document.querySelector("#subject")?.focus(); } export function read() { return document.getElementById("subject")?.textContent; }'
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
+
+for (const source of [
+ 'import { createRawSnippet } from "svelte"; export const snippet = createRawSnippet(() => ({ render: () => "<link rel=stylesheet href=/extra.css>" }));',
+ 'import { createRawSnippet as raw } from "svelte"; export const snippet = raw(() => ({ render: () => "<script src=/tests/provider.js></script>" }));',
+ 'import * as renderer from "svelte"; export const snippet = renderer["create" + "RawSnippet"](() => ({ render: () => "<style>body{color:red}</style>" }));',
+ 'export * from "svelte";',
+ 'export { createRawSnippet as raw } from "svelte";',
+ 'const renderer = await import("svelte"); export const snippet = renderer.createRawSnippet;',
+ 'import { render } from "svelte/server"; export { render };'
+])
+ test(`pinned Svelte raw rendering remains unavailable: ${source}`, async () => {
+ await fixture(async ({ directory, put, execute }) => {
+ await confineSvelte(directory);
+ await put('src/routes/+page.ts', source);
+ reject(
+ execute(),
+ /createRawSnippet|raw-render|forbidden production import svelte\/server/
+ );
+ });
+ });
+
+test('actual pinned safe Svelte imports remain available', async () => {
+ await fixture(async ({ directory, put, execute }) => {
+ await confineSvelte(directory);
+ await put(
+ 'src/routes/+page.ts',
+ 'import { onMount } from "svelte"; import type { Snippet } from "svelte"; export { onMount }; export type { Snippet };'
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
+
+for (const mutation of [
+ 'opaque.rel = "stylesheet";',
+ 'opaque["href"] = "/extra.css";',
+ 'opaque.setAttribute("rel", "stylesheet");',
+ 'const setter = opaque.setAttribute; setter.apply(opaque, ["href", "/extra.css"]);',
+ 'Object.assign(opaque, { rel: "stylesheet" });',
+ 'const attribute = opaque.attributes.item(0); attribute.nodeValue = "/extra.css";',
+ 'opaque.relList.add("stylesheet");',
+ 'Reflect.set(opaque, "href", "/extra.css");'
+])
+ test(`mutation grammar rejects opaque inputs without DOM acquisition: ${mutation}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ 'export function mutate(opaque: unknown) { ' +
+ mutation.replaceAll(
+ 'opaque.',
+ '(opaque as Record<string, unknown>).'
+ ) +
+ ' }'
+ );
+ reject(execute(), /DOM|mutation|reflection|model/);
+ });
+ });
+
+test('string-named raw-render exports cannot bypass semantic import admission', async () => {
+ await fixture(async ({ directory, put, execute }) => {
+ await confineSvelte(directory);
+ await put(
+ 'src/routes/+page.ts',
+ 'import { "createRawSnippet" as raw } from "svelte"; export { raw };'
+ );
+ reject(execute(), /raw-render factories/);
+ });
+});
+
+for (const source of [
+ 'new Worker("https://example.invalid/client.js");',
+ 'new SharedWorker("/tests/client.js");',
+ 'importScripts("https://example.invalid/client.js");',
+ 'navigator.serviceWorker.register("/tests/client.js");',
+ 'const capabilities = navigator; capabilities["service" + "Worker"].register("/tests/client.js");',
+ 'window.navigator["service" + "Worker"].register("/tests/client.js");',
+ 'const registrations = window.navigator.serviceWorker; registrations.register("/tests/client.js");',
+ 'const audio = new AudioContext(); audio.audioWorklet.addModule("/tests/client.js");'
+])
+ test(`browser worker loading cannot bypass source imports: ${source}`, async () => {
+ await fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ reject(execute(), /loader|worker|DOM|capability/);
+ });
+ });
+
+test('approved navigator capabilities and plain model flags remain admitted', async () => {
+ await fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ 'const model = { serviceWorker: false }; export const disabled = model.serviceWorker; export function online() { return navigator.onLine; } export function estimate() { return navigator.storage.estimate(); } export function copy(value: string) { return window.navigator.clipboard.writeText(value); }'
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ });
+});
+
+const helperImport =
+ "import { internalHref, navigationHref } from '../lib/navigation-url';";
+for (const [
+ name,
+ code,
+ accepted
+] of /** @type {Array<[string,string,boolean]>} */ ([
+ ['concat executable', "<a href={'java'+'script:alert(1)'}>bad</a>", false],
+ [
+ 'shorthand executable',
+ "<script>const href='javascript:alert(1)';</script><a {href}>bad</a>",
+ false
+ ],
+ [
+ 'mixed executable',
+ '<script>const scheme=\'java\';</script><a href="{scheme}script:alert(1)">bad</a>',
+ false
+ ],
+ [
+ 'conditional executable',
+ "<a href={true ? '/safe' : 'javascript:alert(1)'}>bad</a>",
+ false
+ ],
+ [
+ 'alias executable',
+ "<script>const a='javascript:alert(1)'; const href=a;</script><a {href}>bad</a>",
+ false
+ ],
+ [
+ 'safe aliases',
+ "<script>const a='/search'; const href=a+'?q=food';</script><a {href}>safe</a>",
+ true
+ ],
+ [
+ 'safe template',
+ "<script>const id='example';</script><a href={`/products/${id}`}>safe</a>",
+ true
+ ],
+ [
+ 'wrapped route',
+ `<script lang="ts">${helperImport} const route=(id: string) => '/products/'+id; const id='example';</script><a href={internalHref(route(id))}>safe</a>`,
+ true
+ ],
+ [
+ 'wrapped contact',
+ `<script lang="ts">${helperImport} const contact: unknown='https://example.com';</script><a href={navigationHref(contact)}>safe</a>`,
+ true
+ ],
+ [
+ 'forged spelling',
+ "<script>const internalHref=x=>x;</script><a href={internalHref('javascript:alert(1)')}>bad</a>",
+ false
+ ],
+ [
+ 'each shadows helper',
+ `<script>${helperImport} const funcs=[x=>x];</script>{#each funcs as internalHref}<a href={internalHref('javascript:alert(1)')}>bad</a>{/each}`,
+ false
+ ],
+ [
+ 'snippet shadows helper',
+ `<script>${helperImport}</script>{#snippet row(internalHref)}<a href={internalHref('javascript:alert(1)')}>bad</a>{/snippet}`,
+ false
+ ],
+ [
+ 'const shadows helper',
+ `<script>${helperImport}</script>{#if true}{@const internalHref = x=>x}<a href={internalHref('javascript:alert(1)')}>bad</a>{/if}`,
+ false
+ ],
+ [
+ 'module scope helper',
+ `<script module>${helperImport}</script><a href={internalHref('/products/a')}>safe</a>`,
+ true
+ ],
+ [
+ 'instance shadows module',
+ `<script module>${helperImport}</script><script>const internalHref=x=>x;</script><a href={internalHref('javascript:alert(1)')}>bad</a>`,
+ false
+ ],
+ [
+ 'module sees no instance helper',
+ `<script module>export const wrong=internalHref('javascript:alert(1)');</script><script>${helperImport}</script><a href={wrong}>bad</a>`,
+ false
+ ],
+ [
+ 'unknown prop',
+ '<script>let {href}=$props();</script><a {href}>bad</a>',
+ false
+ ],
+ [
+ 'cast prop',
+ '<script lang="ts">let {href}: {href:string}=$props();</script><a href={href as string}>bad</a>',
+ false
+ ],
+ [
+ 'resource validator cannot admit remote image',
+ `<script>${helperImport}</script><img src={navigationHref('https://example.com/image.png')} alt="bad"/>`,
+ false
+ ],
+ [
+ 'remote image',
+ '<img src="https://example.com/image.png" alt="bad"/>',
+ false
+ ],
+ [
+ 'remote srcset',
+ '<img srcset="https://example.com/image.png 2x" alt="bad"/>',
+ false
+ ],
+ [
+ 'remote poster',
+ '<video poster="https://example.com/image.png"></video>',
+ false
+ ],
+ ['form computed', "<form action={'java'+'script:alert(1)'}></form>", false],
+ ['URL control', '<a href="https://user:secret@example.com">bad</a>', false],
+ ['backslash', '<a href="/\\evil.test">bad</a>', false],
+ [
+ 'namespace SVG',
+ '<svg><a xlink:href="javascript:alert(1)">bad</a></svg>',
+ false
+ ]
+])) {
+ test(`D07 markup: ${name}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.svelte', code);
+ const result = execute();
+ assert.equal(
+ result.status,
+ accepted ? 0 : 1,
+ result.stdout + result.stderr
+ );
+ }));
+}
+
+for (const [
+ name,
+ code,
+ accepted
+] of /** @type {Array<[string,string,boolean]>} */ ([
+ ['Location literal', "location.assign('/search');", true],
+ ['Location qualified literal', "window.location.replace('/search');", true],
+ ['Location href literal', "location.href='/search';", true],
+ ['Location write literal', "window.location='/search';", true],
+ ['Location executable', "location.assign('javascript:alert(1)');", false],
+ ['Location external', "location.assign('https://example.com');", false],
+ [
+ 'Location escaped',
+ "const target=location; target.assign('/search');",
+ false
+ ],
+ [
+ 'Location destructured',
+ "const {assign}=location; assign('/search');",
+ false
+ ],
+ ['Location computed', "location['assign']('/search');", false],
+ [
+ 'validated Location',
+ `${helperImport} const target=internalHref('/search'); if(target !== undefined) location.assign(target);`,
+ true
+ ],
+ [
+ 'undefined Location',
+ `${helperImport} location.assign(internalHref('/search'));`,
+ false
+ ],
+ [
+ 'asserted Location',
+ `${helperImport} location.assign(internalHref('/search')!);`,
+ false
+ ],
+ [
+ 'Kit literal',
+ "import {goto as navigate} from '$app/navigation'; navigate('/search');",
+ true
+ ],
+ [
+ 'Kit validated',
+ `${helperImport} import {goto} from '$app/navigation'; const target=internalHref('/search'); if(target) goto(target);`,
+ true
+ ],
+ [
+ 'Kit undefined',
+ `${helperImport} import {goto} from '$app/navigation'; goto(internalHref('/search'));`,
+ false
+ ],
+ [
+ 'Kit executable',
+ "import {goto} from '$app/navigation'; goto('javascript:alert(1)');",
+ false
+ ],
+ [
+ 'Kit escaped',
+ "import {goto} from '$app/navigation'; const redirect=goto; redirect('javascript:alert(1)');",
+ false
+ ],
+ [
+ 'callback timer',
+ 'setTimeout(()=>{},0); setInterval(function(){},100);',
+ true
+ ],
+ [
+ 'named callback timer',
+ 'function callback(){} setTimeout(callback,0);',
+ true
+ ],
+ [
+ 'const callback timer',
+ 'const callback=()=>{}; setInterval(callback,100);',
+ true
+ ],
+ [
+ 'shadowed timer ordinary model',
+ "const setTimeout=(value:string)=>value; setTimeout('data');",
+ true
+ ],
+ ['string timer', "setTimeout('alert(1)',0);", false],
+ ['unknown timer', 'setTimeout(callback,0);', false],
+ ['escaped timer', "const later=setTimeout; later('alert(1)',0);", false],
+ ['qualified timer', 'window.setTimeout(()=>{},0);', false],
+ ['computed timer', 'globalThis["setTimeout"](()=>{},0);', false],
+ [
+ 'destructured timer',
+ 'const {setTimeout: later}=window; later(()=>{},0);',
+ false
+ ],
+ [
+ 'reassigned callback',
+ 'let cb=()=>{}; cb=external; setTimeout(cb,0);',
+ false
+ ],
+ [
+ 'parameter callback unsupported',
+ 'function schedule(cb:()=>void){setTimeout(cb,0)}',
+ false
+ ],
+ [
+ 'literal replace',
+ "const value='one two'; export const normalized=value.replace(/\\s+/g,' ');",
+ true
+ ],
+ [
+ 'alias replace',
+ "const value='one two'; const alias=value; alias.replace('two','three');",
+ true
+ ],
+ [
+ 'fake replace',
+ "const value=external as string; value.replace('two','three');",
+ false
+ ],
+ [
+ 'DOM replace',
+ "document.querySelector('link').relList.replace('icon','stylesheet');",
+ false
+ ],
+ ['local Set', "const seen=new Set<string>(); seen.add('public-id');", true],
+ [
+ 'shadowed Set',
+ "function f(Set:any){const seen=new Set();seen.add('x')}",
+ false
+ ],
+ [
+ 'Set alias',
+ "const seen=new Set(); const other=seen; other.add('x');",
+ false
+ ],
+ ['Set rebound', "let seen=new Set();seen=external;seen.add('x');", false],
+ [
+ 'Set escaped add',
+ "const seen=new Set(); const add=seen.add; add('x');",
+ false
+ ],
+ ['opaque add', "(external as Set<string>).add('x');", false],
+ [
+ 'DOM add',
+ "document.querySelector('link').relList.add('stylesheet');",
+ false
+ ]
+])) {
+ test(`D07 JavaScript: ${name}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', code);
+ const result = execute();
+ assert.equal(
+ result.status,
+ accepted ? 0 : 1,
+ result.stdout + result.stderr
+ );
+ }));
+}
+
+test('D07 helper runtime validates unknown values without effects or coercion', async () => {
+ const { internalHref, navigationHref } =
+ await import('../../src/lib/navigation-url.ts');
+ const evil = {
+ toString() {
+ throw new Error('coercion');
+ }
+ };
+ for (const value of [
+ evil,
+ null,
+ undefined,
+ 5,
+ [],
+ {},
+ '',
+ '//evil.test',
+ '/\\evil.test',
+ 'javascript:alert(1)',
+ 'data:text/html,x',
+ 'https://u:p@example.com',
+ 'https://@example.com',
+ 'https:////@example.com',
+ 'https:///@example.com',
+ 'https:////example.com',
+ 'mailto://evil.example/path',
+ 'tel://evil.example/path',
+ '\ud800',
+ '/foo\nbar',
+ '/%0d%0aevil',
+ '/%5cevil',
+ '/%zz',
+ 'a'.repeat(8193)
+ ]) {
+ assert.equal(internalHref(value), undefined);
+ assert.equal(navigationHref(value), undefined);
+ }
+ for (const value of [
+ '/search?q=food',
+ '#item',
+ '?query=food',
+ '/products/example'
+ ]) {
+ assert.equal(internalHref(value), value);
+ assert.equal(navigationHref(value), value);
+ }
+ for (const value of [
+ 'https://example.com/path',
+ 'HTTPS://example.com/path',
+ 'https://example.com/@path?email=buyer@example.com',
+ 'mailto:buyer@example.com',
+ 'tel:+123456789'
+ ]) {
+ assert.equal(internalHref(value), undefined);
+ assert.equal(navigationHref(value), value);
+ }
+ assert.equal(internalHref('/' + 'é'.repeat(4095)), '/' + 'é'.repeat(4095));
+ assert.equal(internalHref('/' + 'é'.repeat(4096)), undefined);
+ assert.equal(internalHref('/' + 'a'.repeat(8191)), '/' + 'a'.repeat(8191));
+ let mutable = '/safe';
+ assert.equal(internalHref(mutable), '/safe');
+ mutable = 'javascript:alert(1)';
+ assert.equal(internalHref(mutable), undefined);
+});
+
+test('D07 helper pin rejects source tampering and spoofed module exports', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/navigation-url.ts',
+ 'export const internalHref=(value:unknown)=>value;'
+ );
+ await put(
+ 'src/routes/+page.svelte',
+ `<script>${helperImport}</script><a href={internalHref('/safe')}>bad</a>`
+ );
+ reject(execute(), /source identity/);
+ }));
+
+test('D07 alias and named re-export retain exact helper export identity', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/links.ts',
+ "export {internalHref as routeHref} from './navigation-url';"
+ );
+ await put(
+ 'src/routes/+page.svelte',
+ "<script>import {routeHref as validated} from '../lib/links'; const unknownRoute='/search';</script><a href={validated(unknownRoute)}>safe</a>"
+ );
+ assert.equal(execute().status, 0);
+ }));
+
+test('D07 positives compile with actual Svelte and TypeScript', async () =>
+ fixture(async ({ put, execute, directory }) => {
+ const { compile } = await import('svelte/compiler');
+ const source = `<script lang="ts">${helperImport} let {href}: {href: unknown} = $props(); const route=(id:string)=>'/products/'+id;</script><a href={navigationHref(href)}>contact</a><a href={internalHref(route('example'))}>product</a>`;
+ await put('src/routes/+page.svelte', source);
+ assert.equal(execute().status, 0);
+ const output = compile(source, {
+ filename: path.join(directory, 'src/routes/+page.svelte'),
+ generate: 'server'
+ });
+ assert.ok(output.js.code.length > 0);
+ assert.deepEqual(output.warnings, []);
+ const { default: ts } = await import('typescript');
+ const navigation = `import {internalHref} from './src/lib/navigation-url'; import {goto} from '$app/navigation'; export function search(input:unknown){const target=internalHref(input); if(target !== undefined) void goto(target);} export const normalize='one two'.replace(/\\s+/g,' '); const seen=new Set<string>();seen.add('id'); setTimeout(()=>seen.add('next'),0);`;
+ await put('positive.ts', navigation);
+ const program = ts.createProgram([path.join(directory, 'positive.ts')], {
+ strict: true,
+ noEmit: true,
+ target: ts.ScriptTarget.ESNext,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ skipLibCheck: true,
+ types: ['@sveltejs/kit']
+ });
+ assert.deepEqual(
+ ts
+ .getPreEmitDiagnostics(program)
+ .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n')),
+ []
+ );
+ }));
+
+for (const [
+ name,
+ code,
+ accepted
+] of /** @type {Array<[string,string,boolean]>} */ ([
+ [
+ 'namespace helper',
+ "<script>import * as links from '../lib/navigation-url'; const route='/safe';</script><a href={links.internalHref(route)}>safe</a>",
+ true
+ ],
+ [
+ 'await shadows helper',
+ `<script>${helperImport} const pending=Promise.resolve(x=>x);</script>{#await pending then internalHref}<a href={internalHref('javascript:alert(1)')}>bad</a>{/await}`,
+ false
+ ],
+ [
+ 'reassigned helper',
+ `<script>${helperImport} internalHref=x=>x;</script><a href={internalHref('javascript:alert(1)')}>bad</a>`,
+ false
+ ],
+ [
+ 'spoofed import',
+ "<script>import {internalHref} from '../lib/spoof';</script><a href={internalHref('javascript:alert(1)')}>bad</a>",
+ false
+ ],
+ [
+ 'namespace escape',
+ "<script>import * as nav from '$app/navigation'; const copy=nav; copy.goto('javascript:alert(1)');</script>",
+ false
+ ],
+ [
+ 'namespace Kit navigation',
+ "<script>import * as nav from '$app/navigation'; const go=()=>nav.goto('/search');</script><button onclick={go}>Search</button>",
+ true
+ ],
+ [
+ 'reassigned Kit capability',
+ "<script>import {goto} from '$app/navigation'; goto=x=>x; goto('javascript:alert(1)');</script>",
+ false
+ ]
+]))
+ test(`D07 binding identity: ${name}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/spoof.ts',
+ 'export const internalHref=(value:unknown)=>value;'
+ );
+ await put('src/routes/+page.svelte', code);
+ const result = execute();
+ assert.equal(result.status, accepted ? 0 : 1, result.stderr);
+ }));
+
+for (const [code, accepted] of /** @type {Array<[string,boolean]>} */ ([
+ [
+ "const text='one two';const normalized=text.replace(/\\s+/g,' ');normalized.replace('two','three');",
+ true
+ ],
+ [
+ "const seen=new Set<string>(); seen.add('id'); const count=seen.size; const exists=seen.has('id');",
+ true
+ ],
+ ["const seen=new Set<string>(); external(seen); seen.add('id');", false],
+ ['const seen=new Set<string>(); export const leak=seen;', false],
+ ["const seen=new Set<string>(); const read=seen.has; read('id');", false]
+]))
+ test(`D07 concrete receivers: ${code}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', code);
+ const result = execute();
+ assert.equal(result.status, accepted ? 0 : 1, result.stderr);
+ }));
+
+test('D07 package import alias retains helper identity without evaluating configuration', async () =>
+ fixture(async ({ put, execute, pkg }) => {
+ pkg.imports = { '#links': './src/lib/navigation-url.ts' };
+ await put('package.json', JSON.stringify(pkg));
+ await put(
+ 'src/routes/+page.svelte',
+ "<script>import {internalHref as validated} from '#links';const input='/safe';</script><a href={validated(input)}>safe</a>"
+ );
+ assert.equal(execute().status, 0);
+ }));
+
+for (const command of ['check', 'lint', 'build', 'test:unit', 'dev'])
+ test(`D07 actual ${command} stops before framework dispatch on computed executable URL`, async () =>
+ fixture(async ({ put, directory }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ "<a href={'java'+'script:import(\"nostr-tools\")'}>bad</a>"
+ );
+ const result = spawnSync('corepack', ['pnpm', 'run', command], {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 8000
+ });
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(result.stderr, /unsafe markup URL/);
+ assert.doesNotMatch(
+ result.stdout,
+ /svelte-check found|vite v.*building|RUN\s+v/
+ );
+ }));
+
+test('D07 component props are validated at the actual element sink and compile', async () =>
+ fixture(async ({ put, execute, directory }) => {
+ const { compile } = await import('svelte/compiler');
+ const component =
+ '<script lang="ts">import {navigationHref} from \'./navigation-url\'; let {href}: {href:unknown}=$props();</script><a href={navigationHref(href)}>Contact</a>';
+ const page =
+ "<script lang=\"ts\">import Link from '../lib/Link.svelte';const contact:unknown='https://example.com';</script><Link href={contact}/>";
+ await put('src/lib/Link.svelte', component);
+ await put('src/routes/+page.svelte', page);
+ assert.equal(execute().status, 0);
+ for (const [source, name] of [
+ [component, 'src/lib/Link.svelte'],
+ [page, 'src/routes/+page.svelte']
+ ]) {
+ const compiled = compile(source, {
+ filename: path.join(directory, name),
+ generate: 'server'
+ });
+ assert.ok(compiled.js.code.length);
+ assert.deepEqual(compiled.warnings, []);
+ }
+ await put(
+ 'src/lib/Link.svelte',
+ '<script lang="ts">let {href}: {href:string}=$props();</script><a {href}>Bad</a>'
+ );
+ reject(execute(), /unsafe markup URL/);
+ }));
+
+test('D07 helper byte pin includes the leading UTF8 BOM', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/navigation-url.ts',
+ '\ufeff' +
+ (await readFile(path.join(root, 'src/lib/navigation-url.ts'), 'utf8'))
+ );
+ reject(execute(), /source identity/);
+ }));
+
+for (const producer of [
+ "import {goto} from '$app/navigation'; export {goto};",
+ "import {goto as imported} from '$app/navigation'; export {imported as redirected};",
+ "import * as navigation from '$app/navigation'; export {navigation};",
+ "import {goto} from '$app/navigation'; export default goto;"
+])
+ test(`D07 local Kit exports cannot launder navigation: ${producer}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/lib/escaped.ts', producer);
+ await put(
+ 'src/routes/+page.ts',
+ "import {goto as redirected} from '../lib/escaped'; redirected('javascript:alert(1)');"
+ );
+ reject(execute(), /escaped (goto capability|navigation namespace)/);
+ }));
+
+test('D07 named module Kit reexports retain sink identity for actual consumers', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/navigation.ts',
+ "export {goto as navigate} from '$app/navigation';"
+ );
+ await put(
+ 'src/routes/+page.ts',
+ "import {navigate} from '../lib/navigation'; navigate('/search');"
+ );
+ assert.equal(execute().status, 0);
+ await put(
+ 'src/routes/+page.ts',
+ "import {navigate} from '../lib/navigation'; navigate('javascript:alert(1)');"
+ );
+ reject(execute(), /defined validated internal URL/);
+ }));
+
+test('D07 local helper reexports are untrusted until explicitly resolved at a sink', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/indirect.ts',
+ "import {internalHref} from './navigation-url'; export {internalHref as validated};"
+ );
+ await put(
+ 'src/routes/+page.svelte',
+ "<script>import {validated} from '../lib/indirect';const route='/safe';</script><a href={validated(route)}>Unknown binding</a>"
+ );
+ reject(execute(), /unsafe markup URL/);
+ }));
+
+test('D07 literal Svelte element tags share URL context admission and compile', async () =>
+ fixture(async ({ put, execute, directory }) => {
+ const { compile } = await import('svelte/compiler');
+ const positive =
+ "<svelte:element this={'a'} href='https://example.com'>Contact</svelte:element>";
+ await put('src/routes/+page.svelte', positive);
+ assert.equal(execute().status, 0);
+ const compiled = compile(positive, {
+ filename: path.join(directory, 'src/routes/+page.svelte'),
+ generate: 'server'
+ });
+ assert.ok(compiled.js.code.length);
+ assert.deepEqual(compiled.warnings, []);
+ for (const source of [
+ "<svelte:element this='a' href={'java'+'script:alert(1)'}>Bad</svelte:element>",
+ "<svelte:element this='img' src='https://example.com/image.png' alt='Bad'/>",
+ "<svelte:element this='image' href='https://example.com/image.png'/>",
+ "<script>const tag='a';</script><svelte:element this={tag} href='https://example.com'>Unsupported</svelte:element>"
+ ]) {
+ await put('src/routes/+page.svelte', source);
+ reject(execute(), /unsafe markup URL|computed markup resource elements/);
+ }
+ }));
+
+for (const barrel of [
+ "export * from './bridge';",
+ "export * as navigation from './bridge';"
+])
+ test(`D07 Kit capability cannot escape renamed bridge through ${barrel}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/bridge.ts',
+ "export {goto as redirect} from '$app/navigation';"
+ );
+ await put('src/lib/barrel.ts', barrel);
+ await put(
+ 'src/routes/+page.ts',
+ "import {redirect} from '../lib/barrel';redirect('javascript:alert(1)');"
+ );
+ reject(execute(), /navigation star\/namespace reexport/);
+ }));
+
+test('D07 renamed Kit namespace aliases cannot escape actual binding identity', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/lib/bridge.ts',
+ "export {goto as redirect} from '$app/navigation';"
+ );
+ await put(
+ 'src/routes/+page.ts',
+ "import * as navigation from '../lib/bridge'; const escaped=navigation;escaped.redirect('javascript:alert(1)');"
+ );
+ reject(execute(), /escaped navigation namespace/);
+ }));
+
+for (const source of [
+ "location.assign(setTimeout('alert(1)',0) ? '/one' : '/two');",
+ "import {goto} from '$app/navigation'; location.assign(goto('javascript:alert(1)') ? '/one' : '/two');",
+ "window.location.href=setInterval('alert(1)',100) ? '/one' : '/two';"
+])
+ test(`D07 accepted Location URL does not hide hostile expression descendants: ${source}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ reject(
+ execute(),
+ /direct function callback|defined validated internal URL/
+ );
+ }));
+
+test('D07 Location conditional callback expressions remain admitted with complete descendant audit', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ "location.assign(setTimeout(()=>{},0) ? '/one' : '/two'); window.location.replace('/search'); window.location.href='/search';"
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ }));
+
+for (const source of [
+ "Set = fake; const seen=new Set(); seen.add('id');",
+ "Set ||= fake; const seen=new Set(); seen.add('id');",
+ "Set = fake; const seen=new Set(); const read=seen.has; read('id');"
+])
+ test(`D07 global collection constructor rebinding is untrusted: ${source}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ const result = execute();
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ }));
+
+for (const href of [
+ 'https:////@example.com',
+ 'https:///@example.com',
+ 'https:////example.com'
+])
+ test(`D07 malformed HTTPS authority cannot normalize away credentials: ${href}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ `<a href=${JSON.stringify(href)}>Bad</a>`
+ );
+ reject(execute(), /unsafe markup URL/);
+ }));
+
+const smilMutation =
+ "<svg width='300' height='100'><a id='link' href='/safe'><text x='10' y='50'>Click</text></a><set href='#link' attributeName='href' to='javascript:window.__smilExecuted=true' begin='0s' fill='freeze'/></svg>";
+for (const tag of [
+ 'set',
+ 'animate',
+ 'animateMotion',
+ 'animateTransform',
+ 'discard',
+ 'SET',
+ 'svg:animate',
+ 'svg:animateTransform'
+])
+ test(`D07 declarative SVG mutation tag is rejected: ${tag}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ `<svg><${tag} href='#link' attributeName='href' to='javascript:alert(1)'/></svg>`
+ );
+ reject(execute(), /declarative SVG resource\/style mutation/);
+ }));
+
+for (const tag of [
+ 'set',
+ 'animate',
+ 'animateMotion',
+ 'animateTransform',
+ 'discard',
+ 'SVG:SET'
+])
+ test(`D07 literal Svelte element cannot construct SVG mutation: ${tag}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.svelte',
+ `<svg><svelte:element this={${JSON.stringify(tag)}} href='#link' attributeName='href' to='javascript:alert(1)'/></svg>`
+ );
+ reject(execute(), /declarative SVG resource\/style mutation/);
+ }));
+
+test('D07 actual SMIL href mutation fixture rejects while static SVG compiles', async () =>
+ fixture(async ({ put, execute, directory }) => {
+ await put('src/routes/+page.svelte', smilMutation);
+ reject(execute(), /declarative SVG resource\/style mutation/);
+ const source =
+ "<svg viewBox='0 0 100 100' role='img' aria-label='Static graphic'><path d='M0 0 L20 20'/><a href='/safe'><text x='10' y='50'>Safe link</text></a></svg>";
+ await put('src/routes/+page.svelte', source);
+ assert.equal(execute().status, 0);
+ const { compile } = await import('svelte/compiler');
+ const compiled = compile(source, {
+ filename: path.join(directory, 'src/routes/+page.svelte'),
+ generate: 'server'
+ });
+ assert.ok(compiled.js.code.length);
+ assert.deepEqual(compiled.warnings, []);
+ }));
+
+for (const source of [
+ 'export function motion(element:Element){element.animate([{opacity:0},{opacity:1}],100);}',
+ 'export function motion(element:Element){const animate=element.animate;animate.call(element,[{opacity:0},{opacity:1}],100);}',
+ "export function motion(element:Element){const key='animate';const escaped=element[key];escaped([{opacity:0},{opacity:1}],100);}",
+ "export function motion(element:Element){const escaped=element['ani'+'mate'];escaped([{opacity:0},{opacity:1}],100);}",
+ "export function motion(element:Element,flag:boolean){const key=flag?'animate':'setKeyframes';const escaped=element[key];escaped([{opacity:0},{opacity:1}],100);}",
+ 'export function motion(effect:KeyframeEffect){effect.setKeyframes([{opacity:0},{opacity:1}]);}',
+ 'export function motion(effect:KeyframeEffect){const update=effect.setKeyframes;update([{opacity:0},{opacity:1}]);}',
+ 'export function motion(element:Element){new KeyframeEffect(element,[{opacity:0},{opacity:1}],100);}',
+ 'const Effect=KeyframeEffect;new Effect(opaque,[{opacity:0},{opacity:1}],100);',
+ 'new Animation(opaque);',
+ 'const CreateAnimation=Animation;new CreateAnimation(opaque);',
+ "document.createElementNS('http://www.w3.org/2000/svg','set');"
+])
+ test(`D07 imperative style/animation capability is rejected: ${source}`, async () =>
+ fixture(async ({ put, execute }) => {
+ await put('src/routes/+page.ts', source);
+ const result = execute();
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(
+ result.stderr,
+ /mutation\/setter|animation constructors|SVG resource\/style constructors|DOM handles/
+ );
+ }));
+
+test('D07 animation names remain ordinary owned model data', async () =>
+ fixture(async ({ put, execute }) => {
+ await put(
+ 'src/routes/+page.ts',
+ "const model={animate:false,setKeyframes:0}; model.animate=true;model.setKeyframes+=1; export const flag=model.animate;export const revision=model.setKeyframes; function Animation(value:string){return value} export const label=Animation('ordinary model');"
+ );
+ const result = execute();
+ assert.equal(result.status, 0, result.stderr);
+ }));
+
+for (const command of ['check', 'lint', 'build', 'test:unit', 'dev'])
+ test(`D07 actual ${command} stops before framework dispatch on SVG URL mutation`, async () =>
+ fixture(async ({ put, directory }) => {
+ await put('src/routes/+page.svelte', smilMutation);
+ const result = spawnSync('corepack', ['pnpm', 'run', command], {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 8000
+ });
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 1, result.stdout + result.stderr);
+ assert.match(result.stderr, /declarative SVG resource\/style mutation/);
+ assert.doesNotMatch(
+ result.stdout,
+ /svelte-check found|vite v.*building|RUN\s+v/
+ );
+ }));
diff --git a/web/tools/check-source.mjs b/web/tools/check-source.mjs
@@ -1,148 +1,12 @@
-import { readdir, open } from 'node:fs/promises';
-import { constants } from 'node:fs';
import { fileURLToPath } from 'node:url';
-import path from 'node:path';
-import ts from 'typescript';
-import { parse } from 'svelte/compiler';
+import { auditSource } from './source-boundaries.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
-const sourceRoot = path.join(root, 'src');
-const allowedCss = new Set(['src/theme.css', 'src/app.css']);
-const findings = [];
-
-// Same source-audit limit as the standalone native inventory reader.
-const sourceByteLimit = 8 * 1024 * 1024;
-async function readSource(file) {
- const handle = await open(
- file,
- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
- );
- try {
- const stat = await handle.stat();
- if (!stat.isFile() || stat.size > sourceByteLimit)
- throw new Error(`Unsafe source file: ${file}`);
- const chunks = [];
- let size = 0;
- for (;;) {
- const buffer = Buffer.alloc(64 * 1024);
- const { bytesRead } = await handle.read(buffer);
- if (!bytesRead) break;
- size += bytesRead;
- if (size > sourceByteLimit)
- throw new Error(`Source file exceeds audit limit: ${file}`);
- chunks.push(buffer.subarray(0, bytesRead));
- }
- return new TextDecoder('utf-8', { fatal: true }).decode(
- Buffer.concat(chunks)
- );
- } finally {
- await handle.close();
- }
-}
-async function scan(directory) {
- for (const entry of await readdir(directory, { withFileTypes: true })) {
- const file = path.join(directory, entry.name);
- const relative = path.relative(root, file).split(path.sep).join('/');
- if (entry.isSymbolicLink()) {
- findings.push(`${relative}: source symlinks are forbidden`);
- continue;
- }
- if (entry.isDirectory()) {
- await scan(file);
- continue;
- }
- if (!entry.isFile()) {
- findings.push(`${relative}: nonregular source entries are forbidden`);
- continue;
- }
- if (/\.(css|scss|sass|less)$/.test(relative) && !allowedCss.has(relative))
- findings.push(
- `${relative}: handwritten CSS belongs in theme.css or app.css`
- );
- if (!/\.(svelte|[cm]?[jt]s)$/.test(relative)) continue;
- const content = await readSource(file);
- const scripts = [];
- if (relative.endsWith('.svelte')) {
- const ast = parse(content, { modern: true });
- if (ast.css) findings.push(`${relative}: component CSS is forbidden`);
- const visit = (node) => {
- if (!node || typeof node !== 'object') return;
- if (
- node.type === 'StyleDirective' ||
- (node.type === 'Attribute' && node.name === 'style')
- )
- findings.push(`${relative}: inline styles are forbidden`);
- for (const value of Object.values(node)) {
- if (Array.isArray(value)) value.forEach(visit);
- else if (value && typeof value === 'object') visit(value);
- }
- };
- visit(ast.fragment);
- for (const script of [ast.instance, ast.module])
- if (script)
- scripts.push(content.slice(script.content.start, script.content.end));
- } else scripts.push(content);
- const inspectImport = (specifier) => {
- const resolved = specifier.startsWith('.')
- ? path.resolve(path.dirname(file), specifier)
- : null;
- if (
- (resolved && !resolved.startsWith(sourceRoot + path.sep)) ||
- /(^|\/)(tests?|core|app|foundation|enterprise|ops|generated)(\/|$)/.test(
- specifier
- ) ||
- /^(node:|nostr-tools(?:\/|$)|@nostr-dev-kit\/|@radroots\/)/.test(
- specifier
- )
- )
- findings.push(`${relative}: forbidden production import ${specifier}`);
- if (
- /\.(css|scss|sass|less)(\?|$)/.test(specifier) &&
- !(
- relative === 'src/routes/+layout.svelte' &&
- resolved &&
- allowedCss.has(
- path.relative(root, resolved).split(path.sep).join('/')
- )
- )
- )
- findings.push(`${relative}: CSS must be imported by the root layout`);
- if (
- /^applesauce-/.test(specifier) &&
- !relative.startsWith('src/lib/nostr/')
- )
- findings.push(`${relative}: Applesauce imports belong in lib/nostr`);
- };
- for (const script of scripts) {
- const parsed = ts.createSourceFile(
- file + '.ts',
- script,
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TS
- );
- const visit = (node) => {
- if (
- (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
- node.moduleSpecifier &&
- ts.isStringLiteral(node.moduleSpecifier)
- )
- inspectImport(node.moduleSpecifier.text);
- if (
- ts.isCallExpression(node) &&
- node.expression.kind === ts.SyntaxKind.ImportKeyword &&
- node.arguments[0] &&
- ts.isStringLiteral(node.arguments[0])
- )
- inspectImport(node.arguments[0].text);
- ts.forEachChild(node, visit);
- };
- visit(parsed);
- }
- }
-}
-await scan(sourceRoot);
-if (findings.length) {
- console.error(findings.join('\n'));
+try {
+ const findings = await auditSource(root);
+ if (findings.length) throw new Error(findings.join('\n'));
+ console.log('Source style/import boundaries: checked');
+} catch (error) {
+ console.error(error.message);
process.exitCode = 1;
-} else console.log('Source style/import boundaries: checked');
+}
diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs
@@ -0,0 +1,2078 @@
+import { readdir, open, lstat, realpath } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import { createHash } from 'node:crypto';
+import ts from 'typescript';
+import { parse } from 'svelte/compiler';
+
+const byteLimit = 8 * 1024 * 1024;
+const codeExtension = /\.(svelte|[cm]?[jt]sx?)$/;
+const forbiddenPath =
+ /(^|\/)(tests?|__tests__|fixtures?|harness|providers?|credentials?|core|app|foundation|enterprise|ops|generated|node_modules|build|\.svelte-kit)(\/|$)|\.(test|spec)\./i;
+const applesauce = new Set([
+ 'applesauce-core',
+ 'applesauce-relay',
+ 'applesauce-signers',
+ 'applesauce-common',
+ 'applesauce-loaders'
+]);
+const runtimePackages = new Set([
+ 'svelte',
+ '@sveltejs/kit',
+ 'rxjs',
+ ...applesauce
+]);
+const frameworkModules = new Set([
+ '$app/env',
+ '$app/env/public',
+ '$app/forms',
+ '$app/navigation',
+ '$app/paths',
+ '$app/state'
+]);
+const declarativeMutationTags = new Set([
+ 'set',
+ 'animate',
+ 'animatemotion',
+ 'animatetransform',
+ 'discard'
+]);
+const inside = (directory, file) => file.startsWith(directory + path.sep);
+const relative = (root, file) =>
+ path.relative(root, file).split(path.sep).join('/');
+
+// Admit bytes before any third-party parser. Retain the opened identity and
+// reject replacement, hardlinks, mutation, symlinks and nonregular entries.
+async function readSource(file) {
+ const before = await lstat(file);
+ if (!before.isFile() || before.nlink !== 1 || (await realpath(file)) !== file)
+ throw new Error(`Unsafe source file: ${file}`);
+ const handle = await open(
+ file,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
+ );
+ try {
+ const stat = await handle.stat();
+ if (
+ !stat.isFile() ||
+ stat.nlink !== 1 ||
+ stat.size > byteLimit ||
+ stat.dev !== before.dev ||
+ stat.ino !== before.ino
+ )
+ throw new Error(`Unsafe source file: ${file}`);
+ const chunks = [];
+ let size = 0;
+ for (;;) {
+ const buffer = Buffer.alloc(64 * 1024);
+ const { bytesRead } = await handle.read(buffer);
+ if (!bytesRead) break;
+ size += bytesRead;
+ if (size > byteLimit)
+ throw new Error(`Source file exceeds audit limit: ${file}`);
+ chunks.push(buffer.subarray(0, bytesRead));
+ }
+ const after = await handle.stat();
+ const named = await lstat(file);
+ if (
+ size !== stat.size ||
+ after.size !== stat.size ||
+ after.mtimeMs !== stat.mtimeMs ||
+ after.ctimeMs !== stat.ctimeMs ||
+ named.dev !== stat.dev ||
+ named.ino !== stat.ino ||
+ !named.isFile() ||
+ named.nlink !== 1 ||
+ (await realpath(file)) !== file
+ )
+ throw new Error(`Source file changed during audit: ${file}`);
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(
+ Buffer.concat(chunks)
+ );
+ } finally {
+ await handle.close();
+ }
+}
+
+function sourceAst(file, text) {
+ const ast = ts.createSourceFile(
+ file,
+ text,
+ ts.ScriptTarget.Latest,
+ true,
+ file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
+ );
+ if (ast.parseDiagnostics.length)
+ throw new Error(`${file}: invalid source syntax`);
+ return ast;
+}
+// A source guard is not a JavaScript sandbox. Admit a deliberately bounded DOM
+// grammar: direct focus/blur/scroll and scalar control reads; no escaped nodes,
+// actions, bindings, raw render factories or opaque object mutation. Svelte owns
+// DOM updates. Mutable application data must be locally owned plain data, with
+// pure values and lexical aliases. Future imperative UI work needs explicit
+// admission and negative tests rather than a type cast or an ignored diagnostic.
+function mutationAdmission(ast, report, identity = () => null) {
+ // Bind this admitted AST only, without libs, module resolution, file reads,
+ // config loading or evaluation. Symbols distinguish aliases and shadowing.
+ const options = {
+ noLib: true,
+ noResolve: true,
+ types: [],
+ allowNonTsExtensions: true
+ };
+ const host = {
+ ...ts.createCompilerHost(options),
+ getSourceFile: (name) => (name === ast.fileName ? ast : undefined),
+ fileExists: (name) => name === ast.fileName,
+ directoryExists: () => false,
+ getDirectories: () => [],
+ readFile: () => undefined
+ };
+ const checker = ts
+ .createProgram([ast.fileName], options, host)
+ .getTypeChecker();
+ const unwrap = (node) => {
+ while (
+ node &&
+ (ts.isParenthesizedExpression(node) ||
+ ts.isAsExpression(node) ||
+ ts.isTypeAssertionExpression(node) ||
+ ts.isNonNullExpression(node))
+ )
+ node = node.expression;
+ return node;
+ };
+ const member = (node) =>
+ ts.isPropertyAccessExpression(node)
+ ? node.name.text
+ : ts.isElementAccessExpression(node) &&
+ ts.isStringLiteralLike(node.argumentExpression)
+ ? node.argumentExpression.text
+ : null;
+ function uiLeaf(node) {
+ let top = node;
+ while (
+ top.parent &&
+ (ts.isPropertyAccessExpression(top.parent) ||
+ ts.isElementAccessExpression(top.parent) ||
+ ts.isCallExpression(top.parent) ||
+ ts.isNonNullExpression(top.parent) ||
+ ts.isAsExpression(top.parent) ||
+ ts.isParenthesizedExpression(top.parent)) &&
+ top.parent.expression === top
+ )
+ top = top.parent;
+ const action =
+ ts.isCallExpression(top) &&
+ ['focus', 'blur', 'scrollIntoView'].includes(member(top.expression)) &&
+ top.arguments.length === 0;
+ const read =
+ !action &&
+ ['value', 'checked', 'selectedIndex', 'textContent'].includes(
+ member(top)
+ );
+ if (!action && !read) return false;
+ const receiver = unwrap(
+ action ? top.expression.expression : top.expression
+ );
+ if (
+ ts.isPropertyAccessExpression(receiver) &&
+ ['currentTarget', 'target'].includes(receiver.name.text)
+ )
+ return true;
+ return (
+ ts.isCallExpression(receiver) &&
+ ts.isPropertyAccessExpression(receiver.expression) &&
+ ts.isIdentifier(receiver.expression.expression) &&
+ receiver.expression.expression.text === 'document' &&
+ !checker.getSymbolAtLocation(receiver.expression.expression) &&
+ ['getElementById', 'querySelector'].includes(
+ receiver.expression.name.text
+ ) &&
+ receiver.arguments.length === 1 &&
+ ts.isStringLiteralLike(receiver.arguments[0])
+ );
+ }
+ function pure(node, seen = new Set()) {
+ node = unwrap(node);
+ if (!node) return false;
+ if (
+ ts.isStringLiteralLike(node) ||
+ ts.isNumericLiteral(node) ||
+ ts.isBigIntLiteral(node) ||
+ [
+ ts.SyntaxKind.TrueKeyword,
+ ts.SyntaxKind.FalseKeyword,
+ ts.SyntaxKind.NullKeyword
+ ].includes(node.kind)
+ )
+ return true;
+ if (ts.isObjectLiteralExpression(node))
+ return node.properties.every(
+ (property) =>
+ ts.isPropertyAssignment(property) &&
+ !ts.isComputedPropertyName(property.name) &&
+ !['__proto__', 'constructor', 'prototype'].includes(
+ property.name.text
+ ) &&
+ pure(property.initializer, seen)
+ );
+ if (ts.isArrayLiteralExpression(node))
+ return node.elements.every((element) => pure(element, seen));
+ if (ts.isIdentifier(node)) {
+ const symbol = checker.getSymbolAtLocation(node);
+ if (!symbol) return node.text === 'undefined';
+ if (seen.has(symbol)) return false;
+ seen = new Set([...seen, symbol]);
+ const declarations = symbol.declarations ?? [];
+ return (
+ declarations.length === 1 &&
+ (ts.isVariableDeclaration(declarations[0])
+ ? pure(declarations[0].initializer, seen)
+ : ts.isParameter(declarations[0]) &&
+ [
+ ts.SyntaxKind.StringKeyword,
+ ts.SyntaxKind.NumberKeyword,
+ ts.SyntaxKind.BooleanKeyword,
+ ts.SyntaxKind.BigIntKeyword
+ ].includes(declarations[0].type?.kind))
+ );
+ }
+ if (
+ (ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)) &&
+ owned(node.expression, seen)
+ )
+ return (
+ member(node) !== null &&
+ !['constructor', 'prototype', '__proto__'].includes(member(node))
+ );
+ if (ts.isPrefixUnaryExpression(node)) return pure(node.operand, seen);
+ if (
+ ts.isBinaryExpression(node) &&
+ !ts.isAssignmentOperator(node.operatorToken.kind)
+ )
+ return pure(node.left, seen) && pure(node.right, seen);
+ if (ts.isConditionalExpression(node))
+ return (
+ pure(node.condition, seen) &&
+ pure(node.whenTrue, seen) &&
+ pure(node.whenFalse, seen)
+ );
+ return uiLeaf(node) && !ts.isCallExpression(node);
+ }
+ function owned(node, seen = new Set()) {
+ node = unwrap(node);
+ if (!node) return false;
+ if (ts.isObjectLiteralExpression(node) || ts.isArrayLiteralExpression(node))
+ return pure(node, seen);
+ if (ts.isIdentifier(node)) {
+ const symbol = checker.getSymbolAtLocation(node);
+ if (!symbol || seen.has(symbol)) return false;
+ const declaration =
+ symbol.declarations?.length === 1 ? symbol.declarations[0] : null;
+ return (
+ declaration &&
+ ts.isVariableDeclaration(declaration) &&
+ owned(declaration.initializer, new Set([...seen, symbol]))
+ );
+ }
+ if (
+ ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)
+ )
+ return (
+ owned(node.expression, seen) &&
+ member(node) !== null &&
+ !['constructor', 'prototype', '__proto__'].includes(member(node))
+ );
+ return false;
+ }
+ const writes = new Set();
+ const globalWrites = new Set();
+ const collectWrites = (node) => {
+ if (
+ (ts.isBinaryExpression(node) &&
+ ts.isAssignmentOperator(node.operatorToken.kind)) ||
+ ((ts.isPrefixUnaryExpression(node) ||
+ ts.isPostfixUnaryExpression(node)) &&
+ [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(
+ node.operator
+ ))
+ ) {
+ const target = unwrap(
+ ts.isBinaryExpression(node) ? node.left : node.operand
+ );
+ if (ts.isIdentifier(target)) {
+ const symbol = checker.getSymbolAtLocation(target);
+ if (symbol) writes.add(symbol);
+ else globalWrites.add(target.text);
+ }
+ }
+ ts.forEachChild(node, collectWrites);
+ };
+ collectWrites(ast);
+ function bindingSymbol(node) {
+ const parent = node.parent;
+ if (
+ ts.isExportSpecifier(parent) &&
+ !parent.parent.parent.moduleSpecifier &&
+ node === (parent.propertyName ?? parent.name)
+ )
+ return checker.getExportSpecifierLocalTargetSymbol(parent);
+ return checker.getSymbolAtLocation(node);
+ }
+ function declaration(node) {
+ const symbol = bindingSymbol(node);
+ return symbol && !writes.has(symbol) && symbol.declarations?.length === 1
+ ? symbol.declarations[0]
+ : null;
+ }
+ function immutable(node, seen = new Set()) {
+ if (!ts.isIdentifier(node)) return null;
+ const decl = declaration(node);
+ if (
+ !decl ||
+ !ts.isVariableDeclaration(decl) ||
+ !decl.initializer ||
+ !(decl.parent.flags & ts.NodeFlags.Const) ||
+ seen.has(decl)
+ )
+ return null;
+ return { node: decl.initializer, seen: new Set([...seen, decl]) };
+ }
+ // Reject writes and namespace escapes independently from successful sink
+ // resolution, so losing a binding's trust can never hide its capability.
+ function capabilityBinding(node) {
+ const symbol = bindingSymbol(node);
+ const decl =
+ symbol?.declarations?.length === 1 ? symbol.declarations[0] : null;
+ if (decl && ts.isImportSpecifier(decl))
+ return identity(
+ decl.parent.parent.parent.moduleSpecifier.text,
+ (decl.propertyName ?? decl.name).text
+ );
+ if (decl && ts.isNamespaceImport(decl))
+ return identity(decl.parent.parent.moduleSpecifier.text, null) === 'goto'
+ ? 'navigationNamespace'
+ : null;
+ return null;
+ }
+ function imported(node) {
+ node = unwrap(node);
+ if (ts.isIdentifier(node)) {
+ const decl = declaration(node);
+ if (
+ decl &&
+ ts.isImportSpecifier(decl) &&
+ !decl.isTypeOnly &&
+ !decl.parent.parent.isTypeOnly
+ )
+ return identity(
+ decl.parent.parent.parent.moduleSpecifier.text,
+ (decl.propertyName ?? decl.name).text
+ );
+ }
+ if (
+ ts.isPropertyAccessExpression(node) &&
+ ts.isIdentifier(node.expression)
+ ) {
+ const decl = declaration(node.expression);
+ if (decl && ts.isNamespaceImport(decl) && !decl.parent.isTypeOnly)
+ return identity(
+ decl.parent.parent.moduleSpecifier.text,
+ node.name.text
+ );
+ }
+ return null;
+ }
+ function strings(node, seen = new Set()) {
+ node = unwrap(node);
+ if (!node) return null;
+ if (ts.isStringLiteralLike(node)) return [node.text];
+ const alias = immutable(node, seen);
+ if (alias) return strings(alias.node, alias.seen);
+ if (ts.isConditionalExpression(node)) {
+ const a = strings(node.whenTrue, seen),
+ b = strings(node.whenFalse, seen);
+ return a && b && a.length + b.length <= 64 ? [...a, ...b] : null;
+ }
+ if (
+ ts.isBinaryExpression(node) &&
+ node.operatorToken.kind === ts.SyntaxKind.PlusToken
+ ) {
+ const a = strings(node.left, seen),
+ b = strings(node.right, seen);
+ return a && b && a.length * b.length <= 64
+ ? a.flatMap((x) => b.map((y) => x + y))
+ : null;
+ }
+ if (ts.isTemplateExpression(node)) {
+ let result = [node.head.text];
+ for (const span of node.templateSpans) {
+ const part = strings(span.expression, seen);
+ if (!part || result.length * part.length > 64) return null;
+ result = result.flatMap((x) =>
+ part.map((y) => x + y + span.literal.text)
+ );
+ }
+ return result;
+ }
+ return null;
+ }
+ function forbiddenCharacters(value) {
+ return [...value].some((character) => {
+ const code = character.charCodeAt(0);
+ return code < 32 || (code >= 127 && code <= 159) || character === '\\';
+ });
+ }
+ function safeText(value, internal) {
+ if (
+ !value ||
+ value.length > 8192 ||
+ !value.isWellFormed() ||
+ Buffer.byteLength(value) > 8192 ||
+ /\s/u.test(value) ||
+ forbiddenCharacters(value)
+ )
+ return false;
+ try {
+ if (forbiddenCharacters(decodeURIComponent(value))) return false;
+ const local =
+ (value[0] === '/' && value[1] !== '/') || ['?', '#'].includes(value[0]);
+ if (!local && (internal || !/^(https:\/\/|mailto:|tel:)/i.test(value)))
+ return false;
+ if (/^https:/i.test(value) && !/^https:\/\/[^/?#]/i.test(value))
+ return false;
+ const url = new URL(value, 'https://navigation.invalid');
+ return (
+ !url.username &&
+ !url.password &&
+ !/^https:\/\/[^/?#]*@/i.test(value) &&
+ (local || url.protocol === 'https:' || !url.host) &&
+ (local ? url.origin === 'https://navigation.invalid' : !!url.pathname)
+ );
+ } catch {
+ return false;
+ }
+ }
+ function urlValue(node, internal, defined = false) {
+ // Casts and non-null assertions are never evidence of runtime admission.
+ while (ts.isParenthesizedExpression(node)) node = node.expression;
+ const values = strings(node);
+ if (values) return values.every((value) => safeText(value, internal));
+ if (
+ ts.isCallExpression(node) &&
+ node.arguments.length === 1 &&
+ ['internalHref', ...(internal ? [] : ['navigationHref'])].includes(
+ imported(node.expression)
+ )
+ )
+ return !defined;
+ const alias = immutable(node);
+ if (
+ defined &&
+ alias &&
+ ts.isCallExpression(alias.node) &&
+ urlValue(alias.node, internal)
+ ) {
+ let child = node;
+ for (
+ let parent = node.parent;
+ parent;
+ child = parent, parent = parent.parent
+ ) {
+ if (ts.isIfStatement(parent) && parent.thenStatement === child) {
+ const condition = parent.expression;
+ if (
+ ts.isIdentifier(condition) &&
+ checker.getSymbolAtLocation(condition) ===
+ checker.getSymbolAtLocation(node)
+ )
+ return true;
+ if (
+ ts.isBinaryExpression(condition) &&
+ condition.operatorToken.kind ===
+ ts.SyntaxKind.ExclamationEqualsEqualsToken &&
+ ts.isIdentifier(condition.left) &&
+ checker.getSymbolAtLocation(condition.left) ===
+ checker.getSymbolAtLocation(node) &&
+ ts.isIdentifier(condition.right) &&
+ condition.right.text === 'undefined' &&
+ !checker.getSymbolAtLocation(condition.right)?.declarations?.length
+ )
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ function global(node, names) {
+ return (
+ ts.isIdentifier(node) &&
+ names.includes(node.text) &&
+ !checker.getSymbolAtLocation(node)
+ );
+ }
+ function location(node) {
+ return (
+ global(node, ['location']) ||
+ (ts.isPropertyAccessExpression(node) &&
+ node.name.text === 'location' &&
+ global(node.expression, ['window', 'globalThis', 'self']))
+ );
+ }
+ function locationSink(node) {
+ if (
+ ts.isCallExpression(node) &&
+ ts.isPropertyAccessExpression(node.expression) &&
+ ['assign', 'replace'].includes(node.expression.name.text) &&
+ location(node.expression.expression)
+ )
+ return (
+ node.arguments.length === 1 && urlValue(node.arguments[0], true, true)
+ );
+ if (
+ ts.isBinaryExpression(node) &&
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
+ (location(node.left) ||
+ (ts.isPropertyAccessExpression(node.left) &&
+ node.left.name.text === 'href' &&
+ location(node.left.expression)))
+ )
+ return urlValue(node.right, true, true);
+ return false;
+ }
+ function locationUse(node) {
+ let top = node;
+ while (
+ top.parent &&
+ ((ts.isPropertyAccessExpression(top.parent) &&
+ top.parent.expression === top) ||
+ (ts.isCallExpression(top.parent) && top.parent.expression === top))
+ )
+ top = top.parent;
+ if (
+ top.parent &&
+ ts.isBinaryExpression(top.parent) &&
+ top.parent.left === top
+ )
+ top = top.parent;
+ return locationSink(top);
+ }
+ function callback(node) {
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) return true;
+ const decl = ts.isIdentifier(node) && declaration(node);
+ if (decl && ts.isFunctionDeclaration(decl)) return true;
+ const alias = immutable(node);
+ return (
+ !!alias &&
+ (ts.isArrowFunction(alias.node) || ts.isFunctionExpression(alias.node))
+ );
+ }
+ function timerUse(node) {
+ const parent = node.parent;
+ return (
+ ts.isCallExpression(parent) &&
+ parent.expression === node &&
+ parent.arguments.length >= 1 &&
+ callback(parent.arguments[0])
+ );
+ }
+ function collection(node) {
+ const alias = immutable(node);
+ return (
+ !!alias &&
+ ts.isNewExpression(alias.node) &&
+ global(alias.node.expression, ['Set']) &&
+ !globalWrites.has('Set') &&
+ (!alias.node.arguments?.length ||
+ (alias.node.arguments.length === 1 &&
+ ts.isArrayLiteralExpression(alias.node.arguments[0]) &&
+ pure(alias.node.arguments[0])))
+ );
+ }
+ function stringReceiver(node, seen = new Set()) {
+ if (strings(node)) return true;
+ const alias = immutable(unwrap(node), seen);
+ if (alias) return stringReceiver(alias.node, alias.seen);
+ node = unwrap(node);
+ return (
+ ts.isCallExpression(node) &&
+ ts.isPropertyAccessExpression(node.expression) &&
+ node.expression.name.text === 'replace' &&
+ node.arguments.length === 2 &&
+ stringReceiver(node.expression.expression, seen) &&
+ (ts.isRegularExpressionLiteral(node.arguments[0]) ||
+ !!strings(node.arguments[0])) &&
+ !!strings(node.arguments[1])
+ );
+ }
+ function primitiveMethod(node) {
+ const call = node.parent;
+ if (
+ !ts.isPropertyAccessExpression(node) ||
+ !ts.isCallExpression(call) ||
+ call.expression !== node
+ )
+ return false;
+ if (node.name.text === 'add')
+ return (
+ collection(node.expression) &&
+ call.arguments.length === 1 &&
+ pure(call.arguments[0])
+ );
+ if (node.name.text === 'replace')
+ return (
+ stringReceiver(node.expression) &&
+ call.arguments.length === 2 &&
+ (ts.isRegularExpressionLiteral(call.arguments[0]) ||
+ !!strings(call.arguments[0])) &&
+ !!strings(call.arguments[1])
+ );
+ return false;
+ }
+ const animationMethods = new Set(['animate', 'setKeyframes']);
+ const methods = new Set([
+ ...animationMethods,
+ 'setAttribute',
+ 'setAttributeNS',
+ 'toggleAttribute',
+ 'removeAttribute',
+ 'removeAttributeNS',
+ 'setAttributeNode',
+ 'setAttributeNodeNS',
+ 'removeAttributeNode',
+ 'setNamedItem',
+ 'setNamedItemNS',
+ 'removeNamedItem',
+ 'removeNamedItemNS',
+ 'add',
+ 'remove',
+ 'replace',
+ 'toggle',
+ 'setProperty',
+ 'removeProperty',
+ 'appendRule',
+ 'deleteRule',
+ 'insertRule',
+ 'replaceSync',
+ 'append',
+ 'prepend',
+ 'appendChild',
+ 'insertBefore',
+ 'insertAdjacentElement',
+ 'insertAdjacentHTML',
+ 'replaceChild',
+ 'replaceChildren',
+ 'removeChild',
+ 'before',
+ 'after',
+ 'replaceWith',
+ 'write',
+ 'writeln',
+ 'insertNode',
+ 'surroundContents',
+ 'createContextualFragment',
+ 'execCommand',
+ 'load',
+ 'setHTML',
+ 'setHTMLUnsafe',
+ '__defineGetter__',
+ '__defineSetter__',
+ 'push',
+ 'unshift',
+ 'splice'
+ ]);
+ const navigatorCapabilities = new Set([
+ 'clipboard',
+ 'locks',
+ 'storage',
+ 'onLine',
+ 'language',
+ 'languages',
+ 'userAgent',
+ 'platform',
+ 'hardwareConcurrency',
+ 'cookieEnabled'
+ ]);
+ const navigatorLeaf = (node) =>
+ ts.isPropertyAccessExpression(node.parent) &&
+ node.parent.expression === node &&
+ navigatorCapabilities.has(node.parent.name.text);
+ function inspect(node) {
+ const admittedLocation = locationSink(node);
+ if (
+ ts.isCallExpression(node) &&
+ imported(node.expression) === 'goto' &&
+ (node.arguments.length < 1 || !urlValue(node.arguments[0], true, true))
+ )
+ report('navigation goto requires a defined validated internal URL');
+ if (
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ /^__hcr(?:Navigation|Resource)Url$/.test(node.expression.text)
+ ) {
+ const internal = node.expression.text === '__hcrResourceUrl';
+ if (
+ node.arguments.length !== 1 ||
+ !urlValue(node.arguments[0], internal) ||
+ (internal && !strings(node.arguments[0]))
+ )
+ report('unresolved or unsafe markup URL');
+ }
+ if (
+ ts.isBinaryExpression(node) &&
+ ts.isAssignmentOperator(node.operatorToken.kind) &&
+ !admittedLocation
+ ) {
+ const left = unwrap(node.left);
+ if (
+ (ts.isPropertyAccessExpression(left) ||
+ ts.isElementAccessExpression(left)) &&
+ (!owned(left.expression) || !pure(node.right))
+ )
+ report(
+ 'opaque DOM/object mutations are forbidden; use owned plain model data'
+ );
+ if (ts.isIdentifier(left) && owned(left) && !pure(node.right))
+ report('owned model reassignment cannot introduce opaque capabilities');
+ if (
+ ts.isArrayLiteralExpression(left) ||
+ ts.isObjectLiteralExpression(left)
+ )
+ report(
+ 'bulk mutation targets must use the admitted plain-model grammar'
+ );
+ }
+ if (
+ ((ts.isPrefixUnaryExpression(node) ||
+ ts.isPostfixUnaryExpression(node)) &&
+ [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(
+ node.operator
+ )) ||
+ ts.isDeleteExpression(node)
+ ) {
+ const operand = unwrap(
+ ts.isDeleteExpression(node) ? node.expression : node.operand
+ );
+ if (
+ (ts.isPropertyAccessExpression(operand) ||
+ ts.isElementAccessExpression(operand)) &&
+ !owned(operand.expression)
+ )
+ report('opaque DOM/object update/delete mutations are forbidden');
+ }
+ if (
+ ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)
+ ) {
+ const computedNames = ts.isElementAccessExpression(node)
+ ? strings(node.argumentExpression)
+ : null;
+ const name =
+ member(node) ?? (computedNames?.length === 1 ? computedNames[0] : null);
+ if (
+ computedNames?.some((name) => animationMethods.has(name)) &&
+ !owned(node.expression)
+ )
+ report(
+ 'opaque or indirect animation mutation/setter APIs are forbidden'
+ );
+ if (
+ imported(node) === 'goto' &&
+ !(ts.isCallExpression(node.parent) && node.parent.expression === node)
+ )
+ report('escaped goto capability is forbidden');
+ if (location(node) && !locationUse(node))
+ report('opaque Location capability is forbidden');
+ if (
+ ['setTimeout', 'setInterval'].includes(name) &&
+ global(node.expression, ['window', 'globalThis', 'self'])
+ )
+ report('indirect timer capability is forbidden');
+ if (
+ name === 'navigator' &&
+ ts.isIdentifier(node.expression) &&
+ ['window', 'globalThis', 'self'].includes(node.expression.text) &&
+ !checker.getSymbolAtLocation(node.expression) &&
+ !navigatorLeaf(node)
+ )
+ report('opaque navigator capabilities cannot expose worker loaders');
+ if (['constructor', 'prototype', '__proto__'].includes(name))
+ report(
+ 'prototype capability access is outside the admitted DOM/model grammar'
+ );
+ if (
+ [
+ 'currentTarget',
+ 'target',
+ 'ownerDocument',
+ 'contentDocument',
+ 'contentWindow',
+ 'defaultView',
+ 'composedPath',
+ 'getRootNode'
+ ].includes(name) &&
+ !owned(node.expression) &&
+ !uiLeaf(node)
+ )
+ report(
+ 'opaque DOM capabilities cannot escape direct UI leaf operations'
+ );
+ const locationMethod =
+ ts.isPropertyAccessExpression(node) &&
+ ['assign', 'replace'].includes(name) &&
+ location(node.expression) &&
+ locationUse(node);
+ if (
+ methods.has(name) &&
+ !primitiveMethod(node) &&
+ !locationMethod &&
+ !(
+ animationMethods.has(name) &&
+ owned(node.expression) &&
+ !ts.isCallExpression(node.parent)
+ )
+ ) {
+ if (
+ !ts.isCallExpression(node.parent) ||
+ node.parent.expression !== node ||
+ !owned(node.expression) ||
+ !node.parent.arguments.every((argument) => pure(argument))
+ )
+ report('opaque or indirect DOM mutation/setter APIs are forbidden');
+ }
+ }
+ if (ts.isIdentifier(node)) {
+ const parent = node.parent;
+ if (
+ collection(node) &&
+ !(ts.isVariableDeclaration(parent) && parent.name === node) &&
+ !(
+ ts.isPropertyAccessExpression(parent) &&
+ parent.expression === node &&
+ ((['add', 'has'].includes(parent.name.text) &&
+ ts.isCallExpression(parent.parent) &&
+ parent.parent.expression === parent &&
+ parent.parent.arguments.every((argument) => pure(argument))) ||
+ parent.name.text === 'size')
+ )
+ )
+ report(
+ 'owned collection capabilities cannot escape direct data operations'
+ );
+ const capability = capabilityBinding(node);
+ if (capability && writes.has(checker.getSymbolAtLocation(node)))
+ report('reassigned navigation capability is forbidden');
+ if (
+ capability === 'navigationNamespace' &&
+ !ts.isNamespaceImport(parent) &&
+ !(
+ ts.isPropertyAccessExpression(parent) &&
+ parent.expression === node &&
+ parent.name.text === 'goto' &&
+ ts.isCallExpression(parent.parent) &&
+ parent.parent.expression === parent
+ )
+ )
+ report('escaped navigation namespace is forbidden');
+ const propertyName =
+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
+ (ts.isPropertyAssignment(parent) &&
+ parent.name === node &&
+ !ts.isShorthandPropertyAssignment(parent));
+ const typeName =
+ ts.isTypeReferenceNode(parent) || ts.isTypeQueryNode(parent);
+ const symbol = checker.getSymbolAtLocation(node);
+ if (
+ !propertyName &&
+ !typeName &&
+ !symbol &&
+ ['KeyframeEffect', 'Animation'].includes(node.text)
+ )
+ report('imperative animation constructors are forbidden');
+ if (
+ !propertyName &&
+ !typeName &&
+ !symbol &&
+ node.text === 'Set' &&
+ globalWrites.has('Set')
+ )
+ report('global Set constructor rebinding is forbidden');
+ if (
+ !propertyName &&
+ !typeName &&
+ !symbol &&
+ ['setTimeout', 'setInterval'].includes(node.text) &&
+ !timerUse(node)
+ )
+ report('timer requires a direct function callback');
+ if (
+ !propertyName &&
+ !typeName &&
+ global(node, ['location']) &&
+ !locationUse(node)
+ )
+ report('opaque Location capability is forbidden');
+ if (
+ imported(node) === 'goto' &&
+ !(
+ ts.isImportSpecifier(parent) ||
+ (ts.isCallExpression(parent) && parent.expression === node)
+ )
+ )
+ report('escaped goto capability is forbidden');
+ if (!propertyName && !typeName && !symbol) {
+ if (node.text === 'navigator' && !navigatorLeaf(node))
+ report('opaque navigator capabilities cannot expose worker loaders');
+ if (
+ node.text === 'document' &&
+ !uiLeaf(node) &&
+ !ts.isTypeOfExpression(parent)
+ )
+ report('DOM handles cannot escape the bounded direct UI grammar');
+ if (
+ [
+ 'window',
+ 'globalThis',
+ 'self',
+ 'top',
+ 'parent',
+ 'frames',
+ 'opener'
+ ].includes(node.text) &&
+ !ts.isTypeOfExpression(parent)
+ ) {
+ if (
+ !ts.isPropertyAccessExpression(parent) ||
+ parent.expression !== node ||
+ !['nostr', 'indexedDB', 'crypto', 'navigator', 'location'].includes(
+ parent.name.text
+ )
+ )
+ report('opaque browser/DOM global capability access is forbidden');
+ }
+ if (
+ /^(?:Document|Node|Element|DOMParser|DOMImplementation|Range|XPathEvaluator|XSLTProcessor|HTML\w*Element|SVG\w*Element|CSS\w*|DOMTokenList|NamedNodeMap|Attr)$/.test(
+ node.text
+ )
+ )
+ report(
+ 'native DOM/resource constructors are outside the admitted UI grammar'
+ );
+ if (['Object', 'Reflect'].includes(node.text)) {
+ if (
+ !ts.isPropertyAccessExpression(parent) ||
+ parent.expression !== node ||
+ !ts.isCallExpression(parent.parent) ||
+ parent.parent.expression !== parent ||
+ !parent.parent.arguments.every((argument) => pure(argument))
+ )
+ report(
+ 'reflection/bulk operations require direct calls over owned plain data'
+ );
+ }
+ }
+ }
+ for (const doc of node.jsDoc ?? []) inspect(doc);
+ ts.forEachChild(node, inspect);
+ }
+ inspect(ast);
+ return owned;
+}
+
+function literal(node) {
+ if (ts.isStringLiteralLike(node)) return node.text;
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
+ if (ts.isArrayLiteralExpression(node)) return node.elements.map(literal);
+ if (ts.isObjectLiteralExpression(node)) {
+ const value = Object.create(null);
+ for (const property of node.properties) {
+ if (
+ !ts.isPropertyAssignment(property) ||
+ !property.name ||
+ (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name))
+ )
+ throw new Error('Import configuration must use literal properties');
+ const key = property.name.text;
+ if (Object.hasOwn(value, key))
+ throw new Error('Duplicate import configuration property');
+ value[key] = literal(property.initializer);
+ }
+ return value;
+ }
+ throw new Error('Import configuration must be statically resolvable');
+}
+
+async function configuration(root) {
+ for (const name of await readdir(root)) {
+ if (/^(vite|svelte)\.config\.(js|mjs|cjs|mts|cts)$/.test(name))
+ throw new Error(`Unsupported competing source configuration: ${name}`);
+ }
+ const pkg = JSON.parse(await readSource(path.join(root, 'package.json')));
+ const configText = await readSource(path.join(root, 'tsconfig.json'));
+ const parsed = ts.parseConfigFileTextToJson('tsconfig.json', configText);
+ if (parsed.error) throw new Error('Invalid tsconfig.json');
+ const config = parsed.config;
+ if (config.extends !== '$app/tsconfig' || config.compilerOptions?.baseUrl)
+ throw new Error('Unsupported TypeScript import configuration');
+ const vite = sourceAst(
+ 'vite.config.ts',
+ await readSource(path.join(root, 'vite.config.ts'))
+ );
+ const defaults = vite.statements.filter(ts.isExportAssignment);
+ if (
+ defaults.length !== 1 ||
+ !ts.isCallExpression(defaults[0].expression) ||
+ defaults[0].expression.expression.getText(vite) !== 'defineConfig'
+ )
+ throw new Error('Vite configuration must be statically resolvable');
+ const object = defaults[0].expression.arguments[0];
+ if (!object || !ts.isObjectLiteralExpression(object))
+ throw new Error('Vite configuration must be a literal object');
+ const aliases = [];
+ const configKeys = new Set();
+ for (const property of object.properties) {
+ if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name))
+ throw new Error('Unsupported Vite import configuration');
+ const key = property.name.text;
+ if (configKeys.has(key))
+ throw new Error('Duplicate Vite configuration property');
+ configKeys.add(key);
+ if (key === 'plugins') {
+ // Keep the existing Kit3/static adapter pipeline. Arbitrary plugins can
+ // rewrite imports invisibly; they require explicit guard support.
+ const normalized = property.initializer.getText(vite).replace(/\s/g, '');
+ if (
+ normalized !==
+ "[sveltekit({adapter:adapter({strict:true,fallback:'200.html'})})]" &&
+ normalized !==
+ '[sveltekit({adapter:adapter({strict:true,fallback:"200.html"})})]'
+ )
+ throw new Error('Unsupported Vite source transformation');
+ } else if (key === 'resolve') {
+ const resolve = literal(property.initializer);
+ if (Object.keys(resolve).some((name) => name !== 'alias'))
+ throw new Error('Unsupported Vite resolution option');
+ const values = Array.isArray(resolve.alias)
+ ? resolve.alias
+ : Object.entries(resolve.alias ?? {}).map(([find, replacement]) => ({
+ find,
+ replacement
+ }));
+ for (const value of values) {
+ if (
+ typeof value.find !== 'string' ||
+ typeof value.replacement !== 'string'
+ )
+ throw new Error('Unsupported Vite alias');
+ aliases.push(value);
+ }
+ } else throw new Error(`Unsupported Vite configuration property: ${key}`);
+ }
+ // Configuration must not execute hidden resolver mutation before defineConfig.
+ for (const statement of vite.statements) {
+ if (ts.isImportDeclaration(statement)) {
+ const imported = statement.moduleSpecifier.text;
+ const clause = statement.importClause;
+ const expected = imported === 'vite' ? 'defineConfig' : 'sveltekit';
+ if (imported === '@sveltejs/adapter-static') {
+ if (!clause || clause.name?.text !== 'adapter' || clause.namedBindings)
+ throw new Error('Unsupported Vite adapter binding');
+ } else if (
+ !clause ||
+ clause.name ||
+ !clause.namedBindings ||
+ !ts.isNamedImports(clause.namedBindings) ||
+ clause.namedBindings.elements.length !== 1 ||
+ clause.namedBindings.elements[0].propertyName ||
+ clause.namedBindings.elements[0].name.text !== expected
+ )
+ throw new Error('Unsupported Vite resolver binding');
+ if (
+ !['vite', '@sveltejs/kit/vite', '@sveltejs/adapter-static'].includes(
+ imported
+ )
+ )
+ throw new Error(`Unsupported Vite config import: ${imported}`);
+ } else if (!ts.isExportAssignment(statement))
+ throw new Error('Unsupported Vite configuration statement');
+ }
+ for (const [find, replacements] of Object.entries(
+ config.compilerOptions?.paths ?? {}
+ )) {
+ if (
+ !Array.isArray(replacements) ||
+ replacements.length !== 1 ||
+ typeof replacements[0] !== 'string'
+ )
+ throw new Error('Unsupported TypeScript path mapping');
+ // Audit TS mappings as well as Vite mappings, so a second resolution
+ // surface cannot hide an unsafe target from source checks.
+ aliases.push({ find, replacement: replacements[0], typescript: true });
+ }
+ return { pkg, aliases };
+}
+
+export async function auditSource(root) {
+ root = path.resolve(root);
+ const sourceRoot = path.join(root, 'src');
+ const files = new Map();
+ const findings = [];
+ const allowedCss = new Set(['src/theme.css', 'src/app.css']);
+ const complain = (file, message) =>
+ findings.push(`${relative(root, file)}: ${message}`);
+ async function inventory(directory) {
+ const before = await lstat(directory);
+ if (
+ !before.isDirectory() ||
+ before.isSymbolicLink() ||
+ (await realpath(directory)) !== directory
+ )
+ throw new Error(`Unsafe source directory: ${directory}`);
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const file = path.join(directory, entry.name);
+ const stat = await lstat(file);
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
+ complain(
+ file,
+ 'source symlinks/nonregular source entries are forbidden'
+ );
+ continue;
+ }
+ if (stat.isDirectory()) await inventory(file);
+ else files.set(file, await readSource(file));
+ }
+ const after = await lstat(directory);
+ if (
+ before.dev !== after.dev ||
+ before.ino !== after.ino ||
+ before.mtimeMs !== after.mtimeMs ||
+ before.ctimeMs !== after.ctimeMs
+ )
+ throw new Error(`Source directory changed during audit: ${directory}`);
+ }
+ await inventory(sourceRoot);
+ const { pkg, aliases } = await configuration(root);
+ const dependencies = { ...pkg.dependencies, ...pkg.devDependencies };
+ const cssImports = [];
+ function local(file, target, specifier) {
+ if (
+ !inside(sourceRoot, target) ||
+ forbiddenPath.test(relative(sourceRoot, target))
+ ) {
+ complain(file, `forbidden production import ${specifier}`);
+ return;
+ }
+ const candidates = [
+ target,
+ ...[
+ '.ts',
+ '.tsx',
+ '.js',
+ '.jsx',
+ '.mts',
+ '.mjs',
+ '.cts',
+ '.cjs',
+ '.svelte'
+ ].map((extension) => target + extension),
+ ...['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.svelte'].map(
+ (extension) => path.join(target, 'index' + extension)
+ )
+ ];
+ // TypeScript source commonly retains a .js extension for its emitted path.
+ if (/\.[cm]?js$/.test(target))
+ candidates.push(
+ target
+ .replace(/\.js$/, '.ts')
+ .replace(/\.mjs$/, '.mts')
+ .replace(/\.cjs$/, '.cts')
+ );
+ const found = candidates.find((candidate) => files.has(candidate));
+ if (!found)
+ return complain(file, `unresolved production import ${specifier}`);
+ const name = relative(root, found);
+ if (/\.(css|scss|sass|less)$/.test(found)) {
+ if (
+ relative(root, file) !== 'src/routes/+layout.svelte' ||
+ !allowedCss.has(name)
+ )
+ complain(file, 'CSS must be imported by the root layout');
+ else cssImports.push(name);
+ } else if (!codeExtension.test(found))
+ complain(file, `unsupported production import ${specifier}`);
+ return found;
+ }
+ function resolve(file, specifier, seen = new Set(), unrestricted = false) {
+ if (
+ typeof specifier !== 'string' ||
+ /[\\?#]/.test(specifier.replace(/^#/, '')) ||
+ [...specifier].some((character) => character.charCodeAt(0) <= 32) ||
+ specifier.includes('%') ||
+ specifier.startsWith('/')
+ )
+ return complain(file, `unsafe production import ${specifier}`);
+ if (seen.has(specifier))
+ return complain(file, `cyclic import alias ${specifier}`);
+ seen = new Set([...seen, specifier]);
+ const matches = aliases.filter(({ find }) =>
+ find.includes('*')
+ ? specifier.startsWith(find.split('*')[0]) &&
+ specifier.endsWith(find.split('*')[1])
+ : specifier === find ||
+ (!find.startsWith('#') && specifier.startsWith(find + '/'))
+ );
+ if (matches.length) {
+ const identities = [];
+ for (const alias of matches) {
+ const tail = alias.find.includes('*')
+ ? specifier.slice(
+ alias.find.indexOf('*'),
+ specifier.length - alias.find.split('*')[1].length || undefined
+ )
+ : specifier.slice(alias.find.length);
+ const target = alias.replacement.includes('*')
+ ? alias.replacement.replace('*', tail)
+ : alias.replacement + tail;
+ if (
+ alias.typescript ||
+ target.startsWith('.') ||
+ path.isAbsolute(target)
+ )
+ identities.push(local(file, path.resolve(root, target), specifier));
+ else identities.push(resolve(file, target, seen, unrestricted));
+ }
+ return identities.every((value) => value === identities[0])
+ ? identities[0]
+ : null;
+ }
+ if (specifier.startsWith('#')) {
+ const entries = Object.entries(pkg.imports ?? {}).filter(
+ ([key]) =>
+ key === specifier ||
+ (key.endsWith('/*') && specifier.startsWith(key.slice(0, -1)))
+ );
+ if (!entries.length)
+ return complain(file, `unresolved production import ${specifier}`);
+ // Audit all conditions, not only the current host's default branch.
+ const targets = (value) =>
+ typeof value === 'string'
+ ? [value]
+ : value && typeof value === 'object' && !Array.isArray(value)
+ ? Object.values(value).flatMap(targets)
+ : (() => {
+ throw new Error(`Unsafe package import ${specifier}`);
+ })();
+ const identities = [];
+ for (const [key, value] of entries)
+ for (const raw of targets(value)) {
+ const target = key.endsWith('/*')
+ ? raw.replace('*', specifier.slice(key.length - 1))
+ : raw;
+ if (target.startsWith('.'))
+ identities.push(local(file, path.resolve(root, target), specifier));
+ else identities.push(resolve(file, target, seen, unrestricted));
+ }
+ return identities.every((value) => value === identities[0])
+ ? identities[0]
+ : null;
+ }
+ if (specifier.startsWith('.'))
+ return local(
+ file,
+ path.resolve(path.dirname(file), specifier),
+ specifier
+ );
+ if (frameworkModules.has(specifier)) return specifier;
+ const packageName = specifier.startsWith('@')
+ ? specifier.split('/').slice(0, 2).join('/')
+ : specifier.split('/')[0];
+ const declared = dependencies[packageName];
+ const actualName =
+ typeof declared === 'string' && declared.startsWith('npm:')
+ ? declared.slice(4).replace(/@[^@]*$/, '')
+ : packageName;
+ if (
+ unrestricted &&
+ actualName === 'svelte' &&
+ !specifier.slice(packageName.length).startsWith('/store')
+ )
+ return complain(
+ file,
+ 'unrestricted Svelte raw-render module access is forbidden'
+ );
+ const actualImport = actualName + specifier.slice(packageName.length);
+ if (
+ (actualName === '@sveltejs/kit' &&
+ !['@sveltejs/kit', '@sveltejs/kit/hooks'].includes(actualImport)) ||
+ (actualName === 'svelte' &&
+ /^(svelte\/(compiler|internal|server|attachments|package\.json))/.test(
+ actualImport
+ ))
+ )
+ return complain(file, `forbidden production import ${specifier}`);
+ if (
+ applesauce.has(actualName) &&
+ !relative(root, file).startsWith('src/lib/nostr/')
+ )
+ complain(file, 'Applesauce imports belong in lib/nostr');
+ if (
+ !runtimePackages.has(actualName) ||
+ typeof declared !== 'string' ||
+ /^(file:|link:|workspace:|git|https?:|\.\.?\/)/.test(declared)
+ )
+ return complain(file, `forbidden production import ${specifier}`);
+ if (
+ !/^(?:npm:(?:@[^/]+\/)?[^@]+@)?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(
+ declared
+ )
+ )
+ return complain(file, `unpinned production import ${specifier}`);
+ // Direct package imports must be exported by the installed, pinned package;
+ // never search parent node_modules or fall back to a sibling workspace.
+ try {
+ const resolved = createRequire(path.join(root, 'package.json')).resolve(
+ specifier
+ );
+ if (!inside(path.join(root, 'node_modules'), resolved))
+ throw new Error('outside web dependencies');
+ } catch {
+ complain(file, `unresolved production import ${specifier}`);
+ }
+ }
+ const helperFile = path.join(root, 'src/lib/navigation-url.ts');
+ const helperPin =
+ '4ce96334d7cf57ccba518132078278b71d3bf70f519202e491a5f6a8840f7b19';
+ const helperTrusted =
+ files.has(helperFile) &&
+ createHash('sha256').update(files.get(helperFile)).digest('hex') ===
+ helperPin;
+ if (files.has(helperFile) && !helperTrusted)
+ complain(
+ helperFile,
+ 'navigation helper source identity does not match reviewed pin'
+ );
+ function exportIdentity(file, exported, seen = new Set()) {
+ const key = file + ':' + exported;
+ if (seen.has(key)) return null;
+ seen = new Set([...seen, key]);
+ if (file === '$app/navigation') return exported === 'goto' ? 'goto' : null;
+ if (
+ file === helperFile &&
+ helperTrusted &&
+ ['internalHref', 'navigationHref'].includes(exported)
+ )
+ return exported;
+ if (
+ !files.has(file) ||
+ !codeExtension.test(file) ||
+ file.endsWith('.svelte')
+ )
+ return null;
+ const ast = sourceAst(file, files.get(file));
+ const matches = [];
+ for (const node of ast.statements) {
+ if (
+ ts.isExportDeclaration(node) &&
+ !node.isTypeOnly &&
+ node.moduleSpecifier &&
+ node.exportClause &&
+ ts.isNamedExports(node.exportClause)
+ ) {
+ for (const element of node.exportClause.elements)
+ if (!element.isTypeOnly && element.name.text === exported)
+ matches.push(
+ exportIdentity(
+ resolve(file, node.moduleSpecifier.text),
+ (element.propertyName ?? element.name).text,
+ seen
+ )
+ );
+ }
+ }
+ return matches.length === 1 ? matches[0] : null;
+ }
+ function navigationExports(file, seen = new Set()) {
+ if (file === '$app/navigation') return true;
+ if (
+ seen.has(file) ||
+ !files.has(file) ||
+ !codeExtension.test(file) ||
+ file.endsWith('.svelte')
+ )
+ return false;
+ seen = new Set([...seen, file]);
+ const ast = sourceAst(file, files.get(file));
+ for (const node of ast.statements) {
+ if (
+ !ts.isExportDeclaration(node) ||
+ node.isTypeOnly ||
+ !node.moduleSpecifier
+ )
+ continue;
+ const target = resolve(file, node.moduleSpecifier.text);
+ if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
+ if (navigationExports(target, seen)) return true;
+ } else if (ts.isNamedExports(node.exportClause)) {
+ if (
+ node.exportClause.elements.some(
+ (element) =>
+ !element.isTypeOnly &&
+ exportIdentity(
+ target,
+ (element.propertyName ?? element.name).text
+ ) === 'goto'
+ )
+ )
+ return true;
+ }
+ }
+ return false;
+ }
+ for (const [file, content] of files) {
+ const name = relative(root, file);
+ if (/\.(css|scss|sass|less)$/.test(name) && !allowedCss.has(name))
+ complain(file, 'handwritten CSS belongs in theme.css or app.css');
+ if (/HC_TEST_ONLY_PROVIDER|HC_TEST_ONLY_SIGNER/.test(content))
+ complain(file, 'test provider code is forbidden in production');
+ if (forbiddenPath.test(relative(sourceRoot, file)))
+ complain(
+ file,
+ 'test/native/generated/credential source is forbidden in production'
+ );
+ if (allowedCss.has(name)) {
+ // CSS loading is outside the two handwritten-file contract. Decode
+ // escapes/comments before checking so escaped @import/url cannot hide.
+ const css = content
+ .replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_, hex) =>
+ String.fromCodePoint(parseInt(hex, 16))
+ )
+ .replace(/\\([^\r\n])/g, '$1')
+ .replace(/\/\*[\s\S]*?\*\//g, '');
+ if (/@import\b|url\s*\(/i.test(css))
+ complain(file, 'CSS import/url loading is forbidden');
+ }
+ const html = name === 'src/app.html';
+ if (!codeExtension.test(file) && !html) continue;
+ const scripts = [];
+ if (file.endsWith('.svelte') || html) {
+ const ast = parse(content, { modern: true });
+ if (ast.css)
+ complain(file, 'component CSS and inline styles are forbidden');
+ const staticAttribute = (attribute) => {
+ if (!attribute || attribute.type !== 'Attribute') return null;
+ if (
+ Array.isArray(attribute.value) &&
+ attribute.value.every((part) => part.type === 'Text')
+ )
+ return attribute.value.map((part) => part.data).join('');
+ if (
+ attribute.value?.type === 'ExpressionTag' &&
+ attribute.value.expression?.type === 'Literal' &&
+ typeof attribute.value.expression.value === 'string'
+ )
+ return attribute.value.expression.value;
+ return null;
+ };
+ const elementTag = (node) => {
+ const tag =
+ node.type === 'SvelteElement'
+ ? node.tag?.type === 'Literal' && typeof node.tag.value === 'string'
+ ? node.tag.value
+ : null
+ : node.name;
+ return tag?.toLowerCase().split(':').pop();
+ };
+ const inspectElement = (node) => {
+ const tag = elementTag(node);
+ if (node.type === 'SvelteElement' && !tag)
+ return complain(
+ file,
+ 'computed markup resource elements are forbidden'
+ );
+ if (declarativeMutationTags.has(tag))
+ complain(
+ file,
+ 'declarative SVG resource/style mutation is forbidden'
+ );
+ if (
+ [
+ 'script',
+ 'style',
+ 'iframe',
+ 'object',
+ 'embed',
+ 'applet',
+ 'base'
+ ].includes(tag)
+ )
+ complain(
+ file,
+ 'raw markup scripts/styles/embedded resources are forbidden'
+ );
+ const attributes = node.attributes ?? [];
+ const values = new Map();
+ for (const attribute of attributes) {
+ if (attribute.type === 'SpreadAttribute')
+ complain(file, 'computed markup attributes are forbidden');
+ if (attribute.type !== 'Attribute') continue;
+ const key = attribute.name.toLowerCase();
+ if (values.has(key))
+ complain(
+ file,
+ 'duplicate markup resource attributes are forbidden'
+ );
+ values.set(key, attribute);
+ const value = staticAttribute(attribute);
+ if (key === 'srcdoc')
+ complain(file, 'embedded markup documents are forbidden');
+ if (/^on[a-z]/.test(key) && (html || value !== null))
+ complain(file, 'raw markup event scripts are forbidden');
+ if (
+ ['href', 'src', 'xlink:href', 'action', 'formaction'].includes(
+ key
+ ) &&
+ value !== null &&
+ /^(?:javascript|vbscript|data):/i.test(
+ [...value]
+ .filter((character) => character.charCodeAt(0) > 32)
+ .join('')
+ )
+ )
+ complain(file, 'executable markup resource URLs are forbidden');
+ }
+ if (tag === 'link') {
+ const rel = staticAttribute(values.get('rel'));
+ const href = staticAttribute(values.get('href'));
+ const tokens = rel?.toLowerCase().trim().split(/\s+/) ?? [];
+ const safeRelations = new Set([
+ 'icon',
+ 'shortcut',
+ 'apple-touch-icon',
+ 'mask-icon',
+ 'canonical',
+ 'alternate',
+ 'author',
+ 'license',
+ 'help'
+ ]);
+ if (
+ !tokens.length ||
+ tokens.some((token) => !safeRelations.has(token))
+ )
+ complain(
+ file,
+ 'markup stylesheet/client resource links are forbidden'
+ );
+ // Resource selectors must stay literal. Spreads and computed href,
+ // rel, as, type or resource URLs cannot smuggle another loader mode.
+ if (
+ rel === null ||
+ href === null ||
+ ['as', 'type'].some(
+ (key) =>
+ values.has(key) && staticAttribute(values.get(key)) === null
+ )
+ )
+ complain(file, 'computed markup resource attributes are forbidden');
+ if (href !== null) {
+ const url = href.replace(/^%sveltekit.assets%/, '');
+ if (
+ /[\\\s]/.test(url) ||
+ [...url].some((character) => character.charCodeAt(0) < 32) ||
+ /^(?:javascript|vbscript|data):/i.test(url)
+ )
+ complain(file, 'unsafe markup resource URL');
+ if (
+ tokens.some((token) =>
+ ['icon', 'shortcut', 'apple-touch-icon', 'mask-icon'].includes(
+ token
+ )
+ ) &&
+ (!/^\/(?!\/)[a-zA-Z0-9_./-]+\.(?:ico|png|svg)$/.test(url) ||
+ url.split('/').includes('..'))
+ )
+ complain(
+ file,
+ 'favicon resources must use literal owned image paths'
+ );
+ }
+ }
+ if (tag === 'meta' && values.has('http-equiv')) {
+ const directive = staticAttribute(values.get('http-equiv'));
+ if (directive === null || directive.toLowerCase() === 'refresh')
+ complain(
+ file,
+ 'markup refresh/executable directives are forbidden'
+ );
+ }
+ };
+ const visit = (node) => {
+ if (!node || typeof node !== 'object') return;
+ if (
+ node.type === 'RegularElement' ||
+ node.type === 'SvelteElement' ||
+ (node.type === 'Component' &&
+ declarativeMutationTags.has(elementTag(node))) ||
+ (html && node.name && Array.isArray(node.attributes))
+ )
+ inspectElement(node);
+ if (
+ (node.type === 'BindDirective' && node.name === 'this') ||
+ [
+ 'UseDirective',
+ 'AttachTag',
+ 'TransitionDirective',
+ 'AnimateDirective'
+ ].includes(node.type)
+ )
+ complain(
+ file,
+ 'DOM bindings/actions/attachments cannot expose opaque mutation capabilities'
+ );
+ if (node.type === 'HtmlTag')
+ complain(file, 'raw markup injection is forbidden');
+ if (
+ node.type === 'StyleDirective' ||
+ (node.type === 'Attribute' && node.name.toLowerCase() === 'style')
+ )
+ complain(file, 'inline styles are forbidden');
+ for (const value of Object.values(node)) {
+ if (Array.isArray(value)) value.forEach(visit);
+ else if (value && typeof value === 'object') visit(value);
+ }
+ };
+ visit(ast.fragment);
+ for (const script of [ast.instance, ast.module]) {
+ if (!script) continue;
+ if (
+ html ||
+ script.attributes?.some(
+ (attribute) =>
+ !['lang', 'context', 'module'].includes(
+ attribute.name?.toLowerCase()
+ )
+ )
+ )
+ complain(
+ file,
+ 'inline HTML scripts or external scripts are forbidden'
+ );
+ }
+ const expression = (node) => content.slice(node.start, node.end);
+ const attributeExpression = (attribute) => {
+ const parts = Array.isArray(attribute.value)
+ ? attribute.value
+ : [attribute.value];
+ if (
+ !parts.length ||
+ parts.some(
+ (part) => !part || !['Text', 'ExpressionTag'].includes(part.type)
+ )
+ )
+ return 'undefined';
+ return parts
+ .map((part) =>
+ part.type === 'Text'
+ ? JSON.stringify(part.data)
+ : '(' + expression(part.expression) + ')'
+ )
+ .join(' + ');
+ };
+ // One lexical graph: module declarations enclose instance declarations,
+ // and template bindings enclose their own branch bodies. Detached
+ // expression parses cannot prove imported identity or shadowing.
+ const emit = (node) => {
+ if (!node || typeof node !== 'object') return '';
+ if (node.type === 'Fragment')
+ return '{' + node.nodes.map(emit).join('\n') + '}';
+ if (node.type === 'ConstTag')
+ return node.declaration.declarations
+ .map(
+ (decl) =>
+ 'const ' +
+ expression(decl.id) +
+ ' = ' +
+ expression(decl.init) +
+ ';'
+ )
+ .join('\n');
+ if (node.type === 'EachBlock')
+ return (
+ '(' +
+ expression(node.expression) +
+ '); { let ' +
+ expression(node.context) +
+ ';' +
+ (node.index ? 'let ' + node.index + ';' : '') +
+ (node.key ? '(' + expression(node.key) + ');' : '') +
+ emit(node.body) +
+ '}' +
+ emit(node.fallback)
+ );
+ if (node.type === 'SnippetBlock')
+ return (
+ 'function ' +
+ expression(node.expression) +
+ '(' +
+ node.parameters.map(expression).join(',') +
+ ')' +
+ emit(node.body)
+ );
+ if (node.type === 'AwaitBlock')
+ return (
+ '(' +
+ expression(node.expression) +
+ ');' +
+ emit(node.pending) +
+ '{' +
+ (node.value ? 'let ' + expression(node.value) + ';' : '') +
+ emit(node.then) +
+ '}{' +
+ (node.error ? 'let ' + expression(node.error) + ';' : '') +
+ emit(node.catch) +
+ '}'
+ );
+ let result = '';
+ if (node.attributes) {
+ const tag = elementTag(node);
+ for (const attribute of node.attributes) {
+ if (attribute.type === 'LetDirective')
+ result +=
+ 'let ' +
+ (attribute.expression
+ ? expression(attribute.expression)
+ : attribute.name) +
+ ';';
+ if (
+ node.type !== 'Component' &&
+ attribute.type === 'Attribute' &&
+ [
+ 'href',
+ 'src',
+ 'xlink:href',
+ 'action',
+ 'formaction',
+ 'srcset',
+ 'poster'
+ ].includes(attribute.name.toLowerCase())
+ ) {
+ const resource =
+ !(
+ (tag === 'a' || tag === 'area') &&
+ attribute.name.toLowerCase() === 'href'
+ ) &&
+ !['action', 'formaction'].includes(
+ attribute.name.toLowerCase()
+ );
+ let value = attributeExpression(attribute);
+ if (tag === 'link' && staticAttribute(attribute) !== null)
+ value = JSON.stringify(
+ staticAttribute(attribute).replace(/^%sveltekit.assets%/, '')
+ );
+ result +=
+ (resource ? '__hcrResourceUrl' : '__hcrNavigationUrl') +
+ '(' +
+ value +
+ ');';
+ if (['srcset', 'poster'].includes(attribute.name.toLowerCase()))
+ complain(file, 'media resource attributes are forbidden');
+ }
+ }
+ }
+ if (node.expression?.start !== undefined)
+ result += '(' + expression(node.expression) + ');';
+ for (const [key, value] of Object.entries(node)) {
+ if (
+ [
+ 'expression',
+ 'context',
+ 'parameters',
+ 'declaration',
+ 'error'
+ ].includes(key)
+ )
+ continue;
+ if (Array.isArray(value)) result += value.map(emit).join('\n');
+ else if (value && typeof value === 'object') result += emit(value);
+ }
+ return node.attributes ? '{' + result + '}' : result;
+ };
+ scripts.push(
+ (ast.module
+ ? content.slice(ast.module.content.start, ast.module.content.end)
+ : '') +
+ '\nfunction __hcrInstance() {\n' +
+ (ast.instance
+ ? content.slice(
+ ast.instance.content.start,
+ ast.instance.content.end
+ )
+ : '') +
+ '\n' +
+ emit(ast.fragment) +
+ '\n}'
+ );
+ } else scripts.push(content);
+ for (const script of scripts) {
+ const ast = sourceAst(file, script);
+ const ownedModel = mutationAdmission(
+ ast,
+ (message) => complain(file, message),
+ (specifier, exported) => {
+ const target = resolve(file, specifier);
+ return exported === null
+ ? navigationExports(target)
+ ? 'goto'
+ : null
+ : exportIdentity(target, exported);
+ }
+ );
+ if (ast.referencedFiles.length || ast.typeReferenceDirectives.length)
+ complain(file, 'source reference directives are forbidden');
+ const inspect = (node) => {
+ if (
+ ts.isExportDeclaration(node) &&
+ node.moduleSpecifier &&
+ (!node.exportClause || ts.isNamespaceExport(node.exportClause)) &&
+ navigationExports(resolve(file, node.moduleSpecifier.text))
+ )
+ complain(
+ file,
+ 'escaped navigation star/namespace reexport is forbidden'
+ );
+ if (
+ (ts.isImportDeclaration(node) ||
+ ts.isExportDeclaration(node) ||
+ ts.isJSDocImportTag(node)) &&
+ node.moduleSpecifier
+ )
+ resolve(
+ file,
+ node.moduleSpecifier.text,
+ new Set(),
+ (ts.isImportDeclaration(node) &&
+ ((node.importClause?.namedBindings &&
+ ts.isNamespaceImport(node.importClause.namedBindings)) ||
+ node.importClause?.name)) ||
+ (ts.isExportDeclaration(node) && !node.exportClause)
+ );
+ if (
+ (ts.isImportSpecifier(node) || ts.isExportSpecifier(node)) &&
+ (node.propertyName ?? node.name).text === 'createRawSnippet'
+ )
+ complain(file, 'Svelte raw-render factories are forbidden');
+ if (ts.isImportTypeNode(node)) {
+ if (
+ ts.isLiteralTypeNode(node.argument) &&
+ ts.isStringLiteral(node.argument.literal)
+ )
+ resolve(file, node.argument.literal.text);
+ else complain(file, 'unresolved production import type');
+ }
+ if (
+ ts.isNewExpression(node) &&
+ node.expression.getText(ast) === 'URL' &&
+ node.arguments?.[1]?.getText(ast) === 'import.meta.url'
+ ) {
+ if (ts.isStringLiteralLike(node.arguments[0]))
+ resolve(file, node.arguments[0].text);
+ else complain(file, 'computed production imports are forbidden');
+ }
+ if (ts.isImportEqualsDeclaration(node))
+ complain(file, 'require/import-equals loaders are forbidden');
+ if (
+ ts.isCallExpression(node) &&
+ node.expression.kind === ts.SyntaxKind.ImportKeyword
+ ) {
+ if (
+ node.arguments.length !== 1 ||
+ !ts.isStringLiteralLike(node.arguments[0])
+ )
+ complain(file, 'computed production imports are forbidden');
+ else resolve(file, node.arguments[0].text, new Set(), true);
+ }
+ if (
+ ts.isIdentifier(node) &&
+ [
+ 'createRawSnippet',
+ 'require',
+ 'eval',
+ 'Function',
+ 'WebSocket',
+ 'Worker',
+ 'SharedWorker',
+ 'importScripts',
+ 'AudioContext',
+ 'OfflineAudioContext',
+ 'AudioWorkletNode',
+ 'generateSecretKey',
+ 'getSecretKey',
+ 'setSecretKey',
+ 'testSigner',
+ 'mockSigner',
+ 'testProvider',
+ 'mockProvider'
+ ].includes(node.text)
+ )
+ complain(
+ file,
+ `production loader/provider/credential API is forbidden: ${node.text}`
+ );
+ if (
+ (ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)) &&
+ !ownedModel(node.expression) &&
+ [
+ 'serviceWorker',
+ 'audioWorklet',
+ 'paintWorklet',
+ 'addModule'
+ ].includes(
+ ts.isPropertyAccessExpression(node)
+ ? node.name.text
+ : ts.isStringLiteralLike(node.argumentExpression)
+ ? node.argumentExpression.text
+ : ''
+ )
+ )
+ complain(file, 'browser worker/client loaders are forbidden');
+ if (
+ ts.isPropertyAccessExpression(node) &&
+ node.expression.getText(ast) === 'import.meta' &&
+ ['glob', 'globEager', 'resolve'].includes(node.name.text)
+ )
+ complain(file, 'computed production imports are forbidden');
+ if (
+ (ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)) &&
+ /^(window|globalThis)\b/.test(node.expression.getText(ast)) &&
+ (ts.isElementAccessExpression(node) ||
+ ['WebSocket', 'eval', 'Function'].includes(node.name.text))
+ )
+ complain(file, 'indirect production loaders are forbidden');
+ if (
+ ts.isPropertyAccessExpression(node) &&
+ !ownedModel(node.expression) &&
+ [
+ 'style',
+ 'cssText',
+ 'styleSheets',
+ 'insertRule',
+ 'adoptedStyleSheets'
+ ].includes(node.name.text)
+ )
+ complain(file, 'JS-generated inline styles are forbidden');
+ if (
+ ts.isCallExpression(node) &&
+ ts.isPropertyAccessExpression(node.expression) &&
+ ['setAttribute', 'createElement'].includes(
+ node.expression.name.text
+ ) &&
+ node.arguments.some(
+ (argument) =>
+ ts.isStringLiteralLike(argument) &&
+ argument.text.toLowerCase() === 'style'
+ )
+ )
+ complain(file, 'JS-generated inline styles are forbidden');
+ if (
+ ts.isPropertyAccessExpression(node) &&
+ !ownedModel(node.expression) &&
+ ['innerHTML', 'outerHTML', 'srcdoc', 'insertAdjacentHTML'].includes(
+ node.name.text
+ )
+ )
+ complain(file, 'raw markup injection APIs are forbidden');
+ if (
+ ts.isElementAccessExpression(node) &&
+ !ownedModel(node.expression) &&
+ ts.isStringLiteralLike(node.argumentExpression) &&
+ ['innerHTML', 'outerHTML', 'srcdoc', 'style', 'cssText'].includes(
+ node.argumentExpression.text
+ )
+ )
+ complain(file, 'raw markup/style injection APIs are forbidden');
+ if (
+ ts.isCallExpression(node) &&
+ (ts.isPropertyAccessExpression(node.expression) ||
+ ts.isElementAccessExpression(node.expression))
+ ) {
+ const method = ts.isPropertyAccessExpression(node.expression)
+ ? node.expression.name.text
+ : ts.isStringLiteralLike(node.expression.argumentExpression)
+ ? node.expression.argumentExpression.text
+ : null;
+ if (method === null)
+ complain(file, 'computed markup/API calls are forbidden');
+ if (['createElement', 'createElementNS'].includes(method)) {
+ const tag = node.arguments[method === 'createElementNS' ? 1 : 0];
+ if (!tag || !ts.isStringLiteralLike(tag))
+ complain(
+ file,
+ 'computed markup resource constructors are forbidden'
+ );
+ else if (
+ declarativeMutationTags.has(
+ tag.text.toLowerCase().split(':').pop()
+ )
+ )
+ complain(
+ file,
+ 'declarative SVG resource/style constructors are forbidden'
+ );
+ else if (
+ [
+ 'script',
+ 'style',
+ 'link',
+ 'iframe',
+ 'object',
+ 'embed',
+ 'applet',
+ 'base'
+ ].includes(tag.text.toLowerCase().split(':').pop())
+ )
+ complain(file, 'raw markup resource constructors are forbidden');
+ }
+ if (
+ ['write', 'writeln'].includes(method) &&
+ /(?:^|\.)document$/.test(node.expression.expression.getText(ast))
+ )
+ complain(file, 'raw markup document writers are forbidden');
+ }
+ const accessedMethod = ts.isPropertyAccessExpression(node)
+ ? node.name.text
+ : ts.isElementAccessExpression(node) &&
+ ts.isStringLiteralLike(node.argumentExpression)
+ ? node.argumentExpression.text
+ : null;
+ if (
+ ['createElement', 'createElementNS'].includes(accessedMethod) &&
+ (!ts.isCallExpression(node.parent) || node.parent.expression !== node)
+ )
+ complain(file, 'indirect markup resource constructors are forbidden');
+ for (const doc of node.jsDoc ?? []) inspect(doc);
+ ts.forEachChild(node, inspect);
+ };
+ inspect(ast);
+ }
+ }
+ const presentCss = [...allowedCss].filter((file) =>
+ files.has(path.join(root, file))
+ );
+ if (
+ presentCss.length &&
+ (presentCss.length !== 2 ||
+ cssImports.join(',') !== 'src/theme.css,src/app.css')
+ )
+ findings.push(
+ 'CSS must be imported exactly once, theme.css then app.css, by the root layout'
+ );
+ return findings;
+}