From 7fbc0351f697fd77f8fab0b8114be758b22226e4 Mon Sep 17 00:00:00 2001 From: Dave Jong Date: Tue, 17 Nov 2026 22:02:27 +0100 Subject: [PATCH] Share the hosted deployment metadata path across build and runtime --- README.md | 15 +++++++++------ src/cli.ts | 15 +++++++++++---- src/deployment-metadata.ts | 24 ++++++++++++++++++++++++ src/prepare-deploy.ts | 25 +++++++++++++------------ src/register.ts | 26 +++----------------------- tests/protect/hosted-deploy.test.ts | 12 +++++++++++- 6 files changed, 71 insertions(+), 46 deletions(-) create mode 100644 src/deployment-metadata.ts diff --git a/README.md b/README.md index 8c58acb..ccc5d80 100644 --- a/README.md +++ b/README.md @@ -572,16 +572,19 @@ apps, or app entries that load Fastify before the hook, use the framework's plugin integration. Activate either the preload adapter or the in-app adapter once per app. -To bind the guard to the map for a deployment, run this from the app's source -directory with the site UUID and API key set. Set `PATCHSTACK_ENVIRONMENT` to -`production` or `sandbox` for the deployment tier. Use an existing, separate -artifact directory per deployment and keep the JSON alongside that build: +Set the site UUID, server API key, and `PATCHSTACK_ENVIRONMENT` in the host's +deployment configuration. Give the build step and the app process the same +`PATCHSTACK_DEPLOYMENT_FILE` path in that release's artifact directory. Run +the following once per deployment from the app's source directory after +installing its dependencies: ```sh -patchstack-connect prepare-deploy --out ./patchstack-deployment.json +patchstack-connect prepare-deploy ``` -Set `PATCHSTACK_DEPLOYMENT_FILE` to that JSON file in the running server. The +The command uses the configured artifact path. An explicit `--out ` +overrides it. Each release should have its own artifact directory so a +replacement or rollback can start with that release's metadata. The command requires a lockfile and reports the dependency inventory and structural input map. It writes only the selected output file. It exits nonzero on a failed upload and marks the selected output incomplete until both uploads diff --git a/src/cli.ts b/src/cli.ts index 79a2da1..06be724 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -187,9 +187,9 @@ Usage: file; a pre-bundle --upload also stamps the existing guard rules file; --follow-symlinks leaves the project dir). Uses the app's own TypeScript - patchstack-connect prepare-deploy --out Report dependencies and upload the input map for - a host-managed site. Write its deployment metadata - for the Node preload. Requires site credentials + patchstack-connect prepare-deploy [--out ] Report dependencies and upload the input map for + a host-managed site. Write PATCHSTACK_DEPLOYMENT_FILE + (or --out). Requires site credentials patchstack-connect init Optional: pre-seed .patchstackrc.json with an existing site UUID patchstack-connect status [options] Show current configuration and whether the @@ -2377,7 +2377,14 @@ async function main(): Promise { } setRunCommand(args.command); - if (args.command === 'prepare-deploy') return prepareDeploy(getStringFlag(args.flags, 'out')); + if (args.command === 'prepare-deploy') { + const out = getStringFlag(args.flags, 'out'); + if (args.flags.has('out') && !out?.trim()) { + console.error('--out requires a deployment metadata path.'); + return 1; + } + return prepareDeploy(out); + } if (!KNOWN_COMMANDS.has(args.command)) return runCommand(args); let code = 1; try { diff --git a/src/deployment-metadata.ts b/src/deployment-metadata.ts new file mode 100644 index 0000000..68c3a5f --- /dev/null +++ b/src/deployment-metadata.ts @@ -0,0 +1,24 @@ +import { readFileSync } from 'node:fs'; + +import { canonicalBuildId } from './build-id.js'; + +export interface HostedDeployment { + siteUuid: string; + buildId: string; + manifestChecksum: string; +} + +export function readHostedDeployment(file: string, siteUuid: string): HostedDeployment { + let data: Partial | null; + try { + data = JSON.parse(readFileSync(file, 'utf8')); + } catch { + throw new Error('Patchstack could not read PATCHSTACK_DEPLOYMENT_FILE.'); + } + const buildId = canonicalBuildId(data?.buildId); + const checksum = data?.manifestChecksum; + if (data?.siteUuid !== siteUuid || buildId === null || typeof checksum !== 'string' || !/^[0-9a-f]{12}$/.test(checksum)) { + throw new Error('PATCHSTACK_DEPLOYMENT_FILE must contain a completed build for PATCHSTACK_SITE_UUID.'); + } + return { siteUuid, buildId, manifestChecksum: checksum }; +} diff --git a/src/prepare-deploy.ts b/src/prepare-deploy.ts index 59c0b25..b01bf56 100644 --- a/src/prepare-deploy.ts +++ b/src/prepare-deploy.ts @@ -3,31 +3,32 @@ import { resolve } from 'node:path'; import { computeManifestChecksum } from './checksum.js'; import { postManifest } from './client.js'; import { resolveConfig } from './config.js'; +import type { HostedDeployment } from './deployment-metadata.js'; import { isCanonicalUuid, isCredential } from './endpoint-policy.js'; import { runMapDetailed } from './map-command.js'; import { buildWirePayload } from './normalize.js'; import { atomicWriteFileSync } from './safe-file.js'; import { scanLockfile } from './parsers/index.js'; -export interface HostedDeployment { - siteUuid: string; - buildId: string; - manifestChecksum: string; -} - export async function prepareDeploy(out: string | undefined): Promise { + const output = out ?? process.env.PATCHSTACK_DEPLOYMENT_FILE; + if (!output?.trim()) { + console.error('prepare-deploy requires PATCHSTACK_DEPLOYMENT_FILE or --out.'); + return 1; + } + const cwd = process.cwd(); + const file = resolve(cwd, output); + // Reusing a path for a failed preparation must not leave the previous build stamped there. + atomicWriteFileSync(file, 'null\n', { encoding: 'utf8' }); + const envSiteUuid = process.env.PATCHSTACK_SITE_UUID; const apiKey = process.env.PATCHSTACK_API_KEY; - if (!out?.trim() || !isCanonicalUuid(envSiteUuid) || !isCredential(apiKey)) { - console.error('prepare-deploy requires --out, PATCHSTACK_SITE_UUID and PATCHSTACK_API_KEY.'); + if (!isCanonicalUuid(envSiteUuid) || !isCredential(apiKey)) { + console.error('prepare-deploy requires PATCHSTACK_SITE_UUID and PATCHSTACK_API_KEY.'); return 1; } const siteUuid = envSiteUuid.toLowerCase(); - const cwd = process.cwd(); - const file = resolve(cwd, out); - // A failed rerun cannot leave a successful stamp for a different build at the selected path. - atomicWriteFileSync(file, 'null\n', { encoding: 'utf8' }); const config = { ...(await resolveConfig({ cwd, cliSiteUuid: siteUuid, detectSiteIdentity: true })), pulseAuth: apiKey, diff --git a/src/register.ts b/src/register.ts index 8a126a6..970237c 100644 --- a/src/register.ts +++ b/src/register.ts @@ -1,8 +1,6 @@ -import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { createProtection, type Protection } from '@patchstack/connect/protect'; -import { canonicalBuildId } from './build-id.js'; -import type { HostedDeployment } from './prepare-deploy.js'; +import { readHostedDeployment } from './deployment-metadata.js'; import { isCanonicalUuid, isCredential, safeRemoteUrl } from './endpoint-policy.js'; const siteUuid = process.env.PATCHSTACK_SITE_UUID; @@ -20,27 +18,9 @@ if (configuredRulesUrl !== undefined && (!pulseRulesUrl || /[?#]/.test(pulseRule throw new Error('PATCHSTACK_PULSE_RULES_URL must be an HTTPS or loopback HTTP base URL without a query or fragment.'); } -function deploymentForSite(site: string): HostedDeployment | undefined { - const file = process.env.PATCHSTACK_DEPLOYMENT_FILE; - if (file === undefined) return undefined; - let deployment: Partial | null; - try { - deployment = JSON.parse(readFileSync(file, 'utf8')); - } catch { - throw new Error('Patchstack could not read PATCHSTACK_DEPLOYMENT_FILE.'); - } - const buildId = canonicalBuildId(deployment?.buildId); - const manifestChecksum = deployment?.manifestChecksum; - if ( - deployment?.siteUuid !== site || buildId === null - || typeof manifestChecksum !== 'string' || !/^[0-9a-f]{12}$/.test(manifestChecksum) - ) { - throw new Error('PATCHSTACK_DEPLOYMENT_FILE must contain a completed build for PATCHSTACK_SITE_UUID.'); - } - return { siteUuid: site, buildId, manifestChecksum }; -} +const deploymentFile = process.env.PATCHSTACK_DEPLOYMENT_FILE; +const deployment = deploymentFile === undefined ? undefined : readHostedDeployment(deploymentFile, siteUuid.toLowerCase()); -const deployment = deploymentForSite(siteUuid.toLowerCase()); // The configured service has its own transport so screening application egress cannot freeze rule updates. const fetchAtStartup = globalThis.fetch.bind(globalThis); const serviceFetch: typeof fetch = (input, init) => fetchAtStartup(input, { ...init, redirect: 'error' }); diff --git a/tests/protect/hosted-deploy.test.ts b/tests/protect/hosted-deploy.test.ts index 0062bd2..b1b83ea 100644 --- a/tests/protect/hosted-deploy.test.ts +++ b/tests/protect/hosted-deploy.test.ts @@ -113,7 +113,7 @@ it.skipIf(!existsSync(join(root, 'dist/register.js')))('reports, deploys and rol const deploy = async (cwd: string, site: number) => { const env = options(cwd, site); // The explicit deployment path must also work from a host's npm prebuild hook. - await run(process.execPath, [cli, 'prepare-deploy', '--out', artifact], { + await run(process.execPath, [cli, 'prepare-deploy'], { ...env, env: { ...env.env, npm_lifecycle_event: 'prebuild' }, }); const data = readFileSync(join(cwd, artifact), 'utf8'); @@ -171,6 +171,16 @@ it.skipIf(!existsSync(join(root, 'dist/register.js')))('reports, deploys and rol expect(await start(next, 0)).toMatchObject({ results: [403, 200, 200], status: { matched: true, buildId: updated.buildId } }); expect(await start(a, 0)).toMatchObject({ results: [200, 200, 200], status: { matched: false, buildId: first.buildId } }); + const buildOptions = options(a, 0); + await run(process.execPath, [cli, 'prepare-deploy', '--out', 'other.json'], buildOptions); + expect(JSON.parse(readFileSync(join(a, 'other.json'), 'utf8'))).toEqual(first); + await expect(run(process.execPath, [cli, 'prepare-deploy', '--out'], buildOptions)).rejects.toThrow('--out requires'); + expect(JSON.parse(readFileSync(join(a, artifact), 'utf8'))).toEqual(first); + await expect(run(process.execPath, [cli, 'prepare-deploy'], { + ...buildOptions, env: { ...buildOptions.env, PATCHSTACK_API_KEY: undefined }, + })).rejects.toThrow('requires PATCHSTACK_SITE_UUID and PATCHSTACK_API_KEY'); + expect(readFileSync(join(a, artifact), 'utf8')).toBe('null\n'); + rejectUpload = true; await expect(deploy(next, 0)).rejects.toThrow('no deployment metadata was produced'); await expect(start(next, 0)).rejects.toThrow('must contain a completed build for PATCHSTACK_SITE_UUID');