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 { AuthEnvironmentScopes } from "@t3tools/contracts";
11
12import {
13 type AuthPairingLinkRepositoryError,
14 PersistenceDecodeError,
15 type PersistenceErrorCorrelation,
16 PersistenceSqlError,
17} from "./Errors.ts";
18
19export const AuthPairingLinkRecord = Schema.Struct({
20 id: Schema.String,
21 credential: Schema.String,
22 method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
23 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
24 subject: Schema.String,
25 label: Schema.NullOr(Schema.String),
26 proofKeyThumbprint: Schema.NullOr(Schema.String),
27 createdAt: Schema.DateTimeUtcFromString,
28 expiresAt: Schema.DateTimeUtcFromString,
29 consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
30 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
31});
32export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
33
34export const CreateAuthPairingLinkInput = Schema.Struct({
35 id: Schema.String,
36 credential: Schema.String,
37 method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
38 scopes: AuthEnvironmentScopes,
39 subject: Schema.String,
40 label: Schema.NullOr(Schema.String),
41 proofKeyThumbprint: Schema.NullOr(Schema.String),
42 createdAt: Schema.DateTimeUtcFromString,
43 expiresAt: Schema.DateTimeUtcFromString,
44});
45export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;
46
47export const ConsumeAuthPairingLinkInput = Schema.Struct({
48 credential: Schema.String,
49 proofKeyThumbprint: Schema.NullOr(Schema.String),
50 requestedScopes: Schema.optionalKey(AuthEnvironmentScopes),
51 consumedAt: Schema.DateTimeUtcFromString,
52 now: Schema.DateTimeUtcFromString,
53});
54export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;
55
56export const ListActiveAuthPairingLinksInput = Schema.Struct({
57 now: Schema.DateTimeUtcFromString,
58});
59export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;
60
61export const RevokeAuthPairingLinkInput = Schema.Struct({
62 id: Schema.String,
63 revokedAt: Schema.DateTimeUtcFromString,
64});
65export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;
66
67export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
68 credential: Schema.String,
69});
70export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
71
72const AuthPairingLinkRawDbRow = Schema.Struct({
73 id: Schema.String,
74 credential: Schema.Unknown,
75 method: Schema.Unknown,
76 scopes: Schema.Unknown,
77 subject: Schema.Unknown,
78 label: Schema.Unknown,
79 proofKeyThumbprint: Schema.Unknown,
80 createdAt: Schema.Unknown,
81 expiresAt: Schema.Unknown,
82 consumedAt: Schema.Unknown,
83 revokedAt: Schema.Unknown,
84});
85
86const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);
87
88export class AuthPairingLinkRepository extends Context.Service<
89 AuthPairingLinkRepository,
90 {
91 readonly create: (
92 input: CreateAuthPairingLinkInput,
93 ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
94 readonly consumeAvailable: (
95 input: ConsumeAuthPairingLinkInput,
96 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
97 readonly listActive: (
98 input: ListActiveAuthPairingLinksInput,
99 ) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
100 readonly revoke: (
101 input: RevokeAuthPairingLinkInput,
102 ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
103 readonly getByCredential: (
104 input: GetAuthPairingLinkByCredentialInput,
105 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
106 }
107>()("t3/persistence/AuthPairingLinks/AuthPairingLinkRepository") {}
108
109function toPersistenceSqlOrDecodeError(
110 sqlOperation: string,
111 decodeOperation: string,
112 correlation?: PersistenceErrorCorrelation,
113) {
114 return (cause: unknown): AuthPairingLinkRepositoryError =>
115 Schema.isSchemaError(cause)
116 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
117 : new PersistenceSqlError({
118 operation: sqlOperation,
119 ...(correlation === undefined ? {} : { correlation }),
120 cause,
121 });
122}
123
124/** @public */
125export const make = Effect.gen(function* () {
126 const sql = yield* SqlClient.SqlClient;
127
128 const createPairingLinkRow = SqlSchema.void({
129 Request: CreateAuthPairingLinkInput,
130 execute: (input) =>
131 sql`
132 INSERT INTO auth_pairing_links (
133 id,
134 credential,
135 method,
136 scopes,
137 subject,
138 label,
139 proof_key_thumbprint,
140 created_at,
141 expires_at,
142 consumed_at,
143 revoked_at
144 )
145 VALUES (
146 ${input.id},
147 ${input.credential},
148 ${input.method},
149 ${JSON.stringify(input.scopes)},
150 ${input.subject},
151 ${input.label},
152 ${input.proofKeyThumbprint},
153 ${input.createdAt},
154 ${input.expiresAt},
155 NULL,
156 NULL
157 )
158 `,
159 });
160
161 const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({
162 Request: ConsumeAuthPairingLinkInput,
163 Result: AuthPairingLinkRawDbRow,
164 execute: ({ credential, proofKeyThumbprint, requestedScopes, consumedAt, now }) =>
165 sql`
166 UPDATE auth_pairing_links
167 SET consumed_at = ${consumedAt}
168 WHERE credential = ${credential}
169 AND revoked_at IS NULL
170 AND consumed_at IS NULL
171 AND expires_at > ${now}
172 AND (
173 proof_key_thumbprint IS NULL
174 OR proof_key_thumbprint = ${proofKeyThumbprint}
175 )
176 AND (${requestedScopes === undefined ? 1 : 0} OR EXISTS (
177 SELECT 1
178 FROM json_each(${JSON.stringify(requestedScopes ?? [])}) AS requested
179 WHERE requested.value IN (
180 SELECT value FROM json_each(auth_pairing_links.scopes)
181 )
182 ))
183 RETURNING
184 id AS "id",
185 credential AS "credential",
186 method AS "method",
187 scopes AS "scopes",
188 subject AS "subject",
189 label AS "label",
190 proof_key_thumbprint AS "proofKeyThumbprint",
191 created_at AS "createdAt",
192 expires_at AS "expiresAt",
193 consumed_at AS "consumedAt",
194 revoked_at AS "revokedAt"
195 `,
196 });
197
198 const listActivePairingLinkRows = SqlSchema.findAll({
199 Request: ListActiveAuthPairingLinksInput,
200 Result: AuthPairingLinkRawDbRow,
201 execute: ({ now }) =>
202 sql`
203 SELECT
204 id AS "id",
205 credential AS "credential",
206 method AS "method",
207 scopes AS "scopes",
208 subject AS "subject",
209 label AS "label",
210 proof_key_thumbprint AS "proofKeyThumbprint",
211 created_at AS "createdAt",
212 expires_at AS "expiresAt",
213 consumed_at AS "consumedAt",
214 revoked_at AS "revokedAt"
215 FROM auth_pairing_links
216 WHERE revoked_at IS NULL
217 AND consumed_at IS NULL
218 AND expires_at > ${now}
219 ORDER BY created_at DESC, id DESC
220 `,
221 });
222
223 const revokePairingLinkRow = SqlSchema.findAll({
224 Request: RevokeAuthPairingLinkInput,
225 Result: Schema.Struct({ id: Schema.String }),
226 execute: ({ id, revokedAt }) =>
227 sql`
228 UPDATE auth_pairing_links
229 SET revoked_at = ${revokedAt}
230 WHERE id = ${id}
231 AND revoked_at IS NULL
232 AND consumed_at IS NULL
233 RETURNING id AS "id"
234 `,
235 });
236
237 const getPairingLinkRowByCredential = SqlSchema.findOneOption({
238 Request: GetAuthPairingLinkByCredentialInput,
239 Result: AuthPairingLinkRawDbRow,
240 execute: ({ credential }) =>
241 sql`
242 SELECT
243 id AS "id",
244 credential AS "credential",
245 method AS "method",
246 scopes AS "scopes",
247 subject AS "subject",
248 label AS "label",
249 proof_key_thumbprint AS "proofKeyThumbprint",
250 created_at AS "createdAt",
251 expires_at AS "expiresAt",
252 consumed_at AS "consumedAt",
253 revoked_at AS "revokedAt"
254 FROM auth_pairing_links
255 WHERE credential = ${credential}
256 `,
257 });
258
259 const create: AuthPairingLinkRepository["Service"]["create"] = (input) =>
260 createPairingLinkRow(input).pipe(
261 Effect.mapError(
262 toPersistenceSqlOrDecodeError(
263 "AuthPairingLinkRepository.create:query",
264 "AuthPairingLinkRepository.create:encodeRequest",
265 { pairingLinkId: input.id },
266 ),
267 ),
268 );
269
270 const consumeAvailable: AuthPairingLinkRepository["Service"]["consumeAvailable"] = (input) =>
271 consumeAvailablePairingLinkRow(input).pipe(
272 Effect.mapError(
273 toPersistenceSqlOrDecodeError(
274 "AuthPairingLinkRepository.consumeAvailable:query",
275 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
276 ),
277 ),
278 Effect.flatMap((rowOption) =>
279 Option.match(rowOption, {
280 onNone: () => Effect.succeedNone,
281 onSome: (row) =>
282 decodeAuthPairingLinkDbRow(row).pipe(
283 Effect.mapError((cause) =>
284 PersistenceDecodeError.fromSchemaError(
285 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
286 cause,
287 { pairingLinkId: row.id },
288 ),
289 ),
290 Effect.asSome,
291 ),
292 }),
293 ),
294 );
295
296 const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
297 listActivePairingLinkRows(input).pipe(
298 NodeSqliteClient.readOnly,
299 Effect.mapError(
300 toPersistenceSqlOrDecodeError(
301 "AuthPairingLinkRepository.listActive:query",
302 "AuthPairingLinkRepository.listActive:decodeRows",
303 ),
304 ),
305 Effect.flatMap((rows) =>
306 Effect.forEach(rows, (row) =>
307 decodeAuthPairingLinkDbRow(row).pipe(
308 Effect.mapError((cause) =>
309 PersistenceDecodeError.fromSchemaError(
310 "AuthPairingLinkRepository.listActive:decodeRows",
311 cause,
312 { pairingLinkId: row.id },
313 ),
314 ),
315 ),
316 ),
317 ),
318 );
319
320 const revoke: AuthPairingLinkRepository["Service"]["revoke"] = (input) =>
321 revokePairingLinkRow(input).pipe(
322 Effect.mapError(
323 toPersistenceSqlOrDecodeError(
324 "AuthPairingLinkRepository.revoke:query",
325 "AuthPairingLinkRepository.revoke:decodeRows",
326 { pairingLinkId: input.id },
327 ),
328 ),
329 Effect.map((rows) => rows.length > 0),
330 );
331
332 const getByCredential: AuthPairingLinkRepository["Service"]["getByCredential"] = (input) =>
333 getPairingLinkRowByCredential(input).pipe(
334 NodeSqliteClient.readOnly,
335 Effect.mapError(
336 toPersistenceSqlOrDecodeError(
337 "AuthPairingLinkRepository.getByCredential:query",
338 "AuthPairingLinkRepository.getByCredential:decodeRow",
339 ),
340 ),
341 Effect.flatMap((rowOption) =>
342 Option.match(rowOption, {
343 onNone: () => Effect.succeedNone,
344 onSome: (row) =>
345 decodeAuthPairingLinkDbRow(row).pipe(
346 Effect.mapError((cause) =>
347 PersistenceDecodeError.fromSchemaError(
348 "AuthPairingLinkRepository.getByCredential:decodeRow",
349 cause,
350 { pairingLinkId: row.id },
351 ),
352 ),
353 Effect.asSome,
354 ),
355 }),
356 ),
357 );
358
359 return {
360 create,
361 consumeAvailable,
362 listActive,
363 revoke,
364 getByCredential,
365 } satisfies AuthPairingLinkRepository["Service"];
366});
367
368export const layer = Layer.effect(AuthPairingLinkRepository, make);