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 RuntimeMode,
10 type ServerAuthSessionMethod,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as Crypto from "effect/Crypto";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as PubSub from "effect/PubSub";
19import * as Ref from "effect/Ref";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import * as Option from "effect/Option";
23
24import * as ServerConfig from "../config.ts";
25import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26import * as AuthSessions from "../persistence/AuthSessions.ts";
27import * as ServerSecretStore from "./ServerSecretStore.ts";
28import {
29 REUSABLE_DEV_SESSION_EXPIRES_AT,
30 REUSABLE_DEV_SESSION_PREFIX,
31 resolveReusableDevAuth,
32} from "./ReusableDevAuth.ts";
33import {
34 base64UrlDecodeUtf8,
35 base64UrlEncode,
36 resolveLegacySessionCookieName,
37 resolveSessionCookieName,
38 signPayload,
39 timingSafeEqualBase64Url,
40} from "./utils.ts";
41
42export interface IssuedSession {
43 readonly sessionId: AuthSessionId;
44 readonly token: string;
45 readonly method: ServerAuthSessionMethod;
46 readonly client: AuthClientMetadata;
47 readonly expiresAt: DateTime.DateTime;
48 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
49 readonly proofKeyThumbprint?: string;
50}
51
52export interface VerifiedSession {
53 readonly sessionId: AuthSessionId;
54 readonly token: string;
55 readonly method: ServerAuthSessionMethod;
56 readonly client: AuthClientMetadata;
57 readonly expiresAt?: DateTime.DateTime;
58 readonly subject: string;
59 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
60 readonly proofKeyThumbprint?: string;
61 readonly runtimeModeCeiling?: RuntimeMode;
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 readonly runtimeModeCeiling?: RuntimeMode;
379 readonly replaceActiveForSubjectAndMethod?: boolean;
380 readonly replaceSessionId?: AuthSessionId;
381 }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
382 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
383 readonly issueWebSocketToken: (
384 sessionId: AuthSessionId,
385 input?: {
386 readonly ttl?: Duration.Duration;
387 },
388 ) => Effect.Effect<
389 {
390 readonly token: string;
391 readonly expiresAt: DateTime.DateTime;
392 },
393 SessionCredentialInternalError
394 >;
395 readonly verifyWebSocketToken: (
396 token: string,
397 ) => Effect.Effect<VerifiedSession, SessionCredentialError>;
398 readonly listActive: () => Effect.Effect<
399 ReadonlyArray<AuthClientSession>,
400 SessionCredentialInternalError
401 >;
402 readonly streamChanges: Stream.Stream<SessionCredentialChange>;
403 readonly awaitInvalidation: (
404 sessionId: AuthSessionId,
405 ) => Effect.Effect<void, SessionCredentialVerificationError>;
406 readonly revoke: (
407 sessionId: AuthSessionId,
408 ) => Effect.Effect<boolean, SessionCredentialInternalError>;
409 readonly revokeAllExcept: (
410 sessionId: AuthSessionId,
411 ) => Effect.Effect<number, SessionCredentialInternalError>;
412 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
413 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
414 readonly recordClientConnection: (
415 sessionId: AuthSessionId,
416 client: {
417 readonly surface?: ClientSurface | undefined;
418 readonly appVersion?: string | undefined;
419 },
420 ) => Effect.Effect<void, never>;
421 }
422>()("t3/auth/SessionStore") {}
423
424const SIGNING_SECRET_NAME = "server-signing-key";
425const DEFAULT_SESSION_TTL = Duration.days(30);
426const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
427
428const SessionClaims = Schema.Struct({
429 v: Schema.Literals([1, 2]),
430 kind: Schema.Literal("session"),
431 sid: AuthSessionId,
432 sub: Schema.String,
433 scopes: AuthEnvironmentScopes,
434 method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
435 jkt: Schema.optionalKey(Schema.String),
436 rtc: Schema.optionalKey(RuntimeMode),
437 iat: Schema.Number,
438 exp: Schema.Number,
439});
440type SessionClaims = typeof SessionClaims.Type;
441
442const WebSocketClaims = Schema.Struct({
443 v: Schema.Literal(1),
444 kind: Schema.Literal("websocket"),
445 sid: AuthSessionId,
446 iat: Schema.Number,
447 exp: Schema.Number,
448});
449type WebSocketClaims = typeof WebSocketClaims.Type;
450
451const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
452const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
453
454function createDefaultClientMetadata(): AuthClientMetadata {
455 return {
456 deviceType: "unknown",
457 };
458}
459
460function toClientMetadata(record: {
461 readonly label: string | null;
462 readonly ipAddress: string | null;
463 readonly userAgent: string | null;
464 readonly deviceType: AuthClientMetadata["deviceType"];
465 readonly os: string | null;
466 readonly browser: string | null;
467}): AuthClientMetadata {
468 return {
469 ...(record.label ? { label: record.label } : {}),
470 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
471 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
472 deviceType: record.deviceType,
473 ...(record.os ? { os: record.os } : {}),
474 ...(record.browser ? { browser: record.browser } : {}),
475 };
476}
477
478function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
479 return {
480 ...input,
481 current: false,
482 };
483}
484
485export const make = Effect.gen(function* () {
486 const crypto = yield* Crypto.Crypto;
487 const serverConfig = yield* ServerConfig.ServerConfig;
488 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
489 const secretStore = yield* ServerSecretStore.ServerSecretStore;
490 const authSessions = yield* AuthSessions.AuthSessionRepository;
491 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
492 const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
493 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
494 const cookieInput = {
495 mode: serverConfig.mode,
496 port: serverConfig.port,
497 host: serverConfig.host,
498 instanceKey: serverConfig.stateDir,
499 environmentId: yield* serverEnvironment.getEnvironmentId,
500 development: serverConfig.devUrl !== undefined,
501 } as const;
502 const cookieName = resolveSessionCookieName(cookieInput);
503 const legacyCookieName = resolveLegacySessionCookieName(cookieInput);
504 const devAuth = resolveReusableDevAuth(serverConfig);
505 if (devAuth) {
506 yield* authSessions
507 .createIfAbsent({
508 sessionId: devAuth.sessionId,
509 subject: "reusable-dev-token",
510 scopes: AuthStandardClientScopes,
511 method: "browser-session-cookie",
512 client: {
513 label: "Reusable dev token",
514 ipAddress: null,
515 userAgent: null,
516 deviceType: "unknown",
517 os: null,
518 browser: null,
519 },
520 issuedAt: yield* DateTime.now,
521 expiresAt: REUSABLE_DEV_SESSION_EXPIRES_AT,
522 })
523 .pipe(
524 Effect.mapError(
525 (cause) => new SessionCredentialIssueError({ sessionId: devAuth.sessionId, cause }),
526 ),
527 );
528 }
529
530 const emitUpsert = (clientSession: AuthClientSession) =>
531 PubSub.publish(changesPubSub, {
532 type: "clientUpserted",
533 clientSession,
534 }).pipe(Effect.asVoid);
535
536 const emitRemoved = (sessionId: AuthSessionId) =>
537 PubSub.publish(changesPubSub, {
538 type: "clientRemoved",
539 sessionId,
540 }).pipe(Effect.asVoid);
541
542 const loadActiveSession = Effect.fn("SessionStore.loadActiveSession")(function* (
543 sessionId: AuthSessionId,
544 ) {
545 const row = yield* authSessions.getById({ sessionId });
546 if (Option.isNone(row) || row.value.revokedAt !== null) {
547 return Option.none<AuthClientSession>();
548 }
549
550 const connectedSessions = yield* Ref.get(connectedSessionsRef);
551 const connected = connectedSessions.has(row.value.sessionId);
552 const now = yield* DateTime.now;
553 if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
554 return Option.none<AuthClientSession>();
555 }
556 return Option.some(
557 toAuthClientSession({
558 sessionId: row.value.sessionId,
559 subject: row.value.subject,
560 scopes: row.value.scopes,
561 method: row.value.method,
562 client: toClientMetadata(row.value.client),
563 issuedAt: row.value.issuedAt,
564 expiresAt: row.value.expiresAt,
565 lastConnectedAt: row.value.lastConnectedAt,
566 connected,
567 }),
568 );
569 });
570
571 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
572 Ref.modify(connectedSessionsRef, (current) => {
573 const next = new Map(current);
574 const wasDisconnected = !next.has(sessionId);
575 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
576 return [wasDisconnected, next] as const;
577 }).pipe(
578 Effect.flatMap((wasDisconnected) =>
579 wasDisconnected
580 ? DateTime.now.pipe(
581 Effect.flatMap((lastConnectedAt) =>
582 authSessions.setLastConnectedAt({
583 sessionId,
584 lastConnectedAt,
585 }),
586 ),
587 )
588 : Effect.void,
589 ),
590 Effect.flatMap(() => loadActiveSession(sessionId)),
591 Effect.flatMap((session) =>
592 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
593 ),
594 Effect.catchCause((cause) =>
595 Effect.logError("Failed to publish connected-session auth update.").pipe(
596 Effect.annotateLogs({
597 sessionId,
598 cause,
599 }),
600 ),
601 ),
602 Effect.withSpan("SessionStore.markConnected"),
603 );
604
605 const recordClientConnection: SessionStore["Service"]["recordClientConnection"] = (
606 sessionId,
607 client,
608 ) =>
609 client.surface === undefined && client.appVersion === undefined
610 ? Effect.void
611 : authSessions
612 .setClientConnection({
613 sessionId,
614 surface: client.surface ?? null,
615 appVersion: client.appVersion ?? null,
616 })
617 .pipe(
618 Effect.catchCause((cause) =>
619 Effect.logWarning("Failed to record session client connection metadata.").pipe(
620 Effect.annotateLogs({ sessionId, cause }),
621 ),
622 ),
623 Effect.withSpan("SessionStore.recordClientConnection"),
624 );
625
626 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
627 Ref.update(connectedSessionsRef, (current) => {
628 const next = new Map(current);
629 const remaining = (next.get(sessionId) ?? 0) - 1;
630 if (remaining > 0) {
631 next.set(sessionId, remaining);
632 } else {
633 next.delete(sessionId);
634 }
635 return next;
636 }).pipe(
637 Effect.flatMap(() => loadActiveSession(sessionId)),
638 Effect.flatMap((session) =>
639 Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
640 ),
641 Effect.catchCause((cause) =>
642 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
643 Effect.annotateLogs({
644 sessionId,
645 cause,
646 }),
647 ),
648 ),
649 Effect.withSpan("SessionStore.markDisconnected"),
650 );
651
652 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
653 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
654 function* (input) {
655 const sessionId = AuthSessionId.make(
656 yield* crypto
657 .randomUUIDv4()
658 .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ cause }))),
659 );
660 const issuedAt = yield* DateTime.now;
661 const expiresAt = DateTime.add(issuedAt, {
662 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
663 });
664 const claims: SessionClaims = {
665 v: 1,
666 kind: "session",
667 sid: sessionId,
668 sub: input?.subject ?? "browser",
669 scopes: input?.scopes ?? AuthStandardClientScopes,
670 method: input?.method ?? "browser-session-cookie",
671 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
672 ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
673 iat: issuedAt.epochMilliseconds,
674 exp: expiresAt.epochMilliseconds,
675 };
676
677 const encodedPayload = yield* encodeClaims(claims).pipe(
678 Effect.map(base64UrlEncode),
679 Effect.mapError(
680 (cause) =>
681 new SessionCredentialIssueError({
682 sessionId,
683 cause: new SessionClaimsEncodingError({
684 sessionId,
685 operation: "encode_session_claims",
686 cause,
687 }),
688 }),
689 ),
690 );
691 const signature = signPayload(encodedPayload, signingSecret);
692 const client = input?.client ?? createDefaultClientMetadata();
693 const sessionRecord = {
694 sessionId,
695 subject: claims.sub,
696 scopes: claims.scopes,
697 method: claims.method,
698 client: {
699 label: client.label ?? null,
700 ipAddress: client.ipAddress ?? null,
701 userAgent: client.userAgent ?? null,
702 deviceType: client.deviceType,
703 os: client.os ?? null,
704 browser: client.browser ?? null,
705 },
706 issuedAt,
707 expiresAt,
708 } satisfies AuthSessions.CreateAuthSessionInput;
709 const replacedSessionIds = yield* (
710 input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod
711 ? authSessions.createReplacingActive({
712 session: sessionRecord,
713 revokedAt: issuedAt,
714 ...(input.replaceSessionId !== undefined
715 ? { replaceSessionId: input.replaceSessionId }
716 : {}),
717 })
718 : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>))
719 ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
720 if (replacedSessionIds.length > 0) {
721 yield* Ref.update(connectedSessionsRef, (current) => {
722 const next = new Map(current);
723 for (const replacedSessionId of replacedSessionIds) {
724 next.delete(replacedSessionId);
725 }
726 return next;
727 });
728 yield* Effect.forEach(replacedSessionIds, emitRemoved, {
729 concurrency: "unbounded",
730 discard: true,
731 });
732 }
733 yield* emitUpsert(
734 toAuthClientSession({
735 sessionId,
736 subject: claims.sub,
737 scopes: claims.scopes,
738 method: claims.method,
739 client,
740 issuedAt,
741 expiresAt,
742 lastConnectedAt: null,
743 connected: false,
744 }),
745 );
746
747 return {
748 sessionId,
749 token: `${encodedPayload}.${signature}`,
750 method: claims.method,
751 client,
752 expiresAt: expiresAt,
753 scopes: claims.scopes,
754 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
755 } satisfies IssuedSession;
756 },
757 );
758
759 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
760 function* (token) {
761 if (devAuth?.matches(token)) {
762 const row = yield* authSessions
763 .getById({ sessionId: devAuth.sessionId })
764 .pipe(
765 Effect.mapError(
766 (cause) =>
767 new SessionCredentialVerificationError({ sessionId: devAuth.sessionId, cause }),
768 ),
769 );
770 if (Option.isNone(row)) {
771 return yield* new UnknownSessionTokenError({ sessionId: devAuth.sessionId });
772 }
773 if (row.value.revokedAt !== null) {
774 return yield* new SessionTokenRevokedError({
775 sessionId: devAuth.sessionId,
776 revokedAt: row.value.revokedAt,
777 });
778 }
779 const observedAt = yield* DateTime.now;
780 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
781 return yield* new SessionTokenExpiredError({
782 sessionId: devAuth.sessionId,
783 expiresAt: row.value.expiresAt,
784 observedAt,
785 });
786 }
787 return {
788 sessionId: row.value.sessionId,
789 token,
790 method: row.value.method,
791 client: toClientMetadata(row.value.client),
792 expiresAt: row.value.expiresAt,
793 subject: row.value.subject,
794 scopes: row.value.scopes,
795 } satisfies VerifiedSession;
796 }
797 const [encodedPayload, signature] = token.split(".");
798 if (!encodedPayload || !signature) {
799 return yield* new MalformedSessionTokenError({});
800 }
801
802 const expectedSignature = signPayload(encodedPayload, signingSecret);
803 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
804 return yield* new InvalidSessionTokenSignatureError({});
805 }
806
807 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
808 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
809 );
810
811 const observedAt = yield* DateTime.now;
812 const expiresAt = DateTime.make(claims.exp);
813 if (Option.isNone(expiresAt)) {
814 return yield* new InvalidSessionExpirationClaimError({
815 sessionId: claims.sid,
816 expirationClaim: claims.exp,
817 });
818 }
819 if (claims.exp <= observedAt.epochMilliseconds) {
820 return yield* new SessionTokenExpiredError({
821 sessionId: claims.sid,
822 expiresAt: expiresAt.value,
823 observedAt,
824 });
825 }
826
827 const row = yield* authSessions
828 .getById({ sessionId: claims.sid })
829 .pipe(
830 Effect.mapError(
831 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
832 ),
833 );
834 if (Option.isNone(row)) {
835 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
836 }
837 if (row.value.revokedAt !== null) {
838 return yield* new SessionTokenRevokedError({
839 sessionId: claims.sid,
840 revokedAt: row.value.revokedAt,
841 });
842 }
843
844 return {
845 sessionId: claims.sid,
846 token,
847 method: claims.method,
848 client: toClientMetadata(row.value.client),
849 expiresAt: expiresAt.value,
850 subject: claims.sub,
851 scopes: claims.scopes,
852 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
853 ...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
854 } satisfies VerifiedSession;
855 },
856 );
857
858 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
859 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
860 "SessionStore.issueWebSocketToken",
861 )(function* (sessionId, input) {
862 const issuedAt = yield* DateTime.now;
863 const expiresAt = DateTime.add(issuedAt, {
864 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
865 });
866 const claims: WebSocketClaims = {
867 v: 1,
868 kind: "websocket",
869 sid: sessionId,
870 iat: issuedAt.epochMilliseconds,
871 exp: expiresAt.epochMilliseconds,
872 };
873 const encodedPayload = yield* encodeWsClaims(claims).pipe(
874 Effect.map(base64UrlEncode),
875 Effect.mapError(
876 (cause) =>
877 new WebSocketTokenIssueError({
878 sessionId,
879 cause: new SessionClaimsEncodingError({
880 sessionId,
881 operation: "encode_websocket_claims",
882 cause,
883 }),
884 }),
885 ),
886 );
887 const signature = signPayload(encodedPayload, signingSecret);
888 return {
889 token: `${encodedPayload}.${signature}`,
890 expiresAt,
891 };
892 });
893
894 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
895 "SessionStore.verifyWebSocketToken",
896 )(function* (token) {
897 const [encodedPayload, signature] = token.split(".");
898 if (!encodedPayload || !signature) {
899 return yield* new MalformedWebSocketTokenError({});
900 }
901
902 const expectedSignature = signPayload(encodedPayload, signingSecret);
903 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
904 return yield* new InvalidWebSocketTokenSignatureError({});
905 }
906
907 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
908 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
909 );
910 if (claims.sid.startsWith(REUSABLE_DEV_SESSION_PREFIX) && claims.sid !== devAuth?.sessionId) {
911 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
912 }
913
914 const observedAt = yield* DateTime.now;
915 const expiresAt = DateTime.make(claims.exp);
916 if (Option.isNone(expiresAt)) {
917 return yield* new InvalidSessionExpirationClaimError({
918 sessionId: claims.sid,
919 expirationClaim: claims.exp,
920 });
921 }
922 if (claims.exp <= observedAt.epochMilliseconds) {
923 return yield* new WebSocketTokenExpiredError({
924 sessionId: claims.sid,
925 expiresAt: expiresAt.value,
926 observedAt,
927 });
928 }
929
930 const row = yield* authSessions
931 .getById({ sessionId: claims.sid })
932 .pipe(
933 Effect.mapError(
934 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
935 ),
936 );
937 if (Option.isNone(row)) {
938 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
939 }
940 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
941 return yield* new WebSocketSessionExpiredError({
942 sessionId: claims.sid,
943 expiresAt: row.value.expiresAt,
944 observedAt,
945 });
946 }
947 if (row.value.revokedAt !== null) {
948 return yield* new WebSocketSessionRevokedError({
949 sessionId: claims.sid,
950 revokedAt: row.value.revokedAt,
951 });
952 }
953
954 return {
955 sessionId: row.value.sessionId,
956 token,
957 method: row.value.method,
958 client: toClientMetadata(row.value.client),
959 expiresAt: row.value.expiresAt,
960 subject: row.value.subject,
961 scopes: row.value.scopes,
962 } satisfies VerifiedSession;
963 });
964
965 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
966 function* () {
967 const now = yield* DateTime.now;
968 const connectedSessions = yield* Ref.get(connectedSessionsRef);
969 const rows = yield* authSessions.listActive({
970 now,
971 connectedSessionIds: Array.from(connectedSessions.keys()),
972 });
973
974 return rows.map((row) =>
975 toAuthClientSession({
976 sessionId: row.sessionId,
977 subject: row.subject,
978 scopes: row.scopes,
979 method: row.method,
980 client: toClientMetadata(row.client),
981 issuedAt: row.issuedAt,
982 expiresAt: row.expiresAt,
983 lastConnectedAt: row.lastConnectedAt,
984 connected: connectedSessions.has(row.sessionId),
985 }),
986 );
987 },
988 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
989 );
990
991 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
992 function* (sessionId) {
993 const revokedAt = yield* DateTime.now;
994 const revoked = yield* authSessions
995 .revoke({
996 sessionId,
997 revokedAt,
998 })
999 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
1000 if (revoked) {
1001 yield* Ref.update(connectedSessionsRef, (current) => {
1002 const next = new Map(current);
1003 next.delete(sessionId);
1004 return next;
1005 });
1006 yield* emitRemoved(sessionId);
1007 }
1008 return revoked;
1009 },
1010 );
1011
1012 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
1013 "SessionStore.revokeAllExcept",
1014 )(function* (sessionId) {
1015 const revokedAt = yield* DateTime.now;
1016 const revokedSessionIds = yield* authSessions
1017 .revokeAllExcept({
1018 currentSessionId: sessionId,
1019 revokedAt,
1020 })
1021 .pipe(
1022 Effect.mapError(
1023 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
1024 ),
1025 );
1026 if (revokedSessionIds.length > 0) {
1027 yield* Ref.update(connectedSessionsRef, (current) => {
1028 const next = new Map(current);
1029 for (const revokedSessionId of revokedSessionIds) {
1030 next.delete(revokedSessionId);
1031 }
1032 return next;
1033 });
1034 yield* Effect.forEach(
1035 revokedSessionIds,
1036 (revokedSessionId) => emitRemoved(revokedSessionId),
1037 {
1038 concurrency: "unbounded",
1039 discard: true,
1040 },
1041 );
1042 }
1043 return revokedSessionIds.length;
1044 });
1045
1046 const awaitInvalidation = Effect.fn(function* (sessionId: AuthSessionId) {
1047 return yield* Effect.scoped(
1048 Effect.gen(function* () {
1049 // Subscribe before reading: revocation can race with the WebSocket upgrade.
1050 const subscription = yield* PubSub.subscribe(changesPubSub);
1051 const row = yield* authSessions
1052 .getById({ sessionId })
1053 .pipe(
1054 Effect.mapError(
1055 (cause) => new SessionCredentialVerificationError({ sessionId, cause }),
1056 ),
1057 );
1058 if (Option.isNone(row) || row.value.revokedAt !== null) return;
1059 const now = yield* DateTime.now;
1060 const remaining = row.value.expiresAt.epochMilliseconds - now.epochMilliseconds;
1061 if (remaining <= 0) return;
1062 yield* Effect.raceFirst(
1063 Stream.fromSubscription(subscription).pipe(
1064 Stream.filter(
1065 (change) => change.type === "clientRemoved" && change.sessionId === sessionId,
1066 ),
1067 Stream.runHead,
1068 ),
1069 Effect.sleep(Duration.millis(remaining)),
1070 );
1071 }),
1072 );
1073 });
1074
1075 return SessionStore.of({
1076 cookieName,
1077 legacyCookieName,
1078 issue,
1079 verify,
1080 issueWebSocketToken,
1081 verifyWebSocketToken,
1082 listActive,
1083 awaitInvalidation,
1084 get streamChanges() {
1085 return Stream.fromPubSub(changesPubSub);
1086 },
1087 revoke,
1088 revokeAllExcept,
1089 markConnected,
1090 markDisconnected,
1091 recordClientConnection,
1092 });
1093});
1094
1095export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));