Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
MCP sign-in: keep the client secret a server issues at registration
darkbringer196c93df80f8e
diff --git a/server/mcp-oauth-store.ts b/server/mcp-oauth-store.tsindex 9360b2c360..cec98618c7 100644--- a/server/mcp-oauth-store.ts+++ b/server/mcp-oauth-store.ts@@ -17,7 +17,9 @@ const recordSchema = z.object({state: z.enum(["needs-sign-in", "signed-in"]),issuer: z.string().optional(),clientId: z.string().optional(),- /** The secret stays in config.json; it is never kept here. */+ /** Only a secret the server issued at dynamic registration. A configured app's secret stays in config.json and is+ * never kept here. */+ clientSecret: z.string().optional(),tokenAuth: z.enum(["client_secret_post", "client_secret_basic"]).optional(),redirectUri: z.string().optional(),tokenEndpoint: z.string().optional(),diff --git a/server/mcp-oauth.test.ts b/server/mcp-oauth.test.tsindex 79a93ac22c..0bed8ffeff 100644--- a/server/mcp-oauth.test.ts+++ b/server/mcp-oauth.test.ts@@ -326,6 +326,34 @@ describe("review fixes", () => {expect(manager.authState("docs", mcp.url)).toBe("signed-in");});+ it("keeps a secret the server issues at registration and proves it on sign-in, refresh and sign-out", async () => {+ await setup({ registerConfidential: "client_secret_basic", expiresIn: 60 });+ const started = await manager.start("docs", mcp.url);+ await approve(started);+ expect((await settled("docs", started.flowId)).phase).toBe("succeeded");+ const token = await manager.accessToken("docs", mcp.url);+ expect(oauth.counts.refresh).toBe(1);+ expect(oauth.isValid(`Bearer ${token}`)).toBe(true);+ await manager.signOut("docs", mcp.url);+ expect(oauth.counts.revoke).toBe(1);+ expect(oauth.clientAuths).toEqual([+ { method: "basic", clientId: "client_1" },+ { method: "basic", clientId: "client_1" },+ { method: "basic", clientId: "client_1" },+ ]);+ });++ it("sends an issued secret in the form when the registration asks for that", async () => {+ await setup({ registerConfidential: "client_secret_post" });+ const started = await manager.start("docs", mcp.url);+ await approve(started);+ expect((await settled("docs", started.flowId)).phase).toBe("succeeded");+ expect(oauth.clientAuths).toEqual([{ method: "post", clientId: "client_1" }]);+ const stored = JSON.parse(readFileSync(join(dir, "mcp-oauth.json"), "utf8")).servers.docs;+ expect(stored).toMatchObject({ clientId: "client_1", tokenAuth: "client_secret_post" });+ expect(stored.clientSecret).toMatch(/^secret_/);+ });+it("registers a fresh client for every sign-in", async () => {await setup();for (let i = 0; i < 2; i++) {diff --git a/server/mcp-oauth.ts b/server/mcp-oauth.tsindex 78fa01fce4..a79c350035 100644--- a/server/mcp-oauth.ts+++ b/server/mcp-oauth.ts@@ -134,6 +134,8 @@ interface ClientAuth {id: string;secret?: string;method: TokenAuthMethod;+ /** Issued by the server's dynamic registration, not configured: kept with the sign-in so refreshes can prove it. */+ registered?: boolean;}/** RFC 8414 §2: an absent list means client_secret_basic. */@@ -251,6 +253,7 @@ export class McpOAuthManager {private recordClient(name: string, record: McpOAuthRecord): ClientAuth | null {if (!record.clientId) return null;if (!record.tokenAuth) return { id: record.clientId, method: "none" };+ if (record.clientSecret) return { id: record.clientId, secret: record.clientSecret, method: record.tokenAuth };const configured = this.clients(name, record.url);return configured?.clientId === record.clientId && configured.clientSecret? { id: record.clientId, secret: configured.clientSecret, method: record.tokenAuth }@@ -528,8 +531,9 @@ export class McpOAuthManager {}}- /** A fresh public client per sign-in: authorization servers prune idle clients, so a cached id goes stale. */- private async register(meta: McpAuthMetadata, redirectUri: string): Promise<string> {+ /** A fresh client per sign-in: authorization servers prune idle clients, so a cached id goes stale. It asks to be+ * public; a server that issues a secret anyway (Supabase) gets it back on every token request. */+ private async register(meta: McpAuthMetadata, redirectUri: string): Promise<ClientAuth> {if (!meta.registrationEndpoint) {throw new McpOAuthError("no-registration", "This server only signs in apps registered with it in advance. Edit the server and add that app's client ID under Sign-in app.");}@@ -547,11 +551,19 @@ export class McpOAuthManager {signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),});const parsed: unknown = await response.json().catch(() => null);- const body = (parsed && typeof parsed === "object" ? parsed : {}) as { client_id?: unknown; error_description?: unknown };+ const body = (parsed && typeof parsed === "object" ? parsed : {}) as {+ client_id?: unknown;+ client_secret?: unknown;+ token_endpoint_auth_method?: unknown;+ error_description?: unknown;+ };if (!response.ok || typeof body.client_id !== "string" || !body.client_id) {throw new RegistrationRefused(registrationRefusal(response, body.error_description));}- return body.client_id;+ if (typeof body.client_secret !== "string" || !body.client_secret) return { id: body.client_id, method: "none" };+ const issued = body.token_endpoint_auth_method;+ const method = issued === "client_secret_basic" || issued === "client_secret_post" ? issued : tokenAuthMethod(meta, body.client_secret);+ return { id: body.client_id, secret: body.client_secret, method, registered: true };}private async begin(name: string, url: string, starting: StartingFlow, wwwAuthenticate?: string | null): Promise<McpSignInStatus> {@@ -563,13 +575,13 @@ export class McpOAuthManager {if (!registered && starting.browser.remote && starting.browser.origin) {const redirectUri = `${starting.browser.origin}${CALLBACK_PATH}`;- let clientId: string | null = null;+ let client: ClientAuth | null = null;try {- clientId = await this.register(meta, redirectUri);+ client = await this.register(meta, redirectUri);} catch (error) {if (!(error instanceof RegistrationRefused)) throw error;}- if (clientId) return { ...this.open(name, url, starting, meta, redirectUri, { id: clientId, method: "none" }, null, meta.scopes).status };+ if (client) return { ...this.open(name, url, starting, meta, redirectUri, client, null, meta.scopes).status };}const listener = await this.listener(preferredPort(url), registered !== undefined);@@ -577,7 +589,7 @@ export class McpOAuthManager {const redirectUri = `http://127.0.0.1:${listener.port}${CALLBACK_PATH}`;const client: ClientAuth = registered? { id: registered.clientId, ...(registered.clientSecret ? { secret: registered.clientSecret } : {}), method: tokenAuthMethod(meta, registered.clientSecret) }- : { id: await this.register(meta, redirectUri), method: "none" };+ : await this.register(meta, redirectUri);const scopes = registered?.scopes?.length ? registered.scopes : meta.scopes;const flow = this.open(name, url, starting, meta, redirectUri, client, listener, scopes);listener.reserved -= 1;@@ -778,6 +790,7 @@ export class McpOAuthManager {state: "signed-in",issuer: flow.meta.issuer,clientId: flow.client.id,+ ...(flow.client.registered && flow.client.secret ? { clientSecret: flow.client.secret } : {}),...(flow.client.method !== "none" ? { tokenAuth: flow.client.method } : {}),redirectUri: flow.redirectUri,tokenEndpoint: flow.meta.tokenEndpoint,diff --git a/server/testing/fake-oauth-server.ts b/server/testing/fake-oauth-server.tsindex 3a8cc41c1e..da1d82a0a5 100644--- a/server/testing/fake-oauth-server.ts+++ b/server/testing/fake-oauth-server.ts@@ -34,6 +34,8 @@ export interface FakeOAuthOptions {preRegistered?: Record<string, string | null>;/** advertised token_endpoint_auth_methods_supported */tokenAuthMethods?: string[];+ /** registration issues a secret with this method, whatever the client asked for, and the token endpoint requires it */+ registerConfidential?: "client_secret_basic" | "client_secret_post";/** Require offline_access to issue a refresh token and advertise it only on the authorization server. */offlineAccess?: boolean;}@@ -77,7 +79,7 @@ export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<Falet issuer = "";const clientAuths: FakeClientAuth[] = [];const fake: Partial<FakeOAuth> = { lastAuthorize: null, clientAuths, options };- const preRegistered = options.preRegistered ?? {};+ const preRegistered = { ...options.preRegistered };/** The authenticated client, or null when its secret is missing or wrong (RFC 6749 §2.3: one method per request). */const authenticate = (req: IncomingMessage, form: URLSearchParams): string | null => {@@ -142,6 +144,11 @@ export async function startFakeOAuth(options: FakeOAuthOptions = {}): Promise<Faconst body = JSON.parse(await readBody(req)) as { redirect_uris?: string[] };if (body.redirect_uris?.some((uri) => options.refuseRedirect?.(uri))) return json(res, 400, { error: "invalid_redirect_uri" });const clientId = `client_${counts.register}`;+ if (options.registerConfidential) {+ const secret = `secret_${randomBytes(8).toString("hex")}`;+ preRegistered[clientId] = secret;+ return json(res, 201, { client_id: clientId, client_secret: secret, token_endpoint_auth_method: options.registerConfidential, redirect_uris: body.redirect_uris });+ }clients.add(clientId);return json(res, 201, { client_id: clientId, redirect_uris: body.redirect_uris });}