@mulmoclaude/core 7.0.0 → 7.2.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 (58) hide show
  1. package/dist/collection/registry/server/index.cjs +6 -5
  2. package/dist/collection/registry/server/index.cjs.map +1 -1
  3. package/dist/collection/registry/server/index.js +6 -5
  4. package/dist/collection/registry/server/index.js.map +1 -1
  5. package/dist/collection/server/index.cjs +2 -2
  6. package/dist/collection/server/index.js +2 -2
  7. package/dist/collection-watchers/index.cjs +2 -2
  8. package/dist/collection-watchers/index.js +2 -2
  9. package/dist/containment-D_vAa6eT.js +40 -0
  10. package/dist/containment-D_vAa6eT.js.map +1 -0
  11. package/dist/containment-Dc3gO4wD.cjs +65 -0
  12. package/dist/containment-Dc3gO4wD.cjs.map +1 -0
  13. package/dist/{discovery-DR4GNqrp.js → discovery-BIQY56d1.js} +4 -4
  14. package/dist/discovery-BIQY56d1.js.map +1 -0
  15. package/dist/{discovery-BkCeYBf6.cjs → discovery-D3e3JaAv.cjs} +4 -4
  16. package/dist/discovery-D3e3JaAv.cjs.map +1 -0
  17. package/dist/feeds/server/index.cjs +2 -2
  18. package/dist/feeds/server/index.js +2 -2
  19. package/dist/files/containment.d.ts +9 -0
  20. package/dist/files/index.cjs +38 -8
  21. package/dist/files/index.cjs.map +1 -1
  22. package/dist/files/index.d.ts +2 -0
  23. package/dist/files/index.js +30 -5
  24. package/dist/files/index.js.map +1 -1
  25. package/dist/files/withinRoot.d.ts +5 -0
  26. package/dist/google/index.cjs +1 -1
  27. package/dist/google/index.js +1 -1
  28. package/dist/{server-CnCUBmSn.cjs → server-BGxmZppB.cjs} +4 -3
  29. package/dist/server-BGxmZppB.cjs.map +1 -0
  30. package/dist/{server-Dp5KWarO.js → server-MKJPGYKI.js} +4 -3
  31. package/dist/server-MKJPGYKI.js.map +1 -0
  32. package/dist/whisper/extra-args.d.ts +14 -0
  33. package/dist/whisper/index.cjs +76 -8
  34. package/dist/whisper/index.cjs.map +1 -1
  35. package/dist/whisper/index.js +76 -8
  36. package/dist/whisper/index.js.map +1 -1
  37. package/dist/whisper/sidecar-helpers.d.ts +3 -2
  38. package/dist/whisper/sidecar.d.ts +2 -2
  39. package/dist/wiki/server/fs.d.ts +0 -7
  40. package/dist/wiki/server/index.cjs +7 -59
  41. package/dist/wiki/server/index.cjs.map +1 -1
  42. package/dist/wiki/server/index.js +8 -60
  43. package/dist/wiki/server/index.js.map +1 -1
  44. package/dist/withinRoot-CHPN9eHD.cjs +53 -0
  45. package/dist/withinRoot-CHPN9eHD.cjs.map +1 -0
  46. package/dist/withinRoot-CheaBWt0.js +42 -0
  47. package/dist/withinRoot-CheaBWt0.js.map +1 -0
  48. package/dist/workspace-setup/index.js +36 -2
  49. package/dist/workspace-setup/index.js.map +1 -1
  50. package/package.json +1 -1
  51. package/dist/discovery-BkCeYBf6.cjs.map +0 -1
  52. package/dist/discovery-DR4GNqrp.js.map +0 -1
  53. package/dist/safe-D79sHxq1.cjs +0 -43
  54. package/dist/safe-D79sHxq1.cjs.map +0 -1
  55. package/dist/safe-DRNa8UBp.js +0 -30
  56. package/dist/safe-DRNa8UBp.js.map +0 -1
  57. package/dist/server-CnCUBmSn.cjs.map +0 -1
  58. package/dist/server-Dp5KWarO.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../../rolldown-runtime-CmQyd0Gu.cjs");
