@mulmoclaude/core 5.13.0 → 5.14.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.
|
@@ -105,3 +105,9 @@ When the page is for the user to decide something — pick between mockups, sett
|
|
|
105
105
|
- `text` is plain text, at most 20,000 characters; a longer one is refused, not truncated.
|
|
106
106
|
- The host shows it in a confirmation bar above the page. The user can edit it, and it is sent as their next message only when they press Send — so after presenting, finish your turn instead of waiting or polling.
|
|
107
107
|
- Write `text` so it stands on its own: name each decision and the option chosen, not just "B".
|
|
108
|
+
- A page you write with `html` purely to hand decisions back may pass `submit: "direct"` to `presentHtml`: its posts then reach the conversation without the confirmation bar, as long as each one carries the key the host puts in the page's URL. A post without it, or a second one within a few seconds, still goes to the bar. It is ignored for `path` — never ask for it on a page whose script you did not write.
|
|
109
|
+
|
|
110
|
+
```js
|
|
111
|
+
const key = new URLSearchParams(location.hash.slice(1)).get("mulmo-submit-key");
|
|
112
|
+
window.parent.postMessage({ type: "mulmo-html-submit", text: summary(), key }, "*");
|
|
113
|
+
```
|
package/dist/files/index.cjs
CHANGED
|
@@ -117,8 +117,8 @@ async function openVerifiedWithinScope(scope, relative, hooks = {}) {
|
|
|
117
117
|
await handle.close();
|
|
118
118
|
return null;
|
|
119
119
|
}
|
|
120
|
-
/** The
|
|
121
|
-
async function
|
|
120
|
+
/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */
|
|
121
|
+
async function verifiedCreatedFileDir(bound, dirReal, staging, handle) {
|
|
122
122
|
const scopeReal = await scopeRealNow(bound);
|
|
123
123
|
const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);
|
|
124
124
|
if (dirAgain === null) return null;
|
|
@@ -130,7 +130,7 @@ async function writeStaging(bound, dirReal, staging, content, hooks) {
|
|
|
130
130
|
const handle = await node_fs.promises.open(node_path.default.join(dirReal, staging), CREATE_FLAGS);
|
|
131
131
|
try {
|
|
132
132
|
await hooks.afterOpen?.();
|
|
133
|
-
const stagingDir = await
|
|
133
|
+
const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);
|
|
134
134
|
if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);
|
|
135
135
|
await handle.writeFile(content);
|
|
136
136
|
return stagingDir;
|
|
@@ -138,6 +138,9 @@ async function writeStaging(bound, dirReal, staging, content, hooks) {
|
|
|
138
138
|
await handle.close();
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
|
+
var assertSingleName = (leaf) => {
|
|
142
|
+
if (leaf === "" || leaf === "." || leaf === ".." || node_path.default.basename(leaf) !== leaf || leaf.includes("/")) throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);
|
|
143
|
+
};
|
|
141
144
|
var stagingNameFor = (leaf) => `${leaf}.${(0, node_crypto.randomBytes)(STAGING_SUFFIX_BYTES).toString("hex")}.tmp`;
|
|
142
145
|
var removeQuietly = async (absPath) => {
|
|
143
146
|
await node_fs.promises.unlink(absPath).catch(() => {});
|
|
@@ -155,6 +158,7 @@ async function renameIntoPlace(stagingDir, staging, leaf, hooks) {
|
|
|
155
158
|
* verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call
|
|
156
159
|
* makes the write fail — unless the link's target is a directory the actor could already write. */
|
|
157
160
|
async function writeFileVerifiedInScope(scope, dirReal, leaf, content, hooks = {}) {
|
|
161
|
+
assertSingleName(leaf);
|
|
158
162
|
const bound = await bindScope(scope);
|
|
159
163
|
if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);
|
|
160
164
|
const staging = stagingNameFor(leaf);
|
|
@@ -163,6 +167,24 @@ async function writeFileVerifiedInScope(scope, dirReal, leaf, content, hooks = {
|
|
|
163
167
|
throw err;
|
|
164
168
|
}), staging, leaf, hooks);
|
|
165
169
|
}
|
|
170
|
+
/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`
|
|
171
|
+
* exists, as `writeFile(…, { flag: "wx" })` does. The new file is verified to sit inside the scope before any byte is
|
|
172
|
+
* written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file
|
|
173
|
+
* in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */
|
|
174
|
+
async function createFileVerifiedInScope(scope, dirReal, leaf, content, hooks = {}) {
|
|
175
|
+
assertSingleName(leaf);
|
|
176
|
+
const bound = await bindScope(scope);
|
|
177
|
+
if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);
|
|
178
|
+
await hooks.beforeOpen?.();
|
|
179
|
+
const handle = await node_fs.promises.open(node_path.default.join(dirReal, leaf), CREATE_FLAGS);
|
|
180
|
+
try {
|
|
181
|
+
await hooks.afterOpen?.();
|
|
182
|
+
if (await verifiedCreatedFileDir(bound, dirReal, leaf, handle) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);
|
|
183
|
+
await handle.writeFile(content);
|
|
184
|
+
} finally {
|
|
185
|
+
await handle.close();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
166
188
|
// src/files/byPath.ts
|
|
167
189
|
var MARKDOWN_EXTENSIONS = [".md"];
|
|
168
190
|
var HTML_EXTENSIONS = [".html", ".htm"];
|
|
@@ -266,6 +288,7 @@ exports.HTML_EXTENSIONS = HTML_EXTENSIONS;
|
|
|
266
288
|
exports.MARKDOWN_EXTENSIONS = MARKDOWN_EXTENSIONS;
|
|
267
289
|
exports.canonicalRoot = require_root.canonicalRoot;
|
|
268
290
|
exports.createByPathFileOps = createByPathFileOps;
|
|
291
|
+
exports.createFileVerifiedInScope = createFileVerifiedInScope;
|
|
269
292
|
exports.existsAsFile = existsAsFile;
|
|
270
293
|
exports.isEnoent = isEnoent;
|
|
271
294
|
exports.joinPosixRelPath = require_relPath.joinPosixRelPath;
|
package/dist/files/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["writeFileAtomic","path","realpathSync","constants","promises","path","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\";\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,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAMA,aAAAA,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;ACHA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAaC,UAAAA,QAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJA,UAAAA,QAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,IAAI,iBAAiB,YAAY,CAAC,aAAa,WAAW,WAAWA,UA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,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,OAAOG,UAAAA,QAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAOA,UAAAA,QAAK,WAAW,SAAS,IAAIA,UAAAA,QAAK,QAAQ,SAAS,IAAI;AAChE"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["writeFileAtomic","path","realpathSync","constants","promises","path","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\";\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,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AC;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,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"}
|
package/dist/files/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { writeFileAtomic, writeFileAtomicSync, type WriteAtomicOptions } from './atomic.js';
|
|
2
2
|
export { writeJsonAtomic } from './json.js';
|
|
3
3
|
export { isEnoent, resolveWithinRoot } from './safe.js';
|
|
4
|
-
export { openVerifiedWithinScope, writeFileVerifiedInScope, scopeRealpath, resolveExistingWithinRoot, realpathIfPresent, type VerifiedScope, type VerifiedFileHooks, } from './verified.js';
|
|
4
|
+
export { openVerifiedWithinScope, writeFileVerifiedInScope, createFileVerifiedInScope, scopeRealpath, resolveExistingWithinRoot, realpathIfPresent, type VerifiedScope, type VerifiedFileHooks, } from './verified.js';
|
|
5
5
|
export { toPosixRelPath, joinPosixRelPath } from './relPath.js';
|
|
6
6
|
export { canonicalRoot } from './root.js';
|
|
7
7
|
export { resolveByPath, existsAsFile, createByPathFileOps, MARKDOWN_EXTENSIONS, HTML_EXTENSIONS, type ByPathFileOps, type ByPathOptions } from './byPath.js';
|
package/dist/files/index.js
CHANGED
|
@@ -114,8 +114,8 @@ async function openVerifiedWithinScope(scope, relative, hooks = {}) {
|
|
|
114
114
|
await handle.close();
|
|
115
115
|
return null;
|
|
116
116
|
}
|
|
117
|
-
/** The
|
|
118
|
-
async function
|
|
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
|
|
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
|
package/dist/files/index.js.map
CHANGED
|
@@ -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,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAM,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;ACHA,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,IAAI,iBAAiB,YAAY,CAAC,aAAa,WAAW,WAAW,KAAK,GAAG,GAC3E,OAAO;CAET,OAAO;AACT;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF;;AClBA,IAAM,aAAa,UAAU,YAAY,UAAU,cAAc,MAAM,UAAU,cAAc;AAC/F,IAAM,eAAe,UAAU,WAAW,UAAU,UAAU,UAAU,UAA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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,GAAkB;CACnH,MAAM,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;ACHA,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,IAAI,iBAAiB,YAAY,CAAC,aAAa,WAAW,WAAW,KAAK,GAAG,GAC3E,OAAO;CAET,OAAO;AACT;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF;;AClBA,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,S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B,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"}
|
package/dist/files/verified.d.ts
CHANGED
|
@@ -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>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mulmoclaude/core",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.14.0",
|
|
4
4
|
"description": "Shared server-side core for MulmoClaude and MulmoTerminal — the always-shipped-together subsystems consolidated behind subpath exports so the two hosts can't drift. Server-only except the browser-safe ./artifacts, ./whisper/client, ./workspace-setup/slug, ./translation/client, ./remote-view, ./remote-host and ./plugin-vue entries. All host specifics are injected.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|