Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(auth): report whoami and capabilities transport from the verified principal (#5899)

garrytan0d6677141dc9
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 1fcd86c18a..c1929262ce 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -50,7 +50,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time.
- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the registration loop replaces each handler with `withOutputRedaction(op)`, so a `'retrieval'` op's output is redacted on every dispatch path (see `src/core/ops/contract.ts`); the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx, scope?)` is the link-read sibling for `get_links`/`get_backlinks`/`traverse_graph` (`scope` defaults to `sourceScopeOpts(ctx)`; the link ops pass their resolved per-call `federatedSearchScope`): a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
-- `src/core/ops/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `Operation.outputRedaction: OutputRedactionPolicy` is REQUIRED, so typecheck forces every op to say how its response treats stored text: `'retrieval'` (the whole response passes `redactRetrievalOutput`, uncapped, assignment rule on), `{ retrieval: { localVerbatim: [...] } }` (same, but the named top-level keys stay raw for the trusted local CLI, `ctx.remote === false`; the memory verbs' `facts`), `{ exempt: reason }` (deliberately raw with a one-line reason: page reads `get_page`/`fetch`/`get_chunks`/`get_raw_data`/`get_versions`, skill-catalog files, admin job ops) or `'no_stored_text'` (returns no page, chunk, fact, take or transcript text). `operations.ts` applies the policy at registration (`withOutputRedaction` in `src/core/search/output-redaction.ts`); `test/retrieval-op-redaction.test.ts` sweeps every classified op with a planted secret.
+- `src/core/ops/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `Operation.outputRedaction: OutputRedactionPolicy` is REQUIRED, so typecheck forces every op to say how its response treats stored text: `'retrieval'` (the whole response passes `redactRetrievalOutput`, uncapped, assignment rule on), `{ retrieval: { localVerbatim: [...] } }` (same, but the named top-level keys stay raw for the trusted local CLI, `ctx.remote === false`; the memory verbs' `facts`), `{ exempt: reason }` (deliberately raw with a one-line reason: page reads `get_page`/`fetch`/`get_chunks`/`get_raw_data`/`get_versions`, skill-catalog files, admin job ops) or `'no_stored_text'` (returns no page, chunk, fact, take or transcript text). `operations.ts` applies the policy at registration (`withOutputRedaction` in `src/core/search/output-redaction.ts`); `test/retrieval-op-redaction.test.ts` sweeps every classified op with a planted secret. `whoami` and the HTTP `gbrain://capabilities` resource choose `oauth` vs `legacy` through `authTransport`, which trusts the verifier-set `AuthInfo.principal` and falls back to the `gbrain_cl_` id prefix only when no principal is present.
- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index 12de158eec..db253e2d28 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -10,6 +10,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
import { ListToolsRequestSchema, CallToolRequestSchema, type CallToolRequest } from '@modelcontextprotocol/sdk/types.js';
import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
import { opAllowedForBoundClient } from '../core/operations.ts';
+import { authTransport } from '../core/ops/contract.ts';
import type { AuthInfo, Operation } from '../core/operations.ts';
import { disabledOpsForPublishGates } from '../mcp/publish-gates.ts';
import { resolveMcpInstructions } from '../mcp/instructions.ts';
@@ -181,7 +182,7 @@ function createMcpRequestServer(
},
);
installCapabilitiesResource(server, async () => {
- return { transport: authInfo.clientId.startsWith('gbrain_cl_') ? 'oauth' : 'legacy', client_id: authInfo.clientId,
+ return { transport: authTransport(authInfo), client_id: authInfo.clientId,
...await resolveAuthCapabilities(authInfo, engine, config), administration: mcpAdministrationGuidance(mcpResourceUrl.toString()) };
}, createSkillResources(engine, async () => {
const sourceId = authInfo.sourceId ?? 'default';
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 316c172e08..52e72e2255 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -275,6 +275,16 @@ export interface AuthInfo {
surfaceSetBy?: string;
}
+/**
+ * Transport a verified caller authenticated through. The verifier-set
+ * `principal` is authoritative; the `gbrain_cl_` client-id prefix is only a
+ * fallback for AuthInfo built without one.
+ */
+export function authTransport(auth: AuthInfo): 'oauth' | 'legacy' {
+ if (auth.principal) return auth.principal.kind === 'oauth_client' ? 'oauth' : 'legacy';
+ return auth.clientId.startsWith('gbrain_cl_') ? 'oauth' : 'legacy';
+}
+
export interface OperationContext {
engine: BrainEngine;
config: GBrainConfig;
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 988195b1d6..1566eda5f1 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -7,7 +7,7 @@
*/
import type { Operation } from './contract.ts';
-import { OperationError } from './contract.ts';
+import { OperationError, authTransport } from './contract.ts';
import { assertSourceInCallerScope, assertSourceInCallerWriteScope, sourceScopeOpts } from './context.ts';
import { resolveAuthCapabilities } from '../harness/capabilities.ts';
@@ -49,11 +49,9 @@ const whoami: Operation = {
'or set ctx.remote === false.',
);
}
- // OAuth tokens have client_id starting with 'gbrain_cl_'; legacy
- // access_tokens reuse `name` as both clientId and clientName (verifyAccessToken
- // at oauth-provider.ts:417-430). Detect by inspecting the prefix.
- const isOauth = ctx.auth.clientId.startsWith('gbrain_cl_');
- if (isOauth) {
+ // Legacy access_tokens reuse `name` as both clientId and clientName, so the
+ // transport comes from the verifier-set principal (prefix only as fallback).
+ if (authTransport(ctx.auth) === 'oauth') {
return {
transport: 'oauth',
client_id: ctx.auth.clientId,
diff --git a/test/serve-http-auth-outcomes.test.ts b/test/serve-http-auth-outcomes.test.ts
index c76d4ee7b4..2309eb0ade 100644
--- a/test/serve-http-auth-outcomes.test.ts
+++ b/test/serve-http-auth-outcomes.test.ts
@@ -8,8 +8,9 @@
* modules, owner cookie vs OAuth admin bearer at /admin/api/*, session
* revocation, the PKCE authorization-code and refresh-token flows through
* owner consent, resource-audience rejection at /mcp, the /mcp dispatch
- * context (remote, auth, source scope, surface) and the OAuth CORS gate
- * ordered ahead of the SDK router's own `*` CORS.
+ * context (remote, auth, source scope, surface), the transport whoami and
+ * gbrain://capabilities report from the verified principal, and the OAuth
+ * CORS gate ordered ahead of the SDK router's own `*` CORS.
* Fails when: a module builds its own limiter or session map, an OAuth token
* can administer, sign-out leaves a session alive, a flow step breaks, a
* foreign-audience token reaches dispatch, dispatch loses remote/auth/source
@@ -25,6 +26,7 @@ import express from 'express';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { buildServeHttpApp } from '../src/commands/serve-http.ts';
import { VERB_NAMES } from '../src/core/verbs.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
import { TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from './helpers/oauth.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -271,6 +273,50 @@ describe('/mcp dispatch context', () => {
});
});
+// whoami and gbrain://capabilities must report the transport the verifier
+// actually authenticated, not one guessed from the id: hand-provisioned OAuth
+// client ids need not start with gbrain_cl_, and legacy tokens may be named
+// like one. Both callers are checked through the real HTTP stack so principal
+// propagation and serialization are covered, not just the helper.
+describe('/mcp transport provenance', () => {
+ async function capabilities(app: RunningApp, token: string): Promise<any> {
+ const read = await mcpResult(app, token, 'resources/read', { uri: 'gbrain://capabilities' });
+ return JSON.parse(read.contents[0].text);
+ }
+
+ test('an OAuth client whose id lacks the gbrain_cl_ prefix reports oauth on both surfaces', async () => {
+ const app = await startApp();
+ const cookie = await ownerCookie(app);
+ const { clientId, clientSecret } = await registerClient(app, cookie, { scopes: 'read write', grantTypes: ['client_credentials'] });
+ const handProvisioned = `research-custom-client-${clientSeq}`;
+ await engine.executeRaw('UPDATE oauth_clients SET client_id = $1 WHERE client_id = $2', [handProvisioned, clientId]);
+ const token = await clientCredentialsToken(app, handProvisioned, clientSecret!, 'read write');
+
+ const who = toolPayload(await mcpResult(app, token, 'tools/call', { name: 'whoami', arguments: {} }));
+ expect(who.transport).toBe('oauth');
+ expect(who.client_id).toBe(handProvisioned);
+ expect(who.source_id).toBe('default');
+ expect(who.token_name).toBeUndefined();
+
+ const caps = await capabilities(app, token);
+ expect(caps.transport).toBe('oauth');
+ expect(caps.client_id).toBe(handProvisioned);
+ });
+
+ test('a legacy token named like an OAuth client id reports legacy on both surfaces', async () => {
+ const app = await startApp();
+ const lookalike = `gbrain_cl_lookalike-${++clientSeq}`;
+ const { token } = await mintLegacyToken(engine, { name: lookalike, takesHolders: ['world'], scopes: ['read'] });
+
+ const who = toolPayload(await mcpResult(app, token, 'tools/call', { name: 'whoami', arguments: {} }));
+ expect(who).toEqual({ transport: 'legacy', token_name: lookalike, scopes: ['read'], expires_at: null });
+
+ const caps = await capabilities(app, token);
+ expect(caps.transport).toBe('legacy');
+ expect(caps.client_id).toBe(lookalike);
+ });
+});
+
describe('OAuth CORS gate runs before the SDK router', () => {
const origin = 'https://browser-app.example';
const preflight = (app: RunningApp, path: string) => fetch(`${app.base}${path}`, {
diff --git a/test/whoami.test.ts b/test/whoami.test.ts
index e19bf4e783..69a9dd7dc2 100644
--- a/test/whoami.test.ts
+++ b/test/whoami.test.ts
@@ -126,6 +126,45 @@ describe('whoami op contract', () => {
expect(result.federated_read).toEqual(['canonical-brain']);
});
+ // The verifier-set principal wins over the id prefix: hand-provisioned OAuth
+ // client ids need not start with gbrain_cl_, and a legacy token may be named
+ // like one. The prefix-only tests above/below pin the no-principal fallback.
+ test('principal oauth_client reports oauth even when the client id has no gbrain_cl_ prefix', async () => {
+ const auth: AuthInfo = {
+ token: 'gbrain_at_xxx',
+ clientId: 'research-custom-client',
+ principal: { kind: 'oauth_client', id: 'research-custom-client' },
+ clientName: 'Research client',
+ scopes: ['read', 'write'],
+ expiresAt: 1234567890,
+ sourceId: 'research',
+ allowedSources: ['research', 'default'],
+ };
+ const result = (await whoami.handler(ctxWith({ remote: true, auth }), {})) as any;
+ expect(result).toMatchObject({
+ transport: 'oauth',
+ client_id: 'research-custom-client',
+ client_name: 'Research client',
+ expires_at: 1234567890,
+ source_id: 'research',
+ federated_read: ['research', 'default'],
+ });
+ expect(result.token_name).toBeUndefined();
+ });
+
+ test('principal legacy_token reports legacy even when the token name looks like an OAuth client id', async () => {
+ const auth: AuthInfo = {
+ token: 'legacy-token',
+ clientId: 'gbrain_cl_lookalike',
+ principal: { kind: 'legacy_token', id: '00000000-0000-4000-8000-000000000001' },
+ clientName: 'gbrain_cl_lookalike',
+ scopes: ['read'],
+ expiresAt: 999999999,
+ };
+ const result = (await whoami.handler(ctxWith({ remote: true, auth }), {})) as any;
+ expect(result).toEqual({ transport: 'legacy', token_name: 'gbrain_cl_lookalike', scopes: ['read'], expires_at: null });
+ });
+
test('legacy transport (token name as clientId, no gbrain_cl_ prefix)', async () => {
const auth: AuthInfo = {
token: 'legacy-token',