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

SessionStore.ts

978 lines30.3 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<string, 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 return Option.some(
519 toAuthClientSession({
520 sessionId: row.value.sessionId,
521 subject: row.value.subject,
522 scopes: row.value.scopes,
523 method: row.value.method,
524 client: toClientMetadata(row.value.client),
525 issuedAt: row.value.issuedAt,
526 expiresAt: row.value.expiresAt,
527 lastConnectedAt: row.value.lastConnectedAt,
528 connected: connectedSessions.has(row.value.sessionId),
529 }),
530 );
531 });
532​
533 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
534 Ref.modify(connectedSessionsRef, (current) => {
535 const next = new Map(current);
536 const wasDisconnected = !next.has(sessionId);
537 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
538 return [wasDisconnected, next] as const;
539 }).pipe(
540 Effect.flatMap((wasDisconnected) =>
541 wasDisconnected
542 ? DateTime.now.pipe(
543 Effect.flatMap((lastConnectedAt) =>
544 authSessions.setLastConnectedAt({
545 sessionId,
546 lastConnectedAt,
547 }),
548 ),
549 )
550 : Effect.void,
551 ),
552 Effect.flatMap(() => loadActiveSession(sessionId)),
553 Effect.flatMap((session) =>
554 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
555 ),
556 Effect.catchCause((cause) =>
557 Effect.logError("Failed to publish connected-session auth update.").pipe(
558 Effect.annotateLogs({
559 sessionId,
560 cause,
561 }),
562 ),
563 ),
564 Effect.withSpan("SessionStore.markConnected"),
565 );
566​
567 // Best-effort: connection metadata must never block or fail a connect.
568 const recordClientConnection: SessionStore["Service"]["recordClientConnection"] = (
569 sessionId,
570 client,
571 ) =>
572 client.surface === undefined && client.appVersion === undefined
573 ? Effect.void
574 : authSessions
575 .setClientConnection({
576 sessionId,
577 surface: client.surface ?? null,
578 appVersion: client.appVersion ?? null,
579 })
580 .pipe(
581 Effect.catchCause((cause) =>
582 Effect.logWarning("Failed to record session client connection metadata.").pipe(
583 Effect.annotateLogs({ sessionId, cause }),
584 ),
585 ),
586 Effect.withSpan("SessionStore.recordClientConnection"),
587 );
588​
589 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
590 Ref.update(connectedSessionsRef, (current) => {
591 const next = new Map(current);
592 const remaining = (next.get(sessionId) ?? 0) - 1;
593 if (remaining > 0) {
594 next.set(sessionId, remaining);
595 } else {
596 next.delete(sessionId);
597 }
598 return next;
599 }).pipe(
600 Effect.flatMap(() => loadActiveSession(sessionId)),
601 Effect.flatMap((session) =>
602 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
603 ),
604 Effect.catchCause((cause) =>
605 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
606 Effect.annotateLogs({
607 sessionId,
608 cause,
609 }),
610 ),
611 ),
612 Effect.withSpan("SessionStore.markDisconnected"),
613 );
614​
615 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
616 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
617 function* (input) {
618 const sessionId = AuthSessionId.make(
619 yield* crypto.randomUUIDv4.pipe(
620 Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
621 ),
622 );
623 const issuedAt = yield* DateTime.now;
624 const expiresAt = DateTime.add(issuedAt, {
625 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
626 });
627 const claims: SessionClaims = {
628 v: 1,
629 kind: "session",
630 sid: sessionId,
631 sub: input?.subject ?? "browser",
632 scopes: input?.scopes ?? AuthStandardClientScopes,
633 method: input?.method ?? "browser-session-cookie",
634 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
635 iat: issuedAt.epochMilliseconds,
636 exp: expiresAt.epochMilliseconds,
637 };
638​
639 const encodedPayload = yield* encodeClaims(claims).pipe(
640 Effect.map(base64UrlEncode),
641 Effect.mapError(
642 (cause) =>
643 new SessionCredentialIssueError({
644 sessionId,
645 cause: new SessionClaimsEncodingError({
646 sessionId,
647 operation: "encode_session_claims",
648 cause,
649 }),
650 }),
651 ),
652 );
653 const signature = signPayload(encodedPayload, signingSecret);
654 const client = input?.client ?? createDefaultClientMetadata();
655 const sessionRecord = {
656 sessionId,
657 subject: claims.sub,
658 scopes: claims.scopes,
659 method: claims.method,
660 client: {
661 label: client.label ?? null,
662 ipAddress: client.ipAddress ?? null,
663 userAgent: client.userAgent ?? null,
664 deviceType: client.deviceType,
665 os: client.os ?? null,
666 browser: client.browser ?? null,
667 },
668 issuedAt,
669 expiresAt,
670 } satisfies AuthSessions.CreateAuthSessionInput;
671 const replacedSessionIds = yield* (
672 input?.replaceActiveForSubjectAndMethod
673 ? authSessions.createReplacingActive({ session: sessionRecord, revokedAt: issuedAt })
674 : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>))
675 ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
676 if (replacedSessionIds.length > 0) {
677 yield* Ref.update(connectedSessionsRef, (current) => {
678 const next = new Map(current);
679 for (const replacedSessionId of replacedSessionIds) {
680 next.delete(replacedSessionId);
681 }
682 return next;
683 });
684 yield* Effect.forEach(replacedSessionIds, emitRemoved, {
685 concurrency: "unbounded",
686 discard: true,
687 });
688 }
689 yield* emitUpsert(
690 toAuthClientSession({
691 sessionId,
692 subject: claims.sub,
693 scopes: claims.scopes,
694 method: claims.method,
695 client,
696 issuedAt,
697 expiresAt,
698 lastConnectedAt: null,
699 connected: false,
700 }),
701 );
702​
703 return {
704 sessionId,
705 token: `${encodedPayload}.${signature}`,
706 method: claims.method,
707 client,
708 expiresAt: expiresAt,
709 scopes: claims.scopes,
710 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
711 } satisfies IssuedSession;
712 },
713 );
714​
715 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
716 function* (token) {
717 const [encodedPayload, signature] = token.split(".");
718 if (!encodedPayload || !signature) {
719 return yield* new MalformedSessionTokenError({});
720 }
721​
722 const expectedSignature = signPayload(encodedPayload, signingSecret);
723 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
724 return yield* new InvalidSessionTokenSignatureError({});
725 }
726​
727 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
728 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
729 );
730​
731 const observedAt = yield* DateTime.now;
732 const expiresAt = DateTime.make(claims.exp);
733 if (Option.isNone(expiresAt)) {
734 return yield* new InvalidSessionExpirationClaimError({
735 sessionId: claims.sid,
736 expirationClaim: claims.exp,
737 });
738 }
739 if (claims.exp <= observedAt.epochMilliseconds) {
740 return yield* new SessionTokenExpiredError({
741 sessionId: claims.sid,
742 expiresAt: expiresAt.value,
743 observedAt,
744 });
745 }
746​
747 const row = yield* authSessions
748 .getById({ sessionId: claims.sid })
749 .pipe(
750 Effect.mapError(
751 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
752 ),
753 );
754 if (Option.isNone(row)) {
755 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
756 }
757 if (row.value.revokedAt !== null) {
758 return yield* new SessionTokenRevokedError({
759 sessionId: claims.sid,
760 revokedAt: row.value.revokedAt,
761 });
762 }
763​
764 return {
765 sessionId: claims.sid,
766 token,
767 method: claims.method,
768 client: toClientMetadata(row.value.client),
769 expiresAt: expiresAt.value,
770 subject: claims.sub,
771 scopes: claims.scopes,
772 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
773 } satisfies VerifiedSession;
774 },
775 );
776​
777 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
778 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
779 "SessionStore.issueWebSocketToken",
780 )(function* (sessionId, input) {
781 const issuedAt = yield* DateTime.now;
782 const expiresAt = DateTime.add(issuedAt, {
783 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
784 });
785 const claims: WebSocketClaims = {
786 v: 1,
787 kind: "websocket",
788 sid: sessionId,
789 iat: issuedAt.epochMilliseconds,
790 exp: expiresAt.epochMilliseconds,
791 };
792 const encodedPayload = yield* encodeWsClaims(claims).pipe(
793 Effect.map(base64UrlEncode),
794 Effect.mapError(
795 (cause) =>
796 new WebSocketTokenIssueError({
797 sessionId,
798 cause: new SessionClaimsEncodingError({
799 sessionId,
800 operation: "encode_websocket_claims",
801 cause,
802 }),
803 }),
804 ),
805 );
806 const signature = signPayload(encodedPayload, signingSecret);
807 return {
808 token: `${encodedPayload}.${signature}`,
809 expiresAt,
810 };
811 });
812​
813 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
814 "SessionStore.verifyWebSocketToken",
815 )(function* (token) {
816 const [encodedPayload, signature] = token.split(".");
817 if (!encodedPayload || !signature) {
818 return yield* new MalformedWebSocketTokenError({});
819 }
820​
821 const expectedSignature = signPayload(encodedPayload, signingSecret);
822 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
823 return yield* new InvalidWebSocketTokenSignatureError({});
824 }
825​
826 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
827 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
828 );
829​
830 const observedAt = yield* DateTime.now;
831 const expiresAt = DateTime.make(claims.exp);
832 if (Option.isNone(expiresAt)) {
833 return yield* new InvalidSessionExpirationClaimError({
834 sessionId: claims.sid,
835 expirationClaim: claims.exp,
836 });
837 }
838 if (claims.exp <= observedAt.epochMilliseconds) {
839 return yield* new WebSocketTokenExpiredError({
840 sessionId: claims.sid,
841 expiresAt: expiresAt.value,
842 observedAt,
843 });
844 }
845​
846 const row = yield* authSessions
847 .getById({ sessionId: claims.sid })
848 .pipe(
849 Effect.mapError(
850 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
851 ),
852 );
853 if (Option.isNone(row)) {
854 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
855 }
856 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
857 return yield* new WebSocketSessionExpiredError({
858 sessionId: claims.sid,
859 expiresAt: row.value.expiresAt,
860 observedAt,
861 });
862 }
863 if (row.value.revokedAt !== null) {
864 return yield* new WebSocketSessionRevokedError({
865 sessionId: claims.sid,
866 revokedAt: row.value.revokedAt,
867 });
868 }
869​
870 return {
871 sessionId: row.value.sessionId,
872 token,
873 method: row.value.method,
874 client: toClientMetadata(row.value.client),
875 expiresAt: row.value.expiresAt,
876 subject: row.value.subject,
877 scopes: row.value.scopes,
878 } satisfies VerifiedSession;
879 });
880​
881 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
882 function* () {
883 const now = yield* DateTime.now;
884 const connectedSessions = yield* Ref.get(connectedSessionsRef);
885 const rows = yield* authSessions.listActive({ now });
886​
887 return rows.map((row) =>
888 toAuthClientSession({
889 sessionId: row.sessionId,
890 subject: row.subject,
891 scopes: row.scopes,
892 method: row.method,
893 client: toClientMetadata(row.client),
894 issuedAt: row.issuedAt,
895 expiresAt: row.expiresAt,
896 lastConnectedAt: row.lastConnectedAt,
897 connected: connectedSessions.has(row.sessionId),
898 }),
899 );
900 },
901 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
902 );
903​
904 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
905 function* (sessionId) {
906 const revokedAt = yield* DateTime.now;
907 const revoked = yield* authSessions
908 .revoke({
909 sessionId,
910 revokedAt,
911 })
912 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
913 if (revoked) {
914 yield* Ref.update(connectedSessionsRef, (current) => {
915 const next = new Map(current);
916 next.delete(sessionId);
917 return next;
918 });
919 yield* emitRemoved(sessionId);
920 }
921 return revoked;
922 },
923 );
924​
925 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
926 "SessionStore.revokeAllExcept",
927 )(function* (sessionId) {
928 const revokedAt = yield* DateTime.now;
929 const revokedSessionIds = yield* authSessions
930 .revokeAllExcept({
931 currentSessionId: sessionId,
932 revokedAt,
933 })
934 .pipe(
935 Effect.mapError(
936 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
937 ),
938 );
939 if (revokedSessionIds.length > 0) {
940 yield* Ref.update(connectedSessionsRef, (current) => {
941 const next = new Map(current);
942 for (const revokedSessionId of revokedSessionIds) {
943 next.delete(revokedSessionId);
944 }
945 return next;
946 });
947 yield* Effect.forEach(
948 revokedSessionIds,
949 (revokedSessionId) => emitRemoved(revokedSessionId),
950 {
951 concurrency: "unbounded",
952 discard: true,
953 },
954 );
955 }
956 return revokedSessionIds.length;
957 });
958​
959 return SessionStore.of({
960 cookieName,
961 legacyCookieName,
962 issue,
963 verify,
964 issueWebSocketToken,
965 verifyWebSocketToken,
966 listActive,
967 get streamChanges() {
968 return Stream.fromPubSub(changesPubSub);
969 },
970 revoke,
971 revokeAllExcept,
972 markConnected,
973 markDisconnected,
974 recordClientConnection,
975 });
976});
977​
978export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));