Add NIP-5A aggregate hash and version snapshots to nsite deploys

Publishes the aggregate `x` tag on every nsite manifest (kind 15128 /
35128). Adds an opt-in per-project `publishSnapshotOnDeploy` flag in
`.nsite/config.json` that also publishes a kind 5128 manifest snapshot
so older site versions remain reachable. Snapshots are deduplicated:
if a snapshot with the same aggregate hash already exists for the site,
the publish is skipped.

The flag is exposed as a "Publish version history" checkbox in the
nsite deploy form and is persisted to `.nsite/config.json` immediately
on toggle so the choice survives without a deploy.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This commit is contained in:
hzrd149andClaude Opus 4.7 committed 2026-05-15 13:17:48 -05:00
1 parent 0da339c214
commit d1e71184e6
8 files changed
+619 -96

No files matched your search

+51 -1
View File
@@ -108,6 +108,7 @@ interface NsiteFormData {
siteTitle: string;
siteDescription: string;
dTag: string;
publishSnapshotOnDeploy: boolean;
}
interface NetlifyFormData {
@@ -177,6 +178,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
siteTitle: cfg.title ?? '',
siteDescription: cfg.description ?? '',
dTag: (cfg.id != null && cfg.id !== '') ? cfg.id : '',
publishSnapshotOnDeploy: cfg.publishSnapshotOnDeploy ?? false,
});
setNsiteShowFullForm(false);
} else {
@@ -194,6 +196,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
siteTitle: '',
siteDescription: '',
dTag: '',
publishSnapshotOnDeploy: false,
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
@@ -280,6 +283,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
siteDescription: nsiteForm.siteDescription || undefined,
sourceUrl,
siteIdentifier: nsiteForm.dTag || undefined,
publishSnapshotOnDeploy: nsiteForm.publishSnapshotOnDeploy,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider;
@@ -405,6 +409,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
description: nsiteForm.siteDescription || undefined,
fallback: '/index.html',
gatewayHostnames: [nsiteProvider.gateway],
publishSnapshotOnDeploy: nsiteForm.publishSnapshotOnDeploy,
};
await writeNsiteVfsConfig(fs, projectPath, newNsiteVfsConfig);
// Update in-memory state so summary view reflects new values immediately
@@ -517,7 +522,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '', publishSnapshotOnDeploy: false });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
@@ -549,6 +554,44 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setNsiteForm(prev => ({ ...prev, siteDescription }));
}, []);
const handleNsitePublishSnapshotOnDeployChange = useCallback(async (publishSnapshotOnDeploy: boolean) => {
setNsiteForm(prev => ({ ...prev, publishSnapshotOnDeploy }));
// Persist immediately so the choice survives closing the dialog without
// deploying. We assemble the full config from the currently-selected
// provider + form values so the file is valid even on first toggle
// (before any deploy has run).
if (!projectId) return;
if (selectedProvider?.type !== 'nsite') return;
const projectPath = `${projectsPath}/${projectId}`;
const cfg: NsiteVfsConfig = {
relays: selectedProvider.relayUrls,
servers: selectedProvider.blossomServers,
id: nsiteForm.dTag || undefined,
title: nsiteForm.siteTitle || undefined,
description: nsiteForm.siteDescription || undefined,
fallback: '/index.html',
gatewayHostnames: [selectedProvider.gateway],
publishSnapshotOnDeploy,
};
try {
await writeNsiteVfsConfig(fs, projectPath, cfg);
setNsiteVfsConfig(cfg);
} catch (err) {
console.warn('Failed to persist publishSnapshotOnDeploy to .nsite/config.json:', err);
}
}, [
projectId,
projectsPath,
selectedProvider,
fs,
nsiteForm.dTag,
nsiteForm.siteTitle,
nsiteForm.siteDescription,
]);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
setNetlifyForm({ siteId, siteName });
}, []);
@@ -621,6 +664,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<span className="text-muted-foreground">Blossom servers</span>
<span className="font-medium">{serverCount} configured</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Version history</span>
<span className="font-medium">{nsiteVfsConfig.publishSnapshotOnDeploy ? 'Enabled' : 'Disabled'}</span>
</div>
</div>
<button
type="button"
@@ -640,6 +687,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
// .nsite/config.json wins; .git/shakespeare/deploy.json is the legacy fallback
const savedSiteTitle = nsiteVfsConfig?.title ?? legacy?.siteTitle;
const savedSiteDescription = nsiteVfsConfig?.description ?? legacy?.siteDescription;
const savedPublishSnapshotOnDeploy = nsiteVfsConfig?.publishSnapshotOnDeploy ?? false;
return (
<div className="space-y-3">
@@ -649,8 +697,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
savedNsec={legacy?.nsec}
savedSiteTitle={savedSiteTitle}
savedSiteDescription={savedSiteDescription}
savedPublishSnapshotOnDeploy={savedPublishSnapshotOnDeploy}
onSiteTitleChange={handleNsiteSiteTitleChange}
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
onPublishSnapshotOnDeployChange={handleNsitePublishSnapshotOnDeployChange}
/>
{nsiteVfsConfig && (
<button
+144 -88
View File
@@ -1,105 +1,161 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useState, useEffect, useRef, useCallback } from "react";
import { AlertCircle } from "lucide-react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Checkbox } from "@/components/ui/checkbox";
interface NsiteDeployFormProps {
/** Human-readable project name — used to default the title */
projectName: string;
/** Persisted values from a previous deployment */
savedSiteTitle?: string;
savedSiteDescription?: string;
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
savedNsec?: string;
onSiteTitleChange: (title: string) => void;
onSiteDescriptionChange: (description: string) => void;
/** Human-readable project name — used to default the title */
projectName: string;
/** Persisted values from a previous deployment */
savedSiteTitle?: string;
savedSiteDescription?: string;
savedPublishSnapshotOnDeploy?: boolean;
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
savedNsec?: string;
onSiteTitleChange: (title: string) => void;
onSiteDescriptionChange: (description: string) => void;
onPublishSnapshotOnDeployChange: (enabled: boolean) => void;
}
export function NsiteDeployForm({
projectName,
savedSiteTitle,
savedSiteDescription,
savedNsec,
onSiteTitleChange,
onSiteDescriptionChange,
projectName,
savedSiteTitle,
savedSiteDescription,
savedPublishSnapshotOnDeploy,
savedNsec,
onSiteTitleChange,
onSiteDescriptionChange,
onPublishSnapshotOnDeployChange,
}: NsiteDeployFormProps) {
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
const [siteDescription, setSiteDescription] = useState(
savedSiteDescription ?? "",
);
const [publishSnapshotOnDeploy, setPublishSnapshotOnDeploy] = useState(
savedPublishSnapshotOnDeploy ?? false,
);
// On mount: sync all saved values to parent and set defaults.
// The component is keyed by selectedProviderId in DeploySteps, so this always
// runs with fresh props — no initialized guard needed.
const initializedRef = useRef(false);
const stableSyncToParent = useCallback(() => {
if (initializedRef.current) return;
initializedRef.current = true;
// On mount: sync all saved values to parent and set defaults.
// The component is keyed by selectedProviderId in DeploySteps, so this always
// runs with fresh props — no initialized guard needed.
const initializedRef = useRef(false);
const stableSyncToParent = useCallback(() => {
if (initializedRef.current) return;
initializedRef.current = true;
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
const initialTitle = savedSiteTitle ?? projectName;
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
onSiteTitleChange(initialTitle);
}, [savedSiteDescription, savedSiteTitle, siteTitle, projectName, onSiteDescriptionChange, onSiteTitleChange]);
const initialTitle = savedSiteTitle ?? projectName;
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
onSiteTitleChange(initialTitle);
useEffect(() => {
stableSyncToParent();
}, [stableSyncToParent]);
onPublishSnapshotOnDeployChange(savedPublishSnapshotOnDeploy ?? false);
}, [
savedSiteDescription,
savedSiteTitle,
savedPublishSnapshotOnDeploy,
siteTitle,
projectName,
onSiteDescriptionChange,
onSiteTitleChange,
onPublishSnapshotOnDeployChange,
]);
const handleSiteTitleChange = (value: string) => {
setSiteTitle(value);
onSiteTitleChange(value);
};
useEffect(() => {
stableSyncToParent();
}, [stableSyncToParent]);
const handleSiteDescriptionChange = (value: string) => {
setSiteDescription(value);
onSiteDescriptionChange(value);
};
const handleSiteTitleChange = (value: string) => {
setSiteTitle(value);
onSiteTitleChange(value);
};
return (
<div className="space-y-4">
const handleSiteDescriptionChange = (value: string) => {
setSiteDescription(value);
onSiteDescriptionChange(value);
};
{/* Migration notice */}
{savedNsec && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Site identity is changing.</strong> This project was previously deployed with a
dedicated private key. Going forward, it will deploy under your Nostr identity. The old
site will remain at its original address until overwritten.
</AlertDescription>
</Alert>
)}
const handlePublishSnapshotOnDeployChange = (value: boolean) => {
setPublishSnapshotOnDeploy(value);
onPublishSnapshotOnDeployChange(value);
};
{/* Site title */}
<div className="space-y-2">
<Label htmlFor="nsite-title">Site Title</Label>
<Input
id="nsite-title"
value={siteTitle}
onChange={(e) => handleSiteTitleChange(e.target.value)}
placeholder="My Nostr Site"
/>
<p className="text-xs text-muted-foreground">
Shown by nsite gateways and directories. Included as a title tag in the manifest.
</p>
</div>
return (
<div className="space-y-4">
{/* Migration notice */}
{savedNsec && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Site identity is changing.</strong> This project was
previously deployed with a dedicated private key. Going forward, it
will deploy under your Nostr identity. The old site will remain at
its original address until overwritten.
</AlertDescription>
</Alert>
)}
{/* Site description */}
<div className="space-y-2">
<Label htmlFor="nsite-description">Description <span className="text-muted-foreground font-normal">(optional)</span></Label>
<Textarea
id="nsite-description"
value={siteDescription}
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
placeholder="A short description of this site…"
rows={3}
/>
<p className="text-xs text-muted-foreground">
Included as a description tag in the manifest.
</p>
</div>
</div>
);
{/* Site title */}
<div className="space-y-2">
<Label htmlFor="nsite-title">Site Title</Label>
<Input
id="nsite-title"
value={siteTitle}
onChange={(e) => handleSiteTitleChange(e.target.value)}
placeholder="My Nostr Site"
/>
<p className="text-xs text-muted-foreground">
Shown by nsite gateways and directories. Included as a title tag in
the manifest.
</p>
</div>
{/* Site description */}
<div className="space-y-2">
<Label htmlFor="nsite-description">
Description{" "}
<span className="text-muted-foreground font-normal">(optional)</span>
</Label>
<Textarea
id="nsite-description"
value={siteDescription}
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
placeholder="A short description of this site…"
rows={3}
/>
<p className="text-xs text-muted-foreground">
Included as a description tag in the manifest.
</p>
</div>
{/* Version history toggle */}
<div className="space-y-2">
<div className="flex items-start space-x-2">
<Checkbox
id="nsite-publish-snapshot-on-deploy"
checked={publishSnapshotOnDeploy}
onCheckedChange={(checked) =>
handlePublishSnapshotOnDeployChange(checked === true)
}
className="mt-0.5"
/>
<div className="space-y-1 leading-none">
<Label
htmlFor="nsite-publish-snapshot-on-deploy"
className="text-sm font-medium cursor-pointer"
>
Publish version history
</Label>
<p className="text-xs text-muted-foreground">
Publishes a version each time the app is deployed. This allows
users to use older versions of the app.
</p>
</div>
</div>
</div>
</div>
);
}
+78 -7
View File
@@ -4,12 +4,16 @@ import { nip19 } from 'nostr-tools';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
import { buildNsiteUrl } from '../utils/nsite';
import {
buildNsiteParentRef,
buildNsiteSnapshotTags,
computeNsiteAggregateHash,
NSITE_NAMED_SITE_KIND,
NSITE_ROOT_SITE_KIND,
} from '../utils/nsiteAggregateHash';
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
const NSITE_ROOT_SITE_KIND = 15128;
/** nsite v2 named-site kind (addressable by pubkey+kind+d) */
const NSITE_NAMED_SITE_KIND = 35128;
/** nsite v2 manifest snapshot kind (regular event capturing a point-in-time manifest) */
const NSITE_SNAPSHOT_KIND = 5128;
/** BUD-02 Blossom authorization event kind */
const BLOSSOM_AUTH_KIND = 24242;
@@ -268,6 +272,7 @@ export class NsiteAdapter implements DeployAdapter {
private siteDescription?: string;
private sourceUrl?: string;
private siteIdentifier?: string;
private publishSnapshotOnDeploy: boolean;
constructor(config: NsiteDeployConfig) {
this.fs = config.fs;
@@ -280,6 +285,7 @@ export class NsiteAdapter implements DeployAdapter {
this.siteDescription = config.siteDescription;
this.sourceUrl = config.sourceUrl;
this.siteIdentifier = config.siteIdentifier;
this.publishSnapshotOnDeploy = config.publishSnapshotOnDeploy ?? false;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
@@ -364,11 +370,18 @@ export class NsiteAdapter implements DeployAdapter {
// SPA fallback: map /404.html to the same blob as /index.html so that
// React Router (and other SPAs) work correctly — the nsite host server
// serves /404.html when a path is not found, acting as a client-side router fallback.
// The SPA fallback IS a published `path` tag, so it is included in the
// aggregate hash below.
const indexFile = files.find(f => f.path === '/index.html');
if (indexFile && !files.some(f => f.path === '/404.html')) {
pathTags.push(['path', '/404.html', indexFile.sha256]);
}
// NIP-5A aggregate hash — deterministic digest of the manifest's path tags.
// Always attached so the published manifest is indexable and discoverable,
// and so the snapshot event (when emitted) can carry exactly the same value.
const aggregateHash = await computeNsiteAggregateHash(pathTags);
const serverTags: string[][] = serverBases.map(url => ['server', url]);
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
@@ -379,7 +392,7 @@ export class NsiteAdapter implements DeployAdapter {
tags.push(['d', this.siteIdentifier]);
}
tags.push(...pathTags, ...serverTags, ...relayTags);
tags.push(...pathTags, ['x', aggregateHash, 'aggregate'], ...serverTags, ...relayTags);
if (this.siteTitle) {
tags.push(['title', this.siteTitle]);
@@ -393,10 +406,12 @@ export class NsiteAdapter implements DeployAdapter {
tags.push(['source', this.sourceUrl]);
}
const createdAt = Math.floor(Date.now() / 1000);
const manifestEvent = await this.signer.signEvent({
kind: manifestKind,
content: '',
created_at: Math.floor(Date.now() / 1000),
created_at: createdAt,
tags,
});
@@ -405,6 +420,58 @@ export class NsiteAdapter implements DeployAdapter {
// no separate kind 10002 or kind 10063 events are published.
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
// ── Step 6: Optionally publish a manifest snapshot (NIP-5A kind 5128) ────
// When enabled, this captures the current manifest as an immutable, id-addressable
// event so historical versions remain reachable. Off by default — the user
// opts in per-project via .nsite/config.json (`publishSnapshotOnDeploy: true`).
//
// Deduplication: skip the snapshot publish if a kind-5128 event with the
// same aggregate hash for the same site already exists on the relays. A new
// snapshot of a byte-for-byte equivalent version would just be relay noise.
//
// Inferred from signer.signEvent so the full NostrEvent shape is preserved
// when this is later passed to relayClient.event().
let snapshotEvent: Awaited<ReturnType<typeof this.signer.signEvent>> | undefined;
let snapshotSkippedReason: 'unchanged' | undefined;
if (this.publishSnapshotOnDeploy) {
const parentRef = buildNsiteParentRef(pubkey, this.siteIdentifier);
const existingSnapshots = await relayClient.query(
[{
kinds: [NSITE_SNAPSHOT_KIND],
authors: [pubkey],
'#a': [parentRef],
'#x': [aggregateHash],
limit: 1,
}],
{ signal: AbortSignal.timeout(5_000) },
).catch(() => []);
if (existingSnapshots.length > 0) {
snapshotSkippedReason = 'unchanged';
} else {
const snapshotTags = buildNsiteSnapshotTags({
pubkey,
siteIdentifier: this.siteIdentifier,
pathTags,
aggregateHash,
serverTags,
title: this.siteTitle,
description: this.siteDescription,
sourceUrl: this.sourceUrl,
});
snapshotEvent = await this.signer.signEvent({
kind: NSITE_SNAPSHOT_KIND,
content: '',
created_at: createdAt,
tags: snapshotTags,
});
await relayClient.event(snapshotEvent, { signal: AbortSignal.timeout(10_000) });
}
}
// Build the canonical deployed URL (always the long-form base36 or npub URL)
const siteUrl = buildNsiteUrl({
pubkeyHex: pubkey,
@@ -433,6 +500,10 @@ export class NsiteAdapter implements DeployAdapter {
manifestKind,
vanityUrl,
canonicalUrl: siteUrl,
aggregateHash,
snapshotId: snapshotEvent?.id,
snapshotCreatedAt: snapshotEvent?.created_at,
snapshotSkipped: snapshotSkippedReason,
},
};
}
+5
View File
@@ -66,6 +66,11 @@ export interface NsiteDeployConfig {
* When absent → publishes kind 15128 (root site), URL = {npub}.{gateway}
*/
siteIdentifier?: string;
/**
* When true, also publish a NIP-5A kind 5128 manifest snapshot event alongside
* the main manifest so historical versions remain addressable by event id.
*/
publishSnapshotOnDeploy?: boolean;
}
export interface CloudflareDeployConfig {
+80
View File
@@ -0,0 +1,80 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { MockFS } from '@/test/MockFS';
import { readNsiteVfsConfig, writeNsiteVfsConfig } from './nsiteConfig';
const PROJECT = '/projects/demo';
describe('nsiteConfig.publishSnapshotOnDeploy', () => {
let fs: MockFS;
beforeEach(() => {
fs = new MockFS();
});
it('round-trips publishSnapshotOnDeploy=true', async () => {
await writeNsiteVfsConfig(fs, PROJECT, {
relays: ['wss://relay.example.com'],
servers: ['https://blossom.example.com'],
publishSnapshotOnDeploy: true,
});
const read = await readNsiteVfsConfig(fs, PROJECT);
expect(read?.publishSnapshotOnDeploy).toBe(true);
});
it('round-trips publishSnapshotOnDeploy=false', async () => {
await writeNsiteVfsConfig(fs, PROJECT, {
relays: ['wss://relay.example.com'],
servers: ['https://blossom.example.com'],
publishSnapshotOnDeploy: false,
});
const read = await readNsiteVfsConfig(fs, PROJECT);
expect(read?.publishSnapshotOnDeploy).toBe(false);
});
it('accepts a config without publishSnapshotOnDeploy (backward compatibility)', async () => {
await fs.writeFile(
`${PROJECT}/.nsite/config.json`,
JSON.stringify({
relays: ['wss://relay.example.com'],
servers: ['https://blossom.example.com'],
}),
);
const read = await readNsiteVfsConfig(fs, PROJECT);
expect(read).not.toBeNull();
expect(read?.publishSnapshotOnDeploy).toBeUndefined();
});
it('rejects non-boolean publishSnapshotOnDeploy values', async () => {
await fs.writeFile(
`${PROJECT}/.nsite/config.json`,
JSON.stringify({
relays: ['wss://relay.example.com'],
servers: ['https://blossom.example.com'],
publishSnapshotOnDeploy: 'yes',
}),
);
// Invalid types are coerced to null per readNsiteVfsConfig's error handling.
const read = await readNsiteVfsConfig(fs, PROJECT);
expect(read).toBeNull();
});
it('preserves unknown keys when merging on write', async () => {
await fs.writeFile(
`${PROJECT}/.nsite/config.json`,
JSON.stringify({
relays: ['wss://relay.example.com'],
servers: ['https://blossom.example.com'],
customField: 'kept-from-nsyte-cli',
}),
);
await writeNsiteVfsConfig(fs, PROJECT, {
relays: ['wss://relay.example.com'],
servers: ['https://blossom.example.com'],
publishSnapshotOnDeploy: true,
});
const raw = await fs.readFile(`${PROJECT}/.nsite/config.json`, 'utf8');
const parsed = JSON.parse(raw as string);
expect(parsed.customField).toBe('kept-from-nsyte-cli');
expect(parsed.publishSnapshotOnDeploy).toBe(true);
});
});
+7
View File
@@ -40,6 +40,12 @@ export interface NsiteVfsConfig {
fallback?: string;
/** Gateway hostnames that serve this nsite */
gatewayHostnames?: string[];
/**
* When true, every deploy also publishes a kind 5128 manifest snapshot event
* so older versions of the site remain reachable by event id.
* Absent/false → snapshots are not published.
*/
publishSnapshotOnDeploy?: boolean;
}
const nsiteVfsConfigSchema = z
@@ -51,6 +57,7 @@ const nsiteVfsConfigSchema = z
description: z.string().optional(),
fallback: z.string().optional(),
gatewayHostnames: z.array(z.string()).optional(),
publishSnapshotOnDeploy: z.boolean().optional(),
})
.passthrough(); // preserve unknown keys in existing files
+168
View File
@@ -0,0 +1,168 @@
import { describe, it, expect } from 'vitest';
import {
buildNsiteSnapshotTags,
computeNsiteAggregateHash,
NSITE_NAMED_SITE_KIND,
NSITE_ROOT_SITE_KIND,
} from './nsiteAggregateHash';
describe('computeNsiteAggregateHash', () => {
// Two-file example from the NIP-5A spec:
// 186ea5fd14e88fd1ac49351759e7ab906fa94892002b60bf7f5a428f28ca1c99 /index.html
// fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321 /favicon.ico
//
// Sorted lines (lex ascending) then sha256 → c2ff582b...9638
// Verified out-of-band with:
// printf '<line1>\n<line2>\n' | sha256sum
const EXPECTED_TWO_FILE_DIGEST =
'c2ff582b672a4c689c5e1753528f03dd31b95ec1fdcc3d82d25e7d91e8769638';
const indexTag = [
'path',
'/index.html',
'186ea5fd14e88fd1ac49351759e7ab906fa94892002b60bf7f5a428f28ca1c99',
];
const faviconTag = [
'path',
'/favicon.ico',
'fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321',
];
it('matches the known digest for the NIP-5A spec example', async () => {
const digest = await computeNsiteAggregateHash([indexTag, faviconTag]);
expect(digest).toBe(EXPECTED_TWO_FILE_DIGEST);
});
it('is independent of path-tag order', async () => {
const forwards = await computeNsiteAggregateHash([indexTag, faviconTag]);
const reverse = await computeNsiteAggregateHash([faviconTag, indexTag]);
expect(forwards).toBe(reverse);
});
it('ignores non-path tags', async () => {
const withNoise = await computeNsiteAggregateHash([
['d', 'blog'],
indexTag,
['title', 'My Site'],
faviconTag,
['server', 'https://example.com'],
]);
expect(withNoise).toBe(EXPECTED_TWO_FILE_DIGEST);
});
it('returns lowercase hex of length 64', async () => {
const digest = await computeNsiteAggregateHash([indexTag]);
expect(digest).toMatch(/^[0-9a-f]{64}$/);
});
it('produces a different digest when a path or hash changes', async () => {
const baseline = await computeNsiteAggregateHash([indexTag, faviconTag]);
const renamed = await computeNsiteAggregateHash([
indexTag,
['path', '/icon.ico', faviconTag[2]],
]);
expect(renamed).not.toBe(baseline);
});
it('returns the sha256 of empty input when no path tags are present', async () => {
// sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
const digest = await computeNsiteAggregateHash([['title', 'noop']]);
expect(digest).toBe(
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
);
});
});
describe('buildNsiteSnapshotTags', () => {
const pubkey = '266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5';
const aggregateHash =
'c2ff582b672a4c689c5e1753528f03dd31b95ec1fdcc3d82d25e7d91e8769638';
const pathTags = [
['path', '/index.html', '186ea5fd14e88fd1ac49351759e7ab906fa94892002b60bf7f5a428f28ca1c99'],
['path', '/favicon.ico', 'fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321'],
];
it('builds a named-site `a` tag of the form 35128:<pubkey>:<dTag>', () => {
const tags = buildNsiteSnapshotTags({
pubkey,
siteIdentifier: 'blog',
pathTags,
aggregateHash,
});
const aTags = tags.filter(t => t[0] === 'a');
expect(aTags).toHaveLength(1);
expect(aTags[0]).toEqual(['a', `${NSITE_NAMED_SITE_KIND}:${pubkey}:blog`]);
});
it('builds a root-site `a` tag of the form 15128:<pubkey>: with empty d-identifier', () => {
const tags = buildNsiteSnapshotTags({
pubkey,
pathTags,
aggregateHash,
});
const aTags = tags.filter(t => t[0] === 'a');
expect(aTags).toHaveLength(1);
expect(aTags[0]).toEqual(['a', `${NSITE_ROOT_SITE_KIND}:${pubkey}:`]);
});
it('includes exactly one aggregate `x` tag matching the input hash', () => {
const tags = buildNsiteSnapshotTags({
pubkey,
siteIdentifier: 'blog',
pathTags,
aggregateHash,
});
const xTags = tags.filter(t => t[0] === 'x');
expect(xTags).toHaveLength(1);
expect(xTags[0]).toEqual(['x', aggregateHash, 'aggregate']);
});
it('copies every path tag from the source manifest', () => {
const tags = buildNsiteSnapshotTags({
pubkey,
siteIdentifier: 'blog',
pathTags,
aggregateHash,
});
const copiedPathTags = tags.filter(t => t[0] === 'path');
expect(copiedPathTags).toEqual(pathTags);
});
it('does not mutate the input path tags', () => {
const original = pathTags.map(t => [...t]);
buildNsiteSnapshotTags({
pubkey,
siteIdentifier: 'blog',
pathTags,
aggregateHash,
}).push(['mutated']);
expect(pathTags).toEqual(original);
});
it('includes optional title, description, source, and server tags when provided', () => {
const tags = buildNsiteSnapshotTags({
pubkey,
siteIdentifier: 'blog',
pathTags,
aggregateHash,
serverTags: [['server', 'https://blossom.example.com']],
title: 'My Blog',
description: 'Hosted on Nostr',
sourceUrl: 'https://github.com/example/blog',
});
expect(tags).toContainEqual(['title', 'My Blog']);
expect(tags).toContainEqual(['description', 'Hosted on Nostr']);
expect(tags).toContainEqual(['source', 'https://github.com/example/blog']);
expect(tags).toContainEqual(['server', 'https://blossom.example.com']);
});
it('omits an `A` tag (spec: non-copied snapshots SHOULD omit it)', () => {
const tags = buildNsiteSnapshotTags({
pubkey,
siteIdentifier: 'blog',
pathTags,
aggregateHash,
});
expect(tags.some(t => t[0] === 'A')).toBe(false);
});
});
+86
View File
@@ -0,0 +1,86 @@
/** NIP-5A nsite manifest kinds. */
export const NSITE_ROOT_SITE_KIND = 15128;
export const NSITE_NAMED_SITE_KIND = 35128;
/**
* NIP-5A aggregate hash for nsite manifests.
*
* The aggregate hash is a deterministic digest of a manifest's `path` tags. It
* identifies a specific site version and is shared by equivalent manifests
* published by different pubkeys.
*
* Algorithm (from NIP-5A):
* 1. For every `path` tag, produce a line `<sha256hash> <absolute-path>\n`.
* 2. Sort the lines in ascending lexicographic order.
* 3. Concatenate the sorted lines as UTF-8 bytes.
* 4. SHA-256 the bytes and return the digest as lowercase hex.
*
* The algorithm uses only `path` tags and is independent of tag order.
*/
export async function computeNsiteAggregateHash(
pathTags: ReadonlyArray<readonly string[]>,
): Promise<string> {
const lines: string[] = [];
for (const tag of pathTags) {
if (tag[0] !== 'path') continue;
const path = tag[1];
const hash = tag[2];
if (typeof path !== 'string' || typeof hash !== 'string') continue;
lines.push(`${hash} ${path}\n`);
}
lines.sort();
const bytes = new TextEncoder().encode(lines.join(''));
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* Build the addressable `a` reference to an nsite manifest for use in snapshot
* (and snapshot-dedup query) tags.
*
* - Named site (kind 35128): `35128:<pubkey>:<dTag>`
* - Root site (kind 15128): `15128:<pubkey>:` (empty d-identifier)
*/
export function buildNsiteParentRef(pubkey: string, siteIdentifier?: string): string {
return siteIdentifier
? `${NSITE_NAMED_SITE_KIND}:${pubkey}:${siteIdentifier}`
: `${NSITE_ROOT_SITE_KIND}:${pubkey}:`;
}
/**
* Build the tag array for a NIP-5A kind-5128 manifest snapshot of a non-copied site.
*
* Per the spec, a snapshot MUST:
* - include exactly one `a` tag referencing the source manifest
* (named: `35128:<pubkey>:<dTag>`, root: `15128:<pubkey>:`)
* - copy the source manifest's `path` tags
* - include exactly one `x` aggregate tag matching the source's aggregate hash
*
* It MAY also copy `server`, `title`, `description`, and `source` tags.
*/
export function buildNsiteSnapshotTags(opts: {
pubkey: string;
siteIdentifier?: string;
pathTags: ReadonlyArray<readonly string[]>;
aggregateHash: string;
serverTags?: ReadonlyArray<readonly string[]>;
title?: string;
description?: string;
sourceUrl?: string;
}): string[][] {
const tags: string[][] = [
['a', buildNsiteParentRef(opts.pubkey, opts.siteIdentifier)],
...opts.pathTags.map(t => [...t]),
['x', opts.aggregateHash, 'aggregate'],
...(opts.serverTags ?? []).map(t => [...t]),
];
if (opts.title) tags.push(['title', opts.title]);
if (opts.description) tags.push(['description', opts.description]);
if (opts.sourceUrl) tags.push(['source', opts.sourceUrl]);
return tags;
}