@tnunamak/dalan 0.0.0-stage → 0.5.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 (182) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +339 -0
  5. package/README.md +348 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +38 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +755 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/connect-chatgpt.md +78 -0
  17. package/docs/connection-longevity.md +37 -0
  18. package/docs/dalan-upgrade.md +242 -0
  19. package/docs/deadman.md +59 -0
  20. package/docs/dot-pr-reviewer.config.example.json +9 -0
  21. package/docs/durability-audit.md +27 -0
  22. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  23. package/docs/keycloak-oauth-setup.md +30 -0
  24. package/docs/local-agent-mcp.md +39 -0
  25. package/docs/manual-setup.md +135 -0
  26. package/docs/mirror-fetch.md +98 -0
  27. package/docs/operations.md +751 -0
  28. package/docs/operator-duties.md +68 -0
  29. package/docs/owner-integrator.md +27 -0
  30. package/docs/portable-auth-profile.md +109 -0
  31. package/docs/pr-head-reviewer.md +54 -0
  32. package/docs/pr-preflight.md +26 -0
  33. package/docs/pull-workers.md +97 -0
  34. package/docs/redaction.md +27 -0
  35. package/docs/service-setup.md +166 -0
  36. package/docs/setup-reference.md +80 -0
  37. package/docs/t3-connector-icon.png +0 -0
  38. package/docs/t3-integration.md +49 -0
  39. package/docs/t3-result-retry-delivery.md +41 -0
  40. package/docs/t3-reverse-control.md +107 -0
  41. package/docs/usage.md +439 -0
  42. package/docs/worker-clients.md +285 -0
  43. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  44. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  45. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  46. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  47. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  48. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  49. package/package.json +65 -4
  50. package/packages/job-core/README.md +18 -0
  51. package/packages/job-core/index.mjs +2 -0
  52. package/packages/job-core/package.json +8 -0
  53. package/packages/job-core/protocol/canonical.mjs +11 -0
  54. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  55. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  56. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  57. package/packages/job-core/transitions.mjs +25 -0
  58. package/scripts/daily-selfcheck.mjs +135 -0
  59. package/scripts/lib/expose-tailscale.mjs +408 -0
  60. package/scripts/live-trial/common.mjs +272 -0
  61. package/scripts/monitor-targets.mjs +44 -0
  62. package/scripts/upgrade-drain.mjs +39 -0
  63. package/scripts/worker-bridge-setup.mjs +925 -0
  64. package/src/ack-ledger.mjs +37 -0
  65. package/src/acp-bridge.mjs +412 -0
  66. package/src/acp-context.mjs +138 -0
  67. package/src/admin-socket.mjs +14 -0
  68. package/src/alerts.mjs +147 -0
  69. package/src/artifact-journal.mjs +75 -0
  70. package/src/as-files.mjs +347 -0
  71. package/src/as-store.mjs +456 -0
  72. package/src/as.mjs +497 -0
  73. package/src/auth.mjs +166 -0
  74. package/src/builtin-http.mjs +22 -0
  75. package/src/check-coverage.mjs +38 -0
  76. package/src/check-lint.mjs +88 -0
  77. package/src/check-readiness.mjs +112 -0
  78. package/src/check-response.mjs +19 -0
  79. package/src/claim-command-ledger.mjs +51 -0
  80. package/src/cli-help.mjs +172 -0
  81. package/src/cli-name.mjs +16 -0
  82. package/src/connect-cli.mjs +126 -0
  83. package/src/consumers.mjs +61 -0
  84. package/src/deadman.mjs +329 -0
  85. package/src/delivery.mjs +19 -0
  86. package/src/demo-worker.mjs +150 -0
  87. package/src/destinations/index.mjs +23 -0
  88. package/src/destinations/none.mjs +15 -0
  89. package/src/destinations/t3.mjs +109 -0
  90. package/src/diagnostic.mjs +78 -0
  91. package/src/docs-url.mjs +9 -0
  92. package/src/drain-runner.mjs +9 -0
  93. package/src/drained-slot.mjs +53 -0
  94. package/src/drained.mjs +40 -0
  95. package/src/durable-waiters.mjs +236 -0
  96. package/src/env.mjs +19 -0
  97. package/src/execution.mjs +112 -0
  98. package/src/failure-type.mjs +28 -0
  99. package/src/get-summary.mjs +32 -0
  100. package/src/git-env.mjs +15 -0
  101. package/src/host-budget-receipts.mjs +154 -0
  102. package/src/host-budget-seccomp.py +33 -0
  103. package/src/host-budget-service.mjs +54 -0
  104. package/src/host-budget-stop.mjs +26 -0
  105. package/src/host-budget-storage.py +259 -0
  106. package/src/host-budget.mjs +149 -0
  107. package/src/host-cgroup.mjs +23 -0
  108. package/src/host-check-allowlist.mjs +42 -0
  109. package/src/host-execution-policy.mjs +38 -0
  110. package/src/host-health.mjs +34 -0
  111. package/src/host-stop-reverify.mjs +44 -0
  112. package/src/inbox.mjs +55 -0
  113. package/src/integrator.mjs +322 -0
  114. package/src/job-retention.mjs +69 -0
  115. package/src/legacy-names.mjs +8 -0
  116. package/src/lifecycle.mjs +291 -0
  117. package/src/limits.mjs +31 -0
  118. package/src/loopback.mjs +9 -0
  119. package/src/mcp-outcome.mjs +70 -0
  120. package/src/mcp-stdio.mjs +191 -0
  121. package/src/mirror-fetch-lock.py +164 -0
  122. package/src/mirror-fetch.mjs +174 -0
  123. package/src/notify-ledger.mjs +82 -0
  124. package/src/objectives.mjs +129 -0
  125. package/src/owner-report-artifact.mjs +66 -0
  126. package/src/patch-apply.mjs +84 -0
  127. package/src/path-syntax.mjs +16 -0
  128. package/src/paths.mjs +67 -0
  129. package/src/pr-head-reviewer.mjs +596 -0
  130. package/src/pr-preflight.mjs +51 -0
  131. package/src/prepared-node-modules.mjs +129 -0
  132. package/src/projects.mjs +480 -0
  133. package/src/protocol-artifact-commands.mjs +52 -0
  134. package/src/protocol-delivery-driver.mjs +167 -0
  135. package/src/protocol-finish.mjs +100 -0
  136. package/src/protocol-owner-command.mjs +35 -0
  137. package/src/protocol-owner-mutations.mjs +22 -0
  138. package/src/protocol-owner-waiters.mjs +67 -0
  139. package/src/protocol-retention.mjs +52 -0
  140. package/src/protocol-services.mjs +61 -0
  141. package/src/protocol-stop-observer.mjs +131 -0
  142. package/src/publish-plan.mjs +245 -0
  143. package/src/redaction.mjs +763 -0
  144. package/src/rejections.mjs +18 -0
  145. package/src/request-log.mjs +102 -0
  146. package/src/restore-check.mjs +90 -0
  147. package/src/result-binding.mjs +65 -0
  148. package/src/runtime-check.mjs +13 -0
  149. package/src/sandbox-supervisor.mjs +105 -0
  150. package/src/schema-subset.mjs +186 -0
  151. package/src/scopes.mjs +15 -0
  152. package/src/server.mjs +1340 -0
  153. package/src/shutdown-signal.mjs +12 -0
  154. package/src/signal-sandbox-processes.py +56 -0
  155. package/src/signal.mjs +119 -0
  156. package/src/status-evidence.mjs +47 -0
  157. package/src/status-summary.mjs +54 -0
  158. package/src/store.mjs +3057 -0
  159. package/src/submission-policy.mjs +623 -0
  160. package/src/subscription-storage.mjs +64 -0
  161. package/src/t3-audit.mjs +120 -0
  162. package/src/t3-control.mjs +102 -0
  163. package/src/t3-transport.mjs +158 -0
  164. package/src/t3.mjs +209 -0
  165. package/src/terminal-safe.mjs +19 -0
  166. package/src/tool-registry.mjs +451 -0
  167. package/src/try-command.mjs +11 -0
  168. package/src/try.mjs +589 -0
  169. package/src/webhooks.mjs +86 -0
  170. package/src/work-order.mjs +265 -0
  171. package/src/worker-instructions.mjs +26 -0
  172. package/src/worker-prompt.mjs +4 -0
  173. package/src/workers.mjs +622 -0
  174. package/src/workspace.mjs +1058 -0
  175. package/systemd/dot-bridge-heartbeat.service +18 -0
  176. package/systemd/dot-bridge-heartbeat.timer +10 -0
  177. package/systemd/dot-bridge-selfcheck.service +12 -0
  178. package/systemd/dot-bridge-selfcheck.timer +11 -0
  179. package/systemd/dot-bridge.service +17 -0
  180. package/systemd/dot-deadman.service +30 -0
  181. package/systemd/dot-pr-reviewer.service +11 -0
  182. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,18 @@
