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