Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SessionStore.ts

1,085 lines34.2 KB

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