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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file>`
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
Expand Down
15 changes: 11 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file> 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 <file>] Report dependencies and upload the input map for
a host-managed site. Write PATCHSTACK_DEPLOYMENT_FILE
(or --out). Requires site credentials
patchstack-connect init <site-uuid> Optional: pre-seed .patchstackrc.json
with an existing site UUID
patchstack-connect status [options] Show current configuration and whether the
Expand Down Expand Up @@ -2377,7 +2377,14 @@ async function main(): Promise<number> {
}

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 {
Expand Down
24 changes: 24 additions & 0 deletions src/deployment-metadata.ts
Original file line number Diff line number Diff line change
@@ -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<HostedDeployment> | 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 };
}
25 changes: 13 additions & 12 deletions src/prepare-deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number> {
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,
Expand Down
26 changes: 3 additions & 23 deletions src/register.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<HostedDeployment> | 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' });
Expand Down
12 changes: 11 additions & 1 deletion tests/protect/hosted-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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');
Expand Down
Loading