The best way to control Claude Code, Codex and more from any computer or phone

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