1
+ // Refused submits, from the request log's submit_rejected lines, grouped by reason class. The reason class drops the
2
+ // path or value after the first ': ' and any parenthesised detail, so one rule with many paths counts as one class.
3
+ import { canonicalKindLabel, fromStoredSource } from './objectives.mjs';
4
+ export const reasonClass = reason => String(reason ?? '').replace(/\s*\(.*$/s, '').replace(/: .*$/s, '').trim() || 'unknown';
5
+ export function summarizeRejections(lines, sinceMs = 0) {
6
+ const classes = new Map(), bySource = {};
7
+ let refused = 0;
8
+ for (const line of lines) {
9
+ if (!line.includes('"submit_rejected"')) continue;
10
+ let entry; try { entry = JSON.parse(line); } catch { continue; }
11
+ if (entry.kind !== 'submit_rejected' || !(Date.parse(entry.at) >= sinceMs)) continue;
12
+ refused++;
13
+ const name = reasonClass(entry.reason), row = classes.get(name) ?? { reason: name, count: 0, example: entry.reason, request_ids: new Set() };
14
+ row.count++; if (entry.request_id) row.request_ids.add(entry.request_id); classes.set(name, row);
15
+ const source = canonicalKindLabel(entry.task_kind) ?? fromStoredSource(entry.source) ?? 'unknown'; bySource[source] = (bySource[source] ?? 0) + 1;
16
+ }
17
+ return { refused, classes: [...classes.values()].sort((a, b) => b.count - a.count).map(r => ({ reason: r.reason, count: r.count, distinct_requests: r.request_ids.size, example: r.example })), by_kind: bySource };
18
+ }
@@ -0,0 +1,102 @@
1
+ import { readEnv } from './env.mjs';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { StringDecoder } from 'node:string_decoder';
5
+ import { redactLogEntry } from './redaction.mjs';
6
+
7
+ function positiveInteger(value, name) {
8
+ const n = Number(value);
9
+ if (!Number.isSafeInteger(n) || n < 1) throw new Error(`${name} must be a positive integer`);
10
+ return n;
11
+ }
12
+
13
+ // One writer per bridge. Rotation and the complete append run synchronously, so no other
14
+ // log call can interleave them. No open descriptor survives a rename.
15
+ export function createRequestLog(file, {
16
+ maxBytes = readEnv('DALAN_LOG_MAX_BYTES') ?? 32 * 1024 * 1024,
17
+ keep = readEnv('DALAN_LOG_KEEP') ?? 4,
18
+ } = {}) {
19
+ file = path.resolve(file);
20
+ maxBytes = positiveInteger(maxBytes, 'DALAN_LOG_MAX_BYTES');
21
+ keep = positiveInteger(keep, 'DALAN_LOG_KEEP');
22
+ let bytes = 0;
23
+ try { bytes = fs.statSync(file).size; } catch (error) { if (error.code !== 'ENOENT') throw error; }
24
+ return entry => {
25
+ const line = JSON.stringify(redactLogEntry({ at: new Date().toISOString(), ...entry })) + '\n';
26
+ // The crossing line stays whole; the next append starts a fresh file. This also
27
+ // rotates an oversized existing log on the first write after a restart.
28
+ if (bytes > maxBytes) {
29
+ for (const generation of listGenerations(file)) {
30
+ if (generation === file) continue;
31
+ const n = Number(generation.slice(file.length + 1));
32
+ if (n >= keep) fs.unlinkSync(generation);
33
+ else fs.renameSync(generation, `${file}.${n + 1}`);
34
+ }
35
+ fs.renameSync(file, `${file}.1`);
36
+ bytes = 0;
37
+ }
38
+ fs.appendFileSync(file, line, { mode: 0o600 });
39
+ bytes += Buffer.byteLength(line);
40
+ };
41
+ }
42
+
43
+ // Discover retained history independently of the writer's current KEEP setting.
44
+ export function listGenerations(file) {
45
+ let names;
46
+ try { names = fs.readdirSync(path.dirname(file)); }
47
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
48
+ const base = path.basename(file);
49
+ return names.filter(name => name === base || (name.startsWith(`${base}.`) && /^[1-9]\d*$/.test(name.slice(base.length + 1))))
50
+ .sort((a, b) => Number(b.slice(base.length + 1) || 0) - Number(a.slice(base.length + 1) || 0))
51
+ .map(name => path.join(path.dirname(file), name));
52
+ }
53
+
54
+ // Pin inodes before reading: a live bridge may rename or retire generations while
55
+ // a backfill scans them. Verify the filenames still identify the opened snapshot.
56
+ function openSnapshot(file, missingOk) {
57
+ for (let attempt = 0; attempt < 3; attempt++) {
58
+ const opened = [];
59
+ try {
60
+ const files = listGenerations(file);
61
+ if (!files.length && !missingOk) files.push(file); // preserve ENOENT for CLI typos
62
+ for (const name of files) {
63
+ const fd = fs.openSync(name, 'r');
64
+ opened.push({ fd, name });
65
+ opened.at(-1).stat = fs.fstatSync(fd);
66
+ }
67
+ const current = listGenerations(file);
68
+ const stable = current.length === files.length && current.every((name, i) => name === files[i]) && opened.every(({ name, stat }) => {
69
+ const now = fs.statSync(name);
70
+ return now.dev === stat.dev && now.ino === stat.ino;
71
+ });
72
+ if (stable) return opened;
73
+ } catch (error) {
74
+ for (const { fd } of opened) fs.closeSync(fd);
75
+ if (error.code !== 'ENOENT' || attempt === 2) throw error;
76
+ continue;
77
+ }
78
+ for (const { fd } of opened) fs.closeSync(fd);
79
+ }
80
+ throw new Error('request log rotated repeatedly while opening history; retry the read');
81
+ }
82
+
83
+ // Oldest first, complete lines only. Bound memory to a chunk plus one line and never
84
+ // join an incomplete tail in one generation to the first line of the next.
85
+ export function* readLines(file, { missingOk = false } = {}) {
86
+ const opened = openSnapshot(file, missingOk);
87
+ try {
88
+ const buffer = Buffer.alloc(64 * 1024);
89
+ for (const { fd, stat } of opened) {
90
+ const decoder = new StringDecoder('utf8');
91
+ let rest = '', position = 0;
92
+ while (position < stat.size) {
93
+ const n = fs.readSync(fd, buffer, 0, Math.min(buffer.length, stat.size - position), position);
94
+ if (!n) break;
95
+ position += n;
96
+ const lines = (rest + decoder.write(buffer.subarray(0, n))).split('\n');
97
+ rest = lines.pop();
98
+ yield* lines;
99
+ }
100
+ }
101
+ } finally { for (const { fd } of opened) fs.closeSync(fd); }
102
+ }
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ // Read-only check of a restored home: `node restore-check.mjs DATA_ROOT CONFIG_ROOT [REQUEST_ID]`. It opens the databases
3
+ // read-only and decrypts what the bridge's own start would decrypt. It starts no server and no delivery loop and opens no network socket,
4
+ // so a restored webhook subscription or pending notice cannot be sent from here. It also never creates a key.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { SubscriptionCodec } from './subscription-storage.mjs';
9
+ import { openAsValue } from './as-store.mjs';
10
+
11
+ const fail = message => { process.stderr.write(`restore-check: ${message}\n`); process.exit(1); };
12
+ const [dataRoot, configRoot, requestId, extra] = process.argv.slice(2);
13
+ if (!dataRoot || !configRoot || extra !== undefined || requestId?.startsWith('-')) fail('usage: restore-check.mjs DATA_ROOT CONFIG_ROOT [REQUEST_ID]');
14
+
15
+ function readKey(file, what) {
16
+ if (!fs.existsSync(file)) fail(`${what} is missing: ${file}`);
17
+ const stat = fs.lstatSync(file);
18
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) fail(`${what} must be a regular file with mode 0600: ${file}`);
19
+ const key = fs.readFileSync(file);
20
+ if (key.length !== 32) fail(`${what} is not 32 bytes: ${file}`);
21
+ return key;
22
+ }
23
+ const hasTable = (db, name) => db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(name) !== undefined;
24
+
25
+ const file = path.join(dataRoot, 'bridge.db');
26
+ if (!fs.existsSync(file)) fail(`no bridge.db in ${dataRoot}`);
27
+ const db = new DatabaseSync(file, { readOnly: true });
28
+ try {
29
+ const integrity = db.prepare('PRAGMA integrity_check').get().integrity_check;
30
+ if (integrity !== 'ok') fail(`bridge.db integrity_check: ${integrity}`);
31
+ const version = db.prepare('PRAGMA user_version').get().user_version;
32
+ const report = { bridge_db: 'ok', schema: version };
33
+ // The same test the bridge applies when it opens the store: schema 52 or newer, or the storage marker table, means encrypted.
34
+ if (version >= 52 || hasTable(db, 'subscription_storage_meta')) {
35
+ const codec = new SubscriptionCodec(readKey(path.join(`${fs.realpathSync(file)}.secrets`, 'storage.key'), 'subscription storage key'));
36
+ try {
37
+ const marker = db.prepare('SELECT verifier FROM subscription_storage_meta WHERE id=1').get();
38
+ if (!marker || codec.open(marker.verifier, 'verifier') !== 'dot-bridge subscriptions v1') throw new Error();
39
+ const subscriptions = db.prepare('SELECT id,secret,connection FROM subscriptions').all();
40
+ for (const sub of subscriptions) {
41
+ codec.open(sub.secret, `subscriptions:${sub.id}:secret`);
42
+ if (sub.connection !== null) codec.open(sub.connection, `subscriptions:${sub.id}:connection`);
43
+ }
44
+ report.subscription_secrets_decrypted = subscriptions.length;
45
+ } catch { fail('subscription storage cannot be decrypted with the restored key'); }
46
+ } else {
47
+ report.subscription_encryption = 'none (database from before the key existed; no key needed)';
48
+ }
49
+ if (requestId) {
50
+ const row = db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId);
51
+ if (!row) fail(`request ${requestId} is not in the restored bridge.db`);
52
+ report.request = { request_id: requestId, status: row.status };
53
+ } else {
54
+ report.assignments = db.prepare('SELECT count(*) n FROM assignments').get().n;
55
+ }
56
+ // The authorization store keeps its own key beside as.sqlite; its marker table says whether the key is required.
57
+ const authFile = path.join(configRoot, 'as.sqlite');
58
+ if (fs.existsSync(authFile)) {
59
+ const auth = new DatabaseSync(authFile, { readOnly: true });
60
+ try {
61
+ const integrityAuth = auth.prepare('PRAGMA integrity_check').get().integrity_check;
62
+ if (integrityAuth !== 'ok') fail(`as.sqlite integrity_check: ${integrityAuth}`);
63
+ if (hasTable(auth, 'as_storage_meta')) {
64
+ const key = readKey(path.join(configRoot, 'as-storage.key'), 'authorization storage key');
65
+ // The store's own start authenticates the verifier and every sealed row; do the same, read-only.
66
+ try {
67
+ const marker = auth.prepare('SELECT verifier FROM as_storage_meta WHERE id=1').get();
68
+ if (!marker || openAsValue(key, marker.verifier, 'verifier') !== 'dot-bridge storage v1') throw new Error();
69
+ for (const row of auth.prepare('SELECT model,id,payload FROM oidc').all()) openAsValue(key, row.payload, `oidc:${row.model}:${row.id}`);
70
+ for (const [table, column] of [['connections', 'connection_id'], ['pairings', 'code']]) {
71
+ for (const row of auth.prepare(`SELECT ${column} AS id,resource FROM ${table}`).all()) openAsValue(key, row.resource, `${table}:${row.id}`);
72
+ }
73
+ } catch { fail('authorization storage cannot be decrypted with the restored key'); }
74
+ report.as_sqlite = 'ok, key verified';
75
+ }
76
+ else report.as_sqlite = 'ok';
77
+ } finally { auth.close(); }
78
+ }
79
+ // Persistent audit state: the checkpoint must open, or the worker audit fails closed at the next start.
80
+ const checkpointFile = path.join(configRoot, 'workers-audit-checkpoint.sqlite');
81
+ if (fs.existsSync(checkpointFile)) {
82
+ const checkpoint = new DatabaseSync(checkpointFile, { readOnly: true });
83
+ try {
84
+ const integrityAudit = checkpoint.prepare('PRAGMA integrity_check').get().integrity_check;
85
+ if (integrityAudit !== 'ok') fail(`workers-audit-checkpoint.sqlite integrity_check: ${integrityAudit}`);
86
+ report.audit_checkpoint = hasTable(checkpoint, 'checkpoint') && checkpoint.prepare('SELECT 1 FROM checkpoint WHERE id=1').get() ? 'ok, recorded' : 'ok, empty';
87
+ } finally { checkpoint.close(); }
88
+ }
89
+ process.stdout.write(`${JSON.stringify(report)}\n`);
90
+ } finally { db.close(); }
@@ -0,0 +1,65 @@
1
+ const fail=c=>{throw Object.assign(new Error(c),{code:c});};
2
+ const str=v=>typeof v==='string'&&v.length>0;
3
+ const nat=v=>Number.isSafeInteger(v)&&v>=0;
4
+ function canon(v){
5
+ if(v===null||typeof v==='boolean'||typeof v==='string')return v;
6
+ if(typeof v==='number'&&Number.isFinite(v))return v;
7
+ if(Array.isArray(v))return v.map(canon);
8
+ if(v&&Object.getPrototypeOf(v)===Object.prototype)return Object.fromEntries(Object.keys(v).sort().map(k=>[k,canon(v[k])]));
9
+ fail('invalid_json');
10
+ }
11
+ const json=v=>JSON.stringify(canon(v));
12
+ export function migrateResultBindings(db){
13
+ if(!db.isTransaction)fail('transaction_required');
14
+ db.exec('CREATE TABLE IF NOT EXISTS immutable_result_bindings(job TEXT PRIMARY KEY,identity TEXT NOT NULL,receipt TEXT NOT NULL)');
15
+ }
16
+ // No physical process-stop claim is derived from terminal assignment state.
17
+ export function terminalAuthority(native){
18
+ const terminal=['finished','cancelled','deleted'].includes(native?.status);
19
+ return {status:native?.status??'unknown',live_authority:terminal?false:null,
20
+ result_authority:native?.status==='finished'&&native?.late!==true,
21
+ compute_stopped:typeof native?.compute_stopped==='boolean'?native.compute_stopped:null};
22
+ }
23
+ export function createResultBindings({db,authorize,readIntent,readArtifact,readTerminal}){
24
+ if([authorize,readIntent,readArtifact,readTerminal].some(f=>typeof f!=='function'))fail('callbacks_required');
25
+ function bind(input,publish){
26
+ if(!db.isTransaction)fail('transaction_required');
27
+ const {job,subject,worker,claim,epoch,source,policy,outcome,summary,result,artifacts}=input;
28
+ if(![job,subject,worker,claim,source,policy].every(str)||!nat(epoch)||epoch<1||
29
+ !['completed','blocked','failed'].includes(outcome)||typeof summary!=='string'||typeof result!=='string'||!Array.isArray(artifacts))fail('invalid_result');
30
+ const old=db.prepare('SELECT * FROM immutable_result_bindings WHERE job=?').get(job);
31
+ // The retained-receipt branch must bind original worker/subject/claim, not require live lease.
32
+ if(authorize({job,subject,worker,claim,epoch,mode:old?'receipt':'live'})!==true)fail('unauthorized');
33
+ const identity=json(input);
34
+ if(old){
35
+ if(old.identity!==identity)fail('result_conflict');
36
+ return {...JSON.parse(old.receipt),duplicate:true,authority:terminalAuthority(readTerminal(job))};
37
+ }
38
+ const intent=readIntent(job);
39
+ if(!intent||typeof intent.source!=='string'||typeof intent.policy!=='string'||source!==intent.source||policy!==intent.policy)fail('binding_mismatch');
40
+ const ids=new Set();
41
+ for(const ref of artifacts){
42
+ if(!ref||!str(ref.id)||!str(ref.origin_claim)||!nat(ref.origin_epoch)||ref.origin_epoch<1||
43
+ !/^[a-f0-9]{64}$/.test(ref.sha256??'')||!nat(ref.size)||ids.has(ref.id)||
44
+ Object.keys(ref).some(k=>!['id','origin_claim','origin_epoch','sha256','size'].includes(k)))fail('invalid_artifact_reference');
45
+ ids.add(ref.id);
46
+ const native=readArtifact({job,id:ref.id});
47
+ if(!native||native.sealed!==true||native.job!==job||native.id!==ref.id||
48
+ native.sha256!==ref.sha256||native.size!==ref.size||native.origin_claim!==ref.origin_claim||
49
+ native.origin_epoch!==ref.origin_epoch)fail('artifact_binding_mismatch');
50
+ }
51
+ if(input.evidence!==undefined){
52
+ if(!Array.isArray(input.evidence)||input.evidence.some(e=>!e||e.trust!=='worker_attested'||typeof e.statement!=='string'||
53
+ Object.keys(e).some(k=>!['trust','statement'].includes(k))))fail('worker_evidence_cannot_be_verified');
54
+ }
55
+ if(typeof publish!=='function')fail('publish_required');
56
+ // Trusted Store hook performs finishOnce in THIS transaction after all binding checks.
57
+ const receipt=publish({job,subject,worker,claim,epoch,outcome,summary,result,artifacts,source,policy,evidence:input.evidence??[]});
58
+ if(!receipt||typeof receipt.then==='function'||!str(receipt.receipt_id)||receipt.late===true)fail('invalid_native_receipt');
59
+ const terminal=readTerminal(job);
60
+ if(terminal?.status!=='finished'||terminal.late===true)fail('native_result_not_terminal');
61
+ db.prepare('INSERT INTO immutable_result_bindings VALUES(?,?,?)').run(job,identity,json(receipt));
62
+ return {...receipt,duplicate:false,authority:terminalAuthority(terminal)};
63
+ }
64
+ return {bind};
65
+ }
@@ -0,0 +1,13 @@
1
+ // Plain syntax on purpose: this file must load on an old Node so that `dalan` can say why it will not run,
2
+ // instead of crashing inside a module that needs a newer Node (node:sqlite) or a different platform.
3
+ export const MIN_NODE_MAJOR = 24;
4
+
5
+ // A one-line reason the `dalan` command cannot run here, or null when it can.
6
+ export function unsupportedRuntime({ nodeVersion = process.versions.node, platform = process.platform } = {}) {
7
+ if (platform === 'win32') return 'dalan runs on Linux and macOS only. On Windows, use WSL (Windows Subsystem for Linux).';
8
+ const major = Number(String(nodeVersion).split('.')[0]);
9
+ if (!(major >= MIN_NODE_MAJOR)) {
10
+ return `dalan needs Node.js ${MIN_NODE_MAJOR} or newer; this is Node.js ${nodeVersion}. Install a newer one from https://nodejs.org/en/download and run the command again.`;
11
+ }
12
+ return null;
13
+ }
@@ -0,0 +1,105 @@
1
+ import fs from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ // Test-only process-tree supervision helpers. Production host checks use the
6
+ // systemd control-group stop receipt instead of this namespace and PID scan.
7
+
8
+ // bwrap and pasta inherit every fd the bridge process leaves open without close-on-exec. Node's spawn only wires fds 0..2, so this
9
+ // launcher closes every other fd it was handed, then execs the real command. It lists /proc/self/fd (so a sparse fd such as 700 is
10
+ // found as surely as fd 3) and uses bash because only bash can close a multi-digit fd (`exec 700>&-`); dash cannot. The glob is
11
+ // expanded before the loop starts, so closing the directory fd it used is harmless. No redirection wraps the loop: a saved copy of
12
+ // stderr would itself be one of the fds in the list.
13
+ export const LAUNCHER = '/usr/bin/bash';
14
+ const CLOSE_FDS = 'for f in /proc/self/fd/*; do n=${f##*/}; case $n in 0|1|2) ;; *) eval "exec $n>&-" ;; esac; done; exec "$@"';
15
+ export const withClosedFds = (command, args) => [LAUNCHER, ['-c', CLOSE_FDS, 'dot-launcher', command, ...args]];
16
+
17
+ // bwrap --info-fd 3 reports the sandbox's pid-namespace inode and its child pid once the namespace exists. The launcher script that
18
+ // execs bwrap opens the fd on a bridge-owned file (pasta closes inherited fds, so a pipe cannot cross it).
19
+ export const INFO_FD = 3;
20
+ export async function readSandboxInfo(file, { gone = () => false, timeoutMs = 20000, pollMs = 5 } = {}) {
21
+ const end = performance.now() + timeoutMs;
22
+ for (;;) {
23
+ try {
24
+ const info = JSON.parse(fs.readFileSync(file, 'utf8'));
25
+ if (Number.isInteger(info['pid-namespace'])) return info;
26
+ } catch {}
27
+ if (gone() || performance.now() >= end) return null;
28
+ await new Promise(resolve => setTimeout(resolve, pollMs));
29
+ }
30
+ }
31
+
32
+ // TEST-ONLY. stat() and pidNamespace() map an unreadable /proc entry to "gone", which is wrong for proof. Production stop evidence comes
33
+ // from the durable cgroup receipts (host-budget-receipts.mjs), never from this module.
34
+ const numeric = /^[0-9]+$/;
35
+ // "pid (comm) S ppid pgrp ..." where comm may contain spaces and parentheses, so cut at the last ')'. Field 22 is the start time in clock
36
+ // ticks since boot: with the pid it names one process for ever, which a bare pid does not (pids are reused).
37
+ function stat(pid) {
38
+ try {
39
+ const text = fs.readFileSync(`/proc/${pid}/stat`, 'utf8'), rest = text.slice(text.lastIndexOf(')') + 2).split(' ');
40
+ return { state: rest[0], ppid: Number(rest[1]), pgrp: Number(rest[2]), start: Number(rest[19]) };
41
+ } catch { return null; }
42
+ }
43
+ const alive = s => s && s.state !== 'Z' && s.state !== 'X';
44
+ const pidNamespace = pid => { try { return fs.readlinkSync(`/proc/${pid}/ns/pid`); } catch { return null; } };
45
+ export const processStart = pid => stat(pid)?.start ?? null;
46
+ // The namespace init: only a process that is a direct child of the sandbox launcher and no older than it can be recorded as the init.
47
+ export function initIdentity(initPid, launcherPid, sandboxStart) {
48
+ const s = Number.isInteger(initPid) ? stat(initPid) : null;
49
+ return alive(s) && s.ppid === launcherPid && (sandboxStart === null || s.start >= sandboxStart) ? { pid: initPid, start: s.start } : null;
50
+ }
51
+
52
+ // Does this process belong to the sandbox? It must be alive, started no earlier than the sandbox, and either be in the sandbox's pid
53
+ // namespace or process group, or be exactly the recorded namespace init (pid and start time). A bare pid never counts.
54
+ export function classify(pid, { nsInode = null, pgid = null, sandboxStart = null, init = null }) {
55
+ const s = stat(pid);
56
+ if (!alive(s)) return null;
57
+ if (init && pid === init.pid && s.start === init.start) return { pid, start: s.start, reason: 'namespace_init_alive' };
58
+ if (sandboxStart !== null && s.start < sandboxStart) return null;
59
+ const inNs = nsInode !== null && pidNamespace(pid) === `pid:[${nsInode}]`;
60
+ if (inNs) return { pid, start: s.start, reason: 'in_sandbox_pid_namespace' };
61
+ if (pgid !== null && s.pgrp === pgid) return { pid, start: s.start, reason: 'in_process_group' };
62
+ return null;
63
+ }
64
+ // A process that made itself non-dumpable hides its ns link from us, so the namespace init is checked as well: the kernel does not let a
65
+ // pid-namespace init finish exiting until every other task in the namespace is gone.
66
+ export function remainingProcesses(scope) {
67
+ const found = [];
68
+ for (const entry of fs.readdirSync('/proc')) {
69
+ if (!numeric.test(entry)) continue;
70
+ const hit = classify(Number(entry), scope);
71
+ if (hit) found.push(hit);
72
+ }
73
+ return found;
74
+ }
75
+
76
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
77
+ const signalHelper = fileURLToPath(new URL('./signal-sandbox-processes.py', import.meta.url));
78
+ export function signalSandboxProcesses(processes, scope) {
79
+ if (!processes.length) return [];
80
+ const result=spawnSync('/usr/bin/python3',[signalHelper],{input:JSON.stringify({processes,scope}),encoding:'utf8',timeout:2000,maxBuffer:65536,env:{PATH:'/usr/bin:/bin'}});
81
+ if (result.status!==0) return [];
82
+ try { const pids=JSON.parse(result.stdout);return Array.isArray(pids)?pids.filter(Number.isSafeInteger):[]; } catch { return []; }
83
+ }
84
+ // Waits for the sandbox to be empty. After `graceMs` it SIGKILLs what is left, then waits again. Before each kill the process is
85
+ // classified again. The signal helper opens a pidfd, checks the same identity and scope, then signals that pidfd so a later PID reuse
86
+ // cannot redirect SIGKILL to another process.
87
+ export async function verifyStopped({ graceMs = 1000, sweepMs = 2000, pollMs = 20, scan = remainingProcesses, recheck = (entry, scope) => classify(entry.pid, scope), signal = signalSandboxProcesses, ...scope }) {
88
+ const hasScope=Number.isSafeInteger(scope.nsInode)&&scope.nsInode>0 || Number.isSafeInteger(scope.pgid)&&scope.pgid>0 || Number.isSafeInteger(scope.init?.pid)&&Number.isSafeInteger(scope.init?.start);
89
+ if (!hasScope) {
90
+ return { verified: false, remaining: [], swept: [], reason: 'sandbox_scope_unavailable' };
91
+ }
92
+ let remaining = scan(scope), swept = [];
93
+ const waitFor = async ms => { for (const end = performance.now() + ms; remaining.length && performance.now() < end;) { await sleep(pollMs); remaining = scan(scope); } };
94
+ await waitFor(graceMs);
95
+ if (remaining.length) {
96
+ const eligible=[];
97
+ for (const entry of remaining) {
98
+ const again = recheck(entry, scope);
99
+ if (again && again.start === entry.start) eligible.push(entry);
100
+ }
101
+ try { swept.push(...signal(eligible,scope)); } catch {}
102
+ await waitFor(sweepMs);
103
+ }
104
+ return { verified: remaining.length === 0, remaining, swept };
105
+ }
@@ -0,0 +1,186 @@
1
+ // A small JSON-Schema subset for registered-tool arguments. compileSchema() refuses anything it cannot enforce, so no
2
+ // keyword is silently ignored; validateValue() checks a value against the compiled schema. Messages name the field and
3
+ // the rule, never the offending value.
4
+ //
5
+ // Supported: type (object, string, number, integer, boolean, array), properties, required, additionalProperties:false
6
+ // (enforced and implied at every object level), enum (scalars), minLength, maxLength, pattern, minimum, maximum, items,
7
+ // minItems, maxItems, description, title. Everything else ($ref, oneOf, anyOf, allOf, format, const ...) is refused.
8
+ export class SchemaError extends Error {
9
+ constructor(message) { super(message); this.name = 'SchemaError'; }
10
+ }
11
+
12
+ export const SUBSET_LIMITS = Object.freeze({
13
+ maxDepth: 6, maxBytes: 65536, schemaBytes: 16384, maxPattern: 256, defaultString: 8000, defaultArray: 100, maxProperties: 32, maxEnum: 64,
14
+ });
15
+
16
+ const KEYWORDS = new Set(['type', 'properties', 'required', 'additionalProperties', 'enum', 'minLength', 'maxLength', 'pattern',
17
+ 'minimum', 'maximum', 'items', 'minItems', 'maxItems', 'description', 'title']);
18
+ const TYPES = new Set(['object', 'string', 'number', 'integer', 'boolean', 'array']);
19
+ const PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
20
+
21
+ // ---- pattern safety -----------------------------------------------------------------------------------------------
22
+ // A pattern is admitted only in one closed form: ^, an optional literal prefix, ONE character class with ONE quantifier,
23
+ // then $. Examples: ^[a-f0-9]{64}$, ^[A-Za-z0-9_-]+$, ^job-[0-9]{1,8}$, ^\d{4}$. Matching such a pattern is linear in the
24
+ // input: the prefix is fixed text and a single repeated class has no second part to trade characters with, so no input
25
+ // can make the engine backtrack. Groups, alternation, several repeats, escapes other than \d and \-, back-references
26
+ // and lookaround are refused. Arbitrary operator patterns are a later feature.
27
+ export const PATTERN_FORM = '^ + optional literal prefix [A-Za-z0-9_-] + one class such as [a-z0-9_-] or \\d + one of + * {n} {n,m} {n,} + $';
28
+ const PATTERN_GRAMMAR = /^\^[A-Za-z0-9_-]{0,32}(?:\[(?:[A-Za-z0-9_.]-[A-Za-z0-9_.]|[A-Za-z0-9_.]|\\-)+-?\]|\\d)(?:\+|\*|\{\d{1,4}\}|\{\d{1,4},\d{0,4}\})\$$/;
29
+ function unsafePattern(pattern) {
30
+ return PATTERN_GRAMMAR.test(pattern) ? null : `only the form ${PATTERN_FORM} is allowed`;
31
+ }
32
+
33
+ const regexCache = new Map();
34
+ const compiledRegex = pattern => {
35
+ let regex = regexCache.get(pattern);
36
+ if (!regex) { regex = new RegExp(pattern, 'u'); if (regexCache.size > 256) regexCache.clear(); regexCache.set(pattern, regex); }
37
+ return regex;
38
+ };
39
+
40
+ // ---- compile ------------------------------------------------------------------------------------------------------
41
+ const canonicalLength = value => JSON.stringify(value)?.length ?? 0;
42
+
43
+ export function compileSchema(schema) {
44
+ if (canonicalLength(schema) > SUBSET_LIMITS.schemaBytes) throw new SchemaError('schema is too large');
45
+ return compile(schema, 0, 'schema');
46
+ }
47
+
48
+ function compile(schema, depth, path) {
49
+ const bad = why => { throw new SchemaError(`${path}: ${why}`); };
50
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) bad('must be an object');
51
+ if (depth > SUBSET_LIMITS.maxDepth) bad('nested too deeply');
52
+ for (const key of Object.keys(schema)) if (!KEYWORDS.has(key)) bad(`keyword "${key.slice(0, 40)}" is not supported`);
53
+ if (typeof schema.type !== 'string' || !TYPES.has(schema.type)) bad('type must be object, string, number, integer, boolean or array');
54
+ for (const key of ['description', 'title']) if (schema[key] !== undefined && typeof schema[key] !== 'string') bad(`${key} must be a string`);
55
+ const out = { type: schema.type };
56
+ if (schema.description !== undefined) out.description = schema.description;
57
+ if (schema.title !== undefined) out.title = schema.title;
58
+ const only = (...allowed) => {
59
+ for (const key of ['properties', 'required', 'additionalProperties', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'items', 'minItems', 'maxItems', 'enum'])
60
+ if (schema[key] !== undefined && !allowed.includes(key)) bad(`"${key}" does not apply to type ${schema.type}`);
61
+ };
62
+ const intKeyword = key => {
63
+ if (schema[key] === undefined) return;
64
+ if (!Number.isSafeInteger(schema[key]) || schema[key] < 0) bad(`${key} must be a non-negative integer`);
65
+ out[key] = schema[key];
66
+ };
67
+ const numKeyword = key => {
68
+ if (schema[key] === undefined) return;
69
+ if (typeof schema[key] !== 'number' || !Number.isFinite(schema[key])) bad(`${key} must be a number`);
70
+ out[key] = schema[key];
71
+ };
72
+ if (schema.enum !== undefined) {
73
+ if (schema.type === 'object' || schema.type === 'array') bad('enum applies to scalar types only');
74
+ if (!Array.isArray(schema.enum) || !schema.enum.length || schema.enum.length > SUBSET_LIMITS.maxEnum || schema.enum.some(v => !['string', 'number', 'boolean'].includes(typeof v))) bad(`enum must hold 1-${SUBSET_LIMITS.maxEnum} scalars`);
75
+ out.enum = [...schema.enum];
76
+ }
77
+ switch (schema.type) {
78
+ case 'object': {
79
+ only('properties', 'required', 'additionalProperties');
80
+ if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) bad('additionalProperties may only be false');
81
+ const props = schema.properties ?? {};
82
+ if (!props || typeof props !== 'object' || Array.isArray(props)) bad('properties must be an object');
83
+ const names = Object.keys(props);
84
+ if (names.length > SUBSET_LIMITS.maxProperties) bad('too many properties');
85
+ out.properties = {};
86
+ for (const name of names) {
87
+ if (PROTOTYPE_KEYS.has(name)) bad(`property "${name}" is not allowed`);
88
+ out.properties[name] = compile(props[name], depth + 1, `${path}.${name}`);
89
+ }
90
+ if (schema.required !== undefined) {
91
+ if (!Array.isArray(schema.required) || schema.required.some(r => typeof r !== 'string' || !names.includes(r))) bad('required must list declared properties');
92
+ out.required = [...schema.required];
93
+ }
94
+ out.additionalProperties = false;
95
+ break;
96
+ }
97
+ case 'string': {
98
+ only('minLength', 'maxLength', 'pattern', 'enum');
99
+ intKeyword('minLength'); intKeyword('maxLength');
100
+ out.maxLength = Math.min(out.maxLength ?? SUBSET_LIMITS.defaultString, SUBSET_LIMITS.defaultString);
101
+ if (schema.pattern !== undefined) {
102
+ if (typeof schema.pattern !== 'string' || !schema.pattern) bad('pattern must be a non-empty string');
103
+ if (schema.pattern.length > SUBSET_LIMITS.maxPattern) bad(`pattern is longer than ${SUBSET_LIMITS.maxPattern} characters`);
104
+ const unsafe = unsafePattern(schema.pattern);
105
+ if (unsafe) bad(`pattern is not allowed: ${unsafe}`);
106
+ try { compiledRegex(schema.pattern); } catch { bad('pattern is not a valid expression'); }
107
+ out.pattern = schema.pattern;
108
+ }
109
+ break;
110
+ }
111
+ case 'number': case 'integer':
112
+ only('minimum', 'maximum', 'enum');
113
+ numKeyword('minimum'); numKeyword('maximum');
114
+ break;
115
+ case 'boolean':
116
+ only('enum');
117
+ break;
118
+ case 'array':
119
+ only('items', 'minItems', 'maxItems');
120
+ if (schema.items === undefined) bad('array needs items');
121
+ out.items = compile(schema.items, depth + 1, `${path}[]`);
122
+ intKeyword('minItems'); intKeyword('maxItems');
123
+ out.maxItems = Math.min(out.maxItems ?? SUBSET_LIMITS.defaultArray, SUBSET_LIMITS.defaultArray);
124
+ break;
125
+ }
126
+ return out;
127
+ }
128
+
129
+ // ---- validate -----------------------------------------------------------------------------------------------------
130
+ function valueDepth(value, limit) {
131
+ let depth = 0, level = [value];
132
+ while (level.length && depth <= limit) {
133
+ const next = [];
134
+ for (const item of level) if (item && typeof item === 'object') next.push(...(Array.isArray(item) ? item : Object.values(item)));
135
+ if (!next.length) return depth;
136
+ level = next; depth++;
137
+ }
138
+ return depth;
139
+ }
140
+
141
+ export function validateValue(schema, value) {
142
+ let text;
143
+ try { text = JSON.stringify(value); } catch { return ['value: cannot be serialized']; }
144
+ if ((text?.length ?? 0) > SUBSET_LIMITS.maxBytes) return [`value: larger than the ${SUBSET_LIMITS.maxBytes}-byte size cap`];
145
+ if (valueDepth(value, SUBSET_LIMITS.maxDepth) > SUBSET_LIMITS.maxDepth) return [`value: nested deeper than ${SUBSET_LIMITS.maxDepth} levels`];
146
+ const errors = [];
147
+ check(schema, value, 'value', errors);
148
+ return errors;
149
+ }
150
+
151
+ function check(schema, value, path, errors) {
152
+ const fail = why => errors.push(`${path}: ${why}`);
153
+ switch (schema.type) {
154
+ case 'object': {
155
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return fail('must be an object');
156
+ for (const key of Object.keys(value)) {
157
+ if (PROTOTYPE_KEYS.has(key)) { fail('forbidden key'); continue; }
158
+ if (!Object.hasOwn(schema.properties, key)) fail('unknown key');
159
+ }
160
+ for (const key of schema.required ?? []) if (!Object.hasOwn(value, key)) fail(`missing "${key}"`);
161
+ for (const [key, sub] of Object.entries(schema.properties)) if (Object.hasOwn(value, key)) check(sub, value[key], `${path}.${key}`, errors);
162
+ return;
163
+ }
164
+ case 'string':
165
+ if (typeof value !== 'string') return fail('must be a string');
166
+ if (value.length > schema.maxLength) return fail(`longer than ${schema.maxLength}`);
167
+ if (schema.minLength !== undefined && value.length < schema.minLength) fail(`shorter than ${schema.minLength}`);
168
+ if (schema.pattern !== undefined && !compiledRegex(schema.pattern).test(value)) fail('does not match the required pattern');
169
+ break;
170
+ case 'integer': case 'number':
171
+ if (typeof value !== 'number' || !Number.isFinite(value) || (schema.type === 'integer' && !Number.isInteger(value))) return fail(`must be ${schema.type === 'integer' ? 'an integer' : 'a number'}`);
172
+ if (schema.minimum !== undefined && value < schema.minimum) fail(`below ${schema.minimum}`);
173
+ if (schema.maximum !== undefined && value > schema.maximum) fail(`above ${schema.maximum}`);
174
+ break;
175
+ case 'boolean':
176
+ if (typeof value !== 'boolean') return fail('must be a boolean');
177
+ break;
178
+ case 'array':
179
+ if (!Array.isArray(value)) return fail('must be an array');
180
+ if (value.length > schema.maxItems) return fail(`more than ${schema.maxItems} items`);
181
+ if (schema.minItems !== undefined && value.length < schema.minItems) fail(`fewer than ${schema.minItems} items`);
182
+ value.forEach((item, i) => check(schema.items, item, `${path}[${i}]`, errors));
183
+ return;
184
+ }
185
+ if (schema.enum && !schema.enum.includes(value)) fail('not an allowed value');
186
+ }
package/src/scopes.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // OAuth scope names. The neutral names are advertised and issued by default. The older `dot-bridge.*`
2
+ // names stay accepted as aliases for tokens, connections and clients that already use them; each alias
3
+ // maps to exactly the permission of its neutral name, so no alias grants more than before.
4
+ export const LEGACY_SCOPE_ALIASES = Object.freeze({ 'dot-bridge.read': 'dalan.read', 'dot-bridge.work': 'dalan.work' });
5
+ export const ADVERTISED_SCOPES = Object.freeze(['dalan.read', 'dalan.work', 't3.read', 't3.write']);
6
+ export const ACCEPTED_SCOPES = Object.freeze([...ADVERTISED_SCOPES, ...Object.keys(LEGACY_SCOPE_ALIASES)]);
7
+ export const canonicalScope = scope => LEGACY_SCOPE_ALIASES[scope] ?? scope;
8
+ export const canonicalScopes = scopes => new Set([...scopes].filter(Boolean).map(canonicalScope));
9
+ // Names clients see in challenges and protected-resource metadata. Built-in mode and the stable catalog use the neutral
10
+ // names. An external issuer keeps the legacy names unless the operator sets OAUTH_SCOPE_NAMES=neutral in oauth.env, so an
11
+ // issuer that only defines `dot-bridge.*` keeps working with no edit. The frozen legacy-v46 catalog always uses legacy names.
12
+ export const LEGACY_SCOPE_NAMES = Object.freeze(Object.fromEntries(Object.entries(LEGACY_SCOPE_ALIASES).map(([legacy, neutral]) => [neutral, legacy])));
13
+ export const legacyScopeNames = config => config?.legacyScopeNames === true || (config?.builtin !== true && config?.OAUTH_SCOPE_NAMES !== 'neutral');
14
+ export const wireScope = (scope, legacy) => legacy ? String(scope).split(' ').map(name => LEGACY_SCOPE_NAMES[name] ?? name).join(' ') : scope;
15
+ export const advertisedScopeNames = config => ADVERTISED_SCOPES.map(name => wireScope(name, legacyScopeNames(config)));