The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { translatableDetail } from "../errors/translatable.ts"; |
| 3 | import { |
| 4 | AuthAccessTokenType, |
| 5 | connectDeviceVerificationCode, |
| 6 | type ClientConnectionMethod, |
| 7 | EnvironmentId, |
| 8 | type ExecutionEnvironmentDescriptor, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay"; |
| 11 | import * as KeyedLock from "@t3tools/shared/KeyedLock"; |
| 12 | import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; |
| 13 | import { |
| 14 | exchangeRemoteDpopAccessToken, |
| 15 | type RemoteEnvironmentAuthError, |
| 16 | resolveRemoteDpopWebSocketConnectionUrl, |
| 17 | resolveRemoteWebSocketConnectionUrl, |
| 18 | } from "./remote.ts"; |
| 19 | import { |
| 20 | credentialMissingError, |
| 21 | environmentMismatchError, |
| 22 | mapManagedRelayError, |
| 23 | mapRemoteDpopEnvironmentError, |
| 24 | mapRemoteEnvironmentError, |
| 25 | } from "../connection/errors.ts"; |
| 26 | import { DpopConnectionCredential } from "../connection/catalog.ts"; |
| 27 | import * as ConnectionCredentialStore from "../connection/credentialStore.ts"; |
| 28 | import { |
| 29 | ConnectionBlockedError, |
| 30 | ConnectionTransientError, |
| 31 | type ConnectionAttemptError, |
| 32 | type DirectDpopConnection, |
| 33 | } from "../connection/model.ts"; |
| 34 | import { isNearbyAddress } from "../connection/routes.ts"; |
| 35 | import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts"; |
| 36 | import { environmentEndpointUrl } from "../environment/endpoint.ts"; |
| 37 | import * as ClientCapabilities from "../platform/capabilities.ts"; |
| 38 | import * as ManagedRelay from "../relay/managedRelay.ts"; |
| 39 | import * as TokenStore from "./tokenStore.ts"; |
| 40 | import * as Clock from "effect/Clock"; |
| 41 | import * as Context from "effect/Context"; |
| 42 | import * as Effect from "effect/Effect"; |
| 43 | import * as Fiber from "effect/Fiber"; |
| 44 | import * as Layer from "effect/Layer"; |
| 45 | import * as Option from "effect/Option"; |
| 46 | import * as Result from "effect/Result"; |
| 47 | import * as Scope from "effect/Scope"; |
| 48 | import * as Semaphore from "effect/Semaphore"; |
| 49 | import * as HttpClient from "effect/http/HttpClient"; |
| 50 | |
| 51 | import { |
| 52 | DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS, |
| 53 | type PreparedHttpAuthorization, |
| 54 | } from "../connection/model.ts"; |
| 55 | |
| 56 | export interface AuthorizedRemoteEnvironment { |
| 57 | readonly environmentId: EnvironmentId; |
| 58 | readonly label: string; |
| 59 | readonly httpBaseUrl: string; |
| 60 | readonly socketUrl: string; |
| 61 | readonly httpAuthorization: PreparedHttpAuthorization; |
| 62 | readonly descriptor?: ExecutionEnvironmentDescriptor; |
| 63 | } |
| 64 | |
| 65 | export interface AuthorizedRemoteHttpEnvironment { |
| 66 | readonly environmentId: EnvironmentId; |
| 67 | readonly label: string; |
| 68 | readonly httpBaseUrl: string; |
| 69 | readonly httpAuthorization: Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>; |
| 70 | } |
| 71 | |
| 72 | export class RemoteEnvironmentAuthorization extends Context.Service< |
| 73 | RemoteEnvironmentAuthorization, |
| 74 | { |
| 75 | readonly authorizeBearer: (input: { |
| 76 | readonly expectedEnvironmentId: EnvironmentId; |
| 77 | readonly httpBaseUrl: string; |
| 78 | readonly wsBaseUrl: string; |
| 79 | readonly bearerToken: string; |
| 80 | readonly connectionMethod: ClientConnectionMethod; |
| 81 | }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>; |
| 82 | readonly authorizeDpop: (input: { |
| 83 | readonly expectedEnvironmentId: EnvironmentId; |
| 84 | /** |
| 85 | * The access token is not bound to an origin, and each proof is minted |
| 86 | * for the URL it signs, so a token from the relay also works on the |
| 87 | * environment's LAN or tailnet address. |
| 88 | */ |
| 89 | readonly directEndpoint?: { readonly httpBaseUrl: string; readonly wsBaseUrl: string }; |
| 90 | }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>; |
| 91 | /** A saved address paired with this device's DPoP key, which renews with the host itself. */ |
| 92 | readonly authorizeDirectDpop: (input: { |
| 93 | readonly expectedEnvironmentId: EnvironmentId; |
| 94 | readonly connectionId: string; |
| 95 | readonly httpBaseUrl: string; |
| 96 | readonly wsBaseUrl: string; |
| 97 | }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>; |
| 98 | readonly authorizeDirectDpopHttp: ( |
| 99 | connection: DirectDpopConnection, |
| 100 | rejectedAccessToken?: string, |
| 101 | ) => Effect.Effect< |
| 102 | Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>, |
| 103 | ConnectionAttemptError |
| 104 | >; |
| 105 | readonly authorizeDpopHttp: (input: { |
| 106 | readonly expectedEnvironmentId: EnvironmentId; |
| 107 | readonly rejectedAccessToken?: string; |
| 108 | }) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>; |
| 109 | /** |
| 110 | * Lets the next direct authorization of this address skip its own descriptor |
| 111 | * read. Kept only where the address reaches the same machine on every network. |
| 112 | */ |
| 113 | readonly rememberCheckedDescriptor: ( |
| 114 | httpBaseUrl: string, |
| 115 | descriptor: Option.Option<ExecutionEnvironmentDescriptor>, |
| 116 | keepsItsHost: boolean, |
| 117 | ) => Effect.Effect<void>; |
| 118 | /** |
| 119 | * Renews a live socket's token before it expires, so the server moves the |
| 120 | * socket to the new session instead of closing it. Runs until interrupted. |
| 121 | */ |
| 122 | readonly renewDpopBeforeExpiry: (input: { |
| 123 | readonly expectedEnvironmentId: EnvironmentId; |
| 124 | readonly expiresAtEpochMs: number; |
| 125 | readonly directConnection?: DirectDpopConnection; |
| 126 | }) => Effect.Effect<void, ConnectionAttemptError>; |
| 127 | } |
| 128 | >()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {} |
| 129 | |
| 130 | const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000; |
| 131 | const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000; |
| 132 | const CHECKED_DESCRIPTOR_TTL_NANOS = 5_000_000_000n; |
| 133 | // A loopback or LAN host answers well inside this, so a dead one frees its attempt sooner. |
| 134 | const NEARBY_DESCRIPTOR_TIMEOUT_MS = 3_000; |
| 135 | |
| 136 | /** A token with the descriptor its mint read. A cached token has none. */ |
| 137 | interface IssuedDpopToken { |
| 138 | readonly token: TokenStore.RemoteDpopAccessToken; |
| 139 | readonly descriptor?: ExecutionEnvironmentDescriptor; |
| 140 | } |
| 141 | |
| 142 | function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) { |
| 143 | return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError" |
| 144 | ? error |
| 145 | : mapRemoteDpopEnvironmentError(error); |
| 146 | } |
| 147 | |
| 148 | function approvalPendingError(hostLabel: string, thumbprint: string, traceId: string) { |
| 149 | const verificationCode = connectDeviceVerificationCode(thumbprint); |
| 150 | return new ConnectionTransientError({ |
| 151 | reason: "approval-pending", |
| 152 | ...translatableDetail( |
| 153 | msg("Approve this device on {host}. It shows code {verificationCode}.", { |
| 154 | host: hostLabel, |
| 155 | verificationCode, |
| 156 | }), |
| 157 | ), |
| 158 | verificationCode, |
| 159 | traceId, |
| 160 | hop: "server", |
| 161 | via: "relay", |
| 162 | failureCause: "approval_pending", |
| 163 | }); |
| 164 | } |
| 165 | |
| 166 | const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* ( |
| 167 | httpBaseUrl: string, |
| 168 | connectionMethod: ClientConnectionMethod, |
| 169 | timeoutMs?: number, |
| 170 | ) { |
| 171 | return yield* fetchRemoteEnvironmentDescriptor({ |
| 172 | httpBaseUrl, |
| 173 | ...(timeoutMs === undefined ? {} : { timeoutMs }), |
| 174 | }).pipe(Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod))); |
| 175 | }); |
| 176 | |
| 177 | export const make = Effect.gen(function* () { |
| 178 | const serviceScope = yield* Scope.Scope; |
| 179 | const signer = yield* ManagedRelay.ManagedRelayDpopSigner; |
| 180 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 181 | const cloudSession = yield* ClientCapabilities.CloudSession; |
| 182 | const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity; |
| 183 | const presentation = yield* ClientCapabilities.ClientPresentation; |
| 184 | const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore; |
| 185 | const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore; |
| 186 | const httpClient = yield* HttpClient.HttpClient; |
| 187 | const tokenLock = yield* Semaphore.make(1); |
| 188 | const directTokenLocks = yield* KeyedLock.make<string>(); |
| 189 | const tokenOwners = new Map< |
| 190 | EnvironmentId, |
| 191 | { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity } |
| 192 | >(); |
| 193 | const pendingTokens = new Map< |
| 194 | EnvironmentId, |
| 195 | { |
| 196 | readonly id: object; |
| 197 | readonly identity: ClientCapabilities.CloudSessionIdentity; |
| 198 | readonly thumbprint: string; |
| 199 | readonly issued: Effect.Effect<IssuedDpopToken, ConnectionAttemptError>; |
| 200 | } |
| 201 | >(); |
| 202 | |
| 203 | // A route or host check hands its descriptor to the connect it leads to, once, |
| 204 | // so the connect skips a round trip. Only over HTTPS or loopback: any other |
| 205 | // plain http address can belong to another machine after a network change. |
| 206 | const checkedDescriptors = new Map< |
| 207 | string, |
| 208 | { readonly descriptor: ExecutionEnvironmentDescriptor; readonly at: bigint } |
| 209 | >(); |
| 210 | |
| 211 | /** |
| 212 | * A saved LAN address can belong to another machine on a different network. |
| 213 | */ |
| 214 | const verifyDirectEndpoint = Effect.fn("clientRuntime.connection.remote.verifyDirectEndpoint")( |
| 215 | function* (input: { |
| 216 | readonly expectedEnvironmentId: EnvironmentId; |
| 217 | readonly httpBaseUrl: string; |
| 218 | readonly connectionMethod: ClientConnectionMethod; |
| 219 | }) { |
| 220 | const checked = checkedDescriptors.get(input.httpBaseUrl); |
| 221 | checkedDescriptors.delete(input.httpBaseUrl); |
| 222 | // A remembered mismatch still reads again, so a host that answers for the |
| 223 | // right environment a moment later is not blocked. |
| 224 | const descriptor = |
| 225 | checked !== undefined && |
| 226 | checked.descriptor.environmentId === input.expectedEnvironmentId && |
| 227 | (yield* Clock.monotonicTimeNanos) - checked.at <= CHECKED_DESCRIPTOR_TTL_NANOS |
| 228 | ? checked.descriptor |
| 229 | : yield* fetchDescriptor( |
| 230 | input.httpBaseUrl, |
| 231 | input.connectionMethod, |
| 232 | // An SSH forward listens on loopback but reaches a remote host. |
| 233 | input.connectionMethod === "direct" && isNearbyAddress(input.httpBaseUrl) |
| 234 | ? NEARBY_DESCRIPTOR_TIMEOUT_MS |
| 235 | : undefined, |
| 236 | ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)); |
| 237 | if (descriptor.environmentId !== input.expectedEnvironmentId) { |
| 238 | return yield* environmentMismatchError({ |
| 239 | expected: input.expectedEnvironmentId, |
| 240 | actual: descriptor.environmentId, |
| 241 | }); |
| 242 | } |
| 243 | return descriptor; |
| 244 | }, |
| 245 | ); |
| 246 | |
| 247 | const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")( |
| 248 | function* (input: { |
| 249 | readonly expectedEnvironmentId: Parameters< |
| 250 | RemoteEnvironmentAuthorization["Service"]["authorizeBearer"] |
| 251 | >[0]["expectedEnvironmentId"]; |
| 252 | readonly httpBaseUrl: string; |
| 253 | readonly wsBaseUrl: string; |
| 254 | readonly bearerToken: string; |
| 255 | readonly connectionMethod: ClientConnectionMethod; |
| 256 | }) { |
| 257 | const descriptor = yield* verifyDirectEndpoint(input); |
| 258 | const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({ |
| 259 | wsBaseUrl: input.wsBaseUrl, |
| 260 | httpBaseUrl: input.httpBaseUrl, |
| 261 | bearerToken: input.bearerToken, |
| 262 | clientMetadata: presentation.metadata, |
| 263 | connectionMethod: input.connectionMethod, |
| 264 | }).pipe( |
| 265 | Effect.mapError(mapRemoteEnvironmentError), |
| 266 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 267 | ); |
| 268 | return { |
| 269 | environmentId: descriptor.environmentId, |
| 270 | label: descriptor.label, |
| 271 | httpBaseUrl: input.httpBaseUrl, |
| 272 | socketUrl, |
| 273 | descriptor, |
| 274 | httpAuthorization: { |
| 275 | _tag: "Bearer" as const, |
| 276 | token: input.bearerToken, |
| 277 | }, |
| 278 | }; |
| 279 | }, |
| 280 | ); |
| 281 | |
| 282 | const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")( |
| 283 | function* ( |
| 284 | token: TokenStore.RemoteDpopAccessToken, |
| 285 | timeoutMs?: number, |
| 286 | endpoint: { readonly httpBaseUrl: string; readonly wsBaseUrl: string } = token.endpoint, |
| 287 | ) { |
| 288 | return yield* resolveRemoteDpopWebSocketConnectionUrl({ |
| 289 | wsBaseUrl: endpoint.wsBaseUrl, |
| 290 | httpBaseUrl: endpoint.httpBaseUrl, |
| 291 | accessToken: token.accessToken, |
| 292 | createProof: (proof) => |
| 293 | signer.createProof(proof).pipe( |
| 294 | Effect.mapError( |
| 295 | () => |
| 296 | new ConnectionBlockedError({ |
| 297 | reason: "configuration", |
| 298 | ...translatableDetail(msg("Could not create the websocket authorization proof.")), |
| 299 | }), |
| 300 | ), |
| 301 | ), |
| 302 | clientMetadata: presentation.metadata, |
| 303 | connectionMethod: "relay", |
| 304 | ...(timeoutMs === undefined ? {} : { timeoutMs }), |
| 305 | }); |
| 306 | }, |
| 307 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 308 | ); |
| 309 | |
| 310 | const sessionChanged = () => |
| 311 | new ConnectionBlockedError({ |
| 312 | reason: "authentication", |
| 313 | ...translatableDetail( |
| 314 | msg("Your cloud sign-in changed. Sign in again to authorize the environment."), |
| 315 | ), |
| 316 | }); |
| 317 | |
| 318 | // A missing identity before the attempt captures one means the cloud session |
| 319 | // is still loading, not a sign-out. Only a captured identity that goes away |
| 320 | // or changes is evidence of one. |
| 321 | const sessionPending = () => |
| 322 | new ConnectionTransientError({ |
| 323 | reason: "session-pending", |
| 324 | ...translatableDetail(msg("Waiting for the T3 Connect sign-in to load.")), |
| 325 | }); |
| 326 | |
| 327 | const assertSession = Effect.fnUntraced(function* ( |
| 328 | identity: ClientCapabilities.CloudSessionIdentity, |
| 329 | ) { |
| 330 | const current = yield* cloudSession.identity; |
| 331 | if (Option.isNone(current) || current.value !== identity) { |
| 332 | return yield* sessionChanged(); |
| 333 | } |
| 334 | }); |
| 335 | |
| 336 | // Called under tokenLock so a late rejection cannot remove a newer credential. |
| 337 | const removeRejectedToken = Effect.fnUntraced(function* ( |
| 338 | environmentId: EnvironmentId, |
| 339 | accessToken: string, |
| 340 | ) { |
| 341 | const cached = yield* tokenStore.get(environmentId); |
| 342 | if (Option.isSome(cached) && cached.value.accessToken === accessToken) { |
| 343 | yield* tokenStore.remove(environmentId); |
| 344 | tokenOwners.delete(environmentId); |
| 345 | } |
| 346 | }); |
| 347 | |
| 348 | const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* ( |
| 349 | environmentId: EnvironmentId, |
| 350 | identity: ClientCapabilities.CloudSessionIdentity, |
| 351 | ) { |
| 352 | yield* assertSession(identity); |
| 353 | const clerkToken = yield* cloudSession.clerkToken.pipe( |
| 354 | Effect.withSpan("relay.connection.cloudSessionToken.resolve"), |
| 355 | ); |
| 356 | const deviceId = yield* deviceIdentity.deviceId.pipe( |
| 357 | Effect.withSpan("relay.connection.deviceIdentity.resolve"), |
| 358 | ); |
| 359 | yield* assertSession(identity); |
| 360 | const connected = yield* relay |
| 361 | .connectEnvironment({ |
| 362 | clerkToken, |
| 363 | scopes: [RelayEnvironmentConnectScope], |
| 364 | environmentId, |
| 365 | ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}), |
| 366 | }) |
| 367 | .pipe(Effect.mapError(mapManagedRelayError)); |
| 368 | if (connected.environmentId !== environmentId) { |
| 369 | return yield* environmentMismatchError({ |
| 370 | expected: environmentId, |
| 371 | actual: connected.environmentId, |
| 372 | }); |
| 373 | } |
| 374 | yield* assertSession(identity); |
| 375 | return connected; |
| 376 | }); |
| 377 | |
| 378 | const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")( |
| 379 | function* ( |
| 380 | environmentId: EnvironmentId, |
| 381 | thumbprint: string, |
| 382 | identity: ClientCapabilities.CloudSessionIdentity, |
| 383 | ) { |
| 384 | const bootstrap = yield* obtainBootstrap(environmentId, identity); |
| 385 | const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe( |
| 386 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 387 | Effect.withSpan("environment.authorization.descriptor"), |
| 388 | ); |
| 389 | if (descriptor.environmentId !== environmentId) { |
| 390 | return yield* environmentMismatchError({ |
| 391 | expected: environmentId, |
| 392 | actual: descriptor.environmentId, |
| 393 | }); |
| 394 | } |
| 395 | const bootstrapProof = yield* signer |
| 396 | .createProof({ |
| 397 | method: "POST", |
| 398 | url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"), |
| 399 | }) |
| 400 | .pipe( |
| 401 | Effect.mapError( |
| 402 | () => |
| 403 | new ConnectionBlockedError({ |
| 404 | reason: "configuration", |
| 405 | ...translatableDetail(msg("Could not create the environment authorization proof.")), |
| 406 | }), |
| 407 | ), |
| 408 | ); |
| 409 | yield* assertSession(identity); |
| 410 | const access = yield* exchangeRemoteDpopAccessToken({ |
| 411 | httpBaseUrl: bootstrap.endpoint.httpBaseUrl, |
| 412 | credential: bootstrap.credential, |
| 413 | dpopProof: bootstrapProof, |
| 414 | clientMetadata: presentation.metadata, |
| 415 | }).pipe( |
| 416 | Effect.mapError((error) => |
| 417 | error._tag === "EnvironmentConnectApprovalPendingError" |
| 418 | ? approvalPendingError(descriptor.label, thumbprint, error.traceId) |
| 419 | : mapRemoteDpopEnvironmentError(error), |
| 420 | ), |
| 421 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 422 | Effect.withSpan("environment.authorization.accessToken.exchange"), |
| 423 | ); |
| 424 | const issuedAt = yield* Clock.currentTimeMillis; |
| 425 | const token = new TokenStore.RemoteDpopAccessToken({ |
| 426 | environmentId: descriptor.environmentId, |
| 427 | accountId: identity.accountId, |
| 428 | label: descriptor.label, |
| 429 | endpoint: bootstrap.endpoint, |
| 430 | accessToken: access.access_token, |
| 431 | expiresAtEpochMs: issuedAt + access.expires_in * 1_000, |
| 432 | dpopThumbprint: thumbprint, |
| 433 | }); |
| 434 | return { token, descriptor } satisfies IssuedDpopToken; |
| 435 | }, |
| 436 | ); |
| 437 | |
| 438 | const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* ( |
| 439 | input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0], |
| 440 | ) { |
| 441 | const session = yield* cloudSession.identity; |
| 442 | if (Option.isNone(session)) { |
| 443 | return yield* sessionPending(); |
| 444 | } |
| 445 | const identity = session.value; |
| 446 | const thumbprint = yield* signer.thumbprint.pipe( |
| 447 | Effect.mapError( |
| 448 | () => |
| 449 | new ConnectionBlockedError({ |
| 450 | reason: "configuration", |
| 451 | ...translatableDetail(msg("Could not load the environment authorization key.")), |
| 452 | }), |
| 453 | ), |
| 454 | Effect.withSpan("environment.authorization.dpopKey.resolve"), |
| 455 | ); |
| 456 | const selected = yield* tokenLock.withPermits(1)( |
| 457 | Effect.gen(function* () { |
| 458 | yield* assertSession(identity); |
| 459 | const now = yield* Clock.currentTimeMillis; |
| 460 | const cached = yield* tokenStore |
| 461 | .get(input.expectedEnvironmentId) |
| 462 | .pipe(Effect.withSpan("environment.authorization.accessToken.cache")); |
| 463 | const owner = tokenOwners.get(input.expectedEnvironmentId); |
| 464 | if ( |
| 465 | Option.isSome(cached) && |
| 466 | cached.value.environmentId === input.expectedEnvironmentId && |
| 467 | cached.value.accountId === identity.accountId && |
| 468 | cached.value.dpopThumbprint === thumbprint && |
| 469 | cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS && |
| 470 | cached.value.accessToken !== input.rejectedAccessToken && |
| 471 | (owner?.accessToken !== cached.value.accessToken || owner.identity === identity) |
| 472 | ) { |
| 473 | tokenOwners.set(input.expectedEnvironmentId, { |
| 474 | accessToken: cached.value.accessToken, |
| 475 | identity, |
| 476 | }); |
| 477 | return { |
| 478 | issued: Effect.succeed<IssuedDpopToken>({ token: cached.value }), |
| 479 | fromCache: true, |
| 480 | }; |
| 481 | } |
| 482 | if (input.rejectedAccessToken !== undefined) { |
| 483 | yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken); |
| 484 | } |
| 485 | const pending = pendingTokens.get(input.expectedEnvironmentId); |
| 486 | if (pending?.identity === identity && pending.thumbprint === thumbprint) { |
| 487 | return { issued: pending.issued, fromCache: false }; |
| 488 | } |
| 489 | |
| 490 | const id = {}; |
| 491 | const fiber = yield* exchangeDpopToken( |
| 492 | input.expectedEnvironmentId, |
| 493 | thumbprint, |
| 494 | identity, |
| 495 | ).pipe( |
| 496 | Effect.flatMap((issued) => |
| 497 | tokenLock.withPermits(1)( |
| 498 | Effect.gen(function* () { |
| 499 | const { token } = issued; |
| 500 | yield* assertSession(identity); |
| 501 | yield* tokenStore |
| 502 | .put(token) |
| 503 | .pipe(Effect.withSpan("environment.authorization.accessToken.persist")); |
| 504 | const current = yield* cloudSession.identity; |
| 505 | if (Option.isNone(current) || current.value !== identity) { |
| 506 | yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken); |
| 507 | return yield* sessionChanged(); |
| 508 | } |
| 509 | tokenOwners.set(input.expectedEnvironmentId, { |
| 510 | accessToken: token.accessToken, |
| 511 | identity, |
| 512 | }); |
| 513 | if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) { |
| 514 | pendingTokens.delete(input.expectedEnvironmentId); |
| 515 | } |
| 516 | return issued; |
| 517 | }), |
| 518 | ), |
| 519 | ), |
| 520 | Effect.timeoutOrElse({ |
| 521 | duration: DPOP_AUTHORIZATION_TIMEOUT_MS, |
| 522 | orElse: () => |
| 523 | Effect.fail( |
| 524 | new ConnectionTransientError({ |
| 525 | reason: "timeout", |
| 526 | ...translatableDetail(msg("Timed out renewing the environment credential.")), |
| 527 | }), |
| 528 | ), |
| 529 | }), |
| 530 | Effect.ensuring( |
| 531 | tokenLock.withPermits(1)( |
| 532 | Effect.sync(() => { |
| 533 | if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) { |
| 534 | pendingTokens.delete(input.expectedEnvironmentId); |
| 535 | } |
| 536 | }), |
| 537 | ), |
| 538 | ), |
| 539 | // One caller's timeout must not cancel renewal for other HTTP requests. |
| 540 | Effect.forkIn(serviceScope), |
| 541 | ); |
| 542 | const issued = Fiber.join(fiber); |
| 543 | pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, issued }); |
| 544 | return { issued, fromCache: false }; |
| 545 | }), |
| 546 | ); |
| 547 | yield* Effect.annotateCurrentSpan({ |
| 548 | "connection.remote_token_cache": selected.fromCache ? "hit" : "miss", |
| 549 | }); |
| 550 | const issued = yield* selected.issued; |
| 551 | yield* assertSession(identity); |
| 552 | return { ...issued, fromCache: selected.fromCache, identity }; |
| 553 | }); |
| 554 | |
| 555 | const proofError = (detail: string) => () => |
| 556 | new ConnectionBlockedError({ reason: "configuration", ...translatableDetail(detail) }); |
| 557 | |
| 558 | // Requests for the same credential share a renewal without waiting on other hosts. |
| 559 | const directDpopToken = Effect.fn("clientRuntime.connection.remote.directDpopToken")(function* ( |
| 560 | connection: DirectDpopConnection, |
| 561 | rejectedAccessToken?: string, |
| 562 | ) { |
| 563 | return yield* directTokenLocks.withLock( |
| 564 | connection.connectionId, |
| 565 | Effect.gen(function* () { |
| 566 | const stored = yield* credentials.get(connection.connectionId); |
| 567 | if (Option.isNone(stored) || stored.value._tag !== "DpopConnectionCredential") { |
| 568 | return yield* credentialMissingError(connection.connectionId); |
| 569 | } |
| 570 | const current = stored.value; |
| 571 | const now = yield* Clock.currentTimeMillis; |
| 572 | if ( |
| 573 | current.accessToken !== rejectedAccessToken && |
| 574 | current.expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS > now |
| 575 | ) { |
| 576 | return current; |
| 577 | } |
| 578 | const proof = yield* signer |
| 579 | .createProof({ |
| 580 | method: "POST", |
| 581 | url: environmentEndpointUrl(connection.httpBaseUrl, "/oauth/token"), |
| 582 | }) |
| 583 | .pipe( |
| 584 | Effect.mapError( |
| 585 | proofError(msg("Could not create the environment authorization proof.")), |
| 586 | ), |
| 587 | ); |
| 588 | const access = yield* exchangeRemoteDpopAccessToken({ |
| 589 | httpBaseUrl: connection.httpBaseUrl, |
| 590 | credential: current.accessToken, |
| 591 | credentialType: AuthAccessTokenType, |
| 592 | dpopProof: proof, |
| 593 | }).pipe( |
| 594 | Effect.mapError((error) => mapRemoteDpopEnvironmentError(error, "direct")), |
| 595 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 596 | Effect.withSpan("environment.authorization.directRenewal"), |
| 597 | ); |
| 598 | const renewed = new DpopConnectionCredential({ |
| 599 | accessToken: access.access_token, |
| 600 | expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000, |
| 601 | }); |
| 602 | yield* credentials.put(connection.connectionId, renewed); |
| 603 | return renewed; |
| 604 | }), |
| 605 | ); |
| 606 | }); |
| 607 | |
| 608 | const directHttpAuthorization = ( |
| 609 | connection: DirectDpopConnection, |
| 610 | credential: DpopConnectionCredential, |
| 611 | ) => |
| 612 | ({ |
| 613 | _tag: "Dpop", |
| 614 | accessToken: credential.accessToken, |
| 615 | expiresAtEpochMs: credential.expiresAtEpochMs, |
| 616 | directConnection: connection, |
| 617 | }) as const; |
| 618 | |
| 619 | const authorizeDirectDpop = Effect.fn("clientRuntime.connection.remote.authorizeDirectDpop")( |
| 620 | function* ( |
| 621 | input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDirectDpop"]>[0], |
| 622 | ) { |
| 623 | const descriptor = yield* verifyDirectEndpoint({ |
| 624 | expectedEnvironmentId: input.expectedEnvironmentId, |
| 625 | httpBaseUrl: input.httpBaseUrl, |
| 626 | connectionMethod: "direct", |
| 627 | }); |
| 628 | const connection = { connectionId: input.connectionId, httpBaseUrl: input.httpBaseUrl }; |
| 629 | const openSocket = (credential: DpopConnectionCredential) => |
| 630 | resolveRemoteDpopWebSocketConnectionUrl({ |
| 631 | wsBaseUrl: input.wsBaseUrl, |
| 632 | httpBaseUrl: input.httpBaseUrl, |
| 633 | accessToken: credential.accessToken, |
| 634 | createProof: (proof) => |
| 635 | signer |
| 636 | .createProof(proof) |
| 637 | .pipe( |
| 638 | Effect.mapError( |
| 639 | proofError(msg("Could not create the websocket authorization proof.")), |
| 640 | ), |
| 641 | ), |
| 642 | clientMetadata: presentation.metadata, |
| 643 | connectionMethod: "direct", |
| 644 | }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.result); |
| 645 | let credential = yield* directDpopToken(connection); |
| 646 | let socket = yield* openSocket(credential); |
| 647 | // A token the host refuses before its expiry, such as after a clock jump, renews once. |
| 648 | if (Result.isFailure(socket) && socket.failure._tag === "EnvironmentAuthInvalidError") { |
| 649 | credential = yield* directDpopToken(connection, credential.accessToken); |
| 650 | socket = yield* openSocket(credential); |
| 651 | } |
| 652 | if (Result.isFailure(socket)) { |
| 653 | const failure = socket.failure; |
| 654 | return yield* failure._tag === "ConnectionBlockedError" |
| 655 | ? failure |
| 656 | : mapRemoteDpopEnvironmentError(failure, "direct"); |
| 657 | } |
| 658 | return { |
| 659 | environmentId: descriptor.environmentId, |
| 660 | label: descriptor.label, |
| 661 | httpBaseUrl: input.httpBaseUrl, |
| 662 | socketUrl: socket.success, |
| 663 | descriptor, |
| 664 | httpAuthorization: directHttpAuthorization(connection, credential), |
| 665 | }; |
| 666 | }, |
| 667 | ); |
| 668 | |
| 669 | const httpAuthorization = ( |
| 670 | token: TokenStore.RemoteDpopAccessToken, |
| 671 | httpBaseUrl = token.endpoint.httpBaseUrl, |
| 672 | ): AuthorizedRemoteHttpEnvironment => ({ |
| 673 | environmentId: token.environmentId, |
| 674 | label: token.label, |
| 675 | httpBaseUrl, |
| 676 | httpAuthorization: { |
| 677 | _tag: "Dpop", |
| 678 | accessToken: token.accessToken, |
| 679 | expiresAtEpochMs: token.expiresAtEpochMs, |
| 680 | }, |
| 681 | }); |
| 682 | |
| 683 | const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* ( |
| 684 | input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0], |
| 685 | ) { |
| 686 | const endpoint = input.directEndpoint; |
| 687 | const directDescriptor = |
| 688 | endpoint === undefined |
| 689 | ? undefined |
| 690 | : yield* verifyDirectEndpoint({ |
| 691 | expectedEnvironmentId: input.expectedEnvironmentId, |
| 692 | httpBaseUrl: endpoint.httpBaseUrl, |
| 693 | connectionMethod: "direct", |
| 694 | }); |
| 695 | const authorized = ( |
| 696 | token: TokenStore.RemoteDpopAccessToken, |
| 697 | socketUrl: string, |
| 698 | descriptor: ExecutionEnvironmentDescriptor, |
| 699 | ) => ({ ...httpAuthorization(token, endpoint?.httpBaseUrl), socketUrl, descriptor }); |
| 700 | // A cached token comes without a descriptor. That read needs no ticket, so |
| 701 | // it runs beside the ticket request, and a failed ticket abandons it. |
| 702 | const openSocket = Effect.fnUntraced(function* (issued: IssuedDpopToken, timeoutMs?: number) { |
| 703 | const socket = createDpopSocketUrl(issued.token, timeoutMs, endpoint).pipe(Effect.result); |
| 704 | const known = directDescriptor ?? issued.descriptor; |
| 705 | if (known !== undefined) { |
| 706 | return Result.map(yield* socket, (socketUrl) => authorized(issued.token, socketUrl, known)); |
| 707 | } |
| 708 | const reading = yield* fetchDescriptor(issued.token.endpoint.httpBaseUrl, "relay").pipe( |
| 709 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 710 | Effect.forkChild, |
| 711 | ); |
| 712 | const opened = yield* socket; |
| 713 | if (Result.isFailure(opened)) { |
| 714 | yield* Fiber.interrupt(reading); |
| 715 | return Result.fail(opened.failure); |
| 716 | } |
| 717 | return Result.succeed(authorized(issued.token, opened.success, yield* Fiber.join(reading))); |
| 718 | }); |
| 719 | let selected = yield* getDpopToken(input); |
| 720 | if (selected.fromCache) { |
| 721 | const cachedSocket = yield* openSocket(selected, CACHED_ENDPOINT_SOCKET_TIMEOUT_MS); |
| 722 | if (Result.isSuccess(cachedSocket)) { |
| 723 | yield* assertSession(selected.identity); |
| 724 | return cachedSocket.success; |
| 725 | } |
| 726 | if (cachedSocket.failure._tag === "ConnectionBlockedError") { |
| 727 | return yield* mapDpopSocketError(cachedSocket.failure); |
| 728 | } |
| 729 | // An unreachable direct address says nothing about the token, so keep |
| 730 | // it for the T3 Connect route rather than forcing a relay round trip. |
| 731 | if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") { |
| 732 | return yield* mapDpopSocketError(cachedSocket.failure); |
| 733 | } |
| 734 | yield* assertSession(selected.identity); |
| 735 | selected = yield* getDpopToken({ |
| 736 | ...input, |
| 737 | rejectedAccessToken: selected.token.accessToken, |
| 738 | }); |
| 739 | } |
| 740 | const socket = yield* openSocket(selected); |
| 741 | if (Result.isFailure(socket)) { |
| 742 | if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") { |
| 743 | yield* tokenLock.withPermits(1)( |
| 744 | removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken), |
| 745 | ); |
| 746 | } |
| 747 | return yield* mapDpopSocketError(socket.failure); |
| 748 | } |
| 749 | yield* assertSession(selected.identity); |
| 750 | return socket.success; |
| 751 | }); |
| 752 | |
| 753 | return RemoteEnvironmentAuthorization.of({ |
| 754 | authorizeBearer, |
| 755 | // Untraced: it runs on every route and host check. |
| 756 | rememberCheckedDescriptor: Effect.fnUntraced(function* (httpBaseUrl, descriptor, keepsItsHost) { |
| 757 | if (Option.isNone(descriptor) || !keepsItsHost) { |
| 758 | checkedDescriptors.delete(httpBaseUrl); |
| 759 | return; |
| 760 | } |
| 761 | checkedDescriptors.set(httpBaseUrl, { |
| 762 | descriptor: descriptor.value, |
| 763 | at: yield* Clock.monotonicTimeNanos, |
| 764 | }); |
| 765 | }), |
| 766 | authorizeDpop: Effect.fn("environment.authorization")(function (input) { |
| 767 | return authorizeDpop(input); |
| 768 | }), |
| 769 | authorizeDirectDpop, |
| 770 | authorizeDirectDpopHttp: Effect.fn("environment.authorization.directHttp")( |
| 771 | function* (connection, rejectedAccessToken) { |
| 772 | const credential = yield* directDpopToken(connection, rejectedAccessToken); |
| 773 | return directHttpAuthorization(connection, credential); |
| 774 | }, |
| 775 | ), |
| 776 | // The relay tracer must wrap span creation, not just the token request. |
| 777 | authorizeDpopHttp: Effect.fnUntraced(function* (input) { |
| 778 | return yield* getDpopToken(input).pipe( |
| 779 | Effect.map(({ token }) => httpAuthorization(token)), |
| 780 | Effect.withSpan("environment.authorization.http"), |
| 781 | withRelayClientTracing, |
| 782 | ); |
| 783 | }), |
| 784 | // Untraced: a span here would stay open for the socket's lifetime. Each renewal has its own. |
| 785 | renewDpopBeforeExpiry: Effect.fnUntraced(function* (input) { |
| 786 | const direct = input.directConnection; |
| 787 | let expiresAtEpochMs = input.expiresAtEpochMs; |
| 788 | let now = yield* Clock.currentTimeMillis; |
| 789 | // Past expiry the server has closed a T3 Connect socket. A direct socket stays open for |
| 790 | // its session's whole renewal window, so it keeps retrying until a blocked credential. |
| 791 | while (direct !== undefined || now < expiresAtEpochMs) { |
| 792 | // getDpopToken reuses a cached token until it is within the skew of expiry. |
| 793 | // The floor spaces out retries and keeps a wall-clock jump from spinning. |
| 794 | const floor = now < expiresAtEpochMs ? 5_000 : DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS; |
| 795 | yield* Effect.sleep( |
| 796 | Math.max(floor, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now), |
| 797 | ); |
| 798 | const renewed = yield* ( |
| 799 | direct === undefined |
| 800 | ? getDpopToken({ expectedEnvironmentId: input.expectedEnvironmentId }).pipe( |
| 801 | Effect.map(({ token }) => token.expiresAtEpochMs), |
| 802 | ) |
| 803 | : directDpopToken(direct).pipe(Effect.map((credential) => credential.expiresAtEpochMs)) |
| 804 | ).pipe( |
| 805 | Effect.withSpan("environment.authorization.renewSocket"), |
| 806 | withRelayClientTracing, |
| 807 | // A relay blip retries until expiry; a blocked credential ends the loop. |
| 808 | Effect.catchTags({ ConnectionTransientError: () => Effect.succeed(expiresAtEpochMs) }), |
| 809 | ); |
| 810 | expiresAtEpochMs = Math.max(expiresAtEpochMs, renewed); |
| 811 | now = yield* Clock.currentTimeMillis; |
| 812 | } |
| 813 | }), |
| 814 | }); |
| 815 | }); |
| 816 | |
| 817 | export const layer = Layer.effect(RemoteEnvironmentAuthorization, make); |