diff --git a/src/protect/runtime.js b/src/protect/runtime.js index c6b4c5d..7cb8525 100644 --- a/src/protect/runtime.js +++ b/src/protect/runtime.js @@ -227,7 +227,11 @@ export async function createProtection(options = {}) { const { capture: _evidence, ...forCallback } = detection ?? {}; notify( userOnDetect, - { ...forCallback, ...(detection?.rule ? { rule: ruleIdentity(detection.rule) } : {}) }, + { + ...forCallback, + ...(typeof forCallback.message === 'string' ? { message: messageForMode(forCallback.message, forCallback.mode) } : {}), + ...(detection?.rule ? { rule: ruleIdentity(detection.rule) } : {}), + }, 'onDetect', ); }; @@ -1909,7 +1913,16 @@ export async function createProtection(options = {}) { fetchGuard() { return async (request, ...hostArgs) => { const { blocked } = await screenFetchRequest(request, hostArgs); - await deliverInRequest(blocked); + // A middleware that only screens (Next.js on Vercel) is frozen once the route answers, so a queued + // detect-only report would wait for a timer that never runs. Where the host offers `waitUntil`, the + // report is handed to it, as `fetch` does; otherwise it is delivered within the request. + const keep = detections && (blocked || detections.pending()) ? hostWaitUntil(request, hostArgs) : null; + if (keep) { + keep(detections.settle()); + detectPendingSince = null; + } else { + await deliverInRequest(blocked); + } return blocked; }; @@ -3262,9 +3275,16 @@ function blockResponse(result, request) { }); } +// A rule's message is written without knowing the mode it will run under, and the engine's default says +// "Blocked by". A match that did not block must not say it did. +function messageForMode(message, mode) { + return mode === 'block' ? message : message.replace(/^Blocked by /, 'Matched by '); +} + +// Rules the site adds itself carry no category; they are named as what they are rather than as unknown. function defaultOnDetect({ phase, mode, category, rule, message }) { const tag = mode === 'block' ? 'BLOCK' : 'DETECT (dry-run)'; - console.warn(`[patchstack] ${tag} phase=${phase ?? 'request'} category=${category ?? '?'} rule=${rule?.id ?? '?'} ${message ?? ''}`.trim()); + console.warn(`[patchstack] ${tag} phase=${phase ?? 'request'} category=${category || 'custom'} rule=${rule?.id ?? '?'} ${message ?? ''}`.trim()); } /** diff --git a/tests/protect/rules-reader.test.ts b/tests/protect/rules-reader.test.ts index ef3a38d..f93f434 100644 --- a/tests/protect/rules-reader.test.ts +++ b/tests/protect/rules-reader.test.ts @@ -350,3 +350,52 @@ describe('delivering a block report on a host that passes no execution context a await protection.stop(); }); }); + +// A Next.js middleware calls `fetchGuard` with the request alone, and on Vercel the function is frozen +// once the route answers: a detect-only report queued for a later flush would never be sent. +describe('a detect-only report from fetchGuard on a host with waitUntil', () => { + const key = Symbol.for('@vercel/request-context'); + afterEach(() => { + delete (globalThis as Record)[key]; + }); + + it('is handed to the host and delivered, without waiting for a later request', async () => { + const cwd = mkdtempSync(join(tmpdir(), 'ps-reader-')); + dirs.push(cwd); + vi.stubEnv('PATCHSTACK_API_KEY', ''); + vi.stubEnv('PATCHSTACK_PULSE_AUTH', ''); + vi.stubEnv('PATCHSTACK_MODE', ''); + const calls: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (url: string) => { + calls.push(String(url)); + if (String(url).endsWith('/token')) return Response.json({ access_token: 'reader-token', expires_in: 3600 }); + if (String(url).includes('/detections/')) return new Response('{}', { status: 202 }); + return Response.json({ firewall: [{ id: 'live-rule', phase: 'request', action: 'block', rule_v2: [{ parameter: 'get.q', match: { type: 'contains', value: 'live-attack' } }] }], whitelists: [], whitelist_keys: {}, enforcement: 'dry-run' }); + })); + const lines: string[] = []; + vi.spyOn(console, 'warn').mockImplementation((line: string) => { lines.push(line); }); + const protection: any = await createProtection({ + siteUuid: '550e8400-e29b-41d4-a716-446655440000', + pulseRulesUrl: 'https://x.test/monitor/pulse', + cwd, + cacheDir: join(cwd, '.patchstack'), + rules: { firewall: [], whitelists: [], whitelist_keys: {}, _patchstack: { rules_reader: READER } } as never, + reportDetections: true, + }); + const kept: Promise[] = []; + (globalThis as Record)[key] = { get: () => ({ waitUntil: (work: Promise) => { kept.push(work); } }) }; + + expect(await protection.fetchGuard()(new Request('https://app.test/search?q=live-attack'))).toBeNull(); + expect(kept).toHaveLength(1); + await Promise.all(kept); + expect(calls.some((url) => url.includes('/detections/'))).toBe(true); + + // The log line says what happened: a match that did not block, from a rule with no category. + const line = lines.find((l) => l.includes('rule=live-rule')); + expect(line).toContain('DETECT (dry-run)'); + expect(line).toContain('category=custom'); + expect(line).toContain('Matched by Patchstack WAF rule: live-rule'); + expect(line).not.toContain('Blocked'); + await protection.stop(); + }); +});