@yielded/auth-persistence-drizzle 0.1.0-beta.1 → 0.1.0-beta.13
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.
- package/dist/D1.d.mts +23 -18
- package/dist/D1.mjs +10 -4
- package/dist/D1.mjs.map +1 -1
- package/dist/Libsql.d.mts +58 -53
- package/dist/Libsql.mjs +20 -15
- package/dist/Libsql.mjs.map +1 -1
- package/dist/Mysql2.d.mts +58 -46
- package/dist/Mysql2.mjs +13 -6
- package/dist/Mysql2.mjs.map +1 -1
- package/dist/Pglite.d.mts +52 -41
- package/dist/Pglite.mjs +12 -7
- package/dist/Pglite.mjs.map +1 -1
- package/dist/Postgres.d.mts +59 -48
- package/dist/Postgres.mjs +12 -7
- package/dist/Postgres.mjs.map +1 -1
- package/dist/SqliteBun.d.mts +67 -62
- package/dist/SqliteBun.mjs +20 -14
- package/dist/SqliteBun.mjs.map +1 -1
- package/dist/SqliteDo.d.mts +58 -52
- package/dist/SqliteDo.mjs +26 -14
- package/dist/SqliteDo.mjs.map +1 -1
- package/dist/SqliteNode.d.mts +58 -53
- package/dist/SqliteNode.mjs +20 -14
- package/dist/SqliteNode.mjs.map +1 -1
- package/dist/SqliteWasm.d.mts +58 -53
- package/dist/SqliteWasm.mjs +20 -14
- package/dist/SqliteWasm.mjs.map +1 -1
- package/dist/drizzle/d1-database.d.mts +11 -0
- package/dist/drizzle/d1-database.mjs +8 -0
- package/dist/drizzle/d1-database.mjs.map +1 -0
- package/dist/drizzle/d1-emails.d.mts +8 -7
- package/dist/drizzle/d1-emails.mjs +7 -4
- package/dist/drizzle/d1-emails.mjs.map +1 -1
- package/dist/drizzle/d1-identity.mjs +12 -9
- package/dist/drizzle/d1-identity.mjs.map +1 -1
- package/dist/drizzle/d1-oauth.d.mts +10 -9
- package/dist/drizzle/d1-oauth.mjs +7 -4
- package/dist/drizzle/d1-oauth.mjs.map +1 -1
- package/dist/drizzle/d1-passkey.d.mts +3 -14
- package/dist/drizzle/d1-passkey.mjs +2 -1
- package/dist/drizzle/d1-passkey.mjs.map +1 -1
- package/dist/drizzle/d1-password-prepared.d.mts +4 -3
- package/dist/drizzle/d1-password-prepared.mjs +3 -1
- package/dist/drizzle/d1-password-prepared.mjs.map +1 -1
- package/dist/drizzle/d1-passwords.d.mts +6 -5
- package/dist/drizzle/d1-passwords.mjs +11 -7
- package/dist/drizzle/d1-passwords.mjs.map +1 -1
- package/dist/drizzle/d1-phone.d.mts +3 -4
- package/dist/drizzle/d1-phone.mjs +2 -1
- package/dist/drizzle/d1-phone.mjs.map +1 -1
- package/dist/drizzle/d1-planning.d.mts +1 -1
- package/dist/drizzle/d1-proofs.d.mts +4 -3
- package/dist/drizzle/d1-proofs.mjs +3 -1
- package/dist/drizzle/d1-proofs.mjs.map +1 -1
- package/dist/drizzle/d1-sessions.d.mts +11 -10
- package/dist/drizzle/d1-sessions.mjs +15 -9
- package/dist/drizzle/d1-sessions.mjs.map +1 -1
- package/dist/drizzle/d1-totp.d.mts +3 -4
- package/dist/drizzle/d1-totp.mjs +2 -1
- package/dist/drizzle/d1-totp.mjs.map +1 -1
- package/dist/drizzle/email-registration.mjs +2 -1
- package/dist/drizzle/email-registration.mjs.map +1 -1
- package/dist/drizzle/email-target.d.mts +7 -6
- package/dist/drizzle/email-target.mjs +10 -10
- package/dist/drizzle/email-target.mjs.map +1 -1
- package/dist/drizzle/mysql-database.d.mts +8 -0
- package/dist/drizzle/mysql-database.mjs +8 -0
- package/dist/drizzle/mysql-database.mjs.map +1 -0
- package/dist/drizzle/mysql-emails.d.mts +7 -6
- package/dist/drizzle/mysql-emails.mjs +12 -8
- package/dist/drizzle/mysql-emails.mjs.map +1 -1
- package/dist/drizzle/mysql-identity.mjs +12 -9
- package/dist/drizzle/mysql-identity.mjs.map +1 -1
- package/dist/drizzle/mysql-password-prepared.d.mts +3 -2
- package/dist/drizzle/mysql-password-prepared.mjs +6 -2
- package/dist/drizzle/mysql-password-prepared.mjs.map +1 -1
- package/dist/drizzle/mysql-passwords.d.mts +6 -4
- package/dist/drizzle/mysql-passwords.mjs +11 -7
- package/dist/drizzle/mysql-passwords.mjs.map +1 -1
- package/dist/drizzle/mysql-proofs.d.mts +3 -2
- package/dist/drizzle/mysql-proofs.mjs +8 -4
- package/dist/drizzle/mysql-proofs.mjs.map +1 -1
- package/dist/drizzle/mysql-sessions.d.mts +11 -10
- package/dist/drizzle/mysql-sessions.mjs +16 -12
- package/dist/drizzle/mysql-sessions.mjs.map +1 -1
- package/dist/drizzle/native-database.mjs +10 -0
- package/dist/drizzle/native-database.mjs.map +1 -0
- package/dist/drizzle/oauth-connected-drivers.mjs +7 -5
- package/dist/drizzle/oauth-connected-drivers.mjs.map +1 -1
- package/dist/drizzle/oauth-connected-settlement.mjs +3 -2
- package/dist/drizzle/oauth-connected-settlement.mjs.map +1 -1
- package/dist/drizzle/oauth-connected-sign-in.mjs +4 -3
- package/dist/drizzle/oauth-connected-sign-in.mjs.map +1 -1
- package/dist/drizzle/oauth-connected-target.d.mts +6 -7
- package/dist/drizzle/oauth-connected-target.mjs +4 -5
- package/dist/drizzle/oauth-connected-target.mjs.map +1 -1
- package/dist/drizzle/oauth-drivers.mjs +8 -6
- package/dist/drizzle/oauth-drivers.mjs.map +1 -1
- package/dist/drizzle/oauth-target.d.mts +12 -11
- package/dist/drizzle/oauth-target.mjs +13 -12
- package/dist/drizzle/oauth-target.mjs.map +1 -1
- package/dist/drizzle/passkey-drivers.mjs +8 -6
- package/dist/drizzle/passkey-drivers.mjs.map +1 -1
- package/dist/drizzle/passkey-write-drivers.mjs +5 -3
- package/dist/drizzle/passkey-write-drivers.mjs.map +1 -1
- package/dist/drizzle/passkey-write-target.d.mts +1 -1
- package/dist/drizzle/password-prepared-sql.mjs +2 -1
- package/dist/drizzle/password-prepared-sql.mjs.map +1 -1
- package/dist/drizzle/password-prepared-target.d.mts +3 -2
- package/dist/drizzle/password-prepared-target.mjs +4 -3
- package/dist/drizzle/password-prepared-target.mjs.map +1 -1
- package/dist/drizzle/password-registration.mjs +2 -1
- package/dist/drizzle/password-registration.mjs.map +1 -1
- package/dist/drizzle/password-target.d.mts +5 -4
- package/dist/drizzle/password-target.mjs +8 -8
- package/dist/drizzle/password-target.mjs.map +1 -1
- package/dist/drizzle/pg-database.d.mts +9 -0
- package/dist/drizzle/pg-database.mjs +8 -0
- package/dist/drizzle/pg-database.mjs.map +1 -0
- package/dist/drizzle/pg-emails.d.mts +7 -6
- package/dist/drizzle/pg-emails.mjs +12 -8
- package/dist/drizzle/pg-emails.mjs.map +1 -1
- package/dist/drizzle/pg-identity.mjs +12 -9
- package/dist/drizzle/pg-identity.mjs.map +1 -1
- package/dist/drizzle/pg-password-prepared.d.mts +3 -2
- package/dist/drizzle/pg-password-prepared.mjs +6 -2
- package/dist/drizzle/pg-password-prepared.mjs.map +1 -1
- package/dist/drizzle/pg-passwords.d.mts +6 -4
- package/dist/drizzle/pg-passwords.mjs +11 -7
- package/dist/drizzle/pg-passwords.mjs.map +1 -1
- package/dist/drizzle/pg-proofs.d.mts +3 -2
- package/dist/drizzle/pg-proofs.mjs +8 -4
- package/dist/drizzle/pg-proofs.mjs.map +1 -1
- package/dist/drizzle/pg-sessions.d.mts +11 -10
- package/dist/drizzle/pg-sessions.mjs +16 -12
- package/dist/drizzle/pg-sessions.mjs.map +1 -1
- package/dist/drizzle/phone-target.d.mts +4 -3
- package/dist/drizzle/phone-target.mjs +12 -11
- package/dist/drizzle/phone-target.mjs.map +1 -1
- package/dist/drizzle/proof-target.d.mts +3 -2
- package/dist/drizzle/proof-target.mjs +5 -5
- package/dist/drizzle/proof-target.mjs.map +1 -1
- package/dist/drizzle/session-sql.d.mts +1 -0
- package/dist/drizzle/session-target.d.mts +10 -8
- package/dist/drizzle/session-target.mjs +11 -11
- package/dist/drizzle/session-target.mjs.map +1 -1
- package/dist/drizzle/sqlite-emails.mjs +9 -5
- package/dist/drizzle/sqlite-emails.mjs.map +1 -1
- package/dist/drizzle/sqlite-identity.mjs +14 -11
- package/dist/drizzle/sqlite-identity.mjs.map +1 -1
- package/dist/drizzle/sqlite-password-prepared.mjs +7 -3
- package/dist/drizzle/sqlite-password-prepared.mjs.map +1 -1
- package/dist/drizzle/sqlite-passwords.mjs +10 -6
- package/dist/drizzle/sqlite-passwords.mjs.map +1 -1
- package/dist/drizzle/sqlite-proofs.mjs +7 -3
- package/dist/drizzle/sqlite-proofs.mjs.map +1 -1
- package/dist/drizzle/sqlite-sessions.mjs +16 -12
- package/dist/drizzle/sqlite-sessions.mjs.map +1 -1
- package/dist/drizzle/standalone-guard.d.mts +2 -0
- package/dist/drizzle/standalone-guard.mjs +8 -4
- package/dist/drizzle/standalone-guard.mjs.map +1 -1
- package/dist/drizzle/totp-target.d.mts +4 -3
- package/dist/drizzle/totp-target.mjs +31 -28
- package/dist/drizzle/totp-target.mjs.map +1 -1
- package/package.json +1 -1
- package/src/D1.ts +37 -10
- package/src/Libsql.ts +45 -17
- package/src/Mysql2.ts +39 -13
- package/src/Pglite.ts +47 -13
- package/src/Postgres.ts +47 -13
- package/src/SqliteBun.ts +58 -30
- package/src/SqliteDo.ts +61 -19
- package/src/SqliteNode.ts +55 -28
- package/src/SqliteWasm.ts +55 -28
- package/src/drizzle/d1-database.ts +10 -0
- package/src/drizzle/d1-emails.ts +84 -84
- package/src/drizzle/d1-identity.ts +17 -20
- package/src/drizzle/d1-oauth.ts +19 -8
- package/src/drizzle/d1-passkey.ts +5 -1
- package/src/drizzle/d1-password-prepared.ts +38 -37
- package/src/drizzle/d1-passwords.ts +118 -108
- package/src/drizzle/d1-phone.ts +5 -1
- package/src/drizzle/d1-proofs.ts +29 -30
- package/src/drizzle/d1-sessions.ts +51 -38
- package/src/drizzle/d1-totp.ts +5 -1
- package/src/drizzle/email-registration.ts +6 -2
- package/src/drizzle/email-target.ts +17 -19
- package/src/drizzle/mysql-database.ts +8 -0
- package/src/drizzle/mysql-emails.ts +28 -16
- package/src/drizzle/mysql-identity.ts +18 -21
- package/src/drizzle/mysql-password-prepared.ts +10 -8
- package/src/drizzle/mysql-passwords.ts +21 -9
- package/src/drizzle/mysql-proofs.ts +16 -5
- package/src/drizzle/mysql-sessions.ts +40 -17
- package/src/drizzle/native-database.ts +22 -0
- package/src/drizzle/oauth-connected-drivers.ts +18 -6
- package/src/drizzle/oauth-connected-settlement.ts +5 -3
- package/src/drizzle/oauth-connected-sign-in.ts +7 -3
- package/src/drizzle/oauth-connected-target.ts +16 -17
- package/src/drizzle/oauth-drivers.ts +26 -10
- package/src/drizzle/oauth-target.ts +30 -42
- package/src/drizzle/passkey-drivers.ts +21 -13
- package/src/drizzle/passkey-write-drivers.ts +11 -6
- package/src/drizzle/password-prepared-sql.ts +2 -4
- package/src/drizzle/password-prepared-target.ts +9 -6
- package/src/drizzle/password-registration.ts +7 -8
- package/src/drizzle/password-target.ts +19 -18
- package/src/drizzle/pg-database.ts +10 -0
- package/src/drizzle/pg-emails.ts +28 -16
- package/src/drizzle/pg-identity.ts +18 -22
- package/src/drizzle/pg-password-prepared.ts +10 -8
- package/src/drizzle/pg-passwords.ts +21 -9
- package/src/drizzle/pg-proofs.ts +16 -5
- package/src/drizzle/pg-sessions.ts +40 -17
- package/src/drizzle/phone-target.ts +22 -17
- package/src/drizzle/proof-target.ts +9 -12
- package/src/drizzle/session-target.ts +32 -50
- package/src/drizzle/sqlite-emails.ts +30 -13
- package/src/drizzle/sqlite-identity.ts +22 -42
- package/src/drizzle/sqlite-password-prepared.ts +23 -9
- package/src/drizzle/sqlite-passwords.ts +29 -15
- package/src/drizzle/sqlite-proofs.ts +28 -5
- package/src/drizzle/sqlite-sessions.ts +49 -23
- package/src/drizzle/standalone-guard.ts +18 -6
- package/src/drizzle/totp-target.ts +61 -60
- package/dist/drizzle/d1-identity.d.mts +0 -30
- package/dist/drizzle/mysql-identity.d.mts +0 -21
- package/dist/drizzle/pg-identity.d.mts +0 -22
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"d1-password-prepared.mjs","names":["kernel","and","shared"],"sources":["../../src/drizzle/d1-password-prepared.ts"],"sourcesContent":["/* oxlint-disable no-explicit-any -- driver exports preserve concrete consumer mappings. */\nimport type { D1Client } from \"@effect/sql-d1/D1Client\";\nimport {\n coordinateCommit,\n CurrentCommitJournal,\n hasCommitScope,\n type CommitJournal,\n type PreparedCommit,\n LifecycleHooks,\n HookConfigurationError,\n} from \"@yielded/auth/Hooks\";\nimport {\n PasswordRejected,\n PasswordUnavailable,\n PasswordPreparedVersion,\n decodePasswordPreparedReady,\n encodePasswordPreparedReady,\n snapshotPasswordPreparedReady,\n snapshotPasswordPreparedReservation,\n type PasswordPreparedReady,\n type PasswordPreparedReservation,\n type PasswordMutationDecision,\n type PreparePasswordCommit,\n type PasswordPreparedMutation,\n type PasswordPreparedPersistence,\n} from \"@yielded/auth/Password\";\nimport { reportPersistenceFailure } from \"@yielded/auth/Persistence\";\nimport { type ProofCompletionPlan, ProofUnavailable, ProofBinding } from \"@yielded/auth/Proofs\";\nimport { eq, is, isNotNull, lte, or, SQL, sql, type AnyRelations, type Table } from \"drizzle-orm\";\nimport type { EffectSQLiteD1Database } from \"drizzle-orm/effect-d1\";\nimport type { AnySQLiteTable } from \"drizzle-orm/sqlite-core\";\nimport { Cause, DateTime, Effect, Predicate, Redacted, Schema, Context } from \"effect\";\nimport type { Statement } from \"effect/sql/Statement\";\n\nimport { balancedD1And as and, compactD1GeneratedStatement } from \"./d1-generated-statement\";\nimport { passwordD1Kernel as kernel } from \"./d1-passwords\";\nimport { CurrentD1PlanningDatabase, makeD1Owner } from \"./d1-planning\";\nimport { checkD1ProofCompletion, compileD1ProofCompletionPlan } from \"./d1-proofs\";\nimport { D1BatchStatements } from \"./D1BatchStatements\";\nimport { PersistenceMappingError, column, updateValues } from \"./model\";\nimport type {\n D1PasswordPreparedPersistenceMapping,\n D1PasswordPreparedProofMapping,\n} from \"./password-prepared-model\";\nimport { passwordPreparedSqlKernel as shared } from \"./password-prepared-sql\";\nimport {\n ContextInput,\n CompletionInput,\n encodeReservation,\n evidenceCurrent,\n identifierScope,\n reservationOf,\n sameRevision,\n snapshotMutation,\n snapshotReserve,\n unavailable,\n} from \"./password-prepared-state\";\nimport { CurrentPasswordSql, type PasswordSqlDatabase } from \"./password-sql\";\nimport type { SuppliedService } from \"./SuppliedService\";\n\ntype PlanPrepare<Method extends (...args: any[]) => any, A> = (\n value: Parameters<Parameters<Method>[1]>[0],\n journal: CommitJournal,\n) => PreparedCommit<A>;\n\ntype Database = EffectSQLiteD1Database<AnyRelations> & { readonly $client: D1Client };\ntype Mapping = D1PasswordPreparedPersistenceMapping<\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n unknown\n>;\ninterface Planned<A> {\n readonly retryable?: (cause: unknown) => boolean;\n readonly receipt: PreparedCommit<A>;\n readonly statements: ReadonlyArray<Statement<any>>;\n readonly postconditions?: ReadonlyArray<Statement<any>>;\n readonly journalGuard?: PreparedCommit<void>;\n}\n\nconst everyFailureMatches = (\n cause: Cause.Cause<unknown>,\n classify: ((cause: unknown) => boolean) | undefined,\n): boolean =>\n classify !== undefined &&\n cause.reasons.length > 0 &&\n cause.reasons.every((reason) => Cause.isFailReason(reason) && classify(Cause.fail(reason.error)));\n\nconst bindingJson = Schema.encodeSync(Schema.fromJsonString(ProofBinding));\n\nconst authorityCondition = (mapping: Mapping, current: any, moduleId: string) => {\n const p = mapping.password,\n s = kernel.subjectColumns(p),\n i = kernel.identifierColumns(p),\n c = kernel.credentialColumns(p),\n ac = kernel.authorityColumns(p);\n\n const snapshot = current.snapshot,\n native = current.nativeSubjectId;\n\n const identifier =\n snapshot === undefined\n ? sql`true`\n : and(\n p.identifier.d1CurrentCondition({\n identifier: snapshot.identifier,\n nativeSubjectId: native,\n }),\n sql`exists(select 1 from ${p.identifier.table} where ${i.namespace} = ${sql.param(snapshot.identifier.namespace, i.namespace)} and ${i.value} = ${sql.param(snapshot.identifier.value, i.value)} and ${i.subjectId} = ${sql.param(native, i.subjectId)} and ${i.bindingRevision} = ${sql.param(snapshot.identifierBindingRevision, i.bindingRevision)} and ${Predicate.isNullish(current.identifier[p.identifier.verifiedAt]) ? sql`${i.verifiedAt} is null` : sql`${i.verifiedAt} = ${sql.param(current.identifier[p.identifier.verifiedAt], i.verifiedAt)}`})`,\n )!;\n\n return and(\n sql`exists(select 1 from ${p.subject.table} where ${s.id} = ${sql.param(native, s.id)} and ${s.status} = ${sql.param(p.subject.d1ActiveStatusValue, s.status)} and ${s.securityRevision} = ${sql.param(current.revision.securityRevision, s.securityRevision)})`,\n identifier,\n snapshot === undefined\n ? sql`not exists(select 1 from ${p.credential.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(native, c.subjectId)})`\n : sql`exists(select 1 from ${p.credential.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(native, c.subjectId)} and ${c.credentialId} = ${sql.param(snapshot.credentialId, c.credentialId)} and ${c.credentialRevision} = ${sql.param(snapshot.credentialRevision, c.credentialRevision)} and ${c.verifierVersion} = ${sql.param(snapshot.verifierVersion, c.verifierVersion)} and ${c.verifier} = ${sql.param(Redacted.value(snapshot.verifier), c.verifier)} and ${c.normalization} = ${sql.param(snapshot.normalization, c.normalization)})`,\n ...current.revision.credentials.map(\n (entry: any) =>\n sql`exists(select 1 from ${p.authorityCredential.table} where ${ac.subjectId} = ${sql.param(native, ac.subjectId)} and ${ac.credentialId} = ${sql.param(entry.credentialId, ac.credentialId)} and ${ac.revision} = ${sql.param(entry.revision, ac.revision)}${ac.status === undefined ? sql`` : sql` and ${ac.status} = ${sql.param(p.authorityCredential.d1ActiveStatusValue, ac.status)}`})`,\n ),\n )!;\n};\n\nconst existsRow = (mapping: Mapping, row: any) =>\n sql`exists(select 1 from ${mapping.intent.table} where ${shared.rowCondition(mapping, row)})`;\n\nconst terminalStatements = Effect.fn(function* (\n mapping: Mapping,\n row: any,\n state: \"Consumed\" | \"Cancelled\" | \"Expired\",\n marker: string,\n) {\n const database = yield* CurrentD1PlanningDatabase;\n const t = mapping.intent;\n\n return [\n yield* kernel.statement(\n database\n .update(t.table)\n .set(t.encodeTerminal(state))\n .where(shared.rowCondition(mapping, row)),\n ),\n yield* kernel.assertion(\n existsRow(mapping, {\n ...row,\n [t.state]: t.states[state],\n [t.snapshot]: null,\n [t.digest]: null,\n }),\n marker,\n ),\n ];\n});\n\nconst selectInsert = Effect.fn(function* (table: Table, values: object, condition: SQL) {\n const database = yield* CurrentD1PlanningDatabase;\n\n const selected = Object.fromEntries(\n Object.entries(values)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [\n key,\n (is(value, SQL) ? value : sql`${sql.param(value, column(table, key as never))}`).as(key),\n ]),\n );\n\n return database.insert(table as any).select(\n database\n .select(selected)\n .from(sql`(select 1)`)\n .where(condition),\n );\n});\n\nconst makePreparedPlans = (mapping: Mapping, proofMapping?: any) => {\n const p = mapping.password,\n t = mapping.intent,\n c = shared.columns(mapping),\n config = { locking: false };\n\n const readRows = Effect.fn(function* (condition: SQL) {\n const database = yield* CurrentD1PlanningDatabase;\n\n return yield* database.select().from(t.table).where(condition).limit(2);\n });\n\n const run = <A, E, R>(plan: Effect.Effect<Planned<A>, E, R>) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n return yield* shared.valid(mapping)\n ? plan.pipe(\n Effect.flatMap((planned) =>\n Effect.try({\n try: () => ({\n ...planned,\n statements: planned.statements.map((statement) =>\n compactD1GeneratedStatement(database.$client, statement, unavailable),\n ),\n postconditions: planned.postconditions?.map((statement) =>\n compactD1GeneratedStatement(database.$client, statement, unavailable),\n ),\n }),\n catch: (cause) =>\n Schema.is(PasswordUnavailable)(cause)\n ? cause\n : PersistenceMappingError.make({ operation: \"mapping\", cause }),\n }),\n ),\n )\n : Effect.fail(unavailable());\n });\n\n const current = (record: PasswordPreparedReservation | PasswordPreparedReady) =>\n shared.currentAuthority(mapping, config, record);\n\n const complete = <A>(\n uncaptured: PasswordPreparedMutation & { readonly completion?: ProofCompletionPlan },\n prepare: PreparePasswordCommit<PasswordMutationDecision, A>,\n ) =>\n Effect.gen(function* () {\n const input = yield* snapshotMutation(uncaptured);\n\n const completion =\n uncaptured.completion === undefined\n ? undefined\n : {\n prepare: uncaptured.completion.prepare,\n input: yield* Schema.encodeEffect(Schema.fromJsonString(CompletionInput))(\n uncaptured.completion.input,\n ).pipe(\n Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(CompletionInput))),\n Effect.mapError(unavailable),\n ),\n };\n\n if (\n (input.intent.action === \"reset-password\") !== (completion !== undefined) ||\n (completion !== undefined && proofMapping === undefined)\n )\n return yield* unavailable();\n\n const credentialRevision = yield* kernel.allocate(p.allocateRevision, p.allocateRevisionSync),\n verifierVersion = yield* kernel.allocate(p.allocateRevision, p.allocateRevisionSync),\n nextSecurityRevision = yield* kernel.allocateNextSecurityRevision(\n p,\n input.intent.revision.securityRevision,\n );\n\n if (\n nextSecurityRevision === input.intent.revision.securityRevision ||\n credentialRevision === input.intent.credential?.credentialRevision ||\n verifierVersion === input.intent.credential?.verifierVersion\n )\n return yield* unavailable();\n\n const credentialId =\n input.intent.action === \"add-password\"\n ? yield* kernel.allocate(p.allocateCredentialId, p.allocateCredentialIdSync)\n : undefined;\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* current(input.intent),\n rows = yield* readRows(\n and(eq(c.moduleId, input.intent.moduleId), eq(c.intentId, input.intent.intentId))!,\n ),\n row = rows[0],\n now = yield* kernel.readEngineNowMillis(p);\n\n if (\n authority === undefined ||\n rows.length !== 1 ||\n !(yield* shared.recordMatches(\n mapping,\n row,\n input.intent,\n authority.nativeSubjectId,\n yield* encodePasswordPreparedReady(input.intent),\n )) ||\n !evidenceCurrent(input, authority.requirement, now)\n )\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n const marker = `effect-auth-password-prepared:complete:${input.intent.intentId}`;\n\n const requirements = [\n input.mutation.authorization.requirement,\n input.intent.capturedRequirement,\n input.capturedRequirement,\n authority.requirement,\n input.currentRequirement,\n ];\n\n const age = Math.min(...requirements.map((value) => value.maximumAgeMillis));\n\n const live = and(\n existsRow(mapping, row),\n authorityCondition(mapping, authority, input.intent.moduleId),\n sql`${p.d1.engineNowMillis} >= ${input.intent.issuedAtMillis} and ${p.d1.engineNowMillis} < ${input.intent.expiresAtMillis}`,\n ...requirements.map((requirement) =>\n kernel.assuranceCondition(p, input.mutation.authorization.evidence, requirement),\n ),\n ...(input.intent.baseEvidence?.proofs ?? []).map(\n (proof) =>\n sql`${p.d1.engineNowMillis} >= ${DateTime.toEpochMillis(proof.verifiedAt)} and ${p.d1.engineNowMillis} < ${DateTime.toEpochMillis(proof.verifiedAt) + age}`,\n ),\n )!;\n\n let mutation: ReadonlyArray<Statement<any>>;\n let passwordApplied: SQL;\n let mutationGuard: ((cause: unknown) => boolean) | undefined;\n\n if (input.intent.action === \"add-password\") {\n const compiled = yield* kernel.compileAddMutation(p, input.mutation, {\n credentialId: credentialId!,\n credentialRevision,\n verifierVersion,\n nextSecurityRevision,\n });\n\n if (compiled === undefined)\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n mutation = compiled.statements;\n mutationGuard = compiled.retryable;\n passwordApplied = compiled.appliedCondition;\n } else {\n const compiled = yield* kernel.compileReplacementMutation(\n p,\n input.mutation,\n input.intent.action,\n { credentialRevision, verifierVersion, nextSecurityRevision },\n );\n\n if (compiled === undefined)\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n passwordApplied = compiled.protectedMutation.appliedCondition;\n mutationGuard = (cause) => kernel.isGuardFailure(cause, compiled.marker);\n mutation = [\n ...compiled.protectedMutation.statements,\n yield* kernel.assertion(compiled.protectedMutation.appliedCondition, marker),\n ];\n }\n\n const terminal = {\n ...row,\n [t.state]: t.states.Consumed,\n [t.snapshot]: null,\n [t.digest]: null,\n };\n\n const protectedMutation = {\n statements: [\n yield* kernel.assertion(live, marker),\n ...mutation,\n ...(yield* terminalStatements(mapping, row, \"Consumed\", marker)),\n ],\n appliedCondition: and(\n passwordApplied,\n existsRow(mapping, terminal),\n sql`${p.d1.engineNowMillis} >= ${input.intent.issuedAtMillis} and ${p.d1.engineNowMillis} < ${input.intent.expiresAtMillis}`,\n ...(input.intent.baseEvidence?.proofs ?? []).map(\n (proof) =>\n sql`${p.d1.engineNowMillis} >= ${DateTime.toEpochMillis(proof.verifiedAt)} and ${p.d1.engineNowMillis} < ${DateTime.toEpochMillis(proof.verifiedAt) + age}`,\n ),\n ...requirements.map((requirement) =>\n kernel.assuranceCondition(p, input.mutation.authorization.evidence, requirement),\n ),\n )!,\n };\n\n if (completion !== undefined) {\n if (\n input.intent.reset === undefined ||\n completion.input.continuationId !== input.intent.reset.continuationId ||\n bindingJson(completion.input.binding) !== bindingJson(input.intent.reset.binding) ||\n !kernel.completionMatchesPassword({ ...input.mutation, completion })\n )\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n let receipt: PreparedCommit<A> | undefined;\n\n const compiled = yield* compileD1ProofCompletionPlan(\n proofMapping,\n completion,\n protectedMutation,\n (decision) => {\n receipt = prepare(decision === \"completed\" ? \"changed\" : \"rejected\", journal);\n\n return decision;\n },\n );\n\n return {\n retryable: (cause: unknown) =>\n kernel.isGuardFailure(cause, marker) ||\n mutationGuard?.(cause) === true ||\n (completion !== undefined &&\n (kernel.isGuardFailure(\n cause,\n `effect-auth-proof-guard:complete:${completion.input.continuationId}`,\n ) ||\n kernel.isGuardFailure(\n cause,\n `effect-auth-proof-guard:protected:${completion.input.continuationId}`,\n ))),\n receipt: receipt ?? prepare(\"rejected\", journal),\n statements: compiled.statements,\n postconditions: compiled.postconditions,\n };\n }\n\n const postconditions = [\n yield* kernel.assertion(protectedMutation.appliedCondition, marker),\n ];\n\n return {\n retryable: (cause: unknown) =>\n kernel.isGuardFailure(cause, marker) || mutationGuard?.(cause) === true,\n receipt: prepare(\"changed\", journal),\n statements: [...protectedMutation.statements, ...postconditions],\n postconditions,\n };\n }),\n );\n });\n\n const services = {\n reserve: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"reserve\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"reserve\"], A>,\n ) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n const input = yield* snapshotReserve(uncaptured);\n\n if (\n (input.action === \"reset-password\") !==\n (input.reset !== undefined && input.completion !== undefined) ||\n (input.action === \"reset-password\" && proofMapping === undefined) ||\n input.generation !== input.policy.generation ||\n input.policy.retentionMillis <\n Math.max(\n input.policy.preparationLifetimeMillis + input.policy.lifetimeMillis,\n input.policy.admission.action.windowMillis,\n input.policy.admission.subject.windowMillis,\n input.policy.admission.identifier.windowMillis,\n ) ||\n (input.invalidation.existingSessions === \"immediate\" &&\n p.sessionInvalidation !== \"same-authority-immediate\")\n )\n return yield* unavailable();\n\n const version = PasswordPreparedVersion.make(\n yield* kernel.allocate(mapping.allocateVersion, mapping.allocateVersionSync),\n );\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* shared.captureAuthority(mapping, config, input);\n\n if (authority === undefined) return yield* unavailable();\n let proofCondition: SQL = sql`true`;\n\n if (input.reset !== undefined) {\n if (\n input.completion === undefined ||\n input.completion.moduleId !== `${input.moduleId}/reset` ||\n input.completion.purpose !== \"password-reset\" ||\n input.reset.continuationId !== input.completion.continuationId ||\n bindingJson(input.reset.binding) !== bindingJson(input.completion.binding) ||\n input.reset.binding._tag !== \"Subject\" ||\n !sameRevision(input.reset.binding.revision, authority.revision) ||\n authority.snapshot?.identifierVerifiedAtMillis === undefined\n )\n return yield* unavailable();\n const inspected = yield* checkD1ProofCompletion(proofMapping, input.completion);\n\n if (!inspected.accepted) return yield* unavailable();\n proofCondition = inspected.condition;\n }\n\n const ownerCurrent = and(\n authorityCondition(mapping, authority, input.moduleId),\n proofCondition,\n )!;\n\n const marker = `effect-auth-password-prepared:reserve:${input.intentId}`;\n\n const existing = yield* readRows(\n and(eq(c.moduleId, input.moduleId), eq(c.commandId, input.commandId))!,\n );\n\n if (existing.length)\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare({ _tag: \"Existing\" }, journal),\n statements: [\n yield* kernel.assertion(\n and(ownerCurrent, existsRow(mapping, existing[0]))!,\n marker,\n ),\n ],\n };\n\n const now = yield* kernel.readEngineNowMillis(p),\n scope = identifierScope({\n credential: authority.snapshot,\n revision: authority.revision,\n });\n\n const reservation = yield* snapshotPasswordPreparedReservation({\n _tag: \"Preparing\",\n moduleId: input.moduleId,\n generation: input.generation,\n intentId: input.intentId,\n version,\n commandId: input.commandId,\n action: input.action,\n revision: authority.revision,\n ...(authority.snapshot === undefined ? {} : { credential: authority.snapshot }),\n capturedRequirement: authority.requirement,\n ...(input.reset === undefined ? {} : { reset: input.reset }),\n invalidation: input.invalidation,\n createdAtMillis: now,\n preparationExpiresAtMillis: now + input.policy.preparationLifetimeMillis,\n retainUntilMillis: now + input.policy.retentionMillis,\n });\n\n const snapshot = yield* encodeReservation(reservation),\n window = Math.max(\n input.policy.admission.action.windowMillis,\n input.policy.admission.identifier.windowMillis,\n input.policy.admission.subject.windowMillis,\n );\n\n const a = mapping.admission,\n am = column(a.table, a.moduleId),\n ai = column(a.table, a.intentId),\n at = column(a.table, a.admittedAt),\n ar = column(a.table, a.admissionRetainUntil);\n\n const stamp = sql`(select ${at} from ${a.table} where ${am} = ${sql.param(input.moduleId, am)})`,\n retention = sql`(select ${ar} from ${a.table} where ${am} = ${sql.param(input.moduleId, am)})`;\n\n const active = sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(authority.nativeSubjectId, c.subjectId)} and ((${c.state} = ${sql.param(t.states.Preparing, c.state)} and ${c.preparationExpiresAt} > ${p.d1.engineNow}) or (${c.state} = ${sql.param(t.states.Ready, c.state)} and ${c.expiresAt} > ${p.d1.engineNow}))) < ${input.policy.maximumPendingPerSubject}`;\n\n const budgets = [\n [eq(c.action, input.action), input.policy.admission.action],\n [eq(c.identifierScope, scope), input.policy.admission.identifier],\n [eq(c.subjectId, authority.nativeSubjectId), input.policy.admission.subject],\n ] as const;\n\n const admissionDecision = and(\n ownerCurrent,\n active,\n ...budgets.map(\n ([condition, budget]) =>\n sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${condition} and ${c.admittedAt} > ${p.d1.engineInstantMinus(budget.windowMillis)}) < ${budget.limit}`,\n ),\n sql`not exists(select 1 from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.commandId} = ${sql.param(input.commandId, c.commandId)})`,\n sql`${p.d1.engineNowMillis} >= ${now} and ${p.d1.engineNowMillis} < ${reservation.preparationExpiresAtMillis}`,\n )!;\n\n const admittedMillis = mapping.admissionClock.toMillis(stamp),\n retainedMillis = mapping.admissionClock.toMillis(retention);\n\n const clockGuard = and(\n sql`exists(select 1 from ${a.table} where ${am} = ${sql.param(input.moduleId, am)} and ${ai} = ${sql.param(input.intentId, ai)})`,\n sql`${admittedMillis} >= ${now} and ${admittedMillis} <= ${p.d1.engineNowMillis}`,\n sql`${retainedMillis} = ${admittedMillis} + ${window}`,\n )!;\n\n const guard = and(sql`changes() = 1`, clockGuard)!;\n\n const values = {\n ...t.encodeInsert({\n reservation,\n nativeSubjectId: authority.nativeSubjectId,\n identifierScope: scope,\n snapshot,\n admittedAtMillis: now,\n admissionRetainUntilMillis: now + window,\n }),\n [t.admittedAt]: stamp,\n [t.admissionRetainUntil]: retention,\n };\n\n const expected = {\n [t.moduleId]: input.moduleId,\n [t.intentId]: input.intentId,\n [t.commandId]: input.commandId,\n [t.subjectId]: authority.nativeSubjectId,\n [t.action]: input.action,\n [t.generation]: input.generation,\n [t.version]: version,\n [t.state]: t.states.Preparing,\n [t.digest]: null,\n [t.snapshot]: snapshot,\n [t.identifierScope]: scope,\n [t.createdAt]: p.encodeInstant(now),\n [t.preparationExpiresAt]: p.encodeInstant(reservation.preparationExpiresAtMillis),\n [t.expiresAt]: null,\n [t.retainUntil]: p.encodeInstant(reservation.retainUntilMillis),\n [t.admittedAt]: stamp,\n [t.admissionRetainUntil]: retention,\n };\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare({ _tag: \"Reserved\", reservation }, journal),\n statements: [\n yield* kernel.statement(\n database\n .insert(a.table)\n .values(a.encodeInsert(input.moduleId))\n .onConflictDoNothing(),\n ),\n yield* kernel.statement(\n database\n .update(a.table)\n .set(\n updateValues([\n [a.intentId, input.intentId],\n [a.admittedAt, p.d1.engineNow],\n [a.admissionRetainUntil, p.d1.engineInstantPlus(window)],\n ]),\n )\n .where(and(eq(am, input.moduleId), admissionDecision)),\n ),\n yield* kernel.statement(yield* selectInsert(t.table, values, guard)),\n yield* kernel.assertion(existsRow(mapping, expected), marker),\n yield* kernel.assertion(\n and(\n ownerCurrent,\n clockGuard,\n sql`${p.d1.engineNowMillis} < ${reservation.preparationExpiresAtMillis}`,\n sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(authority.nativeSubjectId, c.subjectId)} and ((${c.state} = ${sql.param(t.states.Preparing, c.state)} and ${c.preparationExpiresAt} > ${p.d1.engineNow}) or (${c.state} = ${sql.param(t.states.Ready, c.state)} and ${c.expiresAt} > ${p.d1.engineNow}))) <= ${input.policy.maximumPendingPerSubject}`,\n ...budgets.map(\n ([condition, budget]) =>\n sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${condition} and ${c.admittedAt} > ${p.d1.engineInstantMinus(budget.windowMillis)}) <= ${budget.limit}`,\n ),\n )!,\n marker,\n ),\n ],\n };\n }),\n );\n }),\n publishReady: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"publishReady\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"publishReady\"], A>,\n ) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n const reservation = yield* snapshotPasswordPreparedReservation(uncaptured.reservation),\n ready = yield* snapshotPasswordPreparedReady(uncaptured.ready),\n snapshot = yield* encodeReservation(reservation),\n readySnapshot = yield* encodePasswordPreparedReady(ready);\n\n if ((yield* encodeReservation(reservationOf(ready))) !== snapshot)\n return yield* unavailable();\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* current(reservation),\n rows = yield* readRows(\n and(eq(c.moduleId, reservation.moduleId), eq(c.intentId, reservation.intentId))!,\n ),\n row = rows[0];\n\n if (\n authority === undefined ||\n rows.length !== 1 ||\n !(yield* shared.recordMatches(\n mapping,\n row,\n reservation,\n authority.nativeSubjectId,\n snapshot,\n ))\n )\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n\n const marker = `effect-auth-password-prepared:ready:${ready.intentId}`,\n live = and(\n authorityCondition(mapping, authority, ready.moduleId),\n sql`${p.d1.engineNowMillis} >= ${ready.issuedAtMillis} and ${p.d1.engineNowMillis} < ${reservation.preparationExpiresAtMillis} and ${p.d1.engineNowMillis} < ${ready.expiresAtMillis}`,\n )!;\n\n const expected = {\n ...row,\n [t.state]: t.states.Ready,\n [t.snapshot]: readySnapshot,\n [t.digest]: ready.digest,\n [t.expiresAt]: p.encodeInstant(ready.expiresAtMillis),\n };\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare(\"published\", journal),\n statements: [\n yield* kernel.assertion(and(live, existsRow(mapping, row))!, marker),\n yield* kernel.statement(\n database\n .update(t.table)\n .set(t.encodeReady({ ready, snapshot: readySnapshot }))\n .where(shared.rowCondition(mapping, row)),\n ),\n yield* kernel.assertion(and(live, existsRow(mapping, expected))!, marker),\n ],\n };\n }),\n );\n }),\n context: (uncaptured: Parameters<PasswordPreparedPersistence[\"context\"]>[0]) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n if (yield* hasCommitScope) return yield* unavailable();\n\n const input = yield* Schema.decodeEffect(ContextInput)({ ...uncaptured }).pipe(\n Effect.mapError(unavailable),\n ),\n rows = yield* readRows(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.generation, input.generation),\n eq(c.digest, input.digest),\n eq(c.state, t.states.Ready),\n )!,\n );\n\n if (rows.length !== 1) return yield* PasswordRejected.make({});\n\n const record = yield* decodePasswordPreparedReady(rows[0][t.snapshot]),\n authority = yield* current(record);\n\n if (\n authority === undefined ||\n record.moduleId !== input.moduleId ||\n record.generation !== input.generation ||\n record.digest !== input.digest ||\n !(yield* shared.recordMatches(\n mapping,\n rows[0],\n record,\n authority.nativeSubjectId,\n yield* encodePasswordPreparedReady(record),\n ))\n )\n return yield* PasswordRejected.make({});\n\n const condition = and(\n shared.rowCondition(mapping, rows[0]),\n authorityCondition(mapping, authority, record.moduleId),\n sql`${p.d1.engineNowMillis} >= ${record.issuedAtMillis} and ${p.d1.engineNowMillis} < ${record.expiresAtMillis}`,\n )!;\n\n const guardStatement = yield* kernel.assertion(\n sql`exists(select 1 from ${t.table} where ${condition})`,\n `effect-auth-password-prepared:context:${record.intentId}`,\n );\n\n const guard = yield* Effect.try({\n try: () => compactD1GeneratedStatement(database.$client, guardStatement, unavailable),\n catch: (cause) =>\n Schema.is(PasswordUnavailable)(cause)\n ? cause\n : PersistenceMappingError.make({ operation: \"mapping\", cause }),\n });\n\n yield* database.$client\n .batch([guard])\n .pipe(\n Effect.catchCause(\n (\n cause,\n ): Effect.Effect<never, PasswordRejected | import(\"effect/sql/SqlError\").SqlError> =>\n everyFailureMatches(cause, (failure) =>\n kernel.isGuardFailure(\n failure,\n `effect-auth-password-prepared:context:${record.intentId}`,\n ),\n )\n ? Effect.fail(PasswordRejected.make({}))\n : Effect.failCause(cause),\n ),\n );\n\n return { record, currentRequirement: authority.requirement };\n }),\n complete,\n resetWithProof: complete,\n cancel: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"cancel\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"cancel\"], A>,\n ) =>\n Effect.gen(function* () {\n const record = yield* snapshotPasswordPreparedReady(uncaptured.record);\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* current(record),\n rows = yield* readRows(\n and(eq(c.moduleId, record.moduleId), eq(c.intentId, record.intentId))!,\n ),\n row = rows[0];\n\n if (\n authority === undefined ||\n rows.length !== 1 ||\n !(yield* shared.recordMatches(\n mapping,\n row,\n record,\n authority.nativeSubjectId,\n yield* encodePasswordPreparedReady(record),\n ))\n )\n return { receipt: prepare(false, journal), statements: [] };\n const marker = `effect-auth-password-prepared:cancel:${record.intentId}`;\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare(true, journal),\n statements: [\n yield* kernel.assertion(\n and(\n existsRow(mapping, row),\n authorityCondition(mapping, authority, record.moduleId),\n sql`${p.d1.engineNowMillis} >= ${record.issuedAtMillis} and ${p.d1.engineNowMillis} < ${record.expiresAtMillis}`,\n )!,\n marker,\n ),\n ...(yield* terminalStatements(mapping, row, \"Cancelled\", marker)),\n ],\n };\n }),\n );\n }),\n cleanup: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"cleanup\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"cleanup\"], A>,\n ) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n const input = { ...uncaptured };\n\n if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 1000)\n return yield* unavailable();\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const due = and(\n eq(c.moduleId, input.moduleId),\n or(\n and(\n lte(c.retainUntil, p.d1.engineNow),\n lte(c.admissionRetainUntil, p.d1.engineNow),\n ),\n and(\n isNotNull(c.snapshot),\n or(\n and(\n eq(c.state, t.states.Preparing),\n lte(c.preparationExpiresAt, p.d1.engineNow),\n ),\n and(eq(c.state, t.states.Ready), lte(c.expiresAt, p.d1.engineNow)),\n ),\n ),\n ),\n )!;\n\n const rows = yield* database\n .select()\n .from(t.table)\n .where(due)\n .orderBy(c.createdAt, c.intentId)\n .limit(input.limit + 1);\n\n const now = yield* kernel.readEngineNowMillis(p),\n statements: Statement<any>[] = [],\n marker = `effect-auth-password-prepared:cleanup:${input.moduleId}`;\n\n let removed = 0;\n\n for (const row of rows.slice(0, input.limit)) {\n const retained = yield* p.decodeInstant(row[t.retainUntil]),\n charge = yield* p.decodeInstant(row[t.admissionRetainUntil]);\n\n statements.push(\n yield* kernel.assertion(\n and(\n existsRow(mapping, row),\n sql`exists(select 1 from ${t.table} where ${shared.rowCondition(mapping, row)} and ${due})`,\n )!,\n marker,\n ),\n );\n if (retained <= now && charge <= now) {\n statements.push(\n yield* kernel.statement(\n database\n .delete(t.table)\n .where(\n and(\n shared.rowCondition(mapping, row),\n lte(c.retainUntil, p.d1.engineNow),\n lte(c.admissionRetainUntil, p.d1.engineNow),\n ),\n ),\n ),\n yield* kernel.assertion(\n sql`not exists(select 1 from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.intentId} = ${sql.param(row[t.intentId], c.intentId)})`,\n marker,\n ),\n );\n removed++;\n } else\n statements.push(...(yield* terminalStatements(mapping, row, \"Expired\", marker)));\n }\n const hasMore = rows.length > input.limit;\n\n statements.push(\n yield* kernel.assertion(\n hasMore\n ? sql`exists(select 1 from ${t.table} where ${due})`\n : sql`not exists(select 1 from ${t.table} where ${due})`,\n marker,\n ),\n );\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare({ removed, hasMore }, journal),\n statements,\n };\n }),\n );\n }),\n };\n\n return services;\n};\n\nexport const makeD1PasswordPreparedPersistenceServices = <\n S extends AnySQLiteTable,\n I extends AnySQLiteTable,\n C extends AnySQLiteTable,\n AC extends AnySQLiteTable,\n At extends AnySQLiteTable,\n RS extends AnySQLiteTable,\n CE extends AnySQLiteTable,\n M extends AnySQLiteTable,\n T extends AnySQLiteTable,\n B extends AnySQLiteTable,\n NativeId,\n PS extends AnySQLiteTable = AnySQLiteTable,\n PC extends AnySQLiteTable = AnySQLiteTable,\n PM extends AnySQLiteTable = AnySQLiteTable,\n PSub extends AnySQLiteTable = AnySQLiteTable,\n PI extends AnySQLiteTable = AnySQLiteTable,\n PCr extends AnySQLiteTable = AnySQLiteTable,\n PNativeId = unknown,\n>(\n database: Database,\n mapping: D1PasswordPreparedPersistenceMapping<S, I, C, AC, At, RS, CE, M, T, B, NativeId>,\n proofMapping?: D1PasswordPreparedProofMapping<PS, PC, PM, PSub, PI, PCr, PNativeId>,\n) =>\n Effect.gen(function* () {\n const hooks = yield* LifecycleHooks;\n const plans = makePreparedPlans(mapping as unknown as Mapping, proofMapping);\n\n const run = <Out, Err, Env>(plan: Effect.Effect<Planned<Out>, Err, Env>) =>\n Effect.gen(function* () {\n if (yield* hasCommitScope) return yield* unavailable();\n\n return yield* executeStandalone(plan);\n }).pipe(\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(CurrentPasswordSql, database as unknown as PasswordSqlDatabase),\n Effect.provideService(LifecycleHooks, hooks),\n );\n\n const service: PasswordPreparedPersistence = {\n reserve: (input, prepare) => run(plans.reserve(input, prepare)).pipe(translateFailure),\n publishReady: (input, prepare) =>\n run(plans.publishReady(input, prepare)).pipe(translateFailure),\n context: (input) =>\n plans\n .context(input)\n .pipe(\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(CurrentPasswordSql, database as unknown as PasswordSqlDatabase),\n Effect.provideService(LifecycleHooks, hooks),\n translateContextFailure,\n ),\n complete: (input, prepare) => run(plans.complete(input, prepare)).pipe(translateFailure),\n resetWithProof: (input, prepare) =>\n run(plans.resetWithProof(input, prepare)).pipe(translateFailure),\n cancel: (input, prepare) => run(plans.cancel(input, prepare)).pipe(translateFailure),\n cleanup: (input, prepare) => run(plans.cleanup(input, prepare)).pipe(translateFailure),\n };\n\n return { passwordPreparedPersistence: service };\n });\n\nexport function coordinateD1PasswordPreparedPersistence<\n TargetId,\n S extends AnySQLiteTable,\n I extends AnySQLiteTable,\n C extends AnySQLiteTable,\n AC extends AnySQLiteTable,\n At extends AnySQLiteTable,\n RS extends AnySQLiteTable,\n CE extends AnySQLiteTable,\n M extends AnySQLiteTable,\n T extends AnySQLiteTable,\n B extends AnySQLiteTable,\n NativeId,\n PS extends AnySQLiteTable,\n PC extends AnySQLiteTable,\n PM extends AnySQLiteTable,\n PSub extends AnySQLiteTable,\n PI extends AnySQLiteTable,\n PCr extends AnySQLiteTable,\n PNativeId,\n A,\n E,\n R,\n DatabaseError,\n DatabaseRequirements,\n>(\n acquire: Effect.Effect<Database, DatabaseError, DatabaseRequirements>,\n options: {\n readonly mapping: D1PasswordPreparedPersistenceMapping<\n S,\n I,\n C,\n AC,\n At,\n RS,\n CE,\n M,\n T,\n B,\n NativeId\n >;\n readonly proofMapping?:\n | D1PasswordPreparedProofMapping<PS, PC, PM, PSub, PI, PCr, PNativeId>\n | undefined;\n readonly target: SuppliedService<TargetId, PasswordPreparedPersistence>;\n },\n body: Effect.Effect<A, E, R>,\n): Effect.Effect<\n A,\n E | PasswordUnavailable | HookConfigurationError | DatabaseError,\n Exclude<R, TargetId | D1BatchStatements> | LifecycleHooks | DatabaseRequirements\n> {\n return Effect.flatMap(acquire, (database) =>\n Effect.gen(function* () {\n const hooks = yield* LifecycleHooks;\n\n if (yield* hasCommitScope) return yield* unavailable();\n\n const result = yield* coordinateCommit(\n () =>\n Effect.gen(function* () {\n const statements: Statement<any>[] = [];\n let mutation: Planned<any> | undefined;\n let poisoned = false;\n\n const nativeCollector = D1BatchStatements.of({\n append: (statement) => Effect.sync(() => statements.push(statement)),\n });\n\n const owner = yield* makeD1Owner(unavailable()).pipe(\n Effect.provideService(D1BatchStatements, nativeCollector),\n );\n\n const protect = <Out, Err, Env>(effect: Effect.Effect<Out, Err, Env>) =>\n effect.pipe(\n Effect.onError(() =>\n Effect.sync(() => {\n poisoned = true;\n }),\n ),\n );\n\n const plans = makePreparedPlans(\n options.mapping as unknown as Mapping,\n options.proofMapping,\n );\n\n const run = <Out, Err, Env>(plan: Effect.Effect<Planned<Out>, Err, Env>) =>\n coordinateCommit(\n () =>\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n const planned = yield* plan;\n\n yield* owner.check;\n if (mutation !== undefined) return yield* unavailable();\n const guarded = { ...planned, journalGuard: journal.prepare(undefined) };\n\n mutation = guarded;\n statements.push(...guarded.statements);\n\n return guarded.receipt;\n }),\n { mode: \"batch\" },\n ).pipe(\n Effect.map((result) => result.value),\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(\n CurrentPasswordSql,\n database as unknown as PasswordSqlDatabase,\n ),\n Effect.provideService(LifecycleHooks, hooks),\n );\n\n const service: PasswordPreparedPersistence = {\n reserve: (input, prepare) =>\n owner.run(protect(run(plans.reserve(input, prepare)).pipe(translateFailure))),\n publishReady: (input, prepare) =>\n owner.run(protect(run(plans.publishReady(input, prepare)).pipe(translateFailure))),\n context: (input) =>\n owner.run(\n protect(\n plans\n .context(input)\n .pipe(\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(\n CurrentPasswordSql,\n database as unknown as PasswordSqlDatabase,\n ),\n Effect.provideService(LifecycleHooks, hooks),\n translateContextFailure,\n ),\n ),\n ),\n complete: (input, prepare) =>\n owner.run(protect(run(plans.complete(input, prepare)).pipe(translateFailure))),\n resetWithProof: (input, prepare) =>\n owner.run(\n protect(run(plans.resetWithProof(input, prepare)).pipe(translateFailure)),\n ),\n cancel: (input, prepare) =>\n owner.run(protect(run(plans.cancel(input, prepare)).pipe(translateFailure))),\n cleanup: (input, prepare) =>\n owner.run(protect(run(plans.cleanup(input, prepare)).pipe(translateFailure))),\n };\n\n const provided = Context.make(options.target, service).pipe(\n Context.add(D1BatchStatements, owner.collector),\n );\n\n const value = yield* owner.close(Effect.provideContext(body, provided));\n\n if (poisoned) return yield* unavailable();\n if (mutation?.journalGuard !== undefined) {\n const status = yield* Effect.result(mutation.journalGuard.read);\n\n if (status._tag === \"Success\" || status.failure._tag !== \"CommitPending\")\n return yield* unavailable();\n }\n yield* database.$client\n .batch([...statements, ...(mutation?.postconditions ?? [])])\n .pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) =>\n everyFailureMatches(cause, mutation?.retryable) ? unavailable() : error,\n ),\n ),\n ),\n translateFailure,\n );\n\n return value;\n }),\n { mode: \"batch\" },\n ).pipe(Effect.provideService(LifecycleHooks, hooks));\n\n return result.value;\n }),\n );\n}\n\nconst translateFailure = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, PasswordUnavailable, R> =>\n reportPersistenceFailure(\n effect,\n (error) =>\n Schema.is(PasswordUnavailable)(error) ||\n Schema.is(ProofUnavailable)(error) ||\n Schema.is(HookConfigurationError)(error),\n ).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));\n\nconst translateContextFailure = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, PasswordUnavailable | PasswordRejected, R> =>\n reportPersistenceFailure(\n effect,\n (error) =>\n Schema.is(PasswordUnavailable)(error) ||\n Schema.is(PasswordRejected)(error) ||\n Schema.is(ProofUnavailable)(error) ||\n Schema.is(HookConfigurationError)(error),\n ).pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) => (Schema.is(PasswordRejected)(error) ? error : unavailable())),\n ),\n ),\n );\n\nconst executeStandalone = <A, E, R>(plan: Effect.Effect<Planned<A>, E, R>) =>\n Effect.suspend(() => {\n let retryable: ((cause: unknown) => boolean) | undefined;\n\n return coordinateCommit(\n () =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n const planned = yield* plan;\n\n retryable = planned.retryable;\n yield* database.$client.batch([...planned.statements, ...(planned.postconditions ?? [])]);\n\n return planned.receipt;\n }),\n { mode: \"batch\" },\n ).pipe(\n Effect.map((result) => result.value),\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) =>\n everyFailureMatches(cause, retryable) ? unavailable() : error,\n ),\n ),\n ),\n );\n });\n"],"mappings":";;;;;;;;;;;;;;;;AAuFA,MAAM,uBACJ,OACA,aAEA,aAAa,KAAA,KACb,MAAM,QAAQ,SAAS,KACvB,MAAM,QAAQ,OAAO,WAAW,MAAM,aAAa,MAAM,KAAK,SAAS,MAAM,KAAK,OAAO,KAAK,CAAC,CAAC;AAElG,MAAM,cAAc,OAAO,WAAW,OAAO,eAAe,YAAY,CAAC;AAEzE,MAAM,sBAAsB,SAAkB,SAAc,aAAqB;CAC/E,MAAM,IAAI,QAAQ,UAChB,IAAIA,iBAAO,eAAe,CAAC,GAC3B,IAAIA,iBAAO,kBAAkB,CAAC,GAC9B,IAAIA,iBAAO,kBAAkB,CAAC,GAC9B,KAAKA,iBAAO,iBAAiB,CAAC;CAEhC,MAAM,WAAW,QAAQ,UACvB,SAAS,QAAQ;CAEnB,MAAM,aACJ,aAAa,KAAA,IACT,GAAG,SACHC,cACE,EAAE,WAAW,mBAAmB;EAC9B,YAAY,SAAS;EACrB,iBAAiB;CACnB,CAAC,GACD,GAAG,wBAAwB,EAAE,WAAW,MAAM,SAAS,EAAE,UAAU,KAAK,IAAI,MAAM,SAAS,WAAW,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,MAAM,SAAS,WAAW,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,KAAK,IAAI,MAAM,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,KAAK,IAAI,MAAM,SAAS,2BAA2B,EAAE,eAAe,EAAE,OAAO,UAAU,UAAU,QAAQ,WAAW,EAAE,WAAW,WAAW,IAAI,GAAG,GAAG,EAAE,WAAW,YAAY,GAAG,GAAG,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-prepared.mjs","names":["kernel","and","shared","DatabaseService"],"sources":["../../src/drizzle/d1-password-prepared.ts"],"sourcesContent":["/* oxlint-disable no-explicit-any -- driver exports preserve concrete consumer mappings. */\nimport type { D1Client } from \"@effect/sql-d1/D1Client\";\nimport {\n coordinateCommit,\n CurrentCommitJournal,\n hasCommitScope,\n type CommitJournal,\n type PreparedCommit,\n LifecycleHooks,\n HookConfigurationError,\n} from \"@yielded/auth/Hooks\";\nimport {\n PasswordRejected,\n PasswordUnavailable,\n PasswordPreparedVersion,\n decodePasswordPreparedReady,\n encodePasswordPreparedReady,\n snapshotPasswordPreparedReady,\n snapshotPasswordPreparedReservation,\n type PasswordPreparedReady,\n type PasswordPreparedReservation,\n type PasswordMutationDecision,\n type PreparePasswordCommit,\n type PasswordPreparedMutation,\n type PasswordPreparedPersistence,\n} from \"@yielded/auth/Password\";\nimport { reportPersistenceFailure } from \"@yielded/auth/Persistence\";\nimport { type ProofCompletionPlan, ProofUnavailable, ProofBinding } from \"@yielded/auth/Proofs\";\nimport { eq, is, isNotNull, lte, or, SQL, sql, type AnyRelations, type Table } from \"drizzle-orm\";\nimport type { EffectSQLiteD1Database } from \"drizzle-orm/effect-d1\";\nimport type { AnySQLiteTable } from \"drizzle-orm/sqlite-core\";\nimport { Cause, DateTime, Effect, Predicate, Redacted, Schema, Context } from \"effect\";\nimport type { Statement } from \"effect/sql/Statement\";\n\nimport { Database as DatabaseService } from \"./d1-database\";\nimport { balancedD1And as and, compactD1GeneratedStatement } from \"./d1-generated-statement\";\nimport { passwordD1Kernel as kernel } from \"./d1-passwords\";\nimport { CurrentD1PlanningDatabase, makeD1Owner } from \"./d1-planning\";\nimport { checkD1ProofCompletion, compileD1ProofCompletionPlan } from \"./d1-proofs\";\nimport { D1BatchStatements } from \"./D1BatchStatements\";\nimport { PersistenceMappingError, column, updateValues } from \"./model\";\nimport type {\n D1PasswordPreparedPersistenceMapping,\n D1PasswordPreparedProofMapping,\n} from \"./password-prepared-model\";\nimport { passwordPreparedSqlKernel as shared } from \"./password-prepared-sql\";\nimport {\n ContextInput,\n CompletionInput,\n encodeReservation,\n evidenceCurrent,\n identifierScope,\n reservationOf,\n sameRevision,\n snapshotMutation,\n snapshotReserve,\n unavailable,\n} from \"./password-prepared-state\";\nimport { CurrentPasswordSql, type PasswordSqlDatabase } from \"./password-sql\";\nimport type { SuppliedService } from \"./SuppliedService\";\n\ntype PlanPrepare<Method extends (...args: any[]) => any, A> = (\n value: Parameters<Parameters<Method>[1]>[0],\n journal: CommitJournal,\n) => PreparedCommit<A>;\n\ntype Database = EffectSQLiteD1Database<AnyRelations> & { readonly $client: D1Client };\ntype Mapping = D1PasswordPreparedPersistenceMapping<\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n Table,\n unknown\n>;\ninterface Planned<A> {\n readonly retryable?: (cause: unknown) => boolean;\n readonly receipt: PreparedCommit<A>;\n readonly statements: ReadonlyArray<Statement<any>>;\n readonly postconditions?: ReadonlyArray<Statement<any>>;\n readonly journalGuard?: PreparedCommit<void>;\n}\n\nconst everyFailureMatches = (\n cause: Cause.Cause<unknown>,\n classify: ((cause: unknown) => boolean) | undefined,\n): boolean =>\n classify !== undefined &&\n cause.reasons.length > 0 &&\n cause.reasons.every((reason) => Cause.isFailReason(reason) && classify(Cause.fail(reason.error)));\n\nconst bindingJson = Schema.encodeSync(Schema.fromJsonString(ProofBinding));\n\nconst authorityCondition = (mapping: Mapping, current: any, moduleId: string) => {\n const p = mapping.password,\n s = kernel.subjectColumns(p),\n i = kernel.identifierColumns(p),\n c = kernel.credentialColumns(p),\n ac = kernel.authorityColumns(p);\n\n const snapshot = current.snapshot,\n native = current.nativeSubjectId;\n\n const identifier =\n snapshot === undefined\n ? sql`true`\n : and(\n p.identifier.d1CurrentCondition({\n identifier: snapshot.identifier,\n nativeSubjectId: native,\n }),\n sql`exists(select 1 from ${p.identifier.table} where ${i.namespace} = ${sql.param(snapshot.identifier.namespace, i.namespace)} and ${i.value} = ${sql.param(snapshot.identifier.value, i.value)} and ${i.subjectId} = ${sql.param(native, i.subjectId)} and ${i.bindingRevision} = ${sql.param(snapshot.identifierBindingRevision, i.bindingRevision)} and ${Predicate.isNullish(current.identifier[p.identifier.verifiedAt]) ? sql`${i.verifiedAt} is null` : sql`${i.verifiedAt} = ${sql.param(current.identifier[p.identifier.verifiedAt], i.verifiedAt)}`})`,\n )!;\n\n return and(\n sql`exists(select 1 from ${p.subject.table} where ${s.id} = ${sql.param(native, s.id)} and ${s.status} = ${sql.param(p.subject.d1ActiveStatusValue, s.status)} and ${s.securityRevision} = ${sql.param(current.revision.securityRevision, s.securityRevision)})`,\n identifier,\n snapshot === undefined\n ? sql`not exists(select 1 from ${p.credential.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(native, c.subjectId)})`\n : sql`exists(select 1 from ${p.credential.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(native, c.subjectId)} and ${c.credentialId} = ${sql.param(snapshot.credentialId, c.credentialId)} and ${c.credentialRevision} = ${sql.param(snapshot.credentialRevision, c.credentialRevision)} and ${c.verifierVersion} = ${sql.param(snapshot.verifierVersion, c.verifierVersion)} and ${c.verifier} = ${sql.param(Redacted.value(snapshot.verifier), c.verifier)} and ${c.normalization} = ${sql.param(snapshot.normalization, c.normalization)})`,\n ...current.revision.credentials.map(\n (entry: any) =>\n sql`exists(select 1 from ${p.authorityCredential.table} where ${ac.subjectId} = ${sql.param(native, ac.subjectId)} and ${ac.credentialId} = ${sql.param(entry.credentialId, ac.credentialId)} and ${ac.revision} = ${sql.param(entry.revision, ac.revision)}${ac.status === undefined ? sql`` : sql` and ${ac.status} = ${sql.param(p.authorityCredential.d1ActiveStatusValue, ac.status)}`})`,\n ),\n )!;\n};\n\nconst existsRow = (mapping: Mapping, row: any) =>\n sql`exists(select 1 from ${mapping.intent.table} where ${shared.rowCondition(mapping, row)})`;\n\nconst terminalStatements = Effect.fn(function* (\n mapping: Mapping,\n row: any,\n state: \"Consumed\" | \"Cancelled\" | \"Expired\",\n marker: string,\n) {\n const database = yield* CurrentD1PlanningDatabase;\n const t = mapping.intent;\n\n return [\n yield* kernel.statement(\n database\n .update(t.table)\n .set(t.encodeTerminal(state))\n .where(shared.rowCondition(mapping, row)),\n ),\n yield* kernel.assertion(\n existsRow(mapping, {\n ...row,\n [t.state]: t.states[state],\n [t.snapshot]: null,\n [t.digest]: null,\n }),\n marker,\n ),\n ];\n});\n\nconst selectInsert = Effect.fn(function* (table: Table, values: object, condition: SQL) {\n const database = yield* CurrentD1PlanningDatabase;\n\n const selected = Object.fromEntries(\n Object.entries(values)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [\n key,\n (is(value, SQL) ? value : sql`${sql.param(value, column(table, key as never))}`).as(key),\n ]),\n );\n\n return database.insert(table as any).select(\n database\n .select(selected)\n .from(sql`(select 1)`)\n .where(condition),\n );\n});\n\nconst makePreparedPlans = (mapping: Mapping, proofMapping?: any) => {\n const p = mapping.password,\n t = mapping.intent,\n c = shared.columns(mapping),\n config = { locking: false };\n\n const readRows = Effect.fn(function* (condition: SQL) {\n const database = yield* CurrentD1PlanningDatabase;\n\n return yield* database.select().from(t.table).where(condition).limit(2);\n });\n\n const run = <A, E, R>(plan: Effect.Effect<Planned<A>, E, R>) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n return yield* shared.valid(mapping)\n ? plan.pipe(\n Effect.flatMap((planned) =>\n Effect.try({\n try: () => ({\n ...planned,\n statements: planned.statements.map((statement) =>\n compactD1GeneratedStatement(database.$client, statement, unavailable),\n ),\n postconditions: planned.postconditions?.map((statement) =>\n compactD1GeneratedStatement(database.$client, statement, unavailable),\n ),\n }),\n catch: (cause) =>\n Schema.is(PasswordUnavailable)(cause)\n ? cause\n : PersistenceMappingError.make({ operation: \"mapping\", cause }),\n }),\n ),\n )\n : Effect.fail(unavailable());\n });\n\n const current = (record: PasswordPreparedReservation | PasswordPreparedReady) =>\n shared.currentAuthority(mapping, config, record);\n\n const complete = <A>(\n uncaptured: PasswordPreparedMutation & { readonly completion?: ProofCompletionPlan },\n prepare: PreparePasswordCommit<PasswordMutationDecision, A>,\n ) =>\n Effect.gen(function* () {\n const input = yield* snapshotMutation(uncaptured);\n\n const completion =\n uncaptured.completion === undefined\n ? undefined\n : {\n prepare: uncaptured.completion.prepare,\n input: yield* Schema.encodeEffect(Schema.fromJsonString(CompletionInput))(\n uncaptured.completion.input,\n ).pipe(\n Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(CompletionInput))),\n Effect.mapError(unavailable),\n ),\n };\n\n if (\n (input.intent.action === \"reset-password\") !== (completion !== undefined) ||\n (completion !== undefined && proofMapping === undefined)\n )\n return yield* unavailable();\n\n const credentialRevision = yield* kernel.allocate(p.allocateRevision, p.allocateRevisionSync),\n verifierVersion = yield* kernel.allocate(p.allocateRevision, p.allocateRevisionSync),\n nextSecurityRevision = yield* kernel.allocateNextSecurityRevision(\n p,\n input.intent.revision.securityRevision,\n );\n\n if (\n nextSecurityRevision === input.intent.revision.securityRevision ||\n credentialRevision === input.intent.credential?.credentialRevision ||\n verifierVersion === input.intent.credential?.verifierVersion\n )\n return yield* unavailable();\n\n const credentialId =\n input.intent.action === \"add-password\"\n ? yield* kernel.allocate(p.allocateCredentialId, p.allocateCredentialIdSync)\n : undefined;\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* current(input.intent),\n rows = yield* readRows(\n and(eq(c.moduleId, input.intent.moduleId), eq(c.intentId, input.intent.intentId))!,\n ),\n row = rows[0],\n now = yield* kernel.readEngineNowMillis(p);\n\n if (\n authority === undefined ||\n rows.length !== 1 ||\n !(yield* shared.recordMatches(\n mapping,\n row,\n input.intent,\n authority.nativeSubjectId,\n yield* encodePasswordPreparedReady(input.intent),\n )) ||\n !evidenceCurrent(input, authority.requirement, now)\n )\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n const marker = `effect-auth-password-prepared:complete:${input.intent.intentId}`;\n\n const requirements = [\n input.mutation.authorization.requirement,\n input.intent.capturedRequirement,\n input.capturedRequirement,\n authority.requirement,\n input.currentRequirement,\n ];\n\n const age = Math.min(...requirements.map((value) => value.maximumAgeMillis));\n\n const live = and(\n existsRow(mapping, row),\n authorityCondition(mapping, authority, input.intent.moduleId),\n sql`${p.d1.engineNowMillis} >= ${input.intent.issuedAtMillis} and ${p.d1.engineNowMillis} < ${input.intent.expiresAtMillis}`,\n ...requirements.map((requirement) =>\n kernel.assuranceCondition(p, input.mutation.authorization.evidence, requirement),\n ),\n ...(input.intent.baseEvidence?.proofs ?? []).map(\n (proof) =>\n sql`${p.d1.engineNowMillis} >= ${DateTime.toEpochMillis(proof.verifiedAt)} and ${p.d1.engineNowMillis} < ${DateTime.toEpochMillis(proof.verifiedAt) + age}`,\n ),\n )!;\n\n let mutation: ReadonlyArray<Statement<any>>;\n let passwordApplied: SQL;\n let mutationGuard: ((cause: unknown) => boolean) | undefined;\n\n if (input.intent.action === \"add-password\") {\n const compiled = yield* kernel.compileAddMutation(p, input.mutation, {\n credentialId: credentialId!,\n credentialRevision,\n verifierVersion,\n nextSecurityRevision,\n });\n\n if (compiled === undefined)\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n mutation = compiled.statements;\n mutationGuard = compiled.retryable;\n passwordApplied = compiled.appliedCondition;\n } else {\n const compiled = yield* kernel.compileReplacementMutation(\n p,\n input.mutation,\n input.intent.action,\n { credentialRevision, verifierVersion, nextSecurityRevision },\n );\n\n if (compiled === undefined)\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n passwordApplied = compiled.protectedMutation.appliedCondition;\n mutationGuard = (cause) => kernel.isGuardFailure(cause, compiled.marker);\n mutation = [\n ...compiled.protectedMutation.statements,\n yield* kernel.assertion(compiled.protectedMutation.appliedCondition, marker),\n ];\n }\n\n const terminal = {\n ...row,\n [t.state]: t.states.Consumed,\n [t.snapshot]: null,\n [t.digest]: null,\n };\n\n const protectedMutation = {\n statements: [\n yield* kernel.assertion(live, marker),\n ...mutation,\n ...(yield* terminalStatements(mapping, row, \"Consumed\", marker)),\n ],\n appliedCondition: and(\n passwordApplied,\n existsRow(mapping, terminal),\n sql`${p.d1.engineNowMillis} >= ${input.intent.issuedAtMillis} and ${p.d1.engineNowMillis} < ${input.intent.expiresAtMillis}`,\n ...(input.intent.baseEvidence?.proofs ?? []).map(\n (proof) =>\n sql`${p.d1.engineNowMillis} >= ${DateTime.toEpochMillis(proof.verifiedAt)} and ${p.d1.engineNowMillis} < ${DateTime.toEpochMillis(proof.verifiedAt) + age}`,\n ),\n ...requirements.map((requirement) =>\n kernel.assuranceCondition(p, input.mutation.authorization.evidence, requirement),\n ),\n )!,\n };\n\n if (completion !== undefined) {\n if (\n input.intent.reset === undefined ||\n completion.input.continuationId !== input.intent.reset.continuationId ||\n bindingJson(completion.input.binding) !== bindingJson(input.intent.reset.binding) ||\n !kernel.completionMatchesPassword({ ...input.mutation, completion })\n )\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n let receipt: PreparedCommit<A> | undefined;\n\n const compiled = yield* compileD1ProofCompletionPlan(\n proofMapping,\n completion,\n protectedMutation,\n (decision) => {\n receipt = prepare(decision === \"completed\" ? \"changed\" : \"rejected\", journal);\n\n return decision;\n },\n );\n\n return {\n retryable: (cause: unknown) =>\n kernel.isGuardFailure(cause, marker) ||\n mutationGuard?.(cause) === true ||\n (completion !== undefined &&\n (kernel.isGuardFailure(\n cause,\n `effect-auth-proof-guard:complete:${completion.input.continuationId}`,\n ) ||\n kernel.isGuardFailure(\n cause,\n `effect-auth-proof-guard:protected:${completion.input.continuationId}`,\n ))),\n receipt: receipt ?? prepare(\"rejected\", journal),\n statements: compiled.statements,\n postconditions: compiled.postconditions,\n };\n }\n\n const postconditions = [\n yield* kernel.assertion(protectedMutation.appliedCondition, marker),\n ];\n\n return {\n retryable: (cause: unknown) =>\n kernel.isGuardFailure(cause, marker) || mutationGuard?.(cause) === true,\n receipt: prepare(\"changed\", journal),\n statements: [...protectedMutation.statements, ...postconditions],\n postconditions,\n };\n }),\n );\n });\n\n const services = {\n reserve: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"reserve\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"reserve\"], A>,\n ) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n const input = yield* snapshotReserve(uncaptured);\n\n if (\n (input.action === \"reset-password\") !==\n (input.reset !== undefined && input.completion !== undefined) ||\n (input.action === \"reset-password\" && proofMapping === undefined) ||\n input.generation !== input.policy.generation ||\n input.policy.retentionMillis <\n Math.max(\n input.policy.preparationLifetimeMillis + input.policy.lifetimeMillis,\n input.policy.admission.action.windowMillis,\n input.policy.admission.subject.windowMillis,\n input.policy.admission.identifier.windowMillis,\n ) ||\n (input.invalidation.existingSessions === \"immediate\" &&\n p.sessionInvalidation !== \"same-authority-immediate\")\n )\n return yield* unavailable();\n\n const version = PasswordPreparedVersion.make(\n yield* kernel.allocate(mapping.allocateVersion, mapping.allocateVersionSync),\n );\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* shared.captureAuthority(mapping, config, input);\n\n if (authority === undefined) return yield* unavailable();\n let proofCondition: SQL = sql`true`;\n\n if (input.reset !== undefined) {\n if (\n input.completion === undefined ||\n input.completion.moduleId !== `${input.moduleId}/reset` ||\n input.completion.purpose !== \"password-reset\" ||\n input.reset.continuationId !== input.completion.continuationId ||\n bindingJson(input.reset.binding) !== bindingJson(input.completion.binding) ||\n input.reset.binding._tag !== \"Subject\" ||\n !sameRevision(input.reset.binding.revision, authority.revision) ||\n authority.snapshot?.identifierVerifiedAtMillis === undefined\n )\n return yield* unavailable();\n const inspected = yield* checkD1ProofCompletion(proofMapping, input.completion);\n\n if (!inspected.accepted) return yield* unavailable();\n proofCondition = inspected.condition;\n }\n\n const ownerCurrent = and(\n authorityCondition(mapping, authority, input.moduleId),\n proofCondition,\n )!;\n\n const marker = `effect-auth-password-prepared:reserve:${input.intentId}`;\n\n const existing = yield* readRows(\n and(eq(c.moduleId, input.moduleId), eq(c.commandId, input.commandId))!,\n );\n\n if (existing.length)\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare({ _tag: \"Existing\" }, journal),\n statements: [\n yield* kernel.assertion(\n and(ownerCurrent, existsRow(mapping, existing[0]))!,\n marker,\n ),\n ],\n };\n\n const now = yield* kernel.readEngineNowMillis(p),\n scope = identifierScope({\n credential: authority.snapshot,\n revision: authority.revision,\n });\n\n const reservation = yield* snapshotPasswordPreparedReservation({\n _tag: \"Preparing\",\n moduleId: input.moduleId,\n generation: input.generation,\n intentId: input.intentId,\n version,\n commandId: input.commandId,\n action: input.action,\n revision: authority.revision,\n ...(authority.snapshot === undefined ? {} : { credential: authority.snapshot }),\n capturedRequirement: authority.requirement,\n ...(input.reset === undefined ? {} : { reset: input.reset }),\n invalidation: input.invalidation,\n createdAtMillis: now,\n preparationExpiresAtMillis: now + input.policy.preparationLifetimeMillis,\n retainUntilMillis: now + input.policy.retentionMillis,\n });\n\n const snapshot = yield* encodeReservation(reservation),\n window = Math.max(\n input.policy.admission.action.windowMillis,\n input.policy.admission.identifier.windowMillis,\n input.policy.admission.subject.windowMillis,\n );\n\n const a = mapping.admission,\n am = column(a.table, a.moduleId),\n ai = column(a.table, a.intentId),\n at = column(a.table, a.admittedAt),\n ar = column(a.table, a.admissionRetainUntil);\n\n const stamp = sql`(select ${at} from ${a.table} where ${am} = ${sql.param(input.moduleId, am)})`,\n retention = sql`(select ${ar} from ${a.table} where ${am} = ${sql.param(input.moduleId, am)})`;\n\n const active = sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(authority.nativeSubjectId, c.subjectId)} and ((${c.state} = ${sql.param(t.states.Preparing, c.state)} and ${c.preparationExpiresAt} > ${p.d1.engineNow}) or (${c.state} = ${sql.param(t.states.Ready, c.state)} and ${c.expiresAt} > ${p.d1.engineNow}))) < ${input.policy.maximumPendingPerSubject}`;\n\n const budgets = [\n [eq(c.action, input.action), input.policy.admission.action],\n [eq(c.identifierScope, scope), input.policy.admission.identifier],\n [eq(c.subjectId, authority.nativeSubjectId), input.policy.admission.subject],\n ] as const;\n\n const admissionDecision = and(\n ownerCurrent,\n active,\n ...budgets.map(\n ([condition, budget]) =>\n sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${condition} and ${c.admittedAt} > ${p.d1.engineInstantMinus(budget.windowMillis)}) < ${budget.limit}`,\n ),\n sql`not exists(select 1 from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.commandId} = ${sql.param(input.commandId, c.commandId)})`,\n sql`${p.d1.engineNowMillis} >= ${now} and ${p.d1.engineNowMillis} < ${reservation.preparationExpiresAtMillis}`,\n )!;\n\n const admittedMillis = mapping.admissionClock.toMillis(stamp),\n retainedMillis = mapping.admissionClock.toMillis(retention);\n\n const clockGuard = and(\n sql`exists(select 1 from ${a.table} where ${am} = ${sql.param(input.moduleId, am)} and ${ai} = ${sql.param(input.intentId, ai)})`,\n sql`${admittedMillis} >= ${now} and ${admittedMillis} <= ${p.d1.engineNowMillis}`,\n sql`${retainedMillis} = ${admittedMillis} + ${window}`,\n )!;\n\n const guard = and(sql`changes() = 1`, clockGuard)!;\n\n const values = {\n ...t.encodeInsert({\n reservation,\n nativeSubjectId: authority.nativeSubjectId,\n identifierScope: scope,\n snapshot,\n admittedAtMillis: now,\n admissionRetainUntilMillis: now + window,\n }),\n [t.admittedAt]: stamp,\n [t.admissionRetainUntil]: retention,\n };\n\n const expected = {\n [t.moduleId]: input.moduleId,\n [t.intentId]: input.intentId,\n [t.commandId]: input.commandId,\n [t.subjectId]: authority.nativeSubjectId,\n [t.action]: input.action,\n [t.generation]: input.generation,\n [t.version]: version,\n [t.state]: t.states.Preparing,\n [t.digest]: null,\n [t.snapshot]: snapshot,\n [t.identifierScope]: scope,\n [t.createdAt]: p.encodeInstant(now),\n [t.preparationExpiresAt]: p.encodeInstant(reservation.preparationExpiresAtMillis),\n [t.expiresAt]: null,\n [t.retainUntil]: p.encodeInstant(reservation.retainUntilMillis),\n [t.admittedAt]: stamp,\n [t.admissionRetainUntil]: retention,\n };\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare({ _tag: \"Reserved\", reservation }, journal),\n statements: [\n yield* kernel.statement(\n database\n .insert(a.table)\n .values(a.encodeInsert(input.moduleId))\n .onConflictDoNothing(),\n ),\n yield* kernel.statement(\n database\n .update(a.table)\n .set(\n updateValues([\n [a.intentId, input.intentId],\n [a.admittedAt, p.d1.engineNow],\n [a.admissionRetainUntil, p.d1.engineInstantPlus(window)],\n ]),\n )\n .where(and(eq(am, input.moduleId), admissionDecision)),\n ),\n yield* kernel.statement(yield* selectInsert(t.table, values, guard)),\n yield* kernel.assertion(existsRow(mapping, expected), marker),\n yield* kernel.assertion(\n and(\n ownerCurrent,\n clockGuard,\n sql`${p.d1.engineNowMillis} < ${reservation.preparationExpiresAtMillis}`,\n sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.subjectId} = ${sql.param(authority.nativeSubjectId, c.subjectId)} and ((${c.state} = ${sql.param(t.states.Preparing, c.state)} and ${c.preparationExpiresAt} > ${p.d1.engineNow}) or (${c.state} = ${sql.param(t.states.Ready, c.state)} and ${c.expiresAt} > ${p.d1.engineNow}))) <= ${input.policy.maximumPendingPerSubject}`,\n ...budgets.map(\n ([condition, budget]) =>\n sql`(select count(*) from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${condition} and ${c.admittedAt} > ${p.d1.engineInstantMinus(budget.windowMillis)}) <= ${budget.limit}`,\n ),\n )!,\n marker,\n ),\n ],\n };\n }),\n );\n }),\n publishReady: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"publishReady\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"publishReady\"], A>,\n ) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n const reservation = yield* snapshotPasswordPreparedReservation(uncaptured.reservation),\n ready = yield* snapshotPasswordPreparedReady(uncaptured.ready),\n snapshot = yield* encodeReservation(reservation),\n readySnapshot = yield* encodePasswordPreparedReady(ready);\n\n if ((yield* encodeReservation(reservationOf(ready))) !== snapshot)\n return yield* unavailable();\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* current(reservation),\n rows = yield* readRows(\n and(eq(c.moduleId, reservation.moduleId), eq(c.intentId, reservation.intentId))!,\n ),\n row = rows[0];\n\n if (\n authority === undefined ||\n rows.length !== 1 ||\n !(yield* shared.recordMatches(\n mapping,\n row,\n reservation,\n authority.nativeSubjectId,\n snapshot,\n ))\n )\n return { receipt: prepare(\"rejected\", journal), statements: [] };\n\n const marker = `effect-auth-password-prepared:ready:${ready.intentId}`,\n live = and(\n authorityCondition(mapping, authority, ready.moduleId),\n sql`${p.d1.engineNowMillis} >= ${ready.issuedAtMillis} and ${p.d1.engineNowMillis} < ${reservation.preparationExpiresAtMillis} and ${p.d1.engineNowMillis} < ${ready.expiresAtMillis}`,\n )!;\n\n const expected = {\n ...row,\n [t.state]: t.states.Ready,\n [t.snapshot]: readySnapshot,\n [t.digest]: ready.digest,\n [t.expiresAt]: p.encodeInstant(ready.expiresAtMillis),\n };\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare(\"published\", journal),\n statements: [\n yield* kernel.assertion(and(live, existsRow(mapping, row))!, marker),\n yield* kernel.statement(\n database\n .update(t.table)\n .set(t.encodeReady({ ready, snapshot: readySnapshot }))\n .where(shared.rowCondition(mapping, row)),\n ),\n yield* kernel.assertion(and(live, existsRow(mapping, expected))!, marker),\n ],\n };\n }),\n );\n }),\n context: (uncaptured: Parameters<PasswordPreparedPersistence[\"context\"]>[0]) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n if (yield* hasCommitScope) return yield* unavailable();\n\n const input = yield* Schema.decodeEffect(ContextInput)({ ...uncaptured }).pipe(\n Effect.mapError(unavailable),\n ),\n rows = yield* readRows(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.generation, input.generation),\n eq(c.digest, input.digest),\n eq(c.state, t.states.Ready),\n )!,\n );\n\n if (rows.length !== 1) return yield* PasswordRejected.make({});\n\n const record = yield* decodePasswordPreparedReady(rows[0][t.snapshot]),\n authority = yield* current(record);\n\n if (\n authority === undefined ||\n record.moduleId !== input.moduleId ||\n record.generation !== input.generation ||\n record.digest !== input.digest ||\n !(yield* shared.recordMatches(\n mapping,\n rows[0],\n record,\n authority.nativeSubjectId,\n yield* encodePasswordPreparedReady(record),\n ))\n )\n return yield* PasswordRejected.make({});\n\n const condition = and(\n shared.rowCondition(mapping, rows[0]),\n authorityCondition(mapping, authority, record.moduleId),\n sql`${p.d1.engineNowMillis} >= ${record.issuedAtMillis} and ${p.d1.engineNowMillis} < ${record.expiresAtMillis}`,\n )!;\n\n const guardStatement = yield* kernel.assertion(\n sql`exists(select 1 from ${t.table} where ${condition})`,\n `effect-auth-password-prepared:context:${record.intentId}`,\n );\n\n const guard = yield* Effect.try({\n try: () => compactD1GeneratedStatement(database.$client, guardStatement, unavailable),\n catch: (cause) =>\n Schema.is(PasswordUnavailable)(cause)\n ? cause\n : PersistenceMappingError.make({ operation: \"mapping\", cause }),\n });\n\n yield* database.$client\n .batch([guard])\n .pipe(\n Effect.catchCause(\n (\n cause,\n ): Effect.Effect<never, PasswordRejected | import(\"effect/sql/SqlError\").SqlError> =>\n everyFailureMatches(cause, (failure) =>\n kernel.isGuardFailure(\n failure,\n `effect-auth-password-prepared:context:${record.intentId}`,\n ),\n )\n ? Effect.fail(PasswordRejected.make({}))\n : Effect.failCause(cause),\n ),\n );\n\n return { record, currentRequirement: authority.requirement };\n }),\n complete,\n resetWithProof: complete,\n cancel: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"cancel\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"cancel\"], A>,\n ) =>\n Effect.gen(function* () {\n const record = yield* snapshotPasswordPreparedReady(uncaptured.record);\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const authority = yield* current(record),\n rows = yield* readRows(\n and(eq(c.moduleId, record.moduleId), eq(c.intentId, record.intentId))!,\n ),\n row = rows[0];\n\n if (\n authority === undefined ||\n rows.length !== 1 ||\n !(yield* shared.recordMatches(\n mapping,\n row,\n record,\n authority.nativeSubjectId,\n yield* encodePasswordPreparedReady(record),\n ))\n )\n return { receipt: prepare(false, journal), statements: [] };\n const marker = `effect-auth-password-prepared:cancel:${record.intentId}`;\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare(true, journal),\n statements: [\n yield* kernel.assertion(\n and(\n existsRow(mapping, row),\n authorityCondition(mapping, authority, record.moduleId),\n sql`${p.d1.engineNowMillis} >= ${record.issuedAtMillis} and ${p.d1.engineNowMillis} < ${record.expiresAtMillis}`,\n )!,\n marker,\n ),\n ...(yield* terminalStatements(mapping, row, \"Cancelled\", marker)),\n ],\n };\n }),\n );\n }),\n cleanup: <A>(\n uncaptured: Parameters<PasswordPreparedPersistence[\"cleanup\"]>[0],\n prepare: PlanPrepare<PasswordPreparedPersistence[\"cleanup\"], A>,\n ) =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n\n const input = { ...uncaptured };\n\n if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 1000)\n return yield* unavailable();\n\n return yield* run(\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const due = and(\n eq(c.moduleId, input.moduleId),\n or(\n and(\n lte(c.retainUntil, p.d1.engineNow),\n lte(c.admissionRetainUntil, p.d1.engineNow),\n ),\n and(\n isNotNull(c.snapshot),\n or(\n and(\n eq(c.state, t.states.Preparing),\n lte(c.preparationExpiresAt, p.d1.engineNow),\n ),\n and(eq(c.state, t.states.Ready), lte(c.expiresAt, p.d1.engineNow)),\n ),\n ),\n ),\n )!;\n\n const rows = yield* database\n .select()\n .from(t.table)\n .where(due)\n .orderBy(c.createdAt, c.intentId)\n .limit(input.limit + 1);\n\n const now = yield* kernel.readEngineNowMillis(p),\n statements: Statement<any>[] = [],\n marker = `effect-auth-password-prepared:cleanup:${input.moduleId}`;\n\n let removed = 0;\n\n for (const row of rows.slice(0, input.limit)) {\n const retained = yield* p.decodeInstant(row[t.retainUntil]),\n charge = yield* p.decodeInstant(row[t.admissionRetainUntil]);\n\n statements.push(\n yield* kernel.assertion(\n and(\n existsRow(mapping, row),\n sql`exists(select 1 from ${t.table} where ${shared.rowCondition(mapping, row)} and ${due})`,\n )!,\n marker,\n ),\n );\n if (retained <= now && charge <= now) {\n statements.push(\n yield* kernel.statement(\n database\n .delete(t.table)\n .where(\n and(\n shared.rowCondition(mapping, row),\n lte(c.retainUntil, p.d1.engineNow),\n lte(c.admissionRetainUntil, p.d1.engineNow),\n ),\n ),\n ),\n yield* kernel.assertion(\n sql`not exists(select 1 from ${t.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.intentId} = ${sql.param(row[t.intentId], c.intentId)})`,\n marker,\n ),\n );\n removed++;\n } else\n statements.push(...(yield* terminalStatements(mapping, row, \"Expired\", marker)));\n }\n const hasMore = rows.length > input.limit;\n\n statements.push(\n yield* kernel.assertion(\n hasMore\n ? sql`exists(select 1 from ${t.table} where ${due})`\n : sql`not exists(select 1 from ${t.table} where ${due})`,\n marker,\n ),\n );\n\n return {\n retryable: (cause: unknown) => kernel.isGuardFailure(cause, marker),\n receipt: prepare({ removed, hasMore }, journal),\n statements,\n };\n }),\n );\n }),\n };\n\n return services;\n};\n\nexport const makeD1PasswordPreparedPersistenceServices = Effect.fnUntraced(function* <\n S extends AnySQLiteTable,\n I extends AnySQLiteTable,\n C extends AnySQLiteTable,\n AC extends AnySQLiteTable,\n At extends AnySQLiteTable,\n RS extends AnySQLiteTable,\n CE extends AnySQLiteTable,\n M extends AnySQLiteTable,\n T extends AnySQLiteTable,\n B extends AnySQLiteTable,\n NativeId,\n PS extends AnySQLiteTable = AnySQLiteTable,\n PC extends AnySQLiteTable = AnySQLiteTable,\n PM extends AnySQLiteTable = AnySQLiteTable,\n PSub extends AnySQLiteTable = AnySQLiteTable,\n PI extends AnySQLiteTable = AnySQLiteTable,\n PCr extends AnySQLiteTable = AnySQLiteTable,\n PNativeId = unknown,\n>(\n mapping: D1PasswordPreparedPersistenceMapping<S, I, C, AC, At, RS, CE, M, T, B, NativeId>,\n proofMapping?: D1PasswordPreparedProofMapping<PS, PC, PM, PSub, PI, PCr, PNativeId>,\n) {\n const database = yield* DatabaseService;\n\n const hooks = yield* LifecycleHooks;\n const plans = makePreparedPlans(mapping as unknown as Mapping, proofMapping);\n\n const run = <Out, Err, Env>(plan: Effect.Effect<Planned<Out>, Err, Env>) =>\n Effect.gen(function* () {\n if (yield* hasCommitScope) return yield* unavailable();\n\n return yield* executeStandalone(plan);\n }).pipe(\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(CurrentPasswordSql, database as unknown as PasswordSqlDatabase),\n Effect.provideService(LifecycleHooks, hooks),\n );\n\n const service: PasswordPreparedPersistence = {\n reserve: (input, prepare) => run(plans.reserve(input, prepare)).pipe(translateFailure),\n publishReady: (input, prepare) =>\n run(plans.publishReady(input, prepare)).pipe(translateFailure),\n context: (input) =>\n plans\n .context(input)\n .pipe(\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(CurrentPasswordSql, database as unknown as PasswordSqlDatabase),\n Effect.provideService(LifecycleHooks, hooks),\n translateContextFailure,\n ),\n complete: (input, prepare) => run(plans.complete(input, prepare)).pipe(translateFailure),\n resetWithProof: (input, prepare) =>\n run(plans.resetWithProof(input, prepare)).pipe(translateFailure),\n cancel: (input, prepare) => run(plans.cancel(input, prepare)).pipe(translateFailure),\n cleanup: (input, prepare) => run(plans.cleanup(input, prepare)).pipe(translateFailure),\n };\n\n return { passwordPreparedPersistence: service };\n});\n\nexport function coordinateD1PasswordPreparedPersistence<\n TargetId,\n S extends AnySQLiteTable,\n I extends AnySQLiteTable,\n C extends AnySQLiteTable,\n AC extends AnySQLiteTable,\n At extends AnySQLiteTable,\n RS extends AnySQLiteTable,\n CE extends AnySQLiteTable,\n M extends AnySQLiteTable,\n T extends AnySQLiteTable,\n B extends AnySQLiteTable,\n NativeId,\n PS extends AnySQLiteTable,\n PC extends AnySQLiteTable,\n PM extends AnySQLiteTable,\n PSub extends AnySQLiteTable,\n PI extends AnySQLiteTable,\n PCr extends AnySQLiteTable,\n PNativeId,\n A,\n E,\n R,\n DatabaseError,\n DatabaseRequirements,\n>(\n acquire: Effect.Effect<Database, DatabaseError, DatabaseRequirements>,\n options: {\n readonly mapping: D1PasswordPreparedPersistenceMapping<\n S,\n I,\n C,\n AC,\n At,\n RS,\n CE,\n M,\n T,\n B,\n NativeId\n >;\n readonly proofMapping?:\n | D1PasswordPreparedProofMapping<PS, PC, PM, PSub, PI, PCr, PNativeId>\n | undefined;\n readonly target: SuppliedService<TargetId, PasswordPreparedPersistence>;\n },\n body: Effect.Effect<A, E, R>,\n): Effect.Effect<\n A,\n E | PasswordUnavailable | HookConfigurationError | DatabaseError,\n Exclude<R, TargetId | D1BatchStatements> | LifecycleHooks | DatabaseRequirements\n> {\n return Effect.flatMap(acquire, (database) =>\n Effect.gen(function* () {\n const hooks = yield* LifecycleHooks;\n\n if (yield* hasCommitScope) return yield* unavailable();\n\n const result = yield* coordinateCommit(\n () =>\n Effect.gen(function* () {\n const statements: Statement<any>[] = [];\n let mutation: Planned<any> | undefined;\n let poisoned = false;\n\n const nativeCollector = D1BatchStatements.of({\n append: (statement) => Effect.sync(() => statements.push(statement)),\n });\n\n const owner = yield* makeD1Owner(unavailable()).pipe(\n Effect.provideService(D1BatchStatements, nativeCollector),\n );\n\n const protect = <Out, Err, Env>(effect: Effect.Effect<Out, Err, Env>) =>\n effect.pipe(\n Effect.onError(() =>\n Effect.sync(() => {\n poisoned = true;\n }),\n ),\n );\n\n const plans = makePreparedPlans(\n options.mapping as unknown as Mapping,\n options.proofMapping,\n );\n\n const run = <Out, Err, Env>(plan: Effect.Effect<Planned<Out>, Err, Env>) =>\n coordinateCommit(\n () =>\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n const planned = yield* plan;\n\n yield* owner.check;\n if (mutation !== undefined) return yield* unavailable();\n const guarded = { ...planned, journalGuard: journal.prepare(undefined) };\n\n mutation = guarded;\n statements.push(...guarded.statements);\n\n return guarded.receipt;\n }),\n { mode: \"batch\" },\n ).pipe(\n Effect.map((result) => result.value),\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(\n CurrentPasswordSql,\n database as unknown as PasswordSqlDatabase,\n ),\n Effect.provideService(LifecycleHooks, hooks),\n );\n\n const service: PasswordPreparedPersistence = {\n reserve: (input, prepare) =>\n owner.run(protect(run(plans.reserve(input, prepare)).pipe(translateFailure))),\n publishReady: (input, prepare) =>\n owner.run(protect(run(plans.publishReady(input, prepare)).pipe(translateFailure))),\n context: (input) =>\n owner.run(\n protect(\n plans\n .context(input)\n .pipe(\n Effect.provideService(CurrentD1PlanningDatabase, database),\n Effect.provideService(\n CurrentPasswordSql,\n database as unknown as PasswordSqlDatabase,\n ),\n Effect.provideService(LifecycleHooks, hooks),\n translateContextFailure,\n ),\n ),\n ),\n complete: (input, prepare) =>\n owner.run(protect(run(plans.complete(input, prepare)).pipe(translateFailure))),\n resetWithProof: (input, prepare) =>\n owner.run(\n protect(run(plans.resetWithProof(input, prepare)).pipe(translateFailure)),\n ),\n cancel: (input, prepare) =>\n owner.run(protect(run(plans.cancel(input, prepare)).pipe(translateFailure))),\n cleanup: (input, prepare) =>\n owner.run(protect(run(plans.cleanup(input, prepare)).pipe(translateFailure))),\n };\n\n const provided = Context.make(options.target, service).pipe(\n Context.add(D1BatchStatements, owner.collector),\n );\n\n const value = yield* owner.close(Effect.provideContext(body, provided));\n\n if (poisoned) return yield* unavailable();\n if (mutation?.journalGuard !== undefined) {\n const status = yield* Effect.result(mutation.journalGuard.read);\n\n if (status._tag === \"Success\" || status.failure._tag !== \"CommitPending\")\n return yield* unavailable();\n }\n yield* database.$client\n .batch([...statements, ...(mutation?.postconditions ?? [])])\n .pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) =>\n everyFailureMatches(cause, mutation?.retryable) ? unavailable() : error,\n ),\n ),\n ),\n translateFailure,\n );\n\n return value;\n }),\n { mode: \"batch\" },\n ).pipe(Effect.provideService(LifecycleHooks, hooks));\n\n return result.value;\n }),\n );\n}\n\nconst translateFailure = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, PasswordUnavailable, R> =>\n reportPersistenceFailure(\n effect,\n (error) =>\n Schema.is(PasswordUnavailable)(error) ||\n Schema.is(ProofUnavailable)(error) ||\n Schema.is(HookConfigurationError)(error),\n ).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));\n\nconst translateContextFailure = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, PasswordUnavailable | PasswordRejected, R> =>\n reportPersistenceFailure(\n effect,\n (error) =>\n Schema.is(PasswordUnavailable)(error) ||\n Schema.is(PasswordRejected)(error) ||\n Schema.is(ProofUnavailable)(error) ||\n Schema.is(HookConfigurationError)(error),\n ).pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) => (Schema.is(PasswordRejected)(error) ? error : unavailable())),\n ),\n ),\n );\n\nconst executeStandalone = <A, E, R>(plan: Effect.Effect<Planned<A>, E, R>) =>\n Effect.suspend(() => {\n let retryable: ((cause: unknown) => boolean) | undefined;\n\n return coordinateCommit(\n () =>\n Effect.gen(function* () {\n const database = yield* CurrentD1PlanningDatabase;\n const planned = yield* plan;\n\n retryable = planned.retryable;\n yield* database.$client.batch([...planned.statements, ...(planned.postconditions ?? [])]);\n\n return planned.receipt;\n }),\n { mode: \"batch\" },\n ).pipe(\n Effect.map((result) => result.value),\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) =>\n everyFailureMatches(cause, retryable) ? unavailable() : error,\n ),\n ),\n ),\n );\n });\n"],"mappings":";;;;;;;;;;;;;;;;;AAwFA,MAAM,uBACJ,OACA,aAEA,aAAa,KAAA,KACb,MAAM,QAAQ,SAAS,KACvB,MAAM,QAAQ,OAAO,WAAW,MAAM,aAAa,MAAM,KAAK,SAAS,MAAM,KAAK,OAAO,KAAK,CAAC,CAAC;AAElG,MAAM,cAAc,OAAO,WAAW,OAAO,eAAe,YAAY,CAAC;AAEzE,MAAM,sBAAsB,SAAkB,SAAc,aAAqB;CAC/E,MAAM,IAAI,QAAQ,UAChB,IAAIA,iBAAO,eAAe,CAAC,GAC3B,IAAIA,iBAAO,kBAAkB,CAAC,GAC9B,IAAIA,iBAAO,kBAAkB,CAAC,GAC9B,KAAKA,iBAAO,iBAAiB,CAAC;CAEhC,MAAM,WAAW,QAAQ,UACvB,SAAS,QAAQ;CAEnB,MAAM,aACJ,aAAa,KAAA,IACT,GAAG,SACHC,cACE,EAAE,WAAW,mBAAmB;EAC9B,YAAY,SAAS;EACrB,iBAAiB;CACnB,CAAC,GACD,GAAG,wBAAwB,EAAE,WAAW,MAAM,SAAS,EAAE,UAAU,KAAK,IAAI,MAAM,SAAS,WAAW,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,MAAM,SAAS,WAAW,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,KAAK,IAAI,MAAM,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,KAAK,IAAI,MAAM,SAAS,2BAA2B,EAAE,eAAe,EAAE,OAAO,UAAU,UAAU,QAAQ,WAAW,EAAE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AI,YAAY,IAAI,KAC1D,CACF,CACF,CACF;AACF,CAAC"}
|
|
@@ -2,6 +2,7 @@ import { D1PasswordPersistenceMapping, PasswordRegistrationMapping } from "./pas
|
|
|
2
2
|
import "./model.mjs";
|
|
3
3
|
import { D1ProofPersistenceMapping } from "./proof-model.mjs";
|
|
4
4
|
import { PasswordRegistrationAuthority } from "./password-registration.mjs";
|
|
5
|
+
import { Database as Database$1 } from "./d1-database.mjs";
|
|
5
6
|
import { D1BatchStatements } from "./D1BatchStatements.mjs";
|
|
6
7
|
import { SuppliedService } from "./SuppliedService.mjs";
|
|
7
8
|
import "./d1-planning.mjs";
|
|
@@ -13,16 +14,16 @@ import { HookConfigurationError, LifecycleHooks, PreparedCommit } from "@yielded
|
|
|
13
14
|
import { SecurityRevision } from "@yielded/auth/Sessions";
|
|
14
15
|
import { ProofCompletionInput, ProofCompletionPlan } from "@yielded/auth/Proofs";
|
|
15
16
|
import { PasswordAttemptDecision, PasswordAttemptPolicy, PasswordCredentialSnapshot, PasswordMutationDecision, PasswordMutationInput, PasswordPersistence, PasswordUnavailable, PreparePasswordCommit } from "@yielded/auth/Password";
|
|
17
|
+
import { EffectSQLiteD1Database } from "drizzle-orm/effect-d1";
|
|
16
18
|
import { AnySQLiteTable } from "drizzle-orm/sqlite-core";
|
|
17
19
|
import { Statement } from "effect/sql/Statement";
|
|
18
20
|
import { D1Client } from "@effect/sql-d1/D1Client";
|
|
19
|
-
import { EffectSQLiteD1Database } from "drizzle-orm/effect-d1";
|
|
20
21
|
import "drizzle-orm/effect-core";
|
|
21
22
|
//#region src/drizzle/d1-passwords.d.ts
|
|
22
23
|
type Database = EffectSQLiteD1Database<AnyRelations> & {
|
|
23
24
|
readonly $client: D1Client;
|
|
24
25
|
};
|
|
25
|
-
export declare const makeD1PasswordPersistenceServices: <S extends AnySQLiteTable, I extends AnySQLiteTable, C extends AnySQLiteTable, AC extends AnySQLiteTable, A extends AnySQLiteTable, RS extends AnySQLiteTable, CE extends AnySQLiteTable, M extends AnySQLiteTable, NativeId>(
|
|
26
|
+
export declare const makeD1PasswordPersistenceServices: <S extends AnySQLiteTable, I extends AnySQLiteTable, C extends AnySQLiteTable, AC extends AnySQLiteTable, A extends AnySQLiteTable, RS extends AnySQLiteTable, CE extends AnySQLiteTable, M extends AnySQLiteTable, NativeId>(mapping: D1PasswordPersistenceMapping<S, I, C, AC, A, RS, CE, M, NativeId>, proofMapping?: D1ProofPersistenceMapping<any, any, any, any, any, any, any, any, any, any, any, any> | undefined) => Effect.Effect<{
|
|
26
27
|
passwordPersistence: {
|
|
27
28
|
readonly admitAttempt: <A_1>(input: {
|
|
28
29
|
readonly moduleId: string;
|
|
@@ -64,7 +65,7 @@ export declare const makeD1PasswordPersistenceServices: <S extends AnySQLiteTabl
|
|
|
64
65
|
readonly hasMore: boolean;
|
|
65
66
|
}, A_1>) => Effect.Effect<PreparedCommit<A_1>, PasswordUnavailable>;
|
|
66
67
|
};
|
|
67
|
-
}, never, LifecycleHooks>;
|
|
68
|
+
}, never, Database$1 | LifecycleHooks>;
|
|
68
69
|
type CoordinatorError<E> = E | PasswordUnavailable | HookConfigurationError;
|
|
69
70
|
/**
|
|
70
71
|
* Owns one password transition plus application statements in one D1 batch.
|
|
@@ -75,9 +76,9 @@ export declare function coordinateD1PasswordPersistence<S extends AnySQLiteTable
|
|
|
75
76
|
readonly mapping: D1PasswordPersistenceMapping<S, I, C, AC, At, RS, CE, M, NativeId>;
|
|
76
77
|
readonly proofMapping?: D1ProofPersistenceMapping<any, any, any, any, any, any, any, any, any, any, any, any> | undefined;
|
|
77
78
|
}, body: Effect.Effect<A, E, R>): Effect.Effect<A, CoordinatorError<E> | DatabaseError, Exclude<R, PasswordPersistence | D1BatchStatements> | LifecycleHooks | DatabaseRequirements>;
|
|
78
|
-
export declare const makeD1PasswordRegistrationServices: <Registration, S extends AnySQLiteTable, I extends AnySQLiteTable, C extends AnySQLiteTable, AC extends AnySQLiteTable, Rq extends AnySQLiteTable, NativeId>(
|
|
79
|
+
export declare const makeD1PasswordRegistrationServices: <Registration, S extends AnySQLiteTable, I extends AnySQLiteTable, C extends AnySQLiteTable, AC extends AnySQLiteTable, Rq extends AnySQLiteTable, NativeId>(mapping: PasswordRegistrationMapping<Registration, S, I, C, AC, Rq, NativeId>) => Effect.Effect<{
|
|
79
80
|
registrationAuthority: PasswordRegistrationAuthority<Registration>;
|
|
80
|
-
}, never, LifecycleHooks>;
|
|
81
|
+
}, never, Database$1 | LifecycleHooks>;
|
|
81
82
|
export declare function coordinateD1PasswordRegistration<TargetId, Registration, S extends AnySQLiteTable, I extends AnySQLiteTable, C extends AnySQLiteTable, AC extends AnySQLiteTable, Rq extends AnySQLiteTable, NativeId, A, E, R, DatabaseError, DatabaseRequirements>(acquire: Effect.Effect<Database, DatabaseError, DatabaseRequirements>, options: {
|
|
82
83
|
readonly mapping: PasswordRegistrationMapping<NoInfer<Registration>, S, I, C, AC, Rq, NativeId>;
|
|
83
84
|
readonly target: SuppliedService<TargetId, PasswordRegistrationAuthority<Registration>>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { requiredPasswordConstraints, requiredPasswordRegistrationConstraints } from "./password-model.mjs";
|
|
2
2
|
import { PersistenceMappingError, column, isMappedConstraintConflict, updateValues } from "./model.mjs";
|
|
3
3
|
import { balancedD1And } from "./d1-generated-statement.mjs";
|
|
4
|
+
import { Database } from "./d1-database.mjs";
|
|
4
5
|
import { D1BatchStatements } from "./D1BatchStatements.mjs";
|
|
5
6
|
import { CurrentD1PlanningDatabase, makeD1Owner } from "./d1-planning.mjs";
|
|
6
7
|
import { compileD1ProofCompletionPlan } from "./d1-proofs.mjs";
|
|
@@ -193,22 +194,23 @@ const scopeEntries = (keys, policy) => {
|
|
|
193
194
|
});
|
|
194
195
|
return entries;
|
|
195
196
|
};
|
|
197
|
+
const livePendingAttempts = (mapping, moduleId, action, entry, identifier, nativeSubjectId, activeAt) => {
|
|
198
|
+
const a = attemptColumns(mapping);
|
|
199
|
+
return and(entry.kind === "action" ? and(eq(a.moduleId, moduleId), eq(a.action, action)) : entry.kind === "identifier" ? and(eq(a.moduleId, moduleId), eq(a.action, action), eq(a.identifierNamespace, identifier.namespace), eq(a.identifierValue, identifier.value)) : and(eq(a.moduleId, moduleId), eq(a.action, action), eq(a.subjectId, nativeSubjectId)), eq(a.state, "pending"), sql`${a.retentionUntil} > ${activeAt}`);
|
|
200
|
+
};
|
|
196
201
|
const scopeAdmissionCondition = (mapping, moduleId, action, entry, policy, identifier, nativeSubjectId) => {
|
|
197
202
|
const c = chargeColumns(mapping);
|
|
198
|
-
const
|
|
199
|
-
const pending = entry.kind === "action" ? and(eq(a.moduleId, moduleId), eq(a.action, action), eq(a.state, "pending")) : entry.kind === "identifier" ? and(eq(a.moduleId, moduleId), eq(a.action, action), eq(a.identifierNamespace, identifier.namespace), eq(a.identifierValue, identifier.value), eq(a.state, "pending")) : and(eq(a.moduleId, moduleId), eq(a.action, action), eq(a.subjectId, nativeSubjectId), eq(a.state, "pending"));
|
|
203
|
+
const pending = livePendingAttempts(mapping, moduleId, action, entry, identifier, nativeSubjectId, mapping.d1.engineNow);
|
|
200
204
|
return sql`(select count(*) from ${mapping.charge.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.action} = ${sql.param(action, c.action)} and ${c.scopeKind} = ${sql.param(entry.kind, c.scopeKind)} and ${c.scopeKey} = ${sql.param(entry.key, c.scopeKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(entry.windowMillis)}) < ${entry.limit} and (select count(*) from ${mapping.attempt.table} where ${pending}) < ${policy.maximumPending}`;
|
|
201
205
|
};
|
|
202
206
|
const readScopeAdmission = Effect.fn("DrizzleD1Password.readScopeAdmission")(function* (mapping, moduleId, action, entries, policy, identifier, nativeSubjectId, now) {
|
|
203
207
|
const database = yield* CurrentD1PlanningDatabase;
|
|
204
208
|
const c = chargeColumns(mapping);
|
|
205
|
-
const a = attemptColumns(mapping);
|
|
206
209
|
const admitted = [];
|
|
207
210
|
for (let index = 0; index < entries.length; index++) {
|
|
208
211
|
const entry = entries[index];
|
|
209
212
|
const chargeRows = yield* mapAdapter(database.select({ total: count() }).from(mapping.charge.table).where(and(eq(c.moduleId, moduleId), eq(c.action, action), eq(c.scopeKind, entry.kind), eq(c.scopeKey, entry.key), gte(c.occurredAt, mapping.encodeInstant(now - entry.windowMillis)))));
|
|
210
|
-
const
|
|
211
|
-
const pendingRows = yield* mapAdapter(database.select({ total: count() }).from(mapping.attempt.table).where(pendingWhere));
|
|
213
|
+
const pendingRows = yield* mapAdapter(database.select({ total: count() }).from(mapping.attempt.table).where(livePendingAttempts(mapping, moduleId, action, entry, identifier, nativeSubjectId, mapping.encodeInstant(now))));
|
|
212
214
|
if (Number(chargeRows[0]?.total ?? 0) < entry.limit && Number(pendingRows[0]?.total ?? 0) < policy.maximumPending) admitted.push(entry);
|
|
213
215
|
else if (index === 0) break;
|
|
214
216
|
}
|
|
@@ -752,7 +754,8 @@ const cleanupPlan = Effect.fn("Drizzle.cleanupPlan")(function* (mapping, input,
|
|
|
752
754
|
retryable: (cause) => isGuardFailure(cause, marker)
|
|
753
755
|
};
|
|
754
756
|
});
|
|
755
|
-
const makeD1PasswordPersistenceServices =
|
|
757
|
+
const makeD1PasswordPersistenceServices = Effect.fnUntraced(function* (mapping, proofMapping) {
|
|
758
|
+
const database = yield* Database;
|
|
756
759
|
const hooks = yield* LifecycleHooks;
|
|
757
760
|
const plans = makePasswordPlans(mapping, proofMapping);
|
|
758
761
|
const run = (plan) => Effect.gen(function* () {
|
|
@@ -923,7 +926,8 @@ const makeRegistrationPlans = (mapping) => ({ register: (input, prepare) => Effe
|
|
|
923
926
|
const allocated = yield* allocateRegistration(mapping);
|
|
924
927
|
return yield* planRegistration(mapping, input, allocated, prepare);
|
|
925
928
|
}) });
|
|
926
|
-
const makeD1PasswordRegistrationServices =
|
|
929
|
+
const makeD1PasswordRegistrationServices = Effect.fnUntraced(function* (mapping) {
|
|
930
|
+
const database = yield* Database;
|
|
927
931
|
const hooks = yield* LifecycleHooks;
|
|
928
932
|
const plans = makeRegistrationPlans(mapping);
|
|
929
933
|
const run = (plan) => Effect.gen(function* () {
|