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

AuthPairingLinks.ts

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