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