@intellectual-frontiers/net 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/acme.ts ADDED
@@ -0,0 +1,546 @@
1
+ // Spec: 0001-net FR-008
2
+ /**
3
+ * An ACME client (RFC 8555) that gets a certificate by the DNS-01 challenge (commons 0013-acme): an account (made, or found again by its
4
+ * key with `onlyReturnExisting`), an order for the names, a TXT record `_acme-challenge.<name>` holding the base64url SHA-256 of each key
5
+ * authorization, the challenges answered, the authorizations and the order polled with a growing wait (or the server's `Retry-After`), a
6
+ * certificate signing request for a new ES256 key with the names as its subject alternative names (built with the kernel's `der`), the
7
+ * order finalized and the certificate downloaded. Every request is a JWS (ES256: the account's JWK until the account exists, its `kid`
8
+ * after) with a fresh nonce, and a `badNonce` refusal is retried with the nonce it carries. The TXT records set are always removed, whether
9
+ * the certificate came or not. `cloudflareDns` is a `DnsProvider` over Cloudflare's API; `needsRenewal` and `notAfterOf` read a
10
+ * certificate's validity.
11
+ *
12
+ * Every expected failure (the server refuses, a challenge is invalid, the DNS provider throws, the network fails, the wait runs out) is a
13
+ * `Result` with one sentence; nothing secret (the token, a private key) is ever in it.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { cloudflareDns, issue, LETS_ENCRYPT_STAGING } from "./acme.ts";
18
+ * const r = await issue({
19
+ * directory: LETS_ENCRYPT_STAGING,
20
+ * domains: ["erga.fyi", "*.erga.fyi"],
21
+ * dns: cloudflareDns({ token: "<a token with Zone.DNS edit>", zone: "erga.fyi" }),
22
+ * contact: ["mailto:ops@example.com"],
23
+ * });
24
+ * if (r.kind === "ok") {
25
+ * // keep r.value.accountKey for the next renewal; write r.value.certificatePem and r.value.privateKeyPem where the server reads them
26
+ * }
27
+ * ```
28
+ *
29
+ * @limits
30
+ * DNS-01 only (no HTTP-01 or TLS-ALPN-01), ES256 only (for the account and the certificate's key), no External Account Binding, no
31
+ * revocation, no key change, and no ACME Renewal Information: `needsRenewal` decides by the certificate's own `notAfter`.
32
+ *
33
+ * @module
34
+ */
35
+ import { fromBase64, toBase64, toBase64Url } from "@intellectual-frontiers/formats/base64";
36
+ import * as der from "@intellectual-frontiers/formats/der";
37
+ import {
38
+ array,
39
+ boolean,
40
+ type Decoder,
41
+ formatDecodeError,
42
+ json,
43
+ literal,
44
+ object,
45
+ string,
46
+ err,
47
+ ok,
48
+ type Result,
49
+ } from "@intellectual-frontiers/core";
50
+
51
+ /** Let's Encrypt's production directory. */
52
+ export const LETS_ENCRYPT = "https://acme-v02.api.letsencrypt.org/directory";
53
+ /** Let's Encrypt's staging directory: certificates no browser trusts, for trying a setup without its rate limits. */
54
+ export const LETS_ENCRYPT_STAGING = "https://acme-staging-v02.api.letsencrypt.org/directory";
55
+
56
+ /** Where TXT records are set and removed (a zone's DNS host): `name` is the whole name, `value` the record's text. */
57
+ export type DnsProvider = {
58
+ setTxt(name: string, value: string): Promise<void>;
59
+ removeTxt(name: string, value: string): Promise<void>;
60
+ };
61
+
62
+ /** What `issue` takes. */
63
+ export type IssueOptions = {
64
+ /** The ACME directory's URL (`LETS_ENCRYPT`, `LETS_ENCRYPT_STAGING`, or another CA's). */
65
+ readonly directory: string;
66
+ /** The names the certificate is for; the first is also its common name. A wildcard (`*.erga.fyi`) is proven at `_acme-challenge.erga.fyi`. */
67
+ readonly domains: readonly string[];
68
+ readonly dns: DnsProvider;
69
+ /** The account's ES256 private key as a JWK; a new one is made where it is absent (and given back to keep). */
70
+ readonly accountKey?: JsonWebKey;
71
+ /** The account's contacts (`mailto:...`), sent when the account is made. */
72
+ readonly contact?: readonly string[];
73
+ /** Called for each TXT record once all are set, before the challenges are answered: wait until the record can be seen. */
74
+ readonly propagationWait?: (name: string, value: string) => Promise<void>;
75
+ /** The `fetch` used (a stub, in tests). */
76
+ readonly fetch?: typeof fetch;
77
+ /** The first wait between two polls, growing by half each time up to ten times this (1000 by default). */
78
+ readonly pollIntervalMs?: number;
79
+ /** How long an authorization or the order may take, in all (300000 by default). */
80
+ readonly pollTimeoutMs?: number;
81
+ };
82
+
83
+ /** What `issue` gives: the certificate chain, its key, the account's key to keep, the end of its validity, and what could not be cleaned up. */
84
+ export type Issued = {
85
+ /** The certificate and its chain, PEM, as the CA gives them. */
86
+ readonly certificatePem: string;
87
+ /** The certificate's ES256 private key, PKCS #8 PEM. */
88
+ readonly privateKeyPem: string;
89
+ /** The account's ES256 private key as a JWK: keep it (it is a secret) and give it to the next `issue`. */
90
+ readonly accountKey: JsonWebKey;
91
+ /** The certificate's `notAfter`, ISO 8601. */
92
+ readonly notAfter: string;
93
+ /** A TXT record that could not be removed, one sentence each (none when all were). */
94
+ readonly warnings: readonly string[];
95
+ };
96
+
97
+ const UA = "intellectual-frontiers-commons-acme";
98
+ const PROBLEM = "urn:ietf:params:acme:error:";
99
+
100
+ type Problem = { readonly type: string; readonly detail: string };
101
+ type Reply = { readonly status: number; readonly headers: Headers; readonly text: string };
102
+
103
+ const directoryDecoder = object({ newNonce: string, newAccount: string, newOrder: string });
104
+ const accountDecoder = object({ status: string });
105
+ const orderDecoder = object({ status: string, authorizations: array(string), finalize: string }, { certificate: string });
106
+ const challengeDecoder = object({ type: string, url: string, status: string }, { token: string });
107
+ const authzDecoder = object(
108
+ { status: string, identifier: object({ type: literal("dns"), value: string }), challenges: array(challengeDecoder) },
109
+ { wildcard: boolean },
110
+ );
111
+ const problemDecoder = object({ type: string }, { detail: string });
112
+
113
+ function problemOf(reply: Reply): Problem | undefined {
114
+ const p = json(reply.text, problemDecoder);
115
+ return p.kind === "ok" ? { type: p.value.type, detail: p.value.detail ?? "" } : undefined;
116
+ }
117
+
118
+ function describeReply(what: string, reply: Reply): string {
119
+ const p = problemOf(reply);
120
+ if (p === undefined) return `${what}: the server answered ${reply.status}`;
121
+ const type = p.type.startsWith(PROBLEM) ? p.type.slice(PROBLEM.length) : p.type;
122
+ return `${what}: the server answered ${reply.status} ${type}${p.detail === "" ? "" : ` (${p.detail})`}`;
123
+ }
124
+
125
+ function decoded<T>(what: string, reply: Reply, decoder: Decoder<T>): Result<T, string> {
126
+ const d = json(reply.text, decoder);
127
+ return d.kind === "ok" ? d : err(`${what}: the server's answer is not ACME's (${formatDecodeError(d.error)})`);
128
+ }
129
+
130
+ function bytesOf(buffer: ArrayBuffer): Uint8Array {
131
+ return new Uint8Array(buffer);
132
+ }
133
+
134
+ function utf8(text: string): Uint8Array<ArrayBuffer> {
135
+ return new TextEncoder().encode(text);
136
+ }
137
+
138
+ /** Bytes as PEM: the label's lines around the base64, 64 characters a line. */
139
+ export function pem(label: string, bytes: Uint8Array): string {
140
+ const b64 = toBase64(bytes);
141
+ const lines: string[] = [];
142
+ for (let i = 0; i < b64.length; i += 64) lines.push(b64.slice(i, i + 64));
143
+ return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
144
+ }
145
+
146
+ /** An ECDSA P-256 signature as raw `r || s` (what Web Crypto gives) turned into DER (`SEQUENCE { r INTEGER, s INTEGER }`), as X.509 wants it. */
147
+ export function ecdsaRawToDer(raw: Uint8Array): Uint8Array {
148
+ const half = raw.length / 2;
149
+ return der.sequence(der.integer(raw.subarray(0, half)), der.integer(raw.subarray(half)));
150
+ }
151
+
152
+ /** The RFC 7638 thumbprint of an EC public JWK: the base64url SHA-256 of `{"crv","kty","x","y"}` in that order. */
153
+ export async function jwkThumbprint(jwk: JsonWebKey): Promise<string> {
154
+ const canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
155
+ return toBase64Url(bytesOf(await crypto.subtle.digest("SHA-256", utf8(canonical))));
156
+ }
157
+
158
+ /** The TXT value of a DNS-01 challenge: the base64url SHA-256 of the key authorization `token.thumbprint` (RFC 8555 §8.4). */
159
+ export async function dns01Value(token: string, thumbprint: string): Promise<string> {
160
+ return toBase64Url(bytesOf(await crypto.subtle.digest("SHA-256", utf8(`${token}.${thumbprint}`))));
161
+ }
162
+
163
+ /** The name a DNS-01 TXT record is set at for a name (a wildcard's at its base name). */
164
+ export function challengeName(domain: string): string {
165
+ return `_acme-challenge.${domain.replace(/^\*\./, "")}`;
166
+ }
167
+
168
+ const EC = { name: "ECDSA", namedCurve: "P-256" } as const;
169
+ const ES256 = { name: "ECDSA", hash: "SHA-256" } as const;
170
+
171
+ /** A certification request (PKCS #10, RFC 2986) for these names, signed by the key: the first name as the common name, all as DNS SANs. */
172
+ export async function csr(domains: readonly string[], keys: CryptoKeyPair): Promise<Uint8Array> {
173
+ const first = domains[0] ?? "";
174
+ const subject =
175
+ first.length > 0 && first.length <= 64
176
+ ? der.sequence(der.setOf(der.sequence(der.oid("2.5.4.3"), der.utf8String(first))))
177
+ : der.sequence();
178
+ const spki = bytesOf(await crypto.subtle.exportKey("spki", keys.publicKey));
179
+ const san = der.sequence(...domains.map((d) => der.implicit(2, utf8(d), false)));
180
+ const extensions = der.sequence(der.sequence(der.oid("2.5.29.17"), der.octetString(san)));
181
+ const extensionRequest = der.sequence(der.oid("1.2.840.113549.1.9.14"), der.setOf(extensions));
182
+ const info = der.sequence(der.integer(0), subject, spki, der.implicit(0, extensionRequest, true));
183
+ const signature = bytesOf(await crypto.subtle.sign(ES256, keys.privateKey, new Uint8Array(info)));
184
+ return der.sequence(info, der.algorithm("1.2.840.10045.4.3.2"), der.bitString(ecdsaRawToDer(signature)));
185
+ }
186
+
187
+ function readTime(t: der.Tlv): Date | undefined {
188
+ const s = new TextDecoder().decode(t.content);
189
+ const m =
190
+ t.tag === der.TAG.utcTime
191
+ ? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
192
+ : t.tag === der.TAG.generalizedTime
193
+ ? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
194
+ : null;
195
+ if (m === null) return undefined;
196
+ const [, y = "", mo = "", d = "", h = "", mi = "", se = ""] = m;
197
+ let year = Number(y);
198
+ if (t.tag === der.TAG.utcTime) year += year >= 50 ? 1900 : 2000;
199
+ return new Date(Date.UTC(year, Number(mo) - 1, Number(d), Number(h), Number(mi), Number(se)));
200
+ }
201
+
202
+ /** The `notAfter` of the first certificate in PEM text, or undefined where there is none or it cannot be read. */
203
+ export function notAfterOf(certificatePem: string): Date | undefined {
204
+ const m = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/.exec(certificatePem);
205
+ if (m === null) return undefined;
206
+ const bytes = fromBase64(m[1] ?? "");
207
+ if (bytes.kind === "err") return undefined;
208
+ const cert = der.readTlv(bytes.value);
209
+ if (cert.kind === "err" || cert.value.tag !== der.TAG.sequence) return undefined;
210
+ const top = der.children(cert.value.content);
211
+ const tbs = top.kind === "ok" ? top.value[0] : undefined;
212
+ if (tbs === undefined || tbs.tag !== der.TAG.sequence) return undefined;
213
+ const fields = der.children(tbs.content);
214
+ if (fields.kind === "err") return undefined;
215
+ const offset = fields.value[0]?.tag === 0xa0 ? 1 : 0;
216
+ const validity = fields.value[offset + 3];
217
+ if (validity === undefined || validity.tag !== der.TAG.sequence) return undefined;
218
+ const times = der.children(validity.content);
219
+ const notAfter = times.kind === "ok" ? times.value[1] : undefined;
220
+ return notAfter === undefined ? undefined : readTime(notAfter);
221
+ }
222
+
223
+ /** Whether a certificate ends within `days` of `now` (or has ended, or cannot be read): the time to get a new one. */
224
+ export function needsRenewal(certificatePem: string, now: Date, days = 30): boolean {
225
+ const end = notAfterOf(certificatePem);
226
+ return end === undefined || end.getTime() - now.getTime() < days * 86_400_000;
227
+ }
228
+
229
+ type AccountKey = { readonly privateKey: CryptoKey; readonly jwk: JsonWebKey; readonly privateJwk: JsonWebKey };
230
+
231
+ async function accountKeyOf(given: JsonWebKey | undefined): Promise<Result<AccountKey, string>> {
232
+ try {
233
+ let privateJwk = given;
234
+ if (privateJwk === undefined) {
235
+ const pair = await crypto.subtle.generateKey(EC, true, ["sign", "verify"]);
236
+ privateJwk = await crypto.subtle.exportKey("jwk", pair.privateKey);
237
+ }
238
+ if (privateJwk.kty !== "EC" || privateJwk.crv !== "P-256" || privateJwk.d === undefined)
239
+ return err("the account key is not an ES256 (EC P-256) private JWK");
240
+ const privateKey = await crypto.subtle.importKey("jwk", privateJwk, EC, false, ["sign"]);
241
+ const jwk: JsonWebKey = { kty: "EC", crv: "P-256", x: privateJwk.x ?? "", y: privateJwk.y ?? "" };
242
+ const { key_ops: _ops, ext: _ext, ...kept } = privateJwk;
243
+ return ok({ privateKey, jwk, privateJwk: kept });
244
+ } catch {
245
+ return err("the account key cannot be used as an ES256 private key");
246
+ }
247
+ }
248
+
249
+ function sleep(ms: number): Promise<void> {
250
+ return new Promise((resolve) => setTimeout(resolve, ms));
251
+ }
252
+
253
+ function retryAfter(headers: Headers): number | undefined {
254
+ const v = headers.get("retry-after");
255
+ if (v === null) return undefined;
256
+ const seconds = Number(v);
257
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
258
+ const at = Date.parse(v);
259
+ return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());
260
+ }
261
+
262
+ /** A session with one ACME server: the last nonce, the account key and, once known, the account's URL (`kid`). */
263
+ type Session = {
264
+ kid: string | undefined;
265
+ /** A signed POST of `payload` (or POST-as-GET where it is undefined), retried on `badNonce`. */
266
+ post(url: string, payload: unknown, accept?: string): Promise<Reply>;
267
+ };
268
+
269
+ function openSession(fetcher: typeof fetch, newNonceUrl: string, key: AccountKey): Session {
270
+ let nonce: string | undefined;
271
+ const keep = (headers: Headers): void => {
272
+ const n = headers.get("replay-nonce");
273
+ if (n !== null) nonce = n;
274
+ };
275
+ const fresh = async (): Promise<string> => {
276
+ if (nonce !== undefined) {
277
+ const n = nonce;
278
+ nonce = undefined;
279
+ return n;
280
+ }
281
+ const r = await fetcher(newNonceUrl, { method: "HEAD", headers: { "user-agent": UA } });
282
+ const n = r.headers.get("replay-nonce");
283
+ if (n === null) throw new Error("the server gave no nonce");
284
+ return n;
285
+ };
286
+ const s: Session = {
287
+ kid: undefined,
288
+ async post(url, payload, accept) {
289
+ for (let attempt = 0; ; attempt++) {
290
+ const header = { alg: "ES256", nonce: await fresh(), url, ...(s.kid === undefined ? { jwk: key.jwk } : { kid: s.kid }) };
291
+ const protectedB64 = toBase64Url(utf8(JSON.stringify(header)));
292
+ const payloadB64 = payload === undefined ? "" : toBase64Url(utf8(JSON.stringify(payload)));
293
+ const sig = bytesOf(await crypto.subtle.sign(ES256, key.privateKey, utf8(`${protectedB64}.${payloadB64}`)));
294
+ const r = await fetcher(url, {
295
+ method: "POST",
296
+ headers: { "content-type": "application/jose+json", "user-agent": UA, ...(accept === undefined ? {} : { accept }) },
297
+ body: JSON.stringify({ protected: protectedB64, payload: payloadB64, signature: toBase64Url(sig) }),
298
+ });
299
+ keep(r.headers);
300
+ const reply: Reply = { status: r.status, headers: r.headers, text: await r.text() };
301
+ if (reply.status === 400 && attempt < 5 && problemOf(reply)?.type === `${PROBLEM}badNonce`) continue;
302
+ return reply;
303
+ }
304
+ },
305
+ };
306
+ return s;
307
+ }
308
+
309
+ async function poll<T extends { readonly status: string }>(
310
+ session: Session,
311
+ what: string,
312
+ url: string,
313
+ decoder: Decoder<T>,
314
+ pending: readonly string[],
315
+ o: IssueOptions,
316
+ ): Promise<Result<T, string>> {
317
+ const first = o.pollIntervalMs ?? 1000;
318
+ const deadline = Date.now() + (o.pollTimeoutMs ?? 300_000);
319
+ let wait = first;
320
+ for (;;) {
321
+ const reply = await session.post(url, undefined);
322
+ if (reply.status !== 200) return err(describeReply(what, reply));
323
+ const d = decoded(what, reply, decoder);
324
+ if (d.kind === "err" || !pending.includes(d.value.status)) return d;
325
+ const next = retryAfter(reply.headers) ?? wait;
326
+ if (Date.now() + next > deadline) return err(`${what}: still ${d.value.status} when the wait ran out`);
327
+ await sleep(next);
328
+ wait = Math.min(wait * 1.5, first * 10);
329
+ }
330
+ }
331
+
332
+ async function getAccount(
333
+ session: Session,
334
+ url: string,
335
+ given: boolean,
336
+ contact: readonly string[] | undefined,
337
+ ): Promise<Result<void, string>> {
338
+ if (given) {
339
+ const found = await session.post(url, { onlyReturnExisting: true });
340
+ if (found.status === 200) {
341
+ const kid = found.headers.get("location");
342
+ if (kid === null) return err("finding the account: the server gave no account URL");
343
+ const a = decoded("finding the account", found, accountDecoder);
344
+ if (a.kind === "err") return a;
345
+ if (a.value.status !== "valid") return err(`finding the account: it is ${a.value.status}`);
346
+ session.kid = kid;
347
+ return ok(undefined);
348
+ }
349
+ if (problemOf(found)?.type !== `${PROBLEM}accountDoesNotExist`) return err(describeReply("finding the account", found));
350
+ }
351
+ const made = await session.post(url, { termsOfServiceAgreed: true, ...(contact === undefined ? {} : { contact }) });
352
+ if (made.status !== 201 && made.status !== 200) return err(describeReply("making the account", made));
353
+ const kid = made.headers.get("location");
354
+ if (kid === null) return err("making the account: the server gave no account URL");
355
+ const a = decoded("making the account", made, accountDecoder);
356
+ if (a.kind === "err") return a;
357
+ if (a.value.status !== "valid") return err(`making the account: it is ${a.value.status}`);
358
+ session.kid = kid;
359
+ return ok(undefined);
360
+ }
361
+
362
+ type Txt = { readonly name: string; readonly value: string };
363
+
364
+ async function run(o: IssueOptions, key: AccountKey, fetcher: typeof fetch, set: Txt[]): Promise<Result<Omit<Issued, "warnings">, string>> {
365
+ const domains = o.domains.map((d) => d.toLowerCase());
366
+ const dirReply = await fetcher(o.directory, { headers: { "user-agent": UA } });
367
+ if (dirReply.status !== 200) return err(`reading the directory: the server answered ${dirReply.status}`);
368
+ const dir = decoded("reading the directory", { status: 200, headers: dirReply.headers, text: await dirReply.text() }, directoryDecoder);
369
+ if (dir.kind === "err") return dir;
370
+ const session = openSession(fetcher, dir.value.newNonce, key);
371
+ const account = await getAccount(session, dir.value.newAccount, o.accountKey !== undefined, o.contact);
372
+ if (account.kind === "err") return account;
373
+
374
+ const placed = await session.post(dir.value.newOrder, { identifiers: domains.map((value) => ({ type: "dns", value })) });
375
+ if (placed.status !== 201) return err(describeReply("placing the order", placed));
376
+ const orderUrl = placed.headers.get("location");
377
+ if (orderUrl === null) return err("placing the order: the server gave no order URL");
378
+ const order = decoded("placing the order", placed, orderDecoder);
379
+ if (order.kind === "err") return order;
380
+ if (order.value.status === "invalid") return err("placing the order: the order is invalid");
381
+
382
+ const thumbprint = await jwkThumbprint(key.jwk);
383
+ const answer: { readonly authz: string; readonly challenge: string; readonly domain: string }[] = [];
384
+ for (const authzUrl of order.value.authorizations) {
385
+ const reply = await session.post(authzUrl, undefined);
386
+ if (reply.status !== 200) return err(describeReply("reading an authorization", reply));
387
+ const authz = decoded("reading an authorization", reply, authzDecoder);
388
+ if (authz.kind === "err") return authz;
389
+ const domain = authz.value.identifier.value;
390
+ if (authz.value.status === "valid") continue;
391
+ if (authz.value.status !== "pending") return err(`the authorization of ${domain} is ${authz.value.status}`);
392
+ const ch = authz.value.challenges.find((c) => c.type === "dns-01");
393
+ if (ch === undefined || ch.token === undefined) return err(`the authorization of ${domain} offers no dns-01 challenge`);
394
+ const txt = { name: challengeName(domain), value: await dns01Value(ch.token, thumbprint) };
395
+ await o.dns.setTxt(txt.name, txt.value);
396
+ set.push(txt);
397
+ answer.push({ authz: authzUrl, challenge: ch.url, domain });
398
+ }
399
+ if (o.propagationWait !== undefined) for (const t of set) await o.propagationWait(t.name, t.value);
400
+ for (const a of answer) {
401
+ const reply = await session.post(a.challenge, {});
402
+ if (reply.status !== 200) return err(describeReply(`answering the challenge of ${a.domain}`, reply));
403
+ }
404
+ for (const a of answer) {
405
+ const done = await poll(session, `the authorization of ${a.domain}`, a.authz, authzDecoder, ["pending", "processing"], o);
406
+ if (done.kind === "err") return done;
407
+ if (done.value.status !== "valid") {
408
+ const why = done.value.challenges.find((c) => c.type === "dns-01")?.status ?? done.value.status;
409
+ return err(`the authorization of ${a.domain} is ${done.value.status} (its dns-01 challenge is ${why})`);
410
+ }
411
+ }
412
+
413
+ const certKeys = await crypto.subtle.generateKey(EC, true, ["sign", "verify"]);
414
+ const request = await csr(domains, certKeys);
415
+ const finalized = await session.post(order.value.finalize, { csr: toBase64Url(request) });
416
+ if (finalized.status !== 200) return err(describeReply("finalizing the order", finalized));
417
+ const final = await poll(session, "the order", orderUrl, orderDecoder, ["pending", "ready", "processing"], o);
418
+ if (final.kind === "err") return final;
419
+ if (final.value.status !== "valid" || final.value.certificate === undefined)
420
+ return err(`the order is ${final.value.status}, with no certificate`);
421
+ const cert = await session.post(final.value.certificate, undefined, "application/pem-certificate-chain");
422
+ if (cert.status !== 200) return err(describeReply("downloading the certificate", cert));
423
+ const notAfter = notAfterOf(cert.text);
424
+ if (notAfter === undefined) return err("downloading the certificate: what came is not a PEM certificate");
425
+ const pkcs8 = bytesOf(await crypto.subtle.exportKey("pkcs8", certKeys.privateKey));
426
+ return ok({
427
+ certificatePem: cert.text,
428
+ privateKeyPem: pem("PRIVATE KEY", pkcs8),
429
+ accountKey: key.privateJwk,
430
+ notAfter: notAfter.toISOString(),
431
+ });
432
+ }
433
+
434
+ function reason(e: unknown): string {
435
+ return e instanceof Error ? e.message : String(e);
436
+ }
437
+
438
+ /**
439
+ * A certificate for `domains` from the ACME server at `directory`, proven by DNS-01 through `dns`; or why not. The TXT records set are
440
+ * removed in every case; one that could not be removed is a warning of the result (or added to its error).
441
+ */
442
+ export async function issue(o: IssueOptions): Promise<Result<Issued, string>> {
443
+ if (o.domains.length === 0) return err("no names to issue a certificate for");
444
+ const key = await accountKeyOf(o.accountKey);
445
+ if (key.kind === "err") return key;
446
+ const fetcher = o.fetch ?? fetch;
447
+ const set: Txt[] = [];
448
+ let result: Result<Omit<Issued, "warnings">, string>;
449
+ try {
450
+ result = await run(o, key.value, fetcher, set);
451
+ } catch (e) {
452
+ result = err(`the certificate could not be issued: ${reason(e)}`);
453
+ }
454
+ const warnings: string[] = [];
455
+ for (const t of set) {
456
+ try {
457
+ await o.dns.removeTxt(t.name, t.value);
458
+ } catch (e) {
459
+ warnings.push(`the TXT record at ${t.name} could not be removed: ${reason(e)}`);
460
+ }
461
+ }
462
+ if (result.kind === "err") return warnings.length === 0 ? result : err(`${result.error}; and ${warnings.join("; ")}`);
463
+ return ok({ ...result.value, warnings });
464
+ }
465
+
466
+ const cfEnvelope = object({ success: boolean });
467
+ const cfError = object({ errors: array(object({ message: string })) });
468
+ const cfZones = object({ result: array(object({ id: string, name: string })) });
469
+ const cfRecord = object({ result: object({ id: string }) });
470
+ const cfRecords = object({ result: array(object({ id: string, content: string })) });
471
+
472
+ /** A `DnsProvider` over Cloudflare's API (v4) for one zone, by an API token allowed to edit its DNS (`Zone.DNS`). */
473
+ export function cloudflareDns(o: {
474
+ readonly token: string;
475
+ readonly zone: string;
476
+ readonly api?: string;
477
+ readonly fetch?: typeof fetch;
478
+ }): DnsProvider {
479
+ const api = (o.api ?? "https://api.cloudflare.com/client/v4").replace(/\/+$/, "");
480
+ const fetcher = o.fetch ?? fetch;
481
+ const zone = o.zone.toLowerCase();
482
+ const made = new Map<string, string>();
483
+ let zoneId: string | undefined;
484
+
485
+ async function call<T>(what: string, method: string, path: string, decoder: Decoder<T>, body?: unknown): Promise<T> {
486
+ const r = await fetcher(`${api}${path}`, {
487
+ method,
488
+ headers: { authorization: `Bearer ${o.token}`, "content-type": "application/json" },
489
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
490
+ });
491
+ const text = await r.text();
492
+ const env = json(text, cfEnvelope);
493
+ if (!r.ok || env.kind === "err" || !env.value.success) {
494
+ const errors = json(text, cfError);
495
+ const said = errors.kind === "ok" ? errors.value.errors.map((e) => e.message).join("; ") : "";
496
+ throw new Error(`Cloudflare, ${what}: ${r.status}${said === "" ? "" : ` (${said})`}`);
497
+ }
498
+ const d = json(text, decoder);
499
+ if (d.kind === "err") throw new Error(`Cloudflare, ${what}: an answer not understood (${formatDecodeError(d.error)})`);
500
+ return d.value;
501
+ }
502
+
503
+ async function idOfZone(): Promise<string> {
504
+ if (zoneId !== undefined) return zoneId;
505
+ const zones = await call("finding the zone", "GET", `/zones?name=${encodeURIComponent(zone)}`, cfZones);
506
+ const z = zones.result.find((x) => x.name.toLowerCase() === zone);
507
+ if (z === undefined) throw new Error(`Cloudflare: no zone ${zone} for this token`);
508
+ zoneId = z.id;
509
+ return z.id;
510
+ }
511
+
512
+ function inZone(name: string): void {
513
+ const n = name.toLowerCase();
514
+ if (n !== zone && !n.endsWith(`.${zone}`)) throw new Error(`Cloudflare: ${name} is not in the zone ${zone}`);
515
+ }
516
+
517
+ return {
518
+ async setTxt(name, value) {
519
+ inZone(name);
520
+ const id = await idOfZone();
521
+ const r = await call("adding a TXT record", "POST", `/zones/${id}/dns_records`, cfRecord, {
522
+ type: "TXT",
523
+ name,
524
+ content: `"${value}"`,
525
+ ttl: 60,
526
+ comment: "ACME DNS-01 challenge",
527
+ });
528
+ made.set(`${name}\n${value}`, r.result.id);
529
+ },
530
+ async removeTxt(name, value) {
531
+ inZone(name);
532
+ const id = await idOfZone();
533
+ const known = made.get(`${name}\n${value}`);
534
+ const ids =
535
+ known !== undefined
536
+ ? [known]
537
+ : (
538
+ await call("finding TXT records", "GET", `/zones/${id}/dns_records?type=TXT&name=${encodeURIComponent(name)}`, cfRecords)
539
+ ).result
540
+ .filter((rec) => rec.content === value || rec.content === `"${value}"`)
541
+ .map((rec) => rec.id);
542
+ for (const recordId of ids) await call("removing a TXT record", "DELETE", `/zones/${id}/dns_records/${recordId}`, cfEnvelope);
543
+ made.delete(`${name}\n${value}`);
544
+ },
545
+ };
546
+ }