mulmoclaude 2.10.0 → 2.12.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 (52) hide show
  1. package/README.md +15 -0
  2. package/bin/mulmoclaude.js +44 -51
  3. package/client/assets/{JsonEditor-E3FJ7oRf.js → JsonEditor-DnC5hozl.js} +1 -1
  4. package/client/assets/{marp-CmMNIT1E.js → marp-BH7JDaRq.js} +1 -1
  5. package/client/assets/material-symbols-outlined-DzTrJqFk.woff2 +0 -0
  6. package/client/assets/{feat-3497-Cwr8t4l4.js → mulmoclaude2-wt3640-35L_u9kD.js} +940 -929
  7. package/client/assets/mulmoclaude2-wt3640-DzadcIZy.css +2 -0
  8. package/client/assets/vue-i18n-BVPWXOdL.js +3 -0
  9. package/client/index.html +3 -3
  10. package/package.json +22 -22
  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 +37 -16
  16. package/server/api/auth/bearerExemption.ts +38 -0
  17. package/server/api/auth/clientTokenAccess.ts +57 -0
  18. package/server/api/auth/clientTokenCli.ts +13 -0
  19. package/server/api/auth/clientTokenCommands.ts +110 -0
  20. package/server/api/auth/clientTokenRule.ts +116 -0
  21. package/server/api/auth/clientTokenScope.ts +73 -0
  22. package/server/api/auth/clientTokenStore.ts +226 -0
  23. package/server/api/auth/clientTokenUsage.ts +85 -0
  24. package/server/api/auth/clientTokenUsageRule.ts +59 -0
  25. package/server/api/auth/ownerTokenHandoff.ts +73 -0
  26. package/server/api/auth/principal.ts +94 -0
  27. package/server/api/routes/clientTokens.ts +85 -0
  28. package/server/api/routes/collections.ts +92 -45
  29. package/server/api/routes/files.ts +4 -6
  30. package/server/build/mcp-server.mjs +777 -768
  31. package/server/events/pub-sub/handshakeAuth.ts +3 -5
  32. package/server/events/pub-sub/index.ts +22 -4
  33. package/server/index.ts +33 -51
  34. package/server/system/env.ts +4 -0
  35. package/server/utils/wait-ready.d.mts +20 -0
  36. package/server/utils/wait-ready.mjs +64 -0
  37. package/src/components/SessionHistoryRow.vue +49 -33
  38. package/src/components/SettingsClientTokensTab.vue +176 -0
  39. package/src/components/SettingsModal.vue +4 -1
  40. package/src/config/apiRoutes.ts +4 -0
  41. package/src/lang/de.ts +25 -0
  42. package/src/lang/en.ts +24 -0
  43. package/src/lang/es.ts +24 -0
  44. package/src/lang/fr.ts +25 -0
  45. package/src/lang/ja.ts +24 -0
  46. package/src/lang/ko.ts +24 -0
  47. package/src/lang/pt-BR.ts +24 -0
  48. package/src/lang/zh.ts +23 -0
  49. package/src/utils/html/customViewSrcdoc.ts +5 -0
  50. package/client/assets/feat-3497-DEfIEPf6.css +0 -2
  51. package/client/assets/material-symbols-outlined-Bn5lkljl.woff2 +0 -0
  52. package/client/assets/vue-i18n-BHWgmfE3.js +0 -3
