@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
package/src/alerts.mjs ADDED
@@ -0,0 +1,147 @@
1
+ import { defaultPath } from './paths.mjs';
2
+ import { terminalSafeLine } from './terminal-safe.mjs';
3
+ import { readEnv } from './env.mjs';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ import { loadRedeliveryLimits } from './store.mjs';
8
+ import { redactSinkText, registerSecret } from './redaction.mjs';
9
+
10
+ function config() {
11
+ const file=readEnv('DALAN_ALERTS_FILE')||defaultPath(os.homedir(),'.config/dot-bridge/alerts.env');
12
+ if(!fs.existsSync(file)) return {};
13
+ if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('alerts.env must be mode 0600');
14
+ const settings=Object.fromEntries(fs.readFileSync(file,'utf8').split('\n').filter(x=>x.includes('=')).map(x=>{const i=x.indexOf('=');return [x.slice(0,i),x.slice(i+1)];}));
15
+ // The publisher token and topic URL are credentials the bridge holds: mask them by value everywhere.
16
+ for(const name of ['NTFY_TOKEN','NTFY_URL']) if(settings[name]) registerSecret(settings[name]);
17
+ return settings;
18
+ }
19
+ const notAccepted=message=>Object.assign(new Error(message),{notifyOutcome:'not_accepted'});
20
+ const MASK='[redacted secret]';
21
+ // A credential may be split across title and body ("Bearer" / value, "whsec_" / suffix).
22
+ // If scanning the joined text masks more than the separate scans, mask the title's last token and the whole body:
23
+ // whitespace before the value means no token boundary in the body can be trusted to end the credential.
24
+ export function sanitizeAlertFields(rawTitle,rawMessage) {
25
+ let title=redactSinkText(String(rawTitle).replace(/[\r\n]+/g,' ')),message=redactSinkText(rawMessage);
26
+ const separate=`${title} ${message}`;
27
+ const split=['',' '].some(glue=>redactSinkText(`${String(rawTitle).replace(/[\r\n]+/g,' ')}${glue}${rawMessage}`)!==(glue?separate:`${title}${message}`));
28
+ if(split) {
29
+ title=title.replace(/\S*$/,MASK);
30
+ message=MASK;
31
+ }
32
+ return {title,message};
33
+ }
34
+ async function emit(rawTitle,rawMessage,log,settings,options={}) {
35
+ // One pass before both the log and the transport: a caller never reaches either with a raw secret.
36
+ const {title,message}=sanitizeAlertFields(rawTitle,rawMessage);
37
+ if(!options.skipLog)log({kind:'alert',title,message});
38
+ if(options.requirePublisher&&!settings.NTFY_URL) throw notAccepted('ntfy publisher missing');
39
+ if(options.logOnly) return false;
40
+ // With no publisher, writing the log is delivery; configured POST failures still retry.
41
+ if(!settings.NTFY_URL) return !options.skipLog;
42
+ const headers={Title:title,'Content-Type':'text/plain'};
43
+ if(options.idempotencyKey) headers['X-Idempotency-Key']=options.idempotencyKey;
44
+ if(settings.NTFY_TOKEN) headers.Authorization=`Bearer ${settings.NTFY_TOKEN}`;
45
+ const response=await fetch(settings.NTFY_URL,{method:'POST',headers,body:message,signal:AbortSignal.timeout(5000)});
46
+ if(!response.ok) {
47
+ const message=`ntfy HTTP ${response.status}`;
48
+ if(response.status>=400&&response.status<500) throw notAccepted(message);
49
+ throw new Error(message);
50
+ }
51
+ return true;
52
+ }
53
+ export async function publishAlert(title,message,log,options={}) { return emit(title,message,log,config(),options); }
54
+ const minutes=ms=>Math.round(ms/60000);
55
+ // Transient worker pauses are normal; page only after 30 minutes on the trusted OS clock.
56
+ const ALERT_ATTENTION_DELAY_MS=30*60_000;
57
+ export function redactNote(text) {
58
+ // Known values, strong formats and credential fields only: commit hashes and long identifiers stay readable.
59
+ return terminalSafeLine(redactSinkText(String(text)).replace(/\s+/g,' ').trim());
60
+ }
61
+ // One start and one end alert per usage break; mark after delivery (log-only or published), so a failed publish retries.
62
+ async function breakAlerts(store,log,settings,limits) {
63
+ store.pruneWorkerCalls();
64
+ store.inferBreak(limits);
65
+ const queued=store.hasQueuedFor(['dot']);
66
+ for(const b of store.breakAlertsDue()) {
67
+ if(!b.until&&!b.attention_published_at) {
68
+ if(!queued) {store.observeBreakAlert(b.id,null);continue;}
69
+ const first=b.alert_first_observed_at??store.stamp();
70
+ if(!b.alert_first_observed_at)store.observeBreakAlert(b.id,first);
71
+ if(store.nowMs()-Date.parse(first)<ALERT_ATTENTION_DELAY_MS||!Number.isFinite(Date.parse(first)))continue;
72
+ // An inferred break is silence, not evidence: it is reported and holds nothing until the owner confirms it.
73
+ const effect=b.source==='owner'?`Re-wakes are limited to one probe every ${minutes(limits.breakProbeMs??1800000)} min; the queue stays intact.`:'Not confirmed, so nothing is held; if the worker client reports a usage limit, confirm with dalan break --reason TEXT.';
74
+ const published=await emit('Dalan attention',`worker_break: the worker ${b.source==='owner'?'is':'may be'} on a usage break since ${b.since} (${b.source}): ${redactNote(b.reason).slice(0,200)}. ${effect} Inspect with dalan breaks.`,log,settings);
75
+ if(published)store.markBreakAlert(b.id,'start');
76
+ }
77
+ if(b.until&&b.attention_published_at&&!b.end_alerted_at) {
78
+ const published=await emit('Dalan recovered',`worker_break resolved: ended ${b.until} by ${b.end_source} after ${minutes(Date.parse(b.until)-Date.parse(b.since))} min`,log,settings);
79
+ if(published)store.markBreakAlert(b.id,'end');
80
+ }
81
+ }
82
+ }
83
+ const activeChecks=new WeakMap();
84
+ export function checkAlerts(store,log) {
85
+ if(activeChecks.has(store)) return activeChecks.get(store);
86
+ const run=checkAlertsNow(store,log).finally(()=>activeChecks.delete(store));
87
+ activeChecks.set(store,run);
88
+ return run;
89
+ }
90
+ async function checkAlertsNow(store,log) {
91
+ const settings=config(),limits=loadRedeliveryLimits();
92
+ for(const alert of store.pendingDeliveryAlerts()) {
93
+ const message=`uncertain_delivery: ${alert.request_id?`request ${alert.request_id}`:`message ${alert.message_id??alert.notification_id}`}, notification ${alert.notification_id}: ${redactNote(alert.reason)}. This notice will not be resent automatically. No action is required.`;
94
+ if(!alert.logged_at) {
95
+ log({kind:'alert',...sanitizeAlertFields('Dalan attention',message)});
96
+ store.deliveryAlertLogged(alert.notification_id);
97
+ }
98
+ if(!settings.NTFY_URL)continue;
99
+ await emit('Dalan attention',message,log,settings,{requirePublisher:true,skipLog:true});
100
+ store.deliveryAlertPublished(alert.notification_id);
101
+ }
102
+ await breakAlerts(store,log,settings,limits);
103
+ // Episodes opened under the old condition name continue under the current one.
104
+ store.db.prepare("UPDATE OR IGNORE alert_episodes SET condition='skipped_by_worker' WHERE condition='skipped_by_dot'").run();
105
+ const status=store.status({limits}),lead=Number(settings.ALERT_LEAD_MS||21600000);
106
+ const live=status, classes=live.queue_classes, queued=status.counts.find(x=>x.status==='queued')?.count||0;
107
+ const slots=`${live.claimed_outer_count} of ${live.max_claimed_outer_assignments} slots claimed`;
108
+ const expiresAt=status.subscription.expires_at?Date.parse(status.subscription.expires_at):null;
109
+ // Estimated limits are metrics: reaching one pages once and holds nothing.
110
+ const over=store.overEstimate(limits);
111
+ const denied=status.claim_denied??{count:0,request_ids:[]};
112
+ const conditions={
113
+ claim_denied:{active:denied.count>0,message:()=>`claim_denied: the worker reported that its reviewer denied the claim of ${denied.count} queued assignment(s): ${denied.request_ids.join(', ')}${denied.capacity_hold_until?`. It was a capacity overrun, so re-wakes hold until a claimed assignment ends (at most until ${denied.capacity_hold_until})`:''}. The worker will not retry them and the bridge no longer re-wakes them; cancel or resubmit. Inspect with dalan get ID.`},
114
+ skipped_by_worker:{active:status.skipped_by_worker.count>0,message:()=>`skipped_by_worker: the worker listed but did not claim ${status.skipped_by_worker.count} queued assignment(s) despite free lanes: ${status.skipped_by_worker.request_ids.join(', ')}. They now list after their peers; cancel and re-issue, or take the work yourself.`},
115
+ usage_over_estimate:{active:over.length>0,message:()=>`usage_over_estimate: ${over.map(o=>`${o.name} ${o.used}/${o.limit}${o.learned!==undefined?` (configured ${o.configured}, learned ${o.learned} from break ${o.break_id}${o.learned<o.limit?', floored':''})`:''}`).join('; ')}. Estimates only; the bridge holds no work for them. Inspect with dalan learned.`},
116
+ subscription_lapse:{active:status.subscriptions_active>0&&expiresAt&&expiresAt-store.nowMs()<=lead},
117
+ subscription_inactive:{active:status.subscriptions_active===0},
118
+ callback_auth:{active:status.subscription.auth_failures>=3},
119
+ pause_suspected:{active:classes.pause_suspected>0&&queued>0,message:()=>`pause_suspected: no worker tool call for ${minutes(live.worker_silence_ms??live.oldest_unclaimed_event_2xx_age_ms??0)} min while ${queued} assignments are queued (${slots}). Pause cause unconfirmed.`},
120
+ stale_claims:{active:live.stale_claims.count>0,message:()=>`stale_claims: ${live.stale_claims.count} claimed assignments idle up to ${minutes(live.stale_claims.max_idle_ms)} min (${slots}). Their leases have expired, so another claimant may take them over; the bridge does not abandon them by itself. Inspect with dalan claims.`},
121
+ unclaimed_queued:{active:(live.unclaimed_after_reannounce?.count??0)>0,message:()=>`unclaimed_queued: ${live.unclaimed_after_reannounce.count} queued assignments outlived the ${minutes(limits.rewakeWindowMs)} min re-wake window without a claim (oldest queued ${minutes(live.unclaimed_after_reannounce.oldest_age_ms??0)} min, ${slots}). They are re-woken at most every ${minutes(limits.rewakeStaleMs??1200000)} min; the bridge does not cancel or park them. Inspect with dalan status --json.`},
122
+ transport_failing:{active:classes.transport_failing>0,message:()=>`transport_failing: ${classes.transport_failing} queued assignments never had an event accepted (oldest unclaimed age ${minutes(live.oldest_queue_age_ms??0)} min).`}
123
+ };
124
+ for(const [name,{active,message}] of Object.entries(conditions)) {
125
+ const old=store.db.prepare('SELECT active,started_at,attention_sent_at FROM alert_episodes WHERE condition=?').get(name);
126
+ const now=store.stamp();
127
+ if(active) {
128
+ const started=old?.active&&old.started_at?old.started_at:now;
129
+ if(!old?.active||!old.started_at)store.db.prepare('INSERT INTO alert_episodes(condition,active,started_at,last_change_at,attention_sent_at) VALUES(?,1,?,?,NULL) ON CONFLICT(condition) DO UPDATE SET active=1,started_at=excluded.started_at,last_change_at=excluded.last_change_at,attention_sent_at=NULL').run(name,started,now);
130
+ if(store.nowMs()-Date.parse(started)>=ALERT_ATTENTION_DELAY_MS&&!old?.attention_sent_at) {
131
+ const published=await emit('Dalan attention',message?message():`${name}: inspect dalan status --json`,log,settings);
132
+ // Remote acceptance and the local marker are not atomic; lost replies may duplicate transport.
133
+ if(published)store.db.prepare('UPDATE alert_episodes SET attention_sent_at=? WHERE condition=? AND active=1 AND attention_sent_at IS NULL').run(store.stamp(),name);
134
+ }
135
+ } else if(old?.active) {
136
+ if(old.attention_sent_at&&!await emit('Dalan recovered',`${name} resolved`,log,settings))continue;
137
+ store.db.prepare('UPDATE alert_episodes SET active=0,started_at=NULL,last_change_at=?,attention_sent_at=NULL WHERE condition=?').run(now,name);
138
+ }
139
+ }
140
+ const denials=store.denialNotes();
141
+ if(denials.matches.length) {
142
+ const quote=redactNote(denials.matches[0]).slice(0,80), more=denials.matches.length>1?` (+${denials.matches.length-1} more)`:'';
143
+ // Logged, not paged: a per-task auto-review block is the worker's own business; a real pause pages as pause_suspected or worker_break.
144
+ await emit('Dalan attention',`denial_mentioned: a worker note mentions a denial or pause: "${quote}"${more}. Likely pause cause; no action taken.`,log,settings,{logOnly:true});
145
+ }
146
+ store.ackDenialNotes(denials);
147
+ }
@@ -0,0 +1,75 @@
1
+ // Durable mutation facts only. Workspace owns bytes and native metadata.
2
+ // Call migrateArtifactJournal in the parent's schema migration transaction.
3
+ // Every mutation requires the parent's transaction and a synchronous authority check.
4
+ import { createHash } from 'node:crypto';
5
+
6
+ const fail = code => { throw Object.assign(new Error(code), {code}); };
7
+ const text = v => typeof v === 'string' && v.length > 0 && v.length <= 512;
8
+ const digest = v => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
9
+ const integer = v => Number.isSafeInteger(v) && v >= 0;
10
+ function canonical(v) {
11
+ if (v === null || typeof v === 'boolean' || typeof v === 'string') return v;
12
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
13
+ if (Array.isArray(v)) return v.map(canonical);
14
+ if (v && Object.getPrototypeOf(v) === Object.prototype) {
15
+ return Object.fromEntries(Object.keys(v).sort().map(k => [k, canonical(v[k])]));
16
+ }
17
+ fail('invalid_json');
18
+ }
19
+ const json = v => JSON.stringify(canonical(v));
20
+ export function migrateArtifactJournal(db) {
21
+ if (!db.isTransaction) fail('transaction_required');
22
+ db.exec(`CREATE TABLE IF NOT EXISTS artifact_mutation_journal (
23
+ job TEXT NOT NULL, artifact TEXT NOT NULL, mutation_key TEXT NOT NULL,
24
+ identity TEXT NOT NULL, result TEXT NOT NULL,
25
+ PRIMARY KEY(job, artifact, mutation_key));
26
+ CREATE TABLE IF NOT EXISTS artifact_journal_heads (
27
+ job TEXT NOT NULL, artifact TEXT NOT NULL, reference TEXT NOT NULL,
28
+ origin_claim TEXT NOT NULL, origin_epoch INTEGER NOT NULL,
29
+ size INTEGER NOT NULL, sha256 TEXT, sealed INTEGER NOT NULL,
30
+ PRIMARY KEY(job, artifact));`);
31
+ }
32
+ export function createArtifactJournal({db, authorize, inspect}) {
33
+ if (typeof authorize !== 'function' || typeof inspect !== 'function') fail('callbacks_required');
34
+ const head = (job, artifact) => {
35
+ const row = db.prepare('SELECT * FROM artifact_journal_heads WHERE job=? AND artifact=?').get(job, artifact);
36
+ return row ? {...row, sealed:!!row.sealed} : null;
37
+ };
38
+ function record(command) {
39
+ if (!db.isTransaction) fail('transaction_required');
40
+ const {job, artifact, key, subject, worker, claim, epoch, operation, size, sha256, reference} = command;
41
+ if (![job,artifact,key,subject,worker,claim,reference].every(text) ||
42
+ !Number.isSafeInteger(epoch) || epoch < 1 ||
43
+ !['upload','seal','upload_seal'].includes(operation) || !integer(size) || !digest(sha256)) fail('invalid_mutation');
44
+ // Authority must be checked even for exact replay and inherited seals.
45
+ if (authorize({job,subject,worker,claim,epoch,operation}) !== true) fail('stale_authority');
46
+ const identity = json(command);
47
+ const prior = db.prepare('SELECT identity,result FROM artifact_mutation_journal WHERE job=? AND artifact=? AND mutation_key=?').get(job,artifact,key);
48
+ if (prior) {
49
+ if (prior.identity !== identity) fail('mutation_conflict');
50
+ return JSON.parse(prior.result);
51
+ }
52
+ const previous = head(job,artifact);
53
+ if (previous?.sealed) fail('artifact_sealed');
54
+ if (previous && (previous.origin_claim !== claim || previous.origin_epoch !== epoch ||
55
+ previous.reference !== reference)) fail('artifact_binding_mismatch');
56
+ const uploads=operation==='upload'||operation==='upload_seal';
57
+ if (uploads) {
58
+ if (!integer(command.offset) || !integer(command.chunkSize) || !digest(command.chunkSha256) ||
59
+ command.offset !== (previous?.size ?? 0) || command.offset + command.chunkSize !== size) fail('invalid_chunk_extent');
60
+ } else if (!previous || previous.size !== size || previous.sha256 !== sha256) fail('seal_extent_mismatch');
61
+ // inspect reads the native, durable file; never accept caller attestations.
62
+ const observed = inspect({job,artifact,reference,offset:command.offset,chunkSize:command.chunkSize});
63
+ if (!observed || observed.reference !== reference || observed.size !== size || observed.sha256 !== sha256 ||
64
+ (uploads && observed.chunkSha256 !== command.chunkSha256)) fail('artifact_integrity_mismatch');
65
+ const result = {artifact,reference,size,sha256,sealed:operation !== 'upload',
66
+ origin_claim:previous?.origin_claim ?? claim, origin_epoch:previous?.origin_epoch ?? epoch};
67
+ db.prepare(`INSERT INTO artifact_journal_heads(job,artifact,reference,origin_claim,origin_epoch,size,sha256,sealed)
68
+ VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(job,artifact) DO UPDATE SET size=excluded.size,sha256=excluded.sha256,sealed=excluded.sealed`)
69
+ .run(job,artifact,reference,result.origin_claim,result.origin_epoch,size,sha256,Number(result.sealed));
70
+ db.prepare('INSERT INTO artifact_mutation_journal VALUES(?,?,?,?,?)').run(job,artifact,key,identity,json(result));
71
+ return result;
72
+ }
73
+ return {record, get:head};
74
+ }
75
+ export const artifactBytesDigest = bytes => createHash('sha256').update(bytes).digest('hex');
@@ -0,0 +1,347 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { generateKeyPairSync, randomBytes, randomUUID, createPrivateKey, createPublicKey, sign as cryptoSign, verify as cryptoVerify } from 'node:crypto';
5
+
6
+ // Text that comes from a vendor: no control, format or separator characters (terminal escapes, bidi overrides), bounded length.
7
+ // It lives here, not in as.mjs, so the dalan CLI can use it without loading oidc-provider.
8
+ export const untrusted = (value, max = 80) => String(value ?? '').replace(/[\p{C}\p{Z}]+/gu, ' ').trim().slice(0, max);
9
+
10
+ // Files of the built-in authorization server (AS). All of them live in one 0700 directory and are 0600 files.
11
+ // Keys are generated by `init` only. A server start never creates them: a missing or damaged key file stops the start.
12
+ export const asFiles = dir => ({
13
+ config: path.join(dir, 'as.json'),
14
+ jwks: path.join(dir, 'as-jwks.json'),
15
+ cookies: path.join(dir, 'as-cookie-keys.json'),
16
+ db: path.join(dir, 'as.sqlite'),
17
+ });
18
+
19
+ // Vendor callbacks that the vendors publish. Each entry cites its source. Grok has no published OAuth callback: none is shipped.
20
+ export const DEFAULT_CALLBACKS = Object.freeze([
21
+ // https://claude.com/docs/connectors/building/authentication, "Callback URLs": hosted Claude apps use exactly this URI.
22
+ 'https://claude.ai/api/mcp/auth_callback',
23
+ // https://developers.openai.com/apps-sdk/build/auth, "Redirect URL": the stable URI and the callback-ID-specific URI.
24
+ 'https://chatgpt.com/connector_platform_oauth_redirect',
25
+ 'https://chatgpt.com/connector/oauth/*',
26
+ // Use the provider's exact callback path so another page on the same host cannot receive an authorization code.
27
+ 'https://agent.meta.ai/api/hatch/oauth/callback',
28
+ ]);
29
+
30
+ const fail = message => { throw new Error(`as: ${message}`); };
31
+
32
+ export function assertPrivateDir(dir) {
33
+ let stat;
34
+ try { stat = fs.statSync(dir); } catch { fail(`directory ${dir} is missing`); }
35
+ if (!stat.isDirectory()) fail(`${dir} is not a directory`);
36
+ if ((stat.mode & 0o077) !== 0) fail(`directory ${dir} must be mode 0700`);
37
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) fail(`directory ${dir} must belong to the bridge user`);
38
+ }
39
+
40
+ // Write to a new 0600 file, flush it, then rename it over the target. A crash leaves the old file or the new file, never half of one.
41
+ export function writeAtomic(file, text) {
42
+ const temp = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
43
+ const fd = fs.openSync(temp, 'wx', 0o600);
44
+ try {
45
+ fs.writeSync(fd, text);
46
+ fs.fsyncSync(fd);
47
+ } catch (error) {
48
+ fs.closeSync(fd);
49
+ fs.rmSync(temp, { force: true });
50
+ throw error;
51
+ }
52
+ fs.closeSync(fd);
53
+ fs.renameSync(temp, file);
54
+ const dirFd = fs.openSync(path.dirname(file), 'r');
55
+ try { fs.fsyncSync(dirFd); } finally { fs.closeSync(dirFd); }
56
+ }
57
+
58
+ function readPrivateJson(file, what) {
59
+ let stat;
60
+ try { stat = fs.statSync(file); } catch { fail(`${what} is missing (${file}); run dalan as-init`); }
61
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) fail(`${what} must be a regular file with mode 0600`);
62
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail(`${what} is not valid JSON`); }
63
+ }
64
+
65
+ // ---- callback patterns -------------------------------------------------------------------------------------------
66
+ // A pattern is `https://host[:port]/path`. Scheme, host and port must match exactly. In the path a `*` stands for one
67
+ // segment of letters, digits, `_` and `-`. A redirect URI never carries a query or a fragment.
68
+ export function parseCallbackPattern(pattern, { loopback = false, allowLoopback = true } = {}) {
69
+ if (typeof pattern !== 'string' || pattern.length > 512 || /[\s\u0000-\u001f\u007f]/u.test(pattern)) fail('callback pattern must be a short string without spaces');
70
+ if (allowLoopback && typeof pattern === 'string' && pattern.startsWith('http://')) {
71
+ try { return parseNativeLoopback(pattern, true); }
72
+ catch (error) { if (/omit the port/.test(error.message)) throw error; fail('HTTP is only allowed for canonical native loopback callbacks'); }
73
+ }
74
+ if (!pattern.startsWith('https://')) fail(pattern.startsWith('http://') ? 'HTTP is only allowed for canonical native loopback callbacks' : 'callback pattern must use https');
75
+ if (/[?#@\\]/.test(pattern)) fail('callback pattern must not have credentials, a query or a fragment');
76
+ const slash = pattern.indexOf('/', 'https://'.length);
77
+ if (slash < 0) fail('callback pattern needs a path');
78
+ const authority = pattern.slice('https://'.length, slash), rawPath = pattern.slice(slash);
79
+ if (!authority || authority.includes('*')) fail('callback pattern host and port must be exact');
80
+ let origin;
81
+ try { origin = new URL(`https://${authority}/`).origin; } catch { fail(`callback pattern host ${JSON.stringify(authority)} is invalid`); }
82
+ if (!/^\/[A-Za-z0-9._~\-\/*]*$/.test(rawPath)) fail('callback pattern path has unsupported characters');
83
+ const segments = rawPath.split('/').slice(1);
84
+ if (segments.some(s => s === '' && rawPath !== '/' ) || segments.some(s => s === '.' || s === '..' || (s.includes('*') && s !== '*'))) fail('callback pattern path is not canonical; a * must be a whole segment');
85
+ const regex = new RegExp('^/' + segments.map(s => s === '*' ? '[A-Za-z0-9_-]+' : s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('/') + '$');
86
+ return { pattern, origin, regex };
87
+ }
88
+ export function parseNativeLoopback(uri, pattern = false) {
89
+ if (typeof uri !== 'string' || uri.length > 512 || /[?#@\\\s\u0000-\u001f\u007f%]/u.test(uri)) fail('native callback must be canonical and contain no query, fragment, userinfo or escapes');
90
+ const match = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]+))?(\/[^?#@\\\s\u0000-\u001f\u007f%]*)$/.exec(uri);
91
+ if (!match) fail('native callback host or URI syntax is not allowed');
92
+ const [, hostname, port, pathname] = match;
93
+ if (pattern && port) fail('omit the port in a native callback pattern');
94
+ if (port && (String(Number(port)) !== port || Number(port) < 1 || Number(port) > 65535)) fail('native callback port must be from 1 to 65535');
95
+ const segments = pathname.split('/').slice(1);
96
+ if (pathname !== '/' && segments.some(s => !s || s === '.' || s === '..' || !/^[A-Za-z0-9._~-]+$/.test(s))) fail('native callback path must contain exact canonical segments');
97
+ let url;
98
+ try { url = new URL(uri); } catch { fail('invalid native callback'); }
99
+ if (url.href !== uri) fail('native callback must use canonical spelling');
100
+ return { pattern: pattern ? uri : undefined, loopback: true, hostname, pathname, port: port || '' };
101
+ }
102
+ // Older as.json files could contain non-canonical native paths. Keep those exact owner-approved paths loadable;
103
+ // new registrations still go through parseNativeLoopback above.
104
+ function parseStoredNativeLoopback(uri) {
105
+ if (typeof uri !== 'string' || uri.length > 512 || /[?#@\\\s\u0000-\u001f\u007f]/u.test(uri)) fail('stored native callback is invalid');
106
+ const match = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]+))?(\/[^?#@\\\s\u0000-\u001f\u007f]*)$/.exec(uri);
107
+ if (!match) return parseNativeLoopback(uri, true);
108
+ if (match[2] && (String(Number(match[2])) !== match[2] || Number(match[2]) < 1 || Number(match[2]) > 65535)) fail('stored native callback port is invalid');
109
+ return { pattern: uri, loopback: true, hostname: match[1], pathname: match[3], port: match[2] || '' };
110
+ }
111
+ export function isLoopbackCallback(url) {
112
+ try { return parseStoredNativeLoopback(url.href).hostname === url.hostname; } catch { return false; }
113
+ }
114
+ export function matchesCallback(patterns, uri) {
115
+ if (typeof uri !== 'string') return false;
116
+ let url;
117
+ try { url = new URL(uri); } catch { return false; }
118
+ let native;
119
+ if (uri.startsWith('http://')) { try { native = parseStoredNativeLoopback(uri); } catch { return false; } }
120
+ // The registered string must already be in canonical form: no hidden normalisation, no userinfo, no query, no fragment.
121
+ if (url.href !== uri || !['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) return false;
122
+ return patterns.some(p => p.loopback
123
+ ? !!native && p.hostname === native.hostname && p.pathname === native.pathname
124
+ : url.protocol === 'https:' && p.origin === url.origin && p.regex.test(url.pathname));
125
+ }
126
+
127
+ // ---- as.json -----------------------------------------------------------------------------------------------------
128
+ export function parseAsConfig(value, { allowHttp = false, loopback = false, allowLoopback = true, stored = false } = {}) {
129
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail('as.json must be an object');
130
+ for (const key of Object.keys(value)) if (!['version', 'public_url', 'callbacks', 'limits'].includes(key)) fail(`unknown key ${key} in as.json`);
131
+ if (value.version !== 1) fail('as.json version must be 1');
132
+ let url;
133
+ try { url = new URL(value.public_url); } catch { fail('public_url is not a URL'); }
134
+ const origin = url.origin;
135
+ if (value.public_url !== origin && value.public_url !== `${origin}/`) fail('public_url must be an origin: scheme, host and optional port');
136
+ if (url.protocol !== 'https:' && !((allowHttp || loopback && url.hostname === '127.0.0.1') && url.protocol === 'http:')) fail('public_url must be https (an http test URL needs the explicit test flag)');
137
+ if (!Array.isArray(value.callbacks) || value.callbacks.length > 32) fail('callbacks must be an array of at most 32 patterns');
138
+ const limits = { registrations: 5, interactions: 5, ...value.limits };
139
+ if (value.limits !== undefined && (!value.limits || typeof value.limits !== 'object' || Array.isArray(value.limits))) fail('limits must be an object');
140
+ for (const [key, n] of Object.entries(limits)) {
141
+ if (!['registrations', 'interactions'].includes(key) || !Number.isInteger(n) || n < 1 || n > 100) fail('limits must contain registrations/interactions integers from 1 to 100');
142
+ }
143
+ const patterns = value.callbacks.map(pattern => stored && typeof pattern === 'string' && pattern.startsWith('http://') ? parseStoredNativeLoopback(pattern) : parseCallbackPattern(pattern, { loopback, allowLoopback }));
144
+ return { public_url: origin, callbacks: patterns.map(p => p.pattern), patterns, limits };
145
+ }
146
+ export function loadAsConfig(dir, opts) {
147
+ assertPrivateDir(dir);
148
+ return parseAsConfig(readPrivateJson(asFiles(dir).config, 'as.json'), { ...opts, stored: true });
149
+ }
150
+ export function saveAsCallbacks(dir, callbacks) {
151
+ const file = asFiles(dir).config;
152
+ const current = readPrivateJson(file, 'as.json');
153
+ writeAtomic(file, JSON.stringify({ ...current, callbacks }, null, 2) + '\n');
154
+ }
155
+
156
+ // ---- keys --------------------------------------------------------------------------------------------------------
157
+ // as-jwks.json: { signing_kid, retired: { <kid>: <retired_at ms | null> }, keys: [private ES256 JWKs] }
158
+ // as-cookie-keys.json: { keys: [ { key }, { key, retired_at: <ms | null> }, ... ] } (first entry signs)
159
+ // Retirement starts at rotation: exclusive ownership proves the previous signer has stopped. Keep old keys for the full
160
+ // ID-token, session and interaction lifetimes, plus skew. Legacy null stamps remain retained.
161
+ // How long one pairing attempt stays open for the owner to approve.
162
+ export const PAIRING_MINUTES = 10;
163
+ export const LIFETIMES = Object.freeze({ idToken: 600, session: 3600, interaction: 600, skew: 75 });
164
+ export const JWKS_RETAIN_MS = (LIFETIMES.idToken + LIFETIMES.skew) * 1000;
165
+ export const COOKIE_RETAIN_MS = (Math.max(LIFETIMES.session, LIFETIMES.interaction) + LIFETIMES.skew) * 1000;
166
+ const B64 = /^[A-Za-z0-9_-]{43}$/;
167
+
168
+ // A key is valid only if it works: import the private part, derive its public part, compare with the stated x and y,
169
+ // then sign and verify a message. A well-formed JWK with a swapped scalar fails here.
170
+ function assertWorkingEcKey(key) {
171
+ try {
172
+ const priv = createPrivateKey({ key, format: 'jwk' });
173
+ const derived = createPublicKey(priv).export({ format: 'jwk' });
174
+ if (derived.x !== key.x || derived.y !== key.y) throw new Error('private part does not match public part');
175
+ const pub = createPublicKey({ key: { kty: 'EC', crv: 'P-256', x: key.x, y: key.y }, format: 'jwk' });
176
+ const message = randomBytes(32);
177
+ if (!cryptoVerify('sha256', message, pub, cryptoSign('sha256', message, priv))) throw new Error('sign/verify round trip failed');
178
+ } catch (error) { fail(`as-jwks.json key ${JSON.stringify(String(key.kid))} is not a working ES256 key (${error.message})`); }
179
+ }
180
+ const MAX_KEYS = 8;
181
+ // The one validation for as-jwks.json contents. loadKeys and rotateKeys both use it, so a rotation can never write what a load rejects.
182
+ function validateJwks(jwks) {
183
+ if (!jwks || typeof jwks !== 'object' || !Array.isArray(jwks.keys) || !jwks.keys.length || jwks.keys.length > MAX_KEYS) fail(`as-jwks.json must hold 1 to ${MAX_KEYS} keys`);
184
+ const kids = new Set();
185
+ for (const key of jwks.keys) {
186
+ const ok = key && key.kty === 'EC' && key.crv === 'P-256' && key.alg === 'ES256' && key.use === 'sig' && typeof key.kid === 'string' && key.kid
187
+ && ['x', 'y', 'd'].every(part => typeof key[part] === 'string' && B64.test(key[part]));
188
+ if (!ok || kids.has(key.kid)) fail('as-jwks.json holds a damaged or duplicate key');
189
+ kids.add(key.kid);
190
+ }
191
+ if (!kids.has(jwks.signing_kid)) fail('as-jwks.json signing_kid names no key');
192
+ if (!jwks.retired || typeof jwks.retired !== 'object' || Array.isArray(jwks.retired)) fail('as-jwks.json retired must be an object');
193
+ for (const kid of kids) if (kid !== jwks.signing_kid && !Object.hasOwn(jwks.retired, kid)) fail('as-jwks.json holds a key that is neither signing nor retired');
194
+ for (const [kid, at] of Object.entries(jwks.retired)) if (!kids.has(kid) || kid === jwks.signing_kid || !(at === null || Number.isSafeInteger(at))) fail('as-jwks.json retired list is damaged');
195
+ return jwks;
196
+ }
197
+ function validateCookies(file) {
198
+ const keys = file?.keys;
199
+ if (!Array.isArray(keys) || !keys.length || keys.length > MAX_KEYS) fail('as-cookie-keys.json is damaged');
200
+ keys.forEach((entry, i) => {
201
+ const ok = entry && typeof entry.key === 'string' && /^[A-Za-z0-9_-]{43,}$/.test(entry.key) && (i === 0 ? entry.retired_at === undefined : (entry.retired_at === null || Number.isSafeInteger(entry.retired_at)));
202
+ if (!ok) fail('as-cookie-keys.json is damaged');
203
+ });
204
+ return file;
205
+ }
206
+ const readJwks = dir => validateJwks(readPrivateJson(asFiles(dir).jwks, 'as-jwks.json'));
207
+ const readCookies = dir => validateCookies(readPrivateJson(asFiles(dir).cookies, 'as-cookie-keys.json'));
208
+ export function loadKeys(dir) {
209
+ assertPrivateDir(dir);
210
+ const jwks = readJwks(dir), cookies = readCookies(dir);
211
+ for (const key of jwks.keys) assertWorkingEcKey(key);
212
+ // The provider signs with the first key. The signing kid is chosen explicitly and put first.
213
+ const ordered = [jwks.keys.find(k => k.kid === jwks.signing_kid), ...jwks.keys.filter(k => k.kid !== jwks.signing_kid)];
214
+ return { jwks: { keys: ordered }, signingKid: jwks.signing_kid, cookieKeys: cookies.keys.map(e => e.key) };
215
+ }
216
+ const newEcKey = () => ({ ...generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ format: 'jwk' }), use: 'sig', alg: 'ES256', kid: randomUUID() });
217
+
218
+ // ---- exclusive ownership of the AS state -------------------------------------------------------------------------
219
+ // Hold this exclusive transaction for the owner's lifetime. The kernel releases it on exit, SIGTERM or SIGKILL.
220
+ // Never unlink this database: every starter and rotation must contend on the same inode.
221
+ export function acquireAsOwner(dir) {
222
+ assertPrivateDir(dir);
223
+ // Linux magic values from linux/magic.h. These filesystems cannot provide the local ownership guarantee.
224
+ if (process.platform === 'linux') {
225
+ const type = Number(fs.statfsSync(dir).type) >>> 0;
226
+ if ([0x6969, 0x517b, 0xff534d42, 0xfe534d42, 0x65735546].includes(type)) fail('AS state must use a local filesystem; NFS, SMB/CIFS and FUSE are unsupported. For a trial, use a short directory on a local disk: dalan try --home /short/local/path (not your real home or an existing bridge home)');
227
+ }
228
+ // Keep this path private: a same-process raw open/close can release SQLite's POSIX lock.
229
+ const file = path.join(dir, 'as-owner.sqlite');
230
+ // Do not open/close a raw descriptor for an existing SQLite file: POSIX close would release this process's locks.
231
+ try { fs.closeSync(fs.openSync(file, 'wx', 0o600)); }
232
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
233
+ const stat = fs.lstatSync(file);
234
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) fail('as-owner.sqlite must be a regular file with mode 0600');
235
+ const db = new DatabaseSync(file);
236
+ try { db.exec('PRAGMA busy_timeout=500; BEGIN EXCLUSIVE'); }
237
+ catch (error) {
238
+ db.close();
239
+ if (error.code === 'ERR_SQLITE_ERROR' && error.errcode === 5) fail('AS ownership unavailable after waiting up to 500 ms (database is locked): another bridge, key rotation or init holds it. To rotate keys: stop the bridge, rotate, start');
240
+ throw error;
241
+ }
242
+ let released = false;
243
+ const release = () => {
244
+ if (released) return;
245
+ released = true;
246
+ process.removeListener('exit', release);
247
+ db.close();
248
+ };
249
+ process.once('exit', release);
250
+ return {
251
+ release,
252
+ pruneKeys(now = Date.now()) {
253
+ if (released) fail('AS ownership has been released');
254
+ return pruneKeys(dir, now);
255
+ },
256
+ };
257
+ }
258
+
259
+ // Drop retired entries whose stamp is past the retention window. Pure: returns new contents.
260
+ const prunedJwks = (jwks, now) => {
261
+ const retired = Object.fromEntries(Object.entries(jwks.retired).filter(([, at]) => at === null || at + JWKS_RETAIN_MS > now));
262
+ return { ...jwks, retired, keys: jwks.keys.filter(k => k.kid === jwks.signing_kid || Object.hasOwn(retired, k.kid)) };
263
+ };
264
+ const prunedCookies = (file, now) => ({ keys: file.keys.filter((e, i) => i === 0 || e.retired_at === null || e.retired_at + COOKIE_RETAIN_MS > now) });
265
+ const sameKeys = (a, b) => a.keys.length === b.keys.length;
266
+ const legacyKeys = (entries, label) => {
267
+ const names = entries.filter(([, at]) => at === null).map(([name]) => name);
268
+ return names.length ? `; legacy unstamped ${label}: ${names.join(', ')} (retained indefinitely; see docs/operations.md#legacy-unstamped-keys)` : '';
269
+ };
270
+ const freeAt = (stamps, retain) => { const stamped = stamps.filter(Number.isSafeInteger); return stamped.length ? new Date(Math.min(...stamped) + retain).toISOString() : null; };
271
+
272
+ // Rotation is offline: the lifetime lock excludes every server and other rotation. The previous signer has stopped.
273
+ // The prospective contents (expired keys pruned first) go through the same validation as a load; a rotation that would leave
274
+ // an unloadable state is refused and nothing on disk changes.
275
+ export function rotateKeys(dir, { jwks = true, cookies = true } = {}, now) {
276
+ assertPrivateDir(dir);
277
+ const files = asFiles(dir);
278
+ const owner = acquireAsOwner(dir);
279
+ try {
280
+ now ??= Date.now(); // Sample only after ownership; this command may have been paused before it acquired the lock.
281
+ loadKeys(dir); // Validate both existing files before planning any write.
282
+ const out = {}, writes = [];
283
+ if (jwks) {
284
+ const current = prunedJwks(readJwks(dir), now);
285
+ const key = newEcKey();
286
+ assertWorkingEcKey(key);
287
+ const next = { signing_kid: key.kid, retired: { ...current.retired, [current.signing_kid]: now }, keys: [key, ...current.keys] };
288
+ if (next.keys.length > MAX_KEYS) fail(`too many retained signing keys; wait until ${freeAt(Object.values(current.retired), JWKS_RETAIN_MS) ?? 'no timed expiry'}${legacyKeys(Object.entries(current.retired), 'signing kids')}`);
289
+ validateJwks(next);
290
+ writes.push([files.jwks, next]); out.signing_kid = key.kid;
291
+ }
292
+ if (cookies) {
293
+ const current = prunedCookies(readCookies(dir), now);
294
+ const [active, ...rest] = current.keys;
295
+ const next = { keys: [{ key: randomBytes(32).toString('base64url') }, { key: active.key, retired_at: now }, ...rest] };
296
+ if (next.keys.length > MAX_KEYS) fail(`too many retained cookie keys; wait until ${freeAt(rest.map(e => e.retired_at), COOKIE_RETAIN_MS) ?? 'no timed expiry'}${legacyKeys(current.keys.map((e, i) => [String(i), e.retired_at]), 'cookie positions')}`);
297
+ validateCookies(next);
298
+ writes.push([files.cookies, next]); out.cookie_key_rotated = true;
299
+ }
300
+ for (const [file, contents] of writes) writeAtomic(file, JSON.stringify(contents, null, 2) + '\n');
301
+ loadKeys(dir);
302
+ return out;
303
+ } finally { owner.release(); }
304
+ }
305
+ // Only the lifetime lock owner can prune, before loading the provider's signing keys.
306
+ function pruneKeys(dir, now) {
307
+ const files = asFiles(dir);
308
+ const jwks = readJwks(dir), cookies = readCookies(dir), changed = { pruned: 0 };
309
+ const j = prunedJwks(jwks, now), c = prunedCookies(cookies, now);
310
+ if (!sameKeys(j, jwks)) { writeAtomic(files.jwks, JSON.stringify(validateJwks(j), null, 2) + '\n'); changed.pruned += jwks.keys.length - j.keys.length; }
311
+ if (!sameKeys(c, cookies)) { writeAtomic(files.cookies, JSON.stringify(validateCookies(c), null, 2) + '\n'); changed.pruned += cookies.keys.length - c.keys.length; }
312
+ return changed;
313
+ }
314
+
315
+ // `init`: create the directory, as.json and the keys. It never overwrites a key and never changes an existing public_url.
316
+ export function initAsFiles(dir, { publicUrl, allowHttp = false, loopback = false }) {
317
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
318
+ fs.chmodSync(dir, 0o700);
319
+ assertPrivateDir(dir);
320
+ const files = asFiles(dir);
321
+ const wanted = parseAsConfig({ version: 1, public_url: publicUrl, callbacks: [...DEFAULT_CALLBACKS] }, { allowHttp, loopback });
322
+ // Reinitializing complete state is read-only. Any creation must own the same lock as a server or rotation.
323
+ const complete = [files.config, files.jwks, files.cookies].every(file => fs.existsSync(file));
324
+ const owner = complete ? null : acquireAsOwner(dir);
325
+ try {
326
+ const created = [];
327
+ if (fs.existsSync(files.config)) {
328
+ const existing = loadAsConfig(dir, { allowHttp, loopback });
329
+ if (existing.public_url !== wanted.public_url) fail(`as.json already names ${existing.public_url}; changing the public URL changes the issuer and ends every connection. Remove ${files.config} to start over`);
330
+ } else {
331
+ writeAtomic(files.config, JSON.stringify({ version: 1, public_url: wanted.public_url, callbacks: wanted.callbacks }, null, 2) + '\n');
332
+ created.push('as.json');
333
+ }
334
+ const hasJwks = fs.existsSync(files.jwks), hasCookies = fs.existsSync(files.cookies);
335
+ if (hasJwks !== hasCookies) fail('one key file exists and the other is missing; refusing to guess. Fix or remove both');
336
+ if (!hasJwks) {
337
+ const jwk = newEcKey();
338
+ writeAtomic(files.jwks, JSON.stringify({ signing_kid: jwk.kid, retired: {}, keys: [jwk] }, null, 2) + '\n');
339
+ writeAtomic(files.cookies, JSON.stringify({ keys: [{ key: randomBytes(32).toString('base64url') }] }, null, 2) + '\n');
340
+ created.push('as-jwks.json', 'as-cookie-keys.json');
341
+ }
342
+ loadKeys(dir); // read back what was written
343
+ return { dir, public_url: wanted.public_url, created };
344
+ } finally { owner?.release(); }
345
+ }
346
+
347
+ export const normalizeCode = value => String(value ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '');