Skip to content
Open
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 @@ -164,7 +164,7 @@ https://api.patchstack.com/monitor/claim?site=…
When you've connected, say **done**.

#### What Patchstack found
🔴 High **1** · 🟠 Medium **3** · 🔵 Low **1** · 12 packages outdated · 12 protection rules available
🔴 High **1** · 🟠 Medium **3** · 🔵 Low **1** · 12 packages outdated · 12 protection rules from Patchstack

**Refresh your app's preview** to see the Patchstack widget.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ That's it. `setup` adds `@patchstack/connect` to the project when it is missing

If the server is already running, let the framework reload and check what it actually loaded: `patchstack-connect protect --check --runtime-url https://your-preview.example/api/contact` (loopback HTTP also works). You can supply the same `--runtime-url` to `setup`. This sends one signed, read-only OPTIONS challenge to that explicit URL, without sending the API key or following redirects. The response proves that a guard on that route loaded the current map, and reports its rule-readiness state and active rule counts. It does not prove other routes are covered or that an exploit is blocked. Both CLI and server need the site's server-side credential; `{ activationCheck: false }` disables the responder. If the guard cannot answer or carries an old map, restart/rebuild/deploy and check again. Setup never starts, builds or deploys your app.

Scaffolded guards refresh rules on a timer and on requests: once the rules are older than the refresh interval a request waits for the fetch, and every 30 seconds before that a serving guard re-checks in the background without holding any request, so a host that freezes between requests, or runs many copies of the app, picks up a rule change. Request-triggered refresh waits at most 2500ms by default, shares concurrent work, backs off after failures, and keeps last-known-good policy when offline. It never scans source or reports a manifest in the request path. A request with the header `x-patchstack-sync` runs that refresh straight away, at most once per 15 seconds; Patchstack sends one to the live site after its rules change. Hand-wired guards can configure `requestRefreshMs` (defaults to `refreshMs`, or zero when polling is disabled) and `requestRefreshTimeoutMs` (50–3000ms), or set the former to zero to opt out. `protection.synchronization` exposes the loaded identity, last successful lookup time, source health, readiness and scoped-rule blocking counts without a network call. Rule refresh does not change the loaded map identity.
Scaffolded guards refresh rules on a timer and on requests: once the rules are older than the refresh interval a request waits for the fetch, and every 30 seconds before that a serving guard re-checks in the background without holding any request, so a host that freezes between requests, or runs many copies of the app, picks up a rule change. Request-triggered refresh waits at most 2500ms by default, shares concurrent work, backs off after failures, and keeps last-known-good policy when offline. It never scans source or reports a manifest in the request path. A request with the header `x-patchstack-sync` runs that refresh straight away, at most once per 15 seconds; Patchstack sends one to the live site after its rules change. Hand-wired guards can configure `requestRefreshMs` (defaults to `refreshMs`, or zero when polling is disabled) and `requestRefreshTimeoutMs` (50–3000ms), or set the former to zero to opt out. `protection.synchronization` exposes the loaded identity, last successful lookup time, source health, readiness, rule counts and scoped-rule blocking counts without a network call. Rule refresh does not change the loaded map identity.

The authenticated rules response may include `X-Patchstack-Map-Rules: pending | ready` alongside `X-Patchstack-Build-Match` and `X-Patchstack-Build-ID`, including on a `304`. Readiness applies only when the response confirms the exact map identity requested. An absent or unrecognized readiness value means **unknown**, not ready. The ETag identifies the delivered policy, not map-generation completion. Broad and hardening rules remain usable while map-specific rules are pending.

