Open History to see the last commit
1import {
2 AuthSessionId,
3 AuthStandardClientScopes,
4 AuthEnvironmentScopes,
5 type AuthClientMetadata,
6 type AuthClientSession,
7 type AuthEnvironmentScope,
8 AuthWebSocketTicketUse,
9 RuntimeMode,
10 type ServerAuthSessionMethod,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as SecureRandom from "effect/crypto/SecureRandom";
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 type {
28 ServerAuthInternalError,
29 ServerAuthInvalidCredentialError,
30} from "./EnvironmentAuth.ts";
31import * as PayloadSigner from "./PayloadSigner.ts";
32import * as ServerSecretStore from "./ServerSecretStore.ts";
33import {
34 REUSABLE_DEV_SESSION_EXPIRES_AT,
35 REUSABLE_DEV_SESSION_PREFIX,
36 resolveReusableDevAuth,
37} from "./ReusableDevAuth.ts";
38import {
39 base64UrlDecodeUtf8,
40 base64UrlEncode,
41 resolveLegacySessionCookieName,
42 resolveSessionCookieName,
43} from "./utils.ts";
44
45export interface IssuedSession {
46 readonly sessionId: AuthSessionId;
47 readonly token: string;
48 readonly method: ServerAuthSessionMethod;
49 readonly client: AuthClientMetadata;
50 readonly expiresAt: DateTime.DateTime;
51 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
52 readonly proofKeyThumbprint?: string;
53}
54
55export interface VerifiedSession {
56 readonly sessionId: AuthSessionId;
57 readonly token: string;
58 readonly method: ServerAuthSessionMethod;
59 readonly client: AuthClientMetadata;
60 readonly expiresAt?: DateTime.DateTime;
61 readonly subject: string;
62 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
63 readonly proofKeyThumbprint?: string;
64 readonly runtimeModeCeiling?: RuntimeMode;
65 /** An MCP client that is another T3 Code environment's peer link. */
66 readonly peerLink?: true;
67}
68
69export interface VerifiedWebSocketTicket extends VerifiedSession {
70 readonly audience?: AuthWebSocketTicketUse;
71}
72
73export type SessionCredentialChange =
74 | {
75 readonly type: "clientUpserted";
76 readonly clientSession: AuthClientSession;
77 }
78 | {
79 readonly type: "clientRemoved";
80 readonly sessionId: AuthSessionId;
81 };
82
83export class MalformedSessionTokenError extends Schema.TaggedError<MalformedSessionTokenError>()(
84 "MalformedSessionTokenError",
85 {},
86) {
87 override get message(): string {
88 return "Malformed session token.";
89 }
90}
91
92export class InvalidSessionTokenSignatureError extends Schema.TaggedError<InvalidSessionTokenSignatureError>()(
93 "InvalidSessionTokenSignatureError",
94 {},
95) {
96 override get message(): string {
97 return "Invalid session token signature.";
98 }
99}
100
101export class InvalidSessionTokenPayloadError extends Schema.TaggedError<InvalidSessionTokenPayloadError>()(
102 "InvalidSessionTokenPayloadError",
103 {
104 cause: Schema.Defect(),
105 },
106) {
107 override get message(): string {
108 return "Invalid session token payload.";
109 }
110}
111
112export class SessionTokenExpiredError extends Schema.TaggedError<SessionTokenExpiredError>()(
113 "SessionTokenExpiredError",
114 {
115 sessionId: AuthSessionId,
116 expiresAt: Schema.DateTimeUtc,
117 observedAt: Schema.DateTimeUtc,
118 },
119) {
120 override get message(): string {
121 return "Session token expired.";
122 }
123}
124
125export class UnknownSessionTokenError extends Schema.TaggedError<UnknownSessionTokenError>()(
126 "UnknownSessionTokenError",
127 {
128 sessionId: AuthSessionId,
129 },
130) {
131 override get message(): string {
132 return "Unknown session token.";
133 }
134}
135
136export class SessionTokenNotRenewableError extends Schema.TaggedError<SessionTokenNotRenewableError>()(
137 "SessionTokenNotRenewableError",
138 {
139 sessionId: AuthSessionId,
140 },
141) {
142 override get message(): string {
143 return "Session token cannot be renewed with this key.";
144 }
145}
146
147export class SessionTokenRevokedError extends Schema.TaggedError<SessionTokenRevokedError>()(
148 "SessionTokenRevokedError",
149 {
150 sessionId: AuthSessionId,
151 revokedAt: Schema.DateTimeUtc,
152 },
153) {
154 override get message(): string {
155 return "Session token revoked.";
156 }
157}
158
159export class InvalidSessionExpirationClaimError extends Schema.TaggedError<InvalidSessionExpirationClaimError>()(
160 "InvalidSessionExpirationClaimError",
161 {
162 sessionId: AuthSessionId,
163 expirationClaim: Schema.Number,
164 },
165) {
166 override get message(): string {
167 return "Invalid `exp` claim";
168 }
169}
170
171export class MalformedWebSocketTokenError extends Schema.TaggedError<MalformedWebSocketTokenError>()(
172 "MalformedWebSocketTokenError",
173 {},
174) {
175 override get message(): string {
176 return "Malformed websocket token.";
177 }
178}
179
180export class InvalidWebSocketTokenSignatureError extends Schema.TaggedError<InvalidWebSocketTokenSignatureError>()(
181 "InvalidWebSocketTokenSignatureError",
182 {},
183) {
184 override get message(): string {
185 return "Invalid websocket token signature.";
186 }
187}
188
189export class InvalidWebSocketTokenPayloadError extends Schema.TaggedError<InvalidWebSocketTokenPayloadError>()(
190 "InvalidWebSocketTokenPayloadError",
191 {
192 cause: Schema.Defect(),
193 },
194) {
195 override get message(): string {
196 return "Invalid websocket token payload.";
197 }
198}
199
200export class WebSocketTokenExpiredError extends Schema.TaggedError<WebSocketTokenExpiredError>()(
201 "WebSocketTokenExpiredError",
202 {
203 sessionId: AuthSessionId,
204 expiresAt: Schema.DateTimeUtc,
205 observedAt: Schema.DateTimeUtc,
206 },
207) {
208 override get message(): string {
209 return "Websocket token expired.";
210 }
211}
212
213export class UnknownWebSocketSessionError extends Schema.TaggedError<UnknownWebSocketSessionError>()(
214 "UnknownWebSocketSessionError",
215 {
216 sessionId: AuthSessionId,
217 },
218) {
219 override get message(): string {
220 return "Unknown websocket session.";
221 }
222}
223
224export class WebSocketSessionExpiredError extends Schema.TaggedError<WebSocketSessionExpiredError>()(
225 "WebSocketSessionExpiredError",
226 {
227 sessionId: AuthSessionId,
228 expiresAt: Schema.DateTimeUtc,
229 observedAt: Schema.DateTimeUtc,
230 },
231) {
232 override get message(): string {
233 return "Websocket session expired.";
234 }
235}
236
237export class WebSocketSessionRevokedError extends Schema.TaggedError<WebSocketSessionRevokedError>()(
238 "WebSocketSessionRevokedError",
239 {
240 sessionId: AuthSessionId,
241 revokedAt: Schema.DateTimeUtc,
242 },
243) {
244 override get message(): string {
245 return "Websocket session revoked.";
246 }
247}
248
249export const SessionCredentialInvalidError = Schema.Union([
250 MalformedSessionTokenError,
251 InvalidSessionTokenSignatureError,
252 InvalidSessionTokenPayloadError,
253 SessionTokenExpiredError,
254 UnknownSessionTokenError,
255 SessionTokenRevokedError,
256 SessionTokenNotRenewableError,
257 InvalidSessionExpirationClaimError,
258 MalformedWebSocketTokenError,
259 InvalidWebSocketTokenSignatureError,
260 InvalidWebSocketTokenPayloadError,
261 WebSocketTokenExpiredError,
262 UnknownWebSocketSessionError,
263 WebSocketSessionExpiredError,
264 WebSocketSessionRevokedError,
265]);
266export type SessionCredentialInvalidError = typeof SessionCredentialInvalidError.Type;
267export const isSessionCredentialInvalidError = Schema.is(SessionCredentialInvalidError);
268
269const sessionCredentialInternalErrorContext = {
270 cause: Schema.Defect(),
271};
272
273export class SessionClaimsEncodingError extends Schema.TaggedError<SessionClaimsEncodingError>()(
274 "SessionClaimsEncodingError",
275 {
276 sessionId: AuthSessionId,
277 operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
278 ...sessionCredentialInternalErrorContext,
279 },
280) {
281 override get message(): string {
282 return "Failed to encode claims";
283 }
284}
285
286export class SessionCredentialIssueError extends Schema.TaggedError<SessionCredentialIssueError>()(
287 "SessionCredentialIssueError",
288 {
289 sessionId: Schema.optional(AuthSessionId),
290 ...sessionCredentialInternalErrorContext,
291 },
292) {
293 override get message(): string {
294 return "Failed to issue session credential.";
295 }
296}
297
298export class SessionCredentialVerificationError extends Schema.TaggedError<SessionCredentialVerificationError>()(
299 "SessionCredentialVerificationError",
300 {
301 sessionId: AuthSessionId,
302 ...sessionCredentialInternalErrorContext,
303 },
304) {
305 override get message(): string {
306 return "Failed to verify session credential.";
307 }
308}
309
310export class WebSocketTokenIssueError extends Schema.TaggedError<WebSocketTokenIssueError>()(
311 "WebSocketTokenIssueError",
312 {
313 sessionId: AuthSessionId,
314 ...sessionCredentialInternalErrorContext,
315 },
316) {
317 override get message(): string {
318 return "Failed to issue websocket token.";
319 }
320}
321
322export class WebSocketTokenVerificationError extends Schema.TaggedError<WebSocketTokenVerificationError>()(
323 "WebSocketTokenVerificationError",
324 {
325 sessionId: AuthSessionId,
326 ...sessionCredentialInternalErrorContext,
327 },
328) {
329 override get message(): string {
330 return "Failed to verify websocket token.";
331 }
332}
333
334export class ActiveSessionsListError extends Schema.TaggedError<ActiveSessionsListError>()(
335 "ActiveSessionsListError",
336 {
337 ...sessionCredentialInternalErrorContext,
338 },
339) {
340 override get message(): string {
341 return "Failed to list active sessions.";
342 }
343}
344
345export class SessionRevocationError extends Schema.TaggedError<SessionRevocationError>()(
346 "SessionRevocationError",
347 {
348 sessionId: AuthSessionId,
349 ...sessionCredentialInternalErrorContext,
350 },
351) {
352 override get message(): string {
353 return "Failed to revoke session.";
354 }
355}
356
357export class OtherSessionsRevocationError extends Schema.TaggedError<OtherSessionsRevocationError>()(
358 "OtherSessionsRevocationError",
359 {
360 currentSessionId: AuthSessionId,
361 ...sessionCredentialInternalErrorContext,
362 },
363) {
364 override get message(): string {
365 return "Failed to revoke other sessions.";
366 }
367}
368
369export class ProofKeySessionsError extends Schema.TaggedError<ProofKeySessionsError>()(
370 "ProofKeySessionsError",
371 {
372 operation: Schema.Literals(["lookup", "revoke"]),
373 ...sessionCredentialInternalErrorContext,
374 },
375) {
376 override get message(): string {
377 return `Failed to ${this.operation} sessions by proof key.`;
378 }
379}
380
381export const SessionCredentialInternalError = Schema.Union([
382 SessionClaimsEncodingError,
383 SessionCredentialIssueError,
384 SessionCredentialVerificationError,
385 WebSocketTokenIssueError,
386 WebSocketTokenVerificationError,
387 ActiveSessionsListError,
388 SessionRevocationError,
389 OtherSessionsRevocationError,
390 ProofKeySessionsError,
391]);
392export type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type;
393
394export const SessionCredentialError = Schema.Union([
395 SessionCredentialInvalidError,
396 SessionCredentialInternalError,
397]);
398export type SessionCredentialError = typeof SessionCredentialError.Type;
399
400export class SessionStore extends Context.Service<
401 SessionStore,
402 {
403 readonly cookieName: string;
404 readonly legacyCookieName: string | undefined;
405 readonly issue: (input?: {
406 readonly ttl?: Duration.Duration;
407 readonly subject?: string;
408 readonly method?: ServerAuthSessionMethod;
409 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
410 readonly client?: AuthClientMetadata;
411 readonly proofKeyThumbprint?: string;
412 readonly runtimeModeCeiling?: RuntimeMode;
413 readonly peerLink?: boolean;
414 readonly replaceActiveForSubjectAndMethod?: boolean;
415 readonly replaceSessionId?: AuthSessionId;
416 /** Keeps the session alive this long past each renewal; `ttl` then bounds only the token. */
417 readonly renewalWindow?: Duration.Duration;
418 }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
419 /** Trades a renewable token, even an expired one, for a fresh token on the same session. */
420 readonly renew: (
421 token: string,
422 input: {
423 readonly proofKeyThumbprint: string;
424 readonly ttl: Duration.Duration;
425 readonly renewalWindow: Duration.Duration;
426 readonly consumeProof: Effect.Effect<
427 void,
428 ServerAuthInvalidCredentialError | ServerAuthInternalError
429 >;
430 },
431 ) => Effect.Effect<
432 IssuedSession,
433 SessionCredentialError | ServerAuthInvalidCredentialError | ServerAuthInternalError
434 >;
435 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
436 readonly issueWebSocketToken: (
437 sessionId: AuthSessionId,
438 input?: {
439 readonly ttl?: Duration.Duration;
440 readonly audience?: AuthWebSocketTicketUse;
441 readonly proofKeyThumbprint?: string;
442 },
443 ) => Effect.Effect<
444 {
445 readonly token: string;
446 readonly expiresAt: DateTime.DateTime;
447 },
448 SessionCredentialInternalError
449 >;
450 readonly verifyWebSocketToken: (
451 token: string,
452 ) => Effect.Effect<VerifiedWebSocketTicket, SessionCredentialError>;
453 readonly listActive: () => Effect.Effect<
454 ReadonlyArray<AuthClientSession>,
455 SessionCredentialInternalError
456 >;
457 readonly streamChanges: Stream.Stream<SessionCredentialChange>;
458 /** Completes when a live socket's session is revoked or expires without a renewal for its DPoP key. */
459 readonly awaitInvalidation: (
460 sessionId: AuthSessionId,
461 proofKeyThumbprint?: string,
462 ) => Effect.Effect<void, SessionCredentialVerificationError>;
463 readonly revoke: (
464 sessionId: AuthSessionId,
465 ) => Effect.Effect<boolean, SessionCredentialInternalError>;
466 readonly revokeAllExcept: (
467 sessionId: AuthSessionId,
468 ) => Effect.Effect<number, SessionCredentialInternalError>;
469 readonly proofKeyThumbprintOf: (
470 sessionId: AuthSessionId,
471 ) => Effect.Effect<Option.Option<string>, SessionCredentialInternalError>;
472 /** Revokes every session bound to this DPoP key, so a device it belongs to is cut off now. */
473 readonly revokeByProofKey: (
474 proofKeyThumbprint: string,
475 ) => Effect.Effect<number, SessionCredentialInternalError>;
476 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
477 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
478 }
479>()("t3/auth/SessionStore") {}
480
481const SIGNING_SECRET_NAME = "server-signing-key";
482const DEFAULT_SESSION_TTL = Duration.days(30);
483const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
484
485const SessionClaims = Schema.Struct({
486 v: Schema.Literals([1, 2]),
487 kind: Schema.Literal("session"),
488 sid: AuthSessionId,
489 sub: Schema.String,
490 scopes: AuthEnvironmentScopes,
491 method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
492 jkt: Schema.optionalKey(Schema.String),
493 rtc: Schema.optionalKey(RuntimeMode),
494 /** Signed, so a client cannot shed its peer link's limits. */
495 plk: Schema.optionalKey(Schema.Literal(1)),
496 /** Signed, so only sessions issued as renewable can renew. */
497 rnw: Schema.optionalKey(Schema.Literal(1)),
498 iat: Schema.Number,
499 exp: Schema.Number,
500});
501type SessionClaims = typeof SessionClaims.Type;
502
503const WebSocketClaims = Schema.Struct({
504 v: Schema.Literal(1),
505 kind: Schema.Literal("websocket"),
506 sid: AuthSessionId,
507 aud: Schema.optionalKey(AuthWebSocketTicketUse),
508 jkt: Schema.optionalKey(Schema.String),
509 iat: Schema.Number,
510 exp: Schema.Number,
511});
512type WebSocketClaims = typeof WebSocketClaims.Type;
513
514const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
515const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
516
517function createDefaultClientMetadata(): AuthClientMetadata {
518 return {
519 deviceType: "unknown",
520 };
521}
522
523function toClientMetadata(record: {
524 readonly label: string | null;
525 readonly ipAddress: string | null;
526 readonly userAgent: string | null;
527 readonly deviceType: AuthClientMetadata["deviceType"];
528 readonly os: string | null;
529 readonly browser: string | null;
530}): AuthClientMetadata {
531 return {
532 ...(record.label ? { label: record.label } : {}),
533 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
534 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
535 deviceType: record.deviceType,
536 ...(record.os ? { os: record.os } : {}),
537 ...(record.browser ? { browser: record.browser } : {}),
538 };
539}
540
541function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
542 return {
543 ...input,
544 current: false,
545 };
546}
547
548const make = Effect.gen(function* () {
549 const random = yield* SecureRandom.SecureRandom;
550 const serverConfig = yield* ServerConfig.ServerConfig;
551 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
552 const secretStore = yield* ServerSecretStore.ServerSecretStore;
553 const authSessions = yield* AuthSessions.AuthSessionRepository;
554 const signer = yield* PayloadSigner.fromSecret(
555 yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32),
556 );
557 const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
558 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
559 // Newest session per DPoP key. A live socket moves to it at expiry, so a
560 // client that renews its short-lived token keeps its socket.
561 const latestSessionByProofKey = new Map<string, AuthSessionId>();
562 const cookieInput = {
563 mode: serverConfig.mode,
564 port: serverConfig.port,
565 host: serverConfig.host,
566 instanceKey: serverConfig.stateDir,
567 environmentId: yield* serverEnvironment.getEnvironmentId,
568 development: serverConfig.devUrl !== undefined,
569 } as const;
570 const cookieName = resolveSessionCookieName(cookieInput);
571 const legacyCookieName = resolveLegacySessionCookieName(cookieInput);
572 const devAuth = resolveReusableDevAuth(serverConfig);
573 if (devAuth) {
574 yield* authSessions
575 .createIfAbsent({
576 sessionId: devAuth.sessionId,
577 subject: "reusable-dev-token",
578 scopes: AuthStandardClientScopes,
579 method: "browser-session-cookie",
580 client: {
581 label: "Reusable dev token",
582 ipAddress: null,
583 userAgent: null,
584 deviceType: "unknown",
585 os: null,
586 browser: null,
587 },
588 issuedAt: yield* DateTime.now,
589 expiresAt: REUSABLE_DEV_SESSION_EXPIRES_AT,
590 })
591 .pipe(
592 Effect.mapError(
593 (cause) => new SessionCredentialIssueError({ sessionId: devAuth.sessionId, cause }),
594 ),
595 );
596 }
597
598 const emitUpsert = (clientSession: AuthClientSession) =>
599 PubSub.publish(changesPubSub, {
600 type: "clientUpserted",
601 clientSession,
602 }).pipe(Effect.asVoid);
603
604 const emitRemoved = (sessionId: AuthSessionId) =>
605 PubSub.publish(changesPubSub, {
606 type: "clientRemoved",
607 sessionId,
608 }).pipe(Effect.asVoid);
609
610 const loadActiveSession = Effect.fn("SessionStore.loadActiveSession")(function* (
611 sessionId: AuthSessionId,
612 ) {
613 const row = yield* authSessions.getById({ sessionId });
614 if (Option.isNone(row) || row.value.revokedAt !== null) {
615 return Option.none<AuthClientSession>();
616 }
617
618 const connectedSessions = yield* Ref.get(connectedSessionsRef);
619 const connected = connectedSessions.has(row.value.sessionId);
620 const now = yield* DateTime.now;
621 if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
622 return Option.none<AuthClientSession>();
623 }
624 return Option.some(
625 toAuthClientSession({
626 sessionId: row.value.sessionId,
627 subject: row.value.subject,
628 scopes: row.value.scopes,
629 method: row.value.method,
630 client: toClientMetadata(row.value.client),
631 issuedAt: row.value.issuedAt,
632 expiresAt: row.value.expiresAt,
633 lastConnectedAt: row.value.lastConnectedAt,
634 connected,
635 }),
636 );
637 });
638
639 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
640 Ref.modify(connectedSessionsRef, (current) => {
641 const next = new Map(current);
642 const wasDisconnected = !next.has(sessionId);
643 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
644 return [wasDisconnected, next] as const;
645 }).pipe(
646 Effect.flatMap((wasDisconnected) =>
647 wasDisconnected
648 ? DateTime.now.pipe(
649 Effect.flatMap((lastConnectedAt) =>
650 authSessions.setLastConnectedAt({
651 sessionId,
652 lastConnectedAt,
653 }),
654 ),
655 )
656 : Effect.void,
657 ),
658 Effect.flatMap(() => loadActiveSession(sessionId)),
659 Effect.flatMap((session) =>
660 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
661 ),
662 Effect.catchCause((cause) =>
663 Effect.logError("Failed to publish connected-session auth update.").pipe(
664 Effect.annotateLogs({
665 sessionId,
666 cause,
667 }),
668 ),
669 ),
670 Effect.withSpan("SessionStore.markConnected"),
671 );
672
673 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
674 Ref.update(connectedSessionsRef, (current) => {
675 const next = new Map(current);
676 const remaining = (next.get(sessionId) ?? 0) - 1;
677 if (remaining > 0) {
678 next.set(sessionId, remaining);
679 } else {
680 next.delete(sessionId);
681 }
682 return next;
683 }).pipe(
684 Effect.flatMap(() => loadActiveSession(sessionId)),
685 Effect.flatMap((session) =>
686 Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
687 ),
688 Effect.catchCause((cause) =>
689 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
690 Effect.annotateLogs({
691 sessionId,
692 cause,
693 }),
694 ),
695 ),
696 Effect.withSpan("SessionStore.markDisconnected"),
697 );
698
699 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
700 const signClaims = Effect.fnUntraced(function* (claims: SessionClaims) {
701 const encodedPayload = yield* encodeClaims(claims).pipe(
702 Effect.map(base64UrlEncode),
703 Effect.mapError(
704 (cause) =>
705 new SessionCredentialIssueError({
706 sessionId: claims.sid,
707 cause: new SessionClaimsEncodingError({
708 sessionId: claims.sid,
709 operation: "encode_session_claims",
710 cause,
711 }),
712 }),
713 ),
714 );
715 return `${encodedPayload}.${yield* signer.sign(encodedPayload)}`;
716 });
717 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
718 function* (input) {
719 const sessionId = AuthSessionId.make(
720 yield* random
721 .uuidV4()
722 .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ cause }))),
723 );
724 const issuedAt = yield* DateTime.now;
725 const expiresAt = DateTime.add(issuedAt, {
726 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
727 });
728 const sessionExpiresAt = input?.renewalWindow
729 ? DateTime.add(issuedAt, { milliseconds: Duration.toMillis(input.renewalWindow) })
730 : expiresAt;
731 const claims: SessionClaims = {
732 v: 1,
733 kind: "session",
734 sid: sessionId,
735 sub: input?.subject ?? "browser",
736 scopes: input?.scopes ?? AuthStandardClientScopes,
737 method: input?.method ?? "browser-session-cookie",
738 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
739 ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
740 ...(input?.peerLink === true ? { plk: 1 as const } : {}),
741 ...(input?.renewalWindow ? { rnw: 1 as const } : {}),
742 iat: issuedAt.epochMilliseconds,
743 exp: expiresAt.epochMilliseconds,
744 };
745
746 const token = yield* signClaims(claims);
747 const client = input?.client ?? createDefaultClientMetadata();
748 const sessionRecord = {
749 sessionId,
750 subject: claims.sub,
751 scopes: claims.scopes,
752 method: claims.method,
753 client: {
754 label: client.label ?? null,
755 ipAddress: client.ipAddress ?? null,
756 userAgent: client.userAgent ?? null,
757 deviceType: client.deviceType,
758 os: client.os ?? null,
759 browser: client.browser ?? null,
760 },
761 issuedAt,
762 expiresAt: sessionExpiresAt,
763 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
764 } satisfies AuthSessions.CreateAuthSessionInput;
765 const replacedSessionIds = yield* (
766 input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod
767 ? authSessions.createReplacingActive({
768 session: sessionRecord,
769 revokedAt: issuedAt,
770 ...(input.replaceSessionId !== undefined
771 ? { replaceSessionId: input.replaceSessionId }
772 : {}),
773 })
774 : authSessions.create(sessionRecord).pipe(Effect.as([] as ReadonlyArray<AuthSessionId>))
775 ).pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
776 if (claims.jkt) latestSessionByProofKey.set(claims.jkt, sessionId);
777 if (replacedSessionIds.length > 0) {
778 yield* Ref.update(connectedSessionsRef, (current) => {
779 const next = new Map(current);
780 for (const replacedSessionId of replacedSessionIds) {
781 next.delete(replacedSessionId);
782 }
783 return next;
784 });
785 yield* Effect.forEach(replacedSessionIds, emitRemoved, {
786 concurrency: "unbounded",
787 discard: true,
788 });
789 }
790 yield* emitUpsert(
791 toAuthClientSession({
792 sessionId,
793 subject: claims.sub,
794 scopes: claims.scopes,
795 method: claims.method,
796 client,
797 issuedAt,
798 expiresAt: sessionExpiresAt,
799 lastConnectedAt: null,
800 connected: false,
801 }),
802 );
803
804 return {
805 sessionId,
806 token,
807 method: claims.method,
808 client,
809 expiresAt: expiresAt,
810 scopes: claims.scopes,
811 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
812 } satisfies IssuedSession;
813 },
814 );
815
816 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
817 function* (token) {
818 if (devAuth?.matches(token)) {
819 const row = yield* authSessions
820 .getById({ sessionId: devAuth.sessionId })
821 .pipe(
822 Effect.mapError(
823 (cause) =>
824 new SessionCredentialVerificationError({ sessionId: devAuth.sessionId, cause }),
825 ),
826 );
827 if (Option.isNone(row)) {
828 return yield* new UnknownSessionTokenError({ sessionId: devAuth.sessionId });
829 }
830 if (row.value.revokedAt !== null) {
831 return yield* new SessionTokenRevokedError({
832 sessionId: devAuth.sessionId,
833 revokedAt: row.value.revokedAt,
834 });
835 }
836 const observedAt = yield* DateTime.now;
837 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
838 return yield* new SessionTokenExpiredError({
839 sessionId: devAuth.sessionId,
840 expiresAt: row.value.expiresAt,
841 observedAt,
842 });
843 }
844 return {
845 sessionId: row.value.sessionId,
846 token,
847 method: row.value.method,
848 client: toClientMetadata(row.value.client),
849 expiresAt: row.value.expiresAt,
850 subject: row.value.subject,
851 scopes: row.value.scopes,
852 } satisfies VerifiedSession;
853 }
854 const [encodedPayload, signature] = token.split(".");
855 if (!encodedPayload || !signature) {
856 return yield* new MalformedSessionTokenError({});
857 }
858
859 if (!(yield* signer.verify(encodedPayload, signature))) {
860 return yield* new InvalidSessionTokenSignatureError({});
861 }
862
863 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
864 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
865 );
866
867 const observedAt = yield* DateTime.now;
868 const expiresAt = DateTime.make(claims.exp);
869 if (Option.isNone(expiresAt)) {
870 return yield* new InvalidSessionExpirationClaimError({
871 sessionId: claims.sid,
872 expirationClaim: claims.exp,
873 });
874 }
875 if (claims.exp <= observedAt.epochMilliseconds) {
876 return yield* new SessionTokenExpiredError({
877 sessionId: claims.sid,
878 expiresAt: expiresAt.value,
879 observedAt,
880 });
881 }
882
883 const row = yield* authSessions
884 .getById({ sessionId: claims.sid })
885 .pipe(
886 Effect.mapError(
887 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
888 ),
889 );
890 if (Option.isNone(row)) {
891 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
892 }
893 if (row.value.revokedAt !== null) {
894 return yield* new SessionTokenRevokedError({
895 sessionId: claims.sid,
896 revokedAt: row.value.revokedAt,
897 });
898 }
899
900 return {
901 sessionId: claims.sid,
902 token,
903 method: claims.method,
904 client: toClientMetadata(row.value.client),
905 expiresAt: expiresAt.value,
906 subject: claims.sub,
907 scopes: row.value.scopes,
908 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
909 ...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
910 ...(claims.plk === 1 ? { peerLink: true as const } : {}),
911 } satisfies VerifiedSession;
912 },
913 );
914
915 const renew: SessionStore["Service"]["renew"] = Effect.fn("SessionStore.renew")(
916 function* (token, input) {
917 const [encodedPayload, signature] = token.split(".");
918 if (!encodedPayload || !signature) {
919 return yield* new MalformedSessionTokenError({});
920 }
921 if (!(yield* signer.verify(encodedPayload, signature))) {
922 return yield* new InvalidSessionTokenSignatureError({});
923 }
924 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
925 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
926 );
927 // The token's own expiry is ignored here: the session row's expiry is the renewal window.
928 if (claims.rnw !== 1 || claims.jkt !== input.proofKeyThumbprint) {
929 return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid });
930 }
931 const row = yield* authSessions
932 .getById({ sessionId: claims.sid })
933 .pipe(
934 Effect.mapError(
935 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
936 ),
937 );
938 if (Option.isNone(row)) {
939 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
940 }
941 if (row.value.revokedAt !== null) {
942 return yield* new SessionTokenRevokedError({
943 sessionId: claims.sid,
944 revokedAt: row.value.revokedAt,
945 });
946 }
947 const now = yield* DateTime.now;
948 if (row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
949 return yield* new SessionTokenExpiredError({
950 sessionId: claims.sid,
951 expiresAt: row.value.expiresAt,
952 observedAt: now,
953 });
954 }
955 yield* input.consumeProof;
956 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(input.ttl) });
957 const extended = yield* authSessions
958 .extend({
959 sessionId: claims.sid,
960 expiresAt: DateTime.add(now, { milliseconds: Duration.toMillis(input.renewalWindow) }),
961 now,
962 })
963 .pipe(
964 Effect.mapError(
965 (cause) => new SessionCredentialIssueError({ sessionId: claims.sid, cause }),
966 ),
967 );
968 // A revoke can land between the read above and the update.
969 if (!extended) {
970 return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid });
971 }
972 const renewedToken = yield* signClaims({
973 ...claims,
974 iat: now.epochMilliseconds,
975 exp: expiresAt.epochMilliseconds,
976 });
977 const session = yield* loadActiveSession(claims.sid).pipe(
978 Effect.mapError(
979 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
980 ),
981 );
982 if (Option.isSome(session)) yield* emitUpsert(session.value);
983 return {
984 sessionId: claims.sid,
985 token: renewedToken,
986 method: claims.method,
987 client: toClientMetadata(row.value.client),
988 expiresAt,
989 scopes: row.value.scopes,
990 proofKeyThumbprint: input.proofKeyThumbprint,
991 } satisfies IssuedSession;
992 },
993 );
994
995 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
996 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
997 "SessionStore.issueWebSocketToken",
998 )(function* (sessionId, input) {
999 const issuedAt = yield* DateTime.now;
1000 const expiresAt = DateTime.add(issuedAt, {
1001 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
1002 });
1003 const claims: WebSocketClaims = {
1004 v: 1,
1005 kind: "websocket",
1006 sid: sessionId,
1007 ...(input?.audience ? { aud: input.audience } : {}),
1008 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
1009 iat: issuedAt.epochMilliseconds,
1010 exp: expiresAt.epochMilliseconds,
1011 };
1012 const encodedPayload = yield* encodeWsClaims(claims).pipe(
1013 Effect.map(base64UrlEncode),
1014 Effect.mapError(
1015 (cause) =>
1016 new WebSocketTokenIssueError({
1017 sessionId,
1018 cause: new SessionClaimsEncodingError({
1019 sessionId,
1020 operation: "encode_websocket_claims",
1021 cause,
1022 }),
1023 }),
1024 ),
1025 );
1026 const signature = yield* signer.sign(encodedPayload);
1027 return {
1028 token: `${encodedPayload}.${signature}`,
1029 expiresAt,
1030 };
1031 });
1032
1033 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
1034 "SessionStore.verifyWebSocketToken",
1035 )(function* (token) {
1036 const [encodedPayload, signature] = token.split(".");
1037 if (!encodedPayload || !signature) {
1038 return yield* new MalformedWebSocketTokenError({});
1039 }
1040
1041 if (!(yield* signer.verify(encodedPayload, signature))) {
1042 return yield* new InvalidWebSocketTokenSignatureError({});
1043 }
1044
1045 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
1046 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
1047 );
1048 if (claims.sid.startsWith(REUSABLE_DEV_SESSION_PREFIX) && claims.sid !== devAuth?.sessionId) {
1049 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
1050 }
1051
1052 const observedAt = yield* DateTime.now;
1053 const expiresAt = DateTime.make(claims.exp);
1054 if (Option.isNone(expiresAt)) {
1055 return yield* new InvalidSessionExpirationClaimError({
1056 sessionId: claims.sid,
1057 expirationClaim: claims.exp,
1058 });
1059 }
1060 if (claims.exp <= observedAt.epochMilliseconds) {
1061 return yield* new WebSocketTokenExpiredError({
1062 sessionId: claims.sid,
1063 expiresAt: expiresAt.value,
1064 observedAt,
1065 });
1066 }
1067
1068 const row = yield* authSessions
1069 .getById({ sessionId: claims.sid })
1070 .pipe(
1071 Effect.mapError(
1072 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
1073 ),
1074 );
1075 if (Option.isNone(row)) {
1076 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
1077 }
1078 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
1079 return yield* new WebSocketSessionExpiredError({
1080 sessionId: claims.sid,
1081 expiresAt: row.value.expiresAt,
1082 observedAt,
1083 });
1084 }
1085 if (row.value.revokedAt !== null) {
1086 return yield* new WebSocketSessionRevokedError({
1087 sessionId: claims.sid,
1088 revokedAt: row.value.revokedAt,
1089 });
1090 }
1091
1092 return {
1093 sessionId: row.value.sessionId,
1094 token,
1095 method: row.value.method,
1096 client: toClientMetadata(row.value.client),
1097 expiresAt: row.value.expiresAt,
1098 subject: row.value.subject,
1099 scopes: row.value.scopes,
1100 ...(claims.aud ? { audience: claims.aud } : {}),
1101 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
1102 } satisfies VerifiedWebSocketTicket;
1103 });
1104
1105 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
1106 function* () {
1107 const now = yield* DateTime.now;
1108 const connectedSessions = yield* Ref.get(connectedSessionsRef);
1109 const rows = yield* authSessions.listActive({
1110 now,
1111 connectedSessionIds: Array.from(connectedSessions.keys()),
1112 });
1113
1114 return rows.map((row) =>
1115 toAuthClientSession({
1116 sessionId: row.sessionId,
1117 subject: row.subject,
1118 scopes: row.scopes,
1119 method: row.method,
1120 client: toClientMetadata(row.client),
1121 issuedAt: row.issuedAt,
1122 expiresAt: row.expiresAt,
1123 lastConnectedAt: row.lastConnectedAt,
1124 connected: connectedSessions.has(row.sessionId),
1125 }),
1126 );
1127 },
1128 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
1129 );
1130
1131 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
1132 function* (sessionId) {
1133 const revokedAt = yield* DateTime.now;
1134 const revoked = yield* authSessions
1135 .revoke({
1136 sessionId,
1137 revokedAt,
1138 })
1139 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
1140 if (revoked) {
1141 yield* Ref.update(connectedSessionsRef, (current) => {
1142 const next = new Map(current);
1143 next.delete(sessionId);
1144 return next;
1145 });
1146 yield* emitRemoved(sessionId);
1147 }
1148 return revoked;
1149 },
1150 );
1151
1152 const proofKeyThumbprintOf: SessionStore["Service"]["proofKeyThumbprintOf"] = (sessionId) =>
1153 authSessions
1154 .getProofKeyThumbprint({ sessionId })
1155 .pipe(Effect.mapError((cause) => new ProofKeySessionsError({ operation: "lookup", cause })));
1156
1157 const revokeByProofKey: SessionStore["Service"]["revokeByProofKey"] = Effect.fn(
1158 "SessionStore.revokeByProofKey",
1159 )(function* (proofKeyThumbprint) {
1160 const revokedAt = yield* DateTime.now;
1161 const revokedSessionIds = yield* authSessions
1162 .revokeByProofKey({ proofKeyThumbprint, revokedAt })
1163 .pipe(Effect.mapError((cause) => new ProofKeySessionsError({ operation: "revoke", cause })));
1164 yield* Ref.update(connectedSessionsRef, (current) => {
1165 const next = new Map(current);
1166 for (const revokedSessionId of revokedSessionIds) next.delete(revokedSessionId);
1167 return next;
1168 });
1169 yield* Effect.forEach(revokedSessionIds, emitRemoved, { discard: true });
1170 return revokedSessionIds.length;
1171 });
1172
1173 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
1174 "SessionStore.revokeAllExcept",
1175 )(function* (sessionId) {
1176 const revokedAt = yield* DateTime.now;
1177 const revokedSessionIds = yield* authSessions
1178 .revokeAllExcept({
1179 currentSessionId: sessionId,
1180 revokedAt,
1181 })
1182 .pipe(
1183 Effect.mapError(
1184 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
1185 ),
1186 );
1187 if (revokedSessionIds.length > 0) {
1188 yield* Ref.update(connectedSessionsRef, (current) => {
1189 const next = new Map(current);
1190 for (const revokedSessionId of revokedSessionIds) {
1191 next.delete(revokedSessionId);
1192 }
1193 return next;
1194 });
1195 yield* Effect.forEach(
1196 revokedSessionIds,
1197 (revokedSessionId) => emitRemoved(revokedSessionId),
1198 {
1199 concurrency: "unbounded",
1200 discard: true,
1201 },
1202 );
1203 }
1204 return revokedSessionIds.length;
1205 });
1206
1207 const awaitInvalidation = Effect.fn(function* (
1208 sessionId: AuthSessionId,
1209 proofKeyThumbprint?: string,
1210 ) {
1211 return yield* Effect.scoped(
1212 Effect.gen(function* () {
1213 // Subscribe before reading: revocation can race with the WebSocket upgrade.
1214 const subscription = yield* PubSub.subscribe(changesPubSub);
1215 const readRow = (id: AuthSessionId) =>
1216 authSessions
1217 .getById({ sessionId: id })
1218 .pipe(
1219 Effect.mapError(
1220 (cause) => new SessionCredentialVerificationError({ sessionId: id, cause }),
1221 ),
1222 );
1223 const original = yield* readRow(sessionId);
1224 if (Option.isNone(original)) return;
1225 // Revoking any session the socket has used closes it. Events only wake this loop
1226 // and the rows decide: revocations are written before they are published, and
1227 // clientRemoved also reports an expired session losing its last socket.
1228 const chain = [sessionId];
1229 const nextRemoval = Effect.gen(function* () {
1230 while (true) {
1231 const change = yield* PubSub.take(subscription);
1232 if (change.type === "clientRemoved" && chain.includes(change.sessionId)) return;
1233 }
1234 });
1235 let current = original.value;
1236 while (true) {
1237 const rows = yield* Effect.forEach(chain, readRow);
1238 if (rows.some((row) => Option.isNone(row) || row.value.revokedAt !== null)) return;
1239 // Renewal moves a session's expiry in place, so the snapshot can be stale.
1240 const currentRow = rows.at(-1);
1241 if (currentRow !== undefined && Option.isSome(currentRow)) current = currentRow.value;
1242 const now = yield* DateTime.now;
1243 const remaining = current.expiresAt.epochMilliseconds - now.epochMilliseconds;
1244 if (remaining > 0) {
1245 yield* Effect.raceFirst(nextRemoval, Effect.sleep(Duration.millis(remaining)));
1246 continue;
1247 }
1248 // A renewal can land between the read above and the clock sample.
1249 const latest = yield* readRow(current.sessionId);
1250 if (
1251 Option.isSome(latest) &&
1252 latest.value.expiresAt.epochMilliseconds > current.expiresAt.epochMilliseconds
1253 ) {
1254 current = latest.value;
1255 continue;
1256 }
1257 const successorId =
1258 proofKeyThumbprint === undefined
1259 ? undefined
1260 : latestSessionByProofKey.get(proofKeyThumbprint);
1261 if (successorId === undefined || successorId === current.sessionId) return;
1262 const successor = yield* readRow(successorId);
1263 // The socket keeps its original scopes, so the renewal must still grant all of them.
1264 if (
1265 Option.isNone(successor) ||
1266 successor.value.subject !== original.value.subject ||
1267 !original.value.scopes.every((scope) => successor.value.scopes.includes(scope))
1268 ) {
1269 return;
1270 }
1271 chain.push(successorId);
1272 current = successor.value;
1273 }
1274 }),
1275 );
1276 });
1277
1278 return SessionStore.of({
1279 cookieName,
1280 legacyCookieName,
1281 issue,
1282 renew,
1283 verify,
1284 issueWebSocketToken,
1285 verifyWebSocketToken,
1286 listActive,
1287 awaitInvalidation,
1288 get streamChanges() {
1289 return Stream.fromPubSub(changesPubSub);
1290 },
1291 revoke,
1292 revokeAllExcept,
1293 proofKeyThumbprintOf,
1294 revokeByProofKey,
1295 markConnected,
1296 markDisconnected,
1297 });
1298});
1299
1300export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));