mulmoclaude 2.11.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 (39) hide show
  1. package/README.md +5 -1
  2. package/bin/mulmoclaude.js +13 -35
  3. package/client/assets/{marp-DvbfD9EO.js → marp-BH7JDaRq.js} +1 -1
  4. package/client/assets/{mulmoclaude3-BUmaA-ZX.js → mulmoclaude2-wt3640-35L_u9kD.js} +926 -921
  5. package/client/assets/mulmoclaude2-wt3640-DzadcIZy.css +2 -0
  6. package/client/index.html +2 -2
  7. package/package.json +4 -4
  8. package/server/api/auth/bearerAuth.ts +24 -12
  9. package/server/api/auth/bearerExemption.ts +38 -0
  10. package/server/api/auth/clientTokenCommands.ts +28 -8
  11. package/server/api/auth/clientTokenRule.ts +9 -8
  12. package/server/api/auth/clientTokenScope.ts +73 -0
  13. package/server/api/auth/clientTokenStore.ts +50 -2
  14. package/server/api/auth/clientTokenUsage.ts +85 -0
  15. package/server/api/auth/clientTokenUsageRule.ts +59 -0
  16. package/server/api/auth/ownerTokenHandoff.ts +73 -0
  17. package/server/api/auth/principal.ts +64 -3
  18. package/server/api/routes/clientTokens.ts +85 -0
  19. package/server/api/routes/collections.ts +20 -11
  20. package/server/api/routes/files.ts +4 -6
  21. package/server/build/mcp-server.mjs +727 -727
  22. package/server/index.ts +33 -53
  23. package/server/utils/wait-ready.d.mts +20 -0
  24. package/server/utils/wait-ready.mjs +64 -0
  25. package/src/components/SessionHistoryRow.vue +47 -41
  26. package/src/components/SettingsClientTokensTab.vue +176 -0
  27. package/src/components/SettingsModal.vue +4 -1
  28. package/src/config/apiRoutes.ts +4 -0
  29. package/src/lang/de.ts +25 -0
  30. package/src/lang/en.ts +24 -0
  31. package/src/lang/es.ts +24 -0
  32. package/src/lang/fr.ts +25 -0
  33. package/src/lang/ja.ts +24 -0
  34. package/src/lang/ko.ts +24 -0
  35. package/src/lang/pt-BR.ts +24 -0
  36. package/src/lang/zh.ts +23 -0
  37. package/client/assets/mulmoclaude3-D93Ihflz.css +0 -2
  38. package/server/system/logs/aaa +0 -737
  39. package/server/system/logs/bb +0 -446
@@ -2,6 +2,7 @@
2
2
  // randomness are injected so every command is testable without a terminal.
3
3
 
4
4
  import { addClientToken, revokeClientToken, type ClientTokenRecord } from "./clientTokenRule.js";
5
+ import { FULL_SCOPE, isClientTokenScope, type ClientTokenScope } from "./clientTokenScope.js";
5
6
  import { errorMessage } from "../../utils/errors.js";
6
7
  import { readClientTokenFile, withClientTokenLock, writeClientTokenFile } from "./clientTokenStore.js";
7
8
 
@@ -18,26 +19,42 @@ const EXIT_FAILURE = 1;
18
19
  const EXIT_USAGE = 2;
19
20
 
20
21
  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",
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",
24
25
  "",
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.",
26
30
  ];
27
31
 
32
+ const SCOPE_FLAG = "--scope";
33
+
28
34
  const ADD_REFUSALS = {
29
35
  "invalid-name": "is not a valid name",
30
36
  "duplicate-name": "is already in use; revoke it first or pick another name",
37
+ "invalid-scopes": "cannot have 'full' together with another scope",
31
38
  } as const;
32
39
 
33
- function addCommand(name: string, records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number {
34
- const result = addClientToken(records, { name, nowIso: deps.nowIso(), randomHex: deps.randomHex });
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 });
35
52
  if (!result.ok) {
36
53
  deps.printError(`"${name}" ${ADD_REFUSALS[result.reason]}.`);
37
- return result.reason === "invalid-name" ? EXIT_USAGE : EXIT_FAILURE;
54
+ return result.reason === "duplicate-name" ? EXIT_FAILURE : EXIT_USAGE;
38
55
  }
39
56
  writeClientTokenFile(deps.storePath, result.records);
