app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit 3e124e14bff26c0a638f581e1e579c99a1b8233a
parent a990c84a3ebc587062990009c68beb9f6d5ba8f6
Author: triesap <tyson@radroots.org>
Date:   Sun,  4 Oct 2026 05:13:56 +0000

web: qualify the static shell and fallback contract (HCP-010)

- Retain prerendered SSR home with a separate strict static fallback
- Keep the semantic guest shell available during fallback hydration
- Admit approved document paths while rejecting missing assets and traversal
- Verify real browser refresh, inert HTML and owned fixture teardown

Diffstat:
Mweb/src/routes/+layout.svelte | 5++++-
Mweb/src/routes/+page.svelte | 4----
Mweb/tests/conformance/static.test.ts | 10++++++++++
Mweb/tests/e2e/bootstrap.spec.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/integration/harness/static.ts | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mweb/tests/integration/loopback.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/unit/bootstrap.test.ts | 6+++---
Mweb/vite.config.ts | 4+++-
8 files changed, 291 insertions(+), 20 deletions(-)

diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte @@ -4,4 +4,7 @@ let { children }: { children: Snippet } = $props(); </script> -{@render children()} +<main> + <h1>HarvestCircle</h1> + {@render children()} +</main> diff --git a/web/src/routes/+page.svelte b/web/src/routes/+page.svelte @@ -1,7 +1,3 @@ <svelte:head> <title>HarvestCircle</title> </svelte:head> - -<main> - <h1>HarvestCircle</h1> -</main> diff --git a/web/tests/conformance/static.test.ts b/web/tests/conformance/static.test.ts @@ -12,6 +12,16 @@ await test('actual static shell is prerendered and excludes controlled harness c const html = await readFile(new URL('index.html', root), 'utf8'); assert.match(html, /<h1>HarvestCircle<\/h1>/); assert.match(html, /<title>HarvestCircle<\/title>/); + const fallback = await readFile(new URL('200.html', root), 'utf8'); + assert.notEqual(fallback, html); + assert.doesNotMatch(fallback, /<h1>HarvestCircle<\/h1>/); + assert.match(fallback, /<script[\s\S]*_app\/immutable/); + for (const document of [html, fallback]) { + assert.doesNotMatch( + document, + /HC_TEST_ONLY_|nostr|private|draft|conversation|signEvent|indexedDB|WebSocket/i + ); + } const metadata = await readFile(new URL('build-info.json', root), 'utf8'); assert.equal( metadata, diff --git a/web/tests/e2e/bootstrap.spec.ts b/web/tests/e2e/bootstrap.spec.ts @@ -3,6 +3,74 @@ import { createRelayHarness } from '../integration/harness/relay.ts'; import { createStaticHarness } from '../integration/harness/static.ts'; import { installControlledProvider } from './harness/provider.ts'; +test('copied nested navigation and refresh boot the real shell without fabricating a product', async ({ + browser +}) => { + const server = await createStaticHarness(); + const context = await browser.newContext(); + const withoutJavaScript = await browser.newContext({ + javaScriptEnabled: false + }); + try { + for (const owned of [context, withoutJavaScript]) { + await owned.route('**/*', (route) => + new URL(route.request().url()).origin === server.url + ? route.continue() + : route.abort() + ); + } + const copiedPath = '/products/unsupported-coordinate'; + const staticPage = await withoutJavaScript.newPage(); + await staticPage.goto(server.url); + await expect( + staticPage.getByRole('heading', { name: 'HarvestCircle' }) + ).toBeVisible(); + await expect(staticPage).toHaveTitle('HarvestCircle'); + const fallback = await staticPage.goto(server.url + copiedPath); + expect(fallback?.status()).toBe(200); + // The separate SPA document has no prerendered product or browser state. + await expect( + staticPage.getByRole('heading', { name: 'HarvestCircle' }) + ).toHaveCount(0); + + const page = await context.newPage(); + const failures: string[] = []; + page.on('pageerror', (error) => failures.push(error.message)); + for (const navigate of [ + () => page.goto(server.url + copiedPath), + () => page.reload() + ]) { + const result = await navigate(); + expect(result?.status()).toBe(200); + await expect( + page.getByRole('heading', { name: 'HarvestCircle' }) + ).toBeVisible(); + // Future product route controllers remain unimplemented in this slice. + await expect( + page.getByRole('heading', { name: '404', exact: true }) + ).toBeVisible(); + await expect(page.getByText('Not Found', { exact: true })).toBeVisible(); + expect(new URL(page.url()).pathname).toBe(copiedPath); + expect(await page.evaluate(() => 'nostr' in window)).toBe(false); + } + expect(failures).toEqual([]); + for (const asset of ['/missing.js', '/missing.css', '/_app/missing.png']) { + const response = await context.request.get(server.url + asset, { + headers: { accept: 'text/html' } + }); + expect(response.status()).toBe(404); + expect(await response.text()).toBe(''); + } + } finally { + await context.close(); + await withoutJavaScript.close(); + await server.close(); + } + expect(context.pages()).toHaveLength(0); + expect(withoutJavaScript.pages()).toHaveLength(0); + expect(server.state()).toEqual({ listening: false, childProcesses: 0 }); +}); + test('actual browser loads guest shell without an extension', async ({ browser }) => { diff --git a/web/tests/integration/harness/static.ts b/web/tests/integration/harness/static.ts @@ -1,10 +1,47 @@ import { createServer } from 'node:http'; import { once } from 'node:events'; -import { readFile, realpath } from 'node:fs/promises'; +import { readFile, realpath, stat } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -// HC_TEST_ONLY_STATIC_SERVER: exact static files only; no dynamic fallback. +// HC_TEST_ONLY_STATIC_SERVER: target-neutral static host contract, not an app server. +// Admission is URL syntax only; client route owners validate coordinates and authority. +function isNavigationPath(pathname: string) { + if (new TextEncoder().encode(pathname).length > 2048) return false; + const segments = pathname.slice(1).split('/'); + if (segments.some((segment) => !/^[A-Za-z0-9_-]+$/.test(segment))) + return pathname === '/'; + const publicShells = new Set([ + 'search', + 'sell', + 'selling', + 'messages', + 'about', + 'privacy' + ]); + return ( + (segments.length === 1 && publicShells.has(segments[0])) || + (segments[0] === 'products' && + (segments.length === 2 || + (segments.length === 3 && segments[2] === 'edit'))) || + (segments[0] === 'selling' && + segments[1] === 'drafts' && + segments.length === 3) || + (segments[0] === 'messages' && segments.length === 2) + ); +} + +function acceptsHtml(accept: string) { + return accept.split(',').some((entry) => { + const [type, ...parameters] = entry.trim().split(';'); + if (type?.trim().toLowerCase() !== 'text/html') return false; + const quality = parameters.find((parameter) => + parameter.trim().startsWith('q=') + ); + return !quality || Number(quality.trim().slice(2)) > 0; + }); +} + export async function createStaticHarness() { const root = await realpath( fileURLToPath(new URL('../../../build/', import.meta.url)) @@ -15,15 +52,56 @@ export async function createStaticHarness() { response.writeHead(405).end(); return; } - const url = new URL(request.url ?? '/', 'http://127.0.0.1'); - const requested = decodeURIComponent(url.pathname); - const file = await realpath( - path.resolve( - root, - '.' + (requested === '/' ? '/index.html' : requested) - ) - ); - if (!file.startsWith(root + path.sep)) { + // Validate before URL parsing can normalize literal or encoded dot segments. + const raw = (request.url ?? '/').split('?')[0]; + if (!raw.startsWith('/') || /%2f|%5c|%25/i.test(raw)) { + response.writeHead(404).end(); + return; + } + const requested = decodeURIComponent(raw); + if ( + /[\\#]/u.test(requested) || + [...requested].some( + (character) => + character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127 + ) || + requested + .split('/') + .some((segment) => segment === '.' || segment === '..') + ) { + response.writeHead(404).end(); + return; + } + async function existing(relative: string) { + try { + const candidate = await realpath(path.resolve(root, '.' + relative)); + if ( + !candidate.startsWith(root + path.sep) || + !(await stat(candidate)).isFile() + ) + return null; + return candidate; + } catch { + return null; + } + } + let file = await existing(requested === '/' ? '/index.html' : requested); + const navigation = isNavigationPath(requested); + if (!file && navigation) { + file = + (await existing(requested + '.html')) ?? + (await existing(requested + '/index.html')); + } + if ( + !file && + navigation && + acceptsHtml(request.headers.accept ?? '') && + (!request.headers['sec-fetch-dest'] || + request.headers['sec-fetch-dest'] === 'document') + ) { + file = await existing('/200.html'); + } + if (!file) { response.writeHead(404).end(); return; } diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts @@ -1,6 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { once } from 'node:events'; +import { request } from 'node:http'; +import { readFile } from 'node:fs/promises'; import WebSocket from 'ws'; import { createRelayHarness } from './harness/relay.ts'; import { createStaticHarness } from './harness/static.ts'; @@ -33,6 +35,118 @@ await test('real loopback REQ/CLOSE and active teardown release owned resources' assert.equal(socket.readyState, WebSocket.CLOSED); }); +await test('navigation fallback serves actual separate output and preserves missing assets', async () => { + const server = await createStaticHarness(); + const fallback = await readFile( + new URL('../../build/200.html', import.meta.url), + 'utf8' + ); + const document = { accept: 'text/html', 'sec-fetch-dest': 'document' }; + try { + for (const pathname of [ + '/search?q=food', + '/sell', + '/selling', + '/messages', + '/about', + '/privacy', + '/products/unsupported-coordinate', + '/products/unsupported-coordinate/edit', + '/selling/drafts/unknown-draft', + '/messages/unknown-conversation' + ]) { + 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); + } + for (const pathname of [ + '/missing.js', + '/missing.css', + '/missing.json', + '/missing.png', + '/_app/missing', + '/assets/missing', + '/products/missing.js', + '/unowned', + '/products/', + '/products/a/extra', + '/products/a.b' + ]) { + const result = await fetch(server.url + pathname, { headers: document }); + assert.equal(result.status, 404, pathname); + assert.doesNotMatch(result.headers.get('content-type') ?? '', /html/); + assert.equal(await result.text(), ''); + } + const rejectedHeaders: Record<string, string>[] = [ + { accept: '*/*' }, + { accept: 'application/json' }, + { accept: 'text/html;q=0' }, + { accept: 'text/html', 'sec-fetch-dest': 'script' } + ]; + for (const headers of rejectedHeaders) { + assert.equal( + (await fetch(server.url + '/products/a', { headers })).status, + 404 + ); + } + assert.equal( + ( + await fetch(server.url + '/products/a', { + method: 'POST', + headers: document + }) + ).status, + 405 + ); + // node:http retains raw paths that URL/fetch would normalize before sending. + for (const pathname of [ + '/../index.html', + '/products/../index.html', + '/%2e%2e/index.html', + '/products%2fa', + '/products/%252e%252e', + '/products/%5cfoo', + '/products/%00', + '/products/%zz', + '/products/' + 'a'.repeat(2048) + ]) { + const status = await new Promise<number | undefined>( + (resolve, reject) => { + const req = request( + server.url, + { path: pathname, headers: document }, + (response) => { + response.resume(); + response.on('end', () => resolve(response.statusCode)); + } + ); + req.on('error', reject); + req.end(); + } + ); + assert.equal(status, 404, pathname); + } + const metadata = await fetch(server.url + '/build-info.json', { + headers: document + }); + assert.equal(metadata.status, 200); + assert.equal(metadata.headers.get('content-type'), 'application/json'); + assert.deepEqual( + await metadata.json(), + JSON.parse( + await readFile( + new URL('../../build/build-info.json', import.meta.url), + 'utf8' + ) + ) + ); + } finally { + await server.close(); + } + assert.deepEqual(server.state(), { listening: false, childProcesses: 0 }); +}); + await test('loopback static fixture serves actual output and closes its listener', async () => { const server = await createStaticHarness(); try { diff --git a/web/tests/unit/bootstrap.test.ts b/web/tests/unit/bootstrap.test.ts @@ -1,8 +1,7 @@ import { render } from 'svelte/server'; import { describe, expect, it } from 'vitest'; -import Page from '../../src/routes/+page.svelte'; import Shell from './Shell.svelte'; -import { prerender } from '../../src/routes/+layout'; +import { prerender, ssr } from '../../src/routes/+layout'; describe('static guest shell', () => { it('keeps browser globals absent and enforces effect tripwires', () => { @@ -18,10 +17,11 @@ describe('static guest shell', () => { ); }); it('imports and renders on the server without browser capabilities', () => { - const output = render(Page); + const output = render(Shell); expect(output.body).toContain('<h1>HarvestCircle</h1>'); expect(output.head).toContain('<title>HarvestCircle</title>'); expect(prerender).toBe(true); + expect(ssr).toBe(true); }); it('composes the root layout and route with semantic guest content', () => { const output = render(Shell); diff --git a/web/vite.config.ts b/web/vite.config.ts @@ -3,5 +3,7 @@ import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ - plugins: [sveltekit({ adapter: adapter({ strict: true }) })] + plugins: [ + sveltekit({ adapter: adapter({ strict: true, fallback: '200.html' }) }) + ] });