3
- const require_server = require("../../server-CnCUBmSn.cjs");
4
- const require_discovery = require("../../discovery-BkCeYBf6.cjs");
3
+ const require_server = require("../../server-BGxmZppB.cjs");
4
+ const require_discovery = require("../../discovery-D3e3JaAv.cjs");
5
5
  const require_feeds_paths = require("../paths.cjs");
6
6
  const require_itemId = require("../../itemId-D2XAQ8RU.cjs");
7
7
  const require_project = require("../../project-DDTIVEMU.cjs");
@@ -1,5 +1,5 @@
1
- import { F as buildCollectionActionSeedPrompt, I as promptPathsFor, z as readSkillTemplate } from "../../server-Dp5KWarO.js";
2
- import { W as resolveDataDir, _t as createForwardingLogger, d as storeFor, k as listItems, n as discoverCollections, q as safeSlugName, vt as createHostSlot } from "../../discovery-DR4GNqrp.js";
1
+ import { F as buildCollectionActionSeedPrompt, I as promptPathsFor, z as readSkillTemplate } from "../../server-MKJPGYKI.js";
2
+ import { W as resolveDataDir, _t as createForwardingLogger, d as storeFor, k as listItems, n as discoverCollections, q as safeSlugName, vt as createHostSlot } from "../../discovery-BIQY56d1.js";
3
3
  import { FEEDS_DIR, feedDir, feedStatePath, feedsRoot, ingestStateDir, ingestStatePath } from "../paths.js";
4
4
  import { J as INGEST_KINDS, q as FEED_SCHEDULES } from "../../itemId-D_pSpa3U.js";
5
5
  import { t as mergeIntoExisting } from "../../project-mU6-xLfy.js";
@@ -0,0 +1,9 @@
1
+ export declare function isWithinRoot(rootReal: string, candidateReal: string, separator?: string): boolean;
2
+ export declare function realpathSyncOrNull(absPath: string): string | null;
3
+ /** `candidateReal` re-spelled under `rootReal` when both, at their on-disk spelling, are one inside the other; null
4
+ * otherwise. The second look for a check that compared two realpaths taken with different letter case (a JS realpath
5
+ * keeps the case it was given, or a link's), so a target truly inside is not refused. */
6
+ export declare function respelledWithinRoot(rootReal: string, candidateReal: string): string | null;
7
+ /** True when `candidateReal` is inside `rootReal`: the case-preserving test, then the second look at the on-disk spelling
8
+ * for two realpaths taken with different letter case. The check every caller uses. */
9
+ export declare function isInsideRoot(rootReal: string, candidateReal: string): boolean;
@@ -1,7 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
3
  const require_root = require("../root-9lRFeXbm.cjs");
4
- const require_safe = require("../safe-D79sHxq1.cjs");
4
+ const require_containment = require("../containment-Dc3gO4wD.cjs");
5
+ const require_withinRoot = require("../withinRoot-CHPN9eHD.cjs");
5
6
  const require_relPath = require("../relPath-CZiP2S_a.cjs");
6
7
  const require_artifacts_paths = require("../artifacts/paths.cjs");
7
8
  let node_fs = require("node:fs");
@@ -16,6 +17,30 @@ var JSON_INDENT = 2;
16
17
  async function writeJsonAtomic(filePath, data, opts = {}) {
17
18
  await require_root.writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);
18
19
  }
