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

EnvironmentAuth.ts

996 lines34.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 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 Schema from "effect/Schema";
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​
70const serverAuthInternalErrorContext = {
71 cause: Schema.Defect(),
72};
73​
74export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthBootstrapCredentialValidationError>()(
75 "ServerAuthBootstrapCredentialValidationError",
76 {
77 ...serverAuthInternalErrorContext,
78 },
79) {
80 override get message(): string {
81 return "Failed to validate bootstrap credential.";
82 }
84​
85export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
86 "ServerAuthSessionCredentialValidationError",
87 {
88 ...serverAuthInternalErrorContext,
89 },
90) {
91 override get message(): string {
92 return "Failed to validate session credential.";
93 }
95​
96export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
97 "ServerAuthAuthenticatedSessionIssueError",
98 {
99 ...serverAuthInternalErrorContext,
100 },
101) {
102 override get message(): string {
103 return "Failed to issue authenticated session.";
104 }
106​
107export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
108 "ServerAuthAuthenticatedAccessTokenIssueError",
109 {
110 ...serverAuthInternalErrorContext,
111 },
112) {
113 override get message(): string {
114 return "Failed to issue authenticated access token.";
115 }
117​
118export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
119 "ServerAuthPairingLinkCreationError",
120 {
121 ...serverAuthInternalErrorContext,
122 },
123) {
124 override get message(): string {
125 return "Failed to create pairing link.";
126 }
128​
129export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<ServerAuthPairingLinksListError>()(
130 "ServerAuthPairingLinksListError",
131 {
132 ...serverAuthInternalErrorContext,
133 },
134) {
135 override get message(): string {
136 return "Failed to list pairing links.";
137 }
139​
140export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
141 "ServerAuthPairingLinkRevocationError",
142 {
143 ...serverAuthInternalErrorContext,
144 },
145) {
146 override get message(): string {
147 return "Failed to revoke pairing link.";
148 }
150​
151export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
152 "ServerAuthSessionTokenIssueError",
153 {
154 ...serverAuthInternalErrorContext,
155 },
156) {
157 override get message(): string {
158 return "Failed to issue session token.";
159 }
161​
162export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerAuthSessionsListError>()(
163 "ServerAuthSessionsListError",
164 {
165 ...serverAuthInternalErrorContext,
166 },
167) {
168 override get message(): string {
169 return "Failed to list sessions.";
170 }
172​
173export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
174 "ServerAuthSessionRevocationError",
175 {
176 ...serverAuthInternalErrorContext,
177 },
178) {
179 override get message(): string {
180 return "Failed to revoke session.";
181 }
183​
184export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
185 "ServerAuthOtherSessionsRevocationError",
186 {
187 ...serverAuthInternalErrorContext,
188 },
189) {
190 override get message(): string {
191 return "Failed to revoke other sessions.";
192 }
194​
195export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
196 "ServerAuthWebSocketTokenIssueError",
197 {
198 ...serverAuthInternalErrorContext,
199 },
200) {
201 override get message(): string {
202 return "Failed to issue websocket token.";
203 }
205​
206export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
207 "ServerAuthDpopReplayStateRecordError",
208 {
209 ...serverAuthInternalErrorContext,
210 },
211) {
212 override get message(): string {
213 return "Failed to record DPoP proof replay state.";
214 }
216​
217export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
218 "ServerAuthDpopReplayKeyCalculationError",
219 {
220 ...serverAuthInternalErrorContext,
221 },
222) {
223 override get message(): string {
224 return "Failed to calculate DPoP replay key.";
225 }
227​
228export class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountVerificationError>()(
229 "ServerAuthLinkedCloudAccountVerificationError",
230 {
231 ...serverAuthInternalErrorContext,
232 },
233) {
234 override get message(): string {
235 return "Could not verify the linked cloud account.";
236 }
238​
239export class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountReadError>()(
240 "ServerAuthLinkedCloudAccountReadError",
241 {
242 ...serverAuthInternalErrorContext,
243 },
244) {
245 override get message(): string {
246 return "Could not read the linked cloud account.";
247 }
249​
250export class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountMissingError>()(
251 "ServerAuthLinkedCloudAccountMissingError",
252 {},
253) {
254 override get message(): string {
255 return "Cloud linked user is not installed for this environment.";
256 }
258​
259export class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudLinkJwtSigningError>()(
260 "ServerAuthCloudLinkJwtSigningError",
261 {
262 ...serverAuthInternalErrorContext,
263 },
264) {
265 override get message(): string {
266 return "Failed to sign cloud link JWT.";
267 }
269​
270export class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedErrorClass<ServerAuthCloudMintPublicKeyMissingError>()(
271 "ServerAuthCloudMintPublicKeyMissingError",
272 {},
273) {
274 override get message(): string {
275 return "Cloud mint public key is not installed for this environment.";
276 }
278​
279export class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedErrorClass<ServerAuthCloudRelayIssuerMissingError>()(
280 "ServerAuthCloudRelayIssuerMissingError",
281 {},
282) {
283 override get message(): string {
284 return "Cloud relay issuer is not installed for this environment.";
285 }
287​
288export class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudHealthJwtSigningError>()(
289 "ServerAuthCloudHealthJwtSigningError",
290 {
291 ...serverAuthInternalErrorContext,
292 },
293) {
294 override get message(): string {
295 return "Failed to sign cloud health JWT.";
296 }
298​
299export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudMintJwtSigningError>()(
300 "ServerAuthCloudMintJwtSigningError",
301 {
302 ...serverAuthInternalErrorContext,
303 },
304) {
305 override get message(): string {
306 return "Failed to sign cloud mint JWT.";
307 }
309​
310export const ServerAuthInternalError = Schema.Union([
311 ServerAuthBootstrapCredentialValidationError,
312 ServerAuthSessionCredentialValidationError,
313 ServerAuthAuthenticatedSessionIssueError,
314 ServerAuthAuthenticatedAccessTokenIssueError,
315 ServerAuthPairingLinkCreationError,
316 ServerAuthPairingLinksListError,
317 ServerAuthPairingLinkRevocationError,
318 ServerAuthSessionTokenIssueError,
319 ServerAuthSessionsListError,
320 ServerAuthSessionRevocationError,
321 ServerAuthOtherSessionsRevocationError,
322 ServerAuthWebSocketTokenIssueError,
323 ServerAuthDpopReplayStateRecordError,
324 ServerAuthDpopReplayKeyCalculationError,
325 ServerAuthLinkedCloudAccountVerificationError,
326 ServerAuthLinkedCloudAccountReadError,
327 ServerAuthLinkedCloudAccountMissingError,
328 ServerAuthCloudLinkJwtSigningError,
329 ServerAuthCloudMintPublicKeyMissingError,
330 ServerAuthCloudRelayIssuerMissingError,
331 ServerAuthCloudHealthJwtSigningError,
332 ServerAuthCloudMintJwtSigningError,
333]);
334export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
335export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
336​
337export class ServerAuthMissingCredentialError extends Schema.TaggedErrorClass<ServerAuthMissingCredentialError>()(
338 "ServerAuthMissingCredentialError",
339 {},
340) {
341 override get message(): string {
342 return "Server authentication credential is missing.";
343 }
345​
346export class ServerAuthInvalidCredentialError extends Schema.TaggedErrorClass<ServerAuthInvalidCredentialError>()(
347 "ServerAuthInvalidCredentialError",
348 {
349 diagnostic: Schema.optional(Schema.String),
350 cause: Schema.optional(Schema.Defect()),
351 },
352) {
353 override get message(): string {
354 return "Server authentication credential is invalid.";
355 }
357​
358export const ServerAuthCredentialError = Schema.Union([
359 ServerAuthMissingCredentialError,
360 ServerAuthInvalidCredentialError,
361]);
362export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
363export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
364export const serverAuthCredentialReason = (
365 error: ServerAuthCredentialError,
366): "missing_credential" | "invalid_credential" =>
367 error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
368​
369export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
370 "ServerAuthInvalidScopeError",
371 {},
372) {
373 override get message(): string {
374 return "The requested authentication scope is invalid.";
375 }
377​
378export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
379 "ServerAuthScopeNotGrantedError",
380 {},
381) {
382 override get message(): string {
383 return "The requested authentication scope was not granted.";
384 }
386​
387export const ServerAuthInvalidRequestError = Schema.Union([
388 ServerAuthInvalidScopeError,
389 ServerAuthScopeNotGrantedError,
390]);
391export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
392export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
393export const serverAuthInvalidRequestReason = (
394 error: ServerAuthInvalidRequestError,
395): "invalid_scope" | "scope_not_granted" =>
396 error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
397​
398export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
399 "ServerAuthForbiddenOperationError",
400 {},
401) {
402 override get message(): string {
403 return "The current authentication session cannot revoke itself.";
404 }
406​
407export class EnvironmentAuth extends Context.Service<
408 EnvironmentAuth,
409 {
410 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
411 readonly getSessionState: (
412 request: HttpServerRequest.HttpServerRequest,
413 ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
414 readonly createBrowserSession: (
415 credential: string,
416 requestMetadata: AuthClientMetadata,
417 ) => Effect.Effect<
418 {
419 readonly response: AuthBrowserSessionResult;
420 readonly sessionToken: string;
421 },
422 ServerAuthInvalidCredentialError | ServerAuthInternalError
423 >;
424 readonly exchangeBootstrapCredentialForAccessToken: (
425 credential: string,
426 requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
427 requestMetadata: AuthClientMetadata,
428 input?: {
429 readonly proofKeyThumbprint?: string;
430 },
431 ) => Effect.Effect<
432 AuthAccessTokenResult,
433 ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
434 >;
435 readonly createPairingLink: (input?: {
436 readonly ttl?: Duration.Duration;
437 readonly label?: string;
438 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
439 readonly subject?: string;
440 readonly proofKeyThumbprint?: string;
441 readonly purpose?: "startup";
442 }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
443 readonly issuePairingCredential: (
444 input?: AuthCreatePairingCredentialInput,
445 ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
446 readonly issueStartupPairingCredential: () => Effect.Effect<
447 AuthPairingCredentialResult,
448 ServerAuthInternalError
449 >;
450 readonly listPairingLinks: (input?: {
451 readonly excludeSubjects?: ReadonlyArray<string>;
452 }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
453 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
454 readonly issueSession: (input?: {
455 readonly ttl?: Duration.Duration;
456 readonly subject?: string;
457 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
458 readonly label?: string;
459 }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
460 readonly listSessions: () => Effect.Effect<
461 ReadonlyArray<AuthClientSession>,
462 ServerAuthInternalError
463 >;
464 readonly revokeSession: (
465 sessionId: AuthSessionId,
466 ) => Effect.Effect<boolean, ServerAuthInternalError>;
467 readonly revokeOtherSessionsExcept: (
468 sessionId: AuthSessionId,
469 ) => Effect.Effect<number, ServerAuthInternalError>;
470 readonly listClientSessions: (
471 currentSessionId: AuthSessionId,
472 ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
473 readonly revokeClientSession: (
474 currentSessionId: AuthSessionId,
475 targetSessionId: AuthSessionId,
476 ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
477 readonly revokeOtherClientSessions: (
478 currentSessionId: AuthSessionId,
479 ) => Effect.Effect<number, ServerAuthInternalError>;
480 readonly authenticateHttpRequest: (
481 request: HttpServerRequest.HttpServerRequest,
482 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
483 readonly authenticateWebSocketUpgrade: (
484 request: HttpServerRequest.HttpServerRequest,
485 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
486 readonly issueWebSocketTicket: (
487 session: Pick<AuthenticatedSession, "sessionId">,
488 ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
489 readonly issueStartupPairingUrl: (
490 baseUrl: string,
491 ) => Effect.Effect<string, ServerAuthInternalError>;
492 }
493>()("t3/auth/EnvironmentAuth") {}
494​
495type BootstrapExchangeResult = {
496 readonly response: AuthBrowserSessionResult;
497 readonly sessionToken: string;
498};
499​
500const AUTHORIZATION_PREFIX = "Bearer ";
501const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
502const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
503​
504const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
505 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
506 const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
507 if (leftCanManage !== rightCanManage) {
508 return leftCanManage ? -1 : 1;
509 }
510 if (left.connected !== right.connected) {
511 return left.connected ? -1 : 1;
512 }
513 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
514};
515​
516export function toBootstrapExchangeError(
517 cause: PairingGrantStore.BootstrapCredentialError,
518): ServerAuthInvalidCredentialError | ServerAuthInternalError {
519 if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
520 return new ServerAuthBootstrapCredentialValidationError({ cause });
521 }
522​
523 return new ServerAuthInvalidCredentialError({
524 cause,
525 });
527​
528const mapSessionVerificationErrors = <A, R>(
529 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
530): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
531 effect.pipe(
532 Effect.mapError((cause) =>
533 SessionStore.isSessionCredentialInvalidError(cause)
534 ? new ServerAuthInvalidCredentialError({ cause })
535 : new ServerAuthSessionCredentialValidationError({ cause }),
536 ),
537 );
538​
539function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
540 const header = request.headers["authorization"];
541 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
542 return null;
543 }
544 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
545 return token.length > 0 ? token : null;
547​
548function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {
549 const header = request.headers["authorization"];
550 if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {
551 return null;
552 }
553 const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();
554 return token.length > 0 ? token : null;
556​
557export const make = Effect.gen(function* () {
558 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
559 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
560 const sessions = yield* SessionStore.SessionStore;
561 const secretStore = yield* ServerSecretStore.ServerSecretStore;
562 const crypto = yield* Crypto.Crypto;
563 const descriptor = yield* policy.getDescriptor();
564​
565 const authenticateToken = (
566 token: string,
567 ): Effect.Effect<
568 AuthenticatedSession,
569 ServerAuthInvalidCredentialError | ServerAuthInternalError
570 > =>
571 sessions.verify(token).pipe(
572 Effect.tapError((cause) =>
573 SessionStore.isSessionCredentialInvalidError(cause)
574 ? Effect.logWarning("Rejected authenticated session credential.").pipe(
575 Effect.annotateLogs({
576 reason: cause.message,
577 }),
578 )
579 : Effect.void,
580 ),
581 Effect.map((session) => ({
582 sessionId: session.sessionId,
583 subject: session.subject,
584 method: session.method,
585 scopes: session.scopes,
586 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
587 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
588 })),
589 mapSessionVerificationErrors,
590 );
591​
592 const authenticateRequest = (
593 request: HttpServerRequest.HttpServerRequest,
594 ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
595 const cookieToken = request.cookies[sessions.cookieName];
596 const bearerToken = parseBearerToken(request);
597 const dpopToken = parseDpopToken(request);
598 const credential = cookieToken ?? bearerToken ?? dpopToken;
599 if (!credential) {
600 return Effect.fail(new ServerAuthMissingCredentialError({}));
601 }
602 return authenticateToken(credential).pipe(
603 Effect.flatMap((session) => {
604 if (session.proofKeyThumbprint) {
605 if (!dpopToken || dpopToken !== credential) {
606 return Effect.fail(
607 new ServerAuthInvalidCredentialError({
608 diagnostic: "DPoP-bound access token requires DPoP authorization.",
609 }),
610 );
611 }
612 return verifyRequestDpopProof({
613 request,
614 expectedThumbprint: session.proofKeyThumbprint,
615 expectedAccessToken: dpopToken,
616 }).pipe(
617 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
618 Effect.provideService(Crypto.Crypto, crypto),
619 Effect.as(session),
620 );
621 }
622 if (dpopToken) {
623 return Effect.fail(
624 new ServerAuthInvalidCredentialError({
625 diagnostic: "DPoP authorization requires a proof-bound access token.",
626 }),
627 );
628 }
629 return Effect.succeed(session);
630 }),
631 );
632 };
633​
634 const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
635 authenticateRequest(request).pipe(
636 Effect.map(
637 (session) =>
638 ({
639 authenticated: true,
640 auth: descriptor,
641 scopes: session.scopes,
642 sessionMethod: session.method,
643 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
644 }) satisfies AuthSessionState,
645 ),
646 Effect.catchIf(isServerAuthCredentialError, () =>
647 Effect.succeed({
648 authenticated: false,
649 auth: descriptor,
650 } satisfies AuthSessionState),
651 ),
652 Effect.withSpan("EnvironmentAuth.getSessionState"),
653 );
654​
655 const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = (
656 credential,
657 requestMetadata,
658 ) =>
659 bootstrapCredentials.consume(credential).pipe(
660 Effect.mapError(toBootstrapExchangeError),
661 Effect.flatMap((grant) =>
662 sessions
663 .issue({
664 method: "browser-session-cookie",
665 subject: grant.subject,
666 scopes: grant.scopes,
667 client: {
668 ...requestMetadata,
669 ...(grant.label ? { label: grant.label } : {}),
670 },
671 })
672 .pipe(
673 Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
674 ),
675 ),
676 Effect.map(
677 (session) =>
678 ({
679 response: {
680 authenticated: true,
681 scopes: session.scopes,
682 sessionMethod: session.method,
683 expiresAt: DateTime.toUtc(session.expiresAt),
684 } satisfies AuthBrowserSessionResult,
685 sessionToken: session.token,
686 }) satisfies BootstrapExchangeResult,
687 ),
688 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
689 );
690​
691 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
692 (credential, requestedScopes, requestMetadata, input) =>
693 bootstrapCredentials.consume(credential, input).pipe(
694 Effect.mapError(toBootstrapExchangeError),
695 Effect.flatMap((grant) =>
696 Effect.gen(function* () {
697 const grantedScopes = requestedScopes ?? grant.scopes;
698 if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
699 return yield* new ServerAuthScopeNotGrantedError({});
700 }
701 return yield* sessions
702 .issue({
703 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
704 subject: grant.subject,
705 scopes: grantedScopes,
706 ...(input?.proofKeyThumbprint
707 ? {
708 proofKeyThumbprint: input.proofKeyThumbprint,
709 ttl: Duration.hours(1),
710 }
711 : {}),
712 client: {
713 ...requestMetadata,
714 ...(grant.label ? { label: grant.label } : {}),
715 },
716 })
717 .pipe(
718 Effect.mapError(
719 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
720 ),
721 );
722 }),
723 ),
724 Effect.flatMap((session) =>
725 DateTime.now.pipe(
726 Effect.map(
727 (now) =>
728 ({
729 access_token: session.token,
730 issued_token_type: AuthAccessTokenType,
731 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
732 expires_in: Math.max(
733 0,
734 Math.floor(
735 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
736 ),
737 ),
738 scope: encodeOAuthScope(session.scopes),
739 }) satisfies AuthAccessTokenResult,
740 ),
741 ),
742 ),
743 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
744 );
745​
746 const issuePairingCredentialForSubject = (input: {
747 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
748 readonly subject: string;
749 readonly label?: string;
750 readonly purpose?: "startup";
751 }) =>
752 createPairingLink({
753 scopes: input.scopes,
754 subject: input.subject,
755 ...(input.label ? { label: input.label } : {}),
756 ...(input.purpose ? { purpose: input.purpose } : {}),
757 }).pipe(
758 Effect.map(
759 (issued) =>
760 ({
761 id: issued.id,
762 credential: issued.credential,
763 ...(issued.label ? { label: issued.label } : {}),
764 expiresAt: issued.expiresAt,
765 }) satisfies AuthPairingCredentialResult,
766 ),
767 );
768​
769 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
770 "EnvironmentAuth.createPairingLink",
771 )(
772 function* (input) {
773 const createdAt = yield* DateTime.now;
774 const issued = yield* bootstrapCredentials.issueOneTimeToken({
775 scopes: input?.scopes ?? AuthStandardClientScopes,
776 subject: input?.subject ?? "one-time-token",
777 ...(input?.ttl ? { ttl: input.ttl } : {}),
778 ...(input?.label ? { label: input.label } : {}),
779 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
780 ...(input?.purpose ? { purpose: input.purpose } : {}),
781 });
782 return {
783 id: issued.id,
784 credential: issued.credential,
785 scopes: input?.scopes ?? AuthStandardClientScopes,
786 subject: input?.subject ?? "one-time-token",
787 ...(issued.label ? { label: issued.label } : {}),
788 createdAt: DateTime.toUtc(createdAt),
789 expiresAt: DateTime.toUtc(issued.expiresAt),
790 } satisfies IssuedPairingLink;
791 },
792 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
793 );
794​
795 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
796 bootstrapCredentials.listActive().pipe(
797 Effect.map((pairingLinks) => {
798 const excludedSubjects = input?.excludeSubjects ?? [
799 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
800 ];
801 return pairingLinks
802 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
803 .toSorted(
804 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
805 );
806 }),
807 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
808 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
809 );
810​
811 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
812 bootstrapCredentials.revoke(id).pipe(
813 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
814 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
815 );
816​
817 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
818 sessions
819 .issue({
820 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
821 method: "bearer-access-token",
822 scopes: input?.scopes ?? AuthAdministrativeScopes,
823 client: {
824 ...(input?.label ? { label: input.label } : {}),
825 deviceType: "bot",
826 },
827 ...(input?.ttl ? { ttl: input.ttl } : {}),
828 })
829 .pipe(
830 Effect.map(
831 (issued) =>
832 ({
833 sessionId: issued.sessionId,
834 token: issued.token,
835 method: "bearer-access-token",
836 scopes: issued.scopes,
837 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
838 client: issued.client,
839 expiresAt: DateTime.toUtc(issued.expiresAt),
840 }) satisfies IssuedBearerSession,
841 ),
842 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
843 Effect.withSpan("EnvironmentAuth.issueSession"),
844 );
845​
846 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
847 sessions.listActive().pipe(
848 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
849 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
850 Effect.withSpan("EnvironmentAuth.listSessions"),
851 );
852​
853 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
854 sessions.revoke(sessionId).pipe(
855 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
856 Effect.withSpan("EnvironmentAuth.revokeSession"),
857 );
858​
859 const revokeOtherSessionsExcept: EnvironmentAuth["Service"]["revokeOtherSessionsExcept"] = (
860 sessionId,
861 ) =>
862 sessions.revokeAllExcept(sessionId).pipe(
863 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
864 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
865 );
866​
867 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
868 issuePairingCredentialForSubject({
869 scopes: input?.scopes ?? AuthStandardClientScopes,
870 subject: "one-time-token",
871 ...(input?.label ? { label: input.label } : {}),
872 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
873​
874 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
875 () =>
876 issuePairingCredentialForSubject({
877 scopes: AuthAdministrativeScopes,
878 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
879 purpose: "startup",
880 }).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
881​
882 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
883 listSessions().pipe(
884 Effect.map((clientSessions) =>
885 clientSessions.map(
886 (clientSession): AuthClientSession => ({
887 ...clientSession,
888 current: clientSession.sessionId === currentSessionId,
889 }),
890 ),
891 ),
892 Effect.withSpan("EnvironmentAuth.listClientSessions"),
893 );
894​
895 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
896 "EnvironmentAuth.revokeClientSession",
897 )(function* (currentSessionId, targetSessionId) {
898 if (currentSessionId === targetSessionId) {
899 return yield* new ServerAuthForbiddenOperationError({});
900 }
901 return yield* revokeSession(targetSessionId);
902 });
903​
904 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
905 currentSessionId,
906 ) =>
907 revokeOtherSessionsExcept(currentSessionId).pipe(
908 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
909 );
910​
911 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
912 issueStartupPairingCredential().pipe(
913 Effect.map((issued) => {
914 const url = new URL(baseUrl);
915 url.pathname = "/pair";
916 url.searchParams.delete("token");
917 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
918 return url.toString();
919 }),
920 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
921 );
922​
923 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
924 sessions.issueWebSocketToken(session.sessionId).pipe(
925 Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
926 Effect.map(
927 (issued) =>
928 ({
929 ticket: issued.token,
930 expiresAt: DateTime.toUtc(issued.expiresAt),
931 }) satisfies AuthWebSocketTicketResult,
932 ),
933 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
934 );
935​
936 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
937 request,
938 ) =>
939 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
940​
941 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
942 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
943 const requestUrl = HttpServerRequest.toURL(request);
944 if (Option.isSome(requestUrl)) {
945 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
946 if (websocketTicket && websocketTicket.trim().length > 0) {
947 return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
948 Effect.map((session) => ({
949 sessionId: session.sessionId,
950 subject: session.subject,
951 method: session.method,
952 scopes: session.scopes,
953 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
954 })),
955 mapSessionVerificationErrors,
956 );
957 }
958 }
959​
960 return yield* authenticateRequest(request);
961 });
962​
963 return EnvironmentAuth.of({
964 getDescriptor: () =>
965 Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
966 getSessionState,
967 createBrowserSession,
968 exchangeBootstrapCredentialForAccessToken,
969 createPairingLink,
970 issuePairingCredential,
971 issueStartupPairingCredential,
972 listPairingLinks,
973 revokePairingLink,
974 issueSession,
975 listSessions,
976 revokeSession,
977 revokeOtherSessionsExcept,
978 listClientSessions,
979 revokeClientSession,
980 revokeOtherClientSessions,
981 authenticateHttpRequest,
982 authenticateWebSocketUpgrade,
983 issueWebSocketTicket,
984 issueStartupPairingUrl,
985 });
986});
987​
988export const layer = Layer.effect(EnvironmentAuth, make).pipe(
989 Layer.provideMerge(PairingGrantStore.layer),
990 Layer.provideMerge(SessionStore.layer),
991 Layer.provideMerge(EnvironmentAuthPolicy.layer),
992);
993​
994export const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);
995​
996export const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));