mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Let people take back the sites they had before the gateway
The domains Shakespeare Deploy published to are now served by a gateway that took them over, and the sites already under those names had to keep working, so they were republished under an archive key rather than left to break. That key is not theirs. This is how it stops speaking for them: the gateway holds a record of who each name is waiting for, they publish their own copy of the site, and the name is repointed at it. All of it at once, because the person with one name to recover is not the person this is for. Doing it a site at a time through the deploy button would mean re-deploying a hundred projects, most of which are no longer checked out anywhere, to recover sites whose files the gateway already has. The list is only reached by asking, never on page load: finding out what is waiting costs a signature, and a signing prompt nobody asked for is worse than a button that sometimes opens an empty list. A name whose site was always published under its owner's key needs nothing republished — the record is the whole migration. The rest need the archived manifest signed again, which reproduces the site exactly, since a manifest is its tags and the blobs are addressed by hash and already sit where the server tags say. Publishing happens before claiming, so the name never points at an event the gateway has not fetched. What a name must never do is come back at the cost of a live one. Kind 35128 is addressable, so republishing an archived snapshot at a `d` tag someone already publishes under would replace the current site with an old copy of itself — which is not hypothetical: two of the first hundred names looked at were exactly that. Those are claimed straight to the site that already exists, so both names end up serving it. Working that out needs relays to answer, so silence from them is treated as silence and not as "publishes nothing": a user whose own sites the gateway is already serving must see at least those come back, or nothing is planned at all. Also fixes ProviderConfigDialog, which had grown a relay list and a server list and no height limit, and was pushing its own Save button off the bottom of the screen with no way to scroll to it.
This commit is contained in:
8 files changed
+715
-40
No files matched your search
@@ -79,8 +79,8 @@ export function ProviderConfigDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogContent className="max-w-md max-h-[90vh] flex flex-col">
|
||||
<DialogHeader className="shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={gatewayUrl || baseURL}
|
||||
@@ -94,7 +94,10 @@ export function ProviderConfigDialog({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 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. */}
|
||||
<div className="flex-1 overflow-y-auto space-y-4 py-4 px-1 -mx-1">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-name">
|
||||
Name <span className="text-destructive">*</span>
|
||||
@@ -303,7 +306,7 @@ export function ProviderConfigDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<DialogFooter className="gap-2 shrink-0">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/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 } 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;
|
||||
|
||||
/** Where a single name has got to. */
|
||||
type RowStatus =
|
||||
| { kind: 'waiting' }
|
||||
| { kind: 'publishing' }
|
||||
| { kind: 'claiming' }
|
||||
| { kind: 'done' }
|
||||
| { kind: 'failed'; error: string };
|
||||
|
||||
interface NpanelMigrationDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: NpanelProvider;
|
||||
}
|
||||
|
||||
function describeStep(claim: NpanelClaimPlan): string {
|
||||
switch (claim.step.kind) {
|
||||
case 'claim':
|
||||
return claim.step.reason === 'mine'
|
||||
? 'Already published under your key — only the record changes.'
|
||||
: 'You already publish a site under this name; the address will point at it.';
|
||||
case 'republish':
|
||||
return 'A copy will be published under your key, then the name repointed.';
|
||||
case 'blocked':
|
||||
return claim.step.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 [statuses, setStatuses] = useState<Record<string, RowStatus>>({});
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
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;
|
||||
|
||||
const setStatus = (hostname: string, status: RowStatus) => {
|
||||
setStatuses((previous) => ({ ...previous, [hostname]: status }));
|
||||
};
|
||||
|
||||
/**
|
||||
* Take back one name.
|
||||
*
|
||||
* Publish before claiming, always: a hostname pointed at an event the gateway
|
||||
* has never seen serves nothing until it catches up, and the order that gap
|
||||
* is smallest in is this one.
|
||||
*/
|
||||
const migrate = async (claim: NpanelClaimPlan): Promise<void> => {
|
||||
if (!user || claim.step.kind === 'blocked') return;
|
||||
|
||||
let address: string;
|
||||
|
||||
if (claim.step.kind === 'republish') {
|
||||
setStatus(claim.hostname, { kind: 'publishing' });
|
||||
|
||||
const event = await user.signer.signEvent({
|
||||
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),
|
||||
});
|
||||
|
||||
await nostr
|
||||
.group(provider.relayUrls)
|
||||
.event(event, { signal: AbortSignal.timeout(PUBLISH_TIMEOUT_MS) });
|
||||
|
||||
address = `${NAMED_SITE_KIND}:${user.pubkey}:${claim.step.identifier}`;
|
||||
} else {
|
||||
address = claim.step.address;
|
||||
}
|
||||
|
||||
setStatus(claim.hostname, { kind: 'claiming' });
|
||||
await claimNpanelHostname(provider.dashboardHost, user.signer, claim.hostname, address);
|
||||
setStatus(claim.hostname, { kind: 'done' });
|
||||
};
|
||||
|
||||
const migrateAll = async () => {
|
||||
setRunning(true);
|
||||
|
||||
// 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;
|
||||
|
||||
try {
|
||||
await migrate(claim);
|
||||
} catch (err) {
|
||||
setStatus(claim.hostname, {
|
||||
kind: 'failed',
|
||||
error: err instanceof Error ? err.message : 'Failed',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setRunning(false);
|
||||
// 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 };
|
||||
|
||||
switch (status.kind) {
|
||||
case 'publishing':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> Publishing…
|
||||
</span>
|
||||
);
|
||||
case 'claiming':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> Claiming…
|
||||
</span>
|
||||
);
|
||||
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>
|
||||
);
|
||||
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 (
|
||||
<Dialog open={open} onOpenChange={running ? undefined : onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
|
||||
<DialogHeader className="shrink-0">
|
||||
<DialogTitle>Take back your sites</DialogTitle>
|
||||
<DialogDescription>
|
||||
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.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto space-y-4 py-2">
|
||||
{isLoading && (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error.message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{claims && claims.length === 0 && (
|
||||
<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>
|
||||
<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>
|
||||
)}
|
||||
|
||||
{blocked.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Needs a decision</h4>
|
||||
<div className="rounded-md border border-dashed divide-y">
|
||||
{blocked.map((claim) => (
|
||||
<div key={claim.hostname} className="p-3 space-y-0.5">
|
||||
<div className="font-mono text-sm truncate">{claim.hostname}</div>
|
||||
<p className="text-xs text-muted-foreground">{describeStep(claim)}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<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 > 0
|
||||
? `${done} of ${actionable.length} 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}>
|
||||
Close
|
||||
</Button>
|
||||
<Button onClick={migrateAll} disabled={running || actionable.length === 0}>
|
||||
{running ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Migrating…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
{failed > 0 ? 'Retry' : `Migrate all (${actionable.length})`}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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<NpanelClaimPlan[]>({
|
||||
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<string>();
|
||||
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) }));
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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<Response> {
|
||||
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<Response> {
|
||||
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<Error> {
|
||||
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<Error> {
|
||||
return npanelError(response, fallback);
|
||||
}
|
||||
}
|
||||
@@ -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<Response> {
|
||||
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<Error> {
|
||||
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<NpanelClaim[]> {
|
||||
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<void> {
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
@@ -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> = {}): 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);
|
||||
});
|
||||
});
|
||||
@@ -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<string>,
|
||||
): 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]),
|
||||
];
|
||||
}
|
||||
@@ -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<PresetDeployProvider | null>(null);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
||||
const [migratingProvider, setMigratingProvider] = useState<NpanelProvider | null>(null);
|
||||
|
||||
// Drag and drop sensors
|
||||
const sensors = useSensors(
|
||||
@@ -341,6 +344,38 @@ export function DeploySettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 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' ? (
|
||||
<div
|
||||
key={`migrate-${provider.id}`}
|
||||
className="rounded-lg border border-dashed p-4 flex flex-wrap items-center justify-between gap-3"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<h4 className="text-sm font-medium">Sites from before {provider.name}</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Names you published on {provider.domain} under the old host are being served
|
||||
from an archive until you take them back.
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setMigratingProvider(provider)}>
|
||||
Take back sites
|
||||
</Button>
|
||||
</div>
|
||||
) : null
|
||||
))}
|
||||
|
||||
{migratingProvider && (
|
||||
<NpanelMigrationDialog
|
||||
open
|
||||
onOpenChange={(open) => !open && setMigratingProvider(null)}
|
||||
provider={migratingProvider}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Provider Config Dialog */}
|
||||
{selectedProviderIndex !== null && settings.providers[selectedProviderIndex] && (
|
||||
<ProviderConfigDialog
|
||||
|
||||
Reference in new issue
Block a user