Skip to content

Commit 319ebec

Browse files
committed
Chore(CI): Preserve Pages build inputs across Worker deployments
1 parent 5c46f89 commit 319ebec

3 files changed

Lines changed: 98 additions & 1 deletion

File tree

‎scripts/pages-site-release.mjs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,25 @@ async function publicCohort(root = '.') {
135135
return names.sort()
136136
}
137137

138+
// Pages applies Wrangler vars on every Worker deployment, replacing dashboard plaintext
139+
// values. Retain the build inputs in that same source of truth; never copy process.env
140+
// or masked dashboard secret bindings into the configuration.
141+
export function hostedBuildConfig(config, input, { packageManager, nodeVersion = process.versions.node }) {
142+
const metadata = releaseMetadata(input)
143+
assert.match(packageManager ?? '', /^bun@\d+\.\d+\.\d+$/, 'The hosted build requires a pinned Bun version')
144+
assert.match(nodeVersion, /^\d+\.\d+\.\d+$/, 'The actual hosted Node version is required')
145+
assert.equal(config.pages_build_output_dir, 'site/out', 'Pages must publish the verified output directory')
146+
const vars = {
147+
BUN_VERSION: packageManager.slice(4), NODE_VERSION: nodeVersion, SKIP_DEPENDENCY_INSTALL: '1',
148+
MASTER_CSS_PAGES_PROJECT: metadata.project, MASTER_CSS_PAGES_SUBDOMAIN: metadata.subdomain,
149+
MASTER_CSS_IMAGE_TRANSFORMATIONS: 'false', MASTER_LEGACY_DESIGN_CUTOVER: metadata.legacyDesignCutover ? '1' : '0'
150+
}
151+
const result = { ...config, vars: { ...config.vars, ...vars } }
152+
if (config.env?.production) result.env = { ...config.env,
153+
production: { ...config.env.production, vars: { ...config.env.production.vars, ...vars } } }
154+
return result
155+
}
156+
138157
export function registryFromState(state, metadata, names) {
139158
assert.equal(state.schemaVersion, 1)
140159
assert.equal(state.revision, metadata.releaseRevision)
@@ -375,6 +394,17 @@ async function main(command, directory) {
375394
const proof = await verifyOutput('site/out', manifest, metadata)
376395
const pointer = git(['ls-remote', '--heads', remote, `refs/heads/${metadata.deliveryBranch}`])
377396
assert.equal(pointer, `${metadata.revision}\trefs/heads/${metadata.deliveryBranch}`, 'A newer release superseded this Pages build')
397+
// Only after source, registry, complete output inventory and delivery pointer verify.
398+
// This build-local configuration is outside site/out and the immutable CI manifest.
399+
const configPath = 'wrangler.jsonc'
400+
const config = JSON.parse(await readFile(configPath, 'utf8'))
401+
const { packageManager } = JSON.parse(await readFile('package.json', 'utf8'))
402+
const next = hostedBuildConfig(config, metadata, { packageManager })
403+
const temporaryConfig = `${configPath}.verified`
404+
try {
405+
await writeFile(temporaryConfig, jsonBytes(next))
406+
await rename(temporaryConfig, configPath)
407+
} finally { await rm(temporaryConfig, { force: true }) }
378408
console.log(JSON.stringify(proof))
379409
return
380410
}

‎scripts/pages-site-release.test.mjs‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
55
import path from 'node:path'
66
import { fileURLToPath, pathToFileURL } from 'node:url'
77
import { test } from 'node:test'
8-
import { ciMetadata, hostedMetadata, newestTag, planDelivery, registryFromNpm, registryFromState, selectExactTag, selectReleaseTag, verifyPublicRegistry } from './pages-site-release.mjs'
8+
import { ciMetadata, hostedBuildConfig, hostedMetadata, newestTag, planDelivery, registryFromNpm, registryFromState, selectExactTag, selectReleaseTag, verifyPublicRegistry } from './pages-site-release.mjs'
99
import { createManifest, inventoryDigest, jsonBytes, manifestName, manifestUrl, outputInventory, prepareIdentity, sha256 } from './pages-site-manifest.mjs'
1010

1111
const revision = 'a'.repeat(40)
@@ -158,6 +158,49 @@ test('the real hosted shell command fails before installing tools when release i
158158
assert.deepEqual(await readdir(temporary), [], 'The rejected build removes its temporary evidence directory')
159159
})
160160

