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