@mulmoclaude/core 7.4.0 → 7.6.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 (114) hide show
  1. package/dist/{root-CqxPNSyK.js → atomic-C3NMg6-j.js} +2 -20
  2. package/dist/atomic-C3NMg6-j.js.map +1 -0
  3. package/dist/{root-9lRFeXbm.cjs → atomic-cqafMWEI.cjs} +1 -25
  4. package/dist/atomic-cqafMWEI.cjs.map +1 -0
  5. package/dist/collection/index.cjs +3 -3
  6. package/dist/collection/index.js +3 -3
  7. package/dist/collection/registry/server/index.cjs +5 -5
  8. package/dist/collection/registry/server/index.cjs.map +1 -1
  9. package/dist/collection/registry/server/index.js +4 -4
  10. package/dist/collection/server/index.cjs +3 -3
  11. package/dist/collection/server/index.js +3 -3
  12. package/dist/collection-watchers/index.cjs +5 -5
  13. package/dist/collection-watchers/index.js +5 -5
  14. package/dist/{discovery-DxmMcpFo.cjs → discovery-BSvWBOGB.cjs} +7 -6
  15. package/dist/discovery-BSvWBOGB.cjs.map +1 -0
  16. package/dist/{discovery-RyuhNKjx.js → discovery-DEhLlDVW.js} +6 -5
  17. package/dist/discovery-DEhLlDVW.js.map +1 -0
  18. package/dist/{dist-BmO4oSQy.js → dist--searOB5.js} +2 -2
  19. package/dist/dist--searOB5.js.map +1 -0
  20. package/dist/{dist-734JaRYi.cjs → dist-CdSEjlVx.cjs} +2 -2
  21. package/dist/dist-CdSEjlVx.cjs.map +1 -0
  22. package/dist/errorMessage-B-iVKe5R.cjs +1 -0
  23. package/dist/errorMessage-D-HWCI2W.js +1 -0
  24. package/dist/{errors-B9mCEVG9.cjs → errors-B7ShVbIB.cjs} +2 -2
  25. package/dist/{errors-B9mCEVG9.cjs.map → errors-B7ShVbIB.cjs.map} +1 -1
  26. package/dist/{errors-0QwjDxsv.js → errors-BbH5CeKm.js} +2 -2
  27. package/dist/{errors-0QwjDxsv.js.map → errors-BbH5CeKm.js.map} +1 -1
  28. package/dist/feeds/server/index.cjs +6 -6
  29. package/dist/feeds/server/index.cjs.map +1 -1
  30. package/dist/feeds/server/index.js +6 -6
  31. package/dist/feeds/server/index.js.map +1 -1
  32. package/dist/files/index.cjs +8 -13
  33. package/dist/files/index.cjs.map +1 -1
  34. package/dist/files/index.js +3 -8
  35. package/dist/files/index.js.map +1 -1
  36. package/dist/google/index.cjs +5 -5
  37. package/dist/google/index.cjs.map +1 -1
  38. package/dist/google/index.js +4 -4
  39. package/dist/json-BGdV2cz6.cjs +16 -0
  40. package/dist/json-BGdV2cz6.cjs.map +1 -0
  41. package/dist/json-BizOSThv.js +11 -0
  42. package/dist/json-BizOSThv.js.map +1 -0
  43. package/dist/{listen-uiEnXcW9.js → listen-Bm8N0g9o.js} +2 -2
  44. package/dist/{listen-uiEnXcW9.js.map → listen-Bm8N0g9o.js.map} +1 -1
  45. package/dist/{listen-OmfLDX1l.cjs → listen-OGOFPIdk.cjs} +2 -2
  46. package/dist/{listen-OmfLDX1l.cjs.map → listen-OGOFPIdk.cjs.map} +1 -1
  47. package/dist/notifier/index.cjs +1 -1
  48. package/dist/notifier/index.js +1 -1
  49. package/dist/{notifier-CRTk34EC.cjs → notifier-8R05SHLj.cjs} +2 -2
  50. package/dist/{notifier-CRTk34EC.cjs.map → notifier-8R05SHLj.cjs.map} +1 -1
  51. package/dist/{notifier-htdf4ekH.js → notifier-D7TmVus0.js} +2 -2
  52. package/dist/{notifier-htdf4ekH.js.map → notifier-D7TmVus0.js.map} +1 -1
  53. package/dist/plugin-vue/index.cjs +1 -1
  54. package/dist/plugin-vue/index.cjs.map +1 -1
  55. package/dist/plugin-vue/index.js +1 -1
  56. package/dist/plugin-vue/index.js.map +1 -1
  57. package/dist/prompt-files/index.cjs +1 -1
  58. package/dist/prompt-files/index.js +1 -1
  59. package/dist/{promptSafety-CjxafW2b.cjs → promptSafety-CF6OCtor.cjs} +2 -2
  60. package/dist/{promptSafety-CjxafW2b.cjs.map → promptSafety-CF6OCtor.cjs.map} +1 -1
  61. package/dist/{promptSafety-B8LECAkY.js → promptSafety-CYU_kLUL.js} +2 -2
  62. package/dist/{promptSafety-B8LECAkY.js.map → promptSafety-CYU_kLUL.js.map} +1 -1
  63. package/dist/remote-host/index.cjs +1 -1
  64. package/dist/remote-host/index.js +1 -1
  65. package/dist/remote-host/server/index.cjs +4 -4
  66. package/dist/remote-host/server/index.js +4 -4
  67. package/dist/{remote-host-TiMhcW1o.js → remote-host-BiCg_ioB.js} +2 -2
  68. package/dist/{remote-host-TiMhcW1o.js.map → remote-host-BiCg_ioB.js.map} +1 -1
  69. package/dist/{remote-host-11euEZKP.cjs → remote-host-neXWDACl.cjs} +2 -2
  70. package/dist/{remote-host-11euEZKP.cjs.map → remote-host-neXWDACl.cjs.map} +1 -1
  71. package/dist/remote-view/index.cjs +1 -1
  72. package/dist/remote-view/index.js +1 -1
  73. package/dist/root-Ccgd3H5S.cjs +29 -0
  74. package/dist/root-Ccgd3H5S.cjs.map +1 -0
  75. package/dist/root-s0MUUMQU.js +22 -0
  76. package/dist/root-s0MUUMQU.js.map +1 -0
  77. package/dist/runtime-plugins/containment.d.ts +5 -0
  78. package/dist/runtime-plugins/download.d.ts +12 -0
  79. package/dist/runtime-plugins/fetchPackage.d.ts +65 -0
  80. package/dist/runtime-plugins/index.cjs +810 -5
  81. package/dist/runtime-plugins/index.cjs.map +1 -1
  82. package/dist/runtime-plugins/index.d.ts +7 -0
  83. package/dist/runtime-plugins/index.js +786 -8
  84. package/dist/runtime-plugins/index.js.map +1 -1
  85. package/dist/runtime-plugins/inspect.d.ts +18 -0
  86. package/dist/runtime-plugins/install.d.ts +48 -0
  87. package/dist/runtime-plugins/installSource.d.ts +37 -0
  88. package/dist/runtime-plugins/ledger.d.ts +3 -0
  89. package/dist/runtime-plugins/ledgerWrite.d.ts +17 -0
  90. package/dist/runtime-plugins/load.d.ts +2 -2
  91. package/dist/runtime-plugins/npmBuiltinNames.d.ts +1 -0
  92. package/dist/scheduler/index.cjs +2 -2
  93. package/dist/scheduler/index.js +2 -2
  94. package/dist/{server-ZKTtI8_W.cjs → server-BxwOUg_l.cjs} +9 -9
  95. package/dist/{server-ZKTtI8_W.cjs.map → server-BxwOUg_l.cjs.map} +1 -1
  96. package/dist/{server-xdXBsiba.js → server-C3HNV-PG.js} +6 -6
  97. package/dist/{server-xdXBsiba.js.map → server-C3HNV-PG.js.map} +1 -1
  98. package/dist/utils/index.cjs +2 -2
  99. package/dist/utils/index.js +2 -2
  100. package/dist/whisper/index.cjs +2 -2
  101. package/dist/whisper/index.js +2 -2
  102. package/dist/wiki/index.cjs +1 -1
  103. package/dist/wiki/index.js +1 -1
  104. package/dist/workspace-setup/index.js +1 -1
  105. package/dist/workspace-setup/index.js.map +1 -1
  106. package/package.json +1 -1
  107. package/dist/discovery-DxmMcpFo.cjs.map +0 -1
  108. package/dist/discovery-RyuhNKjx.js.map +0 -1
  109. package/dist/dist-734JaRYi.cjs.map +0 -1
  110. package/dist/dist-BmO4oSQy.js.map +0 -1
  111. package/dist/errorMessage-D0kR547_.cjs +0 -1
  112. package/dist/errorMessage-TpKxrmeo.js +0 -1
  113. package/dist/root-9lRFeXbm.cjs.map +0 -1
  114. package/dist/root-CqxPNSyK.js.map +0 -1
