Files
shakespeare/src/lib/deploy/NpanelAdapter.test.ts
T
Alex Gleason fc26a8b27b Deploy to the gateway that actually serves shakespeare.wtf now
Shakespeare Deploy uploaded a zip to a host that kept the files itself. That
host has been replaced: those domains are served out of nsite manifests, so a
deploy through the old API has been succeeding and changing nothing anyone can
see. This replaces it.

NpanelAdapter is NsiteAdapter plus a name. The site is an ordinary nsite under
the user's own key — same event, readable by any nsite client, gateway or no
gateway — and the second half of the deploy asks the gateway to point a hostname
at it. Its predecessor claimed names implicitly, by watching relays and
reserving whichever d tag it saw first; this one keeps an explicit row, which is
what makes a name something its owner holds rather than something they won a
race for. The hostname is asked about before it is claimed, because "nobody
holds this", "I already hold this" and "somebody else holds this" are three
different acts and creating-then-reading-the-409 cannot tell the last two apart.

The name field checks availability as you type, against an endpoint that takes
no credentials: somebody choosing a name has not decided to make an account yet.
A name this project already deployed to is not reported as taken — it is theirs.
An unreachable gateway reports available, because being wrong that way costs a
clear error at deploy time, and being wrong the other way tells someone a free
name is taken and they settle for worse.

Also fixes readDeploySettings, which swallowed a missing file and an unreadable
one alike and answered "no providers" to both. The default provider it was meant
to hand new users had therefore never reached anybody: it was written, saved
back as an empty list on the next render, and gone. The two cases are now
distinct, because inventing defaults for a file that exists but will not parse
would silently replace whatever the user had.

Providers and per-project deploy records saved under the old type are migrated
on load rather than dropped. The project file holds one record per provider a
project ever deployed to, so rejecting one entry would take a Netlify site id
and a Vercel project id with it.

Verified end to end against the live gateway: a fresh key self-enrolled,
uploaded a blob, published a manifest, claimed a name, and the site served
publicly with the SPA fallback working on a deep path.

The package-lock version bump is npm reconciling it with package.json, which
had drifted before this work.
2026-09-13 12:54:30 -05:00

