@hasna/hooks 0.13.1 → 0.14.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 -15
- package/bin/hooks/stop-review.js +53 -17
- package/bin/hooks-mcp.js +4787 -1415
- package/bin/index.js +5250 -2337
- package/bin/native-safety-entry.js +15 -37
- package/bin/native-safety-worker.cjs +38 -36
- package/bin/serve.js +34 -11
- package/dist/index.js +4970 -1579
- package/dist/lib/claude-skills-coordination.d.ts +1 -1
- package/dist/lib/codex-safety-trust.d.ts +2 -2
- package/dist/lib/native-safety-registration.d.ts +2 -2
- package/dist/lib/native-safety.d.ts +1 -1
- package/dist/lib/registry.d.ts +3 -1
- package/dist/native-safety.d.ts +4 -2
- package/dist/native-safety.js +21 -2
- package/dist/sdk/index.js +9 -53
- package/hooks/hook-job-folder-guard/README.md +61 -0
- package/hooks/hook-job-folder-guard/package.json +12 -0
- package/hooks/hook-job-folder-guard/src/classify.ts +398 -0
- package/hooks/hook-job-folder-guard/src/hook.ts +96 -0
- package/hooks/hook-protected-delete-guard/README.md +114 -0
- package/hooks/hook-protected-delete-guard/package.json +12 -0
- package/hooks/hook-protected-delete-guard/src/hook.ts +539 -0
- package/hooks/hook-signed-link-guard/src/classify.ts +41 -2
- package/hooks/hook-stop-review/README.md +16 -0
- package/hooks/hook-stop-review/manifest.json +1 -1
- package/hooks/hook-stop-review/package.json +1 -1
- package/hooks/hook-stop-review/src/hook.ts +1 -1
- package/hooks/hook-stop-review/src/native.ts +44 -8
- package/hooks/hook-stop-review/src/policy.ts +20 -8
- package/hooks/hook-stop-review/src/runtime.ts +16 -13
- package/hooks/hook-stop-review/src/types.ts +12 -2
- package/hooks/hook-trash-guard/README.md +130 -13
- package/hooks/hook-trash-guard/src/hook.ts +518 -71
- package/hooks/local-executors.ts +130 -12
- package/hooks/native-safety-composite.ts +19 -8
- package/package.json +3 -3
- package/scripts/build-native-entry.ts +123 -0
- package/scripts/build-native-worker.ts +11 -4
- package/scripts/validate-package.ts +8 -2
- package/hooks/native-safety-entry.ts +0 -11
package/hooks/local-executors.ts
CHANGED
|
@@ -78,6 +78,8 @@ export type ProgramKind = "c-interp" | "awk" | "shell";
|
|
|
78
78
|
export interface EmbeddedProgram {
|
|
79
79
|
text: string;
|
|
80
80
|
kind: ProgramKind;
|
|
81
|
+
/** The language of a `c-interp` program that has a reader of its own. */
|
|
82
|
+
language?: "python";
|
|
81
83
|
}
|
|
82
84
|
|
|
83
85
|
export interface ExecutorFinding {
|
|
@@ -152,23 +154,105 @@ const SSH_LOCAL_EXEC_OPTS = new Set(["proxycommand", "localcommand", "knownhosts
|
|
|
152
154
|
const C_INTERP_DANGER = /(?:`|\$\()|\b(?:system|exec|execve|execvp|popen|spawn|posix_spawn|fork|subprocess|Popen|check_output|check_call|shell_exec|passthru|proc_open|pcntl_exec|qx|open|fopen|sysopen|unlink|remove|delete|rmtree|rmdir|mkdir|rename|truncate|ftruncate|chmod|chown|symlink|writeFile|createWriteStream|appendFile|child_process|FileUtils|shutil|Kernel|require|import|load|eval|os|sys|io|fs|File|IO|Dir|Path|pathlib|Deno|Bun)|%x\W/;
|
|
153
155
|
|
|
154
156
|
/**
|
|
155
|
-
* awk danger: `system
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
157
|
+
* awk danger: `system`, `getline`, `close` and `fflush` in any use, matched
|
|
158
|
+
* anywhere, since awk reads `1system("x")` as a call; and
|
|
159
|
+
* a gawk `@` before anything but `@` or `/`: an indirect call (`@f()`, `@ f()`)
|
|
160
|
+
* can reach `system` by a name built from strings, and `@load` or `@include`
|
|
161
|
+
* brings in other code. `/^@@/` stays text.
|
|
160
162
|
*/
|
|
161
|
-
const AWK_DANGER = /
|
|
163
|
+
const AWK_DANGER = /system|getline|close|fflush|@(?![@/])/;
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Whether an awk program can only read. Output leaves it only through a `print`
|
|
167
|
+
* or `printf`, and a redirection follows its statement, so a `>` or `|` before
|
|
168
|
+
* the first print is an operator or a pattern. Past it, even a `>` in a string
|
|
169
|
+
* fails, because telling a string from a regexp or a comment takes a parser. A
|
|
170
|
+
* line continuation (awks differ on it) anywhere fails once a `>` or `|` is
|
|
171
|
+
* present.
|
|
172
|
+
*/
|
|
173
|
+
function awkProgramIsReadOnly(program: string): boolean {
|
|
174
|
+
if (AWK_DANGER.test(program)) return false;
|
|
175
|
+
if (!/[|>]/.test(program)) return true;
|
|
176
|
+
if (/\\\r?\n/.test(program)) return false;
|
|
177
|
+
const print = program.search(/print/);
|
|
178
|
+
return print < 0 || !/[|>]/.test(program.slice(print));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* A `.` followed by anything but reading in `json` and `sys`, or a method of a
|
|
183
|
+
* string, a container or a file. `write` fails on any file `open` may produce
|
|
184
|
+
* here. Nothing listed reaches a module, a code object or a buffer; what isn't
|
|
185
|
+
* listed is refused, which is why this can't go stale the way a list of dangers
|
|
186
|
+
* does. A `case` class pattern reads attributes with no `.`, so PYTHON_UNSAFE
|
|
187
|
+
* refuses `case`, and a string can't hide it (see pythonCode).
|
|
188
|
+
*/
|
|
189
|
+
const PYTHON_UNLISTED_ATTRIBUTE = /\.\s*(?!(?:argv|std(?:in|out|err)|exit|write|loads?|dumps?|strip|split(?:lines)?|join|replace|(?:start|end)swith|lower|find|count|get|items|keys|values|append|sort|read)\b)[a-zA-Z_]/;
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Only a builtin gives a bare name power: the only modules let in are `json`
|
|
193
|
+
* and `sys`, and their attributes are reached through a `.`, which
|
|
194
|
+
* PYTHON_UNLISTED_ATTRIBUTE checks. Refused here: the builtins that run code or
|
|
195
|
+
* return live objects (any name ending in `attr` among them), `case`, whose
|
|
196
|
+
* class pattern reads attributes with no `.`, and every name that starts with
|
|
197
|
+
* `_`, a lone `_` included. A name is refused even when assigned to, since
|
|
198
|
+
* `exec=exec` keeps the function.
|
|
199
|
+
*/
|
|
200
|
+
const PYTHON_UNSAFE = /(?<![\w.])(?:breakpoint|case|compile|\w*attr|eval|exec|globals|help|locals|type|vars)\b|(?<!\w)_/;
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* A python program as python reads it, with comments gone and every string out
|
|
204
|
+
* of the way. A string made only of `r`, `b` and `t` may be a read mode, so it
|
|
205
|
+
* stays visible as `~`; every other string becomes `%`. Three quotes always open
|
|
206
|
+
* a triple-quoted string, as in python: `''''` is never read as two empty
|
|
207
|
+
* strings, so one left open stays a bare quote. A word is a token of its own, so
|
|
208
|
+
* only up to two of python's prefix letters (`r`, `b`, `u`, `f`, `t`) can be a
|
|
209
|
+
* string prefix and the end of a name can't: `case'x'` reads as `case%` and
|
|
210
|
+
* `if'x'` as `if%`, as python reads them. An `f` or `t` string holds code, so
|
|
211
|
+
* its fields stay. If a field holds a brace (it may hide a nested string) or a
|
|
212
|
+
* `#` (python 3.12 reads a comment there, and a `}` in it doesn't close the
|
|
213
|
+
* field), the whole string comes back as a bare quote. A backslash outside a string is a token of its
|
|
214
|
+
* own, so that an escaped quote can't open a string and scan to the end of the
|
|
215
|
+
* program each time; it stays in the result, and a backslash there is refused.
|
|
216
|
+
*/
|
|
217
|
+
function pythonCode(source: string): string {
|
|
218
|
+
return source.replace(/#.*|\\[^]|([rRbBuUfFtT]{0,2})("""|'''|(["'])(?!\3\3))((?:\\[^]|(?!\2)[^\\])*)\2|\w+/g, (whole, prefix: string, fence, _, text: string) => {
|
|
219
|
+
if (!fence) return whole[0] === "#" ? "" : whole;
|
|
220
|
+
if (!/[ft]/i.test(prefix)) return /^[rbt]+$/.test(text) ? "~" : "%";
|
|
221
|
+
let fields = "";
|
|
222
|
+
const rest = text.replace(/\{\{|\}\}|\{([^{}#]*)\}/g, (_, field = "") => ((fields += `${pythonCode(field)},`), ""));
|
|
223
|
+
return /[{}]/.test(rest) ? "'" : `(${fields})`;
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Whether an inline python program is provably read-only: a backtick or `$(`
|
|
229
|
+
* is refused, as is what can't be read as code (a leftover quote or backslash,
|
|
230
|
+
* or any non-ASCII character), nothing unsafe may be named, a statement may import only
|
|
231
|
+
* `json` and `sys`, `open` must read one plain path, and nothing unlisted may be
|
|
232
|
+
* reached through a `.`. A program over 8,192 characters is refused unread:
|
|
233
|
+
* past about 16,000 the scanner's regex slows sharply on an unclosed string.
|
|
234
|
+
*/
|
|
235
|
+
function pythonProgramIsReadOnly(program: string): boolean {
|
|
236
|
+
if (program.length > 8192 || /`|\$\(/.test(program)) return false;
|
|
237
|
+
const code = pythonCode(program);
|
|
238
|
+
if (/['"\\]|[^\0-\x7f]/.test(code) || PYTHON_UNSAFE.test(code)) return false;
|
|
239
|
+
if (/\b(?:import|from)\b/.test(code.replace(/\bimport\s+(?:json|sys)(?:\s*,\s*(?:json|sys))*(?=\s*(?:;|$))/gm, ""))) return false;
|
|
240
|
+
if (/\bopen\b/.test(code.replace(/\bopen\([\w.[\]%]+(?:,\s*(?:mode=)?~)?(?:,\s*encoding=%)?\)/g, ""))) return false;
|
|
241
|
+
return !PYTHON_UNLISTED_ATTRIBUTE.test(code);
|
|
242
|
+
}
|
|
162
243
|
|
|
163
244
|
/**
|
|
164
245
|
* Whether an embedded program is provably read-only for its grammar. A `shell`
|
|
165
246
|
* value is judged by the caller with its own command classifier (it is a shell
|
|
166
|
-
* command); only `c-interp` and `awk` are judged here.
|
|
247
|
+
* command); only `c-interp` and `awk` are judged here. After the delete-verb
|
|
248
|
+
* check, Python 3 is judged by its allow-list in place of the danger words,
|
|
249
|
+
* since a program naming no danger word can still reach a debugger or a dunder
|
|
250
|
+
* chain.
|
|
167
251
|
*/
|
|
168
252
|
export function embeddedProgramIsReadOnly(program: EmbeddedProgram): boolean {
|
|
169
253
|
if (mentionsDeleteVerb(program.text)) return false;
|
|
170
|
-
if (program.kind === "awk") return
|
|
171
|
-
if (program.kind === "c-interp") return !C_INTERP_DANGER.test(program.text);
|
|
254
|
+
if (program.kind === "awk") return awkProgramIsReadOnly(program.text);
|
|
255
|
+
if (program.kind === "c-interp") return program.language === "python" ? pythonProgramIsReadOnly(program.text) : !C_INTERP_DANGER.test(program.text);
|
|
172
256
|
// shell: never decided here.
|
|
173
257
|
return false;
|
|
174
258
|
}
|
|
@@ -177,11 +261,12 @@ export function embeddedProgramIsReadOnly(program: EmbeddedProgram): boolean {
|
|
|
177
261
|
function interpPrograms(name: string, words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding | null {
|
|
178
262
|
const spec = INTERP_PROGRAM_FLAGS[name] ?? (VERSIONED_INTERP.test(name) ? INTERP_PROGRAM_FLAGS[name.replace(/[0-9.]+$/, "")] : undefined);
|
|
179
263
|
if (!spec) return null;
|
|
264
|
+
const inline = (text: string): EmbeddedProgram => (name.startsWith("python3") ? { text, kind: "c-interp", language: "python" } : { text, kind: "c-interp" });
|
|
180
265
|
const programs: EmbeddedProgram[] = [];
|
|
181
266
|
let unresolved = false;
|
|
182
267
|
const takeNext = (at: number): number => {
|
|
183
268
|
if (at + 1 >= words.length || opaque(at + 1)) { unresolved = true; return at; }
|
|
184
|
-
programs.push(
|
|
269
|
+
programs.push(inline(words[at + 1]));
|
|
185
270
|
return at + 1;
|
|
186
271
|
};
|
|
187
272
|
for (let at = index + 1; at < words.length; at++) {
|
|
@@ -193,7 +278,7 @@ function interpPrograms(name: string, words: string[], index: number, opaque: (a
|
|
|
193
278
|
const eq = word.indexOf("=");
|
|
194
279
|
const longName = eq < 0 ? word : word.slice(0, eq);
|
|
195
280
|
if (spec.long.has(longName)) {
|
|
196
|
-
if (eq >= 0) programs.push(
|
|
281
|
+
if (eq >= 0) programs.push(inline(word.slice(eq + 1)));
|
|
197
282
|
else at = takeNext(at);
|
|
198
283
|
}
|
|
199
284
|
continue;
|
|
@@ -203,7 +288,7 @@ function interpPrograms(name: string, words: string[], index: number, opaque: (a
|
|
|
203
288
|
const cluster = word.slice(1);
|
|
204
289
|
for (let i = 0; i < cluster.length; i++) {
|
|
205
290
|
if (!spec.letters.has(cluster[i])) continue;
|
|
206
|
-
if (i < cluster.length - 1) programs.push(
|
|
291
|
+
if (i < cluster.length - 1) programs.push(inline(cluster.slice(i + 1)));
|
|
207
292
|
else at = takeNext(at);
|
|
208
293
|
break;
|
|
209
294
|
}
|
|
@@ -634,6 +719,39 @@ export interface ShellProgram {
|
|
|
634
719
|
export const ansiPlain = (text: string): string =>
|
|
635
720
|
text.replace(/\$'(?:[^'\\]|\\[\s\S])*'/g, (word) => word.replace(/\\[\s\S]/g, (pair) => (pair === "\\'" ? "\\x27" : pair)));
|
|
636
721
|
|
|
722
|
+
/**
|
|
723
|
+
* ansiPlain, with a `$'…'` word read from every `$'` in `text` rather than in one
|
|
724
|
+
* pass from the left (HO-00222). A `$'` that bash does not read as ANSI-C (inside
|
|
725
|
+
* quotes, in a comment or a here-document body) starts a word in that pass which
|
|
726
|
+
* runs to the opening quote of a real `$'it\'s'`, so the real word was never
|
|
727
|
+
* respelled. A word can hold another `$'` only as its closing quote, so the words
|
|
728
|
+
* cover the text at most about twice. A stray `$'` can only respell more than
|
|
729
|
+
* bash would, so callers read this beside ansiPlain, never instead of it.
|
|
730
|
+
*/
|
|
731
|
+
export function ansiPlainEvery(text: string): string {
|
|
732
|
+
const word = /\$'(?:[^'\\]|\\[\s\S])*'/y;
|
|
733
|
+
const found = new Set<number>();
|
|
734
|
+
for (let at = text.indexOf("$'"); at >= 0; at = text.indexOf("$'", at + 1)) {
|
|
735
|
+
word.lastIndex = at;
|
|
736
|
+
const match = word.exec(text);
|
|
737
|
+
if (!match) continue;
|
|
738
|
+
const end = at + match[0].length - 1;
|
|
739
|
+
for (let i = at + 2; i < end; i++) {
|
|
740
|
+
if (text[i] !== "\\") continue;
|
|
741
|
+
if (text[i + 1] === "'") found.add(i);
|
|
742
|
+
i++;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (found.size === 0) return text;
|
|
746
|
+
let out = "";
|
|
747
|
+
let from = 0;
|
|
748
|
+
for (const at of [...found].sort((a, b) => a - b)) {
|
|
749
|
+
out += `${text.slice(from, at)}\\x27`;
|
|
750
|
+
from = at + 2;
|
|
751
|
+
}
|
|
752
|
+
return out + text.slice(from);
|
|
753
|
+
}
|
|
754
|
+
|
|
637
755
|
export function shellProgram(raw: string[], index: number, decodeName: (raw: string) => string | null = literalWord): ShellProgram | null {
|
|
638
756
|
if (index < 0 || index >= raw.length) return null;
|
|
639
757
|
const name = baseName(decodeName(raw[index]) ?? "");
|
|
@@ -1,22 +1,25 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
2
|
import { isAbsolute } from "node:path";
|
|
3
|
-
import { evaluate as evaluateTrash, findTrashBinary, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
|
|
3
|
+
import { evaluate as evaluateTrash, findTrashBinary, HANDOFF_REFUSED, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
|
|
4
4
|
import { evaluate as evaluateRepos } from "./hook-workspace-repos-guard/src/hook";
|
|
5
|
+
import { guard as evaluateProtectedDelete } from "./hook-protected-delete-guard/src/hook";
|
|
5
6
|
import { readWithLegacyQuotes } from "./local-executors";
|
|
6
7
|
import { evaluate as evaluateSignedLinks } from "./hook-signed-link-guard/src/hook";
|
|
7
8
|
import type { CodewithHookInput, CodewithHookOutput } from "./codewith-native-common";
|
|
8
9
|
|
|
9
10
|
// The native safety composite: trash-guard, workspace-repos-guard and
|
|
10
|
-
// signed-link-guard judged together for one capability name
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// signed-link-guard judged together for one capability name, and
|
|
12
|
+
// protected-delete-guard judged on its own under its name. The v2 worker
|
|
13
|
+
// (hooks/native-safety-worker.ts) calls it, and the v1 entry carries that worker
|
|
14
|
+
// (scripts/build-native-entry.ts), so one guard decision has one
|
|
15
|
+
// implementation. It reads no stdin, writes no stdout and never exits: the
|
|
16
|
+
// caller owns the process.
|
|
14
17
|
|
|
15
|
-
export type NativeSafetyCompositeGuard = "trash-guard" | "workspace-repos-guard";
|
|
18
|
+
export type NativeSafetyCompositeGuard = "trash-guard" | "workspace-repos-guard" | "protected-delete-guard";
|
|
16
19
|
|
|
17
20
|
/** Refuses an unknown capability name exactly as the v1 entry always has. */
|
|
18
21
|
export function assertCompositeGuard(guard: unknown): asserts guard is NativeSafetyCompositeGuard {
|
|
19
|
-
if (guard !== "trash-guard" && guard !== "workspace-repos-guard") throw new Error("Invalid safety capability");
|
|
22
|
+
if (guard !== "trash-guard" && guard !== "workspace-repos-guard" && guard !== "protected-delete-guard") throw new Error("Invalid safety capability");
|
|
20
23
|
}
|
|
21
24
|
|
|
22
25
|
/**
|
|
@@ -54,6 +57,14 @@ export function evaluateComposite(guard: string, inputText: string): string {
|
|
|
54
57
|
const shellCommand = input.tool_name === "Bash" || (monitor && typeof input.tool_input.command === "string");
|
|
55
58
|
const evaluated: CodewithHookInput = monitor && shellCommand ? { ...input, tool_name: "Bash" } : input;
|
|
56
59
|
const deny = (reason: string) => ({ hookSpecificOutput: { hookEventName: "PreToolUse" as const, permissionDecision: "deny" as const, permissionDecisionReason: reason } });
|
|
60
|
+
// protected-delete-guard judges by its own class and nothing else: it only
|
|
61
|
+
// denies, it looks for no trash binary, and the checkout rules and the
|
|
62
|
+
// signed-link guard stay with the registrations that carry them, so switching
|
|
63
|
+
// this one off changes nothing but its own refusals.
|
|
64
|
+
if (name === "protected-delete-guard") {
|
|
65
|
+
const own = evaluateProtectedDelete(evaluated, { home: homedir(), cwd: input.cwd, env: process.env });
|
|
66
|
+
return JSON.stringify({ verdict: own.hookSpecificOutput?.permissionDecision === "deny" ? own : null });
|
|
67
|
+
}
|
|
57
68
|
const repos = evaluateRepos(evaluated).output;
|
|
58
69
|
// Every shell command, whatever the capability name: the guard reaches each
|
|
59
70
|
// registration of this entry. Its refusal outranks a Trash rewrite, because an
|
|
@@ -73,7 +84,7 @@ export function evaluateComposite(guard: string, inputText: string): string {
|
|
|
73
84
|
}
|
|
74
85
|
const verdict: CodewithHookOutput = repos.decision === "block" ? deny(repos.reason!)
|
|
75
86
|
: signedLinks.hookSpecificOutput ? signedLinks
|
|
76
|
-
: handoff ? deny(
|
|
87
|
+
: handoff ? deny(HANDOFF_REFUSED)
|
|
77
88
|
: trash;
|
|
78
89
|
return JSON.stringify({ verdict: "continue" in verdict ? null : verdict });
|
|
79
90
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hasna/hooks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Open source hooks library for AI coding agents - Install safety, quality, and automation hooks with a single command",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"postinstall": "node scripts/ensure-profiles-dir.mjs",
|
|
54
54
|
"scan:artifact": "bun scripts/artifact-scan.ts",
|
|
55
55
|
"prepack": "bun run build && bun run scan:artifact",
|
|
56
|
-
"build:native-safety": "bun build
|
|
56
|
+
"build:native-safety": "bun scripts/build-native-entry.ts && bun build ./src/native-safety.ts --outdir ./dist --target bun && bun run build:native-readiness",
|
|
57
57
|
"build:native-readiness": "bun build ./hooks/native-readiness-entry.ts --outdir ./bin --target node --format=cjs && bun build ./src/native-readiness.ts --outdir ./dist --target bun",
|
|
58
58
|
"build:native-safety-worker": "bun scripts/build-native-worker.ts",
|
|
59
59
|
"build:bundled-hooks": "bun scripts/build-bundled-hooks.ts",
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"@hasna/contracts": "~1.2.1"
|
|
88
88
|
},
|
|
89
89
|
"dependencies": {
|
|
90
|
-
"@hasna/skills": "0.10.
|
|
90
|
+
"@hasna/skills": "0.10.100",
|
|
91
91
|
"@hasna/events": "^0.1.16",
|
|
92
92
|
"@hasna/secrets": "0.4.2",
|
|
93
93
|
"@modelcontextprotocol/sdk": "1.31.0",
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Build the v1 native safety entry, bin/native-safety-entry.js (HO-00144).
|
|
4
|
+
*
|
|
5
|
+
* The v1 supervisor (src/lib/native-safety.ts, the current template and the
|
|
6
|
+
* frozen previous one the Sumi guard record keeps) reads the file a
|
|
7
|
+
* registration pins, checks its sha256 and passes its bytes to Bun as ONE
|
|
8
|
+
* `--eval` argument. Linux refuses a single argument of 131,072 bytes or more
|
|
9
|
+
* (MAX_ARG_STRLEN with 4 KiB pages), and the guard code alone is close to that.
|
|
10
|
+
*
|
|
11
|
+
* So the entry carries the v2 worker (scripts/build-native-worker.ts: the same
|
|
12
|
+
* bundle as bin/native-safety-worker.cjs) deflated and base64-encoded. When it
|
|
13
|
+
* runs, it inflates those bytes, refuses unless their sha256 equals the one
|
|
14
|
+
* written into the entry, evaluates exactly those bytes as a CommonJS function
|
|
15
|
+
* body with a `require` that serves only `node:` builtins (the v2 loader's
|
|
16
|
+
* shape, ADR 0001 section 3.3), and writes `evaluate(argv[1], stdin)` to
|
|
17
|
+
* stdout. Its contract with the supervisor is the v1 entry's: the capability
|
|
18
|
+
* name in argv[1], the hook input on stdin, one JSON write to stdout, and a
|
|
19
|
+
* non-zero exit on any failure.
|
|
20
|
+
*
|
|
21
|
+
* The supervisor's digest covers the deflated bytes and inflating is
|
|
22
|
+
* deterministic, so the code that runs is still fixed by the pinned digest.
|
|
23
|
+
* This raises the v1 ceiling, it does not remove it: the entry itself must stay
|
|
24
|
+
* below the argument limit, and the build refuses one that does not. The v2
|
|
25
|
+
* launcher (ADR 0001), which reads the worker from its file, has no such limit.
|
|
26
|
+
*
|
|
27
|
+
* Usage: bun scripts/build-native-entry.ts [--outfile <path>]
|
|
28
|
+
*/
|
|
29
|
+
import { createHash } from "node:crypto";
|
|
30
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
31
|
+
import { dirname, join, resolve } from "node:path";
|
|
32
|
+
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
|
33
|
+
import { bundleNativeSafetyWorker } from "./build-native-worker";
|
|
34
|
+
|
|
35
|
+
export const ENTRY_OUTFILE = "bin/native-safety-entry.js";
|
|
36
|
+
/** Linux's single exec argument limit with 4 KiB pages; the entry must stay below it. */
|
|
37
|
+
export const ENTRY_ARGUMENT_LIMIT = 131_072;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The entry's exact text for a deflated, base64-encoded worker and the worker's sha256.
|
|
41
|
+
*
|
|
42
|
+
* The first line must be the `// @bun` pragma that `bun build` writes. Without
|
|
43
|
+
* it Bun transpiles an `--eval` source this large and caches the result under
|
|
44
|
+
* `$HOME/.bun/install/cache`: the guard would write into the home it guards,
|
|
45
|
+
* and a later call could run that cached code instead of the bytes the
|
|
46
|
+
* supervisor verified. With it, Bun runs the text as written, so the entry is
|
|
47
|
+
* an ES module and uses `import`, not `require`.
|
|
48
|
+
*/
|
|
49
|
+
function entryText(packed: string, sha256: string): string {
|
|
50
|
+
return `// @bun
|
|
51
|
+
// @hasna/hooks native safety entry for the v1 supervisor: the v2 worker (bin/native-safety-worker.cjs), deflated. See scripts/build-native-entry.ts.
|
|
52
|
+
import { inflateRawSync } from "node:zlib";
|
|
53
|
+
import { createHash } from "node:crypto";
|
|
54
|
+
import { builtinModules, createRequire } from "node:module";
|
|
55
|
+
const builtins = new Set(builtinModules), load = createRequire("/");
|
|
56
|
+
const source = inflateRawSync(Buffer.from("${packed}", "base64"));
|
|
57
|
+
if (createHash("sha256").update(source).digest("hex") !== "${sha256}") throw new Error("native safety worker digest mismatch");
|
|
58
|
+
const worker = { exports: {} };
|
|
59
|
+
const workerRequire = (specifier) => {
|
|
60
|
+
if (typeof specifier === "string" && /^node:[a-z][a-z0-9_]*(?:[/][a-z][a-z0-9_]*)*$/.test(specifier) && builtins.has(specifier.slice(5))) return load(specifier);
|
|
61
|
+
throw new Error("native safety worker may require only node: builtins");
|
|
62
|
+
};
|
|
63
|
+
new Function("module", "exports", "require", source.toString("utf8"))(worker, worker.exports, workerRequire);
|
|
64
|
+
if (worker.exports.abi !== 2 || typeof worker.exports.evaluate !== "function") throw new Error("native safety worker ABI mismatch");
|
|
65
|
+
process.stdout.write(worker.exports.evaluate(process.argv[1], await Bun.stdin.text()));
|
|
66
|
+
`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The entry that carries `workerSource`. Pure: the same worker gives the same entry. */
|
|
70
|
+
export function nativeSafetyEntrySource(workerSource: string): string {
|
|
71
|
+
const bytes = Buffer.from(workerSource, "utf8");
|
|
72
|
+
return entryText(deflateRawSync(bytes, { level: 9 }).toString("base64"), createHash("sha256").update(bytes).digest("hex"));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The worker bytes an entry carries, or undefined when `entry` is not exactly
|
|
77
|
+
* an entry this script writes: the wrapper text must match byte for byte, and
|
|
78
|
+
* the inflated bytes must match the sha256 written into it.
|
|
79
|
+
*/
|
|
80
|
+
export function nativeSafetyEntryWorker(entry: string): Buffer | undefined {
|
|
81
|
+
const parts = /\nconst source = inflateRawSync\(Buffer\.from\("([A-Za-z0-9+/]*={0,2})", "base64"\)\);\nif \(createHash\("sha256"\)\.update\(source\)\.digest\("hex"\) !== "([0-9a-f]{64})"\)/.exec(entry);
|
|
82
|
+
if (!parts || entryText(parts[1]!, parts[2]!) !== entry) return undefined;
|
|
83
|
+
try {
|
|
84
|
+
const source = inflateRawSync(Buffer.from(parts[1]!, "base64"));
|
|
85
|
+
return createHash("sha256").update(source).digest("hex") === parts[2] ? source : undefined;
|
|
86
|
+
} catch { return undefined; }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface NativeSafetyEntryBuild { outfile: string; bytes: number; sha256: string; workerBytes: number; workerSHA256: string; version: string }
|
|
90
|
+
|
|
91
|
+
/** Bundle the worker, wrap it and write the entry. Writes nothing when the worker check or the size check fails. */
|
|
92
|
+
export async function buildNativeSafetyEntry(options: { packageDir?: string; outfile?: string } = {}): Promise<NativeSafetyEntryBuild> {
|
|
93
|
+
const packageDir = resolve(options.packageDir ?? join(import.meta.dir, ".."));
|
|
94
|
+
const outfile = resolve(packageDir, options.outfile ?? ENTRY_OUTFILE);
|
|
95
|
+
const { source, version } = await bundleNativeSafetyWorker(packageDir);
|
|
96
|
+
const entry = nativeSafetyEntrySource(source);
|
|
97
|
+
const bytes = Buffer.byteLength(entry);
|
|
98
|
+
if (bytes >= ENTRY_ARGUMENT_LIMIT) throw new Error(`native safety entry is ${bytes} bytes; one exec argument holds at most ${ENTRY_ARGUMENT_LIMIT - 1}`);
|
|
99
|
+
mkdirSync(dirname(outfile), { recursive: true });
|
|
100
|
+
// A new file is never group- or world-writable, whatever the umask: the supervisor's pin check refuses such a file.
|
|
101
|
+
writeFileSync(outfile, entry, { mode: 0o644 });
|
|
102
|
+
return {
|
|
103
|
+
outfile, bytes, sha256: createHash("sha256").update(entry).digest("hex"),
|
|
104
|
+
workerBytes: Buffer.byteLength(source), workerSHA256: createHash("sha256").update(source).digest("hex"), version,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (import.meta.main) {
|
|
109
|
+
const args = process.argv.slice(2);
|
|
110
|
+
let outfile: string | undefined;
|
|
111
|
+
if (args.length === 2 && args[0] === "--outfile" && args[1]) outfile = resolve(args[1]);
|
|
112
|
+
else if (args.length !== 0) {
|
|
113
|
+
console.error("usage: bun scripts/build-native-entry.ts [--outfile <path>]");
|
|
114
|
+
process.exit(2);
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
const built = await buildNativeSafetyEntry({ outfile });
|
|
118
|
+
console.log(`native-safety-entry.js ${built.version}: ${built.bytes} bytes (worker ${built.workerBytes} bytes, sha256 ${built.workerSHA256}), sha256 ${built.sha256} -> ${built.outfile}`);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -107,10 +107,9 @@ export function workerBundleProblems(source: string): string[] {
|
|
|
107
107
|
|
|
108
108
|
export interface NativeSafetyWorkerBuild { outfile: string; bytes: number; sha256: string; version: string }
|
|
109
109
|
|
|
110
|
-
/** Bundle
|
|
111
|
-
export async function
|
|
112
|
-
|
|
113
|
-
const outfile = resolve(packageDir, options.outfile ?? WORKER_OUTFILE);
|
|
110
|
+
/** Bundle and check the worker without writing it. Throws when a check fails. */
|
|
111
|
+
export async function bundleNativeSafetyWorker(packageDir: string = join(import.meta.dir, "..")): Promise<{ source: string; version: string }> {
|
|
112
|
+
packageDir = resolve(packageDir);
|
|
114
113
|
const version: unknown = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")).version;
|
|
115
114
|
if (typeof version !== "string" || !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) throw new Error("package.json has no valid version for the native safety worker");
|
|
116
115
|
const result = await Bun.build({
|
|
@@ -128,6 +127,14 @@ export async function buildNativeSafetyWorker(options: { packageDir?: string; ou
|
|
|
128
127
|
const source = await result.outputs[0]!.text();
|
|
129
128
|
const problems = workerBundleProblems(source);
|
|
130
129
|
if (problems.length > 0) throw new Error(`native safety worker bundle refused:\n${problems.map((problem) => ` - ${problem}`).join("\n")}`);
|
|
130
|
+
return { source, version };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Bundle, check and write the worker. Writes nothing when a check fails. */
|
|
134
|
+
export async function buildNativeSafetyWorker(options: { packageDir?: string; outfile?: string } = {}): Promise<NativeSafetyWorkerBuild> {
|
|
135
|
+
const packageDir = resolve(options.packageDir ?? join(import.meta.dir, ".."));
|
|
136
|
+
const outfile = resolve(packageDir, options.outfile ?? WORKER_OUTFILE);
|
|
137
|
+
const { source, version } = await bundleNativeSafetyWorker(packageDir);
|
|
131
138
|
mkdirSync(dirname(outfile), { recursive: true });
|
|
132
139
|
// A new file is never group- or world-writable, whatever the umask: the launcher's pin check refuses such a worker.
|
|
133
140
|
writeFileSync(outfile, source, { mode: 0o644 });
|
|
@@ -3,6 +3,7 @@ import { existsSync } from "node:fs";
|
|
|
3
3
|
import { chmod, copyFile, mkdtemp, mkdir, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { validatePackedBundledHooks } from "./validate-bundled-hooks";
|
|
6
|
+
import { ENTRY_ARGUMENT_LIMIT, nativeSafetyEntryWorker } from "./build-native-entry";
|
|
6
7
|
|
|
7
8
|
type PackageJson = {
|
|
8
9
|
name: string;
|
|
@@ -275,10 +276,15 @@ console.log("packed Hooks accepts codex-settings-v6 and refuses unknown mode wit
|
|
|
275
276
|
async function validatePackedNativeSafety(packageDir: string, smokeDir: string): Promise<void> {
|
|
276
277
|
const worker = join(packageDir, "bin/native-safety-entry.js");
|
|
277
278
|
const bytes = await readFile(worker);
|
|
278
|
-
// The supervisor passes the
|
|
279
|
+
// The supervisor passes the entry as one `--eval` argument; Linux refuses a
|
|
279
280
|
// single argument over 32 pages (131,072 bytes with 4 KiB pages), and every
|
|
280
281
|
// command would then fail to launch. Check it before the launch smoke tests.
|
|
281
|
-
if (bytes.length >=
|
|
282
|
+
if (bytes.length >= ENTRY_ARGUMENT_LIMIT) throw new Error(`Packed native entry is ${bytes.length} bytes; one exec argument holds at most ${ENTRY_ARGUMENT_LIMIT - 1}`);
|
|
283
|
+
// The entry carries the v2 worker deflated (scripts/build-native-entry.ts).
|
|
284
|
+
// Both lanes must run the same guard code, so it must carry exactly the
|
|
285
|
+
// packed bin/native-safety-worker.cjs.
|
|
286
|
+
const carried = nativeSafetyEntryWorker(bytes.toString("utf8"));
|
|
287
|
+
if (!carried || !carried.equals(await readFile(join(packageDir, "bin/native-safety-worker.cjs")))) throw new Error("Packed native entry does not carry the packed bin/native-safety-worker.cjs");
|
|
282
288
|
const home = join(smokeDir, "native-safety-home");
|
|
283
289
|
await mkdir(home, { mode: 0o700 });
|
|
284
290
|
const settings = join(home, ".codex", "hooks.json");
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { assertCompositeGuard, evaluateComposite } from "./native-safety-composite";
|
|
2
|
-
|
|
3
|
-
// The v1 native safety entry: a thin wrapper over the composite. Its contract is
|
|
4
|
-
// fixed by the v1 supervisor (src/lib/native-safety.ts): the capability name is
|
|
5
|
-
// argv[1], the hook input is stdin, the verdict is one JSON write to stdout, and
|
|
6
|
-
// any failure exits non-zero.
|
|
7
|
-
// Bundled with import.meta.main=false, so the original standalone run wrappers
|
|
8
|
-
// cannot swallow exceptions or emit a second response. Only this entry runs.
|
|
9
|
-
const name = process.argv[1];
|
|
10
|
-
assertCompositeGuard(name);
|
|
11
|
-
process.stdout.write(evaluateComposite(name, await Bun.stdin.text()));
|