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

AuthSessions.ts

503 lines16.3 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import * as SqlClient from "effect/unstable/sql/SqlClient";
7import * as SqlSchema from "effect/unstable/sql/SqlSchema";
8​
9import {
10 AuthClientMetadataDeviceType,
11 AuthEnvironmentScopes,
12 AuthSessionId,
13 ClientSurface,
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});
56export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
57​
58export const CreateReplacingActiveAuthSessionInput = Schema.Struct({
59 session: CreateAuthSessionInput,
60 revokedAt: Schema.DateTimeUtcFromString,
61});
62export type CreateReplacingActiveAuthSessionInput =
63 typeof CreateReplacingActiveAuthSessionInput.Type;
64​
65export const GetAuthSessionByIdInput = Schema.Struct({
66 sessionId: AuthSessionId,
67});
68export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
69​
70export const ListActiveAuthSessionsInput = Schema.Struct({
71 now: Schema.DateTimeUtcFromString,
72});
73export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
74​
75export const RevokeAuthSessionInput = Schema.Struct({
76 sessionId: AuthSessionId,
77 revokedAt: Schema.DateTimeUtcFromString,
78});
79export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
80​
81export const RevokeOtherAuthSessionsInput = Schema.Struct({
82 currentSessionId: AuthSessionId,
83 revokedAt: Schema.DateTimeUtcFromString,
84});
85export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
86​
87export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
88 sessionId: AuthSessionId,
89 lastConnectedAt: Schema.DateTimeUtcFromString,
90});
91export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
92​
93export const SetAuthSessionClientConnectionInput = Schema.Struct({
94 sessionId: AuthSessionId,
95 surface: Schema.NullOr(ClientSurface),
96 appVersion: Schema.NullOr(Schema.String),
97});
98export type SetAuthSessionClientConnectionInput = typeof SetAuthSessionClientConnectionInput.Type;
99​
100export class AuthSessionRepository extends Context.Service<
101 AuthSessionRepository,
102 {
103 readonly create: (
104 input: CreateAuthSessionInput,
105 ) => Effect.Effect<void, AuthSessionRepositoryError>;
106 readonly createReplacingActive: (
107 input: CreateReplacingActiveAuthSessionInput,
108 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
109 readonly getById: (
110 input: GetAuthSessionByIdInput,
111 ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
112 readonly listActive: (
113 input: ListActiveAuthSessionsInput,
114 ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
115 readonly revoke: (
116 input: RevokeAuthSessionInput,
117 ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
118 readonly revokeAllExcept: (
119 input: RevokeOtherAuthSessionsInput,
120 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
121 readonly setLastConnectedAt: (
122 input: SetAuthSessionLastConnectedAtInput,
123 ) => Effect.Effect<void, AuthSessionRepositoryError>;
124 readonly setClientConnection: (
125 input: SetAuthSessionClientConnectionInput,
126 ) => Effect.Effect<void, AuthSessionRepositoryError>;
127 }
128>()("t3/persistence/AuthSessions/AuthSessionRepository") {}
129​
130const AuthSessionDbRow = Schema.Struct({
131 sessionId: AuthSessionId,
132 subject: Schema.String,
133 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
134 method: ServerAuthSessionMethod,
135 clientLabel: Schema.NullOr(Schema.String),
136 clientIpAddress: Schema.NullOr(Schema.String),
137 clientUserAgent: Schema.NullOr(Schema.String),
138 clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
139 clientOs: Schema.NullOr(Schema.String),
140 clientBrowser: Schema.NullOr(Schema.String),
141 issuedAt: Schema.DateTimeUtcFromString,
142 expiresAt: Schema.DateTimeUtcFromString,
143 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
144 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
145});
146​
147const AuthSessionRawDbRow = Schema.Struct({
148 sessionId: Schema.String,
149 subject: Schema.Unknown,
150 scopes: Schema.Unknown,
151 method: Schema.Unknown,
152 clientLabel: Schema.Unknown,
153 clientIpAddress: Schema.Unknown,
154 clientUserAgent: Schema.Unknown,
155 clientDeviceType: Schema.Unknown,
156 clientOs: Schema.Unknown,
157 clientBrowser: Schema.Unknown,
158 issuedAt: Schema.Unknown,
159 expiresAt: Schema.Unknown,
160 lastConnectedAt: Schema.Unknown,
161 revokedAt: Schema.Unknown,
162});
163​
164const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);
165​
166function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
167 return {
168 sessionId: row.sessionId,
169 subject: row.subject,
170 scopes: row.scopes,
171 method: row.method,
172 client: {
173 label: row.clientLabel,
174 ipAddress: row.clientIpAddress,
175 userAgent: row.clientUserAgent,
176 deviceType: row.clientDeviceType,
177 os: row.clientOs,
178 browser: row.clientBrowser,
179 },
180 issuedAt: row.issuedAt,
181 expiresAt: row.expiresAt,
182 lastConnectedAt: row.lastConnectedAt,
183 revokedAt: row.revokedAt,
184 };
186​
187function toPersistenceSqlOrDecodeError(
188 sqlOperation: string,
189 decodeOperation: string,
190 correlation?: PersistenceErrorCorrelation,
191) {
192 return (cause: unknown): AuthSessionRepositoryError =>
193 Schema.isSchemaError(cause)
194 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
195 : new PersistenceSqlError({
196 operation: sqlOperation,
197 ...(correlation === undefined ? {} : { correlation }),
198 cause,
199 });
201​
202export const make = Effect.gen(function* () {
203 const sql = yield* SqlClient.SqlClient;
204​
205 const createSessionRow = SqlSchema.void({
206 Request: CreateAuthSessionInput,
207 execute: (input) =>
208 sql`
209 INSERT INTO auth_sessions (
210 session_id,
211 subject,
212 scopes,
213 method,
214 client_label,
215 client_ip_address,
216 client_user_agent,
217 client_device_type,
218 client_os,
219 client_browser,
220 issued_at,
221 expires_at,
222 revoked_at
223 )
224 VALUES (
225 ${input.sessionId},
226 ${input.subject},
227 ${JSON.stringify(input.scopes)},
228 ${input.method},
229 ${input.client.label},
230 ${input.client.ipAddress},
231 ${input.client.userAgent},
232 ${input.client.deviceType},
233 ${input.client.os},
234 ${input.client.browser},
235 ${input.issuedAt},
236 ${input.expiresAt},
237 NULL
238 )
239 `,
240 });
241​
242 const getSessionRowById = SqlSchema.findOneOption({
243 Request: GetAuthSessionByIdInput,
244 Result: AuthSessionRawDbRow,
245 execute: ({ sessionId }) =>
246 sql`
247 SELECT
248 session_id AS "sessionId",
249 subject AS "subject",
250 scopes AS "scopes",
251 method AS "method",
252 client_label AS "clientLabel",
253 client_ip_address AS "clientIpAddress",
254 client_user_agent AS "clientUserAgent",
255 client_device_type AS "clientDeviceType",
256 client_os AS "clientOs",
257 client_browser AS "clientBrowser",
258 issued_at AS "issuedAt",
259 expires_at AS "expiresAt",
260 last_connected_at AS "lastConnectedAt",
261 revoked_at AS "revokedAt"
262 FROM auth_sessions
263 WHERE session_id = ${sessionId}
264 `,
265 });
266​
267 const revokeActiveSessionsForReplacement = SqlSchema.findAll({
268 Request: CreateReplacingActiveAuthSessionInput,
269 Result: Schema.Struct({ sessionId: AuthSessionId }),
270 execute: ({ session, revokedAt }) =>
271 sql`
272 UPDATE auth_sessions
273 SET revoked_at = ${revokedAt}
274 WHERE subject = ${session.subject}
275 AND method = ${session.method}
276 AND revoked_at IS NULL
277 AND expires_at > ${revokedAt}
278 RETURNING session_id AS "sessionId"
279 `,
280 });
281​
282 const listActiveSessionRows = SqlSchema.findAll({
283 Request: ListActiveAuthSessionsInput,
284 Result: AuthSessionRawDbRow,
285 execute: ({ now }) =>
286 sql`
287 SELECT
288 session_id AS "sessionId",
289 subject AS "subject",
290 scopes AS "scopes",
291 method AS "method",
292 client_label AS "clientLabel",
293 client_ip_address AS "clientIpAddress",
294 client_user_agent AS "clientUserAgent",
295 client_device_type AS "clientDeviceType",
296 client_os AS "clientOs",
297 client_browser AS "clientBrowser",
298 issued_at AS "issuedAt",
299 expires_at AS "expiresAt",
300 last_connected_at AS "lastConnectedAt",
301 revoked_at AS "revokedAt"
302 FROM auth_sessions
303 WHERE revoked_at IS NULL
304 AND expires_at > ${now}
305 ORDER BY issued_at DESC, session_id DESC
306 `,
307 });
308​
309 const setLastConnectedAtRow = SqlSchema.void({
310 Request: SetAuthSessionLastConnectedAtInput,
311 execute: ({ sessionId, lastConnectedAt }) =>
312 sql`
313 UPDATE auth_sessions
314 SET last_connected_at = ${lastConnectedAt}
315 WHERE session_id = ${sessionId}
316 AND revoked_at IS NULL
317 `,
318 });
319​
320 // COALESCE keeps the previous value when a client reports only one field, so
321 // a partial report never nulls out data a fuller client stored earlier.
322 const setClientConnectionRow = SqlSchema.void({
323 Request: SetAuthSessionClientConnectionInput,
324 execute: ({ sessionId, surface, appVersion }) =>
325 sql`
326 UPDATE auth_sessions
327 SET client_surface = COALESCE(${surface}, client_surface),
328 client_app_version = COALESCE(${appVersion}, client_app_version)
329 WHERE session_id = ${sessionId}
330 AND revoked_at IS NULL
331 `,
332 });
333​
334 const revokeSessionRows = SqlSchema.findAll({
335 Request: RevokeAuthSessionInput,
336 Result: Schema.Struct({ sessionId: AuthSessionId }),
337 execute: ({ sessionId, revokedAt }) =>
338 sql`
339 UPDATE auth_sessions
340 SET revoked_at = ${revokedAt}
341 WHERE session_id = ${sessionId}
342 AND revoked_at IS NULL
343 RETURNING session_id AS "sessionId"
344 `,
345 });
346​
347 const revokeOtherSessionRows = SqlSchema.findAll({
348 Request: RevokeOtherAuthSessionsInput,
349 Result: Schema.Struct({ sessionId: AuthSessionId }),
350 execute: ({ currentSessionId, revokedAt }) =>
351 sql`
352 UPDATE auth_sessions
353 SET revoked_at = ${revokedAt}
354 WHERE session_id <> ${currentSessionId}
355 AND revoked_at IS NULL
356 RETURNING session_id AS "sessionId"
357 `,
358 });
359​
360 const create: AuthSessionRepository["Service"]["create"] = (input) =>
361 createSessionRow(input).pipe(
362 Effect.mapError(
363 toPersistenceSqlOrDecodeError(
364 "AuthSessionRepository.create:query",
365 "AuthSessionRepository.create:encodeRequest",
366 { sessionId: input.sessionId },
367 ),
368 ),
369 );
370​
371 const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = (
372 input,
373 ) =>
374 sql
375 .withTransaction(
376 revokeActiveSessionsForReplacement(input).pipe(
377 Effect.flatMap((revokedRows) =>
378 createSessionRow(input.session).pipe(
379 Effect.as(revokedRows.map((row) => row.sessionId)),
380 ),
381 ),
382 ),
383 )
384 .pipe(
385 Effect.mapError(
386 toPersistenceSqlOrDecodeError(
387 "AuthSessionRepository.createReplacingActive:query",
388 "AuthSessionRepository.createReplacingActive:encodeRequest",
389 { sessionId: input.session.sessionId },
390 ),
391 ),
392 );
393​
394 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
395 getSessionRowById(input).pipe(
396 Effect.mapError(
397 toPersistenceSqlOrDecodeError(
398 "AuthSessionRepository.getById:query",
399 "AuthSessionRepository.getById:decodeRow",
400 { sessionId: input.sessionId },
401 ),
402 ),
403 Effect.flatMap((rowOption) =>
404 Option.match(rowOption, {
405 onNone: () => Effect.succeed(Option.none()),
406 onSome: (row) =>
407 decodeAuthSessionDbRow(row).pipe(
408 Effect.mapError((cause) =>
409 PersistenceDecodeError.fromSchemaError(
410 "AuthSessionRepository.getById:decodeRow",
411 cause,
412 { sessionId: input.sessionId },
413 ),
414 ),
415 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
416 ),
417 }),
418 ),
419 );
420​
421 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
422 listActiveSessionRows(input).pipe(
423 Effect.mapError(
424 toPersistenceSqlOrDecodeError(
425 "AuthSessionRepository.listActive:query",
426 "AuthSessionRepository.listActive:decodeRows",
427 ),
428 ),
429 Effect.flatMap((rows) =>
430 Effect.forEach(rows, (row) =>
431 decodeAuthSessionDbRow(row).pipe(
432 Effect.mapError((cause) =>
433 PersistenceDecodeError.fromSchemaError(
434 "AuthSessionRepository.listActive:decodeRows",
435 cause,
436 { sessionId: row.sessionId },
437 ),
438 ),
439 Effect.map(toAuthSessionRecord),
440 ),
441 ),
442 ),
443 );
444​
445 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
446 revokeSessionRows(input).pipe(
447 Effect.mapError(
448 toPersistenceSqlOrDecodeError(
449 "AuthSessionRepository.revoke:query",
450 "AuthSessionRepository.revoke:decodeRows",
451 { sessionId: input.sessionId },
452 ),
453 ),
454 Effect.map((rows) => rows.length > 0),
455 );
456​
457 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
458 revokeOtherSessionRows(input).pipe(
459 Effect.mapError(
460 toPersistenceSqlOrDecodeError(
461 "AuthSessionRepository.revokeAllExcept:query",
462 "AuthSessionRepository.revokeAllExcept:decodeRows",
463 { currentSessionId: input.currentSessionId },
464 ),
465 ),
466 Effect.map((rows) => rows.map((row) => row.sessionId)),
467 );
468​
469 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
470 setLastConnectedAtRow(input).pipe(
471 Effect.mapError(
472 toPersistenceSqlOrDecodeError(
473 "AuthSessionRepository.setLastConnectedAt:query",
474 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
475 { sessionId: input.sessionId },
476 ),
477 ),
478 );
479​
480 const setClientConnection: AuthSessionRepository["Service"]["setClientConnection"] = (input) =>
481 setClientConnectionRow(input).pipe(
482 Effect.mapError(
483 toPersistenceSqlOrDecodeError(
484 "AuthSessionRepository.setClientConnection:query",
485 "AuthSessionRepository.setClientConnection:encodeRequest",
486 { sessionId: input.sessionId },
487 ),
488 ),
489 );
490​
491 return {
492 create,
493 createReplacingActive,
494 getById,
495 listActive,
496 revoke,
497 revokeAllExcept,
498 setLastConnectedAt,
499 setClientConnection,
500 } satisfies AuthSessionRepository["Service"];
501});
502​
503export const layer = Layer.effect(AuthSessionRepository, make);