From 4aab6ccac9767c27d26ed6b8692ca0cf99524275 Mon Sep 17 00:00:00 2001 From: Dave Jong Date: Tue, 17 Nov 2026 20:07:42 +0100 Subject: [PATCH 1/2] Prepare hosted Node deployments with their input map --- AGENT-INSTALL.md | 2 +- README.md | 23 ++++ src/cli.ts | 5 + src/map-command.ts | 2 +- src/prepare-deploy.ts | 58 ++++++++++ src/protect/protect.d.ts | 2 + src/protect/runtime.js | 2 +- src/register.ts | 29 ++++- tests/protect/hosted-deploy.test.ts | 174 ++++++++++++++++++++++++++++ 9 files changed, 293 insertions(+), 4 deletions(-) create mode 100644 src/prepare-deploy.ts create mode 100644 tests/protect/hosted-deploy.test.ts diff --git a/AGENT-INSTALL.md b/AGENT-INSTALL.md index 1a8d8fbb..82c08d1f 100644 --- a/AGENT-INSTALL.md +++ b/AGENT-INSTALL.md @@ -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. Inbound request and response screening require a separately mounted adapter. 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 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). - **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 diff --git a/README.md b/README.md index 461f302a..9f6ac1ee 100644 --- a/README.md +++ b/README.md @@ -557,6 +557,29 @@ the app already needs. The ESM preload and the middleware import use the same guard instance. CommonJS apps can load the same export with `await import()` during their async startup. +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: + +```sh +patchstack-connect prepare-deploy --out ./patchstack-deployment.json +``` + +Set `PATCHSTACK_DEPLOYMENT_FILE` to that JSON file in the running server. 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 +succeed. The preload refuses an incomplete file or one for a different site. +It reports the manifest checksum with live status and presents the map identity +when fetching rules. Patchstack still needs to confirm the map before scoped +rules can block. A rollback should start the older artifact with its original +metadata. If that map is no longer confirmed, its scoped rules only detect. +Serialize deployments for the same site to keep the latest reported map aligned +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. + ## Programmatic API ```ts diff --git a/src/cli.ts b/src/cli.ts index c68de50a..79a2da1f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -124,6 +124,7 @@ import { setupProtection, wireBuildScripts, wireDevelopmentScript } from './setu 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 { isInstallOrBuildHook, isPreBundleBuildHook, undeliveredReportLines } from './build-hook.js'; import { applyBuildStamp, applyManifestChecksum } from './build-stamp.js'; import { detectStack, type StackDescriptor } from './stack.js'; @@ -186,6 +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 init Optional: pre-seed .patchstackrc.json with an existing site UUID patchstack-connect status [options] Show current configuration and whether the @@ -2373,6 +2377,7 @@ async function main(): Promise { } setRunCommand(args.command); + if (args.command === 'prepare-deploy') return prepareDeploy(getStringFlag(args.flags, 'out')); if (!KNOWN_COMMANDS.has(args.command)) return runCommand(args); let code = 1; try { diff --git a/src/map-command.ts b/src/map-command.ts index 861448dd..c6134c03 100644 --- a/src/map-command.ts +++ b/src/map-command.ts @@ -151,7 +151,7 @@ export async function runMapDetailed(flags: Flags, options: MapOptions = {}): Pr // Setup prepares the next startup; a prebuild upload prepares the next bundle. Both write the // identity of THIS map into the imported rules file. A standalone manual map remains unbound. let buildId: string | null = null; - if (options.setup || isPreBundleBuildHook()) { + if (options.setup || (!options.declare && isPreBundleBuildHook())) { let candidate: string | null = null; let identityError: string | null = null; try { diff --git a/src/prepare-deploy.ts b/src/prepare-deploy.ts new file mode 100644 index 00000000..59c0b25b --- /dev/null +++ b/src/prepare-deploy.ts @@ -0,0 +1,58 @@ +import { resolve } from 'node:path'; + +import { computeManifestChecksum } from './checksum.js'; +import { postManifest } from './client.js'; +import { resolveConfig } from './config.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 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.'); + 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, + apiKey, + claimToken: null, + }; + const { payload } = buildWirePayload(await scanLockfile(cwd)); + const manifest = await postManifest(config, payload); + if (!manifest.stored && manifest.reason !== 'duplicate') { + console.error('prepare-deploy: Patchstack did not accept the dependency manifest.'); + return 1; + } + + const map = await runMapDetailed(new Map([['upload', true]]), { config, declare: true }); + if (!map.buildId || (map.upload?.result !== 'stored' && map.upload?.result !== 'unchanged')) { + console.error('prepare-deploy: no deployment metadata was produced for the input map.'); + return 1; + } + + const deployment: HostedDeployment = { + siteUuid, + buildId: map.buildId, + manifestChecksum: computeManifestChecksum(payload.packages), + }; + atomicWriteFileSync(file, JSON.stringify(deployment, null, 2) + '\n', { encoding: 'utf8' }); + console.log('Patchstack deployment metadata is ready.'); + return 0; +} diff --git a/src/protect/protect.d.ts b/src/protect/protect.d.ts index 5e4baaa4..828352b5 100644 --- a/src/protect/protect.d.ts +++ b/src/protect/protect.d.ts @@ -443,6 +443,8 @@ export interface CreateProtectionOptions { * the same effect as passing nothing. */ buildId?: string; + /** Package manifest checksum for the running deployment report. */ + manifestChecksum?: string; /** * Take responsibility for `rules` you supply yourself, including any `build_scope` they carry. * diff --git a/src/protect/runtime.js b/src/protect/runtime.js index fb7d6683..441bfcfd 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -1774,7 +1774,7 @@ export async function createProtection(options = {}) { const noteLive = async (request) => { if (!liveReportDue(request)) return; try { - await liveReporter.note(publicOriginOf(request), options.rules?._patchstack?.manifest_checksum); + await liveReporter.note(publicOriginOf(request), options.manifestChecksum ?? options.rules?._patchstack?.manifest_checksum); } catch { /* never let the live report affect screening */ } }; /** A Node request as the one thing {@link noteLive} reads: its headers, behind a `get`. */ diff --git a/src/register.ts b/src/register.ts index 00f0350c..c48e4d23 100644 --- a/src/register.ts +++ b/src/register.ts @@ -1,5 +1,8 @@ +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 { isCanonicalUuid, isCredential, safeRemoteUrl } from './endpoint-policy.js'; const siteUuid = process.env.PATCHSTACK_SITE_UUID; @@ -16,8 +19,32 @@ if (pulseRulesUrl !== undefined && safeRemoteUrl(pulseRulesUrl) === null) { throw new Error('PATCHSTACK_PULSE_RULES_URL must use HTTPS or a loopback HTTP URL.'); } +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 deployment = deploymentForSite(siteUuid.toLowerCase()); + export const protection: Protection = await createProtection({ - siteUuid, + siteUuid: siteUuid.toLowerCase(), + buildId: deployment?.buildId, + manifestChecksum: deployment?.manifestChecksum, apiKey, pulseAuth: apiKey, pulseRulesUrl, diff --git a/tests/protect/hosted-deploy.test.ts b/tests/protect/hosted-deploy.test.ts new file mode 100644 index 00000000..6d18afd4 --- /dev/null +++ b/tests/protect/hosted-deploy.test.ts @@ -0,0 +1,174 @@ +import { execFile } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { promisify } from 'node:util'; +import { expect, it } from 'vitest'; + +const run = promisify(execFile); +const root = resolve(); +const cli = join(root, 'dist/cli.js'); +const sites = ['11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222']; +const artifact = 'deployment.json'; + +function makeApp(cwd: string, route: string) { + mkdirSync(join(cwd, 'node_modules/@patchstack'), { recursive: true }); + symlinkSync(root, join(cwd, 'node_modules/@patchstack/connect'), 'junction'); + symlinkSync(join(root, 'node_modules/express'), join(cwd, 'node_modules/express'), 'junction'); + writeFileSync(join(cwd, 'package.json'), JSON.stringify({ + name: 'hosted-fixture', type: 'module', dependencies: { express: '5.3.0' }, + })); + writeFileSync(join(cwd, 'package-lock.json'), JSON.stringify({ + name: 'hosted-fixture', version: '1.0.0', lockfileVersion: 3, + packages: { '': { name: 'hosted-fixture' }, 'node_modules/express': { version: '5.3.0' } }, + })); + writeFileSync(join(cwd, 'server.js'), ` + import express from 'express'; + import { expressProtection, protection } from '@patchstack/connect/register'; + + const app = express(); + app.use(express.json()); + app.use(expressProtection); + app.post('${route}', (req, res) => res.json({ label: req.body.label })); + + const server = app.listen(0, '127.0.0.1'); + await new Promise((resolve, reject) => server.once('listening', resolve).once('error', reject)); + try { + const results = []; + for (const label of ['site-1', 'site-2', 'ordinary']) { + const response = await fetch('http://127.0.0.1:' + server.address().port + '${route}', { + method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Forwarded-Host': 'fixture.example' }, + body: JSON.stringify({ label }), + }); + results.push(response.status); + if (response.ok && (await response.json()).label !== label) throw new Error('Unexpected app response'); + } + console.log(JSON.stringify({ results, status: protection.synchronization })); + } finally { + server.close(); + await protection.stop(); + } + `); +} + +it.skipIf(!existsSync(join(root, 'dist/register.js')))('reports, deploys and rolls back isolated hosted apps', async () => { + const dir = mkdtempSync(join(tmpdir(), 'hosted-connect-')); + const requests: { action: string; site: string; body: Record }[] = []; + const maps = new Map(); + let rejectUpload = false; + let rulesUnavailable = false; + const api = createServer(async (req, res) => { + const [, , , action, site] = (req.url ?? '').split('/'); + let input = ''; + for await (const chunk of req) input += chunk; + const body = input ? JSON.parse(input) : {}; + const send = (code: number, data: unknown) => { + res.writeHead(code, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(data)); + }; + if (req.url === '/api/logs/log') return send(200, { result: 'accepted' }); + if (action === 'token' && body.client_secret === 'synthetic-key' && ['1', '2'].includes(body.client_id)) { + return send(200, { access_token: 'fixture-' + body.client_id }); + } + const client = sites.indexOf(site!) + 1; + if (!client || req.headers.authorization !== 'Bearer fixture-' + client) return send(401, {}); + requests.push({ action: action!, site: site!, body }); + if (action === 'manifest') return send(200, { uuid: site, stored: true }); + if (action === 'input-map') { + if (rejectUpload) return send(503, {}); + maps.set(site!, body.build_id); + return send(200, { result: 'stored', revision: 1 }); + } + if (action === 'rules') { + if (rulesUnavailable) return send(503, {}); + const build = maps.get(site!); + if (build && req.headers['x-patchstack-build'] === build) { + res.setHeader('X-Patchstack-Build-Match', 'match'); + res.setHeader('X-Patchstack-Build-ID', build); + res.setHeader('X-Patchstack-Map-Rules', 'ready'); + } + return send(200, { firewall: [{ + id: 'fixture-' + client, build_scope: build, + rule_v2: [{ parameter: 'post.label', match: { type: 'equals', value: 'site-' + client } }], + }], whitelists: [], whitelist_keys: {} }); + } + if (action === 'live' || action === 'detections') return send(200, { result: 'accepted' }); + return send(404, {}); + }); + try { + await new Promise((done, reject) => api.once('error', reject).listen(0, '127.0.0.1', done)); + const base = 'http://127.0.0.1:' + (api.address() as AddressInfo).port + '/monitor/pulse'; + const options = (cwd: string, site: number, nodeOptions = '') => ({ + cwd, timeout: 15_000, + env: { + PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, + NODE_OPTIONS: nodeOptions, + PATCHSTACK_ENDPOINT: base + '/manifest', PATCHSTACK_PULSE_RULES_URL: base, + PATCHSTACK_API_KEY: 'synthetic-key-' + (site + 1), PATCHSTACK_SITE_UUID: sites[site], + PATCHSTACK_ENVIRONMENT: 'production', PATCHSTACK_MODE: 'block', PATCHSTACK_DEPLOYMENT_FILE: artifact, + }, + }); + 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], { + ...env, env: { ...env.env, npm_lifecycle_event: 'prebuild' }, + }); + const data = readFileSync(join(cwd, artifact), 'utf8'); + expect(data).not.toContain('synthetic-key'); + return JSON.parse(data); + }; + const start = async (cwd: string, site: number) => { + const { stdout } = await run(process.execPath, ['server.js'], + options(cwd, site, '--import=@patchstack/connect/register')); + return JSON.parse(stdout.trim().split('\n').at(-1)!); + }; + + const a = join(dir, 'a'); + const b = join(dir, 'b'); + makeApp(a, '/submit'); + makeApp(b, '/submit'); + const [first, second] = await Promise.all([deploy(a, 0), deploy(b, 1)]); + const [liveA, liveB] = await Promise.all([start(a, 0), start(b, 1)]); + expect(liveA).toMatchObject({ results: [403, 200, 200], status: { siteUuid: sites[0], matched: true, buildId: first.buildId } }); + expect(liveB).toMatchObject({ results: [200, 403, 200], status: { siteUuid: sites[1], matched: true, buildId: second.buildId } }); + for (const [index, deployment] of [first, second].entries()) { + const site = sites[index]; + expect(requests).toContainEqual(expect.objectContaining({ action: 'manifest', site, + body: expect.objectContaining({ packages: expect.arrayContaining([{ name: 'express', version: '5.3.0' }]) }) })); + expect(requests).toContainEqual(expect.objectContaining({ action: 'input-map', site, + body: expect.objectContaining({ build_id: deployment.buildId, endpoints: expect.arrayContaining([ + expect.objectContaining({ route: '/submit' }), + ]) }) })); + expect(requests).toContainEqual(expect.objectContaining({ action: 'live', site, + body: expect.objectContaining({ checksum: deployment.manifestChecksum }) })); + expect(requests).toContainEqual(expect.objectContaining({ action: 'detections', site, + body: expect.objectContaining({ detections: expect.arrayContaining([ + expect.objectContaining({ rule_id: 'fixture-' + (index + 1), enforced: true }), + ]) }) })); + } + await expect(start(a, 1)).rejects.toThrow('must contain a completed build for PATCHSTACK_SITE_UUID'); + rulesUnavailable = true; + expect(await start(a, 0)).toMatchObject({ results: [403, 200, 200], status: { source: { origin: 'cache', ok: false } } }); + rulesUnavailable = false; + + const next = join(dir, 'a-next'); + makeApp(next, '/submit-v2'); + const updated = await deploy(next, 0); + expect(updated.buildId).not.toBe(first.buildId); + 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 } }); + + 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'); + } finally { + await new Promise((done) => { + api.close(() => done()); + api.closeAllConnections(); + }); + rmSync(dir, { recursive: true, force: true }); + } +}, 25_000); From 815519c34a5c76b76a3e9f9dc2c2b469bdca2691 Mon Sep 17 00:00:00 2001 From: Dave Jong Date: Tue, 17 Nov 2026 20:10:48 +0100 Subject: [PATCH 2/2] Keep hosted rule refresh separate from application egress --- src/protect/engine/pulse-client.js | 9 ++++++--- src/protect/protect.d.ts | 4 +++- src/protect/rules/source.js | 1 + src/register.ts | 12 +++++++++--- tests/protect/hosted-deploy.test.ts | 12 +++++++++++- tests/protect/register.test.ts | 1 + 6 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/protect/engine/pulse-client.js b/src/protect/engine/pulse-client.js index 1b278270..3b07e346 100644 --- a/src/protect/engine/pulse-client.js +++ b/src/protect/engine/pulse-client.js @@ -33,11 +33,12 @@ export class PulseRuleClient { #ttlEffective = 0; #etag; #pulseAuth; + #fetchImpl; #detectionState; #buildId; - constructor({ siteUuid, baseUrl, cacheTtl, etag, timeoutMs, pulseAuth, detectionState, buildId } = {}) { + constructor({ siteUuid, baseUrl, cacheTtl, etag, timeoutMs, pulseAuth, detectionState, buildId, fetchImpl } = {}) { // Bounded so app STARTUP can't hang on a slow API: hosted platforms fail a deploy whose health // check is slow, and we always have a cache/bundled fallback to boot from. this.#timeoutMs = Number(timeoutMs) > 0 ? Number(timeoutMs) : 30_000; @@ -47,6 +48,7 @@ export class PulseRuleClient { this.#cacheTtl = Number.isFinite(cacheTtl) && cacheTtl > 0 ? cacheTtl : DEFAULT_CACHE_TTL; this.#etag = etag ?? null; this.#pulseAuth = pulseAuth ?? null; + this.#fetchImpl = fetchImpl; // Whether this guard reports detections, declared on a request it already makes. // // Detections are only sent when a rule fires, so silence at the server means one of three things — @@ -77,13 +79,14 @@ export class PulseRuleClient { } const url = `${this.#baseUrl}/rules/${encodeURIComponent(this.#siteUuid)}`; try { + const fetchRules = this.#fetchImpl ?? globalThis.fetch; // Sent without an `Authorization` header when no credential resolved or the exchange failed. // The server refuses that, and the refusal is handled the same way as any other failure: fall // back to cached or bundled rules. Attempting it anyway is deliberate — protection must never // hinge on the token path, and the runtime warns at boot when no credential resolves. const auth = await pulseAuthHeader( { pulseAuth: this.#pulseAuth, endpoint: this.#baseUrl, timeoutMs: this.#timeoutMs }, - fetch, + fetchRules, ); const headers = { Accept: 'application/json', ...auth }; // Claimed only on an authenticated request. Fetching rules must never hinge on getting a token @@ -111,7 +114,7 @@ export class PulseRuleClient { headers[REQUEST_PATH_HEADER] = '1'; } if (this.#etag) headers['If-None-Match'] = this.#etag; - const response = await fetch(url, { method: 'GET', headers, signal: AbortSignal.timeout(this.#timeoutMs) }); + const response = await fetchRules(url, { method: 'GET', headers, signal: AbortSignal.timeout(this.#timeoutMs) }); if (response.status === 304) { this.#touch(now); // revalidated — reset the clock (fresh jitter) diff --git a/src/protect/protect.d.ts b/src/protect/protect.d.ts index 828352b5..dfa64270 100644 --- a/src/protect/protect.d.ts +++ b/src/protect/protect.d.ts @@ -298,8 +298,10 @@ export interface CreateProtectionOptions { /** Optional Source-Host header for connector hostname checks. */ sourceHost?: string; /** Optional fetch override for the block-log and detection reporters (tests). The rules client and - * the manifest re-post use the global `fetch`. */ + * the manifest re-post use the global `fetch` by default. */ fetchImpl?: typeof fetch; + /** Optional transport for site UUID rule delivery and its credential exchange. */ + ruleFetchImpl?: typeof fetch; /** * Re-fetch and hot-swap the live rules every N ms. For long-lived runtimes that aren't restarted * on change (an AI builder's sandbox/preview) so a rule that becomes relevant after boot still diff --git a/src/protect/rules/source.js b/src/protect/rules/source.js index a701cdbe..d469b142 100644 --- a/src/protect/rules/source.js +++ b/src/protect/rules/source.js @@ -221,6 +221,7 @@ export async function resolveRules(options, store, ctx = {}) { etag: sameBuild ? prior?.etag : null, timeoutMs, pulseAuth: ctx.pulseAuth, + fetchImpl: options.ruleFetchImpl, detectionState: ctx.detectionState, buildId: identity.id, }); diff --git a/src/register.ts b/src/register.ts index c48e4d23..8a126a6e 100644 --- a/src/register.ts +++ b/src/register.ts @@ -8,15 +8,16 @@ import { isCanonicalUuid, isCredential, safeRemoteUrl } from './endpoint-policy. const siteUuid = process.env.PATCHSTACK_SITE_UUID; const apiKey = process.env.PATCHSTACK_API_KEY; const mode = process.env.PATCHSTACK_MODE; -const pulseRulesUrl = process.env.PATCHSTACK_PULSE_RULES_URL; +const configuredRulesUrl = process.env.PATCHSTACK_PULSE_RULES_URL; +const pulseRulesUrl = safeRemoteUrl(configuredRulesUrl)?.replace(/\/+$/, ''); if (!isCanonicalUuid(siteUuid)) throw new Error('Patchstack preload requires PATCHSTACK_SITE_UUID.'); if (!isCredential(apiKey)) throw new Error('Patchstack preload requires a valid PATCHSTACK_API_KEY.'); if (mode !== undefined && mode !== 'block' && mode !== 'dry-run') { throw new Error('PATCHSTACK_MODE must be block or dry-run.'); } -if (pulseRulesUrl !== undefined && safeRemoteUrl(pulseRulesUrl) === null) { - throw new Error('PATCHSTACK_PULSE_RULES_URL must use HTTPS or a loopback HTTP URL.'); +if (configuredRulesUrl !== undefined && (!pulseRulesUrl || /[?#]/.test(pulseRulesUrl))) { + 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 { @@ -40,6 +41,9 @@ function deploymentForSite(site: string): HostedDeployment | undefined { } 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' }); export const protection: Protection = await createProtection({ siteUuid: siteUuid.toLowerCase(), @@ -48,6 +52,8 @@ export const protection: Protection = await createProtection({ apiKey, pulseAuth: apiKey, pulseRulesUrl, + fetchImpl: serviceFetch, + ruleFetchImpl: serviceFetch, mode: mode ?? 'block', egress: process.env.PATCHSTACK_EGRESS === '1', refreshMs: process.env.PATCHSTACK_ENVIRONMENT === 'sandbox' ? 15_000 : 300_000, diff --git a/tests/protect/hosted-deploy.test.ts b/tests/protect/hosted-deploy.test.ts index 6d18afd4..0062bd2e 100644 --- a/tests/protect/hosted-deploy.test.ts +++ b/tests/protect/hosted-deploy.test.ts @@ -105,7 +105,7 @@ it.skipIf(!existsSync(join(root, 'dist/register.js')))('reports, deploys and rol env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, NODE_OPTIONS: nodeOptions, - PATCHSTACK_ENDPOINT: base + '/manifest', PATCHSTACK_PULSE_RULES_URL: base, + PATCHSTACK_ENDPOINT: base + '/manifest', PATCHSTACK_PULSE_RULES_URL: base + '/', PATCHSTACK_API_KEY: 'synthetic-key-' + (site + 1), PATCHSTACK_SITE_UUID: sites[site], PATCHSTACK_ENVIRONMENT: 'production', PATCHSTACK_MODE: 'block', PATCHSTACK_DEPLOYMENT_FILE: artifact, }, @@ -149,6 +149,16 @@ it.skipIf(!existsSync(join(root, 'dist/register.js')))('reports, deploys and rol expect.objectContaining({ rule_id: 'fixture-' + (index + 1), enforced: true }), ]) }) })); } + const egressOptions = options(a, 0, '--import=@patchstack/connect/register'); + await run(process.execPath, ['--input-type=module', '--eval', ` + import assert from 'node:assert/strict'; + import { protection } from '@patchstack/connect/register'; + assert.equal((await protection.refresh()).ok, true); + assert.equal(protection.synchronization.matched, true); + await assert.rejects(fetch(process.env.PATCHSTACK_PULSE_RULES_URL), /blocked an outbound request/); + await protection.stop(); + `], { ...egressOptions, env: { ...egressOptions.env, PATCHSTACK_EGRESS: '1' } }); + await expect(start(a, 1)).rejects.toThrow('must contain a completed build for PATCHSTACK_SITE_UUID'); rulesUnavailable = true; expect(await start(a, 0)).toMatchObject({ results: [403, 200, 200], status: { source: { origin: 'cache', ok: false } } }); diff --git a/tests/protect/register.test.ts b/tests/protect/register.test.ts index a13fc65b..ac86d782 100644 --- a/tests/protect/register.test.ts +++ b/tests/protect/register.test.ts @@ -55,6 +55,7 @@ describe.skipIf(!existsSync(register))('built Node preload', () => { PATCHSTACK_PULSE_RULES_URL: 'https://rules.example.test/monitor/pulse', PATCHSTACK_MODE: 'block', PATCHSTACK_EGRESS: '0', + PATCHSTACK_DEPLOYMENT_FILE: undefined, }, encoding: 'utf8', timeout: 10_000,