dsh-taskbridge 1.7.0 → 1.8.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -21
  3. package/README.md +150 -289
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -627
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +13 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +6 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +12 -5
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -53
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
@@ -1,789 +1,789 @@
1
- // Delegation authorization: server-issued connection identities and
2
- // single-use task grants.
3
- //
4
- // Threat model, stated plainly so no reader mistakes this for more than it is:
5
- // a process running as the same operating-system user, with unrestricted
6
- // filesystem access, can read this process's memory and is not an adversarial
7
- // security boundary. What these grants do guarantee is that no code path in
8
- // this plugin dispatches model work without an authorization that a human
9
- // operator created through the authenticated DSH surface — so an external tool,
10
- // an MCP client, a prompt-injected agent, or a plain HTTP caller cannot cause
11
- // delegation on its own, including after a restart.
12
- //
13
- // Deliberate design consequences:
14
- // * Grants live only in memory. Nothing here is persisted, so a restart cannot
15
- // resurrect an authorization. Delegation is off after every restart.
16
- // * Grant state is never derived from caller-supplied data. A caller may name a
17
- // grant id; only this module decides whether that grant still authorizes one
18
- // task, and consuming it is unconditional on success.
19
- // * A connection identity is issued by the server together with a random
20
- // secret. Only the secret's hash is retained, so a memory dump of this
21
- // registry does not yield usable tokens.
22
-
23
- import { randomBytes, randomUUID } from 'node:crypto';
24
- import path from 'node:path';
25
-
26
- import { LIMITS } from '../config/defaults.js';
27
- import { safeEqual, sha256 } from './fence.js';
28
-
29
- /** Bounds that keep an accidental loop from growing unbounded state. */
30
- export const AUTH_LIMITS = Object.freeze({
31
- connections: 16,
32
- grantsPerConnection: 32,
33
- grantsTotal: 256,
34
- tokenBytes: 32,
35
- listeners: 64,
36
- });
37
-
38
- /**
39
- * A connection is only live while it keeps presenting its token. The lease is
40
- * idle-based, not absolute: a heartbeat (an authenticated request) pushes it
41
- * forward, and a connection that goes silent is revoked together with its
42
- * grants so a background worker cannot keep executing on a forgotten grant.
43
- */
44
- export const DEFAULT_CONNECTION_LEASE_MS = 120_000;
45
-
46
- /** How long a settled grant or connection is retained before removal. */
47
- export const AUTH_RETENTION_MS = 10 * 60 * 1000;
48
-
49
- /** How often the host should call {@link AuthorizationRegistry#sweep}. */
50
- export const AUTH_SWEEP_INTERVAL_MS = 30_000;
51
-
52
- /** Reasons carried by invalidation events. */
53
- export const AUTH_EVENT_REASONS = Object.freeze({
54
- revoked: 'revoked',
55
- expired: 'expired',
56
- leaseExpired: 'lease-expired',
57
- revokedAll: 'revoked-all',
58
- });
59
-
60
- /** Refusal codes for authorization failures. */
61
- export const AUTH_CODES = Object.freeze({
62
- connectionUnknown: 'CONNECTION_UNKNOWN',
63
- connectionRevoked: 'CONNECTION_REVOKED',
64
- connectionExpired: 'CONNECTION_EXPIRED',
65
- connectionLimit: 'CONNECTION_LIMIT',
66
- grantUnknown: 'GRANT_UNKNOWN',
67
- grantExpired: 'GRANT_EXPIRED',
68
- grantRevoked: 'GRANT_REVOKED',
69
- grantConsumed: 'GRANT_CONSUMED',
70
- grantNotConsumed: 'GRANT_NOT_CONSUMED',
71
- grantMismatch: 'GRANT_MISMATCH',
72
- grantLimit: 'GRANT_LIMIT',
73
- });
74
-
75
- /** An authorization refusal with a stable machine code. */
76
- export class AuthError extends Error {
77
- /**
78
- * @param {string} code - stable machine code.
79
- * @param {string} message - human-readable explanation.
80
- * @param {object} [details] - bounded, non-secret details.
81
- */
82
- constructor(code, message, details = {}) {
83
- super(message);
84
- this.name = 'AuthError';
85
- this.code = code;
86
- this.details = details;
87
- }
88
- }
89
-
90
- /** Task grants are single-use; session grants allow repeated execution until TTL. */
91
- export const GRANT_KINDS = Object.freeze(['task', 'session']);
92
-
93
- /**
94
- * In-memory registry of connection identities and task grants.
95
- *
96
- * All state transitions are synchronous. That is what makes consumption atomic:
97
- * the expiry, revocation and consumed checks run in one uninterrupted step, so
98
- * two concurrent callers can never both observe an unconsumed grant.
99
- */
100
- export class AuthorizationRegistry {
101
- /**
102
- * @param {object} [options] - `now` clock and `leaseMs` overrides for tests.
103
- */
104
- constructor(options = {}) {
105
- this.now = options.now ?? (() => Date.now());
106
- const leaseMs = options.leaseMs ?? DEFAULT_CONNECTION_LEASE_MS;
107
- if (typeof leaseMs !== 'number' || !Number.isFinite(leaseMs) || leaseMs <= 0) {
108
- throw new AuthError('AUTH_LEASE_INVALID', 'leaseMs must be a positive number of milliseconds', {});
109
- }
110
- this.leaseMs = leaseMs;
111
- /** @type {Map<string, object>} */
112
- this.connections = new Map();
113
- /** @type {Map<string, object>} */
114
- this.grants = new Map();
115
- /** @type {Set<Function>} */
116
- this.listeners = new Set();
117
- }
118
-
119
- /**
120
- * Subscribe to invalidation events.
121
- *
122
- * An event is emitted whenever an authorization stops being usable for a
123
- * reason other than "this request failed": revocation, expiry, an operator
124
- * revoke-all, or a connection losing its idle lease. The job engine subscribes
125
- * here and cancels matching tasks, which is what makes revoke an actual
126
- * cancellation rather than a promise.
127
- *
128
- * Listener failures are swallowed: one bad subscriber must not break
129
- * authorization bookkeeping for everyone else.
130
- * @param {(event: {kind: 'grant'|'connection'|'all', grantId?: string, connectionId?: string, reason: string}) => void} listener - callback.
131
- * @returns {() => void} unsubscribe function; idempotent.
132
- */
133
- subscribe(listener) {
134
- if (typeof listener !== 'function') {
135
- throw new AuthError('AUTH_LISTENER_INVALID', 'an invalidation listener must be a function', {});
136
- }
137
- if (this.listeners.size >= AUTH_LIMITS.listeners) {
138
- throw new AuthError(AUTH_CODES.grantLimit, `at most ${AUTH_LIMITS.listeners} listeners may be registered`, {
139
- limit: AUTH_LIMITS.listeners,
140
- });
141
- }
142
- this.listeners.add(listener);
143
- let active = true;
144
- return () => {
145
- if (!active) return;
146
- active = false;
147
- this.listeners.delete(listener);
148
- };
149
- }
150
-
151
- /**
152
- * Emit one invalidation event to every subscriber.
153
- * @param {object} event - `kind`, optional `grantId`/`connectionId`, `reason`.
154
- * @returns {void}
155
- */
156
- emit(event) {
157
- const payload = Object.freeze({
158
- kind: event.kind,
159
- ...(event.grantId === undefined ? {} : { grantId: event.grantId }),
160
- ...(event.connectionId === undefined ? {} : { connectionId: event.connectionId }),
161
- reason: event.reason,
162
- });
163
- for (const listener of [...this.listeners]) {
164
- try {
165
- listener(payload);
166
- } catch {
167
- // A subscriber's failure is its own problem; the registry stays usable.
168
- }
169
- }
170
- }
171
-
172
- /**
173
- * Drop every subscriber. Used on dispose so a stopped plugin cannot be woken.
174
- * @returns {number} number of listeners removed.
175
- */
176
- unsubscribeAll() {
177
- const removed = this.listeners.size;
178
- this.listeners.clear();
179
- return removed;
180
- }
181
-
182
- /**
183
- * Whether any delegation authorization exists. This is the plugin's single
184
- * "is delegation on" oracle; it is false in a fresh process by construction.
185
- * @returns {boolean} true only while at least one usable grant is present.
186
- */
187
- isDelegationAuthorized() {
188
- this.sweep();
189
- for (const grant of this.grants.values()) {
190
- if (!this.isUsable(grant)) continue;
191
- const connection = this.connections.get(grant.connectionId);
192
- if (connection === undefined || !this.isConnectionLive(connection)) continue;
193
- return true;
194
- }
195
- return false;
196
- }
197
-
198
- /**
199
- * Issue a new connection identity. The caller receives the secret exactly
200
- * once; the registry retains only its hash.
201
- * @param {{ label?: string, peer?: object }} input - operator-supplied label and audit facts.
202
- * @returns {{ connectionId: string, token: string, label: string, createdAt: number }} issued identity.
203
- */
204
- issueConnection(input = {}) {
205
- this.sweep();
206
- if (this.connections.size >= AUTH_LIMITS.connections) {
207
- throw new AuthError(AUTH_CODES.connectionLimit, `at most ${AUTH_LIMITS.connections} connections may be registered`, {
208
- limit: AUTH_LIMITS.connections,
209
- });
210
- }
211
- const connectionId = `conn-${randomUUID()}`;
212
- const token = randomBytes(AUTH_LIMITS.tokenBytes).toString('base64url');
213
- const label = typeof input.label === 'string' && input.label.trim() !== ''
214
- ? input.label.trim().slice(0, 80)
215
- : 'unnamed connection';
216
- const createdAt = this.now();
217
- this.connections.set(connectionId, {
218
- connectionId,
219
- label,
220
- tokenHash: sha256(token),
221
- createdAt,
222
- lastSeenAt: createdAt,
223
- revokedAt: null,
224
- peer: {
225
- // Peer facts are recorded for audit only; they never authorize anything.
226
- address: typeof input.peer?.address === 'string' ? input.peer.address : null,
227
- },
228
- });
229
- return { connectionId, token, label, createdAt };
230
- }
231
-
232
- /**
233
- * Resolve a presented connection token to its identity and renew its lease.
234
- *
235
- * Authentication is the heartbeat: an authenticated request is the only thing
236
- * that pushes `lastSeenAt` forward. A token that is recognised but whose lease
237
- * has already lapsed is refused *without* renewal, so a silent period cannot be
238
- * papered over by the next request — the connection stays revoked.
239
- * @param {unknown} token - presented secret.
240
- * @returns {object | null} the live connection record, or null.
241
- */
242
- authenticate(token) {
243
- if (typeof token !== 'string' || token.length === 0) return null;
244
- const hash = sha256(token);
245
- for (const connection of this.connections.values()) {
246
- // Hash comparison first so the comparison itself is length-stable.
247
- if (!safeEqual(hash, connection.tokenHash)) continue;
248
- if (!this.isConnectionLive(connection)) {
249
- // Expired or revoked: refuse and make sure the state is settled, but do
250
- // not refresh the lease. Renewing here would let an attacker who holds a
251
- // stale token revive a dead connection indefinitely.
252
- this.expireConnection(connection, AUTH_EVENT_REASONS.leaseExpired);
253
- return null;
254
- }
255
- connection.lastSeenAt = this.now();
256
- return connection;
257
- }
258
- return null;
259
- }
260
-
261
- /**
262
- * Whether a connection record may still act.
263
- * @param {object} connection - internal record.
264
- * @returns {boolean} true when not revoked and inside its idle lease.
265
- */
266
- isConnectionLive(connection) {
267
- if (connection.revokedAt !== null) return false;
268
- return this.now() - connection.lastSeenAt <= this.leaseMs;
269
- }
270
-
271
- /**
272
- * Revoke a connection because its idle lease lapsed, and emit the event.
273
- *
274
- * A connection that is already revoked has already been announced; it is not
275
- * re-announced with a different reason, because that would cancel the same
276
- * tasks twice under a misleading cause.
277
- * @param {object} connection - internal record.
278
- * @param {string} reason - event reason.
279
- * @returns {number} number of grants revoked alongside it.
280
- */
281
- expireConnection(connection, reason) {
282
- if (connection.revokedAt !== null) return 0;
283
- return this.revokeConnectionInternal(connection, reason);
284
- }
285
-
286
- /**
287
- * Revoke one connection and every grant it holds.
288
- *
289
- * The grants are revoked in the same synchronous step, so no execution can
290
- * observe "connection revoked but grant still live". One `connection` event is
291
- * emitted so the engine can cancel that connection's running tasks.
292
- * @param {string} connectionId - identity to revoke.
293
- * @returns {number} number of grants revoked with it.
294
- */
295
- revokeConnection(connectionId) {
296
- const connection = this.connections.get(connectionId);
297
- if (connection === undefined) {
298
- throw new AuthError(AUTH_CODES.connectionUnknown, 'unknown connection', { connectionId });
299
- }
300
- if (connection.revokedAt !== null) return 0;
301
- return this.revokeConnectionInternal(connection, AUTH_EVENT_REASONS.revoked);
302
- }
303
-
304
- /**
305
- * Shared revocation path: stamp the connection, its grants, and announce it once.
306
- * @param {object} connection - internal record.
307
- * @param {string} reason - event reason.
308
- * @returns {number} number of grants revoked with it.
309
- */
310
- revokeConnectionInternal(connection, reason) {
311
- const at = this.now();
312
- connection.revokedAt = at;
313
- let revoked = 0;
314
- for (const grant of this.grants.values()) {
315
- if (grant.connectionId !== connection.connectionId || grant.revokedAt !== null) continue;
316
- grant.revokedAt = at;
317
- revoked += 1;
318
- }
319
- this.emit({ kind: 'connection', connectionId: connection.connectionId, reason });
320
- return revoked;
321
- }
322
-
323
- /**
324
- * Remove a connection and its grants entirely.
325
- * @param {string} connectionId - identity to forget.
326
- * @returns {boolean} true when something was removed.
327
- */
328
- forgetConnection(connectionId) {
329
- for (const [id, grant] of this.grants) {
330
- if (grant.connectionId === connectionId) this.grants.delete(id);
331
- }
332
- return this.connections.delete(connectionId);
333
- }
334
-
335
- /**
336
- * Issue an authorization for one task or one session.
337
- *
338
- * A grant always names the connection that will exercise it and the exact
339
- * workspace it covers. Both are required, so an authorization for one project
340
- * can never be spent on another.
341
- * @param {string} connectionId - issuing (and later exercising) connection.
342
- * @param {object} input - `kind`, `workspacePath`, `ttlSeconds`, `overrides`.
343
- * @returns {object} the grant record safe to return to its owner.
344
- */
345
- issueGrant(connectionId, input) {
346
- this.sweep();
347
- const connection = this.requireLiveConnection(connectionId);
348
- const kind = input?.kind;
349
- if (!GRANT_KINDS.includes(kind)) {
350
- throw new AuthError('GRANT_KIND_INVALID', `grant kind must be one of ${GRANT_KINDS.join(', ')}`, { kind });
351
- }
352
- const workspacePath = normalizeWorkspace(input?.workspacePath);
353
- const ttlSeconds = input?.ttlSeconds;
354
- if (typeof ttlSeconds !== 'number' || !Number.isInteger(ttlSeconds) || ttlSeconds <= 0) {
355
- throw new AuthError('GRANT_TTL_INVALID', 'grant ttlSeconds must be a positive integer', {});
356
- }
357
- // The TTL is bounded per kind by the same limits settings validation uses,
358
- // so a caller cannot mint an effectively permanent authorization by asking
359
- // for a longer lifetime than the operator's own settings allow.
360
- const bounds = kind === 'session'
361
- ? { min: LIMITS.sessionGrantTtlSecondsMin, max: LIMITS.sessionGrantTtlSecondsMax }
362
- : { min: LIMITS.taskGrantTtlSecondsMin, max: LIMITS.taskGrantTtlSecondsMax };
363
- if (ttlSeconds < bounds.min || ttlSeconds > bounds.max) {
364
- throw new AuthError(
365
- 'GRANT_TTL_OUT_OF_RANGE',
366
- `a ${kind} grant TTL must be between ${bounds.min} and ${bounds.max} seconds`,
367
- { kind, min: bounds.min, max: bounds.max, ttlSeconds },
368
- );
369
- }
370
- if (this.grants.size >= AUTH_LIMITS.grantsTotal) {
371
- throw new AuthError(AUTH_CODES.grantLimit, `at most ${AUTH_LIMITS.grantsTotal} grants may be outstanding`, {
372
- limit: AUTH_LIMITS.grantsTotal,
373
- });
374
- }
375
- const own = [...this.grants.values()].filter((grant) => grant.connectionId === connection.connectionId);
376
- if (own.length >= AUTH_LIMITS.grantsPerConnection) {
377
- throw new AuthError(AUTH_CODES.grantLimit, `at most ${AUTH_LIMITS.grantsPerConnection} grants per connection`, {
378
- limit: AUTH_LIMITS.grantsPerConnection,
379
- });
380
- }
381
- const createdAt = this.now();
382
- const grant = {
383
- grantId: `grant-${randomUUID()}`,
384
- connectionId: connection.connectionId,
385
- kind,
386
- workspacePath,
387
- overrides: input?.overrides === undefined ? null : structuredClone(input.overrides),
388
- createdAt,
389
- expiresAt: createdAt + ttlSeconds * 1000,
390
- consumedAt: null,
391
- consumedByTaskId: null,
392
- revokedAt: null,
393
- };
394
- this.grants.set(grant.grantId, grant);
395
- return publicGrant(grant);
396
- }
397
-
398
- /**
399
- * Atomically consume a task grant for exactly one task.
400
- *
401
- * Every refusal path leaves the grant untouched and every success path marks
402
- * it consumed before the caller can act on it, so a replayed request can only
403
- * ever fail.
404
- * @param {object} input - `connectionId`, `grantId`, `taskId`, `workspacePath`.
405
- * @returns {object} the consumed grant snapshot.
406
- */
407
- consumeTaskGrant(input) {
408
- const connection = this.requireLiveConnection(input?.connectionId);
409
- const grant = this.grants.get(input?.grantId);
410
- if (grant === undefined || grant.connectionId !== connection.connectionId) {
411
- throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
412
- }
413
- if (grant.kind !== 'task') {
414
- throw new AuthError(AUTH_CODES.grantMismatch, 'this grant does not authorize a single task', { kind: grant.kind });
415
- }
416
- this.assertUsable(grant);
417
- const workspacePath = normalizeWorkspace(input?.workspacePath);
418
- if (workspacePath !== grant.workspacePath) {
419
- throw new AuthError(AUTH_CODES.grantMismatch, 'grant does not cover this workspace', {
420
- workspacePath,
421
- });
422
- }
423
- const taskId = input?.taskId;
424
- if (typeof taskId !== 'string' || taskId === '') {
425
- throw new AuthError('GRANT_TASK_REQUIRED', 'consuming a task grant requires the task id it authorizes', {});
426
- }
427
- grant.consumedAt = this.now();
428
- grant.consumedByTaskId = taskId;
429
- return publicGrant(grant);
430
- }
431
-
432
- /**
433
- * Assert that a specific task is still authorized right now.
434
- *
435
- * This is the check a long-running job repeats as it progresses, and it is
436
- * deliberately stricter than "a grant exists":
437
- *
438
- * * the connection must be live (not revoked, not past its idle lease);
439
- * * the grant must belong to that exact connection and cover that exact
440
- * workspace;
441
- * * the grant must not be revoked or expired;
442
- * * a `task` grant must already be consumed *by this very task*, because a
443
- * consumed task grant stays consumed — it authorizes its own task and no
444
- * other, and an unconsumed one has not authorized anything yet;
445
- * * a `session` grant must be the one named by `grantId`, if one is named.
446
- *
447
- * @param {{ connectionId: unknown, grantId: unknown, taskId: unknown, workspacePath: unknown }} input - the four facts.
448
- * @returns {object} a safe clone of the grant, never the stored record.
449
- */
450
- assertTaskAuthorized(input) {
451
- const connection = this.requireLiveConnection(input?.connectionId);
452
- const taskId = input?.taskId;
453
- if (typeof taskId !== 'string' || taskId === '') {
454
- throw new AuthError('GRANT_TASK_REQUIRED', 'an authorization check requires the task id', {});
455
- }
456
- const grant = this.grants.get(input?.grantId);
457
- if (grant === undefined || grant.connectionId !== connection.connectionId) {
458
- // Another connection's grant is reported as unknown, never as forbidden:
459
- // a distinct code would confirm that the id exists.
460
- throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
461
- }
462
- // Only revocation and expiry disqualify a grant here: a task grant that is
463
- // consumed *by this task* is exactly what authorizes it, so consumption is
464
- // checked below as a binding rather than refused as a state.
465
- this.assertLive(grant);
466
- const workspacePath = normalizeWorkspace(input?.workspacePath);
467
- if (workspacePath !== grant.workspacePath) {
468
- throw new AuthError(AUTH_CODES.grantMismatch, 'grant does not cover this workspace', { workspacePath });
469
- }
470
- if (grant.kind === 'task') {
471
- if (grant.consumedAt === null) {
472
- throw new AuthError(AUTH_CODES.grantNotConsumed, 'this task grant has not been consumed by any task', {});
473
- }
474
- if (grant.consumedByTaskId !== taskId) {
475
- throw new AuthError(AUTH_CODES.grantConsumed, 'grant has already been consumed by another task', {
476
- consumedByTaskId: grant.consumedByTaskId,
477
- consumedAt: grant.consumedAt,
478
- });
479
- }
480
- } else if (grant.kind !== 'session') {
481
- throw new AuthError(AUTH_CODES.grantMismatch, 'this grant kind does not authorize a task', { kind: grant.kind });
482
- }
483
- return publicGrant(grant);
484
- }
485
-
486
- /**
487
- * Check a session grant without consuming it. Used by the execution plane on
488
- * each call, so revoking the grant stops further execution immediately.
489
- *
490
- * When `grantId` is supplied, exactly that grant is checked. A caller that
491
- * names a grant and is then handed a *different* live grant would be told it
492
- * holds an authorization it never referenced, so the lookup is never widened.
493
- * @param {object} input - `connectionId`, `workspacePath`, optional `grantId`.
494
- * @returns {object} the live session grant snapshot.
495
- */
496
- requireSessionGrant(input) {
497
- const connection = this.requireLiveConnection(input?.connectionId);
498
- const workspacePath = normalizeWorkspace(input?.workspacePath);
499
- const named = input?.grantId;
500
- if (named !== undefined) {
501
- const grant = this.grants.get(named);
502
- if (grant === undefined || grant.connectionId !== connection.connectionId) {
503
- throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
504
- }
505
- if (grant.kind !== 'session') {
506
- throw new AuthError(AUTH_CODES.grantMismatch, 'this grant is not a session grant', { kind: grant.kind });
507
- }
508
- if (grant.workspacePath !== workspacePath) {
509
- throw new AuthError(AUTH_CODES.grantMismatch, 'grant does not cover this workspace', { workspacePath });
510
- }
511
- if (!this.isUsable(grant)) this.assertUsable(grant);
512
- return publicGrant(grant);
513
- }
514
- let found = null;
515
- for (const grant of this.grants.values()) {
516
- if (grant.connectionId !== connection.connectionId) continue;
517
- if (grant.kind !== 'session') continue;
518
- if (grant.workspacePath !== workspacePath) continue;
519
- if (!this.isUsable(grant)) continue;
520
- found = grant;
521
- break;
522
- }
523
- if (found === null) {
524
- throw new AuthError(AUTH_CODES.grantUnknown, 'no live session grant covers this workspace', { workspacePath });
525
- }
526
- return publicGrant(found);
527
- }
528
-
529
- /**
530
- * Revoke one grant and announce it.
531
- * @param {{ connectionId?: string, grantId: unknown, allowOperator?: boolean }} input - revocation request.
532
- * @returns {object} the revoked grant snapshot.
533
- */
534
- revokeGrant(input) {
535
- const grant = this.grants.get(input?.grantId);
536
- if (grant === undefined) {
537
- throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant', {});
538
- }
539
- if (input?.allowOperator !== true && grant.connectionId !== input?.connectionId) {
540
- throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
541
- }
542
- if (grant.revokedAt === null) {
543
- grant.revokedAt = this.now();
544
- this.emit({
545
- kind: 'grant',
546
- grantId: grant.grantId,
547
- connectionId: grant.connectionId,
548
- reason: AUTH_EVENT_REASONS.revoked,
549
- });
550
- }
551
- return publicGrant(grant);
552
- }
553
-
554
- /**
555
- * Revoke every outstanding authorization. This is the operator's "stop
556
- * everything now" action and the plugin's dispose path.
557
- *
558
- * One `all` event is emitted instead of one event per grant: a subscriber
559
- * should stop everything once, not N times.
560
- * @returns {number} number of grants revoked.
561
- */
562
- revokeAll() {
563
- const at = this.now();
564
- let count = 0;
565
- for (const grant of this.grants.values()) {
566
- if (grant.revokedAt !== null) continue;
567
- grant.revokedAt = at;
568
- count += 1;
569
- }
570
- for (const connection of this.connections.values()) {
571
- if (connection.revokedAt === null) connection.revokedAt = at;
572
- }
573
- this.emit({ kind: 'all', reason: AUTH_EVENT_REASONS.revokedAll });
574
- return count;
575
- }
576
-
577
- /**
578
- * List grants visible to one connection. Consumption and expiry are reported
579
- * as facts; no token or hash is included.
580
- * @param {string} connectionId - queried connection.
581
- * @returns {object[]} grant snapshots owned by that connection.
582
- */
583
- listGrants(connectionId) {
584
- this.sweep();
585
- const out = [];
586
- for (const grant of this.grants.values()) {
587
- if (grant.connectionId !== connectionId) continue;
588
- out.push(publicGrant(grant));
589
- }
590
- return out.sort((a, b) => b.createdAt - a.createdAt);
591
- }
592
-
593
- /**
594
- * List connections for the operator surface, with liveness facts only.
595
- *
596
- * `live` and `leaseExpiresAt` are derived, not stored: a connection is live
597
- * while it is not revoked and inside its idle lease. The token and its hash are
598
- * never part of this projection, now or later.
599
- * @returns {object[]} connection snapshots without secrets or hashes.
600
- */
601
- listConnections() {
602
- this.sweep();
603
- const now = this.now();
604
- return [...this.connections.values()]
605
- .map((connection) => ({
606
- connectionId: connection.connectionId,
607
- label: connection.label,
608
- createdAt: connection.createdAt,
609
- lastSeenAt: connection.lastSeenAt,
610
- leaseExpiresAt: connection.lastSeenAt + this.leaseMs,
611
- live: this.isConnectionLive(connection),
612
- revoked: connection.revokedAt !== null,
613
- revokedAt: connection.revokedAt,
614
- peer: { ...connection.peer },
615
- }))
616
- .sort((a, b) => b.createdAt - a.createdAt);
617
- }
618
-
619
- /**
620
- * Settle and bound the registry.
621
- *
622
- * Three things happen here and all of them are idempotent:
623
- *
624
- * 1. A connection past its idle lease is revoked together with its grants,
625
- * and one `connection` event is emitted so the engine can cancel its work.
626
- * 2. A grant that expires before being revoked emits one `grant` event, once
627
- * — including a grant a running task has consumed. Expiring quietly would
628
- * leave a running task with no notification.
629
- * 3. Settled grants and connections older than the retention window are
630
- * deleted, which is what keeps both maps bounded across a long session.
631
- *
632
- * @returns {{ grants: number, connections: number }} number of entries removed.
633
- */
634
- sweep() {
635
- const now = this.now();
636
- let grantsRemoved = 0;
637
- let connectionsRemoved = 0;
638
-
639
- for (const connection of this.connections.values()) {
640
- if (connection.revokedAt !== null) continue;
641
- if (now - connection.lastSeenAt <= this.leaseMs) continue;
642
- this.expireConnection(connection, AUTH_EVENT_REASONS.leaseExpired);
643
- }
644
-
645
- for (const [id, grant] of this.grants) {
646
- if (grant.expiryAnnounced !== true && grant.expiresAt <= now) {
647
- grant.expiryAnnounced = true;
648
- // A revoked grant has already been announced as revoked and must not be
649
- // re-announced. A *consumed* grant has not: a running task holding it
650
- // needs to learn that its authorization has run out, so consumption is
651
- // deliberately not part of this condition.
652
- if (grant.revokedAt === null) {
653
- this.emit({
654
- kind: 'grant',
655
- grantId: grant.grantId,
656
- connectionId: grant.connectionId,
657
- reason: AUTH_EVENT_REASONS.expired,
658
- });
659
- }
660
- }
661
- const settledAt = Math.max(grant.expiresAt, grant.consumedAt ?? 0, grant.revokedAt ?? 0);
662
- if (settledAt === 0) continue;
663
- if (now - settledAt <= AUTH_RETENTION_MS) continue;
664
- this.grants.delete(id);
665
- grantsRemoved += 1;
666
- }
667
-
668
- for (const [id, connection] of this.connections) {
669
- if (connection.revokedAt === null) continue;
670
- if (now - connection.revokedAt <= AUTH_RETENTION_MS) continue;
671
- this.connections.delete(id);
672
- connectionsRemoved += 1;
673
- }
674
-
675
- return { grants: grantsRemoved, connections: connectionsRemoved };
676
- }
677
-
678
- /**
679
- * Resolve a connection that must still be able to act.
680
- *
681
- * An expired lease is reported as expired and the connection is settled (with
682
- * its invalidation event) rather than being silently refreshed: the caller did
683
- * not present a token on this path, so there is no heartbeat to justify
684
- * renewal.
685
- * @param {unknown} connectionId - connection identity.
686
- * @returns {object} the live connection record.
687
- */
688
- requireLiveConnection(connectionId) {
689
- const connection = this.connections.get(connectionId);
690
- if (connection === undefined) {
691
- throw new AuthError(AUTH_CODES.connectionUnknown, 'unknown connection', {});
692
- }
693
- if (connection.revokedAt !== null) {
694
- throw new AuthError(AUTH_CODES.connectionRevoked, 'connection has been revoked', {});
695
- }
696
- if (!this.isConnectionLive(connection)) {
697
- this.expireConnection(connection, AUTH_EVENT_REASONS.leaseExpired);
698
- throw new AuthError(AUTH_CODES.connectionExpired, 'connection lease has expired', {});
699
- }
700
- return connection;
701
- }
702
-
703
- isUsable(grant) {
704
- return grant.consumedAt === null && grant.revokedAt === null && grant.expiresAt > this.now();
705
- }
706
-
707
- /**
708
- * Refuse a grant that is revoked or expired. Consumption is not checked here
709
- * because whether consumption is disqualifying depends on the question: a
710
- * task grant must be consumed to authorize its own task.
711
- * @param {object} grant - internal record.
712
- * @returns {void}
713
- */
714
- assertLive(grant) {
715
- if (grant.revokedAt !== null) {
716
- throw new AuthError(AUTH_CODES.grantRevoked, 'grant has been revoked', {});
717
- }
718
- if (grant.expiresAt <= this.now()) {
719
- throw new AuthError(AUTH_CODES.grantExpired, 'grant has expired', { expiresAt: grant.expiresAt });
720
- }
721
- }
722
-
723
- assertUsable(grant) {
724
- this.assertLive(grant);
725
- if (grant.consumedAt !== null) {
726
- throw new AuthError(AUTH_CODES.grantConsumed, 'grant has already been consumed', {
727
- consumedByTaskId: grant.consumedByTaskId,
728
- consumedAt: grant.consumedAt,
729
- });
730
- }
731
- }
732
- }
733
-
734
- /**
735
- * Canonical workspace key for grant comparison.
736
- *
737
- * Two spellings of the same directory must produce the same key, or a grant
738
- * issued for `C:\work\project` would refuse a request for `c:/work/project/`.
739
- * The rules are explicit so they can be reasoned about:
740
- *
741
- * * the value must be a non-empty string without a NUL byte;
742
- * * it must be absolute (a drive-letter path, a UNC path, or a rooted path);
743
- * * it is normalized and resolved as a path (`..` and `.` segments collapse),
744
- * which is why `C:\work\..\other` and `C:\other` are the same key;
745
- * * a filesystem root keeps its separator: `C:\` and `/` stay `C:\` and `/`,
746
- * because `C:` is a drive-relative path, not the root;
747
- * * on Windows, both separators are folded to `\` and the whole key is
748
- * lowercased, since that filesystem is case-insensitive.
749
- *
750
- * @param {unknown} value - candidate workspace path.
751
- * @returns {string} canonical workspace key.
752
- */
753
- export function normalizeWorkspace(value) {
754
- if (typeof value !== 'string' || value.trim() === '') {
755
- throw new AuthError('GRANT_WORKSPACE_REQUIRED', 'a workspace path is required', {});
756
- }
757
- if (value.includes('\0')) {
758
- throw new AuthError('GRANT_WORKSPACE_INVALID', 'a workspace path must not contain a NUL byte', {});
759
- }
760
- const trimmed = value.trim();
761
- if (!path.isAbsolute(trimmed)) {
762
- throw new AuthError('GRANT_WORKSPACE_NOT_ABSOLUTE', 'workspace path must be absolute', {});
763
- }
764
- const resolved = path.resolve(trimmed);
765
- if (process.platform !== 'win32') return resolved;
766
- const folded = resolved.replace(/\//g, '\\').toLowerCase();
767
- // `path.resolve` already produced a root-preserving form; keep it that way so
768
- // `c:\` never degrades to `c:`.
769
- return folded;
770
- }
771
-
772
- /**
773
- * Public projection of a grant: identifiers and lifecycle facts only.
774
- * @param {object} grant - internal record.
775
- * @returns {object} fresh snapshot.
776
- */
777
- function publicGrant(grant) {
778
- return {
779
- grantId: grant.grantId,
780
- kind: grant.kind,
781
- workspacePath: grant.workspacePath,
782
- createdAt: grant.createdAt,
783
- expiresAt: grant.expiresAt,
784
- consumedAt: grant.consumedAt,
785
- consumedByTaskId: grant.consumedByTaskId,
786
- revokedAt: grant.revokedAt,
787
- overrides: grant.overrides === null ? null : structuredClone(grant.overrides),
788
- };
789
- }
1
+ // Delegation authorization: server-issued connection identities and
2
+ // single-use task grants.
3
+ //
4
+ // Threat model, stated plainly so no reader mistakes this for more than it is:
5
+ // a process running as the same operating-system user, with unrestricted
6
+ // filesystem access, can read this process's memory and is not an adversarial
7
+ // security boundary. What these grants do guarantee is that no code path in
8
+ // this plugin dispatches model work without an authorization that a human
9
+ // operator created through the authenticated DSH surface — so an external tool,
10
+ // an MCP client, a prompt-injected agent, or a plain HTTP caller cannot cause
11
+ // delegation on its own, including after a restart.
12
+ //
13
+ // Deliberate design consequences:
14
+ // * Grants live only in memory. Nothing here is persisted, so a restart cannot
15
+ // resurrect an authorization. Delegation is off after every restart.
16
+ // * Grant state is never derived from caller-supplied data. A caller may name a
17
+ // grant id; only this module decides whether that grant still authorizes one
18
+ // task, and consuming it is unconditional on success.
19
+ // * A connection identity is issued by the server together with a random
20
+ // secret. Only the secret's hash is retained, so a memory dump of this
21
+ // registry does not yield usable tokens.
22
+
23
+ import { randomBytes, randomUUID } from 'node:crypto';
24
+ import path from 'node:path';
25
+
26
+ import { LIMITS } from '../config/defaults.js';
27
+ import { safeEqual, sha256 } from './fence.js';
28
+
29
+ /** Bounds that keep an accidental loop from growing unbounded state. */
30
+ export const AUTH_LIMITS = Object.freeze({
31
+ connections: 16,
32
+ grantsPerConnection: 32,
33
+ grantsTotal: 256,
34
+ tokenBytes: 32,
35
+ listeners: 64,
36
+ });
37
+
38
+ /**
39
+ * A connection is only live while it keeps presenting its token. The lease is
40
+ * idle-based, not absolute: a heartbeat (an authenticated request) pushes it
41
+ * forward, and a connection that goes silent is revoked together with its
42
+ * grants so a background worker cannot keep executing on a forgotten grant.
43
+ */
44
+ export const DEFAULT_CONNECTION_LEASE_MS = 120_000;
45
+
46
+ /** How long a settled grant or connection is retained before removal. */
47
+ export const AUTH_RETENTION_MS = 10 * 60 * 1000;
48
+
49
+ /** How often the host should call {@link AuthorizationRegistry#sweep}. */
50
+ export const AUTH_SWEEP_INTERVAL_MS = 30_000;
51
+
52
+ /** Reasons carried by invalidation events. */
53
+ export const AUTH_EVENT_REASONS = Object.freeze({
54
+ revoked: 'revoked',
55
+ expired: 'expired',
56
+ leaseExpired: 'lease-expired',
57
+ revokedAll: 'revoked-all',
58
+ });
59
+
60
+ /** Refusal codes for authorization failures. */
61
+ export const AUTH_CODES = Object.freeze({
62
+ connectionUnknown: 'CONNECTION_UNKNOWN',
63
+ connectionRevoked: 'CONNECTION_REVOKED',
64
+ connectionExpired: 'CONNECTION_EXPIRED',
65
+ connectionLimit: 'CONNECTION_LIMIT',
66
+ grantUnknown: 'GRANT_UNKNOWN',
67
+ grantExpired: 'GRANT_EXPIRED',
68
+ grantRevoked: 'GRANT_REVOKED',
69
+ grantConsumed: 'GRANT_CONSUMED',
70
+ grantNotConsumed: 'GRANT_NOT_CONSUMED',
71
+ grantMismatch: 'GRANT_MISMATCH',
72
+ grantLimit: 'GRANT_LIMIT',
73
+ });
74
+
75
+ /** An authorization refusal with a stable machine code. */
76
+ export class AuthError extends Error {
77
+ /**
78
+ * @param {string} code - stable machine code.
79
+ * @param {string} message - human-readable explanation.
80
+ * @param {object} [details] - bounded, non-secret details.
81
+ */
82
+ constructor(code, message, details = {}) {
83
+ super(message);
84
+ this.name = 'AuthError';
85
+ this.code = code;
86
+ this.details = details;
87
+ }
88
+ }
89
+
90
+ /** Task grants are single-use; session grants allow repeated execution until TTL. */
91
+ export const GRANT_KINDS = Object.freeze(['task', 'session']);
92
+
93
+ /**
94
+ * In-memory registry of connection identities and task grants.
95
+ *
96
+ * All state transitions are synchronous. That is what makes consumption atomic:
97
+ * the expiry, revocation and consumed checks run in one uninterrupted step, so
98
+ * two concurrent callers can never both observe an unconsumed grant.
99
+ */
100
+ export class AuthorizationRegistry {
101
+ /**
102
+ * @param {object} [options] - `now` clock and `leaseMs` overrides for tests.
103
+ */
104
+ constructor(options = {}) {
105
+ this.now = options.now ?? (() => Date.now());
106
+ const leaseMs = options.leaseMs ?? DEFAULT_CONNECTION_LEASE_MS;
107
+ if (typeof leaseMs !== 'number' || !Number.isFinite(leaseMs) || leaseMs <= 0) {
108
+ throw new AuthError('AUTH_LEASE_INVALID', 'leaseMs must be a positive number of milliseconds', {});
109
+ }
110
+ this.leaseMs = leaseMs;
111
+ /** @type {Map<string, object>} */
112
+ this.connections = new Map();
113
+ /** @type {Map<string, object>} */
114
+ this.grants = new Map();
115
+ /** @type {Set<Function>} */
116
+ this.listeners = new Set();
117
+ }
118
+
119
+ /**
120
+ * Subscribe to invalidation events.
121
+ *
122
+ * An event is emitted whenever an authorization stops being usable for a
123
+ * reason other than "this request failed": revocation, expiry, an operator
124
+ * revoke-all, or a connection losing its idle lease. The job engine subscribes
125
+ * here and cancels matching tasks, which is what makes revoke an actual
126
+ * cancellation rather than a promise.
127
+ *
128
+ * Listener failures are swallowed: one bad subscriber must not break
129
+ * authorization bookkeeping for everyone else.
130
+ * @param {(event: {kind: 'grant'|'connection'|'all', grantId?: string, connectionId?: string, reason: string}) => void} listener - callback.
131
+ * @returns {() => void} unsubscribe function; idempotent.
132
+ */
133
+ subscribe(listener) {
134
+ if (typeof listener !== 'function') {
135
+ throw new AuthError('AUTH_LISTENER_INVALID', 'an invalidation listener must be a function', {});
136
+ }
137
+ if (this.listeners.size >= AUTH_LIMITS.listeners) {
138
+ throw new AuthError(AUTH_CODES.grantLimit, `at most ${AUTH_LIMITS.listeners} listeners may be registered`, {
139
+ limit: AUTH_LIMITS.listeners,
140
+ });
141
+ }
142
+ this.listeners.add(listener);
143
+ let active = true;
144
+ return () => {
145
+ if (!active) return;
146
+ active = false;
147
+ this.listeners.delete(listener);
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Emit one invalidation event to every subscriber.
153
+ * @param {object} event - `kind`, optional `grantId`/`connectionId`, `reason`.
154
+ * @returns {void}
155
+ */
156
+ emit(event) {
157
+ const payload = Object.freeze({
158
+ kind: event.kind,
159
+ ...(event.grantId === undefined ? {} : { grantId: event.grantId }),
160
+ ...(event.connectionId === undefined ? {} : { connectionId: event.connectionId }),
161
+ reason: event.reason,
162
+ });
163
+ for (const listener of [...this.listeners]) {
164
+ try {
165
+ listener(payload);
166
+ } catch {
167
+ // A subscriber's failure is its own problem; the registry stays usable.
168
+ }
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Drop every subscriber. Used on dispose so a stopped plugin cannot be woken.
174
+ * @returns {number} number of listeners removed.
175
+ */
176
+ unsubscribeAll() {
177
+ const removed = this.listeners.size;
178
+ this.listeners.clear();
179
+ return removed;
180
+ }
181
+
182
+ /**
183
+ * Whether any delegation authorization exists. This is the plugin's single
184
+ * "is delegation on" oracle; it is false in a fresh process by construction.
185
+ * @returns {boolean} true only while at least one usable grant is present.
186
+ */
187
+ isDelegationAuthorized() {
188
+ this.sweep();
189
+ for (const grant of this.grants.values()) {
190
+ if (!this.isUsable(grant)) continue;
191
+ const connection = this.connections.get(grant.connectionId);
192
+ if (connection === undefined || !this.isConnectionLive(connection)) continue;
193
+ return true;
194
+ }
195
+ return false;
196
+ }
197
+
198
+ /**
199
+ * Issue a new connection identity. The caller receives the secret exactly
200
+ * once; the registry retains only its hash.
201
+ * @param {{ label?: string, peer?: object }} input - operator-supplied label and audit facts.
202
+ * @returns {{ connectionId: string, token: string, label: string, createdAt: number }} issued identity.
203
+ */
204
+ issueConnection(input = {}) {
205
+ this.sweep();
206
+ if (this.connections.size >= AUTH_LIMITS.connections) {
207
+ throw new AuthError(AUTH_CODES.connectionLimit, `at most ${AUTH_LIMITS.connections} connections may be registered`, {
208
+ limit: AUTH_LIMITS.connections,
209
+ });
210
+ }
211
+ const connectionId = `conn-${randomUUID()}`;
212
+ const token = randomBytes(AUTH_LIMITS.tokenBytes).toString('base64url');
213
+ const label = typeof input.label === 'string' && input.label.trim() !== ''
214
+ ? input.label.trim().slice(0, 80)
215
+ : 'unnamed connection';
216
+ const createdAt = this.now();
217
+ this.connections.set(connectionId, {
218
+ connectionId,
219
+ label,
220
+ tokenHash: sha256(token),
221
+ createdAt,
222
+ lastSeenAt: createdAt,
223
+ revokedAt: null,
224
+ peer: {
225
+ // Peer facts are recorded for audit only; they never authorize anything.
226
+ address: typeof input.peer?.address === 'string' ? input.peer.address : null,
227
+ },
228
+ });
229
+ return { connectionId, token, label, createdAt };
230
+ }
231
+
232
+ /**
233
+ * Resolve a presented connection token to its identity and renew its lease.
234
+ *
235
+ * Authentication is the heartbeat: an authenticated request is the only thing
236
+ * that pushes `lastSeenAt` forward. A token that is recognised but whose lease
237
+ * has already lapsed is refused *without* renewal, so a silent period cannot be
238
+ * papered over by the next request — the connection stays revoked.
239
+ * @param {unknown} token - presented secret.
240
+ * @returns {object | null} the live connection record, or null.
241
+ */
242
+ authenticate(token) {
243
+ if (typeof token !== 'string' || token.length === 0) return null;
244
+ const hash = sha256(token);
245
+ for (const connection of this.connections.values()) {
246
+ // Hash comparison first so the comparison itself is length-stable.
247
+ if (!safeEqual(hash, connection.tokenHash)) continue;
248
+ if (!this.isConnectionLive(connection)) {
249
+ // Expired or revoked: refuse and make sure the state is settled, but do
250
+ // not refresh the lease. Renewing here would let an attacker who holds a
251
+ // stale token revive a dead connection indefinitely.
252
+ this.expireConnection(connection, AUTH_EVENT_REASONS.leaseExpired);
253
+ return null;
254
+ }
255
+ connection.lastSeenAt = this.now();
256
+ return connection;
257
+ }
258
+ return null;
259
+ }
260
+
261
+ /**
262
+ * Whether a connection record may still act.
263
+ * @param {object} connection - internal record.
264
+ * @returns {boolean} true when not revoked and inside its idle lease.
265
+ */
266
+ isConnectionLive(connection) {
267
+ if (connection.revokedAt !== null) return false;
268
+ return this.now() - connection.lastSeenAt <= this.leaseMs;
269
+ }
270
+
271
+ /**
272
+ * Revoke a connection because its idle lease lapsed, and emit the event.
273
+ *
274
+ * A connection that is already revoked has already been announced; it is not
275
+ * re-announced with a different reason, because that would cancel the same
276
+ * tasks twice under a misleading cause.
277
+ * @param {object} connection - internal record.
278
+ * @param {string} reason - event reason.
279
+ * @returns {number} number of grants revoked alongside it.
280
+ */
281
+ expireConnection(connection, reason) {
282
+ if (connection.revokedAt !== null) return 0;
283
+ return this.revokeConnectionInternal(connection, reason);
284
+ }
285
+
286
+ /**
287
+ * Revoke one connection and every grant it holds.
288
+ *
289
+ * The grants are revoked in the same synchronous step, so no execution can
290
+ * observe "connection revoked but grant still live". One `connection` event is
291
+ * emitted so the engine can cancel that connection's running tasks.
292
+ * @param {string} connectionId - identity to revoke.
293
+ * @returns {number} number of grants revoked with it.
294
+ */
295
+ revokeConnection(connectionId) {
296
+ const connection = this.connections.get(connectionId);
297
+ if (connection === undefined) {
298
+ throw new AuthError(AUTH_CODES.connectionUnknown, 'unknown connection', { connectionId });
299
+ }
300
+ if (connection.revokedAt !== null) return 0;
301
+ return this.revokeConnectionInternal(connection, AUTH_EVENT_REASONS.revoked);
302
+ }
303
+
304
+ /**
305
+ * Shared revocation path: stamp the connection, its grants, and announce it once.
306
+ * @param {object} connection - internal record.
307
+ * @param {string} reason - event reason.
308
+ * @returns {number} number of grants revoked with it.
309
+ */
310
+ revokeConnectionInternal(connection, reason) {
311
+ const at = this.now();
312
+ connection.revokedAt = at;
313
+ let revoked = 0;
314
+ for (const grant of this.grants.values()) {
315
+ if (grant.connectionId !== connection.connectionId || grant.revokedAt !== null) continue;
316
+ grant.revokedAt = at;
317
+ revoked += 1;
318
+ }
319
+ this.emit({ kind: 'connection', connectionId: connection.connectionId, reason });
320
+ return revoked;
321
+ }
322
+
323
+ /**
324
+ * Remove a connection and its grants entirely.
325
+ * @param {string} connectionId - identity to forget.
326
+ * @returns {boolean} true when something was removed.
327
+ */
328
+ forgetConnection(connectionId) {
329
+ for (const [id, grant] of this.grants) {
330
+ if (grant.connectionId === connectionId) this.grants.delete(id);
331
+ }
332
+ return this.connections.delete(connectionId);
333
+ }
334
+
335
+ /**
336
+ * Issue an authorization for one task or one session.
337
+ *
338
+ * A grant always names the connection that will exercise it and the exact
339
+ * workspace it covers. Both are required, so an authorization for one project
340
+ * can never be spent on another.
341
+ * @param {string} connectionId - issuing (and later exercising) connection.
342
+ * @param {object} input - `kind`, `workspacePath`, `ttlSeconds`, `overrides`.
343
+ * @returns {object} the grant record safe to return to its owner.
344
+ */
345
+ issueGrant(connectionId, input) {
346
+ this.sweep();
347
+ const connection = this.requireLiveConnection(connectionId);
348
+ const kind = input?.kind;
349
+ if (!GRANT_KINDS.includes(kind)) {
350
+ throw new AuthError('GRANT_KIND_INVALID', `grant kind must be one of ${GRANT_KINDS.join(', ')}`, { kind });
351
+ }
352
+ const workspacePath = normalizeWorkspace(input?.workspacePath);
353
+ const ttlSeconds = input?.ttlSeconds;
354
+ if (typeof ttlSeconds !== 'number' || !Number.isInteger(ttlSeconds) || ttlSeconds <= 0) {
355
+ throw new AuthError('GRANT_TTL_INVALID', 'grant ttlSeconds must be a positive integer', {});
356
+ }
357
+ // The TTL is bounded per kind by the same limits settings validation uses,
358
+ // so a caller cannot mint an effectively permanent authorization by asking
359
+ // for a longer lifetime than the operator's own settings allow.
360
+ const bounds = kind === 'session'
361
+ ? { min: LIMITS.sessionGrantTtlSecondsMin, max: LIMITS.sessionGrantTtlSecondsMax }
362
+ : { min: LIMITS.taskGrantTtlSecondsMin, max: LIMITS.taskGrantTtlSecondsMax };
363
+ if (ttlSeconds < bounds.min || ttlSeconds > bounds.max) {
364
+ throw new AuthError(
365
+ 'GRANT_TTL_OUT_OF_RANGE',
366
+ `a ${kind} grant TTL must be between ${bounds.min} and ${bounds.max} seconds`,
367
+ { kind, min: bounds.min, max: bounds.max, ttlSeconds },
368
+ );
369
+ }
370
+ if (this.grants.size >= AUTH_LIMITS.grantsTotal) {
371
+ throw new AuthError(AUTH_CODES.grantLimit, `at most ${AUTH_LIMITS.grantsTotal} grants may be outstanding`, {
372
+ limit: AUTH_LIMITS.grantsTotal,
373
+ });
374
+ }
375
+ const own = [...this.grants.values()].filter((grant) => grant.connectionId === connection.connectionId);
376
+ if (own.length >= AUTH_LIMITS.grantsPerConnection) {
377
+ throw new AuthError(AUTH_CODES.grantLimit, `at most ${AUTH_LIMITS.grantsPerConnection} grants per connection`, {
378
+ limit: AUTH_LIMITS.grantsPerConnection,
379
+ });
380
+ }
381
+ const createdAt = this.now();
382
+ const grant = {
383
+ grantId: `grant-${randomUUID()}`,
384
+ connectionId: connection.connectionId,
385
+ kind,
386
+ workspacePath,
387
+ overrides: input?.overrides === undefined ? null : structuredClone(input.overrides),
388
+ createdAt,
389
+ expiresAt: createdAt + ttlSeconds * 1000,
390
+ consumedAt: null,
391
+ consumedByTaskId: null,
392
+ revokedAt: null,
393
+ };
394
+ this.grants.set(grant.grantId, grant);
395
+ return publicGrant(grant);
396
+ }
397
+
398
+ /**
399
+ * Atomically consume a task grant for exactly one task.
400
+ *
401
+ * Every refusal path leaves the grant untouched and every success path marks
402
+ * it consumed before the caller can act on it, so a replayed request can only
403
+ * ever fail.
404
+ * @param {object} input - `connectionId`, `grantId`, `taskId`, `workspacePath`.
405
+ * @returns {object} the consumed grant snapshot.
406
+ */
407
+ consumeTaskGrant(input) {
408
+ const connection = this.requireLiveConnection(input?.connectionId);
409
+ const grant = this.grants.get(input?.grantId);
410
+ if (grant === undefined || grant.connectionId !== connection.connectionId) {
411
+ throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
412
+ }
413
+ if (grant.kind !== 'task') {
414
+ throw new AuthError(AUTH_CODES.grantMismatch, 'this grant does not authorize a single task', { kind: grant.kind });
415
+ }
416
+ this.assertUsable(grant);
417
+ const workspacePath = normalizeWorkspace(input?.workspacePath);
418
+ if (workspacePath !== grant.workspacePath) {
419
+ throw new AuthError(AUTH_CODES.grantMismatch, 'grant does not cover this workspace', {
420
+ workspacePath,
421
+ });
422
+ }
423
+ const taskId = input?.taskId;
424
+ if (typeof taskId !== 'string' || taskId === '') {
425
+ throw new AuthError('GRANT_TASK_REQUIRED', 'consuming a task grant requires the task id it authorizes', {});
426
+ }
427
+ grant.consumedAt = this.now();
428
+ grant.consumedByTaskId = taskId;
429
+ return publicGrant(grant);
430
+ }
431
+
432
+ /**
433
+ * Assert that a specific task is still authorized right now.
434
+ *
435
+ * This is the check a long-running job repeats as it progresses, and it is
436
+ * deliberately stricter than "a grant exists":
437
+ *
438
+ * * the connection must be live (not revoked, not past its idle lease);
439
+ * * the grant must belong to that exact connection and cover that exact
440
+ * workspace;
441
+ * * the grant must not be revoked or expired;
442
+ * * a `task` grant must already be consumed *by this very task*, because a
443
+ * consumed task grant stays consumed — it authorizes its own task and no
444
+ * other, and an unconsumed one has not authorized anything yet;
445
+ * * a `session` grant must be the one named by `grantId`, if one is named.
446
+ *
447
+ * @param {{ connectionId: unknown, grantId: unknown, taskId: unknown, workspacePath: unknown }} input - the four facts.
448
+ * @returns {object} a safe clone of the grant, never the stored record.
449
+ */
450
+ assertTaskAuthorized(input) {
451
+ const connection = this.requireLiveConnection(input?.connectionId);
452
+ const taskId = input?.taskId;
453
+ if (typeof taskId !== 'string' || taskId === '') {
454
+ throw new AuthError('GRANT_TASK_REQUIRED', 'an authorization check requires the task id', {});
455
+ }
456
+ const grant = this.grants.get(input?.grantId);
457
+ if (grant === undefined || grant.connectionId !== connection.connectionId) {
458
+ // Another connection's grant is reported as unknown, never as forbidden:
459
+ // a distinct code would confirm that the id exists.
460
+ throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
461
+ }
462
+ // Only revocation and expiry disqualify a grant here: a task grant that is
463
+ // consumed *by this task* is exactly what authorizes it, so consumption is
464
+ // checked below as a binding rather than refused as a state.
465
+ this.assertLive(grant);
466
+ const workspacePath = normalizeWorkspace(input?.workspacePath);
467
+ if (workspacePath !== grant.workspacePath) {
468
+ throw new AuthError(AUTH_CODES.grantMismatch, 'grant does not cover this workspace', { workspacePath });
469
+ }
470
+ if (grant.kind === 'task') {
471
+ if (grant.consumedAt === null) {
472
+ throw new AuthError(AUTH_CODES.grantNotConsumed, 'this task grant has not been consumed by any task', {});
473
+ }
474
+ if (grant.consumedByTaskId !== taskId) {
475
+ throw new AuthError(AUTH_CODES.grantConsumed, 'grant has already been consumed by another task', {
476
+ consumedByTaskId: grant.consumedByTaskId,
477
+ consumedAt: grant.consumedAt,
478
+ });
479
+ }
480
+ } else if (grant.kind !== 'session') {
481
+ throw new AuthError(AUTH_CODES.grantMismatch, 'this grant kind does not authorize a task', { kind: grant.kind });
482
+ }
483
+ return publicGrant(grant);
484
+ }
485
+
486
+ /**
487
+ * Check a session grant without consuming it. Used by the execution plane on
488
+ * each call, so revoking the grant stops further execution immediately.
489
+ *
490
+ * When `grantId` is supplied, exactly that grant is checked. A caller that
491
+ * names a grant and is then handed a *different* live grant would be told it
492
+ * holds an authorization it never referenced, so the lookup is never widened.
493
+ * @param {object} input - `connectionId`, `workspacePath`, optional `grantId`.
494
+ * @returns {object} the live session grant snapshot.
495
+ */
496
+ requireSessionGrant(input) {
497
+ const connection = this.requireLiveConnection(input?.connectionId);
498
+ const workspacePath = normalizeWorkspace(input?.workspacePath);
499
+ const named = input?.grantId;
500
+ if (named !== undefined) {
501
+ const grant = this.grants.get(named);
502
+ if (grant === undefined || grant.connectionId !== connection.connectionId) {
503
+ throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
504
+ }
505
+ if (grant.kind !== 'session') {
506
+ throw new AuthError(AUTH_CODES.grantMismatch, 'this grant is not a session grant', { kind: grant.kind });
507
+ }
508
+ if (grant.workspacePath !== workspacePath) {
509
+ throw new AuthError(AUTH_CODES.grantMismatch, 'grant does not cover this workspace', { workspacePath });
510
+ }
511
+ if (!this.isUsable(grant)) this.assertUsable(grant);
512
+ return publicGrant(grant);
513
+ }
514
+ let found = null;
515
+ for (const grant of this.grants.values()) {
516
+ if (grant.connectionId !== connection.connectionId) continue;
517
+ if (grant.kind !== 'session') continue;
518
+ if (grant.workspacePath !== workspacePath) continue;
519
+ if (!this.isUsable(grant)) continue;
520
+ found = grant;
521
+ break;
522
+ }
523
+ if (found === null) {
524
+ throw new AuthError(AUTH_CODES.grantUnknown, 'no live session grant covers this workspace', { workspacePath });
525
+ }
526
+ return publicGrant(found);
527
+ }
528
+
529
+ /**
530
+ * Revoke one grant and announce it.
531
+ * @param {{ connectionId?: string, grantId: unknown, allowOperator?: boolean }} input - revocation request.
532
+ * @returns {object} the revoked grant snapshot.
533
+ */
534
+ revokeGrant(input) {
535
+ const grant = this.grants.get(input?.grantId);
536
+ if (grant === undefined) {
537
+ throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant', {});
538
+ }
539
+ if (input?.allowOperator !== true && grant.connectionId !== input?.connectionId) {
540
+ throw new AuthError(AUTH_CODES.grantUnknown, 'no such grant for this connection', {});
541
+ }
542
+ if (grant.revokedAt === null) {
543
+ grant.revokedAt = this.now();
544
+ this.emit({
545
+ kind: 'grant',
546
+ grantId: grant.grantId,
547
+ connectionId: grant.connectionId,
548
+ reason: AUTH_EVENT_REASONS.revoked,
549
+ });
550
+ }
551
+ return publicGrant(grant);
552
+ }
553
+
554
+ /**
555
+ * Revoke every outstanding authorization. This is the operator's "stop
556
+ * everything now" action and the plugin's dispose path.
557
+ *
558
+ * One `all` event is emitted instead of one event per grant: a subscriber
559
+ * should stop everything once, not N times.
560
+ * @returns {number} number of grants revoked.
561
+ */
562
+ revokeAll() {
563
+ const at = this.now();
564
+ let count = 0;
565
+ for (const grant of this.grants.values()) {
566
+ if (grant.revokedAt !== null) continue;
567
+ grant.revokedAt = at;
568
+ count += 1;
569
+ }
570
+ for (const connection of this.connections.values()) {
571
+ if (connection.revokedAt === null) connection.revokedAt = at;
572
+ }
573
+ this.emit({ kind: 'all', reason: AUTH_EVENT_REASONS.revokedAll });
574
+ return count;
575
+ }
576
+
577
+ /**
578
+ * List grants visible to one connection. Consumption and expiry are reported
579
+ * as facts; no token or hash is included.
580
+ * @param {string} connectionId - queried connection.
581
+ * @returns {object[]} grant snapshots owned by that connection.
582
+ */
583
+ listGrants(connectionId) {
584
+ this.sweep();
585
+ const out = [];
586
+ for (const grant of this.grants.values()) {
587
+ if (grant.connectionId !== connectionId) continue;
588
+ out.push(publicGrant(grant));
589
+ }
590
+ return out.sort((a, b) => b.createdAt - a.createdAt);
591
+ }
592
+
593
+ /**
594
+ * List connections for the operator surface, with liveness facts only.
595
+ *
596
+ * `live` and `leaseExpiresAt` are derived, not stored: a connection is live
597
+ * while it is not revoked and inside its idle lease. The token and its hash are
598
+ * never part of this projection, now or later.
599
+ * @returns {object[]} connection snapshots without secrets or hashes.
600
+ */
601
+ listConnections() {
602
+ this.sweep();
603
+ const now = this.now();
604
+ return [...this.connections.values()]
605
+ .map((connection) => ({
606
+ connectionId: connection.connectionId,
607
+ label: connection.label,
608
+ createdAt: connection.createdAt,
609
+ lastSeenAt: connection.lastSeenAt,
610
+ leaseExpiresAt: connection.lastSeenAt + this.leaseMs,
611
+ live: this.isConnectionLive(connection),
612
+ revoked: connection.revokedAt !== null,
613
+ revokedAt: connection.revokedAt,
614
+ peer: { ...connection.peer },
615
+ }))
616
+ .sort((a, b) => b.createdAt - a.createdAt);
617
+ }
618
+
619
+ /**
620
+ * Settle and bound the registry.
621
+ *
622
+ * Three things happen here and all of them are idempotent:
623
+ *
624
+ * 1. A connection past its idle lease is revoked together with its grants,
625
+ * and one `connection` event is emitted so the engine can cancel its work.
626
+ * 2. A grant that expires before being revoked emits one `grant` event, once
627
+ * — including a grant a running task has consumed. Expiring quietly would
628
+ * leave a running task with no notification.
629
+ * 3. Settled grants and connections older than the retention window are
630
+ * deleted, which is what keeps both maps bounded across a long session.
631
+ *
632
+ * @returns {{ grants: number, connections: number }} number of entries removed.
633
+ */
634
+ sweep() {
635
+ const now = this.now();
636
+ let grantsRemoved = 0;
637
+ let connectionsRemoved = 0;
638
+
639
+ for (const connection of this.connections.values()) {
640
+ if (connection.revokedAt !== null) continue;
641
+ if (now - connection.lastSeenAt <= this.leaseMs) continue;
642
+ this.expireConnection(connection, AUTH_EVENT_REASONS.leaseExpired);
643
+ }
644
+
645
+ for (const [id, grant] of this.grants) {
646
+ if (grant.expiryAnnounced !== true && grant.expiresAt <= now) {
647
+ grant.expiryAnnounced = true;
648
+ // A revoked grant has already been announced as revoked and must not be
649
+ // re-announced. A *consumed* grant has not: a running task holding it
650
+ // needs to learn that its authorization has run out, so consumption is
651
+ // deliberately not part of this condition.
652
+ if (grant.revokedAt === null) {
653
+ this.emit({
654
+ kind: 'grant',
655
+ grantId: grant.grantId,
656
+ connectionId: grant.connectionId,
657
+ reason: AUTH_EVENT_REASONS.expired,
658
+ });
659
+ }
660
+ }
661
+ const settledAt = Math.max(grant.expiresAt, grant.consumedAt ?? 0, grant.revokedAt ?? 0);
662
+ if (settledAt === 0) continue;
663
+ if (now - settledAt <= AUTH_RETENTION_MS) continue;
664
+ this.grants.delete(id);
665
+ grantsRemoved += 1;
666
+ }
667
+
668
+ for (const [id, connection] of this.connections) {
669
+ if (connection.revokedAt === null) continue;
670
+ if (now - connection.revokedAt <= AUTH_RETENTION_MS) continue;
671
+ this.connections.delete(id);
672
+ connectionsRemoved += 1;
673
+ }
674
+
675
+ return { grants: grantsRemoved, connections: connectionsRemoved };
676
+ }
677
+
678
+ /**
679
+ * Resolve a connection that must still be able to act.
680
+ *
681
+ * An expired lease is reported as expired and the connection is settled (with
682
+ * its invalidation event) rather than being silently refreshed: the caller did
683
+ * not present a token on this path, so there is no heartbeat to justify
684
+ * renewal.
685
+ * @param {unknown} connectionId - connection identity.
686
+ * @returns {object} the live connection record.
687
+ */
688
+ requireLiveConnection(connectionId) {
689
+ const connection = this.connections.get(connectionId);
690
+ if (connection === undefined) {
691
+ throw new AuthError(AUTH_CODES.connectionUnknown, 'unknown connection', {});
692
+ }
693
+ if (connection.revokedAt !== null) {
694
+ throw new AuthError(AUTH_CODES.connectionRevoked, 'connection has been revoked', {});
695
+ }
696
+ if (!this.isConnectionLive(connection)) {
697
+ this.expireConnection(connection, AUTH_EVENT_REASONS.leaseExpired);
698
+ throw new AuthError(AUTH_CODES.connectionExpired, 'connection lease has expired', {});
699
+ }
700
+ return connection;
701
+ }
702
+
703
+ isUsable(grant) {
704
+ return grant.consumedAt === null && grant.revokedAt === null && grant.expiresAt > this.now();
705
+ }
706
+
707
+ /**
708
+ * Refuse a grant that is revoked or expired. Consumption is not checked here
709
+ * because whether consumption is disqualifying depends on the question: a
710
+ * task grant must be consumed to authorize its own task.
711
+ * @param {object} grant - internal record.
712
+ * @returns {void}
713
+ */
714
+ assertLive(grant) {
715
+ if (grant.revokedAt !== null) {
716
+ throw new AuthError(AUTH_CODES.grantRevoked, 'grant has been revoked', {});
717
+ }
718
+ if (grant.expiresAt <= this.now()) {
719
+ throw new AuthError(AUTH_CODES.grantExpired, 'grant has expired', { expiresAt: grant.expiresAt });
720
+ }
721
+ }
722
+
723
+ assertUsable(grant) {
724
+ this.assertLive(grant);
725
+ if (grant.consumedAt !== null) {
726
+ throw new AuthError(AUTH_CODES.grantConsumed, 'grant has already been consumed', {
727
+ consumedByTaskId: grant.consumedByTaskId,
728
+ consumedAt: grant.consumedAt,
729
+ });
730
+ }
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Canonical workspace key for grant comparison.
736
+ *
737
+ * Two spellings of the same directory must produce the same key, or a grant
738
+ * issued for `C:\work\project` would refuse a request for `c:/work/project/`.
739
+ * The rules are explicit so they can be reasoned about:
740
+ *
741
+ * * the value must be a non-empty string without a NUL byte;
742
+ * * it must be absolute (a drive-letter path, a UNC path, or a rooted path);
743
+ * * it is normalized and resolved as a path (`..` and `.` segments collapse),
744
+ * which is why `C:\work\..\other` and `C:\other` are the same key;
745
+ * * a filesystem root keeps its separator: `C:\` and `/` stay `C:\` and `/`,
746
+ * because `C:` is a drive-relative path, not the root;
747
+ * * on Windows, both separators are folded to `\` and the whole key is
748
+ * lowercased, since that filesystem is case-insensitive.
749
+ *
750
+ * @param {unknown} value - candidate workspace path.
751
+ * @returns {string} canonical workspace key.
752
+ */
753
+ export function normalizeWorkspace(value) {
754
+ if (typeof value !== 'string' || value.trim() === '') {
755
+ throw new AuthError('GRANT_WORKSPACE_REQUIRED', 'a workspace path is required', {});
756
+ }
757
+ if (value.includes('\0')) {
758
+ throw new AuthError('GRANT_WORKSPACE_INVALID', 'a workspace path must not contain a NUL byte', {});
759
+ }
760
+ const trimmed = value.trim();
761
+ if (!path.isAbsolute(trimmed)) {
762
+ throw new AuthError('GRANT_WORKSPACE_NOT_ABSOLUTE', 'workspace path must be absolute', {});
763
+ }
764
+ const resolved = path.resolve(trimmed);
765
+ if (process.platform !== 'win32') return resolved;
766
+ const folded = resolved.replace(/\//g, '\\').toLowerCase();
767
+ // `path.resolve` already produced a root-preserving form; keep it that way so
768
+ // `c:\` never degrades to `c:`.
769
+ return folded;
770
+ }
771
+
772
+ /**
773
+ * Public projection of a grant: identifiers and lifecycle facts only.
774
+ * @param {object} grant - internal record.
775
+ * @returns {object} fresh snapshot.
776
+ */
777
+ function publicGrant(grant) {
778
+ return {
779
+ grantId: grant.grantId,
780
+ kind: grant.kind,
781
+ workspacePath: grant.workspacePath,
782
+ createdAt: grant.createdAt,
783
+ expiresAt: grant.expiresAt,
784
+ consumedAt: grant.consumedAt,
785
+ consumedByTaskId: grant.consumedByTaskId,
786
+ revokedAt: grant.revokedAt,
787
+ overrides: grant.overrides === null ? null : structuredClone(grant.overrides),
788
+ };
789
+ }