mulmoclaude 2.10.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 (34) 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-CmMNIT1E.js → marp-DvbfD9EO.js} +1 -1
  5. package/client/assets/material-symbols-outlined-DzTrJqFk.woff2 +0 -0
  6. package/client/assets/{feat-3497-Cwr8t4l4.js → mulmoclaude3-BUmaA-ZX.js} +588 -582
  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/build/mcp-server.mjs +617 -608
  24. package/server/events/pub-sub/handshakeAuth.ts +3 -5
  25. package/server/events/pub-sub/index.ts +22 -4
  26. package/server/index.ts +3 -1
  27. package/server/system/env.ts +4 -0
  28. package/server/system/logs/aaa +737 -0
  29. package/server/system/logs/bb +446 -0
  30. package/src/components/SessionHistoryRow.vue +11 -1
  31. package/src/utils/html/customViewSrcdoc.ts +5 -0
  32. package/client/assets/feat-3497-DEfIEPf6.css +0 -2
  33. package/client/assets/material-symbols-outlined-Bn5lkljl.woff2 +0 -0
  34. package/client/assets/vue-i18n-BHWgmfE3.js +0 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mulmoclaude",
3
- "version": "2.10.0",
3
+ "version": "2.11.0",
4
4
  "description": "MulmoClaude — GUI-chat with Claude Code + long-term memory. One command to start.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,38 +21,38 @@
21
21
  "sandbox-entrypoint.sh"
22
22
  ],
23
23
  "dependencies": {
24
- "@google/genai": "^2.30.0",
24
+ "@google/genai": "^2.31.0",
25
25
  "@gui-chat-plugin/browse": "^2.1.0",
26
26
  "@gui-chat-plugin/camera": "^2.1.0",
27
27
  "@gui-chat-plugin/google-map": "^2.1.0",
28
28
  "@gui-chat-plugin/mindmap": "^2.1.0",
29
29
  "@gui-chat-plugin/shapescript": "^8.2.2",
30
- "@gui-chat-plugin/spreadsheet": "^4.3.0",
30
+ "@gui-chat-plugin/spreadsheet": "^5.0.1",
31
31
  "@marp-team/marp-core": "^4.4.0",
32
- "@mulmobridge/chat-service": "^2.0.0",
32
+ "@mulmobridge/chat-service": "^2.1.0",
33
33
  "@mulmobridge/client": "^1.5.0",
34
34
  "@mulmobridge/protocol": "^1.1.0",
35
35
  "@mulmobridge/web-push": "^1.1.0",
36
36
  "@mulmocast/deck": "^2.1.0",
37
- "@mulmocast/types": "^2.21.0",
37
+ "@mulmocast/types": "^2.24.0",
38
38
  "@mulmochat-plugin/quiz": "^2.1.0",
39
39
  "@mulmochat-plugin/ui-image": "^0.4.1",
40
- "@mulmoclaude/accounting-plugin": "^4.0.2",
41
- "@mulmoclaude/chart-plugin": "^4.6.2",
42
- "@mulmoclaude/collection-plugin": "^5.5.0",
40
+ "@mulmoclaude/accounting-plugin": "^5.0.0",
41
+ "@mulmoclaude/chart-plugin": "^5.0.0",
42
+ "@mulmoclaude/collection-plugin": "^6.0.0",
43
43
  "@mulmoclaude/common": "^1.5.0",
44
- "@mulmoclaude/core": "^5.14.0",
44
+ "@mulmoclaude/core": "^6.0.0",
45
45
  "@mulmoclaude/form-plugin": "^2.2.0",
46
- "@mulmoclaude/google-plugin": "^4.1.0",
47
- "@mulmoclaude/html-plugin": "^5.2.0",
48
- "@mulmoclaude/markdown-plugin": "^5.2.0",
46
+ "@mulmoclaude/google-plugin": "^5.0.0",
47
+ "@mulmoclaude/html-plugin": "^6.0.0",
48
+ "@mulmoclaude/markdown-plugin": "^6.0.0",
49
49
  "@mulmoclaude/markdown-utils": "^3.0.2",
50
- "@mulmoclaude/mulmoscript-plugin": "^5.5.0",
50
+ "@mulmoclaude/mulmoscript-plugin": "^6.0.0",
51
51
  "@mulmoclaude/spotify-plugin": "^2.0.3",
52
52
  "@mulmoclaude/x-plugin": "^1.0.4",
53
53
  "@receptron/task-scheduler": "^1.0.3",
54
54
  "cors": "^2.8.6",
55
- "dotenv": "^18.0.8",
55
+ "dotenv": "^18.0.9",
56
56
  "exifr": "^7.1.3",
57
57
  "express": "^5.3.0",
58
58
  "fast-xml-parser": "^5.11.2",
@@ -60,22 +60,22 @@
60
60
  "graphai": "^2.0.18",
61
61
  "gui-chat-protocol": "^2.3.0",
62
62
  "heic-convert": "^2.1.0",
63
- "ignore": "^7.0.13",
63
+ "ignore": "^7.0.14",
64
64
  "js-yaml": "^5.5.0",
65
65
  "jszip": "^3.10.2",
66
66
  "kenteiscript": "^0.2.0",
67
67
  "mammoth": "^1.13.0",
68
- "marked": "^18.1.1",
69
- "mulmocast": "^2.23.0",
70
- "node-html-parser": "^9.0.5",
71
- "puppeteer": "^25.15.0",
68
+ "marked": "^18.1.3",
69
+ "mulmocast": "^2.24.0",
70
+ "node-html-parser": "^9.0.6",
71
+ "puppeteer": "^25.16.0",
72
72
  "sharp": "^0.35.5",
73
73
  "socket.io": "^4.8.4",
74
74
  "socket.io-client": "^4.8.4",
75
75
  "tsx": "^4.23.15",
76
76
  "uuid": "^14.0.3",
77
77
  "which": "^7.0.0",
78
- "ws": "^8.22.0",
78
+ "ws": "^8.22.1",
79
79
  "zod": "^4.6.7"
80
80
  },
