app

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

commit c5c8a0ffb5c5a2d9058c0f76078db78f4d7d87fa
parent 19c5fc473accb3f750e9428165d5a1b70206d203
Author: triesap <tyson@radroots.org>
Date:   Mon,  5 Oct 2026 17:13:39 +0000

web: define private resource handles and safe URL constructors (HCP-018)

- Generate opaque local UUIDs only through explicit platform randomness.
- Build draft and conversation paths without private compose context.
- Restrict contextual back links to safe declared destinations.
- Verify syntax, fallback rendering, and absence of implicit effects.

Diffstat:
Aweb/src/lib/components/ContextBack.svelte | 20++++++++++++++++++++
Aweb/src/lib/private-handles.ts | 19+++++++++++++++++++
Mweb/src/lib/routes.ts | 38++++++++++++++++++++++++++++++++++++++
Aweb/src/params/local_id.ts | 5+++++
Aweb/tests/unit/private-routes.test.ts | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 232 insertions(+), 0 deletions(-)

diff --git a/web/src/lib/components/ContextBack.svelte b/web/src/lib/components/ContextBack.svelte @@ -0,0 +1,20 @@ +<script lang="ts"> + import { internalHref } from '../navigation-url'; + import { safeContextBack } from '../routes'; + type Props = { href?: unknown; fallback?: unknown }; + let { href, fallback = '/search' }: Props = $props(); + let target = $derived( + safeContextBack(href) ?? safeContextBack(fallback) ?? '/search' + ); + let label = $derived( + target === '/selling' + ? 'Back to selling' + : target === '/messages' + ? 'Back to messages' + : target.startsWith('/products/') + ? 'Back to listing' + : 'Search food' + ); +</script> + +<a href={internalHref(target)} class="button button--secondary">{label}</a> diff --git a/web/src/lib/private-handles.ts b/web/src/lib/private-handles.ts @@ -0,0 +1,19 @@ +// Local handles identify records; callers must separately resolve the active owner. +export function canonicalLocalId(value: unknown): string | undefined { + return typeof value === 'string' && + value.length === 36 && + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test( + value + ) + ? value + : undefined; +} + +// Explicit local creation only. No import/render operation creates a handle. +export function newLocalId(): string | undefined { + try { + return canonicalLocalId(globalThis.crypto.randomUUID()); + } catch { + return undefined; + } +} diff --git a/web/src/lib/routes.ts b/web/src/lib/routes.ts @@ -1,5 +1,43 @@ import { decodeProductReference } from './nostr/references'; import { internalHref } from './navigation-url'; +import { canonicalLocalId } from './private-handles'; + +export function staticHref(input: unknown): string | undefined { + switch (input) { + case '/': + case '/search': + case '/sell': + case '/selling': + case '/messages': + case '/about': + case '/privacy': + return internalHref(input); + default: + return undefined; + } +} + +export function draftHref(input: unknown): string | undefined { + const id = canonicalLocalId(input); + return id === undefined ? undefined : internalHref(`/selling/drafts/${id}`); +} + +export function conversationHref(input: unknown): string | undefined { + const id = canonicalLocalId(input); + return id === undefined ? undefined : internalHref(`/messages/${id}`); +} + +export function safeContextBack(input: unknown): string | undefined { + if (input === '/search' || input === '/selling' || input === '/messages') + return internalHref(input); + if ( + typeof input !== 'string' || + input.length > '/products/'.length + 2048 || + !input.startsWith('/products/') + ) + return undefined; + return productHref(input.slice('/products/'.length)); +} export function productHref(input: unknown): string | undefined { const reference = decodeProductReference(input); diff --git a/web/src/params/local_id.ts b/web/src/params/local_id.ts @@ -0,0 +1,5 @@ +import { canonicalLocalId } from '../lib/private-handles'; + +export function match(value: string): boolean { + return canonicalLocalId(value) !== undefined; +} diff --git a/web/tests/unit/private-routes.test.ts b/web/tests/unit/private-routes.test.ts @@ -0,0 +1,150 @@ +import { render } from 'svelte/server'; +import { describe, expect, it, vi } from 'vitest'; +import { canonicalLocalId, newLocalId } from '../../src/lib/private-handles'; +import { + conversationHref, + draftHref, + safeContextBack, + staticHref +} from '../../src/lib/routes'; +import { match } from '../../src/params/local_id'; +import ContextBack from '../../src/lib/components/ContextBack.svelte'; +import { naddrEncode } from 'applesauce-core/helpers/pointers'; +import oracle from './reference-oracle.json'; + +const id = '6b65d774-26f1-4e7e-a414-387d347b3106'; + +describe('opaque private resource URLs', () => { + it('generates canonical UUIDs with the platform randomUUID operation', () => { + const random = vi.spyOn(globalThis.crypto, 'randomUUID'); + const ids = Array.from({ length: 32 }, () => newLocalId()); + expect(random).toHaveBeenCalledTimes(32); + expect(new Set(ids).size).toBe(32); + for (const value of ids) { + expect(canonicalLocalId(value)).toBe(value); + expect(match(value!)).toBe(true); + } + random.mockRestore(); + }); + it('fails safely when platform randomness is unavailable', () => { + const random = vi + .spyOn(globalThis.crypto, 'randomUUID') + .mockImplementation(() => { + throw new Error('Unavailable'); + }); + expect(newLocalId()).toBeUndefined(); + random.mockRestore(); + }); + for (const value of [ + undefined, + null, + {}, + '', + id.toUpperCase(), + ` ${id}`, + `${id}/edit`, + `${id}?body=hello`, + `${id}#peer`, + id.replace('-4e7e-', '-7e7e-'), + id.replace('-a414-', '-0414-'), + '0'.repeat(64), + 'x'.repeat(8193) + ]) + it(`rejects a noncanonical private handle ${JSON.stringify(value)?.slice(0, 80) ?? 'undefined'}`, () => { + expect(canonicalLocalId(value)).toBeUndefined(); + expect(draftHref(value)).toBeUndefined(); + expect(conversationHref(value)).toBeUndefined(); + if (typeof value === 'string') expect(match(value)).toBe(false); + }); + it('puts only the opaque token into both private resource paths', () => { + expect(draftHref(id)).toBe(`/selling/drafts/${id}`); + expect(conversationHref(id)).toBe(`/messages/${id}`); + for (const href of [draftHref(id), conversationHref(id)]) { + const url = new URL(href!, 'https://example.invalid'); + expect(url.search).toBe(''); + expect(url.hash).toBe(''); + expect(url.pathname.endsWith(id)).toBe(true); + } + }); + it('treats unknown but well-formed handles as syntax, never owner/data authority', () => { + expect(match(id)).toBe(true); + expect(draftHref({ id, owner: 'alice', body: 'secret' })).toBeUndefined(); + expect( + conversationHref({ id, peer: 'bob', quantity: '2', listing: 'carrots' }) + ).toBeUndefined(); + expect(safeContextBack(`/selling/drafts/${id}`)).toBeUndefined(); + expect(safeContextBack(`/messages/${id}`)).toBeUndefined(); + }); +}); + +describe('explicit contextual navigation', () => { + it('keeps only canonical public listing context and strips relay hints', () => { + const coordinate = { + kind: 30402, + pubkey: oracle.key_cases[0].pubkey, + identifier: 'Carrots:菜' + }; + const canonical = naddrEncode(coordinate); + const hinted = naddrEncode({ + ...coordinate, + relays: ['wss://example.invalid'] + }); + expect(safeContextBack(`/products/${hinted.toUpperCase()}`)).toBe( + `/products/${canonical}` + ); + const output = render(ContextBack, { + props: { href: `/products/${hinted}` } + }).body; + expect(output).toContain(`href="/products/${canonical}"`); + expect(output).toContain('Back to listing'); + for (const href of [ + `/products/${hinted}/edit`, + `/products/${hinted}?peer=alice`, + '/products/' + 'x'.repeat(2049) + ]) + expect(safeContextBack(href)).toBeUndefined(); + }); + for (const href of [ + '/', + '/search', + '/sell', + '/selling', + '/messages', + '/about', + '/privacy' + ]) + it(`constructs the declared static route ${href}`, () => { + expect(staticHref(href)).toBe(href); + }); + for (const href of [ + 'https://example.invalid/', + '//example.invalid/', + '/orders', + '/search?returnTo=https://example.invalid', + '/messages?peer=alice', + '/selling#body', + '/search/../messages', + '/%2f%2fexample.invalid', + '\\evil', + {} + ]) + it(`rejects arbitrary return context ${JSON.stringify(href)}`, () => { + expect(safeContextBack(href)).toBeUndefined(); + expect(staticHref(href)).toBeUndefined(); + const output = render(ContextBack, { + props: { href, fallback: '/messages' } + }).body; + expect(output).toContain('href="/messages"'); + expect(output).toContain('Back to messages'); + }); + it('renders a safe fallback without acquiring randomness or creating local data', () => { + const random = vi.spyOn(globalThis.crypto, 'randomUUID'); + const output = render(ContextBack, { + props: { href: '/messages/unknown', fallback: '//evil' } + }).body; + expect(output).toContain('href="/search"'); + expect(output).toContain('Search food'); + expect(random).not.toHaveBeenCalled(); + random.mockRestore(); + }); +});