Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import {
4 ORCHESTRATION_PROTOCOL_HEADER,
5 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
6} from "@t3tools/contracts";
7import * as Result from "effect/Result";
8import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
9import { FetchHttpClient, type HttpMethod } from "effect/http";
10
11import type { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
12import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";
13import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
14import {
15 executeEnvironmentHttpRequest,
16 makeEnvironmentHttpApiGroupClient,
17 RemoteEnvironmentAuthFetchError,
18 RemoteEnvironmentAuthTimeoutError,
19 type RemoteEnvironmentRequestError,
20} from "../rpc/http.ts";
21
22export interface EnvironmentHttpAuthHeaders {
23 readonly authorization?: string;
24 readonly dpop?: string;
25}
26
27export function withOrchestrationProtocolHeader(
28 headers: EnvironmentHttpAuthHeaders,
29): EnvironmentHttpAuthHeaders & {
30 readonly [ORCHESTRATION_PROTOCOL_HEADER]: typeof ORCHESTRATION_PROTOCOL_VERSION_TEXT;
31} {
32 return {
33 ...headers,
34 [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT,
35 };
36}
37
38/**
39 * Primary/local environments with no bearer or DPoP credential authenticate the
40 * browser via a session cookie. A cross-origin `fetch` does not send cookies by
41 * default, so those requests must opt into credentialed mode; bearer/DPoP
42 * connections carry their credential in a header and need no cookies. Applied
43 * per-request via `FetchHttpClient.RequestInit`, which the fetch client reads
44 * from the fiber context at request time.
45 */
46const withEnvironmentCredentials = <A, E, R>(
47 authorization: PreparedHttpAuthorization | null,
48 request: Effect.Effect<A, E, R>,
49): Effect.Effect<A, E, R> =>
50 authorization === null
51 ? request.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" }))
52 : request;
53
54/**
55 * Build request-bound headers from the current environment credential:
56 * - primary/local connections carry no credential,
57 * - bearer connections send a static `Bearer` token,
58 * - relay connections send a `DPoP` access token with a freshly signed proof
59 * bound to this request's method and URL.
60 *
61 * The DPoP signer is passed in (not resolved from context) and is only required
62 * for relay/DPoP connections, so bearer/primary connections work even when no
63 * signer is available.
64 */
65const buildEnvironmentAuthHeaders = (
66 authorization: PreparedHttpAuthorization | null,
67 method: HttpMethod.HttpMethod,
68 url: string,
69 signer: Option.Option<ManagedRelayDpopSigner["Service"]>,
70): Effect.Effect<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> =>
71 Effect.gen(function* () {
72 if (authorization === null) {
73 return {};
74 }
75 if (authorization._tag === "Bearer") {
76 return { authorization: `Bearer ${authorization.token}` };
77 }
78 if (Option.isNone(signer)) {
79 return yield* new RemoteEnvironmentAuthFetchError({
80 message: "No DPoP signer is available to authorize the environment request.",
81 cause: authorization._tag,
82 });
83 }
84 const proof = yield* signer.value
85 .createProof({ method, url, accessToken: authorization.accessToken })
86 .pipe(
87 Effect.mapError(
88 (cause) =>
89 new RemoteEnvironmentAuthFetchError({
90 message: "Could not create the environment request authorization proof.",
91 cause,
92 }),
93 ),
94 );
95 return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };
96 });
97
98/**
99 * Resolve relay credentials at request time without replacing the live socket.
100 * A rejected credential gets one refresh and retry, with a new request-bound
101 * proof. Cookie and bearer requests keep their existing authentication behavior.
102 *
103 * A DPoP request is T3 Connect work, so its span starts an exported trace that
104 * the environment continues; its local caller's span would leave that trace
105 * without a root.
106 */
107export const executeAuthenticatedEnvironmentHttpRequest = <
108 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
109 A,
110 E,
111 R,
112>(
113 input: Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0],
114) =>
115 input.prepared.httpAuthorization?._tag === "Dpop"
116 ? executeEnvironmentRequest(input).pipe(
117 Effect.withSpan(ENVIRONMENT_REQUEST_SPAN, { root: true }),
118 withRelayClientTracing,
119 )
120 : executeEnvironmentRequest(input).pipe(Effect.withSpan(ENVIRONMENT_REQUEST_SPAN));
121
122const ENVIRONMENT_REQUEST_SPAN = "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest";
123
124const executeEnvironmentRequest = Effect.fnUntraced(function* <
125 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
126 A,
127 E,
128 R,
129>(input: {
130 readonly prepared: PreparedConnection;
131 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
132 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
133 readonly method: HttpMethod.HttpMethod;
134 readonly url: (httpBaseUrl: string) => string;
135 readonly timeoutMs: number;
136 readonly group: Group;
137 readonly request: (input: {
138 readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>>;
139 readonly headers: EnvironmentHttpAuthHeaders;
140 }) => Effect.Effect<A, E, R>;
141 /** Some endpoints report rejected credentials in a successful response. */
142 readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean;
143}): Effect.fn.Return<
144 A,
145 RemoteEnvironmentRequestError,
146 Effect.Services<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>> | R
147> {
148 let httpBaseUrl = input.prepared.httpBaseUrl;
149 return yield* Effect.gen(function* () {
150 let rejectedAccessToken: string | undefined;
151 for (;;) {
152 let authorization = input.prepared.httpAuthorization;
153 if (authorization?._tag === "Dpop") {
154 const remote = input.remoteAuthorization;
155 if (remote === undefined || Option.isNone(remote)) {
156 return yield* new RemoteEnvironmentAuthFetchError({
157 message: "No relay authorization service is available for the environment request.",
158 cause: input.prepared.target._tag,
159 });
160 }
161 const current = yield* remote.value
162 .authorizeDpopHttp({
163 expectedEnvironmentId: input.prepared.environmentId,
164 ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
165 })
166 .pipe(
167 Effect.mapError(
168 (cause) =>
169 new RemoteEnvironmentAuthFetchError({
170 message: "Could not authorize the environment request.",
171 cause,
172 }),
173 ),
174 );
175 // A learned direct route keeps its own origin; only the token renews.
176 if (input.prepared.target._tag === "RelayConnectionTarget") {
177 httpBaseUrl = current.httpBaseUrl;
178 }
179 authorization = current.httpAuthorization;
180 }
181
182 const requestUrl = input.url(httpBaseUrl);
183 const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group);
184 const headers = yield* buildEnvironmentAuthHeaders(
185 authorization,
186 input.method,
187 requestUrl,
188 input.signer,
189 );
190 const result = yield* executeEnvironmentHttpRequest(
191 requestUrl,
192 input.timeoutMs,
193 withEnvironmentCredentials(authorization, input.request({ client, headers })),
194 ).pipe(Effect.result);
195
196 if (Result.isFailure(result)) {
197 if (
198 authorization?._tag === "Dpop" &&
199 rejectedAccessToken === undefined &&
200 result.failure._tag === "EnvironmentAuthInvalidError" &&
201 result.failure.reason === "invalid_credential"
202 ) {
203 rejectedAccessToken = authorization.accessToken;
204 continue;
205 }
206 return yield* result.failure;
207 }
208
209 if (
210 authorization?._tag === "Dpop" &&
211 input.isUnauthorizedResponse?.(result.success) === true
212 ) {
213 if (rejectedAccessToken === undefined) {
214 rejectedAccessToken = authorization.accessToken;
215 continue;
216 }
217 return yield* new RemoteEnvironmentAuthFetchError({
218 message: "The environment rejected the renewed session authorization.",
219 cause: result.success,
220 });
221 }
222 return result.success;
223 }
224 }).pipe(
225 Effect.timeoutOrElse({
226 duration: input.timeoutMs,
227 orElse: () =>
228 Effect.fail(new RemoteEnvironmentAuthTimeoutError(input.url(httpBaseUrl), input.timeoutMs)),
229 }),
230 );
231});