@yielded/auth-persistence 0.1.0-beta.23 → 0.1.0-beta.24

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 (175) hide show
  1. package/README.md +11 -0
  2. package/dist/Adapter.d.mts +12 -6
  3. package/dist/Adapter.mjs +8 -3
  4. package/dist/OAuthPersistence.d.mts +87 -0
  5. package/dist/OAuthPersistence.mjs +125 -0
  6. package/dist/OAuthPersistence.mjs.map +1 -0
  7. package/dist/_virtual/_rolldown/runtime.mjs +13 -0
  8. package/dist/index.d.mts +3 -1
  9. package/dist/index.mjs +3 -1
  10. package/dist/internal/configuration.d.mts +1 -1
  11. package/dist/internal/configuration.mjs.map +1 -1
  12. package/dist/internal/models/oauth-connected-model.d.mts +294 -0
  13. package/dist/internal/models/oauth-connected-model.mjs +22 -0
  14. package/dist/internal/models/oauth-connected-model.mjs.map +1 -0
  15. package/dist/internal/models/oauth-model.d.mts +467 -0
  16. package/dist/internal/models/oauth-model.mjs +49 -0
  17. package/dist/internal/models/oauth-model.mjs.map +1 -0
  18. package/dist/internal/models/password-model.d.mts +4 -47
  19. package/dist/internal/models/password-model.mjs +0 -1
  20. package/dist/internal/models/password-model.mjs.map +1 -1
  21. package/dist/internal/native-sql-table.d.mts +4 -0
  22. package/dist/internal/native-sql-table.mjs +7 -0
  23. package/dist/internal/native-sql-table.mjs.map +1 -1
  24. package/dist/internal/oauth/accounts.d.mts +8 -0
  25. package/dist/internal/oauth/accounts.mjs +379 -0
  26. package/dist/internal/oauth/accounts.mjs.map +1 -0
  27. package/dist/internal/oauth/connected-access.d.mts +9 -0
  28. package/dist/internal/oauth/connected-access.mjs +229 -0
  29. package/dist/internal/oauth/connected-access.mjs.map +1 -0
  30. package/dist/internal/oauth/connected-collection.d.mts +7 -0
  31. package/dist/internal/oauth/connected-collection.mjs +214 -0
  32. package/dist/internal/oauth/connected-collection.mjs.map +1 -0
  33. package/dist/internal/oauth/connected-custody.d.mts +6 -0
  34. package/dist/internal/oauth/connected-custody.mjs +165 -0
  35. package/dist/internal/oauth/connected-custody.mjs.map +1 -0
  36. package/dist/internal/oauth/connected-flow.d.mts +7 -0
  37. package/dist/internal/oauth/connected-flow.mjs +324 -0
  38. package/dist/internal/oauth/connected-flow.mjs.map +1 -0
  39. package/dist/internal/oauth/connected-input.mjs +122 -0
  40. package/dist/internal/oauth/connected-input.mjs.map +1 -0
  41. package/dist/internal/oauth/connected-keys.d.mts +2 -0
  42. package/dist/internal/oauth/connected-keys.mjs +22 -0
  43. package/dist/internal/oauth/connected-keys.mjs.map +1 -0
  44. package/dist/internal/oauth/connected-maintenance.d.mts +9 -0
  45. package/dist/internal/oauth/connected-maintenance.mjs +226 -0
  46. package/dist/internal/oauth/connected-maintenance.mjs.map +1 -0
  47. package/dist/internal/oauth/connected-management.d.mts +9 -0
  48. package/dist/internal/oauth/connected-management.mjs +243 -0
  49. package/dist/internal/oauth/connected-management.mjs.map +1 -0
  50. package/dist/internal/oauth/connected-reference.mjs +63 -0
  51. package/dist/internal/oauth/connected-reference.mjs.map +1 -0
  52. package/dist/internal/oauth/connected-settlement.d.mts +8 -0
  53. package/dist/internal/oauth/connected-settlement.mjs +141 -0
  54. package/dist/internal/oauth/connected-settlement.mjs.map +1 -0
  55. package/dist/internal/oauth/connected-sign-in.d.mts +10 -0
  56. package/dist/internal/oauth/connected-sign-in.mjs +281 -0
  57. package/dist/internal/oauth/connected-sign-in.mjs.map +1 -0
  58. package/dist/internal/oauth/connected-state.d.mts +14 -0
  59. package/dist/internal/oauth/connected-state.mjs +469 -0
  60. package/dist/internal/oauth/connected-state.mjs.map +1 -0
  61. package/dist/internal/oauth/connected-target.d.mts +21 -0
  62. package/dist/internal/oauth/connected-target.mjs +117 -0
  63. package/dist/internal/oauth/connected-target.mjs.map +1 -0
  64. package/dist/internal/oauth/flow.d.mts +5 -0
  65. package/dist/internal/oauth/flow.mjs +279 -0
  66. package/dist/internal/oauth/flow.mjs.map +1 -0
  67. package/dist/internal/oauth/input.mjs +127 -0
  68. package/dist/internal/oauth/input.mjs.map +1 -0
  69. package/dist/internal/oauth/owner.d.mts +10 -0
  70. package/dist/internal/oauth/owner.mjs +10 -0
  71. package/dist/internal/oauth/owner.mjs.map +1 -0
  72. package/dist/internal/oauth/query-compiler.d.mts +7 -0
  73. package/dist/internal/oauth/query-compiler.mjs +9 -0
  74. package/dist/internal/oauth/query-compiler.mjs.map +1 -0
  75. package/dist/internal/oauth/registration.d.mts +7 -0
  76. package/dist/internal/oauth/registration.mjs +393 -0
  77. package/dist/internal/oauth/registration.mjs.map +1 -0
  78. package/dist/internal/oauth/state.mjs +107 -0
  79. package/dist/internal/oauth/state.mjs.map +1 -0
  80. package/dist/internal/oauth/target.d.mts +31 -0
  81. package/dist/internal/oauth/target.mjs +273 -0
  82. package/dist/internal/oauth/target.mjs.map +1 -0
  83. package/dist/internal/oauth-kernel.d.mts +1423 -0
  84. package/dist/internal/oauth-kernel.mjs +187 -0
  85. package/dist/internal/oauth-kernel.mjs.map +1 -0
  86. package/dist/internal/oauth-proxy.d.mts +31 -0
  87. package/dist/internal/oauth-proxy.mjs +129 -0
  88. package/dist/internal/oauth-proxy.mjs.map +1 -0
  89. package/dist/internal/passkey-kernel.d.mts +5 -5
  90. package/dist/internal/{password-attempts.d.mts → password-credentials.d.mts} +3 -4
  91. package/dist/internal/password-credentials.mjs +121 -0
  92. package/dist/internal/password-credentials.mjs.map +1 -0
  93. package/dist/internal/password-kernel.d.mts +8 -24
  94. package/dist/internal/password-kernel.mjs +4 -42
  95. package/dist/internal/password-kernel.mjs.map +1 -1
  96. package/dist/internal/persistence.d.mts +1 -1
  97. package/dist/internal/persistence.mjs +2 -2
  98. package/dist/internal/persistence.mjs.map +1 -1
  99. package/dist/internal/query-operations.d.mts +2 -0
  100. package/dist/internal/session-kernel.d.mts +2 -2
  101. package/dist/internal/session-kernel.mjs +74 -18
  102. package/dist/internal/session-kernel.mjs.map +1 -1
  103. package/dist/internal/sql-oauth-connected-model.d.mts +29 -0
  104. package/dist/internal/sql-oauth-connected-model.mjs +7 -0
  105. package/dist/internal/sql-oauth-connected-model.mjs.map +1 -0
  106. package/dist/internal/sql-oauth-model.d.mts +60 -0
  107. package/dist/internal/sql-oauth-model.mjs +10 -0
  108. package/dist/internal/sql-oauth-model.mjs.map +1 -0
  109. package/dist/internal/sql-query.d.mts +12 -0
  110. package/dist/internal/sql-query.mjs +15 -18
  111. package/dist/internal/sql-query.mjs.map +1 -1
  112. package/dist/internal/sql-storage-validation.mjs +54 -0
  113. package/dist/internal/sql-storage-validation.mjs.map +1 -0
  114. package/dist/internal/storage-mapping.mjs +1 -37
  115. package/dist/internal/storage-mapping.mjs.map +1 -1
  116. package/dist/internal/storage-plans.d.mts +7 -0
  117. package/dist/internal/storage-plans.mjs +189 -0
  118. package/dist/internal/storage-plans.mjs.map +1 -0
  119. package/dist/internal/storage-tables.d.mts +0 -56
  120. package/dist/internal/storage-tables.mjs +0 -17
  121. package/dist/internal/storage-tables.mjs.map +1 -1
  122. package/dist/internal/storage-validation.d.mts +6 -1
  123. package/dist/internal/storage-validation.mjs +42 -1
  124. package/dist/internal/storage-validation.mjs.map +1 -1
  125. package/dist/internal/transaction-kernel.mjs +3 -2
  126. package/dist/internal/transaction-kernel.mjs.map +1 -1
  127. package/package.json +1 -1
  128. package/src/Adapter.ts +89 -5
  129. package/src/OAuthPersistence.ts +427 -0
  130. package/src/index.ts +3 -0
  131. package/src/internal/configuration.ts +1 -3
  132. package/src/internal/models/oauth-connected-model.ts +396 -0
  133. package/src/internal/models/oauth-model.ts +708 -0
  134. package/src/internal/models/password-model.ts +0 -56
  135. package/src/internal/native-sql-table.ts +14 -0
  136. package/src/internal/oauth/accounts.ts +838 -0
  137. package/src/internal/oauth/connected-access.ts +388 -0
  138. package/src/internal/oauth/connected-collection.ts +345 -0
  139. package/src/internal/oauth/connected-custody.ts +308 -0
  140. package/src/internal/oauth/connected-flow.ts +562 -0
  141. package/src/internal/oauth/connected-input.ts +147 -0
  142. package/src/internal/oauth/connected-keys.ts +31 -0
  143. package/src/internal/oauth/connected-maintenance.ts +379 -0
  144. package/src/internal/oauth/connected-management.ts +391 -0
  145. package/src/internal/oauth/connected-reference.ts +135 -0
  146. package/src/internal/oauth/connected-settlement.ts +278 -0
  147. package/src/internal/oauth/connected-sign-in.ts +472 -0
  148. package/src/internal/oauth/connected-state.ts +924 -0
  149. package/src/internal/oauth/connected-target.ts +307 -0
  150. package/src/internal/oauth/flow.ts +505 -0
  151. package/src/internal/oauth/input.ts +201 -0
  152. package/src/internal/oauth/owner.ts +22 -0
  153. package/src/internal/oauth/query-compiler.ts +15 -0
  154. package/src/internal/oauth/registration.ts +676 -0
  155. package/src/internal/oauth/state.ts +218 -0
  156. package/src/internal/oauth/target.ts +803 -0
  157. package/src/internal/oauth-kernel.ts +294 -0
  158. package/src/internal/oauth-proxy.ts +176 -0
  159. package/src/internal/password-credentials.ts +245 -0
  160. package/src/internal/password-kernel.ts +5 -98
  161. package/src/internal/persistence.ts +1 -1
  162. package/src/internal/query-operations.ts +2 -0
  163. package/src/internal/session-kernel.ts +143 -55
  164. package/src/internal/sql-oauth-connected-model.ts +145 -0
  165. package/src/internal/sql-oauth-model.ts +263 -0
  166. package/src/internal/sql-query.ts +16 -13
  167. package/src/internal/sql-storage-validation.ts +64 -0
  168. package/src/internal/storage-mapping.ts +0 -37
  169. package/src/internal/storage-plans.ts +218 -0
  170. package/src/internal/storage-tables.ts +0 -20
  171. package/src/internal/storage-validation.ts +58 -0
  172. package/src/internal/transaction-kernel.ts +6 -2
  173. package/dist/internal/password-attempts.mjs +0 -197
  174. package/dist/internal/password-attempts.mjs.map +0 -1
  175. package/src/internal/password-attempts.ts +0 -466
