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 = (sessionId: AuthSessionId) =>
543 Effect.gen(function* () {
544 const row = yield* authSessions.getById({ sessionId });
545 if (Option.isNone(row) || row.value.revokedAt !== null) {
546 return Option.none<AuthClientSession>();
547 }
548
549 const connectedSessions = yield* Ref.get(connectedSessionsRef);
550 const connected = connectedSessions.has(row.value.sessionId);
551 const now = yield* DateTime.now;
552 if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
553 return Option.none<AuthClientSession>();
554 }
555 return Option.some(
556 toAuthClientSession({
557 sessionId: row.value.sessionId,
558 subject: row.value.subject,
559 scopes: row.value.scopes,
560 method: row.value.method,
561 client: toClientMetadata(row.value.client),
562 issuedAt: row.value.issuedAt,
563 expiresAt: row.value.expiresAt,
564 lastConnectedAt: row.value.lastConnectedAt,
565 connected,
566 }),
567 );
568 });
569
570 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
571 Ref.modify(connectedSessionsRef, (current) => {
572 const next = new Map(current);
573 const wasDisconnected = !next.has(sessionId);
574 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
575 return [wasDisconnected, next] as const;
576 }).pipe(
577 Effect.flatMap((wasDisconnected) =>
578 wasDisconnected
579 ? DateTime.now.pipe(
580 Effect.flatMap((lastConnectedAt) =>
581 authSessions.setLastConnectedAt({
582 sessionId,
583 lastConnectedAt,
584 }),
585 ),
586 )
587 : Effect.void,
588 ),
589 Effect.flatMap(() => loadActiveSession(sessionId)),
590 Effect.flatMap((session) =>
591 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
592 ),
593 Effect.catchCause((cause) =>
594 Effect.logError("Failed to publish connected-session auth update.").pipe(
595 Effect.annotateLogs({
596 sessionId,
597 cause,
598 }),
599 ),
600 ),
601 Effect.withSpan("SessionStore.markConnected"),
602 );
603
604 const recordClientConnection: SessionStore["Service"]["recordClientConnection"] = (
605 sessionId,
606 client,
607 ) =>
608 client.surface === undefined && client.appVersion === undefined
609 ? Effect.void
610 : authSessions
611 .setClientConnection({
612 sessionId,
613 surface: client.surface ?? null,
614 appVersion: client.appVersion ?? null,
615 })
616 .pipe(
617 Effect.catchCause((cause) =>
618 Effect.logWarning("Failed to record session client connection metadata.").pipe(
619 Effect.annotateLogs({ sessionId, cause }),
620 ),
621 ),
622 Effect.withSpan("SessionStore.recordClientConnection"),
623 );
624
625 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
626 Ref.update(connectedSessionsRef, (current) => {
627 const next = new Map(current);
628 const remaining = (next.get(sessionId) ?? 0) - 1;
629 if (remaining > 0) {
630 next.set(sessionId, remaining);
631 } else {
632 next.delete(sessionId);
633 }
634 return next;
635 }).pipe(
636 Effect.flatMap(() => loadActiveSession(sessionId)),
637 Effect.flatMap((session) =>
638 Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
639 ),
640 Effect.catchCause((cause) =>
641 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
642 Effect.annotateLogs({
643 sessionId,
644 cause,
645 }),
646 ),
647 ),
648 Effect.withSpan("SessionStore.markDisconnected"),
649 );
650
651 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
652 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
653 function* (input) {
654 const sessionId = AuthSessionId.make(
655 yield* crypto
656 .randomUUIDv4()
657 .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ cause }))),
658 );
659 const issuedAt = yield* DateTime.now;
660 const expiresAt = DateTime.add(issuedAt, {
661 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
662 });
663 const claims: SessionClaims = {
664 v: 1,
665 kind: "session",
666 sid: sessionId,
667 sub: input?.subject ?? "browser",
668 scopes: input?.scopes ?? AuthStandardClientScopes,
669 method: input?.method ?? "browser-session-cookie",
670 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
671 ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
672 iat: issuedAt.epochMilliseconds,
673 exp: expiresAt.epochMilliseconds,
674 };
675
676 const encodedPayload = yield* encodeClaims(claims).pipe(
677 Effect.map(base64UrlEncode),
678 Effect.mapError(
679 (cause) =>
680 new SessionCredentialIssueError({
681 sessionId,
682 cause: new SessionClaimsEncodingError({
683 sessionId,
684 operation: "encode_session_claims",
685 cause,
686 }),
687 }),
688 ),
689 );
690 const signature = signPayload(encodedPayload, signingSecret);
691 const client = input?.client ?? createDefaultClientMetadata();
692 const sessionRecord = {
693 sessionId,
694 subject: claims.sub,
695 scopes: claims.scopes,
696 method: claims.method,
697 client: {
698 label: client.label ?? null,
699 ipAddress: client.ipAddress ?? null,
700 userAgent: client.userAgent ?? null,
701 deviceType: client.deviceType,
702 os: client.os ?? null,
703 browser: client.browser ?? null,
704 },
705 issuedAt,
706 expiresAt,
707 } satisfies AuthSessions.CreateAuthSessionInput;
708 const replacedSessionIds = yield* (
709 input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod
710 ? authSessions.createReplacingActive({
711 session: sessionRecord,
712 revokedAt: issuedAt,
713 ...(input.replaceSessionId !== undefined
714 ? { replaceSessionId: input.replaceSessionId }
715 : {}),
716 })
717 : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>))
718 ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
719 if (replacedSessionIds.length > 0) {
720 yield* Ref.update(connectedSessionsRef, (current) => {
721 const next = new Map(current);
722 for (const replacedSessionId of replacedSessionIds) {
723 next.delete(replacedSessionId);
724 }
725 return next;
726 });
727 yield* Effect.forEach(replacedSessionIds, emitRemoved, {
728 concurrency: "unbounded",
729 discard: true,
730 });
731 }
732 yield* emitUpsert(
733 toAuthClientSession({
734 sessionId,
735 subject: claims.sub,
736 scopes: claims.scopes,
737 method: claims.method,
738 client,
739 issuedAt,
740 expiresAt,
741 lastConnectedAt: null,
742 connected: false,
743 }),
744 );
745
746 return {
747 sessionId,
748 token: `${encodedPayload}.${signature}`,
749 method: claims.method,
750 client,
751 expiresAt: expiresAt,
752 scopes: claims.scopes,
753 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
754 } satisfies IssuedSession;
755 },
756 );
757
758 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
759 function* (token) {
760 if (devAuth?.matches(token)) {
761 const row = yield* authSessions
762 .getById({ sessionId: devAuth.sessionId })
763 .pipe(
764 Effect.mapError(
765 (cause) =>
766 new SessionCredentialVerificationError({ sessionId: devAuth.sessionId, cause }),
767 ),
768 );
769 if (Option.isNone(row)) {
770 return yield* new UnknownSessionTokenError({ sessionId: devAuth.sessionId });
771 }
772 if (row.value.revokedAt !== null) {
773 return yield* new SessionTokenRevokedError({
774 sessionId: devAuth.sessionId,
775 revokedAt: row.value.revokedAt,
776 });
777 }
778 const observedAt = yield* DateTime.now;
779 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
780 return yield* new SessionTokenExpiredError({
781 sessionId: devAuth.sessionId,
782 expiresAt: row.value.expiresAt,
783 observedAt,
784 });
785 }
786 return {
787 sessionId: row.value.sessionId,
788 token,
789 method: row.value.method,
790 client: toClientMetadata(row.value.client),
791 expiresAt: row.value.expiresAt,
792 subject: row.value.subject,
793 scopes: row.value.scopes,
794 } satisfies VerifiedSession;
795 }
796 const [encodedPayload, signature] = token.split(".");
797 if (!encodedPayload || !signature) {
798 return yield* new MalformedSessionTokenError({});
799 }
800
801 const expectedSignature = signPayload(encodedPayload, signingSecret);
802 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
803 return yield* new InvalidSessionTokenSignatureError({});
804 }
805
806 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
807 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
808 );
809
810 const observedAt = yield* DateTime.now;
811 const expiresAt = DateTime.make(claims.exp);
812 if (Option.isNone(expiresAt)) {
813 return yield* new InvalidSessionExpirationClaimError({
814 sessionId: claims.sid,
815 expirationClaim: claims.exp,
816 });
817 }
818 if (claims.exp <= observedAt.epochMilliseconds) {
819 return yield* new SessionTokenExpiredError({
820 sessionId: claims.sid,
821 expiresAt: expiresAt.value,
822 observedAt,
823 });
824 }
825
826 const row = yield* authSessions
827 .getById({ sessionId: claims.sid })
828 .pipe(
829 Effect.mapError(
830 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
831 ),
832 );
833 if (Option.isNone(row)) {
834 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
835 }
836 if (row.value.revokedAt !== null) {
837 return yield* new SessionTokenRevokedError({
838 sessionId: claims.sid,
839 revokedAt: row.value.revokedAt,
840 });
841 }
842
843 return {
844 sessionId: claims.sid,
845 token,
846 method: claims.method,
847 client: toClientMetadata(row.value.client),
848 expiresAt: expiresAt.value,
849 subject: claims.sub,
850 scopes: claims.scopes,
851 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
852 ...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
853 } satisfies VerifiedSession;
854 },
855 );
856
857 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
858 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
859 "SessionStore.issueWebSocketToken",
860 )(function* (sessionId, input) {
861 const issuedAt = yield* DateTime.now;
862 const expiresAt = DateTime.add(issuedAt, {
863 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
864 });
865 const claims: WebSocketClaims = {
866 v: 1,
867 kind: "websocket",
868 sid: sessionId,
869 iat: issuedAt.epochMilliseconds,
870 exp: expiresAt.epochMilliseconds,
871 };
872 const encodedPayload = yield* encodeWsClaims(claims).pipe(
873 Effect.map(base64UrlEncode),
874 Effect.mapError(
875 (cause) =>
876 new WebSocketTokenIssueError({
877 sessionId,
878 cause: new SessionClaimsEncodingError({
879 sessionId,
880 operation: "encode_websocket_claims",
881 cause,
882 }),
883 }),
884 ),
885 );
886 const signature = signPayload(encodedPayload, signingSecret);
887 return {
888 token: `${encodedPayload}.${signature}`,
889 expiresAt,
890 };
891 });
892
893 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
894 "SessionStore.verifyWebSocketToken",
895 )(function* (token) {
896 const [encodedPayload, signature] = token.split(".");
897 if (!encodedPayload || !signature) {
898 return yield* new MalformedWebSocketTokenError({});
899 }
900
901 const expectedSignature = signPayload(encodedPayload, signingSecret);
902 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
903 return yield* new InvalidWebSocketTokenSignatureError({});
904 }
905
906 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
907 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
908 );
909 if (claims.sid.startsWith(REUSABLE_DEV_SESSION_PREFIX) && claims.sid !== devAuth?.sessionId) {
910 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
911 }
912
913 const observedAt = yield* DateTime.now;
914 const expiresAt = DateTime.make(claims.exp);
915 if (Option.isNone(expiresAt)) {
916 return yield* new InvalidSessionExpirationClaimError({
917 sessionId: claims.sid,
918 expirationClaim: claims.exp,
919 });
920 }
921 if (claims.exp <= observedAt.epochMilliseconds) {
922 return yield* new WebSocketTokenExpiredError({
923 sessionId: claims.sid,
924 expiresAt: expiresAt.value,
925 observedAt,
926 });
927 }
928
929 const row = yield* authSessions
930 .getById({ sessionId: claims.sid })
931 .pipe(
932 Effect.mapError(
933 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
934 ),
935 );
936 if (Option.isNone(row)) {
937 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
938 }
939 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
940 return yield* new WebSocketSessionExpiredError({
941 sessionId: claims.sid,
942 expiresAt: row.value.expiresAt,
943 observedAt,
944 });
945 }
946 if (row.value.revokedAt !== null) {
947 return yield* new WebSocketSessionRevokedError({
948 sessionId: claims.sid,
949 revokedAt: row.value.revokedAt,
950 });
951 }
952
953 return {
954 sessionId: row.value.sessionId,
955 token,
956 method: row.value.method,
957 client: toClientMetadata(row.value.client),
958 expiresAt: row.value.expiresAt,
959 subject: row.value.subject,
960 scopes: row.value.scopes,
961 } satisfies VerifiedSession;
962 });
963
964 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
965 function* () {
966 const now = yield* DateTime.now;
967 const connectedSessions = yield* Ref.get(connectedSessionsRef);
968 const rows = yield* authSessions.listActive({
969 now,
970 connectedSessionIds: Array.from(connectedSessions.keys()),
971 });
972
973 return rows.map((row) =>
974 toAuthClientSession({
975 sessionId: row.sessionId,
976 subject: row.subject,
977 scopes: row.scopes,
978 method: row.method,
979 client: toClientMetadata(row.client),
980 issuedAt: row.issuedAt,
981 expiresAt: row.expiresAt,
982 lastConnectedAt: row.lastConnectedAt,
983 connected: connectedSessions.has(row.sessionId),
984 }),
985 );
986 },
987 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
988 );
989
990 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
991 function* (sessionId) {
992 const revokedAt = yield* DateTime.now;
993 const revoked = yield* authSessions
994 .revoke({
995 sessionId,
996 revokedAt,
997 })
998 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
999 if (revoked) {
1000 yield* Ref.update(connectedSessionsRef, (current) => {
1001 const next = new Map(current);
1002 next.delete(sessionId);
1003 return next;
1004 });
1005 yield* emitRemoved(sessionId);
1006 }
1007 return revoked;
1008 },
1009 );
1010
1011 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
1012 "SessionStore.revokeAllExcept",
1013 )(function* (sessionId) {
1014 const revokedAt = yield* DateTime.now;
1015 const revokedSessionIds = yield* authSessions
1016 .revokeAllExcept({
1017 currentSessionId: sessionId,
1018 revokedAt,
1019 })
1020 .pipe(
1021 Effect.mapError(
1022 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
1023 ),
1024 );
1025 if (revokedSessionIds.length > 0) {
1026 yield* Ref.update(connectedSessionsRef, (current) => {
1027 const next = new Map(current);
1028 for (const revokedSessionId of revokedSessionIds) {
1029 next.delete(revokedSessionId);
1030 }
1031 return next;
1032 });
1033 yield* Effect.forEach(
1034 revokedSessionIds,
1035 (revokedSessionId) => emitRemoved(revokedSessionId),
1036 {
1037 concurrency: "unbounded",
1038 discard: true,
1039 },
1040 );
1041 }
1042 return revokedSessionIds.length;
1043 });
1044
1045 const awaitInvalidation = Effect.fn(function* (sessionId: AuthSessionId) {
1046 return yield* Effect.scoped(
1047 Effect.gen(function* () {
1048 // Subscribe before reading: revocation can race with the WebSocket upgrade.
1049 const subscription = yield* PubSub.subscribe(changesPubSub);
1050 const row = yield* authSessions
1051 .getById({ sessionId })
1052 .pipe(
1053 Effect.mapError(
1054 (cause) => new SessionCredentialVerificationError({ sessionId, cause }),
1055 ),
1056 );
1057 if (Option.isNone(row) || row.value.revokedAt !== null) return;
1058 const now = yield* DateTime.now;
1059 const remaining = row.value.expiresAt.epochMilliseconds - now.epochMilliseconds;
1060 if (remaining <= 0) return;
1061 yield* Effect.raceFirst(
1062 Stream.fromSubscription(subscription).pipe(
1063 Stream.filter(
1064 (change) => change.type === "clientRemoved" && change.sessionId === sessionId,
1065 ),
1066 Stream.runHead,
1067 ),
1068 Effect.sleep(Duration.millis(remaining)),
1069 );
1070 }),
1071 );
1072 });
1073
1074 return SessionStore.of({
1075 cookieName,
1076 legacyCookieName,
1077 issue,
1078 verify,
1079 issueWebSocketToken,
1080 verifyWebSocketToken,
1081 listActive,
1082 awaitInvalidation,
1083 get streamChanges() {
1084 return Stream.fromPubSub(changesPubSub);
1085 },
1086 revoke,
1087 revokeAllExcept,
1088 markConnected,
1089 markDisconnected,
1090 recordClientConnection,
1091 });
1092});
1093
1094export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));