mulmoclaude 2.9.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +11 -0
  2. package/bin/mulmoclaude.js +32 -17
  3. package/client/assets/{JsonEditor-E3FJ7oRf.js → JsonEditor-DnC5hozl.js} +1 -1
  4. package/client/assets/{marp-C3oyTBz_.js → marp-DvbfD9EO.js} +1 -1
  5. package/client/assets/material-symbols-outlined-DzTrJqFk.woff2 +0 -0
  6. package/client/assets/{feat-3497-qPLQlhNs.js → mulmoclaude3-BUmaA-ZX.js} +606 -600
  7. package/client/assets/mulmoclaude3-D93Ihflz.css +2 -0
  8. package/client/assets/vue-i18n-BVPWXOdL.js +3 -0
  9. package/client/index.html +3 -3
  10. package/package.json +20 -20
  11. package/server/agent/backend/claude-code.ts +50 -5
  12. package/server/agent/config.ts +3 -1
  13. package/server/agent/sandboxEnv.ts +148 -0
  14. package/server/agent/sandboxEnvPlan.ts +188 -0
  15. package/server/api/auth/bearerAuth.ts +19 -10
  16. package/server/api/auth/clientTokenAccess.ts +57 -0
  17. package/server/api/auth/clientTokenCli.ts +13 -0
  18. package/server/api/auth/clientTokenCommands.ts +90 -0
  19. package/server/api/auth/clientTokenRule.ts +115 -0
  20. package/server/api/auth/clientTokenStore.ts +178 -0
  21. package/server/api/auth/principal.ts +33 -0
  22. package/server/api/routes/collections.ts +73 -35
  23. package/server/api/routes/files.ts +230 -89
  24. package/server/api/routes/pdf.ts +68 -62
  25. package/server/api/routes/runtime-plugin.ts +33 -32
  26. package/server/build/mcp-server.mjs +618 -609
  27. package/server/events/pub-sub/handshakeAuth.ts +3 -5
  28. package/server/events/pub-sub/index.ts +22 -4
  29. package/server/index.ts +30 -95
  30. package/server/plugins/confined-file-ops.ts +5 -3
  31. package/server/system/config.ts +1 -1
  32. package/server/system/env.ts +4 -0
  33. package/server/system/logs/aaa +737 -0
  34. package/server/system/logs/bb +446 -0
  35. package/server/utils/exif.ts +4 -7
  36. package/server/utils/files/artifactMount.ts +89 -0
  37. package/server/utils/files/attachment-store.ts +17 -29
  38. package/server/utils/files/image-store.ts +7 -13
  39. package/server/utils/files/plugins-io.ts +13 -5
  40. package/server/utils/files/safe.ts +0 -8
  41. package/server/utils/files/sendFileHandle.ts +115 -0
  42. package/server/utils/files/store-files.ts +86 -0
  43. package/server/utils/files/storePaths.ts +23 -0
  44. package/server/utils/files/thumbnail-store.ts +25 -23
  45. package/server/utils/files/upload-io.ts +9 -8
  46. package/server/utils/html/htmlArtifactSplicer.ts +19 -14
  47. package/server/utils/share/packHtml.ts +23 -34
  48. package/server/workspace/photo-locations/index.ts +26 -27
  49. package/server/workspace/photo-locations/list.ts +17 -29
  50. package/server/workspace/photo-locations/store.ts +4 -0
  51. package/server/workspace/wiki-pages/io.ts +9 -8
  52. package/src/components/SessionHistoryRow.vue +11 -1
  53. package/src/utils/html/customViewSrcdoc.ts +5 -0
  54. package/client/assets/feat-3497-CVVJjM2K.css +0 -2
  55. package/client/assets/material-symbols-outlined-Bn5lkljl.woff2 +0 -0
  56. package/client/assets/vue-i18n-BHWgmfE3.js +0 -3
  57. package/server/utils/files/store-resolvers.ts +0 -58
@@ -10,17 +10,15 @@
10
10
  // data/attachments/YYYY/MM/<id>.<ext> (original, always)
11
11
  // data/attachments/YYYY/MM/<id>.pdf (companion, PPTX only — same <id>)
12
12
 
13
- import { readFile, stat } from "fs/promises";
14
13
  import path from "path";
15
14
  import { WORKSPACE_DIRS, WORKSPACE_PATHS } from "../../workspace/paths.js";
16
15
  import { shortId } from "../id.js";
17
- import { writeFileAtomic } from "./atomic.js";
18
16
  import { yearMonthUtc } from "@mulmoclaude/core/artifacts";
19
17
  import { makePathValidator } from "./path-validator.js";
20
- import { makeStoreResolvers } from "./store-resolvers.js";
18
+ import { makeStoreFiles } from "./store-files.js";
21
19
  import { storedExtensionFor } from "./attachment-mime.js";
