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 { |
| 2 | authScopeRequiredResponse, |
| 3 | AuthAccessTokenType, |
| 4 | AuthAccessWriteScope, |
| 5 | AuthStandardClientScopes, |
| 6 | AuthGrantScope, |
| 7 | EnvironmentAuthInvalidError, |
| 8 | type EnvironmentAuthInvalidReason, |
| 9 | EnvironmentConnectApprovalPendingError, |
| 10 | EnvironmentHttpApi, |
| 11 | EnvironmentHttpForbiddenError, |
| 12 | EnvironmentInternalError, |
| 13 | type EnvironmentInternalErrorReason, |
| 14 | EnvironmentOperationForbiddenError, |
| 15 | EnvironmentRequestInvalidError, |
| 16 | type EnvironmentRequestInvalidReason, |
| 17 | EnvironmentResourceNotFoundError, |
| 18 | type EnvironmentResourceNotFoundReason, |
| 19 | EnvironmentScopeRequiredError, |
| 20 | EnvironmentAuthenticatedAuth, |
| 21 | EnvironmentAuthenticatedPrincipal, |
| 22 | mcpClientScopes, |
| 23 | } from "@t3tools/contracts"; |
| 24 | import type { AuthEnvironmentScope, DpopFailureReason } from "@t3tools/contracts"; |
| 25 | import { parseOAuthScope } from "@t3tools/shared/oauthScope"; |
| 26 | import { causeErrorTag } from "@t3tools/shared/observability"; |
| 27 | import * as Clock from "effect/Clock"; |
| 28 | import * as DateTime from "effect/DateTime"; |
| 29 | import * as Effect from "effect/Effect"; |
| 30 | import * as Option from "effect/Option"; |
| 31 | import * as Schema from "effect/Schema"; |
| 32 | import * as Layer from "effect/Layer"; |
| 33 | import * as Cookies from "effect/http/Cookies"; |
| 34 | import * as HttpEffect from "effect/http/HttpEffect"; |
| 35 | import { HttpServerRequest, HttpServerResponse } from "effect/http"; |
| 36 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 37 | |
| 38 | import * as EnvironmentAuth from "./EnvironmentAuth.ts"; |
| 39 | import * as SessionStore from "./SessionStore.ts"; |
| 40 | import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts"; |
| 41 | import { deriveAuthClientMetadata } from "./utils.ts"; |
| 42 | import { checkRequestDpopProof } from "./dpop.ts"; |
| 43 | import { requestUrl } from "../requestUrl.ts"; |
| 44 | |
| 45 | const CREDENTIAL_RESPONSE_HEADERS = { |
| 46 | "cache-control": "no-store", |
| 47 | pragma: "no-cache", |
| 48 | } as const; |
| 49 | |
| 50 | const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) => |
| 51 | Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)), |
| 52 | ); |
| 53 | |
| 54 | const appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) => |
| 55 | Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")), |
| 56 | ); |
| 57 | |
| 58 | const appendDpopChallengeOnUnauthorized = |
| 59 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 60 | Effect.fnUntraced(function* (error: EnvironmentAuthInvalidError) { |
| 61 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 62 | const usesDpop = |
| 63 | (request.originalUrl.startsWith("/oauth/token") && request.headers.dpop !== undefined) || |
| 64 | /^DPoP /i.test(request.headers.authorization ?? ""); |
| 65 | if (usesDpop) { |
| 66 | yield* appendDpopChallengeHeader; |
| 67 | } |
| 68 | return yield* error; |
| 69 | }); |
| 70 | |
| 71 | const currentEnvironmentTraceId = Effect.currentParentSpan.pipe( |
| 72 | Effect.map((span) => span.traceId), |
| 73 | Effect.orElseSucceed(() => "unavailable"), |
| 74 | ); |
| 75 | |
| 76 | export const annotateEnvironmentRequest = |
| 77 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 78 | Effect.fnUntraced(function* (endpoint: string) { |
| 79 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 80 | const url = requestUrl(request); |
| 81 | const traceId = yield* currentEnvironmentTraceId; |
| 82 | |
| 83 | yield* Effect.addFinalizer((exit) => |
| 84 | exit._tag === "Failure" |
| 85 | ? Effect.logWarning("environment api request failed", { |
| 86 | endpoint, |
| 87 | traceId, |
| 88 | errorTag: causeErrorTag(exit.cause), |
| 89 | cause: exit.cause, |
| 90 | }) |
| 91 | : Effect.void, |
| 92 | ); |
| 93 | yield* Effect.annotateLogsScoped({ "environment.endpoint": endpoint, traceId }); |
| 94 | yield* Effect.annotateCurrentSpan({ |
| 95 | "environment.endpoint": endpoint, |
| 96 | "http.request.method": request.method, |
| 97 | "url.path": url._tag === "Some" ? url.value.pathname : "unknown", |
| 98 | }); |
| 99 | }); |
| 100 | |
| 101 | export function failEnvironmentAuthInvalid( |
| 102 | reason: EnvironmentAuthInvalidReason, |
| 103 | dpopFailureReason?: DpopFailureReason, |
| 104 | ) { |
| 105 | return currentEnvironmentTraceId.pipe( |
| 106 | Effect.flatMap((traceId) => |
| 107 | Effect.fail( |
| 108 | new EnvironmentAuthInvalidError({ |
| 109 | code: "auth_invalid", |
| 110 | reason, |
| 111 | ...(dpopFailureReason === undefined ? {} : { dpopFailureReason }), |
| 112 | traceId, |
| 113 | }), |
| 114 | ), |
| 115 | ), |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | export function failEnvironmentInvalidRequest(reason: EnvironmentRequestInvalidReason) { |
| 120 | return currentEnvironmentTraceId.pipe( |
| 121 | Effect.flatMap((traceId) => |
| 122 | Effect.fail(new EnvironmentRequestInvalidError({ code: "invalid_request", reason, traceId })), |
| 123 | ), |
| 124 | ); |
| 125 | } |
| 126 | |
| 127 | export function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope) { |
| 128 | return currentEnvironmentTraceId.pipe( |
| 129 | Effect.flatMap((traceId) => |
| 130 | Effect.fail( |
| 131 | new EnvironmentScopeRequiredError({ |
| 132 | code: "insufficient_scope", |
| 133 | ...authScopeRequiredResponse(requiredScope), |
| 134 | traceId, |
| 135 | }), |
| 136 | ), |
| 137 | ), |
| 138 | ); |
| 139 | } |
| 140 | |
| 141 | function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_allowed") { |
| 142 | return currentEnvironmentTraceId.pipe( |
| 143 | Effect.flatMap((traceId) => |
| 144 | Effect.fail( |
| 145 | new EnvironmentOperationForbiddenError({ |
| 146 | code: "operation_forbidden", |
| 147 | reason, |
| 148 | traceId, |
| 149 | }), |
| 150 | ), |
| 151 | ), |
| 152 | ); |
| 153 | } |
| 154 | |
| 155 | export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) { |
| 156 | return currentEnvironmentTraceId.pipe( |
| 157 | Effect.flatMap((traceId) => |
| 158 | Effect.fail(new EnvironmentResourceNotFoundError({ code: "not_found", reason, traceId })), |
| 159 | ), |
| 160 | ); |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * `<img>` and WebSocket cannot set headers, so media routes (device hub, preview stream) |
| 165 | * authenticate the way the `/ws` upgrade does: a cookie for browser sessions, or a short-lived |
| 166 | * `wsTicket` minted over authenticated HTTP for bearer and DPoP clients. |
| 167 | */ |
| 168 | export const authenticateMediaRequest = |
| 169 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 170 | Effect.fnUntraced(function* (requiredScope: AuthEnvironmentScope) { |
| 171 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 172 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 173 | const session = yield* serverAuth.authenticateWebSocketUpgrade(request, "media").pipe( |
| 174 | Effect.catch((error) => |
| 175 | Effect.gen(function* () { |
| 176 | if (EnvironmentAuth.isServerAuthCredentialError(error)) { |
| 177 | return yield* failEnvironmentAuthInvalid( |
| 178 | EnvironmentAuth.serverAuthCredentialReason(error), |
| 179 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 180 | ); |
| 181 | } |
| 182 | return yield* failEnvironmentInternal("internal_error", error); |
| 183 | }), |
| 184 | ), |
| 185 | ); |
| 186 | if (!session.scopes.includes(requiredScope)) { |
| 187 | return yield* failEnvironmentScopeRequired(requiredScope); |
| 188 | } |
| 189 | return session; |
| 190 | }); |
| 191 | |
| 192 | export const failEnvironmentInternal = |
| 193 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 194 | Effect.fnUntraced(function* (reason: EnvironmentInternalErrorReason, error?: unknown) { |
| 195 | const traceId = yield* currentEnvironmentTraceId; |
| 196 | if (error !== undefined) { |
| 197 | yield* Effect.logError("environment api operation failed", { |
| 198 | reason, |
| 199 | traceId, |
| 200 | cause: error, |
| 201 | }); |
| 202 | } |
| 203 | return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId }); |
| 204 | }); |
| 205 | |
| 206 | // Plaintext LAN servers still need the cookie; TLS arrives through a proxy that sets X-Forwarded-Proto. |
| 207 | const sessionCookieOptions = (request: HttpServerRequest.HttpServerRequest) => ({ |
| 208 | httpOnly: true, |
| 209 | path: "/", |
| 210 | sameSite: "lax" as const, |
| 211 | secure: Option.exists(requestUrl(request), (url) => url.protocol === "https:"), |
| 212 | }); |
| 213 | |
| 214 | const appendSessionCookie = ( |
| 215 | request: HttpServerRequest.HttpServerRequest, |
| 216 | cookieName: string, |
| 217 | token: string, |
| 218 | expiresAt: DateTime.DateTime, |
| 219 | ) => |
| 220 | Effect.fromResult( |
| 221 | Cookies.set(Cookies.empty, cookieName, token, { |
| 222 | ...sessionCookieOptions(request), |
| 223 | expires: DateTime.toDate(expiresAt), |
| 224 | }), |
| 225 | ).pipe( |
| 226 | Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")), |
| 227 | Effect.flatMap((cookies) => |
| 228 | HttpEffect.appendPreResponseHandler((_request, response) => |
| 229 | Effect.succeed(HttpServerResponse.mergeCookies(response, cookies)), |
| 230 | ), |
| 231 | ), |
| 232 | ); |
| 233 | |
| 234 | export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* ( |
| 235 | scope: AuthEnvironmentScope, |
| 236 | ) { |
| 237 | const session = yield* EnvironmentAuthenticatedPrincipal; |
| 238 | if (!session.scopes.has(scope)) { |
| 239 | return yield* failEnvironmentScopeRequired(scope); |
| 240 | } |
| 241 | return session; |
| 242 | }); |
| 243 | |
| 244 | export const layerAuthenticatedAuth = Layer.effect( |
| 245 | EnvironmentAuthenticatedAuth, |
| 246 | Effect.gen(function* () { |
| 247 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 248 | return (httpEffect) => |
| 249 | Effect.gen(function* () { |
| 250 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 251 | const startTime = yield* Clock.currentTimeNanos; |
| 252 | const session = yield* serverAuth.authenticateHttpRequest(request).pipe( |
| 253 | Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => |
| 254 | failEnvironmentAuthInvalid( |
| 255 | EnvironmentAuth.serverAuthCredentialReason(error), |
| 256 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 257 | ), |
| 258 | ), |
| 259 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 260 | failEnvironmentInternal("internal_error", error), |
| 261 | ), |
| 262 | ); |
| 263 | const endTime = yield* Clock.currentTimeNanos; |
| 264 | const handler = httpEffect.pipe( |
| 265 | Effect.provideService(EnvironmentAuthenticatedPrincipal, { |
| 266 | ...session, |
| 267 | scopes: new Set(session.scopes), |
| 268 | }), |
| 269 | ); |
| 270 | return yield* session.subject === EnvironmentAuth.CLOUD_CONNECT_SUBJECT |
| 271 | ? traceAuthenticatedRelayRequest(handler, { startTime, endTime }) |
| 272 | : handler; |
| 273 | }).pipe(Effect.catchTags({ EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized })); |
| 274 | }), |
| 275 | ); |
| 276 | |
| 277 | export const layer = HttpApiBuilder.group( |
| 278 | EnvironmentHttpApi, |
| 279 | "auth", |
| 280 | Effect.fnUntraced(function* (handlers) { |
| 281 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 282 | const sessions = yield* SessionStore.SessionStore; |
| 283 | |
| 284 | return handlers |
| 285 | .handle( |
| 286 | "session", |
| 287 | Effect.fn("environment.auth.session")( |
| 288 | function* (args) { |
| 289 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 290 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 291 | const result = yield* serverAuth.getSessionState(request); |
| 292 | const credential = EnvironmentAuth.selectRequestCredential( |
| 293 | request, |
| 294 | sessions.cookieName, |
| 295 | sessions.legacyCookieName, |
| 296 | ); |
| 297 | if ( |
| 298 | credential?.source === "legacy-cookie" && |
| 299 | result.authenticated && |
| 300 | result.sessionMethod === "browser-session-cookie" && |
| 301 | result.expiresAt |
| 302 | ) { |
| 303 | yield* appendSessionCookie( |
| 304 | request, |
| 305 | sessions.cookieName, |
| 306 | credential.token, |
| 307 | result.expiresAt, |
| 308 | ); |
| 309 | yield* appendCredentialResponseHeaders; |
| 310 | } |
| 311 | return result; |
| 312 | }, |
| 313 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 314 | failEnvironmentInternal("internal_error", error), |
| 315 | ), |
| 316 | ), |
| 317 | ) |
| 318 | .handle( |
| 319 | "browserSession", |
| 320 | Effect.fn("environment.auth.browserSession")( |
| 321 | function* (args) { |
| 322 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 323 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 324 | const previousCredential = EnvironmentAuth.selectRequestCredential( |
| 325 | request, |
| 326 | sessions.cookieName, |
| 327 | sessions.legacyCookieName, |
| 328 | ); |
| 329 | const result = yield* serverAuth.createBrowserSession( |
| 330 | args.payload.credential, |
| 331 | deriveAuthClientMetadata({ request }), |
| 332 | previousCredential && |
| 333 | EnvironmentAuth.isBrowserCookieCredential(previousCredential.source) |
| 334 | ? previousCredential.token |
| 335 | : undefined, |
| 336 | ); |
| 337 | const cookieName = result.cookieName ?? sessions.cookieName; |
| 338 | const selectedCookie = yield* Effect.fromResult( |
| 339 | Cookies.set(Cookies.empty, cookieName, result.sessionToken, { |
| 340 | ...sessionCookieOptions(request), |
| 341 | expires: DateTime.toDate(result.response.expiresAt), |
| 342 | }), |
| 343 | ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed"))); |
| 344 | const sessionCookies = result.expireNormalCookie |
| 345 | ? yield* Effect.fromResult( |
| 346 | Cookies.expireCookie( |
| 347 | selectedCookie, |
| 348 | sessions.cookieName, |
| 349 | sessionCookieOptions(request), |
| 350 | ), |
| 351 | ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed"))) |
| 352 | : selectedCookie; |
| 353 | |
| 354 | yield* HttpEffect.appendPreResponseHandler((_request, response) => |
| 355 | Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)), |
| 356 | ); |
| 357 | yield* appendCredentialResponseHeaders; |
| 358 | return result.response; |
| 359 | }, |
| 360 | Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => |
| 361 | failEnvironmentAuthInvalid( |
| 362 | EnvironmentAuth.serverAuthCredentialReason(error), |
| 363 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 364 | ), |
| 365 | ), |
| 366 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 367 | failEnvironmentInternal("browser_session_issuance_failed", error), |
| 368 | ), |
| 369 | ), |
| 370 | ) |
| 371 | .handle( |
| 372 | "token", |
| 373 | Effect.fn("environment.auth.token")( |
| 374 | function* (args) { |
| 375 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 376 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 377 | const requestedScopes = |
| 378 | args.payload.scope === undefined |
| 379 | ? undefined |
| 380 | : (parseOAuthScope(args.payload.scope)?.filter(Schema.is(AuthGrantScope)) ?? null); |
| 381 | if (requestedScopes === null || requestedScopes?.length === 0) { |
| 382 | return yield* failEnvironmentInvalidRequest("invalid_scope"); |
| 383 | } |
| 384 | // Bootstrap exchanges leave the proof unrecorded because its key is not always trusted. |
| 385 | const proof = args.headers.dpop |
| 386 | ? yield* checkRequestDpopProof({ request }).pipe( |
| 387 | Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => |
| 388 | appendDpopChallengeHeader.pipe( |
| 389 | Effect.andThen( |
| 390 | failEnvironmentAuthInvalid( |
| 391 | "invalid_credential", |
| 392 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 393 | ), |
| 394 | ), |
| 395 | ), |
| 396 | ), |
| 397 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 398 | failEnvironmentInternal("access_token_issuance_failed", error), |
| 399 | ), |
| 400 | ) |
| 401 | : undefined; |
| 402 | yield* appendCredentialResponseHeaders; |
| 403 | if (args.payload.subject_token_type === AuthAccessTokenType) { |
| 404 | if (requestedScopes !== undefined) { |
| 405 | return yield* failEnvironmentInvalidRequest("invalid_scope"); |
| 406 | } |
| 407 | if (!proof) { |
| 408 | yield* appendDpopChallengeHeader; |
| 409 | return yield* failEnvironmentAuthInvalid("invalid_credential"); |
| 410 | } |
| 411 | return yield* serverAuth.renewAccessToken( |
| 412 | args.payload.subject_token, |
| 413 | proof.thumbprint, |
| 414 | proof.consume, |
| 415 | ); |
| 416 | } |
| 417 | return yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 418 | args.payload.subject_token, |
| 419 | requestedScopes, |
| 420 | deriveAuthClientMetadata({ |
| 421 | request, |
| 422 | presented: { |
| 423 | ...(args.payload.client_label ? { label: args.payload.client_label } : {}), |
| 424 | ...(args.payload.client_device_type |
| 425 | ? { deviceType: args.payload.client_device_type } |
| 426 | : {}), |
| 427 | ...(args.payload.client_os ? { os: args.payload.client_os } : {}), |
| 428 | }, |
| 429 | }), |
| 430 | proof ? { proofKeyThumbprint: proof.thumbprint } : undefined, |
| 431 | ); |
| 432 | }, |
| 433 | traceRelayRequest, |
| 434 | Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => |
| 435 | failEnvironmentAuthInvalid( |
| 436 | EnvironmentAuth.serverAuthCredentialReason(error), |
| 437 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 438 | ), |
| 439 | ), |
| 440 | Effect.catchTags({ |
| 441 | ServerAuthConnectApprovalPendingError: () => |
| 442 | currentEnvironmentTraceId.pipe( |
| 443 | Effect.flatMap((traceId) => |
| 444 | Effect.fail( |
| 445 | new EnvironmentConnectApprovalPendingError({ |
| 446 | code: "connect_approval_pending", |
| 447 | traceId, |
| 448 | }), |
| 449 | ), |
| 450 | ), |
| 451 | ), |
| 452 | }), |
| 453 | Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) => |
| 454 | failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)), |
| 455 | ), |
| 456 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 457 | failEnvironmentInternal("access_token_issuance_failed", error), |
| 458 | ), |
| 459 | ), |
| 460 | ) |
| 461 | .handle( |
| 462 | "webSocketTicket", |
| 463 | Effect.fn("environment.auth.webSocketTicket")( |
| 464 | function* (args) { |
| 465 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 466 | const session = yield* EnvironmentAuthenticatedPrincipal; |
| 467 | yield* appendCredentialResponseHeaders; |
| 468 | return yield* serverAuth.issueWebSocketTicket(session); |
| 469 | }, |
| 470 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 471 | failEnvironmentInternal("websocket_ticket_issuance_failed", error), |
| 472 | ), |
| 473 | ), |
| 474 | ) |
| 475 | .handle( |
| 476 | "webSocketTicketFor", |
| 477 | Effect.fn("environment.auth.webSocketTicketFor")( |
| 478 | function* (args) { |
| 479 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 480 | const session = yield* EnvironmentAuthenticatedPrincipal; |
| 481 | yield* appendCredentialResponseHeaders; |
| 482 | return yield* serverAuth.issueWebSocketTicket(session, { use: args.params.use }); |
| 483 | }, |
| 484 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 485 | failEnvironmentInternal("websocket_ticket_issuance_failed", error), |
| 486 | ), |
| 487 | ), |
| 488 | ) |
| 489 | .handle( |
| 490 | "pairingCredential", |
| 491 | Effect.fn("environment.auth.pairingCredential")( |
| 492 | function* (args) { |
| 493 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 494 | const session = yield* requireEnvironmentScope(AuthAccessWriteScope); |
| 495 | const delegatedScopes = args.payload.access |
| 496 | ? mcpClientScopes(args.payload.access) |
| 497 | : (args.payload.scopes ?? AuthStandardClientScopes); |
| 498 | if ( |
| 499 | delegatedScopes.length === 0 || |
| 500 | new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length |
| 501 | ) { |
| 502 | return yield* failEnvironmentInvalidRequest("invalid_scope"); |
| 503 | } |
| 504 | for (const delegatedScope of delegatedScopes) { |
| 505 | if (!session.scopes.has(delegatedScope)) { |
| 506 | return yield* failEnvironmentScopeRequired(delegatedScope); |
| 507 | } |
| 508 | } |
| 509 | return yield* serverAuth.issuePairingCredential(args.payload); |
| 510 | }, |
| 511 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 512 | failEnvironmentInternal("pairing_credential_issuance_failed", error), |
| 513 | ), |
| 514 | Effect.catchTags({ |
| 515 | ManagedPolicyRefusedError: (error) => |
| 516 | Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })), |
| 517 | }), |
| 518 | ), |
| 519 | ) |
| 520 | .handle( |
| 521 | "revokePairingLink", |
| 522 | Effect.fn("environment.auth.revokePairingLink")( |
| 523 | function* (args) { |
| 524 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 525 | yield* requireEnvironmentScope(AuthAccessWriteScope); |
| 526 | const revoked = yield* serverAuth.revokePairingLink(args.payload.id); |
| 527 | return { revoked }; |
| 528 | }, |
| 529 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 530 | failEnvironmentInternal("pairing_link_revoke_failed", error), |
| 531 | ), |
| 532 | ), |
| 533 | ) |
| 534 | .handle( |
| 535 | "revokeClient", |
| 536 | Effect.fn("environment.auth.revokeClient")( |
| 537 | function* (args) { |
| 538 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 539 | const session = yield* requireEnvironmentScope(AuthAccessWriteScope); |
| 540 | const revoked = yield* serverAuth.revokeClientSession( |
| 541 | session.sessionId, |
| 542 | args.payload.sessionId, |
| 543 | ); |
| 544 | return { revoked }; |
| 545 | }, |
| 546 | Effect.catchTags({ |
| 547 | ServerAuthForbiddenOperationError: () => |
| 548 | failEnvironmentOperationForbidden("current_session_revoke_not_allowed"), |
| 549 | }), |
| 550 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 551 | failEnvironmentInternal("client_session_revoke_failed", error), |
| 552 | ), |
| 553 | ), |
| 554 | ) |
| 555 | .handle( |
| 556 | "approveConnectDevice", |
| 557 | Effect.fn("environment.auth.approveConnectDevice")( |
| 558 | function* (args) { |
| 559 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 560 | yield* requireEnvironmentScope(AuthAccessWriteScope); |
| 561 | const approved = yield* serverAuth.approveConnectDevice(args.payload.pairingLinkId); |
| 562 | return { approved }; |
| 563 | }, |
| 564 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 565 | failEnvironmentInternal("connect_device_approve_failed", error), |
| 566 | ), |
| 567 | ), |
| 568 | ) |
| 569 | .handle( |
| 570 | "revokeConnectDevice", |
| 571 | Effect.fn("environment.auth.revokeConnectDevice")( |
| 572 | function* (args) { |
| 573 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 574 | yield* requireEnvironmentScope(AuthAccessWriteScope); |
| 575 | const revoked = yield* serverAuth.revokeConnectDevice(args.payload.proofKeyThumbprint); |
| 576 | return { revoked }; |
| 577 | }, |
| 578 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 579 | failEnvironmentInternal("connect_device_revoke_failed", error), |
| 580 | ), |
| 581 | ), |
| 582 | ) |
| 583 | .handle( |
| 584 | "revokeOtherClients", |
| 585 | Effect.fn("environment.auth.revokeOtherClients")( |
| 586 | function* (args) { |
| 587 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 588 | const session = yield* requireEnvironmentScope(AuthAccessWriteScope); |
| 589 | const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId); |
| 590 | return { revokedCount }; |
| 591 | }, |
| 592 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 593 | failEnvironmentInternal("client_session_revoke_failed", error), |
| 594 | ), |
| 595 | ), |
| 596 | ); |
| 597 | }), |
| 598 | ); |