From 21e4da5fbe27cb6a032ddd7099ba39dd8914a598 Mon Sep 17 00:00:00 2001 From: hzrd149 Date: Fri, 15 May 2026 13:36:10 -0500 Subject: [PATCH] Add version-history modal for nsite snapshots Adds a History icon button next to the Deploy button (visible only when an nsite provider is selected). Opens NsiteVersionsDialog, which queries the configured relays for kind 5128 manifest snapshots authored by the logged-in user for the current site, listed newest-first with date and file count. Each row exposes an "open" link to `https://v.` (NIP-5A snapshot URL) and a delete action that publishes a NIP-09 kind 5 event scoped to the snapshot kind. Deletion is gated behind an AlertDialog confirm and removes the row optimistically. A new buildNsiteSnapshotUrl helper is added in lib/utils/nsite.ts, and the existing pubkeyToBase36 is renamed to hex32ToBase36 (its existing name is kept as a deprecated alias). Co-Authored-By: Claude Opus 4.7 (1M context) --- src/components/deploy/DeploySteps.tsx | 84 ++++-- src/components/deploy/NsiteVersionsDialog.tsx | 284 ++++++++++++++++++ src/lib/utils/nsite.ts | 27 +- 3 files changed, 362 insertions(+), 33 deletions(-) create mode 100644 src/components/deploy/NsiteVersionsDialog.tsx diff --git a/src/components/deploy/DeploySteps.tsx b/src/components/deploy/DeploySteps.tsx index 17349286..85feeb36 100644 --- a/src/components/deploy/DeploySteps.tsx +++ b/src/components/deploy/DeploySteps.tsx @@ -1,6 +1,6 @@ import { useState, useEffect, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; -import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react'; +import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, History } from 'lucide-react'; import { ExternalFavicon } from '@/components/ExternalFavicon'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -24,6 +24,7 @@ import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm'; import { VercelDeployForm } from '@/components/deploy/VercelDeployForm'; import { NsiteSettingsDialog } from '@/components/deploy/NsiteSettingsDialog'; +import { NsiteVersionsDialog } from '@/components/deploy/NsiteVersionsDialog'; import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm'; import { DenoDeployForm } from '@/components/deploy/DenoDeployForm'; import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm'; @@ -177,6 +178,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp const [nsiteVfsConfig, setNsiteVfsConfig] = useState(null); const [nsiteVfsConfigLoading, setNsiteVfsConfigLoading] = useState(true); const [nsiteSettingsOpen, setNsiteSettingsOpen] = useState(false); + const [nsiteVersionsOpen, setNsiteVersionsOpen] = useState(false); useEffect(() => { if (!projectId) { @@ -777,6 +779,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp /> )} + {nsiteVfsConfig && user && selectedProvider?.type === 'nsite' && ( + + )} +

Deploy your project

@@ -956,34 +969,49 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp )} {selectedProvider && ( - + + {selectedProvider.type === 'nsite' && nsiteVfsConfig && user && ( + )} - +

)} )} diff --git a/src/components/deploy/NsiteVersionsDialog.tsx b/src/components/deploy/NsiteVersionsDialog.tsx new file mode 100644 index 00000000..7b58a6c0 --- /dev/null +++ b/src/components/deploy/NsiteVersionsDialog.tsx @@ -0,0 +1,284 @@ +import { useCallback, useEffect, useState } from 'react'; +import { ExternalLink, History, Loader2, Trash2 } from 'lucide-react'; +import type { NostrEvent } from '@nostrify/nostrify'; +import { useNostr } from '@nostrify/react'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; +import { Button } from '@/components/ui/button'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; +import { buildNsiteParentRef } from '@/lib/utils/nsiteAggregateHash'; +import { buildNsiteSnapshotUrl } from '@/lib/utils/nsite'; + +const NSITE_SNAPSHOT_KIND = 5128; +const QUERY_LIMIT = 500; +const QUERY_TIMEOUT_MS = 8_000; + +interface NsiteVersionsDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + /** Author of the snapshots — typically the logged-in user's pubkey */ + pubkey: string; + /** Named-site dTag (empty for root sites) */ + siteIdentifier?: string; + /** Gateway hostname used to build snapshot URLs (e.g. "nsite.lol") */ + gateway: string; + /** Relays to query and to publish deletion events through */ + relayUrls: string[]; +} + +interface VersionRow { + id: string; + createdAt: number; + fileCount: number; + /** Lower-case aggregate hash hex if present on the event */ + aggregateHash?: string; +} + +function countPathTags(event: NostrEvent): number { + let n = 0; + for (const tag of event.tags) { + if (tag[0] === 'path') n++; + } + return n; +} + +function extractAggregateHash(event: NostrEvent): string | undefined { + for (const tag of event.tags) { + if (tag[0] === 'x' && tag[2] === 'aggregate') return tag[1]; + } + return undefined; +} + +const dateFormatter = new Intl.DateTimeFormat(undefined, { + dateStyle: 'medium', + timeStyle: 'short', +}); + +export function NsiteVersionsDialog({ + open, + onOpenChange, + pubkey, + siteIdentifier, + gateway, + relayUrls, +}: NsiteVersionsDialogProps) { + const { nostr } = useNostr(); + const { mutateAsync: publishEvent } = useNostrPublish(); + + const [versions, setVersions] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + // Pending delete: which event id is awaiting confirmation + const [confirmDeleteId, setConfirmDeleteId] = useState(null); + // Currently in-flight deletions (event ids) + const [deletingIds, setDeletingIds] = useState>(new Set()); + + const parentRef = buildNsiteParentRef(pubkey, siteIdentifier); + + const loadVersions = useCallback(async () => { + if (!pubkey) return; + setLoading(true); + setError(null); + try { + const relayClient = nostr.group(relayUrls); + const events = await relayClient.query( + [{ + kinds: [NSITE_SNAPSHOT_KIND], + authors: [pubkey], + '#a': [parentRef], + limit: QUERY_LIMIT, + }], + { signal: AbortSignal.timeout(QUERY_TIMEOUT_MS) }, + ); + + // Dedup by event id (relays may return duplicates) and sort newest-first. + const byId = new Map(); + for (const ev of events) byId.set(ev.id, ev); + + const rows: VersionRow[] = Array.from(byId.values()) + .sort((a, b) => b.created_at - a.created_at) + .map(ev => ({ + id: ev.id, + createdAt: ev.created_at, + fileCount: countPathTags(ev), + aggregateHash: extractAggregateHash(ev), + })); + + setVersions(rows); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load versions'); + } finally { + setLoading(false); + } + }, [nostr, relayUrls, pubkey, parentRef]); + + // Refetch each time the dialog opens so the list is fresh after a new deploy. + useEffect(() => { + if (!open) return; + loadVersions(); + }, [open, loadVersions]); + + const handleDelete = async (eventId: string) => { + setConfirmDeleteId(null); + setDeletingIds(prev => new Set(prev).add(eventId)); + try { + // NIP-09 deletion: kind 5 event with `e` tag for the event id and `k` tag + // for its kind so clients can scope the deletion intent. + await publishEvent({ + kind: 5, + content: '', + tags: [ + ['e', eventId], + ['k', String(NSITE_SNAPSHOT_KIND)], + ], + }); + // Optimistically drop from the list — relay propagation is best-effort. + setVersions(prev => prev.filter(v => v.id !== eventId)); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to delete version'); + } finally { + setDeletingIds(prev => { + const next = new Set(prev); + next.delete(eventId); + return next; + }); + } + }; + + const pendingDelete = confirmDeleteId + ? versions.find(v => v.id === confirmDeleteId) + : null; + + return ( + + + + + + Version history + + + Snapshots published for this nsite. Each version is a permanent, + shareable copy of the site at the time it was deployed. + + + +
+ {loading && versions.length === 0 ? ( +
+ + Loading versions… +
+ ) : error ? ( +

{error}

+ ) : versions.length === 0 ? ( +
+

No published versions yet.

+

+ Enable "Publish version history" in site settings to start + tracking deploys. +

+
+ ) : ( +
    + {versions.map((v) => { + const url = buildNsiteSnapshotUrl({ eventIdHex: v.id, gateway }); + const deleting = deletingIds.has(v.id); + return ( +
  • +
    +
    + {dateFormatter.format(new Date(v.createdAt * 1000))} +
    +
    + {v.fileCount} {v.fileCount === 1 ? 'file' : 'files'} + {v.aggregateHash && ( + <> + · + {v.aggregateHash.slice(0, 8)} + + )} +
    +
    + + + + +
  • + ); + })} +
+ )} +
+
+ + {/* Delete confirmation */} + { if (!o) setConfirmDeleteId(null); }} + > + + + Delete this version? + + {pendingDelete && ( + <> + Publishes a Nostr delete event for the snapshot from{' '} + {dateFormatter.format(new Date(pendingDelete.createdAt * 1000))}. + Relays that honor NIP-09 will drop the event; gateways may continue + serving cached copies until they refresh. + + )} + + + + Cancel + confirmDeleteId && handleDelete(confirmDeleteId)} + className="bg-destructive text-destructive-foreground hover:bg-destructive/90" + > + Delete + + + + +
+ ); +} diff --git a/src/lib/utils/nsite.ts b/src/lib/utils/nsite.ts index 01c86a16..dde06098 100644 --- a/src/lib/utils/nsite.ts +++ b/src/lib/utils/nsite.ts @@ -63,16 +63,19 @@ export function isValidDTag(value: string): boolean { } /** - * Encode a 32-byte pubkey (as hex string) into a 50-character lowercase base36 string. - * Used to build named-site subdomain URLs: `{base36pubkey}{dTag}.{gateway}` + * Encode a 32-byte hex value into a 50-character lowercase base36 string. + * + * Used to build canonical nsite subdomain URLs: + * - Named site: `{base36pubkey}{dTag}.{gateway}` + * - Snapshot: `v{base36snapshotId}.{gateway}` * * Ported from nsite.run/apps/spa/src/lib/base36.js */ -export function pubkeyToBase36(pubkeyHex: string): string { +export function hex32ToBase36(hex: string): string { // hex → Uint8Array const bytes = new Uint8Array(32); for (let i = 0; i < 32; i++) { - bytes[i] = parseInt(pubkeyHex.slice(i * 2, i * 2 + 2), 16); + bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); } const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; @@ -92,6 +95,9 @@ export function pubkeyToBase36(pubkeyHex: string): string { return digits.reverse().join('').padStart(50, '0'); } +/** @deprecated use {@link hex32ToBase36} — kept as an alias for callers that still use this name. */ +export const pubkeyToBase36 = hex32ToBase36; + /** * Build the deployed URL for an nsite. * @@ -106,8 +112,19 @@ export function buildNsiteUrl(opts: { }): string { const { pubkeyHex, npub, gateway, siteIdentifier } = opts; if (siteIdentifier) { - const base36 = pubkeyToBase36(pubkeyHex); + const base36 = hex32ToBase36(pubkeyHex); return `https://${base36}${siteIdentifier}.${gateway}`; } return `https://${npub}.${gateway}`; } + +/** + * Build the canonical URL for an nsite manifest snapshot (NIP-5A kind 5128). + * `https://v{base36snapshotId}.{gateway}` + */ +export function buildNsiteSnapshotUrl(opts: { + eventIdHex: string; + gateway: string; +}): string { + return `https://v${hex32ToBase36(opts.eventIdHex)}.${opts.gateway}`; +}