@robota-sdk/agent-transport 3.0.0-beta.81 → 3.0.0-beta.83

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +752 -0
  2. package/dist/browser/client.d.ts +2 -2
  3. package/dist/browser/client.js +1 -1
  4. package/dist/browser/index.d.ts +31 -11
  5. package/dist/browser/index.d.ts.map +1 -1
  6. package/dist/browser/index.js +1 -1
  7. package/dist/browser/index.js.map +1 -1
  8. package/dist/browser/observer-messages-Bx-xReUQ.js +2 -0
  9. package/dist/browser/observer-messages-Bx-xReUQ.js.map +1 -0
  10. package/dist/browser/{message-decoders-BB8n-H2X.d.ts → observer-messages-DC_8VHk9.d.ts} +104 -7
  11. package/dist/browser/observer-messages-DC_8VHk9.d.ts.map +1 -0
  12. package/dist/node/index.cjs +1 -1
  13. package/dist/node/index.d.cts +131 -14
  14. package/dist/node/index.d.cts.map +1 -1
  15. package/dist/node/index.d.ts +131 -14
  16. package/dist/node/index.d.ts.map +1 -1
  17. package/dist/node/index.js +1 -1
  18. package/dist/node/index.js.map +1 -1
  19. package/dist/node/node.cjs +1 -1
  20. package/dist/node/node.d.cts +177 -2
  21. package/dist/node/node.d.cts.map +1 -1
  22. package/dist/node/node.d.ts +178 -3
  23. package/dist/node/node.d.ts.map +1 -1
  24. package/dist/node/node.js +1 -1
  25. package/dist/node/node.js.map +1 -1
  26. package/package.json +13 -11
  27. package/src/__tests__/bearer-resource-gate.test.ts +120 -0
  28. package/src/__tests__/file-transfer.test.ts +281 -0
  29. package/src/__tests__/history-attached-budget.test.ts +216 -0
  30. package/src/__tests__/message-decoders.test.ts +201 -5
  31. package/src/__tests__/session-detail-loop-status.test.ts +169 -0
  32. package/src/__tests__/session-directory-messages.test.ts +192 -0
  33. package/src/__tests__/session-history-wire.test.ts +342 -0
  34. package/src/__tests__/session-message-handler-observe.test.ts +193 -0
  35. package/src/__tests__/session-message-handler.test.ts +82 -1
  36. package/src/__tests__/ws-broadcast-events.test.ts +10 -0
  37. package/src/client.ts +9 -1
  38. package/src/index.ts +14 -2
  39. package/src/loop-control-messages.ts +34 -0
  40. package/src/message-decoders.ts +82 -4
  41. package/src/node/bearer-resource-gate.ts +291 -0
  42. package/src/node/file-transfer.ts +530 -0
  43. package/src/node/index.ts +30 -0
  44. package/src/observer-messages.ts +36 -0
  45. package/src/open-prompts.ts +76 -0
  46. package/src/outbound-delivery.ts +11 -2
  47. package/src/protocol-session.ts +7 -1
  48. package/src/session-directory-messages.ts +85 -0
  49. package/src/session-events.ts +93 -18
  50. package/src/session-message-handler.ts +53 -8
  51. package/src/session-query-messages.ts +105 -4
  52. package/src/wire-messages.ts +105 -7
  53. package/dist/browser/message-decoders-BB8n-H2X.d.ts.map +0 -1
  54. package/dist/browser/message-decoders-CDmDoZPR.js +0 -2
  55. package/dist/browser/message-decoders-CDmDoZPR.js.map +0 -1
package/src/index.ts CHANGED
@@ -33,9 +33,13 @@
33
33
  */
34
34
 
35
35
  export { createSessionMessageHandler } from './session-message-handler.js';
36
- export type { ISessionMessageHandlerOptions } from './session-message-handler.js';
36
+ export type {
37
+ ISessionMessageHandlerOptions,
38
+ TSessionSurfaceRole,
39
+ } from './session-message-handler.js';
37
40
  // ARCH-030: the connection-scoped outbound delivery boundary every carrier builds and passes down.