226 lines
7.7 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { generateSecretKey, getPublicKey } from 'nostr-tools';
import type { NostrEvent, NostrSigner } from '@nostrify/nostrify';
import { NpanelAdapter, checkNameAvailable } from './NpanelAdapter';
import type { JSRuntimeFS } from '../JSRuntime';
const DASHBOARD_HOST = 'npanel.example.test';
const DOMAIN = 'example.test';
const secretKey = generateSecretKey();
const pubkey = getPublicKey(secretKey);
/**
* A signer that fills in the fields a real one would, without signing.
*
* Not a shortcut around something worth testing: the adapter never verifies a
* signature, it base64-encodes whatever it is handed, so what these tests are
* about is which tags end up on the event and where it gets sent. Signing for
* real is also not available here — jsdom's TextEncoder returns a Uint8Array
* from its own realm, which fails the `instanceof` check inside @noble/hashes,
* so nostr-tools cannot hash an event under this test environment at all.
*/
const signer: NostrSigner = {
getPublicKey: async () => pubkey,
signEvent: async (template) => ({
...template,
id: 'f'.repeat(64),
pubkey,
sig: '0'.repeat(128),
}),
} as NostrSigner;
/** Requests the adapter made, so a test can assert what it asked the gateway. */
interface Call {
method: string;
path: string;
body?: unknown;
auth: NostrEvent;
}
let calls: Call[] = [];
let fetchMock: ReturnType<typeof vi.fn>;
/**
* An adapter whose nsite half is stubbed out.
*
* Publishing the site is {@link NsiteAdapter}'s job and is covered where it
* lives; what is worth pinning down here is the second half — which requests
* the gateway gets, and what happens when it says no.
*/
function adapterWithStubbedSite(subdomain: string): NpanelAdapter {
const adapter = new NpanelAdapter({
fs: {} as JSRuntimeFS,
nostr: {} as never,
signer,
dashboardHost: DASHBOARD_HOST,
domain: DOMAIN,
subdomain,
gateway: DOMAIN,
relayUrls: [],
blossomServers: [],
});
const inner = (adapter as unknown as { nsite: { deploy: unknown } }).nsite;
inner.deploy = vi.fn(async () => ({
url: `https://base36.${DOMAIN}`,
metadata: { canonicalUrl: `https://base36.${DOMAIN}`, filesPublished: 3 },
}));
return adapter;
}
/** Respond to the adapter's requests in the order it makes them. */
function respondWith(...responses: Array<{ status: number; body?: unknown }>): void {
let index = 0;
fetchMock.mockImplementation(async (request: Request) => {
const header = request.headers.get('Authorization') ?? '';
const auth = JSON.parse(atob(header.replace(/^Nostr /, ''))) as NostrEvent;
const body = request.body ? await request.clone().json() : undefined;
calls.push({ method: request.method, path: new URL(request.url).pathname, body, auth });
const next = responses[index++] ?? { status: 500 };
return new Response(next.body === undefined ? null : JSON.stringify(next.body), {
status: next.status,
headers: { 'Content-Type': 'application/json' },
});
});
}
beforeEach(() => {
calls = [];
fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('NpanelAdapter', () => {
it('claims an unused name and returns the hostname it got', async () => {
respondWith({ status: 404, body: { error: 'Host not found.' } }, { status: 201, body: { host: {} } });
const result = await adapterWithStubbedSite('mysite').deploy({
projectId: 'p',
projectPath: '/projects/p',
});
expect(result.url).toBe(`https://mysite.${DOMAIN}`);
expect(calls.map((c) => `${c.method} ${c.path}`)).toEqual([
`GET /api/hosts/mysite.${DOMAIN}`,
'POST /api/hosts',
]);
// The site is served from a manifest that may not have every path, so the
// gateway has to be told to fall back to the shell rather than 404.
expect(calls[1].body).toMatchObject({
hostname: `mysite.${DOMAIN}`,
address: `35128:${pubkey}:mysite`,
spa: true,
});
});
it('signs each request for the URL it is sent to', async () => {
respondWith({ status: 404 }, { status: 201, body: { host: {} } });
await adapterWithStubbedSite('mysite').deploy({ projectId: 'p', projectPath: '/projects/p' });
for (const call of calls) {
const tag = (name: string) => call.auth.tags.find(([k]) => k === name)?.[1];
expect(call.auth.kind).toBe(27235);
expect(call.auth.pubkey).toBe(pubkey);
expect(tag('method')).toBe(call.method);
expect(tag('u')).toBe(`https://${DASHBOARD_HOST}${call.path}`);
}
});
it('leaves a name alone when it already points at this site', async () => {
respondWith({
status: 200,
body: { host: { address: `35128:${pubkey}:mysite` } },
});
await adapterWithStubbedSite('mysite').deploy({ projectId: 'p', projectPath: '/projects/p' });
// A redeploy is the common case; it should cost one read and no write.
expect(calls).toHaveLength(1);
expect(calls[0].method).toBe('GET');
});
it('repoints a name it holds that points somewhere else', async () => {
respondWith(
{ status: 200, body: { host: { address: '35128:someoneelse:mysite' } } },
{ status: 200, body: { host: {} } },
);
await adapterWithStubbedSite('mysite').deploy({ projectId: 'p', projectPath: '/projects/p' });
expect(calls[1].method).toBe('PATCH');
expect(calls[1].body).toEqual({ address: `35128:${pubkey}:mysite` });
});
it('says plainly when a name belongs to someone else', async () => {
respondWith({ status: 403, body: { error: "You don't have access to this host." } });
await expect(
adapterWithStubbedSite('taken').deploy({ projectId: 'p', projectPath: '/projects/p' }),
).rejects.toThrow(/belongs to someone else/);
});
it('says plainly when a name is claimed between the check and the claim', async () => {
respondWith({ status: 404 }, { status: 409, body: { error: 'already configured.' } });
await expect(
adapterWithStubbedSite('racy').deploy({ projectId: 'p', projectPath: '/projects/p' }),
).rejects.toThrow(/was just taken/);
});
it("passes on the gateway's own explanation of a refusal", async () => {
respondWith(
{ status: 404 },
{ status: 403, body: { error: 'You already have 25 sites here, which is the limit.' } },
);
await expect(
adapterWithStubbedSite('over-quota').deploy({ projectId: 'p', projectPath: '/projects/p' }),
).rejects.toThrow(/25 sites here/);
});
});
describe('checkNameAvailable', () => {
it('reports what the gateway says', async () => {
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
);
await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({
available: false,
reason: 'taken',
});
});
it('asks without credentials', async () => {
fetchMock.mockResolvedValue(new Response(JSON.stringify({ hostname: 'x', available: true })));
await checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe(`https://${DASHBOARD_HOST}/api/hosts/x.${DOMAIN}/available`);
expect((init as RequestInit | undefined)?.headers).toBeUndefined();
});
it('treats an unreachable gateway as available', async () => {
// Being wrong this way costs a clear error at deploy time. Being wrong the
// other way tells somebody a free name is taken and they settle for worse.
fetchMock.mockRejectedValue(new Error('offline'));
await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({
available: true,
});
});
});