81
81
  "optionalDependencies": {
@@ -9,12 +9,22 @@
9
9
  // home so the existing test suite under test/agent/ keeps working
10
10
  // unchanged.
11
11
 
12
- import { spawn, type ChildProcessByStdio } from "child_process";
12
+ import { spawn, type ChildProcess, type ChildProcessByStdio } from "child_process";
13
13
  import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
14
- import type { Readable, Writable } from "stream";
15
- import { buildCliArgs, buildDockerSpawnArgs, buildUserMessageLine, resolveSystemPromptPaths, type CliArgsParams } from "../config.js";
14
+ import { Writable, type Readable } from "stream";
15
+ import {
16
+ buildCliArgs,
17
+ buildDockerSpawnArgs,
18
+ buildUserMessageLine,
19
+ resolveSystemPromptPaths,
20
+ SANDBOX_IMAGE,
21
+ type CliArgsParams,
22
+ type DockerSpawnArgsParams,
23
+ } from "../config.js";
16
24
  import { writeFileAtomic } from "../../utils/files/atomic.js";
17
25
  import { resolveSandboxAuth } from "../sandboxMounts.js";
26
+ import { ENV_FILE_FD, resolveSandboxEnv } from "../sandboxEnv.js";
27
+ import { dockerEnvNames, dockerMountSources, ENTRYPOINT_ENV_NAMES, IMAGE_ENV_NAMES, insertDockerOptions } from "../sandboxEnvPlan.js";
18
28
  import { pluginLedgerMountArgs, removePluginLedgerStaging, withPluginLedgerCleanup } from "../pluginLedgerMount.js";
19
29
  import { getCachedReferenceDirs, referenceDirMountArgs } from "../../workspace/reference-dirs.js";
20
30
  import { createStreamParser, type AgentEvent, type RawStreamEvent } from "../stream.js";
@@ -58,7 +68,7 @@ function spawnClaude(useDocker: boolean, workspacePath: string, cliArgs: string[
58
68
  const pluginLedger = pluginLedgerMountArgs({ platform: process.platform });
59
69
  const { stagingDir } = pluginLedger;
60
70
  return withPluginLedgerCleanup(stagingDir, () => {
61
- const dockerArgs = buildDockerSpawnArgs({
71
+ const sandbox = withSandboxEnv({
62
72
  workspacePath,
63
73
  cliArgs,
64
74
  chatSessionId,
@@ -68,7 +78,7 @@ function spawnClaude(useDocker: boolean, workspacePath: string, cliArgs: string[
68
78
  sandboxAuthArgs: [...sandboxAuth.args, ...refDirArgs, ...pluginLedger.args],
69
79
  sshAgentForward: env.sandboxSshAgentForward,
70
80
  });
71
- const proc = spawn("docker", dockerArgs, { stdio: ["pipe", "pipe", "pipe"] });
81
+ const proc = spawnDocker(sandbox.dockerArgs, sandbox.envFileText);
72
82
  // The container bind-mounts the staged ledgers, so they have to outlive its
73
83
  // start — `close` is the first moment they are certainly unused.
74
84
  if (stagingDir !== null) proc.once("close", () => removePluginLedgerStaging(stagingDir));
@@ -76,6 +86,41 @@ function spawnClaude(useDocker: boolean, workspacePath: string, cliArgs: string[
76
86
  });
77
87
  }
78
88
 
89
+ const isClaudeProc = (proc: ChildProcess): proc is ClaudeProc => proc.stdin !== null && proc.stdout !== null && proc.stderr !== null;
90
+
91
+ // With an env file, docker reads it from a pipe on fd 3 (`--env-file /dev/fd/3`),
92
+ // so the checked values never touch the disk. A docker that exits before reading
93
+ // closes the pipe; that EPIPE is the run's failure to report, not the server's.
94
+ function spawnDocker(dockerArgs: string[], envFileText: string | null): ClaudeProc {
95
+ if (envFileText === null) return spawn("docker", dockerArgs, { stdio: ["pipe", "pipe", "pipe"] });
96
+ const proc = spawn("docker", dockerArgs, { stdio: ["pipe", "pipe", "pipe", "pipe"] });
97
+ const envFilePipe = proc.stdio[ENV_FILE_FD];
98
+ // Without a writable fd 3, docker would wait on `/dev/fd/3` forever.
99
+ if (!(envFilePipe instanceof Writable) || !isClaudeProc(proc)) {
100
+ proc.kill();
101
+ throw new Error("docker was spawned without its stdio pipes");
102
+ }
103
+ envFilePipe.on("error", (error) => log.warn("sandbox", "docker did not read the SANDBOX_ENV_FILE pipe", { error: errorMessage(error) }));
104
+ envFilePipe.end(envFileText);
105
+ return proc;
106
+ }
107
+
108
+ // The reserved names and the mounted host paths are read off the argv the
109
+ // sandbox would get anyway, so a variable or mount added later is covered
110
+ // without a list to keep in step; the entrypoint's inputs and the image's own
111
+ // variables are added because the argv does not carry them.
112
+ function withSandboxEnv(params: DockerSpawnArgsParams): { dockerArgs: string[]; envFileText: string | null } {
113
+ const dockerArgs = buildDockerSpawnArgs(params);
114
+ const sandboxEnv = resolveSandboxEnv({
115
+ names: env.sandboxEnvNames,
116
+ envFilePath: env.sandboxEnvFile,
117
+ hostEnv: process.env,
118
+ reservedNames: new Set([...dockerEnvNames(dockerArgs, SANDBOX_IMAGE), ...ENTRYPOINT_ENV_NAMES, ...IMAGE_ENV_NAMES]),
119
+ mountedHostPaths: dockerMountSources(dockerArgs, SANDBOX_IMAGE),
120
+ });
121
+ return { dockerArgs: insertDockerOptions(dockerArgs, SANDBOX_IMAGE, sandboxEnv.args), envFileText: sandboxEnv.envFileText };
122
+ }
123
+
79
124
  // Counts the tools a turn ran FROM THE BUILT-IN BROKER. Scoped to
80
125
  // `mcp__mulmoclaude__` rather than `mcp__`, because the beacon only speaks for
81
126
  // that broker: a working `mcp__github__…` call says nothing about whether OUR
@@ -1051,6 +1051,8 @@ export function dockerBindMountArgs(opts: DockerBindMountOpts): string[] {
1051
1051
  ];
1052
1052
  }
1053
1053
 
1054
+ export const SANDBOX_IMAGE = "mulmoclaude-sandbox";
1055
+
1054
1056
  export function buildDockerSpawnArgs(params: DockerSpawnArgsParams): string[] {
1055
1057
  const {
1056
1058
  workspacePath,
@@ -1112,7 +1114,7 @@ export function buildDockerSpawnArgs(params: DockerSpawnArgsParams): string[] {
1112
1114
  ...dockerBindMountArgs({ projectRoot, packageRoot, workspacePath, homeDir, packagesMount, platform }),
1113
1115
  ...sandboxAuthArgs,
1114
1116
  ...extraHosts,
1115
- "mulmoclaude-sandbox",
1117
+ SANDBOX_IMAGE,
1116
1118
  "claude",
1117
1119
  ...cliArgs,
1118
1120
  ];
@@ -0,0 +1,148 @@
1
+ // Reads `SANDBOX_ENV_FILE` and logs the outcome of `planSandboxEnv` (#3617). The
2
+ // decision itself lives in `sandboxEnvPlan.ts`.
3
+ //
4
+ // The accepted file lines reach docker through a pipe, never through a file:
5
+ // the caller writes `envFileText` to the child's fd 3 and docker reads it as
6
+ // `--env-file /dev/fd/3`. A copy on disk would need a place only this user can
7
+ // read on every platform, and a cleanup that survives a killed server.
8
+
9
+ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync, type Stats } from "node:fs";
10
+ import path from "node:path";
11
+ import { log } from "../system/logger/index.js";
12
+ import { errorMessage } from "../utils/errors.js";
13
+ import type { Platform } from "./config.js";
14
+ import { pathAncestors, planSandboxEnv, type EnvFileInput, type SandboxEnvPlan } from "./sandboxEnvPlan.js";
15
+
16
+ // An env file is a handful of lines; anything this large is not one.
17
+ const ENV_FILE_MAX_BYTES = 64 * 1024;
18
+
19
+ /** The child's file descriptor that carries the env file. */
20
+ export const ENV_FILE_FD = 3;
21
+ const ENV_FILE_FD_PATH = `/dev/fd/${ENV_FILE_FD}`;
22
+
23
+ // Docker refuses the whole env file on invalid UTF-8, where `toString` would
24
+ // quietly substitute U+FFFD and hand docker a file that fails the run.
25
+ const STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true });
26
+
27
+ function readBoundedText(handle: number, size: number): string {
28
+ const buffer = Buffer.alloc(size);
29
+ const bytes = readSync(handle, buffer, 0, size, 0);
30
+ return STRICT_UTF8.decode(buffer.subarray(0, bytes));
31
+ }
32
+
33
+ // `.native`: the JS `realpathSync` keeps the caller's letter case, so on a
34
+ // case-insensitive volume `/Users/ME/ws` and `/Users/me/ws` would compare as two
35
+ // places. The native call returns the on-disk spelling; folding case ourselves
36
+ // would be wrong on a case-sensitive volume.
37
+ const canonicalPath = (target: string): string => realpathSync.native(target);
38
+
39
+ const realpathOr = (target: string): string => {
40
+ try {
41
+ return canonicalPath(target);
42
+ } catch {
43
+ return path.resolve(target);
44
+ }
45
+ };
46
+
47
+ // `..` as a whole segment, not as a prefix: `..secrets.env` is a file INSIDE.
48
+ const isInside = (child: string, parent: string): boolean => {
49
+ const relative = path.relative(parent, child);
50
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
51
+ };
52
+
53
+ // Every step of the path, as written and as resolved, must lie outside every
54
+ // mount: a symlink inside one is the agent's to retarget — at the user's own
55
+ // file, or at any host file whose lines would then reach the container.
56
+ function reachableFromSandbox(paths: readonly string[], mountedHostPaths: readonly string[]): boolean {
57
+ const roots = mountedHostPaths.flatMap((mounted) => [path.resolve(mounted), realpathOr(mounted)]);
58
+ const steps = paths.flatMap((target) => pathAncestors(target, path.sep)).flatMap((step) => [step, realpathOr(step)]);
59
+ return steps.some((step) => roots.some((root) => isInside(step, root)));
60
+ }
61
+
62
+ type StatAtPath = (target: string) => Stats;
63
+
64
+ // The opened object must be the one now at the resolved path, so a swap between
65
+ // the checks and the read cannot change what is passed. A second hard link may
66
+ // sit inside a mount, where no path check can see it, so the file must have one.
67
+ function checkOpenedFile(opened: Stats, absolutePath: string, mountedHostPaths: readonly string[], statAtPath: StatAtPath): void {
68
+ if (!opened.isFile()) throw new Error("not a regular file");
69
+ if (opened.size > ENV_FILE_MAX_BYTES) throw new Error(`larger than ${ENV_FILE_MAX_BYTES} bytes`);
70
+ if (opened.nlink > 1) throw new Error("has more than one hard link");
71
+ const realPath = canonicalPath(absolutePath);
72
+ const atRealPath = statAtPath(realPath);
73
+ if (atRealPath.dev !== opened.dev || atRealPath.ino !== opened.ino) throw new Error("changed while being read");
74
+ if (reachableFromSandbox([absolutePath, realPath], mountedHostPaths)) throw new Error("inside a directory mounted into the sandbox");
75
+ }
76
+
77
+ // The descriptor opened first is the only one read. `O_NONBLOCK` so a FIFO opens
78
+ // at once and is then refused by `isFile` instead of blocking the spawn; absent
79
+ // on Windows, it falls out of the mask.
80
+ function readCheckedFile(absolutePath: string, mountedHostPaths: readonly string[], statAtPath: StatAtPath): string {
81
+ const handle = openSync(absolutePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
82
+ try {
83
+ const opened = fstatSync(handle);
84
+ checkOpenedFile(opened, absolutePath, mountedHostPaths, statAtPath);
85
+ return readBoundedText(handle, opened.size);
86
+ } finally {
87
+ closeSync(handle);
88
+ }
89
+ }
90
+
91
+ /** The file, unless the container can reach it: the agent could then see every
92
+ * value — refused ones included — and rewrite the next turn's. `statAtPath` is a
93
+ * test seam for a file swapped between the open and the check. */
94
+ export function readEnvFileInput(
95
+ filePath: string | undefined,
96
+ mountedHostPaths: readonly string[],
97
+ statAtPath: StatAtPath = (target) => statSync(target),
98
+ ): EnvFileInput | null {
99
+ if (filePath === undefined || filePath === "") return null;
100
+ const absolutePath = path.resolve(filePath);
101
+ try {
102
+ return { path: absolutePath, text: readCheckedFile(absolutePath, mountedHostPaths, statAtPath) };
103
+ } catch (err) {
104
+ return { path: absolutePath, error: errorMessage(err) };
105
+ }
106
+ }
107
+
108
+ function logSandboxEnvPlan(plan: SandboxEnvPlan, envFile: EnvFileInput | null): void {
109
+ if (envFile !== null && "error" in envFile) {
110
+ log.warn("sandbox", "SANDBOX_ENV_FILE not passed to the container", { path: envFile.path, error: envFile.error });
111
+ }
112
+ if (plan.skipped.length > 0) log.warn("sandbox", "sandbox env entries ignored", { skipped: plan.skipped });
113
+ }
114
+
115
+ export interface ResolveSandboxEnvParams {
116
+ names: readonly string[];
117
+ envFilePath: string | undefined;
118
+ hostEnv: Readonly<Record<string, string | undefined>>;
119
+ reservedNames: ReadonlySet<string>;
120
+ mountedHostPaths: readonly string[];
121
+ /** Test seam; production gets the host platform. */
122
+ platform?: Platform | undefined;
123
+ }
124
+
125
+ export interface ResolvedSandboxEnv {
126
+ /** `--env-file /dev/fd/3` (when there is file text) then `-e NAME` pairs, for just before the image. */
127
+ args: string[];
128
+ /** What the caller MUST write to the child's `ENV_FILE_FD`, or null for no extra fd. */
129
+ envFileText: string | null;
130
+ }
131
+
132
+ // Windows has no `/dev/fd`; until it has a pipe of its own, the file is not
133
+ // passed there rather than written to disk.
134
+ function envFileForPlatform(envFilePath: string | undefined, platform: Platform): string | undefined {
135
+ if (envFilePath === undefined || envFilePath === "" || platform !== "win32") return envFilePath;
136
+ log.warn("sandbox", "SANDBOX_ENV_FILE is not supported on Windows hosts; use SANDBOX_ENV to pass variables by name");
137
+ return undefined;
138
+ }
139
+
140
+ export function resolveSandboxEnv(params: ResolveSandboxEnvParams): ResolvedSandboxEnv {
141
+ const envFile = readEnvFileInput(envFileForPlatform(params.envFilePath, params.platform ?? process.platform), params.mountedHostPaths);
142
+ const plan = planSandboxEnv({ names: params.names, envFile, hostEnv: params.hostEnv, reservedNames: params.reservedNames });
143
+ logSandboxEnvPlan(plan, envFile);
144
+ const passedNames = [...new Set([...plan.fileNames, ...plan.namedNames])];
145
+ if (passedNames.length > 0) log.info("sandbox", "host env passed to container", { names: passedNames });
146
+ const fileArgs = plan.envFileText === null ? [] : ["--env-file", ENV_FILE_FD_PATH];
147
+ return { args: [...fileArgs, ...plan.nameArgs], envFileText: plan.envFileText };
148
+ }
@@ -0,0 +1,188 @@
1
+ // Which extra environment variables reach the Docker sandbox (#3617). Pure: the
2
+ // caller reads the env file and the host environment and injects them.
3
+ //
4
+ // Values never enter the docker argv. `SANDBOX_ENV` names become `-e NAME`, which
5
+ // docker resolves from its own environment — the server's, inherited unchanged.
6
+ // File entries are not copied into that environment either, because it also
7
+ // configures the docker CLI itself (`DOCKER_HOST`, `HOME`, …). Instead the lines
8
+ // that pass are re-serialised into `envFileText`, which the caller hands docker as
9
+ // its `--env-file`: docker then reads exactly what was checked, not the user's
10
+ // file again after it might have changed.
11
+
12
+ export type SandboxEnvSource = "SANDBOX_ENV" | "SANDBOX_ENV_FILE";
13
+
14
+ export type SandboxEnvSkipReason = "invalid-name" | "invalid-value" | "reserved" | "unset-on-host";
15
+
16
+ export interface SandboxEnvSkip {
17
+ source: SandboxEnvSource;
18
+ /** The variable name, or `#<position>` / `line <n>` for an invalid one: an
19
+ * invalid entry is often a mistyped assignment, and its text can hold a secret. */
20
+ entry: string;
21
+ reason: SandboxEnvSkipReason;
22
+ }
23
+
24
+ export interface EnvFileEntry {
25
+ name: string;
26
+ /** A bare `NAME` line: docker takes the value from its own environment. */
27
+ bare: boolean;
28
+ /** The line as docker would read it, leading whitespace dropped. */
29
+ line: string;
30
+ lineNumber: number;
31
+ }
32
+
33
+ export type EnvFileInput = { path: string; text: string } | { path: string; error: string };
34
+
35
+ export interface SandboxEnvInput {
36
+ names: readonly string[];
37
+ envFile: EnvFileInput | null;
38
+ hostEnv: Readonly<Record<string, string | undefined>>;
39
+ reservedNames: ReadonlySet<string>;
40
+ }
41
+
42
+ export interface SandboxEnvPlan {
43
+ /** `-e NAME` pairs for `SANDBOX_ENV`, to follow any `--env-file` so they win. */
44
+ nameArgs: string[];
45
+ /** The accepted env-file lines, or null when no file line passes. */
46
+ envFileText: string | null;
47
+ /** Names each source passes, for logging. Never values. */
48
+ fileNames: string[];
49
+ namedNames: string[];
50
+ skipped: SandboxEnvSkip[];
51
+ }
52
+
53
+ // Variables `sandbox-entrypoint.sh` reads even on runs whose argv does not set
54
+ // them — `HOST_UID` alone switches the entrypoint into its root-only branch.
55
+ export const ENTRYPOINT_ENV_NAMES: readonly string[] = ["HOST_UID", "HOST_GID", "SANDBOX_SSH_ALLOWED_HOSTS", "SSH_AUTH_SOCK"];
56
+
57
+ // Variables the sandbox image sets (`docker image inspect … .Config.Env`). The
58
+ // entrypoint and the CLI are started by bare name, so a host `PATH` replacing the
59
+ // image's stops the container from starting at all.
60
+ export const IMAGE_ENV_NAMES: readonly string[] = ["PATH", "NODE_VERSION", "YARN_VERSION"];
61
+
62
+ // Docker's own rule for an env-file name: not empty, no whitespace. `=` cannot
63
+ // occur in a parsed name, and in a `SANDBOX_ENV` entry it would turn `-e NAME`
64
+ // into an assignment whose value sits in the argv.
65
+ export const isEnvName = (name: string): boolean => name !== "" && !/[\s=]/.test(name);
66
+
67
+ // Mirrors docker's `--env-file` reader: lines split on LF with one trailing CR
68
+ // dropped (the last line's too, newline or not), leading whitespace dropped,
69
+ // blank and `#` lines skipped, the name ending at the first `=`, and a bare
70
+ // `NAME` taking the host's value.
71
+ function envFileEntry(rawLine: string, lineNumber: number): EnvFileEntry | null {
72
+ const line = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).trimStart();
73
+ if (line === "" || line.startsWith("#")) return null;
74
+ const separator = line.indexOf("=");
75
+ const name = separator === -1 ? line : line.slice(0, separator);
76
+ return { name, bare: separator === -1, line, lineNumber };
77
+ }
78
+
79
+ export function parseEnvFileText(text: string): EnvFileEntry[] {
80
+ return text.split("\n").flatMap((rawLine, index) => envFileEntry(rawLine, index + 1) ?? []);
81
+ }
82
+
83
+ /** Every variable name a `-e` / `--env` flag sets before `image` in a docker argv. */
84
+ export function dockerEnvNames(dockerArgs: readonly string[], image: string): Set<string> {
85
+ const options = optionsBeforeImage(dockerArgs, image);
86
+ const values = options.filter((_, index) => index > 0 && (options[index - 1] === "-e" || options[index - 1] === "--env"));
87
+ return new Set(values.map((value) => value.split("=", 1).join("")));
88
+ }
89
+
90
+ function optionsBeforeImage(dockerArgs: readonly string[], image: string): readonly string[] {
91
+ const imageIndex = dockerArgs.indexOf(image);
92
+ return imageIndex === -1 ? dockerArgs : dockerArgs.slice(0, imageIndex);
93
+ }
94
+
95
+ // `-v SOURCE:TARGET[:ro]`. A source never holds `:` (`dockerMountArgs` moves such
96
+ // a path to `--mount`), except a Windows drive letter, which is kept.
97
+ function volumeSource(value: string): string {
98
+ const drive = /^[A-Za-z]:/.test(value) ? value.slice(0, 2) : "";
99
+ const rest = value.slice(drive.length);
100
+ const end = rest.indexOf(":");
101
+ return drive + (end === -1 ? rest : rest.slice(0, end));
102
+ }
103
+
104
+ function mountSource(value: string): string | null {
105
+ const field = value.split(",").find((part) => part.startsWith("source=") || part.startsWith("src="));
106
+ return field === undefined ? null : field.slice(field.indexOf("=") + 1);
107
+ }
108
+
109
+ /** The host side of every `-v` / `--mount` before `image`: what the container can read. */
110
+ export function dockerMountSources(dockerArgs: readonly string[], image: string): string[] {
111
+ const options = optionsBeforeImage(dockerArgs, image);
112
+ return options.flatMap((value, index): string[] => {
113
+ const flag = options[index - 1];
114
+ if (flag === "-v" || flag === "--volume") return [volumeSource(value)];
115
+ const source = flag === "--mount" ? mountSource(value) : null;
116
+ return source === null ? [] : [source];
117
+ });
118
+ }
119
+
120
+ /** Every path from the root down to `absolutePath` itself: `/a/b/f` → `/`, `/a`, `/a/b`, `/a/b/f`. */
121
+ export function pathAncestors(absolutePath: string, sep: string): string[] {
122
+ const root = absolutePath.startsWith(sep) ? sep : (absolutePath.split(sep)[0] ?? "") + sep;
123
+ const segments = absolutePath.slice(root.length).split(sep).filter(Boolean);
124
+ return [root, ...segments.map((_, index) => root + segments.slice(0, index + 1).join(sep))];
125
+ }
126
+
127
+ /** `extra` spliced in just before `image`, i.e. after every option already set. */
128
+ export function insertDockerOptions(dockerArgs: readonly string[], image: string, extra: readonly string[]): string[] {
129
+ const imageIndex = dockerArgs.indexOf(image);
130
+ if (imageIndex === -1) throw new Error(`docker argv has no image "${image}"`);
131
+ return [...dockerArgs.slice(0, imageIndex), ...extra, ...dockerArgs.slice(imageIndex)];
132
+ }
133
+
134
+ interface Verdict<T> {
135
+ item: T;
136
+ skip: SandboxEnvSkip | null;
137
+ }
138
+
139
+ function splitVerdicts<T>(verdicts: Verdict<T>[]): { accepted: T[]; skipped: SandboxEnvSkip[] } {
140
+ return {
141
+ accepted: verdicts.flatMap((verdict) => (verdict.skip === null ? [verdict.item] : [])),
142
+ skipped: verdicts.flatMap((verdict) => (verdict.skip === null ? [] : [verdict.skip])),
143
+ };
144
+ }
145
+
146
+ function namedVerdict(name: string, position: number, input: SandboxEnvInput): Verdict<string> {
147
+ const skip = (entry: string, reason: SandboxEnvSkipReason): Verdict<string> => ({ item: name, skip: { source: "SANDBOX_ENV", entry, reason } });
148
+ if (!isEnvName(name)) return skip(`#${position}`, "invalid-name");
149
+ if (input.reservedNames.has(name)) return skip(name, "reserved");
150
+ if (input.hostEnv[name] === undefined) return skip(name, "unset-on-host");
151
+ return { item: name, skip: null };
152
+ }
153
+
154
+ function fileVerdict(entry: EnvFileEntry, input: SandboxEnvInput): Verdict<EnvFileEntry> {
155
+ const skip = (label: string, reason: SandboxEnvSkipReason): Verdict<EnvFileEntry> => ({
156
+ item: entry,
157
+ skip: { source: "SANDBOX_ENV_FILE", entry: label, reason },
158
+ });
159
+ if (!isEnvName(entry.name)) return skip(`line ${entry.lineNumber}`, "invalid-name");
160
+ // The container runtime refuses a NUL anywhere in a value, failing the run.
161
+ if (entry.line.includes("\0")) return skip(`line ${entry.lineNumber}`, "invalid-value");
162
+ if (input.reservedNames.has(entry.name)) return skip(entry.name, "reserved");
163
+ if (entry.bare && input.hostEnv[entry.name] === undefined) return skip(entry.name, "unset-on-host");
164
+ return { item: entry, skip: null };
165
+ }
166
+
167
+ // Of repeated lines docker keeps the last, so only the last one is judged.
168
+ function lastPerName(entries: EnvFileEntry[]): EnvFileEntry[] {
169
+ const valid = entries.filter((entry) => isEnvName(entry.name));
170
+ const last = new Map(valid.map((entry) => [entry.name, entry]));
171
+ return entries.filter((entry) => !isEnvName(entry.name) || last.get(entry.name) === entry);
172
+ }
173
+
174
+ function planFileEnv(text: string, input: SandboxEnvInput): { accepted: EnvFileEntry[]; skipped: SandboxEnvSkip[] } {
175
+ return splitVerdicts(lastPerName(parseEnvFileText(text)).map((entry) => fileVerdict(entry, input)));
176
+ }
177
+
178
+ export function planSandboxEnv(input: SandboxEnvInput): SandboxEnvPlan {
179
+ const named = splitVerdicts([...new Set(input.names)].map((name, index) => namedVerdict(name, index + 1, input)));
180
+ const fromFile = input.envFile !== null && "text" in input.envFile ? planFileEnv(input.envFile.text, input) : { accepted: [], skipped: [] };
181
+ return {
182
+ nameArgs: named.accepted.flatMap((name) => ["-e", name]),
183
+ envFileText: fromFile.accepted.length === 0 ? null : `${fromFile.accepted.map((entry) => entry.line).join("\n")}\n`,
184
+ fileNames: fromFile.accepted.map((entry) => entry.name),
185
+ namedNames: named.accepted,
186
+ skipped: [...fromFile.skipped, ...named.skipped],
187
+ };
188
+ }
@@ -19,15 +19,17 @@
19
19
  // - **No token in logs**. Reject messages are generic ("unauthorized")
20
20
  // so a leaked log line doesn't reveal whether "no header" vs
21
21
  // "wrong token" — matches common auth-hardening guidance.
22
- // - **The token rule lives in `@mulmoclaude/common/token-guard`**
23
- // (`isAuthorizedToken`): constant-time, byte-length-checked, and shared
24
- // with the view-token check, the `/ws/pubsub` and `/ws/chat` handshake
25
- // guards and the webhook bridge, so every surface refuses the same way.
22
+ // - **The token rule lives in `./principal.ts`**: the owner token or a named
23
+ // client token (#3618), shared with the `/ws/pubsub` and `/ws/chat`
24
+ // handshake guards, so every surface refuses the same way. A client token
25
+ // is then refused (403) on the owner-only paths in `./clientTokenAccess.ts`.
26
26
 
27
27
  import type { Request, Response, NextFunction } from "express";
28
- import { getCurrentToken } from "./token.js";
29
- import { isAuthorizedToken, UNAUTHORIZED_MESSAGE } from "@mulmoclaude/common/token-guard";
30
- import { unauthorized } from "../../utils/httpError.js";
28
+ import { rememberRequestPrincipal, resolveTokenPrincipal } from "./principal.js";
29
+ import { isOwnerOnlyApiPath } from "./clientTokenAccess.js";
30
+ import { UNAUTHORIZED_MESSAGE } from "@mulmoclaude/common/token-guard";
31
+ import { forbidden, unauthorized } from "../../utils/httpError.js";
32
+ import { log } from "../../system/logger/index.js";
31
33
 
32
34
  const BEARER_PREFIX = "Bearer ";
33
35
 
@@ -37,11 +39,18 @@ export function bearerAuth(req: Request, res: Response, next: NextFunction): voi
37
39
  unauthorized(res, UNAUTHORIZED_MESSAGE);
38
40
  return;
39
41
  }
40
- // `getCurrentToken()` is null until bootstrap, which the rule refuses too:
41
- // a request that beats `generateAndWriteToken()` gets a 401, not a pass.
42
- if (!isAuthorizedToken(header.slice(BEARER_PREFIX.length), getCurrentToken())) {
42
+ // The owner token is null until bootstrap, which the rule refuses too: a
43
+ // request that beats `generateAndWriteToken()` gets a 401, not a pass.
44
+ const principal = resolveTokenPrincipal(header.slice(BEARER_PREFIX.length));
45
+ if (principal === null) {
43
46
  unauthorized(res, UNAUTHORIZED_MESSAGE);
44
47
  return;
45
48
  }
49
+ if (principal.kind === "client" && isOwnerOnlyApiPath(req.path)) {
50
+ log.warn("auth", "client token refused on an owner-only path", { client: principal.name, method: req.method, path: req.path });
51
+ forbidden(res, "forbidden");
52
+ return;
53
+ }
54
+ rememberRequestPrincipal(req, principal);
46
55
  next();
47
56
  }
@@ -0,0 +1,57 @@
1
+ // Which `/api/*` paths a client token may NOT call (#3618): settings, secrets,
2
+ // and everything that changes how the host itself behaves or runs the agent
3
+ // outside a bridge chat. A leaked client token should reach the data external
4
+ // services read and write, not the keys to the house. Pure.
5
+ //
6
+ // Bridge chats (`/api/transports/…`, `/ws/chat`) stay open: a bridge is the
7
+ // main reason to issue a client token at all. A path that runs the agent only
8
+ // for some requests (a collection action of kind "agent") refuses client
9
+ // tokens in its own handler, via `isClientTokenRequest`. So does minting a
10
+ // view token: it is signed with the owner key and would outlive a revoke.
11
+
12
+ // Relative to the `/api` mount, which is where `bearerAuth` sees them.
13
+ const OWNER_ONLY_PREFIXES: readonly string[] = [
14
+ "/agent",
15
+ "/internal",
16
+ "/wiki/internal",
17
+ "/config",
18
+ "/secrets",
19
+ "/roles",
20
+ "/skills",
21
+ "/scheduler",
22
+ "/plugins",
23
+ "/hooks",
24
+ "/mcp",
25
+ "/mcp-tools",
26
+ "/shutdown",
27
+ "/remote-host",
28
+ "/google",
29
+ "/diagnostics",
30
+ "/sandbox",
31
+ "/shortcuts",
32
+ "/collections-registry",
33
+ "/chat-index",
34
+ ];
35
+
36
+ /** A collection action or feed ingest of kind "agent" starts a hidden agent
37
+ * run, which only the owner may do; every other kind returns or applies data. */
38
+ export const startsAgentRun = (kind: string | undefined): boolean => kind === "agent";
39
+
40
+ // Express matches routes case-insensitively and does not collapse `//`, so the
41
+ // check folds both and strips a trailing slash; an undecodable path is treated
42
+ // as owner-only rather than guessed at.
43
+ function normalizeApiPath(rawPath: string): string | null {
44
+ try {
45
+ const decoded = decodeURIComponent(rawPath).toLowerCase();
46
+ const collapsed = decoded.replace(/\/{2,}/g, "/");
47
+ return collapsed.length > 1 && collapsed.endsWith("/") ? collapsed.slice(0, -1) : collapsed;
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ export function isOwnerOnlyApiPath(rawPath: string): boolean {
54
+ const normalized = normalizeApiPath(rawPath);
55
+ if (normalized === null) return true;
56
+ return OWNER_ONLY_PREFIXES.some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`));
57
+ }
@@ -0,0 +1,13 @@
1
+ // Entry point for `mulmoclaude token …` / `yarn token …`. Writes straight to
2
+ // the terminal: the issued token must reach the user verbatim, once.
3
+ import { randomBytes } from "node:crypto";
4
+ import { runClientTokenCommand } from "./clientTokenCommands.js";
5
+ import { clientTokensPath } from "./clientTokenStore.js";
6
+
7
+ process.exitCode = runClientTokenCommand(process.argv.slice(2), {
8
+ storePath: clientTokensPath(),
9
+ nowIso: () => new Date().toISOString(),
10
+ randomHex: (bytes) => randomBytes(bytes).toString("hex"),
11
+ print: (line) => process.stdout.write(`${line}\n`),
12
+ printError: (line) => process.stderr.write(`${line}\n`),
13
+ });