@osqd/bothandlerjs 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +227 -1
- package/README.md +18 -10
- package/dist/adapters/fastify.d.ts +10 -0
- package/dist/adapters/index.cjs +38 -10
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.js +38 -10
- package/dist/adapters/index.js.map +1 -1
- package/dist/challenge/index.d.ts +40 -0
- package/dist/cli.cjs +2256 -103
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2256 -103
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +55 -0
- package/dist/core.d.ts +48 -21
- package/dist/corpus/index.cjs +365 -7
- package/dist/corpus/index.cjs.map +1 -1
- package/dist/corpus/index.js +365 -7
- package/dist/corpus/index.js.map +1 -1
- package/dist/corpus/schema.d.ts +33 -0
- package/dist/crawler-ranges.d.ts +31 -0
- package/dist/dashboard/client/actions.d.ts +1 -1
- package/dist/dashboard/client/app.d.ts +9 -2
- package/dist/dashboard/client/boot.d.ts +32 -3
- package/dist/dashboard/client/query.d.ts +72 -12
- package/dist/dashboard/client/registry.d.ts +25 -0
- package/dist/dashboard/client/saved.d.ts +29 -0
- package/dist/dashboard/client/store.d.ts +16 -2
- package/dist/dashboard/client/types.d.ts +2 -0
- package/dist/dashboard/client.generated.d.ts +1 -1
- package/dist/dashboard/types.d.ts +15 -0
- package/dist/detectors/blended-identity.d.ts +34 -0
- package/dist/detectors/challenge-integrity.d.ts +26 -0
- package/dist/detectors/challenge-reaction.d.ts +39 -0
- package/dist/detectors/clearance.d.ts +1 -23
- package/dist/detectors/id-enumeration.d.ts +31 -0
- package/dist/detectors/index.d.ts +24 -1
- package/dist/detectors/known-bots.d.ts +11 -0
- package/dist/detectors/marker.d.ts +106 -0
- package/dist/detectors/parameter-sweep.d.ts +39 -0
- package/dist/detectors/probe-signature.d.ts +27 -0
- package/dist/detectors/probe-volume.d.ts +26 -0
- package/dist/detectors/site-baseline.d.ts +135 -0
- package/dist/detectors/target-integrity.d.ts +16 -0
- package/dist/detectors/transport-coherence.d.ts +31 -0
- package/dist/detectors/trap.d.ts +10 -3
- package/dist/detectors/types.d.ts +17 -0
- package/dist/element/index.cjs +730 -80
- package/dist/element/index.cjs.map +1 -1
- package/dist/element/index.js +730 -80
- package/dist/element/index.js.map +1 -1
- package/dist/index.cjs +2044 -123
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +2025 -123
- package/dist/index.js.map +1 -1
- package/dist/internal/async.d.ts +0 -3
- package/dist/internal/ip.d.ts +18 -0
- package/dist/internal/text.d.ts +28 -0
- package/dist/metrics.d.ts +18 -0
- package/dist/probe/index.d.ts +153 -0
- package/dist/probe/marker.d.ts +119 -0
- package/dist/site/index.d.ts +122 -0
- package/dist/state.d.ts +205 -0
- package/dist/stores/redis.d.ts +24 -1
- package/dist/types.d.ts +106 -0
- package/docs/course/05-detectors.md +9 -4
- package/docs/course/06-identity.md +1 -1
- package/docs/course/16-proving-it.md +15 -9
- package/docs/course/index.md +1 -1
- package/docs/design/decisions.md +1 -1
- package/docs/detection/correlation.md +284 -0
- package/docs/detection/detectors.md +259 -1
- package/docs/detection/index.md +2 -1
- package/docs/detection/shadow-mode.md +147 -0
- package/docs/detection/signatures.md +10 -2
- package/docs/index.md +3 -2
- package/docs/integration/client-ip.md +16 -0
- package/docs/operations/dashboard.md +40 -1
- package/docs/operations/filters.md +143 -0
- package/docs/operations/index.md +1 -0
- package/docs/operations/metrics.md +18 -0
- package/docs/policy/presets.md +1 -1
- package/docs/start/choosing-a-policy.md +1 -1
- package/docs/start/first-integration.md +1 -1
- package/docs/start/installation.md +2 -2
- package/docs/testing/cli.md +7 -1
- package/docs/testing/corpus.md +12 -8
- package/docs/testing/index.md +1 -1
- package/docs/testing/try-it.md +1 -1
- package/package.json +4 -1
package/dist/cli.js
CHANGED
|
@@ -114,6 +114,45 @@ var init_lru = __esm({
|
|
|
114
114
|
}
|
|
115
115
|
});
|
|
116
116
|
|
|
117
|
+
// src/internal/text.ts
|
|
118
|
+
function safeSummary(text) {
|
|
119
|
+
let flawed = text.length > SUMMARY_CHARS;
|
|
120
|
+
if (!flawed) {
|
|
121
|
+
for (let i = 0; i < text.length; i++) {
|
|
122
|
+
const code = text.charCodeAt(i);
|
|
123
|
+
if (code < 32 || code >= 127 && code <= 159 || code >= 55296 && code <= 57343) {
|
|
124
|
+
flawed = true;
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (!flawed) return text;
|
|
130
|
+
let out = "";
|
|
131
|
+
const limit = Math.min(text.length, SUMMARY_CHARS);
|
|
132
|
+
for (let i = 0; i < limit; i++) {
|
|
133
|
+
const code = text.charCodeAt(i);
|
|
134
|
+
if (code < 32 || code >= 127 && code <= 159) {
|
|
135
|
+
out += "\uFFFD";
|
|
136
|
+
} else if (code >= 55296 && code <= 56319) {
|
|
137
|
+
const next = text.charCodeAt(i + 1);
|
|
138
|
+
if (next >= 56320 && next <= 57343) {
|
|
139
|
+
out += text[i] + text[i + 1];
|
|
140
|
+
i++;
|
|
141
|
+
} else out += "\uFFFD";
|
|
142
|
+
} else if (code >= 56320 && code <= 57343) {
|
|
143
|
+
out += "\uFFFD";
|
|
144
|
+
} else out += text[i];
|
|
145
|
+
}
|
|
146
|
+
return text.length > SUMMARY_CHARS ? `${out}\u2026` : out;
|
|
147
|
+
}
|
|
148
|
+
var SUMMARY_CHARS;
|
|
149
|
+
var init_text = __esm({
|
|
150
|
+
"src/internal/text.ts"() {
|
|
151
|
+
"use strict";
|
|
152
|
+
SUMMARY_CHARS = 512;
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
|
|
117
156
|
// src/state.ts
|
|
118
157
|
function hashString(value) {
|
|
119
158
|
let hash = 2166136261;
|
|
@@ -123,16 +162,50 @@ function hashString(value) {
|
|
|
123
162
|
}
|
|
124
163
|
return hash >>> 0;
|
|
125
164
|
}
|
|
126
|
-
|
|
165
|
+
function walkStepOf(path) {
|
|
166
|
+
if (path.length > MAX_WALK_PATH_CHARS) return void 0;
|
|
167
|
+
let depth = 0;
|
|
168
|
+
for (let i = 0; i < path.length; i++) {
|
|
169
|
+
if (path.charCodeAt(i) === 47 && ++depth > MAX_WALK_SEGMENTS) return void 0;
|
|
170
|
+
}
|
|
171
|
+
let value;
|
|
172
|
+
const parts = [];
|
|
173
|
+
for (const segment of path.split("/")) {
|
|
174
|
+
if (segment === "") continue;
|
|
175
|
+
if (DIGITS.test(segment)) {
|
|
176
|
+
const parsed = Number(segment);
|
|
177
|
+
if (Number.isSafeInteger(parsed) && parsed <= 1e7) value = parsed;
|
|
178
|
+
parts.push("#");
|
|
179
|
+
} else {
|
|
180
|
+
parts.push(segment);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (value === void 0) return void 0;
|
|
184
|
+
let template = `/${parts.join("/")}`;
|
|
185
|
+
if (template.length > TEMPLATE_CHARS) template = `${template.slice(0, TEMPLATE_CHARS)}\u2026`;
|
|
186
|
+
return { template, id: value };
|
|
187
|
+
}
|
|
188
|
+
var TIMESTAMP_RING, PATH_CAP, QUERY_CAP, METHOD_CAP, WALK_CAP, IDENTITY_CAP, TEMPLATE_CHARS, MAX_WALK_SEGMENTS, MAX_WALK_PATH_CHARS, MAX_QUERY_KEYS, DIGITS, UA_CAP, MAX_TRACKED_ARRIVALS, MAX_TRACKED_PATHS, MAX_TRACKED_QUERIES, ActorState, ActorRegistry;
|
|
127
189
|
var init_state = __esm({
|
|
128
190
|
"src/state.ts"() {
|
|
129
191
|
"use strict";
|
|
130
192
|
init_lru();
|
|
193
|
+
init_text();
|
|
131
194
|
TIMESTAMP_RING = 32;
|
|
132
195
|
PATH_CAP = 64;
|
|
196
|
+
QUERY_CAP = 64;
|
|
197
|
+
METHOD_CAP = 12;
|
|
198
|
+
WALK_CAP = 4;
|
|
199
|
+
IDENTITY_CAP = 12;
|
|
200
|
+
TEMPLATE_CHARS = 120;
|
|
201
|
+
MAX_WALK_SEGMENTS = 24;
|
|
202
|
+
MAX_WALK_PATH_CHARS = 512;
|
|
203
|
+
MAX_QUERY_KEYS = 24;
|
|
204
|
+
DIGITS = /^\d+$/;
|
|
133
205
|
UA_CAP = 4;
|
|
134
206
|
MAX_TRACKED_ARRIVALS = TIMESTAMP_RING;
|
|
135
207
|
MAX_TRACKED_PATHS = PATH_CAP;
|
|
208
|
+
MAX_TRACKED_QUERIES = QUERY_CAP;
|
|
136
209
|
ActorState = class {
|
|
137
210
|
key;
|
|
138
211
|
firstSeen;
|
|
@@ -173,6 +246,96 @@ var init_state = __esm({
|
|
|
173
246
|
paths = /* @__PURE__ */ new Set();
|
|
174
247
|
pathsOverflowed = false;
|
|
175
248
|
pathsSaturatedAtTotal = 0;
|
|
249
|
+
/**
|
|
250
|
+
* Distinct *parameterised* requests: the path together with its query.
|
|
251
|
+
*
|
|
252
|
+
* Counted apart from `paths` because the two answer different questions and a scraper
|
|
253
|
+
* lives in the gap between them. `/products?page=1` through `?page=200` is one path and
|
|
254
|
+
* two hundred requests, so breadth reads it as somebody rereading a single page — which
|
|
255
|
+
* is exactly what enumerating a catalogue looks like from the path alone.
|
|
256
|
+
*/
|
|
257
|
+
queries = /* @__PURE__ */ new Set();
|
|
258
|
+
queriesOverflowed = false;
|
|
259
|
+
/**
|
|
260
|
+
* Which HTTP methods this actor has used.
|
|
261
|
+
*
|
|
262
|
+
* A browser navigating issues GET. Something that has issued nothing but HEAD across a
|
|
263
|
+
* long visit is checking what exists rather than reading it, and that is a fact about
|
|
264
|
+
* the actor rather than about any one of its requests — which is why it is kept here.
|
|
265
|
+
*/
|
|
266
|
+
/**
|
|
267
|
+
* What has happened with this actor's marker cookie.
|
|
268
|
+
*
|
|
269
|
+
* Counted rather than listed: the useful questions are all "how often", and a list of
|
|
270
|
+
* marker ids would grow with a client's cookie jar for no benefit. The three drift
|
|
271
|
+
* flags are sticky — once a client has been seen claiming two different browsers under
|
|
272
|
+
* one marker it has done so, and a later request that looks tidy again does not undo
|
|
273
|
+
* it. That is the point of correlating a series rather than judging a request.
|
|
274
|
+
*/
|
|
275
|
+
/**
|
|
276
|
+
* When this actor was last challenged, and how it described itself at that moment.
|
|
277
|
+
*
|
|
278
|
+
* Kept so that what a client does *in response* to being challenged can be read. That
|
|
279
|
+
* reaction is better evidence than anything observed passively, because the stimulus
|
|
280
|
+
* was ours: we chose the moment, so a change of identity that follows it within
|
|
281
|
+
* seconds is a reaction to it rather than a coincidence we went looking for.
|
|
282
|
+
*/
|
|
283
|
+
/**
|
|
284
|
+
* Answers to challenges that were valid in form but wrong in a way only the series
|
|
285
|
+
* shows: a solution already spent, or one returned faster than the puzzle allows.
|
|
286
|
+
*/
|
|
287
|
+
/** Requests for a path no other client had ever asked this site for. */
|
|
288
|
+
novelPaths = 0;
|
|
289
|
+
replayedSolutions = 0;
|
|
290
|
+
implausibleSolves = 0;
|
|
291
|
+
challengedAt = 0;
|
|
292
|
+
challengeShape;
|
|
293
|
+
markerIssues = 0;
|
|
294
|
+
markerReturns = 0;
|
|
295
|
+
markerForgeries = 0;
|
|
296
|
+
driftSeen = { browser: false, platform: false, language: false };
|
|
297
|
+
driftEvents = 0;
|
|
298
|
+
methods = /* @__PURE__ */ new Set();
|
|
299
|
+
/**
|
|
300
|
+
* Numeric walks in progress, by path shape: `/user/#` against the ids requested under it.
|
|
301
|
+
*
|
|
302
|
+
* Three numbers per shape, deliberately — a count, a lowest and a highest — rather than
|
|
303
|
+
* the ids themselves. What separates enumeration from reading is not which ids were
|
|
304
|
+
* asked for but whether they *cover a range*: thirty requests spanning thirty
|
|
305
|
+
* consecutive ids is a walk, and thirty scattered across a hundred thousand is somebody
|
|
306
|
+
* following links. Both are answerable from a count and a span, and only the count and
|
|
307
|
+
* the span survive an actor asking for ten thousand of them.
|
|
308
|
+
*/
|
|
309
|
+
walks = /* @__PURE__ */ new Map();
|
|
310
|
+
/**
|
|
311
|
+
* Every named identity this actor has claimed, and what kind each was.
|
|
312
|
+
*
|
|
313
|
+
* Kept because the interesting question is not what one request said but what the *set*
|
|
314
|
+
* of them says. One address claiming sqlmap and nikto is a scan; one claiming Googlebot
|
|
315
|
+
* and Bingbot is a forgery, since at most one of those can be true of an address. Neither
|
|
316
|
+
* observation exists inside a single request.
|
|
317
|
+
*/
|
|
318
|
+
identities = /* @__PURE__ */ new Map();
|
|
319
|
+
/**
|
|
320
|
+
* A name somebody gave this actor.
|
|
321
|
+
*
|
|
322
|
+
* Nothing in detection reads it. It exists because an address is not a memory: the
|
|
323
|
+
* person who worked out that `198.51.100.4` is the partner's price feed should be able
|
|
324
|
+
* to write that down where the next person will see it, rather than in a ticket.
|
|
325
|
+
*/
|
|
326
|
+
actorLabel;
|
|
327
|
+
/** Requests from this actor that carried a scanner payload or target. */
|
|
328
|
+
probePayloads = 0;
|
|
329
|
+
/**
|
|
330
|
+
* What the application answered, for the requests anybody bothered to tell us about.
|
|
331
|
+
*
|
|
332
|
+
* The engine decides *before* the response exists, so this arrives afterwards and only
|
|
333
|
+
* when the adapter reports it. Kept as two counters rather than a list because the one
|
|
334
|
+
* question worth asking is a ratio: an actor whose requests are almost all misses is
|
|
335
|
+
* looking for something rather than reading anything.
|
|
336
|
+
*/
|
|
337
|
+
responsesSeen = 0;
|
|
338
|
+
missesSeen = 0;
|
|
176
339
|
userAgents = /* @__PURE__ */ new Set();
|
|
177
340
|
constructor(key, now) {
|
|
178
341
|
this.key = key;
|
|
@@ -192,6 +355,16 @@ var init_state = __esm({
|
|
|
192
355
|
this.pathsOverflowed = true;
|
|
193
356
|
this.pathsSaturatedAtTotal = this.total;
|
|
194
357
|
}
|
|
358
|
+
const keys = Object.keys(facts.query);
|
|
359
|
+
if (keys.length > 0 && keys.length <= MAX_QUERY_KEYS) {
|
|
360
|
+
keys.sort();
|
|
361
|
+
const signature = `${facts.path}?${keys.map((key) => `${key}=${facts.query[key] ?? ""}`).join("&")}`;
|
|
362
|
+
const queryHash = hashString(signature);
|
|
363
|
+
if (this.queries.size < QUERY_CAP) this.queries.add(queryHash);
|
|
364
|
+
else if (!this.queries.has(queryHash)) this.queriesOverflowed = true;
|
|
365
|
+
}
|
|
366
|
+
if (this.methods.size < METHOD_CAP) this.methods.add(facts.method);
|
|
367
|
+
this.noteWalk(facts.path);
|
|
195
368
|
const ua = facts.headers["user-agent"];
|
|
196
369
|
if (ua !== void 0 && this.userAgents.size < UA_CAP) this.userAgents.add(ua);
|
|
197
370
|
}
|
|
@@ -202,6 +375,145 @@ var init_state = __esm({
|
|
|
202
375
|
get pathsSaturated() {
|
|
203
376
|
return this.pathsOverflowed;
|
|
204
377
|
}
|
|
378
|
+
/** Distinct path-and-query combinations seen. Saturates at {@link QUERY_CAP}. */
|
|
379
|
+
get distinctQueries() {
|
|
380
|
+
return this.queries.size;
|
|
381
|
+
}
|
|
382
|
+
get queriesSaturated() {
|
|
383
|
+
return this.queriesOverflowed;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Records what the application answered. Called after the response, if at all.
|
|
387
|
+
*
|
|
388
|
+
* 404 and 410 only. A 403 is usually this library's own doing and counting it would
|
|
389
|
+
* make the detector that reads this argue with itself; a 500 is the site's problem and
|
|
390
|
+
* says nothing about the client.
|
|
391
|
+
*/
|
|
392
|
+
recordOutcome(status) {
|
|
393
|
+
this.responsesSeen++;
|
|
394
|
+
if (status === 404 || status === 410) this.missesSeen++;
|
|
395
|
+
}
|
|
396
|
+
/** Responses reported for this actor. Zero unless something is reporting them. */
|
|
397
|
+
get responses() {
|
|
398
|
+
return this.responsesSeen;
|
|
399
|
+
}
|
|
400
|
+
/** Of those, how many were 404 or 410. */
|
|
401
|
+
get misses() {
|
|
402
|
+
return this.missesSeen;
|
|
403
|
+
}
|
|
404
|
+
/** Names this actor, or clears the name when given nothing. Trimmed and bounded. */
|
|
405
|
+
setLabel(label) {
|
|
406
|
+
const trimmed = label === void 0 ? void 0 : safeSummary(label).trim().slice(0, 120);
|
|
407
|
+
this.actorLabel = trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
|
|
408
|
+
}
|
|
409
|
+
get label() {
|
|
410
|
+
return this.actorLabel;
|
|
411
|
+
}
|
|
412
|
+
/** Records a named identity this actor claimed. Called once per matching signature. */
|
|
413
|
+
noteIdentity(id, category, verifiable) {
|
|
414
|
+
if (this.identities.has(id) || this.identities.size >= IDENTITY_CAP) return;
|
|
415
|
+
this.identities.set(id, { category, verifiable });
|
|
416
|
+
}
|
|
417
|
+
/** Records that this request was for a path the site had never served to anybody. */
|
|
418
|
+
noteNovelPath() {
|
|
419
|
+
if (this.novelPaths < 1e6) this.novelPaths++;
|
|
420
|
+
}
|
|
421
|
+
/** How many of this actor's requests were for a path nobody else had ever asked for. */
|
|
422
|
+
get novelPathCount() {
|
|
423
|
+
return this.novelPaths;
|
|
424
|
+
}
|
|
425
|
+
/** Records something wrong with a submitted solution that only its history reveals. */
|
|
426
|
+
noteChallengeAnomaly(kind) {
|
|
427
|
+
if (kind === "replay") {
|
|
428
|
+
if (this.replayedSolutions < 1e6) this.replayedSolutions++;
|
|
429
|
+
} else if (this.implausibleSolves < 1e6) this.implausibleSolves++;
|
|
430
|
+
}
|
|
431
|
+
/** Solutions this actor submitted that had already been spent, and ones returned too fast. */
|
|
432
|
+
get challengeAnomalies() {
|
|
433
|
+
return { replays: this.replayedSolutions, implausible: this.implausibleSolves };
|
|
434
|
+
}
|
|
435
|
+
/** Records that a challenge went out, and the identity claimed as it did. */
|
|
436
|
+
noteChallengeIssued(at, shape) {
|
|
437
|
+
this.challengedAt = at;
|
|
438
|
+
this.challengeShape = shape;
|
|
439
|
+
}
|
|
440
|
+
/** The moment of the last challenge, and the identity claimed then. `at` is 0 for none. */
|
|
441
|
+
get lastChallenge() {
|
|
442
|
+
return { at: this.challengedAt, shape: this.challengeShape };
|
|
443
|
+
}
|
|
444
|
+
/** Records that a marker was handed to this actor on the way out. */
|
|
445
|
+
noteMarkerIssued() {
|
|
446
|
+
if (this.markerIssues < 1e6) this.markerIssues++;
|
|
447
|
+
}
|
|
448
|
+
/** Records what this request's marker cookie turned out to be. */
|
|
449
|
+
noteMarker(returned, forged, drift) {
|
|
450
|
+
if (returned && this.markerReturns < 1e6) this.markerReturns++;
|
|
451
|
+
if (forged && this.markerForgeries < 1e6) this.markerForgeries++;
|
|
452
|
+
if (drift === void 0) return;
|
|
453
|
+
if (drift.browser || drift.platform || drift.language) {
|
|
454
|
+
if (this.driftEvents < 1e6) this.driftEvents++;
|
|
455
|
+
}
|
|
456
|
+
this.driftSeen.browser ||= drift.browser;
|
|
457
|
+
this.driftSeen.platform ||= drift.platform;
|
|
458
|
+
this.driftSeen.language ||= drift.language;
|
|
459
|
+
}
|
|
460
|
+
/** Markers handed to this actor, and how many came back. */
|
|
461
|
+
get markers() {
|
|
462
|
+
return { issued: this.markerIssues, returned: this.markerReturns, forged: this.markerForgeries };
|
|
463
|
+
}
|
|
464
|
+
/** Which parts of a claimed identity have ever changed under one marker. */
|
|
465
|
+
get identityDrift() {
|
|
466
|
+
return { ...this.driftSeen, events: this.driftEvents };
|
|
467
|
+
}
|
|
468
|
+
/** Records that this request carried a scanner payload, so later requests can know. */
|
|
469
|
+
notePayloadProbe() {
|
|
470
|
+
this.probePayloads++;
|
|
471
|
+
}
|
|
472
|
+
/** Every identity claimed so far, by id. */
|
|
473
|
+
get claimedIdentities() {
|
|
474
|
+
return this.identities;
|
|
475
|
+
}
|
|
476
|
+
/** How many of this actor's requests carried a scanner payload or target. */
|
|
477
|
+
get payloadProbes() {
|
|
478
|
+
return this.probePayloads;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Files a request under the shape of its path, if that path carries a number.
|
|
482
|
+
*
|
|
483
|
+
* The last numeric segment is the one taken to be the identifier: in `/api/v2/orders/42`
|
|
484
|
+
* the version is part of the shape and the order id is what is being walked.
|
|
485
|
+
*/
|
|
486
|
+
noteWalk(path) {
|
|
487
|
+
const step = walkStepOf(path);
|
|
488
|
+
if (step === void 0) return;
|
|
489
|
+
const { template, id: value } = step;
|
|
490
|
+
const existing = this.walks.get(template);
|
|
491
|
+
if (existing !== void 0) {
|
|
492
|
+
existing.count++;
|
|
493
|
+
if (value < existing.min) existing.min = value;
|
|
494
|
+
if (value > existing.max) existing.max = value;
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (this.walks.size < WALK_CAP) this.walks.set(template, { count: 1, min: value, max: value });
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* The path shape this actor has walked hardest, with how far it reached.
|
|
501
|
+
*
|
|
502
|
+
* `span` is inclusive of both ends, so a walk of 1 to 30 spans 30. Comparing the count
|
|
503
|
+
* against it is what separates covering a range from visiting a few points in one.
|
|
504
|
+
*/
|
|
505
|
+
densestWalk() {
|
|
506
|
+
let best;
|
|
507
|
+
for (const [template, walk] of this.walks) {
|
|
508
|
+
const span = walk.max - walk.min + 1;
|
|
509
|
+
if (best === void 0 || walk.count > best.count) best = { template, count: walk.count, span };
|
|
510
|
+
}
|
|
511
|
+
return best;
|
|
512
|
+
}
|
|
513
|
+
/** Every HTTP method this actor has used, in first-seen order. */
|
|
514
|
+
get methodsSeen() {
|
|
515
|
+
return [...this.methods];
|
|
516
|
+
}
|
|
205
517
|
/**
|
|
206
518
|
* Requests seen when {@link distinctPaths} stopped being able to grow, or 0 if it
|
|
207
519
|
* still can. Over that many requests the distinct count is exact, so it is the only
|
|
@@ -290,6 +602,13 @@ var init_state = __esm({
|
|
|
290
602
|
key: this.key,
|
|
291
603
|
requests: this.total,
|
|
292
604
|
distinctPaths: this.distinctPaths,
|
|
605
|
+
distinctQueries: this.distinctQueries,
|
|
606
|
+
methodsSeen: this.methodsSeen,
|
|
607
|
+
...this.actorLabel === void 0 ? {} : { label: this.actorLabel },
|
|
608
|
+
walk: this.densestWalk(),
|
|
609
|
+
responses: this.responses,
|
|
610
|
+
misses: this.misses,
|
|
611
|
+
queriesSaturated: this.queriesSaturated,
|
|
293
612
|
firstSeen: this.firstSeen,
|
|
294
613
|
lastSeen: this.lastSeen,
|
|
295
614
|
sinceLastMs: this.sinceLast(now),
|
|
@@ -636,6 +955,12 @@ function renderChallengePage(options) {
|
|
|
636
955
|
<meta charset="utf-8">
|
|
637
956
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
638
957
|
<meta name="robots" content="noindex, nofollow">
|
|
958
|
+
<!-- An empty icon, so the browser does not go looking for /favicon.ico on its own. It
|
|
959
|
+
is the browser that makes that request rather than this page, and under
|
|
960
|
+
default-src 'none' it is refused \u2014 which Firefox reports to the console as a
|
|
961
|
+
security error on a page whose entire purpose is to reassure somebody that nothing
|
|
962
|
+
is wrong. Declaring one stops the request being made at all. -->
|
|
963
|
+
<link rel="icon" href="data:,">
|
|
639
964
|
<title>${title}</title>
|
|
640
965
|
<style>
|
|
641
966
|
:root { color-scheme: light dark; --fg: #16181d; --muted: #5b6270; --bg: #fbfbfc; --line: #e2e5ea; --accent: #2f6feb; }
|
|
@@ -826,8 +1151,8 @@ function parseAcceptLanguage(header) {
|
|
|
826
1151
|
if (header === void 0 || header.trim() === "") return [];
|
|
827
1152
|
const entries = [];
|
|
828
1153
|
const parts = header.split(",").slice(0, MAX_TAGS);
|
|
829
|
-
parts.forEach((
|
|
830
|
-
const [rawTag, ...parameters] =
|
|
1154
|
+
parts.forEach((part2, order) => {
|
|
1155
|
+
const [rawTag, ...parameters] = part2.trim().split(";");
|
|
831
1156
|
const tag = (rawTag ?? "").trim().toLowerCase();
|
|
832
1157
|
if (tag === "" || tag === "*" || !/^[a-z]{1,8}(-[a-z\d]{1,8})*$/.test(tag)) return;
|
|
833
1158
|
let q = 1;
|
|
@@ -1008,7 +1333,14 @@ function analyseMovement(path) {
|
|
|
1008
1333
|
timingVariation: coefficientOfVariation(gaps),
|
|
1009
1334
|
accelerationChanges,
|
|
1010
1335
|
straightness: pathLength === 0 ? 1 : Math.min(1, Math.hypot(netX, netY) / pathLength),
|
|
1011
|
-
|
|
1336
|
+
// Over the samples this actually looked at, not over everything that arrived. The
|
|
1337
|
+
// two differ by however many discontinuities were dropped above, and using the raw
|
|
1338
|
+
// count meant a path with pauses in it reported a *lower* fractional share than the
|
|
1339
|
+
// samples it was computed from — which reads as "these coordinates are integers"
|
|
1340
|
+
// when what happened is that most of them were never examined. It costs the people
|
|
1341
|
+
// most likely to have pauses: somebody who moved the pointer, stopped to read, and
|
|
1342
|
+
// moved again.
|
|
1343
|
+
fractionalShare: distances.length === 0 ? 0 : fractional / distances.length,
|
|
1012
1344
|
totalTurning
|
|
1013
1345
|
};
|
|
1014
1346
|
}
|
|
@@ -1103,9 +1435,10 @@ function verifyInteraction(report2, elapsedMs, settings = DEFAULT_INTERACTION_SE
|
|
|
1103
1435
|
const failed = Object.keys(CAPABILITY_WEIGHTS).filter((name) => report2.capabilities[name] !== true);
|
|
1104
1436
|
notes.push(failed.length === 0 ? "capabilities 100%" : `capabilities ${(capabilityScore * 100).toFixed(0)}% (missing: ${failed.join(", ")})`);
|
|
1105
1437
|
let score = capabilityScore * 0.6;
|
|
1106
|
-
const
|
|
1438
|
+
const analysis = analyseMovement(report2.path);
|
|
1439
|
+
const measurable = report2.via === "pointer" && analysis.samples >= 4;
|
|
1107
1440
|
if (measurable) {
|
|
1108
|
-
const movement = scoreMovement(
|
|
1441
|
+
const movement = scoreMovement(analysis);
|
|
1109
1442
|
notes.push(`movement ${(movement * 100).toFixed(0)}%`);
|
|
1110
1443
|
score += movement * 0.4;
|
|
1111
1444
|
} else {
|
|
@@ -1204,7 +1537,7 @@ var init_http = __esm({
|
|
|
1204
1537
|
});
|
|
1205
1538
|
|
|
1206
1539
|
// src/challenge/index.ts
|
|
1207
|
-
var ChallengeService;
|
|
1540
|
+
var IMPLAUSIBLE_HASHES_PER_MS, MAX_TRACKED_TOKENS, MAX_BEARERS, ChallengeService;
|
|
1208
1541
|
var init_challenge = __esm({
|
|
1209
1542
|
"src/challenge/index.ts"() {
|
|
1210
1543
|
"use strict";
|
|
@@ -1215,7 +1548,11 @@ var init_challenge = __esm({
|
|
|
1215
1548
|
init_interaction();
|
|
1216
1549
|
init_http();
|
|
1217
1550
|
init_crypto();
|
|
1551
|
+
init_lru();
|
|
1218
1552
|
init_clock();
|
|
1553
|
+
IMPLAUSIBLE_HASHES_PER_MS = 2e4;
|
|
1554
|
+
MAX_TRACKED_TOKENS = 2e4;
|
|
1555
|
+
MAX_BEARERS = 64;
|
|
1219
1556
|
ChallengeService = class {
|
|
1220
1557
|
constructor(options) {
|
|
1221
1558
|
this.options = options;
|
|
@@ -1231,11 +1568,14 @@ var init_challenge = __esm({
|
|
|
1231
1568
|
this.verifyPath = options.verifyPath ?? "/__bothandler/verify";
|
|
1232
1569
|
this.cookieName = options.cookieName ?? "__bh_clearance";
|
|
1233
1570
|
this.clock = options.clock ?? systemClock;
|
|
1571
|
+
this.bearers = new TtlLru(MAX_TRACKED_TOKENS, this.clearanceTtlMs, this.clock);
|
|
1234
1572
|
this.store = options.store;
|
|
1235
1573
|
this.interaction = !wantsGesture ? void 0 : { ...DEFAULT_INTERACTION_SETTINGS, ...options.interaction === true ? {} : options.interaction };
|
|
1236
1574
|
}
|
|
1237
1575
|
options;
|
|
1238
1576
|
secrets;
|
|
1577
|
+
/** Clearance token id to the actors that have presented it. Bounded both ways. */
|
|
1578
|
+
bearers;
|
|
1239
1579
|
difficulty;
|
|
1240
1580
|
challengeTtlMs;
|
|
1241
1581
|
clock;
|
|
@@ -1318,7 +1658,11 @@ var init_challenge = __esm({
|
|
|
1318
1658
|
"cache-control": "no-store, private",
|
|
1319
1659
|
// The page carries one inline script and nothing else. Locking the policy
|
|
1320
1660
|
// this far down means the interstitial cannot be turned into a fetch primitive.
|
|
1321
|
-
|
|
1661
|
+
// `img-src data:` permits nothing off this machine — a data: URI is inline by
|
|
1662
|
+
// definition — and exists only so the empty icon the page declares is honoured.
|
|
1663
|
+
// Without it the browser asks for /favicon.ico by itself and is refused, which
|
|
1664
|
+
// Firefox prints as a security error in the console of every person challenged.
|
|
1665
|
+
"content-security-policy": `default-src 'none'; script-src 'nonce-${rendered.scriptNonce}'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
|
|
1322
1666
|
"referrer-policy": "no-referrer",
|
|
1323
1667
|
"x-content-type-options": "nosniff",
|
|
1324
1668
|
"x-robots-tag": "noindex, nofollow"
|
|
@@ -1363,6 +1707,11 @@ var init_challenge = __esm({
|
|
|
1363
1707
|
interactionScore = outcome.score;
|
|
1364
1708
|
notes = outcome.notes;
|
|
1365
1709
|
}
|
|
1710
|
+
const elapsedSinceIssue = this.clock.now() - verified.payload.iat;
|
|
1711
|
+
const floorMs = 2 ** verified.payload.diff / IMPLAUSIBLE_HASHES_PER_MS | 0;
|
|
1712
|
+
if (elapsedSinceIssue >= 0 && elapsedSinceIssue < floorMs) {
|
|
1713
|
+
return { ok: false, status: 400, reason: "solution returned faster than the puzzle allows", signal: "implausible-speed" };
|
|
1714
|
+
}
|
|
1366
1715
|
if (this.store) {
|
|
1367
1716
|
let claimed;
|
|
1368
1717
|
try {
|
|
@@ -1370,7 +1719,7 @@ var init_challenge = __esm({
|
|
|
1370
1719
|
} catch {
|
|
1371
1720
|
claimed = true;
|
|
1372
1721
|
}
|
|
1373
|
-
if (!claimed) return { ok: false, status: 409, reason: "challenge already solved" };
|
|
1722
|
+
if (!claimed) return { ok: false, status: 409, reason: "challenge already solved", signal: "replay" };
|
|
1374
1723
|
}
|
|
1375
1724
|
return {
|
|
1376
1725
|
ok: true,
|
|
@@ -1400,10 +1749,55 @@ var init_challenge = __esm({
|
|
|
1400
1749
|
}
|
|
1401
1750
|
/** Reads and validates the clearance cookie for an actor. Returns `undefined` if there is none valid. */
|
|
1402
1751
|
read(actorKey, cookies) {
|
|
1752
|
+
const inspected = this.inspect(actorKey, cookies);
|
|
1753
|
+
return inspected.claims;
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Reads a clearance token and says what became of it.
|
|
1757
|
+
*
|
|
1758
|
+
* `read` answers the only question the clearance detector used to ask — is this client
|
|
1759
|
+
* cleared — and throws away the reason when the answer is no. One of those reasons is
|
|
1760
|
+
* worth keeping: a token whose *signature* is ours but whose subject is somebody
|
|
1761
|
+
* else's has been moved between clients. Usually that is innocent and extremely
|
|
1762
|
+
* common, because the subject is derived from the address and a phone changing
|
|
1763
|
+
* networks changes its address. It stops being innocent when one token turns up under
|
|
1764
|
+
* a great many different actors, which is a token being handed around.
|
|
1765
|
+
*/
|
|
1766
|
+
inspect(actorKey, cookies) {
|
|
1403
1767
|
const token = cookies?.[this.cookieName];
|
|
1404
|
-
if (token === void 0) return
|
|
1405
|
-
const
|
|
1406
|
-
|
|
1768
|
+
if (token === void 0) return { presentedBy: 0 };
|
|
1769
|
+
const now = this.clock.now();
|
|
1770
|
+
const verified = verifyToken(token, this.secrets, now, this.subjectsFor(actorKey));
|
|
1771
|
+
if (verified.ok) return { claims: verified.payload, presentedBy: this.noteBearer(verified.payload.jti, actorKey) };
|
|
1772
|
+
if (verified.reason !== "wrong-actor") return { presentedBy: 0 };
|
|
1773
|
+
const claims = this.claimsOf(token);
|
|
1774
|
+
return claims === void 0 ? { presentedBy: 0 } : { boundElsewhere: true, presentedBy: this.noteBearer(claims.jti, actorKey) };
|
|
1775
|
+
}
|
|
1776
|
+
/** The claims inside a token whose signature has already been checked. */
|
|
1777
|
+
claimsOf(token) {
|
|
1778
|
+
const separator = token.lastIndexOf(".");
|
|
1779
|
+
if (separator <= 0) return void 0;
|
|
1780
|
+
try {
|
|
1781
|
+
const claims = JSON.parse(base64UrlDecode(token.slice(0, separator)).toString("utf8"));
|
|
1782
|
+
return typeof claims?.jti === "string" ? claims : void 0;
|
|
1783
|
+
} catch {
|
|
1784
|
+
return void 0;
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* Files this presentation under the token's own id, returning how many distinct actors
|
|
1789
|
+
* have now presented it. Bounded in both directions, and in process for the reason
|
|
1790
|
+
* given in `state.ts`: a store round trip per request buys precision nobody asked for.
|
|
1791
|
+
*/
|
|
1792
|
+
noteBearer(jti, actorKey) {
|
|
1793
|
+
if (this.bearers === void 0) return 0;
|
|
1794
|
+
let seen = this.bearers.get(jti);
|
|
1795
|
+
if (seen === void 0) {
|
|
1796
|
+
seen = /* @__PURE__ */ new Set();
|
|
1797
|
+
this.bearers.set(jti, seen);
|
|
1798
|
+
}
|
|
1799
|
+
if (seen.size < MAX_BEARERS) seen.add(actorKey);
|
|
1800
|
+
return seen.size;
|
|
1407
1801
|
}
|
|
1408
1802
|
/** A `Set-Cookie` that removes any clearance. Call it on logout. */
|
|
1409
1803
|
revoke() {
|
|
@@ -1576,6 +1970,11 @@ function toPrometheus(snapshot, options = {}) {
|
|
|
1576
1970
|
counter("downgrades_total", "Terminal actions the safety guard replaced for lack of proof.", [["", snapshot.downgrades]]);
|
|
1577
1971
|
counter("proven_total", "Assessments resting on proven evidence.", [["", snapshot.proven]]);
|
|
1578
1972
|
counter("detector_firings_total", "Evidence produced, by detector.", Object.entries(snapshot.detectorFirings).map(([detector, value]) => [`{detector="${escapeLabel(detector)}"}`, value]));
|
|
1973
|
+
const shadowFirings = Object.entries(snapshot.shadowFirings);
|
|
1974
|
+
if (shadowFirings.length > 0) {
|
|
1975
|
+
counter("shadow_firings_total", "Evidence produced by shadowed detectors, which decided nothing.", shadowFirings.map(([detector, value]) => [`{detector="${escapeLabel(detector)}"}`, value]));
|
|
1976
|
+
counter("shadow_verdict_changes_total", "Assessments the shadowed detectors would have moved, by the verdict they would have produced.", Object.entries(snapshot.shadowChanges).map(([verdict, value]) => [`{verdict="${verdict}"}`, value]));
|
|
1977
|
+
}
|
|
1579
1978
|
counter("detector_failures_total", "Detector errors and timeouts.", Object.entries(snapshot.detectorFailures).map(([detector, value]) => [`{detector="${escapeLabel(detector)}"}`, value]));
|
|
1580
1979
|
const timings = Object.entries(snapshot.detectorTimings);
|
|
1581
1980
|
if (timings.length > 0) {
|
|
@@ -1643,6 +2042,8 @@ var init_metrics = __esm({
|
|
|
1643
2042
|
detectorFirings = /* @__PURE__ */ new Map();
|
|
1644
2043
|
detectorFailures = /* @__PURE__ */ new Map();
|
|
1645
2044
|
detectorTimings = /* @__PURE__ */ new Map();
|
|
2045
|
+
shadowFirings = /* @__PURE__ */ new Map();
|
|
2046
|
+
shadowChanges = zeroed(VERDICTS);
|
|
1646
2047
|
challengesIssued = 0;
|
|
1647
2048
|
challengesSolved = 0;
|
|
1648
2049
|
challengesRejected = 0;
|
|
@@ -1676,6 +2077,10 @@ var init_metrics = __esm({
|
|
|
1676
2077
|
}
|
|
1677
2078
|
for (const item of assessment.evidence) bump(this.detectorFirings, item.detector);
|
|
1678
2079
|
for (const item of assessment.humanEvidence) bump(this.detectorFirings, item.detector);
|
|
2080
|
+
for (const item of assessment.shadowEvidence) bump(this.shadowFirings, item.detector);
|
|
2081
|
+
if (assessment.shadowVerdict !== void 0 && assessment.shadowVerdict.verdict !== assessment.verdict) {
|
|
2082
|
+
this.shadowChanges[assessment.shadowVerdict.verdict]++;
|
|
2083
|
+
}
|
|
1679
2084
|
for (const failure of assessment.failures) bump(this.detectorFailures, failure.detector);
|
|
1680
2085
|
const ms = assessment.durationMs;
|
|
1681
2086
|
this.durationCount++;
|
|
@@ -1742,6 +2147,8 @@ var init_metrics = __esm({
|
|
|
1742
2147
|
detectorFirings: Object.fromEntries(this.detectorFirings),
|
|
1743
2148
|
detectorFailures: Object.fromEntries(this.detectorFailures),
|
|
1744
2149
|
detectorTimings: Object.fromEntries([...this.detectorTimings].map(([id, timing]) => [id, { ...timing }])),
|
|
2150
|
+
shadowFirings: Object.fromEntries(this.shadowFirings),
|
|
2151
|
+
shadowChanges: { ...this.shadowChanges },
|
|
1745
2152
|
challenges: { issued: this.challengesIssued, solved: this.challengesSolved, rejected: this.challengesRejected },
|
|
1746
2153
|
clearances: Object.fromEntries(this.clearances),
|
|
1747
2154
|
challengeRejections: Object.fromEntries(this.challengeRejections),
|
|
@@ -2083,8 +2490,21 @@ __export(ip_exports, {
|
|
|
2083
2490
|
networkKey: () => networkKey,
|
|
2084
2491
|
normalizeIp: () => normalizeIp,
|
|
2085
2492
|
parseCidr: () => parseCidr,
|
|
2086
|
-
parseIp: () => parseIp
|
|
2493
|
+
parseIp: () => parseIp,
|
|
2494
|
+
stripPort: () => stripPort
|
|
2087
2495
|
});
|
|
2496
|
+
function stripPort(value) {
|
|
2497
|
+
const input = value.trim();
|
|
2498
|
+
if (input.startsWith("[")) {
|
|
2499
|
+
const close = input.indexOf("]");
|
|
2500
|
+
if (close > 0) return input.slice(1, close);
|
|
2501
|
+
return input;
|
|
2502
|
+
}
|
|
2503
|
+
const colon = input.indexOf(":");
|
|
2504
|
+
if (colon === -1 || input.indexOf(":", colon + 1) !== -1) return input;
|
|
2505
|
+
const host = input.slice(0, colon);
|
|
2506
|
+
return parseIpv4(host) !== null ? host : input;
|
|
2507
|
+
}
|
|
2088
2508
|
function parseIp(value) {
|
|
2089
2509
|
const input = value.trim();
|
|
2090
2510
|
if (input.length === 0 || input.length > 45) return null;
|
|
@@ -2097,11 +2517,11 @@ function parseIpv4(value) {
|
|
|
2097
2517
|
if (parts.length !== 4) return null;
|
|
2098
2518
|
const bytes = new Uint8Array(4);
|
|
2099
2519
|
for (let i = 0; i < 4; i++) {
|
|
2100
|
-
const
|
|
2101
|
-
if (
|
|
2102
|
-
if (!/^\d+$/.test(
|
|
2103
|
-
if (
|
|
2104
|
-
const n = Number(
|
|
2520
|
+
const part2 = parts[i];
|
|
2521
|
+
if (part2.length === 0 || part2.length > 3) return null;
|
|
2522
|
+
if (!/^\d+$/.test(part2)) return null;
|
|
2523
|
+
if (part2.length > 1 && part2[0] === "0") return null;
|
|
2524
|
+
const n = Number(part2);
|
|
2105
2525
|
if (n > 255) return null;
|
|
2106
2526
|
bytes[i] = n;
|
|
2107
2527
|
}
|
|
@@ -2368,9 +2788,13 @@ function redactAssessment(assessment, options) {
|
|
|
2368
2788
|
removed,
|
|
2369
2789
|
assessment: {
|
|
2370
2790
|
...assessment,
|
|
2791
|
+
...assessment.marker === void 0 ? {} : { marker: reduceMarker(assessment.marker, options) },
|
|
2371
2792
|
actor: options.maskIp ? { ...assessment.actor, key: maskActorKey(assessment.actor.key) } : assessment.actor,
|
|
2372
2793
|
evidence: scrubEvidence(assessment.evidence, removed),
|
|
2373
2794
|
humanEvidence: scrubEvidence(assessment.humanEvidence, removed),
|
|
2795
|
+
// Scrubbed on the same terms: a shadowed detector reads the same request as every
|
|
2796
|
+
// other one, so its summary can quote the same secret out of it.
|
|
2797
|
+
shadowEvidence: scrubEvidence(assessment.shadowEvidence, removed),
|
|
2374
2798
|
facts: {
|
|
2375
2799
|
...assessment.facts,
|
|
2376
2800
|
ip: options.maskIp ? maskIpValue(assessment.facts.ip) : assessment.facts.ip,
|
|
@@ -2422,6 +2846,15 @@ function maskActorKey(key) {
|
|
|
2422
2846
|
if (separator === -1) return networkKey(key);
|
|
2423
2847
|
return `${networkKey(key.slice(0, separator))}|${key.slice(separator + 1)}`;
|
|
2424
2848
|
}
|
|
2849
|
+
function reduceMarker(marker, options) {
|
|
2850
|
+
return {
|
|
2851
|
+
...marker,
|
|
2852
|
+
reading: { kind: marker.reading.kind },
|
|
2853
|
+
// The shape is three coarse parts of the User-Agent. If the User-Agent itself is
|
|
2854
|
+
// being withheld, the parts of it must go too, or the setting only half applies.
|
|
2855
|
+
...options.dropUserAgent === true ? { shape: { b: "", o: "", l: "" } } : {}
|
|
2856
|
+
};
|
|
2857
|
+
}
|
|
2425
2858
|
var REDACTED, CREDENTIAL_HEADERS, ALWAYS_STRIP, MIN_SCRUB_LENGTH;
|
|
2426
2859
|
var init_redact = __esm({
|
|
2427
2860
|
"src/notify/redact.ts"() {
|
|
@@ -3155,37 +3588,50 @@ var init_dns = __esm({
|
|
|
3155
3588
|
});
|
|
3156
3589
|
|
|
3157
3590
|
// src/detectors/clearance.ts
|
|
3158
|
-
function
|
|
3591
|
+
function withShared(shared, primary) {
|
|
3592
|
+
return shared === void 0 ? primary : [primary, shared];
|
|
3593
|
+
}
|
|
3594
|
+
function clearanceDetector(service, sharingThreshold = DEFAULT_SHARING_THRESHOLD) {
|
|
3159
3595
|
return {
|
|
3160
3596
|
id: "clearance",
|
|
3161
3597
|
description: "Reads a signed clearance token proving the client previously passed a check",
|
|
3162
3598
|
cost: "cheap",
|
|
3163
3599
|
stage: "always",
|
|
3164
3600
|
inspect(ctx) {
|
|
3165
|
-
const claims = service.
|
|
3166
|
-
|
|
3601
|
+
const { claims, boundElsewhere, presentedBy } = service.inspect(ctx.actor.key, ctx.facts.cookies);
|
|
3602
|
+
const shared = presentedBy >= sharingThreshold ? {
|
|
3603
|
+
detector: "clearance",
|
|
3604
|
+
summary: `The clearance token presented here has now been presented by ${presentedBy} different clients`,
|
|
3605
|
+
direction: "bot",
|
|
3606
|
+
certainty: "moderate",
|
|
3607
|
+
botClass: "scraper"
|
|
3608
|
+
} : void 0;
|
|
3609
|
+
if (!claims) {
|
|
3610
|
+
void boundElsewhere;
|
|
3611
|
+
return shared;
|
|
3612
|
+
}
|
|
3167
3613
|
const ageMs = ctx.facts.timestamp - claims.iat;
|
|
3168
3614
|
if (claims.lvl === "operator") {
|
|
3169
|
-
return {
|
|
3615
|
+
return withShared(shared, {
|
|
3170
3616
|
detector: "clearance",
|
|
3171
3617
|
summary: "Client holds an operator-granted clearance token",
|
|
3172
3618
|
direction: "human",
|
|
3173
3619
|
certainty: "certain",
|
|
3174
3620
|
deterministicBasis: "The application issued this clearance itself, on evidence it holds and this library cannot see. It is an assertion by the operator, not an inference from the request, and the token's signature binds it to this actor.",
|
|
3175
3621
|
metadata: { level: claims.lvl, ageMs }
|
|
3176
|
-
};
|
|
3622
|
+
});
|
|
3177
3623
|
}
|
|
3178
3624
|
if (claims.lvl === "interaction") {
|
|
3179
|
-
return {
|
|
3625
|
+
return withShared(shared, {
|
|
3180
3626
|
detector: "clearance",
|
|
3181
3627
|
summary: "Client holds a clearance token granted after a trusted input event",
|
|
3182
3628
|
direction: "human",
|
|
3183
3629
|
certainty: "strong",
|
|
3184
3630
|
weight: 0.7,
|
|
3185
3631
|
metadata: { level: claims.lvl, ageMs }
|
|
3186
|
-
};
|
|
3632
|
+
});
|
|
3187
3633
|
}
|
|
3188
|
-
return {
|
|
3634
|
+
return withShared(shared, {
|
|
3189
3635
|
detector: "clearance",
|
|
3190
3636
|
summary: "Client holds a clearance token granted for a completed proof of work",
|
|
3191
3637
|
direction: "human",
|
|
@@ -3196,13 +3642,389 @@ function clearanceDetector(service) {
|
|
|
3196
3642
|
ageMs,
|
|
3197
3643
|
note: "Proof of work demonstrates a JavaScript engine and spent CPU. It does not demonstrate a person."
|
|
3198
3644
|
}
|
|
3199
|
-
};
|
|
3645
|
+
});
|
|
3200
3646
|
}
|
|
3201
3647
|
};
|
|
3202
3648
|
}
|
|
3649
|
+
var DEFAULT_SHARING_THRESHOLD;
|
|
3203
3650
|
var init_clearance = __esm({
|
|
3204
3651
|
"src/detectors/clearance.ts"() {
|
|
3205
3652
|
"use strict";
|
|
3653
|
+
DEFAULT_SHARING_THRESHOLD = 12;
|
|
3654
|
+
}
|
|
3655
|
+
});
|
|
3656
|
+
|
|
3657
|
+
// src/probe/marker.ts
|
|
3658
|
+
function identityShape(facts, ua) {
|
|
3659
|
+
const platform = facts.headers["sec-ch-ua-platform"]?.replace(/"/g, "").trim().toLowerCase();
|
|
3660
|
+
const language = facts.headers["accept-language"]?.split(",")[0]?.split("-")[0]?.trim().toLowerCase();
|
|
3661
|
+
return {
|
|
3662
|
+
// A client that names no browser is its own category, and an empty User-Agent must
|
|
3663
|
+
// not read as equal to every other empty one by accident — it reads as "none", which
|
|
3664
|
+
// is exactly what it is, and changing away from it is a real change.
|
|
3665
|
+
b: part(ua.browser ?? (ua.raw.length === 0 ? "none" : `t:${withoutVersions(ua.raw)}`)),
|
|
3666
|
+
o: part(ua.os ?? platform ?? "none"),
|
|
3667
|
+
l: part(language ?? "none")
|
|
3668
|
+
};
|
|
3669
|
+
}
|
|
3670
|
+
function part(value) {
|
|
3671
|
+
const trimmed = value.length > 40 ? value.slice(0, 40) : value;
|
|
3672
|
+
return trimmed.toLowerCase();
|
|
3673
|
+
}
|
|
3674
|
+
function withoutVersions(raw) {
|
|
3675
|
+
return raw.replace(VERSION_NUMBERS, "#");
|
|
3676
|
+
}
|
|
3677
|
+
function driftBetween(issued, now) {
|
|
3678
|
+
return { browser: issued.b !== now.b, platform: issued.o !== now.o, language: issued.l !== now.l };
|
|
3679
|
+
}
|
|
3680
|
+
function newMarker(shape, ttlMs, now) {
|
|
3681
|
+
return { v: 1, sub: randomId(9), iat: now, exp: now + ttlMs, ...shape };
|
|
3682
|
+
}
|
|
3683
|
+
function markerCookie(name, claims, secrets, options) {
|
|
3684
|
+
return serializeCookie(name, issueToken(claims, secrets), {
|
|
3685
|
+
maxAgeMs: claims.exp - claims.iat,
|
|
3686
|
+
sameSite: options.sameSite ?? "Lax",
|
|
3687
|
+
secure: options.secure ?? true,
|
|
3688
|
+
// Nothing in a page needs to read this, and a marker readable by script is one a
|
|
3689
|
+
// cross-site script can lift.
|
|
3690
|
+
httpOnly: true,
|
|
3691
|
+
...options.domain === void 0 ? {} : { domain: options.domain }
|
|
3692
|
+
});
|
|
3693
|
+
}
|
|
3694
|
+
function readMarker(value, secrets, now) {
|
|
3695
|
+
if (value === void 0 || value.length === 0) return { kind: "absent" };
|
|
3696
|
+
if (!TOKEN_SHAPE.test(value)) return { kind: "absent" };
|
|
3697
|
+
const verified = verifyToken(value, secrets, now);
|
|
3698
|
+
if (verified.ok) return { kind: "valid", claims: verified.payload };
|
|
3699
|
+
return verified.reason === "expired" ? { kind: "expired" } : { kind: "forged" };
|
|
3700
|
+
}
|
|
3701
|
+
var VERSION_NUMBERS, TOKEN_SHAPE;
|
|
3702
|
+
var init_marker = __esm({
|
|
3703
|
+
"src/probe/marker.ts"() {
|
|
3704
|
+
"use strict";
|
|
3705
|
+
init_token();
|
|
3706
|
+
init_crypto();
|
|
3707
|
+
init_http();
|
|
3708
|
+
VERSION_NUMBERS = /\d+(?:[._]\d+)*/g;
|
|
3709
|
+
TOKEN_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
3710
|
+
}
|
|
3711
|
+
});
|
|
3712
|
+
|
|
3713
|
+
// src/detectors/challenge-reaction.ts
|
|
3714
|
+
function challengeReactionDetector(options = {}) {
|
|
3715
|
+
const windowMs = options.windowMs ?? 6e4;
|
|
3716
|
+
const minUnsolved = options.minUnsolved ?? 4;
|
|
3717
|
+
return {
|
|
3718
|
+
id: "challenge-reaction",
|
|
3719
|
+
description: "Reads how a client responded to being challenged: a changed identity, or never answering at all",
|
|
3720
|
+
cost: "cheap",
|
|
3721
|
+
stage: "always",
|
|
3722
|
+
inspect(ctx) {
|
|
3723
|
+
const found = [];
|
|
3724
|
+
const { at, shape } = ctx.state.lastChallenge;
|
|
3725
|
+
const since = at === 0 ? Number.POSITIVE_INFINITY : ctx.facts.timestamp - at;
|
|
3726
|
+
if (shape !== void 0 && since >= 0 && since <= windowMs) {
|
|
3727
|
+
const now = ctx.marker?.shape ?? identityShape(ctx.facts, ctx.ua);
|
|
3728
|
+
if (now.b !== shape.b) {
|
|
3729
|
+
const proven = ctx.marker?.reading.kind === "valid";
|
|
3730
|
+
found.push({
|
|
3731
|
+
detector: "challenge-reaction",
|
|
3732
|
+
summary: proven ? `Client changed the browser it claims to be within ${Math.round(since / 1e3)}s of being challenged, holding the same marker throughout` : `A client at this address changed the browser it claims to be within ${Math.round(since / 1e3)}s of being challenged`,
|
|
3733
|
+
direction: "bot",
|
|
3734
|
+
certainty: proven ? "strong" : "moderate",
|
|
3735
|
+
botClass: "impersonator",
|
|
3736
|
+
// One cause with `identity-drift`: this client changed what it claims to be.
|
|
3737
|
+
// Both fire together whenever a challenge is what prompted the change.
|
|
3738
|
+
family: "identity-change"
|
|
3739
|
+
});
|
|
3740
|
+
}
|
|
3741
|
+
}
|
|
3742
|
+
if (ctx.state.unsolvedChallenges >= minUnsolved) {
|
|
3743
|
+
found.push({
|
|
3744
|
+
detector: "challenge-reaction",
|
|
3745
|
+
summary: `Challenged ${ctx.state.unsolvedChallenges} times and has never returned a solution`,
|
|
3746
|
+
direction: "bot",
|
|
3747
|
+
certainty: "moderate",
|
|
3748
|
+
botClass: "unknown"
|
|
3749
|
+
});
|
|
3750
|
+
}
|
|
3751
|
+
return found.length > 0 ? found : void 0;
|
|
3752
|
+
}
|
|
3753
|
+
};
|
|
3754
|
+
}
|
|
3755
|
+
var init_challenge_reaction = __esm({
|
|
3756
|
+
"src/detectors/challenge-reaction.ts"() {
|
|
3757
|
+
"use strict";
|
|
3758
|
+
init_marker();
|
|
3759
|
+
}
|
|
3760
|
+
});
|
|
3761
|
+
|
|
3762
|
+
// src/detectors/challenge-integrity.ts
|
|
3763
|
+
function challengeIntegrityDetector(options = {}) {
|
|
3764
|
+
const minReplays = options.minReplays ?? 3;
|
|
3765
|
+
const minImplausible = options.minImplausible ?? 1;
|
|
3766
|
+
return {
|
|
3767
|
+
id: "challenge-integrity",
|
|
3768
|
+
description: "Reports solutions that were replayed, or returned faster than the proof of work allows",
|
|
3769
|
+
cost: "cheap",
|
|
3770
|
+
stage: "always",
|
|
3771
|
+
inspect(ctx) {
|
|
3772
|
+
const { replays, implausible } = ctx.state.challengeAnomalies;
|
|
3773
|
+
const found = [];
|
|
3774
|
+
if (replays >= minReplays) {
|
|
3775
|
+
found.push({
|
|
3776
|
+
detector: "challenge-integrity",
|
|
3777
|
+
summary: `Submitted ${replays} solutions for challenges that had already been solved`,
|
|
3778
|
+
direction: "bot",
|
|
3779
|
+
certainty: "moderate",
|
|
3780
|
+
botClass: "unknown"
|
|
3781
|
+
});
|
|
3782
|
+
}
|
|
3783
|
+
if (implausible >= minImplausible) {
|
|
3784
|
+
found.push({
|
|
3785
|
+
detector: "challenge-integrity",
|
|
3786
|
+
summary: implausible > 1 ? `Returned ${implausible} solutions faster than the proof of work can be computed in a browser` : "Returned a solution faster than the proof of work can be computed in a browser",
|
|
3787
|
+
direction: "bot",
|
|
3788
|
+
certainty: "moderate",
|
|
3789
|
+
botClass: "automation"
|
|
3790
|
+
});
|
|
3791
|
+
}
|
|
3792
|
+
return found.length > 0 ? found : void 0;
|
|
3793
|
+
}
|
|
3794
|
+
};
|
|
3795
|
+
}
|
|
3796
|
+
var init_challenge_integrity = __esm({
|
|
3797
|
+
"src/detectors/challenge-integrity.ts"() {
|
|
3798
|
+
"use strict";
|
|
3799
|
+
}
|
|
3800
|
+
});
|
|
3801
|
+
|
|
3802
|
+
// src/detectors/site-baseline.ts
|
|
3803
|
+
function distributedWalkDetector(options = {}) {
|
|
3804
|
+
const minActors = options.minActors ?? 8;
|
|
3805
|
+
const minIds = options.minIds ?? 150;
|
|
3806
|
+
const minCoverage = options.minCoverage ?? 0.6;
|
|
3807
|
+
const maxRevisitRatio = options.maxRevisitRatio ?? 1.3;
|
|
3808
|
+
const minRevisitRatio = options.minRevisitRatio ?? 0.7;
|
|
3809
|
+
return {
|
|
3810
|
+
id: "distributed-walk",
|
|
3811
|
+
description: "Reports a numeric range being walked across many clients, none of which walks enough of it alone",
|
|
3812
|
+
cost: "cheap",
|
|
3813
|
+
stage: "always",
|
|
3814
|
+
inspect(ctx) {
|
|
3815
|
+
if (ctx.site === void 0 || !ctx.site.warm) return void 0;
|
|
3816
|
+
const step = walkStepOf(ctx.facts.path);
|
|
3817
|
+
if (step === void 0) return void 0;
|
|
3818
|
+
const spread = ctx.site.spreadOf(step.template);
|
|
3819
|
+
if (spread === void 0) return void 0;
|
|
3820
|
+
if (spread.actors < minActors || spread.ids < minIds) return void 0;
|
|
3821
|
+
if (spread.coverage < minCoverage) return void 0;
|
|
3822
|
+
const revisits = spread.visits / spread.ids;
|
|
3823
|
+
if (revisits > maxRevisitRatio || revisits < minRevisitRatio) return void 0;
|
|
3824
|
+
return {
|
|
3825
|
+
detector: "distributed-walk",
|
|
3826
|
+
summary: `${spread.actors} clients between them have requested ${spread.ids} ids under ${step.template}, covering ${(spread.coverage * 100).toFixed(0)}% of the range and almost none of them twice`,
|
|
3827
|
+
direction: "bot",
|
|
3828
|
+
certainty: "moderate",
|
|
3829
|
+
botClass: "scraper"
|
|
3830
|
+
};
|
|
3831
|
+
}
|
|
3832
|
+
};
|
|
3833
|
+
}
|
|
3834
|
+
function pathNoveltyDetector(options = {}) {
|
|
3835
|
+
const minRequests = options.minRequests ?? 30;
|
|
3836
|
+
const minNovelShare = options.minNovelShare ?? 0.95;
|
|
3837
|
+
return {
|
|
3838
|
+
id: "path-novelty",
|
|
3839
|
+
description: "Reports a client whose requests are almost all for paths this site has never been asked for",
|
|
3840
|
+
cost: "cheap",
|
|
3841
|
+
stage: "always",
|
|
3842
|
+
inspect(ctx) {
|
|
3843
|
+
if (ctx.site === void 0 || !ctx.site.warm) return void 0;
|
|
3844
|
+
const total = ctx.state.total;
|
|
3845
|
+
if (total < minRequests) return void 0;
|
|
3846
|
+
const share = ctx.state.novelPathCount / total;
|
|
3847
|
+
if (share < minNovelShare) return void 0;
|
|
3848
|
+
return {
|
|
3849
|
+
detector: "path-novelty",
|
|
3850
|
+
summary: `${(share * 100).toFixed(0)}% of this client's ${total} requests were for paths no other client has ever asked this site for`,
|
|
3851
|
+
direction: "bot",
|
|
3852
|
+
certainty: "moderate",
|
|
3853
|
+
botClass: "scanner",
|
|
3854
|
+
// The same cause `probe-signature` names when a path is on a list it ships: this
|
|
3855
|
+
// client is walking a list rather than reading a site.
|
|
3856
|
+
family: "wordlist-probe"
|
|
3857
|
+
};
|
|
3858
|
+
}
|
|
3859
|
+
};
|
|
3860
|
+
}
|
|
3861
|
+
function missBaselineDetector(options = {}) {
|
|
3862
|
+
const minResponses = options.minResponses ?? 20;
|
|
3863
|
+
const minRatio = options.minRatio ?? 5;
|
|
3864
|
+
const floor = options.floor ?? 0.5;
|
|
3865
|
+
return {
|
|
3866
|
+
id: "miss-baseline",
|
|
3867
|
+
description: 'Compares how often a client is answered "not found" with how often this site answers that at all',
|
|
3868
|
+
cost: "cheap",
|
|
3869
|
+
stage: "always",
|
|
3870
|
+
inspect(ctx) {
|
|
3871
|
+
const siteRate = ctx.site?.missRate;
|
|
3872
|
+
if (siteRate === void 0) return void 0;
|
|
3873
|
+
const { responses, misses } = ctx.state;
|
|
3874
|
+
if (responses < minResponses) return void 0;
|
|
3875
|
+
const rate = misses / responses;
|
|
3876
|
+
if (rate < floor) return void 0;
|
|
3877
|
+
if (siteRate > 0 && rate / siteRate < minRatio) return void 0;
|
|
3878
|
+
return {
|
|
3879
|
+
detector: "miss-baseline",
|
|
3880
|
+
summary: siteRate > 0 ? `${(rate * 100).toFixed(0)}% of this client's requests were answered "not found", against ${(siteRate * 100).toFixed(1)}% across the site` : `${(rate * 100).toFixed(0)}% of this client's requests were answered "not found", on a site that otherwise never answers that`,
|
|
3881
|
+
direction: "bot",
|
|
3882
|
+
certainty: "moderate",
|
|
3883
|
+
botClass: "scanner",
|
|
3884
|
+
// `probe-volume` reads the same misses against a fixed threshold. Two readings
|
|
3885
|
+
// of one cause, so the stronger stands and they do not sum.
|
|
3886
|
+
family: "misses"
|
|
3887
|
+
};
|
|
3888
|
+
}
|
|
3889
|
+
};
|
|
3890
|
+
}
|
|
3891
|
+
function pathCampaignDetector(options = {}) {
|
|
3892
|
+
const minClients = options.minClients ?? 12;
|
|
3893
|
+
const minMissShare = options.minMissShare ?? 0.9;
|
|
3894
|
+
const minAnswered = options.minAnswered ?? 10;
|
|
3895
|
+
return {
|
|
3896
|
+
id: "path-campaign",
|
|
3897
|
+
description: "Reports a path this site never served that many unrelated clients have suddenly begun requesting",
|
|
3898
|
+
cost: "cheap",
|
|
3899
|
+
stage: "always",
|
|
3900
|
+
inspect(ctx) {
|
|
3901
|
+
const surge = ctx.site?.surgeOf(ctx.facts.path);
|
|
3902
|
+
if (surge === void 0) return void 0;
|
|
3903
|
+
if (surge.clients < minClients || surge.answered < minAnswered) return void 0;
|
|
3904
|
+
if (surge.misses / surge.answered < minMissShare) return void 0;
|
|
3905
|
+
return {
|
|
3906
|
+
detector: "path-campaign",
|
|
3907
|
+
summary: `${surge.clients} unrelated clients have requested ${ctx.facts.path} since it first appeared ${Math.round(surge.ageMs / 6e4)} minutes ago, and the site has answered "not found" to almost all of them`,
|
|
3908
|
+
direction: "bot",
|
|
3909
|
+
certainty: "moderate",
|
|
3910
|
+
botClass: "scanner"
|
|
3911
|
+
};
|
|
3912
|
+
}
|
|
3913
|
+
};
|
|
3914
|
+
}
|
|
3915
|
+
var init_site_baseline = __esm({
|
|
3916
|
+
"src/detectors/site-baseline.ts"() {
|
|
3917
|
+
"use strict";
|
|
3918
|
+
init_state();
|
|
3919
|
+
}
|
|
3920
|
+
});
|
|
3921
|
+
|
|
3922
|
+
// src/detectors/marker.ts
|
|
3923
|
+
function identityDriftDetector(options = {}) {
|
|
3924
|
+
const reportSoft = options.reportSoftDrift ?? true;
|
|
3925
|
+
return {
|
|
3926
|
+
id: "identity-drift",
|
|
3927
|
+
description: "Compares the identity a client claims now with the one it claimed when it was given its marker",
|
|
3928
|
+
cost: "cheap",
|
|
3929
|
+
stage: "always",
|
|
3930
|
+
inspect(ctx) {
|
|
3931
|
+
const drift = ctx.marker?.drift;
|
|
3932
|
+
if (drift === void 0) return void 0;
|
|
3933
|
+
if (drift.browser) {
|
|
3934
|
+
return {
|
|
3935
|
+
detector: "identity-drift",
|
|
3936
|
+
summary: "Client is holding a marker this server issued to a different browser, so one of the two identities it has claimed is false",
|
|
3937
|
+
direction: "bot",
|
|
3938
|
+
certainty: "strong",
|
|
3939
|
+
botClass: "impersonator"
|
|
3940
|
+
};
|
|
3941
|
+
}
|
|
3942
|
+
if (!reportSoft || !(drift.platform || drift.language)) return void 0;
|
|
3943
|
+
const what = drift.platform && drift.language ? "platform and language" : drift.platform ? "platform" : "language";
|
|
3944
|
+
return {
|
|
3945
|
+
detector: "identity-drift",
|
|
3946
|
+
// Named precisely, because the operator reading this needs to know it is the
|
|
3947
|
+
// soft case: a person switching to the desktop site produces exactly this.
|
|
3948
|
+
summary: `Client's claimed ${what} changed while holding one marker, which a person can also do deliberately`,
|
|
3949
|
+
direction: "bot",
|
|
3950
|
+
certainty: "moderate",
|
|
3951
|
+
botClass: "unknown"
|
|
3952
|
+
};
|
|
3953
|
+
}
|
|
3954
|
+
};
|
|
3955
|
+
}
|
|
3956
|
+
function markerIntegrityDetector(options = {}) {
|
|
3957
|
+
const minForgeries = options.minForgeries ?? 1;
|
|
3958
|
+
return {
|
|
3959
|
+
id: "marker-integrity",
|
|
3960
|
+
description: "Reports a marker cookie presented with a signature this server could not have produced",
|
|
3961
|
+
cost: "cheap",
|
|
3962
|
+
stage: "always",
|
|
3963
|
+
inspect(ctx) {
|
|
3964
|
+
if (ctx.marker?.reading.kind !== "forged") return void 0;
|
|
3965
|
+
const { forged } = ctx.state.markers;
|
|
3966
|
+
if (forged < minForgeries) return void 0;
|
|
3967
|
+
return {
|
|
3968
|
+
detector: "marker-integrity",
|
|
3969
|
+
summary: forged > 1 ? `Presented a marker cookie this server never signed, ${forged} times` : "Presented a marker cookie this server never signed",
|
|
3970
|
+
direction: "bot",
|
|
3971
|
+
certainty: "strong",
|
|
3972
|
+
botClass: "scanner"
|
|
3973
|
+
};
|
|
3974
|
+
}
|
|
3975
|
+
};
|
|
3976
|
+
}
|
|
3977
|
+
function markerPersistenceDetector(options = {}) {
|
|
3978
|
+
const minIssued = options.minIssued ?? 5;
|
|
3979
|
+
return {
|
|
3980
|
+
id: "marker-persistence",
|
|
3981
|
+
description: "Reports a client that has been handed a marker repeatedly and has never returned one",
|
|
3982
|
+
cost: "cheap",
|
|
3983
|
+
stage: "always",
|
|
3984
|
+
inspect(ctx) {
|
|
3985
|
+
if (ctx.marker === void 0) return void 0;
|
|
3986
|
+
if (ctx.facts.headers["cookie"] === void 0) return void 0;
|
|
3987
|
+
const { issued, returned } = ctx.state.markers;
|
|
3988
|
+
if (returned > 0 || issued < minIssued) return void 0;
|
|
3989
|
+
return {
|
|
3990
|
+
detector: "marker-persistence",
|
|
3991
|
+
summary: `Sends cookies but has never returned the one this server set, across ${issued} responses that offered it`,
|
|
3992
|
+
direction: "bot",
|
|
3993
|
+
certainty: "moderate",
|
|
3994
|
+
botClass: "http-client",
|
|
3995
|
+
// The same cause `session-integrity` reports when it sees no cookie at all: one
|
|
3996
|
+
// client that does not keep state. Without this they are two moderate signals
|
|
3997
|
+
// for one observation, and the population that produces it is people who block
|
|
3998
|
+
// cookies — so the double count landed squarely on them. Measured on the corpus:
|
|
3999
|
+
// it took `cookies-blocked` from 21 to 38 before the family was named.
|
|
4000
|
+
family: "no-session"
|
|
4001
|
+
};
|
|
4002
|
+
}
|
|
4003
|
+
};
|
|
4004
|
+
}
|
|
4005
|
+
function markerFanoutDetector(options = {}) {
|
|
4006
|
+
const minNetworks = options.minNetworks ?? 16;
|
|
4007
|
+
return {
|
|
4008
|
+
id: "marker-fanout",
|
|
4009
|
+
description: "Counts the distinct networks one marker cookie has been presented from",
|
|
4010
|
+
cost: "cheap",
|
|
4011
|
+
stage: "always",
|
|
4012
|
+
inspect(ctx) {
|
|
4013
|
+
const networks = ctx.marker?.networks ?? 0;
|
|
4014
|
+
if (networks < minNetworks) return void 0;
|
|
4015
|
+
return {
|
|
4016
|
+
detector: "marker-fanout",
|
|
4017
|
+
summary: `One client has presented the same marker from ${networks} different networks`,
|
|
4018
|
+
direction: "bot",
|
|
4019
|
+
certainty: "moderate",
|
|
4020
|
+
botClass: "scraper"
|
|
4021
|
+
};
|
|
4022
|
+
}
|
|
4023
|
+
};
|
|
4024
|
+
}
|
|
4025
|
+
var init_marker2 = __esm({
|
|
4026
|
+
"src/detectors/marker.ts"() {
|
|
4027
|
+
"use strict";
|
|
3206
4028
|
}
|
|
3207
4029
|
});
|
|
3208
4030
|
|
|
@@ -3352,7 +4174,7 @@ function compileSignatures(signatures = BOT_SIGNATURES) {
|
|
|
3352
4174
|
}
|
|
3353
4175
|
return new MultiPatternMatcher(entries);
|
|
3354
4176
|
}
|
|
3355
|
-
var BOT_CATEGORIES, SEARCH, AI, SEO, SOCIAL, MONITORING, ARCHIVE, FEED, SECURITY, LIBRARY, HEADLESS, EMBEDDED, ADVERTISING, COMMERCE, ACADEMIC, ACCESSIBILITY, BOT_SIGNATURES;
|
|
4177
|
+
var BOT_CATEGORIES, SEARCH, AI, SEO, SOCIAL, MONITORING, ARCHIVE, FEED, SECURITY, LIBRARY, HEADLESS, EMBEDDED, ADVERTISING, COMMERCE, ACADEMIC, EMAIL_SECURITY, ACCESSIBILITY, BOT_SIGNATURES;
|
|
3356
4178
|
var init_known_bots = __esm({
|
|
3357
4179
|
"src/detectors/known-bots.ts"() {
|
|
3358
4180
|
"use strict";
|
|
@@ -3373,6 +4195,7 @@ var init_known_bots = __esm({
|
|
|
3373
4195
|
"commerce",
|
|
3374
4196
|
"accessibility",
|
|
3375
4197
|
"academic",
|
|
4198
|
+
"email-security",
|
|
3376
4199
|
"other"
|
|
3377
4200
|
];
|
|
3378
4201
|
SEARCH = [
|
|
@@ -3397,6 +4220,13 @@ var init_known_bots = __esm({
|
|
|
3397
4220
|
{ id: "yisouspider", name: "Shenma (Yisou) Spider", tokens: ["yisouspider"], category: "search", benign: true, robotsAgent: "YisouSpider", verification: { kind: "none" } },
|
|
3398
4221
|
{ id: "yahoo-slurp", name: "Yahoo! Slurp", tokens: ["yahoo! slurp"], category: "search", benign: true, robotsAgent: "Slurp", verification: { kind: "fcrdns", domains: ["crawl.yahoo.net", "yahoo.com"] } },
|
|
3399
4222
|
{ id: "mail-ru", name: "Mail.Ru bot", tokens: ["mail.ru_bot"], category: "search", benign: true, verification: { kind: "none" } },
|
|
4223
|
+
{ id: "brave-search", name: "Brave Search", tokens: ["bravesearchbot"], category: "search", benign: true, robotsAgent: "BraveSearchBot", verification: { kind: "none" } },
|
|
4224
|
+
{ id: "ecosia", name: "Ecosia", tokens: ["ecosiabot"], category: "search", benign: true, verification: { kind: "none" } },
|
|
4225
|
+
{ id: "startpage", name: "Startpage", tokens: ["startpagebot"], category: "search", benign: true, verification: { kind: "none" } },
|
|
4226
|
+
{ id: "daum", name: "Daumoa", tokens: ["daumoa"], category: "search", benign: true, verification: { kind: "none" } },
|
|
4227
|
+
{ id: "stract", name: "Stract", tokens: ["stractbot"], category: "search", benign: true, verification: { kind: "none" } },
|
|
4228
|
+
{ id: "rightdao", name: "RightDao", tokens: ["rightdaobot"], category: "search", benign: true, verification: { kind: "none" } },
|
|
4229
|
+
{ id: "gigablast", name: "Gigablast", tokens: ["gigablastopensource"], category: "search", benign: true, verification: { kind: "none" } },
|
|
3400
4230
|
{ id: "exabot", name: "Exabot (Exalead)", tokens: ["exabot"], category: "search", benign: true, verification: { kind: "none" } },
|
|
3401
4231
|
{ id: "kagibot", name: "Kagi", tokens: ["kagibot"], category: "search", benign: true, robotsAgent: "KagiBot", verification: { kind: "none" } }
|
|
3402
4232
|
];
|
|
@@ -3467,11 +4297,15 @@ var init_known_bots = __esm({
|
|
|
3467
4297
|
{ id: "pinterestbot", name: "Pinterestbot", tokens: ["pinterest/", "pinterestbot"], category: "social", benign: true, verification: { kind: "fcrdns", domains: ["pinterest.com"] } },
|
|
3468
4298
|
{ id: "mastodon", name: "Mastodon / Fediverse", tokens: ["mastodon/", "pleroma", "misskey/", "akkoma"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3469
4299
|
{ id: "embedly", name: "Embedly", tokens: ["embedly"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3470
|
-
{ id: "bluesky", name: "Bluesky card fetcher", tokens: ["bluesky cardyb", "cardyb/"], category: "social", benign: true, verification: { kind: "none" } },
|
|
4300
|
+
{ id: "bluesky", name: "Bluesky card fetcher", tokens: ["bluesky cardyb", "cardyb/", "blueskybot"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3471
4301
|
{ id: "iframely", name: "Iframely", tokens: ["iframely"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3472
4302
|
{ id: "skype-preview", name: "Skype URI preview", tokens: ["skypeuripreview"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3473
4303
|
{ id: "vk-share", name: "VK / Odnoklassniki preview", tokens: ["vkshare", "odklbot"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3474
4304
|
{ id: "discourse-onebox", name: "Discourse Onebox", tokens: ["discourse forum onebox"], category: "social", benign: true, verification: { kind: "none" } },
|
|
4305
|
+
{ id: "microsoft-preview", name: "Microsoft Teams preview", tokens: ["microsoftpreview"], category: "social", benign: true, verification: { kind: "none" } },
|
|
4306
|
+
{ id: "zoom-preview", name: "Zoom link preview", tokens: ["zoombot"], category: "social", benign: true, verification: { kind: "none" } },
|
|
4307
|
+
{ id: "signal-preview", name: "Signal link preview", tokens: ["signalbot"], category: "social", benign: true, verification: { kind: "none" } },
|
|
4308
|
+
{ id: "matrix-synapse", name: "Matrix (Synapse) preview", tokens: ["synapse/"], category: "social", benign: true, verification: { kind: "none" } },
|
|
3475
4309
|
{ id: "yahoo-preview", name: "Yahoo Link Preview", tokens: ["yahoo link preview"], category: "social", benign: true, verification: { kind: "none" } }
|
|
3476
4310
|
];
|
|
3477
4311
|
MONITORING = [
|
|
@@ -3511,6 +4345,10 @@ var init_known_bots = __esm({
|
|
|
3511
4345
|
{ id: "smartnews", name: "SmartNews", tokens: ["smartnewsbot"], category: "feed", benign: true, verification: { kind: "none" } },
|
|
3512
4346
|
{ id: "flipboard", name: "Flipboard", tokens: ["flipboardproxy"], category: "feed", benign: true, verification: { kind: "none" } },
|
|
3513
4347
|
{ id: "podcast-index", name: "Podcast Index", tokens: ["podcastindexbot"], category: "feed", benign: true, verification: { kind: "none" } },
|
|
4348
|
+
// Spotify's podcast fetcher sends `Spotify/1.0` — and so does the Spotify desktop app,
|
|
4349
|
+
// with a person driving it. There is no token that separates them, so this one is left
|
|
4350
|
+
// unnamed rather than named wrongly: the corpus proved the point immediately by blocking
|
|
4351
|
+
// a human under `protect-auth`, `indexers-only` and `under-attack` at once.
|
|
3514
4352
|
{ id: "freshrss", name: "FreshRSS", tokens: ["freshrss"], category: "feed", benign: true, verification: { kind: "none" } },
|
|
3515
4353
|
{ id: "netnewswire", name: "NetNewsWire", tokens: ["netnewswire"], category: "feed", benign: true, verification: { kind: "none" } },
|
|
3516
4354
|
{ id: "overcast", name: "Overcast", tokens: ["overcast/"], category: "feed", benign: true, verification: { kind: "none" } },
|
|
@@ -3637,7 +4475,23 @@ var init_known_bots = __esm({
|
|
|
3637
4475
|
];
|
|
3638
4476
|
ADVERTISING = [
|
|
3639
4477
|
{ id: "adsbot-google", name: "AdsBot-Google", tokens: ["adsbot-google", "mediapartners-google", "adsbot"], category: "advertising", benign: true, verification: { kind: "fcrdns", domains: ["googlebot.com", "google.com"] } },
|
|
3640
|
-
{ id: "criteo", name: "Criteo", tokens: ["criteobot"], category: "advertising", benign: true, verification: { kind: "none" } }
|
|
4478
|
+
{ id: "criteo", name: "Criteo", tokens: ["criteobot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4479
|
+
// Verification and contextual classification: they read a page to decide whether an ad
|
|
4480
|
+
// may appear beside it, or what the page is about. A publisher usually wants these and a
|
|
4481
|
+
// site with no advertising has no reason to.
|
|
4482
|
+
{ id: "doubleverify", name: "DoubleVerify", tokens: ["doubleverifybot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4483
|
+
{ id: "ias", name: "Integral Ad Science", tokens: ["ias crawler"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4484
|
+
{ id: "moat", name: "Moat", tokens: ["moatbot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4485
|
+
{ id: "comscore", name: "comScore (Proximic)", tokens: ["proximic"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4486
|
+
{ id: "grapeshot", name: "Grapeshot", tokens: ["grapeshotcrawler"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4487
|
+
{ id: "peer39", name: "Peer39", tokens: ["peer39bot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4488
|
+
{ id: "taboola", name: "Taboola", tokens: ["taboolabot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4489
|
+
{ id: "outbrain", name: "Outbrain", tokens: ["outbrainbot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4490
|
+
{ id: "pubmatic", name: "PubMatic", tokens: ["pubmaticbot"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4491
|
+
{ id: "thetradedesk", name: "The Trade Desk", tokens: ["ttd-content"], category: "advertising", benign: true, verification: { kind: "none" } },
|
|
4492
|
+
// Competitive ad intelligence rather than verification: it collects what everyone else
|
|
4493
|
+
// is running. Named, and left for the operator to decide about.
|
|
4494
|
+
{ id: "adbeat", name: "Adbeat", tokens: ["adbeat_bot"], category: "advertising", benign: false, verification: { kind: "none" } }
|
|
3641
4495
|
];
|
|
3642
4496
|
COMMERCE = [
|
|
3643
4497
|
{ id: "idealo", name: "idealo", tokens: ["idealo-bot"], category: "commerce", benign: false, verification: { kind: "none" } },
|
|
@@ -3653,6 +4507,12 @@ var init_known_bots = __esm({
|
|
|
3653
4507
|
{ id: "openalex", name: "OpenAlex", tokens: ["openalexbot"], category: "academic", benign: true, verification: { kind: "none" } },
|
|
3654
4508
|
{ id: "webis", name: "Webis research crawler", tokens: ["webisbot"], category: "academic", benign: true, verification: { kind: "none" } }
|
|
3655
4509
|
];
|
|
4510
|
+
EMAIL_SECURITY = [
|
|
4511
|
+
{ id: "proofpoint", name: "Proofpoint URL Defense", tokens: ["proofpointurldefensebot"], category: "email-security", benign: true, verification: { kind: "none" } },
|
|
4512
|
+
{ id: "mimecast", name: "Mimecast URL Protect", tokens: ["mimecasturlprotectbot"], category: "email-security", benign: true, verification: { kind: "none" } },
|
|
4513
|
+
{ id: "barracuda", name: "Barracuda Link Protect", tokens: ["barracudalinkprotectbot"], category: "email-security", benign: true, verification: { kind: "none" } },
|
|
4514
|
+
{ id: "cisco-esa", name: "Cisco Secure Email", tokens: ["ciscosecureemailbot"], category: "email-security", benign: true, verification: { kind: "none" } }
|
|
4515
|
+
];
|
|
3656
4516
|
ACCESSIBILITY = [
|
|
3657
4517
|
{ id: "siteimprove", name: "Siteimprove", tokens: ["siteimprovebot"], category: "accessibility", benign: true, robotsAgent: "SiteimproveBot", verification: { kind: "none" } }
|
|
3658
4518
|
];
|
|
@@ -3671,7 +4531,8 @@ var init_known_bots = __esm({
|
|
|
3671
4531
|
...EMBEDDED,
|
|
3672
4532
|
...COMMERCE,
|
|
3673
4533
|
...ACADEMIC,
|
|
3674
|
-
...ACCESSIBILITY
|
|
4534
|
+
...ACCESSIBILITY,
|
|
4535
|
+
...EMAIL_SECURITY
|
|
3675
4536
|
]);
|
|
3676
4537
|
}
|
|
3677
4538
|
});
|
|
@@ -3992,6 +4853,309 @@ var init_ua = __esm({
|
|
|
3992
4853
|
}
|
|
3993
4854
|
});
|
|
3994
4855
|
|
|
4856
|
+
// src/probe/index.ts
|
|
4857
|
+
function hashToBit(value) {
|
|
4858
|
+
let hash = 2166136261;
|
|
4859
|
+
for (let i = 0; i < value.length; i++) {
|
|
4860
|
+
hash ^= value.charCodeAt(i);
|
|
4861
|
+
hash = Math.imul(hash, 16777619);
|
|
4862
|
+
}
|
|
4863
|
+
return (hash >>> 0) % FANOUT_BITS;
|
|
4864
|
+
}
|
|
4865
|
+
function estimateDistinct(sketch, cap) {
|
|
4866
|
+
let set = 0;
|
|
4867
|
+
for (let word = 0; word < FANOUT_WORDS; word++) {
|
|
4868
|
+
let bits = sketch[word];
|
|
4869
|
+
while (bits !== 0) {
|
|
4870
|
+
bits &= bits - 1;
|
|
4871
|
+
set++;
|
|
4872
|
+
}
|
|
4873
|
+
}
|
|
4874
|
+
if (set >= FANOUT_BITS) return cap;
|
|
4875
|
+
const estimate = Math.round(-FANOUT_BITS * Math.log(1 - set / FANOUT_BITS));
|
|
4876
|
+
return Math.min(estimate, cap);
|
|
4877
|
+
}
|
|
4878
|
+
var DEFAULT_TTL_MS, FANOUT_WORDS, FANOUT_BITS, MarkerProbe;
|
|
4879
|
+
var init_probe = __esm({
|
|
4880
|
+
"src/probe/index.ts"() {
|
|
4881
|
+
"use strict";
|
|
4882
|
+
init_marker();
|
|
4883
|
+
init_lru();
|
|
4884
|
+
init_ip();
|
|
4885
|
+
init_marker();
|
|
4886
|
+
DEFAULT_TTL_MS = 12 * 60 * 6e4;
|
|
4887
|
+
FANOUT_WORDS = 4;
|
|
4888
|
+
FANOUT_BITS = FANOUT_WORDS * 32;
|
|
4889
|
+
MarkerProbe = class {
|
|
4890
|
+
cookieName;
|
|
4891
|
+
secrets;
|
|
4892
|
+
ttlMs;
|
|
4893
|
+
cookieOptions;
|
|
4894
|
+
clock;
|
|
4895
|
+
/**
|
|
4896
|
+
* Marker id to a 128-bit sketch of the networks it has been presented from.
|
|
4897
|
+
*
|
|
4898
|
+
* A `Set` of network strings is the obvious structure and measured at **55.6 MB** with
|
|
4899
|
+
* both caps full — twenty thousand markers each seen from a few dozen networks — which
|
|
4900
|
+
* is far too much to hand somebody for switching on a detector. The question being
|
|
4901
|
+
* asked is only ever "has this marker come from more than about sixteen networks", and
|
|
4902
|
+
* a bitmap answers that in sixteen bytes by linear counting: hash each network to a
|
|
4903
|
+
* bit, then estimate the distinct count from how many bits are set.
|
|
4904
|
+
*
|
|
4905
|
+
* The estimate carries a few percent of error in **either** direction — measured, 16
|
|
4906
|
+
* real networks read as 17 and 32 read as 33 — so the threshold it feeds is a soft
|
|
4907
|
+
* boundary rather than a hard one. That is honest for this signal in particular, which
|
|
4908
|
+
* cannot separate a proxy pool from a heavily mobile person at any resolution, and is
|
|
4909
|
+
* why it is capped at `moderate` and never denies anybody by itself.
|
|
4910
|
+
*/
|
|
4911
|
+
fanout;
|
|
4912
|
+
maxNetworks;
|
|
4913
|
+
/**
|
|
4914
|
+
* Markers already verified, by the exact cookie value that verified.
|
|
4915
|
+
*
|
|
4916
|
+
* A browsing session sends one identical cookie on every request, and verifying it is
|
|
4917
|
+
* an HMAC — which measured at roughly twenty microseconds, nearly doubling the cost of
|
|
4918
|
+
* an assessment to re-establish a fact that had not changed. The cache is only ever
|
|
4919
|
+
* populated with *successes*: caching failures would let anyone flood it with unique
|
|
4920
|
+
* junk, and a failure is cheap to reach anyway.
|
|
4921
|
+
*
|
|
4922
|
+
* Expiry is still checked on every hit, so a cached marker stops being accepted at the
|
|
4923
|
+
* moment it should. The key is the whole signed value, so a cache hit is only possible
|
|
4924
|
+
* for a string that already carried a valid signature.
|
|
4925
|
+
*/
|
|
4926
|
+
verified;
|
|
4927
|
+
constructor(options) {
|
|
4928
|
+
if (options.secrets.length === 0) throw new Error("A marker probe requires at least one secret");
|
|
4929
|
+
for (const secret of options.secrets) {
|
|
4930
|
+
if (secret.length < 32) {
|
|
4931
|
+
throw new Error("Each marker secret must be at least 32 characters; generate one with `crypto.randomBytes(32).toString('base64url')`");
|
|
4932
|
+
}
|
|
4933
|
+
}
|
|
4934
|
+
this.secrets = options.secrets;
|
|
4935
|
+
this.cookieName = options.cookieName ?? "__bh_m";
|
|
4936
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
4937
|
+
this.clock = options.clock;
|
|
4938
|
+
const tracked = options.maxTrackedMarkers ?? 2e4;
|
|
4939
|
+
this.maxNetworks = options.maxNetworksPerMarker ?? 96;
|
|
4940
|
+
this.fanout = tracked > 0 ? new TtlLru(tracked, this.ttlMs, options.clock) : void 0;
|
|
4941
|
+
const cached = options.maxVerifiedMarkers ?? 5e3;
|
|
4942
|
+
this.verified = cached > 0 ? new TtlLru(cached, this.ttlMs, options.clock) : void 0;
|
|
4943
|
+
this.cookieOptions = {
|
|
4944
|
+
...options.sameSite === void 0 ? {} : { sameSite: options.sameSite },
|
|
4945
|
+
...options.secure === void 0 ? {} : { secure: options.secure },
|
|
4946
|
+
...options.domain === void 0 ? {} : { domain: options.domain }
|
|
4947
|
+
};
|
|
4948
|
+
try {
|
|
4949
|
+
markerCookie(this.cookieName, newMarker({ b: "x", o: "x", l: "x" }, this.ttlMs, 0), this.secrets, this.cookieOptions);
|
|
4950
|
+
} catch (error) {
|
|
4951
|
+
throw new Error(`The marker probe cannot issue a cookie with this configuration: ${error instanceof Error ? error.message : String(error)}`);
|
|
4952
|
+
}
|
|
4953
|
+
}
|
|
4954
|
+
/** Reads the marker this request carried, and measures it against the request. */
|
|
4955
|
+
observe(facts, ua) {
|
|
4956
|
+
const shape = identityShape(facts, ua);
|
|
4957
|
+
const reading = this.read(facts.cookies?.[this.cookieName]);
|
|
4958
|
+
const drift = reading.kind === "valid" ? driftBetween({ b: reading.claims.b, o: reading.claims.o, l: reading.claims.l }, shape) : void 0;
|
|
4959
|
+
const networks = reading.kind === "valid" ? this.noteNetwork(reading.claims.sub, facts.ip) : 0;
|
|
4960
|
+
return { reading, drift, shape, networks };
|
|
4961
|
+
}
|
|
4962
|
+
/**
|
|
4963
|
+
* Whether this response should carry a marker.
|
|
4964
|
+
*
|
|
4965
|
+
* Only when the client is not already holding a good one. An ordinary visitor is
|
|
4966
|
+
* therefore issued a cookie once and then browses with uncached-by-`Set-Cookie`
|
|
4967
|
+
* responses never again; a client that discards cookies is issued one every time,
|
|
4968
|
+
* which is itself the observation `marker-persistence` is built on.
|
|
4969
|
+
*/
|
|
4970
|
+
shouldIssue(observation) {
|
|
4971
|
+
return observation.reading.kind !== "valid";
|
|
4972
|
+
}
|
|
4973
|
+
/** Verifies a presented marker, reusing an earlier verification of the same value. */
|
|
4974
|
+
read(value) {
|
|
4975
|
+
if (value === void 0 || value.length === 0) return { kind: "absent" };
|
|
4976
|
+
const now = this.clock.now();
|
|
4977
|
+
const remembered = this.verified?.get(value);
|
|
4978
|
+
if (remembered !== void 0) return remembered.exp > now ? { kind: "valid", claims: remembered } : { kind: "expired" };
|
|
4979
|
+
const reading = readMarker(value, this.secrets, now);
|
|
4980
|
+
if (reading.kind === "valid") this.verified?.set(value, reading.claims);
|
|
4981
|
+
return reading;
|
|
4982
|
+
}
|
|
4983
|
+
/**
|
|
4984
|
+
* Files this presentation under the marker's own id and returns how many distinct
|
|
4985
|
+
* networks it has now come from.
|
|
4986
|
+
*
|
|
4987
|
+
* A `/24` rather than an address, because a single visitor's address changes for
|
|
4988
|
+
* ordinary reasons all day — a phone moving between cells, a router relearning a
|
|
4989
|
+
* lease — while the network it sits behind usually does not. Counting addresses would
|
|
4990
|
+
* report every commuter.
|
|
4991
|
+
*/
|
|
4992
|
+
noteNetwork(markerId, ip) {
|
|
4993
|
+
if (this.fanout === void 0) return 0;
|
|
4994
|
+
let sketch = this.fanout.get(markerId);
|
|
4995
|
+
if (sketch === void 0) {
|
|
4996
|
+
sketch = new Uint32Array(FANOUT_WORDS);
|
|
4997
|
+
this.fanout.set(markerId, sketch);
|
|
4998
|
+
}
|
|
4999
|
+
const bit = hashToBit(networkKey(ip));
|
|
5000
|
+
sketch[bit >>> 5] = sketch[bit >>> 5] | 1 << (bit & 31);
|
|
5001
|
+
return estimateDistinct(sketch, this.maxNetworks);
|
|
5002
|
+
}
|
|
5003
|
+
/** The `Set-Cookie` handing this client a marker bound to the identity it just claimed. */
|
|
5004
|
+
issue(observation) {
|
|
5005
|
+
return markerCookie(this.cookieName, newMarker(observation.shape, this.ttlMs, this.clock.now()), this.secrets, this.cookieOptions);
|
|
5006
|
+
}
|
|
5007
|
+
};
|
|
5008
|
+
}
|
|
5009
|
+
});
|
|
5010
|
+
|
|
5011
|
+
// src/site/index.ts
|
|
5012
|
+
function bucketSet(record, bucket) {
|
|
5013
|
+
record.bits[bucket >>> 5] = record.bits[bucket >>> 5] | 1 << (bucket & 31);
|
|
5014
|
+
}
|
|
5015
|
+
function bucketGet(record, bucket) {
|
|
5016
|
+
return (record.bits[bucket >>> 5] & 1 << (bucket & 31)) !== 0;
|
|
5017
|
+
}
|
|
5018
|
+
function coarsen(record) {
|
|
5019
|
+
const merged = new Uint32Array(WALK_BUCKETS / 32);
|
|
5020
|
+
for (let bucket = 0; bucket < WALK_BUCKETS / 2; bucket++) {
|
|
5021
|
+
const low = bucket * 2;
|
|
5022
|
+
if (bucketGet(record, low) || bucketGet(record, low + 1)) {
|
|
5023
|
+
merged[bucket >>> 5] = merged[bucket >>> 5] | 1 << (bucket & 31);
|
|
5024
|
+
}
|
|
5025
|
+
}
|
|
5026
|
+
record.bits = merged;
|
|
5027
|
+
record.scale *= 2;
|
|
5028
|
+
}
|
|
5029
|
+
function stripUndefined2(value) {
|
|
5030
|
+
const out = {};
|
|
5031
|
+
for (const [key, entry] of Object.entries(value)) if (entry !== void 0) out[key] = entry;
|
|
5032
|
+
return out;
|
|
5033
|
+
}
|
|
5034
|
+
var WALK_BUCKETS, DEFAULTS, SiteProfile;
|
|
5035
|
+
var init_site = __esm({
|
|
5036
|
+
"src/site/index.ts"() {
|
|
5037
|
+
"use strict";
|
|
5038
|
+
init_lru();
|
|
5039
|
+
WALK_BUCKETS = 1024;
|
|
5040
|
+
DEFAULTS = {
|
|
5041
|
+
warmupRequests: 5e3,
|
|
5042
|
+
maxPaths: 5e4,
|
|
5043
|
+
maxTemplates: 256,
|
|
5044
|
+
maxActorsPerTemplate: 64,
|
|
5045
|
+
windowMs: 60 * 6e4,
|
|
5046
|
+
maxWatchedPaths: 2048,
|
|
5047
|
+
maxActorsPerPath: 64
|
|
5048
|
+
};
|
|
5049
|
+
SiteProfile = class {
|
|
5050
|
+
options;
|
|
5051
|
+
paths;
|
|
5052
|
+
walks;
|
|
5053
|
+
watched;
|
|
5054
|
+
clock;
|
|
5055
|
+
observed = 0;
|
|
5056
|
+
misses = 0;
|
|
5057
|
+
answered = 0;
|
|
5058
|
+
constructor(options) {
|
|
5059
|
+
this.options = { ...DEFAULTS, ...stripUndefined2(options) };
|
|
5060
|
+
this.paths = new TtlLru(this.options.maxPaths, this.options.windowMs, options.clock);
|
|
5061
|
+
this.walks = new TtlLru(this.options.maxTemplates, this.options.windowMs, options.clock);
|
|
5062
|
+
this.clock = options.clock;
|
|
5063
|
+
this.watched = this.options.maxWatchedPaths > 0 ? new TtlLru(this.options.maxWatchedPaths, this.options.windowMs, options.clock) : void 0;
|
|
5064
|
+
}
|
|
5065
|
+
/**
|
|
5066
|
+
* Whether enough traffic has been seen for any of this to mean anything.
|
|
5067
|
+
*
|
|
5068
|
+
* Every reader checks this. A profile that answers during warmup is worse than one
|
|
5069
|
+
* that does not exist, because it answers confidently and wrongly.
|
|
5070
|
+
*/
|
|
5071
|
+
get warm() {
|
|
5072
|
+
return this.observed >= this.options.warmupRequests;
|
|
5073
|
+
}
|
|
5074
|
+
get requestsObserved() {
|
|
5075
|
+
return this.observed;
|
|
5076
|
+
}
|
|
5077
|
+
/** The share of answered requests that were misses, or `undefined` before warmup. */
|
|
5078
|
+
get missRate() {
|
|
5079
|
+
return this.warm && this.answered > 0 ? this.misses / this.answered : void 0;
|
|
5080
|
+
}
|
|
5081
|
+
/** Files a request. Called once per assessed request, before the detectors run. */
|
|
5082
|
+
record(path, actorKey) {
|
|
5083
|
+
if (this.observed < Number.MAX_SAFE_INTEGER) this.observed++;
|
|
5084
|
+
const seen = this.paths.get(path);
|
|
5085
|
+
this.paths.set(path, (seen ?? 0) + 1);
|
|
5086
|
+
if (this.watched === void 0 || !this.warm) return;
|
|
5087
|
+
let surge = this.watched.get(path);
|
|
5088
|
+
if (surge === void 0) {
|
|
5089
|
+
if (seen !== void 0) return;
|
|
5090
|
+
surge = { actors: /* @__PURE__ */ new Set(), firstSeen: this.clock.now(), answered: 0, misses: 0 };
|
|
5091
|
+
this.watched.set(path, surge);
|
|
5092
|
+
}
|
|
5093
|
+
if (surge.actors.size < this.options.maxActorsPerPath) surge.actors.add(actorKey);
|
|
5094
|
+
}
|
|
5095
|
+
/** Files what the application answered, for the site's miss rate and each watched path. */
|
|
5096
|
+
recordOutcome(path, status) {
|
|
5097
|
+
if (this.answered < Number.MAX_SAFE_INTEGER) this.answered++;
|
|
5098
|
+
const missed = status === 404 || status === 410;
|
|
5099
|
+
if (missed) this.misses++;
|
|
5100
|
+
const surge = this.watched?.get(path);
|
|
5101
|
+
if (surge === void 0) return;
|
|
5102
|
+
surge.answered++;
|
|
5103
|
+
if (missed) surge.misses++;
|
|
5104
|
+
}
|
|
5105
|
+
/** What has happened to a path since it first appeared. `undefined` if not watched. */
|
|
5106
|
+
surgeOf(path) {
|
|
5107
|
+
if (!this.warm) return void 0;
|
|
5108
|
+
const surge = this.watched?.get(path);
|
|
5109
|
+
if (surge === void 0) return void 0;
|
|
5110
|
+
return { clients: surge.actors.size, ageMs: this.clock.now() - surge.firstSeen, answered: surge.answered, misses: surge.misses };
|
|
5111
|
+
}
|
|
5112
|
+
/**
|
|
5113
|
+
* How many times the site has served this path, to anybody.
|
|
5114
|
+
*
|
|
5115
|
+
* `undefined` before warmup, and `0` for a path this process has not seen — which is
|
|
5116
|
+
* not the same as one the site does not have, and is why the detector reading this
|
|
5117
|
+
* needs a great many of them before it says anything.
|
|
5118
|
+
*/
|
|
5119
|
+
timesSeen(path) {
|
|
5120
|
+
return this.warm ? this.paths.get(path) ?? 0 : void 0;
|
|
5121
|
+
}
|
|
5122
|
+
/** Files one step of a numeric walk against the shape it belongs to. */
|
|
5123
|
+
recordWalk(template, id, actorKey) {
|
|
5124
|
+
let record = this.walks.get(template);
|
|
5125
|
+
if (record === void 0) {
|
|
5126
|
+
record = { actors: /* @__PURE__ */ new Set(), bits: new Uint32Array(WALK_BUCKETS / 32), scale: 1, min: id, max: id, visits: 0 };
|
|
5127
|
+
this.walks.set(template, record);
|
|
5128
|
+
}
|
|
5129
|
+
record.visits++;
|
|
5130
|
+
if (record.actors.size < this.options.maxActorsPerTemplate) record.actors.add(actorKey);
|
|
5131
|
+
if (id < record.min) record.min = id;
|
|
5132
|
+
if (id > record.max) record.max = id;
|
|
5133
|
+
while (Math.floor(record.max / record.scale) >= WALK_BUCKETS) coarsen(record);
|
|
5134
|
+
bucketSet(record, Math.floor(id / record.scale));
|
|
5135
|
+
}
|
|
5136
|
+
/** What the whole site has done with one numeric shape. `undefined` before warmup. */
|
|
5137
|
+
spreadOf(template) {
|
|
5138
|
+
if (!this.warm) return void 0;
|
|
5139
|
+
const record = this.walks.get(template);
|
|
5140
|
+
if (record === void 0) return void 0;
|
|
5141
|
+
const lowest = Math.floor(record.min / record.scale);
|
|
5142
|
+
const highest = Math.floor(record.max / record.scale);
|
|
5143
|
+
let touched = 0;
|
|
5144
|
+
for (let bucket = lowest; bucket <= highest; bucket++) if (bucketGet(record, bucket)) touched++;
|
|
5145
|
+
const window = highest - lowest + 1;
|
|
5146
|
+
return {
|
|
5147
|
+
actors: record.actors.size,
|
|
5148
|
+
ids: touched * record.scale,
|
|
5149
|
+
buckets: touched,
|
|
5150
|
+
scale: record.scale,
|
|
5151
|
+
visits: record.visits,
|
|
5152
|
+
coverage: touched / window
|
|
5153
|
+
};
|
|
5154
|
+
}
|
|
5155
|
+
};
|
|
5156
|
+
}
|
|
5157
|
+
});
|
|
5158
|
+
|
|
3995
5159
|
// src/detectors/accept-signature.ts
|
|
3996
5160
|
function acceptSignatureDetector() {
|
|
3997
5161
|
return {
|
|
@@ -4377,49 +5541,280 @@ var init_client_hints = __esm({
|
|
|
4377
5541
|
}
|
|
4378
5542
|
});
|
|
4379
5543
|
|
|
4380
|
-
// src/detectors/crawl-breadth.ts
|
|
4381
|
-
function crawlBreadthDetector(options = {}) {
|
|
4382
|
-
const threshold = options.threshold ?? 30;
|
|
4383
|
-
const noveltyRatio = options.noveltyRatio ?? 0.85;
|
|
4384
|
-
const minRequests = options.minRequests ?? 20;
|
|
4385
|
-
if (threshold > MAX_TRACKED_PATHS) {
|
|
4386
|
-
throw new RangeError(
|
|
4387
|
-
`crawlBreadthDetector threshold ${threshold} can never be reached: an actor's distinct-path count saturates at ${MAX_TRACKED_PATHS}. Use ${MAX_TRACKED_PATHS} or fewer.`
|
|
4388
|
-
);
|
|
4389
|
-
}
|
|
5544
|
+
// src/detectors/crawl-breadth.ts
|
|
5545
|
+
function crawlBreadthDetector(options = {}) {
|
|
5546
|
+
const threshold = options.threshold ?? 30;
|
|
5547
|
+
const noveltyRatio = options.noveltyRatio ?? 0.85;
|
|
5548
|
+
const minRequests = options.minRequests ?? 20;
|
|
5549
|
+
if (threshold > MAX_TRACKED_PATHS) {
|
|
5550
|
+
throw new RangeError(
|
|
5551
|
+
`crawlBreadthDetector threshold ${threshold} can never be reached: an actor's distinct-path count saturates at ${MAX_TRACKED_PATHS}. Use ${MAX_TRACKED_PATHS} or fewer.`
|
|
5552
|
+
);
|
|
5553
|
+
}
|
|
5554
|
+
return {
|
|
5555
|
+
id: "crawl-breadth",
|
|
5556
|
+
description: "Compares distinct paths against total requests to distinguish reading a site from enumerating it",
|
|
5557
|
+
cost: "cheap",
|
|
5558
|
+
stage: "always",
|
|
5559
|
+
inspect(ctx) {
|
|
5560
|
+
const { distinctPaths, total, pathsSaturated } = ctx.state;
|
|
5561
|
+
if (total < minRequests || distinctPaths < threshold) return void 0;
|
|
5562
|
+
const measuredOver = pathsSaturated ? ctx.state.requestsWhenPathsSaturated : total;
|
|
5563
|
+
const ratio = measuredOver > 0 ? distinctPaths / measuredOver : 0;
|
|
5564
|
+
if (ratio < noveltyRatio) return void 0;
|
|
5565
|
+
return {
|
|
5566
|
+
detector: "crawl-breadth",
|
|
5567
|
+
summary: pathsSaturated ? `at least ${distinctPaths} distinct paths, ${(ratio * 100).toFixed(0)}% of the first ${measuredOver} requests never revisited` : `${distinctPaths} distinct paths across ${total} requests (${(ratio * 100).toFixed(0)}% never revisited)`,
|
|
5568
|
+
direction: "bot",
|
|
5569
|
+
certainty: "weak",
|
|
5570
|
+
weight: ctx.state.pathsSaturated ? 0.25 : 0.15,
|
|
5571
|
+
botClass: "scraper",
|
|
5572
|
+
metadata: {
|
|
5573
|
+
distinctPaths,
|
|
5574
|
+
totalRequests: total,
|
|
5575
|
+
noveltyRatio: Number(ratio.toFixed(3)),
|
|
5576
|
+
measuredOverRequests: measuredOver,
|
|
5577
|
+
saturated: pathsSaturated
|
|
5578
|
+
}
|
|
5579
|
+
};
|
|
5580
|
+
}
|
|
5581
|
+
};
|
|
5582
|
+
}
|
|
5583
|
+
var init_crawl_breadth = __esm({
|
|
5584
|
+
"src/detectors/crawl-breadth.ts"() {
|
|
5585
|
+
"use strict";
|
|
5586
|
+
init_state();
|
|
5587
|
+
}
|
|
5588
|
+
});
|
|
5589
|
+
|
|
5590
|
+
// src/detectors/parameter-sweep.ts
|
|
5591
|
+
function parameterSweepDetector(options = {}) {
|
|
5592
|
+
const threshold = options.threshold ?? 25;
|
|
5593
|
+
const variantsPerPath = options.variantsPerPath ?? 8;
|
|
5594
|
+
const minRequests = options.minRequests ?? 20;
|
|
5595
|
+
if (threshold > MAX_TRACKED_QUERIES) {
|
|
5596
|
+
throw new RangeError(
|
|
5597
|
+
`parameterSweepDetector threshold ${threshold} can never be reached: an actor's distinct-query count saturates at ${MAX_TRACKED_QUERIES}. Use ${MAX_TRACKED_QUERIES} or fewer.`
|
|
5598
|
+
);
|
|
5599
|
+
}
|
|
5600
|
+
return {
|
|
5601
|
+
id: "parameter-sweep",
|
|
5602
|
+
description: "Counts distinct query strings against the paths they sit on, to catch enumeration that leaves the path unchanged",
|
|
5603
|
+
cost: "cheap",
|
|
5604
|
+
stage: "always",
|
|
5605
|
+
inspect(ctx) {
|
|
5606
|
+
const { distinctPaths, distinctQueries, queriesSaturated, total } = ctx.state;
|
|
5607
|
+
if (total < minRequests || distinctQueries < threshold) return void 0;
|
|
5608
|
+
const spread = distinctQueries / Math.max(1, distinctPaths);
|
|
5609
|
+
if (spread < variantsPerPath) return void 0;
|
|
5610
|
+
return {
|
|
5611
|
+
detector: "parameter-sweep",
|
|
5612
|
+
summary: queriesSaturated ? `at least ${distinctQueries} distinct query strings across only ${distinctPaths} path(s)` : `${distinctQueries} distinct query strings across only ${distinctPaths} path(s) in ${total} requests`,
|
|
5613
|
+
direction: "bot",
|
|
5614
|
+
certainty: "weak",
|
|
5615
|
+
// Saturation means the count stopped being able to grow, so the real spread is
|
|
5616
|
+
// wider than the one reported — the same argument breadth makes for itself.
|
|
5617
|
+
weight: queriesSaturated ? 0.25 : 0.15,
|
|
5618
|
+
botClass: "scraper",
|
|
5619
|
+
metadata: {
|
|
5620
|
+
distinctQueries,
|
|
5621
|
+
distinctPaths,
|
|
5622
|
+
variantsPerPath: Number(spread.toFixed(1)),
|
|
5623
|
+
totalRequests: total,
|
|
5624
|
+
saturated: queriesSaturated
|
|
5625
|
+
}
|
|
5626
|
+
};
|
|
5627
|
+
}
|
|
5628
|
+
};
|
|
5629
|
+
}
|
|
5630
|
+
var init_parameter_sweep = __esm({
|
|
5631
|
+
"src/detectors/parameter-sweep.ts"() {
|
|
5632
|
+
"use strict";
|
|
5633
|
+
init_state();
|
|
5634
|
+
}
|
|
5635
|
+
});
|
|
5636
|
+
|
|
5637
|
+
// src/detectors/transport-coherence.ts
|
|
5638
|
+
function transportCoherenceDetector(options = {}) {
|
|
5639
|
+
const checkLegacyHttp = options.legacyHttp ?? true;
|
|
5640
|
+
const minHeadRequests = options.minHeadRequests ?? 8;
|
|
5641
|
+
return {
|
|
5642
|
+
id: "transport-coherence",
|
|
5643
|
+
description: "Reads the HTTP version and the methods across a visit against the client the request claims to be",
|
|
5644
|
+
cost: "cheap",
|
|
5645
|
+
stage: "always",
|
|
5646
|
+
inspect(ctx) {
|
|
5647
|
+
if (!claimsBrowser(ctx.ua)) return void 0;
|
|
5648
|
+
const results = [];
|
|
5649
|
+
const version = ctx.facts.httpVersion;
|
|
5650
|
+
if (checkLegacyHttp && version !== void 0 && LEGACY_VERSIONS.has(version)) {
|
|
5651
|
+
results.push({
|
|
5652
|
+
detector: "transport-coherence",
|
|
5653
|
+
summary: `Client claims to be a browser but negotiated HTTP/${version}, which no shipping browser has offered in over a decade`,
|
|
5654
|
+
direction: "bot",
|
|
5655
|
+
certainty: "moderate",
|
|
5656
|
+
botClass: "impersonator",
|
|
5657
|
+
// One downgrading proxy in front of the application does this to every request
|
|
5658
|
+
// that passes through it, so this must count once rather than once per reason.
|
|
5659
|
+
family: "legacy-transport",
|
|
5660
|
+
metadata: { httpVersion: version, browser: ctx.ua.browser }
|
|
5661
|
+
});
|
|
5662
|
+
}
|
|
5663
|
+
const methods = ctx.state.methodsSeen;
|
|
5664
|
+
if (ctx.state.total >= minHeadRequests && methods.length > 0 && methods.every((method) => method === "HEAD")) {
|
|
5665
|
+
results.push({
|
|
5666
|
+
detector: "transport-coherence",
|
|
5667
|
+
summary: `Client claims to be a browser but has issued nothing but HEAD across ${ctx.state.total} requests`,
|
|
5668
|
+
direction: "bot",
|
|
5669
|
+
certainty: "moderate",
|
|
5670
|
+
botClass: "scraper",
|
|
5671
|
+
metadata: { requests: ctx.state.total, browser: ctx.ua.browser }
|
|
5672
|
+
});
|
|
5673
|
+
}
|
|
5674
|
+
return results.length > 0 ? results : void 0;
|
|
5675
|
+
}
|
|
5676
|
+
};
|
|
5677
|
+
}
|
|
5678
|
+
var LEGACY_VERSIONS;
|
|
5679
|
+
var init_transport_coherence = __esm({
|
|
5680
|
+
"src/detectors/transport-coherence.ts"() {
|
|
5681
|
+
"use strict";
|
|
5682
|
+
init_ua();
|
|
5683
|
+
LEGACY_VERSIONS = /* @__PURE__ */ new Set(["0.9", "1.0"]);
|
|
5684
|
+
}
|
|
5685
|
+
});
|
|
5686
|
+
|
|
5687
|
+
// src/detectors/probe-volume.ts
|
|
5688
|
+
function probeVolumeDetector(options = {}) {
|
|
5689
|
+
const minResponses = options.minResponses ?? 20;
|
|
5690
|
+
const missRatio = options.missRatio ?? 0.8;
|
|
5691
|
+
return {
|
|
5692
|
+
id: "probe-volume",
|
|
5693
|
+
description: "Reads the share of an actor's requests that were answered 404 or 410, where the application reports them",
|
|
5694
|
+
cost: "cheap",
|
|
5695
|
+
stage: "always",
|
|
5696
|
+
inspect(ctx) {
|
|
5697
|
+
const { responses, misses } = ctx.state;
|
|
5698
|
+
if (responses < minResponses) return void 0;
|
|
5699
|
+
const ratio = misses / responses;
|
|
5700
|
+
if (ratio < missRatio) return void 0;
|
|
5701
|
+
return {
|
|
5702
|
+
detector: "probe-volume",
|
|
5703
|
+
summary: `${misses} of this client's last ${responses} requests were answered "not found" (${(ratio * 100).toFixed(0)}%)`,
|
|
5704
|
+
direction: "bot",
|
|
5705
|
+
certainty: "moderate",
|
|
5706
|
+
botClass: "scanner",
|
|
5707
|
+
// `miss-baseline` reads the same misses relative to the site's own rate. One
|
|
5708
|
+
// cause, so the stronger reading stands rather than the two summing.
|
|
5709
|
+
family: "misses",
|
|
5710
|
+
metadata: { responses, misses, missRatio: Number(ratio.toFixed(3)) }
|
|
5711
|
+
};
|
|
5712
|
+
}
|
|
5713
|
+
};
|
|
5714
|
+
}
|
|
5715
|
+
var init_probe_volume = __esm({
|
|
5716
|
+
"src/detectors/probe-volume.ts"() {
|
|
5717
|
+
"use strict";
|
|
5718
|
+
}
|
|
5719
|
+
});
|
|
5720
|
+
|
|
5721
|
+
// src/detectors/id-enumeration.ts
|
|
5722
|
+
function idEnumerationDetector(options = {}) {
|
|
5723
|
+
const minRequests = options.minRequests ?? 30;
|
|
5724
|
+
const density = options.density ?? 0.9;
|
|
4390
5725
|
return {
|
|
4391
|
-
id: "
|
|
4392
|
-
description: "
|
|
5726
|
+
id: "id-enumeration",
|
|
5727
|
+
description: "Reports an actor covering a contiguous range of numeric identifiers under one path shape",
|
|
4393
5728
|
cost: "cheap",
|
|
4394
5729
|
stage: "always",
|
|
4395
5730
|
inspect(ctx) {
|
|
4396
|
-
const
|
|
4397
|
-
if (
|
|
4398
|
-
|
|
4399
|
-
const
|
|
4400
|
-
if (
|
|
5731
|
+
const walk = ctx.state.densestWalk();
|
|
5732
|
+
if (walk === void 0 || walk.count < minRequests) return void 0;
|
|
5733
|
+
if (walk.span < minRequests) return void 0;
|
|
5734
|
+
const covered = Math.min(1, walk.count / walk.span);
|
|
5735
|
+
if (covered < density) return void 0;
|
|
4401
5736
|
return {
|
|
4402
|
-
detector: "
|
|
4403
|
-
summary:
|
|
5737
|
+
detector: "id-enumeration",
|
|
5738
|
+
summary: `${walk.count} requests to ${walk.template} covering ${(covered * 100).toFixed(0)}% of a ${walk.span}-wide range of ids`,
|
|
4404
5739
|
direction: "bot",
|
|
4405
|
-
certainty: "
|
|
4406
|
-
weight: ctx.state.pathsSaturated ? 0.25 : 0.15,
|
|
5740
|
+
certainty: "moderate",
|
|
4407
5741
|
botClass: "scraper",
|
|
4408
|
-
metadata: {
|
|
4409
|
-
distinctPaths,
|
|
4410
|
-
totalRequests: total,
|
|
4411
|
-
noveltyRatio: Number(ratio.toFixed(3)),
|
|
4412
|
-
measuredOverRequests: measuredOver,
|
|
4413
|
-
saturated: pathsSaturated
|
|
4414
|
-
}
|
|
5742
|
+
metadata: { template: walk.template, requests: walk.count, span: walk.span, coverage: Number(covered.toFixed(3)) }
|
|
4415
5743
|
};
|
|
4416
5744
|
}
|
|
4417
5745
|
};
|
|
4418
5746
|
}
|
|
4419
|
-
var
|
|
4420
|
-
"src/detectors/
|
|
5747
|
+
var init_id_enumeration = __esm({
|
|
5748
|
+
"src/detectors/id-enumeration.ts"() {
|
|
5749
|
+
"use strict";
|
|
5750
|
+
}
|
|
5751
|
+
});
|
|
5752
|
+
|
|
5753
|
+
// src/detectors/blended-identity.ts
|
|
5754
|
+
function blendedIdentityDetector(options = {}) {
|
|
5755
|
+
const scannerFloor = options.scannerIdentities ?? 2;
|
|
5756
|
+
const crawlerFloor = options.crawlerIdentities ?? 2;
|
|
5757
|
+
return {
|
|
5758
|
+
id: "blended-identity",
|
|
5759
|
+
description: "Reads the set of identities one actor has claimed across requests for combinations that cannot all be true",
|
|
5760
|
+
cost: "cheap",
|
|
5761
|
+
stage: "always",
|
|
5762
|
+
inspect(ctx) {
|
|
5763
|
+
const claimed = ctx.state.claimedIdentities;
|
|
5764
|
+
if (claimed.size === 0) return void 0;
|
|
5765
|
+
const scanners = [];
|
|
5766
|
+
const crawlers = [];
|
|
5767
|
+
const benignCrawlers = [];
|
|
5768
|
+
for (const [id, what] of claimed) {
|
|
5769
|
+
if (what.category === "security") scanners.push(id);
|
|
5770
|
+
if (what.verifiable) crawlers.push(id);
|
|
5771
|
+
if (what.category === "search" || what.category === "ai" || what.category === "social") benignCrawlers.push(id);
|
|
5772
|
+
}
|
|
5773
|
+
const results = [];
|
|
5774
|
+
if (scanners.length >= scannerFloor) {
|
|
5775
|
+
results.push({
|
|
5776
|
+
detector: "blended-identity",
|
|
5777
|
+
summary: `One client has arrived as ${scanners.length} different security tools: ${scanners.join(", ")}`,
|
|
5778
|
+
direction: "bot",
|
|
5779
|
+
certainty: "strong",
|
|
5780
|
+
weight: 0.7,
|
|
5781
|
+
botClass: "scanner",
|
|
5782
|
+
metadata: { identities: scanners }
|
|
5783
|
+
});
|
|
5784
|
+
}
|
|
5785
|
+
if (crawlers.length >= crawlerFloor) {
|
|
5786
|
+
results.push({
|
|
5787
|
+
detector: "blended-identity",
|
|
5788
|
+
summary: `One client has claimed ${crawlers.length} crawler identities that publish address proofs: ${crawlers.join(", ")}`,
|
|
5789
|
+
direction: "bot",
|
|
5790
|
+
certainty: "strong",
|
|
5791
|
+
weight: 0.7,
|
|
5792
|
+
botClass: "impersonator",
|
|
5793
|
+
// Not `certain`, and the line is worth holding. Each operator publishes a proof
|
|
5794
|
+
// tied to addresses it controls, so at most one claim can be true — but a shared
|
|
5795
|
+
// egress in front of two genuinely different clients would produce the same set,
|
|
5796
|
+
// and this library refuses to deny anybody on an inference.
|
|
5797
|
+
metadata: { identities: crawlers }
|
|
5798
|
+
});
|
|
5799
|
+
}
|
|
5800
|
+
if (ctx.state.payloadProbes > 0 && benignCrawlers.length > 0) {
|
|
5801
|
+
results.push({
|
|
5802
|
+
detector: "blended-identity",
|
|
5803
|
+
summary: `Client claims to be ${benignCrawlers.join(", ")} and has sent ${ctx.state.payloadProbes} scanner payload(s)`,
|
|
5804
|
+
direction: "bot",
|
|
5805
|
+
certainty: "strong",
|
|
5806
|
+
weight: 0.75,
|
|
5807
|
+
botClass: "impersonator",
|
|
5808
|
+
metadata: { identities: benignCrawlers, payloadProbes: ctx.state.payloadProbes }
|
|
5809
|
+
});
|
|
5810
|
+
}
|
|
5811
|
+
return results.length > 0 ? results : void 0;
|
|
5812
|
+
}
|
|
5813
|
+
};
|
|
5814
|
+
}
|
|
5815
|
+
var init_blended_identity = __esm({
|
|
5816
|
+
"src/detectors/blended-identity.ts"() {
|
|
4421
5817
|
"use strict";
|
|
4422
|
-
init_state();
|
|
4423
5818
|
}
|
|
4424
5819
|
});
|
|
4425
5820
|
|
|
@@ -5003,14 +6398,16 @@ function findPayload(path, query) {
|
|
|
5003
6398
|
for (const { pattern, what, tier } of PAYLOADS) {
|
|
5004
6399
|
if (pattern.test(path)) return { what, where: "path", sample: path, tier };
|
|
5005
6400
|
}
|
|
5006
|
-
for (const
|
|
6401
|
+
for (const key in query) {
|
|
6402
|
+
const value = query[key];
|
|
6403
|
+
if (!PAYLOAD_GATE.test(value)) continue;
|
|
5007
6404
|
for (const { pattern, what, tier } of PAYLOADS) {
|
|
5008
6405
|
if (pattern.test(value)) return { what, where: `query parameter "${key.slice(0, 40)}"`, sample: value, tier };
|
|
5009
6406
|
}
|
|
5010
6407
|
}
|
|
5011
6408
|
return void 0;
|
|
5012
6409
|
}
|
|
5013
|
-
var EXPLOIT_PATHS, EXPLOIT_SUFFIXES, PLATFORM_PATHS, PAYLOADS, INJECTION_PUNCTUATION, PROBE_METHODS;
|
|
6410
|
+
var EXPLOIT_PATHS, EXPLOIT_SUFFIXES, PLATFORM_PATHS, PAYLOADS, PAYLOAD_GATE, INJECTION_PUNCTUATION, PROBE_METHODS;
|
|
5014
6411
|
var init_probe_signature = __esm({
|
|
5015
6412
|
"src/detectors/probe-signature.ts"() {
|
|
5016
6413
|
"use strict";
|
|
@@ -5084,11 +6481,74 @@ var init_probe_signature = __esm({
|
|
|
5084
6481
|
{ pattern: /<script[\s>]/i, what: "an inline script tag", tier: "markup" },
|
|
5085
6482
|
{ pattern: /\bon(?:error|load|mouseover)\s*=/i, what: "an inline event handler", tier: "markup" }
|
|
5086
6483
|
];
|
|
6484
|
+
PAYLOAD_GATE = /[$`:(<=\s]/;
|
|
5087
6485
|
INJECTION_PUNCTUATION = /['"]|--\s|\/\*|;|%27|%22/;
|
|
5088
6486
|
PROBE_METHODS = /* @__PURE__ */ new Set(["TRACE", "TRACK", "DEBUG", "CONNECT"]);
|
|
5089
6487
|
}
|
|
5090
6488
|
});
|
|
5091
6489
|
|
|
6490
|
+
// src/detectors/target-integrity.ts
|
|
6491
|
+
function targetIntegrityDetector(options = {}) {
|
|
6492
|
+
const reportPlain = options.reportPlainTraversal ?? true;
|
|
6493
|
+
return {
|
|
6494
|
+
id: "target-integrity",
|
|
6495
|
+
description: "Reports a request target spelled to get past something rather than to fetch something",
|
|
6496
|
+
cost: "cheap",
|
|
6497
|
+
stage: "always",
|
|
6498
|
+
inspect(ctx) {
|
|
6499
|
+
const raw = ctx.facts.rawPath;
|
|
6500
|
+
if (raw === void 0) return void 0;
|
|
6501
|
+
const findings = [];
|
|
6502
|
+
if (ABSOLUTE_FORM.test(raw)) {
|
|
6503
|
+
findings.push({ what: "asked this server to fetch a URL elsewhere, which is a request addressed to a proxy", certainty: "strong" });
|
|
6504
|
+
}
|
|
6505
|
+
if (DOUBLE_ENCODED.test(raw)) {
|
|
6506
|
+
findings.push({ what: "encoded its own encoding, so one round of decoding leaves it still encoded", certainty: "strong" });
|
|
6507
|
+
}
|
|
6508
|
+
if (ENCODED_CONTROL.test(raw)) {
|
|
6509
|
+
findings.push({ what: "carried a control character in the target", certainty: "strong" });
|
|
6510
|
+
}
|
|
6511
|
+
if (TRAVERSAL.test(raw)) {
|
|
6512
|
+
if (ENCODED_SEPARATOR.test(raw)) {
|
|
6513
|
+
findings.push({ what: "spelled the dots and slashes of a directory traversal in percent-encoding", certainty: "strong" });
|
|
6514
|
+
} else if (reportPlain) {
|
|
6515
|
+
findings.push({ what: "walked up out of the site root", certainty: "moderate" });
|
|
6516
|
+
}
|
|
6517
|
+
} else if (ENCODED_SLASH.test(raw)) {
|
|
6518
|
+
findings.push({ what: "hid a path separator inside a segment by encoding it", certainty: "moderate" });
|
|
6519
|
+
}
|
|
6520
|
+
if (findings.length === 0) return void 0;
|
|
6521
|
+
const certainty = findings.some((finding) => finding.certainty === "strong") ? "strong" : "moderate";
|
|
6522
|
+
const what = findings.map((finding) => finding.what);
|
|
6523
|
+
const listed = what.length === 1 ? what[0] : `${what.slice(0, -1).join(", ")}, and ${what[what.length - 1]}`;
|
|
6524
|
+
return {
|
|
6525
|
+
detector: "target-integrity",
|
|
6526
|
+
summary: `The request target ${listed}`,
|
|
6527
|
+
direction: "bot",
|
|
6528
|
+
certainty,
|
|
6529
|
+
botClass: "scanner",
|
|
6530
|
+
// One act, however many ways it shows. A traversal is usually encoded and an
|
|
6531
|
+
// encoded traversal is often double-encoded; compounding them would turn one
|
|
6532
|
+
// request into three independent reasons to be suspicious.
|
|
6533
|
+
family: "evasive-target",
|
|
6534
|
+
metadata: { target: raw.length > 200 ? `${raw.slice(0, 200)}\u2026` : raw }
|
|
6535
|
+
};
|
|
6536
|
+
}
|
|
6537
|
+
};
|
|
6538
|
+
}
|
|
6539
|
+
var ENCODED_SEPARATOR, ENCODED_SLASH, DOUBLE_ENCODED, ENCODED_CONTROL, TRAVERSAL, ABSOLUTE_FORM;
|
|
6540
|
+
var init_target_integrity = __esm({
|
|
6541
|
+
"src/detectors/target-integrity.ts"() {
|
|
6542
|
+
"use strict";
|
|
6543
|
+
ENCODED_SEPARATOR = /%2e|%2f|%5c/i;
|
|
6544
|
+
ENCODED_SLASH = /%2f|%5c/i;
|
|
6545
|
+
DOUBLE_ENCODED = /%25[0-9a-f]{2}/i;
|
|
6546
|
+
ENCODED_CONTROL = /%0[0-9a-f]|%1[0-9a-f]|%7f/i;
|
|
6547
|
+
TRAVERSAL = /\.\.|%2e%2e|%2e\.|\.%2e/i;
|
|
6548
|
+
ABSOLUTE_FORM = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
6549
|
+
}
|
|
6550
|
+
});
|
|
6551
|
+
|
|
5092
6552
|
// src/detectors/rate-anomaly.ts
|
|
5093
6553
|
function rateAnomalyDetector(options = {}) {
|
|
5094
6554
|
const windowMs = options.windowMs ?? 1e4;
|
|
@@ -5591,20 +7051,26 @@ function defaultDetectors(options = {}) {
|
|
|
5591
7051
|
// Identity first: a self-declaration or a verified crawler settles the question
|
|
5592
7052
|
// outright, and the engine can then skip everything that would only add nuance.
|
|
5593
7053
|
selfIdentifiedDetector(),
|
|
7054
|
+
blendedIdentityDetector(),
|
|
5594
7055
|
trapDetector(),
|
|
5595
7056
|
ipIntelligenceDetector(),
|
|
5596
7057
|
probeSignatureDetector(),
|
|
7058
|
+
targetIntegrityDetector(),
|
|
5597
7059
|
// Single-request consistency.
|
|
5598
7060
|
headerIntegrityDetector(),
|
|
5599
7061
|
uaCoherenceDetector(),
|
|
5600
7062
|
clientHintsDetector(),
|
|
5601
7063
|
fetchMetadataDetector(),
|
|
5602
7064
|
acceptSignatureDetector(),
|
|
7065
|
+
transportCoherenceDetector(),
|
|
5603
7066
|
headerOrderDetector(),
|
|
5604
7067
|
// Behaviour across requests.
|
|
5605
7068
|
rateAnomalyDetector(),
|
|
5606
7069
|
cadenceDetector(),
|
|
5607
7070
|
crawlBreadthDetector(),
|
|
7071
|
+
parameterSweepDetector(),
|
|
7072
|
+
probeVolumeDetector(),
|
|
7073
|
+
idEnumerationDetector(),
|
|
5608
7074
|
sessionIntegrityDetector(),
|
|
5609
7075
|
// The other side of the argument: what a real browsing session looks like.
|
|
5610
7076
|
browsingCoherenceDetector(),
|
|
@@ -5620,12 +7086,18 @@ var init_detectors = __esm({
|
|
|
5620
7086
|
init_cadence();
|
|
5621
7087
|
init_client_hints();
|
|
5622
7088
|
init_crawl_breadth();
|
|
7089
|
+
init_parameter_sweep();
|
|
7090
|
+
init_transport_coherence();
|
|
7091
|
+
init_probe_volume();
|
|
7092
|
+
init_id_enumeration();
|
|
7093
|
+
init_blended_identity();
|
|
5623
7094
|
init_crawler_verification();
|
|
5624
7095
|
init_fetch_metadata();
|
|
5625
7096
|
init_header_integrity();
|
|
5626
7097
|
init_header_order();
|
|
5627
7098
|
init_ip_intelligence();
|
|
5628
7099
|
init_probe_signature();
|
|
7100
|
+
init_target_integrity();
|
|
5629
7101
|
init_rate_anomaly();
|
|
5630
7102
|
init_self_identified();
|
|
5631
7103
|
init_session_integrity();
|
|
@@ -5881,6 +7353,7 @@ function resolveConfig(config = {}) {
|
|
|
5881
7353
|
}
|
|
5882
7354
|
seen.add(detector.id);
|
|
5883
7355
|
}
|
|
7356
|
+
const shadowDetectors = new Set(config.shadowDetectors ?? []);
|
|
5884
7357
|
const rules = [...config.rules ?? []];
|
|
5885
7358
|
if (config.preset !== void 0) {
|
|
5886
7359
|
const preset = PRESETS[config.preset];
|
|
@@ -5909,6 +7382,36 @@ function resolveConfig(config = {}) {
|
|
|
5909
7382
|
if (proxyConfig.trustProxy !== true && (trustedProxies !== void 0 || proxyConfig.hops !== void 0)) {
|
|
5910
7383
|
warnings.push("proxy.trustedProxies / proxy.hops are configured but proxy.trustProxy is not enabled, so the forwarded header is ignored and the socket address is used.");
|
|
5911
7384
|
}
|
|
7385
|
+
if (config.probe !== void 0) {
|
|
7386
|
+
if (config.probe.cookieName !== void 0 && config.probe.cookieName === config.challenge?.cookieName) {
|
|
7387
|
+
throw new ConfigError(
|
|
7388
|
+
`probe.cookieName and challenge.cookieName are both "${config.probe.cookieName}". One would overwrite the other on every response, so clearance and the marker would each destroy the other.`
|
|
7389
|
+
);
|
|
7390
|
+
}
|
|
7391
|
+
if (config.probe.secure === false) {
|
|
7392
|
+
warnings.push(
|
|
7393
|
+
"probe.secure is false, so the marker cookie will travel over plain HTTP and can be read by anything on the path. It is meant for local development; leave it unset in production."
|
|
7394
|
+
);
|
|
7395
|
+
}
|
|
7396
|
+
if (config.probe.domain !== void 0 && config.probe.domain.startsWith(".") === false && config.probe.domain.includes(".") === false) {
|
|
7397
|
+
warnings.push(`probe.domain is "${config.probe.domain}", which is not a domain a browser will accept, so the marker will never be stored or returned.`);
|
|
7398
|
+
}
|
|
7399
|
+
if (config.probe.ttlMs !== void 0 && config.probe.ttlMs < 6e4) {
|
|
7400
|
+
warnings.push(
|
|
7401
|
+
`probe.ttlMs is ${config.probe.ttlMs}ms. A marker that expires within a minute is re-issued on almost every request, which makes responses uncacheable and leaves nothing long enough to correlate.`
|
|
7402
|
+
);
|
|
7403
|
+
}
|
|
7404
|
+
}
|
|
7405
|
+
if (config.site !== void 0 && config.site.warmupRequests !== void 0 && config.site.warmupRequests < 500) {
|
|
7406
|
+
warnings.push(
|
|
7407
|
+
`site.warmupRequests is ${config.site.warmupRequests}. A baseline drawn from so little traffic is not one \u2014 every path is rare when nothing has been seen \u2014 so the site detectors will report ordinary visitors until real traffic arrives.`
|
|
7408
|
+
);
|
|
7409
|
+
}
|
|
7410
|
+
if (config.actorKey === void 0 && detectors2.some((detector) => detector.id === "identity-rotation")) {
|
|
7411
|
+
warnings.push(
|
|
7412
|
+
"identity-rotation is enabled while `actorKey` is left as the client address, so one actor means one address. A NAT gateway \u2014 an office, a campus, a mobile carrier \u2014 presents many people's browsers under a single address, which is this detector's exact signature and is entirely innocent. Give `actorKey` something narrower than an address (a session cookie, an authenticated user id, or an address combined with a TLS fingerprint), or take the detector out."
|
|
7413
|
+
);
|
|
7414
|
+
}
|
|
5912
7415
|
const strictEvidence = config.strictEvidence ?? process.env["NODE_ENV"] !== "production";
|
|
5913
7416
|
const falsePositivePolicy = config.falsePositivePolicy ?? "strict";
|
|
5914
7417
|
if (falsePositivePolicy === "aggressive") {
|
|
@@ -5923,6 +7426,7 @@ function resolveConfig(config = {}) {
|
|
|
5923
7426
|
}
|
|
5924
7427
|
return {
|
|
5925
7428
|
detectors: detectors2,
|
|
7429
|
+
shadowDetectors,
|
|
5926
7430
|
rules,
|
|
5927
7431
|
ranges,
|
|
5928
7432
|
signatures,
|
|
@@ -5960,11 +7464,11 @@ function clamp(value, min, max) {
|
|
|
5960
7464
|
return Math.min(max, Math.max(min, value));
|
|
5961
7465
|
}
|
|
5962
7466
|
function resolveClientIp(socketAddress, headers, proxy) {
|
|
5963
|
-
const direct = socketAddress !== void 0 ? normalizeIp(socketAddress) ?? socketAddress : "";
|
|
7467
|
+
const direct = socketAddress !== void 0 ? normalizeIp(stripPort(socketAddress)) ?? socketAddress : "";
|
|
5964
7468
|
if (!proxy.trustProxy) return direct;
|
|
5965
7469
|
const header = headers[proxy.header];
|
|
5966
7470
|
if (header === void 0) return direct;
|
|
5967
|
-
const chain = header.slice(0, 2048).split(",").map((entry) => entry
|
|
7471
|
+
const chain = header.slice(0, 2048).split(",").map((entry) => stripPort(entry)).filter((entry) => entry.length > 0 && parseIp(entry) !== null).map((entry) => normalizeIp(entry));
|
|
5968
7472
|
if (chain.length === 0) return direct;
|
|
5969
7473
|
if (proxy.trustedProxies) {
|
|
5970
7474
|
if (direct !== "" && !proxy.trustedProxies.contains(direct)) return direct;
|
|
@@ -6221,11 +7725,15 @@ var init_feed = __esm({
|
|
|
6221
7725
|
certain: assessment.certain,
|
|
6222
7726
|
durationMs: Number(assessment.durationMs.toFixed(3)),
|
|
6223
7727
|
bypass: assessment.bypass,
|
|
6224
|
-
|
|
7728
|
+
// Shadowed findings ride in the same list, flagged. They belong on the same screen
|
|
7729
|
+
// as the evidence that did decide — the comparison is the point — and the flag is
|
|
7730
|
+
// what stops the page, and `previewAssessment`, from treating them as such.
|
|
7731
|
+
evidence: [...assessment.evidence, ...assessment.humanEvidence, ...assessment.shadowEvidence].map((item) => ({
|
|
6225
7732
|
detector: item.detector,
|
|
6226
7733
|
summary: item.summary,
|
|
6227
7734
|
certainty: item.certainty,
|
|
6228
7735
|
direction: item.direction,
|
|
7736
|
+
...item.shadow === true ? { shadow: true } : {},
|
|
6229
7737
|
family: item.family,
|
|
6230
7738
|
deterministicBasis: item.deterministicBasis,
|
|
6231
7739
|
identity: item.identity,
|
|
@@ -6234,6 +7742,7 @@ var init_feed = __esm({
|
|
|
6234
7742
|
category: typeof item.metadata?.["category"] === "string" ? item.metadata["category"] : void 0,
|
|
6235
7743
|
weight: item.weight
|
|
6236
7744
|
})),
|
|
7745
|
+
...assessment.shadowVerdict === void 0 ? {} : { shadowVerdict: assessment.shadowVerdict },
|
|
6237
7746
|
failures: assessment.failures.map((failure) => ({ detector: failure.detector, reason: failure.reason, message: failure.message })),
|
|
6238
7747
|
actorStats: {
|
|
6239
7748
|
requests: assessment.actor.requests,
|
|
@@ -6443,6 +7952,7 @@ function isDenial(action) {
|
|
|
6443
7952
|
function assessmentFromEntry(entry) {
|
|
6444
7953
|
const evidence = [];
|
|
6445
7954
|
const humanEvidence = [];
|
|
7955
|
+
const shadowEvidence = [];
|
|
6446
7956
|
for (const item of entry.evidence) {
|
|
6447
7957
|
const rebuilt = {
|
|
6448
7958
|
detector: item.detector,
|
|
@@ -6453,9 +7963,11 @@ function assessmentFromEntry(entry) {
|
|
|
6453
7963
|
...item.identity !== void 0 ? { identity: item.identity } : {},
|
|
6454
7964
|
...item.family !== void 0 ? { family: item.family } : {},
|
|
6455
7965
|
// `category` is read off metadata by the matcher, so it has to go back there.
|
|
6456
|
-
...item.category !== void 0 ? { metadata: { category: item.category } } : {}
|
|
7966
|
+
...item.category !== void 0 ? { metadata: { category: item.category } } : {},
|
|
7967
|
+
...item.shadow === true ? { shadow: true } : {}
|
|
6457
7968
|
};
|
|
6458
|
-
(item.
|
|
7969
|
+
if (item.shadow === true) shadowEvidence.push(rebuilt);
|
|
7970
|
+
else (item.direction === "human" ? humanEvidence : evidence).push(rebuilt);
|
|
6459
7971
|
}
|
|
6460
7972
|
return {
|
|
6461
7973
|
requestId: entry.requestId,
|
|
@@ -6467,10 +7979,17 @@ function assessmentFromEntry(entry) {
|
|
|
6467
7979
|
certain: entry.certain,
|
|
6468
7980
|
evidence,
|
|
6469
7981
|
humanEvidence,
|
|
7982
|
+
shadowEvidence,
|
|
7983
|
+
...entry.shadowVerdict === void 0 ? {} : { shadowVerdict: entry.shadowVerdict },
|
|
6470
7984
|
actor: {
|
|
6471
7985
|
key: entry.actor,
|
|
6472
7986
|
requests: entry.actorStats.requests,
|
|
6473
7987
|
distinctPaths: entry.actorStats.distinctPaths,
|
|
7988
|
+
distinctQueries: 0,
|
|
7989
|
+
queriesSaturated: false,
|
|
7990
|
+
methodsSeen: ["GET"],
|
|
7991
|
+
responses: 0,
|
|
7992
|
+
misses: 0,
|
|
6474
7993
|
firstSeen: entry.actorStats.firstSeen,
|
|
6475
7994
|
lastSeen: entry.at,
|
|
6476
7995
|
...entry.actorStats.sinceLastMs !== void 0 ? { sinceLastMs: entry.actorStats.sinceLastMs } : {},
|
|
@@ -6519,7 +8038,7 @@ var CLIENT_SCRIPT;
|
|
|
6519
8038
|
var init_client_generated = __esm({
|
|
6520
8039
|
"src/dashboard/client.generated.ts"() {
|
|
6521
8040
|
"use strict";
|
|
6522
|
-
CLIENT_SCRIPT = '"use strict";\n(() => {\n // src/dashboard/client/css.ts\n function cssEscape(value) {\n return typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : String(value).replace(/[^\\w-]/g, "\\\\$&");\n }\n\n // src/dashboard/client/dom.ts\n function el(tag, className, value) {\n const node = document.createElement(tag);\n if (className !== void 0 && className !== null && className !== "") node.className = className;\n if (value !== void 0 && value !== null) node.textContent = String(value);\n return node;\n }\n function svgEl(name, attributes = {}) {\n const node = document.createElementNS("http://www.w3.org/2000/svg", name);\n for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));\n return node;\n }\n function svgText(attributes, text) {\n const node = svgEl("text", attributes);\n node.textContent = String(text);\n return node;\n }\n function clear(node) {\n while (node.firstChild) node.removeChild(node.firstChild);\n }\n var root = typeof document === "undefined" ? void 0 : document;\n var themeHost = typeof document === "undefined" ? void 0 : document.documentElement;\n var embedded = false;\n function isEmbedded() {\n return embedded;\n }\n function eventTarget() {\n return embedded ? root : globalThis;\n }\n function rootNode() {\n return root;\n }\n function themeElement() {\n return themeHost;\n }\n function $(id) {\n const node = root.querySelector(`#${cssEscape(id)}`);\n if (node === null || node === void 0) throw new Error(`dashboard: no element #${id}`);\n return node;\n }\n function byId(id) {\n return $(id);\n }\n function css(name) {\n return getComputedStyle(themeHost).getPropertyValue(name).trim();\n }\n var sequence = 0;\n function label(text, control) {\n const node = document.createElement("label");\n node.textContent = text;\n const single = Array.isArray(control) ? control.length === 1 ? control[0] : void 0 : control;\n if (single !== void 0 && /^(input|select|textarea)$/i.test(single.tagName)) {\n if (single.id === "") single.id = `field-${++sequence}`;\n node.htmlFor = single.id;\n } else {\n const group = Array.isArray(control) ? control : [control];\n for (const node_ of group) if (!node_.hasAttribute("aria-label")) node_.setAttribute("aria-label", text);\n }\n return node;\n }\n\n // src/dashboard/client/boot.ts\n var raw = globalThis.__BOOTSTRAP__;\n var BOOT = raw ?? {\n base: "",\n title: "bothandlerjs",\n allowReset: false,\n allowEdit: false,\n allowGuardEdit: false,\n allowActing: false,\n peers: [],\n sections: { feed: true, evidence: true, actors: true, registry: true, tester: true, statistics: true, audit: true, notices: true, changes: true, policy: true, guard: true, robots: true, ranges: true },\n links: []\n };\n var API = BOOT.base;\n var SECTIONS = BOOT.sections;\n\n // src/dashboard/client/app.ts\n var app = {\n draw: () => {\n },\n drawNow: () => {\n },\n showTab: () => {\n },\n syncUrl: () => {\n }\n };\n function toast(kind, title, detail = "") {\n const node = el("div", `toast ${kind}`);\n node.appendChild(el("b", null, title));\n if (detail !== "") node.appendChild(el("span", null, detail));\n const host = rootNode().querySelector("#toasts");\n if (host === null) return;\n host.appendChild(node);\n setTimeout(() => node.remove(), 6e3);\n }\n function download(text, filename, type) {\n const blob = new Blob([text], { type });\n const url = URL.createObjectURL(blob);\n const anchor = el("a");\n anchor.href = url;\n anchor.download = filename;\n anchor.click();\n setTimeout(() => URL.revokeObjectURL(url), 1e3);\n }\n function today() {\n return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);\n }\n\n // src/dashboard/client/outcome.ts\n var DENY = /* @__PURE__ */ new Set(["block", "drop", "redirect"]);\n var MITIGATE = /* @__PURE__ */ new Set(["challenge", "rate-limit", "delay"]);\n function outcome(entry) {\n return actionKind(entry.action);\n }\n function actionKind(action) {\n if (action === void 0) return "pending";\n if (DENY.has(action)) return "deny";\n if (MITIGATE.has(action)) return "mitigate";\n return "allow";\n }\n function verdictBadge(entry) {\n if (entry.verdict === "verified-bot" || entry.verdict === "confirmed-bot") return ["b-proven", entry.verdict];\n if (entry.verdict === "suspected-bot") return ["b-suspected", "suspected-bot"];\n if (entry.verdict === "human") return ["b-human", "human"];\n return ["b-unknown", entry.bypass !== void 0 ? `skipped \xB7 ${entry.bypass}` : "unknown"];\n }\n function provenBots(verdicts) {\n return (verdicts["confirmed-bot"] ?? 0) + (verdicts["verified-bot"] ?? 0);\n }\n\n // src/dashboard/client/query.ts\n var FIELDS = {\n path: "path",\n url: "path",\n actor: "actor",\n ip: "actor",\n ua: "userAgent",\n useragent: "userAgent",\n agent: "userAgent",\n verdict: "verdict",\n action: "action",\n rule: "rule",\n detector: "detector",\n identity: "identity",\n method: "method",\n class: "botClass",\n botclass: "botClass",\n id: "requestId",\n request: "requestId",\n bypass: "bypass",\n score: "score",\n outcome: "outcome",\n certain: "certain"\n };\n var NUMERIC = /* @__PURE__ */ new Set(["score"]);\n function tokenize(input) {\n const tokens = [];\n let current = "";\n let quoted = false;\n for (const character of input) {\n if (character === \'"\') {\n quoted = !quoted;\n continue;\n }\n if (!quoted && /\\s/.test(character)) {\n if (current !== "") tokens.push(current);\n current = "";\n continue;\n }\n current += character;\n }\n if (current !== "") tokens.push(current);\n return tokens;\n }\n function parseQuery(input) {\n const terms = [];\n for (const token of tokenize(input.trim())) {\n const negated = token.startsWith("-") || token.startsWith("!");\n const body = negated ? token.slice(1) : token;\n if (body === "") continue;\n const colon = body.indexOf(":");\n const name = colon === -1 ? "" : body.slice(0, colon).toLowerCase();\n const field2 = FIELDS[name];\n if (colon === -1 || field2 === void 0) {\n terms.push({ field: void 0, value: body.toLowerCase(), negated });\n continue;\n }\n let value = body.slice(colon + 1).toLowerCase();\n let compare;\n if (NUMERIC.has(field2)) {\n compare = value.startsWith(">") ? ">" : value.startsWith("<") ? "<" : "=";\n if (compare !== "=") value = value.slice(1);\n }\n if (value === "") continue;\n terms.push({ field: field2, value, negated, compare });\n }\n return terms;\n }\n function searchableText(entry) {\n const parts = [\n entry.method,\n entry.path,\n entry.actor,\n entry.userAgent,\n entry.verdict,\n entry.botClass,\n entry.identity ?? "",\n entry.action ?? "",\n entry.rule ?? "",\n entry.requestId\n ];\n for (const item of entry.evidence) parts.push(item.detector, item.summary);\n return parts.join(" ").toLowerCase();\n }\n function fieldValue(entry, field2) {\n switch (field2) {\n case "path":\n return entry.path;\n case "actor":\n return entry.actor;\n case "userAgent":\n return entry.userAgent;\n case "verdict":\n return entry.verdict;\n case "action":\n return entry.action ?? "";\n case "rule":\n return entry.rule ?? "";\n case "identity":\n return entry.identity ?? "";\n case "method":\n return entry.method;\n case "botClass":\n return entry.botClass;\n case "requestId":\n return entry.requestId;\n case "bypass":\n return entry.bypass ?? "";\n case "outcome":\n return outcome(entry);\n case "certain":\n return String(entry.certain);\n case "detector":\n return entry.evidence.map((item) => item.detector).join(" ");\n default:\n return "";\n }\n }\n function matchesTerm(term, entry, haystack) {\n if (term.field === void 0) return haystack.includes(term.value);\n if (term.field === "score") {\n const wanted = Number(term.value);\n if (Number.isNaN(wanted)) return false;\n if (term.compare === ">") return entry.score > wanted;\n if (term.compare === "<") return entry.score < wanted;\n return entry.score === wanted;\n }\n return fieldValue(entry, term.field).toLowerCase().includes(term.value);\n }\n function matchesQuery(terms, entry, haystack) {\n for (const term of terms) {\n if (matchesTerm(term, entry, haystack) === term.negated) return false;\n }\n return true;\n }\n function matchesFilter(filter, entry) {\n switch (filter) {\n case "proven":\n return entry.certain;\n case "suspected":\n return entry.verdict === "suspected-bot";\n case "human":\n return entry.verdict === "human";\n case "guard":\n return entry.downgradedFrom !== void 0;\n case "deny":\n return outcome(entry) === "deny";\n case "mitigate":\n return outcome(entry) === "mitigate";\n case "allow":\n return outcome(entry) === "allow";\n default:\n return true;\n }\n }\n\n // src/dashboard/client/store.ts\n var MAX_ROWS = 1e3;\n var state = {\n rows: [],\n byId: /* @__PURE__ */ new Map(),\n snapshot: void 0,\n policy: void 0,\n actors: [],\n actorsTracked: 0,\n paused: false,\n filter: "all",\n search: "",\n terms: [],\n tab: "live",\n open: /* @__PURE__ */ new Set(),\n actor: void 0,\n rangeMs: 3e5,\n scoreScope: "run",\n editorRules: [],\n editorDirty: false,\n editorMode: "gui",\n guardDirty: false,\n bufferedWhilePaused: 0,\n laggedDrops: 0,\n feedPage: 0,\n feedFrozen: void 0,\n actorsPage: 0,\n feedPageSize: 50,\n actorsPageSize: 25,\n caughtUp: 0\n };\n function ingest(entry) {\n const existing = state.byId.get(entry.requestId);\n if (existing !== void 0) {\n existing.entry = entry;\n existing.rev++;\n existing.text = void 0;\n return;\n }\n const row = { entry, rev: 0 };\n state.byId.set(entry.requestId, row);\n state.rows.push(row);\n if (state.rows.length > MAX_ROWS) {\n for (const dropped of state.rows.splice(0, state.rows.length - MAX_ROWS)) {\n state.byId.delete(dropped.entry.requestId);\n state.open.delete(dropped.entry.requestId);\n }\n }\n }\n function clearFeed() {\n state.rows = [];\n state.byId = /* @__PURE__ */ new Map();\n state.open.clear();\n state.actor = void 0;\n state.bufferedWhilePaused = 0;\n state.laggedDrops = 0;\n resetPaging();\n }\n function setSearch(value) {\n state.search = value;\n state.terms = parseQuery(value);\n resetPaging();\n }\n function resetPaging() {\n state.feedPage = 0;\n state.feedFrozen = void 0;\n }\n function textOf(row) {\n if (row.text === void 0) row.text = searchableText(row.entry);\n return row.text;\n }\n function sortRows() {\n state.rows.sort((a, b) => a.entry.at - b.entry.at);\n }\n function matches(row) {\n return matchesFilter(state.filter, row.entry) && matchesQuery(state.terms, row.entry, textOf(row));\n }\n function matchingRows(limit = Number.POSITIVE_INFINITY) {\n const shown = [];\n for (let i = state.rows.length - 1; i >= 0 && shown.length < limit; i--) {\n const row = state.rows[i];\n if (row !== void 0 && matches(row)) shown.push(row);\n }\n return shown;\n }\n function feedPage(size) {\n const all = state.feedPage === 0 || state.feedFrozen === void 0 ? matchingRows() : state.feedFrozen;\n const pages = Math.max(1, Math.ceil(all.length / size));\n const page = Math.min(Math.max(0, state.feedPage), pages - 1);\n if (page !== state.feedPage) state.feedPage = page;\n return { rows: all.slice(page * size, page * size + size), page, pages, total: all.length };\n }\n function goToFeedPage(page) {\n const next = Math.max(0, page);\n if (next === 0) {\n state.feedFrozen = void 0;\n } else if (state.feedFrozen === void 0) {\n state.feedFrozen = matchingRows();\n }\n state.feedPage = next;\n }\n function matchingCount() {\n let count = 0;\n for (const row of state.rows) if (matches(row)) count++;\n return count;\n }\n function oldestAt() {\n return state.rows[0]?.entry.at;\n }\n function bump(counter, key) {\n counter.set(key, (counter.get(key) ?? 0) + 1);\n }\n function aggregate(rows) {\n const totals = {\n detectors: /* @__PURE__ */ new Map(),\n actors: /* @__PURE__ */ new Map(),\n identities: /* @__PURE__ */ new Map(),\n paths: /* @__PURE__ */ new Map(),\n deniedPaths: /* @__PURE__ */ new Map(),\n guardStops: /* @__PURE__ */ new Map(),\n ruleHits: /* @__PURE__ */ new Map(),\n bypassed: /* @__PURE__ */ new Map()\n };\n for (const { entry } of rows) {\n for (const item of entry.evidence) bump(totals.detectors, item.detector);\n bump(totals.actors, entry.actor);\n if (entry.bypass !== void 0) {\n bump(totals.bypassed, `${entry.path} (${entry.bypass})`);\n continue;\n }\n bump(totals.paths, entry.path);\n if (entry.identity !== void 0 && entry.identity !== "") {\n bump(totals.identities, `${entry.identity} \xB7 ${entry.verdict === "verified-bot" ? "verified" : "claimed"}`);\n }\n if (outcome(entry) === "deny") bump(totals.deniedPaths, entry.path);\n if (entry.downgradedFrom !== void 0 && entry.rule !== void 0) bump(totals.guardStops, `${entry.rule} \u2192 ${entry.downgradedFrom}`);\n if (entry.rule !== void 0) bump(totals.ruleHits, entry.rule);\n }\n return totals;\n }\n\n // src/dashboard/client/api.ts\n async function getJson(path) {\n const response = await fetch(API + path);\n if (!response.ok) throw new Error(await errorFrom(response));\n return await response.json();\n }\n async function postJson(path, body) {\n const response = await fetch(API + path, {\n method: "POST",\n headers: { "content-type": "application/json" },\n body: JSON.stringify(body)\n });\n const data = await response.json().catch(() => ({}));\n return response.ok ? { ok: true, data } : { ok: false, data, error: String(data.error ?? "The server refused this.") };\n }\n async function errorFrom(response) {\n const body = await response.json().catch(() => ({}));\n return body.error ?? `${response.status} ${response.statusText}`;\n }\n\n // src/dashboard/client/actions.ts\n var armed = 0;\n function isConfirming() {\n return armed > 0;\n }\n function actorActions(key, after) {\n if (!BOOT.allowActing) return [];\n const forget = el("button", null, "Forget");\n forget.title = "Discard this actor\'s history \u2014 the cure for a false positive that has stuck";\n forget.addEventListener("click", () => {\n void act({ key, action: "forget" }, `Forgot ${key}`, "Its next request is assessed as a first request.", after);\n });\n const clear2 = el("button", null, "Clear as human");\n clear2.title = "Grant this actor human clearance for an hour, as though it had solved a challenge";\n clear2.addEventListener("click", () => {\n void act({ key, action: "clear", forMs: 60 * 6e4 }, `Cleared ${key}`, "Held as human for an hour, then reassessed.", after);\n });\n return [confirmingButton("Allowlist", `Allowlist ${key} \u2014 it stops being assessed at all`, () => allowlist(key, after)), forget, clear2];\n }\n function confirmingButton(label2, confirmation, run2) {\n const button = el("button", "danger", label2);\n let pending2 = false;\n let timer2;\n const disarm = () => {\n if (!pending2) return;\n pending2 = false;\n armed--;\n button.textContent = label2;\n button.className = "danger";\n };\n button.addEventListener("click", () => {\n if (pending2) {\n if (timer2 !== void 0) clearTimeout(timer2);\n disarm();\n run2();\n return;\n }\n pending2 = true;\n armed++;\n button.textContent = confirmation;\n button.className = "danger primary";\n timer2 = setTimeout(disarm, 5e3);\n });\n return button;\n }\n async function allowlist(key, after) {\n const result = await postJson("/api/ranges", { name: "allowlist", add: [key] });\n if (!result.ok) {\n toast("bad", "Not allowlisted", result.error ?? "");\n return;\n }\n toast("warn", `Allowlisted ${key}`, "Requests from it are no longer assessed at all.");\n after();\n }\n async function act(body, title, detail, after) {\n const result = await postJson("/api/actor", body);\n if (!result.ok) {\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n toast("ok", title, detail);\n after();\n }\n\n // src/dashboard/client/format.ts\n var numbers = new Intl.NumberFormat();\n function n(value) {\n return numbers.format(value ?? 0);\n }\n function pct(part, whole) {\n return whole > 0 ? `${Math.round(part / whole * 100)}%` : "\u2014";\n }\n function ms(value) {\n return value >= 10 ? `${value.toFixed(1)}ms` : `${value.toFixed(2)}ms`;\n }\n function uptime(milliseconds) {\n const seconds = Math.max(0, Math.round(milliseconds / 1e3));\n if (seconds < 90) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n if (minutes < 90) return `${minutes}m`;\n return `${Math.round(minutes / 60)}h`;\n }\n function rangeLabel(milliseconds) {\n const seconds = Math.round(milliseconds / 1e3);\n if (seconds < 90) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n return minutes < 90 ? `${minutes} min` : `${Math.round(minutes / 60)}h`;\n }\n function clockTime(at) {\n const when = new Date(at);\n return `${pad(when.getHours())}:${pad(when.getMinutes())}:${pad(when.getSeconds())}`;\n }\n function clockDate(at) {\n const when = new Date(at);\n return `${pad(when.getDate())}-${pad(when.getMonth() + 1)}-${when.getFullYear()}`;\n }\n function clockStamp(at) {\n return `${clockDate(at)} ${clockTime(at)}`;\n }\n function pad(value) {\n return String(value).padStart(2, "0");\n }\n function windowLabel(count, oldestAt2, now) {\n if (count === 0) return "this window \xB7 empty";\n const span = oldestAt2 === void 0 ? 0 : Math.max(0, now - oldestAt2);\n return `last ${n(count)} requests \xB7 ${rangeLabel(span)}`;\n }\n\n // src/dashboard/client/bars.ts\n function drawBars(target, rows, emptyText) {\n clear(target);\n const filtered = [...rows].filter(([, value]) => value > 0);\n if (filtered.length === 0) {\n target.appendChild(el("div", "note", emptyText));\n return;\n }\n filtered.sort((a, b) => b[1] - a[1]);\n const max = filtered[0]?.[1] ?? 1;\n for (const [label2, value] of filtered.slice(0, 14)) {\n const bar = el("div", "bar");\n const track = el("div", "track");\n const fill = el("div", "fill");\n fill.style.width = `${Math.max(2, Math.round(value / max * 100))}%`;\n track.appendChild(fill);\n track.appendChild(el("div", "lbl", label2));\n bar.appendChild(track);\n bar.appendChild(el("div", "v tnum", n(value)));\n target.appendChild(bar);\n }\n }\n function pairs(record) {\n return Object.entries(record ?? {});\n }\n\n // src/dashboard/client/actor.ts\n function initActor() {\n if (!SECTIONS.actors) return;\n $("actor-close").addEventListener("click", closeActor);\n }\n function openActor(key) {\n state.actor = key;\n app.drawNow();\n $("actor-panel").scrollIntoView({ block: "nearest" });\n }\n function closeActor() {\n state.actor = void 0;\n app.drawNow();\n }\n function drawActor() {\n if (!SECTIONS.actors) return;\n const panel = $("actor-panel");\n if (state.actor === void 0) {\n panel.hidden = true;\n return;\n }\n panel.hidden = false;\n $("actor-key").textContent = state.actor;\n const mine = state.rows.filter((row) => row.entry.actor === state.actor).map((row) => row.entry);\n const latest = mine[mine.length - 1];\n const stats = latest?.actorStats;\n const gaps = [];\n for (let i = 1; i < mine.length; i++) gaps.push(mine[i].at - mine[i - 1].at);\n const meanGap = gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0;\n const box = $("actor-stats");\n clear(box);\n const rows = [\n ["In this window", `${n(mine.length)} requests`],\n ["Engine sees", stats !== void 0 ? `${n(stats.requests)} requests, ${n(stats.distinctPaths)} distinct paths` : "\u2014"],\n ["Prior confirmations", stats !== void 0 ? n(stats.priorConfirmations) : "\u2014"],\n ["Holds clearance", stats !== void 0 ? stats.cleared ? "yes" : "no" : "\u2014"],\n ["First seen", stats !== void 0 ? clockStamp(stats.firstSeen) : "\u2014"],\n ["Mean gap", gaps.length > 0 ? `${Math.round(meanGap)}ms over ${n(gaps.length)} gaps` : "one request only"]\n ];\n for (const [key, value] of rows) {\n box.appendChild(el("dt", null, key));\n box.appendChild(el("dd", null, value));\n }\n const verdicts = /* @__PURE__ */ new Map();\n const actions = /* @__PURE__ */ new Map();\n for (const entry of mine) {\n verdicts.set(entry.verdict, (verdicts.get(entry.verdict) ?? 0) + 1);\n if (entry.action !== void 0) actions.set(entry.action, (actions.get(entry.action) ?? 0) + 1);\n }\n drawBars($("actor-mix"), [...verdicts, ...actions], "Nothing yet.");\n const bar = $("actor-actions");\n clear(bar);\n const buttons = actorActions(state.actor, () => app.drawNow());\n bar.hidden = buttons.length === 0;\n for (const button of buttons) bar.appendChild(button);\n }\n\n // src/dashboard/client/pager.ts\n var painted = /* @__PURE__ */ new WeakMap();\n function renderPager(host, model, options) {\n const signature = JSON.stringify([model.page, model.from, model.to, model.total, model.atStart, model.atEnd, model.held ?? "", options.withSize, model.size?.current]);\n if (painted.get(host) === signature && host.childElementCount > 0) return;\n painted.set(host, signature);\n clear(host);\n const steps = [\n { to: model.page - 1, glyph: "\u2039", label: "Previous page", disabled: model.atStart },\n { to: model.page + 1, glyph: "\u203A", label: "Next page", disabled: model.atEnd }\n ];\n const [previous, next] = steps;\n host.appendChild(stepButton(previous, model));\n const range = model.total === void 0 ? `${n(model.from)}\u2013${n(model.to)}` : `${n(model.from)}\u2013${n(model.to)} of ${n(model.total)}`;\n const where = el("span", "where", range);\n where.setAttribute("aria-live", "polite");\n host.appendChild(where);\n host.appendChild(stepButton(next, model));\n if (model.held !== void 0) {\n const held = el("span", "held", model.held);\n held.title = "New requests are still arriving and are still counted. They appear when you return to the first page.";\n host.appendChild(held);\n }\n if (options.withSize && model.size !== void 0) {\n const size = model.size;\n const label2 = el("label", "size");\n label2.appendChild(document.createTextNode("Per page"));\n const select2 = document.createElement("select");\n for (const choice of size.choices) {\n const option = document.createElement("option");\n option.value = String(choice);\n option.textContent = String(choice);\n option.selected = choice === size.current;\n select2.appendChild(option);\n }\n select2.addEventListener("change", () => {\n const chosen = Number(select2.value);\n if (Number.isFinite(chosen) && chosen > 0) size.set(chosen);\n });\n label2.appendChild(select2);\n host.appendChild(label2);\n }\n }\n function stepButton(step, model) {\n const button = el("button", "step", step.glyph);\n const element = button;\n element.type = "button";\n element.disabled = step.disabled;\n button.setAttribute("aria-label", step.label);\n button.title = step.label;\n button.addEventListener("click", () => model.go(Math.max(0, step.to)));\n return button;\n }\n\n // src/dashboard/client/replay.ts\n function replayLine(entry) {\n const headers = {};\n for (const [name, value] of entry.headers ?? []) headers[name] = value;\n const query = Object.keys(entry.query).map((name) => `${encodeURIComponent(name)}=${encodeURIComponent(entry.query[name] ?? "")}`).join("&");\n return JSON.stringify({\n method: entry.method,\n url: entry.path + (query === "" ? "" : `?${query}`),\n headers,\n ip: entry.actor,\n timestamp: new Date(entry.at).toISOString(),\n protocol: entry.protocol ?? "https",\n httpVersion: entry.httpVersion ?? "1.1"\n });\n }\n function replayFile(entries) {\n return entries.map(replayLine).join("\\n");\n }\n function corpusCase(entry) {\n const headers = (entry.headers ?? []).map((pair) => ` [${JSON.stringify(pair[0])}, ${JSON.stringify(pair[1])}]`).join(",\\n");\n return [\n "bot({",\n ` id: ${JSON.stringify(`case-${entry.requestId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`)},`,\n ` title: ${JSON.stringify(`${entry.method} ${entry.path} from ${entry.userAgent.slice(0, 60)}`)},`,\n \' audience: "unwanted-bot", // human | benign-bot | declared-bot | unwanted-bot | hostile | infrastructure\',\n \' category: "observed",\',\n ` provenance: "Captured from the live dashboard on ${new Date(entry.at).toISOString().slice(0, 10)}",`,\n " requests: [",\n " {",\n " headers: [",\n headers,\n " ],",\n ` protocol: ${JSON.stringify(entry.protocol ?? "https")},`,\n ` httpVersion: ${JSON.stringify(entry.httpVersion ?? "1.1")},`,\n ` path: ${JSON.stringify(entry.path)},`,\n " },",\n " ],",\n ` expect: { verdict: ${JSON.stringify(entry.verdict)}, certain: ${String(entry.certain)} },`,\n "}),"\n ].join("\\n");\n }\n\n // src/dashboard/client/result.ts\n function showResult(kind, build) {\n const box = $("policy-result");\n box.hidden = false;\n box.className = `result ${kind}`;\n clear(box);\n build(box);\n }\n function renderPreview(preview, notes = []) {\n showResult(preview.newDenials > 0 ? "warn" : "ok", (box) => {\n const head = el("div");\n head.appendChild(el("b", null, `${n(preview.changed)} of ${n(preview.evaluated)} requests would be treated differently.`));\n box.appendChild(head);\n for (const note of notes) box.appendChild(el("div", "ev-meta", note));\n if (preview.newDenials > 0) {\n box.appendChild(el("div", null, `${n(preview.newDenials)} request(s) that are served today would be denied. Read the samples before applying this.`));\n }\n for (const warning of preview.warnings) box.appendChild(el("div", "ev-meta", warning));\n const dead = preview.ruleHits.filter((row) => row.hits === 0 && row.rule !== "default");\n if (dead.length > 0) box.appendChild(el("div", "ev-meta", `Never matched in this window: ${dead.map((row) => row.rule).join(", ")}`));\n if (preview.samples.length > 0) {\n const table = el("table", "diff");\n const head2 = el("tr");\n for (const label2 of ["Request", "Now", "Would be"]) head2.appendChild(el("th", null, label2));\n table.appendChild(head2);\n for (const sample of preview.samples) {\n const row = el("tr");\n const what = el("td");\n what.appendChild(el("div", "mono", sample.path));\n what.appendChild(el("div", "ev-meta", `${sample.verdict} \xB7 ${sample.userAgent.slice(0, 48)}`));\n row.appendChild(what);\n const from = el("td", "from");\n from.appendChild(el("div", null, sample.from));\n from.appendChild(el("div", "ev-meta", sample.fromRule));\n row.appendChild(from);\n const kind = sample.to === "block" || sample.to === "drop" || sample.to === "redirect" ? "deny" : sample.to === "allow" ? "allow" : "";\n const to = el("td", `to ${kind}`);\n to.appendChild(el("div", null, sample.to));\n to.appendChild(el("div", "ev-meta", sample.toRule));\n row.appendChild(to);\n table.appendChild(row);\n }\n box.appendChild(table);\n } else if (preview.evaluated === 0) {\n box.appendChild(el("div", "ev-meta", "No traffic in the window to preview against \u2014 send some requests first."));\n }\n });\n }\n\n // src/dashboard/client/guard.ts\n var draft;\n var MODE_NOTES = {\n strict: "A terminal action survives only on proven evidence. Nothing is ever denied on a guess. This is the default, and it is the claim this library makes about itself.",\n balanced: "A terminal action also survives on a probabilistic verdict that clears the score threshold with at least two independent strong signals. Real people do trip two signals \u2014 a hardened browser behind a corporate proxy is the usual pair \u2014 so this setting will eventually deny somebody who should have been served.",\n aggressive: "The guard is off. Every rule does exactly what it says, on proof or on suspicion alike, and the people it turns away first are the ones with the most unusual and most legitimate setups."\n };\n function drawGuard() {\n if (!SECTIONS.guard) return;\n const document_ = state.policy;\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const editable = document_?.guardEditable === true;\n const panel = $("stat-policy");\n clear(panel);\n if (!editable || document_ === void 0) {\n const rows = [\n ["False-positive policy", snapshot.policy.falsePositivePolicy],\n ["Fallback when the guard stops a rule", snapshot.policy.fallbackAction],\n ["Terminal score threshold", String(snapshot.policy.terminalScoreThreshold)],\n ["Suspect threshold", String(snapshot.policy.suspectThreshold)],\n ["Action when no rule matches", snapshot.policy.defaultAction],\n ["Challenge configured", snapshot.policy.challengeEnabled ? "yes" : "no"],\n ["Range sets", snapshot.ranges.length === 0 ? "none" : snapshot.ranges.map((range) => `${range.name} (${range.size})`).join(", ")]\n ];\n for (const [key, value] of rows) {\n const line = el("div", "stat-row");\n line.appendChild(el("span", "k", key));\n line.appendChild(el("span", "v", value));\n panel.appendChild(line);\n }\n $("guard-mode").textContent = "not editable here";\n $("guard-note").textContent = "These are fixed at construction on this dashboard. It can change which rules exist; it cannot change how far a rule is allowed to go, because relaxing that is the one edit that can start denying people. Enable it deliberately with controls: { editGuard: true }.";\n return;\n }\n if (draft === void 0) draft = { ...document_.guard };\n const vocabulary = document_.vocabulary;\n $("guard-mode").textContent = state.guardDirty ? "unsaved changes" : "editable";\n $("guard-note").textContent = "Changing these changes what every rule is allowed to do, on the next request. Preview it against the traffic in the window first \u2014 that is the only view you get of who it would start turning away.";\n panel.appendChild(\n guardField(\n // "Mode" rather than "Guard": the panel is already called that, and a field\n // repeating its own panel\'s name reads as a heading rather than as a control.\n "Mode",\n segmented(\n vocabulary.falsePositivePolicies.map((mode) => [mode, mode]),\n draft.falsePositivePolicy,\n (value) => {\n setDraft({ falsePositivePolicy: value });\n drawGuard();\n }\n )\n )\n );\n panel.appendChild(el("div", "note guard-explains", MODE_NOTES[draft.falsePositivePolicy] ?? ""));\n panel.appendChild(\n guardField(\n "Fallback",\n select(vocabulary.fallbackActions, draft.fallbackAction, (value) => setDraft({ fallbackAction: value })),\n "what a stopped rule becomes \u2014 the terminal actions are absent because a terminal fallback would deny the request the guard just protected"\n )\n );\n panel.appendChild(\n guardField(\n "Default action",\n select(vocabulary.actions, draft.defaultAction, (value) => setDraft({ defaultAction: value })),\n "when no rule matches"\n )\n );\n panel.appendChild(\n guardField(\n "Terminal score",\n number(draft.terminalScoreThreshold, (value) => setDraft({ terminalScoreThreshold: value })),\n "balanced mode only: the score a probabilistic verdict must clear"\n )\n );\n panel.appendChild(\n guardField(\n "Suspect at",\n number(draft.suspectThreshold, (value) => setDraft({ suspectThreshold: value })),\n "the score at which a request becomes suspected-bot"\n )\n );\n const bar = el("div", "bar-actions");\n const preview = el("button", null, "Preview");\n preview.addEventListener("click", () => {\n void previewGuard();\n });\n const apply = el("button", "primary", "Apply");\n apply.addEventListener("click", () => {\n void applyGuard();\n });\n const revert = el("button", null, "Revert");\n revert.addEventListener("click", () => {\n draft = { ...document_.guard };\n state.guardDirty = false;\n drawGuard();\n });\n bar.appendChild(preview);\n bar.appendChild(apply);\n bar.appendChild(revert);\n panel.appendChild(bar);\n }\n function setDraft(change) {\n if (draft === void 0) return;\n draft = { ...draft, ...change };\n state.guardDirty = true;\n $("guard-mode").textContent = "unsaved changes";\n }\n function resetGuardDraft() {\n draft = void 0;\n state.guardDirty = false;\n }\n function liveRules() {\n return (state.policy?.rules ?? []).filter((row) => row.editable && row.rule !== void 0).map((row) => row.rule);\n }\n async function previewGuard() {\n if (draft === void 0) return;\n const result = await postJson("/api/policy/preview", { rules: liveRules(), guard: draft });\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n renderPreview(result.data, state.editorDirty ? ["Previewed against the rules currently in force, not the unsaved edits in the editor."] : []);\n app.showTab("policy");\n }\n async function applyGuard() {\n if (draft === void 0) return;\n const result = await postJson("/api/guard", draft);\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Guard unchanged", result.error ?? "");\n return;\n }\n state.guardDirty = false;\n draft = { ...result.data.guard };\n if (state.policy !== void 0) state.policy.guard = { ...result.data.guard };\n toast("ok", "Guard changed", `${result.data.guard.falsePositivePolicy}, falling back to ${result.data.guard.fallbackAction}.`);\n showResult("warn", (box) => {\n box.appendChild(el("div", null, "The guard changed. It applies from the next request, and it is in the notices panel and in your logs."));\n if (result.data.guard.falsePositivePolicy !== "strict") {\n box.appendChild(\n el(\n "div",\n "ev-meta",\n "Requests can now be denied without proof. The guard-stop count is the series to watch: every stop that no longer happens is a request that used to be recoverable and is not any more."\n )\n );\n }\n });\n app.draw();\n }\n function guardField(name, control, hint) {\n const row = el("div", "field");\n row.appendChild(label(name, control));\n const right = el("div", "field-row");\n right.appendChild(control);\n if (hint !== void 0) right.appendChild(el("span", "hint", hint));\n row.appendChild(right);\n return row;\n }\n function segmented(options, value, onChange) {\n const box = el("div", "seg");\n for (const [label2, option] of options) {\n const button = el("button", null, label2);\n button.type = "button";\n button.setAttribute("aria-pressed", String(option === value));\n button.addEventListener("click", () => onChange(option));\n box.appendChild(button);\n }\n return box;\n }\n function select(options, value, onChange) {\n const node = el("select");\n for (const option of options) {\n const item = el("option", null, option);\n item.value = option;\n if (option === value) item.selected = true;\n node.appendChild(item);\n }\n node.addEventListener("change", () => onChange(node.value));\n return node;\n }\n function number(value, onChange) {\n const input = el("input");\n input.type = "number";\n input.min = "1";\n input.max = "100";\n input.value = String(value);\n input.addEventListener("input", () => {\n if (input.value !== "") onChange(Number(input.value));\n });\n return input;\n }\n\n // src/dashboard/client/ranges.ts\n var sets = [];\n async function loadRanges() {\n if (!SECTIONS.ranges) return;\n try {\n const body = await getJson("/api/ranges");\n sets = body.ranges;\n drawRanges();\n } catch {\n }\n }\n function drawRanges() {\n if (!SECTIONS.ranges) return;\n const body = $("ranges-body");\n clear(body);\n $("ranges-mode").textContent = BOOT.allowActing ? "editable" : "read-only";\n $("ranges-note").textContent = BOOT.allowActing ? "An address on the allowlist is not judged leniently \u2014 it is not judged at all. Detection does not run on it, no evidence is produced, and no rule sees it." : "These come from the code that constructed the handler. Enable controls.editRanges to add an address from here.";\n if (sets.length === 0) {\n body.appendChild(el("div", "note", "No range sets are configured. Add an address to the allowlist and one appears."));\n }\n for (const set of sets) {\n const block = el("div", "rangeset");\n const heading = el("h3");\n heading.appendChild(document.createTextNode(set.name));\n heading.appendChild(el("span", null, `${n(set.size)} entr${set.size === 1 ? "y" : "ies"}`));\n block.appendChild(heading);\n const list = el("div", "cidrs");\n for (const entry of set.entries) {\n const chip = el("span", BOOT.allowActing ? "cidr" : "cidr readonly");\n chip.appendChild(document.createTextNode(entry));\n if (BOOT.allowActing) {\n const remove = el("button", null, "\xD7");\n remove.title = `Remove ${entry} from ${set.name}`;\n remove.setAttribute("aria-label", `Remove ${entry} from ${set.name}`);\n remove.addEventListener("click", () => void update(set.name, { remove: [entry] }));\n chip.appendChild(remove);\n }\n list.appendChild(chip);\n }\n if (set.entries.length === 0) list.appendChild(el("span", "hint", "empty"));\n block.appendChild(list);\n body.appendChild(block);\n }\n if (!BOOT.allowActing) return;\n const form = el("div", "rangeset");\n const row = el("div", "field-row");\n const name = el("input", "mono-input");\n name.type = "text";\n name.value = "allowlist";\n name.setAttribute("aria-label", "Range set");\n name.style.maxWidth = "150px";\n const value = el("input", "mono-input");\n value.type = "text";\n value.placeholder = "203.0.113.0/24";\n value.setAttribute("aria-label", "Address or CIDR to add");\n const add = el("button", null, "Add");\n const submit = () => {\n const entry = value.value.trim();\n if (entry === "") return;\n value.value = "";\n void update(name.value.trim(), { add: [entry] });\n };\n add.addEventListener("click", submit);\n value.addEventListener("keydown", (event) => {\n if (event.key === "Enter") submit();\n });\n row.appendChild(name);\n row.appendChild(value);\n row.appendChild(add);\n form.appendChild(row);\n body.appendChild(form);\n }\n async function update(name, change) {\n const result = await postJson("/api/ranges", { name, ...change });\n if (!result.ok) {\n toast("bad", "Ranges unchanged", result.error ?? "");\n return;\n }\n toast(name === "allowlist" && change.add !== void 0 ? "warn" : "ok", `\u201C${name}\u201D updated`, `${n(result.data.entries?.length ?? 0)} entr${result.data.entries?.length === 1 ? "y" : "ies"} now.`);\n await loadRanges();\n }\n\n // src/dashboard/client/draft.ts\n function draftRule(entry, existingIds = []) {\n const match = {};\n let because;\n let stem;\n const proven = entry.evidence.filter((item) => item.certainty === "certain" && item.direction !== "human");\n const detectors = [...new Set((proven.length > 0 ? proven : entry.evidence.filter((item) => item.direction !== "human")).map((item) => item.detector))];\n if (entry.identity !== void 0 && entry.identity !== "") {\n match["identity"] = [entry.identity];\n if (entry.certain) match["certain"] = true;\n stem = entry.identity;\n because = entry.certain ? `Matched on the identity \u201C${entry.identity}\u201D, and on proof \u2014 so a client merely claiming that name does not match.` : `Matched on the claimed identity \u201C${entry.identity}\u201D. Nothing has verified it, so this matches anything that says so.`;\n } else if (proven.length > 0) {\n match["detector"] = detectors;\n match["certain"] = true;\n stem = detectors[0] ?? "proven";\n because = `Matched on proof from ${detectors.join(", ")}. Only requests that carry the same proof match.`;\n } else if (detectors.length > 0) {\n match["verdict"] = [entry.verdict];\n match["detector"] = detectors;\n match["minScore"] = Math.max(0, Math.floor(entry.score / 10) * 10);\n stem = detectors[0] ?? entry.verdict;\n because = `Matched on ${entry.verdict} at score ${String(match["minScore"])} or more, from ${detectors.join(", ")}. Every one of those is probabilistic, so the guard will not let this rule deny anybody.`;\n } else {\n match["verdict"] = [entry.verdict];\n stem = entry.verdict;\n because = `Nothing fired on this request, so there is nothing sharper to match on than the verdict itself. Narrow it before you use it.`;\n }\n return {\n rule: {\n id: uniqueId(`from-${slug(stem)}`, existingIds),\n match,\n action: "tag",\n reason: "Drafted from a request on the dashboard.",\n _open: true\n },\n because\n };\n }\n function slug(value) {\n const cleaned = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");\n return cleaned === "" ? "request" : cleaned.slice(0, 40);\n }\n function uniqueId(wanted, taken) {\n if (!taken.includes(wanted)) return wanted;\n for (let suffix = 2; suffix < 1e3; suffix++) {\n const candidate = `${wanted}-${suffix}`;\n if (!taken.includes(candidate)) return candidate;\n }\n return `${wanted}-${Date.now()}`;\n }\n\n // src/dashboard/client/policy.ts\n async function loadPolicy() {\n if (!SECTIONS.policy) return;\n try {\n const document_ = await getJson("/api/policy");\n state.policy = document_;\n if (!state.editorDirty) {\n setEditorRules(document_.rules.filter((row) => row.editable).map((row) => row.rule));\n }\n if (!state.guardDirty) resetGuardDraft();\n drawPolicyTab();\n } catch {\n }\n }\n function setEditorRules(rules) {\n state.editorRules = JSON.parse(JSON.stringify(rules ?? []));\n renderEditor();\n }\n function markDirty() {\n state.editorDirty = true;\n $("policy-dirty").hidden = false;\n }\n function editorRules() {\n if (state.editorMode === "json") {\n try {\n const parsed = JSON.parse(byId("policy-json").value);\n if (!Array.isArray(parsed)) return { error: "The JSON must be an array of rules." };\n return { rules: parsed };\n } catch (error) {\n return { error: `The editor does not contain valid JSON: ${String(error)}` };\n }\n }\n return { rules: state.editorRules };\n }\n function cleanRule(rule) {\n const match = {};\n for (const [key, value] of Object.entries(rule.match ?? {})) {\n if (value === void 0 || value === null || value === "") continue;\n if (Array.isArray(value) && value.length === 0) continue;\n match[key] = value;\n }\n const params = {};\n for (const [key, value] of Object.entries(rule.params ?? {})) {\n if (value === void 0 || value === null || value === "") continue;\n if (key === "limit") {\n const limit = value;\n if (limit.max === void 0 || limit.windowMs === void 0) continue;\n }\n params[key] = value;\n }\n const out = { id: rule.id, match, action: rule.action };\n if (Object.keys(params).length > 0) out["params"] = params;\n if (rule.reason !== void 0 && rule.reason !== "") out["reason"] = rule.reason;\n return out;\n }\n function cleanRules(rules) {\n return rules.map(cleanRule);\n }\n function field(name, control, hint) {\n const row = el("div", "field");\n row.appendChild(label(name, control));\n const right = el("div", "field-row");\n for (const node of Array.isArray(control) ? control : [control]) right.appendChild(node);\n if (hint !== void 0) right.appendChild(el("span", "hint", hint));\n row.appendChild(right);\n return row;\n }\n function chipSelect(options, selected, onChange) {\n const box = el("div", "chips-select");\n const chosen = Array.isArray(selected) ? [...selected] : selected === void 0 ? [] : [String(selected)];\n for (const option of options) {\n const button = el("button", null, option);\n button.type = "button";\n button.setAttribute("aria-pressed", String(chosen.includes(option)));\n button.addEventListener("click", () => {\n const at = chosen.indexOf(option);\n if (at === -1) chosen.push(option);\n else chosen.splice(at, 1);\n button.setAttribute("aria-pressed", String(at === -1));\n onChange(chosen.length === 0 ? void 0 : [...chosen]);\n });\n box.appendChild(button);\n }\n return box;\n }\n function segmented2(options, value, onChange) {\n const box = el("div", "seg");\n for (const [label2, option] of options) {\n const button = el("button", null, label2);\n button.type = "button";\n button.setAttribute("aria-pressed", String(option === value));\n button.addEventListener("click", () => {\n for (const other of Array.from(box.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n onChange(option);\n });\n box.appendChild(button);\n }\n return box;\n }\n function textInput(value, placeholder, onChange, mono = false) {\n const input = el("input", mono ? "mono-input" : null);\n input.type = "text";\n input.value = value === void 0 || value === null ? "" : String(value);\n input.placeholder = placeholder;\n input.addEventListener("input", () => onChange(input.value.trim() === "" ? void 0 : input.value));\n return input;\n }\n function listInput(value, placeholder, onChange) {\n const current = value === void 0 ? "" : Array.isArray(value) ? value.join(", ") : String(value);\n const input = textInput(current, placeholder, () => {\n }, true);\n input.addEventListener("input", () => {\n const parts = input.value.split(",").map((part) => part.trim()).filter(Boolean);\n onChange(parts.length === 0 ? void 0 : parts.length === 1 ? parts[0] : parts);\n });\n return input;\n }\n function numberInput(value, placeholder, onChange) {\n const input = el("input");\n input.type = "number";\n input.value = value === void 0 || value === null ? "" : String(value);\n input.placeholder = placeholder;\n input.addEventListener("input", () => onChange(input.value === "" ? void 0 : Number(input.value)));\n return input;\n }\n function matchSummary(rule) {\n const box = el("div", "rule-summary");\n const match = rule.match ?? {};\n const parts = [];\n for (const key of ["verdict", "botClass", "category", "identity", "detector", "method", "path"]) {\n const value = match[key];\n if (value === void 0) continue;\n parts.push([key, Array.isArray(value) ? value.join(", ") : String(value)]);\n }\n if (match["certain"] !== void 0) parts.push(["certain", String(match["certain"])]);\n if (match["minScore"] !== void 0 || match["maxScore"] !== void 0) {\n parts.push(["score", `${String(match["minScore"] ?? 0)}\u2013${String(match["maxScore"] ?? 99)}`]);\n }\n if (match["minPriorConfirmations"] !== void 0) parts.push(["prior", String(match["minPriorConfirmations"])]);\n if (match["minUnsolvedChallenges"] !== void 0) parts.push(["unsolved", String(match["minUnsolvedChallenges"])]);\n if (parts.length === 0) {\n box.appendChild(el("span", "none", "matches everything"));\n return box;\n }\n for (const [key, value] of parts.slice(0, 4)) box.appendChild(el("span", "t", `${key}: ${value}`));\n if (parts.length > 4) box.appendChild(el("span", "k", `+${parts.length - 4} more`));\n return box;\n }\n function ruleCard(rule, index) {\n const vocabulary = state.policy?.vocabulary;\n const open = rule._open === true;\n const card = el("div", `rule${open ? "" : " collapsed"}`);\n const head = el("div", "rule-head");\n const chevron = el("button", "chev", open ? "\u25BE" : "\u25B8");\n chevron.title = open ? "Collapse" : "Expand";\n chevron.setAttribute("aria-expanded", String(open));\n chevron.addEventListener("click", () => {\n rule._open = !open;\n renderEditor();\n });\n head.appendChild(chevron);\n head.appendChild(el("span", "ord", index + 1));\n const id = textInput(rule.id, "rule-id", (value) => {\n rule.id = value ?? "";\n markDirty();\n }, true);\n id.setAttribute("aria-label", "Rule id");\n head.appendChild(id);\n if (open) {\n const action = el("select");\n action.setAttribute("aria-label", "Action");\n for (const name of vocabulary?.actions ?? []) {\n const option = el("option", null, name);\n option.value = name;\n if (name === rule.action) option.selected = true;\n action.appendChild(option);\n }\n action.addEventListener("change", () => {\n rule.action = action.value;\n rule.params = {};\n markDirty();\n renderEditor();\n });\n head.appendChild(action);\n } else {\n head.appendChild(matchSummary(rule));\n head.appendChild(el("span", `act-pill ${actionKind(rule.action)}`, rule.action));\n }\n const up = el("button", "icon", "\u2191");\n up.title = "Move earlier \u2014 the first matching rule wins";\n up.addEventListener("click", () => moveRule(index, -1));\n const down = el("button", "icon", "\u2193");\n down.title = "Move later";\n down.addEventListener("click", () => moveRule(index, 1));\n const remove = el("button", "icon danger", "Remove");\n remove.addEventListener("click", () => {\n state.editorRules.splice(index, 1);\n markDirty();\n renderEditor();\n });\n head.appendChild(up);\n head.appendChild(down);\n head.appendChild(remove);\n card.appendChild(head);\n if (!open) return card;\n const body = el("div", "rule-body");\n rule.match = rule.match ?? {};\n const match = rule.match;\n body.appendChild(field("Verdict", chipSelect(vocabulary?.verdicts ?? [], match["verdict"], (value) => {\n match["verdict"] = value;\n markDirty();\n })));\n body.appendChild(field("Bot class", chipSelect(vocabulary?.botClasses ?? [], match["botClass"], (value) => {\n match["botClass"] = value;\n markDirty();\n })));\n body.appendChild(field("Category", chipSelect(vocabulary?.categories ?? [], match["category"], (value) => {\n match["category"] = value;\n markDirty();\n })));\n body.appendChild(field("Detector", chipSelect(vocabulary?.detectors ?? [], match["detector"], (value) => {\n match["detector"] = value;\n markDirty();\n })));\n body.appendChild(field("Method", chipSelect(vocabulary?.methods ?? [], match["method"], (value) => {\n match["method"] = value;\n markDirty();\n })));\n body.appendChild(\n field(\n "Evidence",\n segmented2(\n [\n ["any", void 0],\n ["proven", true],\n ["unproven", false]\n ],\n match["certain"],\n (value) => {\n match["certain"] = value;\n markDirty();\n }\n ),\n "proven means at least one piece of certain evidence \u2014 including a proven human"\n )\n );\n body.appendChild(\n field("Score", [\n numberInput(match["minScore"], "min", (value) => {\n match["minScore"] = value;\n markDirty();\n }),\n el("span", "hint", "to"),\n numberInput(match["maxScore"], "max", (value) => {\n match["maxScore"] = value;\n markDirty();\n })\n ])\n );\n body.appendChild(field("Identity", listInput(match["identity"], "googlebot, gptbot", (value) => {\n match["identity"] = value;\n markDirty();\n })));\n body.appendChild(field("Path", listInput(match["path"], "/api/, /search", (value) => {\n match["path"] = value;\n markDirty();\n }), "a string matches as a prefix"));\n body.appendChild(\n field(\n "Prior bots",\n numberInput(match["minPriorConfirmations"], "0", (value) => {\n match["minPriorConfirmations"] = value;\n markDirty();\n }),\n "times this actor was already proven a bot"\n )\n );\n body.appendChild(\n field(\n "Unsolved",\n numberInput(match["minUnsolvedChallenges"], "0", (value) => {\n match["minUnsolvedChallenges"] = value;\n markDirty();\n }),\n "challenges issued to this actor that were never answered \u2014 solving one clears the count"\n )\n );\n rule.params = rule.params ?? {};\n const params = rule.params;\n for (const node of paramFields(rule.action, params)) body.appendChild(node);\n body.appendChild(field("Reason", textInput(rule.reason, "shown in the decision and in your logs", (value) => {\n rule.reason = value ?? "";\n markDirty();\n })));\n card.appendChild(body);\n return card;\n }\n function paramFields(action, params) {\n switch (action) {\n case "block":\n return [\n field("Status", numberInput(params["status"], "403", (value) => {\n params["status"] = value;\n markDirty();\n })),\n field("Body", textInput(params["body"], "Automated traffic is not served here.", (value) => {\n params["body"] = value;\n markDirty();\n }))\n ];\n case "redirect":\n return [field("Location", textInput(params["location"], "/too-fast", (value) => {\n params["location"] = value;\n markDirty();\n }, true))];\n case "delay":\n return [field("Delay", numberInput(params["delayMs"], "250", (value) => {\n params["delayMs"] = value;\n markDirty();\n }), "milliseconds")];\n case "rate-limit": {\n const limit = params["limit"] ?? {};\n params["limit"] = limit;\n return [\n field("Limit", [\n numberInput(limit["max"], "60", (value) => {\n limit["max"] = value;\n markDirty();\n }),\n el("span", "hint", "requests per"),\n numberInput(limit["windowMs"], "60000", (value) => {\n limit["windowMs"] = value;\n markDirty();\n }),\n el("span", "hint", "ms")\n ])\n ];\n }\n case "custom":\n return [field("Handler", textInput(params["handler"], "handler-id", (value) => {\n params["handler"] = value;\n markDirty();\n }, true), "id of a handler you registered")];\n default:\n return [];\n }\n }\n function lockedCard(row) {\n const card = el("div", "rule locked");\n const head = el("div", "rule-head");\n head.appendChild(el("span", "ord", `#${row.index + 1}`));\n head.appendChild(el("span", "mono", row.id));\n head.appendChild(el("span", "grow"));\n head.appendChild(el("span", "pill", "predicate \u2014 locked"));\n card.appendChild(head);\n card.appendChild(\n el("div", "rule-body", "This rule matches with a function, which cannot be represented here or sent over HTTP. It stays exactly as it is, at this position, whatever else you change.")\n );\n return card;\n }\n function moveRule(index, delta) {\n const target = index + delta;\n if (target < 0 || target >= state.editorRules.length) return;\n const moved = state.editorRules.splice(index, 1)[0];\n if (moved === void 0) return;\n state.editorRules.splice(target, 0, moved);\n markDirty();\n renderEditor();\n }\n function renderEditor() {\n if (!SECTIONS.policy) return;\n const list = $("rulelist");\n clear(list);\n const locked = (state.policy?.rules ?? []).filter((row) => !row.editable);\n if (state.editorRules.length === 0 && locked.length === 0) {\n list.appendChild(el("div", "note", "No rules. Every request takes the default action \u2014 add one, or import a set."));\n }\n const rendered2 = state.editorRules.map((rule, index) => ruleCard(rule, index));\n for (const row of locked) rendered2.splice(Math.min(row.index, rendered2.length), 0, lockedCard(row));\n for (const node of rendered2) list.appendChild(node);\n if (state.editorMode === "json") byId("policy-json").value = JSON.stringify(cleanRules(state.editorRules), null, 2);\n }\n function drawPolicyTab() {\n const document_ = state.policy;\n if (document_ === void 0) return;\n const editable = document_.editable;\n $("policy-apply").hidden = !editable;\n byId("policy-json").readOnly = !editable;\n $("policy-mode").textContent = editable ? "editable" : "read-only";\n $("rule-add").hidden = !editable;\n $("policy-import").hidden = !editable;\n const preserved = document_.rules.filter((row) => !row.editable);\n let note = editable ? "First match wins \u2014 order matters." : "Read-only. Enable controls.editPolicy to change these.";\n if (preserved.length > 0) note += ` ${preserved.length} rule(s) use a predicate function and are locked.`;\n $("policy-note").textContent = note;\n renderPresetButtons();\n drawGuard();\n drawRanges();\n if (SECTIONS.robots) {\n $("robots-preview").textContent = document_.robots === "" ? "(this policy declines no crawler by name)" : document_.robots;\n const notes = $("robots-notes");\n clear(notes);\n for (const note_ of document_.robotsNotes) notes.appendChild(el("div", "ev-meta", `${note_.rule}: ${note_.reason}`));\n }\n const rules = $("stat-rules");\n clear(rules);\n const installed = state.snapshot?.rules ?? [];\n if (installed.length === 0) rules.appendChild(el("div", "note", "No rules configured \u2014 every request takes the default action."));\n else installed.forEach((rule, index) => rules.appendChild(el("span", "chip", `${index + 1}. ${rule}`)));\n }\n async function draftIntoEditor(entry) {\n if (state.policy === void 0) await loadPolicy();\n const drafted = draftRule(entry, state.editorRules.map((rule) => rule.id));\n state.editorRules.push(drafted.rule);\n markDirty();\n if (state.editorMode === "json") byId("policy-json").value = JSON.stringify(cleanRules(state.editorRules), null, 2);\n renderEditor();\n app.showTab("policy");\n const notes = [\n `Drafted \u201C${drafted.rule.id}\u201D, tagging only. Nothing is applied \u2014 read it, choose the action, then apply.`,\n drafted.because,\n "It was added last, which is the only position that cannot change what an existing rule does. Move it up with \u2191 if it needs to win."\n ];\n showResult("warn", (box) => {\n for (const note of notes) box.appendChild(el("div", note === notes[0] ? null : "ev-meta", note));\n });\n toast("ok", "Rule drafted", "In the editor, tagging only, not applied.");\n await runPreview(notes);\n }\n function switchToGui() {\n if (state.editorMode === "gui") return;\n const parsed = editorRules();\n if (parsed.error !== void 0) {\n toast("bad", "That JSON will not parse", parsed.error);\n return;\n }\n state.editorRules = parsed.rules ?? [];\n state.editorMode = "gui";\n $("mode-gui").setAttribute("aria-pressed", "true");\n $("mode-json").setAttribute("aria-pressed", "false");\n $("editor-gui").hidden = false;\n $("editor-json").hidden = true;\n renderEditor();\n }\n function switchToJson() {\n state.editorMode = "json";\n $("mode-gui").setAttribute("aria-pressed", "false");\n $("mode-json").setAttribute("aria-pressed", "true");\n $("editor-gui").hidden = true;\n $("editor-json").hidden = false;\n byId("policy-json").value = JSON.stringify(cleanRules(state.editorRules), null, 2);\n }\n async function exportSettings() {\n try {\n const response = await fetch(`${API}/api/settings`);\n const text = await response.text();\n if (!response.ok) throw new Error(text);\n download(text, `bothandler-settings-${today()}.json`, "application/json");\n toast("ok", "Settings exported", "Rules, plus a record of the configuration around them.");\n } catch (error) {\n toast("bad", "Export failed", String(error));\n }\n }\n function readSettingsFile(file) {\n const reader = new FileReader();\n reader.onload = () => {\n try {\n applyImported(JSON.parse(String(reader.result)), file.name);\n } catch (error) {\n toast("bad", "That file is not JSON", String(error));\n }\n };\n reader.onerror = () => toast("bad", "Could not read that file", "");\n reader.readAsText(file);\n }\n function applyImported(document_, name) {\n const rules = Array.isArray(document_) ? document_ : Array.isArray(document_.rules) ? document_.rules : void 0;\n if (rules === void 0) {\n toast("bad", "Nothing to import", "Expected an array of rules, or a settings file with a rules array.");\n return;\n }\n setEditorRules(rules);\n markDirty();\n switchToGui();\n const ignored = [];\n const readOnly = document_.readOnly;\n if (readOnly !== void 0) {\n ignored.push("the guard, the detectors, the ranges and the audit \u2014 those come from the code that built the handler, not from a file");\n if (Array.isArray(readOnly.lockedRules) && readOnly.lockedRules.length > 0) {\n ignored.push(`${readOnly.lockedRules.length} predicate rule(s), which stay as they are`);\n }\n }\n showResult("warn", (box) => {\n box.appendChild(el("div", null, `Loaded ${rules.length} rule(s) from ${name}. Nothing has been applied yet \u2014 preview it first.`));\n for (const line of ignored) box.appendChild(el("div", "ev-meta", `Ignored: ${line}`));\n });\n toast("ok", `Imported ${rules.length} rule(s)`, "Review, preview, then apply.");\n }\n function collectForSubmit() {\n const parsed = editorRules();\n if (parsed.error !== void 0) {\n showResult("bad", (box) => box.appendChild(el("div", null, parsed.error ?? "")));\n toast("bad", "That JSON will not parse", parsed.error);\n return void 0;\n }\n const cleaned = cleanRules(parsed.rules ?? []);\n const blank = cleaned.filter((rule) => rule["id"] === void 0 || rule["id"] === "").length;\n if (blank > 0) {\n toast("bad", "Every rule needs an id", "It is what every decision and log line names.");\n return void 0;\n }\n return cleaned;\n }\n async function runPreview(notes = []) {\n const rules = collectForSubmit();\n if (rules === void 0) return;\n const result = await postJson("/api/policy/preview", { rules });\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n renderPreview(result.data, notes);\n }\n async function applyPolicy() {\n const rules = collectForSubmit();\n if (rules === void 0) return;\n const result = await postJson("/api/policy/apply", { rules });\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n state.editorDirty = false;\n $("policy-dirty").hidden = true;\n await loadPolicy();\n toast("ok", "Applied", `${n(result.data.rules)} rule(s) now in force.`);\n showResult("ok", (box) => {\n box.appendChild(el("div", null, `Applied. ${n(result.data.rules)} rule(s) are now in force.`));\n for (const warning of result.data.warnings ?? []) box.appendChild(el("div", "ev-meta", warning));\n });\n }\n function renderPresetButtons() {\n const box = $("preset-buttons");\n const presets = state.policy?.vocabulary.presets ?? [];\n if (box.childElementCount === presets.length) return;\n clear(box);\n for (const preset of presets) {\n const button = el("button", null, preset);\n button.addEventListener("click", () => {\n void (async () => {\n const result = await postJson("/api/policy/preview", { preset });\n if (!result.ok) {\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n renderPreview(result.data);\n })();\n });\n box.appendChild(button);\n }\n }\n function initPolicy() {\n if (!SECTIONS.policy) return;\n $("mode-gui").addEventListener("click", switchToGui);\n $("mode-json").addEventListener("click", switchToJson);\n $("rule-add").addEventListener("click", () => {\n state.editorRules.push({ id: `new-rule-${state.editorRules.length + 1}`, match: {}, action: "tag", params: {}, _open: true });\n markDirty();\n renderEditor();\n });\n $("rule-expand").addEventListener("click", () => {\n const anyClosed = state.editorRules.some((rule) => rule._open !== true);\n for (const rule of state.editorRules) rule._open = anyClosed;\n $("rule-expand").textContent = anyClosed ? "Collapse all" : "Expand all";\n renderEditor();\n });\n byId("policy-json").addEventListener("input", markDirty);\n $("policy-preview").addEventListener("click", () => void runPreview());\n $("policy-apply").addEventListener("click", () => void applyPolicy());\n $("policy-revert").addEventListener("click", () => {\n state.editorDirty = false;\n $("policy-dirty").hidden = true;\n $("policy-result").hidden = true;\n resetGuardDraft();\n void loadPolicy();\n });\n $("policy-export").addEventListener("click", () => void exportSettings());\n $("policy-import").addEventListener("click", () => byId("policy-file").click());\n byId("policy-file").addEventListener("change", () => {\n const input = byId("policy-file");\n const file = input.files?.[0];\n if (file !== void 0) readSettingsFile(file);\n input.value = "";\n });\n const panel = $("editor-panel");\n for (const name of ["dragenter", "dragover"]) {\n panel.addEventListener(name, (event) => {\n if (state.policy?.editable !== true) return;\n event.preventDefault();\n panel.classList.add("drop");\n });\n }\n for (const name of ["dragleave", "drop"]) {\n panel.addEventListener(name, (event) => {\n panel.classList.remove("drop");\n if (name !== "drop") return;\n event.preventDefault();\n const file = event.dataTransfer?.files?.[0];\n if (file !== void 0) readSettingsFile(file);\n });\n }\n }\n\n // src/dashboard/client/feed.ts\n var FILTERS = [\n ["all", "All"],\n ["proven", "Proven"],\n ["suspected", "Suspected"],\n ["human", "Human"],\n ["guard", "Guard stops"],\n ["deny", "Denied"],\n ["mitigate", "Mitigated"],\n ["allow", "Served"]\n ];\n var rendered = /* @__PURE__ */ new Map();\n function initFeed() {\n const loadThem = byId("feed-load-skipped");\n loadThem.addEventListener("click", () => {\n loadThem.disabled = true;\n void loadSkipped().finally(() => {\n loadThem.disabled = false;\n });\n });\n const filters = $("filters");\n for (const [name, label2] of FILTERS) {\n const button = el("button", null, label2);\n button.setAttribute("aria-pressed", String(name === state.filter));\n button.dataset["filter"] = name;\n button.addEventListener("click", () => {\n state.filter = name;\n resetPaging();\n for (const other of Array.from(filters.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n app.syncUrl();\n app.drawNow();\n });\n filters.appendChild(button);\n }\n const search = byId("search");\n search.addEventListener("input", () => {\n setSearch(search.value.trim());\n app.syncUrl();\n app.drawNow();\n });\n const exportShown = byId("feed-export");\n exportShown.hidden = !SECTIONS.evidence;\n exportShown.addEventListener("click", () => {\n const rows = matchingRows();\n if (rows.length === 0) {\n toast("warn", "Nothing to export", "No request in the window matches this filter.");\n return;\n }\n const entries = rows.map((row) => row.entry).reverse();\n download(`${replayFile(entries)}\n`, `bothandler-feed-${today()}.jsonl`, "application/x-ndjson");\n toast("ok", `Exported ${n(entries.length)} request(s)`, "Replay them with `bothandlerjs replay`.");\n });\n }\n function reflectFilterButtons() {\n for (const button of Array.from($("filters").children)) {\n button.setAttribute("aria-pressed", String(button instanceof HTMLElement && button.dataset["filter"] === state.filter));\n }\n const search = byId("search");\n if (search.value !== state.search) search.value = state.search;\n }\n async function loadSkipped() {\n const before = state.rows.length;\n try {\n const body = await getJson("/api/feed");\n for (const entry of body.entries) ingest(entry);\n sortRows();\n } catch {\n toast("bad", "Could not load them", "The dashboard did not answer. The entries are still in the window; try again.");\n return;\n }\n state.caughtUp = (state.snapshot?.skipped ?? 0) + state.laggedDrops;\n const added = state.rows.length - before;\n resetPaging();\n app.drawNow();\n toast(\n added > 0 ? "ok" : "warn",\n added > 0 ? `Loaded ${n(added)}` : "Nothing left to load",\n added > 0 ? "They are in the feed now, in the order they happened." : "The window no longer holds them; the ring had already rotated past."\n );\n }\n var FEED_PAGE_SIZES = [25, 50, 100, 200];\n function drawPager(paged) {\n const size = state.feedPageSize;\n const hidden = paged.pages <= 1;\n const model = {\n page: paged.page,\n from: paged.page * size + 1,\n to: Math.min(paged.total, (paged.page + 1) * size),\n total: paged.total,\n atStart: paged.page === 0,\n atEnd: paged.page >= paged.pages - 1,\n ...paged.page > 0 ? { held: "held while you read" } : {},\n go: (page) => {\n goToFeedPage(page);\n app.drawNow();\n },\n size: {\n current: size,\n choices: FEED_PAGE_SIZES,\n set: (next) => {\n state.feedPageSize = next;\n resetPaging();\n app.drawNow();\n }\n }\n };\n for (const [id, withSize] of [\n ["feed-pager-top", true],\n ["feed-pager", false]\n ]) {\n const host = $(id);\n host.hidden = hidden;\n if (hidden) clear(host);\n else renderPager(host, model, { withSize });\n }\n }\n function drawFeed() {\n const body = byId("rows");\n const paged = feedPage(state.feedPageSize);\n const shown = paged.rows;\n let index = 0;\n const place = (node) => {\n const current = body.childNodes[index] ?? null;\n if (current !== node) body.insertBefore(node, current);\n index++;\n };\n for (const row of shown) {\n const id = row.entry.requestId;\n const open = state.open.has(id);\n let cached = rendered.get(id);\n if (cached === void 0 || cached.rev !== row.rev || cached.open !== open) {\n cached = {\n row: buildRow(row.entry, open),\n detail: open ? buildDetail(row.entry) : void 0,\n rev: row.rev,\n open\n };\n rendered.set(id, cached);\n }\n place(cached.row);\n if (cached.detail !== void 0) place(cached.detail);\n }\n while (body.childNodes.length > index) body.removeChild(body.childNodes[index]);\n if (rendered.size > shown.length * 2 + 100) {\n const live = new Set(shown.map((row) => row.entry.requestId));\n for (const id of Array.from(rendered.keys())) if (!live.has(id)) rendered.delete(id);\n }\n const total = state.rows.length;\n const matching = matchingCount();\n $("empty").hidden = total > 0;\n $("feed-count").textContent = matching === total ? `${n(total)} in this window` : `${n(matching)} of ${n(total)}`;\n drawPager(paged);\n const skipped = Math.max(0, (state.snapshot?.skipped ?? 0) + state.laggedDrops - state.caughtUp);\n const note = $("feed-skipped");\n note.hidden = skipped === 0;\n note.textContent = `${n(skipped)} not streamed`;\n byId("feed-load-skipped").hidden = skipped === 0;\n note.title = state.laggedDrops > 0 ? `${n(state.laggedDrops)} were skipped because this connection could not keep up, and the rest by the rate cap. All of them are still in the window, the preview and the export.` : "Entries the rate cap kept off this stream. They are still in the window, the preview and the export \u2014 raise maxEventsPerSecond to see them live.";\n }\n function resetFeedCache() {\n rendered.clear();\n }\n function buildRow(entry, open) {\n const out = outcome(entry);\n const tr = el("tr", `row a-${entry.downgradedFrom !== void 0 ? "guard" : out}${open ? " open" : ""}`);\n tr.appendChild(el("td", "num mono tnum when", clockTime(entry.at)));\n const request = el("td", "edge req");\n const toggle = el("button", "row-toggle", `${entry.method} ${entry.path}`);\n toggle.type = "button";\n toggle.setAttribute("aria-expanded", String(open));\n toggle.setAttribute("aria-label", `${entry.method} ${entry.path}, ${entry.verdict}. Evidence.`);\n toggle.dataset["request"] = entry.requestId;\n request.appendChild(toggle);\n const ua = el("span", "ua");\n if (SECTIONS.actors) {\n const actorLink = el("a", null, entry.actor);\n actorLink.href = "#actor";\n actorLink.title = "Show everything from this actor";\n actorLink.addEventListener("click", (event) => {\n event.preventDefault();\n event.stopPropagation();\n openActor(entry.actor);\n });\n ua.appendChild(actorLink);\n ua.appendChild(document.createTextNode(` \xB7 ${entry.userAgent}`));\n } else {\n ua.appendChild(document.createTextNode(`${entry.actor} \xB7 ${entry.userAgent}`));\n }\n ua.title = `${entry.actor} \xB7 ${entry.userAgent}`;\n request.appendChild(ua);\n tr.appendChild(request);\n const verdictCell = el("td");\n const [badgeClass, badgeLabel] = verdictBadge(entry);\n verdictCell.appendChild(el("span", `badge ${badgeClass}`, badgeLabel));\n if (entry.identity !== void 0) verdictCell.appendChild(el("span", "sub", entry.identity));\n tr.appendChild(verdictCell);\n tr.appendChild(el("td", "num mono tnum", entry.certain ? "proven" : String(entry.score)));\n const actionCell = el("td");\n if (entry.action !== void 0) {\n const kind = out === "deny" ? "act-deny" : out === "mitigate" ? "act-mitigate" : out === "allow" ? "act-allow" : "act-tag";\n actionCell.appendChild(el("span", `act ${kind}`, entry.action));\n if (entry.rule !== void 0) {\n const ruleLabel = el("span", "sub", entry.rule);\n ruleLabel.title = entry.rule;\n actionCell.appendChild(ruleLabel);\n }\n if (entry.downgradedFrom !== void 0) actionCell.appendChild(el("span", "guard", `guard stopped ${entry.downgradedFrom}`));\n } else {\n actionCell.appendChild(el("span", "sub", "assessed only"));\n }\n tr.appendChild(actionCell);\n tr.appendChild(el("td", "num mono tnum", entry.durationMs.toFixed(2)));\n tr.dataset["request"] = entry.requestId;\n const flip = () => {\n if (state.open.has(entry.requestId)) state.open.delete(entry.requestId);\n else state.open.add(entry.requestId);\n app.drawNow();\n rootNode().querySelector(`button.row-toggle[data-request="${cssEscape(entry.requestId)}"]`)?.focus();\n };\n toggle.addEventListener("click", (event) => {\n event.stopPropagation();\n flip();\n });\n tr.addEventListener("click", flip);\n return tr;\n }\n function buildDetail(entry) {\n const tr = el("tr", "detail");\n const cell = el("td");\n cell.colSpan = 6;\n if (!SECTIONS.evidence) {\n cell.appendChild(\n el(\n "div",\n "ev-meta",\n "The evidence section is switched off on this dashboard, so the reasons behind this verdict are not sent to it. What fired, and why, is on a dashboard that has `sections: { evidence: true }`."\n )\n );\n } else if (entry.evidence.length === 0) {\n cell.appendChild(\n el(\n "div",\n "ev-meta",\n entry.bypass !== void 0 ? `Detection was skipped for this request: ${entry.bypass}.` : "No detector produced any evidence. This is what ordinary traffic looks like."\n )\n );\n } else {\n const list = el("div", "ev");\n for (const item of entry.evidence) {\n const row = el("div", `ev-item${item.direction === "human" ? " human" : ""}`);\n row.appendChild(el("div", `tier t-${item.certainty}`, item.certainty));\n const body = el("div");\n body.appendChild(el("div", null, item.summary));\n let meta = `${item.detector} \xB7 points to ${item.direction}`;\n if (item.family !== void 0) meta += ` \xB7 family \u201C${item.family}\u201D, counted once with its siblings`;\n body.appendChild(el("div", "ev-meta", meta));\n if (item.deterministicBasis !== void 0) body.appendChild(el("div", "basis", item.deterministicBasis));\n row.appendChild(body);\n list.appendChild(row);\n }\n cell.appendChild(list);\n }\n for (const failure of entry.failures) {\n cell.appendChild(el("div", "ev-meta", `Detector ${failure.detector} ${failure.reason}: ${failure.message}`));\n }\n if (entry.downgradeReason !== void 0) cell.appendChild(el("div", "basis", `Guard: ${entry.downgradeReason}`));\n const queryNames = Object.keys(entry.query);\n if (queryNames.length > 0) {\n const queryTable = el("table", "hdr");\n for (const name of queryNames) {\n const value = entry.query[name] ?? "";\n const row = el("tr");\n row.appendChild(el("td", "n", `?${name}`));\n row.appendChild(el("td", `v${value === "[redacted]" ? " red" : ""}`, value));\n queryTable.appendChild(row);\n }\n cell.appendChild(queryTable);\n }\n if (entry.headers !== void 0 && entry.headers.length > 0) {\n const table = el("table", "hdr");\n for (const [name, value] of entry.headers) {\n const row = el("tr");\n row.appendChild(el("td", "n", `${name}:`));\n row.appendChild(el("td", `v${value === "[redacted]" ? " red" : ""}`, value));\n table.appendChild(row);\n }\n cell.appendChild(table);\n }\n const tools = el("div", "tools");\n if (SECTIONS.evidence) {\n tools.appendChild(copyButton("Copy replay line", () => replayLine(entry)));\n tools.appendChild(downloadButton("Download replay line", () => replayLine(entry), `request-${entry.requestId}.jsonl`));\n tools.appendChild(copyButton("Copy corpus case", () => corpusCase(entry)));\n }\n if (SECTIONS.policy) {\n const draft2 = el("button", null, "Draft a rule");\n draft2.title = "Start a rule from this request, in the policy editor";\n draft2.addEventListener("click", (event) => {\n event.stopPropagation();\n void draftIntoEditor(entry);\n });\n tools.appendChild(draft2);\n }\n if (SECTIONS.actors) {\n const actorButton = el("button", null, "Show this actor");\n actorButton.addEventListener("click", (event) => {\n event.stopPropagation();\n openActor(entry.actor);\n });\n tools.appendChild(actorButton);\n }\n cell.appendChild(tools);\n const foot = el("div", "detail-foot");\n foot.appendChild(el("span", null, clockTime(entry.at)));\n foot.appendChild(el("span", null, `actor ${entry.actor}`));\n if (entry.rule !== void 0) foot.appendChild(el("span", null, `rule \u201C${entry.rule}\u201D`));\n foot.appendChild(el("span", null, `assessed in ${entry.durationMs.toFixed(3)}ms`));\n foot.appendChild(el("span", "mono", entry.requestId));\n cell.appendChild(foot);\n tr.appendChild(cell);\n return tr;\n }\n function copyButton(label2, produce) {\n const button = el("button", null, label2);\n button.addEventListener("click", (event) => {\n event.stopPropagation();\n const text = produce();\n const done = () => {\n button.textContent = "Copied";\n setTimeout(() => {\n button.textContent = label2;\n }, 1200);\n };\n if (navigator.clipboard?.writeText !== void 0) navigator.clipboard.writeText(text).then(done, () => showText(text));\n else showText(text);\n });\n return button;\n }\n function downloadButton(label2, produce, filename) {\n const button = el("button", null, label2);\n button.addEventListener("click", (event) => {\n event.stopPropagation();\n download(`${produce()}\n`, filename, "application/x-ndjson");\n });\n return button;\n }\n function showText(text) {\n const box = el("pre", "code", text);\n const host = $("policy-result");\n host.hidden = false;\n host.className = "result";\n clear(host);\n host.appendChild(el("div", "ev-meta", "Copying needs a secure context; here is the text."));\n host.appendChild(box);\n const selection = getSelection();\n if (selection !== null) {\n const range = document.createRange();\n range.selectNodeContents(box);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n\n // src/dashboard/client/stream.ts\n var source;\n function connectStream() {\n if (!SECTIONS.feed) {\n $("dot").className = "dot";\n $("conn").textContent = "feed off";\n return;\n }\n if (source !== void 0) return;\n source = new EventSource(`${API}/api/stream`);\n source.addEventListener("open", () => {\n $("dot").className = "dot on";\n $("conn").textContent = "live";\n });\n source.addEventListener("sync", (event) => {\n const detail = JSON.parse(event.data);\n if (!detail.replace) return;\n clearFeed();\n resetFeedCache();\n });\n source.addEventListener("entry", (event) => {\n ingest(JSON.parse(event.data));\n if (state.paused) {\n state.bufferedWhilePaused++;\n $("pause").textContent = `Resume (${state.bufferedWhilePaused})`;\n }\n app.draw();\n });\n source.addEventListener("update", (event) => {\n ingest(JSON.parse(event.data));\n app.draw();\n });\n source.addEventListener("reset", () => {\n clearFeed();\n resetFeedCache();\n app.draw();\n });\n source.addEventListener("lagged", (event) => {\n const detail = JSON.parse(event.data);\n state.laggedDrops += detail.dropped;\n app.draw();\n });\n source.addEventListener("stats", (event) => {\n state.snapshot = JSON.parse(event.data);\n app.draw();\n });\n source.addEventListener("error", () => {\n $("dot").className = "dot off";\n $("conn").textContent = "reconnecting\u2026";\n });\n }\n async function loadInitialSnapshot() {\n try {\n state.snapshot = await getJson("/api/stats");\n app.drawNow();\n } catch {\n }\n }\n\n // src/dashboard/client/panels.ts\n var paintedSnapshot;\n function drawTiles(force = false) {\n if (!SECTIONS.statistics) return;\n const box = $("tiles");\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n if (!force && paintedSnapshot === snapshot) return;\n paintedSnapshot = snapshot;\n const metrics = snapshot.metrics;\n clear(box);\n if (metrics === void 0) {\n box.appendChild(el("div", "note", "Counters are switched off on this handler (metrics: false). The live feed still works."));\n return;\n }\n const actions = metrics.actions;\n const denied = actions.block + actions.drop + actions.redirect;\n const mitigated = actions.challenge + actions["rate-limit"] + actions.delay;\n const served = actions.allow + actions.tag + actions.log;\n const total = metrics.requests;\n const unremarkable = metrics.verdicts.unknown + metrics.verdicts.human;\n const provenBotCount = provenBots(metrics.verdicts);\n const actors = SECTIONS.registry ? { tab: "actors", label: "Actors" } : void 0;\n const tiles = [\n ["", n(total), "Requests", "since start", void 0],\n ["proven", n(provenBotCount), "Proven bots", `${pct(provenBotCount, total)} of traffic`, void 0],\n ["warn", n(metrics.verdicts["suspected-bot"]), "Suspected", "never denied alone", void 0],\n ["", n(unremarkable), "Unremarkable", `${pct(unremarkable, total)} of traffic`, void 0],\n ["warn", n(metrics.downgrades), "Guard stops", metrics.downgrades > 0 ? "a rule over-reached" : "no rule overreached", void 0],\n ["crit", n(denied), "Denied", `${pct(denied, total)} of traffic`, void 0],\n [\n "",\n n(mitigated),\n "Mitigated",\n metrics.challenges.issued > 0 ? `${n(metrics.challenges.solved)} of ${n(metrics.challenges.issued)} challenges solved` : "challenged or limited",\n void 0\n ],\n ["good", n(served), "Served", `${pct(served, total)} of traffic`, void 0],\n ["", n(metrics.actorsTracked), "Actors tracked", "in the registry now", actors]\n ];\n for (const [kind, value, key, sub, goes] of tiles) {\n const tile = goes === void 0 ? el("div", `tile ${kind}`) : el("button", `tile ${kind} go`);\n tile.appendChild(el("div", "v tnum", value));\n tile.appendChild(el("div", "k", key));\n tile.appendChild(el("div", "s", sub));\n if (goes !== void 0) {\n tile.type = "button";\n tile.appendChild(el("span", "sr-only", `. Show the ${goes.label} screen`));\n tile.addEventListener("click", () => app.showTab(goes.tab, { replace: false }));\n }\n box.appendChild(tile);\n }\n }\n function drawChips() {\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const box = $("chips");\n clear(box);\n const facts = [\n // Which process this is, first, because everything after it is a fact about this\n // process and nothing else. Behind a load balancer there are as many of these\n // dashboards as there are pods, each showing its own share of the traffic.\n ["instance", snapshot.instance],\n ["guard", snapshot.policy.falsePositivePolicy],\n ["suspect at", String(snapshot.policy.suspectThreshold)]\n ];\n if (SECTIONS.statistics) facts.push(["detectors", String(snapshot.detectors.length)]);\n if (SECTIONS.policy) facts.push(["rules", String(snapshot.rules.length)]);\n facts.push(["uptime", uptime(snapshot.now - snapshot.startedAt)]);\n for (const [label2, value] of facts) {\n const fact = el("span");\n fact.appendChild(document.createTextNode(`${label2} `));\n fact.appendChild(el("b", null, value));\n box.appendChild(fact);\n }\n }\n function updateWindowLabels() {\n const label2 = windowLabel(state.rows.length, oldestAt(), Date.now());\n for (const node of Array.from(rootNode().querySelectorAll(".win"))) node.textContent = label2;\n }\n function drawLivePanels() {\n if (!SECTIONS.statistics) return;\n const totals = aggregate(state.rows);\n drawBars($("live-detectors"), totals.detectors, "Nothing has fired in this window.");\n if (SECTIONS.actors) drawBars($("live-actors"), totals.actors, "No traffic in this window.");\n }\n function drawStatsPanels() {\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const metrics = snapshot.metrics;\n if (metrics !== void 0) {\n drawBars($("stat-verdicts"), pairs(metrics.verdicts), "Nothing assessed yet.");\n drawBars($("stat-actions"), pairs(metrics.actions), "No decisions yet.");\n drawBars($("stat-classes"), pairs(metrics.botClasses), "Nothing classified yet.");\n drawBars($("stat-detectors"), pairs(metrics.detectorFirings), "No detector has produced evidence yet.");\n const challenges = $("stat-challenges");\n clear(challenges);\n if (!snapshot.policy.challengeEnabled) {\n challenges.appendChild(el("div", "note", "No challenge is configured, so a rule asking for one degrades to a tag. Set challenge.secrets to enable it."));\n } else {\n const funnel = [\n ["Issued", n(metrics.challenges.issued)],\n ["Solved", n(metrics.challenges.solved)],\n ["Rejected", n(metrics.challenges.rejected)],\n ["Solve rate", metrics.challenges.issued > 0 ? pct(metrics.challenges.solved, metrics.challenges.issued) : "\u2014"]\n ];\n for (const [key, value] of funnel) challenges.appendChild(statRow(key, value));\n }\n const health = $("stat-health");\n clear(health);\n const bypassed = metrics.bypassed.allowlist + metrics.bypassed["ignored-path"];\n const rows = [\n ["Requests assessed", n(metrics.requests)],\n ["Bypassed \u2014 allowlist", n(metrics.bypassed.allowlist)],\n ["Bypassed \u2014 ignored path", n(metrics.bypassed["ignored-path"])],\n ["Detection ran on", pct(metrics.requests - bypassed, metrics.requests)],\n ["Actors tracked", n(metrics.actorsTracked)],\n ["Guard stops", n(metrics.downgrades)]\n ];\n const failures = pairs(metrics.detectorFailures);\n for (const [detector, count] of failures) rows.push([`Detector failures \u2014 ${detector}`, n(count)]);\n for (const [key, value] of rows) health.appendChild(statRow(key, value));\n if (failures.length === 0) health.appendChild(el("div", "note", "No detector has thrown or timed out."));\n }\n const totals = aggregate(state.rows);\n if (SECTIONS.actors) drawBars($("stat-identities"), totals.identities, "No client has named itself in this window.");\n drawBars($("stat-paths"), totals.paths, "No traffic in this window.");\n drawBars($("stat-denied-paths"), totals.deniedPaths, "Nothing has been denied in this window.");\n drawBars($("stat-guard"), totals.guardStops, "No rule has asked for more than its evidence supports.");\n drawBars($("stat-bypassed"), totals.bypassed, "Nothing bypassed detection.");\n drawRuleHits(totals);\n const list = $("stat-detector-list");\n clear(list);\n $("detector-count").textContent = `${snapshot.detectors.length} installed`;\n for (const detector of snapshot.detectors) {\n const row = el("div", "det");\n const left = el("div");\n left.appendChild(el("div", "mono", detector.id));\n left.appendChild(el("div", "d", detector.description));\n row.appendChild(left);\n const fires = metrics?.detectorFirings[detector.id] ?? 0;\n const timing = metrics?.detectorTimings[detector.id];\n let right = `${n(fires)} \xB7 ${detector.cost} \xB7 ${detector.stage}`;\n if (timing !== void 0 && timing.count > 0) right += ` \xB7 ${ms(timing.totalMs / timing.count)} avg`;\n row.appendChild(el("div", "n", right));\n list.appendChild(row);\n }\n }\n function statRow(key, value) {\n const line = el("div", "stat-row");\n line.appendChild(el("span", "k", key));\n line.appendChild(el("span", "v", value));\n return line;\n }\n function drawRuleHits(totals) {\n const target = $("stat-rule-hits");\n clear(target);\n const rules = state.snapshot?.rules ?? [];\n if (rules.length === 0) {\n target.appendChild(el("div", "note", "No rules configured."));\n return;\n }\n let max = 1;\n for (const rule of rules) max = Math.max(max, totals.ruleHits.get(rule) ?? 0);\n for (const rule of rules) {\n const value = totals.ruleHits.get(rule) ?? 0;\n const bar = el("div", `bar${value === 0 ? " dead" : ""}`);\n const track = el("div", "track");\n if (value > 0) {\n const fill = el("div", "fill");\n fill.style.width = `${Math.max(2, Math.round(value / max * 100))}%`;\n track.appendChild(fill);\n }\n track.appendChild(el("div", "lbl", rule));\n bar.appendChild(track);\n bar.appendChild(el("div", "v tnum", value === 0 ? "never" : n(value)));\n target.appendChild(bar);\n }\n }\n function drawAudit() {\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const body = $("audit-body");\n const checks = $("audit-checks");\n clear(body);\n clear(checks);\n const audit = snapshot.audit;\n if (audit === void 0) {\n $("audit-spans").textContent = "";\n body.appendChild(\n el(\n "div",\n "note",\n "The traffic audit is switched off on this handler (audit: false). It watches the shape of your traffic rather than any one request \u2014 a spike in automation, a collapse in human traffic, a policy suddenly denying far more than usual."\n )\n );\n return;\n }\n const current = audit.window;\n const baseline = audit.baseline;\n $("audit-spans").textContent = `last ${rangeLabel(current.spanMs)} against the ${rangeLabel(baseline.spanMs)} before`;\n const rows = [\n ["Requests", n(current.requests), n(baseline.requests)],\n ["Rate", `${current.rate.toFixed(1)}/min`, `${baseline.rate.toFixed(1)}/min`],\n ["Bot share", `${Math.round(current.botShare * 100)}%`, `${Math.round(baseline.botShare * 100)}%`],\n ["Bots", n(current.bots), n(baseline.bots)],\n ["Humans", n(current.humans), n(baseline.humans)],\n ["Denials", n(current.denials), n(baseline.denials)],\n ["Challenges", n(current.challenges), n(baseline.challenges)],\n ["Guard stops", n(current.downgrades), n(baseline.downgrades)],\n ["Detector failures", n(current.failures), n(baseline.failures)],\n ["Bypassed", n(current.bypassed), n(baseline.bypassed)]\n ];\n for (const [key, now, was] of rows) {\n const line = el("div", "stat-row");\n line.appendChild(el("span", "k", key));\n const values = el("span", "v");\n values.appendChild(el("b", null, now));\n values.appendChild(el("span", "was", ` was ${was}`));\n line.appendChild(values);\n body.appendChild(line);\n }\n if (audit.checks.length === 0) {\n checks.appendChild(el("div", "note", "No checks are installed, so nothing here will ever raise an anomaly."));\n return;\n }\n for (const check of audit.checks) {\n const row = el("div", "det");\n const left = el("div");\n left.appendChild(el("div", "mono", check.id));\n left.appendChild(el("div", "d", check.description));\n row.appendChild(left);\n checks.appendChild(row);\n }\n }\n function drawNoticeBadge() {\n const notices = state.snapshot?.notices ?? [];\n const badge = $("notice-badge");\n badge.hidden = notices.length === 0 || !SECTIONS.notices;\n badge.textContent = String(notices.length);\n }\n function drawNotices() {\n const box = $("stat-notices");\n const notices = state.snapshot?.notices ?? [];\n clear(box);\n $("notice-count").textContent = notices.length > 0 ? `${notices.length} total` : "";\n if (notices.length === 0) {\n box.appendChild(el("div", "note", "Nothing to report: no startup warnings, no detector errors."));\n return;\n }\n for (const notice of notices.slice().reverse().slice(0, 40)) {\n const row = el("div", `notice ${notice.kind}`);\n const when = el("div", "when");\n when.appendChild(el("div", "tag", notice.kind));\n when.appendChild(el("div", null, clockTime(notice.at)));\n row.appendChild(when);\n const body = el("div");\n body.appendChild(el("div", null, notice.message));\n if (notice.source !== void 0) body.appendChild(el("div", "ev-meta", notice.source));\n row.appendChild(body);\n box.appendChild(row);\n }\n }\n function drawChanges() {\n if (!SECTIONS.changes) return;\n const box = $("stat-changes");\n const changes = state.snapshot?.changes ?? [];\n clear(box);\n $("change-count").textContent = changes.length > 0 ? `${changes.length} this run` : "";\n if (changes.length === 0) {\n box.appendChild(el("div", "note", "Nothing has been changed at runtime. Rules, guard and ranges are as the code that built this handler left them."));\n return;\n }\n for (const change of changes.slice().reverse()) {\n const row = el("div", "notice");\n const when = el("div", "when");\n when.appendChild(el("div", "tag", change.kind));\n when.appendChild(el("div", null, clockTime(change.at)));\n row.appendChild(when);\n const body = el("div");\n body.appendChild(el("div", null, change.summary));\n body.appendChild(el("div", "ev-meta", change.by === void 0 || change.by === "" ? "by an unnamed viewer \u2014 this listener\'s auth carries no identity" : `by ${change.by}`));\n row.appendChild(body);\n box.appendChild(row);\n }\n }\n function drawPeers() {\n const box = $("peers");\n if (BOOT.peers.length === 0) {\n box.hidden = true;\n return;\n }\n if (box.childElementCount > 0) return;\n box.appendChild(el("span", "hint", "also:"));\n for (const peer of BOOT.peers) {\n const link = el("a", "linkbtn", peer.label);\n link.href = peer.href;\n link.rel = "noreferrer noopener";\n box.appendChild(link);\n }\n }\n\n // src/dashboard/client/charts.ts\n var BUCKETS = 60;\n var LATENCY_BOUNDS = [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 25, 50, 100];\n var SCORE_BOUNDS = 10;\n function positionTip(tip, host, clientX, boxLeft) {\n tip.style.opacity = "1";\n tip.style.left = `${Math.min(host.clientWidth - 150, Math.max(4, clientX - boxLeft - 60))}px`;\n tip.style.top = "14px";\n }\n function tipRow(label2, value, colour) {\n const line = el("div", "r");\n const left = el("em");\n if (colour !== void 0) {\n const swatch = el("span", "swatch");\n swatch.style.background = colour;\n left.appendChild(swatch);\n }\n left.appendChild(document.createTextNode(label2));\n line.appendChild(left);\n line.appendChild(el("b", null, value));\n return line;\n }\n function timeline() {\n const bucketMs = state.rangeMs / BUCKETS;\n const now = Date.now();\n const start2 = now - state.rangeMs;\n const buckets = [];\n for (let i = 0; i < BUCKETS; i++) buckets.push({ at: start2 + i * bucketMs, served: 0, mitigated: 0, denied: 0, total: 0 });\n for (const { entry } of state.rows) {\n const index = Math.floor((entry.at - start2) / bucketMs);\n if (index < 0 || index >= BUCKETS) continue;\n const bucket = buckets[index];\n if (bucket === void 0) continue;\n bucket.total++;\n const out = outcome(entry);\n if (out === "deny") bucket.denied++;\n else if (out === "mitigate") bucket.mitigated++;\n else bucket.served++;\n }\n return buckets;\n }\n function drawTraffic() {\n const host = $("traffic-chart");\n const svg = $("traffic");\n const width = Math.max(320, host.clientWidth - 30);\n const height = 190;\n const padBottom = 26;\n const markerRow = 8;\n const plot = height - padBottom - markerRow;\n const buckets = timeline();\n const now = Date.now();\n const start2 = now - state.rangeMs;\n let peak = 1;\n for (const bucket of buckets) if (bucket.total > peak) peak = bucket.total;\n const max = Math.max(2, Math.ceil(peak / 2) * 2);\n clear(svg);\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n svg.setAttribute("height", String(height));\n const s1 = css("--s1");\n const s2 = css("--s2");\n const crit = css("--crit");\n const grid = css("--grid");\n const muted = css("--muted");\n const step = width / BUCKETS;\n const barWidth = Math.max(2, step - 2);\n for (const fraction of [0, 0.5, 1]) {\n const y = markerRow + plot - fraction * plot;\n svg.appendChild(svgEl("line", { class: "gridline", x1: 0, x2: width, y1: y, y2: y, stroke: grid, "stroke-width": 1 }));\n if (fraction > 0) svg.appendChild(svgText({ x: 2, y: y - 3, fill: muted, "font-size": 10 }, Math.round(max * fraction)));\n }\n buckets.forEach((bucket, index) => {\n const x = index * step + 1;\n const servedHeight = bucket.served / max * plot;\n const mitigatedHeight = bucket.mitigated / max * plot;\n let y = markerRow + plot;\n if (servedHeight > 0) {\n y -= servedHeight;\n svg.appendChild(svgEl("rect", { x, y, width: barWidth, height: servedHeight, fill: s1, rx: 2 }));\n }\n if (mitigatedHeight > 0) {\n y -= mitigatedHeight + (servedHeight > 0 ? 2 : 0);\n svg.appendChild(svgEl("rect", { x, y: Math.max(markerRow, y), width: barWidth, height: mitigatedHeight, fill: s2, rx: 2 }));\n }\n if (bucket.denied > 0) svg.appendChild(svgEl("rect", { x, y: 0, width: barWidth, height: 5, fill: crit, rx: 2 }));\n });\n svg.appendChild(svgEl("line", { x1: 0, x2: width, y1: markerRow + plot, y2: markerRow + plot, stroke: css("--line"), "stroke-width": 1 }));\n const span = rangeLabel(state.rangeMs);\n const labels = [\n [0, `${span} ago`],\n [BUCKETS / 2, rangeLabel(state.rangeMs / 2)],\n [BUCKETS - 1, "now"]\n ];\n for (const [position, text] of labels) {\n svg.appendChild(svgText({ x: Math.min(width - 26, Math.max(0, position * step)), y: height - 8, fill: muted, "font-size": 10 }, text));\n }\n const changes = (state.snapshot?.changes ?? []).filter((change) => change.at >= start2 && change.at <= now);\n const markColour = css("--proven-text");\n for (const change of changes) {\n const x = (change.at - start2) / state.rangeMs * width;\n svg.appendChild(svgEl("line", { x1: x, x2: x, y1: 0, y2: markerRow + plot, stroke: markColour, "stroke-width": 1.5, "stroke-dasharray": "3 2", opacity: 0.85 }));\n const dot = svgEl("circle", { cx: x, cy: 3, r: 3, fill: markColour });\n const title = svgEl("title");\n title.textContent = `${clockTime(change.at)} \xB7 ${change.kind}: ${change.summary}${change.by === void 0 ? "" : ` (by ${change.by})`}`;\n dot.appendChild(title);\n svg.appendChild(dot);\n }\n const hover = svgEl("rect", { x: 0, y: 0, width: 0, height: markerRow + plot, fill: css("--ink"), opacity: 0.06 });\n svg.appendChild(hover);\n const tip = $("traffic-tip");\n host.onmousemove = (event) => {\n const box = svg.getBoundingClientRect();\n const index = Math.floor((event.clientX - box.left) / box.width * BUCKETS);\n const bucket = buckets[index];\n if (bucket === void 0) {\n tip.style.opacity = "0";\n hover.setAttribute("width", "0");\n return;\n }\n hover.setAttribute("x", String(index * step));\n hover.setAttribute("width", String(step));\n clear(tip);\n tip.appendChild(el("div", "t", `${clockTime(bucket.at)} \xB7 ${Math.round(state.rangeMs / BUCKETS / 1e3)}s`));\n tip.appendChild(tipRow("Served", n(bucket.served), s1));\n tip.appendChild(tipRow("Mitigated", n(bucket.mitigated), s2));\n tip.appendChild(tipRow("Denied", n(bucket.denied), crit));\n positionTip(tip, host, event.clientX, box.left);\n };\n host.onmouseleave = () => {\n tip.style.opacity = "0";\n hover.setAttribute("width", "0");\n };\n const total = buckets.reduce((sum, bucket) => sum + bucket.total, 0);\n $("traffic-window").textContent = `last ${rangeLabel(state.rangeMs)}`;\n const served = buckets.reduce((sum, bucket) => sum + bucket.served, 0);\n const mitigated = buckets.reduce((sum, bucket) => sum + bucket.mitigated, 0);\n const denied = buckets.reduce((sum, bucket) => sum + bucket.denied, 0);\n const busiest = buckets.reduce((best, bucket) => bucket.total > best.total ? bucket : best, buckets[0] ?? { at: now, total: 0, served: 0, mitigated: 0, denied: 0 });\n $("traffic-alt").textContent = `Traffic over the last ${rangeLabel(state.rangeMs)}: ${n(total)} requests \u2014 ${n(served)} served, ${n(mitigated)} mitigated, ${n(denied)} denied. ` + (total === 0 ? "No traffic in this range." : `Busiest ${Math.round(state.rangeMs / BUCKETS / 1e3)}-second interval: ${n(busiest.total)} requests at ${clockTime(busiest.at)}.`) + (changes.length === 0 ? "" : ` ${n(changes.length)} runtime change${changes.length === 1 ? "" : "s"} in this range: ${changes.map((change) => `${change.kind}, ${change.summary}`).join("; ")}.`);\n const legend = $("traffic-legend");\n clear(legend);\n legend.appendChild(el("span", null, `${n(total)} requests in the last ${rangeLabel(state.rangeMs)} \xB7`));\n const oldest = oldestAt();\n if (oldest !== void 0 && Date.now() - oldest < state.rangeMs * 0.9) {\n legend.appendChild(el("span", null, `window holds ${rangeLabel(Date.now() - oldest)} \xB7`));\n }\n for (const [label2, colour] of [\n ["Served", s1],\n ["Mitigated \u2014 challenged, limited or delayed", s2],\n ["Denied", crit]\n ]) {\n const item = el("span");\n const swatch = el("span", "swatch");\n swatch.style.background = colour;\n item.appendChild(swatch);\n item.appendChild(document.createTextNode(label2));\n legend.appendChild(item);\n }\n if (changes.length > 0) {\n const item = el("span");\n item.appendChild(el("span", "mark"));\n item.appendChild(document.createTextNode(`${n(changes.length)} runtime change${changes.length === 1 ? "" : "s"} \u2014 hover a marker`));\n legend.appendChild(item);\n }\n }\n function differences(cumulative) {\n const counts = [];\n for (let i = 0; i < cumulative.length; i++) counts.push((cumulative[i] ?? 0) - (i > 0 ? cumulative[i - 1] ?? 0 : 0));\n return counts;\n }\n function drawScores() {\n const host = $("score-chart");\n const svg = $("scores");\n clear(svg);\n const metrics = state.snapshot?.metrics;\n const fromRun = state.scoreScope === "run" && metrics !== void 0;\n let buckets;\n let scored;\n let proven;\n if (fromRun && metrics !== void 0) {\n buckets = differences(metrics.scores.buckets);\n scored = metrics.scores.count;\n proven = metrics.proven;\n } else {\n buckets = new Array(SCORE_BOUNDS).fill(0);\n scored = 0;\n proven = 0;\n for (const { entry } of state.rows) {\n if (entry.bypass !== void 0) continue;\n if (entry.certain) {\n proven++;\n continue;\n }\n const index = Math.min(SCORE_BOUNDS - 1, Math.floor(entry.score / 10));\n buckets[index] = (buckets[index] ?? 0) + 1;\n scored++;\n }\n }\n const width = Math.max(280, host.clientWidth - 30);\n const height = 190;\n const padBottom = 30;\n const plot = height - padBottom;\n let max = 1;\n for (const value of buckets) if (value > max) max = value;\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n svg.setAttribute("height", String(height));\n const fill = css("--s1");\n const muted = css("--muted");\n const grid = css("--grid");\n const crit = css("--crit");\n svg.appendChild(svgEl("line", { class: "gridline", x1: 0, x2: width, y1: plot, y2: plot, stroke: grid, "stroke-width": 1 }));\n const step = width / SCORE_BOUNDS;\n buckets.forEach((value, index) => {\n const barHeight = value / max * (plot - 8);\n const barWidth = Math.max(2, Math.min(step - 6, 56));\n if (barHeight > 0) {\n svg.appendChild(svgEl("rect", { x: index * step + (step - barWidth) / 2, y: plot - barHeight, width: barWidth, height: barHeight, fill, rx: 3 }));\n }\n svg.appendChild(svgText({ x: index * step + 1, y: height - 14, fill: muted, "font-size": 9.5 }, index * 10));\n });\n const threshold = state.snapshot?.policy.suspectThreshold ?? 60;\n const x = threshold / 100 * width;\n svg.appendChild(svgEl("line", { x1: x, x2: x, y1: 0, y2: plot, stroke: crit, "stroke-width": 2, "stroke-dasharray": "4 3" }));\n svg.appendChild(svgText({ x: Math.min(width - 92, x + 5), y: 11, fill: crit, "font-size": 10 }, `suspect at ${threshold}`));\n svg.appendChild(svgText({ x: 0, y: height - 2, fill: muted, "font-size": 10 }, "score (probabilistic requests only)"));\n const tip = $("score-tip");\n host.onmousemove = (event) => {\n const box = svg.getBoundingClientRect();\n const index = Math.floor((event.clientX - box.left) / box.width * SCORE_BOUNDS);\n const value = buckets[index];\n if (value === void 0) {\n tip.style.opacity = "0";\n return;\n }\n clear(tip);\n tip.appendChild(el("div", "t", `score ${index * 10}\u2013${index * 10 + 9}`));\n tip.appendChild(tipRow("requests", n(value)));\n tip.appendChild(tipRow("share", pct(value, scored)));\n positionTip(tip, host, event.clientX, box.left);\n };\n host.onmouseleave = () => {\n tip.style.opacity = "0";\n };\n let over = 0;\n for (let bucket = 0; bucket < SCORE_BOUNDS; bucket++) if (bucket * 10 >= threshold) over += buckets[bucket] ?? 0;\n const legend = $("score-legend");\n clear(legend);\n legend.appendChild(el("span", null, `${n(scored)} scored \xB7 ${n(over)} at or over the threshold \xB7 ${n(proven)} proven, which carry no score`));\n $("score-alt").textContent = `Distribution of probabilistic scores ${fromRun ? "since start" : "in the retained window"}, with the suspect threshold at ${threshold}. ${n(scored)} scored requests, ${n(over)} at or over the threshold, ${n(proven)} proven and therefore unscored. ` + (scored === 0 ? "Nothing scored yet." : `By ten-point band: ${buckets.map((value, index) => `${index * 10}\u2013${index * 10 + 9}: ${n(value)}`).join(", ")}.`);\n $("score-window").textContent = fromRun ? "since start" : windowLabel(state.rows.length, oldestAt(), Date.now());\n if (state.scoreScope === "run" && metrics === void 0) {\n legend.appendChild(el("span", null, "\xB7 counters are off on this handler, so this is the retained window"));\n }\n }\n function drawLatency() {\n const host = $("latency-chart");\n const svg = $("latency");\n clear(svg);\n const metrics = state.snapshot?.metrics;\n if (metrics === void 0 || metrics.duration.count === 0) {\n $("latency-summary").textContent = "No assessments yet.";\n $("latency-alt").textContent = "Assessment latency: no assessments yet.";\n svg.setAttribute("viewBox", "0 0 100 40");\n svg.setAttribute("height", "40");\n svg.appendChild(svgText({ x: 0, y: 20, fill: css("--muted"), "font-size": 11 }, "No assessments yet."));\n return;\n }\n const cumulative = metrics.duration.buckets;\n const counts = differences(cumulative);\n const width = Math.max(280, host.clientWidth - 30);\n const height = 190;\n const padBottom = 30;\n const plot = height - padBottom;\n let max = 1;\n for (const value of counts) if (value > max) max = value;\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n svg.setAttribute("height", String(height));\n const fill = css("--s1");\n const muted = css("--muted");\n const grid = css("--grid");\n svg.appendChild(svgEl("line", { class: "gridline", x1: 0, x2: width, y1: plot, y2: plot, stroke: grid, "stroke-width": 1 }));\n const step = width / counts.length;\n counts.forEach((value, index) => {\n const barHeight = value / max * (plot - 6);\n if (barHeight > 0) {\n svg.appendChild(svgEl("rect", { x: index * step + 1, y: plot - barHeight, width: Math.max(2, step - 3), height: barHeight, fill, rx: 3 }));\n }\n if (index % 2 === 0) {\n svg.appendChild(svgText({ x: index * step + 1, y: height - 14, fill: muted, "font-size": 9.5 }, index < LATENCY_BOUNDS.length ? String(LATENCY_BOUNDS[index]) : "more"));\n }\n });\n svg.appendChild(svgText({ x: 0, y: height - 2, fill: muted, "font-size": 10 }, "milliseconds (upper bound of each bucket)"));\n const tip = $("latency-tip");\n host.onmousemove = (event) => {\n const box = svg.getBoundingClientRect();\n const index = Math.floor((event.clientX - box.left) / box.width * counts.length);\n const value = counts[index];\n if (value === void 0) {\n tip.style.opacity = "0";\n return;\n }\n clear(tip);\n tip.appendChild(el("div", "t", index < LATENCY_BOUNDS.length ? `\u2264 ${LATENCY_BOUNDS[index]}ms` : "over 100ms"));\n tip.appendChild(tipRow("requests", n(value)));\n tip.appendChild(tipRow("share", pct(value, metrics.duration.count)));\n positionTip(tip, host, event.clientX, box.left);\n };\n host.onmouseleave = () => {\n tip.style.opacity = "0";\n };\n const mean = metrics.duration.totalMs / metrics.duration.count;\n const p95 = percentile(cumulative, metrics.duration.count, 0.95);\n $("latency-summary").textContent = `Time spent in detection, per request \xB7 mean ${ms(mean)} \xB7 p95 ${ms(p95)} \xB7 max ${ms(metrics.duration.maxMs)}`;\n $("latency-alt").textContent = `Assessment latency since start over ${n(metrics.duration.count)} requests: mean ${ms(mean)}, 95th percentile ${ms(p95)}, maximum ${ms(metrics.duration.maxMs)}. By bucket: ${counts.map((value, index) => `${index < LATENCY_BOUNDS.length ? `up to ${LATENCY_BOUNDS[index]}ms` : "over 100ms"}: ${n(value)}`).join(", ")}.`;\n }\n function percentile(cumulative, count, fraction) {\n const target = count * fraction;\n const last = LATENCY_BOUNDS[LATENCY_BOUNDS.length - 1] ?? 100;\n for (let i = 0; i < cumulative.length; i++) {\n if ((cumulative[i] ?? 0) >= target) return i < LATENCY_BOUNDS.length ? LATENCY_BOUNDS[i] ?? last : last;\n }\n return last;\n }\n\n // src/dashboard/client/registry.ts\n var timer;\n async function loadActors() {\n if (!SECTIONS.registry) return;\n try {\n const body = await getJson(`/api/actors?limit=${state.actorsPageSize}&offset=${state.actorsPage * state.actorsPageSize}`);\n state.actors = body.actors;\n state.actorsTracked = body.tracked;\n drawActors();\n } catch {\n }\n }\n function trackActors() {\n if (timer !== void 0) clearInterval(timer);\n timer = void 0;\n if (state.tab !== "actors") return;\n void loadActors();\n timer = setInterval(() => {\n if (state.tab !== "actors" || state.paused || isConfirming()) return;\n void loadActors();\n }, 4e3);\n }\n var ACTORS_PAGE_SIZES = [25, 50, 100, 200];\n function drawActorsPager(full) {\n const page = state.actorsPage;\n const hidden = page === 0 && !full;\n const from = page * state.actorsPageSize + 1;\n const model = {\n page,\n from,\n to: from + state.actors.length - 1,\n total: state.actorsTracked,\n atStart: page === 0,\n atEnd: !full,\n go: (next) => {\n state.actorsPage = Math.max(0, next);\n void loadActors();\n },\n size: {\n current: state.actorsPageSize,\n choices: ACTORS_PAGE_SIZES,\n set: (next) => {\n state.actorsPageSize = next;\n state.actorsPage = 0;\n void loadActors();\n }\n }\n };\n for (const [id, withSize] of [\n ["actors-pager-top", true],\n ["actors-pager", false]\n ]) {\n const host = $(id);\n host.hidden = hidden;\n if (hidden) clear(host);\n else renderPager(host, model, { withSize });\n }\n }\n function drawActors() {\n if (!SECTIONS.registry) return;\n if (isConfirming()) return;\n const body = byId("actor-rows");\n clear(body);\n const actors = state.actors;\n $("actors-count").textContent = `${n(actors.length)} shown \xB7 ${n(state.actorsTracked)} tracked`;\n drawActorsPager(actors.length === state.actorsPageSize);\n byId("actors-empty").hidden = actors.length > 0;\n for (const actor of actors) {\n const row = el("tr");\n row.appendChild(el("td", "who", actor.key));\n row.appendChild(el("td", "num tnum", n(actor.requests)));\n row.appendChild(el("td", "num tnum", n(actor.recentRate)));\n row.appendChild(el("td", "num tnum", n(actor.distinctPaths)));\n const cadence = el("td", "num tnum", actor.cadenceCv === void 0 ? "\u2014" : actor.cadenceCv.toFixed(2));\n if (actor.cadenceCv !== void 0 && actor.cadenceCv < 0.15) cadence.className += " warn-text";\n row.appendChild(cadence);\n row.appendChild(el("td", "num tnum", n(actor.priorConfirmations)));\n const unsolved = el("td", "num tnum", n(actor.unsolvedChallenges));\n if (actor.unsolvedChallenges >= 3) unsolved.className += " warn-text";\n row.appendChild(unsolved);\n const stateCell = el("td");\n const tags = [];\n if (actor.cleared) tags.push("cleared as human");\n if (actor.distinctUserAgents > 1) tags.push(`${actor.distinctUserAgents} User-Agents`);\n tags.push(`first seen ${clockStamp(actor.firstSeen)}`);\n stateCell.appendChild(el("div", "tagline", tags.join(" \xB7 ")));\n row.appendChild(stateCell);\n const actions = el("td", "acts");\n const inFeed = el("button", null, "In feed");\n inFeed.title = "Show this actor\'s requests in the live feed";\n inFeed.addEventListener("click", () => {\n setSearch(`actor:${actor.key}`);\n const search = byId("search");\n search.value = state.search;\n app.showTab("live");\n app.syncUrl();\n });\n actions.appendChild(inFeed);\n for (const button of actorActions(actor.key, () => void loadActors())) actions.appendChild(button);\n row.appendChild(actions);\n body.appendChild(row);\n }\n }\n\n // src/dashboard/client/tester.ts\n function initTester() {\n if (!SECTIONS.tester) return;\n $("test-run").addEventListener("click", () => void run());\n byId("test-input").addEventListener("keydown", (event) => {\n if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {\n event.preventDefault();\n void run();\n }\n });\n }\n async function run() {\n const raw2 = byId("test-input").value;\n if (raw2.trim() === "") {\n toast("warn", "Nothing to assess", "Paste a User-Agent, a curl command, or a header block.");\n return;\n }\n const result = await postJson("/api/test", {\n raw: raw2,\n ip: byId("test-ip").value.trim(),\n url: byId("test-url").value.trim()\n });\n const box = $("test-result");\n box.hidden = false;\n clear(box);\n if (!result.ok) {\n box.className = "result bad";\n box.appendChild(el("div", null, result.error ?? "The server could not read that."));\n return;\n }\n const { entry, reason, assumed } = result.data;\n const out = outcome(entry);\n box.className = `result ${out === "deny" ? "bad" : out === "mitigate" ? "warn" : "ok"}`;\n const head = el("div");\n const [badgeClass, badgeLabel] = verdictBadge(entry);\n head.appendChild(el("span", `badge ${badgeClass}`, badgeLabel));\n head.appendChild(document.createTextNode(" "));\n head.appendChild(el("b", null, entry.action ?? "no decision"));\n if (entry.rule !== void 0) head.appendChild(el("span", "ev-meta", ` via ${entry.rule}`));\n box.appendChild(head);\n box.appendChild(el("div", "ev-meta", `${entry.certain ? "proven" : `score ${entry.score}`} \xB7 assessed in ${ms(entry.durationMs)}`));\n if (entry.downgradedFrom !== void 0) {\n box.appendChild(el("div", "guard", `The guard stopped ${entry.downgradedFrom} here.`));\n if (entry.downgradeReason !== void 0) box.appendChild(el("div", "basis", entry.downgradeReason));\n }\n if (entry.evidence.length === 0) {\n box.appendChild(el("div", "ev-meta", entry.bypass !== void 0 ? `Detection was skipped: ${entry.bypass}.` : "No detector produced any evidence."));\n } else {\n const list = el("div", "ev");\n for (const item of entry.evidence) {\n const row = el("div", `ev-item${item.direction === "human" ? " human" : ""}`);\n row.appendChild(el("div", `tier t-${item.certainty}`, item.certainty));\n const detail = el("div");\n detail.appendChild(el("div", null, item.summary));\n detail.appendChild(el("div", "ev-meta", `${item.detector} \xB7 points to ${item.direction}`));\n if (item.deterministicBasis !== void 0) detail.appendChild(el("div", "basis", item.deterministicBasis));\n row.appendChild(detail);\n list.appendChild(row);\n }\n box.appendChild(list);\n }\n box.appendChild(el("div", "ev-meta", reason));\n const notes = [...assumed, "no history: this is assessed as a first request, so cadence and crawl breadth have nothing to read"];\n box.appendChild(el("div", "assumed", `Assumed \u2014 ${notes.join("; ")}.`));\n }\n\n // src/dashboard/client/index.ts\n var TABS = [\n ["tab-live", "live", SECTIONS.feed],\n ["tab-actors", "actors", SECTIONS.registry],\n ["tab-stats", "stats", SECTIONS.statistics],\n ["tab-policy", "policy", SECTIONS.policy]\n ];\n var available = TABS.filter(([, , enabled]) => enabled);\n var FIRST = available[0]?.[1] ?? "live";\n function tabIndexOf(name) {\n const at = available.findIndex(([, tab]) => tab === name);\n return at === -1 ? 0 : at;\n }\n function isTab(value) {\n return available.some(([, name]) => name === value);\n }\n function initSkipLink() {\n if (!isEmbedded()) return;\n const skip = rootNode().querySelector("a.skip");\n if (skip === null) return;\n skip.addEventListener("click", (event) => {\n event.preventDefault();\n const target = rootNode().querySelector(`#view-${state.tab}`) ?? rootNode().querySelector("#view-live");\n if (target === null) return;\n target.tabIndex = -1;\n target.focus();\n target.scrollIntoView({ block: "start" });\n });\n }\n function initHeader() {\n const box = $("links");\n for (const link of BOOT.links) {\n const anchor = el("a", "linkbtn", link.label);\n anchor.href = link.href;\n anchor.rel = "noreferrer noopener";\n box.appendChild(anchor);\n }\n let stored = null;\n try {\n stored = localStorage.getItem("bothandler-dashboard-theme");\n } catch {\n stored = null;\n }\n if (stored === "dark" || stored === "light") themeElement().setAttribute("data-theme", stored);\n $("theme").addEventListener("click", () => {\n let current = themeElement().getAttribute("data-theme");\n if (current === null) current = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";\n const next = current === "dark" ? "light" : "dark";\n themeElement().setAttribute("data-theme", next);\n try {\n localStorage.setItem("bothandler-dashboard-theme", next);\n } catch {\n }\n drawNow();\n });\n const pause = byId("pause");\n pause.hidden = !SECTIONS.feed;\n pause.addEventListener("click", () => {\n state.paused = !state.paused;\n pause.setAttribute("aria-pressed", String(state.paused));\n pause.textContent = state.paused ? `Resume${state.bufferedWhilePaused > 0 ? ` (${state.bufferedWhilePaused})` : ""}` : "Pause";\n if (!state.paused) {\n state.bufferedWhilePaused = 0;\n drawNow();\n }\n });\n if (BOOT.allowReset) {\n const reset = byId("reset");\n reset.hidden = false;\n reset.addEventListener("click", () => {\n reset.disabled = true;\n void fetch(`${API}/api/reset`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).then(async (response) => {\n if (!response.ok) {\n const body = await response.json().catch(() => ({}));\n toast("bad", "Reset refused", body.error ?? String(response.status));\n return;\n }\n clearFeed();\n resetFeedCache();\n drawNow();\n }).catch(() => {\n }).finally(() => {\n reset.disabled = false;\n });\n });\n }\n const header = rootNode().querySelector("header");\n if (header !== null) {\n const apply = () => {\n themeElement().style.setProperty("--header-h", `${header.getBoundingClientRect().height}px`);\n };\n apply();\n if (typeof ResizeObserver === "function") new ResizeObserver(apply).observe(header);\n else addEventListener("resize", apply);\n }\n }\n function syncUrl(replace = true) {\n if (isEmbedded()) return;\n const params = new URLSearchParams();\n if (state.filter !== "all") params.set("f", state.filter);\n if (state.search !== "") params.set("q", state.search);\n const query = params.toString();\n const hash = `#${state.tab}${query === "" ? "" : `?${query}`}`;\n if (location.hash === hash) return;\n history[replace ? "replaceState" : "pushState"]({ tab: state.tab }, "", hash);\n }\n function readUrl() {\n const raw2 = isEmbedded() ? "" : location.hash.slice(1);\n const split = raw2.indexOf("?");\n const name = split === -1 ? raw2 : raw2.slice(0, split);\n const params = new URLSearchParams(split === -1 ? "" : raw2.slice(split + 1));\n const filter = params.get("f") ?? "all";\n return {\n tab: isTab(name) ? name : FIRST,\n filter,\n search: params.get("q") ?? ""\n };\n }\n function showTab(name, options = {}) {\n const target = isTab(name) ? name : FIRST;\n state.tab = target;\n for (const [id, tab, enabled] of TABS) {\n const selected = tab === target;\n const node = $(id);\n node.hidden = !enabled;\n node.setAttribute("aria-selected", String(selected));\n node.tabIndex = selected ? 0 : -1;\n $(`view-${tab}`).hidden = !selected || !enabled;\n }\n if (options.focus === true) $(available[tabIndexOf(target)]?.[0] ?? "tab-live").focus();\n if (target === "policy" && state.policy === void 0) {\n void loadPolicy();\n void loadRanges();\n }\n trackActors();\n if (options.push !== false) syncUrl(options.replace !== false);\n drawNow();\n }\n function initTabs() {\n available.forEach(([id, name], index) => {\n const tab = $(id);\n tab.addEventListener("click", () => showTab(name, { replace: false }));\n tab.addEventListener("keydown", (event) => {\n let next = -1;\n if (event.key === "ArrowRight") next = (index + 1) % available.length;\n else if (event.key === "ArrowLeft") next = (index - 1 + available.length) % available.length;\n else if (event.key === "Home") next = 0;\n else if (event.key === "End") next = available.length - 1;\n if (next === -1) return;\n event.preventDefault();\n showTab(available[next]?.[1] ?? FIRST, { focus: true, replace: false });\n });\n });\n if (isEmbedded()) return;\n addEventListener("popstate", () => {\n const url = readUrl();\n state.filter = url.filter;\n setSearch(url.search);\n reflectFilterButtons();\n showTab(url.tab, { push: false });\n });\n }\n function initKeyboard() {\n eventTarget().addEventListener("keydown", ((event) => {\n const target = event.target;\n const typing = target !== null && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT");\n if (event.key === "Escape") {\n if (typing && target?.id === "search" && target.value !== "") {\n target.value = "";\n setSearch("");\n syncUrl();\n drawNow();\n return;\n }\n if (typing) {\n target?.blur();\n return;\n }\n if (state.actor !== void 0) {\n state.actor = void 0;\n drawNow();\n return;\n }\n if (state.open.size > 0) {\n state.open.clear();\n drawNow();\n }\n return;\n }\n if (typing || event.metaKey || event.ctrlKey || event.altKey) return;\n if (event.key === "/" && SECTIONS.feed) {\n event.preventDefault();\n showTab("live");\n const search = byId("search");\n search.focus();\n search.select();\n return;\n }\n const digit = ["1", "2", "3", "4"].indexOf(event.key);\n if (digit !== -1 && digit < available.length) {\n event.preventDefault();\n showTab(available[digit]?.[1] ?? FIRST, { focus: true, replace: false });\n }\n }));\n }\n function initRanges() {\n const ranges = [\n ["1m", 6e4],\n ["5m", 3e5],\n ["15m", 9e5],\n ["1h", 36e5]\n ];\n const host = $("traffic-range");\n for (const [label2, value] of ranges) {\n const button = el("button", null, label2);\n button.setAttribute("aria-pressed", String(value === state.rangeMs));\n button.addEventListener("click", () => {\n state.rangeMs = value;\n for (const other of Array.from(host.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n drawTraffic();\n });\n host.appendChild(button);\n }\n const scopes = [\n ["since start", "run"],\n ["this window", "window"]\n ];\n const scopeHost = $("score-scope");\n for (const [label2, value] of scopes) {\n const button = el("button", null, label2);\n button.setAttribute("aria-pressed", String(value === state.scoreScope));\n button.addEventListener("click", () => {\n state.scoreScope = value;\n for (const other of Array.from(scopeHost.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n drawScores();\n });\n scopeHost.appendChild(button);\n }\n }\n var pending = false;\n function schedule() {\n if (state.paused || pending) return;\n pending = true;\n requestAnimationFrame(() => {\n pending = false;\n draw();\n });\n }\n function draw() {\n drawChips();\n drawTiles();\n drawNoticeBadge();\n updateWindowLabels();\n if (state.tab === "live") {\n drawActor();\n drawFeed();\n drawLivePanels();\n } else if (state.tab === "actors") {\n drawActors();\n } else if (state.tab === "stats") {\n drawTraffic();\n drawLatency();\n drawScores();\n drawStatsPanels();\n if (SECTIONS.audit) drawAudit();\n } else {\n drawPolicyTab();\n if (SECTIONS.notices) drawNotices();\n if (SECTIONS.changes) drawChanges();\n }\n }\n function drawNow() {\n draw();\n }\n function applySections() {\n const gated = [\n ["tiles", SECTIONS.statistics],\n ["tester-panel", SECTIONS.tester],\n ["ranges-panel", SECTIONS.ranges],\n ["changes-panel", SECTIONS.changes],\n ["actor-panel", SECTIONS.actors],\n ["live-actors-panel", SECTIONS.actors],\n ["audit-panel", SECTIONS.audit],\n ["audit-checks-panel", SECTIONS.audit],\n ["notices-panel", SECTIONS.notices],\n ["guard-panel", SECTIONS.guard],\n ["robots-panel", SECTIONS.robots],\n ["identities-panel", SECTIONS.actors],\n ["evidence-legend", SECTIONS.evidence]\n ];\n for (const [id, enabled] of gated) {\n const node = rootNode().querySelector(`#${id}`);\n if (node !== null && !enabled) node.remove();\n }\n }\n function start() {\n app.draw = schedule;\n app.drawNow = drawNow;\n app.showTab = showTab;\n app.syncUrl = () => syncUrl();\n applySections();\n initHeader();\n drawPeers();\n initTabs();\n initSkipLink();\n initKeyboard();\n initRanges();\n if (SECTIONS.feed) initFeed();\n initActor();\n initTester();\n initPolicy();\n let resizeTimer;\n addEventListener("resize", () => {\n if (resizeTimer !== void 0) clearTimeout(resizeTimer);\n resizeTimer = setTimeout(() => {\n if (state.tab === "stats") {\n drawTraffic();\n drawLatency();\n drawScores();\n }\n }, 120);\n });\n const url = readUrl();\n state.filter = url.filter;\n setSearch(url.search);\n if (SECTIONS.feed) reflectFilterButtons();\n showTab(url.tab, { replace: true });\n suspendScrollAnchoring();\n void loadInitialSnapshot().finally(settleScrollAnchoring);\n connectStream();\n }\n function htmlElement() {\n const root2 = rootNode();\n return root2 instanceof Document ? root2.documentElement : void 0;\n }\n function suspendScrollAnchoring() {\n htmlElement()?.classList.add("settling");\n }\n function settleScrollAnchoring() {\n const html = htmlElement();\n if (html === void 0) return;\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n html.classList.remove("settling");\n });\n });\n }\n start();\n})();\n';
|
|
8041
|
+
CLIENT_SCRIPT = '"use strict";\n(() => {\n // src/dashboard/client/css.ts\n function cssEscape(value) {\n return typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : String(value).replace(/[^\\w-]/g, "\\\\$&");\n }\n\n // src/dashboard/client/dom.ts\n function el(tag, className, value) {\n const node = document.createElement(tag);\n if (className !== void 0 && className !== null && className !== "") node.className = className;\n if (value !== void 0 && value !== null) node.textContent = String(value);\n return node;\n }\n function svgEl(name, attributes = {}) {\n const node = document.createElementNS("http://www.w3.org/2000/svg", name);\n for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));\n return node;\n }\n function svgText(attributes, text) {\n const node = svgEl("text", attributes);\n node.textContent = String(text);\n return node;\n }\n function clear(node) {\n while (node.firstChild) node.removeChild(node.firstChild);\n }\n var root = typeof document === "undefined" ? void 0 : document;\n var themeHost = typeof document === "undefined" ? void 0 : document.documentElement;\n var embedded = false;\n function isEmbedded() {\n return embedded;\n }\n function eventTarget() {\n return embedded ? root : globalThis;\n }\n function rootNode() {\n return root;\n }\n function themeElement() {\n return themeHost;\n }\n function $(id) {\n const node = root.querySelector(`#${cssEscape(id)}`);\n if (node === null || node === void 0) throw new Error(`dashboard: no element #${id}`);\n return node;\n }\n function byId(id) {\n return $(id);\n }\n function css(name) {\n return getComputedStyle(themeHost).getPropertyValue(name).trim();\n }\n var sequence = 0;\n function label(text, control) {\n const node = document.createElement("label");\n node.textContent = text;\n const single = Array.isArray(control) ? control.length === 1 ? control[0] : void 0 : control;\n if (single !== void 0 && /^(input|select|textarea)$/i.test(single.tagName)) {\n if (single.id === "") single.id = `field-${++sequence}`;\n node.htmlFor = single.id;\n } else {\n const group = Array.isArray(control) ? control : [control];\n for (const node_ of group) if (!node_.hasAttribute("aria-label")) node_.setAttribute("aria-label", text);\n }\n return node;\n }\n\n // src/dashboard/client/boot.ts\n var FALLBACK = {\n base: "",\n title: "bothandlerjs",\n allowReset: false,\n allowEdit: false,\n allowGuardEdit: false,\n allowActing: false,\n peers: [],\n sections: { feed: true, evidence: true, actors: true, registry: true, tester: true, statistics: true, audit: true, notices: true, changes: true, policy: true, guard: true, robots: true, ranges: true },\n links: []\n };\n var BOOT = globalThis.__BOOTSTRAP__ ?? FALLBACK;\n var API = BOOT.base;\n var SECTIONS = BOOT.sections;\n\n // src/dashboard/client/app.ts\n var app = {\n draw: () => {\n },\n drawNow: () => {\n },\n showTab: () => {\n },\n syncUrl: () => {\n }\n };\n function toast(kind, title, detail = "") {\n const node = el("div", `toast ${kind}`);\n node.appendChild(el("b", null, title));\n if (detail !== "") node.appendChild(el("span", null, detail));\n const host = rootNode().querySelector("#toasts");\n if (host === null) return;\n host.appendChild(node);\n setTimeout(() => node.remove(), 6e3);\n }\n function download(text, filename, type) {\n const blob = new Blob([text], { type });\n const url = URL.createObjectURL(blob);\n const anchor = el("a");\n anchor.href = url;\n anchor.download = filename;\n anchor.click();\n setTimeout(() => URL.revokeObjectURL(url), 1e3);\n }\n function today() {\n return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);\n }\n\n // src/dashboard/client/outcome.ts\n var DENY = /* @__PURE__ */ new Set(["block", "drop", "redirect"]);\n var MITIGATE = /* @__PURE__ */ new Set(["challenge", "rate-limit", "delay"]);\n function outcome(entry) {\n return actionKind(entry.action);\n }\n function actionKind(action) {\n if (action === void 0) return "pending";\n if (DENY.has(action)) return "deny";\n if (MITIGATE.has(action)) return "mitigate";\n return "allow";\n }\n function verdictBadge(entry) {\n if (entry.verdict === "verified-bot" || entry.verdict === "confirmed-bot") return ["b-proven", entry.verdict];\n if (entry.verdict === "suspected-bot") return ["b-suspected", "suspected-bot"];\n if (entry.verdict === "human") return ["b-human", "human"];\n return ["b-unknown", entry.bypass !== void 0 ? `skipped \xB7 ${entry.bypass}` : "unknown"];\n }\n function provenBots(verdicts) {\n return (verdicts["confirmed-bot"] ?? 0) + (verdicts["verified-bot"] ?? 0);\n }\n\n // src/dashboard/client/query.ts\n var FIELDS = {\n path: "path",\n url: "path",\n actor: "actor",\n ip: "actor",\n ua: "userAgent",\n useragent: "userAgent",\n agent: "userAgent",\n verdict: "verdict",\n action: "action",\n rule: "rule",\n detector: "detector",\n identity: "identity",\n method: "method",\n class: "botClass",\n botclass: "botClass",\n id: "requestId",\n request: "requestId",\n bypass: "bypass",\n score: "score",\n outcome: "outcome",\n certain: "certain"\n };\n var NUMERIC = /* @__PURE__ */ new Set(["score"]);\n var FIELD_NAMES = Object.keys(FIELDS).sort();\n var FIELD_VALUES = {\n verdict: ["confirmed-bot", "verified-bot", "suspected-bot", "human", "unknown"],\n class: ["scanner", "scraper", "impersonator", "automation", "http-client", "declared-bot", "verified-bot", "human", "unknown"],\n botclass: ["scanner", "scraper", "impersonator", "automation", "http-client", "declared-bot", "verified-bot", "human", "unknown"],\n action: ["allow", "tag", "log", "challenge", "rate-limit", "delay", "block", "drop", "redirect"],\n outcome: ["allow", "mitigate", "deny", "pending"],\n certain: ["true", "false"],\n method: ["GET", "POST", "HEAD", "PUT", "PATCH", "DELETE", "OPTIONS"]\n };\n function suggestFor(input, caret) {\n const before = input.slice(0, caret);\n const start2 = Math.max(before.lastIndexOf(" ") + 1, 0);\n const token = before.slice(start2);\n const to = caret;\n const negated = token.startsWith("-") || token.startsWith("!");\n const body = negated ? token.slice(1) : token;\n const colon = body.indexOf(":");\n if (colon === -1) {\n const partial2 = body.toLowerCase();\n if (partial2.startsWith("$")) {\n return { options: OPERATORS.filter((name) => name.startsWith(partial2)), from: start2, to };\n }\n const options2 = FIELD_NAMES.filter((name) => name.startsWith(partial2)).map((name) => `${negated ? token[0] : ""}${name}:`);\n return { options: options2, from: start2, to };\n }\n const field2 = body.slice(0, colon).toLowerCase();\n const values = FIELD_VALUES[field2];\n if (values === void 0) return { options: [], from: start2, to };\n const partial = body.slice(colon + 1).toLowerCase();\n const prefix = `${negated ? token[0] : ""}${field2}:`;\n const forms = partial.startsWith("$") ? ["$in(", "$notin("].filter((form) => form.startsWith(partial)).map((form) => `${prefix}${form}`) : [];\n const options = [...forms, ...values.filter((value) => value.toLowerCase().startsWith(partial)).map((value) => `${prefix}${value}`)];\n return { options, from: start2, to };\n }\n var OPERATORS = ["$and", "$or", "$not", "$in", "$notin"];\n var MAX_GROUP_DEPTH = 32;\n function tokenize(input) {\n const tokens = [];\n let current = "";\n let quoted = false;\n let depth = 0;\n const flush = () => {\n if (current === "") return;\n const lower = current.toLowerCase();\n if (lower === "$and" || lower === "$or" || lower === "$not") tokens.push({ kind: "op", op: lower.slice(1) });\n else tokens.push({ kind: "word", text: current });\n current = "";\n };\n for (let i = 0; i < input.length; i++) {\n const character = input[i];\n if (character === \'"\') {\n quoted = !quoted;\n continue;\n }\n if (quoted) {\n current += character;\n continue;\n }\n if (depth > 0) {\n current += character;\n if (character === "(") depth++;\n else if (character === ")") {\n depth--;\n if (depth === 0) flush();\n }\n continue;\n }\n if (character === "(") {\n if (/\\$(in|notin)$/i.test(current)) {\n current += character;\n depth = 1;\n continue;\n }\n flush();\n tokens.push({ kind: "open" });\n continue;\n }\n if (character === ")") {\n flush();\n tokens.push({ kind: "close" });\n continue;\n }\n if (/\\s/.test(character)) {\n flush();\n continue;\n }\n current += character;\n }\n flush();\n return tokens;\n }\n function toTerm(word) {\n const negated = word.startsWith("-") || word.startsWith("!");\n const body = negated ? word.slice(1) : word;\n if (body === "") return void 0;\n const colon = body.indexOf(":");\n const name = colon === -1 ? "" : body.slice(0, colon).toLowerCase();\n const field2 = FIELDS[name];\n if (colon === -1 || field2 === void 0) return { field: void 0, value: body.toLowerCase(), negated };\n const rest = body.slice(colon + 1);\n const set = /^\\$(in|notin)\\(([\\s\\S]*)$/i.exec(rest);\n if (set !== null) {\n const inside = set[2].endsWith(")") ? set[2].slice(0, -1) : set[2];\n const values = inside.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry !== "");\n const inverted = set[1].toLowerCase() === "notin";\n return { field: field2, value: values[0] ?? "", negated: negated !== inverted, values };\n }\n let value = rest.toLowerCase();\n let compare;\n if (NUMERIC.has(field2)) {\n compare = value.startsWith(">") ? ">" : value.startsWith("<") ? "<" : "=";\n if (compare !== "=") value = value.slice(1);\n }\n if (value === "") return void 0;\n return { field: field2, value, negated, compare };\n }\n function parseTokens(tokens) {\n let at = 0;\n let depth = 0;\n const parseUnary = () => {\n const token = tokens[at];\n if (token === void 0) return void 0;\n if (token.kind === "op" && token.op === "not") {\n at++;\n const of = parseUnary();\n return of === void 0 ? void 0 : { kind: "not", of };\n }\n if (token.kind === "open") {\n at++;\n if (depth >= MAX_GROUP_DEPTH) return void 0;\n depth++;\n const inner = parseOr();\n depth--;\n if (tokens[at]?.kind === "close") at++;\n return inner.kind === "all" ? void 0 : inner;\n }\n if (token.kind === "close") return void 0;\n if (token.kind === "op") {\n at++;\n return parseUnary();\n }\n at++;\n const term = toTerm(token.text);\n return term === void 0 ? void 0 : { kind: "term", term };\n };\n const parseAnd = () => {\n const parts = [];\n while (at < tokens.length) {\n const token = tokens[at];\n if (token === void 0 || token.kind === "close") break;\n if (token.kind === "op" && token.op === "or") break;\n if (token.kind === "op" && token.op === "and") {\n at++;\n continue;\n }\n const before = at;\n const part = parseUnary();\n if (part !== void 0) parts.push(part);\n if (at === before) at++;\n }\n return parts.length === 0 ? { kind: "all" } : parts.length === 1 ? parts[0] : { kind: "and", parts };\n };\n const parseOr = () => {\n const parts = [parseAnd()];\n while (tokens[at]?.kind === "op" && tokens[at].op === "or") {\n at++;\n parts.push(parseAnd());\n }\n const real = parts.filter((part) => part.kind !== "all");\n if (real.length === 0) return { kind: "all" };\n return real.length === 1 ? real[0] : { kind: "or", parts: real };\n };\n return parseOr();\n }\n var MAX_QUERY_CHARS = 8192;\n function parseFilter(input) {\n const trimmed = input.trim();\n return parseTokens(tokenize(trimmed.length > MAX_QUERY_CHARS ? trimmed.slice(0, MAX_QUERY_CHARS) : trimmed));\n }\n function searchableText(entry) {\n const parts = [\n entry.method,\n entry.path,\n entry.actor,\n entry.userAgent,\n entry.verdict,\n entry.botClass,\n entry.identity ?? "",\n entry.action ?? "",\n entry.rule ?? "",\n entry.requestId\n ];\n for (const item of entry.evidence) parts.push(item.detector, item.summary);\n return parts.join(" ").toLowerCase();\n }\n function fieldValue(entry, field2) {\n switch (field2) {\n case "path":\n return entry.path;\n case "actor":\n return entry.actor;\n case "userAgent":\n return entry.userAgent;\n case "verdict":\n return entry.verdict;\n case "action":\n return entry.action ?? "";\n case "rule":\n return entry.rule ?? "";\n case "identity":\n return entry.identity ?? "";\n case "method":\n return entry.method;\n case "botClass":\n return entry.botClass;\n case "requestId":\n return entry.requestId;\n case "bypass":\n return entry.bypass ?? "";\n case "outcome":\n return outcome(entry);\n case "certain":\n return String(entry.certain);\n case "detector":\n return entry.evidence.map((item) => item.detector).join(" ");\n default:\n return "";\n }\n }\n function matchesTerm(term, entry, haystack) {\n if (term.field === void 0) return haystack.includes(term.value);\n if (term.values !== void 0) {\n if (term.values.length === 0) return false;\n const actual = fieldValue(entry, term.field).toLowerCase();\n return term.values.some((value) => actual.includes(value));\n }\n if (term.field === "score") {\n const wanted = Number(term.value);\n if (Number.isNaN(wanted)) return false;\n if (term.compare === ">") return entry.score > wanted;\n if (term.compare === "<") return entry.score < wanted;\n return entry.score === wanted;\n }\n return fieldValue(entry, term.field).toLowerCase().includes(term.value);\n }\n function matches(filter, entry, haystack) {\n switch (filter.kind) {\n case "all":\n return true;\n case "term":\n return matchesTerm(filter.term, entry, haystack) !== filter.term.negated;\n case "not":\n return !matches(filter.of, entry, haystack);\n case "and":\n return filter.parts.every((part) => matches(part, entry, haystack));\n case "or":\n return filter.parts.some((part) => matches(part, entry, haystack));\n }\n }\n function matchesFilter(filter, entry) {\n switch (filter) {\n case "proven":\n return entry.certain;\n case "suspected":\n return entry.verdict === "suspected-bot";\n case "human":\n return entry.verdict === "human";\n case "guard":\n return entry.downgradedFrom !== void 0;\n case "deny":\n return outcome(entry) === "deny";\n case "mitigate":\n return outcome(entry) === "mitigate";\n case "allow":\n return outcome(entry) === "allow";\n default:\n return true;\n }\n }\n\n // src/dashboard/client/store.ts\n var MAX_ROWS = 1e3;\n var state = {\n rows: [],\n byId: /* @__PURE__ */ new Map(),\n snapshot: void 0,\n policy: void 0,\n actors: [],\n actorsTracked: 0,\n actorScope: "tracked",\n paused: false,\n filter: "all",\n search: "",\n query: { kind: "all" },\n tab: "live",\n open: /* @__PURE__ */ new Set(),\n actor: void 0,\n rangeMs: 3e5,\n scoreScope: "run",\n editorRules: [],\n editorDirty: false,\n editorMode: "gui",\n guardDirty: false,\n bufferedWhilePaused: 0,\n laggedDrops: 0,\n feedPage: 0,\n feedFrozen: void 0,\n actorsPage: 0,\n feedPageSize: 50,\n actorsPageSize: 25,\n fromMs: void 0,\n toMs: void 0,\n caughtUp: 0\n };\n function ingest(entry) {\n const existing = state.byId.get(entry.requestId);\n if (existing !== void 0) {\n existing.entry = entry;\n existing.rev++;\n existing.text = void 0;\n return;\n }\n const row = { entry, rev: 0 };\n state.byId.set(entry.requestId, row);\n state.rows.push(row);\n if (state.rows.length > MAX_ROWS) {\n for (const dropped of state.rows.splice(0, state.rows.length - MAX_ROWS)) {\n state.byId.delete(dropped.entry.requestId);\n state.open.delete(dropped.entry.requestId);\n }\n }\n }\n function clearFeed() {\n state.rows = [];\n state.byId = /* @__PURE__ */ new Map();\n state.open.clear();\n state.actor = void 0;\n state.bufferedWhilePaused = 0;\n state.laggedDrops = 0;\n resetPaging();\n }\n function setSearch(value) {\n state.search = value;\n state.query = parseFilter(value);\n resetPaging();\n }\n function setTimeframe(from, to) {\n state.fromMs = from;\n state.toMs = to;\n resetPaging();\n }\n function resetPaging() {\n state.feedPage = 0;\n state.feedFrozen = void 0;\n }\n function textOf(row) {\n if (row.text === void 0) row.text = searchableText(row.entry);\n return row.text;\n }\n function sortRows() {\n state.rows.sort((a, b) => a.entry.at - b.entry.at);\n }\n function matches2(row) {\n if (state.fromMs !== void 0 && row.entry.at < state.fromMs) return false;\n if (state.toMs !== void 0 && row.entry.at > state.toMs) return false;\n return matchesFilter(state.filter, row.entry) && matches(state.query, row.entry, textOf(row));\n }\n function matchingRows(limit = Number.POSITIVE_INFINITY) {\n const shown = [];\n for (let i = state.rows.length - 1; i >= 0 && shown.length < limit; i--) {\n const row = state.rows[i];\n if (row !== void 0 && matches2(row)) shown.push(row);\n }\n return shown;\n }\n function feedPage(size) {\n const all = state.feedPage === 0 || state.feedFrozen === void 0 ? matchingRows() : state.feedFrozen;\n const pages = Math.max(1, Math.ceil(all.length / size));\n const page = Math.min(Math.max(0, state.feedPage), pages - 1);\n if (page !== state.feedPage) state.feedPage = page;\n return { rows: all.slice(page * size, page * size + size), page, pages, total: all.length };\n }\n function goToFeedPage(page) {\n const next = Math.max(0, page);\n if (next === 0) {\n state.feedFrozen = void 0;\n } else if (state.feedFrozen === void 0) {\n state.feedFrozen = matchingRows();\n }\n state.feedPage = next;\n }\n function matchingCount() {\n let count = 0;\n for (const row of state.rows) if (matches2(row)) count++;\n return count;\n }\n function oldestAt() {\n return state.rows[0]?.entry.at;\n }\n function bump(counter, key) {\n counter.set(key, (counter.get(key) ?? 0) + 1);\n }\n function aggregate(rows) {\n const totals = {\n detectors: /* @__PURE__ */ new Map(),\n actors: /* @__PURE__ */ new Map(),\n identities: /* @__PURE__ */ new Map(),\n paths: /* @__PURE__ */ new Map(),\n deniedPaths: /* @__PURE__ */ new Map(),\n guardStops: /* @__PURE__ */ new Map(),\n ruleHits: /* @__PURE__ */ new Map(),\n bypassed: /* @__PURE__ */ new Map()\n };\n for (const { entry } of rows) {\n for (const item of entry.evidence) bump(totals.detectors, item.detector);\n bump(totals.actors, entry.actor);\n if (entry.bypass !== void 0) {\n bump(totals.bypassed, `${entry.path} (${entry.bypass})`);\n continue;\n }\n bump(totals.paths, entry.path);\n if (entry.identity !== void 0 && entry.identity !== "") {\n bump(totals.identities, `${entry.identity} \xB7 ${entry.verdict === "verified-bot" ? "verified" : "claimed"}`);\n }\n if (outcome(entry) === "deny") bump(totals.deniedPaths, entry.path);\n if (entry.downgradedFrom !== void 0 && entry.rule !== void 0) bump(totals.guardStops, `${entry.rule} \u2192 ${entry.downgradedFrom}`);\n if (entry.rule !== void 0) bump(totals.ruleHits, entry.rule);\n }\n return totals;\n }\n\n // src/dashboard/client/api.ts\n async function getJson(path) {\n const response = await fetch(API + path);\n if (!response.ok) throw new Error(await errorFrom(response));\n return await response.json();\n }\n async function postJson(path, body) {\n const response = await fetch(API + path, {\n method: "POST",\n headers: { "content-type": "application/json" },\n body: JSON.stringify(body)\n });\n const data = await response.json().catch(() => ({}));\n return response.ok ? { ok: true, data } : { ok: false, data, error: String(data.error ?? "The server refused this.") };\n }\n async function errorFrom(response) {\n const body = await response.json().catch(() => ({}));\n return body.error ?? `${response.status} ${response.statusText}`;\n }\n\n // src/dashboard/client/actions.ts\n var armed = 0;\n function isConfirming() {\n return armed > 0;\n }\n function actorActions(key, after, current) {\n if (!BOOT.allowActing) return [];\n const forget = el("button", null, "Forget");\n forget.title = "Discard this actor\'s history \u2014 the cure for a false positive that has stuck";\n forget.addEventListener("click", () => {\n void act({ key, action: "forget" }, `Forgot ${key}`, "Its next request is assessed as a first request.", after);\n });\n const clear2 = el("button", null, "Clear as human");\n clear2.title = "Grant this actor human clearance for an hour, as though it had solved a challenge";\n clear2.addEventListener("click", () => {\n void act({ key, action: "clear", forMs: 60 * 6e4 }, `Cleared ${key}`, "Held as human for an hour, then reassessed.", after);\n });\n const label2 = labelControl(key, current, after);\n return [confirmingButton("Allowlist", `Allowlist ${key} \u2014 it stops being assessed at all`, () => allowlist(key, after)), forget, clear2, label2];\n }\n function labelControl(key, current, after) {\n const host = el("span", "label-edit");\n const button = el("button", null, current === void 0 ? "Label" : "Relabel");\n button.title = "Give this actor a name, for whoever reads this next. It never changes a verdict.";\n const commit = (value) => {\n const trimmed = value.trim().slice(0, 120);\n void act(\n { key, action: "label", ...trimmed === "" ? {} : { label: trimmed } },\n trimmed === "" ? `Cleared the label on ${key}` : `Labelled ${key}`,\n trimmed === "" ? "It shows as its address again." : `Shown as "${trimmed}" wherever it appears.`,\n after\n );\n };\n button.addEventListener("click", () => {\n const container = host.parentElement;\n clear(host);\n const input = el("input", "label-input");\n input.type = "text";\n input.value = current ?? "";\n input.placeholder = "A name for this client";\n input.setAttribute("aria-label", `Name for ${key}`);\n input.maxLength = 120;\n const save = el("button", "label-save", "Save");\n save.title = "Save this name";\n const cancel = el("button", null, "Cancel");\n cancel.title = "Leave the name as it was";\n input.title = "Enter to save, Escape to cancel";\n armed++;\n container?.classList.add("editing");\n let settled = false;\n const finish = (accept) => {\n if (settled) return;\n settled = true;\n armed--;\n container?.classList.remove("editing");\n if (accept) commit(input.value);\n else {\n clear(host);\n host.appendChild(button);\n }\n };\n for (const control of [input, save, cancel]) {\n control.addEventListener("keydown", (event) => {\n const pressed = event.key;\n if (pressed === "Escape") {\n event.preventDefault();\n finish(false);\n } else if (pressed === "Enter" && control === input) {\n event.preventDefault();\n finish(true);\n }\n });\n }\n for (const control of [save, cancel]) control.addEventListener("mousedown", (event) => event.preventDefault());\n save.addEventListener("click", () => finish(true));\n cancel.addEventListener("click", () => finish(false));\n host.addEventListener("focusout", (event) => {\n const next = event.relatedTarget;\n if (next !== null && host.contains(next)) return;\n finish(false);\n });\n host.append(input, save, cancel);\n input.focus();\n input.select();\n });\n host.appendChild(button);\n return host;\n }\n function confirmingButton(label2, confirmation, run2) {\n const button = el("button", "danger", label2);\n let pending2 = false;\n let timer2;\n const disarm = () => {\n if (!pending2) return;\n pending2 = false;\n armed--;\n button.textContent = label2;\n button.className = "danger";\n };\n button.addEventListener("click", () => {\n if (pending2) {\n if (timer2 !== void 0) clearTimeout(timer2);\n disarm();\n run2();\n return;\n }\n pending2 = true;\n armed++;\n button.textContent = confirmation;\n button.className = "danger primary";\n timer2 = setTimeout(disarm, 5e3);\n });\n return button;\n }\n async function allowlist(key, after) {\n const result = await postJson("/api/ranges", { name: "allowlist", add: [key] });\n if (!result.ok) {\n toast("bad", "Not allowlisted", result.error ?? "");\n return;\n }\n toast("warn", `Allowlisted ${key}`, "Requests from it are no longer assessed at all.");\n after();\n }\n async function act(body, title, detail, after) {\n const result = await postJson("/api/actor", body);\n if (!result.ok) {\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n toast("ok", title, detail);\n after();\n }\n\n // src/dashboard/client/format.ts\n var numbers = new Intl.NumberFormat();\n function n(value) {\n return numbers.format(value ?? 0);\n }\n function pct(part, whole) {\n return whole > 0 ? `${Math.round(part / whole * 100)}%` : "\u2014";\n }\n function ms(value) {\n return value >= 10 ? `${value.toFixed(1)}ms` : `${value.toFixed(2)}ms`;\n }\n function uptime(milliseconds) {\n const seconds = Math.max(0, Math.round(milliseconds / 1e3));\n if (seconds < 90) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n if (minutes < 90) return `${minutes}m`;\n return `${Math.round(minutes / 60)}h`;\n }\n function rangeLabel(milliseconds) {\n const seconds = Math.round(milliseconds / 1e3);\n if (seconds < 90) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n return minutes < 90 ? `${minutes} min` : `${Math.round(minutes / 60)}h`;\n }\n function clockTime(at) {\n const when = new Date(at);\n return `${pad(when.getHours())}:${pad(when.getMinutes())}:${pad(when.getSeconds())}`;\n }\n function clockDate(at) {\n const when = new Date(at);\n return `${pad(when.getDate())}-${pad(when.getMonth() + 1)}-${when.getFullYear()}`;\n }\n function clockStamp(at) {\n return `${clockDate(at)} ${clockTime(at)}`;\n }\n function pad(value) {\n return String(value).padStart(2, "0");\n }\n function windowLabel(count, oldestAt2, now) {\n if (count === 0) return "this window \xB7 empty";\n const span = oldestAt2 === void 0 ? 0 : Math.max(0, now - oldestAt2);\n return `last ${n(count)} requests \xB7 ${rangeLabel(span)}`;\n }\n\n // src/dashboard/client/bars.ts\n function drawBars(target, rows, emptyText) {\n clear(target);\n const filtered = [...rows].filter(([, value]) => value > 0);\n if (filtered.length === 0) {\n target.appendChild(el("div", "note", emptyText));\n return;\n }\n filtered.sort((a, b) => b[1] - a[1]);\n const max = filtered[0]?.[1] ?? 1;\n for (const [label2, value] of filtered.slice(0, 14)) {\n const bar = el("div", "bar");\n const track = el("div", "track");\n const fill = el("div", "fill");\n fill.style.width = `${Math.max(2, Math.round(value / max * 100))}%`;\n track.appendChild(fill);\n track.appendChild(el("div", "lbl", label2));\n bar.appendChild(track);\n bar.appendChild(el("div", "v tnum", n(value)));\n target.appendChild(bar);\n }\n }\n function pairs(record) {\n return Object.entries(record ?? {});\n }\n\n // src/dashboard/client/actor.ts\n function initActor() {\n if (!SECTIONS.actors) return;\n $("actor-close").addEventListener("click", closeActor);\n }\n function openActor(key) {\n state.actor = key;\n app.drawNow();\n $("actor-panel").scrollIntoView({ block: "nearest" });\n }\n function closeActor() {\n state.actor = void 0;\n app.drawNow();\n }\n function drawActor() {\n if (!SECTIONS.actors) return;\n const panel = $("actor-panel");\n if (state.actor === void 0) {\n panel.hidden = true;\n return;\n }\n panel.hidden = false;\n $("actor-key").textContent = state.actor;\n const mine = state.rows.filter((row) => row.entry.actor === state.actor).map((row) => row.entry);\n const latest = mine[mine.length - 1];\n const stats = latest?.actorStats;\n const gaps = [];\n for (let i = 1; i < mine.length; i++) gaps.push(mine[i].at - mine[i - 1].at);\n const meanGap = gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0;\n const box = $("actor-stats");\n clear(box);\n const rows = [\n ["In this window", `${n(mine.length)} requests`],\n ["Engine sees", stats !== void 0 ? `${n(stats.requests)} requests, ${n(stats.distinctPaths)} distinct paths` : "\u2014"],\n ["Prior confirmations", stats !== void 0 ? n(stats.priorConfirmations) : "\u2014"],\n ["Holds clearance", stats !== void 0 ? stats.cleared ? "yes" : "no" : "\u2014"],\n ["First seen", stats !== void 0 ? clockStamp(stats.firstSeen) : "\u2014"],\n ["Mean gap", gaps.length > 0 ? `${Math.round(meanGap)}ms over ${n(gaps.length)} gaps` : "one request only"]\n ];\n for (const [key, value] of rows) {\n box.appendChild(el("dt", null, key));\n box.appendChild(el("dd", null, value));\n }\n const verdicts = /* @__PURE__ */ new Map();\n const actions = /* @__PURE__ */ new Map();\n for (const entry of mine) {\n verdicts.set(entry.verdict, (verdicts.get(entry.verdict) ?? 0) + 1);\n if (entry.action !== void 0) actions.set(entry.action, (actions.get(entry.action) ?? 0) + 1);\n }\n drawBars($("actor-mix"), [...verdicts, ...actions], "Nothing yet.");\n const bar = $("actor-actions");\n clear(bar);\n const buttons = actorActions(state.actor, () => app.drawNow());\n bar.hidden = buttons.length === 0;\n for (const button of buttons) bar.appendChild(button);\n }\n\n // src/dashboard/client/saved.ts\n var FILTERS_KEY = "bothandler.filters";\n var MAX_SAVED = 50;\n function read(key, fallback) {\n if (isEmbedded()) return fallback;\n try {\n const raw = localStorage.getItem(key);\n if (raw === null) return fallback;\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : fallback;\n } catch {\n return fallback;\n }\n }\n function write(key, value) {\n if (isEmbedded()) return;\n try {\n localStorage.setItem(key, JSON.stringify(value));\n } catch {\n }\n }\n function savedFilters() {\n return read(FILTERS_KEY, []).filter((entry) => typeof entry?.name === "string");\n }\n function saveFilter(entry) {\n const kept = savedFilters().filter((existing) => existing.name !== entry.name);\n const next = [entry, ...kept].slice(0, MAX_SAVED);\n write(FILTERS_KEY, next);\n return next;\n }\n function deleteFilter(name) {\n const next = savedFilters().filter((entry) => entry.name !== name);\n write(FILTERS_KEY, next);\n return next;\n }\n\n // src/dashboard/client/pager.ts\n var painted = /* @__PURE__ */ new WeakMap();\n function renderPager(host, model, options) {\n const signature = JSON.stringify([model.page, model.from, model.to, model.total, model.atStart, model.atEnd, model.held ?? "", options.withSize, model.size?.current]);\n if (painted.get(host) === signature && host.childElementCount > 0) return;\n painted.set(host, signature);\n clear(host);\n const steps = [\n { to: model.page - 1, glyph: "\u2039", label: "Previous page", disabled: model.atStart },\n { to: model.page + 1, glyph: "\u203A", label: "Next page", disabled: model.atEnd }\n ];\n const [previous, next] = steps;\n host.appendChild(stepButton(previous, model));\n const range = model.total === void 0 ? `${n(model.from)}\u2013${n(model.to)}` : `${n(model.from)}\u2013${n(model.to)} of ${n(model.total)}`;\n const where = el("span", "where", range);\n where.setAttribute("aria-live", "polite");\n host.appendChild(where);\n host.appendChild(stepButton(next, model));\n if (model.held !== void 0) {\n const held = el("span", "held", model.held);\n held.title = "New requests are still arriving and are still counted. They appear when you return to the first page.";\n host.appendChild(held);\n }\n if (options.withSize && model.size !== void 0) {\n const size = model.size;\n const label2 = el("label", "size");\n label2.appendChild(document.createTextNode("Per page"));\n const select2 = document.createElement("select");\n for (const choice of size.choices) {\n const option = document.createElement("option");\n option.value = String(choice);\n option.textContent = String(choice);\n option.selected = choice === size.current;\n select2.appendChild(option);\n }\n select2.addEventListener("change", () => {\n const chosen = Number(select2.value);\n if (Number.isFinite(chosen) && chosen > 0) size.set(chosen);\n });\n label2.appendChild(select2);\n host.appendChild(label2);\n }\n }\n function stepButton(step, model) {\n const button = el("button", "step", step.glyph);\n const element = button;\n element.type = "button";\n element.disabled = step.disabled;\n button.setAttribute("aria-label", step.label);\n button.title = step.label;\n button.addEventListener("click", () => model.go(Math.max(0, step.to)));\n return button;\n }\n\n // src/dashboard/client/replay.ts\n function replayLine(entry) {\n const headers = {};\n for (const [name, value] of entry.headers ?? []) headers[name] = value;\n const query = Object.keys(entry.query).map((name) => `${encodeURIComponent(name)}=${encodeURIComponent(entry.query[name] ?? "")}`).join("&");\n return JSON.stringify({\n method: entry.method,\n url: entry.path + (query === "" ? "" : `?${query}`),\n headers,\n ip: entry.actor,\n timestamp: new Date(entry.at).toISOString(),\n protocol: entry.protocol ?? "https",\n httpVersion: entry.httpVersion ?? "1.1"\n });\n }\n function replayFile(entries) {\n return entries.map(replayLine).join("\\n");\n }\n function corpusCase(entry) {\n const headers = (entry.headers ?? []).map((pair) => ` [${JSON.stringify(pair[0])}, ${JSON.stringify(pair[1])}]`).join(",\\n");\n return [\n "bot({",\n ` id: ${JSON.stringify(`case-${entry.requestId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`)},`,\n ` title: ${JSON.stringify(`${entry.method} ${entry.path} from ${entry.userAgent.slice(0, 60)}`)},`,\n \' audience: "unwanted-bot", // human | benign-bot | declared-bot | unwanted-bot | hostile | infrastructure\',\n \' category: "observed",\',\n ` provenance: "Captured from the live dashboard on ${new Date(entry.at).toISOString().slice(0, 10)}",`,\n " requests: [",\n " {",\n " headers: [",\n headers,\n " ],",\n ` protocol: ${JSON.stringify(entry.protocol ?? "https")},`,\n ` httpVersion: ${JSON.stringify(entry.httpVersion ?? "1.1")},`,\n ` path: ${JSON.stringify(entry.path)},`,\n " },",\n " ],",\n ` expect: { verdict: ${JSON.stringify(entry.verdict)}, certain: ${String(entry.certain)} },`,\n "}),"\n ].join("\\n");\n }\n\n // src/dashboard/client/result.ts\n function showResult(kind, build) {\n const box = $("policy-result");\n box.hidden = false;\n box.className = `result ${kind}`;\n clear(box);\n build(box);\n }\n function renderPreview(preview, notes = []) {\n showResult(preview.newDenials > 0 ? "warn" : "ok", (box) => {\n const head = el("div");\n head.appendChild(el("b", null, `${n(preview.changed)} of ${n(preview.evaluated)} requests would be treated differently.`));\n box.appendChild(head);\n for (const note of notes) box.appendChild(el("div", "ev-meta", note));\n if (preview.newDenials > 0) {\n box.appendChild(el("div", null, `${n(preview.newDenials)} request(s) that are served today would be denied. Read the samples before applying this.`));\n }\n for (const warning of preview.warnings) box.appendChild(el("div", "ev-meta", warning));\n const dead = preview.ruleHits.filter((row) => row.hits === 0 && row.rule !== "default");\n if (dead.length > 0) box.appendChild(el("div", "ev-meta", `Never matched in this window: ${dead.map((row) => row.rule).join(", ")}`));\n if (preview.samples.length > 0) {\n const table = el("table", "diff");\n const head2 = el("tr");\n for (const label2 of ["Request", "Now", "Would be"]) head2.appendChild(el("th", null, label2));\n table.appendChild(head2);\n for (const sample of preview.samples) {\n const row = el("tr");\n const what = el("td");\n what.appendChild(el("div", "mono", sample.path));\n what.appendChild(el("div", "ev-meta", `${sample.verdict} \xB7 ${sample.userAgent.slice(0, 48)}`));\n row.appendChild(what);\n const from = el("td", "from");\n from.appendChild(el("div", null, sample.from));\n from.appendChild(el("div", "ev-meta", sample.fromRule));\n row.appendChild(from);\n const kind = sample.to === "block" || sample.to === "drop" || sample.to === "redirect" ? "deny" : sample.to === "allow" ? "allow" : "";\n const to = el("td", `to ${kind}`);\n to.appendChild(el("div", null, sample.to));\n to.appendChild(el("div", "ev-meta", sample.toRule));\n row.appendChild(to);\n table.appendChild(row);\n }\n box.appendChild(table);\n } else if (preview.evaluated === 0) {\n box.appendChild(el("div", "ev-meta", "No traffic in the window to preview against \u2014 send some requests first."));\n }\n });\n }\n\n // src/dashboard/client/guard.ts\n var draft;\n var MODE_NOTES = {\n strict: "A terminal action survives only on proven evidence. Nothing is ever denied on a guess. This is the default, and it is the claim this library makes about itself.",\n balanced: "A terminal action also survives on a probabilistic verdict that clears the score threshold with at least two independent strong signals. Real people do trip two signals \u2014 a hardened browser behind a corporate proxy is the usual pair \u2014 so this setting will eventually deny somebody who should have been served.",\n aggressive: "The guard is off. Every rule does exactly what it says, on proof or on suspicion alike, and the people it turns away first are the ones with the most unusual and most legitimate setups."\n };\n function drawGuard() {\n if (!SECTIONS.guard) return;\n const document_ = state.policy;\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const editable = document_?.guardEditable === true;\n const panel = $("stat-policy");\n clear(panel);\n if (!editable || document_ === void 0) {\n const rows = [\n ["False-positive policy", snapshot.policy.falsePositivePolicy],\n ["Fallback when the guard stops a rule", snapshot.policy.fallbackAction],\n ["Terminal score threshold", String(snapshot.policy.terminalScoreThreshold)],\n ["Suspect threshold", String(snapshot.policy.suspectThreshold)],\n ["Action when no rule matches", snapshot.policy.defaultAction],\n ["Challenge configured", snapshot.policy.challengeEnabled ? "yes" : "no"],\n ["Range sets", snapshot.ranges.length === 0 ? "none" : snapshot.ranges.map((range) => `${range.name} (${range.size})`).join(", ")]\n ];\n for (const [key, value] of rows) {\n const line = el("div", "stat-row");\n line.appendChild(el("span", "k", key));\n line.appendChild(el("span", "v", value));\n panel.appendChild(line);\n }\n $("guard-mode").textContent = "not editable here";\n $("guard-note").textContent = "These are fixed at construction on this dashboard. It can change which rules exist; it cannot change how far a rule is allowed to go, because relaxing that is the one edit that can start denying people. Enable it deliberately with controls: { editGuard: true }.";\n return;\n }\n if (draft === void 0) draft = { ...document_.guard };\n const vocabulary = document_.vocabulary;\n $("guard-mode").textContent = state.guardDirty ? "unsaved changes" : "editable";\n $("guard-note").textContent = "Changing these changes what every rule is allowed to do, on the next request. Preview it against the traffic in the window first \u2014 that is the only view you get of who it would start turning away.";\n panel.appendChild(\n guardField(\n // "Mode" rather than "Guard": the panel is already called that, and a field\n // repeating its own panel\'s name reads as a heading rather than as a control.\n "Mode",\n segmented(\n vocabulary.falsePositivePolicies.map((mode) => [mode, mode]),\n draft.falsePositivePolicy,\n (value) => {\n setDraft({ falsePositivePolicy: value });\n drawGuard();\n }\n )\n )\n );\n panel.appendChild(el("div", "note guard-explains", MODE_NOTES[draft.falsePositivePolicy] ?? ""));\n panel.appendChild(\n guardField(\n "Fallback",\n select(vocabulary.fallbackActions, draft.fallbackAction, (value) => setDraft({ fallbackAction: value })),\n "what a stopped rule becomes \u2014 the terminal actions are absent because a terminal fallback would deny the request the guard just protected"\n )\n );\n panel.appendChild(\n guardField(\n "Default action",\n select(vocabulary.actions, draft.defaultAction, (value) => setDraft({ defaultAction: value })),\n "when no rule matches"\n )\n );\n panel.appendChild(\n guardField(\n "Terminal score",\n number(draft.terminalScoreThreshold, (value) => setDraft({ terminalScoreThreshold: value })),\n "balanced mode only: the score a probabilistic verdict must clear"\n )\n );\n panel.appendChild(\n guardField(\n "Suspect at",\n number(draft.suspectThreshold, (value) => setDraft({ suspectThreshold: value })),\n "the score at which a request becomes suspected-bot"\n )\n );\n const bar = el("div", "bar-actions");\n const preview = el("button", null, "Preview");\n preview.addEventListener("click", () => {\n void previewGuard();\n });\n const apply2 = el("button", "primary", "Apply");\n apply2.addEventListener("click", () => {\n void applyGuard();\n });\n const revert = el("button", null, "Revert");\n revert.addEventListener("click", () => {\n draft = { ...document_.guard };\n state.guardDirty = false;\n drawGuard();\n });\n bar.appendChild(preview);\n bar.appendChild(apply2);\n bar.appendChild(revert);\n panel.appendChild(bar);\n }\n function setDraft(change) {\n if (draft === void 0) return;\n draft = { ...draft, ...change };\n state.guardDirty = true;\n $("guard-mode").textContent = "unsaved changes";\n }\n function resetGuardDraft() {\n draft = void 0;\n state.guardDirty = false;\n }\n function liveRules() {\n return (state.policy?.rules ?? []).filter((row) => row.editable && row.rule !== void 0).map((row) => row.rule);\n }\n async function previewGuard() {\n if (draft === void 0) return;\n const result = await postJson("/api/policy/preview", { rules: liveRules(), guard: draft });\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n renderPreview(result.data, state.editorDirty ? ["Previewed against the rules currently in force, not the unsaved edits in the editor."] : []);\n app.showTab("policy");\n }\n async function applyGuard() {\n if (draft === void 0) return;\n const result = await postJson("/api/guard", draft);\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Guard unchanged", result.error ?? "");\n return;\n }\n state.guardDirty = false;\n draft = { ...result.data.guard };\n if (state.policy !== void 0) state.policy.guard = { ...result.data.guard };\n toast("ok", "Guard changed", `${result.data.guard.falsePositivePolicy}, falling back to ${result.data.guard.fallbackAction}.`);\n showResult("warn", (box) => {\n box.appendChild(el("div", null, "The guard changed. It applies from the next request, and it is in the notices panel and in your logs."));\n if (result.data.guard.falsePositivePolicy !== "strict") {\n box.appendChild(\n el(\n "div",\n "ev-meta",\n "Requests can now be denied without proof. The guard-stop count is the series to watch: every stop that no longer happens is a request that used to be recoverable and is not any more."\n )\n );\n }\n });\n app.draw();\n }\n function guardField(name, control, hint) {\n const row = el("div", "field");\n row.appendChild(label(name, control));\n const right = el("div", "field-row");\n right.appendChild(control);\n if (hint !== void 0) right.appendChild(el("span", "hint", hint));\n row.appendChild(right);\n return row;\n }\n function segmented(options, value, onChange) {\n const box = el("div", "seg");\n for (const [label2, option] of options) {\n const button = el("button", null, label2);\n button.type = "button";\n button.setAttribute("aria-pressed", String(option === value));\n button.addEventListener("click", () => onChange(option));\n box.appendChild(button);\n }\n return box;\n }\n function select(options, value, onChange) {\n const node = el("select");\n for (const option of options) {\n const item = el("option", null, option);\n item.value = option;\n if (option === value) item.selected = true;\n node.appendChild(item);\n }\n node.addEventListener("change", () => onChange(node.value));\n return node;\n }\n function number(value, onChange) {\n const input = el("input");\n input.type = "number";\n input.min = "1";\n input.max = "100";\n input.value = String(value);\n input.addEventListener("input", () => {\n if (input.value !== "") onChange(Number(input.value));\n });\n return input;\n }\n\n // src/dashboard/client/ranges.ts\n var sets = [];\n async function loadRanges() {\n if (!SECTIONS.ranges) return;\n try {\n const body = await getJson("/api/ranges");\n sets = body.ranges;\n drawRanges();\n } catch {\n }\n }\n function drawRanges() {\n if (!SECTIONS.ranges) return;\n const body = $("ranges-body");\n clear(body);\n $("ranges-mode").textContent = BOOT.allowActing ? "editable" : "read-only";\n $("ranges-note").textContent = BOOT.allowActing ? "An address on the allowlist is not judged leniently \u2014 it is not judged at all. Detection does not run on it, no evidence is produced, and no rule sees it." : "These come from the code that constructed the handler. Enable controls.editRanges to add an address from here.";\n if (sets.length === 0) {\n body.appendChild(el("div", "note", "No range sets are configured. Add an address to the allowlist and one appears."));\n }\n for (const set of sets) {\n const block = el("div", "rangeset");\n const heading = el("h3");\n heading.appendChild(document.createTextNode(set.name));\n heading.appendChild(el("span", null, `${n(set.size)} entr${set.size === 1 ? "y" : "ies"}`));\n block.appendChild(heading);\n const list = el("div", "cidrs");\n for (const entry of set.entries) {\n const chip = el("span", BOOT.allowActing ? "cidr" : "cidr readonly");\n chip.appendChild(document.createTextNode(entry));\n if (BOOT.allowActing) {\n const remove = el("button", null, "\xD7");\n remove.title = `Remove ${entry} from ${set.name}`;\n remove.setAttribute("aria-label", `Remove ${entry} from ${set.name}`);\n remove.addEventListener("click", () => void update(set.name, { remove: [entry] }));\n chip.appendChild(remove);\n }\n list.appendChild(chip);\n }\n if (set.entries.length === 0) list.appendChild(el("span", "hint", "empty"));\n block.appendChild(list);\n body.appendChild(block);\n }\n if (!BOOT.allowActing) return;\n const form = el("div", "rangeset");\n const row = el("div", "field-row");\n const name = el("input", "mono-input");\n name.type = "text";\n name.value = "allowlist";\n name.setAttribute("aria-label", "Range set");\n name.style.maxWidth = "150px";\n const value = el("input", "mono-input");\n value.type = "text";\n value.placeholder = "203.0.113.0/24";\n value.setAttribute("aria-label", "Address or CIDR to add");\n const add = el("button", null, "Add");\n const submit = () => {\n const entry = value.value.trim();\n if (entry === "") return;\n value.value = "";\n void update(name.value.trim(), { add: [entry] });\n };\n add.addEventListener("click", submit);\n value.addEventListener("keydown", (event) => {\n if (event.key === "Enter") submit();\n });\n row.appendChild(name);\n row.appendChild(value);\n row.appendChild(add);\n form.appendChild(row);\n body.appendChild(form);\n }\n async function update(name, change) {\n const result = await postJson("/api/ranges", { name, ...change });\n if (!result.ok) {\n toast("bad", "Ranges unchanged", result.error ?? "");\n return;\n }\n toast(name === "allowlist" && change.add !== void 0 ? "warn" : "ok", `\u201C${name}\u201D updated`, `${n(result.data.entries?.length ?? 0)} entr${result.data.entries?.length === 1 ? "y" : "ies"} now.`);\n await loadRanges();\n }\n\n // src/dashboard/client/draft.ts\n function draftRule(entry, existingIds = []) {\n const match = {};\n let because;\n let stem;\n const proven = entry.evidence.filter((item) => item.certainty === "certain" && item.direction !== "human");\n const detectors = [...new Set((proven.length > 0 ? proven : entry.evidence.filter((item) => item.direction !== "human")).map((item) => item.detector))];\n if (entry.identity !== void 0 && entry.identity !== "") {\n match["identity"] = [entry.identity];\n if (entry.certain) match["certain"] = true;\n stem = entry.identity;\n because = entry.certain ? `Matched on the identity \u201C${entry.identity}\u201D, and on proof \u2014 so a client merely claiming that name does not match.` : `Matched on the claimed identity \u201C${entry.identity}\u201D. Nothing has verified it, so this matches anything that says so.`;\n } else if (proven.length > 0) {\n match["detector"] = detectors;\n match["certain"] = true;\n stem = detectors[0] ?? "proven";\n because = `Matched on proof from ${detectors.join(", ")}. Only requests that carry the same proof match.`;\n } else if (detectors.length > 0) {\n match["verdict"] = [entry.verdict];\n match["detector"] = detectors;\n match["minScore"] = Math.max(0, Math.floor(entry.score / 10) * 10);\n stem = detectors[0] ?? entry.verdict;\n because = `Matched on ${entry.verdict} at score ${String(match["minScore"])} or more, from ${detectors.join(", ")}. Every one of those is probabilistic, so the guard will not let this rule deny anybody.`;\n } else {\n match["verdict"] = [entry.verdict];\n stem = entry.verdict;\n because = `Nothing fired on this request, so there is nothing sharper to match on than the verdict itself. Narrow it before you use it.`;\n }\n return {\n rule: {\n id: uniqueId(`from-${slug(stem)}`, existingIds),\n match,\n action: "tag",\n reason: "Drafted from a request on the dashboard.",\n _open: true\n },\n because\n };\n }\n function slug(value) {\n const cleaned = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");\n return cleaned === "" ? "request" : cleaned.slice(0, 40);\n }\n function uniqueId(wanted, taken) {\n if (!taken.includes(wanted)) return wanted;\n for (let suffix = 2; suffix < 1e3; suffix++) {\n const candidate = `${wanted}-${suffix}`;\n if (!taken.includes(candidate)) return candidate;\n }\n return `${wanted}-${Date.now()}`;\n }\n\n // src/dashboard/client/policy.ts\n async function loadPolicy() {\n if (!SECTIONS.policy) return;\n try {\n const document_ = await getJson("/api/policy");\n state.policy = document_;\n if (!state.editorDirty) {\n setEditorRules(document_.rules.filter((row) => row.editable).map((row) => row.rule));\n }\n if (!state.guardDirty) resetGuardDraft();\n drawPolicyTab();\n } catch {\n }\n }\n function setEditorRules(rules) {\n state.editorRules = JSON.parse(JSON.stringify(rules ?? []));\n renderEditor();\n }\n function markDirty() {\n state.editorDirty = true;\n $("policy-dirty").hidden = false;\n }\n function editorRules() {\n if (state.editorMode === "json") {\n try {\n const parsed = JSON.parse(byId("policy-json").value);\n if (!Array.isArray(parsed)) return { error: "The JSON must be an array of rules." };\n return { rules: parsed };\n } catch (error) {\n return { error: `The editor does not contain valid JSON: ${String(error)}` };\n }\n }\n return { rules: state.editorRules };\n }\n function cleanRule(rule) {\n const match = {};\n for (const [key, value] of Object.entries(rule.match ?? {})) {\n if (value === void 0 || value === null || value === "") continue;\n if (Array.isArray(value) && value.length === 0) continue;\n match[key] = value;\n }\n const params = {};\n for (const [key, value] of Object.entries(rule.params ?? {})) {\n if (value === void 0 || value === null || value === "") continue;\n if (key === "limit") {\n const limit = value;\n if (limit.max === void 0 || limit.windowMs === void 0) continue;\n }\n params[key] = value;\n }\n const out = { id: rule.id, match, action: rule.action };\n if (Object.keys(params).length > 0) out["params"] = params;\n if (rule.reason !== void 0 && rule.reason !== "") out["reason"] = rule.reason;\n return out;\n }\n function cleanRules(rules) {\n return rules.map(cleanRule);\n }\n function field(name, control, hint) {\n const row = el("div", "field");\n row.appendChild(label(name, control));\n const right = el("div", "field-row");\n for (const node of Array.isArray(control) ? control : [control]) right.appendChild(node);\n if (hint !== void 0) right.appendChild(el("span", "hint", hint));\n row.appendChild(right);\n return row;\n }\n function chipSelect(options, selected, onChange) {\n const box = el("div", "chips-select");\n const chosen = Array.isArray(selected) ? [...selected] : selected === void 0 ? [] : [String(selected)];\n for (const option of options) {\n const button = el("button", null, option);\n button.type = "button";\n button.setAttribute("aria-pressed", String(chosen.includes(option)));\n button.addEventListener("click", () => {\n const at = chosen.indexOf(option);\n if (at === -1) chosen.push(option);\n else chosen.splice(at, 1);\n button.setAttribute("aria-pressed", String(at === -1));\n onChange(chosen.length === 0 ? void 0 : [...chosen]);\n });\n box.appendChild(button);\n }\n return box;\n }\n function segmented2(options, value, onChange) {\n const box = el("div", "seg");\n for (const [label2, option] of options) {\n const button = el("button", null, label2);\n button.type = "button";\n button.setAttribute("aria-pressed", String(option === value));\n button.addEventListener("click", () => {\n for (const other of Array.from(box.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n onChange(option);\n });\n box.appendChild(button);\n }\n return box;\n }\n function textInput(value, placeholder, onChange, mono = false) {\n const input = el("input", mono ? "mono-input" : null);\n input.type = "text";\n input.value = value === void 0 || value === null ? "" : String(value);\n input.placeholder = placeholder;\n input.addEventListener("input", () => onChange(input.value.trim() === "" ? void 0 : input.value));\n return input;\n }\n function listInput(value, placeholder, onChange) {\n const current = value === void 0 ? "" : Array.isArray(value) ? value.join(", ") : String(value);\n const input = textInput(current, placeholder, () => {\n }, true);\n input.addEventListener("input", () => {\n const parts = input.value.split(",").map((part) => part.trim()).filter(Boolean);\n onChange(parts.length === 0 ? void 0 : parts.length === 1 ? parts[0] : parts);\n });\n return input;\n }\n function numberInput(value, placeholder, onChange) {\n const input = el("input");\n input.type = "number";\n input.value = value === void 0 || value === null ? "" : String(value);\n input.placeholder = placeholder;\n input.addEventListener("input", () => onChange(input.value === "" ? void 0 : Number(input.value)));\n return input;\n }\n function matchSummary(rule) {\n const box = el("div", "rule-summary");\n const match = rule.match ?? {};\n const parts = [];\n for (const key of ["verdict", "botClass", "category", "identity", "detector", "method", "path"]) {\n const value = match[key];\n if (value === void 0) continue;\n parts.push([key, Array.isArray(value) ? value.join(", ") : String(value)]);\n }\n if (match["certain"] !== void 0) parts.push(["certain", String(match["certain"])]);\n if (match["minScore"] !== void 0 || match["maxScore"] !== void 0) {\n parts.push(["score", `${String(match["minScore"] ?? 0)}\u2013${String(match["maxScore"] ?? 99)}`]);\n }\n if (match["minPriorConfirmations"] !== void 0) parts.push(["prior", String(match["minPriorConfirmations"])]);\n if (match["minUnsolvedChallenges"] !== void 0) parts.push(["unsolved", String(match["minUnsolvedChallenges"])]);\n if (parts.length === 0) {\n box.appendChild(el("span", "none", "matches everything"));\n return box;\n }\n for (const [key, value] of parts.slice(0, 4)) box.appendChild(el("span", "t", `${key}: ${value}`));\n if (parts.length > 4) box.appendChild(el("span", "k", `+${parts.length - 4} more`));\n return box;\n }\n function ruleCard(rule, index) {\n const vocabulary = state.policy?.vocabulary;\n const open = rule._open === true;\n const card = el("div", `rule${open ? "" : " collapsed"}`);\n const head = el("div", "rule-head");\n const chevron = el("button", "chev", open ? "\u25BE" : "\u25B8");\n chevron.title = open ? "Collapse" : "Expand";\n chevron.setAttribute("aria-expanded", String(open));\n chevron.addEventListener("click", () => {\n rule._open = !open;\n renderEditor();\n });\n head.appendChild(chevron);\n head.appendChild(el("span", "ord", index + 1));\n const id = textInput(rule.id, "rule-id", (value) => {\n rule.id = value ?? "";\n markDirty();\n }, true);\n id.setAttribute("aria-label", "Rule id");\n head.appendChild(id);\n if (open) {\n const action = el("select");\n action.setAttribute("aria-label", "Action");\n for (const name of vocabulary?.actions ?? []) {\n const option = el("option", null, name);\n option.value = name;\n if (name === rule.action) option.selected = true;\n action.appendChild(option);\n }\n action.addEventListener("change", () => {\n rule.action = action.value;\n rule.params = {};\n markDirty();\n renderEditor();\n });\n head.appendChild(action);\n } else {\n head.appendChild(matchSummary(rule));\n head.appendChild(el("span", `act-pill ${actionKind(rule.action)}`, rule.action));\n }\n const up = el("button", "icon", "\u2191");\n up.title = "Move earlier \u2014 the first matching rule wins";\n up.addEventListener("click", () => moveRule(index, -1));\n const down = el("button", "icon", "\u2193");\n down.title = "Move later";\n down.addEventListener("click", () => moveRule(index, 1));\n const remove = el("button", "icon danger", "Remove");\n remove.addEventListener("click", () => {\n state.editorRules.splice(index, 1);\n markDirty();\n renderEditor();\n });\n head.appendChild(up);\n head.appendChild(down);\n head.appendChild(remove);\n card.appendChild(head);\n if (!open) return card;\n const body = el("div", "rule-body");\n rule.match = rule.match ?? {};\n const match = rule.match;\n body.appendChild(field("Verdict", chipSelect(vocabulary?.verdicts ?? [], match["verdict"], (value) => {\n match["verdict"] = value;\n markDirty();\n })));\n body.appendChild(field("Bot class", chipSelect(vocabulary?.botClasses ?? [], match["botClass"], (value) => {\n match["botClass"] = value;\n markDirty();\n })));\n body.appendChild(field("Category", chipSelect(vocabulary?.categories ?? [], match["category"], (value) => {\n match["category"] = value;\n markDirty();\n })));\n body.appendChild(field("Detector", chipSelect(vocabulary?.detectors ?? [], match["detector"], (value) => {\n match["detector"] = value;\n markDirty();\n })));\n body.appendChild(field("Method", chipSelect(vocabulary?.methods ?? [], match["method"], (value) => {\n match["method"] = value;\n markDirty();\n })));\n body.appendChild(\n field(\n "Evidence",\n segmented2(\n [\n ["any", void 0],\n ["proven", true],\n ["unproven", false]\n ],\n match["certain"],\n (value) => {\n match["certain"] = value;\n markDirty();\n }\n ),\n "proven means at least one piece of certain evidence \u2014 including a proven human"\n )\n );\n body.appendChild(\n field("Score", [\n numberInput(match["minScore"], "min", (value) => {\n match["minScore"] = value;\n markDirty();\n }),\n el("span", "hint", "to"),\n numberInput(match["maxScore"], "max", (value) => {\n match["maxScore"] = value;\n markDirty();\n })\n ])\n );\n body.appendChild(field("Identity", listInput(match["identity"], "googlebot, gptbot", (value) => {\n match["identity"] = value;\n markDirty();\n })));\n body.appendChild(field("Path", listInput(match["path"], "/api/, /search", (value) => {\n match["path"] = value;\n markDirty();\n }), "a string matches as a prefix"));\n body.appendChild(\n field(\n "Prior bots",\n numberInput(match["minPriorConfirmations"], "0", (value) => {\n match["minPriorConfirmations"] = value;\n markDirty();\n }),\n "times this actor was already proven a bot"\n )\n );\n body.appendChild(\n field(\n "Unsolved",\n numberInput(match["minUnsolvedChallenges"], "0", (value) => {\n match["minUnsolvedChallenges"] = value;\n markDirty();\n }),\n "challenges issued to this actor that were never answered \u2014 solving one clears the count"\n )\n );\n rule.params = rule.params ?? {};\n const params = rule.params;\n for (const node of paramFields(rule.action, params)) body.appendChild(node);\n body.appendChild(field("Reason", textInput(rule.reason, "shown in the decision and in your logs", (value) => {\n rule.reason = value ?? "";\n markDirty();\n })));\n card.appendChild(body);\n return card;\n }\n function paramFields(action, params) {\n switch (action) {\n case "block":\n return [\n field("Status", numberInput(params["status"], "403", (value) => {\n params["status"] = value;\n markDirty();\n })),\n field("Body", textInput(params["body"], "Automated traffic is not served here.", (value) => {\n params["body"] = value;\n markDirty();\n }))\n ];\n case "redirect":\n return [field("Location", textInput(params["location"], "/too-fast", (value) => {\n params["location"] = value;\n markDirty();\n }, true))];\n case "delay":\n return [field("Delay", numberInput(params["delayMs"], "250", (value) => {\n params["delayMs"] = value;\n markDirty();\n }), "milliseconds")];\n case "rate-limit": {\n const limit = params["limit"] ?? {};\n params["limit"] = limit;\n return [\n field("Limit", [\n numberInput(limit["max"], "60", (value) => {\n limit["max"] = value;\n markDirty();\n }),\n el("span", "hint", "requests per"),\n numberInput(limit["windowMs"], "60000", (value) => {\n limit["windowMs"] = value;\n markDirty();\n }),\n el("span", "hint", "ms")\n ])\n ];\n }\n case "custom":\n return [field("Handler", textInput(params["handler"], "handler-id", (value) => {\n params["handler"] = value;\n markDirty();\n }, true), "id of a handler you registered")];\n default:\n return [];\n }\n }\n function lockedCard(row) {\n const card = el("div", "rule locked");\n const head = el("div", "rule-head");\n head.appendChild(el("span", "ord", `#${row.index + 1}`));\n head.appendChild(el("span", "mono", row.id));\n head.appendChild(el("span", "grow"));\n head.appendChild(el("span", "pill", "predicate \u2014 locked"));\n card.appendChild(head);\n card.appendChild(\n el("div", "rule-body", "This rule matches with a function, which cannot be represented here or sent over HTTP. It stays exactly as it is, at this position, whatever else you change.")\n );\n return card;\n }\n function moveRule(index, delta) {\n const target = index + delta;\n if (target < 0 || target >= state.editorRules.length) return;\n const moved = state.editorRules.splice(index, 1)[0];\n if (moved === void 0) return;\n state.editorRules.splice(target, 0, moved);\n markDirty();\n renderEditor();\n }\n function renderEditor() {\n if (!SECTIONS.policy) return;\n const list = $("rulelist");\n clear(list);\n const locked = (state.policy?.rules ?? []).filter((row) => !row.editable);\n if (state.editorRules.length === 0 && locked.length === 0) {\n list.appendChild(el("div", "note", "No rules. Every request takes the default action \u2014 add one, or import a set."));\n }\n const rendered2 = state.editorRules.map((rule, index) => ruleCard(rule, index));\n for (const row of locked) rendered2.splice(Math.min(row.index, rendered2.length), 0, lockedCard(row));\n for (const node of rendered2) list.appendChild(node);\n if (state.editorMode === "json") byId("policy-json").value = JSON.stringify(cleanRules(state.editorRules), null, 2);\n }\n function drawPolicyTab() {\n const document_ = state.policy;\n if (document_ === void 0) return;\n const editable = document_.editable;\n $("policy-apply").hidden = !editable;\n byId("policy-json").readOnly = !editable;\n $("policy-mode").textContent = editable ? "editable" : "read-only";\n $("rule-add").hidden = !editable;\n $("policy-import").hidden = !editable;\n const preserved = document_.rules.filter((row) => !row.editable);\n let note = editable ? "First match wins \u2014 order matters." : "Read-only. Enable controls.editPolicy to change these.";\n if (preserved.length > 0) note += ` ${preserved.length} rule(s) use a predicate function and are locked.`;\n $("policy-note").textContent = note;\n renderPresetButtons();\n drawGuard();\n drawRanges();\n if (SECTIONS.robots) {\n $("robots-preview").textContent = document_.robots === "" ? "(this policy declines no crawler by name)" : document_.robots;\n const notes = $("robots-notes");\n clear(notes);\n for (const note_ of document_.robotsNotes) notes.appendChild(el("div", "ev-meta", `${note_.rule}: ${note_.reason}`));\n }\n const rules = $("stat-rules");\n clear(rules);\n const installed = state.snapshot?.rules ?? [];\n if (installed.length === 0) rules.appendChild(el("div", "note", "No rules configured \u2014 every request takes the default action."));\n else installed.forEach((rule, index) => rules.appendChild(el("span", "chip", `${index + 1}. ${rule}`)));\n }\n async function draftIntoEditor(entry) {\n if (state.policy === void 0) await loadPolicy();\n const drafted = draftRule(entry, state.editorRules.map((rule) => rule.id));\n state.editorRules.push(drafted.rule);\n markDirty();\n if (state.editorMode === "json") byId("policy-json").value = JSON.stringify(cleanRules(state.editorRules), null, 2);\n renderEditor();\n app.showTab("policy");\n const notes = [\n `Drafted \u201C${drafted.rule.id}\u201D, tagging only. Nothing is applied \u2014 read it, choose the action, then apply.`,\n drafted.because,\n "It was added last, which is the only position that cannot change what an existing rule does. Move it up with \u2191 if it needs to win."\n ];\n showResult("warn", (box) => {\n for (const note of notes) box.appendChild(el("div", note === notes[0] ? null : "ev-meta", note));\n });\n toast("ok", "Rule drafted", "In the editor, tagging only, not applied.");\n await runPreview(notes);\n }\n function switchToGui() {\n if (state.editorMode === "gui") return;\n const parsed = editorRules();\n if (parsed.error !== void 0) {\n toast("bad", "That JSON will not parse", parsed.error);\n return;\n }\n state.editorRules = parsed.rules ?? [];\n state.editorMode = "gui";\n $("mode-gui").setAttribute("aria-pressed", "true");\n $("mode-json").setAttribute("aria-pressed", "false");\n $("editor-gui").hidden = false;\n $("editor-json").hidden = true;\n renderEditor();\n }\n function switchToJson() {\n state.editorMode = "json";\n $("mode-gui").setAttribute("aria-pressed", "false");\n $("mode-json").setAttribute("aria-pressed", "true");\n $("editor-gui").hidden = true;\n $("editor-json").hidden = false;\n byId("policy-json").value = JSON.stringify(cleanRules(state.editorRules), null, 2);\n }\n async function exportSettings() {\n try {\n const response = await fetch(`${API}/api/settings`);\n const text = await response.text();\n if (!response.ok) throw new Error(text);\n download(text, `bothandler-settings-${today()}.json`, "application/json");\n toast("ok", "Settings exported", "Rules, plus a record of the configuration around them.");\n } catch (error) {\n toast("bad", "Export failed", String(error));\n }\n }\n function readSettingsFile(file) {\n const reader = new FileReader();\n reader.onload = () => {\n try {\n applyImported(JSON.parse(String(reader.result)), file.name);\n } catch (error) {\n toast("bad", "That file is not JSON", String(error));\n }\n };\n reader.onerror = () => toast("bad", "Could not read that file", "");\n reader.readAsText(file);\n }\n function applyImported(document_, name) {\n const rules = Array.isArray(document_) ? document_ : Array.isArray(document_.rules) ? document_.rules : void 0;\n if (rules === void 0) {\n toast("bad", "Nothing to import", "Expected an array of rules, or a settings file with a rules array.");\n return;\n }\n setEditorRules(rules);\n markDirty();\n switchToGui();\n const ignored = [];\n const readOnly = document_.readOnly;\n if (readOnly !== void 0) {\n ignored.push("the guard, the detectors, the ranges and the audit \u2014 those come from the code that built the handler, not from a file");\n if (Array.isArray(readOnly.lockedRules) && readOnly.lockedRules.length > 0) {\n ignored.push(`${readOnly.lockedRules.length} predicate rule(s), which stay as they are`);\n }\n }\n showResult("warn", (box) => {\n box.appendChild(el("div", null, `Loaded ${rules.length} rule(s) from ${name}. Nothing has been applied yet \u2014 preview it first.`));\n for (const line of ignored) box.appendChild(el("div", "ev-meta", `Ignored: ${line}`));\n });\n toast("ok", `Imported ${rules.length} rule(s)`, "Review, preview, then apply.");\n }\n function collectForSubmit() {\n const parsed = editorRules();\n if (parsed.error !== void 0) {\n showResult("bad", (box) => box.appendChild(el("div", null, parsed.error ?? "")));\n toast("bad", "That JSON will not parse", parsed.error);\n return void 0;\n }\n const cleaned = cleanRules(parsed.rules ?? []);\n const blank = cleaned.filter((rule) => rule["id"] === void 0 || rule["id"] === "").length;\n if (blank > 0) {\n toast("bad", "Every rule needs an id", "It is what every decision and log line names.");\n return void 0;\n }\n return cleaned;\n }\n async function runPreview(notes = []) {\n const rules = collectForSubmit();\n if (rules === void 0) return;\n const result = await postJson("/api/policy/preview", { rules });\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n renderPreview(result.data, notes);\n }\n async function applyPolicy() {\n const rules = collectForSubmit();\n if (rules === void 0) return;\n const result = await postJson("/api/policy/apply", { rules });\n if (!result.ok) {\n showResult("bad", (box) => box.appendChild(el("div", null, result.error ?? "")));\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n state.editorDirty = false;\n $("policy-dirty").hidden = true;\n await loadPolicy();\n toast("ok", "Applied", `${n(result.data.rules)} rule(s) now in force.`);\n showResult("ok", (box) => {\n box.appendChild(el("div", null, `Applied. ${n(result.data.rules)} rule(s) are now in force.`));\n for (const warning of result.data.warnings ?? []) box.appendChild(el("div", "ev-meta", warning));\n });\n }\n function renderPresetButtons() {\n const box = $("preset-buttons");\n const presets = state.policy?.vocabulary.presets ?? [];\n if (box.childElementCount === presets.length) return;\n clear(box);\n for (const preset of presets) {\n const button = el("button", null, preset);\n button.addEventListener("click", () => {\n void (async () => {\n const result = await postJson("/api/policy/preview", { preset });\n if (!result.ok) {\n toast("bad", "Refused", result.error ?? "");\n return;\n }\n renderPreview(result.data);\n })();\n });\n box.appendChild(button);\n }\n }\n function initPolicy() {\n if (!SECTIONS.policy) return;\n $("mode-gui").addEventListener("click", switchToGui);\n $("mode-json").addEventListener("click", switchToJson);\n $("rule-add").addEventListener("click", () => {\n state.editorRules.push({ id: `new-rule-${state.editorRules.length + 1}`, match: {}, action: "tag", params: {}, _open: true });\n markDirty();\n renderEditor();\n });\n $("rule-expand").addEventListener("click", () => {\n const anyClosed = state.editorRules.some((rule) => rule._open !== true);\n for (const rule of state.editorRules) rule._open = anyClosed;\n $("rule-expand").textContent = anyClosed ? "Collapse all" : "Expand all";\n renderEditor();\n });\n byId("policy-json").addEventListener("input", markDirty);\n $("policy-preview").addEventListener("click", () => void runPreview());\n $("policy-apply").addEventListener("click", () => void applyPolicy());\n $("policy-revert").addEventListener("click", () => {\n state.editorDirty = false;\n $("policy-dirty").hidden = true;\n $("policy-result").hidden = true;\n resetGuardDraft();\n void loadPolicy();\n });\n $("policy-export").addEventListener("click", () => void exportSettings());\n $("policy-import").addEventListener("click", () => byId("policy-file").click());\n byId("policy-file").addEventListener("change", () => {\n const input = byId("policy-file");\n const file = input.files?.[0];\n if (file !== void 0) readSettingsFile(file);\n input.value = "";\n });\n const panel = $("editor-panel");\n for (const name of ["dragenter", "dragover"]) {\n panel.addEventListener(name, (event) => {\n if (state.policy?.editable !== true) return;\n event.preventDefault();\n panel.classList.add("drop");\n });\n }\n for (const name of ["dragleave", "drop"]) {\n panel.addEventListener(name, (event) => {\n panel.classList.remove("drop");\n if (name !== "drop") return;\n event.preventDefault();\n const file = event.dataTransfer?.files?.[0];\n if (file !== void 0) readSettingsFile(file);\n });\n }\n }\n\n // src/dashboard/client/feed.ts\n var FILTERS = [\n ["all", "All"],\n ["proven", "Proven"],\n ["suspected", "Suspected"],\n ["human", "Human"],\n ["guard", "Guard stops"],\n ["deny", "Denied"],\n ["mitigate", "Mitigated"],\n ["allow", "Served"]\n ];\n var rendered = /* @__PURE__ */ new Map();\n function initFeed() {\n const loadThem = byId("feed-load-skipped");\n loadThem.addEventListener("click", () => {\n loadThem.disabled = true;\n void loadSkipped().finally(() => {\n loadThem.disabled = false;\n });\n });\n const filters = $("filters");\n for (const [name, label2] of FILTERS) {\n const button = el("button", null, label2);\n button.setAttribute("aria-pressed", String(name === state.filter));\n button.dataset["filter"] = name;\n button.addEventListener("click", () => {\n state.filter = name;\n resetPaging();\n for (const other of Array.from(filters.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n app.syncUrl();\n app.drawNow();\n });\n filters.appendChild(button);\n }\n const search = byId("search");\n search.addEventListener("input", () => {\n setSearch(search.value.trim());\n app.syncUrl();\n app.drawNow();\n showSuggestions(search);\n });\n initSuggestions(search);\n initTimeframe();\n initSavedFilters(search);\n const exportShown = byId("feed-export");\n exportShown.hidden = !SECTIONS.evidence;\n exportShown.addEventListener("click", () => {\n const rows = matchingRows();\n if (rows.length === 0) {\n toast("warn", "Nothing to export", "No request in the window matches this filter.");\n return;\n }\n const entries = rows.map((row) => row.entry).reverse();\n download(`${replayFile(entries)}\n`, `bothandler-feed-${today()}.jsonl`, "application/x-ndjson");\n toast("ok", `Exported ${n(entries.length)} request(s)`, "Replay them with `bothandlerjs replay`.");\n });\n }\n function reflectFilterButtons() {\n for (const button of Array.from($("filters").children)) {\n button.setAttribute("aria-pressed", String(button instanceof HTMLElement && button.dataset["filter"] === state.filter));\n }\n const search = byId("search");\n if (search.value !== state.search) search.value = state.search;\n }\n async function loadSkipped() {\n const before = state.rows.length;\n let served;\n try {\n const body = await getJson("/api/feed");\n for (const entry of body.entries) ingest(entry);\n served = body.skipped;\n sortRows();\n } catch {\n toast("bad", "Could not load them", "The dashboard did not answer. The entries are still in the window; try again.");\n return;\n }\n state.caughtUp = (served ?? state.snapshot?.skipped ?? 0) + state.laggedDrops;\n const added = state.rows.length - before;\n resetPaging();\n app.drawNow();\n toast(\n added > 0 ? "ok" : "warn",\n added > 0 ? `Loaded ${n(added)}` : "Nothing left to load",\n added > 0 ? "They are in the feed now, in the order they happened." : "The window no longer holds them; the ring had already rotated past."\n );\n }\n var highlighted = -1;\n function suggestionList() {\n return $("search-suggest");\n }\n function closeSuggestions(input) {\n const list = suggestionList();\n list.hidden = true;\n clear(list);\n highlighted = -1;\n input.setAttribute("aria-expanded", "false");\n }\n function showSuggestions(input) {\n const caret = input.selectionStart ?? input.value.length;\n const { options, from, to } = suggestFor(input.value, caret);\n const list = suggestionList();\n if (options.length === 0 || input.value.slice(from, to) === options[0]) {\n closeSuggestions(input);\n return;\n }\n clear(list);\n highlighted = -1;\n options.slice(0, 12).forEach((option, index) => {\n const item = el("li", null, option);\n item.setAttribute("role", "option");\n item.setAttribute("aria-selected", "false");\n item.addEventListener("mousedown", (event) => {\n event.preventDefault();\n apply(input, option, from, to);\n });\n item.dataset["index"] = String(index);\n list.appendChild(item);\n });\n list.hidden = false;\n input.setAttribute("aria-expanded", "true");\n }\n function apply(input, option, from, to) {\n const before = input.value.slice(0, from);\n const after = input.value.slice(to);\n input.value = `${before}${option}${after}`;\n const caret = before.length + option.length;\n input.setSelectionRange(caret, caret);\n setSearch(input.value.trim());\n app.syncUrl();\n app.drawNow();\n closeSuggestions(input);\n showSuggestions(input);\n input.focus();\n }\n function initSuggestions(input) {\n input.addEventListener("keydown", (event) => {\n const list = suggestionList();\n const items = Array.from(list.querySelectorAll("li"));\n if (list.hidden || items.length === 0) return;\n if (event.key === "Escape") {\n closeSuggestions(input);\n return;\n }\n if (event.key === "ArrowDown" || event.key === "ArrowUp") {\n event.preventDefault();\n highlighted = (highlighted + (event.key === "ArrowDown" ? 1 : items.length - 1) + (highlighted === -1 && event.key === "ArrowUp" ? 1 : 0)) % items.length;\n items.forEach((item, index) => item.setAttribute("aria-selected", String(index === highlighted)));\n return;\n }\n if ((event.key === "Enter" || event.key === "Tab") && highlighted >= 0) {\n const chosen = items[highlighted]?.textContent ?? "";\n const caret = input.selectionStart ?? input.value.length;\n const { from, to } = suggestFor(input.value, caret);\n event.preventDefault();\n apply(input, chosen, from, to);\n }\n });\n input.addEventListener("blur", () => {\n setTimeout(() => closeSuggestions(input), 120);\n });\n input.addEventListener("focus", () => showSuggestions(input));\n }\n function initSavedFilters(input) {\n const host = $("saved-filters");\n const redraw = () => {\n clear(host);\n const entries = savedFilters();\n const select2 = document.createElement("select");\n select2.setAttribute("aria-label", "Saved filters");\n const first = document.createElement("option");\n first.value = "";\n first.textContent = entries.length === 0 ? "No saved filters" : "Saved filters\u2026";\n select2.appendChild(first);\n for (const entry of entries) {\n const option = document.createElement("option");\n option.value = entry.name;\n option.textContent = entry.name;\n select2.appendChild(option);\n }\n select2.addEventListener("change", () => {\n const chosen = entries.find((entry) => entry.name === select2.value);\n if (chosen === void 0) return;\n input.value = chosen.query;\n setSearch(chosen.query);\n state.filter = chosen.filter;\n reflectFilterButtons();\n resetPaging();\n app.syncUrl();\n app.drawNow();\n });\n host.appendChild(select2);\n const save = el("button", null, "Save");\n save.type = "button";\n save.title = "Save this filter, in this browser, under a name";\n save.addEventListener("click", () => {\n const name = prompt("Save this filter as:")?.trim();\n if (name === void 0 || name === "") return;\n saveFilter({ name, query: input.value.trim(), filter: state.filter });\n redraw();\n toast("ok", "Filter saved", `"${name}" is in this browser. It is not shared with anybody else.`);\n });\n host.appendChild(save);\n if (select2.value !== "") {\n const remove = el("button", null, "Delete");\n remove.type = "button";\n remove.addEventListener("click", () => {\n deleteFilter(select2.value);\n redraw();\n });\n host.appendChild(remove);\n }\n };\n redraw();\n }\n function initTimeframe() {\n const from = byId("from-at");\n const to = byId("to-at");\n const clearButton = byId("timeframe-clear");\n const read2 = (input) => {\n if (input.value === "") return void 0;\n const parsed = new Date(input.value).getTime();\n return Number.isFinite(parsed) ? parsed : void 0;\n };\n const apply2 = () => {\n const start2 = read2(from);\n const end = read2(to);\n if (start2 !== void 0 && end !== void 0 && end < start2) {\n toast("warn", "That window runs backwards", "The end is before the start, so nothing can fall inside it.");\n }\n setTimeframe(start2, end);\n clearButton.hidden = start2 === void 0 && end === void 0;\n app.drawNow();\n };\n from.addEventListener("change", apply2);\n to.addEventListener("change", apply2);\n clearButton.addEventListener("click", () => {\n from.value = "";\n to.value = "";\n apply2();\n });\n }\n var FEED_PAGE_SIZES = [25, 50, 100, 200];\n function drawPager(paged) {\n const size = state.feedPageSize;\n const hidden = paged.pages <= 1;\n const model = {\n page: paged.page,\n from: paged.page * size + 1,\n to: Math.min(paged.total, (paged.page + 1) * size),\n total: paged.total,\n atStart: paged.page === 0,\n atEnd: paged.page >= paged.pages - 1,\n ...paged.page > 0 ? { held: "held while you read" } : {},\n go: (page) => {\n goToFeedPage(page);\n app.drawNow();\n },\n size: {\n current: size,\n choices: FEED_PAGE_SIZES,\n set: (next) => {\n state.feedPageSize = next;\n resetPaging();\n app.drawNow();\n }\n }\n };\n for (const [id, withSize] of [\n ["feed-pager-top", true],\n ["feed-pager", false]\n ]) {\n const host = $(id);\n host.hidden = hidden;\n if (hidden) clear(host);\n else renderPager(host, model, { withSize });\n }\n }\n function drawFeed() {\n const body = byId("rows");\n const paged = feedPage(state.feedPageSize);\n const shown = paged.rows;\n let index = 0;\n const place = (node) => {\n const current = body.childNodes[index] ?? null;\n if (current !== node) body.insertBefore(node, current);\n index++;\n };\n for (const row of shown) {\n const id = row.entry.requestId;\n const open = state.open.has(id);\n let cached = rendered.get(id);\n if (cached === void 0 || cached.rev !== row.rev || cached.open !== open) {\n cached = {\n row: buildRow(row.entry, open),\n detail: open ? buildDetail(row.entry) : void 0,\n rev: row.rev,\n open\n };\n rendered.set(id, cached);\n }\n place(cached.row);\n if (cached.detail !== void 0) place(cached.detail);\n }\n while (body.childNodes.length > index) body.removeChild(body.childNodes[index]);\n if (rendered.size > shown.length * 2 + 100) {\n const live = new Set(shown.map((row) => row.entry.requestId));\n for (const id of Array.from(rendered.keys())) if (!live.has(id)) rendered.delete(id);\n }\n const total = state.rows.length;\n const matching = matchingCount();\n $("empty").hidden = total > 0;\n $("feed-count").textContent = matching === total ? `${n(total)} in this window` : `${n(matching)} of ${n(total)}`;\n drawPager(paged);\n const skipped = Math.max(0, (state.snapshot?.skipped ?? 0) + state.laggedDrops - state.caughtUp);\n const note = $("feed-skipped");\n note.hidden = skipped === 0;\n note.textContent = `${n(skipped)} not streamed`;\n byId("feed-load-skipped").hidden = skipped === 0;\n note.title = state.laggedDrops > 0 ? `${n(state.laggedDrops)} were skipped because this connection could not keep up, and the rest by the rate cap. All of them are still in the window, the preview and the export.` : "Entries the rate cap kept off this stream. They are still in the window, the preview and the export \u2014 raise maxEventsPerSecond to see them live.";\n }\n function resetFeedCache() {\n rendered.clear();\n }\n function buildRow(entry, open) {\n const out = outcome(entry);\n const tr = el("tr", `row a-${entry.downgradedFrom !== void 0 ? "guard" : out}${open ? " open" : ""}`);\n tr.appendChild(el("td", "num mono tnum when", clockTime(entry.at)));\n const request = el("td", "edge req");\n const toggle = el("button", "row-toggle", `${entry.method} ${entry.path}`);\n toggle.type = "button";\n toggle.setAttribute("aria-expanded", String(open));\n toggle.setAttribute("aria-label", `${entry.method} ${entry.path}, ${entry.verdict}. Evidence.`);\n toggle.dataset["request"] = entry.requestId;\n request.appendChild(toggle);\n const ua = el("span", "ua");\n if (SECTIONS.actors) {\n const actorLink = el("a", null, entry.actor);\n actorLink.href = "#actor";\n actorLink.title = "Show everything from this actor";\n actorLink.addEventListener("click", (event) => {\n event.preventDefault();\n event.stopPropagation();\n openActor(entry.actor);\n });\n ua.appendChild(actorLink);\n ua.appendChild(document.createTextNode(` \xB7 ${entry.userAgent}`));\n } else {\n ua.appendChild(document.createTextNode(`${entry.actor} \xB7 ${entry.userAgent}`));\n }\n ua.title = `${entry.actor} \xB7 ${entry.userAgent}`;\n request.appendChild(ua);\n tr.appendChild(request);\n const verdictCell = el("td");\n const [badgeClass, badgeLabel] = verdictBadge(entry);\n verdictCell.appendChild(el("span", `badge ${badgeClass}`, badgeLabel));\n if (entry.identity !== void 0) verdictCell.appendChild(el("span", "sub", entry.identity));\n tr.appendChild(verdictCell);\n tr.appendChild(el("td", "num mono tnum", entry.certain ? "proven" : String(entry.score)));\n const actionCell = el("td");\n if (entry.action !== void 0) {\n const kind = out === "deny" ? "act-deny" : out === "mitigate" ? "act-mitigate" : out === "allow" ? "act-allow" : "act-tag";\n actionCell.appendChild(el("span", `act ${kind}`, entry.action));\n if (entry.rule !== void 0) {\n const ruleLabel = el("span", "sub", entry.rule);\n ruleLabel.title = entry.rule;\n actionCell.appendChild(ruleLabel);\n }\n if (entry.downgradedFrom !== void 0) actionCell.appendChild(el("span", "guard", `guard stopped ${entry.downgradedFrom}`));\n } else {\n actionCell.appendChild(el("span", "sub", "assessed only"));\n }\n tr.appendChild(actionCell);\n tr.appendChild(el("td", "num mono tnum", entry.durationMs.toFixed(2)));\n tr.dataset["request"] = entry.requestId;\n const flip = () => {\n if (state.open.has(entry.requestId)) state.open.delete(entry.requestId);\n else state.open.add(entry.requestId);\n app.drawNow();\n rootNode().querySelector(`button.row-toggle[data-request="${cssEscape(entry.requestId)}"]`)?.focus();\n };\n toggle.addEventListener("click", (event) => {\n event.stopPropagation();\n flip();\n });\n tr.addEventListener("click", flip);\n return tr;\n }\n function buildDetail(entry) {\n const tr = el("tr", "detail");\n const cell = el("td");\n cell.colSpan = 6;\n if (!SECTIONS.evidence) {\n cell.appendChild(\n el(\n "div",\n "ev-meta",\n "The evidence section is switched off on this dashboard, so the reasons behind this verdict are not sent to it. What fired, and why, is on a dashboard that has `sections: { evidence: true }`."\n )\n );\n } else if (entry.evidence.length === 0) {\n cell.appendChild(\n el(\n "div",\n "ev-meta",\n entry.bypass !== void 0 ? `Detection was skipped for this request: ${entry.bypass}.` : "No detector produced any evidence. This is what ordinary traffic looks like."\n )\n );\n } else {\n const list = el("div", "ev");\n for (const item of entry.evidence) {\n const row = el("div", `ev-item${item.direction === "human" ? " human" : ""}${item.shadow === true ? " shadow" : ""}`);\n row.appendChild(el("div", `tier t-${item.certainty}`, item.certainty));\n const body = el("div");\n body.appendChild(el("div", null, item.summary));\n let meta = `${item.detector} \xB7 points to ${item.direction}`;\n if (item.family !== void 0) meta += ` \xB7 family \u201C${item.family}\u201D, counted once with its siblings`;\n if (item.shadow === true) meta += " \xB7 shadowed: counted, and part of no decision";\n body.appendChild(el("div", "ev-meta", meta));\n if (item.deterministicBasis !== void 0) body.appendChild(el("div", "basis", item.deterministicBasis));\n row.appendChild(body);\n list.appendChild(row);\n }\n cell.appendChild(list);\n }\n if (entry.shadowVerdict !== void 0) {\n const would = entry.shadowVerdict;\n const changed = would.verdict !== entry.verdict;\n cell.appendChild(\n el(\n "div",\n `ev-meta shadow-verdict${changed ? " changed" : ""}`,\n changed ? `With the shadowed detectors counted, this request would have been ${would.verdict} at ${would.score} instead of ${entry.verdict} at ${entry.score}.` : `With the shadowed detectors counted, this request would still have been ${would.verdict}${would.score === entry.score ? "" : `, at ${would.score} rather than ${entry.score}`}.`\n )\n );\n }\n for (const failure of entry.failures) {\n cell.appendChild(el("div", "ev-meta", `Detector ${failure.detector} ${failure.reason}: ${failure.message}`));\n }\n if (entry.downgradeReason !== void 0) cell.appendChild(el("div", "basis", `Guard: ${entry.downgradeReason}`));\n const queryNames = Object.keys(entry.query);\n if (queryNames.length > 0) {\n const queryTable = el("table", "hdr");\n for (const name of queryNames) {\n const value = entry.query[name] ?? "";\n const row = el("tr");\n row.appendChild(el("td", "n", `?${name}`));\n row.appendChild(el("td", `v${value === "[redacted]" ? " red" : ""}`, value));\n queryTable.appendChild(row);\n }\n cell.appendChild(queryTable);\n }\n if (entry.headers !== void 0 && entry.headers.length > 0) {\n const table = el("table", "hdr");\n for (const [name, value] of entry.headers) {\n const row = el("tr");\n row.appendChild(el("td", "n", `${name}:`));\n row.appendChild(el("td", `v${value === "[redacted]" ? " red" : ""}`, value));\n table.appendChild(row);\n }\n cell.appendChild(table);\n }\n const tools = el("div", "tools");\n if (SECTIONS.evidence) {\n tools.appendChild(copyButton("Copy replay line", () => replayLine(entry)));\n tools.appendChild(downloadButton("Download replay line", () => replayLine(entry), `request-${entry.requestId}.jsonl`));\n tools.appendChild(copyButton("Copy corpus case", () => corpusCase(entry)));\n }\n if (SECTIONS.policy) {\n const draft2 = el("button", null, "Draft a rule");\n draft2.title = "Start a rule from this request, in the policy editor";\n draft2.addEventListener("click", (event) => {\n event.stopPropagation();\n void draftIntoEditor(entry);\n });\n tools.appendChild(draft2);\n }\n if (SECTIONS.actors) {\n const actorButton = el("button", null, "Show this actor");\n actorButton.addEventListener("click", (event) => {\n event.stopPropagation();\n openActor(entry.actor);\n });\n tools.appendChild(actorButton);\n }\n cell.appendChild(tools);\n const foot = el("div", "detail-foot");\n foot.appendChild(el("span", null, clockTime(entry.at)));\n foot.appendChild(el("span", null, `actor ${entry.actor}`));\n if (entry.rule !== void 0) foot.appendChild(el("span", null, `rule \u201C${entry.rule}\u201D`));\n foot.appendChild(el("span", null, `assessed in ${entry.durationMs.toFixed(3)}ms`));\n foot.appendChild(el("span", "mono", entry.requestId));\n cell.appendChild(foot);\n tr.appendChild(cell);\n return tr;\n }\n function copyButton(label2, produce) {\n const button = el("button", null, label2);\n button.addEventListener("click", (event) => {\n event.stopPropagation();\n const text = produce();\n const done = () => {\n button.textContent = "Copied";\n setTimeout(() => {\n button.textContent = label2;\n }, 1200);\n };\n if (navigator.clipboard?.writeText !== void 0) navigator.clipboard.writeText(text).then(done, () => showText(text));\n else showText(text);\n });\n return button;\n }\n function downloadButton(label2, produce, filename) {\n const button = el("button", null, label2);\n button.addEventListener("click", (event) => {\n event.stopPropagation();\n download(`${produce()}\n`, filename, "application/x-ndjson");\n });\n return button;\n }\n function showText(text) {\n const box = el("pre", "code", text);\n const host = $("policy-result");\n host.hidden = false;\n host.className = "result";\n clear(host);\n host.appendChild(el("div", "ev-meta", "Copying needs a secure context; here is the text."));\n host.appendChild(box);\n const selection = getSelection();\n if (selection !== null) {\n const range = document.createRange();\n range.selectNodeContents(box);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n\n // src/dashboard/client/stream.ts\n var source;\n function connectStream() {\n if (!SECTIONS.feed) {\n $("dot").className = "dot";\n $("conn").textContent = "feed off";\n return;\n }\n if (source !== void 0) return;\n source = new EventSource(`${API}/api/stream`);\n source.addEventListener("open", () => {\n $("dot").className = "dot on";\n $("conn").textContent = "live";\n });\n source.addEventListener("sync", (event) => {\n const detail = JSON.parse(event.data);\n if (!detail.replace) return;\n clearFeed();\n resetFeedCache();\n });\n source.addEventListener("entry", (event) => {\n ingest(JSON.parse(event.data));\n if (state.paused) {\n state.bufferedWhilePaused++;\n $("pause").textContent = `Resume (${state.bufferedWhilePaused})`;\n }\n app.draw();\n });\n source.addEventListener("update", (event) => {\n ingest(JSON.parse(event.data));\n app.draw();\n });\n source.addEventListener("reset", () => {\n clearFeed();\n resetFeedCache();\n app.draw();\n });\n source.addEventListener("lagged", (event) => {\n const detail = JSON.parse(event.data);\n state.laggedDrops += detail.dropped;\n app.draw();\n });\n source.addEventListener("stats", (event) => {\n state.snapshot = JSON.parse(event.data);\n app.draw();\n });\n source.addEventListener("error", () => {\n $("dot").className = "dot off";\n $("conn").textContent = "reconnecting\u2026";\n });\n }\n async function loadInitialSnapshot() {\n try {\n state.snapshot = await getJson("/api/stats");\n app.drawNow();\n } catch {\n }\n }\n\n // src/dashboard/client/panels.ts\n var paintedSnapshot;\n function drawTiles(force = false) {\n if (!SECTIONS.statistics) return;\n const box = $("tiles");\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n if (!force && paintedSnapshot === snapshot) return;\n paintedSnapshot = snapshot;\n const metrics = snapshot.metrics;\n clear(box);\n if (metrics === void 0) {\n box.appendChild(el("div", "note", "Counters are switched off on this handler (metrics: false). The live feed still works."));\n return;\n }\n const actions = metrics.actions;\n const denied = actions.block + actions.drop + actions.redirect;\n const mitigated = actions.challenge + actions["rate-limit"] + actions.delay;\n const served = actions.allow + actions.tag + actions.log;\n const total = metrics.requests;\n const unremarkable = metrics.verdicts.unknown + metrics.verdicts.human;\n const provenBotCount = provenBots(metrics.verdicts);\n const actors = SECTIONS.registry ? { tab: "actors", label: "Actors" } : void 0;\n const tiles = [\n ["", n(total), "Requests", "since start", void 0],\n ["proven", n(provenBotCount), "Proven bots", `${pct(provenBotCount, total)} of traffic`, void 0],\n ["warn", n(metrics.verdicts["suspected-bot"]), "Suspected", "never denied alone", void 0],\n ["", n(unremarkable), "Unremarkable", `${pct(unremarkable, total)} of traffic`, void 0],\n ["warn", n(metrics.downgrades), "Guard stops", metrics.downgrades > 0 ? "a rule over-reached" : "no rule overreached", void 0],\n ["crit", n(denied), "Denied", `${pct(denied, total)} of traffic`, void 0],\n [\n "",\n n(mitigated),\n "Mitigated",\n metrics.challenges.issued > 0 ? `${n(metrics.challenges.solved)} of ${n(metrics.challenges.issued)} challenges solved` : "challenged or limited",\n void 0\n ],\n ["good", n(served), "Served", `${pct(served, total)} of traffic`, void 0],\n ["", n(metrics.actorsTracked), "Actors tracked", "in the registry now", actors]\n ];\n for (const [kind, value, key, sub, goes] of tiles) {\n const tile = goes === void 0 ? el("div", `tile ${kind}`) : el("button", `tile ${kind} go`);\n tile.appendChild(el("div", "v tnum", value));\n tile.appendChild(el("div", "k", key));\n tile.appendChild(el("div", "s", sub));\n if (goes !== void 0) {\n tile.type = "button";\n tile.appendChild(el("span", "sr-only", `. Show the ${goes.label} screen`));\n tile.addEventListener("click", () => app.showTab(goes.tab, { replace: false }));\n }\n box.appendChild(tile);\n }\n }\n function drawChips() {\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const box = $("chips");\n clear(box);\n const facts = [\n // Which process this is, first, because everything after it is a fact about this\n // process and nothing else. Behind a load balancer there are as many of these\n // dashboards as there are pods, each showing its own share of the traffic.\n ["instance", snapshot.instance],\n ["guard", snapshot.policy.falsePositivePolicy],\n ["suspect at", String(snapshot.policy.suspectThreshold)]\n ];\n if (SECTIONS.statistics) facts.push(["detectors", String(snapshot.detectors.length)]);\n if (SECTIONS.policy) facts.push(["rules", String(snapshot.rules.length)]);\n facts.push(["uptime", uptime(snapshot.now - snapshot.startedAt)]);\n for (const [label2, value] of facts) {\n const fact = el("span");\n fact.appendChild(document.createTextNode(`${label2} `));\n fact.appendChild(el("b", null, value));\n box.appendChild(fact);\n }\n }\n function updateWindowLabels() {\n const label2 = windowLabel(state.rows.length, oldestAt(), Date.now());\n for (const node of Array.from(rootNode().querySelectorAll(".win"))) node.textContent = label2;\n }\n function drawLivePanels() {\n if (!SECTIONS.statistics) return;\n const totals = aggregate(state.rows);\n drawBars($("live-detectors"), totals.detectors, "Nothing has fired in this window.");\n if (SECTIONS.actors) drawBars($("live-actors"), totals.actors, "No traffic in this window.");\n }\n function drawStatsPanels() {\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const metrics = snapshot.metrics;\n if (metrics !== void 0) {\n drawBars($("stat-verdicts"), pairs(metrics.verdicts), "Nothing assessed yet.");\n drawBars($("stat-actions"), pairs(metrics.actions), "No decisions yet.");\n drawBars($("stat-classes"), pairs(metrics.botClasses), "Nothing classified yet.");\n drawBars($("stat-detectors"), pairs(metrics.detectorFirings), "No detector has produced evidence yet.");\n const challenges = $("stat-challenges");\n clear(challenges);\n if (!snapshot.policy.challengeEnabled) {\n challenges.appendChild(el("div", "note", "No challenge is configured, so a rule asking for one degrades to a tag. Set challenge.secrets to enable it."));\n } else {\n const funnel = [\n ["Issued", n(metrics.challenges.issued)],\n ["Solved", n(metrics.challenges.solved)],\n ["Rejected", n(metrics.challenges.rejected)],\n ["Solve rate", metrics.challenges.issued > 0 ? pct(metrics.challenges.solved, metrics.challenges.issued) : "\u2014"]\n ];\n for (const [key, value] of funnel) challenges.appendChild(statRow(key, value));\n }\n const health = $("stat-health");\n clear(health);\n const bypassed = metrics.bypassed.allowlist + metrics.bypassed["ignored-path"];\n const rows = [\n ["Requests assessed", n(metrics.requests)],\n ["Bypassed \u2014 allowlist", n(metrics.bypassed.allowlist)],\n ["Bypassed \u2014 ignored path", n(metrics.bypassed["ignored-path"])],\n ["Detection ran on", pct(metrics.requests - bypassed, metrics.requests)],\n ["Actors tracked", n(metrics.actorsTracked)],\n ["Guard stops", n(metrics.downgrades)]\n ];\n const shadowed = pairs(metrics.shadowFirings);\n if (shadowed.length > 0) {\n const moved = Object.entries(metrics.shadowChanges).filter(([, count]) => count > 0);\n rows.push(["Shadowed findings", n(shadowed.reduce((total, [, count]) => total + count, 0))]);\n for (const [verdict, count] of moved) rows.push([`Would have become ${verdict}`, n(count)]);\n if (moved.length === 0) rows.push(["Verdicts they would have changed", "none"]);\n }\n const failures = pairs(metrics.detectorFailures);\n for (const [detector, count] of failures) rows.push([`Detector failures \u2014 ${detector}`, n(count)]);\n for (const [key, value] of rows) health.appendChild(statRow(key, value));\n if (failures.length === 0) health.appendChild(el("div", "note", "No detector has thrown or timed out."));\n }\n const totals = aggregate(state.rows);\n if (SECTIONS.actors) drawBars($("stat-identities"), totals.identities, "No client has named itself in this window.");\n drawBars($("stat-paths"), totals.paths, "No traffic in this window.");\n drawBars($("stat-denied-paths"), totals.deniedPaths, "Nothing has been denied in this window.");\n drawBars($("stat-guard"), totals.guardStops, "No rule has asked for more than its evidence supports.");\n drawBars($("stat-bypassed"), totals.bypassed, "Nothing bypassed detection.");\n drawRuleHits(totals);\n const list = $("stat-detector-list");\n clear(list);\n $("detector-count").textContent = `${snapshot.detectors.length} installed`;\n for (const detector of snapshot.detectors) {\n const row = el("div", `det${detector.shadow === true ? " shadow" : ""}`);\n const left = el("div");\n left.appendChild(el("div", "mono", detector.id));\n left.appendChild(el("div", "d", detector.description));\n row.appendChild(left);\n const fires = (detector.shadow === true ? metrics?.shadowFirings[detector.id] : metrics?.detectorFirings[detector.id]) ?? 0;\n const timing = metrics?.detectorTimings[detector.id];\n let right = `${n(fires)}${detector.shadow === true ? " shadowed" : ""} \xB7 ${detector.cost} \xB7 ${detector.stage}`;\n if (timing !== void 0 && timing.count > 0) right += ` \xB7 ${ms(timing.totalMs / timing.count)} avg`;\n row.appendChild(el("div", "n", right));\n list.appendChild(row);\n }\n }\n function statRow(key, value) {\n const line = el("div", "stat-row");\n line.appendChild(el("span", "k", key));\n line.appendChild(el("span", "v", value));\n return line;\n }\n function drawRuleHits(totals) {\n const target = $("stat-rule-hits");\n clear(target);\n const rules = state.snapshot?.rules ?? [];\n if (rules.length === 0) {\n target.appendChild(el("div", "note", "No rules configured."));\n return;\n }\n let max = 1;\n for (const rule of rules) max = Math.max(max, totals.ruleHits.get(rule) ?? 0);\n for (const rule of rules) {\n const value = totals.ruleHits.get(rule) ?? 0;\n const bar = el("div", `bar${value === 0 ? " dead" : ""}`);\n const track = el("div", "track");\n if (value > 0) {\n const fill = el("div", "fill");\n fill.style.width = `${Math.max(2, Math.round(value / max * 100))}%`;\n track.appendChild(fill);\n }\n track.appendChild(el("div", "lbl", rule));\n bar.appendChild(track);\n bar.appendChild(el("div", "v tnum", value === 0 ? "never" : n(value)));\n target.appendChild(bar);\n }\n }\n function drawAudit() {\n const snapshot = state.snapshot;\n if (snapshot === void 0) return;\n const body = $("audit-body");\n const checks = $("audit-checks");\n clear(body);\n clear(checks);\n const audit = snapshot.audit;\n if (audit === void 0) {\n $("audit-spans").textContent = "";\n body.appendChild(\n el(\n "div",\n "note",\n "The traffic audit is switched off on this handler (audit: false). It watches the shape of your traffic rather than any one request \u2014 a spike in automation, a collapse in human traffic, a policy suddenly denying far more than usual."\n )\n );\n return;\n }\n const current = audit.window;\n const baseline = audit.baseline;\n $("audit-spans").textContent = `last ${rangeLabel(current.spanMs)} against the ${rangeLabel(baseline.spanMs)} before`;\n const rows = [\n ["Requests", n(current.requests), n(baseline.requests)],\n ["Rate", `${current.rate.toFixed(1)}/min`, `${baseline.rate.toFixed(1)}/min`],\n ["Bot share", `${Math.round(current.botShare * 100)}%`, `${Math.round(baseline.botShare * 100)}%`],\n ["Bots", n(current.bots), n(baseline.bots)],\n ["Humans", n(current.humans), n(baseline.humans)],\n ["Denials", n(current.denials), n(baseline.denials)],\n ["Challenges", n(current.challenges), n(baseline.challenges)],\n ["Guard stops", n(current.downgrades), n(baseline.downgrades)],\n ["Detector failures", n(current.failures), n(baseline.failures)],\n ["Bypassed", n(current.bypassed), n(baseline.bypassed)]\n ];\n for (const [key, now, was] of rows) {\n const line = el("div", "stat-row");\n line.appendChild(el("span", "k", key));\n const values = el("span", "v");\n values.appendChild(el("b", null, now));\n values.appendChild(el("span", "was", ` was ${was}`));\n line.appendChild(values);\n body.appendChild(line);\n }\n if (audit.checks.length === 0) {\n checks.appendChild(el("div", "note", "No checks are installed, so nothing here will ever raise an anomaly."));\n return;\n }\n for (const check of audit.checks) {\n const row = el("div", "det");\n const left = el("div");\n left.appendChild(el("div", "mono", check.id));\n left.appendChild(el("div", "d", check.description));\n row.appendChild(left);\n checks.appendChild(row);\n }\n }\n function drawNoticeBadge() {\n const notices = state.snapshot?.notices ?? [];\n const badge = $("notice-badge");\n badge.hidden = notices.length === 0 || !SECTIONS.notices;\n badge.textContent = String(notices.length);\n }\n function drawNotices() {\n const box = $("stat-notices");\n const notices = state.snapshot?.notices ?? [];\n clear(box);\n $("notice-count").textContent = notices.length > 0 ? `${notices.length} total` : "";\n if (notices.length === 0) {\n box.appendChild(el("div", "note", "Nothing to report: no startup warnings, no detector errors."));\n return;\n }\n for (const notice of notices.slice().reverse().slice(0, 40)) {\n const row = el("div", `notice ${notice.kind}`);\n const when = el("div", "when");\n when.appendChild(el("div", "tag", notice.kind));\n when.appendChild(el("div", null, clockTime(notice.at)));\n row.appendChild(when);\n const body = el("div");\n body.appendChild(el("div", null, notice.message));\n if (notice.source !== void 0) body.appendChild(el("div", "ev-meta", notice.source));\n row.appendChild(body);\n box.appendChild(row);\n }\n }\n function drawChanges() {\n if (!SECTIONS.changes) return;\n const box = $("stat-changes");\n const changes = state.snapshot?.changes ?? [];\n clear(box);\n $("change-count").textContent = changes.length > 0 ? `${changes.length} this run` : "";\n if (changes.length === 0) {\n box.appendChild(el("div", "note", "Nothing has been changed at runtime. Rules, guard and ranges are as the code that built this handler left them."));\n return;\n }\n for (const change of changes.slice().reverse()) {\n const row = el("div", "notice");\n const when = el("div", "when");\n when.appendChild(el("div", "tag", change.kind));\n when.appendChild(el("div", null, clockTime(change.at)));\n row.appendChild(when);\n const body = el("div");\n body.appendChild(el("div", null, change.summary));\n body.appendChild(el("div", "ev-meta", change.by === void 0 || change.by === "" ? "by an unnamed viewer \u2014 this listener\'s auth carries no identity" : `by ${change.by}`));\n row.appendChild(body);\n box.appendChild(row);\n }\n }\n function drawPeers() {\n const box = $("peers");\n if (BOOT.peers.length === 0) {\n box.hidden = true;\n return;\n }\n if (box.childElementCount > 0) return;\n box.appendChild(el("span", "hint", "also:"));\n for (const peer of BOOT.peers) {\n const link = el("a", "linkbtn", peer.label);\n link.href = peer.href;\n link.rel = "noreferrer noopener";\n box.appendChild(link);\n }\n }\n\n // src/dashboard/client/charts.ts\n var BUCKETS = 60;\n var LATENCY_BOUNDS = [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 25, 50, 100];\n var SCORE_BOUNDS = 10;\n function positionTip(tip, host, clientX, boxLeft) {\n tip.style.opacity = "1";\n tip.style.left = `${Math.min(host.clientWidth - 150, Math.max(4, clientX - boxLeft - 60))}px`;\n tip.style.top = "14px";\n }\n function tipRow(label2, value, colour) {\n const line = el("div", "r");\n const left = el("em");\n if (colour !== void 0) {\n const swatch = el("span", "swatch");\n swatch.style.background = colour;\n left.appendChild(swatch);\n }\n left.appendChild(document.createTextNode(label2));\n line.appendChild(left);\n line.appendChild(el("b", null, value));\n return line;\n }\n function timeline() {\n const bucketMs = state.rangeMs / BUCKETS;\n const now = Date.now();\n const start2 = now - state.rangeMs;\n const buckets = [];\n for (let i = 0; i < BUCKETS; i++) buckets.push({ at: start2 + i * bucketMs, served: 0, mitigated: 0, denied: 0, total: 0 });\n for (const { entry } of state.rows) {\n const index = Math.floor((entry.at - start2) / bucketMs);\n if (index < 0 || index >= BUCKETS) continue;\n const bucket = buckets[index];\n if (bucket === void 0) continue;\n bucket.total++;\n const out = outcome(entry);\n if (out === "deny") bucket.denied++;\n else if (out === "mitigate") bucket.mitigated++;\n else bucket.served++;\n }\n return buckets;\n }\n function drawTraffic() {\n const host = $("traffic-chart");\n const svg = $("traffic");\n const width = Math.max(320, host.clientWidth - 30);\n const height = 190;\n const padBottom = 26;\n const markerRow = 8;\n const plot = height - padBottom - markerRow;\n const buckets = timeline();\n const now = Date.now();\n const start2 = now - state.rangeMs;\n let peak = 1;\n for (const bucket of buckets) if (bucket.total > peak) peak = bucket.total;\n const max = Math.max(2, Math.ceil(peak / 2) * 2);\n clear(svg);\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n svg.setAttribute("height", String(height));\n const s1 = css("--s1");\n const s2 = css("--s2");\n const crit = css("--crit");\n const grid = css("--grid");\n const muted = css("--muted");\n const step = width / BUCKETS;\n const barWidth = Math.max(2, step - 2);\n for (const fraction of [0, 0.5, 1]) {\n const y = markerRow + plot - fraction * plot;\n svg.appendChild(svgEl("line", { class: "gridline", x1: 0, x2: width, y1: y, y2: y, stroke: grid, "stroke-width": 1 }));\n if (fraction > 0) svg.appendChild(svgText({ x: 2, y: y - 3, fill: muted, "font-size": 10 }, Math.round(max * fraction)));\n }\n buckets.forEach((bucket, index) => {\n const x = index * step + 1;\n const servedHeight = bucket.served / max * plot;\n const mitigatedHeight = bucket.mitigated / max * plot;\n let y = markerRow + plot;\n if (servedHeight > 0) {\n y -= servedHeight;\n svg.appendChild(svgEl("rect", { x, y, width: barWidth, height: servedHeight, fill: s1, rx: 2 }));\n }\n if (mitigatedHeight > 0) {\n y -= mitigatedHeight + (servedHeight > 0 ? 2 : 0);\n svg.appendChild(svgEl("rect", { x, y: Math.max(markerRow, y), width: barWidth, height: mitigatedHeight, fill: s2, rx: 2 }));\n }\n if (bucket.denied > 0) svg.appendChild(svgEl("rect", { x, y: 0, width: barWidth, height: 5, fill: crit, rx: 2 }));\n });\n svg.appendChild(svgEl("line", { x1: 0, x2: width, y1: markerRow + plot, y2: markerRow + plot, stroke: css("--line"), "stroke-width": 1 }));\n const span = rangeLabel(state.rangeMs);\n const labels = [\n [0, `${span} ago`],\n [BUCKETS / 2, rangeLabel(state.rangeMs / 2)],\n [BUCKETS - 1, "now"]\n ];\n for (const [position, text] of labels) {\n svg.appendChild(svgText({ x: Math.min(width - 26, Math.max(0, position * step)), y: height - 8, fill: muted, "font-size": 10 }, text));\n }\n const changes = (state.snapshot?.changes ?? []).filter((change) => change.at >= start2 && change.at <= now);\n const markColour = css("--proven-text");\n for (const change of changes) {\n const x = (change.at - start2) / state.rangeMs * width;\n svg.appendChild(svgEl("line", { x1: x, x2: x, y1: 0, y2: markerRow + plot, stroke: markColour, "stroke-width": 1.5, "stroke-dasharray": "3 2", opacity: 0.85 }));\n const dot = svgEl("circle", { cx: x, cy: 3, r: 3, fill: markColour });\n const title = svgEl("title");\n title.textContent = `${clockTime(change.at)} \xB7 ${change.kind}: ${change.summary}${change.by === void 0 ? "" : ` (by ${change.by})`}`;\n dot.appendChild(title);\n svg.appendChild(dot);\n }\n const hover = svgEl("rect", { x: 0, y: 0, width: 0, height: markerRow + plot, fill: css("--ink"), opacity: 0.06 });\n svg.appendChild(hover);\n const tip = $("traffic-tip");\n host.onmousemove = (event) => {\n const box = svg.getBoundingClientRect();\n const index = Math.floor((event.clientX - box.left) / box.width * BUCKETS);\n const bucket = buckets[index];\n if (bucket === void 0) {\n tip.style.opacity = "0";\n hover.setAttribute("width", "0");\n return;\n }\n hover.setAttribute("x", String(index * step));\n hover.setAttribute("width", String(step));\n clear(tip);\n tip.appendChild(el("div", "t", `${clockTime(bucket.at)} \xB7 ${Math.round(state.rangeMs / BUCKETS / 1e3)}s`));\n tip.appendChild(tipRow("Served", n(bucket.served), s1));\n tip.appendChild(tipRow("Mitigated", n(bucket.mitigated), s2));\n tip.appendChild(tipRow("Denied", n(bucket.denied), crit));\n positionTip(tip, host, event.clientX, box.left);\n };\n host.onmouseleave = () => {\n tip.style.opacity = "0";\n hover.setAttribute("width", "0");\n };\n const total = buckets.reduce((sum, bucket) => sum + bucket.total, 0);\n $("traffic-window").textContent = `last ${rangeLabel(state.rangeMs)}`;\n const served = buckets.reduce((sum, bucket) => sum + bucket.served, 0);\n const mitigated = buckets.reduce((sum, bucket) => sum + bucket.mitigated, 0);\n const denied = buckets.reduce((sum, bucket) => sum + bucket.denied, 0);\n const busiest = buckets.reduce((best, bucket) => bucket.total > best.total ? bucket : best, buckets[0] ?? { at: now, total: 0, served: 0, mitigated: 0, denied: 0 });\n $("traffic-alt").textContent = `Traffic over the last ${rangeLabel(state.rangeMs)}: ${n(total)} requests \u2014 ${n(served)} served, ${n(mitigated)} mitigated, ${n(denied)} denied. ` + (total === 0 ? "No traffic in this range." : `Busiest ${Math.round(state.rangeMs / BUCKETS / 1e3)}-second interval: ${n(busiest.total)} requests at ${clockTime(busiest.at)}.`) + (changes.length === 0 ? "" : ` ${n(changes.length)} runtime change${changes.length === 1 ? "" : "s"} in this range: ${changes.map((change) => `${change.kind}, ${change.summary}`).join("; ")}.`);\n const legend = $("traffic-legend");\n clear(legend);\n legend.appendChild(el("span", null, `${n(total)} requests in the last ${rangeLabel(state.rangeMs)} \xB7`));\n const oldest = oldestAt();\n if (oldest !== void 0 && Date.now() - oldest < state.rangeMs * 0.9) {\n legend.appendChild(el("span", null, `window holds ${rangeLabel(Date.now() - oldest)} \xB7`));\n }\n for (const [label2, colour] of [\n ["Served", s1],\n ["Mitigated \u2014 challenged, limited or delayed", s2],\n ["Denied", crit]\n ]) {\n const item = el("span");\n const swatch = el("span", "swatch");\n swatch.style.background = colour;\n item.appendChild(swatch);\n item.appendChild(document.createTextNode(label2));\n legend.appendChild(item);\n }\n if (changes.length > 0) {\n const item = el("span");\n item.appendChild(el("span", "mark"));\n item.appendChild(document.createTextNode(`${n(changes.length)} runtime change${changes.length === 1 ? "" : "s"} \u2014 hover a marker`));\n legend.appendChild(item);\n }\n }\n function differences(cumulative) {\n const counts = [];\n for (let i = 0; i < cumulative.length; i++) counts.push((cumulative[i] ?? 0) - (i > 0 ? cumulative[i - 1] ?? 0 : 0));\n return counts;\n }\n function drawScores() {\n const host = $("score-chart");\n const svg = $("scores");\n clear(svg);\n const metrics = state.snapshot?.metrics;\n const fromRun = state.scoreScope === "run" && metrics !== void 0;\n let buckets;\n let scored;\n let proven;\n if (fromRun && metrics !== void 0) {\n buckets = differences(metrics.scores.buckets);\n scored = metrics.scores.count;\n proven = metrics.proven;\n } else {\n buckets = new Array(SCORE_BOUNDS).fill(0);\n scored = 0;\n proven = 0;\n for (const { entry } of state.rows) {\n if (entry.bypass !== void 0) continue;\n if (entry.certain) {\n proven++;\n continue;\n }\n const index = Math.min(SCORE_BOUNDS - 1, Math.floor(entry.score / 10));\n buckets[index] = (buckets[index] ?? 0) + 1;\n scored++;\n }\n }\n const width = Math.max(280, host.clientWidth - 30);\n const height = 190;\n const padBottom = 30;\n const plot = height - padBottom;\n let max = 1;\n for (const value of buckets) if (value > max) max = value;\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n svg.setAttribute("height", String(height));\n const fill = css("--s1");\n const muted = css("--muted");\n const grid = css("--grid");\n const crit = css("--crit");\n svg.appendChild(svgEl("line", { class: "gridline", x1: 0, x2: width, y1: plot, y2: plot, stroke: grid, "stroke-width": 1 }));\n const step = width / SCORE_BOUNDS;\n buckets.forEach((value, index) => {\n const barHeight = value / max * (plot - 8);\n const barWidth = Math.max(2, Math.min(step - 6, 56));\n if (barHeight > 0) {\n svg.appendChild(svgEl("rect", { x: index * step + (step - barWidth) / 2, y: plot - barHeight, width: barWidth, height: barHeight, fill, rx: 3 }));\n }\n svg.appendChild(svgText({ x: index * step + 1, y: height - 14, fill: muted, "font-size": 9.5 }, index * 10));\n });\n const threshold = state.snapshot?.policy.suspectThreshold ?? 60;\n const x = threshold / 100 * width;\n svg.appendChild(svgEl("line", { x1: x, x2: x, y1: 0, y2: plot, stroke: crit, "stroke-width": 2, "stroke-dasharray": "4 3" }));\n svg.appendChild(svgText({ x: Math.min(width - 92, x + 5), y: 11, fill: crit, "font-size": 10 }, `suspect at ${threshold}`));\n svg.appendChild(svgText({ x: 0, y: height - 2, fill: muted, "font-size": 10 }, "score (probabilistic requests only)"));\n const tip = $("score-tip");\n host.onmousemove = (event) => {\n const box = svg.getBoundingClientRect();\n const index = Math.floor((event.clientX - box.left) / box.width * SCORE_BOUNDS);\n const value = buckets[index];\n if (value === void 0) {\n tip.style.opacity = "0";\n return;\n }\n clear(tip);\n tip.appendChild(el("div", "t", `score ${index * 10}\u2013${index * 10 + 9}`));\n tip.appendChild(tipRow("requests", n(value)));\n tip.appendChild(tipRow("share", pct(value, scored)));\n positionTip(tip, host, event.clientX, box.left);\n };\n host.onmouseleave = () => {\n tip.style.opacity = "0";\n };\n let over = 0;\n for (let bucket = 0; bucket < SCORE_BOUNDS; bucket++) if (bucket * 10 >= threshold) over += buckets[bucket] ?? 0;\n const legend = $("score-legend");\n clear(legend);\n legend.appendChild(el("span", null, `${n(scored)} scored \xB7 ${n(over)} at or over the threshold \xB7 ${n(proven)} proven, which carry no score`));\n $("score-alt").textContent = `Distribution of probabilistic scores ${fromRun ? "since start" : "in the retained window"}, with the suspect threshold at ${threshold}. ${n(scored)} scored requests, ${n(over)} at or over the threshold, ${n(proven)} proven and therefore unscored. ` + (scored === 0 ? "Nothing scored yet." : `By ten-point band: ${buckets.map((value, index) => `${index * 10}\u2013${index * 10 + 9}: ${n(value)}`).join(", ")}.`);\n $("score-window").textContent = fromRun ? "since start" : windowLabel(state.rows.length, oldestAt(), Date.now());\n if (state.scoreScope === "run" && metrics === void 0) {\n legend.appendChild(el("span", null, "\xB7 counters are off on this handler, so this is the retained window"));\n }\n }\n function drawLatency() {\n const host = $("latency-chart");\n const svg = $("latency");\n clear(svg);\n const metrics = state.snapshot?.metrics;\n if (metrics === void 0 || metrics.duration.count === 0) {\n $("latency-summary").textContent = "No assessments yet.";\n $("latency-alt").textContent = "Assessment latency: no assessments yet.";\n svg.setAttribute("viewBox", "0 0 100 40");\n svg.setAttribute("height", "40");\n svg.appendChild(svgText({ x: 0, y: 20, fill: css("--muted"), "font-size": 11 }, "No assessments yet."));\n return;\n }\n const cumulative = metrics.duration.buckets;\n const counts = differences(cumulative);\n const width = Math.max(280, host.clientWidth - 30);\n const height = 190;\n const padBottom = 30;\n const plot = height - padBottom;\n let max = 1;\n for (const value of counts) if (value > max) max = value;\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n svg.setAttribute("height", String(height));\n const fill = css("--s1");\n const muted = css("--muted");\n const grid = css("--grid");\n svg.appendChild(svgEl("line", { class: "gridline", x1: 0, x2: width, y1: plot, y2: plot, stroke: grid, "stroke-width": 1 }));\n const step = width / counts.length;\n counts.forEach((value, index) => {\n const barHeight = value / max * (plot - 6);\n if (barHeight > 0) {\n svg.appendChild(svgEl("rect", { x: index * step + 1, y: plot - barHeight, width: Math.max(2, step - 3), height: barHeight, fill, rx: 3 }));\n }\n if (index % 2 === 0) {\n svg.appendChild(svgText({ x: index * step + 1, y: height - 14, fill: muted, "font-size": 9.5 }, index < LATENCY_BOUNDS.length ? String(LATENCY_BOUNDS[index]) : "more"));\n }\n });\n svg.appendChild(svgText({ x: 0, y: height - 2, fill: muted, "font-size": 10 }, "milliseconds (upper bound of each bucket)"));\n const tip = $("latency-tip");\n host.onmousemove = (event) => {\n const box = svg.getBoundingClientRect();\n const index = Math.floor((event.clientX - box.left) / box.width * counts.length);\n const value = counts[index];\n if (value === void 0) {\n tip.style.opacity = "0";\n return;\n }\n clear(tip);\n tip.appendChild(el("div", "t", index < LATENCY_BOUNDS.length ? `\u2264 ${LATENCY_BOUNDS[index]}ms` : "over 100ms"));\n tip.appendChild(tipRow("requests", n(value)));\n tip.appendChild(tipRow("share", pct(value, metrics.duration.count)));\n positionTip(tip, host, event.clientX, box.left);\n };\n host.onmouseleave = () => {\n tip.style.opacity = "0";\n };\n const mean = metrics.duration.totalMs / metrics.duration.count;\n const p95 = percentile(cumulative, metrics.duration.count, 0.95);\n $("latency-summary").textContent = `Time spent in detection, per request \xB7 mean ${ms(mean)} \xB7 p95 ${ms(p95)} \xB7 max ${ms(metrics.duration.maxMs)}`;\n $("latency-alt").textContent = `Assessment latency since start over ${n(metrics.duration.count)} requests: mean ${ms(mean)}, 95th percentile ${ms(p95)}, maximum ${ms(metrics.duration.maxMs)}. By bucket: ${counts.map((value, index) => `${index < LATENCY_BOUNDS.length ? `up to ${LATENCY_BOUNDS[index]}ms` : "over 100ms"}: ${n(value)}`).join(", ")}.`;\n }\n function percentile(cumulative, count, fraction) {\n const target = count * fraction;\n const last = LATENCY_BOUNDS[LATENCY_BOUNDS.length - 1] ?? 100;\n for (let i = 0; i < cumulative.length; i++) {\n if ((cumulative[i] ?? 0) >= target) return i < LATENCY_BOUNDS.length ? LATENCY_BOUNDS[i] ?? last : last;\n }\n return last;\n }\n\n // src/dashboard/client/registry.ts\n var timer;\n async function loadActors() {\n if (!SECTIONS.registry) return;\n try {\n const body = await getJson(`/api/actors?limit=${state.actorsPageSize}&offset=${state.actorsPage * state.actorsPageSize}`);\n state.actors = body.actors;\n state.actorsTracked = body.tracked;\n drawActors();\n } catch {\n }\n }\n function trackActors() {\n if (timer !== void 0) clearInterval(timer);\n timer = void 0;\n if (state.tab !== "actors") return;\n void loadActors();\n timer = setInterval(() => {\n if (state.tab !== "actors" || state.paused || isConfirming()) return;\n if (state.actorScope === "feed") return;\n void loadActors();\n }, 4e3);\n }\n var ACTORS_PAGE_SIZES = [25, 50, 100, 200];\n function drawActorsPager(full) {\n const page = state.actorsPage;\n const hidden = page === 0 && !full;\n const from = page * state.actorsPageSize + 1;\n const model = {\n page,\n from,\n to: from + state.actors.length - 1,\n total: state.actorsTracked,\n atStart: page === 0,\n atEnd: !full,\n go: (next) => {\n state.actorsPage = Math.max(0, next);\n void loadActors();\n },\n size: {\n current: state.actorsPageSize,\n choices: ACTORS_PAGE_SIZES,\n set: (next) => {\n state.actorsPageSize = next;\n state.actorsPage = 0;\n void loadActors();\n }\n }\n };\n for (const [id, withSize] of [\n ["actors-pager-top", true],\n ["actors-pager", false]\n ]) {\n const host = $(id);\n host.hidden = hidden;\n if (hidden) clear(host);\n else renderPager(host, model, { withSize });\n }\n }\n function feedActors() {\n const byKey = /* @__PURE__ */ new Map();\n for (const row of matchingRows()) {\n const entry = row.entry;\n let seen = byKey.get(entry.actor);\n if (seen === void 0) {\n seen = { rows: 0, paths: /* @__PURE__ */ new Set(), agents: /* @__PURE__ */ new Set(), first: entry.at, last: entry.at };\n byKey.set(entry.actor, seen);\n }\n seen.rows++;\n seen.paths.add(entry.path);\n seen.agents.add(entry.userAgent);\n if (entry.at < seen.first) seen.first = entry.at;\n if (entry.at > seen.last) seen.last = entry.at;\n seen.stats = entry.actorStats ?? seen.stats;\n }\n const labels = new Map(state.actors.filter((actor) => actor.label !== void 0).map((actor) => [actor.key, actor.label]));\n const out = [];\n for (const [key, seen] of byKey) {\n const label2 = labels.get(key);\n out.push({\n key,\n ...label2 === void 0 ? {} : { label: label2 },\n requests: seen.rows,\n recentRate: Number.NaN,\n distinctPaths: seen.paths.size,\n distinctUserAgents: seen.agents.size,\n cadenceCv: void 0,\n // A dash where the feed cannot know, like the three columns below it. A confident\n // zero under a heading that means "how many times has this client been proven a bot"\n // is worse than an admission, and it was the only column here still guessing.\n priorConfirmations: seen.stats?.priorConfirmations ?? Number.NaN,\n unsolvedChallenges: Number.NaN,\n cleared: seen.stats?.cleared ?? false,\n firstSeen: seen.stats?.firstSeen ?? seen.first,\n lastSeen: seen.last\n });\n }\n return out.sort((a, b) => b.requests - a.requests);\n }\n function applyActorScope(scope) {\n if (!SECTIONS.registry) return;\n state.actorScope = scope;\n for (const [id, on] of [\n ["actors-scope-tracked", scope === "tracked"],\n ["actors-scope-feed", scope === "feed"]\n ]) {\n byId(id).className = on ? "on" : "";\n byId(id).setAttribute("aria-pressed", String(on));\n }\n drawActors();\n }\n function initActorScope() {\n if (!SECTIONS.registry) return;\n const choose = (scope) => {\n applyActorScope(scope);\n app.syncUrl({ replace: false });\n };\n $("actors-scope-tracked").addEventListener("click", () => choose("tracked"));\n $("actors-scope-feed").addEventListener("click", () => choose("feed"));\n }\n function drawActors() {\n if (!SECTIONS.registry) return;\n if (isConfirming()) return;\n const body = byId("actor-rows");\n clear(body);\n const fromFeed = state.actorScope === "feed";\n const actors = fromFeed ? feedActors() : state.actors;\n $("actors-count").textContent = fromFeed ? `${n(actors.length)} in the feed you are looking at \xB7 ${n(state.actorsTracked)} tracked` : `${n(actors.length)} shown \xB7 ${n(state.actorsTracked)} tracked`;\n drawActorsPager(!fromFeed && actors.length === state.actorsPageSize);\n if (fromFeed) for (const id of ["actors-pager-top", "actors-pager"]) byId(id).hidden = true;\n byId("actors-empty").hidden = actors.length > 0;\n for (const actor of actors) {\n const row = el("tr");\n const who = el("td", "who");\n if (actor.label === void 0) who.textContent = actor.key;\n else {\n who.appendChild(el("div", "label", actor.label));\n who.appendChild(el("div", "sub", actor.key));\n }\n row.appendChild(who);\n row.appendChild(el("td", "num tnum", n(actor.requests)));\n row.appendChild(el("td", "num tnum", Number.isNaN(actor.recentRate) ? "\u2014" : n(actor.recentRate)));\n row.appendChild(el("td", "num tnum", n(actor.distinctPaths)));\n const cadence = el("td", "num tnum", actor.cadenceCv === void 0 ? "\u2014" : actor.cadenceCv.toFixed(2));\n if (actor.cadenceCv !== void 0 && actor.cadenceCv < 0.15) cadence.className += " warn-text";\n row.appendChild(cadence);\n row.appendChild(el("td", "num tnum", Number.isNaN(actor.priorConfirmations) ? "\u2014" : n(actor.priorConfirmations)));\n const unsolved = el("td", "num tnum", Number.isNaN(actor.unsolvedChallenges) ? "\u2014" : n(actor.unsolvedChallenges));\n if (actor.unsolvedChallenges >= 3) unsolved.className += " warn-text";\n row.appendChild(unsolved);\n const stateCell = el("td");\n const tags = [];\n if (actor.cleared) tags.push("cleared as human");\n if (actor.distinctUserAgents > 1) tags.push(`${actor.distinctUserAgents} User-Agents`);\n tags.push(`first seen ${clockStamp(actor.firstSeen)}`);\n stateCell.appendChild(el("div", "tagline", tags.join(" \xB7 ")));\n row.appendChild(stateCell);\n const actions = el("td", "acts");\n const inFeed = el("button", null, "In feed");\n inFeed.title = "Show this actor\'s requests in the live feed";\n inFeed.addEventListener("click", () => {\n setSearch(`actor:${actor.key}`);\n const search = byId("search");\n search.value = state.search;\n app.showTab("live");\n app.syncUrl();\n });\n actions.appendChild(inFeed);\n for (const button of actorActions(actor.key, () => void loadActors(), actor.label)) actions.appendChild(button);\n row.appendChild(actions);\n body.appendChild(row);\n }\n }\n\n // src/dashboard/client/tester.ts\n function initTester() {\n if (!SECTIONS.tester) return;\n $("test-run").addEventListener("click", () => void run());\n byId("test-input").addEventListener("keydown", (event) => {\n if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {\n event.preventDefault();\n void run();\n }\n });\n }\n async function run() {\n const raw = byId("test-input").value;\n if (raw.trim() === "") {\n toast("warn", "Nothing to assess", "Paste a User-Agent, a curl command, or a header block.");\n return;\n }\n const result = await postJson("/api/test", {\n raw,\n ip: byId("test-ip").value.trim(),\n url: byId("test-url").value.trim()\n });\n const box = $("test-result");\n box.hidden = false;\n clear(box);\n if (!result.ok) {\n box.className = "result bad";\n box.appendChild(el("div", null, result.error ?? "The server could not read that."));\n return;\n }\n const { entry, reason, assumed } = result.data;\n const out = outcome(entry);\n box.className = `result ${out === "deny" ? "bad" : out === "mitigate" ? "warn" : "ok"}`;\n const head = el("div");\n const [badgeClass, badgeLabel] = verdictBadge(entry);\n head.appendChild(el("span", `badge ${badgeClass}`, badgeLabel));\n head.appendChild(document.createTextNode(" "));\n head.appendChild(el("b", null, entry.action ?? "no decision"));\n if (entry.rule !== void 0) head.appendChild(el("span", "ev-meta", ` via ${entry.rule}`));\n box.appendChild(head);\n box.appendChild(el("div", "ev-meta", `${entry.certain ? "proven" : `score ${entry.score}`} \xB7 assessed in ${ms(entry.durationMs)}`));\n if (entry.downgradedFrom !== void 0) {\n box.appendChild(el("div", "guard", `The guard stopped ${entry.downgradedFrom} here.`));\n if (entry.downgradeReason !== void 0) box.appendChild(el("div", "basis", entry.downgradeReason));\n }\n if (entry.evidence.length === 0) {\n box.appendChild(el("div", "ev-meta", entry.bypass !== void 0 ? `Detection was skipped: ${entry.bypass}.` : "No detector produced any evidence."));\n } else {\n const list = el("div", "ev");\n for (const item of entry.evidence) {\n const row = el("div", `ev-item${item.direction === "human" ? " human" : ""}`);\n row.appendChild(el("div", `tier t-${item.certainty}`, item.certainty));\n const detail = el("div");\n detail.appendChild(el("div", null, item.summary));\n detail.appendChild(el("div", "ev-meta", `${item.detector} \xB7 points to ${item.direction}`));\n if (item.deterministicBasis !== void 0) detail.appendChild(el("div", "basis", item.deterministicBasis));\n row.appendChild(detail);\n list.appendChild(row);\n }\n box.appendChild(list);\n }\n box.appendChild(el("div", "ev-meta", reason));\n const notes = [...assumed, "no history: this is assessed as a first request, so cadence and crawl breadth have nothing to read"];\n box.appendChild(el("div", "assumed", `Assumed \u2014 ${notes.join("; ")}.`));\n }\n\n // src/dashboard/client/index.ts\n var TABS = [\n ["tab-live", "live", SECTIONS.feed],\n ["tab-actors", "actors", SECTIONS.registry],\n ["tab-stats", "stats", SECTIONS.statistics],\n ["tab-policy", "policy", SECTIONS.policy]\n ];\n var available = TABS.filter(([, , enabled]) => enabled);\n var FIRST = available[0]?.[1] ?? "live";\n function tabIndexOf(name) {\n const at = available.findIndex(([, tab]) => tab === name);\n return at === -1 ? 0 : at;\n }\n function isTab(value) {\n return available.some(([, name]) => name === value);\n }\n function initSkipLink() {\n if (!isEmbedded()) return;\n const skip = rootNode().querySelector("a.skip");\n if (skip === null) return;\n skip.addEventListener("click", (event) => {\n event.preventDefault();\n const target = rootNode().querySelector(`#view-${state.tab}`) ?? rootNode().querySelector("#view-live");\n if (target === null) return;\n target.tabIndex = -1;\n target.focus();\n target.scrollIntoView({ block: "start" });\n });\n }\n function initHeader() {\n const box = $("links");\n for (const link of BOOT.links) {\n const anchor = el("a", "linkbtn", link.label);\n anchor.href = link.href;\n anchor.rel = "noreferrer noopener";\n box.appendChild(anchor);\n }\n let stored = null;\n try {\n stored = localStorage.getItem("bothandler-dashboard-theme");\n } catch {\n stored = null;\n }\n if (stored === "dark" || stored === "light") themeElement().setAttribute("data-theme", stored);\n $("theme").addEventListener("click", () => {\n let current = themeElement().getAttribute("data-theme");\n if (current === null) current = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";\n const next = current === "dark" ? "light" : "dark";\n themeElement().setAttribute("data-theme", next);\n try {\n localStorage.setItem("bothandler-dashboard-theme", next);\n } catch {\n }\n drawNow();\n });\n const pause = byId("pause");\n pause.hidden = !SECTIONS.feed;\n pause.addEventListener("click", () => {\n state.paused = !state.paused;\n pause.setAttribute("aria-pressed", String(state.paused));\n pause.textContent = state.paused ? `Resume${state.bufferedWhilePaused > 0 ? ` (${state.bufferedWhilePaused})` : ""}` : "Pause";\n if (!state.paused) {\n state.bufferedWhilePaused = 0;\n drawNow();\n }\n });\n if (BOOT.allowReset) {\n const reset = byId("reset");\n reset.hidden = false;\n reset.addEventListener("click", () => {\n reset.disabled = true;\n void fetch(`${API}/api/reset`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).then(async (response) => {\n if (!response.ok) {\n const body = await response.json().catch(() => ({}));\n toast("bad", "Reset refused", body.error ?? String(response.status));\n return;\n }\n clearFeed();\n resetFeedCache();\n drawNow();\n }).catch(() => {\n }).finally(() => {\n reset.disabled = false;\n });\n });\n }\n const header = rootNode().querySelector("header");\n if (header !== null) {\n const apply2 = () => {\n themeElement().style.setProperty("--header-h", `${header.getBoundingClientRect().height}px`);\n };\n apply2();\n if (typeof ResizeObserver === "function") new ResizeObserver(apply2).observe(header);\n else addEventListener("resize", apply2);\n }\n }\n function syncUrl(replace = true) {\n if (isEmbedded()) return;\n const params = new URLSearchParams();\n if (state.filter !== "all") params.set("f", state.filter);\n if (state.search !== "") params.set("q", state.search);\n if (state.actorScope !== "tracked") params.set("a", state.actorScope);\n const query = params.toString();\n const hash = `#${state.tab}${query === "" ? "" : `?${query}`}`;\n if (location.hash === hash) return;\n history[replace ? "replaceState" : "pushState"]({ tab: state.tab }, "", hash);\n }\n function readUrl() {\n const raw = isEmbedded() ? "" : location.hash.slice(1);\n const split = raw.indexOf("?");\n const name = split === -1 ? raw : raw.slice(0, split);\n const params = new URLSearchParams(split === -1 ? "" : raw.slice(split + 1));\n const filter = params.get("f") ?? "all";\n return {\n tab: isTab(name) ? name : FIRST,\n filter,\n search: params.get("q") ?? "",\n // Anything but the one alternative reads as the default rather than as an error:\n // a hand-edited URL should land somewhere, and this is the somewhere it lands.\n actorScope: params.get("a") === "feed" ? "feed" : "tracked"\n };\n }\n function showTab(name, options = {}) {\n const target = isTab(name) ? name : FIRST;\n state.tab = target;\n for (const [id, tab, enabled] of TABS) {\n const selected = tab === target;\n const node = $(id);\n node.hidden = !enabled;\n node.setAttribute("aria-selected", String(selected));\n node.tabIndex = selected ? 0 : -1;\n $(`view-${tab}`).hidden = !selected || !enabled;\n }\n if (options.focus === true) $(available[tabIndexOf(target)]?.[0] ?? "tab-live").focus();\n if (target === "policy" && state.policy === void 0) {\n void loadPolicy();\n void loadRanges();\n }\n trackActors();\n if (options.push !== false) syncUrl(options.replace !== false);\n drawNow();\n }\n function initTabs() {\n available.forEach(([id, name], index) => {\n const tab = $(id);\n tab.addEventListener("click", () => showTab(name, { replace: false }));\n tab.addEventListener("keydown", (event) => {\n let next = -1;\n if (event.key === "ArrowRight") next = (index + 1) % available.length;\n else if (event.key === "ArrowLeft") next = (index - 1 + available.length) % available.length;\n else if (event.key === "Home") next = 0;\n else if (event.key === "End") next = available.length - 1;\n if (next === -1) return;\n event.preventDefault();\n showTab(available[next]?.[1] ?? FIRST, { focus: true, replace: false });\n });\n });\n if (isEmbedded()) return;\n addEventListener("popstate", () => {\n const url = readUrl();\n state.filter = url.filter;\n setSearch(url.search);\n reflectFilterButtons();\n applyActorScope(url.actorScope);\n showTab(url.tab, { push: false });\n });\n }\n function initKeyboard() {\n eventTarget().addEventListener("keydown", ((event) => {\n const target = event.target;\n const typing = target !== null && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT");\n if (event.key === "Escape") {\n if (typing && target?.id === "search" && target.value !== "") {\n target.value = "";\n setSearch("");\n syncUrl();\n drawNow();\n return;\n }\n if (typing) {\n target?.blur();\n return;\n }\n if (state.actor !== void 0) {\n state.actor = void 0;\n drawNow();\n return;\n }\n if (state.open.size > 0) {\n state.open.clear();\n drawNow();\n }\n return;\n }\n if (typing || event.metaKey || event.ctrlKey || event.altKey) return;\n if (event.key === "/" && SECTIONS.feed) {\n event.preventDefault();\n showTab("live");\n const search = byId("search");\n search.focus();\n search.select();\n return;\n }\n const digit = ["1", "2", "3", "4"].indexOf(event.key);\n if (digit !== -1 && digit < available.length) {\n event.preventDefault();\n showTab(available[digit]?.[1] ?? FIRST, { focus: true, replace: false });\n }\n }));\n }\n function initRanges() {\n const ranges = [\n ["1m", 6e4],\n ["5m", 3e5],\n ["15m", 9e5],\n ["1h", 36e5]\n ];\n const host = $("traffic-range");\n for (const [label2, value] of ranges) {\n const button = el("button", null, label2);\n button.setAttribute("aria-pressed", String(value === state.rangeMs));\n button.addEventListener("click", () => {\n state.rangeMs = value;\n for (const other of Array.from(host.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n drawTraffic();\n });\n host.appendChild(button);\n }\n const scopes = [\n ["since start", "run"],\n ["this window", "window"]\n ];\n const scopeHost = $("score-scope");\n for (const [label2, value] of scopes) {\n const button = el("button", null, label2);\n button.setAttribute("aria-pressed", String(value === state.scoreScope));\n button.addEventListener("click", () => {\n state.scoreScope = value;\n for (const other of Array.from(scopeHost.children)) other.setAttribute("aria-pressed", "false");\n button.setAttribute("aria-pressed", "true");\n drawScores();\n });\n scopeHost.appendChild(button);\n }\n }\n var pending = false;\n function schedule() {\n if (state.paused || pending) return;\n pending = true;\n requestAnimationFrame(() => {\n pending = false;\n draw();\n });\n }\n function draw() {\n drawChips();\n drawTiles();\n drawNoticeBadge();\n updateWindowLabels();\n if (state.tab === "live") {\n drawActor();\n drawFeed();\n drawLivePanels();\n } else if (state.tab === "actors") {\n drawActors();\n } else if (state.tab === "stats") {\n drawTraffic();\n drawLatency();\n drawScores();\n drawStatsPanels();\n if (SECTIONS.audit) drawAudit();\n } else {\n drawPolicyTab();\n if (SECTIONS.notices) drawNotices();\n if (SECTIONS.changes) drawChanges();\n }\n }\n function drawNow() {\n draw();\n }\n function applySections() {\n const gated = [\n ["tiles", SECTIONS.statistics],\n ["tester-panel", SECTIONS.tester],\n ["ranges-panel", SECTIONS.ranges],\n ["changes-panel", SECTIONS.changes],\n ["actor-panel", SECTIONS.actors],\n ["live-actors-panel", SECTIONS.actors],\n ["audit-panel", SECTIONS.audit],\n ["audit-checks-panel", SECTIONS.audit],\n ["notices-panel", SECTIONS.notices],\n ["guard-panel", SECTIONS.guard],\n ["robots-panel", SECTIONS.robots],\n ["identities-panel", SECTIONS.actors],\n ["evidence-legend", SECTIONS.evidence]\n ];\n for (const [id, enabled] of gated) {\n const node = rootNode().querySelector(`#${id}`);\n if (node !== null && !enabled) node.remove();\n }\n }\n function start() {\n app.draw = schedule;\n app.drawNow = drawNow;\n app.showTab = showTab;\n app.syncUrl = (options) => syncUrl(options?.replace !== false);\n applySections();\n initHeader();\n drawPeers();\n initTabs();\n initSkipLink();\n initKeyboard();\n initRanges();\n if (SECTIONS.feed) initFeed();\n initActor();\n initActorScope();\n initTester();\n initPolicy();\n let resizeTimer;\n addEventListener("resize", () => {\n if (resizeTimer !== void 0) clearTimeout(resizeTimer);\n resizeTimer = setTimeout(() => {\n if (state.tab === "stats") {\n drawTraffic();\n drawLatency();\n drawScores();\n }\n }, 120);\n });\n const url = readUrl();\n state.filter = url.filter;\n setSearch(url.search);\n if (SECTIONS.feed) reflectFilterButtons();\n applyActorScope(url.actorScope);\n showTab(url.tab, { replace: true });\n suspendScrollAnchoring();\n void loadInitialSnapshot().finally(settleScrollAnchoring);\n connectStream();\n }\n function htmlElement() {\n const root2 = rootNode();\n return root2 instanceof Document ? root2.documentElement : void 0;\n }\n function suspendScrollAnchoring() {\n htmlElement()?.classList.add("settling");\n }\n function settleScrollAnchoring() {\n const html = htmlElement();\n if (html === void 0) return;\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n html.classList.remove("settling");\n });\n });\n }\n start();\n})();\n';
|
|
6523
8042
|
}
|
|
6524
8043
|
});
|
|
6525
8044
|
|
|
@@ -6739,7 +8258,10 @@ button[disabled] { opacity: .5; cursor: default; }
|
|
|
6739
8258
|
.tab[aria-selected="true"] { color: var(--ink); border-bottom-color: var(--s1); }
|
|
6740
8259
|
|
|
6741
8260
|
/* --- layout ------------------------------------------------------------- */
|
|
6742
|
-
|
|
8261
|
+
/* The top padding is the gap under the sticky header. At 18px the counter row sat almost
|
|
8262
|
+
against the header's border and read as part of it; the tiles carry their own border, so
|
|
8263
|
+
two lines were meeting with nothing between them. */
|
|
8264
|
+
main { padding: 28px 20px 64px; max-width: 1680px; margin: 0 auto; }
|
|
6743
8265
|
.stack { display: grid; gap: 16px; }
|
|
6744
8266
|
/* Everything above the feed is drawn by script once the first snapshot arrives, which
|
|
6745
8267
|
inserts a block of content above what is already laid out. The browser's scroll
|
|
@@ -6770,6 +8292,33 @@ button.tile {
|
|
|
6770
8292
|
cursor: pointer; appearance: none; transition: border-color .12s, box-shadow .12s;
|
|
6771
8293
|
}
|
|
6772
8294
|
button.tile:hover { border-color: var(--focus); }
|
|
8295
|
+
/* The suggestion list under the search box, positioned against the search wrapper. */
|
|
8296
|
+
.search { position: relative; }
|
|
8297
|
+
.suggest {
|
|
8298
|
+
position: absolute; top: calc(100% + 4px); left: 0; z-index: 30; margin: 0; padding: 4px;
|
|
8299
|
+
list-style: none; min-width: 220px; max-height: 260px; overflow-y: auto;
|
|
8300
|
+
background: var(--surface); border: 1px solid var(--line); border-radius: 9px; box-shadow: var(--shadow);
|
|
8301
|
+
}
|
|
8302
|
+
.suggest li { padding: 4px 9px; border-radius: 6px; cursor: pointer; font-size: 12px; }
|
|
8303
|
+
.suggest li[aria-selected="true"] { background: color-mix(in srgb, var(--focus) 18%, transparent); }
|
|
8304
|
+
|
|
8305
|
+
/* Saved filters: a list of small removable things. Quiet, because it is not what
|
|
8306
|
+
somebody came to the page to look at. */
|
|
8307
|
+
.saved { display: flex; align-items: center; gap: 6px; }
|
|
8308
|
+
/* Two open-ended bounds rather than a list of durations: "from the incident until now",
|
|
8309
|
+
"everything up to when it stopped" and "between these two moments" are the same control
|
|
8310
|
+
with one end left empty. */
|
|
8311
|
+
.timeframe { display: flex; align-items: center; gap: 8px; font-size: 11.5px; color: var(--muted); }
|
|
8312
|
+
.timeframe label { display: inline-flex; align-items: center; gap: 4px; }
|
|
8313
|
+
.timeframe input {
|
|
8314
|
+
font: inherit; font-size: 11.5px; padding: 2px 5px; border-radius: 6px;
|
|
8315
|
+
border: 1px solid var(--line); background: var(--surface); color: var(--ink);
|
|
8316
|
+
}
|
|
8317
|
+
.timeframe button { font: inherit; font-size: 11.5px; padding: 3px 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); cursor: pointer; }
|
|
8318
|
+
.saved select { font: inherit; font-size: 11.5px; padding: 3px 6px; border-radius: 7px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); max-width: 170px; }
|
|
8319
|
+
.saved button { font: inherit; font-size: 11.5px; padding: 3px 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); cursor: pointer; }
|
|
8320
|
+
.saved button:hover { border-color: var(--focus); }
|
|
8321
|
+
|
|
6773
8322
|
/* The badge's companion: fetches the entries the stream skipped. Sits inline with the
|
|
6774
8323
|
heading, so it is styled to read as part of the sentence rather than as a form control. */
|
|
6775
8324
|
.load-skipped {
|
|
@@ -6791,6 +8340,10 @@ button.tile:hover { border-color: var(--focus); }
|
|
|
6791
8340
|
.pager button:hover:not(:disabled) { border-color: var(--focus); }
|
|
6792
8341
|
.pager button:disabled { opacity: .45; cursor: default; }
|
|
6793
8342
|
.pager .where { font-variant-numeric: tabular-nums; }
|
|
8343
|
+
/* A labelled actor leads with its name and keeps the key underneath: whoever named it did
|
|
8344
|
+
so because the key was not the useful part, and the key is still what you search for. */
|
|
8345
|
+
td.who .label { font-weight: 560; }
|
|
8346
|
+
td.who .sub { color: var(--muted); font-size: 11px; }
|
|
6794
8347
|
.pager.pager-top { padding: 2px 2px 9px; border-bottom: 1px solid var(--line); margin-bottom: 9px; }
|
|
6795
8348
|
/* The feed's upper pager rides in the toolbar rather than owning a row of its own, which
|
|
6796
8349
|
was thirty-six pixels of mostly empty rule above every screenful of requests. */
|
|
@@ -6911,7 +8464,29 @@ input[type="search"] {
|
|
|
6911
8464
|
}
|
|
6912
8465
|
input[type="search"]::placeholder { color: var(--muted); }
|
|
6913
8466
|
|
|
6914
|
-
|
|
8467
|
+
/* separate with zero spacing rather than collapse, and the difference is the whole
|
|
8468
|
+
reason the column headers work in Safari.
|
|
8469
|
+
|
|
8470
|
+
Collapsed borders and sticky table cells are a long-standing sore point in WebKit: the
|
|
8471
|
+
CSSWG has an open issue on collapsed borders not following a cell when it sticks
|
|
8472
|
+
(csswg-drafts#3136), and Safari is widely reported to drop the stickiness of a th
|
|
8473
|
+
altogether under a collapsed table. Separating the borders is the standard remedy.
|
|
8474
|
+
|
|
8475
|
+
What was actually measured: the header sticks correctly in Chromium and in Firefox,
|
|
8476
|
+
both before and after this change, and it was reported adrift in Safari — which is what
|
|
8477
|
+
a sticky element that has stopped sticking looks like. WebKit could not be run on the
|
|
8478
|
+
machine this was written on, so the Safari half of it rests on that report and on the
|
|
8479
|
+
documented behaviour rather than on a measurement taken here.
|
|
8480
|
+
|
|
8481
|
+
The rendering is all but unchanged. Every border in these tables is a bottom border on
|
|
8482
|
+
the cell itself, plus the per-cell left accent on td.edge; no border is shared between
|
|
8483
|
+
two cells, so there is nothing for collapsing to merge and nothing for separating to
|
|
8484
|
+
double, and zero spacing keeps the cells touching. The one measurable difference is the
|
|
8485
|
+
accent column, which moves two pixels: collapsing centres that 3px border on the cell
|
|
8486
|
+
edge and leaves half of it outside the box, while separating puts all of it inside.
|
|
8487
|
+
Measured rather than assumed, and the leftmost column starting two pixels earlier is
|
|
8488
|
+
both imperceptible and the more correct of the two. */
|
|
8489
|
+
table { width: 100%; border-collapse: separate; border-spacing: 0; }
|
|
6915
8490
|
thead th {
|
|
6916
8491
|
/* Measured at runtime — see trackHeaderHeight(). The literal is the fallback for
|
|
6917
8492
|
the instant before the first measurement, and for the tab strip wrapping. */
|
|
@@ -7203,9 +8778,44 @@ input::placeholder { color: color-mix(in srgb, var(--muted) 80%, transparent); }
|
|
|
7203
8778
|
#actor-rows td { font-size: 12.5px; }
|
|
7204
8779
|
#actor-rows td.who { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
|
|
7205
8780
|
#actor-rows td.acts { text-align: right; white-space: nowrap; }
|
|
8781
|
+
/* The tracked/shown toggle above the actors table. A segmented pair rather than a
|
|
8782
|
+
dropdown: there are two answers and both are worth reading at a glance. */
|
|
8783
|
+
.scope { display: flex; gap: 6px; padding: 0 14px 10px; }
|
|
8784
|
+
.scope button { font-size: 11.5px; padding: 4px 10px; }
|
|
8785
|
+
.scope button.on { background: var(--accent); color: var(--on-accent, #fff); border-color: var(--accent); }
|
|
8786
|
+
|
|
7206
8787
|
#actor-rows td.acts button { font-size: 11px; padding: 3px 8px; margin-left: 4px; }
|
|
8788
|
+
/* The Label control, which becomes a text box with a Save and a Cancel in place.
|
|
8789
|
+
|
|
8790
|
+
The cell does not wrap, so an editor that sat beside the row's other four buttons put
|
|
8791
|
+
Save off the right edge of the panel, where it could be seen and not clicked. While
|
|
8792
|
+
the editor is open it stands in for those buttons instead — which is also the right
|
|
8793
|
+
thing on its own, since Allowlist and Forget are not what somebody naming a client is
|
|
8794
|
+
reaching for. */
|
|
8795
|
+
.acts.editing > :not(.label-edit), .bar-actions.editing > :not(.label-edit) { display: none; }
|
|
8796
|
+
/* inline-flex rather than inline-block: the row is three fixed-size controls and a flex
|
|
8797
|
+
line is the layout that cannot spill them past its own edge. */
|
|
8798
|
+
.label-edit { display: inline-flex; align-items: center; gap: 4px; }
|
|
8799
|
+
.label-edit button { flex: 0 0 auto; }
|
|
8800
|
+
#actor-rows td.acts .label-save, #actor-actions .label-save { border-color: var(--accent); color: var(--accent); }
|
|
8801
|
+
/* Qualified with the element name on purpose: input[type="text"] { width: 100% } above
|
|
8802
|
+
outranks a bare class, so the width here was quietly ignored and the box grew to fill
|
|
8803
|
+
whatever it was in — which is what put Save and Cancel outside the panel. */
|
|
8804
|
+
input.label-input {
|
|
8805
|
+
font: inherit; font-size: 11px; padding: 3px 8px; width: 15ch; flex: 0 0 auto; box-sizing: border-box;
|
|
8806
|
+
color: var(--ink); background: var(--surface); border: 1px solid var(--accent); border-radius: 6px;
|
|
8807
|
+
}
|
|
8808
|
+
input.label-input:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
|
|
8809
|
+
|
|
7207
8810
|
/* A tag, not a warning: a cleared actor is a decision somebody made, and a metronomic
|
|
7208
8811
|
one is a measurement. Neither is a verdict, so neither gets a verdict's colour. */
|
|
8812
|
+
/* A shadowed finding: shown at full detail, and visibly not part of the decision. Dimmed
|
|
8813
|
+
and set behind a rule rather than coloured, because every colour on this page already
|
|
8814
|
+
means something about a verdict and this one took no part in a verdict. */
|
|
8815
|
+
.det.shadow { opacity: 0.72; }
|
|
8816
|
+
.ev-item.shadow { opacity: 0.72; border-left: 2px dashed var(--line); padding-left: 8px; }
|
|
8817
|
+
.shadow-verdict { margin-top: 8px; font-style: italic; }
|
|
8818
|
+
.shadow-verdict.changed { color: var(--ink-2); font-style: normal; }
|
|
7209
8819
|
.tagline { font-size: 11px; color: var(--muted); }
|
|
7210
8820
|
.tagline b { color: var(--ink-2); font-weight: 600; }
|
|
7211
8821
|
|
|
@@ -7303,8 +8913,16 @@ input::placeholder { color: color-mix(in srgb, var(--muted) 80%, transparent); }
|
|
|
7303
8913
|
<div class="toolbar">
|
|
7304
8914
|
<div class="filters" id="filters"></div>
|
|
7305
8915
|
<div class="search">
|
|
7306
|
-
<input type="search" id="search" placeholder="path:/api actor:203.0.113.4 -rule:allow-crawlers" spellcheck="false" autocomplete="off"
|
|
8916
|
+
<input type="search" id="search" placeholder="path:/api actor:203.0.113.4 -rule:allow-crawlers" spellcheck="false" autocomplete="off"
|
|
8917
|
+
role="combobox" aria-expanded="false" aria-controls="search-suggest" aria-autocomplete="list">
|
|
7307
8918
|
<kbd aria-hidden="true">/</kbd>
|
|
8919
|
+
<ul class="suggest" id="search-suggest" role="listbox" aria-label="Filter suggestions" hidden></ul>
|
|
8920
|
+
</div>
|
|
8921
|
+
<div class="saved" id="saved-filters"></div>
|
|
8922
|
+
<div class="timeframe" id="timeframe">
|
|
8923
|
+
<label>From <input type="datetime-local" id="from-at" step="1"></label>
|
|
8924
|
+
<label>To <input type="datetime-local" id="to-at" step="1"></label>
|
|
8925
|
+
<button type="button" id="timeframe-clear" hidden>Clear</button>
|
|
7308
8926
|
</div>
|
|
7309
8927
|
<button id="feed-export" title="Download every request matching this filter as replay JSONL">Export</button>
|
|
7310
8928
|
<div class="pager pager-inline" id="feed-pager-top" hidden></div>
|
|
@@ -7368,6 +8986,12 @@ input::placeholder { color: color-mix(in srgb, var(--muted) 80%, transparent); }
|
|
|
7368
8986
|
<div class="note" id="actors-note">Everyone the engine is currently remembering, busiest first — a far larger
|
|
7369
8987
|
population than the feed's ring, which holds requests rather than clients. This is
|
|
7370
8988
|
what <code>cadence</code>, <code>crawl-breadth</code> and <code>rate-anomaly</code> are reading.</div>
|
|
8989
|
+
<div class="scope" role="group" aria-label="Which actors to list">
|
|
8990
|
+
<button id="actors-scope-tracked" class="on" aria-pressed="true"
|
|
8991
|
+
title="Every client the engine is remembering, busiest first">Tracked</button>
|
|
8992
|
+
<button id="actors-scope-feed" aria-pressed="false"
|
|
8993
|
+
title="Only the clients that appear in the feed you are looking at, after its filter">Shown in the feed</button>
|
|
8994
|
+
</div>
|
|
7371
8995
|
<div class="pager pager-top" id="actors-pager-top" hidden></div>
|
|
7372
8996
|
<div class="feed-scroll">
|
|
7373
8997
|
<table>
|
|
@@ -7681,18 +9305,21 @@ function createFacts(input) {
|
|
|
7681
9305
|
const rawPath = queryStart === -1 ? url : url.slice(0, queryStart);
|
|
7682
9306
|
const headers = /* @__PURE__ */ Object.create(null);
|
|
7683
9307
|
for (const [name, value] of Object.entries(input.headers)) {
|
|
7684
|
-
const
|
|
7685
|
-
|
|
9308
|
+
const lower = name.toLowerCase();
|
|
9309
|
+
const joined = lower === "cookie" && Array.isArray(value) ? value.join("; ") : joinHeaderValue(value);
|
|
9310
|
+
if (joined !== void 0) headers[lower] = joined;
|
|
7686
9311
|
}
|
|
9312
|
+
const normalized = normalizePath(rawPath);
|
|
7687
9313
|
const facts = {
|
|
7688
9314
|
method: (input.method ?? "GET").toUpperCase(),
|
|
7689
|
-
path:
|
|
9315
|
+
path: normalized,
|
|
7690
9316
|
query: parseQuery(queryStart === -1 ? "" : url.slice(queryStart + 1)),
|
|
7691
9317
|
headers,
|
|
7692
9318
|
headerOrder: extractOrder(input.rawHeaders, headers),
|
|
7693
9319
|
ip: normalizeIp(input.ip) ?? input.ip,
|
|
7694
9320
|
timestamp: input.timestamp ?? Date.now()
|
|
7695
9321
|
};
|
|
9322
|
+
if (rawPath !== normalized) facts.rawPath = rawPath.length > MAX_RAW_PATH ? rawPath.slice(0, MAX_RAW_PATH) : rawPath;
|
|
7696
9323
|
const cookieHeader = headers["cookie"];
|
|
7697
9324
|
if (cookieHeader !== void 0) facts.cookies = parseCookies(cookieHeader);
|
|
7698
9325
|
if (input.protocol !== void 0) facts.protocol = input.protocol;
|
|
@@ -7725,12 +9352,23 @@ function parseQuery(search) {
|
|
|
7725
9352
|
const query = /* @__PURE__ */ Object.create(null);
|
|
7726
9353
|
if (search.length === 0) return query;
|
|
7727
9354
|
let count = 0;
|
|
7728
|
-
for (const [key, value] of new URLSearchParams(search)) {
|
|
9355
|
+
for (const [key, value] of new URLSearchParams(boundedSearch(search))) {
|
|
7729
9356
|
if (count++ >= MAX_QUERY_PARAMS) break;
|
|
7730
9357
|
query[key] = value.length > 1024 ? value.slice(0, 1024) : value;
|
|
7731
9358
|
}
|
|
7732
9359
|
return query;
|
|
7733
9360
|
}
|
|
9361
|
+
function boundedSearch(search) {
|
|
9362
|
+
let seen = 0;
|
|
9363
|
+
let at = search.charCodeAt(0) === 63 ? 1 : 0;
|
|
9364
|
+
while (at < search.length) {
|
|
9365
|
+
let end = search.indexOf("&", at);
|
|
9366
|
+
if (end === -1) end = search.length;
|
|
9367
|
+
if (end !== at && ++seen > MAX_QUERY_PARAMS) return search.slice(0, at - 1);
|
|
9368
|
+
at = end + 1;
|
|
9369
|
+
}
|
|
9370
|
+
return search;
|
|
9371
|
+
}
|
|
7734
9372
|
function extractOrder(rawHeaders, headers) {
|
|
7735
9373
|
if (!rawHeaders || rawHeaders.length === 0) return EMPTY_ORDER;
|
|
7736
9374
|
let isNodeStyle = rawHeaders.length % 2 === 0;
|
|
@@ -7766,13 +9404,14 @@ function isHeaderName(value) {
|
|
|
7766
9404
|
}
|
|
7767
9405
|
return true;
|
|
7768
9406
|
}
|
|
7769
|
-
var MAX_URL_LENGTH, MAX_QUERY_PARAMS, MAX_ORDERED_HEADERS, EMPTY_ORDER;
|
|
9407
|
+
var MAX_URL_LENGTH, MAX_RAW_PATH, MAX_QUERY_PARAMS, MAX_ORDERED_HEADERS, EMPTY_ORDER;
|
|
7770
9408
|
var init_facts = __esm({
|
|
7771
9409
|
"src/facts.ts"() {
|
|
7772
9410
|
"use strict";
|
|
7773
9411
|
init_http();
|
|
7774
9412
|
init_ip();
|
|
7775
9413
|
MAX_URL_LENGTH = 8192;
|
|
9414
|
+
MAX_RAW_PATH = 512;
|
|
7776
9415
|
MAX_QUERY_PARAMS = 64;
|
|
7777
9416
|
MAX_ORDERED_HEADERS = 64;
|
|
7778
9417
|
EMPTY_ORDER = Object.freeze([]);
|
|
@@ -8061,7 +9700,7 @@ function buildDashboard(handler, options, host) {
|
|
|
8061
9700
|
return send(response, 200, "application/json; charset=utf-8", JSON.stringify(snapshot()));
|
|
8062
9701
|
case "/api/feed":
|
|
8063
9702
|
if (!sections.feed) return sectionOff(response, "feed");
|
|
8064
|
-
return send(response, 200, "application/json; charset=utf-8", JSON.stringify({ entries: feed.backlog().map(project) }));
|
|
9703
|
+
return send(response, 200, "application/json; charset=utf-8", JSON.stringify({ entries: feed.backlog().map(project), skipped: feed.skipped }));
|
|
8065
9704
|
case "/api/stream":
|
|
8066
9705
|
if (!sections.feed) return sectionOff(response, "feed");
|
|
8067
9706
|
return stream(request, url, response);
|
|
@@ -8139,8 +9778,11 @@ function buildDashboard(handler, options, host) {
|
|
|
8139
9778
|
} else if (action === "clear") {
|
|
8140
9779
|
const forMs = typeof payload?.forMs === "number" && Number.isFinite(payload.forMs) ? Math.min(24 * 60 * 6e4, Math.max(0, payload.forMs)) : DEFAULT_CLEARANCE_MS;
|
|
8141
9780
|
handler.clearActor(key, forMs, { by });
|
|
9781
|
+
} else if (action === "label") {
|
|
9782
|
+
const label = typeof payload?.label === "string" ? payload.label : void 0;
|
|
9783
|
+
handler.labelActor(key, label, { by });
|
|
8142
9784
|
} else {
|
|
8143
|
-
sendError(response, 400, 'Expected `action` to be "forget" or "
|
|
9785
|
+
sendError(response, 400, 'Expected `action` to be "forget", "clear" or "label".');
|
|
8144
9786
|
return;
|
|
8145
9787
|
}
|
|
8146
9788
|
send(response, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true }));
|
|
@@ -8575,7 +10217,7 @@ function headerValue(request, name) {
|
|
|
8575
10217
|
if (value === void 0) return void 0;
|
|
8576
10218
|
return (Array.isArray(value) ? value[0] : value)?.trim().toLowerCase();
|
|
8577
10219
|
}
|
|
8578
|
-
function
|
|
10220
|
+
function stripPort2(host) {
|
|
8579
10221
|
if (host.startsWith("[")) {
|
|
8580
10222
|
const end = host.indexOf("]");
|
|
8581
10223
|
return end === -1 ? host : host.slice(0, end + 1);
|
|
@@ -8587,15 +10229,15 @@ function stripPort(host) {
|
|
|
8587
10229
|
function resolveAllowedHosts(host, extra) {
|
|
8588
10230
|
if (extra?.includes("*")) return void 0;
|
|
8589
10231
|
if (!LOOPBACK_HOSTS.has(host)) return void 0;
|
|
8590
|
-
const allowed = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1",
|
|
8591
|
-
for (const entry of extra ?? []) allowed.add(
|
|
10232
|
+
const allowed = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1", stripPort2(host).toLowerCase()]);
|
|
10233
|
+
for (const entry of extra ?? []) allowed.add(stripPort2(entry).toLowerCase());
|
|
8592
10234
|
return allowed;
|
|
8593
10235
|
}
|
|
8594
10236
|
function hostAllowed(request, allowed) {
|
|
8595
10237
|
if (allowed === void 0) return true;
|
|
8596
10238
|
const host = headerValue(request, "host");
|
|
8597
10239
|
if (host === void 0) return false;
|
|
8598
|
-
return allowed.has(
|
|
10240
|
+
return allowed.has(stripPort2(host));
|
|
8599
10241
|
}
|
|
8600
10242
|
function isSameOrigin(request) {
|
|
8601
10243
|
const site = headerValue(request, "sec-fetch-site");
|
|
@@ -8638,7 +10280,7 @@ function rangeUpdate(body2, handler) {
|
|
|
8638
10280
|
}
|
|
8639
10281
|
function resolveMountedHosts(extra) {
|
|
8640
10282
|
if (extra === void 0 || extra.length === 0 || extra.includes("*")) return void 0;
|
|
8641
|
-
return new Set(extra.map((name) =>
|
|
10283
|
+
return new Set(extra.map((name) => stripPort2(name).toLowerCase()));
|
|
8642
10284
|
}
|
|
8643
10285
|
function validateClients(entries) {
|
|
8644
10286
|
const set = new IpRangeSet(entries);
|
|
@@ -8890,6 +10532,12 @@ var init_dashboard = __esm({
|
|
|
8890
10532
|
});
|
|
8891
10533
|
|
|
8892
10534
|
// src/core.ts
|
|
10535
|
+
function sanitize(item) {
|
|
10536
|
+
const summary = safeSummary(item.summary);
|
|
10537
|
+
const basis = item.deterministicBasis === void 0 ? void 0 : safeSummary(item.deterministicBasis);
|
|
10538
|
+
if (summary === item.summary && basis === item.deterministicBasis) return item;
|
|
10539
|
+
return { ...item, summary, ...basis === void 0 ? {} : { deterministicBasis: basis } };
|
|
10540
|
+
}
|
|
8893
10541
|
function attribute(context) {
|
|
8894
10542
|
return context.by === void 0 || context.by === "" ? "" : ` by ${context.by}`;
|
|
8895
10543
|
}
|
|
@@ -8915,6 +10563,10 @@ var init_core = __esm({
|
|
|
8915
10563
|
init_policy();
|
|
8916
10564
|
init_dns();
|
|
8917
10565
|
init_clearance();
|
|
10566
|
+
init_challenge_reaction();
|
|
10567
|
+
init_challenge_integrity();
|
|
10568
|
+
init_site_baseline();
|
|
10569
|
+
init_marker2();
|
|
8918
10570
|
init_evidence();
|
|
8919
10571
|
init_known_bots();
|
|
8920
10572
|
init_types2();
|
|
@@ -8922,6 +10574,10 @@ var init_core = __esm({
|
|
|
8922
10574
|
init_ua();
|
|
8923
10575
|
init_pattern();
|
|
8924
10576
|
init_crypto();
|
|
10577
|
+
init_text();
|
|
10578
|
+
init_probe();
|
|
10579
|
+
init_site();
|
|
10580
|
+
init_state();
|
|
8925
10581
|
init_config();
|
|
8926
10582
|
init_async();
|
|
8927
10583
|
init_ip();
|
|
@@ -8932,6 +10588,10 @@ var init_core = __esm({
|
|
|
8932
10588
|
store;
|
|
8933
10589
|
policy;
|
|
8934
10590
|
challenge;
|
|
10591
|
+
/** The marker-cookie probe, when the operator asked for one. See `probe` in the config. */
|
|
10592
|
+
probe;
|
|
10593
|
+
/** The site-wide baseline, when the operator asked for one. See `site` in the config. */
|
|
10594
|
+
site;
|
|
8935
10595
|
notifications;
|
|
8936
10596
|
/**
|
|
8937
10597
|
* The traffic audit, or `undefined` when it was switched off with `audit: false`.
|
|
@@ -8947,6 +10607,8 @@ var init_core = __esm({
|
|
|
8947
10607
|
cheapDetectors = [];
|
|
8948
10608
|
ioDetectors = [];
|
|
8949
10609
|
confirmingDetectors = [];
|
|
10610
|
+
/** Hoisted from the resolved config: read once per detector per request. */
|
|
10611
|
+
shadowIds;
|
|
8950
10612
|
events;
|
|
8951
10613
|
ignoreExact;
|
|
8952
10614
|
ignorePatterns;
|
|
@@ -8961,12 +10623,15 @@ var init_core = __esm({
|
|
|
8961
10623
|
this.store = options.store ?? new MemoryStore({ clock: this.config.clock });
|
|
8962
10624
|
this.registry = new ActorRegistry(this.config.clock, { windowMs: this.config.actorWindowMs, maxActors: this.config.maxActors });
|
|
8963
10625
|
this.signatures = compileSignatures(this.config.signatures);
|
|
10626
|
+
this.shadowIds = this.config.shadowDetectors;
|
|
8964
10627
|
this.resolver = cachingResolver(options.resolver ?? nodeDnsResolver(this.config.detectorTimeoutMs));
|
|
8965
10628
|
this.handlers = new Map((options.handlers ?? []).map((handler) => [handler.id, handler]));
|
|
8966
10629
|
this.isHuman = options.isHuman;
|
|
8967
10630
|
this.meter = options.metrics === false ? void 0 : new Metrics(typeof options.metrics === "object" ? options.metrics : {});
|
|
8968
10631
|
this.timing = this.meter?.perDetectorTiming === true;
|
|
8969
10632
|
this.challenge = options.challenge ? new ChallengeService({ ...options.challenge, store: this.store, clock: this.config.clock }) : void 0;
|
|
10633
|
+
this.probe = options.probe !== void 0 ? new MarkerProbe({ ...options.probe, clock: this.config.clock }) : void 0;
|
|
10634
|
+
this.site = options.site !== void 0 ? new SiteProfile({ ...options.site, clock: this.config.clock }) : void 0;
|
|
8970
10635
|
this.notifications = new NotificationHub({
|
|
8971
10636
|
...options.notifications,
|
|
8972
10637
|
clock: this.config.clock,
|
|
@@ -8987,12 +10652,35 @@ var init_core = __esm({
|
|
|
8987
10652
|
const detectors2 = [...this.config.detectors];
|
|
8988
10653
|
if (this.challenge && !detectors2.some((detector) => detector.id === "clearance")) {
|
|
8989
10654
|
detectors2.unshift(clearanceDetector(this.challenge));
|
|
10655
|
+
if (!detectors2.some((detector) => detector.id === "challenge-reaction")) {
|
|
10656
|
+
detectors2.unshift(challengeReactionDetector());
|
|
10657
|
+
}
|
|
10658
|
+
if (!detectors2.some((detector) => detector.id === "challenge-integrity")) {
|
|
10659
|
+
detectors2.unshift(challengeIntegrityDetector());
|
|
10660
|
+
}
|
|
10661
|
+
}
|
|
10662
|
+
if (this.site !== void 0) {
|
|
10663
|
+
for (const detector of [distributedWalkDetector(), pathNoveltyDetector(), missBaselineDetector(), pathCampaignDetector()]) {
|
|
10664
|
+
if (!detectors2.some((installed) => installed.id === detector.id)) detectors2.unshift(detector);
|
|
10665
|
+
}
|
|
10666
|
+
}
|
|
10667
|
+
if (this.probe !== void 0) {
|
|
10668
|
+
for (const detector of [identityDriftDetector(), markerIntegrityDetector(), markerPersistenceDetector(), markerFanoutDetector()]) {
|
|
10669
|
+
if (!detectors2.some((installed) => installed.id === detector.id)) detectors2.unshift(detector);
|
|
10670
|
+
}
|
|
8990
10671
|
}
|
|
8991
10672
|
for (const detector of detectors2) {
|
|
8992
10673
|
if (detector.stage === "confirming") this.confirmingDetectors.push(detector);
|
|
8993
10674
|
else if (detector.cost === "io") this.ioDetectors.push(detector);
|
|
8994
10675
|
else this.cheapDetectors.push(detector);
|
|
8995
10676
|
}
|
|
10677
|
+
for (const id of this.shadowIds) {
|
|
10678
|
+
if (!detectors2.some((detector) => detector.id === id)) {
|
|
10679
|
+
this.warn(
|
|
10680
|
+
`shadowDetectors names "${id}", which is not an installed detector, so nothing is being shadowed by that entry. Installed: ${detectors2.map((detector) => detector.id).join(", ")}.`
|
|
10681
|
+
);
|
|
10682
|
+
}
|
|
10683
|
+
}
|
|
8996
10684
|
if (options.shareConfirmations === true) {
|
|
8997
10685
|
this.registry.onFirstSight = (state) => this.loadSharedConfirmations(state);
|
|
8998
10686
|
}
|
|
@@ -9147,6 +10835,45 @@ var init_core = __esm({
|
|
|
9147
10835
|
this.warn(`Actor "${key}" was cleared as human at runtime${attribute(context)}, until ${new Date(until).toISOString()}.`);
|
|
9148
10836
|
this.events.emit("actor-change", { key, action: "clear", until, by: context.by });
|
|
9149
10837
|
}
|
|
10838
|
+
/**
|
|
10839
|
+
* Tells the engine what the application answered.
|
|
10840
|
+
*
|
|
10841
|
+
* The one thing detection cannot see for itself. Every verdict here is reached *before*
|
|
10842
|
+
* the response exists — that is what makes it useful, since it can shape the response —
|
|
10843
|
+
* and so the status is knowledge only the application holds. Handed back, it closes the
|
|
10844
|
+
* oldest gap in reading a scanner: an actor whose requests are almost all misses is
|
|
10845
|
+
* looking for something rather than reading anything, and no amount of header analysis
|
|
10846
|
+
* shows that.
|
|
10847
|
+
*
|
|
10848
|
+
* Optional, and silent when the actor has already been forgotten. Nothing about
|
|
10849
|
+
* detection depends on it being called; supplying it sharpens `probe-volume` and
|
|
10850
|
+
* nothing else. The bundled Node adapter wires it up for you.
|
|
10851
|
+
*/
|
|
10852
|
+
recordOutcome(facts, status) {
|
|
10853
|
+
if (!this.isIgnoredPath(facts.path) && !this.isAllowlisted(facts.ip)) {
|
|
10854
|
+
this.site?.recordOutcome(facts.path, status);
|
|
10855
|
+
}
|
|
10856
|
+
if (!Number.isFinite(status)) return;
|
|
10857
|
+
this.registry.peek(this.actorKeyFor(facts))?.recordOutcome(status);
|
|
10858
|
+
}
|
|
10859
|
+
/**
|
|
10860
|
+
* Gives an actor a name, or clears it with `undefined`.
|
|
10861
|
+
*
|
|
10862
|
+
* Detection never reads it — a label cannot make anybody more or less suspicious, and
|
|
10863
|
+
* that separation is deliberate: the moment a note changes a verdict, writing notes
|
|
10864
|
+
* becomes a way to be wrong about people at scale. It is for the humans reading the
|
|
10865
|
+
* dashboard, and it survives exactly as long as the actor does.
|
|
10866
|
+
*
|
|
10867
|
+
* Available from code so a deployment can label what it already knows — its own
|
|
10868
|
+
* monitoring, a partner's feed, the office egress — rather than waiting for somebody to
|
|
10869
|
+
* recognise the address twice.
|
|
10870
|
+
*/
|
|
10871
|
+
labelActor(key, label, context = {}) {
|
|
10872
|
+
const state = this.registry.peek(key);
|
|
10873
|
+
if (state === void 0) return;
|
|
10874
|
+
state.setLabel(label);
|
|
10875
|
+
this.warn(`Actor "${key}" was ${label === void 0 ? "unlabelled" : `labelled "${state.label ?? ""}"`} at runtime${attribute(context)}.`);
|
|
10876
|
+
}
|
|
9150
10877
|
/** Convenience for `updateRanges("crawler:<id>", …)`, matching a signature id. */
|
|
9151
10878
|
updateCrawlerRanges(signatureId, entries, context = {}) {
|
|
9152
10879
|
this.updateRanges(`crawler:${signatureId}`, entries, context);
|
|
@@ -9259,7 +10986,10 @@ var init_core = __esm({
|
|
|
9259
10986
|
id: detector.id,
|
|
9260
10987
|
description: detector.description,
|
|
9261
10988
|
cost: detector.cost ?? "cheap",
|
|
9262
|
-
stage: detector.stage ?? "always"
|
|
10989
|
+
stage: detector.stage ?? "always",
|
|
10990
|
+
// Present only when it is true, so a deployment shadowing nothing lists exactly
|
|
10991
|
+
// what it listed before.
|
|
10992
|
+
...this.shadowIds.has(detector.id) ? { shadow: true } : {}
|
|
9263
10993
|
}));
|
|
9264
10994
|
}
|
|
9265
10995
|
/** Recovers the client address from a socket address and headers, honouring the proxy config. */
|
|
@@ -9302,8 +11032,22 @@ var init_core = __esm({
|
|
|
9302
11032
|
const state = record ? this.registry.observe(actorKey, facts) : detachedActor(actorKey, facts);
|
|
9303
11033
|
const ua = parseUserAgent(facts.headers["user-agent"]);
|
|
9304
11034
|
const signatureMatches = ua.lower.length > 0 ? this.signatures.matchAll(ua.lower) : [];
|
|
11035
|
+
for (const match of signatureMatches) state.noteIdentity(match.id, match.category, match.verification.kind !== "none");
|
|
11036
|
+
const marker = this.probe?.observe(facts, ua);
|
|
11037
|
+
if (marker !== void 0 && record) {
|
|
11038
|
+
state.noteMarker(marker.reading.kind === "valid", marker.reading.kind === "forged", marker.drift);
|
|
11039
|
+
}
|
|
11040
|
+
if (this.site !== void 0 && record) {
|
|
11041
|
+
const seenBefore = this.site.timesSeen(facts.path);
|
|
11042
|
+
this.site.record(facts.path, actorKey);
|
|
11043
|
+
if (seenBefore === 0) state.noteNovelPath();
|
|
11044
|
+
const step = walkStepOf(facts.path);
|
|
11045
|
+
if (step !== void 0) this.site.recordWalk(step.template, step.id, actorKey);
|
|
11046
|
+
}
|
|
9305
11047
|
const context = {
|
|
9306
11048
|
facts,
|
|
11049
|
+
marker,
|
|
11050
|
+
site: this.site,
|
|
9307
11051
|
ua,
|
|
9308
11052
|
actor: state.snapshot(facts.timestamp),
|
|
9309
11053
|
state,
|
|
@@ -9315,21 +11059,22 @@ var init_core = __esm({
|
|
|
9315
11059
|
shared: /* @__PURE__ */ new Map()
|
|
9316
11060
|
};
|
|
9317
11061
|
const evidence = [];
|
|
11062
|
+
const shadowEvidence = [];
|
|
9318
11063
|
const failures = [];
|
|
9319
11064
|
let pending;
|
|
9320
11065
|
for (const detector of this.cheapDetectors) {
|
|
9321
|
-
const inFlight = this.run(detector, context, evidence, failures, 0);
|
|
11066
|
+
const inFlight = this.run(detector, context, evidence, shadowEvidence, failures, 0);
|
|
9322
11067
|
if (inFlight !== void 0) (pending ??= []).push(inFlight);
|
|
9323
11068
|
}
|
|
9324
11069
|
for (const detector of this.ioDetectors) {
|
|
9325
|
-
const inFlight = this.run(detector, context, evidence, failures, this.config.detectorTimeoutMs);
|
|
11070
|
+
const inFlight = this.run(detector, context, evidence, shadowEvidence, failures, this.config.detectorTimeoutMs);
|
|
9326
11071
|
if (inFlight !== void 0) (pending ??= []).push(inFlight);
|
|
9327
11072
|
}
|
|
9328
11073
|
if (pending !== void 0) await Promise.all(pending);
|
|
9329
11074
|
if (signatureMatches.length > 0 && this.confirmingDetectors.length > 0) {
|
|
9330
11075
|
let confirming;
|
|
9331
11076
|
for (const detector of this.confirmingDetectors) {
|
|
9332
|
-
const inFlight = this.run(detector, context, evidence, failures, this.config.detectorTimeoutMs);
|
|
11077
|
+
const inFlight = this.run(detector, context, evidence, shadowEvidence, failures, this.config.detectorTimeoutMs);
|
|
9333
11078
|
if (inFlight !== void 0) (confirming ??= []).push(inFlight);
|
|
9334
11079
|
}
|
|
9335
11080
|
if (confirming !== void 0) await Promise.all(confirming);
|
|
@@ -9349,11 +11094,23 @@ var init_core = __esm({
|
|
|
9349
11094
|
this.fail(error, "isHuman");
|
|
9350
11095
|
}
|
|
9351
11096
|
}
|
|
11097
|
+
if (evidence.some((item) => item.detector === "probe-signature")) state.notePayloadProbe();
|
|
9352
11098
|
const combined = combineEvidence(evidence, {
|
|
9353
11099
|
suspectThreshold: this.config.suspectThreshold,
|
|
9354
11100
|
strictEvidence: this.config.strictEvidence,
|
|
9355
11101
|
onEvidenceViolation: (message) => this.warn(message)
|
|
9356
11102
|
});
|
|
11103
|
+
let shadowVerdict;
|
|
11104
|
+
if (shadowEvidence.length > 0) {
|
|
11105
|
+
const wouldBe = combineEvidence([...evidence, ...shadowEvidence], {
|
|
11106
|
+
suspectThreshold: this.config.suspectThreshold,
|
|
11107
|
+
strictEvidence: this.config.strictEvidence,
|
|
11108
|
+
onEvidenceViolation: (message, item) => {
|
|
11109
|
+
if (item.shadow === true) this.warn(message);
|
|
11110
|
+
}
|
|
11111
|
+
});
|
|
11112
|
+
shadowVerdict = { verdict: wouldBe.verdict, botClass: wouldBe.botClass, score: wouldBe.score, certain: wouldBe.certain };
|
|
11113
|
+
}
|
|
9357
11114
|
const actor = state.snapshot(facts.timestamp);
|
|
9358
11115
|
if (combined.verdict === "confirmed-bot" && record) {
|
|
9359
11116
|
state.confirmations++;
|
|
@@ -9369,10 +11126,13 @@ var init_core = __esm({
|
|
|
9369
11126
|
certain: combined.certain,
|
|
9370
11127
|
evidence: combined.botEvidence,
|
|
9371
11128
|
humanEvidence: combined.humanEvidence,
|
|
11129
|
+
shadowEvidence: sortEvidence(shadowEvidence),
|
|
11130
|
+
...shadowVerdict === void 0 ? {} : { shadowVerdict },
|
|
9372
11131
|
actor,
|
|
9373
11132
|
durationMs: this.config.clock.now() - started,
|
|
9374
11133
|
failures,
|
|
9375
|
-
facts
|
|
11134
|
+
facts,
|
|
11135
|
+
...marker === void 0 ? {} : { marker }
|
|
9376
11136
|
};
|
|
9377
11137
|
if (!record) return assessment;
|
|
9378
11138
|
this.meter?.recordAssessment(assessment);
|
|
@@ -9409,15 +11169,46 @@ var init_core = __esm({
|
|
|
9409
11169
|
onChallenge: (event) => {
|
|
9410
11170
|
this.meter?.recordChallenge(event);
|
|
9411
11171
|
const state = this.registry.peek(assessment.actor.key);
|
|
9412
|
-
if (state !== void 0)
|
|
11172
|
+
if (state !== void 0) {
|
|
11173
|
+
state.unsolvedChallenges++;
|
|
11174
|
+
state.noteChallengeIssued(
|
|
11175
|
+
this.config.clock.now(),
|
|
11176
|
+
assessment.marker?.shape ?? identityShape(assessment.facts, parseUserAgent(assessment.facts.headers["user-agent"]))
|
|
11177
|
+
);
|
|
11178
|
+
}
|
|
9413
11179
|
this.events.emit("challenge", { phase: event, actorKey: assessment.actor.key });
|
|
9414
11180
|
}
|
|
9415
11181
|
});
|
|
11182
|
+
const issued = this.markerFor(assessment);
|
|
11183
|
+
if (issued !== void 0) {
|
|
11184
|
+
if (outcome.kind === "continue" && outcome.responseHeaders?.["set-cookie"] === void 0) {
|
|
11185
|
+
outcome.responseHeaders = { ...outcome.responseHeaders, "set-cookie": issued };
|
|
11186
|
+
} else if (outcome.kind === "respond" && outcome.headers["set-cookie"] === void 0) {
|
|
11187
|
+
outcome.headers = { ...outcome.headers, "set-cookie": issued };
|
|
11188
|
+
}
|
|
11189
|
+
}
|
|
9416
11190
|
if (this.notifications.enabled && (outcome.kind !== "continue" || outcome.delayMs !== void 0)) {
|
|
9417
11191
|
this.notifications.emit({ type: "action", at: new Date(facts.timestamp).toISOString(), assessment, decision });
|
|
9418
11192
|
}
|
|
9419
11193
|
return { assessment, decision, outcome };
|
|
9420
11194
|
}
|
|
11195
|
+
/**
|
|
11196
|
+
* The `Set-Cookie` this response should carry, if any.
|
|
11197
|
+
*
|
|
11198
|
+
* Nothing is issued to a client that already holds a valid marker, because a
|
|
11199
|
+
* `Set-Cookie` on every response makes every response uncacheable by shared caches —
|
|
11200
|
+
* a detection feature is not worth a site's cache-hit ratio. Nothing is issued to a
|
|
11201
|
+
* verified crawler either: Googlebot does not keep cookies, so a marker sent to it is
|
|
11202
|
+
* a header that will never come back and an issuance count that means nothing.
|
|
11203
|
+
*/
|
|
11204
|
+
markerFor(assessment) {
|
|
11205
|
+
if (this.probe === void 0 || assessment.marker === void 0) return void 0;
|
|
11206
|
+
if (assessment.botClass === "verified-bot") return void 0;
|
|
11207
|
+
if (!this.probe.shouldIssue(assessment.marker)) return void 0;
|
|
11208
|
+
const state = this.registry.peek(assessment.actor.key);
|
|
11209
|
+
state?.noteMarkerIssued();
|
|
11210
|
+
return this.probe.issue(assessment.marker);
|
|
11211
|
+
}
|
|
9421
11212
|
/** True when this request is the challenge verification endpoint. */
|
|
9422
11213
|
isChallengeEndpoint(facts) {
|
|
9423
11214
|
return this.challenge !== void 0 && facts.method === "POST" && facts.path === this.challenge.verifyPath;
|
|
@@ -9436,6 +11227,9 @@ var init_core = __esm({
|
|
|
9436
11227
|
this.meter?.recordChallenge(outcome.ok ? "solved" : "rejected");
|
|
9437
11228
|
if (outcome.ok) this.meter?.recordClearance(outcome.level);
|
|
9438
11229
|
else this.meter?.recordChallengeRejection(outcome.reason);
|
|
11230
|
+
if (!outcome.ok && outcome.signal !== void 0) {
|
|
11231
|
+
this.registry.peek(actorKey)?.noteChallengeAnomaly(outcome.signal);
|
|
11232
|
+
}
|
|
9439
11233
|
if (outcome.interactionScore !== void 0) this.meter?.recordInteractionScore(outcome.interactionScore);
|
|
9440
11234
|
if (outcome.ok) this.audit?.recordChallengeSolved(this.config.clock.now());
|
|
9441
11235
|
this.events.emit("challenge", {
|
|
@@ -9472,7 +11266,9 @@ var init_core = __esm({
|
|
|
9472
11266
|
* await. Failures are absorbed here in both paths: a detector can throw, reject or
|
|
9473
11267
|
* hang, and none of those may reach the request.
|
|
9474
11268
|
*/
|
|
9475
|
-
run(detector, context, sink, failures, timeoutMs) {
|
|
11269
|
+
run(detector, context, sink, shadowSink, failures, timeoutMs) {
|
|
11270
|
+
const shadowed = this.shadowIds.has(detector.id);
|
|
11271
|
+
const target = shadowed ? shadowSink : sink;
|
|
9476
11272
|
const startedAt = this.timing ? this.config.clock.now() : 0;
|
|
9477
11273
|
let raw;
|
|
9478
11274
|
try {
|
|
@@ -9483,7 +11279,7 @@ var init_core = __esm({
|
|
|
9483
11279
|
return void 0;
|
|
9484
11280
|
}
|
|
9485
11281
|
if (!(raw instanceof Promise)) {
|
|
9486
|
-
this.collect(raw,
|
|
11282
|
+
this.collect(raw, target, shadowed);
|
|
9487
11283
|
if (startedAt !== 0) this.meter?.recordDetectorTiming(detector.id, this.config.clock.now() - startedAt);
|
|
9488
11284
|
return void 0;
|
|
9489
11285
|
}
|
|
@@ -9498,7 +11294,7 @@ var init_core = __esm({
|
|
|
9498
11294
|
this.events.emit("detector-failure", { detector: detector.id, reason: "timeout", message, requestId: "" });
|
|
9499
11295
|
return;
|
|
9500
11296
|
}
|
|
9501
|
-
this.collect(result,
|
|
11297
|
+
this.collect(result, target, shadowed);
|
|
9502
11298
|
},
|
|
9503
11299
|
(error) => {
|
|
9504
11300
|
if (startedAt !== 0) this.meter?.recordDetectorTiming(detector.id, this.config.clock.now() - startedAt);
|
|
@@ -9506,13 +11302,14 @@ var init_core = __esm({
|
|
|
9506
11302
|
}
|
|
9507
11303
|
);
|
|
9508
11304
|
}
|
|
9509
|
-
collect(result, sink) {
|
|
11305
|
+
collect(result, sink, shadowed = false) {
|
|
9510
11306
|
if (result === void 0 || result === null) return;
|
|
11307
|
+
const mark = (item) => shadowed ? { ...sanitize(item), shadow: true } : sanitize(item);
|
|
9511
11308
|
if (Array.isArray(result)) {
|
|
9512
|
-
for (let i = 0; i < result.length; i++) sink.push(result[i]);
|
|
11309
|
+
for (let i = 0; i < result.length; i++) sink.push(mark(result[i]));
|
|
9513
11310
|
return;
|
|
9514
11311
|
}
|
|
9515
|
-
sink.push(result);
|
|
11312
|
+
sink.push(mark(result));
|
|
9516
11313
|
}
|
|
9517
11314
|
recordFailure(detector, failures, error, requestId = "") {
|
|
9518
11315
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -9532,10 +11329,16 @@ var init_core = __esm({
|
|
|
9532
11329
|
certain: false,
|
|
9533
11330
|
evidence: [],
|
|
9534
11331
|
humanEvidence: [],
|
|
11332
|
+
shadowEvidence: [],
|
|
9535
11333
|
actor: existing?.snapshot(facts.timestamp) ?? {
|
|
9536
11334
|
key: actorKey,
|
|
9537
11335
|
requests: 0,
|
|
9538
11336
|
distinctPaths: 0,
|
|
11337
|
+
distinctQueries: 0,
|
|
11338
|
+
queriesSaturated: false,
|
|
11339
|
+
methodsSeen: ["GET"],
|
|
11340
|
+
responses: 0,
|
|
11341
|
+
misses: 0,
|
|
9539
11342
|
firstSeen: facts.timestamp,
|
|
9540
11343
|
lastSeen: facts.timestamp,
|
|
9541
11344
|
priorConfirmations: 0,
|
|
@@ -10337,7 +12140,7 @@ var init_ai_crawlers = __esm({
|
|
|
10337
12140
|
});
|
|
10338
12141
|
|
|
10339
12142
|
// src/corpus/adversarial.ts
|
|
10340
|
-
var CHROME_UA, ADVERSARIAL_CASES;
|
|
12143
|
+
var CHROME_UA, CURL_UA, ADVERSARIAL_CASES;
|
|
10341
12144
|
var init_adversarial = __esm({
|
|
10342
12145
|
"src/corpus/adversarial.ts"() {
|
|
10343
12146
|
"use strict";
|
|
@@ -10345,7 +12148,248 @@ var init_adversarial = __esm({
|
|
|
10345
12148
|
init_schema();
|
|
10346
12149
|
init_ranges();
|
|
10347
12150
|
CHROME_UA = userAgentOf("chromeWindows");
|
|
12151
|
+
CURL_UA = "curl/8.4.0";
|
|
10348
12152
|
ADVERSARIAL_CASES = [
|
|
12153
|
+
bot({
|
|
12154
|
+
id: "two-scanners-one-address",
|
|
12155
|
+
title: "One address arriving as two different security tools",
|
|
12156
|
+
audience: "hostile",
|
|
12157
|
+
category: "scanning",
|
|
12158
|
+
provenance: "The shape of an actual scan: an operator runs more than one tool against a target, and both announce themselves honestly. Each request on its own is a declared bot; the pair is a scan, and that reading does not exist inside either request.",
|
|
12159
|
+
requests: [
|
|
12160
|
+
{ headers: [["Host", "shop.example"], ["User-Agent", "sqlmap/1.7.2#stable (http://sqlmap.org)"], ["Accept", "*/*"]], ip: "198.51.100.66", atMs: 0 },
|
|
12161
|
+
{ headers: [["Host", "shop.example"], ["User-Agent", "Mozilla/5.00 (Nikto/2.5.0) (Evasions:None) (Test:Port Check)"], ["Accept", "*/*"]], ip: "198.51.100.66", atMs: 1e3 }
|
|
12162
|
+
],
|
|
12163
|
+
expect: { verdict: "confirmed-bot", certain: true, detectors: ["blended-identity"] },
|
|
12164
|
+
notes: "Holds under the default address-based actor key, which is what separates it from `identity-rotation`. A NAT gateway presents a hundred browsers \u2014 that is exactly why counting User-Agents there is useless \u2014 and it does not present sqlmap and nikto."
|
|
12165
|
+
}),
|
|
12166
|
+
bot({
|
|
12167
|
+
id: "two-crawler-claims-one-address",
|
|
12168
|
+
title: "One address claiming to be both Googlebot and Bingbot",
|
|
12169
|
+
audience: "hostile",
|
|
12170
|
+
category: "impersonation",
|
|
12171
|
+
provenance: "At most one of these can be true of an address: each operator publishes a proof tied to addresses it controls. The contradiction is visible from the claims alone, with no lookup \u2014 which matters when DNS is unreachable and neither claim can be refuted on its own.",
|
|
12172
|
+
requests: [
|
|
12173
|
+
{ headers: [["Host", "shop.example"], ["User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"], ["Accept", "*/*"]], ip: "198.51.100.67", atMs: 0 },
|
|
12174
|
+
{ headers: [["Host", "shop.example"], ["User-Agent", "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"], ["Accept", "*/*"]], ip: "198.51.100.67", atMs: 1e3 }
|
|
12175
|
+
],
|
|
12176
|
+
expect: { detectors: ["blended-identity"] },
|
|
12177
|
+
notes: "Held at `strong` rather than `certain`. Trusting the wrong forwarded header collapses every client onto one address, and then two genuinely different crawlers produce this exact set \u2014 so it may contribute to a denial and may not be the whole of one."
|
|
12178
|
+
}),
|
|
12179
|
+
bot({
|
|
12180
|
+
id: "id-harvest-contiguous",
|
|
12181
|
+
title: "Every profile id in order, with a copied browser header set",
|
|
12182
|
+
audience: "hostile",
|
|
12183
|
+
category: "scraping",
|
|
12184
|
+
provenance: "Harvesting by identifier rather than by link: the shape of an IDOR sweep and of profile collection. Distinct-path breadth reads it as somebody who visited a lot of pages, which is also what it reads when a person works through a documentation site.",
|
|
12185
|
+
requests: repeat({ ...browser("chromeWindows"), ip: "198.51.100.65" }, 40, 800, (index) => `/user/${index + 1}`),
|
|
12186
|
+
expect: {
|
|
12187
|
+
// One `moderate` signal against a flawless header set, like the others here. What
|
|
12188
|
+
// changed is that the walk is now *visible* — before this detector it was scored
|
|
12189
|
+
// identically to a hundred and twenty scattered ids and to ordinary article paths.
|
|
12190
|
+
verdict: "unknown",
|
|
12191
|
+
detectors: ["id-enumeration"]
|
|
12192
|
+
},
|
|
12193
|
+
notes: "What separates this from reading is not which ids were asked for but that they cover a range: people arrive at ids through links, and links do not densely enumerate an integer interval. Held at `moderate` because products in one category often carry consecutive ids, so somebody browsing a catalogue makes a smaller version of this shape."
|
|
12194
|
+
}),
|
|
12195
|
+
bot({
|
|
12196
|
+
id: "wordlist-scan-mostly-misses",
|
|
12197
|
+
title: "A wordlist walked with a copied browser header set, almost all of it missing",
|
|
12198
|
+
audience: "hostile",
|
|
12199
|
+
category: "scanning",
|
|
12200
|
+
provenance: "The oldest tell there is, and the one this library could not see: it decides before the response exists, which is what lets it shape the response and also what hides the status from it. A person browsing does not generate thirty misses in a row; a wordlist does almost nothing else.",
|
|
12201
|
+
requests: repeat({ ...browser("chromeWindows"), ip: "198.51.100.64", status: 404 }, 30, 700, (index) => `/${["admin", "backup", "old", "test", "config", "db"][index % 6]}-${index}`),
|
|
12202
|
+
expect: {
|
|
12203
|
+
// One `moderate` signal against an otherwise flawless header set does not cross the
|
|
12204
|
+
// line, and it should not: a site that has just moved its URLs produces the same
|
|
12205
|
+
// shape from ordinary readers. Raising the ceiling so this case reads better would
|
|
12206
|
+
// be tuning the detector to the test rather than to the traffic.
|
|
12207
|
+
verdict: "unknown",
|
|
12208
|
+
detectors: ["probe-volume"]
|
|
12209
|
+
},
|
|
12210
|
+
notes: "Only counts 404 and 410. A 403 is usually this library's own doing, and counting it would let a rule that challenges an actor manufacture the evidence for having challenged it; a 500 is the site's problem and says nothing about the client. Capped at `moderate` because a site that has just moved its URLs produces this from perfectly ordinary readers."
|
|
12211
|
+
}),
|
|
12212
|
+
bot({
|
|
12213
|
+
id: "browser-claim-over-http-1-0",
|
|
12214
|
+
title: "A perfect Chrome header set, arriving over HTTP/1.0",
|
|
12215
|
+
audience: "hostile",
|
|
12216
|
+
category: "impersonation",
|
|
12217
|
+
provenance: "Most tooling lets you set headers and does not let you choose an HTTP version, so the transport is the half a copied header set does not cover. No shipping browser has offered HTTP/1.0 to a server in well over a decade.",
|
|
12218
|
+
requests: repeat({ ...browser("chromeWindows"), ip: "198.51.100.62", httpVersion: "1.0" }, 30, 900, (index) => `/${["news", "about", "blog", "help", "terms"][index % 5]}`),
|
|
12219
|
+
expect: {
|
|
12220
|
+
// Contributes rather than concludes. On its own, against an otherwise flawless
|
|
12221
|
+
// header set, one `moderate` signal does not reach the threshold — and it should
|
|
12222
|
+
// not, because an intermediary can cause this. Beside anything sharper it does.
|
|
12223
|
+
verdict: "unknown",
|
|
12224
|
+
detectors: ["transport-coherence"]
|
|
12225
|
+
},
|
|
12226
|
+
notes: "Capped at `moderate` because it is not always the client's doing: a few older load balancers speak HTTP/1.0 to the origin, and behind one of those every request looks like this. That is what `transportCoherenceDetector({ legacyHttp: false })` is for, and why this may never deny anybody on its own."
|
|
12227
|
+
}),
|
|
12228
|
+
// ---------------------------------------------------------------------------
|
|
12229
|
+
// The optional sources. None of these can be detected without the operator
|
|
12230
|
+
// switching something on — a marker cookie, or a site-wide baseline — so each
|
|
12231
|
+
// exists to hold that feature to the same standard as everything shipped by
|
|
12232
|
+
// default. See `docs/detection/correlation.md`.
|
|
12233
|
+
// ---------------------------------------------------------------------------
|
|
12234
|
+
bot({
|
|
12235
|
+
id: "marker-held-while-identity-changes",
|
|
12236
|
+
title: "One client presenting a marker it was issued as Chrome, then as curl",
|
|
12237
|
+
audience: "unwanted-bot",
|
|
12238
|
+
category: "evasion",
|
|
12239
|
+
provenance: "Identity rotation, which is invisible without a marker. Correlating by address cannot tell this apart from two people sharing an office connection, so the library declined to guess. A signed cookie removes the ambiguity: both requests carried an HMAC only this server can produce.",
|
|
12240
|
+
requires: ["marker-probe"],
|
|
12241
|
+
requests: [
|
|
12242
|
+
...repeat({ ...browser("chromeWindows"), ip: "198.51.100.81", headers: [...browser("chromeWindows").headers, ["Cookie", "sid=held"]] }, 4, 1500, (i) => `/products/${i}`),
|
|
12243
|
+
...repeat({ ...plain(CURL_UA), ip: "198.51.100.81", headers: [...plain(CURL_UA).headers, ["Cookie", "sid=held"]] }, 4, 1500, (i) => `/products/${i + 4}`).map((request) => ({ ...request, atMs: (request.atMs ?? 0) + 6e3 }))
|
|
12244
|
+
],
|
|
12245
|
+
expect: { verdict: "confirmed-bot", detectors: ["identity-drift"] },
|
|
12246
|
+
notes: "The browser family carries the weight and the platform does not, because a phone with `Request desktop site` changes its platform and is a person. Software does not change what it is."
|
|
12247
|
+
}),
|
|
12248
|
+
bot({
|
|
12249
|
+
id: "marker-never-stored-though-cookies-sent",
|
|
12250
|
+
title: "A client replaying a captured session cookie and storing nothing new",
|
|
12251
|
+
audience: "unwanted-bot",
|
|
12252
|
+
category: "scraping",
|
|
12253
|
+
provenance: "A scraper handed a session header to copy. It sends the one cookie it was configured with on every request and never stores anything the server sets, which a browser with a jar does not do.",
|
|
12254
|
+
requires: ["marker-probe"],
|
|
12255
|
+
keepsCookies: false,
|
|
12256
|
+
requests: repeat(
|
|
12257
|
+
{ ...browser("chromeWindows"), ip: "198.51.100.82", headers: [...browser("chromeWindows").headers, ["Cookie", "sid=captured-elsewhere"]] },
|
|
12258
|
+
9,
|
|
12259
|
+
1200,
|
|
12260
|
+
(i) => `/products/${i}`
|
|
12261
|
+
),
|
|
12262
|
+
expect: { verdict: "unknown", detectors: ["marker-persistence"] },
|
|
12263
|
+
notes: "Deliberately narrower than `session-integrity`, which already reports a client sending no cookie at all. Overlapping them double-counted one observation and the population it landed on was people who block cookies."
|
|
12264
|
+
}),
|
|
12265
|
+
bot({
|
|
12266
|
+
id: "marker-edited-by-its-holder",
|
|
12267
|
+
title: "A client that edited the signed cookie it was given",
|
|
12268
|
+
audience: "unwanted-bot",
|
|
12269
|
+
category: "evasion",
|
|
12270
|
+
provenance: "Browsers do not edit their own cookies. A marker failing its HMAC was altered by whoever held it, and the only reason to alter an opaque signed value is to see what the server does with a different one.",
|
|
12271
|
+
requires: ["marker-probe"],
|
|
12272
|
+
keepsCookies: false,
|
|
12273
|
+
requests: repeat(
|
|
12274
|
+
{ ...browser("chromeWindows"), ip: "198.51.100.83", headers: [...browser("chromeWindows").headers, ["Cookie", "__bh_m=eyJ2IjoxfQ.not-a-signature-this-server-made"]] },
|
|
12275
|
+
4,
|
|
12276
|
+
1500,
|
|
12277
|
+
(i) => `/account/${i}`
|
|
12278
|
+
),
|
|
12279
|
+
expect: { verdict: "unknown", detectors: ["marker-integrity"] },
|
|
12280
|
+
notes: "Stops at `strong` rather than `certain` because a middlebox or a broken cookie jar can mangle a value in transit. That is rare, it is not the client's fault, and it should cost a challenge rather than a door."
|
|
12281
|
+
}),
|
|
12282
|
+
bot({
|
|
12283
|
+
id: "marker-carried-across-a-proxy-pool",
|
|
12284
|
+
title: "One marker presented from twenty different networks",
|
|
12285
|
+
audience: "unwanted-bot",
|
|
12286
|
+
category: "scraping",
|
|
12287
|
+
provenance: "A scraper on a rotating proxy pool that keeps its cookie jar, which most of them do because discarding it breaks the sites they are taking. The marker comes back only from the client that received it, so this is one client across twenty networks.",
|
|
12288
|
+
requires: ["marker-probe"],
|
|
12289
|
+
requests: Array.from({ length: 20 }, (_, index) => ({
|
|
12290
|
+
...browser("chromeWindows"),
|
|
12291
|
+
headers: [...browser("chromeWindows").headers, ["Cookie", "sid=pooled"]],
|
|
12292
|
+
ip: `198.51.${140 + index}.9`,
|
|
12293
|
+
path: `/catalogue/${index}`,
|
|
12294
|
+
atMs: index * 2500
|
|
12295
|
+
})),
|
|
12296
|
+
expect: { verdict: "unknown", detectors: ["marker-fanout"] },
|
|
12297
|
+
notes: "Capped at `moderate` and offered no higher: a phone on a carrier using CGNAT can be renumbered across a great many /24s in the twelve hours a marker lives, and so can anyone whose employer egresses through a rotating pool."
|
|
12298
|
+
}),
|
|
12299
|
+
bot({
|
|
12300
|
+
id: "range-walked-across-many-clients",
|
|
12301
|
+
title: "An id range divided between ten clients so none of them walks enough to notice",
|
|
12302
|
+
audience: "unwanted-bot",
|
|
12303
|
+
category: "scraping",
|
|
12304
|
+
provenance: "The threat every per-actor threshold misses by construction. Split a range across enough addresses and each one is unremarkable, `id-enumeration` fires for nobody, and the range is still walked end to end. It is only visible in the union.",
|
|
12305
|
+
requires: ["site-baseline"],
|
|
12306
|
+
requests: Array.from({ length: 200 }, (_, index) => ({
|
|
12307
|
+
...browser("chromeWindows"),
|
|
12308
|
+
ip: `198.51.${170 + index % 10}.5`,
|
|
12309
|
+
path: `/user/${index + 1}`,
|
|
12310
|
+
atMs: index * 900
|
|
12311
|
+
})),
|
|
12312
|
+
expect: { verdict: "unknown", detectors: ["distributed-walk"] },
|
|
12313
|
+
notes: "Coverage and the revisit ratio must both agree. Many clients on numbered pages is what a catalogue is; what a catalogue also has, and an enumeration does not, is people returning to the same popular items."
|
|
12314
|
+
}),
|
|
12315
|
+
bot({
|
|
12316
|
+
id: "fresh-path-wanted-by-everybody",
|
|
12317
|
+
title: "A path this site never served, requested at once by twenty unrelated clients",
|
|
12318
|
+
audience: "unwanted-bot",
|
|
12319
|
+
category: "recon",
|
|
12320
|
+
provenance: "What a freshly disclosed vulnerability looks like from inside a site: a URL nobody had ever requested is requested by hundreds of unrelated clients within the hour, each making a single request and moving on.",
|
|
12321
|
+
requires: ["site-baseline"],
|
|
12322
|
+
requests: Array.from({ length: 20 }, (_, index) => ({
|
|
12323
|
+
...plain(CURL_UA),
|
|
12324
|
+
ip: `198.51.${190 + index}.11`,
|
|
12325
|
+
path: "/vendor/proprietary-thing/rce.php",
|
|
12326
|
+
status: 404,
|
|
12327
|
+
atMs: index * 3e3
|
|
12328
|
+
})),
|
|
12329
|
+
expect: { verdict: "unknown", detectors: ["path-campaign"] },
|
|
12330
|
+
notes: "The miss rate is required rather than optional. Many clients arriving at once on a brand-new URL is also exactly what a successful launch looks like; what separates them is whether the site had anything to serve."
|
|
12331
|
+
}),
|
|
12332
|
+
bot({
|
|
12333
|
+
id: "missing-far-more-than-this-site-does",
|
|
12334
|
+
title: 'A client answered "not found" far more often than the site answers it at all',
|
|
12335
|
+
audience: "unwanted-bot",
|
|
12336
|
+
category: "recon",
|
|
12337
|
+
provenance: "A fixed miss threshold is wrong on both kinds of site: on one mid-migration it reports everybody, and on a tidy one it stays silent while a client misses a third of the time. The site's own rate is the only honest comparison.",
|
|
12338
|
+
requires: ["site-baseline"],
|
|
12339
|
+
requests: repeat({ ...plain(CURL_UA), ip: "198.51.210.12", status: 404 }, 26, 1100, (i) => `/backup-${i}.sql`),
|
|
12340
|
+
expect: { verdict: "unknown", detectors: ["miss-baseline"] },
|
|
12341
|
+
notes: "Shares the `misses` family with `probe-volume`, which reads the same misses against a fixed threshold. One cause, so the stronger reading stands rather than the two summing."
|
|
12342
|
+
}),
|
|
12343
|
+
bot({
|
|
12344
|
+
id: "solution-farm-replaying-answers",
|
|
12345
|
+
title: "A client answering challenges with solutions that have already been spent",
|
|
12346
|
+
audience: "unwanted-bot",
|
|
12347
|
+
category: "evasion",
|
|
12348
|
+
provenance: "What a solved-challenge farm looks like from the server. A challenge nonce is random, single-use and signed, so a second valid solution for one is the same answer sent twice or one answer handed around \u2014 neither of which a browser does. One replay is a retried POST on a flaky connection, which is why the threshold is not one.",
|
|
12349
|
+
challengeHistory: { replayedSolutions: 4, implausibleSolves: 2 },
|
|
12350
|
+
requests: repeat({ ...browser("chromeWindows"), ip: "198.51.100.71" }, 6, 1500, () => "/account"),
|
|
12351
|
+
expect: {
|
|
12352
|
+
// A shape worth reporting and not worth concluding from: the client is otherwise
|
|
12353
|
+
// indistinguishable from the browser whose headers it copied.
|
|
12354
|
+
verdict: "unknown",
|
|
12355
|
+
detectors: ["challenge-integrity"]
|
|
12356
|
+
},
|
|
12357
|
+
notes: "The proof-of-work floor is measured on the server between issuing and receiving, so no client clock is involved, and it is set at a SHA-256 rate no browser has ever reached. Both signals stay `moderate`: they say the answers did not come from the page we served, which is a fact about the answering software rather than proof about the traffic it is attached to."
|
|
12358
|
+
}),
|
|
12359
|
+
bot({
|
|
12360
|
+
id: "head-only-visit",
|
|
12361
|
+
title: "A visit made entirely of HEAD, claiming a browser",
|
|
12362
|
+
audience: "unwanted-bot",
|
|
12363
|
+
category: "scraping",
|
|
12364
|
+
provenance: "Checking what exists without reading any of it: link checkers, availability monitors and inventory watchers all do this, and a browser navigating never does.",
|
|
12365
|
+
requests: repeat({ ...browser("chromeWindows"), ip: "198.51.100.63", method: "HEAD" }, 30, 900, (index) => `/${["news", "about", "blog", "help", "terms"][index % 5]}`),
|
|
12366
|
+
expect: {
|
|
12367
|
+
// As above: a shape worth reporting, not worth concluding from alone.
|
|
12368
|
+
verdict: "unknown",
|
|
12369
|
+
detectors: ["transport-coherence"]
|
|
12370
|
+
},
|
|
12371
|
+
notes: "One HEAD is a browser checking a link it is about to follow, or a cache revalidating; the shape only means anything across a visit, which is why it is counted on the actor rather than on the request. A link checker is a real and mostly harmless thing to be, so this stays `moderate`."
|
|
12372
|
+
}),
|
|
12373
|
+
bot({
|
|
12374
|
+
id: "catalogue-sweep-by-page",
|
|
12375
|
+
title: "A catalogue taken a page at a time, with the path never changing",
|
|
12376
|
+
audience: "unwanted-bot",
|
|
12377
|
+
category: "scraping",
|
|
12378
|
+
provenance: "How a catalogue is actually taken. The collector copies a browser's headers exactly and walks ?page=1..N, which leaves the path constant \u2014 so distinct-path breadth reads it as somebody rereading one page rather than as enumeration.",
|
|
12379
|
+
requests: repeat({ ...browser("chromeWindows"), ip: "198.51.100.61" }, 40, 900, (index) => `/products?page=${index}`),
|
|
12380
|
+
expect: {
|
|
12381
|
+
// Not proven, and not even suspected at this pace. Said plainly because it is true:
|
|
12382
|
+
// headers this clean leave only behaviour, behaviour is weak by construction, and a
|
|
12383
|
+
// collector polite enough to space its requests stays under the line. What changed
|
|
12384
|
+
// is that it no longer scores *lower* than the identical crawl expressed as distinct
|
|
12385
|
+
// paths — measured at a faster pace before this detector existed, the two differed by
|
|
12386
|
+
// seven points and only the path version crossed; they now score the same at every
|
|
12387
|
+
// volume tried.
|
|
12388
|
+
verdict: "unknown",
|
|
12389
|
+
detectors: ["parameter-sweep"]
|
|
12390
|
+
},
|
|
12391
|
+
notes: "The counterpart to crawl-breadth rather than a replacement for it: breadth counts paths, this counts what is hung on them. Both stay weak, and both are worth having because a collector picks one shape or the other and nothing says which. Neither is a reason to deny anybody on its own."
|
|
12392
|
+
}),
|
|
10349
12393
|
// ---------------------------------------------------------------------------
|
|
10350
12394
|
// Forged identities. The narrow case where a lie is provable.
|
|
10351
12395
|
// ---------------------------------------------------------------------------
|
|
@@ -10688,6 +12732,38 @@ var init_adversarial = __esm({
|
|
|
10688
12732
|
expect: { certain: false, detectors: ["probe-signature"], neverAction: ["block", "drop"] },
|
|
10689
12733
|
tags: ["scanning"]
|
|
10690
12734
|
}),
|
|
12735
|
+
bot({
|
|
12736
|
+
id: "traversal-encoded-past-a-filter",
|
|
12737
|
+
title: "A traversal with its dots and slashes written in percent-encoding",
|
|
12738
|
+
audience: "hostile",
|
|
12739
|
+
category: "wordlist-probe",
|
|
12740
|
+
provenance: "The standard first move against a path filter, and the reason this library keeps the raw target: normalisation resolves the dots, so what reaches a wordlist check is `/app/config.yml` \u2014 an ordinary-looking path nobody has, on no list. The spelling is the whole signal, and it is destroyed by the thing that makes rules work.",
|
|
12741
|
+
requests: [{ ...browser("chromeWindows"), path: "/%2e%2e%2f%2e%2e%2fapp/config.yml", status: 404 }],
|
|
12742
|
+
expect: { certain: false, detectors: ["target-integrity"], neverAction: ["block", "drop"] },
|
|
12743
|
+
notes: "`strong`, not proven. A path segment carrying a URL as data is encoded to sit in a path and encoded again by whatever built the link, which produces the same characters honestly \u2014 so this may score, and may not close a door on its own.",
|
|
12744
|
+
tags: ["scanning"]
|
|
12745
|
+
}),
|
|
12746
|
+
bot({
|
|
12747
|
+
id: "traversal-double-encoded",
|
|
12748
|
+
title: "A traversal encoded twice, so one round of decoding leaves it encoded",
|
|
12749
|
+
audience: "hostile",
|
|
12750
|
+
category: "wordlist-probe",
|
|
12751
|
+
provenance: "Aimed at a filter that decodes once and then inspects: after its single pass the target still reads `%2e%2e%2f`, which the filter does not recognise, and the server behind it decodes again.",
|
|
12752
|
+
requests: [{ ...browser("chromeWindows"), path: "/static/%252e%252e%252f%252e%252e%252fetc/passwd", status: 404 }],
|
|
12753
|
+
expect: { certain: false, detectors: ["target-integrity"], neverAction: ["block", "drop"] },
|
|
12754
|
+
tags: ["scanning"]
|
|
12755
|
+
}),
|
|
12756
|
+
bot({
|
|
12757
|
+
id: "absolute-form-proxy-probe",
|
|
12758
|
+
title: "A request target addressed to somewhere else entirely",
|
|
12759
|
+
audience: "hostile",
|
|
12760
|
+
category: "protocol-abuse",
|
|
12761
|
+
provenance: "Absolute-form is the request line a client sends to a *proxy*. Arriving at an origin server it is a question \u2014 will you fetch this for me \u2014 and open-proxy scanning asks it of everything with a port 80 open.",
|
|
12762
|
+
requests: [{ ...plain(CHROME_UA), path: "http://scanner.example/check", status: 404 }],
|
|
12763
|
+
expect: { certain: false, detectors: ["target-integrity"], neverAction: ["block", "drop"] },
|
|
12764
|
+
notes: "RFC 9112 \xA73.2.2 requires servers to accept absolute-form, so this is not malformed and is not proven. No browser has ever sent one to an origin server.",
|
|
12765
|
+
tags: ["scanning"]
|
|
12766
|
+
}),
|
|
10691
12767
|
bot({
|
|
10692
12768
|
id: "probe-trace-method",
|
|
10693
12769
|
title: "A TRACE request",
|
|
@@ -12341,6 +14417,46 @@ var init_humans = __esm({
|
|
|
12341
14417
|
],
|
|
12342
14418
|
expect: { verdict: "unknown", maxScore: 0, notDetectors: ["header-order"], action: "allow" }
|
|
12343
14419
|
}),
|
|
14420
|
+
human({
|
|
14421
|
+
id: "request-desktop-site-mid-visit",
|
|
14422
|
+
title: "Somebody switching their phone to the desktop version of a site",
|
|
14423
|
+
category: "mangled-by-infrastructure",
|
|
14424
|
+
provenance: "`Request desktop site` rewrites the User-Agent to claim a Mac. The browser is the same Safari and the cookie jar is the same jar, so the marker comes back \u2014 which means the library can see, correctly, that one client has now described itself two different ways.",
|
|
14425
|
+
requires: ["marker-probe"],
|
|
14426
|
+
notes: "The reason `identity-drift` weighs a changed *browser family* at `strong` and a changed platform only at `moderate`. Software does not change what it is; a platform changes when a person taps a menu item, and this is that person.",
|
|
14427
|
+
requests: [
|
|
14428
|
+
...humanPaced({ ...browser("safariIos"), ip: "203.0.115.24", headers: [...browser("safariIos").headers, ["Cookie", "sid=phone-session"]] }, [
|
|
14429
|
+
"/",
|
|
14430
|
+
"/collections/lamps",
|
|
14431
|
+
"/products/brass-desk-lamp",
|
|
14432
|
+
"/products/brass-desk-lamp/reviews"
|
|
14433
|
+
]),
|
|
14434
|
+
// The same person, same session, having tapped "Request desktop site".
|
|
14435
|
+
...humanPaced(
|
|
14436
|
+
{ ...browser("safariMac"), ip: "203.0.115.24", headers: [...browser("safariMac").headers, ["Cookie", "sid=phone-session"]] },
|
|
14437
|
+
["/products/brass-desk-lamp", "/delivery", "/products/brass-desk-lamp", "/basket"]
|
|
14438
|
+
).map((request) => ({ ...request, atMs: (request.atMs ?? 0) + 47e3 }))
|
|
14439
|
+
],
|
|
14440
|
+
expect: { certain: false, action: ["allow", "tag", "log", "delay", "challenge", "rate-limit"] },
|
|
14441
|
+
tags: ["known-cost"]
|
|
14442
|
+
}),
|
|
14443
|
+
human({
|
|
14444
|
+
id: "broken-link-shared-widely",
|
|
14445
|
+
title: "A crowd of people following one mistyped link",
|
|
14446
|
+
category: "mangled-by-infrastructure",
|
|
14447
|
+
provenance: "Somebody shares a URL with a typo in it and thousands of real people follow it within the hour. From the server this is a path the site has never served, requested by many unrelated clients, and answered `not found` to every one of them \u2014 which is the exact shape `path-campaign` reads.",
|
|
14448
|
+
requires: ["site-baseline"],
|
|
14449
|
+
notes: "The known cost of comparing a client with the rest of the traffic: most of the evidence is about what *other* people did, and a person following a bad link is indistinguishable here from one running a list. It is capped at `moderate` for this case specifically, and the guarantee it must keep is this one \u2014 reported, never refused.",
|
|
14450
|
+
requests: Array.from({ length: 16 }, (_, index) => ({
|
|
14451
|
+
...browser("chromeWindows", { kind: "cross-site-navigate", referer: "https://social.example/" }),
|
|
14452
|
+
ip: `203.0.114.${index + 1}`,
|
|
14453
|
+
path: "/blog/anouncing-our-new-thing",
|
|
14454
|
+
status: 404,
|
|
14455
|
+
atMs: index * 4e3
|
|
14456
|
+
})),
|
|
14457
|
+
expect: { certain: false, action: ["allow", "tag", "log", "delay", "challenge", "rate-limit"] },
|
|
14458
|
+
tags: ["known-cost"]
|
|
14459
|
+
}),
|
|
12344
14460
|
human({
|
|
12345
14461
|
id: "cgnat-shared-address",
|
|
12346
14462
|
title: "Many people behind one carrier-grade NAT address",
|
|
@@ -13261,6 +15377,23 @@ function checkExpectations(item, result, assertActions) {
|
|
|
13261
15377
|
}
|
|
13262
15378
|
return failures;
|
|
13263
15379
|
}
|
|
15380
|
+
function withExtraCookies(request, extra) {
|
|
15381
|
+
const headers = [];
|
|
15382
|
+
let merged = false;
|
|
15383
|
+
for (const [name, value] of request.headers) {
|
|
15384
|
+
if (!merged && name.toLowerCase() === "cookie") {
|
|
15385
|
+
headers.push([name, [value, ...extra].join("; ")]);
|
|
15386
|
+
merged = true;
|
|
15387
|
+
} else {
|
|
15388
|
+
headers.push([name, value]);
|
|
15389
|
+
}
|
|
15390
|
+
}
|
|
15391
|
+
if (!merged) headers.push(["Cookie", extra.join("; ")]);
|
|
15392
|
+
return { ...request, headers };
|
|
15393
|
+
}
|
|
15394
|
+
function keepsCookies(request) {
|
|
15395
|
+
return request.headers.some(([name]) => name.toLowerCase() === "cookie");
|
|
15396
|
+
}
|
|
13264
15397
|
async function runCase(handler, clock, item, startedAt, provides, assertActions = true) {
|
|
13265
15398
|
const missing = (item.requires ?? []).filter((capability) => !provides.has(capability));
|
|
13266
15399
|
if (missing.length > 0) {
|
|
@@ -13283,11 +15416,24 @@ async function runCase(handler, clock, item, startedAt, provides, assertActions
|
|
|
13283
15416
|
const seed = toFacts(item.requests[0], fallbackIp, clock.now());
|
|
13284
15417
|
clearanceCookie = handler.grantClearance(seed, item.clearance)?.split(";")[0];
|
|
13285
15418
|
}
|
|
15419
|
+
if (item.challengeHistory !== void 0) {
|
|
15420
|
+
clock.set(startedAt);
|
|
15421
|
+
const seed = toFacts(item.requests[0], fallbackIp, clock.now());
|
|
15422
|
+
const key = handler.actorKeyFor(seed);
|
|
15423
|
+
const state = handler.registry.observe(key, seed);
|
|
15424
|
+
for (let i = 0; i < (item.challengeHistory.replayedSolutions ?? 0); i++) state.noteChallengeAnomaly("replay");
|
|
15425
|
+
for (let i = 0; i < (item.challengeHistory.implausibleSolves ?? 0); i++) state.noteChallengeAnomaly("implausible-speed");
|
|
15426
|
+
}
|
|
15427
|
+
let issuedCookies;
|
|
13286
15428
|
for (const request of item.requests) {
|
|
13287
15429
|
clock.set(startedAt + (request.atMs ?? 0));
|
|
13288
|
-
const
|
|
13289
|
-
const
|
|
15430
|
+
const extraCookies = [clearanceCookie, item.keepsCookies ?? keepsCookies(request) ? issuedCookies : void 0].filter((value) => value !== void 0);
|
|
15431
|
+
const withCookies = extraCookies.length === 0 ? request : withExtraCookies(request, extraCookies);
|
|
15432
|
+
const facts = toFacts(withCookies, fallbackIp, clock.now());
|
|
13290
15433
|
const { assessment, decision, outcome } = await handler.handle(facts);
|
|
15434
|
+
const setCookie = outcome.kind === "continue" ? outcome.responseHeaders?.["set-cookie"] : outcome.kind === "respond" ? outcome.headers["set-cookie"] : void 0;
|
|
15435
|
+
if (setCookie !== void 0) issuedCookies = setCookie.split(";")[0];
|
|
15436
|
+
handler.recordOutcome(facts, request.status ?? 200);
|
|
13291
15437
|
requests.push({ assessment, decision, outcome });
|
|
13292
15438
|
}
|
|
13293
15439
|
const final = requests[requests.length - 1];
|
|
@@ -13975,14 +16121,21 @@ function robots(flags) {
|
|
|
13975
16121
|
}
|
|
13976
16122
|
function detectors(flags) {
|
|
13977
16123
|
const preset = flags.get("preset");
|
|
13978
|
-
|
|
13979
|
-
|
|
16124
|
+
if (preset !== void 0 && !(preset in PRESETS)) {
|
|
16125
|
+
process.stderr.write(`Unknown preset "${preset}". One of: ${Object.keys(PRESETS).join(", ")}
|
|
16126
|
+
`);
|
|
16127
|
+
return 1;
|
|
16128
|
+
}
|
|
16129
|
+
const handler = new BotHandler(preset !== void 0 ? { preset } : {});
|
|
16130
|
+
const installed = handler.describeDetectors();
|
|
16131
|
+
for (const entry of installed) {
|
|
13980
16132
|
process.stdout.write(`${entry.id.padEnd(24)} ${entry.cost.padEnd(6)} ${entry.stage.padEnd(11)} ${entry.description}
|
|
13981
16133
|
`);
|
|
13982
16134
|
}
|
|
13983
16135
|
process.stdout.write(`
|
|
13984
|
-
${
|
|
16136
|
+
${installed.length} detectors installed.
|
|
13985
16137
|
`);
|
|
16138
|
+
process.stderr.write("note: a preset selects rules, not detectors. `challenge`, `probe` and `site` are what add to this list.\n");
|
|
13986
16139
|
return 0;
|
|
13987
16140
|
}
|
|
13988
16141
|
var COMMON_LOG = /^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+)(?: (HTTP\/[\d.]+))?" (\d{3}) (\S+)(?: "([^"]*)" "([^"]*)")?/;
|