40
- deps.print(`Issued client token "${name}" (id ${result.record.id}). It is shown only this once:`);
57
+ deps.print(`Issued client token "${name}" (id ${result.record.id}, scopes ${result.record.scopes.join(",")}). It is shown only this once:`);
41
58
  deps.print("");
42
59
  deps.print(result.token);
43
60
  deps.print("");
@@ -64,9 +81,12 @@ function revokeCommand(name: string, records: readonly ClientTokenRecord[], deps
64
81
 
65
82
  function dispatch(args: readonly string[], records: readonly ClientTokenRecord[], deps: ClientTokenCommandDeps): number | null {
66
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
+ }
67
88
  if (extra.length > 0) return null;
68
89
  if (command === "list" && name === undefined) return listCommand(records, deps);
69
- if (command === "add" && name !== undefined) return addCommand(name, records, deps);
70
90
  if (command === "revoke" && name !== undefined) return revokeCommand(name, records, deps);
71
91
  return null;
72
92
  }
@@ -8,6 +8,7 @@
8
8
  import { createHash } from "node:crypto";
9
9
  import { isAuthorizedToken, tokenEquals } from "@mulmoclaude/common/token-guard";
10
10
  import { isRecord, isUnknownArray } from "../../utils/types.js";
11
+ import { FULL_SCOPE, isClientTokenScope, isValidScopeSet, type ClientTokenScope } from "./clientTokenScope.js";
11
12
 
12
13
  export const CLIENT_TOKEN_PREFIX = "mct_";
13
14
  export const CLIENT_TOKEN_ID_BYTES = 8;
@@ -17,9 +18,6 @@ const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
17
18
  const CLIENT_TOKEN_NAME_RE = /^[A-Za-z0-9][\w.-]{0,63}$/;
18
19
  const STORE_VERSION = 1;
19
20
 
