agentrail-core 0.0.0 → 0.2.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/dist/event.js ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One event as a component sends it to the collector (`POST /ingest/events`):
3
+ * the journey engine's event less `tenant` and `observedAt`, which the
4
+ * collector stamps from the source's workspace and its own clock, and
5
+ * `hashKeyId`, which it stamps from the key the call names.
6
+ *
7
+ * The engine, private to Argus, holds the schema the collector checks; this
8
+ * package holds the same shape as types, so no component imports the
9
+ * engine. The edge's and the browser's tests check every call they send
10
+ * against the contract Argus writes (`packages/contract`).
11
+ */
12
+ export const SURFACES = [
13
+ 'edge',
14
+ 'firewall',
15
+ 'browser',
16
+ 'http',
17
+ 'mcp',
18
+ 'a2a',
19
+ 'genai',
20
+ 'auth',
21
+ 'payment',
22
+ 'custom',
23
+ ];
package/dist/hash.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The keyed hash a component applies before anything leaves the customer: a
3
+ * client address, a verified principal's id. HMAC-SHA256 with the
4
+ * workspace's hash key, cut to 32 hex characters, so every component of one
5
+ * workspace hashes one value alike and the engine can only ever compare two
6
+ * for equality (docs/research/agent-journey-correlation.md, 12.12).
7
+ */
8
+ export declare function keyedHash(hashKey: string, value: string): Promise<string>;
9
+ /**
10
+ * The id a component's calls name its hash key by: the first 16 hex
11
+ * characters of the key's SHA-256. The collector stamps it on each event
12
+ * carrying a hashed value, and the linker compares hashed values only
13
+ * between events hashed with one key, so a workspace can replace its key.
14
+ * Argus works out the same id from the key it holds, so a key needs no id
15
+ * of its own; 64 bits of its hash say nothing of the key.
16
+ */
17
+ export declare function hashKeyIdOf(hashKey: string): Promise<string>;
package/dist/hash.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The keyed hash a component applies before anything leaves the customer: a
3
+ * client address, a verified principal's id. HMAC-SHA256 with the
4
+ * workspace's hash key, cut to 32 hex characters, so every component of one
5
+ * workspace hashes one value alike and the engine can only ever compare two
6
+ * for equality (docs/research/agent-journey-correlation.md, 12.12).
7
+ */
8
+ const encoder = new TextEncoder();
9
+ /** HMAC keys imported once per hash key, for the life of the runtime. */
10
+ const keys = new Map();
11
+ function keyOf(hashKey) {
12
+ const known = keys.get(hashKey);
13
+ if (known !== undefined)
14
+ return known;
15
+ const imported = crypto.subtle.importKey('raw', encoder.encode(hashKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
16
+ keys.set(hashKey, imported);
17
+ return imported;
18
+ }
19
+ /** The first `bytes` bytes of a digest, as lowercase hex. */
20
+ function hexOf(digest, bytes) {
21
+ return [...new Uint8Array(digest)]
22
+ .slice(0, bytes)
23
+ .map((byte) => byte.toString(16).padStart(2, '0'))
24
+ .join('');
25
+ }
26
+ export async function keyedHash(hashKey, value) {
27
+ const signature = await crypto.subtle.sign('HMAC', await keyOf(hashKey), encoder.encode(value));
28
+ return hexOf(signature, 16);
29
+ }
30
+ /**
31
+ * The id a component's calls name its hash key by: the first 16 hex
32
+ * characters of the key's SHA-256. The collector stamps it on each event
33
+ * carrying a hashed value, and the linker compares hashed values only
34
+ * between events hashed with one key, so a workspace can replace its key.
35
+ * Argus works out the same id from the key it holds, so a key needs no id
36
+ * of its own; 64 bits of its hash say nothing of the key.
37
+ */
38
+ export async function hashKeyIdOf(hashKey) {
39
+ return hexOf(await crypto.subtle.digest('SHA-256', encoder.encode(hashKey)), 8);
40
+ }
package/dist/id.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Ids for what a component mints (an event, a tab, a batch of frames): a
3
+ * random UUID, version 4, from `crypto.getRandomValues`. `crypto.randomUUID`
4
+ * mints the same, but a page has it only over HTTPS: on a site served over
5
+ * plain HTTP, the browser script would record nothing.
6
+ */
7
+ /** Bytes as lowercase hex, two characters each. */
8
+ export declare function hexOf(bytes: Uint8Array): string;
9
+ /** A random UUID, version 4. */
10
+ export declare function newId(): string;
package/dist/id.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Ids for what a component mints (an event, a tab, a batch of frames): a
3
+ * random UUID, version 4, from `crypto.getRandomValues`. `crypto.randomUUID`
4
+ * mints the same, but a page has it only over HTTPS: on a site served over
5
+ * plain HTTP, the browser script would record nothing.
6
+ */
7
+ /** Bytes as lowercase hex, two characters each. */
8
+ export function hexOf(bytes) {
9
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
10
+ }
11
+ /** A random UUID, version 4. */
12
+ export function newId() {
13
+ const hex = hexOf(crypto.getRandomValues(new Uint8Array(16)));
14
+ // The version is 4; the variant's two bits are 10, the two after random.
15
+ const variant = (8 | (Number.parseInt(hex.charAt(16), 16) & 3)).toString(16);
16
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
17
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What every Agentrail component shares, in any runtime with the Fetch API
3
+ * and WebCrypto: the event the collector takes, markers, the keyed hash,
4
+ * trace context, the session, and the client that sends events. Nothing
5
+ * here imports Node, the DOM or OpenTelemetry.
6
+ */
7
+ export { SURFACES, type AgentrailEvent, type ClockSource, type Component, type PrincipalKind, type RegistrationPhase, type SignatureOutcome, type SpanContext, type SpanKind, type Surface, } from './event.js';
8
+ export { MAX_LINK_INDEX, MarkerError, linkMarker, mintMarker, newMarker, parseMarker, type ParsedMarker, } from './marker.js';
9
+ export { SessionTimeoutError, newSessionId, sessionCookie, sessionStartOf, type SessionCookie, type SessionCookieOptions, } from './session.js';
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';
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';
14
+ export { VERSION } from './version.js';
15
+ export { formatTraceparent, newSpanId, newTraceId, parseTraceparent, } from './trace.js';
16
+ export { CollectorFailedError, CollectorRefusedError, CollectorUnavailableError, createCollector, type Collector, type CollectorOptions, } from './collector.js';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What every Agentrail component shares, in any runtime with the Fetch API
3
+ * and WebCrypto: the event the collector takes, markers, the keyed hash,
4
+ * trace context, the session, and the client that sends events. Nothing
5
+ * here imports Node, the DOM or OpenTelemetry.
6
+ */
7
+ export { SURFACES, } from './event.js';
8
+ export { MAX_LINK_INDEX, MarkerError, linkMarker, mintMarker, newMarker, parseMarker, } from './marker.js';
9
+ export { SessionTimeoutError, newSessionId, sessionCookie, sessionStartOf, } from './session.js';
10
+ export { hashKeyIdOf, keyedHash } from './hash.js';
11
+ export { TRACE_HANDOFF_HEADER, TraceHandoffInputError, readTraceHandoff, encodeTraceHandoff, signTraceHandoff, traceHandoffTarget, verifyTraceHandoff, } from './trace-handoff.js';
12
+ export { newId } from './id.js';
13
+ export { KNOWN_SIGNERS, SIGNATURE_CHECK_OUTCOMES, createSignatureVerifier, keyThumbprint, } from './web-bot-auth.js';
14
+ export { VERSION } from './version.js';
15
+ export { formatTraceparent, newSpanId, newTraceId, parseTraceparent, } from './trace.js';
16
+ export { CollectorFailedError, CollectorRefusedError, CollectorUnavailableError, createCollector, } from './collector.js';
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Planted markers: 64 random bits in Crockford base32 (13 characters) and a
3
+ * Luhn mod 32 check character; a link's marker adds a two-character lane
4
+ * before the check, so each link of a response is proven on its own. The
5
+ * engine reads them back case-folded, with Crockford's look-alikes, and
6
+ * refuses any whose check fails (docs/research/agent-journey-correlation.md,
7
+ * 5.2 and 15.1). This is the same arithmetic and the same reading as the
8
+ * engine's; `test/parity.test.ts` proves the two agree.
9
+ */
10
+ /** The last lane a response's links can take; past it a link goes unmarked. */
11
+ export declare const MAX_LINK_INDEX: number;
12
+ /** A marker that is not one this package minted, or a lane out of range. */
13
+ export declare class MarkerError extends Error {
14
+ readonly name = "MarkerError";
15
+ }
16
+ /** A response marker from eight random bytes. */
17
+ export declare function mintMarker(random: Uint8Array): string;
18
+ /** A response marker from this runtime's strong random source. */
19
+ export declare function newMarker(): string;
20
+ /** How the engine reads a value: a marker, or why it is none. */
21
+ export type ParsedMarker = {
22
+ readonly valid: true;
23
+ /** The response marker, canonical, without its check character. */
24
+ readonly base: string;
25
+ /** The lane of a link's marker; null for a response's own. */
26
+ readonly link: number | null;
27
+ } | {
28
+ readonly valid: false;
29
+ readonly reason: 'length' | 'alphabet' | 'check';
30
+ };
31
+ /**
32
+ * Reads a value as an agent sent it back, as the engine does: case-folded,
33
+ * `-` dropped, I and L read as 1 and O as 0; then 14 or 16 characters of the
34
+ * alphabet whose check character holds. Only a value it reads as valid is a
35
+ * marker: anything else, an image's `h=600` or a path's `/h/getting-started`,
36
+ * is the site's own.
37
+ */
38
+ export declare function parseMarker(raw: string): ParsedMarker;
39
+ /** The marker for one link of a response: its lane. */
40
+ export declare function linkMarker(marker: string, index: number): string;
package/dist/marker.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Planted markers: 64 random bits in Crockford base32 (13 characters) and a
3
+ * Luhn mod 32 check character; a link's marker adds a two-character lane
4
+ * before the check, so each link of a response is proven on its own. The
5
+ * engine reads them back case-folded, with Crockford's look-alikes, and
6
+ * refuses any whose check fails (docs/research/agent-journey-correlation.md,
7
+ * 5.2 and 15.1). This is the same arithmetic and the same reading as the
8
+ * engine's; `test/parity.test.ts` proves the two agree.
9
+ */
10
+ const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
11
+ const BASE = ALPHABET.length;
12
+ const PAYLOAD_LENGTH = 13;
13
+ const LANE_LENGTH = 2;
14
+ const RANDOM_BYTES = 8;
15
+ /** The last lane a response's links can take; past it a link goes unmarked. */
16
+ export const MAX_LINK_INDEX = BASE * BASE - 1;
17
+ /** A marker that is not one this package minted, or a lane out of range. */
18
+ export class MarkerError extends Error {
19
+ name = 'MarkerError';
20
+ }
21
+ function valueOf(character) {
22
+ const value = ALPHABET.indexOf(character);
23
+ if (value === -1)
24
+ throw new MarkerError(`Not in the marker alphabet: ${character}.`);
25
+ return value;
26
+ }
27
+ function checkValue(values) {
28
+ let sum = 0;
29
+ let factor = 2;
30
+ // From the last character back, doubling every other one.
31
+ for (const value of [...values].reverse()) {
32
+ const addend = factor * value;
33
+ sum += Math.floor(addend / BASE) + (addend % BASE);
34
+ factor = factor === 2 ? 1 : 2;
35
+ }
36
+ return (BASE - (sum % BASE)) % BASE;
37
+ }
38
+ function withCheck(values) {
39
+ return [...values, checkValue(values)]
40
+ .map((value) => ALPHABET.charAt(value))
41
+ .join('');
42
+ }
43
+ /** A response marker from eight random bytes. */
44
+ export function mintMarker(random) {
45
+ if (random.length !== RANDOM_BYTES)
46
+ throw new MarkerError(`A marker needs ${String(RANDOM_BYTES)} random bytes, not ${String(random.length)}.`);
47
+ let bits = 0n;
48
+ for (const byte of random)
49
+ bits = (bits << 8n) | BigInt(byte);
50
+ const values = [];
51
+ for (let index = PAYLOAD_LENGTH - 1; index >= 0; index -= 1)
52
+ values.push(Number((bits >> BigInt(index * 5)) & 31n));
53
+ return withCheck(values);
54
+ }
55
+ /** A response marker from this runtime's strong random source. */
56
+ export function newMarker() {
57
+ return mintMarker(crypto.getRandomValues(new Uint8Array(RANDOM_BYTES)));
58
+ }
59
+ /**
60
+ * Reads a value as an agent sent it back, as the engine does: case-folded,
61
+ * `-` dropped, I and L read as 1 and O as 0; then 14 or 16 characters of the
62
+ * alphabet whose check character holds. Only a value it reads as valid is a
63
+ * marker: anything else, an image's `h=600` or a path's `/h/getting-started`,
64
+ * is the site's own.
65
+ */
66
+ export function parseMarker(raw) {
67
+ const text = raw
68
+ .toUpperCase()
69
+ .replaceAll('-', '')
70
+ .replaceAll('I', '1')
71
+ .replaceAll('L', '1')
72
+ .replaceAll('O', '0');
73
+ if (text.length !== PAYLOAD_LENGTH + 1 &&
74
+ text.length !== PAYLOAD_LENGTH + LANE_LENGTH + 1)
75
+ return { valid: false, reason: 'length' };
76
+ const values = [];
77
+ for (const character of text) {
78
+ const value = ALPHABET.indexOf(character);
79
+ if (value === -1)
80
+ return { valid: false, reason: 'alphabet' };
81
+ values.push(value);
82
+ }
83
+ const check = values.pop();
84
+ if (check !== checkValue(values))
85
+ return { valid: false, reason: 'check' };
86
+ const [high, low] = values.slice(PAYLOAD_LENGTH);
87
+ return {
88
+ valid: true,
89
+ base: text.slice(0, PAYLOAD_LENGTH),
90
+ link: high === undefined || low === undefined ? null : high * BASE + low,
91
+ };
92
+ }
93
+ /** The marker for one link of a response: its lane. */
94
+ export function linkMarker(marker, index) {
95
+ if (marker.length !== PAYLOAD_LENGTH + 1)
96
+ throw new MarkerError(`Not a response marker: ${marker}.`);
97
+ if (!Number.isInteger(index) || index < 0 || index > MAX_LINK_INDEX)
98
+ throw new MarkerError(`A lane is 0 to ${String(MAX_LINK_INDEX)}, not ${String(index)}.`);
99
+ const values = Array.from(marker.slice(0, PAYLOAD_LENGTH), valueOf);
100
+ values.push(Math.floor(index / BASE), index % BASE);
101
+ return withCheck(values);
102
+ }
@@ -0,0 +1,40 @@
1
+ /** An idle timeout a cookie cannot carry. */
2
+ export declare class SessionTimeoutError extends Error {
3
+ readonly name = "SessionTimeoutError";
4
+ }
5
+ /**
6
+ * A session id minted at `now`, milliseconds since the epoch, from this
7
+ * runtime's strong random source. It needs no secure context, as
8
+ * `crypto.randomUUID` does.
9
+ */
10
+ export declare function newSessionId(now: number): string;
11
+ /** When a session was minted, from its id; null for an id `newSessionId` could not have minted. */
12
+ export declare function sessionStartOf(id: string): number | null;
13
+ export interface SessionCookieOptions {
14
+ readonly name: string;
15
+ /** Seconds without a request after which the session ends; 30 minutes by default. */
16
+ readonly idleTimeout?: number | undefined;
17
+ /**
18
+ * The domain the session is shared across, as `example.com` for
19
+ * `docs.example.com` and `app.example.com`; the one host that set it
20
+ * when absent.
21
+ */
22
+ readonly domain?: string | undefined;
23
+ }
24
+ export interface SessionCookie {
25
+ /**
26
+ * The session a `Cookie` header or `document.cookie` holds, when it is one
27
+ * to go on with at `now`: minted as `newSessionId` mints, less than 24
28
+ * hours before. One minted after `now` is kept: a page's clock may run
29
+ * ahead of the edge's, and a page mints too.
30
+ */
31
+ read(cookies: string, now: number): string | null;
32
+ /**
33
+ * The `Set-Cookie` value, or the `document.cookie` write, that keeps
34
+ * `session` for another idle timeout. Never `HttpOnly`: the browser script
35
+ * reads it.
36
+ */
37
+ write(session: string, secure: boolean): string;
38
+ }
39
+ /** The session cookie a component reads and writes. */
40
+ export declare function sessionCookie(options: SessionCookieOptions): SessionCookie;
@@ -0,0 +1,69 @@
1
+ import { hexOf } from './id.js';
2
+ /**
3
+ * A visitor's session, kept as web analytics and PostHog keep one: it ends
4
+ * after 30 minutes without a request, and lasts 24 hours at most. The edge
5
+ * and the browser script share it in one cookie, which each writes again
6
+ * with the idle timeout as its `Max-Age` on every answer or page view, so the
7
+ * browser drops it once the visitor has been idle that long. The id is a
8
+ * UUIDv7, which carries the time it was minted, so either tells a session's
9
+ * age from its id and keeps nothing else.
10
+ */
11
+ /** Seconds without a request after which a session ends, unless a site sets its own. */
12
+ const SESSION_IDLE_TIMEOUT = 30 * 60;
13
+ /** How long a session lasts at most, idle or not, in milliseconds. */
14
+ const SESSION_MAX_LENGTH = 24 * 60 * 60 * 1000;
15
+ /** A UUIDv7: a 48-bit time in milliseconds, the version, the variant, the rest random. */
16
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
17
+ /** An idle timeout a cookie cannot carry. */
18
+ export class SessionTimeoutError extends Error {
19
+ name = 'SessionTimeoutError';
20
+ }
21
+ /**
22
+ * A session id minted at `now`, milliseconds since the epoch, from this
23
+ * runtime's strong random source. It needs no secure context, as
24
+ * `crypto.randomUUID` does.
25
+ */
26
+ export function newSessionId(now) {
27
+ const time = Math.floor(now).toString(16).padStart(12, '0');
28
+ const random = hexOf(crypto.getRandomValues(new Uint8Array(10)));
29
+ // The variant's two bits are 10; the two after them are random.
30
+ const variant = (8 | (Number.parseInt(random.charAt(3), 16) & 3)).toString(16);
31
+ return `${time.slice(0, 8)}-${time.slice(8)}-7${random.slice(0, 3)}-${variant}${random.slice(4, 7)}-${random.slice(7, 19)}`;
32
+ }
33
+ /** When a session was minted, from its id; null for an id `newSessionId` could not have minted. */
34
+ export function sessionStartOf(id) {
35
+ if (!SESSION_ID.test(id))
36
+ return null;
37
+ return Number.parseInt(id.slice(0, 8) + id.slice(9, 13), 16);
38
+ }
39
+ /** The session cookie a component reads and writes. */
40
+ export function sessionCookie(options) {
41
+ const { name, idleTimeout = SESSION_IDLE_TIMEOUT, domain } = options;
42
+ if (!Number.isSafeInteger(idleTimeout) || idleTimeout < 1)
43
+ throw new SessionTimeoutError(`A session's idle timeout is a whole number of seconds, at least 1, not ${String(idleTimeout)}.`);
44
+ return {
45
+ read(cookies, now) {
46
+ for (const part of cookies.split(';')) {
47
+ const [key, ...value] = part.trim().split('=');
48
+ if (key !== name)
49
+ continue;
50
+ const session = value.join('=');
51
+ const start = sessionStartOf(session);
52
+ return start !== null && now - start < SESSION_MAX_LENGTH
53
+ ? session
54
+ : null;
55
+ }
56
+ return null;
57
+ },
58
+ write(session, secure) {
59
+ return [
60
+ `${name}=${session}`,
61
+ 'Path=/',
62
+ `Max-Age=${String(idleTimeout)}`,
63
+ ...(domain === undefined ? [] : [`Domain=${domain}`]),
64
+ 'SameSite=Lax',
65
+ ...(secure ? ['Secure'] : []),
66
+ ].join('; ');
67
+ },
68
+ };
69
+ }
@@ -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;