@@ -0,0 +1,85 @@
1
+ // Records client-token uses in memory and writes them out in batches (#3637):
2
+ // at most once per flush delay, and on shutdown. A write failure is logged and
3
+ // left for a later flush; it never reaches the request that caused it.
4
+
5
+ import { log } from "../../system/logger/index.js";
6
+ import { errorMessage } from "../../utils/errors.js";
7
+ import { ONE_SECOND_MS } from "../../utils/time.js";
8
+ import { noteClientTokenUse, pruneClientTokenUsage, serializeClientTokenUsage, type ClientTokenUsage } from "./clientTokenUsageRule.js";
9
+ import { readClientTokenUsageFile, writeClientTokenUsageFile } from "./clientTokenStore.js";
10
+
11
+ export const USAGE_FLUSH_DELAY_MS = 30 * ONE_SECOND_MS;
12
+
13
+ export interface ClientTokenUsageTracker {
14
+ note: (tokenId: string) => void;
15
+ snapshot: () => ReadonlyMap<string, string>;
16
+ /** Writes now if anything changed since the last write. */
17
+ flush: () => void;
18
+ }
19
+
20
+ export interface ClientTokenUsageTrackerOptions {
21
+ filePath: string;
22
+ /** The ids still in the store, so a flush drops revoked ones; null when the
23
+ * store cannot be read, which drops nothing. */
24
+ liveIds: () => readonly string[] | null;
25
+ now?: () => number;
26
+ flushDelayMs?: number;
27
+ }
28
+
29
+ /** The pruned map once written; null when anything failed, which leaves the
30
+ * in-memory map and its changes to the next flush. */
31
+ function writeUsage(filePath: string, usage: ClientTokenUsage, liveIds: () => readonly string[] | null): ClientTokenUsage | null {
32
+ try {
33
+ const pruned = pruneClientTokenUsage(usage, liveIds());
34
+ writeClientTokenUsageFile(filePath, serializeClientTokenUsage(pruned));
35
+ return pruned;
36
+ } catch (err) {
37
+ log.warn("auth", "could not write client-token usage", { path: filePath, error: errorMessage(err) });
38
+ return null;
39
+ }
40
+ }
41
+
42
+ class UsageTracker implements ClientTokenUsageTracker {
43
+ private loaded: ClientTokenUsage | null = null;
44
+ private dirty = false;
45
+ private timer: ReturnType<typeof setTimeout> | null = null;
46
+
47
+ constructor(private readonly options: Required<ClientTokenUsageTrackerOptions>) {}
48
+
49
+ note = (tokenId: string): void => {
50
+ if (!noteClientTokenUse(this.usage(), tokenId, this.options.now())) return;
51
+ this.dirty = true;
52
+ this.schedule();
53
+ };
54
+
55
+ snapshot = (): ReadonlyMap<string, string> => new Map(this.usage());
56
+
57
+ // A failed write stays dirty and tries again later, so an idle client's last
58
+ // use is not left to a graceful shutdown that may never come.
59
+ flush = (): void => {
60
+ if (this.timer !== null) clearTimeout(this.timer);
61
+ this.timer = null;
62
+ if (!this.dirty) return;
63
+ const written = writeUsage(this.options.filePath, this.usage(), this.options.liveIds);
64
+ if (written === null) {
65
+ this.schedule();
66
+ return;
67
+ }
68
+ // Revoked ids leave memory too, not only the file.
69
+ this.loaded = written;
70
+ this.dirty = false;
71
+ };
72
+
73
+ private usage(): ClientTokenUsage {
74
+ this.loaded ??= readClientTokenUsageFile(this.options.filePath);
75
+ return this.loaded;
76
+ }
77
+
78
+ private schedule(): void {
79
+ this.timer ??= setTimeout(this.flush, this.options.flushDelayMs).unref();
80
+ }
81
+ }
82
+
83
+ export function createClientTokenUsageTracker(options: ClientTokenUsageTrackerOptions): ClientTokenUsageTracker {
84
+ return new UsageTracker({ now: Date.now, flushDelayMs: USAGE_FLUSH_DELAY_MS, ...options });
85
+ }
@@ -0,0 +1,59 @@
1
+ // When each client token was last used (#3637), and what Settings lists. Pure —
2
+ // the clock and the store's records are passed in.
3
+ //
4
+ // Minute resolution, so the map changes at most once a minute per token and a
5
+ // busy client does not keep the file dirty.
6
+
7
+ import { isRecord } from "../../utils/types.js";
8
+ import { ONE_MINUTE_MS } from "../../utils/time.js";
9
+ import type { ClientTokenRecord } from "./clientTokenRule.js";
10
+
11
+ const USAGE_FILE_VERSION = 1;
12
+ const CLIENT_TOKEN_ID_RE = /^[0-9a-f]{16}$/;
13
+
14
+ /** Token id → the minute it was last used, as an ISO string. */
15
+ export type ClientTokenUsage = Map<string, string>;
16
+
17
+ export interface ClientTokenListing {
18
+ name: string;
19
+ id: string;
20
+ createdAt: string;
21
+ scopes: ClientTokenRecord["scopes"];
22
+ lastUsedAt: string | null;
23
+ }
24
+
25
+ export const usageMinuteIso = (nowMs: number): string => new Date(Math.floor(nowMs / ONE_MINUTE_MS) * ONE_MINUTE_MS).toISOString();
26
+
27
+ /** True when this use moved the token's minute, i.e. the file needs writing. */
28
+ export function noteClientTokenUse(usage: ClientTokenUsage, tokenId: string, nowMs: number): boolean {
29
+ const minute = usageMinuteIso(nowMs);
30
+ if (usage.get(tokenId) === minute) return false;
31
+ usage.set(tokenId, minute);
32
+ return true;
33
+ }
34
+
35
+ const isUsageEntry = (entry: [string, unknown]): entry is [string, string] =>
36
+ CLIENT_TOKEN_ID_RE.test(entry[0]) && typeof entry[1] === "string" && !Number.isNaN(Date.parse(entry[1]));
37
+
38
+ /** The usage file's JSON. Anything malformed is dropped rather than thrown:
39
+ * these times are advisory and must never stand in the way of a request. */
40
+ export function parseClientTokenUsage(raw: unknown): ClientTokenUsage {
41
+ if (!isRecord(raw) || raw.version !== USAGE_FILE_VERSION || !isRecord(raw.lastUsed)) return new Map();
42
+ const entries = Object.entries(raw.lastUsed).filter(isUsageEntry);
43
+ return new Map(entries);
44
+ }
45
+
46
+ /** Only ids still in the store, so a revoked token's entry is dropped. `null`
47
+ * means the store was not read completely: nothing is dropped on a guess. */
48
+ export function pruneClientTokenUsage(usage: ClientTokenUsage, liveIds: readonly string[] | null): ClientTokenUsage {
49
+ if (liveIds === null) return new Map(usage);
50
+ return new Map([...usage].filter(([tokenId]) => liveIds.includes(tokenId)));
51
+ }
52
+
53
+ export function serializeClientTokenUsage(usage: ClientTokenUsage): string {
54
+ return `${JSON.stringify({ version: USAGE_FILE_VERSION, lastUsed: Object.fromEntries(usage) }, null, 2)}\n`;
55
+ }
56
+
57
+ export function listClientTokens(records: readonly ClientTokenRecord[], usage: ReadonlyMap<string, string>): ClientTokenListing[] {
58
+ return records.map(({ name, id, createdAt, scopes }) => ({ name, id, createdAt, scopes: [...scopes], lastUsedAt: usage.get(id) ?? null }));
59
+ }
@@ -0,0 +1,73 @@
1
+ // Which page loads may receive the owner bearer token embedded in index.html
2
+ // (#3627). The server binds 127.0.0.1, so a request from anywhere else arrives
3
+ // through something the user put in front of it — a tunnel or reverse proxy —
4
+ // and that hop also appears as a loopback peer. Only a direct load of
5
+ // `http://localhost:<port>` is trusted. Pure: the production handler and the
6
+ // dev server's Vite plugin both pass in what they can see.
7
+
8
+ import type { IncomingHttpHeaders } from "node:http";
9
+
10
+ // Hostnames a browser on this machine uses to reach the server directly. A
11
+ // permitted list: a proxy forwarding its public host is refused, and so is a
12
+ // DNS-rebinding page whose hostname merely resolves to 127.0.0.1.
13
+ const DIRECT_HOSTNAMES: readonly string[] = ["localhost", "127.0.0.1", "[::1]"];
14
+
15
+ // A proxy that rewrites Host to localhost still says it is there.
16
+ const PROXY_HEADERS: readonly string[] = [
17
+ "forwarded",
18
+ "x-forwarded-for",
19
+ "x-forwarded-host",
20
+ "x-forwarded-proto",
21
+ "x-forwarded-port",
22
+ "x-real-ip",
23
+ "cf-connecting-ip",
24
+ "true-client-ip",
25
+ "tailscale-user-login",
26
+ "via",
27
+ ];
28
+
29
+ export type OwnerTokenHandoff = { ok: true } | { ok: false; reason: "remote-peer" | "target" | "host" | "forwarded" };
30
+
31
+ export interface PageRequest {
32
+ remoteAddress: string | undefined;
33
+ /** The request target as sent (`req.url`). */
34
+ target: string | undefined;
35
+ headers: IncomingHttpHeaders;
36
+ /** `req.rawHeaders`: Node keeps only the first of two `Host` fields in `headers`. */
37
+ rawHeaders: readonly string[];
38
+ }
39
+
40
+ /** Node reports an IPv4 peer on a dual-stack socket as `::ffff:127.0.0.1`. */
41
+ export function isLoopbackAddress(address: string | undefined): boolean {
42
+ if (!address) return false;
43
+ const bare = address.startsWith("::ffff:") ? address.slice("::ffff:".length) : address;
44
+ return bare === "::1" || bare.startsWith("127.");
45
+ }
46
+
47
+ const isPortSuffix = (rest: string): boolean => rest === "" || (rest.startsWith(":") && /^\d+$/.test(rest.slice(1)));
48
+
49
+ /** The Host header's hostname, lowercased and without its port, or null. */
50
+ export function hostnameOf(host: string | undefined): string | null {
51
+ if (typeof host !== "string" || host === "") return null;
52
+ const lowered = host.toLowerCase();
53
+ const nameEnd = lowered.startsWith("[") ? lowered.indexOf("]") + 1 : lowered.includes(":") ? lowered.indexOf(":") : lowered.length;
54
+ const name = lowered.slice(0, nameEnd);
55
+ if (name === "" || (lowered.startsWith("[") && nameEnd <= "[]".length)) return null;
56
+ return isPortSuffix(lowered.slice(nameEnd)) ? name : null;
57
+ }
58
+
59
+ const hostFieldCount = (rawHeaders: readonly string[]): number => rawHeaders.filter((value, index) => index % 2 === 0 && value.toLowerCase() === "host").length;
60
+
61
+ // A browser sends origin-form (`/path`); a proxy forwarding an absolute-form
62
+ // target (`http://public.example/`) would otherwise pass with a localhost Host.
63
+ const isOriginFormTarget = (target: string | undefined): boolean => typeof target === "string" && target.startsWith("/");
64
+
65
+ export function decideOwnerTokenHandoff(request: PageRequest): OwnerTokenHandoff {
66
+ if (!isLoopbackAddress(request.remoteAddress)) return { ok: false, reason: "remote-peer" };
67
+ if (!isOriginFormTarget(request.target)) return { ok: false, reason: "target" };
68
+ if (hostFieldCount(request.rawHeaders) !== 1) return { ok: false, reason: "host" };
69
+ const hostname = hostnameOf(request.headers.host);
70
+ if (hostname === null || !DIRECT_HOSTNAMES.includes(hostname)) return { ok: false, reason: "host" };
71
+ if (PROXY_HEADERS.some((name) => request.headers[name] !== undefined)) return { ok: false, reason: "forwarded" };
72
+ return { ok: true };
73
+ }
@@ -0,0 +1,94 @@
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 { clientTokenUsagePath, clientTokensPath, createClientTokenSource, readClientTokenFile } from "./clientTokenStore.js";
8
+ import { hasFullScope, isCollectionInScope } from "./clientTokenScope.js";
9
+ import { createClientTokenUsageTracker, type ClientTokenUsageTracker } from "./clientTokenUsage.js";
10
+ import { listClientTokens, type ClientTokenListing } from "./clientTokenUsageRule.js";
11
+ import { log } from "../../system/logger/index.js";
12
+ import { errorMessage } from "../../utils/errors.js";
13
+
14
+ // Keyed by path because the path follows `homedir()`, which a test moves.
15
+ const sources = new Map<string, () => readonly ClientTokenRecord[]>();
16
+ const usageTrackers = new Map<string, ClientTokenUsageTracker>();
17
+
18
+ function storedClientTokens(): readonly ClientTokenRecord[] {
19
+ const filePath = clientTokensPath();
20
+ const source = sources.get(filePath) ?? createClientTokenSource(filePath);
21
+ sources.set(filePath, source);
22
+ return source();
23
+ }
24
+
25
+ // Read fresh rather than through the cached source, which serves an unreadable
26
+ // store as an empty one. Null unless the read was complete: an entry this server
27
+ // cannot read may be a live token whose last use must survive the flush.
28
+ function liveClientTokenIds(): string[] | null {
29
+ try {
30
+ const { records, droppedCount } = readClientTokenFile(clientTokensPath());
31
+ return droppedCount > 0 ? null : records.map((record) => record.id);
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ function usageTracker(): ClientTokenUsageTracker {
38
+ const filePath = clientTokenUsagePath();
39
+ const tracker = usageTrackers.get(filePath) ?? createClientTokenUsageTracker({ filePath, liveIds: liveClientTokenIds });
40
+ usageTrackers.set(filePath, tracker);
41
+ return tracker;
42
+ }
43
+
44
+ // Last-used times are advisory: recording one must never fail the request.
45
+ function noteUse(tokenId: string): void {
46
+ try {
47
+ usageTracker().note(tokenId);
48
+ } catch (err) {
49
+ log.warn("auth", "could not record client-token use", { error: errorMessage(err) });
50
+ }
51
+ }
52
+
53
+ export function resolveTokenPrincipal(provided: unknown): Principal | null {
54
+ const principal = resolvePrincipal(provided, getCurrentToken(), storedClientTokens);
55
+ if (principal?.kind === "client") noteUse(principal.id);
56
+ return principal;
57
+ }
58
+
59
+ export interface StoredClientTokenListing {
60
+ tokens: ClientTokenListing[];
61
+ /** Entries in the store this server cannot read; they authorize nothing. */
62
+ unreadableEntryCount: number;
63
+ }
64
+
65
+ /** What Settings shows: never a token's value or hash. Read fresh, and throws on
66
+ * an unreadable store, so the page reports it instead of showing no tokens. */
67
+ export function listStoredClientTokens(): StoredClientTokenListing {
68
+ const { records, droppedCount } = readClientTokenFile(clientTokensPath());
69
+ return { tokens: listClientTokens(records, usageTracker().snapshot()), unreadableEntryCount: droppedCount };
70
+ }
71
+
72
+ export const flushClientTokenUsage = (): void => usageTracker().flush();
73
+
74
+ /** The sockets carry every collection's events and the bridge chat, which no
75
+ * scope narrows, so only the owner and a `full` client token connect (#3636). */
76
+ export function isSocketAuthorizedBearer(provided: unknown): boolean {
77
+ const principal = resolveTokenPrincipal(provided);
78
+ return principal !== null && (principal.kind === "owner" || hasFullScope(principal.scopes));
79
+ }
80
+
81
+ // Who `bearerAuth` let in, for a handler whose rule depends on more than the
82
+ // path. A WeakMap so a finished request leaves nothing behind.
83
+ const requestPrincipals = new WeakMap<object, Principal>();
84
+
85
+ export function rememberRequestPrincipal(req: object, principal: Principal): void {
86
+ requestPrincipals.set(req, principal);
87
+ }
88
+
89
+ export const isClientTokenRequest = (req: object): boolean => requestPrincipals.get(req)?.kind === "client";
90
+
91
+ export function isCollectionVisibleToRequest(req: object, slug: string): boolean {
92
+ const principal = requestPrincipals.get(req);
93
+ return principal?.kind !== "client" || isCollectionInScope(principal.scopes, slug);
94
+ }
@@ -0,0 +1,85 @@
1
+ // Settings → client tokens (#3637): list them, revoke one. Issuing stays on the
2
+ // CLI so a token's value never reaches a browser. Under `/api/config`, which
3
+ // `clientTokenAccess.ts` keeps owner-only, so a client token cannot list or
4
+ // revoke tokens.
5
+
6
+ import { Router, type Request } from "express";
7
+
8
+ import { API_ROUTES } from "../../../src/config/apiRoutes.js";
9
+ import { log } from "../../system/logger/index.js";
10
+ import { errorMessage } from "../../utils/errors.js";
11
+ import { badRequest, conflict, notFound, serverError, type ApiResponse } from "../../utils/httpError.js";
12
+ import { listStoredClientTokens, type StoredClientTokenListing } from "../auth/principal.js";
13
+ import { ClientTokenLockBusyError, REVOKE_OUTCOMES, clientTokensPath, revokeStoredClientToken, type RevokeOutcome } from "../auth/clientTokenStore.js";
14
+
15
+ export type ClientTokensResponse = StoredClientTokenListing;
16
+
17
+ export interface RevokeClientTokenResponse {
18
+ revoked: string;
19
+ }
20
+
21
+ export interface ClientTokensDeps {
22
+ /** Throws when the store cannot be read. */
23
+ list: () => StoredClientTokenListing;
24
+ revoke: (target: { name: string; id: string }) => RevokeOutcome;
25
+ }
26
+
27
+ const defaultDeps: ClientTokensDeps = {
28
+ list: listStoredClientTokens,
29
+ revoke: (target) => revokeStoredClientToken(clientTokensPath(), target),
30
+ };
31
+
32
+ const REFUSALS: Record<Exclude<RevokeOutcome, typeof REVOKE_OUTCOMES.revoked>, { send: typeof conflict; message: string }> = {
33
+ [REVOKE_OUTCOMES.notFound]: { send: notFound, message: "no client token by that name" },
34
+ [REVOKE_OUTCOMES.changed]: { send: conflict, message: "that name now belongs to a different token; reload the list" },
35
+ [REVOKE_OUTCOMES.unreadableEntries]: {
36
+ send: conflict,
37
+ message: "client-tokens.json has entries this server cannot read; revoking here would drop them, so use `mulmoclaude token revoke`",
38
+ },
39
+ };
40
+
41
+ function answerRevoke(outcome: RevokeOutcome, name: string, res: ApiResponse<RevokeClientTokenResponse>): void {
42
+ if (outcome === REVOKE_OUTCOMES.revoked) {
43
+ log.info("auth", "client token revoked from Settings", { client: name });
44
+ res.json({ revoked: name });
45
+ return;
46
+ }
47
+ const refusal = REFUSALS[outcome];
48
+ refusal.send(res, refusal.message);
49
+ }
50
+
51
+ function revokeOrRefuse(deps: ClientTokensDeps, target: { name: string; id: string }, res: ApiResponse<RevokeClientTokenResponse>): void {
52
+ try {
53
+ answerRevoke(deps.revoke(target), target.name, res);
54
+ } catch (err) {
55
+ if (err instanceof ClientTokenLockBusyError) {
56
+ conflict(res, errorMessage(err));
57
+ return;
58
+ }
59
+ log.warn("auth", "client token revoke failed", { client: target.name, error: errorMessage(err) });
60
+ serverError(res, errorMessage(err));
61
+ }
62
+ }
63
+
64
+ function listOrFail(deps: ClientTokensDeps, res: ApiResponse<ClientTokensResponse>): void {
65
+ try {
66
+ res.json(deps.list());
67
+ } catch (err) {
68
+ log.warn("auth", "client token list failed", { error: errorMessage(err) });
69
+ serverError(res, errorMessage(err));
70
+ }
71
+ }
72
+
73
+ export function createClientTokensRouter(deps: ClientTokensDeps = defaultDeps): Router {
74
+ const router = Router();
75
+ router.get(API_ROUTES.config.clientTokens, (_req: Request, res: ApiResponse<ClientTokensResponse>) => listOrFail(deps, res));
76
+ router.delete(API_ROUTES.config.clientToken, (req: Request<{ name: string }>, res: ApiResponse<RevokeClientTokenResponse>) => {
77
+ const { id } = req.query;
78
+ if (typeof id !== "string" || id === "") {
79
+ badRequest(res, "id is required");
80
+ return;
81
+ }
82
+ revokeOrRefuse(deps, { name: req.params.name, id }, res);
83
+ });
84
+ return router;
85
+ }
@@ -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, isCollectionVisibleToRequest } 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;
@@ -260,16 +269,25 @@ async function toClientSummary(collection: LoadedCollection): Promise<Collection
260
269
  return { ...summary, icon, iconSources: [spec.source.collection] };
261
270
  }
