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

SessionStore.ts

986 lines30.6 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 /**
374 * Atomically revoke active sessions with the same subject and method
375 * before storing this session.
376 */
377 readonly replaceActiveForSubjectAndMethod?: boolean;
378 }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
379 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
380 readonly issueWebSocketToken: (
381 sessionId: AuthSessionId,
382 input?: {
383 readonly ttl?: Duration.Duration;
384 },
385 ) => Effect.Effect<
386 {
387 readonly token: string;
388 readonly expiresAt: DateTime.DateTime;
389 },
390 SessionCredentialInternalError
391 >;
392 readonly verifyWebSocketToken: (
393 token: string,
394 ) => Effect.Effect<VerifiedSession, SessionCredentialError>;
395 readonly listActive: () => Effect.Effect<
396 ReadonlyArray<AuthClientSession>,
397 SessionCredentialInternalError
398 >;
399 readonly streamChanges: Stream.Stream<SessionCredentialChange>;
400 readonly revoke: (
401 sessionId: AuthSessionId,
402 ) => Effect.Effect<boolean, SessionCredentialInternalError>;
403 readonly revokeAllExcept: (
404 sessionId: AuthSessionId,
405 ) => Effect.Effect<number, SessionCredentialInternalError>;
406 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
407 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
408 readonly recordClientConnection: (
409 sessionId: AuthSessionId,
410 client: {
411 readonly surface?: ClientSurface | undefined;
412 readonly appVersion?: string | undefined;
413 },
414 ) => Effect.Effect<void, never>;
415 }
416>()("t3/auth/SessionStore") {}
417​
418const SIGNING_SECRET_NAME = "server-signing-key";
419const DEFAULT_SESSION_TTL = Duration.days(30);
420const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
421​
422const SessionClaims = Schema.Struct({
423 v: Schema.Literal(1),
424 kind: Schema.Literal("session"),
425 sid: AuthSessionId,
426 sub: Schema.String,
427 scopes: AuthEnvironmentScopes,
428 method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
429 jkt: Schema.optionalKey(Schema.String),
430 iat: Schema.Number,
431 exp: Schema.Number,
432});
433type SessionClaims = typeof SessionClaims.Type;
434​
435const WebSocketClaims = Schema.Struct({
436 v: Schema.Literal(1),
437 kind: Schema.Literal("websocket"),
438 sid: AuthSessionId,
439 iat: Schema.Number,
440 exp: Schema.Number,
441});
442type WebSocketClaims = typeof WebSocketClaims.Type;
443​
444const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
445const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
446​
447function createDefaultClientMetadata(): AuthClientMetadata {
448 return {
449 deviceType: "unknown",
450 };
452​
453function toClientMetadata(record: {
454 readonly label: string | null;
455 readonly ipAddress: string | null;
456 readonly userAgent: string | null;
457 readonly deviceType: AuthClientMetadata["deviceType"];
458 readonly os: string | null;
459 readonly browser: string | null;
460}): AuthClientMetadata {
461 return {
462 ...(record.label ? { label: record.label } : {}),
463 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
464 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
465 deviceType: record.deviceType,
466 ...(record.os ? { os: record.os } : {}),
467 ...(record.browser ? { browser: record.browser } : {}),
468 };
470​
471function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
472 return {
473 ...input,
474 current: false,
475 };
477​
478export const make = Effect.gen(function* () {
479 const crypto = yield* Crypto.Crypto;
480 const serverConfig = yield* ServerConfig.ServerConfig;
481 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
482 const secretStore = yield* ServerSecretStore.ServerSecretStore;
483 const authSessions = yield* AuthSessions.AuthSessionRepository;
484 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
485 const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
486 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
487 const cookieInput = {
488 mode: serverConfig.mode,
489 port: serverConfig.port,
490 host: serverConfig.host,
491 instanceKey: serverConfig.stateDir,
492 environmentId: yield* serverEnvironment.getEnvironmentId,
493 development: serverConfig.devUrl !== undefined,
494 } as const;
495 const cookieName = resolveSessionCookieName(cookieInput);
496 const legacyCookieName = resolveLegacySessionCookieName(cookieInput);
497​
498 const emitUpsert = (clientSession: AuthClientSession) =>
499 PubSub.publish(changesPubSub, {
500 type: "clientUpserted",
501 clientSession,
502 }).pipe(Effect.asVoid);
503​
504 const emitRemoved = (sessionId: AuthSessionId) =>
505 PubSub.publish(changesPubSub, {
506 type: "clientRemoved",
507 sessionId,
508 }).pipe(Effect.asVoid);
509​
510 const loadActiveSession = (sessionId: AuthSessionId) =>
511 Effect.gen(function* () {
512 const row = yield* authSessions.getById({ sessionId });
513 if (Option.isNone(row) || row.value.revokedAt !== null) {
514 return Option.none<AuthClientSession>();
515 }
516​
517 const connectedSessions = yield* Ref.get(connectedSessionsRef);
518 const connected = connectedSessions.has(row.value.sessionId);
519 const now = yield* DateTime.now;
520 if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
521 return Option.none<AuthClientSession>();
522 }
523 return Option.some(
524 toAuthClientSession({
525 sessionId: row.value.sessionId,
526 subject: row.value.subject,
527 scopes: row.value.scopes,
528 method: row.value.method,
529 client: toClientMetadata(row.value.client),
530 issuedAt: row.value.issuedAt,
531 expiresAt: row.value.expiresAt,
532 lastConnectedAt: row.value.lastConnectedAt,
533 connected,
534 }),
535 );
536 });
537​
538 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
539 Ref.modify(connectedSessionsRef, (current) => {
540 const next = new Map(current);
541 const wasDisconnected = !next.has(sessionId);
542 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
543 return [wasDisconnected, next] as const;
544 }).pipe(
545 Effect.flatMap((wasDisconnected) =>
546 wasDisconnected
547 ? DateTime.now.pipe(
548 Effect.flatMap((lastConnectedAt) =>
549 authSessions.setLastConnectedAt({
550 sessionId,
551 lastConnectedAt,
552 }),
553 ),
554 )
555 : Effect.void,
556 ),
557 Effect.flatMap(() => loadActiveSession(sessionId)),
558 Effect.flatMap((session) =>
559 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
560 ),
561 Effect.catchCause((cause) =>
562 Effect.logError("Failed to publish connected-session auth update.").pipe(
563 Effect.annotateLogs({
564 sessionId,
565 cause,
566 }),
567 ),
568 ),
569 Effect.withSpan("SessionStore.markConnected"),
570 );
571​
572 // Best-effort: connection metadata must never block or fail a connect.
573 const recordClientConnection: SessionStore["Service"]["recordClientConnection"] = (
574 sessionId,
575 client,
576 ) =>
577 client.surface === undefined && client.appVersion === undefined
578 ? Effect.void
579 : authSessions
580 .setClientConnection({
581 sessionId,
582 surface: client.surface ?? null,
583 appVersion: client.appVersion ?? null,
584 })
585 .pipe(
586 Effect.catchCause((cause) =>
587 Effect.logWarning("Failed to record session client connection metadata.").pipe(
588 Effect.annotateLogs({ sessionId, cause }),
589 ),
590 ),
591 Effect.withSpan("SessionStore.recordClientConnection"),
592 );
593​
594 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
595 Ref.update(connectedSessionsRef, (current) => {
596 const next = new Map(current);
597 const remaining = (next.get(sessionId) ?? 0) - 1;
598 if (remaining > 0) {
599 next.set(sessionId, remaining);
600 } else {
601 next.delete(sessionId);
602 }
603 return next;
604 }).pipe(
605 Effect.flatMap(() => loadActiveSession(sessionId)),
606 Effect.flatMap((session) =>
607 Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
608 ),
609 Effect.catchCause((cause) =>
610 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
611 Effect.annotateLogs({
612 sessionId,
613 cause,
614 }),
615 ),
616 ),
617 Effect.withSpan("SessionStore.markDisconnected"),
618 );
619​
620 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
621 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
622 function* (input) {
623 const sessionId = AuthSessionId.make(
624 yield* crypto.randomUUIDv4.pipe(
625 Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
626 ),
627 );
628 const issuedAt = yield* DateTime.now;
629 const expiresAt = DateTime.add(issuedAt, {
630 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
631 });
632 const claims: SessionClaims = {
633 v: 1,
634 kind: "session",
635 sid: sessionId,
636 sub: input?.subject ?? "browser",
637 scopes: input?.scopes ?? AuthStandardClientScopes,
638 method: input?.method ?? "browser-session-cookie",
639 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
640 iat: issuedAt.epochMilliseconds,
641 exp: expiresAt.epochMilliseconds,
642 };
643​
644 const encodedPayload = yield* encodeClaims(claims).pipe(
645 Effect.map(base64UrlEncode),
646 Effect.mapError(
647 (cause) =>
648 new SessionCredentialIssueError({
649 sessionId,
650 cause: new SessionClaimsEncodingError({
651 sessionId,
652 operation: "encode_session_claims",
653 cause,
654 }),
655 }),
656 ),
657 );
658 const signature = signPayload(encodedPayload, signingSecret);
659 const client = input?.client ?? createDefaultClientMetadata();
660 const sessionRecord = {
661 sessionId,
662 subject: claims.sub,
663 scopes: claims.scopes,
664 method: claims.method,
665 client: {
666 label: client.label ?? null,
667 ipAddress: client.ipAddress ?? null,
668 userAgent: client.userAgent ?? null,
669 deviceType: client.deviceType,
670 os: client.os ?? null,
671 browser: client.browser ?? null,
672 },
673 issuedAt,
674 expiresAt,
675 } satisfies AuthSessions.CreateAuthSessionInput;
676 const replacedSessionIds = yield* (
677 input?.replaceActiveForSubjectAndMethod
678 ? authSessions.createReplacingActive({ session: sessionRecord, revokedAt: issuedAt })
679 : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>))
680 ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
681 if (replacedSessionIds.length > 0) {
682 yield* Ref.update(connectedSessionsRef, (current) => {
683 const next = new Map(current);
684 for (const replacedSessionId of replacedSessionIds) {
685 next.delete(replacedSessionId);
686 }
687 return next;
688 });
689 yield* Effect.forEach(replacedSessionIds, emitRemoved, {
690 concurrency: "unbounded",
691 discard: true,
692 });
693 }
694 yield* emitUpsert(
695 toAuthClientSession({
696 sessionId,
697 subject: claims.sub,
698 scopes: claims.scopes,
699 method: claims.method,
700 client,
701 issuedAt,
702 expiresAt,
703 lastConnectedAt: null,
704 connected: false,
705 }),
706 );
707​
708 return {
709 sessionId,
710 token: `${encodedPayload}.${signature}`,
711 method: claims.method,
712 client,
713 expiresAt: expiresAt,
714 scopes: claims.scopes,
715 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
716 } satisfies IssuedSession;
717 },
718 );
719​
720 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
721 function* (token) {
722 const [encodedPayload, signature] = token.split(".");
723 if (!encodedPayload || !signature) {
724 return yield* new MalformedSessionTokenError({});
725 }
726​
727 const expectedSignature = signPayload(encodedPayload, signingSecret);
728 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
729 return yield* new InvalidSessionTokenSignatureError({});
730 }
731​
732 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
733 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
734 );
735​
736 const observedAt = yield* DateTime.now;
737 const expiresAt = DateTime.make(claims.exp);
738 if (Option.isNone(expiresAt)) {
739 return yield* new InvalidSessionExpirationClaimError({
740 sessionId: claims.sid,
741 expirationClaim: claims.exp,
742 });
743 }
744 if (claims.exp <= observedAt.epochMilliseconds) {
745 return yield* new SessionTokenExpiredError({
746 sessionId: claims.sid,
747 expiresAt: expiresAt.value,
748 observedAt,
749 });
750 }
751​
752 const row = yield* authSessions
753 .getById({ sessionId: claims.sid })
754 .pipe(
755 Effect.mapError(
756 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
757 ),
758 );
759 if (Option.isNone(row)) {
760 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
761 }
762 if (row.value.revokedAt !== null) {
763 return yield* new SessionTokenRevokedError({
764 sessionId: claims.sid,
765 revokedAt: row.value.revokedAt,
766 });
767 }
768​
769 return {
770 sessionId: claims.sid,
771 token,
772 method: claims.method,
773 client: toClientMetadata(row.value.client),
774 expiresAt: expiresAt.value,
775 subject: claims.sub,
776 scopes: claims.scopes,
777 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
778 } satisfies VerifiedSession;
779 },
780 );
781​
782 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
783 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
784 "SessionStore.issueWebSocketToken",
785 )(function* (sessionId, input) {
786 const issuedAt = yield* DateTime.now;
787 const expiresAt = DateTime.add(issuedAt, {
788 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
789 });
790 const claims: WebSocketClaims = {
791 v: 1,
792 kind: "websocket",
793 sid: sessionId,
794 iat: issuedAt.epochMilliseconds,
795 exp: expiresAt.epochMilliseconds,
796 };
797 const encodedPayload = yield* encodeWsClaims(claims).pipe(
798 Effect.map(base64UrlEncode),
799 Effect.mapError(
800 (cause) =>
801 new WebSocketTokenIssueError({
802 sessionId,
803 cause: new SessionClaimsEncodingError({
804 sessionId,
805 operation: "encode_websocket_claims",
806 cause,
807 }),
808 }),
809 ),
810 );
811 const signature = signPayload(encodedPayload, signingSecret);
812 return {
813 token: `${encodedPayload}.${signature}`,
814 expiresAt,
815 };
816 });
817​
818 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
819 "SessionStore.verifyWebSocketToken",
820 )(function* (token) {
821 const [encodedPayload, signature] = token.split(".");
822 if (!encodedPayload || !signature) {
823 return yield* new MalformedWebSocketTokenError({});
824 }
825​
826 const expectedSignature = signPayload(encodedPayload, signingSecret);
827 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
828 return yield* new InvalidWebSocketTokenSignatureError({});
829 }
830​
831 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
832 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
833 );
834​
835 const observedAt = yield* DateTime.now;
836 const expiresAt = DateTime.make(claims.exp);
837 if (Option.isNone(expiresAt)) {
838 return yield* new InvalidSessionExpirationClaimError({
839 sessionId: claims.sid,
840 expirationClaim: claims.exp,
841 });
842 }
843 if (claims.exp <= observedAt.epochMilliseconds) {
844 return yield* new WebSocketTokenExpiredError({
845 sessionId: claims.sid,
846 expiresAt: expiresAt.value,
847 observedAt,
848 });
849 }
850​
851 const row = yield* authSessions
852 .getById({ sessionId: claims.sid })
853 .pipe(
854 Effect.mapError(
855 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
856 ),
857 );
858 if (Option.isNone(row)) {
859 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
860 }
861 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
862 return yield* new WebSocketSessionExpiredError({
863 sessionId: claims.sid,
864 expiresAt: row.value.expiresAt,
865 observedAt,
866 });
867 }
868 if (row.value.revokedAt !== null) {
869 return yield* new WebSocketSessionRevokedError({
870 sessionId: claims.sid,
871 revokedAt: row.value.revokedAt,
872 });
873 }
874​
875 return {
876 sessionId: row.value.sessionId,
877 token,
878 method: row.value.method,
879 client: toClientMetadata(row.value.client),
880 expiresAt: row.value.expiresAt,
881 subject: row.value.subject,
882 scopes: row.value.scopes,
883 } satisfies VerifiedSession;
884 });
885​
886 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
887 function* () {
888 const now = yield* DateTime.now;
889 const connectedSessions = yield* Ref.get(connectedSessionsRef);
890 const rows = yield* authSessions.listActive({
891 now,
892 connectedSessionIds: Array.from(connectedSessions.keys()),
893 });
894​
895 return rows.map((row) =>
896 toAuthClientSession({
897 sessionId: row.sessionId,
898 subject: row.subject,
899 scopes: row.scopes,
900 method: row.method,
901 client: toClientMetadata(row.client),
902 issuedAt: row.issuedAt,
903 expiresAt: row.expiresAt,
904 lastConnectedAt: row.lastConnectedAt,
905 connected: connectedSessions.has(row.sessionId),
906 }),
907 );
908 },
909 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
910 );
911​
912 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
913 function* (sessionId) {
914 const revokedAt = yield* DateTime.now;
915 const revoked = yield* authSessions
916 .revoke({
917 sessionId,
918 revokedAt,
919 })
920 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
921 if (revoked) {
922 yield* Ref.update(connectedSessionsRef, (current) => {
923 const next = new Map(current);
924 next.delete(sessionId);
925 return next;
926 });
927 yield* emitRemoved(sessionId);
928 }
929 return revoked;
930 },
931 );
932​
933 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
934 "SessionStore.revokeAllExcept",
935 )(function* (sessionId) {
936 const revokedAt = yield* DateTime.now;
937 const revokedSessionIds = yield* authSessions
938 .revokeAllExcept({
939 currentSessionId: sessionId,
940 revokedAt,
941 })
942 .pipe(
943 Effect.mapError(
944 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
945 ),
946 );
947 if (revokedSessionIds.length > 0) {
948 yield* Ref.update(connectedSessionsRef, (current) => {
949 const next = new Map(current);
950 for (const revokedSessionId of revokedSessionIds) {
951 next.delete(revokedSessionId);
952 }
953 return next;
954 });
955 yield* Effect.forEach(
956 revokedSessionIds,
957 (revokedSessionId) => emitRemoved(revokedSessionId),
958 {
959 concurrency: "unbounded",
960 discard: true,
961 },
962 );
963 }
964 return revokedSessionIds.length;
965 });
966​
967 return SessionStore.of({
968 cookieName,
969 legacyCookieName,
970 issue,
971 verify,
972 issueWebSocketToken,
973 verifyWebSocketToken,
974 listActive,
975 get streamChanges() {
976 return Stream.fromPubSub(changesPubSub);
977 },
978 revoke,
979 revokeAllExcept,
980 markConnected,
981 markDisconnected,
982 recordClientConnection,
983 });
984});
985​
986export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));