@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.
- package/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
package/src/workers.mjs
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import { readEnv } from './env.mjs';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
8
|
+
import { writeAtomic } from './as-files.mjs';
|
|
9
|
+
import { parseExecution } from './execution.mjs';
|
|
10
|
+
|
|
11
|
+
const fail=message=>{throw new Error(`workers: ${message}`);};
|
|
12
|
+
const object=(v,keys)=>{if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).some(k=>!keys.includes(k))) fail(`expected object with keys ${keys.join(', ')}`);};
|
|
13
|
+
const text=v=>{if(typeof v!=='string'||!v||v.length>2048) fail('connection fields must be non-empty strings');return v;};
|
|
14
|
+
const legacyWorker={connections:[],capabilities:new Set(['t3']),guidance:'resume'};
|
|
15
|
+
const repoPart=/^[A-Za-z0-9_.-]+$/;
|
|
16
|
+
function validRepoName(repo) {
|
|
17
|
+
if(typeof repo!=='string'||repo.split('/').length!==2) return false;
|
|
18
|
+
return repo.split('/').every(part=>repoPart.test(part)&&part!=='.'&&part!=='..'&&!part.includes('..'));
|
|
19
|
+
}
|
|
20
|
+
export function parseRepoPattern(pattern) {
|
|
21
|
+
if(typeof pattern!=='string'||!pattern) fail('repos must contain exact OWNER/REPO entries');
|
|
22
|
+
if(!validRepoName(pattern)) fail(`invalid repository "${pattern}"; use exact OWNER/REPO (wildcards are unsupported)`);
|
|
23
|
+
return pattern;
|
|
24
|
+
}
|
|
25
|
+
function normalizeRepoSettings(config,name) {
|
|
26
|
+
if(Object.hasOwn(config,'repo_access')) fail(`${name}.repo_access is unsupported; use an exact repos list`);
|
|
27
|
+
if(Object.hasOwn(config,'denied_repos')) fail(`${name}.denied_repos is unsupported; use an exact repos list`);
|
|
28
|
+
const hasRepos=Object.hasOwn(config,'repos');
|
|
29
|
+
if(hasRepos&&(!Array.isArray(config.repos)||config.repos.some(r=>typeof r!=='string'))) fail(`${name}.repos must be an array of exact OWNER/REPO entries`);
|
|
30
|
+
const repos=hasRepos?config.repos.map(parseRepoPattern):[];
|
|
31
|
+
if(repos&&new Set(repos.map(r=>r.toLowerCase())).size!==repos.length) fail(`${name}.repos must not contain duplicate repositories`);
|
|
32
|
+
return {repos};
|
|
33
|
+
}
|
|
34
|
+
function repoMatches(pattern,repo) {
|
|
35
|
+
if(!validRepoName(repo)) return false;
|
|
36
|
+
const [owner,name]=repo.split('/'),[allowedOwner,allowedName]=pattern.split('/');
|
|
37
|
+
return owner.toLowerCase()===allowedOwner.toLowerCase()&&name.toLowerCase()===allowedName.toLowerCase();
|
|
38
|
+
}
|
|
39
|
+
// Only configuration loading chooses legacy semantics; claims record the returned lane scope as a fact.
|
|
40
|
+
export const LEGACY_PROFILE={legacy:true,workers:new Map([['dot',legacyWorker]]),resolve:()=> 'dot',laneScope:'subject',defaultExecution:'host',
|
|
41
|
+
allowsRepo:()=>false,repoPolicy:worker=>worker==='dot'?{mode:'exact',repos:[]}:null};
|
|
42
|
+
// An existing install is a database that already carries a schema. An empty or schema-less bridge.db (a touched file,
|
|
43
|
+
// a restore step) is not one. The check opens read-only, so it never creates or modifies the file.
|
|
44
|
+
export function hasInstalledDatabase(file) {
|
|
45
|
+
let db;
|
|
46
|
+
try {
|
|
47
|
+
if(!fs.statSync(file).size) return false;
|
|
48
|
+
db=new DatabaseSync(file,{readOnly:true});
|
|
49
|
+
return db.prepare('PRAGMA user_version').get().user_version>0;
|
|
50
|
+
} catch { return false; }
|
|
51
|
+
finally { try { db?.close(); } catch {} }
|
|
52
|
+
}
|
|
53
|
+
// `dalan init --legacy` writes this file next to the generated authorization-server files. The server treats it as the
|
|
54
|
+
// owner's explicit choice of the single-worker legacy profile, so a first start needs no environment variable.
|
|
55
|
+
export const LEGACY_MARKER_FILE='legacy-profile';
|
|
56
|
+
export const legacyMarkerPath=configDir=>path.join(configDir,LEGACY_MARKER_FILE);
|
|
57
|
+
export function writeLegacyMarker(configDir) { writeAtomic(legacyMarkerPath(configDir),'legacy\n'); }
|
|
58
|
+
export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
|
|
59
|
+
object(value,['workers','default_execution']); object(value.workers,Object.keys(value.workers??{}));
|
|
60
|
+
const workers=new Map();
|
|
61
|
+
for(const [name,config] of Object.entries(value.workers)) {
|
|
62
|
+
if(name==='pool'||name==='unknown') fail(`worker name "${name}" is reserved and unsupported`);
|
|
63
|
+
if(!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) fail('invalid worker name');
|
|
64
|
+
if(Object.hasOwn(config??{},'pool')) fail(`${name}.pool is not supported`);
|
|
65
|
+
object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination']);
|
|
66
|
+
const repoSettings=normalizeRepoSettings(config,name);
|
|
67
|
+
if(config.guidance!==undefined&&config.guidance!=='resume') fail(`${name}.guidance may only be "resume"`);
|
|
68
|
+
if(builtin&&config.connections!==undefined&&!(Array.isArray(config.connections)&&!config.connections.length)) fail(`${name}.connections must be absent in built-in mode; connections are recorded by dalan connect approve`);
|
|
69
|
+
if(!builtin&&(!Array.isArray(config.connections)||!config.connections.length)) fail(`${name} needs connections`);
|
|
70
|
+
const connections=(builtin?[]:config.connections).map(record=>{
|
|
71
|
+
object(record,['issuer','subject','client_id','connection_id']);
|
|
72
|
+
const result=Object.fromEntries(Object.entries(record).map(([k,v])=>[k,text(v)]));
|
|
73
|
+
text(result.issuer);
|
|
74
|
+
// The operator names the principal. connection_id and client_id only narrow it, so a record without a subject would
|
|
75
|
+
// let any other allowed subject that presents the same pin become this worker.
|
|
76
|
+
if(!result.subject) fail(`${name}: every connection record needs a subject; add "subject" (the token's sub claim) to the record`);
|
|
77
|
+
text(result.subject);
|
|
78
|
+
if(!result.connection_id) text(result.client_id);
|
|
79
|
+
return result;
|
|
80
|
+
});
|
|
81
|
+
const caps=config.capabilities??[];
|
|
82
|
+
if(!Array.isArray(caps)||caps.some(c=>c!=='t3')) fail('capabilities may only contain t3');
|
|
83
|
+
workers.set(name,{connections,capabilities:new Set(caps),...(config.guidance?{guidance:config.guidance}:{}),...repoSettings,
|
|
84
|
+
...(Object.hasOwn(config,'destination')?{destination:parseDestinationDeclaration(config.destination)}:{})});
|
|
85
|
+
}
|
|
86
|
+
if(!workers.size) fail('workers must not be empty');
|
|
87
|
+
const defaultExecution=value.default_execution===undefined?'none':parseExecution(value.default_execution,'workers: default_execution');
|
|
88
|
+
return {workers,...(builtin&&builtinConnectionIds?{builtinConnectionIds}:{}),laneScope:'worker',defaultExecution,allowsRepo(worker,repo){
|
|
89
|
+
const setting=workers.get(worker);
|
|
90
|
+
if(!setting||!validRepoName(repo)) return false;
|
|
91
|
+
return setting.repos.some(pattern=>repoMatches(pattern,repo));
|
|
92
|
+
},repoPolicy(worker){
|
|
93
|
+
const setting=workers.get(worker);
|
|
94
|
+
if(!setting) return null;
|
|
95
|
+
return {mode:'exact',repos:[...setting.repos]};
|
|
96
|
+
},resolve:principal=>{
|
|
97
|
+
if(principal.local&&workers.has('dot')) return 'dot';
|
|
98
|
+
const matches=[];
|
|
99
|
+
for(const [name,worker] of workers) for(const record of worker.connections)
|
|
100
|
+
if(Object.entries(record).every(([key,v])=>principal[key]===v)) matches.push(name);
|
|
101
|
+
if(matches.length!==1) {
|
|
102
|
+
const code=matches.length?'conflicting_connection':'unknown_connection';
|
|
103
|
+
throw Object.assign(new Error(code),{code});
|
|
104
|
+
}
|
|
105
|
+
return matches[0];
|
|
106
|
+
}};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const destinationFields=['operator','provider','data_categories','retention','training','terms'];
|
|
110
|
+
function parseDestinationDeclaration(value) {
|
|
111
|
+
object(value,destinationFields);
|
|
112
|
+
const result={};
|
|
113
|
+
for(const field of destinationFields) {
|
|
114
|
+
const entry=value[field]??null;
|
|
115
|
+
if(field==='data_categories') {
|
|
116
|
+
if(entry!==null&&(!Array.isArray(entry)||entry.length>32||entry.some(x=>typeof x!=='string'||!x.trim()||x.length>256)))
|
|
117
|
+
fail('destination.data_categories must be null or at most 32 nonempty strings');
|
|
118
|
+
result[field]=entry===null?null:[...new Set(entry)].sort();
|
|
119
|
+
} else {
|
|
120
|
+
if(entry!==null&&(typeof entry!=='string'||!entry.trim()||entry.length>2048))
|
|
121
|
+
fail('destination.'+field+' must be null or a nonempty string of at most 2048 characters');
|
|
122
|
+
result[field]=entry;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
// The digest of the connections a worker has now. A retry compares it with the approved snapshot without a full disclosure.
|
|
128
|
+
export function connectionsDigest(profile,worker) {
|
|
129
|
+
const connections=profile.builtinConnectionIds
|
|
130
|
+
? [...new Set(profile.builtinConnectionIds(worker).map(text))].sort()
|
|
131
|
+
: (profile.workers.get(worker).connections??[]).map(connection=>
|
|
132
|
+
JSON.stringify([connection.issuer??null,connection.subject??null,connection.client_id??null,connection.connection_id??null])).sort();
|
|
133
|
+
return 'sha256:'+createHash('sha256').update(JSON.stringify(connections)).digest('hex');
|
|
134
|
+
}
|
|
135
|
+
// Identity covers the normalized declaration, worker, execution and connection identities.
|
|
136
|
+
// Repository policy is a separate current restriction, not part of destination identity.
|
|
137
|
+
export function destinationDisclosure(profile,worker,execution,assignment={}) {
|
|
138
|
+
if(!profile?.workers||!profile.workers.has(worker))throw new Error('destination configuration unavailable for worker '+worker);
|
|
139
|
+
const declaration=profile.workers.get(worker).destination;
|
|
140
|
+
if(declaration===undefined)return null;
|
|
141
|
+
// Built-in mode records connections through dalan connect approve, so a
|
|
142
|
+
// worker's configured connections are always empty there; the live set can
|
|
143
|
+
// only come from the callback. Without it the disclosure would silently bind
|
|
144
|
+
// the digest of the empty set, so refuse loudly instead. External-OAuth
|
|
145
|
+
// workers always carry non-empty configured connections, so they never hit
|
|
146
|
+
// this branch.
|
|
147
|
+
if(typeof profile.builtinConnectionIds!=='function'&&(profile.workers.get(worker).connections??[]).length===0)
|
|
148
|
+
throw new Error('destination live-connection callback required for worker '+worker+' in built-in mode');
|
|
149
|
+
const connections_digest=connectionsDigest(profile,worker);
|
|
150
|
+
const identity={schema_version:1,worker,execution,connections_digest,declaration:parseDestinationDeclaration(declaration)};
|
|
151
|
+
const revision='sha256:'+createHash('sha256').update(JSON.stringify(identity)).digest('hex');
|
|
152
|
+
const repositories=(assignment.inputs??[]).filter(input=>input?.github_repo!==undefined).map(input=>input.github_repo);
|
|
153
|
+
return {...identity,revision,
|
|
154
|
+
assurance:{worker:'checked',execution:'checked',...Object.fromEntries(destinationFields.map(field=>[field,identity.declaration[field]===null?'unknown':'declared']))},
|
|
155
|
+
policy:{assurance:'checked',allowed:repositories.every(repo=>profile.allowsRepo(worker,repo)),repositories}};
|
|
156
|
+
}
|
|
157
|
+
export function destinationDifferences(approved,current) {
|
|
158
|
+
const fields=['worker','execution','connections_digest',...destinationFields];
|
|
159
|
+
return fields.flatMap(field=>{
|
|
160
|
+
const before=destinationFields.includes(field)?approved?.declaration?.[field]??null:approved?.[field]??null;
|
|
161
|
+
const after=destinationFields.includes(field)?current?.declaration?.[field]??null:current?.[field]??null;
|
|
162
|
+
return JSON.stringify(before)===JSON.stringify(after)?[]:[{field,approved:before,current:after}];
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
export function destinationError(details) {
|
|
166
|
+
return Object.assign(new Error(JSON.stringify(details)),{destination:details});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function loadWorkers(file=readEnv('DALAN_WORKERS_FILE')||defaultPath(os.homedir(),'.config/dot-bridge/workers.json'),options={}) {
|
|
170
|
+
try {
|
|
171
|
+
if((fs.statSync(file).mode&0o777)!==0o600) fail('file must be mode 0600');
|
|
172
|
+
const {auditGrants=false,...parseOptions}=options;
|
|
173
|
+
const profile=parseWorkers(JSON.parse(fs.readFileSync(file,'utf8')),parseOptions);
|
|
174
|
+
if(auditGrants) auditProfileGrants(file,profile,parseOptions);
|
|
175
|
+
return profile;
|
|
176
|
+
} catch(error) {if(error.code==='ENOENT') return legacyRepoProfile(file,options.auditGrants===true);throw error;}
|
|
177
|
+
}
|
|
178
|
+
export function loadOwnerWorkers(file=readEnv('DALAN_WORKERS_FILE')||defaultPath(os.homedir(),'.config/dot-bridge/workers.json')) {
|
|
179
|
+
try {
|
|
180
|
+
if((fs.statSync(file).mode&0o777)!==0o600) fail('file must be mode 0600');
|
|
181
|
+
return parseOwnerWorkers(JSON.parse(fs.readFileSync(file,'utf8')));
|
|
182
|
+
} catch(error) { if(error.code==='ENOENT') return legacyRepoProfile(file);throw error; }
|
|
183
|
+
}
|
|
184
|
+
function parseOwnerWorkers(value) {
|
|
185
|
+
const entries=Object.values(value?.workers??{});
|
|
186
|
+
// Built-in profiles permit both absent and empty connection arrays. Only persisted records imply external OAuth.
|
|
187
|
+
const external=entries.some(worker=>Array.isArray(worker?.connections)&&worker.connections.length>0);
|
|
188
|
+
return parseWorkers(value,{builtin:!external});
|
|
189
|
+
}
|
|
190
|
+
export function resolveWorker(profile,principal) {
|
|
191
|
+
if(principal.builtin) {
|
|
192
|
+
const name=principal.connection?.worker;
|
|
193
|
+
if(typeof name!=='string'||!profile.workers.has(name)) throw Object.assign(new Error('unknown_connection'),{code:'unknown_connection'});
|
|
194
|
+
return name;
|
|
195
|
+
}
|
|
196
|
+
return profile.resolve(principal);
|
|
197
|
+
}
|
|
198
|
+
export const visibleTargets=(profile,worker)=>profile.workers.has(worker)?[worker]:[];
|
|
199
|
+
export const canSee=(profile,worker,target)=>profile.workers.has(worker)&&worker===target;
|
|
200
|
+
export const hasCapability=(profile,worker,capability)=>profile.workers.get(worker)?.capabilities.has(capability)===true;
|
|
201
|
+
export function assertTarget(profile,worker) {
|
|
202
|
+
if(worker==='pool') throw new Error('worker "pool" is not supported');
|
|
203
|
+
if(!profile.workers.has(worker)) throw new Error(`unknown worker "${worker}"; configured workers: ${[...profile.workers.keys()].join(', ')}`);
|
|
204
|
+
return worker;
|
|
205
|
+
}
|
|
206
|
+
// One source of truth for a fresh generic host: one named worker, no t3 capability, no host execution. Never overwrites.
|
|
207
|
+
export function writeGenericProfile(file,name) {
|
|
208
|
+
parseWorkers({workers:{[name]:{}}},{builtin:true});
|
|
209
|
+
fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
|
|
210
|
+
try { fs.writeFileSync(file,`${JSON.stringify({workers:{[name]:{repos:[]}},default_execution:'none'},null,2)}\n`,{mode:0o600,flag:'wx'}); }
|
|
211
|
+
catch(error) { if(error.code==='EEXIST') throw new Error(`${file} already exists; init does not overwrite a worker profile`); throw error; }
|
|
212
|
+
fs.chmodSync(file,0o600);
|
|
213
|
+
return file;
|
|
214
|
+
}
|
|
215
|
+
// One private journal commits the seed and its audit together. Profile publication is
|
|
216
|
+
// restartable; an interrupted migration reuses this seed instead of scanning again.
|
|
217
|
+
export const workerRepoMigrationFile = file => path.join(path.dirname(file), path.basename(file, '.json') + '-repos.json');
|
|
218
|
+
function readRepoMigration(file) {
|
|
219
|
+
const journal=workerRepoMigrationFile(file);
|
|
220
|
+
let stat;
|
|
221
|
+
try {stat=fs.lstatSync(journal);} catch(error) {if(error.code==='ENOENT')return null;throw error;}
|
|
222
|
+
if(!stat.isFile()||(stat.mode&0o777)!==0o600||(typeof process.getuid==='function'&&stat.uid!==process.getuid()))fail('repository migration journal must be an owned mode-0600 regular file');
|
|
223
|
+
let value;try {value=JSON.parse(fs.readFileSync(journal,'utf8'));} catch {fail('repository migration journal is not valid JSON');}
|
|
224
|
+
object(value,['version','entries']);
|
|
225
|
+
if(value.version!==1||!Array.isArray(value.entries))fail('invalid repository migration journal');
|
|
226
|
+
const seen=new Set();
|
|
227
|
+
for(const entry of value.entries) {
|
|
228
|
+
object(entry,['worker','kind','repos','complete','event','queued_repositories']);
|
|
229
|
+
if(!/^[a-z][a-z0-9_-]{0,31}$/.test(entry.worker)||seen.has(entry.worker)||!['legacy','profile'].includes(entry.kind)||typeof entry.complete!=='boolean')fail('invalid repository migration entry');
|
|
230
|
+
seen.add(entry.worker);
|
|
231
|
+
normalizeRepoSettings({repos:entry.repos},entry.worker);
|
|
232
|
+
object(entry.event,['event_id','at','actor','worker','before','after']);
|
|
233
|
+
object(entry.event.actor,['host_uid']);object(entry.event.before,['mode','repos']);object(entry.event.after,['mode','repos']);
|
|
234
|
+
if(typeof entry.event.at!=='string'||!/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(entry.event.at)||!Number.isFinite(Date.parse(entry.event.at))||!entry.event.actor||!(entry.event.actor.host_uid===null||Number.isSafeInteger(entry.event.actor.host_uid)&&entry.event.actor.host_uid>=0))fail('invalid repository migration audit identity');
|
|
235
|
+
if(entry.event?.worker!==entry.worker||entry.event.before?.mode!=='legacy-any'||entry.event.before.repos!==null||entry.event.after?.mode!=='exact'||!Array.isArray(entry.event.after.repos)||entry.event.after.repos.some(repo=>!validRepoName(repo))||!/^[0-9a-f-]{36}$/.test(entry.event.event_id))fail('invalid repository migration audit');
|
|
236
|
+
if(entry.queued_repositories!==undefined) {
|
|
237
|
+
if(!Array.isArray(entry.queued_repositories))fail('invalid queued repository evidence');
|
|
238
|
+
for(const queued of entry.queued_repositories) {
|
|
239
|
+
object(queued,['repo','request_ids']);
|
|
240
|
+
if(!validRepoName(queued.repo)||!entry.event.after.repos.some(repo=>repo.toLowerCase()===queued.repo.toLowerCase()))fail('queued repository is not in the original seed');
|
|
241
|
+
if(!Array.isArray(queued.request_ids)||!queued.request_ids.length||queued.request_ids.some(id=>typeof id!=='string'||!id)||new Set(queued.request_ids).size!==queued.request_ids.length)fail('invalid queued repository job IDs');
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return value;
|
|
246
|
+
}
|
|
247
|
+
function legacyRepoProfile(file,auditGrants=false) {
|
|
248
|
+
const entry=readRepoMigration(file)?.entries.find(item=>item.worker==='dot'&&item.kind==='legacy');
|
|
249
|
+
if(!entry)return LEGACY_PROFILE;
|
|
250
|
+
const repos=auditGrants?(reconcileGrants(file,()=>new Map([['dot',readRepoMigration(file)?.entries.find(item=>item.worker==='dot'&&item.kind==='legacy')?.repos??[]]])).applied.get('dot')??[]):entry.repos;
|
|
251
|
+
return {...LEGACY_PROFILE,allowsRepo:(worker,repo)=>worker==='dot'&&repos.some(pattern=>repoMatches(pattern,repo)),
|
|
252
|
+
repoPolicy:worker=>worker==='dot'?{mode:'exact',repos:[...repos],source:'admitted-history'}:null};
|
|
253
|
+
}
|
|
254
|
+
// Grants that stand in the configuration with no audit record. The audit trail is the migration journal's events followed
|
|
255
|
+
// by workers-audit.jsonl; a worker's audited list is the `after` list of its latest event (empty when it has none).
|
|
256
|
+
// A hand edit of workers.json (or of the legacy journal) is not a CLI change and writes no event itself.
|
|
257
|
+
//
|
|
258
|
+
// The audit log is append-only text that a same-user process can delete. Every append therefore also records a checkpoint
|
|
259
|
+
// (byte length and SHA-256 of the log, last event id) in a private SQLite file beside it, and that file doubles as the
|
|
260
|
+
// lock that serializes every writer of the audit. A log that is missing, shorter than its checkpoint, or whose recorded
|
|
261
|
+
// prefix changed fails closed: no grant without a matching event applies. Without a checkpoint (an install that was never
|
|
262
|
+
// audited) the existing list is recorded once. A same-user actor who deletes the checkpoint file and the log together
|
|
263
|
+
// leaves an install that looks never-audited; that actor can equally rewrite workers.json and the queue, so this check
|
|
264
|
+
// detects accidents and one-sided tampering, not a full compromise of the account.
|
|
265
|
+
const auditFileOf=workersFile=>path.join(path.dirname(workersFile),'workers-audit.jsonl');
|
|
266
|
+
const checkpointFileOf=workersFile=>path.join(path.dirname(workersFile),'workers-audit-checkpoint.sqlite');
|
|
267
|
+
const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
268
|
+
const CHECKPOINT_SQL='CREATE TABLE IF NOT EXISTS checkpoint(id INTEGER PRIMARY KEY CHECK(id=1),size INTEGER NOT NULL,sha256 TEXT NOT NULL,last_event_id TEXT)';
|
|
269
|
+
export const AUDIT_INTEGRITY_HINT='Grants without a matching audit event are denied. Re-approve each grant you want with dalan worker allow NAME OWNER/REPO; the first allow or deny resets workers.json to the grants the surviving audit proves and records a new baseline.';
|
|
270
|
+
// Serializes read, compare and append for every writer of the audit (loaders and the worker allow/deny commands).
|
|
271
|
+
export function withAuditLock(workersFile,fn) {
|
|
272
|
+
if(!fs.existsSync(path.dirname(workersFile))) return fn(null);
|
|
273
|
+
const sidecar=checkpointFileOf(workersFile);
|
|
274
|
+
try {fs.closeSync(fs.openSync(sidecar,'wx',0o600));} catch(error) {if(error.code!=='EEXIST')throw error;}
|
|
275
|
+
const stat=fs.lstatSync(sidecar);
|
|
276
|
+
if(!stat.isFile()||(stat.mode&0o777)!==0o600||(typeof process.getuid==='function'&&stat.uid!==process.getuid())) throw new Error('audit checkpoint file is not an owned mode-0600 regular file');
|
|
277
|
+
const db=new DatabaseSync(sidecar);
|
|
278
|
+
try {
|
|
279
|
+
db.exec('PRAGMA busy_timeout=30000');
|
|
280
|
+
db.exec('BEGIN EXCLUSIVE');
|
|
281
|
+
let result;
|
|
282
|
+
try {db.exec(CHECKPOINT_SQL);result=fn(db);} catch(error) {try {db.exec('ROLLBACK');} catch {/* report the original error */}throw error;}
|
|
283
|
+
db.exec('COMMIT');
|
|
284
|
+
return result;
|
|
285
|
+
} finally {db.close();}
|
|
286
|
+
}
|
|
287
|
+
// null: no checkpoint (never audited). {error}: present but unreadable, which fails closed like a mismatch.
|
|
288
|
+
function readCheckpoint(workersFile,db) {
|
|
289
|
+
const read=handle=>handle.prepare('SELECT size,sha256,last_event_id FROM checkpoint WHERE id=1').get()??null;
|
|
290
|
+
if(db) return read(db);
|
|
291
|
+
const sidecar=checkpointFileOf(workersFile);
|
|
292
|
+
if(!fs.existsSync(sidecar)) return null;
|
|
293
|
+
let handle;
|
|
294
|
+
try {
|
|
295
|
+
handle=new DatabaseSync(sidecar,{readOnly:true});
|
|
296
|
+
handle.exec('PRAGMA busy_timeout=30000');
|
|
297
|
+
if(!handle.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='checkpoint'").get()) return null;
|
|
298
|
+
return read(handle);
|
|
299
|
+
} catch {return {error:'the audit checkpoint cannot be read'};}
|
|
300
|
+
finally {handle?.close();}
|
|
301
|
+
}
|
|
302
|
+
function recordCheckpoint(db,auditFile) {
|
|
303
|
+
if(!db) return;
|
|
304
|
+
const bytes=fs.readFileSync(auditFile),lines=bytes.toString('utf8').split('\n').filter(Boolean);
|
|
305
|
+
let last=null;try {last=JSON.parse(lines.at(-1)??'null')?.event_id??null;} catch {/* torn tail; the next load reports it */}
|
|
306
|
+
db.prepare('INSERT OR REPLACE INTO checkpoint(id,size,sha256,last_event_id) VALUES (1,?,?,?)').run(bytes.length,sha256(bytes),last);
|
|
307
|
+
}
|
|
308
|
+
// The log may be longer than the checkpoint (an append whose checkpoint did not commit), never shorter or different.
|
|
309
|
+
function integrityFailure(history,checkpoint) {
|
|
310
|
+
if(!checkpoint) return null;
|
|
311
|
+
const where='the audit log workers-audit.jsonl';
|
|
312
|
+
if(checkpoint.error) return checkpoint.error;
|
|
313
|
+
if(!history.raw) return `${where} is missing or unreadable, but audit events were recorded`;
|
|
314
|
+
if(history.raw.length<checkpoint.size) return `${where} is shorter than its recorded checkpoint (truncated)`;
|
|
315
|
+
if(sha256(history.raw.subarray(0,checkpoint.size))!==checkpoint.sha256) return `${where} does not match its recorded checkpoint (changed)`;
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
function auditedRepoState(workersFile,db) {
|
|
319
|
+
const auditFile=auditFileOf(workersFile);
|
|
320
|
+
const history=readWorkerRepoHistory(auditFile,{workersFile,maxBytes:Infinity,keepRaw:true});
|
|
321
|
+
const state=new Map();
|
|
322
|
+
for(const event of history.events) if(event.after.mode==='exact') state.set(event.worker,event.after.repos);
|
|
323
|
+
let pending=new Set();
|
|
324
|
+
try {pending=new Set((readRepoMigration(workersFile)?.entries??[]).filter(entry=>entry.kind==='profile'&&!entry.complete).map(entry=>entry.worker));}
|
|
325
|
+
catch {/* readWorkerRepoHistory already reports an unreadable journal as incomplete */}
|
|
326
|
+
const checkpoint=readCheckpoint(workersFile,db);
|
|
327
|
+
return {auditFile,history,state,pending,checkpoint,integrity_error:integrityFailure(history,checkpoint)};
|
|
328
|
+
}
|
|
329
|
+
const repoKey=repo=>repo.toLowerCase();
|
|
330
|
+
const diffRepos=(from,to)=>{const keys=new Set(from.map(repoKey));return to.filter(repo=>!keys.has(repoKey(repo)));};
|
|
331
|
+
function evaluateGrants(workersFile,current,write,db) {
|
|
332
|
+
const {auditFile,history,state,pending,checkpoint,integrity_error}=auditedRepoState(workersFile,db);
|
|
333
|
+
const applied=new Map(),unaudited=[];
|
|
334
|
+
let needsWrite=false;
|
|
335
|
+
for(const [worker,repos] of current) {
|
|
336
|
+
const audited=state.get(worker)??[];
|
|
337
|
+
const added=diffRepos(audited,repos),removed=diffRepos(repos,audited);
|
|
338
|
+
// A pending migration's list comes from its own journal event, which readRepoMigration validates and
|
|
339
|
+
// seedWorkerRepos publishes before it marks the worker complete: the journal is the audit record for that list.
|
|
340
|
+
if(pending.has(worker)||(!added.length&&!removed.length)) {applied.set(worker,[...repos]);continue;}
|
|
341
|
+
let recorded=false;
|
|
342
|
+
if(write&&history.complete&&!integrity_error) {
|
|
343
|
+
needsWrite=true;
|
|
344
|
+
if(db) {
|
|
345
|
+
try {appendWorkerRepoAudit(auditFile,worker,{mode:'exact',repos:audited},{mode:'exact',repos},'config-reconcile',db);recorded=true;}
|
|
346
|
+
catch {/* fail closed below */}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
// A grant takes effect only once its audit event exists. A removal needs no event to be safe.
|
|
350
|
+
applied.set(worker,recorded?[...repos]:repos.filter(repo=>!added.some(grant=>repoKey(grant)===repoKey(repo))));
|
|
351
|
+
if(added.length&&!recorded)unaudited.push({worker,repos:added});
|
|
352
|
+
}
|
|
353
|
+
// Bind an unbound log (no checkpoint yet), or a log longer than its checkpoint, before anything else relies on it.
|
|
354
|
+
if(write&&history.complete&&!integrity_error&&history.raw&&(!checkpoint||checkpoint.size!==history.raw.length)) {
|
|
355
|
+
needsWrite=true;
|
|
356
|
+
if(db) recordCheckpoint(db,auditFile);
|
|
357
|
+
}
|
|
358
|
+
return {applied,unaudited,history,integrity_error,needsWrite};
|
|
359
|
+
}
|
|
360
|
+
// `readCurrent` returns the current grants per worker. It runs again inside the lock, so a decision never rests on a
|
|
361
|
+
// view that a concurrent allow, deny or load has since replaced.
|
|
362
|
+
function reconcileGrants(workersFile,readCurrent,{write=true}={}) {
|
|
363
|
+
const first=evaluateGrants(workersFile,readCurrent(),write,null);
|
|
364
|
+
if(!write||!first.needsWrite) return first;
|
|
365
|
+
try {return withAuditLock(workersFile,db=>evaluateGrants(workersFile,readCurrent(),true,db));}
|
|
366
|
+
catch {
|
|
367
|
+
// The lock or audit is unusable: fail closed, apply nothing that the audit does not already list.
|
|
368
|
+
const denied=new Map(first.unaudited.map(item=>[item.worker,item.repos.map(repoKey)]));
|
|
369
|
+
return {...first,applied:new Map([...first.applied].map(([worker,repos])=>[worker,repos.filter(repo=>!(denied.get(worker)??[]).includes(repoKey(repo)))]))};
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
function auditProfileGrants(file,profile,parseOptions) {
|
|
373
|
+
const readCurrent=()=>{
|
|
374
|
+
const fresh=parseWorkers(JSON.parse(fs.readFileSync(file,'utf8')),parseOptions);
|
|
375
|
+
return new Map([...fresh.workers].map(([name,setting])=>[name,setting.repos]));
|
|
376
|
+
};
|
|
377
|
+
const {applied}=reconcileGrants(file,readCurrent);
|
|
378
|
+
for(const [name,setting] of profile.workers) setting.repos=applied.get(name)??[];
|
|
379
|
+
}
|
|
380
|
+
// Read-only view for doctor and worker list: grants that have no audit record yet, and grants the bridge recorded itself.
|
|
381
|
+
export function inspectGrantAudit(file) {
|
|
382
|
+
const readCurrent=()=>{const profile=loadOwnerWorkers(file);return new Map([...profile.workers.keys()].map(name=>[name,profile.repoPolicy(name).repos]));};
|
|
383
|
+
const {unaudited,history,integrity_error}=reconcileGrants(file,readCurrent,{write:false});
|
|
384
|
+
const recorded=history.events.filter(event=>event.source==='config-reconcile'&&diffRepos(event.before.repos??[],event.after.repos??[]).length)
|
|
385
|
+
.map(event=>({event_id:event.event_id,at:event.at,worker:event.worker,repos:diffRepos(event.before.repos??[],event.after.repos??[])}));
|
|
386
|
+
return {unaudited,recorded,history_error:history.error,integrity_error:integrity_error??null};
|
|
387
|
+
}
|
|
388
|
+
export function seedWorkerRepos(file,db,{existingInstall=true,migrationNow=new Date().toISOString()}={}) {
|
|
389
|
+
let journal=readRepoMigration(file);
|
|
390
|
+
if(!journal) {
|
|
391
|
+
const raw=fs.existsSync(file)?JSON.parse(fs.readFileSync(file,'utf8')):null;
|
|
392
|
+
const names=raw?Object.keys(raw.workers):['dot'];
|
|
393
|
+
const entries=[];
|
|
394
|
+
// One instant for the whole migration, so a job cannot expire between two workers' scans.
|
|
395
|
+
if(typeof migrationNow!=='string'||!Number.isFinite(Date.parse(migrationNow)))fail('invalid repository migration time');
|
|
396
|
+
if(existingInstall)for(const worker of names) {
|
|
397
|
+
if(raw&&Object.hasOwn(raw.workers[worker],'repos'))continue;
|
|
398
|
+
const repos=new Map(),queuedRepositories=new Map();
|
|
399
|
+
// Prior claims and live queued jobs preserve old grants. An expired queued row is no longer live evidence; the
|
|
400
|
+
// service may be offline, so its expiry sweep has not necessarily changed its status yet.
|
|
401
|
+
for(const {request_id,repo,status} of db.prepare(`SELECT a.request_id,json_extract(a.payload,'$.inputs[0].github_repo') AS repo,a.status FROM assignments a
|
|
402
|
+
WHERE a.target_worker=? AND (
|
|
403
|
+
(a.status<>'queued' AND EXISTS (SELECT 1 FROM claims c WHERE c.request_id=a.request_id)) OR
|
|
404
|
+
(a.status='queued' AND a.cancelled_at IS NULL AND (a.valid_until IS NULL OR a.valid_until>? OR
|
|
405
|
+
(COALESCE(a.valid_until_source,'')='queue_p90' AND EXISTS (SELECT 1 FROM claims c WHERE c.request_id=a.request_id))))
|
|
406
|
+
) ORDER BY repo COLLATE NOCASE,a.request_id`).all(worker,migrationNow)) {
|
|
407
|
+
if(!validRepoName(repo))continue;
|
|
408
|
+
const key=repo.toLowerCase();
|
|
409
|
+
if(!repos.has(key))repos.set(key,repo);
|
|
410
|
+
if(status==='queued') {
|
|
411
|
+
const queued=queuedRepositories.get(key)??{repo,request_ids:[]};
|
|
412
|
+
queued.request_ids.push(request_id);
|
|
413
|
+
queuedRepositories.set(key,queued);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const exact=[...repos.values()].sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
417
|
+
const queuedExact=[...queuedRepositories.values()].sort((a,b)=>a.repo.toLowerCase().localeCompare(b.repo.toLowerCase()));
|
|
418
|
+
const event={event_id:randomUUID(),at:new Date().toISOString(),actor:{host_uid:typeof process.getuid==='function'?process.getuid():null},worker,
|
|
419
|
+
before:{mode:'legacy-any',repos:null},after:{mode:'exact',repos:exact}};
|
|
420
|
+
// Keep the one-time causal evidence so migrate-repos can show which queued rows justified each repository grant.
|
|
421
|
+
entries.push({worker,kind:raw?'profile':'legacy',repos:exact,complete:!raw,event,queued_repositories:queuedExact});
|
|
422
|
+
}
|
|
423
|
+
const value={version:1,entries},journalFile=workerRepoMigrationFile(file),temp=journalFile+'.'+randomUUID()+'.tmp';
|
|
424
|
+
fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
|
|
425
|
+
try {
|
|
426
|
+
writeAtomic(temp,JSON.stringify(value,null,2)+'\n');
|
|
427
|
+
try {fs.linkSync(temp,journalFile);} catch(error) {if(error.code!=='EEXIST')throw error;}
|
|
428
|
+
const fd=fs.openSync(path.dirname(file),'r');try{fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
|
|
429
|
+
} finally {fs.rmSync(temp,{force:true});}
|
|
430
|
+
journal=readRepoMigration(file);
|
|
431
|
+
}
|
|
432
|
+
for(const entry of journal.entries) {
|
|
433
|
+
if(entry.kind!=='profile'||entry.complete)continue;
|
|
434
|
+
// Never overwrite an explicit list, even after a crash between the two publications.
|
|
435
|
+
if(!fs.existsSync(file))fail('worker profile disappeared during repository migration');
|
|
436
|
+
const raw=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
437
|
+
const worker=raw.workers[entry.worker];
|
|
438
|
+
if(worker&&!Object.hasOwn(worker,'repos')) {
|
|
439
|
+
worker.repos=[...entry.repos];
|
|
440
|
+
parseOwnerWorkers(raw);
|
|
441
|
+
// Preserve an operator's existing workers.json symlink.
|
|
442
|
+
writeAtomic(fs.realpathSync(file),JSON.stringify(raw,null,2)+'\n');
|
|
443
|
+
}
|
|
444
|
+
entry.complete=true;
|
|
445
|
+
writeAtomic(workerRepoMigrationFile(file),JSON.stringify(journal,null,2)+'\n');
|
|
446
|
+
}
|
|
447
|
+
return {workers:journal.entries.map(entry=>{
|
|
448
|
+
const queued=new Map((entry.queued_repositories??[]).map(row=>[row.repo.toLowerCase(),row.request_ids]));
|
|
449
|
+
return {worker:entry.worker,mode:'exact',repos:entry.repos,source:'admitted-history',
|
|
450
|
+
seeded_repositories:entry.event.after.repos.map(repo=>({repo,queued_request_ids:queued.get(repo.toLowerCase())??[]}))};
|
|
451
|
+
})};
|
|
452
|
+
}
|
|
453
|
+
// A grant is recorded before it takes effect, so a grant never stands without its audit event. A removal takes effect
|
|
454
|
+
// first: failing closed is safe, and the error then says that the audit event is missing.
|
|
455
|
+
function commitRepoPolicyChange(action,auditFile,name,before,after,apply,db) {
|
|
456
|
+
if(action!=='allow') {
|
|
457
|
+
apply();
|
|
458
|
+
try { appendWorkerRepoAudit(auditFile,name,before,after,undefined,db); }
|
|
459
|
+
catch(error) { throw new Error(`repository policy was updated, but ${error.message}`); }
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
try { appendWorkerRepoAudit(auditFile,name,before,after,undefined,db); }
|
|
463
|
+
catch(error) { throw new Error(`repository grant not applied: ${error.message}`); }
|
|
464
|
+
try { apply(); }
|
|
465
|
+
catch(error) {
|
|
466
|
+
// The event now describes a grant that did not happen; add the reverse event so the history stays true.
|
|
467
|
+
try { appendWorkerRepoAudit(auditFile,name,after,before,undefined,db); } catch { /* report the original error */ }
|
|
468
|
+
throw error;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
export function updateWorkerRepoPolicy(file,name,action,repo) {
|
|
472
|
+
// Validate before taking the lock, then hold it across the read, the audit append and the config write.
|
|
473
|
+
if(!/^[a-z][a-z0-9_-]{0,31}$/.test(name)||['pool','unknown'].includes(name)) fail('invalid worker name');
|
|
474
|
+
if(!['allow','deny'].includes(action)) fail('invalid repository policy action');
|
|
475
|
+
if(repo==='--any') fail('--any is unsupported; provide an exact OWNER/REPO');
|
|
476
|
+
parseRepoPattern(repo);
|
|
477
|
+
return withAuditLock(file,db=>{
|
|
478
|
+
const recovered=db?resetAfterIntegrityFailure(file,db):null;
|
|
479
|
+
// A repository added by hand since the last load gets its own reconcile event first, so this command's event
|
|
480
|
+
// records only the repository the operator named.
|
|
481
|
+
if(db) evaluateGrants(file,currentGrants(file),true,db);
|
|
482
|
+
const result=applyWorkerRepoPolicy(file,name,action,repo,db);
|
|
483
|
+
return recovered?.length?{...result,reset_to_audited:recovered}:result;
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
// The grants now in the configuration per worker, read without any loader (so no second lock).
|
|
487
|
+
function currentGrants(file) {
|
|
488
|
+
if(fs.existsSync(file)) {
|
|
489
|
+
const profile=parseOwnerWorkers(JSON.parse(fs.readFileSync(file,'utf8')));
|
|
490
|
+
return new Map([...profile.workers].map(([name,setting])=>[name,setting.repos]));
|
|
491
|
+
}
|
|
492
|
+
const journal=readRepoMigration(file);
|
|
493
|
+
return new Map((journal?.entries??[]).filter(entry=>entry.kind==='legacy').map(entry=>[entry.worker,entry.repos]));
|
|
494
|
+
}
|
|
495
|
+
// After the audit log failed its checkpoint, the first allow or deny is the operator's re-approval. It drops every grant
|
|
496
|
+
// that the surviving audit does not list, then records the log as the new baseline. Dropped grants stay denied until
|
|
497
|
+
// the operator allows them again.
|
|
498
|
+
function resetAfterIntegrityFailure(file,db) {
|
|
499
|
+
const {auditFile,state,integrity_error,history}=auditedRepoState(file,db);
|
|
500
|
+
if(!integrity_error) return null;
|
|
501
|
+
const dropped=[];
|
|
502
|
+
const journal=readRepoMigration(file);
|
|
503
|
+
if(fs.existsSync(file)) {
|
|
504
|
+
const raw=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
505
|
+
for(const [worker,setting] of Object.entries(raw.workers??{})) {
|
|
506
|
+
const audited=state.get(worker)??[],listed=Array.isArray(setting.repos)?setting.repos:[];
|
|
507
|
+
// Only drop: keep what both the configuration and the surviving audit list, never add from the audit.
|
|
508
|
+
const kept=listed.filter(repo=>audited.some(k=>repoKey(k)===repoKey(repo)));
|
|
509
|
+
if(kept.length!==listed.length) {dropped.push({worker,repos:listed.filter(repo=>!kept.includes(repo))});setting.repos=kept;}
|
|
510
|
+
}
|
|
511
|
+
if(dropped.length) writeAtomic(fs.realpathSync(file),JSON.stringify(raw,null,2)+'\n');
|
|
512
|
+
} else if(journal) {
|
|
513
|
+
for(const entry of journal.entries) if(entry.kind==='legacy') {
|
|
514
|
+
const audited=state.get(entry.worker)??[];
|
|
515
|
+
const kept=entry.repos.filter(repo=>audited.some(k=>repoKey(k)===repoKey(repo)));
|
|
516
|
+
if(kept.length!==entry.repos.length) {dropped.push({worker:entry.worker,repos:entry.repos.filter(repo=>!kept.includes(repo))});entry.repos=kept;}
|
|
517
|
+
}
|
|
518
|
+
if(dropped.length) writeAtomic(workerRepoMigrationFile(file),JSON.stringify(journal,null,2)+'\n');
|
|
519
|
+
}
|
|
520
|
+
if(history.raw) recordCheckpoint(db,auditFile);
|
|
521
|
+
else db.prepare('DELETE FROM checkpoint').run();
|
|
522
|
+
return dropped;
|
|
523
|
+
}
|
|
524
|
+
function applyWorkerRepoPolicy(file,name,action,repo,db) {
|
|
525
|
+
if(!fs.existsSync(file)) {
|
|
526
|
+
const journal=readRepoMigration(file),entry=journal?.entries.find(item=>item.worker===name&&item.kind==='legacy');
|
|
527
|
+
if(!entry)fail('no workers.json and no seeded repos-only policy; see docs/operations.md#legacy-repository-policy-migration (existing installs: dalan worker migrate-repos; new installs: dalan init --worker NAME)');
|
|
528
|
+
const before={mode:'exact',repos:[...entry.repos]},repos=new Map(entry.repos.map(repo=>[repo.toLowerCase(),repo]));
|
|
529
|
+
if(action==='allow')repos.set(repo.toLowerCase(),repo);else repos.delete(repo.toLowerCase());
|
|
530
|
+
entry.repos=[...repos.values()];
|
|
531
|
+
const after={mode:'exact',repos:[...entry.repos]};
|
|
532
|
+
if(JSON.stringify(before.repos)===JSON.stringify(after.repos))return after;
|
|
533
|
+
commitRepoPolicyChange(action,path.join(path.dirname(file),'workers-audit.jsonl'),name,before,after,
|
|
534
|
+
()=>writeAtomic(workerRepoMigrationFile(file),JSON.stringify(journal,null,2)+'\n'),db);
|
|
535
|
+
return after;
|
|
536
|
+
}
|
|
537
|
+
const stat=fs.lstatSync(file);
|
|
538
|
+
if(!stat.isFile()||stat.isSymbolicLink()) fail('workers file must be a regular file');
|
|
539
|
+
if((stat.mode&0o777)!==0o600) fail('file must be mode 0600');
|
|
540
|
+
const raw=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
541
|
+
const parseProfile=()=>parseOwnerWorkers(raw);
|
|
542
|
+
const profile=parseProfile();
|
|
543
|
+
if(!profile.workers.has(name)) fail(`unknown worker "${name}"; configured workers: ${[...profile.workers.keys()].join(', ')}`);
|
|
544
|
+
const selected=raw.workers[name];
|
|
545
|
+
const before=normalizeRepoSettings(selected,name);
|
|
546
|
+
const repos=new Map(before.repos.map(r=>[r.toLowerCase(),r]));
|
|
547
|
+
if(action==='allow') repos.set(repo.toLowerCase(),repo); else repos.delete(repo.toLowerCase());
|
|
548
|
+
selected.repos=[...repos.values()];
|
|
549
|
+
const after=parseProfile().repoPolicy(name);
|
|
550
|
+
if(JSON.stringify(before.repos)===JSON.stringify(after.repos)) return after;
|
|
551
|
+
commitRepoPolicyChange(action,path.join(path.dirname(file),'workers-audit.jsonl'),name,{mode:'exact',repos:before.repos},after,()=>{
|
|
552
|
+
const temp=`${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
553
|
+
try {
|
|
554
|
+
fs.writeFileSync(temp,`${JSON.stringify(raw,null,2)}\n`,{mode:0o600,flag:'wx'});
|
|
555
|
+
fs.chmodSync(temp,0o600);
|
|
556
|
+
fs.renameSync(temp,file);
|
|
557
|
+
} finally { fs.rmSync(temp,{force:true}); }
|
|
558
|
+
},db);
|
|
559
|
+
return after;
|
|
560
|
+
}
|
|
561
|
+
function appendWorkerRepoAudit(auditFile,worker,before,after,source,db) {
|
|
562
|
+
const event={event_id:randomUUID(),at:new Date().toISOString(),actor:{host_uid:typeof process.getuid==='function'?process.getuid():null},worker,before,after,...(source?{source}:{})};
|
|
563
|
+
try {
|
|
564
|
+
const flags=fs.constants.O_APPEND|fs.constants.O_CREAT|fs.constants.O_WRONLY|(fs.constants.O_NOFOLLOW??0);
|
|
565
|
+
const fd=fs.openSync(auditFile,flags,0o600);
|
|
566
|
+
try {
|
|
567
|
+
if(!fs.fstatSync(fd).isFile()) throw new Error('audit path is not a regular file');
|
|
568
|
+
fs.fchmodSync(fd,0o600);
|
|
569
|
+
const bytes=Buffer.from(JSON.stringify(event)+'\n');
|
|
570
|
+
for(let offset=0;offset<bytes.length;) {
|
|
571
|
+
const written=fs.writeSync(fd,bytes,offset,bytes.length-offset);
|
|
572
|
+
if(!Number.isSafeInteger(written)||written<=0||written>bytes.length-offset) throw new Error('audit append made no valid progress');
|
|
573
|
+
offset+=written;
|
|
574
|
+
}
|
|
575
|
+
fs.fsyncSync(fd);
|
|
576
|
+
} finally { fs.closeSync(fd); }
|
|
577
|
+
const dirfd=fs.openSync(path.dirname(auditFile),'r');try{fs.fsyncSync(dirfd);}finally{fs.closeSync(dirfd);}
|
|
578
|
+
recordCheckpoint(db,auditFile);
|
|
579
|
+
} catch(error) { throw new Error(`its audit event could not be written to ${auditFile}: ${error.message}`); }
|
|
580
|
+
}
|
|
581
|
+
// A bounded snapshot of history must never make the current policy unavailable.
|
|
582
|
+
export function readWorkerRepoHistory(file,{workersFile=path.join(path.dirname(file),'workers.json'),maxBytes=1024*1024,keepRaw=false}={}) {
|
|
583
|
+
let seeded=[],seedError=null;
|
|
584
|
+
try {seeded=readRepoMigration(workersFile)?.entries.map(entry=>entry.event)??[];} catch {seedError='repository migration audit unavailable';}
|
|
585
|
+
let fd;
|
|
586
|
+
try {
|
|
587
|
+
if(fs.lstatSync(file).isSymbolicLink()) throw new Error('unsafe audit file');
|
|
588
|
+
fd=fs.openSync(file,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
|
|
589
|
+
const stat=fs.fstatSync(fd);
|
|
590
|
+
if(!stat.isFile()||(stat.mode&0o777)!==0o600||(typeof process.getuid==='function'&&stat.uid!==process.getuid())) throw new Error('unsafe audit file');
|
|
591
|
+
const offset=Math.max(0,stat.size-maxBytes),bytes=Buffer.alloc(stat.size-offset);
|
|
592
|
+
let read=0;
|
|
593
|
+
while(read<bytes.length) {const n=fs.readSync(fd,bytes,read,bytes.length-read,offset+read);if(!n)break;read+=n;}
|
|
594
|
+
let text=bytes.subarray(0,read).toString('utf8'),complete=offset===0&&read===bytes.length,error=null;
|
|
595
|
+
if(offset>0)text=text.slice(text.indexOf('\n')+1);
|
|
596
|
+
if(text&&!text.endsWith('\n')) {text=text.slice(0,text.lastIndexOf('\n')+1);complete=false;error='incomplete audit record; history counts are unknown';}
|
|
597
|
+
const events=[];
|
|
598
|
+
const snapshot=value=>value&&typeof value==='object'&&(
|
|
599
|
+
(value.mode==='legacy-any'&&value.repos===null)||
|
|
600
|
+
(value.mode==='exact'&&Array.isArray(value.repos)&&value.repos.every(validRepoName)));
|
|
601
|
+
for(const line of text.split('\n').filter(Boolean)) {
|
|
602
|
+
try {
|
|
603
|
+
const event=JSON.parse(line);
|
|
604
|
+
if(!/^[0-9a-f-]{36}$/.test(event?.event_id)||typeof event.at!=='string'||!/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(event.at)||!Number.isFinite(Date.parse(event.at))||
|
|
605
|
+
!/^[a-z][a-z0-9_-]{0,31}$/.test(event.worker)||!event.actor||!(event.actor.host_uid===null||Number.isSafeInteger(event.actor.host_uid)&&event.actor.host_uid>=0)||!snapshot(event.before)||!snapshot(event.after)) throw new Error('invalid record');
|
|
606
|
+
const project=value=>({mode:value.mode,repos:value.repos});
|
|
607
|
+
events.push({event_id:event.event_id,at:event.at,actor:{host_uid:event.actor.host_uid},worker:event.worker,before:project(event.before),after:project(event.after),...(event.source==='config-reconcile'?{source:event.source}:{})});
|
|
608
|
+
} catch {complete=false;error='invalid audit record; history counts are unknown';}
|
|
609
|
+
}
|
|
610
|
+
return {events:[...seeded,...events],complete:complete&&!seedError,error:error??seedError,...(keepRaw&&offset===0?{raw:bytes.subarray(0,read)}:{})};
|
|
611
|
+
} catch(error) {
|
|
612
|
+
return error.code==='ENOENT'?{events:seeded,complete:!seedError,error:seedError}:{events:seeded,complete:false,error:'audit history unavailable; current policy is still shown'};
|
|
613
|
+
} finally {if(fd!==undefined)fs.closeSync(fd);}
|
|
614
|
+
}
|
|
615
|
+
// Profile mode needs a named target. A one-worker profile defaults to that worker; otherwise the caller must choose.
|
|
616
|
+
export function submitTarget(profile,requested) {
|
|
617
|
+
if(requested!==undefined) return assertTarget(profile,requested);
|
|
618
|
+
if(profile.legacy===true) return undefined;
|
|
619
|
+
const names=[...profile.workers.keys()];
|
|
620
|
+
if(names.length===1) return names[0];
|
|
621
|
+
throw new Error(`submit needs a target worker: use --worker NAME; configured: ${names.join(', ')}`);
|
|
622
|
+
}
|