262
271
 
263
- router.get(API_ROUTES.collections.list, async (_req: Request, res: ApiResponse<CollectionsListResponse>) => {
264
- try {
265
- const collections = await discoverCollections();
266
- const summaries = await Promise.all(collections.map(toClientSummary));
267
- res.json({ collections: summaries });
268
- } catch (err) {
269
- log.warn("collections", "list failed", { error: errorMessage(err) });
270
- serverError(res, errorMessage(err));
271
- }
272
- });
272
+ export interface CollectionsListDeps {
273
+ discover: () => Promise<LoadedCollection[]>;
274
+ summarize: (collection: LoadedCollection) => Promise<CollectionSummary>;
275
+ }
276
+
277
+ /** A scoped client token (#3636) sees only its own collections. */
278
+ export function createCollectionsListHandler(deps: CollectionsListDeps = { discover: () => discoverCollections(), summarize: toClientSummary }) {
279
+ return async (req: Request, res: ApiResponse<CollectionsListResponse>): Promise<void> => {
280
+ try {
281
+ const collections = (await deps.discover()).filter((collection) => isCollectionVisibleToRequest(req, collection.slug));
282
+ res.json({ collections: await Promise.all(collections.map(deps.summarize)) });
283
+ } catch (err) {
284
+ log.warn("collections", "list failed", { error: errorMessage(err) });
285
+ serverError(res, errorMessage(err));
286
+ }
287
+ };
288
+ }
289
+
290
+ router.get(API_ROUTES.collections.list, createCollectionsListHandler());
273
291
 
