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