@yielded/auth-persistence 0.1.0-beta.10 → 0.1.0-beta.11
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/README.md +2 -7
- package/dist/index.d.mts +1 -2
- package/dist/index.mjs +1 -2
- package/dist/internal/configuration.d.mts +1 -1
- package/dist/internal/configuration.mjs.map +1 -1
- package/dist/internal/email-kernel.d.mts +1 -1
- package/dist/internal/email-kernel.mjs.map +1 -1
- package/dist/internal/oauth-server.d.mts +1 -1
- package/dist/internal/oauth-server.mjs +1 -1
- package/dist/internal/oauth-server.mjs.map +1 -1
- package/dist/internal/passkey/state.mjs +3 -2
- package/dist/internal/passkey/state.mjs.map +1 -1
- package/dist/internal/passkey/target.d.mts +1 -1
- package/dist/internal/passkey/target.mjs.map +1 -1
- package/dist/internal/passkey/write-state.mjs +3 -2
- package/dist/internal/passkey/write-state.mjs.map +1 -1
- package/dist/internal/passkey/write-target.mjs.map +1 -1
- package/dist/internal/passkey-kernel.d.mts +5 -5
- package/dist/internal/passkeys.mjs +1 -1
- package/dist/internal/passkeys.mjs.map +1 -1
- package/dist/internal/password-kernel.d.mts +1 -1
- package/dist/internal/password-kernel.mjs.map +1 -1
- package/dist/internal/persistence.d.mts +1 -1
- package/dist/internal/persistence.mjs +1 -1
- package/dist/internal/persistence.mjs.map +1 -1
- package/dist/internal/proof-kernel.d.mts +1 -1
- package/dist/internal/proof-kernel.mjs.map +1 -1
- package/dist/internal/query-operations.d.mts +1 -1
- package/dist/internal/session-kernel.d.mts +1 -1
- package/dist/internal/session-kernel.mjs.map +1 -1
- package/dist/internal/sql-persistence.mjs +1 -1
- package/dist/internal/sql-persistence.mjs.map +1 -1
- package/dist/internal/sql-query.mjs.map +1 -1
- package/dist/internal/standalone.d.mts +1 -1
- package/dist/internal/standalone.mjs.map +1 -1
- package/dist/internal/storage-validation.mjs.map +1 -1
- package/dist/internal/transaction-execution-kernel.d.mts +3 -3
- package/dist/internal/transaction-execution-kernel.mjs.map +1 -1
- package/dist/internal/transaction-kernel.d.mts +3 -3
- package/dist/internal/transaction-kernel.mjs.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +0 -1
- package/src/internal/configuration.ts +1 -1
- package/src/internal/email-kernel.ts +1 -1
- package/src/internal/oauth-server.ts +1 -1
- package/src/internal/passkey/state.ts +3 -2
- package/src/internal/passkey/target.ts +1 -1
- package/src/internal/passkey/write-state.ts +3 -2
- package/src/internal/passkey/write-target.ts +1 -1
- package/src/internal/passkeys.ts +1 -1
- package/src/internal/password-kernel.ts +1 -1
- package/src/internal/persistence.ts +1 -1
- package/src/internal/proof-kernel.ts +1 -1
- package/src/internal/query-operations.ts +1 -1
- package/src/internal/session-kernel.ts +1 -1
- package/src/internal/sql-persistence.ts +1 -1
- package/src/internal/sql-query.ts +2 -2
- package/src/internal/standalone.ts +1 -1
- package/src/internal/storage-validation.ts +1 -1
- package/src/internal/transaction-execution-kernel.ts +3 -3
- package/src/internal/transaction-kernel.ts +3 -3
- package/dist/internal/oauth-app.d.mts +0 -11
- package/dist/internal/oauth-app.mjs +0 -57
- package/dist/internal/oauth-app.mjs.map +0 -1
- package/src/internal/oauth-app.ts +0 -82
package/README.md
CHANGED
|
@@ -7,13 +7,8 @@ Drizzle integrations live in `@yielded/auth-persistence-drizzle`; this package h
|
|
|
7
7
|
no Drizzle dependency or exports. Core workflows and replaceable service contracts
|
|
8
8
|
remain in `@yielded/auth`.
|
|
9
9
|
|
|
10
|
-
`OAuthAppPersistence` separately supplies the single-table store for
|
|
11
|
-
[`OAuthApp`](../../docs/guide/oauth.md#sign-in-and-connect-provider-access).
|
|
12
|
-
It has no dependency on the broader auth schema or a session repository. Apply its
|
|
13
|
-
exported migration with the application's runner and provide an Effect SQL client.
|
|
14
|
-
|
|
15
10
|
`OAuthServerPersistence` supplies independent, single-table consent and grant
|
|
16
|
-
storage for [MCP authorization](../../docs/guide/oauth.md#authorize-mcp-clients).
|
|
11
|
+
storage for [MCP authorization](../../docs/src/content/docs/guide/oauth.md#authorize-mcp-clients).
|
|
17
12
|
Its conditional writes and monotonic revocation require standalone commits.
|
|
18
13
|
|
|
19
14
|
Applications own subject provisioning, policy, claims, delivery, and their database
|
|
@@ -23,5 +18,5 @@ The composed Layer covers password sign-in and management, email address verific
|
|
|
23
18
|
and changes, phone sign-in, and passkey sign-in and management with stateful sessions
|
|
24
19
|
on PostgreSQL and SQLite. The `/Adapter` module exposes the shared mapping contracts
|
|
25
20
|
and transaction kernels used by companion adapters.
|
|
26
|
-
See [persistence examples](../../docs/reference/adapters.md#runnable-examples) for all
|
|
21
|
+
See [persistence examples](../../docs/src/content/docs/reference/adapters.md#runnable-examples) for all
|
|
27
22
|
four ownership models and their current limits.
|
package/dist/index.d.mts
CHANGED
|
@@ -2,6 +2,5 @@ import { PersistenceMappingError } from "./internal/mapping-error.mjs";
|
|
|
2
2
|
import { StorageColumn, StorageTable } from "./internal/storage-tables.mjs";
|
|
3
3
|
import { PersistenceConfigurationError } from "./internal/configuration.mjs";
|
|
4
4
|
import { AuthPersistence } from "./internal/sql-persistence.mjs";
|
|
5
|
-
import { OAuthAppPersistence } from "./internal/oauth-app.mjs";
|
|
6
5
|
import { OAuthServerPersistence } from "./internal/oauth-server.mjs";
|
|
7
|
-
export { AuthPersistence,
|
|
6
|
+
export { AuthPersistence, OAuthServerPersistence, PersistenceConfigurationError, PersistenceMappingError, StorageColumn, StorageTable };
|
package/dist/index.mjs
CHANGED
|
@@ -2,6 +2,5 @@ import { PersistenceConfigurationError } from "./internal/configuration.mjs";
|
|
|
2
2
|
import { PersistenceMappingError } from "./internal/mapping-error.mjs";
|
|
3
3
|
import { StorageColumn, StorageTable } from "./internal/storage-tables.mjs";
|
|
4
4
|
import { AuthPersistence } from "./internal/sql-persistence.mjs";
|
|
5
|
-
import { OAuthAppPersistence } from "./internal/oauth-app.mjs";
|
|
6
5
|
import { OAuthServerPersistence } from "./internal/oauth-server.mjs";
|
|
7
|
-
export { AuthPersistence,
|
|
6
|
+
export { AuthPersistence, OAuthServerPersistence, PersistenceConfigurationError, PersistenceMappingError, StorageColumn, StorageTable };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PersistenceMappingError } from "./mapping-error.mjs";
|
|
2
2
|
import { StorageRole } from "./storage-tables.mjs";
|
|
3
3
|
import { Context, Effect, Layer, Schema } from "effect";
|
|
4
|
-
import { SqlClient } from "effect/
|
|
4
|
+
import { SqlClient } from "effect/sql";
|
|
5
5
|
import { PasskeyActionChallenge, PasskeyConfig, PasskeyConfigurationError, PasskeyCredentials, PasskeyEnrollmentContext, PasskeyManagementPersistence, PasskeyManagementPolicy, PasskeyMethodPolicy, PasskeyPersistence } from "@yielded/auth/Passkey";
|
|
6
6
|
import { SubjectId } from "@yielded/auth/Schema";
|
|
7
7
|
import { AuthenticationAuthority, AuthenticationRequirement, make } from "@yielded/auth/Sessions";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configuration.mjs","names":[],"sources":["../../src/internal/configuration.ts"],"sourcesContent":["import type { EmailAction, EmailAddressPersistence } from \"@yielded/auth/Email\";\nimport type { LoginIdentifier } from \"@yielded/auth/Identity\";\nimport type {\n PasskeyActionChallenge,\n PasskeyConfig,\n PasskeyCredentials,\n PasskeyEnrollmentContext,\n PasskeyManagementPersistence,\n PasskeyManagementPolicy,\n PasskeyMethodPolicy,\n PasskeyPersistence,\n PasskeyConfigurationError,\n} from \"@yielded/auth/Passkey\";\nimport type {\n PasswordAction,\n PasswordPersistence,\n PasswordUnavailable,\n} from \"@yielded/auth/Password\";\nimport type { PhoneAdmission, PhoneSignInTargets } from \"@yielded/auth/PhoneOtp\";\nimport type { ProofPersistence } from \"@yielded/auth/Proofs\";\nimport type { SubjectId } from \"@yielded/auth/Schema\";\nimport type {\n AuthenticationAuthority,\n AuthenticationRequirement,\n make as makeSessions,\n} from \"@yielded/auth/Sessions\";\nimport { type Context, type Effect, type Layer, Schema } from \"effect\";\nimport type { SqlClient } from \"effect/unstable/sql\";\n\nimport type { PersistenceMappingError } from \"./mapping-error\";\nimport type { StorageRole } from \"./storage-tables\";\n\nexport class PersistenceConfigurationError extends Schema.TaggedError<PersistenceConfigurationError>()(\n \"PersistenceConfigurationError\",\n { reason: Schema.String },\n) {}\n\nexport type ClaimsCodec = Schema.Codec<unknown, unknown, never, never>;\n\nexport interface PasskeyFeature {\n readonly kind: \"passkey\";\n readonly moduleId: string;\n readonly policy: Effect.Effect<PasskeyMethodPolicy, PasskeyConfigurationError, PasskeyConfig>;\n readonly management?: boolean;\n readonly managementPolicy?: PasskeyManagementPolicy;\n}\n\nexport interface Strategy {\n readonly strategy: object;\n readonly persistence?:\n | PasskeyFeature\n | {\n readonly kind: \"password\" | \"phone\" | \"email\";\n readonly moduleId: string;\n readonly lifecycle?: boolean;\n readonly management?: boolean;\n readonly addresses?: boolean;\n };\n readonly RegistrationAuthority?: Context.Key<unknown, unknown>;\n}\n\nexport interface Definition<C extends ClaimsCodec, Id extends string> {\n readonly namespace: string;\n readonly claims: C;\n readonly sessionMode?: string;\n readonly sessions: ReturnType<typeof makeSessions<C, Id>>;\n readonly strategies: Readonly<Record<string, Strategy>>;\n}\n\ntype KeyId<T> = T extends Context.Key<infer Id, infer _Service> ? Id : never;\ntype Enabled<\n A extends { readonly strategies: Readonly<Record<string, Strategy>> },\n Kind extends \"password\" | \"phone\" | \"email\" | \"passkey\",\n> = Extract<A[\"strategies\"][keyof A[\"strategies\"]], { persistence: { kind: Kind } }>;\n\ntype ManagedPassword<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> =\n Extract<Enabled<A, \"password\">, { persistence: { management: true } }>;\n\ntype ManagedPasskey<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> =\n Extract<Enabled<A, \"passkey\">, { persistence: { management: true } }>;\n\nexport type PasskeyRequirement<\n A extends { readonly strategies: Readonly<Record<string, Strategy>> },\n> = Enabled<A, \"passkey\"> extends never ? never : PasskeyConfig;\n\ntype RegistrationKey<S> = S extends { readonly RegistrationAuthority: infer K } ? K : never;\ntype Registration<S> =\n RegistrationKey<S> extends Context.Key<infer _Id, infer Service>\n ? Service extends { readonly register: (input: infer Input, ...args: never[]) => unknown }\n ? Input extends { readonly registration: infer Value }\n ? Value\n : never\n : never\n : never;\n\nexport interface ProvisioningId<Id extends string> {\n readonly authNamespace: Id;\n readonly service: \"PersistenceProvisioning\";\n}\n\nexport type Provisioning<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> = {\n readonly [\n K in keyof A[\"strategies\"] as A[\"strategies\"][K] extends {\n persistence: { kind: \"password\"; management: true };\n }\n ? K\n : never\n ]: (input: {\n readonly identifier: LoginIdentifier;\n readonly registration: Registration<A[\"strategies\"][K]>;\n }) => Effect.Effect<SubjectId, PasswordUnavailable>;\n};\n\nexport type ProvisioningRequirement<\n A extends { readonly namespace: string; readonly strategies: Readonly<Record<string, Strategy>> },\n> = ManagedPassword<A> extends never ? never : ProvisioningId<A[\"namespace\"]>;\n\ntype ProofRoles =\n | \"proofRequests\"\n | \"proofSeries\"\n | \"proofGenerations\"\n | \"proofContinuations\"\n | \"proofScopes\"\n | \"proofAbuse\"\n | \"proofFailures\"\n | \"proofCommands\";\n\ntype UsesProofs<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> =\n | Enabled<A, \"phone\">\n | Enabled<A, \"email\">\n | ManagedPassword<A>;\n\nexport type Ports<C extends ClaimsCodec, Id extends string, A extends Definition<C, Id>> =\n | AuthenticationAuthority\n | KeyId<A[\"sessions\"][\"StatefulSessionPersistence\"]>\n | KeyId<A[\"sessions\"][\"SessionRepository\"]>\n | (Enabled<A, \"password\"> extends never ? never : PasswordPersistence)\n | KeyId<RegistrationKey<ManagedPassword<A>>>\n | (Enabled<A, \"passkey\"> extends never ? never : PasskeyPersistence | PasskeyCredentials)\n | (ManagedPasskey<A> extends never\n ? never\n : PasskeyManagementPersistence | PasskeyEnrollmentContext)\n | (Enabled<A, \"email\"> extends never ? never : EmailAddressPersistence)\n | (UsesProofs<A> extends never ? never : ProofPersistence)\n | (Enabled<A, \"phone\"> extends never ? never : PhoneAdmission | PhoneSignInTargets);\n\nexport type Roles<C extends ClaimsCodec, Id extends string, A extends Definition<C, Id>> =\n | \"identifiers\"\n | \"credentials\"\n | \"sessions\"\n | \"sessionFlows\"\n | (Enabled<A, \"password\"> extends never\n ? never\n :\n | \"passwords\"\n | \"passwordAttempts\"\n | \"passwordScopes\"\n | \"passwordCharges\"\n | \"passwordCommands\")\n | (ManagedPassword<A> extends never ? never : \"passwordRegistrations\")\n | (Enabled<A, \"phone\"> extends never ? never : \"phoneState\")\n | (Enabled<A, \"email\"> extends never ? never : \"emailCredentials\" | \"emailCommands\")\n | (Enabled<A, \"passkey\"> extends never\n ? never\n :\n | \"passkeyCredentials\"\n | \"passkeyOwnership\"\n | \"passkeyHandles\"\n | \"passkeyModules\"\n | \"passkeyFlows\"\n | \"passkeyAdmissions\"\n | \"passkeyCharges\")\n | (ManagedPasskey<A> extends never ? never : \"passkeyCommands\")\n | (UsesProofs<A> extends never ? never : ProofRoles);\n\nexport interface SubjectOptions<T extends object, NativeId> {\n readonly table: T;\n readonly id: string;\n readonly status: string;\n readonly activeValue: unknown;\n readonly securityRevision: string;\n readonly idCodec: Schema.Codec<SubjectId, NativeId>;\n readonly requirements: (\n row: Readonly<Record<string, unknown>>,\n ) => Effect.Effect<AuthenticationRequirement, PersistenceMappingError>;\n /** Defaults to sign-in requirements. Recovery can have a distinct application policy. */\n readonly actionRequirements?: (\n row: Readonly<Record<string, unknown>>,\n action: PasswordAction | EmailAction | PasskeyActionChallenge[\"action\"],\n ) => Effect.Effect<AuthenticationRequirement, PersistenceMappingError>;\n}\n\n/** Codecs at the application-owned subject and timestamp boundary. */\nexport interface SubjectMapping {\n readonly table: object;\n readonly id: string;\n readonly status: string;\n readonly securityRevision: string;\n readonly activeValue: unknown;\n readonly requirements: SubjectOptions<object, unknown>[\"requirements\"];\n readonly actionRequirements: NonNullable<SubjectOptions<object, unknown>[\"actionRequirements\"]>;\n readonly toSubject: (value: unknown) => Effect.Effect<SubjectId, PersistenceMappingError>;\n readonly toNative: (value: SubjectId) => Effect.Effect<unknown, PersistenceMappingError>;\n readonly toSubjectSync: (value: unknown) => SubjectId;\n readonly toNativeSync: (value: SubjectId) => unknown;\n}\n\nexport interface MappingInput {\n readonly tables: Partial<Record<StorageRole, object>>;\n readonly subjects: SubjectMapping;\n readonly encodeInstant: (millis: number) => unknown;\n readonly decodeInstant: (value: unknown) => Effect.Effect<number, PersistenceMappingError>;\n readonly decodeInstantSync: (value: unknown) => number;\n}\n\nexport interface StorageLayout<\n T extends object,\n Role extends StorageRole = StorageRole,\n> extends MappingInput {\n readonly namespace: string;\n readonly schema: Readonly<Record<Role, T>>;\n}\n\nexport interface ConfigId<Id extends string> {\n readonly authNamespace: Id;\n readonly service: \"PersistenceConfig\";\n}\n\nexport interface TimestampOptions<Instant> {\n readonly type: \"text\" | \"integer\";\n readonly codec: Schema.Codec<number, Instant>;\n}\n\nexport interface BoundPersistence<\n T extends object,\n R,\n C extends ClaimsCodec,\n Id extends string,\n A extends Definition<C, Id>,\n> {\n readonly Config: Context.Service<ConfigId<A[\"namespace\"]>, StorageLayout<T, Roles<C, Id, A>>> & {\n readonly layer: (\n value: StorageLayout<T, Roles<C, Id, A>>,\n ) => Layer.Layer<ConfigId<A[\"namespace\"]>>;\n };\n /** Create only the application subject. Runs inside the owning auth SQL transaction;\n * use that SqlClient (including Drizzle over it), and return the new subject ID.\n * Do not perform external side effects or open an independent transaction here.\n */\n readonly Provisioning: Context.Service<ProvisioningRequirement<A>, Provisioning<A>>;\n readonly layer: Layer.Layer<\n Ports<C, Id, A>,\n PersistenceConfigurationError,\n | ConfigId<A[\"namespace\"]>\n | ProvisioningRequirement<A>\n | PasskeyRequirement<A>\n | SqlClient.SqlClient\n | R\n >;\n readonly managed: <N, Instant = number>(options: {\n readonly subjects: SubjectOptions<T, N>;\n readonly tables?: Partial<Record<Roles<C, Id, A>, T>>;\n readonly prefix?: string;\n readonly timestamps?: TimestampOptions<Instant>;\n }) => StorageLayout<T, Roles<C, Id, A>>;\n readonly map: <N, Instant = number>(options: {\n readonly subjects: SubjectOptions<T, N>;\n readonly tables: Readonly<Record<Roles<C, Id, A>, T>>;\n readonly timestamps?: TimestampOptions<Instant>;\n }) => StorageLayout<T, Roles<C, Id, A>>;\n}\n\n/** Shared configuration shape. The backend chooses table types and service requirements. */\nexport interface PersistenceApi<T extends object, R = never> {\n readonly make: <\n C extends ClaimsCodec,\n const Id extends string,\n const A extends Definition<C, Id>,\n >(\n auth: A & Definition<C, Id>,\n ) => BoundPersistence<T, R, C, Id, A>;\n}\n"],"mappings":";;AAgCA,IAAa,gCAAb,cAAmD,OAAO,YAA2C,CAAC,CACpG,iCACA,EAAE,QAAQ,OAAO,OAAO,CAC1B,CAAC,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"configuration.mjs","names":[],"sources":["../../src/internal/configuration.ts"],"sourcesContent":["import type { EmailAction, EmailAddressPersistence } from \"@yielded/auth/Email\";\nimport type { LoginIdentifier } from \"@yielded/auth/Identity\";\nimport type {\n PasskeyActionChallenge,\n PasskeyConfig,\n PasskeyCredentials,\n PasskeyEnrollmentContext,\n PasskeyManagementPersistence,\n PasskeyManagementPolicy,\n PasskeyMethodPolicy,\n PasskeyPersistence,\n PasskeyConfigurationError,\n} from \"@yielded/auth/Passkey\";\nimport type {\n PasswordAction,\n PasswordPersistence,\n PasswordUnavailable,\n} from \"@yielded/auth/Password\";\nimport type { PhoneAdmission, PhoneSignInTargets } from \"@yielded/auth/PhoneOtp\";\nimport type { ProofPersistence } from \"@yielded/auth/Proofs\";\nimport type { SubjectId } from \"@yielded/auth/Schema\";\nimport type {\n AuthenticationAuthority,\n AuthenticationRequirement,\n make as makeSessions,\n} from \"@yielded/auth/Sessions\";\nimport { type Context, type Effect, type Layer, Schema } from \"effect\";\nimport type { SqlClient } from \"effect/sql\";\n\nimport type { PersistenceMappingError } from \"./mapping-error\";\nimport type { StorageRole } from \"./storage-tables\";\n\nexport class PersistenceConfigurationError extends Schema.TaggedError<PersistenceConfigurationError>()(\n \"PersistenceConfigurationError\",\n { reason: Schema.String },\n) {}\n\nexport type ClaimsCodec = Schema.Codec<unknown, unknown, never, never>;\n\nexport interface PasskeyFeature {\n readonly kind: \"passkey\";\n readonly moduleId: string;\n readonly policy: Effect.Effect<PasskeyMethodPolicy, PasskeyConfigurationError, PasskeyConfig>;\n readonly management?: boolean;\n readonly managementPolicy?: PasskeyManagementPolicy;\n}\n\nexport interface Strategy {\n readonly strategy: object;\n readonly persistence?:\n | PasskeyFeature\n | {\n readonly kind: \"password\" | \"phone\" | \"email\";\n readonly moduleId: string;\n readonly lifecycle?: boolean;\n readonly management?: boolean;\n readonly addresses?: boolean;\n };\n readonly RegistrationAuthority?: Context.Key<unknown, unknown>;\n}\n\nexport interface Definition<C extends ClaimsCodec, Id extends string> {\n readonly namespace: string;\n readonly claims: C;\n readonly sessionMode?: string;\n readonly sessions: ReturnType<typeof makeSessions<C, Id>>;\n readonly strategies: Readonly<Record<string, Strategy>>;\n}\n\ntype KeyId<T> = T extends Context.Key<infer Id, infer _Service> ? Id : never;\ntype Enabled<\n A extends { readonly strategies: Readonly<Record<string, Strategy>> },\n Kind extends \"password\" | \"phone\" | \"email\" | \"passkey\",\n> = Extract<A[\"strategies\"][keyof A[\"strategies\"]], { persistence: { kind: Kind } }>;\n\ntype ManagedPassword<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> =\n Extract<Enabled<A, \"password\">, { persistence: { management: true } }>;\n\ntype ManagedPasskey<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> =\n Extract<Enabled<A, \"passkey\">, { persistence: { management: true } }>;\n\nexport type PasskeyRequirement<\n A extends { readonly strategies: Readonly<Record<string, Strategy>> },\n> = Enabled<A, \"passkey\"> extends never ? never : PasskeyConfig;\n\ntype RegistrationKey<S> = S extends { readonly RegistrationAuthority: infer K } ? K : never;\ntype Registration<S> =\n RegistrationKey<S> extends Context.Key<infer _Id, infer Service>\n ? Service extends { readonly register: (input: infer Input, ...args: never[]) => unknown }\n ? Input extends { readonly registration: infer Value }\n ? Value\n : never\n : never\n : never;\n\nexport interface ProvisioningId<Id extends string> {\n readonly authNamespace: Id;\n readonly service: \"PersistenceProvisioning\";\n}\n\nexport type Provisioning<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> = {\n readonly [\n K in keyof A[\"strategies\"] as A[\"strategies\"][K] extends {\n persistence: { kind: \"password\"; management: true };\n }\n ? K\n : never\n ]: (input: {\n readonly identifier: LoginIdentifier;\n readonly registration: Registration<A[\"strategies\"][K]>;\n }) => Effect.Effect<SubjectId, PasswordUnavailable>;\n};\n\nexport type ProvisioningRequirement<\n A extends { readonly namespace: string; readonly strategies: Readonly<Record<string, Strategy>> },\n> = ManagedPassword<A> extends never ? never : ProvisioningId<A[\"namespace\"]>;\n\ntype ProofRoles =\n | \"proofRequests\"\n | \"proofSeries\"\n | \"proofGenerations\"\n | \"proofContinuations\"\n | \"proofScopes\"\n | \"proofAbuse\"\n | \"proofFailures\"\n | \"proofCommands\";\n\ntype UsesProofs<A extends { readonly strategies: Readonly<Record<string, Strategy>> }> =\n | Enabled<A, \"phone\">\n | Enabled<A, \"email\">\n | ManagedPassword<A>;\n\nexport type Ports<C extends ClaimsCodec, Id extends string, A extends Definition<C, Id>> =\n | AuthenticationAuthority\n | KeyId<A[\"sessions\"][\"StatefulSessionPersistence\"]>\n | KeyId<A[\"sessions\"][\"SessionRepository\"]>\n | (Enabled<A, \"password\"> extends never ? never : PasswordPersistence)\n | KeyId<RegistrationKey<ManagedPassword<A>>>\n | (Enabled<A, \"passkey\"> extends never ? never : PasskeyPersistence | PasskeyCredentials)\n | (ManagedPasskey<A> extends never\n ? never\n : PasskeyManagementPersistence | PasskeyEnrollmentContext)\n | (Enabled<A, \"email\"> extends never ? never : EmailAddressPersistence)\n | (UsesProofs<A> extends never ? never : ProofPersistence)\n | (Enabled<A, \"phone\"> extends never ? never : PhoneAdmission | PhoneSignInTargets);\n\nexport type Roles<C extends ClaimsCodec, Id extends string, A extends Definition<C, Id>> =\n | \"identifiers\"\n | \"credentials\"\n | \"sessions\"\n | \"sessionFlows\"\n | (Enabled<A, \"password\"> extends never\n ? never\n :\n | \"passwords\"\n | \"passwordAttempts\"\n | \"passwordScopes\"\n | \"passwordCharges\"\n | \"passwordCommands\")\n | (ManagedPassword<A> extends never ? never : \"passwordRegistrations\")\n | (Enabled<A, \"phone\"> extends never ? never : \"phoneState\")\n | (Enabled<A, \"email\"> extends never ? never : \"emailCredentials\" | \"emailCommands\")\n | (Enabled<A, \"passkey\"> extends never\n ? never\n :\n | \"passkeyCredentials\"\n | \"passkeyOwnership\"\n | \"passkeyHandles\"\n | \"passkeyModules\"\n | \"passkeyFlows\"\n | \"passkeyAdmissions\"\n | \"passkeyCharges\")\n | (ManagedPasskey<A> extends never ? never : \"passkeyCommands\")\n | (UsesProofs<A> extends never ? never : ProofRoles);\n\nexport interface SubjectOptions<T extends object, NativeId> {\n readonly table: T;\n readonly id: string;\n readonly status: string;\n readonly activeValue: unknown;\n readonly securityRevision: string;\n readonly idCodec: Schema.Codec<SubjectId, NativeId>;\n readonly requirements: (\n row: Readonly<Record<string, unknown>>,\n ) => Effect.Effect<AuthenticationRequirement, PersistenceMappingError>;\n /** Defaults to sign-in requirements. Recovery can have a distinct application policy. */\n readonly actionRequirements?: (\n row: Readonly<Record<string, unknown>>,\n action: PasswordAction | EmailAction | PasskeyActionChallenge[\"action\"],\n ) => Effect.Effect<AuthenticationRequirement, PersistenceMappingError>;\n}\n\n/** Codecs at the application-owned subject and timestamp boundary. */\nexport interface SubjectMapping {\n readonly table: object;\n readonly id: string;\n readonly status: string;\n readonly securityRevision: string;\n readonly activeValue: unknown;\n readonly requirements: SubjectOptions<object, unknown>[\"requirements\"];\n readonly actionRequirements: NonNullable<SubjectOptions<object, unknown>[\"actionRequirements\"]>;\n readonly toSubject: (value: unknown) => Effect.Effect<SubjectId, PersistenceMappingError>;\n readonly toNative: (value: SubjectId) => Effect.Effect<unknown, PersistenceMappingError>;\n readonly toSubjectSync: (value: unknown) => SubjectId;\n readonly toNativeSync: (value: SubjectId) => unknown;\n}\n\nexport interface MappingInput {\n readonly tables: Partial<Record<StorageRole, object>>;\n readonly subjects: SubjectMapping;\n readonly encodeInstant: (millis: number) => unknown;\n readonly decodeInstant: (value: unknown) => Effect.Effect<number, PersistenceMappingError>;\n readonly decodeInstantSync: (value: unknown) => number;\n}\n\nexport interface StorageLayout<\n T extends object,\n Role extends StorageRole = StorageRole,\n> extends MappingInput {\n readonly namespace: string;\n readonly schema: Readonly<Record<Role, T>>;\n}\n\nexport interface ConfigId<Id extends string> {\n readonly authNamespace: Id;\n readonly service: \"PersistenceConfig\";\n}\n\nexport interface TimestampOptions<Instant> {\n readonly type: \"text\" | \"integer\";\n readonly codec: Schema.Codec<number, Instant>;\n}\n\nexport interface BoundPersistence<\n T extends object,\n R,\n C extends ClaimsCodec,\n Id extends string,\n A extends Definition<C, Id>,\n> {\n readonly Config: Context.Service<ConfigId<A[\"namespace\"]>, StorageLayout<T, Roles<C, Id, A>>> & {\n readonly layer: (\n value: StorageLayout<T, Roles<C, Id, A>>,\n ) => Layer.Layer<ConfigId<A[\"namespace\"]>>;\n };\n /** Create only the application subject. Runs inside the owning auth SQL transaction;\n * use that SqlClient (including Drizzle over it), and return the new subject ID.\n * Do not perform external side effects or open an independent transaction here.\n */\n readonly Provisioning: Context.Service<ProvisioningRequirement<A>, Provisioning<A>>;\n readonly layer: Layer.Layer<\n Ports<C, Id, A>,\n PersistenceConfigurationError,\n | ConfigId<A[\"namespace\"]>\n | ProvisioningRequirement<A>\n | PasskeyRequirement<A>\n | SqlClient.SqlClient\n | R\n >;\n readonly managed: <N, Instant = number>(options: {\n readonly subjects: SubjectOptions<T, N>;\n readonly tables?: Partial<Record<Roles<C, Id, A>, T>>;\n readonly prefix?: string;\n readonly timestamps?: TimestampOptions<Instant>;\n }) => StorageLayout<T, Roles<C, Id, A>>;\n readonly map: <N, Instant = number>(options: {\n readonly subjects: SubjectOptions<T, N>;\n readonly tables: Readonly<Record<Roles<C, Id, A>, T>>;\n readonly timestamps?: TimestampOptions<Instant>;\n }) => StorageLayout<T, Roles<C, Id, A>>;\n}\n\n/** Shared configuration shape. The backend chooses table types and service requirements. */\nexport interface PersistenceApi<T extends object, R = never> {\n readonly make: <\n C extends ClaimsCodec,\n const Id extends string,\n const A extends Definition<C, Id>,\n >(\n auth: A & Definition<C, Id>,\n ) => BoundPersistence<T, R, C, Id, A>;\n}\n"],"mappings":";;AAgCA,IAAa,gCAAb,cAAmD,OAAO,YAA2C,CAAC,CACpG,iCACA,EAAE,QAAQ,OAAO,OAAO,CAC1B,CAAC,CAAC,CAAC"}
|
|
@@ -8,7 +8,7 @@ import { AuthenticationRevision, SecurityRevision } from "@yielded/auth/Sessions
|
|
|
8
8
|
import { EmailAddressMutation, EmailCredentialSnapshot, EmailUnavailable } from "@yielded/auth/Email";
|
|
9
9
|
import { ProofCompletionInput } from "@yielded/auth/Proofs";
|
|
10
10
|
import { LoginIdentifier } from "@yielded/auth/Identity";
|
|
11
|
-
import * as SqlError$1 from "effect/
|
|
11
|
+
import * as SqlError$1 from "effect/sql/SqlError";
|
|
12
12
|
//#region src/internal/email-kernel.d.ts
|
|
13
13
|
type AdapterFailure = QueryFailure | PersistenceMappingError | SqlError$1.SqlError;
|
|
14
14
|
type SignInMapping = AnyEmailSignInMapping;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-kernel.mjs","names":[],"sources":["../../src/internal/email-kernel.ts"],"sourcesContent":["import {\n EmailAddressPersistence,\n type EmailAddressMutation,\n type EmailAction,\n type EmailCredentialSnapshot,\n EmailSignInTargets,\n EmailUnavailable,\n snapshotEmailCredential,\n snapshotEmailRequirement,\n snapshotEmailRevision,\n} from \"@yielded/auth/Email\";\nimport {\n coordinateCommit,\n CurrentCommitJournal,\n hasCommitScope,\n type CommitJournal,\n type PreparedCommit,\n LifecycleHooks,\n HookConfigurationError,\n} from \"@yielded/auth/Hooks\";\nimport type { LoginIdentifier } from \"@yielded/auth/Identity\";\nimport { reportPersistenceFailure } from \"@yielded/auth/Persistence\";\nimport {\n ProofUnavailable,\n type ProofCompletionDecision,\n type ProofCompletionInput,\n} from \"@yielded/auth/Proofs\";\nimport {\n assessAuthentication,\n snapshotAuthenticationEvidence,\n type AuthenticationRevision,\n type SecurityRevision,\n} from \"@yielded/auth/Sessions\";\nimport { Cause, Context, DateTime, Effect, Option, Schema } from \"effect\";\nimport type * as SqlError from \"effect/unstable/sql/SqlError\";\n\nimport { isMappedConstraintConflict, PersistenceMappingError } from \"./mapping-error\";\nimport {\n type AnyEmailAddressMapping,\n type AnyEmailSignInMapping,\n requiredEmailAddressConstraints,\n requiredEmailSignInConstraints,\n} from \"./models/email-model\";\nimport {\n CurrentProofSql,\n type makeProofKernel,\n type ProofSqlConfiguration,\n type ProofSqlDatabase,\n} from \"./proof-kernel\";\n/* oxlint-disable no-explicit-any -- the shared dialect kernel erases consumer Drizzle table types internally. */\nimport type { QueryFailure } from \"./query-operations\";\nimport type { QueryOperations, SqlFragment, SqlColumn } from \"./query-operations\";\n\ntype AdapterFailure = QueryFailure | PersistenceMappingError | SqlError.SqlError;\ntype SignInMapping = AnyEmailSignInMapping;\n\nexport interface EmailSqlQuery<A = ReadonlyArray<any>> extends Effect.Effect<A, AdapterFailure> {\n readonly getSQL: () => ReturnType<QueryOperations[\"sql\"]>;\n readonly from: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly where: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly limit: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly orderBy: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly for: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly set: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly values: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly returning: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly innerJoin: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly onConflictDoNothing: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly onDuplicateKeyUpdate: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly $returningId: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n}\n\nexport interface EmailSqlDatabase {\n readonly select: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly insert: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly update: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly delete: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly transaction: <A, E, R>(\n body: (transaction: EmailSqlDatabase) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | SqlError.SqlError, R>;\n}\n\nexport class CurrentEmailSql extends Context.Service<CurrentEmailSql, EmailSqlDatabase>()(\n \"effect-auth/CurrentEmailSql\",\n) {}\n\nexport interface EmailSqlConfiguration {\n readonly mode: \"interactive\" | \"synchronous\";\n readonly locking: boolean;\n readonly standaloneGuard: Effect.Effect<void, EmailUnavailable>;\n readonly coordinated?: boolean;\n readonly proof?: {\n readonly mapping: any;\n readonly configuration: ProofSqlConfiguration;\n };\n}\n\nexport interface CurrentAddress {\n readonly nativeSubjectId: unknown;\n readonly subject: any;\n readonly revision: AuthenticationRevision;\n readonly source?: {\n readonly credential: any;\n readonly identifier: any;\n readonly snapshot: EmailCredentialSnapshot;\n };\n readonly targetIdentifier?: any;\n readonly targetCredential?: any;\n readonly targetIdentifierRevision?: SecurityRevision;\n readonly eligible: boolean;\n}\n\nexport const makeEmailKernel = <\n Fragment extends SqlFragment = SqlFragment,\n Column extends SqlColumn = SqlColumn,\n>(\n operations: QueryOperations<Fragment, Column>,\n proofs: Pick<ReturnType<typeof makeProofKernel>, \"completeProofPlanIn\">,\n) => {\n type AddressMapping = AnyEmailAddressMapping<Fragment>;\n\n const { and, eq, inArray, lte, column, updateValues } = operations;\n const { completeProofPlanIn } = proofs;\n const unavailable = () => EmailUnavailable.make({});\n\n const translateFailure = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, EmailUnavailable, R> =>\n reportPersistenceFailure(\n effect,\n (error) =>\n Schema.is(EmailUnavailable)(error) ||\n Schema.is(ProofUnavailable)(error) ||\n Schema.is(HookConfigurationError)(error),\n ).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));\n\n const nowMillis = Effect.map(DateTime.now, DateTime.toEpochMillis);\n\n const selectRows = (query: EmailSqlQuery, locking: boolean) =>\n locking && typeof query.for === \"function\" ? query.for(\"update\") : query;\n\n const sameIdentifier = (left: LoginIdentifier, right: LoginIdentifier) =>\n left.namespace === right.namespace && left.value === right.value;\n\n const validEmailSignInConstraints = (mapping: SignInMapping) =>\n Object.entries(requiredEmailSignInConstraints).every(\n ([key, value]) =>\n mapping.constraints[key as keyof typeof requiredEmailSignInConstraints] === value,\n );\n\n const validAddressConstraints = (mapping: AddressMapping) =>\n Object.entries(requiredEmailAddressConstraints).every(\n ([key, value]) =>\n mapping.constraints[key as keyof typeof requiredEmailAddressConstraints] === value,\n );\n\n const subjectColumns = (mapping: SignInMapping) => ({\n id: column(mapping.subject.table, mapping.subject.id),\n status: column(mapping.subject.table, mapping.subject.status),\n securityRevision: column(mapping.subject.table, mapping.subject.securityRevision),\n });\n\n const identifierColumns = (mapping: SignInMapping) => ({\n namespace: column(mapping.identifier.table, mapping.identifier.namespace),\n value: column(mapping.identifier.table, mapping.identifier.value),\n subjectId: column(mapping.identifier.table, mapping.identifier.subjectId),\n verifiedAt: column(mapping.identifier.table, mapping.identifier.verifiedAt),\n bindingRevision: column(mapping.identifier.table, mapping.identifier.bindingRevision),\n });\n\n const credentialColumns = (mapping: SignInMapping) => ({\n moduleId: column(mapping.credential.table, mapping.credential.moduleId),\n subjectId: column(mapping.credential.table, mapping.credential.subjectId),\n credentialId: column(mapping.credential.table, mapping.credential.credentialId),\n identifierNamespace: column(mapping.credential.table, mapping.credential.identifierNamespace),\n identifierValue: column(mapping.credential.table, mapping.credential.identifierValue),\n credentialRevision: column(mapping.credential.table, mapping.credential.credentialRevision),\n status: column(mapping.credential.table, mapping.credential.status),\n });\n\n const authorityColumns = (mapping: AddressMapping) => ({\n subjectId: column(mapping.authorityCredential.table, mapping.authorityCredential.subjectId),\n credentialId: column(\n mapping.authorityCredential.table,\n mapping.authorityCredential.credentialId,\n ),\n revision: column(mapping.authorityCredential.table, mapping.authorityCredential.revision),\n status: column(mapping.authorityCredential.table, mapping.authorityCredential.status),\n });\n\n const commandColumns = (mapping: AddressMapping) => ({\n moduleId: column(mapping.command.table, mapping.command.moduleId),\n commandId: column(mapping.command.table, mapping.command.commandId),\n action: column(mapping.command.table, mapping.command.action),\n bindingDigest: column(mapping.command.table, mapping.command.bindingDigest),\n retentionUntil: column(mapping.command.table, mapping.command.retentionUntil),\n });\n\n const allocate = <A>(\n mode: EmailSqlConfiguration[\"mode\"],\n asynchronous: Effect.Effect<A, PersistenceMappingError> | undefined,\n synchronous: (() => A) | undefined,\n ) => {\n if (mode === \"synchronous\")\n return synchronous === undefined\n ? Effect.fail(unavailable())\n : Effect.try({\n try: synchronous,\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n if (asynchronous !== undefined) return asynchronous;\n\n return synchronous === undefined\n ? Effect.fail(unavailable())\n : Effect.try({\n try: synchronous,\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n };\n\n const nextSecurityRevision = (\n mapping: AddressMapping,\n mode: EmailSqlConfiguration[\"mode\"],\n current: SecurityRevision,\n ) => {\n if (mode === \"synchronous\")\n return mapping.subject.nextSecurityRevisionSync === undefined\n ? Effect.fail(unavailable())\n : Effect.try({\n try: () => mapping.subject.nextSecurityRevisionSync!(current),\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n if (mapping.subject.nextSecurityRevision !== undefined)\n return mapping.subject.nextSecurityRevision(current);\n if (mapping.subject.nextSecurityRevisionSync !== undefined)\n return Effect.try({\n try: () => mapping.subject.nextSecurityRevisionSync!(current),\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n\n return Effect.fail(unavailable());\n };\n\n const safeRead = <A, E, R>(\n database: EmailSqlDatabase,\n configuration: EmailSqlConfiguration,\n body: Effect.Effect<A, E, R>,\n ) =>\n Effect.gen(function* () {\n if (configuration.coordinated !== true) {\n if (yield* hasCommitScope) return yield* unavailable();\n yield* configuration.standaloneGuard;\n }\n\n return yield* database.transaction((transaction) =>\n body.pipe(\n Effect.provideService(CurrentEmailSql, transaction),\n Effect.provideService(CurrentProofSql, transaction as unknown as ProofSqlDatabase),\n ),\n );\n });\n\n const owned = <A, E, R>(\n database: EmailSqlDatabase,\n configuration: EmailSqlConfiguration,\n body: Effect.Effect<A, E, R>,\n ) => {\n const run = coordinateCommit(\n () =>\n database.transaction((transaction) =>\n body.pipe(\n Effect.provideService(CurrentEmailSql, transaction),\n Effect.provideService(CurrentProofSql, transaction as unknown as ProofSqlDatabase),\n ),\n ),\n { mode: configuration.mode },\n ).pipe(Effect.map((result) => result.value));\n\n return configuration.coordinated !== true\n ? Effect.gen(function* () {\n if (yield* hasCommitScope) return yield* unavailable();\n yield* configuration.standaloneGuard;\n\n return yield* run;\n })\n : run;\n };\n\n const emailLookupQuery = (\n mapping: SignInMapping,\n moduleId: string,\n identifier: LoginIdentifier,\n ) => {\n const subject = subjectColumns(mapping),\n binding = identifierColumns(mapping),\n credential = credentialColumns(mapping);\n\n return {\n fields: {\n subject: mapping.subject.table,\n identifier: mapping.identifier.table,\n credential: mapping.credential.table,\n },\n from: mapping.identifier.table,\n subjectTable: mapping.subject.table,\n subjectJoin: eq(subject.id, binding.subjectId),\n credentialTable: mapping.credential.table,\n credentialJoin: and(\n eq(credential.moduleId, moduleId),\n eq(credential.subjectId, binding.subjectId),\n eq(credential.identifierNamespace, binding.namespace),\n eq(credential.identifierValue, binding.value),\n ),\n predicate: and(\n eq(binding.namespace, identifier.namespace),\n eq(binding.value, identifier.value),\n ),\n limit: 1,\n };\n };\n\n const emailLookupRows = Effect.fn(\"Drizzle.emailLookupRows\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n identifier: LoginIdentifier,\n ) {\n const database = yield* CurrentEmailSql;\n const query = emailLookupQuery(mapping, moduleId, identifier);\n\n return yield* database\n .select(query.fields)\n .from(query.from)\n .innerJoin(query.subjectTable, query.subjectJoin)\n .innerJoin(query.credentialTable, query.credentialJoin)\n .where(query.predicate)\n .limit(query.limit);\n });\n\n const decodeEmailSnapshot = Effect.fn(\"DrizzleEmail.decodeSnapshot\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n requested: LoginIdentifier,\n row: any,\n ) {\n if (\n !mapping.subject.isActiveStatus(row.subject[mapping.subject.status]) ||\n !mapping.identifier.isCurrent(row.identifier) ||\n !mapping.credential.isActiveStatus(row.credential[mapping.credential.status])\n )\n return undefined;\n\n const snapshot = yield* mapping.credential\n .decode({\n moduleId,\n subject: row.subject,\n identifier: row.identifier,\n credential: row.credential,\n })\n .pipe(Effect.flatMap(snapshotEmailCredential));\n\n const subjectId = yield* mapping.subjectId.toSubject(row.subject[mapping.subject.id]);\n\n const verifiedAtMillis = yield* mapping.decodeInstant(\n row.identifier[mapping.identifier.verifiedAt],\n );\n\n if (\n snapshot.moduleId !== moduleId ||\n !sameIdentifier(snapshot.identifier, requested) ||\n snapshot.revision.subjectId !== subjectId ||\n snapshot.revision.securityRevision !== row.subject[mapping.subject.securityRevision] ||\n snapshot.identifierRevision !== row.identifier[mapping.identifier.bindingRevision] ||\n snapshot.verifiedAtMillis !== verifiedAtMillis ||\n snapshot.credentialId !== row.credential[mapping.credential.credentialId] ||\n snapshot.credentialRevision !== row.credential[mapping.credential.credentialRevision]\n )\n return undefined;\n\n return snapshot;\n });\n\n const makeSqlEmailSignInTargets = Effect.fn(\"makeSqlEmailSignInTargets\")(function (\n database: EmailSqlDatabase,\n mapping: SignInMapping,\n configuration: EmailSqlConfiguration,\n ): Effect.Effect<EmailSignInTargets[\"Service\"]> {\n return Effect.succeed(\n EmailSignInTargets.of({\n lookup: (input) =>\n (validEmailSignInConstraints(mapping)\n ? safeRead(\n database,\n configuration,\n Effect.gen(function* () {\n const row = (yield* emailLookupRows(\n mapping,\n input.moduleId,\n input.identifier,\n ))[0];\n\n if (row === undefined) return Option.none();\n\n const snapshot = yield* decodeEmailSnapshot(\n mapping,\n input.moduleId,\n input.identifier,\n row,\n );\n\n return snapshot === undefined ? Option.none() : Option.some(snapshot);\n }),\n )\n : Effect.fail(unavailable())\n ).pipe(Effect.provideService(CurrentEmailSql, database), translateFailure),\n }),\n );\n });\n\n const readSubject = Effect.fn(\"DrizzleEmail.readSubject\")(function* (\n mapping: AddressMapping,\n subjectId: string,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const nativeSubjectId = yield* mapping.subjectId.toNative(subjectId as any);\n const s = subjectColumns(mapping);\n\n const subject = (yield* selectRows(\n database.select().from(mapping.subject.table).where(eq(s.id, nativeSubjectId)).limit(1),\n locking,\n ))[0];\n\n return { nativeSubjectId, subject };\n });\n\n const identifierRow = Effect.fn(\"Drizzle.identifierRow\")(function* (\n mapping: SignInMapping,\n identifier: LoginIdentifier,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const i = identifierColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.identifier.table)\n .where(and(eq(i.namespace, identifier.namespace), eq(i.value, identifier.value)))\n .limit(1),\n locking,\n );\n });\n\n const credentialById = Effect.fn(\"Drizzle.credentialById\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n credentialId: string,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const c = credentialColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(and(eq(c.moduleId, moduleId), eq(c.credentialId, credentialId)))\n .limit(1),\n locking,\n );\n });\n\n const credentialByIdentifier = Effect.fn(\"Drizzle.credentialByIdentifier\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n identifier: LoginIdentifier,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const c = credentialColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(\n and(\n eq(c.moduleId, moduleId),\n eq(c.identifierNamespace, identifier.namespace),\n eq(c.identifierValue, identifier.value),\n ),\n )\n .limit(1),\n locking,\n );\n });\n\n const currentAddress = Effect.fn(\"DrizzleEmail.currentAddress\")(function* (\n mapping: AddressMapping,\n input: {\n readonly moduleId: string;\n readonly subjectId: string;\n readonly target: LoginIdentifier;\n readonly sourceCredentialId?: string;\n },\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const locked = yield* readSubject(mapping, input.subjectId, locking);\n\n if (\n locked.subject === undefined ||\n !mapping.subject.isActiveStatus(locked.subject[mapping.subject.status])\n )\n return undefined;\n\n const discoveredSource =\n input.sourceCredentialId === undefined\n ? undefined\n : (yield* credentialById(mapping, input.moduleId, input.sourceCredentialId, false))[0];\n\n const sourceIdentifier: LoginIdentifier | undefined =\n discoveredSource === undefined\n ? undefined\n : {\n namespace: discoveredSource[mapping.credential.identifierNamespace],\n value: discoveredSource[mapping.credential.identifierValue],\n };\n\n const identifiers = [\n input.target,\n ...(sourceIdentifier === undefined ? [] : [sourceIdentifier]),\n ]\n .filter(\n (value, index, values) =>\n values.findIndex((candidate) => sameIdentifier(candidate, value)) === index,\n )\n .sort((left, right) =>\n `${left.namespace}\\u0000${left.value}`.localeCompare(\n `${right.namespace}\\u0000${right.value}`,\n ),\n );\n\n const lockedIdentifiers = new Map<string, any>();\n\n for (const identifier of identifiers) {\n const row = (yield* identifierRow(mapping, identifier, locking))[0];\n\n if (row !== undefined)\n lockedIdentifiers.set(`${identifier.namespace}\\u0000${identifier.value}`, row);\n }\n\n const sourceCredential =\n input.sourceCredentialId === undefined\n ? undefined\n : (yield* credentialById(mapping, input.moduleId, input.sourceCredentialId, locking))[0];\n\n const targetCredential = (yield* credentialByIdentifier(\n mapping,\n input.moduleId,\n input.target,\n locking,\n ))[0];\n\n const a = authorityColumns(mapping);\n\n const authority = yield* selectRows(\n database\n .select()\n .from(mapping.authorityCredential.table)\n .where(eq(a.subjectId, locked.nativeSubjectId))\n .orderBy(a.credentialId),\n locking,\n );\n\n const activeAuthority = authority.filter((row: any) =>\n mapping.authorityCredential.isActiveStatus(row[mapping.authorityCredential.status]),\n );\n\n const subjectId = yield* mapping.subjectId.toSubject(locked.nativeSubjectId);\n\n const revision: AuthenticationRevision = Object.freeze({\n subjectId,\n securityRevision: locked.subject[mapping.subject.securityRevision],\n credentials: Object.freeze(\n activeAuthority.map((row: any) =>\n Object.freeze({\n credentialId: row[mapping.authorityCredential.credentialId],\n revision: row[mapping.authorityCredential.revision],\n }),\n ),\n ),\n });\n\n const targetIdentifier = lockedIdentifiers.get(\n `${input.target.namespace}\\u0000${input.target.value}`,\n );\n\n const targetOwned =\n targetIdentifier !== undefined &&\n mapping.subjectId.equals(\n targetIdentifier[mapping.identifier.subjectId],\n locked.nativeSubjectId,\n );\n\n const targetMutable =\n targetOwned &&\n mapping.identifier.isMutableTarget(targetIdentifier) &&\n (targetCredential === undefined ||\n (!mapping.credential.isActiveStatus(targetCredential[mapping.credential.status]) &&\n mapping.subjectId.equals(\n targetCredential[mapping.credential.subjectId],\n locked.nativeSubjectId,\n )));\n\n let source: CurrentAddress[\"source\"];\n\n if (input.sourceCredentialId !== undefined) {\n if (\n sourceCredential === undefined ||\n sourceIdentifier === undefined ||\n !mapping.subjectId.equals(\n sourceCredential[mapping.credential.subjectId],\n locked.nativeSubjectId,\n ) ||\n !mapping.credential.isActiveStatus(sourceCredential[mapping.credential.status])\n )\n return undefined;\n\n const sourceIdentifierRow = lockedIdentifiers.get(\n `${sourceIdentifier.namespace}\\u0000${sourceIdentifier.value}`,\n );\n\n if (\n sourceIdentifierRow === undefined ||\n !mapping.identifier.isCurrent(sourceIdentifierRow) ||\n !mapping.subjectId.equals(\n sourceIdentifierRow[mapping.identifier.subjectId],\n locked.nativeSubjectId,\n )\n )\n return undefined;\n\n const snapshot = yield* mapping.credential\n .decode({\n moduleId: input.moduleId,\n subject: locked.subject,\n identifier: sourceIdentifierRow,\n credential: sourceCredential,\n })\n .pipe(Effect.flatMap(snapshotEmailCredential));\n\n source = { credential: sourceCredential, identifier: sourceIdentifierRow, snapshot };\n }\n let eligible = targetIdentifier === undefined ? targetCredential === undefined : targetMutable;\n\n if (input.sourceCredentialId !== undefined && source === undefined) eligible = false;\n if (source !== undefined && sameIdentifier(source.snapshot.identifier, input.target))\n eligible = false;\n if (mapping.addressCardinality === \"single\" && input.sourceCredentialId === undefined) {\n const c = credentialColumns(mapping);\n\n const rows = yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(and(eq(c.moduleId, input.moduleId), eq(c.subjectId, locked.nativeSubjectId))),\n locking,\n );\n\n if (\n rows.some((row: any) => mapping.credential.isActiveStatus(row[mapping.credential.status]))\n )\n eligible = false;\n }\n\n return {\n nativeSubjectId: locked.nativeSubjectId,\n subject: locked.subject,\n revision,\n ...(source === undefined ? {} : { source }),\n ...(targetIdentifier === undefined ? {} : { targetIdentifier }),\n ...(targetCredential === undefined ? {} : { targetCredential }),\n ...(targetMutable\n ? { targetIdentifierRevision: targetIdentifier[mapping.identifier.bindingRevision] }\n : {}),\n eligible,\n };\n });\n\n const sameEmailRevision = (left: AuthenticationRevision, right: AuthenticationRevision) => {\n if (\n left.subjectId !== right.subjectId ||\n left.securityRevision !== right.securityRevision ||\n left.credentials.length !== right.credentials.length\n )\n return false;\n\n const expected = [...left.credentials].sort((a, b) =>\n a.credentialId.localeCompare(b.credentialId),\n );\n\n const actual = [...right.credentials].sort((a, b) =>\n a.credentialId.localeCompare(b.credentialId),\n );\n\n return expected.every(\n (item, index) =>\n item.credentialId === actual[index]!.credentialId &&\n item.revision === actual[index]!.revision,\n );\n };\n\n const actionModule = (moduleId: string, action: EmailAction) =>\n `${moduleId}/${action === \"verify-address\" ? \"verify-address\" : \"change-address\"}`;\n\n const actionPurpose = (action: EmailAction) =>\n action === \"verify-address\" ? \"email-address-verification\" : \"email-address-change\";\n\n const completionMatches = (input: EmailAddressMutation, action: EmailAction) => {\n const completion = input.completion.input;\n const binding = completion.binding;\n\n return (\n completion.moduleId === actionModule(input.moduleId, action) &&\n completion.purpose === actionPurpose(action) &&\n binding._tag === \"IdentifierChange\" &&\n sameIdentifier(binding.identifier, input.target) &&\n sameEmailRevision(binding.revision, input.captured.revision)\n );\n };\n\n const snapshotEmailMutation = Effect.fn(\"DrizzleEmail.snapshotMutation\")(function* (\n input: EmailAddressMutation,\n ) {\n const evidence = yield* snapshotAuthenticationEvidence(input.authorization.evidence).pipe(\n Effect.mapError(unavailable),\n );\n\n const requirement = yield* snapshotEmailRequirement(input.authorization.requirement);\n\n const source =\n input.captured.source === undefined\n ? undefined\n : yield* snapshotEmailCredential(input.captured.source);\n\n return Object.freeze({\n ...input,\n target: Object.freeze({ ...input.target }),\n ...(input.invalidation === undefined\n ? {}\n : { invalidation: Object.freeze({ ...input.invalidation }) }),\n captured: Object.freeze({\n eligible: input.captured.eligible,\n revision: snapshotEmailRevision(input.captured.revision),\n ...(input.captured.targetIdentifierRevision === undefined\n ? {}\n : { targetIdentifierRevision: input.captured.targetIdentifierRevision }),\n ...(source === undefined ? {} : { source }),\n }),\n authorization: Object.freeze({\n challenge: Object.freeze({\n ...input.authorization.challenge,\n target: Object.freeze({ ...input.authorization.challenge.target }),\n revision: snapshotEmailRevision(input.authorization.challenge.revision),\n }),\n evidence,\n requirement,\n }),\n });\n });\n\n const validateEmailAuthority = Effect.fn(\"DrizzleEmail.validateAuthority\")(function* (\n mapping: AddressMapping,\n configuration: EmailSqlConfiguration,\n input: EmailAddressMutation,\n action: EmailAction,\n ) {\n const confirmsExisting =\n action === \"verify-address\" && input.captured.targetIdentifierRevision !== undefined;\n\n if (\n !input.captured.eligible ||\n !completionMatches(input, action) ||\n input.authorization.challenge.moduleId !== input.moduleId ||\n input.authorization.challenge.action !== action ||\n input.authorization.challenge.commandId !== input.commandId ||\n !sameIdentifier(input.authorization.challenge.target, input.target) ||\n input.authorization.challenge.sourceCredentialId !== input.captured.source?.credentialId ||\n !sameEmailRevision(input.authorization.challenge.revision, input.captured.revision) ||\n input.authorization.challenge.targetIdentifierRevision !==\n input.captured.targetIdentifierRevision ||\n (input.authorization.evidence.flowId as string) !== (input.commandId as string) ||\n input.authorization.evidence.bindingDigest !== input.authorization.challenge.bindingDigest ||\n !sameEmailRevision(input.authorization.evidence.revision, input.captured.revision) ||\n (action === \"verify-address\" && input.captured.source !== undefined) ||\n (action === \"change-address\" && input.captured.source === undefined) ||\n confirmsExisting !== (input.invalidation === undefined) ||\n (input.invalidation?.existingSessions === \"immediate\" &&\n mapping.sessionInvalidation !== \"same-authority-immediate\")\n )\n return undefined;\n\n const current = yield* currentAddress(\n mapping,\n {\n moduleId: input.moduleId,\n subjectId: input.captured.revision.subjectId,\n target: input.target,\n ...(input.captured.source === undefined\n ? {}\n : { sourceCredentialId: input.captured.source.credentialId }),\n },\n configuration.locking,\n );\n\n if (\n current === undefined ||\n !current.eligible ||\n !sameEmailRevision(current.revision, input.captured.revision) ||\n current.targetIdentifierRevision !== input.captured.targetIdentifierRevision ||\n (input.captured.source !== undefined &&\n (current.source === undefined ||\n current.source.snapshot.identifierRevision !== input.captured.source.identifierRevision ||\n current.source.snapshot.credentialRevision !== input.captured.source.credentialRevision ||\n !sameIdentifier(current.source.snapshot.identifier, input.captured.source.identifier)))\n )\n return undefined;\n\n const currentRequirement = yield* mapping.subject.decodeActionRequirement(\n current.subject,\n action,\n );\n\n const original = yield* assessAuthentication(\n input.authorization.evidence,\n input.authorization.requirement,\n ).pipe(Effect.mapError(unavailable));\n\n const configured = yield* assessAuthentication(\n input.authorization.evidence,\n currentRequirement,\n ).pipe(Effect.mapError(unavailable));\n\n return original.satisfied && configured.satisfied ? current : undefined;\n });\n\n const commandExists = Effect.fn(\"Drizzle.commandExists\")(function* (\n mapping: AddressMapping,\n moduleId: string,\n commandId: string,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const c = commandColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.command.table)\n .where(and(eq(c.moduleId, moduleId), eq(c.commandId, commandId)))\n .limit(1),\n locking,\n );\n });\n\n const applyMutation = Effect.fn(\"DrizzleEmail.applyMutation\")(function* (\n mapping: AddressMapping,\n input: EmailAddressMutation,\n action: EmailAction,\n current: CurrentAddress,\n allocated: {\n readonly targetCredentialId: string;\n readonly targetIdentifierRevision: SecurityRevision;\n readonly targetCredentialRevision: SecurityRevision;\n readonly sourceIdentifierRevision: SecurityRevision;\n readonly sourceCredentialRevision: SecurityRevision;\n readonly nextSecurityRevision: SecurityRevision;\n },\n now: number,\n ) {\n const database = yield* CurrentEmailSql;\n\n const i = identifierColumns(mapping);\n const c = credentialColumns(mapping);\n const a = authorityColumns(mapping);\n const s = subjectColumns(mapping);\n\n const targetCredentialId =\n current.targetCredential?.[mapping.credential.credentialId] ?? allocated.targetCredentialId;\n\n if (action === \"change-address\") {\n const source = current.source!;\n\n yield* database\n .update(mapping.identifier.table)\n .set(\n mapping.identifier.encodeRetirement({\n source: source.snapshot.identifier,\n bindingRevision: allocated.sourceIdentifierRevision,\n }),\n )\n .where(\n and(\n eq(i.namespace, source.snapshot.identifier.namespace),\n eq(i.value, source.snapshot.identifier.value),\n eq(i.subjectId, current.nativeSubjectId),\n eq(i.bindingRevision, source.snapshot.identifierRevision),\n ),\n );\n yield* database\n .update(mapping.credential.table)\n .set(\n mapping.credential.encodeRetirement({\n source: source.snapshot.identifier,\n credentialRevision: allocated.sourceCredentialRevision,\n }),\n )\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.credentialId, source.snapshot.credentialId),\n eq(c.subjectId, current.nativeSubjectId),\n eq(c.credentialRevision, source.snapshot.credentialRevision),\n ),\n );\n yield* database\n .update(mapping.authorityCredential.table)\n .set(mapping.authorityCredential.encodeRetirement(allocated.sourceCredentialRevision))\n .where(\n and(\n eq(a.subjectId, current.nativeSubjectId),\n eq(a.credentialId, source.snapshot.credentialId),\n eq(a.revision, source.snapshot.credentialRevision),\n ),\n );\n }\n if (current.targetIdentifier === undefined) {\n yield* database.insert(mapping.identifier.table).values(\n mapping.identifier.encodeVerifiedInsert({\n identifier: input.target,\n subjectId: current.nativeSubjectId,\n verifiedAtMillis: now,\n bindingRevision: allocated.targetIdentifierRevision,\n }),\n );\n } else {\n yield* database\n .update(mapping.identifier.table)\n .set(\n mapping.identifier.encodeVerification({\n verifiedAtMillis: now,\n bindingRevision: allocated.targetIdentifierRevision,\n }),\n )\n .where(\n and(\n eq(i.namespace, input.target.namespace),\n eq(i.value, input.target.value),\n eq(i.subjectId, current.nativeSubjectId),\n eq(i.bindingRevision, current.targetIdentifier![mapping.identifier.bindingRevision]),\n ),\n );\n }\n if (current.targetCredential === undefined) {\n yield* database.insert(mapping.credential.table).values(\n mapping.credential.encodeVerifiedInsert({\n moduleId: input.moduleId,\n subjectId: current.nativeSubjectId,\n credentialId: targetCredentialId,\n identifier: input.target,\n credentialRevision: allocated.targetCredentialRevision,\n }),\n );\n yield* database.insert(mapping.authorityCredential.table).values(\n mapping.authorityCredential.encodeInsert({\n subjectId: current.nativeSubjectId,\n credentialId: targetCredentialId,\n revision: allocated.targetCredentialRevision,\n }),\n );\n } else {\n const oldRevision = current.targetCredential[mapping.credential.credentialRevision];\n\n yield* database\n .update(mapping.credential.table)\n .set(\n mapping.credential.encodeActivation({\n identifier: input.target,\n credentialRevision: allocated.targetCredentialRevision,\n }),\n )\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.credentialId, targetCredentialId),\n eq(c.subjectId, current.nativeSubjectId),\n eq(c.credentialRevision, oldRevision),\n ),\n );\n yield* database\n .update(mapping.authorityCredential.table)\n .set(mapping.authorityCredential.encodeActivation(allocated.targetCredentialRevision))\n .where(\n and(\n eq(a.subjectId, current.nativeSubjectId),\n eq(a.credentialId, targetCredentialId),\n eq(a.revision, oldRevision),\n ),\n );\n }\n yield* database\n .update(mapping.subject.table)\n .set(updateValues([[mapping.subject.securityRevision, allocated.nextSecurityRevision]]))\n .where(\n and(\n eq(s.id, current.nativeSubjectId),\n eq(s.securityRevision, input.captured.revision.securityRevision),\n ),\n );\n yield* database.insert(mapping.command.table).values(\n mapping.command.encodeInsert({\n moduleId: input.moduleId,\n commandId: input.commandId,\n action,\n bindingDigest: input.authorization.challenge.bindingDigest,\n retentionUntilMillis: now + mapping.commandRetentionMillis,\n }),\n );\n\n const sourceStillActive =\n action === \"verify-address\"\n ? []\n : yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.credentialId, current.source!.snapshot.credentialId),\n eq(c.subjectId, current.nativeSubjectId),\n ),\n ),\n false,\n );\n\n const target = (yield* emailLookupRows(mapping, input.moduleId, input.target))[0];\n\n const targetAuthority = yield* selectRows(\n database\n .select()\n .from(mapping.authorityCredential.table)\n .where(\n and(eq(a.subjectId, current.nativeSubjectId), eq(a.credentialId, targetCredentialId)),\n )\n .limit(1),\n false,\n );\n\n const command = yield* selectRows(\n database\n .select()\n .from(mapping.command.table)\n .where(\n and(\n eq(commandColumns(mapping).moduleId, input.moduleId),\n eq(commandColumns(mapping).commandId, input.commandId),\n eq(commandColumns(mapping).action, action),\n eq(commandColumns(mapping).bindingDigest, input.authorization.challenge.bindingDigest),\n eq(\n commandColumns(mapping).retentionUntil,\n mapping.encodeInstant(now + mapping.commandRetentionMillis),\n ),\n ),\n )\n .limit(1),\n false,\n );\n\n const targetVerifiedAt =\n target === undefined\n ? undefined\n : yield* mapping.decodeInstant(target.identifier[mapping.identifier.verifiedAt]);\n\n const sourceIdentifier =\n action === \"verify-address\"\n ? []\n : yield* identifierRow(mapping, current.source!.snapshot.identifier, false);\n\n const sourceAuthority =\n action === \"verify-address\"\n ? []\n : yield* selectRows(\n database\n .select()\n .from(mapping.authorityCredential.table)\n .where(\n and(\n eq(a.subjectId, current.nativeSubjectId),\n eq(a.credentialId, current.source!.snapshot.credentialId),\n ),\n )\n .limit(1),\n false,\n );\n\n return (\n target !== undefined &&\n mapping.subjectId.equals(target.subject[mapping.subject.id], current.nativeSubjectId) &&\n mapping.subject.isActiveStatus(target.subject[mapping.subject.status]) &&\n target.subject[mapping.subject.securityRevision] === allocated.nextSecurityRevision &&\n target.identifier[mapping.identifier.bindingRevision] ===\n allocated.targetIdentifierRevision &&\n targetVerifiedAt === now &&\n target.credential[mapping.credential.credentialRevision] ===\n allocated.targetCredentialRevision &&\n target.credential[mapping.credential.credentialId] === targetCredentialId &&\n mapping.subjectId.equals(\n target.credential[mapping.credential.subjectId],\n current.nativeSubjectId,\n ) &&\n mapping.identifier.isCurrent(target.identifier) &&\n mapping.credential.isActiveStatus(target.credential[mapping.credential.status]) &&\n targetAuthority.length === 1 &&\n targetAuthority[0]![mapping.authorityCredential.revision] ===\n allocated.targetCredentialRevision &&\n mapping.authorityCredential.isActiveStatus(\n targetAuthority[0]![mapping.authorityCredential.status],\n ) &&\n command.length === 1 &&\n (action === \"verify-address\" ||\n (sourceStillActive.length === 1 &&\n sourceStillActive[0]![mapping.credential.credentialRevision] ===\n allocated.sourceCredentialRevision &&\n !mapping.credential.isActiveStatus(sourceStillActive[0]![mapping.credential.status]) &&\n sourceIdentifier.length === 1 &&\n mapping.subjectId.equals(\n sourceIdentifier[0]![mapping.identifier.subjectId],\n current.nativeSubjectId,\n ) &&\n sourceIdentifier[0]![mapping.identifier.bindingRevision] ===\n allocated.sourceIdentifierRevision &&\n !mapping.identifier.isCurrent(sourceIdentifier[0]!) &&\n sourceAuthority.length === 1 &&\n sourceAuthority[0]![mapping.authorityCredential.revision] ===\n allocated.sourceCredentialRevision &&\n !mapping.authorityCredential.isActiveStatus(\n sourceAuthority[0]![mapping.authorityCredential.status],\n )))\n );\n });\n\n const probeProofCompletion = Effect.fn(\"Drizzle.probeProofCompletion\")(function* (\n configuration: EmailSqlConfiguration,\n input: ProofCompletionInput,\n ) {\n const database = yield* CurrentEmailSql;\n\n if (configuration.proof === undefined) return yield* Effect.fail(unavailable());\n const validProbe = { _tag: \"EmailProofCompletionValid\" } as const;\n\n const plan = {\n input,\n prepare: <A>(\n decision: ProofCompletionDecision,\n journal: CommitJournal,\n project: (decision: ProofCompletionDecision) => A,\n ) => journal.prepare(project(decision)),\n };\n\n const probe = coordinateCommit(\n () =>\n database.transaction((transaction) =>\n completeProofPlanIn(\n configuration.proof!.mapping,\n configuration.proof!.configuration,\n plan,\n Effect.fail(validProbe),\n () => false,\n ).pipe(\n Effect.provideService(CurrentProofSql, transaction as unknown as ProofSqlDatabase),\n ),\n ),\n { mode: configuration.mode },\n );\n\n return yield* probe.pipe(\n Effect.as(false),\n Effect.catchCause((cause) => {\n const reason = cause.reasons[0];\n\n return cause.reasons.length === 1 &&\n reason !== undefined &&\n Cause.isFailReason(reason) &&\n reason.error === validProbe\n ? Effect.succeed(true)\n : Effect.failCause(cause);\n }),\n );\n });\n\n const prepareRejected = Effect.fn(\"Drizzle.prepareRejected\")(function* <A>(\n configuration: EmailSqlConfiguration,\n prepare: (value: \"rejected\", journal: CommitJournal) => PreparedCommit<A>,\n ) {\n const database = yield* CurrentEmailSql;\n\n return yield* owned(\n database,\n configuration,\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n return yield* Effect.succeed(prepare(\"rejected\", journal));\n }),\n );\n });\n\n const makeSqlEmailAddressPersistence = Effect.fn(\"makeSqlEmailAddressPersistence\")(function* (\n database: EmailSqlDatabase,\n mapping: AddressMapping,\n configuration: EmailSqlConfiguration,\n ): Effect.fn.Return<EmailAddressPersistence[\"Service\"], never, LifecycleHooks> {\n const hooks = yield* LifecycleHooks;\n\n return EmailAddressPersistence.of({\n target: (input) =>\n (validAddressConstraints(mapping)\n ? safeRead(\n database,\n configuration,\n Effect.gen(function* () {\n const current = yield* currentAddress(mapping, input, configuration.locking);\n\n if (current === undefined) return yield* unavailable();\n\n return Object.freeze({\n revision: snapshotEmailRevision(current.revision),\n eligible: current.eligible,\n ...(current.targetIdentifierRevision === undefined\n ? {}\n : { targetIdentifierRevision: current.targetIdentifierRevision }),\n ...(current.source === undefined\n ? {}\n : { source: yield* snapshotEmailCredential(current.source.snapshot) }),\n });\n }),\n )\n : Effect.fail(unavailable())\n ).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n checkCompletion: (input) => {\n if (configuration.proof === undefined || input.binding._tag !== \"IdentifierChange\")\n return Effect.succeed(false).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n );\n const binding = input.binding;\n\n return safeRead(\n database,\n configuration,\n Effect.gen(function* () {\n const action: EmailAction | undefined =\n input.moduleId.endsWith(\"/verify-address\") &&\n input.purpose === \"email-address-verification\"\n ? \"verify-address\"\n : input.moduleId.endsWith(\"/change-address\") &&\n input.purpose === \"email-address-change\"\n ? \"change-address\"\n : undefined;\n\n if (action === undefined) return false;\n const moduleId = input.moduleId.slice(0, -`/${action}`.length);\n\n const current = yield* currentAddress(\n mapping,\n {\n moduleId,\n subjectId: binding.revision.subjectId,\n target: binding.identifier,\n },\n false,\n );\n\n return current !== undefined && sameEmailRevision(current.revision, binding.revision);\n }),\n )\n .pipe(\n Effect.flatMap((current) =>\n current ? probeProofCompletion(configuration, input) : Effect.succeed(false),\n ),\n )\n .pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n );\n },\n verifyWithProof: (uncaptured, prepare) =>\n mutateAddress(mapping, configuration, uncaptured, \"verify-address\", prepare).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n changeWithProof: (uncaptured, prepare) =>\n mutateAddress(mapping, configuration, uncaptured, \"change-address\", prepare).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n cleanup: (input, prepare) =>\n owned(\n database,\n configuration,\n Effect.gen(function* () {\n const transaction = yield* CurrentEmailSql;\n const journal = yield* CurrentCommitJournal;\n\n const c = commandColumns(mapping);\n const now = yield* nowMillis;\n\n const rows = yield* selectRows(\n transaction\n .select({ commandId: c.commandId })\n .from(mapping.command.table)\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n lte(c.retentionUntil, mapping.encodeInstant(now)),\n ),\n )\n .limit(input.limit + 1),\n configuration.locking,\n );\n\n const selected = rows.slice(0, input.limit);\n\n const receipt = prepare(\n { removed: selected.length, hasMore: rows.length > input.limit },\n journal,\n );\n\n if (selected.length > 0)\n yield* transaction.delete(mapping.command.table).where(\n and(\n eq(c.moduleId, input.moduleId),\n inArray(\n c.commandId,\n selected.map((row: any) => row.commandId),\n ),\n lte(c.retentionUntil, mapping.encodeInstant(now)),\n ),\n );\n\n return receipt;\n }),\n ).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n });\n });\n\n const mutateAddress = Effect.fn(\"Drizzle.mutateAddress\")(function* <A>(\n mapping: AddressMapping,\n configuration: EmailSqlConfiguration,\n uncaptured: EmailAddressMutation,\n action: EmailAction,\n prepare: (value: \"changed\" | \"rejected\", journal: CommitJournal) => PreparedCommit<A>,\n ) {\n const database = yield* CurrentEmailSql;\n\n if (!validAddressConstraints(mapping) || configuration.proof === undefined)\n return yield* unavailable();\n const input = yield* snapshotEmailMutation(uncaptured);\n\n const targetCredentialId = yield* allocate(\n configuration.mode,\n mapping.allocateCredentialId,\n mapping.allocateCredentialIdSync,\n );\n\n const targetIdentifierRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const targetCredentialRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const sourceIdentifierRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const sourceCredentialRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const confirmsExisting =\n action === \"verify-address\" && input.captured.targetIdentifierRevision !== undefined;\n\n const nextRevision = confirmsExisting\n ? input.captured.revision.securityRevision\n : yield* nextSecurityRevision(\n mapping,\n configuration.mode,\n input.captured.revision.securityRevision,\n );\n\n if (\n (!confirmsExisting && nextRevision === input.captured.revision.securityRevision) ||\n [\n targetIdentifierRevision,\n targetCredentialRevision,\n sourceIdentifierRevision,\n sourceCredentialRevision,\n ].some((value) => input.captured.revision.credentials.some((item) => item.revision === value))\n )\n return yield* unavailable();\n\n const run = owned(\n database,\n configuration,\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const current = yield* validateEmailAuthority(mapping, configuration, input, action);\n\n if (current === undefined) return prepare(\"rejected\", journal);\n if (\n (yield* commandExists(mapping, input.moduleId, input.commandId, configuration.locking))\n .length > 0\n )\n return prepare(\"rejected\", journal);\n let receipt: PreparedCommit<A> | undefined;\n\n yield* completeProofPlanIn(\n configuration.proof!.mapping,\n configuration.proof!.configuration,\n input.completion,\n Effect.gen(function* () {\n // The proof helper may wait on continuation/series locks. Read the\n // commit clock and reassess both policies only after those locks.\n const currentRequirement = yield* mapping.subject.decodeActionRequirement(\n current.subject,\n action,\n );\n\n const original = yield* assessAuthentication(\n input.authorization.evidence,\n input.authorization.requirement,\n ).pipe(Effect.mapError(unavailable));\n\n const configured = yield* assessAuthentication(\n input.authorization.evidence,\n currentRequirement,\n ).pipe(Effect.mapError(unavailable));\n\n if (!original.satisfied || !configured.satisfied) return false;\n const now = yield* nowMillis;\n\n return yield* applyMutation(\n mapping,\n input,\n action,\n current,\n {\n targetCredentialId,\n targetIdentifierRevision,\n targetCredentialRevision,\n sourceIdentifierRevision,\n sourceCredentialRevision,\n nextSecurityRevision: nextRevision,\n },\n now,\n );\n }),\n (decision) => {\n receipt = prepare(decision === \"completed\" ? \"changed\" : \"rejected\", journal);\n\n return decision;\n },\n );\n\n return receipt ?? prepare(\"rejected\", journal);\n }),\n );\n\n return yield* run.pipe(\n Effect.catchCause((cause) =>\n (cause.reasons.every(Cause.isFailReason) &&\n isMappedConstraintConflict(mapping.isCommandConflict, cause)) ||\n (cause.reasons.every(Cause.isFailReason) &&\n isMappedConstraintConflict(mapping.isIdentifierConflict, cause)) ||\n (cause.reasons.every(Cause.isFailReason) &&\n isMappedConstraintConflict(mapping.isCredentialConflict, cause))\n ? prepareRejected(configuration, prepare)\n : Effect.failCause(cause),\n ),\n );\n });\n\n return {\n validEmailSignInConstraints,\n emailLookupQuery,\n decodeEmailSnapshot,\n makeSqlEmailSignInTargets,\n currentAddress,\n sameEmailRevision,\n snapshotEmailMutation,\n validateEmailAuthority,\n makeSqlEmailAddressPersistence,\n };\n};\n"],"mappings":";;;;;;;;;;AAkFA,IAAa,kBAAb,cAAqC,QAAQ,QAA2C,CAAC,CACvF,6BACF,CAAC,CAAC,CAAC;AA4BH,MAAa,mBAIX,YACA,WACG;CAGH,MAAM,EAAE,KAAK,IAAI,SAAS,KAAK,QAAQ,iBAAiB;CACxD,MAAM,EAAE,wBAAwB;CAChC,MAAM,oBAAoB,iBAAiB,KAAK,CAAC,CAAC;CAElD,MAAM,oBACJ,WAEA,yBACE,SACC,UACC,OAAO,GAAG,gBAAgB,CAAC,CAAC,KAAK,KACjC,OAAO,GAAG,gBAAgB,CAAC,CAAC,KAAK,KACjC,OAAO,GAAG,sBAAsB,CAAC,CAAC,KAAK,CAC3C,CAAC,CAAC,KAAK,OAAO,YAAY,UAAU,OAAO,UAAU,MAAM,IAAI,aAAa,YAAY,CAAC,CAAC,CAAC,CAAC;CAE9F,MAAM,YAAY,OAAO,IAAI,SAAS,KAAK,SAA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,OAAO;GACT,CACF;GAEA,OAAO,WAAW,QAAQ,YAAY,OAAO;EAC/C,CAAC,CAGa,CAAC,CAAC,KAChB,OAAO,YAAY,UAChB,MAAM,QAAQ,MAAM,MAAM,YAAY,KACrC,2BAA2B,QAAQ,mBAAmB,KAAK,KAC5D,MAAM,QAAQ,MAAM,MAAM,YAAY,KACrC,2BAA2B,QAAQ,sBAAsB,KAAK,KAC/D,MAAM,QAAQ,MAAM,MAAM,YAAY,KACrC,2BAA2B,QAAQ,sBAAsB,KAAK,IAC5D,gBAAgB,eAAe,OAAO,IACtC,OAAO,UAAU,KAAK,CAC5B,CACF;CACF,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"email-kernel.mjs","names":[],"sources":["../../src/internal/email-kernel.ts"],"sourcesContent":["import {\n EmailAddressPersistence,\n type EmailAddressMutation,\n type EmailAction,\n type EmailCredentialSnapshot,\n EmailSignInTargets,\n EmailUnavailable,\n snapshotEmailCredential,\n snapshotEmailRequirement,\n snapshotEmailRevision,\n} from \"@yielded/auth/Email\";\nimport {\n coordinateCommit,\n CurrentCommitJournal,\n hasCommitScope,\n type CommitJournal,\n type PreparedCommit,\n LifecycleHooks,\n HookConfigurationError,\n} from \"@yielded/auth/Hooks\";\nimport type { LoginIdentifier } from \"@yielded/auth/Identity\";\nimport { reportPersistenceFailure } from \"@yielded/auth/Persistence\";\nimport {\n ProofUnavailable,\n type ProofCompletionDecision,\n type ProofCompletionInput,\n} from \"@yielded/auth/Proofs\";\nimport {\n assessAuthentication,\n snapshotAuthenticationEvidence,\n type AuthenticationRevision,\n type SecurityRevision,\n} from \"@yielded/auth/Sessions\";\nimport { Cause, Context, DateTime, Effect, Option, Schema } from \"effect\";\nimport type * as SqlError from \"effect/sql/SqlError\";\n\nimport { isMappedConstraintConflict, PersistenceMappingError } from \"./mapping-error\";\nimport {\n type AnyEmailAddressMapping,\n type AnyEmailSignInMapping,\n requiredEmailAddressConstraints,\n requiredEmailSignInConstraints,\n} from \"./models/email-model\";\nimport {\n CurrentProofSql,\n type makeProofKernel,\n type ProofSqlConfiguration,\n type ProofSqlDatabase,\n} from \"./proof-kernel\";\n/* oxlint-disable no-explicit-any -- the shared dialect kernel erases consumer Drizzle table types internally. */\nimport type { QueryFailure } from \"./query-operations\";\nimport type { QueryOperations, SqlFragment, SqlColumn } from \"./query-operations\";\n\ntype AdapterFailure = QueryFailure | PersistenceMappingError | SqlError.SqlError;\ntype SignInMapping = AnyEmailSignInMapping;\n\nexport interface EmailSqlQuery<A = ReadonlyArray<any>> extends Effect.Effect<A, AdapterFailure> {\n readonly getSQL: () => ReturnType<QueryOperations[\"sql\"]>;\n readonly from: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly where: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly limit: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly orderBy: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly for: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly set: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly values: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly returning: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly innerJoin: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly onConflictDoNothing: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly onDuplicateKeyUpdate: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n readonly $returningId: (...args: ReadonlyArray<any>) => EmailSqlQuery<A>;\n}\n\nexport interface EmailSqlDatabase {\n readonly select: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly insert: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly update: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly delete: (...args: ReadonlyArray<any>) => EmailSqlQuery;\n readonly transaction: <A, E, R>(\n body: (transaction: EmailSqlDatabase) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | SqlError.SqlError, R>;\n}\n\nexport class CurrentEmailSql extends Context.Service<CurrentEmailSql, EmailSqlDatabase>()(\n \"effect-auth/CurrentEmailSql\",\n) {}\n\nexport interface EmailSqlConfiguration {\n readonly mode: \"interactive\" | \"synchronous\";\n readonly locking: boolean;\n readonly standaloneGuard: Effect.Effect<void, EmailUnavailable>;\n readonly coordinated?: boolean;\n readonly proof?: {\n readonly mapping: any;\n readonly configuration: ProofSqlConfiguration;\n };\n}\n\nexport interface CurrentAddress {\n readonly nativeSubjectId: unknown;\n readonly subject: any;\n readonly revision: AuthenticationRevision;\n readonly source?: {\n readonly credential: any;\n readonly identifier: any;\n readonly snapshot: EmailCredentialSnapshot;\n };\n readonly targetIdentifier?: any;\n readonly targetCredential?: any;\n readonly targetIdentifierRevision?: SecurityRevision;\n readonly eligible: boolean;\n}\n\nexport const makeEmailKernel = <\n Fragment extends SqlFragment = SqlFragment,\n Column extends SqlColumn = SqlColumn,\n>(\n operations: QueryOperations<Fragment, Column>,\n proofs: Pick<ReturnType<typeof makeProofKernel>, \"completeProofPlanIn\">,\n) => {\n type AddressMapping = AnyEmailAddressMapping<Fragment>;\n\n const { and, eq, inArray, lte, column, updateValues } = operations;\n const { completeProofPlanIn } = proofs;\n const unavailable = () => EmailUnavailable.make({});\n\n const translateFailure = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, EmailUnavailable, R> =>\n reportPersistenceFailure(\n effect,\n (error) =>\n Schema.is(EmailUnavailable)(error) ||\n Schema.is(ProofUnavailable)(error) ||\n Schema.is(HookConfigurationError)(error),\n ).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));\n\n const nowMillis = Effect.map(DateTime.now, DateTime.toEpochMillis);\n\n const selectRows = (query: EmailSqlQuery, locking: boolean) =>\n locking && typeof query.for === \"function\" ? query.for(\"update\") : query;\n\n const sameIdentifier = (left: LoginIdentifier, right: LoginIdentifier) =>\n left.namespace === right.namespace && left.value === right.value;\n\n const validEmailSignInConstraints = (mapping: SignInMapping) =>\n Object.entries(requiredEmailSignInConstraints).every(\n ([key, value]) =>\n mapping.constraints[key as keyof typeof requiredEmailSignInConstraints] === value,\n );\n\n const validAddressConstraints = (mapping: AddressMapping) =>\n Object.entries(requiredEmailAddressConstraints).every(\n ([key, value]) =>\n mapping.constraints[key as keyof typeof requiredEmailAddressConstraints] === value,\n );\n\n const subjectColumns = (mapping: SignInMapping) => ({\n id: column(mapping.subject.table, mapping.subject.id),\n status: column(mapping.subject.table, mapping.subject.status),\n securityRevision: column(mapping.subject.table, mapping.subject.securityRevision),\n });\n\n const identifierColumns = (mapping: SignInMapping) => ({\n namespace: column(mapping.identifier.table, mapping.identifier.namespace),\n value: column(mapping.identifier.table, mapping.identifier.value),\n subjectId: column(mapping.identifier.table, mapping.identifier.subjectId),\n verifiedAt: column(mapping.identifier.table, mapping.identifier.verifiedAt),\n bindingRevision: column(mapping.identifier.table, mapping.identifier.bindingRevision),\n });\n\n const credentialColumns = (mapping: SignInMapping) => ({\n moduleId: column(mapping.credential.table, mapping.credential.moduleId),\n subjectId: column(mapping.credential.table, mapping.credential.subjectId),\n credentialId: column(mapping.credential.table, mapping.credential.credentialId),\n identifierNamespace: column(mapping.credential.table, mapping.credential.identifierNamespace),\n identifierValue: column(mapping.credential.table, mapping.credential.identifierValue),\n credentialRevision: column(mapping.credential.table, mapping.credential.credentialRevision),\n status: column(mapping.credential.table, mapping.credential.status),\n });\n\n const authorityColumns = (mapping: AddressMapping) => ({\n subjectId: column(mapping.authorityCredential.table, mapping.authorityCredential.subjectId),\n credentialId: column(\n mapping.authorityCredential.table,\n mapping.authorityCredential.credentialId,\n ),\n revision: column(mapping.authorityCredential.table, mapping.authorityCredential.revision),\n status: column(mapping.authorityCredential.table, mapping.authorityCredential.status),\n });\n\n const commandColumns = (mapping: AddressMapping) => ({\n moduleId: column(mapping.command.table, mapping.command.moduleId),\n commandId: column(mapping.command.table, mapping.command.commandId),\n action: column(mapping.command.table, mapping.command.action),\n bindingDigest: column(mapping.command.table, mapping.command.bindingDigest),\n retentionUntil: column(mapping.command.table, mapping.command.retentionUntil),\n });\n\n const allocate = <A>(\n mode: EmailSqlConfiguration[\"mode\"],\n asynchronous: Effect.Effect<A, PersistenceMappingError> | undefined,\n synchronous: (() => A) | undefined,\n ) => {\n if (mode === \"synchronous\")\n return synchronous === undefined\n ? Effect.fail(unavailable())\n : Effect.try({\n try: synchronous,\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n if (asynchronous !== undefined) return asynchronous;\n\n return synchronous === undefined\n ? Effect.fail(unavailable())\n : Effect.try({\n try: synchronous,\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n };\n\n const nextSecurityRevision = (\n mapping: AddressMapping,\n mode: EmailSqlConfiguration[\"mode\"],\n current: SecurityRevision,\n ) => {\n if (mode === \"synchronous\")\n return mapping.subject.nextSecurityRevisionSync === undefined\n ? Effect.fail(unavailable())\n : Effect.try({\n try: () => mapping.subject.nextSecurityRevisionSync!(current),\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n if (mapping.subject.nextSecurityRevision !== undefined)\n return mapping.subject.nextSecurityRevision(current);\n if (mapping.subject.nextSecurityRevisionSync !== undefined)\n return Effect.try({\n try: () => mapping.subject.nextSecurityRevisionSync!(current),\n catch: (cause) => new PersistenceMappingError({ operation: \"mapping\", cause }),\n });\n\n return Effect.fail(unavailable());\n };\n\n const safeRead = <A, E, R>(\n database: EmailSqlDatabase,\n configuration: EmailSqlConfiguration,\n body: Effect.Effect<A, E, R>,\n ) =>\n Effect.gen(function* () {\n if (configuration.coordinated !== true) {\n if (yield* hasCommitScope) return yield* unavailable();\n yield* configuration.standaloneGuard;\n }\n\n return yield* database.transaction((transaction) =>\n body.pipe(\n Effect.provideService(CurrentEmailSql, transaction),\n Effect.provideService(CurrentProofSql, transaction as unknown as ProofSqlDatabase),\n ),\n );\n });\n\n const owned = <A, E, R>(\n database: EmailSqlDatabase,\n configuration: EmailSqlConfiguration,\n body: Effect.Effect<A, E, R>,\n ) => {\n const run = coordinateCommit(\n () =>\n database.transaction((transaction) =>\n body.pipe(\n Effect.provideService(CurrentEmailSql, transaction),\n Effect.provideService(CurrentProofSql, transaction as unknown as ProofSqlDatabase),\n ),\n ),\n { mode: configuration.mode },\n ).pipe(Effect.map((result) => result.value));\n\n return configuration.coordinated !== true\n ? Effect.gen(function* () {\n if (yield* hasCommitScope) return yield* unavailable();\n yield* configuration.standaloneGuard;\n\n return yield* run;\n })\n : run;\n };\n\n const emailLookupQuery = (\n mapping: SignInMapping,\n moduleId: string,\n identifier: LoginIdentifier,\n ) => {\n const subject = subjectColumns(mapping),\n binding = identifierColumns(mapping),\n credential = credentialColumns(mapping);\n\n return {\n fields: {\n subject: mapping.subject.table,\n identifier: mapping.identifier.table,\n credential: mapping.credential.table,\n },\n from: mapping.identifier.table,\n subjectTable: mapping.subject.table,\n subjectJoin: eq(subject.id, binding.subjectId),\n credentialTable: mapping.credential.table,\n credentialJoin: and(\n eq(credential.moduleId, moduleId),\n eq(credential.subjectId, binding.subjectId),\n eq(credential.identifierNamespace, binding.namespace),\n eq(credential.identifierValue, binding.value),\n ),\n predicate: and(\n eq(binding.namespace, identifier.namespace),\n eq(binding.value, identifier.value),\n ),\n limit: 1,\n };\n };\n\n const emailLookupRows = Effect.fn(\"Drizzle.emailLookupRows\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n identifier: LoginIdentifier,\n ) {\n const database = yield* CurrentEmailSql;\n const query = emailLookupQuery(mapping, moduleId, identifier);\n\n return yield* database\n .select(query.fields)\n .from(query.from)\n .innerJoin(query.subjectTable, query.subjectJoin)\n .innerJoin(query.credentialTable, query.credentialJoin)\n .where(query.predicate)\n .limit(query.limit);\n });\n\n const decodeEmailSnapshot = Effect.fn(\"DrizzleEmail.decodeSnapshot\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n requested: LoginIdentifier,\n row: any,\n ) {\n if (\n !mapping.subject.isActiveStatus(row.subject[mapping.subject.status]) ||\n !mapping.identifier.isCurrent(row.identifier) ||\n !mapping.credential.isActiveStatus(row.credential[mapping.credential.status])\n )\n return undefined;\n\n const snapshot = yield* mapping.credential\n .decode({\n moduleId,\n subject: row.subject,\n identifier: row.identifier,\n credential: row.credential,\n })\n .pipe(Effect.flatMap(snapshotEmailCredential));\n\n const subjectId = yield* mapping.subjectId.toSubject(row.subject[mapping.subject.id]);\n\n const verifiedAtMillis = yield* mapping.decodeInstant(\n row.identifier[mapping.identifier.verifiedAt],\n );\n\n if (\n snapshot.moduleId !== moduleId ||\n !sameIdentifier(snapshot.identifier, requested) ||\n snapshot.revision.subjectId !== subjectId ||\n snapshot.revision.securityRevision !== row.subject[mapping.subject.securityRevision] ||\n snapshot.identifierRevision !== row.identifier[mapping.identifier.bindingRevision] ||\n snapshot.verifiedAtMillis !== verifiedAtMillis ||\n snapshot.credentialId !== row.credential[mapping.credential.credentialId] ||\n snapshot.credentialRevision !== row.credential[mapping.credential.credentialRevision]\n )\n return undefined;\n\n return snapshot;\n });\n\n const makeSqlEmailSignInTargets = Effect.fn(\"makeSqlEmailSignInTargets\")(function (\n database: EmailSqlDatabase,\n mapping: SignInMapping,\n configuration: EmailSqlConfiguration,\n ): Effect.Effect<EmailSignInTargets[\"Service\"]> {\n return Effect.succeed(\n EmailSignInTargets.of({\n lookup: (input) =>\n (validEmailSignInConstraints(mapping)\n ? safeRead(\n database,\n configuration,\n Effect.gen(function* () {\n const row = (yield* emailLookupRows(\n mapping,\n input.moduleId,\n input.identifier,\n ))[0];\n\n if (row === undefined) return Option.none();\n\n const snapshot = yield* decodeEmailSnapshot(\n mapping,\n input.moduleId,\n input.identifier,\n row,\n );\n\n return snapshot === undefined ? Option.none() : Option.some(snapshot);\n }),\n )\n : Effect.fail(unavailable())\n ).pipe(Effect.provideService(CurrentEmailSql, database), translateFailure),\n }),\n );\n });\n\n const readSubject = Effect.fn(\"DrizzleEmail.readSubject\")(function* (\n mapping: AddressMapping,\n subjectId: string,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const nativeSubjectId = yield* mapping.subjectId.toNative(subjectId as any);\n const s = subjectColumns(mapping);\n\n const subject = (yield* selectRows(\n database.select().from(mapping.subject.table).where(eq(s.id, nativeSubjectId)).limit(1),\n locking,\n ))[0];\n\n return { nativeSubjectId, subject };\n });\n\n const identifierRow = Effect.fn(\"Drizzle.identifierRow\")(function* (\n mapping: SignInMapping,\n identifier: LoginIdentifier,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const i = identifierColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.identifier.table)\n .where(and(eq(i.namespace, identifier.namespace), eq(i.value, identifier.value)))\n .limit(1),\n locking,\n );\n });\n\n const credentialById = Effect.fn(\"Drizzle.credentialById\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n credentialId: string,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const c = credentialColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(and(eq(c.moduleId, moduleId), eq(c.credentialId, credentialId)))\n .limit(1),\n locking,\n );\n });\n\n const credentialByIdentifier = Effect.fn(\"Drizzle.credentialByIdentifier\")(function* (\n mapping: SignInMapping,\n moduleId: string,\n identifier: LoginIdentifier,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const c = credentialColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(\n and(\n eq(c.moduleId, moduleId),\n eq(c.identifierNamespace, identifier.namespace),\n eq(c.identifierValue, identifier.value),\n ),\n )\n .limit(1),\n locking,\n );\n });\n\n const currentAddress = Effect.fn(\"DrizzleEmail.currentAddress\")(function* (\n mapping: AddressMapping,\n input: {\n readonly moduleId: string;\n readonly subjectId: string;\n readonly target: LoginIdentifier;\n readonly sourceCredentialId?: string;\n },\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const locked = yield* readSubject(mapping, input.subjectId, locking);\n\n if (\n locked.subject === undefined ||\n !mapping.subject.isActiveStatus(locked.subject[mapping.subject.status])\n )\n return undefined;\n\n const discoveredSource =\n input.sourceCredentialId === undefined\n ? undefined\n : (yield* credentialById(mapping, input.moduleId, input.sourceCredentialId, false))[0];\n\n const sourceIdentifier: LoginIdentifier | undefined =\n discoveredSource === undefined\n ? undefined\n : {\n namespace: discoveredSource[mapping.credential.identifierNamespace],\n value: discoveredSource[mapping.credential.identifierValue],\n };\n\n const identifiers = [\n input.target,\n ...(sourceIdentifier === undefined ? [] : [sourceIdentifier]),\n ]\n .filter(\n (value, index, values) =>\n values.findIndex((candidate) => sameIdentifier(candidate, value)) === index,\n )\n .sort((left, right) =>\n `${left.namespace}\\u0000${left.value}`.localeCompare(\n `${right.namespace}\\u0000${right.value}`,\n ),\n );\n\n const lockedIdentifiers = new Map<string, any>();\n\n for (const identifier of identifiers) {\n const row = (yield* identifierRow(mapping, identifier, locking))[0];\n\n if (row !== undefined)\n lockedIdentifiers.set(`${identifier.namespace}\\u0000${identifier.value}`, row);\n }\n\n const sourceCredential =\n input.sourceCredentialId === undefined\n ? undefined\n : (yield* credentialById(mapping, input.moduleId, input.sourceCredentialId, locking))[0];\n\n const targetCredential = (yield* credentialByIdentifier(\n mapping,\n input.moduleId,\n input.target,\n locking,\n ))[0];\n\n const a = authorityColumns(mapping);\n\n const authority = yield* selectRows(\n database\n .select()\n .from(mapping.authorityCredential.table)\n .where(eq(a.subjectId, locked.nativeSubjectId))\n .orderBy(a.credentialId),\n locking,\n );\n\n const activeAuthority = authority.filter((row: any) =>\n mapping.authorityCredential.isActiveStatus(row[mapping.authorityCredential.status]),\n );\n\n const subjectId = yield* mapping.subjectId.toSubject(locked.nativeSubjectId);\n\n const revision: AuthenticationRevision = Object.freeze({\n subjectId,\n securityRevision: locked.subject[mapping.subject.securityRevision],\n credentials: Object.freeze(\n activeAuthority.map((row: any) =>\n Object.freeze({\n credentialId: row[mapping.authorityCredential.credentialId],\n revision: row[mapping.authorityCredential.revision],\n }),\n ),\n ),\n });\n\n const targetIdentifier = lockedIdentifiers.get(\n `${input.target.namespace}\\u0000${input.target.value}`,\n );\n\n const targetOwned =\n targetIdentifier !== undefined &&\n mapping.subjectId.equals(\n targetIdentifier[mapping.identifier.subjectId],\n locked.nativeSubjectId,\n );\n\n const targetMutable =\n targetOwned &&\n mapping.identifier.isMutableTarget(targetIdentifier) &&\n (targetCredential === undefined ||\n (!mapping.credential.isActiveStatus(targetCredential[mapping.credential.status]) &&\n mapping.subjectId.equals(\n targetCredential[mapping.credential.subjectId],\n locked.nativeSubjectId,\n )));\n\n let source: CurrentAddress[\"source\"];\n\n if (input.sourceCredentialId !== undefined) {\n if (\n sourceCredential === undefined ||\n sourceIdentifier === undefined ||\n !mapping.subjectId.equals(\n sourceCredential[mapping.credential.subjectId],\n locked.nativeSubjectId,\n ) ||\n !mapping.credential.isActiveStatus(sourceCredential[mapping.credential.status])\n )\n return undefined;\n\n const sourceIdentifierRow = lockedIdentifiers.get(\n `${sourceIdentifier.namespace}\\u0000${sourceIdentifier.value}`,\n );\n\n if (\n sourceIdentifierRow === undefined ||\n !mapping.identifier.isCurrent(sourceIdentifierRow) ||\n !mapping.subjectId.equals(\n sourceIdentifierRow[mapping.identifier.subjectId],\n locked.nativeSubjectId,\n )\n )\n return undefined;\n\n const snapshot = yield* mapping.credential\n .decode({\n moduleId: input.moduleId,\n subject: locked.subject,\n identifier: sourceIdentifierRow,\n credential: sourceCredential,\n })\n .pipe(Effect.flatMap(snapshotEmailCredential));\n\n source = { credential: sourceCredential, identifier: sourceIdentifierRow, snapshot };\n }\n let eligible = targetIdentifier === undefined ? targetCredential === undefined : targetMutable;\n\n if (input.sourceCredentialId !== undefined && source === undefined) eligible = false;\n if (source !== undefined && sameIdentifier(source.snapshot.identifier, input.target))\n eligible = false;\n if (mapping.addressCardinality === \"single\" && input.sourceCredentialId === undefined) {\n const c = credentialColumns(mapping);\n\n const rows = yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(and(eq(c.moduleId, input.moduleId), eq(c.subjectId, locked.nativeSubjectId))),\n locking,\n );\n\n if (\n rows.some((row: any) => mapping.credential.isActiveStatus(row[mapping.credential.status]))\n )\n eligible = false;\n }\n\n return {\n nativeSubjectId: locked.nativeSubjectId,\n subject: locked.subject,\n revision,\n ...(source === undefined ? {} : { source }),\n ...(targetIdentifier === undefined ? {} : { targetIdentifier }),\n ...(targetCredential === undefined ? {} : { targetCredential }),\n ...(targetMutable\n ? { targetIdentifierRevision: targetIdentifier[mapping.identifier.bindingRevision] }\n : {}),\n eligible,\n };\n });\n\n const sameEmailRevision = (left: AuthenticationRevision, right: AuthenticationRevision) => {\n if (\n left.subjectId !== right.subjectId ||\n left.securityRevision !== right.securityRevision ||\n left.credentials.length !== right.credentials.length\n )\n return false;\n\n const expected = [...left.credentials].sort((a, b) =>\n a.credentialId.localeCompare(b.credentialId),\n );\n\n const actual = [...right.credentials].sort((a, b) =>\n a.credentialId.localeCompare(b.credentialId),\n );\n\n return expected.every(\n (item, index) =>\n item.credentialId === actual[index]!.credentialId &&\n item.revision === actual[index]!.revision,\n );\n };\n\n const actionModule = (moduleId: string, action: EmailAction) =>\n `${moduleId}/${action === \"verify-address\" ? \"verify-address\" : \"change-address\"}`;\n\n const actionPurpose = (action: EmailAction) =>\n action === \"verify-address\" ? \"email-address-verification\" : \"email-address-change\";\n\n const completionMatches = (input: EmailAddressMutation, action: EmailAction) => {\n const completion = input.completion.input;\n const binding = completion.binding;\n\n return (\n completion.moduleId === actionModule(input.moduleId, action) &&\n completion.purpose === actionPurpose(action) &&\n binding._tag === \"IdentifierChange\" &&\n sameIdentifier(binding.identifier, input.target) &&\n sameEmailRevision(binding.revision, input.captured.revision)\n );\n };\n\n const snapshotEmailMutation = Effect.fn(\"DrizzleEmail.snapshotMutation\")(function* (\n input: EmailAddressMutation,\n ) {\n const evidence = yield* snapshotAuthenticationEvidence(input.authorization.evidence).pipe(\n Effect.mapError(unavailable),\n );\n\n const requirement = yield* snapshotEmailRequirement(input.authorization.requirement);\n\n const source =\n input.captured.source === undefined\n ? undefined\n : yield* snapshotEmailCredential(input.captured.source);\n\n return Object.freeze({\n ...input,\n target: Object.freeze({ ...input.target }),\n ...(input.invalidation === undefined\n ? {}\n : { invalidation: Object.freeze({ ...input.invalidation }) }),\n captured: Object.freeze({\n eligible: input.captured.eligible,\n revision: snapshotEmailRevision(input.captured.revision),\n ...(input.captured.targetIdentifierRevision === undefined\n ? {}\n : { targetIdentifierRevision: input.captured.targetIdentifierRevision }),\n ...(source === undefined ? {} : { source }),\n }),\n authorization: Object.freeze({\n challenge: Object.freeze({\n ...input.authorization.challenge,\n target: Object.freeze({ ...input.authorization.challenge.target }),\n revision: snapshotEmailRevision(input.authorization.challenge.revision),\n }),\n evidence,\n requirement,\n }),\n });\n });\n\n const validateEmailAuthority = Effect.fn(\"DrizzleEmail.validateAuthority\")(function* (\n mapping: AddressMapping,\n configuration: EmailSqlConfiguration,\n input: EmailAddressMutation,\n action: EmailAction,\n ) {\n const confirmsExisting =\n action === \"verify-address\" && input.captured.targetIdentifierRevision !== undefined;\n\n if (\n !input.captured.eligible ||\n !completionMatches(input, action) ||\n input.authorization.challenge.moduleId !== input.moduleId ||\n input.authorization.challenge.action !== action ||\n input.authorization.challenge.commandId !== input.commandId ||\n !sameIdentifier(input.authorization.challenge.target, input.target) ||\n input.authorization.challenge.sourceCredentialId !== input.captured.source?.credentialId ||\n !sameEmailRevision(input.authorization.challenge.revision, input.captured.revision) ||\n input.authorization.challenge.targetIdentifierRevision !==\n input.captured.targetIdentifierRevision ||\n (input.authorization.evidence.flowId as string) !== (input.commandId as string) ||\n input.authorization.evidence.bindingDigest !== input.authorization.challenge.bindingDigest ||\n !sameEmailRevision(input.authorization.evidence.revision, input.captured.revision) ||\n (action === \"verify-address\" && input.captured.source !== undefined) ||\n (action === \"change-address\" && input.captured.source === undefined) ||\n confirmsExisting !== (input.invalidation === undefined) ||\n (input.invalidation?.existingSessions === \"immediate\" &&\n mapping.sessionInvalidation !== \"same-authority-immediate\")\n )\n return undefined;\n\n const current = yield* currentAddress(\n mapping,\n {\n moduleId: input.moduleId,\n subjectId: input.captured.revision.subjectId,\n target: input.target,\n ...(input.captured.source === undefined\n ? {}\n : { sourceCredentialId: input.captured.source.credentialId }),\n },\n configuration.locking,\n );\n\n if (\n current === undefined ||\n !current.eligible ||\n !sameEmailRevision(current.revision, input.captured.revision) ||\n current.targetIdentifierRevision !== input.captured.targetIdentifierRevision ||\n (input.captured.source !== undefined &&\n (current.source === undefined ||\n current.source.snapshot.identifierRevision !== input.captured.source.identifierRevision ||\n current.source.snapshot.credentialRevision !== input.captured.source.credentialRevision ||\n !sameIdentifier(current.source.snapshot.identifier, input.captured.source.identifier)))\n )\n return undefined;\n\n const currentRequirement = yield* mapping.subject.decodeActionRequirement(\n current.subject,\n action,\n );\n\n const original = yield* assessAuthentication(\n input.authorization.evidence,\n input.authorization.requirement,\n ).pipe(Effect.mapError(unavailable));\n\n const configured = yield* assessAuthentication(\n input.authorization.evidence,\n currentRequirement,\n ).pipe(Effect.mapError(unavailable));\n\n return original.satisfied && configured.satisfied ? current : undefined;\n });\n\n const commandExists = Effect.fn(\"Drizzle.commandExists\")(function* (\n mapping: AddressMapping,\n moduleId: string,\n commandId: string,\n locking: boolean,\n ) {\n const database = yield* CurrentEmailSql;\n\n const c = commandColumns(mapping);\n\n return yield* selectRows(\n database\n .select()\n .from(mapping.command.table)\n .where(and(eq(c.moduleId, moduleId), eq(c.commandId, commandId)))\n .limit(1),\n locking,\n );\n });\n\n const applyMutation = Effect.fn(\"DrizzleEmail.applyMutation\")(function* (\n mapping: AddressMapping,\n input: EmailAddressMutation,\n action: EmailAction,\n current: CurrentAddress,\n allocated: {\n readonly targetCredentialId: string;\n readonly targetIdentifierRevision: SecurityRevision;\n readonly targetCredentialRevision: SecurityRevision;\n readonly sourceIdentifierRevision: SecurityRevision;\n readonly sourceCredentialRevision: SecurityRevision;\n readonly nextSecurityRevision: SecurityRevision;\n },\n now: number,\n ) {\n const database = yield* CurrentEmailSql;\n\n const i = identifierColumns(mapping);\n const c = credentialColumns(mapping);\n const a = authorityColumns(mapping);\n const s = subjectColumns(mapping);\n\n const targetCredentialId =\n current.targetCredential?.[mapping.credential.credentialId] ?? allocated.targetCredentialId;\n\n if (action === \"change-address\") {\n const source = current.source!;\n\n yield* database\n .update(mapping.identifier.table)\n .set(\n mapping.identifier.encodeRetirement({\n source: source.snapshot.identifier,\n bindingRevision: allocated.sourceIdentifierRevision,\n }),\n )\n .where(\n and(\n eq(i.namespace, source.snapshot.identifier.namespace),\n eq(i.value, source.snapshot.identifier.value),\n eq(i.subjectId, current.nativeSubjectId),\n eq(i.bindingRevision, source.snapshot.identifierRevision),\n ),\n );\n yield* database\n .update(mapping.credential.table)\n .set(\n mapping.credential.encodeRetirement({\n source: source.snapshot.identifier,\n credentialRevision: allocated.sourceCredentialRevision,\n }),\n )\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.credentialId, source.snapshot.credentialId),\n eq(c.subjectId, current.nativeSubjectId),\n eq(c.credentialRevision, source.snapshot.credentialRevision),\n ),\n );\n yield* database\n .update(mapping.authorityCredential.table)\n .set(mapping.authorityCredential.encodeRetirement(allocated.sourceCredentialRevision))\n .where(\n and(\n eq(a.subjectId, current.nativeSubjectId),\n eq(a.credentialId, source.snapshot.credentialId),\n eq(a.revision, source.snapshot.credentialRevision),\n ),\n );\n }\n if (current.targetIdentifier === undefined) {\n yield* database.insert(mapping.identifier.table).values(\n mapping.identifier.encodeVerifiedInsert({\n identifier: input.target,\n subjectId: current.nativeSubjectId,\n verifiedAtMillis: now,\n bindingRevision: allocated.targetIdentifierRevision,\n }),\n );\n } else {\n yield* database\n .update(mapping.identifier.table)\n .set(\n mapping.identifier.encodeVerification({\n verifiedAtMillis: now,\n bindingRevision: allocated.targetIdentifierRevision,\n }),\n )\n .where(\n and(\n eq(i.namespace, input.target.namespace),\n eq(i.value, input.target.value),\n eq(i.subjectId, current.nativeSubjectId),\n eq(i.bindingRevision, current.targetIdentifier![mapping.identifier.bindingRevision]),\n ),\n );\n }\n if (current.targetCredential === undefined) {\n yield* database.insert(mapping.credential.table).values(\n mapping.credential.encodeVerifiedInsert({\n moduleId: input.moduleId,\n subjectId: current.nativeSubjectId,\n credentialId: targetCredentialId,\n identifier: input.target,\n credentialRevision: allocated.targetCredentialRevision,\n }),\n );\n yield* database.insert(mapping.authorityCredential.table).values(\n mapping.authorityCredential.encodeInsert({\n subjectId: current.nativeSubjectId,\n credentialId: targetCredentialId,\n revision: allocated.targetCredentialRevision,\n }),\n );\n } else {\n const oldRevision = current.targetCredential[mapping.credential.credentialRevision];\n\n yield* database\n .update(mapping.credential.table)\n .set(\n mapping.credential.encodeActivation({\n identifier: input.target,\n credentialRevision: allocated.targetCredentialRevision,\n }),\n )\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.credentialId, targetCredentialId),\n eq(c.subjectId, current.nativeSubjectId),\n eq(c.credentialRevision, oldRevision),\n ),\n );\n yield* database\n .update(mapping.authorityCredential.table)\n .set(mapping.authorityCredential.encodeActivation(allocated.targetCredentialRevision))\n .where(\n and(\n eq(a.subjectId, current.nativeSubjectId),\n eq(a.credentialId, targetCredentialId),\n eq(a.revision, oldRevision),\n ),\n );\n }\n yield* database\n .update(mapping.subject.table)\n .set(updateValues([[mapping.subject.securityRevision, allocated.nextSecurityRevision]]))\n .where(\n and(\n eq(s.id, current.nativeSubjectId),\n eq(s.securityRevision, input.captured.revision.securityRevision),\n ),\n );\n yield* database.insert(mapping.command.table).values(\n mapping.command.encodeInsert({\n moduleId: input.moduleId,\n commandId: input.commandId,\n action,\n bindingDigest: input.authorization.challenge.bindingDigest,\n retentionUntilMillis: now + mapping.commandRetentionMillis,\n }),\n );\n\n const sourceStillActive =\n action === \"verify-address\"\n ? []\n : yield* selectRows(\n database\n .select()\n .from(mapping.credential.table)\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n eq(c.credentialId, current.source!.snapshot.credentialId),\n eq(c.subjectId, current.nativeSubjectId),\n ),\n ),\n false,\n );\n\n const target = (yield* emailLookupRows(mapping, input.moduleId, input.target))[0];\n\n const targetAuthority = yield* selectRows(\n database\n .select()\n .from(mapping.authorityCredential.table)\n .where(\n and(eq(a.subjectId, current.nativeSubjectId), eq(a.credentialId, targetCredentialId)),\n )\n .limit(1),\n false,\n );\n\n const command = yield* selectRows(\n database\n .select()\n .from(mapping.command.table)\n .where(\n and(\n eq(commandColumns(mapping).moduleId, input.moduleId),\n eq(commandColumns(mapping).commandId, input.commandId),\n eq(commandColumns(mapping).action, action),\n eq(commandColumns(mapping).bindingDigest, input.authorization.challenge.bindingDigest),\n eq(\n commandColumns(mapping).retentionUntil,\n mapping.encodeInstant(now + mapping.commandRetentionMillis),\n ),\n ),\n )\n .limit(1),\n false,\n );\n\n const targetVerifiedAt =\n target === undefined\n ? undefined\n : yield* mapping.decodeInstant(target.identifier[mapping.identifier.verifiedAt]);\n\n const sourceIdentifier =\n action === \"verify-address\"\n ? []\n : yield* identifierRow(mapping, current.source!.snapshot.identifier, false);\n\n const sourceAuthority =\n action === \"verify-address\"\n ? []\n : yield* selectRows(\n database\n .select()\n .from(mapping.authorityCredential.table)\n .where(\n and(\n eq(a.subjectId, current.nativeSubjectId),\n eq(a.credentialId, current.source!.snapshot.credentialId),\n ),\n )\n .limit(1),\n false,\n );\n\n return (\n target !== undefined &&\n mapping.subjectId.equals(target.subject[mapping.subject.id], current.nativeSubjectId) &&\n mapping.subject.isActiveStatus(target.subject[mapping.subject.status]) &&\n target.subject[mapping.subject.securityRevision] === allocated.nextSecurityRevision &&\n target.identifier[mapping.identifier.bindingRevision] ===\n allocated.targetIdentifierRevision &&\n targetVerifiedAt === now &&\n target.credential[mapping.credential.credentialRevision] ===\n allocated.targetCredentialRevision &&\n target.credential[mapping.credential.credentialId] === targetCredentialId &&\n mapping.subjectId.equals(\n target.credential[mapping.credential.subjectId],\n current.nativeSubjectId,\n ) &&\n mapping.identifier.isCurrent(target.identifier) &&\n mapping.credential.isActiveStatus(target.credential[mapping.credential.status]) &&\n targetAuthority.length === 1 &&\n targetAuthority[0]![mapping.authorityCredential.revision] ===\n allocated.targetCredentialRevision &&\n mapping.authorityCredential.isActiveStatus(\n targetAuthority[0]![mapping.authorityCredential.status],\n ) &&\n command.length === 1 &&\n (action === \"verify-address\" ||\n (sourceStillActive.length === 1 &&\n sourceStillActive[0]![mapping.credential.credentialRevision] ===\n allocated.sourceCredentialRevision &&\n !mapping.credential.isActiveStatus(sourceStillActive[0]![mapping.credential.status]) &&\n sourceIdentifier.length === 1 &&\n mapping.subjectId.equals(\n sourceIdentifier[0]![mapping.identifier.subjectId],\n current.nativeSubjectId,\n ) &&\n sourceIdentifier[0]![mapping.identifier.bindingRevision] ===\n allocated.sourceIdentifierRevision &&\n !mapping.identifier.isCurrent(sourceIdentifier[0]!) &&\n sourceAuthority.length === 1 &&\n sourceAuthority[0]![mapping.authorityCredential.revision] ===\n allocated.sourceCredentialRevision &&\n !mapping.authorityCredential.isActiveStatus(\n sourceAuthority[0]![mapping.authorityCredential.status],\n )))\n );\n });\n\n const probeProofCompletion = Effect.fn(\"Drizzle.probeProofCompletion\")(function* (\n configuration: EmailSqlConfiguration,\n input: ProofCompletionInput,\n ) {\n const database = yield* CurrentEmailSql;\n\n if (configuration.proof === undefined) return yield* Effect.fail(unavailable());\n const validProbe = { _tag: \"EmailProofCompletionValid\" } as const;\n\n const plan = {\n input,\n prepare: <A>(\n decision: ProofCompletionDecision,\n journal: CommitJournal,\n project: (decision: ProofCompletionDecision) => A,\n ) => journal.prepare(project(decision)),\n };\n\n const probe = coordinateCommit(\n () =>\n database.transaction((transaction) =>\n completeProofPlanIn(\n configuration.proof!.mapping,\n configuration.proof!.configuration,\n plan,\n Effect.fail(validProbe),\n () => false,\n ).pipe(\n Effect.provideService(CurrentProofSql, transaction as unknown as ProofSqlDatabase),\n ),\n ),\n { mode: configuration.mode },\n );\n\n return yield* probe.pipe(\n Effect.as(false),\n Effect.catchCause((cause) => {\n const reason = cause.reasons[0];\n\n return cause.reasons.length === 1 &&\n reason !== undefined &&\n Cause.isFailReason(reason) &&\n reason.error === validProbe\n ? Effect.succeed(true)\n : Effect.failCause(cause);\n }),\n );\n });\n\n const prepareRejected = Effect.fn(\"Drizzle.prepareRejected\")(function* <A>(\n configuration: EmailSqlConfiguration,\n prepare: (value: \"rejected\", journal: CommitJournal) => PreparedCommit<A>,\n ) {\n const database = yield* CurrentEmailSql;\n\n return yield* owned(\n database,\n configuration,\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n return yield* Effect.succeed(prepare(\"rejected\", journal));\n }),\n );\n });\n\n const makeSqlEmailAddressPersistence = Effect.fn(\"makeSqlEmailAddressPersistence\")(function* (\n database: EmailSqlDatabase,\n mapping: AddressMapping,\n configuration: EmailSqlConfiguration,\n ): Effect.fn.Return<EmailAddressPersistence[\"Service\"], never, LifecycleHooks> {\n const hooks = yield* LifecycleHooks;\n\n return EmailAddressPersistence.of({\n target: (input) =>\n (validAddressConstraints(mapping)\n ? safeRead(\n database,\n configuration,\n Effect.gen(function* () {\n const current = yield* currentAddress(mapping, input, configuration.locking);\n\n if (current === undefined) return yield* unavailable();\n\n return Object.freeze({\n revision: snapshotEmailRevision(current.revision),\n eligible: current.eligible,\n ...(current.targetIdentifierRevision === undefined\n ? {}\n : { targetIdentifierRevision: current.targetIdentifierRevision }),\n ...(current.source === undefined\n ? {}\n : { source: yield* snapshotEmailCredential(current.source.snapshot) }),\n });\n }),\n )\n : Effect.fail(unavailable())\n ).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n checkCompletion: (input) => {\n if (configuration.proof === undefined || input.binding._tag !== \"IdentifierChange\")\n return Effect.succeed(false).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n );\n const binding = input.binding;\n\n return safeRead(\n database,\n configuration,\n Effect.gen(function* () {\n const action: EmailAction | undefined =\n input.moduleId.endsWith(\"/verify-address\") &&\n input.purpose === \"email-address-verification\"\n ? \"verify-address\"\n : input.moduleId.endsWith(\"/change-address\") &&\n input.purpose === \"email-address-change\"\n ? \"change-address\"\n : undefined;\n\n if (action === undefined) return false;\n const moduleId = input.moduleId.slice(0, -`/${action}`.length);\n\n const current = yield* currentAddress(\n mapping,\n {\n moduleId,\n subjectId: binding.revision.subjectId,\n target: binding.identifier,\n },\n false,\n );\n\n return current !== undefined && sameEmailRevision(current.revision, binding.revision);\n }),\n )\n .pipe(\n Effect.flatMap((current) =>\n current ? probeProofCompletion(configuration, input) : Effect.succeed(false),\n ),\n )\n .pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n );\n },\n verifyWithProof: (uncaptured, prepare) =>\n mutateAddress(mapping, configuration, uncaptured, \"verify-address\", prepare).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n changeWithProof: (uncaptured, prepare) =>\n mutateAddress(mapping, configuration, uncaptured, \"change-address\", prepare).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n cleanup: (input, prepare) =>\n owned(\n database,\n configuration,\n Effect.gen(function* () {\n const transaction = yield* CurrentEmailSql;\n const journal = yield* CurrentCommitJournal;\n\n const c = commandColumns(mapping);\n const now = yield* nowMillis;\n\n const rows = yield* selectRows(\n transaction\n .select({ commandId: c.commandId })\n .from(mapping.command.table)\n .where(\n and(\n eq(c.moduleId, input.moduleId),\n lte(c.retentionUntil, mapping.encodeInstant(now)),\n ),\n )\n .limit(input.limit + 1),\n configuration.locking,\n );\n\n const selected = rows.slice(0, input.limit);\n\n const receipt = prepare(\n { removed: selected.length, hasMore: rows.length > input.limit },\n journal,\n );\n\n if (selected.length > 0)\n yield* transaction.delete(mapping.command.table).where(\n and(\n eq(c.moduleId, input.moduleId),\n inArray(\n c.commandId,\n selected.map((row: any) => row.commandId),\n ),\n lte(c.retentionUntil, mapping.encodeInstant(now)),\n ),\n );\n\n return receipt;\n }),\n ).pipe(\n Effect.provideService(CurrentEmailSql, database),\n Effect.provideService(LifecycleHooks, hooks),\n translateFailure,\n ),\n });\n });\n\n const mutateAddress = Effect.fn(\"Drizzle.mutateAddress\")(function* <A>(\n mapping: AddressMapping,\n configuration: EmailSqlConfiguration,\n uncaptured: EmailAddressMutation,\n action: EmailAction,\n prepare: (value: \"changed\" | \"rejected\", journal: CommitJournal) => PreparedCommit<A>,\n ) {\n const database = yield* CurrentEmailSql;\n\n if (!validAddressConstraints(mapping) || configuration.proof === undefined)\n return yield* unavailable();\n const input = yield* snapshotEmailMutation(uncaptured);\n\n const targetCredentialId = yield* allocate(\n configuration.mode,\n mapping.allocateCredentialId,\n mapping.allocateCredentialIdSync,\n );\n\n const targetIdentifierRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const targetCredentialRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const sourceIdentifierRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const sourceCredentialRevision = yield* allocate(\n configuration.mode,\n mapping.allocateRevision,\n mapping.allocateRevisionSync,\n );\n\n const confirmsExisting =\n action === \"verify-address\" && input.captured.targetIdentifierRevision !== undefined;\n\n const nextRevision = confirmsExisting\n ? input.captured.revision.securityRevision\n : yield* nextSecurityRevision(\n mapping,\n configuration.mode,\n input.captured.revision.securityRevision,\n );\n\n if (\n (!confirmsExisting && nextRevision === input.captured.revision.securityRevision) ||\n [\n targetIdentifierRevision,\n targetCredentialRevision,\n sourceIdentifierRevision,\n sourceCredentialRevision,\n ].some((value) => input.captured.revision.credentials.some((item) => item.revision === value))\n )\n return yield* unavailable();\n\n const run = owned(\n database,\n configuration,\n Effect.gen(function* () {\n const journal = yield* CurrentCommitJournal;\n\n const current = yield* validateEmailAuthority(mapping, configuration, input, action);\n\n if (current === undefined) return prepare(\"rejected\", journal);\n if (\n (yield* commandExists(mapping, input.moduleId, input.commandId, configuration.locking))\n .length > 0\n )\n return prepare(\"rejected\", journal);\n let receipt: PreparedCommit<A> | undefined;\n\n yield* completeProofPlanIn(\n configuration.proof!.mapping,\n configuration.proof!.configuration,\n input.completion,\n Effect.gen(function* () {\n // The proof helper may wait on continuation/series locks. Read the\n // commit clock and reassess both policies only after those locks.\n const currentRequirement = yield* mapping.subject.decodeActionRequirement(\n current.subject,\n action,\n );\n\n const original = yield* assessAuthentication(\n input.authorization.evidence,\n input.authorization.requirement,\n ).pipe(Effect.mapError(unavailable));\n\n const configured = yield* assessAuthentication(\n input.authorization.evidence,\n currentRequirement,\n ).pipe(Effect.mapError(unavailable));\n\n if (!original.satisfied || !configured.satisfied) return false;\n const now = yield* nowMillis;\n\n return yield* applyMutation(\n mapping,\n input,\n action,\n current,\n {\n targetCredentialId,\n targetIdentifierRevision,\n targetCredentialRevision,\n sourceIdentifierRevision,\n sourceCredentialRevision,\n nextSecurityRevision: nextRevision,\n },\n now,\n );\n }),\n (decision) => {\n receipt = prepare(decision === \"completed\" ? \"changed\" : \"rejected\", journal);\n\n return decision;\n },\n );\n\n return receipt ?? prepare(\"rejected\", journal);\n }),\n );\n\n return yield* run.pipe(\n Effect.catchCause((cause) =>\n (cause.reasons.every(Cause.isFailReason) &&\n isMappedConstraintConflict(mapping.isCommandConflict, cause)) ||\n (cause.reasons.every(Cause.isFailReason) &&\n isMappedConstraintConflict(mapping.isIdentifierConflict, cause)) ||\n (cause.reasons.every(Cause.isFailReason) &&\n isMappedConstraintConflict(mapping.isCredentialConflict, cause))\n ? prepareRejected(configuration, prepare)\n : Effect.failCause(cause),\n ),\n );\n });\n\n return {\n validEmailSignInConstraints,\n emailLookupQuery,\n decodeEmailSnapshot,\n makeSqlEmailSignInTargets,\n currentAddress,\n sameEmailRevision,\n snapshotEmailMutation,\n validateEmailAuthority,\n makeSqlEmailAddressPersistence,\n };\n};\n"],"mappings":";;;;;;;;;;AAkFA,IAAa,kBAAb,cAAqC,QAAQ,QAA2C,CAAC,CACvF,6BACF,CAAC,CAAC,CAAC;AA4BH,MAAa,mBAIX,YACA,WACG;CAGH,MAAM,EAAE,KAAK,IAAI,SAAS,KAAK,QAAQ,iBAAiB;CACxD,MAAM,EAAE,wBAAwB;CAChC,MAAM,oBAAoB,iBAAiB,KAAK,CAAC,CAAC;CAElD,MAAM,oBACJ,WAEA,yBACE,SACC,UACC,OAAO,GAAG,gBAAgB,CAAC,CAAC,KAAK,KACjC,OAAO,GAAG,gBAAgB,CAAC,CAAC,KAAK,KACjC,OAAO,GAAG,sBAAsB,CAAC,CAAC,KAAK,CAC3C,CAAC,CAAC,KAAK,OAAO,YAAY,UAAU,OAAO,UAAU,MAAM,IAAI,aAAa,YAAY,CAAC,CAAC,CAAC,CAAC;CAE9F,MAAM,YAAY,OAAO,IAAI,SAAS,KAAK,SAAS,aAAa;CAEjE,MAAM,cAAc,OAAsB,YACxC,WAAW,OAAO,MAAM,QAAQ,aAAa,MAAM,IAAI,QAAQ,IAAI;CAErE,MAAM,kBAAkB,MAAuB,UAC7C,KAAK,cAAc,MAAM,aAAa,KAAK,UAAU,MAAM;CAE7D,MAAM,+BAA+B,YACnC,OAAO,QAAQ,8BAA8B,CAAC,CAAC,OAC5C,CAAC,KAAK,WACL,QAAQ,YAAY,SAAwD,KAChF;CAEF,MAAM,2BAA2B,YAC/B,OAAO,QAAQ,+BAA+B,CAAC,CAAC,OAC7C,CAAC,KAAK,WACL,QAAQ,YAAY,SAAyD,KACjF;CAEF,MAAM,kBAAkB,aAA4B;EAClD,IAAI,OAAO,QAAQ,QAAQ,OAA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F"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Layer } from "effect";
|
|
2
|
-
import { SqlClient } from "effect/
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
3
|
import { Persistence, Unavailable } from "@yielded/auth/OAuthServer";
|
|
4
4
|
//#region src/internal/oauth-server.d.ts
|
|
5
5
|
export declare const OAuthServerPersistence: {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { requireStandalone } from "./standalone.mjs";
|
|
2
2
|
import { Effect, Layer, Schema } from "effect";
|
|
3
|
-
import { SqlClient } from "effect/
|
|
3
|
+
import { SqlClient } from "effect/sql";
|
|
4
4
|
import { Persistence, Record, Unavailable } from "@yielded/auth/OAuthServer";
|
|
5
5
|
//#region src/internal/oauth-server.ts
|
|
6
6
|
const codec = Schema.fromJsonString(Record);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-server.mjs","names":[],"sources":["../../src/internal/oauth-server.ts"],"sourcesContent":["import { Persistence, Record, Unavailable } from \"@yielded/auth/OAuthServer\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { SqlClient } from \"effect/
|
|
1
|
+
{"version":3,"file":"oauth-server.mjs","names":[],"sources":["../../src/internal/oauth-server.ts"],"sourcesContent":["import { Persistence, Record, Unavailable } from \"@yielded/auth/OAuthServer\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { SqlClient } from \"effect/sql\";\n\nimport { requireStandalone } from \"./standalone\";\n\nconst codec = Schema.fromJsonString(Record);\n\nconst Row = Schema.Struct({\n payload: Schema.String,\n version: Schema.String,\n revoked: Schema.Literals([0, 1]),\n});\n\n/** SQLite (including D1) and PostgreSQL. Apply once through application migrations.\n * Expired records may be deleted when expires_at_millis <= the current time.\n * Revocation has its own monotonic column so it cannot lose a race with rotation.\n */\nconst migration = `CREATE TABLE yielded_oauth_server (\n namespace TEXT NOT NULL,\n grant_id TEXT NOT NULL,\n version TEXT NOT NULL,\n revoked INTEGER NOT NULL DEFAULT 0,\n expires_at_millis BIGINT NOT NULL,\n payload TEXT NOT NULL,\n PRIMARY KEY (namespace, grant_id)\n)`;\n\nconst layer = Layer.effect(\n Persistence,\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n if (!sql.onDialectOrElse({ sqlite: () => true, pg: () => true, orElse: () => false }))\n return yield* Unavailable.make({});\n const standalone = requireStandalone(() => Unavailable.make({}), sql);\n\n const failure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n effect.pipe(Effect.mapError(() => Unavailable.make({})));\n\n return Persistence.of({\n get: Effect.fn(\"OAuthServerPersistence.get\")(function* (namespace, id) {\n yield* standalone;\n\n const rows =\n yield* sql`SELECT payload, version, revoked FROM yielded_oauth_server WHERE namespace = ${namespace} AND grant_id = ${id}`;\n\n if (rows.length === 0) return undefined;\n if (rows.length !== 1) return yield* Unavailable.make({});\n const row = yield* Schema.decodeUnknownEffect(Row)(rows[0]);\n const record = yield* Schema.decodeEffect(codec)(row.payload);\n\n if (record.version !== row.version) return yield* Unavailable.make({});\n\n return row.revoked === 1 ? { ...record, status: \"Revoked\" as const } : record;\n }, failure),\n insert: Effect.fn(\"OAuthServerPersistence.insert\")(function* (namespace, id, record) {\n yield* standalone;\n const payload = yield* Schema.encodeEffect(codec)(record);\n\n const rows =\n yield* sql`INSERT INTO yielded_oauth_server (namespace, grant_id, version, revoked, expires_at_millis, payload) VALUES (${namespace}, ${id}, ${record.version}, ${record.status === \"Revoked\" ? 1 : 0}, ${record.expiresAtMillis}, ${payload}) ON CONFLICT (namespace, grant_id) DO NOTHING RETURNING version`;\n\n return rows.length === 1;\n }, failure),\n compareAndSet: Effect.fn(\"OAuthServerPersistence.compareAndSet\")(function* (\n namespace,\n id,\n version,\n record,\n ) {\n yield* standalone;\n if (version === record.version) return yield* Unavailable.make({});\n const payload = yield* Schema.encodeEffect(codec)(record);\n\n const rows =\n yield* sql`UPDATE yielded_oauth_server SET version = ${record.version}, revoked = ${record.status === \"Revoked\" ? 1 : 0}, expires_at_millis = ${record.expiresAtMillis}, payload = ${payload} WHERE namespace = ${namespace} AND grant_id = ${id} AND version = ${version} AND revoked = 0 RETURNING version`;\n\n return rows.length === 1;\n }, failure),\n revoke: Effect.fn(\"OAuthServerPersistence.revoke\")(function* (namespace, id) {\n yield* standalone;\n yield* sql`UPDATE yielded_oauth_server SET revoked = 1 WHERE namespace = ${namespace} AND grant_id = ${id}`;\n }, failure),\n });\n }),\n);\n\nexport const OAuthServerPersistence = { migration, layer };\n"],"mappings":";;;;;AAMA,MAAM,QAAQ,OAAO,eAAe,MAAM;AAE1C,MAAM,MAAM,OAAO,OAAO;CACxB,SAAS,OAAO;CAChB,SAAS,OAAO;CAChB,SAAS,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC;AACjC,CAAC;AA4ED,MAAa,yBAAyB;CAAE;;;;;;;;;CAAW,OA5DrC,MAAM,OAClB,aACA,OAAO,IAAI,aAAa;EACtB,MAAM,MAAM,OAAO,UAAU;EAE7B,IAAI,CAAC,IAAI,gBAAgB;GAAE,cAAc;GAAM,UAAU;GAAM,cAAc;EAAM,CAAC,GAClF,OAAO,OAAO,YAAY,KAAK,CAAC,CAAC;EACnC,MAAM,aAAa,wBAAwB,YAAY,KAAK,CAAC,CAAC,GAAG,GAAG;EAEpE,MAAM,WAAoB,WACxB,OAAO,KAAK,OAAO,eAAe,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC;EAEzD,OAAO,YAAY,GAAG;GACpB,KAAK,OAAO,GAAG,4BAA4B,CAAC,CAAC,WAAW,WAAW,IAAI;IACrE,OAAO;IAEP,MAAM,OACJ,OAAO,GAAG,gFAAgF,UAAU,kBAAkB;IAExH,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;IAC9B,IAAI,KAAK,WAAW,GAAG,OAAO,OAAO,YAAY,KAAK,CAAC,CAAC;IACxD,MAAM,MAAM,OAAO,OAAO,oBAAoB,GAAG,CAAC,CAAC,KAAK,EAAE;IAC1D,MAAM,SAAS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PasskeyRegistrationCeremonyConstraints } from "../models/passkey-registration-ceremony-model.mjs";
|
|
3
|
-
import { Context, Effect,
|
|
3
|
+
import { Context, Effect, Schema } from "effect";
|
|
4
4
|
import { PasskeyCeremony, PasskeyConfigurationError, PasskeyCredential, PasskeyMethodPolicy, PasskeyModuleId, PasskeyProfile, PasskeyRevision, PasskeyUnavailable, snapshotPasskeySync } from "@yielded/auth/Passkey";
|
|
5
5
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
6
6
|
import { randomBytes } from "@noble/hashes/utils.js";
|
|
7
|
+
import { Base64Url } from "effect/encoding";
|
|
7
8
|
//#region src/internal/passkey/state.ts
|
|
8
9
|
var CurrentPasskeyTransaction = class extends Context.Service()("effect-auth/drizzle/CurrentPasskeyTransaction") {};
|
|
9
10
|
const makePasskeyStateKernel = (operations, transactions) => {
|
|
@@ -14,7 +15,7 @@ const makePasskeyStateKernel = (operations, transactions) => {
|
|
|
14
15
|
if (!value) throw unavailable();
|
|
15
16
|
};
|
|
16
17
|
const { col, equal, copiedRow, matchesNativeRow } = makeTransactionRows(unavailable);
|
|
17
|
-
const nonce = () =>
|
|
18
|
+
const nonce = () => Base64Url.encode(randomBytes(32));
|
|
18
19
|
const encoder = new TextEncoder();
|
|
19
20
|
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
20
21
|
/** RP tuples and admission scopes have no collation-dependent string identity. */
|