domainkit 0.0.1 → 0.1.0-beta.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -1
  3. package/dist/auth-Df9BuC25.mjs +460 -0
  4. package/dist/auth-Df9BuC25.mjs.map +1 -0
  5. package/dist/client-DvXfJx_E.mjs +534 -0
  6. package/dist/client-DvXfJx_E.mjs.map +1 -0
  7. package/dist/cloudflare-C_ixZsJo.mjs +46 -0
  8. package/dist/cloudflare-C_ixZsJo.mjs.map +1 -0
  9. package/dist/cloudflare-DClWuAm8.d.mts +23 -0
  10. package/dist/cloudflare.d.mts +3 -0
  11. package/dist/cloudflare.mjs +2 -0
  12. package/dist/dns-record-Dzo4flM5.mjs +259 -0
  13. package/dist/dns-record-Dzo4flM5.mjs.map +1 -0
  14. package/dist/effect-cloudflare.d.mts +2 -0
  15. package/dist/effect-cloudflare.mjs +2 -0
  16. package/dist/effect-vercel.d.mts +2 -0
  17. package/dist/effect-vercel.mjs +2 -0
  18. package/dist/effect.d.mts +63 -0
  19. package/dist/effect.mjs +28 -0
  20. package/dist/effect.mjs.map +1 -0
  21. package/dist/index-D1KtyjuI.d.mts +71 -0
  22. package/dist/index-DQAjUrZu.d.mts +94 -0
  23. package/dist/index.d.mts +128 -0
  24. package/dist/index.mjs +198 -0
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/manifest-DjH3BVB9.d.mts +579 -0
  27. package/dist/receipt-C7PjnibZ.mjs +28 -0
  28. package/dist/receipt-C7PjnibZ.mjs.map +1 -0
  29. package/dist/resolver-BjZwN2JE.d.mts +2327 -0
  30. package/dist/resolver-D5nVrR10.mjs +153 -0
  31. package/dist/resolver-D5nVrR10.mjs.map +1 -0
  32. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  33. package/dist/testing.d.mts +47 -0
  34. package/dist/testing.mjs +117 -0
  35. package/dist/testing.mjs.map +1 -0
  36. package/dist/vercel-BWz_9Y1v.mjs +38 -0
  37. package/dist/vercel-BWz_9Y1v.mjs.map +1 -0
  38. package/dist/vercel-Vc_K_87s.d.mts +22 -0
  39. package/dist/vercel.d.mts +3 -0
  40. package/dist/vercel.mjs +2 -0
  41. package/dist/verify-CeMW6XtK.mjs +1109 -0
  42. package/dist/verify-CeMW6XtK.mjs.map +1 -0
  43. package/dist/verify-DPB1OfZ5.d.mts +979 -0
  44. package/package.json +94 -6
  45. package/bun.lock +0 -66
  46. package/index.ts +0 -1
  47. package/tsconfig.json +0 -30
