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
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 29 additions & 12 deletions packages/client/src/invisible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -33,6 +33,8 @@ export class InvisibleSession {
private startTime: number;
private lastScore: (VerifyResponse & { timestamp: number }) | null = null;
private listeners: Listener[] = [];
private challengeRequest: Promise<Challenge> | null = null;
private scoring: Promise<VerifyResponse> | null = null;

constructor(options?: InvisibleOptions) {
this.options = Object.assign(
Expand Down Expand Up @@ -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<void> {
try {
await this.powManager.fetchChallenge(this.options.siteKey);
} catch (e) {
console.warn('PoW challenge fetch failed:', e);
}
}

private _attachListeners(): void {
const handlers: Record<string, EventListener> = {
mousemove: (e) => this.behavioral.recordMouseMove(e as MouseEvent),
Expand Down Expand Up @@ -161,6 +155,17 @@ export class InvisibleSession {
}

async execute(action = ''): Promise<VerifyResponse> {
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<VerifyResponse> {
const elapsed = Date.now() - this.startTime;
if (elapsed < this.options.minCollectionTime) {
await new Promise((r) => setTimeout(r, this.options.minCollectionTime - elapsed));
Expand All @@ -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 },
Expand All @@ -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}`,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
50 changes: 50 additions & 0 deletions packages/client/src/pow.test.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -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();
}
});
36 changes: 36 additions & 0 deletions packages/express/src/captcha.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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();
}
});
5 changes: 4 additions & 1 deletion packages/express/src/captcha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
1 change: 1 addition & 0 deletions packages/nextjs/src/captcha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
79 changes: 75 additions & 4 deletions packages/webdecoy/src/captcha/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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 };
}
}

Expand Down Expand Up @@ -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: {} }));
Expand Down
Loading
Loading