diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 637907b9c..8ec2cec2c 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. 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 Use the API URL from your administrator. In a new or unlinked app: diff --git a/docs/guide/email/domains.md b/docs/guide/email/domains.md index d878debac..d6e19bb52 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 645c634a3..5c7a8469f 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -134,18 +134,18 @@ 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/). -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 @@ -246,6 +246,49 @@ 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 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 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. 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. + +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. + +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 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**. 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. + +#### Variables and branches + +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. + +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. 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 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). diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 074ccafc2..57fa7e0c2 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -100,19 +100,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/index.ts b/packages/deploy-cloudflare/src/index.ts index ab5a2aef8..4b20d783f 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, @@ -58,6 +59,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 eb6327004..7b8972ad3 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,33 @@ const MAX_VERSION_MESSAGE_BYTES = 1000; export function encodeCloudflareVersionMessage( history: ReadonlyArray | MigrationSummary | null, triggerConfig?: CloudflareTriggerConfig, - contentHash?: string, + 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, + 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 ? { 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 +397,7 @@ export function parseCloudflareVersionMessage( if (!triggerConfig) { return null; } + const source = parseVersionSource(value.source); return { schema: 2, ...migrationState, @@ -377,12 +405,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. @@ -1093,8 +1140,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; @@ -1125,6 +1172,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; /** @@ -1158,6 +1213,45 @@ type InternalCloudflareVersionActivationOptions = CloudflareVersionActivationOpt candidateSecretsFilePath?: string; }; +/** + * 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 + ); +} + /** Upload, probe, and atomically activate a verified Worker Version. */ export async function activateCloudflareVersion( options: CloudflareVersionActivationOptions, @@ -1211,6 +1305,18 @@ async function activateCloudflareVersionWithSecretsFile( return { ok: false, reason: 'uploader-changed' }; } const previousVersionId = previous.versionId; + const adoptsPlaceholder = + options.adoptPlaceholderVersionId !== undefined && + !options.preserveTriggers && + !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, @@ -1437,7 +1543,7 @@ async function activateCloudflareVersionWithSecretsFile( const resolved = resolvePreservedTraffic( desiredTriggerConfig, previousTrafficConfig, - previous.versionId !== null && !(await previousIsSecretOnlyDraft()), + previous.versionId !== null && !adoptsPlaceholder && !(await previousIsSecretOnlyDraft()), ); if (!resolved) { return { @@ -1467,7 +1573,7 @@ async function activateCloudflareVersionWithSecretsFile( ? encodeCloudflareVersionMessage( desiredMetadata.migrations ?? desiredMetadata.migrationSummary ?? null, desiredTriggerConfig, - desiredMetadata.contentHash, + { contentHash: desiredMetadata.contentHash, source: desiredMetadata.source }, ) : options.message; const versionedPreviousTriggerConfigWithTraffic = @@ -1480,6 +1586,22 @@ 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 }, + previous.versionId, + options.atomic === true, + previousTriggerConfig, + previousIsRestorePlaceholder, + ); + } const bootstrapVoidDraft = !options.preserveTriggers && !options.requirePreviewForReadiness && @@ -1839,8 +1961,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 b608b7fd6..217aed8b5 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, @@ -2580,12 +2581,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 +2610,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 +2620,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 () => { @@ -3112,6 +3124,11 @@ describe('Cloudflare version activation', () => { expect( parseCloudflareVersionMessage(encodeCloudflareVersionMessage([], triggers, digest)), ).toMatchObject({ contentHash: digest }); + expect( + parseCloudflareVersionMessage( + encodeCloudflareVersionMessage([], triggers, { contentHash: digest }), + ), + ).toMatchObject({ contentHash: digest }); expect( parseCloudflareVersionMessage( `void:${JSON.stringify({ schema: 2, migrations: [], triggerConfig: triggers, contentHash: 'bad' })}`, @@ -3119,6 +3136,45 @@ 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":[]}', + ); + }); + + 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 @@ -6756,3 +6812,285 @@ 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.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( + 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', 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 () => { + 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/cloudflare-auth.ts b/packages/void/src/cli/cloudflare-auth.ts index ac485c3d4..3b4d5adda 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 66c81186b..820bc873f 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/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index 753abb977..4034ba20d 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 { @@ -517,6 +521,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) { @@ -840,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; }, }); @@ -858,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-cloudflare-auth.ts b/packages/void/src/cli/deploy-cloudflare-auth.ts index 050c2d832..6ccfbe379 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 = @@ -260,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; @@ -268,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 => { @@ -315,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 b959f0899..debe1cab3 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,8 +189,15 @@ export async function connectCloudflareDeployAccount(options: { ); // Pin the uploaders before the first authenticated command, including account discovery. const pins = createCloudflareUploaderPins(root, deps); + const configAccountId = readWranglerTopLevelString(rootConfig, 'account_id'); + const accountMismatch = workersBuildsAccountMismatch(options.workersBuilds, configAccountId); + if (accountMismatch) { + log.error(accountMismatch); + return null; + } let accountId = - readWranglerTopLevelString(rootConfig, 'account_id') ?? + configAccountId ?? + options.workersBuilds?.accountId ?? (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); if (!accountId) { const accountRunner = observeCloudflareRunner( @@ -679,7 +690,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 18ccaf782..71eb802ee 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'; @@ -18,6 +20,9 @@ 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'; +import { readWranglerPublishedTrafficSnapshot } from './wrangler.ts'; export type CloudflareMigration = Awaited>; @@ -31,6 +36,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. */ @@ -42,19 +48,55 @@ 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; 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(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. @@ -83,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 6622e2f7d..9ba6c5b74 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, @@ -78,6 +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 { confirmWorkersBuildsWorker, workersBuildsTargetMismatch } from './workers-builds.ts'; import { sameMigrationsDir, writeProvisionedWranglerConfig } from './wrangler.ts'; /** Validate source-level native deploy inputs before account operations or project code. */ @@ -199,6 +205,10 @@ export type CloudflareDeploySource = NonNullable< 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; @@ -269,6 +279,7 @@ export async function preflightCloudflareWorker(input: { persistAccount: !(options.reuseExistingWorker || initialCloudflareLink), readinessAccessOrigin: options.readinessAccessOrigin, reporter, + workersBuilds: options.workersBuilds, }); if (!connection) { return exit(1); @@ -277,12 +288,33 @@ 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, 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({ @@ -527,6 +559,41 @@ export async function preflightCloudflareWorker(input: { } } + // 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 = + 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. @@ -722,6 +789,8 @@ export async function preflightCloudflareWorker(input: { return { ...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 2e4d812a8..865608d26 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -17,12 +17,15 @@ 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 { reconfirmWorkersBuildsPlaceholder, 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. */ @@ -40,6 +43,10 @@ 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; + /** 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; @@ -50,6 +57,8 @@ export async function publishCloudflareWorker(input: { pinnedHandoffLink, accountId, workerName, + workersBuildsWorkerTag, + workersBuildsPlaceholderVersionId, cfUploaderIsPinned, apiBaseUrl, complianceRegion, @@ -78,6 +87,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) { @@ -139,6 +160,9 @@ export async function publishCloudflareWorker(input: { verifyTarget(); }), allowFirstDeploymentBootstrap: workerWasMissingBeforeSecretProvisioning, + ...(workersBuildsPlaceholderVersionId + ? { adoptPlaceholderVersionId: workersBuildsPlaceholderVersionId } + : {}), ...(pinActiveSecrets ? { pinActiveSecrets } : {}), atomic, ...(input.readinessAttempts !== undefined @@ -176,6 +200,17 @@ 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, + workerTag: workersBuildsWorkerTag, + 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 ac59349d6..6557e1bc8 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, @@ -77,6 +78,13 @@ 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 { + confirmWorkersBuildsWorker, + reconfirmWorkersBuildsPlaceholder, + workersBuildsTargetMismatch, + workersBuildsVersionSource, + writeDeployOutputEntry, +} from './workers-builds.ts'; import { readWranglerManagedQueueCleanupCandidates } from './wrangler.ts'; /** Default runtime date for static and framework Workers that set none. */ @@ -388,6 +396,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 +430,28 @@ 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); + } + 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 { @@ -560,12 +590,28 @@ 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([], { - ...readCloudflareTriggerConfig(staticConfigPath, configPath), - ...(existingWorker ? { preserve: true } : {}), - }) + ? encodeCloudflareVersionMessage( + [], + { + ...readCloudflareTriggerConfig(staticConfigPath, configPath), + ...(existingWorker ? { preserve: true } : {}), + }, + { source: workersBuildsVersionSource(options.workersBuilds) }, + ) : ''; const cfOutput = usesCf ? await prepareCfStaticBuildOutput({ @@ -650,6 +696,9 @@ export async function runCloudflareStaticDeploy( }), } : {}), + ...(buildsWorker.placeholderVersionId + ? { adoptPlaceholderVersionId: buildsWorker.placeholderVersionId } + : {}), }, ).finally(() => cfOutput?.dispose()); if (!execution.ok) { @@ -676,6 +725,17 @@ export async function runCloudflareStaticDeploy( execution, cliLog, }); + // Builds and other Wrangler-aware CI read the result from the trusted output file. + writeDeployOutputEntry( + options.deployOutputFile, + { + workerName, + workerTag: buildsWorker.workerTag, + 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-token.ts b/packages/void/src/cli/deploy-cloudflare-token.ts new file mode 100644 index 000000000..f058c54c3 --- /dev/null +++ b/packages/void/src/cli/deploy-cloudflare-token.ts @@ -0,0 +1,193 @@ +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. + * 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 { + 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 > 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'); + } + 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-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 83b40f00c..c40bb7657 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; @@ -216,6 +217,7 @@ export async function runCloudflareDeploy( const migration = await prepareCloudflareWorkerMigrations({ ...deployment, skipMigrations: options.skipMigrations, + workersBuilds: options.workersBuilds, onD1Restore: (command) => { d1RestoreCommand = command; }, @@ -228,6 +230,8 @@ export async function runCloudflareDeploy( detectedFramework, initialCloudflareCandidate, migration, + deployOutputFile: options.deployOutputFile, + workersBuilds: options.workersBuilds, }); } catch (error) { if (error !== stop) { diff --git a/packages/void/src/cli/deploy-resources.ts b/packages/void/src/cli/deploy-resources.ts index 042649e70..63abf9e4a 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 0ceb894ac..2fffa6e7b 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/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index 4bb5ad77e..a30bf97cd 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 }; @@ -71,6 +72,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; @@ -195,6 +206,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 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/deploy.ts b/packages/void/src/cli/deploy.ts index 338f4ae60..970f5bf79 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/email-cloudflare.ts b/packages/void/src/cli/email-cloudflare.ts index b817cf418..b39e693e3 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/platform-installer-workers.ts b/packages/void/src/cli/platform-installer-workers.ts index e5d637af1..b13fbf88c 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/src/cli/workers-builds.ts b/packages/void/src/cli/workers-builds.ts new file mode 100644 index 000000000..fc956757a --- /dev/null +++ b/packages/void/src/cli/workers-builds.ts @@ -0,0 +1,484 @@ +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` (`CLOUDFLARE_CI_OVERRIDE_WORKER_NAME` for the `cf` CLI). + */ +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; + /** + * 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; +}>; + +/** 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') ?? + 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'), + }; +} + +/** 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 with this app's folder as its root directory.`, + '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'); +} + +/** 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'; + +/** + * 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 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. 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; + 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 => { + let response: Response; + try { + response = await (input.fetchImpl ?? fetch)(url, { + headers: { Authorization: `Bearer ${input.token}` }, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + } 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<{ + deployments?: Array<{ + created_on?: unknown; + versions?: Array<{ version_id?: unknown; percentage?: unknown }>; + }>; + }>(`${script}/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' || + Number(traffic[0].percentage) !== 100 + ) { + 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; + annotations?: Record; + resources?: { + bindings?: unknown; + script?: { handlers?: unknown; named_handlers?: unknown; 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 || + !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; + } + + const domains = await read>( + `${account}/domains?service=${encodeURIComponent(input.workerName)}`, + ); + if (!Array.isArray(domains) || domains.length !== 0) { + return null; + } + 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 { + 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 + * (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; + workerName: string; + accountId: string; + apiBaseUrl: string; + token: string | undefined; + fetchImpl?: typeof fetch; +}): Promise<{ workerTag: string | null; placeholderVersionId: string | null } | { error: string }> { + const matchTag = input.builds?.matchTag; + if (!matchTag) { + return { workerTag: null, placeholderVersionId: null }; + } + if (!input.token) { + return { + 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) => ({ + 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.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}.`); + } + 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'), + }; + } + 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; + } +} + +/** + * 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; + } + 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, + }); + } 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; + } + 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, +): { 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`. + * + * 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, + 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 8b8d90ea3..2633d7d1a 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 2a0b3ae8b..aaf6346b0 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -2797,6 +2797,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; @@ -5132,6 +5154,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' }), @@ -5155,6 +5221,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) @@ -6181,7 +6248,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' }), @@ -6242,6 +6309,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', () => { @@ -6313,6 +6404,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/); @@ -14015,3 +14113,528 @@ describe('runCloudflareDeploy — previews', () => { expect(wranglerArgs).toEqual([]); }); }); + +describe('Workers Builds', () => { + const BUILDS_SHA = '0123456789abcdef0123456789abcdef01234567'; + + 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/scripts') || href.includes('/workers/domains')) { + return Response.json({ success: false }, { status: 404 }); + } + 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 { + 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('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('Workers Builds supplied a Worker tag but no API token'); + expect(errors).toContain('Settings > Build > API token'); + 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' }, + { 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({ + '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('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' }); + }); + + 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( + '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: { handlers: ['fetch'], last_deployed_from: 'dash_template' }, + }, + } + : href === `${account}/domains?service=myapp` + ? domains() + : href === `${account}/services/myapp/environments/production/routes` + ? [] + : undefined; + return result === undefined + ? servicesFetch(url, init) + : 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 = []; + 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_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 () => { + 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'); + 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: BUILDS_TAG, + 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', + worker_tag: BUILDS_TAG, + version_id: '22222222-2222-4222-8222-222222222222', + }); + } finally { + rmSync(outputDir, { recursive: true, force: true }); + } + }); + + 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' }); + 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('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); + const { deps, exitCalls } = harness(); + + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + + expect(exitCalls).toEqual([]); + }); +}); diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index e2b74d763..b35b94a1f 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); @@ -608,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/deploy-cloudflare-token.test.ts b/packages/void/test/unit/deploy-cloudflare-token.test.ts new file mode 100644 index 000000000..375130ce6 --- /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 > Build > 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'); + }); +}); diff --git a/packages/void/test/unit/email-cloudflare.test.ts b/packages/void/test/unit/email-cloudflare.test.ts index 5073ac76f..6cae58d25 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/platform-worker-reuse.test.ts b/packages/void/test/unit/platform-worker-reuse.test.ts index 5a4646c98..0f76fdf6e 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: { 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 000000000..fcf1fa503 --- /dev/null +++ b/packages/void/test/unit/workers-builds.test.ts @@ -0,0 +1,624 @@ +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, + confirmWorkersBuildsWorker, + readWorkersBuildsContext, + readWorkersBuildsPlaceholderVersion, + reconfirmWorkersBuildsPlaceholder, + 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', + WRANGLER_CI_MATCH_TAG: 'tag-1', + 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', + matchTag: 'tag-1', + accountId: 'account-1', + }); + }); + + 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', + 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', () => { + 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( + '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.'); + }); + + 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('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.clone(); + }); + 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', 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' } }), + ); + }); + + it('skips untagged builds and stops a tagged build when its token is missing', 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, placeholderVersionId: null }); + await expect( + confirmWorkersBuildsWorker({ + ...base, + builds: readWorkersBuildsContext({ WORKERS_CI: '1' }), + token: 't', + }), + ).resolves.toEqual({ workerTag: null, placeholderVersionId: null }); + await expect( + confirmWorkersBuildsWorker({ ...base, builds, token: undefined }), + ).resolves.toMatchObject({ error: expect.stringContaining('Settings > Build > API token') }); + 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('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: 500 }), + 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('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; + routes: 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: { handlers: ['fetch'], named_handlers: [], last_deployed_from: 'dash_template' }, + }, + }, + domains: [], + routes: [], + }; + } + + 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}/services/my-app/environments/production/routes` + ? fixture.routes + : 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: { 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: { + handlers: ['fetch'], + named_handlers: [{ name: 'Counter', handlers: ['fetch'] }], + last_deployed_from: 'dash_template', + }, + }; + }, + (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.routes = [{ pattern: 'example.com/*' }]; + }, + (fixture) => { + fixture.routes = undefined; + }, + ]; + for (const change of variants) { + const fixture = placeholder(); + change(fixture); + await expect(read(respond(fixture))).resolves.toBeNull(); + } + }); + + 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 = { + 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('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 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); + 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(); + 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{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_\d{3}-[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, workerTag: 'tag-1' }, + () => {}, + ); + 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', worker_tag: 'tag-1', 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(); + }); +});