@tnunamak/dalan 0.8.1 → 0.8.2

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 (124) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +64 -19
  100. package/src/service-update.mjs +193 -48
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/as-store.mjs CHANGED
@@ -55,6 +55,8 @@ export class AsStore {
55
55
  CREATE INDEX IF NOT EXISTS oidc_expiry ON oidc(expires_at) WHERE expires_at IS NOT NULL;
56
56
  CREATE TABLE IF NOT EXISTS refresh_receipts(
57
57
  grant_id TEXT PRIMARY KEY, token_id TEXT NOT NULL, deadline INTEGER NOT NULL, payload TEXT NOT NULL) WITHOUT ROWID;
58
+ CREATE TABLE IF NOT EXISTS refresh_heads(
59
+ grant_id TEXT PRIMARY KEY, payload TEXT NOT NULL, prev_id TEXT, rotated_at INTEGER) WITHOUT ROWID;
58
60
  CREATE TABLE IF NOT EXISTS static_clients(client_id TEXT PRIMARY KEY) WITHOUT ROWID;
59
61
  CREATE TABLE IF NOT EXISTS connections(
60
62
  connection_id TEXT PRIMARY KEY, worker TEXT NOT NULL, grant_id TEXT NOT NULL UNIQUE, client_id TEXT NOT NULL,
@@ -71,6 +73,9 @@ export class AsStore {
71
73
  const columns = this.db.prepare('PRAGMA table_info(windows)').all().map(c => c.name);
72
74
  if (!columns.includes('registrations')) this.db.exec('ALTER TABLE windows ADD COLUMN registrations INTEGER NOT NULL DEFAULT 0');
73
75
  if (!columns.includes('generation')) this.db.exec('ALTER TABLE windows ADD COLUMN generation TEXT');
76
+ const headColumns = this.db.prepare('PRAGMA table_info(refresh_heads)').all().map(c => c.name);
77
+ if (!headColumns.includes('prev_id')) this.db.exec('ALTER TABLE refresh_heads ADD COLUMN prev_id TEXT');
78
+ if (!headColumns.includes('rotated_at')) this.db.exec('ALTER TABLE refresh_heads ADD COLUMN rotated_at INTEGER');
74
79
  try { this.#initializeCodec(); } catch { this.db.close(); throw new Error('as: encrypted storage could not be opened'); }
75
80
  this.onGrantRevoked = () => {};
76
81
  const self = this;
@@ -196,6 +201,34 @@ export class AsStore {
196
201
  if (!row || row.deadline <= this.now()) return undefined;
197
202
  return { ...row, value: JSON.parse(this.#open(row.payload, `refresh-receipt:${row.grant_id}`)) };
198
203
  }
204
+ // The grant's current head refresh token, sealed, with the id of the one token rotated away to make it. Only that token,
205
+ // presented within windowMs of the rotation (never before it: a clock step back is refused), is answered with the head.
206
+ reuseHead(grantId, tokenValue, windowMs) {
207
+ const row = this.db.prepare('SELECT payload,prev_id,rotated_at FROM refresh_heads WHERE grant_id=?').get(grantId);
208
+ if (!row || row.rotated_at === null) return undefined;
209
+ const age = this.now() - row.rotated_at;
210
+ if (age < 0 || age > windowMs || row.prev_id !== this.#id('RefreshToken', tokenValue)) return undefined;
211
+ return { head: this.#open(row.payload, `refresh-head:${grantId}`), age };
212
+ }
213
+ // Commit-time fence for a tolerated reuse, like commitRefresh: nothing it read may have changed, the connection must still be
214
+ // live, and the head must still be the one served. Only then are the staged access-token writes stored.
215
+ commitReuse(exchange, grantId, clientId, head, windowMs) {
216
+ this.tx(() => {
217
+ for (const [model, id, original] of exchange.reads) {
218
+ if (JSON.stringify(this.find(model, id)) !== original) throw new errors.InvalidGrant('refresh state changed');
219
+ }
220
+ const connection = this.connectionByGrant(grantId);
221
+ const grant = this.find('Grant', grantId);
222
+ if (!connection || connection.revoked_at !== null || connection.client_id !== clientId || !grant || grant.clientId !== clientId) throw new errors.InvalidGrant('grant inactive');
223
+ const row = this.db.prepare('SELECT payload,rotated_at FROM refresh_heads WHERE grant_id=?').get(grantId);
224
+ const age = row?.rotated_at == null ? -1 : this.now() - row.rotated_at;
225
+ if (!row || age < 0 || age > windowMs || this.#open(row.payload, `refresh-head:${grantId}`) !== head) throw new errors.InvalidGrant('refresh state changed');
226
+ for (const [op, model, id, payload, ttl] of exchange.writes) {
227
+ if (op !== 'upsert' || model !== 'AccessToken') throw new errors.InvalidGrant('refresh state changed');
228
+ this.upsert(model, id, payload, ttl);
229
+ }
230
+ });
231
+ }
199
232
  refreshValid(grantId, clientId, successor) {
200
233
  const connection = this.connectionByGrant(grantId);
201
234
  const grant = this.find('Grant', grantId);
@@ -226,6 +259,11 @@ export class AsStore {
226
259
  this.db.prepare('DELETE FROM refresh_receipts WHERE deadline<=? OR grant_id=?').run(this.now(), grantId);
227
260
  this.db.prepare('INSERT INTO refresh_receipts VALUES(?,?,?,?)').run(grantId, this.#id('RefreshToken', token), deadline,
228
261
  this.#seal(JSON.stringify({ clientId, params, response }), `refresh-receipt:${grantId}`));
262
+ // No rotated token in the response means no head to serve; a stale head must not outlive it.
263
+ if (typeof response?.refresh_token === 'string') {
264
+ this.db.prepare('INSERT INTO refresh_heads VALUES(?,?,?,?) ON CONFLICT(grant_id) DO UPDATE SET payload=excluded.payload,prev_id=excluded.prev_id,rotated_at=excluded.rotated_at')
265
+ .run(grantId, this.#seal(response.refresh_token, `refresh-head:${grantId}`), this.#id('RefreshToken', token), this.now());
266
+ } else this.db.prepare('DELETE FROM refresh_heads WHERE grant_id=?').run(grantId);
229
267
  });
230
268
  }
231
269
 
@@ -268,6 +306,7 @@ export class AsStore {
268
306
  #revokeGrantRows(grantId, reason, now = this.now()) {
269
307
  this.db.prepare('DELETE FROM oidc WHERE grant_id=?').run(grantId);
270
308
  this.db.prepare("DELETE FROM oidc WHERE model='Grant' AND id=?").run(grantId);
309
+ this.db.prepare('DELETE FROM refresh_heads WHERE grant_id=?').run(grantId);
271
310
  this.db.prepare('UPDATE connections SET revoked_at=?,revoked_reason=? WHERE grant_id=? AND revoked_at IS NULL').run(now, reason, grantId);
272
311
  }
273
312
  // The one revocation path: tokens, codes and the Grant record go, and the connection row is marked. Idempotent.
@@ -311,6 +350,7 @@ export class AsStore {
311
350
  purge() {
312
351
  const now = this.now();
313
352
  this.db.prepare('DELETE FROM refresh_receipts WHERE deadline<=?').run(now);
353
+ this.db.prepare('DELETE FROM refresh_heads WHERE grant_id NOT IN (SELECT grant_id FROM connections WHERE revoked_at IS NULL)').run();
314
354
  const expired = this.db.prepare('DELETE FROM oidc WHERE expires_at IS NOT NULL AND expires_at<=?').run(now).changes;
315
355
  // Registered clients that never got a connection are dropped after a day: anonymous registration must not grow without bound.
316
356
  const stale = this.db.prepare(`DELETE FROM oidc WHERE model='Client' AND created_at<? AND id NOT IN (SELECT client_id FROM static_clients) AND id NOT IN (SELECT client_id FROM connections)
@@ -322,12 +362,14 @@ export class AsStore {
322
362
 
323
363
  // ---- pairing window --------------------------------------------------------------------------------------------
324
364
  openWindow(worker, minutes) {
325
- const now = this.now(), open = this.window();
326
- if (open && open.worker !== worker) throw new Error(`a pairing window for ${open.worker} is open until ${new Date(open.expires_at).toISOString()}; stop it first`);
327
- if (open) this.db.prepare('UPDATE windows SET expires_at=? WHERE id=1').run(now + minutes * 60000);
328
- else this.db.prepare('INSERT INTO windows(id,worker,opened_at,expires_at,registrations,generation) VALUES(1,?,?,?,0,?) ON CONFLICT(id) DO UPDATE SET worker=excluded.worker,opened_at=excluded.opened_at,expires_at=excluded.expires_at,registrations=0,generation=excluded.generation')
329
- .run(worker, now, now + minutes * 60000, randomUUID());
330
- return this.window();
365
+ return this.tx(() => {
366
+ const now = this.now(), open = this.window();
367
+ if (open && open.worker !== worker) throw new Error(`a pairing window for ${open.worker} is open until ${new Date(open.expires_at).toISOString()}; stop it first`);
368
+ if (open) this.db.prepare('UPDATE windows SET expires_at=? WHERE id=1').run(now + minutes * 60000);
369
+ else this.db.prepare('INSERT INTO windows(id,worker,opened_at,expires_at,registrations,generation) VALUES(1,?,?,?,0,?) ON CONFLICT(id) DO UPDATE SET worker=excluded.worker,opened_at=excluded.opened_at,expires_at=excluded.expires_at,registrations=0,generation=excluded.generation')
370
+ .run(worker, now, now + minutes * 60000, randomUUID());
371
+ return this.window();
372
+ });
331
373
  }
332
374
  window() {
333
375
  const row = this.db.prepare('SELECT * FROM windows WHERE id=1').get();
@@ -414,6 +456,9 @@ export class AsStore {
414
456
  commitApproval({ code, worker, grantId, snapshot, replace }) {
415
457
  return this.tx(() => {
416
458
  const now = this.now();
459
+ const reserved = this.db.prepare("SELECT expires_at FROM pairings WHERE code=? AND state='approving'").get(code);
460
+ if (!reserved) throw new Error('pairing is no longer being approved');
461
+ if (!Number.isFinite(reserved.expires_at) || reserved.expires_at <= now) throw new Error('pairing approval expired');
417
462
  // Removal and approval serialize here, so a delayed approval cannot recreate a connection after client removal.
418
463
  if (!this.db.prepare("SELECT 1 FROM oidc WHERE model='Client' AND id=?").get(snapshot.client_id)) throw new Error('client was removed');
419
464
  let replaced = null;
package/src/as.mjs CHANGED
@@ -3,7 +3,7 @@ const GRANT_TYPES = ['authorization_code', 'refresh_token', 'client_credentials'
3
3
  const TOKEN_PARAMS = ['grant_type', 'code', 'redirect_uri', 'client_id', 'client_secret', 'code_verifier', 'refresh_token', 'scope', 'resource', 'client_assertion', 'client_assertion_type'];
4
4
  import { Provider, errors } from 'oidc-provider';
5
5
  import { ACCEPTED_SCOPES, ADVERTISED_SCOPES, canonicalScopes } from './scopes.mjs';
6
- import { randomUUID } from 'node:crypto';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
7
  import { performance } from 'node:perf_hooks';
8
8
  import { acquireAsOwner, asFiles, LIFETIMES, PAIRING_MINUTES, loadAsConfig, loadKeys, isLoopbackCallback, matchesCallback, parseAsConfig, parseCallbackPattern, parseNativeLoopback, saveAsCallbacks, untrusted } from './as-files.mjs';
9
9
  import { AsStore, LIMITS, normalizeCode, showCode } from './as-store.mjs';
@@ -16,6 +16,10 @@ import { approvalFacts, approvalRecord, describeClient } from './client-approval
16
16
  export const SCOPES = ADVERTISED_SCOPES;
17
17
  export const ACCOUNT = 'owner';
18
18
  const ACCESS_TOKEN_TTL = 3600;
19
+ // The token rotated away one step ago, presented this soon after, is a concurrent holder of the connection, not a replay
20
+ // (Okta rotation grace period, Auth0 rotation overlap). Measured need: stale holders arrived 38 s and 175 s late; Okta allows 0-60 s.
21
+ // DALAN_REFRESH_REUSE_WINDOW_MS overrides it (clamped to 1 s .. 1 h) so tests can cross the window quickly.
22
+ export const REUSE_WINDOW_MS = Math.min(3600000, Math.max(1000, Number(process.env.DALAN_REFRESH_REUSE_WINDOW_MS) || 5 * 60 * 1000));
19
23
  const OFF = Object.freeze({ enabled: false });
20
24
  const html = text => String(text).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
21
25
  export { untrusted };
@@ -107,7 +111,8 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
107
111
  scopes: [...ACCEPTED_SCOPES],
108
112
  pkce: { required: () => true }, // S256 is the only method the library supports
109
113
  ttl: { AuthorizationCode: 600, AccessToken: ACCESS_TOKEN_TTL, RefreshToken: 30 * 86400, Grant: 90 * 86400, Interaction: LIFETIMES.interaction, Session: LIFETIMES.session, IdToken: LIFETIMES.idToken, ClientCredentials: 600, DeviceCode: 600 },
110
- rotateRefreshToken: true,
114
+ // A reuse inside the window answers with the current head and must not rotate it again.
115
+ rotateRefreshToken: async ctx => !ctx.dalanReuseHead,
111
116
  // A connection is the owner's approval, not a browser login: its tokens must not die with the pairing session.
112
117
  // oidc-provider's default binds them to the session unless the client asks for offline_access. Revocation stays per connection.
113
118
  expiresWithSession: async () => false,
@@ -171,7 +176,22 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
171
176
  const receipt = source.consumed && store.refreshReceipt(tokenValue);
172
177
  const retry = receipt && receipt.grant_id === source.grantId && receipt.value.clientId === clientId &&
173
178
  receipt.value.params === fingerprint && store.refreshValid(source.grantId, clientId, receipt.value.response.refresh_token);
174
- if (source.consumed && !retry) return await handler(ctx);
179
+ if (source.consumed && !retry) {
180
+ // A concurrent holder of the same connection may present the one token that was rotated away moments ago. Inside the
181
+ // window, answer with a fresh access token and the current head, without rotating. Anything else the provider revokes.
182
+ const reuse = source.clientId === clientId && source.exp * 1000 > Date.now() ? store.reuseHead(source.grantId, tokenValue, REUSE_WINDOW_MS) : undefined;
183
+ if (reuse && store.refreshValid(source.grantId, clientId, reuse.head)) {
184
+ ctx.dalanReuseHead = reuse.head;
185
+ ctx.oidc.params.refresh_token = reuse.head;
186
+ // Staged like an ordinary refresh: nothing is stored or returned unless the commit-time checks still hold.
187
+ const staged = { reads: [], writes: [], retryToken: undefined };
188
+ await store.refreshExchange.run(staged, () => handler(ctx));
189
+ store.commitReuse(staged, source.grantId, clientId, reuse.head, REUSE_WINDOW_MS);
190
+ log({ kind: 'as_refresh_reuse_tolerated', age_ms: reuse.age });
191
+ return;
192
+ }
193
+ return await handler(ctx);
194
+ }
175
195
  const exchange = { reads: [], writes: [], retryToken: retry ? tokenValue : undefined };
176
196
  try { await store.refreshExchange.run(exchange, () => handler(ctx)); }
177
197
  catch (error) {
@@ -206,7 +226,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
206
226
  if (!store.reserveRegistration()) return reject(429, 'temporarily_unavailable', 'Registration limit reached. Reuse the client this worker already registered. If you cannot, ask the owner to run dalan connect reset, then retry.');
207
227
  if (Number(ctx.get('content-length')) > 8192) return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
208
228
  const normalized = await normalizeRegistration(ctx.req);
209
- if (normalized === 'too_large') { ctx.req.destroy(); return; }
229
+ if (normalized === 'too_large') return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
210
230
  if (normalized === 'invalid') return reject(400, 'invalid_request', 'The registration body must be a UTF-8 JSON object.');
211
231
  let bytes = 0;
212
232
  const count = chunk => { bytes += chunk.length; if (bytes > 8192) ctx.req.destroy(); };
@@ -391,11 +411,13 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
391
411
  // The owner CLI never prints the bridge path secret (approve output checks this), so show the resource's origin and shape only.
392
412
  const shownResource = resource => `${new URL(resource).origin}/<secret>/mcp`;
393
413
  const shownIssuer = `${publicUrl.origin}/<secret>/oauth`; // the issuer carries the secret path prefix too
414
+ const fingerprint = value => createHash('sha256').update(value).digest('base64url');
394
415
  const pendingView = pairing => {
395
416
  const shown = describeClient({ name: pairing.client_name, clientId: pairing.client_id, redirectUri: pairing.redirect_uri, worker: pairing.worker, issuer: shownIssuer, resource: '', scopes: [] });
396
417
  return {
397
418
  code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
398
419
  native: isLoopbackCallback(new URL(pairing.redirect_uri)),
420
+ interaction_fingerprint: fingerprint(pairing.uid),
399
421
  redirect_uri: pairing.redirect_uri, redirect_host: shown.redirect_host, redirect_origin: shown.redirect_origin, redirect_punycode: shown.redirect_punycode, known_client: shown.known_client,
400
422
  resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
401
423
  expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
@@ -443,7 +465,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
443
465
  stop() { return { closed: store.closeWindow() }; },
444
466
  pending() {
445
467
  const window = store.window();
446
- return { window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, pending: window ? supersede(store.pendingPairings().filter(p => p.worker === window.worker).map(pendingView)) : [] };
468
+ return { authorization_endpoint_fingerprint: fingerprint(issuer + '/auth'), window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, pending: window ? supersede(store.pendingPairings().filter(p => p.worker === window.worker).map(pendingView)) : [] };
447
469
  },
448
470
  async approve({ code, worker, replace = false, confirm_redirect: confirmRedirect }) {
449
471
  if (typeof code !== 'string' || normalizeCode(code).length !== 8) throw new Error('invalid pairing code');
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ // Catalog preflight only. Stop writers before using this snapshot to switch catalogs.
3
+ // It neither changes catalogs nor settles answers.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { journalPath, readJournal } from './answer-journal.mjs';
9
+
10
+ function unknownSends(receiptsDir) {
11
+ let directories;
12
+ try { directories = fs.readdirSync(receiptsDir, { withFileTypes: true }); }
13
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
14
+ const sends = [];
15
+ // src/answer-journal.mjs#journalPath: <job>.answers/<encoded question>.json.
16
+ for (const directory of directories.sort((a, b) => a.name.localeCompare(b.name))) {
17
+ if (!directory.name.endsWith('.answers')) continue;
18
+ if (!directory.isDirectory()) throw new Error('answer journal directory is not a regular directory');
19
+ const job = directory.name.slice(0, -'.answers'.length);
20
+ const dir = path.join(receiptsDir, directory.name);
21
+ for (const file of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
22
+ if (!file.name.endsWith('.json')) continue; // Unpublished stage files are not journal entries.
23
+ if (!file.isFile()) throw new Error('answer journal is not a regular file');
24
+ const questionId = decodeURIComponent(file.name.slice(0, -'.json'.length));
25
+ const filename = path.join(dir, file.name);
26
+ if (journalPath(receiptsDir, job, questionId) !== filename) throw new Error('noncanonical answer journal filename');
27
+ // Validate the complete envelope, but never expose answer text or command envelopes.
28
+ const entry = readJournal(filename, job, questionId);
29
+ if (!entry) throw new Error('answer journal disappeared during inventory; retry with writers stopped');
30
+ if (entry.state !== 'committed') {
31
+ sends.push({ job: entry.job, question_id: entry.question_id, state: entry.state });
32
+ }
33
+ }
34
+ }
35
+ return sends;
36
+ }
37
+
38
+ export function inventory({ dataRoot, receiptsDir = path.join(dataRoot, 'receipts') }) {
39
+ // src/restore-check.mjs#db: readOnly prevents creation and Store migrations.
40
+ const db = new DatabaseSync(path.join(dataRoot, 'bridge.db'), { readOnly: true });
41
+ try {
42
+ db.exec('BEGIN');
43
+ // src/store.mjs#Store.constructor creates assignments.
44
+ // src/store.mjs#Store.answerQuestionInTransaction treats finished/cancelled as terminal.
45
+ const open_jobs = db.prepare("SELECT request_id,status FROM assignments WHERE status NOT IN ('finished','cancelled') ORDER BY request_id").all().map(row => ({ ...row }));
46
+ // src/store.mjs#Store.migrate creates job_questions.
47
+ // src/store.mjs#Store.answerQuestionInTransaction saves answer/answered_at together.
48
+ // Include unanswered audit questions on finished jobs; do not silently discard them.
49
+ const open_questions = db.prepare('SELECT request_id AS job,question_id FROM job_questions WHERE answer IS NULL ORDER BY request_id,question_id').all().map(row => ({ ...row }));
50
+ // src/store.mjs#Store.assertRegrantReady: terminal jobs can still own host effects.
51
+ const open_checks = db.prepare("SELECT id,request_id AS job,check_id,status,stop_verified FROM check_jobs WHERE status='running' OR stop_verified IS NOT 1 ORDER BY request_id,id").all().map(row => ({ ...row }));
52
+ // src/store.mjs#Store.finishOnce enqueues result delivery after marking a job finished.
53
+ const pending_deliveries = db.prepare("SELECT id,request_id AS job,kind,state FROM notifications WHERE state IN ('pending','sending','failed','uncertain','uncertain_terminal') AND kind IN ('t3','blocker','watch') ORDER BY request_id,id").all().map(row => ({ ...row }));
54
+ const unknown_sends = unknownSends(receiptsDir);
55
+ db.exec('COMMIT');
56
+ return { open_jobs, open_questions, open_checks, pending_deliveries, unknown_sends, safe_to_switch: !open_jobs.length && !open_questions.length && !open_checks.length && !pending_deliveries.length && !unknown_sends.length };
57
+ } finally { db.close(); }
58
+ }
59
+
60
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
61
+ const [dataRoot, extra] = process.argv.slice(2);
62
+ try {
63
+ if (!dataRoot || extra !== undefined) throw new Error('usage: node src/catalog-switch-inventory.mjs DATA_ROOT');
64
+ process.stdout.write(JSON.stringify(inventory({ dataRoot })) + '\n');
65
+ } catch {
66
+ // Fail closed. No success-shaped JSON and no answer content on an unreadable input.
67
+ process.stderr.write('catalog-switch-inventory: inventory unavailable; check arguments, database and answer journals. Nothing was changed.\n');
68
+ process.exitCode = 1;
69
+ }
70
+ }
@@ -5,8 +5,11 @@ export async function checkResponse(work, running, {
5
5
  schedule = setTimeout,
6
6
  cancel = clearTimeout,
7
7
  } = {}) {
8
- if (!Number.isFinite(responseMs) || responseMs < 0)
8
+ if (!Number.isFinite(responseMs) || responseMs < 0) {
9
+ // Observe rejected work even when the response budget is invalid.
10
+ Promise.resolve(work).catch(() => {});
9
11
  throw new TypeError('responseMs must be a non-negative finite number');
12
+ }
10
13
  let timer;
11
14
  try {
12
15
  return await Promise.race([
package/src/cli-help.mjs CHANGED
@@ -6,6 +6,8 @@ import { docsUrl } from './docs-url.mjs';
6
6
  // commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
7
7
  // `dalan help --internal`. Every command runs and has its own help either way.
8
8
  export const COMMANDS = [
9
+ { name: 'jobs', summary: 'Read a versioned page of jobs', usage: 'dalan jobs --json [--worker W] [--status S] [--since T] [--kind K] [--source S] [--limit N] [--cursor C]', detail: ['Reads local state without changing it. Default page size 100, maximum 1000. Pass next_cursor to --cursor for the next page. --since filters creation time (Nh, Nd, RFC3339, or all). See docs/operations.md#stable-read-interface for fields and compatibility.'] },
10
+ { name: 'events', summary: 'Read a versioned page of lifecycle events', usage: 'dalan events --json [--since T] [--worker W] [--type TYPE] [--limit N] [--cursor C]', detail: ['Reads retained lifecycle events in ID order without changing state. Default page size 100, maximum 1000. --since takes Nh, Nd, RFC3339, or all. Pass next_cursor to --cursor for the next page. See docs/operations.md#stable-read-interface.'] },
9
11
  { name: 'relationships', group: 'operator', summary: 'List or end relationships', usage: 'dalan relationships list | end RELATIONSHIP_ID [--json]', detail: ['Ending a relationship blocks new work; existing jobs and grants remain.'] },
10
12
  { name: 'grants', group: 'operator', summary: 'List authority held by each enforcer', usage: 'dalan grants [--json]', detail: ['Shows relationship and grant lifetimes independently.'] },
11
13
  { name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--route NAME]] [--home DIR] [--port N] [--callback PATTERN]...',
@@ -16,12 +18,12 @@ export const COMMANDS = [
16
18
  ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
17
19
  ' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN local mode only: allow one more OAuth callback pattern; repeatable', '',
18
20
  'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a temporary public trial creates a new home, and a saved stable route uses ~/.local/share/dalan-hosted. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
19
- { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup [--route NAME]',
21
+ { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup [--route NAME | --cancel OPERATION_ID]',
20
22
  detail: ['Asks Gozar which routes can serve Dalan, shows what it returned, and saves your choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in.',
21
23
  'With --route NAME, asks Gozar for the route with that name. Afterwards `dalan try --public` uses the saved route.', '', 'Example: dalan setup'] },
22
24
  { name: 'service', group: 'operator', summary: 'Install, update or inspect a long-running bridge service', usage: 'dalan service install|migrate-workers|update|auto-update|status [options]',
23
25
  detail: ['Install the bridge as a background service that starts on its own, and publish it through a Gozar route.', '',
24
- 'Install: dalan service install --worker NAME --route NAME [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update] [--write-units-only]',
26
+ 'Install: dalan service install --worker NAME [--route NAME] [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update] [--write-units-only]',
25
27
  'With --route alone, Gozar supplies the public address and Dalan picks a loopback port. To use an HTTPS origin you already run, pass --public-url https://HOST --port N --target HOST:PORT instead, with optional [--lan-port N] [--verify-cmd COMMAND].',
26
28
  'New installs enable a daily update timer with up to one hour of jitter. Existing preferences are preserved.',
27
29
  'Update: dalan service update [--check|--yes] [--retry] [--home DIR] [--json]. --check only reports availability. --retry tries a release again after a rollback.',
@@ -42,6 +44,7 @@ export const COMMANDS = [
42
44
  { name: 'connect', group: 'start', summary: 'Pair a worker client with the bridge', usage: 'dalan connect <subcommand> [options]',
43
45
  detail: ['Subcommands:', ' start --worker NAME [--minutes N] open a pairing window for a worker', ' pending [--json] show connection attempts waiting for approval',
44
46
  ' approve CODE --worker NAME approve only the attempt with this code', ' [--confirm-redirect URI] required for a native client: the redirect you expect', ' [--replace] replace an existing connection for the worker',
47
+ ' complete URL --worker NAME [--replace] [--json]', ' approve and finish a local loopback sign-in without a browser;', ' URL is the authorization URL the local client printed',
45
48
  ' list [--json] show connected workers', ' revoke NAME disconnect a worker', ' stop close the pairing window', ' reset clear pairing state',
46
49
  ' add-client --redirect-uri URI [--name NAME] [--json] register an OAuth client', ' clients [--json] list OAuth clients', ' remove-client CLIENT_ID [--json] remove an OAuth client',
47
50
  ' allow-callback PATTERN allow another OAuth callback pattern', ' signal-token [--worker NAME] [--rotate] [--json] show or rotate a worker signal token', '',
@@ -61,6 +64,10 @@ export const COMMANDS = [
61
64
  ' dalan submit --worker local --execution none --deliver none --file first-job.json --json', ' dalan wait REQUEST_ID', ' dalan get REQUEST_ID', ' dalan decide REQUEST_ID accepted',
62
65
  '', 'Example (a question that needs no files):', ' dalan submit --worker local --brief "What does a database index do?"', '',
63
66
  'Replace REQUEST_ID with the request_id that submit prints. Read the report before you accept it.', `first-job.json and the full walk-through: ${docsUrl('docs/manual-setup.md', 'submit-finish-and-read-the-result')}`] },
67
+ { name: 'forecast', summary: 'Preview a job’s admission without queuing it', usage: 'dalan forecast (--file PATH | --stdin | --brief TEXT) [options]',
68
+ detail: ['Runs the same admission checks as dalan submit --dry-run. Nothing is queued or reserved.', 'Use submit input and worker options. --json prints the admission report.'] },
69
+ { name: 'correct', summary: 'Submit a corrected version of a job', usage: 'dalan correct REQUEST_ID (--file PATH | --stdin | --brief TEXT) [options]',
70
+ detail: ['Runs dalan submit --revises REQUEST_ID with the remaining submit arguments. It does not cancel the earlier job.'] },
64
71
  { name: 'status', group: 'everyday', summary: 'Show the bridge, queue and worker state', usage: 'dalan status [--explain] [--json]',
65
72
  detail: ['Prints the bridge state.', '', 'Options:', ' --explain describe the state and recent metrics in plain words', ' --json print JSON', '', 'Example: dalan status, then dalan inbox --all'] },
66
73
  { name: 'get', group: 'everyday', summary: 'Show one job (or message) by ID', usage: 'dalan get ID [--json]',
@@ -74,6 +81,8 @@ export const COMMANDS = [
74
81
  detail: ['Lists what needs you. A producer is the shell or agent session that submitted the job. Inside a Claude Code or Codex session, plain dalan inbox lists that session\'s jobs.', 'Outside a Claude Code or Codex session, plain dalan inbox lists every producer\'s jobs on this bridge home.', '--all lists every producer anywhere; --producer ID lists one.', '', 'Options:', ' --since, --before an RFC3339 time or a duration such as 72h or 3d', '', 'Default window: jobs updated in the last 72 hours. Questions are always listed. To see older results: dalan inbox --all --since all', '', 'A line marked "wake held: parent_stopped" is a result or question that did not reach your T3 thread because the thread\'s latest run was stopped. It stays queued and sends when the thread runs again; read it now with dalan get.', '', 'Example: dalan inbox --all, then dalan get REQUEST_ID'] },
75
82
  { name: 'decide', group: 'everyday', summary: 'Record your decision on a finished job', usage: 'dalan decide ID WORD [--note TEXT]',
76
83
  detail: ['Records your decision on a finished job. Review the report or patch first.', '', 'WORD is one of: accepted, applied, useful_no_change, useful_negative, not_useful.', 'Example: dalan decide REQUEST_ID accepted'] },
84
+ { name: 'materialize', summary: 'Publish a finished job\'s patch as a draft pull request, or preview the decision', usage: 'dalan materialize ID (--dry-run | [--approve] [--dir PATH]) [--json]',
85
+ detail: ['Reads a current finished job and the owner grant in ~/.config/dot-bridge/materialize.json.', 'With --dry-run it prints the decision and the patch files, and changes nothing.', 'Otherwise, when the grant covers the repository (or asks for approval and you pass --approve), it commits the patch at the job\'s base commit in a temporary worktree of the clone in --dir (default: the current directory), pushes a new branch dalan/ID and opens a draft pull request.', 'It never replaces an existing branch, never merges and records no decision.'] },
77
86
  { name: 'apply', group: 'everyday', summary: 'Apply a finished job\'s patch to a directory', usage: 'dalan apply ID [--dir PATH] [--release]',
78
87
  detail: ['Applies the patch from a finished job to a directory (default: the current directory) and records the decision "applied" for you, after the patch is written.', 'There is no need to accept the job first.', 'If the write fails, the files are put back and the job stays not applied. If the process dies before the bridge confirms, `dalan get` shows the apply as uncertain; run apply again to resolve it. If the checkout was left partly changed, the error names the files and the recovery steps; "dalan apply ID --release" gives up the uncertain apply on purpose and touches no file.'] },
79
88
  { name: 'mcp', group: 'everyday', summary: 'Serve submit, wait, result and status as local MCP tools over stdio', usage: 'dalan mcp',
@@ -88,6 +97,8 @@ export const COMMANDS = [
88
97
  { name: 'pause', group: 'operator', summary: 'Stop handing out new jobs', usage: 'dalan pause --reason TEXT' },
89
98
  { name: 'resume', group: 'operator', summary: 'Resume handing out jobs', usage: 'dalan resume' },
90
99
  // Reachable, but not on the first screen.
100
+ { name: 'quiesce', summary: 'Hold new effectful calls for a restart', usage: 'dalan quiesce on|off|status [--json]',
101
+ detail: ['Closes (on) or reopens (off) the admission gate so the service can restart without waiting for worker leases. While on, every call that changes state is refused with a retryable message; reads still answer and no lease changes.', '', 'status prints on, admitted_in_flight, delivery_in_flight, host_checks_unverified and live_leases. The mode is in memory only: a restart reopens the gate.'] },
91
102
  { name: 'artifact', summary: 'Download a job artifact', usage: 'dalan artifact ID --output PATH' },
92
103
  { name: 'cancel', summary: 'Cancel a job', usage: 'dalan cancel ID [--reason TEXT]',
93
104
  detail: ['Withdraws a job.', '', 'Scope controlled: the job. Its authority is withdrawn, so a result sent after this is kept as audit evidence and is not accepted.', 'Not controlled: worker compute. A worker that already holds the job may still run and report late. Nothing here proves it stopped (compute_stopped stays false until a stop is verified).', '',
@@ -118,7 +129,7 @@ export const COMMANDS = [
118
129
  { name: 'break-usage-backfill', internal: true, summary: 'Backfill usage for a capacity break', usage: 'dalan break-usage-backfill --id N [--log PATH] [--json]' },
119
130
  { name: 'as-init', internal: true, summary: 'Create built-in authorization server files (older form of init)', usage: 'dalan as-init --public-url https://HOST [--json]' },
120
131
  { name: 'as-rotate-keys', summary: 'Rotate the authorization server keys', usage: 'dalan as-rotate-keys [--jwks-only|--cookies-only] [--json] (stop the bridge first)' },
121
- { name: 'prepare-deps', internal: true, summary: 'Prepare dependencies for a source directory', usage: 'dalan prepare-deps SOURCE_DIRECTORY [--json] [--replace-invalid]' },
132
+ { name: 'prepare-deps', internal: true, summary: 'Prepare dependencies for a source directory', usage: 'dalan prepare-deps SOURCE_DIRECTORY [--go|--pnpm] [--json] [--replace-invalid] | dalan prepare-deps --prune [--keep N]' },
122
133
  ];
123
134
 
124
135
  const GROUPS = [['start', 'Getting started'], ['everyday', 'Everyday'], ['operator', 'Operator']];
package/src/cli-name.mjs CHANGED
@@ -10,7 +10,19 @@ const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
10
10
  export function cliCommand(argv1, env = process.env) {
11
11
  const real = p => { try { return fs.realpathSync(p); } catch { return null; } };
12
12
  const self = real(path.resolve(argv1 ?? defaultBin));
13
- const onPath = self && (env.PATH ?? '').split(path.delimiter).some(dir => dir && real(path.join(dir, 'dalan')) === self);
13
+ let firstOnPath = null;
14
+ for (const dir of env.PATH == null ? [] : env.PATH.split(path.delimiter)) {
15
+ const candidate = path.join(dir || '.', 'dalan');
16
+ try {
17
+ if (!fs.statSync(candidate).isFile()) continue;
18
+ fs.accessSync(candidate, fs.constants.X_OK);
19
+ } catch {
20
+ continue;
21
+ }
22
+ firstOnPath = real(candidate);
23
+ if (firstOnPath !== null) break;
24
+ }
25
+ const onPath = self && firstOnPath === self;
14
26
  if (onPath) return env.npm_command === 'exec' ? 'npx @tnunamak/dalan' : 'dalan';
15
27
  return `node ${shellQuote(self ?? path.resolve(argv1 ?? defaultBin))}`;
16
28
  }
@@ -1,13 +1,15 @@
1
1
  import { defaultPath } from './paths.mjs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
- import { assertPrivateDir, untrusted, writeAtomic } from './as-files.mjs';
4
+ import { createHash } from 'node:crypto';
5
+ import { request as httpRequest } from 'node:http';
6
+ import { assertPrivateDir, isLoopbackCallback, untrusted, writeAtomic } from './as-files.mjs';
5
7
  import { normalizeCode, PAIRING_MINUTES } from './as-files.mjs';
6
8
  const WAKE_POLL_SECONDS = 60;
7
9
 
8
10
  // `dalan connect ...`: the owner's side of the built-in authorization server. Every call goes through the owner Unix
9
11
  // socket with the operator key; none of it exists on the public listener.
10
- const USAGE = 'usage: dalan connect add-client --redirect-uri URI [--name NAME] [--json] | clients [--json] | remove-client CLIENT_ID | start --worker NAME [--minutes N] | stop | reset | pending | approve CODE --worker NAME [--confirm-redirect URI] [--replace] | list | revoke NAME | allow-callback PATTERN | signal-token [--worker NAME] [--rotate] [--json]';
12
+ const USAGE = 'usage: dalan connect add-client --redirect-uri URI [--name NAME] [--json] | clients [--json] | remove-client CLIENT_ID | start --worker NAME [--minutes N] | stop | reset | pending | approve CODE --worker NAME [--confirm-redirect URI] [--replace] | complete URL --worker NAME [--replace] [--json] | list | revoke NAME | allow-callback PATTERN | signal-token [--worker NAME] [--rotate] [--json]';
11
13
 
12
14
  // Terminal-safe text: vendor-supplied strings never reach the terminal as raw bytes.
13
15
  const q = value => JSON.stringify(String(value ?? '').replace(/[\p{C}\p{Z}]+/gu, ' ').trim());
@@ -34,7 +36,153 @@ export function formatClients(result) {
34
36
  ].join('\n')).join('\n\n');
35
37
  }
36
38
 
37
- export async function connectCommand(args, { request, operator, option, json }) {
39
+ const fingerprint = value => createHash('sha256').update(value).digest('base64url');
40
+ const redirectStatus = status => [301, 302, 303, 307, 308].includes(status);
41
+ const authorityEndpoint = url => url.origin + url.pathname;
42
+
43
+ // A short-lived, one-issuer in-memory cookie jar. No cookie or operator header is
44
+ // sent with the final local callback. No redirect is followed by the HTTP client.
45
+ function interactionBrowser(issuer, signal) {
46
+ const jar = new Map();
47
+ return async function get(url, phaseSignal = signal) {
48
+ if (url.origin !== issuer.origin || url.username || url.password || url.hash) throw new Error('Bridge sent an unexpected authorization redirect.');
49
+ const now = Date.now();
50
+ const headers = {};
51
+ const cookies = [...jar.values()].filter(c => c.expires > now && (!c.secure || url.protocol === 'https:')
52
+ && (url.pathname === c.path || url.pathname.startsWith(c.path.endsWith('/') ? c.path : c.path + '/')));
53
+ if (cookies.length) headers.cookie = cookies.sort((a, b) => b.path.length - a.path.length).map(c => c.part).join('; ');
54
+ let response;
55
+ try { response = await fetch(url, { headers, signal: phaseSignal, redirect: 'manual' }); }
56
+ catch { throw new Error('Could not load the bridge authorization page.'); }
57
+ const cookieHeaders = response.headers.getSetCookie();
58
+ for (const line of cookieHeaders) {
59
+ const [part, ...attrs] = line.split(';').map(s => s.trim());
60
+ const name = part.slice(0, part.indexOf('='));
61
+ if (!name || !/^[A-Za-z0-9_.-]+$/.test(name) || /[\r\n]/.test(part)) continue;
62
+ const options = new Map(attrs.map(attr => {
63
+ const i = attr.indexOf('=');
64
+ return i < 0 ? [attr.toLowerCase(), true] : [attr.slice(0, i).toLowerCase(), attr.slice(i + 1)];
65
+ }));
66
+ // The authorization server's interaction cookies are host-only.
67
+ if (options.has('domain')) continue;
68
+ const candidate = options.get('path');
69
+ const cookiePath = typeof candidate === 'string' && candidate.startsWith('/') ? candidate : (url.pathname.slice(0, url.pathname.lastIndexOf('/')) || '/');
70
+ const maxAge = options.has('max-age') ? Number(options.get('max-age')) : NaN;
71
+ const expiresAt = options.has('expires') ? Date.parse(options.get('expires')) : NaN;
72
+ const expires = Number.isFinite(maxAge) ? now + maxAge * 1000 : Number.isFinite(expiresAt) ? expiresAt : Infinity;
73
+ const key = name + '\0' + cookiePath;
74
+ if (expires <= now) jar.delete(key);
75
+ else jar.set(key, { part, path: cookiePath, secure: options.has('secure'), expires });
76
+ }
77
+ const location = response.headers.get('location');
78
+ if (response.body) await response.body.cancel().catch(() => {});
79
+ return { status: response.status, location };
80
+ };
81
+ }
82
+
83
+ function nextUrl(response, base) {
84
+ if (!redirectStatus(response.status) || !response.location) return null;
85
+ try {
86
+ const url = new URL(response.location, base);
87
+ return !url.username && !url.password && !url.hash ? url : null;
88
+ } catch { return null; }
89
+ }
90
+
91
+ function isLocalRedirect(raw) {
92
+ if (typeof raw !== 'string' || !/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|\?|$)/i.test(raw)) return false;
93
+ try { return isLoopbackCallback(new URL(raw)); } catch { return false; }
94
+ }
95
+
96
+ function sameLocalCallback(given, expected, original, issuer) {
97
+ // The callback carries code/state/iss, so check the loopback form without its query; the rest must match the approved redirect.
98
+ if (!given || given.username || given.password || given.hash || !isLocalRedirect(given.origin + given.pathname)
99
+ || given.origin !== expected.origin || given.pathname !== expected.pathname) return false;
100
+ if (given.searchParams.getAll('code').length !== 1 || !given.searchParams.get('code')
101
+ || given.searchParams.has('error') || given.searchParams.getAll('state').length > 1
102
+ || given.searchParams.get('state') !== original.searchParams.get('state')
103
+ || (given.searchParams.has('iss') && (given.searchParams.getAll('iss').length !== 1 || given.searchParams.get('iss') !== issuer.href))) return false;
104
+ const params = new URLSearchParams(given.searchParams);
105
+ for (const key of ['code', 'state', 'iss', 'session_state']) params.delete(key);
106
+ return params.toString() === expected.searchParams.toString();
107
+ }
108
+
109
+ function sendLocalCallback(url, signal) {
110
+ // No proxy, cookie, referrer or redirect handling. localhost is resolved only
111
+ // against literal loopback addresses, regardless of machine DNS configuration.
112
+ const loopbacks = [{ address: '127.0.0.1', family: 4 }, { address: '::1', family: 6 }];
113
+ return new Promise((resolve, reject) => {
114
+ const req = httpRequest(url, { agent: false, signal, autoSelectFamily: true,
115
+ lookup(_host, options, done) { if (options.all) done(null, loopbacks); else done(null, loopbacks[0].address, 4); },
116
+ }, response => {
117
+ const ok = response.statusCode >= 200 && response.statusCode < 400;
118
+ response.destroy();
119
+ if (ok) resolve();
120
+ else reject(new Error('The local client did not accept the callback after approval.'));
121
+ });
122
+ req.on('error', () => reject(new Error('Could not deliver the callback to the local client after approval.')));
123
+ req.end();
124
+ });
125
+ }
126
+
127
+ async function completeLocalConnection(input, worker, replace, request, headers, outerSignal) {
128
+ let auth;
129
+ try { auth = new URL(input); } catch { throw new Error('Use this bridge’s exact authorization endpoint URL.'); }
130
+ if (!['http:', 'https:'].includes(auth.protocol) || auth.username || auth.password || auth.hash) throw new Error('Use this bridge’s exact authorization endpoint URL.');
131
+ const owner = async (route, method, body) => {
132
+ try { return await request(route, method, body, headers()); }
133
+ catch { throw new Error('The bridge owner operation was refused. Check the local operator key and pairing window; use --replace only to replace a connection you own.'); }
134
+ };
135
+ const pending = () => owner('/connect/pending', 'GET', null);
136
+ const view = await pending();
137
+ if (view.authorization_endpoint_fingerprint !== fingerprint(authorityEndpoint(auth))) throw new Error('Use this bridge’s exact authorization endpoint URL.');
138
+ if (view.window?.worker !== worker) throw new Error('No pairing window is open for that worker.');
139
+ const redirects = auth.searchParams.getAll('redirect_uri');
140
+ if (redirects.length !== 1 || !isLocalRedirect(redirects[0])) throw new Error('A canonical loopback callback is required.');
141
+ const issuer = new URL(auth.pathname.slice(0, -'/auth'.length), auth.origin);
142
+ const phaseSignal = () => {
143
+ const budget = AbortSignal.timeout(10000);
144
+ return outerSignal ? AbortSignal.any([outerSignal, budget]) : budget;
145
+ };
146
+ const signal = phaseSignal();
147
+ const get = interactionBrowser(issuer, signal);
148
+ const interaction = nextUrl(await get(auth), auth);
149
+ const interactionPrefix = issuer.pathname + '/interaction/';
150
+ if (!interaction || interaction.origin !== issuer.origin || interaction.search || !interaction.pathname.startsWith(interactionPrefix)
151
+ || !/^[A-Za-z0-9_-]{10,64}$/.test(interaction.pathname.slice(interactionPrefix.length))) {
152
+ throw new Error('The bridge did not start an authorization interaction.');
153
+ }
154
+ if ((await get(interaction)).status !== 200) throw new Error('The bridge did not open a pending pairing.');
155
+ const current = await pending();
156
+ if (current.window?.worker !== worker) throw new Error('No pairing window is open for that worker.');
157
+ const uid = interaction.pathname.slice(interactionPrefix.length);
158
+ const matches = current.pending.filter(p => p.interaction_fingerprint === fingerprint(uid));
159
+ const pairing = matches[0];
160
+ if (matches.length !== 1 || pairing.worker !== worker || !pairing.native || pairing.redirect_uri !== redirects[0]) {
161
+ throw new Error('Could not verify the exact loopback pairing for this authorization request.');
162
+ }
163
+ const result = await owner('/connect/approve', 'POST', { worker, replace, code: pairing.code, confirm_redirect: pairing.redirect_uri });
164
+ // Approval committed. Reuse the same interaction and cookies, with a new bounded
165
+ // callback phase. Do not retry the approval if local notification fails.
166
+ const followUp = phaseSignal();
167
+ const expected = new URL(pairing.redirect_uri);
168
+ try {
169
+ let step = interaction;
170
+ for (let hop = 0; hop < 5; hop++) {
171
+ const target = nextUrl(await get(step, followUp), step);
172
+ if (sameLocalCallback(target, expected, auth, issuer)) {
173
+ await sendLocalCallback(target, followUp);
174
+ return { connection_id: result.connection_id };
175
+ }
176
+ if (!target || target.origin !== issuer.origin || !target.pathname.startsWith(issuer.pathname + '/auth/')) break;
177
+ step = target;
178
+ }
179
+ throw new Error('No verified local callback was returned.');
180
+ } catch (cause) {
181
+ throw new Error(`Connection ${q(result.connection_id)} was approved, but the local callback did not complete. Check the connection before retrying.`, { cause });
182
+ }
183
+ }
184
+
185
+ export async function connectCommand(args, { request, operator, option, json, signal }) {
38
186
  const sub = args.shift();
39
187
  const headers = () => ({ 'x-operator-key': operator() });
40
188
  const flags = new Set(['--json', '--replace', '--rotate']);
@@ -82,7 +230,14 @@ export async function connectCommand(args, { request, operator, option, json })
82
230
  case 'pending': {
83
231
  if (positional.length) throw new Error(USAGE);
84
232
  const result = await request('/connect/pending', 'GET', null, headers());
85
- return json ? { result } : { result: formatPending(result), plain: true };
233
+ const publicView = { window: result.window, pending: result.pending.map(({ interaction_fingerprint, ...item }) => item) };
234
+ return json ? { result: publicView } : { result: formatPending(publicView), plain: true };
235
+ }
236
+ case 'complete': {
237
+ if (positional.length !== 1 || !worker || args.filter(arg => arg === '--worker').length !== 1
238
+ || args.some((arg, i) => arg.startsWith('--') && !['--worker', '--replace', '--json'].includes(arg))) throw new Error(USAGE);
239
+ const result = await completeLocalConnection(positional[0], worker, args.includes('--replace'), request, headers, signal);
240
+ return json ? { result } : { result: 'Connected: ' + q(result.connection_id), plain: true };
86
241
  }
87
242
  case 'approve': {
88
243
  if (positional.length !== 1 || !worker) throw new Error(USAGE);
package/src/deadman.mjs CHANGED
@@ -303,11 +303,14 @@ export class Deadman {
303
303
  });
304
304
  }
305
305
 
306
- async close() {
307
- if (this.timer) clearInterval(this.timer);
308
- if (this.server) await new Promise(resolve => this.server.close(resolve));
309
- await this.tickPromise;
310
- this.db.close();
306
+ close() {
307
+ this.closePromise ??= (async () => {
308
+ if (this.timer) clearInterval(this.timer);
309
+ if (this.server) await new Promise(resolve => this.server.close(resolve));
310
+ await this.tickPromise;
311
+ this.db.close();
312
+ })();
313
+ return this.closePromise;
311
314
  }
312
315
  }
313
316