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

EnvironmentAuth.ts

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