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