Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/integrations/cloudflare.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -1522,7 +1522,7 @@ Add a custom domain to the saved target. Hosted Void projects print the DNS reco
void domain delete <hostname> [--project <name>]
```

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.

Expand Down
54 changes: 54 additions & 0 deletions packages/void/src/cli/cf-compat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,52 @@ async function clearWorkerCronSchedules(worker: string): Promise<Result> {
}
}

async function clearWorkerCustomDomains(worker: string): Promise<Result> {
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,
Expand Down Expand Up @@ -1028,6 +1074,14 @@ async function workerChanges(): Promise<Result> {
}
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()!;
Expand Down
61 changes: 4 additions & 57 deletions packages/void/src/cli/cloudflare-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => {
Expand Down Expand Up @@ -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<void> {
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<string, unknown>).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. */
Expand Down Expand Up @@ -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
Expand Down
Loading