@agent-custody/receipts 0.16.11 → 0.16.12
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/README.md +14 -5
- package/dist/check.js +12 -0
- package/dist/cli.js +116 -3
- package/dist/config.d.ts +3 -0
- package/dist/config.js +13 -0
- package/dist/door-app.js +1 -1
- package/dist/door-core.d.ts +13 -1
- package/dist/door-core.js +16 -2
- package/dist/door-error-rates.d.ts +102 -0
- package/dist/door-error-rates.js +178 -0
- package/dist/door-form.d.ts +7 -2
- package/dist/door-form.js +52 -4
- package/dist/door-measure.d.ts +153 -0
- package/dist/door-measure.js +325 -0
- package/dist/door-signals.d.ts +414 -0
- package/dist/door-signals.js +555 -0
- package/dist/door-test-set.d.ts +43 -0
- package/dist/door-test-set.js +117 -0
- package/dist/door-worker.d.ts +16 -1
- package/dist/door-worker.js +26 -2
- package/dist/door.js +2 -2
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/lock.d.ts +5 -0
- package/dist/lock.js +1 -1
- package/docs/door-error-rates.md +490 -0
- package/docs/door-languages.md +3 -1
- package/docs/door-middleware.md +6 -1
- package/docs/door-quickstart.md +2 -2
- package/docs/door-signals.md +112 -2
- package/docs/door-worker.md +13 -0
- package/docs/door.md +32 -5
- package/docs/github-action.md +2 -2
- package/docs/tutorials.md +4 -0
- package/package.json +2 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Error rates for the door's signals, from labelled door receipts. What must hold: a rate is reported for one kind of
|
|
2
|
+
// arrival and one label source at a time, never pooled. A pooled rate depends on the mix of kinds in the sample, so it
|
|
3
|
+
// would say nothing about the next site. And only receipts that verify under the door's key are scored.
|
|
4
|
+
import { lstatSync, readdirSync, readFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { ARRIVAL_FACT } from "./door-core.js";
|
|
8
|
+
import { LABELS, LABEL_USES } from "./door-measure.js";
|
|
9
|
+
import { verifyBundle } from "./verify.js";
|
|
10
|
+
/**
|
|
11
|
+
* Where a label came from. `test-set`: the arrival was built to be that kind, so the label is true by construction.
|
|
12
|
+
* `operator`: a person who knows the traffic said so. `challenge`: derived from a passed Turnstile or hCaptcha check,
|
|
13
|
+
* so it carries the provider's own error rate. `door`: the door's own check said so (a verified agent, from
|
|
14
|
+
* `door labels`). Such a label is good for the flags and never for a question about `class`, which would score the
|
|
15
|
+
* door against itself; its `validFor` says so.
|
|
16
|
+
*/
|
|
17
|
+
export const LABEL_SOURCES = ["test-set", "operator", "challenge", "door"];
|
|
18
|
+
/**
|
|
19
|
+
* One line of a labels file: what one receipt's arrival really was. A line that `door labels --receipt-ids` exports is
|
|
20
|
+
* also a record of `door measure`, so the fields of that format are accepted here and not read.
|
|
21
|
+
*/
|
|
22
|
+
export const DoorLabelSchema = z.object({
|
|
23
|
+
receiptId: z.string().min(1),
|
|
24
|
+
/** the kind of arrival, such as `browser` or `forged-signature`; rates are reported per kind */
|
|
25
|
+
kind: z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/, { message: "a kind is lower-case letters, digits, and hyphens, at most 64" }),
|
|
26
|
+
/** a program, not a person at a browser */
|
|
27
|
+
automated: z.boolean(),
|
|
28
|
+
/** the agent it names, under a permission this door accepts for this route; null when it named no agent, or when the label does not say */
|
|
29
|
+
genuine: z.boolean().nullable(),
|
|
30
|
+
source: z.enum(LABEL_SOURCES),
|
|
31
|
+
/** the questions and flags this label is good for; absent when it is good for all. A question that is not in the list does not score the label */
|
|
32
|
+
validFor: z.array(z.enum(LABEL_USES)).optional(),
|
|
33
|
+
set: z.string().optional(),
|
|
34
|
+
session: z.string().optional(),
|
|
35
|
+
label: z.enum(LABELS).optional(),
|
|
36
|
+
labelSource: z.string().optional(),
|
|
37
|
+
flags: z.record(z.string(), z.boolean()).optional(),
|
|
38
|
+
}).strict().refine((l) => l.label === undefined || (l.label === "automated") === l.automated, { message: "label and automated disagree", path: ["label"] });
|
|
39
|
+
/** The questions the door's signals answer today. Each is scored only on the labels it applies to. */
|
|
40
|
+
export const DOOR_QUESTIONS = [
|
|
41
|
+
{
|
|
42
|
+
id: "agent",
|
|
43
|
+
asks: "Does `class` tell a program from a person?",
|
|
44
|
+
wrong: "a program whose class is `unknown`, or a person whose class is not",
|
|
45
|
+
applies: () => true,
|
|
46
|
+
isWrong: (a, l) => (l.automated ? a.class === "unknown" : a.class !== "unknown"),
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: "verified",
|
|
50
|
+
asks: "Is `verified` given to the genuine agent, and only to it?",
|
|
51
|
+
wrong: "a genuine agent that is not `verified`, or an arrival that is not genuine and is",
|
|
52
|
+
applies: (l) => l.genuine !== null,
|
|
53
|
+
isWrong: (a, l) => (l.genuine ? a.class !== "verified" : a.class === "verified"),
|
|
54
|
+
},
|
|
55
|
+
];
|
|
56
|
+
/** The Wilson score interval for `errors` in `n` at 95%. With no errors it still gives an upper bound, which is the honest figure for a small sample. */
|
|
57
|
+
export function wilson(errors, n) {
|
|
58
|
+
if (n === 0)
|
|
59
|
+
return { low: 0, high: 1 };
|
|
60
|
+
const z = 1.959963984540054;
|
|
61
|
+
const p = errors / n;
|
|
62
|
+
const d = 1 + (z * z) / n;
|
|
63
|
+
const centre = p + (z * z) / (2 * n);
|
|
64
|
+
const margin = z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n));
|
|
65
|
+
// at 0 or n errors the bound is exactly 0 or 1; floating point would leave a residue
|
|
66
|
+
return { low: errors === 0 ? 0 : (centre - margin) / d, high: errors === n ? 1 : (centre + margin) / d };
|
|
67
|
+
}
|
|
68
|
+
/** The arrival fact of every door receipt in `dir` that verifies under `issuerKeys`, the principal keys that sign its grants, and the log, when given. Anything else is skipped with its reason. */
|
|
69
|
+
export function readDoorArrivals(dir, opts) {
|
|
70
|
+
const arrivals = new Map();
|
|
71
|
+
const skipped = [];
|
|
72
|
+
for (const file of readdirSync(dir).filter((f) => f.endsWith(".json")).sort()) {
|
|
73
|
+
const path = join(dir, file);
|
|
74
|
+
if (!lstatSync(path).isFile()) {
|
|
75
|
+
skipped.push({ file, reason: "not a regular file" });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const bundle = JSON.parse(readFileSync(path, "utf8"));
|
|
80
|
+
const result = verifyBundle(bundle, { issuerKeys: opts.issuerKeys, principalKeys: opts.principalKeys ?? [], ...(opts.logKeys ? { logKeys: opts.logKeys } : {}), ...(opts.logFile ? { logFile: opts.logFile } : {}) });
|
|
81
|
+
if (!result.ok) {
|
|
82
|
+
skipped.push({ file, reason: `does not verify: ${result.checks.filter((c) => !c.ok).map((c) => c.name).join("; ")}` });
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const p = JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString("utf8")).predicate;
|
|
86
|
+
if (p.issuer.kind !== "door") {
|
|
87
|
+
skipped.push({ file, reason: `issued by a ${p.issuer.kind}, not a door` });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const arrival = p.facts[ARRIVAL_FACT]?.value;
|
|
91
|
+
if (!arrival || typeof arrival !== "object" || typeof arrival.class !== "string") {
|
|
92
|
+
skipped.push({ file, reason: "the arrival fact is withheld or missing; its capture rule must keep facts in clear" });
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
arrivals.set(p.receiptId, arrival);
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
skipped.push({ file, reason: e instanceof Error ? e.message : String(e) });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return { arrivals, skipped };
|
|
102
|
+
}
|
|
103
|
+
/** A labels file: one JSON object per line, as `DoorLabelSchema`. A line that does not parse throws with its number; a receipt labelled twice throws. */
|
|
104
|
+
export function parseLabels(text) {
|
|
105
|
+
const labels = [];
|
|
106
|
+
const seen = new Set();
|
|
107
|
+
text.split("\n").forEach((line, i) => {
|
|
108
|
+
if (!line.trim())
|
|
109
|
+
return;
|
|
110
|
+
let raw;
|
|
111
|
+
try {
|
|
112
|
+
raw = JSON.parse(line);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
throw new Error(`labels line ${i + 1}: not JSON`);
|
|
116
|
+
}
|
|
117
|
+
const r = DoorLabelSchema.safeParse(raw);
|
|
118
|
+
if (!r.success)
|
|
119
|
+
throw new Error(`labels line ${i + 1}: ${r.error.issues.map((x) => `${x.path.join(".") || "line"}: ${x.message}`).join("; ")}`);
|
|
120
|
+
if (seen.has(r.data.receiptId))
|
|
121
|
+
throw new Error(`labels line ${i + 1}: receipt ${r.data.receiptId} is labelled twice`);
|
|
122
|
+
seen.add(r.data.receiptId);
|
|
123
|
+
labels.push(r.data);
|
|
124
|
+
});
|
|
125
|
+
return labels;
|
|
126
|
+
}
|
|
127
|
+
/** Labels from passed challenges, for receipts that have no label: the provider judged a person present. They carry the provider's error rate. */
|
|
128
|
+
export function challengeLabels(arrivals, labelled) {
|
|
129
|
+
const taken = new Set(labelled);
|
|
130
|
+
const out = [];
|
|
131
|
+
for (const [receiptId, a] of arrivals) {
|
|
132
|
+
if (!taken.has(receiptId) && a.challenge?.outcome === "passed")
|
|
133
|
+
out.push({ receiptId, kind: "challenge-passed", automated: false, genuine: null, source: "challenge" });
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
/** One row per question, label source, and kind. `unmatched` lists labels whose receipt was not read or did not verify. */
|
|
138
|
+
export function doorErrorRates(arrivals, labels) {
|
|
139
|
+
const unmatched = [];
|
|
140
|
+
const groups = new Map();
|
|
141
|
+
for (const label of labels) {
|
|
142
|
+
const arrival = arrivals.get(label.receiptId);
|
|
143
|
+
if (!arrival) {
|
|
144
|
+
unmatched.push(label.receiptId);
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
for (const q of DOOR_QUESTIONS) {
|
|
148
|
+
if (!q.applies(label) || (label.validFor && !label.validFor.includes(q.id)))
|
|
149
|
+
continue;
|
|
150
|
+
const key = `${q.id}\0${label.source}\0${label.kind}`;
|
|
151
|
+
const g = groups.get(key) ?? { question: q.id, kind: label.kind, source: label.source, arrivals: 0, wrong: 0 };
|
|
152
|
+
g.arrivals++;
|
|
153
|
+
if (q.isWrong(arrival, label))
|
|
154
|
+
g.wrong++;
|
|
155
|
+
groups.set(key, g);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const order = (id) => DOOR_QUESTIONS.findIndex((q) => q.id === id);
|
|
159
|
+
const rows = [...groups.values()]
|
|
160
|
+
.sort((a, b) => order(a.question) - order(b.question))
|
|
161
|
+
.map((g) => ({ ...g, rate: g.wrong / g.arrivals, ...wilson(g.wrong, g.arrivals) }));
|
|
162
|
+
return { rows, unmatched };
|
|
163
|
+
}
|
|
164
|
+
const pct = (x) => `${(x * 100).toFixed(1)}%`;
|
|
165
|
+
/** The rows as Markdown: a table per question, each row one kind from one label source. */
|
|
166
|
+
export function formatErrorRates(rows) {
|
|
167
|
+
const out = [];
|
|
168
|
+
for (const q of DOOR_QUESTIONS) {
|
|
169
|
+
const mine = rows.filter((r) => r.question === q.id);
|
|
170
|
+
if (!mine.length)
|
|
171
|
+
continue;
|
|
172
|
+
out.push(`**${q.asks}** An error is ${q.wrong}.`, "", "| kind | labels | arrivals | wrong | error rate (lower is better) | 95% interval |", "| --- | --- | ---: | ---: | ---: | --- |");
|
|
173
|
+
for (const r of mine)
|
|
174
|
+
out.push(`| \`${r.kind}\` | ${r.source} | ${r.arrivals} | ${r.wrong} | ${pct(r.rate)} | ${pct(r.low)} to ${pct(r.high)} |`);
|
|
175
|
+
out.push("");
|
|
176
|
+
}
|
|
177
|
+
return out.join("\n");
|
|
178
|
+
}
|
package/dist/door-form.d.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import type { DoorConfig } from "./config.ts";
|
|
2
2
|
export declare const FORM_SCRIPT_PATH = "/.well-known/agent-custody-door/form.js";
|
|
3
3
|
type Challenge = NonNullable<DoorConfig["challenge"]>;
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* The browser script for a door's challenge config. Public: it carries the provider, the site key, the header, and the
|
|
6
|
+
* action. With `report` the script also sends the form report: the time from the first key press, pointer press, click,
|
|
7
|
+
* or paste in the form to the submit, the counts of key presses and pointer presses, whether a paste happened, and
|
|
8
|
+
* whether every event was trusted.
|
|
9
|
+
*/
|
|
10
|
+
export declare function formScript(challenge: Challenge, report?: boolean): string;
|
|
6
11
|
export {};
|
package/dist/door-form.js
CHANGED
|
@@ -1,10 +1,58 @@
|
|
|
1
|
+
import { FORM_REPORT_HEADER, MAX_FORM_EVENTS, MAX_FORM_FILL_MS } from "./door-signals.js";
|
|
1
2
|
export const FORM_SCRIPT_PATH = "/.well-known/agent-custody-door/form.js";
|
|
2
3
|
const PROVIDER_SCRIPT = {
|
|
3
4
|
turnstile: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",
|
|
4
5
|
hcaptcha: "https://js.hcaptcha.com/1/api.js?render=explicit",
|
|
5
6
|
};
|
|
6
|
-
/**
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* The browser script for a door's challenge config. Public: it carries the provider, the site key, the header, and the
|
|
9
|
+
* action. With `report` the script also sends the form report: the time from the first key press, pointer press, click,
|
|
10
|
+
* or paste in the form to the submit, the counts of key presses and pointer presses, whether a paste happened, and
|
|
11
|
+
* whether every event was trusted.
|
|
12
|
+
*/
|
|
13
|
+
export function formScript(challenge, report = false) {
|
|
14
|
+
// a click with no pointer press before it (a keyboard or an assistive tool pressed the button) counts as a pointer press
|
|
15
|
+
const count = report ? `
|
|
16
|
+
// the form report: counts only, no field value and no key identity
|
|
17
|
+
const started = performance.now();
|
|
18
|
+
let first = -1, keys = 0, pointers = 0, pasted = 0, trusted = 1, down = false, moves = 0, lastKey = -1, shortest = -1, longest = -1;
|
|
19
|
+
const saw = (event) => {
|
|
20
|
+
if (first < 0) first = performance.now();
|
|
21
|
+
if (!event.isTrusted) trusted = 0;
|
|
22
|
+
};
|
|
23
|
+
// on the document, since a control outside the form element can belong to it (a button with form="id")
|
|
24
|
+
const mine = (event) => {
|
|
25
|
+
const target = event.target;
|
|
26
|
+
return !!target && (target.form === form || (typeof target.closest === "function" && target.closest("form") === form));
|
|
27
|
+
};
|
|
28
|
+
const on = (type, count) => document.addEventListener(type, (event) => { if (mine(event)) count(event); }, true);
|
|
29
|
+
on("keydown", (event) => {
|
|
30
|
+
if (event.repeat) return;
|
|
31
|
+
saw(event);
|
|
32
|
+
keys++;
|
|
33
|
+
const now = performance.now();
|
|
34
|
+
if (lastKey >= 0) {
|
|
35
|
+
const gap = now - lastKey;
|
|
36
|
+
if (shortest < 0 || gap < shortest) shortest = gap;
|
|
37
|
+
if (gap > longest) longest = gap;
|
|
38
|
+
}
|
|
39
|
+
lastKey = now;
|
|
40
|
+
});
|
|
41
|
+
// moves do not start the fill: a pointer crosses a form on its way elsewhere
|
|
42
|
+
on("pointermove", () => { moves++; });
|
|
43
|
+
on("touchmove", () => { moves++; });
|
|
44
|
+
on("pointerdown", (event) => { saw(event); down = true; pointers++; });
|
|
45
|
+
on("click", (event) => { saw(event); if (!down) pointers++; down = false; });
|
|
46
|
+
on("paste", (event) => { saw(event); pasted = 1; });
|
|
47
|
+
const filled = (event) => {
|
|
48
|
+
const ms = first < 0 ? 0 : Math.min(Math.max(Math.round(performance.now() - first), 0), ${MAX_FORM_FILL_MS});
|
|
49
|
+
const cut = (v) => Math.min(Math.max(Math.round(v), 0), ${MAX_FORM_FILL_MS});
|
|
50
|
+
const value = "v=2;ms=" + ms + ";k=" + Math.min(keys, ${MAX_FORM_EVENTS}) + ";p=" + Math.min(pointers, ${MAX_FORM_EVENTS}) + ";paste=" + pasted + ";trusted=" + (event.isTrusted ? trusted : 0)
|
|
51
|
+
+ ";mv=" + Math.min(moves, ${MAX_FORM_EVENTS}) + ";ks=" + (keys > 2 ? cut(longest - shortest) : 0) + ";rd=" + (first < 0 ? 0 : cut(first - started));
|
|
52
|
+
first = -1; keys = 0; pointers = 0; pasted = 0; trusted = 1; down = false; moves = 0; lastKey = -1; shortest = -1; longest = -1;
|
|
53
|
+
return value;
|
|
54
|
+
};` : "";
|
|
55
|
+
const send = report ? `{ [settings.header]: token, ${JSON.stringify(FORM_REPORT_HEADER)}: filled(event) }` : "{ [settings.header]: token }";
|
|
8
56
|
const settings = { provider: challenge.provider, siteKey: challenge.siteKey, header: challenge.header, src: PROVIDER_SCRIPT[challenge.provider], ...(challenge.action ? { action: challenge.action } : {}) };
|
|
9
57
|
return `// agent-custody door: form protector. Load it with a script tag, src ${FORM_SCRIPT_PATH} and defer; data-forms on the tag selects the forms.
|
|
10
58
|
(() => {
|
|
@@ -33,7 +81,7 @@ export function formScript(challenge) {
|
|
|
33
81
|
options["response-field"] = false;
|
|
34
82
|
if (settings.action) options.action = settings.action;
|
|
35
83
|
}
|
|
36
|
-
const widget = api().render(box, options)
|
|
84
|
+
const widget = api().render(box, options);${count}
|
|
37
85
|
let sending = false;
|
|
38
86
|
form.addEventListener("submit", async (event) => {
|
|
39
87
|
// a button's formaction, formmethod, and formenctype override the form's; a GET or another site's action goes natively
|
|
@@ -59,7 +107,7 @@ export function formScript(challenge) {
|
|
|
59
107
|
for (const field of tokenFields) data.delete(field);
|
|
60
108
|
const multipart = (attr("formenctype", form.getAttribute("enctype")) || "").toLowerCase() === "multipart/form-data";
|
|
61
109
|
try {
|
|
62
|
-
const res = await fetch(to, { method: "POST", body: multipart ? data : new URLSearchParams(data), headers: {
|
|
110
|
+
const res = await fetch(to, { method: "POST", body: multipart ? data : new URLSearchParams(data), headers: ${send}, credentials: "same-origin", signal: AbortSignal.timeout(30000) });
|
|
63
111
|
if (res.redirected) return location.assign(res.url);
|
|
64
112
|
const type = res.headers.get("content-type") || "";
|
|
65
113
|
if (res.status === 403 && type.includes("application/json")) {
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { type FlagSignal, type Observation, type Signals } from "./door-signals.ts";
|
|
2
|
+
import type { ReceiptPredicate } from "./receipt.ts";
|
|
3
|
+
export declare const LABELS: readonly ["human", "automated"];
|
|
4
|
+
export type Label = (typeof LABELS)[number];
|
|
5
|
+
/** The questions about `class` that `door error-rates` scores (src/door-error-rates.ts). */
|
|
6
|
+
export declare const LABEL_QUESTIONS: readonly ["agent", "verified"];
|
|
7
|
+
export type LabelQuestion = (typeof LABEL_QUESTIONS)[number];
|
|
8
|
+
/** What a label can be good for: a question about `class`, or a flag. `validFor` holds these names in both label formats. */
|
|
9
|
+
export declare const LABEL_USES: readonly ["agent", "verified", "fingerprint.headers.mismatch", "fingerprint.headers.hintsMismatch", "fingerprint.headers.fetchInvalid", "fingerprint.tls.mismatch", "fingerprint.tls.knownTool", "behaviour.timing.regular", "behaviour.navigation.directWrite", "behaviour.form.fast", "behaviour.form.noInput"];
|
|
10
|
+
export type LabelUse = (typeof LABEL_USES)[number];
|
|
11
|
+
/** The value of each flag that applies to one arrival. A flag that does not apply is absent. */
|
|
12
|
+
export type FlagValues = Partial<Record<FlagSignal, boolean>>;
|
|
13
|
+
/**
|
|
14
|
+
* One line of a labelled set (JSON Lines). It has `observation`, which the measure replays, or `flags`, which a door
|
|
15
|
+
* computed when the arrival came. The records of one session are in time order.
|
|
16
|
+
*/
|
|
17
|
+
export interface LabelledRecord {
|
|
18
|
+
/** the name of the labelled set */
|
|
19
|
+
set: string;
|
|
20
|
+
/** the session inside the set: one client over one period */
|
|
21
|
+
session: string;
|
|
22
|
+
label: Label;
|
|
23
|
+
/** how the label was assigned */
|
|
24
|
+
labelSource: string;
|
|
25
|
+
/** what this label is good for; absent when it is good for every flag and question. A flag that is not in the list does not count the record */
|
|
26
|
+
validFor?: LabelUse[];
|
|
27
|
+
/** what was recorded of the arrival; `at` is the recorded time in milliseconds */
|
|
28
|
+
observation?: Observation;
|
|
29
|
+
/** for a record exported from a door: the flags the door computed */
|
|
30
|
+
flags?: FlagValues;
|
|
31
|
+
/**
|
|
32
|
+
* The fields of a `door error-rates` label (`DoorLabelSchema`), on a record that `door labels` exports. The measure
|
|
33
|
+
* does not read them. `automated` says what `label` says.
|
|
34
|
+
*/
|
|
35
|
+
receiptId?: string;
|
|
36
|
+
kind?: string;
|
|
37
|
+
automated?: boolean;
|
|
38
|
+
genuine?: boolean | null;
|
|
39
|
+
source?: string;
|
|
40
|
+
}
|
|
41
|
+
/** A count with its rate. `rate`, `low`, and `high` are integers per 10,000, and null when `n` is 0: not measured. */
|
|
42
|
+
export interface Rate {
|
|
43
|
+
/** how many arrivals, or sessions, the flag applies to */
|
|
44
|
+
n: number;
|
|
45
|
+
flagged: number;
|
|
46
|
+
rate: number | null;
|
|
47
|
+
/** the 95% Wilson interval, rounded outward */
|
|
48
|
+
low: number | null;
|
|
49
|
+
high: number | null;
|
|
50
|
+
}
|
|
51
|
+
export interface SideMeasure {
|
|
52
|
+
/** each arrival counts once */
|
|
53
|
+
arrivals: Rate;
|
|
54
|
+
/** each session counts once; a session is flagged when one of its arrivals is */
|
|
55
|
+
sessions: Rate;
|
|
56
|
+
}
|
|
57
|
+
export interface FlagMeasure {
|
|
58
|
+
flag: FlagSignal;
|
|
59
|
+
/** the false-positive rate: humans that the flag marks */
|
|
60
|
+
human: SideMeasure;
|
|
61
|
+
/** the detection rate: automated clients that the flag marks */
|
|
62
|
+
automated: SideMeasure;
|
|
63
|
+
}
|
|
64
|
+
export interface SetMeasure {
|
|
65
|
+
set: string;
|
|
66
|
+
arrivals: Record<Label, number>;
|
|
67
|
+
sessions: Record<Label, number>;
|
|
68
|
+
/** arrivals per label source */
|
|
69
|
+
labelSources: Record<Label, Record<string, number>>;
|
|
70
|
+
flags: FlagMeasure[];
|
|
71
|
+
}
|
|
72
|
+
export interface MeasureResult {
|
|
73
|
+
format: "agent-custody/door-measure/v1";
|
|
74
|
+
/** `rate`, `low`, and `high` are integers per this many */
|
|
75
|
+
per: 10000;
|
|
76
|
+
/** the confidence level of the Wilson interval, in percent */
|
|
77
|
+
confidencePercent: 95;
|
|
78
|
+
/** the constants of door-signals.ts that the flags read, as they were for this measure */
|
|
79
|
+
thresholds: Record<string, unknown>;
|
|
80
|
+
sets: SetMeasure[];
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Every exported constant of door-signals.ts that a flag reads. A result measured with other values does not describe
|
|
84
|
+
* this door. The rules that read a User-Agent (`statedClient`, the embedded-Chromium forms) are code and not constants:
|
|
85
|
+
* a change to them needs a new measure too, and this record does not show it.
|
|
86
|
+
*/
|
|
87
|
+
export declare function thresholds(): Record<string, unknown>;
|
|
88
|
+
/** The rate `flagged / n` and its 95% Wilson score interval, as integers per 10,000. The interval is rounded outward. */
|
|
89
|
+
export declare function rateOf(flagged: number, n: number): Rate;
|
|
90
|
+
/**
|
|
91
|
+
* The flags that apply to an arrival, from its signals. The header flag applies only when the record has the header
|
|
92
|
+
* names. The client-hints flag applies only when the arrival sent `sec-ch-ua`, and the Fetch Metadata flag only when it
|
|
93
|
+
* sent a `sec-fetch-*` header: without them the flag is false by construction. The TLS flags apply only when a well-formed JA4 arrived. The form flags apply only to a well-formed form report.
|
|
94
|
+
*/
|
|
95
|
+
export declare function flagValues(signals: Pick<Signals, "fingerprint" | "behaviour">, hasHeaders: boolean): FlagValues;
|
|
96
|
+
/** True when the text can be the name of a set, a session, or a label source. */
|
|
97
|
+
export declare const isName: (v: unknown) => v is string;
|
|
98
|
+
/**
|
|
99
|
+
* A labelled record from one line of a set. Throws with the reason when the line is not one. Every field of the
|
|
100
|
+
* observation has its type checked here, so the replay never meets a number where the door's code reads text. The
|
|
101
|
+
* method is in upper case, as the door records it.
|
|
102
|
+
*/
|
|
103
|
+
export declare function parseLabelledRecord(line: string): LabelledRecord;
|
|
104
|
+
export interface Measure {
|
|
105
|
+
/** counts one record; throws when a session changes its label or goes back in time */
|
|
106
|
+
add(record: LabelledRecord): void;
|
|
107
|
+
result(): MeasureResult;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Counts labelled records as they come, so a large set is never held whole. Each session has its own history, as one
|
|
111
|
+
* source has at the door, and its records must come in time order. The memory grows with the number of sessions.
|
|
112
|
+
*/
|
|
113
|
+
export declare function createMeasure(): Measure;
|
|
114
|
+
/** The measure of a set that fits in memory. The records of each session are sorted by their recorded time first. */
|
|
115
|
+
export declare function measure(records: Iterable<LabelledRecord>): MeasureResult;
|
|
116
|
+
/**
|
|
117
|
+
* An integer per 10,000 as a percentage with one decimal. `down` and `up` round to the printed digit in that direction:
|
|
118
|
+
* a bound of an interval is printed outward, so the printed interval is never narrower than the computed one.
|
|
119
|
+
*/
|
|
120
|
+
export declare function percent(per10k: number, round?: "nearest" | "down" | "up"): string;
|
|
121
|
+
/** The rate of a measured count as a percentage. A count above zero that rounds to 0.0% is `<0.1%`, so that it does not read as zero. */
|
|
122
|
+
export declare function ratePercent(r: Rate): string;
|
|
123
|
+
/** The interval of a measured count as text, each bound printed outward: `0.2% to 3.7%`. */
|
|
124
|
+
export declare function intervalText(r: Rate): string;
|
|
125
|
+
/** One rate as text: `3/200 = 1.5% (0.5% to 4.4%)`, or `not measured` when the flag applies to nothing. */
|
|
126
|
+
export declare function formatRate(r: Rate): string;
|
|
127
|
+
/** The result as text: for each set, each flag, with both sides per session and per arrival. */
|
|
128
|
+
export declare function formatMeasure(result: MeasureResult): string;
|
|
129
|
+
export interface LabelExport {
|
|
130
|
+
records: LabelledRecord[];
|
|
131
|
+
/** door receipts read */
|
|
132
|
+
read: number;
|
|
133
|
+
/** receipts of a door that had no `behaviour` config: no flag to export */
|
|
134
|
+
noSignals: number;
|
|
135
|
+
/** arrivals with no label: no passed challenge and no verified agent */
|
|
136
|
+
unlabelled: number;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* A labelled set from a door's own verified receipts. An arrival that passed the challenge is `human`
|
|
140
|
+
* (`challenge-passed`); an arrival of a verified agent is `automated` (`verified-agent`); the rest have no label and
|
|
141
|
+
* are left out, as is a verified agent that passed the challenge. A record holds the label and the flags only. The session is a number: the door's source (the agent, else
|
|
142
|
+
* the address), cut where it is silent for `HISTORY_WINDOW_MS`. No path, address, agent name, header, or time leaves.
|
|
143
|
+
*
|
|
144
|
+
* Each record also holds the label in the fields of `door error-rates`: `kind`, `automated`, `genuine`, and `source`.
|
|
145
|
+
* `genuine` is always null: a receipt does not say whether an agent is the agent that it names, except through the
|
|
146
|
+
* door's own check, and that check is what `door error-rates` scores. The label of a verified agent is the door's own
|
|
147
|
+
* word (`source: "door"`), so its `validFor` holds the flags only and no question about `class` counts it. With
|
|
148
|
+
* `receiptIds` a record has its `receiptId`, which `door error-rates --labels` needs. The id names one receipt of the
|
|
149
|
+
* operator, so it is off unless asked for.
|
|
150
|
+
*/
|
|
151
|
+
export declare function labelsFromReceipts(predicates: Iterable<ReceiptPredicate>, set: string, opts?: {
|
|
152
|
+
receiptIds?: boolean;
|
|
153
|
+
}): LabelExport;
|