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

http.ts

371 lines13.8 KB

1import {
2 AuthAccessReadScope,
3 AuthAccessWriteScope,
4 AuthStandardClientScopes,
5 AuthOrchestrationOperateScope,
6 AuthOrchestrationReadScope,
7 AuthRelayReadScope,
8 AuthRelayWriteScope,
9 AuthReviewWriteScope,
10 AuthTerminalOperateScope,
11 EnvironmentAuthInvalidError,
12 type EnvironmentAuthInvalidReason,
13 EnvironmentHttpApi,
14 EnvironmentInternalError,
15 type EnvironmentInternalErrorReason,
16 EnvironmentOperationForbiddenError,
17 EnvironmentRequestInvalidError,
18 type EnvironmentRequestInvalidReason,
19 EnvironmentScopeRequiredError,
20 EnvironmentAuthenticatedAuth,
21 EnvironmentAuthenticatedPrincipal,
22} from "@t3tools/contracts";
23import type { AuthEnvironmentScope } from "@t3tools/contracts";
24import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
25import { causeErrorTag } from "@t3tools/shared/observability";
26import * as DateTime from "effect/DateTime";
27import * as Effect from "effect/Effect";
28import * as Layer from "effect/Layer";
29import * as Cookies from "effect/unstable/http/Cookies";
30import * as HttpEffect from "effect/unstable/http/HttpEffect";
31import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
32import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
33​
34import * as EnvironmentAuth from "./EnvironmentAuth.ts";
35import * as SessionStore from "./SessionStore.ts";
36import { deriveAuthClientMetadata } from "./utils.ts";
37​
38export const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(
39 Effect.map((span) => span.traceId),
40 Effect.orElseSucceed(() => "unavailable"),
41);
42​
43export function annotateEnvironmentRequest(endpoint: string) {
44 return Effect.gen(function* () {
45 const request = yield* HttpServerRequest.HttpServerRequest;
46 const url = HttpServerRequest.toURL(request);
47 const traceId = yield* currentEnvironmentTraceId;
48​
49 yield* Effect.addFinalizer((exit) =>
50 exit._tag === "Failure"
51 ? Effect.logWarning("environment api request failed", {
52 endpoint,
53 traceId,
54 errorTag: causeErrorTag(exit.cause),
55 cause: exit.cause,
56 })
57 : Effect.void,
58 );
59 yield* Effect.annotateLogsScoped({ "environment.endpoint": endpoint, traceId });
60 yield* Effect.annotateCurrentSpan({
61 "environment.endpoint": endpoint,
62 "http.request.method": request.method,
63 "url.path": url._tag === "Some" ? url.value.pathname : "unknown",
64 });
65 });
67​
68export function failEnvironmentAuthInvalid(reason: EnvironmentAuthInvalidReason) {
69 return currentEnvironmentTraceId.pipe(
70 Effect.flatMap((traceId) =>
71 Effect.fail(new EnvironmentAuthInvalidError({ code: "auth_invalid", reason, traceId })),
72 ),
73 );
75​
76export function failEnvironmentInvalidRequest(reason: EnvironmentRequestInvalidReason) {
77 return currentEnvironmentTraceId.pipe(
78 Effect.flatMap((traceId) =>
79 Effect.fail(new EnvironmentRequestInvalidError({ code: "invalid_request", reason, traceId })),
80 ),
81 );
83​
84export function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope) {
85 return currentEnvironmentTraceId.pipe(
86 Effect.flatMap((traceId) =>
87 Effect.fail(
88 new EnvironmentScopeRequiredError({
89 code: "insufficient_scope",
90 requiredScope,
91 traceId,
92 }),
93 ),
94 ),
95 );
97​
98function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_allowed") {
99 return currentEnvironmentTraceId.pipe(
100 Effect.flatMap((traceId) =>
101 Effect.fail(
102 new EnvironmentOperationForbiddenError({
103 code: "operation_forbidden",
104 reason,
105 traceId,
106 }),
107 ),
108 ),
109 );
111​
112export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
113 return Effect.gen(function* () {
114 const traceId = yield* currentEnvironmentTraceId;
115 if (error !== undefined) {
116 yield* Effect.logError("environment api operation failed", {
117 reason,
118 traceId,
119 cause: error,
120 });
121 }
122 return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
123 });
125​
126export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
127 scope: AuthEnvironmentScope,
128) {
129 const session = yield* EnvironmentAuthenticatedPrincipal;
130 if (!session.scopes.has(scope)) {
131 return yield* failEnvironmentScopeRequired(scope);
132 }
133 return session;
134});
135​
136export const environmentAuthenticatedAuthLayer = Layer.effect(
137 EnvironmentAuthenticatedAuth,
138 Effect.gen(function* () {
139 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
140 return (httpEffect) =>
141 Effect.gen(function* () {
142 const request = yield* HttpServerRequest.HttpServerRequest;
143 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
144 Effect.catchTags({
145 ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
146 ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),
147 }),
148 );
149 return yield* httpEffect.pipe(
150 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
151 ...session,
152 scopes: new Set(session.scopes),
153 }),
154 );
155 });
156 }),
157);
158​
159export const authHttpApiLayer = HttpApiBuilder.group(
160 EnvironmentHttpApi,
161 "auth",
162 Effect.fnUntraced(function* (handlers) {
163 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
164 const sessions = yield* SessionStore.SessionStore;
165​
166 return handlers
167 .handle(
168 "session",
169 Effect.fn("environment.auth.session")(
170 function* (args) {
171 yield* annotateEnvironmentRequest(args.endpoint.name);
172 const request = yield* HttpServerRequest.HttpServerRequest;
173 return yield* serverAuth.getSessionState(request);
174 },
175 Effect.catchTag("ServerAuthInternalError", (error) =>
176 failEnvironmentInternal("internal_error", error),
177 ),
178 ),
179 )
180 .handle(
181 "browserSession",
182 Effect.fn("environment.auth.browserSession")(
183 function* (args) {
184 yield* annotateEnvironmentRequest(args.endpoint.name);
185 const request = yield* HttpServerRequest.HttpServerRequest;
186 const result = yield* serverAuth.createBrowserSession(
187 args.payload.credential,
188 deriveAuthClientMetadata({ request }),
189 );
190 const sessionCookies = yield* Effect.fromResult(
191 Cookies.set(Cookies.empty, sessions.cookieName, result.sessionToken, {
192 expires: DateTime.toDate(result.response.expiresAt),
193 httpOnly: true,
194 path: "/",
195 sameSite: "lax",
196 }),
197 ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")));
198​
199 yield* HttpEffect.appendPreResponseHandler((_request, response) =>
200 Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
201 );
202 return result.response;
203 },
204 Effect.catchTags({
205 ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
206 ServerAuthInternalError: (error) =>
207 failEnvironmentInternal("browser_session_issuance_failed", error),
208 }),
209 ),
210 )
211 .handle(
212 "token",
213 Effect.fn("environment.auth.token")(
214 function* (args) {
215 yield* annotateEnvironmentRequest(args.endpoint.name);
216 const request = yield* HttpServerRequest.HttpServerRequest;
217 const requestedScopes =
218 args.payload.scope === undefined
219 ? undefined
220 : parseAllowedOAuthScope({
221 value: args.payload.scope,
222 allowedScopes: new Set<AuthEnvironmentScope>([
223 AuthOrchestrationReadScope,
224 AuthOrchestrationOperateScope,
225 AuthTerminalOperateScope,
226 AuthReviewWriteScope,
227 AuthAccessReadScope,
228 AuthAccessWriteScope,
229 AuthRelayReadScope,
230 AuthRelayWriteScope,
231 ]),
232 });
233 if (requestedScopes === null)
234 return yield* failEnvironmentInvalidRequest("invalid_scope");
235 return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
236 args.payload.subject_token,
237 requestedScopes,
238 deriveAuthClientMetadata({
239 request,
240 presented: {
241 ...(args.payload.client_label ? { label: args.payload.client_label } : {}),
242 ...(args.payload.client_device_type
243 ? { deviceType: args.payload.client_device_type }
244 : {}),
245 ...(args.payload.client_os ? { os: args.payload.client_os } : {}),
246 },
247 }),
248 );
249 },
250 Effect.catchTags({
251 ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
252 ServerAuthInvalidRequestError: (error) => failEnvironmentInvalidRequest(error.reason),
253 ServerAuthInternalError: (error) =>
254 failEnvironmentInternal("access_token_issuance_failed", error),
255 }),
256 ),
257 )
258 .handle(
259 "webSocketTicket",
260 Effect.fn("environment.auth.webSocketTicket")(
261 function* (args) {
262 yield* annotateEnvironmentRequest(args.endpoint.name);
263 const session = yield* EnvironmentAuthenticatedPrincipal;
264 return yield* serverAuth.issueWebSocketTicket(session);
265 },
266 Effect.catchTag("ServerAuthInternalError", (error) =>
267 failEnvironmentInternal("websocket_ticket_issuance_failed", error),
268 ),
269 ),
270 )
271 .handle(
272 "pairingCredential",
273 Effect.fn("environment.auth.pairingCredential")(
274 function* (args) {
275 yield* annotateEnvironmentRequest(args.endpoint.name);
276 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
277 const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
278 if (
279 delegatedScopes.length === 0 ||
280 new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
281 ) {
282 return yield* failEnvironmentInvalidRequest("invalid_scope");
283 }
284 for (const delegatedScope of delegatedScopes) {
285 if (!session.scopes.has(delegatedScope)) {
286 return yield* failEnvironmentScopeRequired(delegatedScope);
287 }
288 }
289 return yield* serverAuth.issuePairingCredential(args.payload);
290 },
291 Effect.catchTag("ServerAuthInternalError", (error) =>
292 failEnvironmentInternal("pairing_credential_issuance_failed", error),
293 ),
294 ),
295 )
296 .handle(
297 "pairingLinks",
298 Effect.fn("environment.auth.pairingLinks")(
299 function* (args) {
300 yield* annotateEnvironmentRequest(args.endpoint.name);
301 yield* requireEnvironmentScope(AuthAccessReadScope);
302 return yield* serverAuth.listPairingLinks();
303 },
304 Effect.catchTag("ServerAuthInternalError", (error) =>
305 failEnvironmentInternal("pairing_links_load_failed", error),
306 ),
307 ),
308 )
309 .handle(
310 "revokePairingLink",
311 Effect.fn("environment.auth.revokePairingLink")(
312 function* (args) {
313 yield* annotateEnvironmentRequest(args.endpoint.name);
314 yield* requireEnvironmentScope(AuthAccessWriteScope);
315 const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
316 return { revoked };
317 },
318 Effect.catchTag("ServerAuthInternalError", (error) =>
319 failEnvironmentInternal("pairing_link_revoke_failed", error),
320 ),
321 ),
322 )
323 .handle(
324 "clients",
325 Effect.fn("environment.auth.clients")(
326 function* (args) {
327 yield* annotateEnvironmentRequest(args.endpoint.name);
328 const session = yield* requireEnvironmentScope(AuthAccessReadScope);
329 return yield* serverAuth.listClientSessions(session.sessionId);
330 },
331 Effect.catchTag("ServerAuthInternalError", (error) =>
332 failEnvironmentInternal("client_sessions_load_failed", error),
333 ),
334 ),
335 )
336 .handle(
337 "revokeClient",
338 Effect.fn("environment.auth.revokeClient")(
339 function* (args) {
340 yield* annotateEnvironmentRequest(args.endpoint.name);
341 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
342 const revoked = yield* serverAuth.revokeClientSession(
343 session.sessionId,
344 args.payload.sessionId,
345 );
346 return { revoked };
347 },
348 Effect.catchTags({
349 ServerAuthForbiddenOperationError: (error) =>
350 failEnvironmentOperationForbidden(error.reason),
351 ServerAuthInternalError: (error) =>
352 failEnvironmentInternal("client_session_revoke_failed", error),
353 }),
354 ),
355 )
356 .handle(
357 "revokeOtherClients",
358 Effect.fn("environment.auth.revokeOtherClients")(
359 function* (args) {
360 yield* annotateEnvironmentRequest(args.endpoint.name);
361 const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
362 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
363 return { revokedCount };
364 },
365 Effect.catchTag("ServerAuthInternalError", (error) =>
366 failEnvironmentInternal("client_session_revoke_failed", error),
367 ),
368 ),
369 );
370 }),
371);