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