diff --git a/src/components/ProviderConfigDialog.tsx b/src/components/ProviderConfigDialog.tsx index 278d7231..60b812e9 100644 --- a/src/components/ProviderConfigDialog.tsx +++ b/src/components/ProviderConfigDialog.tsx @@ -79,8 +79,8 @@ export function ProviderConfigDialog({ return ( - - + +
-
+ {/* The fields scroll, the buttons don't: a provider with relay and + blossom lists is taller than a phone, and a Save button below the + fold is a Save button nobody can press. */} +
- + + +
+ + +
+ ); +} diff --git a/src/hooks/useNpanelClaims.ts b/src/hooks/useNpanelClaims.ts new file mode 100644 index 00000000..7b47c2da --- /dev/null +++ b/src/hooks/useNpanelClaims.ts @@ -0,0 +1,86 @@ +import { useQuery } from '@tanstack/react-query'; +import { useNostr } from '@nostrify/react'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import type { NpanelProvider } from '@/contexts/DeploySettingsContext'; +import { fetchNpanelClaims, type NpanelClaim } from '@/lib/deploy/npanelApi'; +import { NAMED_SITE_KIND, planClaim, type MigrationStep } from '@/lib/deploy/npanelMigration'; + +/** How long the relay round trip for one's own sites is given. */ +const RELAY_TIMEOUT_MS = 4_000; + +/** A waiting name, with what it would take to get it back. */ +export interface NpanelClaimPlan extends NpanelClaim { + step: MigrationStep; +} + +/** The `identifier` half of a `kind:pubkey:identifier` address. */ +function addressIdentifier(address: string): string { + return address.split(':').slice(2).join(':'); +} + +/** + * The names waiting for the logged-in user on a gateway, and what each needs. + * + * The second half of the answer comes from relays rather than the gateway: to + * know whether a name can simply be repointed, one has to know which sites this + * user already publishes, and that is on the network, not in npanel. + */ +export function useNpanelClaims(provider: NpanelProvider | undefined) { + const { user } = useCurrentUser(); + const { nostr } = useNostr(); + + return useQuery({ + queryKey: ['npanel-claims', provider?.dashboardHost, user?.pubkey], + enabled: Boolean(provider && user), + // Nobody's list of waiting names changes on its own, and every refetch + // costs a signature — which on a remote signer costs a round trip. + staleTime: 5 * 60 * 1000, + refetchOnWindowFocus: false, + retry: false, + queryFn: async ({ signal }) => { + if (!provider || !user) return []; + + const claims = await fetchNpanelClaims(provider.dashboardHost, user.signer, signal); + if (!claims.length) return []; + + // Only the names actually in play are asked about, rather than every + // site this key has ever published. + const wanted = new Set(); + for (const claim of claims) { + const identifier = claim.manifest?.tags.find(([name]) => name === 'd')?.[1]; + if (identifier) wanted.add(identifier); + if (claim.mine && claim.address) wanted.add(addressIdentifier(claim.address)); + } + + const events = wanted.size + ? await nostr.group(provider.relayUrls).query( + [{ kinds: [NAMED_SITE_KIND], authors: [user.pubkey], '#d': [...wanted] }], + { signal: AbortSignal.any([signal, AbortSignal.timeout(RELAY_TIMEOUT_MS)]) }, + ) + : []; + + const published = new Set( + events + .map((event) => event.tags.find(([name]) => name === 'd')?.[1]) + .filter((identifier): identifier is string => Boolean(identifier)), + ); + + // A name npanel serves from this user's own key is a site this user + // published, so relays that know nothing about it are relays that are + // not answering. Planning against that silence would mean republishing + // over live sites, so it fails loudly instead. + const known = claims + .filter((claim) => claim.mine && claim.address) + .map((claim) => addressIdentifier(claim.address ?? '')) + .filter(Boolean); + + if (known.length && !known.some((identifier) => published.has(identifier))) { + throw new Error( + 'Relays did not answer with the sites you already publish, so it is not safe to work out what needs republishing. Try again in a moment.', + ); + } + + return claims.map((claim) => ({ ...claim, step: planClaim(claim, user.pubkey, published) })); + }, + }); +} diff --git a/src/lib/deploy/NpanelAdapter.ts b/src/lib/deploy/NpanelAdapter.ts index 1b3ce722..d1c99242 100644 --- a/src/lib/deploy/NpanelAdapter.ts +++ b/src/lib/deploy/NpanelAdapter.ts @@ -1,15 +1,11 @@ -import { NIP98 } from '@nostrify/nostrify'; -import { N64 } from '@nostrify/nostrify/utils'; import type { NostrSigner } from '@nostrify/nostrify'; import type { DeployAdapter, DeployOptions, DeployResult, NpanelDeployConfig } from './types'; import { NsiteAdapter } from './NsiteAdapter'; +import { NPANEL_TIMEOUT_MS, npanelError, npanelRequest } from './npanelApi'; /** nsite named-site kind. An npanel host always points at one of these. */ const NAMED_SITE_KIND = 35128; -/** Timeout for a single API call (ms). */ -const FETCH_TIMEOUT_MS = 15_000; - /** What `GET /api/hosts/:hostname/available` answers. */ export interface NameAvailability { hostname: string; @@ -38,7 +34,7 @@ export async function checkNameAvailable( const url = `https://${dashboardHost}/api/hosts/${encodeURIComponent(hostname)}/available`; try { - const response = await fetch(url, { signal: signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS) }); + const response = await fetch(url, { signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS) }); if (!response.ok) return { hostname, available: true }; return (await response.json()) as NameAvailability; } catch { @@ -146,37 +142,12 @@ export class NpanelAdapter implements DeployAdapter { } /** A NIP-98 request to the gateway's API. */ - private async request(method: string, path: string, body?: unknown): Promise { - const url = `https://${this.dashboardHost}${path}`; - - let request = new Request(url, { - method, - ...(body === undefined - ? {} - : { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }), - }); - - // Signed against the URL being requested, so the token authorizes this call - // and no other. No CORS proxy: npanel answers browsers directly, and a proxy - // would rewrite the URL out from under the signature. - const template = await NIP98.template(request); - const event = await this.signer.signEvent(template); - - const headers = new Headers(request.headers); - headers.set('Authorization', `Nostr ${N64.encodeEvent(event)}`); - request = new Request(request, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); - - return await fetch(request); + private request(method: string, path: string, body?: unknown): Promise { + return npanelRequest(this.dashboardHost, this.signer, method, path, body); } /** The gateway's own sentence about a failure, which is written to be read. */ - private async error(response: Response, fallback: string): Promise { - const body = await response.json().catch(() => null) as { error?: string } | null; - - if (response.status === 403 && !body?.error) { - return new Error(`${fallback}: this gateway is not accepting new sites right now.`); - } - - return new Error(body?.error ?? `${fallback} (HTTP ${response.status}).`); + private error(response: Response, fallback: string): Promise { + return npanelError(response, fallback); } } diff --git a/src/lib/deploy/npanelApi.ts b/src/lib/deploy/npanelApi.ts new file mode 100644 index 00000000..37182d25 --- /dev/null +++ b/src/lib/deploy/npanelApi.ts @@ -0,0 +1,119 @@ +import { NIP98 } from '@nostrify/nostrify'; +import { N64 } from '@nostrify/nostrify/utils'; +import type { NostrSigner } from '@nostrify/nostrify'; + +/** Timeout for a single API call (ms). */ +export const NPANEL_TIMEOUT_MS = 15_000; + +/** + * A NIP-98 request to an npanel gateway's API. + * + * Signed against the URL being requested, so the token authorizes this call and + * no other. No CORS proxy: npanel answers browsers directly, and a proxy would + * rewrite the URL out from under the signature. + */ +export async function npanelRequest( + dashboardHost: string, + signer: NostrSigner, + method: string, + path: string, + body?: unknown, + signal?: AbortSignal, +): Promise { + const url = `https://${dashboardHost}${path}`; + + let request = new Request(url, { + method, + ...(body === undefined + ? {} + : { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }), + }); + + const template = await NIP98.template(request); + const event = await signer.signEvent(template); + + const headers = new Headers(request.headers); + headers.set('Authorization', `Nostr ${N64.encodeEvent(event)}`); + request = new Request(request, { + headers, + signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS), + }); + + return await fetch(request); +} + +/** The gateway's own sentence about a failure, which is written to be read. */ +export async function npanelError(response: Response, fallback: string): Promise { + const body = (await response.json().catch(() => null)) as { error?: string } | null; + + if (response.status === 403 && !body?.error) { + return new Error(`${fallback}: this gateway is not accepting new sites right now.`); + } + + return new Error(body?.error ?? `${fallback} (HTTP ${response.status}).`); +} + +/** An nsite manifest, reduced to the parts that are the site. */ +export interface NpanelClaimManifest { + kind: number; + content: string; + tags: string[][]; +} + +/** A name waiting to be handed back to whoever held it before this gateway. */ +export interface NpanelClaim { + hostname: string; + /** Where the record came from, eg `picohost`. */ + source: string; + /** Whether something is being served at the name right now. */ + live: boolean; + /** Where the name points today, as `kind:pubkey:identifier`, or null if nowhere. */ + address: string | null; + /** Whether that address is already the claimant's own key. */ + mine: boolean; + /** The archive's copy, when there is one to republish. Null when `mine`. */ + manifest: NpanelClaimManifest | null; +} + +/** + * The names this signer can take back from the gateway's archive. + * + * Empty for anyone with nothing waiting, which is almost everyone — this is the + * residue of one migration, not a feature of the gateway. + */ +export async function fetchNpanelClaims( + dashboardHost: string, + signer: NostrSigner, + signal?: AbortSignal, +): Promise { + const response = await npanelRequest(dashboardHost, signer, 'GET', '/api/claims', undefined, signal); + + if (!response.ok) { + throw await npanelError(response, 'Could not ask the gateway which names are waiting for you'); + } + + const { claims } = (await response.json()) as { claims: NpanelClaim[] }; + return claims; +} + +/** Point a name waiting for this signer at a site they published. */ +export async function claimNpanelHostname( + dashboardHost: string, + signer: NostrSigner, + hostname: string, + address: string, + signal?: AbortSignal, +): Promise { + const response = await npanelRequest( + dashboardHost, + signer, + 'POST', + `/api/claims/${encodeURIComponent(hostname)}`, + { address }, + signal, + ); + + if (!response.ok) { + throw await npanelError(response, `Could not take back ${hostname}`); + } +} diff --git a/src/lib/deploy/npanelMigration.test.ts b/src/lib/deploy/npanelMigration.test.ts new file mode 100644 index 00000000..ba415d08 --- /dev/null +++ b/src/lib/deploy/npanelMigration.test.ts @@ -0,0 +1,88 @@ +import { describe, it, expect } from 'vitest'; +import type { NpanelClaim } from './npanelApi'; +import { NAMED_SITE_KIND, planClaim, republishTags } from './npanelMigration'; + +const PUBKEY = 'a'.repeat(64); +const ARCHIVE = 'b'.repeat(64); + +function claim(overrides: Partial = {}): NpanelClaim { + return { + hostname: 'mysite.shakespeare.wtf', + source: 'picohost', + live: true, + address: `${NAMED_SITE_KIND}:${ARCHIVE}:mysite`, + mine: false, + manifest: { + kind: NAMED_SITE_KIND, + content: '', + tags: [ + ['d', 'mysite'], + ['title', 'mysite.shakespeare.wtf'], + ['path', '/index.html', 'c'.repeat(64)], + ['server', 'https://blossom.ditto.pub/'], + ], + }, + ...overrides, + }; +} + +describe('planClaim', () => { + it('only changes the record for a site already on the owner’s key', () => { + const address = `${NAMED_SITE_KIND}:${PUBKEY}:mysite`; + + expect(planClaim(claim({ mine: true, address, manifest: null }), PUBKEY, new Set())).toEqual({ + kind: 'claim', + address, + reason: 'mine', + }); + }); + + it('points a name at a site the owner already publishes, rather than republishing over it', () => { + // The destructive case: kind 35128 is addressable, so publishing the + // archive's stale copy at this `d` tag would replace the live site. + expect(planClaim(claim(), PUBKEY, new Set(['mysite']))).toEqual({ + kind: 'claim', + address: `${NAMED_SITE_KIND}:${PUBKEY}:mysite`, + reason: 'published', + }); + }); + + it('republishes the archived manifest when nothing is published under that name', () => { + const step = planClaim(claim(), PUBKEY, new Set(['something-else'])); + + expect(step.kind).toBe('republish'); + expect(step).toMatchObject({ identifier: 'mysite' }); + }); + + it('refuses a root site, which would replace the owner’s main site', () => { + const rooted = claim({ manifest: { kind: 15128, content: '', tags: [] } }); + + expect(planClaim(rooted, PUBKEY, new Set()).kind).toBe('blocked'); + }); + + it('has nothing to do for a reservation whose site never made it across', () => { + const empty = claim({ live: false, address: null, manifest: null }); + + expect(planClaim(empty, PUBKEY, new Set()).kind).toBe('blocked'); + }); +}); + +describe('republishTags', () => { + it('keeps the files and where to fetch them, and takes the relay hints', () => { + const manifest = claim().manifest; + if (!manifest) throw new Error('fixture has a manifest'); + + const tags = republishTags( + { ...manifest, tags: [...manifest.tags, ['relay', 'wss://gone.example']] }, + 'mysite', + ['wss://relay.ditto.pub'], + ); + + expect(tags[0]).toEqual(['d', 'mysite']); + expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]); + expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']); + expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']); + expect(tags).not.toContainEqual(['relay', 'wss://gone.example']); + expect(tags.filter(([name]) => name === 'd')).toHaveLength(1); + }); +}); diff --git a/src/lib/deploy/npanelMigration.ts b/src/lib/deploy/npanelMigration.ts new file mode 100644 index 00000000..cce44196 --- /dev/null +++ b/src/lib/deploy/npanelMigration.ts @@ -0,0 +1,107 @@ +import type { NpanelClaim, NpanelClaimManifest } from './npanelApi'; + +/** nsite named-site kind. Everything a gateway archived is one of these. */ +export const NAMED_SITE_KIND = 35128; + +/** + * What taking one name back requires. + * + * Three outcomes rather than two, because the interesting case is the one in + * the middle: a name whose site is already published under the claimant's own + * key needs no republishing at all, and republishing it anyway would overwrite + * a live site with an old snapshot of itself. + */ +export type MigrationStep = + /** Point the name at a site that already exists. Costs one request. */ + | { kind: 'claim'; address: string; reason: 'mine' | 'published' } + /** Publish the archived manifest under the claimant's key, then point at it. */ + | { kind: 'republish'; identifier: string; manifest: NpanelClaimManifest } + /** Nothing safe to do without a person deciding something first. */ + | { kind: 'blocked'; reason: string }; + +/** The `d` tag of a manifest, which for a named site is the site's identifier. */ +export function manifestIdentifier(manifest: NpanelClaimManifest): string { + return manifest.tags.find(([name]) => name === 'd')?.[1] ?? ''; +} + +/** + * Decide how a single waiting name gets back to its owner. + * + * `published` is the set of `d` tags the owner already publishes kind-35128 + * events under. It is what separates a name that only needs a record changed + * from one that needs a site published, and getting it wrong in the careless + * direction destroys a live site: kind 35128 is addressable, so a second event + * at the same `d` tag replaces the first one everywhere. + */ +export function planClaim( + claim: NpanelClaim, + pubkey: string, + published: ReadonlySet, +): MigrationStep { + // Already on their key — the site was never anyone else's, only the record + // of who owns the name was missing. + if (claim.mine && claim.address) { + return { kind: 'claim', address: claim.address, reason: 'mine' }; + } + + if (!claim.manifest) { + return { + kind: 'blocked', + reason: 'Nothing was archived under this name. Deploy a project to it to take it back.', + }; + } + + // A root site is the one site a key can only have one of. Republishing an + // archived copy as one would replace whatever the claimant's own key serves. + if (claim.manifest.kind !== NAMED_SITE_KIND) { + return { + kind: 'blocked', + reason: 'This name was archived as a root site, which would replace your main site if republished.', + }; + } + + const identifier = manifestIdentifier(claim.manifest); + if (!identifier) { + return { kind: 'blocked', reason: 'The archived site has no name to publish it under.' }; + } + + // The site is already theirs under this name; the hostname just needs to be + // told about it. Both names then serve the same site, which is what someone + // who deployed the same project twice was always asking for. + if (published.has(identifier)) { + return { + kind: 'claim', + address: `${NAMED_SITE_KIND}:${pubkey}:${identifier}`, + reason: 'published', + }; + } + + return { kind: 'republish', identifier, manifest: claim.manifest }; +} + +/** + * The tags to sign to republish an archived site under one's own key. + * + * An nsite manifest is its tags — the paths and their hashes, and the Blossom + * servers those hashes can be fetched from — so signing these again produces + * the same site, file for file, under a different key. The blobs themselves are + * addressed by hash and are already where the `server` tags say they are, so + * nothing has to be uploaded. + * + * Relay hints are replaced rather than kept: the archive's, if it had any, say + * where the archive published, and this event is going somewhere else. + */ +export function republishTags( + manifest: NpanelClaimManifest, + identifier: string, + relayUrls: string[], +): string[][] { + const kept = manifest.tags.filter(([name]) => name !== 'd' && name !== 'relay' && name !== 'r'); + + return [ + // First, as an addressable event's `d` tag should be. + ['d', identifier], + ...kept, + ...relayUrls.map((url) => ['relay', url]), + ]; +} diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 2f034241..e113afd6 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -7,13 +7,15 @@ import { useDeploySettings } from '@/hooks/useDeploySettings'; import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth'; import { useVercelOAuth } from '@/hooks/useVercelOAuth'; import { useCurrentUser } from '@/hooks/useCurrentUser'; -import type { DeployProvider } from '@/contexts/DeploySettingsContext'; +import type { DeployProvider, NpanelProvider } from '@/contexts/DeploySettingsContext'; import type { PresetDeployProvider } from '@/lib/deploy/types'; import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NPANEL_PROVIDER, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets'; import { ExternalFavicon } from '@/components/ExternalFavicon'; import { ProviderConfigDialog } from '@/components/ProviderConfigDialog'; import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog'; import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog'; +import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog'; +import { Button } from '@/components/ui/button'; import { DndContext, closestCenter, @@ -150,6 +152,7 @@ export function DeploySettings() { const [selectedPreset, setSelectedPreset] = useState(null); const [addDialogOpen, setAddDialogOpen] = useState(false); const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false); + const [migratingProvider, setMigratingProvider] = useState(null); // Drag and drop sensors const sensors = useSensors( @@ -341,6 +344,38 @@ export function DeploySettings() { )} + {/* Sites held for their previous owner on a gateway that took over a + domain. Shown without asking the gateway first: finding out costs + a signature, and a signing prompt nobody asked for is worse than a + button that sometimes opens an empty list. */} + {user && settings.providers.map((provider) => ( + provider.type === 'npanel' ? ( +
+
+

Sites from before {provider.name}

+

+ Names you published on {provider.domain} under the old host are being served + from an archive until you take them back. +

+
+ +
+ ) : null + ))} + + {migratingProvider && ( + !open && setMigratingProvider(null)} + provider={migratingProvider} + /> + )} + {/* Provider Config Dialog */} {selectedProviderIndex !== null && settings.providers[selectedProviderIndex] && (