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