Open History to see the last commit
1import * as Context from "effect/Context";
2import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as SqlClient from "effect/sql/SqlClient";
8import * as SqlSchema from "effect/sql/SqlSchema";
9
10import {
11 AuthClientMetadataDeviceType,
12 AuthEnvironmentScopes,
13 AuthSessionId,
14 ServerAuthSessionMethod,
15} from "@t3tools/contracts";
16
17import {
18 type AuthSessionRepositoryError,
19 PersistenceDecodeError,
20 type PersistenceErrorCorrelation,
21 PersistenceSqlError,
22} from "./Errors.ts";
23
24export const AuthSessionClientMetadataRecord = Schema.Struct({
25 label: Schema.NullOr(Schema.String),
26 ipAddress: Schema.NullOr(Schema.String),
27 userAgent: Schema.NullOr(Schema.String),
28 deviceType: AuthClientMetadataDeviceType,
29 os: Schema.NullOr(Schema.String),
30 browser: Schema.NullOr(Schema.String),
31});
32export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;
33
34export const AuthSessionRecord = Schema.Struct({
35 sessionId: AuthSessionId,
36 subject: Schema.String,
37 scopes: AuthEnvironmentScopes,
38 method: ServerAuthSessionMethod,
39 client: AuthSessionClientMetadataRecord,
40 issuedAt: Schema.DateTimeUtcFromString,
41 expiresAt: Schema.DateTimeUtcFromString,
42 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
43 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
44});
45export type AuthSessionRecord = typeof AuthSessionRecord.Type;
46
47export const CreateAuthSessionInput = Schema.Struct({
48 sessionId: AuthSessionId,
49 subject: Schema.String,
50 scopes: AuthEnvironmentScopes,
51 method: ServerAuthSessionMethod,
52 client: AuthSessionClientMetadataRecord,
53 issuedAt: Schema.DateTimeUtcFromString,
54 expiresAt: Schema.DateTimeUtcFromString,
55 proofKeyThumbprint: Schema.optionalKey(Schema.String),
56});
57export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
58
59export const CreateReplacingActiveAuthSessionInput = Schema.Struct({
60 session: CreateAuthSessionInput,
61 revokedAt: Schema.DateTimeUtcFromString,
62 replaceSessionId: Schema.optionalKey(AuthSessionId),
63});
64export type CreateReplacingActiveAuthSessionInput =
65 typeof CreateReplacingActiveAuthSessionInput.Type;
66
67export const GetAuthSessionByIdInput = Schema.Struct({
68 sessionId: AuthSessionId,
69});
70export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
71
72export const ListActiveAuthSessionsInput = Schema.Struct({
73 now: Schema.DateTimeUtcFromString,
74 connectedSessionIds: Schema.optionalKey(Schema.Array(AuthSessionId)),
75});
76export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
77
78export const RevokeAuthSessionInput = Schema.Struct({
79 sessionId: AuthSessionId,
80 revokedAt: Schema.DateTimeUtcFromString,
81});
82export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
83
84export const RevokeOtherAuthSessionsInput = Schema.Struct({
85 currentSessionId: AuthSessionId,
86 revokedAt: Schema.DateTimeUtcFromString,
87});
88export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
89
90export const RevokeAuthSessionsByProofKeyInput = Schema.Struct({
91 proofKeyThumbprint: Schema.String,
92 revokedAt: Schema.DateTimeUtcFromString,
93});
94export type RevokeAuthSessionsByProofKeyInput = typeof RevokeAuthSessionsByProofKeyInput.Type;
95
96export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
97 sessionId: AuthSessionId,
98 lastConnectedAt: Schema.DateTimeUtcFromString,
99});
100export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
101
102export class AuthSessionRepository extends Context.Service<
103 AuthSessionRepository,
104 {
105 readonly create: (
106 input: CreateAuthSessionInput,
107 ) => Effect.Effect<void, AuthSessionRepositoryError>;
108 readonly createReplacingActive: (
109 input: CreateReplacingActiveAuthSessionInput,
110 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
111 readonly createIfAbsent: (
112 input: CreateAuthSessionInput,
113 ) => Effect.Effect<void, AuthSessionRepositoryError>;
114 readonly getById: (
115 input: GetAuthSessionByIdInput,
116 ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
117 readonly listActive: (
118 input: ListActiveAuthSessionsInput,
119 ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
120 readonly revoke: (
121 input: RevokeAuthSessionInput,
122 ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
123 readonly revokeAllExcept: (
124 input: RevokeOtherAuthSessionsInput,
125 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
126 readonly setLastConnectedAt: (
127 input: SetAuthSessionLastConnectedAtInput,
128 ) => Effect.Effect<void, AuthSessionRepositoryError>;
129 readonly getProofKeyThumbprint: (
130 input: GetAuthSessionByIdInput,
131 ) => Effect.Effect<Option.Option<string>, AuthSessionRepositoryError>;
132 readonly revokeByProofKey: (
133 input: RevokeAuthSessionsByProofKeyInput,
134 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
135 }
136>()("t3/persistence/AuthSessions/AuthSessionRepository") {}
137
138const AuthSessionDbRow = Schema.Struct({
139 sessionId: AuthSessionId,
140 subject: Schema.String,
141 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
142 method: ServerAuthSessionMethod,
143 clientLabel: Schema.NullOr(Schema.String),
144 clientIpAddress: Schema.NullOr(Schema.String),
145 clientUserAgent: Schema.NullOr(Schema.String),
146 clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
147 clientOs: Schema.NullOr(Schema.String),
148 clientBrowser: Schema.NullOr(Schema.String),
149 issuedAt: Schema.DateTimeUtcFromString,
150 expiresAt: Schema.DateTimeUtcFromString,
151 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
152 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
153});
154
155const AuthSessionRawDbRow = Schema.Struct({
156 sessionId: Schema.String,
157 subject: Schema.Unknown,
158 scopes: Schema.Unknown,
159 method: Schema.Unknown,
160 clientLabel: Schema.Unknown,
161 clientIpAddress: Schema.Unknown,
162 clientUserAgent: Schema.Unknown,
163 clientDeviceType: Schema.Unknown,
164 clientOs: Schema.Unknown,
165 clientBrowser: Schema.Unknown,
166 issuedAt: Schema.Unknown,
167 expiresAt: Schema.Unknown,
168 lastConnectedAt: Schema.Unknown,
169 revokedAt: Schema.Unknown,
170});
171
172const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);
173
174function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
175 return {
176 sessionId: row.sessionId,
177 subject: row.subject,
178 scopes: row.scopes,
179 method: row.method,
180 client: {
181 label: row.clientLabel,
182 ipAddress: row.clientIpAddress,
183 userAgent: row.clientUserAgent,
184 deviceType: row.clientDeviceType,
185 os: row.clientOs,
186 browser: row.clientBrowser,
187 },
188 issuedAt: row.issuedAt,
189 expiresAt: row.expiresAt,
190 lastConnectedAt: row.lastConnectedAt,
191 revokedAt: row.revokedAt,
192 };
193}
194
195function toPersistenceSqlOrDecodeError(
196 sqlOperation: string,
197 decodeOperation: string,
198 correlation?: PersistenceErrorCorrelation,
199) {
200 return (cause: unknown): AuthSessionRepositoryError =>
201 Schema.isSchemaError(cause)
202 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
203 : new PersistenceSqlError({
204 operation: sqlOperation,
205 ...(correlation === undefined ? {} : { correlation }),
206 cause,
207 });
208}
209
210/** @public */
211export const make = Effect.gen(function* () {
212 const sql = yield* SqlClient.SqlClient;
213
214 const insertSessionRow = (ignoreExisting: boolean) =>
215 SqlSchema.void({
216 Request: CreateAuthSessionInput,
217 execute: (input) =>
218 sql`
219 INSERT INTO auth_sessions (
220 session_id,
221 subject,
222 scopes,
223 method,
224 client_label,
225 client_ip_address,
226 client_user_agent,
227 client_device_type,
228 client_os,
229 client_browser,
230 issued_at,
231 expires_at,
232 revoked_at,
233 proof_key_thumbprint
234 )
235 VALUES (
236 ${input.sessionId},
237 ${input.subject},
238 ${JSON.stringify(input.scopes)},
239 ${input.method},
240 ${input.client.label},
241 ${input.client.ipAddress},
242 ${input.client.userAgent},
243 ${input.client.deviceType},
244 ${input.client.os},
245 ${input.client.browser},
246 ${input.issuedAt},
247 ${input.expiresAt},
248 NULL,
249 ${input.proofKeyThumbprint ?? null}
250 )
251 ${ignoreExisting ? sql`ON CONFLICT(session_id) DO NOTHING` : sql``}
252 `,
253 });
254 const createSessionRow = insertSessionRow(false);
255 const createSessionRowIfAbsent = insertSessionRow(true);
256
257 const getSessionRowById = SqlSchema.findOneOption({
258 Request: GetAuthSessionByIdInput,
259 Result: AuthSessionRawDbRow,
260 execute: ({ sessionId }) =>
261 sql`
262 SELECT
263 session_id AS "sessionId",
264 subject AS "subject",
265 scopes AS "scopes",
266 method AS "method",
267 client_label AS "clientLabel",
268 client_ip_address AS "clientIpAddress",
269 client_user_agent AS "clientUserAgent",
270 client_device_type AS "clientDeviceType",
271 client_os AS "clientOs",
272 client_browser AS "clientBrowser",
273 issued_at AS "issuedAt",
274 expires_at AS "expiresAt",
275 last_connected_at AS "lastConnectedAt",
276 revoked_at AS "revokedAt"
277 FROM auth_sessions
278 WHERE session_id = ${sessionId}
279 `,
280 });
281
282 const revokeActiveSessionsForReplacement = SqlSchema.findAll({
283 Request: CreateReplacingActiveAuthSessionInput,
284 Result: Schema.Struct({ sessionId: AuthSessionId }),
285 execute: ({ session, revokedAt, replaceSessionId }) =>
286 sql`
287 UPDATE auth_sessions
288 SET revoked_at = ${revokedAt}
289 WHERE ${
290 replaceSessionId === undefined
291 ? sql`subject = ${session.subject}`
292 : sql`session_id = ${replaceSessionId}`
293 }
294 AND method = ${session.method}
295 AND revoked_at IS NULL
296 AND expires_at > ${revokedAt}
297 RETURNING session_id AS "sessionId"
298 `,
299 });
300
301 const listActiveSessionRows = SqlSchema.findAll({
302 Request: ListActiveAuthSessionsInput,
303 Result: AuthSessionRawDbRow,
304 execute: ({ now, connectedSessionIds = [] }) =>
305 sql`
306 SELECT
307 session_id AS "sessionId",
308 subject AS "subject",
309 scopes AS "scopes",
310 method AS "method",
311 client_label AS "clientLabel",
312 client_ip_address AS "clientIpAddress",
313 client_user_agent AS "clientUserAgent",
314 client_device_type AS "clientDeviceType",
315 client_os AS "clientOs",
316 client_browser AS "clientBrowser",
317 issued_at AS "issuedAt",
318 expires_at AS "expiresAt",
319 last_connected_at AS "lastConnectedAt",
320 revoked_at AS "revokedAt"
321 FROM auth_sessions
322 WHERE revoked_at IS NULL
323 AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)})
324 ORDER BY issued_at DESC, session_id DESC
325 `,
326 });
327
328 const setLastConnectedAtRow = SqlSchema.void({
329 Request: SetAuthSessionLastConnectedAtInput,
330 execute: ({ sessionId, lastConnectedAt }) =>
331 sql`
332 UPDATE auth_sessions
333 SET last_connected_at = ${lastConnectedAt}
334 WHERE session_id = ${sessionId}
335 AND revoked_at IS NULL
336 `,
337 });
338
339 const revokeSessionRows = SqlSchema.findAll({
340 Request: RevokeAuthSessionInput,
341 Result: Schema.Struct({ sessionId: AuthSessionId }),
342 execute: ({ sessionId, revokedAt }) =>
343 sql`
344 UPDATE auth_sessions
345 SET revoked_at = ${revokedAt}
346 WHERE session_id = ${sessionId}
347 AND revoked_at IS NULL
348 RETURNING session_id AS "sessionId"
349 `,
350 });
351
352 const proofKeyThumbprintRows = SqlSchema.findAll({
353 Request: GetAuthSessionByIdInput,
354 Result: Schema.Struct({ proofKeyThumbprint: Schema.String }),
355 execute: ({ sessionId }) =>
356 sql`
357 SELECT proof_key_thumbprint AS "proofKeyThumbprint"
358 FROM auth_sessions
359 WHERE session_id = ${sessionId}
360 AND proof_key_thumbprint IS NOT NULL
361 `,
362 });
363
364 const revokeByProofKeyRows = SqlSchema.findAll({
365 Request: RevokeAuthSessionsByProofKeyInput,
366 Result: Schema.Struct({ sessionId: AuthSessionId }),
367 execute: ({ proofKeyThumbprint, revokedAt }) =>
368 sql`
369 UPDATE auth_sessions
370 SET revoked_at = ${revokedAt}
371 WHERE proof_key_thumbprint = ${proofKeyThumbprint}
372 AND revoked_at IS NULL
373 RETURNING session_id AS "sessionId"
374 `,
375 });
376
377 const revokeOtherSessionRows = SqlSchema.findAll({
378 Request: RevokeOtherAuthSessionsInput,
379 Result: Schema.Struct({ sessionId: AuthSessionId }),
380 execute: ({ currentSessionId, revokedAt }) =>
381 sql`
382 UPDATE auth_sessions
383 SET revoked_at = ${revokedAt}
384 WHERE session_id <> ${currentSessionId}
385 AND revoked_at IS NULL
386 RETURNING session_id AS "sessionId"
387 `,
388 });
389
390 const create: AuthSessionRepository["Service"]["create"] = (input) =>
391 createSessionRow(input).pipe(
392 Effect.mapError(
393 toPersistenceSqlOrDecodeError(
394 "AuthSessionRepository.create:query",
395 "AuthSessionRepository.create:encodeRequest",
396 { sessionId: input.sessionId },
397 ),
398 ),
399 );
400
401 const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = (
402 input,
403 ) =>
404 sql
405 .withTransaction(
406 revokeActiveSessionsForReplacement(input).pipe(
407 Effect.flatMap((revokedRows) =>
408 createSessionRow(input.session).pipe(
409 Effect.as(revokedRows.map((row) => row.sessionId)),
410 ),
411 ),
412 ),
413 )
414 .pipe(
415 Effect.mapError(
416 toPersistenceSqlOrDecodeError(
417 "AuthSessionRepository.createReplacingActive:query",
418 "AuthSessionRepository.createReplacingActive:encodeRequest",
419 { sessionId: input.session.sessionId },
420 ),
421 ),
422 );
423
424 const createIfAbsent: AuthSessionRepository["Service"]["createIfAbsent"] = (input) =>
425 createSessionRowIfAbsent(input).pipe(
426 Effect.mapError(
427 toPersistenceSqlOrDecodeError(
428 "AuthSessionRepository.createIfAbsent:query",
429 "AuthSessionRepository.createIfAbsent:encodeRequest",
430 { sessionId: input.sessionId },
431 ),
432 ),
433 );
434
435 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
436 getSessionRowById(input).pipe(
437 NodeSqliteClient.readOnly,
438 Effect.mapError(
439 toPersistenceSqlOrDecodeError(
440 "AuthSessionRepository.getById:query",
441 "AuthSessionRepository.getById:decodeRow",
442 { sessionId: input.sessionId },
443 ),
444 ),
445 Effect.flatMap((rowOption) =>
446 Option.match(rowOption, {
447 onNone: () => Effect.succeedNone,
448 onSome: (row) =>
449 decodeAuthSessionDbRow(row).pipe(
450 Effect.mapError((cause) =>
451 PersistenceDecodeError.fromSchemaError(
452 "AuthSessionRepository.getById:decodeRow",
453 cause,
454 { sessionId: input.sessionId },
455 ),
456 ),
457 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
458 ),
459 }),
460 ),
461 );
462
463 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
464 listActiveSessionRows(input).pipe(
465 NodeSqliteClient.readOnly,
466 Effect.mapError(
467 toPersistenceSqlOrDecodeError(
468 "AuthSessionRepository.listActive:query",
469 "AuthSessionRepository.listActive:decodeRows",
470 ),
471 ),
472 Effect.flatMap((rows) =>
473 Effect.forEach(rows, (row) =>
474 decodeAuthSessionDbRow(row).pipe(
475 Effect.mapError((cause) =>
476 PersistenceDecodeError.fromSchemaError(
477 "AuthSessionRepository.listActive:decodeRows",
478 cause,
479 { sessionId: row.sessionId },
480 ),
481 ),
482 Effect.map(toAuthSessionRecord),
483 ),
484 ),
485 ),
486 );
487
488 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
489 revokeSessionRows(input).pipe(
490 Effect.mapError(
491 toPersistenceSqlOrDecodeError(
492 "AuthSessionRepository.revoke:query",
493 "AuthSessionRepository.revoke:decodeRows",
494 { sessionId: input.sessionId },
495 ),
496 ),
497 Effect.map((rows) => rows.length > 0),
498 );
499
500 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
501 revokeOtherSessionRows(input).pipe(
502 Effect.mapError(
503 toPersistenceSqlOrDecodeError(
504 "AuthSessionRepository.revokeAllExcept:query",
505 "AuthSessionRepository.revokeAllExcept:decodeRows",
506 { currentSessionId: input.currentSessionId },
507 ),
508 ),
509 Effect.map((rows) => rows.map((row) => row.sessionId)),
510 );
511
512 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
513 setLastConnectedAtRow(input).pipe(
514 Effect.mapError(
515 toPersistenceSqlOrDecodeError(
516 "AuthSessionRepository.setLastConnectedAt:query",
517 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
518 { sessionId: input.sessionId },
519 ),
520 ),
521 );
522
523 const getProofKeyThumbprint: AuthSessionRepository["Service"]["getProofKeyThumbprint"] = (
524 input,
525 ) =>
526 proofKeyThumbprintRows(input).pipe(
527 NodeSqliteClient.readOnly,
528 Effect.mapError(
529 toPersistenceSqlOrDecodeError(
530 "AuthSessionRepository.getProofKeyThumbprint:query",
531 "AuthSessionRepository.getProofKeyThumbprint:decodeRows",
532 { sessionId: input.sessionId },
533 ),
534 ),
535 Effect.map((rows) => Option.fromNullishOr(rows[0]?.proofKeyThumbprint)),
536 );
537
538 const revokeByProofKey: AuthSessionRepository["Service"]["revokeByProofKey"] = (input) =>
539 revokeByProofKeyRows(input).pipe(
540 Effect.mapError(
541 toPersistenceSqlOrDecodeError(
542 "AuthSessionRepository.revokeByProofKey:query",
543 "AuthSessionRepository.revokeByProofKey:decodeRows",
544 ),
545 ),
546 Effect.map((rows) => rows.map((row) => row.sessionId)),
547 );
548
549 return {
550 create,
551 createReplacingActive,
552 createIfAbsent,
553 getById,
554 listActive,
555 revoke,
556 revokeAllExcept,
557 setLastConnectedAt,
558 getProofKeyThumbprint,
559 revokeByProofKey,
560 } satisfies AuthSessionRepository["Service"];
561});
562
563export const layer = Layer.effect(AuthSessionRepository, make);