22
20
 
23
- const resolvers = makeStoreResolvers(() => WORKSPACE_PATHS.attachments, WORKSPACE_DIRS.attachments);
21
+ const store = makeStoreFiles(() => WORKSPACE_PATHS.attachments, WORKSPACE_DIRS.attachments);
24
22
 
25
23
  export interface SavedAttachment {
26
24
  /** Workspace-relative path of the file written to disk. */
@@ -31,14 +29,15 @@ export interface SavedAttachment {
31
29
  }
32
30
 
33
31
  /** Post-save hook fired after every successful `saveAttachment`.
34
- * Receives the absolute on-disk path, the workspace-relative path
35
- * (the same one returned to the caller), and the MIME type the
36
- * bytes were saved with. Hooks must NEVER throw — the upload is
37
- * already on disk by the time the hook runs, so a failure should
32
+ * Receives the workspace-relative path (the same one returned to the
33
+ * caller) and the MIME type the bytes were saved with — no absolute
34
+ * path, so a hook reads the bytes back through the store. Hooks must
35
+ * NEVER throw — the upload is already on disk by the time the hook
36
+ * runs, so a failure should
38
37
  * log and return, not propagate. Multiple hooks fan out via
39
38
  * `Promise.allSettled` so one slow / failing hook can't block or
40
39
  * break the others. (#1222 PR-A.) */
41
- export type SaveAttachmentHook = (absPath: string, relativePath: string, mimeType: string) => Promise<void>;
40
+ export type SaveAttachmentHook = (relativePath: string, mimeType: string) => Promise<void>;
42
41
 
43
42
  const saveAttachmentHooks: SaveAttachmentHook[] = [];
44
43
 
@@ -54,14 +53,14 @@ export function registerSaveAttachmentHook(hook: SaveAttachmentHook): () => void
54
53
  };
55
54
  }
56
55
 
