Open History to see the last commit
1import {
2 AuthSessionId,
3 AuthStandardClientScopes,
4 AuthEnvironmentScopes,
5 type AuthClientMetadata,
6 type AuthClientSession,
7 type AuthEnvironmentScope,
8 AuthWebSocketTicketUse,
9 type ClientSurface,
10 RuntimeMode,
11 type ServerAuthSessionMethod,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as Crypto from "effect/Crypto";
15import * as DateTime from "effect/DateTime";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as PubSub from "effect/PubSub";
20import * as Ref from "effect/Ref";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import * as Option from "effect/Option";
24
25import * as ServerConfig from "../config.ts";
26import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
27import * as AuthSessions from "../persistence/AuthSessions.ts";
28import * as ServerSecretStore from "./ServerSecretStore.ts";
29import {
30 REUSABLE_DEV_SESSION_EXPIRES_AT,
31 REUSABLE_DEV_SESSION_PREFIX,
32 resolveReusableDevAuth,
33} from "./ReusableDevAuth.ts";
34import {
35 base64UrlDecodeUtf8,
36 base64UrlEncode,
37 resolveLegacySessionCookieName,
38 resolveSessionCookieName,
39 signPayload,
40 timingSafeEqualBase64Url,
41} from "./utils.ts";
42
43export interface IssuedSession {
44 readonly sessionId: AuthSessionId;
45 readonly token: string;
46 readonly method: ServerAuthSessionMethod;
47 readonly client: AuthClientMetadata;
48 readonly expiresAt: DateTime.DateTime;
49 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
50 readonly proofKeyThumbprint?: string;
51}
52
53export interface VerifiedSession {
54 readonly sessionId: AuthSessionId;
55 readonly token: string;
56 readonly method: ServerAuthSessionMethod;
57 readonly client: AuthClientMetadata;
58 readonly expiresAt?: DateTime.DateTime;
59 readonly subject: string;
60 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
61 readonly proofKeyThumbprint?: string;
62 readonly runtimeModeCeiling?: RuntimeMode;
63}
64
65export interface VerifiedWebSocketTicket extends VerifiedSession {
66 readonly audience?: AuthWebSocketTicketUse;
67}
68
69export type SessionCredentialChange =
70 | {
71 readonly type: "clientUpserted";
72 readonly clientSession: AuthClientSession;
73 }
74 | {
75 readonly type: "clientRemoved";
76 readonly sessionId: AuthSessionId;
77 };
78
79export class MalformedSessionTokenError extends Schema.TaggedError<MalformedSessionTokenError>()(
80 "MalformedSessionTokenError",
81 {},
82) {
83 override get message(): string {
84 return "Malformed session token.";
85 }
86}
87
88export class InvalidSessionTokenSignatureError extends Schema.TaggedError<InvalidSessionTokenSignatureError>()(
89 "InvalidSessionTokenSignatureError",
90 {},
91) {
92 override get message(): string {
93 return "Invalid session token signature.";
94 }
95}
96
97export class InvalidSessionTokenPayloadError extends Schema.TaggedError<InvalidSessionTokenPayloadError>()(
98 "InvalidSessionTokenPayloadError",
99 {
100 cause: Schema.Defect(),
101 },
102) {
103 override get message(): string {
104 return "Invalid session token payload.";
105 }
106}
107
108export class SessionTokenExpiredError extends Schema.TaggedError<SessionTokenExpiredError>()(
109 "SessionTokenExpiredError",
110 {
111 sessionId: AuthSessionId,
112 expiresAt: Schema.DateTimeUtc,
113 observedAt: Schema.DateTimeUtc,
114 },
115) {
116 override get message(): string {
117 return "Session token expired.";
118 }
119}
120
121export class UnknownSessionTokenError extends Schema.TaggedError<UnknownSessionTokenError>()(
122 "UnknownSessionTokenError",
123 {
124 sessionId: AuthSessionId,
125 },
126) {
127 override get message(): string {
128 return "Unknown session token.";
129 }
130}
131
132export class SessionTokenRevokedError extends Schema.TaggedError<SessionTokenRevokedError>()(
133 "SessionTokenRevokedError",
134 {
135 sessionId: AuthSessionId,
136 revokedAt: Schema.DateTimeUtc,
137 },
138) {
139 override get message(): string {
140 return "Session token revoked.";
141 }
142}
143
144export class InvalidSessionExpirationClaimError extends Schema.TaggedError<InvalidSessionExpirationClaimError>()(
145 "InvalidSessionExpirationClaimError",
146 {
147 sessionId: AuthSessionId,
148 expirationClaim: Schema.Number,
149 },
150) {
151 override get message(): string {
152 return "Invalid `exp` claim";
153 }
154}
155
156export class MalformedWebSocketTokenError extends Schema.TaggedError<MalformedWebSocketTokenError>()(
157 "MalformedWebSocketTokenError",
158 {},
159) {
160 override get message(): string {
161 return "Malformed websocket token.";
162 }
163}
164
165export class InvalidWebSocketTokenSignatureError extends Schema.TaggedError<InvalidWebSocketTokenSignatureError>()(
166 "InvalidWebSocketTokenSignatureError",
167 {},
168) {
169 override get message(): string {
170 return "Invalid websocket token signature.";
171 }
172}
173
174export class InvalidWebSocketTokenPayloadError extends Schema.TaggedError<InvalidWebSocketTokenPayloadError>()(
175 "InvalidWebSocketTokenPayloadError",
176 {
177 cause: Schema.Defect(),
178 },
179) {
180 override get message(): string {
181 return "Invalid websocket token payload.";
182 }
183}
184
185export class WebSocketTokenExpiredError extends Schema.TaggedError<WebSocketTokenExpiredError>()(
186 "WebSocketTokenExpiredError",
187 {
188 sessionId: AuthSessionId,
189 expiresAt: Schema.DateTimeUtc,
190 observedAt: Schema.DateTimeUtc,
191 },
192) {
193 override get message(): string {
194 return "Websocket token expired.";
195 }
196}
197
198export class UnknownWebSocketSessionError extends Schema.TaggedError<UnknownWebSocketSessionError>()(
199 "UnknownWebSocketSessionError",
200 {
201 sessionId: AuthSessionId,
202 },
203) {
204 override get message(): string {
205 return "Unknown websocket session.";
206 }
207}
208
209export class WebSocketSessionExpiredError extends Schema.TaggedError<WebSocketSessionExpiredError>()(
210 "WebSocketSessionExpiredError",
211 {
212 sessionId: AuthSessionId,
213 expiresAt: Schema.DateTimeUtc,
214 observedAt: Schema.DateTimeUtc,
215 },
216) {
217 override get message(): string {
218 return "Websocket session expired.";
219 }
220}
221
222export class WebSocketSessionRevokedError extends Schema.TaggedError<WebSocketSessionRevokedError>()(
223 "WebSocketSessionRevokedError",
224 {
225 sessionId: AuthSessionId,
226 revokedAt: Schema.DateTimeUtc,
227 },
228) {
229 override get message(): string {
230 return "Websocket session revoked.";
231 }
232}
233
234export const SessionCredentialInvalidError = Schema.Union([
235 MalformedSessionTokenError,
236 InvalidSessionTokenSignatureError,
237 InvalidSessionTokenPayloadError,
238 SessionTokenExpiredError,
239 UnknownSessionTokenError,
240 SessionTokenRevokedError,
241 InvalidSessionExpirationClaimError,
242 MalformedWebSocketTokenError,
243 InvalidWebSocketTokenSignatureError,
244 InvalidWebSocketTokenPayloadError,
245 WebSocketTokenExpiredError,
246 UnknownWebSocketSessionError,
247 WebSocketSessionExpiredError,
248 WebSocketSessionRevokedError,
249]);
250export type SessionCredentialInvalidError = typeof SessionCredentialInvalidError.Type;
251export const isSessionCredentialInvalidError = Schema.is(SessionCredentialInvalidError);
252
253const sessionCredentialInternalErrorContext = {
254 cause: Schema.Defect(),
255};
256
257export class SessionClaimsEncodingError extends Schema.TaggedError<SessionClaimsEncodingError>()(
258 "SessionClaimsEncodingError",
259 {
260 sessionId: AuthSessionId,
261 operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
262 ...sessionCredentialInternalErrorContext,
263 },
264) {
265 override get message(): string {
266 return "Failed to encode claims";
267 }
268}
269
270export class SessionCredentialIssueError extends Schema.TaggedError<SessionCredentialIssueError>()(
271 "SessionCredentialIssueError",
272 {
273 sessionId: Schema.optional(AuthSessionId),
274 ...sessionCredentialInternalErrorContext,
275 },
276) {
277 override get message(): string {
278 return "Failed to issue session credential.";
279 }
280}
281
282export class SessionCredentialVerificationError extends Schema.TaggedError<SessionCredentialVerificationError>()(
283 "SessionCredentialVerificationError",
284 {
285 sessionId: AuthSessionId,
286 ...sessionCredentialInternalErrorContext,
287 },
288) {
289 override get message(): string {
290 return "Failed to verify session credential.";
291 }
292}
293
294export class WebSocketTokenIssueError extends Schema.TaggedError<WebSocketTokenIssueError>()(
295 "WebSocketTokenIssueError",
296 {
297 sessionId: AuthSessionId,
298 ...sessionCredentialInternalErrorContext,
299 },
300) {
301 override get message(): string {
302 return "Failed to issue websocket token.";
303 }
304}
305
306export class WebSocketTokenVerificationError extends Schema.TaggedError<WebSocketTokenVerificationError>()(
307 "WebSocketTokenVerificationError",
308 {
309 sessionId: AuthSessionId,
310 ...sessionCredentialInternalErrorContext,
311 },
312) {
313 override get message(): string {
314 return "Failed to verify websocket token.";
315 }
316}
317
318export class ActiveSessionsListError extends Schema.TaggedError<ActiveSessionsListError>()(
319 "ActiveSessionsListError",
320 {
321 ...sessionCredentialInternalErrorContext,
322 },
323) {
324 override get message(): string {
325 return "Failed to list active sessions.";
326 }
327}
328
329export class SessionRevocationError extends Schema.TaggedError<SessionRevocationError>()(
330 "SessionRevocationError",
331 {
332 sessionId: AuthSessionId,
333 ...sessionCredentialInternalErrorContext,
334 },
335) {
336 override get message(): string {
337 return "Failed to revoke session.";
338 }
339}
340
341export class OtherSessionsRevocationError extends Schema.TaggedError<OtherSessionsRevocationError>()(
342 "OtherSessionsRevocationError",
343 {
344 currentSessionId: AuthSessionId,
345 ...sessionCredentialInternalErrorContext,
346 },
347) {
348 override get message(): string {
349 return "Failed to revoke other sessions.";
350 }
351}
352
353export const SessionCredentialInternalError = Schema.Union([
354 SessionClaimsEncodingError,
355 SessionCredentialIssueError,
356 SessionCredentialVerificationError,
357 WebSocketTokenIssueError,
358 WebSocketTokenVerificationError,
359 ActiveSessionsListError,
360 SessionRevocationError,
361 OtherSessionsRevocationError,
362]);
363export type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type;
364
365export const SessionCredentialError = Schema.Union([
366 SessionCredentialInvalidError,
367 SessionCredentialInternalError,
368]);
369export type SessionCredentialError = typeof SessionCredentialError.Type;
370
371export class SessionStore extends Context.Service<
372 SessionStore,
373 {
374 readonly cookieName: string;
375 readonly legacyCookieName: string | undefined;
376 readonly issue: (input?: {
377 readonly ttl?: Duration.Duration;
378 readonly subject?: string;
379 readonly method?: ServerAuthSessionMethod;
380 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
381 readonly client?: AuthClientMetadata;
382 readonly proofKeyThumbprint?: string;
383 readonly runtimeModeCeiling?: RuntimeMode;
384 readonly replaceActiveForSubjectAndMethod?: boolean;
385 readonly replaceSessionId?: AuthSessionId;
386 }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
387 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
388 readonly issueWebSocketToken: (
389 sessionId: AuthSessionId,
390 input?: {
391 readonly ttl?: Duration.Duration;
392 readonly audience?: AuthWebSocketTicketUse;
393 readonly proofKeyThumbprint?: string;
394 },
395 ) => Effect.Effect<
396 {
397 readonly token: string;
398 readonly expiresAt: DateTime.DateTime;
399 },
400 SessionCredentialInternalError
401 >;
402 readonly verifyWebSocketToken: (
403 token: string,
404 ) => Effect.Effect<VerifiedWebSocketTicket, SessionCredentialError>;
405 readonly listActive: () => Effect.Effect<
406 ReadonlyArray<AuthClientSession>,
407 SessionCredentialInternalError
408 >;
409 readonly streamChanges: Stream.Stream<SessionCredentialChange>;
410 readonly awaitInvalidation: (
411 sessionId: AuthSessionId,
412 ) => Effect.Effect<void, SessionCredentialVerificationError>;
413 readonly revoke: (
414 sessionId: AuthSessionId,
415 ) => Effect.Effect<boolean, SessionCredentialInternalError>;
416 readonly revokeAllExcept: (
417 sessionId: AuthSessionId,
418 ) => Effect.Effect<number, SessionCredentialInternalError>;
419 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
420 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
421 readonly recordClientConnection: (
422 sessionId: AuthSessionId,
423 client: {
424 readonly surface?: ClientSurface | undefined;
425 readonly appVersion?: string | undefined;
426 },
427 ) => Effect.Effect<void, never>;
428 }
429>()("t3/auth/SessionStore") {}
430
431const SIGNING_SECRET_NAME = "server-signing-key";
432const DEFAULT_SESSION_TTL = Duration.days(30);
433const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
434
435const SessionClaims = Schema.Struct({
436 v: Schema.Literals([1, 2]),
437 kind: Schema.Literal("session"),
438 sid: AuthSessionId,
439 sub: Schema.String,
440 scopes: AuthEnvironmentScopes,
441 method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
442 jkt: Schema.optionalKey(Schema.String),
443 rtc: Schema.optionalKey(RuntimeMode),
444 iat: Schema.Number,
445 exp: Schema.Number,
446});
447type SessionClaims = typeof SessionClaims.Type;
448
449const WebSocketClaims = Schema.Struct({
450 v: Schema.Literal(1),
451 kind: Schema.Literal("websocket"),
452 sid: AuthSessionId,
453 aud: Schema.optionalKey(AuthWebSocketTicketUse),
454 jkt: Schema.optionalKey(Schema.String),
455 iat: Schema.Number,
456 exp: Schema.Number,
457});
458type WebSocketClaims = typeof WebSocketClaims.Type;
459
460const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
461const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
462
463function createDefaultClientMetadata(): AuthClientMetadata {
464 return {
465 deviceType: "unknown",
466 };
467}
468
469function toClientMetadata(record: {
470 readonly label: string | null;
471 readonly ipAddress: string | null;
472 readonly userAgent: string | null;
473 readonly deviceType: AuthClientMetadata["deviceType"];
474 readonly os: string | null;
475 readonly browser: string | null;
476}): AuthClientMetadata {
477 return {
478 ...(record.label ? { label: record.label } : {}),
479 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
480 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
481 deviceType: record.deviceType,
482 ...(record.os ? { os: record.os } : {}),
483 ...(record.browser ? { browser: record.browser } : {}),
484 };
485}
486
487function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
488 return {
489 ...input,
490 current: false,
491 };
492}
493
494const make = Effect.gen(function* () {
495 const crypto = yield* Crypto.Crypto;
496 const serverConfig = yield* ServerConfig.ServerConfig;
497 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
498 const secretStore = yield* ServerSecretStore.ServerSecretStore;
499 const authSessions = yield* AuthSessions.AuthSessionRepository;
500 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
501 const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
502 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
503 const cookieInput = {
504 mode: serverConfig.mode,
505 port: serverConfig.port,
506 host: serverConfig.host,
507 instanceKey: serverConfig.stateDir,
508 environmentId: yield* serverEnvironment.getEnvironmentId,
509 development: serverConfig.devUrl !== undefined,
510 } as const;
511 const cookieName = resolveSessionCookieName(cookieInput);
512 const legacyCookieName = resolveLegacySessionCookieName(cookieInput);
513 const devAuth = resolveReusableDevAuth(serverConfig);
514 if (devAuth) {
515 yield* authSessions
516 .createIfAbsent({
517 sessionId: devAuth.sessionId,
518 subject: "reusable-dev-token",
519 scopes: AuthStandardClientScopes,
520 method: "browser-session-cookie",
521 client: {
522 label: "Reusable dev token",
523 ipAddress: null,
524 userAgent: null,
525 deviceType: "unknown",
526 os: null,
527 browser: null,
528 },
529 issuedAt: yield* DateTime.now,
530 expiresAt: REUSABLE_DEV_SESSION_EXPIRES_AT,
531 })
532 .pipe(
533 Effect.mapError(
534 (cause) => new SessionCredentialIssueError({ sessionId: devAuth.sessionId, cause }),
535 ),
536 );
537 }
538
539 const emitUpsert = (clientSession: AuthClientSession) =>
540 PubSub.publish(changesPubSub, {
541 type: "clientUpserted",
542 clientSession,
543 }).pipe(Effect.asVoid);
544
545 const emitRemoved = (sessionId: AuthSessionId) =>
546 PubSub.publish(changesPubSub, {
547 type: "clientRemoved",
548 sessionId,
549 }).pipe(Effect.asVoid);
550
551 const loadActiveSession = Effect.fn("SessionStore.loadActiveSession")(function* (
552 sessionId: AuthSessionId,
553 ) {
554 const row = yield* authSessions.getById({ sessionId });
555 if (Option.isNone(row) || row.value.revokedAt !== null) {
556 return Option.none<AuthClientSession>();
557 }
558
559 const connectedSessions = yield* Ref.get(connectedSessionsRef);
560 const connected = connectedSessions.has(row.value.sessionId);
561 const now = yield* DateTime.now;
562 if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
563 return Option.none<AuthClientSession>();
564 }
565 return Option.some(
566 toAuthClientSession({
567 sessionId: row.value.sessionId,
568 subject: row.value.subject,
569 scopes: row.value.scopes,
570 method: row.value.method,
571 client: toClientMetadata(row.value.client),
572 issuedAt: row.value.issuedAt,
573 expiresAt: row.value.expiresAt,
574 lastConnectedAt: row.value.lastConnectedAt,
575 connected,
576 }),
577 );
578 });
579
580 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
581 Ref.modify(connectedSessionsRef, (current) => {
582 const next = new Map(current);
583 const wasDisconnected = !next.has(sessionId);
584 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
585 return [wasDisconnected, next] as const;
586 }).pipe(
587 Effect.flatMap((wasDisconnected) =>
588 wasDisconnected
589 ? DateTime.now.pipe(
590 Effect.flatMap((lastConnectedAt) =>
591 authSessions.setLastConnectedAt({
592 sessionId,
593 lastConnectedAt,
594 }),
595 ),
596 )
597 : Effect.void,
598 ),
599 Effect.flatMap(() => loadActiveSession(sessionId)),
600 Effect.flatMap((session) =>
601 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
602 ),
603 Effect.catchCause((cause) =>
604 Effect.logError("Failed to publish connected-session auth update.").pipe(
605 Effect.annotateLogs({
606 sessionId,
607 cause,
608 }),
609 ),
610 ),
611 Effect.withSpan("SessionStore.markConnected"),
612 );
613
614 const recordClientConnection: SessionStore["Service"]["recordClientConnection"] = (
615 sessionId,
616 client,
617 ) =>
618 client.surface === undefined && client.appVersion === undefined
619 ? Effect.void
620 : authSessions
621 .setClientConnection({
622 sessionId,
623 surface: client.surface ?? null,
624 appVersion: client.appVersion ?? null,
625 })
626 .pipe(
627 Effect.catchCause((cause) =>
628 Effect.logWarning("Failed to record session client connection metadata.").pipe(
629 Effect.annotateLogs({ sessionId, cause }),
630 ),
631 ),
632 Effect.withSpan("SessionStore.recordClientConnection"),
633 );
634
635 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
636 Ref.update(connectedSessionsRef, (current) => {
637 const next = new Map(current);
638 const remaining = (next.get(sessionId) ?? 0) - 1;
639 if (remaining > 0) {
640 next.set(sessionId, remaining);
641 } else {
642 next.delete(sessionId);
643 }
644 return next;
645 }).pipe(
646 Effect.flatMap(() => loadActiveSession(sessionId)),
647 Effect.flatMap((session) =>
648 Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
649 ),
650 Effect.catchCause((cause) =>
651 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
652 Effect.annotateLogs({
653 sessionId,
654 cause,
655 }),
656 ),
657 ),
658 Effect.withSpan("SessionStore.markDisconnected"),
659 );
660
661 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
662 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
663 function* (input) {
664 const sessionId = AuthSessionId.make(
665 yield* crypto
666 .randomUUIDv4()
667 .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ cause }))),
668 );
669 const issuedAt = yield* DateTime.now;
670 const expiresAt = DateTime.add(issuedAt, {
671 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
672 });
673 const claims: SessionClaims = {
674 v: 1,
675 kind: "session",
676 sid: sessionId,
677 sub: input?.subject ?? "browser",
678 scopes: input?.scopes ?? AuthStandardClientScopes,
679 method: input?.method ?? "browser-session-cookie",
680 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
681 ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
682 iat: issuedAt.epochMilliseconds,
683 exp: expiresAt.epochMilliseconds,
684 };
685
686 const encodedPayload = yield* encodeClaims(claims).pipe(
687 Effect.map(base64UrlEncode),
688 Effect.mapError(
689 (cause) =>
690 new SessionCredentialIssueError({
691 sessionId,
692 cause: new SessionClaimsEncodingError({
693 sessionId,
694 operation: "encode_session_claims",
695 cause,
696 }),
697 }),
698 ),
699 );
700 const signature = signPayload(encodedPayload, signingSecret);
701 const client = input?.client ?? createDefaultClientMetadata();
702 const sessionRecord = {
703 sessionId,
704 subject: claims.sub,
705 scopes: claims.scopes,
706 method: claims.method,
707 client: {
708 label: client.label ?? null,
709 ipAddress: client.ipAddress ?? null,
710 userAgent: client.userAgent ?? null,
711 deviceType: client.deviceType,
712 os: client.os ?? null,
713 browser: client.browser ?? null,
714 },
715 issuedAt,
716 expiresAt,
717 } satisfies AuthSessions.CreateAuthSessionInput;
718 const replacedSessionIds = yield* (
719 input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod
720 ? authSessions.createReplacingActive({
721 session: sessionRecord,
722 revokedAt: issuedAt,
723 ...(input.replaceSessionId !== undefined
724 ? { replaceSessionId: input.replaceSessionId }
725 : {}),
726 })
727 : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>))
728 ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
729 if (replacedSessionIds.length > 0) {
730 yield* Ref.update(connectedSessionsRef, (current) => {
731 const next = new Map(current);
732 for (const replacedSessionId of replacedSessionIds) {
733 next.delete(replacedSessionId);
734 }
735 return next;
736 });
737 yield* Effect.forEach(replacedSessionIds, emitRemoved, {
738 concurrency: "unbounded",
739 discard: true,
740 });
741 }
742 yield* emitUpsert(
743 toAuthClientSession({
744 sessionId,
745 subject: claims.sub,
746 scopes: claims.scopes,
747 method: claims.method,
748 client,
749 issuedAt,
750 expiresAt,
751 lastConnectedAt: null,
752 connected: false,
753 }),
754 );
755
756 return {
757 sessionId,
758 token: `${encodedPayload}.${signature}`,
759 method: claims.method,
760 client,
761 expiresAt: expiresAt,
762 scopes: claims.scopes,
763 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
764 } satisfies IssuedSession;
765 },
766 );
767
768 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
769 function* (token) {
770 if (devAuth?.matches(token)) {
771 const row = yield* authSessions
772 .getById({ sessionId: devAuth.sessionId })
773 .pipe(
774 Effect.mapError(
775 (cause) =>
776 new SessionCredentialVerificationError({ sessionId: devAuth.sessionId, cause }),
777 ),
778 );
779 if (Option.isNone(row)) {
780 return yield* new UnknownSessionTokenError({ sessionId: devAuth.sessionId });
781 }
782 if (row.value.revokedAt !== null) {
783 return yield* new SessionTokenRevokedError({
784 sessionId: devAuth.sessionId,
785 revokedAt: row.value.revokedAt,
786 });
787 }
788 const observedAt = yield* DateTime.now;
789 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
790 return yield* new SessionTokenExpiredError({
791 sessionId: devAuth.sessionId,
792 expiresAt: row.value.expiresAt,
793 observedAt,
794 });
795 }
796 return {
797 sessionId: row.value.sessionId,
798 token,
799 method: row.value.method,
800 client: toClientMetadata(row.value.client),
801 expiresAt: row.value.expiresAt,
802 subject: row.value.subject,
803 scopes: row.value.scopes,
804 } satisfies VerifiedSession;
805 }
806 const [encodedPayload, signature] = token.split(".");
807 if (!encodedPayload || !signature) {
808 return yield* new MalformedSessionTokenError({});
809 }
810
811 const expectedSignature = signPayload(encodedPayload, signingSecret);
812 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
813 return yield* new InvalidSessionTokenSignatureError({});
814 }
815
816 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
817 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
818 );
819
820 const observedAt = yield* DateTime.now;
821 const expiresAt = DateTime.make(claims.exp);
822 if (Option.isNone(expiresAt)) {
823 return yield* new InvalidSessionExpirationClaimError({
824 sessionId: claims.sid,
825 expirationClaim: claims.exp,
826 });
827 }
828 if (claims.exp <= observedAt.epochMilliseconds) {
829 return yield* new SessionTokenExpiredError({
830 sessionId: claims.sid,
831 expiresAt: expiresAt.value,
832 observedAt,
833 });
834 }
835
836 const row = yield* authSessions
837 .getById({ sessionId: claims.sid })
838 .pipe(
839 Effect.mapError(
840 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
841 ),
842 );
843 if (Option.isNone(row)) {
844 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
845 }
846 if (row.value.revokedAt !== null) {
847 return yield* new SessionTokenRevokedError({
848 sessionId: claims.sid,
849 revokedAt: row.value.revokedAt,
850 });
851 }
852
853 return {
854 sessionId: claims.sid,
855 token,
856 method: claims.method,
857 client: toClientMetadata(row.value.client),
858 expiresAt: expiresAt.value,
859 subject: claims.sub,
860 scopes: claims.scopes,
861 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
862 ...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
863 } satisfies VerifiedSession;
864 },
865 );
866
867 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
868 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
869 "SessionStore.issueWebSocketToken",
870 )(function* (sessionId, input) {
871 const issuedAt = yield* DateTime.now;
872 const expiresAt = DateTime.add(issuedAt, {
873 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
874 });
875 const claims: WebSocketClaims = {
876 v: 1,
877 kind: "websocket",
878 sid: sessionId,
879 ...(input?.audience ? { aud: input.audience } : {}),
880 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
881 iat: issuedAt.epochMilliseconds,
882 exp: expiresAt.epochMilliseconds,
883 };
884 const encodedPayload = yield* encodeWsClaims(claims).pipe(
885 Effect.map(base64UrlEncode),
886 Effect.mapError(
887 (cause) =>
888 new WebSocketTokenIssueError({
889 sessionId,
890 cause: new SessionClaimsEncodingError({
891 sessionId,
892 operation: "encode_websocket_claims",
893 cause,
894 }),
895 }),
896 ),
897 );
898 const signature = signPayload(encodedPayload, signingSecret);
899 return {
900 token: `${encodedPayload}.${signature}`,
901 expiresAt,
902 };
903 });
904
905 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
906 "SessionStore.verifyWebSocketToken",
907 )(function* (token) {
908 const [encodedPayload, signature] = token.split(".");
909 if (!encodedPayload || !signature) {
910 return yield* new MalformedWebSocketTokenError({});
911 }
912
913 const expectedSignature = signPayload(encodedPayload, signingSecret);
914 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
915 return yield* new InvalidWebSocketTokenSignatureError({});
916 }
917
918 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
919 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
920 );
921 if (claims.sid.startsWith(REUSABLE_DEV_SESSION_PREFIX) && claims.sid !== devAuth?.sessionId) {
922 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
923 }
924
925 const observedAt = yield* DateTime.now;
926 const expiresAt = DateTime.make(claims.exp);
927 if (Option.isNone(expiresAt)) {
928 return yield* new InvalidSessionExpirationClaimError({
929 sessionId: claims.sid,
930 expirationClaim: claims.exp,
931 });
932 }
933 if (claims.exp <= observedAt.epochMilliseconds) {
934 return yield* new WebSocketTokenExpiredError({
935 sessionId: claims.sid,
936 expiresAt: expiresAt.value,
937 observedAt,
938 });
939 }
940
941 const row = yield* authSessions
942 .getById({ sessionId: claims.sid })
943 .pipe(
944 Effect.mapError(
945 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
946 ),
947 );
948 if (Option.isNone(row)) {
949 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
950 }
951 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
952 return yield* new WebSocketSessionExpiredError({
953 sessionId: claims.sid,
954 expiresAt: row.value.expiresAt,
955 observedAt,
956 });
957 }
958 if (row.value.revokedAt !== null) {
959 return yield* new WebSocketSessionRevokedError({
960 sessionId: claims.sid,
961 revokedAt: row.value.revokedAt,
962 });
963 }
964
965 return {
966 sessionId: row.value.sessionId,
967 token,
968 method: row.value.method,
969 client: toClientMetadata(row.value.client),
970 expiresAt: row.value.expiresAt,
971 subject: row.value.subject,
972 scopes: row.value.scopes,
973 ...(claims.aud ? { audience: claims.aud } : {}),
974 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
975 } satisfies VerifiedWebSocketTicket;
976 });
977
978 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
979 function* () {
980 const now = yield* DateTime.now;
981 const connectedSessions = yield* Ref.get(connectedSessionsRef);
982 const rows = yield* authSessions.listActive({
983 now,
984 connectedSessionIds: Array.from(connectedSessions.keys()),
985 });
986
987 return rows.map((row) =>
988 toAuthClientSession({
989 sessionId: row.sessionId,
990 subject: row.subject,
991 scopes: row.scopes,
992 method: row.method,
993 client: toClientMetadata(row.client),
994 issuedAt: row.issuedAt,
995 expiresAt: row.expiresAt,
996 lastConnectedAt: row.lastConnectedAt,
997 connected: connectedSessions.has(row.sessionId),
998 }),
999 );
1000 },
1001 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
1002 );
1003
1004 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
1005 function* (sessionId) {
1006 const revokedAt = yield* DateTime.now;
1007 const revoked = yield* authSessions
1008 .revoke({
1009 sessionId,
1010 revokedAt,
1011 })
1012 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
1013 if (revoked) {
1014 yield* Ref.update(connectedSessionsRef, (current) => {
1015 const next = new Map(current);
1016 next.delete(sessionId);
1017 return next;
1018 });
1019 yield* emitRemoved(sessionId);
1020 }
1021 return revoked;
1022 },
1023 );
1024
1025 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
1026 "SessionStore.revokeAllExcept",
1027 )(function* (sessionId) {
1028 const revokedAt = yield* DateTime.now;
1029 const revokedSessionIds = yield* authSessions
1030 .revokeAllExcept({
1031 currentSessionId: sessionId,
1032 revokedAt,
1033 })
1034 .pipe(
1035 Effect.mapError(
1036 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
1037 ),
1038 );
1039 if (revokedSessionIds.length > 0) {
1040 yield* Ref.update(connectedSessionsRef, (current) => {
1041 const next = new Map(current);
1042 for (const revokedSessionId of revokedSessionIds) {
1043 next.delete(revokedSessionId);
1044 }
1045 return next;
1046 });
1047 yield* Effect.forEach(
1048 revokedSessionIds,
1049 (revokedSessionId) => emitRemoved(revokedSessionId),
1050 {
1051 concurrency: "unbounded",
1052 discard: true,
1053 },
1054 );
1055 }
1056 return revokedSessionIds.length;
1057 });
1058
1059 const awaitInvalidation = Effect.fn(function* (sessionId: AuthSessionId) {
1060 return yield* Effect.scoped(
1061 Effect.gen(function* () {
1062 // Subscribe before reading: revocation can race with the WebSocket upgrade.
1063 const subscription = yield* PubSub.subscribe(changesPubSub);
1064 const row = yield* authSessions
1065 .getById({ sessionId })
1066 .pipe(
1067 Effect.mapError(
1068 (cause) => new SessionCredentialVerificationError({ sessionId, cause }),
1069 ),
1070 );
1071 if (Option.isNone(row) || row.value.revokedAt !== null) return;
1072 const now = yield* DateTime.now;
1073 const remaining = row.value.expiresAt.epochMilliseconds - now.epochMilliseconds;
1074 if (remaining <= 0) return;
1075 yield* Effect.raceFirst(
1076 Stream.fromSubscription(subscription).pipe(
1077 Stream.filter(
1078 (change) => change.type === "clientRemoved" && change.sessionId === sessionId,
1079 ),
1080 Stream.runHead,
1081 ),
1082 Effect.sleep(Duration.millis(remaining)),
1083 );
1084 }),
1085 );
1086 });
1087
1088 return SessionStore.of({
1089 cookieName,
1090 legacyCookieName,
1091 issue,
1092 verify,
1093 issueWebSocketToken,
1094 verifyWebSocketToken,
1095 listActive,
1096 awaitInvalidation,
1097 get streamChanges() {
1098 return Stream.fromPubSub(changesPubSub);
1099 },
1100 revoke,
1101 revokeAllExcept,
1102 markConnected,
1103 markDisconnected,
1104 recordClientConnection,
1105 });
1106});
1107
1108export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));