@@ -1 +1 @@
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,O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G,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,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":["path","isWithinRoot","respelledWithinRoot","realpathSync","constants","promises","path","isInsideRoot","randomBytes","renameWithWindowsRetry","classifyFilePath","path","realpath","fsStat","readFile","writeFileAtomic","path"],"sources":["../../src/files/safe.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["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":";;;;;;;;;;;;;;;;;AAMA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAaA,UAAAA,QAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJA,UAAAA,QAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,OAAOC,oBAAAA,aAAa,UAAU,YAAY,IAAI,eAAeC,oBAAAA,oBAAoB,UAAU,YAAY;AACzG;AAEA,SAAS,eAAe,SAAg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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,19 +1,14 @@
1
- import { i as writeFileAtomicSync, n as renameWithWindowsRetry, r as writeFileAtomic, t as canonicalRoot } from "../root-CqxPNSyK.js";
1
+ import { n as writeFileAtomic, r as writeFileAtomicSync, t as renameWithWindowsRetry } from "../atomic-C3NMg6-j.js";
2
+ import { t as writeJsonAtomic } from "../json-BizOSThv.js";
2
3
  import { i as respelledWithinRoot, n as isWithinRoot, r as realpathSyncOrNull, t as isInsideRoot } from "../containment-D_vAa6eT.js";
3
4
  import { n as readTextWithinRootSync, t as readTextWithinRoot } from "../withinRoot-CheaBWt0.js";
4
5
  import { n as toPosixRelPath, t as joinPosixRelPath } from "../relPath-BkKmqiiF.js";
6
+ import { t as canonicalRoot } from "../root-s0MUUMQU.js";
5
7
  import { classifyFilePath } from "../artifacts/paths.js";
6
8
  import { constants, promises, realpathSync } from "node:fs";
7
9
  import path from "node:path";
8
10
  import { randomBytes } from "node:crypto";
9
11
  import { readFile, realpath, stat } from "node:fs/promises";
10
- // src/files/json.ts
11
- var JSON_INDENT = 2;
12
- /** Atomic JSON write (2-space indent) — serialize then write through the atomic
13
- * tmp-file + rename seam so a reader never sees a half-written document. */
14
- async function writeJsonAtomic(filePath, data, opts = {}) {
15
- await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);
16
- }
17
12
  // src/files/safe.ts
