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

EnvironmentAuth.ts

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