38
41
  export {
42
+ ATTACHED_SURFACE_MAX_PENDING_BYTES,
39
43
  createOutboundDelivery,
40
44
  createPendingStallClock,
41
45
  isOverPendingBudget,
@@ -48,9 +52,17 @@ export type {
48
52
  TOutboundDeliver,
49
53
  } from './outbound-delivery.js';
50
54
  export { PROTOCOL_SESSION_EVENT_CLASSIFICATION } from './session-events.js';
55
+ // The one list of messages an observer may send: the host refuses the rest, a client sends no others.
56
+ export { isObserverMessageType } from './observer-messages.js';
51
57
  export type { TProtocolSessionEventClassification } from './session-events.js';
52
58
  export type { IProtocolSession } from './protocol-session.js';
53
- export type { TClientMessage, TServerMessage, TSeqServerMessage } from './wire-messages.js';
59
+ export type {
60
+ IWireHistoryEntry,
61
+ TClientMessage,
62
+ TServerMessage,
63
+ TSeqServerMessage,
64
+ TWireExecutionResult,
65
+ } from './wire-messages.js';
54
66
  // Issue #2045: the owner-side runtime decoders; carriers implement `raw → decodeFrame → typed`.
55
67
  export {
56
68
  MAX_INBOUND_FRAME_BYTES,
@@ -0,0 +1,34 @@
1
+ import type { TOutboundDeliver } from './outbound-delivery.js';
2
+ import type { IProtocolSession } from './protocol-session.js';
3
+ import type { TClientMessage } from './wire-messages.js';
4
+
5
+ type TLoopControlMessage = Extract<TClientMessage, { type: 'stop-waiting-loop' }>;
6
+
7
+ export function isLoopControlMessage(msg: TClientMessage): msg is TLoopControlMessage {
8
+ return msg.type === 'stop-waiting-loop';
9
+ }
10
+
11
+ /**
12
+ * Stop the self-paced loop that is waiting for its next wake. The session decides which loop, if
13
+ * any; the reply carries its outcome, and a session that throws is reported as a failed stop.
14
+ */
15
+ export function handleLoopControlMessage(
16
+ session: IProtocolSession,
17
+ deliver: TOutboundDeliver,
18
+ msg: TLoopControlMessage,
19
+ ): void {
20
+ const { requestId } = msg;
21
+ session.stopWaitingSelfPacedLoop().then(
22
+ (outcome) => deliver({ type: 'waiting_loop_stop', requestId, outcome }),
23
+ (error: unknown) =>
24
+ deliver({
25
+ type: 'waiting_loop_stop',
26
+ requestId,
27
+ outcome: { kind: 'failed', message: errorMessage(error) },
28
+ }),
29
+ );
30
+ }
31
+
32
+ function errorMessage(error: unknown): string {
33
+ return error instanceof Error ? error.message : String(error);
34
+ }
@@ -14,6 +14,8 @@
14
14
  * owner and is tracked there, not duplicated in a transport package.
15
15
  */
16
16
 
17
+ import { SESSION_CHANGE_REFUSAL_CODES } from '@robota-sdk/agent-interface-session';
18
+
17
19
  import type { TBackgroundControlAction, TClientMessage, TServerMessage } from './wire-messages.js';
18
20
 
19
21
  export type TMessageDecodeResult<TMessage> =
@@ -32,6 +34,7 @@ const isString = (v: unknown): v is string => typeof v === 'string';
32
34
  const isNonEmptyString = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
33
35
  const isBoolean = (v: unknown): v is boolean => typeof v === 'boolean';
34
36
  const isFiniteNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
37
+ const isCount = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) >= 0;
35
38
  const isOptional =
36
39
  (check: (v: unknown) => boolean) =>
37
40
  (v: unknown): boolean =>
@@ -42,6 +45,19 @@ const oneOf =
42
45
  (members: readonly string[]) =>
43
46
  (v: unknown): boolean =>
44
47
  typeof v === 'string' && members.includes(v);
48
+ /** A record, not an array, so a turn source added to the union without one here fails to compile. */
49
+ const TURN_SOURCES: Readonly<
50
+ Record<Extract<TServerMessage, { type: 'turn_source' }>['source'], true>
51
+ > = { user: true, 'agent-wakeup': true, peer: true, external: true };
52
+ /** A history entry's envelope is this package's (`IWireHistoryEntry`); its `data` is the recorder's. */
53
+ const isWireHistoryEntry = (v: unknown): boolean =>
54
+ isRecord(v) &&
55
+ isString(v['id']) &&
56
+ isString(v['timestamp']) &&
57
+ isString(v['category']) &&
58
+ isString(v['type']);
59
+ const isWireHistoryEntries = (v: unknown): boolean =>
60
+ Array.isArray(v) && v.every(isWireHistoryEntry);
45
61
 
46
62
  type TFieldCheck = (value: unknown) => boolean;
47
63
  type TVariantShape = Readonly<Record<string, TFieldCheck>>;
@@ -69,6 +85,7 @@ const isBackgroundTaskListFilter: TFieldCheck = (v) =>
69
85
  const isBackgroundTaskInput: TFieldCheck = (v) =>
70
86
  isRecord(v) && isOptional(isString)(v['prompt']) && isOptional(isString)(v['stdin']);
71
87
  const isBackgroundTaskLogCursor: TFieldCheck = (v) => isRecord(v) && isFiniteNumber(v['offset']);
88
+ const isExecutionDetailCursor: TFieldCheck = (v) => isRecord(v) && isCount(v['offset']);
72
89
  const isPermissionResultValue: TFieldCheck = (v) =>
73
90
  isBoolean(v) || v === 'allow-session' || v === 'allow-project';
74
91
  const isActionResponse: TFieldCheck = (v) =>
@@ -79,14 +96,43 @@ const isActionResponse: TFieldCheck = (v) =>
79
96
  isOptional(isString)(v['text'])) ||
