@mago-foundation/mago-ski 0.1.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.
Files changed (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
@@ -1,33 +1,73 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { createHash, randomBytes } from 'node:crypto';
2
2
  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 swapped in after the lstat check; the fstat below then rejects it.
7
+ const nonBlock = fsConstants.O_NONBLOCK ?? 0;
8
+ const DEFAULT_MAX_READ_BYTES = 1024 * 1024;
9
+ const READ_CHUNK_BYTES = 64 * 1024;
10
+ const DEFAULT_FILE_MODE = 0o644;
11
+ const DEFAULT_LOG_MODE = 0o600;
12
+ const TEMP_RANDOM_BYTES = 6;
13
+ function sameFileIdentity(left, right) {
14
+ return left.dev === right.dev && left.ino === right.ino;
15
+ }
16
+ function sameFileVersion(left, right) {
17
+ return (sameFileIdentity(left, right) &&
18
+ left.size === right.size &&
19
+ left.mtimeNs === right.mtimeNs &&
20
+ left.ctimeNs === right.ctimeNs);
21
+ }
6
22
  export function isInside(root, candidate) {
7
- const relative = path.relative(root, candidate);
8
- return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
23
+ const resolvedRoot = path.resolve(root);
24
+ const resolvedCandidate = path.resolve(candidate);
25
+ const relative = path.relative(resolvedRoot, resolvedCandidate);
26
+ return (relative === '' ||
27
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));
9
28
  }
10
- /** Reads a regular, non-symlink file, failing if it changes while being read. */
11
- export async function readRegularFile(filePath, label, maxBytes = 1024 * 1024) {
12
- const entry = await lstat(filePath);
13
- if (entry.isSymbolicLink() || !entry.isFile())
29
+ /**
30
+ * Reads a regular, non-symlink file, failing if it changes while being read.
31
+ * The type and size are checked before any content is read, and at most `maxBytes` (+1 to detect growth) are read.
32
+ */
33
+ export async function readRegularFile(filePath, label, maxBytes = DEFAULT_MAX_READ_BYTES) {
34
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
35
+ throw new Error(`Invalid maxBytes limit for ${label}`);
36
+ }
37
+ const maxLimit = BigInt(maxBytes);
38
+ const entry = await lstat(filePath, { bigint: true });
39
+ if (entry.isSymbolicLink() || !entry.isFile()) {
14
40
  throw new Error(`${label} must be a regular, non-symlink file`);
15
- if (entry.size > maxBytes)
41
+ }
42
+ if (entry.size > maxLimit) {
16
43
  throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
17
- const handle = await open(filePath, fsConstants.O_RDONLY | noFollow);
44
+ }
45
+ let handle;
18
46
  try {
19
- const before = await handle.stat();
20
- if (!before.isFile() || before.dev !== entry.dev || before.ino !== entry.ino)
47
+ handle = await open(filePath, fsConstants.O_RDONLY | noFollow | nonBlock);
48
+ const before = await handle.stat({ bigint: true });
49
+ if (!before.isFile() || !sameFileIdentity(entry, before))
21
50
  throw new Error(`${label} changed while being read`);
22
- const bytes = await handle.readFile();
23
- const after = await handle.stat();
24
- if (bytes.length > maxBytes || before.size !== after.size || before.mtimeMs !== after.mtimeMs || bytes.length !== after.size) {
25
- throw new Error(`${label} changed while being read or exceeds its size limit`);
51
+ if (before.size > maxLimit)
52
+ throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
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));
26
63
  }
27
- return bytes;
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);
28
68
  }
29
69
  finally {
30
- await handle.close();
70
+ await handle?.close();
31
71
  }
32
72
  }
33
73
  /** Resolves a file path and requires it to be outside `root` (both canonicalized). */
@@ -44,36 +84,75 @@ export async function resolveOutside(filePath, root, label, { allowMissing = fal
44
84
  canonical = await realpath(requested);
45
85
  }
46
86
  catch (error) {
47
- if (!allowMissing || error?.code !== 'ENOENT')
87
+ const code = error?.code;
88
+ if (!allowMissing || code !== 'ENOENT')
48
89
  throw error;
49
- canonical = path.join(await realpath(path.dirname(requested)), path.basename(requested));
90
+ canonical = path.join(await realpathAllowingMissing(path.dirname(requested)), path.basename(requested));
50
91
  }
51
- if (isInside(canonicalRoot, canonical))
92
+ if (isInside(canonicalRoot, canonical)) {
52
93
  throw new Error(`${label} must be outside ${canonicalRoot}`);
94
+ }
53
95
  return canonical;
54
96
  }
