diff --git a/src/components/deploy/DeploySteps.tsx b/src/components/deploy/DeploySteps.tsx index 2e0612fe..28c4912e 100644 --- a/src/components/deploy/DeploySteps.tsx +++ b/src/components/deploy/DeploySteps.tsx @@ -17,7 +17,8 @@ import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useGit } from '@/hooks/useGit'; import { NostrURI } from '@/lib/NostrURI'; import { Link } from 'react-router-dom'; -import type { DeployProvider } from '@/contexts/DeploySettingsContext'; +import type { DeployProvider, NpanelProvider } from '@/contexts/DeploySettingsContext'; +import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog'; import type { PresetDeployProvider } from '@/lib/deploy/types'; import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets'; import { NpanelDeployForm } from '@/components/deploy/NpanelDeployForm'; @@ -154,6 +155,24 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp const [deployResult, setDeployResult] = useState<{ url: string } | null>(null); const [error, setError] = useState(null); const [isNpanelFormValid, setIsNpanelFormValid] = useState(true); + /** + * The gateway whose held names are being looked at, if any. + * + * Owned here rather than by the name field, because what someone recognising + * one of their names wants is usually all of them, and because the dialog + * that hands them back outlives the field that prompted it. + */ + const [migratingProvider, setMigratingProvider] = useState(null); + + /** + * Whether the deploy failed because the gateway is holding the name for this + * user, which is a refusal with something to do about it. + * + * Read off the sentence npanel sent rather than a status code, since the 409 + * it arrives as also covers a name somebody else holds and a name that is + * simply configured already. + */ + const heldName = error !== null && /being held for you/i.test(error); // .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy const [nsiteVfsConfig, setNsiteVfsConfig] = useState(null); @@ -627,6 +646,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp onSiteTitleChange={handleNpanelSiteTitleChange} onSiteDescriptionChange={handleNpanelSiteDescriptionChange} onValidationChange={handleNpanelValidationChange} + onTakeBackSites={() => setMigratingProvider(npanelProvider)} /> ); } @@ -978,7 +998,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp {error && ( - {error} + +

{error}