80
97
  (v['type'] === 'cancelled' && v['values'] === undefined && v['text'] === undefined));
81
98
 
99
+ type TWaitingLoopStopOutcome = Extract<TServerMessage, { type: 'waiting_loop_stop' }>['outcome'];
100
+ /** Keyed by `kind`, so an outcome added to the union without a shape here fails to compile. */
101
+ const WAITING_LOOP_STOP_OUTCOME_SHAPES: Readonly<
102
+ Record<TWaitingLoopStopOutcome['kind'], TVariantShape>
103
+ > = {
104
+ none: {},
105
+ several: { message: isString },
106
+ stopped: { loopId: isNonEmptyString, message: isOptional(isString) },
107
+ failed: { loopId: isOptional(isNonEmptyString), message: isString },
108
+ };
109
+ const isWaitingLoopStopOutcome: TFieldCheck = (v) => {
110
+ if (!isRecord(v) || !isString(v['kind'])) return false;
111
+ const kind = v['kind'];
112
+ if (!Object.prototype.hasOwnProperty.call(WAITING_LOOP_STOP_OUTCOME_SHAPES, kind)) return false;
113
+ const shape = WAITING_LOOP_STOP_OUTCOME_SHAPES[kind as TWaitingLoopStopOutcome['kind']];
114
+ return Object.entries(shape).every(([field, check]) => check(v[field]));
115
+ };
116
+
82
117
  /** One entry per `TClientMessage` variant — a variant added to the union without one fails the test. */