Expand Down
12 changes: 9 additions & 3 deletions src/activation-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,18 @@ export async function checkActivation(url: string, config: Config, cwd: string,
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';
const rules = status.rules as {request?:number;response?:number;scopedBlocking?:number} | undefined;
const source = status.source as {ok?:boolean} | undefined;
const rules = status.rules as {request?:number;response?:number;egress?:number;delivered?:number;local?:number;scopedBlocking?:number} | undefined;
const source = status.source as {ok?:boolean;origin?:string} | undefined;
const split = `${Number(rules?.request ?? 0)} request / ${Number(rules?.response ?? 0)} response`;
const plural = (count: number) => `${count} ${count === 1 ? 'rule' : 'rules'}`;
const fetchedFromPatchstack = source?.origin === 'api' || source?.origin === 'cache';
const counts = typeof rules?.delivered === 'number' && typeof rules.local === 'number'
? `${plural(rules.delivered)} ${fetchedFromPatchstack ? 'from Patchstack' : 'from its bundled rules file'} + ${rules.local} of the guard's own (${split} / ${Number(rules.egress ?? 0)} outgoing)`
: `${split} rules`;
const age = typeof status.lastCheckedAt === 'number' ? ` (${Math.max(0,Math.floor((Date.now()-status.lastCheckedAt)/1000))}s since last success)` : '';
return {
ok:true,
message:`Guard active at the checked URL with the current map; rule readiness ${readiness}; server map match ${status.matched === true ? 'confirmed' : 'unconfirmed'}; last rule lookup ${source?.ok === true ? 'successful' : 'unconfirmed'}${age}; ${Number(rules?.request ?? 0)} request / ${Number(rules?.response ?? 0)} response rules; ${Number(rules?.scopedBlocking ?? 0)} map-scoped rules in blocking mode${status.devSync ? ' (HMR detect-only hold)' : ''}. This does not prove coverage of other routes or exploit blocking.`,
message:`Guard active at the checked URL with the current map; rule readiness ${readiness}; server map match ${status.matched === true ? 'confirmed' : 'unconfirmed'}; last rule lookup ${source?.ok === true ? 'successful' : 'unconfirmed'}${age}; ${counts}; ${Number(rules?.scopedBlocking ?? 0)} rules for this app's own routes in blocking mode${status.devSync ? ' (HMR detect-only hold)' : ''}. This does not prove coverage of other routes or exploit blocking.`,
summary:`Protection answered at the checked URL with the current app map. Rules: ${readiness}; map match: ${status.matched === true ? 'confirmed' : 'unconfirmed'}; latest rule check: ${source?.ok === true ? 'successful' : 'unconfirmed'}${age}.${status.devSync ? ' Rules for specific inputs only report attacks during hot reload.' : ''} This does not prove blocking or protection on other URLs.`,
};
};
Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1674,7 +1674,7 @@ async function runSetup(args: ParsedArgs): Promise<number> {
if (synced.rules.ok) {
// Rules are enforced by protection in a server; an app without one has nothing to apply them.
if (!noServer) report.rules = synced.rules.count;
report.done.push(`Live rule lookup succeeded (${synced.rules.count} delivered rules; not proof of runtime enforcement)`);
report.done.push(`Live rule lookup succeeded (${synced.rules.count} ${synced.rules.count === 1 ? 'rule' : 'rules'} from Patchstack${noServer ? '' : ", on top of the guard's own"}; not proof of runtime enforcement)`);
if (!noServer) {
if (synced.rules.mapRules === 'ready') {
report.done.push(`Rules for this map are ready${synced.rules.count === 0 ? ' (no applicable rules)' : ''}`);
Expand Down
2 changes: 1 addition & 1 deletion src/protect/protect.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface SynchronizationStatus {
source: {ok: boolean; origin: "api" | "cache" | "bundled" | "empty"; reason?: string};
mode: "block" | "dry-run";
devSync: boolean;
rules: {request: number; response: number; egress: number; scoped: number; scopedBlocking: number};
rules: {request: number; response: number; egress: number; delivered: number; local: number; scoped: number; scopedBlocking: number};
}

export interface Protection {
Expand Down
3 changes: 3 additions & 0 deletions src/protect/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -452,11 +452,13 @@ export async function createProtection(options = {}) {
let engine;
let responseRuleSet;
let egressRuleSet;
let deliveredRuleCount = 0;

// Split the delivered ruleset by phase (default "request"), merging phase defaults +
// per-call overrides. Detection is fully rule-driven — nothing hardcoded.
const applyBundle = (delivered) => {
const incoming = delivered.firewall ?? [];
deliveredRuleCount = incoming.length;
requestRules = byPhase(incoming, 'request');
responseRules = [...configuredResponseRules, ...byPhase(incoming, 'response')];
screenCap = responseScreenCap(responseRules);
Expand Down Expand Up @@ -1764,6 +1766,7 @@ export async function createProtection(options = {}) {
mode,
devSync: typeof process !== 'undefined' && process.env.PATCHSTACK_DEV_SYNC === '1',
rules: {request:requestRules.length, response:responseRules.length, egress:egressRules.length,
delivered: deliveredRuleCount, local: configuredResponseRules.length + configuredEgressRules.length,
scoped: [...requestRules, ...responseRules, ...egressRules].filter(rule => 'build_scope' in rule).length,
scopedBlocking: [...requestRules, ...responseRules, ...egressRules].filter(rule => 'build_scope' in rule && ruleMode(rule) === 'block').length},
});
Expand Down
4 changes: 2 additions & 2 deletions src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ function renderConcise(
if (findings.length > 0) lines.push(...findings);
if ((report.rules ?? 0) > 0) {
const rules = report.rules!;
lines.push(` ${paint(ANSI.green, `${rules} protection ${rules === 1 ? 'rule' : 'rules'} available`)}`);
lines.push(` ${paint(ANSI.green, `${rules} protection ${rules === 1 ? 'rule' : 'rules'} from Patchstack`)}`);
}
if (findings.length > 0 || (report.rules ?? 0) > 0) lines.push('');

Expand Down Expand Up @@ -318,7 +318,7 @@ export function renderSummary(report: StatusReport, progress: Progress, context:
const canProtect = protectionPossible(report);
context = { ...context, noServer: !canProtect };

const rules = canProtect && (report.rules ?? 0) > 0 ? `${report.rules} protection ${report.rules === 1 ? 'rule' : 'rules'} available` : null;
const rules = canProtect && (report.rules ?? 0) > 0 ? `${report.rules} protection ${report.rules === 1 ? 'rule' : 'rules'} from Patchstack` : null;
let headline: string;
if (counted && findings.vulnerable > 0) {
const vulnerabilities = findings.severity.high + findings.severity.medium + findings.severity.low + findings.severity.unknown;
Expand Down
36 changes: 36 additions & 0 deletions tests/protect/activation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest';
import { ACTIVATION_HEADER, activationChallenge, activationResponse, verifyActivationResponse } from '../../src/protect/activation.js';
import { createProtection } from '../../src/protect/runtime.js';
import { checkActivation } from '../../src/activation-check.js';
import { DEFAULT_EGRESS_RULES, DEFAULT_RESPONSE_RULES } from '../../src/protect/defaults.js';
import type { Config } from '../../src/types.js';

const secret='synthetic-activation-secret-1234';
Expand Down Expand Up @@ -75,6 +76,41 @@ it.each(['ready', 'pending', 'unknown'])('keeps %s readiness and enforcement lim
expect(result.summary).toContain('This does not prove blocking or protection on other URLs.');
});

it('counts rules from Patchstack apart from the guard\'s own, and the two add up to the phase split', async () => {
const match = [{ parameter: 'get.q', match: { type: 'contains', value: 'attack' } }];
const delivered = [{ id: 'synthetic-a', rule_v2: match }, { id: 'synthetic-b', phase: 'response', rule_v2: match }];
const p = await createProtection({ pulseAuth: secret, buildId: build, rules: { firewall: delivered }, cache: false, reportDetections: false });
try {
const { rules } = p.synchronization;
expect(rules.delivered).toBe(2);
expect(rules.local).toBe(DEFAULT_RESPONSE_RULES.length + DEFAULT_EGRESS_RULES.length);
expect(rules.request + rules.response + rules.egress).toBe(rules.delivered + rules.local);
} finally { await p.stop(); }
});

async function checkedWith(status: Record<string, unknown>): Promise<string> {
vi.stubGlobal('fetch', async (target: string, init: RequestInit) => activationResponse(new Request(target, init), secret, () => ({
siteUuid: site, buildId: build, mapRules: 'ready', ...status,
})));
return (await checkActivation(url, config, '.', build)).message;
}

it('names where the rules came from, with a split that adds up', async () => {
const counts = { request: 6, response: 20, egress: 2, delivered: 17, local: 11, scopedBlocking: 0 };
expect(await checkedWith({ source: { ok: true, origin: 'api' }, rules: counts }))
.toContain("17 rules from Patchstack + 11 of the guard's own (6 request / 20 response / 2 outgoing)");
expect(await checkedWith({ source: { ok: false, origin: 'bundled' }, rules: counts }))
.toContain("17 rules from its bundled rules file + 11 of the guard's own");
expect(await checkedWith({ source: { ok: true, origin: 'api' }, rules: { ...counts, delivered: 1 } }))
.toContain('1 rule from Patchstack');
});

it('keeps the phase split alone for a guard that does not report where its rules came from', async () => {
const message = await checkedWith({ source: { ok: true, origin: 'api' }, rules: { request: 6, response: 20, scopedBlocking: 0 } });
expect(message).toContain('; 6 request / 20 response rules;');
expect(message).not.toContain('from Patchstack');
});

it('bounds a transport that ignores abort', async()=>{
vi.useFakeTimers();vi.stubGlobal('fetch',()=>new Promise(()=>{}));
const work=checkActivation(url,config,'.',build);
Expand Down
6 changes: 3 additions & 3 deletions tests/report.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ describe('renderStatus concise', () => {
' Low ███████░░░░░░░░░░░░░ 1',
'',
' 12 packages are outdated',
' 12 protection rules available',
' 12 protection rules from Patchstack',
'',
'More npx @patchstack/connect vulns vulnerability details',
]);
Expand Down Expand Up @@ -199,7 +199,7 @@ describe('renderSummary', () => {
`When you've connected, say **done**.`,
'',
'#### What Patchstack found',
'🔴 High **1** · 🟠 Medium **3** · 🔵 Low **1** · 12 packages outdated · 12 protection rules available',
'🔴 High **1** · 🟠 Medium **3** · 🔵 Low **1** · 12 packages outdated · 12 protection rules from Patchstack',
'',
"**Refresh your app's preview** to see the Patchstack widget.",
]);
Expand Down Expand Up @@ -285,7 +285,7 @@ describe('renderSummary', () => {
it('never states a count the run did not get', () => {
const lines = renderSummary(report({ findings: null, rules: 12 }), notConnected, context, { widgetOnPage: false, dashboardUrl: null });
expect(lines[5]).toBe('### 🛡️ Checked 89 packages, now watching them');
expect(lines[7]).toBe('12 protection rules available.');
expect(lines[7]).toBe('12 protection rules from Patchstack.');
});

it('ends on the word AGENT-INSTALL.md maps to next, and the doc still maps the summary for later', () => {
Expand Down