@yielded/auth-persistence 0.1.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.md +27 -0
  2. package/dist/Adapter.d.mts +30 -0
  3. package/dist/Adapter.mjs +25 -0
  4. package/dist/index.d.mts +7 -0
  5. package/dist/index.mjs +7 -0
  6. package/dist/internal/PasswordPreparedPostconditions.d.mts +22 -0
  7. package/dist/internal/PasswordPreparedPostconditions.mjs +12 -0
  8. package/dist/internal/PasswordPreparedPostconditions.mjs.map +1 -0
  9. package/dist/internal/configuration.d.mts +174 -0
  10. package/dist/internal/configuration.mjs +7 -0
  11. package/dist/internal/configuration.mjs.map +1 -0
  12. package/dist/internal/email-kernel.d.mts +275 -0
  13. package/dist/internal/email-kernel.mjs +487 -0
  14. package/dist/internal/email-kernel.mjs.map +1 -0
  15. package/dist/internal/mapping-error.d.mts +10 -0
  16. package/dist/internal/mapping-error.mjs +30 -0
  17. package/dist/internal/mapping-error.mjs.map +1 -0
  18. package/dist/internal/models/common.d.mts +12 -0
  19. package/dist/internal/models/email-model.d.mts +353 -0
  20. package/dist/internal/models/email-model.mjs +21 -0
  21. package/dist/internal/models/email-model.mjs.map +1 -0
  22. package/dist/internal/models/passkey-model.d.mts +266 -0
  23. package/dist/internal/models/passkey-model.mjs +34 -0
  24. package/dist/internal/models/passkey-model.mjs.map +1 -0
  25. package/dist/internal/models/passkey-registration-ceremony-model.d.mts +49 -0
  26. package/dist/internal/models/passkey-registration-ceremony-model.mjs +18 -0
  27. package/dist/internal/models/passkey-registration-ceremony-model.mjs.map +1 -0
  28. package/dist/internal/models/passkey-write-model.d.mts +189 -0
  29. package/dist/internal/models/passkey-write-model.mjs +13 -0
  30. package/dist/internal/models/passkey-write-model.mjs.map +1 -0
  31. package/dist/internal/models/password-model.d.mts +328 -0
  32. package/dist/internal/models/password-model.mjs +23 -0
  33. package/dist/internal/models/password-model.mjs.map +1 -0
  34. package/dist/internal/models/proof-model.d.mts +285 -0
  35. package/dist/internal/models/proof-model.mjs +17 -0
  36. package/dist/internal/models/proof-model.mjs.map +1 -0
  37. package/dist/internal/models/session-model.d.mts +199 -0
  38. package/dist/internal/models/session-model.mjs +20 -0
  39. package/dist/internal/models/session-model.mjs.map +1 -0
  40. package/dist/internal/models/step-up-model.d.mts +66 -0
  41. package/dist/internal/models/step-up-model.mjs +9 -0
  42. package/dist/internal/models/step-up-model.mjs.map +1 -0
  43. package/dist/internal/oauth-app.d.mts +11 -0
  44. package/dist/internal/oauth-app.mjs +57 -0
  45. package/dist/internal/oauth-app.mjs.map +1 -0
  46. package/dist/internal/oauth-server.d.mts +10 -0
  47. package/dist/internal/oauth-server.mjs +66 -0
  48. package/dist/internal/oauth-server.mjs.map +1 -0
  49. package/dist/internal/passkey/admission.d.mts +6 -0
  50. package/dist/internal/passkey/admission.mjs +216 -0
  51. package/dist/internal/passkey/admission.mjs.map +1 -0
  52. package/dist/internal/passkey/credentials.d.mts +14 -0
  53. package/dist/internal/passkey/credentials.mjs +249 -0
  54. package/dist/internal/passkey/credentials.mjs.map +1 -0
  55. package/dist/internal/passkey/enrollment.mjs +138 -0
  56. package/dist/internal/passkey/enrollment.mjs.map +1 -0
  57. package/dist/internal/passkey/flow.d.mts +21 -0
  58. package/dist/internal/passkey/flow.mjs +452 -0
  59. package/dist/internal/passkey/flow.mjs.map +1 -0
  60. package/dist/internal/passkey/management.mjs +231 -0
  61. package/dist/internal/passkey/management.mjs.map +1 -0
  62. package/dist/internal/passkey/registration-ceremony.d.mts +9 -0
  63. package/dist/internal/passkey/registration-ceremony.mjs +129 -0
  64. package/dist/internal/passkey/registration-ceremony.mjs.map +1 -0
  65. package/dist/internal/passkey/registration-custody.d.mts +2 -0
  66. package/dist/internal/passkey/registration-custody.mjs +52 -0
  67. package/dist/internal/passkey/registration-custody.mjs.map +1 -0
  68. package/dist/internal/passkey/registration-write.mjs +211 -0
  69. package/dist/internal/passkey/registration-write.mjs.map +1 -0
  70. package/dist/internal/passkey/state.d.mts +10 -0
  71. package/dist/internal/passkey/state.mjs +234 -0
  72. package/dist/internal/passkey/state.mjs.map +1 -0
  73. package/dist/internal/passkey/target.d.mts +19 -0
  74. package/dist/internal/passkey/target.mjs +190 -0
  75. package/dist/internal/passkey/target.mjs.map +1 -0
  76. package/dist/internal/passkey/write-state.d.mts +17 -0
  77. package/dist/internal/passkey/write-state.mjs +345 -0
  78. package/dist/internal/passkey/write-state.mjs.map +1 -0
  79. package/dist/internal/passkey/write-target.mjs +192 -0
  80. package/dist/internal/passkey/write-target.mjs.map +1 -0
  81. package/dist/internal/passkey-kernel.d.mts +5592 -0
  82. package/dist/internal/passkey-kernel.mjs +49 -0
  83. package/dist/internal/passkey-kernel.mjs.map +1 -0
  84. package/dist/internal/passkeys.d.mts +7 -0
  85. package/dist/internal/passkeys.mjs +368 -0
  86. package/dist/internal/passkeys.mjs.map +1 -0
  87. package/dist/internal/password-kernel.d.mts +290 -0
  88. package/dist/internal/password-kernel.mjs +704 -0
  89. package/dist/internal/password-kernel.mjs.map +1 -0
  90. package/dist/internal/persistence.d.mts +25 -0
  91. package/dist/internal/persistence.mjs +291 -0
  92. package/dist/internal/persistence.mjs.map +1 -0
  93. package/dist/internal/phone-kernel.d.mts +162 -0
  94. package/dist/internal/phone-kernel.mjs +434 -0
  95. package/dist/internal/phone-kernel.mjs.map +1 -0
  96. package/dist/internal/proof-kernel.d.mts +93 -0
  97. package/dist/internal/proof-kernel.mjs +619 -0
  98. package/dist/internal/proof-kernel.mjs.map +1 -0
  99. package/dist/internal/query-operations.d.mts +61 -0
  100. package/dist/internal/registration-contract.d.mts +16 -0
  101. package/dist/internal/registration.mjs +66 -0
  102. package/dist/internal/registration.mjs.map +1 -0
  103. package/dist/internal/session-kernel.d.mts +48 -0
  104. package/dist/internal/session-kernel.mjs +737 -0
  105. package/dist/internal/session-kernel.mjs.map +1 -0
  106. package/dist/internal/sql-persistence.d.mts +10 -0
  107. package/dist/internal/sql-persistence.mjs +37 -0
  108. package/dist/internal/sql-persistence.mjs.map +1 -0
  109. package/dist/internal/sql-query.mjs +207 -0
  110. package/dist/internal/sql-query.mjs.map +1 -0
  111. package/dist/internal/sql-table.d.mts +36 -0
  112. package/dist/internal/sql-table.mjs +81 -0
  113. package/dist/internal/sql-table.mjs.map +1 -0
  114. package/dist/internal/standalone.d.mts +9 -0
  115. package/dist/internal/standalone.mjs +13 -0
  116. package/dist/internal/standalone.mjs.map +1 -0
  117. package/dist/internal/step-up-state.d.mts +49 -0
  118. package/dist/internal/step-up-state.mjs +32 -0
  119. package/dist/internal/step-up-state.mjs.map +1 -0
  120. package/dist/internal/storage-mapping.mjs +686 -0
  121. package/dist/internal/storage-mapping.mjs.map +1 -0
  122. package/dist/internal/storage-tables.d.mts +913 -0
  123. package/dist/internal/storage-tables.mjs +387 -0
  124. package/dist/internal/storage-tables.mjs.map +1 -0
  125. package/dist/internal/storage-validation.mjs +58 -0
  126. package/dist/internal/storage-validation.mjs.map +1 -0
  127. package/dist/internal/transaction-execution-kernel.d.mts +38 -0
  128. package/dist/internal/transaction-execution-kernel.mjs +116 -0
  129. package/dist/internal/transaction-execution-kernel.mjs.map +1 -0
  130. package/dist/internal/transaction-kernel.d.mts +77 -0
  131. package/dist/internal/transaction-kernel.mjs +260 -0
  132. package/dist/internal/transaction-kernel.mjs.map +1 -0
  133. package/package.json +1 -0
  134. package/src/Adapter.ts +291 -0
  135. package/src/index.ts +6 -0
  136. package/src/internal/PasswordPreparedPostconditions.ts +30 -0
  137. package/src/internal/configuration.ts +282 -0
  138. package/src/internal/email-kernel.ts +1535 -0
  139. package/src/internal/mapping-error.ts +36 -0
  140. package/src/internal/models/common.ts +11 -0
  141. package/src/internal/models/email-model.ts +559 -0
  142. package/src/internal/models/passkey-model.ts +390 -0
  143. package/src/internal/models/passkey-registration-ceremony-model.ts +72 -0
  144. package/src/internal/models/passkey-write-model.ts +297 -0
  145. package/src/internal/models/password-model.ts +513 -0
  146. package/src/internal/models/proof-model.ts +424 -0
  147. package/src/internal/models/session-model.ts +375 -0
  148. package/src/internal/models/step-up-model.ts +135 -0
  149. package/src/internal/oauth-app.ts +82 -0
  150. package/src/internal/oauth-server.ts +89 -0
  151. package/src/internal/passkey/admission.ts +361 -0
  152. package/src/internal/passkey/credentials.ts +511 -0
  153. package/src/internal/passkey/enrollment.ts +326 -0
  154. package/src/internal/passkey/flow.ts +1062 -0
  155. package/src/internal/passkey/management.ts +421 -0
  156. package/src/internal/passkey/registration-ceremony.ts +283 -0
  157. package/src/internal/passkey/registration-custody.ts +91 -0
  158. package/src/internal/passkey/registration-write.ts +426 -0
  159. package/src/internal/passkey/state.ts +353 -0
  160. package/src/internal/passkey/target.ts +586 -0
  161. package/src/internal/passkey/write-state.ts +681 -0
  162. package/src/internal/passkey/write-target.ts +452 -0
  163. package/src/internal/passkey-kernel.ts +104 -0
  164. package/src/internal/passkeys.ts +606 -0
  165. package/src/internal/password-kernel.ts +2124 -0
  166. package/src/internal/persistence.ts +588 -0
  167. package/src/internal/phone-kernel.ts +846 -0
  168. package/src/internal/proof-kernel.ts +1954 -0
  169. package/src/internal/query-operations.ts +81 -0
  170. package/src/internal/registration-contract.ts +22 -0
  171. package/src/internal/registration.ts +161 -0
  172. package/src/internal/session-kernel.ts +2217 -0
  173. package/src/internal/sql-persistence.ts +45 -0
  174. package/src/internal/sql-query.ts +298 -0
  175. package/src/internal/sql-table.ts +104 -0
  176. package/src/internal/standalone.ts +30 -0
  177. package/src/internal/step-up-state.ts +139 -0
  178. package/src/internal/storage-mapping.ts +708 -0
  179. package/src/internal/storage-tables.ts +408 -0
  180. package/src/internal/storage-validation.ts +117 -0
  181. package/src/internal/transaction-execution-kernel.ts +313 -0
  182. package/src/internal/transaction-kernel.ts +593 -0
