From e00768f6937353777b2c294d8c2351fb505d9789 Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sun, 22 Nov 2026 22:19:16 -0600 Subject: [PATCH 1/2] Connect verified invisible CAPTCHA scores to subsequent requests --- README.md | 10 +-- packages/client/src/invisible.ts | 41 +++++++---- packages/client/src/pow.test.ts | 50 ++++++++++++++ packages/nextjs/src/captcha.ts | 1 + packages/webdecoy/src/captcha/http.test.ts | 79 ++++++++++++++++++++-- packages/webdecoy/src/captcha/http.ts | 58 ++++++++++------ packages/webdecoy/src/captcha/service.ts | 44 +++++++++--- packages/webdecoy/src/client-signals.ts | 66 +++++++++++++----- packages/webdecoy/src/fetch-guard.ts | 4 +- 9 files changed, 284 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 69e1e2a..b302250 100644 --- a/README.md +++ b/README.md @@ -455,10 +455,12 @@ app.use(webdecoy({ })); ``` -`@webdecoy/client` collects behavioural, environmental and form signals in the -browser; `/score` records the verdict against the session; `clientSignals()` acts -on it for the requests that follow. Before this the score went back to the -browser and the origin never learned anything from it. +Configure the browser client to score against the same HTTPS origin as the +protected application. After verifying the browser's proof and committed signals, +`/score` stores the verdict and sends a host-only, HttpOnly cookie. Subsequent +requests can use the verdict through `clientSignals()` for up to 15 minutes. +Set `clientSignals({ store: signalStore, siteKey })` when multiple site keys +share one request host. **A request with no session is `NOT_RUN`, never a denial** — curl and Googlebot both send nothing, and scoring silence would deny exactly the crawlers you most diff --git a/packages/client/src/invisible.ts b/packages/client/src/invisible.ts index 30dcbf5..c09e7b8 100644 --- a/packages/client/src/invisible.ts +++ b/packages/client/src/invisible.ts @@ -14,7 +14,7 @@ import { TemporalCollector } from './temporal'; import { PoWManager } from './pow'; import { getServerUrl, getBasePath } from './config'; import { sha256 } from './sha256'; -import type { CollectedSignals, InvisibleOptions, PoWSolution, VerifyResponse } from './types'; +import type { Challenge, CollectedSignals, InvisibleOptions, PoWSolution, VerifyResponse } from './types'; interface Listener { event: string; @@ -33,6 +33,8 @@ export class InvisibleSession { private startTime: number; private lastScore: (VerifyResponse & { timestamp: number }) | null = null; private listeners: Listener[] = []; + private challengeRequest: Promise | null = null; + private scoring: Promise | null = null; constructor(options?: InvisibleOptions) { this.options = Object.assign( @@ -69,21 +71,13 @@ export class InvisibleSession { if (this.options.autoScore) this._attachToForms(); - void this._fetchChallenge(); + this.challengeRequest = this.powManager.fetchChallenge(this.options.siteKey); } private serverOrigin(): string | null { return this.options.serverUrl || getServerUrl(); } - private async _fetchChallenge(): Promise { - try { - await this.powManager.fetchChallenge(this.options.siteKey); - } catch (e) { - console.warn('PoW challenge fetch failed:', e); - } - } - private _attachListeners(): void { const handlers: Record = { mousemove: (e) => this.behavioral.recordMouseMove(e as MouseEvent), @@ -161,6 +155,17 @@ export class InvisibleSession { } async execute(action = ''): Promise { + const run = () => this._collectAndScore(action); + const score = this.scoring ? this.scoring.then(run, run) : run(); + this.scoring = score; + try { + return await score; + } finally { + if (this.scoring === score) this.scoring = null; + } + } + + private async _collectAndScore(action: string): Promise { const elapsed = Date.now() - this.startTime; if (elapsed < this.options.minCollectionTime) { await new Promise((r) => setTimeout(r, this.options.minCollectionTime - elapsed)); @@ -178,6 +183,12 @@ export class InvisibleSession { const formAnalysis = getFormAnalyzer().analyze(); const sensorData = this.sensor.analyze(); + let challenge = await (this.challengeRequest ?? this.powManager.fetchChallenge(this.options.siteKey)); + this.challengeRequest = null; + if (challenge.expiresAt <= Date.now()) { + challenge = await this.powManager.fetchChallenge(this.options.siteKey); + } + const signals: CollectedSignals = { behavioral: behavioralData, environmental: { ...envData, rafConsistency: rafData, ...asyncEnvData, sensor: sensorData }, @@ -187,7 +198,7 @@ export class InvisibleSession { sessionId: this.id, siteKey: this.options.siteKey, action, - challengeNonce: this.powManager.challenge?.nonce || null, + challengeNonce: challenge.nonce || null, timestamp: Date.now(), userAgent: navigator.userAgent, screenSize: `${screen.width}x${screen.height}`, @@ -200,7 +211,12 @@ export class InvisibleSession { const signalsJson = JSON.stringify(signals); const signalsHash = await sha256(signalsJson); - const powSolution = await this.powManager.solveWithSignalsHash(this.options.siteKey, signalsHash); + let powSolution: PoWSolution; + try { + powSolution = await this.powManager.solveWithSignalsHash(this.options.siteKey, signalsHash); + } finally { + this.powManager.reset(); + } const powTiming = { duration: powSolution.duration, iterations: powSolution.iterations, @@ -226,6 +242,7 @@ export class InvisibleSession { try { const response = await fetch(url + getBasePath() + '/score', { method: 'POST', + credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ siteKey: this.options.siteKey, diff --git a/packages/client/src/pow.test.ts b/packages/client/src/pow.test.ts index 0ba877b..7668bba 100644 --- a/packages/client/src/pow.test.ts +++ b/packages/client/src/pow.test.ts @@ -1,7 +1,10 @@ +import { EnvironmentalCollector } from './collectors/environment'; import { getServerUrl, setServerUrl } from './config'; import { InvisibleSession } from './invisible'; import { PoWManager } from './pow'; +jest.mock('./sha256', () => ({ sha256: async () => 'fixture-hash' })); + const globalFetch = globalThis.fetch; const originalOrigin = getServerUrl(); const challengeData = { @@ -47,3 +50,50 @@ it('fetches the invisible session challenge from its configured origin', () => { session.destroy(); } }); + + +it('binds consecutive invisible scores to their own challenges', async () => { + const instance = 'https://session.example.test'; + const posted: Array<{ signalsJson: string; powSolution: { challengeId: string } }> = []; + let challengeCount = 0; + globalThis.fetch = jest.fn(async (url: unknown, init?: RequestInit) => { + if (String(url).includes('/challenge?')) { + const id = String(++challengeCount); + return { ok: true, json: async () => ({ + ...challengeData, id, nonce: 'nonce-' + id, expiresAt: Date.now() + 60_000, + }) } as Response; + } + + expect(init?.credentials).toBe('same-origin'); + posted.push(JSON.parse(init?.body as string)); + return { ok: true, json: async () => ({ success: true, token: 'fixture-token' }) } as Response; + }); + + const collect = jest.spyOn(EnvironmentalCollector.prototype, 'collect').mockReturnValue({}); + const asyncCollect = jest.spyOn(EnvironmentalCollector.prototype, 'collectAsync').mockResolvedValue({}); + const frames = jest.spyOn(EnvironmentalCollector.prototype, 'measureRAFConsistency').mockResolvedValue({}); + const solve = jest.spyOn(PoWManager.prototype, 'solveWithSignalsHash').mockImplementation(async function (this: PoWManager) { + return { + challengeId: this.challenge!.challengeId, + nonce: 2, hash: 'test-hash', iterations: 10, duration: 25, difficulty: 2, + signalsHash: 'fixture-hash', local: false, + }; + }); + const session = new InvisibleSession({ serverUrl: instance, autoScore: false, minCollectionTime: 0 }); + try { + await Promise.all([session.execute('first'), session.execute('second')]); + + expect(challengeCount).toBe(2); + expect(posted.map(({ signalsJson, powSolution }) => ({ + action: JSON.parse(signalsJson).meta.action, + challengeNonce: JSON.parse(signalsJson).meta.challengeNonce, + challengeId: powSolution.challengeId, + }))).toEqual([ + { action: 'first', challengeNonce: 'nonce-1', challengeId: '1' }, + { action: 'second', challengeNonce: 'nonce-2', challengeId: '2' }, + ]); + } finally { + session.destroy(); + for (const spy of [collect, asyncCollect, frames, solve]) spy.mockRestore(); + } +}); diff --git a/packages/nextjs/src/captcha.ts b/packages/nextjs/src/captcha.ts index 032a778..e637be6 100644 --- a/packages/nextjs/src/captcha.ts +++ b/packages/nextjs/src/captcha.ts @@ -71,6 +71,7 @@ export function createCaptchaHandler(options?: NextCaptchaOptions): NextCaptchaH } const headers = headersToRecord(req.headers); + if (!headers.host && !headers[':authority']) headers.host = url.host; const result = await endpoints.handle({ method: req.method, pathname: url.pathname, diff --git a/packages/webdecoy/src/captcha/http.test.ts b/packages/webdecoy/src/captcha/http.test.ts index 900a205..d0d3305 100644 --- a/packages/webdecoy/src/captcha/http.test.ts +++ b/packages/webdecoy/src/captcha/http.test.ts @@ -5,7 +5,8 @@ */ import { createHash } from 'crypto'; -import { MemoryClientSignalStore } from '../client-signals'; +import { clientSignals, MemoryClientSignalStore } from '../client-signals'; +import { createTestHarness, expectRuleState, request } from '../testing'; import { createCaptchaEndpoints, type CaptchaRequest } from './http'; import type { ChallengeData, PoWSolution } from './types'; @@ -33,11 +34,12 @@ const ENV = { navigator: { platform: 'MacIntel', maxTouchPoints: 0 }, }; -function solve(challenge: ChallengeData): PoWSolution { +function solve(challenge: ChallengeData, signalsHash?: string): PoWSolution { const target = '0'.repeat(challenge.difficulty); + const prefix = signalsHash ? `${challenge.prefix}:${signalsHash}` : challenge.prefix; for (let n = 0; ; n++) { - const hash = createHash('sha256').update(`${challenge.prefix}:${n}`).digest('hex'); - if (hash.startsWith(target)) return { challengeId: challenge.id, nonce: n, hash }; + const hash = createHash('sha256').update(`${prefix}:${n}`).digest('hex'); + if (hash.startsWith(target)) return { challengeId: challenge.id, nonce: n, hash, signalsHash }; } } @@ -172,6 +174,75 @@ describe('captcha HTTP endpoints', () => { } }); + it('connects a verified invisible score to the next request with a scoped receipt', async () => { + const host = 'captcha.example.test'; + const ip = '203.0.113.9'; + const signalStore = new MemoryClientSignalStore({ ttl: 3_600_000 }); + const { captcha, handle } = createCaptchaEndpoints({ secret: 'test-secret', signalStore }); + const rule = clientSignals({ store: signalStore, siteKey: 'site' }); + const dryRun = clientSignals({ store: signalStore, siteKey: 'site', minScore: 0, dryRun: true }); + const sdk = createTestHarness({ rules: [rule] }); + const dryRunSdk = createTestHarness({ rules: [dryRun] }); + const now = Date.now(); + const clock = jest.spyOn(Date, 'now').mockReturnValue(now); + + try { + const challenge = await captcha.issueChallenge('site', ip, 2); + const signalsJson = JSON.stringify({ + behavioral: HUMAN, + environmental: ENV, + meta: { sessionId: 'browser-session', challengeNonce: challenge.nonce }, + }); + const signalsHash = createHash('sha256').update(signalsJson).digest('hex'); + clock.mockReturnValue(now + 3000); + const res = await handle(req({ + method: 'POST', + pathname: '/__webdecoy/score', + ip, + headers: { ...HEADERS, host, origin: 'https://' + host }, + body: { siteKey: 'site', action: 'login', signalsJson, powSolution: solve(challenge, signalsHash) }, + })); + + expect(res?.body).toMatchObject({ success: true, action: 'login', sessionId: null }); + expect(res?.headers['cache-control']).toBe('private, no-store'); + const cookie = res?.headers['set-cookie'] ?? ''; + expect(cookie).toMatch(/^__Host-wd_cs=[a-f0-9]{48}; Path=\/; Max-Age=900; Secure; HttpOnly; SameSite=Lax$/); + const receipt = cookie.split(';')[0]; + const followup = request({ ip, headers: { host, cookie: receipt } }); + + expectRuleState(await sdk.protect(followup), 'client-signals', 'RUN'); + const monitored = await dryRunSdk.protect(followup); + expectRuleState(monitored, 'client-signals', 'DRY_RUN'); + expect(JSON.stringify(monitored)).not.toContain(receipt.split('=')[1]); + + const otherHost = request({ ip, headers: { host: 'other.example.test', cookie: receipt } }); + expectRuleState(await sdk.protect(otherHost), 'client-signals', 'NOT_RUN'); + expectRuleState(await sdk.protect(request({ ip, headers: { host } })), 'client-signals', 'NOT_RUN'); + + const wrongSite = createTestHarness({ rules: [clientSignals({ store: signalStore, siteKey: 'other' })] }); + expectRuleState(await wrongSite.protect(followup), 'client-signals', 'NOT_RUN'); + + clock.mockReturnValue(now + 903_000); + expect(signalStore.size).toBe(1); + expectRuleState(await sdk.protect(followup), 'client-signals', 'NOT_RUN'); + } finally { + clock.mockRestore(); + } + }); + + it('omits the receipt when there is no verified browser proof', async () => { + const signalStore = new MemoryClientSignalStore(); + const { handle } = createCaptchaEndpoints({ secret: 'test-secret', signalStore }); + const res = await handle(req({ + method: 'POST', + pathname: '/__webdecoy/score', + headers: { ...HEADERS, host: 'captcha.example.test', origin: 'https://captcha.example.test' }, + body: { siteKey: 'site', signals: { behavioral: HUMAN, environmental: ENV } }, + })); + expect(res?.headers).not.toHaveProperty('set-cookie'); + expect(signalStore.size).toBe(0); + }); + it('400s a token verify with no token', async () => { const { handle } = createCaptchaEndpoints({ secret: 's' }); const res = await handle(req({ method: 'POST', pathname: '/__webdecoy/token/verify', body: {} })); diff --git a/packages/webdecoy/src/captcha/http.ts b/packages/webdecoy/src/captcha/http.ts index 8003469..9f8a950 100644 --- a/packages/webdecoy/src/captcha/http.ts +++ b/packages/webdecoy/src/captcha/http.ts @@ -13,7 +13,14 @@ import { Captcha, type CaptchaOptions } from './service'; import type { Signals } from '../detection/types'; -import type { ClientSignalStore } from '../client-signals'; +import { + CLIENT_RECEIPT_COOKIE, + CLIENT_RECEIPT_PREFIX, + CLIENT_RECEIPT_TTL_MS, + getClientSignalHost, + type ClientSignalStore, +} from '../client-signals'; +import { randomHex } from '../webcrypto'; /** Normalized inbound request the adapters construct. */ export interface CaptchaRequest { @@ -55,7 +62,7 @@ interface VerifyBody { powTiming?: { duration?: number; iterations?: number } | null; action?: string; token?: string; - /** The browser widget's session id, sent by `@webdecoy/client`. */ + /** Session ID supplied by an existing application integration. */ sessionId?: string; } @@ -115,8 +122,9 @@ export function createCaptchaEndpoints(options: CaptchaEndpointsOptions = {}) { // POST {base}/score (invisible mode) if (sub === '/score' && method === 'POST') { const b = (req.body ?? {}) as VerifyBody; - const result = await captcha.score({ - siteKey: b.siteKey ?? 'default', + const siteKey = b.siteKey ?? 'default'; + const { result, verifiedSignals } = await captcha.scoreForSession({ + siteKey, ip: req.ip, userAgent, headers: req.headers, @@ -128,25 +136,35 @@ export function createCaptchaEndpoints(options: CaptchaEndpointsOptions = {}) { action: b.action, }); - // Remember the verdict against the browser's session, so the requests - // that follow can act on it. Without this the score goes back to the - // browser and the origin never learns anything from it — which was the - // gap: all the parts existed and nothing joined them. - if (signalStore && b.sessionId) { + const legacyId = typeof b.sessionId === 'string' && !b.sessionId.startsWith(CLIENT_RECEIPT_PREFIX) + ? b.sessionId || null + : null; + const response = json(200, { ...result, sessionId: legacyId }); + if (!signalStore) return response; + + const at = Date.now(); + const verdict = { score: result.score, recommendation: result.recommendation, at }; + if (legacyId) { + await signalStore.set({ ...verdict, sessionId: legacyId }); + return response; + } + + const host = getClientSignalHost(req.headers); + const origin = req.headers.origin; + if ( + verifiedSignals && host && (!origin || origin === 'https://' + host) + && typeof siteKey === 'string' && siteKey.length <= 128 + ) { + const receipt = randomHex(24); await signalStore.set({ - sessionId: b.sessionId, - score: result.score, - recommendation: result.recommendation, - at: Date.now(), + ...verdict, + sessionId: CLIENT_RECEIPT_PREFIX + receipt, + receipt: { host, siteKey, expiresAt: at + CLIENT_RECEIPT_TTL_MS }, }); + response.headers['set-cookie'] = `${CLIENT_RECEIPT_COOKIE}=${receipt}; Path=/; Max-Age=${CLIENT_RECEIPT_TTL_MS / 1000}; Secure; HttpOnly; SameSite=Lax`; + response.headers['cache-control'] = 'private, no-store'; } - - return json(200, { - ...result, - // Echoed so the widget can set the cookie the rule reads, without the - // developer wiring a second endpoint to hand it one. - sessionId: b.sessionId ?? null, - }); + return response; } // POST {base}/token/verify diff --git a/packages/webdecoy/src/captcha/service.ts b/packages/webdecoy/src/captcha/service.ts index 2516803..bbe6e7a 100644 --- a/packages/webdecoy/src/captcha/service.ts +++ b/packages/webdecoy/src/captcha/service.ts @@ -84,16 +84,20 @@ export class Captcha { * signals, and issues a session token on success. Mirrors `runVerification`. */ async verify(input: VerifyInput): Promise { - return this.verifySubmission(input, true); + return (await this.verifySubmission(input, true)).result; } - private async verifySubmission(input: VerifyInput, widgetInteraction: boolean): Promise { + private async verifySubmission(input: VerifyInput, widgetInteraction: boolean): Promise<{ + result: VerifyResult; + verifiedSignals: boolean; + }> { const { siteKey, ip, userAgent } = input; const headers = input.headers ?? {}; let signals: Signals = input.signals ?? {}; const extraDetections: Detection[] = []; // 1. Signals commitment: the solution may bind a hash of the raw signals. + let committedSignals = false; const clientSignalsHash = input.powSolution?.signalsHash ?? null; if (input.signalsJson && clientSignalsHash) { const computed = await sha256Hex(input.signalsJson); @@ -106,7 +110,11 @@ export class Captcha { }); } try { - signals = JSON.parse(input.signalsJson); + const parsed: unknown = JSON.parse(input.signalsJson); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + signals = parsed as Signals; + committedSignals = computed === clientSignalsHash; + } } catch { // Keep the parsed signals if the raw JSON is unusable. } @@ -153,19 +161,33 @@ export class Captcha { ? 'challenge' : verdict.recommendation; - return { ...verdict, success, recommendation, token }; + return { + result: { ...verdict, success, recommendation, token }, + verifiedSignals: proofVerified && committedSignals && !!pow.nonce && signals.meta?.challengeNonce === pow.nonce, + }; } /** Invisible-mode scoring — same pipeline, returns a compact result + action. */ async score(input: VerifyInput & { action?: string }): Promise { - const result = await this.verifySubmission(input, false); + return (await this.scoreForSession(input)).result; + } + + /** @internal Return the score and whether the server verified the committed signals. */ + async scoreForSession(input: VerifyInput & { action?: string }): Promise<{ + result: ScoreResult; + verifiedSignals: boolean; + }> { + const { result, verifiedSignals } = await this.verifySubmission(input, false); return { - success: result.success, - score: result.score, - token: result.token, - action: input.action ?? '', - recommendation: result.recommendation, - ...(result.observations ? { observations: result.observations } : {}), + result: { + success: result.success, + score: result.score, + token: result.token, + action: input.action ?? '', + recommendation: result.recommendation, + ...(result.observations ? { observations: result.observations } : {}), + }, + verifiedSignals, }; } diff --git a/packages/webdecoy/src/client-signals.ts b/packages/webdecoy/src/client-signals.ts index 75ce815..1f1e954 100644 --- a/packages/webdecoy/src/client-signals.ts +++ b/packages/webdecoy/src/client-signals.ts @@ -33,8 +33,10 @@ import type { Recommendation } from './detection'; /** The engine's verdict on one browser session. */ export interface ClientVerdict { - /** Session id supplied by the browser widget. */ + /** Identifier used by the store. */ sessionId: string; + /** Scope of a receipt issued by the embedded score endpoint. */ + receipt?: { host: string; siteKey: string; expiresAt: number }; /** 0–1, higher is more bot-like. */ score: number; /** What the engine recommends doing about it. */ @@ -99,30 +101,53 @@ export class MemoryClientSignalStore implements ClientSignalStore { } } -/** The cookie the widget sets, and the header it will also accept. */ +/** Session references supplied by an existing application integration. */ export const CLIENT_SESSION_COOKIE = 'wd_cs'; export const CLIENT_SESSION_HEADER = 'x-wd-session'; -/** Read the browser session id off a request, cookie first then header. */ -export function readClientSession(headers: Record): string | undefined { - const cookie = headers['cookie']; - if (cookie) { - for (const part of cookie.split(';')) { - const eq = part.indexOf('='); - if (eq < 0) continue; - if (part.slice(0, eq).trim() === CLIENT_SESSION_COOKIE) { - const value = part.slice(eq + 1).trim(); - if (value) return value; - } +export const CLIENT_RECEIPT_COOKIE = '__Host-wd_cs'; +export const CLIENT_RECEIPT_PREFIX = 'receipt:'; +export const CLIENT_RECEIPT_TTL_MS = 15 * 60_000; + +/** Normalize the request authority for receipt scope checks. */ +export function getClientSignalHost(headers: Record): string | undefined { + const value = headers.host ?? headers[':authority']; + if (typeof value !== 'string' || value.length > 255 || !/^[a-z0-9.:[\]-]+$/i.test(value)) { + return undefined; + } + try { + return new URL('https://' + value).host || undefined; + } catch { + return undefined; + } +} + +function readCookie(header: string | undefined, name: string): string | undefined { + if (!header) return undefined; + for (const part of header.split(';')) { + const eq = part.indexOf('='); + if (eq >= 0 && part.slice(0, eq).trim() === name) { + return part.slice(eq + 1).trim(); } } - const header = headers[CLIENT_SESSION_HEADER]; - return header || undefined; + return undefined; +} + +/** Read the server receipt or an application-supplied legacy session id. */ +export function readClientSession(headers: Record): string | undefined { + const receipt = readCookie(headers.cookie, CLIENT_RECEIPT_COOKIE); + if (receipt !== undefined) { + return /^[0-9a-f]{48}$/.test(receipt) ? CLIENT_RECEIPT_PREFIX + receipt : undefined; + } + const legacy = readCookie(headers.cookie, CLIENT_SESSION_COOKIE) || headers[CLIENT_SESSION_HEADER]; + return legacy && !legacy.startsWith(CLIENT_RECEIPT_PREFIX) ? legacy : undefined; } export interface ClientSignalConfig { /** Where verdicts are read from. Must be the store `/score` writes to. */ store: ClientSignalStore; + /** Site key expected by this rule when several site keys share a request host. */ + siteKey?: string; /** * Deny at or above this score, 0–1. The engine's own `recommendation` is used * when this is omitted. @@ -143,12 +168,14 @@ export interface ClientSignalConfig { export class ClientSignalRule implements Rule { readonly name = 'client-signals'; private readonly store: ClientSignalStore; + private readonly siteKey?: string; private readonly minScore?: number; private readonly action: 'DENY' | 'THROTTLE'; private readonly dryRun: boolean; constructor(config: ClientSignalConfig) { this.store = config.store; + this.siteKey = config.siteKey; this.minScore = config.minScore; this.action = config.action ?? 'DENY'; this.dryRun = config.dryRun ?? false; @@ -180,7 +207,12 @@ export class ClientSignalRule implements Rule { ? (this.store.get(sessionId) as ClientVerdict | undefined) : (context.prepared?.[this.name] as ClientVerdict | undefined); - if (!verdict) { + const issuedReceipt = sessionId.startsWith(CLIENT_RECEIPT_PREFIX); + const receipt = verdict?.receipt; + const usableReceipt = receipt && Date.now() < receipt.expiresAt + && getClientSignalHost(context.headers) === receipt.host + && (this.siteKey === undefined || this.siteKey === receipt.siteKey); + if (!verdict || verdict.sessionId !== sessionId || ((issuedReceipt || this.siteKey !== undefined) && !usableReceipt)) { return { action: 'ALLOW', rule: this.name, @@ -209,7 +241,7 @@ export class ClientSignalRule implements Rule { metadata: { score: verdict.score, recommendation: verdict.recommendation, - sessionId, + ...(issuedReceipt ? {} : { sessionId }), dryRun: this.dryRun, }, }; diff --git a/packages/webdecoy/src/fetch-guard.ts b/packages/webdecoy/src/fetch-guard.ts index f249e3c..1167fa1 100644 --- a/packages/webdecoy/src/fetch-guard.ts +++ b/packages/webdecoy/src/fetch-guard.ts @@ -158,13 +158,15 @@ export function createFetchGuard(options: FetchGuardOptions = {}): FetchGuard { async check(request: Request, peer?: string): Promise { const url = new URL(request.url); + const headers = headerRecord(request.headers); + if (!headers.host && !headers[':authority']) headers.host = url.host; const metadata: RequestMetadata = { method: request.method, path: url.pathname, ip: resolveIP(request, peer), user_agent: request.headers.get('user-agent') ?? undefined, - headers: headerRecord(request.headers), + headers, query: url.search ? url.search.slice(1) : undefined, timestamp: Date.now(), }; From b6fcefb908faf148f3109362d53d0ed2e43c61a8 Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sun, 22 Nov 2026 22:21:37 -0600 Subject: [PATCH 2/2] Preserve application cookies on Express CAPTCHA responses --- packages/express/src/captcha.test.ts | 36 ++++++++++++++++++++++++++++ packages/express/src/captcha.ts | 5 +++- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 packages/express/src/captcha.test.ts diff --git a/packages/express/src/captcha.test.ts b/packages/express/src/captcha.test.ts new file mode 100644 index 0000000..70b27d8 --- /dev/null +++ b/packages/express/src/captcha.test.ts @@ -0,0 +1,36 @@ +import express from 'express'; +import { AddressInfo } from 'node:net'; +import { webdecoyCaptcha } from './captcha'; + +jest.mock('@webdecoy/node', () => ({ + ...jest.requireActual('@webdecoy/node'), + createCaptchaEndpoints: () => ({ + handle: async () => ({ + status: 200, + headers: { 'set-cookie': '__Host-wd_cs=fixture; Path=/; Secure; HttpOnly' }, + body: { success: true }, + }), + }), +})); + +it('appends the CAPTCHA receipt to cookies set by the application', async () => { + const app = express(); + app.use((_req, res, next) => { + res.setHeader('set-cookie', 'app-session=fixture; Path=/; HttpOnly'); + next(); + }); + app.use(webdecoyCaptcha()); + const server = app.listen(0, '127.0.0.1'); + await new Promise((resolve, reject) => server.once('listening', resolve).once('error', reject)); + try { + const { port } = server.address() as AddressInfo; + const response = await fetch(`http://127.0.0.1:${port}/__webdecoy/score`, { method: 'POST' }); + expect(response.status).toBe(200); + expect(response.headers.getSetCookie()).toEqual([ + 'app-session=fixture; Path=/; HttpOnly', + '__Host-wd_cs=fixture; Path=/; Secure; HttpOnly', + ]); + } finally { + server.close(); + } +}); diff --git a/packages/express/src/captcha.ts b/packages/express/src/captcha.ts index c0be842..5c9c4c7 100644 --- a/packages/express/src/captcha.ts +++ b/packages/express/src/captcha.ts @@ -86,7 +86,10 @@ export function webdecoyCaptcha(options?: ExpressCaptchaOptions): RequestHandler } res.status(result.status); - for (const [k, v] of Object.entries(result.headers)) res.setHeader(k, v); + for (const [name, value] of Object.entries(result.headers)) { + if (name === 'set-cookie') res.append(name, value); + else res.setHeader(name, value); + } res.json(result.body); } }