@mulmoclaude/core 5.13.0 → 6.0.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.
@@ -114,8 +114,8 @@ async function openVerifiedWithinScope(scope, relative, hooks = {}) {
114
114
  await handle.close();
115
115
  return null;
116
116
  }
117
- /** The staging file's directory, re-resolved, if it is inside the scope now and holds exactly the opened staging file. */
118
- async function verifiedStagingDir(bound, dirReal, staging, handle) {
117
+ /** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */
118
+ async function verifiedCreatedFileDir(bound, dirReal, staging, handle) {
119
119
  const scopeReal = await scopeRealNow(bound);
120
120
  const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);
121
121
  if (dirAgain === null) return null;
@@ -127,7 +127,7 @@ async function writeStaging(bound, dirReal, staging, content, hooks) {
127
127
  const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);
128
128
  try {
129
129
  await hooks.afterOpen?.();
130
- const stagingDir = await verifiedStagingDir(bound, dirReal, staging, handle);
130
+ const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);
131
131
  if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);
132
132
  await handle.writeFile(content);
133
133
  return stagingDir;
@@ -135,6 +135,9 @@ async function writeStaging(bound, dirReal, staging, content, hooks) {
135
135
  await handle.close();
136
136
  }
137
137
  }
138
+ var assertSingleName = (leaf) => {
139
+ if (leaf === "" || leaf === "." || leaf === ".." || path.basename(leaf) !== leaf || leaf.includes("/")) throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);
140
+ };
138
141
  var stagingNameFor = (leaf) => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString("hex")}.tmp`;
139
142
  var removeQuietly = async (absPath) => {
140
143
  await promises.unlink(absPath).catch(() => {});
@@ -152,6 +155,7 @@ async function renameIntoPlace(stagingDir, staging, leaf, hooks) {
152
155
  * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call
153
156
  * makes the write fail — unless the link's target is a directory the actor could already write. */
154
157
  async function writeFileVerifiedInScope(scope, dirReal, leaf, content, hooks = {}) {
158
+ assertSingleName(leaf);
155
159
  const bound = await bindScope(scope);
156
160
  if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);
157
161
  const staging = stagingNameFor(leaf);
@@ -160,6 +164,24 @@ async function writeFileVerifiedInScope(scope, dirReal, leaf, content, hooks = {
160
164
  throw err;
161
165
  }), staging, leaf, hooks);
162
166
  }
167
+ /** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`
168
+ * exists, as `writeFile(…, { flag: "wx" })` does. The new file is verified to sit inside the scope before any byte is
169
+ * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file
170
+ * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */
171
+ async function createFileVerifiedInScope(scope, dirReal, leaf, content, hooks = {}) {
172
+ assertSingleName(leaf);
173
+ const bound = await bindScope(scope);
174
+ if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);
175
+ await hooks.beforeOpen?.();
176
+ const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);
177
+ try {
178
+ await hooks.afterOpen?.();
179
+ if (await verifiedCreatedFileDir(bound, dirReal, leaf, handle) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);
180
+ await handle.writeFile(content);
181
+ } finally {
182
+ await handle.close();
183
+ }
184
+ }
163
185
  // src/files/byPath.ts
164
186
  var MARKDOWN_EXTENSIONS = [".md"];
165
187
  var HTML_EXTENSIONS = [".html", ".htm"];
@@ -259,6 +281,6 @@ function resolveHtmlFileRequestPath(workspaceRoot, reqPath) {
259
281
  const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join("/") : `/${rest.join("/")}`;
260
282
  return path.isAbsolute(candidate) ? path.resolve(candidate) : null;
261
283
  }
262
- export { HTML_EXTENSIONS, MARKDOWN_EXTENSIONS, canonicalRoot, createByPathFileOps, existsAsFile, isEnoent, joinPosixRelPath, openVerifiedWithinScope, realpathIfPresent, resolveByPath, resolveExistingWithinRoot, resolveHtmlFileRequestPath, resolveWithinRoot, scopeRealpath, toPosixRelPath, writeFileAtomic, writeFileAtomicSync, writeFileVerifiedInScope, writeJsonAtomic };
284
+ export { HTML_EXTENSIONS, MARKDOWN_EXTENSIONS, canonicalRoot, createByPathFileOps, createFileVerifiedInScope, existsAsFile, isEnoent, joinPosixRelPath, openVerifiedWithinScope, realpathIfPresent, resolveByPath, resolveExistingWithinRoot, resolveHtmlFileRequestPath, resolveWithinRoot, scopeRealpath, toPosixRelPath, writeFileAtomic, writeFileAtomicSync, writeFileVerifiedInScope, writeJsonAtomic };
263
285
 
264
286
  //# sourceMappingURL=index.js.map
