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
20 changes: 18 additions & 2 deletions packages/client/src/collectors/behavioral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ export class BehavioralCollector {
eventDeltas: this.eventDeltas.slice(-50),
eventDeltaVariance,
mouseEventRate,
scrollEvents: this.scrollEvents.length,
...this.analyzeScrolling(),
keyEvents: this.keyEvents.length,
touchEvents: this.touchEvents.length,
focusEvents: this.focusEvents.length,
Expand All @@ -313,6 +313,21 @@ export class BehavioralCollector {
};
}

private analyzeScrolling(): { scrollEvents: number; scrollMorphology?: { samples: number; maxStep: number } } {
const events = this.scrollEvents;
const samples = events.length;
if (samples < 2) return { scrollEvents: samples };

let maxStep = 0;
for (let i = 1; i < samples; i++) {
const previous = events[i - 1];
const current = events[i];
const step = Math.abs(current.x - previous.x) + Math.abs(current.y - previous.y);
maxStep = Math.max(maxStep, step);
}
return { scrollEvents: samples, scrollMorphology: { samples, maxStep } };
}

_analyzeTouchPoints(touches: TouchSample[]): Record<string, unknown> {
if (!touches || touches.length === 0) {
return {
Expand Down Expand Up @@ -581,7 +596,8 @@ export class BehavioralCollector {
avgAcceleration: 0, accelerationChanges: 0, microTremorScore: 0.5,
straightLineRatio: 0, microMovements: 0, directionChanges: 0,
eventDeltas: [], eventDeltaVariance: 0, mouseEventRate: 0,
scrollEvents: this.scrollEvents.length, keyEvents: this.keyEvents.length,
...this.analyzeScrolling(),
keyEvents: this.keyEvents.length,
touchEvents: this.touchEvents.length, focusEvents: this.focusEvents.length,
clickData: this.clickData, interactionDuration: Date.now() - this.startTime,
...this._analyzeTouchPoints(this.touchEvents),
Expand Down
32 changes: 32 additions & 0 deletions packages/client/src/collectors/scroll-morphology.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { BehavioralCollector } from './behavioral';

it('summarizes recent scroll displacement with and without mouse samples', () => {
const collector = new BehavioralCollector();
const scrollX = jest.replaceProperty(window, 'scrollX', 0);
const scrollY = jest.replaceProperty(window, 'scrollY', 0);
try {
collector.recordScroll(new Event('scroll'));
expect(collector.analyze()).not.toHaveProperty('scrollMorphology');

scrollX.replaceValue(20);
scrollY.replaceValue(70);
collector.recordScroll(new Event('scroll'));
scrollY.replaceValue(30);
collector.recordScroll(new Event('scroll'));
expect(collector.analyze()).toMatchObject({
scrollEvents: 3,
scrollMorphology: { samples: 3, maxStep: 90 },
});

for (let i = 0; i < 10; i++) {
collector.recordMouseMove(new MouseEvent('mousemove', { clientX: i }));
}
expect(collector.analyze()).toMatchObject({
totalPoints: 10,
scrollMorphology: { samples: 3, maxStep: 90 },
});
} finally {
scrollX.restore();
scrollY.restore();
}
});
2 changes: 2 additions & 0 deletions packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,8 @@ The SDK also ships an in-process captcha: it scores behavioral, environmental an

Mount the endpoints with your adapter (`webdecoyCaptcha` in Express, `webdecoyCaptchaPlugin` in Fastify, `createCaptchaHandler` in Next.js) or with `createCaptchaEndpoints()`. They serve `GET /__webdecoy/challenge`, `POST /__webdecoy/verify`, `POST /__webdecoy/score` and `POST /__webdecoy/token/verify`.

When the browser provides usable scroll samples, `/verify` and `/score` return an `observations` entry with the ID `large-scroll-step-v1`. It summarizes the sample count and largest step in CSS pixels for diagnostics.

```ts
import express from 'express';
import { webdecoyCaptcha } from '@webdecoy/express';
Expand Down
29 changes: 26 additions & 3 deletions packages/webdecoy/src/captcha/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import { createHash } from 'crypto';
import { MemoryClientSignalStore } from '../client-signals';
import { createCaptchaEndpoints, type CaptchaRequest } from './http';
import type { ChallengeData, PoWSolution } from './types';

Expand Down Expand Up @@ -107,7 +108,8 @@ describe('captcha HTTP endpoints', () => {
});

it.each(['verify', 'score'])('applies route-specific interaction checks on /%s', async (route) => {
const { captcha, handle } = createCaptchaEndpoints({ secret: 's' });
const signalStore = new MemoryClientSignalStore();
const { captcha, handle } = createCaptchaEndpoints({ secret: 's', signalStore });
const ip = '73.15.22.100';
const now = Date.now();
const clock = jest.spyOn(Date, 'now').mockReturnValue(now);
Expand All @@ -123,9 +125,14 @@ describe('captcha HTTP endpoints', () => {
body: {
siteKey: 'site',
action: 'login',
sessionId: 'scroll-session',
powSolution: solve(challenge),
signals: {
behavioral: { ...HUMAN, interactionDuration: 90_000 },
behavioral: {
...HUMAN,
interactionDuration: 90_000,
scrollMorphology: { samples: 3, maxStep: 680 },
},
environmental: ENV,
meta: { challengeNonce: challenge.nonce, invisible: true },
},
Expand All @@ -134,7 +141,17 @@ describe('captcha HTTP endpoints', () => {
);

expect(res?.status).toBe(200);
expect(res?.body).toMatchObject({ success: true, token: expect.any(String) });
expect(res?.body).toMatchObject({
success: true,
token: expect.any(String),
observations: [{
id: 'large-scroll-step-v1',
mode: 'observe',
status: 'detected',
samples: 3,
maxStep: 680,
}],
});
if (route === 'verify') {
expect(res?.body).toMatchObject({
detections: expect.arrayContaining([
Expand All @@ -143,6 +160,12 @@ describe('captcha HTTP endpoints', () => {
});
} else {
expect(res?.body).toMatchObject({ action: 'login', score: 0 });
expect(signalStore.get('scroll-session')).toEqual({
sessionId: 'scroll-session',
score: 0,
recommendation: 'allow',
at: now + 90_000,
});
}
} finally {
clock.mockRestore();
Expand Down
1 change: 1 addition & 0 deletions packages/webdecoy/src/captcha/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ export class Captcha {
token: result.token,
action: input.action ?? '',
recommendation: result.recommendation,
...(result.observations ? { observations: result.observations } : {}),
};
}

Expand Down
1 change: 1 addition & 0 deletions packages/webdecoy/src/captcha/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,5 @@ export interface ScoreResult {
token: string | null;
action: string;
recommendation: Recommendation;
observations?: Verdict['observations'];
}
26 changes: 26 additions & 0 deletions packages/webdecoy/src/detection/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,32 @@ describe('widget and invisible interaction modes', () => {
});
});

describe('observe-only scroll diagnostics', () => {
it.each([
{ maxStep: 80, status: 'clear' },
{ maxStep: 680, status: 'detected' },
])('reports $status for a $maxStep pixel step without folding it into scoring', ({ maxStep, status }) => {
const baseline = score({ behavioral: HUMAN_BEHAVIOR });
const verdict = score({ behavioral: { ...HUMAN_BEHAVIOR, scrollMorphology: { samples: 3, maxStep } } });

expect(verdict).toEqual({
...baseline,
timestamp: verdict.timestamp,
observations: [{ id: 'large-scroll-step-v1', mode: 'observe', status, samples: 3, maxStep }],
});
});

it.each([
{ name: 'a legacy payload', behavioral: HUMAN_BEHAVIOR },
{ name: 'one scroll event', behavioral: { scrollMorphology: { samples: 1, maxStep: 680 } } },
{ name: 'an invalid distance', behavioral: { scrollMorphology: { samples: 3, maxStep: Infinity } } },
{ name: 'keyboard navigation', behavioral: { keyEvents: 2, scrollMorphology: { samples: 3, maxStep: 680 } } },
{ name: 'touch navigation', behavioral: { touchEvents: 1, scrollMorphology: { samples: 3, maxStep: 680 } } },
])('omits the measurement for $name', ({ behavioral }) => {
expect(score({ behavioral })).not.toHaveProperty('observations');
});
});

describe('vision AI detection', () => {
it('detects impossibly fast PoW', () => {
const v = score({ temporal: { pow: { duration: 10, iterations: 100000 } } });
Expand Down
3 changes: 3 additions & 0 deletions packages/webdecoy/src/detection/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import type { Detection, DetectionContext, Signals, Verdict } from './types';
import { DEFAULT_WEIGHTS } from './weights';
import { observeScrollJump } from './scroll-observation';
import { isDatacenterIP } from './ip';
import {
InMemoryFingerprintStore,
Expand Down Expand Up @@ -162,13 +163,15 @@ export class DetectionEngine {
// --- Aggregate -------------------------------------------------------------
const categoryScores = calculateCategoryScores(detections, this.weights);
const score = calculateFinalScore(categoryScores, this.weights);
const scrollObservation = observeScrollJump(signals.behavioral);

return {
success: score < 0.5,
score,
recommendation: recommend(score),
categoryScores,
detections,
...(scrollObservation ? { observations: [scrollObservation] } : {}),
timestamp: Math.floor(Date.now() / 1000),
};
}
Expand Down
1 change: 1 addition & 0 deletions packages/webdecoy/src/detection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export * from './detectors';

export type {
Detection,
ScrollJumpObservation,
CategoryScores,
Recommendation,
Signals,
Expand Down
22 changes: 22 additions & 0 deletions packages/webdecoy/src/detection/scroll-observation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { BehavioralSignals, ScrollJumpObservation } from './types';

const MAX_SCROLL_SAMPLES = 100;
const LARGE_SCROLL_STEP_PX = 400;

/** Measure large steps separately from scoring because many browser actions can move a page. */
export function observeScrollJump(behavioral?: BehavioralSignals): ScrollJumpObservation | undefined {
const { samples, maxStep } = behavioral?.scrollMorphology ?? {};
if (
typeof samples !== 'number' || !Number.isInteger(samples) || samples < 2 || samples > MAX_SCROLL_SAMPLES
|| typeof maxStep !== 'number' || !Number.isFinite(maxStep) || maxStep < 0
|| (behavioral?.keyEvents ?? 0) > 0 || (behavioral?.touchEvents ?? 0) > 0
) return undefined;

return {
id: 'large-scroll-step-v1',
mode: 'observe',
status: maxStep > LARGE_SCROLL_STEP_PX ? 'detected' : 'clear',
samples,
maxStep,
};
}
13 changes: 13 additions & 0 deletions packages/webdecoy/src/detection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export interface BehavioralSignals {
touchEvents?: number;
pointerHasNonMouseType?: boolean;
keyEvents?: number;
/** Count of recent scroll events and largest CSS pixel step between them. */
scrollMorphology?: { samples?: number; maxStep?: number };
microTremorScore?: number;
approachDirectness?: number;
clickPrecision?: number;
Expand Down Expand Up @@ -294,6 +296,15 @@ export interface DetectionContext {
extraDetections?: Detection[];
}

/** A diagnostic based on recent page scroll movement. */
export interface ScrollJumpObservation {
id: 'large-scroll-step-v1';
mode: 'observe';
status: 'detected' | 'clear';
samples: number;
maxStep: number;
}

/** Final verdict returned by {@link DetectionEngine.score}. */
export interface Verdict {
/** True when the weighted score is below the success threshold (< 0.5). */
Expand All @@ -306,6 +317,8 @@ export interface Verdict {
categoryScores: CategoryScores;
/** Every triggered detection. */
detections: Detection[];
/** Scroll diagnostics returned when the browser supplied enough usable evidence. */
observations?: ScrollJumpObservation[];
/** Unix seconds at evaluation time. */
timestamp: number;
}
1 change: 1 addition & 0 deletions packages/webdecoy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ export {
export type {
DetectionEngineOptions,
Detection,
ScrollJumpObservation,
CategoryScores,
Recommendation,
Signals,
Expand Down
Loading