20
+ // src/files/safe.ts
21
+ /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
22
+ * missing file as an empty/default result instead of a thrown error. */
23
+ function isEnoent(err) {
24
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
25
+ }
26
+ /** Realpath-based read-time containment: resolve `relPath` against the root's
27
+ * realpath and require the target's realpath to stay inside it. Returns null
28
+ * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already
29
+ * be a realpath. The one implementation for host and plugins (#2461) — this
30
+ * security-critical primitive must not drift per consumer. */
31
+ function resolveWithinRoot(rootReal, relPath) {
32
+ const normalized = node_path.default.normalize(relPath || "");
33
+ const resolvedReal = realpathOrNull(node_path.default.resolve(rootReal, normalized));
34
+ if (resolvedReal === null) return null;
35
+ return require_containment.isWithinRoot(rootReal, resolvedReal) ? resolvedReal : require_containment.respelledWithinRoot(rootReal, resolvedReal);
36
+ }
37
+ function realpathOrNull(absPath) {
38
+ try {
39
+ return (0, node_fs.realpathSync)(absPath);
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
19
44
  // src/files/verified.ts
20
45
  var READ_FLAGS = node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0) | (node_fs.constants.O_NONBLOCK ?? 0);
21
46
  var CREATE_FLAGS = node_fs.constants.O_WRONLY | node_fs.constants.O_CREAT | node_fs.constants.O_EXCL | (node_fs.constants.O_NOFOLLOW ?? 0);
@@ -25,22 +50,22 @@ async function realpathIfPresent(absPath) {
25
50
  try {
26
51
  return await node_fs.promises.realpath(absPath);
27
52
  } catch (err) {
28
- if (require_safe.isEnoent(err)) return null;
53
+ if (isEnoent(err)) return null;
29
54
  throw err;
30
55
  }
31
56
  }
32
- var isWithin = (rootReal, candidateReal) => candidateReal === rootReal || candidateReal.startsWith(rootReal + node_path.default.sep);
33
57
  /** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */
34
58
  async function resolveExistingWithinRoot(rootReal, relative) {
35
59
  const candidateReal = await realpathIfPresent(node_path.default.resolve(rootReal, relative));
36
- return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;
60
+ if (candidateReal === null) return null;
61
+ return require_containment.isInsideRoot(rootReal, candidateReal) ? candidateReal : null;
37
62
  }
38
63
  var sameFile = (onDisk, opened) => onDisk.dev === opened.dev && onDisk.ino === opened.ino;
39
64
  async function lstatIfPresent(absPath) {
40
65
  try {
41
66
  return await node_fs.promises.lstat(absPath, { bigint: true });
42
67
  } catch (err) {
43
- if (require_safe.isEnoent(err)) return null;
68
+ if (isEnoent(err)) return null;
44
69
  throw err;
45
70
  }
46
71
  }
@@ -48,7 +73,7 @@ async function openIfPresent(absPath, flags) {
48
73
  try {
49
74
  return await node_fs.promises.open(absPath, flags);
50
75
  } catch (err) {
51
- if (require_safe.isEnoent(err)) return null;
76
+ if (isEnoent(err)) return null;
52
77
  throw err;
53
78
  }
54
79
  }
@@ -266,14 +291,19 @@ exports.canonicalRoot = require_root.canonicalRoot;
266
291
  exports.createByPathFileOps = createByPathFileOps;
267
292
  exports.createFileVerifiedInScope = createFileVerifiedInScope;
268
293
  exports.existsAsFile = existsAsFile;
269
- exports.isEnoent = require_safe.isEnoent;
294
+ exports.isEnoent = isEnoent;
295
+ exports.isInsideRoot = require_containment.isInsideRoot;
296
+ exports.isWithinRoot = require_containment.isWithinRoot;
270
297
  exports.joinPosixRelPath = require_relPath.joinPosixRelPath;
271
298
  exports.openVerifiedWithinScope = openVerifiedWithinScope;
299
+ exports.readTextWithinRoot = require_withinRoot.readTextWithinRoot;
300
+ exports.readTextWithinRootSync = require_withinRoot.readTextWithinRootSync;
272
301
  exports.realpathIfPresent = realpathIfPresent;
302
+ exports.realpathSyncOrNull = require_containment.realpathSyncOrNull;
273
303
  exports.resolveByPath = resolveByPath;
274
304
  exports.resolveExistingWithinRoot = resolveExistingWithinRoot;
275
305
  exports.resolveHtmlFileRequestPath = resolveHtmlFileRequestPath;
276
- exports.resolveWithinRoot = require_safe.resolveWithinRoot;
306
+ exports.resolveWithinRoot = resolveWithinRoot;
277
307
  exports.scopeRealpath = scopeRealpath;
278
308
  exports.toPosixRelPath = require_relPath.toPosixRelPath;
279
309
  exports.writeFileAtomic = require_root.writeFileAtomic;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["writeFileAtomic","constants","promises","isEnoent","path","randomBytes","renameWithWindowsRetry","classifyFilePath","path","realpath","fsStat","readFile","writeFileAtomic","path"],"sources":["../../src/files/json.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","// Containment that survives a path swapped between the check and the use (#3573). Node fs has no\n// openat, so a read opens first and then proves the handle is the in-root file, and a write\n// verifies its staging file before renaming within that same directory. See\n// plans/fix-3573-verified-open.md for what is closed and what stays best-effort.\n\nimport { constants, promises, type BigIntStats } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { renameWithWindowsRetry } from \"./atomic.js\";\nimport { isEnoent } from \"./safe.js\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nconst isWithin = (rootReal: string, candidateReal: string): boolean => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAMA,aAAAA,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;ACKA,IAAM,aAAaC,QAAAA,UAAU,YAAYA,QAAAA,UAAU,cAAc,MAAMA,QAAAA,UAAU,cAAc;AAC/F,IAAM,eAAeA,QAAAA,UAAU,WAAWA,QAAAA,UAAU,UAAUA,QAAAA,UAAU,UAAUA,QAAAA,UAAU,cAAc;AAC1G,IAAM,uBAAuB;;AAU7B,eAAsB,kBAAkB,SAAyC;CAC/E,IAAI;EACF,OAAO,MAAMC,QAAAA,SAAS,SAAS,OAAO;CACxC,SAAS,KAAK;EACZ,IAAIC,aAAAA,SAAS,GAAG,GAAG,OAAO;EAC1B,MAAM;CACR;AACF;AAEA,IAAM,YAAY,UAAkB,kBAAmC,kBAAkB,YAAY,cAAc,WAAW,WAAWC,UAAAA,QAAK,GAAG;;AAGjJ,eAAsB,0BAA0B,UAAkB,UAA0C;CAC1G,MAAM,gBAAgB,MAAM,kBAAkBA,UAAAA,QAAK,QAAQ,UAAU,QAAQ,CAAC;CAC9E,OAAO,kBAAkB,QAAQ,SAAS,UAAU,aAAa,IAAI,gBAAgB;AACvF;AAEA,IAAM,YAAY,QAAqB,WAAiC,OAAO,QAAQ,OAAO,OAAO,OAAO,QAAQ,OAAO;AAE3H,eAAe,eAAe,SAA8C;CAC1E,IAAI;EACF,OAAO,MAAMF,QAAAA,SAAS,MAAM,SAAS,EAAE,QAAQ,KAAK,CAAC;CACvD,SAAS,KAAK;EACZ,IAAIC,aAAAA,SAAS,GAAG,GAAG,OAAO;EAC1B,MAAM;CACR;AACF;AAEA,eAAe,cAAc,SAAiB,OAA2C;CACvF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0B,OAAO;CACtF,MAAM,CAAC,aAAa;CACpB,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,KAAK,MAAM,YAAY,YAAY,MAAM,YAAY,OAAO,YAAY,QAAQ,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,GACnI,OAAO;CAET,IAAI,UAAU,2BAA2B,OAAOG,UAAAA,QAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAOA,UAAAA,QAAK,WAAW,SAAS,IAAIA,UAAAA,QAAK,QAAQ,SAAS,IAAI;AAChE"}
1
+ {"version":3,"file":"index.cjs","names":["writeFileAtomic","path","isWithinRoot","respelledWithinRoot","realpathSync","constants","promises","path","isInsideRoot","randomBytes","renameWithWindowsRetry","classifyFilePath","path","realpath","fsStat","readFile","writeFileAtomic","path"],"sources":["../../src/files/json.ts","../../src/files/safe.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { isWithinRoot, respelledWithinRoot } from \"./containment.js\";\n\n/** True for a `not found` filesystem error (ENOENT) — lets callers treat a\n * missing file as an empty/default result instead of a thrown error. */\nexport function isEnoent(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\";\n}\n\n/** Realpath-based read-time containment: resolve `relPath` against the root's\n * realpath and require the target's realpath to stay inside it. Returns null\n * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already\n * be a realpath. The one implementation for host and plugins (#2461) — this\n * security-critical primitive must not drift per consumer. */\nexport function resolveWithinRoot(rootReal: string, relPath: string): string | null {\n const normalized = path.normalize(relPath || \"\");\n const resolved = path.resolve(rootReal, normalized);\n const resolvedReal = realpathOrNull(resolved);\n if (resolvedReal === null) return null;\n return isWithinRoot(rootReal, resolvedReal) ? resolvedReal : respelledWithinRoot(rootReal, resolvedReal);\n}\n\nfunction realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n","// Containment that survives a path swapped between the check and the use (#3573). Node fs has no\n// openat, so a read opens first and then proves the handle is the in-root file, and a write\n// verifies its staging file before renaming within that same directory. See\n// plans/fix-3573-verified-open.md for what is closed and what stays best-effort.\n\nimport { constants, promises, type BigIntStats } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { renameWithWindowsRetry } from \"./atomic.js\";\nimport { isEnoent } from \"./safe.js\";\nimport { isInsideRoot } from \"./containment.js\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n if (candidateReal === null) return null;\n return isInsideRoot(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAMA,aAAAA,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;ACFA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAaC,UAAAA,QAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eAD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AAI,KAAK,MAAM,YAAY,YAAY,MAAM,YAAY,OAAO,YAAY,QAAQ,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,GACnI,OAAO;CAET,IAAI,UAAU,2BAA2B,OAAOG,UAAAA,QAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAOA,UAAAA,QAAK,WAAW,SAAS,IAAIA,UAAAA,QAAK,QAAQ,SAAS,IAAI;AAChE"}
@@ -2,6 +2,8 @@ export { writeFileAtomic, writeFileAtomicSync, type WriteAtomicOptions } from '.
2
2
  export { writeJsonAtomic } from './json.js';
3
3
  export { isEnoent, resolveWithinRoot } from './safe.js';
4
4
  export { openVerifiedWithinScope, writeFileVerifiedInScope, createFileVerifiedInScope, scopeRealpath, resolveExistingWithinRoot, realpathIfPresent, type VerifiedScope, type VerifiedFileHooks, } from './verified.js';
5
+ export { isInsideRoot, isWithinRoot, realpathSyncOrNull } from './containment.js';
6
+ export { readTextWithinRoot, readTextWithinRootSync } from './withinRoot.js';
5
7
  export { toPosixRelPath, joinPosixRelPath } from './relPath.js';
6
8
  export { canonicalRoot } from './root.js';
7
9
  export { resolveByPath, existsAsFile, createByPathFileOps, MARKDOWN_EXTENSIONS, HTML_EXTENSIONS, type ByPathFileOps, type ByPathOptions } from './byPath.js';
@@ -1,8 +1,9 @@
1
1
  import { i as writeFileAtomicSync, n as renameWithWindowsRetry, r as writeFileAtomic, t as canonicalRoot } from "../root-CqxPNSyK.js";
2
- import { n as resolveWithinRoot, t as isEnoent } from "../safe-DRNa8UBp.js";
2
+ import { i as respelledWithinRoot, n as isWithinRoot, r as realpathSyncOrNull, t as isInsideRoot } from "../containment-D_vAa6eT.js";
3
+ import { n as readTextWithinRootSync, t as readTextWithinRoot } from "../withinRoot-CheaBWt0.js";
3
4
  import { n as toPosixRelPath, t as joinPosixRelPath } from "../relPath-BkKmqiiF.js";
4
5
  import { classifyFilePath } from "../artifacts/paths.js";
5
- import { constants, promises } from "node:fs";
6
+ import { constants, promises, realpathSync } from "node:fs";
6
7
  import path from "node:path";
7
8
  import { randomBytes } from "node:crypto";
8
9
  import { readFile, realpath, stat } from "node:fs/promises";
@@ -13,6 +14,30 @@ var JSON_INDENT = 2;
13
14
  async function writeJsonAtomic(filePath, data, opts = {}) {
14
15
  await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);
15
16
  }
17
+ // src/files/safe.ts
18
+ /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
19
+ * missing file as an empty/default result instead of a thrown error. */
20
+ function isEnoent(err) {
21
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
22
+ }
23
+ /** Realpath-based read-time containment: resolve `relPath` against the root's
24
+ * realpath and require the target's realpath to stay inside it. Returns null
25
+ * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already
26
+ * be a realpath. The one implementation for host and plugins (#2461) — this
27
+ * security-critical primitive must not drift per consumer. */
28
+ function resolveWithinRoot(rootReal, relPath) {
29
+ const normalized = path.normalize(relPath || "");
30
+ const resolvedReal = realpathOrNull(path.resolve(rootReal, normalized));
31
+ if (resolvedReal === null) return null;
32
+ return isWithinRoot(rootReal, resolvedReal) ? resolvedReal : respelledWithinRoot(rootReal, resolvedReal);
33
+ }
34
+ function realpathOrNull(absPath) {
35
+ try {
36
+ return realpathSync(absPath);
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
16
41
  // src/files/verified.ts
17
42
  var READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
18
43
  var CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);
@@ -26,11 +51,11 @@ async function realpathIfPresent(absPath) {
26
51
  throw err;
27
52
  }
28
53
  }
29
- var isWithin = (rootReal, candidateReal) => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);
30
54
  /** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */
