Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(thin-client): one cache file per client, read without following symlinks

garrytan79d02f7cecb6
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 81716349bd..87f94f008b 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. Access tokens are cached in process and in `src/core/remote-token-cache.ts`: a 0600 file (`remote-token-cache.json` under the gbrain home) shared by every CLI process, keyed by a hash of issuer, MCP URL, client id and secret, holding only the bearer and its expiry (30 s before the host's), written by atomic rename, ignored and deleted when another user could read it; an HTTP 401 drops the entry. The host authorizes every request against the client's current grant, so a cached token never outranks it (`test/thin-client-token-cache-7360.test.ts`). `_clearMcpClientTokenCache({keepDisk})` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. Access tokens are cached in process and in `src/core/remote-token-cache.ts`: one 0600 file per key under `remote-tokens/` in the gbrain home, shared by every CLI process, keyed by a hash of issuer, MCP URL, client id and secret, holding only the bearer and its expiry (30 s before the host's), written by atomic rename, read through an `O_NOFOLLOW` descriptor whose `fstat` must show this user and no group/other bits (otherwise deleted); an HTTP 401 drops the entry. The host authorizes every request against the client's current grant, so a cached token never outranks it (`test/thin-client-token-cache-7360.test.ts`). `_clearMcpClientTokenCache({keepDisk})` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests and `stuck-recovery-resolution` audit entries (`gbrain repair stuck-recovery`) never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`). #6351: `loadApprovedSet` takes an optional lazy `emptyHash` (the hash a preview of the same selection prints when it finds nothing, from current state including source incarnations); with no saved row and a matching hash it returns an empty set, so the apply command an empty preview prints succeeds while a changed incarnation still refuses `preview_changed`. The eight preview-bound repair kinds without a local `emptyPlanHash` (stale-atoms, captured-facts, conversation-labels, extractor-facts, failed-writes, frontmatter, loop-facts, ontology-facts) pass it. Pinned by `test/repair-empty-preview-apply.test.ts`.
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index fce6d52e98..b9182e194b 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -208,11 +208,12 @@ Three storage paths in priority order:
3. macOS Keychain integration is not supported (roadmap item).
The access token the thin client mints is cached in
-`~/.gbrain/remote-token-cache.json` (0600, bearer and expiry only, no secret)
-and reused by every `gbrain` command until 30 seconds before it expires, so a
+`~/.gbrain/remote-tokens/` (one 0600 file per client, bearer and expiry only,
+no secret) and reused by every `gbrain` command until 30 seconds before it expires, so a
per-prompt hook mints about one token per token lifetime instead of one per
command. Changing the client id or secret starts a fresh token; deleting the
-file is always safe. The host still checks each request against the client's
+directory is always safe. Processes that start together with no cached token
+each mint one. The host still checks each request against the client's
current grant, so narrowing or revoking the client takes effect on the cached
token at once.
diff --git a/src/core/remote-token-cache.ts b/src/core/remote-token-cache.ts
index eb1e1108a6..0d5463e9bb 100644
--- a/src/core/remote-token-cache.ts
+++ b/src/core/remote-token-cache.ts
@@ -7,15 +7,19 @@
* until shortly before it expires.
*
* Trust: an entry is keyed by a hash of the issuer, MCP URL, client id and
- * client secret, so another client or a rotated secret never reuses it. The
- * file stores the bearer and its expiry only (no secret, no client id) and is
- * written 0600 by an atomic rename, which replaces a planted symlink instead
- * of writing through it. A file another user could read is not trusted. The
- * host authorizes every request against the client's current grant, so a
- * cached token never acts with more scope than the client holds.
+ * client secret, so another client or a rotated secret never reuses it. Each
+ * key has its own file under `remote-tokens/` in the gbrain home, holding the
+ * bearer and its expiry only (no secret, no client id). A file is written
+ * 0600 by an atomic rename, which replaces a planted symlink instead of
+ * writing through it, and read through a descriptor opened without following
+ * symlinks, so the ownership and mode it checks belong to the bytes it reads.
+ * A file another user owns or could read is deleted and not used. The host
+ * authorizes every request against the client's current grant, so a cached
+ * token never acts with more scope than the client holds.
*/
import { createHash, randomUUID } from 'node:crypto';
-import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
import { gbrainPath } from './config.ts';
export interface CachedToken {
@@ -24,73 +28,54 @@ export interface CachedToken {
expires_at_ms: number;
}
-interface CacheFile { version: 1; entries: Record<string, CachedToken> }
-
-const cachePath = () => gbrainPath('remote-token-cache.json');
+const cacheDir = () => gbrainPath('remote-tokens');
+const entryPath = (key: string) => join(cacheDir(), `${key}.json`);
export function tokenCacheKey(remote: { issuer_url: string; mcp_url: string; oauth_client_id: string }, secret: string): string {
return createHash('sha256').update(JSON.stringify([remote.issuer_url, remote.mcp_url, remote.oauth_client_id, secret])).digest('hex');
}
-function readEntries(): Record<string, CachedToken> {
- const path = cachePath();
+export function readCachedToken(key: string): CachedToken | undefined {
+ const path = entryPath(key);
+ let fd: number;
+ try {
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ELOOP') dropCachedToken(key);
+ return undefined;
+ }
try {
- const st = lstatSync(path);
+ const st = fstatSync(fd);
if (!st.isFile() || (st.mode & 0o077) !== 0 || (typeof process.getuid === 'function' && st.uid !== process.getuid())) {
- rmSync(path, { force: true });
- return {};
+ dropCachedToken(key);
+ return undefined;
}
- const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<CacheFile>;
- if (parsed?.version !== 1 || !parsed.entries || typeof parsed.entries !== 'object' || Array.isArray(parsed.entries)) return {};
- const entries: Record<string, CachedToken> = {};
- for (const [key, value] of Object.entries(parsed.entries)) {
- if (typeof value?.access_token === 'string' && Number.isFinite(value.expires_at_ms)) entries[key] = value;
- }
- return entries;
+ const entry = JSON.parse(readFileSync(fd, 'utf8')) as Partial<CachedToken>;
+ if (typeof entry?.access_token !== 'string' || typeof entry.expires_at_ms !== 'number' || !(entry.expires_at_ms > Date.now())) return undefined;
+ return { access_token: entry.access_token, expires_at_ms: entry.expires_at_ms };
} catch {
- return {};
+ return undefined;
+ } finally {
+ closeSync(fd);
}
}
-function writeEntries(entries: Record<string, CachedToken>): void {
- const path = cachePath();
+export function writeCachedToken(key: string, token: CachedToken): void {
+ const path = entryPath(key);
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
- mkdirSync(gbrainPath(), { recursive: true, mode: 0o700 });
- const now = Date.now();
- const live = Object.fromEntries(Object.entries(entries).filter(([, e]) => e.expires_at_ms > now));
- if (Object.keys(live).length === 0) {
- rmSync(path, { force: true });
- return;
- }
- const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
- writeFileSync(tmp, JSON.stringify({ version: 1, entries: live } satisfies CacheFile), { mode: 0o600, flag: 'wx' });
- try {
- renameSync(tmp, path);
- } catch (e) {
- rmSync(tmp, { force: true });
- throw e;
- }
+ mkdirSync(cacheDir(), { recursive: true, mode: 0o700 });
+ writeFileSync(tmp, JSON.stringify(token), { mode: 0o600, flag: 'wx' });
+ renameSync(tmp, path);
} catch {
- // A cache that cannot be written only costs a mint on the next process.
+ rmSync(tmp, { force: true });
}
}
-export function readCachedToken(key: string): CachedToken | undefined {
- const entry = readEntries()[key];
- return entry && entry.expires_at_ms > Date.now() ? entry : undefined;
-}
-
-export function writeCachedToken(key: string, token: CachedToken): void {
- writeEntries({ ...readEntries(), [key]: token });
-}
-
export function dropCachedToken(key: string): void {
- const entries = readEntries();
- if (!(key in entries)) return;
- delete entries[key];
- writeEntries(entries);
+ try { rmSync(entryPath(key), { force: true }); } catch { /* best-effort */ }
}
export function clearTokenCacheFile(): void {
- try { rmSync(cachePath(), { force: true }); } catch { /* best-effort */ }
+ try { rmSync(cacheDir(), { recursive: true, force: true }); } catch { /* best-effort */ }
}
diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.ts
index aab007ff05..d96415cf1c 100644
--- a/test/e2e/thin-client.test.ts
+++ b/test/e2e/thin-client.test.ts
@@ -417,8 +417,13 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
// Routed-op lane (runThinClientRouted): connection refused surfaces the
// RemoteMcpError network/unreachable rendering with the mcp_url named.
const search = await spawn(['search', G3_MARKER, '--json'], clientHome);
- // CLI_ONLY lane (runRecall's thin-client branch): the same RemoteMcpError
- // class propagates with its raw discovery-failure message.
+ // CLI_ONLY lane (runRecall's thin-client branch) with the access token the
+ // earlier calls cached (#7360): no discovery runs, and the MCP connection
+ // itself is refused.
+ const recallCached = await spawn(['recall', '--grep', G3_MARKER, '--json'], clientHome);
+ // With no cached token the same RemoteMcpError class propagates with its
+ // raw discovery-failure message.
+ rmSync(join(clientHome, '.gbrain', 'remote-tokens'), { recursive: true, force: true });
const recall = await spawn(['recall', '--grep', G3_MARKER, '--json'], clientHome);
// Fail-fast bound: connection-refused returns in milliseconds; even the
// routed default timeout is 30s. Anything near the 120s test timeout is
@@ -427,6 +432,9 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
expect(search.exitCode, cliDiagnostic("thin-client CLI", search)).toBe(1);
expect(JSON.parse(search.stdout)).toMatchObject({ code: expect.any(String), contract_version: 1 }); // D1: the error envelope, no results
expect(search.stderr).toContain(`Cannot reach http://127.0.0.1:${serverPort}/mcp`);
+ expect(recallCached.exitCode, cliDiagnostic("thin-client CLI", recallCached)).toBe(1);
+ expect(JSON.parse(recallCached.stdout)).toMatchObject({ code: expect.any(String), contract_version: 1 });
+ expect(recallCached.stderr).toContain(`http://127.0.0.1:${serverPort}/mcp`);
expect(recall.exitCode, cliDiagnostic("thin-client CLI", recall)).toBe(1);
expect(JSON.parse(recall.stdout)).toMatchObject({ code: expect.any(String), contract_version: 1 }); // D1: the error envelope, no results
expect(recall.stderr).toMatch(/OAuth discovery failed/);
diff --git a/test/thin-client-token-cache-7360.test.ts b/test/thin-client-token-cache-7360.test.ts
index 4d2965b9a4..0de76ad43b 100644
--- a/test/thin-client-token-cache-7360.test.ts
+++ b/test/thin-client-token-cache-7360.test.ts
@@ -24,6 +24,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { callRemoteTool, RemoteMcpError, _clearMcpClientTokenCache } from '../src/core/mcp-client.ts';
+import { tokenCacheKey } from '../src/core/remote-token-cache.ts';
import { ownerCookie, registerOAuthClient, startServeHttp, thinClientConfig, type LiveServeHttp } from './helpers/live-mcp-servers.ts';
import { runCli } from './helpers/cli-spawn.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -33,7 +34,9 @@ let serve: LiveServeHttp;
let cookie: string;
const home = mkdtempSync(join(tmpdir(), 'gbrain-token-cache-7360-'));
const inHome = (fn: () => Promise<void>) => () => withEnv({ GBRAIN_HOME: home }, fn);
-const cacheFile = () => join(home, '.gbrain', 'remote-token-cache.json');
+type Client = { clientId: string; clientSecret: string };
+const cacheFile = (client: Client, root = home) =>
+ join(root, '.gbrain', 'remote-tokens', `${tokenCacheKey(thinClientConfig(serve, client).remote_mcp!, client.clientSecret)}.json`);
async function mintedTokens(clientId: string): Promise<number> {
const rows = await engine.executeRaw<{ n: number }>(
@@ -88,7 +91,7 @@ describe('#7360 token reuse across processes', () => {
expect(`${r.exitCode}\n${r.stderr}`).toBe('0\n');
}
expect(await mintedTokens(client.clientId)).toBe(1);
- const mode = statSync(join(cliHome, '.gbrain', 'remote-token-cache.json')).mode & 0o777;
+ const mode = statSync(cacheFile(client, cliHome)).mode & 0o777;
expect(mode).toBe(0o600);
} finally {
rmSync(cliHome, { recursive: true, force: true });
@@ -99,9 +102,9 @@ describe('#7360 token reuse across processes', () => {
const client = await registerOAuthClient(serve, cookie, 'read write');
const config = thinClientConfig(serve, client);
await callRemoteTool(config, 'get_brain_identity', {});
- const cached = JSON.parse(readFileSync(cacheFile(), 'utf8'));
- for (const entry of Object.values(cached.entries) as Array<{ expires_at_ms: number }>) entry.expires_at_ms = Date.now() - 1;
- writeFileSync(cacheFile(), JSON.stringify(cached), { mode: 0o600 });
+ const cached = JSON.parse(readFileSync(cacheFile(client), 'utf8'));
+ cached.expires_at_ms = Date.now() - 1;
+ writeFileSync(cacheFile(client), JSON.stringify(cached), { mode: 0o600 });
newProcess();
await callRemoteTool(config, 'get_brain_identity', {});
expect(await mintedTokens(client.clientId)).toBe(2);
@@ -167,8 +170,8 @@ describe('#7360 cache file hygiene', () => {
test('the cache file is 0600 and holds no secret', inHome(async () => {
const client = await registerOAuthClient(serve, cookie, 'read write');
await callRemoteTool(thinClientConfig(serve, client), 'get_brain_identity', {});
- expect(statSync(cacheFile()).mode & 0o777).toBe(0o600);
- const text = readFileSync(cacheFile(), 'utf8');
+ expect(statSync(cacheFile(client)).mode & 0o777).toBe(0o600);
+ const text = readFileSync(cacheFile(client), 'utf8');
expect(text).not.toContain(client.clientSecret);
expect(text).not.toContain(client.clientId);
}), 60_000);
@@ -177,22 +180,48 @@ describe('#7360 cache file hygiene', () => {
const client = await registerOAuthClient(serve, cookie, 'read write');
const config = thinClientConfig(serve, client);
await callRemoteTool(config, 'get_brain_identity', {});
- chmodSync(cacheFile(), 0o644);
+ chmodSync(cacheFile(client), 0o644);
newProcess();
await callRemoteTool(config, 'get_brain_identity', {});
expect(await mintedTokens(client.clientId)).toBe(2);
- expect(statSync(cacheFile()).mode & 0o777).toBe(0o600);
+ expect(statSync(cacheFile(client)).mode & 0o777).toBe(0o600);
}), 60_000);
test('a symlinked cache file is replaced, never written through', inHome(async () => {
const client = await registerOAuthClient(serve, cookie, 'read write');
const target = join(home, 'elsewhere.json');
writeFileSync(target, 'untouched', { mode: 0o600 });
- rmSync(cacheFile(), { force: true });
- symlinkSync(target, cacheFile());
+ mkdirSync(join(home, '.gbrain', 'remote-tokens'), { recursive: true, mode: 0o700 });
+ rmSync(cacheFile(client), { force: true });
+ symlinkSync(target, cacheFile(client));
await callRemoteTool(thinClientConfig(serve, client), 'get_brain_identity', {});
expect(readFileSync(target, 'utf8')).toBe('untouched');
- expect(lstatSync(cacheFile()).isSymbolicLink()).toBe(false);
- expect(existsSync(cacheFile())).toBe(true);
+ expect(lstatSync(cacheFile(client)).isSymbolicLink()).toBe(false);
+ expect(existsSync(cacheFile(client))).toBe(true);
+ }), 60_000);
+
+ test('a symlinked entry is never read, even when it points at a private file holding a token', inHome(async () => {
+ const client = await registerOAuthClient(serve, cookie, 'read write');
+ const config = thinClientConfig(serve, client);
+ await callRemoteTool(config, 'get_brain_identity', {});
+ const target = join(home, 'planted.json');
+ writeFileSync(target, JSON.stringify({ access_token: 'planted-token', expires_at_ms: Date.now() + 3_600_000 }), { mode: 0o600 });
+ rmSync(cacheFile(client), { force: true });
+ symlinkSync(target, cacheFile(client));
+ newProcess();
+ await callRemoteTool(config, 'get_brain_identity', {});
+ expect(await mintedTokens(client.clientId)).toBe(2);
+ expect(lstatSync(cacheFile(client)).isSymbolicLink()).toBe(false);
+ }), 60_000);
+
+ test('two clients keep separate entries', inHome(async () => {
+ const a = await registerOAuthClient(serve, cookie, 'read');
+ const b = await registerOAuthClient(serve, cookie, 'read');
+ await callRemoteTool(thinClientConfig(serve, a), 'get_brain_identity', {});
+ await callRemoteTool(thinClientConfig(serve, b), 'get_brain_identity', {});
+ newProcess();
+ await callRemoteTool(thinClientConfig(serve, a), 'get_brain_identity', {});
+ await callRemoteTool(thinClientConfig(serve, b), 'get_brain_identity', {});
+ expect([await mintedTokens(a.clientId), await mintedTokens(b.clientId)]).toEqual([1, 1]);
}), 60_000);
});