@crewhaus/tool-state 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,144 @@
1
+ /**
2
+ * Turning caller-supplied identifiers into filenames, safely and reversibly.
3
+ *
4
+ * Two kinds of identifier flow into this package:
5
+ *
6
+ * NAMES — namespaces, streams, topics, counters, checkpoints, indexes.
7
+ * The caller picks them, so they are held to a strict charset and
8
+ * a short length. They round-trip exactly.
9
+ * KEYS — key-value keys, note ids, dedupe ids. These come from the world
10
+ * (a URL, a message id, an order number), so they may contain
11
+ * anything printable and are percent-encoded instead.
12
+ *
13
+ * The encoding only ever emits `[a-z0-9._%~-]`, with LOWERCASE hex digits, so
14
+ * two identifiers that differ only in case never collide into one filename on
15
+ * a case-insensitive filesystem (macOS, Windows) — a bug that would otherwise
16
+ * appear only on someone else's machine. A leading dot is encoded too, so an
17
+ * encoded name is never a hidden file and never `.` or `..`.
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ /** Characters that survive encoding untouched. */
21
+ const UNRESERVED = "abcdefghijklmnopqrstuvwxyz0123456789._-";
22
+ /**
23
+ * Longest encoded filename produced. Beyond it the name is truncated and a
24
+ * digest appended, which keeps every filename inside the 255-byte limit every
25
+ * mainstream filesystem shares. A truncated name cannot be decoded, which is
26
+ * why each record also stores its own key in its contents.
27
+ */
28
+ export const MAX_ENCODED_LENGTH = 200;
29
+ /** Length of the appended digest, in hex characters. */
30
+ const DIGEST_CHARS = 32;
31
+ /**
32
+ * Percent-encode `raw` into a filename-safe segment.
33
+ *
34
+ * Deterministic: the same input always produces the same filename, including
35
+ * the truncated form, whose digest is taken over the whole original.
36
+ */
37
+ export function encodeSegment(raw) {
38
+ const bytes = new TextEncoder().encode(raw);
39
+ let out = "";
40
+ for (let i = 0; i < bytes.length; i += 1) {
41
+ const byte = bytes[i] ?? 0;
42
+ const ch = String.fromCharCode(byte);
43
+ const plain = byte < 0x80 && UNRESERVED.includes(ch) && !(ch === "." && i === 0);
44
+ out += plain ? ch : `%${byte.toString(16).padStart(2, "0")}`;
45
+ }
46
+ if (out.length === 0)
47
+ return "%00";
48
+ if (out.length <= MAX_ENCODED_LENGTH)
49
+ return out;
50
+ const digest = createHash("sha256").update(raw).digest("hex").slice(0, DIGEST_CHARS);
51
+ return `${out.slice(0, MAX_ENCODED_LENGTH - DIGEST_CHARS - 1)}~${digest}`;
52
+ }
53
+ /**
54
+ * Reverse `encodeSegment`, or `undefined` when the segment is a truncated
55
+ * form (it carries a `~`) or is not a well-formed encoding. Callers that may
56
+ * meet a truncated name read the identifier out of the file instead.
57
+ */
58
+ export function decodeSegment(encoded) {
59
+ if (encoded.includes("~"))
60
+ return undefined;
61
+ const bytes = [];
62
+ for (let i = 0; i < encoded.length; i += 1) {
63
+ const ch = encoded[i] ?? "";
64
+ if (ch !== "%") {
65
+ if (!UNRESERVED.includes(ch))
66
+ return undefined;
67
+ bytes.push(ch.charCodeAt(0));
68
+ continue;
69
+ }
70
+ const hex = encoded.slice(i + 1, i + 3);
71
+ if (!/^[0-9a-f]{2}$/.test(hex))
72
+ return undefined;
73
+ bytes.push(Number.parseInt(hex, 16));
74
+ i += 2;
75
+ }
76
+ try {
77
+ return new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(bytes));
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
83
+ /** Longest a NAME may be. Short enough that its encoded form never truncates. */
84
+ export const MAX_NAME_LENGTH = 64;
85
+ /** Longest a KEY may be. Longer keys are refused rather than silently cut. */
86
+ export const MAX_KEY_LENGTH = 512;
87
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
88
+ /**
89
+ * Validate a NAME, returning a readable complaint or `undefined` when it is
90
+ * fine. `label` names the field so the message tells the caller which one.
91
+ */
92
+ export function validateName(label, value) {
93
+ if (value.length === 0)
94
+ return `${label} may not be empty`;
95
+ if (value.length > MAX_NAME_LENGTH) {
96
+ return `${label} is ${value.length} characters, over the ${MAX_NAME_LENGTH} limit`;
97
+ }
98
+ if (!NAME_PATTERN.test(value)) {
99
+ return `${label} "${value}" must start with a letter or digit and contain only letters, digits, '.', '-' and '_'`;
100
+ }
101
+ if (value.includes(".."))
102
+ return `${label} "${value}" may not contain '..'`;
103
+ return undefined;
104
+ }
105
+ /**
106
+ * Control characters: NUL through unit separator, plus DEL.
107
+ *
108
+ * Written with `\u` escapes, NOT with `\x` escapes and not as raw bytes. The
109
+ * formatter rewrites `\x00`-style escapes inside a regex literal into the
110
+ * bytes they denote, and a source file carrying literal control characters is
111
+ * not parsed the same way by every engine — Bun 1.3.11 rejects the resulting
112
+ * class as "range out of order" while 1.3.14 accepts it, so that form shipped
113
+ * green locally and failed in CI. `\u` escapes survive formatting.
114
+ * `apps/cli/src/source-hygiene.test.ts` fails if the raw-byte form returns.
115
+ */
116
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point.
117
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
118
+ /**
119
+ * Validate a KEY. Anything printable is allowed — keys are external ids — but
120
+ * control characters are refused because they would make the record's own
121
+ * JSON, and every log line quoting it, unreadable.
122
+ */
123
+ export function validateKey(label, value, max = MAX_KEY_LENGTH) {
124
+ if (value.length === 0)
125
+ return `${label} may not be empty`;
126
+ if (value.length > max) {
127
+ return `${label} is ${value.length} characters, over the ${max} limit`;
128
+ }
129
+ if (CONTROL_CHARS.test(value))
130
+ return `${label} may not contain control characters`;
131
+ return undefined;
132
+ }
133
+ /**
134
+ * Plain lexicographic comparison by UTF-16 code unit — deliberately NOT
135
+ * `localeCompare`, whose ordering depends on the machine's locale and would
136
+ * make the same listing differ between two runs on two laptops.
137
+ */
138
+ export function compareStrings(a, b) {
139
+ if (a < b)
140
+ return -1;
141
+ if (a > b)
142
+ return 1;
143
+ return 0;
144
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Record semantics: time, expiry, versions and compare-and-set.
3
+ *
4
+ * Nothing here reads the clock. Every tool that needs "now" takes it from the
5
+ * caller, because a tool whose output moves on its own is not deterministic
6
+ * and cannot be replayed, cached or tested. That is also why expiry is
7
+ * evaluated only when the caller supplies `now`: a store that quietly drops a
8
+ * record because a machine's clock drifted is worse than one that says it did
9
+ * not check.
10
+ */
11
+ /** A stored key-value record, exactly as it sits on disk. */
12
+ export type StoredRecord = {
13
+ readonly key: string;
14
+ readonly value: unknown;
15
+ /** Bumped on every write; the token compare-and-set is written against. */
16
+ readonly version: number;
17
+ /** ISO-8601 instant, derived from a caller-supplied `now` plus a TTL. */
18
+ readonly expiresAt?: string;
19
+ /** The caller's `now` at the last write, when one was supplied. */
20
+ readonly updatedAt?: string;
21
+ };
22
+ /** True for a JSON object (not an array, not null). */
23
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
24
+ /**
25
+ * Parse a caller-supplied instant, strictly and INDEPENDENTLY OF THE MACHINE.
26
+ *
27
+ * `Date.parse` accepts a lot of implementation-defined nonsense ("now",
28
+ * "Tuesday"), and two runtimes need not agree on it, so a leading `YYYY-MM-DD`
29
+ * is required before the value is trusted.
30
+ *
31
+ * A date-time with no offset ("2026-01-02T03:04:05") is read as UTC, not as
32
+ * local time. ECMAScript says the opposite — it reads such a value in the
33
+ * machine's own zone — which would make the same `now` produce a different
34
+ * stored timestamp and a different expiry on a laptop in New York than on a
35
+ * runner in UTC, and this package's whole claim is that the same inputs
36
+ * produce the same bytes. The offset is appended before parsing, so an
37
+ * explicit `Z` or `±hh:mm` still wins and is honoured exactly.
38
+ */
39
+ export declare function parseInstant(value: string): number | undefined;
40
+ /** Canonical ISO-8601 rendering, so two spellings of one instant store alike. */
41
+ export declare function formatInstant(ms: number): string;
42
+ /** The expiry instant for a record written at `nowMs` with `ttlSeconds`. */
43
+ export declare function expiryFrom(nowMs: number, ttlSeconds: number): string;
44
+ /**
45
+ * Whether a record has expired.
46
+ *
47
+ * `false` when the question cannot be decided at all — no `expiresAt`, no
48
+ * caller-supplied `now`, or an `expiresAt` that cannot be parsed. Undecidable
49
+ * reads as "not expired" on purpose: the callers pair this with an
50
+ * `expiryChecked` flag, and hiding a record because a timestamp was unreadable
51
+ * would lose data on a guess.
52
+ */
53
+ export declare function isExpired(expiresAt: string | undefined, nowMs: number | undefined): boolean;
54
+ /**
55
+ * Compare-and-set check. `expected` of 0 means "this key must not exist yet".
56
+ * Returns a readable explanation of the conflict, or `undefined` when the
57
+ * write may proceed.
58
+ */
59
+ export declare function casConflict(current: number | undefined, expected: number | undefined): string | undefined;
60
+ /** Byte length of a string's UTF-8 encoding — what a size cap should measure. */
61
+ export declare function byteLength(text: string): number;
62
+ /**
63
+ * Validate a stored record's shape, so a truncated or hand-edited file is
64
+ * reported as corrupt instead of being handed back as a record with holes.
65
+ */
66
+ export declare function isStoredRecord(value: unknown): value is StoredRecord;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Record semantics: time, expiry, versions and compare-and-set.
3
+ *
4
+ * Nothing here reads the clock. Every tool that needs "now" takes it from the
5
+ * caller, because a tool whose output moves on its own is not deterministic
6
+ * and cannot be replayed, cached or tested. That is also why expiry is
7
+ * evaluated only when the caller supplies `now`: a store that quietly drops a
8
+ * record because a machine's clock drifted is worse than one that says it did
9
+ * not check.
10
+ */
11
+ /** True for a JSON object (not an array, not null). */
12
+ export function isPlainObject(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ const INSTANT = /^\d{4}-\d{2}-\d{2}(?:[T ](\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?)(Z|[+-]\d{2}:?\d{2})?)?$/;
16
+ /**
17
+ * Parse a caller-supplied instant, strictly and INDEPENDENTLY OF THE MACHINE.
18
+ *
19
+ * `Date.parse` accepts a lot of implementation-defined nonsense ("now",
20
+ * "Tuesday"), and two runtimes need not agree on it, so a leading `YYYY-MM-DD`
21
+ * is required before the value is trusted.
22
+ *
23
+ * A date-time with no offset ("2026-01-02T03:04:05") is read as UTC, not as
24
+ * local time. ECMAScript says the opposite — it reads such a value in the
25
+ * machine's own zone — which would make the same `now` produce a different
26
+ * stored timestamp and a different expiry on a laptop in New York than on a
27
+ * runner in UTC, and this package's whole claim is that the same inputs
28
+ * produce the same bytes. The offset is appended before parsing, so an
29
+ * explicit `Z` or `±hh:mm` still wins and is honoured exactly.
30
+ */
31
+ export function parseInstant(value) {
32
+ const match = INSTANT.exec(value);
33
+ if (match === null)
34
+ return undefined;
35
+ const time = match[1];
36
+ const zone = match[2];
37
+ const normalized = time === undefined ? value : `${value.replace(" ", "T")}${zone === undefined ? "Z" : ""}`;
38
+ const ms = Date.parse(normalized);
39
+ return Number.isNaN(ms) ? undefined : ms;
40
+ }
41
+ /** Canonical ISO-8601 rendering, so two spellings of one instant store alike. */
42
+ export function formatInstant(ms) {
43
+ return new Date(ms).toISOString();
44
+ }
45
+ /** The expiry instant for a record written at `nowMs` with `ttlSeconds`. */
46
+ export function expiryFrom(nowMs, ttlSeconds) {
47
+ return formatInstant(nowMs + Math.round(ttlSeconds * 1000));
48
+ }
49
+ /**
50
+ * Whether a record has expired.
51
+ *
52
+ * `false` when the question cannot be decided at all — no `expiresAt`, no
53
+ * caller-supplied `now`, or an `expiresAt` that cannot be parsed. Undecidable
54
+ * reads as "not expired" on purpose: the callers pair this with an
55
+ * `expiryChecked` flag, and hiding a record because a timestamp was unreadable
56
+ * would lose data on a guess.
57
+ */
58
+ export function isExpired(expiresAt, nowMs) {
59
+ if (expiresAt === undefined || nowMs === undefined)
60
+ return false;
61
+ const deadline = parseInstant(expiresAt);
62
+ if (deadline === undefined)
63
+ return false;
64
+ return nowMs >= deadline;
65
+ }
66
+ /**
67
+ * Compare-and-set check. `expected` of 0 means "this key must not exist yet".
68
+ * Returns a readable explanation of the conflict, or `undefined` when the
69
+ * write may proceed.
70
+ */
71
+ export function casConflict(current, expected) {
72
+ if (expected === undefined)
73
+ return undefined;
74
+ if (expected === 0) {
75
+ return current === undefined
76
+ ? undefined
77
+ : `expected the key to be absent but it exists at version ${current}`;
78
+ }
79
+ if (current === undefined)
80
+ return `expected version ${expected} but the key does not exist`;
81
+ if (current !== expected)
82
+ return `expected version ${expected} but the current version is ${current}`;
83
+ return undefined;
84
+ }
85
+ /** Byte length of a string's UTF-8 encoding — what a size cap should measure. */
86
+ export function byteLength(text) {
87
+ return Buffer.byteLength(text, "utf8");
88
+ }
89
+ /**
90
+ * Validate a stored record's shape, so a truncated or hand-edited file is
91
+ * reported as corrupt instead of being handed back as a record with holes.
92
+ */
93
+ export function isStoredRecord(value) {
94
+ if (!isPlainObject(value))
95
+ return false;
96
+ if (typeof value["key"] !== "string")
97
+ return false;
98
+ if (typeof value["version"] !== "number" || !Number.isFinite(value["version"]))
99
+ return false;
100
+ if (!("value" in value))
101
+ return false;
102
+ const expires = value["expiresAt"];
103
+ if (expires !== undefined && typeof expires !== "string")
104
+ return false;
105
+ return true;
106
+ }
@@ -0,0 +1,52 @@
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.
16
+ */
17
+ export type SafePath = {
18
+ readonly abs: string;
19
+ readonly real: string;
20
+ /** The path as the caller wrote it, for echoing back in results. */
21
+ readonly given: string;
22
+ /** Slash-separated path relative to the workspace root. */
23
+ readonly rel: string;
24
+ };
25
+ /**
26
+ * Check an already-lexically-contained path beneath an ALREADY-VALIDATED root,
27
+ * and return its real location.
28
+ *
29
+ * This is the second half of containment, and the half a lexical check cannot
30
+ * do: `state/kv/x` may itself be a symlink to `/etc`, in which case the
31
+ * joined path is textually inside the root and the write still lands outside
32
+ * it (CWE-59). Every interior path this package touches goes through here.
33
+ */
34
+ export declare function resolveWithin(toolName: string, rootReal: string, abs: string, label: string): string;
35
+ /** The workspace root, resolved. Every path is contained within it. */
36
+ export declare function workspaceRoot(): string;
37
+ export declare function resolveSafe(toolName: string, rel: string, root?: string): SafePath;
38
+ /** A path relative to the workspace root, with `/` separators on every OS. */
39
+ export declare function toPosix(p: string): string;
40
+ /**
41
+ * True when `candidate` is `parent` or lives underneath it. Both must already
42
+ * be absolute. Used to keep an imported state entry inside the state root.
43
+ */
44
+ export declare function isInside(parent: string, candidate: string): boolean;
45
+ /**
46
+ * Reject an imported entry name that would escape its destination: an
47
+ * absolute path, a Windows drive prefix, a NUL, or any `..`, `.` or empty
48
+ * segment. Backslashes are normalised first, so a Windows-flavoured escape is
49
+ * caught on a POSIX machine too. Checked on the NAME, before anything is
50
+ * written, because afterwards the damage is done.
51
+ */
52
+ export declare function entryNameEscapes(name: string): boolean;
package/dist/paths.js ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Path containment — the gate every caller-supplied path in this package
3
+ * passes through before any syscall touches it.
4
+ *
5
+ * This started as `@crewhaus/tool-fsx`'s gate and refuses everything that one
6
+ * refuses, for the same reason: a lexical check alone is fooled by a symlink
7
+ * that lives inside the workspace and points outside it (CWE-59), so the real
8
+ * path is checked too. The workspace root is `process.cwd()`, matching the
9
+ * other file tools, so a harness that trusts one tool's boundary gets the same
10
+ * boundary here — including for the state directory itself, which a caller may
11
+ * name.
12
+ *
13
+ * Two cases this package's own layout forced, and where it is stricter:
14
+ *
15
+ * - a DANGLING symlink is refused rather than treated as a free name. It
16
+ * "does not exist" to `existsSync`, and `open(…, "a")` would then follow
17
+ * it and create the file it points at, outside the workspace.
18
+ * - an INTERIOR path is re-checked against its real location
19
+ * (`resolveWithin`). Approving `stateDir` says nothing about `kv/cache`
20
+ * inside it, and a symlink there is the escape that actually works.
21
+ */
22
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
23
+ import * as path from "node:path";
24
+ import { CrewhausError } from "@crewhaus/errors";
25
+ /** Raised when a caller-supplied path resolves outside the workspace root. */
26
+ export class ToolPermissionError extends CrewhausError {
27
+ name = "ToolPermissionError";
28
+ toolName;
29
+ path;
30
+ constructor(toolName, attemptedPath) {
31
+ super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
32
+ this.toolName = toolName;
33
+ this.path = attemptedPath;
34
+ }
35
+ }
36
+ /**
37
+ * Does a name exist on disk, WITHOUT following a final symlink?
38
+ *
39
+ * `existsSync` follows, so it answers "no" for a dangling symlink — and a
40
+ * caller that treats that as "a leaf I may create" then opens the link and
41
+ * writes through it to wherever it points. `lstat` answers about the link
42
+ * itself, which is what a containment check has to reason about.
43
+ */
44
+ function existsNoFollow(abs) {
45
+ try {
46
+ lstatSync(abs);
47
+ return true;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ /**
54
+ * The real path of `abs`, refused unless it lands inside `rootReal`.
55
+ *
56
+ * Shared by `resolveSafe` (root against the workspace) and `resolveWithin`
57
+ * (an interior path against the state root). The deepest EXISTING ancestor is
58
+ * realpath'd and the missing tail re-appended, so a leaf that does not exist
59
+ * yet is allowed — but a DANGLING symlink is not: `lstat` sees the link, so
60
+ * `realpathSync` is asked about it and fails, and the failure is a refusal.
61
+ */
62
+ function realWithin(toolName, rootReal, abs, label) {
63
+ try {
64
+ const real = resolveLocation(abs);
65
+ if (real !== rootReal && !real.startsWith(`${rootReal}${path.sep}`)) {
66
+ throw new ToolPermissionError(toolName, label);
67
+ }
68
+ return real;
69
+ }
70
+ catch (err) {
71
+ if (err instanceof ToolPermissionError)
72
+ throw err;
73
+ throw new ToolPermissionError(toolName, label);
74
+ }
75
+ }
76
+ /**
77
+ * Check an already-lexically-contained path beneath an ALREADY-VALIDATED root,
78
+ * and return its real location.
79
+ *
80
+ * This is the second half of containment, and the half a lexical check cannot
81
+ * do: `state/kv/x` may itself be a symlink to `/etc`, in which case the
82
+ * joined path is textually inside the root and the write still lands outside
83
+ * it (CWE-59). Every interior path this package touches goes through here.
84
+ */
85
+ export function resolveWithin(toolName, rootReal, abs, label) {
86
+ return realWithin(toolName, path.resolve(rootReal), abs, label);
87
+ }
88
+ /** The workspace root, resolved. Every path is contained within it. */
89
+ export function workspaceRoot() {
90
+ return path.resolve(process.cwd());
91
+ }
92
+ /**
93
+ * Resolve `rel` inside the workspace, or throw `ToolPermissionError`.
94
+ *
95
+ * The leaf is allowed not to exist — every tool here that creates something
96
+ * needs to validate a destination before it is made — so the deepest
97
+ * EXISTING ancestor is realpath'd and the missing tail re-appended. Any
98
+ * failure other than that walk fails closed.
99
+ */
100
+ /**
101
+ * Where `target` would actually land, with every symlink on the way already
102
+ * followed — including one whose own target does not exist yet.
103
+ *
104
+ * `realpathSync` gives up with ENOENT on a dangling link. Treating that as a
105
+ * failure would refuse a perfectly ordinary link to a file this harness is
106
+ * about to create, so the dangling hop is followed by hand instead and the
107
+ * result re-checked for containment.
108
+ */
109
+ function resolveLocation(target, depth = 0) {
110
+ if (depth > 40)
111
+ throw new Error(`symlink chain at "${target}" is too long to resolve`);
112
+ let probe = target;
113
+ const tail = [];
114
+ while (!existsNoFollow(probe)) {
115
+ tail.unshift(path.basename(probe));
116
+ const parent = path.dirname(probe);
117
+ if (parent === probe)
118
+ break; // reached the filesystem root
119
+ probe = parent;
120
+ }
121
+ let probeReal;
122
+ try {
123
+ probeReal = realpathSync(probe);
124
+ }
125
+ catch (err) {
126
+ if (err.code !== "ENOENT")
127
+ throw err;
128
+ // The name is there but `realpath` cannot finish it: a symlink with a
129
+ // missing target. `readlinkSync` throws EINVAL on anything else, which
130
+ // fails closed.
131
+ const link = readlinkSync(probe);
132
+ // A RELATIVE target resolves against the directory that actually CONTAINS
133
+ // the link, which is not the link's lexical parent when that parent is
134
+ // itself reached through a symlink. `<root>/dirlink/x -> ../y` with
135
+ // `dirlink` pointing out of the root really lands at `<elsewhere>/y`, but
136
+ // measured from the lexical parent it reads as `<root>/y` — an in-root
137
+ // path the caller's path does not lead to. So the parent is made real
138
+ // first. An absolute target ignores the base.
139
+ const base = realpathSync(path.dirname(probe));
140
+ probeReal = resolveLocation(path.resolve(base, link), depth + 1);
141
+ }
142
+ return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
143
+ }
144
+ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
145
+ const rootResolved = path.resolve(root);
146
+ const abs = path.resolve(rootResolved, rel);
147
+ // 1) Lexical containment — rejects `..` and absolute escapes. The trailing
148
+ // separator avoids the `/root` vs `/root-sibling` prefix pitfall.
149
+ if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
150
+ throw new ToolPermissionError(toolName, rel);
151
+ }
152
+ // 2) Symlink-aware containment. The real path must land inside the real
153
+ // root, so an in-workspace symlink pointing at /etc is refused here.
154
+ let rootReal;
155
+ try {
156
+ rootReal = realpathSync(rootResolved);
157
+ }
158
+ catch {
159
+ throw new ToolPermissionError(toolName, rel);
160
+ }
161
+ const real = realWithin(toolName, rootReal, abs, rel);
162
+ return {
163
+ abs,
164
+ real,
165
+ given: rel,
166
+ rel: toPosix(path.relative(rootResolved, abs)),
167
+ };
168
+ }
169
+ /** A path relative to the workspace root, with `/` separators on every OS. */
170
+ export function toPosix(p) {
171
+ return path.sep === "/" ? p : p.split(path.sep).join("/");
172
+ }
173
+ /**
174
+ * True when `candidate` is `parent` or lives underneath it. Both must already
175
+ * be absolute. Used to keep an imported state entry inside the state root.
176
+ */
177
+ export function isInside(parent, candidate) {
178
+ const p = path.resolve(parent);
179
+ const c = path.resolve(candidate);
180
+ return c === p || c.startsWith(`${p}${path.sep}`);
181
+ }
182
+ /**
183
+ * Reject an imported entry name that would escape its destination: an
184
+ * absolute path, a Windows drive prefix, a NUL, or any `..`, `.` or empty
185
+ * segment. Backslashes are normalised first, so a Windows-flavoured escape is
186
+ * caught on a POSIX machine too. Checked on the NAME, before anything is
187
+ * written, because afterwards the damage is done.
188
+ */
189
+ export function entryNameEscapes(name) {
190
+ const normalized = name.replace(/\\/g, "/");
191
+ if (normalized.length === 0)
192
+ return true;
193
+ if (normalized.startsWith("/"))
194
+ return true;
195
+ if (/^[A-Za-z]:/.test(normalized))
196
+ return true;
197
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: a NUL truncates a path at the syscall boundary, so it may never reach one.
198
+ if (/[\u0000]/.test(normalized))
199
+ return true;
200
+ return normalized
201
+ .split("/")
202
+ .some((segment) => segment === ".." || segment === "." || segment === "");
203
+ }