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

EnvironmentAuth.ts

721 lines25.8 KB

1import {
2 AuthAccessTokenType,
3 AuthAccessWriteScope,
4 AuthAdministrativeScopes,
5 AuthStandardClientScopes,
6 type AuthAccessTokenResult,
7 type AuthBrowserSessionResult,
8 type AuthClientMetadata,
9 type AuthClientSession,
10 type AuthCreatePairingCredentialInput,
11 type AuthEnvironmentScope,
12 type AuthPairingLink,
13 type AuthPairingCredentialResult,
14 type AuthSessionId,
15 type AuthSessionState,
16 type ServerAuthDescriptor,
17 type ServerAuthSessionMethod,
18 type AuthWebSocketTicketResult,
19} from "@t3tools/contracts";
20import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
21import * as Context from "effect/Context";
22import * as Crypto from "effect/Crypto";
23import * as Data from "effect/Data";
24import * as DateTime from "effect/DateTime";
25import * as Duration from "effect/Duration";
26import * as Effect from "effect/Effect";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
30​
31import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
32import * as PairingGrantStore from "./PairingGrantStore.ts";
33import * as ServerSecretStore from "./ServerSecretStore.ts";
34import * as SessionStore from "./SessionStore.ts";
35import { verifyRequestDpopProof } from "./dpop.ts";
36import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sqlite.ts";
37​
38export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
39export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
40​
41export interface IssuedPairingLink {
42 readonly id: string;
43 readonly credential: string;
44 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
45 readonly subject: string;
46 readonly label?: string;
47 readonly createdAt: DateTime.Utc;
48 readonly expiresAt: DateTime.Utc;
50​
51export interface IssuedBearerSession {
52 readonly sessionId: AuthSessionId;
53 readonly token: string;
54 readonly method: "bearer-access-token";
55 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
56 readonly subject: string;
57 readonly client: AuthClientMetadata;
58 readonly expiresAt: DateTime.Utc;
60​
61export interface AuthenticatedSession {
62 readonly sessionId: AuthSessionId;
63 readonly subject: string;
64 readonly method: ServerAuthSessionMethod;
65 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
66 readonly proofKeyThumbprint?: string;
67 readonly expiresAt?: DateTime.DateTime;
69​
70export class ServerAuthInternalError extends Data.TaggedError("ServerAuthInternalError")<{
71 readonly message: string;
72 readonly cause?: unknown;
73}> {}
74​
75export class ServerAuthInvalidCredentialError extends Data.TaggedError(
76 "ServerAuthInvalidCredentialError",
77)<{
78 readonly reason: "missing_credential" | "invalid_credential";
79 readonly cause?: unknown;
80}> {}
81​
82export class ServerAuthInvalidRequestError extends Data.TaggedError(
83 "ServerAuthInvalidRequestError",
84)<{
85 readonly reason: "invalid_scope" | "scope_not_granted";
86}> {}
87​
88export class ServerAuthForbiddenOperationError extends Data.TaggedError(
89 "ServerAuthForbiddenOperationError",
90)<{
91 readonly reason: "current_session_revoke_not_allowed";
92}> {}
93​
94export interface EnvironmentAuthShape {
95 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
96 readonly getSessionState: (
97 request: HttpServerRequest.HttpServerRequest,
98 ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
99 readonly createBrowserSession: (
100 credential: string,
101 requestMetadata: AuthClientMetadata,
102 ) => Effect.Effect<
103 {
104 readonly response: AuthBrowserSessionResult;
105 readonly sessionToken: string;
106 },
107 ServerAuthInvalidCredentialError | ServerAuthInternalError
108 >;
109 readonly exchangeBootstrapCredentialForAccessToken: (
110 credential: string,
111 requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
112 requestMetadata: AuthClientMetadata,
113 input?: {
114 readonly proofKeyThumbprint?: string;
115 },
116 ) => Effect.Effect<
117 AuthAccessTokenResult,
118 ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
119 >;
120 readonly createPairingLink: (input?: {
121 readonly ttl?: Duration.Duration;
122 readonly label?: string;
123 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
124 readonly subject?: string;
125 readonly proofKeyThumbprint?: string;
126 }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
127 readonly issuePairingCredential: (
128 input?: AuthCreatePairingCredentialInput,
129 ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
130 readonly issueStartupPairingCredential: () => Effect.Effect<
131 AuthPairingCredentialResult,
132 ServerAuthInternalError
133 >;
134 readonly listPairingLinks: (input?: {
135 readonly excludeSubjects?: ReadonlyArray<string>;
136 }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
137 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
138 readonly issueSession: (input?: {
139 readonly ttl?: Duration.Duration;
140 readonly subject?: string;
141 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
142 readonly label?: string;
143 }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
144 readonly listSessions: () => Effect.Effect<
145 ReadonlyArray<AuthClientSession>,
146 ServerAuthInternalError
147 >;
148 readonly revokeSession: (
149 sessionId: AuthSessionId,
150 ) => Effect.Effect<boolean, ServerAuthInternalError>;
151 readonly revokeOtherSessionsExcept: (
152 sessionId: AuthSessionId,
153 ) => Effect.Effect<number, ServerAuthInternalError>;
154 readonly listClientSessions: (
155 currentSessionId: AuthSessionId,
156 ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
157 readonly revokeClientSession: (
158 currentSessionId: AuthSessionId,
159 targetSessionId: AuthSessionId,
160 ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
161 readonly revokeOtherClientSessions: (
162 currentSessionId: AuthSessionId,
163 ) => Effect.Effect<number, ServerAuthInternalError>;
164 readonly authenticateHttpRequest: (
165 request: HttpServerRequest.HttpServerRequest,
166 ) => Effect.Effect<
167 AuthenticatedSession,
168 ServerAuthInvalidCredentialError | ServerAuthInternalError
169 >;
170 readonly authenticateWebSocketUpgrade: (
171 request: HttpServerRequest.HttpServerRequest,
172 ) => Effect.Effect<
173 AuthenticatedSession,
174 ServerAuthInvalidCredentialError | ServerAuthInternalError
175 >;
176 readonly issueWebSocketTicket: (
177 session: Pick<AuthenticatedSession, "sessionId">,
178 ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
179 readonly issueStartupPairingUrl: (
180 baseUrl: string,
181 ) => Effect.Effect<string, ServerAuthInternalError>;
183​
184export class EnvironmentAuth extends Context.Service<EnvironmentAuth, EnvironmentAuthShape>()(
185 "t3/auth/EnvironmentAuth",
186) {}
187​
188type BootstrapExchangeResult = {
189 readonly response: AuthBrowserSessionResult;
190 readonly sessionToken: string;
191};
192​
193const AUTHORIZATION_PREFIX = "Bearer ";
194const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
195const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
196​
197const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
198 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
199 const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
200 if (leftCanManage !== rightCanManage) {
201 return leftCanManage ? -1 : 1;
202 }
203 if (left.connected !== right.connected) {
204 return left.connected ? -1 : 1;
205 }
206 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
207};
208​
209const toInternalError =
210 (message: string) =>
211 (cause: unknown): ServerAuthInternalError =>
212 new ServerAuthInternalError({ message, cause });
213​
214export function toBootstrapExchangeError(
215 cause: PairingGrantStore.BootstrapCredentialError,
216): ServerAuthInvalidCredentialError | ServerAuthInternalError {
217 if (cause._tag === "BootstrapCredentialInternalError") {
218 return new ServerAuthInternalError({
219 message: "Failed to validate bootstrap credential.",
220 cause,
221 });
222 }
223​
224 return new ServerAuthInvalidCredentialError({
225 reason: "invalid_credential",
226 cause,
227 });
229​
230const mapSessionVerificationErrors = <A, R>(
231 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
232): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
233 effect.pipe(
234 Effect.catchTags({
235 SessionCredentialInvalidError: (cause) =>
236 Effect.fail(new ServerAuthInvalidCredentialError({ reason: "invalid_credential", cause })),
237 SessionCredentialInternalError: (cause) =>
238 Effect.fail(
239 new ServerAuthInternalError({
240 message: "Failed to validate session credential.",
241 cause,
242 }),
243 ),
244 }),
245 );
246​
247function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
248 const header = request.headers["authorization"];
249 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
250 return null;
251 }
252 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
253 return token.length > 0 ? token : null;
255​
256function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {
257 const header = request.headers["authorization"];
258 if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {
259 return null;
260 }
261 const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();
262 return token.length > 0 ? token : null;
264​
265export const make = Effect.fn("makeEnvironmentAuth")(function* () {
266 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
267 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
268 const sessions = yield* SessionStore.SessionStore;
269 const secretStore = yield* ServerSecretStore.ServerSecretStore;
270 const crypto = yield* Crypto.Crypto;
271 const descriptor = yield* policy.getDescriptor();
272​
273 const authenticateToken = (
274 token: string,
275 ): Effect.Effect<
276 AuthenticatedSession,
277 ServerAuthInvalidCredentialError | ServerAuthInternalError
278 > =>
279 sessions.verify(token).pipe(
280 Effect.tapErrorTag("SessionCredentialInvalidError", (cause) =>
281 Effect.logWarning("Rejected authenticated session credential.").pipe(
282 Effect.annotateLogs({
283 reason: cause.message,
284 }),
285 ),
286 ),
287 Effect.map((session) => ({
288 sessionId: session.sessionId,
289 subject: session.subject,
290 method: session.method,
291 scopes: session.scopes,
292 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
293 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
294 })),
295 mapSessionVerificationErrors,
296 );
297​
298 const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
299 const cookieToken = request.cookies[sessions.cookieName];
300 const bearerToken = parseBearerToken(request);
301 const dpopToken = parseDpopToken(request);
302 const credential = cookieToken ?? bearerToken ?? dpopToken;
303 if (!credential) {
304 return Effect.fail(new ServerAuthInvalidCredentialError({ reason: "missing_credential" }));
305 }
306 return authenticateToken(credential).pipe(
307 Effect.flatMap((session) => {
308 if (session.proofKeyThumbprint) {
309 if (!dpopToken || dpopToken !== credential) {
310 return Effect.fail(
311 new ServerAuthInvalidCredentialError({
312 reason: "invalid_credential",
313 cause: "DPoP-bound access token requires DPoP authorization.",
314 }),
315 );
316 }
317 return verifyRequestDpopProof({
318 request,
319 expectedThumbprint: session.proofKeyThumbprint,
320 expectedAccessToken: dpopToken,
321 }).pipe(
322 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
323 Effect.provideService(Crypto.Crypto, crypto),
324 Effect.as(session),
325 );
326 }
327 if (dpopToken) {
328 return Effect.fail(
329 new ServerAuthInvalidCredentialError({
330 reason: "invalid_credential",
331 cause: "DPoP authorization requires a proof-bound access token.",
332 }),
333 );
334 }
335 return Effect.succeed(session);
336 }),
337 );
338 };
339​
340 const getSessionState: EnvironmentAuthShape["getSessionState"] = (request) =>
341 authenticateRequest(request).pipe(
342 Effect.map(
343 (session) =>
344 ({
345 authenticated: true,
346 auth: descriptor,
347 scopes: session.scopes,
348 sessionMethod: session.method,
349 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
350 }) satisfies AuthSessionState,
351 ),
352 Effect.catchTag("ServerAuthInvalidCredentialError", () =>
353 Effect.succeed({
354 authenticated: false,
355 auth: descriptor,
356 } satisfies AuthSessionState),
357 ),
358 Effect.withSpan("EnvironmentAuth.getSessionState"),
359 );
360​
361 const createBrowserSession: EnvironmentAuthShape["createBrowserSession"] = (
362 credential,
363 requestMetadata,
364 ) =>
365 bootstrapCredentials.consume(credential).pipe(
366 Effect.mapError(toBootstrapExchangeError),
367 Effect.flatMap((grant) =>
368 sessions
369 .issue({
370 method: "browser-session-cookie",
371 subject: grant.subject,
372 scopes: grant.scopes,
373 client: {
374 ...requestMetadata,
375 ...(grant.label ? { label: grant.label } : {}),
376 },
377 })
378 .pipe(
379 Effect.mapError(
380 (cause) =>
381 new ServerAuthInternalError({
382 message: "Failed to issue authenticated session.",
383 cause,
384 }),
385 ),
386 ),
387 ),
388 Effect.map(
389 (session) =>
390 ({
391 response: {
392 authenticated: true,
393 scopes: session.scopes,
394 sessionMethod: session.method,
395 expiresAt: DateTime.toUtc(session.expiresAt),
396 } satisfies AuthBrowserSessionResult,
397 sessionToken: session.token,
398 }) satisfies BootstrapExchangeResult,
399 ),
400 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
401 );
402​
403 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuthShape["exchangeBootstrapCredentialForAccessToken"] =
404 (credential, requestedScopes, requestMetadata, input) =>
405 bootstrapCredentials.consume(credential, input).pipe(
406 Effect.mapError(toBootstrapExchangeError),
407 Effect.flatMap((grant) =>
408 Effect.gen(function* () {
409 const grantedScopes = requestedScopes ?? grant.scopes;
410 if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
411 return yield* new ServerAuthInvalidRequestError({
412 reason: "scope_not_granted",
413 });
414 }
415 return yield* sessions
416 .issue({
417 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
418 subject: grant.subject,
419 scopes: grantedScopes,
420 ...(input?.proofKeyThumbprint
421 ? {
422 proofKeyThumbprint: input.proofKeyThumbprint,
423 ttl: Duration.hours(1),
424 }
425 : {}),
426 client: {
427 ...requestMetadata,
428 ...(grant.label ? { label: grant.label } : {}),
429 },
430 })
431 .pipe(
432 Effect.mapError(
433 (cause) =>
434 new ServerAuthInternalError({
435 message: "Failed to issue authenticated access token.",
436 cause,
437 }),
438 ),
439 );
440 }),
441 ),
442 Effect.flatMap((session) =>
443 DateTime.now.pipe(
444 Effect.map(
445 (now) =>
446 ({
447 access_token: session.token,
448 issued_token_type: AuthAccessTokenType,
449 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
450 expires_in: Math.max(
451 0,
452 Math.floor(
453 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
454 ),
455 ),
456 scope: encodeOAuthScope(session.scopes),
457 }) satisfies AuthAccessTokenResult,
458 ),
459 ),
460 ),
461 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
462 );
463​
464 const issuePairingCredentialForSubject = (input: {
465 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
466 readonly subject: string;
467 readonly label?: string;
468 }) =>
469 createPairingLink({
470 scopes: input.scopes,
471 subject: input.subject,
472 ...(input.label ? { label: input.label } : {}),
473 }).pipe(
474 Effect.map(
475 (issued) =>
476 ({
477 id: issued.id,
478 credential: issued.credential,
479 ...(issued.label ? { label: issued.label } : {}),
480 expiresAt: issued.expiresAt,
481 }) satisfies AuthPairingCredentialResult,
482 ),
483 );
484​
485 const createPairingLink: EnvironmentAuthShape["createPairingLink"] = Effect.fn(
486 "EnvironmentAuth.createPairingLink",
487 )(
488 function* (input) {
489 const createdAt = yield* DateTime.now;
490 const issued = yield* bootstrapCredentials.issueOneTimeToken({
491 scopes: input?.scopes ?? AuthStandardClientScopes,
492 subject: input?.subject ?? "one-time-token",
493 ...(input?.ttl ? { ttl: input.ttl } : {}),
494 ...(input?.label ? { label: input.label } : {}),
495 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
496 });
497 return {
498 id: issued.id,
499 credential: issued.credential,
500 scopes: input?.scopes ?? AuthStandardClientScopes,
501 subject: input?.subject ?? "one-time-token",
502 ...(issued.label ? { label: issued.label } : {}),
503 createdAt: DateTime.toUtc(createdAt),
504 expiresAt: DateTime.toUtc(issued.expiresAt),
505 } satisfies IssuedPairingLink;
506 },
507 Effect.mapError(toInternalError("Failed to create pairing link.")),
508 );
509​
510 const listPairingLinks: EnvironmentAuthShape["listPairingLinks"] = (input) =>
511 bootstrapCredentials.listActive().pipe(
512 Effect.map((pairingLinks) => {
513 const excludedSubjects = input?.excludeSubjects ?? [
514 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
515 ];
516 return pairingLinks
517 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
518 .toSorted(
519 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
520 );
521 }),
522 Effect.mapError(toInternalError("Failed to list pairing links.")),
523 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
524 );
525​
526 const revokePairingLink: EnvironmentAuthShape["revokePairingLink"] = (id) =>
527 bootstrapCredentials
528 .revoke(id)
529 .pipe(
530 Effect.mapError(toInternalError("Failed to revoke pairing link.")),
531 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
532 );
533​
534 const issueSession: EnvironmentAuthShape["issueSession"] = (input) =>
535 sessions
536 .issue({
537 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
538 method: "bearer-access-token",
539 scopes: input?.scopes ?? AuthAdministrativeScopes,
540 client: {
541 ...(input?.label ? { label: input.label } : {}),
542 deviceType: "bot",
543 },
544 ...(input?.ttl ? { ttl: input.ttl } : {}),
545 })
546 .pipe(
547 Effect.map(
548 (issued) =>
549 ({
550 sessionId: issued.sessionId,
551 token: issued.token,
552 method: "bearer-access-token",
553 scopes: issued.scopes,
554 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
555 client: issued.client,
556 expiresAt: DateTime.toUtc(issued.expiresAt),
557 }) satisfies IssuedBearerSession,
558 ),
559 Effect.mapError(toInternalError("Failed to issue session token.")),
560 Effect.withSpan("EnvironmentAuth.issueSession"),
561 );
562​
563 const listSessions: EnvironmentAuthShape["listSessions"] = () =>
564 sessions.listActive().pipe(
565 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
566 Effect.mapError(toInternalError("Failed to list sessions.")),
567 Effect.withSpan("EnvironmentAuth.listSessions"),
568 );
569​
570 const revokeSession: EnvironmentAuthShape["revokeSession"] = (sessionId) =>
571 sessions
572 .revoke(sessionId)
573 .pipe(
574 Effect.mapError(toInternalError("Failed to revoke session.")),
575 Effect.withSpan("EnvironmentAuth.revokeSession"),
576 );
577​
578 const revokeOtherSessionsExcept: EnvironmentAuthShape["revokeOtherSessionsExcept"] = (
579 sessionId,
580 ) =>
581 sessions
582 .revokeAllExcept(sessionId)
583 .pipe(
584 Effect.mapError(toInternalError("Failed to revoke other sessions.")),
585 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
586 );
587​
588 const issuePairingCredential: EnvironmentAuthShape["issuePairingCredential"] = (input) =>
589 issuePairingCredentialForSubject({
590 scopes: input?.scopes ?? AuthStandardClientScopes,
591 subject: "one-time-token",
592 ...(input?.label ? { label: input.label } : {}),
593 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
594​
595 const issueStartupPairingCredential: EnvironmentAuthShape["issueStartupPairingCredential"] = () =>
596 issuePairingCredentialForSubject({
597 scopes: AuthAdministrativeScopes,
598 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
599 }).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
600​
601 const listClientSessions: EnvironmentAuthShape["listClientSessions"] = (currentSessionId) =>
602 listSessions().pipe(
603 Effect.map((clientSessions) =>
604 clientSessions.map(
605 (clientSession): AuthClientSession => ({
606 ...clientSession,
607 current: clientSession.sessionId === currentSessionId,
608 }),
609 ),
610 ),
611 Effect.withSpan("EnvironmentAuth.listClientSessions"),
612 );
613​
614 const revokeClientSession: EnvironmentAuthShape["revokeClientSession"] = Effect.fn(
615 "EnvironmentAuth.revokeClientSession",
616 )(function* (currentSessionId, targetSessionId) {
617 if (currentSessionId === targetSessionId) {
618 return yield* new ServerAuthForbiddenOperationError({
619 reason: "current_session_revoke_not_allowed",
620 });
621 }
622 return yield* revokeSession(targetSessionId);
623 });
624​
625 const revokeOtherClientSessions: EnvironmentAuthShape["revokeOtherClientSessions"] = (
626 currentSessionId,
627 ) =>
628 revokeOtherSessionsExcept(currentSessionId).pipe(
629 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
630 );
631​
632 const issueStartupPairingUrl: EnvironmentAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
633 issueStartupPairingCredential().pipe(
634 Effect.map((issued) => {
635 const url = new URL(baseUrl);
636 url.pathname = "/pair";
637 url.searchParams.delete("token");
638 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
639 return url.toString();
640 }),
641 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
642 );
643​
644 const issueWebSocketTicket: EnvironmentAuthShape["issueWebSocketTicket"] = (session) =>
645 sessions.issueWebSocketToken(session.sessionId).pipe(
646 Effect.mapError(
647 (cause) =>
648 new ServerAuthInternalError({
649 message: "Failed to issue websocket token.",
650 cause,
651 }),
652 ),
653 Effect.map(
654 (issued) =>
655 ({
656 ticket: issued.token,
657 expiresAt: DateTime.toUtc(issued.expiresAt),
658 }) satisfies AuthWebSocketTicketResult,
659 ),
660 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
661 );
662​
663 const authenticateHttpRequest: EnvironmentAuthShape["authenticateHttpRequest"] = (request) =>
664 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
665​
666 const authenticateWebSocketUpgrade: EnvironmentAuthShape["authenticateWebSocketUpgrade"] =
667 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
668 const requestUrl = HttpServerRequest.toURL(request);
669 if (Option.isSome(requestUrl)) {
670 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
671 if (websocketTicket && websocketTicket.trim().length > 0) {
672 return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
673 Effect.map((session) => ({
674 sessionId: session.sessionId,
675 subject: session.subject,
676 method: session.method,
677 scopes: session.scopes,
678 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
679 })),
680 mapSessionVerificationErrors,
681 );
682 }
683 }
684​
685 return yield* authenticateRequest(request);
686 });
687​
688 return {
689 getDescriptor: () =>
690 Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
691 getSessionState,
692 createBrowserSession,
693 exchangeBootstrapCredentialForAccessToken,
694 createPairingLink,
695 issuePairingCredential,
696 issueStartupPairingCredential,
697 listPairingLinks,
698 revokePairingLink,
699 issueSession,
700 listSessions,
701 revokeSession,
702 revokeOtherSessionsExcept,
703 listClientSessions,
704 revokeClientSession,
705 revokeOtherClientSessions,
706 authenticateHttpRequest,
707 authenticateWebSocketUpgrade,
708 issueWebSocketTicket,
709 issueStartupPairingUrl,
710 } satisfies EnvironmentAuthShape;
711});
712​
713export const layer = Layer.effect(EnvironmentAuth, make()).pipe(
714 Layer.provideMerge(PairingGrantStore.layer),
715 Layer.provideMerge(SessionStore.layer),
716 Layer.provideMerge(EnvironmentAuthPolicy.layer),
717);
718​
719export const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);
720​
721export const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));