Open History to see the last commit
1import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
2import * as Clock from "effect/Clock";
3import * as DateTime from "effect/DateTime";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as PubSub from "effect/PubSub";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import * as Option from "effect/Option";
12
13import { ServerConfig } from "../../config.ts";
14import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
15import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
16import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
17import {
18 SessionCredentialError,
19 SessionCredentialService,
20 type IssuedSession,
21 type SessionCredentialChange,
22 type SessionCredentialServiceShape,
23 type VerifiedSession,
24} from "../Services/SessionCredentialService.ts";
25import {
26 base64UrlDecodeUtf8,
27 base64UrlEncode,
28 resolveSessionCookieName,
29 signPayload,
30 timingSafeEqualBase64Url,
31} from "../utils.ts";
32
33const SIGNING_SECRET_NAME = "server-signing-key";
34const DEFAULT_SESSION_TTL = Duration.days(30);
35const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
36
37const SessionClaims = Schema.Struct({
38 v: Schema.Literal(1),
39 kind: Schema.Literal("session"),
40 sid: AuthSessionId,
41 sub: Schema.String,
42 role: Schema.Literals(["owner", "client"]),
43 method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
44 iat: Schema.Number,
45 exp: Schema.Number,
46});
47type SessionClaims = typeof SessionClaims.Type;
48
49const WebSocketClaims = Schema.Struct({
50 v: Schema.Literal(1),
51 kind: Schema.Literal("websocket"),
52 sid: AuthSessionId,
53 iat: Schema.Number,
54 exp: Schema.Number,
55});
56type WebSocketClaims = typeof WebSocketClaims.Type;
57
58const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
59const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
60
61function createDefaultClientMetadata(): AuthClientMetadata {
62 return {
63 deviceType: "unknown",
64 };
65}
66
67function toClientMetadata(record: {
68 readonly label: string | null;
69 readonly ipAddress: string | null;
70 readonly userAgent: string | null;
71 readonly deviceType: AuthClientMetadata["deviceType"];
72 readonly os: string | null;
73 readonly browser: string | null;
74}): AuthClientMetadata {
75 return {
76 ...(record.label ? { label: record.label } : {}),
77 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
78 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
79 deviceType: record.deviceType,
80 ...(record.os ? { os: record.os } : {}),
81 ...(record.browser ? { browser: record.browser } : {}),
82 };
83}
84
85function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
86 return {
87 ...input,
88 current: false,
89 };
90}
91
92export const makeSessionCredentialService = Effect.gen(function* () {
93 const serverConfig = yield* ServerConfig;
94 const secretStore = yield* ServerSecretStore;
95 const authSessions = yield* AuthSessionRepository;
96 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
97 const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
98 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
99 const cookieName = resolveSessionCookieName({
100 mode: serverConfig.mode,
101 port: serverConfig.port,
102 });
103
104 const toSessionCredentialError = (message: string) => (cause: unknown) =>
105 new SessionCredentialError({
106 message,
107 cause,
108 });
109
110 const emitUpsert = (clientSession: AuthClientSession) =>
111 PubSub.publish(changesPubSub, {
112 type: "clientUpserted",
113 clientSession,
114 }).pipe(Effect.asVoid);
115
116 const emitRemoved = (sessionId: AuthSessionId) =>
117 PubSub.publish(changesPubSub, {
118 type: "clientRemoved",
119 sessionId,
120 }).pipe(Effect.asVoid);
121
122 const loadActiveSession = (sessionId: AuthSessionId) =>
123 Effect.gen(function* () {
124 const row = yield* authSessions.getById({ sessionId });
125 if (Option.isNone(row) || row.value.revokedAt !== null) {
126 return Option.none<AuthClientSession>();
127 }
128
129 const connectedSessions = yield* Ref.get(connectedSessionsRef);
130 return Option.some(
131 toAuthClientSession({
132 sessionId: row.value.sessionId,
133 subject: row.value.subject,
134 role: row.value.role,
135 method: row.value.method,
136 client: toClientMetadata(row.value.client),
137 issuedAt: row.value.issuedAt,
138 expiresAt: row.value.expiresAt,
139 lastConnectedAt: row.value.lastConnectedAt,
140 connected: connectedSessions.has(row.value.sessionId),
141 }),
142 );
143 });
144
145 const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
146 Ref.modify(connectedSessionsRef, (current) => {
147 const next = new Map(current);
148 const wasDisconnected = !next.has(sessionId);
149 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
150 return [wasDisconnected, next] as const;
151 }).pipe(
152 Effect.flatMap((wasDisconnected) =>
153 wasDisconnected
154 ? DateTime.now.pipe(
155 Effect.flatMap((lastConnectedAt) =>
156 authSessions.setLastConnectedAt({
157 sessionId,
158 lastConnectedAt,
159 }),
160 ),
161 )
162 : Effect.void,
163 ),
164 Effect.flatMap(() => loadActiveSession(sessionId)),
165 Effect.flatMap((session) =>
166 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
167 ),
168 Effect.catchCause((cause) =>
169 Effect.logError("Failed to publish connected-session auth update.").pipe(
170 Effect.annotateLogs({
171 sessionId,
172 cause,
173 }),
174 ),
175 ),
176 );
177
178 const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
179 Ref.update(connectedSessionsRef, (current) => {
180 const next = new Map(current);
181 const remaining = (next.get(sessionId) ?? 0) - 1;
182 if (remaining > 0) {
183 next.set(sessionId, remaining);
184 } else {
185 next.delete(sessionId);
186 }
187 return next;
188 }).pipe(
189 Effect.flatMap(() => loadActiveSession(sessionId)),
190 Effect.flatMap((session) =>
191 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
192 ),
193 Effect.catchCause((cause) =>
194 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
195 Effect.annotateLogs({
196 sessionId,
197 cause,
198 }),
199 ),
200 ),
201 );
202
203 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
204 const issue: SessionCredentialServiceShape["issue"] = (input) =>
205 Effect.gen(function* () {
206 const sessionId = AuthSessionId.make(crypto.randomUUID());
207 const issuedAt = yield* DateTime.now;
208 const expiresAt = DateTime.add(issuedAt, {
209 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
210 });
211 const claims: SessionClaims = {
212 v: 1,
213 kind: "session",
214 sid: sessionId,
215 sub: input?.subject ?? "browser",
216 role: input?.role ?? "client",
217 method: input?.method ?? "browser-session-cookie",
218 iat: issuedAt.epochMilliseconds,
219 exp: expiresAt.epochMilliseconds,
220 };
221
222 const encodedPayload = yield* encodeClaims(claims).pipe(
223 Effect.map(base64UrlEncode),
224 Effect.mapError(
225 (cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),
226 ),
227 );
228 const signature = signPayload(encodedPayload, signingSecret);
229 const client = input?.client ?? createDefaultClientMetadata();
230 yield* authSessions.create({
231 sessionId,
232 subject: claims.sub,
233 role: claims.role,
234 method: claims.method,
235 client: {
236 label: client.label ?? null,
237 ipAddress: client.ipAddress ?? null,
238 userAgent: client.userAgent ?? null,
239 deviceType: client.deviceType,
240 os: client.os ?? null,
241 browser: client.browser ?? null,
242 },
243 issuedAt,
244 expiresAt,
245 });
246 yield* emitUpsert(
247 toAuthClientSession({
248 sessionId,
249 subject: claims.sub,
250 role: claims.role,
251 method: claims.method,
252 client,
253 issuedAt,
254 expiresAt,
255 lastConnectedAt: null,
256 connected: false,
257 }),
258 );
259
260 return {
261 sessionId,
262 token: `${encodedPayload}.${signature}`,
263 method: claims.method,
264 client,
265 expiresAt: expiresAt,
266 role: claims.role,
267 } satisfies IssuedSession;
268 }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
269
270 const verify: SessionCredentialServiceShape["verify"] = (token) =>
271 Effect.gen(function* () {
272 const [encodedPayload, signature] = token.split(".");
273 if (!encodedPayload || !signature) {
274 return yield* new SessionCredentialError({
275 message: "Malformed session token.",
276 });
277 }
278
279 const expectedSignature = signPayload(encodedPayload, signingSecret);
280 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
281 return yield* new SessionCredentialError({
282 message: "Invalid session token signature.",
283 });
284 }
285
286 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
287 Effect.mapError(
288 (cause) =>
289 new SessionCredentialError({
290 message: "Invalid session token payload.",
291 cause,
292 }),
293 ),
294 );
295
296 const now = yield* Clock.currentTimeMillis;
297 if (claims.exp <= now) {
298 return yield* new SessionCredentialError({
299 message: "Session token expired.",
300 });
301 }
302
303 const row = yield* authSessions.getById({ sessionId: claims.sid });
304 if (Option.isNone(row)) {
305 return yield* new SessionCredentialError({
306 message: "Unknown session token.",
307 });
308 }
309 if (row.value.revokedAt !== null) {
310 return yield* new SessionCredentialError({
311 message: "Session token revoked.",
312 });
313 }
314
315 const expiresAt = DateTime.make(claims.exp);
316 if (Option.isNone(expiresAt)) {
317 return yield* new SessionCredentialError({
318 message: "Invalid `exp` claim",
319 });
320 }
321
322 return {
323 sessionId: claims.sid,
324 token,
325 method: claims.method,
326 client: toClientMetadata(row.value.client),
327 expiresAt: expiresAt.value,
328 subject: claims.sub,
329 role: claims.role,
330 } satisfies VerifiedSession;
331 }).pipe(
332 Effect.mapError((cause) =>
333 cause instanceof SessionCredentialError
334 ? cause
335 : new SessionCredentialError({
336 message: "Failed to verify session credential.",
337 cause,
338 }),
339 ),
340 );
341
342 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
343 const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
344 sessionId,
345 input,
346 ) =>
347 Effect.gen(function* () {
348 const issuedAt = yield* DateTime.now;
349 const expiresAt = DateTime.add(issuedAt, {
350 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
351 });
352 const claims: WebSocketClaims = {
353 v: 1,
354 kind: "websocket",
355 sid: sessionId,
356 iat: issuedAt.epochMilliseconds,
357 exp: expiresAt.epochMilliseconds,
358 };
359 const encodedPayload = yield* encodeWsClaims(claims).pipe(
360 Effect.map(base64UrlEncode),
361 Effect.mapError(
362 (cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),
363 ),
364 );
365 const signature = signPayload(encodedPayload, signingSecret);
366 return {
367 token: `${encodedPayload}.${signature}`,
368 expiresAt,
369 };
370 }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
371
372 const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
373 Effect.gen(function* () {
374 const [encodedPayload, signature] = token.split(".");
375 if (!encodedPayload || !signature) {
376 return yield* new SessionCredentialError({
377 message: "Malformed websocket token.",
378 });
379 }
380
381 const expectedSignature = signPayload(encodedPayload, signingSecret);
382 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
383 return yield* new SessionCredentialError({
384 message: "Invalid websocket token signature.",
385 });
386 }
387
388 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
389 Effect.mapError(
390 (cause) =>
391 new SessionCredentialError({
392 message: "Invalid websocket token payload.",
393 cause,
394 }),
395 ),
396 );
397
398 const now = yield* Clock.currentTimeMillis;
399 if (claims.exp <= now) {
400 return yield* new SessionCredentialError({
401 message: "Websocket token expired.",
402 });
403 }
404
405 const row = yield* authSessions.getById({ sessionId: claims.sid });
406 if (Option.isNone(row)) {
407 return yield* new SessionCredentialError({
408 message: "Unknown websocket session.",
409 });
410 }
411 if (row.value.expiresAt.epochMilliseconds <= now) {
412 return yield* new SessionCredentialError({
413 message: "Websocket session expired.",
414 });
415 }
416 if (row.value.revokedAt !== null) {
417 return yield* new SessionCredentialError({
418 message: "Websocket session revoked.",
419 });
420 }
421
422 return {
423 sessionId: row.value.sessionId,
424 token,
425 method: row.value.method,
426 client: toClientMetadata(row.value.client),
427 expiresAt: row.value.expiresAt,
428 subject: row.value.subject,
429 role: row.value.role,
430 } satisfies VerifiedSession;
431 }).pipe(
432 Effect.mapError((cause) =>
433 cause instanceof SessionCredentialError
434 ? cause
435 : new SessionCredentialError({
436 message: "Failed to verify websocket token.",
437 cause,
438 }),
439 ),
440 );
441
442 const listActive: SessionCredentialServiceShape["listActive"] = () =>
443 Effect.gen(function* () {
444 const now = yield* DateTime.now;
445 const connectedSessions = yield* Ref.get(connectedSessionsRef);
446 const rows = yield* authSessions.listActive({ now });
447
448 return rows.map((row) =>
449 toAuthClientSession({
450 sessionId: row.sessionId,
451 subject: row.subject,
452 role: row.role,
453 method: row.method,
454 client: toClientMetadata(row.client),
455 issuedAt: row.issuedAt,
456 expiresAt: row.expiresAt,
457 lastConnectedAt: row.lastConnectedAt,
458 connected: connectedSessions.has(row.sessionId),
459 }),
460 );
461 }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
462
463 const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
464 Effect.gen(function* () {
465 const revokedAt = yield* DateTime.now;
466 const revoked = yield* authSessions.revoke({
467 sessionId,
468 revokedAt,
469 });
470 if (revoked) {
471 yield* Ref.update(connectedSessionsRef, (current) => {
472 const next = new Map(current);
473 next.delete(sessionId);
474 return next;
475 });
476 yield* emitRemoved(sessionId);
477 }
478 return revoked;
479 }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
480
481 const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
482 Effect.gen(function* () {
483 const revokedAt = yield* DateTime.now;
484 const revokedSessionIds = yield* authSessions.revokeAllExcept({
485 currentSessionId: sessionId,
486 revokedAt,
487 });
488 if (revokedSessionIds.length > 0) {
489 yield* Ref.update(connectedSessionsRef, (current) => {
490 const next = new Map(current);
491 for (const revokedSessionId of revokedSessionIds) {
492 next.delete(revokedSessionId);
493 }
494 return next;
495 });
496 yield* Effect.forEach(
497 revokedSessionIds,
498 (revokedSessionId) => emitRemoved(revokedSessionId),
499 {
500 concurrency: "unbounded",
501 discard: true,
502 },
503 );
504 }
505 return revokedSessionIds.length;
506 }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
507
508 return {
509 cookieName,
510 issue,
511 verify,
512 issueWebSocketToken,
513 verifyWebSocketToken,
514 listActive,
515 get streamChanges() {
516 return Stream.fromPubSub(changesPubSub);
517 },
518 revoke,
519 revokeAllExcept,
520 markConnected,
521 markDisconnected,
522 } satisfies SessionCredentialServiceShape;
523});
524
525export const SessionCredentialServiceLive = Layer.effect(
526 SessionCredentialService,
527 makeSessionCredentialService,
528).pipe(Layer.provideMerge(AuthSessionRepositoryLive));