57
- async function runSaveAttachmentHooks(absPath: string, relativePath: string, mimeType: string): Promise<void> {
56
+ async function runSaveAttachmentHooks(relativePath: string, mimeType: string): Promise<void> {
58
57
  if (saveAttachmentHooks.length === 0) return;
59
58
  // Snapshot the array so a hook that calls `registerSaveAttachmentHook`
60
59
  // (or its unregister fn) during this loop doesn't mutate the
61
60
  // iteration order. `allSettled` so one failing hook doesn't stop
62
61
  // the others — failures are the hook's responsibility to log.
63
62
  const snapshot = [...saveAttachmentHooks];
64
- await Promise.allSettled(snapshot.map((hook) => hook(absPath, relativePath, mimeType)));
63
+ await Promise.allSettled(snapshot.map((hook) => hook(relativePath, mimeType)));
65
64
  }
66
65
 
67
66
  /** Save a single attachment under data/attachments/YYYY/MM/. The
@@ -70,15 +69,13 @@ async function runSaveAttachmentHooks(absPath: string, relativePath: string, mim
70
69
  export async function saveAttachment(base64Data: string, mimeType: string, originalFilename?: string): Promise<SavedAttachment> {
71
70
  const partition = yearMonthUtc();
72
71
  const ext = storedExtensionFor(mimeType, originalFilename);
73
- const filename = `${shortId()}${ext}`;
74
- const absPath = path.join(WORKSPACE_PATHS.attachments, partition, filename);
75
- await writeFileAtomic(absPath, Buffer.from(base64Data, "base64"));
76
- const relativePath = path.posix.join(WORKSPACE_DIRS.attachments, partition, filename);
72
+ const relativePath = path.posix.join(WORKSPACE_DIRS.attachments, partition, `${shortId()}${ext}`);
73
+ await store.write(relativePath, Buffer.from(base64Data, "base64"));
77
74
  // Hooks (e.g. photo-EXIF capture) are awaited so callers can rely
78
75
  // on the sidecar existing by the time `saveAttachment` resolves —
79
76
  // simplifies test assertions and removes a class of race conditions
80
77
  // for downstream tools that read sidecars right after upload.
81
- await runSaveAttachmentHooks(absPath, relativePath, mimeType);
78
+ await runSaveAttachmentHooks(relativePath, mimeType);
82
79
  return { relativePath, mimeType };
83
80
  }
84
81
 
@@ -92,30 +89,21 @@ export async function saveCompanion(originalRelativePath: string, buf: Buffer, e
92
89
  const dir = path.posix.dirname(originalRelativePath);
93
90
  const base = path.posix.basename(originalRelativePath, path.posix.extname(originalRelativePath));
94
91
  const relativePath = path.posix.join(dir, `${base}${ext}`);
95
- const absPath = await resolvers.forWrite(relativePath);
96
- await writeFileAtomic(absPath, buf);
92
+ await store.write(relativePath, buf);
97
93
  return relativePath;
98
94
  }
99
95
 
100
96
  export async function loadAttachmentBase64(relativePath: string): Promise<string> {
101
- const absPath = await resolvers.forRead(relativePath);
102
- const buf = await readFile(absPath);
103
- return buf.toString("base64");
97
+ return (await store.read(relativePath)).toString("base64");
104
98
  }
105
99
 
106
100
  export async function loadAttachmentBytes(relativePath: string): Promise<Buffer> {
107
- const absPath = await resolvers.forRead(relativePath);
108
- return readFile(absPath);
101
+ return store.read(relativePath);
109
102
  }
110
103
 
111
104
  /** True when `relativePath` names a regular file inside the attachment store. */
112
105
  export async function attachmentExists(relativePath: string): Promise<boolean> {
113
- try {
114
- const absPath = await resolvers.forRead(relativePath);
115
- return (await stat(absPath)).isFile();
116
- } catch {
117
- return false;
118
- }
106
+ return store.isFile(relativePath);
119
107
  }
120
108
 
121
109
  export const isAttachmentPath = makePathValidator({ prefix: WORKSPACE_DIRS.attachments });
@@ -1,32 +1,26 @@
1
- import { readFile } from "fs/promises";
2
1
  import path from "path";
3
2
  import { WORKSPACE_DIRS, WORKSPACE_PATHS } from "../../workspace/paths.js";
4
3
  import { shortId } from "../id.js";
5
- import { writeFileAtomic } from "./atomic.js";
6
4
  import { yearMonthUtc } from "@mulmoclaude/core/artifacts";
7
5
  import { makePathValidator } from "./path-validator.js";
8
- import { makeStoreResolvers } from "./store-resolvers.js";
6
+ import { makeStoreFiles } from "./store-files.js";
9
7
 
10
- const resolvers = makeStoreResolvers(() => WORKSPACE_PATHS.images, WORKSPACE_DIRS.images);
8
+ const store = makeStoreFiles(() => WORKSPACE_PATHS.images, WORKSPACE_DIRS.images);
11
9
 
12
10
  // #764 sharded under images/YYYY/MM/ (UTC). Buffer pass-through avoids re-encoding the PNG bytes.
13
11
  export async function saveImage(base64Data: string): Promise<string> {
14
12
  const partition = yearMonthUtc();
15
- const filename = `${shortId()}.png`;
16
- const absPath = path.join(WORKSPACE_PATHS.images, partition, filename);
17
- await writeFileAtomic(absPath, Buffer.from(base64Data, "base64"));
18
- return path.posix.join(WORKSPACE_DIRS.images, partition, filename);
13
+ const relativePath = path.posix.join(WORKSPACE_DIRS.images, partition, `${shortId()}.png`);
14
+ await store.write(relativePath, Buffer.from(base64Data, "base64"));
15
+ return relativePath;
19
16
  }
20
17
 
21
18
  export async function overwriteImage(relativePath: string, base64Data: string): Promise<void> {
22
- const absPath = await resolvers.forWrite(relativePath);
23
- await writeFileAtomic(absPath, Buffer.from(base64Data, "base64"));
19
+ await store.write(relativePath, Buffer.from(base64Data, "base64"));
24
20
  }
25
21
 
26
22
  export async function loadImageBase64(relativePath: string): Promise<string> {
27
- const absPath = await resolvers.forRead(relativePath);
28
- const buf = await readFile(absPath);
29
- return buf.toString("base64");
23
+ return (await store.read(relativePath)).toString("base64");
30
24
  }
31
25
 
32
26
  export function stripDataUri(dataUri: string): string {
@@ -15,8 +15,9 @@
15
15
  // written ledger never bricks server boot. Writes go through the
16
16
  // atomic helper, so a crashed install can't leave a corrupt file.
17
17
 
18
- import { readFile } from "node:fs/promises";
19
18
  import path from "node:path";
19
+ import type { VerifiedScope } from "@mulmoclaude/core/files";
20
+ import { openArtifactFile } from "./artifactMount.js";
20
21
  import { loadJsonFile } from "./json.js";
21
22
  import { hasStringProp } from "../types.js";
22
23
  import { WORKSPACE_PATHS } from "../../workspace/paths.js";
@@ -57,10 +58,17 @@ export interface PluginAsset {
57
58
  contentType: string;
58
59
  }
59
60
 
60
- export async function readPluginAsset(absPath: string): Promise<PluginAsset> {
61
- const data = await readFile(absPath);
62
- const ext = path.extname(absPath).toLowerCase();
63
- return { data, contentType: pluginAssetContentType(ext) };
61
+ /** Null for a path that is missing, not a regular file, or outside the scope (also when swapped mid-read); other
62
+ * read errors propagate. The bytes come from the verified handle (#3573). */
63
+ export async function readPluginAsset(scope: VerifiedScope, relPath: string): Promise<PluginAsset | null> {
64
+ const handle = await openArtifactFile(scope, relPath);
65
+ if (handle === null) return null;
66
+ try {
67
+ const data = await handle.readFile();
68
+ return { data, contentType: pluginAssetContentType(path.extname(relPath).toLowerCase()) };
69
+ } finally {
70
+ await handle.close();
71
+ }
64
72
  }
65
73
 
66
74
  // Lookup table over a switch — flat data structure stays under
@@ -14,14 +14,6 @@ export function isEnoent(err: unknown): boolean {
14
14
  return isErrorWithCode(err) && err.code === "ENOENT";
15
15
  }
16
16
 
17
- export function readBinarySafeSync(absPath: string): Buffer | null {
18
- try {
19
- return readFileSync(absPath);
20
- } catch {
21
- return null;
22
- }
23
- }
24
-
25
17
  export async function readTextSafe(absPath: string): Promise<string | null> {
26
18
  try {
27
19
  return await promises.readFile(absPath, "utf-8");
@@ -0,0 +1,115 @@
1
+ // Serve an already-opened file. `express.static` re-opens by path after the caller's check, so a
2
+ // path swapped in between is followed; serving from the verified handle closes that window.
3
+
4
+ import path from "node:path";
5
+ import type { Stats } from "node:fs";
6
+ import type { FileHandle } from "node:fs/promises";
7
+ import { pipeline } from "node:stream/promises";
8
+ import type { Request, Response } from "express";
9
+
10
+ const HEX = 16;
11
+ const RANGE_NOT_SATISFIABLE = -1;
12
+
13
+ export interface ByteRange {
14
+ start: number;
15
+ end: number;
16
+ }
17
+
18
+ /** What `req.range(size, { combine: true })` returns: ranges, -1 (unsatisfiable), -2 (malformed) or nothing. */
19
+ export type ParsedRange = number | readonly ByteRange[] | undefined;
20
+
21
+ export type RangeChoice = { kind: "whole" } | { kind: "unsatisfiable" } | { kind: "part"; range: ByteRange };
22
+
23
+ const WHOLE: RangeChoice = { kind: "whole" };
24
+
25
+ /** Several ranges, a malformed header or none at all get the whole file, as `send` does. */
26
+ export function chooseByteRange(parsed: ParsedRange): RangeChoice {
27
+ if (parsed === RANGE_NOT_SATISFIABLE) return { kind: "unsatisfiable" };
28
+ const only = typeof parsed === "object" && parsed.length === 1 ? parsed[0] : undefined;
29
+ return only === undefined ? WHOLE : { kind: "part", range: only };
30
+ }
31
+
32
+ const weakEtag = (stats: Stats): string => `W/"${stats.size.toString(HEX)}-${Math.floor(stats.mtimeMs).toString(HEX)}"`;
33
+
34
+ /** The validators a conditional request is judged against, as headers carry them. */
35
+ export interface Validators {
36
+ etag: string;
37
+ lastModified: string;
38
+ }
39
+
40
+ const parseHttpDate = (value: string | undefined): number => (value === undefined ? Number.NaN : Date.parse(value));
41
+
42
+ const tokenList = (header: string): string[] =>
43
+ header
44
+ .split(",")
45
+ .map((token) => token.trim())
46
+ .filter((token) => token !== "");
47
+
48
+ const etagMatches = (token: string, etag: string): boolean => token === etag || `W/${token}` === etag || token === `W/${etag}`;
49
+
50
+ /** A Range is honoured without If-Range, or when If-Range names the current entity tag or a date no older than it — as `send` does. */
51
+ export function rangeApplies(ifRange: string | undefined, validators: Validators): boolean {
52
+ if (ifRange === undefined || ifRange === "") return true;
53
+ if (ifRange.includes('"')) return ifRange.includes(validators.etag);
54
+ return parseHttpDate(validators.lastModified) <= parseHttpDate(ifRange);
55
+ }
56
+
57
+ /** If-Match / If-Unmodified-Since that the current entity fails, answered 412 as `send` does. */
58
+ export function preconditionFailed(ifMatch: string | undefined, ifUnmodifiedSince: string | undefined, validators: Validators): boolean {
59
+ if (ifMatch !== undefined && ifMatch !== "") return ifMatch !== "*" && !tokenList(ifMatch).some((token) => etagMatches(token, validators.etag));
60
+ const unmodifiedSince = parseHttpDate(ifUnmodifiedSince);
61
+ const lastModified = parseHttpDate(validators.lastModified);
62
+ return !Number.isNaN(unmodifiedSince) && (Number.isNaN(lastModified) || lastModified > unmodifiedSince);
63
+ }
64
+
65
+ function setEntityHeaders(res: Response, stats: Stats, relPath: string): Validators {
66
+ const validators = { etag: weakEtag(stats), lastModified: stats.mtime.toUTCString() };
67
+ if (res.getHeader("Content-Type") === undefined) res.type(path.extname(relPath) || "application/octet-stream");
68
+ res.setHeader("Accept-Ranges", "bytes");
69
+ res.setHeader("Cache-Control", "public, max-age=0");
70
+ res.setHeader("Last-Modified", validators.lastModified);
71
+ res.setHeader("ETag", validators.etag);
72
+ return validators;
73
+ }
74
+
75
+ // Only a byte range is served; any other unit gets the whole file, as `send` does.
76
+ const BYTES_RANGE_RE = /^ *bytes=/;
77
+
78
+ function requestedRange(req: Request, size: number, validators: Validators): RangeChoice {
79
+ if (!BYTES_RANGE_RE.test(req.get("Range") ?? "") || !rangeApplies(req.get("If-Range"), validators)) return WHOLE;
80
+ return chooseByteRange(req.range(size, { combine: true }));
81
+ }
82
+
83
+ /** 412 / 304 / 416 carry no body, like the 404s these mounts answer. True when one was sent. */
84
+ function answeredWithoutBody(req: Request, res: Response, size: number, validators: Validators, choice: RangeChoice): boolean {
85
+ if (preconditionFailed(req.get("If-Match"), req.get("If-Unmodified-Since"), validators)) res.status(412);
86
+ else if (req.fresh) res.status(304);
87
+ else if (choice.kind === "unsatisfiable") res.status(416).setHeader("Content-Range", `bytes */${size}`);
88
+ else return false;
89
+ res.end();
90
+ return true;
91
+ }
92
+
93
+ async function streamBytes(req: Request, res: Response, handle: FileHandle, size: number, choice: RangeChoice): Promise<void> {
94
+ const { start, end } = choice.kind === "part" ? choice.range : { start: 0, end: size - 1 };
95
+ if (choice.kind === "part") res.status(206).setHeader("Content-Range", `bytes ${start}-${end}/${size}`);
96
+ res.setHeader("Content-Length", String(end - start + 1));
97
+ if (req.method === "HEAD" || size === 0) {
98
+ res.end();
99
+ return;
100
+ }
101
+ // A client that goes away mid-body rejects the pipeline; the response is already torn down then.
102
+ await pipeline(handle.createReadStream({ start, end, autoClose: false }), res).catch(() => res.destroy());
103
+ }
104
+
105
+ /** Serves `handle` as `relPath` (its extension picks the Content-Type unless one is set) and closes it. */
106
+ export async function sendFileHandle(req: Request, res: Response, handle: FileHandle, relPath: string): Promise<void> {
107
+ try {
108
+ const stats = await handle.stat();
109
+ const validators = setEntityHeaders(res, stats, relPath);
110
+ const choice = requestedRange(req, stats.size, validators);
111
+ if (!answeredWithoutBody(req, res, stats.size, validators, choice)) await streamBytes(req, res, handle, stats.size, choice);
112
+ } finally {
113
+ await handle.close();
114
+ }
115
+ }
@@ -0,0 +1,86 @@
1
+ // The image and attachment stores read and write only inside the workspace: the store folder is
2
+ // re-resolved under it on every call, so a store folder replaced by a link out is refused rather
3
+ // than becoming the root, and contents go through the verified open / write
4
+ // (plans/fix-3573-store-files.md).
5
+
6
+ import { readdir, type FileHandle } from "node:fs/promises";
7
+ import type { Dirent } from "node:fs";
8
+ import { resolveExistingWithinRoot, scopeRealpath } from "@mulmoclaude/core/files";
9
+ import { makeConfinedFileOps } from "../../plugins/confined-file-ops.js";
10
+ import { artifactScope, openArtifactFile } from "./artifactMount.js";
11
+ import { storeRelativePath, storeTrustedRoot } from "./storePaths.js";
12
+
13
+ export interface StoreFiles {
14
+ /** Bytes of a regular file in the store; throws when it is missing, a directory, or outside. */
15
+ read: (relativePath: string) => Promise<Buffer>;
16
+ /** Atomic write. Creates the store folder and partitions; `mode` is applied through the verified handle. */
17
+ write: (relativePath: string, content: Uint8Array, options?: { mode?: number }) => Promise<void>;
18
+ /** Never throws: anything but a regular file inside the store is false. */
19
+ isFile: (relativePath: string) => Promise<boolean>;
20
+ /** Entries of a folder in the store ("" for the store itself); empty when it is missing or outside. Names only:
21
+ * a folder swapped for a link mid-call can name outside entries, so read contents through `read`, never by path. */
22
+ listDir: (relativeDir: string) => Promise<Dirent[]>;
23
+ }
24
+
25
+ const rejected = (relativePath: string): Error => new Error(`path traversal rejected: ${relativePath}`);
26
+
27
+ // `getRoot()` is re-read per call because tests repoint `WORKSPACE_PATHS.<dir>` mid-run.
28
+ function storeLocation(getRoot: () => string, dirPrefix: string, relativePath: string): { root: string; trustedRoot: string; inStore: string } {
29
+ const root = getRoot();
30
+ const trustedRoot = storeTrustedRoot(root, dirPrefix);
31
+ const inStore = storeRelativePath(relativePath, dirPrefix);
32
+ if (trustedRoot === null || inStore === null) throw rejected(relativePath);
33
+ return { root, trustedRoot, inStore };
34
+ }
35
+
36
+ async function openStoreFile(getRoot: () => string, dirPrefix: string, relativePath: string): Promise<FileHandle | null> {
37
+ const { trustedRoot, inStore } = storeLocation(getRoot, dirPrefix, relativePath);
38
+ const scope = await artifactScope(trustedRoot, dirPrefix);
39
+ return scope === null ? null : openArtifactFile(scope, inStore);
40
+ }
41
+
42
+ // Only the names are check-then-use: every content read goes back through `openStoreFile`.
43
+ async function listStoreDir(getRoot: () => string, dirPrefix: string, relativeDir: string): Promise<Dirent[]> {
44
+ const trustedRoot = storeTrustedRoot(getRoot(), dirPrefix);
45
+ const inStore = relativeDir === "" ? "" : storeRelativePath(relativeDir, dirPrefix);
46
+ const scope = trustedRoot === null || inStore === null ? null : await artifactScope(trustedRoot, dirPrefix);
47
+ const scopeReal = scope === null ? null : await scopeRealpath(scope);
48
+ const dirReal = scopeReal === null || inStore === null ? null : await resolveExistingWithinRoot(scopeReal, inStore);
49
+ return dirReal === null ? [] : readdir(dirReal, { withFileTypes: true });
50
+ }
51
+
52
+ async function chmodStoreFile(getRoot: () => string, dirPrefix: string, relativePath: string, mode: number): Promise<void> {
53
+ const handle = await openStoreFile(getRoot, dirPrefix, relativePath);
54
+ if (handle === null) throw rejected(relativePath);
55
+ try {
56
+ await handle.chmod(mode);
57
+ } finally {
58
+ await handle.close();
59
+ }
60
+ }
61
+
62
+ export function makeStoreFiles(getRoot: () => string, dirPrefix: string): StoreFiles {
63
+ return {
64
+ read: async (relativePath) => {
65
+ const handle = await openStoreFile(getRoot, dirPrefix, relativePath);
66
+ if (handle === null) throw rejected(relativePath);
67
+ try {
68
+ return await handle.readFile();
69
+ } finally {
70
+ await handle.close();
71
+ }
72
+ },
73
+ write: async (relativePath, content, options = {}) => {
74
+ const { root, trustedRoot, inStore } = storeLocation(getRoot, dirPrefix, relativePath);
75
+ await makeConfinedFileOps({ root, trustedRoot }).write(inStore, content);
76
+ if (options.mode !== undefined) await chmodStoreFile(getRoot, dirPrefix, relativePath, options.mode);
77
+ },
78
+ isFile: async (relativePath) => {
79
+ const handle = await openStoreFile(getRoot, dirPrefix, relativePath).catch(() => null);
80
+ if (handle === null) return false;
81
+ await handle.close();
82
+ return true;
83
+ },
84
+ listDir: (relativeDir) => listStoreDir(getRoot, dirPrefix, relativeDir).catch(() => []),
85
+ };
86
+ }
@@ -0,0 +1,23 @@
1
+ // Path rules for the image / attachment stores, kept free of fs so both directions can be tested.
2
+
3
+ import path from "node:path";
4
+
5
+ // `C:foo` is relative to drive C:'s cwd, so `path.isAbsolute` misses it.
6
+ const WINDOWS_DRIVE_RE = /^[a-zA-Z]:/;
7
+
8
+ /** The workspace a store root `<workspace>/<dirPrefix>` lives in; null when the root does not end in `dirPrefix`. */
9
+ export function storeTrustedRoot(absRoot: string, dirPrefix: string): string | null {
10
+ const segments = dirPrefix.split("/");
11
+ const anchor = path.resolve(absRoot, ...segments.map(() => ".."));
12
+ return path.join(anchor, ...segments) === path.resolve(absRoot) ? anchor : null;
13
+ }
14
+
15
+ /** `relativePath` (workspace-relative, optionally under `dirPrefix/`) as a path inside the store; null when it
16
+ * is empty, absolute, drive-qualified, carries a NUL, or leads out of the store. */
17
+ export function storeRelativePath(relativePath: string, dirPrefix: string): string | null {
18
+ const slashed = relativePath.replace(/\\/g, "/");
19
+ const inStore = slashed.startsWith(`${dirPrefix}/`) ? slashed.slice(dirPrefix.length + 1) : slashed;
20
+ if (inStore === "" || inStore.includes("\0") || path.posix.isAbsolute(inStore) || path.isAbsolute(inStore) || WINDOWS_DRIVE_RE.test(inStore)) return null;
21
+ const normalised = path.posix.normalize(inStore);
22
+ return normalised === "." || normalised === ".." || normalised.startsWith("../") ? null : normalised;
23
+ }
@@ -5,12 +5,12 @@
5
5
  // host produces here. Kept a leaf util (no collection/remote-view imports) so
6
6
  // the builder in remoteView.ts is the only wiring point.
7
7
  //
8
- // Reads are workspace-containment-guarded (resolveWithinRoot, same discipline as
9
- // image-store.ts). Results are cached by (path, mtime, maxEdge) so repeated
8
+ // Reads go through the verified handle (#3573), so a path swapped mid-call cannot
9
+ // reach outside the workspace. Results are cached by (path, mtime, maxEdge) so repeated
10
10
  // pages / "load more" scrolls never re-decode the same source.
11
- import { readFile, realpath, stat } from "fs/promises";
11
+ import type { FileHandle } from "fs/promises";
12
12
  import { workspacePath } from "../../workspace/paths.js";
13
- import { resolveWithinRoot } from "./safe.js";
13
+ import { artifactScope, openArtifactFile } from "./artifactMount.js";
14
14
  import { log } from "../../system/logger/index.js";
15
15
 
16
16
  /** Decode → downscale to fit `maxEdge` (never enlarge) → re-encode JPEG.
@@ -62,6 +62,21 @@ export function clearThumbnailCache(): void {
62
62
  cache.clear();
63
63
  }
64
64
 
65
+ async function thumbnailFromHandle(handle: FileHandle, relPath: string, maxEdge: number, resize: ResizeToJpeg): Promise<string | null> {
66
+ try {
67
+ const info = await handle.stat();
68
+ const cached = cacheGet(relPath, info.mtimeMs, maxEdge);
69
+ if (cached) return cached;
70
+ const out = await resize(await handle.readFile(), maxEdge);
71
+ const dataUrl = `data:image/jpeg;base64,${out.toString("base64")}`;
72
+ cacheSet(relPath, { mtimeMs: info.mtimeMs, maxEdge, dataUrl });
73
+ return dataUrl;
74
+ } catch (err) {
75
+ log.warn("thumbnail", "resolve failed", { relPath, error: String(err) });
76
+ return null;
77
+ }
78
+ }
79
+
65
80
  /** Resolve a workspace-relative image path to a downscaled JPEG `data:` URL, or
66
81
  * `null` when the path escapes the workspace, is missing, or can't be decoded —
67
82
  * the caller then leaves the field as its original path (rendered as a
@@ -70,26 +85,13 @@ export function clearThumbnailCache(): void {
70
85
  export function createThumbnailResolver(resize: ResizeToJpeg = sharpResize) {
71
86
  return async function resolveThumbnail(relPath: string, maxEdge: number): Promise<string | null> {
72
87
  if (typeof relPath !== "string" || relPath.length === 0) return null;
73
- let root: string;
74
- try {
75
- root = await realpath(workspacePath);
76
- } catch {
77
- return null;
78
- }
79
- const abs = resolveWithinRoot(root, relPath);
80
- if (!abs) return null;
81
- const info = await stat(abs).catch(() => null);
82
- if (!info?.isFile()) return null;
83
- const cached = cacheGet(relPath, info.mtimeMs, maxEdge);
84
- if (cached) return cached;
88
+ const scope = await artifactScope(workspacePath, "").catch(() => null);
89
+ const handle = scope === null ? null : await openArtifactFile(scope, relPath).catch(() => null);
90
+ if (handle === null) return null;
85
91
  try {
86
- const out = await resize(await readFile(abs), maxEdge);
87
- const dataUrl = `data:image/jpeg;base64,${out.toString("base64")}`;
88
- cacheSet(relPath, { mtimeMs: info.mtimeMs, maxEdge, dataUrl });
89
- return dataUrl;
90
- } catch (err) {
91
- log.warn("thumbnail", "resolve failed", { relPath, error: String(err) });
92
- return null;
92
+ return await thumbnailFromHandle(handle, relPath, maxEdge, resize);
93
+ } finally {
94
+ await handle.close();
93
95
  }
94
96
  };
95
97
  }
@@ -1,18 +1,19 @@
1
- // Exclusive-create write for dropped-file uploads (#2270).
1
+ // Exclusive-create write for new files: dropped-file uploads (#2270) and the File Explorer's "New file".
2
2
  //
3
3
  // Route handlers don't call raw `fs` — this is the domain module for that
4
4
  // write. It deliberately does NOT go through `writeFileAtomic`: that writes a
5
5
  // temp file and renames over the destination, which would silently clobber an
6
6
  // existing file. The upload route's non-clobbering rename loop is built on the
7
- // `wx` flag failing with EEXIST instead.
7
+ // create failing with EEXIST instead.
8
8
 
9
- import { mkdir, writeFile } from "fs/promises";
9
+ import { mkdir } from "fs/promises";
10
10
  import path from "path";
11
+ import { createFileVerifiedInScope } from "@mulmoclaude/core/files";
11
12
 
12
- /** Create `absPath` holding `bytes`, creating parents as needed. Throws with
13
- * `code: "EEXIST"` when the file is already there — the caller's cue to try
14
- * the next `name (n).ext` candidate. */
15
- export async function writeNewFileExclusive(absPath: string, bytes: Buffer): Promise<void> {
13
+ /** Create `absPath` holding `content`, creating parents as needed. `workspaceRoot` is the async realpath of the
14
+ * workspace: the new file is proven to sit inside it before any byte is written (#3573). Throws with
15
+ * `code: "EEXIST"` when the file is already there — the caller's cue to try the next `name (n).ext` candidate. */
16
+ export async function writeNewFileExclusive(workspaceRoot: string, absPath: string, content: string | Uint8Array): Promise<void> {
16
17
  await mkdir(path.dirname(absPath), { recursive: true });
17
- await writeFile(absPath, bytes, { flag: "wx" });
18
+ await createFileVerifiedInScope({ trustedReal: workspaceRoot, scopeWithinTrusted: "" }, path.dirname(absPath), path.basename(absPath), content);
18
19
  }
@@ -16,22 +16,27 @@
16
16
  // startup as an import side effect.
17
17
 
18
18
  import { readFile as fsReadFile } from "fs/promises";
19
- import { resolveWithinRoot } from "../files/safe.js";
19
+ import type { VerifiedScope } from "@mulmoclaude/core/files";
20
+ import { openArtifactFile } from "../files/artifactMount.js";
20
21
  import { injectImageRepairScript } from "../../../src/utils/image/imageRepairInlineScript.js";
21
22
  import { injectHeightReporterScript } from "../../../src/utils/html/iframeHeightReporterScript.js";
22
23
 
23
- /** Read an HTML artifact file (under `htmlsRoot`) and splice the
24
- * image-self-repair script before its closing `</body>`. Returns
25
- * the spliced HTML on success, `null` when the file can't be
26
- * resolved (escapes the root) or read (missing / unreadable).
27
- *
28
- * `htmlsRoot` MUST already be a realpath — `resolveWithinRoot`
29
- * compares against it strictly. The middleware in `server/index.ts`
30
- * passes the cached `getHtmlsDirReal()` result, which is a realpath. */
31
- export async function readAndInjectHtmlArtifact(htmlsRoot: string, relPath: string): Promise<string | null> {
32
- const abs = resolveWithinRoot(htmlsRoot, relPath);
33
- if (!abs) return null;
34
- return readAndInjectHtmlFile(abs);
24
+ const spliceHelperScripts = (raw: string): string => injectHeightReporterScript(injectImageRepairScript(raw));
25
+
26
+ /** Read an HTML artifact under `scope` through a verified handle and splice the helper scripts.
27
+ * Null when the file is missing, outside the scope, not a regular file, or unreadable. */
28
+ export async function readAndInjectHtmlArtifact(scope: VerifiedScope, relPath: string): Promise<string | null> {
29
+ try {
30
+ const handle = await openArtifactFile(scope, relPath);
31
+ if (handle === null) return null;
32
+ try {
33
+ return spliceHelperScripts(await handle.readFile("utf8"));
34
+ } finally {
35
+ await handle.close();
36
+ }
37
+ } catch {
38
+ return null;
39
+ }
35
40
  }
36
41
 
37
42
  /** Same splice, for a page the caller has ALREADY resolved to an absolute path.
@@ -45,5 +50,5 @@ export async function readAndInjectHtmlFile(absPath: string): Promise<string | n
45
50
  } catch {
46
51
  return null;
47
52
  }
48
- return injectHeightReporterScript(injectImageRepairScript(raw));
53
+ return spliceHelperScripts(raw);
49
54
  }