Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SessionStore.ts

1,102 lines34.7 KB

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