18
13
  /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
19
14
  * missing file as an empty/default result instead of a thrown error. */
@@ -1 +1 @@
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,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAa,KAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJ,KAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,OAAO,aAAa,UAAU,YAAY,IAAI,eAAe,oBAAoB,UAAU,YAAY;AACzG;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF;;ACfA,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,KAAK;EACZ,IAAI,SAAS,GAAG,GAAG,OAAO;EAC1B,MAAM;CACR;AACF;;AAGA,eAAsB,0BAA0B,UAAkB,UAA0C;CAC1G,MAAM,gBAAgB,MAAM,kBAAkB,KAAK,QAAQ,UAAU,QAAQ,CAAC;CAC9E,IAAI,kBAAkB,MAAM,OAAO;CACnC,OAAO,aAAa,UAAU,aAAa,IAAI,gBA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AAU,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/safe.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["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":";;;;;;;;;;;;;;AAMA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAa,KAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJ,KAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,OAAO,aAAa,UAAU,YAAY,IAAI,eAAe,oBAAoB,UAAU,YAAY;AACzG;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF;;ACfA,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,KAAK;EACZ,IAAI,SAAS,GAAG,GAAG,OAAO;EAC1B,MAAM;CACR;AACF;;AAGA,eAAsB,0BAA0B,UAAkB,UA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;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,13 +1,13 @@
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-DxmMcpFo.cjs");
4
- require("../errors-B9mCEVG9.cjs");
3
+ const require_discovery = require("../discovery-BSvWBOGB.cjs");
4
+ require("../errors-B7ShVbIB.cjs");
5
5
  const require_itemId = require("../itemId-D2XAQ8RU.cjs");
6
6
  const require_text = require("../text-BQiyo5R9.cjs");
7
7
  const require_paths = require("../paths-DUHAueEv.cjs");
8
- const require_root = require("../root-9lRFeXbm.cjs");
8
+ const require_atomic = require("../atomic-cqafMWEI.cjs");
9
9
  const require_utils_fetch = require("../utils/fetch.cjs");
10
- const require_dist = require("../dist-734JaRYi.cjs");
10
+ const require_dist = require("../dist-CdSEjlVx.cjs");
11
11
  const require_project = require("../project-DDTIVEMU.cjs");
12
12
  let node_fs = require("node:fs");
13
13
  let node_path = require("node:path");
@@ -280,7 +280,7 @@ async function readJsonOrNull(filePath) {
280
280
  * to the tmp file and survives the rename. A single-writer token file, so the
281
281
  * staging name is stable (`uniqueTmp: false`). */
282
282
  async function writeJsonAtomicWithMode(filePath, data, mode) {
283
- await require_root.writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), {
283
+ await require_atomic.writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), {
284
284
  mode,
285
285
  uniqueTmp: false
286
286
  });