@intellectual-frontiers/net 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/acme.d.ts +71 -0
- package/dist/acme.js +475 -0
- package/dist/dns.d.ts +57 -0
- package/dist/dns.js +381 -0
- package/dist/http-client.d.ts +149 -0
- package/dist/http-client.js +248 -0
- package/dist/mod.d.ts +21 -0
- package/dist/mod.js +21 -0
- package/dist/net.d.ts +84 -0
- package/dist/net.js +288 -0
- package/dist/serve.d.ts +33 -0
- package/dist/serve.js +109 -0
- package/dist/tcp.d.ts +77 -0
- package/dist/tcp.js +274 -0
- package/package.json +72 -4
- package/src/acme.ts +546 -0
- package/src/dns.ts +423 -0
- package/src/http-client.ts +369 -0
- package/src/mod.ts +22 -0
- package/src/net.ts +332 -0
- package/src/serve.ts +135 -0
- package/src/tcp.ts +344 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Intellectual Frontiers
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @intellectual-frontiers/net
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The network as one typed library: downloads that retry and resume, an HTTP server over web Request and Response, typed HTTP clients with recorded transports and AWS signing, TCP and TLS, DNS records, and ACME certificates by DNS-01; the same code on Bun and Node 26.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bun add @intellectual-frontiers/net # or: npm install @intellectual-frontiers/net
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/net
|
package/dist/acme.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
2
|
+
/** Let's Encrypt's production directory. */
|
|
3
|
+
export declare const LETS_ENCRYPT = "https://acme-v02.api.letsencrypt.org/directory";
|
|
4
|
+
/** Let's Encrypt's staging directory: certificates no browser trusts, for trying a setup without its rate limits. */
|
|
5
|
+
export declare const LETS_ENCRYPT_STAGING = "https://acme-staging-v02.api.letsencrypt.org/directory";
|
|
6
|
+
/** Where TXT records are set and removed (a zone's DNS host): `name` is the whole name, `value` the record's text. */
|
|
7
|
+
export type DnsProvider = {
|
|
8
|
+
setTxt(name: string, value: string): Promise<void>;
|
|
9
|
+
removeTxt(name: string, value: string): Promise<void>;
|
|
10
|
+
};
|
|
11
|
+
/** What `issue` takes. */
|
|
12
|
+
export type IssueOptions = {
|
|
13
|
+
/** The ACME directory's URL (`LETS_ENCRYPT`, `LETS_ENCRYPT_STAGING`, or another CA's). */
|
|
14
|
+
readonly directory: string;
|
|
15
|
+
/** The names the certificate is for; the first is also its common name. A wildcard (`*.erga.fyi`) is proven at `_acme-challenge.erga.fyi`. */
|
|
16
|
+
readonly domains: readonly string[];
|
|
17
|
+
readonly dns: DnsProvider;
|
|
18
|
+
/** The account's ES256 private key as a JWK; a new one is made where it is absent (and given back to keep). */
|
|
19
|
+
readonly accountKey?: JsonWebKey;
|
|
20
|
+
/** The account's contacts (`mailto:...`), sent when the account is made. */
|
|
21
|
+
readonly contact?: readonly string[];
|
|
22
|
+
/** Called for each TXT record once all are set, before the challenges are answered: wait until the record can be seen. */
|
|
23
|
+
readonly propagationWait?: (name: string, value: string) => Promise<void>;
|
|
24
|
+
/** The `fetch` used (a stub, in tests). */
|
|
25
|
+
readonly fetch?: typeof fetch;
|
|
26
|
+
/** The first wait between two polls, growing by half each time up to ten times this (1000 by default). */
|
|
27
|
+
readonly pollIntervalMs?: number;
|
|
28
|
+
/** How long an authorization or the order may take, in all (300000 by default). */
|
|
29
|
+
readonly pollTimeoutMs?: number;
|
|
30
|
+
};
|
|
31
|
+
/** 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. */
|
|
32
|
+
export type Issued = {
|
|
33
|
+
/** The certificate and its chain, PEM, as the CA gives them. */
|
|
34
|
+
readonly certificatePem: string;
|
|
35
|
+
/** The certificate's ES256 private key, PKCS #8 PEM. */
|
|
36
|
+
readonly privateKeyPem: string;
|
|
37
|
+
/** The account's ES256 private key as a JWK: keep it (it is a secret) and give it to the next `issue`. */
|
|
38
|
+
readonly accountKey: JsonWebKey;
|
|
39
|
+
/** The certificate's `notAfter`, ISO 8601. */
|
|
40
|
+
readonly notAfter: string;
|
|
41
|
+
/** A TXT record that could not be removed, one sentence each (none when all were). */
|
|
42
|
+
readonly warnings: readonly string[];
|
|
43
|
+
};
|
|
44
|
+
/** Bytes as PEM: the label's lines around the base64, 64 characters a line. */
|
|
45
|
+
export declare function pem(label: string, bytes: Uint8Array): string;
|
|
46
|
+
/** 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. */
|
|
47
|
+
export declare function ecdsaRawToDer(raw: Uint8Array): Uint8Array;
|
|
48
|
+
/** The RFC 7638 thumbprint of an EC public JWK: the base64url SHA-256 of `{"crv","kty","x","y"}` in that order. */
|
|
49
|
+
export declare function jwkThumbprint(jwk: JsonWebKey): Promise<string>;
|
|
50
|
+
/** The TXT value of a DNS-01 challenge: the base64url SHA-256 of the key authorization `token.thumbprint` (RFC 8555 §8.4). */
|
|
51
|
+
export declare function dns01Value(token: string, thumbprint: string): Promise<string>;
|
|
52
|
+
/** The name a DNS-01 TXT record is set at for a name (a wildcard's at its base name). */
|
|
53
|
+
export declare function challengeName(domain: string): string;
|
|
54
|
+
/** 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. */
|
|
55
|
+
export declare function csr(domains: readonly string[], keys: CryptoKeyPair): Promise<Uint8Array>;
|
|
56
|
+
/** The `notAfter` of the first certificate in PEM text, or undefined where there is none or it cannot be read. */
|
|
57
|
+
export declare function notAfterOf(certificatePem: string): Date | undefined;
|
|
58
|
+
/** Whether a certificate ends within `days` of `now` (or has ended, or cannot be read): the time to get a new one. */
|
|
59
|
+
export declare function needsRenewal(certificatePem: string, now: Date, days?: number): boolean;
|
|
60
|
+
/**
|
|
61
|
+
* A certificate for `domains` from the ACME server at `directory`, proven by DNS-01 through `dns`; or why not. The TXT records set are
|
|
62
|
+
* removed in every case; one that could not be removed is a warning of the result (or added to its error).
|
|
63
|
+
*/
|
|
64
|
+
export declare function issue(o: IssueOptions): Promise<Result<Issued, string>>;
|
|
65
|
+
/** A `DnsProvider` over Cloudflare's API (v4) for one zone, by an API token allowed to edit its DNS (`Zone.DNS`). */
|
|
66
|
+
export declare function cloudflareDns(o: {
|
|
67
|
+
readonly token: string;
|
|
68
|
+
readonly zone: string;
|
|
69
|
+
readonly api?: string;
|
|
70
|
+
readonly fetch?: typeof fetch;
|
|
71
|
+
}): DnsProvider;
|
package/dist/acme.js
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
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 { array, boolean, formatDecodeError, json, literal, object, string, err, ok, } from "@intellectual-frontiers/core";
|
|
38
|
+
/** Let's Encrypt's production directory. */
|
|
39
|
+
export const LETS_ENCRYPT = "https://acme-v02.api.letsencrypt.org/directory";
|
|
40
|
+
/** Let's Encrypt's staging directory: certificates no browser trusts, for trying a setup without its rate limits. */
|
|
41
|
+
export const LETS_ENCRYPT_STAGING = "https://acme-staging-v02.api.letsencrypt.org/directory";
|
|
42
|
+
const UA = "intellectual-frontiers-commons-acme";
|
|
43
|
+
const PROBLEM = "urn:ietf:params:acme:error:";
|
|
44
|
+
const directoryDecoder = object({ newNonce: string, newAccount: string, newOrder: string });
|
|
45
|
+
const accountDecoder = object({ status: string });
|
|
46
|
+
const orderDecoder = object({ status: string, authorizations: array(string), finalize: string }, { certificate: string });
|
|
47
|
+
const challengeDecoder = object({ type: string, url: string, status: string }, { token: string });
|
|
48
|
+
const authzDecoder = object({ status: string, identifier: object({ type: literal("dns"), value: string }), challenges: array(challengeDecoder) }, { wildcard: boolean });
|
|
49
|
+
const problemDecoder = object({ type: string }, { detail: string });
|
|
50
|
+
function problemOf(reply) {
|
|
51
|
+
const p = json(reply.text, problemDecoder);
|
|
52
|
+
return p.kind === "ok" ? { type: p.value.type, detail: p.value.detail ?? "" } : undefined;
|
|
53
|
+
}
|
|
54
|
+
function describeReply(what, reply) {
|
|
55
|
+
const p = problemOf(reply);
|
|
56
|
+
if (p === undefined)
|
|
57
|
+
return `${what}: the server answered ${reply.status}`;
|
|
58
|
+
const type = p.type.startsWith(PROBLEM) ? p.type.slice(PROBLEM.length) : p.type;
|
|
59
|
+
return `${what}: the server answered ${reply.status} ${type}${p.detail === "" ? "" : ` (${p.detail})`}`;
|
|
60
|
+
}
|
|
61
|
+
function decoded(what, reply, decoder) {
|
|
62
|
+
const d = json(reply.text, decoder);
|
|
63
|
+
return d.kind === "ok" ? d : err(`${what}: the server's answer is not ACME's (${formatDecodeError(d.error)})`);
|
|
64
|
+
}
|
|
65
|
+
function bytesOf(buffer) {
|
|
66
|
+
return new Uint8Array(buffer);
|
|
67
|
+
}
|
|
68
|
+
function utf8(text) {
|
|
69
|
+
return new TextEncoder().encode(text);
|
|
70
|
+
}
|
|
71
|
+
/** Bytes as PEM: the label's lines around the base64, 64 characters a line. */
|
|
72
|
+
export function pem(label, bytes) {
|
|
73
|
+
const b64 = toBase64(bytes);
|
|
74
|
+
const lines = [];
|
|
75
|
+
for (let i = 0; i < b64.length; i += 64)
|
|
76
|
+
lines.push(b64.slice(i, i + 64));
|
|
77
|
+
return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----\n`;
|
|
78
|
+
}
|
|
79
|
+
/** 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. */
|
|
80
|
+
export function ecdsaRawToDer(raw) {
|
|
81
|
+
const half = raw.length / 2;
|
|
82
|
+
return der.sequence(der.integer(raw.subarray(0, half)), der.integer(raw.subarray(half)));
|
|
83
|
+
}
|
|
84
|
+
/** The RFC 7638 thumbprint of an EC public JWK: the base64url SHA-256 of `{"crv","kty","x","y"}` in that order. */
|
|
85
|
+
export async function jwkThumbprint(jwk) {
|
|
86
|
+
const canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
|
|
87
|
+
return toBase64Url(bytesOf(await crypto.subtle.digest("SHA-256", utf8(canonical))));
|
|
88
|
+
}
|
|
89
|
+
/** The TXT value of a DNS-01 challenge: the base64url SHA-256 of the key authorization `token.thumbprint` (RFC 8555 §8.4). */
|
|
90
|
+
export async function dns01Value(token, thumbprint) {
|
|
91
|
+
return toBase64Url(bytesOf(await crypto.subtle.digest("SHA-256", utf8(`${token}.${thumbprint}`))));
|
|
92
|
+
}
|
|
93
|
+
/** The name a DNS-01 TXT record is set at for a name (a wildcard's at its base name). */
|
|
94
|
+
export function challengeName(domain) {
|
|
95
|
+
return `_acme-challenge.${domain.replace(/^\*\./, "")}`;
|
|
96
|
+
}
|
|
97
|
+
const EC = { name: "ECDSA", namedCurve: "P-256" };
|
|
98
|
+
const ES256 = { name: "ECDSA", hash: "SHA-256" };
|
|
99
|
+
/** 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. */
|
|
100
|
+
export async function csr(domains, keys) {
|
|
101
|
+
const first = domains[0] ?? "";
|
|
102
|
+
const subject = first.length > 0 && first.length <= 64
|
|
103
|
+
? der.sequence(der.setOf(der.sequence(der.oid("2.5.4.3"), der.utf8String(first))))
|
|
104
|
+
: der.sequence();
|
|
105
|
+
const spki = bytesOf(await crypto.subtle.exportKey("spki", keys.publicKey));
|
|
106
|
+
const san = der.sequence(...domains.map((d) => der.implicit(2, utf8(d), false)));
|
|
107
|
+
const extensions = der.sequence(der.sequence(der.oid("2.5.29.17"), der.octetString(san)));
|
|
108
|
+
const extensionRequest = der.sequence(der.oid("1.2.840.113549.1.9.14"), der.setOf(extensions));
|
|
109
|
+
const info = der.sequence(der.integer(0), subject, spki, der.implicit(0, extensionRequest, true));
|
|
110
|
+
const signature = bytesOf(await crypto.subtle.sign(ES256, keys.privateKey, new Uint8Array(info)));
|
|
111
|
+
return der.sequence(info, der.algorithm("1.2.840.10045.4.3.2"), der.bitString(ecdsaRawToDer(signature)));
|
|
112
|
+
}
|
|
113
|
+
function readTime(t) {
|
|
114
|
+
const s = new TextDecoder().decode(t.content);
|
|
115
|
+
const m = t.tag === der.TAG.utcTime
|
|
116
|
+
? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
|
|
117
|
+
: t.tag === der.TAG.generalizedTime
|
|
118
|
+
? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s)
|
|
119
|
+
: null;
|
|
120
|
+
if (m === null)
|
|
121
|
+
return undefined;
|
|
122
|
+
const [, y = "", mo = "", d = "", h = "", mi = "", se = ""] = m;
|
|
123
|
+
let year = Number(y);
|
|
124
|
+
if (t.tag === der.TAG.utcTime)
|
|
125
|
+
year += year >= 50 ? 1900 : 2000;
|
|
126
|
+
return new Date(Date.UTC(year, Number(mo) - 1, Number(d), Number(h), Number(mi), Number(se)));
|
|
127
|
+
}
|
|
128
|
+
/** The `notAfter` of the first certificate in PEM text, or undefined where there is none or it cannot be read. */
|
|
129
|
+
export function notAfterOf(certificatePem) {
|
|
130
|
+
const m = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/.exec(certificatePem);
|
|
131
|
+
if (m === null)
|
|
132
|
+
return undefined;
|
|
133
|
+
const bytes = fromBase64(m[1] ?? "");
|
|
134
|
+
if (bytes.kind === "err")
|
|
135
|
+
return undefined;
|
|
136
|
+
const cert = der.readTlv(bytes.value);
|
|
137
|
+
if (cert.kind === "err" || cert.value.tag !== der.TAG.sequence)
|
|
138
|
+
return undefined;
|
|
139
|
+
const top = der.children(cert.value.content);
|
|
140
|
+
const tbs = top.kind === "ok" ? top.value[0] : undefined;
|
|
141
|
+
if (tbs === undefined || tbs.tag !== der.TAG.sequence)
|
|
142
|
+
return undefined;
|
|
143
|
+
const fields = der.children(tbs.content);
|
|
144
|
+
if (fields.kind === "err")
|
|
145
|
+
return undefined;
|
|
146
|
+
const offset = fields.value[0]?.tag === 0xa0 ? 1 : 0;
|
|
147
|
+
const validity = fields.value[offset + 3];
|
|
148
|
+
if (validity === undefined || validity.tag !== der.TAG.sequence)
|
|
149
|
+
return undefined;
|
|
150
|
+
const times = der.children(validity.content);
|
|
151
|
+
const notAfter = times.kind === "ok" ? times.value[1] : undefined;
|
|
152
|
+
return notAfter === undefined ? undefined : readTime(notAfter);
|
|
153
|
+
}
|
|
154
|
+
/** Whether a certificate ends within `days` of `now` (or has ended, or cannot be read): the time to get a new one. */
|
|
155
|
+
export function needsRenewal(certificatePem, now, days = 30) {
|
|
156
|
+
const end = notAfterOf(certificatePem);
|
|
157
|
+
return end === undefined || end.getTime() - now.getTime() < days * 86_400_000;
|
|
158
|
+
}
|
|
159
|
+
async function accountKeyOf(given) {
|
|
160
|
+
try {
|
|
161
|
+
let privateJwk = given;
|
|
162
|
+
if (privateJwk === undefined) {
|
|
163
|
+
const pair = await crypto.subtle.generateKey(EC, true, ["sign", "verify"]);
|
|
164
|
+
privateJwk = await crypto.subtle.exportKey("jwk", pair.privateKey);
|
|
165
|
+
}
|
|
166
|
+
if (privateJwk.kty !== "EC" || privateJwk.crv !== "P-256" || privateJwk.d === undefined)
|
|
167
|
+
return err("the account key is not an ES256 (EC P-256) private JWK");
|
|
168
|
+
const privateKey = await crypto.subtle.importKey("jwk", privateJwk, EC, false, ["sign"]);
|
|
169
|
+
const jwk = { kty: "EC", crv: "P-256", x: privateJwk.x ?? "", y: privateJwk.y ?? "" };
|
|
170
|
+
const { key_ops: _ops, ext: _ext, ...kept } = privateJwk;
|
|
171
|
+
return ok({ privateKey, jwk, privateJwk: kept });
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return err("the account key cannot be used as an ES256 private key");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function sleep(ms) {
|
|
178
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
179
|
+
}
|
|
180
|
+
function retryAfter(headers) {
|
|
181
|
+
const v = headers.get("retry-after");
|
|
182
|
+
if (v === null)
|
|
183
|
+
return undefined;
|
|
184
|
+
const seconds = Number(v);
|
|
185
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
186
|
+
return seconds * 1000;
|
|
187
|
+
const at = Date.parse(v);
|
|
188
|
+
return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());
|
|
189
|
+
}
|
|
190
|
+
function openSession(fetcher, newNonceUrl, key) {
|
|
191
|
+
let nonce;
|
|
192
|
+
const keep = (headers) => {
|
|
193
|
+
const n = headers.get("replay-nonce");
|
|
194
|
+
if (n !== null)
|
|
195
|
+
nonce = n;
|
|
196
|
+
};
|
|
197
|
+
const fresh = async () => {
|
|
198
|
+
if (nonce !== undefined) {
|
|
199
|
+
const n = nonce;
|
|
200
|
+
nonce = undefined;
|
|
201
|
+
return n;
|
|
202
|
+
}
|
|
203
|
+
const r = await fetcher(newNonceUrl, { method: "HEAD", headers: { "user-agent": UA } });
|
|
204
|
+
const n = r.headers.get("replay-nonce");
|
|
205
|
+
if (n === null)
|
|
206
|
+
throw new Error("the server gave no nonce");
|
|
207
|
+
return n;
|
|
208
|
+
};
|
|
209
|
+
const s = {
|
|
210
|
+
kid: undefined,
|
|
211
|
+
async post(url, payload, accept) {
|
|
212
|
+
for (let attempt = 0;; attempt++) {
|
|
213
|
+
const header = { alg: "ES256", nonce: await fresh(), url, ...(s.kid === undefined ? { jwk: key.jwk } : { kid: s.kid }) };
|
|
214
|
+
const protectedB64 = toBase64Url(utf8(JSON.stringify(header)));
|
|
215
|
+
const payloadB64 = payload === undefined ? "" : toBase64Url(utf8(JSON.stringify(payload)));
|
|
216
|
+
const sig = bytesOf(await crypto.subtle.sign(ES256, key.privateKey, utf8(`${protectedB64}.${payloadB64}`)));
|
|
217
|
+
const r = await fetcher(url, {
|
|
218
|
+
method: "POST",
|
|
219
|
+
headers: { "content-type": "application/jose+json", "user-agent": UA, ...(accept === undefined ? {} : { accept }) },
|
|
220
|
+
body: JSON.stringify({ protected: protectedB64, payload: payloadB64, signature: toBase64Url(sig) }),
|
|
221
|
+
});
|
|
222
|
+
keep(r.headers);
|
|
223
|
+
const reply = { status: r.status, headers: r.headers, text: await r.text() };
|
|
224
|
+
if (reply.status === 400 && attempt < 5 && problemOf(reply)?.type === `${PROBLEM}badNonce`)
|
|
225
|
+
continue;
|
|
226
|
+
return reply;
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
return s;
|
|
231
|
+
}
|
|
232
|
+
async function poll(session, what, url, decoder, pending, o) {
|
|
233
|
+
const first = o.pollIntervalMs ?? 1000;
|
|
234
|
+
const deadline = Date.now() + (o.pollTimeoutMs ?? 300_000);
|
|
235
|
+
let wait = first;
|
|
236
|
+
for (;;) {
|
|
237
|
+
const reply = await session.post(url, undefined);
|
|
238
|
+
if (reply.status !== 200)
|
|
239
|
+
return err(describeReply(what, reply));
|
|
240
|
+
const d = decoded(what, reply, decoder);
|
|
241
|
+
if (d.kind === "err" || !pending.includes(d.value.status))
|
|
242
|
+
return d;
|
|
243
|
+
const next = retryAfter(reply.headers) ?? wait;
|
|
244
|
+
if (Date.now() + next > deadline)
|
|
245
|
+
return err(`${what}: still ${d.value.status} when the wait ran out`);
|
|
246
|
+
await sleep(next);
|
|
247
|
+
wait = Math.min(wait * 1.5, first * 10);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async function getAccount(session, url, given, contact) {
|
|
251
|
+
if (given) {
|
|
252
|
+
const found = await session.post(url, { onlyReturnExisting: true });
|
|
253
|
+
if (found.status === 200) {
|
|
254
|
+
const kid = found.headers.get("location");
|
|
255
|
+
if (kid === null)
|
|
256
|
+
return err("finding the account: the server gave no account URL");
|
|
257
|
+
const a = decoded("finding the account", found, accountDecoder);
|
|
258
|
+
if (a.kind === "err")
|
|
259
|
+
return a;
|
|
260
|
+
if (a.value.status !== "valid")
|
|
261
|
+
return err(`finding the account: it is ${a.value.status}`);
|
|
262
|
+
session.kid = kid;
|
|
263
|
+
return ok(undefined);
|
|
264
|
+
}
|
|
265
|
+
if (problemOf(found)?.type !== `${PROBLEM}accountDoesNotExist`)
|
|
266
|
+
return err(describeReply("finding the account", found));
|
|
267
|
+
}
|
|
268
|
+
const made = await session.post(url, { termsOfServiceAgreed: true, ...(contact === undefined ? {} : { contact }) });
|
|
269
|
+
if (made.status !== 201 && made.status !== 200)
|
|
270
|
+
return err(describeReply("making the account", made));
|
|
271
|
+
const kid = made.headers.get("location");
|
|
272
|
+
if (kid === null)
|
|
273
|
+
return err("making the account: the server gave no account URL");
|
|
274
|
+
const a = decoded("making the account", made, accountDecoder);
|
|
275
|
+
if (a.kind === "err")
|
|
276
|
+
return a;
|
|
277
|
+
if (a.value.status !== "valid")
|
|
278
|
+
return err(`making the account: it is ${a.value.status}`);
|
|
279
|
+
session.kid = kid;
|
|
280
|
+
return ok(undefined);
|
|
281
|
+
}
|
|
282
|
+
async function run(o, key, fetcher, set) {
|
|
283
|
+
const domains = o.domains.map((d) => d.toLowerCase());
|
|
284
|
+
const dirReply = await fetcher(o.directory, { headers: { "user-agent": UA } });
|
|
285
|
+
if (dirReply.status !== 200)
|
|
286
|
+
return err(`reading the directory: the server answered ${dirReply.status}`);
|
|
287
|
+
const dir = decoded("reading the directory", { status: 200, headers: dirReply.headers, text: await dirReply.text() }, directoryDecoder);
|
|
288
|
+
if (dir.kind === "err")
|
|
289
|
+
return dir;
|
|
290
|
+
const session = openSession(fetcher, dir.value.newNonce, key);
|
|
291
|
+
const account = await getAccount(session, dir.value.newAccount, o.accountKey !== undefined, o.contact);
|
|
292
|
+
if (account.kind === "err")
|
|
293
|
+
return account;
|
|
294
|
+
const placed = await session.post(dir.value.newOrder, { identifiers: domains.map((value) => ({ type: "dns", value })) });
|
|
295
|
+
if (placed.status !== 201)
|
|
296
|
+
return err(describeReply("placing the order", placed));
|
|
297
|
+
const orderUrl = placed.headers.get("location");
|
|
298
|
+
if (orderUrl === null)
|
|
299
|
+
return err("placing the order: the server gave no order URL");
|
|
300
|
+
const order = decoded("placing the order", placed, orderDecoder);
|
|
301
|
+
if (order.kind === "err")
|
|
302
|
+
return order;
|
|
303
|
+
if (order.value.status === "invalid")
|
|
304
|
+
return err("placing the order: the order is invalid");
|
|
305
|
+
const thumbprint = await jwkThumbprint(key.jwk);
|
|
306
|
+
const answer = [];
|
|
307
|
+
for (const authzUrl of order.value.authorizations) {
|
|
308
|
+
const reply = await session.post(authzUrl, undefined);
|
|
309
|
+
if (reply.status !== 200)
|
|
310
|
+
return err(describeReply("reading an authorization", reply));
|
|
311
|
+
const authz = decoded("reading an authorization", reply, authzDecoder);
|
|
312
|
+
if (authz.kind === "err")
|
|
313
|
+
return authz;
|
|
314
|
+
const domain = authz.value.identifier.value;
|
|
315
|
+
if (authz.value.status === "valid")
|
|
316
|
+
continue;
|
|
317
|
+
if (authz.value.status !== "pending")
|
|
318
|
+
return err(`the authorization of ${domain} is ${authz.value.status}`);
|
|
319
|
+
const ch = authz.value.challenges.find((c) => c.type === "dns-01");
|
|
320
|
+
if (ch === undefined || ch.token === undefined)
|
|
321
|
+
return err(`the authorization of ${domain} offers no dns-01 challenge`);
|
|
322
|
+
const txt = { name: challengeName(domain), value: await dns01Value(ch.token, thumbprint) };
|
|
323
|
+
await o.dns.setTxt(txt.name, txt.value);
|
|
324
|
+
set.push(txt);
|
|
325
|
+
answer.push({ authz: authzUrl, challenge: ch.url, domain });
|
|
326
|
+
}
|
|
327
|
+
if (o.propagationWait !== undefined)
|
|
328
|
+
for (const t of set)
|
|
329
|
+
await o.propagationWait(t.name, t.value);
|
|
330
|
+
for (const a of answer) {
|
|
331
|
+
const reply = await session.post(a.challenge, {});
|
|
332
|
+
if (reply.status !== 200)
|
|
333
|
+
return err(describeReply(`answering the challenge of ${a.domain}`, reply));
|
|
334
|
+
}
|
|
335
|
+
for (const a of answer) {
|
|
336
|
+
const done = await poll(session, `the authorization of ${a.domain}`, a.authz, authzDecoder, ["pending", "processing"], o);
|
|
337
|
+
if (done.kind === "err")
|
|
338
|
+
return done;
|
|
339
|
+
if (done.value.status !== "valid") {
|
|
340
|
+
const why = done.value.challenges.find((c) => c.type === "dns-01")?.status ?? done.value.status;
|
|
341
|
+
return err(`the authorization of ${a.domain} is ${done.value.status} (its dns-01 challenge is ${why})`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const certKeys = await crypto.subtle.generateKey(EC, true, ["sign", "verify"]);
|
|
345
|
+
const request = await csr(domains, certKeys);
|
|
346
|
+
const finalized = await session.post(order.value.finalize, { csr: toBase64Url(request) });
|
|
347
|
+
if (finalized.status !== 200)
|
|
348
|
+
return err(describeReply("finalizing the order", finalized));
|
|
349
|
+
const final = await poll(session, "the order", orderUrl, orderDecoder, ["pending", "ready", "processing"], o);
|
|
350
|
+
if (final.kind === "err")
|
|
351
|
+
return final;
|
|
352
|
+
if (final.value.status !== "valid" || final.value.certificate === undefined)
|
|
353
|
+
return err(`the order is ${final.value.status}, with no certificate`);
|
|
354
|
+
const cert = await session.post(final.value.certificate, undefined, "application/pem-certificate-chain");
|
|
355
|
+
if (cert.status !== 200)
|
|
356
|
+
return err(describeReply("downloading the certificate", cert));
|
|
357
|
+
const notAfter = notAfterOf(cert.text);
|
|
358
|
+
if (notAfter === undefined)
|
|
359
|
+
return err("downloading the certificate: what came is not a PEM certificate");
|
|
360
|
+
const pkcs8 = bytesOf(await crypto.subtle.exportKey("pkcs8", certKeys.privateKey));
|
|
361
|
+
return ok({
|
|
362
|
+
certificatePem: cert.text,
|
|
363
|
+
privateKeyPem: pem("PRIVATE KEY", pkcs8),
|
|
364
|
+
accountKey: key.privateJwk,
|
|
365
|
+
notAfter: notAfter.toISOString(),
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
function reason(e) {
|
|
369
|
+
return e instanceof Error ? e.message : String(e);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* A certificate for `domains` from the ACME server at `directory`, proven by DNS-01 through `dns`; or why not. The TXT records set are
|
|
373
|
+
* removed in every case; one that could not be removed is a warning of the result (or added to its error).
|
|
374
|
+
*/
|
|
375
|
+
export async function issue(o) {
|
|
376
|
+
if (o.domains.length === 0)
|
|
377
|
+
return err("no names to issue a certificate for");
|
|
378
|
+
const key = await accountKeyOf(o.accountKey);
|
|
379
|
+
if (key.kind === "err")
|
|
380
|
+
return key;
|
|
381
|
+
const fetcher = o.fetch ?? fetch;
|
|
382
|
+
const set = [];
|
|
383
|
+
let result;
|
|
384
|
+
try {
|
|
385
|
+
result = await run(o, key.value, fetcher, set);
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
result = err(`the certificate could not be issued: ${reason(e)}`);
|
|
389
|
+
}
|
|
390
|
+
const warnings = [];
|
|
391
|
+
for (const t of set) {
|
|
392
|
+
try {
|
|
393
|
+
await o.dns.removeTxt(t.name, t.value);
|
|
394
|
+
}
|
|
395
|
+
catch (e) {
|
|
396
|
+
warnings.push(`the TXT record at ${t.name} could not be removed: ${reason(e)}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (result.kind === "err")
|
|
400
|
+
return warnings.length === 0 ? result : err(`${result.error}; and ${warnings.join("; ")}`);
|
|
401
|
+
return ok({ ...result.value, warnings });
|
|
402
|
+
}
|
|
403
|
+
const cfEnvelope = object({ success: boolean });
|
|
404
|
+
const cfError = object({ errors: array(object({ message: string })) });
|
|
405
|
+
const cfZones = object({ result: array(object({ id: string, name: string })) });
|
|
406
|
+
const cfRecord = object({ result: object({ id: string }) });
|
|
407
|
+
const cfRecords = object({ result: array(object({ id: string, content: string })) });
|
|
408
|
+
/** A `DnsProvider` over Cloudflare's API (v4) for one zone, by an API token allowed to edit its DNS (`Zone.DNS`). */
|
|
409
|
+
export function cloudflareDns(o) {
|
|
410
|
+
const api = (o.api ?? "https://api.cloudflare.com/client/v4").replace(/\/+$/, "");
|
|
411
|
+
const fetcher = o.fetch ?? fetch;
|
|
412
|
+
const zone = o.zone.toLowerCase();
|
|
413
|
+
const made = new Map();
|
|
414
|
+
let zoneId;
|
|
415
|
+
async function call(what, method, path, decoder, body) {
|
|
416
|
+
const r = await fetcher(`${api}${path}`, {
|
|
417
|
+
method,
|
|
418
|
+
headers: { authorization: `Bearer ${o.token}`, "content-type": "application/json" },
|
|
419
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
420
|
+
});
|
|
421
|
+
const text = await r.text();
|
|
422
|
+
const env = json(text, cfEnvelope);
|
|
423
|
+
if (!r.ok || env.kind === "err" || !env.value.success) {
|
|
424
|
+
const errors = json(text, cfError);
|
|
425
|
+
const said = errors.kind === "ok" ? errors.value.errors.map((e) => e.message).join("; ") : "";
|
|
426
|
+
throw new Error(`Cloudflare, ${what}: ${r.status}${said === "" ? "" : ` (${said})`}`);
|
|
427
|
+
}
|
|
428
|
+
const d = json(text, decoder);
|
|
429
|
+
if (d.kind === "err")
|
|
430
|
+
throw new Error(`Cloudflare, ${what}: an answer not understood (${formatDecodeError(d.error)})`);
|
|
431
|
+
return d.value;
|
|
432
|
+
}
|
|
433
|
+
async function idOfZone() {
|
|
434
|
+
if (zoneId !== undefined)
|
|
435
|
+
return zoneId;
|
|
436
|
+
const zones = await call("finding the zone", "GET", `/zones?name=${encodeURIComponent(zone)}`, cfZones);
|
|
437
|
+
const z = zones.result.find((x) => x.name.toLowerCase() === zone);
|
|
438
|
+
if (z === undefined)
|
|
439
|
+
throw new Error(`Cloudflare: no zone ${zone} for this token`);
|
|
440
|
+
zoneId = z.id;
|
|
441
|
+
return z.id;
|
|
442
|
+
}
|
|
443
|
+
function inZone(name) {
|
|
444
|
+
const n = name.toLowerCase();
|
|
445
|
+
if (n !== zone && !n.endsWith(`.${zone}`))
|
|
446
|
+
throw new Error(`Cloudflare: ${name} is not in the zone ${zone}`);
|
|
447
|
+
}
|
|
448
|
+
return {
|
|
449
|
+
async setTxt(name, value) {
|
|
450
|
+
inZone(name);
|
|
451
|
+
const id = await idOfZone();
|
|
452
|
+
const r = await call("adding a TXT record", "POST", `/zones/${id}/dns_records`, cfRecord, {
|
|
453
|
+
type: "TXT",
|
|
454
|
+
name,
|
|
455
|
+
content: `"${value}"`,
|
|
456
|
+
ttl: 60,
|
|
457
|
+
comment: "ACME DNS-01 challenge",
|
|
458
|
+
});
|
|
459
|
+
made.set(`${name}\n${value}`, r.result.id);
|
|
460
|
+
},
|
|
461
|
+
async removeTxt(name, value) {
|
|
462
|
+
inZone(name);
|
|
463
|
+
const id = await idOfZone();
|
|
464
|
+
const known = made.get(`${name}\n${value}`);
|
|
465
|
+
const ids = known !== undefined
|
|
466
|
+
? [known]
|
|
467
|
+
: (await call("finding TXT records", "GET", `/zones/${id}/dns_records?type=TXT&name=${encodeURIComponent(name)}`, cfRecords)).result
|
|
468
|
+
.filter((rec) => rec.content === value || rec.content === `"${value}"`)
|
|
469
|
+
.map((rec) => rec.id);
|
|
470
|
+
for (const recordId of ids)
|
|
471
|
+
await call("removing a TXT record", "DELETE", `/zones/${id}/dns_records/${recordId}`, cfEnvelope);
|
|
472
|
+
made.delete(`${name}\n${value}`);
|
|
473
|
+
},
|
|
474
|
+
};
|
|
475
|
+
}
|
package/dist/dns.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
2
|
+
/** The record types that can be asked for. */
|
|
3
|
+
export type RecordType = "A" | "AAAA" | "CNAME" | "MX" | "NS" | "TXT" | "SRV";
|
|
4
|
+
/** A mail exchanger. */
|
|
5
|
+
export type MxRecord = {
|
|
6
|
+
readonly preference: number;
|
|
7
|
+
readonly exchange: string;
|
|
8
|
+
};
|
|
9
|
+
/** A service's host and port. */
|
|
10
|
+
export type SrvRecord = {
|
|
11
|
+
readonly priority: number;
|
|
12
|
+
readonly weight: number;
|
|
13
|
+
readonly port: number;
|
|
14
|
+
readonly target: string;
|
|
15
|
+
};
|
|
16
|
+
/** The shape of one record of each type: an address or a name as a string, `TXT` as its strings (join them for the whole text). */
|
|
17
|
+
export type RecordOf = {
|
|
18
|
+
readonly A: string;
|
|
19
|
+
readonly AAAA: string;
|
|
20
|
+
readonly CNAME: string;
|
|
21
|
+
readonly NS: string;
|
|
22
|
+
readonly MX: MxRecord;
|
|
23
|
+
readonly TXT: readonly string[];
|
|
24
|
+
readonly SRV: SrvRecord;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Why there is no answer: the name does not exist (NXDOMAIN), it has no record of that type, or the DNS could not be asked (`code` is
|
|
28
|
+
* `ESERVFAIL`, `EREFUSED`, `EFORMERR`, `ENOTIMP` or `ERCODE<n>` for the server's answer, `ETIMEOUT`, `ECANCELLED`, `EBADRESP` for an
|
|
29
|
+
* answer that cannot be read, `EBADNAME`, `ENOSERVERS`, or the host's error code, such as `ECONNREFUSED`).
|
|
30
|
+
*/
|
|
31
|
+
export type DnsError = {
|
|
32
|
+
readonly kind: "not-found";
|
|
33
|
+
readonly name: string;
|
|
34
|
+
} | {
|
|
35
|
+
readonly kind: "no-data";
|
|
36
|
+
readonly name: string;
|
|
37
|
+
readonly type: RecordType;
|
|
38
|
+
} | {
|
|
39
|
+
readonly kind: "failed";
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly code: string;
|
|
42
|
+
readonly message: string;
|
|
43
|
+
};
|
|
44
|
+
/** The server to ask, instead of the system's. */
|
|
45
|
+
export type NameServer = {
|
|
46
|
+
readonly ipAddr: string;
|
|
47
|
+
readonly port?: number;
|
|
48
|
+
};
|
|
49
|
+
/** How to ask. */
|
|
50
|
+
export type ResolveDnsOptions = {
|
|
51
|
+
/** The server to ask; the system's where not given. */
|
|
52
|
+
readonly nameServer?: NameServer;
|
|
53
|
+
/** Aborting it gives up (a `failed` error with code `ECANCELLED`). */
|
|
54
|
+
readonly signal?: AbortSignal;
|
|
55
|
+
};
|
|
56
|
+
/** The records of a type for a name, or why there are none. */
|
|
57
|
+
export declare function resolveDns<T extends RecordType>(name: string, type: T, options?: ResolveDnsOptions): Promise<Result<readonly RecordOf[T][], DnsError>>;
|