From 149589ae7e6b72a5be57ddb052a41f3eee0e7614 Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Tue, 18 Aug 2026 23:13:12 +0000 Subject: [PATCH 1/2] fix(brain): keep the confirmed company domain after checkout return (#1536) Returning from Stripe remounts onboarding and reseeds the domain from the user's email, so the header showed the wrong company and a research retry would re-run on the wrong domain. Past the confirm step, read the org's stored brainWorkspaceDomain instead. --- .../onboarding-brain/company-brain-onboarding.tsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/web/components/onboarding-brain/company-brain-onboarding.tsx b/apps/web/components/onboarding-brain/company-brain-onboarding.tsx index 3d69acb73..61b0cdddf 100644 --- a/apps/web/components/onboarding-brain/company-brain-onboarding.tsx +++ b/apps/web/components/onboarding-brain/company-brain-onboarding.tsx @@ -3,6 +3,7 @@ import { LogoFull } from "@ui/assets/Logo" import { Button } from "@ui/components/button" import { Input } from "@ui/components/input" +import { useAuth } from "@lib/auth-context" import { cn } from "@lib/utils" import { ArrowRight, @@ -15,6 +16,7 @@ import { import { useQuery, useQueryClient } from "@tanstack/react-query" import { AnimatePresence, motion } from "motion/react" import { type ReactNode, useEffect, useRef, useState } from "react" +import { getBrainWorkspaceDomain } from "@/lib/billing-utils" import { dmSans125ClassName, dmSansClassName } from "@/lib/fonts" import { type ResearchEvent, @@ -102,13 +104,19 @@ export function CompanyBrainOnboarding({ setPhase("trial") analytics.brainTrialCardViewed() }, [needsSetup, phase]) + const { org } = useAuth() const [domain, setDomain] = useState(initialDomain) const [organizationChoices, setOrganizationChoices] = useState< CompanyBrainOrganizationChoice[] | null >(null) const [serverSchedulesResearch, setServerSchedulesResearch] = useState(false) const firstName = name.trim().split(/\s+/)[0] ?? "" - const clean = normalizeDomain(domain) + // Returning from checkout remounts and reseeds local state from the email domain, + // so past the confirm step the org's stored domain is the one to trust. + const confirmedDomain = getBrainWorkspaceDomain(org?.metadata) + const clean = normalizeDomain( + phase === "confirm" ? domain : confirmedDomain || domain, + ) const queryClient = useQueryClient() const { status: researchStatus } = useResearchStatus(phase === "research") const researchDone = researchStatus === "done" From 18a2dfbe3929c872684fd2b407fc0058c427baa3 Mon Sep 17 00:00:00 2001 From: Dhravya Date: Wed, 19 Aug 2026 02:27:27 +0000 Subject: [PATCH 2/2] feat(mcp): accept Supermemory API keys as Bearer auth (#1537) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Stack Context Single-auth story for the Claude Code supermemory plugin rework: the plugin's hooks and its MCP surface share one credential (`sm_` API key from the existing browser connect flow). That requires `mcp.supermemory.ai` to accept plain API keys, which it currently rejects (OAuth JWT only). ## What? - `validateApiKey()` in `server/auth`: `sm_`-prefixed Bearer tokens validate via the existing `fetchSession()` (`GET /v3/session`) and map to the same `AuthUser` shape as OAuth tokens (`userId` ← `user.id`, `organizationId` ← `org.id`, the key itself as `bearerToken` for downstream API calls). Successful lookups cached per isolate for 60s. - `handleMcpRequest` routes by token shape: `sm_` keys → session validation, everything else → OAuth JWT verification (unchanged). - `sessionInfoSchema` now types the `org.id` field the session endpoint already returns. ## Why? MCP clients that already hold an API key (Claude Code plugin hooks, CLI, scripts) can connect without an OAuth dance or a second consent. OAuth behavior is untouched — the existing "rejects opaque API keys" test on the OAuth validator still passes; keys just get their own path. Malformed keys are rejected without an API round-trip. Tests: 4 new cases (valid key → AuthUser, cache hit → single fetch, 401 → null, malformed → no request). `vitest run src/server/auth` 13/13, `tsc --noEmit` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- > [!NOTE] > **Medium Risk** > Adds a new authentication path on the MCP entrypoint with in-memory key caching (60s TTL), so revoked keys may remain valid briefly within an isolate; OAuth behavior is unchanged. > > **Overview** > MCP Bearer auth now accepts **`sm_` Supermemory API keys** in addition to OAuth JWTs, so clients that already hold an API key can connect without OAuth. > > **`validateApiKey`** treats keys matching `sm_` plus at least 17 non-space characters as API keys: it calls **`GET /v3/session`** with the key as Bearer, maps **`user.id`** and **`org.id`** into the same **`AuthUser`** shape as OAuth (key kept as **`bearerToken`** for downstream API calls), and caches successful results per isolate for **60s** (up to 1000 entries, full clear on overflow). Malformed keys are rejected locally with no HTTP call; session **401** yields unauthenticated. > > **`handleMcpRequest`** branches on token shape: API keys go through session validation; other tokens still use JWT verification unchanged. > > **`sessionInfoSchema`** now includes optional **`org.id`** typing for session responses used when resolving organization context from API keys. > > Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e54fb11bf1598d07a807eb2b0b63a347aaa58fb6. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot). --- apps/mcp/src/server/auth/index.test.ts | 62 +++++++++++++++++++++++++- apps/mcp/src/server/auth/index.ts | 45 +++++++++++++++++++ apps/mcp/src/server/index.ts | 11 ++++- apps/mcp/src/shared/types.ts | 1 + 4 files changed, 116 insertions(+), 3 deletions(-) diff --git a/apps/mcp/src/server/auth/index.test.ts b/apps/mcp/src/server/auth/index.test.ts index e3501890e..8e8d043ee 100644 --- a/apps/mcp/src/server/auth/index.test.ts +++ b/apps/mcp/src/server/auth/index.test.ts @@ -1,6 +1,6 @@ import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT } from "jose" import { afterEach, beforeAll, describe, expect, it, vi } from "vitest" -import { fetchSession, validateOAuthToken } from "./index" +import { fetchSession, validateApiKey, validateOAuthToken } from "./index" const API_URL = "https://api.example.com" const ISSUER = `${API_URL}/api/auth` @@ -120,4 +120,64 @@ describe("MCP authentication", () => { status: 403, }) }) + + function sessionResponse() { + return Response.json({ + user: { id: "user_test", email: "test@example.com" }, + org: { id: "org_test" }, + role: "owner", + accessType: "full", + scope: { type: "full", permission: "write" }, + }) + } + + it("validates an sm_ API key via the session endpoint", async () => { + const fetchSpy = vi.fn().mockResolvedValue(sessionResponse()) + vi.stubGlobal("fetch", fetchSpy) + const key = "sm_valid_key_0123456789abcdef" + + await expect(validateApiKey(key, API_URL)).resolves.toEqual({ + userId: "user_test", + organizationId: "org_test", + bearerToken: key, + scopes: [], + }) + expect(fetchSpy).toHaveBeenCalledWith( + `${API_URL}/v3/session`, + expect.objectContaining({ + headers: { Authorization: `Bearer ${key}` }, + }), + ) + }) + + it("caches a validated API key within the TTL", async () => { + const fetchSpy = vi.fn().mockResolvedValue(sessionResponse()) + vi.stubGlobal("fetch", fetchSpy) + const key = "sm_cached_key_0123456789abcdef" + + await validateApiKey(key, API_URL) + await validateApiKey(key, API_URL) + expect(fetchSpy).toHaveBeenCalledTimes(1) + }) + + it("rejects an API key the session endpoint refuses", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}) + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(new Response(null, { status: 401 })), + ) + + await expect( + validateApiKey("sm_revoked_key_0123456789abcdef", API_URL), + ).resolves.toBeNull() + }) + + it("rejects malformed API keys without an API request", async () => { + const fetchSpy = vi.fn() + vi.stubGlobal("fetch", fetchSpy) + + await expect(validateApiKey("sm_short", API_URL)).resolves.toBeNull() + await expect(validateApiKey("not_a_key", API_URL)).resolves.toBeNull() + expect(fetchSpy).not.toHaveBeenCalled() + }) }) diff --git a/apps/mcp/src/server/auth/index.ts b/apps/mcp/src/server/auth/index.ts index a09969339..425f05970 100644 --- a/apps/mcp/src/server/auth/index.ts +++ b/apps/mcp/src/server/auth/index.ts @@ -52,6 +52,51 @@ export async function fetchSession( return result.data } +// Opaque Supermemory API keys (sm_...) authenticate via the session endpoint +// instead of JWT verification. Successful lookups are cached per isolate so a +// busy MCP session doesn't re-validate on every JSON-RPC message. +const API_KEY_PATTERN = /^sm_\S{17,}$/ +const API_KEY_CACHE_TTL_MS = 60_000 +const API_KEY_CACHE_MAX_ENTRIES = 1000 + +const apiKeyCache = new Map() + +export function isApiKey(token: string): boolean { + return API_KEY_PATTERN.test(token) +} + +export async function validateApiKey( + token: string, + apiUrl: string, +): Promise { + if (!isApiKey(token)) return null + + const cached = apiKeyCache.get(token) + if (cached && cached.expiresAt > Date.now()) return cached.user + + try { + const session = await fetchSession(token, apiUrl) + const organizationId = session.org?.id + if (!organizationId) return null + + const user: AuthUser = { + userId: session.user.id, + organizationId, + bearerToken: token, + scopes: [], + } + if (apiKeyCache.size >= API_KEY_CACHE_MAX_ENTRIES) apiKeyCache.clear() + apiKeyCache.set(token, { + user, + expiresAt: Date.now() + API_KEY_CACHE_TTL_MS, + }) + return user + } catch (error) { + console.error("API key validation error:", error) + return null + } +} + export async function validateOAuthToken( token: string, apiUrl: string, diff --git a/apps/mcp/src/server/index.ts b/apps/mcp/src/server/index.ts index f435ea3a4..0fac82c71 100644 --- a/apps/mcp/src/server/index.ts +++ b/apps/mcp/src/server/index.ts @@ -2,7 +2,12 @@ import type { AuthInfo } from "@modelcontextprotocol/server" import { createMcpHandler } from "agents/mcp/server" import { Hono, type Context } from "hono" import { cors } from "hono/cors" -import { validateOAuthToken, type AuthUser } from "./auth" +import { + isApiKey, + validateApiKey, + validateOAuthToken, + type AuthUser, +} from "./auth" import { SupermemoryMCP } from "./legacy-protocol-state" import { createSupermemoryServer } from "./server" import type { ActorContext, ServerEnv } from "./types" @@ -176,7 +181,9 @@ async function handleMcpRequest( if (!token) return unauthorizedResponse(resourceMetadataUrl) - const authUser = await validateOAuthToken(token, apiUrl, mcpResource) + const authUser = isApiKey(token) + ? await validateApiKey(token, apiUrl) + : await validateOAuthToken(token, apiUrl, mcpResource) if (!authUser) return unauthorizedResponse(resourceMetadataUrl, true) const actor: ActorContext = { diff --git a/apps/mcp/src/shared/types.ts b/apps/mcp/src/shared/types.ts index b8c4fe357..838b13fb6 100644 --- a/apps/mcp/src/shared/types.ts +++ b/apps/mcp/src/shared/types.ts @@ -27,6 +27,7 @@ export const sessionInfoSchema = z.looseObject({ email: z.string().optional(), name: z.string().optional(), }), + org: z.looseObject({ id: z.string().min(1) }).optional(), role: z.string().optional(), accessType: z.enum(["full", "restricted"]).optional(), containerTags: z.array(containerTagAccessSchema).nullable().optional(),