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