@@ -0,0 +1,408 @@
1
+ import { Schema } from "effect";
2
+
3
+ export const StorageColumn = Schema.Struct({
4
+ name: Schema.NonEmptyString,
5
+ type: Schema.Literals(["text", "integer", "boolean"]),
6
+ nullable: Schema.optionalKey(Schema.Boolean),
7
+ });
8
+
9
+ export const StorageTable = Schema.Struct({
10
+ name: Schema.NonEmptyString,
11
+ schema: Schema.optionalKey(Schema.NonEmptyString),
12
+ columns: Schema.Record(Schema.String, StorageColumn),
13
+ unique: Schema.Array(Schema.Array(Schema.String)),
14
+ });
15
+
16
+ export type StorageTable = typeof StorageTable.Type;
17
+
18
+ const text = { type: "text" as const };
19
+ const integer = { type: "integer" as const };
20
+ const boolean = { type: "boolean" as const };
21
+ const optionalText = { ...text, nullable: true };
22
+ const optionalInteger = { ...integer, nullable: true };
23
+
24
+ const spec = <C extends Readonly<Record<string, Omit<typeof StorageColumn.Type, "name">>>>(
25
+ columns: C,
26
+ unique: ReadonlyArray<ReadonlyArray<Extract<keyof C, string>>>,
27
+ ) => ({ columns, unique });
28
+
29
+ /** Logical roles are independent of table names and migration ownership. */
30
+ export const storageTables = {
31
+ subjects: spec({ id: text, active: boolean, securityRevision: text }, [["id"]]),
32
+ identifiers: spec(
33
+ {
34
+ namespace: text,
35
+ value: text,
36
+ subjectId: text,
37
+ revision: text,
38
+ verifiedAt: optionalInteger,
39
+ active: boolean,
40
+ },
41
+ [["namespace", "value"]],
42
+ ),
43
+ credentials: spec({ credentialId: text, subjectId: text, revision: text, active: boolean }, [
44
+ ["credentialId"],
45
+ ]),
46
+ passwords: spec(
47
+ {
48
+ moduleId: text,
49
+ subjectId: text,
50
+ credentialId: text,
51
+ credentialRevision: text,
52
+ verifierVersion: text,
53
+ verifier: text,
54
+ normalization: text,
55
+ },
56
+ [
57
+ ["moduleId", "subjectId"],
58
+ ["moduleId", "credentialId"],
59
+ ],
60
+ ),
61
+ passwordAttempts: spec(
62
+ {
63
+ moduleId: text,
64
+ action: text,
65
+ attemptId: text,
66
+ identifierNamespace: text,
67
+ identifierValue: text,
68
+ subjectId: optionalText,
69
+ credentialId: optionalText,
70
+ securityRevision: optionalText,
71
+ credentialRevision: optionalText,
72
+ verifierVersion: optionalText,
73
+ identifierBindingRevision: optionalText,
74
+ admittedAt: integer,
75
+ deadline: integer,
76
+ retentionUntil: integer,
77
+ state: text,
78
+ },
79
+ [["moduleId", "attemptId"]],
80
+ ),
81
+ passwordScopes: spec({ moduleId: text, action: text, scopeKind: text, scopeKey: text }, [
82
+ ["moduleId", "action", "scopeKind", "scopeKey"],
83
+ ]),
84
+ passwordCharges: spec(
85
+ {
86
+ moduleId: text,
87
+ action: text,
88
+ scopeKind: text,
89
+ scopeKey: text,
90
+ attemptId: text,
91
+ occurredAt: integer,
92
+ retentionUntil: integer,
93
+ },
94
+ [["moduleId", "action", "scopeKind", "scopeKey", "attemptId"]],
95
+ ),
96
+ passwordCommands: spec(
97
+ {
98
+ moduleId: text,
99
+ commandId: text,
100
+ action: text,
101
+ bindingDigest: text,
102
+ decision: text,
103
+ retentionUntil: integer,
104
+ },
105
+ [["moduleId", "commandId"]],
106
+ ),
107
+ passwordRegistrations: spec({ moduleId: text, requestId: text }, [["moduleId", "requestId"]]),
108
+ emailCredentials: spec(
109
+ {
110
+ moduleId: text,
111
+ subjectId: text,
112
+ credentialId: text,
113
+ identifierNamespace: text,
114
+ identifierValue: text,
115
+ credentialRevision: text,
116
+ active: boolean,
117
+ },
118
+ [
119
+ ["moduleId", "credentialId"],
120
+ ["moduleId", "identifierNamespace", "identifierValue"],
121
+ ],
122
+ ),
123
+ emailCommands: spec(
124
+ { moduleId: text, commandId: text, action: text, bindingDigest: text, retentionUntil: integer },
125
+ [["moduleId", "commandId"]],
126
+ ),
127
+ phoneState: spec({ scope: text, state: text, version: text }, [["scope"]]),
128
+ passkeyCredentials: spec(
129
+ {
130
+ credentialId: text,
131
+ subjectId: text,
132
+ rpId: text,
133
+ protocolCredentialId: text,
134
+ credentialKey: text,
135
+ handleKey: text,
136
+ userHandle: text,
137
+ publicKey: text,
138
+ algorithm: integer,
139
+ profile: text,
140
+ credentialRevision: text,
141
+ active: boolean,
142
+ primarySignIn: boolean,
143
+ enrollmentUserVerified: boolean,
144
+ backupEligible: boolean,
145
+ backupState: boolean,
146
+ counter: integer,
147
+ maximumCounter: integer,
148
+ name: text,
149
+ createdAt: integer,
150
+ lastUsedAt: optionalInteger,
151
+ },
152
+ [["credentialId"], ["credentialKey"]],
153
+ ),
154
+ passkeyOwnership: spec(
155
+ {
156
+ credentialKey: text,
157
+ rpId: text,
158
+ protocolCredentialId: text,
159
+ subjectId: optionalText,
160
+ credentialId: optionalText,
161
+ state: text,
162
+ version: text,
163
+ reservationId: optionalText,
164
+ },
165
+ [["credentialKey"]],
166
+ ),
167
+ passkeyHandles: spec(
168
+ {
169
+ handleKey: text,
170
+ rpId: text,
171
+ userHandle: text,
172
+ subjectId: optionalText,
173
+ state: text,
174
+ version: text,
175
+ reservationId: optionalText,
176
+ },
177
+ [["handleKey"], ["rpId", "subjectId"]],
178
+ ),
179
+ passkeyModules: spec(
180
+ {
181
+ moduleId: text,
182
+ active: boolean,
183
+ policyRevision: text,
184
+ policy: text,
185
+ },
186
+ [["moduleId"]],
187
+ ),
188
+ passkeyFlows: spec(
189
+ {
190
+ moduleId: text,
191
+ flowId: text,
192
+ commandId: text,
193
+ purpose: text,
194
+ state: text,
195
+ version: text,
196
+ generation: integer,
197
+ snapshot: text,
198
+ policySnapshot: text,
199
+ requestBindingVerifier: text,
200
+ requestBindingExpiresAt: integer,
201
+ issuedAt: integer,
202
+ expiresAt: integer,
203
+ retentionUntil: integer,
204
+ claimId: optionalText,
205
+ claimedAt: optionalInteger,
206
+ claimExpiresAt: optionalInteger,
207
+ credentialSnapshot: optionalText,
208
+ subjectScope: optionalText,
209
+ targetScope: optionalText,
210
+ },
211
+ [
212
+ ["moduleId", "flowId"],
213
+ ["moduleId", "commandId"],
214
+ ],
215
+ ),
216
+ passkeyAdmissions: spec(
217
+ {
218
+ authorityScope: text,
219
+ moduleId: text,
220
+ version: text,
221
+ ownerMarker: text,
222
+ admittedAt: optionalInteger,
223
+ },
224
+ [["authorityScope", "moduleId"]],
225
+ ),
226
+ passkeyCharges: spec(
227
+ {
228
+ moduleId: text,
229
+ flowId: text,
230
+ purpose: text,
231
+ kind: text,
232
+ scope: text,
233
+ originalWindowMillis: integer,
234
+ admittedAt: optionalInteger,
235
+ retainUntil: optionalInteger,
236
+ version: text,
237
+ ownerMarker: text,
238
+ },
239
+ [["moduleId", "flowId", "kind"]],
240
+ ),
241
+ passkeyCommands: spec(
242
+ {
243
+ moduleId: text,
244
+ commandId: text,
245
+ subjectId: text,
246
+ credentialId: text,
247
+ intent: text,
248
+ decision: text,
249
+ retentionUntil: integer,
250
+ version: text,
251
+ },
252
+ [["moduleId", "commandId"]],
253
+ ),
254
+ proofRequests: spec(
255
+ {
256
+ moduleId: text,
257
+ requestId: text,
258
+ fingerprint: text,
259
+ proofId: text,
260
+ purpose: text,
261
+ keyId: text,
262
+ createdAt: integer,
263
+ retentionUntil: integer,
264
+ receipt: text,
265
+ },
266
+ [["moduleId", "requestId"]],
267
+ ),
268
+ proofSeries: spec(
269
+ {
270
+ moduleId: text,
271
+ purpose: text,
272
+ scopeKey: text,
273
+ activeProofId: optionalText,
274
+ lastIssueAt: optionalInteger,
275
+ version: text,
276
+ },
277
+ [["moduleId", "purpose", "scopeKey"]],
278
+ ),
279
+ proofGenerations: spec(
280
+ {
281
+ moduleId: text,
282
+ purpose: text,
283
+ proofId: text,
284
+ requestId: text,
285
+ seriesKey: text,
286
+ deliveryId: text,
287
+ binding: text,
288
+ verifierKeyId: text,
289
+ verifierDigest: text,
290
+ issuedAt: integer,
291
+ expiresAt: integer,
292
+ version: text,
293
+ state: text,
294
+ sendCount: integer,
295
+ deliveryState: text,
296
+ claimVersion: optionalText,
297
+ claimDeadline: optionalInteger,
298
+ retryAt: optionalInteger,
299
+ deliveryRetryMillis: integer,
300
+ retentionUntil: integer,
301
+ fingerprint: text,
302
+ },
303
+ [
304
+ ["moduleId", "proofId"],
305
+ ["moduleId", "deliveryId"],
306
+ ],
307
+ ),
308
+ proofContinuations: spec(
309
+ {
310
+ moduleId: text,
311
+ purpose: text,
312
+ continuationId: text,
313
+ digest: text,
314
+ proofId: text,
315
+ seriesKey: text,
316
+ binding: text,
317
+ expiresAt: integer,
318
+ consumed: boolean,
319
+ version: text,
320
+ retentionUntil: integer,
321
+ },
322
+ [
323
+ ["moduleId", "continuationId"],
324
+ ["moduleId", "digest"],
325
+ ],
326
+ ),
327
+ proofScopes: spec(
328
+ { moduleId: text, purpose: text, action: text, scopeKind: text, scopeKey: text },
329
+ [["moduleId", "purpose", "action", "scopeKind", "scopeKey"]],
330
+ ),
331
+ proofAbuse: spec(
332
+ {
333
+ moduleId: text,
334
+ purpose: text,
335
+ action: text,
336
+ scopeKind: text,
337
+ scopeKey: text,
338
+ commandId: text,
339
+ occurredAt: integer,
340
+ retentionUntil: integer,
341
+ },
342
+ [["moduleId", "action", "scopeKind", "scopeKey", "commandId"]],
343
+ ),
344
+ proofFailures: spec(
345
+ {
346
+ moduleId: text,
347
+ purpose: text,
348
+ seriesKey: text,
349
+ commandId: text,
350
+ occurredAt: integer,
351
+ retentionUntil: integer,
352
+ },
353
+ [["moduleId", "seriesKey", "commandId"]],
354
+ ),
355
+ proofCommands: spec(
356
+ { moduleId: text, commandId: text, kind: text, decision: text, retentionUntil: integer },
357
+ [["moduleId", "commandId"]],
358
+ ),
359
+ sessions: spec(
360
+ {
361
+ sessionId: text,
362
+ subjectId: text,
363
+ digest: text,
364
+ version: text,
365
+ securityRevision: text,
366
+ issuedAt: integer,
367
+ expiresAt: integer,
368
+ absoluteExpiresAt: integer,
369
+ record: text,
370
+ },
371
+ [["sessionId"], ["digest"]],
372
+ ),
373
+ sessionFlows: spec(
374
+ {
375
+ flowId: text,
376
+ subjectId: text,
377
+ state: text,
378
+ pendingDigest: optionalText,
379
+ dedupUntil: integer,
380
+ },
381
+ [["flowId"]],
382
+ ),
383
+ } as const;
384
+
385
+ export type StorageRole = keyof typeof storageTables;
386
+
387
+ export const tableDefinition = (
388
+ role: StorageRole,
389
+ name: string,
390
+ subjectType: "text" | "integer" = "text",
391
+ ): StorageTable => {
392
+ const table = storageTables[role];
393
+
394
+ return {
395
+ name,
396
+ columns: Object.fromEntries(
397
+ Object.entries(table.columns).map(([key, column]) => [
398
+ key,
399
+ {
400
+ ...column,
401
+ name: key.replace(/[A-Z]/g, (letter) => "_" + letter.toLowerCase()),
402
+ ...(key === "subjectId" ? { type: subjectType } : {}),
403
+ },
404
+ ]),
405
+ ),
406
+ unique: table.unique,
407
+ };
408
+ };
@@ -0,0 +1,117 @@
1
+ import { Effect, Schema } from "effect";
2
+ import type { SqlClient } from "effect/unstable/sql/SqlClient";
3
+
4
+ import { PersistenceConfigurationError } from "./configuration";
5
+ import type { StorageTable } from "./storage-tables";
6
+
7
+ const Column = Schema.Struct({ name: Schema.String, pk: Schema.Int });
8
+ const Index = Schema.Struct({ name: Schema.String, unique: Schema.Int, partial: Schema.Int });
9
+ const IndexColumn = Schema.Struct({ name: Schema.NullOr(Schema.String) });
10
+ const PgColumns = Schema.Array(Schema.Struct({ name: Schema.String }));
11
+ const PgKeys = Schema.Array(Schema.Struct({ columns: Schema.Array(Schema.String) }));
12
+ const quote = (value: string) => '"' + value.replaceAll('"', '""') + '"';
13
+
14
+ export const qualifiedTableName = (table: Pick<StorageTable, "name" | "schema">) =>
15
+ (table.schema === undefined ? "" : quote(table.schema) + ".") + quote(table.name);
16
+
17
+ /** Validate physical uniqueness before the first authentication operation. A
18
+ * partial or expression index cannot establish these unconditional guarantees. */
19
+ export const validateStorage = (
20
+ client: SqlClient,
21
+ dialect: "pg" | "sqlite",
22
+ table: StorageTable,
23
+ required: ReadonlyArray<ReadonlyArray<string>>,
24
+ ) =>
25
+ Effect.gen(function* () {
26
+ const physicalKeys: ReadonlyArray<ReadonlyArray<string>> = yield* dialect === "sqlite"
27
+ ? Effect.gen(function* () {
28
+ if (table.schema !== undefined && table.schema !== "main")
29
+ return yield* PersistenceConfigurationError.make({
30
+ reason: "SQLite storage must belong to the main database",
31
+ });
32
+
33
+ const columns = yield* client`select name, pk from pragma_table_info(${table.name})`.pipe(
34
+ Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Column))),
35
+ );
36
+
37
+ for (const column of Object.values(table.columns)) {
38
+ if (!columns.some((actual) => actual.name === column.name))
39
+ return yield* PersistenceConfigurationError.make({
40
+ reason: `Missing SQL column ${table.name}.${column.name}`,
41
+ });
42
+ }
43
+ const keys: string[][] = [];
44
+ const primary = columns.filter((column) => column.pk > 0).sort((a, b) => a.pk - b.pk);
45
+
46
+ if (primary.length > 0) keys.push(primary.map((column) => column.name));
47
+
48
+ const indexes =
49
+ yield* client`select name, "unique", partial from pragma_index_list(${table.name})`.pipe(
50
+ Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Index))),
51
+ );
52
+
53
+ for (const index of indexes) {
54
+ if (index.unique !== 1 || index.partial !== 0) continue;
55
+
56
+ const columns = yield* client`select name from pragma_index_info(${index.name})`.pipe(
57
+ Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(IndexColumn))),
58
+ );
59
+
60
+ if (columns.every((column) => column.name !== null))
61
+ keys.push(columns.flatMap((column) => (column.name === null ? [] : [column.name])));
62
+ }
63
+
64
+ return keys;
65
+ })
66
+ : Effect.gen(function* () {
67
+ const relation = qualifiedTableName(table);
68
+
69
+ const columns =
70
+ yield* client`select attname as name from pg_attribute where attrelid = to_regclass(${relation}) and attnum > 0 and not attisdropped`.pipe(
71
+ Effect.flatMap(Schema.decodeUnknownEffect(PgColumns)),
72
+ );
73
+
74
+ for (const column of Object.values(table.columns)) {
75
+ if (!columns.some((actual) => actual.name === column.name))
76
+ return yield* PersistenceConfigurationError.make({
77
+ reason: `Missing SQL column ${relation}.${column.name}`,
78
+ });
79
+ }
80
+
81
+ const indexes = yield* client`
82
+ select array_agg(a.attname order by k.ordinality) as columns
83
+ from pg_index i
84
+ cross join lateral unnest(i.indkey) with ordinality as k(attnum, ordinality)
85
+ join pg_attribute a on a.attrelid = i.indrelid and a.attnum = k.attnum
86
+ where i.indrelid = to_regclass(${relation}) and i.indisunique and i.indisvalid
87
+ and i.indimmediate and i.indpred is null and i.indexprs is null
88
+ and k.ordinality <= i.indnkeyatts
89
+ group by i.indexrelid
90
+ `.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PgKeys)));
91
+
92
+ return indexes.map((index) => index.columns);
93
+ });
94
+
95
+ for (const keys of required) {
96
+ const columns = keys.map((key) => table.columns[key]?.name);
97
+
98
+ if (
99
+ columns.some((column) => column === undefined) ||
100
+ !physicalKeys.some(
101
+ (actual) =>
102
+ actual.length === columns.length && actual.every((column) => columns.includes(column)),
103
+ )
104
+ )
105
+ return yield* PersistenceConfigurationError.make({
106
+ reason: `Missing unique key on ${table.name} (${keys.join(", ")})`,
107
+ });
108
+ }
109
+ }).pipe(
110
+ Effect.mapError((error) =>
111
+ Schema.is(PersistenceConfigurationError)(error)
112
+ ? error
113
+ : PersistenceConfigurationError.make({
114
+ reason: `Cannot validate SQL storage for ${table.name}`,
115
+ }),
116
+ ),
117
+ );