@@ -0,0 +1,1109 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { D as parse$1, O as Error$1, T as decode$3, _ as equals, b as Service, h as decode$4, m as data, s as Observed, u as Schema$5, w as Schema$4, y as Error$2 } from "./dns-record-Dzo4flM5.mjs";
3
+ import { a as toAsync$2, m as Service$2, n as Service$4, o as Service$1, t as Error$3, u as Service$3 } from "./resolver-D5nVrR10.mjs";
4
+ import { c as Value } from "./client-DvXfJx_E.mjs";
5
+ import { Cause, Clock, Crypto, Effect, Layer, PlatformError, Schema, SchemaIssue, SchemaTransformation } from "effect";
6
+ import * as oauth from "oauth4webapi";
7
+ import { getDomain } from "tldts";
8
+ import * as DnsPacket from "@leichtgewicht/dns-packet";
9
+ //#region package.json
10
+ var version = "0.1.0-beta.0";
11
+ //#endregion
12
+ //#region src/auth/connection.ts
13
+ var connection_exports = /* @__PURE__ */ __exportAll({
14
+ AuthorizationError: () => AuthorizationError$1,
15
+ Capability: () => Capability,
16
+ Grant: () => Grant,
17
+ Schema: () => Schema$3,
18
+ assertGrant: () => assertGrant,
19
+ decode: () => decode$2,
20
+ encode: () => encode$1,
21
+ validate: () => validate
22
+ });
23
+ const Capability = Schema.Literals(["dns:read", "dns:write"]);
24
+ const Grant = Schema.TaggedUnion({
25
+ account: {},
26
+ domains: { domains: Schema.Array(Schema$4) }
27
+ });
28
+ const Schema$3 = Schema.Struct({
29
+ accountId: Schema.String,
30
+ capabilities: Schema.Array(Capability),
31
+ createdAt: Schema.DateFromString,
32
+ expiresAt: Schema.NullOr(Schema.DateFromString),
33
+ grant: Grant,
34
+ id: Schema.String,
35
+ kind: Schema.Literals(["oauth2", "token"]),
36
+ providerId: Schema.String,
37
+ scopes: Schema.Array(Schema.String),
38
+ subjectId: Schema.String
39
+ });
40
+ const decode$2 = Effect.fn("Connection.decode")((input) => Schema.decodeUnknownEffect(Schema$3)(input).pipe(Effect.mapError((cause) => new Error$1({ message: cause.message }))));
41
+ const validate = Effect.fn("Connection.validate")((input) => Schema.decodeUnknownEffect(Schema.toType(Schema$3))(input).pipe(Effect.mapError((cause) => new Error$1({ message: cause.message }))));
42
+ const encode$1 = Schema.encodeSync(Schema$3);
43
+ var AuthorizationError$1 = class extends Schema.TaggedError()("AuthorizationError", { message: Schema.String }) {};
44
+ function assertGrant(connection, request) {
45
+ if (connection.providerId !== request.providerId || connection.accountId !== request.accountId) throw new AuthorizationError$1({ message: "Connection does not grant this provider account" });
46
+ if (connection.expiresAt !== null) {
47
+ if (Number.isNaN(connection.expiresAt.getTime())) throw new AuthorizationError$1({ message: "Connection expiration is invalid" });
48
+ if (connection.expiresAt <= (request.now ?? /* @__PURE__ */ new Date())) throw new AuthorizationError$1({ message: "Connection has expired" });
49
+ }
50
+ if (!connection.capabilities.includes(request.capability)) throw new AuthorizationError$1({ message: `Connection lacks the ${request.capability} capability` });
51
+ let domain;
52
+ try {
53
+ domain = parse$1(request.domain);
54
+ } catch (cause) {
55
+ if (cause instanceof Error$1) throw cause;
56
+ throw new Error$1({ message: cause instanceof Error ? cause.message : String(cause) });
57
+ }
58
+ if (connection.grant._tag === "domains" && !connection.grant.domains.includes(domain)) throw new AuthorizationError$1({ message: "Connection does not grant this domain" });
59
+ return domain;
60
+ }
61
+ //#endregion
62
+ //#region src/plan/canonical-json.ts
63
+ var canonical_json_exports = /* @__PURE__ */ __exportAll({
64
+ CryptoError: () => CryptoError,
65
+ sha256Encoded: () => sha256Encoded,
66
+ sha256Json: () => sha256Json,
67
+ sha256Text: () => sha256Text,
68
+ stringify: () => stringify,
69
+ webCryptoLayer: () => webCryptoLayer
70
+ });
71
+ var CryptoError = class extends Schema.TaggedError()("CryptoError", { message: Schema.String }) {};
72
+ /** Deterministic JSON serialization for already schema-encoded protocol values. */
73
+ function stringify(value) {
74
+ if (value === null || typeof value !== "object") {
75
+ const encoded = JSON.stringify(value);
76
+ if (encoded === void 0) throw new TypeError("Value is not representable as JSON");
77
+ return encoded;
78
+ }
79
+ if (isJsonArray(value)) return `[${value.map(stringify).join(",")}]`;
80
+ return `{${Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stringify(entry)}`).join(",")}}`;
81
+ }
82
+ function isJsonArray(value) {
83
+ return Array.isArray(value);
84
+ }
85
+ const sha256Text = Effect.fn("Digest.sha256Text")(function* (value) {
86
+ return [...yield* (yield* Crypto.Crypto).digest("SHA-256", new TextEncoder().encode(value)).pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
87
+ });
88
+ const sha256Json = Effect.fn("Digest.sha256Json")((value) => Effect.try({
89
+ try: () => stringify(value),
90
+ catch: (cause) => new CryptoError({ message: cause instanceof Error ? cause.message : String(cause) })
91
+ }).pipe(Effect.flatMap(sha256Text)));
92
+ function sha256EncodedProgram(schema, value) {
93
+ return Schema.encodeEffect(schema)(value).pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })), Effect.flatMap(Schema.decodeUnknownEffect(Schema.Json)), Effect.mapError((cause) => new CryptoError({ message: cause.message })), Effect.flatMap(sha256Json));
94
+ }
95
+ const sha256Encoded = Effect.fn("Digest.sha256Encoded")(sha256EncodedProgram);
96
+ /** Portable Web Crypto implementation for hosts that want a ready-made Layer. */
97
+ const webCryptoLayer = Layer.succeed(Crypto.Crypto, Crypto.make({
98
+ randomBytes: (size) => crypto.getRandomValues(new Uint8Array(size)),
99
+ digest: (algorithm, data) => Effect.tryPromise({
100
+ try: async () => {
101
+ const bytes = new Uint8Array(data.byteLength);
102
+ bytes.set(data);
103
+ return new Uint8Array(await crypto.subtle.digest(algorithm, bytes.buffer));
104
+ },
105
+ catch: (cause) => PlatformError.systemError({
106
+ _tag: "Unknown",
107
+ module: "WebCrypto",
108
+ method: "digest",
109
+ cause
110
+ })
111
+ })
112
+ }));
113
+ //#endregion
114
+ //#region src/auth/oauth.ts
115
+ var oauth_exports = /* @__PURE__ */ __exportAll({
116
+ begin: () => begin,
117
+ complete: () => complete,
118
+ refresh: () => refresh,
119
+ revoke: () => revoke
120
+ });
121
+ function beginProgram(input) {
122
+ return Effect.gen(function* () {
123
+ const stateStore = yield* Service$1;
124
+ const cryptoService = yield* Crypto.Crypto;
125
+ const now = yield* Clock.currentTimeMillis;
126
+ const state = base64Url(yield* cryptoBytes(cryptoService, 32));
127
+ const codeVerifier = base64Url(yield* cryptoBytes(cryptoService, 32));
128
+ const challenge = base64Url(yield* cryptoService.digest("SHA-256", new TextEncoder().encode(codeVerifier)).pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message }))));
129
+ const stateHash = yield* sha256Text(state);
130
+ const authorizationUrl = new URL(input.method.authorizationServer.authorization_endpoint);
131
+ authorizationUrl.search = new URLSearchParams({
132
+ client_id: input.client.clientId,
133
+ code_challenge: challenge,
134
+ code_challenge_method: "S256",
135
+ redirect_uri: input.redirectUri,
136
+ response_type: "code",
137
+ scope: input.method.scopes.join(" "),
138
+ state
139
+ }).toString();
140
+ yield* stateStore.put({
141
+ clientId: input.client.clientId,
142
+ codeVerifier: Value.from(codeVerifier),
143
+ expiresAt: new Date(now + (input.ttlMs ?? 6e5)),
144
+ grant: input.grant,
145
+ method: input.method,
146
+ redirectUri: input.redirectUri,
147
+ stateHash,
148
+ subjectId: input.subjectId
149
+ });
150
+ return { authorizationUrl };
151
+ });
152
+ }
153
+ function completeProgram(input) {
154
+ return Effect.gen(function* () {
155
+ const stateStore = yield* Service$1;
156
+ const connectionStore = yield* Service$2;
157
+ const credentialStore = yield* Service$3;
158
+ const cryptoService = yield* Crypto.Crypto;
159
+ const state = input.callbackUrl.searchParams.get("state");
160
+ if (state === null) return yield* new AuthorizationError$1({ message: "OAuth callback is missing state" });
161
+ const now = yield* Clock.currentTimeMillis;
162
+ const continuation = yield* stateStore.consume(yield* sha256Text(state), new Date(now));
163
+ if (continuation === null) return yield* new AuthorizationError$1({ message: "OAuth continuation is expired, unknown, or already used" });
164
+ if (continuation.clientId !== input.client.clientId) return yield* new AuthorizationError$1({ message: "OAuth client does not match the continuation" });
165
+ const as = continuation.method.authorizationServer;
166
+ const client = { client_id: continuation.clientId };
167
+ const authentication = yield* effectClientAuthentication(continuation.method, input.client);
168
+ const tokens = yield* providerRequest(input.providerId, async (signal) => {
169
+ const callbackParameters = oauth.validateAuthResponse(as, client, input.callbackUrl, state);
170
+ const response = await oauth.authorizationCodeGrantRequest(as, client, authentication, callbackParameters, continuation.redirectUri, continuation.codeVerifier.expose(), requestOptions(input.fetch, signal));
171
+ return oauth.processAuthorizationCodeResponse(as, client, response);
172
+ });
173
+ const accessToken = Value.from(tokens.access_token);
174
+ const subject = yield* input.resolveSubject(tokens, accessToken);
175
+ const id = yield* cryptoService.randomUUIDv4.pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })));
176
+ const connection = yield* validate({
177
+ accountId: subject.accountId,
178
+ capabilities: [...continuation.method.capabilities],
179
+ createdAt: new Date(now),
180
+ expiresAt: subject.expiresAt,
181
+ grant: continuation.grant,
182
+ id,
183
+ kind: "oauth2",
184
+ providerId: input.providerId,
185
+ scopes: (tokens.scope ?? continuation.method.scopes.join(" ")).split(" ").filter(Boolean),
186
+ subjectId: continuation.subjectId
187
+ });
188
+ yield* credentialStore.put(connection.id, {
189
+ accessToken,
190
+ refreshToken: tokens.refresh_token === void 0 ? null : Value.from(tokens.refresh_token),
191
+ tokenType: tokens.token_type
192
+ });
193
+ yield* connectionStore.put(connection);
194
+ return connection;
195
+ });
196
+ }
197
+ function refreshProgram(input) {
198
+ return Effect.gen(function* () {
199
+ const credentialStore = yield* Service$3;
200
+ const credential = yield* requireCredential(input.connection.id, credentialStore);
201
+ const refreshToken = credential.refreshToken;
202
+ if (refreshToken === null) return yield* new AuthorizationError$1({ message: "Connection has no refresh token" });
203
+ const as = input.method.authorizationServer;
204
+ const client = { client_id: input.client.clientId };
205
+ const authentication = yield* effectClientAuthentication(input.method, input.client);
206
+ const tokens = yield* providerRequest(input.connection.providerId, async (signal) => {
207
+ const response = await oauth.refreshTokenGrantRequest(as, client, authentication, refreshToken.expose(), requestOptions(input.fetch, signal));
208
+ return oauth.processRefreshTokenResponse(as, client, response);
209
+ });
210
+ yield* credentialStore.put(input.connection.id, {
211
+ accessToken: Value.from(tokens.access_token),
212
+ refreshToken: tokens.refresh_token === void 0 ? credential.refreshToken : Value.from(tokens.refresh_token),
213
+ tokenType: tokens.token_type
214
+ });
215
+ });
216
+ }
217
+ function revokeProgram(input) {
218
+ return Effect.gen(function* () {
219
+ if (input.method.authorizationServer.revocation_endpoint === void 0) return yield* new AuthorizationError$1({ message: "Provider does not advertise token revocation" });
220
+ const credentialStore = yield* Service$3;
221
+ const credential = yield* requireCredential(input.connection.id, credentialStore);
222
+ const as = input.method.authorizationServer;
223
+ const authentication = yield* effectClientAuthentication(input.method, input.client);
224
+ yield* providerRequest(input.connection.providerId, async (signal) => {
225
+ const response = await oauth.revocationRequest(as, { client_id: input.client.clientId }, authentication, credential.accessToken.expose(), requestOptions(input.fetch, signal));
226
+ await oauth.processRevocationResponse(response);
227
+ });
228
+ yield* credentialStore.delete(input.connection.id);
229
+ });
230
+ }
231
+ function effectClientAuthentication(method, client) {
232
+ return Effect.try({
233
+ try: () => clientAuthentication(method, client),
234
+ catch: (cause) => cause instanceof Error$1 ? cause : new Error$1({ message: "OAuth client authentication is invalid" })
235
+ });
236
+ }
237
+ function clientAuthentication(method, client) {
238
+ switch (method.clientAuth) {
239
+ case "none": return oauth.None();
240
+ case "client_secret_basic":
241
+ if (client.clientSecret === void 0) throw new Error$1({ message: "Client secret is required" });
242
+ return oauth.ClientSecretBasic(client.clientSecret.expose());
243
+ case "client_secret_post":
244
+ if (client.clientSecret === void 0) throw new Error$1({ message: "Client secret is required" });
245
+ return oauth.ClientSecretPost(client.clientSecret.expose());
246
+ }
247
+ }
248
+ function requestOptions(fetchImplementation, signal) {
249
+ return fetchImplementation === void 0 ? { signal } : {
250
+ signal,
251
+ [oauth.customFetch]: (url, options) => fetchImplementation(url, {
252
+ ...options,
253
+ body: options.body
254
+ })
255
+ };
256
+ }
257
+ function requireCredential(connectionId, store) {
258
+ return store.get(connectionId).pipe(Effect.flatMap((credential) => credential === null ? Effect.fail(new AuthorizationError$1({ message: "Connection credentials are unavailable" })) : Effect.succeed(credential)));
259
+ }
260
+ function providerRequest(providerId, request) {
261
+ return Effect.tryPromise({
262
+ try: request,
263
+ catch: (cause) => cause instanceof AuthorizationError$1 || cause instanceof Error$1 ? cause : new Error$2({
264
+ cause,
265
+ message: safeOAuthMessage(cause),
266
+ operation: "oauthRequest",
267
+ providerId
268
+ })
269
+ });
270
+ }
271
+ function cryptoBytes(cryptoService, size) {
272
+ return cryptoService.randomBytes(size).pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })));
273
+ }
274
+ function base64Url(bytes) {
275
+ let binary = "";
276
+ for (const byte of bytes) binary += String.fromCharCode(byte);
277
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
278
+ }
279
+ function safeOAuthMessage(cause) {
280
+ return cause instanceof Error ? cause.name : "OAuth provider request failed";
281
+ }
282
+ const begin = Effect.fn("OAuth.begin")(beginProgram);
283
+ const complete = Effect.fn("OAuth.complete")(completeProgram);
284
+ const refresh = Effect.fn("OAuth.refresh")(refreshProgram);
285
+ const revoke = Effect.fn("OAuth.revoke")(revokeProgram);
286
+ //#endregion
287
+ //#region src/auth/manifest.ts
288
+ var manifest_exports = /* @__PURE__ */ __exportAll({
289
+ Method: () => Method,
290
+ Schema: () => Schema$2,
291
+ decode: () => decode$1
292
+ });
293
+ const Method = Schema.TaggedUnion({
294
+ integration: {
295
+ capabilities: Schema.Array(Schema.Literals(["dns:read", "dns:write"])),
296
+ installUrl: Schema.String,
297
+ tokenEndpoint: Schema.String
298
+ },
299
+ oauth2: {
300
+ authorizationServer: Schema.Struct({
301
+ authorization_endpoint: Schema.String,
302
+ issuer: Schema.String,
303
+ revocation_endpoint: Schema.optionalKey(Schema.String),
304
+ token_endpoint: Schema.String
305
+ }),
306
+ capabilities: Schema.Array(Schema.Literals(["dns:read", "dns:write"])),
307
+ clientAuth: Schema.Literals([
308
+ "none",
309
+ "client_secret_basic",
310
+ "client_secret_post"
311
+ ]),
312
+ scopes: Schema.Array(Schema.String)
313
+ },
314
+ token: {
315
+ capabilities: Schema.Array(Schema.Literals(["dns:read", "dns:write"])),
316
+ instructionsUrl: Schema.String
317
+ }
318
+ });
319
+ const Schema$2 = Schema.Struct({
320
+ methods: Schema.Array(Method),
321
+ providerId: Schema.String
322
+ });
323
+ const decode$1 = Effect.fn("ProviderAuth.decode")((input) => Schema.decodeUnknownEffect(Schema$2)(input).pipe(Effect.mapError((cause) => new Error$1({ message: cause.message }))));
324
+ //#endregion
325
+ //#region src/auth/token.ts
326
+ var token_exports = /* @__PURE__ */ __exportAll({ connect: () => connect });
327
+ const connect = Effect.fn("TokenConnection.connect")(function* (input) {
328
+ const connectionStore = yield* Service$2;
329
+ const credentialStore = yield* Service$3;
330
+ const cryptoService = yield* Crypto.Crypto;
331
+ const validation = yield* input.validate(input.token);
332
+ const createdAt = new Date(yield* Clock.currentTimeMillis);
333
+ const id = yield* cryptoService.randomUUIDv4.pipe(Effect.mapError((cause) => new CryptoError({ message: cause.message })));
334
+ const connection = yield* validate({
335
+ accountId: validation.accountId,
336
+ capabilities: [...validation.capabilities],
337
+ createdAt,
338
+ expiresAt: validation.expiresAt,
339
+ grant: input.grant,
340
+ id,
341
+ kind: "token",
342
+ providerId: input.providerId,
343
+ scopes: [...validation.scopes],
344
+ subjectId: input.subjectId
345
+ });
346
+ yield* credentialStore.put(connection.id, {
347
+ accessToken: input.token,
348
+ refreshToken: null,
349
+ tokenType: "bearer"
350
+ });
351
+ yield* connectionStore.put(connection);
352
+ return connection;
353
+ });
354
+ //#endregion
355
+ //#region src/discovery/zones.ts
356
+ var zones_exports = /* @__PURE__ */ __exportAll({ candidates: () => candidates });
357
+ function candidates(input) {
358
+ const domain = parse$1(input);
359
+ const registrable = getDomain(domain, { allowPrivateDomains: true });
360
+ if (registrable === null) throw new Error$1({ message: "Domain does not have a registrable DNS zone" });
361
+ const labels = domain.split(".");
362
+ const registrableLabels = registrable.split(".").length;
363
+ const values = [];
364
+ for (let index = 0; index <= labels.length - registrableLabels; index += 1) values.push(parse$1(labels.slice(index).join(".")));
365
+ return values;
366
+ }
367
+ //#endregion
368
+ //#region src/discovery/selection.ts
369
+ var selection_exports = /* @__PURE__ */ __exportAll({
370
+ Evidence: () => Evidence,
371
+ Selection: () => Selection,
372
+ select: () => select
373
+ });
374
+ const Evidence = Schema.Struct({
375
+ accountId: Schema.String,
376
+ connectionId: Schema.String,
377
+ decisiveNameserverMatch: Schema.Boolean,
378
+ matchedNameservers: Schema.Array(Schema$4),
379
+ providerId: Schema.String,
380
+ zone: Schema$4
381
+ });
382
+ const Selection = Schema.TaggedUnion({
383
+ selected: {
384
+ candidate: Evidence,
385
+ evidence: Schema.Array(Evidence),
386
+ reason: Schema.Literals(["explicit", "unique-nameserver-match"])
387
+ },
388
+ manual: {
389
+ evidence: Schema.Array(Evidence),
390
+ reason: Schema.Literals(["ambiguous", "unsupported"])
391
+ }
392
+ });
393
+ function select(input) {
394
+ const domain = parse$1(input.domain);
395
+ const zoneCandidates = new Set(candidates(domain));
396
+ const authoritative = nameserverSet(input.authoritativeNameservers);
397
+ const eligible = input.connectedZones.filter((connected) => {
398
+ if (!zoneCandidates.has(parse$1(connected.zone))) return false;
399
+ try {
400
+ assertGrant(connected.connection, {
401
+ accountId: connected.accountId,
402
+ capability: "dns:read",
403
+ domain,
404
+ ...input.now === void 0 ? {} : { now: input.now },
405
+ providerId: connected.providerId
406
+ });
407
+ return true;
408
+ } catch {
409
+ return false;
410
+ }
411
+ });
412
+ const evidence = eligible.map((connected) => evidenceFor(connected, authoritative));
413
+ if (input.explicit !== void 0) {
414
+ const explicitZone = parse$1(input.explicit.zone);
415
+ const index = eligible.findIndex((connected) => connected.providerId === input.explicit?.providerId && connected.accountId === input.explicit.accountId && parse$1(connected.zone) === explicitZone);
416
+ if (index < 0) throw new AuthorizationError$1({ message: "Explicit provider zone is not connected or granted" });
417
+ const candidate = evidence[index];
418
+ if (candidate === void 0) throw new Error("Eligible provider evidence is missing");
419
+ return {
420
+ _tag: "selected",
421
+ candidate,
422
+ evidence,
423
+ reason: "explicit"
424
+ };
425
+ }
426
+ const decisive = evidence.filter(({ decisiveNameserverMatch }) => decisiveNameserverMatch);
427
+ const candidate = decisive[0];
428
+ return decisive.length === 1 && candidate !== void 0 ? {
429
+ _tag: "selected",
430
+ candidate,
431
+ evidence,
432
+ reason: "unique-nameserver-match"
433
+ } : {
434
+ _tag: "manual",
435
+ evidence,
436
+ reason: decisive.length > 1 ? "ambiguous" : "unsupported"
437
+ };
438
+ }
439
+ function evidenceFor(connected, authoritative) {
440
+ const configured = new Set(nameserverSet(connected.nameservers));
441
+ const matchedNameservers = authoritative.filter((nameserver) => configured.has(nameserver));
442
+ return {
443
+ accountId: connected.accountId,
444
+ connectionId: connected.connection.id,
445
+ decisiveNameserverMatch: authoritative.length > 0 && matchedNameservers.length === authoritative.length,
446
+ matchedNameservers,
447
+ providerId: connected.providerId,
448
+ zone: parse$1(connected.zone)
449
+ };
450
+ }
451
+ function nameserverSet(nameservers) {
452
+ return [...new Set(nameservers.map(parse$1))].sort();
453
+ }
454
+ //#endregion
455
+ //#region src/plan/types.ts
456
+ var types_exports = /* @__PURE__ */ __exportAll({
457
+ Authorization: () => Authorization,
458
+ Operation: () => Operation,
459
+ Receipt: () => Receipt,
460
+ Schema: () => Schema$1,
461
+ decode: () => decode,
462
+ decodeReceipt: () => decodeReceipt,
463
+ encode: () => encode,
464
+ encodeReceipt: () => encodeReceipt
465
+ });
466
+ const Operation = Schema.TaggedUnion({
467
+ create: {
468
+ id: Schema.String,
469
+ requirement: Schema$5
470
+ },
471
+ noop: {
472
+ id: Schema.String,
473
+ requirement: Schema$5,
474
+ ttlDrift: Schema.Boolean
475
+ },
476
+ conflict: {
477
+ existing: Schema.Array(Observed),
478
+ id: Schema.String,
479
+ reason: Schema.String,
480
+ requirement: Schema$5
481
+ }
482
+ });
483
+ const Schema$1 = Schema.Struct({
484
+ digest: Schema.String,
485
+ operations: Schema.Array(Operation),
486
+ providerId: Schema.String,
487
+ version: Schema.Literal("domainkit.dns-plan.v1"),
488
+ zone: Schema$4
489
+ });
490
+ const Authorization = Schema.Struct({
491
+ allowPartial: Schema.Boolean,
492
+ operationIds: Schema.Array(Schema.String),
493
+ planDigest: Schema.String,
494
+ version: Schema.Literal("domainkit.plan-authorization.v1")
495
+ });
496
+ const Receipt = Schema.Struct({
497
+ appliedAt: Schema.DateFromString,
498
+ operations: Schema.Array(Schema.Struct({
499
+ operationId: Schema.String,
500
+ providerRecordId: Schema.NullOr(Schema.String)
501
+ })),
502
+ planDigest: Schema.String,
503
+ providerId: Schema.String,
504
+ status: Schema.Literals(["complete", "partial"]),
505
+ version: Schema.Literal("domainkit.apply-receipt.v1"),
506
+ zone: Schema$4
507
+ });
508
+ const decode = Effect.fn("DnsPlan.decode")((input) => Schema.decodeUnknownEffect(Schema$1)(input).pipe(Effect.mapError((cause) => new Error$1({ message: cause.message }))));
509
+ const encode = Schema.encodeSync(Schema$1);
510
+ const decodeReceipt = Effect.fn("DnsPlan.decodeReceipt")((input) => Schema.decodeUnknownEffect(Receipt)(input).pipe(Effect.mapError((cause) => new Error$1({ message: cause.message }))));
511
+ const encodeReceipt = Schema.encodeSync(Receipt);
512
+ //#endregion
513
+ //#region src/plan/plan.ts
514
+ var plan_exports = /* @__PURE__ */ __exportAll({
515
+ AuthorizationError: () => AuthorizationError,
516
+ ConflictError: () => ConflictError,
517
+ PartialApplyError: () => PartialApplyError,
518
+ StaleError: () => StaleError,
519
+ apply: () => apply,
520
+ authorize: () => authorize$1,
521
+ create: () => create,
522
+ renderManualInstructions: () => renderManualInstructions
523
+ });
524
+ const UnsignedPlan = Schema.Struct({
525
+ operations: Schema.Array(Operation),
526
+ providerId: Schema.String,
527
+ version: Schema.Literal("domainkit.dns-plan.v1"),
528
+ zone: Schema$4
529
+ });
530
+ const RequirementDigest = Schema.Struct({ requirement: Schema$5 });
531
+ var ConflictError = class extends Schema.TaggedError()("PlanConflictError", { operationIds: Schema.Array(Schema.String) }) {};
532
+ var AuthorizationError = class extends Schema.TaggedError()("AuthorizationError", { message: Schema.String }) {};
533
+ var StaleError = class extends Schema.TaggedError()("StalePlanError", {
534
+ approvedPlanDigest: Schema.String,
535
+ currentPlanDigest: Schema.String
536
+ }) {};
537
+ var PartialApplyError = class extends Schema.TaggedError()("PartialApplyError", {
538
+ causeTag: Schema.Literals([
539
+ "CryptoError",
540
+ "InvalidInputError",
541
+ "Interrupted",
542
+ "ProviderError",
543
+ "StalePlanError"
544
+ ]),
545
+ failedOperationId: Schema.String,
546
+ message: Schema.String,
547
+ receipt: Receipt
548
+ }) {};
549
+ /** Builds a deterministic DNS plan through the provider in the Effect environment. */
550
+ const create = Effect.fn("Provisioning.create")(function* (input) {
551
+ const provider = yield* Service;
552
+ const zone = yield* decode$3(input.zone);
553
+ const requirements = (yield* Effect.forEach(input.requirements, decode$4, { concurrency: "unbounded" })).sort(compareRecords);
554
+ const existing = [...yield* provider.listRecords(zone)].sort(compareRecords);
555
+ const { operations } = yield* Effect.reduce(requirements, () => ({
556
+ operations: [],
557
+ projected: existing
558
+ }), (state, requirement) => reconcileRequirement(requirement, state.projected).pipe(Effect.map((operation) => ({
559
+ operations: [...state.operations, operation],
560
+ projected: operation._tag === "create" ? [...state.projected, operation.requirement].sort(compareRecords) : state.projected
561
+ }))));
562
+ const unsigned = {
563
+ operations,
564
+ providerId: provider.id,
565
+ version: "domainkit.dns-plan.v1",
566
+ zone
567
+ };
568
+ return {
569
+ ...unsigned,
570
+ digest: yield* sha256Encoded(UnsignedPlan, unsigned)
571
+ };
572
+ });
573
+ /** Authorizes all or a selected subset of create operations in a digest-bound plan. */
574
+ const authorize$1 = Effect.fn("Provisioning.authorize")(function* (plan, operationIds, options = {}) {
575
+ yield* validateDigest(plan);
576
+ const createIds = plan.operations.filter((operation) => operation._tag === "create").map(({ id }) => id);
577
+ const selected = [...new Set(operationIds ?? createIds)].sort();
578
+ const unknown = selected.filter((id) => !createIds.includes(id));
579
+ if (unknown.length > 0) return yield* new AuthorizationError({ message: `Unknown operation IDs: ${unknown.join(", ")}` });
580
+ if (!options.allowPartial && selected.length !== createIds.length) return yield* new AuthorizationError({ message: "Partial authorization requires allowPartial" });
581
+ return {
582
+ allowPartial: options.allowPartial ?? false,
583
+ operationIds: selected,
584
+ planDigest: plan.digest,
585
+ version: "domainkit.plan-authorization.v1"
586
+ };
587
+ });
588
+ /** Applies approved creates sequentially after full and per-operation revalidation. */
589
+ const apply = Effect.fn("Provisioning.apply")(function* (input) {
590
+ const { authorization, plan } = input;
591
+ const provider = yield* Service;
592
+ yield* validateDigest(plan);
593
+ if (authorization.planDigest !== plan.digest) return yield* new AuthorizationError({ message: "Authorization belongs to a different plan" });
594
+ if (provider.id !== plan.providerId) return yield* new AuthorizationError({ message: "Provider does not match the approved plan" });
595
+ const conflicts = plan.operations.filter((operation) => operation._tag === "conflict");
596
+ if (conflicts.length > 0) return yield* new ConflictError({ operationIds: conflicts.map(({ id }) => id) });
597
+ const creates = plan.operations.filter(Operation.guards.create);
598
+ const approved = new Set(authorization.operationIds);
599
+ const unknown = authorization.operationIds.filter((id) => !creates.some((operation) => operation.id === id));
600
+ if (unknown.length > 0) return yield* new AuthorizationError({ message: `Authorization contains unknown operations: ${unknown.join(", ")}` });
601
+ if (!authorization.allowPartial && creates.some(({ id }) => !approved.has(id))) return yield* new AuthorizationError({ message: "Authorization does not cover every create operation" });
602
+ const currentPlan = yield* create({
603
+ requirements: plan.operations.map(({ requirement }) => requirement),
604
+ zone: plan.zone
605
+ });
606
+ if (currentPlan.digest !== plan.digest) return yield* new StaleError({
607
+ approvedPlanDigest: plan.digest,
608
+ currentPlanDigest: currentPlan.digest
609
+ });
610
+ const operations = [];
611
+ for (const operation of creates) {
612
+ if (!approved.has(operation.id)) continue;
613
+ yield* Effect.gen(function* () {
614
+ yield* assertStillCreatable(plan, operation);
615
+ const result = yield* provider.createRecord(plan.zone, operation.requirement);
616
+ operations.push({
617
+ operationId: operation.id,
618
+ providerRecordId: result.providerRecordId
619
+ });
620
+ }).pipe(Effect.catch((failure) => operations.length === 0 ? Effect.fail(failure) : makeReceipt(input, operations, "partial").pipe(Effect.flatMap((receipt) => Effect.fail(new PartialApplyError({
621
+ causeTag: failure._tag,
622
+ failedOperationId: operation.id,
623
+ message: failureMessage(failure),
624
+ receipt
625
+ }))))), Effect.catchCause((cause) => {
626
+ if (!Cause.hasInterruptsOnly(cause) || operations.length === 0) return Effect.failCause(cause);
627
+ return makeReceipt(input, operations, "partial").pipe(Effect.flatMap((receipt) => Effect.fail(new PartialApplyError({
628
+ causeTag: "Interrupted",
629
+ failedOperationId: operation.id,
630
+ message: "DNS apply was interrupted after confirmed writes",
631
+ receipt
632
+ }))));
633
+ }));
634
+ }
635
+ return yield* makeReceipt(input, operations, "complete");
636
+ });
637
+ function renderManualInstructions(plan) {
638
+ return plan.operations.map((operation) => {
639
+ const record = operation.requirement;
640
+ const data$2 = Object.entries(data(record)).map(([key, value]) => `${key}=${value}`).join(" ");
641
+ return `${operation._tag.toUpperCase()} ${record._tag} ${record.name} ${data$2}`.trim();
642
+ });
643
+ }
644
+ function makeReceipt(input, operations, status) {
645
+ return Clock.currentTimeMillis.pipe(Effect.map((now) => ({
646
+ appliedAt: new Date(now),
647
+ operations,
648
+ planDigest: input.plan.digest,
649
+ providerId: input.plan.providerId,
650
+ status,
651
+ version: "domainkit.apply-receipt.v1",
652
+ zone: input.plan.zone
653
+ })));
654
+ }
655
+ function assertStillCreatable(plan, operation) {
656
+ return create({
657
+ requirements: [operation.requirement],
658
+ zone: plan.zone
659
+ }).pipe(Effect.flatMap((currentPlan) => {
660
+ const currentOperation = currentPlan.operations[0];
661
+ return currentOperation?._tag === "create" && currentOperation.id === operation.id ? Effect.void : Effect.fail(new StaleError({
662
+ approvedPlanDigest: plan.digest,
663
+ currentPlanDigest: currentPlan.digest
664
+ }));
665
+ }));
666
+ }
667
+ function reconcileRequirement(requirement, allExisting) {
668
+ return Effect.gen(function* () {
669
+ const sameName = allExisting.filter((record) => record.name === requirement.name);
670
+ const sameSet = sameName.filter((record) => record._tag !== "Opaque" && record._tag === requirement._tag);
671
+ const exact = sameSet.find((record) => equals(record, requirement));
672
+ const id = yield* sha256Encoded(RequirementDigest, { requirement });
673
+ if (exact !== void 0) return {
674
+ _tag: "noop",
675
+ id,
676
+ requirement,
677
+ ttlDrift: exact.ttl !== requirement.ttl
678
+ };
679
+ if (sameName.length > 0 && (requirement._tag === "CNAME" || sameName.some((record) => record._tag === "CNAME"))) return {
680
+ _tag: "conflict",
681
+ existing: sameName,
682
+ id,
683
+ reason: "CNAME records cannot coexist with other records at the same name",
684
+ requirement
685
+ };
686
+ if (sameSet.length > 0 && (requirement.policy === "exclusive" || sameSet.some(({ policy }) => policy === "exclusive"))) return {
687
+ _tag: "conflict",
688
+ existing: sameSet,
689
+ id,
690
+ reason: "The exclusive record set already contains incompatible data",
691
+ requirement
692
+ };
693
+ return {
694
+ _tag: "create",
695
+ id,
696
+ requirement
697
+ };
698
+ });
699
+ }
700
+ function validateDigest(plan) {
701
+ const unsigned = {
702
+ operations: plan.operations,
703
+ providerId: plan.providerId,
704
+ version: plan.version,
705
+ zone: plan.zone
706
+ };
707
+ return sha256Encoded(UnsignedPlan, unsigned).pipe(Effect.flatMap((digest) => digest === plan.digest ? Effect.void : Effect.fail(new AuthorizationError({ message: "Plan digest does not match its contents" }))));
708
+ }
709
+ function failureMessage(failure) {
710
+ return failure._tag === "StalePlanError" ? "DNS state changed while applying the approved plan" : failure.message;
711
+ }
712
+ function compareRecords(left, right) {
713
+ const encode = Schema.encodeSync(Observed);
714
+ const toJson = Schema.decodeUnknownSync(Schema.Json);
715
+ const leftJson = stringify(toJson(encode(left)));
716
+ const rightJson = stringify(toJson(encode(right)));
717
+ return leftJson < rightJson ? -1 : leftJson > rightJson ? 1 : 0;
718
+ }
719
+ //#endregion
720
+ //#region src/plan/connection-authorization.ts
721
+ var connection_authorization_exports = /* @__PURE__ */ __exportAll({ authorize: () => authorize });
722
+ const authorize = Effect.fn("ConnectionAuthorization.authorize")(function* (input) {
723
+ yield* Effect.try({
724
+ try: () => assertGrant(input.connection, {
725
+ accountId: input.accountId,
726
+ capability: "dns:write",
727
+ domain: input.plan.zone,
728
+ providerId: input.plan.providerId
729
+ }),
730
+ catch: (cause) => cause instanceof AuthorizationError$1 || cause instanceof Error$1 ? cause : new AuthorizationError$1({ message: "Connection grant is invalid" })
731
+ });
732
+ return yield* authorize$1(input.plan, input.operationIds, input.allowPartial === void 0 ? {} : { allowPartial: input.allowPartial });
733
+ });
734
+ //#endregion
735
+ //#region src/verification/dns-data.ts
736
+ var dns_data_exports = /* @__PURE__ */ __exportAll({ parse: () => parse });
737
+ const CanonicalAddress = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.transform({
738
+ decode: (value) => value.trim().toLowerCase(),
739
+ encode: (value) => value
740
+ })));
741
+ const CanonicalDomain = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.transformOrFail({
742
+ decode: (value, options) => Effect.try({
743
+ try: () => parse$1(value).toString(),
744
+ catch: (cause) => new SchemaIssue.InvalidValue({ message: cause instanceof Error ? cause.message : String(cause) }, value, options)
745
+ }),
746
+ encode: (value) => Effect.succeed(value)
747
+ })));
748
+ const CanonicalMx = tokenizedDomain(2, 1);
749
+ const CanonicalSrv = tokenizedDomain(4, 3);
750
+ const CanonicalTxt = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.transform({
751
+ decode: (value) => {
752
+ const trimmed = value.trim();
753
+ const chunks = [...trimmed.matchAll(/"((?:\\.|[^"])*)"/g)];
754
+ return chunks.length === 0 ? trimmed : chunks.map((match) => (match[1] ?? "").replace(/\\"/g, "\"").replace(/\\\\/g, "\\")).join("");
755
+ },
756
+ encode: (value) => value
757
+ })));
758
+ const CanonicalCaa = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.transform({
759
+ decode: (value) => value.trim().replace(/\s+"([\s\S]*)"$/, " $1"),
760
+ encode: (value) => value
761
+ })));
762
+ function parse(type, input) {
763
+ const schema = (() => {
764
+ switch (type) {
765
+ case "A":
766
+ case "AAAA": return CanonicalAddress;
767
+ case "CNAME":
768
+ case "NS": return CanonicalDomain;
769
+ case "MX": return CanonicalMx;
770
+ case "SRV": return CanonicalSrv;
771
+ case "TXT": return CanonicalTxt;
772
+ case "CAA": return CanonicalCaa;
773
+ }
774
+ })();
775
+ try {
776
+ return Schema.decodeUnknownSync(schema)(input);
777
+ } catch (cause) {
778
+ throw new Error$1({ message: cause instanceof Error ? cause.message : String(cause) });
779
+ }
780
+ }
781
+ function tokenizedDomain(length, domainIndex) {
782
+ return Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.transformOrFail({
783
+ decode: (value, options) => Effect.try({
784
+ try: () => {
785
+ const parts = value.trim().split(/\s+/);
786
+ if (parts.length !== length) throw new Error("DNS record data has an invalid field count");
787
+ const domain = parts[domainIndex];
788
+ if (domain === void 0) throw new Error("DNS record target is missing");
789
+ parts[domainIndex] = parse$1(domain);
790
+ return parts.join(" ");
791
+ },
792
+ catch: (cause) => new SchemaIssue.InvalidValue({ message: cause instanceof Error ? cause.message : String(cause) }, value, options)
793
+ }),
794
+ encode: (value) => Effect.succeed(value)
795
+ })));
796
+ }
797
+ //#endregion
798
+ //#region src/verification/doh.ts
799
+ var doh_exports = /* @__PURE__ */ __exportAll({
800
+ layer: () => layer$1,
801
+ make: () => make$1,
802
+ toAsync: () => toAsync$1
803
+ });
804
+ function make$1(options) {
805
+ const fetch = options.fetch ?? globalThis.fetch;
806
+ const timeoutMs = options.timeoutMs ?? 5e3;
807
+ return { resolve: Effect.fn("DnsOverHttps.resolve")((query) => Effect.tryPromise({
808
+ try: (effectSignal) => request({
809
+ effectSignal,
810
+ fetch,
811
+ query,
812
+ timeoutMs,
813
+ endpoint: options.endpoint
814
+ }),
815
+ catch: (cause) => cause instanceof Error$3 ? cause : new Error$3({
816
+ cause,
817
+ message: cause instanceof Error ? cause.message : "DNS resolution failed",
818
+ reason: "transport"
819
+ })
820
+ }).pipe(Effect.flatMap((message) => decodeResolution(query, message)))) };
821
+ }
822
+ const layer$1 = (options) => Layer.succeed(Service$4, make$1(options));
823
+ const toAsync$1 = (options) => toAsync$2(make$1(options));
824
+ function decodeResolution(query, message) {
825
+ return Effect.try({
826
+ try: () => DnsPacket.decode(message),
827
+ catch: (cause) => new Error$3({
828
+ cause,
829
+ message: "DoH returned an invalid DNS message",
830
+ reason: "response"
831
+ })
832
+ }).pipe(Effect.flatMap((packet) => validatePacket(query, packet)), Effect.flatMap(decodePacket));
833
+ }
834
+ function decodePacket(packet) {
835
+ if (packet.rcode === "NXDOMAIN") return Effect.succeed({ _tag: "nodata" });
836
+ if (packet.rcode !== "NOERROR") return Effect.fail(new Error$3({
837
+ message: `DNS resolver returned ${packet.rcode ?? "an unknown response code"}`,
838
+ reason: "response"
839
+ }));
840
+ if (packet.answers === void 0 || packet.answers.length === 0) return Effect.succeed({ _tag: "nodata" });
841
+ return Effect.forEach(packet.answers, decodeAnswer, { concurrency: "unbounded" }).pipe(Effect.map((answers) => {
842
+ const supportedAnswers = answers.filter((answer) => answer !== null);
843
+ return supportedAnswers.length === 0 ? { _tag: "nodata" } : {
844
+ _tag: "answer",
845
+ answers: supportedAnswers
846
+ };
847
+ }));
848
+ }
849
+ function validatePacket(query, packet) {
850
+ return Effect.try({
851
+ try: () => {
852
+ if (packet.type !== "response") throw new Error("DoH returned a DNS query");
853
+ if (packet.id !== 0) throw new Error("DoH response used an unexpected message ID");
854
+ if (packet.flag_tc) throw new Error("DoH returned a truncated DNS response");
855
+ const questions = packet.questions ?? [];
856
+ if (questions.length !== 1) throw new Error("DoH returned an unexpected question count");
857
+ const question = questions[0];
858
+ if (question === void 0) throw new Error("DoH response omitted the DNS question");
859
+ if (question.class !== "IN" || question.type !== query.type || parse$1(question.name) !== query.name) throw new Error("DoH response did not match the DNS question");
860
+ return packet;
861
+ },
862
+ catch: (cause) => new Error$3({
863
+ cause,
864
+ message: cause instanceof Error ? cause.message : "DoH returned an invalid DNS response",
865
+ reason: "response"
866
+ })
867
+ });
868
+ }
869
+ function decodeAnswer(answer) {
870
+ return Effect.gen(function* () {
871
+ if (answer.class !== "IN") return null;
872
+ const decoded = yield* Effect.try({
873
+ try: () => answerData(answer),
874
+ catch: (cause) => new Error$3({
875
+ cause,
876
+ message: "DoH returned invalid DNS record data",
877
+ reason: "response"
878
+ })
879
+ });
880
+ if (decoded === void 0) return null;
881
+ const name = yield* decode$3(answer.name);
882
+ const data = yield* Effect.try({
883
+ try: () => parse(decoded.type, decoded.data),
884
+ catch: (cause) => new Error$3({
885
+ cause,
886
+ message: "DoH returned invalid DNS record data",
887
+ reason: "response"
888
+ })
889
+ });
890
+ if (answer.ttl === void 0) return yield* new Error$3({
891
+ message: "DoH response omitted the DNS record TTL",
892
+ reason: "response"
893
+ });
894
+ return {
895
+ data,
896
+ name,
897
+ ttl: answer.ttl,
898
+ type: decoded.type
899
+ };
900
+ }).pipe(Effect.mapError((cause) => cause instanceof Error$3 ? cause : new Error$3({
901
+ cause,
902
+ message: cause.message,
903
+ reason: "response"
904
+ })));
905
+ }
906
+ function answerData(answer) {
907
+ switch (answer.type) {
908
+ case "A":
909
+ case "AAAA":
910
+ case "CNAME":
911
+ case "NS": return {
912
+ data: answer.data,
913
+ type: answer.type
914
+ };
915
+ case "CAA": return {
916
+ data: `${answer.data.flags ?? 0} ${answer.data.tag} ${answer.data.value}`,
917
+ type: answer.type
918
+ };
919
+ case "MX": return {
920
+ data: `${requiredNumber(answer.data.preference, "MX preference")} ${answer.data.exchange}`,
921
+ type: answer.type
922
+ };
923
+ case "SRV": return {
924
+ data: [
925
+ requiredNumber(answer.data.priority, "SRV priority"),
926
+ requiredNumber(answer.data.weight, "SRV weight"),
927
+ requiredNumber(answer.data.port, "SRV port"),
928
+ answer.data.target
929
+ ].join(" "),
930
+ type: answer.type
931
+ };
932
+ case "TXT": return {
933
+ data: decodeTxt(answer.data),
934
+ type: answer.type
935
+ };
936
+ default: return;
937
+ }
938
+ }
939
+ function decodeTxt(data) {
940
+ const encoded = (Array.isArray(data) ? data : [data]).map((chunk) => typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk);
941
+ const length = encoded.reduce((total, chunk) => total + chunk.length, 0);
942
+ const joined = new Uint8Array(length);
943
+ let offset = 0;
944
+ for (const chunk of encoded) {
945
+ joined.set(chunk, offset);
946
+ offset += chunk.length;
947
+ }
948
+ return new TextDecoder("utf-8", { fatal: true }).decode(joined);
949
+ }
950
+ function requiredNumber(value, field) {
951
+ if (value === void 0) throw new Error(`DoH response omitted ${field}`);
952
+ return value;
953
+ }
954
+ async function request(input) {
955
+ const controller = new AbortController();
956
+ let timedOut = false;
957
+ const abortFromEffect = () => controller.abort(input.effectSignal.reason);
958
+ const abortFromHost = () => controller.abort(input.query.signal?.reason);
959
+ input.effectSignal.addEventListener("abort", abortFromEffect, { once: true });
960
+ input.query.signal?.addEventListener("abort", abortFromHost, { once: true });
961
+ const timer = setTimeout(() => {
962
+ timedOut = true;
963
+ controller.abort(/* @__PURE__ */ new Error("DNS resolution timed out"));
964
+ }, input.timeoutMs);
965
+ try {
966
+ const query = Uint8Array.from(DnsPacket.encode({
967
+ flags: DnsPacket.RECURSION_DESIRED,
968
+ id: 0,
969
+ questions: [{
970
+ name: input.query.name,
971
+ type: input.query.type
972
+ }],
973
+ type: "query"
974
+ }));
975
+ const response = await input.fetch(new URL(input.endpoint), {
976
+ body: query,
977
+ headers: {
978
+ accept: "application/dns-message",
979
+ "content-type": "application/dns-message"
980
+ },
981
+ method: "POST",
982
+ signal: controller.signal
983
+ });
984
+ if (!response.ok) throw new Error$3({
985
+ message: `DoH returned HTTP ${response.status}`,
986
+ reason: "transport"
987
+ });
988
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
989
+ if (contentType !== "application/dns-message") throw new Error$3({
990
+ message: `DoH returned unsupported content type ${contentType ?? "<missing>"}`,
991
+ reason: "response"
992
+ });
993
+ return new Uint8Array(await response.arrayBuffer());
994
+ } catch (cause) {
995
+ if (timedOut) throw new Error$3({
996
+ message: "DNS query timed out",
997
+ reason: "timeout"
998
+ });
999
+ throw cause;
1000
+ } finally {
1001
+ clearTimeout(timer);
1002
+ input.effectSignal.removeEventListener("abort", abortFromEffect);
1003
+ input.query.signal?.removeEventListener("abort", abortFromHost);
1004
+ }
1005
+ }
1006
+ //#endregion
1007
+ //#region src/verification/cloudflare-doh.ts
1008
+ var cloudflare_doh_exports = /* @__PURE__ */ __exportAll({
1009
+ layer: () => layer,
1010
+ make: () => make,
1011
+ toAsync: () => toAsync
1012
+ });
1013
+ const endpoint = "https://cloudflare-dns.com/dns-query";
1014
+ function make(options = {}) {
1015
+ return make$1({
1016
+ ...options,
1017
+ endpoint: options.endpoint ?? endpoint
1018
+ });
1019
+ }
1020
+ const layer = (options = {}) => Layer.succeed(Service$4, make(options));
1021
+ const toAsync = (options = {}) => toAsync$2(make(options));
1022
+ //#endregion
1023
+ //#region src/verification/verify.ts
1024
+ var verify_exports = /* @__PURE__ */ __exportAll({
1025
+ ProviderObservation: () => ProviderObservation,
1026
+ PublicDnsObservation: () => PublicDnsObservation,
1027
+ Result: () => Result,
1028
+ record: () => record
1029
+ });
1030
+ const ProviderObservation = Schema.TaggedUnion({
1031
+ match: {},
1032
+ missing: {},
1033
+ mismatch: { records: Schema.Array(Schema$5) },
1034
+ failure: { message: Schema.String }
1035
+ });
1036
+ const PublicDnsObservation = Schema.TaggedUnion({
1037
+ propagated: {},
1038
+ missing: {},
1039
+ mismatch: { answers: Schema.Array(Schema.String) },
1040
+ timeout: {},
1041
+ failure: { message: Schema.String }
1042
+ });
1043
+ const Result = Schema.Struct({
1044
+ provider: ProviderObservation,
1045
+ publicDns: PublicDnsObservation,
1046
+ status: Schema.Literals([
1047
+ "verified",
1048
+ "pending",
1049
+ "mismatch",
1050
+ "unavailable"
1051
+ ])
1052
+ });
1053
+ const record = Effect.fn("Verification.record")(function* (input) {
1054
+ const provider = yield* Service;
1055
+ const resolver = yield* Service$4;
1056
+ const [providerObservation, publicDns] = yield* Effect.all([observeProvider(provider, input.zone, input.record).pipe(Effect.catch((failure) => Effect.succeed({
1057
+ _tag: "failure",
1058
+ message: failure.message
1059
+ }))), resolver.resolve({
1060
+ name: input.record.name,
1061
+ type: input.record._tag
1062
+ }).pipe(Effect.match({
1063
+ onFailure: (failure) => failure.reason === "timeout" ? { _tag: "timeout" } : {
1064
+ _tag: "failure",
1065
+ message: failure.message
1066
+ },
1067
+ onSuccess: (resolution) => observePublicDns(input.record, resolution)
1068
+ }))], { concurrency: "unbounded" });
1069
+ return {
1070
+ provider: providerObservation,
1071
+ publicDns,
1072
+ status: providerObservation._tag === "match" && publicDns._tag === "propagated" ? "verified" : providerObservation._tag === "failure" || publicDns._tag === "failure" || publicDns._tag === "timeout" ? "unavailable" : providerObservation._tag === "mismatch" || publicDns._tag === "mismatch" ? "mismatch" : "pending"
1073
+ };
1074
+ });
1075
+ function observeProvider(provider, zone, requirement) {
1076
+ return provider.listRecords(zone).pipe(Effect.map((records) => {
1077
+ if (records.some((existing) => existing._tag !== "Opaque" && equals(existing, requirement))) return { _tag: "match" };
1078
+ const sameSet = records.filter((existing) => existing._tag !== "Opaque" && existing.name === requirement.name && existing._tag === requirement._tag);
1079
+ return sameSet.length === 0 ? { _tag: "missing" } : {
1080
+ _tag: "mismatch",
1081
+ records: sameSet
1082
+ };
1083
+ }));
1084
+ }
1085
+ function observePublicDns(requirement, resolution) {
1086
+ if (resolution._tag === "nodata") return { _tag: "missing" };
1087
+ const expected = parse(requirement._tag, recordValue(requirement));
1088
+ return resolution.answers.some((answer) => answer.name === requirement.name && answer.type === requirement._tag && parse(answer.type, answer.data) === expected) ? { _tag: "propagated" } : {
1089
+ _tag: "mismatch",
1090
+ answers: resolution.answers.map(({ data }) => data)
1091
+ };
1092
+ }
1093
+ function recordValue(requirement) {
1094
+ const data$1 = data(requirement);
1095
+ switch (requirement._tag) {
1096
+ case "A":
1097
+ case "AAAA": return String(data$1.address);
1098
+ case "CNAME":
1099
+ case "NS": return String(data$1.target);
1100
+ case "TXT": return String(data$1.value);
1101
+ case "MX": return `${data$1.priority} ${data$1.exchange}`;
1102
+ case "CAA": return `${data$1.flags} ${data$1.tag} ${data$1.value}`;
1103
+ case "SRV": return `${data$1.priority} ${data$1.weight} ${data$1.port} ${data$1.target}`;
1104
+ }
1105
+ }
1106
+ //#endregion
1107
+ export { decode$1 as A, Capability as B, types_exports as C, token_exports as D, connect as E, refresh as F, decode$2 as G, Schema$3 as H, revoke as I, encode$1 as K, canonical_json_exports as L, begin as M, complete as N, Method as O, oauth_exports as P, webCryptoLayer as R, encodeReceipt as S, zones_exports as T, assertGrant as U, Grant as V, connection_exports as W, Receipt as _, doh_exports as a, decodeReceipt as b, authorize as c, authorize$1 as d, create as f, Operation as g, Authorization as h, toAsync as i, manifest_exports as j, Schema$2 as k, connection_authorization_exports as l, renderManualInstructions as m, verify_exports as n, toAsync$1 as o, plan_exports as p, version as q, cloudflare_doh_exports as r, dns_data_exports as s, record as t, apply as u, Schema$1 as v, selection_exports as w, encode as x, decode as y, AuthorizationError$1 as z };
1108
+
1109
+ //# sourceMappingURL=verify-CeMW6XtK.mjs.map