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
@@ -0,0 +1,90 @@
1
+ // `mulmoclaude token add|list|revoke` (#3618). The terminal I/O, clock and
2
+ // randomness are injected so every command is testable without a terminal.
3
+
4
+ import { addClientToken, revokeClientToken, type ClientTokenRecord } from "./clientTokenRule.js";
5
+ import { errorMessage } from "../../utils/errors.js";
6
+ import { readClientTokenFile, withClientTokenLock, writeClientTokenFile } from "./clientTokenStore.js";
7
+
8
+ export interface ClientTokenCommandDeps {
9
+ storePath: string;
10
+ nowIso: () => string;
11
+ randomHex: (bytes: number) => string;
12
+ print: (line: string) => void;
13
+ printError: (line: string) => void;
14
+ }
15
+
16
+ const EXIT_OK = 0;
17
+ const EXIT_FAILURE = 1;
18
+ const EXIT_USAGE = 2;
19
+
20
+ export const CLIENT_TOKEN_USAGE = [
21
+ "Usage: mulmoclaude token add <name> issue a token (shown once)",
22
+ " mulmoclaude token list list issued tokens (never their values)",
23
+ " mulmoclaude token revoke <name> revoke a token; a running server stops accepting it at once",
24
+ "",
25
+ "A name is 1-64 letters, digits, '.', '_' or '-', starting with a letter or digit.",
26
+ ];
27
+
28
+ const ADD_REFUSALS = {
29
+ "invalid-name": "is not a valid name",
30
+ "duplicate-name": "is already in use; revoke it first or pick another name",
31
+ } as const;
32
+
33
+ function addCommand(name: string, records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
34
+ const result = addClientToken(records, { name, nowIso: deps.nowIso(), randomHex: deps.randomHex });
35
+ if (!result.ok) {
36
+ deps.printError(`"${name}" ${ADD_REFUSALS[result.reason]}.`);
37
+ return result.reason === "invalid-name" ? EXIT_USAGE : EXIT_FAILURE;
38
+ }
39
+ writeClientTokenFile(deps.storePath, result.records);
40
+ deps.print(`Issued client token "${name}" (id ${result.record.id}). It is shown only this once:`);
41
+ deps.print("");
42
+ deps.print(result.token);
43
+ deps.print("");
44
+ deps.print("Give it to that client as MULMOCLAUDE_AUTH_TOKEN, and to no other.");
45
+ return EXIT_OK;
46
+ }
47
+
48
+ function listCommand(records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
49
+ if (records.length === 0) deps.print("No client tokens issued.");
50
+ records.forEach((record) => deps.print(`${record.name}\t${record.id}\t${record.createdAt}\t${record.scopes.join(",")}`));
51
+ return EXIT_OK;
52
+ }
53
+
54
+ function revokeCommand(name: string, records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
55
+ const remaining = revokeClientToken(records, name);
56
+ if (remaining === null) {
57
+ deps.printError(`No client token named "${name}".`);
58
+ return EXIT_FAILURE;
59
+ }
60
+ writeClientTokenFile(deps.storePath, remaining);
61
+ deps.print(`Revoked client token "${name}".`);
62
+ return EXIT_OK;
63
+ }
64
+
65
+ function dispatch(args: readonly string[], records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number | null {
66
+ const [command, name, ...extra] = args;
67
+ if (extra.length > 0) return null;
68
+ if (command === "list" && name === undefined) return listCommand(records, deps);
69
+ if (command === "add" && name !== undefined) return addCommand(name, records, deps);
70
+ if (command === "revoke" && name !== undefined) return revokeCommand(name, records, deps);
71
+ return null;
72
+ }
73
+
74
+ function runLocked(args: readonly string[], deps: ClientTokenCommandDeps): number {
75
+ const { records, droppedCount } = readClientTokenFile(deps.storePath);
76
+ if (droppedCount > 0) deps.printError(`${deps.storePath}: ${droppedCount} invalid entries are ignored and will be dropped on the next change.`);
77
+ const exitCode = dispatch(args, records, deps);
78
+ if (exitCode !== null) return exitCode;
79
+ CLIENT_TOKEN_USAGE.forEach((line) => deps.printError(line));
80
+ return EXIT_USAGE;
81
+ }
82
+
83
+ export function runClientTokenCommand(args: readonly string[], deps: ClientTokenCommandDeps): number {
84
+ try {
85
+ return withClientTokenLock(deps.storePath, () => runLocked(args, deps));
86
+ } catch (err) {
87
+ deps.printError(errorMessage(err));
88
+ return EXIT_FAILURE;
89
+ }
90
+ }
@@ -0,0 +1,115 @@
1
+ // Named client tokens (#3618): who a presented bearer token belongs to, and the
2
+ // store edits `mulmoclaude token add|revoke` make. Pure — the caller injects the
3
+ // stored records, the clock and the randomness.
4
+ //
5
+ // Only a SHA-256 of each token is stored. A token is 256 random bits, so a
6
+ // plain hash is enough: there is nothing for a slow hash to stretch.
7
+
8
+ import { createHash } from "node:crypto";
9
+ import { isAuthorizedToken, tokenEquals } from "@mulmoclaude/common/token-guard";
10
+ import { isRecord, isUnknownArray } from "../../utils/types.js";
11
+
12
+ export const CLIENT_TOKEN_PREFIX = "mct_";
13
+ export const CLIENT_TOKEN_ID_BYTES = 8;
14
+ export const CLIENT_TOKEN_SECRET_BYTES = 32;
15
+ const CLIENT_TOKEN_RE = /^mct_([0-9a-f]{16})_[0-9a-f]{64}$/;
16
+ const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
17
+ const CLIENT_TOKEN_NAME_RE = /^[A-Za-z0-9][\w.-]{0,63}$/;
18
+ const STORE_VERSION = 1;
19
+
20
+ export const CLIENT_TOKEN_SCOPES = ["full"] as const;
21
+ export type ClientTokenScope = (typeof CLIENT_TOKEN_SCOPES)[number];
22
+
23
+ export interface ClientTokenRecord {
24
+ id: string;
25
+ name: string;
26
+ sha256: string;
27
+ createdAt: string;
28
+ scopes: ClientTokenScope[];
29
+ }
30
+
31
+ export type Principal = { kind: "owner" } | { kind: "client"; id: string; name: string; scopes: ClientTokenScope[] };
32
+
33
+ const isScope = (value: unknown): value is ClientTokenScope => CLIENT_TOKEN_SCOPES.some((scope) => scope === value);
34
+
35
+ export const isClientTokenName = (name: string): boolean => CLIENT_TOKEN_NAME_RE.test(name);
36
+
37
+ export const hashClientToken = (token: string): string => createHash("sha256").update(token).digest("hex");
38
+
39
+ export const formatClientToken = (idHex: string, secretHex: string): string => `${CLIENT_TOKEN_PREFIX}${idHex}_${secretHex}`;
40
+
41
+ /** The id part of a well-formed client token, or null for anything else. */
42
+ export function clientTokenId(token: string): string | null {
43
+ return CLIENT_TOKEN_RE.exec(token)?.[1] ?? null;
44
+ }
45
+
46
+ function toRecord(value: unknown): ClientTokenRecord | null {
47
+ if (!isRecord(value)) return null;
48
+ const { id, name, sha256, createdAt, scopes } = value;
49
+ if (typeof id !== "string" || !/^[0-9a-f]{16}$/.test(id)) return null;
50
+ if (typeof name !== "string" || !isClientTokenName(name)) return null;
51
+ if (typeof sha256 !== "string" || !SHA256_HEX_RE.test(sha256)) return null;
52
+ if (typeof createdAt !== "string") return null;
53
+ if (!isUnknownArray(scopes) || scopes.length === 0 || !scopes.every(isScope)) return null;
54
+ return { id, name, sha256, createdAt, scopes: [...scopes] };
55
+ }
56
+
57
+ export interface ParsedClientTokenStore {
58
+ records: ClientTokenRecord[];
59
+ /** Entries that were not a valid record; they authorize nothing. */
60
+ droppedCount: number;
61
+ }
62
+
63
+ /** The store file's parsed JSON. Throws on a file that is not a store at all,
64
+ * so the server accepts no client token and the CLI does not overwrite it. */
65
+ export function parseClientTokenStore(raw: unknown): ParsedClientTokenStore {
66
+ if (!isRecord(raw) || raw.version !== STORE_VERSION || !isUnknownArray(raw.tokens)) throw new Error(`not a version ${STORE_VERSION} client-token store`);
67
+ const parsed = raw.tokens.map(toRecord);
68
+ const records = parsed.filter((record): record is ClientTokenRecord => record !== null);
69
+ return { records, droppedCount: parsed.length - records.length };
70
+ }
71
+
72
+ export function serializeClientTokenStore(records: readonly ClientTokenRecord[]): string {
73
+ return `${JSON.stringify({ version: STORE_VERSION, tokens: records }, null, 2)}\n`;
74
+ }
75
+
76
+ function findClientToken(token: string, records: readonly ClientTokenRecord[]): ClientTokenRecord | null {
77
+ const tokenId = clientTokenId(token);
78
+ const record = tokenId === null ? undefined : records.find((candidate) => candidate.id === tokenId);
79
+ if (record === undefined) return null;
80
+ return tokenEquals(hashClientToken(token), record.sha256) ? record : null;
81
+ }
82
+
83
+ /** Owner first, so the store is read only for a token in the client format.
84
+ * No owner token yet (pre-bootstrap) refuses everything, client tokens too. */
85
+ export function resolvePrincipal(provided: unknown, ownerToken: string | null, clientTokens: () => readonly ClientTokenRecord[]): Principal | null {
86
+ if (ownerToken === null || ownerToken === "") return null;
87
+ if (isAuthorizedToken(provided, ownerToken)) return { kind: "owner" };
88
+ if (typeof provided !== "string" || !provided.startsWith(CLIENT_TOKEN_PREFIX)) return null;
89
+ const record = findClientToken(provided, clientTokens());
90
+ return record === null ? null : { kind: "client", id: record.id, name: record.name, scopes: record.scopes };
91
+ }
92
+
93
+ export type AddClientTokenResult =
94
+ { ok: true; records: ClientTokenRecord[]; token: string; record: ClientTokenRecord } | { ok: false; reason: "invalid-name" | "duplicate-name" };
95
+
96
+ export interface AddClientTokenParams {
97
+ name: string;
98
+ nowIso: string;
99
+ randomHex: (bytes: number) => string;
100
+ }
101
+
102
+ export function addClientToken(records: readonly ClientTokenRecord[], params: AddClientTokenParams): AddClientTokenResult {
103
+ if (!isClientTokenName(params.name)) return { ok: false, reason: "invalid-name" };
104
+ if (records.some((record) => record.name === params.name)) return { ok: false, reason: "duplicate-name" };
105
+ const tokenId = params.randomHex(CLIENT_TOKEN_ID_BYTES);
106
+ const token = formatClientToken(tokenId, params.randomHex(CLIENT_TOKEN_SECRET_BYTES));
107
+ const record: ClientTokenRecord = { id: tokenId, name: params.name, sha256: hashClientToken(token), createdAt: params.nowIso, scopes: ["full"] };
108
+ return { ok: true, records: [...records, record], token, record };
109
+ }
110
+
111
+ /** The records without `name`, or null when no token has that name. */
112
+ export function revokeClientToken(records: readonly ClientTokenRecord[], name: string): ClientTokenRecord[] | null {
113
+ const remaining = records.filter((record) => record.name !== name);
114
+ return remaining.length === records.length ? null : remaining;
115
+ }
@@ -0,0 +1,178 @@
1
+ // The client-token store on disk (#3618): `~/.mulmoclaude/client-tokens.json`,
2
+ // beside `secrets/` and outside the workspace — the workspace is the agent's
3
+ // data space and may be synced, and this file decides who may call the API.
4
+
5
+ import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync, writeSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { writeFileAtomicSync } from "../../utils/files/atomic.js";
9
+ import { log } from "../../system/logger/index.js";
10
+ import { errorMessage } from "../../utils/errors.js";
11
+ import { isErrorWithCode } from "../../utils/types.js";
12
+ import { ONE_SECOND_MS } from "../../utils/time.js";
13
+ import { parseClientTokenStore, serializeClientTokenStore, type ClientTokenRecord } from "./clientTokenRule.js";
14
+
15
+ const STORE_FILE_MODE = 0o600;
16
+ const STORE_DIR_MODE = 0o700;
17
+ // Each record is a few hundred bytes; a file this large is not one we wrote.
18
+ const STORE_MAX_BYTES = 1024 * 1024;
19
+
20
+ export function clientTokensPath(home: string = homedir()): string {
21
+ return path.join(home, ".mulmoclaude", "client-tokens.json");
22
+ }
23
+
24
+ const isMissing = (err: unknown): boolean => isErrorWithCode(err) && err.code === "ENOENT";
25
+
26
+ function readBoundedFile(filePath: string): string {
27
+ const handle = openSync(filePath, "r");
28
+ try {
29
+ const { size } = fstatSync(handle);
30
+ if (size > STORE_MAX_BYTES) throw new Error(`larger than ${STORE_MAX_BYTES} bytes`);
31
+ const buffer = Buffer.alloc(size);
32
+ const bytes = readSync(handle, buffer, 0, size, 0);
33
+ return buffer.subarray(0, bytes).toString("utf8");
34
+ } finally {
35
+ closeSync(handle);
36
+ }
37
+ }
38
+
39
+ /** The stored records. A missing file is an empty store; anything unreadable
40
+ * throws, with the path in the message. */
41
+ export function readClientTokenFile(filePath: string): { records: ClientTokenRecord[]; droppedCount: number } {
42
+ try {
43
+ return parseClientTokenStore(JSON.parse(readBoundedFile(filePath)));
44
+ } catch (err) {
45
+ if (isMissing(err)) return { records: [], droppedCount: 0 };
46
+ throw new Error(`${filePath}: ${errorMessage(err)}`);
47
+ }
48
+ }
49
+
50
+ /** Refuses a store it could not read back, rather than locking every client out. */
51
+ export function writeClientTokenFile(filePath: string, records: readonly ClientTokenRecord[]): void {
52
+ const text = serializeClientTokenStore(records);
53
+ if (Buffer.byteLength(text, "utf8") > STORE_MAX_BYTES) throw new Error(`${filePath}: the store would exceed ${STORE_MAX_BYTES} bytes`);
54
+ mkdirSync(path.dirname(filePath), { recursive: true, mode: STORE_DIR_MODE });
55
+ writeFileAtomicSync(filePath, text, { mode: STORE_FILE_MODE });
56
+ }
57
+
58
+ // A lock with no readable owner pid (written by a command killed before it
59
+ // recorded one) is taken over after this long.
60
+ const LOCK_STALE_MS = 30 * ONE_SECOND_MS;
61
+
62
+ interface LockState {
63
+ ownerPid: number | null;
64
+ ageMs: number;
65
+ }
66
+
67
+ /** A lock is abandoned when its recorded owner is gone; age decides only when
68
+ * no owner was recorded, so a paused but live command keeps its lock. */
69
+ export function isAbandonedLock(lock: LockState, isOwnerAlive: (pid: number) => boolean): boolean {
70
+ return lock.ownerPid === null ? lock.ageMs > LOCK_STALE_MS : !isOwnerAlive(lock.ownerPid);
71
+ }
72
+
73
+ function isProcessAlive(pid: number): boolean {
74
+ try {
75
+ process.kill(pid, 0);
76
+ return true;
77
+ } catch (err) {
78
+ return isErrorWithCode(err) && err.code === "EPERM";
79
+ }
80
+ }
81
+
82
+ function readLockState(lockPath: string, nowMs: number): LockState | null {
83
+ try {
84
+ const ageMs = nowMs - statSync(lockPath).mtimeMs;
85
+ const pid = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
86
+ return { ownerPid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, ageMs };
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ const busyError = (lockPath: string): Error => new Error(`${lockPath}: another token command is running; retry once it finishes`);
93
+
94
+ function openLock(lockPath: string): number {
95
+ const handle = openSync(lockPath, "wx", STORE_FILE_MODE);
96
+ writeSync(handle, `${process.pid}\n`);
97
+ return handle;
98
+ }
99
+
100
+ function acquireLock(lockPath: string, nowMs: number): number {
101
+ try {
102
+ return openLock(lockPath);
103
+ } catch (err) {
104
+ if (!isErrorWithCode(err) || err.code !== "EEXIST") throw busyError(lockPath);
105
+ const state = readLockState(lockPath, nowMs);
106
+ if (state !== null && !isAbandonedLock(state, isProcessAlive)) throw busyError(lockPath);
107
+ rmSync(lockPath, { force: true });
108
+ try {
109
+ return openLock(lockPath);
110
+ } catch {
111
+ throw busyError(lockPath);
112
+ }
113
+ }
114
+ }
115
+
116
+ // Only the lock this command created: if it was taken over, the new owner's
117
+ // lock must survive this command's cleanup.
118
+ function releaseLock(lockPath: string, handle: number): void {
119
+ const { dev, ino } = fstatSync(handle);
120
+ closeSync(handle);
121
+ try {
122
+ const current = statSync(lockPath);
123
+ if (current.dev === dev && current.ino === ino) rmSync(lockPath, { force: true });
124
+ } catch {
125
+ // Already gone.
126
+ }
127
+ }
128
+
129
+ /** Runs a read-modify-write of the store with no other token command in between,
130
+ * so two commands cannot drop each other's add or undo each other's revoke. */
131
+ export function withClientTokenLock<T>(filePath: string, run: () => T, nowMs: number = Date.now()): T {
132
+ mkdirSync(path.dirname(filePath), { recursive: true, mode: STORE_DIR_MODE });
133
+ const lockPath = `${filePath}.lock`;
134
+ const handle = acquireLock(lockPath, nowMs);
135
+ try {
136
+ return run();
137
+ } finally {
138
+ releaseLock(lockPath, handle);
139
+ }
140
+ }
141
+
142
+ const MISSING_KEY = "missing";
143
+
144
+ // `ctimeMs` so a chmod alone is noticed. Any stat failure other than ENOENT
145
+ // gets its own key and goes on to the read, which logs why it failed.
146
+ function statKey(filePath: string): string {
147
+ try {
148
+ const stats = statSync(filePath);
149
+ return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}`;
150
+ } catch (err) {
151
+ return isMissing(err) ? MISSING_KEY : `stat-error:${isErrorWithCode(err) ? err.code : "unknown"}`;
152
+ }
153
+ }
154
+
155
+ function loadForServer(filePath: string): ClientTokenRecord[] {
156
+ try {
157
+ const { records, droppedCount } = readClientTokenFile(filePath);
158
+ if (droppedCount > 0) log.warn("auth", "client-token store has invalid entries; they authorize nothing", { path: filePath, droppedCount });
159
+ return records;
160
+ } catch (err) {
161
+ log.warn("auth", "client-token store unreadable; no client token is accepted", { error: errorMessage(err) });
162
+ return [];
163
+ }
164
+ }
165
+
166
+ /** The records, re-read whenever the file changes (an atomic write replaces
167
+ * the inode), so `token revoke` applies to the next request. */
168
+ export function createClientTokenSource(filePath: string): () => readonly ClientTokenRecord[] {
169
+ const cache: { key: string | null; records: readonly ClientTokenRecord[] } = { key: null, records: [] };
170
+ return () => {
171
+ const key = statKey(filePath);
172
+ if (key !== cache.key) {
173
+ cache.records = key === MISSING_KEY ? [] : loadForServer(filePath);
174
+ cache.key = key;
175
+ }
176
+ return cache.records;
177
+ };
178
+ }
@@ -0,0 +1,33 @@
1
+ // The one check every bearer surface on the host applies — `/api/*`,
2
+ // `/ws/pubsub`, `/ws/chat`: the owner token, or a named client token from the
3
+ // store (#3618).
4
+
5
+ import { getCurrentToken } from "./token.js";
6
+ import { resolvePrincipal, type ClientTokenRecord, type Principal } from "./clientTokenRule.js";
7
+ import { clientTokensPath, createClientTokenSource } from "./clientTokenStore.js";
8
+
9
+ // Keyed by path because the path follows `homedir()`, which a test moves.
10
+ const sources = new Map<string, () => readonly ClientTokenRecord[]>();
11
+
12
+ function storedClientTokens(): readonly ClientTokenRecord[] {
13
+ const filePath = clientTokensPath();
14
+ const source = sources.get(filePath) ?? createClientTokenSource(filePath);
15
+ sources.set(filePath, source);
16
+ return source();
17
+ }
18
+
19
+ export function resolveTokenPrincipal(provided: unknown): Principal | null {
20
+ return resolvePrincipal(provided, getCurrentToken(), storedClientTokens);
21
+ }
22
+
23
+ export const isAuthorizedBearer = (provided: unknown): boolean => resolveTokenPrincipal(provided) !== null;
24
+
25
+ // Who `bearerAuth` let in, for a handler whose rule depends on more than the
26
+ // path. A WeakMap so a finished request leaves nothing behind.
27
+ const requestPrincipals = new WeakMap<object, Principal>();
28
+
29
+ export function rememberRequestPrincipal(req: object, principal: Principal): void {
30
+ requestPrincipals.set(req, principal);
31
+ }
32
+
33
+ export const isClientTokenRequest = (req: object): boolean => requestPrincipals.get(req)?.kind === "client";
@@ -10,7 +10,7 @@
10
10
 
11
11
  import { Router, Request, Response, NextFunction } from "express";
12
12
  import { API_ROUTES } from "../../../src/config/apiRoutes.js";
13
- import { actionVisible } from "@mulmoclaude/core/collection";
13
+ import { actionVisible, buildCustomViewFields } from "@mulmoclaude/core/collection";
14
14
  import {
15
15
  collectionWritable,
16
16
  computeCollectionIcon,
@@ -63,6 +63,8 @@ import {
63
63
  import { clampImageMaxEdge, clampLimit, clampOffset, normalizeFields, normalizeMutate } from "@mulmoclaude/core/remote-view";
64
64
  import { resolveThumbnail } from "../../utils/files/thumbnail-store.js";
65
65
  import { badRequest, notFound, conflict, forbidden, methodNotAllowed, serverError, serviceUnavailable, type ApiResponse } from "../../utils/httpError.js";
66
+ import { isClientTokenRequest } from "../auth/principal.js";
67
+ import { startsAgentRun } from "../auth/clientTokenAccess.js";
66
68
  import { requestBodyRecord } from "../../utils/requestBody.js";
67
69
  import { ONE_MINUTE_MS } from "../../utils/time.js";
68
70
  import { errorMessage } from "../../utils/errors.js";
@@ -83,8 +85,10 @@ const router = Router();
83
85
  // Load a collection by slug or send a 404 and return null. Callers do
84
86
  // `const collection = await loadCollectionOr404(slug, res); if (!collection) return;`.
85
87
  // The load-or-404 preamble was repeated across ~16 route handlers.
86
- async function loadCollectionOr404(slug: string, res: Response): Promise<LoadedCollection | null> {
87
- const collection = await loadCollection(slug);
88
+ type CollectionLoader = (slug: string) => Promise<LoadedCollection | null>;
89
+
90
+ async function loadCollectionOr404(slug: string, res: Response, load: CollectionLoader = loadCollection): Promise<LoadedCollection | null> {
91
+ const collection = await load(slug);
88
92
  if (!collection) {
89
93
  notFound(res, `collection '${slug}' not found`);
90
94
  return null;
@@ -113,8 +117,13 @@ export function findViewOr404(collection: LoadedCollection, viewId: string, res:
113
117
  // Resolve a collection + one of its custom views by id, or send a 404
114
118
  // (missing collection or missing view) and return null. Shared by the
115
119
  // view-file / view-i18n / view-token routes.
116
- async function resolveCustomViewOr404(slug: string, viewId: string, res: Response): Promise<ResolvedCustomView | null> {
117
- const collection = await loadCollectionOr404(slug, res);
120
+ async function resolveCustomViewOr404(
121
+ slug: string,
122
+ viewId: string,
123
+ res: Response,
124
+ load: CollectionLoader = loadCollection,
125
+ ): Promise<ResolvedCustomView | null> {
126
+ const collection = await loadCollectionOr404(slug, res, load);
118
127
  if (!collection) return null;
119
128
  const view = findViewOr404(collection, viewId, res);
120
129
  if (!view) return null;
@@ -466,6 +475,10 @@ router.post(API_ROUTES.collections.refresh, async (req: Request<{ slug: string }
466
475
  badRequest(res, `collection '${collection.slug}' is not refreshable (no ingest or googleCalendar config)`);
467
476
  return;
468
477
  }
478
+ if (isClientTokenRequest(req) && startsAgentRun(collection.schema.ingest?.kind)) {
479
+ forbidden(res, "forbidden");
480
+ return;
481
+ }
469
482
  try {
470
483
  if (collection.schema.ingest) await refreshFeedCollection(collection, res);
471
484
  else await refreshCalendarCollection(collection.slug, res);
@@ -513,16 +526,19 @@ router.post(API_ROUTES.collections.calendarPush, async (req: Request<{ slug: str
513
526
  // 409 on a double-dispatch (the stamp-at-dispatch guard); 503 on a
514
527
  // cap-miss / launch failure so the button un-sticks and reads honest.
515
528
  async function respondForActionKind(
529
+ req: Request,
516
530
  res: ApiResponse<ActionRunResponse>,
517
- collection: LoadedCollection,
518
- action: CollectionSeededAction,
519
- seed: ActionSeedResponse,
520
- itemId?: string | undefined,
531
+ dispatch: { collection: LoadedCollection; action: CollectionSeededAction; seed: ActionSeedResponse; itemId?: string | undefined },
521
532
  ): Promise<void> {
533
+ const { collection, action, seed, itemId } = dispatch;
522
534
  if (action.kind !== "agent") {
523
535
  res.json(seed);
524
536
  return;
525
537
  }
538
+ if (isClientTokenRequest(req) && startsAgentRun(action.kind)) {
539
+ forbidden(res, "forbidden");
540
+ return;
541
+ }
526
542
  const outcome = await dispatchAgentAction({ collection, action, seed: seed.prompt, itemId });
527
543
  if (!outcome.ok) {
528
544
  if (outcome.alreadyRunning) conflict(res, outcome.error);
@@ -618,7 +634,7 @@ router.post(
618
634
  kind: action.kind,
619
635
  });
620
636
  const seed = { prompt: buildActionSeedPrompt(record, template, promptPathsFor(collection, workspacePath)), role: action.role };
621
- await respondForActionKind(res, collection, action, seed, req.params.itemId);
637
+ await respondForActionKind(req, res, { collection, action, seed, itemId: req.params.itemId });
622
638
  } catch (err) {
623
639
  log.warn("collections", "action seed failed", {
624
640
  slug: collection.slug,
@@ -665,7 +681,7 @@ router.post(API_ROUTES.collections.collectionAction, async (req: Request<{ slug:
665
681
  serverError(res, `template '${action.template}' for action '${action.id}' could not be read`);
666
682
  return;
667
683
  }
668
- await respondForActionKind(res, collection, action, seed);
684
+ await respondForActionKind(req, res, { collection, action, seed });
669
685
  } catch (err) {
670
686
  log.warn("collections", "collection action seed failed", {
671
687
  slug: collection.slug,
@@ -936,33 +952,55 @@ router.get(API_ROUTES.collections.viewI18n, async (req: Request<{ slug: string }
936
952
  }
937
953
  });
938
954
 
939
- // Mint a scoped token for a custom view. Behind the global bearer (only the
940
- // real frontend can mint); clamps requested caps to what the view declared
941
- // so a `read`-only view can never obtain a `write` token.
942
- router.post(API_ROUTES.collections.viewToken, async (req: Request<{ slug: string }>, res: Response) => {
943
- try {
944
- const { slug } = req.params;
945
- const body = requestBodyRecord(req.body);
946
- const viewId = typeof body.viewId === "string" ? body.viewId.trim() : "";
947
- if (!viewId) {
948
- badRequest(res, "`viewId` is required");
955
+ export interface ViewTokenDeps {
956
+ loadCollection: CollectionLoader;
957
+ mint: typeof mintViewToken;
958
+ }
959
+
960
+ /** The view-token mint behind a deps seam, so the response contract (clamped
961
+ * capabilities, schema-derived `fields`) is unit-testable without mounting
962
+ * the express app. */
963
+ export const createViewTokenHandler =
964
+ (deps: ViewTokenDeps) =>
965
+ async (req: Request<{ slug: string }>, res: Response): Promise<void> => {
966
+ if (isClientTokenRequest(req)) {
967
+ forbidden(res, "forbidden");
949
968
  return;
950
969
  }
951
- const resolved = await resolveCustomViewOr404(slug, viewId, res);
952
- if (!resolved) return;
953
- const { view } = resolved;
954
- const granted = clampCapabilities(view.capabilities, parseCapabilities(body.capabilities));
955
- const minted = mintViewToken(slug, granted);
956
- if (!minted) {
957
- serverError(res, "view token unavailable (server not ready)");
958
- return;
970
+ try {
971
+ const { slug } = req.params;
972
+ const body = requestBodyRecord(req.body);
973
+ const viewId = typeof body.viewId === "string" ? body.viewId.trim() : "";
974
+ if (!viewId) {
975
+ badRequest(res, "`viewId` is required");
976
+ return;
977
+ }
978
+ const resolved = await resolveCustomViewOr404(slug, viewId, res, deps.loadCollection);
979
+ if (!resolved) return;
980
+ const { collection, view } = resolved;
981
+ const granted = clampCapabilities(view.capabilities, parseCapabilities(body.capabilities));
982
+ const minted = deps.mint(slug, granted);
983
+ if (!minted) {
984
+ serverError(res, "view token unavailable (server not ready)");
985
+ return;
986
+ }
987
+ res.json({
988
+ token: minted.token,
989
+ exp: minted.exp,
990
+ dataUrl: API_ROUTES.collections.viewData.replace(":slug", slug),
991
+ capabilities: granted,
992
+ fields: buildCustomViewFields(collection.schema),
993
+ });
994
+ } catch (err) {
995
+ log.warn("collections", "view-token mint failed", { slug: singleLineForLog(req.params.slug), error: errorMessage(err) });
996
+ serverError(res, errorMessage(err));
959
997
  }
960
- res.json({ token: minted.token, exp: minted.exp, dataUrl: API_ROUTES.collections.viewData.replace(":slug", slug), capabilities: granted });
961
- } catch (err) {
962
- log.warn("collections", "view-token mint failed", { slug: singleLineForLog(req.params.slug), error: errorMessage(err) });
963
- serverError(res, errorMessage(err));
964
- }
965
- });
998
+ };
999
+
1000
+ // Mint a scoped token for a custom view. Behind the global bearer (only the
1001
+ // real frontend can mint); clamps requested caps to what the view declared
1002
+ // so a `read`-only view can never obtain a `write` token.
1003
+ router.post(API_ROUTES.collections.viewToken, createViewTokenHandler({ loadCollection, mint: mintViewToken }));
966
1004
 
967
1005
  // Scoped read: enriched records (getItems). Guarded by the view token only
968
1006
  // (exempt from global bearer + CSRF — see server/index.ts).