diff --git a/src/components/deploy/NpanelMigrationDialog.tsx b/src/components/deploy/NpanelMigrationDialog.tsx index d387178d..d2cc32c4 100644 --- a/src/components/deploy/NpanelMigrationDialog.tsx +++ b/src/components/deploy/NpanelMigrationDialog.tsx @@ -1,7 +1,9 @@ import { useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { useNostr } from '@nostrify/react'; -import { AlertCircle, Check, ExternalLink, Loader2, Rocket, Trash2 } from 'lucide-react'; +import type { NostrEvent } from '@nostrify/nostrify'; +import { AlertCircle, Check, ExternalLink, Eye, Loader2, Rocket, Tag, Trash2 } from 'lucide-react'; +import type { LucideIcon } from 'lucide-react'; import { Dialog, DialogContent, @@ -10,14 +12,30 @@ import { DialogHeader, DialogTitle, } from '@/components/ui/dialog'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNpanelClaims, type NpanelClaimPlan, type NpanelTakenSite } from '@/hooks/useNpanelClaims'; import type { NpanelProvider } from '@/contexts/DeploySettingsContext'; -import { claimNpanelHostname } from '@/lib/deploy/npanelApi'; -import { NAMED_SITE_KIND, republishTags, retitleTags } from '@/lib/deploy/npanelMigration'; +import { claimNpanelHostname, deleteNpanelClaim } from '@/lib/deploy/npanelApi'; +import { + NAMED_SITE_KIND, + nsitePreviewUrl, + republishTags, + retitleTags, + sitePreviewUrl, +} from '@/lib/deploy/npanelMigration'; import { checkRelayCoverage, forwardMissing, host, publishToRelays } from '@/lib/deploy/publishToRelays'; /** Where a single name has got to. */ @@ -25,9 +43,18 @@ type RowStatus = | { kind: 'waiting' } | { kind: 'publishing' } | { kind: 'claiming' } + | { kind: 'deleting' } + | { kind: 'deleted'; note?: string } | { kind: 'done'; partial?: string } | { kind: 'failed'; error: string }; +/** A name a person has asked to delete, and has not confirmed yet. */ +interface PendingDeletion { + hostname: string; + /** Whether a copy of the site is published under their own key. */ + published: boolean; +} + /** What the last coverage run found, as a sentence per relay. */ interface CoverageReport { lines: string[]; @@ -52,6 +79,11 @@ function describeStep(claim: NpanelClaimPlan): string { } } +/** The `d` tag of an event, which for a named site is the site's identifier. */ +function eventIdentifier(event: NostrEvent): string { + return event.tags.find(([name]) => name === 'd')?.[1] ?? ''; +} + /** "took 3 of 5 relays", where that is worth saying. */ function coverageNote(accepted: string[], rejected: { url: string; reason: string }[]): string | undefined { if (!rejected.length) return undefined; @@ -66,8 +98,11 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi const { data, isLoading, error } = useNpanelClaims(open ? provider : undefined); const [statuses, setStatuses] = useState>({}); - const [running, setRunning] = useState(null); + const [running, setRunning] = useState(null); const [coverage, setCoverage] = useState(null); + const [confirming, setConfirming] = useState(null); + /** Whether anything has happened that the cached lists do not know about. */ + const [dirty, setDirty] = useState(false); const claims = data?.waiting ?? []; const actionable = claims.filter((claim) => claim.step.kind !== 'blocked'); @@ -77,12 +112,19 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi const strays = (data?.taken ?? []).filter((site) => site.stray); const done = Object.values(statuses).filter((status) => status.kind === 'done').length; + const deleted = Object.values(statuses).filter((status) => status.kind === 'deleted').length; const failed = Object.values(statuses).filter((status) => status.kind === 'failed').length; const setStatus = (hostname: string, status: RowStatus) => { setStatuses((previous) => ({ ...previous, [hostname]: status })); }; + /** Whether a row has already reached a state no further action applies to. */ + const settled = (hostname: string): boolean => { + const kind = statuses[hostname]?.kind; + return kind === 'done' || kind === 'deleted'; + }; + /** * Take back one name. * @@ -145,33 +187,54 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi }); }; - /** Ask a relay to forget a manifest that was published for an unusable name. */ + /** + * Give a name up rather than take it back. + * + * Only npanel forgets anything. The archive's manifest stays on relays under + * the archive's key, and a copy published under the user's own key stays + * theirs — what ends is this gateway serving the name and holding it for + * them. Saying otherwise in the confirmation would be a promise nothing here + * can keep. + */ + const removeClaim = async (hostname: string): Promise => { + if (!user) return; + + setStatus(hostname, { kind: 'deleting' }); + await deleteNpanelClaim(provider.dashboardHost, user.signer, hostname); + setStatus(hostname, { kind: 'deleted' }); + }; + + /** + * Undo a manifest published for a name that can never load. + * + * Both halves, because there is no useful middle state: a relay is asked to + * forget the event, and the gateway to forget the name. Keeping the record + * for a hostname whose TLS handshake has always failed and always will would + * leave a row in this list forever with nothing to do about it. + * + * The gateway going second is deliberate — it is the recoverable half. A + * deletion request cannot be taken back, so it is the one that has to be + * worth making on its own. + */ const removeStray = async (site: NpanelTakenSite): Promise => { if (!user) return; setStatus(site.hostname, { kind: 'publishing' }); - try { - const identifier = site.event.tags.find(([name]) => name === 'd')?.[1] ?? ''; - const deletion = await user.signer.signEvent({ - kind: 5, - content: 'Published for a hostname no certificate can cover.', - created_at: Math.floor(Date.now() / 1000), - tags: [ - ['e', site.event.id], - ['a', `${site.event.kind}:${user.pubkey}:${identifier}`], - ['k', String(site.event.kind)], - ], - }); + const deletion = await user.signer.signEvent({ + kind: 5, + content: 'Published for a hostname no certificate can cover.', + created_at: Math.floor(Date.now() / 1000), + tags: [ + ['e', site.event.id], + ['a', `${site.event.kind}:${user.pubkey}:${eventIdentifier(site.event)}`], + ['k', String(site.event.kind)], + ], + }); - await publishToRelays(nostr, deletion, provider.relayUrls); - setStatus(site.hostname, { kind: 'done' }); - } catch (err) { - setStatus(site.hostname, { - kind: 'failed', - error: err instanceof Error ? err.message : 'Failed', - }); - } + await publishToRelays(nostr, deletion, provider.relayUrls); + await removeClaim(site.hostname); + setStatus(site.hostname, { kind: 'deleted', note: 'Retracted, and taken off the gateway.' }); }; /** Run `action` over `rows`, one at a time, recording failures per row. */ @@ -181,7 +244,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi action: (row: T) => Promise, ): Promise => { for (const row of rows) { - if (statuses[key(row)]?.kind === 'done') continue; + if (settled(key(row))) continue; try { await action(row); @@ -194,6 +257,30 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi } }; + /** + * One row's action, on its own. + * + * Still holds the whole dialog while it runs. A signer answers one request at + * a time whatever the UI allows, and two buttons that look live but queue + * behind each other read as a hang. + */ + const runRow = async (hostname: string, action: () => Promise): Promise => { + setRunning('row'); + + try { + await action(); + // Deliberately not refetched here. Somebody clearing out twenty sites + // clicks twenty times, and re-reading the list after each one would cost + // a signature and a relay round trip to learn what the row already says. + // The list is caught up when the dialog closes. + setDirty(true); + } catch (err) { + setStatus(hostname, { kind: 'failed', error: err instanceof Error ? err.message : 'Failed' }); + } + + setRunning(null); + }; + const migrateAll = async () => { setRunning('migrate'); // One at a time: a remote signer answers one request at a time anyway, and @@ -201,6 +288,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi // than a hundred simultaneous errors. await runEach(actionable, (claim) => claim.hostname, migrate); setRunning(null); + setDirty(true); // Whatever succeeded is no longer waiting, and whatever failed still is. queryClient.invalidateQueries({ queryKey: ['npanel-claims'] }); }; @@ -209,6 +297,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi setRunning('titles'); await runEach(retitlable, (site) => site.hostname, retitle); setRunning(null); + setDirty(true); queryClient.invalidateQueries({ queryKey: ['npanel-claims'] }); }; @@ -268,6 +357,19 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi Claiming… ); + case 'deleting': + return ( + + Deleting… + + ); + case 'deleted': + return ( + + + {status.note ?? `Deleted from ${provider.domain}.`} + + ); case 'done': return ( @@ -295,191 +397,349 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi const busy = running !== null; + /** Names still worth running the bulk button over. */ + const remaining = actionable.filter((claim) => !settled(claim.hostname)).length; + + /** + * Where this sitting has got to, said once. + * + * Deleting is reported alongside taking names back rather than folded into + * it, because they are opposite decisions and somebody who has just made + * thirty of them should be able to see that they did. + */ + const summary = (() => { + const parts: string[] = []; + if (done) parts.push(`${done} done`); + if (deleted) parts.push(`${deleted} deleted`); + if (failed) parts.push(`${failed} failed`); + + if (failed) return `${parts.join(', ')} — try the failed ones again.`; + if (parts.length) { + return `${parts.join(', ')}. A republished site takes the gateway about a minute to pick up.`; + } + return `${remaining} to migrate.`; + })(); + + /** + * Close, and let the lists catch up. + * + * Marked stale rather than refetched: the query is disabled while the dialog + * is shut, so nothing is asked until somebody opens it again — and asking + * costs a signature, which on a remote signer costs a round trip. + */ + const close = () => { + if (dirty) { + queryClient.invalidateQueries({ queryKey: ['npanel-claims'] }); + queryClient.invalidateQueries({ queryKey: ['npanel-claim-count'] }); + } + onOpenChange(false); + }; + + /** + * What can be done about one name, minus whatever does not apply to it. + * + * Every row gets its own controls rather than only the bulk button, because + * the list is not a queue of decisions already made. Somebody with forty + * names on file wants three of them back and the rest gone, and until now the + * only thing the dialog would do was hand them all forty. + */ + const renderActions = ( + hostname: string, + options: { + /** Where the site can be looked at, when anywhere can show it. */ + preview?: string; + /** The one thing this row's section does to a name that is staying. */ + act?: { label: string; icon: LucideIcon; run: () => Promise }; + /** Present when the name can be given up. `published` decides what the confirmation promises. */ + deletable?: { published: boolean }; + }, + ) => { + const gone = settled(hostname); + const ActionIcon = options.act?.icon; + + return ( +
+ {options.preview && ( + + )} + + {options.act && ActionIcon && !gone && ( + + )} + + {options.deletable && !gone && ( + + )} +
+ ); + }; + return ( - - - - Take back your sites - - These names on {provider.domain} were yours before this gateway took the domain over. - They are being served from an archive key until you publish your own copy. - - + <> + (next ? onOpenChange(true) : close())}> + + + Take back your sites + + These names on {provider.domain} were yours before this gateway took the domain over. + They are being served from an archive key until you publish your own copy. + + -
- {isLoading && ( -
- - - -
- )} - - {error && ( - - - {error.message} - - )} - - {data && !claims.length && !data.taken.length && ( -

- Nothing is waiting for you here. -

- )} - - {actionable.length > 0 && ( -
-

Waiting for you

-
- {actionable.map((claim) => ( -
-
-
{claim.hostname}
-
{renderStatus(claim.hostname, describeStep(claim))}
-
- - {claim.step.kind === 'republish' ? 'republish' : 'claim'} - -
- ))} +
+ {isLoading && ( +
+ + +
-
- )} + )} - {retitlable.length > 0 && ( -
-
-
-

Titled after their address

-

- The archive could only call a site by its hostname. These say what they are - actually called, so the name they publish under can too. -

-
- -
-
- {retitlable.map((site) => ( -
-
-
{site.hostname}
-
- {renderStatus( - site.hostname, - site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.', - )} + {error && ( + + + {error.message} + + )} + + {data && !claims.length && !data.taken.length && ( +

+ Nothing is waiting for you here. +

+ )} + + {actionable.length > 0 && ( +
+

Waiting for you

+
+ {actionable.map((claim) => ( +
+
+
{claim.hostname}
+
{renderStatus(claim.hostname, describeStep(claim))}
+ {renderActions(claim.hostname, { + preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain), + // The word the button uses is the work it does. A name + // whose site is already on this key publishes nothing. + act: { + label: claim.step.kind === 'republish' ? 'Publish' : 'Claim', + icon: Rocket, + run: () => migrate(claim), + }, + // A `claim` step, either reason, means a copy of the site + // is already published under this key and survives the + // name going away. A `republish` step means it is not. + deletable: { published: claim.step.kind === 'claim' }, + })}
-
- ))} -
-
- )} - - {(data?.events.length ?? 0) > 0 && ( -
-
-
-

Relay coverage

-

- A site is only as findable as the relays holding its manifest. This sends the - events you already published to the relays that do not have them — same events, - no signing. -

-
- -
- {coverage && ( -
- {coverage.lines.map((line) => ( -

- {line} -

))}
- )} -
- )} +
+ )} - {strays.length > 0 && ( -
-

Published for a name that cannot load

-
- {strays.map((site) => ( -
-
-
{site.hostname}
-
- {renderStatus( - site.hostname, - `No certificate covers a name this deep under ${provider.domain}.`, - )} + {retitlable.length > 0 && ( +
+
+
+

Titled after their address

+

+ The archive could only call a site by its hostname. These say what they are + actually called, so the name they publish under can too. +

+
+ +
+
+ {retitlable.map((site) => ( +
+
+
{site.hostname}
+
+ {renderStatus( + site.hostname, + site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.', + )} +
+ {renderActions(site.hostname, { + preview: sitePreviewUrl( + `${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`, + site.hostname, + provider.domain, + ), + act: { label: 'Retitle', icon: Tag, run: () => retitle(site) }, + deletable: { published: true }, + })}
- -
- ))} + ))} +
-
- )} + )} - {blocked.length > 0 && ( -
-

Needs a decision

-
- {blocked.map((claim) => ( -
-
{claim.hostname}
-

{describeStep(claim)}

+ {(data?.events.length ?? 0) > 0 && ( +
+
+
+

Relay coverage

+

+ A site is only as findable as the relays holding its manifest. This sends the + events you already published to the relays that do not have them — same events, + no signing. +

- ))} + +
+ {coverage && ( +
+ {coverage.lines.map((line) => ( +

+ {line} +

+ ))} +
+ )}
-
- )} -
+ )} - - - {failed > 0 - ? `${done} done, ${failed} failed — run it again to retry.` - : done > 0 - ? `${done} done. A republished site takes the gateway about a minute to pick up.` - : `${actionable.length} to migrate.`} - -
- - + {strays.length > 0 && ( +
+

Published for a name that cannot load

+
+ {strays.map((site) => ( +
+
+
{site.hostname}
+
+ {renderStatus( + site.hostname, + `No certificate covers a name this deep under ${provider.domain}.`, + )} +
+
+ {/* + One button, not two. What is wrong with these is that + they exist at all, so there is no version of retracting + the manifest that leaves the gateway's record worth + keeping — the name has never loaded for anyone and never + will. The hostname is unservable, so the preview can only + come from the address. + */} + {renderActions(site.hostname, { + preview: nsitePreviewUrl( + `${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`, + ), + act: { label: 'Retract', icon: Trash2, run: () => removeStray(site) }, + })} +
+ ))} +
+
+ )} + + {blocked.length > 0 && ( +
+

Needs a decision

+

+ Nothing here can be taken back safely without you choosing something first. Deleting + is a decision too, and for most of these it is the right one. +

+
+ {blocked.map((claim) => ( +
+
+
{claim.hostname}
+
{renderStatus(claim.hostname, describeStep(claim))}
+
+ {renderActions(claim.hostname, { + preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain), + deletable: { published: claim.mine }, + })} +
+ ))} +
+
+ )}
-
- -
+ + + {summary} +
+ + +
+
+
+
+ + !next && setConfirming(null)}> + + + Delete {confirming?.hostname}? + + {provider.name} stops serving this name and stops holding it for you, and it goes back + to being anybody's to take. This cannot be undone.{' '} + {confirming?.published + ? 'The site itself stays published under your key, and can still be reached by its address.' + : 'The archived copy stays on Nostr under the key that published it — this only ends the gateway serving it.'} + + + + Cancel + { + const hostname = confirming?.hostname; + setConfirming(null); + if (hostname) void runRow(hostname, () => removeClaim(hostname)); + }} + > + Delete + + + + + ); } diff --git a/src/lib/deploy/npanelApi.ts b/src/lib/deploy/npanelApi.ts index b2f151f5..940521ea 100644 --- a/src/lib/deploy/npanelApi.ts +++ b/src/lib/deploy/npanelApi.ts @@ -179,3 +179,32 @@ export async function claimNpanelHostname( throw await npanelError(response, `Could not take back ${hostname}`); } } + +/** + * Give a name up rather than take it back. + * + * The gateway forgets the hostname entirely: it stops serving the archived + * site, stops holding the name, and the name goes back to being anybody's. What + * this cannot touch is the network — the archive's manifest is its own event + * under its own key, and a copy the user published is theirs to retract — so + * this is a request to one server and nothing more. + */ +export async function deleteNpanelClaim( + dashboardHost: string, + signer: NostrSigner, + hostname: string, + signal?: AbortSignal, +): Promise { + const response = await npanelRequest( + dashboardHost, + signer, + 'DELETE', + `/api/claims/${encodeURIComponent(hostname)}`, + undefined, + signal, + ); + + if (!response.ok) { + throw await npanelError(response, `Could not delete ${hostname}`); + } +} diff --git a/src/lib/deploy/npanelMigration.test.ts b/src/lib/deploy/npanelMigration.test.ts index e47f329d..8748d432 100644 --- a/src/lib/deploy/npanelMigration.test.ts +++ b/src/lib/deploy/npanelMigration.test.ts @@ -3,11 +3,14 @@ import type { NostrEvent } from '@nostrify/nostrify'; import type { NpanelClaim } from './npanelApi'; import { NAMED_SITE_KIND, + ROOT_SITE_KIND, hasArchiveTitle, isServableHostname, + nsitePreviewUrl, planClaim, republishTags, retitleTags, + sitePreviewUrl, } from './npanelMigration'; const PUBKEY = 'a'.repeat(64); @@ -95,6 +98,54 @@ describe('isServableHostname', () => { }); }); +describe('nsitePreviewUrl', () => { + it('addresses a named site by its base36 pubkey and identifier', () => { + expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:mysite`)).toMatch(/^https:\/\/[0-9a-z]{50}mysite\.nsite\.lol$/); + }); + + it('addresses a root site by its npub', () => { + expect(nsitePreviewUrl(`${ROOT_SITE_KIND}:${ARCHIVE}:`)).toMatch(/^https:\/\/npub1[0-9a-z]+\.nsite\.lol$/); + }); + + it('has nowhere to send an identifier that will not fit a DNS label', () => { + // About a quarter of what this migration carries: the host it came from + // named sites after projects and never had to fit one in a subdomain. + expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`)).toBeUndefined(); + // Uppercase resolves as a DNS label and then matches no `d` tag, which is + // worse than no link at all. + expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:ErrorTime`)).toBeUndefined(); + }); + + it('says nothing about an address it cannot read', () => { + expect(nsitePreviewUrl(null)).toBeUndefined(); + expect(nsitePreviewUrl(undefined)).toBeUndefined(); + expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:not-a-pubkey:mysite`)).toBeUndefined(); + expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:`)).toBeUndefined(); + }); +}); + +describe('sitePreviewUrl', () => { + it('prefers the address, which outlives both the name and its certificate', () => { + expect(sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:mysite`, 'mysite.shakespeare.wtf', DOMAIN)).toMatch( + /\.nsite\.lol$/, + ); + }); + + it('falls back to the hostname when no gateway label can hold the identifier', () => { + expect( + sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`, 'long.shakespeare.wtf', DOMAIN), + ).toBe('https://long.shakespeare.wtf'); + }); + + it('offers nothing for a name that is neither servable nor addressable', () => { + // A link to a certificate error is worse than no button. + expect(sitePreviewUrl(null, 'a.b.shakespeare.wtf', DOMAIN)).toBeUndefined(); + expect( + sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`, 'a.b.shakespeare.wtf', DOMAIN), + ).toBeUndefined(); + }); +}); + describe('republishTags', () => { it('keeps the files and where to fetch them, and takes the archive’s words', () => { const manifest = claim().manifest; diff --git a/src/lib/deploy/npanelMigration.ts b/src/lib/deploy/npanelMigration.ts index 64bf462d..96f3c175 100644 --- a/src/lib/deploy/npanelMigration.ts +++ b/src/lib/deploy/npanelMigration.ts @@ -1,9 +1,26 @@ +import { nip19 } from 'nostr-tools'; import type { NostrEvent } from '@nostrify/nostrify'; +import { buildNsiteUrl, isValidDTag } from '@/lib/utils/nsite'; import type { NpanelClaim, NpanelClaimManifest } from './npanelApi'; /** nsite named-site kind. Everything a gateway archived is one of these. */ export const NAMED_SITE_KIND = 35128; +/** nsite root-site kind. One per key, which is why one is never republished. */ +export const ROOT_SITE_KIND = 15128; + +/** + * A gateway that serves any nsite from its address alone. + * + * Not this gateway, deliberately. Everything in this list is a decision about a + * site somebody has not looked at in a year, and the honest way to show them one + * is from an address rather than from the name that is in question — a name + * about to be deleted, or one that no certificate covers and that has therefore + * never loaded for anyone. It reads the same relays this provider publishes to, + * so the archive's copy is as findable there as anywhere. + */ +const PREVIEW_GATEWAY = 'nsite.lol'; + /** * Tags the archive wrote about itself, which are not the site's to carry. * @@ -60,6 +77,59 @@ export function isServableHostname(hostname: string, domain: string): boolean { return label.length > 0 && !label.includes('.'); } +/** + * Somewhere the site at an address can actually be looked at. + * + * Preferred over the hostname because a preview is worth most for the names the + * hostname cannot show: one too deep for a wildcard certificate, which answers a + * TLS error and always has, and one about to be deleted, which will stop + * answering at all. An address survives both. + * + * Undefined when the identifier is longer than a DNS label leaves room for — + * about a quarter of what this migration carries, because the host it came from + * named sites after projects and never had to fit one in a subdomain. There is + * no address-based URL for those on any gateway, so callers fall back to the + * hostname where the hostname works. + */ +export function nsitePreviewUrl(address: string | null | undefined): string | undefined { + if (!address) return undefined; + + const [kind, pubkey, ...rest] = address.split(':'); + const identifier = rest.join(':'); + + if (!/^[0-9a-f]{64}$/i.test(pubkey ?? '')) return undefined; + + if (Number(kind) === ROOT_SITE_KIND && !identifier) { + return buildNsiteUrl({ pubkeyHex: pubkey, npub: nip19.npubEncode(pubkey), gateway: PREVIEW_GATEWAY }); + } + + if (Number(kind) === NAMED_SITE_KIND && isValidDTag(identifier)) { + return buildNsiteUrl({ + pubkeyHex: pubkey, + npub: nip19.npubEncode(pubkey), + gateway: PREVIEW_GATEWAY, + siteIdentifier: identifier, + }); + } + + return undefined; +} + +/** + * Where to send somebody who wants to see a site before deciding about it. + * + * {@link nsitePreviewUrl} first, the hostname second, and nothing at all for a + * name that is both unservable and unaddressable — which is a real combination + * here, and better shown as no button than as a link to a certificate error. + */ +export function sitePreviewUrl( + address: string | null | undefined, + hostname: string, + domain: string, +): string | undefined { + return nsitePreviewUrl(address) ?? (isServableHostname(hostname, domain) ? `https://${hostname}` : undefined); +} + /** * Decide how a single waiting name gets back to its owner. *