Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

environmentHttpAuth.ts

198 lines7.4 KB

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