20
- export const CLIENT_TOKEN_SCOPES = ["full"] as const;
21
- export type ClientTokenScope = (typeof CLIENT_TOKEN_SCOPES)[number];
22
-
23
21
  export interface ClientTokenRecord {
24
22
  id: string;
25
23
  name: string;
@@ -30,8 +28,6 @@ export interface ClientTokenRecord {
30
28
 
31
29
  export type Principal = { kind: "owner" } | { kind: "client"; id: string; name: string; scopes: ClientTokenScope[] };
32
30
 
33
- const isScope = (value: unknown): value is ClientTokenScope => CLIENT_TOKEN_SCOPES.some((scope) => scope === value);
34
-
35
31
  export const isClientTokenName = (name: string): boolean => CLIENT_TOKEN_NAME_RE.test(name);
36
32
 
37
33
  export const hashClientToken = (token: string): string => createHash("sha256").update(token).digest("hex");
@@ -50,7 +46,7 @@ function toRecord(value: unknown): ClientTokenRecord | null {
50
46
  if (typeof name !== "string" || !isClientTokenName(name)) return null;
51
47
  if (typeof sha256 !== "string" || !SHA256_HEX_RE.test(sha256)) return null;
52
48
  if (typeof createdAt !== "string") return null;
53
- if (!isUnknownArray(scopes) || scopes.length === 0 || !scopes.every(isScope)) return null;
49
+ if (!isUnknownArray(scopes) || !scopes.every(isClientTokenScope) || !isValidScopeSet(scopes)) return null;
54
50
  return { id, name, sha256, createdAt, scopes: [...scopes] };
55
51
  }
56
52
 
@@ -91,20 +87,25 @@ export function resolvePrincipal(provided: unknown, ownerToken: string | null, c
91
87
  }
92
88
 
93
89
  export type AddClientTokenResult =
94
- { ok: true; records: ClientTokenRecord[]; token: string; record: ClientTokenRecord } | { ok: false; reason: "invalid-name" | "duplicate-name" };
90
+ | { ok: true; records: ClientTokenRecord[]; token: string; record: ClientTokenRecord }
91
+ | { ok: false; reason: "invalid-name" | "duplicate-name" | "invalid-scopes" };
95
92
 
96
93
  export interface AddClientTokenParams {
97
94
  name: string;
98
95
  nowIso: string;
99
96
  randomHex: (bytes: number) => string;
97
+ /** Defaults to `full`. */
98
+ scopes?: readonly ClientTokenScope[];
100
99
  }
101
100
 
102
101
  export function addClientToken(records: readonly ClientTokenRecord[], params: AddClientTokenParams): AddClientTokenResult {
103
102
  if (!isClientTokenName(params.name)) return { ok: false, reason: "invalid-name" };
104
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" };
105
106
  const tokenId = params.randomHex(CLIENT_TOKEN_ID_BYTES);
106
107
  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
+ const record: ClientTokenRecord = { id: tokenId, name: params.name, sha256: hashClientToken(token), createdAt: params.nowIso, scopes };
108
109
  return { ok: true, records: [...records, record], token, record };
109
110
  }
110
111
 
@@ -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
+ }
@@ -10,7 +10,8 @@ import { log } from "../../system/logger/index.js";
10
10
  import { errorMessage } from "../../utils/errors.js";
11
11
  import { isErrorWithCode } from "../../utils/types.js";
12
12
  import { ONE_SECOND_MS } from "../../utils/time.js";
13
- import { parseClientTokenStore, serializeClientTokenStore, type ClientTokenRecord } from "./clientTokenRule.js";
13
+ import { parseClientTokenStore, revokeClientToken, serializeClientTokenStore, type ClientTokenRecord } from "./clientTokenRule.js";
14
+ import { parseClientTokenUsage, type ClientTokenUsage } from "./clientTokenUsageRule.js";
14
15
 
15
16
  const STORE_FILE_MODE = 0o600;
16
17
  const STORE_DIR_MODE = 0o700;
@@ -21,6 +22,12 @@ export function clientTokensPath(home: string = homedir()): string {
21
22
  return path.join(home, ".mulmoclaude", "client-tokens.json");
22
23
  }
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
+
24
31
  const isMissing = (err: unknown): boolean => isErrorWithCode(err) && err.code === "ENOENT";
25
32
 
26
33
  function readBoundedFile(filePath: string): string {
@@ -89,7 +96,9 @@ function readLockState(lockPath: string, nowMs: number): LockState | null {
89
96
  }
90
97
  }
91
98
 
92
- const busyError = (lockPath: string): Error => new Error(`${lockPath}: another token command is running; retry once it finishes`);
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`);
93
102
 
94
103
  function openLock(lockPath: string): number {
95
104
  const handle = openSync(lockPath, "wx", STORE_FILE_MODE);
@@ -139,6 +148,45 @@ export function withClientTokenLock<T>(filePath: string, run: () => T, nowMs: nu
139
148
  }
140
149
  }
141
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
+
142
190
  const MISSING_KEY = "missing";
143
191
 
144
192
  // `ctimeMs` so a chmod alone is noticed. Any stat failure other than ENOENT
@@ -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
+ }
@@ -4,10 +4,16 @@
4
4
 
5
5
  import { getCurrentToken } from "./token.js";
6
6
  import { resolvePrincipal, type ClientTokenRecord, type Principal } from "./clientTokenRule.js";
7
- import { clientTokensPath, createClientTokenSource } from "./clientTokenStore.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";
8
13
 
9
14
  // Keyed by path because the path follows `homedir()`, which a test moves.
10
15
  const sources = new Map<string, () => readonly ClientTokenRecord[]>();
16
+ const usageTrackers = new Map<string, ClientTokenUsageTracker>();
11
17
 
12
18
  function storedClientTokens(): readonly ClientTokenRecord[] {
13
19
  const filePath = clientTokensPath();
@@ -16,11 +22,61 @@ function storedClientTokens(): readonly ClientTokenRecord[] {
16
22
  return source();
17
23
  }
18
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
+
19
53
  export function resolveTokenPrincipal(provided: unknown): Principal | null {
20
- return resolvePrincipal(provided, getCurrentToken(), storedClientTokens);
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 };
21
70
  }
22
71
 
23
- export const isAuthorizedBearer = (provided: unknown): boolean => resolveTokenPrincipal(provided) !== null;
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
+ }
24
80
 
25
81
  // Who `bearerAuth` let in, for a handler whose rule depends on more than the
26
82
  // path. A WeakMap so a finished request leaves nothing behind.
@@ -31,3 +87,8 @@ export function rememberRequestPrincipal(req: object, principal: Principal): voi
31
87
  }
32
88
 
33
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
+ }