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