Give a name back under the title its site chose, and say which relays took it

Three things the migration got wrong, all of them the same shape: something was
known and not said.

The archive titled every site it carried after the site's hostname, because an
address was all it knew about a site it had only ever seen at one. Handing that
back hands back an address where a name should be — a site called "Arguable"
comes home titled "arguable.shakespeare.wtf". The gateway can now read the name
the site was carrying all along, out of its webmanifest or the metadata it
publishes for link previews, and that is what gets signed. A site that never
said what it is called gets no title, which is what a manifest without one has
always meant. Its `alt` goes too: it says the site is archived so that it keeps
working, which is a true sentence about the archive and stops being true here.

Names already taken back are listed and fixed the same way, rebuilt from the
event as relays hold it rather than from the gateway's copy — a site redeployed
since the migration ran has moved on, and rebuilding it from what the gateway
fetched would quietly restore an older version of it.

Publishing to relays went through a pool that resolves on the first acceptance
and discards every other answer, so a manifest that reached one relay out of
five was reported exactly like one that reached all five, and the reasons the
other four refused were received and thrown away. Of 102 manifests published
this way in one sitting, one relay held every one and another held none, and
nothing anywhere said so. Every relay is now published to on its own and
reported on by name. One acceptance is still a success — the event exists and
whoever reads that relay will find it — so this is a note, not a failure.

The gaps that leaves are closed without signing anything: the events go out
again exactly as they are, ids and signatures unchanged, to the relays whose own
answer says they are missing them. A relay that already has one says duplicate
and nothing happens; a relay that refused before finally says why, which is the
only way to hear a reason that was discarded at the time.

Ordinary nsite deploys published the same blind way, so they use the same
helper and carry the same coverage.

Lastly, names more than one label under the gateway's domain are refused rather
than published for. A wildcard certificate covers one label, so `a.b.example.com`
can be claimed, published for, and will still fail its handshake for everyone
forever. Five are on file, inherited from a host that accepted them; one already
has a manifest published for it, which can now be retracted.
This commit is contained in:
Alex Gleason committed 2026-09-13 16:40:33 -05:00
1 parent cb5561ba69
commit d06b9235a8
8 files changed
+997 -102

No files matched your search

