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