161+
test('hosted Pages configuration retains build inputs for either channel without copying environment secrets', () => {
162+
const config = { name: 'fixture', compatibility_date: '2026-06-11', pages_build_output_dir: 'site/out',
163+
vars: { PUBLIC_LABEL: 'Keep', JSON_VALUE: { nested: true }, NODE_VERSION: 'stale' },
164+
kv_namespaces: [{ binding: 'CACHE', id: 'existing-kv' }],
165+
env: { production: { vars: { PUBLIC_LABEL: 'Production' }, compatibility_flags: ['nodejs_compat'] },
166+
preview: { vars: { PUBLIC_LABEL: 'Preview' }, kv_namespaces: [{ binding: 'CACHE', id: 'preview-kv' }] } } }
167+
const original = structuredClone(config)
168+
const previous = process.env.OPENAI_API_KEY
169+
process.env.OPENAI_API_KEY = 'must-not-copy-secret'
170+
try {
171+
for (const channel of ['main', 'rc']) for (const cutover of [false, true]) {
172+
const input = channel === 'main' ? { ...metadata, legacyDesignCutover: cutover } : { ...metadata,
173+
channel: 'rc', version: '2.0.0-rc.1', tag: 'v2.0.0-rc.1', deliveryBranch: 'codex/pages-rc',
174+
origin: 'https://rc.css.master.co', project: 'release-candidate', subdomain: 'release-candidate-e8w.pages.dev', legacyDesignCutover: cutover }
175+
const result = hostedBuildConfig(config, input, { packageManager: 'bun@1.4.4' })
176+
for (const vars of [result.vars, result.env.production.vars]) {
177+
assert.equal(vars.NODE_VERSION, process.versions.node)
178+
assert.equal(vars.BUN_VERSION, '1.4.4')
179+
assert.equal(vars.SKIP_DEPENDENCY_INSTALL, '1')
180+
assert.equal(vars.MASTER_CSS_PAGES_PROJECT, input.project)
181+
assert.equal(vars.MASTER_CSS_PAGES_SUBDOMAIN, input.subdomain)
182+
assert.equal(vars.MASTER_CSS_IMAGE_TRANSFORMATIONS, 'false')
183+
assert.equal(vars.MASTER_LEGACY_DESIGN_CUTOVER, cutover ? '1' : '0')
184+
assert.equal(vars.OPENAI_API_KEY, undefined)
185+
}
186+
assert.deepEqual(result.vars.JSON_VALUE, config.vars.JSON_VALUE)
187+
assert.equal(result.env.production.vars.JSON_VALUE, undefined, 'Production must not inherit local-only vars')
188+
assert.equal(result.vars.PUBLIC_LABEL, 'Keep')
189+
assert.equal(result.env.production.vars.PUBLIC_LABEL, 'Production')
190+
assert.deepEqual(result.kv_namespaces, config.kv_namespaces)
191+
assert.deepEqual(result.env.preview, config.env.preview)
192+
assert.deepEqual(result.env.production.compatibility_flags, config.env.production.compatibility_flags)
193+
assert.deepEqual(hostedBuildConfig(result, input, { packageManager: 'bun@1.4.4' }), result, 'Every subsequent deploy retains the same values')
194+
}
195+
} finally { if (previous === undefined) delete process.env.OPENAI_API_KEY; else process.env.OPENAI_API_KEY = previous }
196+
assert.deepEqual(config, original)
197+
const noProductionVars = hostedBuildConfig({ ...config, env: { production: {} } }, metadata, { packageManager: 'bun@1.4.4' })
198+
assert.equal(noProductionVars.env.production.vars.PUBLIC_LABEL, undefined, 'An empty production environment also must not inherit local vars')
199+
assert.throws(() => hostedBuildConfig(config, { ...metadata, project: 'not/a/project' }, { packageManager: 'bun@1.4.4' }))
200+
assert.throws(() => hostedBuildConfig(config, metadata, { packageManager: 'bun@latest' }), /pinned Bun/)
201+
assert.throws(() => hostedBuildConfig(config, metadata, { packageManager: 'bun@1.4.4', nodeVersion: '$(untrusted)' }), /actual hosted Node/)
202+
})
203+
161204
for (const cutover of [false, true]) test(`the real hosted shell exports the exact release and cutover=${cutover}, rejecting altered bytes`, async t => {
162205
const delivery = { ...metadata, legacyDesignCutover: cutover }
163206
const root = await mkdtemp(path.join(tmpdir(), 'master-pages-hosted-'))
@@ -167,6 +210,10 @@ for (const cutover of [false, true]) test(`the real hosted shell exports the exa
167210
await copyFile(new URL(name, import.meta.url), path.join(root, 'scripts', name))
168211
}
169212
await writeFile(path.join(root, 'packages/css/package.json'), JSON.stringify({ name: '@master/css' }))
213+
await writeFile(path.join(root, 'package.json'), JSON.stringify({ packageManager: 'bun@1.4.4' }))
214+
const originalConfig = jsonBytes({ name: 'fixture', pages_build_output_dir: 'site/out', vars: { EXISTING: 'retained' },
215+
kv_namespaces: [{ binding: 'CACHE', id: 'existing-kv' }] })
216+
await writeFile(path.join(root, 'wrangler.jsonc'), originalConfig)
170217
const payload = { 'index.html': '<p>Release fixture</p>', 'assets/a.css': 'a{color:red}' }
171218
if (cutover) Object.assign(payload, { '_worker.js': 'export default {}', '_routes.json': '{"version":1}' })
172219
for (const [name, contents] of Object.entries(payload)) await writeFile(path.join(root, 'verified', name), contents)
@@ -217,12 +264,28 @@ if(process.argv[2]==='install') {
217264
MASTER_LEGACY_DESIGN_CUTOVER: cutover ? '1' : '0', PAGES_FIXTURE_MANIFEST: path.join(root, 'manifest.json') }
218265
const result = execFileSync('bash', [path.join(root, 'scripts/build-site-hosted.sh')], { env, stdio: 'pipe', encoding: 'utf8' })
219266
assert.ok(result.includes(manifest.buildDigest))
267+
const config = JSON.parse(await readFile(path.join(root, 'wrangler.jsonc'), 'utf8'))
268+
assert.equal(config.vars.MASTER_LEGACY_DESIGN_CUTOVER, cutover ? '1' : '0')
269+
assert.equal(config.vars.MASTER_CSS_PAGES_PROJECT, metadata.project)
270+
assert.equal(config.vars.NODE_VERSION, process.versions.node)
271+
assert.equal(config.vars.BUN_VERSION, '1.4.4')
272+
assert.equal(config.vars.EXISTING, 'retained')
273+
assert.deepEqual(config.kv_namespaces, [{ binding: 'CACHE', id: 'existing-kv' }])
274+
assert.deepEqual(await outputInventory(path.join(root, 'site/out')), manifest.files, 'Config generation cannot modify the verified public output')
275+
assert.ok((await readFile(path.join(root, 'manifest.json'))).equals(jsonBytes(manifest)), 'The immutable CI manifest is unchanged')
220276
assert.deepEqual((await readFile(path.join(root, 'trace.txt'), 'utf8')).trim().split('\n'), ['install --frozen-lockfile', 'run build:site'])
277+
await writeFile(path.join(root, 'wrangler.jsonc'), originalConfig)
278+
assert.throws(() => execFileSync('bash', [path.join(root, 'scripts/build-site-hosted.sh')], {
279+
env: { ...env, MASTER_CSS_PAGES_PROJECT: 'wrong-project' }, stdio: 'pipe'
280+
}))
281+
assert.ok((await readFile(path.join(root, 'wrangler.jsonc'))).equals(originalConfig), 'Rejected metadata cannot write configuration')
221282
await writeFile(path.join(root, 'payload.json'), JSON.stringify({ ...payload, 'assets/a.css': 'a{color:blue}' }))
222283
assert.throws(() => execFileSync('bash', [path.join(root, 'scripts/build-site-hosted.sh')], { env, stdio: 'pipe' }), error => {
223284
assert.ok(error.stderr.toString().includes('Cloudflare output differs'))
224285
return true
225286
})
287+
assert.ok((await readFile(path.join(root, 'wrangler.jsonc'))).equals(originalConfig), 'Rejected output cannot write configuration')
288+
assert.equal((await readdir(root)).includes('wrangler.jsonc.verified'), false)
226289
})
227290

228291
async function deliveryFixture(t, scenario) {

‎site/tests/release-cutover-runbook.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,10 @@ This command verifies the retained manifest against its exact public release ass
122122

123123
If a failed site job is rerun, it downloads the npm evidence artifact named by the original completed release job, even when the workflow attempt number changes. If its delivery ref already selects this SHA, no new push or synthetic commit is made. Inspect or retry that exact Pages deployment through the authorized dashboard when appropriate; do not force a ref, move a version tag or republish npm to obtain a site retry. A new publication manifest with different bytes requires reconciliation, never `--clobber`.
124124

125+
Pages reconstructs the site from the same source and lockfile, then `hosted-verify` compares every output file with the immutable CI manifest before deployment. It does not directly upload the CI archive. After that comparison and the delivery-ref check succeed, `hosted-verify` atomically updates the build-local `wrangler.jsonc` with seven controlled plaintext build inputs: the actual Node version, repository-pinned Bun version, `SKIP_DEPENDENCY_INSTALL=1`, and the verified project, subdomain, portable-image and legacy-cutover values. This configuration is outside `site/out`; neither public output nor the CI manifest changes. Existing runtime variables, bindings and other configuration remain intact, and production variables keep Wrangler's non-inheritance semantics. Arbitrary process variables and dashboard secrets are never copied.
126+
127+
This synchronization is required on every Worker deployment: [Wrangler configuration is the Pages source of truth](https://developers.cloudflare.com/pages/functions/wrangler-configuration/), so an empty source `vars` map can replace dashboard plaintext build values. Verify the seven build inputs after delivery, including the actual channel's project and subdomain. Keep four explicit prefixes on each surface's Pages build command: `MASTER_CSS_PAGES_PROJECT`, `MASTER_CSS_PAGES_SUBDOMAIN`, `MASTER_CSS_IMAGE_TRANSFORMATIONS=false` and `MASTER_LEGACY_DESIGN_CUTOVER` aligned with its GitHub variable. Use that surface's real project/subdomain, including RC. Pages can apply source configuration before the hosted shell runs, so dashboard-only identity values are insufficient. A failed metadata, registry, output or delivery-ref check must leave the configuration untouched.
128+
125129
`release-artifacts/site-delivery.json` records the source, actual version, logical channel, delivery ref, project, mode and owning GitHub run/attempt before any asset/ref write. Each external write records its intent and acknowledged, rejected or unknown response outcome; asset/ref verification is recorded separately. A lost response can leave a successful remote write with an `unknown` outcome. A failed CLI status never means that no write occurred or that Cloudflare rolled back. Inspect the retained receipt and authoritative asset/ref state before retrying. Retries with an existing local receipt append an attempt without replacing its history; separate workflow attempts retain separate artifacts. Immutable-host and canonical verification flags become true only after their respective live checks complete. Failure receipts contain fixed phase/error codes, never raw responses, credentials or private dashboard identifiers.
126130

127131
1. Stage the exact verified output with its commit identity. A private preview and the new project's production `pages.dev` bootstrap are distinct deployment environments. Require the real `X-Robots-Tag: noindex` response on either Pages-hosted surface; do not assume a production bootstrap inherits preview defaults. The Git delivery watcher explicitly checks the immutable identity response header. Retain the immutable deployment URL because branch aliases can move. These Pages-host rules do not impose a separate JSON SEO requirement on the canonical domain. [Preview deployment documentation](https://developers.cloudflare.com/pages/configuration/preview-deployments/)

0 commit comments

Comments
 (0)