mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +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
@@ -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]),
|
||||
];
|
||||
}
|
||||
Reference in new issue
Block a user