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