diff --git a/cli/src/auth.rs b/cli/src/auth.rs index b9a8a71e13..0c02e6bd43 100644 --- a/cli/src/auth.rs +++ b/cli/src/auth.rs @@ -248,22 +248,6 @@ impl AuthStore { self.write_secrets(&secrets) } - #[allow(dead_code)] // Retained for explicit credential inspection and compatibility tooling. - pub fn load_inline_protocol_temporary( - &self, - ) -> Result, AuthError> { - let Some(secrets) = self.read_secrets_for_current_api()? else { - return Ok(None); - }; - if secrets.logout_in_progress { - return Ok(None); - } - secrets - .inline_protocol_temporary - .map(TryInto::try_into) - .transpose() - } - pub fn load_inline_protocol_authorizations( &self, ) -> Result, AuthError> { diff --git a/cli/src/main.rs b/cli/src/main.rs index 245d583ac4..75f26a2046 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -7360,19 +7360,6 @@ fn proto_user_matches_filter(user: &proto::User, needle: &str) -> bool { false } -#[allow(dead_code)] // Retained until the legacy bearer-only compatibility seam is removed. -async fn fetch_message_by_id( - realtime: &mut AuthenticatedRealtime, - peer: &proto::InputPeer, - message_id: i64, -) -> Result> { - let (messages, _) = fetch_messages_by_ids(realtime, peer, &[message_id]).await?; - messages - .into_iter() - .next() - .ok_or_else(|| CliError::invalid_args("Message not found for that peer.").into()) -} - /// The server caps one history page, so longer ranges are fetched in pages. const HISTORY_PAGE_LIMIT: i32 = 500; diff --git a/crates/agent-driver-claude/src/harness/session.rs b/crates/agent-driver-claude/src/harness/session.rs index 63088a3eed..bf9adac018 100644 --- a/crates/agent-driver-claude/src/harness/session.rs +++ b/crates/agent-driver-claude/src/harness/session.rs @@ -14,12 +14,12 @@ use std::time::{Duration, Instant}; use inline_agent_bridge::harness::{ Availability, AvailabilityMatrix, CapabilityManifest, Catalog, CatalogMode, CatalogScope, - CompatTier, DEFAULT_HUB_CAPACITY, Delivery, DeliveryKind, Envelope, Event, EventHub, - EventStream, ExecutableInfo, ExecutableSource, ForkPoint, HarnessDriver, HarnessFuture, HeldBy, - HeldSurface, Input, InputDisposition, InputReceipt, InteractionId, LiveWork, ModeId, Op, - OpError, OpKind, OpOutcome, OpenError, OpenMode, OpenSpec, Origin, OutputMode, QueueEntryId, - ReleaseOutcome, Released, RunState, RunStateTracker, RuntimeHealth, RuntimeInfo, SendError, - Session, SessionKey, SessionPage, SessionQuery, SessionSummary, SettingsScope, SetupReason, + CompatTier, DEFAULT_HUB_CAPACITY, Delivery, DeliveryKind, Event, EventHub, EventStream, + ExecutableInfo, ExecutableSource, ForkPoint, HarnessDriver, HarnessFuture, HeldBy, HeldSurface, + Input, InputDisposition, InputReceipt, InteractionId, LiveWork, ModeId, Op, OpError, OpKind, + OpOutcome, OpenError, OpenMode, OpenSpec, Origin, OutputMode, QueueEntryId, ReleaseOutcome, + Released, RunState, RunStateTracker, RuntimeHealth, RuntimeInfo, SendError, Session, + SessionKey, SessionPage, SessionQuery, SessionSummary, SettingsScope, SetupReason, SteerPriority, TurnPhase, }; use inline_agent_bridge::{ @@ -1819,11 +1819,6 @@ fn open_error(error: ConnectError) -> OpenError { OpenError::Driver(DriverError::Unavailable(error.to_string())) } -#[allow(dead_code)] -fn envelope_session(envelope: &Envelope) -> &str { - envelope.session.session.as_str() -} - #[cfg(test)] mod launch_tests { use super::*; diff --git a/crates/agent-driver-claude/src/history.rs b/crates/agent-driver-claude/src/history.rs index 98c162e6d4..9208f9f517 100644 --- a/crates/agent-driver-claude/src/history.rs +++ b/crates/agent-driver-claude/src/history.rs @@ -692,7 +692,7 @@ mod tests { /// `INLINE_HISTORY_LAB=[,…] cargo test -p inline-agent-driver-claude --lib history_lab -- --ignored --nocapture` #[cfg(test)] #[test] -#[ignore] +#[ignore = "lab: reads the local Claude Code store; set INLINE_HISTORY_LAB"] fn history_lab() { let store = crate::sessions::SessionStore::resolve(&[]).expect("a Claude Code store"); for id in std::env::var("INLINE_HISTORY_LAB") diff --git a/packages/mcp/src/server/store/bun-sqlite-store.ts b/packages/mcp/src/server/store/bun-sqlite-store.ts deleted file mode 100644 index 0ce3204470..0000000000 --- a/packages/mcp/src/server/store/bun-sqlite-store.ts +++ /dev/null @@ -1,500 +0,0 @@ -import { Database } from "bun:sqlite" -import { mkdirSync } from "node:fs" -import { dirname } from "node:path" -import type { - AuthCode, - AuthRequest, - Grant, - RegisteredClient, - StoredAccessToken, - StoredRefreshToken, - Store, -} from "./types" - -export function createBunSqliteStore(config: { dbPath: string }): Store { - if (config.dbPath !== ":memory:") { - // Ensure the parent directory exists so Bun's sqlite can create the file. - mkdirSync(dirname(config.dbPath), { recursive: true }) - } - const db = new Database(config.dbPath) - const store = new BunSqliteStore(db) - store.ensureSchema() - return store -} - -class BunSqliteStore implements Store { - constructor(private readonly db: Database) {} - - ensureSchema(): void { - this.db.exec(` - pragma journal_mode = wal; - create table if not exists oauth_clients ( - client_id text primary key, - redirect_uris_json text not null, - client_name text, - created_at_ms integer not null - ); - create table if not exists auth_requests ( - id text primary key, - client_id text not null, - redirect_uri text not null, - state text not null, - scope text not null, - code_challenge text not null, - csrf_token text not null, - device_id text not null, - inline_user_id text, - email text, - inline_token_enc text, - created_at_ms integer not null, - expires_at_ms integer not null - ); - create table if not exists grants ( - id text primary key, - client_id text not null, - inline_user_id text not null, - scope text not null, - space_ids_json text not null, - allow_home_chats integer not null default 0, - allow_dms integer not null default 0, - allow_home_threads integer not null default 0, - inline_token_enc text not null, - created_at_ms integer not null, - revoked_at_ms integer - ); - create table if not exists auth_codes ( - code text primary key, - grant_id text not null, - client_id text not null, - redirect_uri text not null, - code_challenge text not null, - used_at_ms integer, - created_at_ms integer not null, - expires_at_ms integer not null - ); - create table if not exists access_tokens ( - token_hash_hex text primary key, - grant_id text not null, - created_at_ms integer not null, - expires_at_ms integer not null, - revoked_at_ms integer - ); - create table if not exists refresh_tokens ( - token_hash_hex text primary key, - grant_id text not null, - created_at_ms integer not null, - expires_at_ms integer not null, - revoked_at_ms integer, - replaced_by_hash_hex text - ); - create table if not exists rate_limits ( - bucket_key text primary key, - count integer not null, - reset_at_ms integer not null - ); - `) - - this.ensureColumn("grants", "allow_home_chats", "integer not null default 0") - this.ensureColumn("grants", "allow_dms", "integer not null default 0") - this.ensureColumn("grants", "allow_home_threads", "integer not null default 0") - // Backfill grants created before the split between DMs and home threads. - this.db.exec(` - update grants - set allow_dms = 1, - allow_home_threads = 1 - where allow_home_chats = 1 and allow_dms = 0 and allow_home_threads = 0; - `) - } - - private ensureColumn(tableName: string, columnName: string, columnDefSql: string): void { - const columns = this.db.query<{ name: string }, []>(`pragma table_info(${tableName})`).all() - if (columns.some((column) => column.name === columnName)) return - this.db.exec(`alter table ${tableName} add column ${columnName} ${columnDefSql}`) - } - - cleanupExpired(nowMs: number): void { - this.db.query("delete from auth_requests where expires_at_ms <= ?").run(nowMs) - this.db.query("delete from auth_codes where expires_at_ms <= ?").run(nowMs) - this.db.query("delete from rate_limits where reset_at_ms <= ?").run(nowMs) - } - - consumeRateLimit(input: { key: string; nowMs: number; windowMs: number; max: number }): { allowed: boolean; retryAfterSeconds: number } { - const run = this.db.transaction((key: string, nowMs: number, windowMs: number, max: number) => { - this.db.query("delete from rate_limits where bucket_key = ? and reset_at_ms <= ?").run(key, nowMs) - - const existing = this.db - .query<{ count: number; reset_at_ms: number }, [string]>("select count, reset_at_ms from rate_limits where bucket_key = ?") - .get(key) - - if (!existing) { - this.db.query("insert into rate_limits (bucket_key, count, reset_at_ms) values (?, ?, ?)").run(key, 1, nowMs + windowMs) - return { allowed: true, retryAfterSeconds: 0 } - } - - const nextCount = existing.count + 1 - this.db.query("update rate_limits set count = ? where bucket_key = ?").run(nextCount, key) - const allowed = nextCount <= max - const retryAfterSeconds = allowed ? 0 : Math.max(1, Math.ceil((existing.reset_at_ms - nowMs) / 1000)) - return { allowed, retryAfterSeconds } - }) - - return run(input.key, input.nowMs, input.windowMs, input.max) - } - - createClient(input: { redirectUris: string[]; clientName: string | null; nowMs: number }): RegisteredClient { - const clientId = crypto.randomUUID() - this.db - .query("insert into oauth_clients (client_id, redirect_uris_json, client_name, created_at_ms) values (?, ?, ?, ?)") - .run(clientId, JSON.stringify(input.redirectUris), input.clientName, input.nowMs) - return { clientId, redirectUris: input.redirectUris, clientName: input.clientName, createdAtMs: input.nowMs } - } - - getClient(clientId: string): RegisteredClient | null { - const row = this.db - .query<{ client_id: string; redirect_uris_json: string; client_name: string | null; created_at_ms: number }, [string]>( - "select client_id, redirect_uris_json, client_name, created_at_ms from oauth_clients where client_id = ?", - ) - .get(clientId) - if (!row) return null - return { - clientId: row.client_id, - redirectUris: JSON.parse(row.redirect_uris_json) as string[], - clientName: row.client_name, - createdAtMs: row.created_at_ms, - } - } - - createAuthRequest(input: { - id: string - clientId: string - redirectUri: string - state: string - scope: string - codeChallenge: string - csrfToken: string - deviceId: string - nowMs: number - expiresAtMs: number - }): AuthRequest { - this.db - .query( - "insert into auth_requests (id, client_id, redirect_uri, state, scope, code_challenge, csrf_token, device_id, created_at_ms, expires_at_ms) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - ) - .run( - input.id, - input.clientId, - input.redirectUri, - input.state, - input.scope, - input.codeChallenge, - input.csrfToken, - input.deviceId, - input.nowMs, - input.expiresAtMs, - ) - return { - id: input.id, - clientId: input.clientId, - redirectUri: input.redirectUri, - state: input.state, - scope: input.scope, - codeChallenge: input.codeChallenge, - csrfToken: input.csrfToken, - deviceId: input.deviceId, - inlineUserId: null, - email: null, - inlineTokenEnc: null, - createdAtMs: input.nowMs, - expiresAtMs: input.expiresAtMs, - } - } - - getAuthRequest(id: string, nowMs: number): AuthRequest | null { - const row = this.db - .query< - { - id: string - client_id: string - redirect_uri: string - state: string - scope: string - code_challenge: string - csrf_token: string - device_id: string - inline_user_id: string | null - email: string | null - inline_token_enc: string | null - created_at_ms: number - expires_at_ms: number - }, - [string] - >( - "select id, client_id, redirect_uri, state, scope, code_challenge, csrf_token, device_id, inline_user_id, email, inline_token_enc, created_at_ms, expires_at_ms from auth_requests where id = ?", - ) - .get(id) - if (!row) return null - if (row.expires_at_ms <= nowMs) return null - return { - id: row.id, - clientId: row.client_id, - redirectUri: row.redirect_uri, - state: row.state, - scope: row.scope, - codeChallenge: row.code_challenge, - csrfToken: row.csrf_token, - deviceId: row.device_id, - inlineUserId: row.inline_user_id ? BigInt(row.inline_user_id) : null, - email: row.email, - inlineTokenEnc: row.inline_token_enc, - createdAtMs: row.created_at_ms, - expiresAtMs: row.expires_at_ms, - } - } - - setAuthRequestEmail(id: string, email: string): void { - this.db.query("update auth_requests set email = ? where id = ?").run(email, id) - } - - setAuthRequestInlineTokenEnc(id: string, inlineTokenEnc: string): void { - this.db.query("update auth_requests set inline_token_enc = ? where id = ?").run(inlineTokenEnc, id) - } - - setAuthRequestInlineUserId(id: string, inlineUserId: bigint): void { - this.db.query("update auth_requests set inline_user_id = ? where id = ?").run(inlineUserId.toString(), id) - } - - deleteAuthRequest(id: string): void { - this.db.query("delete from auth_requests where id = ?").run(id) - } - - createGrant(input: { - id: string - clientId: string - inlineUserId: bigint - scope: string - spaceIds: bigint[] - allowDms?: boolean - allowHomeThreads?: boolean - inlineTokenEnc: string - nowMs: number - }): Grant { - const allowDms = input.allowDms ?? false - const allowHomeThreads = input.allowHomeThreads ?? false - const allowHomeChats = allowDms || allowHomeThreads - this.db - .query( - "insert into grants (id, client_id, inline_user_id, scope, space_ids_json, allow_home_chats, allow_dms, allow_home_threads, inline_token_enc, created_at_ms) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - ) - .run( - input.id, - input.clientId, - input.inlineUserId.toString(), - input.scope, - JSON.stringify(input.spaceIds.map((s) => s.toString())), - allowHomeChats ? 1 : 0, - allowDms ? 1 : 0, - allowHomeThreads ? 1 : 0, - input.inlineTokenEnc, - input.nowMs, - ) - return { - id: input.id, - clientId: input.clientId, - inlineUserId: input.inlineUserId, - scope: input.scope, - spaceIds: input.spaceIds, - allowDms, - allowHomeThreads, - inlineTokenEnc: input.inlineTokenEnc, - createdAtMs: input.nowMs, - revokedAtMs: null, - } - } - - getGrant(grantId: string): Grant | null { - const row = this.db - .query< - { - id: string - client_id: string - inline_user_id: string - scope: string - space_ids_json: string - allow_dms: number - allow_home_threads: number - inline_token_enc: string - created_at_ms: number - revoked_at_ms: number | null - }, - [string] - >( - "select id, client_id, inline_user_id, scope, space_ids_json, allow_dms, allow_home_threads, inline_token_enc, created_at_ms, revoked_at_ms from grants where id = ?", - ) - .get(grantId) - if (!row) return null - return { - id: row.id, - clientId: row.client_id, - inlineUserId: BigInt(row.inline_user_id), - scope: row.scope, - spaceIds: (JSON.parse(row.space_ids_json) as string[]).map((s) => BigInt(s)), - allowDms: row.allow_dms === 1, - allowHomeThreads: row.allow_home_threads === 1, - inlineTokenEnc: row.inline_token_enc, - createdAtMs: row.created_at_ms, - revokedAtMs: row.revoked_at_ms, - } - } - - revokeGrant(grantId: string, nowMs: number): void { - this.db.query("update grants set revoked_at_ms = ? where id = ? and revoked_at_ms is null").run(nowMs, grantId) - } - - createAuthCode(input: { - code: string - grantId: string - clientId: string - redirectUri: string - codeChallenge: string - nowMs: number - expiresAtMs: number - }): AuthCode { - this.db - .query( - "insert into auth_codes (code, grant_id, client_id, redirect_uri, code_challenge, created_at_ms, expires_at_ms) values (?, ?, ?, ?, ?, ?, ?)", - ) - .run(input.code, input.grantId, input.clientId, input.redirectUri, input.codeChallenge, input.nowMs, input.expiresAtMs) - return { - code: input.code, - grantId: input.grantId, - clientId: input.clientId, - redirectUri: input.redirectUri, - codeChallenge: input.codeChallenge, - usedAtMs: null, - createdAtMs: input.nowMs, - expiresAtMs: input.expiresAtMs, - } - } - - getAuthCode(code: string, nowMs: number): AuthCode | null { - const row = this.db - .query< - { - code: string - grant_id: string - client_id: string - redirect_uri: string - code_challenge: string - used_at_ms: number | null - created_at_ms: number - expires_at_ms: number - }, - [string] - >( - "select code, grant_id, client_id, redirect_uri, code_challenge, used_at_ms, created_at_ms, expires_at_ms from auth_codes where code = ?", - ) - .get(code) - if (!row) return null - if (row.expires_at_ms <= nowMs) return null - return { - code: row.code, - grantId: row.grant_id, - clientId: row.client_id, - redirectUri: row.redirect_uri, - codeChallenge: row.code_challenge, - usedAtMs: row.used_at_ms, - createdAtMs: row.created_at_ms, - expiresAtMs: row.expires_at_ms, - } - } - - markAuthCodeUsed(code: string, nowMs: number): void { - this.db.query("update auth_codes set used_at_ms = ? where code = ?").run(nowMs, code) - } - - createAccessToken(input: { tokenHashHex: string; grantId: string; nowMs: number; expiresAtMs: number }): void { - this.db - .query( - "insert into access_tokens (token_hash_hex, grant_id, created_at_ms, expires_at_ms) values (?, ?, ?, ?)", - ) - .run(input.tokenHashHex, input.grantId, input.nowMs, input.expiresAtMs) - } - - getAccessToken(tokenHashHex: string, nowMs: number): StoredAccessToken | null { - const row = this.db - .query< - { token_hash_hex: string; grant_id: string; created_at_ms: number; expires_at_ms: number; revoked_at_ms: number | null }, - [string] - >("select token_hash_hex, grant_id, created_at_ms, expires_at_ms, revoked_at_ms from access_tokens where token_hash_hex = ?") - .get(tokenHashHex) - if (!row) return null - if (row.revoked_at_ms != null) return null - if (row.expires_at_ms <= nowMs) return null - return { - tokenHashHex: row.token_hash_hex, - grantId: row.grant_id, - createdAtMs: row.created_at_ms, - expiresAtMs: row.expires_at_ms, - revokedAtMs: row.revoked_at_ms, - } - } - - createRefreshToken(input: { tokenHashHex: string; grantId: string; nowMs: number; expiresAtMs: number }): void { - this.db - .query( - "insert into refresh_tokens (token_hash_hex, grant_id, created_at_ms, expires_at_ms) values (?, ?, ?, ?)", - ) - .run(input.tokenHashHex, input.grantId, input.nowMs, input.expiresAtMs) - } - - getRefreshToken(tokenHashHex: string, nowMs: number): StoredRefreshToken | null { - const row = this.db - .query< - { - token_hash_hex: string - grant_id: string - created_at_ms: number - expires_at_ms: number - revoked_at_ms: number | null - replaced_by_hash_hex: string | null - }, - [string] - >( - "select token_hash_hex, grant_id, created_at_ms, expires_at_ms, revoked_at_ms, replaced_by_hash_hex from refresh_tokens where token_hash_hex = ?", - ) - .get(tokenHashHex) - if (!row) return null - if (row.revoked_at_ms != null) return null - if (row.expires_at_ms <= nowMs) return null - return { - tokenHashHex: row.token_hash_hex, - grantId: row.grant_id, - createdAtMs: row.created_at_ms, - expiresAtMs: row.expires_at_ms, - revokedAtMs: row.revoked_at_ms, - replacedByHashHex: row.replaced_by_hash_hex, - } - } - - revokeRefreshToken(tokenHashHex: string, nowMs: number, replacedByHashHex: string | null): void { - this.db - .query("update refresh_tokens set revoked_at_ms = ?, replaced_by_hash_hex = ? where token_hash_hex = ?") - .run(nowMs, replacedByHashHex, tokenHashHex) - } - - revokeRefreshTokensByGrant(grantId: string, nowMs: number): void { - this.db - .query("update refresh_tokens set revoked_at_ms = ?, replaced_by_hash_hex = null where grant_id = ? and revoked_at_ms is null") - .run(nowMs, grantId) - } - - findGrantIdByTokenHash(tokenHashHex: string): string | null { - const refresh = this.db.query<{ grant_id: string }, [string]>("select grant_id from refresh_tokens where token_hash_hex = ?").get(tokenHashHex) - if (refresh) return refresh.grant_id - - const access = this.db.query<{ grant_id: string }, [string]>("select grant_id from access_tokens where token_hash_hex = ?").get(tokenHashHex) - if (access) return access.grant_id - - return null - } -} diff --git a/packages/mcp/src/server/store/index.ts b/packages/mcp/src/server/store/index.ts deleted file mode 100644 index 0c3ae86e2e..0000000000 --- a/packages/mcp/src/server/store/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type * from "./types" -export { createMemoryStore } from "./memory-store" - -// Used only for coverage/tests to ensure this module is executed. -export const __storeIndexLoaded = true diff --git a/packages/mcp/src/server/store/memory-store.test.ts b/packages/mcp/src/server/store/memory-store.test.ts deleted file mode 100644 index 95fe216846..0000000000 --- a/packages/mcp/src/server/store/memory-store.test.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { describe, expect, it } from "vitest" -import { __storeIndexLoaded, createMemoryStore } from "./index" - -describe("memory store", () => { - it("executes store index module", () => { - expect(__storeIndexLoaded).toBe(true) - }) - - it("creates and fetches a client", () => { - const store = createMemoryStore() - store.ensureSchema() - const now = 1000 - const client = store.createClient({ redirectUris: ["https://example.com/cb"], clientName: "test", nowMs: now }) - expect(store.getClient(client.clientId)).toEqual(client) - expect(store.getClient("missing")).toBeNull() - }) - - it("auth request lifecycle + expiry", () => { - const store = createMemoryStore() - const now = 1000 - store.createAuthRequest({ - id: "ar1", - clientId: "c1", - redirectUri: "https://example.com/cb", - state: "s", - scope: "messages:read", - codeChallenge: "cc", - csrfToken: "csrf", - deviceId: "d1", - nowMs: now, - expiresAtMs: now + 2, - }) - expect(store.getAuthRequest("ar1", now)?.email).toBeNull() - store.setAuthRequestEmail("ar1", "a@example.com") - store.setAuthRequestInlineTokenEnc("ar1", "enc-token") - store.setAuthRequestInlineUserId("ar1", 123n) - expect(store.getAuthRequest("ar1", now)?.email).toBe("a@example.com") - expect(store.getAuthRequest("ar1", now)?.inlineTokenEnc).toBe("enc-token") - expect(store.getAuthRequest("ar1", now)?.inlineUserId).toBe(123n) - expect(store.getAuthRequest("ar1", now + 2)).toBeNull() - store.deleteAuthRequest("ar1") - expect(store.getAuthRequest("ar1", now)).toBeNull() - }) - - it("grant + auth code + used marker", () => { - const store = createMemoryStore() - const now = 1000 - const grant = store.createGrant({ - id: "g1", - clientId: "c1", - inlineUserId: 42n, - scope: "messages:read offline_access", - spaceIds: [1n, 2n], - allowDms: true, - allowHomeThreads: true, - inlineTokenEnc: "enc", - nowMs: now, - }) - expect(store.getGrant("g1")).toEqual(grant) - expect(store.getGrant("missing")).toBeNull() - - const code = store.createAuthCode({ - code: "code1", - grantId: "g1", - clientId: "c1", - redirectUri: "https://example.com/cb", - codeChallenge: "cc", - nowMs: now, - expiresAtMs: now + 1, - }) - expect(store.getAuthCode("code1", now)).toEqual(code) - store.markAuthCodeUsed("code1", now + 123) - expect(store.getAuthCode("code1", now)?.usedAtMs).toBe(now + 123) - expect(store.getAuthCode("code1", now + 1)).toBeNull() - }) - - it("access/refresh token expiry and refresh revocation", () => { - const store = createMemoryStore() - - store.createAccessToken({ tokenHashHex: "a", grantId: "g", nowMs: 1, expiresAtMs: 2 }) - expect(store.getAccessToken("a", 1)?.grantId).toBe("g") - expect(store.getAccessToken("a", 2)).toBeNull() - expect(store.getAccessToken("missing", 1)).toBeNull() - - // Cover "revoked" branch by injecting a token record via the public API - // then revoking it through a second store instance isn't possible, so we - // indirectly cover by creating a token and then mutating via as-any in test. - ;(store as any).createAccessToken({ tokenHashHex: "rev", grantId: "g", nowMs: 1, expiresAtMs: 999 }) - ;((store as any).getAccessToken("rev", 2) as any).revokedAtMs = 2 - expect(store.getAccessToken("rev", 3)).toBeNull() - - store.createRefreshToken({ tokenHashHex: "r1", grantId: "g", nowMs: 1, expiresAtMs: 999 }) - expect(store.getRefreshToken("r1", 2)?.grantId).toBe("g") - store.revokeRefreshToken("r1", 3, "r2") - expect(store.getRefreshToken("r1", 4)).toBeNull() - expect(store.getRefreshToken("missing", 1)).toBeNull() - - store.createRefreshToken({ tokenHashHex: "exp", grantId: "g", nowMs: 1, expiresAtMs: 2 }) - expect(store.getRefreshToken("exp", 2)).toBeNull() - - // revoke non-existent should be a no-op. - store.revokeRefreshToken("missing", 1, null) - }) - - it("cleanup removes expired auth requests and auth codes", () => { - const store = createMemoryStore() - store.createAuthRequest({ - id: "ar1", - clientId: "c1", - redirectUri: "https://example.com/cb", - state: "s", - scope: "messages:read", - codeChallenge: "cc", - csrfToken: "csrf", - deviceId: "d1", - nowMs: 1, - expiresAtMs: 2, - }) - store.createAuthRequest({ - id: "ar2", - clientId: "c1", - redirectUri: "https://example.com/cb", - state: "s", - scope: "messages:read", - codeChallenge: "cc", - csrfToken: "csrf", - deviceId: "d1", - nowMs: 1, - expiresAtMs: 1, - }) - store.createAuthRequest({ - id: "ar3", - clientId: "c1", - redirectUri: "https://example.com/cb", - state: "s", - scope: "messages:read", - codeChallenge: "cc", - csrfToken: "csrf", - deviceId: "d1", - nowMs: 1, - expiresAtMs: 999, - }) - store.createAuthCode({ - code: "code1", - grantId: "g1", - clientId: "c1", - redirectUri: "https://example.com/cb", - codeChallenge: "cc", - nowMs: 1, - expiresAtMs: 2, - }) - store.createAuthCode({ - code: "code2", - grantId: "g1", - clientId: "c1", - redirectUri: "https://example.com/cb", - codeChallenge: "cc", - nowMs: 1, - expiresAtMs: 999, - }) - - expect(store.getAuthRequest("ar1", 1)).not.toBeNull() - expect(store.getAuthCode("code1", 1)).not.toBeNull() - - store.cleanupExpired(2) - expect(store.getAuthRequest("ar1", 1)).toBeNull() - expect(store.getAuthRequest("ar2", 1)).toBeNull() - expect(store.getAuthCode("code1", 1)).toBeNull() - - // Not expired; should remain. - expect(store.getAuthRequest("ar3", 1)).not.toBeNull() - expect(store.getAuthCode("code2", 1)).not.toBeNull() - }) - - it("no-op updates on missing ids", () => { - const store = createMemoryStore() - store.setAuthRequestEmail("missing", "a@example.com") - store.setAuthRequestInlineTokenEnc("missing", "enc") - store.setAuthRequestInlineUserId("missing", 1n) - store.markAuthCodeUsed("missing", 1) - }) - - it("revokes grants and refresh tokens by grant id and resolves grant by token hash", () => { - const store = createMemoryStore() - const now = 1000 - - store.createGrant({ - id: "g1", - clientId: "c1", - inlineUserId: 42n, - scope: "messages:read", - spaceIds: [1n], - inlineTokenEnc: "enc", - nowMs: now, - }) - - store.createAccessToken({ tokenHashHex: "access1", grantId: "g1", nowMs: now, expiresAtMs: now + 1000 }) - store.createRefreshToken({ tokenHashHex: "refresh1", grantId: "g1", nowMs: now, expiresAtMs: now + 1000 }) - store.createRefreshToken({ tokenHashHex: "refresh2", grantId: "g1", nowMs: now, expiresAtMs: now + 1000 }) - - expect(store.findGrantIdByTokenHash("access1")).toBe("g1") - expect(store.findGrantIdByTokenHash("refresh1")).toBe("g1") - expect(store.findGrantIdByTokenHash("missing")).toBeNull() - - store.revokeGrant("g1", now + 10) - expect(store.getGrant("g1")?.revokedAtMs).toBe(now + 10) - - store.revokeRefreshTokensByGrant("g1", now + 20) - expect(store.getRefreshToken("refresh1", now + 21)).toBeNull() - expect(store.getRefreshToken("refresh2", now + 21)).toBeNull() - }) -}) diff --git a/packages/mcp/src/server/store/memory-store.ts b/packages/mcp/src/server/store/memory-store.ts deleted file mode 100644 index 5876413286..0000000000 --- a/packages/mcp/src/server/store/memory-store.ts +++ /dev/null @@ -1,205 +0,0 @@ -import type { - AuthCode, - AuthRequest, - Grant, - RegisteredClient, - StoredAccessToken, - StoredRefreshToken, - Store, -} from "./types" - -export function createMemoryStore(): Store { - const clients = new Map() - const authRequests = new Map() - const grants = new Map() - const authCodes = new Map() - const accessTokens = new Map() - const refreshTokens = new Map() - const rateLimits = new Map() - - return { - ensureSchema() {}, - - cleanupExpired(nowMs) { - for (const [id, ar] of authRequests) { - if (ar.expiresAtMs <= nowMs) authRequests.delete(id) - } - for (const [code, ac] of authCodes) { - if (ac.expiresAtMs <= nowMs) authCodes.delete(code) - } - for (const [key, entry] of rateLimits) { - if (entry.resetAtMs <= nowMs) rateLimits.delete(key) - } - }, - - consumeRateLimit({ key, nowMs, windowMs, max }) { - const existing = rateLimits.get(key) - if (!existing || existing.resetAtMs <= nowMs) { - rateLimits.set(key, { count: 1, resetAtMs: nowMs + windowMs }) - return { allowed: true, retryAfterSeconds: 0 } - } - - existing.count += 1 - const allowed = existing.count <= max - const retryAfterSeconds = allowed ? 0 : Math.max(1, Math.ceil((existing.resetAtMs - nowMs) / 1000)) - return { allowed, retryAfterSeconds } - }, - - createClient({ redirectUris, clientName, nowMs }) { - const clientId = crypto.randomUUID() - const client: RegisteredClient = { clientId, redirectUris, clientName, createdAtMs: nowMs } - clients.set(clientId, client) - return client - }, - getClient(clientId) { - return clients.get(clientId) ?? null - }, - - createAuthRequest(input) { - const ar: AuthRequest = { - id: input.id, - clientId: input.clientId, - redirectUri: input.redirectUri, - state: input.state, - scope: input.scope, - codeChallenge: input.codeChallenge, - csrfToken: input.csrfToken, - deviceId: input.deviceId, - inlineUserId: null, - email: null, - inlineTokenEnc: null, - createdAtMs: input.nowMs, - expiresAtMs: input.expiresAtMs, - } - authRequests.set(input.id, ar) - return ar - }, - getAuthRequest(id, nowMs) { - const ar = authRequests.get(id) - if (!ar) return null - if (ar.expiresAtMs <= nowMs) return null - return ar - }, - setAuthRequestEmail(id, email) { - const ar = authRequests.get(id) - if (!ar) return - ar.email = email - }, - setAuthRequestInlineTokenEnc(id, inlineTokenEnc) { - const ar = authRequests.get(id) - if (!ar) return - ar.inlineTokenEnc = inlineTokenEnc - }, - setAuthRequestInlineUserId(id, inlineUserId) { - const ar = authRequests.get(id) - if (!ar) return - ar.inlineUserId = inlineUserId - }, - deleteAuthRequest(id) { - authRequests.delete(id) - }, - - createGrant(input) { - const allowDms = input.allowDms ?? false - const allowHomeThreads = input.allowHomeThreads ?? false - const grant: Grant = { - id: input.id, - clientId: input.clientId, - inlineUserId: input.inlineUserId, - scope: input.scope, - spaceIds: input.spaceIds, - allowDms, - allowHomeThreads, - inlineTokenEnc: input.inlineTokenEnc, - createdAtMs: input.nowMs, - revokedAtMs: null, - } - grants.set(grant.id, grant) - return grant - }, - getGrant(grantId) { - return grants.get(grantId) ?? null - }, - revokeGrant(grantId, nowMs) { - const grant = grants.get(grantId) - if (!grant) return - grant.revokedAtMs = nowMs - }, - - createAuthCode(input) { - const code: AuthCode = { - code: input.code, - grantId: input.grantId, - clientId: input.clientId, - redirectUri: input.redirectUri, - codeChallenge: input.codeChallenge, - usedAtMs: null, - createdAtMs: input.nowMs, - expiresAtMs: input.expiresAtMs, - } - authCodes.set(code.code, code) - return code - }, - getAuthCode(code, nowMs) { - const ac = authCodes.get(code) - if (!ac) return null - if (ac.expiresAtMs <= nowMs) return null - return ac - }, - markAuthCodeUsed(code, nowMs) { - const ac = authCodes.get(code) - if (!ac) return - ac.usedAtMs = nowMs - }, - - createAccessToken({ tokenHashHex, grantId, nowMs, expiresAtMs }) { - accessTokens.set(tokenHashHex, { tokenHashHex, grantId, createdAtMs: nowMs, expiresAtMs, revokedAtMs: null }) - }, - getAccessToken(tokenHashHex, nowMs) { - const at = accessTokens.get(tokenHashHex) - if (!at) return null - if (at.revokedAtMs != null) return null - if (at.expiresAtMs <= nowMs) return null - return at - }, - - createRefreshToken({ tokenHashHex, grantId, nowMs, expiresAtMs }) { - refreshTokens.set(tokenHashHex, { - tokenHashHex, - grantId, - createdAtMs: nowMs, - expiresAtMs, - revokedAtMs: null, - replacedByHashHex: null, - }) - }, - getRefreshToken(tokenHashHex, nowMs) { - const rt = refreshTokens.get(tokenHashHex) - if (!rt) return null - if (rt.revokedAtMs != null) return null - if (rt.expiresAtMs <= nowMs) return null - return rt - }, - revokeRefreshToken(tokenHashHex, nowMs, replacedByHashHex) { - const rt = refreshTokens.get(tokenHashHex) - if (!rt) return - rt.revokedAtMs = nowMs - rt.replacedByHashHex = replacedByHashHex - }, - revokeRefreshTokensByGrant(grantId, nowMs) { - for (const rt of refreshTokens.values()) { - if (rt.grantId !== grantId) continue - if (rt.revokedAtMs != null) continue - rt.revokedAtMs = nowMs - rt.replacedByHashHex = null - } - }, - findGrantIdByTokenHash(tokenHashHex) { - const refresh = refreshTokens.get(tokenHashHex) - if (refresh) return refresh.grantId - const access = accessTokens.get(tokenHashHex) - if (access) return access.grantId - return null - }, - } -} diff --git a/packages/mcp/src/server/store/types.ts b/packages/mcp/src/server/store/types.ts deleted file mode 100644 index ac5980d23e..0000000000 --- a/packages/mcp/src/server/store/types.ts +++ /dev/null @@ -1,131 +0,0 @@ -export type RegisteredClient = { - clientId: string - redirectUris: string[] - clientName: string | null - createdAtMs: number -} - -export type AuthRequest = { - id: string - clientId: string - redirectUri: string - state: string - scope: string - codeChallenge: string - csrfToken: string - deviceId: string - inlineUserId: bigint | null - email: string | null - inlineTokenEnc: string | null - createdAtMs: number - expiresAtMs: number -} - -export type Grant = { - id: string - clientId: string - inlineUserId: bigint - scope: string - spaceIds: bigint[] - allowDms: boolean - allowHomeThreads: boolean - inlineTokenEnc: string - createdAtMs: number - revokedAtMs: number | null -} - -export type AuthCode = { - code: string - grantId: string - clientId: string - redirectUri: string - codeChallenge: string - usedAtMs: number | null - createdAtMs: number - expiresAtMs: number -} - -export type StoredAccessToken = { - tokenHashHex: string - grantId: string - createdAtMs: number - expiresAtMs: number - revokedAtMs: number | null -} - -export type StoredRefreshToken = { - tokenHashHex: string - grantId: string - createdAtMs: number - expiresAtMs: number - revokedAtMs: number | null - replacedByHashHex: string | null -} - -export type RateLimitResult = { - allowed: boolean - retryAfterSeconds: number -} - -export type Store = { - ensureSchema(): void - cleanupExpired(nowMs: number): void - - consumeRateLimit(input: { key: string; nowMs: number; windowMs: number; max: number }): RateLimitResult - - createClient(input: { redirectUris: string[]; clientName: string | null; nowMs: number }): RegisteredClient - getClient(clientId: string): RegisteredClient | null - - createAuthRequest(input: { - id: string - clientId: string - redirectUri: string - state: string - scope: string - codeChallenge: string - csrfToken: string - deviceId: string - nowMs: number - expiresAtMs: number - }): AuthRequest - getAuthRequest(id: string, nowMs: number): AuthRequest | null - setAuthRequestEmail(id: string, email: string): void - setAuthRequestInlineTokenEnc(id: string, inlineTokenEnc: string): void - setAuthRequestInlineUserId(id: string, inlineUserId: bigint): void - deleteAuthRequest(id: string): void - - createGrant(input: { - id: string - clientId: string - inlineUserId: bigint - scope: string - spaceIds: bigint[] - allowDms?: boolean - allowHomeThreads?: boolean - inlineTokenEnc: string - nowMs: number - }): Grant - getGrant(grantId: string): Grant | null - revokeGrant(grantId: string, nowMs: number): void - - createAuthCode(input: { - code: string - grantId: string - clientId: string - redirectUri: string - codeChallenge: string - nowMs: number - expiresAtMs: number - }): AuthCode - getAuthCode(code: string, nowMs: number): AuthCode | null - markAuthCodeUsed(code: string, nowMs: number): void - - createAccessToken(input: { tokenHashHex: string; grantId: string; nowMs: number; expiresAtMs: number }): void - getAccessToken(tokenHashHex: string, nowMs: number): StoredAccessToken | null - - createRefreshToken(input: { tokenHashHex: string; grantId: string; nowMs: number; expiresAtMs: number }): void - getRefreshToken(tokenHashHex: string, nowMs: number): StoredRefreshToken | null - revokeRefreshToken(tokenHashHex: string, nowMs: number, replacedByHashHex: string | null): void - revokeRefreshTokensByGrant(grantId: string, nowMs: number): void - findGrantIdByTokenHash(tokenHashHex: string): string | null -}