@mago-foundation/mago-ski 0.4.1 → 0.5.0-beta.1
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 +5 -3
- package/dist/hosts/github/check.d.ts +21 -0
- package/dist/hosts/github/check.js +124 -0
- package/dist/hosts/github/publish.d.ts +7 -0
- package/dist/hosts/github/publish.js +52 -0
- package/dist/hosts/github/run.d.ts +3 -0
- package/dist/hosts/github/run.js +2 -2
- package/dist/src/admission-evidence.d.ts +15 -0
- package/dist/src/admission-evidence.js +48 -0
- package/dist/src/admission.d.ts +102 -0
- package/dist/src/admission.js +316 -0
- package/dist/src/cli.js +199 -2
- package/dist/src/diff.d.ts +4 -0
- package/dist/src/diff.js +1 -1
- package/dist/src/experimental/sigstore.d.ts +24 -0
- package/dist/src/experimental/sigstore.js +22 -0
- package/dist/src/fs-safe.d.ts +15 -2
- package/dist/src/fs-safe.js +68 -50
- package/dist/src/gate/adapters/claude-code.js +8 -6
- package/dist/src/gate/adapters/codex.js +2 -6
- package/dist/src/gate/instance.js +7 -8
- package/dist/src/gate/setup.js +36 -46
- package/dist/src/profile.d.ts +34 -0
- package/dist/src/profile.js +182 -0
- package/dist/src/published-by.d.ts +64 -0
- package/dist/src/published-by.js +227 -0
- package/dist/src/usf-check.d.ts +28 -0
- package/dist/src/usf-check.js +128 -0
- package/dist/src/usf.d.ts +48 -0
- package/dist/src/usf.js +238 -0
- package/docs/hosts/publish.md +65 -0
- package/docs/hosts/skill-check.md +91 -0
- package/docs/spec/admission-v0.md +84 -0
- package/docs/spec/observed-profile-v1.md +51 -0
- package/package.json +4 -1
package/dist/src/fs-safe.d.ts
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
|
+
export interface ReadOwnedRegularFileOptions {
|
|
2
|
+
maxBytes?: number;
|
|
3
|
+
uid: number;
|
|
4
|
+
disallowGroupOtherWrite?: boolean;
|
|
5
|
+
notRegularMessage?: string;
|
|
6
|
+
ownershipMessage?: string;
|
|
7
|
+
}
|
|
1
8
|
export declare function isInside(root: string, candidate: string): boolean;
|
|
2
9
|
/**
|
|
3
|
-
* Reads a regular, non-symlink file, failing if it changes
|
|
4
|
-
*
|
|
10
|
+
* Reads a regular, non-symlink file without following symlinks on the final path component, failing if it changes
|
|
11
|
+
* while being read. Opens directly with `O_NOFOLLOW | O_NONBLOCK`, then checks the opened handle's type and size
|
|
12
|
+
* before reading at most `maxBytes` (+1 to detect growth).
|
|
5
13
|
*/
|
|
6
14
|
export declare function readRegularFile(filePath: string, label: string, maxBytes?: number): Promise<Buffer>;
|
|
15
|
+
/**
|
|
16
|
+
* Reads a regular, non-symlink file whose opened handle is owned by `options.uid` (and by default not writable by
|
|
17
|
+
* group or others), failing if it changes while being read.
|
|
18
|
+
*/
|
|
19
|
+
export declare function readOwnedRegularFile(filePath: string, label: string, options: ReadOwnedRegularFileOptions): Promise<Buffer>;
|
|
7
20
|
/** Resolves a file path and requires it to be outside `root` (both canonicalized). */
|
|
8
21
|
export declare function resolveOutside(filePath: string, root: string, label: string, { allowMissing }?: {
|
|
9
22
|
allowMissing?: boolean | undefined;
|
package/dist/src/fs-safe.js
CHANGED
|
@@ -3,13 +3,28 @@ import { constants as fsConstants } from 'node:fs';
|
|
|
3
3
|
import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
const noFollow = fsConstants.O_NOFOLLOW ?? 0;
|
|
6
|
-
// Never block in open(2) on a FIFO
|
|
6
|
+
// Never block in open(2) on a FIFO; O_NONBLOCK lets open return (or fail with ENXIO) and fstat rejects non-regular files.
|
|
7
7
|
const nonBlock = fsConstants.O_NONBLOCK ?? 0;
|
|
8
8
|
const DEFAULT_MAX_READ_BYTES = 1024 * 1024;
|
|
9
9
|
const READ_CHUNK_BYTES = 64 * 1024;
|
|
10
10
|
const DEFAULT_FILE_MODE = 0o644;
|
|
11
11
|
const DEFAULT_LOG_MODE = 0o600;
|
|
12
12
|
const TEMP_RANDOM_BYTES = 6;
|
|
13
|
+
function isNonRegularOpenError(error) {
|
|
14
|
+
const code = error?.code;
|
|
15
|
+
return code === 'ELOOP' || code === 'EISDIR' || code === 'ENXIO' || code === 'EOPNOTSUPP';
|
|
16
|
+
}
|
|
17
|
+
async function openRegularHandle(filePath, flags, notRegularMessage, mode) {
|
|
18
|
+
try {
|
|
19
|
+
return mode === undefined ? await open(filePath, flags) : await open(filePath, flags, mode);
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (isNonRegularOpenError(error)) {
|
|
23
|
+
throw new Error(notRegularMessage);
|
|
24
|
+
}
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
13
28
|
function sameFileIdentity(left, right) {
|
|
14
29
|
return left.dev === right.dev && left.ino === right.ino;
|
|
15
30
|
}
|
|
@@ -26,50 +41,64 @@ export function isInside(root, candidate) {
|
|
|
26
41
|
return (relative === '' ||
|
|
27
42
|
(relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));
|
|
28
43
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
44
|
+
async function readRegularHandle(handle, before, label, maxBytes) {
|
|
45
|
+
if (before.size > BigInt(maxBytes))
|
|
46
|
+
throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let total = 0;
|
|
49
|
+
while (total <= maxBytes) {
|
|
50
|
+
const remaining = maxBytes + 1 - total;
|
|
51
|
+
const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
|
52
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
|
|
53
|
+
if (bytesRead === 0)
|
|
54
|
+
break;
|
|
55
|
+
total += bytesRead;
|
|
56
|
+
chunks.push(chunk.subarray(0, bytesRead));
|
|
57
|
+
}
|
|
58
|
+
const after = await handle.stat({ bigint: true });
|
|
59
|
+
if (total > maxBytes || !sameFileVersion(before, after) || BigInt(total) !== after.size)
|
|
60
|
+
throw new Error(`${label} changed while being read or exceeds its size limit`);
|
|
61
|
+
return Buffer.concat(chunks, total);
|
|
62
|
+
}
|
|
63
|
+
async function openAndReadRegularFile(filePath, label, maxBytes, notRegularMessage, validateStat) {
|
|
34
64
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
|
|
35
65
|
throw new Error(`Invalid maxBytes limit for ${label}`);
|
|
36
66
|
}
|
|
37
|
-
const
|
|
38
|
-
const entry = await lstat(filePath, { bigint: true });
|
|
39
|
-
if (entry.isSymbolicLink() || !entry.isFile()) {
|
|
40
|
-
throw new Error(`${label} must be a regular, non-symlink file`);
|
|
41
|
-
}
|
|
42
|
-
if (entry.size > maxLimit) {
|
|
43
|
-
throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
|
|
44
|
-
}
|
|
45
|
-
let handle;
|
|
67
|
+
const handle = await openRegularHandle(filePath, fsConstants.O_RDONLY | noFollow | nonBlock, notRegularMessage);
|
|
46
68
|
try {
|
|
47
|
-
handle = await open(filePath, fsConstants.O_RDONLY | noFollow | nonBlock);
|
|
48
69
|
const before = await handle.stat({ bigint: true });
|
|
49
|
-
if (!before.isFile()
|
|
50
|
-
throw new Error(
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const chunks = [];
|
|
54
|
-
let total = 0;
|
|
55
|
-
while (total <= maxBytes) {
|
|
56
|
-
const remaining = maxBytes + 1 - total;
|
|
57
|
-
const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
|
58
|
-
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
|
|
59
|
-
if (bytesRead === 0)
|
|
60
|
-
break;
|
|
61
|
-
total += bytesRead;
|
|
62
|
-
chunks.push(chunk.subarray(0, bytesRead));
|
|
63
|
-
}
|
|
64
|
-
const after = await handle.stat({ bigint: true });
|
|
65
|
-
if (total > maxBytes || !sameFileVersion(before, after) || BigInt(total) !== after.size)
|
|
66
|
-
throw new Error(`${label} changed while being read or exceeds its size limit`);
|
|
67
|
-
return Buffer.concat(chunks, total);
|
|
70
|
+
if (!before.isFile())
|
|
71
|
+
throw new Error(notRegularMessage);
|
|
72
|
+
validateStat?.(before);
|
|
73
|
+
return await readRegularHandle(handle, before, label, maxBytes);
|
|
68
74
|
}
|
|
69
75
|
finally {
|
|
70
|
-
await handle
|
|
76
|
+
await handle.close();
|
|
71
77
|
}
|
|
72
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* Reads a regular, non-symlink file without following symlinks on the final path component, failing if it changes
|
|
81
|
+
* while being read. Opens directly with `O_NOFOLLOW | O_NONBLOCK`, then checks the opened handle's type and size
|
|
82
|
+
* before reading at most `maxBytes` (+1 to detect growth).
|
|
83
|
+
*/
|
|
84
|
+
export async function readRegularFile(filePath, label, maxBytes = DEFAULT_MAX_READ_BYTES) {
|
|
85
|
+
return await openAndReadRegularFile(filePath, label, maxBytes, `${label} must be a regular, non-symlink file`);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Reads a regular, non-symlink file whose opened handle is owned by `options.uid` (and by default not writable by
|
|
89
|
+
* group or others), failing if it changes while being read.
|
|
90
|
+
*/
|
|
91
|
+
export async function readOwnedRegularFile(filePath, label, options) {
|
|
92
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_READ_BYTES;
|
|
93
|
+
const notRegularMessage = options.notRegularMessage ?? `${label} must be a regular, non-symlink file`;
|
|
94
|
+
const ownershipMessage = options.ownershipMessage ?? `${label} must be owned by root and not writable by group or others`;
|
|
95
|
+
const checkMode = options.disallowGroupOtherWrite ?? true;
|
|
96
|
+
return await openAndReadRegularFile(filePath, label, maxBytes, notRegularMessage, (before) => {
|
|
97
|
+
if (before.uid !== BigInt(options.uid) || (checkMode && (before.mode & 18n) !== 0n)) {
|
|
98
|
+
throw new Error(ownershipMessage);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|
|
73
102
|
/** Resolves a file path and requires it to be outside `root` (both canonicalized). */
|
|
74
103
|
export async function resolveOutside(filePath, root, label, { allowMissing = false } = {}) {
|
|
75
104
|
const canonicalRoot = await realpath(path.resolve(root));
|
|
@@ -233,23 +262,12 @@ export async function resolveInsideDirectory(base, item, label) {
|
|
|
233
262
|
export async function appendToRegularFile(filePath, text, label, mode = DEFAULT_LOG_MODE) {
|
|
234
263
|
const target = path.resolve(filePath);
|
|
235
264
|
const flags = fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | noFollow | nonBlock;
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
existing = await lstat(target, { bigint: true });
|
|
239
|
-
if (existing.isSymbolicLink() || !existing.isFile())
|
|
240
|
-
throw new Error(`${label} must be a regular, non-symlink file`);
|
|
241
|
-
}
|
|
242
|
-
catch (error) {
|
|
243
|
-
if (error?.code !== 'ENOENT')
|
|
244
|
-
throw error;
|
|
245
|
-
}
|
|
246
|
-
const handle = await open(target, flags, mode);
|
|
265
|
+
const notRegularMessage = `${label} must be a regular, non-symlink file`;
|
|
266
|
+
const handle = await openRegularHandle(target, flags, notRegularMessage, mode);
|
|
247
267
|
try {
|
|
248
268
|
const opened = await handle.stat({ bigint: true });
|
|
249
269
|
if (!opened.isFile())
|
|
250
|
-
throw new Error(
|
|
251
|
-
if (existing && !sameFileIdentity(existing, opened))
|
|
252
|
-
throw new Error(`${label} changed while being opened`);
|
|
270
|
+
throw new Error(notRegularMessage);
|
|
253
271
|
await handle.appendFile(text, 'utf8');
|
|
254
272
|
}
|
|
255
273
|
finally {
|
|
@@ -25,9 +25,10 @@
|
|
|
25
25
|
// source says enforce (decideAction additionally never lets a service answer downgrade it).
|
|
26
26
|
// The adapter reads no environment variables. The config, its socket directory and the socket must be owned by root
|
|
27
27
|
// (uid 0); argv cannot change that (tests inject a uid through HookDeps via their own entry point).
|
|
28
|
-
import { lstat
|
|
28
|
+
import { lstat } from 'node:fs/promises';
|
|
29
29
|
import path from 'node:path';
|
|
30
30
|
import { isRecord } from "../../canonical-json.js";
|
|
31
|
+
import { readOwnedRegularFile } from "../../fs-safe.js";
|
|
31
32
|
import { validateSkillName } from "../../names.js";
|
|
32
33
|
import { decideAction } from "../contract.js";
|
|
33
34
|
import { parseStrictJson } from "../strict-json.js";
|
|
@@ -44,11 +45,12 @@ const notApproved = (verdict) => `This Skill is not approved by your organisatio
|
|
|
44
45
|
export async function loadConfig(file, rootUid = 0, extraKeys = []) {
|
|
45
46
|
if (!path.isAbsolute(file))
|
|
46
47
|
throw new Error('config path must be absolute');
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
const msg = 'config must be a regular, root-owned, non-writable file';
|
|
49
|
+
const raw = parseStrictJson(await readOwnedRegularFile(file, 'config', {
|
|
50
|
+
uid: rootUid,
|
|
51
|
+
notRegularMessage: msg,
|
|
52
|
+
ownershipMessage: msg,
|
|
53
|
+
}));
|
|
52
54
|
if (!isRecord(raw))
|
|
53
55
|
throw new Error('config must be an object');
|
|
54
56
|
const allowed = ['v', 'socket', 'mode', 'host_exes', 'client_deadline_ms', 'self_deadline_ms', ...extraKeys];
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
// MODE/CONFIG/OWNERSHIP rules are the Claude adapter's (claude-code.ts): argv[1] is the mode, enforce wins, config and
|
|
72
72
|
// socket must be root-owned, the adapter's own environment is not read. Extra config keys: `admin_root` (default
|
|
73
73
|
// /etc/codex/skills; must be the gate service's `managedDir`) and `skill_roots` (extra absolute non-admin roots).
|
|
74
|
-
import { lstat, open, readdir,
|
|
74
|
+
import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';
|
|
75
75
|
import path from 'node:path';
|
|
76
76
|
import { isRecord } from "../../canonical-json.js";
|
|
77
77
|
import { readRegularFile } from "../../fs-safe.js";
|
|
@@ -302,11 +302,7 @@ export async function readProcEnviron(pid) {
|
|
|
302
302
|
async function dotenvMayMoveHome(codexHome) {
|
|
303
303
|
const file = `${codexHome}/.env`;
|
|
304
304
|
try {
|
|
305
|
-
|
|
306
|
-
if (!st.isFile() || st.size > MAX_ENVIRON_BYTES)
|
|
307
|
-
return true; // symlink, FIFO, directory, huge: not inspected
|
|
308
|
-
// nosemgrep: mago-no-raw-read-of-signed-input -- /proc/<pid>/environ of the host process, size checked above; only searched for HOME
|
|
309
|
-
return (await readFile(file)).includes('HOME');
|
|
305
|
+
return (await readRegularFile(file, '.env', MAX_ENVIRON_BYTES)).includes('HOME');
|
|
310
306
|
}
|
|
311
307
|
catch (e) {
|
|
312
308
|
return e.code !== 'ENOENT';
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// One gate instance per host (design docs/design/gate-cli.md, section 1, G1, G7). This module is the single place that knows
|
|
2
2
|
// where an instance keeps its files, what its config file holds and how that maps to the service's own config.
|
|
3
|
-
import { lstat, readFile } from 'node:fs/promises';
|
|
4
3
|
import { createRequire } from 'node:module';
|
|
5
4
|
import path from 'node:path';
|
|
6
5
|
import { isRecord } from "../canonical-json.js";
|
|
6
|
+
import { readOwnedRegularFile } from "../fs-safe.js";
|
|
7
7
|
import { validateKeyId } from "../keys.js";
|
|
8
8
|
import { MODES } from "./contract.js";
|
|
9
9
|
import { parseStrictJson } from "./strict-json.js";
|
|
@@ -78,13 +78,12 @@ export function parseInstanceConfig(raw) {
|
|
|
78
78
|
}
|
|
79
79
|
/** Reads the instance config. It must be a regular file owned by `rootUid` and not writable by group or others. */
|
|
80
80
|
export async function readInstanceConfig(file, rootUid = 0) {
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return parseInstanceConfig(parseStrictJson(await readFile(file)));
|
|
81
|
+
const bytes = await readOwnedRegularFile(file, file, {
|
|
82
|
+
uid: rootUid,
|
|
83
|
+
notRegularMessage: `${file} must be a regular file`,
|
|
84
|
+
ownershipMessage: `${file} must be owned by root and not writable by group or others`,
|
|
85
|
+
});
|
|
86
|
+
return parseInstanceConfig(parseStrictJson(bytes));
|
|
88
87
|
}
|
|
89
88
|
/** The service's own config for an instance. */
|
|
90
89
|
export function instanceToServiceConfig(cfg, rootUid = 0) {
|
package/dist/src/gate/setup.js
CHANGED
|
@@ -9,7 +9,7 @@ import { constants as fsConstants, existsSync } from 'node:fs';
|
|
|
9
9
|
import path from 'node:path';
|
|
10
10
|
import { fileURLToPath } from 'node:url';
|
|
11
11
|
import { isRecord, parseCanonicalJsonBytes, serializeCanonicalJson } from "../canonical-json.js";
|
|
12
|
-
import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
|
|
12
|
+
import { readOwnedRegularFile, readRegularFile, writeFileAtomic } from "../fs-safe.js";
|
|
13
13
|
import { validateKeyId } from "../keys.js";
|
|
14
14
|
import { claudeCodeManagedSettings } from "./adapters/claude-code-settings.js";
|
|
15
15
|
import { codexManagedConfigToml, codexRequirementsToml } from "./adapters/codex-requirements.js";
|
|
@@ -75,10 +75,16 @@ const message = (e) => (e instanceof Error ? e.message : String(e));
|
|
|
75
75
|
* It is opened without following a link; the type and owner are checked on the descriptor, and only then are its first 4 bytes read.
|
|
76
76
|
*/
|
|
77
77
|
export async function checkHostExe(exe, uid, stopAt = '/') {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
78
|
+
let handle;
|
|
79
|
+
try {
|
|
80
|
+
handle = await open(exe, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
const code = errnoCode(e);
|
|
84
|
+
if (code === 'ELOOP' || code === 'EISDIR' || code === 'ENXIO' || code === 'EOPNOTSUPP')
|
|
85
|
+
throw new Error(`${exe} is not a regular file`);
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
82
88
|
try {
|
|
83
89
|
const fd = await handle.stat();
|
|
84
90
|
if (!fd.isFile())
|
|
@@ -404,10 +410,7 @@ function manifestText(files, previous) {
|
|
|
404
410
|
async function readManifest(file, uid) {
|
|
405
411
|
let raw;
|
|
406
412
|
try {
|
|
407
|
-
|
|
408
|
-
if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
409
|
-
return undefined;
|
|
410
|
-
raw = parseCanonicalJsonBytes(await readRegularFile(file, 'manifest', 1024 * 1024), 'manifest');
|
|
413
|
+
raw = parseCanonicalJsonBytes(await readOwnedRegularFile(file, 'manifest', { uid, maxBytes: 1024 * 1024 }), 'manifest');
|
|
411
414
|
}
|
|
412
415
|
catch {
|
|
413
416
|
return undefined;
|
|
@@ -501,16 +504,19 @@ export async function planInit(opts) {
|
|
|
501
504
|
const sharedOwn = await readManifest(p.sharedManifest, uid);
|
|
502
505
|
const foreign = [];
|
|
503
506
|
for (const f of files) {
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
507
|
+
let bytes;
|
|
508
|
+
try {
|
|
509
|
+
bytes = await readRegularFile(f.path, f.path);
|
|
510
|
+
}
|
|
511
|
+
catch (e) {
|
|
512
|
+
const code = errnoCode(e);
|
|
513
|
+
if (code === 'ENOENT' || code === 'ENOTDIR')
|
|
514
|
+
continue;
|
|
515
|
+
if (code !== undefined)
|
|
516
|
+
throw e;
|
|
513
517
|
}
|
|
518
|
+
const h = bytes ? sha256(bytes) : undefined;
|
|
519
|
+
const ours = h !== undefined && (own?.get(f.path) === h || sharedOwn?.get(f.path) === h);
|
|
514
520
|
if (!ours)
|
|
515
521
|
foreign.push(f.path);
|
|
516
522
|
}
|
|
@@ -661,14 +667,6 @@ export async function applyInit(plan, opts = {}) {
|
|
|
661
667
|
}
|
|
662
668
|
return result;
|
|
663
669
|
}
|
|
664
|
-
/** lstat: a regular file (not a symlink) owned by `uid` and not writable by group or others. */
|
|
665
|
-
async function trustedRegularFile(file, uid) {
|
|
666
|
-
const info = await lstat(file);
|
|
667
|
-
if (info.isSymbolicLink() || !info.isFile())
|
|
668
|
-
throw new Error(`${file} must be a regular file, not a symlink`);
|
|
669
|
-
if (info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
670
|
-
throw new Error(NOT_ROOT(file));
|
|
671
|
-
}
|
|
672
670
|
/** Read-only checks, in the order of the design (v1 section 6, G6, G12). Never throws. */
|
|
673
671
|
export async function doctor(host, opts = {}) {
|
|
674
672
|
const out = [];
|
|
@@ -741,17 +739,14 @@ export async function doctor(host, opts = {}) {
|
|
|
741
739
|
// Host config and hook config: exact content of what `gate init` would write now.
|
|
742
740
|
// Codex: the listed homes live in the hook config (the instance config does not know them); deny_read is present or not as written.
|
|
743
741
|
const homes = (host === 'codex' ? await readHookHomes(p.hook) : undefined) ?? { userHomes: [], codexHomes: [] };
|
|
744
|
-
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: the root-owned host config, only searched for one line
|
|
745
|
-
const denyRoots = host === 'codex' && /^deny_read = /mu.test(await readFile(p.hostConfig, 'utf8').catch(() => '')) ? codexDenyRoots(homes) : [];
|
|
746
742
|
const hookExpected = hookConfigText(host, c, homes);
|
|
747
743
|
let hostFileMode;
|
|
748
744
|
try {
|
|
745
|
+
const msg = `${p.hostConfig} must be a regular file owned by root and not writable by others`;
|
|
746
|
+
const hostBytes = await readOwnedRegularFile(p.hostConfig, p.hostConfig, { uid, notRegularMessage: msg, ownershipMessage: msg });
|
|
747
|
+
const denyRoots = host === 'codex' && /^deny_read = /mu.test(hostBytes.toString('utf8')) ? codexDenyRoots(homes) : [];
|
|
749
748
|
const expected = hostConfigText(host, c.mode, tc, p.hook, denyRoots);
|
|
750
|
-
const
|
|
751
|
-
if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
752
|
-
throw new Error(`${p.hostConfig} must be a regular file owned by root and not writable by others`);
|
|
753
|
-
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above as a root-owned regular file not writable by others
|
|
754
|
-
const have = sha256(await readFile(p.hostConfig));
|
|
749
|
+
const have = sha256(hostBytes);
|
|
755
750
|
if (have === sha256(expected)) {
|
|
756
751
|
hostFileMode = c.mode;
|
|
757
752
|
add('host config', 'PASS', `${p.hostConfig} matches what gate init writes`);
|
|
@@ -774,9 +769,8 @@ export async function doctor(host, opts = {}) {
|
|
|
774
769
|
// The unit and the drop-in: root-owned regular files with the content the plan would write.
|
|
775
770
|
for (const [label, file, expected] of [['unit', p.unit, unitText(tc)], ['drop-in', p.dropin, dropinText(c, p.stateRoot)]]) {
|
|
776
771
|
try {
|
|
777
|
-
await
|
|
778
|
-
|
|
779
|
-
if (sha256(await readFile(file)) !== sha256(expected))
|
|
772
|
+
const bytes = await readOwnedRegularFile(file, file, { uid, notRegularMessage: `${file} must be a regular file, not a symlink`, ownershipMessage: NOT_ROOT(file) });
|
|
773
|
+
if (sha256(bytes) !== sha256(expected))
|
|
780
774
|
throw new Error(`${file} differs from what gate init would write now; run gate init again`);
|
|
781
775
|
add(label, 'PASS', `${file} matches what gate init writes`);
|
|
782
776
|
}
|
|
@@ -785,9 +779,8 @@ export async function doctor(host, opts = {}) {
|
|
|
785
779
|
}
|
|
786
780
|
}
|
|
787
781
|
try {
|
|
788
|
-
await
|
|
789
|
-
|
|
790
|
-
if (sha256(await readFile(p.hook)) !== sha256(hookExpected))
|
|
782
|
+
const bytes = await readOwnedRegularFile(p.hook, p.hook, { uid, notRegularMessage: `${p.hook} must be a regular file, not a symlink`, ownershipMessage: NOT_ROOT(p.hook) });
|
|
783
|
+
if (sha256(bytes) !== sha256(hookExpected))
|
|
791
784
|
throw new Error(`${p.hook} differs from what gate init would write now; run gate init again`);
|
|
792
785
|
add('hook config', 'PASS', `${p.hook} matches what gate init writes`);
|
|
793
786
|
}
|
|
@@ -899,8 +892,7 @@ export async function doctor(host, opts = {}) {
|
|
|
899
892
|
/* ---------------------------------------------------------------------------------------------- Codex doctor checks */
|
|
900
893
|
async function readHookHomes(file) {
|
|
901
894
|
try {
|
|
902
|
-
|
|
903
|
-
const raw = parseStrictJson(await readFile(file));
|
|
895
|
+
const raw = parseStrictJson(await readRegularFile(file, 'hook config'));
|
|
904
896
|
if (!isRecord(raw))
|
|
905
897
|
return undefined;
|
|
906
898
|
const list = (v) => (Array.isArray(v) && v.every((x) => typeof x === 'string') ? v : undefined);
|
|
@@ -958,11 +950,9 @@ async function codexDoctor(c, p, homes, uid, opts, add) {
|
|
|
958
950
|
// managed_config.toml: exact content, root-owned.
|
|
959
951
|
try {
|
|
960
952
|
const file = p.managedConfig;
|
|
961
|
-
const
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above as a root-owned regular file not writable by others
|
|
965
|
-
if (sha256(await readFile(file)) !== sha256(codexManagedConfigToml()))
|
|
953
|
+
const msg = `${file} must be a regular file owned by root and not writable by others`;
|
|
954
|
+
const bytes = await readOwnedRegularFile(file, file, { uid, notRegularMessage: msg, ownershipMessage: msg });
|
|
955
|
+
if (sha256(bytes) !== sha256(codexManagedConfigToml()))
|
|
966
956
|
throw new Error(`${file} differs from what gate init would write now; run gate init again`);
|
|
967
957
|
add('managed config', 'PASS', `${file} matches what gate init writes`);
|
|
968
958
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type SkillTree } from './tree-digest.ts';
|
|
2
|
+
export declare const PROFILE_FORMAT = "mago.observed-profile/v1";
|
|
3
|
+
/** Same limit as the origin scan in diff.ts: larger files are not searched. */
|
|
4
|
+
export declare const MAX_SEARCHED_BYTES: number;
|
|
5
|
+
export interface ScriptEvidence {
|
|
6
|
+
path: string;
|
|
7
|
+
reason: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ObservedProfile {
|
|
10
|
+
profile: typeof PROFILE_FORMAT;
|
|
11
|
+
/** Tree digest (mago.skill-tree/v2) of the bytes this profile describes. */
|
|
12
|
+
digest: string;
|
|
13
|
+
/** Host names of http and https addresses found in any searched file. */
|
|
14
|
+
web_hosts: string[];
|
|
15
|
+
/** Files that are code: executable bit, `#!`, a script extension or a build-file name, or Markdown with shell code blocks. */
|
|
16
|
+
scripts: ScriptEvidence[];
|
|
17
|
+
/** Commands named first on a line inside shell code blocks in Markdown files (not a complete list). */
|
|
18
|
+
programs: string[];
|
|
19
|
+
not_searched: {
|
|
20
|
+
/** Images, fonts, audio and video: not searched, not a gap. */
|
|
21
|
+
media: string[];
|
|
22
|
+
/** Binary, not UTF-8, or larger than 2 MiB. */
|
|
23
|
+
unreadable: string[];
|
|
24
|
+
/** Left out by `.skilldigestignore`. */
|
|
25
|
+
ignored: string[];
|
|
26
|
+
};
|
|
27
|
+
/** False when anything above may be missing: an unreadable or ignored file, or a scan limit. */
|
|
28
|
+
complete: boolean;
|
|
29
|
+
}
|
|
30
|
+
/** The profile of a tree read with `collectSkillTree(dir, { includeContents: true })`. */
|
|
31
|
+
export declare function profileTree(tree: SkillTree & {
|
|
32
|
+
contents?: Map<string, Buffer>;
|
|
33
|
+
}): ObservedProfile;
|
|
34
|
+
export declare function observeSkill(skillDir: string): Promise<ObservedProfile>;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Observed profile (mago.observed-profile/v1): what a Skill's own bytes show, computed deterministically and offline.
|
|
2
|
+
// It works on every Skill and never reads the frontmatter, so it cannot be steered by what a Skill says about itself.
|
|
3
|
+
// Spec: docs/spec/observed-profile-v1.md. Changing what it extracts needs a new profile version.
|
|
4
|
+
import { isUtf8 } from 'node:buffer';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { collectOrigins } from "./diff.js";
|
|
7
|
+
import { collectSkillTree, pathsNotCovered } from "./tree-digest.js";
|
|
8
|
+
export const PROFILE_FORMAT = 'mago.observed-profile/v1';
|
|
9
|
+
/** Same limit as the origin scan in diff.ts: larger files are not searched. */
|
|
10
|
+
export const MAX_SEARCHED_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
const MAX_PROGRAMS = 200;
|
|
12
|
+
const SCRIPT_EXTENSIONS = new Set(['.sh', '.bash', '.zsh', '.fish', '.ksh', '.py', '.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.rb', '.pl', '.php', '.lua', '.ps1', '.psm1', '.bat', '.cmd',
|
|
13
|
+
'.go', '.rs', '.java', '.kt', '.kts', '.swift', '.c', '.cc', '.cpp', '.cs', '.vbs', '.awk', '.tcl', '.r', '.jl', '.ex', '.exs', '.groovy', '.scala', '.applescript', '.scpt', '.jar', '.wasm', '.exe', '.dll', '.so', '.dylib']);
|
|
14
|
+
const SCRIPT_NAMES = new Set(['makefile', 'gnumakefile', 'justfile', 'rakefile', 'dockerfile', 'containerfile']);
|
|
15
|
+
const MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown', '.mdx']);
|
|
16
|
+
/** Binary formats that hold no instructions or code for an agent; they are not searched and are not a gap. */
|
|
17
|
+
const MEDIA_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.bmp', '.ico', '.tif', '.tiff', '.heic', '.woff', '.woff2', '.ttf', '.otf', '.eot', '.mp3', '.wav', '.ogg', '.flac', '.m4a', '.mp4', '.webm', '.mov']);
|
|
18
|
+
/** Shell languages, compared on the info string's first part: `bash-session`, `zsh_session`, `sh+x` count as their shell. */
|
|
19
|
+
const SHELL_LANGUAGES = new Set(['sh', 'bash', 'shell', 'zsh', 'fish', 'ksh', 'csh', 'tcsh', 'dash', 'ash', 'console', 'shellsession', 'shellscript', 'terminal', 'powershell', 'ps1', 'pwsh', 'cmd', 'bat', 'batch', 'nushell', 'nu']);
|
|
20
|
+
const isShellLanguage = (info) => SHELL_LANGUAGES.has(info.toLowerCase().split(/[-_+.:]/u)[0]);
|
|
21
|
+
// Indentation, blockquote markers and list markers (`-`, `*`, `+`, `1.`, `1)`), then the fence, then `bash`, `{bash}` or `{.bash ...}`.
|
|
22
|
+
// The three prefix alternatives start with different characters, so the pattern stays linear.
|
|
23
|
+
const fenceOpenPattern = /^(?:[ \t>]|[-*+][ \t]|[0-9]{1,9}[.)][ \t])*(`{3,}|~{3,})[ \t]*\{?\.?([A-Za-z0-9_+.:-]*)/u;
|
|
24
|
+
/** Bracketed IPv6 hosts, which the shared origin scan in diff.ts does not match. */
|
|
25
|
+
const ipv6UrlPattern = /https?:\/\/\[[0-9A-Fa-f:.]{2,45}\](?::[0-9]{1,5})?/gu;
|
|
26
|
+
const MAX_IPV6_HOSTS = 128;
|
|
27
|
+
// Brackets kept, so a bracketed IPv6 host after a backslash stays in the candidate.
|
|
28
|
+
const urlCandidatePattern = /https?:\/\/[^\s"'`<>(){}]+/giu;
|
|
29
|
+
const plainHostPattern = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/u;
|
|
30
|
+
/**
|
|
31
|
+
* The host another URL parser reads from an address with a backslash. WHATWG (used above) treats `\` like `/`, so
|
|
32
|
+
* `https://api.github.com\@evil.example/` is api.github.com there; Python's urlparse and others read evil.example.
|
|
33
|
+
* Both are listed.
|
|
34
|
+
*/
|
|
35
|
+
function backslashHost(candidate) {
|
|
36
|
+
if (!candidate.includes('\\'))
|
|
37
|
+
return null;
|
|
38
|
+
const rest = candidate.slice(candidate.indexOf('://') + 3);
|
|
39
|
+
const end = rest.search(/[/?#]/u);
|
|
40
|
+
const authority = end < 0 ? rest : rest.slice(0, end);
|
|
41
|
+
let host = authority.slice(authority.lastIndexOf('@') + 1).replace(/:[0-9]*$/u, '');
|
|
42
|
+
try {
|
|
43
|
+
host = decodeURIComponent(host);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// Not valid percent-encoding: keep the text as it is.
|
|
47
|
+
}
|
|
48
|
+
host = host.toLowerCase().replace(/\.$/u, '');
|
|
49
|
+
if (/^\[[0-9a-f:.]+\]$/u.test(host)) {
|
|
50
|
+
try {
|
|
51
|
+
return new URL(`http://${host}/`).hostname;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return plainHostPattern.test(host) ? host : null;
|
|
58
|
+
}
|
|
59
|
+
const programPattern = /^[A-Za-z0-9._+-]{1,64}$/u;
|
|
60
|
+
const PREFIX_WORDS = new Set(['sudo', 'doas', 'env', 'exec', 'time', 'nohup', 'command', 'builtin', 'then', 'do', 'else', '!']);
|
|
61
|
+
const extension = (file) => path.posix.extname(file).toLowerCase();
|
|
62
|
+
/** Counts lines that open a shell code block. No open/close tracking: a crafted pairing can never hide a block. */
|
|
63
|
+
function shellFenceCount(text) {
|
|
64
|
+
let count = 0;
|
|
65
|
+
for (const line of text.split(/\r?\n|\r/u)) {
|
|
66
|
+
const match = fenceOpenPattern.exec(line);
|
|
67
|
+
if (match && isShellLanguage(match[2]))
|
|
68
|
+
count += 1;
|
|
69
|
+
}
|
|
70
|
+
return count;
|
|
71
|
+
}
|
|
72
|
+
/** Programs named first on each command line of shell code blocks. Report-only, so open/close tracking is fine here. */
|
|
73
|
+
function shellPrograms(text, into) {
|
|
74
|
+
let open = null;
|
|
75
|
+
for (const line of text.split(/\r?\n|\r/u)) {
|
|
76
|
+
const fence = fenceOpenPattern.exec(line);
|
|
77
|
+
if (open) {
|
|
78
|
+
if (fence && fence[1][0] === open.char && fence[1].length >= open.length && fence[2] === '') {
|
|
79
|
+
open = null;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (!open.shell)
|
|
83
|
+
continue;
|
|
84
|
+
let words = line.replace(/^(?:[ \t>]|[-*+][ \t]|[0-9]{1,9}[.)][ \t])*/u, '').replace(/^(?:\$|PS>|>|%)[ \t]+/u, '').split(/[ \t]+/u).filter(Boolean);
|
|
85
|
+
while (words.length > 0 && (PREFIX_WORDS.has(words[0]) || /^[A-Za-z_][A-Za-z0-9_]*=/u.test(words[0])))
|
|
86
|
+
words = words.slice(1);
|
|
87
|
+
const first = words[0];
|
|
88
|
+
if (first === undefined || first.startsWith('#'))
|
|
89
|
+
continue;
|
|
90
|
+
const name = path.posix.basename(first);
|
|
91
|
+
if (programPattern.test(name) && into.size < MAX_PROGRAMS)
|
|
92
|
+
into.add(name);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (fence)
|
|
96
|
+
open = { char: fence[1][0], length: fence[1].length, shell: isShellLanguage(fence[2]) };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function scriptReason(file, exec, content, text) {
|
|
100
|
+
if (exec)
|
|
101
|
+
return 'executable file';
|
|
102
|
+
if (content.subarray(0, 2).toString('latin1') === '#!')
|
|
103
|
+
return 'starts with #!';
|
|
104
|
+
if (SCRIPT_EXTENSIONS.has(extension(file)))
|
|
105
|
+
return `${extension(file)} file`;
|
|
106
|
+
if (SCRIPT_NAMES.has(path.posix.basename(file).toLowerCase()))
|
|
107
|
+
return 'build or task file';
|
|
108
|
+
if (text !== null && MARKDOWN_EXTENSIONS.has(extension(file))) {
|
|
109
|
+
const fences = shellFenceCount(text);
|
|
110
|
+
if (fences > 0)
|
|
111
|
+
return `${fences} shell code block${fences === 1 ? '' : 's'}`;
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
/** The profile of a tree read with `collectSkillTree(dir, { includeContents: true })`. */
|
|
116
|
+
export function profileTree(tree) {
|
|
117
|
+
const contents = tree.contents;
|
|
118
|
+
const searched = new Map();
|
|
119
|
+
const media = [];
|
|
120
|
+
const unreadable = [];
|
|
121
|
+
const scripts = [];
|
|
122
|
+
const programs = new Set();
|
|
123
|
+
for (const file of tree.files) {
|
|
124
|
+
const content = contents.get(file.path);
|
|
125
|
+
const searchable = content.length <= MAX_SEARCHED_BYTES && !content.includes(0) && isUtf8(content);
|
|
126
|
+
if (!searchable)
|
|
127
|
+
(MEDIA_EXTENSIONS.has(extension(file.path)) ? media : unreadable).push(file.path);
|
|
128
|
+
if (searchable)
|
|
129
|
+
searched.set(file.path, content);
|
|
130
|
+
const text = searchable ? content.toString('utf8') : null;
|
|
131
|
+
const reason = scriptReason(file.path, file.exec, content, text);
|
|
132
|
+
if (reason)
|
|
133
|
+
scripts.push({ path: file.path, reason });
|
|
134
|
+
if (text !== null && MARKDOWN_EXTENSIONS.has(extension(file.path)))
|
|
135
|
+
shellPrograms(text, programs);
|
|
136
|
+
}
|
|
137
|
+
const ignored = pathsNotCovered(tree.excluded);
|
|
138
|
+
// Only searchable files go in, so an incomplete scan means a limit was hit (sites or addresses).
|
|
139
|
+
const origins = collectOrigins(searched);
|
|
140
|
+
const hosts = new Set(origins.origins.map((origin) => new URL(origin).hostname));
|
|
141
|
+
let limitHit = !origins.complete;
|
|
142
|
+
scan: for (const content of searched.values()) {
|
|
143
|
+
const text = content.toString('utf8');
|
|
144
|
+
if (text.includes('\\')) {
|
|
145
|
+
for (const match of text.matchAll(urlCandidatePattern)) {
|
|
146
|
+
const host = backslashHost(match[0]);
|
|
147
|
+
if (host)
|
|
148
|
+
hosts.add(host);
|
|
149
|
+
if (hosts.size > origins.origins.length + MAX_IPV6_HOSTS) {
|
|
150
|
+
limitHit = true;
|
|
151
|
+
break scan;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for (const match of text.matchAll(ipv6UrlPattern)) {
|
|
156
|
+
let host;
|
|
157
|
+
try {
|
|
158
|
+
host = new URL(match[0]).hostname;
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
hosts.add(host);
|
|
164
|
+
if (hosts.size > origins.origins.length + MAX_IPV6_HOSTS) {
|
|
165
|
+
limitHit = true;
|
|
166
|
+
break scan;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
profile: PROFILE_FORMAT,
|
|
172
|
+
digest: tree.digest,
|
|
173
|
+
web_hosts: [...hosts].sort(),
|
|
174
|
+
scripts,
|
|
175
|
+
programs: [...programs].sort(),
|
|
176
|
+
not_searched: { media, unreadable, ignored },
|
|
177
|
+
complete: !limitHit && unreadable.length === 0 && ignored.length === 0,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
export async function observeSkill(skillDir) {
|
|
181
|
+
return profileTree(await collectSkillTree(skillDir, { includeContents: true }));
|
|
182
|
+
}
|