@crewhaus/tool-fleet 0.7.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.
@@ -0,0 +1,97 @@
1
+ import { type ManagerHook, type ManagerHookName } from "@crewhaus/harness-supervisor";
2
+ import { type Loaded } from "./result";
3
+ /** `<harness>/.crewhaus/settings.json`, from the supervisor's own segments. */
4
+ export declare function settingsRelPath(): string;
5
+ export declare function settingsAbsPath(harnessRoot: string): string;
6
+ export type SettingsState = "absent" | "ok" | "unparseable" | "not-a-file" | "unreadable";
7
+ export type SettingsProbe = {
8
+ readonly state: SettingsState;
9
+ readonly path: string;
10
+ readonly detail?: string;
11
+ /** The whole document, when it parsed — every key, including the ones
12
+ * this package knows nothing about. */
13
+ readonly doc?: Record<string, unknown>;
14
+ /** The file's current mode, so a rewrite can preserve it. */
15
+ readonly mode?: number;
16
+ };
17
+ export declare function probeSettings(abs: string, shown: string): SettingsProbe;
18
+ /** A settings file a write may proceed against: absent, or parsed. */
19
+ export declare function writeBlockedBy(probe: SettingsProbe): Loaded<undefined>;
20
+ export type CommandState = "executable" | "not-executable" | "absent" | "unreadable" | "path-lookup";
21
+ export type HookView = {
22
+ readonly name: ManagerHookName;
23
+ /** The declaration verbatim. */
24
+ readonly declaredAs: string;
25
+ /** What the supervisor will actually spawn. */
26
+ readonly argv: readonly string[];
27
+ /** argv[0] resolved the way the supervisor resolves it. */
28
+ readonly command: string;
29
+ readonly commandState: CommandState;
30
+ readonly detail?: string;
31
+ /** Set when the declaration parses to something the operator did not mean. */
32
+ readonly warning?: string;
33
+ };
34
+ /**
35
+ * Whether the command a hook declares can be run — WITHOUT running it.
36
+ *
37
+ * A bare name is left to the OS: `resolveHookCommand` does not touch it, so
38
+ * the answer depends on the PATH of whatever process spawns the hook, which
39
+ * is not this one. Reporting "absent" for it would be a guess; `path-lookup`
40
+ * is the honest answer.
41
+ */
42
+ export declare function probeCommand(command: string): {
43
+ state: CommandState;
44
+ detail?: string;
45
+ };
46
+ /**
47
+ * A string declaration containing whitespace is a single command NAME.
48
+ *
49
+ * This is the shape that reads as working and never runs: the operator
50
+ * writes `"bun run prep.ts"`, the supervisor spawns a file called
51
+ * `bun run prep.ts`, the spawn fails with ENOENT and the start is refused.
52
+ * The check is on the PARSED argv, not on the spelling — a one-element argv
53
+ * whose single element contains whitespace — so it cannot be fooled by how
54
+ * the value was written.
55
+ */
56
+ export declare function splitWarning(argv: readonly string[]): string | undefined;
57
+ /**
58
+ * One hook, parsed, resolved and probed.
59
+ *
60
+ * The declaration is operator-authored JSON this package did not write, so
61
+ * the strings it reports are bounded and stripped of control characters. The
62
+ * PROBE and the resolution run on the raw `command` — the rendered copy is
63
+ * for the result only, never for a decision.
64
+ */
65
+ export declare function viewHook(name: ManagerHookName, hook: ManagerHook, harnessRoot: string): HookView;
66
+ /** Parse a caller's declaration with the supervisor's own parser. */
67
+ export declare function parseDeclaration(value: string | readonly string[]): Loaded<ManagerHook>;
68
+ /** The `manager` object of a parsed document, when it has a usable one. */
69
+ export declare function managerBlock(doc: Record<string, unknown>): Loaded<Record<string, unknown>>;
70
+ /**
71
+ * The document with ONE hook set or removed, everything else preserved.
72
+ *
73
+ * Preservation is the point: `settings.json` also carries the runtime's
74
+ * `hooks` and `permissions` blocks and whatever a newer CLI writes, and this
75
+ * package knows nothing about any of it. So the document is spread, the
76
+ * `manager` block is spread, the `hooks` block is spread, and exactly one
77
+ * key changes.
78
+ */
79
+ export declare function withHook(doc: Record<string, unknown>, manager: Record<string, unknown>, name: ManagerHookName, value: string | readonly string[] | undefined, timeoutMs?: number): Record<string, unknown>;
80
+ /** The timeout a hook will really get, and whether it is the default. */
81
+ export declare function timeoutView(timeoutMs: number): {
82
+ ms: number;
83
+ isDefault: boolean;
84
+ };
85
+ /**
86
+ * Write the document atomically: a temp file in the same directory, then a
87
+ * rename.
88
+ *
89
+ * The rename is what makes it atomic, and it is also what makes the
90
+ * containment check on BOTH names load-bearing — a rename replaces whatever
91
+ * the destination name points at. The caller has already contained them.
92
+ *
93
+ * The mode is preserved when the file existed (a rename would otherwise
94
+ * silently re-permission an operator's file), and a new file is created 0600
95
+ * like every other crewhaus-written settings artifact.
96
+ */
97
+ export declare function writeSettingsFile(tmpAbs: string, finalAbs: string, doc: Record<string, unknown>, mode: number | undefined): Loaded<undefined>;
@@ -0,0 +1,280 @@
1
+ /**
2
+ * The `manager` block of `<harness>/.crewhaus/settings.json`: reading what
3
+ * is declared, reporting what it PARSES to, and replacing one hook without
4
+ * losing the rest of the file.
5
+ *
6
+ * The parse rules are `@crewhaus/harness-supervisor`'s and are not repeated
7
+ * here: `parseManagerHook` decides what a declaration means,
8
+ * `readManagerSettings` fills in the defaults, `resolveHookCommand` decides
9
+ * what a command resolves against, `DEFAULT_HOOK_TIMEOUT_MS` is the timeout
10
+ * a hook gets when none is declared. This module adds the two things a
11
+ * supervisor's tolerant reader deliberately does not have.
12
+ *
13
+ * FIRST, THE FILE'S CONDITION. `readManagerSettings` answers a file that is
14
+ * missing, malformed, or carrying a `manager` key of the wrong type with the
15
+ * same empty defaults — correct for a spawn path that must not die on a
16
+ * typo, useless for an operator asking "are my hooks set up?", and dangerous
17
+ * for a WRITE: re-serializing the defaults over a file that failed to parse
18
+ * would throw away the operator's own JSON, and the file is shared with the
19
+ * runtime's `hooks` and `permissions` blocks.
20
+ *
21
+ * SECOND, THE GAP BETWEEN A DECLARATION AND ITS ARGV. A STRING declaration
22
+ * is ONE command name — the supervisor does not word-split it, on purpose
23
+ * (`"splitting is the first half of implementing a shell"`). So
24
+ * `"bun run prep.ts"` declares a command whose FILENAME is `bun run prep.ts`,
25
+ * which no `spawn` will ever find; the hook then refuses every start with an
26
+ * ENOENT nobody connects back to the settings file. Every report here shows
27
+ * the parsed `argv`, not the spelling, and a write that would create that
28
+ * shape is refused with the array form spelled out.
29
+ */
30
+ import { constants, accessSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from "node:fs";
31
+ import { dirname, isAbsolute, join } from "node:path";
32
+ import { DEFAULT_HOOK_TIMEOUT_MS, parseManagerHook, resolveHookCommand, } from "@crewhaus/harness-supervisor";
33
+ import { MANAGER_SETTINGS_SEGMENTS } from "@crewhaus/harness-supervisor";
34
+ import { fail, probeName, renderPath, renderStorePath, renderText } from "./result";
35
+ /** `<harness>/.crewhaus/settings.json`, from the supervisor's own segments. */
36
+ export function settingsRelPath() {
37
+ return MANAGER_SETTINGS_SEGMENTS.join("/");
38
+ }
39
+ export function settingsAbsPath(harnessRoot) {
40
+ return join(harnessRoot, ...MANAGER_SETTINGS_SEGMENTS);
41
+ }
42
+ /** A settings file a human owns; anything past this is not one. */
43
+ const MAX_SETTINGS_BYTES = 8 * 1024 * 1024;
44
+ export function probeSettings(abs, shown) {
45
+ const kind = probeName(shown, abs);
46
+ if (!kind.ok)
47
+ return { state: "unreadable", path: shown, detail: kind.reason };
48
+ if (kind.value === undefined)
49
+ return { state: "absent", path: shown };
50
+ if (kind.value === "directory" || kind.value === "other") {
51
+ return { state: "not-a-file", path: shown, detail: `it is a ${kind.value}, not a file` };
52
+ }
53
+ let text;
54
+ let mode;
55
+ try {
56
+ const stat = statSync(abs);
57
+ if (stat.size > MAX_SETTINGS_BYTES) {
58
+ return {
59
+ state: "unreadable",
60
+ path: shown,
61
+ detail: `larger than ${MAX_SETTINGS_BYTES} bytes`,
62
+ };
63
+ }
64
+ mode = stat.mode & 0o777;
65
+ text = readFileSync(abs, "utf8");
66
+ }
67
+ catch (err) {
68
+ const code = err.code;
69
+ return {
70
+ state: "unreadable",
71
+ path: shown,
72
+ detail: `could not be read (${code ?? "unknown error"})`,
73
+ };
74
+ }
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(text);
78
+ }
79
+ catch (err) {
80
+ return {
81
+ state: "unparseable",
82
+ path: shown,
83
+ detail: `not valid JSON (${err instanceof Error ? err.message : "parse error"})`,
84
+ ...(mode !== undefined ? { mode } : {}),
85
+ };
86
+ }
87
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
88
+ return {
89
+ state: "unparseable",
90
+ path: shown,
91
+ detail: "the document is not a JSON object",
92
+ ...(mode !== undefined ? { mode } : {}),
93
+ };
94
+ }
95
+ return {
96
+ state: "ok",
97
+ path: shown,
98
+ doc: parsed,
99
+ ...(mode !== undefined ? { mode } : {}),
100
+ };
101
+ }
102
+ /** A settings file a write may proceed against: absent, or parsed. */
103
+ export function writeBlockedBy(probe) {
104
+ if (probe.state === "ok" || probe.state === "absent")
105
+ return { ok: true, value: undefined };
106
+ return fail(probe.state === "unparseable" ? "refused" : "unreadable", `"${probe.path}" ${probe.detail ?? probe.state} — refusing to rewrite it. The file is shared with the runtime's own hooks and permissions blocks, and a rewrite of a document this tool could not read would discard them. A settings file that could not be parsed is not an empty one.`);
107
+ }
108
+ /**
109
+ * Whether the command a hook declares can be run — WITHOUT running it.
110
+ *
111
+ * A bare name is left to the OS: `resolveHookCommand` does not touch it, so
112
+ * the answer depends on the PATH of whatever process spawns the hook, which
113
+ * is not this one. Reporting "absent" for it would be a guess; `path-lookup`
114
+ * is the honest answer.
115
+ */
116
+ export function probeCommand(command) {
117
+ if (!isAbsolute(command))
118
+ return { state: "path-lookup" };
119
+ const kind = probeName(command, command);
120
+ if (!kind.ok)
121
+ return { state: "unreadable", detail: kind.reason };
122
+ if (kind.value === undefined) {
123
+ return { state: "absent", detail: "nothing exists at that path" };
124
+ }
125
+ // WHAT THE NAME IS, before asking whether it can be executed. `access(…,
126
+ // X_OK)` on a DIRECTORY succeeds — the execute bit on a directory means
127
+ // "may be traversed" — so a hook declared as `./prep.sh` when `prep.sh` is
128
+ // a directory reads back `executable` here and then refuses every start of
129
+ // the harness with EACCES. The probe exists to catch exactly that before
130
+ // it is written.
131
+ if (kind.value === "directory" || kind.value === "other") {
132
+ return {
133
+ state: "not-executable",
134
+ detail: `it is a ${kind.value}, not a file — a spawn of it fails with EACCES`,
135
+ };
136
+ }
137
+ if (kind.value === "symlink") {
138
+ // `lstat` answered about the LINK. A dangling one is `absent`, not a
139
+ // permission problem, and a link to a directory is the case above.
140
+ let through;
141
+ try {
142
+ through = statSync(command);
143
+ }
144
+ catch (err) {
145
+ const code = err.code;
146
+ return code === "ENOENT" || code === "ENOTDIR"
147
+ ? { state: "absent", detail: "a symlink whose target does not exist" }
148
+ : {
149
+ state: "unreadable",
150
+ detail: `the symlink could not be followed (${code ?? "unknown"})`,
151
+ };
152
+ }
153
+ if (!through.isFile()) {
154
+ return {
155
+ state: "not-executable",
156
+ detail: "a symlink to something that is not a file — a spawn of it fails with EACCES",
157
+ };
158
+ }
159
+ }
160
+ try {
161
+ accessSync(command, constants.X_OK);
162
+ return { state: "executable" };
163
+ }
164
+ catch {
165
+ return { state: "not-executable", detail: "the file has no execute permission for this user" };
166
+ }
167
+ }
168
+ /**
169
+ * A string declaration containing whitespace is a single command NAME.
170
+ *
171
+ * This is the shape that reads as working and never runs: the operator
172
+ * writes `"bun run prep.ts"`, the supervisor spawns a file called
173
+ * `bun run prep.ts`, the spawn fails with ENOENT and the start is refused.
174
+ * The check is on the PARSED argv, not on the spelling — a one-element argv
175
+ * whose single element contains whitespace — so it cannot be fooled by how
176
+ * the value was written.
177
+ */
178
+ export function splitWarning(argv) {
179
+ const only = argv.length === 1 ? argv[0] : undefined;
180
+ if (only === undefined || !/\s/.test(only))
181
+ return undefined;
182
+ return `declared as ONE command whose name contains whitespace ("${renderPath(only)}"). The supervisor never word-splits a string declaration, so it will spawn a file with that exact name and the start will be refused. Declare the array form instead, e.g. ["${renderPath(only).split(/\s+/).join('", "')}"].`;
183
+ }
184
+ /**
185
+ * One hook, parsed, resolved and probed.
186
+ *
187
+ * The declaration is operator-authored JSON this package did not write, so
188
+ * the strings it reports are bounded and stripped of control characters. The
189
+ * PROBE and the resolution run on the raw `command` — the rendered copy is
190
+ * for the result only, never for a decision.
191
+ */
192
+ export function viewHook(name, hook, harnessRoot) {
193
+ const command = resolveHookCommand(harnessRoot, hook.argv[0]);
194
+ const probed = probeCommand(command);
195
+ const warning = splitWarning(hook.argv);
196
+ return {
197
+ name,
198
+ declaredAs: renderText(hook.declaredAs, 400),
199
+ argv: hook.argv.map((part) => renderText(part, 400)),
200
+ command: renderStorePath(command),
201
+ commandState: probed.state,
202
+ ...(probed.detail !== undefined ? { detail: probed.detail } : {}),
203
+ ...(warning !== undefined ? { warning } : {}),
204
+ };
205
+ }
206
+ /** Parse a caller's declaration with the supervisor's own parser. */
207
+ export function parseDeclaration(value) {
208
+ const hook = parseManagerHook(Array.isArray(value) ? [...value] : value);
209
+ if (hook === undefined) {
210
+ return fail("bad-input", "the declaration parses to no command at all — @crewhaus/harness-supervisor's parseManagerHook drops empty strings and entries that are not non-empty strings, and a hook it cannot parse is silently NO hook");
211
+ }
212
+ return { ok: true, value: hook };
213
+ }
214
+ // ---------------------------------------------------------------------------
215
+ // editing the document
216
+ // ---------------------------------------------------------------------------
217
+ /** The `manager` object of a parsed document, when it has a usable one. */
218
+ export function managerBlock(doc) {
219
+ const manager = doc["manager"];
220
+ if (manager === undefined)
221
+ return { ok: true, value: {} };
222
+ if (typeof manager !== "object" || manager === null || Array.isArray(manager)) {
223
+ return fail("refused", `the "manager" key is ${Array.isArray(manager) ? "an array" : typeof manager}, not an object — the supervisor ignores it entirely and writing into it would replace whatever it holds`);
224
+ }
225
+ return { ok: true, value: manager };
226
+ }
227
+ /**
228
+ * The document with ONE hook set or removed, everything else preserved.
229
+ *
230
+ * Preservation is the point: `settings.json` also carries the runtime's
231
+ * `hooks` and `permissions` blocks and whatever a newer CLI writes, and this
232
+ * package knows nothing about any of it. So the document is spread, the
233
+ * `manager` block is spread, the `hooks` block is spread, and exactly one
234
+ * key changes.
235
+ */
236
+ export function withHook(doc, manager, name, value, timeoutMs) {
237
+ const rawHooks = manager["hooks"];
238
+ const hooks = typeof rawHooks === "object" && rawHooks !== null && !Array.isArray(rawHooks)
239
+ ? { ...rawHooks }
240
+ : {};
241
+ if (value === undefined)
242
+ delete hooks[name];
243
+ else
244
+ hooks[name] = Array.isArray(value) ? [...value] : value;
245
+ if (timeoutMs !== undefined)
246
+ hooks["timeoutMs"] = timeoutMs;
247
+ return { ...doc, manager: { ...manager, hooks } };
248
+ }
249
+ /** The timeout a hook will really get, and whether it is the default. */
250
+ export function timeoutView(timeoutMs) {
251
+ return { ms: timeoutMs, isDefault: timeoutMs === DEFAULT_HOOK_TIMEOUT_MS };
252
+ }
253
+ /**
254
+ * Write the document atomically: a temp file in the same directory, then a
255
+ * rename.
256
+ *
257
+ * The rename is what makes it atomic, and it is also what makes the
258
+ * containment check on BOTH names load-bearing — a rename replaces whatever
259
+ * the destination name points at. The caller has already contained them.
260
+ *
261
+ * The mode is preserved when the file existed (a rename would otherwise
262
+ * silently re-permission an operator's file), and a new file is created 0600
263
+ * like every other crewhaus-written settings artifact.
264
+ */
265
+ export function writeSettingsFile(tmpAbs, finalAbs, doc, mode) {
266
+ try {
267
+ // A harness that has never been supervised has no `.crewhaus` at all —
268
+ // the common case for the FIRST hook anyone declares — and writing the
269
+ // temp file into a directory that does not exist fails with ENOENT. 0700
270
+ // is the mode every other crewhaus state directory is created with.
271
+ mkdirSync(dirname(finalAbs), { recursive: true, mode: 0o700 });
272
+ writeFileSync(tmpAbs, `${JSON.stringify(doc, null, 2)}\n`, { mode: mode ?? 0o600 });
273
+ renameSync(tmpAbs, finalAbs);
274
+ return { ok: true, value: undefined };
275
+ }
276
+ catch (err) {
277
+ const code = err.code;
278
+ return fail("unreadable", `the settings file could not be written (${code ?? "unknown error"})`);
279
+ }
280
+ }
@@ -0,0 +1,42 @@
1
+ import { CrewhausError } from "@crewhaus/errors";
2
+ /** Raised when a caller-supplied path resolves outside the workspace root. */
3
+ export declare class ToolPermissionError extends CrewhausError {
4
+ readonly name = "ToolPermissionError";
5
+ readonly toolName: string;
6
+ readonly path: string;
7
+ constructor(toolName: string, attemptedPath: string);
8
+ }
9
+ /**
10
+ * A validated path, in both forms the tools need.
11
+ *
12
+ * `real` has every in-workspace symlink already resolved and is what I/O
13
+ * should use — operating on it closes most of the check-to-use window.
14
+ * `abs` is the lexical resolution, which is what a tool must use when the
15
+ * question is about the link ITSELF (`Stat` reporting a symlink target,
16
+ * `RemovePath` deleting a link rather than its destination).
17
+ */
18
+ export type SafePath = {
19
+ readonly abs: string;
20
+ readonly real: string;
21
+ /** The path as the caller wrote it, for echoing back in results. */
22
+ readonly given: string;
23
+ /** Slash-separated path relative to the workspace root. */
24
+ readonly rel: string;
25
+ };
26
+ /** The workspace root, resolved. Every path is contained within it. */
27
+ export declare function workspaceRoot(): string;
28
+ export declare function resolveSafe(toolName: string, rel: string, root?: string): SafePath;
29
+ /** A path relative to the workspace root, with `/` separators on every OS. */
30
+ export declare function toPosix(p: string): string;
31
+ /**
32
+ * True when `candidate` is `parent` or lives underneath it. Both must already
33
+ * be absolute. Used to keep an archive entry, or a symlink inside an
34
+ * extracted tree, from reaching outside its destination.
35
+ */
36
+ export declare function isInside(parent: string, candidate: string): boolean;
37
+ /**
38
+ * Reject an archive member name that would escape its destination: an
39
+ * absolute path, a Windows drive prefix, or any `..` segment. Checked on the
40
+ * NAME, before extraction, because after extraction the damage is done.
41
+ */
42
+ export declare function archiveEntryEscapes(name: string): boolean;
package/dist/paths.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Path containment — the gate every caller-supplied path in this package
3
+ * passes through before any syscall touches it.
4
+ *
5
+ * The approach is the one `@crewhaus/tool-fs` uses, and for the same reasons:
6
+ * a lexical check alone is fooled by a symlink that lives inside the
7
+ * workspace and points outside it (CWE-59), so the real path is checked too.
8
+ * The workspace root is `process.cwd()`, matching tool-fs, so a harness that
9
+ * trusts one tool's boundary gets the same boundary here.
10
+ */
11
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
12
+ import * as path from "node:path";
13
+ import { CrewhausError } from "@crewhaus/errors";
14
+ /** Raised when a caller-supplied path resolves outside the workspace root. */
15
+ export class ToolPermissionError extends CrewhausError {
16
+ name = "ToolPermissionError";
17
+ toolName;
18
+ path;
19
+ constructor(toolName, attemptedPath) {
20
+ super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
21
+ this.toolName = toolName;
22
+ this.path = attemptedPath;
23
+ }
24
+ }
25
+ /** The workspace root, resolved. Every path is contained within it. */
26
+ export function workspaceRoot() {
27
+ return path.resolve(process.cwd());
28
+ }
29
+ /**
30
+ * Resolve `rel` inside the workspace, or throw `ToolPermissionError`.
31
+ *
32
+ * The leaf is allowed not to exist — every tool here that creates something
33
+ * needs to validate a destination before it is made — so the deepest
34
+ * EXISTING ancestor is realpath'd and the missing tail re-appended. Any
35
+ * failure other than that walk fails closed.
36
+ */
37
+ /**
38
+ * True when the NAME exists, whether or not it leads anywhere.
39
+ *
40
+ * `existsSync` FOLLOWS symlinks, so it answers false for a link whose target
41
+ * is missing — and that is exactly the case that matters: a dangling link is
42
+ * still a door, because `open(…, "w")` through `evil -> /outside/x` CREATES
43
+ * `/outside/x`. Probing with `lstat` keeps the link's name in the part of the
44
+ * path that gets resolved, rather than in the "does not exist yet" tail that
45
+ * is re-appended to the root verbatim and so passes the containment check.
46
+ */
47
+ function nameExists(p) {
48
+ try {
49
+ lstatSync(p);
50
+ return true;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ /**
57
+ * Where `target` would actually land, with every symlink on the way already
58
+ * followed — including one whose own target does not exist yet.
59
+ *
60
+ * `realpathSync` gives up with ENOENT on a dangling link, which would leave
61
+ * that link unresolved and let it stand in for a plain missing file. So the
62
+ * deepest ancestor that exists as a NAME is resolved, a dangling one is
63
+ * followed a hop by hand, and the components that do not exist are appended.
64
+ * The result is the path an `open` would create, which is the only path worth
65
+ * checking containment against.
66
+ */
67
+ function resolveLocation(target, depth = 0) {
68
+ if (depth > 40)
69
+ throw new Error(`symlink chain at "${target}" is too long to resolve`);
70
+ let probe = target;
71
+ const tail = [];
72
+ while (!nameExists(probe)) {
73
+ tail.unshift(path.basename(probe));
74
+ const parent = path.dirname(probe);
75
+ if (parent === probe)
76
+ break; // reached the filesystem root
77
+ probe = parent;
78
+ }
79
+ let probeReal;
80
+ try {
81
+ probeReal = realpathSync(probe);
82
+ }
83
+ catch (err) {
84
+ if (err.code !== "ENOENT")
85
+ throw err;
86
+ // The name is there but `realpath` cannot finish it: a symlink with a
87
+ // missing target. `readlinkSync` throws EINVAL on anything else, which
88
+ // fails closed.
89
+ const link = readlinkSync(probe);
90
+ // A RELATIVE target resolves against the directory that actually CONTAINS
91
+ // the link, which is not the link's lexical parent when that parent is
92
+ // itself reached through a symlink. `<root>/dirlink/x -> ../y` with
93
+ // `dirlink` pointing out of the root really lands at `<elsewhere>/y`, but
94
+ // measured from the lexical parent it reads as `<root>/y` — an in-root
95
+ // path the caller's path does not lead to. So the parent is made real
96
+ // first. An absolute target ignores the base.
97
+ const base = realpathSync(path.dirname(probe));
98
+ probeReal = resolveLocation(path.resolve(base, link), depth + 1);
99
+ }
100
+ return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
101
+ }
102
+ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
103
+ const rootResolved = path.resolve(root);
104
+ const abs = path.resolve(rootResolved, rel);
105
+ // 1) Lexical containment — rejects `..` and absolute escapes. The trailing
106
+ // separator avoids the `/root` vs `/root-sibling` prefix pitfall.
107
+ if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
108
+ throw new ToolPermissionError(toolName, rel);
109
+ }
110
+ let real;
111
+ try {
112
+ const rootReal = realpathSync(rootResolved);
113
+ real = resolveLocation(abs);
114
+ // 2) Symlink-aware containment. The real path must land inside the real
115
+ // root, so an in-workspace symlink pointing at /etc is refused here.
116
+ if (real !== rootReal && !real.startsWith(`${rootReal}${path.sep}`)) {
117
+ throw new ToolPermissionError(toolName, rel);
118
+ }
119
+ }
120
+ catch (err) {
121
+ if (err instanceof ToolPermissionError)
122
+ throw err;
123
+ throw new ToolPermissionError(toolName, rel);
124
+ }
125
+ return {
126
+ abs,
127
+ real,
128
+ given: rel,
129
+ rel: toPosix(path.relative(rootResolved, abs)),
130
+ };
131
+ }
132
+ /** A path relative to the workspace root, with `/` separators on every OS. */
133
+ export function toPosix(p) {
134
+ return path.sep === "/" ? p : p.split(path.sep).join("/");
135
+ }
136
+ /**
137
+ * True when `candidate` is `parent` or lives underneath it. Both must already
138
+ * be absolute. Used to keep an archive entry, or a symlink inside an
139
+ * extracted tree, from reaching outside its destination.
140
+ */
141
+ export function isInside(parent, candidate) {
142
+ const p = path.resolve(parent);
143
+ const c = path.resolve(candidate);
144
+ return c === p || c.startsWith(`${p}${path.sep}`);
145
+ }
146
+ /**
147
+ * Reject an archive member name that would escape its destination: an
148
+ * absolute path, a Windows drive prefix, or any `..` segment. Checked on the
149
+ * NAME, before extraction, because after extraction the damage is done.
150
+ */
151
+ export function archiveEntryEscapes(name) {
152
+ const normalized = name.replace(/\\/g, "/");
153
+ if (normalized.startsWith("/"))
154
+ return true;
155
+ if (/^[A-Za-z]:/.test(normalized))
156
+ return true;
157
+ return normalized.split("/").some((segment) => segment === "..");
158
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@crewhaus/tool-fleet",
3
+ "version": "0.7.0",
4
+ "type": "module",
5
+ "description": "Deterministic fleet operations: register, recompile, version-pin and inspect the harnesses on this machine",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "test": "bun test src"
16
+ },
17
+ "dependencies": {
18
+ "@crewhaus/errors": "0.7.0",
19
+ "@crewhaus/harness-registry": "0.7.0",
20
+ "@crewhaus/harness-supervisor": "0.7.0",
21
+ "@crewhaus/spec": "0.7.0",
22
+ "@crewhaus/tool-builder": "0.7.0",
23
+ "@crewhaus/tool-catalog": "0.7.0",
24
+ "zod": "^3.23.8"
25
+ },
26
+ "devDependencies": {
27
+ "@crewhaus/tool-executor": "workspace:*"
28
+ },
29
+ "license": "Apache-2.0",
30
+ "author": {
31
+ "name": "Max Meier",
32
+ "email": "max@crewhaus.ai",
33
+ "url": "https://crewhaus.ai"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/crewhaus/factory.git",
38
+ "directory": "packages/tool-fleet"
39
+ },
40
+ "homepage": "https://github.com/crewhaus/factory/tree/main/packages/tool-fleet#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/crewhaus/factory/issues"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"]
48
+ }