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

environmentHttpAuth.ts

208 lines7.6 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 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 makeEnvironmentHttpApiGroupClient,
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 */
45const 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 */
64const 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* <
105 Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1],
106 A,
107 E,
108 R,
109>(input: {
110 readonly prepared: PreparedConnection;
111 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
112 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
113 readonly method: HttpMethod.HttpMethod;
114 readonly url: (httpBaseUrl: string) => string;
115 readonly timeoutMs: number;
116 readonly group: Group;
117 readonly request: (input: {
118 readonly client: Effect.Success<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>>;
119 readonly headers: EnvironmentHttpAuthHeaders;
120 }) => Effect.Effect<A, E, R>;
121 /** Some endpoints report rejected credentials in a successful response. */
122 readonly isUnauthorizedResponse?: (response: NoInfer<A>) => boolean;
123}): Effect.fn.Return<
124 A,
125 RemoteEnvironmentRequestError,
126 Effect.Services<ReturnType<typeof makeEnvironmentHttpApiGroupClient<Group>>> | R
127> {
128 let httpBaseUrl = input.prepared.httpBaseUrl;
129 return yield* Effect.gen(function* () {
130 let rejectedAccessToken: string | undefined;
131 for (;;) {
132 let authorization = input.prepared.httpAuthorization;
133 if (authorization?._tag === "Dpop") {
134 const remote = input.remoteAuthorization;
135 if (remote === undefined || Option.isNone(remote)) {
136 return yield* new RemoteEnvironmentAuthFetchError({
137 message: "No relay authorization service is available for the environment request.",
138 cause: input.prepared.target._tag,
139 });
140 }
141 const current = yield* remote.value
142 .authorizeDpopHttp({
143 expectedEnvironmentId: input.prepared.environmentId,
144 ...(rejectedAccessToken === undefined ? {} : { rejectedAccessToken }),
145 })
146 .pipe(
147 Effect.mapError(
148 (cause) =>
149 new RemoteEnvironmentAuthFetchError({
150 message: "Could not authorize the environment request.",
151 cause,
152 }),
153 ),
154 );
155 httpBaseUrl = current.httpBaseUrl;
156 authorization = current.httpAuthorization;
157 }
158​
159 const requestUrl = input.url(httpBaseUrl);
160 const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group);
161 const headers = yield* buildEnvironmentAuthHeaders(
162 authorization,
163 input.method,
164 requestUrl,
165 input.signer,
166 );
167 const result = yield* executeEnvironmentHttpRequest(
168 requestUrl,
169 input.timeoutMs,
170 withEnvironmentCredentials(authorization, input.request({ client, headers })),
171 ).pipe(Effect.result);
172​
173 if (Result.isFailure(result)) {
174 if (
175 authorization?._tag === "Dpop" &&
176 rejectedAccessToken === undefined &&
177 result.failure._tag === "EnvironmentAuthInvalidError" &&
178 result.failure.reason === "invalid_credential"
179 ) {
180 rejectedAccessToken = authorization.accessToken;
181 continue;
182 }
183 return yield* result.failure;
184 }
185​
186 if (
187 authorization?._tag === "Dpop" &&
188 input.isUnauthorizedResponse?.(result.success) === true
189 ) {
190 if (rejectedAccessToken === undefined) {
191 rejectedAccessToken = authorization.accessToken;
192 continue;
193 }
194 return yield* new RemoteEnvironmentAuthFetchError({
195 message: "The environment rejected the renewed session authorization.",
196 cause: result.success,
197 });
198 }
199 return result.success;
200 }
201 }).pipe(
202 Effect.timeoutOrElse({
203 duration: input.timeoutMs,
204 orElse: () =>
205 Effect.fail(new RemoteEnvironmentAuthTimeoutError(input.url(httpBaseUrl), input.timeoutMs)),
206 }),
207 );
208});