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