@agent-relay/core-bridge 17.2.1 → 18.1.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/auth.js ADDED
@@ -0,0 +1,666 @@
1
+ /**
2
+ * The client side of service-caller challenge authentication
3
+ * (`spawn_callers.challenge` and `spawn_callers.authenticate`), served by
4
+ * Agent Relay Desktop's spawn caller extension.
5
+ *
6
+ * A service caller proves it holds its `caller.json` secret without sending
7
+ * it: it asks for a challenge, computes
8
+ * `HMAC-SHA256(SHA-256(secret), transcript)` over the version 1 transcript,
9
+ * and sends that authenticator. A successful authenticate binds the bridge
10
+ * connection to the caller for the rest of its life; the `spawn.*` calls on
11
+ * it then name no caller at all.
12
+ *
13
+ * Rules a caller must know:
14
+ * - A connection can be bound once. Open a new connection to bind again.
15
+ * - A challenge is single-use and expires 30 seconds after it was issued.
16
+ * - Three attempts on one connection that end without a binding lock it
17
+ * (`auth_locked`); open a new connection.
18
+ * - Neither the secret nor the derived key ever leaves this process.
19
+ */
20
+ import { createHash, createHmac } from 'node:crypto';
21
+ import { constants as fsConstants } from 'node:fs';
22
+ import { lstat, open, realpath, stat } from 'node:fs/promises';
23
+ import path from 'node:path';
24
+ import { inspect } from 'node:util';
25
+ import { CoreBridgeError, CoreRpcError } from './errors.js';
26
+ import { SERVICE_CALLER_DISCONNECT_METHOD, SERVICE_CALLER_IDENTITY_METHOD, SERVICE_CALLER_INBOX_ACK_METHOD, SERVICE_CALLER_INBOX_CLOSE_METHOD, SERVICE_CALLER_INBOX_FAIL_METHOD, SERVICE_CALLER_INBOX_NEXT_METHOD, SERVICE_CALLER_INBOX_OPEN_METHOD, } from './service-callers.js';
27
+ /** The transcript version byte, which is also the challenge `version`. */
28
+ export const CALLER_TRANSCRIPT_VERSION = 1;
29
+ /** The transcript's domain separation string. */
30
+ export const CALLER_TRANSCRIPT_DOMAIN = 'agent-relay/service-caller/v1';
31
+ /** How long a challenge stays valid after it was issued, in milliseconds. */
32
+ export const CALLER_CHALLENGE_TTL_MS = 30_000;
33
+ /** The `caller.json` `auth` value naming this transcript. */
34
+ export const CALLER_AUTH_SCHEME = 'challenge-hmac-sha256/v1';
35
+ /** The exact challenge method named by a schema-v2 caller handoff. */
36
+ export const CALLER_CHALLENGE_METHOD = 'spawn_callers.challenge';
37
+ /** The exact authenticate method named by a schema-v2 caller handoff. */
38
+ export const CALLER_AUTHENTICATE_METHOD = 'spawn_callers.authenticate';
39
+ /**
40
+ * The `caller.json` schemas the credential-only reader accepts.
41
+ * @deprecated Schema 1 is retained for 18.0 API compatibility. New callers
42
+ * must use {@link CALLER_FILE_SCHEMA} and {@link readCallerDescriptor}.
43
+ */
44
+ export const CALLER_FILE_SCHEMAS = ['agent-relay-service-caller/1', 'agent-relay-service-caller/2'];
45
+ /** The strict schema required by the complete service-caller descriptor. */
46
+ export const CALLER_FILE_SCHEMA = CALLER_FILE_SCHEMAS[1];
47
+ /** The feature methods a service-caller connection requires end to end. */
48
+ export const REQUIRED_SERVICE_CALLER_METHODS = [
49
+ CALLER_CHALLENGE_METHOD,
50
+ CALLER_AUTHENTICATE_METHOD,
51
+ 'spawn.targets',
52
+ 'spawn.invoke',
53
+ 'spawn.status',
54
+ 'spawn.release',
55
+ SERVICE_CALLER_IDENTITY_METHOD,
56
+ SERVICE_CALLER_INBOX_OPEN_METHOD,
57
+ SERVICE_CALLER_INBOX_NEXT_METHOD,
58
+ SERVICE_CALLER_INBOX_ACK_METHOD,
59
+ SERVICE_CALLER_INBOX_FAIL_METHOD,
60
+ SERVICE_CALLER_INBOX_CLOSE_METHOD,
61
+ SERVICE_CALLER_DISCONNECT_METHOD,
62
+ ];
63
+ /** The largest `caller.json` this reader opens, in bytes. */
64
+ export const MAX_CALLER_FILE_BYTES = 64 * 1024;
65
+ const CALLER_ID = /^sc_[0-9a-f]{16}$/;
66
+ const CHALLENGE_ID = /^ch_[0-9a-f]{32}$/;
67
+ const B64URL_32 = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
68
+ const SECRET = /^rsc_[A-Za-z0-9_-]{43}$/;
69
+ const CALLER_NAME = /^[A-Za-z0-9_-]{1,200}$/;
70
+ const HARNESS = /^[A-Za-z0-9_-]{1,64}$/;
71
+ const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
72
+ const NONCE_BYTES = 32;
73
+ const CALLER_KEYS = [
74
+ 'account',
75
+ 'auth',
76
+ 'caller_id',
77
+ 'caller_name',
78
+ 'created_at',
79
+ 'desktop_version',
80
+ 'directory_scope',
81
+ 'expires_at',
82
+ 'harnesses',
83
+ 'inbox',
84
+ 'owns_only',
85
+ 'publisher',
86
+ 'schema',
87
+ 'secret',
88
+ 'socket',
89
+ 'workspace',
90
+ ];
91
+ function invalid(code, message) {
92
+ return new CoreBridgeError(code, message);
93
+ }
94
+ function bytesWithin(field, value, min, max) {
95
+ if (typeof value !== 'string')
96
+ throw invalid('invalid_params', `Caller transcript input is invalid: ${field} must be a string.`);
97
+ const bytes = Buffer.from(value, 'utf8');
98
+ if (bytes.length < min || bytes.length > max) {
99
+ throw invalid('invalid_params', `Caller transcript input is invalid: ${field} must be ${min} to ${max} bytes.`);
100
+ }
101
+ return bytes;
102
+ }
103
+ function matching(field, value, pattern) {
104
+ if (typeof value !== 'string' || !pattern.test(value)) {
105
+ throw invalid('invalid_params', `Caller transcript input is invalid: ${field} is malformed.`);
106
+ }
107
+ return Buffer.from(value, 'ascii');
108
+ }
109
+ function millis(field, value) {
110
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
111
+ throw invalid('invalid_params', `Caller transcript input is invalid: ${field} must be an integer from 0 to 2^53 - 1.`);
112
+ }
113
+ return BigInt(value);
114
+ }
115
+ function field(bytes) {
116
+ const prefix = Buffer.alloc(2);
117
+ prefix.writeUInt16BE(bytes.length);
118
+ return Buffer.concat([prefix, bytes]);
119
+ }
120
+ function u64(value) {
121
+ const out = Buffer.alloc(8);
122
+ out.writeBigUInt64BE(value);
123
+ return out;
124
+ }
125
+ function callerFileBad(rule) {
126
+ return invalid('caller_file_invalid', `caller.json is invalid: ${rule}.`);
127
+ }
128
+ function fileRecord(value, name, keys) {
129
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
130
+ throw callerFileBad(`${name} must be an object`);
131
+ }
132
+ const record = value;
133
+ if (Object.keys(record).sort().join(',') !== [...keys].sort().join(',')) {
134
+ throw callerFileBad(`${name} has fields this reader does not know`);
135
+ }
136
+ return record;
137
+ }
138
+ function fileText(value, name, max) {
139
+ if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value, 'utf8') > max) {
140
+ throw callerFileBad(`${name} must be 1 to ${max} bytes`);
141
+ }
142
+ return value;
143
+ }
144
+ function timestamp(value, name) {
145
+ const text = fileText(value, name, 128);
146
+ if (!RFC3339.test(text) || !Number.isFinite(Date.parse(text))) {
147
+ throw callerFileBad(`${name} must be RFC 3339`);
148
+ }
149
+ return text;
150
+ }
151
+ function fileBoolean(value, name) {
152
+ if (typeof value !== 'boolean')
153
+ throw callerFileBad(`${name} must be a boolean`);
154
+ return value;
155
+ }
156
+ function uniqueStrings(value, name, check) {
157
+ if (!Array.isArray(value) || value.length === 0 || value.length > 256) {
158
+ throw callerFileBad(`${name} must contain 1 to 256 entries`);
159
+ }
160
+ const items = [];
161
+ for (const item of value) {
162
+ if (typeof item !== 'string' || !check(item))
163
+ throw callerFileBad(`${name} has a malformed entry`);
164
+ if (items.includes(item))
165
+ throw callerFileBad(`${name} has a duplicate entry`);
166
+ items.push(item);
167
+ }
168
+ return items;
169
+ }
170
+ function currentAuthRoute(value) {
171
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
172
+ return false;
173
+ const auth = value;
174
+ return (Object.keys(auth).sort().join(',') === 'authenticate,challenge,scheme' &&
175
+ auth.scheme === CALLER_AUTH_SCHEME &&
176
+ auth.challenge === CALLER_CHALLENGE_METHOD &&
177
+ auth.authenticate === CALLER_AUTHENTICATE_METHOD);
178
+ }
179
+ /**
180
+ * Preserves the public 18.0 credential-only contract. Schema 1 had no auth
181
+ * field, and the first schema-2 writer used the scheme string; current
182
+ * Desktop writes the explicit route object. Descriptor parsing below remains
183
+ * strict and accepts only the complete current schema.
184
+ */
185
+ function parseCallerCredential(document) {
186
+ if (typeof document !== 'object' || document === null || Array.isArray(document)) {
187
+ throw callerFileBad('it must be an object');
188
+ }
189
+ const doc = document;
190
+ if (!CALLER_FILE_SCHEMAS.includes(doc.schema)) {
191
+ throw callerFileBad('schema is not one this reader knows');
192
+ }
193
+ if (doc.schema === CALLER_FILE_SCHEMA && doc.auth !== CALLER_AUTH_SCHEME && !currentAuthRoute(doc.auth)) {
194
+ throw callerFileBad('auth is not one this reader knows');
195
+ }
196
+ if (typeof doc.caller_id !== 'string' || !CALLER_ID.test(doc.caller_id)) {
197
+ throw callerFileBad('caller_id must be "sc_" and 16 lowercase hex characters');
198
+ }
199
+ if (typeof doc.secret !== 'string' || !SECRET.test(doc.secret)) {
200
+ throw callerFileBad('secret is malformed');
201
+ }
202
+ const workspace = typeof doc.workspace === 'object' && doc.workspace !== null && !Array.isArray(doc.workspace)
203
+ ? doc.workspace
204
+ : undefined;
205
+ const account = typeof doc.account === 'object' && doc.account !== null && !Array.isArray(doc.account)
206
+ ? doc.account
207
+ : undefined;
208
+ return {
209
+ callerId: doc.caller_id,
210
+ secret: doc.secret,
211
+ siteUrl: fileText(workspace?.site_url, 'workspace.site_url', 2048),
212
+ workspaceId: fileText(workspace?.workspace_id, 'workspace.workspace_id', 256),
213
+ userId: fileText(account?.user_id, 'account.user_id', 256),
214
+ };
215
+ }
216
+ function parseCallerDocument(document) {
217
+ if (typeof document !== 'object' || document === null || Array.isArray(document)) {
218
+ throw callerFileBad('it must be an object');
219
+ }
220
+ const raw = document;
221
+ if (raw.schema === 'agent-relay-service-caller/1') {
222
+ throw callerFileBad('schema 1 is retired; rotate the caller in Agent Relay');
223
+ }
224
+ if (raw.schema !== CALLER_FILE_SCHEMA)
225
+ throw callerFileBad('schema is not one this reader knows');
226
+ const keys = raw.rotated_at === undefined ? CALLER_KEYS : [...CALLER_KEYS, 'rotated_at'];
227
+ const doc = fileRecord(raw, 'it', keys);
228
+ const auth = fileRecord(doc.auth, 'auth', ['authenticate', 'challenge', 'scheme']);
229
+ if (auth.scheme !== CALLER_AUTH_SCHEME ||
230
+ auth.challenge !== CALLER_CHALLENGE_METHOD ||
231
+ auth.authenticate !== CALLER_AUTHENTICATE_METHOD) {
232
+ throw callerFileBad('auth is not one this reader knows');
233
+ }
234
+ if (typeof doc.caller_id !== 'string' || !CALLER_ID.test(doc.caller_id)) {
235
+ throw callerFileBad('caller_id must be "sc_" and 16 lowercase hex characters');
236
+ }
237
+ if (typeof doc.caller_name !== 'string' || !CALLER_NAME.test(doc.caller_name)) {
238
+ throw callerFileBad('caller_name is malformed');
239
+ }
240
+ if (typeof doc.secret !== 'string' || !SECRET.test(doc.secret)) {
241
+ throw callerFileBad('secret is malformed');
242
+ }
243
+ const publisher = fileRecord(doc.publisher, 'publisher', ['id', 'name']);
244
+ const workspace = fileRecord(doc.workspace, 'workspace', [
245
+ 'base_url',
246
+ 'relaycast_workspace_id',
247
+ 'site_url',
248
+ 'workspace_id',
249
+ ]);
250
+ const account = fileRecord(doc.account, 'account', ['user_id']);
251
+ const inbox = fileRecord(doc.inbox, 'inbox', [
252
+ 'ack',
253
+ 'close',
254
+ 'disconnect',
255
+ 'fail',
256
+ 'next',
257
+ 'open',
258
+ 'transport',
259
+ ]);
260
+ if (inbox.transport !== 'core-bridge' ||
261
+ inbox.open !== SERVICE_CALLER_INBOX_OPEN_METHOD ||
262
+ inbox.next !== SERVICE_CALLER_INBOX_NEXT_METHOD ||
263
+ inbox.ack !== SERVICE_CALLER_INBOX_ACK_METHOD ||
264
+ inbox.fail !== SERVICE_CALLER_INBOX_FAIL_METHOD ||
265
+ inbox.close !== SERVICE_CALLER_INBOX_CLOSE_METHOD ||
266
+ inbox.disconnect !== SERVICE_CALLER_DISCONNECT_METHOD) {
267
+ throw callerFileBad('inbox is not one this reader knows');
268
+ }
269
+ const socket = fileText(doc.socket, 'socket', 4096);
270
+ if (socket.includes('\0') ||
271
+ (!path.isAbsolute(socket) && !path.win32.isAbsolute(socket) && !/^\\\\\.\\pipe\\/i.test(socket))) {
272
+ throw callerFileBad('socket must be an absolute path or named pipe');
273
+ }
274
+ const callerName = doc.caller_name;
275
+ const publisherName = fileText(publisher.name, 'publisher.name', 256);
276
+ if (publisherName !== callerName) {
277
+ throw callerFileBad('publisher.name must match caller_name');
278
+ }
279
+ const createdAt = timestamp(doc.created_at, 'created_at');
280
+ const rotatedAt = doc.rotated_at === undefined ? undefined : timestamp(doc.rotated_at, 'rotated_at');
281
+ const expiresAt = timestamp(doc.expires_at, 'expires_at');
282
+ const createdMs = Date.parse(createdAt);
283
+ const rotatedMs = rotatedAt === undefined ? undefined : Date.parse(rotatedAt);
284
+ const expiresMs = Date.parse(expiresAt);
285
+ if (expiresMs <= createdMs ||
286
+ (rotatedMs !== undefined && (rotatedMs < createdMs || rotatedMs >= expiresMs))) {
287
+ throw callerFileBad('timestamps are out of order');
288
+ }
289
+ return {
290
+ auth: {
291
+ scheme: CALLER_AUTH_SCHEME,
292
+ challenge: CALLER_CHALLENGE_METHOD,
293
+ authenticate: CALLER_AUTHENTICATE_METHOD,
294
+ },
295
+ callerId: doc.caller_id,
296
+ callerName,
297
+ publisher: {
298
+ id: fileText(publisher.id, 'publisher.id', 256),
299
+ name: publisherName,
300
+ },
301
+ workspace: {
302
+ site_url: fileText(workspace.site_url, 'workspace.site_url', 2048),
303
+ base_url: fileText(workspace.base_url, 'workspace.base_url', 2048),
304
+ workspace_id: fileText(workspace.workspace_id, 'workspace.workspace_id', 256),
305
+ relaycast_workspace_id: fileText(workspace.relaycast_workspace_id, 'workspace.relaycast_workspace_id', 256),
306
+ },
307
+ account: { user_id: fileText(account.user_id, 'account.user_id', 256) },
308
+ secret: doc.secret,
309
+ createdAt,
310
+ ...(rotatedAt === undefined ? {} : { rotatedAt }),
311
+ expiresAt,
312
+ harnesses: uniqueStrings(doc.harnesses, 'harnesses', (item) => HARNESS.test(item)),
313
+ directoryScope: uniqueStrings(doc.directory_scope, 'directory_scope', (item) => item.length <= 4096 && !item.includes('\0') && (path.isAbsolute(item) || path.win32.isAbsolute(item))),
314
+ ownsOnly: fileBoolean(doc.owns_only, 'owns_only'),
315
+ socket,
316
+ inbox: {
317
+ transport: 'core-bridge',
318
+ open: SERVICE_CALLER_INBOX_OPEN_METHOD,
319
+ next: SERVICE_CALLER_INBOX_NEXT_METHOD,
320
+ ack: SERVICE_CALLER_INBOX_ACK_METHOD,
321
+ fail: SERVICE_CALLER_INBOX_FAIL_METHOD,
322
+ close: SERVICE_CALLER_INBOX_CLOSE_METHOD,
323
+ disconnect: SERVICE_CALLER_DISCONNECT_METHOD,
324
+ },
325
+ desktopVersion: fileText(doc.desktop_version, 'desktop_version', 128),
326
+ };
327
+ }
328
+ /**
329
+ * Builds the exact version 1 transcript bytes: the version byte, then each
330
+ * field with a big-endian u16 length prefix.
331
+ * @param input - The challenge fields and the caller's own `caller.json` scope.
332
+ * @returns The transcript bytes the authenticator covers.
333
+ * @throws CoreBridgeError `invalid_params` when a value is outside its bound.
334
+ */
335
+ export function callerTranscript(input) {
336
+ if (!(input.nonce instanceof Uint8Array) || input.nonce.length !== NONCE_BYTES) {
337
+ throw invalid('invalid_params', 'Caller transcript input is invalid: nonce must be 32 bytes.');
338
+ }
339
+ return Buffer.concat([
340
+ Buffer.from([CALLER_TRANSCRIPT_VERSION]),
341
+ field(Buffer.from(CALLER_TRANSCRIPT_DOMAIN, 'ascii')),
342
+ field(matching('challenge_id', input.challengeId, CHALLENGE_ID)),
343
+ field(input.nonce),
344
+ field(matching('caller_id', input.callerId, CALLER_ID)),
345
+ field(bytesWithin('site_url', input.siteUrl, 1, 2048)),
346
+ field(bytesWithin('workspace_id', input.workspaceId, 1, 256)),
347
+ field(bytesWithin('user_id', input.userId, 1, 256)),
348
+ field(u64(millis('issued_at_ms', input.issuedAtMs))),
349
+ field(u64(millis('expires_at_ms', input.expiresAtMs))),
350
+ ]);
351
+ }
352
+ const KEY = Symbol('key');
353
+ /**
354
+ * A caller's credential as read from `caller.json`. It holds the derived key,
355
+ * never the secret, and prints as `[redacted]`: it cannot be logged or
356
+ * serialised by accident.
357
+ */
358
+ export class CallerCredential {
359
+ /** The caller's registry id, which is sent as the challenge param. */
360
+ callerId;
361
+ /** `workspace.site_url`, used only in the transcript. */
362
+ siteUrl;
363
+ /** `workspace.workspace_id`, used only in the transcript. */
364
+ workspaceId;
365
+ /** `account.user_id`, used only in the transcript. */
366
+ userId;
367
+ #key;
368
+ constructor(key, callerId, siteUrl, workspaceId, userId) {
369
+ this.#key = key;
370
+ this.callerId = callerId;
371
+ this.siteUrl = siteUrl;
372
+ this.workspaceId = workspaceId;
373
+ this.userId = userId;
374
+ Object.freeze(this);
375
+ }
376
+ /**
377
+ * Checks a parsed `caller.json` document and derives its key.
378
+ * @param document - The parsed `caller.json` contents.
379
+ * @returns The credential, holding `SHA-256(secret)` and not the secret.
380
+ * @throws CoreBridgeError `caller_file_invalid` when the document does not
381
+ * have the `caller.json` shape. The message never contains the secret.
382
+ */
383
+ static fromDocument(document) {
384
+ const parsed = parseCallerCredential(document);
385
+ const key = createHash('sha256').update(parsed.secret, 'utf8').digest();
386
+ return new CallerCredential(key, parsed.callerId, parsed.siteUrl, parsed.workspaceId, parsed.userId);
387
+ }
388
+ /**
389
+ * Computes the authenticator for one challenge.
390
+ * @param challenge - The challenge exactly as `spawn_callers.challenge` returned it.
391
+ * @returns The HMAC-SHA256 authenticator in base64url without padding.
392
+ * @throws CoreBridgeError `invalid_reply` when the challenge is malformed.
393
+ */
394
+ authenticatorFor(challenge) {
395
+ checkChallenge(challenge);
396
+ const transcript = callerTranscript({
397
+ challengeId: challenge.challenge_id,
398
+ nonce: Buffer.from(challenge.nonce, 'base64url'),
399
+ callerId: this.callerId,
400
+ siteUrl: this.siteUrl,
401
+ workspaceId: this.workspaceId,
402
+ userId: this.userId,
403
+ issuedAtMs: challenge.issued_at_ms,
404
+ expiresAtMs: challenge.expires_at_ms,
405
+ });
406
+ return createHmac('sha256', this.#key).update(transcript).digest('base64url');
407
+ }
408
+ /**
409
+ * Keeps the key out of JSON.
410
+ * @returns A placeholder.
411
+ */
412
+ toJSON() {
413
+ return '[redacted]';
414
+ }
415
+ /**
416
+ * Keeps the key out of string conversion.
417
+ * @returns A placeholder.
418
+ */
419
+ toString() {
420
+ return '[redacted]';
421
+ }
422
+ /**
423
+ * Keeps the key out of `console.log` and `util.inspect`.
424
+ * @returns A placeholder.
425
+ */
426
+ [inspect.custom]() {
427
+ return 'CallerCredential [redacted]';
428
+ }
429
+ }
430
+ function descriptorFromDocument(document) {
431
+ const parsed = parseCallerDocument(document);
432
+ return Object.freeze({
433
+ schema: CALLER_FILE_SCHEMA,
434
+ schemaVersion: 2,
435
+ auth: Object.freeze({ ...parsed.auth }),
436
+ callerId: parsed.callerId,
437
+ callerName: parsed.callerName,
438
+ publisher: Object.freeze({ ...parsed.publisher }),
439
+ workspace: Object.freeze({ ...parsed.workspace }),
440
+ account: Object.freeze({ ...parsed.account }),
441
+ credential: CallerCredential.fromDocument(document),
442
+ createdAt: parsed.createdAt,
443
+ ...(parsed.rotatedAt === undefined ? {} : { rotatedAt: parsed.rotatedAt }),
444
+ expiresAt: parsed.expiresAt,
445
+ harnesses: Object.freeze([...parsed.harnesses]),
446
+ directoryScope: Object.freeze([...parsed.directoryScope]),
447
+ ownsOnly: parsed.ownsOnly,
448
+ socket: parsed.socket,
449
+ inbox: Object.freeze({ ...parsed.inbox }),
450
+ desktopVersion: parsed.desktopVersion,
451
+ });
452
+ }
453
+ function badReply(rule) {
454
+ return new CoreRpcError(`The caller challenge reply is invalid: ${rule}.`, {
455
+ rpcCode: -32603,
456
+ kind: 'internal',
457
+ retryable: false,
458
+ });
459
+ }
460
+ function checkChallenge(challenge) {
461
+ if (typeof challenge !== 'object' || challenge === null)
462
+ throw badReply('it must be an object');
463
+ if (challenge.version !== CALLER_TRANSCRIPT_VERSION)
464
+ throw badReply('version must be 1');
465
+ if (typeof challenge.challenge_id !== 'string' || !CHALLENGE_ID.test(challenge.challenge_id)) {
466
+ throw badReply('challenge_id is malformed');
467
+ }
468
+ if (typeof challenge.nonce !== 'string' || !B64URL_32.test(challenge.nonce))
469
+ throw badReply('nonce is malformed');
470
+ const { issued_at_ms: issued, expires_at_ms: expires } = challenge;
471
+ if (!Number.isSafeInteger(issued) || issued < 0)
472
+ throw badReply('issued_at_ms is out of range');
473
+ if (expires !== issued + CALLER_CHALLENGE_TTL_MS || !Number.isSafeInteger(expires)) {
474
+ throw badReply('expires_at_ms must be issued_at_ms + 30000');
475
+ }
476
+ }
477
+ function checkBound(bound, callerId) {
478
+ const fail = (rule) => new CoreRpcError(`The caller authenticate reply is invalid: ${rule}.`, {
479
+ rpcCode: -32603,
480
+ kind: 'internal',
481
+ retryable: false,
482
+ });
483
+ if (typeof bound !== 'object' || bound === null)
484
+ throw fail('it must be an object');
485
+ if (bound.caller_id !== callerId)
486
+ throw fail('caller_id is not the caller that authenticated');
487
+ if (typeof bound.caller_name !== 'string' || !CALLER_NAME.test(bound.caller_name))
488
+ throw fail('caller_name is malformed');
489
+ if (!Number.isSafeInteger(bound.authority_generation) || bound.authority_generation < 1) {
490
+ throw fail('authority_generation is out of range');
491
+ }
492
+ return {
493
+ caller_id: bound.caller_id,
494
+ caller_name: bound.caller_name,
495
+ authority_generation: bound.authority_generation,
496
+ };
497
+ }
498
+ function requireMethods(client, methods) {
499
+ for (const method of methods) {
500
+ if (client.hello.methods.includes(method))
501
+ continue;
502
+ throw new CoreRpcError(`This Agent Relay core does not offer ${method}; update Agent Relay Desktop.`, {
503
+ rpcCode: -32601,
504
+ kind: 'method_not_found',
505
+ retryable: false,
506
+ });
507
+ }
508
+ }
509
+ /**
510
+ * Refuses a core that cannot provide the complete service-caller lifecycle.
511
+ * @param client - A greeted bridge connection whose advertised methods are checked.
512
+ * @returns Nothing when every required service-caller method is available.
513
+ */
514
+ export function requireServiceCallerMethods(client) {
515
+ requireMethods(client, REQUIRED_SERVICE_CALLER_METHODS);
516
+ }
517
+ /**
518
+ * Binds a bridge connection to a service caller: one challenge and one
519
+ * authenticate. After it returns, `spawn.invoke`, `spawn.status` and
520
+ * `spawn.release` on this connection act as the caller and name no caller.
521
+ * Failures are the core's typed errors (`CoreRpcError`), for example
522
+ * `auth_failed`, `auth_locked`, `already_bound` or `challenge_outstanding`.
523
+ * @param client - A greeted connection that has not been bound yet.
524
+ * @param credential - The credential read from `caller.json`.
525
+ * @param options - Optional timeout and cancellation controls for each of
526
+ * the two calls; the default is the client's call timeout (15 seconds).
527
+ * @returns The bound caller.
528
+ */
529
+ export async function authenticate(client, credential, options) {
530
+ requireMethods(client, [CALLER_CHALLENGE_METHOD, CALLER_AUTHENTICATE_METHOD]);
531
+ const challengeParams = { caller_id: credential.callerId };
532
+ const challenge = await client.call('spawn_callers.challenge', challengeParams, options);
533
+ const params = {
534
+ challenge_id: challenge?.challenge_id,
535
+ authenticator: credential.authenticatorFor(challenge),
536
+ };
537
+ return checkBound(await client.call('spawn_callers.authenticate', params, options), credential.callerId);
538
+ }
539
+ function unsafe(file, rule) {
540
+ return new CoreBridgeError('caller_file_unsafe', `Refusing to read ${file}: ${rule}.`);
541
+ }
542
+ /**
543
+ * Reads and parses `caller.json` once through a checked file descriptor.
544
+ *
545
+ * On macOS and Linux the file must be a regular file (not a symlink), owned
546
+ * by this user, with no group or other permission bits (0600 or stricter),
547
+ * in a directory that is not group- or world-writable unless it is sticky;
548
+ * it is opened with `O_NOFOLLOW`.
549
+ *
550
+ * On Windows the path must be absolute, the file must not be a symlink or
551
+ * reparse point (its real path must be itself), and it must be a regular
552
+ * file. Node has no API to read a Windows access list, so the reader cannot
553
+ * verify the file's DACL or owner; it relies on the per-user profile's
554
+ * access list that Desktop writes the file under.
555
+ * @param file - The absolute path of `caller.json`.
556
+ * @returns The parsed document; callers immediately validate it and discard
557
+ * its secret after deriving the credential key.
558
+ * @throws CoreBridgeError `caller_file_unsafe` when the file fails a check
559
+ * above, `caller_file_invalid` when its contents are malformed.
560
+ */
561
+ async function readCallerDocument(file) {
562
+ if (typeof file !== 'string' || !path.isAbsolute(file) || file.includes('\0')) {
563
+ throw unsafe(String(file), 'the path must be absolute');
564
+ }
565
+ // Open once and check the open descriptor, not the path, so nothing can
566
+ // swap the file between a check and the read. On macOS and Linux
567
+ // O_NOFOLLOW refuses a symlink in place of the file (ELOOP) and O_NONBLOCK
568
+ // keeps a FIFO from blocking the open; Windows has neither flag.
569
+ const posix = process.platform !== 'win32';
570
+ let flags = fsConstants.O_RDONLY;
571
+ if (posix) {
572
+ if (typeof fsConstants.O_NOFOLLOW === 'number')
573
+ flags |= fsConstants.O_NOFOLLOW;
574
+ if (typeof fsConstants.O_NONBLOCK === 'number')
575
+ flags |= fsConstants.O_NONBLOCK;
576
+ }
577
+ let handle;
578
+ try {
579
+ handle = await open(file, flags);
580
+ }
581
+ catch (error) {
582
+ const code = error?.code;
583
+ if (code === 'ELOOP')
584
+ throw unsafe(file, 'it is a symbolic link');
585
+ if (code === 'EISDIR')
586
+ throw unsafe(file, 'it is not a regular file');
587
+ // ENOENT and ENOTDIR pass through unchanged, as a missing file always has.
588
+ throw error;
589
+ }
590
+ let text;
591
+ try {
592
+ const opened = await handle.stat();
593
+ if (!opened.isFile())
594
+ throw unsafe(file, 'it is not a regular file');
595
+ if (opened.size > MAX_CALLER_FILE_BYTES)
596
+ throw unsafe(file, 'it is larger than 64 KiB');
597
+ if (!posix) {
598
+ // Windows gap: Node exposes no access-list API, so the DACL and owner
599
+ // are not verified here. The file lives in the user's profile, whose
600
+ // access list admits only that user, SYSTEM and administrators. What
601
+ // can be checked is: an absolute path that is not a reparse point.
602
+ // The path is examined after the open and must name the file that was
603
+ // opened; it is never used to read. Paths compare case-insensitively,
604
+ // as NTFS resolves them.
605
+ const link = await lstat(file);
606
+ if (link.isSymbolicLink())
607
+ throw unsafe(file, 'it is a symbolic link');
608
+ if (link.ino !== opened.ino || link.dev !== opened.dev) {
609
+ throw unsafe(file, 'it changed while being opened');
610
+ }
611
+ if ((await realpath(file)).toLowerCase() !== path.resolve(file).toLowerCase()) {
612
+ throw unsafe(file, 'it resolves through a link');
613
+ }
614
+ }
615
+ else {
616
+ if (typeof process.getuid === 'function' && opened.uid !== process.getuid()) {
617
+ throw unsafe(file, 'it is not owned by this user');
618
+ }
619
+ if ((opened.mode & 0o077) !== 0)
620
+ throw unsafe(file, 'it is readable or writable by other users (it must be 0600)');
621
+ const parent = await stat(path.dirname(file));
622
+ if ((parent.mode & 0o022) !== 0 && (parent.mode & 0o1000) === 0) {
623
+ throw unsafe(file, 'its directory is writable by other users');
624
+ }
625
+ }
626
+ const buffer = Buffer.alloc(MAX_CALLER_FILE_BYTES + 1);
627
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
628
+ if (bytesRead > MAX_CALLER_FILE_BYTES)
629
+ throw unsafe(file, 'it is larger than 64 KiB');
630
+ text = buffer.subarray(0, bytesRead).toString('utf8');
631
+ buffer.fill(0);
632
+ }
633
+ finally {
634
+ await handle.close();
635
+ }
636
+ let document;
637
+ try {
638
+ document = JSON.parse(text);
639
+ }
640
+ catch {
641
+ // The parser's message can quote the file, secret included.
642
+ throw new CoreBridgeError('caller_file_invalid', 'caller.json is invalid: it is not JSON.');
643
+ }
644
+ return document;
645
+ }
646
+ /**
647
+ * Securely reads and validates the complete schema-v2 caller handoff.
648
+ * The returned descriptor contains no secret; {@link CallerFileDescriptor.credential}
649
+ * retains only its derived key and always prints as `[redacted]`.
650
+ * @param file - The absolute path of the schema-v2 `caller.json` handoff.
651
+ * @returns The validated descriptor and its redacting challenge credential.
652
+ */
653
+ export async function readCallerDescriptor(file) {
654
+ return descriptorFromDocument(await readCallerDocument(file));
655
+ }
656
+ /**
657
+ * Securely reads `caller.json` and returns only its challenge credential.
658
+ * Prefer {@link readCallerDescriptor} when a caller also needs the socket,
659
+ * publisher, workspace, scope or inbox route from the same checked read.
660
+ * @param file - The absolute path of `caller.json`.
661
+ * @returns The credential, holding the derived key and never the secret.
662
+ */
663
+ export async function readCallerCredential(file) {
664
+ return CallerCredential.fromDocument(await readCallerDocument(file));
665
+ }
666
+ //# sourceMappingURL=auth.js.map