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

SessionStore.ts

957 lines29.4 KB

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