+282 -63
View File
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import { AlertCircle, Check, ExternalLink, Loader2, Rocket } from 'lucide-react';
import { AlertCircle, Check, ExternalLink, Loader2, Rocket, Trash2 } from 'lucide-react';
import {
Dialog,
DialogContent,
@@ -14,23 +14,25 @@ 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 } from '@/hooks/useNpanelClaims';
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 } from '@/lib/deploy/npanelMigration';
import { cn } from '@/lib/utils';
/** How long a manifest is given to reach the relays. */
const PUBLISH_TIMEOUT_MS = 10_000;
import { NAMED_SITE_KIND, republishTags, retitleTags } from '@/lib/deploy/npanelMigration';
import { checkRelayCoverage, forwardMissing, host, publishToRelays } from '@/lib/deploy/publishToRelays';
/** Where a single name has got to. */
type RowStatus =
| { kind: 'waiting' }
| { kind: 'publishing' }
| { kind: 'claiming' }
| { kind: 'done' }
| { kind: 'done'; partial?: string }
| { kind: 'failed'; error: string };
/** What the last coverage run found, as a sentence per relay. */
interface CoverageReport {
lines: string[];
}
interface NpanelMigrationDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -50,17 +52,30 @@ function describeStep(claim: NpanelClaimPlan): string {
}
}
/** "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;
const total = accepted.length + rejected.length;
return `${accepted.length} of ${total} relays took it — ${host(rejected[0].url)}: ${rejected[0].reason}`;
}
export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMigrationDialogProps) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
const queryClient = useQueryClient();
const { data: claims, isLoading, error } = useNpanelClaims(open ? provider : undefined);
const { data, isLoading, error } = useNpanelClaims(open ? provider : undefined);
const [statuses, setStatuses] = useState<Record<string, RowStatus>>({});
const [running, setRunning] = useState(false);
const [running, setRunning] = useState<null | 'migrate' | 'titles' | 'coverage'>(null);
const [coverage, setCoverage] = useState<CoverageReport | null>(null);
const claims = data?.waiting ?? [];
const actionable = claims.filter((claim) => claim.step.kind !== 'blocked');
const blocked = claims.filter((claim) => claim.step.kind === 'blocked');
const retitlable = (data?.taken ?? []).filter((site) => site.needsTitle && !site.stray);
const strays = (data?.taken ?? []).filter((site) => site.stray);
const actionable = (claims ?? []).filter((claim) => claim.step.kind !== 'blocked');
const blocked = (claims ?? []).filter((claim) => claim.step.kind === 'blocked');
const done = Object.values(statuses).filter((status) => status.kind === 'done').length;
const failed = Object.values(statuses).filter((status) => status.kind === 'failed').length;
@@ -79,6 +94,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
if (!user || claim.step.kind === 'blocked') return;
let address: string;
let note: string | undefined;
if (claim.step.kind === 'republish') {
setStatus(claim.hostname, { kind: 'publishing' });
@@ -87,12 +103,14 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
kind: NAMED_SITE_KIND,
content: claim.step.manifest.content,
created_at: Math.floor(Date.now() / 1000),
tags: republishTags(claim.step.manifest, claim.step.identifier, provider.relayUrls),
tags: republishTags(claim.step.manifest, claim.step.identifier, provider.relayUrls, {
title: claim.suggestedTitle,
description: claim.suggestedDescription,
}),
});
await nostr
.group(provider.relayUrls)
.event(event, { signal: AbortSignal.timeout(PUBLISH_TIMEOUT_MS) });
const published = await publishToRelays(nostr, event, provider.relayUrls);
note = coverageNote(published.accepted, published.rejected);
address = `${NAMED_SITE_KIND}:${user.pubkey}:${claim.step.identifier}`;
} else {
@@ -101,35 +119,141 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
setStatus(claim.hostname, { kind: 'claiming' });
await claimNpanelHostname(provider.dashboardHost, user.signer, claim.hostname, address);
setStatus(claim.hostname, { kind: 'done' });
setStatus(claim.hostname, { kind: 'done', partial: note });
};
const migrateAll = async () => {
setRunning(true);
/** Republish one already-claimed site under the name it chose for itself. */
const retitle = async (site: NpanelTakenSite): Promise<void> => {
if (!user) return;
// One at a time: a remote signer answers one request at a time anyway, and
// a failure halfway through should leave a list somebody can read rather
// than a hundred simultaneous errors.
for (const claim of actionable) {
if (statuses[claim.hostname]?.kind === 'done') continue;
setStatus(site.hostname, { kind: 'publishing' });
const event = await user.signer.signEvent({
kind: site.event.kind,
content: site.event.content,
created_at: Math.floor(Date.now() / 1000),
tags: retitleTags(site.event, {
title: site.suggestedTitle,
description: site.suggestedDescription,
}),
});
const published = await publishToRelays(nostr, event, provider.relayUrls);
setStatus(site.hostname, {
kind: 'done',
partial: coverageNote(published.accepted, published.rejected),
});
};
/** Ask a relay to forget a manifest that was published for an unusable name. */
const removeStray = async (site: NpanelTakenSite): Promise<void> => {
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)],
],
});
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',
});
}
};
/** Run `action` over `rows`, one at a time, recording failures per row. */
const runEach = async <T,>(
rows: T[],
key: (row: T) => string,
action: (row: T) => Promise<void>,
): Promise<void> => {
for (const row of rows) {
if (statuses[key(row)]?.kind === 'done') continue;
try {
await migrate(claim);
await action(row);
} catch (err) {
setStatus(claim.hostname, {
setStatus(key(row), {
kind: 'failed',
error: err instanceof Error ? err.message : 'Failed',
});
}
}
};
setRunning(false);
const migrateAll = async () => {
setRunning('migrate');
// One at a time: a remote signer answers one request at a time anyway, and
// a failure halfway through should leave a list somebody can read rather
// than a hundred simultaneous errors.
await runEach(actionable, (claim) => claim.hostname, migrate);
setRunning(null);
// Whatever succeeded is no longer waiting, and whatever failed still is.
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
};
const renderStatus = (claim: NpanelClaimPlan) => {
const status = statuses[claim.hostname] ?? { kind: 'waiting' as const };
const fixTitles = async () => {
setRunning('titles');
await runEach(retitlable, (site) => site.hostname, retitle);
setRunning(null);
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
};
/**
* Fill in the relays that are missing these manifests.
*
* Costs no signatures: the events go out exactly as they are, ids and
* signatures unchanged, so a relay that already has one says `duplicate:`
* and a relay that refused before says why.
*/
const fixCoverage = async () => {
const events = data?.events ?? [];
if (!events.length) return;
setRunning('coverage');
setCoverage(null);
try {
const found = await checkRelayCoverage(
nostr,
provider.relayUrls,
events.map((event) => event.id),
);
const result = await forwardMissing(nostr, found, events);
const lines = found.map((relay) => {
const had = relay.present.size;
const sent = result.filled.get(relay.url) ?? 0;
const why = result.refused.get(relay.url);
if (why) return `${host(relay.url)}: had ${had} of ${events.length}, refused the rest — ${why}`;
if (sent) return `${host(relay.url)}: had ${had} of ${events.length}, sent ${sent} more`;
return `${host(relay.url)}: has all ${events.length}`;
});
setCoverage({ lines });
} catch (err) {
setCoverage({ lines: [err instanceof Error ? err.message : 'Could not check relay coverage.'] });
}
setRunning(null);
};
const renderStatus = (hostname: string, fallback: string) => {
const status = statuses[hostname] ?? { kind: 'waiting' as const };
switch (status.kind) {
case 'publishing':
@@ -146,24 +270,33 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
);
case 'done':
return (
<a
href={`https://${claim.hostname}`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
>
<Check className="h-3 w-3" /> Yours <ExternalLink className="h-3 w-3" />
</a>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Check className="h-3 w-3 shrink-0" />
{status.partial ? (
<span>{status.partial}</span>
) : (
<a
href={`https://${hostname}`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 hover:text-foreground"
>
Yours <ExternalLink className="h-3 w-3" />
</a>
)}
</span>
);
case 'failed':
return <span className="text-xs text-destructive">{status.error}</span>;
case 'waiting':
return <span className="text-xs text-muted-foreground">{describeStep(claim)}</span>;
return <span className="text-xs text-muted-foreground">{fallback}</span>;
}
};
const busy = running !== null;
return (
<Dialog open={open} onOpenChange={running ? undefined : onOpenChange}>
<Dialog open={open} onOpenChange={busy ? undefined : onOpenChange}>
<DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader className="shrink-0">
<DialogTitle>Take back your sites</DialogTitle>
@@ -173,7 +306,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto space-y-4 py-2">
<div className="flex-1 overflow-y-auto space-y-6 py-2">
{isLoading && (
<div className="space-y-2">
<Skeleton className="h-12 w-full" />
@@ -189,32 +322,118 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
</Alert>
)}
{claims && claims.length === 0 && (
{data && !claims.length && !data.taken.length && (
<p className="text-sm text-muted-foreground py-8 text-center">
Nothing is waiting for you here.
</p>
)}
{actionable.length > 0 && (
<div className="rounded-md border divide-y">
{actionable.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim)}</div>
<div className="space-y-2">
<h4 className="text-sm font-medium">Waiting for you</h4>
<div className="rounded-md border divide-y">
{actionable.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
</div>
<span className="shrink-0 text-xs rounded-full px-2 py-0.5 border text-muted-foreground">
{claim.step.kind === 'republish' ? 'republish' : 'claim'}
</span>
</div>
<span
className={cn(
'shrink-0 text-xs rounded-full px-2 py-0.5 border',
claim.step.kind === 'republish'
? 'text-muted-foreground'
: 'text-muted-foreground border-dashed',
)}
>
{claim.step.kind === 'republish' ? 'republish' : 'claim'}
</span>
))}
</div>
</div>
)}
{retitlable.length > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Titled after their address</h4>
<p className="text-xs text-muted-foreground">
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.
</p>
</div>
))}
<Button size="sm" variant="outline" onClick={fixTitles} disabled={busy}>
{running === 'titles' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Fix titles'}
</Button>
</div>
<div className="rounded-md border divide-y">
{retitlable.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.',
)}
</div>
</div>
</div>
))}
</div>
</div>
)}
{(data?.events.length ?? 0) > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Relay coverage</h4>
<p className="text-xs text-muted-foreground">
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.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixCoverage} disabled={busy}>
{running === 'coverage' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Check relays'}
</Button>
</div>
{coverage && (
<div className="rounded-md border bg-muted/30 p-3 space-y-1">
{coverage.lines.map((line) => (
<p key={line} className="text-xs font-mono text-muted-foreground break-words">
{line}
</p>
))}
</div>
)}
</div>
)}
{strays.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Published for a name that cannot load</h4>
<div className="rounded-md border border-dashed divide-y">
{strays.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0 space-y-0.5">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
`No certificate covers a name this deep under ${provider.domain}.`,
)}
</div>
</div>
<Button
size="sm"
variant="ghost"
className="shrink-0"
onClick={() => removeStray(site)}
disabled={busy}
>
<Trash2 className="h-4 w-4 mr-1.5" />
Retract
</Button>
</div>
))}
</div>
</div>
)}
@@ -236,17 +455,17 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
<DialogFooter className="shrink-0 gap-2 sm:justify-between items-center">
<span className="text-xs text-muted-foreground">
{failed > 0
? `${done} of ${actionable.length} done, ${failed} failed — run it again to retry.`
? `${done} done, ${failed} failed — run it again to retry.`
: done > 0
? `${done} of ${actionable.length} done. A republished site takes the gateway about a minute to pick up.`
? `${done} done. A republished site takes the gateway about a minute to pick up.`
: `${actionable.length} to migrate.`}
</span>
<div className="flex gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={running}>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
Close
</Button>
<Button onClick={migrateAll} disabled={running || actionable.length === 0}>
{running ? (
<Button onClick={migrateAll} disabled={busy || actionable.length === 0}>
{running === 'migrate' ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Migrating…
+92 -20
View File
@@ -1,35 +1,74 @@
import { useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
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';
import {
NAMED_SITE_KIND,
hasArchiveTitle,
isServableHostname,
manifestIdentifier,
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;
const RELAY_TIMEOUT_MS = 6_000;
/** A waiting name, with what it would take to get it back. */
export interface NpanelClaimPlan extends NpanelClaim {
step: MigrationStep;
}
/** A name already taken back, and the event currently serving it. */
export interface NpanelTakenSite {
hostname: string;
/** The claimant's own manifest, as relays hold it right now. */
event: NostrEvent;
/** What the site calls itself, per the gateway. Null when it never said. */
suggestedTitle: string | null;
suggestedDescription: string | null;
/** Whether the event is still titled after its hostname. */
needsTitle: boolean;
/** A name no certificate can cover, which should never have been published. */
stray: boolean;
}
export interface NpanelClaims {
/** Names still waiting, each with a plan. */
waiting: NpanelClaimPlan[];
/** Names already taken back whose manifest could be improved or removed. */
taken: NpanelTakenSite[];
/** Every event of the user's this query saw, for checking relay coverage. */
events: NostrEvent[];
}
/** The `identifier` half of a `kind:pubkey:identifier` address. */
function addressIdentifier(address: string): string {
return address.split(':').slice(2).join(':');
}
/** 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] ?? '';
}
/**
* 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.
* Half 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. The same query answers
* two more questions at no extra cost — which taken names are still titled
* after their hostname, and which of them should never have been published at
* all — so it is made once and its events are kept.
*/
export function useNpanelClaims(provider: NpanelProvider | undefined) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery<NpanelClaimPlan[]>({
return useQuery<NpanelClaims>({
queryKey: ['npanel-claims', provider?.dashboardHost, user?.pubkey],
enabled: Boolean(provider && user),
// Nobody's list of waiting names changes on its own, and every refetch
@@ -38,19 +77,21 @@ export function useNpanelClaims(provider: NpanelProvider | undefined) {
refetchOnWindowFocus: false,
retry: false,
queryFn: async ({ signal }) => {
if (!provider || !user) return [];
const empty: NpanelClaims = { waiting: [], taken: [], events: [] };
if (!provider || !user) return empty;
const claims = await fetchNpanelClaims(provider.dashboardHost, user.signer, signal);
if (!claims.length) return [];
const claims = await fetchNpanelClaims(provider.dashboardHost, user.signer, signal, { taken: true });
if (!claims.length) return empty;
// Only the names actually in play are asked about, rather than every
// site this key has ever published.
const wanted = new Set<string>();
for (const claim of claims) {
const identifier = claim.manifest?.tags.find(([name]) => name === 'd')?.[1];
const identifier = claim.manifest ? manifestIdentifier(claim.manifest) : '';
if (identifier) wanted.add(identifier);
if (claim.mine && claim.address) wanted.add(addressIdentifier(claim.address));
if (claim.address) wanted.add(addressIdentifier(claim.address));
}
wanted.delete('');
const events = wanted.size
? await nostr.group(provider.relayUrls).query(
@@ -59,16 +100,19 @@ export function useNpanelClaims(provider: NpanelProvider | undefined) {
)
: [];
const published = new Set(
events
.map((event) => event.tags.find(([name]) => name === 'd')?.[1])
.filter((identifier): identifier is string => Boolean(identifier)),
);
const byIdentifier = new Map<string, NostrEvent>();
for (const event of events) {
const identifier = eventIdentifier(event);
if (!identifier) continue;
const seen = byIdentifier.get(identifier);
if (!seen || seen.created_at < event.created_at) byIdentifier.set(identifier, event);
}
const published = new Set(byIdentifier.keys());
// 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.
// published, so relays that know nothing about any of them 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 ?? ''))
@@ -80,7 +124,35 @@ export function useNpanelClaims(provider: NpanelProvider | undefined) {
);
}
return claims.map((claim) => ({ ...claim, step: planClaim(claim, user.pubkey, published) }));
const waiting: NpanelClaimPlan[] = [];
const taken: NpanelTakenSite[] = [];
for (const claim of claims) {
if (!claim.claimed) {
waiting.push({ ...claim, step: planClaim(claim, user.pubkey, published, provider.domain) });
continue;
}
const identifier = claim.address ? addressIdentifier(claim.address) : '';
const event = identifier ? byIdentifier.get(identifier) : undefined;
// A claimed name whose event no relay answered with is not a name with
// nothing wrong; it is a name nothing can be said about. Leaving it out
// is the only option that cannot make it worse.
if (!event) continue;
const stray = !isServableHostname(claim.hostname, provider.domain);
taken.push({
hostname: claim.hostname,
event,
suggestedTitle: claim.suggestedTitle ?? null,
suggestedDescription: claim.suggestedDescription ?? null,
needsTitle: hasArchiveTitle(event, claim.hostname),
stray,
});
}
return { waiting, taken, events: [...byIdentifier.values()] };
},
});
}
+9 -4
View File
@@ -4,6 +4,7 @@ import { nip19 } from 'nostr-tools';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
import { buildNsiteUrl } from '../utils/nsite';
import { publishToRelays } from './publishToRelays';
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
const NSITE_ROOT_SITE_KIND = 15128;
@@ -296,9 +297,6 @@ export class NsiteAdapter implements DeployAdapter {
const pubkey = await this.signer.getPublicKey();
const npub = nip19.npubEncode(pubkey);
// Create grouped relay client
const relayClient = this.nostr.group(this.relayUrls);
// ── Step 1: Walk dist/ and read + hash all files ──────────────────────────
const files: FileEntry[] = [];
await this.collectFiles(distPath, '', files);
@@ -403,7 +401,11 @@ export class NsiteAdapter implements DeployAdapter {
// ── Step 5: Publish manifest ──────────────────────────────────────────────
// Relay and server hints are embedded as tags in the manifest itself —
// no separate kind 10002 or kind 10063 events are published.
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
//
// Relay by relay, because the site is only as findable as the relays that
// actually took it, and publishing to the group as a whole reports success
// the moment one of them does — throwing away what the others said.
const publish = await publishToRelays(this.nostr, manifestEvent, this.relayUrls);
// Build the canonical deployed URL (always the long-form base36 or npub URL)
const siteUrl = buildNsiteUrl({
@@ -433,6 +435,9 @@ export class NsiteAdapter implements DeployAdapter {
manifestKind,
vanityUrl,
canonicalUrl: siteUrl,
eventId: manifestEvent.id,
relaysAccepted: publish.accepted,
relaysRejected: publish.rejected,
},
};
}
+19 -1
View File
@@ -73,6 +73,17 @@ export interface NpanelClaim {
mine: boolean;
/** The archive's copy, when there is one to republish. Null when `mine`. */
manifest: NpanelClaimManifest | null;
/**
* Whether this name has already been taken back.
*
* Absent from gateways that predate the field, which is why it is optional
* rather than assumed false: a list of waiting names is what `GET /api/claims`
* has always returned, so a missing flag means the row is waiting.
*/
claimed?: boolean;
/** What the site calls itself, where the gateway could work it out. */
suggestedTitle?: string | null;
suggestedDescription?: string | null;
}
/**
@@ -80,13 +91,20 @@ export interface NpanelClaim {
*
* Empty for anyone with nothing waiting, which is almost everyone — this is the
* residue of one migration, not a feature of the gateway.
*
* `taken` also returns names already claimed, which is how an app fixes
* something about how it claimed them. Older gateways ignore the parameter and
* answer with the waiting ones, which is a smaller answer rather than a wrong
* one.
*/
export async function fetchNpanelClaims(
dashboardHost: string,
signer: NostrSigner,
signal?: AbortSignal,
opts: { taken?: boolean } = {},
): Promise<NpanelClaim[]> {
const response = await npanelRequest(dashboardHost, signer, 'GET', '/api/claims', undefined, signal);
const path = opts.taken ? '/api/claims?taken=1' : '/api/claims';
const response = await npanelRequest(dashboardHost, signer, 'GET', path, undefined, signal);
if (!response.ok) {
throw await npanelError(response, 'Could not ask the gateway which names are waiting for you');
+101 -11
View File
@@ -1,9 +1,18 @@
import { describe, it, expect } from 'vitest';
import type { NostrEvent } from '@nostrify/nostrify';
import type { NpanelClaim } from './npanelApi';
import { NAMED_SITE_KIND, planClaim, republishTags } from './npanelMigration';
import {
NAMED_SITE_KIND,
hasArchiveTitle,
isServableHostname,
planClaim,
republishTags,
retitleTags,
} from './npanelMigration';
const PUBKEY = 'a'.repeat(64);
const ARCHIVE = 'b'.repeat(64);
const DOMAIN = 'shakespeare.wtf';
function claim(overrides: Partial<NpanelClaim> = {}): NpanelClaim {
return {
@@ -18,6 +27,7 @@ function claim(overrides: Partial<NpanelClaim> = {}): NpanelClaim {
tags: [
['d', 'mysite'],
['title', 'mysite.shakespeare.wtf'],
['alt', 'mysite.shakespeare.wtf — archived so that it keeps working.'],
['path', '/index.html', 'c'.repeat(64)],
['server', 'https://blossom.ditto.pub/'],
],
@@ -30,17 +40,15 @@ 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',
});
expect(
planClaim(claim({ mine: true, address, manifest: null }), PUBKEY, new Set(), DOMAIN),
).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({
expect(planClaim(claim(), PUBKEY, new Set(['mysite']), DOMAIN)).toEqual({
kind: 'claim',
address: `${NAMED_SITE_KIND}:${PUBKEY}:mysite`,
reason: 'published',
@@ -48,7 +56,7 @@ describe('planClaim', () => {
});
it('republishes the archived manifest when nothing is published under that name', () => {
const step = planClaim(claim(), PUBKEY, new Set(['something-else']));
const step = planClaim(claim(), PUBKEY, new Set(['something-else']), DOMAIN);
expect(step.kind).toBe('republish');
expect(step).toMatchObject({ identifier: 'mysite' });
@@ -57,18 +65,38 @@ describe('planClaim', () => {
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');
expect(planClaim(rooted, PUBKEY, new Set(), DOMAIN).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');
expect(planClaim(empty, PUBKEY, new Set(), DOMAIN).kind).toBe('blocked');
});
it('refuses a name no certificate can cover, however it got on the list', () => {
// A wildcard covers one label. The host this migration inherits from took
// these anyway, so five of them are on file and none can serve TLS.
const deep = claim({ hostname: 'webvoice.shakespeare.wtf.shakespeare.wtf', mine: true });
const step = planClaim(deep, PUBKEY, new Set(), DOMAIN);
expect(step.kind).toBe('blocked');
expect(step).toMatchObject({ reason: expect.stringContaining('certificate') });
});
});
describe('isServableHostname', () => {
it('accepts exactly one label under the domain', () => {
expect(isServableHostname('mysite.shakespeare.wtf', DOMAIN)).toBe(true);
expect(isServableHostname('My-Site.Shakespeare.WTF', DOMAIN)).toBe(true);
expect(isServableHostname('a.b.shakespeare.wtf', DOMAIN)).toBe(false);
expect(isServableHostname('shakespeare.wtf', DOMAIN)).toBe(false);
expect(isServableHostname('mysite.example.com', DOMAIN)).toBe(false);
});
});
describe('republishTags', () => {
it('keeps the files and where to fetch them, and takes the relay hints', () => {
it('keeps the files and where to fetch them, and takes the archive’s words', () => {
const manifest = claim().manifest;
if (!manifest) throw new Error('fixture has a manifest');
@@ -76,6 +104,7 @@ describe('republishTags', () => {
{ ...manifest, tags: [...manifest.tags, ['relay', 'wss://gone.example']] },
'mysite',
['wss://relay.ditto.pub'],
{ title: 'My Site', description: 'What it is for.' },
);
expect(tags[0]).toEqual(['d', 'mysite']);
@@ -84,5 +113,66 @@ describe('republishTags', () => {
expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']);
expect(tags).not.toContainEqual(['relay', 'wss://gone.example']);
expect(tags.filter(([name]) => name === 'd')).toHaveLength(1);
// The archive's title was the hostname and its `alt` says the site is
// archived, which stops being true the moment it comes home.
expect(tags).toContainEqual(['title', 'My Site']);
expect(tags).toContainEqual(['description', 'What it is for.']);
expect(tags.filter(([name]) => name === 'title')).toHaveLength(1);
expect(tags.some(([name]) => name === 'alt')).toBe(false);
});
it('leaves a site that never said what it is called untitled', () => {
const manifest = claim().manifest;
if (!manifest) throw new Error('fixture has a manifest');
// Roughly a third of these are shells that set their title from JavaScript.
// No title is what an nsite manifest without one has always meant, and is
// better than a domain wearing a name's clothes.
const tags = republishTags(manifest, 'mysite', [], {});
expect(tags.some(([name]) => name === 'title')).toBe(false);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
});
});
describe('retitleTags', () => {
it('swaps the archive’s words and passes everything else through', () => {
const event = {
id: 'e'.repeat(64),
pubkey: PUBKEY,
kind: NAMED_SITE_KIND,
created_at: 1,
content: '',
sig: '0'.repeat(128),
tags: [
['d', 'mysite'],
['title', 'mysite.shakespeare.wtf'],
['path', '/index.html', 'c'.repeat(64)],
['server', 'https://blossom.ditto.pub/'],
['relay', 'wss://relay.ditto.pub'],
],
} as NostrEvent;
const tags = retitleTags(event, { title: 'My Site' });
expect(tags).toContainEqual(['d', 'mysite']);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
// Built from the event as relays hold it, so a site redeployed since this
// migration ran keeps whatever it has become.
expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']);
expect(tags).toContainEqual(['title', 'My Site']);
expect(tags.filter(([name]) => name === 'title')).toHaveLength(1);
});
});
describe('hasArchiveTitle', () => {
const event = (title: string) =>
({ tags: [['d', 'mysite'], ['title', title]] }) as NostrEvent;
it('recognises a title that is really an address', () => {
expect(hasArchiveTitle(event('mysite.shakespeare.wtf'), 'mysite.shakespeare.wtf')).toBe(true);
expect(hasArchiveTitle(event('My Site'), 'mysite.shakespeare.wtf')).toBe(false);
expect(hasArchiveTitle({ tags: [] } as unknown as NostrEvent, 'mysite.shakespeare.wtf')).toBe(false);
});
});
+89 -3
View File
@@ -1,8 +1,19 @@
import type { NostrEvent } from '@nostrify/nostrify';
import type { NpanelClaim, NpanelClaimManifest } from './npanelApi';
/** nsite named-site kind. Everything a gateway archived is one of these. */
export const NAMED_SITE_KIND = 35128;
/**
* Tags the archive wrote about itself, which are not the site's to carry.
*
* The title it invented was the hostname, because that was all it knew, and the
* `alt` it wrote says the site is archived so that it keeps working — a true
* sentence about the archive that stops being true the moment its owner takes
* the name back.
*/
const ARCHIVE_TAGS = new Set(['title', 'description', 'alt']);
/**
* What taking one name back requires.
*
@@ -19,11 +30,36 @@ export type MigrationStep =
/** Nothing safe to do without a person deciding something first. */
| { kind: 'blocked'; reason: string };
/** What a site calls itself, when it says. */
export interface SiteIdentity {
title?: string | null;
description?: string | null;
}
/** 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] ?? '';
}
/**
* Whether a hostname is one label under the gateway's domain.
*
* The wildcard certificate a gateway serves covers exactly one label, so
* `a.b.example.com` can be pointed at a site, claimed, and published for, and
* will still fail its TLS handshake for everyone forever. The records exist
* because the host this migration inherits from accepted them; there is no
* point signing anything for one.
*/
export function isServableHostname(hostname: string, domain: string): boolean {
const suffix = `.${domain.toLowerCase()}`;
const name = hostname.toLowerCase();
if (!name.endsWith(suffix)) return false;
const label = name.slice(0, -suffix.length);
return label.length > 0 && !label.includes('.');
}
/**
* Decide how a single waiting name gets back to its owner.
*
@@ -37,7 +73,15 @@ export function planClaim(
claim: NpanelClaim,
pubkey: string,
published: ReadonlySet<string>,
domain: string,
): MigrationStep {
if (!isServableHostname(claim.hostname, domain)) {
return {
kind: 'blocked',
reason: `No certificate covers a name this deep under ${domain}, so it can never load.`,
};
}
// 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) {
@@ -88,20 +132,62 @@ export function planClaim(
* 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.
* What is not carried over is the archive's own writing. It titled every site
* after its hostname, which is an address wearing a name's clothes; the site's
* real name, where it has one, is `identity`. A site that never said what it is
* called gets no title, which is what an nsite manifest without one has always
* meant and is more honest than a domain.
*
* Relay hints are replaced for the same reason: the archive's say where the
* archive published, and this event is going somewhere else.
*/
export function republishTags(
manifest: NpanelClaimManifest,
identifier: string,
relayUrls: string[],
identity: SiteIdentity = {},
): string[][] {
const kept = manifest.tags.filter(([name]) => name !== 'd' && name !== 'relay' && name !== 'r');
const kept = manifest.tags.filter(
([name]) => name !== 'd' && name !== 'relay' && name !== 'r' && !ARCHIVE_TAGS.has(name),
);
return [
// First, as an addressable event's `d` tag should be.
['d', identifier],
...kept,
...describeTags(identity),
...relayUrls.map((url) => ['relay', url]),
];
}
/**
* The same event, with the name the site chose in place of the one it was given.
*
* Built from the event as it stands rather than from anything the gateway
* holds, because the two are not always the same thing: a site republished by
* this migration and then redeployed normally has moved on, and rebuilding it
* out of the gateway's copy would quietly restore an older version of the site.
* Everything but the archive's own words is passed through untouched.
*/
export function retitleTags(event: NostrEvent, identity: SiteIdentity): string[][] {
return [...event.tags.filter(([name]) => !ARCHIVE_TAGS.has(name)), ...describeTags(identity)];
}
/**
* Whether an event is still wearing the title the archive gave it.
*
* The archive had one thing to call a site it had only ever seen at an address,
* so a title that is the hostname is a title nobody chose.
*/
export function hasArchiveTitle(event: NostrEvent, hostname: string): boolean {
const title = event.tags.find(([name]) => name === 'title')?.[1];
return typeof title === 'string' && title.toLowerCase() === hostname.toLowerCase();
}
/** `title` and `description` tags, for whichever of them the site supplied. */
function describeTags(identity: SiteIdentity): string[][] {
const tags: string[][] = [];
if (identity.title) tags.push(['title', identity.title]);
if (identity.description) tags.push(['description', identity.description]);
return tags;
}
+180
View File
@@ -0,0 +1,180 @@
import { describe, it, expect, vi } from 'vitest';
import type { NostrEvent, NRelay } from '@nostrify/nostrify';
import { checkRelayCoverage, forwardMissing, publishToRelays, type RelayPool } from './publishToRelays';
const RELAYS = ['wss://a.example', 'wss://b.example', 'wss://c.example'];
function event(id: string): NostrEvent {
return {
id,
pubkey: 'a'.repeat(64),
kind: 35128,
created_at: 1,
content: '',
tags: [],
sig: '0'.repeat(128),
};
}
/**
* A pool whose relays answer however the test says.
*
* `verdicts` maps a relay URL to what it does with an event: `true` accepts,
* a string refuses with that reason. `holdings` is what each relay answers a
* query with.
*/
function pool(
verdicts: Record<string, true | string>,
holdings: Record<string, string[]> = {},
): RelayPool & { sent: Array<[string, string]> } {
const sent: Array<[string, string]> = [];
return {
sent,
group(urls: string[]): NRelay {
const url = urls[0];
return {
async event(e: NostrEvent) {
const verdict = verdicts[url];
if (verdict !== true) throw new Error(verdict ?? 'no such relay');
sent.push([url, e.id]);
},
async query() {
return (holdings[url] ?? []).map(event);
},
} as unknown as NRelay;
},
};
}
describe('publishToRelays', () => {
it('reports every relay separately, not just the first to answer', async () => {
// Nostrify's pool resolves on the first acceptance and discards the rest,
// which is how 97 manifests reached one relay and none reached another
// without anything saying so.
const relays = pool({
'wss://a.example': true,
'wss://b.example': 'blocked: kind 35128 is not accepted by this relay',
'wss://c.example': true,
});
const outcome = await publishToRelays(relays, event('f'.repeat(64)), RELAYS);
expect(outcome.accepted).toEqual(['wss://a.example', 'wss://c.example']);
expect(outcome.rejected).toEqual([
{ url: 'wss://b.example', reason: 'blocked: kind 35128 is not accepted by this relay' },
]);
});
it('is a success when one relay takes it', async () => {
const relays = pool({ 'wss://a.example': true, 'wss://b.example': 'no', 'wss://c.example': 'no' });
// The event exists, and a gateway reading the relay that has it will find
// it. Failing the deploy over the other two would be wrong about something
// the user can see working.
await expect(publishToRelays(relays, event('f'.repeat(64)), RELAYS)).resolves.toMatchObject({
accepted: ['wss://a.example'],
});
});
it('fails, with every reason, when nobody takes it', async () => {
const relays = pool({
'wss://a.example': 'blocked: rate limited',
'wss://b.example': 'invalid: bad signature',
'wss://c.example': 'error: down',
});
await expect(publishToRelays(relays, event('f'.repeat(64)), RELAYS)).rejects.toThrow(
/No relay accepted.*a\.example: blocked: rate limited.*b\.example: invalid: bad signature/s,
);
});
it('refuses to publish nowhere', async () => {
await expect(publishToRelays(pool({}), event('f'.repeat(64)), [])).rejects.toThrow(/No relays/);
});
});
describe('relay coverage', () => {
it('sends each relay only what it is missing, unchanged', async () => {
const events = [event('1'.repeat(64)), event('2'.repeat(64))];
const relays = pool(
{ 'wss://a.example': true, 'wss://b.example': true, 'wss://c.example': true },
{
'wss://a.example': [events[0].id, events[1].id],
'wss://b.example': [events[0].id],
'wss://c.example': [],
},
);
const coverage = await checkRelayCoverage(relays, RELAYS, events.map((e) => e.id));
expect(coverage.map((c) => c.present.size)).toEqual([2, 1, 0]);
const result = await forwardMissing(relays, coverage, events);
expect(result.filled.get('wss://a.example')).toBeUndefined();
expect(result.filled.get('wss://b.example')).toBe(1);
expect(result.filled.get('wss://c.example')).toBe(2);
// The same events, so no signer is involved and a second run is harmless.
expect(relays.sent).toEqual([
['wss://b.example', events[1].id],
['wss://c.example', events[0].id],
['wss://c.example', events[1].id],
]);
});
it('asks a refusing relay once and reports what it said', async () => {
const events = [event('1'.repeat(64)), event('2'.repeat(64)), event('3'.repeat(64))];
const relays = pool({ 'wss://a.example': 'blocked: not accepting these' }, { 'wss://a.example': [] });
const coverage = await checkRelayCoverage(relays, ['wss://a.example'], events.map((e) => e.id));
const result = await forwardMissing(relays, coverage, events);
// Three copies of one sentence is not more information than one.
expect(result.refused.get('wss://a.example')).toBe('blocked: not accepting these');
expect(relays.sent).toHaveLength(0);
});
it('tells a relay that cannot be reached apart from one holding nothing', async () => {
const relays: RelayPool = {
group: () =>
({
query: () => Promise.reject(new Error('connection refused')),
event: () => Promise.resolve(),
}) as unknown as NRelay,
};
const coverage = await checkRelayCoverage(relays, ['wss://a.example'], ['1'.repeat(64)]);
// One is a relay to send to, the other is a relay to try again later.
expect(coverage[0].error).toBe('connection refused');
expect(coverage[0].present.size).toBe(0);
});
it('calls a timeout silence rather than a verdict', async () => {
const relays: RelayPool = {
group: () =>
({
event: () => Promise.reject(new DOMException('aborted', 'TimeoutError')),
}) as unknown as NRelay,
};
await expect(publishToRelays(relays, event('f'.repeat(64)), ['wss://a.example'])).rejects.toThrow(
/no answer before the timeout/,
);
});
});
describe('NsiteAdapter integration point', () => {
it('passes the pool through without a group of its own', async () => {
// The adapter used to call `nostr.group(relays).event(...)`, whose
// Promise.any hid this entirely.
const relays = pool({ 'wss://a.example': true });
const spy = vi.spyOn(relays, 'group');
await publishToRelays(relays, event('f'.repeat(64)), ['wss://a.example']);
expect(spy).toHaveBeenCalledWith(['wss://a.example']);
});
});
+225
View File
@@ -0,0 +1,225 @@
import type { NostrEvent, NRelay } from '@nostrify/nostrify';
/** How long one relay is given to accept an event. */
const PUBLISH_TIMEOUT_MS = 10_000;
/** A relay that refused an event, and the sentence it refused with. */
export interface RelayRejection {
url: string;
/** The relay's own `OK false` message, or whatever went wrong instead. */
reason: string;
}
/** Which relays took an event and which did not. */
export interface PublishOutcome {
accepted: string[];
rejected: RelayRejection[];
}
/** A pool that can be narrowed to a single relay, which is all this needs. */
export interface RelayPool {
group(urls: string[]): NRelay;
}
/**
* Publish to every relay, and report what each one said.
*
* Nostrify's pool publishes with `Promise.any`, which resolves as soon as one
* relay accepts and discards every other answer — including the rejections.
* A deploy to five relays that only one accepted is reported as a success
* indistinguishable from a deploy all five took, and the reason the other four
* refused is received and thrown away.
*
* That is not a hypothetical difference. Of 102 manifests published this way in
* one session, one relay held all of them and another held none, and nothing
* anywhere said so.
*
* One acceptance is still a success — the event exists, and a gateway reading
* any relay that has it will find it — so this throws only when nobody took it.
* The rest is reported rather than raised, because a site published to four
* relays out of five is working, and a deploy that failed over it would be
* wrong about something the user can see.
*/
export async function publishToRelays(
pool: RelayPool,
event: NostrEvent,
relayUrls: string[],
signal?: AbortSignal,
): Promise<PublishOutcome> {
if (!relayUrls.length) {
throw new Error('No relays are configured to publish to.');
}
const results = await Promise.allSettled(
relayUrls.map((url) =>
// One relay per group, so a rejection can be attributed to the relay that
// made it. The pool shares the underlying connections either way.
pool.group([url]).event(event, {
signal: signal ?? AbortSignal.timeout(PUBLISH_TIMEOUT_MS),
}),
),
);
const accepted: string[] = [];
const rejected: RelayRejection[] = [];
results.forEach((result, index) => {
const url = relayUrls[index];
if (result.status === 'fulfilled') {
accepted.push(url);
} else {
rejected.push({ url, reason: describe(result.reason) });
}
});
if (!accepted.length) {
throw new Error(
`No relay accepted this event. ${rejected.map((r) => `${host(r.url)}: ${r.reason}`).join('; ')}`,
);
}
return { accepted, rejected };
}
/**
* A relay's refusal, in whatever form it arrived.
*
* Read by shape rather than by `instanceof`, because a timeout arrives as a
* `DOMException`, which is not an `Error` everywhere — and mistaking one for an
* object with nothing to say turns "this relay never answered" into "this relay
* refused", which are different facts about different things.
*/
function describe(reason: unknown): string {
if (typeof reason === 'string' && reason) return reason;
if (typeof reason !== 'object' || reason === null) return 'refused without saying why';
const { name, message } = reason as { name?: unknown; message?: unknown };
// An abort is our own deadline, not a verdict from the relay.
if (name === 'AbortError' || name === 'TimeoutError') return 'no answer before the timeout';
if (typeof message === 'string' && message) return message;
return typeof name === 'string' && name ? name : 'refused without saying why';
}
/** The hostname of a relay URL, for a message somebody has to read. */
export function host(url: string): string {
try {
return new URL(url).host;
} catch {
return url;
}
}
/** How many event ids are asked about in one filter. */
const COVERAGE_BATCH = 100;
/** How long one relay is given to say what it has. */
const COVERAGE_TIMEOUT_MS = 8_000;
/** Which of a set of events one relay holds. */
export interface RelayCoverage {
url: string;
/** Ids the relay answered with. */
present: Set<string>;
/** Set when the relay could not be asked at all, as opposed to answering "none". */
error?: string;
}
/**
* Ask each relay which of these events it already has.
*
* A relay that cannot be reached is reported as an error rather than as holding
* nothing, because the two call for opposite responses: one is a relay to send
* to, the other is a relay to try again later.
*/
export async function checkRelayCoverage(
pool: RelayPool,
relayUrls: string[],
eventIds: string[],
signal?: AbortSignal,
): Promise<RelayCoverage[]> {
const batches: string[][] = [];
for (let i = 0; i < eventIds.length; i += COVERAGE_BATCH) {
batches.push(eventIds.slice(i, i + COVERAGE_BATCH));
}
return await Promise.all(
relayUrls.map(async (url): Promise<RelayCoverage> => {
const present = new Set<string>();
try {
for (const ids of batches) {
const found = await pool.group([url]).query([{ ids, limit: ids.length }], {
signal: signal ?? AbortSignal.timeout(COVERAGE_TIMEOUT_MS),
});
for (const event of found) present.add(event.id);
}
} catch (error) {
return { url, present, error: describe(error) };
}
return { url, present };
}),
);
}
/** What forwarding a set of events to the relays missing them achieved. */
export interface ForwardResult {
/** Relay URL to the number of events it took that it did not have. */
filled: Map<string, number>;
/** Relay URL to why it would not take them, from the first refusal. */
refused: Map<string, string>;
}
/**
* Send events to the relays that do not have them, exactly as they are.
*
* The same events, ids and signatures unchanged, so this needs no signer and
* can be run as many times as it takes: a relay that already has one answers
* `duplicate:` and nothing happens. Publishing to five relays and having one
* take it is a success that leaves four gaps, and this is how the gaps close
* without anyone re-signing a hundred manifests.
*
* It is also the only way to read why a relay refused in the first place: the
* refusal is thrown away at publish time, and asking again is how you hear it.
*/
export async function forwardMissing(
pool: RelayPool,
coverage: RelayCoverage[],
events: NostrEvent[],
signal?: AbortSignal,
): Promise<ForwardResult> {
const filled = new Map<string, number>();
const refused = new Map<string, string>();
for (const relay of coverage) {
if (relay.error) {
refused.set(relay.url, relay.error);
continue;
}
const missing = events.filter((event) => !relay.present.has(event.id));
if (!missing.length) continue;
let count = 0;
for (const event of missing) {
try {
await pool.group([relay.url]).event(event, {
signal: signal ?? AbortSignal.timeout(PUBLISH_TIMEOUT_MS),
});
count++;
} catch (error) {
// One reason per relay: a relay refusing the first of ninety-seven
// will refuse the rest for the same reason, and ninety-seven copies of
// one sentence is not more information.
if (!refused.has(relay.url)) refused.set(relay.url, describe(error));
break;
}
}
if (count) filled.set(relay.url, count);
}
return { filled, refused };
}