From 2ffb93237378917b6da00cfe30ab7de74c351d4c Mon Sep 17 00:00:00 2001 From: Tamas Erdelyi Date: Thu, 19 Nov 2026 16:17:36 +0000 Subject: [PATCH 1/3] fix(protect): split rule counts into rules from Patchstack and built-in rules - the guard's status reports delivered and built-in rule counts - the runtime check prints them as 'N rules from Patchstack + M built into the guard' - 'map-scoped rules' is now 'rules for this app's own routes' - setup's rule lookup line says the delivered rules sit on top of the built-in ones --- README.md | 2 +- src/activation-check.ts | 8 ++++++-- src/cli.ts | 2 +- src/protect/protect.d.ts | 2 +- src/protect/runtime.js | 3 +++ tests/protect/activation.test.ts | 20 ++++++++++++++++++++ 6 files changed, 32 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index b504a11e..63200af1 100644 --- a/README.md +++ b/README.md @@ -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 (split into rules from Patchstack and rules built into the guard) 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. diff --git a/src/activation-check.ts b/src/activation-check.ts index c5d83d61..252393d4 100644 --- a/src/activation-check.ts +++ b/src/activation-check.ts @@ -36,12 +36,16 @@ 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 rules = status.rules as {request?:number;response?:number;delivered?:number;builtIn?:number;scopedBlocking?:number} | undefined; + const split = `${Number(rules?.request ?? 0)} request / ${Number(rules?.response ?? 0)} response`; + const counts = typeof rules?.delivered === 'number' && typeof rules.builtIn === 'number' + ? `${rules.delivered} rules from Patchstack + ${rules.builtIn} built into the guard (${split})` + : `${split} rules`; const source = status.source as {ok?:boolean} | undefined; 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.`, }; }; diff --git a/src/cli.ts b/src/cli.ts index 5626c0e4..900144aa 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1674,7 +1674,7 @@ async function runSetup(args: ParsedArgs): Promise { 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} rules from Patchstack, on top of the guard's built-in rules; 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)' : ''}`); diff --git a/src/protect/protect.d.ts b/src/protect/protect.d.ts index 93ce9093..c078d4cf 100644 --- a/src/protect/protect.d.ts +++ b/src/protect/protect.d.ts @@ -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; builtIn: number; scoped: number; scopedBlocking: number}; } export interface Protection { diff --git a/src/protect/runtime.js b/src/protect/runtime.js index c6b4c5d7..62140215 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -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); @@ -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, builtIn: 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}, }); diff --git a/tests/protect/activation.test.ts b/tests/protect/activation.test.ts index bafbbea4..5d5080f6 100644 --- a/tests/protect/activation.test.ts +++ b/tests/protect/activation.test.ts @@ -75,6 +75,26 @@ 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('splits the rule count into rules from Patchstack and rules built into the guard', 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.builtIn).toBeGreaterThan(0); + expect(rules.request + rules.response + rules.egress).toBe(rules.delivered + rules.builtIn); + } finally { await p.stop(); } + + vi.stubGlobal('fetch', async (target: string, init: RequestInit) => activationResponse(new Request(target, init), secret, () => ({ + siteUuid: site, buildId: build, mapRules: 'ready', source: { ok: true }, + rules: { request: 6, response: 20, egress: 1, delivered: 17, builtIn: 10, scopedBlocking: 0 }, + }))); + const result = await checkActivation(url, config, '.', build); + expect(result.message).toContain('17 rules from Patchstack + 10 built into the guard (6 request / 20 response)'); + expect(result.message).toContain("0 rules for this app's own routes in blocking mode"); +}); + it('bounds a transport that ignores abort', async()=>{ vi.useFakeTimers();vi.stubGlobal('fetch',()=>new Promise(()=>{})); const work=checkActivation(url,config,'.',build); From 040c1209a35b11ad0464b46bb6b583ea9ae2e01e Mon Sep 17 00:00:00 2001 From: Tamas Erdelyi Date: Thu, 19 Nov 2026 16:29:45 +0000 Subject: [PATCH 2/3] fix(protect): make the rule counts add up and say where the rules came from - the runtime check's split includes outgoing rules, so it adds up to the two totals - rules are 'from Patchstack' only when fetched; otherwise 'from its bundled rules file' - the guard's own rules count is 'local', which also covers rules the host configures - setup and the summary say 'protection rules from Patchstack' instead of 'available' - setup does not mention the guard for an app with no server - one rule is 'rule', not 'rules' --- AGENT-INSTALL.md | 2 +- README.md | 2 +- src/activation-check.ts | 10 ++++++---- src/cli.ts | 2 +- src/protect/protect.d.ts | 2 +- src/protect/runtime.js | 2 +- src/report.ts | 4 ++-- tests/protect/activation.test.ts | 32 ++++++++++++++++++++++++-------- tests/report.test.ts | 6 +++--- 9 files changed, 40 insertions(+), 22 deletions(-) diff --git a/AGENT-INSTALL.md b/AGENT-INSTALL.md index ffb0f4cf..11f05d53 100644 --- a/AGENT-INSTALL.md +++ b/AGENT-INSTALL.md @@ -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. diff --git a/README.md b/README.md index 63200af1..b6d7356e 100644 --- a/README.md +++ b/README.md @@ -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, rule counts (split into rules from Patchstack and rules built into the guard) 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 (`delivered` from Patchstack or the bundled rules file, `local` from the guard's own response and outgoing rules; `request`, `response` and `egress` count both) 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. diff --git a/src/activation-check.ts b/src/activation-check.ts index 252393d4..6287dd0b 100644 --- a/src/activation-check.ts +++ b/src/activation-check.ts @@ -36,12 +36,14 @@ 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;delivered?:number;builtIn?:number;scopedBlocking?:number} | 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 counts = typeof rules?.delivered === 'number' && typeof rules.builtIn === 'number' - ? `${rules.delivered} rules from Patchstack + ${rules.builtIn} built into the guard (${split})` + 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 source = status.source as {ok?:boolean} | undefined; const age = typeof status.lastCheckedAt === 'number' ? ` (${Math.max(0,Math.floor((Date.now()-status.lastCheckedAt)/1000))}s since last success)` : ''; return { ok:true, diff --git a/src/cli.ts b/src/cli.ts index 900144aa..649d48da 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1674,7 +1674,7 @@ async function runSetup(args: ParsedArgs): Promise { 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} rules from Patchstack, on top of the guard's built-in 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)' : ''}`); diff --git a/src/protect/protect.d.ts b/src/protect/protect.d.ts index c078d4cf..e3e595a9 100644 --- a/src/protect/protect.d.ts +++ b/src/protect/protect.d.ts @@ -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; delivered: number; builtIn: number; scoped: number; scopedBlocking: number}; + rules: {request: number; response: number; egress: number; delivered: number; local: number; scoped: number; scopedBlocking: number}; } export interface Protection { diff --git a/src/protect/runtime.js b/src/protect/runtime.js index 62140215..45213091 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -1766,7 +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, builtIn: configuredResponseRules.length + configuredEgressRules.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}, }); diff --git a/src/report.ts b/src/report.ts index c14fb0c4..a9df6246 100644 --- a/src/report.ts +++ b/src/report.ts @@ -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(''); @@ -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; diff --git a/tests/protect/activation.test.ts b/tests/protect/activation.test.ts index 5d5080f6..9288f55e 100644 --- a/tests/protect/activation.test.ts +++ b/tests/protect/activation.test.ts @@ -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'; @@ -75,24 +76,39 @@ 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('splits the rule count into rules from Patchstack and rules built into the guard', async () => { +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.builtIn).toBeGreaterThan(0); - expect(rules.request + rules.response + rules.egress).toBe(rules.delivered + rules.builtIn); + 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): Promise { vi.stubGlobal('fetch', async (target: string, init: RequestInit) => activationResponse(new Request(target, init), secret, () => ({ - siteUuid: site, buildId: build, mapRules: 'ready', source: { ok: true }, - rules: { request: 6, response: 20, egress: 1, delivered: 17, builtIn: 10, scopedBlocking: 0 }, + siteUuid: site, buildId: build, mapRules: 'ready', ...status, }))); - const result = await checkActivation(url, config, '.', build); - expect(result.message).toContain('17 rules from Patchstack + 10 built into the guard (6 request / 20 response)'); - expect(result.message).toContain("0 rules for this app's own routes in blocking mode"); + 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()=>{ diff --git a/tests/report.test.ts b/tests/report.test.ts index 4127c849..d701c3da 100644 --- a/tests/report.test.ts +++ b/tests/report.test.ts @@ -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', ]); @@ -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.", ]); @@ -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', () => { From adc55e874da18345975071dc3dbca32a25f570fd Mon Sep 17 00:00:00 2001 From: Tamas Erdelyi Date: Thu, 19 Nov 2026 16:35:07 +0000 Subject: [PATCH 3/3] docs(readme): shorten the synchronization rule counts mention --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b6d7356e..4bb9df3b 100644 --- a/README.md +++ b/README.md @@ -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, rule counts (`delivered` from Patchstack or the bundled rules file, `local` from the guard's own response and outgoing rules; `request`, `response` and `egress` count both) 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.