55
97
  async function writeHandle(filePath, bytes, mode, flags) {
56
98
  const handle = await open(filePath, flags, mode);
99
+ let succeeded = false;
57
100
  try {
58
101
  await handle.writeFile(bytes);
59
102
  await handle.sync();
103
+ succeeded = true;
60
104
  }
61
- catch (error) {
62
- await handle.close();
63
- await unlink(filePath).catch(() => { });
64
- throw error;
105
+ finally {
106
+ await handle.close().catch((closeError) => {
107
+ if (succeeded) {
108
+ succeeded = false;
109
+ throw closeError;
110
+ }
111
+ });
112
+ if (!succeeded)
113
+ await unlink(filePath).catch(() => { });
65
114
  }
66
- await handle.close();
67
115
  }
68
116
  /** Creates a new file; refuses to overwrite anything that already exists. */
69
- export async function writeNewFile(filePath, bytes, mode = 0o644) {
117
+ export async function writeNewFile(filePath, bytes, mode = DEFAULT_FILE_MODE) {
70
118
  const target = path.resolve(filePath);
71
- await writeHandle(target, bytes, mode, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow);
119
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow;
120
+ await writeHandle(target, bytes, mode, flags);
72
121
  return target;
73
122
  }
74
- /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
75
- export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
123
+ /** The file a write was meant to replace was no longer the one that was read (see `writeFileAtomic`'s `expectSha256`). */
124
+ export class FileChangedError extends Error {
125
+ constructor(message = 'File changed before it could be replaced') {
126
+ super(message);
127
+ this.name = 'FileChangedError';
128
+ }
129
+ }
130
+ /** `sha256:<hex>` of the regular file at `target`, or `null` when it does not exist. Anything else throws. */
131
+ async function currentSha256(target) {
132
+ let bytes;
133
+ try {
134
+ bytes = await readRegularFile(target, 'Document', Number.MAX_SAFE_INTEGER);
135
+ }
136
+ catch (error) {
137
+ if (error?.code === 'ENOENT')
138
+ return null;
139
+ throw new FileChangedError();
140
+ }
141
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
142
+ }
143
+ /**
144
+ * Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one.
145
+ *
146
+ * `options.expectSha256`: `undefined` checks nothing. A `sha256:<hex>` string requires the existing path to be a regular
147
+ * file with that SHA-256, `null` requires the path not to exist. The check runs after the temporary file is written and
148
+ * immediately before the rename; a mismatch removes the temporary file and throws `FileChangedError`. A process that can
149
+ * write the folder can still swap the file between that check and the rename.
150
+ */
151
+ export async function writeFileAtomic(filePath, bytes, mode = DEFAULT_FILE_MODE, options = {}) {
76
152
  const target = path.resolve(filePath);
153
+ const randomHex = randomBytes(TEMP_RANDOM_BYTES).toString('hex');
154
+ const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomHex}.tmp`);
155
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow;
77
156
  try {
78
157
  const existing = await lstat(target);
79
158
  if (existing.isSymbolicLink() || !existing.isFile())
@@ -83,9 +162,10 @@ export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
83
162
  if (error?.code !== 'ENOENT')
84
163
  throw error;
85
164
  }
86
- const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomBytes(6).toString('hex')}.tmp`);
87
- await writeHandle(temporary, bytes, mode, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | noFollow);
165
+ await writeHandle(temporary, bytes, mode, flags);
88
166
  try {
167
+ if (options.expectSha256 !== undefined && (await currentSha256(target)) !== options.expectSha256)
168
+ throw new FileChangedError();
89
169
  await rename(temporary, target);
90
170
  }
91
171
  catch (error) {
@@ -94,3 +174,85 @@ export async function writeFileAtomic(filePath, bytes, mode = 0o644) {
94
174
  }
95
175
  return target;
96
176
  }
177
+ /** Canonical path of `target`, resolving symlinks on the longest existing prefix. A dangling link on the way is an error. */
178
+ export async function realpathAllowingMissing(target) {
179
+ let current = path.resolve(target);
180
+ const missingParts = [];
181
+ while (true) {
182
+ try {
183
+ const resolvedPrefix = await realpath(current);
184
+ return path.join(resolvedPrefix, ...missingParts.reverse());
185
+ }
186
+ catch (error) {
187
+ if (error?.code !== 'ENOENT')
188
+ throw error;
189
+ // realpath also fails with ENOENT for a dangling symlink; its target could be created later.
190
+ const existsAsDanglingLink = await lstat(current).then(() => true, () => false);
191
+ if (existsAsDanglingLink)
192
+ throw new Error(`${current} is a dangling symbolic link`);
193
+ const parent = path.dirname(current);
194
+ if (parent === current)
195
+ throw error;
196
+ missingParts.push(path.basename(current));
197
+ current = parent;
198
+ }
199
+ }
200
+ }
201
+ /**
202
+ * Resolves a policy-supplied path against `base` and requires it to name something strictly inside `base`,
203
+ * after symlinks in its parent directories are resolved. An existing final component must be a regular,
204
+ * non-symlink file. Returns the canonical path.
205
+ */
206
+ export async function resolveInsideDirectory(base, item, label) {
207
+ const resolvedBase = path.resolve(base);
208
+ const canonicalBase = await realpath(resolvedBase);
209
+ const requested = path.resolve(resolvedBase, item);
210
+ const reject = () => new Error(`${label} must name a file inside the policy file's directory (${canonicalBase}); got "${item}"`);
211
+ if (!isInside(resolvedBase, requested) || requested === resolvedBase) {
212
+ throw reject();
213
+ }
214
+ const canonicalParent = await realpathAllowingMissing(path.dirname(requested));
215
+ const canonical = path.join(canonicalParent, path.basename(requested));
216
+ if (canonical === canonicalBase || !isInside(canonicalBase, canonical))
217
+ throw reject();
218
+ try {
219
+ const entry = await lstat(canonical);
220
+ if (entry.isSymbolicLink() || !entry.isFile())
221
+ throw new Error(`${label} must be a regular, non-symlink file`);
222
+ }
223
+ catch (error) {
224
+ if (error?.code !== 'ENOENT')
225
+ throw error;
226
+ }
227
+ return canonical;
228
+ }
229
+ /**
230
+ * Appends text to a log file, creating it (mode 600) if needed. Refuses symbolic links and anything that is not
231
+ * a regular file; O_NONBLOCK keeps a FIFO from hanging the open.
232
+ */
233
+ export async function appendToRegularFile(filePath, text, label, mode = DEFAULT_LOG_MODE) {
234
+ const target = path.resolve(filePath);
235
+ const flags = fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | noFollow | nonBlock;
236
+ let existing;
237
+ try {
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);
247
+ try {
248
+ const opened = await handle.stat({ bigint: true });
249
+ if (!opened.isFile())
250
+ throw new Error(`${label} must be a regular file`);
251
+ if (existing && !sameFileIdentity(existing, opened))
252
+ throw new Error(`${label} changed while being opened`);
253
+ await handle.appendFile(text, 'utf8');
254
+ }
255
+ finally {
256
+ await handle.close();
257
+ }
258
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ // Entry point of the Claude Code hook: `env -i node --no-addons claude-code-hook.js <config.json> <enforce|shadow>`.
2
+ // The config, socket directory and socket must be root-owned; see claude-code.ts.
3
+ import { hookMain } from "./hook-main.js";
4
+ await hookMain(process.argv.slice(2, 4));
@@ -0,0 +1,13 @@
1
+ import type { Mode } from '../../policy.ts';
2
+ export interface ClaudeCodeSettingsInput {
3
+ mode: Mode;
4
+ nodePath: string;
5
+ hookEntry: string;
6
+ configPath: string;
7
+ hookTimeoutSec: number;
8
+ /** Must match the hook config's self_deadline_ms; the host timeout has to outlast it by at least 1 s. */
9
+ selfDeadlineMs: number;
10
+ /** Absolute path of env(1); default /usr/bin/env. */
11
+ envPath?: string;
12
+ }
13
+ export declare function claudeCodeManagedSettings(input: ClaudeCodeSettingsInput): Record<string, unknown>;
@@ -0,0 +1,49 @@
1
+ // Managed-settings generator for the Claude Code hook adapter. Pure: no file access.
2
+ // EVIDENCE: every field marked [cc0.4] is copied from .agent/reviews/cc0.4-fixtures/setup.sh as tested on Claude Code CLI
3
+ // 2.1.296 / Linux (cc0.3-b2b-enforcement-check.md, cc0.4-enforcement-verification.md). The generated settings were also
4
+ // run live on 2.1.318 (-p mode) with the real service and hook: the locks hid every project, user and bundled Skill
5
+ // (tests/live/claude-code-gate.live.ts, docs/spikes/claude-code-gate-live.md). Unverified for any other version;
6
+ // the native locks are bounded spike observations, not a broad host-level guarantee.
7
+ // ENDPOINT REQUIREMENTS (founder-accepted deployment requirements, NOT enforced by this file): the hook command is
8
+ // started with `env -i`, which scrubs NODE_OPTIONS/NODE_PATH/PYTHONPATH etc. for the interpreter, but loader-time
9
+ // variables act BEFORE `env` runs: LD_PRELOAD on the shell Claude Code uses to run the hook, and BASH_ENV if that shell
10
+ // is bash. Same-UID ptrace of the hook or host also stays an endpoint requirement.
11
+ import path from 'node:path';
12
+ const SAFE_PATH = /^\/[A-Za-z0-9._/-]+$/u; // the command is parsed by a shell: no spaces, quotes or metacharacters
13
+ export function claudeCodeManagedSettings(input) {
14
+ const { mode, nodePath, hookEntry, configPath, hookTimeoutSec, selfDeadlineMs } = input;
15
+ const envPath = input.envPath ?? '/usr/bin/env';
16
+ for (const p of [envPath, nodePath, hookEntry, configPath])
17
+ if (!path.isAbsolute(p) || !SAFE_PATH.test(p))
18
+ throw new Error('paths must be absolute and shell-safe');
19
+ if (mode !== 'enforce' && mode !== 'shadow')
20
+ throw new Error('mode must be enforce or shadow');
21
+ if (!Number.isInteger(hookTimeoutSec) || hookTimeoutSec < 1)
22
+ throw new Error('hookTimeoutSec must be a positive integer');
23
+ if (!Number.isInteger(selfDeadlineMs) || selfDeadlineMs < 1 || hookTimeoutSec * 1000 < selfDeadlineMs + 1000)
24
+ throw new Error('hookTimeoutSec * 1000 must be at least selfDeadlineMs + 1000');
25
+ // env -i: the interpreter starts with an empty environment (the adapter needs none), so NODE_OPTIONS etc. cannot hijack it.
26
+ const command = `${envPath} -i ${nodePath} --no-addons ${hookEntry} ${configPath} ${mode}`;
27
+ const gate = { type: 'command', command, timeout: hookTimeoutSec, ...(mode === 'enforce' ? { onFailure: 'block' } : {}) }; // [cc0.4] onFailure
28
+ const hooks = {
29
+ PreToolUse: [{ matcher: 'Skill', hooks: [gate] }], // [cc0.4]
30
+ UserPromptExpansion: [{ hooks: [gate] }], // [cc0.4]
31
+ SessionStart: [{ hooks: [{ type: 'command', command, timeout: hookTimeoutSec }] }], // never blocks
32
+ };
33
+ if (mode === 'shadow')
34
+ return { hooks }; // shadow must not change behaviour: no native locks
35
+ return {
36
+ strictPluginOnlyCustomization: ['skills', 'hooks', 'agents', 'mcp'], // [cc0.4]
37
+ strictKnownMarketplaces: [], // [cc0.4]
38
+ disableSideloadFlags: true, // [cc0.4]
39
+ allowManagedHooksOnly: true, // [cc0.4]
40
+ requiredMinimumVersion: '2.1.296', // [cc0.4] the tested version
41
+ // Built-in / bundled Skills: [cc0.4] setup.sh removes them so only managed-directory Skills exist. Keys and names are
42
+ // copied from that fixture; unverified for other CLI versions (the built-in plugin ids may differ).
43
+ disableBundledSkills: true, // [cc0.4]
44
+ skillOverrides: { design: 'off', doctor: 'off', 'plugin-authoring': 'off' }, // [cc0.4]
45
+ enabledPlugins: Object.fromEntries(// [cc0.4]
46
+ ['cc-plugin-sec-default', 'cc-plugin-agents-md', 'cc-plugin-telemetry', 'cc-plugin-plugin-authoring'].map((x) => [`${x}@builtin`, false])),
47
+ hooks,
48
+ };
49
+ }
@@ -0,0 +1,33 @@
1
+ import type { Mode } from '../../policy.ts';
2
+ import { type GateRequest } from '../contract.ts';
3
+ import { type AskResult } from './client.ts';
4
+ import { findHostPid } from './host-pid.ts';
5
+ export declare const MAX_STDIN_BYTES: number;
6
+ export interface HookConfig {
7
+ socket: string;
8
+ mode: Mode;
9
+ hostExes: string[];
10
+ clientDeadlineMs: number;
11
+ selfDeadlineMs: number;
12
+ rootUid: number;
13
+ /** The validated config object, for adapters that add their own keys (see `extraKeys`). */
14
+ raw: Record<string, unknown>;
15
+ }
16
+ export interface HookOutcome {
17
+ code: number;
18
+ stdout: string;
19
+ stderr: string;
20
+ mode?: Mode;
21
+ }
22
+ export interface HookDeps {
23
+ /** Resolves the whole stdin, or null if it exceeded MAX_STDIN_BYTES. */
24
+ readStdin: () => Promise<Buffer | null>;
25
+ findHost?: typeof findHostPid;
26
+ ask?: (socket: string, request: GateRequest, deadlineMs: number, rootUid: number) => Promise<AskResult>;
27
+ /** Uid that must own the config, socket directory and socket. Production: always 0 (tests inject their own). */
28
+ rootUid?: number;
29
+ }
30
+ /** Strict, closed config: root-owned in production (a deployment requirement; here only "not group/other writable"). */
31
+ export declare function loadConfig(file: string, rootUid?: number, extraKeys?: readonly string[]): Promise<HookConfig>;
32
+ /** Never throws and never outlives the self-deadline. */
33
+ export declare function runHook(argv: readonly string[], deps: HookDeps): Promise<HookOutcome>;
@@ -0,0 +1,193 @@
1
+ // Claude Code hook adapter (E3 packet 9a, profile 1: plain managed-directory Skill names only). Pure of process I/O:
2
+ // claude-code-hook.ts feeds it stdin and writes its outcome.
3
+ //
4
+ // HOST SCHEMA (the one place). These shapes are what the cc0.3/cc0.4 spikes observed on Claude Code CLI 2.1.296 / Linux
5
+ // (.agent/reviews/cc0.4-fixtures/gate.py and cc0.4-enforcement-verification.md). They are NOT a verified complete host
6
+ // API and are unverified for any other version; re-check them before widening the supported matrix.
7
+ // stdin PreToolUse: { hook_event_name: "PreToolUse", tool_name: "Skill", tool_input: { skill: "<name>", ... }, ... }
8
+ // UserPromptExpansion: { hook_event_name: "UserPromptExpansion", command_name: "<name or /name>", ... }
9
+ // SessionStart: { hook_event_name: "SessionStart", ... }
10
+ // Other outer fields (session_id, cwd, transcript_path, ...) are ignored: never used, never logged.
11
+ // UNVERIFIED: whether command_name carries a leading "/" (a single one is stripped), whether built-in slash
12
+ // commands (/help, ...) also reach UserPromptExpansion (they would be denied in enforce: NO_CERTIFICATE).
13
+ // block PreToolUse: stdout {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny",
14
+ // "permissionDecisionReason":<msg>}}, exit 0 (observed to block in cc0.4)
15
+ // UserPromptExpansion: stdout {"decision":"block","reason":<msg>}, exit 0 (observed to block in cc0.4)
16
+ // Primary block mechanism = these JSON answers with exit 0, because they are the only ones the evidence shows
17
+ // working. Exit 2 + stderr is used ONLY when the event cannot be told (unparseable stdin, unknown event); it is
18
+ // the host's generic block but UNVERIFIED here (live check pending; that exit 2 blocks is not evidenced).
19
+ // If the strict parse fails but a lenient byte scan still finds a known blockable event name, that event's
20
+ // deny body is emitted (a spoofed name can only produce a deny). SessionStart is never blocked.
21
+ // allow exit 0, no output.
22
+ //
23
+ // MODE. The managed settings pass the mode as argv[1] (`enforce`|`shadow`) as well as in the config file: if the
24
+ // config is unreadable or invalid, argv decides, and anything but exactly `shadow` is enforce. Enforce wins if either
25
+ // source says enforce (decideAction additionally never lets a service answer downgrade it).
26
+ // The adapter reads no environment variables. The config, its socket directory and the socket must be owned by root
27
+ // (uid 0); argv cannot change that (tests inject a uid through HookDeps via their own entry point).
28
+ import { lstat, readFile } from 'node:fs/promises';
29
+ import path from 'node:path';
30
+ import { isRecord } from "../../canonical-json.js";
31
+ import { validateSkillName } from "../../names.js";
32
+ import { decideAction } from "../contract.js";
33
+ import { parseStrictJson } from "../strict-json.js";
34
+ import { askService, DEFAULT_CLIENT_DEADLINE_MS, newRequestId } from "./client.js";
35
+ import { findHostPid } from "./host-pid.js";
36
+ export const MAX_STDIN_BYTES = 256 * 1024;
37
+ const DEFAULT_SELF_DEADLINE_MS = 3000;
38
+ // Matched to the stdin cap (the default 64 KiB / 16 KiB limits would deny legitimate long prompts).
39
+ const INPUT_LIMITS = { maxBytes: MAX_STDIN_BYTES, maxDepth: 16, maxMembers: 256, maxStringLength: 128 * 1024 };
40
+ const KINDS = ['PreToolUse', 'UserPromptExpansion', 'SessionStart'];
41
+ const COULD_NOT_VERIFY = 'mago-ski could not verify this Skill; it is blocked until verification works.';
42
+ const notApproved = (verdict) => `This Skill is not approved by your organisation (mago-ski: ${verdict}). If it was updated, restart the session to use the new version.`;
43
+ /** Strict, closed config: root-owned in production (a deployment requirement; here only "not group/other writable"). */
44
+ export async function loadConfig(file, rootUid = 0, extraKeys = []) {
45
+ if (!path.isAbsolute(file))
46
+ throw new Error('config path must be absolute');
47
+ const st = await lstat(file);
48
+ if (!st.isFile() || (st.mode & 0o022) !== 0 || st.uid !== rootUid)
49
+ throw new Error('config must be a regular, root-owned, non-writable file');
50
+ const raw = parseStrictJson(await readFile(file));
51
+ if (!isRecord(raw))
52
+ throw new Error('config must be an object');
53
+ const allowed = ['v', 'socket', 'mode', 'host_exes', 'client_deadline_ms', 'self_deadline_ms', ...extraKeys];
54
+ if (Object.keys(raw).some((k) => !allowed.includes(k)) || raw['v'] !== 1)
55
+ throw new Error('config has unknown fields or version');
56
+ const { socket, mode, host_exes: exes } = raw;
57
+ if (typeof socket !== 'string' || !path.isAbsolute(socket) || socket.length > 107)
58
+ throw new Error('bad socket');
59
+ if (mode !== 'enforce' && mode !== 'shadow')
60
+ throw new Error('bad mode');
61
+ const dir = await lstat(path.dirname(socket)); // the socket directory must not be replaceable by other users
62
+ if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o022) !== 0 || dir.uid !== rootUid)
63
+ throw new Error('bad socket directory');
64
+ if (!Array.isArray(exes) || exes.length === 0 || !exes.every((e) => typeof e === 'string' && path.isAbsolute(e)))
65
+ throw new Error('bad host_exes');
66
+ const ms = (v, dflt) => {
67
+ if (v === undefined)
68
+ return dflt;
69
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 50 || v > 60_000)
70
+ throw new Error('bad deadline');
71
+ return v;
72
+ };
73
+ return {
74
+ socket, mode, hostExes: exes, rootUid, raw,
75
+ clientDeadlineMs: ms(raw['client_deadline_ms'], DEFAULT_CLIENT_DEADLINE_MS),
76
+ selfDeadlineMs: ms(raw['self_deadline_ms'], DEFAULT_SELF_DEADLINE_MS),
77
+ };
78
+ }
79
+ /** Closed per-event schemas; `peek` receives the event kind as soon as it is known, even if the rest is invalid. */
80
+ function parseHookInput(bytes, peek) {
81
+ const raw = parseStrictJson(bytes, INPUT_LIMITS);
82
+ if (!isRecord(raw))
83
+ throw new Error('input must be an object');
84
+ const name = raw['hook_event_name'];
85
+ if (typeof name !== 'string' || !KINDS.includes(name))
86
+ throw new Error('unknown event');
87
+ peek(name);
88
+ if (name === 'SessionStart')
89
+ return { kind: 'session-start' };
90
+ let skill;
91
+ if (name === 'PreToolUse') {
92
+ const input = raw['tool_input'];
93
+ if (raw['tool_name'] !== 'Skill' || !isRecord(input))
94
+ throw new Error('not a Skill call');
95
+ skill = input['skill'];
96
+ }
97
+ else {
98
+ skill = raw['command_name'];
99
+ }
100
+ if (typeof skill !== 'string')
101
+ throw new Error('missing Skill name');
102
+ // A plugin-namespaced name (`plugin:name`) fails validateSkillName: unsupported in profile 1, so denied.
103
+ return {
104
+ kind: 'skill', event: name === 'PreToolUse' ? 'skill-invoke' : 'prompt-expansion',
105
+ skill: validateSkillName(skill.startsWith('/') ? skill.slice(1) : skill),
106
+ };
107
+ }
108
+ function block(kind, message) {
109
+ if (kind === 'PreToolUse')
110
+ return { code: 0, stderr: '', stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: message } }) };
111
+ if (kind === 'UserPromptExpansion')
112
+ return { code: 0, stderr: '', stdout: JSON.stringify({ decision: 'block', reason: message }) };
113
+ if (kind === 'SessionStart')
114
+ return { code: 0, stdout: '', stderr: '' };
115
+ return { code: 2, stdout: '', stderr: message }; // event unknown: the host's generic block (unverified)
116
+ }
117
+ /** Lenient scan for a blockable event name in bytes the strict parser rejected. */
118
+ function scanKind(bytes) {
119
+ const text = bytes.toString('latin1');
120
+ // Exactly one hook_event_name in the raw bytes: a second one (e.g. nested in model-controlled tool_input) makes the
121
+ // event ambiguous, so fall back to exit 2 rather than risk the wrong event's block body.
122
+ if ((text.match(/"hook_event_name"/gu) ?? []).length !== 1)
123
+ return undefined;
124
+ const m = /"hook_event_name"\s*:\s*"(PreToolUse|UserPromptExpansion)"/u.exec(text);
125
+ return m ? m[1] : undefined;
126
+ }
127
+ const OK = { code: 0, stdout: '', stderr: '' };
128
+ /** Never throws and never outlives the self-deadline. */
129
+ export async function runHook(argv, deps) {
130
+ let mode = 'enforce';
131
+ const out = await runHookInner(argv, deps, (m) => { mode = m; });
132
+ return { ...out, mode };
133
+ }
134
+ async function runHookInner(argv, deps, setMode) {
135
+ const uid = deps.rootUid ?? 0; // never from argv: a non-root uid here would let that user run a fake service
136
+ let mode = argv[1] === 'shadow' ? 'shadow' : 'enforce';
137
+ let kind;
138
+ let cfg;
139
+ try {
140
+ cfg = await loadConfig(argv[0] ?? '', uid);
141
+ }
142
+ catch {
143
+ cfg = undefined;
144
+ } // lstat first, so a FIFO cannot hang it
145
+ if (cfg?.mode === 'enforce')
146
+ mode = 'enforce';
147
+ setMode(mode);
148
+ const fail = (message) => (mode === 'shadow' ? OK : block(kind, message));
149
+ const work = async () => {
150
+ const bytes = await deps.readStdin();
151
+ if (!bytes)
152
+ return fail(COULD_NOT_VERIFY);
153
+ let parsed;
154
+ try {
155
+ parsed = parseHookInput(bytes, (k) => { kind = k; });
156
+ }
157
+ catch {
158
+ kind ??= scanKind(bytes);
159
+ return fail(COULD_NOT_VERIFY);
160
+ }
161
+ if (!cfg)
162
+ return fail(COULD_NOT_VERIFY);
163
+ let pid;
164
+ try {
165
+ pid = await (deps.findHost ?? findHostPid)(cfg.hostExes);
166
+ }
167
+ catch {
168
+ return fail(COULD_NOT_VERIFY);
169
+ }
170
+ const request = {
171
+ v: 1, request_id: newRequestId(), session: `pid:${pid}`,
172
+ event: parsed.kind === 'session-start' ? 'session-start' : parsed.event,
173
+ ...(parsed.kind === 'skill' ? { skill: parsed.skill } : {}),
174
+ };
175
+ const answer = await (deps.ask ?? askService)(cfg.socket, request, cfg.clientDeadlineMs, cfg.rootUid);
176
+ if (parsed.kind === 'session-start')
177
+ return OK; // never blocks; an unknown session is denied by the service later
178
+ const result = answer.ok ? answer.result : { kind: 'parse-failure' };
179
+ if (decideAction(result, mode) !== 'deny')
180
+ return OK;
181
+ return block(kind, result.kind === 'verdict' && result.verdict !== 'UNVERIFIABLE' ? notApproved(result.verdict) : COULD_NOT_VERIFY);
182
+ };
183
+ let timer;
184
+ const timeout = new Promise((resolve) => {
185
+ timer = setTimeout(() => resolve(fail(COULD_NOT_VERIFY)), cfg?.selfDeadlineMs ?? DEFAULT_SELF_DEADLINE_MS);
186
+ });
187
+ try {
188
+ return await Promise.race([work().catch(() => fail(COULD_NOT_VERIFY)), timeout]);
189
+ }
190
+ finally {
191
+ clearTimeout(timer);
192
+ }
193
+ }
@@ -0,0 +1,13 @@
1
+ import { type GateRequest, type GateResult } from '../contract.ts';
2
+ export type ClientFailure = 'no-answer' | 'late' | 'malformed' | 'connect-failed';
3
+ export type AskResult = {
4
+ ok: true;
5
+ result: GateResult;
6
+ } | {
7
+ ok: false;
8
+ failure: ClientFailure;
9
+ };
10
+ export declare const MAX_ANSWER_BYTES = 4096;
11
+ export declare const DEFAULT_CLIENT_DEADLINE_MS = 1500;
12
+ export declare const newRequestId: () => string;
13
+ export declare function askService(socketPath: string, request: GateRequest, deadlineMs?: number, rootUid?: number): Promise<AskResult>;
@@ -0,0 +1,57 @@
1
+ // Decision-socket client shared by all harness adapters. One strict request line out, one bounded answer line in,
2
+ // its own deadline. It never throws for transport or parse problems; the adapter turns any failure into a deny
3
+ // (service.ts ADAPTER CONTRACT).
4
+ import { randomBytes } from 'node:crypto';
5
+ import { lstat } from 'node:fs/promises';
6
+ import net from 'node:net';
7
+ import { parseGateResult, serializeGateRequest } from "../contract.js";
8
+ export const MAX_ANSWER_BYTES = 4096;
9
+ export const DEFAULT_CLIENT_DEADLINE_MS = 1500;
10
+ export const newRequestId = () => randomBytes(16).toString('hex');
11
+ export async function askService(socketPath, request, deadlineMs = DEFAULT_CLIENT_DEADLINE_MS, rootUid = 0) {
12
+ // Right before connecting: the path must be a socket owned by the service's uid (not a planted file or symlink).
13
+ const st = await lstat(socketPath).catch(() => undefined);
14
+ if (!st || !st.isSocket() || st.uid !== rootUid)
15
+ return { ok: false, failure: 'connect-failed' };
16
+ return new Promise((resolve) => {
17
+ let done = false;
18
+ let connected = false;
19
+ const chunks = [];
20
+ let size = 0;
21
+ const sock = net.connect(socketPath);
22
+ const finish = (r) => {
23
+ if (done)
24
+ return;
25
+ done = true;
26
+ clearTimeout(timer);
27
+ sock.destroy();
28
+ resolve(r);
29
+ };
30
+ const timer = setTimeout(() => finish({ ok: false, failure: connected ? 'late' : 'connect-failed' }), deadlineMs);
31
+ const parse = (line) => {
32
+ try {
33
+ finish({ ok: true, result: parseGateResult(line, request.request_id) });
34
+ }
35
+ catch {
36
+ finish({ ok: false, failure: 'malformed' });
37
+ }
38
+ };
39
+ sock.on('connect', () => { connected = true; sock.write(`${serializeGateRequest(request)}\n`); });
40
+ sock.on('error', () => finish({ ok: false, failure: connected ? 'no-answer' : 'connect-failed' }));
41
+ sock.on('data', (d) => {
42
+ chunks.push(d);
43
+ size += d.length;
44
+ const all = Buffer.concat(chunks);
45
+ const nl = all.indexOf(0x0a);
46
+ if (nl >= 0)
47
+ return parse(all.subarray(0, nl));
48
+ if (size > MAX_ANSWER_BYTES)
49
+ finish({ ok: false, failure: 'malformed' });
50
+ });
51
+ sock.on('close', () => {
52
+ if (done)
53
+ return;
54
+ finish({ ok: false, failure: size === 0 ? 'no-answer' : 'malformed' });
55
+ });
56
+ });
57
+ }
@@ -0,0 +1 @@
1
+ export {};