@tnunamak/dalan 0.6.2 → 0.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 (74) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +2 -0
  4. package/README.md +81 -84
  5. package/bin/dalan.mjs +9 -0
  6. package/bin/dot-worker.mjs +29 -4
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +10 -14
  9. package/docs/claude-worker-onboarding.md +9 -8
  10. package/docs/codex-to-muse.md +21 -35
  11. package/docs/connect-chatgpt.md +10 -16
  12. package/docs/dalan-upgrade.md +4 -2
  13. package/docs/local-agent-mcp.md +24 -4
  14. package/docs/local-agent-requester.md +46 -0
  15. package/docs/manual-setup.md +2 -2
  16. package/docs/operations.md +12 -13
  17. package/docs/pull-workers.md +1 -2
  18. package/docs/service-setup.md +110 -163
  19. package/docs/setup-reference.md +6 -6
  20. package/docs/t3-question-relationship.md +43 -0
  21. package/docs/t3-reverse-control.md +12 -8
  22. package/docs/t3-wake-fence-r4.md +42 -0
  23. package/docs/test-suite-isolation.md +204 -0
  24. package/docs/worker-clients.md +6 -4
  25. package/package.json +5 -3
  26. package/qualification/README.md +13 -0
  27. package/qualification/mcp.json +121 -0
  28. package/qualification/protocol-v0.json +127 -0
  29. package/scripts/dalan-try-selfcheck.mjs +8 -7
  30. package/scripts/worker-bridge-setup.mjs +91 -81
  31. package/src/admin-socket.mjs +2 -1
  32. package/src/answer-journal.mjs +200 -0
  33. package/src/as-store.mjs +5 -3
  34. package/src/as.mjs +35 -26
  35. package/src/auth-check.mjs +59 -0
  36. package/src/cli-help.mjs +16 -16
  37. package/src/client-approval.mjs +57 -0
  38. package/src/client-convenience.mjs +166 -0
  39. package/src/client-conveniences.json +106 -0
  40. package/src/client-conveniences.schema.json +97 -0
  41. package/src/connect-cli.mjs +5 -5
  42. package/src/default-home.mjs +36 -0
  43. package/src/destinations/index.mjs +6 -0
  44. package/src/destinations/none.mjs +3 -0
  45. package/src/destinations/t3.mjs +63 -6
  46. package/src/execution.mjs +20 -2
  47. package/src/follow-current.mjs +27 -0
  48. package/src/gozar-routes.mjs +315 -0
  49. package/src/host-budget.mjs +17 -11
  50. package/src/host-execution-policy.mjs +2 -2
  51. package/src/host-stop-reverify.mjs +6 -4
  52. package/src/integrator.mjs +3 -1
  53. package/src/redirect-policy.mjs +61 -0
  54. package/src/route-setting.mjs +71 -12
  55. package/src/server.mjs +64 -12
  56. package/src/service-auto-update.mjs +8 -1
  57. package/src/service-launchd.mjs +186 -0
  58. package/src/service-migrate-workers.mjs +12 -2
  59. package/src/service-update-runtime.mjs +40 -6
  60. package/src/service-update.mjs +20 -14
  61. package/src/service.mjs +211 -63
  62. package/src/setup.mjs +55 -44
  63. package/src/store.mjs +77 -14
  64. package/src/submission-policy.mjs +8 -4
  65. package/src/t3.mjs +21 -2
  66. package/src/tool-registry.mjs +54 -8
  67. package/src/try-exposure.mjs +7 -657
  68. package/src/try-hosted.mjs +71 -101
  69. package/src/try-selfcheck.mjs +15 -8
  70. package/src/try.mjs +9 -13
  71. package/src/workers.mjs +4 -3
  72. package/src/workspace.mjs +94 -15
  73. package/scripts/lib/expose-tailscale.mjs +0 -408
  74. package/src/try-hosted-clients.mjs +0 -46
