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
2 changes: 1 addition & 1 deletion AGENT-INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This versioned reference ships inside `@patchstack/connect` and documents each s
- **Source and releases:** MIT-licensed, source at https://github.com/patchstack/connect. Each version is published to npm from that repository's GitHub Actions workflow with an npm provenance attestation.
- **How to check it yourself:** `npm view @patchstack/connect` shows the live registry metadata, including the repository and the attestation. After installing, `npm audit signatures` verifies the registry signatures and provenance attestations of the installed packages, this one included.
- **What it does:** it sends the project's package names and versions to Patchstack for vulnerability matching, adds the Patchstack Connector widget to the site when asked (`setup --widget`, or `widget`), installs a runtime exploit guard (`protect`) in the server's request path, and adds scan steps to the install and build scripts. `setup` and the `prebuild` hook also upload a structural map of the server (routes, input names, the packages behind each sink, file:line) so protection rules can target the app's own parameters — never source text or environment values. Run on its own, `map` sends nothing unless you pass `--upload`. The [Command reference](#command-reference) lists every command, what it reads and writes, and what it sends.
- **Host-managed Node applications:** The optional `@patchstack/connect/register` preload starts the existing live guard for a site configured by the host. It can enable outbound screening. The host can mount its Express adapter for request and response screening. The `@patchstack/connect/register/fastify` pilot attaches the Fastify 5.12.1 adapter at startup without editing the app. The optional `prepare-deploy` command uploads the dependency manifest and structural input map for an existing site and writes a credential-free deployment metadata file for the preload. See the [host-managed Node setup](README.md#host-managed-node-applications).
- **Host-managed Node applications:** The optional `@patchstack/connect/register` preload starts the existing live guard for a site configured by the host. It can enable outbound screening. The host can mount its Express adapter for request and response screening. The `@patchstack/connect/register/fastify` pilot attaches the Fastify 5.12.1 adapter at startup without editing the app. The optional `prepare-deploy` command uploads the dependency manifest and structural input map for an existing site and writes a credential-free deployment metadata file for the preload. `verify-deploy` reads that file and waits for a signed readiness verdict at an explicitly configured running app URL. See the [host-managed Node setup](README.md#host-managed-node-applications).
- **How setup ends:** run outside a terminal, as you run it, `setup` ends with `──── Summary ────` and a short message written for the person: what Patchstack found, the link to connect the site, what is left to do and the next step. **That summary is your final message.** Show it exactly as written, with every section. It ends by telling the person to say "done" once they have done the one thing it asks — usually connecting their account. When they say "done", run `npx @patchstack/connect next`, which checks where the project stands and says the next thing to do; show what it prints the same way. Do not add a list of the files `setup` changed: the setup output lists them, so answer from it if the person asks. Do not reword it, drop a section, or add your own: no recap, no account of the commands you ran. Add at most one line, after it, for something you did beyond `setup`. If the summary did not reach you (long output can be cut short), run `npx @patchstack/connect summary`: it prints the same summary again, from `.patchstack/summary.md`, where `setup` saves it. "The message you end on" below has the details, and "Commands for later" lists what to run when the person asks for more (`vulns` shows the vulnerabilities).

## Choose the project path first
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,28 @@ with the build you activate. For a custom Patchstack service, configure
`PATCHSTACK_ENDPOINT` for the build and the corresponding
`PATCHSTACK_PULSE_RULES_URL` for the server.

### Gate traffic on signed readiness

With the candidate process running, set `PATCHSTACK_READINESS_URL` to a route
served by that candidate and run:

```sh
patchstack-connect verify-deploy
```

The verifier reads the same deployment file and site credentials as the
preload. It polls the selected URL with signed OPTIONS requests and checks the
site, map identity, manifest checksum, and rules service's readiness verdict.
Zero applicable rules is a valid ready state. The verifier exits nonzero if the
candidate cannot prove readiness within 60 seconds. Use `--url` to select a
candidate explicitly, `--timeout <seconds>` to change the wait, or
`--require-block` when the candidate should already run in blocking mode.

Point the verifier at the candidate before sending it production traffic. A
shared live URL could reach a different replica. Check each candidate the host
will admit. The verifier checks the chosen route and the guard's loaded
metadata. Use a separate enforcement test to prove specific rule behavior.

## Programmatic API

```ts
Expand Down
5 changes: 4 additions & 1 deletion field-test/hosted-startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ PS_FASTIFY_LIVE=1 npm run test:frameworks -- fastify-startup-cjs "$tarball"
This uploads the fixture's package inventory and input map, starts Fastify in
dry-run mode, and checks a signed activation response over loopback HTTP. It
compares the uploaded build ID with a different local ID, and checks the
service's verdict in both cases. Use a sandbox site reserved for this fixture
service's verdict in both cases. The fixture uses `prepare-deploy` with the
runtime's configured artifact path, and runs `verify-deploy` before sending
ordinary fixture traffic. Readiness must pass on the matching candidate and
refuse the different deployment. Use a sandbox site reserved for this fixture
because each run uploads an app map. Rule delivery and a matching build do not
establish that this fixture has any generated rules to enforce.

Expand Down
87 changes: 73 additions & 14 deletions scripts/framework-consumers.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import { execFile, spawn, spawnSync } from 'node:child_process';
import { once } from 'node:events';
import { createServer as createHttpServer } from 'node:http';
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { ACTIVATION_HEADER, activationChallenge, verifyActivationResponse } from '../src/protect/activation.js';

const output = `({ label: body.label, sample: 'fixture-private' })`;
Expand Down Expand Up @@ -221,8 +222,18 @@ function run(command, args, childEnv = env) {
const child = spawnSync(command, args, { cwd, env: childEnv, encoding: 'utf8', timeout: 180_000 });
assert.equal(child.status, 0, [child.error?.message, child.stdout, child.stderr].join('\n').replaceAll(cwd, '<fixture>'));
}
const packageDir = 'node_modules/@patchstack/connect';
const cli = join(packageDir, 'dist/cli.js');
const deployment = 'host/deployment.json';
const exec = promisify(execFile);
const fixtureSite = '11111111-1111-4111-8111-111111111111';
const fixtureCredentials = { PATCHSTACK_SITE_UUID: fixtureSite, PATCHSTACK_API_KEY: 'synthetic-key-1' };
let localRulesUrl;
let revalidatedFixtureRules = false;

function runHostedCli(args, childEnv) {
return exec(process.execPath, [cli, ...args], { cwd, env: childEnv, timeout: 45_000 });
}

async function check(protectedApp, liveBuild) {
const listener = createServer().listen(0, '127.0.0.1');
Expand All @@ -245,9 +256,9 @@ async function check(protectedApp, liveBuild) {
});
} else if (protectedApp && localRulesUrl) {
Object.assign(processEnv, {
PATCHSTACK_SITE_UUID: fixtureSite,
PATCHSTACK_API_KEY: 'synthetic-key-1',
...fixtureCredentials,
PATCHSTACK_PULSE_RULES_URL: localRulesUrl,
PATCHSTACK_DEPLOYMENT_FILE: deployment,
PATCHSTACK_MODE: 'block',
});
}
Expand All @@ -262,6 +273,23 @@ async function check(protectedApp, liveBuild) {
});
let scopedCheckCompleted = false;
try {
if (protectedApp && fixture.preload) {
const expected = {
...processEnv,
PATCHSTACK_DEPLOYMENT_FILE: deployment,
PATCHSTACK_READINESS_URL: processEnv.ORIGIN + '/fixture',
};
if (liveBuild?.matched === false) {
await assert.rejects(runHostedCli(['verify-deploy', '--timeout', '2'], expected), /different deployment metadata/);
console.log('Readiness refused a different deployment.');
} else {
const args = ['verify-deploy', '--timeout', '25'];
if (processEnv.PATCHSTACK_MODE === 'block') args.push('--require-block');
const { stdout } = await runHostedCli(args, expected);
assert.match(stdout, /Deployment ready at the checked URL/);
console.log(stdout.trim());
}
}
let normal;
for (let attempt = 0; attempt < (liveBuild ? 350 : 200) && app.exitCode === null; attempt++) {
try { normal = await post('ordinary'); break; } catch { await new Promise(done => setTimeout(done, 100)); }
Expand All @@ -287,7 +315,7 @@ async function check(protectedApp, liveBuild) {
assert.equal(status.buildId, buildId);
assert.equal(status.matched, liveBuild.matched);
assert.equal(status.source.ok, true);
assert.equal(status.source.origin, 'api');
assert.ok(['api', 'cache'].includes(status.source.origin));
console.log(reported);
if (scopedRule) {
assert.equal(status.mode, 'block');
Expand Down Expand Up @@ -350,14 +378,12 @@ try {
run('npm', ['install', '--no-audit', '--no-fund', '--ignore-scripts']);
if (fixture.build) run(process.execPath, fixture.build);
await check(false);
const packageDir = 'node_modules/@patchstack/connect';
if (fixture.preload) {
if (live) {
mkdirSync(join(cwd, 'host'), { recursive: true });
copyFileSync(fileURLToPath(new URL('./fastify-startup-live.mjs', import.meta.url)), join(cwd, 'host/live.mjs'));
}
} else {
const cli = join(packageDir, 'dist/cli.js');
run(process.execPath, [cli, 'protect']);
run(process.execPath, [cli, 'protect', '--check']);
readFileSync(join(cwd, fixture.rules));
Expand All @@ -370,28 +396,60 @@ try {
rule_v2: [{ parameter: 'response.header.x-fixture', match: { type: 'regex', value: '/fixture-stream-private/' } }] },
], whitelists: [], whitelist_keys: {} });
if (fixture.preload && !live) {
mockRules = createHttpServer((incoming, reply) => {
incoming.resume();
if (incoming.method === 'POST' && incoming.url === '/monitor/pulse/token') {
let reportedBuild;
let lookups = 0;
mockRules = createHttpServer(async (incoming, reply) => {
const path = incoming.url;
if (incoming.method === 'POST' && path === '/monitor/pulse/token') {
incoming.resume();
reply.writeHead(200, { 'content-type': 'application/json' }).end('{"access_token":"synthetic-token"}');
} else if (incoming.method === 'GET' && incoming.url === `/monitor/pulse/rules/${fixtureSite}`
&& incoming.headers.authorization === 'Bearer synthetic-token') {
reply.writeHead(200, { 'content-type': 'application/json' }).end(fixtureBundle);
return;
}
if (incoming.headers.authorization !== 'Bearer synthetic-token') {
incoming.resume();
reply.writeHead(401).end();
return;
}
if (incoming.method === 'POST' && path === `/monitor/pulse/manifest/${fixtureSite}`) {
incoming.resume();
reply.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ uuid: fixtureSite, stored: true }));
} else if (incoming.method === 'POST' && path === `/monitor/pulse/input-map/${fixtureSite}`) {
let map = '';
for await (const chunk of incoming.setEncoding('utf8')) map += chunk;
reportedBuild = JSON.parse(map).build_id;
reply.writeHead(200, { 'content-type': 'application/json' }).end('{"result":"stored","revision":1}');
} else if (incoming.method === 'GET' && path === `/monitor/pulse/rules/${fixtureSite}`
&& reportedBuild && incoming.headers['x-patchstack-build'] === reportedBuild) {
const etag = '"fixture-bundle"';
reply.setHeader('X-Patchstack-Build-Match', 'match');
reply.setHeader('X-Patchstack-Build-ID', reportedBuild);
reply.setHeader('X-Patchstack-Map-Rules', ++lookups === 1 ? 'pending' : 'ready');
reply.setHeader('ETag', etag);
if (incoming.headers['if-none-match'] === etag) {
revalidatedFixtureRules = true;
reply.writeHead(304).end();
} else reply.writeHead(200, { 'content-type': 'application/json' }).end(fixtureBundle);
} else {
incoming.resume();
reply.writeHead(404).end();
}
});
mockRules.listen(0, '127.0.0.1');
await once(mockRules, 'listening');
localRulesUrl = `http://127.0.0.1:${mockRules.address().port}/monitor/pulse`;
mkdirSync(join(cwd, 'host'), { recursive: true });
await runHostedCli(['prepare-deploy'], {
...env, ...fixtureCredentials, PATCHSTACK_ENVIRONMENT: 'sandbox', PATCHSTACK_DEPLOYMENT_FILE: deployment,
PATCHSTACK_ENDPOINT: localRulesUrl + '/manifest',
});
} else if (!fixture.preload) {
put(fixture.rules, fixtureBundle);
}
if (fixture.build) run(process.execPath, fixture.build);
if (live) {
const deployment = 'host/deployment.json';
run(process.execPath, [join(packageDir, 'dist/cli.js'), 'prepare-deploy', '--out', deployment], {
await runHostedCli(['prepare-deploy'], {
...env, PATCHSTACK_SITE_UUID: siteUuid, PATCHSTACK_API_KEY: apiKey, PATCHSTACK_ENVIRONMENT: 'sandbox',
PATCHSTACK_DEPLOYMENT_FILE: deployment,
...(localSaas ? { PATCHSTACK_ENDPOINT: localSaas + '/manifest' } : {}),
});
await check(true, { file: deployment, matched: true, scopedOutcome: 'block' });
Expand All @@ -405,6 +463,7 @@ try {
}
} else {
await check(true);
if (fixture.preload) assert.equal(revalidatedFixtureRules, true, 'Readiness must follow a conditional rules check.');
}
if (fixture.preload) {
for (const [file, source] of Object.entries(fixture.files)) assert.equal(readFileSync(join(cwd, file), 'utf8'), source);
Expand Down
14 changes: 10 additions & 4 deletions src/activation-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import type { Config } from './types.js';

export interface ActivationResult { ok: boolean; message: string; summary?: string }

export async function probeActivation(target: string, secret: string, signal: AbortSignal): Promise<Record<string, unknown> | null> {
const challenge = await activationChallenge(secret, target);
const response = await fetch(target, {
method: 'OPTIONS', redirect: 'error', signal, headers: { [ACTIVATION_HEADER]: challenge },
});
const body = await readBoundedText(response, 16_384);
return response.ok ? verifyActivationResponse(secret, challenge, body, response.headers.get(ACTIVATION_HEADER)) : null;
}

/** Inspect only an explicitly selected running URL. Never discover ports, start, or restart an app. */
export async function checkActivation(url: string, config: Config, cwd: string, expectedBuildId?: string | null): Promise<ActivationResult> {
const target = safeRemoteUrl(url);
Expand All @@ -23,10 +32,7 @@ export async function checkActivation(url: string, config: Config, cwd: string,
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const work = async (): Promise<ActivationResult> => {
const challenge = await activationChallenge(secret, target);
const response = await fetch(target, {method:'OPTIONS',redirect:'error',signal:controller.signal,headers:{[ACTIVATION_HEADER]:challenge}});
const body = await readBoundedText(response,16_384);
const status = response.ok ? await verifyActivationResponse(secret,challenge,body,response.headers.get(ACTIVATION_HEADER)) : null;
const status = await probeActivation(target, secret, controller.signal);
if (!status || status.siteUuid !== config.siteUuid) return {ok:false,message:'The selected URL did not prove activation for this site. Check the server credential, guard integration and deployed package version.'};
if (!expectedBuildId || status.buildId !== expectedBuildId) return {ok:false,message:'The guard answered, but its loaded map is absent or different. Let the framework reload, or restart/rebuild/deploy, then check again.'};
const readiness = ['ready','pending'].includes(String(status.mapRules)) ? status.mapRules : 'unknown';
Expand Down
22 changes: 21 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ import { runDevelopment } from './dev-command.js';
import { checkActivation } from './activation-check.js';
import { syncSetupProtection } from './setup-sync.js';
import { prepareDeploy } from './prepare-deploy.js';
import { verifyDeploy } from './verify-deploy.js';
import { isInstallOrBuildHook, isPreBundleBuildHook, undeliveredReportLines } from './build-hook.js';
import { applyBuildStamp, applyManifestChecksum } from './build-stamp.js';
import { detectStack, type StackDescriptor } from './stack.js';
Expand Down Expand Up @@ -190,6 +191,10 @@ Usage:
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 verify-deploy [--url <url>] Wait for signed readiness at PATCHSTACK_READINESS_URL
(or --url), using the deployment metadata.
--timeout <seconds> defaults to 60. --require-block
also requires blocking mode
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 @@ -371,7 +376,7 @@ Examples:
npx @patchstack/connect demo-guide node-serialize
`;

const VALUE_FLAGS = new Set(['site-uuid', 'endpoint', 'dir', 'url', 'out', 'claim-token', 'host', 'runtime-url']);
const VALUE_FLAGS = new Set(['site-uuid', 'endpoint', 'dir', 'url', 'out', 'timeout', 'claim-token', 'host', 'runtime-url']);

/** Set from `--verbose`. The default output is a plain status report; this adds the technical lines. */
let verbose = false;
Expand Down Expand Up @@ -2385,6 +2390,21 @@ async function main(): Promise<number> {
}
return prepareDeploy(out);
}
if (args.command === 'verify-deploy') {
const url = getStringFlag(args.flags, 'url');
const rawTimeout = getStringFlag(args.flags, 'timeout');
const seconds = args.flags.has('timeout') ? Number(rawTimeout) : 60;
if ((args.flags.has('url') && !url?.trim()) || !Number.isInteger(seconds) || seconds < 1 || seconds > 300) {
console.error('verify-deploy expects an explicit --url if supplied, and --timeout between 1 and 300 seconds.');
return 1;
}
const requireBlock = args.flags.get('require-block');
if (requireBlock !== undefined && requireBlock !== true) {
console.error('--require-block takes no value.');
return 1;
}
return verifyDeploy(url, seconds, requireBlock === true);
}
if (!KNOWN_COMMANDS.has(args.command)) return runCommand(args);
let code = 1;
try {
Expand Down
2 changes: 2 additions & 0 deletions src/protect/protect.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,8 @@ export interface CreateProtectionOptions {
buildId?: string;
/** Package manifest checksum for the running deployment report. */
manifestChecksum?: string;
/** Recheck build rule readiness more frequently during the first minute after startup. */
startupRulesRetry?: boolean;
/**
* Take responsibility for `rules` you supply yourself, including any `build_scope` they carry.
*
Expand Down
Loading
Loading