domainkit 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/Cloudflare.mjs +1 -0
- package/dist/Cloudflare.mjs.map +1 -1
- package/dist/Connect.mjs +17 -2
- package/dist/Connect.mjs.map +1 -1
- package/dist/Provider.mjs.map +1 -1
- package/dist/Server.mjs +9 -2
- package/dist/Server.mjs.map +1 -1
- package/dist/Testing.mjs +20 -18
- package/dist/Testing.mjs.map +1 -1
- package/dist/Vercel.mjs +3 -1
- package/dist/Vercel.mjs.map +1 -1
- package/dist/internal/cloudflare/client.mjs +10 -5
- package/dist/internal/cloudflare/client.mjs.map +1 -1
- package/dist/internal/conformance/provider.mjs +31 -18
- package/dist/internal/conformance/provider.mjs.map +1 -1
- package/dist/internal/http.mjs +7 -2
- package/dist/internal/http.mjs.map +1 -1
- package/dist/package.mjs +1 -1
- package/dist/types/Connect.d.ts +28 -0
- package/dist/types/Provider.d.ts +6 -0
- package/dist/types/Server.d.ts +4 -0
- package/dist/types/Testing.d.ts +3 -1
- package/dist/types/Vercel.d.ts +1 -1
- package/dist/types/internal/cloudflare/client.d.ts +4 -2
- package/dist/types/internal/conformance/provider.d.ts +10 -3
- package/dist/types/internal/http.d.ts +5 -0
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@ import { DomainKitError, fail } from "../error.mjs";
|
|
|
4
4
|
import { Service } from "../../Custody.mjs";
|
|
5
5
|
import { fresh } from "../ids.mjs";
|
|
6
6
|
import { Service as Service$1, make } from "../../Principal.mjs";
|
|
7
|
-
import { encodeContext } from "../../Provider.mjs";
|
|
7
|
+
import { encodeContext, tokenFields } from "../../Provider.mjs";
|
|
8
8
|
import { Service as Service$2 } from "../../Resolver.mjs";
|
|
9
9
|
import { applied } from "../../Receipt.mjs";
|
|
10
10
|
import { Attachment, Authorization, Credential, Service as Service$3 } from "../../Storage.mjs";
|
|
@@ -12,7 +12,7 @@ import { attach, session } from "../../Connect.mjs";
|
|
|
12
12
|
import { apply, approve, plan } from "../../Provision.mjs";
|
|
13
13
|
import { apply as apply$1, approve as approve$1, plan as plan$1 } from "../../Cleanup.mjs";
|
|
14
14
|
import { layerMemory } from "../../DomainKit.mjs";
|
|
15
|
-
import { DateTime, Effect, Layer } from "effect";
|
|
15
|
+
import { DateTime, Effect, Layer, Redacted } from "effect";
|
|
16
16
|
//#region src/internal/conformance/provider.ts
|
|
17
17
|
const principal = make({
|
|
18
18
|
ownerId: "conformance",
|
|
@@ -67,8 +67,9 @@ const txt = (zone, label, value) => txt$1({
|
|
|
67
67
|
});
|
|
68
68
|
const recordIds = (receipt) => applied(receipt).map(({ providerRecordId }) => providerRecordId);
|
|
69
69
|
/**
|
|
70
|
-
* Runs create/readback/cleanup, exact-noop, conflict, stale-plan,
|
|
71
|
-
* real provider definition, through the same Provision and Cleanup
|
|
70
|
+
* Runs create/readback/cleanup, exact-noop, conflict, stale-plan, partial-apply, and
|
|
71
|
+
* rejected-token against a real provider definition, through the same Provision and Cleanup
|
|
72
|
+
* services hosts use.
|
|
72
73
|
*/
|
|
73
74
|
const provider = (definition, credential, zone, options = {}) => {
|
|
74
75
|
const prefix = options.prefix ?? "domainkit-conformance";
|
|
@@ -86,12 +87,12 @@ const provider = (definition, credential, zone, options = {}) => {
|
|
|
86
87
|
const name = "create-readback-cleanup";
|
|
87
88
|
return Effect.gen(function* () {
|
|
88
89
|
const requirements = [cname(zone, `${prefix}-create`), txt(zone, `${prefix}-page`, "domainkit")];
|
|
89
|
-
const plan$
|
|
90
|
+
const plan$4 = yield* plan({
|
|
90
91
|
domain: attachment.domain,
|
|
91
92
|
requirements
|
|
92
93
|
});
|
|
93
|
-
yield* expect(name, plan$
|
|
94
|
-
const receipt = yield* apply(yield* approve(plan$
|
|
94
|
+
yield* expect(name, plan$4.operations.every(({ _tag }) => _tag === "Create"), "expected two Create operations");
|
|
95
|
+
const receipt = yield* apply(yield* approve(plan$4));
|
|
95
96
|
created = recordIds(receipt);
|
|
96
97
|
yield* expect(name, receipt.status === "complete" && created.length === 2, "apply must return a complete receipt with provider record ids");
|
|
97
98
|
const observed = yield* dns.list(zone);
|
|
@@ -111,12 +112,12 @@ const provider = (definition, credential, zone, options = {}) => {
|
|
|
111
112
|
const requirement = cname(zone, `${prefix}-exact`);
|
|
112
113
|
const { providerRecordId } = yield* dns.create(zone, requirement);
|
|
113
114
|
created = [providerRecordId];
|
|
114
|
-
const plan$
|
|
115
|
+
const plan$5 = yield* plan({
|
|
115
116
|
domain: attachment.domain,
|
|
116
117
|
requirements: [requirement]
|
|
117
118
|
});
|
|
118
|
-
yield* expect(name, plan$
|
|
119
|
-
const receipt = yield* apply(yield* approve(plan$
|
|
119
|
+
yield* expect(name, plan$5.operations[0]?._tag === "Noop", "an exact record must plan as Noop");
|
|
120
|
+
const receipt = yield* apply(yield* approve(plan$5));
|
|
120
121
|
yield* expect(name, applied(receipt).length === 0, "an exact plan must not create another record");
|
|
121
122
|
}).pipe(Effect.ensuring(cleanup(dns, () => created)));
|
|
122
123
|
});
|
|
@@ -126,12 +127,12 @@ const provider = (definition, credential, zone, options = {}) => {
|
|
|
126
127
|
return Effect.gen(function* () {
|
|
127
128
|
const { providerRecordId } = yield* dns.create(zone, txt(zone, `${prefix}-conflict`, "occupied"));
|
|
128
129
|
created = [providerRecordId];
|
|
129
|
-
const plan$
|
|
130
|
+
const plan$3 = yield* plan({
|
|
130
131
|
domain: attachment.domain,
|
|
131
132
|
requirements: [cname(zone, `${prefix}-conflict`)]
|
|
132
133
|
});
|
|
133
|
-
yield* expect(name, plan$
|
|
134
|
-
const rejected = yield* approve(plan$
|
|
134
|
+
yield* expect(name, plan$3.operations[0]?._tag === "Conflict", "a CNAME over an occupied name must plan as Conflict");
|
|
135
|
+
const rejected = yield* approve(plan$3).pipe(Effect.result);
|
|
135
136
|
yield* expect(name, rejected._tag === "Failure" && rejected.failure.reason._tag === "Conflict", "approve must fail closed on conflicts");
|
|
136
137
|
}).pipe(Effect.ensuring(cleanup(dns, () => created)));
|
|
137
138
|
});
|
|
@@ -140,11 +141,11 @@ const provider = (definition, credential, zone, options = {}) => {
|
|
|
140
141
|
const name = "stale-plan";
|
|
141
142
|
return Effect.gen(function* () {
|
|
142
143
|
const requirement = cname(zone, `${prefix}-stale`);
|
|
143
|
-
const plan$
|
|
144
|
+
const plan$6 = yield* plan({
|
|
144
145
|
domain: attachment.domain,
|
|
145
146
|
requirements: [requirement]
|
|
146
147
|
});
|
|
147
|
-
const approval = yield* approve(plan$
|
|
148
|
+
const approval = yield* approve(plan$6);
|
|
148
149
|
const { providerRecordId } = yield* dns.create(zone, requirement);
|
|
149
150
|
created = [providerRecordId];
|
|
150
151
|
const stale = yield* apply(approval).pipe(Effect.result);
|
|
@@ -177,11 +178,11 @@ const provider = (definition, credential, zone, options = {}) => {
|
|
|
177
178
|
let created = [];
|
|
178
179
|
const name = "partial-apply-cleanup";
|
|
179
180
|
return Effect.gen(function* () {
|
|
180
|
-
const plan$
|
|
181
|
+
const plan$2 = yield* plan({
|
|
181
182
|
domain: attachment.domain,
|
|
182
183
|
requirements: [cname(zone, `${prefix}-partial-one`), txt(zone, `${prefix}-partial-two`, "domainkit")]
|
|
183
184
|
});
|
|
184
|
-
const receipt = yield* apply(yield* approve(plan$
|
|
185
|
+
const receipt = yield* apply(yield* approve(plan$2));
|
|
185
186
|
created = recordIds(receipt);
|
|
186
187
|
yield* expect(name, receipt.status === "partial" && created.length === 1, "a later write failure must preserve the first confirmed write in a partial receipt");
|
|
187
188
|
const cleanupPlan = yield* plan$1({ receiptId: receipt.id });
|
|
@@ -191,12 +192,24 @@ const provider = (definition, credential, zone, options = {}) => {
|
|
|
191
192
|
created = [];
|
|
192
193
|
}).pipe(Effect.ensuring(cleanup(dns, () => created)));
|
|
193
194
|
});
|
|
195
|
+
/** A token the provider rejects must read as `Unauthenticated`, so a host tells the customer the provider refused it. */
|
|
196
|
+
const rejectedToken = Effect.gen(function* () {
|
|
197
|
+
const name = "rejected-token";
|
|
198
|
+
const auth = definition.auth.token;
|
|
199
|
+
if (auth === void 0) return;
|
|
200
|
+
const required = tokenFields(auth).filter((field) => field.required);
|
|
201
|
+
if (options.rejectedToken === void 0 && required.some((field) => !field.secret)) return yield* Effect.fail(failure(name, `the token method requires ${required.filter((field) => !field.secret).map((field) => field.name).join(", ")}; pass options.rejectedToken with values the provider rejects`));
|
|
202
|
+
const values = options.rejectedToken ?? Object.fromEntries(required.map((field) => [field.name, Redacted.make("")]));
|
|
203
|
+
const outcome = yield* auth.authenticate(values).pipe(Effect.result);
|
|
204
|
+
yield* expect(name, outcome._tag === "Failure" && outcome.failure.reason._tag === "Unauthenticated", "authenticating a rejected token must fail Unauthenticated");
|
|
205
|
+
});
|
|
194
206
|
return Effect.all([
|
|
195
207
|
createReadbackCleanup,
|
|
196
208
|
exactNoop,
|
|
197
209
|
conflict,
|
|
198
210
|
stalePlan,
|
|
199
|
-
partialApplyCleanup
|
|
211
|
+
partialApplyCleanup,
|
|
212
|
+
rejectedToken
|
|
200
213
|
], { discard: true });
|
|
201
214
|
};
|
|
202
215
|
/** Verification is out of scope for the provider contract; keep the pool quiet. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.mjs","names":["Principal.make","Errors.DomainKitError","Reason.InvalidInput","Storage.Service","Custody.Service","Storage.Authorization","Provider.encodeContext","Storage.Credential","Connect.attach","Storage.Attachment","DnsRecord.cname","DnsRecord.txt","Receipt.applied","Connect.session","session","Principal.Service","DomainKit.layerMemory","Resolver.Service","plan","Provision.plan","Provision.apply","Provision.approve","DnsRecord.equals","Cleanup.plan","Cleanup.apply","Cleanup.approve","Errors.fail","Reason.ProviderUnavailable"],"sources":["../../../src/internal/conformance/provider.ts"],"sourcesContent":["import { DateTime, Effect, Layer } from \"effect\";\n\nimport * as Cleanup from \"../../Cleanup.ts\";\nimport * as Connect from \"../../Connect.ts\";\nimport * as Custody from \"../../Custody.ts\";\nimport * as DnsRecord from \"../../DnsRecord.ts\";\nimport * as Errors from \"../error.ts\";\nimport * as Reason from \"../../Reason.ts\";\nimport * as DomainKit from \"../../DomainKit.ts\";\nimport * as Principal from \"../../Principal.ts\";\nimport * as Provider from \"../../Provider.ts\";\nimport * as Provision from \"../../Provision.ts\";\nimport * as Receipt from \"../../Receipt.ts\";\nimport * as Resolver from \"../../Resolver.ts\";\nimport * as Storage from \"../../Storage.ts\";\nimport { fresh } from \"../ids.ts\";\n\nexport const cases = [\n \"create-readback-cleanup\",\n \"exact-noop\",\n \"conflict\",\n \"stale-plan\",\n \"partial-apply-cleanup\",\n] as const;\nexport type Case = (typeof cases)[number];\n\nconst principal = Principal.make({ ownerId: \"conformance\", actorId: \"conformance\" });\n\nconst failure = (name: Case, message: string) =>\n new Errors.DomainKitError({\n reason: new Reason.InvalidInput({\n message: `provider conformance ${name}: ${message}`,\n field: \"conformance\",\n }),\n });\n\nconst expect = (name: Case, condition: boolean, message: string) =>\n condition ? Effect.void : Effect.fail(failure(name, message));\n\ntype Env = Storage.Service | Connect.Service | Provision.Service | Cleanup.Service;\n\n/** Attach `zone` to a connection built straight from `credential`, bypassing `authenticate`. */\nconst attachZone = (\n definition: Provider.Definition,\n credential: Provider.Credential,\n zone: string,\n) =>\n Effect.gen(function* () {\n const storage = yield* Storage.Service;\n const custody = yield* Custody.Service;\n const now = yield* DateTime.now;\n const authorization = new Storage.Authorization({\n id: yield* fresh(\"auth\"),\n ownerId: principal.ownerId,\n provider: definition.id,\n method: \"token\",\n capabilities: [\"dns:read\", \"dns:write\"],\n context: yield* Provider.encodeContext(definition, credential.context),\n revocation: \"active\",\n createdBy: principal.actorId,\n createdAt: now,\n });\n yield* storage.authorizations.upsert({\n authorization,\n credential: new Storage.Credential({\n ciphertext: yield* custody.seal(credential.secret),\n expiresAt: null,\n rotatedAt: now,\n }),\n });\n const connection = yield* storage.connections.create(authorization.id);\n const attached = yield* Connect.attach({ connectionId: connection.id, domain: zone });\n if (!(attached instanceof Storage.Attachment)) {\n return yield* Effect.fail(\n failure(\"create-readback-cleanup\", `zone ${zone} needs a selection; pass an exact zone`),\n );\n }\n return attached;\n });\n\nconst cname = (zone: string, label: string) =>\n DnsRecord.cname({ name: `${label}.${zone}`, target: \"target.example.net\", ttl: 300 });\nconst txt = (zone: string, label: string, value: string) =>\n DnsRecord.txt({ name: `${label}.${zone}`, value, ttl: 300 });\n\nconst recordIds = (receipt: Receipt.Model) =>\n Receipt.applied(receipt).map(({ providerRecordId }) => providerRecordId);\n\n/**\n * Runs create/readback/cleanup, exact-noop, conflict, stale-plan, and partial-apply against a\n * real provider definition, through the same Provision and Cleanup services hosts use.\n */\nexport const provider = (\n definition: Provider.Definition,\n credential: Provider.Credential,\n zone: string,\n options: { readonly prefix?: string } = {},\n): Effect.Effect<void, Errors.DomainKitError> => {\n const prefix = options.prefix ?? \"domainkit-conformance\";\n const run = <A>(\n target: Provider.Definition,\n body: (\n dns: Provider.Dns,\n attachment: Storage.Attachment,\n ) => Effect.Effect<A, Errors.DomainKitError, Env | Principal.Service>,\n ) =>\n Effect.gen(function* () {\n const attachment = yield* attachZone(target, credential, zone);\n const { session, target: resolved } = yield* Connect.session(attachment.id);\n return yield* body(session.dns(resolved), attachment);\n }).pipe(\n Effect.provideService(Principal.Service, principal),\n Effect.provide(\n DomainKit.layerMemory({\n providers: [target],\n resolver: Layer.succeed(Resolver.Service)(silentResolver),\n }),\n ),\n );\n\n const cleanup = (dns: Provider.Dns, ids: () => ReadonlyArray<string>) =>\n Effect.suspend(() =>\n Effect.forEach(ids(), (id) => dns.delete(zone, id).pipe(Effect.ignore), { discard: true }),\n );\n\n const createReadbackCleanup = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"create-readback-cleanup\";\n return Effect.gen(function* () {\n const requirements = [\n cname(zone, `${prefix}-create`),\n txt(zone, `${prefix}-page`, \"domainkit\"),\n ];\n const plan = yield* Provision.plan({ domain: attachment.domain, requirements });\n yield* expect(\n name,\n plan.operations.every(({ _tag }) => _tag === \"Create\"),\n \"expected two Create operations\",\n );\n const receipt = yield* Provision.apply(yield* Provision.approve(plan));\n created = recordIds(receipt);\n yield* expect(\n name,\n receipt.status === \"complete\" && created.length === 2,\n \"apply must return a complete receipt with provider record ids\",\n );\n const observed = yield* dns.list(zone);\n yield* expect(\n name,\n requirements.every((requirement) =>\n observed.some(({ record }) => DnsRecord.equals(record, requirement)),\n ),\n \"list must return every created record, including across provider pages\",\n );\n const cleanupPlan = yield* Cleanup.plan({ receiptId: receipt.id });\n yield* expect(\n name,\n cleanupPlan.operations.every(({ _tag }) => _tag === \"Delete\"),\n \"cleanup plan must delete both records\",\n );\n const cleaned = yield* Cleanup.apply(yield* Cleanup.approve(cleanupPlan));\n const remaining = yield* Effect.forEach(created, (id) => dns.get(zone, id));\n yield* expect(\n name,\n cleaned.status === \"complete\" && remaining.every((record) => record === null),\n \"receipt-bound cleanup must remove every created record\",\n );\n created = [];\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const exactNoop = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"exact-noop\";\n return Effect.gen(function* () {\n const requirement = cname(zone, `${prefix}-exact`);\n const { providerRecordId } = yield* dns.create(zone, requirement);\n created = [providerRecordId];\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [requirement],\n });\n yield* expect(name, plan.operations[0]?._tag === \"Noop\", \"an exact record must plan as Noop\");\n const receipt = yield* Provision.apply(yield* Provision.approve(plan));\n yield* expect(\n name,\n Receipt.applied(receipt).length === 0,\n \"an exact plan must not create another record\",\n );\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const conflict = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"conflict\";\n return Effect.gen(function* () {\n const { providerRecordId } = yield* dns.create(\n zone,\n txt(zone, `${prefix}-conflict`, \"occupied\"),\n );\n created = [providerRecordId];\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [cname(zone, `${prefix}-conflict`)],\n });\n yield* expect(\n name,\n plan.operations[0]?._tag === \"Conflict\",\n \"a CNAME over an occupied name must plan as Conflict\",\n );\n const rejected = yield* Provision.approve(plan).pipe(Effect.result);\n yield* expect(\n name,\n rejected._tag === \"Failure\" && rejected.failure.reason._tag === \"Conflict\",\n \"approve must fail closed on conflicts\",\n );\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const stalePlan = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"stale-plan\";\n return Effect.gen(function* () {\n const requirement = cname(zone, `${prefix}-stale`);\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [requirement],\n });\n const approval = yield* Provision.approve(plan);\n const { providerRecordId } = yield* dns.create(zone, requirement);\n created = [providerRecordId];\n const stale = yield* Provision.apply(approval).pipe(Effect.result);\n yield* expect(\n name,\n stale._tag === \"Failure\" && stale.failure.reason._tag === \"Stale\",\n \"apply must reject provider state that changed after approval\",\n );\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const flaky: Provider.Definition = {\n ...definition,\n session: (input) => {\n const session = definition.session(input);\n return {\n ...session,\n dns: (target) => {\n const dns = session.dns(target);\n let writes = 0;\n return {\n ...dns,\n create: (targetZone, record) => {\n writes += 1;\n return writes === 2\n ? Errors.fail(\n new Reason.ProviderUnavailable({\n provider: definition.id,\n message: \"injected conformance failure\",\n }),\n )\n : dns.create(targetZone, record);\n },\n };\n },\n };\n },\n };\n\n const partialApplyCleanup = run(flaky, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"partial-apply-cleanup\";\n return Effect.gen(function* () {\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [\n cname(zone, `${prefix}-partial-one`),\n txt(zone, `${prefix}-partial-two`, \"domainkit\"),\n ],\n });\n const receipt = yield* Provision.apply(yield* Provision.approve(plan));\n created = recordIds(receipt);\n yield* expect(\n name,\n receipt.status === \"partial\" && created.length === 1,\n \"a later write failure must preserve the first confirmed write in a partial receipt\",\n );\n const cleanupPlan = yield* Cleanup.plan({ receiptId: receipt.id });\n yield* Cleanup.apply(yield* Cleanup.approve(cleanupPlan));\n const remaining = yield* Effect.forEach(created, (id) => dns.get(zone, id));\n yield* expect(\n name,\n remaining.every((record) => record === null),\n \"partial receipt cleanup must remove the confirmed write\",\n );\n created = [];\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n return Effect.all([createReadbackCleanup, exactNoop, conflict, stalePlan, partialApplyCleanup], {\n discard: true,\n });\n};\n\n/** Verification is out of scope for the provider contract; keep the pool quiet. */\nconst silentResolver: Resolver.Interface = {\n resolve: () => Effect.succeed([]),\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,MAAM,YAAYA,KAAe;CAAE,SAAS;CAAe,SAAS;AAAc,CAAC;AAEnF,MAAM,WAAW,MAAY,YAC3B,IAAIC,eAAsB,EACxB,QAAQ,IAAIC,aAAoB;CAC9B,SAAS,wBAAwB,KAAK,IAAI;CAC1C,OAAO;AACT,CAAC,EACH,CAAC;AAEH,MAAM,UAAU,MAAY,WAAoB,YAC9C,YAAY,OAAO,OAAO,OAAO,KAAK,QAAQ,MAAM,OAAO,CAAC;;AAK9D,MAAM,cACJ,YACA,YACA,SAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,OAAOC;CACvB,MAAM,UAAU,OAAOC;CACvB,MAAM,MAAM,OAAO,SAAS;CAC5B,MAAM,gBAAgB,IAAIC,cAAsB;EAC9C,IAAI,OAAO,MAAM,MAAM;EACvB,SAAS,UAAU;EACnB,UAAU,WAAW;EACrB,QAAQ;EACR,cAAc,CAAC,YAAY,WAAW;EACtC,SAAS,OAAOC,cAAuB,YAAY,WAAW,OAAO;EACrE,YAAY;EACZ,WAAW,UAAU;EACrB,WAAW;CACb,CAAC;CACD,OAAO,QAAQ,eAAe,OAAO;EACnC;EACA,YAAY,IAAIC,WAAmB;GACjC,YAAY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W,CAChD;GACF,CAAC;GACD,MAAM,UAAU,OAAOC,MAAgB,OAAOC,QAAkBH,MAAI,CAAC;GACrE,UAAU,UAAU,OAAO;GAC3B,OAAO,OACL,MACA,QAAQ,WAAW,aAAa,QAAQ,WAAW,GACnD,oFACF;GACA,MAAM,cAAc,OAAOK,OAAa,EAAE,WAAW,QAAQ,GAAG,CAAC;GACjE,OAAOC,QAAc,OAAOC,UAAgB,WAAW,CAAC;GACxD,MAAM,YAAY,OAAO,OAAO,QAAQ,UAAU,OAAO,IAAI,IAAI,MAAM,EAAE,CAAC;GAC1E,OAAO,OACL,MACA,UAAU,OAAO,WAAW,WAAW,IAAI,GAC3C,yDACF;GACA,UAAU,CAAC;EACb,CAAC,CAAC,CAAC,KAAK,OAAO,SAAS,QAAQ,WAAW,OAAO,CAAC,CAAC;CACtD,CAAC;CAED,OAAO,OAAO,IAAI;EAAC;EAAuB;EAAW;EAAU;EAAW;CAAmB,GAAG,EAC9F,SAAS,KACX,CAAC;AACH;;AAGA,MAAM,iBAAqC,EACzC,eAAe,OAAO,QAAQ,CAAC,CAAC,EAClC"}
|
|
1
|
+
{"version":3,"file":"provider.mjs","names":["Principal.make","Errors.DomainKitError","Reason.InvalidInput","Storage.Service","Custody.Service","Storage.Authorization","Provider.encodeContext","Storage.Credential","Connect.attach","Storage.Attachment","DnsRecord.cname","DnsRecord.txt","Receipt.applied","Connect.session","session","Principal.Service","DomainKit.layerMemory","Resolver.Service","plan","Provision.plan","Provision.apply","Provision.approve","DnsRecord.equals","Cleanup.plan","Cleanup.apply","Cleanup.approve","Errors.fail","Reason.ProviderUnavailable","Provider.tokenFields"],"sources":["../../../src/internal/conformance/provider.ts"],"sourcesContent":["import { DateTime, Effect, Layer, Redacted } from \"effect\";\n\nimport * as Cleanup from \"../../Cleanup.ts\";\nimport * as Connect from \"../../Connect.ts\";\nimport * as Custody from \"../../Custody.ts\";\nimport * as DnsRecord from \"../../DnsRecord.ts\";\nimport * as Errors from \"../error.ts\";\nimport * as Reason from \"../../Reason.ts\";\nimport * as DomainKit from \"../../DomainKit.ts\";\nimport * as Principal from \"../../Principal.ts\";\nimport * as Provider from \"../../Provider.ts\";\nimport * as Provision from \"../../Provision.ts\";\nimport * as Receipt from \"../../Receipt.ts\";\nimport * as Resolver from \"../../Resolver.ts\";\nimport * as Storage from \"../../Storage.ts\";\nimport { fresh } from \"../ids.ts\";\n\nexport const cases = [\n \"create-readback-cleanup\",\n \"exact-noop\",\n \"conflict\",\n \"stale-plan\",\n \"partial-apply-cleanup\",\n \"rejected-token\",\n] as const;\nexport type Case = (typeof cases)[number];\n\nconst principal = Principal.make({ ownerId: \"conformance\", actorId: \"conformance\" });\n\nconst failure = (name: Case, message: string) =>\n new Errors.DomainKitError({\n reason: new Reason.InvalidInput({\n message: `provider conformance ${name}: ${message}`,\n field: \"conformance\",\n }),\n });\n\nconst expect = (name: Case, condition: boolean, message: string) =>\n condition ? Effect.void : Effect.fail(failure(name, message));\n\ntype Env = Storage.Service | Connect.Service | Provision.Service | Cleanup.Service;\n\n/** Attach `zone` to a connection built straight from `credential`, bypassing `authenticate`. */\nconst attachZone = (\n definition: Provider.Definition,\n credential: Provider.Credential,\n zone: string,\n) =>\n Effect.gen(function* () {\n const storage = yield* Storage.Service;\n const custody = yield* Custody.Service;\n const now = yield* DateTime.now;\n const authorization = new Storage.Authorization({\n id: yield* fresh(\"auth\"),\n ownerId: principal.ownerId,\n provider: definition.id,\n method: \"token\",\n capabilities: [\"dns:read\", \"dns:write\"],\n context: yield* Provider.encodeContext(definition, credential.context),\n revocation: \"active\",\n createdBy: principal.actorId,\n createdAt: now,\n });\n yield* storage.authorizations.upsert({\n authorization,\n credential: new Storage.Credential({\n ciphertext: yield* custody.seal(credential.secret),\n expiresAt: null,\n rotatedAt: now,\n }),\n });\n const connection = yield* storage.connections.create(authorization.id);\n const attached = yield* Connect.attach({ connectionId: connection.id, domain: zone });\n if (!(attached instanceof Storage.Attachment)) {\n return yield* Effect.fail(\n failure(\"create-readback-cleanup\", `zone ${zone} needs a selection; pass an exact zone`),\n );\n }\n return attached;\n });\n\nconst cname = (zone: string, label: string) =>\n DnsRecord.cname({ name: `${label}.${zone}`, target: \"target.example.net\", ttl: 300 });\nconst txt = (zone: string, label: string, value: string) =>\n DnsRecord.txt({ name: `${label}.${zone}`, value, ttl: 300 });\n\nconst recordIds = (receipt: Receipt.Model) =>\n Receipt.applied(receipt).map(({ providerRecordId }) => providerRecordId);\n\n/**\n * Runs create/readback/cleanup, exact-noop, conflict, stale-plan, partial-apply, and\n * rejected-token against a real provider definition, through the same Provision and Cleanup\n * services hosts use.\n */\nexport const provider = (\n definition: Provider.Definition,\n credential: Provider.Credential,\n zone: string,\n options: {\n readonly prefix?: string;\n /**\n * Token values the provider rejects, for the `rejected-token` case. Default: every required\n * field set to an empty secret, which needs a token method whose required fields are all\n * secrets.\n */\n readonly rejectedToken?: Provider.TokenValues;\n } = {},\n): Effect.Effect<void, Errors.DomainKitError> => {\n const prefix = options.prefix ?? \"domainkit-conformance\";\n const run = <A>(\n target: Provider.Definition,\n body: (\n dns: Provider.Dns,\n attachment: Storage.Attachment,\n ) => Effect.Effect<A, Errors.DomainKitError, Env | Principal.Service>,\n ) =>\n Effect.gen(function* () {\n const attachment = yield* attachZone(target, credential, zone);\n const { session, target: resolved } = yield* Connect.session(attachment.id);\n return yield* body(session.dns(resolved), attachment);\n }).pipe(\n Effect.provideService(Principal.Service, principal),\n Effect.provide(\n DomainKit.layerMemory({\n providers: [target],\n resolver: Layer.succeed(Resolver.Service)(silentResolver),\n }),\n ),\n );\n\n const cleanup = (dns: Provider.Dns, ids: () => ReadonlyArray<string>) =>\n Effect.suspend(() =>\n Effect.forEach(ids(), (id) => dns.delete(zone, id).pipe(Effect.ignore), { discard: true }),\n );\n\n const createReadbackCleanup = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"create-readback-cleanup\";\n return Effect.gen(function* () {\n const requirements = [\n cname(zone, `${prefix}-create`),\n txt(zone, `${prefix}-page`, \"domainkit\"),\n ];\n const plan = yield* Provision.plan({ domain: attachment.domain, requirements });\n yield* expect(\n name,\n plan.operations.every(({ _tag }) => _tag === \"Create\"),\n \"expected two Create operations\",\n );\n const receipt = yield* Provision.apply(yield* Provision.approve(plan));\n created = recordIds(receipt);\n yield* expect(\n name,\n receipt.status === \"complete\" && created.length === 2,\n \"apply must return a complete receipt with provider record ids\",\n );\n const observed = yield* dns.list(zone);\n yield* expect(\n name,\n requirements.every((requirement) =>\n observed.some(({ record }) => DnsRecord.equals(record, requirement)),\n ),\n \"list must return every created record, including across provider pages\",\n );\n const cleanupPlan = yield* Cleanup.plan({ receiptId: receipt.id });\n yield* expect(\n name,\n cleanupPlan.operations.every(({ _tag }) => _tag === \"Delete\"),\n \"cleanup plan must delete both records\",\n );\n const cleaned = yield* Cleanup.apply(yield* Cleanup.approve(cleanupPlan));\n const remaining = yield* Effect.forEach(created, (id) => dns.get(zone, id));\n yield* expect(\n name,\n cleaned.status === \"complete\" && remaining.every((record) => record === null),\n \"receipt-bound cleanup must remove every created record\",\n );\n created = [];\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const exactNoop = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"exact-noop\";\n return Effect.gen(function* () {\n const requirement = cname(zone, `${prefix}-exact`);\n const { providerRecordId } = yield* dns.create(zone, requirement);\n created = [providerRecordId];\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [requirement],\n });\n yield* expect(name, plan.operations[0]?._tag === \"Noop\", \"an exact record must plan as Noop\");\n const receipt = yield* Provision.apply(yield* Provision.approve(plan));\n yield* expect(\n name,\n Receipt.applied(receipt).length === 0,\n \"an exact plan must not create another record\",\n );\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const conflict = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"conflict\";\n return Effect.gen(function* () {\n const { providerRecordId } = yield* dns.create(\n zone,\n txt(zone, `${prefix}-conflict`, \"occupied\"),\n );\n created = [providerRecordId];\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [cname(zone, `${prefix}-conflict`)],\n });\n yield* expect(\n name,\n plan.operations[0]?._tag === \"Conflict\",\n \"a CNAME over an occupied name must plan as Conflict\",\n );\n const rejected = yield* Provision.approve(plan).pipe(Effect.result);\n yield* expect(\n name,\n rejected._tag === \"Failure\" && rejected.failure.reason._tag === \"Conflict\",\n \"approve must fail closed on conflicts\",\n );\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const stalePlan = run(definition, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"stale-plan\";\n return Effect.gen(function* () {\n const requirement = cname(zone, `${prefix}-stale`);\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [requirement],\n });\n const approval = yield* Provision.approve(plan);\n const { providerRecordId } = yield* dns.create(zone, requirement);\n created = [providerRecordId];\n const stale = yield* Provision.apply(approval).pipe(Effect.result);\n yield* expect(\n name,\n stale._tag === \"Failure\" && stale.failure.reason._tag === \"Stale\",\n \"apply must reject provider state that changed after approval\",\n );\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n const flaky: Provider.Definition = {\n ...definition,\n session: (input) => {\n const session = definition.session(input);\n return {\n ...session,\n dns: (target) => {\n const dns = session.dns(target);\n let writes = 0;\n return {\n ...dns,\n create: (targetZone, record) => {\n writes += 1;\n return writes === 2\n ? Errors.fail(\n new Reason.ProviderUnavailable({\n provider: definition.id,\n message: \"injected conformance failure\",\n }),\n )\n : dns.create(targetZone, record);\n },\n };\n },\n };\n },\n };\n\n const partialApplyCleanup = run(flaky, (dns, attachment) => {\n let created: ReadonlyArray<string> = [];\n const name: Case = \"partial-apply-cleanup\";\n return Effect.gen(function* () {\n const plan = yield* Provision.plan({\n domain: attachment.domain,\n requirements: [\n cname(zone, `${prefix}-partial-one`),\n txt(zone, `${prefix}-partial-two`, \"domainkit\"),\n ],\n });\n const receipt = yield* Provision.apply(yield* Provision.approve(plan));\n created = recordIds(receipt);\n yield* expect(\n name,\n receipt.status === \"partial\" && created.length === 1,\n \"a later write failure must preserve the first confirmed write in a partial receipt\",\n );\n const cleanupPlan = yield* Cleanup.plan({ receiptId: receipt.id });\n yield* Cleanup.apply(yield* Cleanup.approve(cleanupPlan));\n const remaining = yield* Effect.forEach(created, (id) => dns.get(zone, id));\n yield* expect(\n name,\n remaining.every((record) => record === null),\n \"partial receipt cleanup must remove the confirmed write\",\n );\n created = [];\n }).pipe(Effect.ensuring(cleanup(dns, () => created)));\n });\n\n /** A token the provider rejects must read as `Unauthenticated`, so a host tells the customer the provider refused it. */\n const rejectedToken = Effect.gen(function* () {\n const name: Case = \"rejected-token\";\n const auth = definition.auth.token;\n if (auth === undefined) return;\n const required = Provider.tokenFields(auth).filter((field) => field.required);\n if (options.rejectedToken === undefined && required.some((field) => !field.secret)) {\n return yield* Effect.fail(\n failure(\n name,\n `the token method requires ${required\n .filter((field) => !field.secret)\n .map((field) => field.name)\n .join(\", \")}; pass options.rejectedToken with values the provider rejects`,\n ),\n );\n }\n const values =\n options.rejectedToken ??\n Object.fromEntries(required.map((field) => [field.name, Redacted.make(\"\")]));\n const outcome = yield* auth.authenticate(values).pipe(Effect.result);\n yield* expect(\n name,\n outcome._tag === \"Failure\" && outcome.failure.reason._tag === \"Unauthenticated\",\n \"authenticating a rejected token must fail Unauthenticated\",\n );\n });\n\n return Effect.all(\n [createReadbackCleanup, exactNoop, conflict, stalePlan, partialApplyCleanup, rejectedToken],\n { discard: true },\n );\n};\n\n/** Verification is out of scope for the provider contract; keep the pool quiet. */\nconst silentResolver: Resolver.Interface = {\n resolve: () => Effect.succeed([]),\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,MAAM,YAAYA,KAAe;CAAE,SAAS;CAAe,SAAS;AAAc,CAAC;AAEnF,MAAM,WAAW,MAAY,YAC3B,IAAIC,eAAsB,EACxB,QA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O,WAAW,KAAK;EAC7B,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,WAAWG,YAAqB,IAAI,CAAC,CAAC,QAAQ,UAAU,MAAM,QAAQ;EAC5E,IAAI,QAAQ,kBAAkB,KAAA,KAAa,SAAS,MAAM,UAAU,CAAC,MAAM,MAAM,GAC/E,OAAO,OAAO,OAAO,KACnB,QACE,MACA,6BAA6B,SAC1B,QAAQ,UAAU,CAAC,MAAM,MAAM,CAAC,CAChC,KAAK,UAAU,MAAM,IAAI,CAAC,CAC1B,KAAK,IAAI,EAAE,8DAChB,CACF;EAEF,MAAM,SACJ,QAAQ,iBACR,OAAO,YAAY,SAAS,KAAK,UAAU,CAAC,MAAM,MAAM,SAAS,KAAK,EAAE,CAAC,CAAC,CAAC;EAC7E,MAAM,UAAU,OAAO,KAAK,aAAa,MAAM,CAAC,CAAC,KAAK,OAAO,MAAM;EACnE,OAAO,OACL,MACA,QAAQ,SAAS,aAAa,QAAQ,QAAQ,OAAO,SAAS,mBAC9D,2DACF;CACF,CAAC;CAED,OAAO,OAAO,IACZ;EAAC;EAAuB;EAAW;EAAU;EAAW;EAAqB;CAAa,GAC1F,EAAE,SAAS,KAAK,CAClB;AACF;;AAGA,MAAM,iBAAqC,EACzC,eAAe,OAAO,QAAQ,CAAC,CAAC,EAClC"}
|
package/dist/internal/http.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Forbidden, ProviderConflict, ProviderRejected, ProviderUnavailable, Unauthenticated } from "../Reason.mjs";
|
|
2
|
-
import { DomainKitError, isDomainKitError } from "./error.mjs";
|
|
2
|
+
import { DomainKitError, fail, isDomainKitError } from "./error.mjs";
|
|
3
3
|
import { Effect } from "effect";
|
|
4
4
|
//#region src/internal/http.ts
|
|
5
5
|
/** One provider HTTP round trip: transport failures and non-JSON replies are already classified. */
|
|
@@ -63,6 +63,11 @@ const classify = (provider, status, headers, message, code) => {
|
|
|
63
63
|
code: code ?? String(status)
|
|
64
64
|
});
|
|
65
65
|
};
|
|
66
|
+
/**
|
|
67
|
+
* During token verification a `Forbidden` answer means the provider did not accept the token, so
|
|
68
|
+
* it reads as `Unauthenticated` with the provider's own message.
|
|
69
|
+
*/
|
|
70
|
+
const rejectedToken = (verification) => verification.pipe(Effect.catchIf((error) => error.reason._tag === "Forbidden", (error) => fail(new Unauthenticated({ message: error.reason.message }))));
|
|
66
71
|
const rejected = (provider, message, code) => new DomainKitError({ reason: new ProviderRejected({
|
|
67
72
|
provider,
|
|
68
73
|
message,
|
|
@@ -85,6 +90,6 @@ const bearer = (token, init) => ({
|
|
|
85
90
|
}
|
|
86
91
|
});
|
|
87
92
|
//#endregion
|
|
88
|
-
export { bearer, classify, headersFrom, rejected, requestJson };
|
|
93
|
+
export { bearer, classify, headersFrom, rejected, rejectedToken, requestJson };
|
|
89
94
|
|
|
90
95
|
//# sourceMappingURL=http.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.mjs","names":["Errors.DomainKitError","Reason.ProviderRejected","Errors.isDomainKitError","Reason.ProviderUnavailable","Reason.Unauthenticated","Reason.Forbidden","Reason.ProviderConflict"],"sources":["../../src/internal/http.ts"],"sourcesContent":["import { Effect } from \"effect\";\n\nimport * as Errors from \"./error.ts\";\nimport * as Reason from \"../Reason.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface Reply {\n readonly status: number;\n readonly ok: boolean;\n readonly headers: Headers;\n /** Parsed JSON, or `null` for an empty body. */\n readonly body: unknown;\n}\n\n/** One provider HTTP round trip: transport failures and non-JSON replies are already classified. */\nexport const requestJson = (input: {\n readonly fetch: Fetch;\n readonly provider: string;\n readonly url: URL | string;\n readonly init?: RequestInit;\n}): Effect.Effect<Reply, Errors.DomainKitError> =>\n Effect.tryPromise({\n try: async (signal): Promise<Reply> => {\n const { fetch: send } = input; // a free call keeps `this` undefined for a native fetch\n const response = await send(input.url, { ...input.init, signal });\n const text = await response.text();\n let body: unknown = null;\n if (text.length > 0) {\n try {\n body = JSON.parse(text);\n } catch {\n throw new Errors.DomainKitError({\n reason: response.ok\n ? new Reason.ProviderRejected({\n provider: input.provider,\n message: `${input.provider} returned a non-JSON response`,\n })\n : classify(\n input.provider,\n response.status,\n response.headers,\n `HTTP ${response.status}`,\n ),\n });\n }\n }\n return { status: response.status, ok: response.ok, headers: response.headers, body };\n },\n catch: (cause) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.ProviderUnavailable({\n provider: input.provider,\n message: cause instanceof Error ? cause.message : `${input.provider} request failed`,\n }),\n }),\n });\n\n/** Host-supplied request headers, given as a value or as a thunk that may await a fresh token. */\nexport const headersFrom = (\n source: HeadersInit | (() => HeadersInit | Promise<HeadersInit>) | undefined,\n): Effect.Effect<Headers, Errors.DomainKitError> =>\n source === undefined\n ? Effect.sync(() => new Headers())\n : typeof source !== \"function\"\n ? Effect.sync(() => new Headers(source))\n : Effect.tryPromise({\n try: async () => new Headers(await source()),\n catch: (cause) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.Unauthenticated({\n message:\n cause instanceof Error ? cause.message : \"Request headers were unavailable\",\n }),\n }),\n });\n\n/**\n * Map an HTTP failure to a reason: 401 -> Unauthenticated, 403 -> Forbidden, 409 or a provider\n * conflict code -> ProviderConflict, 429/5xx -> ProviderUnavailable, else ProviderRejected.\n */\nexport const classify = (\n provider: string,\n status: number,\n headers: Headers,\n message: string,\n code?: string,\n): Reason.Model => {\n if (status === 401) return new Reason.Unauthenticated({ message });\n if (status === 403) return new Reason.Forbidden({ message });\n if (status === 409 || code === \"conflict\") {\n return new Reason.ProviderConflict({\n provider,\n message,\n code: code ?? String(status),\n });\n }\n if (status === 429 || status >= 500) {\n const retryAfterMs = retryAfter(headers.get(\"retry-after\"));\n return new Reason.ProviderUnavailable({\n provider,\n message,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n }\n return new Reason.ProviderRejected({\n provider,\n message,\n code: code ?? String(status),\n });\n};\n\nexport const rejected = (provider: string, message: string, code?: string) =>\n new Errors.DomainKitError({\n reason: new Reason.ProviderRejected({\n provider,\n message,\n ...(code === undefined ? {} : { code }),\n }),\n });\n\nfunction retryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000);\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nexport const bearer = (token: string, init?: RequestInit): RequestInit => ({\n ...init,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${token}`,\n ...(init?.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...init?.headers,\n },\n});\n"],"mappings":";;;;;AAgBA,MAAa,eAAe,UAM1B,OAAO,WAAW;CAChB,KAAK,OAAO,WAA2B;EACrC,MAAM,EAAE,OAAO,SAAS;EACxB,MAAM,WAAW,MAAM,KAAK,MAAM,KAAK;GAAE,GAAG,MAAM;GAAM;EAAO,CAAC;EAChE,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,IAAI,OAAgB;EACpB,IAAI,KAAK,SAAS,GAChB,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,QAAQ;GACN,MAAM,IAAIA,eAAsB,EAC9B,QAAQ,SAAS,KACb,IAAIC,iBAAwB;IAC1B,UAAU,MAAM;IAChB,SAAS,GAAG,MAAM,SAAS;GAC7B,CAAC,IACD,SACE,MAAM,UACN,SAAS,QACT,SAAS,SACT,QAAQ,SAAS,QACnB,EACN,CAAC;EACH;EAEF,OAAO;GAAE,QAAQ,SAAS;GAAQ,IAAI,SAAS;GAAI,SAAS,SAAS;GAAS;EAAK;CACrF;CACA,QAAQ,UACNC,iBAAwB,KAAK,IACzB,QACA,IAAIF,eAAsB,EACxB,QAAQ,IAAIG,oBAA2B;EACrC,UAAU,MAAM;EAChB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,GAAG,MAAM,SAAS;CACtE,CAAC,EACH,CAAC;AACT,CAAC;;AAGH,MAAa,eACX,WAEA,WAAW,KAAA,IACP,OAAO,WAAW,IAAI,QAAQ,CAAC,IAC/B,OAAO,WAAW,aAChB,OAAO,WAAW,IAAI,QAAQ,MAAM,CAAC,IACrC,OAAO,WAAW;CAChB,KAAK,YAAY,IAAI,QAAQ,MAAM,OAAO,CAAC;CAC3C,QAAQ,UACND,iBAAwB,KAAK,IACzB,QACA,IAAIF,eAAsB,EACxB,QAAQ,IAAII,gBAAuB,EACjC,SACE,iBAAiB,QAAQ,MAAM,UAAU,mCAC7C,CAAC,EACH,CAAC;AACT,CAAC;;;;;AAMT,MAAa,YACX,UACA,QACA,SACA,SACA,SACiB;CACjB,IAAI,WAAW,KAAK,OAAO,IAAIA,gBAAuB,EAAE,QAAQ,CAAC;CACjE,IAAI,WAAW,KAAK,OAAO,IAAIC,UAAiB,EAAE,QAAQ,CAAC;CAC3D,IAAI,WAAW,OAAO,SAAS,YAC7B,OAAO,IAAIC,iBAAwB;EACjC;EACA;EACA,MAAM,QAAQ,OAAO,MAAM;CAC7B,CAAC;CAEH,IAAI,WAAW,OAAO,UAAU,KAAK;EACnC,MAAM,eAAe,WAAW,QAAQ,IAAI,aAAa,CAAC;EAC1D,OAAO,IAAIH,oBAA2B;GACpC;GACA;GACA,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;EACvD,CAAC;CACH;CACA,OAAO,IAAIF,iBAAwB;EACjC;EACA;EACA,MAAM,QAAQ,OAAO,MAAM;CAC7B,CAAC;AACH;
|
|
1
|
+
{"version":3,"file":"http.mjs","names":["Errors.DomainKitError","Reason.ProviderRejected","Errors.isDomainKitError","Reason.ProviderUnavailable","Reason.Unauthenticated","Reason.Forbidden","Reason.ProviderConflict","Errors.fail"],"sources":["../../src/internal/http.ts"],"sourcesContent":["import { Effect } from \"effect\";\n\nimport * as Errors from \"./error.ts\";\nimport * as Reason from \"../Reason.ts\";\n\nexport type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface Reply {\n readonly status: number;\n readonly ok: boolean;\n readonly headers: Headers;\n /** Parsed JSON, or `null` for an empty body. */\n readonly body: unknown;\n}\n\n/** One provider HTTP round trip: transport failures and non-JSON replies are already classified. */\nexport const requestJson = (input: {\n readonly fetch: Fetch;\n readonly provider: string;\n readonly url: URL | string;\n readonly init?: RequestInit;\n}): Effect.Effect<Reply, Errors.DomainKitError> =>\n Effect.tryPromise({\n try: async (signal): Promise<Reply> => {\n const { fetch: send } = input; // a free call keeps `this` undefined for a native fetch\n const response = await send(input.url, { ...input.init, signal });\n const text = await response.text();\n let body: unknown = null;\n if (text.length > 0) {\n try {\n body = JSON.parse(text);\n } catch {\n throw new Errors.DomainKitError({\n reason: response.ok\n ? new Reason.ProviderRejected({\n provider: input.provider,\n message: `${input.provider} returned a non-JSON response`,\n })\n : classify(\n input.provider,\n response.status,\n response.headers,\n `HTTP ${response.status}`,\n ),\n });\n }\n }\n return { status: response.status, ok: response.ok, headers: response.headers, body };\n },\n catch: (cause) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.ProviderUnavailable({\n provider: input.provider,\n message: cause instanceof Error ? cause.message : `${input.provider} request failed`,\n }),\n }),\n });\n\n/** Host-supplied request headers, given as a value or as a thunk that may await a fresh token. */\nexport const headersFrom = (\n source: HeadersInit | (() => HeadersInit | Promise<HeadersInit>) | undefined,\n): Effect.Effect<Headers, Errors.DomainKitError> =>\n source === undefined\n ? Effect.sync(() => new Headers())\n : typeof source !== \"function\"\n ? Effect.sync(() => new Headers(source))\n : Effect.tryPromise({\n try: async () => new Headers(await source()),\n catch: (cause) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.Unauthenticated({\n message:\n cause instanceof Error ? cause.message : \"Request headers were unavailable\",\n }),\n }),\n });\n\n/**\n * Map an HTTP failure to a reason: 401 -> Unauthenticated, 403 -> Forbidden, 409 or a provider\n * conflict code -> ProviderConflict, 429/5xx -> ProviderUnavailable, else ProviderRejected.\n */\nexport const classify = (\n provider: string,\n status: number,\n headers: Headers,\n message: string,\n code?: string,\n): Reason.Model => {\n if (status === 401) return new Reason.Unauthenticated({ message });\n if (status === 403) return new Reason.Forbidden({ message });\n if (status === 409 || code === \"conflict\") {\n return new Reason.ProviderConflict({\n provider,\n message,\n code: code ?? String(status),\n });\n }\n if (status === 429 || status >= 500) {\n const retryAfterMs = retryAfter(headers.get(\"retry-after\"));\n return new Reason.ProviderUnavailable({\n provider,\n message,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n }\n return new Reason.ProviderRejected({\n provider,\n message,\n code: code ?? String(status),\n });\n};\n\n/**\n * During token verification a `Forbidden` answer means the provider did not accept the token, so\n * it reads as `Unauthenticated` with the provider's own message.\n */\nexport const rejectedToken = <A, R>(\n verification: Effect.Effect<A, Errors.DomainKitError, R>,\n): Effect.Effect<A, Errors.DomainKitError, R> =>\n verification.pipe(\n Effect.catchIf(\n (error) => error.reason._tag === \"Forbidden\",\n (error) => Errors.fail(new Reason.Unauthenticated({ message: error.reason.message })),\n ),\n );\n\nexport const rejected = (provider: string, message: string, code?: string) =>\n new Errors.DomainKitError({\n reason: new Reason.ProviderRejected({\n provider,\n message,\n ...(code === undefined ? {} : { code }),\n }),\n });\n\nfunction retryAfter(value: string | null): number | undefined {\n if (value === null) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000);\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nexport const bearer = (token: string, init?: RequestInit): RequestInit => ({\n ...init,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${token}`,\n ...(init?.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...init?.headers,\n },\n});\n"],"mappings":";;;;;AAgBA,MAAa,eAAe,UAM1B,OAAO,WAAW;CAChB,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AgB,mBAAmB;EACzE,GAAG,MAAM;CACX;AACF"}
|
package/dist/package.mjs
CHANGED
package/dist/types/Connect.d.ts
CHANGED
|
@@ -283,14 +283,24 @@ export type Discovery = Data.TaggedEnum<{
|
|
|
283
283
|
readonly target: Provider.Target;
|
|
284
284
|
}>;
|
|
285
285
|
};
|
|
286
|
+
/**
|
|
287
|
+
* No connection reaches the domain. `host` names the one registered provider whose declared
|
|
288
|
+
* nameserver suffixes cover every authoritative nameserver; `null` when none or several do.
|
|
289
|
+
*/
|
|
286
290
|
NotFound: {
|
|
287
291
|
readonly nameservers: ReadonlyArray<string>;
|
|
292
|
+
readonly host: {
|
|
293
|
+
readonly provider: string;
|
|
294
|
+
} | null;
|
|
288
295
|
};
|
|
289
296
|
}>;
|
|
290
297
|
export declare const Discovery: {
|
|
291
298
|
readonly $is: <Tag extends "NotFound" | "Resolved" | "SelectionRequired">(tag: Tag) => (u: unknown) => u is Extract<{
|
|
292
299
|
readonly _tag: "NotFound";
|
|
293
300
|
readonly nameservers: ReadonlyArray<string>;
|
|
301
|
+
readonly host: {
|
|
302
|
+
readonly provider: string;
|
|
303
|
+
} | null;
|
|
294
304
|
}, {
|
|
295
305
|
readonly _tag: Tag;
|
|
296
306
|
}> | Extract<{
|
|
@@ -312,6 +322,9 @@ export declare const Discovery: {
|
|
|
312
322
|
<Cases extends { readonly [Tag in "NotFound" | "Resolved" | "SelectionRequired"]: (args: Extract<{
|
|
313
323
|
readonly _tag: "NotFound";
|
|
314
324
|
readonly nameservers: ReadonlyArray<string>;
|
|
325
|
+
readonly host: {
|
|
326
|
+
readonly provider: string;
|
|
327
|
+
} | null;
|
|
315
328
|
} | {
|
|
316
329
|
readonly _tag: "Resolved";
|
|
317
330
|
readonly connectionId: string;
|
|
@@ -327,6 +340,9 @@ export declare const Discovery: {
|
|
|
327
340
|
}>) => any; }>(cases: Cases): (value: {
|
|
328
341
|
readonly _tag: "NotFound";
|
|
329
342
|
readonly nameservers: ReadonlyArray<string>;
|
|
343
|
+
readonly host: {
|
|
344
|
+
readonly provider: string;
|
|
345
|
+
} | null;
|
|
330
346
|
} | {
|
|
331
347
|
readonly _tag: "Resolved";
|
|
332
348
|
readonly connectionId: string;
|
|
@@ -341,6 +357,9 @@ export declare const Discovery: {
|
|
|
341
357
|
<Cases extends { readonly [Tag in "NotFound" | "Resolved" | "SelectionRequired"]: (args: Extract<{
|
|
342
358
|
readonly _tag: "NotFound";
|
|
343
359
|
readonly nameservers: ReadonlyArray<string>;
|
|
360
|
+
readonly host: {
|
|
361
|
+
readonly provider: string;
|
|
362
|
+
} | null;
|
|
344
363
|
} | {
|
|
345
364
|
readonly _tag: "Resolved";
|
|
346
365
|
readonly connectionId: string;
|
|
@@ -356,6 +375,9 @@ export declare const Discovery: {
|
|
|
356
375
|
}>) => any; }>(value: {
|
|
357
376
|
readonly _tag: "NotFound";
|
|
358
377
|
readonly nameservers: ReadonlyArray<string>;
|
|
378
|
+
readonly host: {
|
|
379
|
+
readonly provider: string;
|
|
380
|
+
} | null;
|
|
359
381
|
} | {
|
|
360
382
|
readonly _tag: "Resolved";
|
|
361
383
|
readonly connectionId: string;
|
|
@@ -371,6 +393,9 @@ export declare const Discovery: {
|
|
|
371
393
|
readonly NotFound: Data.TaggedEnum.ConstructorFrom<{
|
|
372
394
|
readonly _tag: "NotFound";
|
|
373
395
|
readonly nameservers: ReadonlyArray<string>;
|
|
396
|
+
readonly host: {
|
|
397
|
+
readonly provider: string;
|
|
398
|
+
} | null;
|
|
374
399
|
}, "_tag">;
|
|
375
400
|
readonly Resolved: Data.TaggedEnum.ConstructorFrom<{
|
|
376
401
|
readonly _tag: "Resolved";
|
|
@@ -446,6 +471,9 @@ export declare const inspect: (domain: string) => Effect.Effect<Snapshot, Errors
|
|
|
446
471
|
export declare const discover: (domain: string) => Effect.Effect<{
|
|
447
472
|
readonly _tag: "NotFound";
|
|
448
473
|
readonly nameservers: ReadonlyArray<string>;
|
|
474
|
+
readonly host: {
|
|
475
|
+
readonly provider: string;
|
|
476
|
+
} | null;
|
|
449
477
|
} | {
|
|
450
478
|
readonly _tag: "Resolved";
|
|
451
479
|
readonly connectionId: string;
|
package/dist/types/Provider.d.ts
CHANGED
|
@@ -210,6 +210,12 @@ export interface IntegrationAuth {
|
|
|
210
210
|
export interface Definition<Context = unknown> {
|
|
211
211
|
readonly id: string;
|
|
212
212
|
readonly name: string;
|
|
213
|
+
/**
|
|
214
|
+
* Hostname suffixes of the nameservers this provider operates, e.g. `ns.cloudflare.com`.
|
|
215
|
+
* `Connect.discover` names the provider as a domain's host when every authoritative nameserver
|
|
216
|
+
* ends in one of them.
|
|
217
|
+
*/
|
|
218
|
+
readonly nameservers?: ReadonlyArray<string>;
|
|
213
219
|
readonly auth: {
|
|
214
220
|
readonly token?: TokenAuth;
|
|
215
221
|
readonly oauth?: OAuthAuth;
|
package/dist/types/Server.d.ts
CHANGED
|
@@ -198,7 +198,11 @@ export declare class DiscoverySelectionRequired extends DiscoverySelectionRequir
|
|
|
198
198
|
}
|
|
199
199
|
declare const DiscoveryNotFound_base: Schema.Class<DiscoveryNotFound, Schema.TaggedStruct<"NotFound", {
|
|
200
200
|
readonly nameservers: Schema.$Array<Schema.String>;
|
|
201
|
+
readonly host: Schema.NullOr<Schema.Struct<{
|
|
202
|
+
readonly provider: Schema.String;
|
|
203
|
+
}>>;
|
|
201
204
|
}>, {}>;
|
|
205
|
+
/** `host` names the registered provider whose nameservers serve the domain, by definition id. */
|
|
202
206
|
export declare class DiscoveryNotFound extends DiscoveryNotFound_base {
|
|
203
207
|
}
|
|
204
208
|
export declare const Discovery: Schema.Union<readonly [typeof DiscoveryResolved, typeof DiscoverySelectionRequired, typeof DiscoveryNotFound]>;
|
package/dist/types/Testing.d.ts
CHANGED
|
@@ -29,6 +29,8 @@ export interface FakeProviderOptions {
|
|
|
29
29
|
readonly failWrite?: (index: number) => boolean;
|
|
30
30
|
/** Nameservers per zone; default `ns1.<zone>`, `ns2.<zone>`. `resolver()` answers NS queries from them. */
|
|
31
31
|
readonly nameservers?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
32
|
+
/** Suffixes the fake declares as `Definition.nameservers`, so `Connect.discover` can name it as a host. */
|
|
33
|
+
readonly nameserverSuffixes?: ReadonlyArray<string>;
|
|
32
34
|
}
|
|
33
35
|
export interface FakeProvider extends Provider.Definition<FakeContext> {
|
|
34
36
|
readonly records: (zone: string) => ReadonlyArray<DnsRecord.Observed>;
|
|
@@ -79,6 +81,6 @@ export type { Case as StorageCase } from "./internal/conformance/storage.ts";
|
|
|
79
81
|
export declare const conformance: {
|
|
80
82
|
/** Runs every Storage invariant (tenant isolation, leases, exactly-once continuations, revocation recovery). */
|
|
81
83
|
storage: typeof storageCases;
|
|
82
|
-
/** Runs create/readback/cleanup, exact-noop, conflict, stale-plan, partial-apply against a real provider definition. */
|
|
84
|
+
/** Runs create/readback/cleanup, exact-noop, conflict, stale-plan, partial-apply, and rejected-token against a real provider definition. */
|
|
83
85
|
provider: typeof providerCases;
|
|
84
86
|
};
|
package/dist/types/Vercel.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Vercel: personal tokens and marketplace integrations. */
|
|
2
2
|
import { type Config, Redacted, Schema } from "effect";
|
|
3
|
-
import type
|
|
3
|
+
import { type Fetch } from "./internal/http.ts";
|
|
4
4
|
import * as Provider from "./Provider.ts";
|
|
5
5
|
/** `teamId` is `null` for a personal account; targets carry the team that owns the zone. */
|
|
6
6
|
export declare const TeamContext: Schema.Struct<{
|
|
@@ -12,8 +12,10 @@ export interface Options {
|
|
|
12
12
|
type Fx<A> = Effect.Effect<A, Errors.DomainKitError>;
|
|
13
13
|
/** Every zone the credential can see, across accounts; internal zones cannot host records. */
|
|
14
14
|
export declare const listZones: (options: Options, accountId?: string) => Fx<ReadonlyArray<Protocol.Zone>>;
|
|
15
|
-
/**
|
|
16
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Token status and expiry from a verify endpoint; `null` expiry means the token never expires. An
|
|
17
|
+
* inactive token, or a 403 from the verify endpoint, is `Unauthenticated`.
|
|
18
|
+
*/
|
|
17
19
|
export declare const verifyToken: (options: Options, path: string) => Fx<DateTime.Utc | null>;
|
|
18
20
|
export declare const tokenExpiry: (options: Options, accountId: string | null) => Fx<{
|
|
19
21
|
readonly expiresAt: DateTime.Utc | null;
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import * as Errors from "../error.ts";
|
|
3
3
|
import * as Provider from "../../Provider.ts";
|
|
4
|
-
export declare const cases: readonly ["create-readback-cleanup", "exact-noop", "conflict", "stale-plan", "partial-apply-cleanup"];
|
|
4
|
+
export declare const cases: readonly ["create-readback-cleanup", "exact-noop", "conflict", "stale-plan", "partial-apply-cleanup", "rejected-token"];
|
|
5
5
|
export type Case = (typeof cases)[number];
|
|
6
6
|
/**
|
|
7
|
-
* Runs create/readback/cleanup, exact-noop, conflict, stale-plan,
|
|
8
|
-
* real provider definition, through the same Provision and Cleanup
|
|
7
|
+
* Runs create/readback/cleanup, exact-noop, conflict, stale-plan, partial-apply, and
|
|
8
|
+
* rejected-token against a real provider definition, through the same Provision and Cleanup
|
|
9
|
+
* services hosts use.
|
|
9
10
|
*/
|
|
10
11
|
export declare const provider: (definition: Provider.Definition, credential: Provider.Credential, zone: string, options?: {
|
|
11
12
|
readonly prefix?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Token values the provider rejects, for the `rejected-token` case. Default: every required
|
|
15
|
+
* field set to an empty secret, which needs a token method whose required fields are all
|
|
16
|
+
* secrets.
|
|
17
|
+
*/
|
|
18
|
+
readonly rejectedToken?: Provider.TokenValues;
|
|
12
19
|
}) => Effect.Effect<void, Errors.DomainKitError>;
|
|
@@ -23,5 +23,10 @@ export declare const headersFrom: (source: HeadersInit | (() => HeadersInit | Pr
|
|
|
23
23
|
* conflict code -> ProviderConflict, 429/5xx -> ProviderUnavailable, else ProviderRejected.
|
|
24
24
|
*/
|
|
25
25
|
export declare const classify: (provider: string, status: number, headers: Headers, message: string, code?: string) => Reason.Model;
|
|
26
|
+
/**
|
|
27
|
+
* During token verification a `Forbidden` answer means the provider did not accept the token, so
|
|
28
|
+
* it reads as `Unauthenticated` with the provider's own message.
|
|
29
|
+
*/
|
|
30
|
+
export declare const rejectedToken: <A, R>(verification: Effect.Effect<A, Errors.DomainKitError, R>) => Effect.Effect<A, Errors.DomainKitError, R>;
|
|
26
31
|
export declare const rejected: (provider: string, message: string, code?: string) => Errors.DomainKitError;
|
|
27
32
|
export declare const bearer: (token: string, init?: RequestInit) => RequestInit;
|