agentrail-core 0.1.0 → 0.3.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/README.md CHANGED
@@ -1,27 +1,29 @@
1
1
  # agentrail-core
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/agentrail-core)](https://www.npmjs.com/package/agentrail-core)
4
+ [![License](https://img.shields.io/github/license/agentrail-co/agentrail-js)](https://github.com/agentrail-co/agentrail-js/blob/main/LICENSE)
5
+
3
6
  What every Agentrail component shares, wherever the Fetch API and WebCrypto
4
- run (Cloudflare Workers, Vercel's edge, Node, browsers): the event the
5
- collector takes, as types; markers, minted and read (`parseMarker`) as the
6
- collector's engine reads them; the keyed hash a workspace hashes addresses
7
- and principals with, and its key's id; W3C trace context; the session
8
- cookie, which ends after 30 minutes idle and a day at most, its id a UUIDv7
9
- that carries its start; and the collector client. Its `send(event,
10
- deadline)` resolves once the call carrying the event has ended: one call is
11
- under way at a time, and what is sent meanwhile goes in the next, together.
12
- It retries what the network or the collector failed after a random wait,
13
- never sooner than a `Retry-After`, ends every call by its deadline, and
14
- tells `onError` of every call given up.
15
-
16
- `agentrail-edge` and `agentrail-browser` are built on it; a component of
17
- your own can be too.
7
+ run: the event the collector takes, markers, the workspace's keyed hash, W3C
8
+ trace context, the session cookie, the signed trace handoff, the Web Bot Auth
9
+ check and the client that sends events to the collector.
10
+
11
+ **To record a site, install one of these instead**:
12
+ [`agentrail-edge`](https://www.npmjs.com/package/agentrail-edge),
13
+ [`agentrail-browser`](https://www.npmjs.com/package/agentrail-browser) or
14
+ [`agentrail-node`](https://www.npmjs.com/package/agentrail-node). They are
15
+ built on this package. Install it directly only to build a component of your
16
+ own:
18
17
 
19
18
  ```sh
20
19
  npm install agentrail-core
21
20
  ```
22
21
 
22
+ Start from the [repository README](https://github.com/agentrail-co/agentrail-js#readme)
23
+ and the [Journeys guide](https://www.agentrail.co/docs/guides/journeys).
24
+
23
25
  Before 1.0, a minor version (0.1 to 0.2) may change what the package offers.
24
26
 
25
27
  ## Licence
26
28
 
27
- [Apache-2.0](LICENSE).
29
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-js/blob/main/LICENSE).
package/dist/event.d.ts CHANGED
@@ -16,11 +16,24 @@ export type ClockSource = 'edge' | 'backend' | 'browser' | 'third_party';
16
16
  export type SpanKind = 'server' | 'client' | 'internal' | 'producer' | 'consumer';
17
17
  /** What a verified principal is. Self-reported identity is never a principal. */
18
18
  export type PrincipalKind = 'user' | 'agent_registration' | 'agent_instance' | 'oauth_client' | 'api_key';
19
+ /**
20
+ * What became of a request's Web Bot Auth signature at the component that
21
+ * saw it; only `verified` says who sent the request.
22
+ */
23
+ export type SignatureOutcome = 'verified' | 'invalid' | 'directory_unreachable' | 'unsupported' | 'unchecked';
19
24
  export type RegistrationPhase = 'created' | 'claim_completed' | 'expired' | 'revoked';
20
25
  export interface SpanContext {
21
26
  readonly traceId: string;
22
27
  readonly spanId: string;
23
28
  }
29
+ /** Approximate network location, resolved before the client address is hashed. */
30
+ export interface IpLocation {
31
+ readonly country: string | null;
32
+ readonly region: string | null;
33
+ readonly city: string | null;
34
+ readonly source: 'dbip' | 'cloudflare' | 'vercel' | 'source';
35
+ readonly observedAt: string;
36
+ }
24
37
  export interface AgentrailEvent {
25
38
  /** Bumped when a field's meaning changes; stored events are read back. */
26
39
  readonly schemaVersion: 1;
@@ -67,12 +80,56 @@ export interface AgentrailEvent {
67
80
  /** The addresses on the site's own hosts a response named, as requested. */
68
81
  readonly linksOut: string[];
69
82
  } | null;
70
- /** Self-reported or network facts: features, never proofs. */
83
+ /**
84
+ * Self-reported or network facts: features, never proofs, and what the
85
+ * collector's classifier of who the caller is reads. A component sends
86
+ * each of the later ones where it captured it; the collector fills null
87
+ * where a component sent nothing.
88
+ */
71
89
  readonly actor: {
72
90
  /** Keyed hash of the client address. */
73
91
  readonly egress: string | null;
92
+ readonly location?: IpLocation | null | undefined;
74
93
  readonly userAgent: string | null;
94
+ /** MCP `clientInfo` name, or another client self-description. */
75
95
  readonly client: string | null;
96
+ /** The client software's own version: an MCP `clientInfo.version`. */
97
+ readonly clientVersion?: string | null | undefined;
98
+ /** The protocol version the client spoke. */
99
+ readonly protocol?: string | null | undefined;
100
+ /** The `Accept` the request sent. */
101
+ readonly accept?: string | null | undefined;
102
+ /**
103
+ * What the caller's HTTP library wrote: its header names, comma-joined
104
+ * and never a value, and the `Accept-Encoding` it sent (null for none).
105
+ */
106
+ readonly transport?: {
107
+ readonly headerNames: string;
108
+ readonly acceptEncoding: string | null;
109
+ } | null | undefined;
110
+ /** `Sec-Fetch-Site`, `-Mode` and `-Dest`, which a browser sends and a programmatic fetcher does not. */
111
+ readonly fetchMetadata?: {
112
+ readonly site: string;
113
+ readonly mode: string;
114
+ readonly dest: string;
115
+ } | null | undefined;
116
+ /** What the network said of the client, where the platform tells it: a feature, never a key. */
117
+ readonly network?: {
118
+ readonly asn: number | null;
119
+ readonly country: string | null;
120
+ readonly ja4: string | null;
121
+ } | null | undefined;
122
+ /** A Web Bot Auth signature: the agent URL it named, its key id, and what became of the check. */
123
+ readonly signature?: {
124
+ readonly agent: string;
125
+ readonly keyId: string | null;
126
+ readonly outcome: SignatureOutcome;
127
+ } | null | undefined;
128
+ /** A bot the platform verified against its own directory. */
129
+ readonly verifiedBot?: {
130
+ readonly category: string;
131
+ readonly name: string | null;
132
+ } | null | undefined;
76
133
  };
77
134
  /** A verified identity, its ids keyed hashes. */
78
135
  readonly principal: {
@@ -94,12 +151,28 @@ export interface AgentrailEvent {
94
151
  /** Marker strings found in this step's request, as received. */
95
152
  readonly seen: string[];
96
153
  };
154
+ /**
155
+ * A WebMCP tool run's facts (kind `agent.tool.executed`): never its
156
+ * arguments or result, only their JSON size.
157
+ */
158
+ readonly webmcp?: WebMcpRun | null | undefined;
97
159
  /** What was hashed or dropped here, and why. */
98
160
  readonly redactions: {
99
161
  readonly field: string;
100
162
  readonly reason: string;
101
163
  }[];
102
164
  }
165
+ /** How a WebMCP tool run ended: `is_error` for a result that said it failed. */
166
+ export type WebMcpOutcome = 'answered' | 'threw' | 'is_error';
167
+ export interface WebMcpRun {
168
+ /** The tool's name; null where it does not match `^[A-Za-z0-9_./-]{1,128}$`. */
169
+ readonly tool: string | null;
170
+ readonly outcome: WebMcpOutcome;
171
+ /** The UTF-8 size of the arguments' JSON; null where they have none. */
172
+ readonly argumentBytes: number | null;
173
+ /** The UTF-8 size of the result's JSON; null where it threw or has none. */
174
+ readonly resultBytes: number | null;
175
+ }
103
176
  /** The capture code that sent a call, and the surfaces it is set up to capture. */
104
177
  export interface Component {
105
178
  readonly name: string;
package/dist/index.d.ts CHANGED
@@ -4,11 +4,13 @@
4
4
  * trace context, the session, and the client that sends events. Nothing
5
5
  * here imports Node, the DOM or OpenTelemetry.
6
6
  */
7
- export { SURFACES, type AgentrailEvent, type ClockSource, type Component, type PrincipalKind, type RegistrationPhase, type SpanContext, type SpanKind, type Surface, } from './event.js';
7
+ export { SURFACES, type AgentrailEvent, type IpLocation, type ClockSource, type Component, type PrincipalKind, type RegistrationPhase, type SignatureOutcome, type SpanContext, type SpanKind, type Surface, type WebMcpOutcome, type WebMcpRun, } from './event.js';
8
8
  export { MAX_LINK_INDEX, MarkerError, linkMarker, mintMarker, newMarker, parseMarker, type ParsedMarker, } from './marker.js';
9
9
  export { SessionTimeoutError, newSessionId, sessionCookie, sessionStartOf, type SessionCookie, type SessionCookieOptions, } from './session.js';
10
10
  export { hashKeyIdOf, keyedHash } from './hash.js';
11
+ export { TRACE_HANDOFF_HEADER, TraceHandoffInputError, readTraceHandoff, encodeTraceHandoff, signTraceHandoff, traceHandoffTarget, verifyTraceHandoff, type TraceHandoffInput, type TraceHandoffVerification, type TraceHandoffVerificationInput, type TraceHandoffRefusal, } from './trace-handoff.js';
11
12
  export { newId } from './id.js';
13
+ export { KNOWN_SIGNERS, SIGNATURE_CHECK_OUTCOMES, createSignatureVerifier, keyThumbprint, type SignatureCheckOutcome, type SignatureVerifier, type SignatureVerifierOptions, type SignedAgent, type SignedRequest, } from './web-bot-auth.js';
12
14
  export { VERSION } from './version.js';
13
15
  export { formatTraceparent, newSpanId, newTraceId, parseTraceparent, } from './trace.js';
14
16
  export { CollectorFailedError, CollectorRefusedError, CollectorUnavailableError, createCollector, type Collector, type CollectorOptions, } from './collector.js';
package/dist/index.js CHANGED
@@ -8,7 +8,9 @@ export { SURFACES, } from './event.js';
8
8
  export { MAX_LINK_INDEX, MarkerError, linkMarker, mintMarker, newMarker, parseMarker, } from './marker.js';
9
9
  export { SessionTimeoutError, newSessionId, sessionCookie, sessionStartOf, } from './session.js';
10
10
  export { hashKeyIdOf, keyedHash } from './hash.js';
11
+ export { TRACE_HANDOFF_HEADER, TraceHandoffInputError, readTraceHandoff, encodeTraceHandoff, signTraceHandoff, traceHandoffTarget, verifyTraceHandoff, } from './trace-handoff.js';
11
12
  export { newId } from './id.js';
13
+ export { KNOWN_SIGNERS, SIGNATURE_CHECK_OUTCOMES, createSignatureVerifier, keyThumbprint, } from './web-bot-auth.js';
12
14
  export { VERSION } from './version.js';
13
15
  export { formatTraceparent, newSpanId, newTraceId, parseTraceparent, } from './trace.js';
14
16
  export { CollectorFailedError, CollectorRefusedError, CollectorUnavailableError, createCollector, } from './collector.js';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The part of HTTP Structured Fields (RFC 8941) that HTTP Message Signatures
3
+ * (RFC 9421) and Web Bot Auth put in headers: a Dictionary whose members are
4
+ * Items or Inner Lists, each with Parameters; Strings, Tokens, Integers,
5
+ * Decimals, Booleans and Byte Sequences as bare items. Read strictly, as the
6
+ * RFC's algorithms read them: a header that does not parse is no signature.
7
+ */
8
+ export type BareItem = {
9
+ readonly kind: 'string';
10
+ readonly value: string;
11
+ } | {
12
+ readonly kind: 'token';
13
+ readonly value: string;
14
+ } | {
15
+ readonly kind: 'integer';
16
+ readonly value: number;
17
+ } | {
18
+ readonly kind: 'decimal';
19
+ readonly value: number;
20
+ } | {
21
+ readonly kind: 'boolean';
22
+ readonly value: boolean;
23
+ } | {
24
+ readonly kind: 'bytes';
25
+ readonly value: Uint8Array<ArrayBuffer>;
26
+ };
27
+ export type Parameters = ReadonlyMap<string, BareItem>;
28
+ export interface Item {
29
+ readonly kind: 'item';
30
+ readonly value: BareItem;
31
+ readonly parameters: Parameters;
32
+ }
33
+ export interface InnerList {
34
+ readonly kind: 'inner-list';
35
+ readonly items: readonly Item[];
36
+ readonly parameters: Parameters;
37
+ }
38
+ export type Member = Item | InnerList;
39
+ /** A header that is not the structured field its name promises. */
40
+ export declare class StructuredFieldError extends Error {
41
+ readonly name = "StructuredFieldError";
42
+ }
43
+ /** A Dictionary: `key=value, key=(a b);p=1, flag`. A key given twice keeps the last. */
44
+ export declare function parseDictionary(text: string): Map<string, Member>;
45
+ /** One Item on its own: `"https://signer.example"` or `token;p=1`. */
46
+ export declare function parseItem(text: string): Item;
47
+ /** A bare item as the RFC writes it, for a signature base's component lines. */
48
+ export declare function serializeBareItem(item: BareItem): string;
49
+ export declare function serializeParameters(parameters: Parameters): string;
50
+ export declare function serializeItem(item: Item): string;
51
+ export declare function serializeInnerList(list: InnerList): string;
@@ -0,0 +1,246 @@
1
+ /**
2
+ * The part of HTTP Structured Fields (RFC 8941) that HTTP Message Signatures
3
+ * (RFC 9421) and Web Bot Auth put in headers: a Dictionary whose members are
4
+ * Items or Inner Lists, each with Parameters; Strings, Tokens, Integers,
5
+ * Decimals, Booleans and Byte Sequences as bare items. Read strictly, as the
6
+ * RFC's algorithms read them: a header that does not parse is no signature.
7
+ */
8
+ /** A header that is not the structured field its name promises. */
9
+ export class StructuredFieldError extends Error {
10
+ name = 'StructuredFieldError';
11
+ }
12
+ const TOKEN_START = /^[A-Za-z*]$/u;
13
+ const TOKEN_CHAR = /^[A-Za-z0-9!#$%&'*+\-.^_`|~:/]$/u;
14
+ const KEY_START = /^[a-z*]$/u;
15
+ const KEY_CHAR = /^[a-z0-9_\-.*]$/u;
16
+ const BASE64 = /^[A-Za-z0-9+/=]*$/u;
17
+ class Reader {
18
+ text;
19
+ position = 0;
20
+ constructor(text) {
21
+ this.text = text;
22
+ }
23
+ peek() {
24
+ return this.text.charAt(this.position);
25
+ }
26
+ next() {
27
+ const char = this.text.charAt(this.position);
28
+ this.position += 1;
29
+ return char;
30
+ }
31
+ done() {
32
+ return this.position >= this.text.length;
33
+ }
34
+ /** Skips spaces, as the RFC's "discard any leading SP characters". */
35
+ skipSpaces() {
36
+ while (this.peek() === ' ')
37
+ this.position += 1;
38
+ }
39
+ /** Skips optional whitespace: spaces and tabs. */
40
+ skipWhitespace() {
41
+ while (this.peek() === ' ' || this.peek() === '\t')
42
+ this.position += 1;
43
+ }
44
+ expect(char) {
45
+ if (this.next() !== char)
46
+ throw new StructuredFieldError(`Expected "${char}" at ${this.position}.`);
47
+ }
48
+ }
49
+ function readKey(reader) {
50
+ if (!KEY_START.test(reader.peek()))
51
+ throw new StructuredFieldError(`A key starts with a letter or "*".`);
52
+ let key = '';
53
+ while (!reader.done() && KEY_CHAR.test(reader.peek()))
54
+ key += reader.next();
55
+ return key;
56
+ }
57
+ function readString(reader) {
58
+ reader.expect('"');
59
+ let value = '';
60
+ for (;;) {
61
+ if (reader.done())
62
+ throw new StructuredFieldError('An unclosed string.');
63
+ const char = reader.next();
64
+ if (char === '\\') {
65
+ const escaped = reader.next();
66
+ if (escaped !== '"' && escaped !== '\\')
67
+ throw new StructuredFieldError('A string escapes only quotes and backslashes.');
68
+ value += escaped;
69
+ }
70
+ else if (char === '"')
71
+ return value;
72
+ else if (char < ' ' || char > '~')
73
+ throw new StructuredFieldError('A string holds printable ASCII only.');
74
+ else
75
+ value += char;
76
+ }
77
+ }
78
+ function readToken(reader) {
79
+ let value = '';
80
+ while (!reader.done() && TOKEN_CHAR.test(reader.peek()))
81
+ value += reader.next();
82
+ return value;
83
+ }
84
+ function readNumber(reader) {
85
+ let text = '';
86
+ if (reader.peek() === '-')
87
+ text += reader.next();
88
+ while (!reader.done() && /^[0-9.]$/u.test(reader.peek()))
89
+ text += reader.next();
90
+ if (!/^-?[0-9]+(?:\.[0-9]{1,3})?$/u.test(text) || text.length > 16)
91
+ throw new StructuredFieldError(`"${text}" is not a number.`);
92
+ return text.includes('.')
93
+ ? { kind: 'decimal', value: Number(text) }
94
+ : { kind: 'integer', value: Number(text) };
95
+ }
96
+ function readBytes(reader) {
97
+ reader.expect(':');
98
+ let encoded = '';
99
+ while (!reader.done() && reader.peek() !== ':')
100
+ encoded += reader.next();
101
+ reader.expect(':');
102
+ if (!BASE64.test(encoded))
103
+ throw new StructuredFieldError('A byte sequence is base64.');
104
+ let binary;
105
+ try {
106
+ binary = atob(encoded);
107
+ }
108
+ catch (error) {
109
+ // Base64 of a length no bytes have: a field that does not parse.
110
+ if (error instanceof DOMException)
111
+ throw new StructuredFieldError('A byte sequence is whole base64.');
112
+ throw error;
113
+ }
114
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
115
+ }
116
+ function readBareItem(reader) {
117
+ const char = reader.peek();
118
+ if (char === '"')
119
+ return { kind: 'string', value: readString(reader) };
120
+ if (char === ':')
121
+ return { kind: 'bytes', value: readBytes(reader) };
122
+ if (char === '?') {
123
+ reader.next();
124
+ const flag = reader.next();
125
+ if (flag !== '0' && flag !== '1')
126
+ throw new StructuredFieldError('A boolean is ?0 or ?1.');
127
+ return { kind: 'boolean', value: flag === '1' };
128
+ }
129
+ if (char === '-' || /^[0-9]$/u.test(char))
130
+ return readNumber(reader);
131
+ if (TOKEN_START.test(char))
132
+ return { kind: 'token', value: readToken(reader) };
133
+ throw new StructuredFieldError(`No item starts with "${char}".`);
134
+ }
135
+ function readParameters(reader) {
136
+ const parameters = new Map();
137
+ while (reader.peek() === ';') {
138
+ reader.next();
139
+ reader.skipSpaces();
140
+ const key = readKey(reader);
141
+ let value = { kind: 'boolean', value: true };
142
+ if (reader.peek() === '=') {
143
+ reader.next();
144
+ value = readBareItem(reader);
145
+ }
146
+ parameters.set(key, value);
147
+ }
148
+ return parameters;
149
+ }
150
+ function readItem(reader) {
151
+ const value = readBareItem(reader);
152
+ return { kind: 'item', value, parameters: readParameters(reader) };
153
+ }
154
+ function readInnerList(reader) {
155
+ reader.expect('(');
156
+ const items = [];
157
+ for (;;) {
158
+ reader.skipSpaces();
159
+ if (reader.peek() === ')') {
160
+ reader.next();
161
+ return { kind: 'inner-list', items, parameters: readParameters(reader) };
162
+ }
163
+ items.push(readItem(reader));
164
+ const after = reader.peek();
165
+ if (after !== ' ' && after !== ')')
166
+ throw new StructuredFieldError('Inner list items are separated by spaces.');
167
+ }
168
+ }
169
+ function readMember(reader) {
170
+ return reader.peek() === '(' ? readInnerList(reader) : readItem(reader);
171
+ }
172
+ /** A Dictionary: `key=value, key=(a b);p=1, flag`. A key given twice keeps the last. */
173
+ export function parseDictionary(text) {
174
+ const reader = new Reader(text);
175
+ const dictionary = new Map();
176
+ reader.skipSpaces();
177
+ while (!reader.done()) {
178
+ const key = readKey(reader);
179
+ if (reader.peek() === '=') {
180
+ reader.next();
181
+ dictionary.set(key, readMember(reader));
182
+ }
183
+ else
184
+ dictionary.set(key, {
185
+ kind: 'item',
186
+ value: { kind: 'boolean', value: true },
187
+ parameters: readParameters(reader),
188
+ });
189
+ reader.skipWhitespace();
190
+ if (reader.done())
191
+ return dictionary;
192
+ reader.expect(',');
193
+ reader.skipWhitespace();
194
+ if (reader.done())
195
+ throw new StructuredFieldError('A trailing comma.');
196
+ }
197
+ return dictionary;
198
+ }
199
+ /** One Item on its own: `"https://signer.example"` or `token;p=1`. */
200
+ export function parseItem(text) {
201
+ const reader = new Reader(text);
202
+ reader.skipSpaces();
203
+ const item = readItem(reader);
204
+ reader.skipSpaces();
205
+ if (!reader.done())
206
+ throw new StructuredFieldError('More than one item where one was expected.');
207
+ return item;
208
+ }
209
+ function serializeString(value) {
210
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
211
+ }
212
+ /** A bare item as the RFC writes it, for a signature base's component lines. */
213
+ export function serializeBareItem(item) {
214
+ switch (item.kind) {
215
+ case 'string':
216
+ return serializeString(item.value);
217
+ case 'token':
218
+ return item.value;
219
+ case 'integer':
220
+ return String(item.value);
221
+ case 'decimal':
222
+ // A decimal keeps a fractional digit, as the RFC writes `1.0`.
223
+ return Number.isInteger(item.value)
224
+ ? item.value.toFixed(1)
225
+ : String(item.value);
226
+ case 'boolean':
227
+ return item.value ? '?1' : '?0';
228
+ case 'bytes':
229
+ return `:${btoa(String.fromCharCode(...item.value))}:`;
230
+ }
231
+ }
232
+ export function serializeParameters(parameters) {
233
+ let text = '';
234
+ for (const [key, value] of parameters)
235
+ text +=
236
+ value.kind === 'boolean' && value.value
237
+ ? `;${key}`
238
+ : `;${key}=${serializeBareItem(value)}`;
239
+ return text;
240
+ }
241
+ export function serializeItem(item) {
242
+ return `${serializeBareItem(item.value)}${serializeParameters(item.parameters)}`;
243
+ }
244
+ export function serializeInnerList(list) {
245
+ return `(${list.items.map(serializeItem).join(' ')})${serializeParameters(list.parameters)}`;
246
+ }
@@ -0,0 +1,58 @@
1
+ import type { SpanContext } from './event.js';
2
+ export declare const TRACE_HANDOFF_HEADER = "x-agentrail-trace-handoff";
3
+ export interface TraceHandoffInput {
4
+ readonly traceparent: string;
5
+ readonly hashKeyId: string;
6
+ readonly issuedAt: number;
7
+ readonly method: string;
8
+ /** Exact origin-form target sent on the wire, after path/query rewrites. */
9
+ readonly target: string;
10
+ }
11
+ interface Expectation {
12
+ readonly traceparent: string | null;
13
+ readonly method: string;
14
+ readonly target: string;
15
+ readonly now: number;
16
+ }
17
+ export interface TraceHandoffVerificationInput extends Expectation {
18
+ readonly hashKey: string;
19
+ }
20
+ export interface TraceHandoffRefusal {
21
+ readonly kind: 'refused';
22
+ readonly reason: 'missing' | 'malformed' | 'key_mismatch' | 'context_mismatch' | 'expired' | 'future' | 'signature_invalid';
23
+ }
24
+ interface Context {
25
+ readonly context: SpanContext;
26
+ readonly traceparent: string;
27
+ readonly hashKeyId: string;
28
+ readonly issuedAt: number;
29
+ }
30
+ export type TraceHandoffVerification = (Context & {
31
+ readonly kind: 'verified';
32
+ }) | TraceHandoffRefusal;
33
+ export declare class TraceHandoffInputError extends Error {
34
+ readonly name = "TraceHandoffInputError";
35
+ constructor();
36
+ }
37
+ /** A fragment never reaches the origin; a trailing empty query still can. */
38
+ export declare function traceHandoffTarget(url: string | URL): string;
39
+ /** Shared canonical bytes for runtimes whose OTel hooks require synchronous HMAC. */
40
+ export declare function encodeTraceHandoff(input: TraceHandoffInput): {
41
+ bytes: Uint8Array<ArrayBuffer>;
42
+ tokenPrefix: string;
43
+ };
44
+ export declare function signTraceHandoff(input: TraceHandoffInput, hashKey: string): Promise<string>;
45
+ /**
46
+ * Unverified candidate only. Node's synchronous OTel propagator checks its MAC
47
+ * with node:crypto; other runtimes use verifyTraceHandoff below. Never continue
48
+ * a trace from this result until the signature over bytes has been verified.
49
+ */
50
+ export declare function readTraceHandoff(token: string | null, expected: Expectation & {
51
+ readonly hashKeyId: string;
52
+ }): (Context & {
53
+ readonly kind: 'candidate';
54
+ readonly bytes: Uint8Array<ArrayBuffer>;
55
+ readonly signature: Uint8Array<ArrayBuffer>;
56
+ }) | TraceHandoffRefusal;
57
+ export declare function verifyTraceHandoff(token: string | null, input: TraceHandoffVerificationInput): Promise<TraceHandoffVerification>;
58
+ export {};
@@ -0,0 +1,141 @@
1
+ import { hashKeyIdOf } from './hash.js';
2
+ import { parseTraceparent } from './trace.js';
3
+ export const TRACE_HANDOFF_HEADER = 'x-agentrail-trace-handoff';
4
+ const MAX_AGE_MS = 60_000;
5
+ const encoder = new TextEncoder();
6
+ const TOKEN = /^ah1\.([0-9a-f]{16})\.(0|[1-9][0-9]{0,15})\.(00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2})\.([0-9a-f]{64})$/u;
7
+ const METHOD = /^[!#$%&'*+.^_`|~0-9a-z-]{1,64}$/iu;
8
+ const keys = new Map();
9
+ export class TraceHandoffInputError extends Error {
10
+ name = 'TraceHandoffInputError';
11
+ constructor() {
12
+ super('Configure a valid trace context, hash key ID, timestamp, method and origin-form target for trace handoff.');
13
+ }
14
+ }
15
+ async function keyOf(hashKey) {
16
+ const held = keys.get(hashKey);
17
+ if (held !== undefined)
18
+ return held;
19
+ const imported = Promise.all([
20
+ crypto.subtle.importKey('raw', encoder.encode(hashKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']),
21
+ hashKeyIdOf(hashKey),
22
+ ]).then(([key, id]) => ({ key, id }));
23
+ keys.set(hashKey, imported);
24
+ return imported;
25
+ }
26
+ /** A fragment never reaches the origin; a trailing empty query still can. */
27
+ export function traceHandoffTarget(url) {
28
+ const parsed = new URL(url);
29
+ const fragmentAt = parsed.href.indexOf('#');
30
+ const sent = fragmentAt < 0 ? parsed.href : parsed.href.slice(0, fragmentAt);
31
+ return `${parsed.pathname}${parsed.search}${parsed.search === '' && sent.endsWith('?') ? '?' : ''}`;
32
+ }
33
+ function validRequest(method, target) {
34
+ return (METHOD.test(method) &&
35
+ target.startsWith('/') &&
36
+ target.isWellFormed() &&
37
+ !/[\u0000\r\n#]/u.test(target));
38
+ }
39
+ function payload(input) {
40
+ return encoder.encode(`agentrail.trace-handoff\u0000${JSON.stringify([
41
+ 1,
42
+ input.hashKeyId,
43
+ input.issuedAt,
44
+ input.traceparent,
45
+ input.method,
46
+ input.target,
47
+ ])}`);
48
+ }
49
+ /** Shared canonical bytes for runtimes whose OTel hooks require synchronous HMAC. */
50
+ export function encodeTraceHandoff(input) {
51
+ if (!/^[0-9a-f]{16}$/u.test(input.hashKeyId) ||
52
+ input.traceparent !== input.traceparent.trim() ||
53
+ parseTraceparent(input.traceparent) === null ||
54
+ !Number.isSafeInteger(input.issuedAt) ||
55
+ input.issuedAt < 0 ||
56
+ !validRequest(input.method, input.target))
57
+ throw new TraceHandoffInputError();
58
+ return {
59
+ bytes: payload(input),
60
+ tokenPrefix: `ah1.${input.hashKeyId}.${input.issuedAt}.${input.traceparent}.`,
61
+ };
62
+ }
63
+ export async function signTraceHandoff(input, hashKey) {
64
+ const key = await keyOf(hashKey);
65
+ if (input.hashKeyId !== key.id)
66
+ throw new TraceHandoffInputError();
67
+ const encoded = encodeTraceHandoff(input);
68
+ const mac = await crypto.subtle.sign('HMAC', key.key, encoded.bytes);
69
+ const hex = [...new Uint8Array(mac)]
70
+ .map((byte) => byte.toString(16).padStart(2, '0'))
71
+ .join('');
72
+ return encoded.tokenPrefix + hex;
73
+ }
74
+ function parsedToken(token) {
75
+ if (token.length > 256)
76
+ return null;
77
+ const [, hashKeyId, time, traceparent, signature] = TOKEN.exec(token) ?? [];
78
+ if (hashKeyId === undefined ||
79
+ time === undefined ||
80
+ traceparent === undefined ||
81
+ signature === undefined)
82
+ return null;
83
+ const context = parseTraceparent(traceparent);
84
+ const issuedAt = Number(time);
85
+ if (context === null || !Number.isSafeInteger(issuedAt))
86
+ return null;
87
+ return {
88
+ hashKeyId,
89
+ issuedAt,
90
+ traceparent,
91
+ context,
92
+ signature: Uint8Array.from({ length: 32 }, (_, index) => Number.parseInt(signature.slice(index * 2, index * 2 + 2), 16)),
93
+ };
94
+ }
95
+ /**
96
+ * Unverified candidate only. Node's synchronous OTel propagator checks its MAC
97
+ * with node:crypto; other runtimes use verifyTraceHandoff below. Never continue
98
+ * a trace from this result until the signature over bytes has been verified.
99
+ */
100
+ export function readTraceHandoff(token, expected) {
101
+ if (token === null)
102
+ return { kind: 'refused', reason: 'missing' };
103
+ const parsed = parsedToken(token);
104
+ if (parsed === null ||
105
+ !validRequest(expected.method, expected.target) ||
106
+ !Number.isSafeInteger(expected.now))
107
+ return { kind: 'refused', reason: 'malformed' };
108
+ if (parsed.hashKeyId !== expected.hashKeyId)
109
+ return { kind: 'refused', reason: 'key_mismatch' };
110
+ if (parsed.traceparent !== expected.traceparent)
111
+ return { kind: 'refused', reason: 'context_mismatch' };
112
+ const age = expected.now - parsed.issuedAt;
113
+ if (age < 0)
114
+ return { kind: 'refused', reason: 'future' };
115
+ if (age > MAX_AGE_MS)
116
+ return { kind: 'refused', reason: 'expired' };
117
+ return {
118
+ ...parsed,
119
+ kind: 'candidate',
120
+ bytes: payload({
121
+ ...parsed,
122
+ method: expected.method,
123
+ target: expected.target,
124
+ }),
125
+ };
126
+ }
127
+ export async function verifyTraceHandoff(token, input) {
128
+ const key = await keyOf(input.hashKey);
129
+ const candidate = readTraceHandoff(token, { ...input, hashKeyId: key.id });
130
+ if (candidate.kind === 'refused')
131
+ return candidate;
132
+ if (!(await crypto.subtle.verify('HMAC', key.key, candidate.signature, candidate.bytes)))
133
+ return { kind: 'refused', reason: 'signature_invalid' };
134
+ return {
135
+ kind: 'verified',
136
+ context: candidate.context,
137
+ traceparent: candidate.traceparent,
138
+ hashKeyId: candidate.hashKeyId,
139
+ issuedAt: candidate.issuedAt,
140
+ };
141
+ }
package/dist/version.d.ts CHANGED
@@ -4,4 +4,4 @@
4
4
  * own in every call. `test/version.test.ts` holds it to every package's
5
5
  * manifest.
6
6
  */
7
- export declare const VERSION = "0.1.0";
7
+ export declare const VERSION = "0.3.0";
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  * own in every call. `test/version.test.ts` holds it to every package's
5
5
  * manifest.
6
6
  */
7
- export const VERSION = '0.1.0';
7
+ export const VERSION = '0.3.0';
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Web Bot Auth (draft-ietf-webbotauth-httpsig-protocol): an agent signs its
3
+ * requests with HTTP Message Signatures (RFC 9421) and names, in
4
+ * `Signature-Agent`, the HTTPS URL it publishes its keys at. A verified
5
+ * signature says who operates the agent; an unverified one is a claim. This
6
+ * checks a request's signature against that directory and reports the
7
+ * outcome with its reason, so a directory that is down is never read as a
8
+ * forged signature (docs/research/agent-journey-correlation.md, 12.3).
9
+ *
10
+ * What it reads: the dictionary form of `Signature-Agent` (`sig="https://…"`)
11
+ * and the bare string signers sent before it; a signature tagged
12
+ * `web-bot-auth` covering `@authority` or `@target-uri` and the agent header;
13
+ * Ed25519, RSA-PSS-SHA512 and ECDSA-P256 keys, matched by the JWK thumbprint
14
+ * the draft makes the key id. Anything else it does not read is reported as
15
+ * unsupported, never as invalid.
16
+ */
17
+ /** What a check here ends as: every outcome but `unchecked`, which is a component that did not check. */
18
+ export declare const SIGNATURE_CHECK_OUTCOMES: readonly ["verified", "invalid", "directory_unreachable", "unsupported"];
19
+ export type SignatureCheckOutcome = (typeof SIGNATURE_CHECK_OUTCOMES)[number];
20
+ /** A request's signed agent: who it says it is, and whether that checked. */
21
+ export interface SignedAgent {
22
+ /** The URL the agent names itself by, where its keys are published. */
23
+ readonly agent: string;
24
+ /** The key id the signature names; null when the headers did not parse that far. */
25
+ readonly keyId: string | null;
26
+ readonly outcome: SignatureCheckOutcome;
27
+ }
28
+ /** What of a request the signature covers: its method, URL and headers. */
29
+ export interface SignedRequest {
30
+ readonly method: string;
31
+ readonly url: string;
32
+ readonly headers: Headers;
33
+ }
34
+ /**
35
+ * The operators known to publish keys for their agents, by the registrable
36
+ * host of the directory: the only hosts a directory is read from unless a
37
+ * site names more. A name the caller chose is otherwise never contacted,
38
+ * since even a public-looking name may resolve to an address inside the
39
+ * network the edge runs in, which the Fetch API gives no way to see.
40
+ */
41
+ export declare const KNOWN_SIGNERS: readonly ["chatgpt.com", "openai.com", "google.com", "anthropic.com", "claude.ai", "perplexity.ai"];
42
+ export interface SignatureVerifierOptions {
43
+ /** The fetch directories are read with; the platform's own by default. */
44
+ readonly fetch?: typeof fetch;
45
+ /**
46
+ * Registrable hosts, beside the known signers, whose key directories may
47
+ * be read (`signer.example.com` covers `keys.signer.example.com`). A
48
+ * signature by any other host is recorded as an unsupported claim.
49
+ */
50
+ readonly signers?: readonly string[];
51
+ /** The clock, milliseconds since the epoch; `Date.now` by default. */
52
+ readonly now?: () => number;
53
+ }
54
+ export type SignatureVerifier = (request: SignedRequest) => Promise<SignedAgent | null>;
55
+ interface Jwk {
56
+ readonly kty: string;
57
+ readonly crv?: string;
58
+ readonly x?: string;
59
+ readonly y?: string;
60
+ readonly n?: string;
61
+ readonly e?: string;
62
+ readonly kid?: string;
63
+ }
64
+ /**
65
+ * The JWK thumbprint (RFC 7638; RFC 8037 for Ed25519) the draft makes a
66
+ * signature's `keyid`: the SHA-256 of the key's required members in
67
+ * lexicographic order, base64url. Null for a key this verifier does not read.
68
+ */
69
+ export declare function keyThumbprint(key: Jwk): Promise<string | null>;
70
+ /**
71
+ * A verifier of requests' Web Bot Auth signatures. One per runtime: it keeps
72
+ * the directories it has read, so a signer's keys are fetched once per
73
+ * `max-age`, not once per request.
74
+ */
75
+ export declare function createSignatureVerifier(options?: SignatureVerifierOptions): SignatureVerifier;
76
+ export {};
@@ -0,0 +1,534 @@
1
+ import { StructuredFieldError, parseDictionary, parseItem, serializeInnerList, serializeItem, } from './structured-fields.js';
2
+ /**
3
+ * Web Bot Auth (draft-ietf-webbotauth-httpsig-protocol): an agent signs its
4
+ * requests with HTTP Message Signatures (RFC 9421) and names, in
5
+ * `Signature-Agent`, the HTTPS URL it publishes its keys at. A verified
6
+ * signature says who operates the agent; an unverified one is a claim. This
7
+ * checks a request's signature against that directory and reports the
8
+ * outcome with its reason, so a directory that is down is never read as a
9
+ * forged signature (docs/research/agent-journey-correlation.md, 12.3).
10
+ *
11
+ * What it reads: the dictionary form of `Signature-Agent` (`sig="https://…"`)
12
+ * and the bare string signers sent before it; a signature tagged
13
+ * `web-bot-auth` covering `@authority` or `@target-uri` and the agent header;
14
+ * Ed25519, RSA-PSS-SHA512 and ECDSA-P256 keys, matched by the JWK thumbprint
15
+ * the draft makes the key id. Anything else it does not read is reported as
16
+ * unsupported, never as invalid.
17
+ */
18
+ /** What a check here ends as: every outcome but `unchecked`, which is a component that did not check. */
19
+ export const SIGNATURE_CHECK_OUTCOMES = [
20
+ /** The signature checks against a key the agent's directory publishes. */
21
+ 'verified',
22
+ /** It does not: a forged or stale signature, or a key the directory does not hold. */
23
+ 'invalid',
24
+ /** The directory could not be read, so nothing is known either way. */
25
+ 'directory_unreachable',
26
+ /** The signature uses a component, algorithm or key this verifier does not read. */
27
+ 'unsupported',
28
+ ];
29
+ /**
30
+ * The operators known to publish keys for their agents, by the registrable
31
+ * host of the directory: the only hosts a directory is read from unless a
32
+ * site names more. A name the caller chose is otherwise never contacted,
33
+ * since even a public-looking name may resolve to an address inside the
34
+ * network the edge runs in, which the Fetch API gives no way to see.
35
+ */
36
+ export const KNOWN_SIGNERS = [
37
+ 'chatgpt.com',
38
+ 'openai.com',
39
+ 'google.com',
40
+ 'anthropic.com',
41
+ 'claude.ai',
42
+ 'perplexity.ai',
43
+ ];
44
+ /** Where an agent publishes its keys, under the URL it names. */
45
+ const DIRECTORY_PATH = '/.well-known/http-message-signatures-directory';
46
+ const DIRECTORY_MEDIA_TYPE = 'application/http-message-signatures-directory+json';
47
+ /** How long a directory read may take: a signed request's answer is already sent. */
48
+ const DIRECTORY_TIMEOUT_MS = 5_000;
49
+ /** How long a directory is kept when it names no `max-age`, and the most it is kept. */
50
+ const DIRECTORY_DEFAULT_TTL_MS = 60 * 60 * 1_000;
51
+ const DIRECTORY_MAX_TTL_MS = 24 * 60 * 60 * 1_000;
52
+ /** How long a directory that could not be read is not asked again, so a down signer is not fetched on every request. */
53
+ const DIRECTORY_RETRY_MS = 60 * 1_000;
54
+ /** How far in the future a signature's `created` may be, for clocks that disagree. */
55
+ const CREATED_SKEW_MS = 5 * 60 * 1_000;
56
+ /** The tag the draft gives these signatures. */
57
+ const TAG = 'web-bot-auth';
58
+ /** The longest agent URL and key id the collector takes; a claim is cut to them. */
59
+ const AGENT_LENGTH = 256;
60
+ const KEY_ID_LENGTH = 256;
61
+ /** The most directories kept at once, and the most failures remembered: a caller names the hosts, so neither may grow without bound. */
62
+ const MAX_DIRECTORIES = 256;
63
+ const MAX_FAILURES = 1_024;
64
+ const encoder = new TextEncoder();
65
+ function base64url(bytes) {
66
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
67
+ return btoa(String.fromCharCode(...view))
68
+ .replaceAll('+', '-')
69
+ .replaceAll('/', '_')
70
+ .replace(/=+$/u, '');
71
+ }
72
+ /** The key's algorithm and members, from what kind of key it is; null for a kind this verifier does not read, or a key missing a member. */
73
+ function publicKeyOf(key) {
74
+ if (key.kty === 'OKP' && key.crv === 'Ed25519' && key.x !== undefined)
75
+ return {
76
+ algorithm: 'ed25519',
77
+ jwk: { crv: 'Ed25519', kty: 'OKP', x: key.x },
78
+ };
79
+ if (key.kty === 'RSA' && key.e !== undefined && key.n !== undefined)
80
+ return {
81
+ algorithm: 'rsa-pss-sha512',
82
+ jwk: { e: key.e, kty: 'RSA', n: key.n },
83
+ };
84
+ if (key.kty === 'EC' &&
85
+ key.crv === 'P-256' &&
86
+ key.x !== undefined &&
87
+ key.y !== undefined)
88
+ return {
89
+ algorithm: 'ecdsa-p256-sha256',
90
+ jwk: { crv: 'P-256', kty: 'EC', x: key.x, y: key.y },
91
+ };
92
+ return null;
93
+ }
94
+ /**
95
+ * The JWK thumbprint (RFC 7638; RFC 8037 for Ed25519) the draft makes a
96
+ * signature's `keyid`: the SHA-256 of the key's required members in
97
+ * lexicographic order, base64url. Null for a key this verifier does not read.
98
+ */
99
+ export async function keyThumbprint(key) {
100
+ const read = publicKeyOf(key);
101
+ if (read === null)
102
+ return null;
103
+ return base64url(await crypto.subtle.digest('SHA-256', encoder.encode(JSON.stringify(read.jwk))));
104
+ }
105
+ function importKey(key) {
106
+ switch (key.algorithm) {
107
+ case 'ed25519':
108
+ return crypto.subtle.importKey('jwk', key.jwk, { name: 'Ed25519' }, false, ['verify']);
109
+ case 'rsa-pss-sha512':
110
+ return crypto.subtle.importKey('jwk', key.jwk, { name: 'RSA-PSS', hash: 'SHA-512' }, false, ['verify']);
111
+ case 'ecdsa-p256-sha256':
112
+ return crypto.subtle.importKey('jwk', key.jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
113
+ }
114
+ }
115
+ function verifyParameters(algorithm) {
116
+ switch (algorithm) {
117
+ case 'ed25519':
118
+ return { name: 'Ed25519' };
119
+ case 'rsa-pss-sha512':
120
+ return { name: 'RSA-PSS', saltLength: 64 };
121
+ case 'ecdsa-p256-sha256':
122
+ return { name: 'ECDSA', hash: 'SHA-256' };
123
+ }
124
+ }
125
+ /**
126
+ * The agent URLs a `Signature-Agent` header names, by dictionary label (the
127
+ * bare form has none): every HTTPS URL it names, each marked whether its
128
+ * directory may be read, so a claim is always recorded against the agent
129
+ * the signature named, readable or not.
130
+ */
131
+ function agentsOf(header, readable) {
132
+ const agents = new Map();
133
+ let members;
134
+ try {
135
+ members = parseDictionary(header);
136
+ }
137
+ catch (error) {
138
+ if (!(error instanceof StructuredFieldError))
139
+ throw error;
140
+ members = new Map();
141
+ }
142
+ for (const [label, member] of members) {
143
+ if (member.kind !== 'item' || member.value.kind !== 'string')
144
+ continue;
145
+ const type = member.parameters.get('type');
146
+ // A directory is the one type this reads; the draft says to ignore others.
147
+ if (type !== undefined &&
148
+ !(type.kind === 'token' && type.value === 'directory'))
149
+ continue;
150
+ if (isHttpsUrl(member.value.value))
151
+ agents.set(label, {
152
+ url: member.value.value,
153
+ readable: readable(member.value.value),
154
+ });
155
+ }
156
+ if (agents.size === 0) {
157
+ // The bare string signers sent before the dictionary form.
158
+ try {
159
+ const item = parseItem(header);
160
+ if (item.value.kind === 'string' && isHttpsUrl(item.value.value))
161
+ agents.set(null, {
162
+ url: item.value.value,
163
+ readable: readable(item.value.value),
164
+ });
165
+ }
166
+ catch (error) {
167
+ if (!(error instanceof StructuredFieldError))
168
+ throw error;
169
+ }
170
+ }
171
+ return agents;
172
+ }
173
+ function isHttpsUrl(value) {
174
+ const url = URL.parse(value);
175
+ return url !== null && url.protocol === 'https:';
176
+ }
177
+ /** A hostname that is an address rather than a name, or a name that is never public. */
178
+ const ADDRESS_OR_PRIVATE_HOST = /^(?:\d{1,3}(?:\.\d{1,3}){3}|\[.*\]|localhost|.*\.(?:localhost|local|internal|arpa))$/iu;
179
+ /**
180
+ * A URL this verifier will read a directory from: HTTPS, on its default
181
+ * port, with no credentials, at a public name that is a listed signer's or
182
+ * under one. The caller chooses the URL, so nothing else is ever contacted
183
+ * from the edge that runs this.
184
+ */
185
+ function isAgentUrl(value, signers) {
186
+ const url = URL.parse(value);
187
+ if (url === null)
188
+ return false;
189
+ if (url.protocol !== 'https:' ||
190
+ url.port !== '' ||
191
+ url.username !== '' ||
192
+ url.password !== '' ||
193
+ !url.hostname.includes('.') ||
194
+ ADDRESS_OR_PRIVATE_HOST.test(url.hostname))
195
+ return false;
196
+ const host = url.hostname.toLowerCase();
197
+ for (const signer of signers)
198
+ if (host === signer || host.endsWith(`.${signer}`))
199
+ return true;
200
+ return false;
201
+ }
202
+ /** The parameters the draft requires on the signature, or null where one is missing or mistyped. */
203
+ function parametersOf(list) {
204
+ const keyId = list.parameters.get('keyid');
205
+ const created = list.parameters.get('created');
206
+ const expires = list.parameters.get('expires');
207
+ const alg = list.parameters.get('alg');
208
+ if (keyId?.kind !== 'string' ||
209
+ created?.kind !== 'integer' ||
210
+ expires?.kind !== 'integer' ||
211
+ (alg !== undefined && alg.kind !== 'string'))
212
+ return null;
213
+ return {
214
+ keyId: keyId.value,
215
+ created: created.value,
216
+ expires: expires.value,
217
+ alg: alg === undefined ? null : alg.value,
218
+ };
219
+ }
220
+ /**
221
+ * A covered component's value, as RFC 9421 derives it from the request: the
222
+ * derived components an agent signs, and a header, whole or one member of
223
+ * it. A component this does not derive is unsupported, never guessed.
224
+ */
225
+ function componentValue(component, request, url) {
226
+ if (component.value.kind !== 'string')
227
+ return { kind: 'unsupported' };
228
+ const name = component.value.value;
229
+ const parameters = component.parameters;
230
+ if (name.startsWith('@')) {
231
+ if (parameters.size > 0)
232
+ return { kind: 'unsupported' };
233
+ switch (name) {
234
+ case '@method':
235
+ // As sent: a method's name is case-sensitive.
236
+ return { kind: 'value', value: request.method };
237
+ case '@target-uri':
238
+ return { kind: 'value', value: url.href };
239
+ case '@authority':
240
+ return { kind: 'value', value: url.host.toLowerCase() };
241
+ case '@scheme':
242
+ return { kind: 'value', value: url.protocol.slice(0, -1) };
243
+ case '@path':
244
+ return { kind: 'value', value: url.pathname };
245
+ case '@query':
246
+ return { kind: 'value', value: url.search === '' ? '?' : url.search };
247
+ default:
248
+ return { kind: 'unsupported' };
249
+ }
250
+ }
251
+ const held = request.headers.get(name.toLowerCase());
252
+ if (held === null)
253
+ return { kind: 'missing' };
254
+ const key = parameters.get('key');
255
+ for (const flag of parameters.keys())
256
+ if (flag !== 'key')
257
+ return { kind: 'unsupported' };
258
+ if (key === undefined)
259
+ return { kind: 'value', value: held.trim() };
260
+ if (key.kind !== 'string')
261
+ return { kind: 'unsupported' };
262
+ let members;
263
+ try {
264
+ members = parseDictionary(held);
265
+ }
266
+ catch (error) {
267
+ if (!(error instanceof StructuredFieldError))
268
+ throw error;
269
+ return { kind: 'missing' };
270
+ }
271
+ const member = members.get(key.value);
272
+ if (member === undefined)
273
+ return { kind: 'missing' };
274
+ return {
275
+ kind: 'value',
276
+ value: member.kind === 'item'
277
+ ? serializeItem(member)
278
+ : serializeInnerList(member),
279
+ };
280
+ }
281
+ /** The signature base (RFC 9421, 2.5): each covered component's line, then the parameters. */
282
+ function signatureBase(list, request, url) {
283
+ const lines = [];
284
+ for (const component of list.items) {
285
+ const value = componentValue(component, request, url);
286
+ if (value.kind !== 'value')
287
+ return { kind: value.kind };
288
+ lines.push(`${serializeItem(component)}: ${value.value}`);
289
+ }
290
+ lines.push(`"@signature-params": ${serializeInnerList(list)}`);
291
+ return { kind: 'base', text: lines.join('\n') };
292
+ }
293
+ function isJwk(value) {
294
+ return (typeof value === 'object' &&
295
+ value !== null &&
296
+ 'kty' in value &&
297
+ typeof value.kty === 'string');
298
+ }
299
+ /** The seconds a `Cache-Control` lets a directory be kept, or null when it says none. */
300
+ function maxAgeOf(cacheControl) {
301
+ const match = /(?:^|,)\s*max-age=(\d+)/iu.exec(cacheControl ?? '');
302
+ return match?.[1] === undefined ? null : Number(match[1]);
303
+ }
304
+ /**
305
+ * The directories read so far, kept until their `max-age` passes; one read
306
+ * at a time per directory, shared by the requests waiting on it; a
307
+ * directory that could not be read is not asked again for a minute, and an
308
+ * earlier copy of it stays, since an outage is not evidence.
309
+ */
310
+ class Directories {
311
+ fetcher;
312
+ now;
313
+ held = new Map();
314
+ reading = new Map();
315
+ failedAt = new Map();
316
+ constructor(fetcher, now) {
317
+ this.fetcher = fetcher;
318
+ this.now = now;
319
+ }
320
+ async read(agent) {
321
+ const address = new URL(DIRECTORY_PATH, agent).href;
322
+ const now = this.now();
323
+ const kept = this.held.get(address);
324
+ if (kept !== undefined && kept.until > now)
325
+ return { kind: 'read', directory: kept.directory };
326
+ const failed = this.failedAt.get(address);
327
+ if (failed !== undefined && now - failed < DIRECTORY_RETRY_MS)
328
+ return kept === undefined
329
+ ? { kind: 'unreachable' }
330
+ : { kind: 'read', directory: kept.directory };
331
+ const underWay = this.reading.get(address);
332
+ if (underWay !== undefined)
333
+ return underWay;
334
+ const reading = (async () => {
335
+ try {
336
+ const read = await this.fetchDirectory(address);
337
+ if (read.kind === 'read')
338
+ this.failedAt.delete(address);
339
+ else {
340
+ this.remember(this.failedAt, address, this.now(), MAX_FAILURES);
341
+ if (kept !== undefined)
342
+ return { kind: 'read', directory: kept.directory };
343
+ }
344
+ return read;
345
+ }
346
+ finally {
347
+ // Whatever became of it, the next check reads again.
348
+ this.reading.delete(address);
349
+ }
350
+ })();
351
+ this.reading.set(address, reading);
352
+ return reading;
353
+ }
354
+ /** Keeps a value, and forgets the oldest once more than `most` are kept. */
355
+ remember(kept, address, value, most) {
356
+ kept.delete(address);
357
+ kept.set(address, value);
358
+ for (const oldest of kept.keys()) {
359
+ if (kept.size <= most)
360
+ break;
361
+ kept.delete(oldest);
362
+ }
363
+ }
364
+ async fetchDirectory(address) {
365
+ let body;
366
+ let cacheControl;
367
+ try {
368
+ const response = await this.fetcher(address, {
369
+ headers: { accept: DIRECTORY_MEDIA_TYPE },
370
+ // The draft forbids following a redirect to a directory.
371
+ redirect: 'manual',
372
+ signal: AbortSignal.timeout(DIRECTORY_TIMEOUT_MS),
373
+ });
374
+ if (response.status !== 200)
375
+ return { kind: 'unreachable' };
376
+ cacheControl = response.headers.get('cache-control');
377
+ body = await response.json();
378
+ }
379
+ catch (error) {
380
+ // The network, TLS, the deadline (on the headers or the body) or a
381
+ // body that is not JSON: the directory is unreachable, which is what
382
+ // the caller is told; the reason is not evidence either.
383
+ if (error instanceof DOMException ||
384
+ error instanceof TypeError ||
385
+ error instanceof SyntaxError)
386
+ return { kind: 'unreachable' };
387
+ throw error;
388
+ }
389
+ if (typeof body !== 'object' ||
390
+ body === null ||
391
+ !('keys' in body) ||
392
+ !Array.isArray(body.keys))
393
+ return { kind: 'unreachable' };
394
+ const directory = { keys: body.keys.filter(isJwk) };
395
+ const maxAge = maxAgeOf(cacheControl);
396
+ const ttl = maxAge === null
397
+ ? DIRECTORY_DEFAULT_TTL_MS
398
+ : Math.min(maxAge * 1_000, DIRECTORY_MAX_TTL_MS);
399
+ this.remember(this.held, address, { directory, until: this.now() + ttl }, MAX_DIRECTORIES);
400
+ return { kind: 'read', directory };
401
+ }
402
+ }
403
+ /** The key in a directory a signature names, by the thumbprint the draft requires or the `kid` the key carries. */
404
+ async function keyNamed(directory, keyId) {
405
+ for (const key of directory.keys) {
406
+ if (key.kid === keyId)
407
+ return key;
408
+ if ((await keyThumbprint(key)) === keyId)
409
+ return key;
410
+ }
411
+ return null;
412
+ }
413
+ /**
414
+ * A verifier of requests' Web Bot Auth signatures. One per runtime: it keeps
415
+ * the directories it has read, so a signer's keys are fetched once per
416
+ * `max-age`, not once per request.
417
+ */
418
+ export function createSignatureVerifier(options = {}) {
419
+ const now = options.now ?? Date.now;
420
+ const directories = new Directories(options.fetch ?? fetch, now);
421
+ const signers = new Set([...KNOWN_SIGNERS, ...(options.signers ?? [])].map((host) => host.toLowerCase()));
422
+ const readable = (url) => isAgentUrl(url, signers);
423
+ return async (request) => {
424
+ const agentHeader = request.headers.get('signature-agent');
425
+ if (agentHeader === null)
426
+ return null;
427
+ const agents = agentsOf(agentHeader, readable);
428
+ const first = agents.values().next();
429
+ const named = first.done ? agentHeader.trim() : first.value.url;
430
+ // An empty header names no one: no claim was made.
431
+ if (named === '')
432
+ return null;
433
+ // Cut to what the collector takes, so a claim never refuses the call
434
+ // that carries it; the check itself read the values whole.
435
+ const claim = (outcome, keyId = null, agent = named) => ({
436
+ agent: agent.slice(0, AGENT_LENGTH),
437
+ keyId: keyId?.slice(0, KEY_ID_LENGTH) ?? null,
438
+ outcome,
439
+ });
440
+ // A header naming no HTTPS URL at all is a claim of nothing checkable.
441
+ if (first.done)
442
+ return claim('invalid');
443
+ const inputHeader = request.headers.get('signature-input');
444
+ const signatureHeader = request.headers.get('signature');
445
+ if (inputHeader === null || signatureHeader === null)
446
+ return claim('invalid');
447
+ let inputs;
448
+ let signatures;
449
+ try {
450
+ inputs = parseDictionary(inputHeader);
451
+ signatures = parseDictionary(signatureHeader);
452
+ }
453
+ catch (error) {
454
+ if (!(error instanceof StructuredFieldError))
455
+ throw error;
456
+ return claim('invalid');
457
+ }
458
+ const signed = [...inputs].flatMap(([name, member]) => {
459
+ const tag = member.parameters.get('tag');
460
+ return member.kind === 'inner-list' &&
461
+ tag?.kind === 'string' &&
462
+ tag.value === TAG
463
+ ? [[name, member]]
464
+ : [];
465
+ })[0];
466
+ if (signed === undefined)
467
+ return claim('invalid');
468
+ const [label, list] = signed;
469
+ const parameters = parametersOf(list);
470
+ if (parameters === null)
471
+ return claim('invalid');
472
+ const { keyId } = parameters;
473
+ const agentComponent = list.items.find((item) => item.value.kind === 'string' && item.value.value === 'signature-agent');
474
+ const coversTarget = list.items.some((item) => item.value.kind === 'string' &&
475
+ (item.value.value === '@authority' ||
476
+ item.value.value === '@target-uri'));
477
+ if (agentComponent === undefined || !coversTarget)
478
+ return claim('invalid', keyId);
479
+ const memberKey = agentComponent.parameters.get('key');
480
+ const signedAgent = memberKey === undefined
481
+ ? first.value
482
+ : memberKey.kind === 'string'
483
+ ? agents.get(memberKey.value)
484
+ : undefined;
485
+ if (signedAgent === undefined)
486
+ return claim('invalid', keyId);
487
+ const agent = signedAgent.url;
488
+ // A URL this verifier will not read a directory from (an address, a
489
+ // private name, a port, credentials) is a claim it cannot check, never
490
+ // one it found false, and never one it checks against another member.
491
+ if (!signedAgent.readable)
492
+ return claim('unsupported', keyId, agent);
493
+ const moment = now();
494
+ if (parameters.created * 1_000 > moment + CREATED_SKEW_MS)
495
+ return claim('invalid', keyId, agent);
496
+ if (parameters.expires * 1_000 <= moment)
497
+ return claim('invalid', keyId, agent);
498
+ const signature = signatures.get(label);
499
+ if (signature?.kind !== 'item' || signature.value.kind !== 'bytes')
500
+ return claim('invalid', keyId, agent);
501
+ const url = URL.parse(request.url);
502
+ if (url === null)
503
+ return claim('invalid', keyId, agent);
504
+ const base = signatureBase(list, request, url);
505
+ if (base.kind === 'unsupported')
506
+ return claim('unsupported', keyId, agent);
507
+ if (base.kind === 'missing')
508
+ return claim('invalid', keyId, agent);
509
+ const read = await directories.read(agent);
510
+ if (read.kind === 'unreachable')
511
+ return claim('directory_unreachable', keyId, agent);
512
+ const key = await keyNamed(read.directory, keyId);
513
+ if (key === null)
514
+ return claim('invalid', keyId, agent);
515
+ const publicKey = publicKeyOf(key);
516
+ if (publicKey === null)
517
+ return claim('unsupported', keyId, agent);
518
+ if (parameters.alg !== null && parameters.alg !== publicKey.algorithm)
519
+ return claim('invalid', keyId, agent);
520
+ let imported;
521
+ try {
522
+ imported = await importKey(publicKey);
523
+ }
524
+ catch (error) {
525
+ // A key the directory published that WebCrypto cannot read is the
526
+ // signer's defect, not a forgery.
527
+ if (error instanceof DOMException || error instanceof TypeError)
528
+ return claim('unsupported', keyId, agent);
529
+ throw error;
530
+ }
531
+ const checks = await crypto.subtle.verify(verifyParameters(publicKey.algorithm), imported, signature.value.value, encoder.encode(base.text));
532
+ return claim(checks ? 'verified' : 'invalid', keyId, agent);
533
+ };
534
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentrail-core",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "What every Agentrail component shares: the event the collector takes, markers, the keyed hash, W3C trace context, and the client that sends events.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {