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