@@ -0,0 +1,200 @@
1
+ // Requester-side journal for `dalan answer`.
2
+ //
3
+ // The server applies one answer per question and replays a stored receipt for an exact retry of
4
+ // {command_key, expected_revision, text}. A retry that changes the expected revision does not replay: it gets
5
+ // revision_conflict. So the requester must remember the exact envelope it first tried to send, and re-send those
6
+ // bytes, never a refreshed copy. This module saves that envelope before the first send.
7
+ //
8
+ // FROZEN INTERFACE (later PRs, such as the dalan mcp answer tools and the restore check, build on exactly this):
9
+ // prepare(job, questionId, text, deps) -> prepared
10
+ // Validate the input, then resume the saved attempt or save a new one. Same text resumes. Different text
11
+ // throws answer_text_mismatch with no network call. A new attempt reads the revision once (deps.readRevision)
12
+ // and saves {key, expected_revision, text} before anything is sent. Throws invalid_answer for a blank answer,
13
+ // an invalid question ID, or text over 4096 UTF-8 BYTES (the server counts bytes, not characters). It never truncates.
14
+ // send(prepared, deps) -> reply
15
+ // Send the saved envelope (deps.post). A lost reply or timeout re-sends the identical envelope, original key and
16
+ // original expected revision, never a refreshed one. command_conflict, revision_conflict and ALREADY_ANSWERED
17
+ // are settled by reading the question back (deps.readQuestion): equal text is confirmed; anything else throws
18
+ // answer_conflict and the journal is left as it is. Retention or authority loss marks the journal "unknown" and
19
+ // throws answer_state_unknown; nothing is ever prepared again.
20
+ // reconcile(job, questionId, deps) -> {state, ...} (never sends an answer)
21
+ // Settle a saved attempt by reading the server back (deps.readQuestion). state is one of:
22
+ // "none" (no journal) | "committed" | "confirmed" (the server holds our text; the journal is now committed) |
23
+ // "pending" (the server has no answer; the saved envelope can still be sent) |
24
+ // "conflict" (the server holds a different answer) | "unknown" (the server cannot be asked).
25
+ // deps: {receiptsDir, io (fs, injectable for tests), readRevision() -> integer|null, post(envelope) -> reply, readQuestion() -> {answer}|undefined,
26
+ // attempts=3, retryDelayMs=200, sleep}. Only the members a function uses are needed.
27
+ // answerThroughJournal(...) is prepare() then send(), for the CLI.
28
+ //
29
+ // File: <receipts>/<job>.answers/<question>.json, mode 0600, fsync on file and directory.
30
+ // {v:1, job, question_id, key:"answer:<question_id>", text, expected_revision, state}
31
+ // state: "prepared" (envelope saved, outcome not known) | "committed" (the server applied it or holds the same
32
+ // answer) | "unknown" (the server cannot be asked: retention or authority loss).
33
+ import fs from 'node:fs';
34
+ import path from 'node:path';
35
+ import { randomBytes } from 'node:crypto';
36
+
37
+ const JOB_ID = /^[-\w]{8,128}$/;
38
+ const QUESTION_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
39
+ export const MAX_ANSWER_BYTES = 4096;
40
+ const STATES = new Set(['prepared', 'committed', 'unknown']);
41
+ const READBACK = /command_conflict|revision_conflict|ALREADY_ANSWERED/;
42
+ const STATE_LOST = /TOMBSTONE|invalid owner capability|unauthorized|no job ".*" in this bridge home|owner capability/i;
43
+
44
+ export class AnswerJournalError extends Error {
45
+ constructor(code, message, fix = []) { super(message); this.code = code; this.kind = 'local'; this.fix = fix; }
46
+ }
47
+
48
+ // One file name per question ID, injective, with no path separators and no name made only of periods.
49
+ const fileStem = questionId => questionId.replace(/[^A-Za-z0-9_-]/g, ch => `%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`);
50
+ export function journalPath(receiptsDir, job, questionId) {
51
+ return path.join(receiptsDir, `${job}.answers`, `${fileStem(questionId)}.json`);
52
+ }
53
+
54
+ function fsyncDir(dir, io = fs) {
55
+ const fd = io.openSync(dir, 'r');
56
+ try { io.fsyncSync(fd); } finally { io.closeSync(fd); }
57
+ }
58
+ // Write the bytes to a private temp file in the target directory and fsync it. The caller publishes it.
59
+ function stage(file, entry, io = fs) {
60
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
61
+ const fd = io.openSync(tmp, 'wx', 0o600);
62
+ try { io.writeSync(fd, JSON.stringify(entry) + '\n'); io.fsyncSync(fd); } finally { io.closeSync(fd); }
63
+ return tmp;
64
+ }
65
+
66
+ export function readJournal(file, job, questionId) {
67
+ let text;
68
+ try { text = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
69
+ let entry;
70
+ try { entry = JSON.parse(text); } catch { entry = null; }
71
+ const ok = entry && entry.v === 1 && entry.job === job && entry.question_id === questionId && entry.key === `answer:${questionId}`
72
+ && typeof entry.text === 'string' && STATES.has(entry.state)
73
+ && (entry.expected_revision === null || Number.isSafeInteger(entry.expected_revision) && entry.expected_revision >= 0);
74
+ if (!ok) throw new AnswerJournalError('answer_journal_corrupt', `the answer journal ${file} is unreadable. It is the only record of an answer that may already be sent, so it was left as it is`,
75
+ ['read GET /questions with `dalan questions REQUEST_ID` to see whether the question has an answer', 'remove the journal file only after you have checked']);
76
+ return entry;
77
+ }
78
+
79
+ // Create every missing directory level and fsync each new directory and its parent, so that after a crash no
80
+ // level of the path can be missing while the server already holds the answer.
81
+ function mkdirDurable(dir, io) {
82
+ const missing = [];
83
+ for (let d = dir; !io.existsSync(d); d = path.dirname(d)) missing.unshift(d);
84
+ for (const d of missing) {
85
+ try { io.mkdirSync(d, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
86
+ fsyncDir(d, io);
87
+ fsyncDir(path.dirname(d), io);
88
+ }
89
+ }
90
+
91
+ // Publish a new journal with no partial file visible. Returns false if another process published first.
92
+ // On return true, the file, its directory, and every directory level this call created are durable.
93
+ function createJournal(file, entry, io) {
94
+ const dir = path.dirname(file);
95
+ mkdirDurable(dir, io);
96
+ const tmp = stage(file, entry, io);
97
+ try {
98
+ try { io.linkSync(tmp, file); } catch (error) { if (error.code === 'EEXIST') return false; throw error; }
99
+ fsyncDir(dir, io);
100
+ return true;
101
+ } finally { io.rmSync(tmp, { force: true }); }
102
+ }
103
+ function setState(file, entry, state) {
104
+ if (entry.state === state) return;
105
+ entry.state = state;
106
+ const tmp = stage(file, entry);
107
+ fs.renameSync(tmp, file);
108
+ fsyncDir(path.dirname(file));
109
+ }
110
+
111
+ function classify(error) {
112
+ const message = String(error?.message ?? '');
113
+ if (error?.local_code === 'unknown_request' || STATE_LOST.test(message)) return 'unknown';
114
+ if (error?.kind === 'transport' || error?.kind === 'http' && error.http_status >= 500) return 'transport';
115
+ if (error?.kind === 'http' && READBACK.test(message)) return 'readback';
116
+ return 'refused';
117
+ }
118
+
119
+ function checkIds(job, questionId) {
120
+ if (!JOB_ID.test(String(job))) throw new AnswerJournalError('invalid_answer', `invalid request ID ${JSON.stringify(String(job).slice(0, 140))}`);
121
+ if (typeof questionId !== 'string' || !QUESTION_ID.test(questionId)) throw new AnswerJournalError('invalid_answer', 'invalid question_id: use 1 to 128 letters, digits, . _ : or -');
122
+ }
123
+ function checkInput(job, questionId, text) {
124
+ checkIds(job, questionId);
125
+ if (typeof text !== 'string' || !text.trim()) throw new AnswerJournalError('invalid_answer', 'answer text must not be blank');
126
+ const bytes = Buffer.byteLength(text);
127
+ if (bytes > MAX_ANSWER_BYTES) throw new AnswerJournalError('invalid_answer', `answer text is ${bytes} UTF-8 bytes; the limit is ${MAX_ANSWER_BYTES} bytes (not characters). Nothing was sent or saved; shorten the answer, it is never truncated`);
128
+ }
129
+
130
+ const answered = (job, questionId, extra) => ({ request_id: job, question_id: questionId, answered: true, ...extra });
131
+ const unknownError = (job, questionId, file, cause) => new AnswerJournalError('answer_state_unknown',
132
+ `cannot tell whether the answer to ${questionId} on ${job} was applied: ${cause.message}. The saved attempt was kept and nothing new was prepared`,
133
+ ['restore access or retention, then run the same answer command again to resume the saved attempt', `the saved attempt is in ${file}`]);
134
+
135
+ export async function prepare(job, questionId, text, { receiptsDir, readRevision, io = fs }) {
136
+ checkInput(job, questionId, text);
137
+ const file = journalPath(receiptsDir, job, questionId);
138
+ let entry = readJournal(file, job, questionId);
139
+ if (!entry) {
140
+ const expected_revision = await readRevision();
141
+ const fresh = { v: 1, job, question_id: questionId, key: `answer:${questionId}`, text, expected_revision, state: 'prepared' };
142
+ if (createJournal(file, fresh, io)) entry = fresh;
143
+ else { entry = readJournal(file, job, questionId); if (!entry) throw new AnswerJournalError('answer_journal_corrupt', 'answer journal vanished while it was created'); }
144
+ }
145
+ if (entry.text !== text) throw new AnswerJournalError('answer_text_mismatch',
146
+ `question ${questionId} on ${job} already has a saved answer attempt with different text. Nothing was sent. Run the same command with the saved text to finish that attempt`,
147
+ [`the saved attempt is in ${file}`]);
148
+ return { job, questionId, file, entry };
149
+ }
150
+
151
+ // Read the question back and settle the saved attempt. Used by send() after a conflict and by reconcile().
152
+ async function settle(prepared, readQuestion, cause) {
153
+ const { job, questionId, file, entry } = prepared;
154
+ let question;
155
+ try { question = await readQuestion(); } catch (error) {
156
+ if (classify(error) === 'unknown') { setState(file, entry, 'unknown'); throw unknownError(job, questionId, file, error); }
157
+ throw error;
158
+ }
159
+ if (question && question.answer === entry.text) { setState(file, entry, 'committed'); return { state: 'confirmed' }; }
160
+ if (question && typeof question.answer === 'string') return { state: 'conflict', cause };
161
+ return { state: 'pending', cause };
162
+ }
163
+
164
+ export async function send(prepared, { post, readQuestion, attempts = 3, retryDelayMs = 200, sleep = ms => new Promise(r => setTimeout(r, ms)) }) {
165
+ const { job, questionId, file, entry } = prepared;
166
+ if (entry.state === 'committed') return answered(job, questionId, { journal: 'committed' });
167
+ // The envelope is frozen here. A retry sends these exact fields: same key, same expected revision, same text.
168
+ const envelope = { id: job, question_id: questionId, text: entry.text, command_key: entry.key, ...(entry.expected_revision === null ? {} : { expected_revision: entry.expected_revision }) };
169
+ for (let attempt = 1; ; attempt++) {
170
+ try {
171
+ const reply = await post(envelope);
172
+ setState(file, entry, 'committed');
173
+ return reply;
174
+ } catch (error) {
175
+ const kind = classify(error);
176
+ if (kind === 'transport' && attempt < attempts) { await sleep(retryDelayMs * attempt); continue; }
177
+ if (kind === 'transport') throw Object.assign(error, { fix: [`the answer may or may not have been applied; run the same answer command again to re-send the saved attempt (${file})`] });
178
+ if (kind === 'unknown') { setState(file, entry, 'unknown'); throw unknownError(job, questionId, file, error); }
179
+ if (kind !== 'readback') throw error;
180
+ const settled = await settle(prepared, readQuestion, error);
181
+ if (settled.state === 'confirmed') return answered(job, questionId, { confirmed: true });
182
+ const holder = settled.state === 'conflict' ? 'a different answer is already recorded for this question' : 'the server did not apply this answer and its state has moved on';
183
+ throw new AnswerJournalError('answer_conflict', `answer to ${questionId} on ${job} was refused (${error.message}): ${holder}. The saved attempt was left unchanged`, [`the saved attempt is in ${file}`]);
184
+ }
185
+ }
186
+ }
187
+
188
+ export async function reconcile(job, questionId, { receiptsDir, readQuestion }) {
189
+ checkIds(job, questionId);
190
+ const file = journalPath(receiptsDir, job, questionId);
191
+ const entry = readJournal(file, job, questionId);
192
+ if (!entry) return { state: 'none' };
193
+ if (entry.state === 'committed') return { state: 'committed' };
194
+ const settled = await settle({ job, questionId, file, entry }, readQuestion);
195
+ return { state: settled.state };
196
+ }
197
+
198
+ export async function answerThroughJournal({ job, questionId, text, ...deps }) {
199
+ return send(await prepare(job, questionId, text, deps), deps);
200
+ }
package/src/as-store.mjs CHANGED
@@ -390,8 +390,8 @@ export class AsStore {
390
390
  return this.db.prepare("SELECT * FROM pairings WHERE state='pending' AND expires_at>? ORDER BY created_at").all(now).map(row => this.#resource(row));
391
391
  }
392
392
  // Atomic reservation: exactly one approval wins a pending code, and it reserves only that code.
393
- // A web pairing (https redirect to a fixed vendor) is refused while a newer web pairing is pending for the same worker:
394
- // an app that registered again abandons its older attempts, and a re-registration reaches the same vendor.
393
+ // A web pairing (https redirect) is refused while a newer web pairing at the same redirect origin is pending for the same worker:
394
+ // an app that registered again abandons its older attempts, and a re-registration reaches the same origin. Other origins never displace it.
395
395
  // A native pairing (loopback redirect) is never refused for a newer attempt and never displaces another one: its
396
396
  // redirect names no party, so a newer registrant must not take the owner's approval from an older teammate.
397
397
  reserve(code) {
@@ -400,9 +400,11 @@ export class AsStore {
400
400
  const row = this.db.prepare("SELECT rowid AS rid, * FROM pairings WHERE code=? AND state='pending' AND expires_at>?").get(code, now);
401
401
  if (!row) return false;
402
402
  if (!isLoopbackCallback(new URL(row.redirect_uri))) {
403
+ // Only a newer web pairing at the SAME redirect origin displaces this one. A client at another origin cannot starve it.
404
+ const origin = new URL(row.redirect_uri).origin;
403
405
  const newer = this.db.prepare("SELECT redirect_uri FROM pairings WHERE state='pending' AND expires_at>? AND worker=? AND rowid<>? AND (created_at>? OR (created_at=? AND rowid>?))")
404
406
  .all(now, row.worker, row.rid, row.created_at, row.created_at, row.rid);
405
- if (newer.some(p => !isLoopbackCallback(new URL(p.redirect_uri)))) return false;
407
+ if (newer.some(p => !isLoopbackCallback(new URL(p.redirect_uri)) && new URL(p.redirect_uri).origin === origin)) return false;
406
408
  }
407
409
  return this.db.prepare("UPDATE pairings SET state='approving' WHERE code=? AND state='pending'").run(code).changes === 1;
408
410
  });
package/src/as.mjs CHANGED
@@ -7,6 +7,8 @@ import { 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';
10
+ import { matchRegisteredRedirect, validateRedirectUri } from './redirect-policy.mjs';
11
+ import { approvalFacts, approvalRecord, describeClient } from './client-approval.mjs';
10
12
 
11
13
  // The built-in authorization server. The protocol (registration, PKCE, codes, tokens, rotation, revocation) is the maintained
12
14
  // oidc-provider library. This file holds only configuration, the owner-approval policy around it, and the lookup that turns a
@@ -53,17 +55,11 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
53
55
  if (!secure && !allowHttp && !loopback) throw new Error('as: an http public_url needs the explicit test flag');
54
56
  let patterns = config.patterns;
55
57
  if (new URL(resource).origin !== publicUrl.origin) throw new Error('as: resource must live on the public URL');
56
- const callbackAllowed = uri => matchesCallback(patterns, uri);
58
+ // Who may register is decided by the redirect URI's own properties (src/redirect-policy.mjs), never by a list of vendors or a client name.
59
+ // Owner-added patterns from older versions stay valid, so an existing registration keeps working; they only add, never restrict.
60
+ const callbackAllowed = uri => validateRedirectUri(uri).ok || matchesCallback(patterns, uri);
57
61
  // Native registrations ignore only the port; the approved request still binds the full redirect URI.
58
- const registeredRedirectAllowed = (client, redirect) => client?.redirectUris?.some(uri => {
59
- if(uri===redirect)return true;
60
- try {
61
- const requested = parseNativeLoopback(redirect);
62
- const registered = parseNativeLoopback(uri);
63
- return requested.loopback && registered.loopback
64
- && requested.hostname === registered.hostname && requested.pathname === registered.pathname;
65
- } catch { return false; }
66
- });
62
+ const registeredRedirectAllowed = (client, redirect) => matchRegisteredRedirect(client?.redirectUris, redirect);
67
63
 
68
64
  const policy = (ctx, metadata) => {
69
65
  if (Buffer.byteLength(JSON.stringify(metadata)) > 4096 || (metadata.client_name?.length ?? 0) > 128 || (metadata.redirect_uris?.length ?? 0) > 8 || metadata.redirect_uris?.some(uri => uri.length > 512)) throw new errors.InvalidClientMetadata('client metadata exceeds the size limit');
@@ -71,7 +67,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
71
67
  for (const uri of metadata.redirect_uris) {
72
68
  if (!callbackAllowed(uri)) {
73
69
  log({ kind: 'as_registration_refused' });
74
- throw new errors.InvalidClientMetadata('redirect_uris must each match an allowed vendor callback (dalan connect allow-callback)');
70
+ throw new errors.InvalidClientMetadata('redirect_uris must each be a plain https URL or a native loopback URL (http://127.0.0.1, http://[::1] or http://localhost)');
75
71
  }
76
72
  }
77
73
  const nativeRedirects = metadata.redirect_uris.map(uri => isLoopbackCallback(new URL(uri)));
@@ -349,7 +345,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
349
345
  const scopes = requestedScopes(details.params.scope);
350
346
  const redirect = details.params.redirect_uri;
351
347
  if (!scopes.some(s => ACCEPTED_SCOPES.includes(s))) return page(res, 400, 'No usable scope', '<p>The app asked for no scope that this bridge offers.</p>');
352
- if (!client || !registeredRedirectAllowed(client, redirect) || !callbackAllowed(redirect)) return page(res, 400, 'Callback not allowed', '<p>The app\'s callback address is not on this bridge\'s allowed list.</p>');
348
+ if (!client || !registeredRedirectAllowed(client, redirect) || !callbackAllowed(redirect)) return page(res, 400, 'Callback not allowed', '<p>The app\'s callback address is not an address this bridge accepts (a plain https URL, or a native loopback URL registered by the app).</p>');
353
349
  if (details.params.resource !== resource) return page(res, 400, 'Wrong resource', '<p>The app did not ask for this bridge\'s resource.</p>');
354
350
  try {
355
351
  pairing = store.pairingFor(uid, { client_id: client.clientId, client_name: untrusted(client.clientName), redirect_uri: redirect, resource, scopes: scopes.join(' '), interaction_expires_at: details.exp * 1000 }, window);
@@ -361,7 +357,9 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
361
357
  if (!window || window.worker !== pairing.worker) return page(res, 403, 'Not accepting connections', '<p>This bridge is not accepting new connections right now.</p>');
362
358
  const code = showCode(pairing.code);
363
359
  const native = isLoopbackCallback(new URL(pairing.redirect_uri));
364
- page(res, 200, 'Connect to Dalan', `<p>Pairing code</p><p class="code">${html(code)}</p><p>Run approval on the bridge computer:</p><pre>dalan connect approve ${html(code)} --worker ${html(pairing.worker)}</pre>${native ? '<p>Native client, identity not verified: host and name prove nothing. The owner must compare this code with the teammate\'s browser page over a trusted channel. The redirect confirmation is only a typo check, not proof of identity.</p>' : ''}<p>This page waits. It checks again every few seconds.</p>`, { refresh: 3 });
360
+ const facts = approvalFacts(describeClient({ name: pairing.client_name, clientId: pairing.client_id, redirectUri: pairing.redirect_uri, worker: pairing.worker, issuer: shownIssuer, resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), code }));
361
+ const factList = `<dl>${facts.map(([label, value]) => `<dt>${html(label)}</dt><dd>${html(value)}</dd>`).join('')}</dl>`;
362
+ page(res, 200, 'Connect to Dalan', `<p>Pairing code</p><p class="code">${html(code)}</p>${factList}<p>Run approval on the bridge computer:</p><pre>dalan connect approve ${html(code)} --worker ${html(pairing.worker)}</pre>${native ? '<p>Native client, identity not verified: host and name prove nothing. The owner must compare this code with the teammate\'s browser page over a trusted channel. The redirect confirmation is only a typo check, not proof of identity.</p>' : '<p>The client name and redirect above are set by the app and are not verified. The owner approves only the code that matches this page.</p>'}<p>This page waits. It checks again every few seconds.</p>`, { refresh: 3 });
365
363
  }
366
364
  async function complete(req, res, details, pairing, client) {
367
365
  const connection = store.connectionByGrant(pairing.grant_id);
@@ -379,24 +377,34 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
379
377
 
380
378
  // ---- owner operations (called from the owner Unix socket only) -------------------------------------------------
381
379
  // Some web apps register multiple clients during one connection flow, so an older pending web code for the same worker
382
- // may no longer finish its token exchange. Those older codes stay visible, marked superseded by the newest web one.
380
+ // may no longer finish its token exchange. Those older codes stay visible, marked superseded by the newest web one at the same redirect origin.
383
381
  // Native (loopback) pairings are never superseded: each is approved by its own code only.
384
382
  const supersede = views => {
385
- const newest = views.filter(view => !view.native).at(-1);
386
- return views.map(view => view.native || view === newest ? view : { ...view, superseded: true, superseded_by: newest.code });
383
+ const newestByOrigin = new Map();
384
+ for (const view of views) if (!view.native) newestByOrigin.set(new URL(view.redirect_uri).origin, view);
385
+ return views.map(view => {
386
+ const newest = view.native ? null : newestByOrigin.get(new URL(view.redirect_uri).origin);
387
+ return !newest || view === newest ? view : { ...view, superseded: true, superseded_by: newest.code };
388
+ });
387
389
  };
390
+
388
391
  // The owner CLI never prints the bridge path secret (approve output checks this), so show the resource's origin and shape only.
389
392
  const shownResource = resource => `${new URL(resource).origin}/<secret>/mcp`;
390
- const pendingView = pairing => ({
391
- code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
392
- native: isLoopbackCallback(new URL(pairing.redirect_uri)),
393
- redirect_uri: pairing.redirect_uri, resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
394
- expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
395
- });
393
+ const shownIssuer = `${publicUrl.origin}/<secret>/oauth`; // the issuer carries the secret path prefix too
394
+ const pendingView = pairing => {
395
+ const shown = describeClient({ name: pairing.client_name, clientId: pairing.client_id, redirectUri: pairing.redirect_uri, worker: pairing.worker, issuer: shownIssuer, resource: '', scopes: [] });
396
+ return {
397
+ code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
398
+ native: isLoopbackCallback(new URL(pairing.redirect_uri)),
399
+ 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
+ resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
401
+ expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
402
+ };
403
+ };
396
404
  const known = worker => typeof worker === 'string' && workerNames().includes(worker);
397
405
  const ops = {
398
406
  addClient({ redirectUri, name } = {}) {
399
- if (!callbackAllowed(redirectUri)) throw new Error('redirect_uri must match an allowed vendor callback');
407
+ if (!callbackAllowed(redirectUri)) throw new Error('redirect_uri must be a plain https URL or a native loopback URL');
400
408
  if (name !== undefined && (typeof name !== 'string' || name.length > 100 || !untrusted(name, 80))) throw new Error('name must be a non-empty string of at most 100 characters');
401
409
  const metadata = {
402
410
  client_id: randomUUID(), redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
@@ -409,7 +417,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
409
417
  delete persisted.client_secret_expires_at;
410
418
  const createdAt = store.addStaticClient(client.clientId, persisted);
411
419
  log({ kind: 'static_client_added', client_id: client.clientId });
412
- return { client_id: client.clientId, created_at: new Date(createdAt).toISOString() };
420
+ return { client_id: client.clientId, token_endpoint_auth_method: 'none', redirect_uris: [redirectUri], created_at: new Date(createdAt).toISOString() };
413
421
  },
414
422
  clients() {
415
423
  return { clients: store.clientRows().map(({ client_id, metadata, created_at, is_static }) => ({
@@ -472,7 +480,8 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
472
480
  const { connection_id, replaced } = store.commitApproval({ code: pairing.code, worker, grantId, snapshot: pairing, replace });
473
481
  if (replaced) store.revokeGrant(replaced.grant_id, 'replaced');
474
482
  log({ kind: 'connection_approved', connection_id, worker, client_id: pairing.client_id, replaced: !!replaced });
475
- return { approved: true, connection_id, worker, grant_id: grantId, client_id: pairing.client_id, redirect_uri: pairing.redirect_uri, scopes: pairing.scopes.split(' '), replaced: replaced?.connection_id ?? null };
483
+ const approval = approvalRecord({ worker, issuer: shownIssuer, resource: shownResource(pairing.resource), clientId: pairing.client_id, redirectUri: pairing.redirect_uri, scopes: pairing.scopes.split(' '), approvedAt: now(), connectionId: connection_id });
484
+ return { approved: true, connection_id, worker, grant_id: grantId, client_id: pairing.client_id, redirect_uri: pairing.redirect_uri, redirect_origin: approval.redirectOrigin, approval, scopes: pairing.scopes.split(' '), replaced: replaced?.connection_id ?? null };
476
485
  } catch (error) {
477
486
  store.failPairing(pairing.code);
478
487
  if (grantId) { try { store.revokeGrant(grantId, 'approval_failed'); } catch { /* the grant has no connection row; deleting its rows is enough */ } }
@@ -482,7 +491,7 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
482
491
  list() {
483
492
  const window = store.window();
484
493
  return { window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, callbacks: patterns.map(p => p.pattern),
485
- connections: store.connections().map(c => ({ connection_id: c.connection_id, worker: c.worker, client_id: c.client_id, redirect_uri: c.redirect_uri, scopes: c.scopes.split(' '), created_at: new Date(c.created_at).toISOString(), revoked_at: c.revoked_at === null ? null : new Date(c.revoked_at).toISOString(), revoked_reason: c.revoked_reason })) };
494
+ connections: store.connections().map(c => ({ connection_id: c.connection_id, worker: c.worker, client_id: c.client_id, redirect_uri: c.redirect_uri, redirect_origin: validateRedirectUri(c.redirect_uri).origin ?? null, scopes: c.scopes.split(' '), created_at: new Date(c.created_at).toISOString(), revoked_at: c.revoked_at === null ? null : new Date(c.revoked_at).toISOString(), revoked_reason: c.revoked_reason })) };
486
495
  },
487
496
  revoke({ worker }) {
488
497
  if (!known(worker)) throw new Error('unknown worker');
@@ -0,0 +1,59 @@
1
+ // `dalan doctor --auth`: a real OAuth client walk against the PUBLIC MCP URL of this home's bridge. The walk itself is
2
+ // runSelfCheck; here the owner's approval is done through the owner admin socket, and the one connection it creates is
3
+ // revoked when the walk ends. A worker that already has a connection is never touched: approving would replace it.
4
+ // No token, pairing code, secret path or full URL is written to any output.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { runSelfCheck } from './try-selfcheck.mjs';
8
+
9
+ const fail = (name, detail) => ({ ok: false, results: [{ name, status: 'FAIL', detail }] });
10
+
11
+ export async function runAuthCheck({ home, workers, worker, request, operator, fetchImpl = fetch, say = () => {}, approveWaitMs = 30_000 }) {
12
+ let url;
13
+ try { url = fs.readFileSync(path.join(home, 'resource-url'), 'utf8').trim(); } catch { url = ''; }
14
+ if (!url) {
15
+ const detail = `no resource-url file in ${home}: this home has no public MCP URL to check (run dalan setup or dalan try first)`;
16
+ say(`FAIL input: ${detail}`); say('RESULT FAIL');
17
+ return fail('input', detail);
18
+ }
19
+ const names = [...workers];
20
+ if (worker && !names.includes(worker)) { const detail = `unknown worker; configured workers: ${names.join(', ') || 'none'}`; say(`FAIL input: ${detail}`); say('RESULT FAIL'); return fail('input', detail); }
21
+ if (!worker) {
22
+ if (names.length !== 1) { const detail = names.length ? `${names.length} workers are configured (${names.join(', ')}); choose one with --worker NAME` : 'no worker is configured'; say(`FAIL input: ${detail}`); say('RESULT FAIL'); return fail('input', detail); }
23
+ worker = names[0];
24
+ }
25
+ const headers = () => ({ 'x-operator-key': operator() });
26
+ let listing;
27
+ try { listing = await request('/connect/list', 'GET', null, headers()); }
28
+ catch (error) { const detail = `cannot ask the bridge about connections: ${String(error?.message ?? error).split('\n')[0].slice(0, 160)}`; say(`FAIL bridge: ${detail}`); say('RESULT FAIL'); return fail('bridge', detail); }
29
+ const existing = (listing.connections ?? []).some(c => c.worker === worker && c.revoked_at === null);
30
+ if (existing) {
31
+ const partial = await runSelfCheck({ url, fetchImpl, say, discoveryOnly: true });
32
+ const detail = `worker ${worker} already has a connection (it would be replaced)`;
33
+ say(`SKIP full walk: ${detail}`);
34
+ return { ok: false, partial: true, results: [...partial.results, { name: 'full walk', status: 'SKIP', detail }] };
35
+ }
36
+ // Registration needs an open pairing window, so the window opens first. A window that is already open is never taken
37
+ // over, not even one for this worker: its owner may be pairing a client right now. Doctor only reports it.
38
+ if (listing.window) {
39
+ const detail = listing.window.worker === worker
40
+ ? `your own pairing window is already open (worker ${worker}); doctor cannot check sign-in while it is open. Finish pairing the client, then run doctor again; or run dalan connect stop, then run doctor again`
41
+ : `a pairing window is already open (worker ${listing.window.worker}); finish it or run dalan connect stop, then retry`;
42
+ say(`FAIL input: ${detail}`); say('RESULT FAIL'); return fail('input', detail);
43
+ }
44
+ let approved = false;
45
+ const approve = async ({ code }) => {
46
+ try { await request('/connect/approve', 'POST', { code, worker, replace: false }, headers()); approved = true; }
47
+ catch (error) { throw new Error(`the owner approval was refused: ${String(error?.message ?? error).split('\n')[0].replaceAll(code, '[code]').slice(0, 120)}`); }
48
+ };
49
+ let outcome, cleanupFailed = false;
50
+ try { await request('/connect/start', 'POST', { worker }, headers()); }
51
+ catch (error) { const detail = `cannot open the pairing window: ${String(error?.message ?? error).split('\n')[0].slice(0, 120)}`; say(`FAIL bridge: ${detail}`); say('RESULT FAIL'); return fail('bridge', detail); }
52
+ try { outcome = await runSelfCheck({ url, fetchImpl, say, approve, approveWaitMs }); }
53
+ finally {
54
+ // Leave the worker as it was: this walk's one connection goes, and a window it opened closes.
55
+ if (approved) { try { await request('/connect/revoke', 'POST', { worker }, headers()); say(`cleanup: the self-check connection for worker ${worker} was revoked`); } catch { cleanupFailed = true; say('FAIL cleanup: the self-check connection could not be revoked; run: dalan connect revoke ' + worker); } }
56
+ try { await request('/connect/stop', 'POST', {}, headers()); } catch { /* the window expires by itself */ }
57
+ }
58
+ return cleanupFailed ? { ok: false, results: [...outcome.results, { name: 'cleanup', status: 'FAIL', detail: `the self-check connection for worker ${worker} was not revoked` }] } : outcome;
59
+ }
package/src/cli-help.mjs CHANGED
@@ -6,27 +6,27 @@ 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: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--client chatgpt|claude] [--route auto|gozar|localhost.run|tailscale]] [--home DIR] [--port N] [--callback PATTERN]...',
10
- detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client such as ChatGPT or claude.ai (the default). `auto` honors a saved temporary-relay choice; otherwise it uses a usable Tailscale route and selects Gozar if no Tailscale route is usable. When it selects Gozar, Dalan names tunnl.gg, links its terms and privacy notice, and asks for consent before exposure. After consent, bundled Gozar creates an installation-owned key and opens the temporary demo link through tunnl.gg. Dalan never uses your SSH keys. The relay ends TLS and can see the connector URL and traffic; the link can stop or change without warning, including within minutes.',
11
- 'Dalan checks the original public address and ends the trial when it detects a change or route loss. The trial itself ends after 3 hours at most. Ctrl-C stops the run; Dalan closes its forwarding gate and attempts to remove its route. If cleanup cannot be confirmed, it reports this and prints a recovery command. Keep private work out of the demo. A Tailscale route is separate from the temporary relay. Choose this computer only, or pass --local, for a',
12
- 'self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
13
- 'Options:', ' --local this computer only', ' --public public trial with the chatgpt or claude sign-in profile (other clients: see Connect any MCP worker in the README)', ' --client NAME chatgpt (default) or claude; implies --public',
14
- '', 'When `auto` selects Gozar because a temporary-relay choice was saved or Tailscale is unavailable, Gozar supplies the tunnl.gg key-bound relay; Dalan keeps OAuth sign-in and identity checks. After consent, Gozar creates a private key for this installation. Dalan does not use your SSH keys. Gozar is bundled; no separate install is needed.',
15
- ' --route NAME auto (saved temporary-relay choice, otherwise usable Tailscale, then bundled Gozar with relay consent), gozar, localhost.run or tailscale; implies --public', ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
9
+ { 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]...',
10
+ detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client (the default) or this computer only. For a hosted client, Dalan asks Gozar for a public HTTPS route, shows what Gozar says about it (who can read the traffic, whether the address is stable, what it costs), and asks for consent before anything is exposed.',
11
+ 'Dalan checks the original public address and ends the trial when it detects a change or route loss. A temporary route lasts for the trial, 3 hours at most; Ctrl-C stops the run and Dalan asks Gozar to remove the route. If cleanup cannot be confirmed, it reports this. A route you saved with `dalan setup` is durable: ending the run never removes it. Keep private work out of a temporary demo.',
12
+ 'Choose this computer only, or pass --local, for a self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
13
+ 'Options:', ' --local this computer only', ' --public public trial through a Gozar route', ' --route NAME use the Gozar route with this name (Gozar decides what the name means); implies --public',
14
+ ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
16
15
  ' --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', '',
17
- '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 public trial creates a new home, and a usable Tailscale route on this computer uses ~/.local/share/dalan-hosted-<client>. 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')}`] },
18
- { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
19
- detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
20
- 'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
16
+ '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')}`] },
17
+ { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup [--route NAME]',
18
+ 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.',
19
+ 'With --route NAME, asks Gozar for the route with that name. Afterwards `dalan try --public` uses the saved route.', '', 'Example: dalan setup'] },
21
20
  { 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]',
22
- detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
23
- 'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]',
21
+ detail: ['Install the bridge as a background service that starts on its own, and publish it through a Gozar route.', '',
22
+ 'Install: dalan service install --worker NAME --route NAME [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update] [--write-units-only]',
23
+ '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].',
24
24
  'New installs enable a daily update timer with up to one hour of jitter. Existing preferences are preserved.',
25
25
  'Update: dalan service update [--check|--yes] [--retry] [--home DIR] [--json]. --check only reports availability. --retry tries a release again after a rollback.',
26
26
  'Updates install side by side, check every worker catalog, then restart and health-check the bridge. Failures attempt to restore the previous install and saved state; a failed rollback is reported.',
27
27
  'Changed tool descriptors stage without switching. Refresh the hosted connectors when you explicitly switch with --yes. The timer never supplies --yes.',
28
28
  'Automatic updates: dalan service auto-update on|off [--home DIR]. Status: dalan service status [--home DIR] [--json] shows the last result.',
29
- 'Service installation and update timers require Linux systemd; launchd is not supported by this command.',
29
+ 'On macOS the service and its update timer are launchd agents that run while you are logged in. On Linux they are systemd user units.',
30
30
  'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
31
31
  'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
32
32
  'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
@@ -79,8 +79,8 @@ export const COMMANDS = [
79
79
  detail: ['Subcommands:', ' allow NAME OWNER/REPO let a worker use a repository', ' deny NAME OWNER/REPO stop a worker using it', ' list [NAME] show each worker\'s repository access', ' migrate-repos convert an old repository policy; stop the service first'] },
80
80
  { name: 'tool', group: 'operator', summary: 'Register tools and choose which workers may call them', usage: 'dalan tool add --file PATH | remove NAME | list | grant NAME WORKER | revoke NAME WORKER [--json]',
81
81
  detail: ['Manages the owner-side tool registry. A worker sees and calls only the tools granted to it. Changing the registry never changes the advertised MCP tool list.', '', 'Subcommands:', ' add --file PATH register a tool from a JSON file: name, description, class (read|write), inputSchema, handler', ' remove NAME remove a tool and its grants', ' list show tools, classes, schema hashes and granted workers', ' grant NAME WORKER let a worker call a tool', ' revoke NAME WORKER stop a worker calling a tool'] },
82
- { name: 'doctor', group: 'operator', summary: 'Check the host setup', usage: 'dalan doctor [--checks] [--json]',
83
- detail: ['Reports whether this host can run jobs.', '', 'Options:', ' --checks lint the owner\'s checks.json instead (local only)', ' --json print JSON'] },
82
+ { name: 'doctor', group: 'operator', summary: 'Check the host setup', usage: 'dalan doctor [--checks | --auth [--worker NAME]] [--json]',
83
+ detail: ['Reports whether this host can run jobs.', '', 'Options:', ' --checks lint the owner\'s checks.json instead (local only)', ' --auth walk the public MCP URL as an OAuth client: challenge, discovery, sign-in, token, tools. Needs a running bridge and a resource-url file in this home.', ' It approves one pairing for the worker through the owner socket and revokes it after. A worker that already has a connection is not touched: only the steps that need no approval run (exit 2).', ' --worker the worker to walk with --auth (required when several are configured)', ' --json print JSON'] },
84
84
  { name: 'paths', group: 'operator', summary: 'Print where Dalan keeps its files', usage: 'dalan paths [--json | --workspace-root | --config-root | --data-root | --state-root]' },
85
85
  { name: 'pause', group: 'operator', summary: 'Stop handing out new jobs', usage: 'dalan pause --reason TEXT' },
86
86
  { name: 'resume', group: 'operator', summary: 'Resume handing out jobs', usage: 'dalan resume' },
@@ -0,0 +1,57 @@
1
+ // What the owner sees, and what is recorded, when a client asks to connect. Everything the client supplied (name, client ID,
2
+ // redirect) is shown as untrusted text: no control, format or separator characters, bounded length, and always labelled.
3
+ // Nothing here makes a trust decision. The name never selects a grant; only the owner's approval of one code does.
4
+ import { untrusted } from './as-files.mjs';
5
+ import { validateRedirectUri } from './redirect-policy.mjs';
6
+ import { displayFor } from './client-convenience.mjs';
7
+
8
+ const OWNER_ID = 'owner';
9
+
10
+ // A display model from one pairing. `resource` must already be the shortened form that hides the secret path.
11
+ export function describeClient({ name, clientId, redirectUri, worker, issuer, resource, scopes, code }) {
12
+ const policy = validateRedirectUri(redirectUri);
13
+ // Display only: a curated label for an exact, already validated HTTPS origin. It never feeds an approval decision.
14
+ const known = policy.ok ? displayFor(policy.uri) : null;
15
+ return {
16
+ code,
17
+ worker: untrusted(worker, 64),
18
+ client_name: untrusted(name, 80),
19
+ client_name_untrusted: true,
20
+ client_id: untrusted(clientId, 128),
21
+ redirect_uri: policy.ok ? policy.uri : untrusted(redirectUri, 512),
22
+ redirect_host: policy.ok ? policy.host : null,
23
+ redirect_origin: policy.ok ? policy.origin : null,
24
+ redirect_kind: policy.ok ? policy.kind : null,
25
+ redirect_punycode: policy.ok ? policy.punycode : false,
26
+ known_client: known ? untrusted(known.name, 80) : null,
27
+ issuer: untrusted(issuer, 256),
28
+ resource: untrusted(resource, 256),
29
+ scopes: [...scopes].map(scope => untrusted(scope, 64)),
30
+ };
31
+ }
32
+
33
+ // Plain-text lines for the browser page (the caller escapes them for HTML).
34
+ export function approvalFacts(view) {
35
+ return [
36
+ ['Client name (set by the app, not verified)', view.client_name || '(none)'],
37
+ ...(view.known_client ? [['Known client (matched by redirect origin; a label only, not proof)', view.known_client]] : []),
38
+ ['Redirect host', view.redirect_host ?? '(invalid)'],
39
+ ['Full redirect', view.redirect_uri],
40
+ ['Client ID', view.client_id],
41
+ ['Worker', view.worker],
42
+ ['Issuer', view.issuer],
43
+ ['Resource', view.resource],
44
+ ['Scopes', view.scopes.join(' ')],
45
+ ...(view.redirect_punycode ? [['Note', 'The host contains punycode (xn--). It may look like another name when decoded.']] : []),
46
+ ];
47
+ }
48
+
49
+ // The record of one approval. The origin groups review and revocation only; it grants nothing to another client, path or port.
50
+ export function approvalRecord({ worker, issuer, resource, clientId, redirectUri, scopes, approvedAt, connectionId }) {
51
+ const policy = validateRedirectUri(redirectUri);
52
+ return {
53
+ ownerId: OWNER_ID, worker, issuer, resource, clientId,
54
+ redirectOrigin: policy.ok ? policy.origin : null, redirectUri, scopes: [...scopes],
55
+ approvedAt: new Date(approvedAt).toISOString(), connectionId,
56
+ };
57
+ }