The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { translatableMessage } from "../errors/translatable.ts"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import { |
| 6 | ORCHESTRATION_PROTOCOL_HEADER, |
| 7 | ORCHESTRATION_PROTOCOL_VERSION_TEXT, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import * as Result from "effect/Result"; |
| 10 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 11 | import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; |
| 12 | import { FetchHttpClient, type HttpMethod } from "effect/http"; |
| 13 | |
| 14 | import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; |
| 15 | import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts"; |
| 16 | import * as EnvironmentSupervisor from "../connection/supervisor.ts"; |
| 17 | import * as ManagedRelay from "../relay/managedRelay.ts"; |
| 18 | import { |
| 19 | executeEnvironmentHttpRequest, |
| 20 | makeEnvironmentHttpApiGroupClient, |
| 21 | makeEnvironmentHttpApiUrlBuilder, |
| 22 | RemoteEnvironmentAuthFetchError, |
| 23 | RemoteEnvironmentAuthTimeoutError, |
| 24 | type RemoteEnvironmentRequestError, |
| 25 | } from "../rpc/http.ts"; |
| 26 | |
| 27 | export interface EnvironmentHttpAuthHeaders { |
| 28 | readonly authorization?: string; |
| 29 | readonly dpop?: string; |
| 30 | } |
| 31 | |
| 32 | export function withOrchestrationProtocolHeader( |
| 33 | headers: EnvironmentHttpAuthHeaders, |
| 34 | ): EnvironmentHttpAuthHeaders & { |
| 35 | readonly [ORCHESTRATION_PROTOCOL_HEADER]: typeof ORCHESTRATION_PROTOCOL_VERSION_TEXT; |
| 36 | } { |
| 37 | return { |
| 38 | ...headers, |
| 39 | [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT, |
| 40 | }; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Cookie-authenticated environments need credentialed mode for cross-origin fetches; bearer/DPoP uses headers. |
| 45 | * `FetchHttpClient` reads `RequestInit` from the fiber context per request. |
| 46 | */ |
| 47 | const withEnvironmentRequestInit = <A, E, R>( |
| 48 | authorization: PreparedHttpAuthorization | null, |
| 49 | requestInit: RequestInit | undefined, |
| 50 | request: Effect.Effect<A, E, R>, |
| 51 | ): Effect.Effect<A, E, R> => { |
| 52 | if (authorization !== null && requestInit === undefined) return request; |
| 53 | return request.pipe( |
| 54 | Effect.provideService(FetchHttpClient.RequestInit, { |
| 55 | ...requestInit, |
| 56 | ...(authorization === null ? { credentials: "include" as const } : {}), |
| 57 | }), |
| 58 | ); |
| 59 | }; |
| 60 | |
| 61 | const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironmentAuthHeaders")( |
| 62 | function* ( |
| 63 | authorization: PreparedHttpAuthorization | null, |
| 64 | method: HttpMethod.HttpMethod, |
| 65 | url: string, |
| 66 | signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>, |
| 67 | ): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> { |
| 68 | if (authorization === null) { |
| 69 | return {}; |
| 70 | } |
| 71 | if (authorization._tag === "Bearer") { |
| 72 | return { authorization: `Bearer ${authorization.token}` }; |
| 73 | } |
| 74 | if (Option.isNone(signer)) { |
| 75 | return yield* new RemoteEnvironmentAuthFetchError({ |
| 76 | ...translatableMessage( |
| 77 | msg("No DPoP signer is available to authorize the environment request."), |
| 78 | ), |
| 79 | cause: authorization._tag, |
| 80 | }); |
| 81 | } |
| 82 | const proof = yield* signer.value |
| 83 | .createProof({ method, url, accessToken: authorization.accessToken }) |
| 84 | .pipe( |
| 85 | Effect.mapError( |
| 86 | (cause) => |
| 87 | new RemoteEnvironmentAuthFetchError({ |
| 88 | ...translatableMessage( |
| 89 | msg("Could not create the environment request authorization proof."), |
| 90 | ), |
| 91 | cause, |
| 92 | }), |
| 93 | ), |
| 94 | ); |
| 95 | return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof }; |
| 96 | }, |
| 97 | ); |
| 98 | |
| 99 | /** |
| 100 | * A DPoP request is T3 Connect work, so its span starts an exported trace that |
| 101 | * the environment continues; its local caller's span would leave that trace |
| 102 | * without a root. |
| 103 | */ |
| 104 | export const executeAuthenticatedEnvironmentHttpRequest = < |
| 105 | Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1], |
| 106 | A, |
| 107 | E, |
| 108 | R, |
| 109 | >( |
| 110 | input: Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0], |
| 111 | ) => |
| 112 | input.prepared.httpAuthorization?._tag === "Dpop" |
| 113 | ? executeEnvironmentRequest(input).pipe( |
| 114 | Effect.withSpan(ENVIRONMENT_REQUEST_SPAN, { root: true }), |
| 115 | withRelayClientTracing, |
| 116 | ) |
| 117 | : executeEnvironmentRequest(input).pipe(Effect.withSpan(ENVIRONMENT_REQUEST_SPAN)); |
| 118 | |
| 119 | /** Sends the request with this client's own credentials on the supervised environment. */ |
| 120 | export const executeConnectedEnvironmentHttpRequest = Effect.fn( |
| 121 | "clientRuntime.state.executeConnectedEnvironmentHttpRequest", |
| 122 | )(function* <Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1], A, E, R>( |
| 123 | input: Omit< |
| 124 | Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0], |
| 125 | "prepared" | "signer" | "remoteAuthorization" |
| 126 | >, |
| 127 | ) { |
| 128 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 129 | const prepared = yield* SubscriptionRef.get(supervisor.prepared); |
| 130 | if (Option.isNone(prepared)) { |
| 131 | return yield* new RemoteEnvironmentAuthFetchError({ |
| 132 | ...translatableMessage(msg("The environment is not connected.")), |
| 133 | cause: supervisor.target._tag, |
| 134 | }); |
| 135 | } |
| 136 | return yield* executeAuthenticatedEnvironmentHttpRequest({ |
| 137 | ...input, |
| 138 | prepared: prepared.value, |
| 139 | signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner), |
| 140 | remoteAuthorization: yield* Effect.serviceOption( |
| 141 | RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, |
| 142 | ), |
| 143 | }); |
| 144 | }); |
| 145 | |
| 146 | const ENVIRONMENT_REQUEST_SPAN = "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest"; |
| 147 | |
| 148 | const executeEnvironmentRequest = Effect.fnUntraced(function* < |
| 149 | Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1], |
| 150 | A, |
| 151 | E, |
| 152 | R, |
| 153 | >(input: { |
| 154 | readonly prepared: Pick< |
| 155 | PreparedConnection, |
| 156 | "environmentId" | "httpBaseUrl" | "httpAuthorization" | "target" |
| 157 | >; |
| 158 | readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>; |
| 159 | readonly remoteAuthorization?: Option.Option< |
| 160 | RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"] |
| 161 | >; |
| 162 | readonly method: HttpMethod.HttpMethod; |
| 163 | /** |
| 164 | * The URL to sign, from the group's contract URL builder. It encodes path |
| 165 | * params exactly like the request client, so the DPoP proof matches the |
| 166 | * URL actually sent. |
| 167 | */ |
| 168 | readonly url: (urls: ReturnType<typeof makeEnvironmentHttpApiUrlBuilder>[Group]) => string; |
| 169 | readonly timeoutMs: number; |
| 170 | /** Extra fetch options, such as refusing redirects for credentialed audio uploads. */ |
| 171 | readonly requestInit?: RequestInit; |
| 172 | readonly group: Group; |
| 173 | readonly request: (input: { |
| 174 | readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>>; |
| 175 | readonly headers: EnvironmentHttpAuthHeaders; |
| 176 | }) => Effect.Effect<A, E, R>; |
| 177 | /** Some endpoints report rejected credentials in a successful response. */ |
| 178 | readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean; |
| 179 | }): Effect.fn.Return< |
| 180 | A, |
| 181 | RemoteEnvironmentRequestError, |
| 182 | Effect.Services<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>> | R |
| 183 | > { |
| 184 | let httpBaseUrl = input.prepared.httpBaseUrl; |
| 185 | const requestUrlFor = (baseUrl: string) => |
| 186 | input.url(makeEnvironmentHttpApiUrlBuilder(baseUrl)[input.group]); |
| 187 | return yield* Effect.gen(function* () { |
| 188 | let rejectedAccessToken: string | undefined; |
| 189 | for (;;) { |
| 190 | let authorization = input.prepared.httpAuthorization; |
| 191 | if (authorization?._tag === "Dpop") { |
| 192 | const remote = input.remoteAuthorization; |
| 193 | if (remote === undefined || Option.isNone(remote)) { |
| 194 | return yield* new RemoteEnvironmentAuthFetchError({ |
| 195 | ...translatableMessage( |
| 196 | msg("No relay authorization service is available for the environment request."), |
| 197 | ), |
| 198 | cause: input.prepared.target._tag, |
| 199 | }); |
| 200 | } |
| 201 | const authFetchError = (cause: unknown) => |
| 202 | new RemoteEnvironmentAuthFetchError({ |
| 203 | ...translatableMessage(msg("Could not authorize the environment request.")), |
| 204 | cause, |
| 205 | }); |
| 206 | const direct = authorization.directConnection; |
| 207 | if (direct !== undefined) { |
| 208 | authorization = yield* remote.value |
| 209 | .authorizeDirectDpopHttp(direct, rejectedAccessToken) |
| 210 | .pipe(Effect.mapError(authFetchError)); |
| 211 | } else { |
| 212 | const current = yield* remote.value |
| 213 | .authorizeDpopHttp({ |
| 214 | expectedEnvironmentId: input.prepared.environmentId, |
| 215 | ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }), |
| 216 | }) |
| 217 | .pipe(Effect.mapError(authFetchError)); |
| 218 | // A learned direct route keeps its own origin; only the token renews. |
| 219 | if (input.prepared.target._tag === "RelayConnectionTarget") { |
| 220 | httpBaseUrl = current.httpBaseUrl; |
| 221 | } |
| 222 | authorization = current.httpAuthorization; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | const requestUrl = requestUrlFor(httpBaseUrl); |
| 227 | const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group); |
| 228 | const headers = yield* buildEnvironmentAuthHeaders( |
| 229 | authorization, |
| 230 | input.method, |
| 231 | requestUrl, |
| 232 | input.signer, |
| 233 | ); |
| 234 | const result = yield* executeEnvironmentHttpRequest( |
| 235 | requestUrl, |
| 236 | input.timeoutMs, |
| 237 | withEnvironmentRequestInit( |
| 238 | authorization, |
| 239 | input.requestInit, |
| 240 | input.request({ client, headers }), |
| 241 | ), |
| 242 | ).pipe(Effect.result); |
| 243 | |
| 244 | if (Result.isFailure(result)) { |
| 245 | if ( |
| 246 | authorization?._tag === "Dpop" && |
| 247 | rejectedAccessToken === undefined && |
| 248 | result.failure._tag === "EnvironmentAuthInvalidError" && |
| 249 | result.failure.reason === "invalid_credential" |
| 250 | ) { |
| 251 | rejectedAccessToken = authorization.accessToken; |
| 252 | continue; |
| 253 | } |
| 254 | return yield* result.failure; |
| 255 | } |
| 256 | |
| 257 | if ( |
| 258 | authorization?._tag === "Dpop" && |
| 259 | input.isUnauthorizedResponse?.(result.success) === true |
| 260 | ) { |
| 261 | if (rejectedAccessToken === undefined) { |
| 262 | rejectedAccessToken = authorization.accessToken; |
| 263 | continue; |
| 264 | } |
| 265 | return yield* new RemoteEnvironmentAuthFetchError({ |
| 266 | ...translatableMessage( |
| 267 | msg("The environment rejected the renewed session authorization."), |
| 268 | ), |
| 269 | cause: result.success, |
| 270 | }); |
| 271 | } |
| 272 | return result.success; |
| 273 | } |
| 274 | }).pipe( |
| 275 | Effect.timeoutOrElse({ |
| 276 | duration: input.timeoutMs, |
| 277 | orElse: () => |
| 278 | Effect.fail( |
| 279 | new RemoteEnvironmentAuthTimeoutError({ |
| 280 | requestUrl: requestUrlFor(httpBaseUrl), |
| 281 | timeoutMs: input.timeoutMs, |
| 282 | }), |
| 283 | ), |
| 284 | }), |
| 285 | ); |
| 286 | }); |