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. 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
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 <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 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 @@ -2373,6 +2377,7 @@ async function main(): Promise<number> {
}

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 {
Expand Down
2 changes: 1 addition & 1 deletion src/map-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
58 changes: 58 additions & 0 deletions src/prepare-deploy.ts
Original file line number Diff line number Diff line change
@@ -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<number> {
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;
}
9 changes: 6 additions & 3 deletions src/protect/engine/pulse-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 —
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion src/protect/protect.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -443,6 +445,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.
*
Expand Down
1 change: 1 addition & 0 deletions src/protect/rules/source.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
Expand Down
2 changes: 1 addition & 1 deletion src/protect/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`. */
Expand Down
41 changes: 37 additions & 4 deletions src/register.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,59 @@
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;
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 {
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 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: siteUuid.toLowerCase(),
buildId: deployment?.buildId,
manifestChecksum: deployment?.manifestChecksum,
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,
Expand Down
Loading
Loading