+ {/* The gateway refuses a name it is holding for this user + and says to take it back instead. Saying so and leaving + them to find out where is the worst of both. */} + {heldName && selectedProvider?.type === 'npanel' && ( + + )} +
)} @@ -1015,6 +1050,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp )} )} + + {migratingProvider && ( + !open && setMigratingProvider(null)} + provider={migratingProvider} + /> + )} ); } diff --git a/src/components/deploy/NpanelDeployForm.tsx b/src/components/deploy/NpanelDeployForm.tsx index 53fae2c3..7ca25340 100644 --- a/src/components/deploy/NpanelDeployForm.tsx +++ b/src/components/deploy/NpanelDeployForm.tsx @@ -1,5 +1,6 @@ import { useState, useEffect, useRef, useCallback } from 'react'; import { AlertCircle, Check, Loader2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; @@ -24,12 +25,21 @@ interface NpanelDeployFormProps { onSiteTitleChange: (title: string) => void; onSiteDescriptionChange: (description: string) => void; onValidationChange?: (isValid: boolean) => void; + /** + * Open the list of names this gateway is holding for whoever signs in. + * + * Passed in rather than opened here: recognising one name is usually not the + * whole of what somebody has waiting, and the dialog that hands them all back + * belongs above this field rather than inside it. + */ + onTakeBackSites?: () => void; } /** What the field is currently saying about the name in it. */ type NameState = | { kind: 'empty' } | { kind: 'mine' } + | { kind: 'waiting' } | { kind: 'checking' } | { kind: 'free' } | { kind: 'unavailable'; message: string }; @@ -40,6 +50,11 @@ function describe(availability: NameAvailability, domain: string): NameState { // there rather than taking anything. if (availability.reason === 'mine') return { kind: 'mine' }; + // Theirs from before the gateway, and still held for them. Not somewhere + // they can deploy until they take it back, which is a thing they can do + // from here rather than a wall. + if (availability.reason === 'waiting') return { kind: 'waiting' }; + if (availability.available) return { kind: 'free' }; if (availability.reason === 'taken') { @@ -61,6 +76,7 @@ export function NpanelDeployForm({ onSiteTitleChange, onSiteDescriptionChange, onValidationChange, + onTakeBackSites, }: NpanelDeployFormProps) { const { user } = useCurrentUser(); const [subdomain, setSubdomain] = useState(savedSubdomain || projectId); @@ -134,7 +150,11 @@ export function NpanelDeployForm({ // A name still being checked stays deployable: the gateway decides for real // when the deploy runs, and blocking the button on an in-flight request would // make the form feel stuck on a slow connection. - const isValid = subdomain.trim() !== '' && nameState.kind !== 'unavailable'; + // A name still waiting is not one to deploy to: the gateway would refuse, + // because taking it back is what turns it into somewhere this user can + // publish. The field says so and offers the step rather than the refusal. + const isValid = + subdomain.trim() !== '' && nameState.kind !== 'unavailable' && nameState.kind !== 'waiting'; useEffect(() => { onValidationChange?.(isValid); @@ -194,6 +214,24 @@ export function NpanelDeployForm({

)} + {nameState.kind === 'waiting' && ( +
+

+ {subdomain.trim()}.{domain} is being held for you. +

+

+ You published it before {domain} moved to this gateway. It is being served from an + archive until you take it back, which publishes your own copy and points the name at + it. +

+ {onTakeBackSites && ( + + )} +
+ )} + {nameState.kind === 'unavailable' && (
diff --git a/src/hooks/useNpanelClaims.ts b/src/hooks/useNpanelClaims.ts index d95eedb5..4d87b490 100644 --- a/src/hooks/useNpanelClaims.ts +++ b/src/hooks/useNpanelClaims.ts @@ -3,7 +3,12 @@ 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 { + fetchNpanelClaimCount, + fetchNpanelClaims, + type NpanelClaim, + type NpanelClaimCount, +} from '@/lib/deploy/npanelApi'; import { NAMED_SITE_KIND, hasArchiveTitle, @@ -156,3 +161,32 @@ export function useNpanelClaims(provider: NpanelProvider | undefined) { }, }); } + +/** + * How many names a gateway is holding for the logged-in user. + * + * Separate from {@link useNpanelClaims} because it is asked at a different + * moment and must cost a different amount. That one runs when somebody opens + * the dialog and has already decided to look; it reads every claimed deploy on + * the gateway and queries relays for this user's own events. This one runs + * because a settings page was opened, so it is one signature and two counted + * rows, and a gateway that cannot answer it says nothing rather than failing. + */ +export function useNpanelClaimCount(provider: NpanelProvider | undefined) { + const { user } = useCurrentUser(); + + return useQuery({ + queryKey: ['npanel-claim-count', 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. Long + // enough that opening settings twice in a sitting asks once. + staleTime: 30 * 60 * 1000, + refetchOnWindowFocus: false, + retry: false, + queryFn: async ({ signal }) => { + if (!provider || !user) return { waiting: 0, taken: 0 }; + return await fetchNpanelClaimCount(provider.dashboardHost, user.signer, signal); + }, + }); +} diff --git a/src/lib/deploy/NpanelAdapter.test.ts b/src/lib/deploy/NpanelAdapter.test.ts index 0302d33d..29de2c4b 100644 --- a/src/lib/deploy/NpanelAdapter.test.ts +++ b/src/lib/deploy/NpanelAdapter.test.ts @@ -271,3 +271,32 @@ describe('checkNameAvailable', () => { ).resolves.toMatchObject({ available: false, reason: 'taken' }); }); }); + +describe('checkNameAvailable, for a name held for its previous owner', () => { + it('reports waiting rather than taken', async () => { + // The state almost every unclaimed name is in: an archive serving it, so + // the public answer is taken and the useful answer is that it is theirs. + fetchMock + .mockResolvedValueOnce( + new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })), + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'waiting' })), + ); + + await expect( + checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer), + ).resolves.toMatchObject({ available: false, reason: 'waiting' }); + }); + + it('says nothing more to somebody who did not sign', async () => { + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })), + ); + + await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({ + reason: 'taken', + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/lib/deploy/NpanelAdapter.ts b/src/lib/deploy/NpanelAdapter.ts index 88d8c561..17651b35 100644 --- a/src/lib/deploy/NpanelAdapter.ts +++ b/src/lib/deploy/NpanelAdapter.ts @@ -12,11 +12,16 @@ export interface NameAvailability { available: boolean; /** * Why it is not free, or — with `available` — that it is not free of somebody - * else. `mine` comes only from a signed request, and only from a gateway new - * enough to answer one; an older one says `taken` and is not wrong, just less - * use to the person who owns the name. + * else. + * + * `mine` is a name this signer can already point somewhere. `waiting` is one + * the gateway is holding for them from before it took the domain over: not + * free, not theirs to deploy to yet, and one claim away from both. Both come + * only from a signed request, and only from a gateway new enough to answer + * one; an older one says `taken`, which is not wrong, just of no use to the + * person the name belongs to. */ - reason?: 'taken' | 'invalid' | 'mine'; + reason?: 'taken' | 'invalid' | 'mine' | 'waiting'; /** Present when `reason` is `invalid`; written to be shown to whoever typed it. */ error?: string; } diff --git a/src/lib/deploy/npanelApi.test.ts b/src/lib/deploy/npanelApi.test.ts new file mode 100644 index 00000000..1a002fa8 --- /dev/null +++ b/src/lib/deploy/npanelApi.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { getPublicKey, generateSecretKey } from 'nostr-tools'; +import type { NostrSigner } from '@nostrify/nostrify'; +import { fetchNpanelClaimCount } from './npanelApi'; + +const DASHBOARD_HOST = 'npanel.example.test'; + +const pubkey = getPublicKey(generateSecretKey()); + +/** + * A signer that fills in the fields a real one would, without signing. + * + * Signing for real is 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 environment. + * Nothing here verifies a signature — what matters is which request goes out + * and what is made of the answer. + */ +const signer: NostrSigner = { + getPublicKey: async () => pubkey, + signEvent: async (template) => ({ + ...template, + id: 'f'.repeat(64), + pubkey, + sig: '0'.repeat(128), + }), +} as NostrSigner; + +let fetchMock: ReturnType; + +beforeEach(() => { + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('fetchNpanelClaimCount', () => { + it('asks the gateway only for the count', async () => { + fetchMock.mockResolvedValue(new Response(JSON.stringify({ waiting: 3, taken: 1 }))); + + await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({ + waiting: 3, + taken: 1, + }); + + const request = fetchMock.mock.calls[0][0] as Request; + expect(request.url).toBe(`https://${DASHBOARD_HOST}/api/claims?summary=1`); + expect(request.headers.get('Authorization')).toMatch(/^Nostr /); + }); + + it('reports nothing waiting when the gateway answers with the list instead', async () => { + // An older gateway ignores the parameter and returns every claim, which is + // a different shape rather than a bigger number — counting it would be + // inventing one. + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ claims: [{ hostname: `a.example.test` }] })), + ); + + await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({ + waiting: 0, + taken: 0, + }); + }); + + it('reports nothing waiting when the gateway cannot be reached', async () => { + // This runs because somebody opened a settings page. A number that failed + // to arrive is not an error worth showing them. + fetchMock.mockRejectedValue(new Error('offline')); + + await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({ + waiting: 0, + taken: 0, + }); + }); + + it('reports nothing waiting when the gateway refuses', async () => { + fetchMock.mockResolvedValue(new Response('nope', { status: 403 })); + + await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({ + waiting: 0, + taken: 0, + }); + }); +}); diff --git a/src/lib/deploy/npanelApi.ts b/src/lib/deploy/npanelApi.ts index f22a5d2c..b2f151f5 100644 --- a/src/lib/deploy/npanelApi.ts +++ b/src/lib/deploy/npanelApi.ts @@ -114,6 +114,50 @@ export async function fetchNpanelClaims( return claims; } +/** How many names a gateway is holding for somebody, and how many they took. */ +export interface NpanelClaimCount { + waiting: number; + taken: number; +} + +/** + * The count alone, without working out what to do about any of them. + * + * {@link fetchNpanelClaims} reads every file of every claimed deploy and returns + * a manifest each, which is the right price for the dialog that hands the names + * back and much too high for the sentence that gets somebody to open it. A + * gateway too old to know the parameter answers with the list instead, so the + * shape is checked rather than assumed — and a gateway that fails outright + * reports nothing waiting, since a number nobody can fetch should not become an + * error on a settings page. + */ +export async function fetchNpanelClaimCount( + dashboardHost: string, + signer: NostrSigner, + signal?: AbortSignal, +): Promise { + const none: NpanelClaimCount = { waiting: 0, taken: 0 }; + + try { + const response = await npanelRequest( + dashboardHost, + signer, + 'GET', + '/api/claims?summary=1', + undefined, + signal, + ); + if (!response.ok) return none; + + const body = (await response.json()) as Partial; + if (typeof body.waiting !== 'number' || typeof body.taken !== 'number') return none; + + return { waiting: body.waiting, taken: body.taken }; + } catch { + return none; + } +} + /** Point a name waiting for this signer at a site they published. */ export async function claimNpanelHostname( dashboardHost: string, diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index e113afd6..7f1357fa 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -15,6 +15,7 @@ import { ProviderConfigDialog } from '@/components/ProviderConfigDialog'; import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog'; import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog'; import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog'; +import { useNpanelClaimCount } from '@/hooks/useNpanelClaims'; import { Button } from '@/components/ui/button'; import { DndContext, @@ -344,27 +345,13 @@ export function DeploySettings() {
)} - {/* 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' ? ( -
-
-

Sites from before {provider.name}

-

- Names you published on {provider.domain} under the old host are being served - from an archive until you take them back. -

-
- -
+ provider={provider} + onOpen={() => setMigratingProvider(provider)} + /> ) : null ))} @@ -440,4 +427,45 @@ export function DeploySettings() { ); } +/** + * Sites held for their previous owner on a gateway that took over a domain. + * + * The count is asked for on load, rather than the card standing there saying + * "you may have sites waiting" to everyone forever. Almost nobody does, and a + * card that cannot tell them apart is one most people learn to ignore before + * it ever applies to them — while the person it does apply to has a few names + * being served from an archive under a key that is not theirs, which is worth + * one signature to say out loud. + * + * It is only the count: {@link useNpanelClaimCount} is two counted rows, not + * the deploy-by-deploy read the dialog does when somebody opens it. + */ +function HeldSites({ provider, onOpen }: { provider: NpanelProvider; onOpen: () => void }) { + const { data } = useNpanelClaimCount(provider); + + // Nothing to say until the gateway says there is something, so a gateway with + // no migration behind it — every gateway but the one — shows nothing at all. + if (!data?.waiting) return null; + + return ( +
+
+

+ {data.waiting === 1 + ? `One name is waiting for you on ${provider.domain}` + : `${data.waiting} names are waiting for you on ${provider.domain}`} +

+

+ You published {data.waiting === 1 ? 'it' : 'them'} before {provider.domain} moved to{' '} + {provider.name}. {data.waiting === 1 ? 'It is' : 'They are'} being served from an archive + until you take {data.waiting === 1 ? 'it' : 'them'} back. +

+
+ +
+ ); +} + export default DeploySettings;