domainkit 0.1.0 → 0.1.1

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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"verify-BjrR_4NF.mjs","names":["S","DomainName.Schema","Schema","decode","InvalidInputError","validate","encode","AuthorizationError","DomainName.parse","Error","S","ConnectionStore.Service","Connection.validate","ProviderAuthorizationStore.Service","CredentialStore.Service","S","Schema","decode","InvalidInputError","validate","encode","OAuthStateStore.Service","Secret","ProviderAuthorizationStore.Service","ConnectionStore.Service","CredentialStore.Service","Connection.AuthorizationError","ProviderAuthorization.validate","Connection.validate","InvalidInputError","DnsProvider.Error","S","Schema","decode","InvalidInputError","ProviderAuthorizationStore.Service","ConnectionStore.Service","CredentialStore.Service","ProviderAuthorization.validate","CryptoFailure","Connection.validate","DomainName.parse","InvalidInputError","DomainName.Schema","DomainName.parse","Zones.candidates","Connection.AuthorizationError","Operation","S","DnsRecord.Schema","DnsRecord.Observed","Schema","DomainName.Schema","Authorization","Receipt","InvalidInputError","UnsignedPlan","S","DnsPlan.Operation","DomainName.Schema","DnsRecord.Schema","DnsPlan.Receipt","create","DnsProvider.Service","DomainName.decode","DnsRecord.decode","authorize","validate","apply","makeReceipt","data","DnsRecord.data","DnsRecord.equals","DnsRecord.Observed","authorize","Connection.assertGrant","Connection.AuthorizationError","InvalidInputError","Provisioning.authorize","S","DnsRecord.Schema","DomainName.Schema","Error","DnsProvider.Service","Provisioning.validate","DnsRecord.equals","DomainName.parse","InvalidInputError","make","DnsResolver.Error","layer","DnsResolver.Service","toAsync","DnsResolver.toAsync","DomainName.parse","DomainName.decode","DnsData.parse","DnsOverHttps.make","DnsResolver.Service","DnsResolver.toAsync","DnsRecord.Schema","DnsProvider.Service","DnsResolver.Service","DnsRecord.equals","DnsData.parse","data","DnsRecord.data"],"sources":["../package.json","../src/auth/connection.ts","../src/auth/connection-lifecycle.ts","../src/auth/authorization.ts","../src/plan/canonical-json.ts","../src/auth/oauth.ts","../src/auth/manifest.ts","../src/auth/token.ts","../src/discovery/zones.ts","../src/discovery/selection.ts","../src/plan/types.ts","../src/plan/plan.ts","../src/plan/connection-authorization.ts","../src/plan/deletion.ts","../src/verification/dns-data.ts","../src/verification/doh.ts","../src/verification/cloudflare-doh.ts","../src/verification/verify.ts"],"sourcesContent":["","import { Effect, Schema as S } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport type { Value as Secret } from \"./secret.ts\";\nimport type { OAuthMethod } from \"./manifest.ts\";\nimport type * as ProviderAuthorization from \"./authorization.ts\";\n\nexport const Grant = S.TaggedUnion({\n account: {},\n domains: { domains: S.Array(DomainName.Schema) },\n});\nexport type Grant = typeof Grant.Type;\n\n/** An owner-scoped grant bound to one provider authorization. */\nexport const Schema = S.Struct({\n authorizationId: S.String,\n createdAt: S.DateFromString,\n grant: Grant,\n id: S.String,\n ownerId: S.String,\n});\nexport interface Connection extends S.Schema.Type<typeof Schema> {}\n\nexport const decode = Effect.fn(\"Connection.decode\")((input: unknown) =>\n S.decodeUnknownEffect(Schema)(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport const validate = Effect.fn(\"Connection.validate\")((input: unknown) =>\n S.decodeUnknownEffect(S.toType(Schema))(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport const encode = S.encodeSync(Schema);\n\nexport interface OAuthContinuation {\n readonly clientId: string;\n readonly codeVerifier: Secret;\n readonly expiresAt: Date;\n readonly grant: Grant;\n readonly method: OAuthMethod;\n readonly ownerId: string;\n readonly redirectUri: string;\n readonly stateHash: string;\n readonly subjectId: string;\n}\n\nexport interface StoredCredential {\n readonly accessToken: Secret;\n readonly refreshToken: Secret | null;\n readonly tokenType: string;\n}\n\nexport class AuthorizationError extends S.TaggedError<AuthorizationError>()(\"AuthorizationError\", {\n message: S.String,\n}) {}\n\nexport function assertGrant(\n connection: Connection,\n authorization: ProviderAuthorization.ProviderAuthorization,\n request: {\n readonly capability: ProviderAuthorization.Capability;\n readonly domain: string;\n readonly now?: Date;\n readonly providerId: string;\n },\n): DomainName.DomainName {\n if (\n connection.authorizationId !== authorization.id ||\n authorization.providerId !== request.providerId\n ) {\n throw new AuthorizationError({ message: \"Connection does not grant this provider account\" });\n }\n if (authorization.expiresAt !== null) {\n if (Number.isNaN(authorization.expiresAt.getTime())) {\n throw new AuthorizationError({ message: \"Connection expiration is invalid\" });\n }\n if (authorization.expiresAt <= (request.now ?? new Date())) {\n throw new AuthorizationError({ message: \"Connection has expired\" });\n }\n }\n if (!authorization.capabilities.includes(request.capability)) {\n throw new AuthorizationError({\n message: `Connection lacks the ${request.capability} capability`,\n });\n }\n let domain: DomainName.DomainName;\n try {\n domain = DomainName.parse(request.domain);\n } catch (cause) {\n if (cause instanceof InvalidInputError) throw cause;\n throw new InvalidInputError({\n message: cause instanceof Error ? cause.message : String(cause),\n });\n }\n if (connection.grant._tag === \"domains\" && !connection.grant.domains.includes(domain)) {\n throw new AuthorizationError({ message: \"Connection does not grant this domain\" });\n }\n return domain;\n}\n","import { Effect, Schema as S } from \"effect\";\n\nimport * as ConnectionStore from \"../stores/connection.ts\";\nimport * as CredentialStore from \"../stores/credential.ts\";\nimport * as ProviderAuthorizationStore from \"../stores/authorization.ts\";\nimport type * as Storage from \"../stores/error.ts\";\nimport * as Connection from \"./connection.ts\";\nimport type * as ProviderAuthorization from \"./authorization.ts\";\n\nexport class Error extends S.TaggedError<Error>()(\"ConnectionLifecycleError\", {\n message: S.String,\n}) {}\n\nexport interface DetachResult {\n readonly connection: Connection.Connection;\n readonly remainingBindings: number;\n readonly revokedAuthorization: boolean;\n}\n\n/** Replace the grant on an owner binding after the host has obtained explicit consent. */\nexport const updateGrant = Effect.fn(\"ConnectionLifecycle.updateGrant\")(function* (input: {\n readonly connection: Connection.Connection;\n readonly grant: Connection.Grant;\n}) {\n const connectionStore = yield* ConnectionStore.Service;\n const connection = yield* Connection.validate({ ...input.connection, grant: input.grant });\n yield* connectionStore.put(connection);\n return connection;\n});\n\n/**\n * Detach one owner binding. The final binding invokes provider revocation before deleting local\n * credential and authorization state. The callback keeps provider-specific revocation outside the\n * portable authorization model.\n */\nexport function detach<E, R>(input: {\n readonly connectionId: string;\n readonly revokeAuthorization: (\n authorization: ProviderAuthorization.ProviderAuthorization,\n ) => Effect.Effect<void, E, R>;\n}): Effect.Effect<DetachResult, Error | Storage.Error | E, R | Requirements> {\n return Effect.gen(function* () {\n const authorizationStore = yield* ProviderAuthorizationStore.Service;\n const connectionStore = yield* ConnectionStore.Service;\n const credentialStore = yield* CredentialStore.Service;\n const connection = yield* connectionStore.get(input.connectionId);\n if (connection === null) {\n return yield* new Error({ message: \"Connection binding does not exist\" });\n }\n const bindings = yield* connectionStore.listByAuthorizationId(connection.authorizationId);\n const remainingBindings = bindings.filter(({ id }) => id !== connection.id);\n if (remainingBindings.length > 0) {\n yield* connectionStore.delete(connection.id);\n return {\n connection,\n remainingBindings: remainingBindings.length,\n revokedAuthorization: false,\n };\n }\n\n const authorization = yield* authorizationStore.get(connection.authorizationId);\n if (authorization === null) {\n // A prior attempt may have revoked and removed the authorization before its final binding\n // delete failed. Both local deletes are idempotent, so finish that interrupted cleanup.\n yield* credentialStore.delete(connection.authorizationId);\n yield* connectionStore.delete(connection.id);\n return { connection, remainingBindings: 0, revokedAuthorization: true };\n }\n yield* input.revokeAuthorization(authorization);\n yield* credentialStore.delete(authorization.id);\n yield* authorizationStore.delete(authorization.id);\n yield* connectionStore.delete(connection.id);\n return { connection, remainingBindings: 0, revokedAuthorization: true };\n });\n}\n\nexport type Requirements =\n | ConnectionStore.Service\n | CredentialStore.Service\n | ProviderAuthorizationStore.Service;\n","import { Effect, Schema as S } from \"effect\";\n\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\n\nexport const Capability = S.Literals([\"dns:read\", \"dns:write\"]);\nexport type Capability = typeof Capability.Type;\n\n/** A provider credential authorization shared by one or more owner connections. */\nexport const Schema = S.Struct({\n accountId: S.String,\n capabilities: S.Array(Capability),\n createdAt: S.DateFromString,\n expiresAt: S.NullOr(S.DateFromString),\n id: S.String,\n kind: S.Literals([\"oauth2\", \"token\"]),\n providerId: S.String,\n scopes: S.Array(S.String),\n subjectId: S.String,\n});\nexport interface ProviderAuthorization extends S.Schema.Type<typeof Schema> {}\n\nexport const decode = Effect.fn(\"ProviderAuthorization.decode\")((input: unknown) =>\n S.decodeUnknownEffect(Schema)(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport const validate = Effect.fn(\"ProviderAuthorization.validate\")((input: unknown) =>\n S.decodeUnknownEffect(S.toType(Schema))(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport const encode = S.encodeSync(Schema);\n","import { Crypto, Effect, Layer, PlatformError, Schema } from \"effect\";\n\nexport class CryptoError extends Schema.TaggedError<CryptoError>()(\"CryptoError\", {\n message: Schema.String,\n}) {}\n\nexport type Json =\n | null\n | boolean\n | number\n | string\n | ReadonlyArray<Json>\n | { readonly [key: string]: Json };\n\n/** Deterministic JSON serialization for already schema-encoded protocol values. */\nexport function stringify(value: Json): string {\n if (value === null || typeof value !== \"object\") {\n const encoded = JSON.stringify(value);\n if (encoded === undefined) throw new TypeError(\"Value is not representable as JSON\");\n return encoded;\n }\n if (isJsonArray(value)) return `[${value.map(stringify).join(\",\")}]`;\n return `{${Object.entries(value)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stringify(entry)}`)\n .join(\",\")}}`;\n}\n\nfunction isJsonArray(value: Json): value is ReadonlyArray<Json> {\n return Array.isArray(value);\n}\n\nexport const sha256Text = Effect.fn(\"Digest.sha256Text\")(function* (value: string) {\n const cryptoService = yield* Crypto.Crypto;\n const digest = yield* cryptoService\n .digest(\"SHA-256\", new TextEncoder().encode(value))\n .pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })));\n return [...digest].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n});\n\nexport const sha256Json = Effect.fn(\"Digest.sha256Json\")((value: Json) =>\n Effect.try({\n try: () => stringify(value),\n catch: (cause) =>\n new CryptoError({ message: cause instanceof Error ? cause.message : String(cause) }),\n }).pipe(Effect.flatMap(sha256Text)),\n);\n\nfunction sha256EncodedProgram<S extends Schema.Constraint>(\n schema: S,\n value: S[\"Type\"],\n): Effect.Effect<string, CryptoError, Crypto.Crypto | S[\"EncodingServices\"]> {\n return Schema.encodeEffect(schema)(value).pipe(\n Effect.mapError((cause) => new CryptoError({ message: cause.message })),\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Json)),\n Effect.mapError((cause) => new CryptoError({ message: cause.message })),\n Effect.flatMap(sha256Json),\n );\n}\n\nexport const sha256Encoded = Effect.fn(\"Digest.sha256Encoded\")(sha256EncodedProgram);\n\n/** Portable Web Crypto implementation for hosts that want a ready-made Layer. */\nexport const webCryptoLayer: Layer.Layer<Crypto.Crypto> = Layer.succeed(\n Crypto.Crypto,\n Crypto.make({\n randomBytes: (size) => crypto.getRandomValues(new Uint8Array(size)),\n digest: (algorithm, data) =>\n Effect.tryPromise({\n try: async () => {\n const bytes = new Uint8Array(data.byteLength);\n bytes.set(data);\n return new Uint8Array(await crypto.subtle.digest(algorithm, bytes.buffer));\n },\n catch: (cause) =>\n PlatformError.systemError({\n _tag: \"Unknown\",\n module: \"WebCrypto\",\n method: \"digest\",\n cause,\n }),\n }),\n }),\n);\n","import { Clock, Crypto, Effect } from \"effect\";\nimport * as oauth from \"oauth4webapi\";\n\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport { CryptoError, sha256Text } from \"../plan/canonical-json.ts\";\nimport * as DnsProvider from \"../provider/provider.ts\";\nimport * as ConnectionStore from \"../stores/connection.ts\";\nimport * as CredentialStore from \"../stores/credential.ts\";\nimport * as ProviderAuthorizationStore from \"../stores/authorization.ts\";\nimport type * as Storage from \"../stores/error.ts\";\nimport * as OAuthStateStore from \"../stores/oauth-state.ts\";\nimport * as Connection from \"./connection.ts\";\nimport * as ProviderAuthorization from \"./authorization.ts\";\nimport type * as ProviderAuth from \"./manifest.ts\";\nimport { Value as Secret } from \"./secret.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface BeginInput {\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly grant: Connection.Grant;\n readonly method: ProviderAuth.OAuthMethod;\n readonly ownerId: string;\n readonly redirectUri: string;\n readonly subjectId: string;\n readonly ttlMs?: number;\n}\n\nexport interface OAuthSubjectResolver {\n (\n tokens: oauth.TokenEndpointResponse,\n accessToken: Secret,\n ): Effect.Effect<\n { readonly accountId: string; readonly expiresAt: Date | null },\n InvalidInputError | DnsProvider.Error\n >;\n}\n\nexport type OAuthError =\n | Connection.AuthorizationError\n | CryptoError\n | InvalidInputError\n | DnsProvider.Error\n | Storage.Error;\n\nfunction beginProgram(\n input: BeginInput,\n): Effect.Effect<\n { readonly authorizationUrl: URL },\n CryptoError | Storage.Error,\n OAuthStateStore.Service | Crypto.Crypto\n> {\n return Effect.gen(function* () {\n const stateStore = yield* OAuthStateStore.Service;\n const cryptoService = yield* Crypto.Crypto;\n const now = yield* Clock.currentTimeMillis;\n const state = base64Url(yield* cryptoBytes(cryptoService, 32));\n const codeVerifier = base64Url(yield* cryptoBytes(cryptoService, 32));\n const challenge = base64Url(\n yield* cryptoService\n .digest(\"SHA-256\", new TextEncoder().encode(codeVerifier))\n .pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message }))),\n );\n const stateHash = yield* sha256Text(state);\n const authorizationUrl = new URL(input.method.authorizationServer.authorization_endpoint);\n authorizationUrl.search = new URLSearchParams({\n client_id: input.client.clientId,\n code_challenge: challenge,\n code_challenge_method: \"S256\",\n redirect_uri: input.redirectUri,\n response_type: \"code\",\n scope: input.method.scopes.join(\" \"),\n state,\n }).toString();\n\n yield* stateStore.put({\n clientId: input.client.clientId,\n codeVerifier: Secret.from(codeVerifier),\n expiresAt: new Date(now + (input.ttlMs ?? 10 * 60_000)),\n grant: input.grant,\n method: input.method,\n ownerId: input.ownerId,\n redirectUri: input.redirectUri,\n stateHash,\n subjectId: input.subjectId,\n });\n return { authorizationUrl };\n });\n}\n\nfunction completeProgram(input: {\n readonly callbackUrl: URL;\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly fetch?: Fetch;\n readonly providerId: string;\n readonly resolveSubject: OAuthSubjectResolver;\n}): Effect.Effect<\n {\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly connection: Connection.Connection;\n },\n OAuthError,\n | OAuthStateStore.Service\n | ProviderAuthorizationStore.Service\n | ConnectionStore.Service\n | CredentialStore.Service\n | Crypto.Crypto\n> {\n return Effect.gen(function* () {\n const stateStore = yield* OAuthStateStore.Service;\n const authorizationStore = yield* ProviderAuthorizationStore.Service;\n const connectionStore = yield* ConnectionStore.Service;\n const credentialStore = yield* CredentialStore.Service;\n const cryptoService = yield* Crypto.Crypto;\n const state = input.callbackUrl.searchParams.get(\"state\");\n if (state === null) {\n return yield* new Connection.AuthorizationError({\n message: \"OAuth callback is missing state\",\n });\n }\n const now = yield* Clock.currentTimeMillis;\n const continuation = yield* stateStore.consume(yield* sha256Text(state), new Date(now));\n if (continuation === null) {\n return yield* new Connection.AuthorizationError({\n message: \"OAuth continuation is expired, unknown, or already used\",\n });\n }\n if (continuation.clientId !== input.client.clientId) {\n return yield* new Connection.AuthorizationError({\n message: \"OAuth client does not match the continuation\",\n });\n }\n\n const as = continuation.method.authorizationServer as oauth.AuthorizationServer;\n const client: oauth.Client = { client_id: continuation.clientId };\n const authentication = yield* effectClientAuthentication(continuation.method, input.client);\n const tokens = yield* providerRequest(input.providerId, async (signal) => {\n const callbackParameters = oauth.validateAuthResponse(as, client, input.callbackUrl, state);\n const response = await oauth.authorizationCodeGrantRequest(\n as,\n client,\n authentication,\n callbackParameters,\n continuation.redirectUri,\n continuation.codeVerifier.expose(),\n requestOptions(input.fetch, signal),\n );\n return oauth.processAuthorizationCodeResponse(as, client, response);\n });\n const accessToken = Secret.from(tokens.access_token);\n const subject = yield* input.resolveSubject(tokens, accessToken);\n const existingAuthorization = yield* authorizationStore.findByProviderAccount(\n input.providerId,\n subject.accountId,\n );\n const authorizationId =\n existingAuthorization?.id ??\n (yield* cryptoService.randomUUIDv4.pipe(\n Effect.mapError((cause) => new CryptoError({ message: cause.message })),\n ));\n const authorization = yield* ProviderAuthorization.validate({\n accountId: subject.accountId,\n capabilities: [...continuation.method.capabilities],\n createdAt: existingAuthorization?.createdAt ?? new Date(now),\n expiresAt: subject.expiresAt,\n id: authorizationId,\n kind: \"oauth2\",\n providerId: input.providerId,\n scopes: (tokens.scope ?? continuation.method.scopes.join(\" \")).split(\" \").filter(Boolean),\n subjectId: continuation.subjectId,\n });\n const existingConnection = yield* connectionStore.find(continuation.ownerId, authorization.id);\n const connection = yield* Connection.validate({\n authorizationId: authorization.id,\n createdAt: existingConnection?.createdAt ?? new Date(now),\n grant: continuation.grant,\n id:\n existingConnection?.id ??\n (yield* cryptoService.randomUUIDv4.pipe(\n Effect.mapError((cause) => new CryptoError({ message: cause.message })),\n )),\n ownerId: continuation.ownerId,\n });\n yield* credentialStore.put(authorization.id, {\n accessToken,\n refreshToken: tokens.refresh_token === undefined ? null : Secret.from(tokens.refresh_token),\n tokenType: tokens.token_type,\n });\n yield* authorizationStore.put(authorization);\n yield* connectionStore.put(connection);\n return { authorization, connection };\n });\n}\n\nfunction refreshProgram(input: {\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly fetch?: Fetch;\n readonly method: ProviderAuth.OAuthMethod;\n}): Effect.Effect<void, OAuthError, CredentialStore.Service> {\n return Effect.gen(function* () {\n const credentialStore = yield* CredentialStore.Service;\n const credential = yield* requireCredential(input.authorization.id, credentialStore);\n const refreshToken = credential.refreshToken;\n if (refreshToken === null) {\n return yield* new Connection.AuthorizationError({\n message: \"Connection has no refresh token\",\n });\n }\n const as = input.method.authorizationServer as oauth.AuthorizationServer;\n const client: oauth.Client = { client_id: input.client.clientId };\n const authentication = yield* effectClientAuthentication(input.method, input.client);\n const tokens = yield* providerRequest(input.authorization.providerId, async (signal) => {\n const response = await oauth.refreshTokenGrantRequest(\n as,\n client,\n authentication,\n refreshToken.expose(),\n requestOptions(input.fetch, signal),\n );\n return oauth.processRefreshTokenResponse(as, client, response);\n });\n yield* credentialStore.put(input.authorization.id, {\n accessToken: Secret.from(tokens.access_token),\n refreshToken:\n tokens.refresh_token === undefined\n ? credential.refreshToken\n : Secret.from(tokens.refresh_token),\n tokenType: tokens.token_type,\n });\n });\n}\n\nfunction revokeProgram(input: {\n readonly client: ProviderAuth.OAuthClientConfiguration;\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly fetch?: Fetch;\n readonly method: ProviderAuth.OAuthMethod;\n}): Effect.Effect<void, OAuthError, CredentialStore.Service> {\n return Effect.gen(function* () {\n if (input.method.authorizationServer.revocation_endpoint === undefined) {\n return yield* new Connection.AuthorizationError({\n message: \"Provider does not advertise token revocation\",\n });\n }\n const credentialStore = yield* CredentialStore.Service;\n const credential = yield* requireCredential(input.authorization.id, credentialStore);\n const as = input.method.authorizationServer as oauth.AuthorizationServer;\n const authentication = yield* effectClientAuthentication(input.method, input.client);\n yield* providerRequest(input.authorization.providerId, async (signal) => {\n const response = await oauth.revocationRequest(\n as,\n { client_id: input.client.clientId },\n authentication,\n credential.accessToken.expose(),\n requestOptions(input.fetch, signal),\n );\n await oauth.processRevocationResponse(response);\n });\n yield* credentialStore.delete(input.authorization.id);\n });\n}\n\nfunction effectClientAuthentication(\n method: ProviderAuth.OAuthMethod,\n client: ProviderAuth.OAuthClientConfiguration,\n): Effect.Effect<oauth.ClientAuth, InvalidInputError> {\n return Effect.try({\n try: () => clientAuthentication(method, client),\n catch: (cause) =>\n cause instanceof InvalidInputError\n ? cause\n : new InvalidInputError({ message: \"OAuth client authentication is invalid\" }),\n });\n}\n\nfunction clientAuthentication(\n method: ProviderAuth.OAuthMethod,\n client: ProviderAuth.OAuthClientConfiguration,\n): oauth.ClientAuth {\n switch (method.clientAuth) {\n case \"none\":\n return oauth.None();\n case \"client_secret_basic\":\n if (client.clientSecret === undefined) {\n throw new InvalidInputError({ message: \"Client secret is required\" });\n }\n return oauth.ClientSecretBasic(client.clientSecret.expose());\n case \"client_secret_post\":\n if (client.clientSecret === undefined) {\n throw new InvalidInputError({ message: \"Client secret is required\" });\n }\n return oauth.ClientSecretPost(client.clientSecret.expose());\n }\n}\n\nfunction requestOptions(\n fetchImplementation: Fetch | undefined,\n signal: AbortSignal,\n): oauth.TokenEndpointRequestOptions {\n return fetchImplementation === undefined\n ? { signal }\n : {\n signal,\n [oauth.customFetch]: (url, options) =>\n fetchImplementation(url, { ...options, body: options.body }),\n };\n}\n\nfunction requireCredential(\n connectionId: string,\n store: CredentialStore.Interface,\n): Effect.Effect<Connection.StoredCredential, Connection.AuthorizationError | Storage.Error> {\n return store.get(connectionId).pipe(\n Effect.flatMap((credential) =>\n credential === null\n ? Effect.fail(\n new Connection.AuthorizationError({\n message: \"Connection credentials are unavailable\",\n }),\n )\n : Effect.succeed(credential),\n ),\n );\n}\n\nfunction providerRequest<A>(providerId: string, request: (signal: AbortSignal) => Promise<A>) {\n return Effect.tryPromise({\n try: request,\n catch: (cause) =>\n cause instanceof Connection.AuthorizationError || cause instanceof InvalidInputError\n ? cause\n : new DnsProvider.Error({\n cause,\n message: safeOAuthMessage(cause),\n operation: \"oauthRequest\",\n providerId,\n }),\n });\n}\n\nfunction cryptoBytes(\n cryptoService: Crypto.Crypto,\n size: number,\n): Effect.Effect<Uint8Array, CryptoError> {\n return cryptoService\n .randomBytes(size)\n .pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })));\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nfunction safeOAuthMessage(cause: unknown): string {\n return cause instanceof Error ? cause.name : \"OAuth provider request failed\";\n}\n\nexport const begin = Effect.fn(\"OAuth.begin\")(beginProgram);\nexport const complete = Effect.fn(\"OAuth.complete\")(completeProgram);\nexport const refresh = Effect.fn(\"OAuth.refresh\")(refreshProgram);\nexport const revoke = Effect.fn(\"OAuth.revoke\")(revokeProgram);\n","import { Effect, Schema as S } from \"effect\";\nimport type * as oauth from \"oauth4webapi\";\n\nimport type * as DnsProvider from \"../provider/provider.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport type { Value as Secret } from \"./secret.ts\";\n\nexport const Method = S.TaggedUnion({\n integration: {\n capabilities: S.Array(S.Literals([\"dns:read\", \"dns:write\"])),\n installUrl: S.String,\n tokenEndpoint: S.String,\n },\n oauth2: {\n authorizationServer: S.Struct({\n authorization_endpoint: S.String,\n issuer: S.String,\n revocation_endpoint: S.optionalKey(S.String),\n token_endpoint: S.String,\n }),\n capabilities: S.Array(S.Literals([\"dns:read\", \"dns:write\"])),\n clientAuth: S.Literals([\"none\", \"client_secret_basic\", \"client_secret_post\"]),\n scopes: S.Array(S.String),\n },\n token: {\n capabilities: S.Array(S.Literals([\"dns:read\", \"dns:write\"])),\n instructionsUrl: S.String,\n },\n});\n\nexport const Schema = S.Struct({\n methods: S.Array(Method),\n providerId: S.String,\n});\nexport interface Manifest extends S.Schema.Type<typeof Schema> {}\nexport type OAuthMethod = Extract<Manifest[\"methods\"][number], { readonly _tag: \"oauth2\" }>;\n/** A provider-owned installation flow that returns a credential from a one-time code. */\nexport type IntegrationMethod = Extract<\n Manifest[\"methods\"][number],\n { readonly _tag: \"integration\" }\n>;\n\nexport const decode = Effect.fn(\"ProviderAuth.decode\")((input: unknown) =>\n S.decodeUnknownEffect(Schema)(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport interface OAuthClientConfiguration {\n readonly clientId: string;\n readonly clientSecret?: Secret;\n}\n\nexport interface TokenValidation {\n readonly accountId: string;\n readonly capabilities: ReadonlyArray<\"dns:read\" | \"dns:write\">;\n readonly expiresAt: Date | null;\n readonly scopes: ReadonlyArray<string>;\n}\n\nexport interface OAuthSubjectResolver {\n (\n tokens: oauth.TokenEndpointResponse,\n accessToken: Secret,\n ): Effect.Effect<\n { readonly accountId: string; readonly expiresAt: Date | null },\n DnsProvider.Error\n >;\n}\n\nexport interface AsyncOAuthSubjectResolver {\n (\n tokens: oauth.TokenEndpointResponse,\n accessToken: Secret,\n ): Promise<{ readonly accountId: string; readonly expiresAt: Date | null }>;\n}\n","import { Clock, Crypto, Effect } from \"effect\";\n\nimport { CryptoError, CryptoError as CryptoFailure } from \"../plan/canonical-json.ts\";\nimport type { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport type * as DnsProvider from \"../provider/provider.ts\";\nimport * as ConnectionStore from \"../stores/connection.ts\";\nimport * as CredentialStore from \"../stores/credential.ts\";\nimport * as ProviderAuthorizationStore from \"../stores/authorization.ts\";\nimport type * as Storage from \"../stores/error.ts\";\nimport * as Connection from \"./connection.ts\";\nimport * as ProviderAuthorization from \"./authorization.ts\";\nimport type * as ProviderAuth from \"./manifest.ts\";\nimport { Value as Secret } from \"./secret.ts\";\n\nexport interface Input {\n readonly grant: Connection.Grant;\n readonly ownerId: string;\n readonly providerId: string;\n readonly subjectId: string;\n readonly token: Secret;\n readonly validate: (\n token: Secret,\n ) => Effect.Effect<ProviderAuth.TokenValidation, DnsProvider.Error | InvalidInputError>;\n}\n\nexport const connect = Effect.fn(\"TokenConnection.connect\")(function* (input: Input) {\n const authorizationStore = yield* ProviderAuthorizationStore.Service;\n const connectionStore = yield* ConnectionStore.Service;\n const credentialStore = yield* CredentialStore.Service;\n const cryptoService = yield* Crypto.Crypto;\n const validation = yield* input.validate(input.token);\n const createdAt = new Date(yield* Clock.currentTimeMillis);\n const existingAuthorization = yield* authorizationStore.findByProviderAccount(\n input.providerId,\n validation.accountId,\n );\n const authorization = yield* ProviderAuthorization.validate({\n accountId: validation.accountId,\n capabilities: [...validation.capabilities],\n createdAt: existingAuthorization?.createdAt ?? createdAt,\n expiresAt: validation.expiresAt,\n id:\n existingAuthorization?.id ??\n (yield* cryptoService.randomUUIDv4.pipe(\n Effect.mapError((cause) => new CryptoFailure({ message: cause.message })),\n )),\n kind: \"token\",\n providerId: input.providerId,\n scopes: [...validation.scopes],\n subjectId: input.subjectId,\n });\n const existingConnection = yield* connectionStore.find(input.ownerId, authorization.id);\n const connection = yield* Connection.validate({\n authorizationId: authorization.id,\n createdAt: existingConnection?.createdAt ?? createdAt,\n grant: input.grant,\n id:\n existingConnection?.id ??\n (yield* cryptoService.randomUUIDv4.pipe(\n Effect.mapError((cause) => new CryptoFailure({ message: cause.message })),\n )),\n ownerId: input.ownerId,\n });\n yield* credentialStore.put(authorization.id, {\n accessToken: input.token,\n refreshToken: null,\n tokenType: \"bearer\",\n });\n yield* authorizationStore.put(authorization);\n yield* connectionStore.put(connection);\n return { authorization, connection };\n});\n\nexport type Error = DnsProvider.Error | InvalidInputError | CryptoError | Storage.Error;\n\nexport type Requirements =\n | ProviderAuthorizationStore.Service\n | ConnectionStore.Service\n | CredentialStore.Service\n | Crypto.Crypto;\n","import { getDomain } from \"tldts\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\n\nexport function candidates(input: string): ReadonlyArray<DomainName.DomainName> {\n const domain = DomainName.parse(input);\n const registrable = getDomain(domain, { allowPrivateDomains: true });\n if (registrable === null) {\n throw new InvalidInputError({ message: \"Domain does not have a registrable DNS zone\" });\n }\n const labels = domain.split(\".\");\n const registrableLabels = registrable.split(\".\").length;\n const values: Array<DomainName.DomainName> = [];\n for (let index = 0; index <= labels.length - registrableLabels; index += 1) {\n values.push(DomainName.parse(labels.slice(index).join(\".\")));\n }\n return values;\n}\n","import { Schema } from \"effect\";\n\nimport * as ProviderAuthorization from \"../auth/authorization.ts\";\nimport * as Connection from \"../auth/connection.ts\";\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as Zones from \"./zones.ts\";\n\nexport interface ConnectedZone {\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly connection: Connection.Connection;\n readonly nameservers: ReadonlyArray<string>;\n readonly providerId: string;\n readonly zone: string;\n}\n\nexport const Evidence = Schema.Struct({\n accountId: Schema.String,\n connectionId: Schema.String,\n decisiveNameserverMatch: Schema.Boolean,\n matchedNameservers: Schema.Array(DomainName.Schema),\n providerId: Schema.String,\n zone: DomainName.Schema,\n});\nexport interface Evidence extends Schema.Schema.Type<typeof Evidence> {}\n\nexport const Selection = Schema.TaggedUnion({\n selected: {\n candidate: Evidence,\n evidence: Schema.Array(Evidence),\n reason: Schema.Literals([\"explicit\", \"unique-nameserver-match\"]),\n },\n manual: {\n evidence: Schema.Array(Evidence),\n reason: Schema.Literals([\"ambiguous\", \"unsupported\"]),\n },\n});\nexport type Selection = typeof Selection.Type;\n\nexport function select(input: {\n readonly authoritativeNameservers: ReadonlyArray<string>;\n readonly connectedZones: ReadonlyArray<ConnectedZone>;\n readonly domain: string;\n readonly explicit?: {\n readonly accountId: string;\n readonly providerId: string;\n readonly zone: string;\n };\n readonly now?: Date;\n}): Selection {\n const domain = DomainName.parse(input.domain);\n const zoneCandidates = new Set(Zones.candidates(domain));\n const authoritative = nameserverSet(input.authoritativeNameservers);\n const eligible = input.connectedZones.filter((connected) => {\n if (!zoneCandidates.has(DomainName.parse(connected.zone))) return false;\n try {\n Connection.assertGrant(connected.connection, connected.authorization, {\n capability: \"dns:read\",\n domain,\n ...(input.now === undefined ? {} : { now: input.now }),\n providerId: connected.providerId,\n });\n return true;\n } catch {\n return false;\n }\n });\n const evidence = eligible.map((connected) => evidenceFor(connected, authoritative));\n\n if (input.explicit !== undefined) {\n const explicitZone = DomainName.parse(input.explicit.zone);\n const index = eligible.findIndex(\n (connected) =>\n connected.providerId === input.explicit?.providerId &&\n connected.authorization.accountId === input.explicit.accountId &&\n DomainName.parse(connected.zone) === explicitZone,\n );\n if (index < 0) {\n throw new Connection.AuthorizationError({\n message: \"Explicit provider zone is not connected or granted\",\n });\n }\n const candidate = evidence[index];\n if (candidate === undefined) throw new Error(\"Eligible provider evidence is missing\");\n return { _tag: \"selected\", candidate, evidence, reason: \"explicit\" };\n }\n\n const decisive = evidence.filter(({ decisiveNameserverMatch }) => decisiveNameserverMatch);\n const candidate = decisive[0];\n return decisive.length === 1 && candidate !== undefined\n ? { _tag: \"selected\", candidate, evidence, reason: \"unique-nameserver-match\" }\n : {\n _tag: \"manual\",\n evidence,\n reason: decisive.length > 1 ? \"ambiguous\" : \"unsupported\",\n };\n}\n\nfunction evidenceFor(\n connected: ConnectedZone,\n authoritative: ReadonlyArray<DomainName.DomainName>,\n): Evidence {\n const configured = new Set(nameserverSet(connected.nameservers));\n const matchedNameservers = authoritative.filter((nameserver) => configured.has(nameserver));\n return {\n accountId: connected.authorization.accountId,\n connectionId: connected.connection.id,\n decisiveNameserverMatch:\n authoritative.length > 0 && matchedNameservers.length === authoritative.length,\n matchedNameservers,\n providerId: connected.providerId,\n zone: DomainName.parse(connected.zone),\n };\n}\n\nfunction nameserverSet(nameservers: ReadonlyArray<string>): ReadonlyArray<DomainName.DomainName> {\n return [...new Set(nameservers.map(DomainName.parse))].sort();\n}\n","import { Effect, Schema as S } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\n\nexport const Operation = S.TaggedUnion({\n create: {\n id: S.String,\n requirement: DnsRecord.Schema,\n },\n noop: {\n id: S.String,\n requirement: DnsRecord.Schema,\n ttlDrift: S.Boolean,\n },\n conflict: {\n existing: S.Array(DnsRecord.Observed),\n id: S.String,\n reason: S.String,\n requirement: DnsRecord.Schema,\n },\n});\nexport type Operation = typeof Operation.Type;\n\nexport const Schema = S.Struct({\n digest: S.String,\n operations: S.Array(Operation),\n providerId: S.String,\n version: S.Literal(\"domainkit.dns-plan.v1\"),\n zone: DomainName.Schema,\n});\nexport interface DnsPlan extends S.Schema.Type<typeof Schema> {}\n\nexport const Authorization = S.Struct({\n allowPartial: S.Boolean,\n operationIds: S.Array(S.String),\n planDigest: S.String,\n version: S.Literal(\"domainkit.plan-authorization.v1\"),\n});\nexport interface PlanAuthorization extends S.Schema.Type<typeof Authorization> {}\n\nexport const Receipt = S.Struct({\n appliedAt: S.DateFromString,\n operations: S.Array(\n S.Struct({\n operationId: S.String,\n providerRecordId: S.NullOr(S.String),\n }),\n ),\n planDigest: S.String,\n providerId: S.String,\n status: S.Literals([\"complete\", \"partial\"]),\n version: S.Literal(\"domainkit.apply-receipt.v1\"),\n zone: DomainName.Schema,\n});\nexport interface ApplyReceipt extends S.Schema.Type<typeof Receipt> {}\n\nexport const decode = Effect.fn(\"DnsPlan.decode\")((input: unknown) =>\n S.decodeUnknownEffect(Schema)(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\n\nexport const encode = S.encodeSync(Schema);\nexport const decodeReceipt = Effect.fn(\"DnsPlan.decodeReceipt\")((input: unknown) =>\n S.decodeUnknownEffect(Receipt)(input).pipe(\n Effect.mapError((cause) => new InvalidInputError({ message: cause.message })),\n ),\n);\nexport const encodeReceipt = S.encodeSync(Receipt);\n","import { Cause, Clock, Crypto, Effect, Schema as S } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport * as DnsProvider from \"../provider/provider.ts\";\nimport { CryptoError, sha256Encoded, stringify } from \"./canonical-json.ts\";\nimport * as DnsPlan from \"./types.ts\";\n\nconst UnsignedPlan = S.Struct({\n operations: S.Array(DnsPlan.Operation),\n providerId: S.String,\n version: S.Literal(\"domainkit.dns-plan.v1\"),\n zone: DomainName.Schema,\n});\n\nconst RequirementDigest = S.Struct({ requirement: DnsRecord.Schema });\n\nexport class ConflictError extends S.TaggedError<ConflictError>()(\"PlanConflictError\", {\n operationIds: S.Array(S.String),\n}) {}\n\nexport class AuthorizationError extends S.TaggedError<AuthorizationError>()(\"AuthorizationError\", {\n message: S.String,\n}) {}\n\nexport class StaleError extends S.TaggedError<StaleError>()(\"StalePlanError\", {\n approvedPlanDigest: S.String,\n currentPlanDigest: S.String,\n}) {}\n\nexport class PartialApplyError extends S.TaggedError<PartialApplyError>()(\"PartialApplyError\", {\n causeTag: S.Literals([\n \"CryptoError\",\n \"InvalidInputError\",\n \"Interrupted\",\n \"ProviderError\",\n \"StalePlanError\",\n ]),\n failedOperationId: S.String,\n message: S.String,\n receipt: DnsPlan.Receipt,\n}) {}\n\nexport interface CreateInput {\n readonly requirements: ReadonlyArray<DnsRecord.Encoded | DnsRecord.DnsRecord>;\n readonly zone: string;\n}\n\nexport interface ApplyInput {\n readonly authorization: DnsPlan.PlanAuthorization;\n readonly plan: DnsPlan.DnsPlan;\n}\n\nexport type CreateError = InvalidInputError | DnsProvider.Error | CryptoError;\nexport type AuthorizeError = AuthorizationError | CryptoError;\nexport type ApplyError =\n | InvalidInputError\n | DnsProvider.Error\n | CryptoError\n | AuthorizationError\n | ConflictError\n | StaleError\n | PartialApplyError;\n\n/** Builds a deterministic DNS plan through the provider in the Effect environment. */\nexport const create = Effect.fn(\"Provisioning.create\")(function* (input: CreateInput) {\n const provider = yield* DnsProvider.Service;\n const zone = yield* DomainName.decode(input.zone);\n const requirements = (yield* Effect.forEach(input.requirements, DnsRecord.decode, {\n concurrency: \"unbounded\",\n })).sort(compareRecords);\n const existing = [...(yield* provider.listRecords(zone))].sort(compareRecords);\n const { operations } = yield* Effect.reduce(\n requirements,\n (): PlanningState => ({ operations: [], projected: existing }),\n (state, requirement) =>\n reconcileRequirement(requirement, state.projected).pipe(\n Effect.map((operation) => ({\n operations: [...state.operations, operation],\n projected:\n operation._tag === \"create\"\n ? [...state.projected, operation.requirement].sort(compareRecords)\n : state.projected,\n })),\n ),\n );\n const unsigned: S.Schema.Type<typeof UnsignedPlan> = {\n operations,\n providerId: provider.id,\n version: \"domainkit.dns-plan.v1\",\n zone,\n };\n return { ...unsigned, digest: yield* sha256Encoded(UnsignedPlan, unsigned) };\n});\n\ninterface PlanningState {\n readonly operations: ReadonlyArray<DnsPlan.Operation>;\n readonly projected: ReadonlyArray<DnsRecord.Observed>;\n}\n\n/** Authorizes all or a selected subset of create operations in a digest-bound plan. */\nexport const authorize = Effect.fn(\"Provisioning.authorize\")(function* (\n plan: DnsPlan.DnsPlan,\n operationIds?: ReadonlyArray<string>,\n options: { readonly allowPartial?: boolean } = {},\n) {\n yield* validate(plan);\n const createIds = plan.operations\n .filter((operation) => operation._tag === \"create\")\n .map(({ id }) => id);\n const selected = [...new Set(operationIds ?? createIds)].sort();\n const unknown = selected.filter((id) => !createIds.includes(id));\n if (unknown.length > 0) {\n return yield* new AuthorizationError({\n message: `Unknown operation IDs: ${unknown.join(\", \")}`,\n });\n }\n if (!options.allowPartial && selected.length !== createIds.length) {\n return yield* new AuthorizationError({\n message: \"Partial authorization requires allowPartial\",\n });\n }\n return {\n allowPartial: options.allowPartial ?? false,\n operationIds: selected,\n planDigest: plan.digest,\n version: \"domainkit.plan-authorization.v1\" as const,\n };\n});\n\n/** Applies approved creates sequentially after full and per-operation revalidation. */\nexport const apply = Effect.fn(\"Provisioning.apply\")(function* (input: ApplyInput) {\n const { authorization, plan } = input;\n const provider = yield* DnsProvider.Service;\n yield* validate(plan);\n if (authorization.planDigest !== plan.digest) {\n return yield* new AuthorizationError({\n message: \"Authorization belongs to a different plan\",\n });\n }\n if (provider.id !== plan.providerId) {\n return yield* new AuthorizationError({\n message: \"Provider does not match the approved plan\",\n });\n }\n const conflicts = plan.operations.filter((operation) => operation._tag === \"conflict\");\n if (conflicts.length > 0) {\n return yield* new ConflictError({\n operationIds: conflicts.map(({ id }) => id),\n });\n }\n\n const creates = plan.operations.filter(DnsPlan.Operation.guards.create);\n const approved = new Set(authorization.operationIds);\n const unknown = authorization.operationIds.filter(\n (id) => !creates.some((operation) => operation.id === id),\n );\n if (unknown.length > 0) {\n return yield* new AuthorizationError({\n message: `Authorization contains unknown operations: ${unknown.join(\", \")}`,\n });\n }\n if (!authorization.allowPartial && creates.some(({ id }) => !approved.has(id))) {\n return yield* new AuthorizationError({\n message: \"Authorization does not cover every create operation\",\n });\n }\n\n const currentPlan = yield* create({\n requirements: plan.operations.map(({ requirement }) => requirement),\n zone: plan.zone,\n });\n if (currentPlan.digest !== plan.digest) {\n return yield* new StaleError({\n approvedPlanDigest: plan.digest,\n currentPlanDigest: currentPlan.digest,\n });\n }\n\n const operations: Array<{\n operationId: string;\n providerRecordId: string | null;\n }> = [];\n for (const operation of creates) {\n if (!approved.has(operation.id)) continue;\n yield* Effect.gen(function* () {\n yield* assertStillCreatable(plan, operation);\n const result = yield* provider.createRecord(plan.zone, operation.requirement);\n operations.push({\n operationId: operation.id,\n providerRecordId: result.providerRecordId,\n });\n }).pipe(\n Effect.catch((failure): Effect.Effect<never, CreateError | StaleError | PartialApplyError> =>\n operations.length === 0\n ? Effect.fail(failure)\n : makeReceipt(input, operations, \"partial\").pipe(\n Effect.flatMap((receipt) =>\n Effect.fail(\n new PartialApplyError({\n causeTag: failure._tag,\n failedOperationId: operation.id,\n message: failureMessage(failure),\n receipt,\n }),\n ),\n ),\n ),\n ),\n Effect.catchCause((cause) => {\n if (!Cause.hasInterruptsOnly(cause) || operations.length === 0) {\n return Effect.failCause(cause);\n }\n return makeReceipt(input, operations, \"partial\").pipe(\n Effect.flatMap((receipt) =>\n Effect.fail(\n new PartialApplyError({\n causeTag: \"Interrupted\",\n failedOperationId: operation.id,\n message: \"DNS apply was interrupted after confirmed writes\",\n receipt,\n }),\n ),\n ),\n );\n }),\n );\n }\n return yield* makeReceipt(input, operations, \"complete\");\n});\n\nexport function renderManualInstructions(plan: DnsPlan.DnsPlan): ReadonlyArray<string> {\n return plan.operations.map((operation) => {\n const record = operation.requirement;\n const data = Object.entries(DnsRecord.data(record))\n .map(([key, value]) => `${key}=${value}`)\n .join(\" \");\n return `${operation._tag.toUpperCase()} ${record._tag} ${record.name} ${data}`.trim();\n });\n}\n\nfunction makeReceipt(\n input: ApplyInput,\n operations: ReadonlyArray<{\n readonly operationId: string;\n readonly providerRecordId: string | null;\n }>,\n status: \"complete\" | \"partial\",\n): Effect.Effect<DnsPlan.ApplyReceipt> {\n return Clock.currentTimeMillis.pipe(\n Effect.map((now) => ({\n appliedAt: new Date(now),\n operations,\n planDigest: input.plan.digest,\n providerId: input.plan.providerId,\n status,\n version: \"domainkit.apply-receipt.v1\" as const,\n zone: input.plan.zone,\n })),\n );\n}\n\nfunction assertStillCreatable(\n plan: DnsPlan.DnsPlan,\n operation: Extract<DnsPlan.Operation, { readonly _tag: \"create\" }>,\n): Effect.Effect<void, CreateError | StaleError, DnsProvider.Service | Crypto.Crypto> {\n return create({\n requirements: [operation.requirement],\n zone: plan.zone,\n }).pipe(\n Effect.flatMap((currentPlan) => {\n const currentOperation = currentPlan.operations[0];\n return currentOperation?._tag === \"create\" && currentOperation.id === operation.id\n ? Effect.void\n : Effect.fail(\n new StaleError({\n approvedPlanDigest: plan.digest,\n currentPlanDigest: currentPlan.digest,\n }),\n );\n }),\n );\n}\n\nfunction reconcileRequirement(\n requirement: DnsRecord.DnsRecord,\n allExisting: ReadonlyArray<DnsRecord.Observed>,\n): Effect.Effect<DnsPlan.Operation, CryptoError, Crypto.Crypto> {\n return Effect.gen(function* () {\n const sameName = allExisting.filter((record) => record.name === requirement.name);\n const sameSet = sameName.filter(\n (record): record is DnsRecord.DnsRecord =>\n record._tag !== \"Opaque\" && record._tag === requirement._tag,\n );\n const exact = sameSet.find((record) => DnsRecord.equals(record, requirement));\n const id = yield* sha256Encoded(RequirementDigest, { requirement });\n if (exact !== undefined) {\n return {\n _tag: \"noop\",\n id,\n requirement,\n ttlDrift: exact.ttl !== requirement.ttl,\n };\n }\n const cnameConflict =\n sameName.length > 0 &&\n (requirement._tag === \"CNAME\" || sameName.some((record) => record._tag === \"CNAME\"));\n if (cnameConflict) {\n return {\n _tag: \"conflict\",\n existing: sameName,\n id,\n reason: \"CNAME records cannot coexist with other records at the same name\",\n requirement,\n };\n }\n if (\n sameSet.length > 0 &&\n (requirement.policy === \"exclusive\" || sameSet.some(({ policy }) => policy === \"exclusive\"))\n ) {\n return {\n _tag: \"conflict\",\n existing: sameSet,\n id,\n reason: \"The exclusive record set already contains incompatible data\",\n requirement,\n };\n }\n return { _tag: \"create\", id, requirement };\n });\n}\n\nexport function validate(\n plan: DnsPlan.DnsPlan,\n): Effect.Effect<void, AuthorizeError, Crypto.Crypto> {\n const unsigned: S.Schema.Type<typeof UnsignedPlan> = {\n operations: plan.operations,\n providerId: plan.providerId,\n version: plan.version,\n zone: plan.zone,\n };\n return sha256Encoded(UnsignedPlan, unsigned).pipe(\n Effect.flatMap((digest) =>\n digest === plan.digest\n ? Effect.void\n : Effect.fail(\n new AuthorizationError({\n message: \"Plan digest does not match its contents\",\n }),\n ),\n ),\n );\n}\n\nfunction failureMessage(failure: CreateError | StaleError): string {\n return failure._tag === \"StalePlanError\"\n ? \"DNS state changed while applying the approved plan\"\n : failure.message;\n}\n\nfunction compareRecords(left: DnsRecord.Observed, right: DnsRecord.Observed): number {\n const encode = S.encodeSync(DnsRecord.Observed);\n const toJson = S.decodeUnknownSync(S.Json);\n const leftJson = stringify(toJson(encode(left)));\n const rightJson = stringify(toJson(encode(right)));\n return leftJson < rightJson ? -1 : leftJson > rightJson ? 1 : 0;\n}\n","import { Crypto, Effect } from \"effect\";\n\nimport * as Connection from \"../auth/connection.ts\";\nimport * as ProviderAuthorization from \"../auth/authorization.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport { CryptoError } from \"./canonical-json.ts\";\nimport * as Provisioning from \"./plan.ts\";\nimport type * as DnsPlan from \"./types.ts\";\n\nexport const authorize = Effect.fn(\"ConnectionAuthorization.authorize\")(function* (input: {\n readonly allowPartial?: boolean;\n readonly authorization: ProviderAuthorization.ProviderAuthorization;\n readonly connection: Connection.Connection;\n readonly domain: string;\n readonly operationIds?: ReadonlyArray<string>;\n readonly plan: DnsPlan.DnsPlan;\n}) {\n const domain = yield* Effect.try({\n try: () =>\n Connection.assertGrant(input.connection, input.authorization, {\n capability: \"dns:write\",\n domain: input.domain,\n providerId: input.plan.providerId,\n }),\n catch: (cause) =>\n cause instanceof Connection.AuthorizationError || cause instanceof InvalidInputError\n ? cause\n : new Connection.AuthorizationError({ message: \"Connection grant is invalid\" }),\n });\n const authorization = yield* Provisioning.authorize(\n input.plan,\n input.operationIds,\n input.allowPartial === undefined ? {} : { allowPartial: input.allowPartial },\n );\n const selected = new Set(authorization.operationIds);\n const outsideGrant = input.plan.operations.filter(\n (operation) =>\n operation._tag === \"create\" &&\n selected.has(operation.id) &&\n operation.requirement.name !== domain &&\n !operation.requirement.name.endsWith(`.${domain}`),\n );\n if (outsideGrant.length > 0) {\n return yield* new Connection.AuthorizationError({\n message: `Plan operations are outside the granted domain ${domain}`,\n });\n }\n return authorization;\n});\n\nexport type Error = Connection.AuthorizationError | InvalidInputError | CryptoError;\nexport type Requirements = Crypto.Crypto;\n","import { Clock, Crypto, Effect, Schema as S } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\nimport * as DnsProvider from \"../provider/provider.ts\";\nimport { CryptoError, sha256Encoded } from \"./canonical-json.ts\";\nimport * as Provisioning from \"./plan.ts\";\nimport * as DnsPlan from \"./types.ts\";\n\nexport const Operation = S.Struct({\n id: S.String,\n providerRecordId: S.String,\n record: DnsRecord.Schema,\n});\nexport interface Operation extends S.Schema.Type<typeof Operation> {}\n\nconst UnsignedPlan = S.Struct({\n createdAt: S.DateFromString,\n expiresAt: S.DateFromString,\n operations: S.Array(Operation),\n providerId: S.String,\n sourcePlanDigest: S.String,\n version: S.Literal(\"domainkit.deletion-plan.v1\"),\n zone: DomainName.Schema,\n});\n\nexport const Plan = S.Struct({ ...UnsignedPlan.fields, digest: S.String });\nexport interface Plan extends S.Schema.Type<typeof Plan> {}\n\nexport const Authorization = S.Struct({\n operationIds: S.Array(S.String),\n planDigest: S.String,\n version: S.Literal(\"domainkit.deletion-authorization.v1\"),\n});\nexport interface Authorization extends S.Schema.Type<typeof Authorization> {}\n\nexport const Receipt = S.Struct({\n deletedAt: S.DateFromString,\n operations: S.Array(S.Struct({ operationId: S.String, providerRecordId: S.String })),\n planDigest: S.String,\n providerId: S.String,\n status: S.Literals([\"complete\", \"partial\"]),\n version: S.Literal(\"domainkit.deletion-receipt.v1\"),\n zone: DomainName.Schema,\n});\nexport interface Receipt extends S.Schema.Type<typeof Receipt> {}\n\nexport class Error extends S.TaggedError<Error>()(\"UnsafeDeletionError\", {\n message: S.String,\n operationId: S.optionalKey(S.String),\n}) {}\n\nexport class PartialError extends S.TaggedError<PartialError>()(\"PartialDeletionError\", {\n failedOperationId: S.String,\n message: S.String,\n receipt: Receipt,\n}) {}\n\nexport interface CreateInput {\n readonly plan: DnsPlan.DnsPlan;\n readonly receipt: DnsPlan.ApplyReceipt;\n readonly ttlMs?: number;\n}\n\n/** Build a fresh deletion plan only from records proven by a prior create receipt. */\nexport const create = Effect.fn(\"Deletion.create\")(function* (input: CreateInput) {\n const provider = yield* DnsProvider.Service;\n yield* Provisioning.validate(input.plan);\n if (\n input.receipt.planDigest !== input.plan.digest ||\n input.receipt.providerId !== input.plan.providerId ||\n input.receipt.zone !== input.plan.zone\n ) {\n return yield* new Error({ message: \"Create receipt does not belong to the source plan\" });\n }\n if (provider.id !== input.plan.providerId) {\n return yield* new Error({ message: \"Provider does not match the source receipt\" });\n }\n const operations = yield* Effect.forEach(input.receipt.operations, (applied) =>\n Effect.gen(function* () {\n const source = input.plan.operations.find(\n (operation) => operation._tag === \"create\" && operation.id === applied.operationId,\n );\n if (source === undefined || source._tag !== \"create\") {\n return yield* new Error({\n message: \"Receipt operation is not a created source record\",\n operationId: applied.operationId,\n });\n }\n if (applied.providerRecordId === null) {\n return yield* new Error({\n message: \"Provider record ID is required for safe deletion\",\n operationId: applied.operationId,\n });\n }\n yield* assertExact(\n provider,\n input.plan.zone,\n applied.providerRecordId,\n source.requirement,\n source.id,\n );\n return {\n id: source.id,\n providerRecordId: applied.providerRecordId,\n record: source.requirement,\n };\n }),\n );\n const now = yield* Clock.currentTimeMillis;\n const unsigned: S.Schema.Type<typeof UnsignedPlan> = {\n createdAt: new Date(now),\n expiresAt: new Date(now + (input.ttlMs ?? 15 * 60_000)),\n operations,\n providerId: input.plan.providerId,\n sourcePlanDigest: input.plan.digest,\n version: \"domainkit.deletion-plan.v1\",\n zone: input.plan.zone,\n };\n return { ...unsigned, digest: yield* sha256Encoded(UnsignedPlan, unsigned) };\n});\n\n/** Produce a separate digest-bound consent artifact for destructive operations. */\nexport const authorize = Effect.fn(\"Deletion.authorize\")(function* (\n plan: Plan,\n operationIds?: ReadonlyArray<string>,\n) {\n yield* validate(plan);\n const selected = [...new Set(operationIds ?? plan.operations.map(({ id }) => id))].sort();\n const unknown = selected.filter(\n (id) => !plan.operations.some((operation) => operation.id === id),\n );\n if (unknown.length > 0) {\n return yield* new Error({ message: `Unknown deletion operation IDs: ${unknown.join(\", \")}` });\n }\n return {\n operationIds: selected,\n planDigest: plan.digest,\n version: \"domainkit.deletion-authorization.v1\" as const,\n };\n});\n\n/** Re-read every approved record before the first delete, then delete by provider record ID. */\nexport const apply = Effect.fn(\"Deletion.apply\")(function* (input: {\n readonly authorization: Authorization;\n readonly plan: Plan;\n readonly priorReceipt?: Receipt;\n}) {\n const provider = yield* DnsProvider.Service;\n yield* validate(input.plan);\n if (input.authorization.planDigest !== input.plan.digest) {\n return yield* new Error({ message: \"Deletion authorization belongs to a different plan\" });\n }\n if (provider.id !== input.plan.providerId) {\n return yield* new Error({ message: \"Provider does not match the deletion plan\" });\n }\n const now = yield* Clock.currentTimeMillis;\n if (input.plan.expiresAt <= new Date(now)) {\n return yield* new Error({ message: \"Deletion plan has expired\" });\n }\n const selected = input.plan.operations.filter(({ id }) =>\n input.authorization.operationIds.includes(id),\n );\n if (selected.length !== input.authorization.operationIds.length) {\n return yield* new Error({ message: \"Deletion authorization contains unknown operations\" });\n }\n const previouslyDeleted = yield* validatePriorReceipt(input.plan, input.priorReceipt);\n const completedIds = new Set(previouslyDeleted.map(({ operationId }) => operationId));\n if (\n previouslyDeleted.some(\n ({ operationId }) => !input.authorization.operationIds.includes(operationId),\n )\n ) {\n return yield* new Error({ message: \"Prior receipt contains an unauthorized operation\" });\n }\n const remaining = selected.filter(({ id }) => !completedIds.has(id));\n yield* Effect.forEach(remaining, (operation) =>\n assertExact(\n provider,\n input.plan.zone,\n operation.providerRecordId,\n operation.record,\n operation.id,\n ),\n );\n\n const deleted: Array<{ operationId: string; providerRecordId: string }> = [...previouslyDeleted];\n for (const operation of remaining) {\n const failure = yield* Effect.gen(function* () {\n yield* assertExact(\n provider,\n input.plan.zone,\n operation.providerRecordId,\n operation.record,\n operation.id,\n );\n yield* provider.deleteRecord(input.plan.zone, operation.providerRecordId);\n deleted.push({ operationId: operation.id, providerRecordId: operation.providerRecordId });\n }).pipe(Effect.match({ onFailure: (cause) => cause, onSuccess: () => null }));\n if (failure !== null) {\n if (deleted.length === 0) return yield* failure;\n return yield* new PartialError({\n failedOperationId: operation.id,\n message: failure.message,\n receipt: yield* makeReceipt(input.plan, deleted, \"partial\"),\n });\n }\n }\n return yield* makeReceipt(input.plan, deleted, \"complete\");\n});\n\nexport function validate(plan: Plan): Effect.Effect<void, Error | CryptoError, Crypto.Crypto> {\n const unsigned: S.Schema.Type<typeof UnsignedPlan> = {\n createdAt: plan.createdAt,\n expiresAt: plan.expiresAt,\n operations: plan.operations,\n providerId: plan.providerId,\n sourcePlanDigest: plan.sourcePlanDigest,\n version: plan.version,\n zone: plan.zone,\n };\n return sha256Encoded(UnsignedPlan, unsigned).pipe(\n Effect.flatMap((digest) =>\n digest === plan.digest\n ? Effect.void\n : Effect.fail(new Error({ message: \"Deletion plan digest does not match its contents\" })),\n ),\n );\n}\n\nfunction validatePriorReceipt(\n plan: Plan,\n receipt: Receipt | undefined,\n): Effect.Effect<ReadonlyArray<{ operationId: string; providerRecordId: string }>, Error> {\n if (receipt === undefined) return Effect.succeed([]);\n if (\n receipt.planDigest !== plan.digest ||\n receipt.providerId !== plan.providerId ||\n receipt.zone !== plan.zone ||\n receipt.status !== \"partial\"\n ) {\n return Effect.fail(\n new Error({ message: \"Prior receipt does not belong to this deletion plan\" }),\n );\n }\n for (const completed of receipt.operations) {\n const operation = plan.operations.find(({ id }) => id === completed.operationId);\n if (operation === undefined || operation.providerRecordId !== completed.providerRecordId) {\n return Effect.fail(\n new Error({ message: \"Prior receipt operation does not match the deletion plan\" }),\n );\n }\n }\n return Effect.succeed([...receipt.operations]);\n}\n\nfunction assertExact(\n provider: DnsProvider.Interface,\n zone: DomainName.DomainName,\n providerRecordId: string,\n expected: DnsRecord.DnsRecord,\n operationId: string,\n): Effect.Effect<void, Error | DnsProvider.Error> {\n return provider.getRecord(zone, providerRecordId).pipe(\n Effect.flatMap((observed) =>\n observed !== null && observed._tag !== \"Opaque\" && DnsRecord.equals(observed, expected)\n ? Effect.void\n : Effect.fail(\n new Error({\n message:\n observed === null\n ? \"Created record no longer exists\"\n : \"Created record content no longer matches its receipt\",\n operationId,\n }),\n ),\n ),\n );\n}\n\nfunction makeReceipt(\n plan: Plan,\n operations: ReadonlyArray<{ readonly operationId: string; readonly providerRecordId: string }>,\n status: \"complete\" | \"partial\",\n): Effect.Effect<Receipt> {\n return Clock.currentTimeMillis.pipe(\n Effect.map((now) => ({\n deletedAt: new Date(now),\n operations,\n planDigest: plan.digest,\n providerId: plan.providerId,\n status,\n version: \"domainkit.deletion-receipt.v1\" as const,\n zone: plan.zone,\n })),\n );\n}\n\nexport type CreateError =\n | Error\n | InvalidInputError\n | Provisioning.AuthorizationError\n | DnsProvider.Error\n | CryptoError;\nexport type ApplyError = Error | PartialError | DnsProvider.Error | CryptoError;\nexport type Requirements = DnsProvider.Service | Crypto.Crypto;\n","import { Effect, Schema, SchemaIssue, SchemaTransformation } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport type * as DnsRecord from \"../domain/dns-record.ts\";\nimport { Error as InvalidInputError } from \"../invalid-input.ts\";\n\nconst CanonicalAddress = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transform({\n decode: (value) => value.trim().toLowerCase(),\n encode: (value) => value,\n }),\n ),\n);\n\nconst CanonicalDomain = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transformOrFail({\n decode: (value, options) =>\n Effect.try({\n try: () => DomainName.parse(value).toString(),\n catch: (cause) =>\n new SchemaIssue.InvalidValue(\n { message: cause instanceof Error ? cause.message : String(cause) },\n value,\n options,\n ),\n }),\n encode: (value) => Effect.succeed(value),\n }),\n ),\n);\n\nconst CanonicalMx = tokenizedDomain(2, 1);\nconst CanonicalSrv = tokenizedDomain(4, 3);\n\nconst CanonicalTxt = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transform({\n decode: (value) => {\n const trimmed = value.trim();\n const chunks = [...trimmed.matchAll(/\"((?:\\\\.|[^\"])*)\"/g)];\n return chunks.length === 0\n ? trimmed\n : chunks\n .map((match) => (match[1] ?? \"\").replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\"))\n .join(\"\");\n },\n encode: (value) => value,\n }),\n ),\n);\n\nconst CanonicalCaa = Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transform({\n decode: (value) => value.trim().replace(/\\s+\"([\\s\\S]*)\"$/, \" $1\"),\n encode: (value) => value,\n }),\n ),\n);\n\nexport function parse(type: DnsRecord.Type, input: unknown): string {\n const schema = (() => {\n switch (type) {\n case \"A\":\n case \"AAAA\":\n return CanonicalAddress;\n case \"CNAME\":\n case \"NS\":\n return CanonicalDomain;\n case \"MX\":\n return CanonicalMx;\n case \"SRV\":\n return CanonicalSrv;\n case \"TXT\":\n return CanonicalTxt;\n case \"CAA\":\n return CanonicalCaa;\n }\n })();\n try {\n return Schema.decodeUnknownSync(schema)(input);\n } catch (cause) {\n throw new InvalidInputError({\n message: cause instanceof Error ? cause.message : String(cause),\n });\n }\n}\n\nfunction tokenizedDomain(length: number, domainIndex: number) {\n return Schema.String.pipe(\n Schema.decodeTo(\n Schema.String,\n SchemaTransformation.transformOrFail({\n decode: (value, options) =>\n Effect.try({\n try: () => {\n const parts = value.trim().split(/\\s+/);\n if (parts.length !== length)\n throw new Error(\"DNS record data has an invalid field count\");\n const domain = parts[domainIndex];\n if (domain === undefined) throw new Error(\"DNS record target is missing\");\n parts[domainIndex] = DomainName.parse(domain);\n return parts.join(\" \");\n },\n catch: (cause) =>\n new SchemaIssue.InvalidValue(\n { message: cause instanceof Error ? cause.message : String(cause) },\n value,\n options,\n ),\n }),\n encode: (value) => Effect.succeed(value),\n }),\n ),\n );\n}\n","import * as DnsPacket from \"@leichtgewicht/dns-packet\";\nimport { Effect, Layer } from \"effect\";\n\nimport * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport * as DnsData from \"./dns-data.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface Options {\n readonly endpoint: string;\n readonly fetch?: Fetch;\n readonly timeoutMs?: number;\n}\n\nexport function make(options: Options): DnsResolver.Interface {\n const fetch = options.fetch ?? globalThis.fetch;\n const timeoutMs = options.timeoutMs ?? 5_000;\n return {\n resolve: Effect.fn(\"DnsOverHttps.resolve\")((query) =>\n Effect.tryPromise({\n try: (effectSignal) =>\n request({ effectSignal, fetch, query, timeoutMs, endpoint: options.endpoint }),\n catch: (cause) =>\n cause instanceof DnsResolver.Error\n ? cause\n : new DnsResolver.Error({\n cause,\n message: cause instanceof Error ? cause.message : \"DNS resolution failed\",\n reason: \"transport\",\n }),\n }).pipe(Effect.flatMap((message) => decodeResolution(query, message))),\n ),\n };\n}\n\nexport const layer = (options: Options): Layer.Layer<DnsResolver.Service> =>\n Layer.succeed(DnsResolver.Service, make(options));\n\nexport const toAsync = (options: Options): DnsResolver.AsyncInterface =>\n DnsResolver.toAsync(make(options));\n\nfunction decodeResolution(\n query: DnsResolver.Query,\n message: Uint8Array,\n): Effect.Effect<DnsResolver.Resolution, DnsResolver.Error> {\n return Effect.try({\n try: () => DnsPacket.decode(message),\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: \"DoH returned an invalid DNS message\",\n reason: \"response\",\n }),\n }).pipe(\n Effect.flatMap((packet) => validatePacket(query, packet)),\n Effect.flatMap(decodePacket),\n );\n}\n\nfunction decodePacket(\n packet: DnsPacket.Packet,\n): Effect.Effect<DnsResolver.Resolution, DnsResolver.Error> {\n if (packet.rcode === \"NXDOMAIN\") {\n return Effect.succeed({ _tag: \"nodata\" });\n }\n if (packet.rcode !== \"NOERROR\") {\n return Effect.fail(\n new DnsResolver.Error({\n message: `DNS resolver returned ${packet.rcode ?? \"an unknown response code\"}`,\n reason: \"response\",\n }),\n );\n }\n if (packet.answers === undefined || packet.answers.length === 0) {\n return Effect.succeed({ _tag: \"nodata\" });\n }\n return Effect.forEach(packet.answers, decodeAnswer, { concurrency: \"unbounded\" }).pipe(\n Effect.map((answers): DnsResolver.Resolution => {\n const supportedAnswers = answers.filter((answer) => answer !== null);\n return supportedAnswers.length === 0\n ? { _tag: \"nodata\" }\n : { _tag: \"answer\", answers: supportedAnswers };\n }),\n );\n}\n\nfunction validatePacket(\n query: DnsResolver.Query,\n packet: DnsPacket.Packet,\n): Effect.Effect<DnsPacket.Packet, DnsResolver.Error> {\n return Effect.try({\n try: () => {\n if (packet.type !== \"response\") throw new Error(\"DoH returned a DNS query\");\n if (packet.id !== 0) throw new Error(\"DoH response used an unexpected message ID\");\n if (packet.flag_tc) throw new Error(\"DoH returned a truncated DNS response\");\n const questions = packet.questions ?? [];\n if (questions.length !== 1) throw new Error(\"DoH returned an unexpected question count\");\n const question = questions[0];\n if (question === undefined) throw new Error(\"DoH response omitted the DNS question\");\n if (\n question.class !== \"IN\" ||\n question.type !== query.type ||\n DomainName.parse(question.name) !== query.name\n ) {\n throw new Error(\"DoH response did not match the DNS question\");\n }\n return packet;\n },\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: cause instanceof Error ? cause.message : \"DoH returned an invalid DNS response\",\n reason: \"response\",\n }),\n });\n}\n\nfunction decodeAnswer(\n answer: DnsPacket.Answer,\n): Effect.Effect<DnsResolver.Answer | null, DnsResolver.Error> {\n return Effect.gen(function* () {\n if (answer.class !== \"IN\") return null;\n const decoded = yield* Effect.try({\n try: () => answerData(answer),\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: \"DoH returned invalid DNS record data\",\n reason: \"response\",\n }),\n });\n if (decoded === undefined) return null;\n const name = yield* DomainName.decode(answer.name);\n const data = yield* Effect.try({\n try: () => DnsData.parse(decoded.type, decoded.data),\n catch: (cause) =>\n new DnsResolver.Error({\n cause,\n message: \"DoH returned invalid DNS record data\",\n reason: \"response\",\n }),\n });\n if (answer.ttl === undefined) {\n return yield* new DnsResolver.Error({\n message: \"DoH response omitted the DNS record TTL\",\n reason: \"response\",\n });\n }\n return { data, name, ttl: answer.ttl, type: decoded.type };\n }).pipe(\n Effect.mapError((cause) =>\n cause instanceof DnsResolver.Error\n ? cause\n : new DnsResolver.Error({ cause, message: cause.message, reason: \"response\" }),\n ),\n );\n}\n\nfunction answerData(\n answer: DnsPacket.Answer,\n): { readonly data: string; readonly type: DnsRecord.Type } | undefined {\n switch (answer.type) {\n case \"A\":\n case \"AAAA\":\n case \"CNAME\":\n case \"NS\":\n return { data: answer.data, type: answer.type };\n case \"CAA\":\n return {\n data: `${answer.data.flags ?? 0} ${answer.data.tag} ${answer.data.value}`,\n type: answer.type,\n };\n case \"MX\":\n return {\n data: `${requiredNumber(answer.data.preference, \"MX preference\")} ${answer.data.exchange}`,\n type: answer.type,\n };\n case \"SRV\":\n return {\n data: [\n requiredNumber(answer.data.priority, \"SRV priority\"),\n requiredNumber(answer.data.weight, \"SRV weight\"),\n requiredNumber(answer.data.port, \"SRV port\"),\n answer.data.target,\n ].join(\" \"),\n type: answer.type,\n };\n case \"TXT\":\n return { data: decodeTxt(answer.data), type: answer.type };\n default:\n return undefined;\n }\n}\n\nfunction decodeTxt(data: DnsPacket.TxtData): string {\n const chunks = Array.isArray(data) ? data : [data];\n const encoded = chunks.map((chunk) =>\n typeof chunk === \"string\" ? new TextEncoder().encode(chunk) : chunk,\n );\n const length = encoded.reduce((total, chunk) => total + chunk.length, 0);\n const joined = new Uint8Array(length);\n let offset = 0;\n for (const chunk of encoded) {\n joined.set(chunk, offset);\n offset += chunk.length;\n }\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(joined);\n}\n\nfunction requiredNumber(value: number | undefined, field: string): number {\n if (value === undefined) throw new Error(`DoH response omitted ${field}`);\n return value;\n}\n\nasync function request(input: {\n readonly effectSignal: AbortSignal;\n readonly endpoint: string;\n readonly fetch: Fetch;\n readonly query: DnsResolver.Query;\n readonly timeoutMs: number;\n}): Promise<Uint8Array> {\n const controller = new AbortController();\n let timedOut = false;\n const abortFromEffect = () => controller.abort(input.effectSignal.reason);\n const abortFromHost = () => controller.abort(input.query.signal?.reason);\n input.effectSignal.addEventListener(\"abort\", abortFromEffect, { once: true });\n input.query.signal?.addEventListener(\"abort\", abortFromHost, { once: true });\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new Error(\"DNS resolution timed out\"));\n }, input.timeoutMs);\n try {\n const query = Uint8Array.from(\n DnsPacket.encode({\n flags: DnsPacket.RECURSION_DESIRED,\n id: 0,\n questions: [{ name: input.query.name, type: input.query.type }],\n type: \"query\",\n }),\n );\n const response = await input.fetch(new URL(input.endpoint), {\n body: query,\n headers: {\n accept: \"application/dns-message\",\n \"content-type\": \"application/dns-message\",\n },\n method: \"POST\",\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new DnsResolver.Error({\n message: `DoH returned HTTP ${response.status}`,\n reason: \"transport\",\n });\n }\n const contentType = response.headers\n .get(\"content-type\")\n ?.split(\";\", 1)[0]\n ?.trim()\n .toLowerCase();\n if (contentType !== \"application/dns-message\") {\n throw new DnsResolver.Error({\n message: `DoH returned unsupported content type ${contentType ?? \"<missing>\"}`,\n reason: \"response\",\n });\n }\n return new Uint8Array(await response.arrayBuffer());\n } catch (cause) {\n if (timedOut) {\n throw new DnsResolver.Error({ message: \"DNS query timed out\", reason: \"timeout\" });\n }\n throw cause;\n } finally {\n clearTimeout(timer);\n input.effectSignal.removeEventListener(\"abort\", abortFromEffect);\n input.query.signal?.removeEventListener(\"abort\", abortFromHost);\n }\n}\n","import { Layer } from \"effect\";\n\nimport * as DnsOverHttps from \"./doh.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\n\nconst endpoint = \"https://cloudflare-dns.com/dns-query\";\n\nexport interface Options extends Omit<DnsOverHttps.Options, \"endpoint\"> {\n readonly endpoint?: string;\n}\n\nexport function make(options: Options = {}): DnsResolver.Interface {\n return DnsOverHttps.make({ ...options, endpoint: options.endpoint ?? endpoint });\n}\n\nexport const layer = (options: Options = {}): Layer.Layer<DnsResolver.Service> =>\n Layer.succeed(DnsResolver.Service, make(options));\n\nexport const toAsync = (options: Options = {}): DnsResolver.AsyncInterface =>\n DnsResolver.toAsync(make(options));\n","import { Effect, Schema } from \"effect\";\n\nimport type * as DomainName from \"../domain/domain-name.ts\";\nimport * as DnsRecord from \"../domain/dns-record.ts\";\nimport * as DnsProvider from \"../provider/provider.ts\";\nimport * as DnsData from \"./dns-data.ts\";\nimport * as DnsResolver from \"./resolver.ts\";\n\nexport const ProviderObservation = Schema.TaggedUnion({\n match: {},\n missing: {},\n mismatch: { records: Schema.Array(DnsRecord.Schema) },\n failure: { message: Schema.String },\n});\nexport type ProviderObservation = typeof ProviderObservation.Type;\n\nexport const PublicDnsObservation = Schema.TaggedUnion({\n propagated: {},\n missing: {},\n mismatch: { answers: Schema.Array(Schema.String) },\n timeout: {},\n failure: { message: Schema.String },\n});\nexport type PublicDnsObservation = typeof PublicDnsObservation.Type;\n\nexport const Result = Schema.Struct({\n provider: ProviderObservation,\n publicDns: PublicDnsObservation,\n status: Schema.Literals([\"verified\", \"pending\", \"mismatch\", \"unavailable\"]),\n});\nexport interface Result extends Schema.Schema.Type<typeof Result> {}\n\nexport const record = Effect.fn(\"Verification.record\")(function* (input: {\n readonly record: DnsRecord.DnsRecord;\n readonly zone: DomainName.DomainName;\n}) {\n const provider = yield* DnsProvider.Service;\n const resolver = yield* DnsResolver.Service;\n const [providerObservation, publicDns] = yield* Effect.all(\n [\n observeProvider(provider, input.zone, input.record).pipe(\n Effect.catch((failure) =>\n Effect.succeed<ProviderObservation>({ _tag: \"failure\", message: failure.message }),\n ),\n ),\n resolver.resolve({ name: input.record.name, type: input.record._tag }).pipe(\n Effect.match({\n onFailure: (failure): PublicDnsObservation =>\n failure.reason === \"timeout\"\n ? { _tag: \"timeout\" }\n : { _tag: \"failure\", message: failure.message },\n onSuccess: (resolution) => observePublicDns(input.record, resolution),\n }),\n ),\n ] as const,\n { concurrency: \"unbounded\" },\n );\n const status: Result[\"status\"] =\n providerObservation._tag === \"match\" && publicDns._tag === \"propagated\"\n ? \"verified\"\n : providerObservation._tag === \"failure\" ||\n publicDns._tag === \"failure\" ||\n publicDns._tag === \"timeout\"\n ? \"unavailable\"\n : providerObservation._tag === \"mismatch\" || publicDns._tag === \"mismatch\"\n ? \"mismatch\"\n : \"pending\";\n return { provider: providerObservation, publicDns, status };\n});\n\nfunction observeProvider(\n provider: DnsProvider.Interface,\n zone: DomainName.DomainName,\n requirement: DnsRecord.DnsRecord,\n): Effect.Effect<ProviderObservation, DnsProvider.Error> {\n return provider.listRecords(zone).pipe(\n Effect.map((records): ProviderObservation => {\n if (\n records.some(\n (existing) => existing._tag !== \"Opaque\" && DnsRecord.equals(existing, requirement),\n )\n ) {\n return { _tag: \"match\" };\n }\n const sameSet = records.filter(\n (existing): existing is DnsRecord.DnsRecord =>\n existing._tag !== \"Opaque\" &&\n existing.name === requirement.name &&\n existing._tag === requirement._tag,\n );\n return sameSet.length === 0 ? { _tag: \"missing\" } : { _tag: \"mismatch\", records: sameSet };\n }),\n );\n}\n\nfunction observePublicDns(\n requirement: DnsRecord.DnsRecord,\n resolution: DnsResolver.Resolution,\n): PublicDnsObservation {\n if (resolution._tag === \"nodata\") return { _tag: \"missing\" };\n const expected = DnsData.parse(requirement._tag, recordValue(requirement));\n return resolution.answers.some(\n (answer) =>\n answer.name === requirement.name &&\n answer.type === requirement._tag &&\n DnsData.parse(answer.type, answer.data) === expected,\n )\n ? { _tag: \"propagated\" }\n : { _tag: \"mismatch\", answers: resolution.answers.map(({ data }) => data) };\n}\n\nfunction recordValue(requirement: DnsRecord.DnsRecord): string {\n const data = DnsRecord.data(requirement);\n switch (requirement._tag) {\n case \"A\":\n case \"AAAA\":\n return String(data.address);\n case \"CNAME\":\n case \"NS\":\n return String(data.target);\n case \"TXT\":\n return String(data.value);\n case \"MX\":\n return `${data.priority} ${data.exchange}`;\n case \"CAA\":\n return `${data.flags} ${data.tag} ${data.value}`;\n case \"SRV\":\n return `${data.priority} ${data.weight} ${data.port} ${data.target}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;ACQA,MAAa,QAAQA,OAAE,YAAY;CACjC,SAAS,CAAC;CACV,SAAS,EAAE,SAASA,OAAE,MAAMC,QAAiB,EAAE;AACjD,CAAC;;AAID,MAAaC,WAASF,OAAE,OAAO;CAC7B,iBAAiBA,OAAE;CACnB,WAAWA,OAAE;CACb,OAAO;CACP,IAAIA,OAAE;CACN,SAASA,OAAE;AACb,CAAC;AAGD,M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