@@ -0,0 +1,838 @@
1
+ /* oxlint-disable no-explicit-any -- compiler table shapes are erased; domain codecs and error channels remain typed. */
2
+ import {
3
+ OAuthAccountRevision,
4
+ OAuthActionAuthorization,
5
+ OAuthLinkAccess,
6
+ OAuthLinkClaim,
7
+ OAuthLinkPendingFlow,
8
+ OAuthLinkTransactionContext,
9
+ OAuthUnlinked,
10
+ OAuthCredentialSnapshot,
11
+ snapshotOAuthSync,
12
+ } from "@yielded/auth/OAuth";
13
+ import {
14
+ SessionInvalidationWindow,
15
+ AuthenticationRequirement,
16
+ SecurityRevision,
17
+ } from "@yielded/auth/Sessions";
18
+ import { DateTime, Effect, Context, Layer } from "effect";
19
+
20
+ import type { SubjectIdCodec } from "../models/common";
21
+ import type { OAuthReferenceGuardDescriptor, OAuthEligibilityFact } from "../models/oauth-model";
22
+ import { OAuthFlow } from "./flow";
23
+ import { CurrentOAuthTransaction } from "./owner";
24
+ import { OAuthQueryCompiler } from "./query-compiler";
25
+ import { OAuthRegistration } from "./registration";
26
+ import {
27
+ invariant,
28
+ oauthIdentityKey,
29
+ sameRevision,
30
+ satisfies,
31
+ storage,
32
+ validAction,
33
+ } from "./state";
34
+
35
+ const make = Effect.gen(function* () {
36
+ const operations = yield* OAuthQueryCompiler;
37
+ const flow = yield* OAuthFlow;
38
+ const registration = yield* OAuthRegistration;
39
+
40
+ const { eq, sql } = operations;
41
+
42
+ const {
43
+ claimFlow,
44
+ credentialStorage,
45
+ currentSubject,
46
+ exactClaim,
47
+ issueFlow,
48
+ linkStorage,
49
+ matchesAccess,
50
+ readFlow,
51
+ terminalFlow,
52
+ } = flow;
53
+
54
+ const { both, col, copiedRow, equal } = operations;
55
+ const { acquireTuple, readTuple } = registration;
56
+
57
+ const contextStorage = storage(OAuthLinkTransactionContext);
58
+
59
+ const unlinkedStorage = storage(OAuthUnlinked);
60
+
61
+ const accountCurrent = (mapping: any, subjectId: OAuthAccountRevision["subjectId"]) =>
62
+ Effect.gen(function* () {
63
+ const native = yield* (mapping.subjectId as SubjectIdCodec<unknown>).toNative(subjectId);
64
+
65
+ return yield* currentSubject(mapping, native);
66
+ });
67
+
68
+ const authorization = (
69
+ mapping: any,
70
+ current: any,
71
+ auth: OAuthActionAuthorization,
72
+ action: OAuthActionAuthorization["challenge"]["action"],
73
+ flowId: string,
74
+ commandId: string,
75
+ intent: string,
76
+ maximumAge: number,
77
+ ) =>
78
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
79
+ Effect.gen(function* () {
80
+ const now = yield* owner.now(mapping.clock);
81
+
82
+ const currentRequirement = snapshotOAuthSync(
83
+ AuthenticationRequirement,
84
+ mapping.subject.decodeActionRequirement(copiedRow(current.row), action),
85
+ );
86
+
87
+ const accepted = yield* validAction(
88
+ auth,
89
+ {
90
+ moduleId: auth.challenge.moduleId,
91
+ action,
92
+ flowId,
93
+ commandId,
94
+ revision: current.revision,
95
+ intent,
96
+ },
97
+ currentRequirement,
98
+ now,
99
+ maximumAge,
100
+ );
101
+
102
+ if (!accepted) return false;
103
+
104
+ const age = Math.min(
105
+ maximumAge,
106
+ auth.requirement.maximumAgeMillis,
107
+ currentRequirement.maximumAgeMillis,
108
+ );
109
+
110
+ const fresh = auth.evidence.proofs.filter(
111
+ (proof) => now - DateTime.toEpochMillis(proof.verifiedAt) < age,
112
+ );
113
+
114
+ invariant(fresh.length > 0);
115
+
116
+ const deadline = Math.min(
117
+ ...fresh.map((proof) => DateTime.toEpochMillis(proof.verifiedAt) + age),
118
+ );
119
+
120
+ owner.postconditions.push(
121
+ sql`${mapping.clock.engineNowMillis} >= ${now} and ${mapping.clock.engineNowMillis} < ${deadline}`,
122
+ );
123
+
124
+ return true;
125
+ }),
126
+ );
127
+
128
+ const currentLink = (mapping: any, flow: typeof OAuthLinkPendingFlow.Type) =>
129
+ Effect.gen(function* () {
130
+ const current = yield* accountCurrent(mapping, flow.context.revision.subjectId);
131
+
132
+ return current !== undefined && sameRevision(current.revision, flow.context.revision)
133
+ ? current
134
+ : undefined;
135
+ });
136
+
137
+ const issueLink = (mapping: any, input: any) =>
138
+ Effect.gen(function* () {
139
+ const flow = snapshotOAuthSync(OAuthLinkPendingFlow, input.flow),
140
+ c = flow.context;
141
+
142
+ const current = yield* currentLink(mapping, flow);
143
+ const auth = snapshotOAuthSync(OAuthActionAuthorization, input.authorization);
144
+
145
+ if (
146
+ current === undefined ||
147
+ auth.challenge.moduleId !== c.moduleId ||
148
+ !(yield* authorization(
149
+ mapping,
150
+ current,
151
+ auth,
152
+ "link-begin",
153
+ c.flowId,
154
+ c.commandId,
155
+ contextStorage.encode(c),
156
+ c.maximumEvidenceAgeMillis,
157
+ ))
158
+ )
159
+ return { _tag: "Rejected" } as const;
160
+
161
+ return yield* issueFlow(mapping, flow, "link");
162
+ });
163
+
164
+ const preflightLink = (mapping: any, original: typeof OAuthLinkAccess.Type) =>
165
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
166
+ Effect.gen(function* () {
167
+ const input = snapshotOAuthSync(OAuthLinkAccess, original);
168
+ // The authenticated subject is known before discovering/locking any flow.
169
+ const current = yield* accountCurrent(mapping, input.subjectId);
170
+ const found = yield* readFlow(mapping, input, "link");
171
+ const now = yield* owner.now(mapping.clock);
172
+
173
+ if (
174
+ current === undefined ||
175
+ found.flow === undefined ||
176
+ found.row?.[mapping.flow.state] !== "Pending" ||
177
+ !matchesAccess(found.flow, input)
178
+ )
179
+ return undefined;
180
+
181
+ const flow = snapshotOAuthSync(OAuthLinkPendingFlow, found.flow as never),
182
+ c = flow.context;
183
+
184
+ if (
185
+ c.revision.subjectId !== input.subjectId ||
186
+ !sameRevision(current.revision, c.revision) ||
187
+ now < c.issuedAtMillis ||
188
+ now >= c.expiresAtMillis
189
+ )
190
+ return undefined;
191
+ owner.postconditions.push(
192
+ sql`${mapping.clock.engineNowMillis} >= ${c.issuedAtMillis} and ${mapping.clock.engineNowMillis} < ${c.expiresAtMillis}`,
193
+ );
194
+
195
+ return { current, flow, row: found.row };
196
+ }),
197
+ );
198
+
199
+ const claimLink = (mapping: any, input: any) =>
200
+ Effect.gen(function* () {
201
+ const found = yield* preflightLink(mapping, input.access);
202
+ const flow = snapshotOAuthSync(OAuthLinkPendingFlow, input.flow);
203
+
204
+ const auth = snapshotOAuthSync(OAuthActionAuthorization, input.authorization),
205
+ c = flow.context;
206
+
207
+ if (
208
+ found === undefined ||
209
+ linkStorage.encode(found.flow) !== linkStorage.encode(flow) ||
210
+ auth.challenge.moduleId !== c.moduleId ||
211
+ !(yield* authorization(
212
+ mapping,
213
+ found.current,
214
+ auth,
215
+ "link-complete",
216
+ c.flowId,
217
+ c.commandId,
218
+ contextStorage.encode(c),
219
+ c.maximumEvidenceAgeMillis,
220
+ ))
221
+ )
222
+ return { _tag: "Rejected" } as const;
223
+ const claim = yield* claimFlow(mapping, { row: found.row!, flow }, input.claimId);
224
+
225
+ return claim === undefined
226
+ ? ({ _tag: "Rejected" } as const)
227
+ : ({ _tag: "Claimed", claim } as const);
228
+ });
229
+
230
+ const checkInvalidation = (mapping: any, original: SessionInvalidationWindow) => {
231
+ const value = snapshotOAuthSync(SessionInvalidationWindow, original);
232
+
233
+ invariant(
234
+ value.trigger === "credential-change" &&
235
+ value.oldAuthenticationEvidence === "rejected" &&
236
+ (mapping.sessionInvalidation === "same-authority-immediate"
237
+ ? value.existingSessions === "immediate" && value.maximumExposureMillis === 0
238
+ : value.existingSessions === "original-absolute-expiry"),
239
+ );
240
+
241
+ return value;
242
+ };
243
+
244
+ const advance = (mapping: any, current: any, removed?: string) =>
245
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
246
+ Effect.gen(function* () {
247
+ const revision = mapping.subject.nextSecurityRevision(current.revision.securityRevision);
248
+
249
+ invariant(
250
+ typeof revision === "string" &&
251
+ revision.length > 0 &&
252
+ revision.length <= 256 &&
253
+ revision !== current.revision.securityRevision,
254
+ );
255
+ const subject = mapping.subject;
256
+
257
+ yield* owner.update(
258
+ subject.table,
259
+ { [subject.id]: current.nativeId },
260
+ { [subject.securityRevision]: revision },
261
+ );
262
+ for (const cleanup of mapping.cleanup) {
263
+ const condition = both(
264
+ eq(col(cleanup.table, cleanup.subjectId), current.nativeId),
265
+ cleanup.condition({
266
+ subjectId: current.nativeId,
267
+ revision: snapshotOAuthSync(OAuthAccountRevision, current.revision),
268
+ ...(removed === undefined ? {} : { removedCredentialId: removed }),
269
+ }),
270
+ );
271
+
272
+ yield* owner.write(owner.database.delete(cleanup.table).where(condition));
273
+ owner.postconditions.push(
274
+ sql`not exists(select 1 from ${cleanup.table} where ${condition})`,
275
+ );
276
+ }
277
+
278
+ return SecurityRevision.make(revision);
279
+ }),
280
+ );
281
+
282
+ const settleLink = (
283
+ mapping: any,
284
+ input: any,
285
+ allocated: { readonly credentialId: string; readonly revision: SecurityRevision },
286
+ ) =>
287
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
288
+ Effect.gen(function* () {
289
+ const claim = snapshotOAuthSync(OAuthLinkClaim, input.claim),
290
+ flow = claim.flow,
291
+ c = flow.context;
292
+
293
+ const current = yield* currentLink(mapping, flow);
294
+
295
+ // Known subject is always locked before tuple/flow; even a rejected outcome
296
+ // settles its exact original claim without adopting a newer revision.
297
+ const identity =
298
+ input.outcome._tag === "Verified" ? input.outcome.identity.identity : undefined;
299
+
300
+ if (identity !== undefined)
301
+ invariant(identity.provider === c.provider && identity.issuer === c.issuer);
302
+
303
+ const tuple =
304
+ identity !== undefined && current !== undefined
305
+ ? yield* readTuple(mapping.ownership, identity)
306
+ : undefined;
307
+
308
+ const exact = yield* exactClaim(mapping, claim, "link");
309
+
310
+ if (exact === undefined) return { _tag: "Rejected" } as const;
311
+ let decision: any = { _tag: input.outcome._tag };
312
+
313
+ if (input.outcome._tag === "Verified") {
314
+ decision = { _tag: "Rejected" };
315
+ const auth = snapshotOAuthSync(OAuthActionAuthorization, input.authorization);
316
+
317
+ if (
318
+ current !== undefined &&
319
+ tuple !== undefined &&
320
+ auth.challenge.moduleId === c.moduleId &&
321
+ (yield* authorization(
322
+ mapping,
323
+ current,
324
+ auth,
325
+ "link-complete",
326
+ c.flowId,
327
+ c.commandId,
328
+ contextStorage.encode(c),
329
+ c.maximumEvidenceAgeMillis,
330
+ ))
331
+ ) {
332
+ const t = mapping.ownership.tuple,
333
+ cr = mapping.credential,
334
+ a = mapping.authority;
335
+
336
+ const login = yield* owner.read(
337
+ cr.table,
338
+ eq(col(cr.table, cr.identityKey), tuple.key),
339
+ {
340
+ limit: 1,
341
+ },
342
+ );
343
+
344
+ const previous = login.rows[0];
345
+
346
+ if (
347
+ tuple.row[t.state] === "Reserved" ||
348
+ (tuple.row[t.state] === "Owned" &&
349
+ !mapping.subjectId.equals(tuple.row[t.subjectId], current.nativeId)) ||
350
+ (previous !== undefined &&
351
+ (previous[cr.moduleId] !== c.moduleId ||
352
+ !mapping.subjectId.equals(previous[cr.subjectId], current.nativeId) ||
353
+ !cr.isActiveStatus(previous[cr.status])))
354
+ )
355
+ decision = { _tag: "Conflict" };
356
+ else if (previous !== undefined) {
357
+ const shared = current.revision.credentials.find(
358
+ (item: any) => item.credentialId === previous[cr.credentialId],
359
+ );
360
+
361
+ if (
362
+ tuple.row[t.state] !== "Owned" ||
363
+ shared?.revision !== previous[cr.credentialRevision] ||
364
+ !(yield* owner.check(
365
+ sql`exists(select 1 from ${cr.table} where ${both(eq(col(cr.table, cr.identityKey), tuple.key), cr.activeCondition)})`,
366
+ ))
367
+ )
368
+ decision = { _tag: "Conflict" };
369
+ else
370
+ decision = {
371
+ _tag: "Linked",
372
+ changed: false,
373
+ credential: snapshotOAuthSync(OAuthCredentialSnapshot, {
374
+ moduleId: c.moduleId,
375
+ identity,
376
+ credentialId: previous[cr.credentialId],
377
+ credentialRevision: previous[cr.credentialRevision],
378
+ revision: current.revision,
379
+ }),
380
+ };
381
+ } else {
382
+ checkInvalidation(mapping, input.invalidation);
383
+
384
+ const values = {
385
+ ...cr.encodeInsert({
386
+ moduleId: c.moduleId,
387
+ subjectId: current.nativeId,
388
+ identityKey: tuple.key,
389
+ credentialId: allocated.credentialId,
390
+ credentialRevision: allocated.revision,
391
+ }),
392
+ [cr.moduleId]: c.moduleId,
393
+ [cr.subjectId]: current.nativeId,
394
+ [cr.identityKey]: tuple.key,
395
+ [cr.credentialId]: allocated.credentialId,
396
+ [cr.credentialRevision]: allocated.revision,
397
+ };
398
+
399
+ invariant(cr.isActiveStatus(values[cr.status]));
400
+
401
+ const inserted = yield* owner.insert(cr.table, values, {
402
+ [cr.credentialId]: allocated.credentialId,
403
+ });
404
+
405
+ login.rows = inserted.rows;
406
+
407
+ const sharedValues = {
408
+ ...a.encodeInsert({
409
+ subjectId: current.nativeId,
410
+ credentialId: allocated.credentialId,
411
+ revision: allocated.revision,
412
+ }),
413
+ [a.subjectId]: current.nativeId,
414
+ [a.credentialId]: allocated.credentialId,
415
+ [a.revision]: allocated.revision,
416
+ };
417
+
418
+ invariant(a.isActiveStatus(sharedValues[a.status]));
419
+
420
+ const shared = yield* owner.insert(a.table, sharedValues, {
421
+ [a.subjectId]: current.nativeId,
422
+ [a.credentialId]: allocated.credentialId,
423
+ });
424
+
425
+ current.authorities.rows = [...current.authorities.rows, ...shared.rows];
426
+ owner.postconditions.push(
427
+ sql`exists(select 1 from ${cr.table} where ${both(
428
+ eq(col(cr.table, cr.credentialId), allocated.credentialId),
429
+ cr.activeCondition,
430
+ )})`,
431
+ sql`exists(select 1 from ${a.table} where ${both(
432
+ eq(col(a.table, a.subjectId), current.nativeId),
433
+ eq(col(a.table, a.credentialId), allocated.credentialId),
434
+ a.activeCondition,
435
+ )})`,
436
+ );
437
+ if (tuple.row[t.state] === "Unowned")
438
+ yield* acquireTuple(mapping.ownership, identity, tuple.key, current.nativeId);
439
+ const next = yield* advance(mapping, current);
440
+
441
+ const revision = snapshotOAuthSync(OAuthAccountRevision, {
442
+ ...current.revision,
443
+ securityRevision: next,
444
+ credentials: [
445
+ ...current.revision.credentials,
446
+ { credentialId: allocated.credentialId, revision: allocated.revision },
447
+ ],
448
+ });
449
+
450
+ decision = {
451
+ _tag: "Linked",
452
+ changed: true,
453
+ credential: snapshotOAuthSync(OAuthCredentialSnapshot, {
454
+ moduleId: c.moduleId,
455
+ identity,
456
+ credentialId: allocated.credentialId,
457
+ credentialRevision: allocated.revision as never,
458
+ revision,
459
+ }),
460
+ };
461
+ }
462
+ }
463
+ }
464
+ yield* terminalFlow(mapping, flow, decision._tag);
465
+
466
+ return decision;
467
+ }),
468
+ );
469
+
470
+ const targetCredential = (mapping: any, moduleId: string, credentialId: string, current: any) =>
471
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
472
+ Effect.gen(function* () {
473
+ const cr = mapping.credential;
474
+
475
+ const found = yield* owner.read(
476
+ cr.table,
477
+ eq(col(cr.table, cr.credentialId), credentialId),
478
+ {
479
+ limit: 1,
480
+ },
481
+ );
482
+
483
+ const row = found.rows[0];
484
+
485
+ if (
486
+ row === undefined ||
487
+ row[cr.moduleId] !== moduleId ||
488
+ !mapping.subjectId.equals(row[cr.subjectId], current.nativeId) ||
489
+ !cr.isActiveStatus(row[cr.status])
490
+ )
491
+ return undefined;
492
+ const t = mapping.ownership.tuple;
493
+
494
+ const tuple = yield* owner.read(
495
+ t.table,
496
+ eq(col(t.table, t.identityKey), row[cr.identityKey]),
497
+ {
498
+ limit: 1,
499
+ },
500
+ );
501
+
502
+ const ownership = tuple.rows[0];
503
+
504
+ if (
505
+ ownership === undefined ||
506
+ ownership[t.state] !== "Owned" ||
507
+ !mapping.subjectId.equals(ownership[t.subjectId], current.nativeId)
508
+ )
509
+ return undefined;
510
+
511
+ const identity = {
512
+ provider: ownership[t.provider],
513
+ issuer: ownership[t.issuer],
514
+ subject: ownership[t.externalSubject],
515
+ };
516
+
517
+ invariant((yield* oauthIdentityKey(identity)) === row[cr.identityKey]);
518
+
519
+ const shared = current.revision.credentials.find(
520
+ (item: any) => item.credentialId === credentialId,
521
+ );
522
+
523
+ if (
524
+ shared?.revision !== row[cr.credentialRevision] ||
525
+ !(yield* owner.check(
526
+ sql`exists(select 1 from ${cr.table} where ${both(eq(col(cr.table, cr.credentialId), credentialId), cr.activeCondition)})`,
527
+ ))
528
+ )
529
+ return undefined;
530
+
531
+ return snapshotOAuthSync(OAuthCredentialSnapshot, {
532
+ moduleId: moduleId as never,
533
+ identity,
534
+ credentialId,
535
+ credentialRevision: row[cr.credentialRevision],
536
+ revision: current.revision,
537
+ });
538
+ }),
539
+ );
540
+
541
+ const unlinkCommand = (mapping: any, moduleId: string, commandId: string) =>
542
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
543
+ owner.read(
544
+ mapping.command.table,
545
+ equal(mapping.command.table, {
546
+ [mapping.command.moduleId]: moduleId,
547
+ [mapping.command.commandId]: commandId,
548
+ }),
549
+ { limit: 1 },
550
+ ),
551
+ );
552
+
553
+ const inspectUnlink = (mapping: any, input: any) =>
554
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
555
+ Effect.gen(function* () {
556
+ const current = yield* accountCurrent(mapping, input.subjectId);
557
+
558
+ if (current === undefined) return { _tag: "Rejected" } as const;
559
+
560
+ const command = yield* unlinkCommand(mapping, input.moduleId, input.commandId),
561
+ r = mapping.command;
562
+
563
+ const old = command.rows[0];
564
+
565
+ if (old !== undefined) {
566
+ const intent = credentialStorage.decode(old[r.intentSnapshot]);
567
+
568
+ if (
569
+ intent.moduleId !== input.moduleId ||
570
+ intent.revision.subjectId !== input.subjectId ||
571
+ intent.credentialId !== input.credentialId ||
572
+ !mapping.subjectId.equals(old[r.subjectId], current.nativeId) ||
573
+ old[r.credentialId] !== input.credentialId
574
+ )
575
+ return { _tag: "Conflict" } as const;
576
+ const metadata = mapping.metadata.condition(current.nativeId);
577
+
578
+ if (!(yield* owner.check(metadata))) return { _tag: "Rejected" } as const;
579
+ owner.postconditions.push(metadata);
580
+
581
+ return { _tag: "Replay", result: unlinkedStorage.decode(old[r.decision]) } as const;
582
+ }
583
+
584
+ const credential = yield* targetCredential(
585
+ mapping,
586
+ input.moduleId,
587
+ input.credentialId,
588
+ current,
589
+ );
590
+
591
+ return credential === undefined
592
+ ? ({ _tag: "Rejected" } as const)
593
+ : ({ _tag: "Target", credential } as const);
594
+ }),
595
+ );
596
+
597
+ const remainingEligibility = (mapping: any, current: any, removed: string) =>
598
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
599
+ Effect.gen(function* () {
600
+ invariant(mapping.eligibility.length > 0 && mapping.eligibility.length <= 32);
601
+ const facts = new Map<string, OAuthEligibilityFact>();
602
+
603
+ const revisions = new Map(
604
+ current.revision.credentials.map((item: any) => [item.credentialId, item.revision]),
605
+ );
606
+
607
+ for (const descriptor of mapping.eligibility) {
608
+ const observed = yield* owner.read(
609
+ descriptor.table,
610
+ both(
611
+ eq(col(descriptor.table, descriptor.subjectId), current.nativeId),
612
+ descriptor.condition(current.nativeId),
613
+ ),
614
+ { orderBy: col(descriptor.table, descriptor.credentialId) },
615
+ );
616
+
617
+ for (const row of observed.rows) {
618
+ const fact = descriptor.decode(copiedRow(row)) as OAuthEligibilityFact | undefined;
619
+
620
+ if (fact === undefined || fact.credentialId === removed) continue;
621
+ invariant(
622
+ fact.credentialId === row[descriptor.credentialId] &&
623
+ fact.revision === row[descriptor.revision] &&
624
+ revisions.get(fact.credentialId) === fact.revision &&
625
+ fact.factors.length <= 8 &&
626
+ fact.factors.every((factor) =>
627
+ ["knowledge", "possession", "inherence"].includes(factor),
628
+ ),
629
+ );
630
+ invariant(
631
+ typeof fact.usablePrimary === "boolean" &&
632
+ typeof fact.userVerified === "boolean" &&
633
+ typeof fact.phishingResistant === "boolean",
634
+ );
635
+
636
+ const normalized = {
637
+ credentialId: fact.credentialId,
638
+ revision: fact.revision,
639
+ usablePrimary: fact.usablePrimary,
640
+ factors: [...new Set(fact.factors)].sort(),
641
+ userVerified: fact.userVerified,
642
+ phishingResistant: fact.phishingResistant,
643
+ };
644
+
645
+ const prior = facts.get(fact.credentialId);
646
+
647
+ // oxlint-disable-next-line no-restricted-properties -- Canonical bounded eligibility fact fingerprint rejects contradictory duplicate IDs.
648
+ invariant(prior === undefined || JSON.stringify(prior) === JSON.stringify(normalized));
649
+ facts.set(fact.credentialId, normalized);
650
+ }
651
+ }
652
+ const available = [...facts.values()];
653
+
654
+ const requirement = snapshotOAuthSync(
655
+ AuthenticationRequirement,
656
+ mapping.subject.decodeAuthenticationRequirement(copiedRow(current.row)),
657
+ );
658
+
659
+ return available.some((fact) => fact.usablePrimary) && satisfies(available, requirement);
660
+ }),
661
+ );
662
+
663
+ const unlink = (mapping: any, input: any) =>
664
+ Effect.flatMap(CurrentOAuthTransaction, (owner) =>
665
+ Effect.gen(function* () {
666
+ const expected = snapshotOAuthSync(OAuthCredentialSnapshot, input.credential);
667
+
668
+ invariant(expected.moduleId === input.moduleId);
669
+ const current = yield* accountCurrent(mapping, expected.revision.subjectId);
670
+
671
+ if (current === undefined) return { _tag: "Rejected" } as const;
672
+
673
+ const guards: ReadonlyArray<OAuthReferenceGuardDescriptor<unknown>> =
674
+ mapping.connectedReferenceGuards ?? [];
675
+
676
+ invariant(guards.length <= 32);
677
+ let referencesGuarded = mapping.connectedReference !== undefined && guards.length > 0;
678
+
679
+ if (mapping.connectedReference !== undefined)
680
+ for (const guard of guards) {
681
+ const condition = guard.condition({
682
+ identity: snapshotOAuthSync(
683
+ OAuthCredentialSnapshot.fields.identity,
684
+ expected.identity,
685
+ ),
686
+ identityKey: yield* oauthIdentityKey(expected.identity),
687
+ subjectId: copiedRow({ value: current.nativeId }).value,
688
+ });
689
+
690
+ const read = yield* owner.read(
691
+ guard.table,
692
+ Effect.isEffect(condition) ? yield* condition : condition,
693
+ { orderBy: col(guard.table, guard.orderBy) },
694
+ );
695
+
696
+ if (read.rows.length === 0) referencesGuarded = false;
697
+ }
698
+
699
+ const command = yield* unlinkCommand(mapping, input.moduleId, input.commandId),
700
+ r = mapping.command;
701
+
702
+ const previous = command.rows[0];
703
+
704
+ if (previous !== undefined) {
705
+ if (
706
+ previous[r.intentSnapshot] !== credentialStorage.encode(expected) ||
707
+ previous[r.credentialId] !== expected.credentialId ||
708
+ !mapping.subjectId.equals(previous[r.subjectId], current.nativeId)
709
+ )
710
+ return { _tag: "Conflict" } as const;
711
+ const metadata = mapping.metadata.condition(current.nativeId);
712
+
713
+ if (!(yield* owner.check(metadata))) return { _tag: "Rejected" } as const;
714
+ owner.postconditions.push(metadata);
715
+
716
+ return {
717
+ _tag: "Unlinked",
718
+ replayed: true,
719
+ result: unlinkedStorage.decode(previous[r.decision]),
720
+ } as const;
721
+ }
722
+
723
+ const actual = yield* targetCredential(
724
+ mapping,
725
+ input.moduleId,
726
+ expected.credentialId,
727
+ current,
728
+ );
729
+
730
+ if (
731
+ actual === undefined ||
732
+ credentialStorage.encode(actual) !== credentialStorage.encode(expected)
733
+ )
734
+ return { _tag: "Rejected" } as const;
735
+ const auth = snapshotOAuthSync(OAuthActionAuthorization, input.authorization);
736
+
737
+ if (
738
+ auth.challenge.moduleId !== input.moduleId ||
739
+ !(yield* authorization(
740
+ mapping,
741
+ current,
742
+ auth,
743
+ "unlink",
744
+ input.commandId,
745
+ input.commandId,
746
+ credentialStorage.encode(expected),
747
+ auth.requirement.maximumAgeMillis,
748
+ ))
749
+ )
750
+ return { _tag: "Rejected" } as const;
751
+ if (!(yield* remainingEligibility(mapping, current, expected.credentialId)))
752
+ return { _tag: "LastSignInMethod" } as const;
753
+
754
+ const invalidation = checkInvalidation(mapping, input.invalidation),
755
+ cr = mapping.credential,
756
+ a = mapping.authority;
757
+
758
+ const key = yield* oauthIdentityKey(expected.identity),
759
+ t = mapping.ownership.tuple;
760
+
761
+ const connected = mapping.connectedReference?.({
762
+ identityKey: key,
763
+ subjectId: copiedRow({ value: current.nativeId }).value,
764
+ });
765
+
766
+ const retain =
767
+ connected !== undefined && (!referencesGuarded || (yield* owner.check(connected)));
768
+
769
+ if (connected !== undefined && referencesGuarded)
770
+ owner.postconditions.push(retain ? connected : sql`not (${connected})`);
771
+ yield* owner.remove(cr.table, { [cr.credentialId]: expected.credentialId });
772
+ yield* owner.remove(a.table, {
773
+ [a.subjectId]: current.nativeId,
774
+ [a.credentialId]: expected.credentialId,
775
+ });
776
+ if (!retain) {
777
+ yield* owner.update(
778
+ t.table,
779
+ { [t.identityKey]: key },
780
+ {
781
+ [t.state]: "Unowned",
782
+ [t.subjectId]: null,
783
+ [t.reservation]: null,
784
+ [t.version]: owner.marker,
785
+ },
786
+ );
787
+ if (mapping.ownership.mode === "separate")
788
+ yield* owner.remove(mapping.ownership.external.table, {
789
+ [mapping.ownership.external.identityKey]: key,
790
+ });
791
+ }
792
+ yield* advance(mapping, current, expected.credentialId);
793
+
794
+ const result = snapshotOAuthSync(OAuthUnlinked, {
795
+ _tag: "Unlinked",
796
+ credentialId: expected.credentialId,
797
+ invalidation,
798
+ });
799
+
800
+ const now = yield* owner.now(mapping.clock);
801
+
802
+ invariant(
803
+ Number.isSafeInteger(input.retentionUntilMillis) &&
804
+ input.retentionUntilMillis > now &&
805
+ input.retentionUntilMillis >= input.nowMillis + 120000,
806
+ );
807
+ const commandKey = { [r.moduleId]: input.moduleId, [r.commandId]: input.commandId };
808
+
809
+ const values = {
810
+ ...r.encodeInsert({
811
+ moduleId: input.moduleId,
812
+ commandId: input.commandId,
813
+ credential: snapshotOAuthSync(OAuthCredentialSnapshot, expected),
814
+ }),
815
+ ...commandKey,
816
+ [r.subjectId]: current.nativeId,
817
+ [r.credentialId]: expected.credentialId,
818
+ [r.intentSnapshot]: credentialStorage.encode(expected),
819
+ [r.decision]: unlinkedStorage.encode(result),
820
+ [r.retentionUntil]: mapping.clock.encodeInstant(input.retentionUntilMillis),
821
+ };
822
+
823
+ const inserted = yield* owner.insert(r.table, values, commandKey);
824
+
825
+ command.rows = inserted.rows;
826
+
827
+ return { _tag: "Unlinked", result, replayed: false } as const;
828
+ }),
829
+ );
830
+
831
+ return { accountCurrent, issueLink, preflightLink, claimLink, settleLink, inspectUnlink, unlink };
832
+ });
833
+
834
+ export class OAuthAccounts extends Context.Service<OAuthAccounts, Effect.Success<typeof make>>()(
835
+ "effect-auth/persistence/OAuthAccounts",
836
+ ) {
837
+ static readonly layer = Layer.effect(OAuthAccounts, make);
838
+ }