domainkit 0.12.2 → 0.14.0
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 +4 -1
- package/dist/DomainKit.mjs +3 -2
- package/dist/DomainKit.mjs.map +1 -1
- package/dist/Server.mjs +47 -22
- package/dist/Server.mjs.map +1 -1
- package/dist/Storage.mjs +16 -1
- package/dist/Storage.mjs.map +1 -1
- package/dist/Transport.mjs +13 -6
- package/dist/Transport.mjs.map +1 -1
- package/dist/Verify.mjs +61 -8
- package/dist/Verify.mjs.map +1 -1
- package/dist/internal/conformance/storage.mjs +30 -0
- package/dist/internal/conformance/storage.mjs.map +1 -1
- package/dist/internal/storage-memory.mjs +16 -1
- package/dist/internal/storage-memory.mjs.map +1 -1
- package/dist/package.mjs +1 -1
- package/dist/types/DomainKit.d.ts +3 -2
- package/dist/types/Server.d.ts +448 -1
- package/dist/types/Storage.d.ts +24 -0
- package/dist/types/Transport.d.ts +2 -0
- package/dist/types/Verify.d.ts +62 -0
- package/package.json +1 -1
package/dist/Storage.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Storage.mjs","names":["Plan.PlanId","Plan.Kind","Plan.Model","Approval.Model","Receipt.Model","Receipt.ReceiptId","Plan.OperationId","DnsRecord.Model","Errors.isDomainKitError","Errors.DomainKitError","Reason.StorageFailed","Principal.Service","Errors.fail","Reason.Busy"],"sources":["../src/Storage.ts"],"sourcesContent":["/**\n * Everything DomainKit persists, behind one service the host installs once. Every method requires\n * `Principal` and is scoped by it. `@domainkit/capsuledb` ships the Postgres implementation;\n * `domainkit/testing` ships the memory one; both pass `Testing.conformance.storage`.\n *\n * Storage never sees plaintext credentials: `Connect` seals secrets through `Custody` before\n * writing a `Credential` row and opens them after reading one.\n *\n * Grouped by noun so the 25-odd methods stay navigable. Implementations must satisfy the\n * invariants documented per group; the conformance suite checks them.\n */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\n\nimport * as Approval from \"./Approval.ts\";\nimport * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport { makeMemory } from \"./internal/storage-memory.ts\";\nimport * as Plan from \"./Plan.ts\";\nimport * as Principal from \"./Principal.ts\";\nimport * as Receipt from \"./Receipt.ts\";\n\nexport type Fx<A> = Effect.Effect<A, Errors.DomainKitError, Principal.Service>;\n\n// ---------------------------------------------------------------------------------------------\n// Rows\n// ---------------------------------------------------------------------------------------------\n\nexport const Capability = Schema.Literals([\"dns:read\", \"dns:write\"]);\nexport type Capability = typeof Capability.Type;\n\nexport const AuthMethod = Schema.Literals([\"token\", \"oauth\", \"integration\"]);\nexport type AuthMethod = typeof AuthMethod.Type;\n\n/** Sealed provider credential plus the metadata needed without unsealing it. */\nexport class Credential extends Schema.Class<Credential>(\"@domainkit/Storage/Credential\")({\n ciphertext: Schema.String,\n expiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n rotatedAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** One provider authorization (an OAuth grant or a token) owned by a principal. */\nexport class Authorization extends Schema.Class<Authorization>(\"@domainkit/Storage/Authorization\")({\n id: Schema.String,\n ownerId: Schema.String,\n provider: Schema.String,\n method: AuthMethod,\n capabilities: Schema.Array(Capability),\n /** Provider-specific account context (account id, team id, ...) decoded by the provider's `context` schema. */\n context: Schema.Unknown,\n revocation: Schema.Literals([\"active\", \"pending\", \"revoked\"]),\n createdBy: Schema.String,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** A connection is the principal-facing handle over an authorization; one authorization, many domains. */\nexport class Connection extends Schema.Class<Connection>(\"@domainkit/Storage/Connection\")({\n id: Schema.String,\n ownerId: Schema.String,\n authorizationId: Schema.String,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport class Attachment extends Schema.Class<Attachment>(\"@domainkit/Storage/Attachment\")({\n id: Schema.String,\n ownerId: Schema.String,\n connectionId: Schema.String,\n domain: Schema.String,\n zone: Schema.String,\n /** The target's label as the provider gave it at attach time, so a UI names the account without a provider call. */\n label: Schema.String,\n /** Provider zone identity (zone id, account id) decoded by the provider's `context` schema. */\n target: Schema.Unknown,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** Interactive-flow state between `Connect.start` and `Connect.complete`. */\nexport class Continuation extends Schema.Class<Continuation>(\"@domainkit/Storage/Continuation\")({\n id: Schema.String,\n ownerId: Schema.String,\n actorId: Schema.String,\n provider: Schema.String,\n payload: Schema.Unknown,\n returnTo: Schema.NullOr(Schema.String),\n expiresAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport const AttemptStatus = Schema.Literals([\n \"planned\",\n \"approved\",\n \"applying\",\n \"complete\",\n \"partial\",\n \"failed\",\n \"expired\",\n \"rejected\",\n]);\nexport type AttemptStatus = typeof AttemptStatus.Type;\n\n/** Who declined the plan, why, and when. Terminal: the domain needs a new plan. */\nexport const Rejection = Schema.Struct({\n actorId: Schema.String,\n reason: Schema.NullOr(Schema.String),\n at: Schema.DateTimeUtcFromString,\n});\nexport type Rejection = typeof Rejection.Type;\n\n/** One durable plan -> approval -> receipt lifecycle. */\nexport class Attempt extends Schema.Class<Attempt>(\"@domainkit/Storage/Attempt\")({\n id: Plan.PlanId,\n ownerId: Schema.String,\n attachmentId: Schema.String,\n kind: Plan.Kind,\n status: AttemptStatus,\n plan: Plan.Model,\n approval: Schema.NullOr(Approval.Model),\n receipt: Schema.NullOr(Receipt.Model),\n rejection: Schema.NullOr(Rejection),\n /** Cleanup attempts point at the provisioning receipt they undo. */\n sourceReceiptId: Schema.NullOr(Receipt.ReceiptId),\n leaseExpiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n /** Why the last apply stopped before any write; cleared on the next claim. */\n failure: Schema.NullOr(Schema.String),\n updatedAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport const RequirementStatus = Schema.Literals([\"satisfied\", \"missing\", \"mismatch\", \"unknown\"]);\nexport type RequirementStatus = typeof RequirementStatus.Type;\n\nexport const Overall = Schema.Literals([\"ready\", \"pending\", \"failed\"]);\nexport type Overall = typeof Overall.Type;\n\n/**\n * Latest observed readiness for one domain, written by `Verify.observe`. Keyed by domain so\n * observe-only hosts (no attachment, public DNS alone) get the same row; `attachmentId` links the\n * attachment when one exists.\n */\nexport class Readiness extends Schema.Class<Readiness>(\"@domainkit/Storage/Readiness\")({\n domain: Schema.String,\n attachmentId: Schema.NullOr(Schema.String),\n ownerId: Schema.String,\n overall: Overall,\n requirements: Schema.Array(\n Schema.Struct({\n operationId: Schema.NullOr(Plan.OperationId),\n record: DnsRecord.Model,\n status: RequirementStatus,\n /** Encoded `Verify.Evidence` values. */\n evidence: Schema.Array(Schema.Unknown),\n }),\n ),\n /** Encoded `Verify.HostEvidence` values, keyed by `source` on merge. */\n host: Schema.Array(Schema.Unknown),\n /** When the current pending streak began; drives the backoff ladder. */\n pendingSince: Schema.NullOr(Schema.DateTimeUtcFromString),\n checkedAt: Schema.DateTimeUtcFromString,\n nextCheckAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n}) {}\n\n// ---------------------------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------------------------\n\nexport interface Interface {\n readonly authorizations: {\n /**\n * Insert, or CAS-replace when `expectedId` is set: the row must exist under this owner with an\n * active revocation state, else `NotFound` / `Busy`.\n */\n readonly upsert: (input: {\n readonly authorization: Authorization;\n readonly credential: Credential;\n readonly expectedId?: string;\n }) => Fx<Authorization>;\n readonly get: (id: string) => Fx<Authorization>;\n readonly credential: (id: string) => Fx<Credential>;\n readonly rotate: (id: string, credential: Credential) => Fx<void>;\n readonly promoteCapabilities: (id: string, capabilities: ReadonlyArray<Capability>) => Fx<void>;\n /**\n * Two-phase: mark `pending`, run `revoke` outside any transaction, then delete. A failed\n * `revoke` leaves the row pending; `recoverRevocations` finishes it later.\n */\n readonly revoke: <E, R>(\n id: string,\n revoke: Effect.Effect<void, E, R>,\n ) => Effect.Effect<void, Errors.DomainKitError | E, Principal.Service | R>;\n readonly recoverRevocations: <E, R>(\n revoke: (authorization: Authorization) => Effect.Effect<void, E, R>,\n ) => Effect.Effect<number, Errors.DomainKitError | E, Principal.Service | R>;\n };\n readonly connections: {\n readonly create: (authorizationId: string) => Fx<Connection>;\n readonly get: (id: string) => Fx<Connection>;\n readonly list: (filter?: { readonly provider?: string }) => Fx<ReadonlyArray<Connection>>;\n /** Fails `InvalidInput` while attachments still reference the connection. */\n readonly remove: (id: string) => Fx<void>;\n };\n readonly attachments: {\n /** One attachment per (owner, domain); a duplicate fails `InvalidInput`. */\n readonly create: (input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string;\n readonly label: string;\n readonly target: unknown;\n }) => Fx<Attachment>;\n readonly get: (id: string) => Fx<Attachment>;\n readonly byDomain: (domain: string) => Fx<Option.Option<Attachment>>;\n readonly list: (connectionId: string) => Fx<ReadonlyArray<Attachment>>;\n readonly remove: (id: string) => Fx<void>;\n };\n readonly continuations: {\n readonly put: (continuation: Continuation) => Fx<void>;\n /** Read without spending; a late read fails `Expired`. */\n readonly get: (id: string) => Fx<Continuation>;\n /** Exactly-once: the second consume of the same id fails `NotFound`; a late one fails `Expired`. */\n readonly consume: (id: string) => Fx<Continuation>;\n };\n readonly attempts: {\n readonly create: (attempt: Attempt) => Fx<Attempt>;\n readonly get: (id: Plan.PlanId) => Fx<Attempt>;\n readonly byApproval: (id: Approval.ApprovalId) => Fx<Attempt>;\n readonly byReceipt: (id: Receipt.ReceiptId) => Fx<Attempt>;\n readonly latest: (attachmentId: string, kind: Plan.Kind) => Fx<Option.Option<Attempt>>;\n /** `planned` -> `approved`; approving again with the same approval id is a no-op, anything else fails `Stale`. */\n readonly approve: (id: Plan.PlanId, approval: Approval.Model) => Fx<Attempt>;\n /**\n * `planned` -> `rejected` (terminal). Rejecting again returns the row unchanged; any other\n * status fails `Stale`, `expired` fails `Expired`, and a digest mismatch fails `Stale`.\n */\n readonly reject: (\n id: Plan.PlanId,\n input: {\n readonly digest: Plan.Digest;\n readonly actorId: string;\n readonly reason: string | null;\n },\n ) => Fx<Attempt>;\n /**\n * Atomic transition to `applying` with a lease from `approved`, `failed`, or an expired\n * `applying`; fails `Busy` while a lease is live and `Stale` from any other status.\n */\n readonly claim: (id: Plan.PlanId, lease: DateTime.Utc) => Fx<Attempt>;\n readonly complete: (id: Plan.PlanId, receipt: Receipt.Model) => Fx<Attempt>;\n readonly fail: (id: Plan.PlanId, message: string) => Fx<Attempt>;\n };\n readonly readiness: {\n /** One row per (owner, domain); `attachmentId`, when set, must exist for the owner. */\n readonly put: (readiness: Readiness) => Fx<void>;\n readonly get: (domain: string) => Fx<Option.Option<Readiness>>;\n };\n /** Single-flight guard keyed by string (credential refresh, apply). Fails `Busy` rather than waiting. */\n readonly withLock: <A, E, R>(\n key: string,\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | Errors.DomainKitError, R | Principal.Service>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@domainkit/Storage\") {}\n\nexport interface MemoryOptions {\n /** Fault injection: runs before every mutation commits; failing here leaves state untouched. */\n readonly beforeCommit?: (operation: string) => Effect.Effect<void, Errors.DomainKitError>;\n}\n\n/** In-memory implementation for tests and local development. Not for production. */\nexport const layerMemory: Layer.Layer<Service> = Layer.sync(Service)(() => makeMemory());\n\n/** `layerMemory` with fault injection for storage-failure tests. */\nexport const layerMemoryWith = (options: MemoryOptions): Layer.Layer<Service> =>\n Layer.sync(Service)(() => makeMemory(options));\n\nexport { makeMemory };\n\n// ---------------------------------------------------------------------------------------------\n// Async adapter\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A Promise-shaped implementation for hosts that persist without Effect. Every method takes the\n * principal explicitly. Rejections become `StorageFailed`; reject with a `DomainKit.Error` to keep\n * a typed reason. Two-phase revocation and locking are split into plain steps so no callback has\n * to run an Effect.\n */\nexport interface AsyncInterface {\n readonly authorizations: {\n readonly upsert: (\n principal: Principal.Interface,\n input: {\n readonly authorization: Authorization;\n readonly credential: Credential;\n readonly expectedId?: string;\n },\n ) => Promise<Authorization>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Authorization>;\n readonly credential: (principal: Principal.Interface, id: string) => Promise<Credential>;\n readonly rotate: (\n principal: Principal.Interface,\n id: string,\n credential: Credential,\n ) => Promise<void>;\n readonly promoteCapabilities: (\n principal: Principal.Interface,\n id: string,\n capabilities: ReadonlyArray<Capability>,\n ) => Promise<void>;\n /** Mark `pending` durably; must be idempotent. */\n readonly prepareRevocation: (\n principal: Principal.Interface,\n id: string,\n ) => Promise<Authorization>;\n /** Delete the authorization after the provider confirmed revocation. */\n readonly completeRevocation: (principal: Principal.Interface, id: string) => Promise<void>;\n readonly pendingRevocations: (\n principal: Principal.Interface,\n ) => Promise<ReadonlyArray<Authorization>>;\n };\n readonly connections: {\n readonly create: (\n principal: Principal.Interface,\n authorizationId: string,\n ) => Promise<Connection>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Connection>;\n readonly list: (\n principal: Principal.Interface,\n filter?: { readonly provider?: string },\n ) => Promise<ReadonlyArray<Connection>>;\n readonly remove: (principal: Principal.Interface, id: string) => Promise<void>;\n };\n readonly attachments: {\n readonly create: (\n principal: Principal.Interface,\n input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string;\n readonly label: string;\n readonly target: unknown;\n },\n ) => Promise<Attachment>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Attachment>;\n readonly byDomain: (\n principal: Principal.Interface,\n domain: string,\n ) => Promise<Attachment | null>;\n readonly list: (\n principal: Principal.Interface,\n connectionId: string,\n ) => Promise<ReadonlyArray<Attachment>>;\n readonly remove: (principal: Principal.Interface, id: string) => Promise<void>;\n };\n readonly continuations: {\n readonly put: (principal: Principal.Interface, continuation: Continuation) => Promise<void>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Continuation>;\n readonly consume: (principal: Principal.Interface, id: string) => Promise<Continuation>;\n };\n readonly attempts: {\n readonly create: (principal: Principal.Interface, attempt: Attempt) => Promise<Attempt>;\n readonly get: (principal: Principal.Interface, id: Plan.PlanId) => Promise<Attempt>;\n readonly byApproval: (\n principal: Principal.Interface,\n id: Approval.ApprovalId,\n ) => Promise<Attempt>;\n readonly byReceipt: (principal: Principal.Interface, id: Receipt.ReceiptId) => Promise<Attempt>;\n readonly latest: (\n principal: Principal.Interface,\n attachmentId: string,\n kind: Plan.Kind,\n ) => Promise<Attempt | null>;\n readonly approve: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n approval: Approval.Model,\n ) => Promise<Attempt>;\n readonly reject: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n input: {\n readonly digest: Plan.Digest;\n readonly actorId: string;\n readonly reason: string | null;\n },\n ) => Promise<Attempt>;\n readonly claim: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n lease: DateTime.Utc,\n ) => Promise<Attempt>;\n readonly complete: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n receipt: Receipt.Model,\n ) => Promise<Attempt>;\n readonly fail: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n message: string,\n ) => Promise<Attempt>;\n };\n readonly readiness: {\n readonly put: (principal: Principal.Interface, readiness: Readiness) => Promise<void>;\n readonly get: (principal: Principal.Interface, domain: string) => Promise<Readiness | null>;\n };\n /** Return `false` when another holder has the key. */\n readonly acquireLock: (principal: Principal.Interface, key: string) => Promise<boolean>;\n readonly releaseLock: (principal: Principal.Interface, key: string) => Promise<void>;\n}\n\nconst storageFailed = (operation: string) => (cause: unknown) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.StorageFailed({\n operation,\n message: cause instanceof Error ? cause.message : String(cause),\n }),\n });\n\n/** Wraps a Promise-shaped implementation. Rejections become `StorageFailed`. */\nexport const fromAsync = (service: AsyncInterface): Interface => {\n const call = <A>(operation: string, run: (principal: Principal.Interface) => Promise<A>): Fx<A> =>\n Effect.flatMap(Principal.Service, (principal) =>\n Effect.tryPromise({ try: () => run(principal), catch: storageFailed(operation) }),\n );\n const option = <A>(\n operation: string,\n run: (principal: Principal.Interface) => Promise<A | null>,\n ) => call(operation, run).pipe(Effect.map(Option.fromNullishOr));\n return {\n authorizations: {\n upsert: (input) =>\n call(\"authorizations.upsert\", (p) => service.authorizations.upsert(p, input)),\n get: (id) => call(\"authorizations.get\", (p) => service.authorizations.get(p, id)),\n credential: (id) =>\n call(\"authorizations.credential\", (p) => service.authorizations.credential(p, id)),\n rotate: (id, credential) =>\n call(\"authorizations.rotate\", (p) => service.authorizations.rotate(p, id, credential)),\n promoteCapabilities: (id, capabilities) =>\n call(\"authorizations.promoteCapabilities\", (p) =>\n service.authorizations.promoteCapabilities(p, id, capabilities),\n ),\n revoke: (id, revoke) =>\n call(\"authorizations.prepareRevocation\", (p) =>\n service.authorizations.prepareRevocation(p, id),\n ).pipe(\n Effect.flatMap(() => revoke),\n Effect.flatMap(() =>\n call(\"authorizations.completeRevocation\", (p) =>\n service.authorizations.completeRevocation(p, id),\n ),\n ),\n ),\n recoverRevocations: (revoke) =>\n call(\"authorizations.pendingRevocations\", (p) =>\n service.authorizations.pendingRevocations(p),\n ).pipe(\n Effect.flatMap((pending) =>\n Effect.forEach(pending, (authorization) =>\n revoke(authorization).pipe(\n Effect.flatMap(() =>\n call(\"authorizations.completeRevocation\", (p) =>\n service.authorizations.completeRevocation(p, authorization.id),\n ),\n ),\n ),\n ),\n ),\n Effect.map((completed) => completed.length),\n ),\n },\n connections: {\n create: (authorizationId) =>\n call(\"connections.create\", (p) => service.connections.create(p, authorizationId)),\n get: (id) => call(\"connections.get\", (p) => service.connections.get(p, id)),\n list: (filter) => call(\"connections.list\", (p) => service.connections.list(p, filter)),\n remove: (id) => call(\"connections.remove\", (p) => service.connections.remove(p, id)),\n },\n attachments: {\n create: (input) => call(\"attachments.create\", (p) => service.attachments.create(p, input)),\n get: (id) => call(\"attachments.get\", (p) => service.attachments.get(p, id)),\n byDomain: (domain) =>\n option(\"attachments.byDomain\", (p) => service.attachments.byDomain(p, domain)),\n list: (connectionId) =>\n call(\"attachments.list\", (p) => service.attachments.list(p, connectionId)),\n remove: (id) => call(\"attachments.remove\", (p) => service.attachments.remove(p, id)),\n },\n continuations: {\n put: (continuation) =>\n call(\"continuations.put\", (p) => service.continuations.put(p, continuation)),\n get: (id) => call(\"continuations.get\", (p) => service.continuations.get(p, id)),\n consume: (id) => call(\"continuations.consume\", (p) => service.continuations.consume(p, id)),\n },\n attempts: {\n create: (attempt) => call(\"attempts.create\", (p) => service.attempts.create(p, attempt)),\n get: (id) => call(\"attempts.get\", (p) => service.attempts.get(p, id)),\n byApproval: (id) => call(\"attempts.byApproval\", (p) => service.attempts.byApproval(p, id)),\n byReceipt: (id) => call(\"attempts.byReceipt\", (p) => service.attempts.byReceipt(p, id)),\n latest: (attachmentId, kind) =>\n option(\"attempts.latest\", (p) => service.attempts.latest(p, attachmentId, kind)),\n approve: (id, approval) =>\n call(\"attempts.approve\", (p) => service.attempts.approve(p, id, approval)),\n reject: (id, input) => call(\"attempts.reject\", (p) => service.attempts.reject(p, id, input)),\n claim: (id, lease) => call(\"attempts.claim\", (p) => service.attempts.claim(p, id, lease)),\n complete: (id, receipt) =>\n call(\"attempts.complete\", (p) => service.attempts.complete(p, id, receipt)),\n fail: (id, message) => call(\"attempts.fail\", (p) => service.attempts.fail(p, id, message)),\n },\n readiness: {\n put: (readiness) => call(\"readiness.put\", (p) => service.readiness.put(p, readiness)),\n get: (domain) => option(\"readiness.get\", (p) => service.readiness.get(p, domain)),\n },\n withLock: (key, effect) =>\n Effect.acquireRelease(\n call(\"acquireLock\", (p) => service.acquireLock(p, key)).pipe(\n Effect.flatMap((acquired) =>\n acquired ? Effect.void : Errors.fail(new Reason.Busy({ key })),\n ),\n ),\n () => call(\"releaseLock\", (p) => service.releaseLock(p, key)).pipe(Effect.ignore),\n ).pipe(\n Effect.flatMap(() => effect),\n Effect.scoped,\n ),\n };\n};\n\nexport const layerFromAsync = (service: AsyncInterface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AAgB,MAAM,QAAQ,YAAY,GAAG,GAAG,CAAC,CAAC,CAAC,KACtD,OAAO,SAAS,aACd,WAAW,OAAO,OAAOC,KAAY,IAAIC,KAAY,EAAE,IAAI,CAAC,CAAC,CAC/D,CACF,SACM,KAAK,gBAAgB,MAAM,QAAQ,YAAY,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,CAClF,CAAC,CAAC,KACA,OAAO,cAAc,MAAM,GAC3B,OAAO,MACT;CACJ;AACF;AAEA,MAAa,kBAAkB,YAC7B,MAAM,QAAQ,OAAO,CAAC,CAAC,UAAU,OAAO,CAAC"}
|
|
1
|
+
{"version":3,"file":"Storage.mjs","names":["Plan.PlanId","Plan.Kind","Plan.Model","Approval.Model","Receipt.Model","Receipt.ReceiptId","Plan.OperationId","DnsRecord.Model","Errors.isDomainKitError","Errors.DomainKitError","Reason.StorageFailed","Principal.Service","Errors.fail","Reason.Busy"],"sources":["../src/Storage.ts"],"sourcesContent":["/**\n * Everything DomainKit persists, behind one service the host installs once. Every method requires\n * `Principal` and is scoped by it. `@domainkit/capsuledb` ships the Postgres implementation;\n * `domainkit/testing` ships the memory one; both pass `Testing.conformance.storage`.\n *\n * Storage never sees plaintext credentials: `Connect` seals secrets through `Custody` before\n * writing a `Credential` row and opens them after reading one.\n *\n * Grouped by noun so the 25-odd methods stay navigable. Implementations must satisfy the\n * invariants documented per group; the conformance suite checks them.\n */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\n\nimport * as Approval from \"./Approval.ts\";\nimport * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport { makeMemory } from \"./internal/storage-memory.ts\";\nimport * as Plan from \"./Plan.ts\";\nimport * as Principal from \"./Principal.ts\";\nimport * as Receipt from \"./Receipt.ts\";\n\nexport type Fx<A> = Effect.Effect<A, Errors.DomainKitError, Principal.Service>;\n\n// ---------------------------------------------------------------------------------------------\n// Rows\n// ---------------------------------------------------------------------------------------------\n\nexport const Capability = Schema.Literals([\"dns:read\", \"dns:write\"]);\nexport type Capability = typeof Capability.Type;\n\nexport const AuthMethod = Schema.Literals([\"token\", \"oauth\", \"integration\"]);\nexport type AuthMethod = typeof AuthMethod.Type;\n\n/** Sealed provider credential plus the metadata needed without unsealing it. */\nexport class Credential extends Schema.Class<Credential>(\"@domainkit/Storage/Credential\")({\n ciphertext: Schema.String,\n expiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n rotatedAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** One provider authorization (an OAuth grant or a token) owned by a principal. */\nexport class Authorization extends Schema.Class<Authorization>(\"@domainkit/Storage/Authorization\")({\n id: Schema.String,\n ownerId: Schema.String,\n provider: Schema.String,\n method: AuthMethod,\n capabilities: Schema.Array(Capability),\n /** Provider-specific account context (account id, team id, ...) decoded by the provider's `context` schema. */\n context: Schema.Unknown,\n revocation: Schema.Literals([\"active\", \"pending\", \"revoked\"]),\n createdBy: Schema.String,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** A connection is the principal-facing handle over an authorization; one authorization, many domains. */\nexport class Connection extends Schema.Class<Connection>(\"@domainkit/Storage/Connection\")({\n id: Schema.String,\n ownerId: Schema.String,\n authorizationId: Schema.String,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport class Attachment extends Schema.Class<Attachment>(\"@domainkit/Storage/Attachment\")({\n id: Schema.String,\n ownerId: Schema.String,\n connectionId: Schema.String,\n domain: Schema.String,\n zone: Schema.String,\n /** The target's label as the provider gave it at attach time, so a UI names the account without a provider call. */\n label: Schema.String,\n /** Provider zone identity (zone id, account id) decoded by the provider's `context` schema. */\n target: Schema.Unknown,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** Interactive-flow state between `Connect.start` and `Connect.complete`. */\nexport class Continuation extends Schema.Class<Continuation>(\"@domainkit/Storage/Continuation\")({\n id: Schema.String,\n ownerId: Schema.String,\n actorId: Schema.String,\n provider: Schema.String,\n payload: Schema.Unknown,\n returnTo: Schema.NullOr(Schema.String),\n expiresAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/**\n * Who a continuation belongs to, without the continuation itself. `payload` has no place here: it\n * carries the PKCE `codeVerifier`, which only the owner-scoped read may reach.\n */\nexport class ContinuationHeader extends Schema.Class<ContinuationHeader>(\n \"@domainkit/Storage/ContinuationHeader\",\n)({\n ownerId: Schema.String,\n actorId: Schema.String,\n provider: Schema.String,\n expiresAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport const AttemptStatus = Schema.Literals([\n \"planned\",\n \"approved\",\n \"applying\",\n \"complete\",\n \"partial\",\n \"failed\",\n \"expired\",\n \"rejected\",\n]);\nexport type AttemptStatus = typeof AttemptStatus.Type;\n\n/** Who declined the plan, why, and when. Terminal: the domain needs a new plan. */\nexport const Rejection = Schema.Struct({\n actorId: Schema.String,\n reason: Schema.NullOr(Schema.String),\n at: Schema.DateTimeUtcFromString,\n});\nexport type Rejection = typeof Rejection.Type;\n\n/** One durable plan -> approval -> receipt lifecycle. */\nexport class Attempt extends Schema.Class<Attempt>(\"@domainkit/Storage/Attempt\")({\n id: Plan.PlanId,\n ownerId: Schema.String,\n attachmentId: Schema.String,\n kind: Plan.Kind,\n status: AttemptStatus,\n plan: Plan.Model,\n approval: Schema.NullOr(Approval.Model),\n receipt: Schema.NullOr(Receipt.Model),\n rejection: Schema.NullOr(Rejection),\n /** Cleanup attempts point at the provisioning receipt they undo. */\n sourceReceiptId: Schema.NullOr(Receipt.ReceiptId),\n leaseExpiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n /** Why the last apply stopped before any write; cleared on the next claim. */\n failure: Schema.NullOr(Schema.String),\n updatedAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport const RequirementStatus = Schema.Literals([\"satisfied\", \"missing\", \"mismatch\", \"unknown\"]);\nexport type RequirementStatus = typeof RequirementStatus.Type;\n\nexport const Overall = Schema.Literals([\"ready\", \"pending\", \"failed\"]);\nexport type Overall = typeof Overall.Type;\n\n/**\n * Latest observed readiness for one domain, written by `Verify.observe`. Keyed by domain so\n * observe-only hosts (no attachment, public DNS alone) get the same row; `attachmentId` links the\n * attachment when one exists.\n */\nexport class Readiness extends Schema.Class<Readiness>(\"@domainkit/Storage/Readiness\")({\n domain: Schema.String,\n attachmentId: Schema.NullOr(Schema.String),\n ownerId: Schema.String,\n overall: Overall,\n requirements: Schema.Array(\n Schema.Struct({\n operationId: Schema.NullOr(Plan.OperationId),\n record: DnsRecord.Model,\n status: RequirementStatus,\n /** Encoded `Verify.Evidence` values. */\n evidence: Schema.Array(Schema.Unknown),\n }),\n ),\n /** Encoded `Verify.HostEvidence` values, keyed by `source` on merge. */\n host: Schema.Array(Schema.Unknown),\n /** When the current pending streak began; drives the backoff ladder. */\n pendingSince: Schema.NullOr(Schema.DateTimeUtcFromString),\n checkedAt: Schema.DateTimeUtcFromString,\n nextCheckAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n}) {}\n\n// ---------------------------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------------------------\n\nexport interface Interface {\n readonly authorizations: {\n /**\n * Insert, or CAS-replace when `expectedId` is set: the row must exist under this owner with an\n * active revocation state, else `NotFound` / `Busy`.\n */\n readonly upsert: (input: {\n readonly authorization: Authorization;\n readonly credential: Credential;\n readonly expectedId?: string;\n }) => Fx<Authorization>;\n readonly get: (id: string) => Fx<Authorization>;\n readonly credential: (id: string) => Fx<Credential>;\n readonly rotate: (id: string, credential: Credential) => Fx<void>;\n readonly promoteCapabilities: (id: string, capabilities: ReadonlyArray<Capability>) => Fx<void>;\n /**\n * Two-phase: mark `pending`, run `revoke` outside any transaction, then delete. A failed\n * `revoke` leaves the row pending; `recoverRevocations` finishes it later.\n */\n readonly revoke: <E, R>(\n id: string,\n revoke: Effect.Effect<void, E, R>,\n ) => Effect.Effect<void, Errors.DomainKitError | E, Principal.Service | R>;\n readonly recoverRevocations: <E, R>(\n revoke: (authorization: Authorization) => Effect.Effect<void, E, R>,\n ) => Effect.Effect<number, Errors.DomainKitError | E, Principal.Service | R>;\n };\n readonly connections: {\n readonly create: (authorizationId: string) => Fx<Connection>;\n readonly get: (id: string) => Fx<Connection>;\n readonly list: (filter?: { readonly provider?: string }) => Fx<ReadonlyArray<Connection>>;\n /** Fails `InvalidInput` while attachments still reference the connection. */\n readonly remove: (id: string) => Fx<void>;\n };\n readonly attachments: {\n /** One attachment per (owner, domain); a duplicate fails `InvalidInput`. */\n readonly create: (input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string;\n readonly label: string;\n readonly target: unknown;\n }) => Fx<Attachment>;\n readonly get: (id: string) => Fx<Attachment>;\n readonly byDomain: (domain: string) => Fx<Option.Option<Attachment>>;\n readonly list: (connectionId: string) => Fx<ReadonlyArray<Attachment>>;\n readonly remove: (id: string) => Fx<void>;\n };\n readonly continuations: {\n readonly put: (continuation: Continuation) => Fx<void>;\n /** Read without spending; a late read fails `Expired`. */\n readonly get: (id: string) => Fx<Continuation>;\n /**\n * The flow's owner, actor, provider, and expiry, without a principal and without spending the\n * row. The one read in this interface that is not tenant-scoped, because `domainkit/server`\n * has to learn whose flow a provider callback finishes before it can resolve the principal to\n * scope by; the callback carries a continuation id and a session cookie and nothing else.\n *\n * A missing row fails `NotFound` and a stale one fails `Expired`, exactly as `get` does, so an\n * expired id never reaches a host. `payload` is out of reach here by construction.\n */\n readonly header: (id: string) => Effect.Effect<ContinuationHeader, Errors.DomainKitError>;\n /** Exactly-once: the second consume of the same id fails `NotFound`; a late one fails `Expired`. */\n readonly consume: (id: string) => Fx<Continuation>;\n };\n readonly attempts: {\n readonly create: (attempt: Attempt) => Fx<Attempt>;\n readonly get: (id: Plan.PlanId) => Fx<Attempt>;\n readonly byApproval: (id: Approval.ApprovalId) => Fx<Attempt>;\n readonly byReceipt: (id: Receipt.ReceiptId) => Fx<Attempt>;\n readonly latest: (attachmentId: string, kind: Plan.Kind) => Fx<Option.Option<Attempt>>;\n /** `planned` -> `approved`; approving again with the same approval id is a no-op, anything else fails `Stale`. */\n readonly approve: (id: Plan.PlanId, approval: Approval.Model) => Fx<Attempt>;\n /**\n * `planned` -> `rejected` (terminal). Rejecting again returns the row unchanged; any other\n * status fails `Stale`, `expired` fails `Expired`, and a digest mismatch fails `Stale`.\n */\n readonly reject: (\n id: Plan.PlanId,\n input: {\n readonly digest: Plan.Digest;\n readonly actorId: string;\n readonly reason: string | null;\n },\n ) => Fx<Attempt>;\n /**\n * Atomic transition to `applying` with a lease from `approved`, `failed`, or an expired\n * `applying`; fails `Busy` while a lease is live and `Stale` from any other status.\n */\n readonly claim: (id: Plan.PlanId, lease: DateTime.Utc) => Fx<Attempt>;\n readonly complete: (id: Plan.PlanId, receipt: Receipt.Model) => Fx<Attempt>;\n readonly fail: (id: Plan.PlanId, message: string) => Fx<Attempt>;\n };\n readonly readiness: {\n /** One row per (owner, domain); `attachmentId`, when set, must exist for the owner. */\n readonly put: (readiness: Readiness) => Fx<void>;\n readonly get: (domain: string) => Fx<Option.Option<Readiness>>;\n };\n /** Single-flight guard keyed by string (credential refresh, apply). Fails `Busy` rather than waiting. */\n readonly withLock: <A, E, R>(\n key: string,\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | Errors.DomainKitError, R | Principal.Service>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@domainkit/Storage\") {}\n\nexport interface MemoryOptions {\n /** Fault injection: runs before every mutation commits; failing here leaves state untouched. */\n readonly beforeCommit?: (operation: string) => Effect.Effect<void, Errors.DomainKitError>;\n}\n\n/** In-memory implementation for tests and local development. Not for production. */\nexport const layerMemory: Layer.Layer<Service> = Layer.sync(Service)(() => makeMemory());\n\n/** `layerMemory` with fault injection for storage-failure tests. */\nexport const layerMemoryWith = (options: MemoryOptions): Layer.Layer<Service> =>\n Layer.sync(Service)(() => makeMemory(options));\n\nexport { makeMemory };\n\n// ---------------------------------------------------------------------------------------------\n// Async adapter\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A Promise-shaped implementation for hosts that persist without Effect. Every method takes the\n * principal explicitly. Rejections become `StorageFailed`; reject with a `DomainKit.Error` to keep\n * a typed reason. Two-phase revocation and locking are split into plain steps so no callback has\n * to run an Effect.\n */\nexport interface AsyncInterface {\n readonly authorizations: {\n readonly upsert: (\n principal: Principal.Interface,\n input: {\n readonly authorization: Authorization;\n readonly credential: Credential;\n readonly expectedId?: string;\n },\n ) => Promise<Authorization>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Authorization>;\n readonly credential: (principal: Principal.Interface, id: string) => Promise<Credential>;\n readonly rotate: (\n principal: Principal.Interface,\n id: string,\n credential: Credential,\n ) => Promise<void>;\n readonly promoteCapabilities: (\n principal: Principal.Interface,\n id: string,\n capabilities: ReadonlyArray<Capability>,\n ) => Promise<void>;\n /** Mark `pending` durably; must be idempotent. */\n readonly prepareRevocation: (\n principal: Principal.Interface,\n id: string,\n ) => Promise<Authorization>;\n /** Delete the authorization after the provider confirmed revocation. */\n readonly completeRevocation: (principal: Principal.Interface, id: string) => Promise<void>;\n readonly pendingRevocations: (\n principal: Principal.Interface,\n ) => Promise<ReadonlyArray<Authorization>>;\n };\n readonly connections: {\n readonly create: (\n principal: Principal.Interface,\n authorizationId: string,\n ) => Promise<Connection>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Connection>;\n readonly list: (\n principal: Principal.Interface,\n filter?: { readonly provider?: string },\n ) => Promise<ReadonlyArray<Connection>>;\n readonly remove: (principal: Principal.Interface, id: string) => Promise<void>;\n };\n readonly attachments: {\n readonly create: (\n principal: Principal.Interface,\n input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string;\n readonly label: string;\n readonly target: unknown;\n },\n ) => Promise<Attachment>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Attachment>;\n readonly byDomain: (\n principal: Principal.Interface,\n domain: string,\n ) => Promise<Attachment | null>;\n readonly list: (\n principal: Principal.Interface,\n connectionId: string,\n ) => Promise<ReadonlyArray<Attachment>>;\n readonly remove: (principal: Principal.Interface, id: string) => Promise<void>;\n };\n readonly continuations: {\n readonly put: (principal: Principal.Interface, continuation: Continuation) => Promise<void>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Continuation>;\n /** Takes no principal: see `Interface.continuations.header`. Never returns `payload`. */\n readonly header: (id: string) => Promise<ContinuationHeader>;\n readonly consume: (principal: Principal.Interface, id: string) => Promise<Continuation>;\n };\n readonly attempts: {\n readonly create: (principal: Principal.Interface, attempt: Attempt) => Promise<Attempt>;\n readonly get: (principal: Principal.Interface, id: Plan.PlanId) => Promise<Attempt>;\n readonly byApproval: (\n principal: Principal.Interface,\n id: Approval.ApprovalId,\n ) => Promise<Attempt>;\n readonly byReceipt: (principal: Principal.Interface, id: Receipt.ReceiptId) => Promise<Attempt>;\n readonly latest: (\n principal: Principal.Interface,\n attachmentId: string,\n kind: Plan.Kind,\n ) => Promise<Attempt | null>;\n readonly approve: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n approval: Approval.Model,\n ) => Promise<Attempt>;\n readonly reject: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n input: {\n readonly digest: Plan.Digest;\n readonly actorId: string;\n readonly reason: string | null;\n },\n ) => Promise<Attempt>;\n readonly claim: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n lease: DateTime.Utc,\n ) => Promise<Attempt>;\n readonly complete: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n receipt: Receipt.Model,\n ) => Promise<Attempt>;\n readonly fail: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n message: string,\n ) => Promise<Attempt>;\n };\n readonly readiness: {\n readonly put: (principal: Principal.Interface, readiness: Readiness) => Promise<void>;\n readonly get: (principal: Principal.Interface, domain: string) => Promise<Readiness | null>;\n };\n /** Return `false` when another holder has the key. */\n readonly acquireLock: (principal: Principal.Interface, key: string) => Promise<boolean>;\n readonly releaseLock: (principal: Principal.Interface, key: string) => Promise<void>;\n}\n\nconst storageFailed = (operation: string) => (cause: unknown) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.StorageFailed({\n operation,\n message: cause instanceof Error ? cause.message : String(cause),\n }),\n });\n\n/** Wraps a Promise-shaped implementation. Rejections become `StorageFailed`. */\nexport const fromAsync = (service: AsyncInterface): Interface => {\n const call = <A>(operation: string, run: (principal: Principal.Interface) => Promise<A>): Fx<A> =>\n Effect.flatMap(Principal.Service, (principal) =>\n Effect.tryPromise({ try: () => run(principal), catch: storageFailed(operation) }),\n );\n const option = <A>(\n operation: string,\n run: (principal: Principal.Interface) => Promise<A | null>,\n ) => call(operation, run).pipe(Effect.map(Option.fromNullishOr));\n return {\n authorizations: {\n upsert: (input) =>\n call(\"authorizations.upsert\", (p) => service.authorizations.upsert(p, input)),\n get: (id) => call(\"authorizations.get\", (p) => service.authorizations.get(p, id)),\n credential: (id) =>\n call(\"authorizations.credential\", (p) => service.authorizations.credential(p, id)),\n rotate: (id, credential) =>\n call(\"authorizations.rotate\", (p) => service.authorizations.rotate(p, id, credential)),\n promoteCapabilities: (id, capabilities) =>\n call(\"authorizations.promoteCapabilities\", (p) =>\n service.authorizations.promoteCapabilities(p, id, capabilities),\n ),\n revoke: (id, revoke) =>\n call(\"authorizations.prepareRevocation\", (p) =>\n service.authorizations.prepareRevocation(p, id),\n ).pipe(\n Effect.flatMap(() => revoke),\n Effect.flatMap(() =>\n call(\"authorizations.completeRevocation\", (p) =>\n service.authorizations.completeRevocation(p, id),\n ),\n ),\n ),\n recoverRevocations: (revoke) =>\n call(\"authorizations.pendingRevocations\", (p) =>\n service.authorizations.pendingRevocations(p),\n ).pipe(\n Effect.flatMap((pending) =>\n Effect.forEach(pending, (authorization) =>\n revoke(authorization).pipe(\n Effect.flatMap(() =>\n call(\"authorizations.completeRevocation\", (p) =>\n service.authorizations.completeRevocation(p, authorization.id),\n ),\n ),\n ),\n ),\n ),\n Effect.map((completed) => completed.length),\n ),\n },\n connections: {\n create: (authorizationId) =>\n call(\"connections.create\", (p) => service.connections.create(p, authorizationId)),\n get: (id) => call(\"connections.get\", (p) => service.connections.get(p, id)),\n list: (filter) => call(\"connections.list\", (p) => service.connections.list(p, filter)),\n remove: (id) => call(\"connections.remove\", (p) => service.connections.remove(p, id)),\n },\n attachments: {\n create: (input) => call(\"attachments.create\", (p) => service.attachments.create(p, input)),\n get: (id) => call(\"attachments.get\", (p) => service.attachments.get(p, id)),\n byDomain: (domain) =>\n option(\"attachments.byDomain\", (p) => service.attachments.byDomain(p, domain)),\n list: (connectionId) =>\n call(\"attachments.list\", (p) => service.attachments.list(p, connectionId)),\n remove: (id) => call(\"attachments.remove\", (p) => service.attachments.remove(p, id)),\n },\n continuations: {\n put: (continuation) =>\n call(\"continuations.put\", (p) => service.continuations.put(p, continuation)),\n get: (id) => call(\"continuations.get\", (p) => service.continuations.get(p, id)),\n header: (id) =>\n Effect.tryPromise({\n try: () => service.continuations.header(id),\n catch: storageFailed(\"continuations.header\"),\n }),\n consume: (id) => call(\"continuations.consume\", (p) => service.continuations.consume(p, id)),\n },\n attempts: {\n create: (attempt) => call(\"attempts.create\", (p) => service.attempts.create(p, attempt)),\n get: (id) => call(\"attempts.get\", (p) => service.attempts.get(p, id)),\n byApproval: (id) => call(\"attempts.byApproval\", (p) => service.attempts.byApproval(p, id)),\n byReceipt: (id) => call(\"attempts.byReceipt\", (p) => service.attempts.byReceipt(p, id)),\n latest: (attachmentId, kind) =>\n option(\"attempts.latest\", (p) => service.attempts.latest(p, attachmentId, kind)),\n approve: (id, approval) =>\n call(\"attempts.approve\", (p) => service.attempts.approve(p, id, approval)),\n reject: (id, input) => call(\"attempts.reject\", (p) => service.attempts.reject(p, id, input)),\n claim: (id, lease) => call(\"attempts.claim\", (p) => service.attempts.claim(p, id, lease)),\n complete: (id, receipt) =>\n call(\"attempts.complete\", (p) => service.attempts.complete(p, id, receipt)),\n fail: (id, message) => call(\"attempts.fail\", (p) => service.attempts.fail(p, id, message)),\n },\n readiness: {\n put: (readiness) => call(\"readiness.put\", (p) => service.readiness.put(p, readiness)),\n get: (domain) => option(\"readiness.get\", (p) => service.readiness.get(p, domain)),\n },\n withLock: (key, effect) =>\n Effect.acquireRelease(\n call(\"acquireLock\", (p) => service.acquireLock(p, key)).pipe(\n Effect.flatMap((acquired) =>\n acquired ? Effect.void : Errors.fail(new Reason.Busy({ key })),\n ),\n ),\n () => call(\"releaseLock\", (p) => service.releaseLock(p, key)).pipe(Effect.ignore),\n ).pipe(\n Effect.flatMap(() => effect),\n Effect.scoped,\n ),\n };\n};\n\nexport const layerFromAsync = (service: AsyncInterface): Layer.Layer<Service> =>\n Layer.succeed(Service)(fromAsync(service));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,aAAa,OAAO,SAAS,CAAC,YAAY,WAAW,CAAC;AAGnE,MAAa,aAAa,OAAO,SAAS;CAAC;CAAS;CAAS;AAAa,CAAC;;AAI3E,IAAa,aAAb,cAAgC,OAAO,MAAkB,+BAA+B,CAAC,CAAC;CACxF,YAAY,OAAO;CACnB,WAAW,OAAO,OAAO,OAAO,qBAAqB;CACrD,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,gBAAb,cAAmC,OAAO,MAAqB,kCAAkC,CAAC,CAAC;CACjG,IAAI,OAAO;CACX,SAAS,OAAO;CAChB,UAAU,OAAO;CACjB,QAAQ;CACR,cAAc,OAAO,MAAM,UAAU;;CAErC,SAAS,OAAO;CAChB,YAAY,OAAO,SAAS;EAAC;EAAU;EAAW;CAAS,CAAC;CAC5D,WAAW,OAAO;CAClB,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,aAAb,cAAgC,OAAO,MAAkB,+BAA+B,CAAC,CAAC;CACxF,IAAI,OAAO;CACX,SAAS,OAAO;CAChB,iBAAiB,OAAO;CACxB,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,a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
165
|
+
verification: {
|
|
166
|
+
observe: (domain, input) => request({
|
|
167
|
+
method: "POST",
|
|
168
|
+
path: `/domains/${encodeURIComponent(domain)}/observations`,
|
|
169
|
+
body: Schema.encodeSync(ObservePayload)(input?.requirements === void 0 ? {} : { requirements: input.requirements }),
|
|
170
|
+
success: Readiness
|
|
171
|
+
}),
|
|
172
|
+
latest: (domain) => request({
|
|
173
|
+
method: "GET",
|
|
174
|
+
path: `/domains/${encodeURIComponent(domain)}/readiness`,
|
|
175
|
+
success: Schema.NullOr(Readiness)
|
|
176
|
+
})
|
|
177
|
+
},
|
|
171
178
|
cleanup: {
|
|
172
179
|
plan: (receiptId) => request({
|
|
173
180
|
method: "POST",
|
package/dist/Transport.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Transport.mjs","names":["Server.Token","Server.OAuth","Server.Integration","Http.headersFrom","Http.requestJson","Errors.decode","Errors.DomainKitError","Http.classify","Server.ApprovePayload","Approval.Model","Server.RejectPayload","Server.Attempt","Receipt.Model","Server.Snapshot","Server.Discovery","Server.Zones","Server.StartPayload","Server.Started","Server.ReconnectPayload","Server.AttachPayload","Server.PlanPayload","Plan.Model","Server.ObservePayload","Server.Readiness","Errors.isDomainKitError","Reason.ProviderUnavailable"],"sources":["../src/Transport.ts"],"sourcesContent":["/**\n * domainkit/client — the browser-side transport `@domainkit/react` consumes. Capability groups are\n * optional: a host that only exposes connection routes declares just `connection`, and the parts\n * of the UI that plan or clean up do not render.\n *\n * const transport = Transport.fromFetch(\"/api/domainkit\")\n *\n * Every method decodes the same wire schemas `domainkit/server` encodes, so a failure arrives as\n * the `DomainKit.Error` the lifecycle raised, reason intact.\n */\nimport { Effect, Schema } from \"effect\";\n\nimport * as Approval from \"./Approval.ts\";\nimport type * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Http from \"./internal/http.ts\";\nimport * as Plan from \"./Plan.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport * as Receipt from \"./Receipt.ts\";\nimport * as Server from \"./Server.ts\";\n\ntype Fx<A> = Effect.Effect<A, Errors.DomainKitError>;\n\nexport type Snapshot = Server.Snapshot;\nexport type Started = Server.Started;\nexport type Readiness = Server.Readiness;\nexport type Attempt = Server.Attempt;\nexport type Candidate = Server.Candidate;\nexport type Discovery = Server.Discovery;\nexport type Zone = Server.Zone;\nexport type Zones = Server.Zones;\nexport type Attachment = Server.Attachment;\nexport type Field = Server.Field;\nexport type MethodDescriptor = Server.MethodDescriptor;\nexport type Method = Server.Method;\n\n/** How a client asks to connect. Mirrors `Connect.Method`, over the wire. */\nexport const Method = {\n /** A lone string for the common one-field provider, or the values its descriptor names. */\n token: (values: string | Readonly<Record<string, string>>): Method =>\n new Server.Token({ values: typeof values === \"string\" ? { token: values } : values }),\n oauth: (options: { readonly returnTo?: string } = {}): Method => new Server.OAuth(options),\n integration: (options: { readonly returnTo?: string } = {}): Method =>\n new Server.Integration(options),\n} as const;\n\nexport interface ConnectionGroup {\n readonly inspect: (domain: string) => Fx<Snapshot>;\n /** Which of this owner's existing connections already reaches the domain. */\n readonly discover: (domain: string) => Fx<Discovery>;\n /** Every zone this owner's connections reach, and where each connection stands. */\n readonly zones: (options?: { readonly provider?: string }) => Fx<Zones>;\n /** Connect a provider. Without a domain the account connects alone and attaches nothing. */\n readonly start: (input: {\n readonly domain?: string;\n readonly provider: string;\n readonly method: Method;\n }) => Fx<Started>;\n /** Prove an account again for a connection this owner holds, keeping its domains. */\n readonly reconnect: (input: {\n readonly connectionId: string;\n readonly method: Method;\n }) => Fx<Started>;\n readonly attach: (input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone?: string;\n }) => Fx<Started>;\n readonly detach: (attachmentId: string) => Fx<void>;\n readonly disconnect: (connectionId: string) => Fx<void>;\n}\n\nexport interface ProvisioningGroup {\n readonly plan: (input: {\n readonly domain: string;\n readonly requirements: ReadonlyArray<DnsRecord.Model>;\n }) => Fx<Plan.Model>;\n readonly approve: (input: {\n readonly planId: Plan.PlanId;\n readonly operationIds?: ReadonlyArray<Plan.OperationId>;\n }) => Fx<Approval.Model>;\n /** Decline the plan; terminal, and approving it afterwards fails `Stale`. */\n readonly reject: (input: {\n readonly planId: Plan.PlanId;\n readonly reason?: string;\n }) => Fx<Attempt>;\n readonly apply: (approvalId: Approval.ApprovalId) => Fx<Receipt.Model>;\n /** The stored plan with its status, approval, receipt, and rejection. */\n readonly attempt: (planId: Plan.PlanId) => Fx<Attempt>;\n /** What one apply landed, by receipt id, for a surface that holds the id and not the attempt. */\n readonly receipt: (receiptId: Receipt.ReceiptId) => Fx<Receipt.Model>;\n}\n\nexport interface VerificationGroup {\n /**\n * Observe the domain's provisioning receipt, or `options.requirements` when supplied (required\n * for a domain with no attachment).\n */\n readonly observe: (\n domain: string,\n options?: { readonly requirements?: ReadonlyArray<DnsRecord.Model> },\n ) => Fx<Readiness>;\n}\n\nexport interface CleanupGroup {\n readonly plan: (receiptId: Receipt.ReceiptId) => Fx<Plan.Model>;\n readonly approve: (input: {\n readonly planId: Plan.PlanId;\n readonly operationIds?: ReadonlyArray<Plan.OperationId>;\n }) => Fx<Approval.Model>;\n readonly reject: (input: {\n readonly planId: Plan.PlanId;\n readonly reason?: string;\n }) => Fx<Attempt>;\n readonly apply: (approvalId: Approval.ApprovalId) => Fx<Receipt.Model>;\n}\n\nexport interface Interface {\n readonly connection?: ConnectionGroup;\n readonly provisioning?: ProvisioningGroup;\n readonly verification?: VerificationGroup;\n readonly cleanup?: CleanupGroup;\n}\n\nexport type Capability = keyof Interface;\n\nexport const allCapabilities: ReadonlyArray<Capability> = [\n \"connection\",\n \"provisioning\",\n \"verification\",\n \"cleanup\",\n];\n\n/** Which groups this transport actually carries, in declaration order. */\nexport const capabilities = (transport: Interface): ReadonlyArray<Capability> =>\n allCapabilities.filter((capability) => transport[capability] !== undefined);\n\nexport interface FetchOptions {\n readonly fetch?: Http.Fetch;\n readonly headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n /** Which groups the server exposes. Default: all. */\n readonly capabilities?: ReadonlyArray<Capability>;\n}\n\n// ---------------------------------------------------------------------------------------------\n// fetch\n// ---------------------------------------------------------------------------------------------\n\n/** A transport over `domainkit/server` routes mounted at `baseUrl`. */\nexport const fromFetch = (baseUrl: string, options: FetchOptions = {}): Interface => {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const source = safeOrigin(base);\n // Resolved at call time and invoked as a free function: a browser `fetch` throws \"Illegal\n // invocation\" when called as a method of anything but `window`, and a host may polyfill later.\n const call: Http.Fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));\n const declared = options.capabilities ?? allCapabilities;\n\n const request = <A>(input: {\n readonly method: \"GET\" | \"POST\" | \"DELETE\";\n readonly path: string;\n readonly body?: unknown;\n readonly success: Schema.Codec<A, unknown> | null;\n }): Fx<A> =>\n Effect.gen(function* () {\n const headers = yield* Http.headersFrom(options.headers);\n if (input.body !== undefined) headers.set(\"content-type\", \"application/json\");\n const reply = yield* Http.requestJson({\n fetch: call,\n provider: source,\n url: `${base}${input.path}`,\n init: {\n method: input.method,\n headers,\n ...(input.body === undefined ? {} : { body: JSON.stringify(input.body) }),\n },\n });\n if (!reply.ok) {\n // The server answers failures with the `DomainKit.Error` value itself. Anything else came\n // from in front of it: a proxy, a login page, a maintenance window.\n const decoded = yield* Effect.result(\n Errors.decode(Errors.DomainKitError, reply.body, \"response\"),\n );\n return yield* decoded._tag === \"Success\"\n ? Effect.fail(decoded.success)\n : Effect.fail(\n new Errors.DomainKitError({\n reason: Http.classify(\n source,\n reply.status,\n reply.headers,\n `${input.method} ${input.path} answered ${reply.status}`,\n ),\n }),\n );\n }\n if (input.success === null) return undefined as A;\n return yield* Errors.decode(input.success, reply.body, \"response\");\n });\n\n /** Provisioning and cleanup share these routes; the attempt knows its kind. */\n const approve = (input: {\n readonly planId: Plan.PlanId;\n readonly operationIds?: ReadonlyArray<Plan.OperationId>;\n }) =>\n request({\n method: \"POST\",\n path: `/plans/${encodeURIComponent(input.planId)}/approvals`,\n body: Schema.encodeSync(Server.ApprovePayload)(\n input.operationIds === undefined ? {} : { operationIds: input.operationIds },\n ),\n success: Approval.Model,\n });\n\n const reject = (input: { readonly planId: Plan.PlanId; readonly reason?: string }) =>\n request({\n method: \"POST\",\n path: `/plans/${encodeURIComponent(input.planId)}/rejections`,\n body: Schema.encodeSync(Server.RejectPayload)(\n input.reason === undefined ? {} : { reason: input.reason },\n ),\n success: Server.Attempt,\n });\n\n const apply = (approvalId: Approval.ApprovalId) =>\n request({\n method: \"POST\",\n path: `/approvals/${encodeURIComponent(approvalId)}/apply`,\n success: Receipt.Model,\n });\n\n const connection: ConnectionGroup = {\n inspect: (domain) =>\n request({\n method: \"GET\",\n path: `/domains/${encodeURIComponent(domain)}`,\n success: Server.Snapshot,\n }),\n discover: (domain) =>\n request({\n method: \"GET\",\n path: `/domains/${encodeURIComponent(domain)}/discovery`,\n success: Server.Discovery,\n }),\n zones: (filter) =>\n request({\n method: \"GET\",\n path:\n filter?.provider === undefined\n ? \"/zones\"\n : `/zones?provider=${encodeURIComponent(filter.provider)}`,\n success: Server.Zones,\n }),\n start: (input) =>\n request({\n method: \"POST\",\n path: \"/connections\",\n body: Schema.encodeSync(Server.StartPayload)(\n input.domain === undefined\n ? { provider: input.provider, method: input.method }\n : { domain: input.domain, provider: input.provider, method: input.method },\n ),\n success: Server.Started,\n }),\n reconnect: (input) =>\n request({\n method: \"POST\",\n path: `/connections/${encodeURIComponent(input.connectionId)}/reconnections`,\n body: Schema.encodeSync(Server.ReconnectPayload)({ method: input.method }),\n success: Server.Started,\n }),\n attach: (input) =>\n request({\n method: \"POST\",\n path: `/connections/${encodeURIComponent(input.connectionId)}/attachments`,\n body: Schema.encodeSync(Server.AttachPayload)(\n input.zone === undefined\n ? { domain: input.domain }\n : { domain: input.domain, zone: input.zone },\n ),\n success: Server.Started,\n }),\n detach: (attachmentId) =>\n request({\n method: \"DELETE\",\n path: `/attachments/${encodeURIComponent(attachmentId)}`,\n success: null,\n }),\n disconnect: (connectionId) =>\n request({\n method: \"DELETE\",\n path: `/connections/${encodeURIComponent(connectionId)}`,\n success: null,\n }),\n };\n\n const provisioning: ProvisioningGroup = {\n plan: (input) =>\n request({\n method: \"POST\",\n path: `/domains/${encodeURIComponent(input.domain)}/plans`,\n body: Schema.encodeSync(Server.PlanPayload)({ requirements: input.requirements }),\n success: Plan.Model,\n }),\n approve,\n reject,\n apply,\n attempt: (planId) =>\n request({\n method: \"GET\",\n path: `/plans/${encodeURIComponent(planId)}`,\n success: Server.Attempt,\n }),\n receipt: (receiptId) =>\n request({\n method: \"GET\",\n path: `/receipts/${encodeURIComponent(receiptId)}`,\n success: Receipt.Model,\n }),\n };\n\n const verification: VerificationGroup = {\n observe: (domain, input) =>\n request({\n method: \"POST\",\n path: `/domains/${encodeURIComponent(domain)}/observations`,\n body: Schema.encodeSync(Server.ObservePayload)(\n input?.requirements === undefined ? {} : { requirements: input.requirements },\n ),\n success: Server.Readiness,\n }),\n };\n\n const cleanup: CleanupGroup = {\n plan: (receiptId) =>\n request({\n method: \"POST\",\n path: `/receipts/${encodeURIComponent(receiptId)}/cleanup-plans`,\n success: Plan.Model,\n }),\n approve,\n reject,\n apply,\n };\n\n const groups = { connection, provisioning, verification, cleanup };\n return Object.fromEntries(\n allCapabilities\n .filter((capability) => declared.includes(capability))\n .map((capability) => [capability, groups[capability]]),\n );\n};\n\n// ---------------------------------------------------------------------------------------------\n// Promise adapters\n// ---------------------------------------------------------------------------------------------\n\n/** The same transport in Promises, for hosts and tests that do not run Effect. */\nexport type AsyncTransport = {\n readonly [K in keyof Interface]?: {\n readonly [M in keyof NonNullable<Interface[K]>]: NonNullable<Interface[K]>[M] extends (\n ...args: infer A\n ) => Effect.Effect<infer R, Errors.DomainKitError>\n ? (...args: A) => Promise<R>\n : never;\n };\n};\n\n/** Adapt a Promise-shaped transport; a rejection that is not a `DomainKit.Error` becomes one. */\nexport const fromAsync = (transport: AsyncTransport): Interface =>\n mapGroups(\n transport,\n (method) =>\n (...args: ReadonlyArray<never>) =>\n Effect.tryPromise({\n try: () => method(...args) as Promise<unknown>,\n catch: (cause) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.ProviderUnavailable({\n provider: \"domainkit\",\n message: `The transport rejected: ${String(cause)}`,\n }),\n }),\n }),\n ) as Interface;\n\n/** Adapt to Promises; every rejection is the `DomainKit.Error` the lifecycle raised. */\nexport const toAsync = (transport: Interface): AsyncTransport =>\n mapGroups(\n transport,\n (method) =>\n (...args: ReadonlyArray<never>) =>\n Effect.runPromise(method(...args) as Effect.Effect<unknown, Errors.DomainKitError>),\n ) as AsyncTransport;\n\ntype AnyMethod = (...args: ReadonlyArray<never>) => unknown;\ntype AnyGroups = { readonly [key: string]: Record<string, AnyMethod> | undefined };\n\n/** Rebuild every declared group with each method wrapped; the two adapters differ only in `wrap`. */\nconst mapGroups = (source: object, wrap: (method: AnyMethod) => AnyMethod): unknown =>\n Object.fromEntries(\n allCapabilities.flatMap((capability) => {\n const group = (source as AnyGroups)[capability];\n if (group === undefined) return [];\n return [\n [\n capability,\n Object.fromEntries(Object.entries(group).map(([name, method]) => [name, wrap(method)])),\n ],\n ];\n }),\n );\n\n// ---------------------------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------------------------\n\nconst safeOrigin = (base: string): string => {\n try {\n return new URL(base).origin;\n } catch {\n return base === \"\" ? \"domainkit\" : base;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,SAAS;;CAEpB,QAAQ,WACN,IAAIA,MAAa,EAAE,QAAQ,OAAO,WAAW,WAAW,EAAE,OAAO,OAAO,IAAI,OAAO,CAAC;CACtF,QAAQ,UAA0C,CAAC,MAAc,IAAIC,MAAa,OAAO;CACzF,cAAc,UAA0C,CAAC,MACvD,IAAIC,YAAmB,OAAO;AAClC;AAkFA,MAAa,kBAA6C;CACxD;CACA;CACA;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AO,OAAO,YACZ,gBACG,QAAQ,eAAe,SAAS,SAAS,UAAU,CAAC,CAAC,CACrD,KAAK,eAAe,CAAC,YAAY,OAAO,WAAW,CAAC,CACzD;AACF;;AAkBA,MAAa,aAAa,cACxB,UACE,YACC,YACE,GAAG,SACF,OAAO,WAAW;CAChB,WAAW,OAAO,GAAG,IAAI;CACzB,QAAQ,UACNG,iBAAwB,KAAK,IACzB,QACA,IAAIlB,eAAsB,EACxB,QAAQ,IAAImB,oBAA2B;EACrC,UAAU;EACV,SAAS,2BAA2B,OAAO,KAAK;CAClD,CAAC,EACH,CAAC;AACT,CAAC,CACP;;AAGF,MAAa,WAAW,cACtB,UACE,YACC,YACE,GAAG,SACF,OAAO,WAAW,OAAO,GAAG,IAAI,CAAkD,CACxF;;AAMF,MAAM,aAAa,QAAgB,SACjC,OAAO,YACL,gBAAgB,SAAS,eAAe;CACtC,MAAM,QAAS,OAAqB;CACpC,IAAI,UAAU,KAAA,GAAW,OAAO,CAAC;CACjC,OAAO,CACL,CACE,YACA,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,CACxF,CACF;AACF,CAAC,CACH;AAMF,MAAM,cAAc,SAAyB;CAC3C,IAAI;EACF,OAAO,IAAI,IAAI,IAAI,CAAC,CAAC;CACvB,QAAQ;EACN,OAAO,SAAS,KAAK,cAAc;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"Transport.mjs","names":["Server.Token","Server.OAuth","Server.Integration","Http.headersFrom","Http.requestJson","Errors.decode","Errors.DomainKitError","Http.classify","Server.ApprovePayload","Approval.Model","Server.RejectPayload","Server.Attempt","Receipt.Model","Server.Snapshot","Server.Discovery","Server.Zones","Server.StartPayload","Server.Started","Server.ReconnectPayload","Server.AttachPayload","Server.PlanPayload","Plan.Model","Server.ObservePayload","Server.Readiness","Errors.isDomainKitError","Reason.ProviderUnavailable"],"sources":["../src/Transport.ts"],"sourcesContent":["/**\n * domainkit/client — the browser-side transport `@domainkit/react` consumes. Capability groups are\n * optional: a host that only exposes connection routes declares just `connection`, and the parts\n * of the UI that plan or clean up do not render.\n *\n * const transport = Transport.fromFetch(\"/api/domainkit\")\n *\n * Every method decodes the same wire schemas `domainkit/server` encodes, so a failure arrives as\n * the `DomainKit.Error` the lifecycle raised, reason intact.\n */\nimport { Effect, Schema } from \"effect\";\n\nimport * as Approval from \"./Approval.ts\";\nimport type * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Http from \"./internal/http.ts\";\nimport * as Plan from \"./Plan.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport * as Receipt from \"./Receipt.ts\";\nimport * as Server from \"./Server.ts\";\n\ntype Fx<A> = Effect.Effect<A, Errors.DomainKitError>;\n\nexport type Snapshot = Server.Snapshot;\nexport type Started = Server.Started;\nexport type Readiness = Server.Readiness;\nexport type Attempt = Server.Attempt;\nexport type Candidate = Server.Candidate;\nexport type Discovery = Server.Discovery;\nexport type Zone = Server.Zone;\nexport type Zones = Server.Zones;\nexport type Attachment = Server.Attachment;\nexport type Field = Server.Field;\nexport type MethodDescriptor = Server.MethodDescriptor;\nexport type Method = Server.Method;\n\n/** How a client asks to connect. Mirrors `Connect.Method`, over the wire. */\nexport const Method = {\n /** A lone string for the common one-field provider, or the values its descriptor names. */\n token: (values: string | Readonly<Record<string, string>>): Method =>\n new Server.Token({ values: typeof values === \"string\" ? { token: values } : values }),\n oauth: (options: { readonly returnTo?: string } = {}): Method => new Server.OAuth(options),\n integration: (options: { readonly returnTo?: string } = {}): Method =>\n new Server.Integration(options),\n} as const;\n\nexport interface ConnectionGroup {\n readonly inspect: (domain: string) => Fx<Snapshot>;\n /** Which of this owner's existing connections already reaches the domain. */\n readonly discover: (domain: string) => Fx<Discovery>;\n /** Every zone this owner's connections reach, and where each connection stands. */\n readonly zones: (options?: { readonly provider?: string }) => Fx<Zones>;\n /** Connect a provider. Without a domain the account connects alone and attaches nothing. */\n readonly start: (input: {\n readonly domain?: string;\n readonly provider: string;\n readonly method: Method;\n }) => Fx<Started>;\n /** Prove an account again for a connection this owner holds, keeping its domains. */\n readonly reconnect: (input: {\n readonly connectionId: string;\n readonly method: Method;\n }) => Fx<Started>;\n readonly attach: (input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone?: string;\n }) => Fx<Started>;\n readonly detach: (attachmentId: string) => Fx<void>;\n readonly disconnect: (connectionId: string) => Fx<void>;\n}\n\nexport interface ProvisioningGroup {\n readonly plan: (input: {\n readonly domain: string;\n readonly requirements: ReadonlyArray<DnsRecord.Model>;\n }) => Fx<Plan.Model>;\n readonly approve: (input: {\n readonly planId: Plan.PlanId;\n readonly operationIds?: ReadonlyArray<Plan.OperationId>;\n }) => Fx<Approval.Model>;\n /** Decline the plan; terminal, and approving it afterwards fails `Stale`. */\n readonly reject: (input: {\n readonly planId: Plan.PlanId;\n readonly reason?: string;\n }) => Fx<Attempt>;\n readonly apply: (approvalId: Approval.ApprovalId) => Fx<Receipt.Model>;\n /** The stored plan with its status, approval, receipt, and rejection. */\n readonly attempt: (planId: Plan.PlanId) => Fx<Attempt>;\n /** What one apply landed, by receipt id, for a surface that holds the id and not the attempt. */\n readonly receipt: (receiptId: Receipt.ReceiptId) => Fx<Receipt.Model>;\n}\n\nexport interface VerificationGroup {\n /**\n * Observe the domain's provisioning receipt, or `options.requirements` when supplied (required\n * for a domain with no attachment).\n */\n readonly observe: (\n domain: string,\n options?: { readonly requirements?: ReadonlyArray<DnsRecord.Model> },\n ) => Fx<Readiness>;\n /** The stored readiness, without observing. `null` until the domain has been observed once. */\n readonly latest: (domain: string) => Fx<Readiness | null>;\n}\n\nexport interface CleanupGroup {\n readonly plan: (receiptId: Receipt.ReceiptId) => Fx<Plan.Model>;\n readonly approve: (input: {\n readonly planId: Plan.PlanId;\n readonly operationIds?: ReadonlyArray<Plan.OperationId>;\n }) => Fx<Approval.Model>;\n readonly reject: (input: {\n readonly planId: Plan.PlanId;\n readonly reason?: string;\n }) => Fx<Attempt>;\n readonly apply: (approvalId: Approval.ApprovalId) => Fx<Receipt.Model>;\n}\n\nexport interface Interface {\n readonly connection?: ConnectionGroup;\n readonly provisioning?: ProvisioningGroup;\n readonly verification?: VerificationGroup;\n readonly cleanup?: CleanupGroup;\n}\n\nexport type Capability = keyof Interface;\n\nexport const allCapabilities: ReadonlyArray<Capability> = [\n \"connection\",\n \"provisioning\",\n \"verification\",\n \"cleanup\",\n];\n\n/** Which groups this transport actually carries, in declaration order. */\nexport const capabilities = (transport: Interface): ReadonlyArray<Capability> =>\n allCapabilities.filter((capability) => transport[capability] !== undefined);\n\nexport interface FetchOptions {\n readonly fetch?: Http.Fetch;\n readonly headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n /** Which groups the server exposes. Default: all. */\n readonly capabilities?: ReadonlyArray<Capability>;\n}\n\n// ---------------------------------------------------------------------------------------------\n// fetch\n// ---------------------------------------------------------------------------------------------\n\n/** A transport over `domainkit/server` routes mounted at `baseUrl`. */\nexport const fromFetch = (baseUrl: string, options: FetchOptions = {}): Interface => {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const source = safeOrigin(base);\n // Resolved at call time and invoked as a free function: a browser `fetch` throws \"Illegal\n // invocation\" when called as a method of anything but `window`, and a host may polyfill later.\n const call: Http.Fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));\n const declared = options.capabilities ?? allCapabilities;\n\n const request = <A>(input: {\n readonly method: \"GET\" | \"POST\" | \"DELETE\";\n readonly path: string;\n readonly body?: unknown;\n readonly success: Schema.Codec<A, unknown> | null;\n }): Fx<A> =>\n Effect.gen(function* () {\n const headers = yield* Http.headersFrom(options.headers);\n if (input.body !== undefined) headers.set(\"content-type\", \"application/json\");\n const reply = yield* Http.requestJson({\n fetch: call,\n provider: source,\n url: `${base}${input.path}`,\n init: {\n method: input.method,\n headers,\n ...(input.body === undefined ? {} : { body: JSON.stringify(input.body) }),\n },\n });\n if (!reply.ok) {\n // The server answers failures with the `DomainKit.Error` value itself. Anything else came\n // from in front of it: a proxy, a login page, a maintenance window.\n const decoded = yield* Effect.result(\n Errors.decode(Errors.DomainKitError, reply.body, \"response\"),\n );\n return yield* decoded._tag === \"Success\"\n ? Effect.fail(decoded.success)\n : Effect.fail(\n new Errors.DomainKitError({\n reason: Http.classify(\n source,\n reply.status,\n reply.headers,\n `${input.method} ${input.path} answered ${reply.status}`,\n ),\n }),\n );\n }\n if (input.success === null) return undefined as A;\n return yield* Errors.decode(input.success, reply.body, \"response\");\n });\n\n /** Provisioning and cleanup share these routes; the attempt knows its kind. */\n const approve = (input: {\n readonly planId: Plan.PlanId;\n readonly operationIds?: ReadonlyArray<Plan.OperationId>;\n }) =>\n request({\n method: \"POST\",\n path: `/plans/${encodeURIComponent(input.planId)}/approvals`,\n body: Schema.encodeSync(Server.ApprovePayload)(\n input.operationIds === undefined ? {} : { operationIds: input.operationIds },\n ),\n success: Approval.Model,\n });\n\n const reject = (input: { readonly planId: Plan.PlanId; readonly reason?: string }) =>\n request({\n method: \"POST\",\n path: `/plans/${encodeURIComponent(input.planId)}/rejections`,\n body: Schema.encodeSync(Server.RejectPayload)(\n input.reason === undefined ? {} : { reason: input.reason },\n ),\n success: Server.Attempt,\n });\n\n const apply = (approvalId: Approval.ApprovalId) =>\n request({\n method: \"POST\",\n path: `/approvals/${encodeURIComponent(approvalId)}/apply`,\n success: Receipt.Model,\n });\n\n const connection: ConnectionGroup = {\n inspect: (domain) =>\n request({\n method: \"GET\",\n path: `/domains/${encodeURIComponent(domain)}`,\n success: Server.Snapshot,\n }),\n discover: (domain) =>\n request({\n method: \"GET\",\n path: `/domains/${encodeURIComponent(domain)}/discovery`,\n success: Server.Discovery,\n }),\n zones: (filter) =>\n request({\n method: \"GET\",\n path:\n filter?.provider === undefined\n ? \"/zones\"\n : `/zones?provider=${encodeURIComponent(filter.provider)}`,\n success: Server.Zones,\n }),\n start: (input) =>\n request({\n method: \"POST\",\n path: \"/connections\",\n body: Schema.encodeSync(Server.StartPayload)(\n input.domain === undefined\n ? { provider: input.provider, method: input.method }\n : { domain: input.domain, provider: input.provider, method: input.method },\n ),\n success: Server.Started,\n }),\n reconnect: (input) =>\n request({\n method: \"POST\",\n path: `/connections/${encodeURIComponent(input.connectionId)}/reconnections`,\n body: Schema.encodeSync(Server.ReconnectPayload)({ method: input.method }),\n success: Server.Started,\n }),\n attach: (input) =>\n request({\n method: \"POST\",\n path: `/connections/${encodeURIComponent(input.connectionId)}/attachments`,\n body: Schema.encodeSync(Server.AttachPayload)(\n input.zone === undefined\n ? { domain: input.domain }\n : { domain: input.domain, zone: input.zone },\n ),\n success: Server.Started,\n }),\n detach: (attachmentId) =>\n request({\n method: \"DELETE\",\n path: `/attachments/${encodeURIComponent(attachmentId)}`,\n success: null,\n }),\n disconnect: (connectionId) =>\n request({\n method: \"DELETE\",\n path: `/connections/${encodeURIComponent(connectionId)}`,\n success: null,\n }),\n };\n\n const provisioning: ProvisioningGroup = {\n plan: (input) =>\n request({\n method: \"POST\",\n path: `/domains/${encodeURIComponent(input.domain)}/plans`,\n body: Schema.encodeSync(Server.PlanPayload)({ requirements: input.requirements }),\n success: Plan.Model,\n }),\n approve,\n reject,\n apply,\n attempt: (planId) =>\n request({\n method: \"GET\",\n path: `/plans/${encodeURIComponent(planId)}`,\n success: Server.Attempt,\n }),\n receipt: (receiptId) =>\n request({\n method: \"GET\",\n path: `/receipts/${encodeURIComponent(receiptId)}`,\n success: Receipt.Model,\n }),\n };\n\n const verification: VerificationGroup = {\n observe: (domain, input) =>\n request({\n method: \"POST\",\n path: `/domains/${encodeURIComponent(domain)}/observations`,\n body: Schema.encodeSync(Server.ObservePayload)(\n input?.requirements === undefined ? {} : { requirements: input.requirements },\n ),\n success: Server.Readiness,\n }),\n latest: (domain) =>\n request({\n method: \"GET\",\n path: `/domains/${encodeURIComponent(domain)}/readiness`,\n success: Schema.NullOr(Server.Readiness),\n }),\n };\n\n const cleanup: CleanupGroup = {\n plan: (receiptId) =>\n request({\n method: \"POST\",\n path: `/receipts/${encodeURIComponent(receiptId)}/cleanup-plans`,\n success: Plan.Model,\n }),\n approve,\n reject,\n apply,\n };\n\n const groups = { connection, provisioning, verification, cleanup };\n return Object.fromEntries(\n allCapabilities\n .filter((capability) => declared.includes(capability))\n .map((capability) => [capability, groups[capability]]),\n );\n};\n\n// ---------------------------------------------------------------------------------------------\n// Promise adapters\n// ---------------------------------------------------------------------------------------------\n\n/** The same transport in Promises, for hosts and tests that do not run Effect. */\nexport type AsyncTransport = {\n readonly [K in keyof Interface]?: {\n readonly [M in keyof NonNullable<Interface[K]>]: NonNullable<Interface[K]>[M] extends (\n ...args: infer A\n ) => Effect.Effect<infer R, Errors.DomainKitError>\n ? (...args: A) => Promise<R>\n : never;\n };\n};\n\n/** Adapt a Promise-shaped transport; a rejection that is not a `DomainKit.Error` becomes one. */\nexport const fromAsync = (transport: AsyncTransport): Interface =>\n mapGroups(\n transport,\n (method) =>\n (...args: ReadonlyArray<never>) =>\n Effect.tryPromise({\n try: () => method(...args) as Promise<unknown>,\n catch: (cause) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.ProviderUnavailable({\n provider: \"domainkit\",\n message: `The transport rejected: ${String(cause)}`,\n }),\n }),\n }),\n ) as Interface;\n\n/** Adapt to Promises; every rejection is the `DomainKit.Error` the lifecycle raised. */\nexport const toAsync = (transport: Interface): AsyncTransport =>\n mapGroups(\n transport,\n (method) =>\n (...args: ReadonlyArray<never>) =>\n Effect.runPromise(method(...args) as Effect.Effect<unknown, Errors.DomainKitError>),\n ) as AsyncTransport;\n\ntype AnyMethod = (...args: ReadonlyArray<never>) => unknown;\ntype AnyGroups = { readonly [key: string]: Record<string, AnyMethod> | undefined };\n\n/** Rebuild every declared group with each method wrapped; the two adapters differ only in `wrap`. */\nconst mapGroups = (source: object, wrap: (method: AnyMethod) => AnyMethod): unknown =>\n Object.fromEntries(\n allCapabilities.flatMap((capability) => {\n const group = (source as AnyGroups)[capability];\n if (group === undefined) return [];\n return [\n [\n capability,\n Object.fromEntries(Object.entries(group).map(([name, method]) => [name, wrap(method)])),\n ],\n ];\n }),\n );\n\n// ---------------------------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------------------------\n\nconst safeOrigin = (base: string): string => {\n try {\n return new URL(base).origin;\n } catch {\n return base === \"\" ? \"domainkit\" : base;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,SAAS;;CAEpB,QAAQ,WACN,IAAIA,MAAa,EAAE,QAAQ,OAAO,WAAW,WAAW,EAAE,OAAO,OAAO,IAAI,OAAO,CAAC;CACtF,QAAQ,UAA0C,CAAC,MAAc,IAAIC,MAAa,OAAO;CACzF,cAAc,UAA0C,CAAC,MACvD,IAAIC,YAAmB,OAAO;AAClC;AAoFA,MAAa,kBAA6C;CACxD;CACA;CACA;CACA;AACF;;AAGA,MAAa,gBAAgB,cAC3B,gBAAgB,QAAQ,eAAe,UAAU,gBAAgB,KAAA,CAAS;;AAc5E,MAAa,aAAa,SAAiB,UAAwB,CAAC,MAAiB;CACnF,MAAM,OAAO,QAAQ,QAAQ,QAAQ,EAAE;CACvC,MAAM,SAAS,WAAW,IAAI;CAG9B,MAAM,OAAmB,QAAQ,WAAW,OAAO,SAAS,WAAW,MAAM,OAAO,IAAI;CACxF,MAAM,WAAW,QAAQ,gBAAgB;CAEzC,MAAM,WAAc,UAMlB,OAAO,IAAI,aAAa;EACtB,MAAM,UAAU,OAAOC,YAAiB,QAAQ,OAAO;EACvD,IAAI,MAAM,SAAS,KAAA,GAAW,QAAQ,IAAI,gBAAgB,kBAAkB;EAC5E,MAAM,QAAQ,OAAOC,YAAiB;GACpC,OAAO;GACP,UAAU;GACV,KAAK,GAAG,OAAO,MAAM;GACrB,MAAM;IACJ,QAAQ,MAAM;IACd;IACA,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,E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L,gBAAgB,SAAS,eAAe;CACtC,MAAM,QAAS,OAAqB;CACpC,IAAI,UAAU,KAAA,GAAW,OAAO,CAAC;CACjC,OAAO,CACL,CACE,YACA,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,CACxF,CACF;AACF,CAAC,CACH;AAMF,MAAM,cAAc,SAAyB;CAC3C,IAAI;EACF,OAAO,IAAI,IAAI,IAAI,CAAC,CAAC;CACvB,QAAQ;EACN,OAAO,SAAS,KAAK,cAAc;CACrC;AACF"}
|
package/dist/Verify.mjs
CHANGED
|
@@ -17,6 +17,7 @@ import { Context, DateTime, Duration, Effect, Layer, Option, Schema } from "effe
|
|
|
17
17
|
var Verify_exports = /* @__PURE__ */ __exportAll({
|
|
18
18
|
Evidence: () => Evidence,
|
|
19
19
|
HostEvidence: () => HostEvidence,
|
|
20
|
+
Observer: () => Observer,
|
|
20
21
|
Policy: () => Policy,
|
|
21
22
|
ProviderEvidence: () => ProviderEvidence,
|
|
22
23
|
PublicDnsEvidence: () => PublicDnsEvidence,
|
|
@@ -27,7 +28,9 @@ var Verify_exports = /* @__PURE__ */ __exportAll({
|
|
|
27
28
|
layer: () => layer,
|
|
28
29
|
make: () => make,
|
|
29
30
|
observe: () => observe,
|
|
30
|
-
|
|
31
|
+
requirementKey: () => requirementKey,
|
|
32
|
+
statusAgainst: () => statusAgainst,
|
|
33
|
+
summary: () => summary
|
|
31
34
|
});
|
|
32
35
|
/**
|
|
33
36
|
* Every piece of evidence carries `values`, what the observer returned for the requirement's name
|
|
@@ -69,11 +72,49 @@ const Evidence = Schema.Union([
|
|
|
69
72
|
HostEvidence
|
|
70
73
|
]);
|
|
71
74
|
var Service = class extends Context.Service()("@domainkit/Verify") {};
|
|
75
|
+
/**
|
|
76
|
+
* A requirement's identity: the record's type, name, and data, and nothing else. It is what a host
|
|
77
|
+
* pairs its own rows against readiness by, instead of trusting the order of the array.
|
|
78
|
+
* `@domainkit/react`'s `Records.identity` is this function.
|
|
79
|
+
*/
|
|
80
|
+
const requirementKey = (record) => [
|
|
81
|
+
record._tag,
|
|
82
|
+
record.name,
|
|
83
|
+
data(record)
|
|
84
|
+
].join(":");
|
|
85
|
+
/**
|
|
86
|
+
* How a readiness stands, as counts. Pure and total: a host renders "3 of 4 found" from the stored
|
|
87
|
+
* fact without deciding what an absent readiness means, because `observed` says so.
|
|
88
|
+
*/
|
|
89
|
+
const summary = (readiness) => {
|
|
90
|
+
const statuses = readiness?.requirements.map(({ status }) => status) ?? [];
|
|
91
|
+
const count = (status) => statuses.filter((candidate) => candidate === status).length;
|
|
92
|
+
return {
|
|
93
|
+
observed: readiness !== null,
|
|
94
|
+
total: statuses.length,
|
|
95
|
+
satisfied: count("satisfied"),
|
|
96
|
+
missing: count("missing"),
|
|
97
|
+
mismatch: count("mismatch"),
|
|
98
|
+
unknown: count("unknown")
|
|
99
|
+
};
|
|
100
|
+
};
|
|
72
101
|
const defaults = {
|
|
73
102
|
backoff: (pendingForMs) => pendingForMs < 6e4 ? 15e3 : pendingForMs < 6e5 ? 6e4 : pendingForMs < 36e5 ? 3e5 : 18e5,
|
|
74
103
|
quorum: "any"
|
|
75
104
|
};
|
|
76
105
|
var Policy = class extends Context.Reference("@domainkit/Verify/Policy", { defaultValue: () => defaults }) {};
|
|
106
|
+
/**
|
|
107
|
+
* The host seam for "DomainKit wrote readiness". The default does nothing; provide one with
|
|
108
|
+
* `Effect.provideService(Verify.Observer, ...)` or `Layer.succeed(Verify.Observer, ...)` over
|
|
109
|
+
* `DomainKit.layer`, the same way `Policy` is overridden.
|
|
110
|
+
*
|
|
111
|
+
* It runs after `storage.readiness.put` returns, outside any transaction, because `Storage`
|
|
112
|
+
* exposes none. A failure or defect in the observer is logged and swallowed: the observation is
|
|
113
|
+
* already durable, and losing it because a projection failed would make the stored fact depend on
|
|
114
|
+
* the host's side effects. A host that needs the projection to be reliable enqueues durable work
|
|
115
|
+
* here rather than doing the work inline.
|
|
116
|
+
*/
|
|
117
|
+
var Observer = class extends Context.Reference("@domainkit/Verify/Observer", { defaultValue: () => ({ readinessChanged: () => Effect.void }) }) {};
|
|
77
118
|
const StoredEvidence = Schema.Array(Evidence);
|
|
78
119
|
const StoredHost = Schema.Array(HostEvidence);
|
|
79
120
|
/** A requirement is satisfied by an exact match; an exclusive one is contradicted by any same-set record. */
|
|
@@ -112,7 +153,7 @@ const overallOf = (requirements, host) => {
|
|
|
112
153
|
return requirements.length + host.length > 0 && requirements.every(({ status }) => status === "satisfied") && host.every(({ status }) => status === "ok") ? "ready" : "pending";
|
|
113
154
|
};
|
|
114
155
|
/** The identity of a requirement set: type, name, data, and policy, independent of labels and order. */
|
|
115
|
-
const
|
|
156
|
+
const requirementSetKey = (requirements) => requirements.map(({ record }) => `${record._tag} ${record.name} ${data(record)} ${record.policy}`).sort().join("\n");
|
|
116
157
|
const make = Effect.gen(function* () {
|
|
117
158
|
const storage = yield* Service$3;
|
|
118
159
|
const connect = yield* Service$4;
|
|
@@ -127,6 +168,7 @@ const make = Effect.gen(function* () {
|
|
|
127
168
|
});
|
|
128
169
|
const decodeRow = (row) => Effect.gen(function* () {
|
|
129
170
|
const requirements = yield* Effect.forEach(row.requirements, (requirement) => decode$1(StoredEvidence, requirement.evidence, "evidence").pipe(Effect.map((evidence) => ({
|
|
171
|
+
key: requirementKey(requirement.record),
|
|
130
172
|
operationId: requirement.operationId,
|
|
131
173
|
record: requirement.record,
|
|
132
174
|
status: requirement.status,
|
|
@@ -147,9 +189,10 @@ const make = Effect.gen(function* () {
|
|
|
147
189
|
const store = (input) => Effect.gen(function* () {
|
|
148
190
|
const principal = yield* Service$1;
|
|
149
191
|
const policy = yield* Policy;
|
|
192
|
+
const observer = yield* Observer;
|
|
150
193
|
const now = yield* DateTime.now;
|
|
151
194
|
const overall = overallOf(input.requirements, input.host);
|
|
152
|
-
const sameRequirements = Option.isSome(input.previous) &&
|
|
195
|
+
const sameRequirements = Option.isSome(input.previous) && requirementSetKey(input.previous.value.requirements) === requirementSetKey(input.requirements);
|
|
153
196
|
const pendingSince = overall === "ready" ? null : sameRequirements && Option.isSome(input.previous) && input.previous.value.pendingSince !== null ? input.previous.value.pendingSince : now;
|
|
154
197
|
const nextCheckAt = pendingSince === null ? null : DateTime.addDuration(now, Duration.millis(policy.backoff(DateTime.toEpochMillis(now) - DateTime.toEpochMillis(pendingSince))));
|
|
155
198
|
const row = new Readiness({
|
|
@@ -169,7 +212,7 @@ const make = Effect.gen(function* () {
|
|
|
169
212
|
nextCheckAt
|
|
170
213
|
});
|
|
171
214
|
yield* storage.readiness.put(row);
|
|
172
|
-
|
|
215
|
+
const readiness = {
|
|
173
216
|
domain: row.domain,
|
|
174
217
|
attachmentId: row.attachmentId,
|
|
175
218
|
overall,
|
|
@@ -178,6 +221,12 @@ const make = Effect.gen(function* () {
|
|
|
178
221
|
checkedAt: now,
|
|
179
222
|
nextCheckAt
|
|
180
223
|
};
|
|
224
|
+
yield* observer.readinessChanged({
|
|
225
|
+
domain: row.domain,
|
|
226
|
+
readiness,
|
|
227
|
+
cause: input.cause
|
|
228
|
+
}).pipe(Effect.catchCause((cause) => Effect.logWarning(`Verify.Observer failed for ${row.domain}`, cause)));
|
|
229
|
+
return readiness;
|
|
181
230
|
});
|
|
182
231
|
const defaultRequirements = (attachment) => Effect.gen(function* () {
|
|
183
232
|
const latest = yield* storage.attempts.latest(attachment.id, "provisioning");
|
|
@@ -236,10 +285,12 @@ const make = Effect.gen(function* () {
|
|
|
236
285
|
observedAt: now
|
|
237
286
|
}));
|
|
238
287
|
const publicStatus = quorumStatus(policy.quorum, publicEvidence.map(({ status }) => status));
|
|
288
|
+
const status = combine([...providerEvidence.map((evidence) => evidence.status), publicStatus]);
|
|
239
289
|
return {
|
|
290
|
+
key: requirementKey(record),
|
|
240
291
|
operationId,
|
|
241
292
|
record,
|
|
242
|
-
status
|
|
293
|
+
status,
|
|
243
294
|
evidence: [...providerEvidence, ...publicEvidence]
|
|
244
295
|
};
|
|
245
296
|
}), { concurrency: "unbounded" });
|
|
@@ -250,7 +301,8 @@ const make = Effect.gen(function* () {
|
|
|
250
301
|
attachment,
|
|
251
302
|
requirements: observed,
|
|
252
303
|
host,
|
|
253
|
-
previous
|
|
304
|
+
previous,
|
|
305
|
+
cause: "observe"
|
|
254
306
|
});
|
|
255
307
|
});
|
|
256
308
|
const attachEvidence = (input) => Effect.gen(function* () {
|
|
@@ -267,7 +319,8 @@ const make = Effect.gen(function* () {
|
|
|
267
319
|
attachment,
|
|
268
320
|
requirements: current.requirements,
|
|
269
321
|
host: [...bySource.values()],
|
|
270
|
-
previous
|
|
322
|
+
previous,
|
|
323
|
+
cause: "evidence"
|
|
271
324
|
});
|
|
272
325
|
});
|
|
273
326
|
const latest = (domain) => Effect.gen(function* () {
|
|
@@ -287,6 +340,6 @@ const observe = accessor((service) => service.observe);
|
|
|
287
340
|
const attachEvidence = accessor((service) => service.attachEvidence);
|
|
288
341
|
const latest = accessor((service) => service.latest);
|
|
289
342
|
//#endregion
|
|
290
|
-
export { Evidence, HostEvidence, Policy, ProviderEvidence, PublicDnsEvidence, Service, Verify_exports, attachEvidence, defaults, latest, layer, make, observe, statusAgainst };
|
|
343
|
+
export { Evidence, HostEvidence, Observer, Policy, ProviderEvidence, PublicDnsEvidence, Service, Verify_exports, attachEvidence, defaults, latest, layer, make, observe, requirementKey, statusAgainst, summary };
|
|
291
344
|
|
|
292
345
|
//# sourceMappingURL=Verify.mjs.map
|
package/dist/Verify.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Verify.mjs","names":["Storage.RequirementStatus","DnsRecord.equals","DnsRecord.sameSet","DnsRecord.data","Storage.Service","Connect.Service","Resolver.Service","DomainName.decode","Errors.decode","Principal.Service","Storage.Readiness","Errors.fail","Reason.InvalidInput"],"sources":["../src/Verify.ts"],"sourcesContent":["/**\n * Observe provider and public DNS for an attachment, persist per-requirement readiness, and say\n * when to look again. The host keeps its own state machine (and any provider-side verification\n * such as SES) and feeds that in as `HostEvidence`.\n */\nimport { Context, DateTime, Duration, Effect, Layer, Option, Schema } from \"effect\";\n\nimport * as Connect from \"./Connect.ts\";\nimport * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport * as DomainName from \"./DomainName.ts\";\nimport type * as Plan from \"./Plan.ts\";\nimport * as Principal from \"./Principal.ts\";\nimport * as Resolver from \"./Resolver.ts\";\nimport * as Storage from \"./Storage.ts\";\n\n/**\n * Every piece of evidence carries `values`, what the observer returned for the requirement's name\n * and type (empty when nothing was found, the lookup timed out, or the resolver failed), and\n * `detail`, `null` when the requirement is satisfied and otherwise the mismatch summary or the\n * resolver's error text, so a host can render \"found X, expected Y\".\n */\n// Rows written before these fields existed decode with the empty values.\nconst Values = Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([])));\nconst Detail = Schema.NullOr(Schema.String).pipe(\n Schema.withDecodingDefaultKey(Effect.succeed(null)),\n);\n\nexport class ProviderEvidence extends Schema.TaggedClass<ProviderEvidence>(\n \"@domainkit/Evidence/Provider\",\n)(\"Provider\", {\n provider: Schema.String,\n status: Storage.RequirementStatus,\n values: Values,\n detail: Detail,\n observedAt: Schema.DateTimeUtcFromString,\n}) {}\nexport class PublicDnsEvidence extends Schema.TaggedClass<PublicDnsEvidence>(\n \"@domainkit/Evidence/PublicDns\",\n)(\"PublicDns\", {\n resolver: Schema.String,\n status: Storage.RequirementStatus,\n values: Values,\n detail: Detail,\n observedAt: Schema.DateTimeUtcFromString,\n}) {}\n/** Anything the host knows that DomainKit cannot observe: SES identity status, a CDN cert, ... */\nexport class HostEvidence extends Schema.TaggedClass<HostEvidence>(\"@domainkit/Evidence/Host\")(\n \"Host\",\n {\n source: Schema.String,\n status: Schema.Literals([\"ok\", \"pending\", \"failed\"]),\n label: Schema.String,\n detail: Detail,\n observedAt: Schema.DateTimeUtcFromString,\n },\n) {}\nexport const Evidence = Schema.Union([ProviderEvidence, PublicDnsEvidence, HostEvidence]);\nexport type Evidence = typeof Evidence.Type;\n\nexport interface Requirement {\n readonly operationId: Plan.OperationId | null;\n readonly record: DnsRecord.Model;\n readonly status: Storage.RequirementStatus;\n readonly evidence: ReadonlyArray<Evidence>;\n}\n\nexport interface Readiness {\n readonly domain: string;\n /** `null` for observe-only domains that have no attachment. */\n readonly attachmentId: string | null;\n readonly overall: Storage.Overall;\n readonly requirements: ReadonlyArray<Requirement>;\n readonly host: ReadonlyArray<HostEvidence>;\n readonly checkedAt: DateTime.Utc;\n readonly nextCheckAt: DateTime.Utc | null;\n}\n\ntype Fx<A> = Effect.Effect<A, Errors.DomainKitError, Principal.Service>;\n\nexport interface Interface {\n /**\n * What to observe, in order of precedence: `requirements` when supplied (an attached domain\n * without a provisioning receipt, or a domain with no attachment whose records the customer\n * applies by hand), else the latest provisioning receipt of the domain's attachment (records it\n * applied or found in place). Neither is `InvalidInput`. Provider evidence is added when the\n * attachment's session can be built; public DNS is always observed, and readiness is stored\n * per domain either way.\n */\n readonly observe: (input: {\n readonly domain: string;\n readonly requirements?: ReadonlyArray<DnsRecord.Model>;\n }) => Fx<Readiness>;\n /** Merge host evidence into stored readiness without re-observing DNS. */\n readonly attachEvidence: (input: {\n readonly domain: string;\n readonly evidence: ReadonlyArray<HostEvidence>;\n }) => Fx<Readiness>;\n readonly latest: (domain: string) => Fx<Readiness | null>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@domainkit/Verify\") {}\n\nexport interface PolicyShape {\n /** Delay before the next check, given time since the first pending observation. Default ladder: 15s, 1m, 5m, 30m. */\n readonly backoff: (pendingForMs: number) => number;\n /** Which resolvers must agree for `satisfied`: default `any`. */\n readonly quorum: \"any\" | \"all\" | { readonly minimum: number };\n}\nexport const defaults: PolicyShape = {\n backoff: (pendingForMs) =>\n pendingForMs < 60_000\n ? 15_000\n : pendingForMs < 10 * 60_000\n ? 60_000\n : pendingForMs < 60 * 60_000\n ? 5 * 60_000\n : 30 * 60_000,\n quorum: \"any\",\n};\nexport class Policy extends Context.Reference<PolicyShape>(\"@domainkit/Verify/Policy\", {\n defaultValue: () => defaults,\n}) {}\n\n// ---------------------------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------------------------\n\nconst StoredEvidence = Schema.Array(Evidence);\n\ninterface ProviderSide {\n readonly provider: string;\n readonly records: ReadonlyArray<DnsRecord.Observed>;\n}\nconst StoredHost = Schema.Array(HostEvidence);\n\n/** A requirement is satisfied by an exact match; an exclusive one is contradicted by any same-set record. */\nexport const statusAgainst = (\n record: DnsRecord.Model,\n observed: ReadonlyArray<DnsRecord.Observed>,\n): Storage.RequirementStatus => {\n if (observed.some((candidate) => DnsRecord.equals(candidate, record))) return \"satisfied\";\n if (\n record.policy === \"exclusive\" &&\n observed.some((candidate) => DnsRecord.sameSet(candidate, record))\n ) {\n return \"mismatch\";\n }\n return \"missing\";\n};\n\ninterface Observation {\n readonly status: Storage.RequirementStatus;\n readonly values: ReadonlyArray<string>;\n readonly detail: string | null;\n}\n\nconst render = (observed: DnsRecord.Observed): string =>\n observed._tag === \"Opaque\" ? JSON.stringify(observed.raw) : DnsRecord.data(observed);\n\n/** Status plus what the observer holds for the requirement's name and type. */\nconst observation = (\n record: DnsRecord.Model,\n observed: ReadonlyArray<DnsRecord.Observed>,\n): Observation => {\n const status = statusAgainst(record, observed);\n const values = observed.filter((candidate) => DnsRecord.sameSet(candidate, record)).map(render);\n const detail =\n status === \"satisfied\"\n ? null\n : values.length === 0\n ? `no ${record._tag} record at ${record.name}`\n : `expected ${DnsRecord.data(record)}; found ${values.join(\", \")}`;\n return { status, values, detail };\n};\n\nconst combine = (statuses: ReadonlyArray<Storage.RequirementStatus>): Storage.RequirementStatus => {\n const known = statuses.filter((status) => status !== \"unknown\");\n if (known.length === 0) return \"unknown\";\n if (known.includes(\"mismatch\")) return \"mismatch\";\n return known.every((status) => status === \"satisfied\") ? \"satisfied\" : \"missing\";\n};\n\nconst quorumStatus = (\n quorum: PolicyShape[\"quorum\"],\n statuses: ReadonlyArray<Storage.RequirementStatus>,\n): Storage.RequirementStatus => {\n const known = statuses.filter((status) => status !== \"unknown\");\n const satisfied = known.filter((status) => status === \"satisfied\").length;\n const needed =\n quorum === \"any\" ? 1 : quorum === \"all\" ? Math.max(1, known.length) : quorum.minimum;\n if (known.includes(\"mismatch\")) return \"mismatch\";\n if (known.length > 0 && satisfied >= needed) return \"satisfied\";\n return known.length === 0 ? \"unknown\" : \"missing\";\n};\n\nconst overallOf = (\n requirements: ReadonlyArray<{ readonly status: Storage.RequirementStatus }>,\n host: ReadonlyArray<HostEvidence>,\n): Storage.Overall => {\n if (\n requirements.some(({ status }) => status === \"mismatch\") ||\n host.some(({ status }) => status === \"failed\")\n ) {\n return \"failed\";\n }\n const ready =\n requirements.length + host.length > 0 &&\n requirements.every(({ status }) => status === \"satisfied\") &&\n host.every(({ status }) => status === \"ok\");\n return ready ? \"ready\" : \"pending\";\n};\n\n/** The identity of a requirement set: type, name, data, and policy, independent of labels and order. */\nconst requirementKey = (requirements: ReadonlyArray<{ readonly record: DnsRecord.Model }>) =>\n requirements\n .map(({ record }) => `${record._tag} ${record.name} ${DnsRecord.data(record)} ${record.policy}`)\n .sort()\n .join(\"\\n\");\n\nexport const make: Effect.Effect<\n Interface,\n never,\n Storage.Service | Connect.Service | Resolver.Service\n> = Effect.gen(function* () {\n const storage = yield* Storage.Service;\n const connect = yield* Connect.Service;\n const resolver = yield* Resolver.Service;\n\n const attachmentFor = (\n input: string,\n ): Fx<{\n readonly domain: DomainName.Model;\n readonly attachment: Storage.Attachment | null;\n }> =>\n Effect.gen(function* () {\n const domain = yield* DomainName.decode(input);\n const attachment = yield* storage.attachments.byDomain(domain);\n return { domain, attachment: Option.getOrNull(attachment) };\n });\n\n const decodeRow = (row: Storage.Readiness): Effect.Effect<Readiness, Errors.DomainKitError> =>\n Effect.gen(function* () {\n const requirements = yield* Effect.forEach(row.requirements, (requirement) =>\n Errors.decode(StoredEvidence, requirement.evidence, \"evidence\").pipe(\n Effect.map((evidence): Requirement => ({\n operationId: requirement.operationId,\n record: requirement.record,\n status: requirement.status,\n evidence,\n })),\n ),\n );\n const host = yield* Errors.decode(StoredHost, row.host, \"host\");\n return {\n domain: row.domain,\n attachmentId: row.attachmentId,\n overall: row.overall,\n requirements,\n host,\n checkedAt: row.checkedAt,\n nextCheckAt: row.nextCheckAt,\n };\n });\n\n /** Persist readiness, carrying the pending streak forward for the backoff ladder. */\n const store = (input: {\n readonly domain: string;\n readonly attachment: Storage.Attachment | null;\n readonly requirements: ReadonlyArray<Requirement>;\n readonly host: ReadonlyArray<HostEvidence>;\n readonly previous: Option.Option<Storage.Readiness>;\n }): Fx<Readiness> =>\n Effect.gen(function* () {\n const principal = yield* Principal.Service;\n const policy = yield* Policy;\n const now = yield* DateTime.now;\n const overall = overallOf(input.requirements, input.host);\n const sameRequirements =\n Option.isSome(input.previous) &&\n requirementKey(input.previous.value.requirements) === requirementKey(input.requirements);\n const pendingSince =\n overall === \"ready\"\n ? null\n : sameRequirements &&\n Option.isSome(input.previous) &&\n input.previous.value.pendingSince !== null\n ? input.previous.value.pendingSince\n : now;\n const nextCheckAt =\n pendingSince === null\n ? null\n : DateTime.addDuration(\n now,\n Duration.millis(\n policy.backoff(DateTime.toEpochMillis(now) - DateTime.toEpochMillis(pendingSince)),\n ),\n );\n const row = new Storage.Readiness({\n domain: input.domain,\n attachmentId: input.attachment?.id ?? null,\n ownerId: principal.ownerId,\n overall,\n requirements: input.requirements.map((requirement) => ({\n operationId: requirement.operationId,\n record: requirement.record,\n status: requirement.status,\n evidence: Schema.encodeSync(StoredEvidence)(requirement.evidence),\n })),\n host: Schema.encodeSync(StoredHost)(input.host),\n pendingSince,\n checkedAt: now,\n nextCheckAt,\n });\n yield* storage.readiness.put(row);\n return {\n domain: row.domain,\n attachmentId: row.attachmentId,\n overall,\n requirements: input.requirements,\n host: input.host,\n checkedAt: now,\n nextCheckAt,\n };\n });\n\n const defaultRequirements = (\n attachment: Storage.Attachment,\n ): Fx<\n ReadonlyArray<{\n readonly operationId: Plan.OperationId | null;\n readonly record: DnsRecord.Model;\n }>\n > =>\n Effect.gen(function* () {\n const latest = yield* storage.attempts.latest(attachment.id, \"provisioning\");\n if (Option.isNone(latest) || latest.value.receipt === null) {\n return yield* Errors.fail(\n new Reason.InvalidInput({\n message: `${attachment.domain} has no provisioning receipt; pass requirements to observe`,\n field: \"requirements\",\n }),\n );\n }\n const receipt = latest.value.receipt;\n const inPlace = new Set(\n receipt.outcomes.flatMap((outcome) =>\n outcome._tag === \"Applied\" || (outcome._tag === \"Skipped\" && outcome.reason === \"noop\")\n ? [outcome.operationId]\n : [],\n ),\n );\n return latest.value.plan.operations\n .filter((operation) => inPlace.has(operation.id))\n .map((operation) => ({ operationId: operation.id, record: operation.record }));\n });\n\n const observe: Interface[\"observe\"] = (input) =>\n Effect.gen(function* () {\n const policy = yield* Policy;\n const { domain, attachment } = yield* attachmentFor(input.domain);\n if (input.requirements === undefined && attachment === null) {\n return yield* Errors.fail(\n new Reason.InvalidInput({\n message: `${domain} is not attached; pass requirements to observe public DNS`,\n field: \"requirements\",\n }),\n );\n }\n const requirements =\n input.requirements === undefined && attachment !== null\n ? yield* defaultRequirements(attachment)\n : (input.requirements ?? []).map((record) => ({ operationId: null, record }));\n if (requirements.length === 0) {\n return yield* Errors.fail(\n new Reason.InvalidInput({\n message: \"Nothing to observe: pass at least one requirement\",\n field: \"requirements\",\n }),\n );\n }\n const now = yield* DateTime.now;\n // Provider readback is evidence when the attachment's session can be built; when it\n // cannot (no attachment, revoked credential, provider outage) public DNS stands alone.\n const providerSide = yield* attachment === null\n ? Effect.succeed(Option.none<ProviderSide>())\n : Effect.gen(function* () {\n const connection = yield* storage.connections.get(attachment.connectionId);\n const authorization = yield* storage.authorizations.get(connection.authorizationId);\n const { session, target } = yield* connect.session(attachment.id);\n const observed = yield* session.dns(target).list(target.zone);\n return Option.some<ProviderSide>({\n provider: authorization.provider,\n records: observed.map(({ record }) => record),\n });\n }).pipe(Effect.catch(() => Effect.succeed(Option.none<ProviderSide>())));\n const observed = yield* Effect.forEach(\n requirements,\n ({ operationId, record }) =>\n Effect.gen(function* () {\n const providerEvidence = Option.isSome(providerSide)\n ? [\n new ProviderEvidence({\n provider: providerSide.value.provider,\n ...observation(record, providerSide.value.records),\n observedAt: now,\n }),\n ]\n : [];\n const outcomes = yield* resolver.resolve(record.name, record._tag);\n const publicEvidence = outcomes.map((outcome) =>\n outcome._tag === \"Answered\"\n ? new PublicDnsEvidence({\n resolver: outcome.answer.resolver,\n ...observation(record, outcome.answer.records),\n observedAt: now,\n })\n : new PublicDnsEvidence({\n resolver: outcome.resolver,\n status: \"unknown\",\n values: [],\n detail:\n outcome._tag === \"TimedOut\"\n ? `${outcome.resolver} timed out`\n : outcome.message,\n observedAt: now,\n }),\n );\n const publicStatus = quorumStatus(\n policy.quorum,\n publicEvidence.map(({ status }) => status),\n );\n const status = combine([\n ...providerEvidence.map((evidence) => evidence.status),\n publicStatus,\n ]);\n return {\n operationId,\n record,\n status,\n evidence: [...providerEvidence, ...publicEvidence],\n } satisfies Requirement;\n }),\n { concurrency: \"unbounded\" },\n );\n const previous = yield* storage.readiness.get(domain);\n const host = Option.isSome(previous)\n ? yield* Errors.decode(StoredHost, previous.value.host, \"host\")\n : [];\n return yield* store({ domain, attachment, requirements: observed, host, previous });\n });\n\n const attachEvidence: Interface[\"attachEvidence\"] = (input) =>\n Effect.gen(function* () {\n const { domain, attachment } = yield* attachmentFor(input.domain);\n const previous = yield* storage.readiness.get(domain);\n const current = Option.isSome(previous)\n ? yield* decodeRow(previous.value)\n : {\n requirements: [] as ReadonlyArray<Requirement>,\n host: [] as ReadonlyArray<HostEvidence>,\n };\n const bySource = new Map(current.host.map((evidence) => [evidence.source, evidence]));\n for (const evidence of input.evidence) bySource.set(evidence.source, evidence);\n return yield* store({\n domain,\n attachment,\n requirements: current.requirements,\n host: [...bySource.values()],\n previous,\n });\n });\n\n const latest: Interface[\"latest\"] = (domain) =>\n Effect.gen(function* () {\n const { domain: name } = yield* attachmentFor(domain);\n const stored = yield* storage.readiness.get(name);\n return Option.isSome(stored) ? yield* decodeRow(stored.value) : null;\n });\n\n return { observe, attachEvidence, latest };\n});\n\nexport const layer: Layer.Layer<\n Service,\n never,\n Storage.Service | Connect.Service | Resolver.Service\n> = Layer.effect(Service)(make);\n\nconst accessor =\n <Args extends ReadonlyArray<unknown>, A>(\n pick: (service: Interface) => (...args: Args) => Fx<A>,\n ): ((...args: Args) => Effect.Effect<A, Errors.DomainKitError, Principal.Service | Service>) =>\n (...args) =>\n Effect.flatMap(Service, (service) => pick(service)(...args));\n\nexport const observe = accessor((service) => service.observe);\nexport const attachEvidence = accessor((service) => service.attachEvidence);\nexport const latest = accessor((service) => service.latest);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC,CAAC,KAAK,OAAO,uBAAuB,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;AACjG,MAAM,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC,CAAC,KAC1C,OAAO,uBAAuB,OAAO,QAAQ,IAAI,CAAC,CACpD;AAEA,IAAa,mBAAb,cAAsC,OAAO,YAC3C,8BACF,CAAC,CAAC,YAAY;CACZ,UAAU,OAAO;CACjB,QAAQA;CACR,QAAQ;CACR,QAAQ;CACR,YAAY,OAAO;AACrB,CAAC,CAAC,CAAC,CAAC;AACJ,IAAa,oBAAb,cAAuC,OAAO,YAC5C,+BACF,CAAC,CAAC,aAAa;CACb,UAAU,OAAO;CACjB,QAAQA;CACR,QAAQ;CACR,QAAQ;CACR,YAAY,OAAO;AACrB,CAAC,CAAC,CAAC,CAAC;;AAEJ,IAAa,eAAb,cAAkC,OAAO,YAA0B,0BAA0B,CAAC,CAC5F,QACA;CACE,QAAQ,OAAO;CACf,QAA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,aAAa;EACtB,MAAM,EAAE,QAAQ,SAAS,OAAO,cAAc,MAAM;EACpD,MAAM,SAAS,OAAO,QAAQ,UAAU,IAAI,IAAI;EAChD,OAAO,OAAO,OAAO,MAAM,IAAI,OAAO,UAAU,OAAO,KAAK,IAAI;CAClE,CAAC;CAEH,OAAO;EAAE;EAAS;EAAgB;CAAO;AAC3C,CAAC;AAED,MAAa,QAIT,MAAM,OAAO,OAAO,CAAC,CAAC,IAAI;AAE9B,MAAM,YAEF,UAED,GAAG,SACF,OAAO,QAAQ,UAAU,YAAY,KAAK,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;AAE/D,MAAa,UAAU,UAAU,YAAY,QAAQ,OAAO;AAC5D,MAAa,iBAAiB,UAAU,YAAY,QAAQ,cAAc;AAC1E,MAAa,SAAS,UAAU,YAAY,QAAQ,MAAM"}
|
|
1
|
+
{"version":3,"file":"Verify.mjs","names":["Storage.RequirementStatus","DnsRecord.data","DnsRecord.equals","DnsRecord.sameSet","Storage.Service","Connect.Service","Resolver.Service","DomainName.decode","Errors.decode","Principal.Service","Storage.Readiness","Errors.fail","Reason.InvalidInput"],"sources":["../src/Verify.ts"],"sourcesContent":["/**\n * Observe provider and public DNS for an attachment, persist per-requirement readiness, and say\n * when to look again. The host keeps its own state machine (and any provider-side verification\n * such as SES) and feeds that in as `HostEvidence`.\n */\nimport { Context, DateTime, Duration, Effect, Layer, Option, Schema } from \"effect\";\n\nimport * as Connect from \"./Connect.ts\";\nimport * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport * as DomainName from \"./DomainName.ts\";\nimport type * as Plan from \"./Plan.ts\";\nimport * as Principal from \"./Principal.ts\";\nimport * as Resolver from \"./Resolver.ts\";\nimport * as Storage from \"./Storage.ts\";\n\n/**\n * Every piece of evidence carries `values`, what the observer returned for the requirement's name\n * and type (empty when nothing was found, the lookup timed out, or the resolver failed), and\n * `detail`, `null` when the requirement is satisfied and otherwise the mismatch summary or the\n * resolver's error text, so a host can render \"found X, expected Y\".\n */\n// Rows written before these fields existed decode with the empty values.\nconst Values = Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([])));\nconst Detail = Schema.NullOr(Schema.String).pipe(\n Schema.withDecodingDefaultKey(Effect.succeed(null)),\n);\n\nexport class ProviderEvidence extends Schema.TaggedClass<ProviderEvidence>(\n \"@domainkit/Evidence/Provider\",\n)(\"Provider\", {\n provider: Schema.String,\n status: Storage.RequirementStatus,\n values: Values,\n detail: Detail,\n observedAt: Schema.DateTimeUtcFromString,\n}) {}\nexport class PublicDnsEvidence extends Schema.TaggedClass<PublicDnsEvidence>(\n \"@domainkit/Evidence/PublicDns\",\n)(\"PublicDns\", {\n resolver: Schema.String,\n status: Storage.RequirementStatus,\n values: Values,\n detail: Detail,\n observedAt: Schema.DateTimeUtcFromString,\n}) {}\n/** Anything the host knows that DomainKit cannot observe: SES identity status, a CDN cert, ... */\nexport class HostEvidence extends Schema.TaggedClass<HostEvidence>(\"@domainkit/Evidence/Host\")(\n \"Host\",\n {\n source: Schema.String,\n status: Schema.Literals([\"ok\", \"pending\", \"failed\"]),\n label: Schema.String,\n detail: Detail,\n observedAt: Schema.DateTimeUtcFromString,\n },\n) {}\nexport const Evidence = Schema.Union([ProviderEvidence, PublicDnsEvidence, HostEvidence]);\nexport type Evidence = typeof Evidence.Type;\n\nexport interface Requirement {\n /** `requirementKey(record)`: what a host pairs its own row against, by content. */\n readonly key: string;\n readonly operationId: Plan.OperationId | null;\n readonly record: DnsRecord.Model;\n readonly status: Storage.RequirementStatus;\n readonly evidence: ReadonlyArray<Evidence>;\n}\n\nexport interface Readiness {\n readonly domain: string;\n /** `null` for observe-only domains that have no attachment. */\n readonly attachmentId: string | null;\n readonly overall: Storage.Overall;\n readonly requirements: ReadonlyArray<Requirement>;\n readonly host: ReadonlyArray<HostEvidence>;\n readonly checkedAt: DateTime.Utc;\n readonly nextCheckAt: DateTime.Utc | null;\n}\n\ntype Fx<A> = Effect.Effect<A, Errors.DomainKitError, Principal.Service>;\n\nexport interface Interface {\n /**\n * What to observe, in order of precedence: `requirements` when supplied (an attached domain\n * without a provisioning receipt, or a domain with no attachment whose records the customer\n * applies by hand), else the latest provisioning receipt of the domain's attachment (records it\n * applied or found in place). Neither is `InvalidInput`. Provider evidence is added when the\n * attachment's session can be built; public DNS is always observed, and readiness is stored\n * per domain either way.\n */\n readonly observe: (input: {\n readonly domain: string;\n readonly requirements?: ReadonlyArray<DnsRecord.Model>;\n }) => Fx<Readiness>;\n /** Merge host evidence into stored readiness without re-observing DNS. */\n readonly attachEvidence: (input: {\n readonly domain: string;\n readonly evidence: ReadonlyArray<HostEvidence>;\n }) => Fx<Readiness>;\n readonly latest: (domain: string) => Fx<Readiness | null>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@domainkit/Verify\") {}\n\n/**\n * A requirement's identity: the record's type, name, and data, and nothing else. It is what a host\n * pairs its own rows against readiness by, instead of trusting the order of the array.\n * `@domainkit/react`'s `Records.identity` is this function.\n */\nexport const requirementKey = (record: DnsRecord.Model): string =>\n [record._tag, record.name, DnsRecord.data(record)].join(\":\");\n\n/** Counts across a readiness's requirements. `observed` is false when there is no readiness yet. */\nexport interface Summary {\n readonly observed: boolean;\n readonly total: number;\n readonly satisfied: number;\n readonly missing: number;\n readonly mismatch: number;\n readonly unknown: number;\n}\n\n/** The least a value has to carry to be summarised: core `Readiness` and the wire shape both do. */\nexport interface Summarisable {\n readonly requirements: ReadonlyArray<{ readonly status: Storage.RequirementStatus }>;\n}\n\n/**\n * How a readiness stands, as counts. Pure and total: a host renders \"3 of 4 found\" from the stored\n * fact without deciding what an absent readiness means, because `observed` says so.\n */\nexport const summary = (readiness: Summarisable | null): Summary => {\n const statuses = readiness?.requirements.map(({ status }) => status) ?? [];\n const count = (status: Storage.RequirementStatus): number =>\n statuses.filter((candidate) => candidate === status).length;\n return {\n observed: readiness !== null,\n total: statuses.length,\n satisfied: count(\"satisfied\"),\n missing: count(\"missing\"),\n mismatch: count(\"mismatch\"),\n unknown: count(\"unknown\"),\n };\n};\n\nexport interface PolicyShape {\n /** Delay before the next check, given time since the first pending observation. Default ladder: 15s, 1m, 5m, 30m. */\n readonly backoff: (pendingForMs: number) => number;\n /** Which resolvers must agree for `satisfied`: default `any`. */\n readonly quorum: \"any\" | \"all\" | { readonly minimum: number };\n}\nexport const defaults: PolicyShape = {\n backoff: (pendingForMs) =>\n pendingForMs < 60_000\n ? 15_000\n : pendingForMs < 10 * 60_000\n ? 60_000\n : pendingForMs < 60 * 60_000\n ? 5 * 60_000\n : 30 * 60_000,\n quorum: \"any\",\n};\nexport class Policy extends Context.Reference<PolicyShape>(\"@domainkit/Verify/Policy\", {\n defaultValue: () => defaults,\n}) {}\n\n/** Why readiness was written: a DNS observation, or host evidence merged into the stored row. */\nexport type Cause = \"observe\" | \"evidence\";\n\nexport interface ReadinessChanged {\n readonly domain: string;\n readonly readiness: Readiness;\n readonly cause: Cause;\n}\n\nexport interface ObserverShape {\n /**\n * Called once per stored readiness, after the write. A host that projects readiness onto its own\n * rows, wakes a durable job at `nextCheckAt`, or notifies a customer hangs it here instead of\n * mirroring the fact at every call site.\n *\n * Events for one domain are not ordered against each other: two observations that overlap both\n * store, last write wins in `Storage`, and their callbacks can finish in either order. A\n * projection compares `readiness.checkedAt`, which is the moment the row was written, and keeps\n * the later one; `latest` remains the authority.\n */\n readonly readinessChanged: (event: ReadinessChanged) => Effect.Effect<void, unknown>;\n}\n\n/**\n * The host seam for \"DomainKit wrote readiness\". The default does nothing; provide one with\n * `Effect.provideService(Verify.Observer, ...)` or `Layer.succeed(Verify.Observer, ...)` over\n * `DomainKit.layer`, the same way `Policy` is overridden.\n *\n * It runs after `storage.readiness.put` returns, outside any transaction, because `Storage`\n * exposes none. A failure or defect in the observer is logged and swallowed: the observation is\n * already durable, and losing it because a projection failed would make the stored fact depend on\n * the host's side effects. A host that needs the projection to be reliable enqueues durable work\n * here rather than doing the work inline.\n */\nexport class Observer extends Context.Reference<ObserverShape>(\"@domainkit/Verify/Observer\", {\n defaultValue: (): ObserverShape => ({ readinessChanged: () => Effect.void }),\n}) {}\n\n// ---------------------------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------------------------\n\nconst StoredEvidence = Schema.Array(Evidence);\n\ninterface ProviderSide {\n readonly provider: string;\n readonly records: ReadonlyArray<DnsRecord.Observed>;\n}\nconst StoredHost = Schema.Array(HostEvidence);\n\n/** A requirement is satisfied by an exact match; an exclusive one is contradicted by any same-set record. */\nexport const statusAgainst = (\n record: DnsRecord.Model,\n observed: ReadonlyArray<DnsRecord.Observed>,\n): Storage.RequirementStatus => {\n if (observed.some((candidate) => DnsRecord.equals(candidate, record))) return \"satisfied\";\n if (\n record.policy === \"exclusive\" &&\n observed.some((candidate) => DnsRecord.sameSet(candidate, record))\n ) {\n return \"mismatch\";\n }\n return \"missing\";\n};\n\ninterface Observation {\n readonly status: Storage.RequirementStatus;\n readonly values: ReadonlyArray<string>;\n readonly detail: string | null;\n}\n\nconst render = (observed: DnsRecord.Observed): string =>\n observed._tag === \"Opaque\" ? JSON.stringify(observed.raw) : DnsRecord.data(observed);\n\n/** Status plus what the observer holds for the requirement's name and type. */\nconst observation = (\n record: DnsRecord.Model,\n observed: ReadonlyArray<DnsRecord.Observed>,\n): Observation => {\n const status = statusAgainst(record, observed);\n const values = observed.filter((candidate) => DnsRecord.sameSet(candidate, record)).map(render);\n const detail =\n status === \"satisfied\"\n ? null\n : values.length === 0\n ? `no ${record._tag} record at ${record.name}`\n : `expected ${DnsRecord.data(record)}; found ${values.join(\", \")}`;\n return { status, values, detail };\n};\n\nconst combine = (statuses: ReadonlyArray<Storage.RequirementStatus>): Storage.RequirementStatus => {\n const known = statuses.filter((status) => status !== \"unknown\");\n if (known.length === 0) return \"unknown\";\n if (known.includes(\"mismatch\")) return \"mismatch\";\n return known.every((status) => status === \"satisfied\") ? \"satisfied\" : \"missing\";\n};\n\nconst quorumStatus = (\n quorum: PolicyShape[\"quorum\"],\n statuses: ReadonlyArray<Storage.RequirementStatus>,\n): Storage.RequirementStatus => {\n const known = statuses.filter((status) => status !== \"unknown\");\n const satisfied = known.filter((status) => status === \"satisfied\").length;\n const needed =\n quorum === \"any\" ? 1 : quorum === \"all\" ? Math.max(1, known.length) : quorum.minimum;\n if (known.includes(\"mismatch\")) return \"mismatch\";\n if (known.length > 0 && satisfied >= needed) return \"satisfied\";\n return known.length === 0 ? \"unknown\" : \"missing\";\n};\n\nconst overallOf = (\n requirements: ReadonlyArray<{ readonly status: Storage.RequirementStatus }>,\n host: ReadonlyArray<HostEvidence>,\n): Storage.Overall => {\n if (\n requirements.some(({ status }) => status === \"mismatch\") ||\n host.some(({ status }) => status === \"failed\")\n ) {\n return \"failed\";\n }\n const ready =\n requirements.length + host.length > 0 &&\n requirements.every(({ status }) => status === \"satisfied\") &&\n host.every(({ status }) => status === \"ok\");\n return ready ? \"ready\" : \"pending\";\n};\n\n/** The identity of a requirement set: type, name, data, and policy, independent of labels and order. */\nconst requirementSetKey = (requirements: ReadonlyArray<{ readonly record: DnsRecord.Model }>) =>\n requirements\n .map(({ record }) => `${record._tag} ${record.name} ${DnsRecord.data(record)} ${record.policy}`)\n .sort()\n .join(\"\\n\");\n\nexport const make: Effect.Effect<\n Interface,\n never,\n Storage.Service | Connect.Service | Resolver.Service\n> = Effect.gen(function* () {\n const storage = yield* Storage.Service;\n const connect = yield* Connect.Service;\n const resolver = yield* Resolver.Service;\n\n const attachmentFor = (\n input: string,\n ): Fx<{\n readonly domain: DomainName.Model;\n readonly attachment: Storage.Attachment | null;\n }> =>\n Effect.gen(function* () {\n const domain = yield* DomainName.decode(input);\n const attachment = yield* storage.attachments.byDomain(domain);\n return { domain, attachment: Option.getOrNull(attachment) };\n });\n\n const decodeRow = (row: Storage.Readiness): Effect.Effect<Readiness, Errors.DomainKitError> =>\n Effect.gen(function* () {\n const requirements = yield* Effect.forEach(row.requirements, (requirement) =>\n Errors.decode(StoredEvidence, requirement.evidence, \"evidence\").pipe(\n Effect.map((evidence): Requirement => ({\n key: requirementKey(requirement.record),\n operationId: requirement.operationId,\n record: requirement.record,\n status: requirement.status,\n evidence,\n })),\n ),\n );\n const host = yield* Errors.decode(StoredHost, row.host, \"host\");\n return {\n domain: row.domain,\n attachmentId: row.attachmentId,\n overall: row.overall,\n requirements,\n host,\n checkedAt: row.checkedAt,\n nextCheckAt: row.nextCheckAt,\n };\n });\n\n /** Persist readiness, carrying the pending streak forward for the backoff ladder. */\n const store = (input: {\n readonly domain: string;\n readonly attachment: Storage.Attachment | null;\n readonly requirements: ReadonlyArray<Requirement>;\n readonly host: ReadonlyArray<HostEvidence>;\n readonly previous: Option.Option<Storage.Readiness>;\n readonly cause: Cause;\n }): Fx<Readiness> =>\n Effect.gen(function* () {\n const principal = yield* Principal.Service;\n const policy = yield* Policy;\n const observer = yield* Observer;\n const now = yield* DateTime.now;\n const overall = overallOf(input.requirements, input.host);\n const sameRequirements =\n Option.isSome(input.previous) &&\n requirementSetKey(input.previous.value.requirements) ===\n requirementSetKey(input.requirements);\n const pendingSince =\n overall === \"ready\"\n ? null\n : sameRequirements &&\n Option.isSome(input.previous) &&\n input.previous.value.pendingSince !== null\n ? input.previous.value.pendingSince\n : now;\n const nextCheckAt =\n pendingSince === null\n ? null\n : DateTime.addDuration(\n now,\n Duration.millis(\n policy.backoff(DateTime.toEpochMillis(now) - DateTime.toEpochMillis(pendingSince)),\n ),\n );\n const row = new Storage.Readiness({\n domain: input.domain,\n attachmentId: input.attachment?.id ?? null,\n ownerId: principal.ownerId,\n overall,\n requirements: input.requirements.map((requirement) => ({\n operationId: requirement.operationId,\n record: requirement.record,\n status: requirement.status,\n evidence: Schema.encodeSync(StoredEvidence)(requirement.evidence),\n })),\n host: Schema.encodeSync(StoredHost)(input.host),\n pendingSince,\n checkedAt: now,\n nextCheckAt,\n });\n yield* storage.readiness.put(row);\n const readiness: Readiness = {\n domain: row.domain,\n attachmentId: row.attachmentId,\n overall,\n requirements: input.requirements,\n host: input.host,\n checkedAt: now,\n nextCheckAt,\n };\n yield* observer\n .readinessChanged({ domain: row.domain, readiness, cause: input.cause })\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(`Verify.Observer failed for ${row.domain}`, cause),\n ),\n );\n return readiness;\n });\n\n const defaultRequirements = (\n attachment: Storage.Attachment,\n ): Fx<\n ReadonlyArray<{\n readonly operationId: Plan.OperationId | null;\n readonly record: DnsRecord.Model;\n }>\n > =>\n Effect.gen(function* () {\n const latest = yield* storage.attempts.latest(attachment.id, \"provisioning\");\n if (Option.isNone(latest) || latest.value.receipt === null) {\n return yield* Errors.fail(\n new Reason.InvalidInput({\n message: `${attachment.domain} has no provisioning receipt; pass requirements to observe`,\n field: \"requirements\",\n }),\n );\n }\n const receipt = latest.value.receipt;\n const inPlace = new Set(\n receipt.outcomes.flatMap((outcome) =>\n outcome._tag === \"Applied\" || (outcome._tag === \"Skipped\" && outcome.reason === \"noop\")\n ? [outcome.operationId]\n : [],\n ),\n );\n return latest.value.plan.operations\n .filter((operation) => inPlace.has(operation.id))\n .map((operation) => ({ operationId: operation.id, record: operation.record }));\n });\n\n const observe: Interface[\"observe\"] = (input) =>\n Effect.gen(function* () {\n const policy = yield* Policy;\n const { domain, attachment } = yield* attachmentFor(input.domain);\n if (input.requirements === undefined && attachment === null) {\n return yield* Errors.fail(\n new Reason.InvalidInput({\n message: `${domain} is not attached; pass requirements to observe public DNS`,\n field: \"requirements\",\n }),\n );\n }\n const requirements =\n input.requirements === undefined && attachment !== null\n ? yield* defaultRequirements(attachment)\n : (input.requirements ?? []).map((record) => ({ operationId: null, record }));\n if (requirements.length === 0) {\n return yield* Errors.fail(\n new Reason.InvalidInput({\n message: \"Nothing to observe: pass at least one requirement\",\n field: \"requirements\",\n }),\n );\n }\n const now = yield* DateTime.now;\n // Provider readback is evidence when the attachment's session can be built; when it\n // cannot (no attachment, revoked credential, provider outage) public DNS stands alone.\n const providerSide = yield* attachment === null\n ? Effect.succeed(Option.none<ProviderSide>())\n : Effect.gen(function* () {\n const connection = yield* storage.connections.get(attachment.connectionId);\n const authorization = yield* storage.authorizations.get(connection.authorizationId);\n const { session, target } = yield* connect.session(attachment.id);\n const observed = yield* session.dns(target).list(target.zone);\n return Option.some<ProviderSide>({\n provider: authorization.provider,\n records: observed.map(({ record }) => record),\n });\n }).pipe(Effect.catch(() => Effect.succeed(Option.none<ProviderSide>())));\n const observed = yield* Effect.forEach(\n requirements,\n ({ operationId, record }) =>\n Effect.gen(function* () {\n const providerEvidence = Option.isSome(providerSide)\n ? [\n new ProviderEvidence({\n provider: providerSide.value.provider,\n ...observation(record, providerSide.value.records),\n observedAt: now,\n }),\n ]\n : [];\n const outcomes = yield* resolver.resolve(record.name, record._tag);\n const publicEvidence = outcomes.map((outcome) =>\n outcome._tag === \"Answered\"\n ? new PublicDnsEvidence({\n resolver: outcome.answer.resolver,\n ...observation(record, outcome.answer.records),\n observedAt: now,\n })\n : new PublicDnsEvidence({\n resolver: outcome.resolver,\n status: \"unknown\",\n values: [],\n detail:\n outcome._tag === \"TimedOut\"\n ? `${outcome.resolver} timed out`\n : outcome.message,\n observedAt: now,\n }),\n );\n const publicStatus = quorumStatus(\n policy.quorum,\n publicEvidence.map(({ status }) => status),\n );\n const status = combine([\n ...providerEvidence.map((evidence) => evidence.status),\n publicStatus,\n ]);\n return {\n key: requirementKey(record),\n operationId,\n record,\n status,\n evidence: [...providerEvidence, ...publicEvidence],\n } satisfies Requirement;\n }),\n { concurrency: \"unbounded\" },\n );\n const previous = yield* storage.readiness.get(domain);\n const host = Option.isSome(previous)\n ? yield* Errors.decode(StoredHost, previous.value.host, \"host\")\n : [];\n return yield* store({\n domain,\n attachment,\n requirements: observed,\n host,\n previous,\n cause: \"observe\",\n });\n });\n\n const attachEvidence: Interface[\"attachEvidence\"] = (input) =>\n Effect.gen(function* () {\n const { domain, attachment } = yield* attachmentFor(input.domain);\n const previous = yield* storage.readiness.get(domain);\n const current = Option.isSome(previous)\n ? yield* decodeRow(previous.value)\n : {\n requirements: [] as ReadonlyArray<Requirement>,\n host: [] as ReadonlyArray<HostEvidence>,\n };\n const bySource = new Map(current.host.map((evidence) => [evidence.source, evidence]));\n for (const evidence of input.evidence) bySource.set(evidence.source, evidence);\n return yield* store({\n domain,\n attachment,\n requirements: current.requirements,\n host: [...bySource.values()],\n previous,\n cause: \"evidence\",\n });\n });\n\n const latest: Interface[\"latest\"] = (domain) =>\n Effect.gen(function* () {\n const { domain: name } = yield* attachmentFor(domain);\n const stored = yield* storage.readiness.get(name);\n return Option.isSome(stored) ? yield* decodeRow(stored.value) : null;\n });\n\n return { observe, attachEvidence, latest };\n});\n\nexport const layer: Layer.Layer<\n Service,\n never,\n Storage.Service | Connect.Service | Resolver.Service\n> = Layer.effect(Service)(make);\n\nconst accessor =\n <Args extends ReadonlyArray<unknown>, A>(\n pick: (service: Interface) => (...args: Args) => Fx<A>,\n ): ((...args: Args) => Effect.Effect<A, Errors.DomainKitError, Principal.Service | Service>) =>\n (...args) =>\n Effect.flatMap(Service, (service) => pick(service)(...args));\n\nexport const observe = accessor((service) => service.observe);\nexport const attachEvidence = accessor((service) => service.attachEvidence);\nexport const latest = accessor((service) => service.latest);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC,CAAC,KAAK,OAAO,uBAAuB,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;AACjG,MAAM,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC,CAAC,KAC1C,OAAO,uBAAuB,OAAO,QAAQ,IAAI,CAAC,CACpD;AAEA,IAAa,mBAAb,cAAsC,OAAO,YAC3C,8BACF,CAAC,CAAC,YAAY;CACZ,UAAU,OAAO;CACjB,QAAQA;CACR,QAAQ;CACR,QAAQ;CACR,YAAY,OAAO;AACrB,CAAC,CAAC,CAAC,CAAC;AACJ,IAAa,oBAAb,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