@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,737 @@
1
+ import { PersistenceMappingError, isMappedConstraintConflict } from "./mapping-error.mjs";
2
+ import { decodeStepUpIntent, encodeStepUpIntent, sameStepUpRevision, stepUpIntentLive, stepUpRotationMatches, validateStepUpPlan } from "./step-up-state.mjs";
3
+ import { Cause, Context, DateTime, Effect, Option, Schema } from "effect";
4
+ import { CurrentCommitJournal, LifecycleHooks, coordinateCommit, hasCommitScope } from "@yielded/auth/Hooks";
5
+ import { PendingAuthenticationInvalid, SessionConflict, SessionInvalid, SessionMetadata, SessionStepUpInvalid, SessionUnavailable, StaleAuthentication, assessAuthentication, pendingAuthenticationContext, snapshotPendingAuthenticationContext, snapshotSessionAuthenticationProvenance } from "@yielded/auth/Sessions";
6
+ import { reportPersistenceFailure } from "@yielded/auth/Persistence";
7
+ //#region src/internal/session-kernel.ts
8
+ /** Native SQL authority for the current transaction or savepoint. */
9
+ var CurrentSessionSql = class extends Context.Service()("effect-auth/drizzle/CurrentSessionSql") {};
10
+ const makeSessionKernel = (operations) => {
11
+ const { and, eq, gt, lte, inArray, or, sql, column, updateValues } = operations;
12
+ const unavailable = () => SessionUnavailable.make({});
13
+ const stale = () => StaleAuthentication.make({});
14
+ const invalidPending = () => PendingAuthenticationInvalid.make({});
15
+ const invalidSession = () => SessionInvalid.make({});
16
+ const mapFailureCause = (effect, map) => Effect.catchCause(effect, (cause) => Effect.failCause(Cause.map(cause, map)));
17
+ const isExpectedMutationError = (error) => {
18
+ const tag = typeof error === "object" && error !== null ? Reflect.get(error, "_tag") : void 0;
19
+ return tag === "SessionStepUpInvalid" || tag === "StaleAuthentication" || tag === "PendingAuthenticationInvalid" || tag === "SessionConflict" || tag === "SessionInvalid" || tag === "SessionUnavailable";
20
+ };
21
+ const normalizeMutation = (mapping) => (effect) => effect.pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => isMappedConstraintConflict(mapping.isConstraintConflict, error) ? SessionConflict.make({}) : error))));
22
+ const safeTransaction = (effect) => reportPersistenceFailure(effect, isExpectedMutationError).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => isExpectedMutationError(error) ? error : unavailable()))));
23
+ const selectRows = (query, locking) => locking && typeof query.for === "function" ? query.for("update") : query;
24
+ const inTransaction = (database, effect) => Effect.suspend(() => database.transaction((current) => effect.pipe(Effect.provideService(CurrentSessionSql, current))));
25
+ const owned = (database, options, isConstraintConflict, body) => {
26
+ const run = coordinateCommit(() => database.transaction((current) => body.pipe(Effect.provideService(CurrentSessionSql, current))), { mode: options.mode }).pipe((effect) => reportPersistenceFailure(effect, (error) => isExpectedMutationError(error) || isMappedConstraintConflict(isConstraintConflict, error)), Effect.map((result) => result.value), Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => isExpectedMutationError(error) ? error : unavailable()))));
27
+ return Effect.gen(function* () {
28
+ const current = yield* Effect.serviceOption(CurrentSessionSql);
29
+ if (!(Option.isSome(current) && current.value === database)) {
30
+ if (yield* hasCommitScope) return yield* unavailable();
31
+ yield* options.standaloneGuard;
32
+ }
33
+ return yield* run;
34
+ });
35
+ };
36
+ const uniqueStrings = (values) => [...new Set(values)].sort();
37
+ const preservesRevision = (completed, original) => {
38
+ const current = new Map(completed.revision.credentials.map((item) => [item.credentialId, item.revision]));
39
+ return completed.flowId === original.flowId && completed.bindingDigest === original.bindingDigest && completed.revision.subjectId === original.revision.subjectId && completed.revision.securityRevision === original.revision.securityRevision && original.revision.credentials.every((item) => current.get(item.credentialId) === item.revision) && original.proofs.every((expected) => completed.proofs.some((proof) => proof.method === expected.method && proof.credentialId === expected.credentialId && proof.userVerified === expected.userVerified && proof.phishingResistant === expected.phishingResistant && DateTime.toEpochMillis(proof.verifiedAt) === DateTime.toEpochMillis(expected.verifiedAt) && proof.factors.length === expected.factors.length && proof.factors.every((factor, index) => factor === expected.factors[index])));
40
+ };
41
+ const authorityColumns = (mapping) => ({
42
+ subjectId: column(mapping.subject.table, mapping.subject.id),
43
+ subjectStatus: column(mapping.subject.table, mapping.subject.status),
44
+ subjectRevision: column(mapping.subject.table, mapping.subject.securityRevision),
45
+ credentialSubjectId: column(mapping.credential.table, mapping.credential.subjectId),
46
+ credentialId: column(mapping.credential.table, mapping.credential.credentialId),
47
+ credentialRevision: column(mapping.credential.table, mapping.credential.revision),
48
+ ...mapping.credential.status === void 0 ? {} : { credentialStatus: column(mapping.credential.table, mapping.credential.status) }
49
+ });
50
+ const subjectColumns = (mapping) => ({
51
+ subjectId: column(mapping.subject.table, mapping.subject.id),
52
+ subjectStatus: column(mapping.subject.table, mapping.subject.status),
53
+ subjectRevision: column(mapping.subject.table, mapping.subject.securityRevision)
54
+ });
55
+ const readSubject = Effect.fn("DrizzleSession.readSubject")(function* (mapping, nativeSubjectId, locking) {
56
+ const database = yield* CurrentSessionSql;
57
+ const columns = subjectColumns(mapping);
58
+ return yield* selectRows(database.select().from(mapping.subject.table).where(eq(columns.subjectId, nativeSubjectId)).limit(1), locking);
59
+ });
60
+ const captureDetailsIn = Effect.fn("DrizzleSession.captureDetails")(function* (mapping, subjectId, credentialIds, locking) {
61
+ const database = yield* CurrentSessionSql;
62
+ const requested = uniqueStrings(credentialIds);
63
+ if (requested.length !== credentialIds.length) return yield* stale();
64
+ const nativeSubjectId = yield* mapping.subjectId.toNative(subjectId);
65
+ const subject = (yield* readSubject(mapping, nativeSubjectId, locking))[0];
66
+ const columns = authorityColumns(mapping);
67
+ if (subject === void 0 || !mapping.subject.isActiveStatus(subject[mapping.subject.status])) return yield* stale();
68
+ const query = database.select().from(mapping.credential.table).where(and(eq(columns.credentialSubjectId, nativeSubjectId), requested.length === 0 ? sql`false` : inArray(columns.credentialId, requested))).orderBy(columns.credentialId);
69
+ const credentialRows = requested.length === 0 ? [] : yield* selectRows(query, locking);
70
+ if (credentialRows.length !== requested.length) return yield* stale();
71
+ const credentials = credentialRows.map((row) => ({
72
+ credentialId: row[mapping.credential.credentialId],
73
+ revision: row[mapping.credential.revision],
74
+ active: mapping.credential.status === void 0 || mapping.credential.isActiveStatus?.(row[mapping.credential.status]) === true
75
+ })).sort((left, right) => left.credentialId.localeCompare(right.credentialId));
76
+ if (credentials.some((item) => !item.active)) return yield* stale();
77
+ return {
78
+ subject,
79
+ revision: {
80
+ subjectId,
81
+ securityRevision: subject[mapping.subject.securityRevision],
82
+ credentials: credentials.map(({ credentialId, revision }) => ({
83
+ credentialId,
84
+ revision
85
+ }))
86
+ }
87
+ };
88
+ });
89
+ const captureIn = Effect.fn("DrizzleSession.capture")(function* (mapping, subjectId, credentialIds, locking) {
90
+ return (yield* captureDetailsIn(mapping, subjectId, credentialIds, locking)).revision;
91
+ });
92
+ const validateEvidenceIn = Effect.fn("DrizzleSession.validateEvidence")(function* (mapping, evidence, locking) {
93
+ const captured = yield* captureDetailsIn(mapping, evidence.revision.subjectId, evidence.revision.credentials.map((item) => item.credentialId), locking);
94
+ if (captured.revision.securityRevision !== evidence.revision.securityRevision || captured.revision.credentials.length !== evidence.revision.credentials.length || captured.revision.credentials.some((item, index) => {
95
+ const expected = [...evidence.revision.credentials].sort((a, b) => a.credentialId.localeCompare(b.credentialId))[index];
96
+ return expected === void 0 || expected.credentialId !== item.credentialId || expected.revision !== item.revision;
97
+ })) return yield* stale();
98
+ return {
99
+ nativeSubjectId: yield* mapping.subjectId.toNative(evidence.revision.subjectId),
100
+ requirement: yield* mapping.subject.decodeRequirement(captured.subject)
101
+ };
102
+ });
103
+ const flowColumns = (mapping) => ({
104
+ flowId: column(mapping.flow.table, mapping.flow.flowId),
105
+ subjectId: column(mapping.flow.table, mapping.flow.subjectId),
106
+ state: column(mapping.flow.table, mapping.flow.state),
107
+ pendingDigest: column(mapping.flow.table, mapping.flow.pendingDigest),
108
+ dedupUntil: column(mapping.flow.table, mapping.flow.dedupUntil)
109
+ });
110
+ const readFlow = Effect.fn("DrizzleSession.readFlow")(function* (mapping, flowId, locking) {
111
+ const database = yield* CurrentSessionSql;
112
+ const columns = flowColumns(mapping);
113
+ return yield* selectRows(database.select().from(mapping.flow.table).where(eq(columns.flowId, flowId)).limit(1), locking);
114
+ });
115
+ const ensureDirectFlowAvailable = Effect.fn("DrizzleSession.ensureFlowAvailable")(function* (mapping, evidence, nativeSubjectId, dedupUntil) {
116
+ const database = yield* CurrentSessionSql;
117
+ const existing = (yield* readFlow(mapping, evidence.flowId, true))[0];
118
+ if (existing !== void 0) {
119
+ const now = yield* freshNow;
120
+ if (DateTime.toEpochMillis(now) < DateTime.toEpochMillis(yield* mapping.flow.decodeInstant(existing[mapping.flow.dedupUntil]))) return yield* SessionConflict.make({});
121
+ if (mapping.pending !== void 0) yield* database.delete(mapping.pending.table).where(eq(column(mapping.pending.table, mapping.pending.flowId), evidence.flowId));
122
+ yield* database.delete(mapping.flow.table).where(eq(flowColumns(mapping).flowId, evidence.flowId));
123
+ }
124
+ return mapping.flow.encodeEstablishedInsert({
125
+ evidence,
126
+ subjectId: nativeSubjectId,
127
+ dedupUntil
128
+ });
129
+ });
130
+ const pendingColumns = (mapping) => ({
131
+ digest: column(mapping.pending.table, mapping.pending.digest),
132
+ version: column(mapping.pending.table, mapping.pending.version),
133
+ flowId: column(mapping.pending.table, mapping.pending.flowId),
134
+ subjectId: column(mapping.pending.table, mapping.pending.subjectId),
135
+ bindingDigest: column(mapping.pending.table, mapping.pending.bindingDigest),
136
+ expiresAt: column(mapping.pending.table, mapping.pending.expiresAt),
137
+ attemptLimit: column(mapping.pending.table, mapping.pending.attemptLimit),
138
+ failedAttempts: column(mapping.pending.table, mapping.pending.failedAttempts),
139
+ consumed: column(mapping.pending.table, mapping.pending.consumed)
140
+ });
141
+ const readPending = Effect.fn("DrizzleSession.readPending")(function* (mapping, digest, locking) {
142
+ const database = yield* CurrentSessionSql;
143
+ return yield* selectRows(database.select().from(mapping.pending.table).where(eq(pendingColumns(mapping).digest, digest)).limit(1), locking);
144
+ });
145
+ const validatePending = Effect.fn("DrizzleSession.validatePending")(function* (mapping, input, projection = "record") {
146
+ const row = (yield* readPending(mapping, input.digest, true))[0];
147
+ if (row === void 0) return yield* invalidPending();
148
+ const record = yield* (projection === "context" ? mapping.pending.decodeContext : mapping.pending.decode)(row);
149
+ const failedAttempts = Number(row[mapping.pending.failedAttempts]);
150
+ if (record.version !== input.version || record.evidence.flowId !== input.flowId || record.evidence.bindingDigest !== input.bindingDigest || row[mapping.pending.consumed] !== false || failedAttempts >= record.attemptLimit) return yield* invalidPending();
151
+ const flow = (yield* readFlow(mapping, input.flowId, true))[0];
152
+ if (flow === void 0 || flow[mapping.flow.state] !== mapping.flow.pendingStateValue || flow[mapping.flow.pendingDigest] !== input.digest) return yield* invalidPending();
153
+ if (DateTime.toEpochMillis(yield* freshNow) >= DateTime.toEpochMillis(record.expiresAt)) return yield* invalidPending();
154
+ return record;
155
+ });
156
+ const consumePending = Effect.fn("DrizzleSession.consumePending")(function* (mapping, input, until) {
157
+ const database = yield* CurrentSessionSql;
158
+ yield* Effect.all([database.update(mapping.pending.table).set(updateValues([[mapping.pending.consumed, true]])).where(and(eq(pendingColumns(mapping).digest, input.digest), eq(pendingColumns(mapping).version, input.version), eq(pendingColumns(mapping).consumed, false))), database.update(mapping.flow.table).set(updateValues([
159
+ [mapping.flow.state, mapping.flow.establishedStateValue],
160
+ [mapping.flow.pendingDigest, null],
161
+ [mapping.flow.dedupUntil, mapping.flow.encodeInstant(until)]
162
+ ])).where(eq(flowColumns(mapping).flowId, input.flowId))]);
163
+ });
164
+ const freshNow = DateTime.now;
165
+ const allocate = (mode, asynchronous, synchronous) => {
166
+ if (mode === "synchronous") return synchronous === void 0 ? Effect.fail(unavailable()) : Effect.try({
167
+ try: synchronous,
168
+ catch: (cause) => PersistenceMappingError.make({
169
+ operation: "allocate",
170
+ cause
171
+ })
172
+ });
173
+ if (asynchronous !== void 0) return asynchronous;
174
+ return synchronous === void 0 ? Effect.fail(unavailable()) : Effect.try({
175
+ try: synchronous,
176
+ catch: (cause) => PersistenceMappingError.make({
177
+ operation: "allocate",
178
+ cause
179
+ })
180
+ });
181
+ };
182
+ const makeSqlAuthenticationAuthority = (database, mapping, options) => Effect.map(LifecycleHooks, (hooks) => {
183
+ const service = {
184
+ capture: (subjectId, credentialIds) => safeTransaction(inTransaction(database, captureIn(mapping, subjectId, credentialIds, true))),
185
+ requirements: (evidence) => safeTransaction(inTransaction(database, validateEvidenceIn(mapping, evidence, true).pipe(Effect.map((result) => result.requirement)))),
186
+ approve: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
187
+ const journal = yield* CurrentCommitJournal;
188
+ const { requirement } = yield* validateEvidenceIn(mapping, input.evidence, true);
189
+ if (input.pending === void 0) {
190
+ const assessed = yield* assessAuthentication(input.evidence, requirement).pipe(Effect.mapError(unavailable));
191
+ const now = yield* freshNow;
192
+ if (!assessed.satisfied || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(input.expiresAt) || DateTime.toEpochMillis(input.expiresAt) > DateTime.toEpochMillis(input.absoluteExpiresAt)) return yield* stale();
193
+ return prepare(void 0, journal);
194
+ }
195
+ if (mapping.pending === void 0) return yield* invalidPending();
196
+ const pendingMapping = {
197
+ ...mapping,
198
+ ...mapping.pending
199
+ };
200
+ const pending = yield* validatePending(pendingMapping, input.pending);
201
+ if (!preservesRevision(input.evidence, pending.evidence)) return yield* invalidPending();
202
+ const assessed = yield* assessAuthentication(input.evidence, requirement).pipe(Effect.mapError(unavailable));
203
+ const now = yield* freshNow;
204
+ if (!assessed.satisfied || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(pending.expiresAt) || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(input.expiresAt) || DateTime.toEpochMillis(input.expiresAt) > DateTime.toEpochMillis(input.absoluteExpiresAt)) return yield* stale();
205
+ const receipt = prepare(void 0, journal);
206
+ yield* consumePending(pendingMapping, input.pending, input.absoluteExpiresAt);
207
+ return receipt;
208
+ }))
209
+ };
210
+ return {
211
+ capture: (subjectId, credentialIds) => service.capture(subjectId, credentialIds).pipe(Effect.provideService(LifecycleHooks, hooks)),
212
+ requirements: (evidence) => service.requirements(evidence).pipe(Effect.provideService(LifecycleHooks, hooks)),
213
+ approve: (input, prepare) => service.approve(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks))
214
+ };
215
+ });
216
+ /** The same locked security checks serve full consumption reads and the
217
+ * claims-free additional-factor context. No lock spans proof verification. */
218
+ const readAuthenticatedPending = Effect.fn("DrizzleSession.readAuthenticatedPending")(function* (mapping, input, projection) {
219
+ const initial = (yield* readPending(mapping, input.digest, false))[0];
220
+ if (initial === void 0) return yield* invalidPending();
221
+ const initialNativeSubjectId = initial[mapping.pending.subjectId];
222
+ if ((yield* readSubject(mapping, initialNativeSubjectId, true))[0] === void 0) return yield* invalidPending();
223
+ const current = (yield* readPending(mapping, input.digest, true))[0];
224
+ if (current === void 0 || !mapping.subjectId.equals(current[mapping.pending.subjectId], initialNativeSubjectId)) return yield* invalidPending();
225
+ const record = yield* (projection === "context" ? mapping.pending.decodeContext : mapping.pending.decode)(current);
226
+ const nativeSubjectId = yield* mapping.subjectId.toNative(record.evidence.revision.subjectId);
227
+ const failedAttempts = Number(current[mapping.pending.failedAttempts]);
228
+ if (!mapping.subjectId.equals(nativeSubjectId, initialNativeSubjectId) || input.bindingDigest !== void 0 && record.evidence.bindingDigest !== input.bindingDigest || current[mapping.pending.version] !== record.version || current[mapping.pending.flowId] !== record.evidence.flowId || current[mapping.pending.bindingDigest] !== record.evidence.bindingDigest || current[mapping.pending.consumed] !== false || failedAttempts >= record.attemptLimit) return yield* invalidPending();
229
+ const flow = (yield* readFlow(mapping, record.evidence.flowId, true))[0];
230
+ if (flow === void 0 || flow[mapping.flow.state] !== mapping.flow.pendingStateValue || flow[mapping.flow.pendingDigest] !== input.digest) return yield* invalidPending();
231
+ const { requirement } = yield* mapFailureCause(validateEvidenceIn(mapping, record.evidence, true), (error) => Schema.is(StaleAuthentication)(error) ? invalidPending() : error);
232
+ yield* assessAuthentication(record.evidence, requirement).pipe(Effect.mapError(() => invalidPending()));
233
+ if (DateTime.toEpochMillis(yield* freshNow) >= DateTime.toEpochMillis(record.expiresAt)) return yield* invalidPending();
234
+ return record;
235
+ });
236
+ const makeSqlPendingAuthentication = (database, mapping, options) => Effect.map(LifecycleHooks, (hooks) => {
237
+ const service = {
238
+ create: (input, _inputNow, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
239
+ const transaction = yield* CurrentSessionSql;
240
+ const journal = yield* CurrentCommitJournal;
241
+ const { nativeSubjectId, requirement } = yield* validateEvidenceIn(mapping, input.evidence, true);
242
+ const existing = (yield* readFlow(mapping, input.evidence.flowId, true))[0];
243
+ if (existing !== void 0) {
244
+ const dedupUntil = yield* mapping.flow.decodeInstant(existing[mapping.flow.dedupUntil]);
245
+ if (DateTime.toEpochMillis(yield* freshNow) < DateTime.toEpochMillis(dedupUntil)) return yield* SessionConflict.make({});
246
+ yield* transaction.delete(mapping.pending.table).where(eq(pendingColumns(mapping).flowId, input.evidence.flowId));
247
+ yield* transaction.delete(mapping.flow.table).where(eq(flowColumns(mapping).flowId, input.evidence.flowId));
248
+ }
249
+ const version = yield* allocate(options.mode, mapping.pending.allocateVersion, mapping.pending.allocateVersionSync);
250
+ yield* assessAuthentication(input.evidence, requirement);
251
+ const now = yield* freshNow;
252
+ if (DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(input.expiresAt)) return yield* stale();
253
+ const record = {
254
+ ...input,
255
+ version
256
+ };
257
+ const receipt = prepare(record, journal);
258
+ yield* transaction.insert(mapping.flow.table).values(mapping.flow.encodePendingInsert({
259
+ evidence: input.evidence,
260
+ subjectId: nativeSubjectId,
261
+ pendingDigest: input.digest,
262
+ dedupUntil: input.expiresAt
263
+ }));
264
+ yield* transaction.insert(mapping.pending.table).values(mapping.pending.encodeInsert(record, {
265
+ subjectId: nativeSubjectId,
266
+ failedAttempts: 0,
267
+ consumed: false
268
+ }));
269
+ return receipt;
270
+ }).pipe(normalizeMutation(mapping))),
271
+ context: (input) => safeTransaction(inTransaction(database, readAuthenticatedPending(mapping, input, "context"))).pipe(Effect.flatMap(pendingAuthenticationContext)),
272
+ read: (input) => safeTransaction(inTransaction(database, readAuthenticatedPending(mapping, input, "record"))).pipe(Effect.map((record) => record)),
273
+ reject: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
274
+ const transaction = yield* CurrentSessionSql;
275
+ const journal = yield* CurrentCommitJournal;
276
+ const initial = (yield* readPending(mapping, input.digest, false))[0];
277
+ if (initial === void 0) return prepare({ _tag: "Rejected" }, journal);
278
+ const record = yield* mapping.pending.decodeContext(initial);
279
+ const nativeSubjectId = yield* mapping.subjectId.toNative(record.evidence.revision.subjectId);
280
+ const subject = (yield* readSubject(mapping, nativeSubjectId, true))[0];
281
+ const current = (yield* readPending(mapping, input.digest, true))[0];
282
+ const now = yield* freshNow;
283
+ const receipt = prepare({ _tag: "Rejected" }, journal);
284
+ if (subject !== void 0 && mapping.subject.isActiveStatus(subject[mapping.subject.status]) && subject[mapping.subject.securityRevision] === record.evidence.revision.securityRevision && current !== void 0 && current[mapping.pending.consumed] === false && record.evidence.bindingDigest === input.bindingDigest && DateTime.toEpochMillis(now) < DateTime.toEpochMillis(record.expiresAt)) yield* transaction.update(mapping.pending.table).set(updateValues([[mapping.pending.failedAttempts, sql`case when ${pendingColumns(mapping).failedAttempts} < ${pendingColumns(mapping).attemptLimit} then ${pendingColumns(mapping).failedAttempts} + 1 else ${pendingColumns(mapping).failedAttempts} end`]])).where(eq(pendingColumns(mapping).digest, input.digest));
285
+ return receipt;
286
+ }))
287
+ };
288
+ return {
289
+ create: (input, now, prepare) => service.create(input, now, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
290
+ context: (input) => service.context(input).pipe(Effect.provideService(LifecycleHooks, hooks)),
291
+ read: (input) => service.read(input).pipe(Effect.provideService(LifecycleHooks, hooks)),
292
+ reject: (input, prepare) => service.reject(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks))
293
+ };
294
+ });
295
+ const sessionColumns = (mapping) => ({
296
+ sessionId: column(mapping.session.table, mapping.session.sessionId),
297
+ subjectId: column(mapping.session.table, mapping.session.subjectId),
298
+ digest: column(mapping.session.table, mapping.session.digest),
299
+ version: column(mapping.session.table, mapping.session.version),
300
+ securityRevision: column(mapping.session.table, mapping.session.securityRevision),
301
+ issuedAt: column(mapping.session.table, mapping.session.issuedAt),
302
+ expiresAt: column(mapping.session.table, mapping.session.expiresAt),
303
+ absoluteExpiresAt: column(mapping.session.table, mapping.session.absoluteExpiresAt)
304
+ });
305
+ const makeSqlStatefulSessions = (database, mapping, options) => Effect.map(LifecycleHooks, (hooks) => {
306
+ const c = sessionColumns(mapping);
307
+ const persistence = {
308
+ establish: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
309
+ const transaction = yield* CurrentSessionSql;
310
+ const journal = yield* CurrentCommitJournal;
311
+ const { nativeSubjectId, requirement } = yield* validateEvidenceIn(mapping, input.evidence, true);
312
+ let flowInsert;
313
+ let pendingExpiresAt;
314
+ if (input.pending === void 0) flowInsert = yield* ensureDirectFlowAvailable(mapping, input.evidence, nativeSubjectId, input.session.absoluteExpiresAt);
315
+ else {
316
+ if (mapping.pending === void 0) return yield* invalidPending();
317
+ const pending = yield* validatePending(mapping, input.pending);
318
+ if (!preservesRevision(input.evidence, pending.evidence)) return yield* invalidPending();
319
+ pendingExpiresAt = pending.expiresAt;
320
+ }
321
+ const nativeSessionId = yield* allocate(options.mode, mapping.session.allocateId, mapping.session.allocateIdSync);
322
+ const sessionId = yield* mapping.sessionId.toSession(nativeSessionId);
323
+ const version = yield* allocate(options.mode, mapping.session.allocateVersion, mapping.session.allocateVersionSync);
324
+ const assessed = yield* assessAuthentication(input.evidence, requirement);
325
+ const now = yield* freshNow;
326
+ if (!assessed.satisfied || pendingExpiresAt !== void 0 && DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(pendingExpiresAt) || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(input.session.expiresAt) || DateTime.toEpochMillis(input.session.expiresAt) > DateTime.toEpochMillis(input.session.absoluteExpiresAt)) return yield* stale();
327
+ const record = {
328
+ ...input.session,
329
+ sessionId,
330
+ version,
331
+ subjectId: input.evidence.revision.subjectId,
332
+ securityRevision: input.evidence.revision.securityRevision,
333
+ assurance: assessed.assurance,
334
+ provenance: yield* snapshotSessionAuthenticationProvenance({ evidence: input.evidence }),
335
+ issuedAt: now
336
+ };
337
+ const receipt = prepare(record, journal);
338
+ if (flowInsert !== void 0) yield* transaction.insert(mapping.flow.table).values(flowInsert);
339
+ else yield* consumePending({
340
+ ...mapping,
341
+ pending: mapping.pending
342
+ }, input.pending, input.session.absoluteExpiresAt);
343
+ yield* transaction.insert(mapping.session.table).values(mapping.session.encodeInsert(record, {
344
+ subjectId: nativeSubjectId,
345
+ sessionId: nativeSessionId
346
+ }));
347
+ return receipt;
348
+ }).pipe(normalizeMutation(mapping))),
349
+ verify: (input) => safeTransaction(inTransaction(database, Effect.gen(function* () {
350
+ const row = (yield* (yield* CurrentSessionSql).select().from(mapping.session.table).where(eq(c.digest, input.digest)).limit(1))[0];
351
+ if (row === void 0) return yield* invalidSession();
352
+ const record = yield* mapping.session.decode(row);
353
+ const nativeSubjectId = yield* mapping.subjectId.toNative(record.subjectId);
354
+ const subject = (yield* readSubject(mapping, nativeSubjectId, false))[0];
355
+ const now = yield* freshNow;
356
+ if (subject === void 0 || !mapping.subject.isActiveStatus(subject[mapping.subject.status]) || subject[mapping.subject.securityRevision] !== record.securityRevision || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(record.expiresAt) || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(record.absoluteExpiresAt)) return yield* invalidSession();
357
+ return record;
358
+ }))),
359
+ rotate: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
360
+ const transaction = yield* CurrentSessionSql;
361
+ const journal = yield* CurrentCommitJournal;
362
+ const nativeSessionId = yield* mapping.sessionId.toNative(input.sessionId);
363
+ const initial = (yield* transaction.select().from(mapping.session.table).where(eq(c.sessionId, nativeSessionId)).limit(1))[0];
364
+ if (initial === void 0) return yield* SessionConflict.make({});
365
+ const initialRecord = yield* mapping.session.decode(initial);
366
+ const nativeSubjectId = yield* mapping.subjectId.toNative(initialRecord.subjectId);
367
+ const subject = (yield* readSubject(mapping, nativeSubjectId, true))[0];
368
+ const row = (yield* selectRows(transaction.select().from(mapping.session.table).where(eq(c.sessionId, nativeSessionId)).limit(1), options.locking))[0];
369
+ if (row === void 0) return yield* SessionConflict.make({});
370
+ const record = yield* mapping.session.decode(row);
371
+ const version = yield* allocate(options.mode, mapping.session.allocateVersion, mapping.session.allocateVersionSync);
372
+ const now = yield* freshNow;
373
+ if (subject === void 0 || !mapping.subject.isActiveStatus(subject[mapping.subject.status]) || subject[mapping.subject.securityRevision] !== input.expectedSecurityRevision || record.securityRevision !== input.expectedSecurityRevision || record.digest !== input.expectedDigest || record.version !== input.expectedVersion || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(record.expiresAt) || DateTime.toEpochMillis(now) >= DateTime.toEpochMillis(record.absoluteExpiresAt) || DateTime.toEpochMillis(input.nextExpiresAt) > DateTime.toEpochMillis(record.absoluteExpiresAt) || DateTime.toEpochMillis(input.nextExpiresAt) <= DateTime.toEpochMillis(now)) return yield* SessionConflict.make({});
374
+ const next = {
375
+ ...record,
376
+ digest: input.nextDigest,
377
+ credentialVersion: input.nextCredentialVersion,
378
+ version,
379
+ issuedAt: now,
380
+ expiresAt: input.nextExpiresAt
381
+ };
382
+ const receipt = prepare(next, journal);
383
+ yield* transaction.update(mapping.session.table).set(mapping.session.encodeRotation(next)).where(and(eq(c.sessionId, nativeSessionId), eq(c.digest, input.expectedDigest), eq(c.version, input.expectedVersion)));
384
+ return receipt;
385
+ })),
386
+ revokeDigest: (digest, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
387
+ const transaction = yield* CurrentSessionSql;
388
+ const journal = yield* CurrentCommitJournal;
389
+ const initial = (yield* transaction.select().from(mapping.session.table).where(eq(c.digest, digest)).limit(1))[0];
390
+ if (initial === void 0) return prepare(false, journal);
391
+ const record = yield* mapping.session.decode(initial);
392
+ const nativeSubjectId = yield* mapping.subjectId.toNative(record.subjectId);
393
+ yield* readSubject(mapping, nativeSubjectId, true);
394
+ const row = (yield* selectRows(transaction.select().from(mapping.session.table).where(eq(c.digest, digest)).limit(1), options.locking))[0];
395
+ const receipt = prepare(row !== void 0, journal);
396
+ if (row !== void 0) yield* transaction.delete(mapping.session.table).where(eq(c.digest, digest));
397
+ return receipt;
398
+ })),
399
+ revoke: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
400
+ const transaction = yield* CurrentSessionSql;
401
+ const journal = yield* CurrentCommitJournal;
402
+ const nativeSubjectId = yield* mapping.subjectId.toNative(input.subjectId);
403
+ const subject = (yield* readSubject(mapping, nativeSubjectId, true))[0];
404
+ if (subject === void 0 || !mapping.subject.isActiveStatus(subject[mapping.subject.status]) || subject[mapping.subject.securityRevision] !== input.expectedSecurityRevision) return yield* stale();
405
+ const nativeSessionId = yield* mapping.sessionId.toNative(input.sessionId);
406
+ const receipt = prepare(void 0, journal);
407
+ yield* transaction.delete(mapping.session.table).where(and(eq(c.subjectId, nativeSubjectId), eq(c.sessionId, nativeSessionId)));
408
+ return receipt;
409
+ })),
410
+ revokeAll: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
411
+ const transaction = yield* CurrentSessionSql;
412
+ const journal = yield* CurrentCommitJournal;
413
+ const nativeSubjectId = yield* mapping.subjectId.toNative(input.subjectId);
414
+ const subject = (yield* readSubject(mapping, nativeSubjectId, true))[0];
415
+ if (subject === void 0 || !mapping.subject.isActiveStatus(subject[mapping.subject.status]) || subject[mapping.subject.securityRevision] !== input.expectedSecurityRevision) return yield* stale();
416
+ const nextRevisionSync = mapping.subject.nextSecurityRevisionSync;
417
+ const next = yield* allocate(options.mode, mapping.subject.nextSecurityRevision?.(input.expectedSecurityRevision), nextRevisionSync === void 0 ? void 0 : () => nextRevisionSync(input.expectedSecurityRevision));
418
+ const receipt = prepare(void 0, journal);
419
+ yield* transaction.update(mapping.subject.table).set(updateValues([[mapping.subject.securityRevision, next]])).where(and(eq(authorityColumns(mapping).subjectId, nativeSubjectId), eq(authorityColumns(mapping).subjectRevision, input.expectedSecurityRevision)));
420
+ yield* transaction.delete(mapping.session.table).where(eq(c.subjectId, nativeSubjectId));
421
+ return receipt;
422
+ }))
423
+ };
424
+ const repository = { list: (input) => safeTransaction(inTransaction(database, Effect.gen(function* () {
425
+ const read = yield* CurrentSessionSql;
426
+ const nativeSubjectId = yield* mapping.subjectId.toNative(input.subjectId);
427
+ const subject = (yield* readSubject(mapping, nativeSubjectId, false))[0];
428
+ if (subject === void 0 || !mapping.subject.isActiveStatus(subject[mapping.subject.status])) return { sessions: [] };
429
+ const cursor = input.cursor === void 0 ? void 0 : yield* mapping.sessionId.toNative(input.cursor);
430
+ const now = yield* freshNow;
431
+ const rows = yield* read.select().from(mapping.session.table).where(and(eq(c.subjectId, nativeSubjectId), eq(c.securityRevision, subject[mapping.subject.securityRevision]), gt(c.expiresAt, mapping.session.encodeInstant(now)), gt(c.absoluteExpiresAt, mapping.session.encodeInstant(now)), cursor === void 0 ? void 0 : gt(c.sessionId, cursor))).orderBy(c.sessionId).limit(input.limit + 1);
432
+ const decoded = yield* Effect.forEach(rows, (row) => mapping.session.decode(row));
433
+ const codec = Schema.toCodecJson(Schema.toType(SessionMetadata));
434
+ const sessions = yield* Effect.forEach(decoded.slice(0, input.limit), (record) => Schema.encodeEffect(codec)(record).pipe(Effect.flatMap(Schema.decodeEffect(codec))));
435
+ return {
436
+ sessions,
437
+ ...decoded[input.limit] === void 0 ? {} : { nextCursor: sessions.at(-1)?.sessionId }
438
+ };
439
+ }))) };
440
+ return {
441
+ statefulSessionPersistence: {
442
+ establish: (input, prepare) => persistence.establish(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
443
+ verify: (input) => persistence.verify(input).pipe(Effect.provideService(LifecycleHooks, hooks)),
444
+ rotate: (input, prepare) => persistence.rotate(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
445
+ revokeDigest: (digest, prepare) => persistence.revokeDigest(digest, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
446
+ revoke: (input, prepare) => persistence.revoke(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
447
+ revokeAll: (input, prepare) => persistence.revokeAll(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks))
448
+ },
449
+ sessionRepository: { list: (input) => repository.list(input).pipe(Effect.provideService(LifecycleHooks, hooks)) }
450
+ };
451
+ });
452
+ const makeSqlSignedValidity = (database, mapping, options) => Effect.map(LifecycleHooks, (hooks) => {
453
+ const subject = subjectColumns(mapping);
454
+ const tombstone = {
455
+ subjectId: column(mapping.tombstone.table, mapping.tombstone.subjectId),
456
+ sessionId: column(mapping.tombstone.table, mapping.tombstone.sessionId),
457
+ absoluteExpiresAt: column(mapping.tombstone.table, mapping.tombstone.absoluteExpiresAt)
458
+ };
459
+ const service = {
460
+ verify: (session, _now) => safeTransaction(inTransaction(database, Effect.gen(function* () {
461
+ const read = yield* CurrentSessionSql;
462
+ const nativeSubjectId = yield* mapping.subjectId.toNative(session.subjectId);
463
+ const nativeSessionId = yield* mapping.sessionId.toNative(session.sessionId);
464
+ const row = (yield* readSubject(mapping, nativeSubjectId, false))[0];
465
+ if (row === void 0 || !mapping.subject.isActiveStatus(row[mapping.subject.status]) || row[mapping.subject.securityRevision] !== session.securityRevision) return yield* invalidSession();
466
+ const authoritativeNow = yield* freshNow;
467
+ if (DateTime.toEpochMillis(authoritativeNow) >= DateTime.toEpochMillis(session.expiresAt) || DateTime.toEpochMillis(authoritativeNow) >= DateTime.toEpochMillis(session.absoluteExpiresAt)) return yield* invalidSession();
468
+ if ((yield* read.select({ sessionId: tombstone.sessionId }).from(mapping.tombstone.table).where(and(eq(tombstone.subjectId, nativeSubjectId), eq(tombstone.sessionId, nativeSessionId), gt(tombstone.absoluteExpiresAt, mapping.tombstone.encodeInstant(authoritativeNow)))).limit(1)).length > 0) return yield* invalidSession();
469
+ }))),
470
+ revoke: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
471
+ const transaction = yield* CurrentSessionSql;
472
+ const journal = yield* CurrentCommitJournal;
473
+ const nativeSubjectId = yield* mapping.subjectId.toNative(input.subjectId);
474
+ const row = (yield* readSubject(mapping, nativeSubjectId, true))[0];
475
+ if (row === void 0 || !mapping.subject.isActiveStatus(row[mapping.subject.status]) || row[mapping.subject.securityRevision] !== input.expectedSecurityRevision) return yield* stale();
476
+ const nativeSessionId = yield* mapping.sessionId.toNative(input.sessionId);
477
+ const existing = yield* transaction.select().from(mapping.tombstone.table).where(and(eq(tombstone.subjectId, nativeSubjectId), eq(tombstone.sessionId, nativeSessionId))).limit(1);
478
+ const receipt = prepare(void 0, journal);
479
+ if (existing[0] === void 0) yield* transaction.insert(mapping.tombstone.table).values(mapping.tombstone.encodeInsert({
480
+ subjectId: nativeSubjectId,
481
+ sessionId: nativeSessionId,
482
+ absoluteExpiresAt: input.absoluteExpiresAt
483
+ }));
484
+ else {
485
+ const existingExpiry = yield* mapping.tombstone.decodeInstant(existing[0][mapping.tombstone.absoluteExpiresAt]);
486
+ if (DateTime.toEpochMillis(input.absoluteExpiresAt) > DateTime.toEpochMillis(existingExpiry)) yield* transaction.update(mapping.tombstone.table).set(updateValues([[mapping.tombstone.absoluteExpiresAt, mapping.tombstone.encodeInstant(input.absoluteExpiresAt)]])).where(and(eq(tombstone.subjectId, nativeSubjectId), eq(tombstone.sessionId, nativeSessionId)));
487
+ }
488
+ return receipt;
489
+ })),
490
+ revokeAll: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
491
+ const transaction = yield* CurrentSessionSql;
492
+ const journal = yield* CurrentCommitJournal;
493
+ const nativeSubjectId = yield* mapping.subjectId.toNative(input.subjectId);
494
+ const row = (yield* readSubject(mapping, nativeSubjectId, true))[0];
495
+ if (row === void 0 || !mapping.subject.isActiveStatus(row[mapping.subject.status]) || row[mapping.subject.securityRevision] !== input.expectedSecurityRevision) return yield* stale();
496
+ const nextRevisionSync = mapping.subject.nextSecurityRevisionSync;
497
+ const next = yield* allocate(options.mode, mapping.subject.nextSecurityRevision?.(input.expectedSecurityRevision), nextRevisionSync === void 0 ? void 0 : () => nextRevisionSync(input.expectedSecurityRevision));
498
+ const receipt = prepare(void 0, journal);
499
+ yield* transaction.update(mapping.subject.table).set(updateValues([[mapping.subject.securityRevision, next]])).where(and(eq(subject.subjectId, nativeSubjectId), eq(subject.subjectRevision, input.expectedSecurityRevision)));
500
+ return receipt;
501
+ }))
502
+ };
503
+ return {
504
+ verify: (session, now) => service.verify(session, now).pipe(Effect.provideService(LifecycleHooks, hooks)),
505
+ revoke: (input, prepare) => service.revoke(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
506
+ revokeAll: (input, prepare) => service.revokeAll(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks))
507
+ };
508
+ });
509
+ const stepUpColumns = (mapping) => Object.fromEntries([
510
+ "digest",
511
+ "version",
512
+ "flowId",
513
+ "subjectId",
514
+ "bindingDigest",
515
+ "snapshot",
516
+ "expiresAt",
517
+ "attemptLimit",
518
+ "failedAttempts",
519
+ "consumed"
520
+ ].map((key) => [key, column(mapping.intent.table, mapping.intent[key])]));
521
+ const stepUpLocator = Effect.fn("DrizzleStepUp.locator")(function* (mapping, digest, locking, expiresAt) {
522
+ const database = yield* CurrentSessionSql;
523
+ return yield* selectRows(database.select().from(mapping.intent.table).where(and(eq(stepUpColumns(mapping).digest, digest), expiresAt === void 0 ? void 0 : eq(stepUpColumns(mapping).expiresAt, mapping.intent.encodeInstant(expiresAt)))).limit(1), locking).pipe(Effect.map((rows) => rows[0]));
524
+ });
525
+ const stepUpAuthority = Effect.fn("DrizzleStepUp.authority")(function* (mapping, revision, locking) {
526
+ const current = yield* captureDetailsIn(mapping, revision.subjectId, revision.credentials.map((c) => c.credentialId), locking);
527
+ if (!sameStepUpRevision(current.revision, revision)) return yield* stale();
528
+ const requirement = yield* mapping.subject.decodeRequirement(current.subject);
529
+ return {
530
+ nativeSubjectId: yield* mapping.subjectId.toNative(revision.subjectId),
531
+ requirement
532
+ };
533
+ });
534
+ const stepUpSource = Effect.fn("DrizzleStepUp.source")(function* (mapping, intent, nativeSubjectId, now, locking) {
535
+ const database = yield* CurrentSessionSql;
536
+ if (!stepUpIntentLive(intent, mapping.source.kind, now)) return yield* SessionStepUpInvalid.make({});
537
+ const source = mapping.source;
538
+ if (source.kind === "StatelessSigned") return {
539
+ nativeSessionId: void 0,
540
+ row: void 0
541
+ };
542
+ const nativeSessionId = yield* source.sessionId.toNative(intent.sourceSessionId);
543
+ if (source.kind === "StateAssistedSigned") {
544
+ const t = source.tombstone;
545
+ if ((yield* selectRows(database.select().from(t.table).where(and(eq(column(t.table, t.subjectId), nativeSubjectId), eq(column(t.table, t.sessionId), nativeSessionId), gt(column(t.table, t.absoluteExpiresAt), t.encodeInstant(now)))).limit(1), locking)).length > 0) return yield* SessionStepUpInvalid.make({});
546
+ return {
547
+ nativeSessionId,
548
+ row: void 0
549
+ };
550
+ }
551
+ const s = source.session, c = sessionColumns(source);
552
+ const row = (yield* selectRows(database.select().from(s.table).where(and(eq(c.sessionId, nativeSessionId), eq(c.subjectId, nativeSubjectId), eq(c.securityRevision, intent.revision.securityRevision), eq(column(s.table, s.credentialVersion), intent.sourceCredentialVersion), eq(column(s.table, s.authenticatedAt), s.encodeInstant(intent.sourceAuthenticatedAt)), eq(c.expiresAt, s.encodeInstant(intent.sourceExpiresAt)), eq(c.absoluteExpiresAt, s.encodeInstant(intent.sourceAbsoluteExpiresAt)), gt(c.expiresAt, s.encodeInstant(now)), gt(c.absoluteExpiresAt, s.encodeInstant(now)))).limit(1), locking))[0];
553
+ if (row === void 0) return yield* SessionStepUpInvalid.make({});
554
+ return {
555
+ nativeSessionId,
556
+ row
557
+ };
558
+ });
559
+ const readSqlStepUp = Effect.fn("DrizzleStepUp.read")(function* (mapping, digest, locking) {
560
+ const first = yield* stepUpLocator(mapping, digest, false);
561
+ if (first === void 0) return yield* SessionStepUpInvalid.make({});
562
+ const intent = yield* decodeStepUpIntent(first[mapping.intent.snapshot]);
563
+ const authority = yield* stepUpAuthority(mapping, intent.revision, locking);
564
+ const source = yield* stepUpSource(mapping, intent, authority.nativeSubjectId, yield* freshNow, locking);
565
+ const row = yield* stepUpLocator(mapping, digest, locking, intent.expiresAt);
566
+ const m = mapping.intent;
567
+ if (row === void 0 || row[m.snapshot] !== first[m.snapshot] || row[m.version] !== intent.version || row[m.digest] !== intent.digest || digest !== intent.digest || row[m.flowId] !== intent.flowId || row[m.bindingDigest] !== intent.bindingDigest || !mapping.subjectId.equals(row[m.subjectId], authority.nativeSubjectId) || Boolean(row[m.consumed]) || !Schema.is(Schema.Natural)(row[m.failedAttempts]) || row[m.failedAttempts] >= row[m.attemptLimit] || row[m.attemptLimit] !== intent.attemptLimit || !stepUpIntentLive(intent, mapping.source.kind, yield* freshNow)) return yield* SessionStepUpInvalid.make({});
568
+ return {
569
+ row,
570
+ intent,
571
+ source,
572
+ ...authority
573
+ };
574
+ });
575
+ const isSqlStepUpRejectAbsence = (error) => {
576
+ const tag = typeof error === "object" && error !== null ? Reflect.get(error, "_tag") : void 0;
577
+ return tag === "SessionStepUpInvalid" || tag === "StaleAuthentication";
578
+ };
579
+ const recoverSqlStepUpRejectAbsence = (effect, rejected) => effect.pipe(Effect.catchCause((cause) => {
580
+ if (cause.reasons.length > 0 && cause.reasons.every((reason) => Cause.isFailReason(reason) && isSqlStepUpRejectAbsence(reason.error))) return Effect.succeed(rejected);
581
+ return Effect.failCause(Cause.map(cause, (error) => isSqlStepUpRejectAbsence(error) ? unavailable() : error));
582
+ }));
583
+ /** Shared implementation; public driver entrypoints restore concrete tables/IDs. */
584
+ const makeSqlSessionStepUp = (database, mapping, options) => Effect.map(LifecycleHooks, (hooks) => {
585
+ const m = mapping.intent, c = stepUpColumns(mapping);
586
+ const read = (digest) => mapFailureCause(safeTransaction(inTransaction(database, readSqlStepUp(mapping, digest, options.locking))), (error) => error._tag === "StaleAuthentication" ? SessionStepUpInvalid.make({}) : error);
587
+ const service = {
588
+ create: (input, _now, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
589
+ const tx = yield* CurrentSessionSql;
590
+ const journal = yield* CurrentCommitJournal;
591
+ const authority = yield* stepUpAuthority(mapping, input.revision, options.locking);
592
+ const version = yield* allocate(options.mode, m.allocateVersion, m.allocateVersionSync);
593
+ const record = {
594
+ ...input,
595
+ version
596
+ };
597
+ yield* stepUpSource(mapping, record, authority.nativeSubjectId, yield* freshNow, options.locking);
598
+ if ((yield* selectRows(tx.select().from(m.table).where(or(eq(c.digest, input.digest), eq(c.flowId, input.flowId))).limit(1), options.locking)).length > 0) return yield* SessionConflict.make({});
599
+ const snapshot = yield* encodeStepUpIntent(record);
600
+ const values = {
601
+ ...m.encodeInsert(record, { subjectId: authority.nativeSubjectId }),
602
+ ...updateValues([
603
+ [m.digest, record.digest],
604
+ [m.version, version],
605
+ [m.flowId, record.flowId],
606
+ [m.subjectId, authority.nativeSubjectId],
607
+ [m.bindingDigest, record.bindingDigest],
608
+ [m.snapshot, snapshot],
609
+ [m.expiresAt, m.encodeInstant(record.expiresAt)],
610
+ [m.attemptLimit, record.attemptLimit],
611
+ [m.failedAttempts, 0],
612
+ [m.consumed, false]
613
+ ])
614
+ };
615
+ const receipt = prepare(record, journal);
616
+ yield* tx.insert(m.table).values(values).pipe(normalizeMutation(mapping));
617
+ if ((yield* tx.select().from(m.table).where(and(eq(c.digest, record.digest), eq(c.version, version), eq(c.flowId, record.flowId), eq(c.subjectId, authority.nativeSubjectId), eq(c.bindingDigest, record.bindingDigest), eq(c.snapshot, snapshot), eq(c.expiresAt, m.encodeInstant(record.expiresAt)), eq(c.attemptLimit, record.attemptLimit), eq(c.failedAttempts, 0), eq(c.consumed, false))).limit(1))[0] === void 0) return yield* unavailable();
618
+ return receipt;
619
+ })).pipe((effect) => mapFailureCause(effect, (error) => error._tag === "SessionStepUpInvalid" ? stale() : error)),
620
+ context: (input) => mapFailureCause(read(input.digest).pipe(Effect.flatMap(({ intent }) => snapshotPendingAuthenticationContext({
621
+ flowId: intent.flowId,
622
+ bindingDigest: intent.bindingDigest,
623
+ revision: intent.revision,
624
+ expiresAtMillis: DateTime.toEpochMillis(intent.expiresAt)
625
+ }))), (error) => error._tag === "PendingAuthenticationInvalid" ? unavailable() : error),
626
+ read: (input) => read(input.digest).pipe(Effect.flatMap((value) => value.intent.bindingDigest === input.bindingDigest ? Effect.succeed(value.intent) : Effect.fail(SessionStepUpInvalid.make({})))),
627
+ reject: (input, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
628
+ const tx = yield* CurrentSessionSql;
629
+ const journal = yield* CurrentCommitJournal;
630
+ const selected = yield* recoverSqlStepUpRejectAbsence(readSqlStepUp(mapping, input.digest, options.locking).pipe(Effect.map((value) => ({
631
+ _tag: "Found",
632
+ value
633
+ }))), { _tag: "Rejected" });
634
+ if (selected._tag === "Rejected") return prepare({ _tag: "Rejected" }, journal);
635
+ const { row, intent } = selected.value;
636
+ const receipt = prepare({ _tag: "Rejected" }, journal);
637
+ yield* tx.update(m.table).set(updateValues([[m.failedAttempts, sql`${c.failedAttempts} + 1`]])).where(and(eq(c.digest, input.digest), eq(c.snapshot, row[m.snapshot]), eq(c.version, intent.version), eq(c.consumed, false), sql`${c.failedAttempts} < ${c.attemptLimit}`));
638
+ const written = yield* stepUpLocator(mapping, input.digest, false);
639
+ if (written === void 0 || written[m.version] !== intent.version || written[m.snapshot] !== row[m.snapshot] || written[m.failedAttempts] !== row[m.failedAttempts] + 1) return yield* unavailable();
640
+ return receipt;
641
+ })),
642
+ complete: (plan, prepare) => owned(database, options, mapping.isConstraintConflict, Effect.gen(function* () {
643
+ const tx = yield* CurrentSessionSql;
644
+ const journal = yield* CurrentCommitJournal;
645
+ yield* validateStepUpPlan(plan);
646
+ const current = yield* stepUpAuthority(mapping, plan.evidence.revision, options.locking);
647
+ const stored = yield* readSqlStepUp(mapping, plan.intent.digest, options.locking);
648
+ if ((yield* encodeStepUpIntent(stored.intent)) !== (yield* encodeStepUpIntent(plan.intent))) return yield* SessionStepUpInvalid.make({});
649
+ const base = yield* assessAuthentication(plan.evidence, current.requirement).pipe(Effect.mapError(() => stale()));
650
+ const profile = yield* assessAuthentication(plan.evidence, stored.intent.requirement).pipe(Effect.mapError(() => stale()));
651
+ if (!base.satisfied || !profile.satisfied) return yield* stale();
652
+ const replacement = plan.replacement, now = yield* freshNow;
653
+ if (DateTime.toEpochMillis(replacement.inspection.session.expiresAt) > DateTime.toEpochMillis(stored.intent.sourceAbsoluteExpiresAt) || DateTime.toEpochMillis(now) < DateTime.toEpochMillis(replacement.inspection.session.issuedAt) || DateTime.toEpochMillis(now) >= Math.min(DateTime.toEpochMillis(replacement.inspection.session.expiresAt), DateTime.toEpochMillis(stored.intent.expiresAt))) return yield* SessionStepUpInvalid.make({});
654
+ let rotation;
655
+ if (replacement._tag === "Stateful") {
656
+ if (mapping.source.kind !== "Stateful") return yield* SessionStepUpInvalid.make({});
657
+ const s = mapping.source.session, row = stored.source.row;
658
+ if (row[s.digest] !== replacement.expectedDigest || row[s.version] !== replacement.expectedRowVersion) return yield* SessionConflict.make({});
659
+ const version = yield* allocate(options.mode, s.allocateVersion, s.allocateVersionSync);
660
+ const next = {
661
+ ...replacement.inspection.session,
662
+ provenance: replacement.inspection.provenance,
663
+ credentialVersion: replacement.inspection.credentialVersion,
664
+ digest: replacement.nextDigest,
665
+ version
666
+ };
667
+ rotation = {
668
+ ...s.encodeRotation(next),
669
+ ...updateValues([
670
+ [s.version, version],
671
+ [s.digest, next.digest],
672
+ [s.credentialVersion, next.credentialVersion],
673
+ [s.authenticatedAt, s.encodeInstant(next.assurance.authenticatedAt)],
674
+ [s.issuedAt, s.encodeInstant(next.issuedAt)],
675
+ [s.expiresAt, s.encodeInstant(next.expiresAt)],
676
+ [s.absoluteExpiresAt, s.encodeInstant(next.absoluteExpiresAt)]
677
+ ])
678
+ };
679
+ }
680
+ const completionVersion = yield* allocate(options.mode, m.allocateVersion, m.allocateVersionSync);
681
+ if (completionVersion === stored.intent.version) return yield* unavailable();
682
+ const completionSnapshot = yield* encodeStepUpIntent({
683
+ ...stored.intent,
684
+ version: completionVersion
685
+ });
686
+ const receipt = prepare(replacement.inspection, journal);
687
+ if (replacement._tag === "Stateful" && mapping.source.kind === "Stateful") {
688
+ const s = mapping.source.session, sc = sessionColumns(mapping.source);
689
+ yield* tx.update(s.table).set(rotation).where(and(eq(sc.sessionId, stored.source.nativeSessionId), eq(sc.digest, replacement.expectedDigest), eq(sc.version, replacement.expectedRowVersion)));
690
+ const written = (yield* tx.select().from(s.table).where(eq(sc.sessionId, stored.source.nativeSessionId)).limit(1))[0];
691
+ if (written === void 0 || written[s.version] !== rotation[s.version]) return yield* unavailable();
692
+ const decoded = yield* s.decode(written);
693
+ if (decoded.version !== rotation[s.version] || !stepUpRotationMatches(plan, decoded)) return yield* unavailable();
694
+ } else if (replacement._tag === "StateAssistedSigned" && mapping.source.kind === "StateAssistedSigned") {
695
+ const t = mapping.source.tombstone;
696
+ const owner = column(t.table, t.subjectId), id = column(t.table, t.sessionId), expiry = column(t.table, t.absoluteExpiresAt);
697
+ yield* tx.delete(t.table).where(and(eq(owner, stored.nativeSubjectId), eq(id, stored.source.nativeSessionId), lte(expiry, t.encodeInstant(yield* freshNow))));
698
+ const values = t.encodeInsert({
699
+ subjectId: stored.nativeSubjectId,
700
+ sessionId: stored.source.nativeSessionId,
701
+ absoluteExpiresAt: replacement.tombstoneUntil
702
+ });
703
+ yield* tx.insert(t.table).values(values).pipe(normalizeMutation(mapping));
704
+ if ((yield* tx.select().from(t.table).where(and(eq(owner, stored.nativeSubjectId), eq(id, stored.source.nativeSessionId), eq(expiry, t.encodeInstant(replacement.tombstoneUntil)))).limit(1))[0] === void 0) return yield* unavailable();
705
+ }
706
+ yield* tx.update(m.table).set(updateValues([
707
+ [m.consumed, true],
708
+ [m.version, completionVersion],
709
+ [m.snapshot, completionSnapshot]
710
+ ])).where(and(eq(c.digest, stored.intent.digest), eq(c.version, stored.intent.version), eq(c.snapshot, stored.row[m.snapshot]), eq(c.consumed, false), eq(c.failedAttempts, stored.row[m.failedAttempts])));
711
+ const completed = yield* stepUpLocator(mapping, stored.intent.digest, false);
712
+ if (completed === void 0 || !completed[m.consumed] || completed[m.version] !== completionVersion || completed[m.snapshot] !== completionSnapshot) return yield* unavailable();
713
+ const commitNow = yield* freshNow;
714
+ if (!stepUpIntentLive(stored.intent, mapping.source.kind, commitNow) || DateTime.toEpochMillis(commitNow) >= DateTime.toEpochMillis(replacement.inspection.session.expiresAt) || !(yield* assessAuthentication(plan.evidence, current.requirement).pipe(Effect.mapError(() => stale()))).satisfied || !(yield* assessAuthentication(plan.evidence, stored.intent.requirement).pipe(Effect.mapError(() => stale()))).satisfied) return yield* stale();
715
+ return receipt;
716
+ }))
717
+ };
718
+ return {
719
+ create: (input, now, prepare) => service.create(input, now, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
720
+ context: (input) => service.context(input).pipe(Effect.provideService(LifecycleHooks, hooks)),
721
+ read: (input) => service.read(input).pipe(Effect.provideService(LifecycleHooks, hooks)),
722
+ reject: (input, prepare) => service.reject(input, prepare).pipe(Effect.provideService(LifecycleHooks, hooks)),
723
+ complete: (plan, prepare) => service.complete(plan, prepare).pipe(Effect.provideService(LifecycleHooks, hooks))
724
+ };
725
+ });
726
+ return {
727
+ makeSqlAuthenticationAuthority,
728
+ makeSqlPendingAuthentication,
729
+ makeSqlStatefulSessions,
730
+ makeSqlSignedValidity,
731
+ makeSqlSessionStepUp
732
+ };
733
+ };
734
+ //#endregion
735
+ export { CurrentSessionSql, makeSessionKernel };
736
+
737
+ //# sourceMappingURL=session-kernel.mjs.map