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