commit aae0805cc6c754219508c30fb93ec1468eface68
parent 6023db01169aa82cb6fe68ca94e1a73750247e72
Author: triesap <tyson@radroots.org>
Date: Wed, 7 Oct 2026 03:21:45 +0000
web: wire shared connection and unsupported-capability gates (HCP-056)
- Bind shared gates to explicit per-client identity and capability actions.
- Fence focus to the originating action, session, view and mounted gate.
- Preserve public lifecycle and audit the exact identity compiler profile.
- Verify SSR, SDK isolation, browser behavior and historical output profiles.
Diffstat:
23 files changed, 1653 insertions(+), 83 deletions(-)
diff --git a/web/eslint.config.js b/web/eslint.config.js
@@ -29,6 +29,10 @@ export default defineConfig(
svelte.configs.recommended,
svelte.configs.prettier,
{
+ files: ['src/lib/components/CapabilityGate.svelte'],
+ languageOptions: { globals: { document: 'readonly' } }
+ },
+ {
files: ['**/*.svelte'],
languageOptions: { parserOptions: { parser: ts.parser, svelteConfig } },
rules: { 'svelte/no-inline-styles': 'error' }
diff --git a/web/src/lib/components/AccountGate.svelte b/web/src/lib/components/AccountGate.svelte
@@ -1,17 +1,52 @@
<script lang="ts">
+ import { getContext, onMount } from 'svelte';
+ import CapabilityGate from './CapabilityGate.svelte';
import Button from './primitives/Button.svelte';
+ import {
+ IDENTITY_VIEW_CONTEXT,
+ identityViewSnapshot,
+ subscribeIdentityView,
+ connectIdentityView,
+ disconnectIdentityView,
+ probeIdentityViewMessaging,
+ type IdentityViewContext
+ } from '../runtime/view-context.ts';
+ const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);
+ let view = $state(identityViewSnapshot(context));
+ onMount(() =>
+ subscribeIdentityView(context, (next) => {
+ view = next;
+ })
+ );
+ function connect() {
+ return connectIdentityView(context);
+ }
+ function disconnect() {
+ disconnectIdentityView(context);
+ }
+ function probe() {
+ return probeIdentityViewMessaging(context, 'reviewed_self_copy');
+ }
</script>
-<svelte:head>
- <title>HarvestCircle</title>
- <meta name="robots" content="noindex" />
-</svelte:head>
+<svelte:head
+ ><title>HarvestCircle</title><meta
+ name="robots"
+ content="noindex"
+ /></svelte:head
+>
<div class="page page--reading stack">
<h1>Connect or unlock</h1>
- <p>Connect an extension and unlock your account to continue.</p>
- <p class="notice">Account access is unavailable during development.</p>
- <div class="cluster">
- <Button label="Connect extension" disabled />
- <Button label="Unlock" disabled />
- </div>
+ <CapabilityGate
+ focusTarget="protected"
+ ondisconnect={disconnect}
+ identity={view.identity}
+ required="messaging"
+ onconnect={view.mounted ? connect : undefined}
+ onprobe={view.mounted ? probe : undefined}
+ />
+ <p class="notice">
+ Private views and editing are unavailable during development.
+ </p>
+ <Button label="Unlock" disabled />
</div>
diff --git a/web/src/lib/components/AppShell.svelte b/web/src/lib/components/AppShell.svelte
@@ -2,25 +2,45 @@
import type { Snippet } from 'svelte';
import { internalHref } from '../navigation-url';
import Button from './primitives/Button.svelte';
+ import CapabilityGate from './CapabilityGate.svelte';
+ import type { IdentityViewActionResult } from '../runtime/view-context.ts';
+ import type { IdentitySnapshot } from '../runtime/identity-session.ts';
import Disclosure from './primitives/Disclosure.svelte';
type ShellRoute =
'/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy';
type Identity =
- | { kind: 'guest'; onconnect?: () => void }
+ | {
+ kind: 'guest';
+ onconnect?: () => Promise<IdentityViewActionResult> | void;
+ }
| { kind: 'connected'; publicKey: string; ondisconnect?: () => void };
let {
children,
currentPath = '/',
availableRoutes = [],
- identity = { kind: 'guest' }
+ identity = { kind: 'guest' },
+ capability,
+ ondisconnect
}: {
children: Snippet;
currentPath?: string;
availableRoutes?: readonly ShellRoute[];
identity?: Identity;
+ capability?: IdentitySnapshot;
+ ondisconnect?: () => void;
} = $props();
+ const observed = $derived(
+ capability ??
+ (identity.kind === 'guest'
+ ? { state: 'guest' as const, reason: 'disconnected' as const }
+ : {
+ state: 'connected' as const,
+ publicKey: identity.publicKey,
+ messaging: 'not_probed' as const
+ })
+ );
const unavailable = $derived(
!availableRoutes.includes('/search') ||
!availableRoutes.includes('/about') ||
@@ -68,11 +88,7 @@
{@render navigation('Search', '/search')}
{#if identity.kind === 'guest'}
{@render navigation('List food', '/sell')}
- <Button
- label="Connect extension"
- disabled={!identity.onconnect}
- onclick={identity.onconnect}
- />
+ {@render navigation('Messages', '/messages')}
{:else}
{@render navigation('Messages', '/messages')}
{@render navigation('Selling', '/selling')}
@@ -85,6 +101,14 @@
/>
</Disclosure>
{/if}
+ <CapabilityGate
+ focusTarget="navbar"
+ {ondisconnect}
+ identity={observed}
+ compact
+ focusScope={currentPath}
+ onconnect={identity.kind === 'guest' ? identity.onconnect : undefined}
+ />
</div>
{#if unavailable}
<p id="shell-availability" class="text-small text-muted">
diff --git a/web/src/lib/components/CapabilityGate.svelte b/web/src/lib/components/CapabilityGate.svelte
@@ -0,0 +1,133 @@
+<script lang="ts">
+ import { onMount, tick } from 'svelte';
+ import type { IdentityViewActionResult } from '../runtime/view-context.ts';
+ import type { IdentitySnapshot } from '../runtime/identity-session.ts';
+ import Button from './primitives/Button.svelte';
+ import { internalHref } from '../navigation-url.ts';
+ let {
+ identity,
+ required = 'connection',
+ compact = false,
+ focusScope = '',
+ focusTarget = 'inline',
+ ondisconnect,
+ onconnect,
+ onprobe
+ }: {
+ identity: IdentitySnapshot;
+ required?: 'connection' | 'messaging';
+ compact?: boolean;
+ focusScope?: string;
+ focusTarget?: 'navbar' | 'protected' | 'inline';
+ ondisconnect?: () => void;
+ onconnect?: () => Promise<IdentityViewActionResult> | void;
+ onprobe?: () => Promise<IdentityViewActionResult> | void;
+ } = $props();
+ let alive = false;
+ onMount(() => {
+ alive = true;
+ return () => {
+ alive = false;
+ };
+ });
+ const connected = $derived(
+ identity.state !== 'guest' && identity.state !== 'pending'
+ );
+ const text = $derived(
+ identity.admission === 'busy'
+ ? 'An extension request is still pending. Wait for it to finish before trying again.'
+ : identity.state === 'pending'
+ ? 'Waiting for extension approval.'
+ : identity.state === 'guest'
+ ? identity.reason === 'refused'
+ ? 'Connection was not approved.'
+ : identity.reason === 'missing' || identity.reason === 'unavailable'
+ ? 'A compatible Nostr extension is not available.'
+ : identity.reason === 'changed_key'
+ ? 'The extension identity changed. Connect again to continue.'
+ : identity.reason === 'invalid_key'
+ ? 'The extension did not return a supported identity.'
+ : 'Use your Nostr extension to choose your identity.'
+ : required === 'connection'
+ ? 'Connected.'
+ : identity.messaging === 'capable'
+ ? 'Messaging support checked.'
+ : identity.messaging === 'unsupported'
+ ? 'This extension does not support the required message encryption.'
+ : identity.messaging === 'refused'
+ ? 'The messaging support check was not approved.'
+ : 'Check support for message encryption before continuing.'
+ );
+ async function run(
+ command: (() => Promise<IdentityViewActionResult> | void) | undefined,
+ messaging: boolean
+ ) {
+ const originalScope = focusScope;
+ let result: IdentityViewActionResult | void;
+ try {
+ result = await command?.();
+ } catch {
+ return;
+ }
+ if (
+ !result ||
+ !result.current() ||
+ result.identity.admission === 'busy' ||
+ result.identity.state === 'guest' ||
+ result.identity.state === 'pending' ||
+ (messaging && result.identity.messaging !== 'capable')
+ )
+ return;
+ await tick();
+ if (!alive || focusScope !== originalScope || !result.current()) return;
+ if (focusTarget === 'navbar')
+ document.getElementById('identity-navbar-status')?.focus();
+ else if (focusTarget === 'protected')
+ document.getElementById('identity-protected-status')?.focus();
+ else document.getElementById('identity-inline-status')?.focus();
+ }
+ function connect() {
+ void run(onconnect, false);
+ }
+ function probe() {
+ void run(onprobe, true);
+ }
+</script>
+
+{#if !compact}<h2>
+ {connected ? 'Connection capabilities' : 'Connect to continue'}
+ </h2>{/if}
+<p
+ id={focusTarget === 'navbar'
+ ? 'identity-navbar-status'
+ : focusTarget === 'protected'
+ ? 'identity-protected-status'
+ : 'identity-inline-status'}
+ role="status"
+ tabindex="-1"
+>
+ {text}
+</p>
+{#if !connected}
+ {#if !compact}<p>Your private key stays in the extension.</p>{/if}
+ <Button
+ label="Connect extension"
+ disabled={identity.state === 'pending' || !onconnect}
+ onclick={connect}
+ />
+ {#if identity.state === 'pending' && ondisconnect}<Button
+ label="Disconnect"
+ onclick={ondisconnect}
+ />{/if}
+ {#if !compact}<div class="cluster">
+ <a href={internalHref('/search')}>Keep browsing</a><a
+ href={internalHref('/about#help')}>Connection help</a
+ >
+ </div>{/if}
+{:else if identity.state !== 'guest' && identity.state !== 'pending' && required === 'messaging' && identity.messaging !== 'capable'}
+ <p>
+ This check asks your extension to encrypt and decrypt a disposable
+ self-copy. It does not unlock messages or change public inbox preferences.
+ </p>
+ <Button label="Check messaging support" disabled={!onprobe} onclick={probe} />
+{/if}
diff --git a/web/src/lib/runtime/view-context.ts b/web/src/lib/runtime/view-context.ts
@@ -0,0 +1,192 @@
+import {
+ createIdentitySession,
+ identitySessionSnapshot,
+ connectIdentity,
+ disconnectIdentity,
+ probeIdentityMessaging,
+ invalidateIdentityOperations,
+ type IdentitySession,
+ type IdentitySnapshot
+} from './identity-session.ts';
+declare const viewBrand: unique symbol;
+export type IdentityViewContext = Readonly<{ [viewBrand]: true }>;
+export type IdentityViewSnapshot = Readonly<{
+ mounted: boolean;
+ identity: IdentitySnapshot;
+}>;
+export type IdentityViewActionResult = IdentityViewSnapshot &
+ Readonly<{ current(): boolean }>;
+export const IDENTITY_VIEW_CONTEXT = 'harvestcircle_identity_view';
+type Listener = (state: IdentityViewSnapshot) => void;
+type Controller = {
+ session: IdentitySession;
+ snapshot(): IdentityViewSnapshot;
+ mount(): boolean;
+ connect(): Promise<IdentityViewActionResult>;
+ probe(review: unknown): Promise<IdentityViewActionResult>;
+ disconnect(): void;
+ close(): void;
+ subscribe(listener: Listener): () => void;
+ invalidate(): void;
+};
+const contexts = new WeakMap<IdentityViewContext, Controller>();
+const unavailable = (): IdentityViewSnapshot => ({
+ mounted: false,
+ identity: { state: 'guest', reason: 'unavailable' }
+});
+// Per-client context construction is SSR-pure. Observed key/capability never
+// authorizes private content, installed storage, inbox readiness or publication.
+export function createIdentityViewContext(): IdentityViewContext {
+ const token = Object.freeze({}) as IdentityViewContext;
+ const session = createIdentitySession();
+ const listeners = new Map<symbol, Listener>();
+ let mounted = false,
+ closed = false,
+ busy = false,
+ generation = Symbol(),
+ viewGeneration = Symbol(),
+ actionGeneration = Symbol();
+ const snapshot = (): IdentityViewSnapshot =>
+ closed
+ ? unavailable()
+ : {
+ mounted,
+ identity: busy
+ ? { ...identitySessionSnapshot(session), admission: 'busy' }
+ : identitySessionSnapshot(session)
+ };
+ function notify() {
+ for (const listener of listeners.values()) {
+ try {
+ listener(snapshot());
+ } catch {
+ /* A presentation observer cannot interrupt owned SDK settlement. */
+ }
+ }
+ }
+ async function action(work: () => Promise<IdentitySnapshot>) {
+ if (!mounted || closed) return { ...snapshot(), current: () => false };
+ busy = false;
+ actionGeneration = Symbol();
+ const originalAction = actionGeneration,
+ original = generation,
+ originalView = viewGeneration,
+ pending = work();
+ notify();
+ const result = await pending;
+ if (!closed && original === generation) {
+ busy = result.admission === 'busy';
+ notify();
+ }
+ return {
+ ...snapshot(),
+ current: () =>
+ !closed &&
+ mounted &&
+ actionGeneration === originalAction &&
+ generation === original &&
+ viewGeneration === originalView
+ };
+ }
+ contexts.set(token, {
+ session,
+ snapshot,
+ invalidate() {
+ viewGeneration = Symbol();
+ invalidateIdentityOperations(session);
+ },
+ mount() {
+ if (closed || typeof window === 'undefined') return false;
+ mounted = true;
+ notify();
+ return true;
+ },
+ connect: () => action(() => connectIdentity(session)),
+ probe: (review) => action(() => probeIdentityMessaging(session, review)),
+ disconnect() {
+ if (closed) return;
+ generation = Symbol();
+ busy = false;
+ disconnectIdentity(session);
+ notify();
+ },
+ close() {
+ if (closed) return;
+ generation = Symbol();
+ busy = false;
+ disconnectIdentity(session);
+ closed = true;
+ mounted = false;
+ notify();
+ listeners.clear();
+ },
+ subscribe(listener) {
+ if (closed) return () => {};
+ const subscription = Symbol();
+ listeners.set(subscription, listener);
+ try {
+ listener(snapshot());
+ } catch {
+ /* Isolate presentation observers. */
+ }
+ return () => {
+ listeners.delete(subscription);
+ };
+ }
+ });
+ return token;
+}
+export function identityViewSnapshot(
+ context: IdentityViewContext
+): IdentityViewSnapshot {
+ return contexts.get(context)?.snapshot() ?? unavailable();
+}
+export function mountIdentityView(context: IdentityViewContext): boolean {
+ return contexts.get(context)?.mount() ?? false;
+}
+export function connectIdentityView(
+ context: IdentityViewContext
+): Promise<IdentityViewActionResult> {
+ return (
+ contexts.get(context)?.connect() ??
+ Promise.resolve({ ...unavailable(), current: () => false })
+ );
+}
+export function probeIdentityViewMessaging(
+ context: IdentityViewContext,
+ review: unknown
+): Promise<IdentityViewActionResult> {
+ return (
+ contexts.get(context)?.probe(review) ??
+ Promise.resolve({ ...unavailable(), current: () => false })
+ );
+}
+export function disconnectIdentityView(context: IdentityViewContext): void {
+ contexts.get(context)?.disconnect();
+}
+export function closeIdentityView(context: IdentityViewContext): void {
+ contexts.get(context)?.close();
+}
+export function subscribeIdentityView(
+ context: IdentityViewContext,
+ listener: Listener
+): () => void {
+ return contexts.get(context)?.subscribe(listener) ?? (() => {});
+}
+export function invalidateIdentityView(context: IdentityViewContext): void {
+ const owned = contexts.get(context);
+ owned?.invalidate();
+}
+// Mechanical observed-owner comparison only, never private authorization.
+export function identityViewMatchesOwner(
+ context: IdentityViewContext,
+ owner: unknown
+): boolean {
+ const state = contexts.get(context)?.snapshot();
+ return (
+ state?.mounted === true &&
+ state.identity.state !== 'guest' &&
+ state.identity.state !== 'pending' &&
+ state.identity.publicKey === owner
+ );
+}
diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte
@@ -10,6 +10,42 @@
} from '../lib/runtime/public-runtime.ts';
import { page } from '$app/state';
import AppShell from '../lib/components/AppShell.svelte';
+ import {
+ createIdentityViewContext,
+ IDENTITY_VIEW_CONTEXT,
+ identityViewSnapshot,
+ mountIdentityView,
+ subscribeIdentityView,
+ connectIdentityView,
+ disconnectIdentityView,
+ closeIdentityView,
+ invalidateIdentityView
+ } from '../lib/runtime/view-context.ts';
+ const identityContext = createIdentityViewContext();
+ setContext(IDENTITY_VIEW_CONTEXT, identityContext);
+ let identityView = $state(identityViewSnapshot(identityContext));
+ $effect(() => {
+ if (page.url.pathname) invalidateIdentityView(identityContext);
+ });
+ function connect() {
+ return connectIdentityView(identityContext);
+ }
+ function disconnect() {
+ disconnectIdentityView(identityContext);
+ }
+ const shellIdentity = $derived(
+ identityView.identity.state === 'guest' ||
+ identityView.identity.state === 'pending'
+ ? {
+ kind: 'guest' as const,
+ onconnect: identityView.mounted ? connect : undefined
+ }
+ : {
+ kind: 'connected' as const,
+ publicKey: identityView.identity.publicKey,
+ ondisconnect: disconnect
+ }
+ );
const publicContext = createPublicRuntimeContext();
setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);
@@ -17,11 +53,24 @@
mountPublicRuntime(publicContext);
return () => closePublicRuntime(publicContext);
});
+ onMount(() => {
+ const off = subscribeIdentityView(identityContext, (next) => {
+ identityView = next;
+ });
+ mountIdentityView(identityContext);
+ return () => {
+ off();
+ closeIdentityView(identityContext);
+ };
+ });
let { children }: { children: Snippet } = $props();
</script>
<AppShell
+ identity={shellIdentity}
+ capability={identityView.identity}
+ ondisconnect={disconnect}
currentPath={page.url.pathname}
availableRoutes={[
'/search',
diff --git a/web/tests/conformance/static.test.ts b/web/tests/conformance/static.test.ts
@@ -16,9 +16,15 @@ await test('actual static shell is prerendered and excludes controlled harness c
assert.notEqual(fallback, html);
assert.doesNotMatch(fallback, /<a[^>]*href="\/"[^>]*>HarvestCircle<\/a>/);
assert.match(fallback, /<script[\s\S]*_app\/immutable/);
+ // Admit the exact public SSR notice, while retaining the original scan
+ // against private state, runtime effects and fixture markers elsewhere.
+ const identityNotice =
+ '<p id="identity-navbar-status" role="status" tabindex="-1">Use your Nostr extension to choose your identity.</p>';
+ assert.equal(html.split(identityNotice).length, 2);
+ assert.ok(!fallback.includes(identityNotice));
for (const document of [html, fallback]) {
assert.doesNotMatch(
- document,
+ document.replace(identityNotice, ''),
/HC_TEST_ONLY_|nostr|private|draft|conversation|signEvent|indexedDB|WebSocket/i
);
}
diff --git a/web/tests/e2e/bootstrap.spec.ts b/web/tests/e2e/bootstrap.spec.ts
@@ -123,15 +123,18 @@ test('actual browser loads guest shell without an extension', async ({
).toBeVisible();
await expect(
page.getByRole('button', { name: 'Connect extension' })
- ).toBeDisabled();
+ ).toBeEnabled();
await expect(
page.getByText(
'Unavailable during development: disabled navigation and actions.'
)
- ).toBeVisible();
+ ).toHaveCount(0);
await expect(
page.getByRole('link', { name: 'Search', exact: true })
).toHaveCount(1);
+ await expect(
+ page.getByRole('link', { name: 'Messages', exact: true })
+ ).toHaveAttribute('href', '/messages');
await page.keyboard.press('Tab');
await expect(
page.getByRole('link', { name: 'Skip to main content' })
diff --git a/web/tests/e2e/capability-gate.spec.ts b/web/tests/e2e/capability-gate.spec.ts
@@ -0,0 +1,491 @@
+import { test, expect, type BrowserContext } from '@playwright/test';
+import { execFileSync } from 'node:child_process';
+import { cp, mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createHash } from 'node:crypto';
+import { createStaticHarness } from '../integration/harness/static.ts';
+declare global {
+ interface Window {
+ hcp056Counts: {
+ keys: number;
+ signs: number;
+ encrypts: number;
+ decrypts: number;
+ };
+ hcp056Release?: () => void;
+ }
+}
+const owner =
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
+async function provider(
+ context: BrowserContext,
+ mode: 'exact' | 'refused' | 'pending' | 'unsupported' = 'exact'
+) {
+ await context.addInitScript(
+ ({ owner, mode }) => {
+ window.hcp056Counts = { keys: 0, signs: 0, encrypts: 0, decrypts: 0 };
+ window.nostr = {
+ getPublicKey: () => {
+ window.hcp056Counts.keys++;
+ if (mode === 'refused')
+ return Promise.reject(new Error('HC_TEST_RAW_PROVIDER_DIAGNOSTIC'));
+ if (mode === 'pending')
+ return new Promise<string>((resolve) => {
+ window.hcp056Release = () => resolve(owner);
+ });
+ return Promise.resolve(owner);
+ },
+ signEvent: () => {
+ window.hcp056Counts.signs++;
+ return Promise.reject(new Error('Unexpected signature'));
+ },
+ ...(mode === 'unsupported'
+ ? {}
+ : {
+ nip44: {
+ encrypt: (_key: string, text: string) => {
+ window.hcp056Counts.encrypts++;
+ return Promise.resolve(text);
+ },
+ decrypt: (_key: string, text: string) => {
+ window.hcp056Counts.decrypts++;
+ return Promise.resolve(text);
+ }
+ }
+ })
+ };
+ },
+ { owner, mode }
+ );
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+});
+test.afterAll(async () => {
+ await server.close();
+});
+test('explicit Connect is enabled after hydration and never repeats Send', async ({
+ browser
+}) => {
+ const context = await browser.newContext();
+ await provider(context);
+ try {
+ const page = await context.newPage();
+ await page.goto(server.url + '/messages');
+ const main = page.getByRole('main'),
+ connect = main.getByRole('button', {
+ name: 'Connect extension',
+ exact: true
+ });
+ await expect(connect).toBeEnabled();
+ await connect.focus();
+ await page.keyboard.press('Enter');
+ await expect(page.getByText('Identity', { exact: true })).toBeVisible();
+ await expect(main.locator('[role="status"][tabindex="-1"]')).toBeFocused();
+ await expect(main.locator('input, textarea, form')).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp056Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+ expect(await main.textContent()).not.toContain(
+ 'HC_TEST_RAW_PROVIDER_DIAGNOSTIC'
+ );
+ await page.locator('summary').click();
+ await page.getByRole('button', { name: 'Disconnect', exact: true }).click();
+ await expect(connect).toBeEnabled();
+ expect(await page.evaluate(() => window.hcp056Counts.keys)).toBe(1);
+ } finally {
+ await context.close();
+ }
+});
+test('failed protected Connect cannot steal focus from a later navbar Connect', async ({
+ browser
+}) => {
+ const context = await browser.newContext();
+ await context.addInitScript((owner) => {
+ let calls = 0;
+ window.nostr = {
+ getPublicKey: () =>
+ ++calls === 1
+ ? Promise.reject(new Error('denied'))
+ : Promise.resolve(owner),
+ signEvent: () => Promise.reject(new Error('Unexpected signature'))
+ };
+ }, owner);
+ try {
+ const page = await context.newPage();
+ await page.goto(server.url + '/messages');
+ const main = page.getByRole('main');
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await expect(
+ main.getByText('Connection was not approved.', { exact: true })
+ ).toBeVisible();
+ await page
+ .getByRole('navigation', { name: 'Primary' })
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await expect(page.getByText('Identity', { exact: true })).toBeVisible();
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP056_COMPETING_FOCUS',
+ activeId: await page.evaluate(() => document.activeElement?.id)
+ })
+ );
+ await expect(page.locator('#identity-navbar-status')).toBeFocused();
+ await expect(main.locator('#identity-protected-status')).not.toBeFocused();
+ } finally {
+ await context.close();
+ }
+});
+test('Messages is discoverable to guests without acquiring identity or private data', async ({
+ browser
+}) => {
+ const context = await browser.newContext();
+ await provider(context);
+ try {
+ const page = await context.newPage();
+ await page.goto(server.url + '/about');
+ const messages = page
+ .getByRole('navigation', { name: 'Primary' })
+ .getByRole('link', { name: 'Messages', exact: true });
+ await expect(messages).toHaveAttribute('href', '/messages');
+ await messages.click();
+ await expect(
+ page
+ .getByRole('main')
+ .getByRole('heading', { name: 'Connect or unlock', exact: true })
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.hcp056Counts.keys)).toBe(0);
+ await expect(
+ page.locator('main input, main textarea, main form')
+ ).toHaveCount(0);
+ } finally {
+ await context.close();
+ }
+});
+test('denied connection has finite help and no raw provider diagnostic', async ({
+ browser
+}) => {
+ const context = await browser.newContext();
+ await provider(context, 'refused');
+ try {
+ const page = await context.newPage();
+ await page.goto(server.url + '/messages');
+ const main = page.getByRole('main');
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await expect(
+ main.getByText('Connection was not approved.', { exact: true })
+ ).toBeVisible();
+ await expect(
+ main.getByRole('link', { name: 'Connection help' })
+ ).toHaveAttribute('href', '/about#help');
+ expect(await main.textContent()).not.toContain(
+ 'HC_TEST_RAW_PROVIDER_DIAGNOSTIC'
+ );
+ expect(await page.evaluate(() => window.hcp056Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+ } finally {
+ await context.close();
+ }
+});
+test('pending connection survives route change without restoring a protected form or scheduling again', async ({
+ browser
+}) => {
+ const context = await browser.newContext();
+ await provider(context, 'pending');
+ try {
+ const page = await context.newPage();
+ await page.goto(server.url + '/messages');
+ await page
+ .locator('main')
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await expect(
+ page
+ .locator('main')
+ .getByText('Waiting for extension approval.', { exact: true })
+ ).toBeVisible();
+ await page.getByRole('link', { name: 'Search', exact: true }).click();
+ const retained = page.getByLabel('What are you looking for?');
+ await retained.focus();
+ await page.evaluate(() => window.hcp056Release?.());
+ await expect(page.getByText('Identity', { exact: true })).toBeVisible();
+ await expect(retained).toBeFocused();
+ await expect(page.getByLabel('What are you looking for?')).toBeVisible();
+ expect(await page.evaluate(() => window.hcp056Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+ } finally {
+ await context.close();
+ }
+});
+test('Disconnect while approval is pending keeps the real slot and fences late connection', async ({
+ browser
+}) => {
+ const context = await browser.newContext();
+ await provider(context, 'pending');
+ try {
+ const page = await context.newPage();
+ await page.goto(server.url + '/messages');
+ const main = page.getByRole('main');
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await main.getByRole('button', { name: 'Disconnect', exact: true }).click();
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await expect(
+ main.getByText(
+ 'An extension request is still pending. Wait for it to finish before trying again.',
+ { exact: true }
+ )
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.hcp056Counts.keys)).toBe(1);
+ await page.evaluate(() => window.hcp056Release?.());
+ await expect(page.locator('summary')).toHaveCount(0);
+ await expect(main.locator('input, textarea, form')).toHaveCount(0);
+ expect(await page.evaluate(() => window.hcp056Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+ // The old genuine SDK job must actually settle before the same author
+ // can connect again. The later navbar action owns focus on this same URL.
+ const navbarConnect = page
+ .getByRole('navigation', { name: 'Primary', exact: true })
+ .getByRole('button', { name: 'Connect extension', exact: true });
+ await expect
+ .poll(async () => {
+ await navbarConnect.click();
+ return page.evaluate(() => window.hcp056Counts.keys);
+ })
+ .toBe(2);
+ await page.evaluate(() => window.hcp056Release?.());
+ await expect(page.getByText('Identity', { exact: true })).toBeVisible();
+ await expect(page.locator('#identity-navbar-status')).toBeFocused();
+ await expect(main.locator('#identity-protected-status')).not.toBeFocused();
+ } finally {
+ await context.close();
+ }
+});
+test.describe('actual shared inline capability component', () => {
+ let fixtureServer: Awaited<ReturnType<typeof createStaticHarness>>,
+ directory: string;
+ test.beforeAll(async () => {
+ test.setTimeout(120_000);
+ directory = await mkdtemp(path.join(tmpdir(), 'hcp056-gates-'));
+ const capsule = fileURLToPath(new URL('../../../', import.meta.url)),
+ checkout = path.join(directory, 'checkout');
+ execFileSync('git', [
+ 'clone',
+ '--quiet',
+ '--no-hardlinks',
+ capsule,
+ checkout
+ ]);
+ for (const name of [
+ 'src/lib/components/CapabilityGate.svelte',
+ 'src/lib/runtime/view-context.ts',
+ 'src/lib/components/AppShell.svelte',
+ 'src/lib/components/AccountGate.svelte',
+ 'src/routes/+layout.svelte',
+ 'tests/e2e/harness/capability-gate.svelte'
+ ])
+ await cp(
+ path.join(capsule, 'web', name),
+ path.join(checkout, 'web', name)
+ );
+ const fixture = await readFile(
+ path.join(capsule, 'web/tests/e2e/harness/capability-gate.svelte'),
+ 'utf8'
+ );
+ await writeFile(
+ path.join(checkout, 'web/src/routes/+page.svelte'),
+ fixture.replaceAll('../../../src/lib/', '../lib/')
+ );
+ const store = execFileSync('corepack', ['pnpm', 'store', 'path'], {
+ cwd: path.join(capsule, 'web')
+ })
+ .toString()
+ .trim();
+ execFileSync(
+ 'corepack',
+ [
+ 'pnpm',
+ 'install',
+ '--offline',
+ '--frozen-lockfile',
+ '--store-dir',
+ path.dirname(store)
+ ],
+ { cwd: path.join(checkout, 'web'), timeout: 90_000, stdio: 'pipe' }
+ );
+ const audit = execFileSync(process.execPath, ['tools/check-source.mjs'], {
+ cwd: path.join(checkout, 'web')
+ }).toString();
+ execFileSync(process.execPath, ['tools/build-info.mjs'], {
+ cwd: path.join(checkout, 'web')
+ });
+ execFileSync(process.execPath, ['node_modules/vite/bin/vite.js', 'build'], {
+ cwd: path.join(checkout, 'web'),
+ timeout: 90_000,
+ stdio: 'pipe'
+ });
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP056_ACTUAL_SHARED_GATE',
+ sourceSha256: createHash('sha256').update(fixture).digest('hex'),
+ audit,
+ qualification:
+ 'controlled Chromium and actual shared view/component/SDK; no named extension/inbox/private publication qualification'
+ })
+ );
+ fixtureServer = await createStaticHarness({
+ buildRoot: path.join(checkout, 'web/build')
+ });
+ });
+ test.afterAll(async () => {
+ await fixtureServer?.close();
+ if (directory) await rm(directory, { recursive: true, force: true });
+ });
+ test('Connect never repeats an earlier inline Send, and self-copy requires a separate reviewed action', async ({
+ browser
+ }) => {
+ const context = await browser.newContext();
+ await provider(context);
+ try {
+ const page = await context.newPage();
+ await page.goto(fixtureServer.url);
+ const main = page.getByRole('main');
+ await main.getByRole('button', { name: 'Explicit test Send' }).click();
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await expect(
+ main.getByText('Earlier sends: 1', { exact: true })
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.hcp056Counts)).toEqual({
+ keys: 1,
+ signs: 0,
+ encrypts: 0,
+ decrypts: 0
+ });
+ await expect(
+ main.locator('[role="status"][tabindex="-1"]')
+ ).toBeFocused();
+ await main
+ .getByRole('button', { name: 'Check messaging support', exact: true })
+ .click();
+ await expect(
+ main.getByText('Messaging support checked.', { exact: true })
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.hcp056Counts)).toEqual({
+ keys: 3,
+ signs: 0,
+ encrypts: 1,
+ decrypts: 1
+ });
+ await expect(
+ main.getByText('Earlier sends: 1', { exact: true })
+ ).toBeVisible();
+ } finally {
+ await context.close();
+ }
+ });
+ test('reviewed probe waits for actual completion before returning focus', async ({
+ browser
+ }) => {
+ const context = await browser.newContext();
+ await provider(context);
+ try {
+ const page = await context.newPage();
+ await page.goto(fixtureServer.url);
+ const main = page.getByRole('main');
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await page.evaluate(() => {
+ window.nostr = {
+ getPublicKey: () =>
+ Promise.resolve(
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'
+ ),
+ signEvent: () => Promise.reject(new Error('Unexpected signature')),
+ nip44: {
+ encrypt: (_key: string, text: string) =>
+ new Promise<string>((resolve) => {
+ window.hcp056Release = () => resolve(text);
+ }),
+ decrypt: (_key: string, text: string) => Promise.resolve(text)
+ }
+ };
+ });
+ await main
+ .getByRole('button', { name: 'Check messaging support', exact: true })
+ .click();
+ await expect(
+ main.getByText('Waiting for extension approval.', { exact: true })
+ ).toBeVisible();
+ const retained = main.getByRole('button', { name: 'Explicit test Send' });
+ await retained.focus();
+ await expect(retained).toBeFocused();
+ await expect(main.locator('#identity-inline-status')).not.toBeFocused();
+ await page.evaluate(() => window.hcp056Release?.());
+ await expect(
+ main.getByText('Messaging support checked.', { exact: true })
+ ).toBeVisible();
+ await expect(main.locator('#identity-inline-status')).toBeFocused();
+ } finally {
+ await context.close();
+ }
+ });
+ test('connected signing-only identity has an explicit unsupported message-encryption state', async ({
+ browser
+ }) => {
+ const context = await browser.newContext();
+ await provider(context, 'unsupported');
+ try {
+ const page = await context.newPage();
+ await page.goto(fixtureServer.url);
+ const main = page.getByRole('main');
+ await main
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ .click();
+ await main
+ .getByRole('button', { name: 'Check messaging support', exact: true })
+ .click();
+ await expect(
+ main.getByText(
+ 'This extension does not support the required message encryption.',
+ { exact: true }
+ )
+ ).toBeVisible();
+ await expect(main.locator('textarea, form')).toHaveCount(0);
+ expect(
+ await page.evaluate(
+ () => window.hcp056Counts.encrypts + window.hcp056Counts.signs
+ )
+ ).toBe(0);
+ } finally {
+ await context.close();
+ }
+ });
+});
diff --git a/web/tests/e2e/harness/capability-gate.svelte b/web/tests/e2e/harness/capability-gate.svelte
@@ -0,0 +1,54 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import CapabilityGate from '../../../src/lib/components/CapabilityGate.svelte';
+ import {
+ createIdentityViewContext,
+ identityViewSnapshot,
+ mountIdentityView,
+ subscribeIdentityView,
+ connectIdentityView,
+ disconnectIdentityView,
+ probeIdentityViewMessaging,
+ closeIdentityView
+ } from '../../../src/lib/runtime/view-context.ts';
+ const context = createIdentityViewContext();
+ let view = $state(identityViewSnapshot(context));
+ let sends = $state(0);
+ onMount(() => {
+ const off = subscribeIdentityView(context, (next) => {
+ view = next;
+ });
+ mountIdentityView(context);
+ return () => {
+ off();
+ closeIdentityView(context);
+ };
+ });
+ function connect() {
+ return connectIdentityView(context);
+ }
+ function probe() {
+ return probeIdentityViewMessaging(context, 'reviewed_self_copy');
+ }
+</script>
+
+<h1>HC_TEST_ONLY_INLINE_GATE</h1>
+<p role="status">Earlier sends: {sends}</p>
+<button
+ type="button"
+ class="button button--secondary"
+ onclick={() => {
+ sends++;
+ }}>Explicit test Send</button
+>
+<CapabilityGate
+ identity={view.identity}
+ required="messaging"
+ onconnect={view.mounted ? connect : undefined}
+ onprobe={view.mounted ? probe : undefined}
+/>
+<button
+ type="button"
+ class="button button--secondary"
+ onclick={() => disconnectIdentityView(context)}>Disconnect fixture</button
+>
diff --git a/web/tests/e2e/primitives.spec.ts b/web/tests/e2e/primitives.spec.ts
@@ -201,26 +201,32 @@ for (const width of [320, 1024]) {
page.getByRole('button', { name: 'Fixture command', exact: true })
).toBeFocused();
await page.keyboard.press('Enter');
- await expect(page.getByRole('status')).toHaveText('Commands: 1');
+ await expect(page.getByRole('main').getByRole('status')).toHaveText(
+ 'Commands: 1'
+ );
await expect(
page.getByRole('button', { name: 'Disabled command' })
).toBeDisabled();
await page
.getByRole('button', { name: 'Disabled command' })
.evaluate((element) => (element as HTMLButtonElement).click());
- await expect(page.getByRole('status')).toHaveText('Commands: 1');
+ await expect(page.getByRole('main').getByRole('status')).toHaveText(
+ 'Commands: 1'
+ );
await page
.getByRole('button', { name: 'Disabled command' })
.evaluate((element) =>
element.dispatchEvent(new MouseEvent('click', { bubbles: true }))
);
- await expect(page.getByRole('status')).toHaveText('Commands: 1');
+ await expect(page.getByRole('main').getByRole('status')).toHaveText(
+ 'Commands: 1'
+ );
await page.keyboard.press('Tab');
await expect(
page.getByRole('link', { name: 'Fixture navigation' })
).toBeFocused();
await page.keyboard.press('Tab');
- await expect(page.locator('summary')).toBeFocused();
+ await expect(page.getByRole('main').locator('summary')).toBeFocused();
await page.keyboard.press('Enter');
await expect(page.locator('details')).toHaveAttribute('open', '');
await page.keyboard.press('Space');
@@ -244,7 +250,9 @@ for (const width of [320, 1024]) {
await page
.getByRole('button', { name: 'Discard draft', exact: true })
.click();
- await expect(page.getByRole('status')).toHaveText('Commands: 2');
+ await expect(page.getByRole('main').getByRole('status')).toHaveText(
+ 'Commands: 2'
+ );
await expect(
page.getByRole('button', { name: 'Discard draft', exact: true })
).toBeDisabled();
diff --git a/web/tests/e2e/product-details.spec.ts b/web/tests/e2e/product-details.spec.ts
@@ -314,7 +314,9 @@ test('real product reload renders verified facts, safe guest contact, explicit c
})
).toHaveAttribute('href', 'https://contact.example.org/collect');
await page.getByRole('button', { name: 'Copy link', exact: true }).click();
- await expect(page.getByRole('status')).toHaveText('Link copied.');
+ await expect(page.getByRole('main').getByRole('status')).toHaveText(
+ 'Link copied.'
+ );
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(
href('active')
);
diff --git a/web/tests/e2e/route-inventory.spec.ts b/web/tests/e2e/route-inventory.spec.ts
@@ -157,6 +157,16 @@ for (const routeCase of cases) {
).toBeDisabled();
await expect(page.locator('main button')).toHaveCount(2);
await expect(
+ page
+ .locator('main')
+ .getByRole('button', { name: 'Connect extension', exact: true })
+ ).toBeEnabled();
+ await expect(
+ page
+ .locator('main')
+ .getByRole('link', { name: 'Connection help' })
+ ).toHaveAttribute('href', '/about#help');
+ await expect(
page.locator('main input, main textarea, main form')
).toHaveCount(0);
expect(await page.locator('main').textContent()).not.toContain(
diff --git a/web/tests/e2e/search-form.spec.ts b/web/tests/e2e/search-form.spec.ts
@@ -202,7 +202,7 @@ for (const width of [320, 1024]) {
name: 'What are you looking for?'
});
const search = page.getByRole('button', { name: 'Search', exact: true });
- const status = page.getByRole('status');
+ const status = page.getByRole('main').getByRole('status');
await expect(query).toHaveCount(1);
await expect(query).toHaveAttribute('rows', '2');
await expect(search).toBeEnabled();
diff --git a/web/tests/e2e/shell.spec.ts b/web/tests/e2e/shell.spec.ts
@@ -34,6 +34,8 @@ test.beforeAll(async () => {
]);
for (const relative of [
'web/src/lib/components/AppShell.svelte',
+ 'web/src/lib/components/CapabilityGate.svelte',
+ 'web/src/lib/runtime/view-context.ts',
'web/src/app.css',
'web/src/routes/+layout.svelte',
'web/tests/unit/components/shell.test.ts',
@@ -194,7 +196,7 @@ async function measure(page: import('@playwright/test').Page, stage: string) {
scroll: globalThis.document.documentElement.scrollWidth,
navigation: Array.from(
globalThis.document.querySelectorAll(
- 'nav[aria-label="Primary"] > .cluster > *'
+ 'nav[aria-label="Primary"] > .cluster > :is(a,span,button,details)'
)
).map((element) => {
const rect = element.getBoundingClientRect();
@@ -273,7 +275,7 @@ for (const width of [320, 1024]) {
exact: true
});
await expect(primary).toHaveText(
- 'HarvestCircle Search List food Connect extension'
+ 'HarvestCircle Search List food Messages Use your Nostr extension to choose your identity. Connect extension'
);
await expect(
page.getByRole('link', { name: 'Search', exact: true })
@@ -284,6 +286,7 @@ for (const width of [320, 1024]) {
'HarvestCircle',
'Search',
'List food',
+ 'Messages',
'Connect extension'
]);
const guestConnect = page.getByRole('button', {
@@ -292,7 +295,9 @@ for (const width of [320, 1024]) {
await guestConnect.focus();
await expect(guestConnect).toBeFocused();
await page.keyboard.press('Enter');
- await expect(page.getByRole('status')).toHaveText('Commands: 1');
+ await expect(
+ page.getByRole('status').filter({ hasText: /^Commands:/ })
+ ).toHaveText('Commands: 1');
await expect(primary).toContainText(
'HarvestCircle Search Messages Selling Identity'
);
@@ -336,7 +341,9 @@ for (const width of [320, 1024]) {
await disconnect.evaluate((element) =>
element.dispatchEvent(new MouseEvent('click', { bubbles: true }))
);
- await expect(page.getByRole('status')).toHaveText('Commands: 1');
+ await expect(
+ page.getByRole('status').filter({ hasText: /^Commands:/ })
+ ).toHaveText('Commands: 1');
await measure(page, 'connected-open-long-key');
await expect(page.locator('header')).not.toContainText(/unread/i);
await page
@@ -345,7 +352,9 @@ for (const width of [320, 1024]) {
await disconnect.focus();
await expect(disconnect).toBeFocused();
await page.keyboard.press('Enter');
- await expect(page.getByRole('status')).toHaveText('Commands: 2');
+ await expect(
+ page.getByRole('status').filter({ hasText: /^Commands:/ })
+ ).toHaveText('Commands: 2');
await page
.getByRole('button', { name: 'Toggle command availability' })
.click();
@@ -357,7 +366,9 @@ for (const width of [320, 1024]) {
await connect.evaluate((element) =>
element.dispatchEvent(new MouseEvent('click', { bubbles: true }))
);
- await expect(page.getByRole('status')).toHaveText('Commands: 2');
+ await expect(
+ page.getByRole('status').filter({ hasText: /^Commands:/ })
+ ).toHaveText('Commands: 2');
expect(external).toEqual([]);
} finally {
await context.close();
@@ -398,13 +409,17 @@ test('controlled shell callbacks become available only after actual hydration',
).toBeVisible();
await expect.poll(() => delayedScripts).toBeGreaterThan(0);
await expect(connect).toBeDisabled();
- await expect(page.getByRole('status')).toHaveText('Commands: 0');
+ await expect(
+ page.getByRole('status').filter({ hasText: /^Commands:/ })
+ ).toHaveText('Commands: 0');
releaseScripts();
await expect(connect).toBeEnabled();
await connect.focus();
await expect(connect).toBeFocused();
await page.keyboard.press('Enter');
- await expect(page.getByRole('status')).toHaveText('Commands: 1');
+ await expect(
+ page.getByRole('status').filter({ hasText: /^Commands:/ })
+ ).toHaveText('Commands: 1');
const identity = page.locator('summary');
await identity.focus();
await expect(identity).toBeFocused();
diff --git a/web/tests/integration/loopback.test.ts b/web/tests/integration/loopback.test.ts
@@ -65,7 +65,10 @@ await test('navigation fallback serves actual separate output and preserves miss
assert.ok(html);
assert.match(html, /<title>HarvestCircle<\/title>/);
assert.match(html, /name="robots" content="noindex"/);
- assert.match(html, /Account access is unavailable during development/);
+ assert.match(
+ html,
+ /Private views and editing are unavailable during development/
+ );
assert.doesNotMatch(html, /<form|<input|<textarea/);
}
assert.notEqual(search, fallback);
diff --git a/web/tests/integration/view-context.test.ts b/web/tests/integration/view-context.test.ts
@@ -0,0 +1,17 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ createIdentityViewContext,
+ mountIdentityView,
+ connectIdentityView,
+ closeIdentityView,
+ identityViewSnapshot
+} from '../../src/lib/runtime/view-context.ts';
+await test('root identity view construction and explicit SSR calls acquire no browser identity', async () => {
+ assert.equal(typeof window, 'undefined');
+ const c = createIdentityViewContext();
+ assert.equal(mountIdentityView(c), false);
+ assert.equal((await connectIdentityView(c)).mounted, false);
+ closeIdentityView(c);
+ assert.equal(identityViewSnapshot(c).identity.state, 'guest');
+});
diff --git a/web/tests/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import {
cp,
@@ -28,6 +29,25 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
// Exact HCP043 product shell bytes, immutable compatibility evidence only.
const historicalProduct =
'<svelte:head><title>Food — HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>Food</h1>\n <p class="notice">Food details are unavailable during development.</p>\n</div>\n';
+ // Frozen public-only HCP055 producers, source6023db01169aa82cb6fe68ca94e1a73750247e72.
+ // Compatibility evidence only; runtime tests never require ancestor Git history.
+ const historicalPublicOnly = {
+ 'src/routes/+layout.svelte': {
+ source:
+ "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';\n import { onMount, setContext, type Snippet } from 'svelte';\n import {\n createPublicRuntimeContext,\n mountPublicRuntime,\n closePublicRuntime,\n PUBLIC_RUNTIME_CONTEXT\n } from '../lib/runtime/public-runtime.ts';\n import { page } from '$app/state';\n import AppShell from '../lib/components/AppShell.svelte';\n\n const publicContext = createPublicRuntimeContext();\n setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);\n onMount(() => {\n mountPublicRuntime(publicContext);\n return () => closePublicRuntime(publicContext);\n });\n\n let { children }: { children: Snippet } = $props();\n</script>\n\n<AppShell\n currentPath={page.url.pathname}\n availableRoutes={[\n '/search',\n '/sell',\n '/selling',\n '/messages',\n '/about',\n '/privacy'\n ]}\n>\n {@render children()}\n</AppShell>\n",
+ sha256: '956da247f23ad9695c3c6f8bff42801aceaa5b84a2606a1a8a5263fd0c637dc7'
+ },
+ 'src/lib/components/AppShell.svelte': {
+ source:
+ "<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import { internalHref } from '../navigation-url';\n import Button from './primitives/Button.svelte';\n import Disclosure from './primitives/Disclosure.svelte';\n\n type ShellRoute =\n '/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy';\n type Identity =\n | { kind: 'guest'; onconnect?: () => void }\n | { kind: 'connected'; publicKey: string; ondisconnect?: () => void };\n let {\n children,\n currentPath = '/',\n availableRoutes = [],\n identity = { kind: 'guest' }\n }: {\n children: Snippet;\n currentPath?: string;\n availableRoutes?: readonly ShellRoute[];\n identity?: Identity;\n } = $props();\n\n const unavailable = $derived(\n !availableRoutes.includes('/search') ||\n !availableRoutes.includes('/about') ||\n !availableRoutes.includes('/privacy') ||\n (identity.kind === 'guest'\n ? !availableRoutes.includes('/sell') || !identity.onconnect\n : !availableRoutes.includes('/selling') ||\n !availableRoutes.includes('/messages') ||\n !identity.ondisconnect)\n );\n\n function available(href: string) {\n return (\n href === '/' ||\n availableRoutes.some((route) => route === href.split('#')[0])\n );\n }\n</script>\n\n{#snippet navigation(label: string, href: string, brand = false)}\n {#if available(href) && internalHref(href)}\n <a\n href={internalHref(href)}\n class=\"shell-link\"\n class:brand\n aria-current={currentPath === href ? 'page' : undefined}>{label}</a\n >\n {:else}\n <span\n class=\"shell-link text-muted\"\n aria-disabled=\"true\"\n aria-describedby=\"shell-availability\"\n aria-current={currentPath === href ? 'page' : undefined}>{label}</span\n >\n {/if}\n{/snippet}\n\n<a href={internalHref('#main-content')} class=\"skip-link visually-hidden\"\n >Skip to main content</a\n>\n<header class=\"navbar\">\n <nav aria-label=\"Primary\" class=\"page navbar__inner\">\n <div class=\"cluster\">\n {@render navigation('HarvestCircle', '/', true)}\n {@render navigation('Search', '/search')}\n {#if identity.kind === 'guest'}\n {@render navigation('List food', '/sell')}\n <Button\n label=\"Connect extension\"\n disabled={!identity.onconnect}\n onclick={identity.onconnect}\n />\n {:else}\n {@render navigation('Messages', '/messages')}\n {@render navigation('Selling', '/selling')}\n <Disclosure summary=\"Identity\">\n <p class=\"key\">{identity.publicKey}</p>\n <Button\n label=\"Disconnect\"\n disabled={!identity.ondisconnect}\n onclick={identity.ondisconnect}\n />\n </Disclosure>\n {/if}\n </div>\n {#if unavailable}\n <p id=\"shell-availability\" class=\"text-small text-muted\">\n Unavailable during development: disabled navigation and actions.\n </p>\n {/if}\n </nav>\n</header>\n<main id=\"main-content\" tabindex=\"-1\" class=\"page\">\n {@render children()}\n</main>\n<footer class=\"footer\">\n <nav aria-label=\"Footer\" class=\"page cluster\">\n {@render navigation('About', '/about')}\n {@render navigation('Privacy', '/privacy')}\n {@render navigation('Help / report', '/about#help')}\n </nav>\n</footer>\n",
+ sha256: 'c8afbb1ee62a16ad47558829518b347fe3e2a312e490312ded812a8b538d828f'
+ },
+ 'src/lib/components/AccountGate.svelte': {
+ source:
+ '<script lang="ts">\n import Button from \'./primitives/Button.svelte\';\n</script>\n\n<svelte:head>\n <title>HarvestCircle</title>\n <meta name="robots" content="noindex" />\n</svelte:head>\n<div class="page page--reading stack">\n <h1>Connect or unlock</h1>\n <p>Connect an extension and unlock your account to continue.</p>\n <p class="notice">Account access is unavailable during development.</p>\n <div class="cluster">\n <Button label="Connect extension" disabled />\n <Button label="Unlock" disabled />\n </div>\n</div>\n',
+ sha256: 'd5f90fb4b9af50037ed19dde626552e82df67017a39408bdbdeff1e712c10fbd'
+ }
+ };
const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output '));
t.after(() => rm(base, { recursive: true, force: true }));
/** @param {string} root @param {string[]} args */
@@ -147,6 +167,46 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
);
}
);
+ await check(
+ 'public-only owned lifecycle remains independently compilable',
+ async (t) => {
+ const f = await fixture(t);
+ for (const [name, value] of Object.entries(historicalPublicOnly)) {
+ assert.equal(
+ createHash('sha256').update(value.source).digest('hex'),
+ value.sha256
+ );
+ await writeFile(path.join(f.web, name), value.source);
+ }
+ await cp(
+ path.join(base, 'web/node_modules'),
+ path.join(f.web, 'node_modules'),
+ { recursive: true, verbatimSymlinks: true }
+ );
+ await refresh(f);
+ execFileSync(
+ process.execPath,
+ [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'],
+ { cwd: f.web, stdio: 'pipe', timeout: 60000 }
+ );
+ const manifest = JSON.parse(
+ await readFile(
+ path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'),
+ 'utf8'
+ )
+ );
+ assert.ok(
+ !Object.values(manifest).some(
+ (record) => record.name === 'view-context'
+ )
+ );
+ assert.ok(
+ Object.values(manifest).some((record) => record.name === 'budgets')
+ );
+ assert.equal((await f.audit()).length, 47);
+ },
+ 60000
+ );
/** @param {{root: string, web: string}} f */
async function refresh(f) {
git(f.root, 'add', '--', 'web/src');
@@ -182,6 +242,10 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
'predecessor SDK graph remains qualified with the historical search form fixture',
async (t) => {
const f = await fixture(t);
+ // This historical graph predates identity activation. Restore its
+ // immutable public-only producers before compiling the former routes.
+ for (const [name, value] of Object.entries(historicalPublicOnly))
+ await writeFile(path.join(f.web, name), value.source);
// Immutable former route bytes are a labelled verification variant only.
const historical =
"<script lang=\"ts\">\n import { page } from '$app/state';\n import SearchForm from '../../lib/components/SearchForm.svelte';\n import {\n normalizePublicQuery,\n queryErrorMessage,\n readPublicQuery\n } from '../../lib/catalog/query-input';\n import type { PublicQuery } from '../../lib/catalog/query-input';\n import { searchHref } from '../../lib/routes';\n import { internalHref } from '../../lib/navigation-url';\n let query = $state<PublicQuery>(normalizePublicQuery(''));\n let error = $state<string | undefined>();\n $effect(() => {\n query = readPublicQuery(page.url);\n error = undefined;\n });\n function search(input: string) {\n const next = normalizePublicQuery(input);\n if (!next.ok) {\n error = queryErrorMessage(next.error);\n return;\n }\n error = undefined;\n const target = internalHref(searchHref(next.text));\n if (target === undefined) {\n error = queryErrorMessage('invalid_query');\n return;\n }\n globalThis.location.assign(target);\n }\n</script>\n\n<svelte:head><title>Search food \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Search food</h1>\n <SearchForm\n onsubmit={search}\n initialValue={query.ok ? query.text : ''}\n error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))}\n />\n <p class=\"notice\">Search data is unavailable during development.</p>\n</div>\n";
@@ -227,6 +291,8 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
'HCP043 search graph remains qualified with the exact historical product shell',
async (t) => {
const f = await fixture(t);
+ for (const [name, value] of Object.entries(historicalPublicOnly))
+ await writeFile(path.join(f.web, name), value.source);
await writeFile(
path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'),
historicalProduct
@@ -397,6 +463,130 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
await refresh(f);
await assert.rejects(f.audit, /compiler|runtime/i);
});
+ for (const mutation of [
+ 'missing-mount',
+ 'missing-subscription',
+ 'missing-unsubscribe',
+ 'missing-close',
+ 'wrong-context',
+ 'duplicate-context',
+ 'extra-mount',
+ 'aliased-mount',
+ 'shadowed',
+ 'missing-context',
+ 'rebound-context'
+ ])
+ await check('owned identity lifecycle rejects ' + mutation, async (t) => {
+ const f = await fixture(t);
+ const file = path.join(f.web, 'src/routes/+layout.svelte');
+ const original = await readFile(file, 'utf8');
+ let layout = original;
+ assert.ok(layout.includes('mountIdentityView(identityContext);'));
+ if (mutation === 'missing-mount')
+ layout = layout.replace('mountIdentityView(identityContext);', '');
+ if (mutation === 'missing-subscription')
+ layout = layout.replace(
+ 'subscribeIdentityView(identityContext,',
+ 'subscribeIdentityView({},'
+ );
+ if (mutation === 'missing-unsubscribe')
+ layout = layout.replace(' off();', '');
+ if (mutation === 'missing-close')
+ layout = layout.replace('closeIdentityView(identityContext);', '');
+ if (mutation === 'wrong-context')
+ layout = layout.replace(
+ 'closeIdentityView(identityContext)',
+ 'closeIdentityView({})'
+ );
+ if (mutation === 'duplicate-context')
+ layout = layout.replace(
+ 'const identityContext = createIdentityViewContext();',
+ 'const identityContext = createIdentityViewContext(); const other = createIdentityViewContext();'
+ );
+ if (mutation === 'extra-mount')
+ layout = layout.replace(
+ 'mountIdentityView(identityContext);',
+ 'mountIdentityView(identityContext); mountIdentityView(identityContext);'
+ );
+ if (mutation === 'aliased-mount')
+ layout = layout
+ .replace(
+ ' mountIdentityView,',
+ ' mountIdentityView as otherMount,'
+ )
+ .replace(
+ 'mountIdentityView(identityContext);',
+ 'otherMount(identityContext);'
+ );
+ if (mutation === 'shadowed')
+ layout = layout.replace(
+ 'const off = subscribeIdentityView',
+ 'const identityContext = {}; const off = subscribeIdentityView'
+ );
+ if (mutation === 'missing-context')
+ layout = layout.replace(
+ 'setContext(IDENTITY_VIEW_CONTEXT, identityContext);',
+ ''
+ );
+ if (mutation === 'rebound-context')
+ layout = layout.replace(
+ 'const identityContext =',
+ 'let identityContext ='
+ );
+ assert.notEqual(layout, original);
+ await writeFile(file, layout);
+ await refresh(f);
+ await assert.rejects(f.audit, /Invalid owned root runtime activation/);
+ });
+ for (const mutation of [
+ 'missing-view',
+ 'missing-heads',
+ 'extra-view-field',
+ 'wrong-view-imports',
+ 'wrong-heads-imports',
+ 'missing-root-edge',
+ 'missing-gate-edge'
+ ])
+ await check(
+ 'owned identity compiler topology rejects ' + mutation,
+ async (t) => {
+ const f = await fixture(t),
+ file = path.join(
+ f.web,
+ '.svelte-kit/output/client/.vite/manifest.json'
+ );
+ const manifest = JSON.parse(await readFile(file, 'utf8'));
+ /** @param {string} name */
+ const find = (name) => {
+ const entry = Object.entries(manifest).find(
+ ([, record]) => record.name === name
+ );
+ assert.ok(entry, 'Missing observed compiler role: ' + name);
+ return entry;
+ };
+ const [identityKey, identity] = find('view-context'),
+ [headsKey, heads] = find('heads');
+ if (mutation === 'missing-view') delete manifest[identityKey];
+ if (mutation === 'missing-heads') delete manifest[headsKey];
+ if (mutation === 'extra-view-field') identity.dynamicImports = [];
+ if (mutation === 'wrong-view-imports') identity.imports = [];
+ if (mutation === 'wrong-heads-imports') heads.imports = [];
+ if (
+ mutation === 'missing-root-edge' ||
+ mutation === 'missing-gate-edge'
+ ) {
+ const [, consumer] = find(
+ mutation === 'missing-root-edge' ? 'nodes/0' : 'AccountGate'
+ );
+ consumer.imports = consumer.imports.filter(
+ /** @param {string} dependency */
+ (dependency) => dependency !== identityKey
+ );
+ }
+ await writeFile(file, JSON.stringify(manifest));
+ await assert.rejects(f.audit, /compiler/i);
+ }
+ );
for (const name of [
'runtime/public-runtime.ts',
'nostr/request-scope.ts',
@@ -515,11 +705,16 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
)
);
const entries = Object.entries(manifest).filter(
- ([, record]) => record.name === 'budgets'
+ ([, record]) => record.name === 'Button'
);
assert.equal(entries.length, 1);
const [key, budget] = entries[0];
- assert.deepEqual(Object.keys(budget).sort(), ['file', 'name']);
+ assert.deepEqual(Object.keys(budget).sort(), ['file', 'imports', 'name']);
+ const client = Object.entries(manifest).find(
+ ([, record]) => record.name === 'client'
+ );
+ assert.ok(client);
+ assert.deepEqual(budget.imports, [client[0]]);
for (const name of ['Disclosure', 'nodes/9', 'routes'])
assert.ok(
Object.values(manifest)
@@ -600,7 +795,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
publisher.imports = publisher.imports.filter(
(/** @type {string} */ key) =>
key !==
- find(mutation === 'publisher-budget' ? 'budgets' : 'Disclosure')[0]
+ find(mutation === 'publisher-budget' ? 'Button' : 'Disclosure')[0]
);
else {
const target = mutation === 'search-publisher' ? 'nodes/9' : 'nodes/7';
@@ -608,7 +803,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
mutation === 'product-shared'
? 'Disclosure'
: mutation === 'product-budget'
- ? 'budgets'
+ ? 'Button'
: 'publishers';
find(target)[1].imports = find(target)[1].imports.filter(
(/** @type {string} */ key) => key !== find(dependency)[0]
@@ -670,7 +865,7 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
return entry;
};
const [sharedKey, shared] = find('Disclosure');
- const [budgetKey] = find('budgets');
+ const [budgetKey] = find('Button');
if (mutation === 'missing-shared') delete manifest[sharedKey];
else if (mutation === 'missing-navigation')
delete manifest[find('navigation')[0]];
@@ -722,14 +917,14 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => {
);
const manifest = JSON.parse(await readFile(file, 'utf8'));
const entry = Object.entries(manifest).find(
- ([, record]) => record.name === 'budgets'
+ ([, record]) => record.name === 'Button'
);
assert.ok(entry);
const [key, budget] = entry;
if (mutation === 'unknown-name') budget.name = 'unapproved-budgets';
if (mutation === 'duplicate') manifest['_HCduplicate.js'] = { ...budget };
if (mutation === 'missing-module') delete manifest[key];
- if (mutation === 'extra-field') budget.imports = [];
+ if (mutation === 'extra-field') budget.dynamicImports = [];
if (
mutation === 'missing-root-edge' ||
mutation === 'missing-routes-edge'
diff --git a/web/tests/unit/components/CapabilityGateHarness.svelte b/web/tests/unit/components/CapabilityGateHarness.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import CapabilityGate from '../../../src/lib/components/CapabilityGate.svelte';
+ import type { IdentitySnapshot } from '../../../src/lib/runtime/identity-session.ts';
+ let {
+ identity = { state: 'guest', reason: 'disconnected' },
+ required = 'connection',
+ onconnect,
+ onprobe
+ }: {
+ identity?: IdentitySnapshot;
+ required?: 'connection' | 'messaging';
+ onconnect?: () => void;
+ onprobe?: () => void;
+ } = $props();
+</script>
+
+<CapabilityGate {identity} {required} {onconnect} {onprobe} />
diff --git a/web/tests/unit/components/capability-gate.test.ts b/web/tests/unit/components/capability-gate.test.ts
@@ -0,0 +1,70 @@
+import { render } from 'svelte/server';
+import { describe, it, expect } from 'vitest';
+import Harness from './CapabilityGateHarness.svelte';
+const owner =
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
+describe('shared safe connection capability presentation', () => {
+ it('guest exposes connection help and browse, with no private form or SSR effect', () => {
+ const forbidden = () => {
+ throw new Error('SSR effect');
+ };
+ const html = render(Harness, { props: { onconnect: forbidden } }).body;
+ expect(html).toContain('Connect extension');
+ expect(html).toContain('Keep browsing');
+ expect(html).toContain('private key stays in the extension');
+ expect(html).not.toMatch(/<form|<textarea|nsec|password|HC_PRIVATE/);
+ });
+ it('pending approval is visibly distinct and cannot schedule another connection', () => {
+ const html = render(Harness, {
+ props: {
+ identity: { state: 'pending', action: 'connect' },
+ onconnect: () => {}
+ }
+ }).body;
+ expect(html).toContain('Waiting for extension');
+ expect(html).toMatch(/<button[^>]*disabled/);
+ });
+ it('missing or denied extension gets finite safe help, never provider diagnostics', () => {
+ for (const reason of ['missing', 'refused'] as const) {
+ const html = render(Harness, {
+ props: { identity: { state: 'guest', reason } }
+ }).body;
+ expect(html).toContain('Connection help');
+ expect(html).not.toMatch(/stack|nsec|<input/);
+ }
+ });
+ it('signing capability is not messaging readiness or inbox authority', () => {
+ const html = render(Harness, {
+ props: {
+ required: 'messaging',
+ identity: {
+ state: 'signing_only',
+ publicKey: owner,
+ messaging: 'unsupported'
+ },
+ onprobe: () => {}
+ }
+ }).body;
+ expect(html).toContain('message encryption');
+ expect(html).not.toMatch(
+ /Send message|Publish listing|inbox ready|<textarea/
+ );
+ });
+ it('connected presentation never executes an earlier operation or exposes a private body', () => {
+ const html = render(Harness, {
+ props: {
+ identity: {
+ state: 'messaging_capable',
+ publicKey: owner,
+ messaging: 'capable'
+ },
+ required: 'messaging',
+ onconnect: () => {
+ throw new Error('Send');
+ }
+ }
+ }).body;
+ expect(html).toContain('Messaging support checked');
+ expect(html).not.toMatch(/HC_PRIVATE|Send message|<form/);
+ });
+});
diff --git a/web/tests/unit/route-inventory.test.ts b/web/tests/unit/route-inventory.test.ts
@@ -70,7 +70,7 @@ describe('thin protected route SSR', () => {
expect(output.head).toMatch(/name="robots" content="noindex"/);
expect(output.body).toContain('Connect or unlock');
expect(output.body).toContain(
- 'Account access is unavailable during development.'
+ 'Private views and editing are unavailable during development.'
);
expect(output.body).toMatch(
/<button[^>]*disabled[^>]*>Connect extension/
diff --git a/web/tests/unit/view-context.test.ts b/web/tests/unit/view-context.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect } from 'vitest';
+import {
+ createIdentityViewContext,
+ identityViewSnapshot,
+ mountIdentityView,
+ connectIdentityView,
+ probeIdentityViewMessaging,
+ disconnectIdentityView,
+ closeIdentityView,
+ subscribeIdentityView,
+ identityViewMatchesOwner,
+ type IdentityViewContext
+} from '../../src/lib/runtime/view-context.ts';
+describe('genuine per-client identity view context', () => {
+ it('constructs separate inert disconnected contexts without browser acquisition', () => {
+ const a = createIdentityViewContext(),
+ b = createIdentityViewContext();
+ expect(a).not.toBe(b);
+ expect(Object.keys(a)).toEqual([]);
+ expect(identityViewSnapshot(a)).toEqual({
+ mounted: false,
+ identity: { state: 'guest', reason: 'disconnected' }
+ });
+ disconnectIdentityView(a);
+ expect(identityViewSnapshot(b).identity).toEqual({
+ state: 'guest',
+ reason: 'disconnected'
+ });
+ });
+ it('rejects forged tokens and does not infer authorization from a public key', async () => {
+ const fake = {} as IdentityViewContext;
+ expect(mountIdentityView(fake)).toBe(false);
+ expect(identityViewMatchesOwner(fake, 'a'.repeat(64))).toBe(false);
+ expect((await connectIdentityView(fake)).identity.state).toBe('guest');
+ });
+ it('SSR cannot mount, connect or invoke a reviewed messaging action', async () => {
+ const c = createIdentityViewContext();
+ expect(mountIdentityView(c)).toBe(false);
+ expect((await connectIdentityView(c)).identity.state).toBe('guest');
+ expect(
+ (await probeIdentityViewMessaging(c, 'reviewed_self_copy')).identity.state
+ ).toBe('guest');
+ });
+ it('snapshot mutation and one subscriber cannot change another context', () => {
+ const a = createIdentityViewContext(),
+ b = createIdentityViewContext();
+ const events: string[] = [];
+ const off = subscribeIdentityView(a, (state) =>
+ events.push(state.identity.state)
+ );
+ const copy = identityViewSnapshot(a);
+ (copy as { mounted: boolean }).mounted = true;
+ expect(identityViewSnapshot(a).mounted).toBe(false);
+ closeIdentityView(a);
+ off();
+ expect(events.length).toBeGreaterThan(0);
+ expect(identityViewSnapshot(b).mounted).toBe(false);
+ expect(identityViewMatchesOwner(b, 'a'.repeat(64))).toBe(false);
+ });
+});
diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs
@@ -209,6 +209,24 @@ async function hasOwnedPublicRuntime(web) {
],
['svelte', ['onMount', 'setContext']]
]);
+ const identityPath = '../lib/runtime/view-context.ts';
+ const hasIdentity = imports.some(
+ (node) =>
+ ts.isStringLiteral(node.moduleSpecifier) &&
+ node.moduleSpecifier.text === identityPath
+ );
+ if (hasIdentity)
+ required.set(identityPath, [
+ 'createIdentityViewContext',
+ 'IDENTITY_VIEW_CONTEXT',
+ 'identityViewSnapshot',
+ 'mountIdentityView',
+ 'subscribeIdentityView',
+ 'connectIdentityView',
+ 'disconnectIdentityView',
+ 'closeIdentityView',
+ 'invalidateIdentityView'
+ ]);
const allowedImports = new Set();
for (const [module, names] of required) {
const declarations = imports.filter(
@@ -236,7 +254,11 @@ async function hasOwnedPublicRuntime(web) {
)
fail();
}
- if (module === runtimePath && elements.length !== names.length) fail();
+ if (
+ (module === runtimePath || module === identityPath) &&
+ elements.length !== names.length
+ )
+ fail();
allowedImports.add(declarations[0]);
}
const printer = ts.createPrinter({ removeComments: true });
@@ -265,10 +287,86 @@ async function hasOwnedPublicRuntime(web) {
lifecycle.some((node, i) => print(node, source) !== shapes[i])
)
fail();
+ // HCP056 adds one separately owned identity lifecycle. The canonical public
+ // activation above remains mandatory, unchanged and independently ordered.
+ if (hasIdentity) {
+ const identityExpected = ts.createSourceFile(
+ 'identity-expected.ts',
+ `
+ const identityContext = createIdentityViewContext();
+ setContext(IDENTITY_VIEW_CONTEXT, identityContext);
+ let identityView = $state(identityViewSnapshot(identityContext));
+ $effect(() => {
+ if (page.url.pathname) invalidateIdentityView(identityContext);
+ });
+ function connect() {
+ return connectIdentityView(identityContext);
+ }
+ function disconnect() {
+ disconnectIdentityView(identityContext);
+ }
+ const shellIdentity = $derived(
+ identityView.identity.state === 'guest' ||
+ identityView.identity.state === 'pending'
+ ? {
+ kind: 'guest' as const,
+ onconnect: identityView.mounted ? connect : undefined
+ }
+ : {
+ kind: 'connected' as const,
+ publicKey: identityView.identity.publicKey,
+ ondisconnect: disconnect
+ }
+ );
+
+ onMount(() => {
+ const off = subscribeIdentityView(identityContext, (next) => {
+ identityView = next;
+ });
+ mountIdentityView(identityContext);
+ return () => {
+ off();
+ closeIdentityView(identityContext);
+ };
+ });
+`,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TS
+ );
+ const identityShapes = identityExpected.statements.map((node) =>
+ print(node, identityExpected)
+ );
+ const identityLifecycle = source.statements.filter((node) =>
+ identityShapes.includes(print(node, source))
+ );
+ if (
+ identityLifecycle.length !== identityShapes.length ||
+ identityLifecycle.some(
+ (node, i) => print(node, source) !== identityShapes[i]
+ )
+ )
+ fail();
+ lifecycle.push(...identityLifecycle);
+ publicText(await readOwned(web, 'src/lib/runtime/view-context.ts'));
+ publicText(await readOwned(web, 'src/lib/runtime/identity-session.ts'));
+ }
// Reject duplicate, shadowed, reassigned, or extra uses of these bindings in
// any other statement, including nested closures. Canonical callbacks have
// no parameters and therefore cannot hide a second context binding.
- const bindings = new Set(['publicContext', ...[...required.values()].flat()]);
+ const bindings = new Set([
+ 'publicContext',
+ ...[...required.values()].flat(),
+ ...(hasIdentity
+ ? [
+ 'identityContext',
+ 'identityView',
+ 'connect',
+ 'disconnect',
+ 'shellIdentity'
+ ]
+ : [])
+ ]);
for (const statement of source.statements) {
if (allowedImports.has(statement) || lifecycle.includes(statement))
continue;
@@ -295,7 +393,7 @@ async function hasOwnedPublicRuntime(web) {
'config/deployment-relays.ts'
])
publicText(await readOwned(web, 'src/lib/' + name));
- return true;
+ return hasIdentity ? 'public_identity' : 'public';
}
/** @param {string} web */
async function productPresentationAdmission(web) {
@@ -488,7 +586,7 @@ export async function auditOutput(webDirectory) {
'AccountGate',
'references',
'legacy',
- 'rolldown-runtime',
+ ...(hasPublicRuntime === 'public_identity' ? [] : ['rolldown-runtime']),
'shared-errors'
])
names.add(name);
@@ -498,7 +596,9 @@ export async function auditOutput(webDirectory) {
'public-key',
...(hasSearchPresentation ? ['Disclosure', 'navigation'] : ['dist']),
'negentropy',
- 'budgets'
+ ...(hasPublicRuntime === 'public_identity'
+ ? ['view-context', 'heads']
+ : ['budgets'])
])
names.add(name);
if (hasProductPresentation) names.add('publishers');
@@ -595,12 +695,27 @@ export async function auditOutput(webDirectory) {
}
const dist = requiredRecord(hasSearchPresentation ? 'Disclosure' : 'dist');
const root = requiredRecord('nodes/0')[1];
- const [budgetKey, budget] = requiredRecord('budgets');
+ const [budgetKey, budget] = requiredRecord(
+ hasPublicRuntime === 'public_identity' ? 'Button' : 'budgets'
+ );
if (
!/^_[A-Za-z0-9_-]+\.js$/.test(budgetKey) ||
- Object.keys(budget).some((field) => !['file', 'name'].includes(field))
+ Object.keys(budget).some(
+ (field) =>
+ !(
+ hasPublicRuntime === 'public_identity'
+ ? ['file', 'name', 'imports']
+ : ['file', 'name']
+ ).includes(field)
+ )
)
throw new Error('Invalid owned budgets compiler identity');
+ if (hasPublicRuntime === 'public_identity')
+ equal(
+ budget.imports,
+ [requiredRecord('client')[0]],
+ 'Invalid owned budgets compiler dependencies'
+ );
for (const consumer of hasSearchPresentation
? [
'Disclosure',
@@ -623,7 +738,13 @@ export async function auditOutput(webDirectory) {
sdk.dynamicImports !== undefined
)
throw new Error('Invalid owned SDK compiler identity');
- equal(sdk.imports, [dist[0]], 'Invalid owned SDK compiler dependency');
+ equal(
+ sdk.imports,
+ hasPublicRuntime === 'public_identity'
+ ? [requiredRecord('heads')[0], dist[0]]
+ : [dist[0]],
+ 'Invalid owned SDK compiler dependency'
+ );
equal(
hasSearchPresentation ? dist[1].dynamicImports : root.dynamicImports,
[sdkNegentropy],
@@ -650,13 +771,16 @@ export async function auditOutput(webDirectory) {
throw new Error('Invalid owned navigation compiler dynamic imports');
equal(
dist[1].imports,
- [
- 'rolldown-runtime',
- 'preload-helper',
- 'public-key',
- 'client',
- 'budgets'
- ].map((name) => requiredRecord(name)[0]),
+ (hasPublicRuntime === 'public_identity'
+ ? ['public-key', 'preload-helper', 'heads', 'client', 'Button']
+ : [
+ 'rolldown-runtime',
+ 'preload-helper',
+ 'public-key',
+ 'client',
+ 'budgets'
+ ]
+ ).map((name) => requiredRecord(name)[0]),
'Invalid owned shared compiler dependencies'
);
for (const [key, record] of [dist, navigation]) {
@@ -670,6 +794,34 @@ export async function auditOutput(webDirectory) {
throw new Error('Invalid owned search compiler chunk');
}
}
+ if (hasPublicRuntime === 'public_identity') {
+ /** @type {[string, string[]][]} */
+ const identityDependencies = [
+ ['view-context', ['public-key', 'heads', 'client', 'Button']],
+ ['heads', ['public-key', 'Button']]
+ ];
+ for (const [name, dependencies] of identityDependencies) {
+ const [key, record] = requiredRecord(name);
+ if (
+ !/^_[A-Za-z0-9_-]+\.js$/.test(key) ||
+ Object.keys(record).some(
+ (field) => !['file', 'name', 'imports'].includes(field)
+ )
+ )
+ throw new Error('Invalid owned identity compiler chunk');
+ equal(
+ record.imports,
+ dependencies.map((dependency) => requiredRecord(dependency)[0]),
+ 'Invalid owned identity compiler dependencies'
+ );
+ }
+ const [identityKey] = requiredRecord('view-context');
+ if (
+ !root.imports?.includes(identityKey) ||
+ !requiredRecord('AccountGate')[1].imports?.includes(identityKey)
+ )
+ throw new Error('Invalid owned identity compiler consumer');
+ }
for (const name of hasSearchPresentation
? ['public-key']
: ['dist', 'public-key']) {
@@ -701,38 +853,68 @@ export async function auditOutput(webDirectory) {
throw new Error('Invalid owned product compiler identity');
equal(
publisher.imports,
- ['public-key', 'Disclosure', 'budgets'].map((name) => entry(name)[0]),
+ (hasPublicRuntime === 'public_identity'
+ ? ['public-key', 'heads', 'Disclosure', 'Button']
+ : ['public-key', 'Disclosure', 'budgets']
+ ).map((name) => entry(name)[0]),
'Invalid owned product publisher compiler dependencies'
);
equal(
entry('nodes/7')[1].imports,
- [
- 'rolldown-runtime',
- 'references',
- 'Disclosure',
- 'client',
- 'budgets',
- 'client.svelte',
- 'state',
- 'Button',
- 'publishers'
- ].map((name) => entry(name)[0]),
+ (hasPublicRuntime === 'public_identity'
+ ? [
+ 'public-key',
+ 'references',
+ 'heads',
+ 'Disclosure',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'state',
+ 'publishers'
+ ]
+ : [
+ 'rolldown-runtime',
+ 'references',
+ 'Disclosure',
+ 'client',
+ 'budgets',
+ 'client.svelte',
+ 'state',
+ 'Button',
+ 'publishers'
+ ]
+ ).map((name) => entry(name)[0]),
'Invalid owned product compiler dependencies'
);
equal(
entry('nodes/9')[1].imports,
- [
- 'references',
- 'Disclosure',
- 'client',
- 'budgets',
- 'client.svelte',
- 'navigation',
- 'state',
- 'Button',
- 'routes',
- 'publishers'
- ].map((name) => entry(name)[0]),
+ (hasPublicRuntime === 'public_identity'
+ ? [
+ 'references',
+ 'heads',
+ 'Disclosure',
+ 'client',
+ 'Button',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'routes',
+ 'publishers'
+ ]
+ : [
+ 'references',
+ 'Disclosure',
+ 'client',
+ 'budgets',
+ 'client.svelte',
+ 'navigation',
+ 'state',
+ 'Button',
+ 'routes',
+ 'publishers'
+ ]
+ ).map((name) => entry(name)[0]),
'Invalid owned search product compiler dependencies'
);
if (