From c2646747ff23e515df7c094ca2cc0f5991386669 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 10:15:43 +0100 Subject: [PATCH 01/25] feat(cloudflare): run non-interactively in Workers Builds and check its target --- packages/void/src/cli/cloudflare-auth.ts | 3 +- packages/void/src/cli/cloudflare-link.ts | 3 +- .../void/src/cli/deploy-cloudflare-auth.ts | 9 +- .../void/src/cli/deploy-cloudflare-helpers.ts | 14 +- .../src/cli/deploy-cloudflare-preflight.ts | 13 +- .../void/src/cli/deploy-cloudflare-static.ts | 13 +- packages/void/src/cli/deploy-cloudflare.ts | 3 +- packages/void/src/cli/deploy-types.ts | 11 + packages/void/src/cli/deploy.ts | 3 +- packages/void/src/cli/workers-builds.ts | 197 +++++++++++++++++ .../void/test/unit/cloudflare-auth.test.ts | 25 +++ .../void/test/unit/cloudflare-deploy.test.ts | 88 ++++++++ .../void/test/unit/workers-builds.test.ts | 204 ++++++++++++++++++ 13 files changed, 573 insertions(+), 13 deletions(-) create mode 100644 packages/void/src/cli/workers-builds.ts create mode 100644 packages/void/test/unit/workers-builds.test.ts diff --git a/packages/void/src/cli/cloudflare-auth.ts b/packages/void/src/cli/cloudflare-auth.ts index ac485c3d46..3b4d5addab 100644 --- a/packages/void/src/cli/cloudflare-auth.ts +++ b/packages/void/src/cli/cloudflare-auth.ts @@ -7,6 +7,7 @@ import { isCleanCloudflareExit, } from './cloudflare-process.ts'; import { resolveCloudflareOperationArgv } from './preset.ts'; +import { canPromptInTerminal } from './workers-builds.ts'; export type CloudflareAccount = Readonly<{ id: string; @@ -115,7 +116,7 @@ export async function ensureCloudflareAuthentication( return existing; } - const interactive = options.interactive ?? (process.stdin.isTTY && process.stdout.isTTY); + const interactive = options.interactive ?? canPromptInTerminal(); if (!interactive) { throw new CloudflareAuthenticationError( 'Cloudflare authentication is required. Set CLOUDFLARE_API_TOKEN in CI, or run `void cloudflare login` in an interactive terminal.', diff --git a/packages/void/src/cli/cloudflare-link.ts b/packages/void/src/cli/cloudflare-link.ts index 66c81186b1..820bc873f2 100644 --- a/packages/void/src/cli/cloudflare-link.ts +++ b/packages/void/src/cli/cloudflare-link.ts @@ -19,6 +19,7 @@ import type { RunDeployOptions } from './deploy.ts'; import { discoverFrameworkWranglerFiles } from './framework-config-migrate.ts'; import { confirm, isCancel, log } from './interactive-prompts.ts'; import { readDeploymentPlatform, writeDeploymentPlatform } from './project.ts'; +import { canPromptInTerminal } from './workers-builds.ts'; const LINK_FILE = '.void/cloudflare-link.json'; export type CloudflareLink = { @@ -266,7 +267,7 @@ export async function maybeLinkCloudflareDeploy( `Set the existing Worker's name in a valid ${name} before linking to Cloudflare.`, ); } - if (!(deps.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY))) { + if (!(deps.interactive ?? canPromptInTerminal())) { throw new Error( `Found ${name} without a deployment destination. Run void deploy interactively to link the existing Worker, or use void deploy --platform cloudflare with Cloudflare credentials in CI.`, ); diff --git a/packages/void/src/cli/deploy-cloudflare-auth.ts b/packages/void/src/cli/deploy-cloudflare-auth.ts index 050c2d832d..fd0737529d 100644 --- a/packages/void/src/cli/deploy-cloudflare-auth.ts +++ b/packages/void/src/cli/deploy-cloudflare-auth.ts @@ -26,6 +26,7 @@ import { } from './env-validation.ts'; import { isCancel, select } from './interactive-prompts.ts'; import { getErrorMessage } from './output.ts'; +import { canPromptInTerminal } from './workers-builds.ts'; import { writeProvisionedWranglerConfig } from './wrangler.ts'; /** Run typed provider operations in the pinned account and API context. */ @@ -96,7 +97,7 @@ export async function prepareExistingCloudflareDeployWithAuth( `Cloudflare credentials from ${overrides.join(', ')} were rejected or cannot access account ${options.accountId}. Correct or unset them, then retry the deploy.`, ); } - if (!process.stdin.isTTY || !process.stdout.isTTY) { + if (!canPromptInTerminal()) { // oxlint-disable-next-line preserve-caught-error -- Provider credential and session failures are translated to a safe user-facing message. throw new Error( wrongAccount @@ -148,7 +149,7 @@ export async function chooseCloudflareDeployAccount(options: { const accounts = session.accounts; let account = accounts[0]; if (accounts.length > 1) { - if (!process.stdin.isTTY || !process.stdout.isTTY) { + if (!canPromptInTerminal()) { throw new Error( 'Multiple Cloudflare accounts are available. Set CLOUDFLARE_ACCOUNT_ID in CI, or run `void init` interactively to choose one.', ); @@ -178,9 +179,9 @@ export async function chooseCloudflareDeployAccount(options: { return account.id; } -/** Non-interactive when CI is detected or stdin/stdout is not a TTY. */ +/** Non-interactive in CI, including Workers Builds, or when stdin/stdout is not a TTY. */ export function isWranglerNonInteractiveOrCI(): boolean { - return ciInfoIsCI || !(process.stdin.isTTY && process.stdout.isTTY); + return ciInfoIsCI || !canPromptInTerminal(); } const GLOBAL_API_KEY_SESSION = diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 4cfbc4f871..5095a0e18f 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -70,6 +70,8 @@ import type { CliLogger } from './log-file.ts'; import { createSpinner, getErrorMessage } from './output.ts'; import { resolveWorkersDevComplianceRegion } from './provision.ts'; import type { ComplianceRegion } from './provision.ts'; +import { workersBuildsAccountMismatch } from './workers-builds.ts'; +import type { WorkersBuildsContext } from './workers-builds.ts'; import { acknowledgeWranglerManagedQueueRemovals, readWranglerPublishedTrafficSnapshot, @@ -168,6 +170,8 @@ export async function connectCloudflareDeployAccount(options: { readinessAccessOrigin: string | null | undefined; /** Scrubs and logs every child this connection runs. */ reporter: CloudflareChildReporter; + /** Workers Builds as recorded before project code ran. */ + workersBuilds?: WorkersBuildsContext | null; }): Promise { const { root, configPath, deps, reporter } = options; let { rootConfig } = options; @@ -185,9 +189,13 @@ export async function connectCloudflareDeployAccount(options: { ); // Pin the uploaders before the first authenticated command, including account discovery. const pins = createCloudflareUploaderPins(root, deps); - let accountId = - readWranglerTopLevelString(rootConfig, 'account_id') ?? - (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); + const configAccountId = readWranglerTopLevelString(rootConfig, 'account_id'); + const accountMismatch = workersBuildsAccountMismatch(options.workersBuilds, configAccountId); + if (accountMismatch) { + log.error(accountMismatch); + return null; + } + let accountId = configAccountId ?? (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); if (!accountId) { const accountRunner = observeCloudflareRunner( deps.runWrangler ?? createDeployWranglerRunner(root, undefined, apiBaseUrl), diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 6622e2f7db..40df98e3dd 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -78,6 +78,7 @@ import type { CliLogger } from './log-file.ts'; import { getErrorMessage } from './output.ts'; import { checkCloudflareProvisionDrift, provisionCloudflareResources } from './provision.ts'; import type { ProvisionDriftEntry } from './provision.ts'; +import { workersBuildsTargetMismatch } from './workers-builds.ts'; import { sameMigrationsDir, writeProvisionedWranglerConfig } from './wrangler.ts'; /** Validate source-level native deploy inputs before account operations or project code. */ @@ -269,6 +270,7 @@ export async function preflightCloudflareWorker(input: { persistAccount: !(options.reuseExistingWorker || initialCloudflareLink), readinessAccessOrigin: options.readinessAccessOrigin, reporter, + workersBuilds: options.workersBuilds, }); if (!connection) { return exit(1); @@ -277,7 +279,16 @@ export async function preflightCloudflareWorker(input: { const { apiBaseUrl, complianceRegion, accountId, runWrangler, assertUploaderStillPinned } = target; rootConfig = connectedConfig; - const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); + const configuredWorkerName = readWranglerTopLevelString(rootConfig, 'name'); + const workerName = configuredWorkerName ?? deriveWorkerName(root); + const buildsMismatch = workersBuildsTargetMismatch(options.workersBuilds, { + workerName, + workerNameSource: configuredWorkerName ? 'config' : 'package', + }); + if (buildsMismatch) { + log.error(buildsMismatch); + return exit(1); + } const { entries: expectedWorkflows } = planWorkflows( rootConfig, source.analysis.workflows, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 21d7e8b47e..28f99ffca7 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -77,6 +77,7 @@ import { detectPreset } from './preset.ts'; import type { StaticPreset, FrameworkPreset } from './preset.ts'; import { deleteEnvVarCaseAware } from './provision.ts'; import type { AssetConfig, DeployManifest } from './types.ts'; +import { workersBuildsTargetMismatch } from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; /** Default runtime date for static and framework Workers that set none. */ @@ -388,6 +389,7 @@ export async function runCloudflareStaticDeploy( persistAccount: !(options.reuseExistingWorker || initialCloudflareLink), readinessAccessOrigin: options.readinessAccessOrigin, reporter, + workersBuilds: options.workersBuilds, }); if (!connection || !(await confirmCloudflareDeployAuthentication(connection, configPath))) { return exit(1); @@ -421,7 +423,16 @@ export async function runCloudflareStaticDeploy( throw new Error('The pending Cloudflare handoff was not saved before deployment.'); } const rootConfig = parseRootWranglerConfig(configPath); - const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); + const configuredWorkerName = readWranglerTopLevelString(rootConfig, 'name'); + const workerName = configuredWorkerName ?? deriveWorkerName(root); + const buildsMismatch = workersBuildsTargetMismatch(options.workersBuilds, { + workerName, + workerNameSource: configuredWorkerName ? 'config' : 'package', + }); + if (buildsMismatch) { + log.error(buildsMismatch); + return exit(1); + } let previousWorkflowVersionId: string | undefined; if (options.atomic) { try { diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 3b09150cf2..2a33937e14 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -30,6 +30,7 @@ import type { RunDeployOptions, CloudflareDeployDeps } from './deploy-types.ts'; import { renderAddressMap } from './email-cloudflare.ts'; import type { CliLogger } from './log-file.ts'; import { FRAMEWORK_PRESETS } from './preset.ts'; +import { withRecordedWorkersBuildsEnv } from './workers-builds.ts'; /** Deploy to the user's own Cloudflare account through the guarded native Worker flow. */ export async function runCloudflareDeploy( @@ -39,7 +40,7 @@ export async function runCloudflareDeploy( deps: CloudflareDeployDeps = {}, ): Promise { // readConfig evaluates void.config.ts in this process. Record operator input before it runs. - options = withRecordedReadinessAccessOrigin(options); + options = withRecordedWorkersBuildsEnv(withRecordedReadinessAccessOrigin(options)); const initialCloudflareLink = readCloudflareLink(root); const initialCloudflareCandidate = readCloudflareCandidate(root); let d1RestoreCommand: string | undefined; diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index 266033f10c..fa4a307a26 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -29,6 +29,7 @@ import type { CliLogger } from './log-file.ts'; import type { DeploymentPlatform } from './project.ts'; import type { provisionCloudflareResources } from './provision.ts'; import type { DeployEvent, DeployTargetAdapter } from './types.ts'; +import type { WorkersBuildsContext } from './workers-builds.ts'; export type DeployVerification = { ok: true; reason?: never } | { ok: false; reason: string }; @@ -69,6 +70,16 @@ export type RunDeployOptions = { * `--platform cloudflare` only. */ readinessAccessOrigin?: string | null; + /** + * Workers Builds context as recorded before project code ran (`null` outside Workers Builds). + * `--platform cloudflare` only. + */ + workersBuilds?: WorkersBuildsContext | null; + /** + * File for the Wrangler-compatible deploy result (`WRANGLER_OUTPUT_FILE_PATH` or + * `WRANGLER_OUTPUT_FILE_DIRECTORY`), recorded before project code ran. `--platform cloudflare` only. + */ + deployOutputFile?: string | null; }; type DeployDoneEvent = Extract; diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 5b9d4eab65..a19d651ac4 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -46,6 +46,7 @@ import { readDeploymentPlatform, readProjectConfig } from './project.ts'; import type { DeploymentPlatform, ProjectConfig } from './project.ts'; import { getRequestedProjectSlug } from './resolve-project.ts'; import type { DeployTarget } from './types.ts'; +import { withRecordedWorkersBuildsEnv } from './workers-builds.ts'; export function resolveDeploymentPlatform( root: string, @@ -58,7 +59,7 @@ export function resolveDeploymentPlatform( /** Run `void deploy`; a failure carries a summary of the deploy log in its message. */ export async function runDeploy(root: string, options?: RunDeployOptions): Promise { // The Cloudflare link check can evaluate void.config.ts, so record operator input first. - options = withRecordedReadinessAccessOrigin(options ?? {}); + options = withRecordedWorkersBuildsEnv(withRecordedReadinessAccessOrigin(options ?? {})); console.log(); const cliLog = openDeployLog({ diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts new file mode 100644 index 0000000000..f9f7475f54 --- /dev/null +++ b/packages/void/src/cli/workers-builds.ts @@ -0,0 +1,197 @@ +import { randomBytes } from 'node:crypto'; +import { appendFileSync, mkdirSync } from 'node:fs'; +import { dirname, resolve } from 'pathslash'; + +/** + * Cloudflare Workers Builds (the Cloudflare GitHub/GitLab integration), as recorded before + * project code ran. Builds sets `WORKERS_CI=1` and injects a build API token plus + * `CLOUDFLARE_ACCOUNT_ID`; it also passes the connected Worker's name in + * `WRANGLER_CI_OVERRIDE_NAME`. + */ +export type WorkersBuildsContext = Readonly<{ + buildId: string | null; + branch: string | null; + /** A full commit SHA. A deploy-hook build reports the branch name here, which is dropped. */ + commit: string | null; + /** The Worker this Builds project is connected to. */ + workerName: string | null; + accountId: string | null; +}>; + +/** The `deploy` entry Workers Builds reads from `WRANGLER_OUTPUT_FILE_PATH`. */ +export type WranglerDeployOutputEntry = Readonly<{ + type: 'deploy'; + version: 1; + worker_name: string; + worker_tag: string | null; + version_id: string; + targets: ReadonlyArray; + wrangler_environment: undefined; + worker_name_overridden: boolean; +}>; + +const COMMIT_SHA = /^[0-9a-f]{40}$/i; + +function readNonEmpty(env: NodeJS.ProcessEnv, name: string): string | null { + const value = env[name]?.trim(); + return value ? value : null; +} + +/** The Workers Builds context, or null outside Workers Builds. */ +export function readWorkersBuildsContext( + env: NodeJS.ProcessEnv = process.env, +): WorkersBuildsContext | null { + const marker = env.WORKERS_CI?.trim().toLowerCase(); + if (marker !== '1' && marker !== 'true') { + return null; + } + const commit = readNonEmpty(env, 'WORKERS_CI_COMMIT_SHA'); + return { + buildId: readNonEmpty(env, 'WORKERS_CI_BUILD_UUID'), + branch: readNonEmpty(env, 'WORKERS_CI_BRANCH'), + commit: commit && COMMIT_SHA.test(commit) ? commit.toLowerCase() : null, + workerName: readNonEmpty(env, 'WRANGLER_CI_OVERRIDE_NAME'), + accountId: readNonEmpty(env, 'CLOUDFLARE_ACCOUNT_ID') ?? readNonEmpty(env, 'CF_ACCOUNT_ID'), + }; +} + +/** Whether Void may prompt: never in Workers Builds, otherwise only on an interactive terminal. */ +export function canPromptInTerminal(env: NodeJS.ProcessEnv = process.env): boolean { + return ( + readWorkersBuildsContext(env) === null && + process.stdin.isTTY === true && + process.stdout.isTTY === true + ); +} + +/** + * The file Wrangler-compatible results are appended to, resolved like Wrangler does: + * `WRANGLER_OUTPUT_FILE_PATH`, else a new file in `WRANGLER_OUTPUT_FILE_DIRECTORY`. + */ +export function resolveDeployOutputFile(env: NodeJS.ProcessEnv = process.env): string | null { + const path = readNonEmpty(env, 'WRANGLER_OUTPUT_FILE_PATH'); + if (path) { + return resolve(path); + } + const directory = readNonEmpty(env, 'WRANGLER_OUTPUT_FILE_DIRECTORY'); + if (!directory) { + return null; + } + const date = new Date() + .toISOString() + .replaceAll(':', '-') + .replace('.', '_') + .replace('T', '_') + .replace('Z', ''); + return resolve(directory, `wrangler-output-${date}-${randomBytes(3).toString('hex')}.json`); +} + +/** + * Record the Workers Builds context and the output file before project code runs: loading + * `void.config.ts` evaluates project code in this process, which could change `process.env`. + * Already recorded values are kept. + */ +export function withRecordedWorkersBuildsEnv< + T extends { workersBuilds?: WorkersBuildsContext | null; deployOutputFile?: string | null }, +>( + options: T, + env: NodeJS.ProcessEnv = process.env, +): T & { workersBuilds: WorkersBuildsContext | null; deployOutputFile: string | null } { + return { + ...options, + workersBuilds: + options.workersBuilds !== undefined ? options.workersBuilds : readWorkersBuildsContext(env), + deployOutputFile: + options.deployOutputFile !== undefined + ? options.deployOutputFile + : resolveDeployOutputFile(env), + }; +} + +/** + * Explain why this deploy cannot run under the Workers Builds settings, or return null. + * Void deploys the Worker named by the project, so it never adopts a different Builds Worker. + */ +export function workersBuildsTargetMismatch( + builds: WorkersBuildsContext | null | undefined, + target: { workerName: string; workerNameSource: 'config' | 'package' }, +): string | null { + if (!builds?.workerName || builds.workerName === target.workerName) { + return null; + } + const source = + target.workerNameSource === 'config' + ? 'cloudflare.name in void.config.ts or void.lock.json' + : 'the package.json name'; + return [ + `deploy: Workers Builds is connected to the Worker "${builds.workerName}", but this project deploys "${target.workerName}" (from ${source}).`, + `Set cloudflare.name to "${builds.workerName}" in void.config.ts and commit it, or connect this repository to the Worker "${target.workerName}" in Workers Builds.`, + 'Nothing was built or deployed.', + ].join('\n'); +} + +/** Explain a project account that differs from the Workers Builds account, or return null. */ +export function workersBuildsAccountMismatch( + builds: WorkersBuildsContext | null | undefined, + configAccountId: string | undefined, +): string | null { + if (!builds?.accountId || !configAccountId || builds.accountId === configAccountId) { + return null; + } + return [ + `deploy: this project deploys to Cloudflare account ${configAccountId} (cloudflare.account_id in void.config.ts or void.lock.json), but Workers Builds runs in account ${builds.accountId}.`, + `Set cloudflare.account_id to "${builds.accountId}" in void.config.ts and commit it, or connect this repository to Workers Builds in account ${configAccountId}.`, + 'Nothing was built or deployed.', + ].join('\n'); +} + +/** Source metadata for the version message, from Workers Builds. */ +export function workersBuildsVersionSource( + builds: WorkersBuildsContext | null | undefined, +): { commit?: string; branch?: string } | undefined { + if (!builds || (!builds.commit && !builds.branch)) { + return undefined; + } + return { + ...(builds.commit ? { commit: builds.commit } : {}), + ...(builds.branch ? { branch: builds.branch } : {}), + }; +} + +/** + * Append a Wrangler-compatible `deploy` entry for an activated version. Only this process + * writes the file: Cloudflare CLI and build children never receive its path. A write failure + * does not undo the deployment, so it is reported through `warn`. + */ +export function writeDeployOutputEntry( + file: string | null | undefined, + deploy: { + workerName: string; + versionId: string; + url: string | undefined; + workerTag?: string | null; + }, + warn: (message: string) => void, +): void { + if (!file) { + return; + } + const entry: WranglerDeployOutputEntry = { + type: 'deploy', + version: 1, + worker_name: deploy.workerName, + worker_tag: deploy.workerTag ?? null, + version_id: deploy.versionId, + targets: deploy.url ? [deploy.url] : [], + wrangler_environment: undefined, + worker_name_overridden: false, + }; + try { + mkdirSync(dirname(file), { recursive: true }); + appendFileSync(file, `${JSON.stringify({ ...entry, timestamp: new Date().toISOString() })}\n`); + } catch (error) { + warn( + `deploy: the deployment succeeded, but its result could not be written to ${file}: ${error instanceof Error ? error.message : String(error)}`, + ); + } +} diff --git a/packages/void/test/unit/cloudflare-auth.test.ts b/packages/void/test/unit/cloudflare-auth.test.ts index 8b8d90ea3b..2633d7d1ad 100644 --- a/packages/void/test/unit/cloudflare-auth.test.ts +++ b/packages/void/test/unit/cloudflare-auth.test.ts @@ -12,6 +12,7 @@ const SESSION = { afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); describe('Cloudflare authentication', () => { @@ -67,6 +68,30 @@ describe('Cloudflare authentication', () => { ).rejects.toThrow('CLOUDFLARE_API_TOKEN'); }); + it('never opens browser login in Workers Builds, even on a terminal', async () => { + vi.stubEnv('WORKERS_CI', '1'); + const descriptors = [process.stdin, process.stdout].map((stream) => { + const descriptor = Object.getOwnPropertyDescriptor(stream, 'isTTY'); + Object.defineProperty(stream, 'isTTY', { configurable: true, value: true }); + return { stream, descriptor }; + }); + const runWrangler = vi.fn(() => ({ status: 1, stderr: '', stdout: '', data: '' })); + try { + await expect(ensureCloudflareAuthentication({ runWrangler })).rejects.toThrow( + 'CLOUDFLARE_API_TOKEN', + ); + } finally { + for (const { stream, descriptor } of descriptors) { + if (descriptor) { + Object.defineProperty(stream, 'isTTY', descriptor); + } else { + Reflect.deleteProperty(stream, 'isTTY'); + } + } + } + expect(runWrangler).toHaveBeenCalledExactlyOnceWith({ type: 'auth.whoami' }, true); + }); + it('accepts an explicit API token for a pinned operation without account discovery', async () => { const previous = process.env.CLOUDFLARE_API_TOKEN; process.env.CLOUDFLARE_API_TOKEN = 'scoped-token'; diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 151fd254fa..38af9773c5 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -13976,3 +13976,91 @@ describe('runCloudflareDeploy — previews', () => { expect(wranglerArgs).toEqual([]); }); }); + +describe('Workers Builds', () => { + const BUILDS_SHA = '0123456789abcdef0123456789abcdef01234567'; + + function stubWorkersBuilds(overrides: Record = {}): void { + const env = { + WORKERS_CI: '1', + WORKERS_CI_BUILD_UUID: 'build-1', + WORKERS_CI_BRANCH: 'main', + WORKERS_CI_COMMIT_SHA: BUILDS_SHA, + WRANGLER_CI_OVERRIDE_NAME: 'myapp', + CLOUDFLARE_ACCOUNT_ID: 'acc123', + ...overrides, + }; + for (const [name, value] of Object.entries(env)) { + vi.stubEnv(name, value); + } + } + + async function failedDeploy(root: string, deps: CloudflareDeployDeps): Promise { + const errors: Array = []; + const errorSpy = vi.spyOn(log, 'error').mockImplementation((message) => { + errors.push(String(message)); + }); + try { + await expect( + runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps), + ).rejects.toBeInstanceOf(ExitError); + } finally { + errorSpy.mockRestore(); + } + return errors.join('\n'); + } + + it('fails before any Cloudflare command when Builds is connected to another Worker', async () => { + stubWorkersBuilds({ WRANGLER_CI_OVERRIDE_NAME: 'builds-app' }); + const root = d1Project(PROVISIONED_D1); + const { deps, trace, exitCalls } = harness(); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(trace).toEqual([]); + expect(errors).toContain('Workers Builds is connected to the Worker "builds-app"'); + expect(errors).toContain('this project deploys "myapp"'); + expect(errors).toContain('Set cloudflare.name to "builds-app" in void.config.ts'); + }); + + it('fails before any Cloudflare command when the project account is not the Builds account', async () => { + stubWorkersBuilds({ CLOUDFLARE_ACCOUNT_ID: 'builds-account' }); + const root = d1Project(PROVISIONED_D1); + const { deps, trace, exitCalls } = harness(); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(trace).toEqual([]); + expect(errors).toContain('deploys to Cloudflare account acc123'); + expect(errors).toContain('Workers Builds runs in account builds-account'); + }); + + it('checks the Builds Worker before building a static site', async () => { + stubWorkersBuilds({ WRANGLER_CI_OVERRIDE_NAME: 'builds-site' }); + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'dist/index.html': '
', + }); + const { deps, wranglerArgs, exitCalls } = harness(); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(wranglerArgs.map((args) => args[0])).not.toContain('deploy'); + expect(errors).toContain('this project deploys "spaapp" (from the package.json name)'); + }); + + it('deploys the Worker Builds is connected to without prompting', async () => { + stubWorkersBuilds(); + const root = d1Project(PROVISIONED_D1); + const { deps, exitCalls } = harness(); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + }); +}); diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts new file mode 100644 index 0000000000..fa3fb02644 --- /dev/null +++ b/packages/void/test/unit/workers-builds.test.ts @@ -0,0 +1,204 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { + canPromptInTerminal, + readWorkersBuildsContext, + resolveDeployOutputFile, + withRecordedWorkersBuildsEnv, + workersBuildsAccountMismatch, + workersBuildsTargetMismatch, + workersBuildsVersionSource, + writeDeployOutputEntry, +} from '../../src/cli/workers-builds.ts'; + +const SHA = '0123456789abcdef0123456789abcdef01234567'; + +const BUILDS_ENV = { + WORKERS_CI: '1', + WORKERS_CI_BUILD_UUID: 'build-1', + WORKERS_CI_BRANCH: 'main', + WORKERS_CI_COMMIT_SHA: SHA, + WRANGLER_CI_OVERRIDE_NAME: 'my-app', + CLOUDFLARE_ACCOUNT_ID: 'account-1', +}; + +let dir: string | undefined; +afterEach(() => { + vi.unstubAllEnvs(); + if (dir) { + rmSync(dir, { recursive: true, force: true }); + dir = undefined; + } +}); + +function withTerminal(interactive: boolean, run: () => T): T { + const descriptors = [process.stdin, process.stdout].map((stream) => { + const descriptor = Object.getOwnPropertyDescriptor(stream, 'isTTY'); + Object.defineProperty(stream, 'isTTY', { configurable: true, value: interactive }); + return { stream, descriptor }; + }); + try { + return run(); + } finally { + for (const { stream, descriptor } of descriptors) { + if (descriptor) { + Object.defineProperty(stream, 'isTTY', descriptor); + } else { + Reflect.deleteProperty(stream, 'isTTY'); + } + } + } +} + +describe('Workers Builds detection', () => { + it('reads the Builds context only when WORKERS_CI is set', () => { + expect(readWorkersBuildsContext({})).toBeNull(); + expect(readWorkersBuildsContext({ WORKERS_CI: '0', WORKERS_CI_BRANCH: 'main' })).toBeNull(); + expect(readWorkersBuildsContext(BUILDS_ENV)).toEqual({ + buildId: 'build-1', + branch: 'main', + commit: SHA, + workerName: 'my-app', + accountId: 'account-1', + }); + }); + + it('drops a commit value that is not a full SHA, as deploy-hook builds report the branch', () => { + expect( + readWorkersBuildsContext({ ...BUILDS_ENV, WORKERS_CI_COMMIT_SHA: 'main' })?.commit, + ).toBeNull(); + }); + + it('never prompts in Workers Builds, even on a terminal', () => { + withTerminal(true, () => { + expect(canPromptInTerminal({})).toBe(true); + expect(canPromptInTerminal(BUILDS_ENV)).toBe(false); + }); + withTerminal(false, () => { + expect(canPromptInTerminal({})).toBe(false); + }); + }); + + it('records the Builds context and output file once, before project code can change them', () => { + const recorded = withRecordedWorkersBuildsEnv( + {}, + { ...BUILDS_ENV, WRANGLER_OUTPUT_FILE_PATH: '/tmp/builds/output.json' }, + ); + expect(recorded.workersBuilds?.workerName).toBe('my-app'); + expect(recorded.deployOutputFile).toMatch(/output\.json$/); + expect(withRecordedWorkersBuildsEnv(recorded, {})).toEqual(recorded); + expect(withRecordedWorkersBuildsEnv({}, {})).toEqual({ + workersBuilds: null, + deployOutputFile: null, + }); + }); +}); + +describe('Workers Builds target checks', () => { + const builds = readWorkersBuildsContext(BUILDS_ENV); + + it('accepts the Worker Builds is connected to', () => { + expect( + workersBuildsTargetMismatch(builds, { workerName: 'my-app', workerNameSource: 'config' }), + ).toBeNull(); + expect( + workersBuildsTargetMismatch(null, { workerName: 'other', workerNameSource: 'config' }), + ).toBeNull(); + }); + + it('names both Workers and the fix when the project deploys another Worker', () => { + const message = workersBuildsTargetMismatch(builds, { + workerName: 'other-app', + workerNameSource: 'package', + }); + expect(message).toContain('Workers Builds is connected to the Worker "my-app"'); + expect(message).toContain('this project deploys "other-app" (from the package.json name)'); + expect(message).toContain('Set cloudflare.name to "my-app" in void.config.ts'); + expect(message).toContain('Nothing was built or deployed.'); + }); + + it('rejects a project account that differs from the Builds account', () => { + expect(workersBuildsAccountMismatch(builds, undefined)).toBeNull(); + expect(workersBuildsAccountMismatch(builds, 'account-1')).toBeNull(); + expect(workersBuildsAccountMismatch(builds, 'account-2')).toContain( + 'Set cloudflare.account_id to "account-1" in void.config.ts', + ); + }); + + it('reports the commit and branch for the version message', () => { + expect(workersBuildsVersionSource(builds)).toEqual({ commit: SHA, branch: 'main' }); + expect(workersBuildsVersionSource(null)).toBeUndefined(); + expect(workersBuildsVersionSource(readWorkersBuildsContext({ WORKERS_CI: '1' }))).toBe( + undefined, + ); + }); +}); + +describe('Wrangler-compatible deploy output', () => { + it('resolves WRANGLER_OUTPUT_FILE_PATH before WRANGLER_OUTPUT_FILE_DIRECTORY', () => { + expect(resolveDeployOutputFile({})).toBeNull(); + expect( + resolveDeployOutputFile({ + WRANGLER_OUTPUT_FILE_PATH: '/tmp/a/output.json', + WRANGLER_OUTPUT_FILE_DIRECTORY: '/tmp/b', + }), + ).toMatch(/\/tmp\/a\/output\.json$/); + expect(resolveDeployOutputFile({ WRANGLER_OUTPUT_FILE_DIRECTORY: '/tmp/b' })).toMatch( + /\/tmp\/b\/wrangler-output-[\d-]+_[\d-]+_\d+-[0-9a-f]{6}\.json$/, + ); + }); + + it('appends one ND-JSON deploy entry and keeps earlier entries', () => { + dir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); + const file = join(dir, 'nested', 'output.json'); + writeDeployOutputEntry( + file, + { workerName: 'my-app', versionId: 'version-1', url: 'https://my-app.example.workers.dev' }, + () => {}, + ); + writeDeployOutputEntry( + file, + { workerName: 'my-app', versionId: 'version-2', url: undefined }, + () => {}, + ); + const entries = readFileSync(file, 'utf8') + .trimEnd() + .split('\n') + .map((line) => JSON.parse(line) as Record); + expect(entries).toHaveLength(2); + expect(entries[0]).toEqual({ + type: 'deploy', + version: 1, + worker_name: 'my-app', + worker_tag: null, + version_id: 'version-1', + targets: ['https://my-app.example.workers.dev'], + worker_name_overridden: false, + timestamp: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/), + }); + expect(entries[1]).toMatchObject({ version_id: 'version-2', targets: [] }); + }); + + it('warns instead of failing when the output file cannot be written', () => { + dir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); + const blocker = join(dir, 'file'); + writeFileSync(blocker, ''); + const warnings: Array = []; + writeDeployOutputEntry( + join(blocker, 'output.json'), + { workerName: 'my-app', versionId: 'version-1', url: undefined }, + (message) => warnings.push(message), + ); + expect(warnings).toEqual([ + expect.stringContaining('the deployment succeeded, but its result could not be written'), + ]); + }); + + it('writes nothing without an output file', () => { + const warn = vi.fn(); + writeDeployOutputEntry(null, { workerName: 'my-app', versionId: 'v', url: undefined }, warn); + expect(warn).not.toHaveBeenCalled(); + }); +}); From c1436b7f3b1282d65719fa5985532bc421f5da98 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 10:16:27 +0100 Subject: [PATCH 02/25] feat(cloudflare): report deploys to WRANGLER_OUTPUT_FILE_PATH --- .../void/src/cli/deploy-cloudflare-publish.ts | 9 +++ .../void/src/cli/deploy-cloudflare-static.ts | 8 +- packages/void/src/cli/deploy-cloudflare.ts | 1 + .../void/test/unit/cloudflare-deploy.test.ts | 81 +++++++++++++++++++ 4 files changed, 98 insertions(+), 1 deletion(-) diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index faafd6b4fa..8d7484c216 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -23,6 +23,7 @@ import { formatDeploySummary } from './deploy-summary.ts'; import type { CloudflareDeployDeps } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; import { note } from './output.ts'; +import { writeDeployOutputEntry } from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; /** Upload the verified Worker as a candidate version, probe it, and activate it. */ @@ -39,6 +40,8 @@ export async function publishCloudflareWorker(input: { readonly preflight: CloudflarePreflight; readonly build: CloudflareBuild; readonly migration: CloudflareMigration; + /** The recorded Wrangler output file, or null. */ + readonly deployOutputFile: string | null | undefined; }): Promise { const { root, deps, exit, cliLog, reporter, atomic, detectedFramework } = input; const { initialCloudflareCandidate } = input; @@ -172,6 +175,12 @@ export async function publishCloudflareWorker(input: { execution, cliLog, }); + // Builds and other Wrangler-aware CI read the result from the trusted output file. + writeDeployOutputEntry( + input.deployOutputFile, + { workerName, versionId: execution.versionId, url: execution.previewUrl }, + (message) => log.warn(message), + ); note( formatDeploySummary({ workerName, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 28f99ffca7..cbfdc8b107 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -77,7 +77,7 @@ import { detectPreset } from './preset.ts'; import type { StaticPreset, FrameworkPreset } from './preset.ts'; import { deleteEnvVarCaseAware } from './provision.ts'; import type { AssetConfig, DeployManifest } from './types.ts'; -import { workersBuildsTargetMismatch } from './workers-builds.ts'; +import { workersBuildsTargetMismatch, writeDeployOutputEntry } from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; /** Default runtime date for static and framework Workers that set none. */ @@ -686,6 +686,12 @@ export async function runCloudflareStaticDeploy( execution, cliLog, }); + // Builds and other Wrangler-aware CI read the result from the trusted output file. + writeDeployOutputEntry( + options.deployOutputFile, + { workerName, versionId: execution.versionId, url: execution.previewUrl }, + (message) => log.warn(message), + ); note(formatDeploySummary({ workerName, typeLabel }), execution.previewUrl); printDeploySuccess(); } diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 2a33937e14..da6fc3f305 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -226,6 +226,7 @@ export async function runCloudflareDeploy( detectedFramework, initialCloudflareCandidate, migration, + deployOutputFile: options.deployOutputFile, }); } catch (error) { if (error !== stop) { diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 38af9773c5..fcce6542c6 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14054,6 +14054,87 @@ describe('Workers Builds', () => { expect(errors).toContain('this project deploys "spaapp" (from the package.json name)'); }); + it('reports the activated version to WRANGLER_OUTPUT_FILE_PATH from the parent only', async () => { + const outputDir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); + const outputFile = join(outputDir, 'output.json'); + try { + stubWorkersBuilds({ WRANGLER_OUTPUT_FILE_PATH: outputFile }); + const root = d1Project(PROVISIONED_D1); + const { deps, exitCalls } = harness(); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + const entries = readFileSync(outputFile, 'utf8') + .trimEnd() + .split('\n') + .map((line) => JSON.parse(line) as Record); + expect(entries).toEqual([ + expect.objectContaining({ + type: 'deploy', + version: 1, + worker_name: 'myapp', + worker_tag: null, + version_id: '22222222-2222-4222-8222-222222222222', + targets: ['https://preview.example.workers.dev'], + worker_name_overridden: false, + }), + ]); + // Cloudflare CLI children and project-code children never see the output file. + expect(deployChildEnv('acc123', 'https://api.cloudflare.com/client/v4')).not.toHaveProperty( + 'WRANGLER_OUTPUT_FILE_PATH', + ); + } finally { + rmSync(outputDir, { recursive: true, force: true }); + } + }); + + it('writes no deploy result when activation fails', async () => { + const outputDir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); + const outputFile = join(outputDir, 'output.json'); + try { + stubWorkersBuilds({ WRANGLER_OUTPUT_FILE_PATH: outputFile }); + const root = d1Project(PROVISIONED_D1); + const { deps } = harness({ + activateVersion: async () => ({ ok: false, reason: 'upload-failed', status: 1 }), + }); + + await failedDeploy(root, deps); + + expect(existsSync(outputFile)).toBe(false); + } finally { + rmSync(outputDir, { recursive: true, force: true }); + } + }); + + it('reports a static site deploy to the output file', async () => { + const outputDir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); + try { + stubWorkersBuilds({ WRANGLER_CI_OVERRIDE_NAME: 'spaapp' }); + vi.stubEnv('WRANGLER_OUTPUT_FILE_DIRECTORY', outputDir); + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'dist/index.html': '
', + }); + const { deps, exitCalls } = harness(); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + const [file] = readdirSync(outputDir); + expect(file).toMatch(/^wrangler-output-.*\.json$/); + expect(JSON.parse(readFileSync(join(outputDir, file), 'utf8'))).toMatchObject({ + type: 'deploy', + worker_name: 'spaapp', + version_id: '22222222-2222-4222-8222-222222222222', + }); + } finally { + rmSync(outputDir, { recursive: true, force: true }); + } + }); + it('deploys the Worker Builds is connected to without prompting', async () => { stubWorkersBuilds(); const root = d1Project(PROVISIONED_D1); From a8b9252e6871182ea9811b63e69cacb5e862e52a Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 10:20:11 +0100 Subject: [PATCH 03/25] feat(cloudflare): preflight API token permissions before building --- .../src/cli/deploy-cloudflare-preflight.ts | 40 ++++ .../void/src/cli/deploy-cloudflare-token.ts | 190 +++++++++++++++++ packages/void/src/cli/deploy-types.ts | 2 + .../void/test/unit/cloudflare-deploy.test.ts | 67 ++++++ .../test/unit/deploy-cloudflare-token.test.ts | 200 ++++++++++++++++++ 5 files changed, 499 insertions(+) create mode 100644 packages/void/src/cli/deploy-cloudflare-token.ts create mode 100644 packages/void/test/unit/deploy-cloudflare-token.test.ts diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 40df98e3dd..7cfdcf9472 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -50,6 +50,11 @@ import { discoverRootWranglerConfig, } from './deploy-cloudflare-helpers.ts'; import { chooseCloudflareQueueNames } from './deploy-cloudflare-queues.ts'; +import { + planCloudflareTokenProbes, + readCloudflareEnvApiToken, + verifyCloudflareTokenPermissions, +} from './deploy-cloudflare-token.ts'; import { log } from './deploy-helpers.ts'; import { resolveWranglerMigrationPattern, @@ -538,6 +543,41 @@ export async function preflightCloudflareWorker(input: { } } + // An API token can lack a product this app uses: the Workers Builds token has no D1, Queues or + // Hyperdrive permission. Read-only probes name every missing permission before provisioning + // or the build. A browser session and an app without these products run no probe. + const apiToken = readCloudflareEnvApiToken(); + const tokenProbes = + apiToken && !existingWorker + ? planCloudflareTokenProbes({ + desired, + configPath, + provision: options.provision === true, + appliesD1Migrations: preBuildMigrations.length > 0 && options.skipMigrations !== true, + }) + : []; + if (apiToken && tokenProbes.length > 0) { + if (!assertUploaderStillPinned()) { + return exit(1); + } + const tokenFailure = await verifyCloudflareTokenPermissions({ + probes: tokenProbes, + accountId, + apiBaseUrl, + token: apiToken, + runWrangler, + fetchImpl: deps.tokenProbeFetch, + workersBuilds: Boolean(options.workersBuilds), + }); + if (tokenFailure) { + log.error(tokenFailure); + return exit(1); + } + cliLog.info('cloudflare_token_permissions', { + products: tokenProbes.map((probe) => probe.kind), + }); + } + // Sandbox needs Workers Paid. A read-only Containers probe checks the plan and token before // provisioning; its failure cannot tell the two apart, so the message covers both. Apps // without Sandbox never run it. diff --git a/packages/void/src/cli/deploy-cloudflare-token.ts b/packages/void/src/cli/deploy-cloudflare-token.ts new file mode 100644 index 0000000000..31fbb8020a --- /dev/null +++ b/packages/void/src/cli/deploy-cloudflare-token.ts @@ -0,0 +1,190 @@ +import { existsSync } from 'node:fs'; +import type { CloudflareCommandResult, CloudflareOperation } from '@void/deploy-cloudflare'; +import { formatCloudflareChildFailure } from './cloudflare-child-report.ts'; +import { isCleanCloudflareExit } from './cloudflare-process.ts'; +import type { CloudflareDeployDeps } from './deploy-types.ts'; +import { checkCloudflareProvisionDrift } from './provision.ts'; +import type { DesiredResourceSet, ProvisionDriftEntry } from './provision.ts'; + +type TokenProduct = ProvisionDriftEntry['kind'] | 'queues'; + +/** The dashboard name of the account permission each product needs. */ +const TOKEN_PERMISSIONS: Record = { + d1: { product: 'D1', permission: 'D1: Edit' }, + kv: { product: 'Workers KV', permission: 'Workers KV Storage: Edit' }, + r2: { product: 'R2', permission: 'Workers R2 Storage: Edit' }, + hyperdrive: { product: 'Hyperdrive', permission: 'Hyperdrive: Edit' }, + queues: { product: 'Queues', permission: 'Queues: Edit' }, +}; + +/** Cloudflare's authorization error codes: 10000 (authentication), 9109 and 7403 (no access). */ +const PERMISSION_ERROR_CODES = new Set([10_000, 9109, 7403]); + +export type CloudflareTokenProbe = Readonly<{ + kind: TokenProduct; + binding: string; + /** A read-only command, or null for the Hyperdrive REST read. */ + operation: CloudflareOperation | null; +}>; + +/** The API token this deploy uses from the environment, or undefined for a browser session. */ +export function readCloudflareEnvApiToken( + env: NodeJS.ProcessEnv = process.env, +): string | undefined { + return env.CLOUDFLARE_API_TOKEN?.trim() || env.CF_API_TOKEN?.trim() || undefined; +} + +/** + * The read-only probes for the products this deploy will call. Queues are read on every deploy + * that uses them, and D1 on every deploy that applies migrations. Otherwise a product is only + * called to provision, so it is probed only when a resource is missing or `--provision` is + * set. An app that uses none of them runs no probe. + */ +export function planCloudflareTokenProbes(input: { + desired: DesiredResourceSet; + configPath: string; + provision: boolean; + /** This deploy applies D1 migrations. */ + appliesD1Migrations: boolean; +}): Array { + const { desired, provision } = input; + const configPath = existsSync(input.configPath) ? input.configPath : undefined; + const missing = checkCloudflareProvisionDrift(input.configPath, desired).missing; + const needs = (kind: ProvisionDriftEntry['kind']): boolean => + provision || missing.some((entry) => entry.kind === kind); + const probes: Array = []; + if ( + desired.d1 && + (input.appliesD1Migrations || desired.d1.readReplication !== undefined || needs('d1')) + ) { + probes.push({ + kind: 'd1', + binding: desired.d1.binding, + operation: { type: 'd1.list', configPath }, + }); + } + const kv = desired.kvNamespaces[0]; + if (kv && needs('kv')) { + probes.push({ + kind: 'kv', + binding: desired.kvNamespaces.map((namespace) => namespace.binding).join(', '), + operation: { type: 'kv.namespace.list', configPath }, + }); + } + if (desired.r2 && needs('r2')) { + probes.push({ + kind: 'r2', + binding: desired.r2.binding, + operation: { type: 'r2.bucket.info', name: desired.r2.bucketName, configPath }, + }); + } + if (desired.hyperdrive && needs('hyperdrive')) { + probes.push({ kind: 'hyperdrive', binding: desired.hyperdrive.binding, operation: null }); + } + const queue = desired.queues[0]; + if (queue) { + probes.push({ + kind: 'queues', + binding: desired.queues.join(', '), + operation: { type: 'queues.info', name: queue, configPath }, + }); + } + return probes; +} + +/** Cloudflare reported that the token lacks access, as opposed to another failure. */ +function isPermissionDenied(result: CloudflareCommandResult): boolean { + if (result.errorCode !== undefined && PERMISSION_ERROR_CODES.has(result.errorCode)) { + return true; + } + return /\b(?:HTTP )?403\b|forbidden|authentication error|not authorized|unauthorized/i.test( + `${result.stderr}\n${result.stdout}`, + ); +} + +/** A completed read that found no resource still proves the token can use the product. */ +function isConfirmedAbsent(result: CloudflareCommandResult): boolean { + return ( + result.status > 0 && + !result.signal && + !result.error && + (result.failure === 'not-found' || result.errorCode === 10_006) + ); +} + +async function readHyperdrive(options: { + accountId: string; + apiBaseUrl: string; + token: string; + fetchImpl: typeof fetch; +}): Promise { + try { + const response = await options.fetchImpl( + `${options.apiBaseUrl}/accounts/${options.accountId}/hyperdrive/configs?page=1&per_page=1`, + { + headers: { Authorization: `Bearer ${options.token}` }, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }, + ); + return response.ok + ? { status: 0, stdout: '', stderr: '' } + : { status: 1, stdout: '', stderr: `Cloudflare API returned HTTP ${response.status}.` }; + } catch (error) { + return { status: 1, stdout: '', stderr: '', error: String(error) }; + } +} + +/** + * Check, before anything is built, that the deploy's API token can use every product this + * deploy calls. Returns null when it can, or one message listing every missing permission. + */ +export async function verifyCloudflareTokenPermissions(input: { + probes: ReadonlyArray; + accountId: string; + apiBaseUrl: string; + token: string; + runWrangler: NonNullable; + fetchImpl?: typeof fetch; + workersBuilds: boolean; +}): Promise { + const denied: Array = []; + const failed: Array = []; + for (const probe of input.probes) { + const result = probe.operation + ? await Promise.resolve(input.runWrangler(probe.operation, { capture: true })) + : await readHyperdrive({ + accountId: input.accountId, + apiBaseUrl: input.apiBaseUrl, + token: input.token, + fetchImpl: input.fetchImpl ?? fetch, + }); + if (isCleanCloudflareExit(result) || isConfirmedAbsent(result)) { + continue; + } + const { product, permission } = TOKEN_PERMISSIONS[probe.kind]; + if (isPermissionDenied(result)) { + denied.push(` • ${permission} (${product}, for ${probe.binding})`); + } else { + failed.push(` • ${product} (${probe.binding}): ${formatCloudflareChildFailure(result)}`); + } + } + if (denied.length > 0) { + return [ + 'deploy: the Cloudflare API token is missing permissions this app needs:', + ...denied, + input.workersBuilds + ? 'Add them to the Workers Builds API token in My Profile > API Tokens, or choose a token that has them in your Worker under Settings > Builds > API token. Then retry the build.' + : 'Add them to the token in My Profile > API Tokens, or use a token that has them, then retry.', + 'Nothing was built or deployed.', + ].join('\n'); + } + if (failed.length > 0) { + return [ + 'deploy: could not confirm that the Cloudflare API token can use the products this app needs:', + ...failed, + 'Retry the deploy. Nothing was built or deployed.', + ].join('\n'); + } + return null; +} diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index fa4a307a26..a2c44ad214 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -204,6 +204,8 @@ export interface CloudflareDeployDeps { emailDns?: EmailDns; /** `fetch` for the two bearer calls wrangler has no command for (default: global `fetch`). */ emailFetch?: EmailFetch; + /** `fetch` for the Hyperdrive token permission probe (default: global `fetch`). */ + tokenProbeFetch?: typeof fetch; /** Override `process.exit` (tests assert the exit code without halting). */ exit?: (code: number) => never; } diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index fcce6542c6..5dfda0d4e7 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14135,6 +14135,73 @@ describe('Workers Builds', () => { } }); + it('stops before provisioning or building when the Builds token lacks D1', async () => { + stubWorkersBuilds({ CLOUDFLARE_API_TOKEN: 'builds-token' }); + const root = d1Project({ account_id: 'acc123', name: 'myapp' }); + const { deps, trace, exitCalls } = harness(); + deps.runWrangler = operationFixture((args) => { + trace.push(`wrangler:${args[0]}`); + if (args[0] === 'whoami') { + return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; + } + if (args[0] === 'd1') { + return { ...cleanExit, status: 1, stderr: 'Authentication error [code: 10000]' }; + } + return cleanExit; + }); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(trace.at(-1)).toBe('wrangler:d1'); + expect(trace).not.toContain('provision'); + expect(trace).not.toContain('build'); + expect(errors).toContain('• D1: Edit (D1, for DB)'); + expect(errors).toContain('Workers Builds API token'); + }); + + it('runs no D1 probe for an app that does not use D1', async () => { + stubWorkersBuilds({ CLOUDFLARE_API_TOKEN: 'builds-token' }); + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'myapp' }), + 'void.json': JSON.stringify({}), + 'routes/index.ts': `export const GET = () => new Response('ok');`, + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123', name: 'myapp' }), + }); + const { deps, wranglerArgs, exitCalls } = harness(); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + expect(wranglerArgs.some((args) => ['d1', 'kv', 'r2', 'queues'].includes(args[0]))).toBe(false); + }); + + it('probes D1 with an API token before provisioning, and not with a browser session', async () => { + const withoutToken = harness(); + await runCloudflareDeploy( + d1Project(PROVISIONED_D1), + { platform: 'cloudflare', provision: true }, + silentCliLog, + withoutToken.deps, + ); + expect(withoutToken.trace.slice(0, withoutToken.trace.indexOf('provision'))).not.toContain( + 'wrangler:d1', + ); + + vi.stubEnv('CLOUDFLARE_API_TOKEN', 'ci-token'); + const withToken = harness(); + await runCloudflareDeploy( + d1Project(PROVISIONED_D1), + { platform: 'cloudflare', provision: true }, + silentCliLog, + withToken.deps, + ); + expect(withToken.trace.indexOf('wrangler:d1')).toBeGreaterThan(-1); + expect(withToken.trace.indexOf('wrangler:d1')).toBeLessThan( + withToken.trace.indexOf('provision'), + ); + }); + it('deploys the Worker Builds is connected to without prompting', async () => { stubWorkersBuilds(); const root = d1Project(PROVISIONED_D1); diff --git a/packages/void/test/unit/deploy-cloudflare-token.test.ts b/packages/void/test/unit/deploy-cloudflare-token.test.ts new file mode 100644 index 0000000000..d38a02cab7 --- /dev/null +++ b/packages/void/test/unit/deploy-cloudflare-token.test.ts @@ -0,0 +1,200 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { CloudflareCommandResult, CloudflareOperation } from '@void/deploy-cloudflare'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { + planCloudflareTokenProbes, + readCloudflareEnvApiToken, + verifyCloudflareTokenPermissions, +} from '../../src/cli/deploy-cloudflare-token.ts'; +import type { CloudflareTokenProbe } from '../../src/cli/deploy-cloudflare-token.ts'; +import type { DesiredResourceSet } from '../../src/cli/provision.ts'; + +const D1_ID = '52b3bbc7-c473-4b26-9486-1345f5de61c4'; +const KV_ID = '7c07b54c9f2a4d1e8b3f6a0c153aa11a'; + +let dir: string | undefined; +afterEach(() => { + if (dir) { + rmSync(dir, { recursive: true, force: true }); + dir = undefined; + } +}); + +function writeConfig(config: Record): string { + dir = mkdtempSync(join(tmpdir(), 'void-token-probe-')); + const configPath = join(dir, 'wrangler.jsonc'); + writeFileSync(configPath, JSON.stringify({ account_id: 'acc', name: 'app', ...config })); + return configPath; +} + +const desired = (overrides: Partial = {}): DesiredResourceSet => ({ + kvNamespaces: [], + queues: [], + ...overrides, +}); + +const ok: CloudflareCommandResult = { status: 0, stdout: '[]', stderr: '' }; + +function verify( + probes: ReadonlyArray, + respond: (operation: CloudflareOperation) => CloudflareCommandResult, + extra: { fetchImpl?: typeof fetch; workersBuilds?: boolean } = {}, +) { + return verifyCloudflareTokenPermissions({ + probes, + accountId: 'acc', + apiBaseUrl: 'https://api.cloudflare.com/client/v4', + token: 'token', + runWrangler: (operation) => respond(operation), + fetchImpl: extra.fetchImpl, + workersBuilds: extra.workersBuilds ?? false, + }); +} + +describe('planCloudflareTokenProbes', () => { + it('runs no probe for an app without D1, KV, R2, Hyperdrive or Queues', () => { + const configPath = writeConfig({}); + expect( + planCloudflareTokenProbes({ + desired: desired(), + configPath, + provision: false, + appliesD1Migrations: false, + }), + ).toEqual([]); + }); + + it('probes D1 when the deploy applies migrations or creates the database', () => { + const recorded = writeConfig({ + d1_databases: [{ binding: 'DB', database_name: 'app-db', database_id: D1_ID }], + }); + const d1 = desired({ d1: { binding: 'DB', name: 'app-db' } }); + const plan = (configPath: string, appliesD1Migrations: boolean) => + planCloudflareTokenProbes({ + desired: d1, + configPath, + provision: false, + appliesD1Migrations, + }).map((probe) => probe.kind); + expect(plan(recorded, false)).toEqual([]); + expect(plan(recorded, true)).toEqual(['d1']); + expect(plan(writeConfig({}), false)).toEqual(['d1']); + }); + + it('probes KV, R2 and Hyperdrive only when they must be provisioned', () => { + const resources = desired({ + kvNamespaces: [{ binding: 'KV', title: 'app-kv' }], + r2: { binding: 'STORAGE', bucketName: 'app-storage' }, + hyperdrive: { binding: 'HYPERDRIVE', name: 'app-db', connectionString: 'postgres://x' }, + }); + const recorded = writeConfig({ + kv_namespaces: [{ binding: 'KV', id: KV_ID }], + r2_buckets: [{ binding: 'STORAGE', bucket_name: 'app-storage' }], + hyperdrive: [{ binding: 'HYPERDRIVE', id: 'a'.repeat(32) }], + }); + const plan = (provision: boolean) => + planCloudflareTokenProbes({ + desired: resources, + configPath: recorded, + provision, + appliesD1Migrations: false, + }).map((probe) => probe.kind); + expect(plan(false)).toEqual([]); + expect(plan(true)).toEqual(['kv', 'r2', 'hyperdrive']); + }); + + it('always probes Queues, which every deploy reads by name', () => { + expect( + planCloudflareTokenProbes({ + desired: desired({ queues: ['app-jobs'] }), + configPath: writeConfig({}), + provision: false, + appliesD1Migrations: false, + }), + ).toEqual([ + expect.objectContaining({ + kind: 'queues', + operation: expect.objectContaining({ type: 'queues.info', name: 'app-jobs' }), + }), + ]); + }); +}); + +describe('verifyCloudflareTokenPermissions', () => { + const d1Probe: CloudflareTokenProbe = { + kind: 'd1', + binding: 'DB', + operation: { type: 'd1.list' }, + }; + const queuesProbe: CloudflareTokenProbe = { + kind: 'queues', + binding: 'app-jobs', + operation: { type: 'queues.info', name: 'app-jobs' }, + }; + + it('names every missing permission and where to add it in Workers Builds', async () => { + const message = await verify( + [d1Probe, queuesProbe], + (operation) => + operation.type === 'd1.list' + ? { status: 1, stdout: '', stderr: 'Authentication error', errorCode: 10_000 } + : { + status: 1, + stdout: '', + stderr: 'Cloudflare did not return the Queue list. (HTTP 403)', + }, + { workersBuilds: true }, + ); + expect(message).toContain('the Cloudflare API token is missing permissions this app needs:'); + expect(message).toContain('• D1: Edit (D1, for DB)'); + expect(message).toContain('• Queues: Edit (Queues, for app-jobs)'); + expect(message).toContain('Workers Builds API token in My Profile > API Tokens'); + expect(message).toContain('Settings > Builds > API token'); + expect(message).toContain('Nothing was built or deployed.'); + }); + + it('accepts a read that finds no resource', async () => { + const r2Probe: CloudflareTokenProbe = { + kind: 'r2', + binding: 'STORAGE', + operation: { type: 'r2.bucket.info', name: 'app-storage' }, + }; + await expect( + verify([r2Probe], () => ({ status: 1, stdout: '', stderr: 'missing', errorCode: 10_006 })), + ).resolves.toBeNull(); + await expect(verify([d1Probe], () => ok)).resolves.toBeNull(); + }); + + it('reports another failure without claiming a missing permission', async () => { + const message = await verify([d1Probe], () => ({ + status: 1, + stdout: '', + stderr: 'socket hang up', + })); + expect(message).toContain('could not confirm that the Cloudflare API token can use'); + expect(message).not.toContain('D1: Edit'); + }); + + it('reads Hyperdrive over the API with the deploy token', async () => { + const fetchImpl = vi.fn(async () => new Response('{}', { status: 403 })); + const message = await verify( + [{ kind: 'hyperdrive', binding: 'HYPERDRIVE', operation: null }], + () => ok, + { fetchImpl: fetchImpl as unknown as typeof fetch }, + ); + expect(fetchImpl).toHaveBeenCalledWith( + 'https://api.cloudflare.com/client/v4/accounts/acc/hyperdrive/configs?page=1&per_page=1', + expect.objectContaining({ headers: { Authorization: 'Bearer token' } }), + ); + expect(message).toContain('• Hyperdrive: Edit (Hyperdrive, for HYPERDRIVE)'); + expect(message).toContain('Add them to the token in My Profile > API Tokens'); + }); + + it('reads the deploy token from the environment only', () => { + expect(readCloudflareEnvApiToken({})).toBeUndefined(); + expect(readCloudflareEnvApiToken({ CF_API_TOKEN: ' token ' })).toBe('token'); + expect(readCloudflareEnvApiToken({ CLOUDFLARE_API_TOKEN: 'a', CF_API_TOKEN: 'b' })).toBe('a'); + }); +}); From f53dc92649c3893e21a12e2d4eceb53160087995 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 10:23:06 +0100 Subject: [PATCH 04/25] feat(cloudflare): record the Builds commit and branch in the version message --- packages/deploy-cloudflare/src/index.ts | 1 + packages/deploy-cloudflare/src/version.ts | 41 +++++++++++++++++-- .../test/unit/version.test.ts | 40 +++++++++++++++++- .../void/src/cli/cloudflare-operations.ts | 1 + .../void/src/cli/deploy-cloudflare-migrate.ts | 15 +++++-- .../void/src/cli/deploy-cloudflare-publish.ts | 3 ++ .../void/src/cli/deploy-cloudflare-static.ts | 18 +++++--- packages/void/src/cli/deploy-cloudflare.ts | 2 + .../src/cli/platform-installer-workers.ts | 4 +- .../void/test/unit/cloudflare-deploy.test.ts | 35 ++++++++++++++++ .../test/unit/cloudflare-operations.test.ts | 9 +++- .../test/unit/platform-worker-reuse.test.ts | 2 +- 12 files changed, 153 insertions(+), 18 deletions(-) diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index ab5a2aef8b..d7ec43f324 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -58,6 +58,7 @@ export { type CloudflareVersionActivation, type CloudflareVersionActivationOptions, type CloudflareVersionMetadata, + type CloudflareVersionSource, type CloudflareWorkersDevSubdomainLookup, } from './version.ts'; export { diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 6f46706b00..190e755c21 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -57,6 +57,8 @@ export type CloudflareVersionMetadata = triggerConfig: CloudflareTriggerConfig; /** Digest of the complete Worker upload input, when supplied by the caller. */ contentHash?: string; + /** The commit and branch this version was built from, when CI reports them. */ + source?: CloudflareVersionSource; }>; export function cloudflareMigrationSummary( @@ -67,6 +69,12 @@ export function cloudflareMigrationSummary( : metadata?.migrationSummary; } +export type CloudflareVersionSource = Readonly<{ + /** Full 40-character commit SHA. */ + commit?: string; + branch?: string; +}>; + export type CloudflareTriggerConfig = Readonly<{ /** This version retained the existing triggers instead of publishing a snapshot. */ preserve?: boolean; @@ -219,14 +227,21 @@ const MAX_VERSION_MESSAGE_BYTES = 1000; export function encodeCloudflareVersionMessage( history: ReadonlyArray | MigrationSummary | null, triggerConfig?: CloudflareTriggerConfig, - contentHash?: string, + extra: Readonly<{ contentHash?: string; source?: CloudflareVersionSource }> = {}, ): string { + const source = parseVersionSource(extra.source); const migrationState = history && 'digest' in history ? { migrations: null, migrationSummary: history } : { migrations: history }; const metadata: CloudflareVersionMetadata = triggerConfig - ? { schema: 2, ...migrationState, triggerConfig, ...(contentHash ? { contentHash } : {}) } + ? { + schema: 2, + ...migrationState, + triggerConfig, + ...(extra.contentHash ? { contentHash: extra.contentHash } : {}), + ...(source ? { source } : {}), + } : { schema: 1, ...migrationState }; return `void:${JSON.stringify(metadata)}`; } @@ -370,6 +385,7 @@ export function parseCloudflareVersionMessage( if (!triggerConfig) { return null; } + const source = parseVersionSource(value.source); return { schema: 2, ...migrationState, @@ -377,12 +393,31 @@ export function parseCloudflareVersionMessage( ...(typeof value.contentHash === 'string' && /^[a-f0-9]{64}$/.test(value.contentHash) ? { contentHash: value.contentHash } : {}), + ...(source ? { source } : {}), }; } catch { return null; } } +/** Keep only a full commit SHA and a bounded branch name; drop anything else. */ +function parseVersionSource(value: unknown): CloudflareVersionSource | undefined { + if (!isRecord(value)) { + return undefined; + } + const commit = + typeof value.commit === 'string' && /^[a-f0-9]{40}$/.test(value.commit) + ? value.commit + : undefined; + const branch = + typeof value.branch === 'string' && value.branch.length > 0 && value.branch.length <= 255 + ? value.branch + : undefined; + return commit || branch + ? { ...(commit ? { commit } : {}), ...(branch ? { branch } : {}) } + : undefined; +} + /** * Capture shared configuration published after activation: routes, workers.dev / preview flags, * crons, queue consumers, workflows, Email Routing addresses, and explicit observability. @@ -1467,7 +1502,7 @@ async function activateCloudflareVersionWithSecretsFile( ? encodeCloudflareVersionMessage( desiredMetadata.migrations ?? desiredMetadata.migrationSummary ?? null, desiredTriggerConfig, - desiredMetadata.contentHash, + { contentHash: desiredMetadata.contentHash, source: desiredMetadata.source }, ) : options.message; const versionedPreviousTriggerConfigWithTraffic = diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index a4e5730789..df3ef8c924 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -2580,12 +2580,17 @@ describe('Cloudflare version activation', () => { it('uses the last published traffic values while adding an ordinary cron', async () => { let applied: Record | undefined; + const uploadedMessages: Array = []; const base = runner(); const runWrangler = operationFixture((args: Array) => { if (args[0] === 'triggers') { applied = readConfigArg(args); return ok(); } + if (args[0] === 'versions' && args[1] === 'upload') { + const index = args.indexOf('--message'); + uploadedMessages.push(index === -1 ? undefined : args[index + 1]); + } return base(args); }); const desired = triggersWith({ @@ -2604,7 +2609,7 @@ describe('Cloudflare version activation', () => { preview_urls: true, routes: [{ pattern: 'app.example.com', custom_domain: true }], }, - message: encodeCloudflareVersionMessage([], desired), + message: encodeCloudflareVersionMessage([], desired, { source: { branch: 'main' } }), fetch: async () => Response.json({ ready: true }), }), ).resolves.toMatchObject({ ok: true }); @@ -2614,6 +2619,12 @@ describe('Cloudflare version activation', () => { routes: [{ pattern: 'app.example.com', custom_domain: true }], triggers: { crons: ['0 * * * *'] }, }); + // Resolving the preserved traffic re-encodes the message and keeps its source. + expect(uploadedMessages).toHaveLength(1); + expect(parseCloudflareVersionMessage(uploadedMessages[0])).toMatchObject({ + source: { branch: 'main' }, + triggerConfig: { workers_dev: false }, + }); }); it('continues an opaque handoff for a later code-only deployment', async () => { @@ -3110,7 +3121,9 @@ describe('Cloudflare version activation', () => { const triggers = triggersWith({ preview_urls: false }); const digest = 'a'.repeat(64); expect( - parseCloudflareVersionMessage(encodeCloudflareVersionMessage([], triggers, digest)), + parseCloudflareVersionMessage( + encodeCloudflareVersionMessage([], triggers, { contentHash: digest }), + ), ).toMatchObject({ contentHash: digest }); expect( parseCloudflareVersionMessage( @@ -3119,6 +3132,29 @@ describe('Cloudflare version activation', () => { ).not.toHaveProperty('contentHash'); }); + it('round-trips the source commit and branch, dropping invalid values', () => { + const triggers = triggersWith({ preview_urls: false }); + const commit = '0123456789abcdef0123456789abcdef01234567'; + expect( + parseCloudflareVersionMessage( + encodeCloudflareVersionMessage([], triggers, { source: { commit, branch: 'main' } }), + ), + ).toMatchObject({ source: { commit, branch: 'main' } }); + expect( + parseCloudflareVersionMessage( + encodeCloudflareVersionMessage([], triggers, { source: { commit: 'main' } }), + ), + ).not.toHaveProperty('source'); + expect( + parseCloudflareVersionMessage( + `void:${JSON.stringify({ schema: 2, migrations: [], triggerConfig: triggers, source: { commit: 'x', branch: 7 } })}`, + ), + ).not.toHaveProperty('source'); + expect(encodeCloudflareVersionMessage([], undefined, { source: { branch: 'main' } })).toBe( + 'void:{"schema":1,"migrations":[]}', + ); + }); + // The Cloudflare CLI applies its Email Routing plan inside `triggers deploy`, reading the // config's `addresses`. The trigger-only config Void hands it must therefore carry the // snapshot's addresses verbatim — and carry NOTHING when the snapshot has none, because an diff --git a/packages/void/src/cli/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index 753abb9771..6b0c9236af 100644 --- a/packages/void/src/cli/cloudflare-operations.ts +++ b/packages/void/src/cli/cloudflare-operations.ts @@ -517,6 +517,7 @@ export async function activateCloudflareExistingVersion( const message = encodeCloudflareVersionMessage( target.metadata.migrations ?? target.metadata.migrationSummary ?? null, targetTriggerConfig, + { source: target.metadata.source }, ); const ownerBeforeActivation = await readActiveCloudflareVersionId(context); if (ownerBeforeActivation !== current.id) { diff --git a/packages/void/src/cli/deploy-cloudflare-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index 18ccaf7826..31da6eaf5d 100644 --- a/packages/void/src/cli/deploy-cloudflare-migrate.ts +++ b/packages/void/src/cli/deploy-cloudflare-migrate.ts @@ -18,6 +18,8 @@ import type { CloudflareDeployDeps } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; import { getErrorMessage } from './output.ts'; import { readDeploymentPlatform } from './project.ts'; +import { workersBuildsVersionSource } from './workers-builds.ts'; +import type { WorkersBuildsContext } from './workers-builds.ts'; export type CloudflareMigration = Awaited>; @@ -31,6 +33,7 @@ type MigrationInput = { readonly build: CloudflareBuild; readonly skipMigrations?: boolean; readonly onD1Restore: (command: string) => void; + readonly workersBuilds?: WorkersBuildsContext | null; }; /** Verify the build and prepare migrations for the deploy's pre-upload check. */ @@ -51,10 +54,14 @@ export async function prepareCloudflareWorkerMigrations(input: MigrationInput): const migrationHistory = input.skipMigrations ? null : migrations.map((migration) => migration.name); - const message = encodeCloudflareVersionMessage(migrationHistory, { - ...readCloudflareTriggerConfig(input.build.generatedConfigPath, configPath), - ...(input.preflight.existingWorker ? { preserve: true } : {}), - }); + const message = encodeCloudflareVersionMessage( + migrationHistory, + { + ...readCloudflareTriggerConfig(input.build.generatedConfigPath, configPath), + ...(input.preflight.existingWorker ? { preserve: true } : {}), + }, + { source: workersBuildsVersionSource(input.workersBuilds) }, + ); // Persistent Better Auth secret: adopted when present, otherwise generated once and verified, // before the first remote migration or upload. diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 8d7484c216..ecdb08d322 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -24,6 +24,7 @@ import type { CloudflareDeployDeps } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; import { note } from './output.ts'; import { writeDeployOutputEntry } from './workers-builds.ts'; +import type { WorkersBuildsContext } from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; /** Upload the verified Worker as a candidate version, probe it, and activate it. */ @@ -42,6 +43,8 @@ export async function publishCloudflareWorker(input: { readonly migration: CloudflareMigration; /** The recorded Wrangler output file, or null. */ readonly deployOutputFile: string | null | undefined; + /** Workers Builds as recorded before project code ran. */ + readonly workersBuilds: WorkersBuildsContext | null | undefined; }): Promise { const { root, deps, exit, cliLog, reporter, atomic, detectedFramework } = input; const { initialCloudflareCandidate } = input; diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index cbfdc8b107..6a0eb7d636 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -77,7 +77,11 @@ import { detectPreset } from './preset.ts'; import type { StaticPreset, FrameworkPreset } from './preset.ts'; import { deleteEnvVarCaseAware } from './provision.ts'; import type { AssetConfig, DeployManifest } from './types.ts'; -import { workersBuildsTargetMismatch, writeDeployOutputEntry } from './workers-builds.ts'; +import { + workersBuildsTargetMismatch, + workersBuildsVersionSource, + writeDeployOutputEntry, +} from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; /** Default runtime date for static and framework Workers that set none. */ @@ -573,10 +577,14 @@ export async function runCloudflareStaticDeploy( } const message = options.preview === undefined - ? encodeCloudflareVersionMessage([], { - ...readCloudflareTriggerConfig(staticConfigPath, configPath), - ...(existingWorker ? { preserve: true } : {}), - }) + ? encodeCloudflareVersionMessage( + [], + { + ...readCloudflareTriggerConfig(staticConfigPath, configPath), + ...(existingWorker ? { preserve: true } : {}), + }, + { source: workersBuildsVersionSource(options.workersBuilds) }, + ) : ''; const cfOutput = usesCf ? await prepareCfStaticBuildOutput({ diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index da6fc3f305..92d3e9c425 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -215,6 +215,7 @@ export async function runCloudflareDeploy( const migration = await prepareCloudflareWorkerMigrations({ ...deployment, skipMigrations: options.skipMigrations, + workersBuilds: options.workersBuilds, onD1Restore: (command) => { d1RestoreCommand = command; }, @@ -227,6 +228,7 @@ export async function runCloudflareDeploy( initialCloudflareCandidate, migration, deployOutputFile: options.deployOutputFile, + workersBuilds: options.workersBuilds, }); } catch (error) { if (error !== stop) { diff --git a/packages/void/src/cli/platform-installer-workers.ts b/packages/void/src/cli/platform-installer-workers.ts index e5d637af16..b13fbf88c7 100644 --- a/packages/void/src/cli/platform-installer-workers.ts +++ b/packages/void/src/cli/platform-installer-workers.ts @@ -756,7 +756,9 @@ export async function deployPlatformWorker( const operation: CloudflareOperation = { type: options.workerExisted ? 'versions.upload' : 'worker.deploy', configPath, - message: encodeCloudflareVersionMessage([], nextTriggers, uploadedContentHash ?? undefined), + message: encodeCloudflareVersionMessage([], nextTriggers, { + contentHash: uploadedContentHash ?? undefined, + }), }; if (secrets) { const secretsPath = join(directory, 'secrets.json'); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 5dfda0d4e7..0203d7866c 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14202,6 +14202,41 @@ describe('Workers Builds', () => { ); }); + it('records the Builds commit and branch in the version message', async () => { + stubWorkersBuilds(); + const root = d1Project(PROVISIONED_D1); + const { deps } = harness(); + const activate = deps.activateVersion!; + const messages: Array = []; + deps.activateVersion = async (options) => { + messages.push(options.message); + return activate(options); + }; + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(messages).toHaveLength(1); + expect(parseCloudflareVersionMessage(messages[0])).toMatchObject({ + schema: 2, + source: { commit: BUILDS_SHA, branch: 'main' }, + }); + }); + + it('leaves the version message without source metadata outside Builds', async () => { + const root = d1Project(PROVISIONED_D1); + const { deps } = harness(); + const activate = deps.activateVersion!; + const messages: Array = []; + deps.activateVersion = async (options) => { + messages.push(options.message); + return activate(options); + }; + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(parseCloudflareVersionMessage(messages[0])).not.toHaveProperty('source'); + }); + it('deploys the Worker Builds is connected to without prompting', async () => { stubWorkersBuilds(); const root = d1Project(PROVISIONED_D1); diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index e2b74d763e..a0f99f0a81 100644 --- a/packages/void/test/unit/cloudflare-operations.test.ts +++ b/packages/void/test/unit/cloudflare-operations.test.ts @@ -371,7 +371,12 @@ describe('Cloudflare version operations', () => { id: 'v1', createdAt: null, message: null, - metadata: { schema: 2, migrations: ['0000_init.sql'], triggerConfig }, + metadata: { + schema: 2, + migrations: ['0000_init.sql'], + triggerConfig, + source: { commit: '0123456789abcdef0123456789abcdef01234567', branch: 'main' }, + }, }, { id: 'v2', @@ -386,7 +391,7 @@ describe('Cloudflare version operations', () => { args.versions.some((version) => version.versionId === 'v1' && version.percentage === 100), )!; expect(activation[0].type === 'versions.deploy' ? activation[0].message : undefined).toBe( - 'void:{"schema":2,"migrations":["0000_init.sql"],"triggerConfig":{"workers_dev":true,"preview_urls":true,"routes":[],"crons":["0 * * * *"],"queueConsumers":[],"workflows":[]}}', + 'void:{"schema":2,"migrations":["0000_init.sql"],"triggerConfig":{"workers_dev":true,"preview_urls":true,"routes":[],"crons":["0 * * * *"],"queueConsumers":[],"workflows":[]},"source":{"commit":"0123456789abcdef0123456789abcdef01234567","branch":"main"}}', ); expect(activation[0]).not.toHaveProperty('bypassDeploymentChecks'); expect(runner.mock.calls.some(([args]) => args.type === 'triggers.deploy')).toBe(true); diff --git a/packages/void/test/unit/platform-worker-reuse.test.ts b/packages/void/test/unit/platform-worker-reuse.test.ts index 5a4646c982..0f76fdf6e9 100644 --- a/packages/void/test/unit/platform-worker-reuse.test.ts +++ b/packages/void/test/unit/platform-worker-reuse.test.ts @@ -98,7 +98,7 @@ async function attemptReuse(input: { 'workers/message': encodeCloudflareVersionMessage( [], triggers, - input.missingAnnotationHash ? undefined : (input.annotationHash ?? originalHash!), + input.missingAnnotationHash ? {} : { contentHash: input.annotationHash ?? originalHash! }, ), }, resources: { From da380b3666310937a36a52fc4d07588c01bb1f35 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 10:24:51 +0100 Subject: [PATCH 05/25] docs: deploy with Workers Builds --- docs/guide/deployment.md | 11 +++++++++++ docs/integrations/cloudflare.md | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 637907b9cb..750aef646d 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -105,6 +105,17 @@ If your platform supports managed GitHub builds, the GitHub App can deploy on pu If CI runs typechecking before deploy, run `void prepare` after installing dependencies to generate the `.void/` types. +## Deploy with Workers Builds {#workers-builds} + +[Workers Builds](https://developers.cloudflare.com/workers/ci-cd/builds/) deploys your Cloudflare app when you push to GitHub or GitLab, without a workflow file. Connect the repository to your Worker in the Cloudflare dashboard, then use these build settings: + +| Setting | Value | +| -------------- | --------------------------------------- | +| Build command | Leave empty | +| Deploy command | `npx void deploy --platform cloudflare` | + +The Worker name in Workers Builds must match the name Void deploys. The default Workers Builds API token has no D1, Queues, or Hyperdrive access, so most Void apps need extra permissions. See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. + ## Deploy to a team platform Use the API URL from your administrator. In a new or unlinked app: diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 645c634a34..e3ac3c405e 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -246,6 +246,40 @@ jobs: Add the same `--dir` and `--spa` flags as your production deploy. Using npm, Yarn or Bun? Use the setup steps that `void init --github` writes. If an earlier job builds the site, download its output and add `--skip-build`. Preview URLs are public; see [`void deploy --preview`](../reference/cli/deploy.md#void-deploy-preview) for the JSON output, naming rules and limits. +### Deploying with Workers Builds {#workers-builds} + +[Workers Builds](https://developers.cloudflare.com/workers/ci-cd/builds/) runs `void deploy` on every push to your production branch. In the Cloudflare dashboard, go to **Workers & Pages**, then create a Worker from your repository or open an existing Worker and go to **Settings** > **Builds** > **Connect**. Use these build settings: + +| Setting | Value | +| -------------- | -------------------------------------------------------- | +| Build command | Leave empty. `void deploy` builds the app. | +| Deploy command | `npx void deploy --platform cloudflare` | +| Root directory | The folder with `void.config.ts`, if it is not the root. | + +The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts`, or your `package.json` name. If `void.config.ts` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. + +In Workers Builds, Void deploys without prompts or a browser sign-in. It uses the build's API token and account. After a successful deploy, Workers Builds shows the deployment URL, and the version message records the commit and branch. + +#### API token permissions + +The API token that Workers Builds creates includes Workers Scripts, Workers KV Storage, Workers R2 Storage, and Workers Routes Edit. Add the permissions your app needs: + +| Your app uses | Permission | +| ----------------------------------- | --------------- | +| `db/` with D1, the default database | D1 Edit | +| Queues | Queues Edit | +| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | + +Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Builds** > **API token**. Void checks the token before building and lists any missing permission. Features with further requirements, such as [email](#deploying-from-ci), need the same permissions as in other CI. + +#### Variables and branches + +Add `DATABASE_URL` and public `VITE_*` values under **Settings** > **Builds** > **Variables and secrets**. Set server secrets with `void secret put`; they persist across deploys. + +Commit `void.lock.json` when it changes locally. Workers Builds does not save files changed during a build, so on later builds Void finds the resources it created by name. + +Workers Builds also builds non-production branches by default. Void does not support preview deployments from Workers Builds yet, so turn off **Builds for non-production branches** in your Worker's build settings. + ### Databases and secrets For PostgreSQL and MySQL, supply `DATABASE_URL` to the deploy process. Void uses it for Hyperdrive and migrations without writing it to config. MySQL schema changes can partially apply before an error; see [failed MySQL migrations](../guide/database/mysql.md#failed-migrations). From a359b2e5a43eb7423557a4d0d770504abef922e3 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 11:02:27 +0100 Subject: [PATCH 06/25] fix(void): scrub and fence the cf CLI Worker-name override --- .../void/src/cli/cloudflare-operations.ts | 16 ++++--- packages/void/src/cli/deploy-resources.ts | 2 +- packages/void/src/cli/deploy-transport.ts | 45 ++++++++++++------- packages/void/src/cli/workers-builds.ts | 6 ++- .../void/test/unit/cloudflare-deploy.test.ts | 33 +++++++++++++- .../test/unit/cloudflare-operations.test.ts | 10 +++++ .../void/test/unit/workers-builds.test.ts | 8 ++++ 7 files changed, 95 insertions(+), 25 deletions(-) diff --git a/packages/void/src/cli/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index 6b0c9236af..4034ba20dd 100644 --- a/packages/void/src/cli/cloudflare-operations.ts +++ b/packages/void/src/cli/cloudflare-operations.ts @@ -19,7 +19,11 @@ import { join } from 'pathslash'; import { materializeCloudflareConfig, persistCloudflareConfig } from '../cloudflare-config.ts'; import { createCloudflareProcessRunner } from './cloudflare-process.ts'; import type { StatementResult } from './db-execute-results.ts'; -import { findAmbientConfigOverride, findWranglerCiOverrideDotenvFile } from './deploy-transport.ts'; +import { + CI_WORKER_NAME_OVERRIDE_ENV_VARS, + findAmbientConfigOverride, + findWranglerCiOverrideDotenvFile, +} from './deploy-transport.ts'; import { Buffer } from './node-buffer.ts'; import { getErrorMessage } from './output.ts'; import { @@ -841,7 +845,9 @@ function createCloudflareOperationRunner( apiBaseUrl, env: () => { const env = provisionEnv({ accountId, apiBaseUrl }); - deleteEnvVarCaseAware(env, 'WRANGLER_CI_OVERRIDE_NAME'); + for (const name of CI_WORKER_NAME_OVERRIDE_ENV_VARS) { + deleteEnvVarCaseAware(env, name); + } return env; }, }); @@ -859,10 +865,10 @@ function assertNoOperationConfigOverride(root: string): void { 'CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH is set. Void Cloudflare operations use the root Wrangler config only.', ); } - const file = findWranglerCiOverrideDotenvFile(root); - if (file) { + const ciOverride = findWranglerCiOverrideDotenvFile(root); + if (ciOverride) { throw new Error( - `Project file "${file}" sets WRANGLER_CI_OVERRIDE_NAME, which can replace the pinned Worker name. Remove it before running this command.`, + `Project file "${ciOverride.file}" sets ${ciOverride.name}, which can replace the pinned Worker name. Remove it before running this command.`, ); } } diff --git a/packages/void/src/cli/deploy-resources.ts b/packages/void/src/cli/deploy-resources.ts index 042649e709..63abf9e4aa 100644 --- a/packages/void/src/cli/deploy-resources.ts +++ b/packages/void/src/cli/deploy-resources.ts @@ -108,7 +108,7 @@ function suffixedResourceName(workerName: string, suffix: string): string { /** * Worker name as the CF plugin derives it (package.json `name`, then the directory name), - * ignoring `WRANGLER_CI_OVERRIDE_NAME`: deploy scrubs that override from the build. + * ignoring the CI Worker-name overrides: deploy scrubs them from the build. */ export function deriveWorkerName(root: string): string { let pkgName: string | undefined; diff --git a/packages/void/src/cli/deploy-transport.ts b/packages/void/src/cli/deploy-transport.ts index 0ceb894ac0..2fffa6e7be 100644 --- a/packages/void/src/cli/deploy-transport.ts +++ b/packages/void/src/cli/deploy-transport.ts @@ -41,20 +41,29 @@ export function scrubManagedDeployBuildMarkers(env: NodeJS.ProcessEnv): NodeJS.P return env; } +/** + * CI Worker-name overrides: Wrangler reads `WRANGLER_CI_OVERRIDE_NAME` and the `cf` CLI + * reads `CLOUDFLARE_CI_OVERRIDE_WORKER_NAME`. Workers Builds sets both. + */ +export const CI_WORKER_NAME_OVERRIDE_ENV_VARS = [ + 'WRANGLER_CI_OVERRIDE_NAME', + 'CLOUDFLARE_CI_OVERRIDE_WORKER_NAME', +] as const; + /** * Deploy-time env selectors that pin the WRONG worker/config out from under the * top-level config this flow provisions + preflights. Scrubbed from every child env * and fenced in the project dotenv (see below), on top of the provisioner's transport * scrub/fence which owns the endpoint-redirect + `CLOUDFLARE_ENV` vars: - * - `WRANGLER_CI_OVERRIDE_NAME` — the Cloudflare tooling (wrangler and the `cf` CLI) - * applies it AFTER config load (`getCIOverrideName()`), REPLACING the upload name, so a - * bare deploy uploads a worker whose name the generated-config check never validated. + * - the CI Worker-name overrides ({@link CI_WORKER_NAME_OVERRIDE_ENV_VARS}) — Wrangler + * and the `cf` CLI apply them AFTER config load, REPLACING the upload name, so a bare + * deploy uploads a worker whose name the generated-config check never validated. * - `CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH` — the CF Vite plugin points the build at an * ALTERNATE wrangler config, flattening a different binding set into * `dist/ssr/wrangler.json`. */ const DEPLOY_CONFIG_OVERRIDE_ENV_VARS = [ - 'WRANGLER_CI_OVERRIDE_NAME', + ...CI_WORKER_NAME_OVERRIDE_ENV_VARS, 'CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH', ] as const; @@ -63,7 +72,7 @@ const DEPLOY_CONFIG_OVERRIDE_ENV_VARS = [ * `--env` is named (`getDefaultEnvFiles("")`). Void runs its deploy steps through the * `cf` CLI, not wrangler, but this set is kept for a user who runs `wrangler deploy` on * the same config. It also covers the `.env` / `.env.local` files `cf` reads. A repo - * dotenv here would bring back `WRANGLER_CI_OVERRIDE_NAME` after the child-env scrub + * dotenv here would bring back a CI Worker-name override after the child-env scrub * removed it. */ const DEPLOY_WRANGLER_DOTENV_FILES = ['.env', '.env.local', '.env.', '.env..local']; @@ -120,14 +129,18 @@ function findDotenvDeclaration( return names.find((name) => keys.has(caseInsensitive ? name.toLowerCase() : name)); } -/** The first dotenv file wrangler reloads that declares `WRANGLER_CI_OVERRIDE_NAME`. */ +/** The first Wrangler or `cf` dotenv file that declares a CI Worker-name override. */ export function findWranglerCiOverrideDotenvFile( root: string, platform: NodeJS.Platform = process.platform, -): string | undefined { - return DEPLOY_WRANGLER_DOTENV_FILES.find((file) => - findDotenvDeclaration(root, file, ['WRANGLER_CI_OVERRIDE_NAME'], platform), - ); +): { file: string; name: string } | undefined { + for (const file of DEPLOY_WRANGLER_DOTENV_FILES) { + const name = findDotenvDeclaration(root, file, CI_WORKER_NAME_OVERRIDE_ENV_VARS, platform); + if (name) { + return { file, name }; + } + } + return undefined; } /** @@ -144,14 +157,14 @@ export function assertNoConfigOverrideInProjectDotenv( root: string, platform: NodeJS.Platform = process.platform, ): void { - // WRANGLER_CI_OVERRIDE_NAME reaches a deploy through the wrangler dotenv reload. - const ciOverrideFile = findWranglerCiOverrideDotenvFile(root, platform); - if (ciOverrideFile) { + // A CI Worker-name override reaches a deploy through the Wrangler and cf dotenv reload. + const ciOverride = findWranglerCiOverrideDotenvFile(root, platform); + if (ciOverride) { throw new Error( - `the project file "${ciOverrideFile}" sets WRANGLER_CI_OVERRIDE_NAME, which wrangler reloads on ` + + `the project file "${ciOverride.file}" sets ${ciOverride.name}, which the Cloudflare CLI reloads on ` + `every command and applies AFTER config load to REPLACE the deployed worker name — so ` + - `\`wrangler deploy\` would upload a worker whose name was never validated. Remove it from ` + - `"${ciOverrideFile}" (set it in your shell/CI only if you truly need a CI name override).`, + `a deploy would upload a worker whose name was never validated. Remove it from ` + + `"${ciOverride.file}" (set it in your shell/CI only if you truly need a CI name override).`, ); } // CLOUDFLARE_ENV / CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH reach the BUILD via Vite's diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index f9f7475f54..9cd7422917 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -6,7 +6,7 @@ import { dirname, resolve } from 'pathslash'; * Cloudflare Workers Builds (the Cloudflare GitHub/GitLab integration), as recorded before * project code ran. Builds sets `WORKERS_CI=1` and injects a build API token plus * `CLOUDFLARE_ACCOUNT_ID`; it also passes the connected Worker's name in - * `WRANGLER_CI_OVERRIDE_NAME`. + * `WRANGLER_CI_OVERRIDE_NAME` (`CLOUDFLARE_CI_OVERRIDE_WORKER_NAME` for the `cf` CLI). */ export type WorkersBuildsContext = Readonly<{ buildId: string | null; @@ -50,7 +50,9 @@ export function readWorkersBuildsContext( buildId: readNonEmpty(env, 'WORKERS_CI_BUILD_UUID'), branch: readNonEmpty(env, 'WORKERS_CI_BRANCH'), commit: commit && COMMIT_SHA.test(commit) ? commit.toLowerCase() : null, - workerName: readNonEmpty(env, 'WRANGLER_CI_OVERRIDE_NAME'), + workerName: + readNonEmpty(env, 'WRANGLER_CI_OVERRIDE_NAME') ?? + readNonEmpty(env, 'CLOUDFLARE_CI_OVERRIDE_WORKER_NAME'), accountId: readNonEmpty(env, 'CLOUDFLARE_ACCOUNT_ID') ?? readNonEmpty(env, 'CF_ACCOUNT_ID'), }; } diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 0203d7866c..fbaea9313f 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -6142,7 +6142,7 @@ describe('runCloudflareDeploy — non-Cloudflare target guard', () => { } }); -describe('runCloudflareDeploy — worker-name override (WRANGLER_CI_OVERRIDE_NAME)', () => { +describe('runCloudflareDeploy — CI worker-name overrides', () => { it('fails closed when a project dotenv declares WRANGLER_CI_OVERRIDE_NAME', async () => { const root = makeProject({ 'package.json': JSON.stringify({ name: 'myapp' }), @@ -6203,6 +6203,30 @@ describe('runCloudflareDeploy — worker-name override (WRANGLER_CI_OVERRIDE_NAM }; expect(written.name).toBe('myapp'); }); + + it('fails closed when a project dotenv declares CLOUDFLARE_CI_OVERRIDE_WORKER_NAME', async () => { + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'myapp' }), + 'void.json': JSON.stringify({}), + 'routes/index.ts': `export const GET = (c) => c.env.DB.prepare('SELECT 1').first();`, + 'wrangler.jsonc': JSON.stringify(PROVISIONED_D1, null, 2), + '.env.local': 'CLOUDFLARE_CI_OVERRIDE_WORKER_NAME=other-worker\n', + }); + const { deps, trace, exitCalls } = harness(); + await expect( + runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps), + ).rejects.toBeInstanceOf(ExitError); + expect(exitCalls).toEqual([1]); + expect(trace).toEqual([]); + }); + + it('scrubs both CI Worker-name overrides from Cloudflare CLI children', () => { + vi.stubEnv('WRANGLER_CI_OVERRIDE_NAME', 'evil-name'); + vi.stubEnv('CLOUDFLARE_CI_OVERRIDE_WORKER_NAME', 'evil-name'); + const env = deployChildEnv('acc123', 'https://api.cloudflare.com/client/v4'); + expect(env).not.toHaveProperty('WRANGLER_CI_OVERRIDE_NAME'); + expect(env).not.toHaveProperty('CLOUDFLARE_CI_OVERRIDE_WORKER_NAME'); + }); }); describe('runCloudflareDeploy — build-config override fences', () => { @@ -6274,6 +6298,13 @@ describe('assertNoConfigOverrideInProjectDotenv', () => { ); }); + it('rejects CLOUDFLARE_CI_OVERRIDE_WORKER_NAME in a cf dotenv file', () => { + const root = makeProject({ '.env': 'CLOUDFLARE_CI_OVERRIDE_WORKER_NAME=x\n' }); + expect(() => assertNoConfigOverrideInProjectDotenv(root, 'linux')).toThrow( + /CLOUDFLARE_CI_OVERRIDE_WORKER_NAME/, + ); + }); + it('rejects CLOUDFLARE_ENV / CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH in the vite production set', () => { const rootA = makeProject({ '.env.production': 'CLOUDFLARE_ENV=prod\n' }); expect(() => assertNoConfigOverrideInProjectDotenv(rootA, 'linux')).toThrow(/CLOUDFLARE_ENV/); diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index a0f99f0a81..b35b94a1f7 100644 --- a/packages/void/test/unit/cloudflare-operations.test.ts +++ b/packages/void/test/unit/cloudflare-operations.test.ts @@ -613,6 +613,16 @@ describe('Cloudflare version operations', () => { }); describe('Cloudflare D1 operations', () => { + it('rejects a project dotenv that overrides the Worker name for the cf CLI', () => { + const root = project(); + writeFileSync(join(root, '.env'), 'CLOUDFLARE_CI_OVERRIDE_WORKER_NAME=other-worker\n'); + const runner = vi.fn(); + expect(() => resolveCloudflareD1Context(root, 'DB', runner)).toThrow( + /"\.env" sets CLOUDFLARE_CI_OVERRIDE_WORKER_NAME/, + ); + expect(runner).not.toHaveBeenCalled(); + }); + it('resolves the configured migration identity and executes remote SQL as JSON', async () => { const root = project(`{ "name": "my-worker", diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index fa3fb02644..57b49b6593 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -65,6 +65,14 @@ describe('Workers Builds detection', () => { }); }); + it('reads the Worker name from the cf CLI override when the Wrangler one is unset', () => { + const { WRANGLER_CI_OVERRIDE_NAME: _wrangler, ...env } = BUILDS_ENV; + expect( + readWorkersBuildsContext({ ...env, CLOUDFLARE_CI_OVERRIDE_WORKER_NAME: 'cf-app' }) + ?.workerName, + ).toBe('cf-app'); + }); + it('drops a commit value that is not a full SHA, as deploy-hook builds report the branch', () => { expect( readWorkersBuildsContext({ ...BUILDS_ENV, WORKERS_CI_COMMIT_SHA: 'main' })?.commit, From a75c44e5aaaca6fa01aea869ea430e64d86b7ca3 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 11:05:50 +0100 Subject: [PATCH 07/25] feat(void): report the Workers Builds Worker tag --- .../src/cli/deploy-cloudflare-preflight.ts | 21 +++- .../void/src/cli/deploy-cloudflare-publish.ts | 8 +- .../void/src/cli/deploy-cloudflare-static.ts | 21 +++- packages/void/src/cli/deploy-types.ts | 2 +- packages/void/src/cli/workers-builds.ts | 80 +++++++++++++ .../void/test/unit/cloudflare-deploy.test.ts | 88 +++++++++++++- .../void/test/unit/workers-builds.test.ts | 113 ++++++++++++++++-- 7 files changed, 318 insertions(+), 15 deletions(-) diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 7cfdcf9472..af123804d4 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -83,7 +83,7 @@ import type { CliLogger } from './log-file.ts'; import { getErrorMessage } from './output.ts'; import { checkCloudflareProvisionDrift, provisionCloudflareResources } from './provision.ts'; import type { ProvisionDriftEntry } from './provision.ts'; -import { workersBuildsTargetMismatch } from './workers-builds.ts'; +import { confirmWorkersBuildsWorker, workersBuildsTargetMismatch } from './workers-builds.ts'; import { sameMigrationsDir, writeProvisionedWranglerConfig } from './wrangler.ts'; /** Validate source-level native deploy inputs before account operations or project code. */ @@ -205,6 +205,8 @@ export type CloudflareDeploySource = NonNullable< export type CloudflarePreflight = Omit & { workerName: string; + /** The Worker tag Workers Builds confirmed for this deploy, or null. */ + workersBuildsWorkerTag: string | null; emailMap: EmailAddressMapInput | null; schemaFacts: SelfHostSchemaFacts; existingWorker: ExistingCloudflareWorker | null; @@ -299,6 +301,18 @@ export async function preflightCloudflareWorker(input: { source.analysis.workflows, workerName, ); + const buildsWorker = await confirmWorkersBuildsWorker({ + builds: options.workersBuilds, + workerName, + accountId, + apiBaseUrl, + token: readCloudflareEnvApiToken(), + fetchImpl: deps.tokenProbeFetch, + }); + if ('error' in buildsWorker) { + log.error(buildsWorker.error); + return exit(1); + } printDeployContext(workerName, 'Cloudflare'); const localWorkflows = readWorkflowDeclarations({ @@ -543,8 +557,8 @@ export async function preflightCloudflareWorker(input: { } } - // An API token can lack a product this app uses: the Workers Builds token has no D1, Queues or - // Hyperdrive permission. Read-only probes name every missing permission before provisioning + // An API token can lack a product this app uses: older Workers Builds tokens have no D1, + // Queues or Hyperdrive permission. Read-only probes name every missing permission before provisioning // or the build. A browser session and an app without these products run no probe. const apiToken = readCloudflareEnvApiToken(); const tokenProbes = @@ -773,6 +787,7 @@ export async function preflightCloudflareWorker(input: { return { ...target, workerName, + workersBuildsWorkerTag: buildsWorker.workerTag, emailMap, schemaFacts, existingWorker, diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index ecdb08d322..39eb86d40b 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -55,6 +55,7 @@ export async function publishCloudflareWorker(input: { pinnedHandoffLink, accountId, workerName, + workersBuildsWorkerTag, cfUploaderIsPinned, apiBaseUrl, complianceRegion, @@ -181,7 +182,12 @@ export async function publishCloudflareWorker(input: { // Builds and other Wrangler-aware CI read the result from the trusted output file. writeDeployOutputEntry( input.deployOutputFile, - { workerName, versionId: execution.versionId, url: execution.previewUrl }, + { + workerName, + workerTag: workersBuildsWorkerTag, + versionId: execution.versionId, + url: execution.previewUrl, + }, (message) => log.warn(message), ); note( diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 6a0eb7d636..c6d14e99c1 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -51,6 +51,7 @@ import { reportCloudflareActivationFailure, formatCloudflareActivationError, } from './deploy-cloudflare-helpers.ts'; +import { readCloudflareEnvApiToken } from './deploy-cloudflare-token.ts'; import { generateDeployWrapperIfNeeded, resolveStaticDeployPreset, @@ -78,6 +79,7 @@ import type { StaticPreset, FrameworkPreset } from './preset.ts'; import { deleteEnvVarCaseAware } from './provision.ts'; import type { AssetConfig, DeployManifest } from './types.ts'; import { + confirmWorkersBuildsWorker, workersBuildsTargetMismatch, workersBuildsVersionSource, writeDeployOutputEntry, @@ -437,6 +439,18 @@ export async function runCloudflareStaticDeploy( log.error(buildsMismatch); return exit(1); } + const buildsWorker = await confirmWorkersBuildsWorker({ + builds: options.workersBuilds, + workerName, + accountId, + apiBaseUrl, + token: readCloudflareEnvApiToken(), + fetchImpl: deps.tokenProbeFetch, + }); + if ('error' in buildsWorker) { + log.error(buildsWorker.error); + return exit(1); + } let previousWorkflowVersionId: string | undefined; if (options.atomic) { try { @@ -697,7 +711,12 @@ export async function runCloudflareStaticDeploy( // Builds and other Wrangler-aware CI read the result from the trusted output file. writeDeployOutputEntry( options.deployOutputFile, - { workerName, versionId: execution.versionId, url: execution.previewUrl }, + { + workerName, + workerTag: buildsWorker.workerTag, + versionId: execution.versionId, + url: execution.previewUrl, + }, (message) => log.warn(message), ); note(formatDeploySummary({ workerName, typeLabel }), execution.previewUrl); diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index a2c44ad214..ae4588d077 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -204,7 +204,7 @@ export interface CloudflareDeployDeps { emailDns?: EmailDns; /** `fetch` for the two bearer calls wrangler has no command for (default: global `fetch`). */ emailFetch?: EmailFetch; - /** `fetch` for the Hyperdrive token permission probe (default: global `fetch`). */ + /** `fetch` for the Hyperdrive token probe and the Workers Builds Worker check (default: global `fetch`). */ tokenProbeFetch?: typeof fetch; /** Override `process.exit` (tests assert the exit code without halting). */ exit?: (code: number) => never; diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 9cd7422917..5d0f6e4a55 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -15,6 +15,11 @@ export type WorkersBuildsContext = Readonly<{ commit: string | null; /** The Worker this Builds project is connected to. */ workerName: string | null; + /** + * The tag of the Worker this build may deploy. A preview build passes the tag of a + * different Worker, so a deploy to the connected Worker's name fails the check. + */ + matchTag: string | null; accountId: string | null; }>; @@ -53,6 +58,9 @@ export function readWorkersBuildsContext( workerName: readNonEmpty(env, 'WRANGLER_CI_OVERRIDE_NAME') ?? readNonEmpty(env, 'CLOUDFLARE_CI_OVERRIDE_WORKER_NAME'), + matchTag: + readNonEmpty(env, 'WRANGLER_CI_MATCH_TAG') ?? + readNonEmpty(env, 'CLOUDFLARE_CI_MATCH_WORKER_TAG'), accountId: readNonEmpty(env, 'CLOUDFLARE_ACCOUNT_ID') ?? readNonEmpty(env, 'CF_ACCOUNT_ID'), }; } @@ -147,6 +155,78 @@ export function workersBuildsAccountMismatch( ].join('\n'); } +/** + * Check that the Worker this deploy targets is the one Workers Builds allows, as Wrangler + * does with `WRANGLER_CI_MATCH_TAG`. Returns the confirmed Worker tag for the output entry + * (null when there is nothing to check), or an error message. Any failure stops the deploy. + */ +export async function confirmWorkersBuildsWorker(input: { + builds: WorkersBuildsContext | null | undefined; + workerName: string; + accountId: string; + apiBaseUrl: string; + token: string | undefined; + fetchImpl?: typeof fetch; +}): Promise<{ workerTag: string | null } | { error: string }> { + const matchTag = input.builds?.matchTag; + if (!matchTag || !input.token) { + return { workerTag: null }; + } + const retry = (reason: string) => ({ + error: [ + `deploy: could not confirm that Workers Builds may deploy the Worker "${input.workerName}": ${reason}`, + 'Retry the build. Nothing was built or deployed.', + ].join('\n'), + }); + let response: Response; + try { + response = await (input.fetchImpl ?? fetch)( + `${input.apiBaseUrl}/accounts/${encodeURIComponent(input.accountId)}/workers/services/${encodeURIComponent(input.workerName)}`, + { + headers: { Authorization: `Bearer ${input.token}` }, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }, + ); + } catch (error) { + return retry(error instanceof Error ? error.message : String(error)); + } + if (response.status === 404) { + return { + error: [ + `deploy: the Worker "${input.workerName}" that Workers Builds is connected to does not exist in account ${input.accountId}.`, + 'Reconnect this repository to a Worker under Settings > Build in the Cloudflare dashboard, then retry the build.', + 'Nothing was built or deployed.', + ].join('\n'), + }; + } + if (!response.ok) { + return retry(`Cloudflare API returned HTTP ${response.status}.`); + } + let tag: unknown; + try { + const body = await response.json<{ + result?: { default_environment?: { script?: { tag?: unknown } } }; + }>(); + tag = body.result?.default_environment?.script?.tag; + } catch { + tag = undefined; + } + if (typeof tag !== 'string' || tag.length === 0) { + return retry('Cloudflare API returned no Worker tag.'); + } + if (tag !== matchTag) { + return { + error: [ + `deploy: Workers Builds did not allow this build to deploy the Worker "${input.workerName}". This happens in preview builds, which void deploy does not support yet.`, + 'Clear Enable Preview Builds under Settings > Build > Branch control in your Worker. For a production build, retry it.', + 'Nothing was built or deployed.', + ].join('\n'), + }; + } + return { workerTag: tag }; +} + /** Source metadata for the version message, from Workers Builds. */ export function workersBuildsVersionSource( builds: WorkersBuildsContext | null | undefined, diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index fbaea9313f..2e6a325e7b 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14011,19 +14011,53 @@ describe('runCloudflareDeploy — previews', () => { describe('Workers Builds', () => { const BUILDS_SHA = '0123456789abcdef0123456789abcdef01234567'; - function stubWorkersBuilds(overrides: Record = {}): void { + const BUILDS_TAG = 'myapp-tag'; + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + /** + * Stub the Builds environment and the Workers services read that confirms its Worker tag. + * Returns the services URLs read. + */ + function stubWorkersBuilds( + overrides: Record = {}, + service: { tag?: string; status?: number } = {}, + ): Array { const env = { WORKERS_CI: '1', WORKERS_CI_BUILD_UUID: 'build-1', WORKERS_CI_BRANCH: 'main', WORKERS_CI_COMMIT_SHA: BUILDS_SHA, WRANGLER_CI_OVERRIDE_NAME: 'myapp', + WRANGLER_CI_MATCH_TAG: BUILDS_TAG, CLOUDFLARE_ACCOUNT_ID: 'acc123', + CLOUDFLARE_API_TOKEN: 'builds-token', ...overrides, }; for (const [name, value] of Object.entries(env)) { vi.stubEnv(name, value); } + const reads: Array = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string | URL | Request) => { + const href = String(url); + if (!href.includes('/workers/services/')) { + throw new Error(`unexpected fetch ${href}`); + } + reads.push(href); + return Response.json( + { + success: true, + result: { default_environment: { script: { tag: service.tag ?? BUILDS_TAG } } }, + }, + { status: service.status ?? 200 }, + ); + }), + ); + return reads; } async function failedDeploy(root: string, deps: CloudflareDeployDeps): Promise { @@ -14085,6 +14119,55 @@ describe('Workers Builds', () => { expect(errors).toContain('this project deploys "spaapp" (from the package.json name)'); }); + it('confirms the Builds Worker tag with the build token before deploying', async () => { + const reads = stubWorkersBuilds(); + const root = d1Project(PROVISIONED_D1); + const { deps, exitCalls } = harness(); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + expect(reads).toEqual([ + 'https://api.cloudflare.com/client/v4/accounts/acc123/workers/services/myapp', + ]); + const [, init] = vi.mocked(fetch).mock.calls[0]; + expect(init?.headers).toEqual({ Authorization: 'Bearer builds-token' }); + }); + + it('stops before building when Builds passes the tag of another Worker', async () => { + stubWorkersBuilds({}, { tag: 'other-tag' }); + const root = d1Project(PROVISIONED_D1); + const { deps, trace, exitCalls } = harness(); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(trace).not.toContain('build'); + expect(trace).not.toContain('provision'); + expect(errors).toContain('This happens in preview builds'); + expect(errors).toContain('Clear Enable Preview Builds under Settings > Build > Branch control'); + }); + + it('stops before building a static site when the Builds Worker does not exist', async () => { + stubWorkersBuilds({ WRANGLER_CI_OVERRIDE_NAME: 'spaapp' }, { status: 404 }); + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'dist/index.html': '
', + }); + const runStaticBuild = vi.fn(); + const { deps, exitCalls } = harness({ runStaticBuild }); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(runStaticBuild).not.toHaveBeenCalled(); + expect(errors).toContain( + 'the Worker "spaapp" that Workers Builds is connected to does not exist', + ); + }); + it('reports the activated version to WRANGLER_OUTPUT_FILE_PATH from the parent only', async () => { const outputDir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); const outputFile = join(outputDir, 'output.json'); @@ -14105,7 +14188,7 @@ describe('Workers Builds', () => { type: 'deploy', version: 1, worker_name: 'myapp', - worker_tag: null, + worker_tag: BUILDS_TAG, version_id: '22222222-2222-4222-8222-222222222222', targets: ['https://preview.example.workers.dev'], worker_name_overridden: false, @@ -14159,6 +14242,7 @@ describe('Workers Builds', () => { expect(JSON.parse(readFileSync(join(outputDir, file), 'utf8'))).toMatchObject({ type: 'deploy', worker_name: 'spaapp', + worker_tag: BUILDS_TAG, version_id: '22222222-2222-4222-8222-222222222222', }); } finally { diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 57b49b6593..f436355746 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { canPromptInTerminal, + confirmWorkersBuildsWorker, readWorkersBuildsContext, resolveDeployOutputFile, withRecordedWorkersBuildsEnv, @@ -21,6 +22,7 @@ const BUILDS_ENV = { WORKERS_CI_BRANCH: 'main', WORKERS_CI_COMMIT_SHA: SHA, WRANGLER_CI_OVERRIDE_NAME: 'my-app', + WRANGLER_CI_MATCH_TAG: 'tag-1', CLOUDFLARE_ACCOUNT_ID: 'account-1', }; @@ -61,16 +63,20 @@ describe('Workers Builds detection', () => { branch: 'main', commit: SHA, workerName: 'my-app', + matchTag: 'tag-1', accountId: 'account-1', }); }); - it('reads the Worker name from the cf CLI override when the Wrangler one is unset', () => { - const { WRANGLER_CI_OVERRIDE_NAME: _wrangler, ...env } = BUILDS_ENV; + it('reads the cf CLI Worker name and tag when the Wrangler ones are unset', () => { + const { WRANGLER_CI_OVERRIDE_NAME: _name, WRANGLER_CI_MATCH_TAG: _tag, ...env } = BUILDS_ENV; expect( - readWorkersBuildsContext({ ...env, CLOUDFLARE_CI_OVERRIDE_WORKER_NAME: 'cf-app' }) - ?.workerName, - ).toBe('cf-app'); + readWorkersBuildsContext({ + ...env, + CLOUDFLARE_CI_OVERRIDE_WORKER_NAME: 'cf-app', + CLOUDFLARE_CI_MATCH_WORKER_TAG: 'cf-tag', + }), + ).toMatchObject({ workerName: 'cf-app', matchTag: 'cf-tag' }); }); it('drops a commit value that is not a full SHA, as deploy-hook builds report the branch', () => { @@ -144,6 +150,99 @@ describe('Workers Builds target checks', () => { }); }); +describe('Workers Builds Worker tag check', () => { + const builds = readWorkersBuildsContext(BUILDS_ENV); + + function check(response: Response | Error, overrides: { token?: string } = {}) { + const fetchImpl = vi.fn(async () => { + if (response instanceof Error) { + throw response; + } + return response; + }); + const result = confirmWorkersBuildsWorker({ + builds, + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: 'https://api.cloudflare.com/client/v4', + token: 'token' in overrides ? overrides.token : 'builds-token', + fetchImpl, + }); + return { result, fetchImpl }; + } + + const service = (tag: unknown) => + Response.json({ success: true, result: { default_environment: { script: { tag } } } }); + + it('returns the confirmed tag when the Worker matches the Builds tag', async () => { + const { result, fetchImpl } = check(service('tag-1')); + await expect(result).resolves.toEqual({ workerTag: 'tag-1' }); + expect(fetchImpl).toHaveBeenCalledWith( + 'https://api.cloudflare.com/client/v4/accounts/account-1/workers/services/my-app', + expect.objectContaining({ headers: { Authorization: 'Bearer builds-token' } }), + ); + }); + + it('checks nothing outside Builds, without a match tag, or without a token', async () => { + const fetchImpl = vi.fn(); + const base = { + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: 'https://api.cloudflare.com/client/v4', + fetchImpl, + }; + await expect( + confirmWorkersBuildsWorker({ ...base, builds: null, token: 't' }), + ).resolves.toEqual({ workerTag: null }); + await expect( + confirmWorkersBuildsWorker({ + ...base, + builds: readWorkersBuildsContext({ WORKERS_CI: '1' }), + token: 't', + }), + ).resolves.toEqual({ workerTag: null }); + await expect( + confirmWorkersBuildsWorker({ ...base, builds, token: undefined }), + ).resolves.toEqual({ workerTag: null }); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('explains a preview build when the Worker has another tag', async () => { + const { result } = check(service('preview-tag')); + const outcome = await result; + expect(outcome).toHaveProperty('error'); + const message = (outcome as { error: string }).error; + expect(message).toContain('This happens in preview builds'); + expect(message).toContain( + 'Clear Enable Preview Builds under Settings > Build > Branch control', + ); + expect(message).toContain('Nothing was built or deployed.'); + }); + + it('explains a missing Worker', async () => { + const { result } = check(Response.json({ success: false }, { status: 404 })); + await expect(result).resolves.toEqual({ + error: expect.stringContaining( + 'Reconnect this repository to a Worker under Settings > Build', + ), + }); + }); + + it('fails closed with a retry when the Worker cannot be read', async () => { + for (const response of [ + Response.json({ success: false }, { status: 403 }), + service(undefined), + new Response('not json'), + new Error('network down'), + ]) { + const { result } = check(response); + await expect(result).resolves.toEqual({ + error: expect.stringContaining('Retry the build. Nothing was built or deployed.'), + }); + } + }); +}); + describe('Wrangler-compatible deploy output', () => { it('resolves WRANGLER_OUTPUT_FILE_PATH before WRANGLER_OUTPUT_FILE_DIRECTORY', () => { expect(resolveDeployOutputFile({})).toBeNull(); @@ -168,7 +267,7 @@ describe('Wrangler-compatible deploy output', () => { ); writeDeployOutputEntry( file, - { workerName: 'my-app', versionId: 'version-2', url: undefined }, + { workerName: 'my-app', versionId: 'version-2', url: undefined, workerTag: 'tag-1' }, () => {}, ); const entries = readFileSync(file, 'utf8') @@ -186,7 +285,7 @@ describe('Wrangler-compatible deploy output', () => { worker_name_overridden: false, timestamp: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/), }); - expect(entries[1]).toMatchObject({ version_id: 'version-2', targets: [] }); + expect(entries[1]).toMatchObject({ version_id: 'version-2', worker_tag: 'tag-1', targets: [] }); }); it('warns instead of failing when the output file cannot be written', () => { From 14cd499e8eb180207e94b24633a4fac16ff5866a Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 11:06:19 +0100 Subject: [PATCH 08/25] docs: match the Workers Builds dashboard labels --- docs/integrations/cloudflare.md | 8 ++++---- packages/void/src/cli/deploy-cloudflare-token.ts | 2 +- packages/void/test/unit/deploy-cloudflare-token.test.ts | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index e3ac3c405e..b72f38ca52 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -248,7 +248,7 @@ Add the same `--dir` and `--spa` flags as your production deploy. Using npm, Yar ### Deploying with Workers Builds {#workers-builds} -[Workers Builds](https://developers.cloudflare.com/workers/ci-cd/builds/) runs `void deploy` on every push to your production branch. In the Cloudflare dashboard, go to **Workers & Pages**, then create a Worker from your repository or open an existing Worker and go to **Settings** > **Builds** > **Connect**. Use these build settings: +[Workers Builds](https://developers.cloudflare.com/workers/ci-cd/builds/) runs `void deploy` on every push to your production branch. In the Cloudflare dashboard, go to **Workers & Pages**, then create a Worker from your repository or open an existing Worker and connect it under **Settings** > **Build**. Use these build settings: | Setting | Value | | -------------- | -------------------------------------------------------- | @@ -258,7 +258,7 @@ Add the same `--dir` and `--spa` flags as your production deploy. Using npm, Yar The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts`, or your `package.json` name. If `void.config.ts` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. -In Workers Builds, Void deploys without prompts or a browser sign-in. It uses the build's API token and account. After a successful deploy, Workers Builds shows the deployment URL, and the version message records the commit and branch. +In Workers Builds, Void deploys without prompts or a browser sign-in. It uses the build's API token and account. After a successful deploy, Workers Builds links the build to the Worker version it deployed, and the version message records the commit and branch. #### API token permissions @@ -274,11 +274,11 @@ Edit the token in **My Profile** > **API Tokens**, or choose a different token i #### Variables and branches -Add `DATABASE_URL` and public `VITE_*` values under **Settings** > **Builds** > **Variables and secrets**. Set server secrets with `void secret put`; they persist across deploys. +Add `DATABASE_URL` and public `VITE_*` values under **Settings** > **Build** > **Build variables and secrets**. Set server secrets with `void secret put`; they persist across deploys. Commit `void.lock.json` when it changes locally. Workers Builds does not save files changed during a build, so on later builds Void finds the resources it created by name. -Workers Builds also builds non-production branches by default. Void does not support preview deployments from Workers Builds yet, so turn off **Builds for non-production branches** in your Worker's build settings. +Workers Builds also builds non-production branches by default. Void does not support preview builds yet and stops them before building, so clear **Enable Preview Builds** under **Settings** > **Build** > **Branch control**. ### Databases and secrets diff --git a/packages/void/src/cli/deploy-cloudflare-token.ts b/packages/void/src/cli/deploy-cloudflare-token.ts index 31fbb8020a..d9b620e2c1 100644 --- a/packages/void/src/cli/deploy-cloudflare-token.ts +++ b/packages/void/src/cli/deploy-cloudflare-token.ts @@ -174,7 +174,7 @@ export async function verifyCloudflareTokenPermissions(input: { 'deploy: the Cloudflare API token is missing permissions this app needs:', ...denied, input.workersBuilds - ? 'Add them to the Workers Builds API token in My Profile > API Tokens, or choose a token that has them in your Worker under Settings > Builds > API token. Then retry the build.' + ? 'Add them to the Workers Builds API token in My Profile > API Tokens, or choose a token that has them in your Worker under Settings > Build > API token. Then retry the build.' : 'Add them to the token in My Profile > API Tokens, or use a token that has them, then retry.', 'Nothing was built or deployed.', ].join('\n'); diff --git a/packages/void/test/unit/deploy-cloudflare-token.test.ts b/packages/void/test/unit/deploy-cloudflare-token.test.ts index d38a02cab7..375130ce6d 100644 --- a/packages/void/test/unit/deploy-cloudflare-token.test.ts +++ b/packages/void/test/unit/deploy-cloudflare-token.test.ts @@ -151,7 +151,7 @@ describe('verifyCloudflareTokenPermissions', () => { expect(message).toContain('• D1: Edit (D1, for DB)'); expect(message).toContain('• Queues: Edit (Queues, for app-jobs)'); expect(message).toContain('Workers Builds API token in My Profile > API Tokens'); - expect(message).toContain('Settings > Builds > API token'); + expect(message).toContain('Settings > Build > API token'); expect(message).toContain('Nothing was built or deployed.'); }); From d0ec825638a78cdb637bb7b00b891e86d1b763a4 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 11:02:10 +0100 Subject: [PATCH 09/25] docs: update Workers Builds API token permissions --- docs/guide/deployment.md | 2 +- docs/integrations/cloudflare.md | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 750aef646d..e2d145f41d 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -114,7 +114,7 @@ If CI runs typechecking before deploy, run `void prepare` after installing depen | Build command | Leave empty | | Deploy command | `npx void deploy --platform cloudflare` | -The Worker name in Workers Builds must match the name Void deploys. The default Workers Builds API token has no D1, Queues, or Hyperdrive access, so most Void apps need extra permissions. See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. +The Worker name in Workers Builds must match the name Void deploys. The API token that Workers Builds creates includes the permissions most Void apps need. Older or custom tokens, and apps that send email, need [extra permissions](../integrations/cloudflare.md#api-token-permissions). See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. ## Deploy to a team platform diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index b72f38ca52..2d39935bb7 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -262,15 +262,20 @@ In Workers Builds, Void deploys without prompts or a browser sign-in. It uses th #### API token permissions -The API token that Workers Builds creates includes Workers Scripts, Workers KV Storage, Workers R2 Storage, and Workers Routes Edit. Add the permissions your app needs: +The API token that Workers Builds creates includes the permissions most Void apps need, such as D1, Queues, Hyperdrive, Workers KV Storage, and Workers R2 Storage. It does not include email sending: for apps that send [email](../guide/email/domains.md#your-own-cloudflare-account), add **Zone Read** and **Email Sending Edit** to any token. -| Your app uses | Permission | -| ----------------------------------- | --------------- | -| `db/` with D1, the default database | D1 Edit | -| Queues | Queues Edit | -| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | +A token keeps its permissions when Workers Builds changes the permissions of new tokens. If you connected your Worker to Workers Builds earlier, or chose your own token, add the permissions your app needs: -Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Builds** > **API token**. Void checks the token before building and lists any missing permission. Features with further requirements, such as [email](#deploying-from-ci), need the same permissions as in other CI. +| Your app uses | Permission | +| ----------------------------------- | ------------------ | +| `db/` with D1, the default database | D1 Edit | +| Queues | Queues Edit | +| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | +| `email/` handlers | Email Routing Edit | + +Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Build** > **API token**. Void checks the token before building and names any missing permission. + +To deploy with another token, add a build secret named `CLOUDFLARE_API_TOKEN` under **Settings** > **Build** > **Build variables and secrets**. It replaces the build's token. A `CLOUDFLARE_ACCOUNT_ID` build variable replaces the build's account the same way. #### Variables and branches From fc77dd1b80c87384de23c61d7b95d6dea8e835ba Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 11:11:52 +0100 Subject: [PATCH 10/25] docs: list email permissions for every Workers Builds token --- docs/integrations/cloudflare.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 2d39935bb7..969e699475 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -262,16 +262,15 @@ In Workers Builds, Void deploys without prompts or a browser sign-in. It uses th #### API token permissions -The API token that Workers Builds creates includes the permissions most Void apps need, such as D1, Queues, Hyperdrive, Workers KV Storage, and Workers R2 Storage. It does not include email sending: for apps that send [email](../guide/email/domains.md#your-own-cloudflare-account), add **Zone Read** and **Email Sending Edit** to any token. +The API token that Workers Builds creates includes the permissions most Void apps need, such as D1, Queues, Hyperdrive, Workers KV Storage, and Workers R2 Storage. It does not include all the email permissions: for apps that use [email](../guide/email/domains.md#your-own-cloudflare-account), add **Zone Read** and **Email Sending Edit** to any token, plus **Email Routing Edit** for apps with `email/` handlers. A token keeps its permissions when Workers Builds changes the permissions of new tokens. If you connected your Worker to Workers Builds earlier, or chose your own token, add the permissions your app needs: -| Your app uses | Permission | -| ----------------------------------- | ------------------ | -| `db/` with D1, the default database | D1 Edit | -| Queues | Queues Edit | -| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | -| `email/` handlers | Email Routing Edit | +| Your app uses | Permission | +| ----------------------------------- | --------------- | +| `db/` with D1, the default database | D1 Edit | +| Queues | Queues Edit | +| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Build** > **API token**. Void checks the token before building and names any missing permission. From 965381e9ab209ae30444c9cec405df74ece96c5d Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 11:31:49 +0100 Subject: [PATCH 11/25] fix: name the email token permissions Cloudflare checks; clarify Workers Builds branch builds --- docs/guide/deployment.md | 2 +- docs/guide/email/domains.md | 2 +- docs/integrations/cloudflare.md | 17 +++++++++-------- packages/void/src/cli/email-cloudflare.ts | 2 +- packages/void/src/cli/workers-builds.ts | 4 ++++ .../void/test/unit/email-cloudflare.test.ts | 4 ++-- packages/void/test/unit/workers-builds.test.ts | 2 +- 7 files changed, 19 insertions(+), 14 deletions(-) diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index e2d145f41d..5d14117bab 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -114,7 +114,7 @@ If CI runs typechecking before deploy, run `void prepare` after installing depen | Build command | Leave empty | | Deploy command | `npx void deploy --platform cloudflare` | -The Worker name in Workers Builds must match the name Void deploys. The API token that Workers Builds creates includes the permissions most Void apps need. Older or custom tokens, and apps that send email, need [extra permissions](../integrations/cloudflare.md#api-token-permissions). See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. +The Worker name in Workers Builds must match the name Void deploys. The API token that Workers Builds creates includes the permissions most Void apps need. Older or custom tokens, and apps that use email, need [extra permissions](../integrations/cloudflare.md#api-token-permissions). See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. ## Deploy to a team platform diff --git a/docs/guide/email/domains.md b/docs/guide/email/domains.md index d878debac8..d6e19bb524 100644 --- a/docs/guide/email/domains.md +++ b/docs/guide/email/domains.md @@ -53,7 +53,7 @@ Use a mail subdomain to keep existing mail on `acme.com` with its current provid ### Setup {#setup-1} -Sign in with `void cloudflare login`, or use a `CLOUDFLARE_API_TOKEN` with **Zone Read** and **Email Sending Edit** in addition to deploy permissions. Apps with `email/` handlers also need **Email Routing Edit**. If your browser session lacks email permissions, log out and sign in again. Global API Keys aren't supported. +Sign in with `void cloudflare login`, or use a `CLOUDFLARE_API_TOKEN` with **Zone Read** and **Email Sending Edit** in addition to deploy permissions. Apps with `email/` handlers also need **Zone Settings Edit**, **Email Routing Rules Edit**, and **Email Routing Account Rules Read**. If your browser session lacks email permissions, log out and sign in again. Global API Keys aren't supported. Run `void deploy --platform cloudflare`. Void shows the domain, routing, sending, DNS, and handler addresses it would configure. Accept to set up email and deploy. Later deploys reuse the setup. If you decline the initial setup, the app deploys without email. diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 969e699475..f4a79261ba 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -145,7 +145,7 @@ Set these CI secrets and variables as needed: Grant **Workers → Admin** for the account when Void creates the Worker. For subsequent deploys, **Workers → Editor** is enough for the Worker itself. Add **Workers Routes Write** for each zone where the deploy adds, updates, or removes a route or Custom Domain. Grant access to any resources Void reads or provisions, such as D1 or KV. See [Cloudflare Workers roles and permissions](https://developers.cloudflare.com/workers/authorization/workers/). -For email, run `void email setup --platform cloudflare` locally, commit `void.lock.json`, and pass `--require-email` in CI. The token also needs Zone Read and Email Sending Edit, plus Email Routing Edit for apps with `email/` handlers. +For email, run `void email setup --platform cloudflare` locally, commit `void.lock.json`, and pass `--require-email` in CI. The token also needs Zone Read and Email Sending Edit. Apps with `email/` handlers also need Zone Settings Edit, Email Routing Rules Edit, and Email Routing Account Rules Read. #### Cloudflare Access @@ -262,15 +262,16 @@ In Workers Builds, Void deploys without prompts or a browser sign-in. It uses th #### API token permissions -The API token that Workers Builds creates includes the permissions most Void apps need, such as D1, Queues, Hyperdrive, Workers KV Storage, and Workers R2 Storage. It does not include all the email permissions: for apps that use [email](../guide/email/domains.md#your-own-cloudflare-account), add **Zone Read** and **Email Sending Edit** to any token, plus **Email Routing Edit** for apps with `email/` handlers. +The API token that Workers Builds creates includes the permissions most Void apps need, such as D1, Queues, Hyperdrive, Workers KV Storage, and Workers R2 Storage. For apps that use [email](../guide/email/domains.md#your-own-cloudflare-account), add **Zone Read** and **Email Sending Edit**, plus **Zone Settings Edit** for apps with `email/` handlers. A token keeps its permissions when Workers Builds changes the permissions of new tokens. If you connected your Worker to Workers Builds earlier, or chose your own token, add the permissions your app needs: -| Your app uses | Permission | -| ----------------------------------- | --------------- | -| `db/` with D1, the default database | D1 Edit | -| Queues | Queues Edit | -| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | +| Your app uses | Permission | +| ----------------------------------- | ------------------------------------------------------------- | +| `db/` with D1, the default database | D1 Edit | +| Queues | Queues Edit | +| PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | +| `email/` handlers | Email Routing Rules Edit and Email Routing Account Rules Read | Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Build** > **API token**. Void checks the token before building and names any missing permission. @@ -282,7 +283,7 @@ Add `DATABASE_URL` and public `VITE_*` values under **Settings** > **Build** > * Commit `void.lock.json` when it changes locally. Workers Builds does not save files changed during a build, so on later builds Void finds the resources it created by name. -Workers Builds also builds non-production branches by default. Void does not support preview builds yet and stops them before building, so clear **Enable Preview Builds** under **Settings** > **Build** > **Branch control**. +Use `npx void deploy --platform cloudflare` only as the production deploy command. `void deploy` always deploys to production, so running it for another branch would replace your production Worker. Void does not support preview builds yet: clear **Enable Preview Builds** under **Settings** > **Build** > **Branch control**. ### Databases and secrets diff --git a/packages/void/src/cli/email-cloudflare.ts b/packages/void/src/cli/email-cloudflare.ts index b817cf418b..b39e693e30 100644 --- a/packages/void/src/cli/email-cloudflare.ts +++ b/packages/void/src/cli/email-cloudflare.ts @@ -622,7 +622,7 @@ export async function preflightEmail(inputs: EmailCloudflareInputs): Promise 0; const permissions = receivesEmail - ? 'Email Routing Edit + Email Sending Edit' + ? 'Zone Read + Zone Settings Edit + Email Routing Rules Edit + Email Routing Account Rules Read + Email Sending Edit' : 'Zone Read + Email Sending Edit'; const pre: EmailPreflight = { diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 5d0f6e4a55..9fe6d79d01 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -244,6 +244,10 @@ export function workersBuildsVersionSource( * Append a Wrangler-compatible `deploy` entry for an activated version. Only this process * writes the file: Cloudflare CLI and build children never receive its path. A write failure * does not undo the deployment, so it is reported through `warn`. + * + * Workers Builds reads these entries only after the deploy command succeeds, and records a + * version only when `worker_tag` and `version_id` are set. `worker_name_overridden` stays false: + * true makes Workers Builds open a pull request that renames the Worker in a Wrangler config. */ export function writeDeployOutputEntry( file: string | null | undefined, diff --git a/packages/void/test/unit/email-cloudflare.test.ts b/packages/void/test/unit/email-cloudflare.test.ts index 5073ac76f1..6cae58d25f 100644 --- a/packages/void/test/unit/email-cloudflare.test.ts +++ b/packages/void/test/unit/email-cloudflare.test.ts @@ -655,7 +655,7 @@ describe('preflightEmail', () => { { scope: 'all', message: expect.stringContaining( - 'an API token needs Email Routing Edit + Email Sending Edit', + 'an API token needs Zone Read + Zone Settings Edit + Email Routing Rules Edit + Email Routing Account Rules Read + Email Sending Edit', ), }, ]); @@ -835,7 +835,7 @@ describe('preflightEmail', () => { // A Global API Key wins over both an OAuth session and CLOUDFLARE_API_TOKEN in // wrangler's env precedence, so neither alternative works until the key is unset. message: - 'the Cloudflare session is a Global API Key (CLOUDFLARE_API_KEY), which has no bearer to borrow for the subaddressing calls — unset CLOUDFLARE_API_KEY, then run `void cloudflare login` or set CLOUDFLARE_API_TOKEN to a token with Email Routing Edit + Email Sending Edit', + 'the Cloudflare session is a Global API Key (CLOUDFLARE_API_KEY), which has no bearer to borrow for the subaddressing calls — unset CLOUDFLARE_API_KEY, then run `void cloudflare login` or set CLOUDFLARE_API_TOKEN to a token with Zone Read + Zone Settings Edit + Email Routing Rules Edit + Email Routing Account Rules Read + Email Sending Edit', }, { state: 'missing-scopes', diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index f436355746..10982af12d 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -253,7 +253,7 @@ describe('Wrangler-compatible deploy output', () => { }), ).toMatch(/\/tmp\/a\/output\.json$/); expect(resolveDeployOutputFile({ WRANGLER_OUTPUT_FILE_DIRECTORY: '/tmp/b' })).toMatch( - /\/tmp\/b\/wrangler-output-[\d-]+_[\d-]+_\d+-[0-9a-f]{6}\.json$/, + /\/tmp\/b\/wrangler-output-\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_\d{3}-[0-9a-f]{6}\.json$/, ); }); From ebba11558a34c02a0cb31883d6fd0a1abb5c6c8f Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 15:05:51 +0100 Subject: [PATCH 12/25] feat: replace the Workers Builds placeholder Worker on the first deploy --- packages/deploy-cloudflare/src/index.ts | 1 + packages/deploy-cloudflare/src/version.ts | 112 ++++++++- .../test/unit/version.test.ts | 213 ++++++++++++++++++ .../void/src/cli/deploy-cloudflare-auth.ts | 6 + .../void/src/cli/deploy-cloudflare-helpers.ts | 2 +- .../void/src/cli/deploy-cloudflare-migrate.ts | 44 +++- .../src/cli/deploy-cloudflare-preflight.ts | 3 + .../void/src/cli/deploy-cloudflare-publish.ts | 4 + .../void/src/cli/deploy-cloudflare-static.ts | 3 + packages/void/src/cli/workers-builds.ts | 109 ++++++++- .../void/test/unit/cloudflare-deploy.test.ts | 118 ++++++++++ .../void/test/unit/workers-builds.test.ts | 174 +++++++++++++- 12 files changed, 773 insertions(+), 16 deletions(-) diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index d7ec43f324..4b20d783f2 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -37,6 +37,7 @@ export { export { activateCloudflareVersion, STALE_VERSION_HISTORY_DELAYS_MS, + canPreserveCloudflareTraffic, deployCloudflareVersionTriggers, deployCloudflareVersionTraffic, encodeCloudflareVersionMessage, diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 190e755c21..1934061349 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -1128,8 +1128,8 @@ export type CloudflareVersionActivationOptions = { /** Account workers.dev subdomain used when this Worker cannot expose version preview URLs. */ workersDevSubdomain?: string; /** - * Look up the account workers.dev subdomain when a first publish reports no URL and - * `workersDevSubdomain` is not set. The subdomain includes the compliance-region label, for + * Look up the account workers.dev subdomain when an upload reports no URL, workers.dev is + * configured and `workersDevSubdomain` is not set. The subdomain includes the compliance-region label, for * example `team.fed` for FedRAMP High. A thrown error counts as `unavailable`. */ resolveWorkersDevSubdomain?: () => Promise; @@ -1160,6 +1160,14 @@ export type CloudflareVersionActivationOptions = { * read below can legitimately observe a version even though no application was ever deployed. */ allowFirstDeploymentBootstrap?: boolean; + /** + * Production version that the caller proved is a disposable placeholder with no traffic to + * keep, such as the hello-world Worker the Cloudflare dashboard creates before the first + * Workers Builds deploy. While it still serves all traffic, activation publishes over it as a + * first deployment. When another version owns traffic, activation stops with + * `deployment-changed`. + */ + adoptPlaceholderVersionId?: string; fetch?: typeof globalThis.fetch; sleep?: (milliseconds: number) => Promise; /** @@ -1194,6 +1202,45 @@ type InternalCloudflareVersionActivationOptions = CloudflareVersionActivationOpt }; /** Upload, probe, and atomically activate a verified Worker Version. */ +/** + * Report, before remote changes such as database migrations, whether activation can keep the + * live traffic settings. It is false only when the authored config leaves `routes`, + * `workers_dev`, or `preview_urls` unset, nothing recorded their published values, and the + * active version is neither a Void deployment, an empty secret draft, nor the adopted + * placeholder. A failed read returns true, so activation still decides. + */ +export async function canPreserveCloudflareTraffic(options: { + runWrangler: CloudflareCommandRunner; + workerName: string; + configPath: string; + sourceConfigPath: string; + previousTrafficConfig?: CloudflareTrafficConfig; + adoptPlaceholderVersionId?: string; +}): Promise { + const desired = readCloudflareTriggerConfig(options.configPath, options.sourceConfigPath); + if ( + (!desired.preserveRoutes && !desired.preserveWorkersDev && !desired.preservePreviewUrls) || + options.previousTrafficConfig + ) { + return true; + } + const current = await readCurrentProductionVersion(options); + if ( + current.kind !== 'ok' || + current.versionId === null || + current.versionId === options.adoptPlaceholderVersionId + ) { + return true; + } + const inspection = await readCloudflareVersionInspection(options, current.versionId); + return ( + !inspection || + inspection.metadata?.schema === 2 || + inspection.isSecretOnlyDraft || + inspection.draftUnknown + ); +} + export async function activateCloudflareVersion( options: CloudflareVersionActivationOptions, ): Promise { @@ -1246,6 +1293,19 @@ async function activateCloudflareVersionWithSecretsFile( return { ok: false, reason: 'uploader-changed' }; } const previousVersionId = previous.versionId; + const adoptsPlaceholder = + options.adoptPlaceholderVersionId !== undefined && + !options.preserveTriggers && + !options.atomic && + !options.requirePreviewForReadiness; + if (adoptsPlaceholder && previousVersionId !== options.adoptPlaceholderVersionId) { + return { + ok: false, + reason: 'deployment-changed', + activeVersionId: previousVersionId, + rollback: 'not-needed', + }; + } if (options.atomic && options.requirePreviewForReadiness) { return { ok: false, @@ -1472,7 +1532,7 @@ async function activateCloudflareVersionWithSecretsFile( const resolved = resolvePreservedTraffic( desiredTriggerConfig, previousTrafficConfig, - previous.versionId !== null && !(await previousIsSecretOnlyDraft()), + previous.versionId !== null && !adoptsPlaceholder && !(await previousIsSecretOnlyDraft()), ); if (!resolved) { return { @@ -1515,6 +1575,17 @@ async function activateCloudflareVersionWithSecretsFile( ); const alias = `void-ready-${Date.now().toString(36)}`; + if (adoptsPlaceholder) { + // The placeholder serves nothing to keep, and a dashboard-created one has workers.dev and + // previews off, so a staged candidate would have no reachable readiness URL. + return bootstrapFirstDeployment( + { ...options, message }, + previous.versionId, + false, + previousTriggerConfig, + previousIsRestorePlaceholder, + ); + } const bootstrapVoidDraft = !options.preserveTriggers && !options.requirePreviewForReadiness && @@ -1874,8 +1945,41 @@ async function activateCloudflareVersionWithSecretsFile( previousIsRestorePlaceholder, ); } + let workersDevSubdomain = options.workersDevSubdomain; + if ( + desiredTriggerConfig.workers_dev && + !workersDevSubdomain && + options.resolveWorkersDevSubdomain + ) { + // A fresh checkout, such as a Workers Builds clone, has no cached account subdomain. + if (!options.verifyUploader()) { + return { + ok: false, + reason: 'uploader-changed', + versionId, + previousVersionId, + rollback: 'not-needed', + }; + } + let lookup: CloudflareWorkersDevSubdomainLookup; + try { + lookup = await options.resolveWorkersDevSubdomain(); + } catch { + lookup = { ok: false, reason: 'unavailable' }; + } + if (!lookup.ok && lookup.reason === 'uploader-changed') { + return { + ok: false, + reason: 'uploader-changed', + versionId, + previousVersionId, + rollback: 'not-needed', + }; + } + workersDevSubdomain = lookup.ok ? lookup.subdomain : undefined; + } readinessUrl = desiredTriggerConfig.workers_dev - ? workersDevReadinessUrl(options.workerName, options.workersDevSubdomain) + ? workersDevReadinessUrl(options.workerName, workersDevSubdomain) : customRouteReadinessUrl(desiredTriggerConfig.routes); readinessUsesCustomRoute = !desiredTriggerConfig.workers_dev && readinessUrl !== undefined; if (readinessUrl) { diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index df3ef8c924..80f7df7bb4 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it, vi } from 'vite-plus/test'; import { activateCloudflareVersion, assertCloudflareDurableObjectLifecycleSupported, + canPreserveCloudflareTraffic, deployCloudflareVersionTriggers, encodeCloudflareVersionMessage, summarizeCloudflareMigrations, @@ -6760,3 +6761,215 @@ describe('Cloudflare trigger synchronization recovery', () => { expect(fixture.triggerCalls()).toBe(1); }); }); + +describe('Workers Builds placeholder adoption', () => { + const omittedTraffic = triggersWith({ + preserveRoutes: true, + preserveWorkersDev: true, + preservePreviewUrls: true, + }); + const placeholderVersions = ok( + JSON.stringify([{ id: CURRENT, number: 1, annotations: { 'workers/triggered_by': 'upload' } }]), + ); + + it('publishes over the placeholder as a first deployment despite omitted traffic settings', async () => { + const runWrangler = runner({ + versions: placeholderVersions, + bootstrap: ok(`Worker Version ID: ${NEXT}\nhttps://my-worker.example.workers.dev`), + }); + const result = await activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + verifyInheritedSecrets: true, + adoptPlaceholderVersionId: CURRENT, + message: encodeCloudflareVersionMessage([], omittedTraffic), + fetch: async () => Response.json({ ready: true }), + }); + expect(result).toMatchObject({ + ok: true, + versionId: NEXT, + previousVersionId: CURRENT, + }); + expect(runWrangler.mock.calls.filter(([args]) => args[0] === 'deploy')).toHaveLength(1); + expect( + runWrangler.mock.calls.some(([args]) => args[0] === 'versions' && args[1] === 'upload'), + ).toBe(false); + }); + + it('stops when another version replaced the placeholder', async () => { + const runWrangler = runner({ versions: placeholderVersions }); + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + adoptPlaceholderVersionId: CONCURRENT, + message: encodeCloudflareVersionMessage([], omittedTraffic), + }), + ).resolves.toMatchObject({ + ok: false, + reason: 'deployment-changed', + activeVersionId: CURRENT, + rollback: 'not-needed', + }); + expect( + runWrangler.mock.calls.some(([args]) => args[1] === 'upload' || args[0] === 'deploy'), + ).toBe(false); + }); + + it('does not adopt when triggers are preserved or the publish is atomic', async () => { + for (const mode of [{ preserveTriggers: true }, { atomic: true }]) { + const runWrangler = runner({ versions: placeholderVersions }); + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + adoptPlaceholderVersionId: CONCURRENT, + message: encodeCloudflareVersionMessage([], omittedTraffic), + fetch: async () => Response.json({ ready: true }), + sleep: async () => {}, + readinessAttempts: 1, + ...mode, + }), + ).resolves.not.toMatchObject({ reason: 'deployment-changed' }); + } + }); + + it('looks up the workers.dev subdomain for a staged candidate without a preview URL', async () => { + const runWrangler = runner({ upload: ok(`Worker Version ID: ${NEXT}`) }); + const resolveWorkersDevSubdomain = vi.fn(async () => ({ + ok: true as const, + subdomain: 'example', + })); + const fetcher = vi.fn(async () => Response.json({ ready: true })); + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + resolveWorkersDevSubdomain, + message: encodeCloudflareVersionMessage([]), + fetch: fetcher, + }), + ).resolves.toMatchObject({ ok: true, versionId: NEXT }); + expect(resolveWorkersDevSubdomain).toHaveBeenCalledOnce(); + expect(fetcher).toHaveBeenCalledWith( + 'https://my-worker.example.workers.dev/__void/ready', + expect.objectContaining({ + headers: expect.objectContaining({ + 'Cloudflare-Workers-Version-Overrides': `my-worker="${NEXT}"`, + }), + }), + ); + }); + + it('stops before the subdomain lookup when the uploader changed', async () => { + const runWrangler = runner({ upload: ok(`Worker Version ID: ${NEXT}`) }); + const resolveWorkersDevSubdomain = vi.fn(async () => ({ + ok: false as const, + reason: 'uploader-changed' as const, + })); + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + resolveWorkersDevSubdomain, + message: encodeCloudflareVersionMessage([]), + fetch: async () => Response.json({ ready: true }), + }), + ).resolves.toMatchObject({ + ok: false, + reason: 'uploader-changed', + versionId: NEXT, + rollback: 'not-needed', + }); + expect(deployRequests(runWrangler)).toEqual([]); + }); +}); + +describe('traffic preservation precheck', () => { + function configs(source: Record) { + const directory = mkdtempSync(join(tmpdir(), 'void-traffic-precheck-')); + const sourceConfigPath = join(directory, 'wrangler.json'); + const configPath = join(directory, 'generated.json'); + writeFileSync(sourceConfigPath, JSON.stringify({ name: 'my-worker', ...source })); + writeFileSync(configPath, JSON.stringify({ name: 'my-worker', ...source })); + return { directory, sourceConfigPath, configPath }; + } + + function activeVersion(version: Record | null) { + return operationFixture((args: Array) => { + if (args[0] === 'deployments') { + return version + ? ok(JSON.stringify({ versions: [{ version_id: CURRENT, percentage: 100 }] })) + : { + stdout: '', + stderr: 'This Worker does not exist on your account. [code: 10007]', + status: 1, + }; + } + if (args[0] === 'versions' && args[1] === 'list') { + return ok(JSON.stringify([{ number: 1, ...version }])); + } + throw new Error(`Unexpected command: ${args.join(' ')}`); + }); + } + + const foreignVersion = { + id: CURRENT, + annotations: { 'workers/triggered_by': 'upload' }, + resources: { bindings: [], script: { last_deployed_from: 'dash' } }, + }; + + it('refuses a foreign Worker whose traffic settings the config omits', async () => { + const paths = configs({}); + try { + await expect( + canPreserveCloudflareTraffic({ + ...paths, + runWrangler: activeVersion(foreignVersion), + workerName: 'my-worker', + }), + ).resolves.toBe(false); + } finally { + rmSync(paths.directory, { recursive: true, force: true }); + } + }); + + it('allows declared traffic, recorded values, Void versions, placeholders and new Workers', async () => { + const declared = configs({ workers_dev: true, preview_urls: false, routes: [] }); + const omitted = configs({}); + try { + const runWrangler = activeVersion(foreignVersion); + const check = (options: Partial[0]>) => + canPreserveCloudflareTraffic({ + ...omitted, + runWrangler, + workerName: 'my-worker', + ...options, + }); + await expect(check(declared)).resolves.toBe(true); + await expect( + check({ previousTrafficConfig: { workers_dev: true, preview_urls: true, routes: [] } }), + ).resolves.toBe(true); + await expect(check({ adoptPlaceholderVersionId: CURRENT })).resolves.toBe(true); + await expect( + check({ + runWrangler: activeVersion({ + ...foreignVersion, + annotations: { + 'workers/message': encodeCloudflareVersionMessage([], triggersWith()), + }, + }), + }), + ).resolves.toBe(true); + await expect(check({ runWrangler: activeVersion(null) })).resolves.toBe(true); + } finally { + rmSync(declared.directory, { recursive: true, force: true }); + rmSync(omitted.directory, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/void/src/cli/deploy-cloudflare-auth.ts b/packages/void/src/cli/deploy-cloudflare-auth.ts index fd0737529d..6ccfbe379e 100644 --- a/packages/void/src/cli/deploy-cloudflare-auth.ts +++ b/packages/void/src/cli/deploy-cloudflare-auth.ts @@ -261,6 +261,8 @@ export async function runWranglerAuthToken( * once, streamed to `wrangler secret put` over stdin (never argv), then verified * by listing names again. A not-yet-deployed Worker is the one safe list failure * treated as absence because Wrangler can attach a secret to its draft Worker. + * A Worker that is still a replaceable placeholder gets the secret with its first deploy too, + * because a standalone `secret put` would publish a new version over the placeholder. */ export async function ensureCloudflareAuthSecret(options: { root: string; @@ -269,6 +271,7 @@ export async function ensureCloudflareAuthSecret(options: { workerName: string; runWrangler: DeployWranglerRun; beforeWranglerRun?: () => boolean; + replacesPlaceholder?: boolean; }): Promise<{ created: boolean; workerWasMissing?: true; candidateSecret?: string }> { let workerWasMissing = false; const beforeRun = (): void => { @@ -316,6 +319,9 @@ export async function ensureCloudflareAuthSecret(options: { // secret endpoints reject a Worker that has not been created yet. return { created: true, workerWasMissing: true, candidateSecret: secret }; } + if (options.replacesPlaceholder) { + return { created: true, candidateSecret: secret }; + } beforeRun(); let put: DeployWranglerRunResult; try { diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 5095a0e18f..2c4d6e6a59 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -687,7 +687,7 @@ function formatCloudflareActivationFailure( case 'traffic-preservation-unavailable': return [ 'deploy: the existing Worker has dashboard-managed routes or visibility that Void cannot safely republish.', - 'Add its current routes, workers_dev, and preview_urls values to the root Wrangler config, then retry; no version was uploaded.', + 'Add its current routes, workers_dev, and preview_urls values to `cloudflare` in void.config.ts or to the root Wrangler config, then retry; no version was uploaded.', ].join('\n'); case 'traffic-split-unsupported': return [ diff --git a/packages/void/src/cli/deploy-cloudflare-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index 31da6eaf5d..71eb802ee4 100644 --- a/packages/void/src/cli/deploy-cloudflare-migrate.ts +++ b/packages/void/src/cli/deploy-cloudflare-migrate.ts @@ -1,4 +1,5 @@ import { + canPreserveCloudflareTraffic, encodeCloudflareVersionMessage, readCloudflareTriggerConfig, } from '@void/deploy-cloudflare'; @@ -10,6 +11,7 @@ import { } from './deploy-artifact-validation.ts'; import { ensureCloudflareAuthSecret } from './deploy-cloudflare-auth.ts'; import type { CloudflareBuild } from './deploy-cloudflare-build.ts'; +import { formatCloudflareActivationError } from './deploy-cloudflare-helpers.ts'; import type { CloudflareDeploySource, CloudflarePreflight } from './deploy-cloudflare-preflight.ts'; import { log } from './deploy-helpers.ts'; import { applyAndVerifyRemoteD1Migrations } from './deploy-migrations.ts'; @@ -20,6 +22,7 @@ import { getErrorMessage } from './output.ts'; import { readDeploymentPlatform } from './project.ts'; import { workersBuildsVersionSource } from './workers-builds.ts'; import type { WorkersBuildsContext } from './workers-builds.ts'; +import { readWranglerPublishedTrafficSnapshot } from './wrangler.ts'; export type CloudflareMigration = Awaited>; @@ -45,9 +48,15 @@ export async function prepareCloudflareWorkerMigrations(input: MigrationInput): }> { const { root, deps, exit, cliLog } = input; const { configPath, authEnabled, dialect } = input.source; - const { accountId, workerName, verification, runWrangler, assertUploaderStillPinned } = - input.preflight; - const { migrations, d1MigrateToken } = input.build; + const { + accountId, + workerName, + verification, + runWrangler, + assertUploaderStillPinned, + workersBuildsPlaceholderVersionId, + } = input.preflight; + const { migrations, d1MigrateToken, generatedConfigPath } = input.build; let workerWasMissingBeforeSecretProvisioning = false; let initialAuthSecret: string | undefined; @@ -57,12 +66,38 @@ export async function prepareCloudflareWorkerMigrations(input: MigrationInput): const message = encodeCloudflareVersionMessage( migrationHistory, { - ...readCloudflareTriggerConfig(input.build.generatedConfigPath, configPath), + ...readCloudflareTriggerConfig(generatedConfigPath, configPath), ...(input.preflight.existingWorker ? { preserve: true } : {}), }, { source: workersBuildsVersionSource(input.workersBuilds) }, ); + // Activation would refuse this Worker anyway, so stop before the first remote change. + if ( + input.preflight.existingWorker === null && + (authEnabled || (!input.skipMigrations && migrations.length > 0)) && + !(await canPreserveCloudflareTraffic({ + runWrangler, + workerName, + configPath: generatedConfigPath, + sourceConfigPath: configPath, + previousTrafficConfig: readWranglerPublishedTrafficSnapshot(configPath), + ...(workersBuildsPlaceholderVersionId + ? { adoptPlaceholderVersionId: workersBuildsPlaceholderVersionId } + : {}), + })) + ) { + log.error( + formatCloudflareActivationError({ + ok: false, + reason: 'traffic-preservation-unavailable', + previousVersionId: null, + rollback: 'not-needed', + }), + ); + return exit(1); + } + // Persistent Better Auth secret: adopted when present, otherwise generated once and verified, // before the first remote migration or upload. if (authEnabled) { @@ -90,6 +125,7 @@ export async function prepareCloudflareWorkerMigrations(input: MigrationInput): workerName, runWrangler, beforeWranglerRun: assertUploaderStillPinned, + ...(workersBuildsPlaceholderVersionId ? { replacesPlaceholder: true } : {}), }); workerWasMissingBeforeSecretProvisioning = authSecret.workerWasMissing === true; initialAuthSecret = authSecret.candidateSecret; diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index af123804d4..9ba6c5b747 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -207,6 +207,8 @@ export type CloudflarePreflight = Omit workerName: string; /** The Worker tag Workers Builds confirmed for this deploy, or null. */ workersBuildsWorkerTag: string | null; + /** The dashboard placeholder version this Workers Builds deploy may replace, or null. */ + workersBuildsPlaceholderVersionId: string | null; emailMap: EmailAddressMapInput | null; schemaFacts: SelfHostSchemaFacts; existingWorker: ExistingCloudflareWorker | null; @@ -788,6 +790,7 @@ export async function preflightCloudflareWorker(input: { ...target, workerName, workersBuildsWorkerTag: buildsWorker.workerTag, + workersBuildsPlaceholderVersionId: buildsWorker.placeholderVersionId, emailMap, schemaFacts, existingWorker, diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 39eb86d40b..8ce4264605 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -56,6 +56,7 @@ export async function publishCloudflareWorker(input: { accountId, workerName, workersBuildsWorkerTag, + workersBuildsPlaceholderVersionId, cfUploaderIsPinned, apiBaseUrl, complianceRegion, @@ -145,6 +146,9 @@ export async function publishCloudflareWorker(input: { verifyTarget(); }), allowFirstDeploymentBootstrap: workerWasMissingBeforeSecretProvisioning, + ...(workersBuildsPlaceholderVersionId + ? { adoptPlaceholderVersionId: workersBuildsPlaceholderVersionId } + : {}), ...(pinActiveSecrets ? { pinActiveSecrets } : {}), atomic, ...(initialAuthSecret diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index c6d14e99c1..86ee281165 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -682,6 +682,9 @@ export async function runCloudflareStaticDeploy( }), } : {}), + ...(buildsWorker.placeholderVersionId + ? { adoptPlaceholderVersionId: buildsWorker.placeholderVersionId } + : {}), }, ).finally(() => cfOutput?.dispose()); if (!execution.ok) { diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 9fe6d79d01..791b5f5b0b 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -155,10 +155,104 @@ export function workersBuildsAccountMismatch( ].join('\n'); } +/** The source Cloudflare records for a Worker version the dashboard creates from a template. */ +const DASHBOARD_TEMPLATE_SOURCE = 'dash_template'; + +/** + * The production version of the hello-world Worker that the Cloudflare dashboard creates before + * the first Workers Builds deploy, or null when the Worker is anything else or cannot be read. + * The proof: one version serves all traffic, the dashboard uploaded it from a template, it has + * no bindings and no Void deploy message, and the Worker has no routes or Custom Domains. + */ +export async function readWorkersBuildsPlaceholderVersion(input: { + workerName: string; + accountId: string; + apiBaseUrl: string; + token: string; + fetchImpl?: typeof fetch; +}): Promise { + const account = `${input.apiBaseUrl}/accounts/${encodeURIComponent(input.accountId)}/workers`; + const script = `${account}/scripts/${encodeURIComponent(input.workerName)}`; + const read = async (url: string): Promise => { + try { + const response = await (input.fetchImpl ?? fetch)(url, { + headers: { Authorization: `Bearer ${input.token}` }, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + if (!response.ok) { + return null; + } + const body = await response.json<{ success?: unknown; result?: T }>(); + return body.success === true && body.result !== undefined ? body.result : null; + } catch { + return null; + } + }; + + const deployments = await read<{ + deployments?: Array<{ + created_on?: unknown; + versions?: Array<{ version_id?: unknown; percentage?: unknown }>; + }>; + }>(`${script}/deployments`); + const latest = deployments?.deployments + ?.filter((deployment) => typeof deployment.created_on === 'string') + .sort((a, b) => String(b.created_on).localeCompare(String(a.created_on)))[0]; + const traffic = latest?.versions; + if ( + !traffic || + traffic.length !== 1 || + typeof traffic[0].version_id !== 'string' || + Number(traffic[0].percentage) !== 100 + ) { + return null; + } + const versionId = traffic[0].version_id; + + const version = await read<{ + id?: unknown; + annotations?: Record; + resources?: { bindings?: unknown; script?: { last_deployed_from?: unknown } }; + }>(`${script}/versions/${encodeURIComponent(versionId)}`); + if ( + !version || + version.id !== versionId || + version.resources?.script?.last_deployed_from !== DASHBOARD_TEMPLATE_SOURCE || + !Array.isArray(version.resources.bindings) || + version.resources.bindings.length !== 0 || + version.annotations?.['workers/message'] !== undefined + ) { + return null; + } + + const domains = await read>( + `${account}/domains?service=${encodeURIComponent(input.workerName)}`, + ); + if (!Array.isArray(domains) || domains.length !== 0) { + return null; + } + const scripts = await read>(`${account}/scripts`); + const listed = Array.isArray(scripts) + ? scripts.find((entry) => entry.id === input.workerName) + : undefined; + if ( + !listed || + (listed.routes !== null && + listed.routes !== undefined && + (!Array.isArray(listed.routes) || listed.routes.length !== 0)) + ) { + return null; + } + return versionId; +} + /** * Check that the Worker this deploy targets is the one Workers Builds allows, as Wrangler * does with `WRANGLER_CI_MATCH_TAG`. Returns the confirmed Worker tag for the output entry * (null when there is nothing to check), or an error message. Any failure stops the deploy. + * `placeholderVersionId` is set when the Worker is still the dashboard's hello-world + * placeholder, which this deploy may replace as a first deployment. */ export async function confirmWorkersBuildsWorker(input: { builds: WorkersBuildsContext | null | undefined; @@ -167,10 +261,10 @@ export async function confirmWorkersBuildsWorker(input: { apiBaseUrl: string; token: string | undefined; fetchImpl?: typeof fetch; -}): Promise<{ workerTag: string | null } | { error: string }> { +}): Promise<{ workerTag: string | null; placeholderVersionId: string | null } | { error: string }> { const matchTag = input.builds?.matchTag; if (!matchTag || !input.token) { - return { workerTag: null }; + return { workerTag: null, placeholderVersionId: null }; } const retry = (reason: string) => ({ error: [ @@ -224,7 +318,16 @@ export async function confirmWorkersBuildsWorker(input: { ].join('\n'), }; } - return { workerTag: tag }; + return { + workerTag: tag, + placeholderVersionId: await readWorkersBuildsPlaceholderVersion({ + workerName: input.workerName, + accountId: input.accountId, + apiBaseUrl: input.apiBaseUrl, + token: input.token, + fetchImpl: input.fetchImpl, + }), + }; } /** Source metadata for the version message, from Workers Builds. */ diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 2e6a325e7b..23be78f56d 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -2758,6 +2758,28 @@ describe('ensureCloudflareAuthSecret', () => { expect(put.args.join(' ')).not.toContain(put.opts.input!.trim()); }); + it('uploads the secret with the first deploy over a Workers Builds placeholder', async () => { + const root = authSecretProject(); + const calls: Array> = []; + const result = await ensureCloudflareAuthSecret({ + root, + configPath: join(root, 'wrangler.jsonc'), + accountId: 'acc123', + workerName: 'authapp', + replacesPlaceholder: true, + runWrangler: operationFixture((args) => { + calls.push(args); + return { ...cleanExit, stdout: '[]' }; + }), + }); + + expect(result).toEqual({ + created: true, + candidateSecret: expect.stringMatching(/^[0-9a-f]{64}$/), + }); + expect(calls.map((args) => args.slice(0, 2))).toEqual([['secret', 'list']]); + }); + it('bootstraps the secret when the Worker has not been deployed yet', async () => { const root = authSecretProject(); let call = 0; @@ -5093,6 +5115,50 @@ describe('runCloudflareDeploy — resource provisioning', () => { expect(output.match(/Successfully deployed!/g)).toHaveLength(1); }); + it('stops before D1 migrations when activation could not keep the live traffic settings', async () => { + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'myapp' }), + 'void.json': JSON.stringify({ database: { readReplication: true } }), + 'routes/index.ts': `export const GET = (c) => c.env.DB.prepare('SELECT 1').first();`, + 'db/migrations/0000_init.sql': `CREATE TABLE notes (id integer primary key);`, + 'wrangler.jsonc': JSON.stringify(PROVISIONED_D1, null, 2), + }); + const foreign = '11111111-1111-4111-8111-111111111111'; + const base = harness(); + const runWrangler: DeployWranglerRun = operationFixture((args, opts) => { + if (args[0] === 'deployments') { + base.trace.push('wrangler:deployments'); + return { + ...cleanExit, + stdout: JSON.stringify({ versions: [{ version_id: foreign, percentage: 100 }] }), + }; + } + if (args[0] === 'versions' && args[1] === 'list') { + return { + ...cleanExit, + stdout: JSON.stringify([ + { id: foreign, number: 1, annotations: { 'workers/triggered_by': 'upload' } }, + ]), + }; + } + return base.deps.runWrangler!(operationFixtureRequest(args), opts); + }); + const output = await captureDeployOutput(async () => { + await expect( + runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, { + ...base.deps, + runWrangler, + }), + ).rejects.toThrow(ExitError); + }); + expect(base.exitCalls).toEqual([1]); + expect(output).toContain('dashboard-managed routes or visibility'); + expect(output).toContain('in void.config.ts'); + expect(base.trace).toContain('wrangler:deployments'); + expect(base.trace).not.toContain('wrangler:d1'); + expect(base.trace).not.toContain('wrangler:deploy'); + }); + it('reconciles opted-in D1 replication before build, gate, migrations and deploy when fully provisioned', async () => { const root = makeProject({ 'package.json': JSON.stringify({ name: 'myapp' }), @@ -5116,6 +5182,7 @@ describe('runCloudflareDeploy — resource provisioning', () => { 'build', 'gate', 'migrate-gate', + 'wrangler:deployments', // can the live traffic settings be kept? 'wrangler:d1', // migrations list (is a restore point needed?) 'wrangler:d1', // migrations apply (after the gate) 'wrangler:d1', // migrations list (pending verify) @@ -14134,6 +14201,57 @@ describe('Workers Builds', () => { expect(init?.headers).toEqual({ Authorization: 'Bearer builds-token' }); }); + it('replaces the dashboard placeholder Worker on the first Builds deploy', async () => { + stubWorkersBuilds(); + const placeholder = '176ee95f-0000-4000-8000-000000000000'; + const account = 'https://api.cloudflare.com/client/v4/accounts/acc123/workers'; + const servicesFetch = vi.mocked(fetch); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string | URL | Request, init?: RequestInit) => { + const href = String(url); + const result = + href === `${account}/scripts/myapp/deployments` + ? { + deployments: [ + { + created_on: '2026-11-26T12:00:00.000Z', + versions: [{ version_id: placeholder, percentage: 100 }], + }, + ], + } + : href === `${account}/scripts/myapp/versions/${placeholder}` + ? { + id: placeholder, + annotations: { 'workers/triggered_by': 'upload' }, + resources: { bindings: [], script: { last_deployed_from: 'dash_template' } }, + } + : href === `${account}/domains?service=myapp` + ? [] + : href === `${account}/scripts` + ? [{ id: 'myapp', routes: null }] + : undefined; + return result === undefined + ? servicesFetch(url, init) + : Response.json({ success: true, result }); + }), + ); + const root = d1Project(PROVISIONED_D1); + const base = harness(); + const activations: Array = []; + const { deps, exitCalls } = harness({ + activateVersion: async (options) => { + activations.push(options.adoptPlaceholderVersionId); + return base.deps.activateVersion!(options); + }, + }); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + expect(activations).toEqual([placeholder]); + }); + it('stops before building when Builds passes the tag of another Worker', async () => { stubWorkersBuilds({}, { tag: 'other-tag' }); const root = d1Project(PROVISIONED_D1); diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 10982af12d..9172fc941f 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -6,6 +6,7 @@ import { canPromptInTerminal, confirmWorkersBuildsWorker, readWorkersBuildsContext, + readWorkersBuildsPlaceholderVersion, resolveDeployOutputFile, withRecordedWorkersBuildsEnv, workersBuildsAccountMismatch, @@ -176,7 +177,7 @@ describe('Workers Builds Worker tag check', () => { it('returns the confirmed tag when the Worker matches the Builds tag', async () => { const { result, fetchImpl } = check(service('tag-1')); - await expect(result).resolves.toEqual({ workerTag: 'tag-1' }); + await expect(result).resolves.toEqual({ workerTag: 'tag-1', placeholderVersionId: null }); expect(fetchImpl).toHaveBeenCalledWith( 'https://api.cloudflare.com/client/v4/accounts/account-1/workers/services/my-app', expect.objectContaining({ headers: { Authorization: 'Bearer builds-token' } }), @@ -193,17 +194,17 @@ describe('Workers Builds Worker tag check', () => { }; await expect( confirmWorkersBuildsWorker({ ...base, builds: null, token: 't' }), - ).resolves.toEqual({ workerTag: null }); + ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); await expect( confirmWorkersBuildsWorker({ ...base, builds: readWorkersBuildsContext({ WORKERS_CI: '1' }), token: 't', }), - ).resolves.toEqual({ workerTag: null }); + ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); await expect( confirmWorkersBuildsWorker({ ...base, builds, token: undefined }), - ).resolves.toEqual({ workerTag: null }); + ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); expect(fetchImpl).not.toHaveBeenCalled(); }); @@ -243,6 +244,171 @@ describe('Workers Builds Worker tag check', () => { }); }); +describe('Workers Builds placeholder Worker', () => { + const API = 'https://api.cloudflare.com/client/v4'; + const ACCOUNT = `${API}/accounts/account-1/workers`; + const STUB_VERSION = '176ee95f-0000-4000-8000-000000000000'; + + type Fixture = { + deployments: unknown; + version: Record; + domains: unknown; + scripts: unknown; + }; + + function placeholder(): Fixture { + return { + deployments: { + deployments: [ + { + created_on: '2026-11-26T12:00:00.000Z', + versions: [{ version_id: STUB_VERSION, percentage: 100 }], + }, + ], + }, + version: { + id: STUB_VERSION, + annotations: { 'workers/triggered_by': 'upload' }, + resources: { bindings: [], script: { last_deployed_from: 'dash_template' } }, + }, + domains: [], + scripts: [{ id: 'my-app', routes: null }], + }; + } + + function respond(fixture: Fixture) { + return vi.fn(async (input) => { + const url = String(input); + const result = + url === `${ACCOUNT}/scripts/my-app/deployments` + ? fixture.deployments + : url === `${ACCOUNT}/scripts/my-app/versions/${STUB_VERSION}` + ? fixture.version + : url === `${ACCOUNT}/domains?service=my-app` + ? fixture.domains + : url === `${ACCOUNT}/scripts` + ? fixture.scripts + : undefined; + return result === undefined + ? Response.json({ success: false }, { status: 404 }) + : Response.json({ success: true, result }); + }); + } + + const read = (fetchImpl: typeof fetch) => + readWorkersBuildsPlaceholderVersion({ + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: API, + token: 'builds-token', + fetchImpl, + }); + + it('returns the version of the dashboard hello-world Worker', async () => { + await expect(read(respond(placeholder()))).resolves.toBe(STUB_VERSION); + }); + + it('rejects any Worker that may serve something to keep', async () => { + const variants: Array<(fixture: Fixture) => void> = [ + (fixture) => { + fixture.version.resources = { + bindings: [{ type: 'kv_namespace', name: 'KV' }], + script: { last_deployed_from: 'dash_template' }, + }; + }, + (fixture) => { + fixture.version.resources = { bindings: [], script: { last_deployed_from: 'dash' } }; + }, + (fixture) => { + fixture.version.annotations = { 'workers/message': 'Edited in the dashboard' }; + }, + (fixture) => { + fixture.version.id = 'another-version'; + }, + (fixture) => { + fixture.deployments = { + deployments: [ + { + created_on: '2026-11-26T12:00:00.000Z', + versions: [ + { version_id: STUB_VERSION, percentage: 50 }, + { version_id: 'another-version', percentage: 50 }, + ], + }, + ], + }; + }, + (fixture) => { + fixture.domains = [{ hostname: 'app.example.com', service: 'my-app' }]; + }, + (fixture) => { + fixture.scripts = [{ id: 'my-app', routes: [{ pattern: 'example.com/*' }] }]; + }, + (fixture) => { + fixture.scripts = [{ id: 'another-app', routes: null }]; + }, + ]; + for (const change of variants) { + const fixture = placeholder(); + change(fixture); + await expect(read(respond(fixture))).resolves.toBeNull(); + } + }); + + it('reads the newest deployment', async () => { + const fixture = placeholder(); + fixture.deployments = { + deployments: [ + { + created_on: '2026-11-26T13:00:00.000Z', + versions: [{ version_id: 'void-version', percentage: 100 }], + }, + { + created_on: '2026-11-26T12:00:00.000Z', + versions: [{ version_id: STUB_VERSION, percentage: 100 }], + }, + ], + }; + await expect(read(respond(fixture))).resolves.toBeNull(); + }); + + it('treats a failed read as no placeholder', async () => { + await expect( + read( + vi.fn(async () => { + throw new Error('network down'); + }), + ), + ).resolves.toBeNull(); + await expect( + read(vi.fn(async () => Response.json({ success: false }, { status: 403 }))), + ).resolves.toBeNull(); + }); + + it('reports the placeholder with the confirmed Worker tag', async () => { + const fixture = placeholder(); + const placeholderFetch = respond(fixture); + const fetchImpl = vi.fn(async (input, init) => + String(input) === `${ACCOUNT}/services/my-app` + ? Response.json({ + success: true, + result: { default_environment: { script: { tag: 'tag-1' } } }, + }) + : placeholderFetch(input, init), + ); + await expect( + confirmWorkersBuildsWorker({ + builds: readWorkersBuildsContext(BUILDS_ENV), + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: API, + token: 'builds-token', + fetchImpl, + }), + ).resolves.toEqual({ workerTag: 'tag-1', placeholderVersionId: STUB_VERSION }); + }); +}); + describe('Wrangler-compatible deploy output', () => { it('resolves WRANGLER_OUTPUT_FILE_PATH before WRANGLER_OUTPUT_FILE_DIRECTORY', () => { expect(resolveDeployOutputFile({})).toBeNull(); From e76c3207240d78cd4ebb2a269a557dea15034007 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Thu, 26 Nov 2026 15:05:53 +0100 Subject: [PATCH 13/25] docs: explain the Workers Builds placeholder and existing Workers --- docs/integrations/cloudflare.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index f4a79261ba..8862ef9d79 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -260,6 +260,8 @@ The Worker name in Workers Builds must match the name Void deploys: `cloudflare. In Workers Builds, Void deploys without prompts or a browser sign-in. It uses the build's API token and account. After a successful deploy, Workers Builds links the build to the Worker version it deployed, and the version message records the commit and branch. +When you create a Worker from your repository, Cloudflare first deploys a placeholder Worker. The first build with Void replaces it. To connect an existing Worker that Void has not deployed, first add its current `routes`, `workers_dev`, and `preview_urls` to `cloudflare` in `void.config.ts`. Otherwise Void stops before it runs migrations or deploys, so the Worker keeps its routes and visibility. + #### API token permissions The API token that Workers Builds creates includes the permissions most Void apps need, such as D1, Queues, Hyperdrive, Workers KV Storage, and Workers R2 Storage. For apps that use [email](../guide/email/domains.md#your-own-cloudflare-account), add **Zone Read** and **Email Sending Edit**, plus **Zone Settings Edit** for apps with `email/` handlers. From bff5ec80968346bc6938e8386f78424b736a27c4 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Sat, 28 Nov 2026 11:57:26 +0100 Subject: [PATCH 14/25] docs: describe the workers.dev subdomain lookup and Workers Builds in the CLI reference --- docs/integrations/cloudflare.md | 26 +++++++++++------------ docs/reference/cli/deploy.md | 26 +++++++++++------------ packages/deploy-cloudflare/src/version.ts | 2 +- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 8862ef9d79..7e65fc5a78 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -134,14 +134,14 @@ Apps using email need `email.from` in `void.config.ts`. Void reviews the domain' Set these CI secrets and variables as needed: -| Name | When needed | -| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `CLOUDFLARE_API_TOKEN` | Required. Workers Admin for the first deploy, or Workers Editor to deploy to an existing Worker. | -| `CLOUDFLARE_ACCOUNT_ID` | When the token can access several accounts. | -| `DATABASE_URL` | PostgreSQL and MySQL provisioning and migrations. | -| `CLOUDFLARE_WORKERS_SUBDOMAIN` | When workers.dev is enabled and the version has no preview URL. Use `my-team` or `my-team.workers.dev`. An account subdomain does not create a readiness URL when `workers_dev` is false. | -| `CF_ACCESS_CLIENT_ID`, `CF_ACCESS_CLIENT_SECRET` | When Cloudflare Access protects the readiness URL. | -| `CF_ACCESS_READINESS_ORIGIN` | When Access protects a route or Custom Domain and `workers_dev` is `false`. See [Cloudflare Access](#cloudflare-access). | +| Name | When needed | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `CLOUDFLARE_API_TOKEN` | Required. Workers Admin for the first deploy, or Workers Editor to deploy to an existing Worker. | +| `CLOUDFLARE_ACCOUNT_ID` | When the token can access several accounts. | +| `DATABASE_URL` | PostgreSQL and MySQL provisioning and migrations. | +| `CLOUDFLARE_WORKERS_SUBDOMAIN` | When workers.dev is enabled, the version has no preview URL, and Void cannot look up the account subdomain. Use `my-team` or `my-team.workers.dev`. An account subdomain does not create a readiness URL when `workers_dev` is false. | +| `CF_ACCESS_CLIENT_ID`, `CF_ACCESS_CLIENT_SECRET` | When Cloudflare Access protects the readiness URL. | +| `CF_ACCESS_READINESS_ORIGIN` | When Access protects a route or Custom Domain and `workers_dev` is `false`. See [Cloudflare Access](#cloudflare-access). | Grant **Workers → Admin** for the account when Void creates the Worker. For subsequent deploys, **Workers → Editor** is enough for the Worker itself. Add **Workers Routes Write** for each zone where the deploy adds, updates, or removes a route or Custom Domain. Grant access to any resources Void reads or provisions, such as D1 or KV. See [Cloudflare Workers roles and permissions](https://developers.cloudflare.com/workers/authorization/workers/). @@ -250,11 +250,11 @@ Add the same `--dir` and `--spa` flags as your production deploy. Using npm, Yar [Workers Builds](https://developers.cloudflare.com/workers/ci-cd/builds/) runs `void deploy` on every push to your production branch. In the Cloudflare dashboard, go to **Workers & Pages**, then create a Worker from your repository or open an existing Worker and connect it under **Settings** > **Build**. Use these build settings: -| Setting | Value | -| -------------- | -------------------------------------------------------- | -| Build command | Leave empty. `void deploy` builds the app. | -| Deploy command | `npx void deploy --platform cloudflare` | -| Root directory | The folder with `void.config.ts`, if it is not the root. | +| Setting | Value | +| -------------- | ------------------------------------------------- | +| Build command | Leave empty. `void deploy` builds the app. | +| Deploy command | `npx void deploy --platform cloudflare` | +| Root directory | The app folder, if it is not the repository root. | The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts`, or your `package.json` name. If `void.config.ts` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 8cdd1d41a3..a903f4d976 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -99,19 +99,19 @@ void deploy --platform cloudflare void deploy --platform cloudflare --require-email # fail instead of deploying without email ``` -Void signs you in through your browser when needed and saves the selected account. In CI, set `CLOUDFLARE_API_TOKEN` and, if the token can access several accounts, `CLOUDFLARE_ACCOUNT_ID`. - -| Option or setting | Cloudflare behavior | -| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | -| `--dir`, `--spa` | Deploy static output through a small Worker and Workers Assets | -| `--skip-build` | Reuse existing static, SPA, or SSG output; unavailable for Worker apps | -| `--skip-migrations` | Skip database migrations; existing PostgreSQL/MySQL Hyperdrive bindings do not require `DATABASE_URL` just to skip SQL | -| `--project` | Unavailable; the Worker and account come from `void.config.ts` and `void.lock.json` | -| Named environments | Unavailable; use the top-level `cloudflare` config | -| `CLOUDFLARE_WORKERS_SUBDOMAIN` | Needed in fresh CI when a workers.dev Worker has no preview URL; cached locally after a deploy. It does not apply when `workers_dev` is false | -| `CF_ACCESS_READINESS_ORIGIN` | Lets Access credentials reach the readiness check on a route or Custom Domain, for example `https://app.example.com` | -| `--require-email` | Fail instead of deploying without email when the email step cannot run, as in CI | -| `DATABASE_URL` | Required in the deploy environment for PostgreSQL or MySQL provisioning and migrations | +Void signs you in through your browser when needed and saves the selected account. In CI, set `CLOUDFLARE_API_TOKEN` and, if the token can access several accounts, `CLOUDFLARE_ACCOUNT_ID`. In [Workers Builds](../../guide/deployment.md#workers-builds), Void uses the build's token and account and never prompts. + +| Option or setting | Cloudflare behavior | +| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--dir`, `--spa` | Deploy static output through a small Worker and Workers Assets | +| `--skip-build` | Reuse existing static, SPA, or SSG output; unavailable for Worker apps | +| `--skip-migrations` | Skip database migrations; existing PostgreSQL/MySQL Hyperdrive bindings do not require `DATABASE_URL` just to skip SQL | +| `--project` | Unavailable; the Worker and account come from `void.config.ts` and `void.lock.json` | +| Named environments | Unavailable; use the top-level `cloudflare` config | +| `CLOUDFLARE_WORKERS_SUBDOMAIN` | Account workers.dev subdomain for the readiness check, when Void cannot look it up and the version has no preview URL. It does not apply when `workers_dev` is false | +| `CF_ACCESS_READINESS_ORIGIN` | Lets Access credentials reach the readiness check on a route or Custom Domain, for example `https://app.example.com` | +| `--require-email` | Fail instead of deploying without email when the email step cannot run, as in CI | +| `DATABASE_URL` | Required in the deploy environment for PostgreSQL or MySQL provisioning and migrations | After `--skip-migrations`, direct Cloudflare deployment history shows the applied migration state as unknown. Rolling back code doesn't reverse database changes. diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 1934061349..02b135fe1e 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -1201,7 +1201,6 @@ type InternalCloudflareVersionActivationOptions = CloudflareVersionActivationOpt candidateSecretsFilePath?: string; }; -/** Upload, probe, and atomically activate a verified Worker Version. */ /** * Report, before remote changes such as database migrations, whether activation can keep the * live traffic settings. It is false only when the authored config leaves `routes`, @@ -1241,6 +1240,7 @@ export async function canPreserveCloudflareTraffic(options: { ); } +/** Upload, probe, and atomically activate a verified Worker Version. */ export async function activateCloudflareVersion( options: CloudflareVersionActivationOptions, ): Promise { From 870cafa8ddbaf1410a30a17e102f41c31d00c05f Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Sat, 28 Nov 2026 12:05:31 +0100 Subject: [PATCH 15/25] fix: harden Workers Builds placeholder adoption --- packages/deploy-cloudflare/src/version.ts | 6 +- .../test/unit/version.test.ts | 70 ++++++++++++++----- .../void/src/cli/deploy-cloudflare-publish.ts | 15 +++- .../void/src/cli/deploy-cloudflare-static.ts | 13 ++++ packages/void/src/cli/workers-builds.ts | 50 ++++++++++++- .../void/test/unit/cloudflare-deploy.test.ts | 41 +++++++++-- .../void/test/unit/workers-builds.test.ts | 55 ++++++++++++++- 7 files changed, 218 insertions(+), 32 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 02b135fe1e..e4c65ce8c6 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -1296,7 +1296,6 @@ async function activateCloudflareVersionWithSecretsFile( const adoptsPlaceholder = options.adoptPlaceholderVersionId !== undefined && !options.preserveTriggers && - !options.atomic && !options.requirePreviewForReadiness; if (adoptsPlaceholder && previousVersionId !== options.adoptPlaceholderVersionId) { return { @@ -1576,12 +1575,11 @@ async function activateCloudflareVersionWithSecretsFile( const alias = `void-ready-${Date.now().toString(36)}`; if (adoptsPlaceholder) { - // The placeholder serves nothing to keep, and a dashboard-created one has workers.dev and - // previews off, so a staged candidate would have no reachable readiness URL. + // The placeholder serves nothing to keep, so publish over it as a new Worker would be. return bootstrapFirstDeployment( { ...options, message }, previous.versionId, - false, + options.atomic === true, previousTriggerConfig, previousIsRestorePlaceholder, ); diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 80f7df7bb4..cca4296e15 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -3156,6 +3156,22 @@ describe('Cloudflare version activation', () => { ); }); + it('keeps the source in a long message, which then needs a recovery reference', () => { + const triggers = triggersWith({ preview_urls: false }); + const migrations = Array.from( + { length: 30 }, + (_, index) => `${String(index).padStart(4, '0')}_create_table.sql`, + ); + const branch = `feature/${'x'.repeat(240)}`; + const message = encodeCloudflareVersionMessage(migrations, triggers, { source: { branch } }); + expect(new TextEncoder().encode(message).length).toBeGreaterThan(1000); + expect(parseCloudflareVersionMessage(message)).toMatchObject({ + migrations, + source: { branch }, + }); + expect(cloudflareVersionMessageReference(message)).toMatch(/^void:ref:[a-f0-9]{64}:30:/); + }); + // The Cloudflare CLI applies its Email Routing plan inside `triggers deploy`, reading the // config's `addresses`. The trigger-only config Void hands it must therefore carry the // snapshot's addresses verbatim — and carry NOTHING when the snapshot has none, because an @@ -6818,23 +6834,43 @@ describe('Workers Builds placeholder adoption', () => { ).toBe(false); }); - it('does not adopt when triggers are preserved or the publish is atomic', async () => { - for (const mode of [{ preserveTriggers: true }, { atomic: true }]) { - const runWrangler = runner({ versions: placeholderVersions }); - await expect( - activateCloudflareVersion({ - runWrangler, - workerName: 'my-worker', - verifyUploader: () => true, - adoptPlaceholderVersionId: CONCURRENT, - message: encodeCloudflareVersionMessage([], omittedTraffic), - fetch: async () => Response.json({ ready: true }), - sleep: async () => {}, - readinessAttempts: 1, - ...mode, - }), - ).resolves.not.toMatchObject({ reason: 'deployment-changed' }); - } + it('does not adopt when triggers are preserved', async () => { + const runWrangler = runner({ versions: placeholderVersions }); + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + adoptPlaceholderVersionId: CONCURRENT, + preserveTriggers: true, + message: encodeCloudflareVersionMessage([], omittedTraffic), + fetch: async () => Response.json({ ready: true }), + sleep: async () => {}, + readinessAttempts: 1, + }), + ).resolves.not.toMatchObject({ reason: 'deployment-changed' }); + }); + + it('publishes over the placeholder atomically when the deploy is atomic', async () => { + const runWrangler = runner({ + versions: placeholderVersions, + bootstrap: ok(`Worker Version ID: ${NEXT}\nhttps://my-worker.example.workers.dev`), + }); + const onProgress = vi.fn(); + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => true, + adoptPlaceholderVersionId: CURRENT, + atomic: true, + onProgress, + message: encodeCloudflareVersionMessage([], omittedTraffic), + fetch: async () => Response.json({ ready: true }), + }), + ).resolves.toMatchObject({ ok: true, versionId: NEXT, previousVersionId: CURRENT }); + expect(onProgress).toHaveBeenCalledWith('Publishing the Worker atomically...'); + expect(runWrangler.mock.calls.filter(([args]) => args[0] === 'deploy')).toHaveLength(1); }); it('looks up the workers.dev subdomain for a staged candidate without a preview URL', async () => { diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 8ce4264605..a023e01006 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -17,13 +17,14 @@ import { } from './deploy-cloudflare-helpers.ts'; import type { CloudflareMigration } from './deploy-cloudflare-migrate.ts'; import type { CloudflareDeploySource, CloudflarePreflight } from './deploy-cloudflare-preflight.ts'; +import { readCloudflareEnvApiToken } from './deploy-cloudflare-token.ts'; import { log } from './deploy-helpers.ts'; import { formatCloudflareSandboxUnavailable, BETTER_AUTH_SECRET_NAME } from './deploy-resources.ts'; import { formatDeploySummary } from './deploy-summary.ts'; import type { CloudflareDeployDeps } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; import { note } from './output.ts'; -import { writeDeployOutputEntry } from './workers-builds.ts'; +import { reconfirmWorkersBuildsPlaceholder, writeDeployOutputEntry } from './workers-builds.ts'; import type { WorkersBuildsContext } from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; @@ -85,6 +86,18 @@ export async function publishCloudflareWorker(input: { if (usesCf && !cfUploaderIsPinned()) { return exit(1); } + const placeholderChanged = await reconfirmWorkersBuildsPlaceholder({ + placeholderVersionId: workersBuildsPlaceholderVersionId, + workerName, + accountId, + apiBaseUrl, + token: readCloudflareEnvApiToken(), + fetchImpl: deps.tokenProbeFetch, + }); + if (placeholderChanged) { + log.error(placeholderChanged); + return exit(1); + } let appliedMigrations = 0; const cfOutput = usesCf ? await prepareBuildOutput() : null; if (!cfOutput && usesCf) { diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 86ee281165..e2f6544795 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -80,6 +80,7 @@ import { deleteEnvVarCaseAware } from './provision.ts'; import type { AssetConfig, DeployManifest } from './types.ts'; import { confirmWorkersBuildsWorker, + reconfirmWorkersBuildsPlaceholder, workersBuildsTargetMismatch, workersBuildsVersionSource, writeDeployOutputEntry, @@ -589,6 +590,18 @@ export async function runCloudflareStaticDeploy( if (usesCf && !cfUploaderIsPinned()) { return exit(1); } + const placeholderChanged = await reconfirmWorkersBuildsPlaceholder({ + placeholderVersionId: buildsWorker.placeholderVersionId, + workerName, + accountId, + apiBaseUrl, + token: readCloudflareEnvApiToken(), + fetchImpl: deps.tokenProbeFetch, + }); + if (placeholderChanged) { + log.error(placeholderChanged); + return exit(1); + } const message = options.preview === undefined ? encodeCloudflareVersionMessage( diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 791b5f5b0b..309a195e11 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -162,7 +162,8 @@ const DASHBOARD_TEMPLATE_SOURCE = 'dash_template'; * The production version of the hello-world Worker that the Cloudflare dashboard creates before * the first Workers Builds deploy, or null when the Worker is anything else or cannot be read. * The proof: one version serves all traffic, the dashboard uploaded it from a template, it has - * no bindings and no Void deploy message, and the Worker has no routes or Custom Domains. + * only a fetch handler, no bindings and no Void deploy message, and the Worker has no routes or + * Custom Domains. */ export async function readWorkersBuildsPlaceholderVersion(input: { workerName: string; @@ -213,7 +214,10 @@ export async function readWorkersBuildsPlaceholderVersion(input: { const version = await read<{ id?: unknown; annotations?: Record; - resources?: { bindings?: unknown; script?: { last_deployed_from?: unknown } }; + resources?: { + bindings?: unknown; + script?: { handlers?: unknown; named_handlers?: unknown; last_deployed_from?: unknown }; + }; }>(`${script}/versions/${encodeURIComponent(versionId)}`); if ( !version || @@ -221,6 +225,11 @@ export async function readWorkersBuildsPlaceholderVersion(input: { version.resources?.script?.last_deployed_from !== DASHBOARD_TEMPLATE_SOURCE || !Array.isArray(version.resources.bindings) || version.resources.bindings.length !== 0 || + !isOnlyFetchHandler(version.resources.script.handlers) || + (version.resources.script.named_handlers !== undefined && + version.resources.script.named_handlers !== null && + (!Array.isArray(version.resources.script.named_handlers) || + version.resources.script.named_handlers.length !== 0)) || version.annotations?.['workers/message'] !== undefined ) { return null; @@ -247,6 +256,10 @@ export async function readWorkersBuildsPlaceholderVersion(input: { return versionId; } +function isOnlyFetchHandler(handlers: unknown): boolean { + return Array.isArray(handlers) && handlers.length === 1 && handlers[0] === 'fetch'; +} + /** * Check that the Worker this deploy targets is the one Workers Builds allows, as Wrangler * does with `WRANGLER_CI_MATCH_TAG`. Returns the confirmed Worker tag for the output entry @@ -330,6 +343,39 @@ export async function confirmWorkersBuildsWorker(input: { }; } +/** + * Prove again, right before activation, that the Worker is still the placeholder that preflight + * found, since the build takes minutes. Returns an error message when it changed. + */ +export async function reconfirmWorkersBuildsPlaceholder(input: { + placeholderVersionId: string | null; + workerName: string; + accountId: string; + apiBaseUrl: string; + token: string | undefined; + fetchImpl?: typeof fetch; +}): Promise { + if (!input.placeholderVersionId) { + return null; + } + const current = input.token + ? await readWorkersBuildsPlaceholderVersion({ + workerName: input.workerName, + accountId: input.accountId, + apiBaseUrl: input.apiBaseUrl, + token: input.token, + fetchImpl: input.fetchImpl, + }) + : null; + if (current === input.placeholderVersionId) { + return null; + } + return [ + `deploy: the Worker "${input.workerName}" changed during the build, so it is no longer the placeholder Worker that Cloudflare created.`, + 'Retry the build. The Worker was not deployed.', + ].join('\n'); +} + /** Source metadata for the version message, from Workers Builds. */ export function workersBuildsVersionSource( builds: WorkersBuildsContext | null | undefined, diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 23be78f56d..a81bd4488f 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14201,9 +14201,10 @@ describe('Workers Builds', () => { expect(init?.headers).toEqual({ Authorization: 'Bearer builds-token' }); }); - it('replaces the dashboard placeholder Worker on the first Builds deploy', async () => { - stubWorkersBuilds(); - const placeholder = '176ee95f-0000-4000-8000-000000000000'; + const PLACEHOLDER_VERSION = '176ee95f-0000-4000-8000-000000000000'; + + function stubPlaceholderWorker(domains: () => Array = () => []) { + const placeholder = PLACEHOLDER_VERSION; const account = 'https://api.cloudflare.com/client/v4/accounts/acc123/workers'; const servicesFetch = vi.mocked(fetch); vi.stubGlobal( @@ -14224,10 +14225,13 @@ describe('Workers Builds', () => { ? { id: placeholder, annotations: { 'workers/triggered_by': 'upload' }, - resources: { bindings: [], script: { last_deployed_from: 'dash_template' } }, + resources: { + bindings: [], + script: { handlers: ['fetch'], last_deployed_from: 'dash_template' }, + }, } : href === `${account}/domains?service=myapp` - ? [] + ? domains() : href === `${account}/scripts` ? [{ id: 'myapp', routes: null }] : undefined; @@ -14236,6 +14240,11 @@ describe('Workers Builds', () => { : Response.json({ success: true, result }); }), ); + } + + it('replaces the dashboard placeholder Worker on the first Builds deploy', async () => { + stubWorkersBuilds(); + stubPlaceholderWorker(); const root = d1Project(PROVISIONED_D1); const base = harness(); const activations: Array = []; @@ -14249,7 +14258,27 @@ describe('Workers Builds', () => { await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); expect(exitCalls).toEqual([]); - expect(activations).toEqual([placeholder]); + expect(activations).toEqual([PLACEHOLDER_VERSION]); + }); + + it('stops before activation when the placeholder Worker changed during the build', async () => { + stubWorkersBuilds(); + let domainReads = 0; + stubPlaceholderWorker(() => + ++domainReads === 1 ? [] : [{ hostname: 'app.example.com', service: 'myapp' }], + ); + const root = d1Project(PROVISIONED_D1); + const activateVersion = vi.fn(); + const { deps, exitCalls } = harness({ activateVersion }); + + const errors = await failedDeploy(root, deps); + + expect(exitCalls).toEqual([1]); + expect(domainReads).toBe(2); + expect(activateVersion).not.toHaveBeenCalled(); + expect(errors).toContain( + 'the Worker "myapp" changed during the build, so it is no longer the placeholder Worker', + ); }); it('stops before building when Builds passes the tag of another Worker', async () => { diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 9172fc941f..39961f0711 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -7,6 +7,7 @@ import { confirmWorkersBuildsWorker, readWorkersBuildsContext, readWorkersBuildsPlaceholderVersion, + reconfirmWorkersBuildsPlaceholder, resolveDeployOutputFile, withRecordedWorkersBuildsEnv, workersBuildsAccountMismatch, @@ -269,7 +270,10 @@ describe('Workers Builds placeholder Worker', () => { version: { id: STUB_VERSION, annotations: { 'workers/triggered_by': 'upload' }, - resources: { bindings: [], script: { last_deployed_from: 'dash_template' } }, + resources: { + bindings: [], + script: { handlers: ['fetch'], named_handlers: [], last_deployed_from: 'dash_template' }, + }, }, domains: [], scripts: [{ id: 'my-app', routes: null }], @@ -313,11 +317,36 @@ describe('Workers Builds placeholder Worker', () => { (fixture) => { fixture.version.resources = { bindings: [{ type: 'kv_namespace', name: 'KV' }], + script: { handlers: ['fetch'], last_deployed_from: 'dash_template' }, + }; + }, + (fixture) => { + fixture.version.resources = { + bindings: [], + script: { handlers: ['fetch'], last_deployed_from: 'dash' }, + }; + }, + (fixture) => { + fixture.version.resources = { + bindings: [], + script: { handlers: ['fetch', 'scheduled'], last_deployed_from: 'dash_template' }, + }; + }, + (fixture) => { + fixture.version.resources = { + bindings: [], script: { last_deployed_from: 'dash_template' }, }; }, (fixture) => { - fixture.version.resources = { bindings: [], script: { last_deployed_from: 'dash' } }; + fixture.version.resources = { + bindings: [], + script: { + handlers: ['fetch'], + named_handlers: [{ name: 'Counter', handlers: ['fetch'] }], + last_deployed_from: 'dash_template', + }, + }; }, (fixture) => { fixture.version.annotations = { 'workers/message': 'Edited in the dashboard' }; @@ -355,6 +384,28 @@ describe('Workers Builds placeholder Worker', () => { } }); + it('reconfirms the placeholder right before activation', async () => { + const reconfirm = (placeholderVersionId: string | null, fetchImpl: typeof fetch) => + reconfirmWorkersBuildsPlaceholder({ + placeholderVersionId, + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: API, + token: 'builds-token', + fetchImpl, + }); + const unchanged = respond(placeholder()); + await expect(reconfirm(STUB_VERSION, unchanged)).resolves.toBeNull(); + const notAdopting = respond(placeholder()); + await expect(reconfirm(null, notAdopting)).resolves.toBeNull(); + expect(notAdopting).not.toHaveBeenCalled(); + const changed = placeholder(); + changed.domains = [{ hostname: 'app.example.com', service: 'my-app' }]; + await expect(reconfirm(STUB_VERSION, respond(changed))).resolves.toContain( + 'the Worker "my-app" changed during the build', + ); + }); + it('reads the newest deployment', async () => { const fixture = placeholder(); fixture.deployments = { From bfc9395b979258d39358e0dcc8432d3f9659ef6e Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Sat, 28 Nov 2026 12:12:49 +0100 Subject: [PATCH 16/25] fix: reject a rollback to the dashboard template version as a Workers Builds placeholder --- packages/void/src/cli/workers-builds.ts | 21 ++++++++-- .../void/test/unit/workers-builds.test.ts | 38 +++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 309a195e11..0c5281d737 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -161,9 +161,9 @@ const DASHBOARD_TEMPLATE_SOURCE = 'dash_template'; /** * The production version of the hello-world Worker that the Cloudflare dashboard creates before * the first Workers Builds deploy, or null when the Worker is anything else or cannot be read. - * The proof: one version serves all traffic, the dashboard uploaded it from a template, it has - * only a fetch handler, no bindings and no Void deploy message, and the Worker has no routes or - * Custom Domains. + * The proof: one version has served all traffic in every deployment, the dashboard uploaded it + * from a template, it has only a fetch handler, no bindings and no Void deploy message, and the + * Worker has no routes or Custom Domains. */ export async function readWorkersBuildsPlaceholderVersion(input: { workerName: string; @@ -197,11 +197,13 @@ export async function readWorkersBuildsPlaceholderVersion(input: { versions?: Array<{ version_id?: unknown; percentage?: unknown }>; }>; }>(`${script}/deployments`); - const latest = deployments?.deployments + const history = deployments?.deployments; + const latest = history ?.filter((deployment) => typeof deployment.created_on === 'string') .sort((a, b) => String(b.created_on).localeCompare(String(a.created_on)))[0]; const traffic = latest?.versions; if ( + !history || !traffic || traffic.length !== 1 || typeof traffic[0].version_id !== 'string' || @@ -210,6 +212,17 @@ export async function readWorkersBuildsPlaceholderVersion(input: { return null; } const versionId = traffic[0].version_id; + // A rollback to the template version after another deployment is not a fresh placeholder. + if ( + !history.every( + (deployment) => + deployment.versions?.length === 1 && + deployment.versions[0].version_id === versionId && + Number(deployment.versions[0].percentage) === 100, + ) + ) { + return null; + } const version = await read<{ id?: unknown; diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 39961f0711..3668689b7f 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -423,6 +423,44 @@ describe('Workers Builds placeholder Worker', () => { await expect(read(respond(fixture))).resolves.toBeNull(); }); + it('rejects a rollback to the template version after another deployment', async () => { + const fixture = placeholder(); + fixture.deployments = { + deployments: [ + { + created_on: '2026-11-26T14:00:00.000Z', + versions: [{ version_id: STUB_VERSION, percentage: 100 }], + }, + { + created_on: '2026-11-26T13:00:00.000Z', + versions: [{ version_id: 'void-version', percentage: 100 }], + }, + { + created_on: '2026-11-26T12:00:00.000Z', + versions: [{ version_id: STUB_VERSION, percentage: 100 }], + }, + ], + }; + await expect(read(respond(fixture))).resolves.toBeNull(); + }); + + it('accepts the placeholder deployed more than once', async () => { + const fixture = placeholder(); + fixture.deployments = { + deployments: [ + { + created_on: '2026-11-26T13:00:00.000Z', + versions: [{ version_id: STUB_VERSION, percentage: 100 }], + }, + { + created_on: '2026-11-26T12:00:00.000Z', + versions: [{ version_id: STUB_VERSION, percentage: 100 }], + }, + ], + }; + await expect(read(respond(fixture))).resolves.toBe(STUB_VERSION); + }); + it('treats a failed read as no placeholder', async () => { await expect( read( From 7df56c69a332419321202463aae1294d11d3128e Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Sat, 28 Nov 2026 22:29:51 +0100 Subject: [PATCH 17/25] fix: name the missing token permission when Workers Builds cannot read the Worker --- docs/integrations/cloudflare.md | 2 ++ packages/void/src/cli/workers-builds.ts | 9 +++++++++ packages/void/test/unit/workers-builds.test.ts | 14 +++++++++++++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 7e65fc5a78..9e86fc0c24 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -285,6 +285,8 @@ Add `DATABASE_URL` and public `VITE_*` values under **Settings** > **Build** > * Commit `void.lock.json` when it changes locally. Workers Builds does not save files changed during a build, so on later builds Void finds the resources it created by name. +Email setup asks for confirmation, which a build cannot give. For an app that uses [email](../guide/email/domains.md#your-own-cloudflare-account), run `void email setup --platform cloudflare` once in your terminal and commit `void.lock.json`. Otherwise Void deploys without email. To fail the build instead, add `--require-email` to the deploy command. + Use `npx void deploy --platform cloudflare` only as the production deploy command. `void deploy` always deploys to production, so running it for another branch would replace your production Worker. Void does not support preview builds yet: clear **Enable Preview Builds** under **Settings** > **Build** > **Branch control**. ### Databases and secrets diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 0c5281d737..da7d72d6b7 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -320,6 +320,15 @@ export async function confirmWorkersBuildsWorker(input: { ].join('\n'), }; } + if (response.status === 401 || response.status === 403) { + return { + error: [ + `deploy: the Cloudflare API token cannot read the Worker "${input.workerName}" (HTTP ${response.status}).`, + 'Give the token Workers Scripts: Edit in My Profile > API Tokens, or choose a token that has it in your Worker under Settings > Build > API token. Then retry the build.', + 'Nothing was built or deployed.', + ].join('\n'), + }; + } if (!response.ok) { return retry(`Cloudflare API returned HTTP ${response.status}.`); } diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 3668689b7f..3ff8c3296b 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -230,9 +230,21 @@ describe('Workers Builds Worker tag check', () => { }); }); + it('names the token permission when the token cannot read the Worker', async () => { + for (const status of [401, 403]) { + const { result } = check(Response.json({ success: false }, { status })); + const outcome = await result; + expect(outcome).toHaveProperty('error'); + const message = (outcome as { error: string }).error; + expect(message).toContain(`cannot read the Worker "my-app" (HTTP ${status})`); + expect(message).toContain('Workers Scripts: Edit'); + expect(message).not.toContain('Retry the build.'); + } + }); + it('fails closed with a retry when the Worker cannot be read', async () => { for (const response of [ - Response.json({ success: false }, { status: 403 }), + Response.json({ success: false }, { status: 500 }), service(undefined), new Response('not json'), new Error('network down'), From aeda7fe03e3311b3967ad1e356254ecc5326f903 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Wed, 2 Dec 2026 09:59:35 +0100 Subject: [PATCH 18/25] test: cover a Workers Builds --preview deploy; qualify production-only docs --- docs/integrations/cloudflare.md | 2 +- .../void/test/unit/cloudflare-deploy.test.ts | 48 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 9e86fc0c24..01e6766b0f 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -287,7 +287,7 @@ Commit `void.lock.json` when it changes locally. Workers Builds does not save fi Email setup asks for confirmation, which a build cannot give. For an app that uses [email](../guide/email/domains.md#your-own-cloudflare-account), run `void email setup --platform cloudflare` once in your terminal and commit `void.lock.json`. Otherwise Void deploys without email. To fail the build instead, add `--require-email` to the deploy command. -Use `npx void deploy --platform cloudflare` only as the production deploy command. `void deploy` always deploys to production, so running it for another branch would replace your production Worker. Void does not support preview builds yet: clear **Enable Preview Builds** under **Settings** > **Build** > **Branch control**. +Use `npx void deploy --platform cloudflare` only as the production deploy command. Without `--preview`, `void deploy` deploys to production, so running it for another branch would replace your production Worker. Void does not support Workers Builds preview builds yet: clear **Enable Preview Builds** under **Settings** > **Build** > **Branch control**. ### Databases and secrets diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index a81bd4488f..dcb322b0cb 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14397,6 +14397,54 @@ describe('Workers Builds', () => { } }); + it('writes no production deploy result for a Preview', async () => { + const outputDir = mkdtempSync(join(tmpdir(), 'void-builds-output-')); + try { + stubWorkersBuilds({ WRANGLER_CI_OVERRIDE_NAME: 'spaapp' }); + vi.stubEnv('WRANGLER_OUTPUT_FILE_DIRECTORY', outputDir); + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify({ name: 'spaapp', account_id: 'acc123' }), + 'dist/index.html': '
', + }); + const base = harness(); + const activateVersion = vi.fn(base.deps.activateVersion); + const runWrangler = operationFixture((args) => { + if (args[0] === 'whoami') { + return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; + } + if (args[0] === 'previews') { + return { + ...cleanExit, + stdout: JSON.stringify({ + previewId: 'prv_1', + previewName: 'pr-64', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-spaapp.team.workers.dev', + deploymentUrl: 'https://dep1-spaapp.team.workers.dev', + }), + }; + } + return cleanExit; + }); + + await captureDeployOutput(() => + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, { + ...base.deps, + runWrangler, + activateVersion, + }), + ); + + expect(base.exitCalls).toEqual([]); + expect(activateVersion).not.toHaveBeenCalled(); + expect(readdirSync(outputDir)).toEqual([]); + } finally { + rmSync(outputDir, { recursive: true, force: true }); + } + }); + it('stops before provisioning or building when the Builds token lacks D1', async () => { stubWorkersBuilds({ CLOUDFLARE_API_TOKEN: 'builds-token' }); const root = d1Project({ account_id: 'acc123', name: 'myapp' }); From f74039af2aaef6bd5b465ce2463c85ac4d117c0b Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Wed, 2 Dec 2026 11:18:20 +0100 Subject: [PATCH 19/25] fix(cloudflare): apply migrations before publishing over the Workers Builds placeholder --- packages/deploy-cloudflare/src/version.ts | 6 +++ .../test/unit/version.test.ts | 50 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index e4c65ce8c6..ddb8eead26 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -1575,6 +1575,12 @@ async function activateCloudflareVersionWithSecretsFile( const alias = `void-ready-${Date.now().toString(36)}`; if (adoptsPlaceholder) { + if (options.beforeUpload) { + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + await options.beforeUpload(); + } // The placeholder serves nothing to keep, so publish over it as a new Worker would be. return bootstrapFirstDeployment( { ...options, message }, diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index cca4296e15..5f907fc19b 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -6813,6 +6813,56 @@ describe('Workers Builds placeholder adoption', () => { ).toBe(false); }); + it.each([false, true])( + 'prepares migrations before publishing over the placeholder (atomic=%s)', + async (atomic) => { + const order: Array = []; + const runWrangler = runner({ + versions: placeholderVersions, + bootstrap: ok(`Worker Version ID: ${NEXT}\nhttps://my-worker.example.workers.dev`), + }); + const beforeUpload = vi.fn(async () => { + order.push('migrations'); + }); + const result = await activateCloudflareVersion({ + runWrangler: async (operation, options) => { + if (operation.type === 'worker.deploy') { + order.push('deploy'); + } + return runWrangler(operation, options); + }, + workerName: 'my-worker', + verifyUploader: () => true, + adoptPlaceholderVersionId: CURRENT, + ...(atomic ? { atomic: true } : {}), + beforeUpload, + message: encodeCloudflareVersionMessage([], omittedTraffic), + fetch: async () => Response.json({ ready: true }), + }); + expect(result).toMatchObject({ ok: true, versionId: NEXT, previousVersionId: CURRENT }); + expect(beforeUpload).toHaveBeenCalledOnce(); + expect(order).toEqual(['migrations', 'deploy']); + }, + ); + + it('does not prepare migrations once the uploader changed', async () => { + const runWrangler = runner({ versions: placeholderVersions }); + const beforeUpload = vi.fn(async () => {}); + let checks = 0; + await expect( + activateCloudflareVersion({ + runWrangler, + workerName: 'my-worker', + verifyUploader: () => ++checks === 1, + adoptPlaceholderVersionId: CURRENT, + beforeUpload, + message: encodeCloudflareVersionMessage([], omittedTraffic), + }), + ).resolves.toMatchObject({ ok: false, reason: 'uploader-changed' }); + expect(beforeUpload).not.toHaveBeenCalled(); + expect(runWrangler.mock.calls.some(([args]) => args[0] === 'deploy')).toBe(false); + }); + it('stops when another version replaced the placeholder', async () => { const runWrangler = runner({ versions: placeholderVersions }); await expect( From 8735e0c9dc861fffc04b5dfb42be1d158da237bd Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Wed, 2 Dec 2026 12:10:50 +0100 Subject: [PATCH 20/25] fix: ask for a retry when the Workers Builds placeholder check cannot finish --- packages/void/src/cli/workers-builds.ts | 75 +++++++++++++------ .../void/test/unit/cloudflare-deploy.test.ts | 3 + .../void/test/unit/workers-builds.test.ts | 61 ++++++++++++--- 3 files changed, 108 insertions(+), 31 deletions(-) diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index da7d72d6b7..e5c624095c 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -155,6 +155,9 @@ export function workersBuildsAccountMismatch( ].join('\n'); } +/** A placeholder check that could not finish, so the Worker may still be the placeholder. */ +export class WorkersBuildsReadError extends Error {} + /** The source Cloudflare records for a Worker version the dashboard creates from a template. */ const DASHBOARD_TEMPLATE_SOURCE = 'dash_template'; @@ -163,7 +166,8 @@ const DASHBOARD_TEMPLATE_SOURCE = 'dash_template'; * the first Workers Builds deploy, or null when the Worker is anything else or cannot be read. * The proof: one version has served all traffic in every deployment, the dashboard uploaded it * from a template, it has only a fetch handler, no bindings and no Void deploy message, and the - * Worker has no routes or Custom Domains. + * Worker has no routes or Custom Domains. A network error, an unreadable body, HTTP 429 or a + * server error throws {@link WorkersBuildsReadError}: the Worker may still be the placeholder. */ export async function readWorkersBuildsPlaceholderVersion(input: { workerName: string; @@ -175,20 +179,29 @@ export async function readWorkersBuildsPlaceholderVersion(input: { const account = `${input.apiBaseUrl}/accounts/${encodeURIComponent(input.accountId)}/workers`; const script = `${account}/scripts/${encodeURIComponent(input.workerName)}`; const read = async (url: string): Promise => { + let response: Response; try { - const response = await (input.fetchImpl ?? fetch)(url, { + response = await (input.fetchImpl ?? fetch)(url, { headers: { Authorization: `Bearer ${input.token}` }, redirect: 'error', signal: AbortSignal.timeout(30_000), }); - if (!response.ok) { - return null; - } - const body = await response.json<{ success?: unknown; result?: T }>(); - return body.success === true && body.result !== undefined ? body.result : null; - } catch { + } catch (error) { + throw new WorkersBuildsReadError(error instanceof Error ? error.message : String(error)); + } + if (response.status === 429 || response.status >= 500) { + throw new WorkersBuildsReadError(`Cloudflare API returned HTTP ${response.status}.`); + } + if (!response.ok) { return null; } + let body: { success?: unknown; result?: T }; + try { + body = await response.json<{ success?: unknown; result?: T }>(); + } catch { + throw new WorkersBuildsReadError('Cloudflare API returned an unreadable response.'); + } + return body.success === true && body.result !== undefined ? body.result : null; }; const deployments = await read<{ @@ -353,16 +366,23 @@ export async function confirmWorkersBuildsWorker(input: { ].join('\n'), }; } - return { - workerTag: tag, - placeholderVersionId: await readWorkersBuildsPlaceholderVersion({ - workerName: input.workerName, - accountId: input.accountId, - apiBaseUrl: input.apiBaseUrl, - token: input.token, - fetchImpl: input.fetchImpl, - }), - }; + try { + return { + workerTag: tag, + placeholderVersionId: await readWorkersBuildsPlaceholderVersion({ + workerName: input.workerName, + accountId: input.accountId, + apiBaseUrl: input.apiBaseUrl, + token: input.token, + fetchImpl: input.fetchImpl, + }), + }; + } catch (error) { + if (error instanceof WorkersBuildsReadError) { + return retry(`could not check whether it is still the placeholder Worker: ${error.message}`); + } + throw error; + } } /** @@ -380,15 +400,26 @@ export async function reconfirmWorkersBuildsPlaceholder(input: { if (!input.placeholderVersionId) { return null; } - const current = input.token - ? await readWorkersBuildsPlaceholderVersion({ + let current: string | null = null; + if (input.token) { + try { + current = await readWorkersBuildsPlaceholderVersion({ workerName: input.workerName, accountId: input.accountId, apiBaseUrl: input.apiBaseUrl, token: input.token, fetchImpl: input.fetchImpl, - }) - : null; + }); + } catch (error) { + if (!(error instanceof WorkersBuildsReadError)) { + throw error; + } + return [ + `deploy: could not check that the Worker "${input.workerName}" is still the placeholder Worker that Cloudflare created: ${error.message}`, + 'Retry the build. The Worker was not deployed.', + ].join('\n'); + } + } if (current === input.placeholderVersionId) { return null; } diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index dcb322b0cb..416686869d 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14111,6 +14111,9 @@ describe('Workers Builds', () => { 'fetch', vi.fn(async (url: string | URL | Request) => { const href = String(url); + if (href.includes('/workers/scripts') || href.includes('/workers/domains')) { + return Response.json({ success: false }, { status: 404 }); + } if (!href.includes('/workers/services/')) { throw new Error(`unexpected fetch ${href}`); } diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 3ff8c3296b..0d09396031 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -160,7 +160,7 @@ describe('Workers Builds Worker tag check', () => { if (response instanceof Error) { throw response; } - return response; + return response.clone(); }); const result = confirmWorkersBuildsWorker({ builds, @@ -473,19 +473,62 @@ describe('Workers Builds placeholder Worker', () => { await expect(read(respond(fixture))).resolves.toBe(STUB_VERSION); }); - it('treats a failed read as no placeholder', async () => { - await expect( - read( - vi.fn(async () => { - throw new Error('network down'); - }), - ), - ).resolves.toBeNull(); + it('treats a rejected read as no placeholder', async () => { await expect( read(vi.fn(async () => Response.json({ success: false }, { status: 403 }))), ).resolves.toBeNull(); }); + it('asks for a retry when the placeholder check cannot finish', async () => { + const transient = (status: number) => { + const healthy = respond(placeholder()); + return vi.fn(async (input, init) => + String(input) === `${ACCOUNT}/domains?service=my-app` + ? Response.json({ success: false }, { status }) + : healthy(input, init), + ); + }; + const offline = vi.fn(async () => { + throw new Error('network down'); + }); + await expect(read(offline)).rejects.toThrow('network down'); + await expect(read(transient(503))).rejects.toThrow('HTTP 503'); + await expect(read(transient(429))).rejects.toThrow('HTTP 429'); + + const services = (fallback: typeof fetch) => + vi.fn(async (input, init) => + String(input) === `${ACCOUNT}/services/my-app` + ? Response.json({ + success: true, + result: { default_environment: { script: { tag: 'tag-1' } } }, + }) + : fallback(input, init), + ); + const confirmed = await confirmWorkersBuildsWorker({ + builds: readWorkersBuildsContext(BUILDS_ENV), + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: API, + token: 'builds-token', + fetchImpl: services(transient(502)), + }); + expect(confirmed).toEqual({ + error: expect.stringContaining('could not check whether it is still the placeholder Worker'), + }); + expect(confirmed).toEqual({ error: expect.stringContaining('Retry the build.') }); + + await expect( + reconfirmWorkersBuildsPlaceholder({ + placeholderVersionId: STUB_VERSION, + workerName: 'my-app', + accountId: 'account-1', + apiBaseUrl: API, + token: 'builds-token', + fetchImpl: offline, + }), + ).resolves.toContain('could not check that the Worker "my-app" is still the placeholder'); + }); + it('reports the placeholder with the confirmed Worker tag', async () => { const fixture = placeholder(); const placeholderFetch = respond(fixture); From 7afe2174e19cf0dd0c92222fbdacddac12d15bfb Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Wed, 2 Dec 2026 16:23:41 +0100 Subject: [PATCH 21/25] docs: name void.lock.json and the checked products in the Workers Builds section --- docs/integrations/cloudflare.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 01e6766b0f..10f3f09c00 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -256,7 +256,7 @@ Add the same `--dir` and `--spa` flags as your production deploy. Using npm, Yar | Deploy command | `npx void deploy --platform cloudflare` | | Root directory | The app folder, if it is not the repository root. | -The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts`, or your `package.json` name. If `void.config.ts` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. +The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts` or `void.lock.json`, or your `package.json` name. If `void.config.ts` or `void.lock.json` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. In Workers Builds, Void deploys without prompts or a browser sign-in. It uses the build's API token and account. After a successful deploy, Workers Builds links the build to the Worker version it deployed, and the version message records the commit and branch. @@ -275,7 +275,7 @@ A token keeps its permissions when Workers Builds changes the permissions of new | PostgreSQL or MySQL via Hyperdrive | Hyperdrive Edit | | `email/` handlers | Email Routing Rules Edit and Email Routing Account Rules Read | -Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Build** > **API token**. Void checks the token before building and names any missing permission. +Edit the token in **My Profile** > **API Tokens**, or choose a different token in your Worker under **Settings** > **Build** > **API token**. Before building, Void checks that the token can use the D1, Queues, Hyperdrive, Workers KV, and R2 resources your app needs, and names any missing permission. To deploy with another token, add a build secret named `CLOUDFLARE_API_TOKEN` under **Settings** > **Build** > **Build variables and secrets**. It replaces the build's token. A `CLOUDFLARE_ACCOUNT_ID` build variable replaces the build's account the same way. From 77751907d37211123c2ee649d0e477f7ab940f06 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Fri, 4 Dec 2026 21:40:56 +0100 Subject: [PATCH 22/25] docs: point multi-app repositories to one Workers Builds connection per Worker --- docs/guide/deployment.md | 2 +- docs/integrations/cloudflare.md | 2 +- packages/void/src/cli/workers-builds.ts | 2 +- packages/void/test/unit/workers-builds.test.ts | 3 +++ 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 5d14117bab..8ec2cec2c5 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -114,7 +114,7 @@ If CI runs typechecking before deploy, run `void prepare` after installing depen | Build command | Leave empty | | Deploy command | `npx void deploy --platform cloudflare` | -The Worker name in Workers Builds must match the name Void deploys. The API token that Workers Builds creates includes the permissions most Void apps need. Older or custom tokens, and apps that use email, need [extra permissions](../integrations/cloudflare.md#api-token-permissions). See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. +The Worker name in Workers Builds must match the name Void deploys. For several apps in one repository, connect each app's Worker with that app's folder as its root directory. The API token that Workers Builds creates includes the permissions most Void apps need. Older or custom tokens, and apps that use email, need [extra permissions](../integrations/cloudflare.md#api-token-permissions). See [Deploying with Workers Builds](../integrations/cloudflare.md#workers-builds) for token permissions, variables, and branch settings. ## Deploy to a team platform diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 10f3f09c00..5c7a8469fe 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -256,7 +256,7 @@ Add the same `--dir` and `--spa` flags as your production deploy. Using npm, Yar | Deploy command | `npx void deploy --platform cloudflare` | | Root directory | The app folder, if it is not the repository root. | -The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts` or `void.lock.json`, or your `package.json` name. If `void.config.ts` or `void.lock.json` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. +The Worker name in Workers Builds must match the name Void deploys: `cloudflare.name` in `void.config.ts` or `void.lock.json`, or your `package.json` name. If `void.config.ts` or `void.lock.json` sets `cloudflare.account_id`, it must be the account that runs the build. Void stops before building when either differs and names the setting to change. For a repository with several Void apps, connect the repository to each app's Worker and set each Worker's root directory to that app's folder. In Workers Builds, Void deploys without prompts or a browser sign-in. It uses the build's API token and account. After a successful deploy, Workers Builds links the build to the Worker version it deployed, and the version message records the commit and branch. diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index e5c624095c..fc54f4b456 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -135,7 +135,7 @@ export function workersBuildsTargetMismatch( : 'the package.json name'; return [ `deploy: Workers Builds is connected to the Worker "${builds.workerName}", but this project deploys "${target.workerName}" (from ${source}).`, - `Set cloudflare.name to "${builds.workerName}" in void.config.ts and commit it, or connect this repository to the Worker "${target.workerName}" in Workers Builds.`, + `Set cloudflare.name to "${builds.workerName}" in void.config.ts and commit it, or connect this repository to the Worker "${target.workerName}" in Workers Builds with this app's folder as its root directory.`, 'Nothing was built or deployed.', ].join('\n'); } diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 0d09396031..f3679ff0fd 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -132,6 +132,9 @@ describe('Workers Builds target checks', () => { expect(message).toContain('Workers Builds is connected to the Worker "my-app"'); expect(message).toContain('this project deploys "other-app" (from the package.json name)'); expect(message).toContain('Set cloudflare.name to "my-app" in void.config.ts'); + expect(message).toContain( + 'connect this repository to the Worker "other-app" in Workers Builds with this app\'s folder as its root directory', + ); expect(message).toContain('Nothing was built or deployed.'); }); From fe853ed17edf69518f1f6672aa6ea7db4568a4e2 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Sat, 5 Dec 2026 12:03:24 +0900 Subject: [PATCH 23/25] Pin the Builds account and verify production routes before claiming a Worker. --- packages/deploy-cloudflare/src/version.ts | 3 +- .../test/unit/version.test.ts | 3 ++ .../void/src/cli/deploy-cloudflare-helpers.ts | 5 ++- packages/void/src/cli/workers-builds.ts | 17 +++------- .../void/test/unit/cloudflare-deploy.test.ts | 34 +++++++++++++++++-- .../void/test/unit/workers-builds.test.ts | 12 +++---- 6 files changed, 51 insertions(+), 23 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index ddb8eead26..65f95929ff 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -227,8 +227,9 @@ const MAX_VERSION_MESSAGE_BYTES = 1000; export function encodeCloudflareVersionMessage( history: ReadonlyArray | MigrationSummary | null, triggerConfig?: CloudflareTriggerConfig, - extra: Readonly<{ contentHash?: string; source?: CloudflareVersionSource }> = {}, + options: string | Readonly<{ contentHash?: string; source?: CloudflareVersionSource }> = {}, ): string { + const extra = typeof options === 'string' ? { contentHash: options } : options; const source = parseVersionSource(extra.source); const migrationState = history && 'digest' in history diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 5f907fc19b..d077dae891 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -3121,6 +3121,9 @@ describe('Cloudflare version activation', () => { it('round-trips an upload digest only when it is a valid SHA-256 value', () => { const triggers = triggersWith({ preview_urls: false }); const digest = 'a'.repeat(64); + expect( + parseCloudflareVersionMessage(encodeCloudflareVersionMessage([], triggers, digest)), + ).toMatchObject({ contentHash: digest }); expect( parseCloudflareVersionMessage( encodeCloudflareVersionMessage([], triggers, { contentHash: digest }), diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 2c4d6e6a59..88e1d9a52c 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -195,7 +195,10 @@ export async function connectCloudflareDeployAccount(options: { log.error(accountMismatch); return null; } - let accountId = configAccountId ?? (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); + let accountId = + configAccountId ?? + options.workersBuilds?.accountId ?? + (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); if (!accountId) { const accountRunner = observeCloudflareRunner( deps.runWrangler ?? createDeployWranglerRunner(root, undefined, apiBaseUrl), diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index fc54f4b456..b0774c6703 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -267,19 +267,10 @@ export async function readWorkersBuildsPlaceholderVersion(input: { if (!Array.isArray(domains) || domains.length !== 0) { return null; } - const scripts = await read>(`${account}/scripts`); - const listed = Array.isArray(scripts) - ? scripts.find((entry) => entry.id === input.workerName) - : undefined; - if ( - !listed || - (listed.routes !== null && - listed.routes !== undefined && - (!Array.isArray(listed.routes) || listed.routes.length !== 0)) - ) { - return null; - } - return versionId; + const routes = await read>( + `${account}/services/${encodeURIComponent(input.workerName)}/environments/production/routes`, + ); + return Array.isArray(routes) && routes.length === 0 ? versionId : null; } function isOnlyFetchHandler(handlers: unknown): boolean { diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 416686869d..e30f06a7ea 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14172,6 +14172,36 @@ describe('Workers Builds', () => { expect(errors).toContain('Workers Builds runs in account builds-account'); }); + it('uses the recorded Builds account when the project does not specify one', async () => { + const reads = stubWorkersBuilds( + { CLOUDFLARE_ACCOUNT_ID: 'different-account' }, + { status: 403 }, + ); + const root = d1Project({ ...PROVISIONED_D1, account_id: undefined }); + const { deps } = harness(); + await expect( + runCloudflareDeploy( + root, + { + platform: 'cloudflare', + workersBuilds: { + buildId: null, + branch: null, + commit: null, + matchTag: BUILDS_TAG, + workerName: 'myapp', + accountId: 'recorded-account', + }, + }, + silentCliLog, + deps, + ), + ).rejects.toBeInstanceOf(ExitError); + expect(reads).toEqual([ + expect.stringContaining('/accounts/recorded-account/workers/services/myapp'), + ]); + }); + it('checks the Builds Worker before building a static site', async () => { stubWorkersBuilds({ WRANGLER_CI_OVERRIDE_NAME: 'builds-site' }); const root = makeProject({ @@ -14235,8 +14265,8 @@ describe('Workers Builds', () => { } : href === `${account}/domains?service=myapp` ? domains() - : href === `${account}/scripts` - ? [{ id: 'myapp', routes: null }] + : href === `${account}/services/myapp/environments/production/routes` + ? [] : undefined; return result === undefined ? servicesFetch(url, init) diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index f3679ff0fd..be1764ae4d 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -269,7 +269,7 @@ describe('Workers Builds placeholder Worker', () => { deployments: unknown; version: Record; domains: unknown; - scripts: unknown; + routes: unknown; }; function placeholder(): Fixture { @@ -291,7 +291,7 @@ describe('Workers Builds placeholder Worker', () => { }, }, domains: [], - scripts: [{ id: 'my-app', routes: null }], + routes: [], }; } @@ -305,8 +305,8 @@ describe('Workers Builds placeholder Worker', () => { ? fixture.version : url === `${ACCOUNT}/domains?service=my-app` ? fixture.domains - : url === `${ACCOUNT}/scripts` - ? fixture.scripts + : url === `${ACCOUNT}/services/my-app/environments/production/routes` + ? fixture.routes : undefined; return result === undefined ? Response.json({ success: false }, { status: 404 }) @@ -386,10 +386,10 @@ describe('Workers Builds placeholder Worker', () => { fixture.domains = [{ hostname: 'app.example.com', service: 'my-app' }]; }, (fixture) => { - fixture.scripts = [{ id: 'my-app', routes: [{ pattern: 'example.com/*' }] }]; + fixture.routes = [{ pattern: 'example.com/*' }]; }, (fixture) => { - fixture.scripts = [{ id: 'another-app', routes: null }]; + fixture.routes = undefined; }, ]; for (const change of variants) { From a36bcd157fe9047df284085f251342e529a4492a Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Sat, 5 Dec 2026 12:04:35 +0900 Subject: [PATCH 24/25] Require the Builds token before deploying a tagged Worker. --- packages/void/src/cli/workers-builds.ts | 8 +++++++- packages/void/test/unit/cloudflare-deploy.test.ts | 8 ++++++++ packages/void/test/unit/workers-builds.test.ts | 4 ++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index b0774c6703..0be9832bd5 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -293,9 +293,15 @@ export async function confirmWorkersBuildsWorker(input: { fetchImpl?: typeof fetch; }): Promise<{ workerTag: string | null; placeholderVersionId: string | null } | { error: string }> { const matchTag = input.builds?.matchTag; - if (!matchTag || !input.token) { + if (!matchTag) { return { workerTag: null, placeholderVersionId: null }; } + if (!input.token) { + return { + error: + 'deploy: Workers Builds supplied a Worker tag, but its build token is missing. Set CLOUDFLARE_API_TOKEN in the build environment and retry.', + }; + } const retry = (reason: string) => ({ error: [ `deploy: could not confirm that Workers Builds may deploy the Worker "${input.workerName}": ${reason}`, diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index e30f06a7ea..df2811fb17 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14172,6 +14172,14 @@ describe('Workers Builds', () => { expect(errors).toContain('Workers Builds runs in account builds-account'); }); + it('stops before using a cached CLI session when a tagged build has no token', async () => { + stubWorkersBuilds({ CLOUDFLARE_API_TOKEN: '', CF_API_TOKEN: '' }); + const { deps, trace } = harness(); + const errors = await failedDeploy(d1Project(PROVISIONED_D1), deps); + expect(errors).toContain('build token is missing'); + expect(trace).not.toContain('build'); + }); + it('uses the recorded Builds account when the project does not specify one', async () => { const reads = stubWorkersBuilds( { CLOUDFLARE_ACCOUNT_ID: 'different-account' }, diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index be1764ae4d..6955636675 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -188,7 +188,7 @@ describe('Workers Builds Worker tag check', () => { ); }); - it('checks nothing outside Builds, without a match tag, or without a token', async () => { + it('skips untagged builds and stops a tagged build when its token is missing', async () => { const fetchImpl = vi.fn(); const base = { workerName: 'my-app', @@ -208,7 +208,7 @@ describe('Workers Builds Worker tag check', () => { ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); await expect( confirmWorkersBuildsWorker({ ...base, builds, token: undefined }), - ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); + ).resolves.toMatchObject({ error: expect.stringContaining('CLOUDFLARE_API_TOKEN') }); expect(fetchImpl).not.toHaveBeenCalled(); }); From 1ef36c189a1025de40fb3df4f52a486d618d0d0f Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Sat, 5 Dec 2026 19:49:55 +0100 Subject: [PATCH 25/25] fix: point a missing Workers Builds token to its API token setting; deprecate the string version-message argument --- packages/deploy-cloudflare/src/version.ts | 11 +++++++++++ packages/void/src/cli/deploy-cloudflare-token.ts | 5 ++++- packages/void/src/cli/workers-builds.ts | 6 ++++-- packages/void/test/unit/cloudflare-deploy.test.ts | 3 ++- packages/void/test/unit/workers-builds.test.ts | 2 +- 5 files changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 72285fb111..7b8972ad3f 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -224,6 +224,17 @@ const Buffer = NodeBuffer as BufferConstructor; const MAX_VERSION_MESSAGE_BYTES = 1000; /** Encode migration state into Cloudflare's version annotation for safe rollback diagnostics. */ +export function encodeCloudflareVersionMessage( + history: ReadonlyArray | MigrationSummary | null, + triggerConfig?: CloudflareTriggerConfig, + options?: Readonly<{ contentHash?: string; source?: CloudflareVersionSource }>, +): string; +/** @deprecated Pass `{ contentHash }` as the third argument instead of a string. */ +export function encodeCloudflareVersionMessage( + history: ReadonlyArray | MigrationSummary | null, + triggerConfig: CloudflareTriggerConfig | undefined, + contentHash: string, +): string; export function encodeCloudflareVersionMessage( history: ReadonlyArray | MigrationSummary | null, triggerConfig?: CloudflareTriggerConfig, diff --git a/packages/void/src/cli/deploy-cloudflare-token.ts b/packages/void/src/cli/deploy-cloudflare-token.ts index d9b620e2c1..f058c54c35 100644 --- a/packages/void/src/cli/deploy-cloudflare-token.ts +++ b/packages/void/src/cli/deploy-cloudflare-token.ts @@ -27,7 +27,10 @@ export type CloudflareTokenProbe = Readonly<{ operation: CloudflareOperation | null; }>; -/** The API token this deploy uses from the environment, or undefined for a browser session. */ +/** + * The API token this deploy uses from the environment, or undefined for a browser session. + * Read at call time like every other deploy step, so a check and the step it guards use one token. + */ export function readCloudflareEnvApiToken( env: NodeJS.ProcessEnv = process.env, ): string | undefined { diff --git a/packages/void/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts index 0be9832bd5..fc956757a6 100644 --- a/packages/void/src/cli/workers-builds.ts +++ b/packages/void/src/cli/workers-builds.ts @@ -298,8 +298,10 @@ export async function confirmWorkersBuildsWorker(input: { } if (!input.token) { return { - error: - 'deploy: Workers Builds supplied a Worker tag, but its build token is missing. Set CLOUDFLARE_API_TOKEN in the build environment and retry.', + error: [ + 'deploy: Workers Builds supplied a Worker tag but no API token, so Void cannot confirm which Worker this build may deploy.', + 'Choose an API token in your Worker under Settings > Build > API token, then retry the build.', + ].join('\n'), }; } const retry = (reason: string) => ({ diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index a2264f4da0..aaf6346b0c 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -14215,7 +14215,8 @@ describe('Workers Builds', () => { stubWorkersBuilds({ CLOUDFLARE_API_TOKEN: '', CF_API_TOKEN: '' }); const { deps, trace } = harness(); const errors = await failedDeploy(d1Project(PROVISIONED_D1), deps); - expect(errors).toContain('build token is missing'); + expect(errors).toContain('Workers Builds supplied a Worker tag but no API token'); + expect(errors).toContain('Settings > Build > API token'); expect(trace).not.toContain('build'); }); diff --git a/packages/void/test/unit/workers-builds.test.ts b/packages/void/test/unit/workers-builds.test.ts index 6955636675..fcf1fa5033 100644 --- a/packages/void/test/unit/workers-builds.test.ts +++ b/packages/void/test/unit/workers-builds.test.ts @@ -208,7 +208,7 @@ describe('Workers Builds Worker tag check', () => { ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); await expect( confirmWorkersBuildsWorker({ ...base, builds, token: undefined }), - ).resolves.toMatchObject({ error: expect.stringContaining('CLOUDFLARE_API_TOKEN') }); + ).resolves.toMatchObject({ error: expect.stringContaining('Settings > Build > API token') }); expect(fetchImpl).not.toHaveBeenCalled(); });