31
55
  async function resolveExistingWithinRoot(rootReal, relative) {
32
56
  const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));
33
- return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;
57
+ if (candidateReal === null) return null;
58
+ return isInsideRoot(rootReal, candidateReal) ? candidateReal : null;
34
59
  }
35
60
  var sameFile = (onDisk, opened) => onDisk.dev === opened.dev && onDisk.ino === opened.ino;
36
61
  async function lstatIfPresent(absPath) {
@@ -257,6 +282,6 @@ function resolveHtmlFileRequestPath(workspaceRoot, reqPath) {
257
282
  const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join("/") : `/${rest.join("/")}`;
258
283
  return path.isAbsolute(candidate) ? path.resolve(candidate) : null;
259
284
  }
260
- export { HTML_EXTENSIONS, MARKDOWN_EXTENSIONS, canonicalRoot, createByPathFileOps, createFileVerifiedInScope, existsAsFile, isEnoent, joinPosixRelPath, openVerifiedWithinScope, realpathIfPresent, resolveByPath, resolveExistingWithinRoot, resolveHtmlFileRequestPath, resolveWithinRoot, scopeRealpath, toPosixRelPath, writeFileAtomic, writeFileAtomicSync, writeFileVerifiedInScope, writeJsonAtomic };
285
+ export { HTML_EXTENSIONS, MARKDOWN_EXTENSIONS, canonicalRoot, createByPathFileOps, createFileVerifiedInScope, existsAsFile, isEnoent, isInsideRoot, isWithinRoot, joinPosixRelPath, openVerifiedWithinScope, readTextWithinRoot, readTextWithinRootSync, realpathIfPresent, realpathSyncOrNull, resolveByPath, resolveExistingWithinRoot, resolveHtmlFileRequestPath, resolveWithinRoot, scopeRealpath, toPosixRelPath, writeFileAtomic, writeFileAtomicSync, writeFileVerifiedInScope, writeJsonAtomic };
261
286
 
262
287
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fsStat"],"sources":["../../src/files/json.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","// Containment that survives a path swapped between the check and the use (#3573). Node fs has no\n// openat, so a read opens first and then proves the handle is the in-root file, and a write\n// verifies its staging file before renaming within that same directory. See\n// plans/fix-3573-verified-open.md for what is closed and what stays best-effort.\n\nimport { constants, promises, type BigIntStats } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { renameWithWindowsRetry } from \"./atomic.js\";\nimport { isEnoent } from \"./safe.js\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nconst isWithin = (rootReal: string, candidateReal: string): boolean => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAM,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;ACKA,IAAM,aAAa,UAAU,YAAY,UAAU,cAAc,MAAM,UAAU,cAAc;AAC/F,IAAM,eAAe,UAAU,WAAW,UAAU,UAAU,UAAU,UAAU,UAAU,cAAc;AAC1G,IAAM,uBAAuB;;AAU7B,eAAsB,kBAAkB,SAAyC;CAC/E,IAAI;EACF,OAAO,MAAM,SAAS,SAAS,OAAO;CACxC,SAAS,KAA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;EAEN,OAAO;CACT;CAMA,OAAO,QAAQ,MAAM,YAAY,QAAQ,SAAS,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,IAAI,OAAO;AAC7F;;;;AAKA,SAAgB,2BAA2B,eAAuB,SAAgC;CAChG,MAAM,UAAU,eAAe,OAAO;CACtC,IAAI,YAAY,QAAQ,QAAQ,SAAS,GAAG,OAAO;CACnD,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,IAAI,UAAU,6BAA6B,UAAU,0BAA0B,OAAO;CACtF,MAAM,CAAC,aAAa;CACpB,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,KAAK,MAAM,YAAY,YAAY,MAAM,YAAY,OAAO,YAAY,QAAQ,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,GACnI,OAAO;CAET,IAAI,UAAU,2BAA2B,OAAO,KAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAO,KAAK,WAAW,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI;AAChE"}
1
+ {"version":3,"file":"index.js","names":["fsStat"],"sources":["../../src/files/json.ts","../../src/files/safe.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { isWithinRoot, respelledWithinRoot } from \"./containment.js\";\n\n/** True for a `not found` filesystem error (ENOENT) — lets callers treat a\n * missing file as an empty/default result instead of a thrown error. */\nexport function isEnoent(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\";\n}\n\n/** Realpath-based read-time containment: resolve `relPath` against the root's\n * realpath and require the target's realpath to stay inside it. Returns null\n * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already\n * be a realpath. The one implementation for host and plugins (#2461) — this\n * security-critical primitive must not drift per consumer. */\nexport function resolveWithinRoot(rootReal: string, relPath: string): string | null {\n const normalized = path.normalize(relPath || \"\");\n const resolved = path.resolve(rootReal, normalized);\n const resolvedReal = realpathOrNull(resolved);\n if (resolvedReal === null) return null;\n return isWithinRoot(rootReal, resolvedReal) ? resolvedReal : respelledWithinRoot(rootReal, resolvedReal);\n}\n\nfunction realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n","// Containment that survives a path swapped between the check and the use (#3573). Node fs has no\n// openat, so a read opens first and then proves the handle is the in-root file, and a write\n// verifies its staging file before renaming within that same directory. See\n// plans/fix-3573-verified-open.md for what is closed and what stays best-effort.\n\nimport { constants, promises, type BigIntStats } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { renameWithWindowsRetry } from \"./atomic.js\";\nimport { isEnoent } from \"./safe.js\";\nimport { isInsideRoot } from \"./containment.js\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n if (candidateReal === null) return null;\n return isInsideRoot(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAM,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;ACFA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QA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;CAI5F,OAAO,KAAK,WAAW,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI;AAChE"}
@@ -0,0 +1,5 @@
1
+ /** Text of a regular file inside `rootReal` (a realpath), or null when it is missing, leads outside, is a FIFO or
2
+ * other non-file, or is unreadable. */
3
+ export declare function readTextWithinRoot(rootReal: string, absPath: string): Promise<string | null>;
4
+ /** Sync twin of `readTextWithinRoot`. */
5
+ export declare function readTextWithinRootSync(rootReal: string, absPath: string): string | null;
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
- const require_discovery = require("../discovery-BkCeYBf6.cjs");
3
+ const require_discovery = require("../discovery-D3e3JaAv.cjs");
4
4
  require("../errors-B9mCEVG9.cjs");
5
5
  const require_itemId = require("../itemId-D2XAQ8RU.cjs");
6
6
  const require_text = require("../text-BQiyo5R9.cjs");
@@ -1,4 +1,4 @@
1
- import { _t as createForwardingLogger, d as storeFor, n as discoverCollections, rt as getWorkspaceRoot, vt as createHostSlot } from "../discovery-DR4GNqrp.js";
1
+ import { _t as createForwardingLogger, d as storeFor, n as discoverCollections, rt as getWorkspaceRoot, vt as createHostSlot } from "../discovery-BIQY56d1.js";
2
2
  import "../errors-0QwjDxsv.js";
3
3
  import { f as parseIsoDate, p as parseIsoDateTime } from "../itemId-D_pSpa3U.js";
4
4
  import { t as truncate } from "../text-BQAuwKVj.js";
@@ -1,10 +1,11 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
2
- const require_discovery = require("./discovery-BkCeYBf6.cjs");
2
+ const require_discovery = require("./discovery-D3e3JaAv.cjs");
3
3
  const require_relPath = require("./relPath-CZiP2S_a.cjs");
4
4
  const require_dist = require("./dist-734JaRYi.cjs");
5
5
  const require_promptSafety = require("./promptSafety-CjxafW2b.cjs");
6
6
  const require_itemId = require("./itemId-D2XAQ8RU.cjs");
7
7
  require("./errors-B9mCEVG9.cjs");
8
+ const require_containment = require("./containment-Dc3gO4wD.cjs");
8
9
  const require_feeds_paths = require("./feeds/paths.cjs");
9
10
  const require_root = require("./root-9lRFeXbm.cjs");
10
11
  const require_skill_bridge_index = require("./skill-bridge/index.cjs");
@@ -1145,7 +1146,7 @@ function deleteTargets(collection, workspaceRoot) {
1145
1146
  function isDataDirSafe(dataDir, slug, workspaceRoot) {
1146
1147
  const acceptableRoots = [node_path.default.resolve(workspaceRoot, "data", slug), node_path.default.resolve(workspaceRoot, "data", "collections", slug)];
1147
1148
  const resolved = node_path.default.resolve(dataDir);
1148
- return acceptableRoots.some((root) => resolved === root || resolved.startsWith(root + node_path.default.sep));
1149
+ return acceptableRoots.some((root) => require_containment.isWithinRoot(root, resolved));
1149
1150
  }
1150
1151
  /** Step 2 of the restore doc — how to bring the records back. A
1151
1152
  * `dataSource` collection has no record files to copy (its rows live in
@@ -2715,4 +2716,4 @@ Object.defineProperty(exports, "validateRecordObject", {
2715
2716
  }
2716
2717
  });
2717
2718
 
2718
- //# sourceMappingURL=server-CnCUBmSn.cjs.map
2719
+ //# sourceMappingURL=server-BGxmZppB.cjs.map