@@ -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\";\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 if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) {\n return null;\n }\n return 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\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nconst isWithin = (rootReal: string, candidateReal: string): boolean => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The staging file's directory, re-resolved, if it is inside the scope now and holds exactly the opened staging file. */\nasync function verifiedStagingDir(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 verifiedStagingDir(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\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 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","// 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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kC;CACxD,IAAI;CACJ,IAAI;EACF,UAAU,QACP,QAAQ,OAAO,EAAE,CAAC,CAClB,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,mBAAmB,OAAO,CAAC;CACjD,QAAQ;EAEN,OAAO;CACT;CAMA,OAAO,QAAQ,MAAM,YAAY,QAAQ,SAAS,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,IAAI,OAAO;AAC7F;;;;AAKA,SAAgB,2BAA2B,eAAuB,SAAgC;CAChG,MAAM,UAAU,eAAe,OAAO;CACtC,IAAI,YAAY,QAAQ,QAAQ,SAAS,GAAG,OAAO;CACnD,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,IAAI,UAAU,6BAA6B,UAAU,0BAA0B,OAAO;CACtF,MAAM,CAAC,aAAa;CACpB,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,KAAK,MAAM,YAAY,YAAY,MAAM,YAAY,OAAO,YAAY,QAAQ,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,GACnI,OAAO;CAET,IAAI,UAAU,2BAA2B,OAAO,KAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAO,KAAK,WAAW,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI;AAChE"}
1
+ {"version":3,"file":"index.js","names":["fsStat"],"sources":["../../src/files/json.ts","../../src/files/safe.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\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 if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) {\n return null;\n }\n return 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\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nconst isWithin = (rootReal: string, candidateReal: string): boolean => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAA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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"}
@@ -26,3 +26,8 @@ export declare function openVerifiedWithinScope(scope: VerifiedScope, relative:
26
26
  * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call
27
27
  * makes the write fail — unless the link's target is a directory the actor could already write. */
28
28
  export declare function writeFileVerifiedInScope(scope: VerifiedScope, dirReal: string, leaf: string, content: string | Uint8Array, hooks?: VerifiedFileHooks): Promise<void>;
29
+ /** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`
30
+ * exists, as `writeFile(…, { flag: "wx" })` does. The new file is verified to sit inside the scope before any byte is
31
+ * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file
32
+ * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */
33
+ export declare function createFileVerifiedInScope(scope: VerifiedScope, dirReal: string, leaf: string, content: string | Uint8Array, hooks?: VerifiedFileHooks): Promise<void>;
@@ -1,13 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_remote_host = require("../remote-host-BW_eH-Nu.cjs");
2
+ const require_remote_host = require("../remote-host-11euEZKP.cjs");
3
3
  exports.COMMAND_SCOPE_PARAM = require_remote_host.COMMAND_SCOPE_PARAM;
4
4
  exports.REMOTE_HOST_PROTOCOL_VERSION = require_remote_host.REMOTE_HOST_PROTOCOL_VERSION;
5
5
  exports.RUNNER_HEALTH_STATES = require_remote_host.RUNNER_HEALTH_STATES;
6
6
  exports.buildHostPresence = require_remote_host.buildHostPresence;
7
7
  exports.byCreatedAt = require_remote_host.byCreatedAt;
8
8
  exports.coerceJsonObject = require_remote_host.coerceJsonObject;
9
- exports.commandsCollection = require_remote_host.commandsCollection;
10
- exports.hostDoc = require_remote_host.hostDoc;
11
9
  exports.isExpired = require_remote_host.isExpired;
12
10
  exports.isRunnerHealth = require_remote_host.isRunnerHealth;
13
11
  exports.isRunnerHealthState = require_remote_host.isRunnerHealthState;
@@ -1,4 +1,3 @@
1
- import { CollectionReference, DocumentData, DocumentReference, Firestore } from 'firebase/firestore';
2
1
  export type JsonValue = string | number | boolean | null | JsonValue[] | {
3
2
  [key: string]: JsonValue;
4
3
  };
@@ -102,7 +101,5 @@ export interface HostPresence {
102
101
  label?: string;
103
102
  }
104
103
  export declare const buildHostPresence: (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine) => HostPresence;
105
- export declare const commandsCollection: (firestore: Firestore, channel: Channel) => CollectionReference<DocumentData>;
106
- export declare const hostDoc: (firestore: Firestore, channel: Channel) => DocumentReference<DocumentData>;
107
104
  export { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from './health.js';
108
105
  export type { RunnerHealth, RunnerHealthState } from './health.js';
@@ -1 +1 @@
1
- export { t as COMMAND_SCOPE_PARAM, n as REMOTE_HOST_PROTOCOL_VERSION, d as RUNNER_HEALTH_STATES, r as buildHostPresence, i as byCreatedAt, a as coerceJsonObject, o as commandsCollection, s as hostDoc, c as isExpired, f as isRunnerHealth, p as isRunnerHealthState, l as readCommandScope, u as toJsonObject } from "../remote-host-CSeDNbE6.js";
1
+ export { t as COMMAND_SCOPE_PARAM, n as REMOTE_HOST_PROTOCOL_VERSION, l as RUNNER_HEALTH_STATES, r as buildHostPresence, i as byCreatedAt, a as coerceJsonObject, o as isExpired, u as isRunnerHealth, d as isRunnerHealthState, s as readCommandScope, c as toJsonObject } from "../remote-host-TiMhcW1o.js";
@@ -2,12 +2,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_dist = require("../../dist-734JaRYi.cjs");
3
3
  require("../../errorMessage-D0kR547_.cjs");
4
4
  const require_listen = require("../../listen-OmfLDX1l.cjs");
5
- const require_remote_host = require("../../remote-host-BW_eH-Nu.cjs");
5
+ const require_remote_host = require("../../remote-host-11euEZKP.cjs");
6
6
  let firebase_firestore = require("firebase/firestore");
7
7
  let node_perf_hooks = require("node:perf_hooks");
8
8
  let firebase_auth = require("firebase/auth");
9
9
  let firebase_app = require("firebase/app");
10
10
  let firebase_storage = require("firebase/storage");
11
+ // src/remote-host/server/paths.ts
12
+ var commandsCollection = (firestore, channel) => (0, firebase_firestore.collection)(firestore, "users", channel.uid, "hosts", channel.hostId, "commands");
13
+ var hostDoc = (firestore, channel) => (0, firebase_firestore.doc)(firestore, "users", channel.uid, "hosts", channel.hostId);
11
14
  var isPlainObject = (value) => {
12
15
  const proto = Object.getPrototypeOf(value);
13
16
  return proto === Object.prototype || proto === null;
@@ -272,7 +275,7 @@ var listenForCommands = (queuedCommands, ctx, goOffline) => {
272
275
  var heartbeatMs = (options) => options.heartbeatMs ?? 6e4;
273
276
  var presenceStaleAfterMs = (options = {}) => heartbeatMs(options) * 3;
274
277
  var buildPresenceBeat = (firestore, channel, handlers, options, onStale) => {
275
- const presence = require_remote_host.hostDoc(firestore, channel);
278
+ const presence = hostDoc(firestore, channel);
276
279
  const report = (message) => options.onEvent?.({
277
280
  phase: "error",
278
281
  method: "presence",
@@ -313,7 +316,7 @@ var startHostRunner = (firestore, channel, handlers, options = {}) => {
313
316
  }
314
317
  presence.announce(true);
315
318
  run.beat = setInterval(presence.beat, heartbeatMs(options));
316
- run.stopListening = listenForCommands((0, firebase_firestore.query)(require_remote_host.commandsCollection(firestore, channel), (0, firebase_firestore.where)("status", "==", "queued")), {
319
+ run.stopListening = listenForCommands((0, firebase_firestore.query)(commandsCollection(firestore, channel), (0, firebase_firestore.where)("status", "==", "queued")), {
317
320
  firestore,
318
321
  handlers,
319
322
  options,
@@ -541,7 +544,7 @@ var presenceIsFresh = (data, now, staleAfterMs = PRESENCE_STALE_MS) => {
541
544
  var createPresenceProbe = (deps) => {
542
545
  const now = deps.now ?? Date.now;
543
546
  return async () => {
544
- return presenceIsFresh((await withTimeout((0, firebase_firestore.getDocFromServer)(require_remote_host.hostDoc(deps.firestore(), deps.channel)), deps.timeoutMs ?? PROBE_TIMEOUT_MS)).data(), now(), deps.staleAfterMs ?? PRESENCE_STALE_MS);
547
+ return presenceIsFresh((await withTimeout((0, firebase_firestore.getDocFromServer)(hostDoc(deps.firestore(), deps.channel)), deps.timeoutMs ?? PROBE_TIMEOUT_MS)).data(), now(), deps.staleAfterMs ?? PRESENCE_STALE_MS);
545
548
  };
546
549
  };
547
550
  // src/remote-host/server/lifecycle.ts
@@ -799,12 +802,14 @@ exports.DEFAULT_HEARTBEAT_MS = DEFAULT_HEARTBEAT_MS;
799
802
  exports.LISTEN_RETRY_WINDOW_MS = require_listen.LISTEN_RETRY_WINDOW_MS;
800
803
  exports.PRESENCE_STALE_BEATS = PRESENCE_STALE_BEATS;
801
804
  exports.PRESENCE_STALE_MS = PRESENCE_STALE_MS;
805
+ exports.commandsCollection = commandsCollection;
802
806
  exports.createHostSessionPersistence = createHostSessionPersistence;
803
807
  exports.createPresenceProbe = createPresenceProbe;
804
808
  exports.createRemoteHost = createRemoteHost;
805
809
  exports.createRemoteHostAuth = createRemoteHostAuth;
806
810
  exports.createRemoteHostFirebase = createRemoteHostFirebase;
807
811
  exports.createRemoteHostSession = createRemoteHostSession;
812
+ exports.hostDoc = hostDoc;
808
813
  exports.isSeedableBlob = isSeedableBlob;
809
814
  exports.presenceIsFresh = presenceIsFresh;
810
815
  exports.presenceStaleAfterMs = presenceStaleAfterMs;