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

EnvironmentAuth.ts

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