The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { |
| 4 | AuthMcpClientAccess, |
| 5 | AuthStandardClientScopes, |
| 6 | type AuthCreatePairingCredentialInput, |
| 7 | type EnvironmentCloudLinkStateResult, |
| 8 | EnvironmentHttpApi, |
| 9 | MCP_PEER_LINK_SOFTWARE_ID, |
| 10 | mcpClientScopes, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import { expect, it } from "@effect/vitest"; |
| 13 | import * as Clock from "effect/Clock"; |
| 14 | import * as Context from "effect/Context"; |
| 15 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as Layer from "effect/Layer"; |
| 18 | import * as Etag from "effect/http/Etag"; |
| 19 | import * as HttpPlatform from "effect/http/HttpPlatform"; |
| 20 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 21 | import * as HttpServerRequest from "effect/http/HttpServerRequest"; |
| 22 | import * as HttpApi from "effect/http-api/HttpApi"; |
| 23 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 24 | import * as Schema from "effect/Schema"; |
| 25 | |
| 26 | import * as CloudLink from "../cloud/CloudLink.ts"; |
| 27 | import * as ServerConfig from "../config.ts"; |
| 28 | import { makeDpopKey } from "./dpop.testkit.ts"; |
| 29 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 30 | import * as ServerSettings from "../serverSettings.ts"; |
| 31 | import * as Sqlite from "../persistence/Sqlite.ts"; |
| 32 | import * as EnvironmentAuth from "./EnvironmentAuth.ts"; |
| 33 | import * as McpOAuth from "./McpOAuth.ts"; |
| 34 | import * as McpOAuthHttp from "./mcpOAuthHttp.ts"; |
| 35 | import * as ServerSecretStore from "./ServerSecretStore.ts"; |
| 36 | import * as AuthHttp from "./http.ts"; |
| 37 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 38 | |
| 39 | class AuthTestApi extends HttpApi.make("environment") |
| 40 | .add(EnvironmentHttpApi.groups.auth) |
| 41 | .add(EnvironmentHttpApi.groups.mcpOAuth) {} |
| 42 | |
| 43 | const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" }); |
| 44 | const layerEnvironmentAuth = EnvironmentAuth.layer.pipe( |
| 45 | Layer.provide(ManagedPolicy.layerTest()), |
| 46 | Layer.provide(Sqlite.layerMemory), |
| 47 | Layer.provideMerge(ServerSecretStore.layer), |
| 48 | Layer.provideMerge(ServerEnvironment.layerIdentity), |
| 49 | Layer.provide(layerConfig), |
| 50 | ); |
| 51 | const notLinked: EnvironmentCloudLinkStateResult = { |
| 52 | linked: false, |
| 53 | cloudUserId: null, |
| 54 | relayUrl: null, |
| 55 | relayIssuer: null, |
| 56 | publishAgentActivity: false, |
| 57 | }; |
| 58 | const makeLayerRoutes = ( |
| 59 | capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void, |
| 60 | linkState: EnvironmentCloudLinkStateResult, |
| 61 | ) => |
| 62 | Layer.mergeAll( |
| 63 | Layer.effectDiscard( |
| 64 | EnvironmentAuth.EnvironmentAuth.pipe(Effect.tap((auth) => Effect.sync(() => capture(auth)))), |
| 65 | ), |
| 66 | HttpApiBuilder.layer(AuthTestApi).pipe( |
| 67 | Layer.provide(AuthHttp.layer), |
| 68 | Layer.provide( |
| 69 | McpOAuthHttp.layer.pipe( |
| 70 | Layer.provide(McpOAuth.layer), |
| 71 | Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })), |
| 72 | Layer.provide( |
| 73 | Layer.mock(CloudLink.CloudLink)({ linkState: () => Effect.succeed(linkState) }), |
| 74 | ), |
| 75 | ), |
| 76 | ), |
| 77 | Layer.provide(AuthHttp.layerAuthenticatedAuth), |
| 78 | ), |
| 79 | ).pipe( |
| 80 | Layer.provideMerge(layerEnvironmentAuth), |
| 81 | Layer.provide(layerConfig), |
| 82 | Layer.provideMerge( |
| 83 | HttpPlatform.layer.pipe( |
| 84 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 85 | Layer.provideMerge(Etag.layerWeak), |
| 86 | ), |
| 87 | ), |
| 88 | Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 89 | ); |
| 90 | |
| 91 | const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); |
| 92 | const ORIGIN = "https://box.example.ts.net"; |
| 93 | const REDIRECT = "http://localhost/callback"; |
| 94 | const verifier = "a".repeat(43) + "-verifier-for-tests"; |
| 95 | const challenge = "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c"; |
| 96 | |
| 97 | const at = (path: string, init?: RequestInit) => |
| 98 | new Request(`http://127.0.0.1${path}`, { |
| 99 | ...init, |
| 100 | headers: { host: "box.example.ts.net", "x-forwarded-proto": "https", ...init?.headers }, |
| 101 | }); |
| 102 | const form = (body: Record<string, string>) => ({ |
| 103 | method: "POST", |
| 104 | headers: { "content-type": "application/x-www-form-urlencoded" }, |
| 105 | body: new URLSearchParams(body).toString(), |
| 106 | }); |
| 107 | |
| 108 | type Handler = (request: Request) => Effect.Effect<Response>; |
| 109 | |
| 110 | const withRoutes = <A, E>( |
| 111 | use: (handler: Handler, auth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>, |
| 112 | linkState = notLinked, |
| 113 | ) => |
| 114 | Effect.gen(function* () { |
| 115 | const random = yield* SecureRandom.SecureRandom; |
| 116 | const context = Context.make(SecureRandom.SecureRandom, random); |
| 117 | let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined; |
| 118 | const layerRoutes = makeLayerRoutes((auth) => { |
| 119 | routerAuth = auth; |
| 120 | }, linkState); |
| 121 | return yield* Effect.acquireUseRelease( |
| 122 | Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })), |
| 123 | (web) => |
| 124 | Effect.gen(function* () { |
| 125 | const handler: Handler = (request) => Effect.promise(() => web.handler(request, context)); |
| 126 | yield* handler(at("/.well-known/oauth-authorization-server")); |
| 127 | return yield* use(handler, routerAuth!); |
| 128 | }), |
| 129 | (web) => Effect.promise(() => web.dispose()), |
| 130 | ); |
| 131 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); |
| 132 | |
| 133 | const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>); |
| 134 | |
| 135 | /** `credential` is a browser cookie, `Bearer <token>`, or the headers of a DPoP request. */ |
| 136 | const postJson = (path: string, body: unknown, credential?: string | Record<string, string>) => |
| 137 | at(path, { |
| 138 | method: "POST", |
| 139 | headers: { |
| 140 | "content-type": "application/json", |
| 141 | ...(credential === undefined |
| 142 | ? {} |
| 143 | : typeof credential !== "string" |
| 144 | ? credential |
| 145 | : credential.startsWith("Bearer ") |
| 146 | ? { authorization: credential } |
| 147 | : { cookie: credential }), |
| 148 | }, |
| 149 | body: encodeJson(body), |
| 150 | }); |
| 151 | |
| 152 | const decide = ( |
| 153 | handler: Handler, |
| 154 | authorization: Record<string, string>, |
| 155 | decision: Record<string, string>, |
| 156 | cookie?: string | Record<string, string>, |
| 157 | ) => |
| 158 | handler(postJson("/oauth/mcp/decision", { authorization, decision }, cookie)).pipe( |
| 159 | Effect.flatMap((response) => |
| 160 | json<{ redirectTo?: string; message?: string }>(response).pipe( |
| 161 | Effect.map((payload) => ({ status: response.status, ...payload })), |
| 162 | ), |
| 163 | ), |
| 164 | ); |
| 165 | |
| 166 | const register = (handler: Handler, redirect = REDIRECT) => |
| 167 | handler( |
| 168 | at("/oauth/mcp/register", { |
| 169 | method: "POST", |
| 170 | headers: { "content-type": "application/json" }, |
| 171 | body: encodeJson({ |
| 172 | client_name: "Claude Code", |
| 173 | redirect_uris: [redirect], |
| 174 | grant_types: ["authorization_code", "refresh_token"], |
| 175 | token_endpoint_auth_method: "none", |
| 176 | }), |
| 177 | }), |
| 178 | ); |
| 179 | |
| 180 | const registeredClientId = (handler: Handler) => |
| 181 | register(handler).pipe( |
| 182 | Effect.flatMap((response) => json<{ client_id: string }>(response)), |
| 183 | Effect.map((body) => body.client_id), |
| 184 | ); |
| 185 | |
| 186 | const authorizeParams = (clientId: string, redirect = "http://localhost:51234/callback") => ({ |
| 187 | response_type: "code", |
| 188 | client_id: clientId, |
| 189 | redirect_uri: redirect, |
| 190 | code_challenge: challenge, |
| 191 | code_challenge_method: "S256", |
| 192 | state: "state-1", |
| 193 | resource: `${ORIGIN}/mcp`, |
| 194 | }); |
| 195 | |
| 196 | it.effect("derives discovery metadata from the origin the client reached", () => |
| 197 | withRoutes((handler) => |
| 198 | Effect.gen(function* () { |
| 199 | const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp")); |
| 200 | expect(yield* json<unknown>(resource)).toMatchObject({ |
| 201 | resource: `${ORIGIN}/mcp`, |
| 202 | authorization_servers: [ORIGIN], |
| 203 | }); |
| 204 | const server = yield* json<unknown>( |
| 205 | yield* handler(at("/.well-known/oauth-authorization-server")), |
| 206 | ); |
| 207 | expect(server).toMatchObject({ |
| 208 | issuer: ORIGIN, |
| 209 | authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`, |
| 210 | token_endpoint: `${ORIGIN}/oauth/mcp/token`, |
| 211 | registration_endpoint: `${ORIGIN}/oauth/mcp/register`, |
| 212 | code_challenge_methods_supported: ["S256"], |
| 213 | }); |
| 214 | }), |
| 215 | ), |
| 216 | ); |
| 217 | |
| 218 | it.effect("registers loopback and https clients and never redirects for an unverified client", () => |
| 219 | withRoutes((handler) => |
| 220 | Effect.gen(function* () { |
| 221 | for (const refused of [ |
| 222 | "http://bot.example/callback", |
| 223 | "https://user:pass@bot.example/callback", |
| 224 | "https://bot.example/callback#", |
| 225 | "http://localhost/callback#", |
| 226 | "javascript:alert(1)", |
| 227 | ]) { |
| 228 | const response = yield* register(handler, refused); |
| 229 | expect(response.status).toBe(400); |
| 230 | expect(yield* json<unknown>(response)).toMatchObject({ error: "invalid_redirect_uri" }); |
| 231 | } |
| 232 | // JSON escaping can inflate the signed client_id past what an authorize URL can carry. |
| 233 | const oversized = yield* handler( |
| 234 | at("/oauth/mcp/register", { |
| 235 | method: "POST", |
| 236 | headers: { "content-type": "application/json" }, |
| 237 | body: encodeJson({ |
| 238 | redirect_uris: Array.from( |
| 239 | { length: 10 }, |
| 240 | (_, index) => `https://bot.example/${index}/${'"'.repeat(480)}`, |
| 241 | ), |
| 242 | }), |
| 243 | }), |
| 244 | ); |
| 245 | expect(oversized.status).toBe(400); |
| 246 | const fiveLongCallbacks = yield* handler( |
| 247 | at("/oauth/mcp/register", { |
| 248 | method: "POST", |
| 249 | headers: { "content-type": "application/json" }, |
| 250 | body: encodeJson({ |
| 251 | client_name: "A".repeat(100), |
| 252 | redirect_uris: Array.from( |
| 253 | { length: 5 }, |
| 254 | (_, index) => `https://a.co/${index}/${"界".repeat(497)}`, |
| 255 | ), |
| 256 | }), |
| 257 | }), |
| 258 | ); |
| 259 | expect(fiveLongCallbacks.status).toBe(201); |
| 260 | |
| 261 | for (const malformed of [ |
| 262 | { client_name: 42, redirect_uris: [REDIRECT] }, |
| 263 | { redirect_uris: REDIRECT }, |
| 264 | ]) { |
| 265 | const response = yield* handler(postJson("/oauth/mcp/register", malformed)); |
| 266 | expect(response.status).toBe(400); |
| 267 | expect(response.headers.get("content-type")).toMatch(/^application\/json/); |
| 268 | expect(yield* json<{ error: string }>(response)).toMatchObject({ |
| 269 | error: expect.stringMatching(/^invalid_(client_metadata|redirect_uri)$/), |
| 270 | }); |
| 271 | } |
| 272 | |
| 273 | const registered = yield* register(handler); |
| 274 | expect(registered.status).toBe(201); |
| 275 | const { client_id: clientId } = (yield* json<unknown>(registered)) as { client_id: string }; |
| 276 | |
| 277 | const forged = yield* handler( |
| 278 | at( |
| 279 | `/oauth/mcp/authorize?${new URLSearchParams(authorizeParams(`${clientId.split(".")[0]}.forged`))}`, |
| 280 | ), |
| 281 | ); |
| 282 | expect(forged.status).toBe(400); |
| 283 | expect(forged.headers.get("location")).toBeNull(); |
| 284 | |
| 285 | const unregistered = yield* handler( |
| 286 | at( |
| 287 | `/oauth/mcp/authorize?${new URLSearchParams( |
| 288 | authorizeParams(clientId, "http://localhost:51234/elsewhere"), |
| 289 | )}`, |
| 290 | ), |
| 291 | ); |
| 292 | expect(unregistered.status).toBe(400); |
| 293 | expect(unregistered.headers.get("location")).toBeNull(); |
| 294 | |
| 295 | for (const resource of [`${ORIGIN}/mcp#section`, `${ORIGIN}/mcp#`]) { |
| 296 | const wrongTarget = yield* handler( |
| 297 | at( |
| 298 | `/oauth/mcp/authorize?${new URLSearchParams({ ...authorizeParams(clientId), resource })}`, |
| 299 | ), |
| 300 | ); |
| 301 | expect(wrongTarget.status).toBe(302); |
| 302 | const location = new URL(wrongTarget.headers.get("location")!, ORIGIN); |
| 303 | expect(location.searchParams.get("error"), resource).toBe("invalid_target"); |
| 304 | } |
| 305 | |
| 306 | const query = new URLSearchParams(authorizeParams(clientId)).toString(); |
| 307 | const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`)); |
| 308 | expect(handoff.status).toBe(302); |
| 309 | expect(handoff.headers.get("location")).toBe(`/connect-agent?${query}`); |
| 310 | const details = yield* handler( |
| 311 | postJson("/oauth/mcp/approval", authorizeParams(clientId)), |
| 312 | ).pipe(Effect.flatMap(json<Record<string, unknown>>)); |
| 313 | expect(details).toEqual({ |
| 314 | clientName: "Claude Code", |
| 315 | redirectHost: "localhost:51234", |
| 316 | environmentHost: "box.example.ts.net", |
| 317 | }); |
| 318 | |
| 319 | const forgedDetails = yield* handler( |
| 320 | postJson("/oauth/mcp/approval", authorizeParams(`${clientId.split(".")[0]}.forged`)), |
| 321 | ); |
| 322 | expect(forgedDetails.status).toBe(400); |
| 323 | expect(yield* json<Record<string, unknown>>(forgedDetails)).not.toHaveProperty("redirectTo"); |
| 324 | }), |
| 325 | ), |
| 326 | ); |
| 327 | |
| 328 | it.live("signs in with a pairing code and issues a token only /mcp accepts", () => |
| 329 | withRoutes((handler, auth) => |
| 330 | Effect.gen(function* () { |
| 331 | const clientId = yield* registeredClientId(handler); |
| 332 | const pairing = yield* auth.issuePairingCredential(); |
| 333 | const params = authorizeParams(clientId); |
| 334 | |
| 335 | const wrongCode = yield* decide(handler, params, { |
| 336 | _tag: "pairing-code", |
| 337 | access: "auto", |
| 338 | code: "nope", |
| 339 | }); |
| 340 | expect(wrongCode.status).toBe(400); |
| 341 | expect(wrongCode.message).toContain("unknown, expired, or already used"); |
| 342 | |
| 343 | const approved = yield* decide(handler, params, { |
| 344 | _tag: "pairing-code", |
| 345 | access: "auto", |
| 346 | code: pairing.credential, |
| 347 | }); |
| 348 | expect(approved.status).toBe(200); |
| 349 | const callback = new URL(approved.redirectTo!); |
| 350 | expect(callback.origin).toBe("http://localhost:51234"); |
| 351 | expect(callback.searchParams.get("state")).toBe("state-1"); |
| 352 | expect(callback.searchParams.get("iss")).toBe(ORIGIN); |
| 353 | const code = callback.searchParams.get("code")!; |
| 354 | |
| 355 | const exchange = (codeVerifier: string) => |
| 356 | handler( |
| 357 | at( |
| 358 | "/oauth/mcp/token", |
| 359 | form({ |
| 360 | grant_type: "authorization_code", |
| 361 | code, |
| 362 | redirect_uri: params.redirect_uri, |
| 363 | client_id: clientId, |
| 364 | code_verifier: codeVerifier, |
| 365 | resource: `${ORIGIN}/mcp`, |
| 366 | }), |
| 367 | ), |
| 368 | ); |
| 369 | const tokenResponse = yield* exchange(verifier); |
| 370 | expect(tokenResponse.status).toBe(200); |
| 371 | const token = (yield* json<unknown>(tokenResponse)) as { |
| 372 | access_token: string; |
| 373 | scope: string; |
| 374 | }; |
| 375 | expect(token.scope).toBe("orchestration:read orchestration:operate"); |
| 376 | |
| 377 | expect((yield* exchange(verifier)).status).toBe(400); |
| 378 | |
| 379 | for (const scheme of ["Bearer", "bearer", "bEaReR"]) { |
| 380 | const client = yield* auth.authenticateMcpClient( |
| 381 | HttpServerRequest.fromWeb( |
| 382 | at("/mcp", { headers: { authorization: `${scheme} ${token.access_token}` } }), |
| 383 | ), |
| 384 | ); |
| 385 | expect(client).toMatchObject({ label: "Claude Code", access: "auto" }); |
| 386 | } |
| 387 | |
| 388 | const session = yield* handler( |
| 389 | at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }), |
| 390 | ); |
| 391 | expect(yield* json<unknown>(session)).toMatchObject({ authenticated: false }); |
| 392 | const ticket = yield* handler( |
| 393 | at("/api/auth/websocket-ticket", { |
| 394 | method: "POST", |
| 395 | headers: { authorization: `Bearer ${token.access_token}` }, |
| 396 | }), |
| 397 | ); |
| 398 | expect(ticket.status).toBe(401); |
| 399 | }), |
| 400 | ), |
| 401 | ); |
| 402 | |
| 403 | it.live("signs in a hosted agent with an https callback that asked for a client secret", () => |
| 404 | withRoutes((handler, auth) => |
| 405 | Effect.gen(function* () { |
| 406 | const callbackUrl = "https://bot.example/oauth/callback"; |
| 407 | const registered = yield* handler( |
| 408 | at("/oauth/mcp/register", { |
| 409 | method: "POST", |
| 410 | headers: { "content-type": "application/json" }, |
| 411 | body: encodeJson({ |
| 412 | client_name: "Hosted bot", |
| 413 | redirect_uris: [callbackUrl], |
| 414 | token_endpoint_auth_method: "client_secret_post", |
| 415 | }), |
| 416 | }), |
| 417 | ); |
| 418 | expect(registered.status).toBe(201); |
| 419 | const client = (yield* json<unknown>(registered)) as { |
| 420 | client_id: string; |
| 421 | token_endpoint_auth_method: string; |
| 422 | }; |
| 423 | expect(client.token_endpoint_auth_method).toBe("none"); |
| 424 | |
| 425 | const params = authorizeParams(client.client_id, callbackUrl); |
| 426 | const details = yield* handler(postJson("/oauth/mcp/approval", params)).pipe( |
| 427 | Effect.flatMap(json<Record<string, unknown>>), |
| 428 | ); |
| 429 | expect(details).toMatchObject({ clientName: "Hosted bot", redirectHost: "bot.example" }); |
| 430 | |
| 431 | const pairing = yield* auth.issuePairingCredential(); |
| 432 | const approved = yield* decide(handler, params, { |
| 433 | _tag: "pairing-code", |
| 434 | access: "approval-required", |
| 435 | code: pairing.credential, |
| 436 | }); |
| 437 | const callback = new URL(approved.redirectTo!); |
| 438 | expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl); |
| 439 | |
| 440 | const tokenResponse = yield* handler( |
| 441 | at( |
| 442 | "/oauth/mcp/token", |
| 443 | form({ |
| 444 | grant_type: "authorization_code", |
| 445 | code: callback.searchParams.get("code")!, |
| 446 | redirect_uri: callbackUrl, |
| 447 | client_id: client.client_id, |
| 448 | client_secret: "unused", |
| 449 | code_verifier: verifier, |
| 450 | }), |
| 451 | ), |
| 452 | ); |
| 453 | expect(tokenResponse.status).toBe(200); |
| 454 | const token = (yield* json<unknown>(tokenResponse)) as { access_token: string }; |
| 455 | const signedIn = yield* auth.authenticateMcpClient( |
| 456 | HttpServerRequest.fromWeb( |
| 457 | at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }), |
| 458 | ), |
| 459 | ); |
| 460 | expect(signedIn).toMatchObject({ label: "Hosted bot", access: "approval-required" }); |
| 461 | }), |
| 462 | ), |
| 463 | ); |
| 464 | |
| 465 | it.live("signs in Gemini, which registers six user-bound redirect URIs for one client", () => |
| 466 | withRoutes((handler, auth) => |
| 467 | Effect.gen(function* () { |
| 468 | const redirectUris = Array.from( |
| 469 | { length: 6 }, |
| 470 | (_, index) => |
| 471 | `https://oauth-redirect.googleusercontent.com/r/user_bound_custom-mcp-test${index}`, |
| 472 | ); |
| 473 | const registered = yield* handler( |
| 474 | at("/oauth/mcp/register", { |
| 475 | method: "POST", |
| 476 | headers: { "content-type": "application/json" }, |
| 477 | body: encodeJson({ |
| 478 | client_name: "Google", |
| 479 | redirect_uris: redirectUris, |
| 480 | token_endpoint_auth_method: "client_secret_basic", |
| 481 | }), |
| 482 | }), |
| 483 | ); |
| 484 | const client = (yield* json<unknown>(registered)) as { client_id: string }; |
| 485 | expect(client).toMatchObject({ redirect_uris: redirectUris }); |
| 486 | expect(registered.status).toBe(201); |
| 487 | |
| 488 | const callbackUrl = redirectUris[5]!; |
| 489 | const params = authorizeParams(client.client_id, callbackUrl); |
| 490 | const pairing = yield* auth.issuePairingCredential(); |
| 491 | const approved = yield* decide(handler, params, { |
| 492 | _tag: "pairing-code", |
| 493 | access: "approval-required", |
| 494 | code: pairing.credential, |
| 495 | }); |
| 496 | const callback = new URL(approved.redirectTo!); |
| 497 | expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl); |
| 498 | }), |
| 499 | ), |
| 500 | ); |
| 501 | |
| 502 | it.live("rejects a wrong PKCE verifier and spends the code", () => |
| 503 | withRoutes((handler, auth) => |
| 504 | Effect.gen(function* () { |
| 505 | const clientId = yield* registeredClientId(handler); |
| 506 | const pairing = yield* auth.issuePairingCredential(); |
| 507 | const params = authorizeParams(clientId); |
| 508 | const approved = yield* decide(handler, params, { |
| 509 | _tag: "pairing-code", |
| 510 | access: "approval-required", |
| 511 | code: pairing.credential, |
| 512 | }); |
| 513 | const code = new URL(approved.redirectTo!).searchParams.get("code")!; |
| 514 | const exchange = (codeVerifier: string) => |
| 515 | handler( |
| 516 | at( |
| 517 | "/oauth/mcp/token", |
| 518 | form({ |
| 519 | grant_type: "authorization_code", |
| 520 | code, |
| 521 | redirect_uri: params.redirect_uri, |
| 522 | client_id: clientId, |
| 523 | code_verifier: codeVerifier, |
| 524 | }), |
| 525 | ), |
| 526 | ); |
| 527 | const wrong = yield* exchange("b".repeat(64)); |
| 528 | expect(wrong.status).toBe(400); |
| 529 | expect(yield* json<unknown>(wrong)).toMatchObject({ error: "invalid_grant" }); |
| 530 | expect((yield* exchange(verifier)).status).toBe(400); |
| 531 | }), |
| 532 | ), |
| 533 | ); |
| 534 | |
| 535 | it.live( |
| 536 | "denies and refuses codes bound to another client's key or without the scopes it grants", |
| 537 | () => |
| 538 | withRoutes((handler, auth) => |
| 539 | Effect.gen(function* () { |
| 540 | const clientId = yield* registeredClientId(handler); |
| 541 | const params = authorizeParams(clientId); |
| 542 | |
| 543 | const denied = yield* decide(handler, params, { _tag: "deny" }); |
| 544 | const deniedUrl = new URL(denied.redirectTo!); |
| 545 | expect(deniedUrl.searchParams.get("error")).toBe("access_denied"); |
| 546 | expect(deniedUrl.searchParams.get("state")).toBe("state-1"); |
| 547 | |
| 548 | const approveWith = (code: string) => |
| 549 | decide(handler, params, { _tag: "pairing-code", access: "auto", code }); |
| 550 | |
| 551 | const bound = yield* auth.createPairingLink({ |
| 552 | proofKeyThumbprint: "device-key-thumbprint", |
| 553 | }); |
| 554 | expect((yield* approveWith(bound.credential)).status).toBe(400); |
| 555 | const stillValid = yield* auth |
| 556 | .exchangeBootstrapCredentialForAccessToken( |
| 557 | bound.credential, |
| 558 | undefined, |
| 559 | { deviceType: "mobile" }, |
| 560 | { proofKeyThumbprint: "device-key-thumbprint" }, |
| 561 | ) |
| 562 | .pipe( |
| 563 | Effect.as(true), |
| 564 | Effect.orElseSucceed(() => false), |
| 565 | ); |
| 566 | expect(stillValid).toBe(true); |
| 567 | |
| 568 | const readOnly = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] }); |
| 569 | const readOnlyResponse = yield* approveWith(readOnly.credential); |
| 570 | expect(readOnlyResponse.status).toBe(400); |
| 571 | expect(readOnlyResponse.message).toContain("cannot grant this access"); |
| 572 | const operator = yield* auth.issuePairingCredential({ |
| 573 | scopes: ["orchestration:read", "orchestration:operate"], |
| 574 | }); |
| 575 | const operatorFull = yield* decide(handler, params, { |
| 576 | _tag: "pairing-code", |
| 577 | access: "full-access", |
| 578 | code: operator.credential, |
| 579 | }); |
| 580 | expect(operatorFull.status).toBe(400); |
| 581 | |
| 582 | const readOnlyApproval = yield* decide(handler, params, { |
| 583 | _tag: "pairing-code", |
| 584 | access: "read-only", |
| 585 | code: readOnly.credential, |
| 586 | }); |
| 587 | expect(readOnlyApproval.status).toBe(200); |
| 588 | const readOnlyToken = yield* handler( |
| 589 | at( |
| 590 | "/oauth/mcp/token", |
| 591 | form({ |
| 592 | grant_type: "authorization_code", |
| 593 | code: new URL(readOnlyApproval.redirectTo!).searchParams.get("code")!, |
| 594 | redirect_uri: params.redirect_uri, |
| 595 | client_id: clientId, |
| 596 | code_verifier: verifier, |
| 597 | resource: `${ORIGIN}/mcp`, |
| 598 | }), |
| 599 | ), |
| 600 | ).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>)); |
| 601 | expect(readOnlyToken.scope).toBe("orchestration:read"); |
| 602 | const readOnlyClient = yield* auth.authenticateMcpClient( |
| 603 | HttpServerRequest.fromWeb( |
| 604 | at("/mcp", { headers: { authorization: `Bearer ${readOnlyToken.access_token}` } }), |
| 605 | ), |
| 606 | ); |
| 607 | expect(readOnlyClient.access).toBe("read-only"); |
| 608 | }), |
| 609 | ), |
| 610 | ); |
| 611 | |
| 612 | it.live("a code minted with an access level's scopes approves that access", () => |
| 613 | withRoutes((handler, auth) => |
| 614 | Effect.gen(function* () { |
| 615 | const params = authorizeParams(yield* registeredClientId(handler)); |
| 616 | for (const access of AuthMcpClientAccess.literals) { |
| 617 | const code = yield* auth.issuePairingCredential({ scopes: [...mcpClientScopes(access)] }); |
| 618 | const approval = yield* decide(handler, params, { |
| 619 | _tag: "pairing-code", |
| 620 | access, |
| 621 | code: code.credential, |
| 622 | }); |
| 623 | expect(approval.status, access).toBe(200); |
| 624 | } |
| 625 | }), |
| 626 | ), |
| 627 | ); |
| 628 | |
| 629 | it.live("an app approval code approves only an app sign-in, at its own level", () => |
| 630 | withRoutes((handler, auth) => |
| 631 | Effect.gen(function* () { |
| 632 | const clientId = yield* registeredClientId(handler); |
| 633 | const params = authorizeParams(clientId); |
| 634 | const issued = yield* auth.issuePairingCredential({ access: "approval-required" }); |
| 635 | expect(issued.access).toBe("approval-required"); |
| 636 | const code = issued.credential; |
| 637 | expect(code).toMatch(/^SUPERVISED-[2-9A-HJ-NP-Z]{12}$/); |
| 638 | |
| 639 | // Signing in a browser, a token exchange and linking all refuse it and leave it unspent. |
| 640 | const browser = yield* handler( |
| 641 | at("/api/auth/browser-session", { |
| 642 | method: "POST", |
| 643 | headers: { "content-type": "application/json" }, |
| 644 | body: encodeJson({ credential: code }), |
| 645 | }), |
| 646 | ); |
| 647 | expect(browser.status).toBe(401); |
| 648 | const exchanged = yield* auth |
| 649 | .exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "bot" }) |
| 650 | .pipe(Effect.flip); |
| 651 | expect(exchanged._tag).toBe("ServerAuthInvalidCredentialError"); |
| 652 | const peer = yield* handler( |
| 653 | at("/oauth/mcp/register", { |
| 654 | method: "POST", |
| 655 | headers: { "content-type": "application/json" }, |
| 656 | body: encodeJson({ |
| 657 | client_name: "Studio", |
| 658 | software_id: MCP_PEER_LINK_SOFTWARE_ID, |
| 659 | redirect_uris: [REDIRECT], |
| 660 | }), |
| 661 | }), |
| 662 | ).pipe(Effect.flatMap(json<{ client_id: string }>)); |
| 663 | const linked = yield* decide(handler, authorizeParams(peer.client_id), { |
| 664 | _tag: "pairing-code", |
| 665 | access: "approval-required", |
| 666 | code, |
| 667 | }); |
| 668 | expect(linked.status).toBe(400); |
| 669 | |
| 670 | // Supervised and Auto share scopes, so only the code's own level may spend it. |
| 671 | const otherLevel = yield* decide(handler, params, { |
| 672 | _tag: "pairing-code", |
| 673 | access: "auto", |
| 674 | code, |
| 675 | }); |
| 676 | expect(otherLevel.status).toBe(400); |
| 677 | |
| 678 | const approved = yield* decide(handler, params, { |
| 679 | _tag: "pairing-code", |
| 680 | access: "approval-required", |
| 681 | code: code.toLowerCase(), |
| 682 | }); |
| 683 | expect(approved.status).toBe(200); |
| 684 | const token = yield* handler( |
| 685 | at( |
| 686 | "/oauth/mcp/token", |
| 687 | form({ |
| 688 | grant_type: "authorization_code", |
| 689 | code: new URL(approved.redirectTo!).searchParams.get("code")!, |
| 690 | redirect_uri: params.redirect_uri, |
| 691 | client_id: clientId, |
| 692 | code_verifier: verifier, |
| 693 | }), |
| 694 | ), |
| 695 | ).pipe(Effect.flatMap(json<{ access_token: string }>)); |
| 696 | const signedIn = yield* auth.authenticateMcpClient( |
| 697 | HttpServerRequest.fromWeb( |
| 698 | at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }), |
| 699 | ), |
| 700 | ); |
| 701 | expect(signedIn.access).toBe("approval-required"); |
| 702 | expect( |
| 703 | (yield* decide(handler, params, { |
| 704 | _tag: "pairing-code", |
| 705 | access: "approval-required", |
| 706 | code, |
| 707 | })).status, |
| 708 | ).toBe(400); |
| 709 | }), |
| 710 | ), |
| 711 | ); |
| 712 | |
| 713 | it.effect( |
| 714 | "sends an app sign-in on the linked tunnel to the hosted app, and a link to its own page", |
| 715 | () => |
| 716 | Effect.gen(function* () { |
| 717 | const handoff = (tunnelHostname: string, peerLink = false) => |
| 718 | withRoutes( |
| 719 | (handler) => |
| 720 | Effect.gen(function* () { |
| 721 | const registered = yield* handler( |
| 722 | at("/oauth/mcp/register", { |
| 723 | method: "POST", |
| 724 | headers: { "content-type": "application/json" }, |
| 725 | body: encodeJson({ |
| 726 | client_name: "Agent", |
| 727 | redirect_uris: [REDIRECT], |
| 728 | token_endpoint_auth_method: "none", |
| 729 | ...(peerLink ? { software_id: MCP_PEER_LINK_SOFTWARE_ID } : {}), |
| 730 | }), |
| 731 | }), |
| 732 | ).pipe(Effect.flatMap(json<{ client_id: string }>)); |
| 733 | const query = new URLSearchParams( |
| 734 | authorizeParams(registered.client_id, "http://localhost:51234/callback"), |
| 735 | ); |
| 736 | const response = yield* handler(at(`/oauth/mcp/authorize?${query}`)); |
| 737 | return { location: response.headers.get("location")!, query: query.toString() }; |
| 738 | }), |
| 739 | { ...notLinked, linked: true, cloudUserId: "user_1", tunnelHostname }, |
| 740 | ); |
| 741 | |
| 742 | const onTunnel = yield* handoff("box.example.ts.net"); |
| 743 | const hosted = new URL(onTunnel.location); |
| 744 | expect(`${hosted.origin}${hosted.pathname}`).toBe("https://app.t3.codes/approve-agent"); |
| 745 | expect(hosted.searchParams.get("environment")).toEqual(expect.any(String)); |
| 746 | hosted.searchParams.delete("environment"); |
| 747 | expect(hosted.searchParams.toString()).toBe(onTunnel.query); |
| 748 | |
| 749 | const elsewhere = yield* handoff("other.t3coderelay.com"); |
| 750 | expect(elsewhere.location).toBe(`/connect-agent?${elsewhere.query}`); |
| 751 | const peerLink = yield* handoff("box.example.ts.net", true); |
| 752 | expect(peerLink.location).toBe(`/connect-agent?${peerLink.query}`); |
| 753 | }), |
| 754 | ); |
| 755 | |
| 756 | it.live("one-click approves only access the browser session holds the scopes for", () => |
| 757 | withRoutes((handler, auth) => |
| 758 | Effect.gen(function* () { |
| 759 | const clientId = yield* registeredClientId(handler); |
| 760 | const params = authorizeParams(clientId); |
| 761 | const browserCookie = (scopes: NonNullable<AuthCreatePairingCredentialInput["scopes"]>) => |
| 762 | Effect.gen(function* () { |
| 763 | const pairing = yield* auth.issuePairingCredential({ scopes }); |
| 764 | const response = yield* handler( |
| 765 | at("/api/auth/browser-session", { |
| 766 | method: "POST", |
| 767 | headers: { "content-type": "application/json" }, |
| 768 | body: encodeJson({ credential: pairing.credential }), |
| 769 | }), |
| 770 | ); |
| 771 | return response.headers.getSetCookie()[0]!.split(";", 1)[0]!; |
| 772 | }); |
| 773 | const details = (cookie: string) => |
| 774 | handler(postJson("/oauth/mcp/approval", params, cookie)).pipe( |
| 775 | Effect.flatMap(json<{ csrfToken?: string; oneClickAccess?: ReadonlyArray<string> }>), |
| 776 | ); |
| 777 | |
| 778 | const admin = yield* browserCookie([...AuthStandardClientScopes]); |
| 779 | const adminDetails = yield* details(admin); |
| 780 | expect(adminDetails.csrfToken).toEqual(expect.any(String)); |
| 781 | expect(adminDetails.oneClickAccess).toEqual([ |
| 782 | "read-only", |
| 783 | "approval-required", |
| 784 | "auto-accept-edits", |
| 785 | "auto", |
| 786 | "full-access", |
| 787 | ]); |
| 788 | const oneClick = yield* decide( |
| 789 | handler, |
| 790 | params, |
| 791 | { _tag: "browser-session", access: "auto", csrfToken: adminDetails.csrfToken! }, |
| 792 | admin, |
| 793 | ); |
| 794 | expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String)); |
| 795 | |
| 796 | const accessOnly = yield* browserCookie(["access:read", "access:write"]); |
| 797 | expect((yield* details(accessOnly)).csrfToken).toBeUndefined(); |
| 798 | const forged = yield* decide( |
| 799 | handler, |
| 800 | params, |
| 801 | { _tag: "browser-session", access: "auto", csrfToken: "forged" }, |
| 802 | accessOnly, |
| 803 | ); |
| 804 | expect(forged.status).toBe(400); |
| 805 | expect(forged.message).toContain("Enter a pairing code instead"); |
| 806 | |
| 807 | const reader = yield* browserCookie(["access:write", "orchestration:read"]); |
| 808 | const readerDetails = yield* details(reader); |
| 809 | expect(readerDetails.csrfToken).toEqual(expect.any(String)); |
| 810 | expect(readerDetails.oneClickAccess).toEqual(["read-only"]); |
| 811 | const tooBroad = yield* decide( |
| 812 | handler, |
| 813 | params, |
| 814 | { _tag: "browser-session", access: "auto", csrfToken: readerDetails.csrfToken! }, |
| 815 | reader, |
| 816 | ); |
| 817 | expect(tooBroad.status).toBe(400); |
| 818 | const readOnly = yield* decide( |
| 819 | handler, |
| 820 | params, |
| 821 | { _tag: "browser-session", access: "read-only", csrfToken: readerDetails.csrfToken! }, |
| 822 | reader, |
| 823 | ); |
| 824 | expect(new URL(readOnly.redirectTo!).searchParams.get("code")).toEqual(expect.any(String)); |
| 825 | |
| 826 | // The hosted app approves with the owner's T3 Connect session, which sends no cookie. |
| 827 | const connect = `Bearer ${(yield* auth.issueSession({ scopes: [...AuthStandardClientScopes] })).token}`; |
| 828 | const connectDetails = yield* details(connect); |
| 829 | expect(connectDetails.oneClickAccess).toContain("full-access"); |
| 830 | const viaConnect = yield* decide( |
| 831 | handler, |
| 832 | params, |
| 833 | { _tag: "browser-session", access: "auto", csrfToken: connectDetails.csrfToken! }, |
| 834 | connect, |
| 835 | ); |
| 836 | expect(new URL(viaConnect.redirectTo!).searchParams.get("code")).toEqual(expect.any(String)); |
| 837 | |
| 838 | // The hosted app may load and decide with two credentials minted for the same browser key. |
| 839 | const key = makeDpopKey(); |
| 840 | const dpopSession = (thumbprint: string) => |
| 841 | auth.issuePairingCredential({ scopes: [...AuthStandardClientScopes] }).pipe( |
| 842 | Effect.flatMap((pairing) => |
| 843 | auth.exchangeBootstrapCredentialForAccessToken( |
| 844 | pairing.credential, |
| 845 | undefined, |
| 846 | { deviceType: "desktop" }, |
| 847 | { proofKeyThumbprint: thumbprint }, |
| 848 | ), |
| 849 | ), |
| 850 | Effect.map((exchanged) => exchanged.access_token), |
| 851 | ); |
| 852 | const iat = Math.floor((yield* Clock.currentTimeMillis) / 1_000); |
| 853 | const dpopHeaders = (signer: typeof key, token: string, path: string) => ({ |
| 854 | authorization: `DPoP ${token}`, |
| 855 | dpop: signer.sign({ method: "POST", url: `${ORIGIN}${path}`, token, iat }), |
| 856 | }); |
| 857 | const loadedWith = yield* dpopSession(key.thumbprint); |
| 858 | const loaded = yield* handler( |
| 859 | postJson( |
| 860 | "/oauth/mcp/approval", |
| 861 | params, |
| 862 | dpopHeaders(key, loadedWith, "/oauth/mcp/approval"), |
| 863 | ), |
| 864 | ).pipe(Effect.flatMap(json<{ csrfToken?: string }>)); |
| 865 | const renewed = yield* dpopSession(key.thumbprint); |
| 866 | const sameKey = yield* decide( |
| 867 | handler, |
| 868 | params, |
| 869 | { _tag: "browser-session", access: "auto", csrfToken: loaded.csrfToken! }, |
| 870 | dpopHeaders(key, renewed, "/oauth/mcp/decision"), |
| 871 | ); |
| 872 | expect(new URL(sameKey.redirectTo!).searchParams.get("code")).toEqual(expect.any(String)); |
| 873 | const otherKey = makeDpopKey(); |
| 874 | const elsewhere = yield* decide( |
| 875 | handler, |
| 876 | params, |
| 877 | { _tag: "browser-session", access: "auto", csrfToken: loaded.csrfToken! }, |
| 878 | dpopHeaders(otherKey, yield* dpopSession(otherKey.thumbprint), "/oauth/mcp/decision"), |
| 879 | ); |
| 880 | expect(elsewhere.status).toBe(400); |
| 881 | }), |
| 882 | ), |
| 883 | ); |
| 884 | |
| 885 | it("matches loopback redirects on everything but the port, and https redirects exactly", () => { |
| 886 | const matches = McpOAuth.redirectMatches; |
| 887 | expect(matches("http://localhost/callback", "http://localhost:9/callback")).toBe(true); |
| 888 | expect(matches("http://127.0.0.1:1/callback", "http://127.0.0.1:2/callback")).toBe(true); |
| 889 | expect(matches("http://localhost/callback", "http://127.0.0.1/callback")).toBe(false); |
| 890 | expect(matches("http://localhost/callback", "https://localhost/callback")).toBe(false); |
| 891 | expect(matches("https://bot.example/cb", "https://bot.example/cb")).toBe(true); |
| 892 | expect(matches("https://bot.example/cb", "https://bot.example:8443/cb")).toBe(false); |
| 893 | expect(matches("https://bot.example/cb", "https://bot.example/cb?x=1")).toBe(false); |
| 894 | expect(matches("https://bot.example/cb", "https://evil.example/cb")).toBe(false); |
| 895 | }); |