83
118
  export const CLIENT_MESSAGE_SHAPES: Readonly<Record<TClientMessage['type'], TVariantShape>> = {
84
119
  submit: { prompt: isNonEmptyString },
85
- command: { name: isNonEmptyString, args: isOptional(isString) },
120
+ command: {
121
+ name: isNonEmptyString,
122
+ args: isOptional(isString),
123
+ requestId: isOptional(isNonEmptyString),
124
+ },
86
125
  abort: {},
87
126
  'cancel-queue': {},
88
127
  'get-messages': {},
128
+ 'get-history': { fromIndex: isOptional(isCount) },
129
+ 'get-prompts': {},
89
130
  'get-context': {},
131
+ 'get-commands': {},
132
+ 'get-status': {},
133
+ 'list-sessions': { requestId: isNonEmptyString },
134
+ 'new-session': { requestId: isOptional(isNonEmptyString) },
135
+ 'switch-session': { sessionId: isNonEmptyString, requestId: isOptional(isNonEmptyString) },
90
136
  'get-usage-report': {},
91
137
  'get-personal-usage-report': {
92
138
  requestId: isNonEmptyString,
@@ -100,6 +146,12 @@ export const CLIENT_MESSAGE_SHAPES: Readonly<Record<TClientMessage['type'], TVar
100
146
  'get-executing': {},
101
147
  'get-pending': {},
102
148
  'get-execution-workspace': {},
149
+ 'read-execution-detail': {
150
+ requestId: isNonEmptyString,
151
+ entryId: isNonEmptyString,
152
+ cursor: isOptional(isExecutionDetailCursor),
153
+ },
154
+ 'stop-waiting-loop': { requestId: isNonEmptyString },
103
155
  'get-background-tasks': { filter: isOptional(isBackgroundTaskListFilter) },
104
156
  'get-background-task': { taskId: isNonEmptyString },
105
157
  'get-background-job-groups': {},
@@ -130,9 +182,31 @@ export const SERVER_MESSAGE_SHAPES: Readonly<Record<TServerMessage['type'], TVar
130
182
  complete: { result: isRecord, ...authored },
131
183
  interrupted: { result: isRecord, ...authored },
132
184
  error: { message: isString, ...authored },
133
- command_result: { name: isString, message: isString, success: isBoolean },
185
+ command_result: {
186
+ name: isString,
187
+ message: isString,
188
+ success: isBoolean,
189
+ requestId: isOptional(isString),
190
+ },
134
191
  messages: { messages: isRecordArray },
192
+ history: { startIndex: isCount, total: isCount, entries: isWireHistoryEntries },
135
193
  context: { state: isRecord },
194
+ history_changed: {},
195
+ turn_source: { source: oneOf(Object.keys(TURN_SOURCES)) },
196
+ commands: { commands: isRecordArray, skills: isRecordArray },
197
+ session_status: { status: isRecord },
198
+ sessions: { requestId: isNonEmptyString, listing: isRecord },
199
+ sessions_error: {
200
+ requestId: isNonEmptyString,
201
+ code: oneOf(['not_available', 'list_failed']),
202
+ message: isString,
203
+ },
204
+ session_switched: { event: isRecord },
205
+ session_change_failed: {
206
+ code: oneOf(SESSION_CHANGE_REFUSAL_CODES),
207
+ message: isString,
208
+ requestId: isOptional(isString),
209
+ },
136
210
  usage_report: { report: isRecord },
137
211
  personal_usage_report: { requestId: isNonEmptyString, report: isRecord },
138
212
  personal_usage_report_error: {
@@ -152,8 +226,12 @@ export const SERVER_MESSAGE_SHAPES: Readonly<Record<TServerMessage['type'], TVar
152
226
  message: isString,
153
227
  },
154
228
  executing: { executing: isBoolean },
155
- pending: { pending: (v) => v === null || isString(v) },
229
+ // An older host sends no count; a client then counts the one prompt it can see.
230
+ pending: { pending: (v) => v === null || isString(v), pendingCount: isOptional(isCount) },
156
231
  execution_workspace_event: { snapshot: isRecord },
232
+ execution_detail: { requestId: isNonEmptyString, page: isRecord },
233
+ execution_detail_error: { requestId: isNonEmptyString, message: isString },
234
+ waiting_loop_stop: { requestId: isNonEmptyString, outcome: isWaitingLoopStopOutcome },
157
235
  background_task_event: { event: isRecord },
158
236
  background_job_group_event: { event: isRecord },
159
237
  plan_event: { event: isRecord },
@@ -176,7 +254,7 @@ export const SERVER_MESSAGE_SHAPES: Readonly<Record<TServerMessage['type'], TVar
176
254
  success: isBoolean,
177
255
  message: isOptional(isString),
178
256
  },
179
- protocol_error: { message: isString },
257
+ protocol_error: { message: isString, requestId: isOptional(isString) },
180
258
  resume_gap: {},
181
259
  };
