Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AuthSessions.ts

530 lines17.4 KB

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