@mago-foundation/mago-ski 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -3
- package/dist/hosts/github/run.d.ts +3 -1
- package/dist/hosts/github/run.js +29 -9
- package/dist/hosts/pi/index.js +48 -5
- package/dist/src/admin.d.ts +136 -1
- package/dist/src/admin.js +221 -84
- package/dist/src/cli.js +335 -10
- package/dist/src/fs-safe.d.ts +15 -2
- package/dist/src/fs-safe.js +32 -3
- package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
- package/dist/src/gate/adapters/claude-code-hook.js +4 -0
- package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
- package/dist/src/gate/adapters/claude-code-settings.js +49 -0
- package/dist/src/gate/adapters/claude-code.d.ts +33 -0
- package/dist/src/gate/adapters/claude-code.js +193 -0
- package/dist/src/gate/adapters/client.d.ts +13 -0
- package/dist/src/gate/adapters/client.js +57 -0
- package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
- package/dist/src/gate/adapters/codex-hook.js +5 -0
- package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
- package/dist/src/gate/adapters/codex-requirements.js +56 -0
- package/dist/src/gate/adapters/codex.d.ts +16 -0
- package/dist/src/gate/adapters/codex.js +574 -0
- package/dist/src/gate/adapters/hook-main.d.ts +7 -0
- package/dist/src/gate/adapters/hook-main.js +35 -0
- package/dist/src/gate/adapters/host-pid.d.ts +1 -0
- package/dist/src/gate/adapters/host-pid.js +20 -0
- package/dist/src/gate/admission.d.ts +54 -0
- package/dist/src/gate/admission.js +490 -0
- package/dist/src/gate/contract.d.ts +51 -0
- package/dist/src/gate/contract.js +94 -0
- package/dist/src/gate/decision-log.d.ts +38 -0
- package/dist/src/gate/decision-log.js +251 -0
- package/dist/src/gate/generations.d.ts +67 -0
- package/dist/src/gate/generations.js +518 -0
- package/dist/src/gate/proc.d.ts +31 -0
- package/dist/src/gate/proc.js +79 -0
- package/dist/src/gate/refresh.d.ts +11 -0
- package/dist/src/gate/refresh.js +30 -0
- package/dist/src/gate/run-verifier.d.ts +23 -0
- package/dist/src/gate/run-verifier.js +89 -0
- package/dist/src/gate/service.d.ts +80 -0
- package/dist/src/gate/service.js +722 -0
- package/dist/src/gate/strict-json.d.ts +11 -0
- package/dist/src/gate/strict-json.js +190 -0
- package/dist/src/gate/trust-store.d.ts +36 -0
- package/dist/src/gate/trust-store.js +251 -0
- package/dist/src/gate/verifier-worker.d.ts +8 -0
- package/dist/src/gate/verifier-worker.js +66 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/keys.d.ts +4 -0
- package/dist/src/keys.js +23 -14
- package/dist/src/policy.d.ts +145 -0
- package/dist/src/policy.js +554 -35
- package/dist/src/recovery-admin.d.ts +173 -0
- package/dist/src/recovery-admin.js +400 -0
- package/dist/src/root-events.d.ts +107 -0
- package/dist/src/root-events.js +376 -0
- package/dist/src/timestamp.d.ts +61 -0
- package/dist/src/timestamp.js +107 -0
- package/dist/src/tree-digest.d.ts +1 -0
- package/dist/src/tree-digest.js +1 -1
- package/dist/src/verify.d.ts +33 -0
- package/dist/src/verify.js +4 -2
- package/docs/hosts/adapter-interface.md +8 -2
- package/docs/hosts/github-action.md +1 -1
- package/docs/hosts/pi.md +2 -0
- package/docs/spec/gui-admin-rack-v1.md +289 -0
- package/docs/spec/root-recovery-v1.md +33 -12
- package/docs/spec/trust-documents-v1.md +8 -2
- package/docs/spec/verification.md +9 -2
- package/docs/threat-model.md +4 -2
- package/package.json +3 -1
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
// Root gate service core (E3 packet 6). Linux only. It owns the trust store, the admission store, the generation
|
|
2
|
+
// store and a per-digest certificate store, and answers hook adapters on a Unix socket. Production runs as root
|
|
3
|
+
// (`rootUid` 0); tests pass their own uid. Out of scope here: harness adapters.
|
|
4
|
+
//
|
|
5
|
+
// IDENTITY. Node has no peer credentials, so the request's `session` (`pid:<n>`) is only a pointer. The service reads
|
|
6
|
+
// the kernel's view of that pid (/proc: start time, exe) and requires exe to be in the configured allowlist of host
|
|
7
|
+
// binaries; the admission ref `<pid>:<startedBootMs>` is derived from those kernel facts, never from the request. A
|
|
8
|
+
// forged request is harmless: the service answers only allow/deny to the asker; a forged session-start for someone
|
|
9
|
+
// else's pid admits it with its true kernel start time (no history shed, no rights gained); an unknown pid or a
|
|
10
|
+
// non-host exe is denied. There is no session-end event in the contract, so dead sessions are reaped (see REAPING). Any local user can send decisions (socket 0666) and so
|
|
11
|
+
// can only affect their own answers; a user who can run an allowlisted binary can already start sessions of their own.
|
|
12
|
+
//
|
|
13
|
+
// PROCESSES ONLY. /proc/<tid> resolves for threads too, and a thread starts later than its process, which would shorten
|
|
14
|
+
// its generation set; processFacts() therefore requires Tgid == pid and rejects nested pid namespaces (NSpid with
|
|
15
|
+
// more than one entry; unsupported). A replaced host binary reads `<path> (deleted)` in /proc/<pid>/exe; that is
|
|
16
|
+
// accepted as `<path>` only when the suffix is exactly " (deleted)" and `<path>` is allowlisted (the process was
|
|
17
|
+
// started from that root-owned path; allowlisted paths must not be creatable by employees).
|
|
18
|
+
//
|
|
19
|
+
// REAPING. Sessions have no end event, so dead ones are reaped: every 60 s while started, at start, and before an
|
|
20
|
+
// admission when open sessions are at >= 90% of MAX_SESSIONS or the asking uid is at its cap. Full /proc sweeps are
|
|
21
|
+
// rate-limited to one per `sweepMinIntervalMs` (default 1000; all triggers share it); a rate-limited sweep keeps the
|
|
22
|
+
// last counts, so an admission at the cap is refused (fail closed) until the next sweep may run. Only ENOENT/ESRCH, a
|
|
23
|
+
// different start time, a non-process Tgid or a nested pid namespace mean dead; ANY OTHER read error (EACCES, EMFILE,
|
|
24
|
+
// ...) keeps the session (admission.ts: an isLive that throws keeps the session), counted for the uid it was admitted under. A session is live if
|
|
25
|
+
// /proc/<pid> is a process whose start time equals the ref's (refs are kernel-derived `pid:starttime`, which cannot
|
|
26
|
+
// recur within a boot, the only reason admission.ts reapSessions is safe here). Per-uid cap (default 256): a new
|
|
27
|
+
// admission is refused (`internal`) while that uid has that many open LIVE sessions, counted from each open
|
|
28
|
+
// session's pid uid in /proc at the last sweep plus admissions since; a re-sent session-start from a capped uid is
|
|
29
|
+
// refused too. Admissions run one at a time, so the cap is exact within one service process.
|
|
30
|
+
//
|
|
31
|
+
// DEPLOYMENT REQUIREMENTS (not enforced here): the socket and state directories' ancestors are not checked, so
|
|
32
|
+
// every ancestor must be root-owned and not writable by employees; the service must see the hosts' pid namespace
|
|
33
|
+
// (no containers between) and /proc without hidepid hiding other uids (an unreadable pid keeps its session open, so
|
|
34
|
+
// hiding pids only delays reaping), and RLIMIT_NOFILE (soft) of at least decision cap + 4 (admin) + 256 (margin for
|
|
35
|
+
// stores, certificates, installs): start() caps the decision connections at (soft limit - 260) and refuses to start
|
|
36
|
+
// when that leaves fewer than 16.
|
|
37
|
+
// ADAPTER CONTRACT (packet 9). A local user can always overload a world-accessible socket that has no peer credentials;
|
|
38
|
+
// the service-side limits below only reduce the blast radius. Therefore every harness adapter MUST treat a missing, late
|
|
39
|
+
// (its own deadline, shorter than the host's hook timeout), empty or malformed answer as DENY in enforce mode, by
|
|
40
|
+
// returning the host's explicit block response itself (e.g. exit code 2 for Codex), never by crashing or timing out.
|
|
41
|
+
// WORK LIMITS. An answered connection is closed as soon as its reply is flushed, whatever the client does, and frees its
|
|
42
|
+
// slot at once. A connection destroyed before its answer is ready cancels the remaining work (checked before assess and
|
|
43
|
+
// before certificates are read) and nothing is written. A uid (taken from /proc for the request's session pid) may have
|
|
44
|
+
// 8 decision requests in flight; the 9th gets gate-error `internal` before any expensive work. The uid charged is the
|
|
45
|
+
// owner of the NAMED pid, not the sender (unknowable without peer credentials), so one local user can exhaust another
|
|
46
|
+
// user's share while flooding; that only yields denials (adapter contract below). Verdicts are cached per
|
|
47
|
+
// (name, digest, trust-root version, revocation-list version) for at most 1 s of the service clock: an accepted
|
|
48
|
+
// revocation or trust root changes the key, so it applies to the very next check; a certificate that expires or becomes
|
|
49
|
+
// valid inside that second (or whose approver expires in it) can be seen up to 1 s late (the TTL bounds the EXPIRED/VERIFIED boundary); storing a
|
|
50
|
+
// certificate clears the cache.
|
|
51
|
+
// The decision connection cap is also lowered to /proc/sys/net/core/somaxconn when that is smaller (a larger cap cannot
|
|
52
|
+
// be queued by the kernel); production should raise net.core.somaxconn to at least the cap (default 1024).
|
|
53
|
+
// CONNECTIONS. Decision socket (0666) at its cap: the OLDEST connection that has not yet delivered a complete request
|
|
54
|
+
// line is destroyed and the newcomer accepted; connections whose request is being processed are never evicted (an answered
|
|
55
|
+
// connection no longer exists, see WORK LIMITS); if every connection is processing, the newcomer is closed. A reconnecting flood therefore cannot starve a client that sends
|
|
56
|
+
// its request promptly. The idle deadline (300 ms / 2 s admin) ends when the request line is complete; processing then
|
|
57
|
+
// has its own deadline (5 s / 60 s admin) after which the connection closes without a reply.
|
|
58
|
+
// The listen backlog is 4096 (the kernel clamps it to net.core.somaxconn): with Node's default 511 a flood of
|
|
59
|
+
// queued connects made legitimate connects wait for SYN retries (measured 14-17 of 20 answered; 20 of 20 at 4096).
|
|
60
|
+
// check() reads at most 16 certificate files per digest (later files are ignored).
|
|
61
|
+
//
|
|
62
|
+
// DECISION LOG (decision-log.ts, `<stateDir>/log` unless `logDir`). Every decision answer is recorded with minimised fields; the
|
|
63
|
+
// session is a keyed hash (random per-service-instance salt, memory only) of the kernel-derived ref. In enforce mode an
|
|
64
|
+
// `allow` (VERIFIED) is returned only after its record is appended AND fsync'd; if that fails the answer is gate-error
|
|
65
|
+
// `internal`. Every other record is best-effort and a failure never changes the answer (deny stays deny; shadow never
|
|
66
|
+
// blocks). Failures only raise `degradedCount` and flip `log.state` to `degraded` in `status`. An unopened log is retried.
|
|
67
|
+
//
|
|
68
|
+
// READINESS. If startup could not open the stores, every decision is gate-error `trust-unavailable`. session-start
|
|
69
|
+
// needs only the admission store (so a session started while trust is stale is still recorded); skill events also
|
|
70
|
+
// need a ready trust store at decision time. A Skill that is not installed answers NO_CERTIFICATE.
|
|
71
|
+
//
|
|
72
|
+
// ORDERING (admission.ts caller contract): install = stage+verify+publish generation, store certificate, point the
|
|
73
|
+
// host-visible link at it, THEN read bootMs and publish to admission, so the stamp is never earlier than the
|
|
74
|
+
// generation's visibility. All admin operations run through one queue.
|
|
75
|
+
// HOST-VISIBLE SKILLS. Hosts load Skills from `managedDir` (Claude Code's managed Skill folder, Codex's admin root), never
|
|
76
|
+
// from the generation store. `<managedDir>/<name>` is a symlink to the current generation, replaced atomically (rename of
|
|
77
|
+
// a fresh link) on install and removed BEFORE the admission uninstall (admin uninstall and auto-uninstall on revoke), so
|
|
78
|
+
// the bytes a host can load are always a published, verified generation, and a removed Skill is hidden first. Anything
|
|
79
|
+
// else at `<managedDir>/<name>` (a real directory, a file) is refused, never replaced. Immutable generations stay on disk.
|
|
80
|
+
// Claude Code follows a symlinked Skill directory in its managed folder (/etc/claude-code/.claude/skills): verified live on
|
|
81
|
+
// 2.1.318 (-p mode), docs/spikes/claude-code-gate-live.md. Codex follows directory symlinks for admin scope (codex.ts).
|
|
82
|
+
// RATE LIMIT. Each uid (the owner of the named pid, as for WORK LIMITS) may make `maxRequestsPerSecPerUid` decision
|
|
83
|
+
// requests per second (burst 3x). Refused requests get gate-error `internal`, are counted in `status` (`log.rateLimited`)
|
|
84
|
+
// and are NOT logged, so a local user flooding the world-accessible socket cannot rotate older records out of the decision
|
|
85
|
+
// log faster than that rate allows for each uid it can name (default 10/s: about 4 KiB/s of records per named uid).
|
|
86
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
87
|
+
import { chmod, lstat, mkdir, readdir, readFile, rename, symlink, unlink } from 'node:fs/promises';
|
|
88
|
+
import net from 'node:net';
|
|
89
|
+
import path from 'node:path';
|
|
90
|
+
import { isRecord, MAX_CANONICAL_JSON_BYTES } from "../canonical-json.js";
|
|
91
|
+
import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
|
|
92
|
+
import { validateDigest, validateSkillName } from "../names.js";
|
|
93
|
+
import { formatTimestamp } from "../time.js";
|
|
94
|
+
import { evaluateCertificate, VERDICT_RANK } from "../verify.js";
|
|
95
|
+
import { openDecisionLog } from "./decision-log.js";
|
|
96
|
+
import { MAX_SESSIONS, openAdmissionStore } from "./admission.js";
|
|
97
|
+
import { parseGateRequest, serializeGateResult } from "./contract.js";
|
|
98
|
+
import { installSkill } from "./generations.js";
|
|
99
|
+
import { assertGatePlatform, bootId, bootMs, NotLiveError, nofileSoftLimit, processFacts, processInfo } from "./proc.js";
|
|
100
|
+
import { parseStrictJson, DEFAULT_STRICT_JSON_LIMITS } from "./strict-json.js";
|
|
101
|
+
import { readInbox } from "./refresh.js";
|
|
102
|
+
import { openTrustStore } from "./trust-store.js";
|
|
103
|
+
const SESSION = /^pid:([1-9][0-9]{0,9})$/u;
|
|
104
|
+
const DELETED = ' (deleted)';
|
|
105
|
+
const MAX_CERT_BYTES = 256 * 1024;
|
|
106
|
+
const MAX_CERTS_PER_DIGEST = 16;
|
|
107
|
+
const ADMIN_LIMITS = { maxBytes: 12 * 1024 * 1024, maxDepth: 4, maxMembers: 8, maxStringLength: 6 * 1024 * 1024 };
|
|
108
|
+
const hex = (digest) => validateDigest(digest).slice('sha256:'.length);
|
|
109
|
+
function b64(value, label, max) {
|
|
110
|
+
if (typeof value !== 'string')
|
|
111
|
+
throw new Error(`${label} must be a base64 string`);
|
|
112
|
+
const bytes = Buffer.from(value, 'base64');
|
|
113
|
+
if (bytes.toString('base64') !== value || bytes.length === 0 || bytes.length > max)
|
|
114
|
+
throw new Error(`${label} is not valid base64 within the size limit`);
|
|
115
|
+
return bytes;
|
|
116
|
+
}
|
|
117
|
+
function onlyKeys(c, keys) {
|
|
118
|
+
if (c['v'] !== 1 || Object.keys(c).some((k) => k !== 'v' && k !== 'cmd' && !keys.includes(k)) || keys.some((k) => !Object.hasOwn(c, k)))
|
|
119
|
+
throw new Error('command has missing or unknown fields');
|
|
120
|
+
}
|
|
121
|
+
async function ownedDir(dir, uid, mode, strict) {
|
|
122
|
+
await mkdir(dir, { mode }).catch((e) => { if (e?.code !== 'EEXIST')
|
|
123
|
+
throw e; });
|
|
124
|
+
const info = await lstat(dir);
|
|
125
|
+
if (info.isSymbolicLink() || !info.isDirectory())
|
|
126
|
+
throw new Error(`${dir} must be a real directory`);
|
|
127
|
+
if (info.uid !== uid)
|
|
128
|
+
throw new Error(`${dir} must be owned by uid ${uid}`);
|
|
129
|
+
if ((info.mode & (strict ? 0o077 : 0o022)) !== 0)
|
|
130
|
+
throw new Error(`${dir} has unsafe permissions`);
|
|
131
|
+
}
|
|
132
|
+
/** net.core.somaxconn; unreadable means no limit. */
|
|
133
|
+
async function readSomaxconn() {
|
|
134
|
+
const n = Number((await readFile('/proc/sys/net/core/somaxconn', 'utf8')).trim());
|
|
135
|
+
return Number.isSafeInteger(n) && n > 0 ? n : Infinity;
|
|
136
|
+
}
|
|
137
|
+
async function listen(server, file, mode) {
|
|
138
|
+
const old = await lstat(file).catch(() => undefined);
|
|
139
|
+
if (old) {
|
|
140
|
+
if (!old.isSocket())
|
|
141
|
+
throw new Error(`${file} exists and is not a socket`);
|
|
142
|
+
await unlink(file);
|
|
143
|
+
}
|
|
144
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(file, 4096, () => { server.off('error', reject); resolve(); }); });
|
|
145
|
+
await chmod(file, mode);
|
|
146
|
+
}
|
|
147
|
+
/** One request line per connection: read to the first newline (bounded, idle deadline), reply with one line, close. Anything else just closes. */
|
|
148
|
+
function serveOnce(live, limit, deadlineMs, processingMs, maxConnections, answer) {
|
|
149
|
+
const conns = new Set();
|
|
150
|
+
const pending = new Set(); // no complete request line yet, oldest first
|
|
151
|
+
return net.createServer({ allowHalfOpen: true }, (sock) => {
|
|
152
|
+
if (conns.size >= maxConnections) {
|
|
153
|
+
const oldest = pending.values().next().value;
|
|
154
|
+
if (!oldest) {
|
|
155
|
+
sock.destroy();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
conns.delete(oldest);
|
|
159
|
+
pending.delete(oldest);
|
|
160
|
+
live.delete(oldest);
|
|
161
|
+
oldest.destroy();
|
|
162
|
+
}
|
|
163
|
+
conns.add(sock);
|
|
164
|
+
pending.add(sock);
|
|
165
|
+
live.add(sock);
|
|
166
|
+
const chunks = [];
|
|
167
|
+
let size = 0;
|
|
168
|
+
let done = false;
|
|
169
|
+
const ctx = { cancelled: false };
|
|
170
|
+
let timer = setTimeout(() => sock.destroy(), deadlineMs);
|
|
171
|
+
sock.on('close', () => { ctx.cancelled = true; clearTimeout(timer); conns.delete(sock); pending.delete(sock); live.delete(sock); });
|
|
172
|
+
sock.on('error', () => sock.destroy());
|
|
173
|
+
sock.on('end', () => { if (!done)
|
|
174
|
+
sock.destroy(); });
|
|
175
|
+
sock.on('data', (chunk) => {
|
|
176
|
+
if (done)
|
|
177
|
+
return; // later bytes (a second request) are ignored
|
|
178
|
+
const nl = chunk.indexOf(0x0a);
|
|
179
|
+
const head = nl < 0 ? chunk : chunk.subarray(0, nl);
|
|
180
|
+
size += head.length;
|
|
181
|
+
if (size > limit) {
|
|
182
|
+
sock.destroy();
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
chunks.push(head);
|
|
186
|
+
if (nl < 0)
|
|
187
|
+
return;
|
|
188
|
+
done = true;
|
|
189
|
+
pending.delete(sock);
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
timer = setTimeout(() => sock.destroy(), processingMs);
|
|
192
|
+
answer(Buffer.concat(chunks), ctx).then((reply) => {
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
conns.delete(sock); // answered: the slot is free now, whatever the client does next
|
|
195
|
+
if (sock.destroyed)
|
|
196
|
+
return;
|
|
197
|
+
if (reply === undefined) {
|
|
198
|
+
sock.destroy();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
timer = setTimeout(() => sock.destroy(), 2000); // flush deadline for a client that never reads
|
|
202
|
+
sock.end(`${reply}\n`, () => sock.destroy());
|
|
203
|
+
}, () => sock.destroy());
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
export function createGateService(config) {
|
|
208
|
+
const now = config.now ?? (() => new Date());
|
|
209
|
+
const mode = config.mode;
|
|
210
|
+
const stateDir = path.resolve(config.stateDir);
|
|
211
|
+
const certsDir = path.join(stateDir, 'certs');
|
|
212
|
+
const stagingDir = path.join(stateDir, 'staging');
|
|
213
|
+
const generationsDir = path.resolve(config.generationsDir);
|
|
214
|
+
const managedDir = path.resolve(config.managedDir);
|
|
215
|
+
let decisionCap = 0;
|
|
216
|
+
const readFacts = config.processFacts ?? processFacts;
|
|
217
|
+
const sweepMinMs = config.sweepMinIntervalMs ?? 1000;
|
|
218
|
+
let lastSweep = -Infinity;
|
|
219
|
+
const uidOf = new Map(); // admitted ref -> uid, for sessions whose /proc state cannot be read
|
|
220
|
+
const sockets = { decision: path.join(config.decisionSocketDir, 'decision.sock'), admin: path.join(config.adminSocketDir, 'admin.sock') };
|
|
221
|
+
let trust;
|
|
222
|
+
let admission;
|
|
223
|
+
let ready = false;
|
|
224
|
+
const servers = [];
|
|
225
|
+
const live = new Set();
|
|
226
|
+
let queue = Promise.resolve();
|
|
227
|
+
const serial = (fn) => { const run = queue.then(fn); queue = run.catch(() => { }); return run; };
|
|
228
|
+
/** Re-reads the clock and retries once: concurrent admissions can stamp slightly ahead of a reading taken earlier. */
|
|
229
|
+
async function stamped(fn) {
|
|
230
|
+
const r = await fn(await bootMs());
|
|
231
|
+
return !r.ok && r.reason === 'clock-moved-backwards' ? fn(await bootMs()) : r;
|
|
232
|
+
}
|
|
233
|
+
// Admissions, sweeps and their counters run one at a time.
|
|
234
|
+
let gate = Promise.resolve();
|
|
235
|
+
const exclusive = (fn) => { const run = gate.then(fn); gate = run.catch(() => { }); return run; };
|
|
236
|
+
let openCount = 0;
|
|
237
|
+
let perUid = new Map();
|
|
238
|
+
const perUidCap = config.maxSessionsPerUid ?? 256;
|
|
239
|
+
/** Reap dead sessions and recount the live ones per uid; at most one sweep per sweepMinMs (a skipped one changes nothing). */
|
|
240
|
+
async function sweep() {
|
|
241
|
+
if (!admission)
|
|
242
|
+
return;
|
|
243
|
+
const t = performance.now();
|
|
244
|
+
if (t - lastSweep < sweepMinMs)
|
|
245
|
+
return;
|
|
246
|
+
lastSweep = t;
|
|
247
|
+
const counts = new Map();
|
|
248
|
+
let total = 0;
|
|
249
|
+
const r = await admission.reapSessions(async (ref) => {
|
|
250
|
+
const m = /^([1-9][0-9]*):([0-9]+)$/u.exec(ref);
|
|
251
|
+
if (!m)
|
|
252
|
+
return false;
|
|
253
|
+
const dead = () => { uidOf.delete(ref); return false; };
|
|
254
|
+
try {
|
|
255
|
+
const f = await readFacts(Number(m[1]));
|
|
256
|
+
if (f.startedBootMs !== Number(m[2]))
|
|
257
|
+
return dead();
|
|
258
|
+
uidOf.set(ref, f.uid);
|
|
259
|
+
counts.set(f.uid, (counts.get(f.uid) ?? 0) + 1);
|
|
260
|
+
total++;
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
catch (e) {
|
|
264
|
+
const code = e?.code;
|
|
265
|
+
if (code === 'ENOENT' || code === 'ESRCH' || e instanceof NotLiveError)
|
|
266
|
+
return dead();
|
|
267
|
+
total++; // unknown state: keep the session, and count it for the uid it was admitted under
|
|
268
|
+
const u = uidOf.get(ref);
|
|
269
|
+
if (u !== undefined)
|
|
270
|
+
counts.set(u, (counts.get(u) ?? 0) + 1);
|
|
271
|
+
return true;
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
if (r.ok) {
|
|
275
|
+
openCount = total;
|
|
276
|
+
perUid = counts;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const admitOnce = (ref, startedBootMs, uid) => exclusive(async () => {
|
|
280
|
+
if (openCount >= MAX_SESSIONS * 0.9 || (perUid.get(uid) ?? 0) >= perUidCap)
|
|
281
|
+
await sweep();
|
|
282
|
+
if ((perUid.get(uid) ?? 0) >= perUidCap)
|
|
283
|
+
return { ok: false, reason: 'session-limit' };
|
|
284
|
+
const r = await stamped((ms) => admission.admitSession(ref, ms, { startedBootMs }));
|
|
285
|
+
if (r.ok) {
|
|
286
|
+
uidOf.set(ref, uid);
|
|
287
|
+
openCount++;
|
|
288
|
+
perUid.set(uid, (perUid.get(uid) ?? 0) + 1);
|
|
289
|
+
}
|
|
290
|
+
return r;
|
|
291
|
+
});
|
|
292
|
+
let reaper;
|
|
293
|
+
let refresher;
|
|
294
|
+
/** Engine verdict for exactly this Skill name and digest under the trust context of this moment. */
|
|
295
|
+
const verdictCache = new Map();
|
|
296
|
+
const CACHE_TTL_MS = 1000;
|
|
297
|
+
const CACHE_MAX = 4096;
|
|
298
|
+
async function check(name, digest, ctx, fresh = false) {
|
|
299
|
+
const at = now().getTime();
|
|
300
|
+
const current = await trust.current(now());
|
|
301
|
+
if (!current.ready)
|
|
302
|
+
return 'UNVERIFIABLE';
|
|
303
|
+
const key = `${current.versions.trustRootVersion}|${current.versions.revocationsVersion}|${name}|${digest}`;
|
|
304
|
+
const hit = verdictCache.get(key);
|
|
305
|
+
if (!fresh && hit && at - hit.at >= 0 && at - hit.at < CACHE_TTL_MS)
|
|
306
|
+
return hit.verdict;
|
|
307
|
+
if (ctx?.cancelled)
|
|
308
|
+
throw new Error('cancelled');
|
|
309
|
+
const verdict = await compute(name, digest, current.context);
|
|
310
|
+
if (verdictCache.size >= CACHE_MAX)
|
|
311
|
+
verdictCache.clear();
|
|
312
|
+
verdictCache.set(key, { verdict, at });
|
|
313
|
+
return verdict;
|
|
314
|
+
}
|
|
315
|
+
async function compute(name, digest, context) {
|
|
316
|
+
const dir = path.join(certsDir, name, hex(digest));
|
|
317
|
+
const files = (await readdir(dir).catch((e) => { if (e.code === 'ENOENT')
|
|
318
|
+
return []; throw e; }))
|
|
319
|
+
.filter((f) => /^[0-9a-f]{64}\.json$/u.test(f)).slice(0, MAX_CERTS_PER_DIGEST);
|
|
320
|
+
let best = 'NO_CERTIFICATE';
|
|
321
|
+
for (const file of files) {
|
|
322
|
+
const bytes = await readRegularFile(path.join(dir, file), 'certificate', MAX_CERT_BYTES);
|
|
323
|
+
const verdict = evaluateCertificate(bytes, name, digest, context, now()).verdict;
|
|
324
|
+
if (VERDICT_RANK[verdict] < VERDICT_RANK[best])
|
|
325
|
+
best = verdict;
|
|
326
|
+
}
|
|
327
|
+
return best;
|
|
328
|
+
}
|
|
329
|
+
const inflight = new Map();
|
|
330
|
+
const inflightCap = config.maxInflightPerUid ?? 8;
|
|
331
|
+
const ratePerSec = config.maxRequestsPerSecPerUid ?? 10;
|
|
332
|
+
const buckets = new Map();
|
|
333
|
+
let rateLimited = 0;
|
|
334
|
+
/** Token bucket per uid: capacity 3x the rate, refilled continuously. */
|
|
335
|
+
function takeToken(uid) {
|
|
336
|
+
const t = performance.now();
|
|
337
|
+
const b = buckets.get(uid) ?? { tokens: ratePerSec * 3, at: t };
|
|
338
|
+
b.tokens = Math.min(ratePerSec * 3, b.tokens + ((t - b.at) / 1000) * ratePerSec);
|
|
339
|
+
b.at = t;
|
|
340
|
+
buckets.set(uid, b);
|
|
341
|
+
if (b.tokens < 1)
|
|
342
|
+
return false;
|
|
343
|
+
b.tokens -= 1;
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
const readInfo = config.processInfo ?? processInfo;
|
|
347
|
+
const salt = randomBytes(32); // per service instance, never stored: logs from different boots cannot be joined by pid
|
|
348
|
+
const logDir = path.resolve(config.logDir ?? path.join(stateDir, 'log'));
|
|
349
|
+
let dlog;
|
|
350
|
+
let opening;
|
|
351
|
+
let logHealthy = true;
|
|
352
|
+
let degradedCount = 0;
|
|
353
|
+
const unattributed = {}; // requests with no kernel-derived session: counted, never logged (flood-proof)
|
|
354
|
+
const getLog = () => dlog ? Promise.resolve(dlog) : (opening ??= openDecisionLog(logDir, {
|
|
355
|
+
rootUid: config.rootUid, now,
|
|
356
|
+
...(config.logMaxSegments !== undefined ? { maxSegments: config.logMaxSegments } : {}),
|
|
357
|
+
...(config.logMaxSegmentBytes !== undefined ? { maxSegmentBytes: config.logMaxSegmentBytes } : {}),
|
|
358
|
+
...(config.logFault ? { fault: config.logFault } : {}),
|
|
359
|
+
}).then((l) => (dlog = l), (e) => { opening = undefined; throw e; }));
|
|
360
|
+
async function handleDecision(request, ctx = { cancelled: false }) {
|
|
361
|
+
const t0 = performance.now();
|
|
362
|
+
const meta = { ref: null, digests: [], versions: null };
|
|
363
|
+
const result = await decide(request, ctx, meta);
|
|
364
|
+
const enforce = mode !== 'shadow';
|
|
365
|
+
const action = result.kind === 'ack' ? 'ack' : result.kind === 'verdict' && result.verdict === 'VERIFIED' ? 'allow' : enforce ? 'deny' : 'observe';
|
|
366
|
+
const durable = action === 'allow' && enforce;
|
|
367
|
+
if (meta.limited) {
|
|
368
|
+
rateLimited++;
|
|
369
|
+
return result;
|
|
370
|
+
} // counted, never logged (see RATE LIMIT)
|
|
371
|
+
if (meta.ref === null) {
|
|
372
|
+
// Never an unlogged allow: verdicts only exist after a session was derived; refuse if that ever changes.
|
|
373
|
+
if (action === 'allow')
|
|
374
|
+
return { v: 1, request_id: request.request_id, kind: 'gate-error', code: 'internal', mode };
|
|
375
|
+
const k = result.kind === 'gate-error' ? result.code : result.kind;
|
|
376
|
+
unattributed[k] = (unattributed[k] ?? 0) + 1;
|
|
377
|
+
return result;
|
|
378
|
+
}
|
|
379
|
+
try {
|
|
380
|
+
const log = await getLog();
|
|
381
|
+
let skill = null;
|
|
382
|
+
try {
|
|
383
|
+
skill = request.skill === undefined ? null : validateSkillName(request.skill);
|
|
384
|
+
}
|
|
385
|
+
catch { /* unusual value: not logged */ }
|
|
386
|
+
await log.append({
|
|
387
|
+
bootMs: await bootMs(), mode, action, event: request.event,
|
|
388
|
+
session: meta.ref === null ? null : createHash('sha256').update(salt).update(meta.ref).digest('hex').slice(0, 16),
|
|
389
|
+
skill, digests: meta.digests.filter((d) => { try {
|
|
390
|
+
validateDigest(d);
|
|
391
|
+
return true;
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
return false;
|
|
395
|
+
} }),
|
|
396
|
+
trustRootVersion: meta.versions?.trustRootVersion ?? null, revocationsVersion: meta.versions?.revocationsVersion ?? null,
|
|
397
|
+
result: result.kind === 'verdict' ? result.verdict : result.kind === 'ack' ? 'ack' : result.code,
|
|
398
|
+
build: config.buildId ?? 'gate-service/v1', elapsedMs: Math.round(performance.now() - t0),
|
|
399
|
+
}, durable);
|
|
400
|
+
logHealthy = true;
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
logHealthy = false;
|
|
404
|
+
degradedCount++;
|
|
405
|
+
if (durable)
|
|
406
|
+
return { v: 1, request_id: request.request_id, mode, kind: 'gate-error', code: 'internal' }; // no allow without its record
|
|
407
|
+
}
|
|
408
|
+
return result;
|
|
409
|
+
}
|
|
410
|
+
async function decide(request, ctx, meta) {
|
|
411
|
+
const base = { v: 1, request_id: request.request_id, mode };
|
|
412
|
+
const fail = (code) => ({ ...base, kind: 'gate-error', code });
|
|
413
|
+
try {
|
|
414
|
+
if (!ready || !trust || !admission)
|
|
415
|
+
return fail('trust-unavailable');
|
|
416
|
+
const pid = SESSION.exec(request.session)?.[1];
|
|
417
|
+
let ref;
|
|
418
|
+
let startedBootMs;
|
|
419
|
+
let uid;
|
|
420
|
+
try {
|
|
421
|
+
if (!pid)
|
|
422
|
+
throw new Error('bad session');
|
|
423
|
+
const info = await readInfo(Number(pid));
|
|
424
|
+
const exe = info.exe.endsWith(DELETED) ? info.exe.slice(0, -DELETED.length) : info.exe;
|
|
425
|
+
if (!config.hostExes.includes(info.exe) && !config.hostExes.includes(exe))
|
|
426
|
+
throw new Error('not a host binary');
|
|
427
|
+
startedBootMs = info.startedBootMs;
|
|
428
|
+
uid = info.uid;
|
|
429
|
+
ref = `${pid}:${startedBootMs}`;
|
|
430
|
+
meta.ref = ref;
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
return fail('no-session-record');
|
|
434
|
+
}
|
|
435
|
+
if (ctx.cancelled)
|
|
436
|
+
return fail('internal'); // the client is gone; nothing will be written
|
|
437
|
+
if (!takeToken(uid)) {
|
|
438
|
+
meta.limited = true;
|
|
439
|
+
return fail('internal');
|
|
440
|
+
}
|
|
441
|
+
if ((inflight.get(uid) ?? 0) >= inflightCap)
|
|
442
|
+
return fail('internal'); // cheap refusal: this uid already has its share in flight
|
|
443
|
+
inflight.set(uid, (inflight.get(uid) ?? 0) + 1);
|
|
444
|
+
try {
|
|
445
|
+
return await decideAdmitted(request, ctx, base, fail, ref, startedBootMs, uid, meta);
|
|
446
|
+
}
|
|
447
|
+
finally {
|
|
448
|
+
const left = (inflight.get(uid) ?? 1) - 1;
|
|
449
|
+
if (left <= 0)
|
|
450
|
+
inflight.delete(uid);
|
|
451
|
+
else
|
|
452
|
+
inflight.set(uid, left);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
return fail('internal');
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
async function decideAdmitted(request, ctx, base, fail, ref, startedBootMs, uid, meta) {
|
|
460
|
+
if (request.event === 'session-start') {
|
|
461
|
+
const r = await admitOnce(ref, startedBootMs, uid);
|
|
462
|
+
// A re-sent start for the same live process is fine; the result is an acknowledgement, never a verdict.
|
|
463
|
+
return r.ok || r.reason === 'session-exists' ? { ...base, kind: 'ack' } : fail('internal');
|
|
464
|
+
}
|
|
465
|
+
const current = await trust.current(now());
|
|
466
|
+
if (!current.ready)
|
|
467
|
+
return fail('trust-unavailable');
|
|
468
|
+
meta.versions = current.versions;
|
|
469
|
+
if (ctx.cancelled)
|
|
470
|
+
return fail('internal');
|
|
471
|
+
const a = await admission.assess(ref, request.skill, (n, d) => check(n, d, ctx));
|
|
472
|
+
if (a.kind === 'verdict')
|
|
473
|
+
meta.digests = a.digests;
|
|
474
|
+
if (a.kind === 'verdict')
|
|
475
|
+
return { ...base, kind: 'verdict', verdict: a.verdict };
|
|
476
|
+
if (a.reason === 'no-session-record')
|
|
477
|
+
return fail('no-session-record');
|
|
478
|
+
if (a.reason === 'not-installed')
|
|
479
|
+
return { ...base, kind: 'verdict', verdict: 'NO_CERTIFICATE' };
|
|
480
|
+
return fail('internal'); // state-corrupt, bound-exceeded, io-busy, internal: contract.ts has no closer code
|
|
481
|
+
}
|
|
482
|
+
async function storeCertificate(name, digest, bytes) {
|
|
483
|
+
const dir = path.join(certsDir, name, hex(digest));
|
|
484
|
+
await mkdir(dir, { recursive: true, mode: 0o755 });
|
|
485
|
+
const file = path.join(dir, `${createHash('sha256').update(bytes).digest('hex')}.json`); // name = content hash: no overwrite with other bytes
|
|
486
|
+
if (await lstat(file).then(() => true, () => false))
|
|
487
|
+
return;
|
|
488
|
+
await writeFileAtomic(file, bytes, 0o444);
|
|
489
|
+
verdictCache.clear();
|
|
490
|
+
}
|
|
491
|
+
/** Points `<managedDir>/<name>` at generation `digest` (atomic rename of a fresh symlink), or removes it (`null`). */
|
|
492
|
+
async function hostLink(name, digest) {
|
|
493
|
+
const file = path.join(managedDir, name);
|
|
494
|
+
if (digest === null) {
|
|
495
|
+
const info = await lstat(file).catch((e) => { if (e.code === 'ENOENT')
|
|
496
|
+
return undefined; throw e; });
|
|
497
|
+
if (!info)
|
|
498
|
+
return;
|
|
499
|
+
if (!info.isSymbolicLink())
|
|
500
|
+
throw new Error(`${file} is not a link made by the gate; refusing to remove it`);
|
|
501
|
+
await unlink(file);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const tmp = path.join(managedDir, `.${name}.${randomBytes(8).toString('hex')}.tmp`);
|
|
505
|
+
await symlink(path.join(generationsDir, name, hex(digest)), tmp);
|
|
506
|
+
// rename over a symlink replaces it atomically; over a real directory it fails (EISDIR), which refuses the install.
|
|
507
|
+
try {
|
|
508
|
+
await rename(tmp, file);
|
|
509
|
+
}
|
|
510
|
+
catch (e) {
|
|
511
|
+
await unlink(tmp).catch(() => { });
|
|
512
|
+
throw e;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// REFRESH + RECONCILE (admin queue only). The inbox is offered to the trust store; a rejected or unreadable inbox changes
|
|
516
|
+
// nothing and extends nothing. Reconcile then re-checks the CURRENT generation of every installed Skill (cache bypassed):
|
|
517
|
+
// enforce uninstalls a non-VERIFIED one (no fallback to an older generation), shadow only records would-uninstall.
|
|
518
|
+
// When trust is not ready nothing can be evaluated, so nothing is uninstalled (decisions already deny in enforce).
|
|
519
|
+
const refreshStatus = { atBootMs: null, result: 'never' };
|
|
520
|
+
let autoUninstalled = [];
|
|
521
|
+
let wouldUninstall = [];
|
|
522
|
+
let reconcileError = null; // last reconcile failure (decisions still deny per digest; this is visibility)
|
|
523
|
+
// Never throws: a failure is recorded in status; decisions still evaluate every digest, so this is defence in depth.
|
|
524
|
+
async function reconcileInstalls() {
|
|
525
|
+
try {
|
|
526
|
+
const gone = await reconcileOnce();
|
|
527
|
+
reconcileError = null;
|
|
528
|
+
return gone;
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
reconcileError = error instanceof Error ? error.message.slice(0, 200) : 'reconcile failed';
|
|
532
|
+
return [];
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
async function reconcileOnce() {
|
|
536
|
+
const gone = [];
|
|
537
|
+
wouldUninstall = [];
|
|
538
|
+
if (!trust || !admission || !(await trust.current(now())).ready)
|
|
539
|
+
return gone;
|
|
540
|
+
for (const { name, digest } of await admission.installed()) {
|
|
541
|
+
let verdict;
|
|
542
|
+
try {
|
|
543
|
+
verdict = await check(name, digest, undefined, true);
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
continue;
|
|
547
|
+
} // unreadable evidence: leave as is
|
|
548
|
+
if (verdict === 'VERIFIED')
|
|
549
|
+
continue;
|
|
550
|
+
if (mode === 'shadow') {
|
|
551
|
+
wouldUninstall.push({ name, digest, verdict });
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
await hostLink(name, null); // hide it from hosts first; a failure stops here and is reported as reconcileError
|
|
555
|
+
const ms = await bootMs();
|
|
556
|
+
if ((await admission.uninstall(name, ms)).ok) {
|
|
557
|
+
gone.push({ name, digest, verdict });
|
|
558
|
+
autoUninstalled = [...autoUninstalled, { name, digest, verdict, bootMs: ms }].slice(-100);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return gone;
|
|
562
|
+
}
|
|
563
|
+
async function refreshNow() {
|
|
564
|
+
let out = { result: 'no-inbox' };
|
|
565
|
+
if (config.inboxDir && trust) {
|
|
566
|
+
const inbox = await readInbox(path.resolve(config.inboxDir), config.rootUid);
|
|
567
|
+
if (inbox.kind === 'absent')
|
|
568
|
+
out = { result: 'no-files' };
|
|
569
|
+
else if (inbox.kind === 'unsafe')
|
|
570
|
+
out = { result: 'unsafe-inbox', reason: inbox.reason };
|
|
571
|
+
else {
|
|
572
|
+
const r = await trust.accept({ trustRootBytes: inbox.trustRootBytes, revocationsBytes: inbox.revocationsBytes }, now());
|
|
573
|
+
out = r.ok ? { result: r.changed ? 'accepted' : 'unchanged' } : { result: 'rejected', reason: `${r.reason}: ${r.message}` };
|
|
574
|
+
}
|
|
575
|
+
refreshStatus.atBootMs = await bootMs();
|
|
576
|
+
refreshStatus.result = out.result;
|
|
577
|
+
if (out.reason)
|
|
578
|
+
refreshStatus.reason = out.reason;
|
|
579
|
+
else
|
|
580
|
+
delete refreshStatus.reason;
|
|
581
|
+
}
|
|
582
|
+
return { ...out, uninstalled: await reconcileInstalls() };
|
|
583
|
+
}
|
|
584
|
+
async function admin(raw) {
|
|
585
|
+
if (!isRecord(raw) || typeof raw['cmd'] !== 'string')
|
|
586
|
+
throw new Error('command must be an object with cmd');
|
|
587
|
+
if (!ready || !trust || !admission)
|
|
588
|
+
return { ok: false, error: 'service is not ready' };
|
|
589
|
+
switch (raw['cmd']) {
|
|
590
|
+
case 'status': {
|
|
591
|
+
onlyKeys(raw, []);
|
|
592
|
+
const c = await trust.current(now());
|
|
593
|
+
const health = await admission.health(); // also retries a store that could not load at start
|
|
594
|
+
return {
|
|
595
|
+
ok: true, ready: ready && health === 'ready', mode, trust: c.ready ? 'ready' : c.reason, admission: health,
|
|
596
|
+
revocationsExpiresAt: c.ready ? formatTimestamp(c.context.revocations.expiresAt) : null, // the remaining offline window
|
|
597
|
+
log: { state: dlog && logHealthy ? 'ready' : 'degraded', degradedCount, unattributed: { ...unattributed }, rateLimited, ...(dlog?.status() ?? { segment: null, lastSeq: 0, chainBreaks: 0 }) },
|
|
598
|
+
lastRefresh: { ...refreshStatus }, reconcileError, autoUninstalled, wouldUninstall,
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
case 'accept-trust': {
|
|
602
|
+
onlyKeys(raw, ['trust_root_b64', 'revocations_b64']);
|
|
603
|
+
const r = await trust.accept({
|
|
604
|
+
trustRootBytes: b64(raw['trust_root_b64'], 'trust_root_b64', MAX_CANONICAL_JSON_BYTES),
|
|
605
|
+
revocationsBytes: b64(raw['revocations_b64'], 'revocations_b64', MAX_CANONICAL_JSON_BYTES),
|
|
606
|
+
}, now());
|
|
607
|
+
if (!r.ok)
|
|
608
|
+
return { ok: false, error: `${r.reason}: ${r.message}` };
|
|
609
|
+
await reconcileInstalls();
|
|
610
|
+
return { ok: true, changed: r.changed };
|
|
611
|
+
}
|
|
612
|
+
case 'install': {
|
|
613
|
+
onlyKeys(raw, ['skill_name', 'source_dir', 'certificate_b64']);
|
|
614
|
+
const name = validateSkillName(raw['skill_name']);
|
|
615
|
+
const source = raw['source_dir'];
|
|
616
|
+
if (typeof source !== 'string' || !path.isAbsolute(source))
|
|
617
|
+
throw new Error('source_dir must be an absolute path');
|
|
618
|
+
const cert = b64(raw['certificate_b64'], 'certificate_b64', MAX_CERT_BYTES);
|
|
619
|
+
const current = await trust.current(now());
|
|
620
|
+
if (!current.ready)
|
|
621
|
+
return { ok: false, error: `trust not ready: ${current.reason}` };
|
|
622
|
+
const r = await installSkill(source, stagingDir, {
|
|
623
|
+
generationsRoot: generationsDir, skillName: name,
|
|
624
|
+
certificates: [{ source: 'admin', bytes: cert }], context: current.context, now: now(), buildProfile: 'gate-service/v1',
|
|
625
|
+
});
|
|
626
|
+
if (!r.ok)
|
|
627
|
+
return { ok: false, error: `${r.reason}: ${r.detail}` };
|
|
628
|
+
const digest = r.manifest.treeDigest;
|
|
629
|
+
await storeCertificate(name, digest, cert);
|
|
630
|
+
await hostLink(name, digest); // hosts can load it from here on
|
|
631
|
+
const p = await stamped((ms) => admission.publish(name, digest, ms)); // after the generation is visible
|
|
632
|
+
if (p.ok)
|
|
633
|
+
return { ok: true, digest, created: r.created };
|
|
634
|
+
await hostLink(name, null).catch(() => { }); // not recorded: hide it rather than serve unrecorded bytes
|
|
635
|
+
return { ok: false, error: `publish refused: ${p.reason}` };
|
|
636
|
+
}
|
|
637
|
+
case 'uninstall': {
|
|
638
|
+
onlyKeys(raw, ['skill_name']);
|
|
639
|
+
const name = validateSkillName(raw['skill_name']);
|
|
640
|
+
await hostLink(name, null); // hidden from hosts before the record changes
|
|
641
|
+
const u = await admission.uninstall(name, await bootMs());
|
|
642
|
+
return u.ok ? { ok: true } : { ok: false, error: `uninstall refused: ${u.reason}` };
|
|
643
|
+
}
|
|
644
|
+
case 'refresh': {
|
|
645
|
+
onlyKeys(raw, []);
|
|
646
|
+
if (!config.inboxDir)
|
|
647
|
+
return { ok: false, error: 'no inbox configured' };
|
|
648
|
+
const r = await refreshNow();
|
|
649
|
+
const ok = r.result === 'accepted' || r.result === 'unchanged' || r.result === 'no-files';
|
|
650
|
+
return ok ? { ok: true, result: r.result, uninstalled: r.uninstalled } : { ok: false, error: `${r.result}: ${r.reason ?? ''}` };
|
|
651
|
+
}
|
|
652
|
+
default: return { ok: false, error: 'unknown command' };
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
const handleAdmin = (command) => serial(() => admin(command)).catch((e) => ({ ok: false, error: e instanceof Error ? e.message : 'failed' }));
|
|
656
|
+
return {
|
|
657
|
+
sockets,
|
|
658
|
+
get decisionCap() { return decisionCap; },
|
|
659
|
+
handleDecision,
|
|
660
|
+
handleAdmin,
|
|
661
|
+
async start() {
|
|
662
|
+
assertGatePlatform(); // before anything is created on disk
|
|
663
|
+
try {
|
|
664
|
+
await ownedDir(stateDir, config.rootUid, 0o700, true);
|
|
665
|
+
for (const d of [stagingDir, certsDir])
|
|
666
|
+
await ownedDir(d, config.rootUid, d === certsDir ? 0o755 : 0o700, d !== certsDir);
|
|
667
|
+
await ownedDir(managedDir, config.rootUid, 0o755, false);
|
|
668
|
+
trust = await openTrustStore(path.join(stateDir, 'trust'), { rootFingerprint: config.rootFingerprint, now: now(), ...(config.maxListAgeMs !== undefined ? { maxListAgeMs: config.maxListAgeMs } : {}) });
|
|
669
|
+
admission = await openAdmissionStore(path.join(stateDir, 'admission'), { bootId: await bootId(), ...(config.admissionFault ? { fault: config.admissionFault } : {}) });
|
|
670
|
+
ready = true;
|
|
671
|
+
await getLog().catch(() => { logHealthy = false; });
|
|
672
|
+
await exclusive(sweep).catch(() => { });
|
|
673
|
+
reaper = setInterval(() => { void exclusive(sweep).catch(() => { }); }, 60_000);
|
|
674
|
+
reaper.unref();
|
|
675
|
+
if (config.inboxDir) {
|
|
676
|
+
refresher = setInterval(() => { void serial(refreshNow).catch(() => { }); }, config.refreshIntervalMs ?? 60_000);
|
|
677
|
+
refresher.unref();
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
ready = false;
|
|
682
|
+
} // stay up and answer trust-unavailable
|
|
683
|
+
const soft = config.nofileLimit ?? await nofileSoftLimit();
|
|
684
|
+
if (!(soft - 260 >= 16))
|
|
685
|
+
throw new Error(`RLIMIT_NOFILE soft limit ${soft} is too low (need at least 276)`);
|
|
686
|
+
const somax = await (config.somaxconn ?? readSomaxconn)().catch(() => Infinity);
|
|
687
|
+
decisionCap = Math.min(config.maxConnections ?? 1024, soft - 260, somax);
|
|
688
|
+
await ownedDir(config.decisionSocketDir, config.rootUid, 0o755, false);
|
|
689
|
+
await ownedDir(config.adminSocketDir, config.rootUid, 0o700, true);
|
|
690
|
+
const decision = serveOnce(live, DEFAULT_STRICT_JSON_LIMITS.maxBytes, config.deadlineMs ?? 300, config.processingMs ?? 5000, decisionCap, async (line, ctx) => {
|
|
691
|
+
try {
|
|
692
|
+
return serializeGateResult(await handleDecision(parseGateRequest(line), ctx));
|
|
693
|
+
}
|
|
694
|
+
catch {
|
|
695
|
+
return undefined;
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
const adminServer = serveOnce(live, ADMIN_LIMITS.maxBytes, config.deadlineMs ?? 2000, config.processingMs ?? 60_000, 4, async (line) => {
|
|
699
|
+
let result;
|
|
700
|
+
try {
|
|
701
|
+
result = await handleAdmin(parseStrictJson(line, ADMIN_LIMITS));
|
|
702
|
+
}
|
|
703
|
+
catch (e) {
|
|
704
|
+
result = { ok: false, error: e instanceof Error ? e.message : 'bad command' };
|
|
705
|
+
}
|
|
706
|
+
return JSON.stringify({ v: 1, ...result });
|
|
707
|
+
});
|
|
708
|
+
servers.push(decision, adminServer);
|
|
709
|
+
await listen(decision, sockets.decision, 0o666);
|
|
710
|
+
await listen(adminServer, sockets.admin, 0o600);
|
|
711
|
+
},
|
|
712
|
+
async stop() {
|
|
713
|
+
if (reaper)
|
|
714
|
+
clearInterval(reaper);
|
|
715
|
+
if (refresher)
|
|
716
|
+
clearInterval(refresher);
|
|
717
|
+
await dlog?.close().catch(() => { });
|
|
718
|
+
await Promise.all(servers.splice(0).map((s) => new Promise((r) => { s.close(() => r()); for (const c of live)
|
|
719
|
+
c.destroy(); })));
|
|
720
|
+
},
|
|
721
|
+
};
|
|
722
|
+
}
|