@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,518 @@
|
|
|
1
|
+
// Private staging and immutable generation store for the Skill gate (E3 packet 4).
|
|
2
|
+
// A candidate Skill is COPIED (never adopted) into a private staging directory, the COPIED bytes are verified with
|
|
3
|
+
// the engine, and only a VERIFIED copy is published as <generationsRoot>/<name>/<digest-hex>/ (read-only) plus a
|
|
4
|
+
// <digest-hex>.manifest.json. The manifest is local installation provenance written by this service, not an
|
|
5
|
+
// approval: approval is the certificate, checked again by the engine on every use.
|
|
6
|
+
// Profile (docs/spec/skill-tree-v2.md): a Skill with a root `.skilldigestignore` is rejected, because ignored paths
|
|
7
|
+
// are uncovered bytes that a read-only, fully verified generation must not contain. The root `.git` and the in-tree
|
|
8
|
+
// certificate are not copied (the digest already excludes them; certificates come from the caller).
|
|
9
|
+
// Linux only (shortcut): every root (source, staging, generations, <generations>/<name>) is opened by walking from `/`
|
|
10
|
+
// one component at a time with O_DIRECTORY|O_NOFOLLOW through /proc/self/fd, so no ancestor can be swapped for a
|
|
11
|
+
// symlink mid-operation. If /proc/self/fd is missing, staging and publishing fail closed (io-error); there is no
|
|
12
|
+
// path-based fallback. Staging and generations roots must not be group/world-writable. Ownership is not checked; in
|
|
13
|
+
// production the store is root-owned and root-only.
|
|
14
|
+
// Publication must be serialised by the service (packet 6). A crash (or a concurrent loser) between rename and
|
|
15
|
+
// manifest write leaves a generation directory without manifest, reported as generation-incomplete; it is never
|
|
16
|
+
// repaired automatically and needs an admin cleanup.
|
|
17
|
+
import { constants as fsConstants, existsSync } from 'node:fs';
|
|
18
|
+
import { chmod, lstat, mkdir, mkdtemp, open, readdir, rename, rm } from 'node:fs/promises';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requirePositiveInteger, requireString } from "../canonical-json.js";
|
|
21
|
+
import { writeFileAtomic } from "../fs-safe.js";
|
|
22
|
+
import { validateDigest, validateSkillName } from "../names.js";
|
|
23
|
+
import { CERTIFICATE_FILENAME, compareTreePaths, decodeEntryName, digestFileList, IGNORE_FILENAME, isExecutable, MAX_FILE_BYTES, MAX_RELATIVE_PATH_BYTES, MAX_TREE_BYTES, MAX_TREE_ENTRIES, MAX_TREE_FILES, sha256Hex, SKILL_FILENAME, TREE_PROFILE, } from "../tree-digest.js";
|
|
24
|
+
import { decide } from "../verify.js";
|
|
25
|
+
export const GENERATION_TYPE = 'mago.gate-generation/v1';
|
|
26
|
+
class GenError extends Error {
|
|
27
|
+
reason;
|
|
28
|
+
verdict;
|
|
29
|
+
constructor(reason, detail, verdict) { super(detail); this.reason = reason; this.verdict = verdict; }
|
|
30
|
+
}
|
|
31
|
+
function toFailure(error) {
|
|
32
|
+
if (error instanceof GenError)
|
|
33
|
+
return { ok: false, reason: error.reason, detail: error.message, ...(error.verdict ? { verdict: error.verdict } : {}) };
|
|
34
|
+
const code = error?.code;
|
|
35
|
+
return { ok: false, reason: 'io-error', detail: typeof code === 'string' ? code : 'unexpected error' };
|
|
36
|
+
}
|
|
37
|
+
const noFollow = fsConstants.O_NOFOLLOW ?? 0;
|
|
38
|
+
const nonBlock = fsConstants.O_NONBLOCK ?? 0;
|
|
39
|
+
const dirFlag = fsConstants.O_DIRECTORY ?? 0;
|
|
40
|
+
const MAX_DEPTH = 64;
|
|
41
|
+
const useProcFd = existsSync('/proc/self/fd');
|
|
42
|
+
const procOf = (h) => `/proc/self/fd/${h.fd}`;
|
|
43
|
+
async function openDirAt(parent, name, create) {
|
|
44
|
+
const p = `${parent}/${name}`;
|
|
45
|
+
let handle;
|
|
46
|
+
for (let attempt = 0; !handle; attempt++) {
|
|
47
|
+
try {
|
|
48
|
+
handle = await open(p, fsConstants.O_RDONLY | dirFlag | noFollow);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
const code = error?.code;
|
|
52
|
+
if (code === 'ELOOP' || code === 'ENOTDIR')
|
|
53
|
+
throw new GenError('symlink', JSON.stringify(name));
|
|
54
|
+
if (code === 'ENOENT' && create !== undefined && attempt === 0) {
|
|
55
|
+
await mkdir(p, { mode: create }).catch((e) => { if (e?.code !== 'EEXIST')
|
|
56
|
+
throw e; });
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (!(await handle.stat()).isDirectory()) {
|
|
63
|
+
await handle.close();
|
|
64
|
+
throw new GenError('symlink', JSON.stringify(name));
|
|
65
|
+
}
|
|
66
|
+
return handle;
|
|
67
|
+
}
|
|
68
|
+
/** Opens an absolute directory race-free (no symlink on any component). `create` makes missing components. */
|
|
69
|
+
async function walkDir(abs, create) {
|
|
70
|
+
if (!useProcFd)
|
|
71
|
+
throw new GenError('io-error', '/proc/self/fd unavailable (Linux only)');
|
|
72
|
+
let cur = await open('/', fsConstants.O_RDONLY | dirFlag);
|
|
73
|
+
for (const comp of path.resolve(abs).split('/').filter(Boolean)) {
|
|
74
|
+
let next;
|
|
75
|
+
try {
|
|
76
|
+
next = await openDirAt(procOf(cur), comp, create);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
await cur.close();
|
|
80
|
+
}
|
|
81
|
+
cur = next;
|
|
82
|
+
}
|
|
83
|
+
return cur;
|
|
84
|
+
}
|
|
85
|
+
async function requirePrivate(h, label) {
|
|
86
|
+
if (((await h.stat()).mode & 0o022) !== 0)
|
|
87
|
+
throw new GenError('io-error', `${label} is group/world-writable`);
|
|
88
|
+
}
|
|
89
|
+
async function openChecked(p, label, wantDir) {
|
|
90
|
+
let handle;
|
|
91
|
+
try {
|
|
92
|
+
handle = await open(p, fsConstants.O_RDONLY | noFollow | nonBlock | (wantDir ? dirFlag : 0));
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
const code = error?.code;
|
|
96
|
+
if (code === 'ELOOP')
|
|
97
|
+
throw new GenError('symlink', JSON.stringify(label));
|
|
98
|
+
if (code === 'ENXIO')
|
|
99
|
+
throw new GenError('special-file', JSON.stringify(label));
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const st = await handle.stat();
|
|
104
|
+
if (wantDir ? !st.isDirectory() : !st.isFile())
|
|
105
|
+
throw new GenError('special-file', JSON.stringify(label));
|
|
106
|
+
if (!wantDir && st.nlink > 1)
|
|
107
|
+
throw new GenError('hard-link', JSON.stringify(label));
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
await handle.close();
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
return handle;
|
|
114
|
+
}
|
|
115
|
+
async function copyFile(src, dst, label, b) {
|
|
116
|
+
if (++b.files > MAX_TREE_FILES)
|
|
117
|
+
throw new GenError('too-large', 'file count');
|
|
118
|
+
const input = await openChecked(src, label, false);
|
|
119
|
+
try {
|
|
120
|
+
const exec = isExecutable((await input.stat()).mode);
|
|
121
|
+
await mkdir(path.dirname(dst), { recursive: true, mode: 0o700 });
|
|
122
|
+
const output = await open(dst, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow, 0o600);
|
|
123
|
+
try {
|
|
124
|
+
const chunk = Buffer.allocUnsafe(64 * 1024);
|
|
125
|
+
let size = 0;
|
|
126
|
+
while (true) {
|
|
127
|
+
const { bytesRead } = await input.read(chunk, 0, chunk.length, null);
|
|
128
|
+
if (bytesRead === 0)
|
|
129
|
+
break;
|
|
130
|
+
size += bytesRead;
|
|
131
|
+
b.bytes += bytesRead;
|
|
132
|
+
if (size > MAX_FILE_BYTES || b.bytes > MAX_TREE_BYTES)
|
|
133
|
+
throw new GenError('too-large', JSON.stringify(label));
|
|
134
|
+
await output.writeFile(chunk.subarray(0, bytesRead));
|
|
135
|
+
}
|
|
136
|
+
await output.chmod(exec ? 0o755 : 0o644);
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
await output.close();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
await input.close();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function copyDir(dir, rel, dst, depth, b) {
|
|
147
|
+
if (depth > MAX_DEPTH)
|
|
148
|
+
throw new GenError('too-large', 'directory depth');
|
|
149
|
+
{
|
|
150
|
+
// Children are addressed through the open directory fd so a swapped ancestor cannot redirect them.
|
|
151
|
+
const base = procOf(dir);
|
|
152
|
+
for (const entry of await readdir(base, { withFileTypes: true, encoding: 'buffer' })) {
|
|
153
|
+
if (++b.entries > MAX_TREE_ENTRIES)
|
|
154
|
+
throw new GenError('too-large', 'entry count');
|
|
155
|
+
let name;
|
|
156
|
+
try {
|
|
157
|
+
name = decodeEntryName(entry.name);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
throw new GenError('unsafe-name', JSON.stringify(rel || '.'));
|
|
161
|
+
}
|
|
162
|
+
const relPath = rel ? `${rel}/${name}` : name;
|
|
163
|
+
if (Buffer.byteLength(relPath) > MAX_RELATIVE_PATH_BYTES)
|
|
164
|
+
throw new GenError('too-large', 'path length');
|
|
165
|
+
if (!rel && name === IGNORE_FILENAME)
|
|
166
|
+
throw new GenError('ignored-content-not-allowed', IGNORE_FILENAME);
|
|
167
|
+
if (!rel && (name === '.git' || (name === CERTIFICATE_FILENAME && !entry.isDirectory())))
|
|
168
|
+
continue;
|
|
169
|
+
const child = `${base}/${name}`;
|
|
170
|
+
if (entry.isSymbolicLink())
|
|
171
|
+
throw new GenError('symlink', JSON.stringify(relPath));
|
|
172
|
+
if (entry.isDirectory()) {
|
|
173
|
+
const sub = await openChecked(child, relPath, true);
|
|
174
|
+
try {
|
|
175
|
+
await copyDir(sub, relPath, path.join(dst, name), depth + 1, b);
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
await sub.close();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
else if (entry.isFile())
|
|
182
|
+
await copyFile(child, path.join(dst, name), relPath, b);
|
|
183
|
+
else
|
|
184
|
+
throw new GenError('special-file', JSON.stringify(relPath));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Opaque handle to a staged copy: the open staging root, the open stage directory and the stage name. publishStaged
|
|
190
|
+
* is the only consumer; it reads the tree and renames through these descriptors, never through a caller path.
|
|
191
|
+
* `stagedDir` is informational (display / tests) and is never used for I/O by this module.
|
|
192
|
+
*/
|
|
193
|
+
export class StagedSkill {
|
|
194
|
+
stagedDir;
|
|
195
|
+
stagingH;
|
|
196
|
+
stageH;
|
|
197
|
+
name;
|
|
198
|
+
closed = false;
|
|
199
|
+
constructor(stagedDir, stagingH, stageH, name) {
|
|
200
|
+
this.stagedDir = stagedDir;
|
|
201
|
+
this.stagingH = stagingH;
|
|
202
|
+
this.stageH = stageH;
|
|
203
|
+
this.name = name;
|
|
204
|
+
}
|
|
205
|
+
/** Removes the staged copy and closes both handles (idempotent). publishStaged calls this on every path. */
|
|
206
|
+
async discard() {
|
|
207
|
+
if (this.closed)
|
|
208
|
+
return;
|
|
209
|
+
this.closed = true;
|
|
210
|
+
try {
|
|
211
|
+
await rm(`${procOf(this.stagingH)}/${this.name}`, { recursive: true, force: true });
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
await this.stageH.close();
|
|
215
|
+
await this.stagingH.close();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** Copies `sourceDir` into a fresh 0700 directory under `stagingRoot`. The caller must publish or discard the result. */
|
|
220
|
+
export async function stageSkill(sourceDir, stagingRoot) {
|
|
221
|
+
let rootH;
|
|
222
|
+
let stagingH;
|
|
223
|
+
let stageH;
|
|
224
|
+
let name;
|
|
225
|
+
try {
|
|
226
|
+
rootH = await walkDir(sourceDir);
|
|
227
|
+
stagingH = await walkDir(stagingRoot, 0o700);
|
|
228
|
+
await requirePrivate(stagingH, 'staging root');
|
|
229
|
+
name = path.basename(await mkdtemp(`${procOf(stagingH)}/stage-`));
|
|
230
|
+
stageH = await openDirAt(procOf(stagingH), name);
|
|
231
|
+
await copyDir(rootH, '', procOf(stageH), 0, { entries: 0, files: 0, bytes: 0 });
|
|
232
|
+
const staged = new StagedSkill(path.join(path.resolve(stagingRoot), name), stagingH, stageH, name);
|
|
233
|
+
stagingH = undefined;
|
|
234
|
+
stageH = undefined;
|
|
235
|
+
return { ok: true, staged };
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (name && stagingH)
|
|
239
|
+
await rm(`${procOf(stagingH)}/${name}`, { recursive: true, force: true });
|
|
240
|
+
return toFailure(error);
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
await rootH?.close();
|
|
244
|
+
await stageH?.close();
|
|
245
|
+
await stagingH?.close();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Collects and digests a tree reading ONLY through open descriptors (/proc/self/fd/<fd>/<child>, O_NOFOLLOW per
|
|
250
|
+
* component), so no ancestor of the tree can redirect it. The kernel resolves /proc/self/fd/<fd> to the opened
|
|
251
|
+
* directory itself, not by re-walking its path; the engine's collectSkillTree cannot be used here because it
|
|
252
|
+
* re-resolves realpath(root) and walks by path. Stricter than the engine: hard links are rejected.
|
|
253
|
+
* Same digest as the engine for the same bytes (tests compare against engine-issued certificates).
|
|
254
|
+
*/
|
|
255
|
+
async function collectFd(root) {
|
|
256
|
+
const files = [];
|
|
257
|
+
const fileModes = new Map();
|
|
258
|
+
const dirs = new Map([['', (await root.stat()).mode & 0o7777]]);
|
|
259
|
+
const excluded = [];
|
|
260
|
+
const seen = new Set();
|
|
261
|
+
let entries = 0, totalBytes = 0;
|
|
262
|
+
const visit = async (dir, rel, depth) => {
|
|
263
|
+
if (depth > MAX_DEPTH)
|
|
264
|
+
throw new GenError('too-large', 'directory depth');
|
|
265
|
+
const base = procOf(dir);
|
|
266
|
+
for (const entry of await readdir(base, { withFileTypes: true, encoding: 'buffer' })) {
|
|
267
|
+
if (++entries > MAX_TREE_ENTRIES)
|
|
268
|
+
throw new GenError('too-large', 'entry count');
|
|
269
|
+
let name;
|
|
270
|
+
try {
|
|
271
|
+
name = decodeEntryName(entry.name);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
throw new GenError('unsafe-name', JSON.stringify(rel || '.'));
|
|
275
|
+
}
|
|
276
|
+
const relPath = rel ? `${rel}/${name}` : name;
|
|
277
|
+
if (Buffer.byteLength(relPath) > MAX_RELATIVE_PATH_BYTES)
|
|
278
|
+
throw new GenError('too-large', 'path length');
|
|
279
|
+
const caseKey = relPath.normalize('NFKC').toLowerCase();
|
|
280
|
+
if (seen.has(caseKey))
|
|
281
|
+
throw new GenError('unsafe-name', `case collision ${JSON.stringify(relPath)}`);
|
|
282
|
+
seen.add(caseKey);
|
|
283
|
+
if (!rel && (name === '.git' || name === IGNORE_FILENAME || (name === CERTIFICATE_FILENAME && !entry.isDirectory()))) {
|
|
284
|
+
excluded.push(relPath);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const child = `${base}/${name}`;
|
|
288
|
+
if (entry.isSymbolicLink())
|
|
289
|
+
throw new GenError('symlink', JSON.stringify(relPath));
|
|
290
|
+
if (entry.isDirectory()) {
|
|
291
|
+
const sub = await openChecked(child, relPath, true);
|
|
292
|
+
try {
|
|
293
|
+
dirs.set(relPath, (await sub.stat()).mode & 0o7777);
|
|
294
|
+
await visit(sub, relPath, depth + 1);
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
await sub.close();
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
else if (entry.isFile()) {
|
|
301
|
+
if (files.length >= MAX_TREE_FILES)
|
|
302
|
+
throw new GenError('too-large', 'file count');
|
|
303
|
+
const h = await openChecked(child, relPath, false);
|
|
304
|
+
try {
|
|
305
|
+
const st = await h.stat();
|
|
306
|
+
if (st.size > MAX_FILE_BYTES)
|
|
307
|
+
throw new GenError('too-large', JSON.stringify(relPath));
|
|
308
|
+
const content = await h.readFile();
|
|
309
|
+
totalBytes += content.length;
|
|
310
|
+
if (content.length > MAX_FILE_BYTES || totalBytes > MAX_TREE_BYTES)
|
|
311
|
+
throw new GenError('too-large', JSON.stringify(relPath));
|
|
312
|
+
files.push({ path: relPath, size: content.length, sha256: sha256Hex(content), exec: isExecutable(st.mode) });
|
|
313
|
+
fileModes.set(relPath, st.mode & 0o7777);
|
|
314
|
+
}
|
|
315
|
+
finally {
|
|
316
|
+
await h.close();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
else
|
|
320
|
+
throw new GenError('special-file', JSON.stringify(relPath));
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
await visit(root, '', 0);
|
|
324
|
+
files.sort((x, y) => compareTreePaths(x.path, y.path));
|
|
325
|
+
if (!files.some((f) => f.path === SKILL_FILENAME))
|
|
326
|
+
throw new GenError('not-verified', 'SKILL.md missing');
|
|
327
|
+
return { digest: digestFileList(files), files, totalBytes, excluded: excluded.sort(), dirs, fileModes };
|
|
328
|
+
}
|
|
329
|
+
const hexOf = (digest) => validateDigest(digest).slice('sha256:'.length);
|
|
330
|
+
const pickFile = (f) => ({ path: f.path, size: f.size, sha256: f.sha256, exec: f.exec });
|
|
331
|
+
function manifestBytes(m) {
|
|
332
|
+
return canonicalBytes({
|
|
333
|
+
type: m.type, skill: m.skill, tree_digest: m.treeDigest, files: m.files.map(pickFile),
|
|
334
|
+
certificate_id: m.certificateId, trust_root_version: m.trustRootVersion,
|
|
335
|
+
revocations_version: m.revocationsVersion, build_profile: m.buildProfile,
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
const MAX_MANIFEST_BYTES = 16 * 1024 * 1024;
|
|
339
|
+
/** Re-verifies generation <digest> inside the open <generations>/<name> directory, reading only through descriptors. */
|
|
340
|
+
async function readGenerationAt(nameH, name, digest) {
|
|
341
|
+
const hex = hexOf(digest);
|
|
342
|
+
const bad = (detail) => new GenError('generation-mismatch', detail);
|
|
343
|
+
let dirH;
|
|
344
|
+
try {
|
|
345
|
+
let raw;
|
|
346
|
+
try {
|
|
347
|
+
const mh = await openChecked(`${procOf(nameH)}/${hex}.manifest.json`, 'generation manifest', false);
|
|
348
|
+
try {
|
|
349
|
+
if ((await mh.stat()).size > MAX_MANIFEST_BYTES)
|
|
350
|
+
throw new Error('too large');
|
|
351
|
+
raw = await mh.readFile();
|
|
352
|
+
}
|
|
353
|
+
finally {
|
|
354
|
+
await mh.close();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
throw bad('manifest missing or unreadable');
|
|
359
|
+
}
|
|
360
|
+
let manifest;
|
|
361
|
+
try {
|
|
362
|
+
const m = exactKeys(parseCanonicalJsonBytes(raw, 'generation manifest'), [
|
|
363
|
+
'type', 'skill', 'tree_digest', 'files', 'certificate_id', 'trust_root_version', 'revocations_version', 'build_profile',
|
|
364
|
+
], 'generation manifest');
|
|
365
|
+
if (m.type !== GENERATION_TYPE || !Array.isArray(m.files))
|
|
366
|
+
throw new Error('bad type');
|
|
367
|
+
manifest = {
|
|
368
|
+
type: GENERATION_TYPE, skill: requireString(m.skill, 'skill', 128), treeDigest: validateDigest(m.tree_digest),
|
|
369
|
+
files: m.files, certificateId: requireString(m.certificate_id, 'certificate_id', 256),
|
|
370
|
+
trustRootVersion: requirePositiveInteger(m.trust_root_version, 'trust_root_version'),
|
|
371
|
+
revocationsVersion: requirePositiveInteger(m.revocations_version, 'revocations_version'),
|
|
372
|
+
buildProfile: requireString(m.build_profile, 'build_profile', 256),
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
throw bad('manifest invalid');
|
|
377
|
+
}
|
|
378
|
+
if (manifest.skill !== name || manifest.treeDigest !== digest)
|
|
379
|
+
throw bad('manifest names another generation');
|
|
380
|
+
let tree;
|
|
381
|
+
try {
|
|
382
|
+
dirH = await openDirAt(procOf(nameH), hex);
|
|
383
|
+
tree = await collectFd(dirH);
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
throw bad('tree unreadable or contains links or special files');
|
|
387
|
+
}
|
|
388
|
+
// excluded must be empty: a planted .git, certificate or ignore rule would hide bytes from the digest.
|
|
389
|
+
if (tree.digest !== digest || tree.excluded.length || !canonicalBytes(tree.files.map(pickFile)).equals(canonicalBytes(manifest.files)))
|
|
390
|
+
throw bad('tree differs from manifest');
|
|
391
|
+
// The digest covers bytes and exec bits; directories and modes are checked here from the same descriptors.
|
|
392
|
+
const dirs = new Set(['']);
|
|
393
|
+
for (const f of tree.files)
|
|
394
|
+
for (let d = path.posix.dirname(f.path); d !== '.'; d = path.posix.dirname(d))
|
|
395
|
+
dirs.add(d);
|
|
396
|
+
for (const [rel, mode] of tree.dirs)
|
|
397
|
+
if (!dirs.has(rel) || mode !== 0o555)
|
|
398
|
+
throw bad('directory mode or unexpected directory');
|
|
399
|
+
for (const f of tree.files)
|
|
400
|
+
if (tree.fileModes.get(f.path) !== (f.exec ? 0o555 : 0o444))
|
|
401
|
+
throw bad('file mode');
|
|
402
|
+
return { ok: true, manifest };
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
return toFailure(error);
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
await dirH?.close();
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/** Re-verifies a published generation against its manifest: bytes, exec bits, modes, no extras, no links. */
|
|
412
|
+
export async function readGeneration(generationsRoot, name, digest) {
|
|
413
|
+
let gensH;
|
|
414
|
+
let nameH;
|
|
415
|
+
try {
|
|
416
|
+
validateSkillName(name);
|
|
417
|
+
hexOf(digest);
|
|
418
|
+
try {
|
|
419
|
+
gensH = await walkDir(generationsRoot);
|
|
420
|
+
nameH = await openDirAt(procOf(gensH), name);
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
if (error?.code === 'ENOENT')
|
|
424
|
+
throw new GenError('generation-mismatch', 'generation missing');
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
return await readGenerationAt(nameH, name, digest);
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
return toFailure(error);
|
|
431
|
+
}
|
|
432
|
+
finally {
|
|
433
|
+
await nameH?.close();
|
|
434
|
+
await gensH?.close();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async function seal(dir, files) {
|
|
438
|
+
const dirs = new Set(['']);
|
|
439
|
+
for (const f of files) {
|
|
440
|
+
await chmod(path.join(dir, f.path), f.exec ? 0o555 : 0o444);
|
|
441
|
+
for (let d = path.posix.dirname(f.path); d !== '.'; d = path.posix.dirname(d))
|
|
442
|
+
dirs.add(d);
|
|
443
|
+
}
|
|
444
|
+
for (const d of [...dirs].sort((a, b) => b.length - a.length))
|
|
445
|
+
await chmod(path.join(dir, d), 0o555);
|
|
446
|
+
}
|
|
447
|
+
/** Verifies the staged copy and publishes it as an immutable generation. The staged copy is always removed and its handles closed. */
|
|
448
|
+
export async function publishStaged(staged, o) {
|
|
449
|
+
let gensH;
|
|
450
|
+
let nameH;
|
|
451
|
+
try {
|
|
452
|
+
let tree;
|
|
453
|
+
try {
|
|
454
|
+
tree = await collectFd(staged.stageH);
|
|
455
|
+
}
|
|
456
|
+
catch (e) {
|
|
457
|
+
throw new GenError('not-verified', e.message);
|
|
458
|
+
}
|
|
459
|
+
if (tree.excluded.length)
|
|
460
|
+
throw new GenError('ignored-content-not-allowed', 'excluded entries in staged tree');
|
|
461
|
+
const result = decide({
|
|
462
|
+
skillDir: staged.stagedDir, skillName: o.skillName, certificates: o.certificates, context: o.context, now: o.now,
|
|
463
|
+
tree: { profile: TREE_PROFILE, digest: tree.digest, root: staged.stagedDir, files: tree.files, totalBytes: tree.totalBytes, excluded: tree.excluded },
|
|
464
|
+
});
|
|
465
|
+
if (result.verdict !== 'VERIFIED')
|
|
466
|
+
throw new GenError('not-verified', result.reason, result.verdict);
|
|
467
|
+
const skill = validateSkillName(o.skillName);
|
|
468
|
+
const hexDigest = hexOf(tree.digest);
|
|
469
|
+
const manifest = {
|
|
470
|
+
type: GENERATION_TYPE, skill: o.skillName, treeDigest: tree.digest, files: tree.files.map(pickFile),
|
|
471
|
+
certificateId: result.certificateId, trustRootVersion: o.context.trustRoot.version,
|
|
472
|
+
revocationsVersion: o.context.revocations.version, buildProfile: o.buildProfile,
|
|
473
|
+
};
|
|
474
|
+
gensH = await walkDir(o.generationsRoot, 0o755);
|
|
475
|
+
await requirePrivate(gensH, 'generations root');
|
|
476
|
+
nameH = await openDirAt(procOf(gensH), skill, 0o755);
|
|
477
|
+
await requirePrivate(nameH, 'generation name directory');
|
|
478
|
+
const dest = path.join(path.resolve(o.generationsRoot), skill, hexDigest);
|
|
479
|
+
const destFd = `${procOf(nameH)}/${hexDigest}`;
|
|
480
|
+
if (await lstat(destFd).then(() => true, () => false)) {
|
|
481
|
+
if (!(await lstat(`${destFd}.manifest.json`).then(() => true, () => false)))
|
|
482
|
+
throw new GenError('generation-incomplete', 'generation directory without manifest');
|
|
483
|
+
const existing = await readGenerationAt(nameH, o.skillName, tree.digest);
|
|
484
|
+
if (!existing.ok)
|
|
485
|
+
return existing;
|
|
486
|
+
return { ok: true, created: false, manifest: existing.manifest, dir: dest };
|
|
487
|
+
}
|
|
488
|
+
// The stage name must still be the directory we verified (same inode); the staging root itself is private.
|
|
489
|
+
const src = `${procOf(staged.stagingH)}/${staged.name}`;
|
|
490
|
+
const [a, b] = await Promise.all([lstat(src), staged.stageH.stat()]);
|
|
491
|
+
if (a.ino !== b.ino || a.dev !== b.dev)
|
|
492
|
+
throw new GenError('not-verified', 'staged directory changed');
|
|
493
|
+
try {
|
|
494
|
+
await rename(src, destFd);
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
if (['EEXIST', 'ENOTEMPTY'].includes(error.code ?? ''))
|
|
498
|
+
throw new GenError('generation-incomplete', 'generation appeared concurrently');
|
|
499
|
+
throw error;
|
|
500
|
+
}
|
|
501
|
+
await seal(procOf(staged.stageH), manifest.files); // same inode as dest, reached by descriptor
|
|
502
|
+
await writeFileAtomic(`${destFd}.manifest.json`, manifestBytes(manifest), 0o444);
|
|
503
|
+
return { ok: true, created: true, manifest, dir: dest };
|
|
504
|
+
}
|
|
505
|
+
catch (error) {
|
|
506
|
+
return toFailure(error);
|
|
507
|
+
}
|
|
508
|
+
finally {
|
|
509
|
+
await nameH?.close();
|
|
510
|
+
await gensH?.close();
|
|
511
|
+
await staged.discard();
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/** Stage, verify the copy, publish. */
|
|
515
|
+
export async function installSkill(sourceDir, stagingRoot, o) {
|
|
516
|
+
const staged = await stageSkill(sourceDir, stagingRoot);
|
|
517
|
+
return staged.ok ? await publishStaged(staged.staged, o) : staged;
|
|
518
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The pid is readable but is not a plain host process (a thread id, a nested pid namespace): definitively not a live session. */
|
|
2
|
+
export declare class NotLiveError extends Error {
|
|
3
|
+
}
|
|
4
|
+
export interface ProcessInfo {
|
|
5
|
+
startedBootMs: number;
|
|
6
|
+
exe: string;
|
|
7
|
+
uid: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Throws a clear error on any platform but Linux. Everything in this module reads /proc, so the gate service checks this
|
|
11
|
+
* before it touches the disk; otherwise a non-Linux host would fail later with an unexplained ENOENT on a /proc path.
|
|
12
|
+
*/
|
|
13
|
+
export declare function assertGatePlatform(platform?: NodeJS.Platform): void;
|
|
14
|
+
export declare function bootId(): Promise<string>;
|
|
15
|
+
/** Milliseconds since boot (CLOCK_BOOTTIME, so suspend counts and wall-clock steps do not matter). */
|
|
16
|
+
export declare function bootMs(): Promise<number>;
|
|
17
|
+
/**
|
|
18
|
+
* Start time and uid of a PROCESS (a thread-group leader), without its exe. Throws if gone, unreadable, a thread id
|
|
19
|
+
* (a thread starts later than its process, which would shorten a session's generation set) or a process of a nested
|
|
20
|
+
* pid namespace (NSpid has more than one entry; unsupported, since pids in requests would not match this /proc).
|
|
21
|
+
*/
|
|
22
|
+
export declare function processFacts(pid: number): Promise<{
|
|
23
|
+
startedBootMs: number;
|
|
24
|
+
uid: number;
|
|
25
|
+
}>;
|
|
26
|
+
/** Checks a /proc/<pid>/status text (process, not a thread, not nested, not a zombie or dead) and returns the real uid. */
|
|
27
|
+
export declare function parseStatus(text: string, pid: number): number;
|
|
28
|
+
/** processFacts plus the exe link. Throws if the process is gone or /proc is unreadable. */
|
|
29
|
+
export declare function processInfo(pid: number): Promise<ProcessInfo>;
|
|
30
|
+
/** Soft RLIMIT_NOFILE of this process (`Infinity` when unlimited), from /proc/self/limits. */
|
|
31
|
+
export declare function nofileSoftLimit(): Promise<number>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Kernel facts for the gate service (Linux only, pure Node). Everything here comes from /proc, never from a request.
|
|
2
|
+
import { readFile, readlink } from 'node:fs/promises';
|
|
3
|
+
// shortcut: CLK_TCK is 100 on all mainstream Linux architectures; `getconf CLK_TCK` would need a shell. Upgrade if an
|
|
4
|
+
// architecture with another USER_HZ must be supported.
|
|
5
|
+
const CLK_TCK = 100;
|
|
6
|
+
const BOOT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
|
7
|
+
/** The pid is readable but is not a plain host process (a thread id, a nested pid namespace): definitively not a live session. */
|
|
8
|
+
export class NotLiveError extends Error {
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Throws a clear error on any platform but Linux. Everything in this module reads /proc, so the gate service checks this
|
|
12
|
+
* before it touches the disk; otherwise a non-Linux host would fail later with an unexplained ENOENT on a /proc path.
|
|
13
|
+
*/
|
|
14
|
+
export function assertGatePlatform(platform = process.platform) {
|
|
15
|
+
if (platform !== 'linux')
|
|
16
|
+
throw new Error(`the mago-ski gate service runs on Linux only (this is ${platform})`);
|
|
17
|
+
}
|
|
18
|
+
export async function bootId() {
|
|
19
|
+
const id = (await readFile('/proc/sys/kernel/random/boot_id', 'utf8')).trim();
|
|
20
|
+
if (!BOOT_ID.test(id))
|
|
21
|
+
throw new Error('unexpected boot_id format');
|
|
22
|
+
return id;
|
|
23
|
+
}
|
|
24
|
+
/** Milliseconds since boot (CLOCK_BOOTTIME, so suspend counts and wall-clock steps do not matter). */
|
|
25
|
+
export async function bootMs() {
|
|
26
|
+
const first = (await readFile('/proc/uptime', 'utf8')).split(' ')[0] ?? '';
|
|
27
|
+
if (!/^\d+\.\d+$/u.test(first))
|
|
28
|
+
throw new Error('unexpected /proc/uptime format');
|
|
29
|
+
return Math.floor(Number(first) * 1000);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Start time and uid of a PROCESS (a thread-group leader), without its exe. Throws if gone, unreadable, a thread id
|
|
33
|
+
* (a thread starts later than its process, which would shorten a session's generation set) or a process of a nested
|
|
34
|
+
* pid namespace (NSpid has more than one entry; unsupported, since pids in requests would not match this /proc).
|
|
35
|
+
*/
|
|
36
|
+
export async function processFacts(pid) {
|
|
37
|
+
if (!Number.isSafeInteger(pid) || pid < 1)
|
|
38
|
+
throw new Error('invalid pid');
|
|
39
|
+
const uid = parseStatus(await readFile(`/proc/${pid}/status`, 'utf8'), pid);
|
|
40
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
|
|
41
|
+
// comm sits in parentheses and may contain spaces and ')': the fields after it start behind the LAST ')'.
|
|
42
|
+
const rest = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
43
|
+
const ticks = Number(rest[19]); // field 22 overall; field 3 (state) is rest[0]
|
|
44
|
+
if (!Number.isSafeInteger(ticks) || ticks < 0)
|
|
45
|
+
throw new Error('unexpected stat format');
|
|
46
|
+
return { startedBootMs: Math.floor((ticks * 1000) / CLK_TCK), uid };
|
|
47
|
+
}
|
|
48
|
+
/** Checks a /proc/<pid>/status text (process, not a thread, not nested, not a zombie or dead) and returns the real uid. */
|
|
49
|
+
export function parseStatus(text, pid) {
|
|
50
|
+
const status = text.split('\n');
|
|
51
|
+
const field = (name) => status.find((l) => l.startsWith(`${name}:`))?.slice(name.length + 1).trim().split(/\s+/u);
|
|
52
|
+
const state = field('State')?.[0];
|
|
53
|
+
if (state === 'Z' || state === 'X')
|
|
54
|
+
throw new NotLiveError('zombie or dead process'); // a zombie keeps its /proc entry but runs nothing
|
|
55
|
+
if (Number(field('Tgid')?.[0]) !== pid)
|
|
56
|
+
throw new NotLiveError('not a process (thread id)');
|
|
57
|
+
if ((field('NSpid')?.length ?? 1) !== 1)
|
|
58
|
+
throw new NotLiveError('nested pid namespace is unsupported');
|
|
59
|
+
const uid = Number(field('Uid')?.[0]);
|
|
60
|
+
if (!Number.isSafeInteger(uid))
|
|
61
|
+
throw new Error('unexpected status format');
|
|
62
|
+
return uid;
|
|
63
|
+
}
|
|
64
|
+
/** processFacts plus the exe link. Throws if the process is gone or /proc is unreadable. */
|
|
65
|
+
export async function processInfo(pid) {
|
|
66
|
+
const facts = await processFacts(pid);
|
|
67
|
+
return { ...facts, exe: await readlink(`/proc/${pid}/exe`) };
|
|
68
|
+
}
|
|
69
|
+
/** Soft RLIMIT_NOFILE of this process (`Infinity` when unlimited), from /proc/self/limits. */
|
|
70
|
+
export async function nofileSoftLimit() {
|
|
71
|
+
const line = (await readFile('/proc/self/limits', 'utf8')).split('\n').find((l) => l.startsWith('Max open files'));
|
|
72
|
+
const soft = line?.slice('Max open files'.length).trim().split(/\s+/u)[0];
|
|
73
|
+
if (soft === 'unlimited')
|
|
74
|
+
return Infinity;
|
|
75
|
+
const n = Number(soft);
|
|
76
|
+
if (!soft || !Number.isSafeInteger(n) || n < 1)
|
|
77
|
+
throw new Error('unexpected /proc/self/limits format');
|
|
78
|
+
return n;
|
|
79
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type InboxRead = {
|
|
2
|
+
kind: 'docs';
|
|
3
|
+
trustRootBytes: Buffer;
|
|
4
|
+
revocationsBytes: Buffer;
|
|
5
|
+
} | {
|
|
6
|
+
kind: 'absent';
|
|
7
|
+
} | {
|
|
8
|
+
kind: 'unsafe';
|
|
9
|
+
reason: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function readInbox(dir: string, rootUid: number): Promise<InboxRead>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Root-only inbox for signed trust documents (E3 packet 7). The customer's distribution (any transport) drops
|
|
2
|
+
// `trust-root.json` and `revocations.json` here; the service reads them and offers them to the trust store, which
|
|
3
|
+
// alone decides acceptance. No network code. The inbox directory must be a real directory owned by `rootUid` and not
|
|
4
|
+
// group/world-writable; files must be regular non-symlinks within the document size limit.
|
|
5
|
+
import { lstat } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { MAX_CANONICAL_JSON_BYTES } from "../canonical-json.js";
|
|
8
|
+
import { readRegularFile } from "../fs-safe.js";
|
|
9
|
+
export async function readInbox(dir, rootUid) {
|
|
10
|
+
try {
|
|
11
|
+
const info = await lstat(dir).catch((e) => { if (e.code === 'ENOENT')
|
|
12
|
+
return undefined; throw e; });
|
|
13
|
+
if (!info)
|
|
14
|
+
return { kind: 'absent' };
|
|
15
|
+
if (info.isSymbolicLink() || !info.isDirectory())
|
|
16
|
+
return { kind: 'unsafe', reason: 'inbox must be a real directory' };
|
|
17
|
+
if (info.uid !== rootUid)
|
|
18
|
+
return { kind: 'unsafe', reason: `inbox must be owned by uid ${rootUid}` };
|
|
19
|
+
if ((info.mode & 0o022) !== 0)
|
|
20
|
+
return { kind: 'unsafe', reason: 'inbox must not be group- or world-writable' };
|
|
21
|
+
const read = (name) => readRegularFile(path.join(dir, name), name, MAX_CANONICAL_JSON_BYTES).catch((e) => { if (e.code === 'ENOENT')
|
|
22
|
+
return undefined; throw e; });
|
|
23
|
+
const trustRootBytes = await read('trust-root.json');
|
|
24
|
+
const revocationsBytes = await read('revocations.json');
|
|
25
|
+
return trustRootBytes && revocationsBytes ? { kind: 'docs', trustRootBytes, revocationsBytes } : { kind: 'absent' };
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
return { kind: 'unsafe', reason: e instanceof Error ? e.message : 'unreadable inbox' };
|
|
29
|
+
}
|
|
30
|
+
}
|