Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.42.64.0 fix: harden confidential OAuth token revocation (takeover of #3017) (#3032)
Time Attakcd61808d8063a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 57b52cbc8c..cb45f903ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@All notable changes to GBrain will be documented in this file.+## [0.42.64.0] - 2026-07-20++### Fixed++- Confidential OAuth clients can now revoke access tokens through the standard revocation endpoint when client secrets are stored as hashes. Invalid credentials fail closed, malformed or mixed authentication is rejected, backend failures remain retryable, and discovery metadata accurately advertises supported authentication methods.++No schema migrations.## [0.42.63.0] - 2026-07-20**Schema commands now open the local brain you actually configured.**diff --git a/VERSION b/VERSIONindex 4c2cace61f..610c068d67 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.42.63.0+0.42.64.0\ No newline at end of filediff --git a/docs/TESTING.md b/docs/TESTING.mdindex 3861366309..69399d7a74 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -3,6 +3,8 @@On-demand reference (see CLAUDE.md Reference map). Current behavior + invariantsonly.+`test/e2e/serve-http-oauth.test.ts` additionally pins confidential POST/Basic revocation, public-client SDK fallthrough, malformed/mixed authentication rejection, cross-client isolation, unknown-token opacity, metadata auth methods, no-store responses, strict post-revoke `401`, and retryable backend `503` semantics.+### Test command tiersSeven test command tiers, each with a clear scope:diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex ba29acf19b..c102a7ef5a 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -8,6 +8,8 @@ lives in `CHANGELOG.md` + `git log` / `git blame`, NOT here. Do not appendper-release `**vX.Y.Z:**` narration — CI enforces this(`scripts/check-key-files-current-state.sh`).+- `src/commands/serve-http.ts` confidential revoke extension — a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`.+- `src/core/operations.ts` — Contract-first operation definitions (the foundation). 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. `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 skipped only when `remote=true && !trustedWorkspace`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `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 (closes the HTTP MCP shell-job RCE where a read+write OAuth token could 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` (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: 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`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface (#1941): `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/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration replacing the `getAllSlugs()→getPage(slug)` N+1 (which silently defaulted to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity.- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification.diff --git a/package.json b/package.jsonindex 2f812de264..4d38e1255f 100644--- a/package.json+++ b/package.json@@ -144,7 +144,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.42.63.0",+ "version": "0.42.64.0","overrides": {"@hono/node-server": "^1.19.13","fast-uri": "^3.1.2",diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex ee8da69bab..2cbae64bce 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -22,6 +22,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';+import { OAuthTokenRevocationRequestSchema } from '@modelcontextprotocol/sdk/shared/auth.js';import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';@@ -37,6 +38,7 @@ import { VERSION } from '../version.ts';import * as db from '../core/db.ts';import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts';import { MinionQueue } from '../core/minions/queue.ts';+import { isRetryableError } from '../core/retry-matcher.ts';import {computeContentHash,validateIngestionEvent,@@ -745,6 +747,93 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption}});+ // The SDK's /revoke handler compares the presented secret with+ // client.client_secret as plaintext. GBrain stores only a SHA-256 hash, so+ // confidential clients need the same hash-aware validation used above for+ // authorization_code and refresh_token exchanges. Public clients present no+ // secret and continue through to the SDK's PKCE-compatible handler.+ app.post('/revoke', ccRateLimiter, express.urlencoded({ extended: false }), async (req, res, next) => {+ res.setHeader('Cache-Control', 'no-store');++ const rawClientId: unknown = req.body?.client_id;+ const rawBodySecret: unknown = req.body?.client_secret;+ const authHeader = (req.headers.authorization ?? '').toString();++ // RFC 6749 §2.3: one client-authentication method per request. Reject+ // duplicates/arrays from express.urlencoded rather than letting them reach+ // hashToken() as non-strings and become a misleading invalid_client error.+ const hasBasicAuth = /^Basic\b/i.test(authHeader);+ if (+ (rawClientId !== undefined && typeof rawClientId !== 'string') ||+ (rawBodySecret !== undefined && typeof rawBodySecret !== 'string') ||+ (hasBasicAuth && (rawClientId !== undefined || rawBodySecret !== undefined))+ ) {+ res.status(400).json({ error: 'invalid_request', error_description: 'Malformed or mixed client authentication' });+ return;+ }++ let clientId = typeof rawClientId === 'string' ? rawClientId : undefined;+ let presentedSecret = typeof rawBodySecret === 'string' && rawBodySecret.length > 0+ ? rawBodySecret+ : undefined;+ if (hasBasicAuth) {+ try {+ const match = authHeader.match(/^Basic\s+([^\s]+)$/i);+ if (!match) throw new Error('Malformed Basic authentication');+ const decoded = Buffer.from(match[1], 'base64').toString('utf8');+ const idx = decoded.indexOf(':');+ if (idx < 1) throw new Error('Malformed Basic authentication');+ clientId = decodeURIComponent(decoded.slice(0, idx).replace(/\+/g, ' '));+ presentedSecret = decodeURIComponent(decoded.slice(idx + 1).replace(/\+/g, ' '));+ if (!presentedSecret) throw new Error('Malformed Basic authentication');+ } catch {+ res.setHeader('WWW-Authenticate', 'Basic realm="gbrain"');+ res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client' });+ return;+ }+ }+ if (!clientId || !presentedSecret) return next();++ const parsedRequest = OAuthTokenRevocationRequestSchema.safeParse(req.body);+ if (!parsedRequest.success || parsedRequest.data.token.length === 0) {+ res.status(400).json({ error: 'invalid_request', error_description: 'Valid token required' });+ return;+ }++ let client;+ try {+ client = await oauthProvider.verifyConfidentialClientSecret(clientId, presentedSecret);+ } catch (e) {+ const msg = e instanceof Error ? e.message : '';+ if (msg === 'Invalid client' || msg === 'Client has been revoked') {+ if (hasBasicAuth) res.setHeader('WWW-Authenticate', 'Basic realm="gbrain"');+ res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client' });+ return;+ }+ console.error('[serve-http] revoke client verification failed:', msg || 'Unknown error');+ const retryable = isRetryableError(e);+ res.status(retryable ? 503 : 500).json({+ error: retryable ? 'temporarily_unavailable' : 'server_error',+ error_description: retryable ? 'Token revocation temporarily unavailable' : 'Token revocation failed',+ });+ return;+ }++ try {+ await oauthProvider.revokeToken(client, parsedRequest.data);+ // RFC 7009 §2.2: successful revocation, including an unknown token, is 200.+ res.status(200).end();+ } catch (e) {+ const msg = e instanceof Error ? e.message : 'Unknown error';+ console.error('[serve-http] token revocation failed:', msg);+ const retryable = isRetryableError(e);+ res.status(retryable ? 503 : 500).json({+ error: retryable ? 'temporarily_unavailable' : 'server_error',+ error_description: retryable ? 'Token revocation temporarily unavailable' : 'Token revocation failed',+ });+ }+ });+// ---------------------------------------------------------------------------// MCP SDK Auth Router (OAuth endpoints)// ---------------------------------------------------------------------------@@ -796,6 +885,16 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionif (body?.grant_types_supported && !body.grant_types_supported.includes('client_credentials')) {body.grant_types_supported.push('client_credentials');}+ if (body?.token_endpoint_auth_methods_supported) {+ for (const method of ['client_secret_basic', 'none']) {+ if (!body.token_endpoint_auth_methods_supported.includes(method)) {+ body.token_endpoint_auth_methods_supported.push(method);+ }+ }+ }+ if (body?.revocation_endpoint_auth_methods_supported && !body.revocation_endpoint_auth_methods_supported.includes('client_secret_basic')) {+ body.revocation_endpoint_auth_methods_supported.push('client_secret_basic');+ }return origJson(body);};}diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex b7f29bae2d..cca6d9f3e2 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -13,6 +13,7 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { createHash } from 'crypto';import { hasDatabase } from './helpers.ts';const skip = !hasDatabase();@@ -210,6 +211,12 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {expect(meta.grant_types_supported).toContain('authorization_code');expect(meta.grant_types_supported).toContain('refresh_token');expect(meta.grant_types_supported).toContain('client_credentials');+ expect(meta.token_endpoint_auth_methods_supported).toEqual(+ expect.arrayContaining(['client_secret_post', 'client_secret_basic', 'none']),+ );+ expect(meta.revocation_endpoint_auth_methods_supported).toEqual(+ expect.arrayContaining(['client_secret_post', 'client_secret_basic']),+ );});test('OAuth metadata issuer matches public URL', async () => {@@ -407,6 +414,194 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {expect(data.error).toBe('invalid_grant');});+ test('confidential client can revoke its token only with its valid secret', async () => {+ const { access_token } = await mintToken('read');+ const wrongSecret = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=${encodeURIComponent(access_token)}&client_id=${clientId}&client_secret=gbrain_cs_wrong_secret`,+ });+ expect(wrongSecret.status).toBe(401);+ expect((await wrongSecret.json() as any).error).toBe('invalid_client');++ // A rejected revoke request must leave the token usable.+ expect((await mcpCall(access_token, 'tools/list')).status).toBe(200);++ const revoke = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=${encodeURIComponent(access_token)}&client_id=${clientId}&client_secret=${clientSecret}`,+ });+ expect(revoke.status).toBe(200);+ expect(revoke.headers.get('cache-control')).toBe('no-store');+ expect((await mcpCall(access_token, 'tools/list')).status).toBe(401);+ }, 15_000);++ test('confidential client_secret_basic revoke returns canonical auth responses', async () => {+ const { access_token: wrongSecretToken } = await mintToken('read');+ const wrongBasic = Buffer.from(`${encodeURIComponent(clientId!)}:${encodeURIComponent('wrong-secret')}`).toString('base64');+ const rejected = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Authorization: `Basic ${wrongBasic}`,+ },+ body: `token=${encodeURIComponent(wrongSecretToken)}`,+ });+ expect(rejected.status).toBe(401);+ expect(rejected.headers.get('www-authenticate')).toMatch(/^Basic /);+ expect((await mcpCall(wrongSecretToken, 'tools/list')).status).toBe(200);++ const { access_token } = await mintToken('read');+ const validBasic = Buffer.from(`${encodeURIComponent(clientId!)}:${encodeURIComponent(clientSecret!)}`).toString('base64');+ const revoked = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Authorization: `Basic ${validBasic}`,+ },+ body: `token=${encodeURIComponent(access_token)}`,+ });+ expect(revoked.status).toBe(200);+ expect(revoked.headers.get('cache-control')).toBe('no-store');+ expect((await mcpCall(access_token, 'tools/list')).status).toBe(401);+ }, 15_000);++ test('revoke validates request shape and rejects mixed client authentication', async () => {+ const { access_token } = await mintToken('read');+ const validBasic = Buffer.from(`${encodeURIComponent(clientId!)}:${encodeURIComponent(clientSecret!)}`).toString('base64');++ const mixed = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Authorization: `Basic ${validBasic}`,+ },+ body: `token=${encodeURIComponent(access_token)}&client_id=${clientId}&client_secret=${clientSecret}`,+ });+ expect(mixed.status).toBe(400);+ expect((await mixed.json() as any).error).toBe('invalid_request');++ const repeatedToken = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=${encodeURIComponent(access_token)}&token=duplicate&client_id=${clientId}&client_secret=${clientSecret}`,+ });+ expect(repeatedToken.status).toBe(400);+ expect((await repeatedToken.json() as any).error).toBe('invalid_request');++ const missingToken = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `client_id=${clientId}&client_secret=${clientSecret}`,+ });+ expect(missingToken.status).toBe(400);+ expect((await missingToken.json() as any).error).toBe('invalid_request');+ expect((await mcpCall(access_token, 'tools/list')).status).toBe(200);+ }, 15_000);++ test('unknown and cross-client tokens are opaque 200 no-ops', async () => {+ const unknown = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=unknown-token&client_id=${clientId}&client_secret=${clientSecret}`,+ });+ expect(unknown.status).toBe(200);++ const { execSync } = await import('child_process');+ const attackerRegistration = execSync(+ `bun run src/cli.ts auth register-client e2e-revoke-attacker-${Date.now()} --grant-types client_credentials --scopes read`,+ { cwd: process.cwd(), encoding: 'utf8', env: { ...process.env } },+ );+ const attackerId = attackerRegistration.match(/Client ID:\s+(gbrain_cl_\S+)/)?.[1];+ const attackerSecret = attackerRegistration.match(/Client Secret:\s+(gbrain_cs_\S+)/)?.[1];+ expect(attackerId).toBeTruthy();+ expect(attackerSecret).toBeTruthy();+ dcrClientIds.push(attackerId!);++ const { access_token: ownerToken } = await mintToken('read');+ const crossClient = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=${encodeURIComponent(ownerToken)}&client_id=${attackerId}&client_secret=${attackerSecret}`,+ });+ expect(crossClient.status).toBe(200);+ expect((await mcpCall(ownerToken, 'tools/list')).status).toBe(200);+ }, 30_000);++ test('public client revoke falls through to the SDK handler', async () => {+ const { execSync } = await import('child_process');+ const registration = execSync(+ `bun run src/cli.ts auth register-client e2e-revoke-public-${Date.now()} --grant-types authorization_code --scopes read --token-endpoint-auth-method none`,+ { cwd: process.cwd(), encoding: 'utf8', env: { ...process.env } },+ );+ const publicClientId = registration.match(/Client ID:\s+(gbrain_cl_\S+)/)?.[1];+ expect(publicClientId).toBeTruthy();+ dcrClientIds.push(publicClientId!);++ const publicToken = `gbrain_at_public_${Date.now()}`;+ const tokenHash = createHash('sha256').update(publicToken).digest('hex');+ const postgres = (await import('postgres')).default;+ const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });+ try {+ await sql`+ INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at)+ VALUES (${tokenHash}, ${'access'}, ${publicClientId!}, ${sql.array(['read'])}, ${Math.floor(Date.now() / 1000) + 3600})+ `;+ } finally {+ await sql.end();+ }++ expect((await mcpCall(publicToken, 'tools/list')).status).toBe(200);+ const revoked = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=${encodeURIComponent(publicToken)}&client_id=${publicClientId}`,+ });+ expect(revoked.status).toBe(200);+ expect((await mcpCall(publicToken, 'tools/list')).status).toBe(401);+ }, 30_000);++ test('retryable revoke backend failure returns 503 and leaves token usable', async () => {+ const { access_token } = await mintToken('read');+ const tokenHash = createHash('sha256').update(access_token).digest('hex');+ const suffix = Date.now().toString();+ const functionName = `e2e_fail_revoke_${suffix}`;+ const triggerName = `e2e_fail_revoke_trigger_${suffix}`;+ const postgres = (await import('postgres')).default;+ const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });+ try {+ await sql.unsafe(`+ CREATE FUNCTION ${functionName}() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN+ IF OLD.token_hash = '${tokenHash}' THEN+ RAISE EXCEPTION 'injected retryable revoke failure' USING ERRCODE = '08006';+ END IF;+ RETURN OLD;+ END;+ $$+ `);+ await sql.unsafe(`+ CREATE TRIGGER ${triggerName}+ BEFORE DELETE ON oauth_tokens+ FOR EACH ROW EXECUTE FUNCTION ${functionName}()+ `);++ const failed = await fetch(`${BASE}/revoke`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `token=${encodeURIComponent(access_token)}&client_id=${clientId}&client_secret=${clientSecret}`,+ });+ expect(failed.status).toBe(503);+ expect((await failed.json() as any).error).toBe('temporarily_unavailable');+ expect((await mcpCall(access_token, 'tools/list')).status).toBe(200);+ } finally {+ await sql.unsafe(`DROP TRIGGER IF EXISTS ${triggerName} ON oauth_tokens`);+ await sql.unsafe(`DROP FUNCTION IF EXISTS ${functionName}()`);+ await sql.end();+ }+ }, 30_000);+// =========================================================================// v0.26.2: DCR /register response shape (RFC 7591 §3.2.1 number contract)// =========================================================================