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.
- package/README.md +15 -0
- package/bin/mulmoclaude.js +44 -51
- package/client/assets/{JsonEditor-E3FJ7oRf.js → JsonEditor-DnC5hozl.js} +1 -1
- package/client/assets/{marp-CmMNIT1E.js → marp-BH7JDaRq.js} +1 -1
- package/client/assets/material-symbols-outlined-DzTrJqFk.woff2 +0 -0
- package/client/assets/{feat-3497-Cwr8t4l4.js → mulmoclaude2-wt3640-35L_u9kD.js} +940 -929
- package/client/assets/mulmoclaude2-wt3640-DzadcIZy.css +2 -0
- package/client/assets/vue-i18n-BVPWXOdL.js +3 -0
- package/client/index.html +3 -3
- package/package.json +22 -22
- package/server/agent/backend/claude-code.ts +50 -5
- package/server/agent/config.ts +3 -1
- package/server/agent/sandboxEnv.ts +148 -0
- package/server/agent/sandboxEnvPlan.ts +188 -0
- package/server/api/auth/bearerAuth.ts +37 -16
- package/server/api/auth/bearerExemption.ts +38 -0
- package/server/api/auth/clientTokenAccess.ts +57 -0
- package/server/api/auth/clientTokenCli.ts +13 -0
- package/server/api/auth/clientTokenCommands.ts +110 -0
- package/server/api/auth/clientTokenRule.ts +116 -0
- package/server/api/auth/clientTokenScope.ts +73 -0
- package/server/api/auth/clientTokenStore.ts +226 -0
- package/server/api/auth/clientTokenUsage.ts +85 -0
- package/server/api/auth/clientTokenUsageRule.ts +59 -0
- package/server/api/auth/ownerTokenHandoff.ts +73 -0
- package/server/api/auth/principal.ts +94 -0
- package/server/api/routes/clientTokens.ts +85 -0
- package/server/api/routes/collections.ts +92 -45
- package/server/api/routes/files.ts +4 -6
- package/server/build/mcp-server.mjs +777 -768
- package/server/events/pub-sub/handshakeAuth.ts +3 -5
- package/server/events/pub-sub/index.ts +22 -4
- package/server/index.ts +33 -51
- package/server/system/env.ts +4 -0
- package/server/utils/wait-ready.d.mts +20 -0
- package/server/utils/wait-ready.mjs +64 -0
- package/src/components/SessionHistoryRow.vue +49 -33
- package/src/components/SettingsClientTokensTab.vue +176 -0
- package/src/components/SettingsModal.vue +4 -1
- package/src/config/apiRoutes.ts +4 -0
- package/src/lang/de.ts +25 -0
- package/src/lang/en.ts +24 -0
- package/src/lang/es.ts +24 -0
- package/src/lang/fr.ts +25 -0
- package/src/lang/ja.ts +24 -0
- package/src/lang/ko.ts +24 -0
- package/src/lang/pt-BR.ts +24 -0
- package/src/lang/zh.ts +23 -0
- package/src/utils/html/customViewSrcdoc.ts +5 -0
- package/client/assets/feat-3497-DEfIEPf6.css +0 -2
- package/client/assets/material-symbols-outlined-Bn5lkljl.woff2 +0 -0
- package/client/assets/vue-i18n-BHWgmfE3.js +0 -3
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
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 { FULL_SCOPE, isClientTokenScope, type ClientTokenScope } from "./clientTokenScope.js";
|
|
6
|
+
import { errorMessage } from "../../utils/errors.js";
|
|
7
|
+
import { readClientTokenFile, withClientTokenLock, writeClientTokenFile } from "./clientTokenStore.js";
|
|
8
|
+
|
|
9
|
+
export interface ClientTokenCommandDeps {
|
|
10
|
+
storePath: string;
|
|
11
|
+
nowIso: () => string;
|
|
12
|
+
randomHex: (bytes: number) => string;
|
|
13
|
+
print: (line: string) => void;
|
|
14
|
+
printError: (line: string) => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const EXIT_OK = 0;
|
|
18
|
+
const EXIT_FAILURE = 1;
|
|
19
|
+
const EXIT_USAGE = 2;
|
|
20
|
+
|
|
21
|
+
export const CLIENT_TOKEN_USAGE = [
|
|
22
|
+
"Usage: mulmoclaude token add <name> [--scope <scope>]... issue a token (shown once)",
|
|
23
|
+
" mulmoclaude token list list issued tokens (never their values)",
|
|
24
|
+
" mulmoclaude token revoke <name> revoke a token; a running server stops accepting it at once",
|
|
25
|
+
"",
|
|
26
|
+
"A name is 1-64 letters, digits, '.', '_' or '-', starting with a letter or digit.",
|
|
27
|
+
"A scope is 'full' (the default: the whole client API and both sockets), or any of",
|
|
28
|
+
"'read' (GET and HEAD only) and 'collection:<slug>' (that collection only; repeatable).",
|
|
29
|
+
"A token with scopes other than 'full' cannot open a socket. 'full' combines with nothing.",
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
const SCOPE_FLAG = "--scope";
|
|
33
|
+
|
|
34
|
+
const ADD_REFUSALS = {
|
|
35
|
+
"invalid-name": "is not a valid name",
|
|
36
|
+
"duplicate-name": "is already in use; revoke it first or pick another name",
|
|
37
|
+
"invalid-scopes": "cannot have 'full' together with another scope",
|
|
38
|
+
} as const;
|
|
39
|
+
|
|
40
|
+
/** `--scope <scope>` pairs, or null when anything else is there. */
|
|
41
|
+
export function parseScopeFlags(flags: readonly string[]): ClientTokenScope[] | null {
|
|
42
|
+
if (flags.length % 2 !== 0) return null;
|
|
43
|
+
const isFlagPosition = (index: number): boolean => index % 2 === 0;
|
|
44
|
+
if (!flags.every((flag, index) => !isFlagPosition(index) || flag === SCOPE_FLAG)) return null;
|
|
45
|
+
const values = flags.filter((_, index) => !isFlagPosition(index));
|
|
46
|
+
return values.every(isClientTokenScope) ? values : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function addCommand(name: string, scopes: readonly ClientTokenScope[], records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
|
|
50
|
+
const requested: readonly ClientTokenScope[] = scopes.length > 0 ? scopes : [FULL_SCOPE];
|
|
51
|
+
const result = addClientToken(records, { name, nowIso: deps.nowIso(), randomHex: deps.randomHex, scopes: requested });
|
|
52
|
+
if (!result.ok) {
|
|
53
|
+
deps.printError(`"${name}" ${ADD_REFUSALS[result.reason]}.`);
|
|
54
|
+
return result.reason === "duplicate-name" ? EXIT_FAILURE : EXIT_USAGE;
|
|
55
|
+
}
|
|
56
|
+
writeClientTokenFile(deps.storePath, result.records);
|
|
57
|
+
deps.print(`Issued client token "${name}" (id ${result.record.id}, scopes ${result.record.scopes.join(",")}). It is shown only this once:`);
|
|
58
|
+
deps.print("");
|
|
59
|
+
deps.print(result.token);
|
|
60
|
+
deps.print("");
|
|
61
|
+
deps.print("Give it to that client as MULMOCLAUDE_AUTH_TOKEN, and to no other.");
|
|
62
|
+
return EXIT_OK;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function listCommand(records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
|
|
66
|
+
if (records.length === 0) deps.print("No client tokens issued.");
|
|
67
|
+
records.forEach((record) => deps.print(`${record.name}\t${record.id}\t${record.createdAt}\t${record.scopes.join(",")}`));
|
|
68
|
+
return EXIT_OK;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function revokeCommand(name: string, records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
|
|
72
|
+
const remaining = revokeClientToken(records, name);
|
|
73
|
+
if (remaining === null) {
|
|
74
|
+
deps.printError(`No client token named "${name}".`);
|
|
75
|
+
return EXIT_FAILURE;
|
|
76
|
+
}
|
|
77
|
+
writeClientTokenFile(deps.storePath, remaining);
|
|
78
|
+
deps.print(`Revoked client token "${name}".`);
|
|
79
|
+
return EXIT_OK;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function dispatch(args: readonly string[], records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number | null {
|
|
83
|
+
const [command, name, ...extra] = args;
|
|
84
|
+
if (command === "add" && name !== undefined) {
|
|
85
|
+
const scopes = parseScopeFlags(extra);
|
|
86
|
+
return scopes === null ? null : addCommand(name, scopes, records, deps);
|
|
87
|
+
}
|
|
88
|
+
if (extra.length > 0) return null;
|
|
89
|
+
if (command === "list" && name === undefined) return listCommand(records, deps);
|
|
90
|
+
if (command === "revoke" && name !== undefined) return revokeCommand(name, records, deps);
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function runLocked(args: readonly string[], deps: ClientTokenCommandDeps): number {
|
|
95
|
+
const { records, droppedCount } = readClientTokenFile(deps.storePath);
|
|
96
|
+
if (droppedCount > 0) deps.printError(`${deps.storePath}: ${droppedCount} invalid entries are ignored and will be dropped on the next change.`);
|
|
97
|
+
const exitCode = dispatch(args, records, deps);
|
|
98
|
+
if (exitCode !== null) return exitCode;
|
|
99
|
+
CLIENT_TOKEN_USAGE.forEach((line) => deps.printError(line));
|
|
100
|
+
return EXIT_USAGE;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function runClientTokenCommand(args: readonly string[], deps: ClientTokenCommandDeps): number {
|
|
104
|
+
try {
|
|
105
|
+
return withClientTokenLock(deps.storePath, () => runLocked(args, deps));
|
|
106
|
+
} catch (err) {
|
|
107
|
+
deps.printError(errorMessage(err));
|
|
108
|
+
return EXIT_FAILURE;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
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
|
+
import { FULL_SCOPE, isClientTokenScope, isValidScopeSet, type ClientTokenScope } from "./clientTokenScope.js";
|
|
12
|
+
|
|
13
|
+
export const CLIENT_TOKEN_PREFIX = "mct_";
|
|
14
|
+
export const CLIENT_TOKEN_ID_BYTES = 8;
|
|
15
|
+
export const CLIENT_TOKEN_SECRET_BYTES = 32;
|
|
16
|
+
const CLIENT_TOKEN_RE = /^mct_([0-9a-f]{16})_[0-9a-f]{64}$/;
|
|
17
|
+
const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
|
|
18
|
+
const CLIENT_TOKEN_NAME_RE = /^[A-Za-z0-9][\w.-]{0,63}$/;
|
|
19
|
+
const STORE_VERSION = 1;
|
|
20
|
+
|
|
21
|
+
export interface ClientTokenRecord {
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
sha256: string;
|
|
25
|
+
createdAt: string;
|
|
26
|
+
scopes: ClientTokenScope[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type Principal = { kind: "owner" } | { kind: "client"; id: string; name: string; scopes: ClientTokenScope[] };
|
|
30
|
+
|
|
31
|
+
export const isClientTokenName = (name: string): boolean => CLIENT_TOKEN_NAME_RE.test(name);
|
|
32
|
+
|
|
33
|
+
export const hashClientToken = (token: string): string => createHash("sha256").update(token).digest("hex");
|
|
34
|
+
|
|
35
|
+
export const formatClientToken = (idHex: string, secretHex: string): string => `${CLIENT_TOKEN_PREFIX}${idHex}_${secretHex}`;
|
|
36
|
+
|
|
37
|
+
/** The id part of a well-formed client token, or null for anything else. */
|
|
38
|
+
export function clientTokenId(token: string): string | null {
|
|
39
|
+
return CLIENT_TOKEN_RE.exec(token)?.[1] ?? null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function toRecord(value: unknown): ClientTokenRecord | null {
|
|
43
|
+
if (!isRecord(value)) return null;
|
|
44
|
+
const { id, name, sha256, createdAt, scopes } = value;
|
|
45
|
+
if (typeof id !== "string" || !/^[0-9a-f]{16}$/.test(id)) return null;
|
|
46
|
+
if (typeof name !== "string" || !isClientTokenName(name)) return null;
|
|
47
|
+
if (typeof sha256 !== "string" || !SHA256_HEX_RE.test(sha256)) return null;
|
|
48
|
+
if (typeof createdAt !== "string") return null;
|
|
49
|
+
if (!isUnknownArray(scopes) || !scopes.every(isClientTokenScope) || !isValidScopeSet(scopes)) return null;
|
|
50
|
+
return { id, name, sha256, createdAt, scopes: [...scopes] };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ParsedClientTokenStore {
|
|
54
|
+
records: ClientTokenRecord[];
|
|
55
|
+
/** Entries that were not a valid record; they authorize nothing. */
|
|
56
|
+
droppedCount: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The store file's parsed JSON. Throws on a file that is not a store at all,
|
|
60
|
+
* so the server accepts no client token and the CLI does not overwrite it. */
|
|
61
|
+
export function parseClientTokenStore(raw: unknown): ParsedClientTokenStore {
|
|
62
|
+
if (!isRecord(raw) || raw.version !== STORE_VERSION || !isUnknownArray(raw.tokens)) throw new Error(`not a version ${STORE_VERSION} client-token store`);
|
|
63
|
+
const parsed = raw.tokens.map(toRecord);
|
|
64
|
+
const records = parsed.filter((record): record is ClientTokenRecord => record !== null);
|
|
65
|
+
return { records, droppedCount: parsed.length - records.length };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function serializeClientTokenStore(records: readonly ClientTokenRecord[]): string {
|
|
69
|
+
return `${JSON.stringify({ version: STORE_VERSION, tokens: records }, null, 2)}\n`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function findClientToken(token: string, records: readonly ClientTokenRecord[]): ClientTokenRecord | null {
|
|
73
|
+
const tokenId = clientTokenId(token);
|
|
74
|
+
const record = tokenId === null ? undefined : records.find((candidate) => candidate.id === tokenId);
|
|
75
|
+
if (record === undefined) return null;
|
|
76
|
+
return tokenEquals(hashClientToken(token), record.sha256) ? record : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Owner first, so the store is read only for a token in the client format.
|
|
80
|
+
* No owner token yet (pre-bootstrap) refuses everything, client tokens too. */
|
|
81
|
+
export function resolvePrincipal(provided: unknown, ownerToken: string | null, clientTokens: () => readonly ClientTokenRecord[]): Principal | null {
|
|
82
|
+
if (ownerToken === null || ownerToken === "") return null;
|
|
83
|
+
if (isAuthorizedToken(provided, ownerToken)) return { kind: "owner" };
|
|
84
|
+
if (typeof provided !== "string" || !provided.startsWith(CLIENT_TOKEN_PREFIX)) return null;
|
|
85
|
+
const record = findClientToken(provided, clientTokens());
|
|
86
|
+
return record === null ? null : { kind: "client", id: record.id, name: record.name, scopes: record.scopes };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type AddClientTokenResult =
|
|
90
|
+
| { ok: true; records: ClientTokenRecord[]; token: string; record: ClientTokenRecord }
|
|
91
|
+
| { ok: false; reason: "invalid-name" | "duplicate-name" | "invalid-scopes" };
|
|
92
|
+
|
|
93
|
+
export interface AddClientTokenParams {
|
|
94
|
+
name: string;
|
|
95
|
+
nowIso: string;
|
|
96
|
+
randomHex: (bytes: number) => string;
|
|
97
|
+
/** Defaults to `full`. */
|
|
98
|
+
scopes?: readonly ClientTokenScope[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function addClientToken(records: readonly ClientTokenRecord[], params: AddClientTokenParams): AddClientTokenResult {
|
|
102
|
+
if (!isClientTokenName(params.name)) return { ok: false, reason: "invalid-name" };
|
|
103
|
+
if (records.some((record) => record.name === params.name)) return { ok: false, reason: "duplicate-name" };
|
|
104
|
+
const scopes = [...new Set<ClientTokenScope>(params.scopes ?? [FULL_SCOPE])];
|
|
105
|
+
if (!isValidScopeSet(scopes)) return { ok: false, reason: "invalid-scopes" };
|
|
106
|
+
const tokenId = params.randomHex(CLIENT_TOKEN_ID_BYTES);
|
|
107
|
+
const token = formatClientToken(tokenId, params.randomHex(CLIENT_TOKEN_SECRET_BYTES));
|
|
108
|
+
const record: ClientTokenRecord = { id: tokenId, name: params.name, sha256: hashClientToken(token), createdAt: params.nowIso, scopes };
|
|
109
|
+
return { ok: true, records: [...records, record], token, record };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The records without `name`, or null when no token has that name. */
|
|
113
|
+
export function revokeClientToken(records: readonly ClientTokenRecord[], name: string): ClientTokenRecord[] | null {
|
|
114
|
+
const remaining = records.filter((record) => record.name !== name);
|
|
115
|
+
return remaining.length === records.length ? null : remaining;
|
|
116
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// What a client token's scopes let it reach (#3636). `full` is stage 1's reach;
|
|
2
|
+
// otherwise `read` limits the methods and `collection:<slug>` limits the paths
|
|
3
|
+
// to those collections. Pure. Every doubtful request is refused, never guessed.
|
|
4
|
+
|
|
5
|
+
import { isSafeSlug } from "@mulmoclaude/core/collection";
|
|
6
|
+
import { isReadMethod, type ApiRequestLine } from "./bearerExemption.js";
|
|
7
|
+
|
|
8
|
+
export const FULL_SCOPE = "full";
|
|
9
|
+
export const READ_SCOPE = "read";
|
|
10
|
+
const COLLECTION_SCOPE_PREFIX = "collection:";
|
|
11
|
+
const COLLECTIONS_SEGMENT = "collections";
|
|
12
|
+
// A static route under `/collections`, matched before `:slug`, that spans every collection.
|
|
13
|
+
const ONTOLOGY_SEGMENT = "ontology";
|
|
14
|
+
|
|
15
|
+
export type ClientTokenScope = typeof FULL_SCOPE | typeof READ_SCOPE | `${typeof COLLECTION_SCOPE_PREFIX}${string}`;
|
|
16
|
+
|
|
17
|
+
const isCollectionScope = (value: string): value is `${typeof COLLECTION_SCOPE_PREFIX}${string}` =>
|
|
18
|
+
value.startsWith(COLLECTION_SCOPE_PREFIX) && isSafeSlug(value.slice(COLLECTION_SCOPE_PREFIX.length));
|
|
19
|
+
|
|
20
|
+
export const isClientTokenScope = (value: unknown): value is ClientTokenScope =>
|
|
21
|
+
typeof value === "string" && (value === FULL_SCOPE || value === READ_SCOPE || isCollectionScope(value));
|
|
22
|
+
|
|
23
|
+
/** At least one scope, and `full` only on its own. */
|
|
24
|
+
export const isValidScopeSet = (scopes: readonly ClientTokenScope[]): boolean => scopes.length > 0 && (!scopes.includes(FULL_SCOPE) || scopes.length === 1);
|
|
25
|
+
|
|
26
|
+
export const hasFullScope = (scopes: readonly ClientTokenScope[]): boolean => scopes.includes(FULL_SCOPE);
|
|
27
|
+
|
|
28
|
+
function scopedCollections(scopes: readonly ClientTokenScope[]): string[] {
|
|
29
|
+
return scopes.filter(isCollectionScope).map((scope) => scope.slice(COLLECTION_SCOPE_PREFIX.length));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Whether a collection may be shown to this token, e.g. in the collection list. */
|
|
33
|
+
export function isCollectionInScope(scopes: readonly ClientTokenScope[], slug: string): boolean {
|
|
34
|
+
const collections = scopedCollections(scopes);
|
|
35
|
+
return collections.length === 0 || collections.includes(slug);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function decodeSegment(segment: string): string | null {
|
|
39
|
+
try {
|
|
40
|
+
return decodeURIComponent(segment);
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The path's segments, decoded one by one so an encoded `/` stays inside its
|
|
47
|
+
// segment; null for an undecodable or dot segment.
|
|
48
|
+
function pathSegments(rawPath: string): string[] | null {
|
|
49
|
+
const decoded = rawPath.split("/").slice(1).map(decodeSegment);
|
|
50
|
+
if (decoded.some((segment) => segment === null || segment === "." || segment === "..")) return null;
|
|
51
|
+
const segments = decoded.filter((segment): segment is string => segment !== null);
|
|
52
|
+
return segments.length > 1 && segments.at(-1) === "" ? segments.slice(0, -1) : segments;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Express matches the static part case-insensitively; the slug it hands the
|
|
56
|
+
// handler keeps its case, so the slug is compared exactly.
|
|
57
|
+
function isCollectionPathInScope({ method, path }: ApiRequestLine, collections: readonly string[]): boolean {
|
|
58
|
+
const segments = pathSegments(path);
|
|
59
|
+
if (segments === null || segments[0]?.toLowerCase() !== COLLECTIONS_SEGMENT) return false;
|
|
60
|
+
const [, slug] = segments;
|
|
61
|
+
if (slug === undefined) return isReadMethod(method);
|
|
62
|
+
if (slug.toLowerCase() === ONTOLOGY_SEGMENT) return false;
|
|
63
|
+
return collections.includes(slug);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Whether a client token's scopes cover this `/api` request (relative to the mount). */
|
|
67
|
+
export function isWithinClientTokenScopes(scopes: readonly ClientTokenScope[], request: ApiRequestLine): boolean {
|
|
68
|
+
if (!isValidScopeSet(scopes)) return false;
|
|
69
|
+
if (hasFullScope(scopes)) return true;
|
|
70
|
+
if (scopes.includes(READ_SCOPE) && !isReadMethod(request.method)) return false;
|
|
71
|
+
const collections = scopedCollections(scopes);
|
|
72
|
+
return collections.length === 0 || isCollectionPathInScope(request, collections);
|
|
73
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
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, revokeClientToken, serializeClientTokenStore, type ClientTokenRecord } from "./clientTokenRule.js";
|
|
14
|
+
import { parseClientTokenUsage, type ClientTokenUsage } from "./clientTokenUsageRule.js";
|
|
15
|
+
|
|
16
|
+
const STORE_FILE_MODE = 0o600;
|
|
17
|
+
const STORE_DIR_MODE = 0o700;
|
|
18
|
+
// Each record is a few hundred bytes; a file this large is not one we wrote.
|
|
19
|
+
const STORE_MAX_BYTES = 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
export function clientTokensPath(home: string = homedir()): string {
|
|
22
|
+
return path.join(home, ".mulmoclaude", "client-tokens.json");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Last-used times (#3637). A file of its own, so recording a use never
|
|
26
|
+
* rewrites the store the server watches and the CLI locks. */
|
|
27
|
+
export function clientTokenUsagePath(home: string = homedir()): string {
|
|
28
|
+
return path.join(home, ".mulmoclaude", "client-tokens-usage.json");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const isMissing = (err: unknown): boolean => isErrorWithCode(err) && err.code === "ENOENT";
|
|
32
|
+
|
|
33
|
+
function readBoundedFile(filePath: string): string {
|
|
34
|
+
const handle = openSync(filePath, "r");
|
|
35
|
+
try {
|
|
36
|
+
const { size } = fstatSync(handle);
|
|
37
|
+
if (size > STORE_MAX_BYTES) throw new Error(`larger than ${STORE_MAX_BYTES} bytes`);
|
|
38
|
+
const buffer = Buffer.alloc(size);
|
|
39
|
+
const bytes = readSync(handle, buffer, 0, size, 0);
|
|
40
|
+
return buffer.subarray(0, bytes).toString("utf8");
|
|
41
|
+
} finally {
|
|
42
|
+
closeSync(handle);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The stored records. A missing file is an empty store; anything unreadable
|
|
47
|
+
* throws, with the path in the message. */
|
|
48
|
+
export function readClientTokenFile(filePath: string): { records: ClientTokenRecord[]; droppedCount: number } {
|
|
49
|
+
try {
|
|
50
|
+
return parseClientTokenStore(JSON.parse(readBoundedFile(filePath)));
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (isMissing(err)) return { records: [], droppedCount: 0 };
|
|
53
|
+
throw new Error(`${filePath}: ${errorMessage(err)}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Refuses a store it could not read back, rather than locking every client out. */
|
|
58
|
+
export function writeClientTokenFile(filePath: string, records: readonly ClientTokenRecord[]): void {
|
|
59
|
+
const text = serializeClientTokenStore(records);
|
|
60
|
+
if (Buffer.byteLength(text, "utf8") > STORE_MAX_BYTES) throw new Error(`${filePath}: the store would exceed ${STORE_MAX_BYTES} bytes`);
|
|
61
|
+
mkdirSync(path.dirname(filePath), { recursive: true, mode: STORE_DIR_MODE });
|
|
62
|
+
writeFileAtomicSync(filePath, text, { mode: STORE_FILE_MODE });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// A lock with no readable owner pid (written by a command killed before it
|
|
66
|
+
// recorded one) is taken over after this long.
|
|
67
|
+
const LOCK_STALE_MS = 30 * ONE_SECOND_MS;
|
|
68
|
+
|
|
69
|
+
interface LockState {
|
|
70
|
+
ownerPid: number | null;
|
|
71
|
+
ageMs: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A lock is abandoned when its recorded owner is gone; age decides only when
|
|
75
|
+
* no owner was recorded, so a paused but live command keeps its lock. */
|
|
76
|
+
export function isAbandonedLock(lock: LockState, isOwnerAlive: (pid: number) => boolean): boolean {
|
|
77
|
+
return lock.ownerPid === null ? lock.ageMs > LOCK_STALE_MS : !isOwnerAlive(lock.ownerPid);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isProcessAlive(pid: number): boolean {
|
|
81
|
+
try {
|
|
82
|
+
process.kill(pid, 0);
|
|
83
|
+
return true;
|
|
84
|
+
} catch (err) {
|
|
85
|
+
return isErrorWithCode(err) && err.code === "EPERM";
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function readLockState(lockPath: string, nowMs: number): LockState | null {
|
|
90
|
+
try {
|
|
91
|
+
const ageMs = nowMs - statSync(lockPath).mtimeMs;
|
|
92
|
+
const pid = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
|
|
93
|
+
return { ownerPid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, ageMs };
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class ClientTokenLockBusyError extends Error {}
|
|
100
|
+
|
|
101
|
+
const busyError = (lockPath: string): Error => new ClientTokenLockBusyError(`${lockPath}: another token command is running; retry once it finishes`);
|
|
102
|
+
|
|
103
|
+
function openLock(lockPath: string): number {
|
|
104
|
+
const handle = openSync(lockPath, "wx", STORE_FILE_MODE);
|
|
105
|
+
writeSync(handle, `${process.pid}\n`);
|
|
106
|
+
return handle;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function acquireLock(lockPath: string, nowMs: number): number {
|
|
110
|
+
try {
|
|
111
|
+
return openLock(lockPath);
|
|
112
|
+
} catch (err) {
|
|
113
|
+
if (!isErrorWithCode(err) || err.code !== "EEXIST") throw busyError(lockPath);
|
|
114
|
+
const state = readLockState(lockPath, nowMs);
|
|
115
|
+
if (state !== null && !isAbandonedLock(state, isProcessAlive)) throw busyError(lockPath);
|
|
116
|
+
rmSync(lockPath, { force: true });
|
|
117
|
+
try {
|
|
118
|
+
return openLock(lockPath);
|
|
119
|
+
} catch {
|
|
120
|
+
throw busyError(lockPath);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Only the lock this command created: if it was taken over, the new owner's
|
|
126
|
+
// lock must survive this command's cleanup.
|
|
127
|
+
function releaseLock(lockPath: string, handle: number): void {
|
|
128
|
+
const { dev, ino } = fstatSync(handle);
|
|
129
|
+
closeSync(handle);
|
|
130
|
+
try {
|
|
131
|
+
const current = statSync(lockPath);
|
|
132
|
+
if (current.dev === dev && current.ino === ino) rmSync(lockPath, { force: true });
|
|
133
|
+
} catch {
|
|
134
|
+
// Already gone.
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Runs a read-modify-write of the store with no other token command in between,
|
|
139
|
+
* so two commands cannot drop each other's add or undo each other's revoke. */
|
|
140
|
+
export function withClientTokenLock<T>(filePath: string, run: () => T, nowMs: number = Date.now()): T {
|
|
141
|
+
mkdirSync(path.dirname(filePath), { recursive: true, mode: STORE_DIR_MODE });
|
|
142
|
+
const lockPath = `${filePath}.lock`;
|
|
143
|
+
const handle = acquireLock(lockPath, nowMs);
|
|
144
|
+
try {
|
|
145
|
+
return run();
|
|
146
|
+
} finally {
|
|
147
|
+
releaseLock(lockPath, handle);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export const REVOKE_OUTCOMES = {
|
|
152
|
+
revoked: "revoked",
|
|
153
|
+
notFound: "not-found",
|
|
154
|
+
/** The name now belongs to a different token than the one the page listed. */
|
|
155
|
+
changed: "changed",
|
|
156
|
+
/** A rewrite would drop entries this server cannot read, e.g. ones a newer version wrote. */
|
|
157
|
+
unreadableEntries: "unreadable-entries",
|
|
158
|
+
} as const;
|
|
159
|
+
export type RevokeOutcome = (typeof REVOKE_OUTCOMES)[keyof typeof REVOKE_OUTCOMES];
|
|
160
|
+
|
|
161
|
+
/** `token revoke` for the Settings page: same lock, same rule, but only the token
|
|
162
|
+
* the page showed. Throws `ClientTokenLockBusyError` while a CLI command runs. */
|
|
163
|
+
export function revokeStoredClientToken(filePath: string, target: { name: string; id: string }): RevokeOutcome {
|
|
164
|
+
return withClientTokenLock(filePath, () => {
|
|
165
|
+
const { records, droppedCount } = readClientTokenFile(filePath);
|
|
166
|
+
const record = records.find((candidate) => candidate.name === target.name);
|
|
167
|
+
if (record === undefined) return REVOKE_OUTCOMES.notFound;
|
|
168
|
+
if (record.id !== target.id) return REVOKE_OUTCOMES.changed;
|
|
169
|
+
if (droppedCount > 0) return REVOKE_OUTCOMES.unreadableEntries;
|
|
170
|
+
writeClientTokenFile(filePath, revokeClientToken(records, target.name) ?? records);
|
|
171
|
+
return REVOKE_OUTCOMES.revoked;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Missing or unreadable reads as empty, logged: losing these times costs only the times. */
|
|
176
|
+
export function readClientTokenUsageFile(filePath: string): ClientTokenUsage {
|
|
177
|
+
try {
|
|
178
|
+
return parseClientTokenUsage(JSON.parse(readBoundedFile(filePath)));
|
|
179
|
+
} catch (err) {
|
|
180
|
+
if (!isMissing(err)) log.warn("auth", "client-token usage file unreadable; last-used times start over", { path: filePath, error: errorMessage(err) });
|
|
181
|
+
return new Map();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function writeClientTokenUsageFile(filePath: string, text: string): void {
|
|
186
|
+
mkdirSync(path.dirname(filePath), { recursive: true, mode: STORE_DIR_MODE });
|
|
187
|
+
writeFileAtomicSync(filePath, text, { mode: STORE_FILE_MODE });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const MISSING_KEY = "missing";
|
|
191
|
+
|
|
192
|
+
// `ctimeMs` so a chmod alone is noticed. Any stat failure other than ENOENT
|
|
193
|
+
// gets its own key and goes on to the read, which logs why it failed.
|
|
194
|
+
function statKey(filePath: string): string {
|
|
195
|
+
try {
|
|
196
|
+
const stats = statSync(filePath);
|
|
197
|
+
return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}`;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
return isMissing(err) ? MISSING_KEY : `stat-error:${isErrorWithCode(err) ? err.code : "unknown"}`;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function loadForServer(filePath: string): ClientTokenRecord[] {
|
|
204
|
+
try {
|
|
205
|
+
const { records, droppedCount } = readClientTokenFile(filePath);
|
|
206
|
+
if (droppedCount > 0) log.warn("auth", "client-token store has invalid entries; they authorize nothing", { path: filePath, droppedCount });
|
|
207
|
+
return records;
|
|
208
|
+
} catch (err) {
|
|
209
|
+
log.warn("auth", "client-token store unreadable; no client token is accepted", { error: errorMessage(err) });
|
|
210
|
+
return [];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The records, re-read whenever the file changes (an atomic write replaces
|
|
215
|
+
* the inode), so `token revoke` applies to the next request. */
|
|
216
|
+
export function createClientTokenSource(filePath: string): () => readonly ClientTokenRecord[] {
|
|
217
|
+
const cache: { key: string | null; records: readonly ClientTokenRecord[] } = { key: null, records: [] };
|
|
218
|
+
return () => {
|
|
219
|
+
const key = statKey(filePath);
|
|
220
|
+
if (key !== cache.key) {
|
|
221
|
+
cache.records = key === MISSING_KEY ? [] : loadForServer(filePath);
|
|
222
|
+
cache.key = key;
|
|
223
|
+
}
|
|
224
|
+
return cache.records;
|
|
225
|
+
};
|
|
226
|
+
}
|