182
260
 
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The shared admission gate of an OAuth resource server reached over HTTP: RFC 6750 bearer challenges,
3
+ * RFC 9728 protected-resource metadata, the public-URL name checks, and a failure-only throttle per
4
+ * peer address. Every remote HTTP carrier that admits by access token composes these pieces, so the
5
+ * rules are one set of code rather than one per carrier.
6
+ *
7
+ * The host is reached through its PUBLIC URL, usually behind a reverse proxy, so every name the gate
8
+ * checks comes from that URL rather than from the listener: the Host and Origin a request must carry
9
+ * (the proxy must preserve Host) and the paths it serves. The listener's own address is never a name a
10
+ * client uses.
11
+ *
12
+ * Refusals answer with an empty body and, for a token problem, only the standard challenge: an error
13
+ * code from RFC 6750 and where the metadata lives. Only failures are counted, so a peer holding a valid
14
+ * token is never throttled, however many failures share its address. What a carrier reports about a
15
+ * refused peer is a coarse address class, never the address.
16
+ *
17
+ * This module binds no listener; a carrier owns its socket and calls these per request.
18
+ */
19
+
20
+ import { BlockList, isIP } from 'node:net';
21
+
22
+ import type { IncomingMessage, ServerResponse } from 'node:http';
23
+
24
+ const WELL_KNOWN_PREFIX = '/.well-known/oauth-protected-resource';
25
+ /** Window over which one address's failures are counted. */
26
+ const FAILURE_WINDOW_MS = 60_000;
27
+ /** Failures one address may have in a window before its further failures answer 429. */
28
+ const MAX_FAILURES_PER_WINDOW = 20;
29
+ /** Addresses tracked at once; the oldest is forgotten first, so a spray cannot grow memory. */
30
+ const MAX_TRACKED_ADDRESSES = 4096;
31
+ /** RFC 6749 scope-token characters: printable ASCII except space, `"` and `\`. */
32
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
33
+
34
+ /** A coarse class of a peer's address; the address itself is never reported. */
35
+ export type TRemoteAddressClass = 'loopback' | 'private' | 'public' | 'unknown';
36
+
37
+ /** Where a refused request came from, and whether its address is over the failure budget. */
38
+ export interface IBearerFailure {
39
+ readonly remote: TRemoteAddressClass;
40
+ readonly throttled: boolean;
41
+ readonly retryAfterSeconds: number;
42
+ }
43
+
44
+ /** The public-facing identity of one resource server and its per-address failure budget. */
45
+ export interface IBearerResourceServer {
46
+ /** The parsed public URL; its path is the resource's base path. */
47
+ readonly url: URL;
48
+ /**
49
+ * Host and Origin must name the public URL. On a mismatch the 403 is written and false returned;
50
+ * nothing is counted, since no credential was judged.
51
+ */
52
+ checkNames(req: IncomingMessage, res: ServerResponse): boolean;
53
+ /** Count one failure against the request's peer. */
54
+ fail(req: IncomingMessage): IBearerFailure;
55
+ /** The request's peer class without counting anything. */
56
+ remote(req: IncomingMessage): TRemoteAddressClass;
57
+ }
58
+
59
+ /** The challenges and metadata of one protected resource (one audience). */
60
+ export interface IProtectedResource {
61
+ /** The RFC 9728 path clients fetch the metadata from. */
62
+ readonly wellKnownPath: string;
63
+ readonly metadata: string;
64
+ readonly challenges: {
65
+ readonly missing: string;
66
+ readonly invalid: string;
67
+ readonly scope: string;
68
+ };
69
+ }
70
+
71
+ const LOOPBACK_RANGES = new BlockList();
72
+ LOOPBACK_RANGES.addSubnet('127.0.0.0', 8, 'ipv4');
73
+ LOOPBACK_RANGES.addAddress('::1', 'ipv6');
74
+ const PRIVATE_RANGES = new BlockList();
75
+ PRIVATE_RANGES.addSubnet('10.0.0.0', 8, 'ipv4');
76
+ PRIVATE_RANGES.addSubnet('172.16.0.0', 12, 'ipv4');
77
+ PRIVATE_RANGES.addSubnet('192.168.0.0', 16, 'ipv4');
78
+ PRIVATE_RANGES.addSubnet('169.254.0.0', 16, 'ipv4');
79
+ PRIVATE_RANGES.addSubnet('100.64.0.0', 10, 'ipv4');
80
+ PRIVATE_RANGES.addSubnet('fc00::', 7, 'ipv6');
81
+ PRIVATE_RANGES.addSubnet('fe80::', 10, 'ipv6');
82
+
83
+ /** A literal address in one spelling: IPv4-mapped IPv6 folded to IPv4, IPv6 lowercased. */
84
+ function normalizeAddress(value: string | undefined): string | undefined {
85
+ if (value === undefined) return undefined;
86
+ const text = value.trim().toLowerCase();
87
+ const mapped = text.startsWith('::ffff:') ? text.slice('::ffff:'.length) : undefined;
88
+ if (mapped !== undefined && isIP(mapped) === 4) return mapped;
89
+ return isIP(text) === 0 ? undefined : text;
90
+ }
91
+
92
+ function classifyAddress(address: string | undefined): TRemoteAddressClass {
93
+ if (address === undefined) return 'unknown';
94
+ const family = isIP(address) === 4 ? 'ipv4' : 'ipv6';
95
+ if (LOOPBACK_RANGES.check(address, family)) return 'loopback';
96
+ if (PRIVATE_RANGES.check(address, family)) return 'private';
97
+ return 'public';
98
+ }
99
+
100
+ /** Parse a resource server's public URL: plain `https`, no credentials, query or fragment. */
101
+ export function parsePublicHttpsUrl(publicUrl: string, label: string): URL {
102
+ let url: URL;
103
+ try {
104
+ url = new URL(publicUrl);
105
+ } catch {
106
+ throw new Error(`${label} public URL must be an absolute https URL`);
107
+ }
108
+ if (url.protocol !== 'https:') throw new Error(`${label} public URL must use https`);
109
+ if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
110
+ throw new Error(`${label} public URL must not carry credentials, a query or a fragment`);
111
+ }
112
+ return url;
113
+ }
114
+
115
+ interface IFailureWindow {
116
+ count: number;
117
+ startedAt: number;
118
+ }
119
+
120
+ /** Counts failures per address in fixed windows. Only failures are ever recorded here. */
121
+ function createFailureCounter(now: () => number) {
122
+ const windows = new Map<string, IFailureWindow>();
123
+ return (address: string): { throttled: boolean; retryAfterSeconds: number } => {
124
+ const at = now();
125
+ let entry = windows.get(address);
126
+ if (entry === undefined || at - entry.startedAt >= FAILURE_WINDOW_MS) {
127
+ windows.delete(address);
128
+ if (windows.size >= MAX_TRACKED_ADDRESSES) {
129
+ for (const [key, value] of windows) {
130
+ if (at - value.startedAt >= FAILURE_WINDOW_MS) windows.delete(key);
131
+ }
132
+ const oldest = windows.keys().next();
133
+ if (windows.size >= MAX_TRACKED_ADDRESSES && oldest.done !== true) {
134
+ windows.delete(oldest.value);
135
+ }
136
+ }
137
+ entry = { count: 0, startedAt: at };
138
+ windows.set(address, entry);
139
+ }
140
+ entry.count += 1;
141
+ const remainingMs = FAILURE_WINDOW_MS - (at - entry.startedAt);
142
+ return {
143
+ throttled: entry.count > MAX_FAILURES_PER_WINDOW,
144
+ retryAfterSeconds: Math.max(1, Math.ceil(remainingMs / 1000)),
145
+ };
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Build the public identity of a resource server. Throws when the public URL is not plain `https`,
151
+ * or a trusted proxy is not a literal address. `label` names the carrier in those messages.
152
+ */
153
+ export function createBearerResourceServer(options: {
154
+ readonly publicUrl: string;
155
+ /** Proxy addresses whose `X-Forwarded-For` is believed. Absent: the header is ignored. */
156
+ readonly trustedProxies?: readonly string[];
157
+ readonly label: string;
158
+ readonly now?: () => number;
159
+ }): IBearerResourceServer {
160
+ const url = parsePublicHttpsUrl(options.publicUrl, options.label);
161
+ const trustedProxies = new Set<string>();
162
+ for (const proxy of options.trustedProxies ?? []) {
163
+ const address = normalizeAddress(proxy);
164
+ if (address === undefined) {
165
+ throw new Error(`${options.label} trusted proxy must be a literal IP address`);
166
+ }
167
+ trustedProxies.add(address);
168
+ }
169
+ const expectedHosts = new Set([url.host]);
170
+ if (url.port === '') expectedHosts.add(`${url.hostname}:443`);
171
+ const failures = createFailureCounter(options.now ?? (() => performance.now()));
172
+
173
+ function remoteAddress(req: IncomingMessage): string | undefined {
174
+ const peer = normalizeAddress(req.socket.remoteAddress);
175
+ if (peer === undefined || !trustedProxies.has(peer)) return peer;
176
+ const header = req.headers['x-forwarded-for'];
177
+ const hops = (Array.isArray(header) ? header.join(',') : (header ?? '')).split(',');
178
+ // Walk from the proxy inward: the nearest hop not itself a trusted proxy is the client, as the
179
+ // trusted proxy saw it. Hops further left were written by the client and are not believed.
180
+ for (let index = hops.length - 1; index >= 0; index -= 1) {
181
+ const hop = normalizeAddress(hops[index]);
182
+ if (hop === undefined) return peer;
183
+ if (!trustedProxies.has(hop)) return hop;
184
+ }
185
+ return peer;
186
+ }
187
+
188
+ return {
189
+ url,
190
+ checkNames(req, res) {
191
+ const host = req.headers.host?.toLowerCase();
192
+ const origin = req.headers.origin;
193
+ if (
194
+ host === undefined ||
195
+ !expectedHosts.has(host) ||
196
+ (origin !== undefined && origin !== url.origin)
197
+ ) {
198
+ res.writeHead(403).end();
199
+ return false;
200
+ }
201
+ return true;
202
+ },
203
+ fail(req) {
204
+ const address = remoteAddress(req);
205
+ return { remote: classifyAddress(address), ...failures(address ?? 'unknown') };
206
+ },
207
+ remote(req) {
208
+ return classifyAddress(remoteAddress(req));
209
+ },
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Describe one protected resource: where its RFC 9728 metadata lives and the challenges that point
215
+ * there. Throws for a non-`https` issuer, or no scope or a scope a challenge cannot quote.
216
+ */
217
+ export function describeProtectedResource(options: {
218
+ /** The resource identifier (`aud`), an `https` URL. */
219
+ readonly resource: string;
220
+ readonly issuer: string;
221
+ readonly scopes: readonly string[];
222
+ readonly label: string;
223
+ }): IProtectedResource {
224
+ const url = parsePublicHttpsUrl(options.resource, options.label);
225
+ let issuer: URL;
226
+ try {
227
+ issuer = new URL(options.issuer);
228
+ } catch {
229
+ throw new Error(`${options.label} authorization issuer must be an absolute https URL`);
230
+ }
231
+ if (issuer.protocol !== 'https:') {
232
+ throw new Error(`${options.label} authorization issuer must use https`);
233
+ }
234
+ if (options.scopes.length === 0 || !options.scopes.every((scope) => SCOPE_TOKEN.test(scope))) {
235
+ throw new Error(`${options.label} authorization needs at least one valid scope`);
236
+ }
237
+ // RFC 9728 §3.1: the well-known segment goes between the host and the resource's path, with a
238
+ // lone terminating slash dropped.
239
+ const wellKnownPath = `${WELL_KNOWN_PREFIX}${url.pathname === '/' ? '' : url.pathname}`;
240
+ const metadataUrl = `${url.origin}${wellKnownPath}`;
241
+ const scopeList = options.scopes.join(' ');
242
+ return {
243
+ wellKnownPath,
244
+ metadata: JSON.stringify({
245
+ resource: options.resource,
246
+ authorization_servers: [options.issuer],
247
+ scopes_supported: [...options.scopes],
248
+ bearer_methods_supported: ['header'],
249
+ }),
250
+ challenges: {
251
+ missing: `Bearer resource_metadata="${metadataUrl}"`,
252
+ invalid: `Bearer error="invalid_token", resource_metadata="${metadataUrl}"`,
253
+ scope: `Bearer error="insufficient_scope", scope="${scopeList}", resource_metadata="${metadataUrl}"`,
254
+ },
255
+ };
256
+ }
257
+
258
+ /** Answer a metadata request: GET only, the JSON document, nothing else. */
259
+ export function serveProtectedResourceMetadata(
260
+ req: IncomingMessage,
261
+ res: ServerResponse,
262
+ resource: IProtectedResource,
263
+ ): void {
264
+ if (req.method !== 'GET') {
265
+ res.writeHead(405, { Allow: 'GET' }).end();
266
+ return;
267
+ }
268
+ res.writeHead(200, { 'Content-Type': 'application/json' }).end(resource.metadata);
269
+ }
270
+
271
+ /**
272
+ * Answer a refused bearer token after its failure was counted: 429 once the peer is over budget,
273
+ * 403 `insufficient_scope` for a missing scope, otherwise 401 with the missing-token or
274
+ * `invalid_token` challenge. Always an empty body.
275
+ */
276
+ export function refuseBearerToken(
277
+ res: ServerResponse,
278
+ resource: IProtectedResource,
279
+ refusal: 'missing-token' | 'missing-scope' | 'invalid-token',
280
+ failure: IBearerFailure,
281
+ ): void {
282
+ if (failure.throttled) {
283
+ res.writeHead(429, { 'Retry-After': String(failure.retryAfterSeconds) }).end();
284
+ } else if (refusal === 'missing-scope') {
285
+ res.writeHead(403, { 'WWW-Authenticate': resource.challenges.scope }).end();
286
+ } else {
287
+ const challenge =
288
+ refusal === 'missing-token' ? resource.challenges.missing : resource.challenges.invalid;
289
+ res.writeHead(401, { 'WWW-Authenticate': challenge }).end();
290
+ }
291
+ }