274
292
  // Raw workspace-ontology entries (buildWorkspaceOntology — derived on
275
293
  // demand, never stored); the /collections Map tab builds its graph from
@@ -466,6 +484,10 @@ router.post(API_ROUTES.collections.refresh, async (req: Request<{ slug: string }
466
484
  badRequest(res, `collection '${collection.slug}' is not refreshable (no ingest or googleCalendar config)`);
467
485
  return;
468
486
  }
487
+ if (isClientTokenRequest(req) && startsAgentRun(collection.schema.ingest?.kind)) {
488
+ forbidden(res, "forbidden");
489
+ return;
490
+ }
469
491
  try {
470
492
  if (collection.schema.ingest) await refreshFeedCollection(collection, res);
471
493
  else await refreshCalendarCollection(collection.slug, res);
@@ -513,16 +535,19 @@ router.post(API_ROUTES.collections.calendarPush, async (req: Request<{ slug: str
513
535
  // 409 on a double-dispatch (the stamp-at-dispatch guard); 503 on a
514
536
  // cap-miss / launch failure so the button un-sticks and reads honest.
515
537
  async function respondForActionKind(
538
+ req: Request,
516
539
  res: ApiResponse<ActionRunResponse>,
517
- collection: LoadedCollection,
518
- action: CollectionSeededAction,
519
- seed: ActionSeedResponse,
520
- itemId?: string | undefined,
540
+ dispatch: { collection: LoadedCollection; action: CollectionSeededAction; seed: ActionSeedResponse; itemId?: string | undefined },
521
541
  ): Promise<void> {
542
+ const { collection, action, seed, itemId } = dispatch;
522
543
  if (action.kind !== "agent") {
523
544
  res.json(seed);
524
545
  return;
525
546
  }
547
+ if (isClientTokenRequest(req) && startsAgentRun(action.kind)) {
548
+ forbidden(res, "forbidden");
549
+ return;
550
+ }
526
551
  const outcome = await dispatchAgentAction({ collection, action, seed: seed.prompt, itemId });
527
552
  if (!outcome.ok) {
528
553
  if (outcome.alreadyRunning) conflict(res, outcome.error);
@@ -618,7 +643,7 @@ router.post(
618
643
  kind: action.kind,
619
644
  });
620
645
  const seed = { prompt: buildActionSeedPrompt(record, template, promptPathsFor(collection, workspacePath)), role: action.role };
621
- await respondForActionKind(res, collection, action, seed, req.params.itemId);
646
+ await respondForActionKind(req, res, { collection, action, seed, itemId: req.params.itemId });
622
647
  } catch (err) {
623
648
  log.warn("collections", "action seed failed", {
624
649
  slug: collection.slug,
@@ -665,7 +690,7 @@ router.post(API_ROUTES.collections.collectionAction, async (req: Request<{ slug:
665
690
  serverError(res, `template '${action.template}' for action '${action.id}' could not be read`);
666
691
  return;
667
692
  }
668
- await respondForActionKind(res, collection, action, seed);
693
+ await respondForActionKind(req, res, { collection, action, seed });
669
694
  } catch (err) {
670
695
  log.warn("collections", "collection action seed failed", {
671
696
  slug: collection.slug,
@@ -936,33 +961,55 @@ router.get(API_ROUTES.collections.viewI18n, async (req: Request<{ slug: string }
936
961
  }
937
962
  });
938
963
 
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");
964
+ export interface ViewTokenDeps {
965
+ loadCollection: CollectionLoader;
966
+ mint: typeof mintViewToken;
967
+ }
968
+
969
+ /** The view-token mint behind a deps seam, so the response contract (clamped
970
+ * capabilities, schema-derived `fields`) is unit-testable without mounting
971
+ * the express app. */
972
+ export const createViewTokenHandler =
973
+ (deps: ViewTokenDeps) =>
974
+ async (req: Request<{ slug: string }>, res: Response): Promise<void> => {
975
+ if (isClientTokenRequest(req)) {
976
+ forbidden(res, "forbidden");
949
977
  return;
950
978
  }
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;
979
+ try {
980
+ const { slug } = req.params;
981
+ const body = requestBodyRecord(req.body);
982
+ const viewId = typeof body.viewId === "string" ? body.viewId.trim() : "";
983
+ if (!viewId) {
984
+ badRequest(res, "`viewId` is required");
985
+ return;
986
+ }
987
+ const resolved = await resolveCustomViewOr404(slug, viewId, res, deps.loadCollection);
988
+ if (!resolved) return;
989
+ const { collection, view } = resolved;
990
+ const granted = clampCapabilities(view.capabilities, parseCapabilities(body.capabilities));
991
+ const minted = deps.mint(slug, granted);
992
+ if (!minted) {
993
+ serverError(res, "view token unavailable (server not ready)");
994
+ return;
995
+ }
996
+ res.json({
997
+ token: minted.token,
998
+ exp: minted.exp,
999
+ dataUrl: API_ROUTES.collections.viewData.replace(":slug", slug),
1000
+ capabilities: granted,
1001
+ fields: buildCustomViewFields(collection.schema),
1002
+ });
1003
+ } catch (err) {
1004
+ log.warn("collections", "view-token mint failed", { slug: singleLineForLog(req.params.slug), error: errorMessage(err) });
1005
+ serverError(res, errorMessage(err));
959
1006
  }
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
- });
1007
+ };
1008
+
1009
+ // Mint a scoped token for a custom view. Behind the global bearer (only the
1010
+ // real frontend can mint); clamps requested caps to what the view declared
1011
+ // so a `read`-only view can never obtain a `write` token.
1012
+ router.post(API_ROUTES.collections.viewToken, createViewTokenHandler({ loadCollection, mint: mintViewToken }));
966
1013
 
967
1014
  // Scoped read: enriched records (getItems). Guarded by the view token only
968
1015
  // (exempt from global bearer + CSRF — see server/index.ts).
@@ -112,8 +112,8 @@ const SENSITIVE_BASENAMES = new Set([
112
112
  "credentials.json",
113
113
  // Claude Code credentials file written by server/credentials.ts.
114
114
  ".session-token",
115
- // Bearer auth token file — readable without auth via /api/files/*
116
- // exemption, so it must be blocked here (defense in depth).
115
+ // Bearer auth token file — readable without auth via the
116
+ // `GET /api/files/*` exemption, so it must be blocked here (defense in depth).
117
117
  ".npmrc",
118
118
  ".htpasswd",
119
119
  // Neither carries an extension, and `classify` answers "text" for every
@@ -202,10 +202,8 @@ export const VIDEO_EXTENSIONS = new Set([".mp4", ".webm", ".mov", ".m4v", ".ogv"
202
202
 
203
203
  /** Things a later double-click would execute. Refused on upload — a drop into
204
204
  * the workspace is for data, not for programs — and refused by the write gate
205
- * for the same reason: `/api/files/*` is exempt from bearer auth
206
- * (`server/index.ts`), so create and PUT are reachable by anything that can
207
- * talk to the loopback port, and "typed through one unauthenticated route" is
208
- * not a weaker capability than "dropped through another". PREVIEW is
205
+ * for the same reason: "typed through one route" is not a weaker capability
206
+ * than "dropped through another". PREVIEW is
209
207
  * deliberately unaffected — a `.sh` still renders as text, it just cannot be
210
208
  * written here. */
211
209
  export const BLOCKED_UPLOAD_EXTENSIONS = new Set([".exe", ".dll", ".so", ".dylib", ".bat", ".cmd", ".com", ".scr", ".msi", ".app", ".sh", ".ps1"]);