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 });
474
475 const emitUpsert = (clientSession: AuthClientSession) =>
476 PubSub.publish(changesPubSub, {
477 type: "clientUpserted",
478 clientSession,
479 }).pipe(Effect.asVoid);
480
481 const emitRemoved = (sessionId: AuthSessionId) =>
482 PubSub.publish(changesPubSub, {
483 type: "clientRemoved",
484 sessionId,
485 }).pipe(Effect.asVoid);
486
487 const loadActiveSession = (sessionId: AuthSessionId) =>
488 Effect.gen(function* () {
489 const row = yield* authSessions.getById({ sessionId });
490 if (Option.isNone(row) || row.value.revokedAt !== null) {
491 return Option.none<AuthClientSession>();
492 }
493
494 const connectedSessions = yield* Ref.get(connectedSessionsRef);
495 return Option.some(
496 toAuthClientSession({
497 sessionId: row.value.sessionId,
498 subject: row.value.subject,
499 scopes: row.value.scopes,
500 method: row.value.method,
501 client: toClientMetadata(row.value.client),
502 issuedAt: row.value.issuedAt,
503 expiresAt: row.value.expiresAt,
504 lastConnectedAt: row.value.lastConnectedAt,
505 connected: connectedSessions.has(row.value.sessionId),
506 }),
507 );
508 });
509
510 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
511 Ref.modify(connectedSessionsRef, (current) => {
512 const next = new Map(current);
513 const wasDisconnected = !next.has(sessionId);
514 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
515 return [wasDisconnected, next] as const;
516 }).pipe(
517 Effect.flatMap((wasDisconnected) =>
518 wasDisconnected
519 ? DateTime.now.pipe(
520 Effect.flatMap((lastConnectedAt) =>
521 authSessions.setLastConnectedAt({
522 sessionId,
523 lastConnectedAt,
524 }),
525 ),
526 )
527 : Effect.void,
528 ),
529 Effect.flatMap(() => loadActiveSession(sessionId)),
530 Effect.flatMap((session) =>
531 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
532 ),
533 Effect.catchCause((cause) =>
534 Effect.logError("Failed to publish connected-session auth update.").pipe(
535 Effect.annotateLogs({
536 sessionId,
537 cause,
538 }),
539 ),
540 ),
541 Effect.withSpan("SessionStore.markConnected"),
542 );
543
544 const markDisconnected: SessionStore["Service"]["markDisconnected"] = (sessionId) =>
545 Ref.update(connectedSessionsRef, (current) => {
546 const next = new Map(current);
547 const remaining = (next.get(sessionId) ?? 0) - 1;
548 if (remaining > 0) {
549 next.set(sessionId, remaining);
550 } else {
551 next.delete(sessionId);
552 }
553 return next;
554 }).pipe(
555 Effect.flatMap(() => loadActiveSession(sessionId)),
556 Effect.flatMap((session) =>
557 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
558 ),
559 Effect.catchCause((cause) =>
560 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
561 Effect.annotateLogs({
562 sessionId,
563 cause,
564 }),
565 ),
566 ),
567 Effect.withSpan("SessionStore.markDisconnected"),
568 );
569
570 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
571 const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
572 function* (input) {
573 const sessionId = AuthSessionId.make(
574 yield* crypto.randomUUIDv4.pipe(
575 Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
576 ),
577 );
578 const issuedAt = yield* DateTime.now;
579 const expiresAt = DateTime.add(issuedAt, {
580 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
581 });
582 const claims: SessionClaims = {
583 v: 1,
584 kind: "session",
585 sid: sessionId,
586 sub: input?.subject ?? "browser",
587 scopes: input?.scopes ?? AuthStandardClientScopes,
588 method: input?.method ?? "browser-session-cookie",
589 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
590 iat: issuedAt.epochMilliseconds,
591 exp: expiresAt.epochMilliseconds,
592 };
593
594 const encodedPayload = yield* encodeClaims(claims).pipe(
595 Effect.map(base64UrlEncode),
596 Effect.mapError(
597 (cause) =>
598 new SessionCredentialIssueError({
599 sessionId,
600 cause: new SessionClaimsEncodingError({
601 sessionId,
602 operation: "encode_session_claims",
603 cause,
604 }),
605 }),
606 ),
607 );
608 const signature = signPayload(encodedPayload, signingSecret);
609 const client = input?.client ?? createDefaultClientMetadata();
610 yield* authSessions
611 .create({
612 sessionId,
613 subject: claims.sub,
614 scopes: claims.scopes,
615 method: claims.method,
616 client: {
617 label: client.label ?? null,
618 ipAddress: client.ipAddress ?? null,
619 userAgent: client.userAgent ?? null,
620 deviceType: client.deviceType,
621 os: client.os ?? null,
622 browser: client.browser ?? null,
623 },
624 issuedAt,
625 expiresAt,
626 })
627 .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
628 yield* emitUpsert(
629 toAuthClientSession({
630 sessionId,
631 subject: claims.sub,
632 scopes: claims.scopes,
633 method: claims.method,
634 client,
635 issuedAt,
636 expiresAt,
637 lastConnectedAt: null,
638 connected: false,
639 }),
640 );
641
642 return {
643 sessionId,
644 token: `${encodedPayload}.${signature}`,
645 method: claims.method,
646 client,
647 expiresAt: expiresAt,
648 scopes: claims.scopes,
649 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
650 } satisfies IssuedSession;
651 },
652 );
653
654 const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
655 function* (token) {
656 const [encodedPayload, signature] = token.split(".");
657 if (!encodedPayload || !signature) {
658 return yield* new MalformedSessionTokenError({});
659 }
660
661 const expectedSignature = signPayload(encodedPayload, signingSecret);
662 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
663 return yield* new InvalidSessionTokenSignatureError({});
664 }
665
666 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
667 Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
668 );
669
670 const observedAt = yield* DateTime.now;
671 const expiresAt = DateTime.make(claims.exp);
672 if (Option.isNone(expiresAt)) {
673 return yield* new InvalidSessionExpirationClaimError({
674 sessionId: claims.sid,
675 expirationClaim: claims.exp,
676 });
677 }
678 if (claims.exp <= observedAt.epochMilliseconds) {
679 return yield* new SessionTokenExpiredError({
680 sessionId: claims.sid,
681 expiresAt: expiresAt.value,
682 observedAt,
683 });
684 }
685
686 const row = yield* authSessions
687 .getById({ sessionId: claims.sid })
688 .pipe(
689 Effect.mapError(
690 (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
691 ),
692 );
693 if (Option.isNone(row)) {
694 return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
695 }
696 if (row.value.revokedAt !== null) {
697 return yield* new SessionTokenRevokedError({
698 sessionId: claims.sid,
699 revokedAt: row.value.revokedAt,
700 });
701 }
702
703 return {
704 sessionId: claims.sid,
705 token,
706 method: claims.method,
707 client: toClientMetadata(row.value.client),
708 expiresAt: expiresAt.value,
709 subject: claims.sub,
710 scopes: claims.scopes,
711 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
712 } satisfies VerifiedSession;
713 },
714 );
715
716 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
717 const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
718 "SessionStore.issueWebSocketToken",
719 )(function* (sessionId, input) {
720 const issuedAt = yield* DateTime.now;
721 const expiresAt = DateTime.add(issuedAt, {
722 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
723 });
724 const claims: WebSocketClaims = {
725 v: 1,
726 kind: "websocket",
727 sid: sessionId,
728 iat: issuedAt.epochMilliseconds,
729 exp: expiresAt.epochMilliseconds,
730 };
731 const encodedPayload = yield* encodeWsClaims(claims).pipe(
732 Effect.map(base64UrlEncode),
733 Effect.mapError(
734 (cause) =>
735 new WebSocketTokenIssueError({
736 sessionId,
737 cause: new SessionClaimsEncodingError({
738 sessionId,
739 operation: "encode_websocket_claims",
740 cause,
741 }),
742 }),
743 ),
744 );
745 const signature = signPayload(encodedPayload, signingSecret);
746 return {
747 token: `${encodedPayload}.${signature}`,
748 expiresAt,
749 };
750 });
751
752 const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
753 "SessionStore.verifyWebSocketToken",
754 )(function* (token) {
755 const [encodedPayload, signature] = token.split(".");
756 if (!encodedPayload || !signature) {
757 return yield* new MalformedWebSocketTokenError({});
758 }
759
760 const expectedSignature = signPayload(encodedPayload, signingSecret);
761 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
762 return yield* new InvalidWebSocketTokenSignatureError({});
763 }
764
765 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
766 Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
767 );
768
769 const observedAt = yield* DateTime.now;
770 const expiresAt = DateTime.make(claims.exp);
771 if (Option.isNone(expiresAt)) {
772 return yield* new InvalidSessionExpirationClaimError({
773 sessionId: claims.sid,
774 expirationClaim: claims.exp,
775 });
776 }
777 if (claims.exp <= observedAt.epochMilliseconds) {
778 return yield* new WebSocketTokenExpiredError({
779 sessionId: claims.sid,
780 expiresAt: expiresAt.value,
781 observedAt,
782 });
783 }
784
785 const row = yield* authSessions
786 .getById({ sessionId: claims.sid })
787 .pipe(
788 Effect.mapError(
789 (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
790 ),
791 );
792 if (Option.isNone(row)) {
793 return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
794 }
795 if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
796 return yield* new WebSocketSessionExpiredError({
797 sessionId: claims.sid,
798 expiresAt: row.value.expiresAt,
799 observedAt,
800 });
801 }
802 if (row.value.revokedAt !== null) {
803 return yield* new WebSocketSessionRevokedError({
804 sessionId: claims.sid,
805 revokedAt: row.value.revokedAt,
806 });
807 }
808
809 return {
810 sessionId: row.value.sessionId,
811 token,
812 method: row.value.method,
813 client: toClientMetadata(row.value.client),
814 expiresAt: row.value.expiresAt,
815 subject: row.value.subject,
816 scopes: row.value.scopes,
817 } satisfies VerifiedSession;
818 });
819
820 const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
821 function* () {
822 const now = yield* DateTime.now;
823 const connectedSessions = yield* Ref.get(connectedSessionsRef);
824 const rows = yield* authSessions.listActive({ now });
825
826 return rows.map((row) =>
827 toAuthClientSession({
828 sessionId: row.sessionId,
829 subject: row.subject,
830 scopes: row.scopes,
831 method: row.method,
832 client: toClientMetadata(row.client),
833 issuedAt: row.issuedAt,
834 expiresAt: row.expiresAt,
835 lastConnectedAt: row.lastConnectedAt,
836 connected: connectedSessions.has(row.sessionId),
837 }),
838 );
839 },
840 Effect.mapError((cause) => new ActiveSessionsListError({ cause })),
841 );
842
843 const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
844 function* (sessionId) {
845 const revokedAt = yield* DateTime.now;
846 const revoked = yield* authSessions
847 .revoke({
848 sessionId,
849 revokedAt,
850 })
851 .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
852 if (revoked) {
853 yield* Ref.update(connectedSessionsRef, (current) => {
854 const next = new Map(current);
855 next.delete(sessionId);
856 return next;
857 });
858 yield* emitRemoved(sessionId);
859 }
860 return revoked;
861 },
862 );
863
864 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
865 "SessionStore.revokeAllExcept",
866 )(function* (sessionId) {
867 const revokedAt = yield* DateTime.now;
868 const revokedSessionIds = yield* authSessions
869 .revokeAllExcept({
870 currentSessionId: sessionId,
871 revokedAt,
872 })
873 .pipe(
874 Effect.mapError(
875 (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
876 ),
877 );
878 if (revokedSessionIds.length > 0) {
879 yield* Ref.update(connectedSessionsRef, (current) => {
880 const next = new Map(current);
881 for (const revokedSessionId of revokedSessionIds) {
882 next.delete(revokedSessionId);
883 }
884 return next;
885 });
886 yield* Effect.forEach(
887 revokedSessionIds,
888 (revokedSessionId) => emitRemoved(revokedSessionId),
889 {
890 concurrency: "unbounded",
891 discard: true,
892 },
893 );
894 }
895 return revokedSessionIds.length;
896 });
897
898 return SessionStore.of({
899 cookieName,
900 issue,
901 verify,
902 issueWebSocketToken,
903 verifyWebSocketToken,
904 listActive,
905 get streamChanges() {
906 return Stream.fromPubSub(changesPubSub);
907 },
908 revoke,
909 revokeAllExcept,
910 markConnected,
911 markDisconnected,
912 });
913});
914
915export const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));