From 174672f52ccbf6cb714774101481de5d8585739b Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Wed, 30 Sep 2026 11:11:52 +0000 Subject: [PATCH] Recover empty Cloudflare domain sets through authenticated transport --- docs/integrations/cloudflare.md | 2 +- docs/reference/cli.md | 2 +- packages/void/src/cli/cf-compat.ts | 54 +++++ .../void/src/cli/cloudflare-operations.ts | 61 +---- packages/void/test/unit/cf-compat.test.ts | 208 +++++++++++++----- .../test/unit/cloudflare-operations.test.ts | 60 ++--- 6 files changed, 243 insertions(+), 144 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 736a0a291..61ae5c508 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -360,7 +360,7 @@ ISR uses the shared cache protocol. Entries are scoped to a deployment and hostn With Cloudflare selected, `void secret`, `void domain`, `void project status|list|logs|rollback`, and remote `void db` commands use the saved Worker and account. Database commands operate on the selected D1 database. Logs are a live tail; Void doesn't provide hosted log history for direct deploys. -Custom domain changes update routes immediately without rewriting schedules, queues, or workflows. Removing the final custom domain requires `CLOUDFLARE_API_TOKEN` with Workers Scripts: Edit because that operation uses Cloudflare's domain-record API. +Custom domain changes update routes immediately without rewriting schedules, queues, or workflows. Removing the final custom domain uses your browser session from `void cloudflare login` or an API token with Workers Scripts: Edit permission. `void project delete` doesn't remove direct Cloudflare resources, which may be shared. Review their use and remove them explicitly in Cloudflare. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 4ef1ed2ca..fe6fe898e 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -1522,7 +1522,7 @@ Add a custom domain to the saved target. Hosted Void projects print the DNS reco void domain delete [--project ] ``` -Direct Cloudflare projects apply the change immediately. Deleting the final custom domain requires `CLOUDFLARE_API_TOKEN` with Workers Scripts: Edit permission because the standard trigger operation does not reconcile an empty custom-domain set; Void fails before changing local or remote state when that token is unavailable. +Direct Cloudflare projects apply the change immediately. Deleting the final custom domain uses your browser session from `void cloudflare login` or an API token with Workers Scripts: Edit permission. If Cloudflare rejects the change, Void attempts to restore the previous domain configuration and reports whether recovery succeeded. Remove a custom domain from the saved target. For Cloudflare, this removes the matching `custom_domain` route and synchronizes triggers. If Cloudflare rejects the update, Void restores the exact previous local config and immediately reapplies it remotely. If that second synchronization also fails, the CLI reports that remote route state may be partial instead of claiming a successful rollback. diff --git a/packages/void/src/cli/cf-compat.ts b/packages/void/src/cli/cf-compat.ts index a87a8c8e0..c54e34caa 100644 --- a/packages/void/src/cli/cf-compat.ts +++ b/packages/void/src/cli/cf-compat.ts @@ -290,6 +290,52 @@ async function clearWorkerCronSchedules(worker: string): Promise { } } +async function clearWorkerCustomDomains(worker: string): Promise { + const base = ( + process.env.CLOUDFLARE_API_BASE_URL ?? 'https://api.cloudflare.com/client/v4' + ).replace(/\/$/, ''); + const endpoint = `${base}/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/domains/records`; + const proxy = + process.env.HTTP_PROXY || + process.env.HTTPS_PROXY || + process.env.http_proxy || + process.env.https_proxy + ? new EnvHttpProxyAgent() + : null; + try { + const response = await httpFetch(endpoint, { + method: 'PUT', + headers: { ...(await apiHeaders()), 'Content-Type': 'application/json' }, + body: JSON.stringify({ + override_scope: true, + override_existing_origin: false, + override_existing_dns_record: false, + origins: [], + }), + redirect: 'error', + signal: AbortSignal.timeout(30_000), + ...(proxy ? { dispatcher: proxy } : {}), + }); + if (!response.ok) { + throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`); + } + let body: unknown; + try { + body = await response.json(); + } catch { + throw new Error( + `Cloudflare returned HTTP ${response.status} with a non-JSON custom-domain response.`, + ); + } + if (object(body).success !== true) { + throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`); + } + return result(0); + } finally { + await proxy?.close(); + } +} + async function assertExistingProvisionableResources( directory: string, account: string, @@ -1028,6 +1074,14 @@ async function workerChanges(): Promise { } return await clearWorkerCronSchedules(name); } + if (args[0] === 'triggers' && args[1] === 'clear-domains') { + const raw = config(); + const name = workerName(); + if (raw.name !== name || (raw.account_id !== undefined && raw.account_id !== accountId())) { + throw new Error('Cloudflare trigger target changed.'); + } + return await clearWorkerCustomDomains(name); + } if ((args[0] === 'versions' && args[1] === 'upload') || args[0] === 'deploy') { const raw = config(); const path = configPath()!; diff --git a/packages/void/src/cli/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index 6b9eac7b6..c2fc9fde5 100644 --- a/packages/void/src/cli/cloudflare-operations.ts +++ b/packages/void/src/cli/cloudflare-operations.ts @@ -617,13 +617,6 @@ export async function changeCloudflareDomain( if (!update.modified) { return update; } - if (update.domains.length === 0 && !emptyDomainPublisher && !resolveCloudflareApiToken()) { - writeFileSync(before.configPath, original); - persistCloudflareConfig(root); - throw new Error( - 'Deleting the final Cloudflare custom domain requires CLOUDFLARE_API_TOKEN for the empty-domain API update. Export a scoped token with Workers Scripts: Edit permission and retry. No local or remote state changed.', - ); - } const triggerConfigDir = mkdtempSync(join(tmpdir(), 'void-domain-triggers-')); const triggerConfigPath = join(triggerConfigDir, 'wrangler.json'); const deployRoutes = async (): Promise => { @@ -668,55 +661,14 @@ export async function changeCloudflareDomain( } /** - * Reconcile an empty Custom Domain set through the API Wrangler itself uses. - * Wrangler 4.130 skips `publishCustomDomains()` when its configured set is - * empty, so `triggers deploy` exits successfully without removing the final - * domain. Direct API access is deliberately limited to an explicit API token; - * OAuth credential storage is Wrangler-private and must not be scraped. + * Publish an explicit empty Custom Domain set through the pinned cf transport. + * Trigger deploy omits empty domain sets; this operation must reconcile them + * explicitly using the same verified browser/API credentials as other commands. */ export async function publishEmptyCloudflareCustomDomainSet( context: CloudflareOperationContext, ): Promise { - const token = resolveCloudflareApiToken(); - if (!token) { - throw new Error( - 'CLOUDFLARE_API_TOKEN is required to restore an empty custom-domain set after the Cloudflare trigger update failed.', - ); - } - const response = await fetch( - `${context.apiBaseUrl}/accounts/${context.accountId}/workers/scripts/${context.workerName}/domains/records`, - { - method: 'PUT', - headers: { - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - override_scope: true, - override_existing_origin: false, - override_existing_dns_record: false, - origins: [], - }), - redirect: 'error', - signal: AbortSignal.timeout(30_000), - }, - ); - let body: unknown; - try { - body = await response.json(); - } catch { - throw new Error( - `Cloudflare returned HTTP ${response.status} with a non-JSON custom-domain response.`, - ); - } - if ( - !response.ok || - typeof body !== 'object' || - body === null || - (body as Record).success !== true - ) { - throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`); - } + await run(context, ['triggers', 'clear-domains', ...targetArgs(context)]); } /** Adapt the direct empty-domain API call to the deployment package's result contract. */ @@ -746,11 +698,6 @@ export function createCloudflareEmptyCronPublisher( }; } -function resolveCloudflareApiToken(): string | undefined { - const token = process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN; - return token || undefined; -} - /** * Build a route-only Wrangler config for a domain update. `triggers deploy` * also reconciles cron, queue-consumer, and workflow triggers found in its diff --git a/packages/void/test/unit/cf-compat.test.ts b/packages/void/test/unit/cf-compat.test.ts index b02c2f326..46eb902e7 100644 --- a/packages/void/test/unit/cf-compat.test.ts +++ b/packages/void/test/unit/cf-compat.test.ts @@ -9,68 +9,150 @@ import { pathToFileURL } from 'node:url'; import { expect, it } from 'vite-plus/test'; import { resolveWranglerArgv } from '../../src/cli/preset.ts'; -it('clears Worker Cron Triggers through the pinned account API', async () => { - const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-')); - let requested = false; - const server = createServer(async (request, response) => { - requested = true; - expect(request.method).toBe('PUT'); - expect(request.url).toBe( - '/client/v4/accounts/test-account/workers/scripts/test-worker/schedules', - ); - expect(request.headers.authorization).toBe('Bearer synthetic-token'); - let body = ''; - for await (const chunk of request) { - body += chunk; - } - expect(body).toBe('[]'); - response.setHeader('Content-Type', 'application/json'); - response.end(JSON.stringify({ success: true, result: { schedules: [] } })); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - try { - const configPath = join(directory, 'wrangler.json'); - writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' })); - const [command, ...prefix] = resolveWranglerArgv(directory); - const output = await new Promise<{ status: number; stderr: string }>((resolve) => { - execFile( - command!, - [...prefix, 'triggers', 'clear-crons', '-c', configPath, '--name', 'test-worker'], - { - cwd: directory, - encoding: 'utf8', - timeout: 20_000, - env: { - PATH: process.env.PATH, - SYSTEMROOT: process.env.SYSTEMROOT, - WINDIR: process.env.WINDIR, - CI: 'true', - CLOUDFLARE_API_TOKEN: 'synthetic-token', - CLOUDFLARE_ACCOUNT_ID: 'test-account', - CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`, +it.each([200, 503])( + 'reports HTTP %i when domain cleanup returns a non-JSON response', + async (status) => { + const directory = mkdtempSync(join(tmpdir(), 'void-cf-domain-error-')); + const server = createServer((request, response) => { + request.resume(); + response.statusCode = status; + response.end('temporary upstream response'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const configPath = join(directory, 'wrangler.json'); + writeFileSync( + configPath, + JSON.stringify({ name: 'test-worker', account_id: 'test-account' }), + ); + const [command, ...prefix] = resolveWranglerArgv(directory); + const output = await new Promise<{ status: number; stderr: string }>((resolve) => { + execFile( + command!, + [...prefix, 'triggers', 'clear-domains', '-c', configPath, '--name', 'test-worker'], + { + cwd: directory, + encoding: 'utf8', + timeout: 20_000, + env: { + PATH: process.env.PATH, + SYSTEMROOT: process.env.SYSTEMROOT, + WINDIR: process.env.WINDIR, + CI: 'true', + CLOUDFLARE_API_TOKEN: 'synthetic-token', + CLOUDFLARE_ACCOUNT_ID: 'test-account', + CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`, + }, }, - }, - (error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }), + (error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }), + ); + }); + expect(output.status).toBe(1); + expect(output.stderr).toContain(`HTTP ${status}`); + expect(output.stderr).not.toContain('synthetic-token'); + } finally { + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }); + rmSync(directory, { recursive: true, force: true }); + } + }, + 30_000, +); + +it.each(['clear-crons', 'clear-domains'])( + 'clears %s through the pinned account API', + async (operation) => { + const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-')); + let requested = false; + const server = createServer(async (request, response) => { + requested = true; + expect(request.method).toBe('PUT'); + expect(request.url).toBe( + `/client/v4/accounts/test-account/workers/scripts/test-worker/${operation === 'clear-crons' ? 'schedules' : 'domains/records'}`, ); + expect(request.headers.authorization).toBe('Bearer synthetic-token'); + let body = ''; + for await (const chunk of request) { + body += chunk; + } + expect(JSON.parse(body)).toEqual( + operation === 'clear-crons' + ? [] + : { + override_scope: true, + override_existing_origin: false, + override_existing_dns_record: false, + origins: [], + }, + ); + response.setHeader('Content-Type', 'application/json'); + response.end(JSON.stringify({ success: true, result: { schedules: [] } })); }); - expect(output.status, output.stderr).toBe(0); - expect(requested).toBe(true); - } finally { - await new Promise((resolve) => { - server.close(() => resolve()); - server.closeAllConnections(); - }); - rmSync(directory, { recursive: true, force: true }); - } -}, 30_000); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const configPath = join(directory, 'wrangler.json'); + writeFileSync( + configPath, + JSON.stringify({ name: 'test-worker', account_id: 'test-account' }), + ); + const [command, ...prefix] = resolveWranglerArgv(directory); + const output = await new Promise<{ status: number; stderr: string }>((resolve) => { + execFile( + command!, + [...prefix, 'triggers', operation, '-c', configPath, '--name', 'test-worker'], + { + cwd: directory, + encoding: 'utf8', + timeout: 20_000, + env: { + PATH: process.env.PATH, + SYSTEMROOT: process.env.SYSTEMROOT, + WINDIR: process.env.WINDIR, + CI: 'true', + CLOUDFLARE_API_TOKEN: 'synthetic-token', + CLOUDFLARE_ACCOUNT_ID: 'test-account', + CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`, + }, + }, + (error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }), + ); + }); + expect(output.status, output.stderr).toBe(0); + expect(requested).toBe(true); + } finally { + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }); + rmSync(directory, { recursive: true, force: true }); + } + }, + 30_000, +); -it.each(['clear-crons'])( +it.each(['clear-crons', 'clear-domains'])( 'uses encrypted browser credentials for %s', async (operation) => { const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-oauth-')); - const server = createServer((request, response) => { - expect(request.headers.authorization).toBe('Bearer synthetic-oauth-token'); - request.resume(); + const requests: Array<{ + method: string | undefined; + url: string | undefined; + authorization: string | undefined; + body: unknown; + }> = []; + const server = createServer(async (request, response) => { + let body = ''; + for await (const chunk of request) { + body += chunk; + } + requests.push({ + method: request.method, + url: request.url, + authorization: request.headers.authorization, + body: JSON.parse(body), + }); response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify({ success: true, result: { schedules: [] } })); }); @@ -145,6 +227,22 @@ syncBuiltinESMExports(); ); }); expect(output.status, output.stderr).toBe(0); + expect(requests).toEqual([ + { + method: 'PUT', + url: `/client/v4/accounts/test-account/workers/scripts/test-worker/${operation === 'clear-crons' ? 'schedules' : 'domains/records'}`, + authorization: 'Bearer synthetic-oauth-token', + body: + operation === 'clear-crons' + ? [] + : { + override_scope: true, + override_existing_origin: false, + override_existing_dns_record: false, + origins: [], + }, + }, + ]); } finally { await new Promise((resolve) => { server.close(() => resolve()); diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index 48fa928e9..bf00fdb37 100644 --- a/packages/void/test/unit/cloudflare-operations.test.ts +++ b/packages/void/test/unit/cloudflare-operations.test.ts @@ -721,50 +721,50 @@ describe('Cloudflare custom domains', () => { const root = project( '{"name":"my-worker","account_id":"account-1","routes":[{"pattern":"app.example.com","custom_domain":true}]}', ); - vi.stubEnv('CLOUDFLARE_API_TOKEN', 'test-token'); - const fetchMock = vi.fn(async () => - Response.json({ success: true, errors: [], messages: [], result: null }), - ); - vi.stubGlobal('fetch', fetchMock); - - await changeCloudflareDomain(root, 'app.example.com', 'delete', vi.fn()); - - expect(fetchMock).toHaveBeenCalledTimes(1); - const [url, init] = fetchMock.mock.calls[0]!; - expect(url).toBe( - 'https://api.cloudflare.com/client/v4/accounts/account-1/workers/scripts/my-worker/domains/records', + vi.stubEnv('CLOUDFLARE_API_TOKEN', ''); + vi.stubEnv('CF_API_TOKEN', ''); + const runner = vi + .fn() + .mockResolvedValue({ status: 0, stdout: '', stderr: '' }); + await changeCloudflareDomain(root, 'app.example.com', 'delete', runner); + expect(runner).toHaveBeenCalledWith( + [ + 'triggers', + 'clear-domains', + '-c', + join(root, 'wrangler.jsonc'), + '--env=', + '--name', + 'my-worker', + ], + { capture: true }, ); - expect(init).toMatchObject({ - method: 'PUT', - headers: { - Authorization: 'Bearer test-token', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - override_scope: true, - override_existing_origin: false, - override_existing_dns_record: false, - origins: [], - }), - redirect: 'error', - }); }); - it('fails closed before deleting the final domain without an API token', async () => { + it('restores the final domain when the authenticated clear operation is rejected', async () => { const root = project( '{"name":"my-worker","account_id":"account-1","routes":[{"pattern":"app.example.com","custom_domain":true}]}', ); const before = readFileSync(join(root, 'wrangler.jsonc'), 'utf-8'); - const runner = vi.fn(); + const runner = vi + .fn() + .mockResolvedValueOnce({ + status: 1, + stdout: '', + stderr: 'Cloudflare authentication is required.', + }) + .mockResolvedValue({ status: 0, stdout: '', stderr: '' }); vi.stubEnv('CLOUDFLARE_API_TOKEN', ''); vi.stubEnv('CF_API_TOKEN', ''); await expect(changeCloudflareDomain(root, 'app.example.com', 'delete', runner)).rejects.toThrow( - 'No local or remote state changed', + 'both the local config and remote triggers were restored', ); expect(readFileSync(join(root, 'wrangler.jsonc'), 'utf-8')).toBe(before); - expect(runner).not.toHaveBeenCalled(); + expect(runner).toHaveBeenCalledTimes(2); + expect(runner.mock.calls[0]?.[0].slice(0, 2)).toEqual(['triggers', 'clear-domains']); + expect(runner.mock.calls[1]?.[0].slice(0, 2)).toEqual(['triggers', 'deploy']); }); it('lists configured domains without an account mutation', () => {