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