agentrail-edge 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,48 +1,33 @@
1
1
  # agentrail-edge
2
2
 
3
- The Agentrail edge, in front of a site on the Fetch API: Cloudflare Workers,
4
- Vercel Routing Middleware, or anything else that speaks it. Each request is
5
- answered through the site's origin and recorded as one event, sent to the
6
- Agentrail collector after the answer through the platform's `waitUntil`, so
7
- recording never slows a request.
8
-
9
- In an answer meant for agents (Markdown, `llms.txt`), every link to the
10
- site's own hosts is marked, so the request an agent makes by following one
11
- is joined to the page it came from. The marker comes off before the origin
12
- sees the request, and only a real one: an `h` parameter or an `/h/` path
13
- that does not read as a marker (an image's `h=600`) is the site's own, and
14
- the request reaches the origin exactly as it was sent. A visitor's address,
15
- and any verified principal, leave the edge only hashed with the workspace's
16
- hash key.
17
-
18
- Requests one edge answers share collector calls: an event goes at once when
19
- no call is under way, and waits for the next one, with every other that
20
- waited, when one is. A quiet site sends a call per request; a busy one
21
- about one per round trip to the collector. A call that failed is tried
22
- again after a random wait, so isolates that failed together do not retry
23
- together, and never sooner than a `Retry-After` the collector sends. Every
24
- call ends within 25 seconds of its request's answer, inside the 30 seconds
25
- Cloudflare gives `waitUntil`; one that cannot is given up and told to
26
- `onError`, never left for the platform to cancel unseen.
27
-
28
- A visitor's session is a cookie the edge sets and the browser script reads
29
- (`agentrail_session`). As in web analytics, it ends after 30 minutes
30
- without a request, and a day after it began: every answer writes it again
31
- for another 30 minutes.
3
+ [![npm](https://img.shields.io/npm/v/agentrail-edge)](https://www.npmjs.com/package/agentrail-edge)
4
+ [![License](https://img.shields.io/github/license/agentrail-co/agentrail-js)](https://github.com/agentrail-co/agentrail-js/blob/main/LICENSE)
5
+
6
+ The Agentrail edge runs in front of your site on Cloudflare Workers, Vercel
7
+ Routing Middleware or any Fetch API runtime. It records every request,
8
+ including those from agents that never run JavaScript, and marks the links in
9
+ answers meant for agents (Markdown, `llms.txt`), so the next request an agent
10
+ makes is joined to the page it came from.
11
+
12
+ Recording happens after the answer, so a visitor never waits for it and never
13
+ sees it fail. A visitor's address and any verified identity leave the edge only
14
+ as keyed hashes. With a request's `Accept` and `Accept-Encoding`, the edge
15
+ sends the names of its headers, never their values: the names the caller
16
+ wrote, lower-cased, without those your platform or a proxy added on the way
17
+ (`cf-*`, `x-vercel-*`, `x-forwarded-*` and the like), at most 40 in 512
18
+ characters.
19
+
20
+ ## Install
32
21
 
33
22
  ```sh
34
23
  npm install agentrail-edge
35
24
  ```
36
25
 
37
- Before 1.0, a minor version (0.1 to 0.2) may change what the package offers.
38
-
39
- ## Cloudflare Workers
26
+ In Agentrail, open **Journeys → Set up** and choose **Edge**. Agentrail shows
27
+ the **Secret** and the **Hash key** once: keep them in your platform's
28
+ secrets as `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY`.
40
29
 
41
- The secret and the hash key come from Agentrail's setup page, as the
42
- `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY` environment variables; the
43
- collector's address is the one the setup page shows. Create the edge once,
44
- on the first request, so the requests an isolate answers share calls; one
45
- created per request still works, and sends a call per request.
30
+ ## Quick start: Cloudflare Workers
46
31
 
47
32
  ```js
48
33
  import { cloudflare, createEdge } from 'agentrail-edge';
@@ -57,41 +42,29 @@ export default {
57
42
  secret: env.AGENTRAIL_SECRET,
58
43
  },
59
44
  hashKey: env.AGENTRAIL_HASH_KEY,
60
- hosts: { 'docs.example.com': 'query' },
45
+ hosts: { 'docs.example.com': 'query' }, // your own hosts
61
46
  });
62
47
  return edge.handle(request, cloudflare(ctx));
63
48
  },
64
49
  };
65
50
  ```
66
51
 
67
- ## Vercel
68
-
69
- In Routing Middleware, `vercel({ waitUntil, origin })` takes `waitUntil`
70
- from `@vercel/functions` and fetches the site itself, since middleware cannot
71
- rewrite an answer it passes on. Create the edge once, outside the handler.
72
-
73
- ## Options
74
-
75
- - `hosts`: the site's own hosts, and how a link to each is marked: `'query'`
76
- adds the `h` parameter, `'path'` an `/h/<marker>` prefix, for a host whose
77
- calls an extra parameter would break.
78
- - `queryAllowlist`: query parameters a recorded path keeps; every other is
79
- dropped, and named as dropped.
80
- - `identify(request)`: the verified principal behind a request, by the site's
81
- own check of its method, URL and headers. It runs after the answer. A
82
- check that throws is told to `onError` as an `IdentifyError`, and the
83
- request is recorded without a principal.
84
- - `sessionIdleTimeout`: seconds without a request after which a session
85
- ends; 1800 (30 minutes) by default.
86
- - `sessionCookieDomain`: the domain a session is shared across, as
87
- `example.com` for `docs.example.com` and `app.example.com`; by default,
88
- the one host. Give the browser script the same two values.
89
- - `sessionCookie`, `service`, `fetch`: the session cookie's name, the
90
- service the events name, and the fetch the collector's calls go through.
91
- - `onError(error)`: told of events that could not be sent, and of an
92
- `identify` that threw; they are logged otherwise. Neither ever reaches the
93
- visitor.
52
+ Create the edge once, on the first request, as this does: the requests an
53
+ isolate answers then share calls to the collector. On Vercel, use
54
+ `vercel({ waitUntil, origin })` in Routing Middleware; the guide has the full
55
+ example.
56
+
57
+ ## Documentation
58
+
59
+ | Topic | Guide |
60
+ | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
61
+ | Cloudflare and Vercel setup, every option, identifying a caller | [Install the edge](https://www.agentrail.co/docs/guides/journeys-edge) |
62
+ | Handing the trace to your servers, and rewriting paths before it | [Install the edge](https://www.agentrail.co/docs/guides/journeys-edge) |
63
+ | Keeping your own servers' calls out (`ignoreRequest`) | [Leave out your own servers](https://www.agentrail.co/docs/guides/journeys-own-servers) |
64
+ | What each request records, including the caller's facts and location | [What Agentrail records](https://www.agentrail.co/docs/guides/journeys-data) |
65
+
66
+ Before 1.0, a minor version (0.1 to 0.2) may change what the package offers.
94
67
 
95
68
  ## Licence
96
69
 
97
- [Apache-2.0](LICENSE).
70
+ [Apache-2.0](https://github.com/agentrail-co/agentrail-js/blob/main/LICENSE).
package/dist/edge.d.ts CHANGED
@@ -1,9 +1,25 @@
1
1
  import { type PrincipalKind } from 'agentrail-core';
2
2
  import { type MarkedHosts } from './links.js';
3
+ /**
4
+ * The header names no caller writes: what a proxy or the platform added on
5
+ * the way (Cloudflare's `cf-*`, Vercel's `x-vercel-*`, `x-forwarded-*`), and
6
+ * Agentrail's own first-party mark. The contract's
7
+ * (`otlp.headerNames.addedOnTheWay`); the tests hold this copy to it.
8
+ */
9
+ export declare const ADDED_ON_THE_WAY: RegExp;
10
+ /** The most header names an event keeps, and the most characters they take joined (`otlp.headerNames`). */
11
+ export declare const HEADER_NAMES_KEPT: {
12
+ readonly count: 40;
13
+ readonly characters: 512;
14
+ };
3
15
  /** The site's `identify` threw: the request is recorded without a principal. */
4
16
  export declare class IdentifyError extends Error {
5
17
  readonly name = "IdentifyError";
6
18
  }
19
+ /** The site's `ignoreRequest` threw: the request is recorded as any other. */
20
+ export declare class IgnoreRequestError extends Error {
21
+ readonly name = "IgnoreRequestError";
22
+ }
7
23
  /**
8
24
  * What the site's own check reads of a request: never its body, which has
9
25
  * gone to the origin by the time the check runs.
@@ -15,6 +31,9 @@ export interface Principal {
15
31
  readonly id: string;
16
32
  readonly actingUserId?: string | null;
17
33
  }
34
+ export declare class TraceHandoffSigningError extends Error {
35
+ readonly name = "TraceHandoffSigningError";
36
+ }
18
37
  export interface EdgeOptions {
19
38
  /** Where events go, and the edge source's secret. */
20
39
  readonly collector: {
@@ -44,6 +63,16 @@ export interface EdgeOptions {
44
63
  * method, URL and headers. It runs after the answer.
45
64
  */
46
65
  readonly identify?: (request: RequestHead) => Principal | null | Promise<Principal | null>;
66
+ /**
67
+ * Requests this edge passes to the origin untouched and records nothing
68
+ * of, by the site's own check of their method, URL and headers: the calls
69
+ * the site's own servers make, which are neither a visitor nor an agent.
70
+ * Check something only your servers can send, such as a shared secret: a
71
+ * user agent or an address is what any caller can claim. A check that
72
+ * throws is told to `onError` as an `IgnoreRequestError`, and the request
73
+ * is recorded as any other.
74
+ */
75
+ readonly ignoreRequest?: (request: RequestHead) => boolean;
47
76
  /** The service the events name; the request's host by default. */
48
77
  readonly service?: string;
49
78
  /**
@@ -51,17 +80,47 @@ export interface EdgeOptions {
51
80
  * Logs by default.
52
81
  */
53
82
  readonly onError?: (error: Error) => void;
83
+ /**
84
+ * Registrable hosts, beside the known signers, whose Web Bot Auth key
85
+ * directories this edge may read; a signature by any other host is
86
+ * recorded as an unsupported claim, and that host is never contacted.
87
+ */
88
+ readonly signers?: readonly string[];
54
89
  /** The fetch the collector's calls go through; the platform's own by default. */
55
90
  readonly fetch?: typeof fetch;
56
91
  }
92
+ /**
93
+ * What the platform tells the edge of the client beyond its address, where
94
+ * it tells anything: features for the collector's classifier, never keys.
95
+ */
96
+ export interface PlatformSignals {
97
+ readonly city?: string | null;
98
+ readonly region?: string | null;
99
+ readonly source?: 'cloudflare' | 'vercel' | 'source';
100
+ /** The client's autonomous system number. */
101
+ readonly asn: number | null;
102
+ /** The client's country, two letters. */
103
+ readonly country: string | null;
104
+ /** The client's TLS fingerprint, JA4. */
105
+ readonly ja4: string | null;
106
+ /** A bot the platform verified against its own directory. */
107
+ readonly verifiedBot: {
108
+ readonly category: string;
109
+ readonly name: string | null;
110
+ } | null;
111
+ }
57
112
  /** What the platform the edge runs on provides. */
58
113
  export interface EdgeAdapter {
59
114
  /** The client's address, as the platform saw it; null when it says none. */
60
115
  clientAddress(request: Request): string | null;
116
+ /** What else the platform says of the client; absent on a platform that says nothing. */
117
+ signals?(request: Request): PlatformSignals;
61
118
  /** Keeps the platform running work past the answer. */
62
119
  waitUntil(work: Promise<unknown>): void;
63
120
  /** Sends the request on to the site. */
64
121
  origin(request: Request): Promise<Response>;
122
+ /** Apply path/query rewrites here, before the final request is signed. */
123
+ prepareOriginRequest?(request: Request): Request | Promise<Request>;
65
124
  /** This edge instance, when the platform names one. */
66
125
  readonly instance: string | null;
67
126
  }
@@ -70,7 +129,7 @@ export interface Edge {
70
129
  handle(request: Request, adapter: EdgeAdapter): Promise<Response>;
71
130
  }
72
131
  export declare function createEdge(options: EdgeOptions): Edge;
73
- /** Cloudflare Workers: the platform's client address, and the Worker's `waitUntil`. */
132
+ /** Cloudflare Workers: the platform's client address, its word on the client, and the Worker's `waitUntil`. */
74
133
  export declare function cloudflare(context: {
75
134
  waitUntil(work: Promise<unknown>): void;
76
135
  }, origin?: (request: Request) => Promise<Response>): EdgeAdapter;
@@ -83,4 +142,5 @@ export declare function cloudflare(context: {
83
142
  export declare function vercel(options: {
84
143
  readonly waitUntil: (work: Promise<unknown>) => void;
85
144
  readonly origin: (request: Request) => Promise<Response>;
145
+ readonly prepareOriginRequest?: EdgeAdapter['prepareOriginRequest'];
86
146
  }): EdgeAdapter;
package/dist/edge.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createCollector, formatTraceparent, hashKeyIdOf, keyedHash, newSessionId, newSpanId, newTraceId, parseMarker, parseTraceparent, sessionCookie, VERSION, } from 'agentrail-core';
1
+ import { createCollector, TRACE_HANDOFF_HEADER, signTraceHandoff, traceHandoffTarget, createSignatureVerifier, formatTraceparent, hashKeyIdOf, keyedHash, newSessionId, newSpanId, newTraceId, parseMarker, parseTraceparent, sessionCookie, VERSION, } from 'agentrail-core';
2
2
  import { MARKER_PARAMETER, markLinks } from './links.js';
3
3
  /**
4
4
  * The edge adapter: in front of a customer's site, on the Fetch API, it
@@ -13,7 +13,12 @@ import { MARKER_PARAMETER, markLinks } from './links.js';
13
13
  * `traceparent`, with any caller's trace kept as a span link only: a public
14
14
  * endpoint never takes its parent from outside;
15
15
  * - the client address and any verified principal, hashed with the
16
- * workspace's key before anything leaves.
16
+ * workspace's key before anything leaves;
17
+ * - what the caller and the network said of it, for the collector's
18
+ * classifier of who the caller is: the `Accept`, the caller's header names
19
+ * and `Accept-Encoding`, and fetch metadata, the
20
+ * platform's word on the network and its verified bots, and a Web Bot
21
+ * Auth signature checked against the keys the agent publishes.
17
22
  *
18
23
  * The events go to the collector after the answer, through the platform's
19
24
  * `waitUntil`, so recording never slows a request. Requests one edge answers
@@ -32,10 +37,36 @@ const MARKABLE_BYTES = 2 * 1024 * 1024;
32
37
  * `identify`.
33
38
  */
34
39
  const SEND_WITHIN_MS = 25_000;
40
+ /** The longest `Accept` the collector takes; a longer one is cut. */
41
+ const ACCEPT_LENGTH = 256;
42
+ /** The longest `Accept-Encoding` the collector takes; a longer one is cut. */
43
+ const ACCEPT_ENCODING_LENGTH = 128;
44
+ /**
45
+ * The header names no caller writes: what a proxy or the platform added on
46
+ * the way (Cloudflare's `cf-*`, Vercel's `x-vercel-*`, `x-forwarded-*`), and
47
+ * Agentrail's own first-party mark. The contract's
48
+ * (`otlp.headerNames.addedOnTheWay`); the tests hold this copy to it.
49
+ */
50
+ export const ADDED_ON_THE_WAY = /^(?:x-forwarded-.*|x-amzn-.*|x-vercel-.*|cf-.*|forwarded|via|x-real-ip|cdn-loop|true-client-ip|agentrail-first-party)$/iu;
51
+ /** The most header names an event keeps, and the most characters they take joined (`otlp.headerNames`). */
52
+ export const HEADER_NAMES_KEPT = { count: 40, characters: 512 };
53
+ /** The longest `Sec-Fetch-*` value the collector takes; the browsers' are one word. */
54
+ const FETCH_METADATA_LENGTH = 32;
55
+ /** The longest JA4 the collector takes. */
56
+ const JA4_LENGTH = 64;
57
+ /** The longest verified-bot category the collector takes. */
58
+ const BOT_CATEGORY_LENGTH = 64;
35
59
  /** The site's `identify` threw: the request is recorded without a principal. */
36
60
  export class IdentifyError extends Error {
37
61
  name = 'IdentifyError';
38
62
  }
63
+ /** The site's `ignoreRequest` threw: the request is recorded as any other. */
64
+ export class IgnoreRequestError extends Error {
65
+ name = 'IgnoreRequestError';
66
+ }
67
+ export class TraceHandoffSigningError extends Error {
68
+ name = 'TraceHandoffSigningError';
69
+ }
39
70
  /**
40
71
  * The markers a query carries in `h`, and the query without them, every
41
72
  * other pair exactly as it came: a value that does not read as a marker is
@@ -136,7 +167,8 @@ export function createEdge(options) {
136
167
  // Every call names the key its events were hashed with. Its id is a
137
168
  // digest, which WebCrypto only gives asynchronously, so the collector is
138
169
  // ready from the first send on, never on a request's path.
139
- const collector = hashKeyIdOf(hashKey).then((hashKeyId) => createCollector({
170
+ const keyId = hashKeyIdOf(hashKey);
171
+ const collector = keyId.then((hashKeyId) => createCollector({
140
172
  endpoint: options.collector.endpoint,
141
173
  secret: options.collector.secret,
142
174
  component: {
@@ -148,6 +180,39 @@ export function createEdge(options) {
148
180
  onError,
149
181
  ...(options.fetch ? { fetch: options.fetch } : {}),
150
182
  }));
183
+ // Checks each signed request against the keys its agent publishes; the
184
+ // directories are read once per `max-age` for the life of the edge.
185
+ const verify = createSignatureVerifier({
186
+ ...(options.fetch ? { fetch: options.fetch } : {}),
187
+ ...(options.signers ? { signers: options.signers } : {}),
188
+ });
189
+ async function requestForOrigin(request, adapter, span) {
190
+ const prepared = await (adapter.prepareOriginRequest?.(request) ?? request);
191
+ const headers = new Headers(prepared.headers);
192
+ const traceparent = formatTraceparent(span);
193
+ headers.set('traceparent', traceparent);
194
+ headers.delete('tracestate');
195
+ headers.delete('baggage');
196
+ headers.delete(TRACE_HANDOFF_HEADER);
197
+ try {
198
+ headers.set(TRACE_HANDOFF_HEADER, await signTraceHandoff({
199
+ traceparent,
200
+ hashKeyId: await keyId,
201
+ issuedAt: Date.now(),
202
+ method: prepared.method,
203
+ target: traceHandoffTarget(prepared.url),
204
+ }, hashKey));
205
+ }
206
+ catch (error) {
207
+ const failure = new TraceHandoffSigningError('Agentrail could not sign the origin trace handoff.', { cause: error });
208
+ // Reporting may throw in the site's callback; it belongs to waitUntil,
209
+ // so a capture failure still forwards the application request unsigned.
210
+ adapter.waitUntil(Promise.resolve().then(() => {
211
+ onError(failure);
212
+ }));
213
+ }
214
+ return new Request(prepared, { headers });
215
+ }
151
216
  /** A path as it is recorded: the allowlisted query only. */
152
217
  function recordedPath(url) {
153
218
  const kept = new URLSearchParams([...url.searchParams].filter(([name]) => allowlist.has(name)));
@@ -225,6 +290,8 @@ export function createEdge(options) {
225
290
  const location = recordedLocation(observed.location, url);
226
291
  const principal = await principalOf(request);
227
292
  const actingUserId = principal?.actingUserId ?? null;
293
+ const signature = await verify(request);
294
+ const { signals } = input;
228
295
  return {
229
296
  schemaVersion: 1,
230
297
  id: crypto.randomUUID(),
@@ -258,11 +325,40 @@ export function createEdge(options) {
258
325
  linksOut: [...observed.linksOut],
259
326
  },
260
327
  actor: {
328
+ location: signals === null ||
329
+ (signals.country === null && !signals.city && !signals.region)
330
+ ? null
331
+ : {
332
+ country: signals.country,
333
+ city: cut(signals.city, 128),
334
+ region: cut(signals.region, 128),
335
+ source: signals.source ?? 'source',
336
+ observedAt: new Date(input.start).toISOString(),
337
+ },
261
338
  egress: input.address === null
262
339
  ? null
263
340
  : await keyedHash(hashKey, input.address),
264
341
  userAgent: request.headers.get('user-agent'),
265
342
  client: null,
343
+ clientVersion: null,
344
+ protocol: null,
345
+ accept: cut(request.headers.get('accept'), ACCEPT_LENGTH),
346
+ transport: transportOf(request.headers),
347
+ fetchMetadata: fetchMetadataOf(request.headers),
348
+ network: signals === null
349
+ ? null
350
+ : {
351
+ asn: signals.asn,
352
+ country: signals.country,
353
+ ja4: cut(signals.ja4, JA4_LENGTH),
354
+ },
355
+ signature,
356
+ verifiedBot: signals?.verifiedBot === null || signals === null
357
+ ? null
358
+ : {
359
+ category: signals.verifiedBot.category.slice(0, BOT_CATEGORY_LENGTH),
360
+ name: signals.verifiedBot.name,
361
+ },
266
362
  },
267
363
  principal: principal === null
268
364
  ? null
@@ -296,8 +392,33 @@ export function createEdge(options) {
296
392
  ],
297
393
  };
298
394
  }
395
+ /** Whether the site's own check leaves this request out; a broken check leaves nothing out. */
396
+ function ignored(request, adapter) {
397
+ if (options.ignoreRequest === undefined)
398
+ return false;
399
+ try {
400
+ return options.ignoreRequest(request);
401
+ }
402
+ catch (error) {
403
+ const failure = new IgnoreRequestError("The site's ignoreRequest threw; the request is recorded.", { cause: error });
404
+ adapter.waitUntil(Promise.resolve().then(() => {
405
+ onError(failure);
406
+ }));
407
+ return false;
408
+ }
409
+ }
299
410
  return {
300
411
  async handle(request, adapter) {
412
+ if (ignored(request, adapter)) {
413
+ // The site's own rewrite still applies: it decides where a request
414
+ // goes, which is nothing to do with whether it is recorded.
415
+ const prepared = await (adapter.prepareOriginRequest?.(request) ??
416
+ request);
417
+ const headers = new Headers(prepared.headers);
418
+ // Only this edge signs a handoff, whatever the caller sent.
419
+ headers.delete(TRACE_HANDOFF_HEADER);
420
+ return adapter.origin(new Request(prepared, { headers }));
421
+ }
301
422
  const start = Date.now();
302
423
  const url = new URL(request.url);
303
424
  const query = markersOffQuery(url.search);
@@ -318,6 +439,8 @@ export function createEdge(options) {
318
439
  headers.set('traceparent', formatTraceparent(span));
319
440
  // The caller's vendor state belongs to the caller's trace.
320
441
  headers.delete('tracestate');
442
+ headers.delete('baggage');
443
+ headers.delete(TRACE_HANDOFF_HEADER);
321
444
  const forwarded = new Request(originUrl, {
322
445
  method: request.method,
323
446
  headers,
@@ -349,12 +472,13 @@ export function createEdge(options) {
349
472
  try {
350
473
  // Links resolve against the address the origin answered for, so a
351
474
  // relative one never carries the marker this request came with.
352
- const answer = await marked(request.method, originUrl, await adapter.origin(forwarded), observed);
475
+ const answer = await marked(request.method, originUrl, await adapter.origin(await requestForOrigin(forwarded, adapter, span)), observed);
353
476
  observed.status = answer.status;
354
477
  observed.location = answer.headers.get('location');
355
478
  observed.contentType = answer.headers.get('content-type');
356
479
  // On every answer, so the session lasts another idle timeout.
357
480
  const withCookie = new Response(answer.body, answer);
481
+ withCookie.headers.delete(TRACE_HANDOFF_HEADER);
358
482
  withCookie.headers.append('set-cookie', cookie.write(session, url.protocol === 'https:'));
359
483
  return withCookie;
360
484
  }
@@ -368,6 +492,7 @@ export function createEdge(options) {
368
492
  request: head,
369
493
  url,
370
494
  address: adapter.clientAddress(request),
495
+ signals: adapter.signals?.(request) ?? null,
371
496
  instance: adapter.instance,
372
497
  start,
373
498
  end,
@@ -382,10 +507,94 @@ export function createEdge(options) {
382
507
  },
383
508
  };
384
509
  }
385
- /** Cloudflare Workers: the platform's client address, and the Worker's `waitUntil`. */
510
+ /** A header or platform value cut to what the collector takes; null for none or an empty one. */
511
+ function cut(value, length) {
512
+ return typeof value === 'string' && value.length > 0
513
+ ? value.slice(0, length)
514
+ : null;
515
+ }
516
+ /**
517
+ * How the caller's HTTP library wrote the request: its header names, the
518
+ * caller's own only, as a Fetch `Headers` holds them (lower-cased and
519
+ * sorted), within what an event keeps, a name past that left out whole; and
520
+ * its `Accept-Encoding`. Names only, never a value. Null where no name is
521
+ * the caller's.
522
+ */
523
+ function transportOf(headers) {
524
+ const kept = [];
525
+ let length = 0;
526
+ for (const name of headers.keys()) {
527
+ if (ADDED_ON_THE_WAY.test(name))
528
+ continue;
529
+ const grown = length + name.length + (kept.length === 0 ? 0 : 1);
530
+ if (kept.length === HEADER_NAMES_KEPT.count ||
531
+ grown > HEADER_NAMES_KEPT.characters)
532
+ break;
533
+ kept.push(name);
534
+ length = grown;
535
+ }
536
+ return kept.length === 0
537
+ ? null
538
+ : {
539
+ headerNames: kept.join(','),
540
+ acceptEncoding: cut(headers.get('accept-encoding'), ACCEPT_ENCODING_LENGTH),
541
+ };
542
+ }
543
+ /** `Sec-Fetch-Site`, `-Mode` and `-Dest` together, as a browser sends all three. */
544
+ function fetchMetadataOf(headers) {
545
+ const site = cut(headers.get('sec-fetch-site'), FETCH_METADATA_LENGTH);
546
+ const mode = cut(headers.get('sec-fetch-mode'), FETCH_METADATA_LENGTH);
547
+ const dest = cut(headers.get('sec-fetch-dest'), FETCH_METADATA_LENGTH);
548
+ return site === null || mode === null || dest === null
549
+ ? null
550
+ : { site, mode, dest };
551
+ }
552
+ /** A two-letter country, as the platforms give one; anything else is none. */
553
+ function decodedCity(value) {
554
+ if (value === null)
555
+ return null;
556
+ try {
557
+ return cut(decodeURIComponent(value), 128);
558
+ }
559
+ catch (error) {
560
+ if (error instanceof URIError)
561
+ return null;
562
+ throw error;
563
+ }
564
+ }
565
+ function countryOf(value) {
566
+ return typeof value === 'string' && /^[A-Z]{2}$/u.test(value) ? value : null;
567
+ }
568
+ function recordOf(value) {
569
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
570
+ ? value
571
+ : null;
572
+ }
573
+ /**
574
+ * What Cloudflare tells a Worker of the client in `request.cf`: its
575
+ * autonomous system and country on every plan; its JA4 under
576
+ * `botManagement`, and the category of a verified bot, where the zone's
577
+ * plan has Bot Management.
578
+ */
579
+ function cloudflareSignals(request) {
580
+ const cf = recordOf(request.cf);
581
+ const bot = recordOf(cf?.botManagement);
582
+ const category = cut(typeof cf?.verifiedBotCategory === 'string' ? cf.verifiedBotCategory : null, BOT_CATEGORY_LENGTH);
583
+ return {
584
+ asn: typeof cf?.asn === 'number' ? cf.asn : null,
585
+ country: countryOf(cf?.country),
586
+ city: typeof cf?.city === 'string' ? cut(cf.city, 128) : null,
587
+ region: typeof cf?.region === 'string' ? cut(cf.region, 128) : null,
588
+ source: 'cloudflare',
589
+ ja4: typeof bot?.ja4 === 'string' ? bot.ja4 : null,
590
+ verifiedBot: category === null ? null : { category, name: null },
591
+ };
592
+ }
593
+ /** Cloudflare Workers: the platform's client address, its word on the client, and the Worker's `waitUntil`. */
386
594
  export function cloudflare(context, origin = (request) => fetch(request)) {
387
595
  return {
388
596
  clientAddress: (request) => request.headers.get('cf-connecting-ip'),
597
+ signals: cloudflareSignals,
389
598
  waitUntil: (work) => {
390
599
  context.waitUntil(work);
391
600
  },
@@ -404,6 +613,20 @@ export function vercel(options) {
404
613
  clientAddress: (request) => request.headers.get('x-real-ip') ??
405
614
  request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
406
615
  null,
616
+ // Vercel's edge names the country and the JA4 in headers; its verified
617
+ // bots are BotID's, read by `checkBotId()` in the app, not here.
618
+ signals: (request) => ({
619
+ asn: null,
620
+ country: countryOf(request.headers.get('x-vercel-ip-country')),
621
+ city: decodedCity(request.headers.get('x-vercel-ip-city')),
622
+ region: cut(request.headers.get('x-vercel-ip-country-region'), 128),
623
+ source: 'vercel',
624
+ ja4: request.headers.get('x-vercel-ja4-digest'),
625
+ verifiedBot: null,
626
+ }),
627
+ ...(options.prepareOriginRequest === undefined
628
+ ? {}
629
+ : { prepareOriginRequest: options.prepareOriginRequest }),
407
630
  waitUntil: options.waitUntil,
408
631
  origin: options.origin,
409
632
  instance: null,
package/dist/index.d.ts CHANGED
@@ -3,5 +3,5 @@
3
3
  * Vercel or anything else on the Fetch API: one event per request, sent to
4
4
  * the collector, with markers, a session and a trace of its own.
5
5
  */
6
- export { IdentifyError, cloudflare, createEdge, vercel, type Edge, type EdgeAdapter, type EdgeOptions, type Principal, type RequestHead, } from './edge.js';
6
+ export { IdentifyError, IgnoreRequestError, TraceHandoffSigningError, cloudflare, createEdge, vercel, type Edge, type EdgeAdapter, type EdgeOptions, type PlatformSignals, type Principal, type RequestHead, } from './edge.js';
7
7
  export { MARKER_PARAMETER, markLinks, type MarkedHosts } from './links.js';
package/dist/index.js CHANGED
@@ -3,5 +3,5 @@
3
3
  * Vercel or anything else on the Fetch API: one event per request, sent to
4
4
  * the collector, with markers, a session and a trace of its own.
5
5
  */
6
- export { IdentifyError, cloudflare, createEdge, vercel, } from './edge.js';
6
+ export { IdentifyError, IgnoreRequestError, TraceHandoffSigningError, cloudflare, createEdge, vercel, } from './edge.js';
7
7
  export { MARKER_PARAMETER, markLinks } from './links.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentrail-edge",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "The Agentrail edge: in front of a site on Cloudflare Workers, Vercel or any Fetch API runtime, it records each request and marks the links agents follow.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  "node": ">=22"
26
26
  },
27
27
  "dependencies": {
28
- "agentrail-core": "0.1.0"
28
+ "agentrail-core": "0.3.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "24.13.3",