From a75f3b891b9dc98655c76c9b381963971a00e583 Mon Sep 17 00:00:00 2001 From: Dave Jong Date: Tue, 17 Nov 2026 20:00:29 +0100 Subject: [PATCH] Add a startup entry point for hosted Node apps --- AGENT-INSTALL.md | 1 + README.md | 23 ++++++++++++ package.json | 6 +++ src/register.ts | 29 +++++++++++++++ tests/protect/register.test.ts | 68 ++++++++++++++++++++++++++++++++++ tsconfig.json | 3 ++ tsup.config.ts | 10 +++++ 7 files changed, 140 insertions(+) create mode 100644 src/register.ts create mode 100644 tests/protect/register.test.ts diff --git a/AGENT-INSTALL.md b/AGENT-INSTALL.md index 81fb74d1..1a8d8fbb 100644 --- a/AGENT-INSTALL.md +++ b/AGENT-INSTALL.md @@ -8,6 +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). - **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 c165c7ad..7170047b 100644 --- a/README.md +++ b/README.md @@ -514,6 +514,29 @@ The Patchstack Connector is a floating control whose form follows the site's cla - **Turning the widget off:** run `npx @patchstack/connect widget --remove`, or set `"widget": false` in `.patchstackrc.json`. Only the widget tag stops; the production marker stays, because Patchstack needs it to recognise your live build. `setup` saves `"widget": false` itself when it sets up a new project without `--widget`. +## Host-managed Node applications + +For one Patchstack site per Node application process, provision a site and set +`PATCHSTACK_SITE_UUID` and `PATCHSTACK_API_KEY` in its server environment. Start +the app from its project directory with the preload installed as part of Connect: + +```sh +node --import @patchstack/connect/register server.js +``` + +If the host configures startup through environment variables, add +`--import=@patchstack/connect/register` to the application's existing +`NODE_OPTIONS`. Scope it to the running application. The preload requires both +values, waits for the initial rules lookup using Connect's startup timeout, and +refreshes rules while the app runs. It uses the existing cache and reporting. +Set `PATCHSTACK_MODE=dry-run` to observe, or `PATCHSTACK_EGRESS=1` to enable +outbound screening. Connect defaults to block mode for this integration. + +Import `protection` from the same entry point to inspect its `synchronization` +and `coverage()` or to mount a request adapter. Preloading alone does not attach +inbound request or response protection. Keep preview and production site +identities separate when their builds are deployed independently. + ## Programmatic API ```ts diff --git a/package.json b/package.json index df7c9713..e8639adf 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,12 @@ }, "default": "./dist/index.js" }, + "./register": { + "import": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + } + }, "./protect": { "workerd": "./dist/protect.edge.js", "worker": "./dist/protect.edge.js", diff --git a/src/register.ts b/src/register.ts new file mode 100644 index 00000000..2c7e1f15 --- /dev/null +++ b/src/register.ts @@ -0,0 +1,29 @@ +import { join } from 'node:path'; +import { createProtection, type Protection } from '@patchstack/connect/protect'; +import { isCanonicalUuid, isCredential, safeRemoteUrl } from './endpoint-policy.js'; + +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; + +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.'); +} + +export const protection: Protection = await createProtection({ + siteUuid, + apiKey, + pulseAuth: apiKey, + pulseRulesUrl, + mode: mode ?? 'block', + egress: process.env.PATCHSTACK_EGRESS === '1', + refreshMs: process.env.PATCHSTACK_ENVIRONMENT === 'sandbox' ? 15_000 : 300_000, + reportManifest: false, + cacheDir: join(process.cwd(), '.patchstack'), +}); diff --git a/tests/protect/register.test.ts b/tests/protect/register.test.ts new file mode 100644 index 00000000..1107fe59 --- /dev/null +++ b/tests/protect/register.test.ts @@ -0,0 +1,68 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const register = resolve('dist/register.js'); +const siteUuid = '11111111-1111-4111-8111-111111111111'; + +describe.skipIf(!existsSync(register))('built Node preload', () => { + function start(apiKey?: string) { + const cwd = mkdtempSync(join(tmpdir(), 'ps-register-')); + try { + const mockService = `data:text/javascript,${encodeURIComponent(` + globalThis.fetch = async (url, init) => { + if (new URL(url).pathname.endsWith('/token')) { + return Response.json({ access_token: 'synthetic-token' }); + } + if (new URL(url).pathname === '/monitor/pulse/rules/${siteUuid}' + && new Headers(init?.headers).get('authorization') === 'Bearer synthetic-token') { + globalThis.fixtureRulesLoaded = true; + return Response.json({ firewall: [{ + id: 'fixture-rule', + rule_v2: [{ parameter: 'get.label', match: { type: 'equals', value: 'fixture-block' } }] + }], whitelists: [], whitelist_keys: {} }); + } + throw new Error('Unexpected service request'); + }; + `)}`; + const entry = pathToFileURL(register).href; + return spawnSync(process.execPath, ['--input-type=module', '--eval', ` + if (!globalThis.fixtureRulesLoaded) throw new Error('Rules were not loaded before the app started'); + const { protection } = await import(${JSON.stringify(entry)}); + const status = protection.synchronization; + console.log(JSON.stringify({ siteUuid: status.siteUuid, rules: status.rules.request, origin: status.source.origin })); + `], { + cwd, + env: { + ...process.env, + NODE_OPTIONS: `--import=${mockService} --import=${entry}`, + PATCHSTACK_SITE_UUID: siteUuid, + PATCHSTACK_API_KEY: apiKey, + PATCHSTACK_PULSE_RULES_URL: 'https://rules.example.test/monitor/pulse', + PATCHSTACK_MODE: 'block', + PATCHSTACK_EGRESS: '0', + }, + encoding: 'utf8', + timeout: 10_000, + }); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + } + + it('fetches the configured site policy before the app starts', () => { + const child = start('synthetic-key-1'); + expect(child.status, child.stderr).toBe(0); + expect(JSON.parse(child.stdout)).toEqual({ siteUuid, rules: 1, origin: 'api' }); + }); + + it('reports missing host configuration before running the app', () => { + const child = start(); + expect(child.status).toBe(1); + expect(child.stderr).toContain('Patchstack preload requires a valid PATCHSTACK_API_KEY'); + expect(child.stdout).toBe(''); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index c4a36da8..2bd18c78 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,6 +3,9 @@ "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", + "paths": { + "@patchstack/connect/protect": ["./src/protect/protect.d.ts"] + }, "lib": ["ES2022"], "types": ["node"], "strict": true, diff --git a/tsup.config.ts b/tsup.config.ts index aa7cf2b2..9ac031b1 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -38,6 +38,16 @@ export default defineConfig([ // guard does not import the compiler. external: ['typescript'], }, + { + entry: { register: 'src/register.ts' }, + format: ['esm'], + dts: true, + clean: false, + sourcemap: true, + esbuildOptions: noEmbeddedSources, + target: 'node20', + external: ['@patchstack/connect/protect'], + }, { // Vendored runtime protection engine (node-waf + createProtection + Supabase guard), // exported as @patchstack/connect/protect. The scaffolded app guard imports this.