commit 2aac51e40e87b33f5b070088d0c5df43913ecd47
parent c5c8a0ffb5c5a2d9058c0f76078db78f4d7d87fa
Author: triesap <tyson@radroots.org>
Date: Mon, 5 Oct 2026 19:35:25 +0000
web: wire public query navigation and history (HCP-019)
- Bound normalized public query copies to 512 UTF-8 bytes and 12 terms.
- Encode public search URLs and restore query input through browser history.
- Present field errors before navigation without creating catalog data.
- Verify exact search compiler output and preserve guarded fixture checks.
Diffstat:
15 files changed, 713 insertions(+), 145 deletions(-)
diff --git a/web/package.json b/web/package.json
@@ -14,7 +14,7 @@
"build": "node tools/check-source.mjs && node tools/build-info.mjs && vite build && node tools/check-output.mjs",
"check": "node tools/check-source.mjs && svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
"lint": "node tools/check-source.mjs && svelte-kit sync && eslint . --max-warnings 0 && prettier --check .",
- "test:unit": "node tools/check-source.mjs && svelte-kit sync && vitest run --config vitest.config.ts && node --test --test-timeout=10000 tests/provenance/*.test.mjs",
+ "test:unit": "node tools/check-source.mjs && svelte-kit sync && vitest run --config vitest.config.ts && node --test --test-concurrency=1 --test-timeout=10000 tests/provenance/*.test.mjs",
"test:conformance": "corepack pnpm build && node --test tests/conformance/*.test.ts",
"test:integration": "corepack pnpm build && node --test --test-timeout=10000 tests/integration/*.test.ts",
"test:e2e": "corepack pnpm build && playwright test"
diff --git a/web/src/lib/catalog/query-input.ts b/web/src/lib/catalog/query-input.ts
@@ -0,0 +1,61 @@
+export type PublicQuery =
+ | {
+ readonly ok: true;
+ readonly text: string;
+ readonly terms: readonly string[];
+ }
+ | {
+ readonly ok: false;
+ readonly error: 'invalid_query' | 'query_too_long' | 'too_many_terms';
+ };
+
+const encoder = new TextEncoder();
+
+export function normalizePublicQuery(input: unknown): PublicQuery {
+ if (typeof input !== 'string') return { ok: false, error: 'invalid_query' };
+ if (input.length > 512) return { ok: false, error: 'query_too_long' };
+ if (!input.isWellFormed()) return { ok: false, error: 'invalid_query' };
+ for (const character of input) {
+ const code = character.charCodeAt(0);
+ if (code <= 8 || (code >= 14 && code <= 31) || (code >= 127 && code <= 159))
+ return { ok: false, error: 'invalid_query' };
+ }
+ if (encoder.encode(input).length > 512)
+ return { ok: false, error: 'query_too_long' };
+ const normalized = input.normalize('NFKC').toLowerCase().trim();
+ const terms = normalized === '' ? [] : normalized.split(/\s+/u);
+ if (terms.length > 12) return { ok: false, error: 'too_many_terms' };
+ const text = terms.join(' ');
+ if (encoder.encode(text).length > 512)
+ return { ok: false, error: 'query_too_long' };
+ return { ok: true, text, terms };
+}
+
+export function readPublicQuery(
+ url: Readonly<{
+ pathname: string;
+ hash: string;
+ search: string;
+ searchParams: Readonly<Pick<URLSearchParams, 'keys' | 'get'>>;
+ }>
+): PublicQuery {
+ if (url.pathname !== '/search' || url.hash !== '' || url.search.length > 8192)
+ return { ok: false, error: 'invalid_query' };
+ const keys = [...url.searchParams.keys()];
+ if (keys.length > 1 || keys.some((key) => key !== 'q'))
+ return { ok: false, error: 'invalid_query' };
+ return normalizePublicQuery(url.searchParams.get('q') ?? '');
+}
+
+export function queryErrorMessage(
+ error: 'invalid_query' | 'query_too_long' | 'too_many_terms'
+): string {
+ switch (error) {
+ case 'query_too_long':
+ return 'Use at most 512 UTF-8 bytes for your search.';
+ case 'too_many_terms':
+ return 'Use at most 12 words for your search.';
+ case 'invalid_query':
+ return 'Enter plain search words without private URL context.';
+ }
+}
diff --git a/web/src/lib/components/SearchForm.svelte b/web/src/lib/components/SearchForm.svelte
@@ -3,13 +3,17 @@
import Button from './primitives/Button.svelte';
let {
onsubmit,
+ initialValue = '',
+ error,
disabled = false
}: {
onsubmit?: (input: string) => void;
+ initialValue?: string;
+ error?: string;
disabled?: boolean;
} = $props();
const id = $props.id();
- let input = $state('');
+ let input = $derived(initialValue);
let composing = $state(false);
const unavailable = $derived(disabled || !onsubmit);
function submit(event: SubmitEvent) {
@@ -27,6 +31,7 @@
{id}
label="What are you looking for?"
hint="For example, carrots or carrots Victoria."
+ {error}
>
{#snippet control({ id, describedby, invalid })}
<textarea
diff --git a/web/src/lib/routes.ts b/web/src/lib/routes.ts
@@ -1,6 +1,17 @@
import { decodeProductReference } from './nostr/references';
import { internalHref } from './navigation-url';
import { canonicalLocalId } from './private-handles';
+import { normalizePublicQuery, readPublicQuery } from './catalog/query-input';
+
+export function searchHref(input: unknown): string | undefined {
+ const query = normalizePublicQuery(input);
+ if (!query.ok) return undefined;
+ const params = new URLSearchParams();
+ if (query.text !== '') params.set('q', query.text);
+ return internalHref(
+ params.size === 0 ? '/search' : `/search?${params.toString()}`
+ );
+}
export function staticHref(input: unknown): string | undefined {
switch (input) {
@@ -28,6 +39,21 @@ export function conversationHref(input: unknown): string | undefined {
}
export function safeContextBack(input: unknown): string | undefined {
+ if (
+ typeof input === 'string' &&
+ input.length <= 8192 &&
+ input.startsWith('/search?') &&
+ !input.includes('#')
+ ) {
+ try {
+ const query = readPublicQuery(
+ new URL(input, 'https://navigation.invalid')
+ );
+ return query.ok ? searchHref(query.text) : undefined;
+ } catch {
+ return undefined;
+ }
+ }
if (input === '/search' || input === '/selling' || input === '/messages')
return internalHref(input);
if (
diff --git a/web/src/routes/+page.svelte b/web/src/routes/+page.svelte
@@ -1,5 +1,26 @@
<script lang="ts">
import SearchForm from '../lib/components/SearchForm.svelte';
+ import {
+ normalizePublicQuery,
+ queryErrorMessage
+ } from '../lib/catalog/query-input';
+ import { searchHref } from '../lib/routes';
+ import { internalHref } from '../lib/navigation-url';
+ let error = $state<string | undefined>();
+ function search(input: string) {
+ const query = normalizePublicQuery(input);
+ if (!query.ok) {
+ error = queryErrorMessage(query.error);
+ return;
+ }
+ error = undefined;
+ const target = internalHref(searchHref(query.text));
+ if (target === undefined) {
+ error = queryErrorMessage('invalid_query');
+ return;
+ }
+ globalThis.location.assign(target);
+ }
</script>
<svelte:head>
@@ -7,5 +28,5 @@
</svelte:head>
<div class="page page--reading">
- <SearchForm />
+ <SearchForm onsubmit={search} {error} />
</div>
diff --git a/web/src/routes/search/+page.svelte b/web/src/routes/search/+page.svelte
@@ -0,0 +1,43 @@
+<script lang="ts">
+ import { page } from '$app/state';
+ import SearchForm from '../../lib/components/SearchForm.svelte';
+ import {
+ normalizePublicQuery,
+ queryErrorMessage,
+ readPublicQuery
+ } from '../../lib/catalog/query-input';
+ import type { PublicQuery } from '../../lib/catalog/query-input';
+ import { searchHref } from '../../lib/routes';
+ import { internalHref } from '../../lib/navigation-url';
+ let query = $state<PublicQuery>(normalizePublicQuery(''));
+ let error = $state<string | undefined>();
+ $effect(() => {
+ query = readPublicQuery(page.url);
+ error = undefined;
+ });
+ function search(input: string) {
+ const next = normalizePublicQuery(input);
+ if (!next.ok) {
+ error = queryErrorMessage(next.error);
+ return;
+ }
+ error = undefined;
+ const target = internalHref(searchHref(next.text));
+ if (target === undefined) {
+ error = queryErrorMessage('invalid_query');
+ return;
+ }
+ globalThis.location.assign(target);
+ }
+</script>
+
+<svelte:head><title>Search food — HarvestCircle</title></svelte:head>
+<div class="page page--reading stack">
+ <h1>Search food</h1>
+ <SearchForm
+ onsubmit={search}
+ initialValue={query.ok ? query.text : ''}
+ error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))}
+ />
+ <p class="notice">Search data is unavailable during development.</p>
+</div>
diff --git a/web/tests/e2e/bootstrap.spec.ts b/web/tests/e2e/bootstrap.spec.ts
@@ -98,10 +98,10 @@ test('actual browser loads guest shell without an extension', async ({
).toBeVisible();
await expect(
page.getByRole('button', { name: 'Search', exact: true })
- ).toBeDisabled();
+ ).toBeEnabled();
await expect(
page.getByText('Search is unavailable during development.')
- ).toBeVisible();
+ ).toHaveCount(0);
await query.fill('carrots');
await query.press('Enter');
await expect(query).toHaveValue('carrots\n');
@@ -111,9 +111,10 @@ test('actual browser loads guest shell without an extension', async ({
cancelable: true
});
if (form.dispatchEvent(event))
- throw new Error('Unavailable submit was not prevented');
+ throw new Error('Native search submit was not prevented');
});
- expect(new URL(page.url()).pathname).toBe('/');
+ await expect(page).toHaveURL(server.url + '/search?q=carrots');
+ await page.goto(server.url);
// Start the existing skip-link keyboard check from the document again.
await page.reload();
await expect(page.getByRole('main')).toHaveCount(1);
diff --git a/web/tests/e2e/query-navigation.spec.ts b/web/tests/e2e/query-navigation.spec.ts
@@ -0,0 +1,91 @@
+import { test, expect } from '@playwright/test';
+import { createStaticHarness } from '../integration/harness/static';
+
+test('real public query navigation normalizes copies and restores Back/Forward state', async ({
+ browser
+}) => {
+ const server = await createStaticHarness();
+ const context = await browser.newContext();
+ const external: string[] = [];
+ try {
+ await context.route('**/*', (route) => {
+ if (new URL(route.request().url()).origin === server.url)
+ return route.continue();
+ external.push(route.request().url());
+ return route.abort();
+ });
+ const page = await context.newPage();
+ await page.goto(server.url);
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await expect(page).toHaveURL(server.url + '/search');
+ const input = page.getByRole('textbox', {
+ name: 'What are you looking for?'
+ });
+ await input.fill(' CARROTS\nVICTORIA 菜 ');
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await expect(page).toHaveURL(
+ server.url + '/search?q=carrots+victoria+%E8%8F%9C'
+ );
+ await expect(input).toHaveValue('carrots victoria 菜');
+ await expect(
+ page.getByText('Search data is unavailable during development.')
+ ).toBeVisible();
+ await input.fill('Turnips');
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await expect(page).toHaveURL(server.url + '/search?q=turnips');
+ await page.goBack();
+ await expect(input).toHaveValue('carrots victoria 菜');
+ await page.goForward();
+ await expect(input).toHaveValue('turnips');
+ expect([...new URL(page.url()).searchParams.keys()]).toEqual(['q']);
+ expect(external).toEqual([]);
+ expect(await page.evaluate(() => 'nostr' in window)).toBe(false);
+ } finally {
+ await context.close();
+ await server.close();
+ }
+ expect(context.pages()).toHaveLength(0);
+ expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
+});
+
+test('real search preserves rejected input and does not navigate or execute excess queries', async ({
+ browser
+}) => {
+ const server = await createStaticHarness();
+ const context = await browser.newContext();
+ try {
+ await context.route('**/*', (route) =>
+ new URL(route.request().url()).origin === server.url
+ ? route.continue()
+ : route.abort()
+ );
+ const page = await context.newPage();
+ await page.goto(server.url);
+ const input = page.getByRole('textbox', {
+ name: 'What are you looking for?'
+ });
+ for (const [value, message] of [
+ ['菜'.repeat(171), 'Use at most 512 UTF-8 bytes'],
+ [Array(13).fill('carrots').join(' '), 'Use at most 12 words']
+ ] as const) {
+ await input.fill(value);
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await expect(input).toHaveValue(value);
+ await expect(input).toHaveAttribute('aria-invalid', 'true');
+ await expect(page.getByText(message, { exact: false })).toBeVisible();
+ expect(new URL(page.url()).pathname).toBe('/');
+ expect(new URL(page.url()).search).toBe('');
+ }
+ await page.goto(server.url + '/search?q=carrots&body=private');
+ await expect(
+ page.getByText('Enter plain search words without private URL context.')
+ ).toBeVisible();
+ await expect(
+ page.getByRole('textbox', { name: 'What are you looking for?' })
+ ).toHaveValue('');
+ } finally {
+ await context.close();
+ await server.close();
+ }
+ expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
+});
diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts
@@ -41,6 +41,13 @@ await test('navigation fallback serves actual separate output and preserves miss
new URL('../../build/200.html', import.meta.url),
'utf8'
);
+ const search = await readFile(
+ new URL('../../build/search.html', import.meta.url),
+ 'utf8'
+ );
+ assert.notEqual(search, fallback);
+ assert.match(search, /<title>Search food — HarvestCircle<\/title>/);
+ assert.match(search, /Search data is unavailable during development\./);
const document = { accept: 'text/html', 'sec-fetch-dest': 'document' };
try {
for (const pathname of [
@@ -58,7 +65,10 @@ await test('navigation fallback serves actual separate output and preserves miss
const result = await fetch(server.url + pathname, { headers: document });
assert.equal(result.status, 200, pathname);
assert.equal(result.headers.get('content-type'), 'text/html');
- assert.equal(await result.text(), fallback);
+ assert.equal(
+ await result.text(),
+ pathname === '/search?q=food' ? search : fallback
+ );
}
for (const pathname of [
'/missing.js',
diff --git a/web/tests/provenance/commands.test.mjs b/web/tests/provenance/commands.test.mjs
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict';
+import { performance } from 'node:perf_hooks';
import { spawnSync } from 'node:child_process';
import {
mkdtemp,
@@ -29,14 +30,22 @@ async function fixture(t) {
await readFile(new URL(source, import.meta.url))
);
await symlink(process.execPath, path.join(root, 'bin/node'));
- const log = path.join(root, 'calls.jsonl');
+ const log = path.join(root, 'calls.frames');
await writeFile(
path.join(root, 'bin/corepack'),
- `#!${process.execPath}
-import { appendFileSync } from 'node:fs';
-appendFileSync(process.env.HC_COMMAND_LOG, JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(2), network: process.env.COREPACK_ENABLE_NETWORK }) + '\\n');
-if (process.argv.includes('--version')) console.log(process.env.HC_PNPM_VERSION ?? '12.9.1');
-else if (process.argv.includes(process.env.HC_FAIL_COMMAND)) process.exit(37);
+ `#!/bin/sh
+printf '%s\\0' "$PWD" "\${COREPACK_ENABLE_NETWORK-}" "$#" "$@" >> "$HC_COMMAND_LOG"
+version=false
+failed=false
+for argument do
+ if [ "$argument" = '--version' ]; then version=true; fi
+ if [ -n "\${HC_FAIL_COMMAND-}" ] && [ "$argument" = "$HC_FAIL_COMMAND" ]; then failed=true; fi
+done
+if [ "$version" = true ]; then
+ printf '%s\\n' "\${HC_PNPM_VERSION-12.9.1}"
+elif [ "$failed" = true ]; then
+ exit 37
+fi
`,
{ mode: 0o755 }
);
@@ -46,103 +55,177 @@ else if (process.argv.includes(process.env.HC_FAIL_COMMAND)) process.exit(37);
HC_COMMAND_LOG: log
};
/** @param {string} target @param {Record<string, string>} [extra] */
- const run = (target, extra = {}) =>
- spawnSync('/usr/bin/make', ['--no-print-directory', target], {
- cwd: root,
- env: { ...env, ...extra },
- encoding: 'utf8',
- timeout: 10000
- });
- const calls = async () =>
- (await readFile(log, 'utf8'))
- .trim()
- .split('\n')
- .map((line) => JSON.parse(line));
+ const run = (target, extra = {}) => {
+ const started = performance.now();
+ const result = spawnSync(
+ '/usr/bin/make',
+ ['--no-print-directory', target],
+ {
+ cwd: root,
+ env: { ...env, ...extra },
+ encoding: 'utf8',
+ timeout: 30000
+ }
+ );
+ return {
+ ...result,
+ diagnostic: JSON.stringify({
+ target,
+ status: result.status,
+ signal: result.signal,
+ error:
+ result.error && 'code' in result.error
+ ? result.error.code
+ : undefined,
+ elapsed_ms: performance.now() - started,
+ stdout: result.stdout,
+ stderr: result.stderr
+ })
+ };
+ };
+ const calls = async () => {
+ const fields = (await readFile(log, 'utf8')).split('\0');
+ assert.equal(fields.pop(), '');
+ const records = [];
+ for (let index = 0; index < fields.length;) {
+ const cwd = fields[index++];
+ const network = fields[index++];
+ const count = Number(fields[index++]);
+ assert.ok(
+ Number.isSafeInteger(count) &&
+ count >= 0 &&
+ index + count <= fields.length
+ );
+ records.push({
+ cwd,
+ args: fields.slice(index, index + count),
+ ...(network ? { network } : {})
+ });
+ index += count;
+ }
+ return records;
+ };
return { root, run, calls };
}
-await test('standalone web targets select web cwd and run every required lane without native tools', async (t) => {
- const { root, run, calls } = await fixture(t);
- for (const target of [
- 'web-doctor',
- 'web-install',
- 'web-check',
- 'web-build',
- 'web-dev'
- ]) {
- const result = run(target);
- assert.equal(result.status, 0, result.stderr);
+await test(
+ 'standalone web targets select web cwd and run every required lane without native tools',
+ { timeout: 180000 },
+ async (t) => {
+ const { root, run, calls } = await fixture(t);
+ for (const target of [
+ 'web-doctor',
+ 'web-install',
+ 'web-check',
+ 'web-build',
+ 'web-dev'
+ ]) {
+ const result = run(target);
+ assert.equal(result.status, 0, result.diagnostic);
+ }
+ const actual = await calls();
+ assert.ok(actual.every((call) => call.cwd === path.join(root, 'web')));
+ assert.ok(
+ actual
+ .filter((call) => call.args.includes('--version'))
+ .every((call) => call.network === '0')
+ );
+ assert.deepEqual(
+ actual
+ .filter((call) => !call.args.includes('--version'))
+ .map((call) => call.args),
+ [
+ ['pnpm', 'install', '--frozen-lockfile'],
+ ['pnpm', 'run', 'check'],
+ ['pnpm', 'run', 'lint'],
+ ['pnpm', 'run', 'test:unit'],
+ ['pnpm', 'run', 'test:conformance'],
+ ['pnpm', 'run', 'build'],
+ ['pnpm', 'run', 'dev']
+ ]
+ );
}
- const actual = await calls();
- assert.ok(actual.every((call) => call.cwd === path.join(root, 'web')));
- assert.ok(
- actual
- .filter((call) => call.args.includes('--version'))
- .every((call) => call.network === '0')
- );
- assert.deepEqual(
- actual
- .filter((call) => !call.args.includes('--version'))
- .map((call) => call.args),
- [
- ['pnpm', 'install', '--frozen-lockfile'],
- ['pnpm', 'run', 'check'],
- ['pnpm', 'run', 'lint'],
- ['pnpm', 'run', 'test:unit'],
- ['pnpm', 'run', 'test:conformance'],
- ['pnpm', 'run', 'build'],
- ['pnpm', 'run', 'dev']
- ]
- );
-});
+);
-await test('doctor rejects a mismatched selected manager before installation', async (t) => {
- const { run, calls } = await fixture(t);
- const result = run('web-install', { HC_PNPM_VERSION: '10.25.0' });
- assert.notEqual(result.status, 0);
- assert.match(result.stderr, /Expected pnpm 12\.9\.1; selected 10\.25\.0/);
- assert.equal((await calls()).length, 1);
-});
+await test(
+ 'doctor rejects a mismatched selected manager before installation',
+ { timeout: 45000 },
+ async (t) => {
+ const { run, calls } = await fixture(t);
+ const result = run('web-install', { HC_PNPM_VERSION: '10.25.0' });
+ assert.notEqual(result.status, 0, result.diagnostic);
+ assert.match(
+ result.stderr,
+ /Expected pnpm 12\.9\.1; selected 10\.25\.0/,
+ result.diagnostic
+ );
+ assert.equal((await calls()).length, 1);
+ }
+);
-await test('web check propagates failing commands and stops subsequent lanes', async (t) => {
- const { run, calls } = await fixture(t);
- const result = run('web-check', { HC_FAIL_COMMAND: 'lint' });
- assert.notEqual(result.status, 0);
- assert.match(result.stderr, /Error 37/);
- assert.deepEqual(
- (await calls()).map((call) => call.args),
- [
- ['pnpm', '--version'],
- ['pnpm', 'run', 'check'],
- ['pnpm', 'run', 'lint']
- ]
- );
-});
+await test(
+ 'web check propagates failing commands and stops subsequent lanes',
+ { timeout: 45000 },
+ async (t) => {
+ const { run, calls } = await fixture(t);
+ const result = run('web-check', { HC_FAIL_COMMAND: 'lint' });
+ assert.notEqual(result.status, 0, result.diagnostic);
+ assert.match(result.stderr, /Error 37/, result.diagnostic);
+ assert.deepEqual(
+ (await calls()).map((call) => call.args),
+ [
+ ['pnpm', '--version'],
+ ['pnpm', 'run', 'check'],
+ ['pnpm', 'run', 'lint']
+ ]
+ );
+ }
+);
-await test('missing web tooling fails without trying native tools', async (t) => {
- const { root, run } = await fixture(t);
- await rm(path.join(root, 'bin/corepack'));
- const result = run('web-build');
- assert.notEqual(result.status, 0);
- assert.match(result.stderr, /ENOENT/);
-});
+await test(
+ 'missing web tooling fails without trying native tools',
+ { timeout: 45000 },
+ async (t) => {
+ const { root, run } = await fixture(t);
+ await rm(path.join(root, 'bin/corepack'));
+ const result = run('web-build');
+ assert.notEqual(result.status, 0, result.diagnostic);
+ assert.match(result.stderr, /ENOENT/, result.diagnostic);
+ }
+);
-await test('doctor rejects mismatched toolchain authorities', async (t) => {
- const { root, run } = await fixture(t);
- await writeFile(path.join(root, 'web/.node-version'), '24.20.0\n');
- const result = run('web-doctor');
- assert.notEqual(result.status, 0);
- assert.match(result.stderr, /Web toolchain pins disagree or are not exact/);
-});
+await test(
+ 'doctor rejects mismatched toolchain authorities',
+ { timeout: 45000 },
+ async (t) => {
+ const { root, run } = await fixture(t);
+ await writeFile(path.join(root, 'web/.node-version'), '24.20.0\n');
+ const result = run('web-doctor');
+ assert.notEqual(result.status, 0, result.diagnostic);
+ assert.match(
+ result.stderr,
+ /Web toolchain pins disagree or are not exact/,
+ result.diagnostic
+ );
+ }
+);
-await test('doctor rejects wrong selected Node before invoking Corepack', async (t) => {
- const { root, run } = await fixture(t);
- const file = path.join(root, 'web/package.json');
- const inputs = JSON.parse(await readFile(file, 'utf8'));
- inputs.engines.node = '24.20.0';
- await writeFile(file, JSON.stringify(inputs));
- await writeFile(path.join(root, 'web/.node-version'), '24.20.0\n');
- const result = run('web-doctor');
- assert.notEqual(result.status, 0);
- assert.match(result.stderr, /Expected Node 24\.20\.0; selected 24\.21\.0/);
-});
+await test(
+ 'doctor rejects wrong selected Node before invoking Corepack',
+ { timeout: 45000 },
+ async (t) => {
+ const { root, run } = await fixture(t);
+ const file = path.join(root, 'web/package.json');
+ const inputs = JSON.parse(await readFile(file, 'utf8'));
+ inputs.engines.node = '24.20.0';
+ await writeFile(file, JSON.stringify(inputs));
+ await writeFile(path.join(root, 'web/.node-version'), '24.20.0\n');
+ const result = run('web-doctor');
+ assert.notEqual(result.status, 0, result.diagnostic);
+ assert.match(
+ result.stderr,
+ /Expected Node 24\.20\.0; selected 24\.21\.0/,
+ result.diagnostic
+ );
+ }
+);
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -20,7 +20,11 @@ import { fileURLToPath } from 'node:url';
import { generateBuildInfo } from '../../tools/build-info.mjs';
import { auditOutput } from '../../tools/check-output.mjs';
-await test('actual output qualification', { timeout: 30000 }, async (t) => {
+// Allow bounded setup/copy time for all 73 checks and two real compilations.
+// Admission checks get 10 seconds; cold compiler work gets 60 seconds.
+await test('actual output qualification', { timeout: 180000 }, async (t) => {
+ /** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */
+ const check = (name, run, timeout = 10000) => t.test(name, { timeout }, run);
const source = fileURLToPath(new URL('../../../', import.meta.url));
const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output '));
t.after(() => rm(base, { recursive: true, force: true }));
@@ -80,7 +84,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
execFileSync(
process.execPath,
[path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'],
- { cwd: path.join(base, 'web'), stdio: 'pipe', timeout: 10000 }
+ { cwd: path.join(base, 'web'), stdio: 'pipe', timeout: 60000 }
);
/** @param {import('node:test').TestContext} t */
@@ -89,20 +93,30 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
await mkdtemp(path.join(os.tmpdir(), 'hc output mutation '))
);
t.after(() => rm(root, { recursive: true, force: true }));
+ // Audit consumers use actual client/prerendered/build bytes and all source
+ // inputs. Server output and generated development/type caches are not audit
+ // inputs; avoid copying them for every mutation under the fixed deadline.
+ const excluded = new Set([
+ path.join(base, 'web/node_modules'),
+ path.join(base, 'web/.svelte-kit/output/server'),
+ path.join(base, 'web/.svelte-kit/generated'),
+ path.join(base, 'web/.svelte-kit/types')
+ ]);
await cp(base, root, {
recursive: true,
- filter: (name) => name !== path.join(base, 'web/node_modules')
+ filter: (name) => !excluded.has(name)
});
const web = path.join(root, 'web');
return { root, web, audit: () => auditOutput(web) };
}
- await t.test(
+ await check(
'actual compiled payload passes and build dispatch invokes the guard last',
async (t) => {
const f = await fixture(t);
const files = await f.audit();
- // Shared unchanged Button now serves both shell and form; CSS stays once-imported.
- assert.equal(files.length, 18);
+ // Exact new search node/shared routes chunk/page; CSS stays once-imported.
+ assert.equal(files.length, 21);
+ assert.ok(files.includes('search.html'));
assert.equal(files.filter((name) => name.endsWith('.css')).length, 1);
assert.ok(
files.some((name) =>
@@ -121,7 +135,64 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
);
}
);
- await t.test(
+ await check(
+ 'search route admission requires its owned source and exact module/page counterparts',
+ async (t) => {
+ const f = await fixture(t);
+ const source = path.join(f.web, 'src/routes/search/+page.svelte');
+ const original = await readFile(source);
+ await rm(source);
+ git(f.root, 'add', '--', 'web/src/routes/search/+page.svelte');
+ await generateBuildInfo(f.web);
+ const metadata = await readFile(
+ path.join(f.web, 'static/build-info.json')
+ );
+ await writeFile(path.join(f.web, 'build/build-info.json'), metadata);
+ await writeFile(
+ path.join(f.web, '.svelte-kit/output/client/build-info.json'),
+ metadata
+ );
+ await assert.rejects(f.audit, /Undeclared compiler module/);
+ await writeFile(source, original);
+ }
+ );
+ for (const mutation of [
+ 'unknown-name',
+ 'duplicate',
+ 'missing-module',
+ 'missing-page',
+ 'changed-page'
+ ]) {
+ await check(
+ 'exact search compiler admission rejects ' + mutation,
+ async (t) => {
+ const f = await fixture(t);
+ const file = path.join(
+ f.web,
+ '.svelte-kit/output/client/.vite/manifest.json'
+ );
+ const manifest = JSON.parse(await readFile(file, 'utf8'));
+ const entry = Object.entries(manifest).find(
+ ([, record]) => record.name === 'routes'
+ );
+ assert.ok(entry, 'The actual shared routes module must exist');
+ const [key, module] = entry;
+ if (mutation === 'unknown-name') module.name = 'unapproved-routes';
+ if (mutation === 'duplicate') manifest.duplicate = { ...module };
+ if (mutation === 'missing-module') delete manifest[key];
+ if (mutation === 'missing-page')
+ await rm(path.join(f.web, 'build/search.html'));
+ if (mutation === 'changed-page')
+ await writeFile(
+ path.join(f.web, 'build/search.html'),
+ '<h1>Different source</h1>'
+ );
+ await writeFile(file, JSON.stringify(manifest));
+ await assert.rejects(f.audit);
+ }
+ );
+ }
+ await check(
'actual route-state compiler module has an owned client counterpart',
async (t) => {
const f = await fixture(t);
@@ -158,7 +229,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
'missing-counterpart',
'changed-counterpart'
]) {
- await t.test('state module fails closed: ' + mutation, async (t) => {
+ await check('state module fails closed: ' + mutation, async (t) => {
const f = await fixture(t);
const file = path.join(
f.web,
@@ -194,7 +265,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
);
});
}
- await t.test(
+ await check(
'actual shared Button compiler module has an owned client counterpart',
async (t) => {
const f = await fixture(t);
@@ -238,7 +309,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
'missing-counterpart',
'changed-counterpart'
]) {
- await t.test('Button module fails closed: ' + mutation, async (t) => {
+ await check('Button module fails closed: ' + mutation, async (t) => {
const f = await fixture(t);
const file = path.join(
f.web,
@@ -282,7 +353,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
'source.map',
'contracts/vector.json'
]) {
- await t.test(`undeclared copied output is rejected: ${name}`, async (t) => {
+ await check(`undeclared copied output is rejected: ${name}`, async (t) => {
const f = await fixture(t);
const file = path.join(f.web, 'build', name);
await mkdir(path.dirname(file), { recursive: true });
@@ -303,7 +374,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
Buffer.from('private_transcript: controlled disclosure'),
Buffer.from('class TestSigner {}')
]) {
- await t.test(
+ await check(
`manifest-admitted contamination ${payload.subarray(0, 18).toString('hex')}`,
async (t) => {
const f = await fixture(t);
@@ -329,7 +400,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
'_app/version.json',
'build-info.json'
]) {
- await t.test(`missing/tampered owned output: ${name}`, async (t) => {
+ await check(`missing/tampered owned output: ${name}`, async (t) => {
const f = await fixture(t);
const file = path.join(f.web, 'build', name);
const original = await readFile(file);
@@ -349,7 +420,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
'source',
'generated'
]) {
- await t.test(`provenance fails closed: ${mutation}`, async (t) => {
+ await check(`provenance fails closed: ${mutation}`, async (t) => {
const f = await fixture(t);
const metadata = JSON.parse(
await readFile(path.join(f.web, 'build/build-info.json'), 'utf8')
@@ -391,7 +462,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
'oversize',
'parent'
]) {
- await t.test(`unsafe output refuses ${kind} promptly`, async (t) => {
+ await check(`unsafe output refuses ${kind} promptly`, async (t) => {
const f = await fixture(t);
const file = path.join(f.web, 'build/index.html');
await rm(file);
@@ -409,7 +480,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
await assert.rejects(f.audit);
});
}
- await t.test(
+ await check(
'compiler manifest cannot authorize arbitrary resources, escapes or unresolved imports',
async (t) => {
const f = await fixture(t);
@@ -435,7 +506,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
}
);
- await t.test(
+ await check(
'generated provenance must remain ignored even when freshly regenerated',
async (t) => {
const f = await fixture(t);
@@ -447,10 +518,12 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
for (const name of [
'static/build-info.json',
'.svelte-kit/output/client/.vite/manifest.json',
- '.svelte-kit/output/prerendered/pages/index.html'
+ '.svelte-kit/output/prerendered/pages/index.html',
+ '.svelte-kit/output/prerendered/pages/search.html',
+ 'src/routes/search/+page.svelte'
]) {
for (const kind of ['fifo', 'symlink', 'hardlink']) {
- await t.test(
+ await check(
`unsafe compiler/static counterpart ${name}: ${kind}`,
async (t) => {
const f = await fixture(t);
@@ -466,7 +539,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
);
}
}
- await t.test(
+ await check(
'empty output directory and excessive depth are rejected',
async (t) => {
const f = await fixture(t);
@@ -479,7 +552,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
await assert.rejects(f.audit);
}
);
- await t.test(
+ await check(
'forged public output failures do not echo private poisoned bytes',
async (t) => {
const f = await fixture(t);
@@ -489,7 +562,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
await assert.rejects(f.audit, (error) => !String(error).includes(marker));
}
);
- await t.test(
+ await check(
'output entry and aggregate-byte bounds reject oversized inventories',
async (t) => {
const f = await fixture(t);
@@ -520,7 +593,7 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
await assert.rejects(f.audit, /Unbounded output bytes/);
}
);
- await t.test(
+ await check(
'actual compiler admits nonempty approved theme/app CSS',
async () => {
const layout = path.join(base, 'web/src/routes/+layout.svelte');
@@ -542,11 +615,12 @@ await test('actual output qualification', { timeout: 30000 }, async (t) => {
await generateBuildInfo(path.join(base, 'web'));
execFileSync(
process.execPath,
- [path.join(base, 'web/node_modules/vite/bin/vite.js'), 'build'],
- { cwd: path.join(base, 'web'), stdio: 'pipe', timeout: 10000 }
+ [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'],
+ { cwd: path.join(base, 'web'), stdio: 'pipe', timeout: 60000 }
);
const files = await auditOutput(await realpath(path.join(base, 'web')));
assert.ok(files.some((name) => name.endsWith('.css')));
- }
+ },
+ 60000
);
});
diff --git a/web/tests/unit/bootstrap.test.ts b/web/tests/unit/bootstrap.test.ts
@@ -27,14 +27,16 @@ describe('static guest shell', () => {
expect(prerender).toBe(true);
expect(ssr).toBe(true);
});
- it('renders the shared anonymous form exactly once with honest unavailable submission', () => {
+ it('renders the shared anonymous form exactly once with an explicit search caller', () => {
const html = render(Shell).body;
expect(html.match(/<textarea\b/g)).toHaveLength(1);
expect(html).toContain('What are you looking for?');
expect(html).toContain('For example, carrots or carrots Victoria.');
expect(html).toContain('rows="2"');
- expect(html).toMatch(/<button[^>]*type="submit"[^>]*disabled[^>]*>Search/);
- expect(html).toContain('Search is unavailable during development.');
+ expect(html).not.toMatch(
+ /<button[^>]*type="submit"[^>]*disabled[^>]*>Search/
+ );
+ expect(html).not.toContain('Search is unavailable during development.');
expect(html).not.toContain('<h1>');
});
it('composes the actual shared shell and preserves the route body without a global h1', () => {
diff --git a/web/tests/unit/components/search-form.test.ts b/web/tests/unit/components/search-form.test.ts
@@ -3,6 +3,23 @@ import { describe, expect, it } from 'vitest';
import SearchForm from '../../../src/lib/components/SearchForm.svelte';
describe('shared labelled search form SSR', () => {
+ it('renders a public URL query and linked field error without invoking navigation', () => {
+ const html = render(SearchForm, {
+ props: {
+ initialValue: 'carrots',
+ error: 'Use at most 12 words.',
+ onsubmit: () => {
+ throw new Error('SSR navigation');
+ }
+ }
+ }).body;
+ expect(html).toContain('carrots');
+ expect(html).toContain('Use at most 12 words.');
+ expect(html).toContain('aria-invalid="true"');
+ const id = html.match(/<textarea[^>]* id="([^"]+)"/)?.[1];
+ expect(html).toContain(`id="${id}-error"`);
+ expect(html).toContain(`aria-describedby="${id}-hint ${id}-error"`);
+ });
it('renders one two-row textarea, visible associated label and example hint', () => {
const html = render(SearchForm).body;
expect(html.match(/<textarea\b/g)).toHaveLength(1);
diff --git a/web/tests/unit/query-input.test.ts b/web/tests/unit/query-input.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import {
+ normalizePublicQuery,
+ readPublicQuery
+} from '../../src/lib/catalog/query-input';
+import { searchHref, safeContextBack } from '../../src/lib/routes';
+
+describe('bounded public search copies', () => {
+ it('normalizes only a search copy using NFKC, lowercase and whitespace', () => {
+ const raw = ' CARROTS\nVICTORIA 菜 ';
+ expect(normalizePublicQuery(raw)).toEqual({
+ ok: true,
+ text: 'carrots victoria 菜',
+ terms: ['carrots', 'victoria', '菜']
+ });
+ expect(raw).toBe(' CARROTS\nVICTORIA 菜 ');
+ expect(searchHref(raw)).toBe('/search?q=carrots+victoria+%E8%8F%9C');
+ });
+ for (const raw of ['', ' \n '])
+ it('omits empty q for bounded browse', () => {
+ expect(searchHref(raw)).toBe('/search');
+ expect(normalizePublicQuery(raw)).toEqual({
+ ok: true,
+ text: '',
+ terms: []
+ });
+ });
+ it('admits the byte boundary and rejects excess before search execution', () => {
+ expect(normalizePublicQuery('a'.repeat(512)).ok).toBe(true);
+ expect(normalizePublicQuery('菜'.repeat(170)).ok).toBe(true);
+ for (const raw of [
+ 'a'.repeat(513),
+ '菜'.repeat(171),
+ 'İ'.repeat(171),
+ '㍿'.repeat(128),
+ 'x'.repeat(100000)
+ ]) {
+ expect(normalizePublicQuery(raw).ok).toBe(false);
+ expect(searchHref(raw)).toBeUndefined();
+ }
+ });
+ it('admits twelve terms but rejects thirteen', () => {
+ expect(normalizePublicQuery(Array(12).fill('a').join(' ')).ok).toBe(true);
+ expect(normalizePublicQuery(Array(13).fill('a').join(' ')).ok).toBe(false);
+ });
+ for (const raw of [
+ undefined,
+ null,
+ {},
+ { body: 'private', peer: 'alice' },
+ '\ud800',
+ 'carrots\0private'
+ ])
+ it(`rejects malformed public input ${JSON.stringify(raw)}`, () => {
+ expect(normalizePublicQuery(raw).ok).toBe(false);
+ expect(searchHref(raw)).toBeUndefined();
+ });
+ it('encodes text as q without creating extra private parameters or fragments', () => {
+ const href = searchHref('carrots&peer=alice#body');
+ const url = new URL(href!, 'https://example.invalid');
+ expect([...url.searchParams.keys()]).toEqual(['q']);
+ expect(url.searchParams.get('q')).toBe('carrots&peer=alice#body');
+ expect(url.hash).toBe('');
+ });
+});
+
+describe('public URL query context', () => {
+ it('restores the one bounded allowed q and canonicalizes back links', () => {
+ const url = new URL('https://example.invalid/search?q=CARROTS%0A%E8%8F%9C');
+ expect(readPublicQuery(url)).toEqual({
+ ok: true,
+ text: 'carrots 菜',
+ terms: ['carrots', '菜']
+ });
+ expect(safeContextBack('/search?q=CARROTS%0A%E8%8F%9C')).toBe(
+ '/search?q=carrots+%E8%8F%9C'
+ );
+ });
+ for (const context of [
+ '/search?q=carrots&body=private',
+ '/search?q=a&q=b',
+ '/search?q=a#peer',
+ '//evil/search?q=a',
+ '/search/../messages?q=a'
+ ])
+ it(`rejects arbitrary or private URL context ${context}`, () => {
+ expect(safeContextBack(context)).toBeUndefined();
+ });
+ it('rejects excess URL queries and does not expose them as executable search', () => {
+ for (const value of ['x'.repeat(513), Array(13).fill('a').join(' ')])
+ expect(
+ readPublicQuery(
+ new URL(
+ '/search?q=' + encodeURIComponent(value),
+ 'https://example.invalid'
+ )
+ ).ok
+ ).toBe(false);
+ expect(
+ readPublicQuery(
+ new URL('/search?body=private', 'https://example.invalid')
+ ).ok
+ ).toBe(false);
+ });
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -200,6 +200,16 @@ export async function auditOutput(webDirectory) {
if (!manifestBytes) throw new Error('Missing compiler manifest');
const manifest = parse(publicText(manifestBytes));
objectKeys(manifest, Object.keys(manifest));
+ // Exact source-owned search route admission; root-only controlled consumers
+ // retain their original compiler shape. Source ancestry/link bounds also apply.
+ let hasSearch = false;
+ try {
+ await readOwned(web, 'src/routes/search/+page.svelte');
+ hasSearch = true;
+ } catch (error) {
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
+ throw error;
+ }
// Admit compiler-owned module identities, not arbitrary extensions/copy roots.
const names = new Set([
'entry/app',
@@ -216,6 +226,10 @@ export async function auditOutput(webDirectory) {
'state',
'Button'
]);
+ if (hasSearch) {
+ names.add('nodes/3');
+ names.add('routes');
+ }
const admitted = new Map([['build-info.json', expectedMetadata]]);
const seen = new Set();
for (const [key, record] of Object.entries(manifest)) {
@@ -232,8 +246,9 @@ export async function auditOutput(webDirectory) {
if (!names.has(record.name) || seen.has(record.name))
throw new Error('Undeclared compiler module');
seen.add(record.name);
- const generatedModule =
- /^\.svelte-kit\/generated\/build\/(?:client-optimized\/(?:app|nodes\/[012])|shared\/error-template)\.js$/;
+ const generatedModule = hasSearch
+ ? /^\.svelte-kit\/generated\/build\/(?:client-optimized\/(?:app|nodes\/[0123])|shared\/error-template)\.js$/
+ : /^\.svelte-kit\/generated\/build\/(?:client-optimized\/(?:app|nodes\/[012])|shared\/error-template)\.js$/;
const frameworkModule =
/^node_modules\/\.pnpm\/[^/]+\/node_modules\/@sveltejs\/kit\/src\/runtime\/client\/(?:client-entry|entry|payload)\.js$/;
if (!(
@@ -311,8 +326,11 @@ export async function auditOutput(webDirectory) {
expectedMetadata,
'Compiler provenance mismatch'
);
- equal([...pages.keys()], ['index.html'], 'Undeclared prerendered pages');
- admitted.set('index.html', pages.get('index.html'));
+ const expectedPages = hasSearch
+ ? ['index.html', 'search.html']
+ : ['index.html'];
+ equal([...pages.keys()], expectedPages, 'Undeclared prerendered pages');
+ for (const name of expectedPages) admitted.set(name, pages.get(name));
// Adapter fallback has no separate disk input. Reconstruct the exact current
// compiler bootstrap shell from the actual index/manifest/version and source
// template; future framework/resource shapes require scoped tested admission.
@@ -325,17 +343,28 @@ export async function auditOutput(webDirectory) {
const app = Object.values(manifest).find(
(record) => record.name === 'entry/app'
).file;
+ const fallbackModules = new Set();
+ const moduleVisited = new Set();
+ /** @param {string} key */
+ function collectModules(key) {
+ if (moduleVisited.has(key)) return;
+ moduleVisited.add(key);
+ const record = manifest[key];
+ fallbackModules.add(record.file);
+ for (const dependency of record.imports ?? []) collectModules(dependency);
+ }
+ for (const [key, record] of Object.entries(manifest))
+ if (
+ ['entry/start', 'entry/app', 'nodes/0', 'client-entry'].includes(
+ record.name
+ )
+ )
+ collectModules(key);
const preload = [
...index.matchAll(/<link href="\.\/([^"<>]+)" rel="modulepreload">/g)
]
.map((match) => match[1])
- .filter(
- (file) =>
- !file.startsWith('_app/immutable/nodes/') ||
- file ===
- Object.values(manifest).find((record) => record.name === 'nodes/0')
- .file
- );
+ .filter((file) => fallbackModules.has(file));
if (!preload.length || preload.some((file) => !admitted.has(file)))
throw new Error('Invalid compiler preloads');
const fallbackCSS = new Set();