@blamejs/core 0.7.18 → 0.7.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +427 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +350 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +399 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/fetch-metadata.js +129 -0
  86. package/lib/middleware/health.js +392 -392
  87. package/lib/middleware/index.js +85 -79
  88. package/lib/middleware/rate-limit.js +358 -358
  89. package/lib/middleware/request-id.js +61 -61
  90. package/lib/middleware/request-log.js +168 -168
  91. package/lib/middleware/require-auth.js +104 -104
  92. package/lib/middleware/security-headers.js +121 -116
  93. package/lib/middleware/sse.js +166 -166
  94. package/lib/migrations.js +383 -383
  95. package/lib/mtls-ca.js +518 -518
  96. package/lib/mtls-engine-default.js +481 -481
  97. package/lib/network-dns.js +632 -632
  98. package/lib/network-heartbeat.js +290 -290
  99. package/lib/network-nts.js +574 -574
  100. package/lib/network-proxy.js +265 -265
  101. package/lib/network-tls.js +328 -328
  102. package/lib/network.js +233 -233
  103. package/lib/notify.js +612 -612
  104. package/lib/ntp-check.js +229 -229
  105. package/lib/numeric-bounds.js +111 -111
  106. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  107. package/lib/object-store/azure-blob.js +488 -488
  108. package/lib/object-store/gcs-bucket-ops.js +351 -351
  109. package/lib/object-store/gcs.js +519 -519
  110. package/lib/object-store/http-put.js +153 -153
  111. package/lib/object-store/index.js +197 -197
  112. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  113. package/lib/object-store/sigv4.js +903 -903
  114. package/lib/observability.js +151 -151
  115. package/lib/otel-export.js +269 -269
  116. package/lib/pagination.js +464 -464
  117. package/lib/parsers/index.js +80 -80
  118. package/lib/parsers/safe-env.js +642 -642
  119. package/lib/parsers/safe-ini.js +292 -292
  120. package/lib/parsers/safe-toml.js +784 -784
  121. package/lib/parsers/safe-xml.js +390 -390
  122. package/lib/parsers/safe-yaml.js +1015 -1015
  123. package/lib/permissions.js +708 -708
  124. package/lib/pqc-agent.js +87 -87
  125. package/lib/pqc-gate.js +279 -279
  126. package/lib/protobuf-encoder.js +190 -190
  127. package/lib/protocol-dispatcher.js +161 -161
  128. package/lib/pubsub-redis.js +167 -167
  129. package/lib/pubsub.js +429 -429
  130. package/lib/queue-local.js +476 -476
  131. package/lib/queue-redis.js +745 -745
  132. package/lib/queue-sqs.js +319 -319
  133. package/lib/queue.js +695 -695
  134. package/lib/redis-client.js +519 -519
  135. package/lib/request-helpers.js +340 -340
  136. package/lib/restore-bundle.js +237 -237
  137. package/lib/restore-rollback.js +259 -259
  138. package/lib/restore.js +409 -409
  139. package/lib/retry.js +376 -376
  140. package/lib/router.js +748 -748
  141. package/lib/safe-async.js +735 -735
  142. package/lib/safe-buffer.js +237 -237
  143. package/lib/safe-json.js +541 -541
  144. package/lib/safe-schema.js +1266 -1266
  145. package/lib/safe-url.js +159 -159
  146. package/lib/scheduler.js +706 -706
  147. package/lib/security-assert.js +373 -373
  148. package/lib/seeders.js +618 -618
  149. package/lib/session.js +535 -478
  150. package/lib/slug.js +269 -269
  151. package/lib/ssrf-guard.js +401 -401
  152. package/lib/static.js +7 -5
  153. package/lib/storage.js +471 -471
  154. package/lib/subject.js +281 -281
  155. package/lib/template.js +791 -791
  156. package/lib/testing.js +798 -798
  157. package/lib/time.js +310 -310
  158. package/lib/totp.js +302 -302
  159. package/lib/tracing.js +494 -494
  160. package/lib/uuid.js +132 -132
  161. package/lib/validate-opts.js +340 -340
  162. package/lib/vault/index.js +308 -308
  163. package/lib/vault/rotate.js +784 -784
  164. package/lib/vault/wrap.js +296 -296
  165. package/lib/vendor/noble-ciphers.cjs +9 -9
  166. package/lib/webhook.js +595 -595
  167. package/lib/websocket.js +1048 -1048
  168. package/package.json +77 -77
  169. package/sbom.cyclonedx.json +7 -7
@@ -1,632 +1,632 @@
1
- "use strict";
2
-
3
- var dns = require("node:dns");
4
- var net = require("node:net");
5
- var nodeCrypto = require("node:crypto");
6
- var https = require("node:https");
7
- var tls = require("node:tls");
8
- var dnsPromises = dns.promises;
9
-
10
- var C = require("./constants");
11
- var lazyRequire = require("./lazy-require");
12
- var safeBuffer = require("./safe-buffer");
13
- var safeUrl = require("./safe-url");
14
- var validateOpts = require("./validate-opts");
15
- var { defineClass } = require("./framework-error");
16
-
17
- var DnsError = defineClass("DnsError", { alwaysPermanent: false });
18
-
19
- // Protocol-fixed byte counts and radixes — passthrough through C.BYTES
20
- // keeps every numeric literal routed through one helper.
21
- var DNS_QTYPE_AAAA = 28; // RFC 3596 — IPv6 record type
22
- var IPV6_ADDR_BYTES = C.BYTES.bytes(16); // IPv6 address octet length
23
- var IPV6_HEX_GROUPS = C.BYTES.bytes(8); // IPv6 16-bit hex groups
24
- var HEX_RADIX = C.BYTES.bytes(16); // parseInt / toString radix-16
25
-
26
- var observability = lazyRequire(function () { return require("./observability"); });
27
-
28
- var STATE = {
29
- servers: null,
30
- resultOrder: null,
31
- family: 0,
32
- lookupTimeoutMs: 0,
33
- cacheTtlMs: 0,
34
- cacheNegativeTtlMs: 0,
35
- doh: null,
36
- dot: null,
37
- };
38
-
39
- var POSITIVE_CACHE = new Map();
40
- var NEGATIVE_CACHE = new Map();
41
-
42
- function _now() { return Date.now(); }
43
-
44
- function _cacheGet(host, family) {
45
- var key = host + "/" + family;
46
- var pos = POSITIVE_CACHE.get(key);
47
- if (pos && pos.expiresAt > _now()) return { hit: true, value: pos.value };
48
- if (pos) POSITIVE_CACHE.delete(key);
49
- var neg = NEGATIVE_CACHE.get(key);
50
- if (neg && neg.expiresAt > _now()) return { hit: true, error: neg.error };
51
- if (neg) NEGATIVE_CACHE.delete(key);
52
- return { hit: false };
53
- }
54
-
55
- function _cachePutPositive(host, family, value) {
56
- if (STATE.cacheTtlMs <= 0) return;
57
- POSITIVE_CACHE.set(host + "/" + family, {
58
- value: value,
59
- expiresAt: _now() + STATE.cacheTtlMs,
60
- });
61
- }
62
-
63
- function _cachePutNegative(host, family, error) {
64
- if (STATE.cacheTtlMs <= 0) return;
65
- var ttl = STATE.cacheNegativeTtlMs > 0 ? STATE.cacheNegativeTtlMs : Math.min(STATE.cacheTtlMs, C.TIME.seconds(30));
66
- NEGATIVE_CACHE.set(host + "/" + family, {
67
- error: error,
68
- expiresAt: _now() + ttl,
69
- });
70
- }
71
-
72
- function _clearCache() {
73
- POSITIVE_CACHE.clear();
74
- NEGATIVE_CACHE.clear();
75
- }
76
-
77
- function setServers(serverList) {
78
- if (!Array.isArray(serverList) || serverList.length === 0) {
79
- throw new DnsError("dns/bad-servers", "dns.setServers: expected non-empty array of resolver IPs");
80
- }
81
- for (var i = 0; i < serverList.length; i++) {
82
- var s = serverList[i];
83
- if (typeof s !== "string" || s.length === 0) {
84
- throw new DnsError("dns/bad-server", "dns.setServers[" + i + "]: expected non-empty string, got " + typeof s);
85
- }
86
- }
87
- STATE.servers = serverList.slice();
88
- try { dns.setServers(serverList); } catch (e) {
89
- throw new DnsError("dns/setservers-failed", "dns.setServers failed: " + e.message);
90
- }
91
- _clearCache();
92
- _emitObs("network.dns.servers.set", { count: serverList.length });
93
- }
94
-
95
- function getServers() {
96
- if (STATE.servers) return STATE.servers.slice();
97
- try { return dns.getServers(); } catch (_e) { return []; }
98
- }
99
-
100
- function setResultOrder(order) {
101
- if (order !== "ipv4first" && order !== "verbatim" && order !== "ipv6first") {
102
- throw new DnsError("dns/bad-result-order",
103
- "dns.setResultOrder: expected 'ipv4first' | 'verbatim' | 'ipv6first', got " + JSON.stringify(order));
104
- }
105
- STATE.resultOrder = order;
106
- if (order === "ipv6first") {
107
- try { dns.setDefaultResultOrder("verbatim"); } catch (_e) { /* node may not support setter on this version — best-effort */ }
108
- } else {
109
- try { dns.setDefaultResultOrder(order); } catch (_e) { /* node may not support setter on this version — best-effort */ }
110
- }
111
- _clearCache();
112
- _emitObs("network.dns.result_order.set", { order: order });
113
- }
114
-
115
- function setFamily(fam) {
116
- if (fam !== 0 && fam !== 4 && fam !== 6) {
117
- throw new DnsError("dns/bad-family", "dns.setFamily: expected 0 | 4 | 6, got " + JSON.stringify(fam));
118
- }
119
- STATE.family = fam;
120
- _clearCache();
121
- }
122
-
123
- function setLookupTimeoutMs(ms) {
124
- if (typeof ms !== "number" || !isFinite(ms) || ms < 0) {
125
- throw new DnsError("dns/bad-timeout",
126
- "dns.setLookupTimeoutMs: expected non-negative finite number, got " + JSON.stringify(ms));
127
- }
128
- STATE.lookupTimeoutMs = ms;
129
- }
130
-
131
- function setCacheTtlMs(ms, negativeMs) {
132
- if (typeof ms !== "number" || !isFinite(ms) || ms < 0) {
133
- throw new DnsError("dns/bad-cache-ttl",
134
- "dns.setCacheTtlMs: expected non-negative finite number, got " + JSON.stringify(ms));
135
- }
136
- STATE.cacheTtlMs = ms;
137
- if (negativeMs !== undefined) {
138
- if (typeof negativeMs !== "number" || !isFinite(negativeMs) || negativeMs < 0) {
139
- throw new DnsError("dns/bad-cache-ttl",
140
- "dns.setCacheTtlMs negativeMs: expected non-negative finite number, got " + JSON.stringify(negativeMs));
141
- }
142
- STATE.cacheNegativeTtlMs = negativeMs;
143
- }
144
- if (ms === 0) _clearCache();
145
- }
146
-
147
- function useDnsOverHttps(opts) {
148
- opts = opts || {};
149
- validateOpts(opts, ["provider", "url", "method", "ca"], "dns.useDnsOverHttps");
150
- var url = opts.url;
151
- if (!url && opts.provider) {
152
- var p = String(opts.provider).toLowerCase();
153
- if (p === "cloudflare") url = "https://cloudflare-dns.com/dns-query";
154
- else if (p === "google") url = "https://dns.google/dns-query";
155
- else if (p === "quad9") url = "https://dns.quad9.net/dns-query";
156
- else throw new DnsError("dns/bad-doh-provider", "dns.useDnsOverHttps: unknown provider '" + opts.provider + "'");
157
- }
158
- if (typeof url !== "string" || url.indexOf("https://") !== 0) {
159
- throw new DnsError("dns/bad-doh-url",
160
- "dns.useDnsOverHttps: url must be an https:// string, got " + JSON.stringify(url));
161
- }
162
- var method = opts.method;
163
- if (method !== undefined && method !== "GET" && method !== "POST") {
164
- throw new DnsError("dns/bad-doh-method",
165
- "dns.useDnsOverHttps: method must be 'GET' | 'POST' | undefined (auto), got " +
166
- JSON.stringify(method));
167
- }
168
- if (opts.ca !== undefined && opts.ca !== null &&
169
- !Buffer.isBuffer(opts.ca) && typeof opts.ca !== "string" && !Array.isArray(opts.ca)) {
170
- throw new DnsError("dns/bad-doh-ca",
171
- "dns.useDnsOverHttps: ca must be a PEM string, Buffer, or array of either");
172
- }
173
- STATE.doh = { url: url, method: method, ca: opts.ca || null };
174
- _clearCache();
175
- _emitObs("network.dns.doh.set", { url: url, method: method || "auto" });
176
- }
177
-
178
- function useDnsOverTls(opts) {
179
- opts = opts || {};
180
- validateOpts(opts, ["host", "port", "servername", "ca"], "dns.useDnsOverTls");
181
- validateOpts.requireNonEmptyString(opts.host, "dns.useDnsOverTls: host", DnsError, "dns/bad-dot-host");
182
- if (opts.ca !== undefined && opts.ca !== null &&
183
- !Buffer.isBuffer(opts.ca) && typeof opts.ca !== "string" && !Array.isArray(opts.ca)) {
184
- throw new DnsError("dns/bad-dot-ca",
185
- "dns.useDnsOverTls: ca must be a PEM string, Buffer, or array of either");
186
- }
187
- STATE.dot = {
188
- host: opts.host,
189
- port: opts.port || 853,
190
- servername: opts.servername || opts.host,
191
- ca: opts.ca || null,
192
- };
193
- _resetDotPool();
194
- _clearCache();
195
- _emitObs("network.dns.dot.set", { host: STATE.dot.host, port: STATE.dot.port });
196
- }
197
-
198
- function _withTimeout(promise, ms, host) {
199
- if (ms <= 0) return promise;
200
- return new Promise(function (resolve, reject) {
201
- var timer = setTimeout(function () {
202
- reject(new DnsError("dns/lookup-timeout", "dns lookup of '" + host + "' exceeded " + ms + "ms"));
203
- }, ms);
204
- timer.unref && timer.unref();
205
- promise.then(
206
- function (v) { clearTimeout(timer); resolve(v); },
207
- function (e) { clearTimeout(timer); reject(e); }
208
- );
209
- });
210
- }
211
-
212
- function _encodeDnsQuery(host, qtype) {
213
- var parts = host.split(".").filter(Boolean);
214
- var nameLen = 1;
215
- for (var i = 0; i < parts.length; i++) nameLen += 1 + Buffer.byteLength(parts[i], "ascii");
216
- var buf = Buffer.alloc(12 + nameLen + 4);
217
- // Cryptographic RNG for the 16-bit DNS query ID — frustrates poisoning
218
- // attempts that guess the transaction ID. Math.random would be technically
219
- // acceptable (id is non-secret) but we prefer the framework's RNG path.
220
- var id = nodeCrypto.randomInt(0, 0x10000);
221
- buf.writeUInt16BE(id, 0);
222
- buf.writeUInt16BE(0x0100, 2);
223
- buf.writeUInt16BE(1, 4);
224
- var off = 12;
225
- for (var p = 0; p < parts.length; p++) {
226
- var s = parts[p];
227
- buf.writeUInt8(Buffer.byteLength(s, "ascii"), off++);
228
- off += buf.write(s, off, "ascii");
229
- }
230
- buf.writeUInt8(0, off++);
231
- buf.writeUInt16BE(qtype, off); off += 2;
232
- buf.writeUInt16BE(1, off);
233
- return { buf: buf, id: id };
234
- }
235
-
236
- function _decodeDnsAnswer(buf, qtype) {
237
- if (!Buffer.isBuffer(buf) || buf.length < 12) throw new DnsError("dns/bad-reply", "dns reply truncated");
238
- var rcode = buf.readUInt8(3) & 0x0f;
239
- if (rcode !== 0) throw new DnsError("dns/no-result", "dns reply rcode " + rcode);
240
- var qdcount = buf.readUInt16BE(4);
241
- var ancount = buf.readUInt16BE(6);
242
- var off = 12;
243
- for (var q = 0; q < qdcount; q++) {
244
- while (off < buf.length && buf[off] !== 0) {
245
- if ((buf[off] & 0xc0) === 0xc0) { off += 2; break; }
246
- off += buf[off] + 1;
247
- }
248
- if (buf[off] === 0) off++;
249
- off += 4;
250
- }
251
- var addrs = [];
252
- for (var a = 0; a < ancount; a++) {
253
- while (off < buf.length && buf[off] !== 0) {
254
- if ((buf[off] & 0xc0) === 0xc0) { off += 2; break; }
255
- off += buf[off] + 1;
256
- }
257
- if (buf[off] === 0) off++;
258
- var rtype = buf.readUInt16BE(off); off += 2;
259
- off += 2;
260
- off += 4;
261
- var rdlen = buf.readUInt16BE(off); off += 2;
262
- if (rtype === qtype && qtype === 1 && rdlen === 4) {
263
- addrs.push(buf[off] + "." + buf[off + 1] + "." + buf[off + 2] + "." + buf[off + 3]);
264
- } else if (rtype === qtype && qtype === DNS_QTYPE_AAAA && rdlen === IPV6_ADDR_BYTES) {
265
- var groups = [];
266
- for (var g = 0; g < IPV6_HEX_GROUPS; g++) {
267
- groups.push(buf.readUInt16BE(off + g * 2).toString(HEX_RADIX));
268
- }
269
- addrs.push(groups.join(":"));
270
- }
271
- off += rdlen;
272
- }
273
- return addrs;
274
- }
275
-
276
- // DoH GET URL length cap. RFC 8484 §4.1 says clients MAY use POST when
277
- // the GET URL would exceed implementation limits. We pick 2048 bytes
278
- // (a conservative ceiling well below RFC 7230's recommended 8 KB) so
279
- // long DNS names (e.g. ESNI / SVCB record queries with operator-side
280
- // hostname concatenation) fall back cleanly. Operator can force POST
281
- // always with `useDnsOverHttps({ url, method: "POST" })`.
282
- var DOH_GET_URL_MAX_BYTES = 2048;
283
-
284
- async function _dohLookup(host, family) {
285
- var qtype = family === 6 ? 28 : 1;
286
- var enc = _encodeDnsQuery(host, qtype);
287
- var b64 = enc.buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
288
- var getUrl = STATE.doh.url + (STATE.doh.url.indexOf("?") === -1 ? "?" : "&") + "dns=" + b64;
289
- var forcedMethod = STATE.doh.method;
290
- var usePost = forcedMethod === "POST" || (!forcedMethod && getUrl.length > DOH_GET_URL_MAX_BYTES);
291
- // STATE.doh.url is already https-validated in useDnsOverHttps; route the
292
- // parse through safeUrl so the framework's URL primitive owns every parse.
293
- var u = safeUrl.parse(STATE.doh.url, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS });
294
- return new Promise(function (resolve, reject) {
295
- var reqOpts = {
296
- hostname: u.hostname,
297
- port: u.port || 443,
298
- path: u.pathname + u.search,
299
- method: usePost ? "POST" : "GET",
300
- headers: {
301
- "accept": "application/dns-message",
302
- },
303
- minVersion: "TLSv1.3",
304
- ecdhCurve: C.TLS_GROUP_CURVE_STR,
305
- };
306
- if (STATE.doh.ca) reqOpts.ca = STATE.doh.ca;
307
- if (usePost) {
308
- reqOpts.headers["content-type"] = "application/dns-message";
309
- reqOpts.headers["content-length"] = enc.buf.length;
310
- } else {
311
- // getUrl was composed from STATE.doh.url + a base64-url DNS query suffix.
312
- // safeUrl.parse re-validates the composed URL.
313
- var parsedGet = safeUrl.parse(getUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS });
314
- reqOpts.path = parsedGet.pathname + parsedGet.search;
315
- }
316
- var req = https.request(reqOpts, function (res) {
317
- // RFC 8484 caps DoH responses at 64 KiB practical max; raise to
318
- // 256 KiB to leave headroom for upstream resolvers that pad.
319
- var collector = safeBuffer.boundedChunkCollector({
320
- maxBytes: C.BYTES.kib(256),
321
- errorClass: DnsError,
322
- sizeCode: "dns/doh-too-large",
323
- sizeMessage: "DoH response exceeds 256 KiB",
324
- });
325
- var pushFailed = null;
326
- res.on("data", function (c) {
327
- if (pushFailed) return;
328
- try { collector.push(c); }
329
- catch (e) { pushFailed = e; }
330
- });
331
- res.on("end", function () {
332
- try {
333
- if (pushFailed) { reject(pushFailed); return; }
334
- var body = collector.result();
335
- if (res.statusCode !== 200) {
336
- reject(new DnsError("dns/doh-http", "DoH HTTP " + res.statusCode + " for " + host));
337
- return;
338
- }
339
- resolve(_decodeDnsAnswer(body, qtype));
340
- } catch (e) { reject(e); }
341
- });
342
- });
343
- req.on("error", function (e) { reject(new DnsError("dns/doh-failed", "DoH request failed: " + e.message)); });
344
- if (usePost) req.write(enc.buf);
345
- req.end();
346
- });
347
- }
348
-
349
- // DoT connection pool. Per-(host:port) cached TLS socket so successive
350
- // lookups amortize the handshake. Sockets idle past the timeout are
351
- // closed and removed; first lookup after expiry rebuilds. Each socket
352
- // services one in-flight query at a time (DNS-over-TCP allows pipelining
353
- // but the framework chooses serialization for simpler back-pressure).
354
- var DOT_IDLE_TIMEOUT_MS = C.TIME.minutes(2);
355
- var _dotPool = new Map(); // "host:port" → { sock, lastUsedAt, idle, queue }
356
-
357
- function _dotPoolKey() {
358
- return STATE.dot.host + ":" + STATE.dot.port;
359
- }
360
-
361
- function _dotConnect() {
362
- var connectOpts = {
363
- host: STATE.dot.host,
364
- port: STATE.dot.port,
365
- servername: STATE.dot.servername,
366
- minVersion: "TLSv1.3",
367
- ecdhCurve: C.TLS_GROUP_CURVE_STR,
368
- };
369
- if (STATE.dot.ca) connectOpts.ca = STATE.dot.ca;
370
- var sock = tls.connect(connectOpts);
371
- // The pool entry is ref()'d while a query is in flight and unref()'d
372
- // when idle — _dotLookup toggles this around its query. Calling
373
- // unref() unconditionally here let node exit during a normal lookup
374
- // when no other I/O kept the event loop alive.
375
- return sock;
376
- }
377
-
378
- function _dotEvict(key) {
379
- var entry = _dotPool.get(key);
380
- if (!entry) return;
381
- try { entry.sock.destroy(); } catch (_e) { /* best-effort socket teardown */ }
382
- _dotPool.delete(key);
383
- }
384
-
385
- async function _dotLookup(host, family) {
386
- var qtype = family === 6 ? 28 : 1;
387
- var enc = _encodeDnsQuery(host, qtype);
388
- var key = _dotPoolKey();
389
- var entry = _dotPool.get(key);
390
- if (entry && (Date.now() - entry.lastUsedAt > DOT_IDLE_TIMEOUT_MS)) {
391
- _dotEvict(key);
392
- entry = null;
393
- }
394
- if (!entry) {
395
- var sock = _dotConnect();
396
- entry = {
397
- sock: sock,
398
- lastUsedAt: Date.now(),
399
- idle: true,
400
- ready: new Promise(function (res, rej) {
401
- sock.once("secureConnect", function () { res(); });
402
- sock.once("error", function (e) {
403
- rej(new DnsError("dns/dot-handshake",
404
- "DoT TLS handshake to " + STATE.dot.host + ":" + STATE.dot.port +
405
- " failed: " + ((e && e.message) || String(e))));
406
- });
407
- }),
408
- };
409
- // Pre-attach a no-op observer so a handshake failure isn't reported
410
- // as an unhandledRejection in the window between this assignment
411
- // and the first lookup awaiting entry.ready. The real reject path
412
- // routes through _dotLookup's then(_, onErr) handler below.
413
- entry.ready.catch(function () { /* observed; routed via per-lookup handler */ });
414
- _dotPool.set(key, entry);
415
- sock.on("error", function () { _dotEvict(key); });
416
- sock.on("close", function () { if (_dotPool.get(key) === entry) _dotPool.delete(key); });
417
- }
418
- // Serialize: each socket handles one query at a time. If another
419
- // query is in flight, queue behind it.
420
- var waitTicket = entry._tail || Promise.resolve();
421
- entry._tail = waitTicket.then(function () {
422
- return new Promise(function (resolve, reject) {
423
- entry.idle = false;
424
- // Hold the event loop open while a query is in flight.
425
- try { entry.sock.ref(); } catch (_e) { /* best-effort event-loop hold */ }
426
- Promise.resolve(entry.ready).then(function () {
427
- var lenBuf = Buffer.alloc(2);
428
- lenBuf.writeUInt16BE(enc.buf.length, 0);
429
- var got = [];
430
- var expectLen = -1;
431
- var done = false;
432
- function settle(err, val) {
433
- if (done) return;
434
- done = true;
435
- entry.sock.removeListener("data", onData);
436
- entry.sock.removeListener("error", onErr);
437
- entry.idle = true;
438
- entry.lastUsedAt = Date.now();
439
- // Release the event-loop hold so an idle pool socket doesn't
440
- // keep node alive between queries.
441
- try { entry.sock.unref(); } catch (_e) { /* best-effort event-loop release */ }
442
- if (err) reject(err); else resolve(val);
443
- }
444
- function onData(chunk) {
445
- got.push(chunk);
446
- var all = Buffer.concat(got);
447
- if (expectLen === -1 && all.length >= 2) expectLen = all.readUInt16BE(0);
448
- if (expectLen >= 0 && all.length >= expectLen + 2) {
449
- try {
450
- settle(null, _decodeDnsAnswer(all.slice(2, 2 + expectLen), qtype));
451
- } catch (e) { settle(e); }
452
- }
453
- }
454
- function onErr(e) {
455
- _dotEvict(key);
456
- settle(new DnsError("dns/dot-failed", "DoT failed: " + e.message));
457
- }
458
- entry.sock.on("data", onData);
459
- entry.sock.on("error", onErr);
460
- entry.sock.write(lenBuf);
461
- entry.sock.write(enc.buf);
462
- }, function (handshakeErr) {
463
- // entry.ready rejected (TLS handshake / cert verification failure).
464
- // Route as the lookup's reject so callers see a real DnsError
465
- // instead of an unhandledRejection from the TLSSocket event.
466
- entry.idle = true;
467
- try { entry.sock.unref(); } catch (_e) { /* best-effort event-loop release */ }
468
- reject(handshakeErr);
469
- });
470
- });
471
- });
472
- return entry._tail;
473
- }
474
-
475
- function _resetDotPool() {
476
- var keys = Array.from(_dotPool.keys());
477
- for (var i = 0; i < keys.length; i++) _dotEvict(keys[i]);
478
- }
479
-
480
- function _orderAddrs(addrs) {
481
- if (STATE.resultOrder === "ipv6first") {
482
- addrs.sort(function (a, b) { return (b.family || 0) - (a.family || 0); });
483
- } else if (STATE.resultOrder === "ipv4first") {
484
- addrs.sort(function (a, b) { return (a.family || 0) - (b.family || 0); });
485
- }
486
- return addrs;
487
- }
488
-
489
- async function _dualStack(queryFn, host, family) {
490
- if (family === 4 || family === 6) {
491
- return _withTimeout(queryFn(host, family), STATE.lookupTimeoutMs, host);
492
- }
493
- var first = STATE.resultOrder === "ipv6first" ? 6 : 4;
494
- var second = first === 4 ? 6 : 4;
495
- var firstResult = await _withTimeout(queryFn(host, first), STATE.lookupTimeoutMs, host).catch(function () { return []; });
496
- var secondResult = await _withTimeout(queryFn(host, second), STATE.lookupTimeoutMs, host).catch(function () { return []; });
497
- return (firstResult || []).concat(secondResult || []);
498
- }
499
-
500
- async function lookup(host, opts) {
501
- opts = opts || {};
502
- validateOpts(opts, ["family", "all"], "dns.lookup");
503
- var family = opts.family !== undefined ? opts.family : STATE.family;
504
- if (net.isIP(host)) {
505
- var fam = net.isIP(host);
506
- var literal = { address: host, family: fam };
507
- return opts.all ? [literal] : literal;
508
- }
509
- var cacheKey = family || 0;
510
- var cached = _cacheGet(host, cacheKey);
511
- if (cached.hit) {
512
- if (cached.error) throw cached.error;
513
- return opts.all ? cached.value : cached.value[0];
514
- }
515
- _emitObs("network.dns.lookup.requested", { family: cacheKey });
516
- var startMs = _now();
517
- try {
518
- var addrs;
519
- if (STATE.doh) {
520
- addrs = await _dualStack(_dohLookup, host, family);
521
- } else if (STATE.dot) {
522
- addrs = await _dualStack(_dotLookup, host, family);
523
- } else {
524
- var nodeOpts = { all: true };
525
- if (family === 4 || family === 6) nodeOpts.family = family;
526
- addrs = await _withTimeout(dnsPromises.lookup(host, nodeOpts), STATE.lookupTimeoutMs, host);
527
- if (!Array.isArray(addrs)) addrs = [addrs];
528
- }
529
- var normalized = (addrs || []).map(function (a) {
530
- if (typeof a === "string") return { address: a, family: net.isIP(a) || 4 };
531
- return { address: a.address || a, family: a.family || net.isIP(a.address || a) || 4 };
532
- });
533
- _orderAddrs(normalized);
534
- if (normalized.length === 0) {
535
- throw new DnsError("dns/no-result", "dns lookup of '" + host + "' returned no addresses");
536
- }
537
- _cachePutPositive(host, cacheKey, normalized);
538
- _emitObs("network.dns.lookup.success", { latencyMs: _now() - startMs, count: normalized.length });
539
- return opts.all ? normalized : normalized[0];
540
- } catch (e) {
541
- _cachePutNegative(host, cacheKey, e);
542
- _emitObs("network.dns.lookup.failure", { latencyMs: _now() - startMs, code: e.code || "unknown" });
543
- throw e;
544
- }
545
- }
546
-
547
- async function _resolveProtocol(host, family) {
548
- if (typeof host !== "string" || host.length === 0) {
549
- throw new DnsError("dns/bad-host", "dns.resolve" + family + ": host required");
550
- }
551
- if (net.isIP(host)) {
552
- if (net.isIP(host) !== family) {
553
- throw new DnsError("dns/wrong-family", "dns.resolve" + family + ": IP literal '" + host + "' is not family " + family);
554
- }
555
- return [host];
556
- }
557
- _emitObs("network.dns.resolve.requested", { family: family });
558
- var startMs = _now();
559
- try {
560
- var addrs;
561
- if (STATE.doh) {
562
- addrs = await _withTimeout(_dohLookup(host, family), STATE.lookupTimeoutMs, host);
563
- } else if (STATE.dot) {
564
- addrs = await _withTimeout(_dotLookup(host, family), STATE.lookupTimeoutMs, host);
565
- } else {
566
- var resolver = family === 6 ? dnsPromises.resolve6 : dnsPromises.resolve4;
567
- addrs = await _withTimeout(resolver(host), STATE.lookupTimeoutMs, host);
568
- }
569
- if (!Array.isArray(addrs)) addrs = [addrs];
570
- var normalized = addrs.map(function (a) { return typeof a === "string" ? a : (a.address || a); });
571
- if (normalized.length === 0) {
572
- throw new DnsError("dns/no-result", "dns.resolve" + family + " of '" + host + "' returned no addresses");
573
- }
574
- _emitObs("network.dns.resolve.success", { family: family, latencyMs: _now() - startMs, count: normalized.length });
575
- return normalized;
576
- } catch (e) {
577
- _emitObs("network.dns.resolve.failure", { family: family, latencyMs: _now() - startMs, code: e.code || "unknown" });
578
- if (e instanceof DnsError) throw e;
579
- throw new DnsError("dns/resolve-failed",
580
- "dns.resolve" + family + " of '" + host + "' failed: " + (e.message || String(e)));
581
- }
582
- }
583
-
584
- async function resolve4(host) { return _resolveProtocol(host, 4); }
585
- async function resolve6(host) { return _resolveProtocol(host, 6); }
586
- async function resolveAaaa(host) { return _resolveProtocol(host, 6); }
587
-
588
- function nodeLookup(host, options, callback) {
589
- if (typeof options === "function") { callback = options; options = {}; }
590
- options = options || {};
591
- var fam = options.family !== undefined ? options.family : 0;
592
- lookup(host, { family: fam, all: !!options.all }).then(
593
- function (res) {
594
- if (options.all) callback(null, res);
595
- else callback(null, res.address, res.family);
596
- },
597
- function (err) { callback(err); }
598
- );
599
- }
600
-
601
- function _emitObs(name, fields) {
602
- try { observability().emit(name, fields || {}); } catch (_e) { /* obs best-effort */ }
603
- }
604
-
605
- function _stateForTest() { return STATE; }
606
- function _resetForTest() {
607
- STATE.servers = null; STATE.resultOrder = null; STATE.family = 0;
608
- STATE.lookupTimeoutMs = 0; STATE.cacheTtlMs = 0; STATE.cacheNegativeTtlMs = 0;
609
- STATE.doh = null; STATE.dot = null;
610
- _clearCache();
611
- _resetDotPool();
612
- }
613
-
614
- module.exports = {
615
- setServers: setServers,
616
- getServers: getServers,
617
- setResultOrder: setResultOrder,
618
- setFamily: setFamily,
619
- setLookupTimeoutMs: setLookupTimeoutMs,
620
- setCacheTtlMs: setCacheTtlMs,
621
- useDnsOverHttps: useDnsOverHttps,
622
- useDnsOverTls: useDnsOverTls,
623
- lookup: lookup,
624
- resolve4: resolve4,
625
- resolve6: resolve6,
626
- resolveAaaa: resolveAaaa,
627
- nodeLookup: nodeLookup,
628
- clearCache: _clearCache,
629
- DnsError: DnsError,
630
- _stateForTest: _stateForTest,
631
- _resetForTest: _resetForTest,
632
- };
1
+ "use strict";
2
+
3
+ var dns = require("node:dns");
4
+ var net = require("node:net");
5
+ var nodeCrypto = require("node:crypto");
6
+ var https = require("node:https");
7
+ var tls = require("node:tls");
8
+ var dnsPromises = dns.promises;
9
+
10
+ var C = require("./constants");
11
+ var lazyRequire = require("./lazy-require");
12
+ var safeBuffer = require("./safe-buffer");
13
+ var safeUrl = require("./safe-url");
14
+ var validateOpts = require("./validate-opts");
15
+ var { defineClass } = require("./framework-error");
16
+
17
+ var DnsError = defineClass("DnsError", { alwaysPermanent: false });
18
+
19
+ // Protocol-fixed byte counts and radixes — passthrough through C.BYTES
20
+ // keeps every numeric literal routed through one helper.
21
+ var DNS_QTYPE_AAAA = 28; // RFC 3596 — IPv6 record type
22
+ var IPV6_ADDR_BYTES = C.BYTES.bytes(16); // IPv6 address octet length
23
+ var IPV6_HEX_GROUPS = C.BYTES.bytes(8); // IPv6 16-bit hex groups
24
+ var HEX_RADIX = C.BYTES.bytes(16); // parseInt / toString radix-16
25
+
26
+ var observability = lazyRequire(function () { return require("./observability"); });
27
+
28
+ var STATE = {
29
+ servers: null,
30
+ resultOrder: null,
31
+ family: 0,
32
+ lookupTimeoutMs: 0,
33
+ cacheTtlMs: 0,
34
+ cacheNegativeTtlMs: 0,
35
+ doh: null,
36
+ dot: null,
37
+ };
38
+
39
+ var POSITIVE_CACHE = new Map();
40
+ var NEGATIVE_CACHE = new Map();
41
+
42
+ function _now() { return Date.now(); }
43
+
44
+ function _cacheGet(host, family) {
45
+ var key = host + "/" + family;
46
+ var pos = POSITIVE_CACHE.get(key);
47
+ if (pos && pos.expiresAt > _now()) return { hit: true, value: pos.value };
48
+ if (pos) POSITIVE_CACHE.delete(key);
49
+ var neg = NEGATIVE_CACHE.get(key);
50
+ if (neg && neg.expiresAt > _now()) return { hit: true, error: neg.error };
51
+ if (neg) NEGATIVE_CACHE.delete(key);
52
+ return { hit: false };
53
+ }
54
+
55
+ function _cachePutPositive(host, family, value) {
56
+ if (STATE.cacheTtlMs <= 0) return;
57
+ POSITIVE_CACHE.set(host + "/" + family, {
58
+ value: value,
59
+ expiresAt: _now() + STATE.cacheTtlMs,
60
+ });
61
+ }
62
+
63
+ function _cachePutNegative(host, family, error) {
64
+ if (STATE.cacheTtlMs <= 0) return;
65
+ var ttl = STATE.cacheNegativeTtlMs > 0 ? STATE.cacheNegativeTtlMs : Math.min(STATE.cacheTtlMs, C.TIME.seconds(30));
66
+ NEGATIVE_CACHE.set(host + "/" + family, {
67
+ error: error,
68
+ expiresAt: _now() + ttl,
69
+ });
70
+ }
71
+
72
+ function _clearCache() {
73
+ POSITIVE_CACHE.clear();
74
+ NEGATIVE_CACHE.clear();
75
+ }
76
+
77
+ function setServers(serverList) {
78
+ if (!Array.isArray(serverList) || serverList.length === 0) {
79
+ throw new DnsError("dns/bad-servers", "dns.setServers: expected non-empty array of resolver IPs");
80
+ }
81
+ for (var i = 0; i < serverList.length; i++) {
82
+ var s = serverList[i];
83
+ if (typeof s !== "string" || s.length === 0) {
84
+ throw new DnsError("dns/bad-server", "dns.setServers[" + i + "]: expected non-empty string, got " + typeof s);
85
+ }
86
+ }
87
+ STATE.servers = serverList.slice();
88
+ try { dns.setServers(serverList); } catch (e) {
89
+ throw new DnsError("dns/setservers-failed", "dns.setServers failed: " + e.message);
90
+ }
91
+ _clearCache();
92
+ _emitObs("network.dns.servers.set", { count: serverList.length });
93
+ }
94
+
95
+ function getServers() {
96
+ if (STATE.servers) return STATE.servers.slice();
97
+ try { return dns.getServers(); } catch (_e) { return []; }
98
+ }
99
+
100
+ function setResultOrder(order) {
101
+ if (order !== "ipv4first" && order !== "verbatim" && order !== "ipv6first") {
102
+ throw new DnsError("dns/bad-result-order",
103
+ "dns.setResultOrder: expected 'ipv4first' | 'verbatim' | 'ipv6first', got " + JSON.stringify(order));
104
+ }
105
+ STATE.resultOrder = order;
106
+ if (order === "ipv6first") {
107
+ try { dns.setDefaultResultOrder("verbatim"); } catch (_e) { /* node may not support setter on this version — best-effort */ }
108
+ } else {
109
+ try { dns.setDefaultResultOrder(order); } catch (_e) { /* node may not support setter on this version — best-effort */ }
110
+ }
111
+ _clearCache();
112
+ _emitObs("network.dns.result_order.set", { order: order });
113
+ }
114
+
115
+ function setFamily(fam) {
116
+ if (fam !== 0 && fam !== 4 && fam !== 6) {
117
+ throw new DnsError("dns/bad-family", "dns.setFamily: expected 0 | 4 | 6, got " + JSON.stringify(fam));
118
+ }
119
+ STATE.family = fam;
120
+ _clearCache();
121
+ }
122
+
123
+ function setLookupTimeoutMs(ms) {
124
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 0) {
125
+ throw new DnsError("dns/bad-timeout",
126
+ "dns.setLookupTimeoutMs: expected non-negative finite number, got " + JSON.stringify(ms));
127
+ }
128
+ STATE.lookupTimeoutMs = ms;
129
+ }
130
+
131
+ function setCacheTtlMs(ms, negativeMs) {
132
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 0) {
133
+ throw new DnsError("dns/bad-cache-ttl",
134
+ "dns.setCacheTtlMs: expected non-negative finite number, got " + JSON.stringify(ms));
135
+ }
136
+ STATE.cacheTtlMs = ms;
137
+ if (negativeMs !== undefined) {
138
+ if (typeof negativeMs !== "number" || !isFinite(negativeMs) || negativeMs < 0) {
139
+ throw new DnsError("dns/bad-cache-ttl",
140
+ "dns.setCacheTtlMs negativeMs: expected non-negative finite number, got " + JSON.stringify(negativeMs));
141
+ }
142
+ STATE.cacheNegativeTtlMs = negativeMs;
143
+ }
144
+ if (ms === 0) _clearCache();
145
+ }
146
+
147
+ function useDnsOverHttps(opts) {
148
+ opts = opts || {};
149
+ validateOpts(opts, ["provider", "url", "method", "ca"], "dns.useDnsOverHttps");
150
+ var url = opts.url;
151
+ if (!url && opts.provider) {
152
+ var p = String(opts.provider).toLowerCase();
153
+ if (p === "cloudflare") url = "https://cloudflare-dns.com/dns-query";
154
+ else if (p === "google") url = "https://dns.google/dns-query";
155
+ else if (p === "quad9") url = "https://dns.quad9.net/dns-query";
156
+ else throw new DnsError("dns/bad-doh-provider", "dns.useDnsOverHttps: unknown provider '" + opts.provider + "'");
157
+ }
158
+ if (typeof url !== "string" || url.indexOf("https://") !== 0) {
159
+ throw new DnsError("dns/bad-doh-url",
160
+ "dns.useDnsOverHttps: url must be an https:// string, got " + JSON.stringify(url));
161
+ }
162
+ var method = opts.method;
163
+ if (method !== undefined && method !== "GET" && method !== "POST") {
164
+ throw new DnsError("dns/bad-doh-method",
165
+ "dns.useDnsOverHttps: method must be 'GET' | 'POST' | undefined (auto), got " +
166
+ JSON.stringify(method));
167
+ }
168
+ if (opts.ca !== undefined && opts.ca !== null &&
169
+ !Buffer.isBuffer(opts.ca) && typeof opts.ca !== "string" && !Array.isArray(opts.ca)) {
170
+ throw new DnsError("dns/bad-doh-ca",
171
+ "dns.useDnsOverHttps: ca must be a PEM string, Buffer, or array of either");
172
+ }
173
+ STATE.doh = { url: url, method: method, ca: opts.ca || null };
174
+ _clearCache();
175
+ _emitObs("network.dns.doh.set", { url: url, method: method || "auto" });
176
+ }
177
+
178
+ function useDnsOverTls(opts) {
179
+ opts = opts || {};
180
+ validateOpts(opts, ["host", "port", "servername", "ca"], "dns.useDnsOverTls");
181
+ validateOpts.requireNonEmptyString(opts.host, "dns.useDnsOverTls: host", DnsError, "dns/bad-dot-host");
182
+ if (opts.ca !== undefined && opts.ca !== null &&
183
+ !Buffer.isBuffer(opts.ca) && typeof opts.ca !== "string" && !Array.isArray(opts.ca)) {
184
+ throw new DnsError("dns/bad-dot-ca",
185
+ "dns.useDnsOverTls: ca must be a PEM string, Buffer, or array of either");
186
+ }
187
+ STATE.dot = {
188
+ host: opts.host,
189
+ port: opts.port || 853,
190
+ servername: opts.servername || opts.host,
191
+ ca: opts.ca || null,
192
+ };
193
+ _resetDotPool();
194
+ _clearCache();
195
+ _emitObs("network.dns.dot.set", { host: STATE.dot.host, port: STATE.dot.port });
196
+ }
197
+
198
+ function _withTimeout(promise, ms, host) {
199
+ if (ms <= 0) return promise;
200
+ return new Promise(function (resolve, reject) {
201
+ var timer = setTimeout(function () {
202
+ reject(new DnsError("dns/lookup-timeout", "dns lookup of '" + host + "' exceeded " + ms + "ms"));
203
+ }, ms);
204
+ timer.unref && timer.unref();
205
+ promise.then(
206
+ function (v) { clearTimeout(timer); resolve(v); },
207
+ function (e) { clearTimeout(timer); reject(e); }
208
+ );
209
+ });
210
+ }
211
+
212
+ function _encodeDnsQuery(host, qtype) {
213
+ var parts = host.split(".").filter(Boolean);
214
+ var nameLen = 1;
215
+ for (var i = 0; i < parts.length; i++) nameLen += 1 + Buffer.byteLength(parts[i], "ascii");
216
+ var buf = Buffer.alloc(12 + nameLen + 4);
217
+ // Cryptographic RNG for the 16-bit DNS query ID — frustrates poisoning
218
+ // attempts that guess the transaction ID. Math.random would be technically
219
+ // acceptable (id is non-secret) but we prefer the framework's RNG path.
220
+ var id = nodeCrypto.randomInt(0, 0x10000);
221
+ buf.writeUInt16BE(id, 0);
222
+ buf.writeUInt16BE(0x0100, 2);
223
+ buf.writeUInt16BE(1, 4);
224
+ var off = 12;
225
+ for (var p = 0; p < parts.length; p++) {
226
+ var s = parts[p];
227
+ buf.writeUInt8(Buffer.byteLength(s, "ascii"), off++);
228
+ off += buf.write(s, off, "ascii");
229
+ }
230
+ buf.writeUInt8(0, off++);
231
+ buf.writeUInt16BE(qtype, off); off += 2;
232
+ buf.writeUInt16BE(1, off);
233
+ return { buf: buf, id: id };
234
+ }
235
+
236
+ function _decodeDnsAnswer(buf, qtype) {
237
+ if (!Buffer.isBuffer(buf) || buf.length < 12) throw new DnsError("dns/bad-reply", "dns reply truncated");
238
+ var rcode = buf.readUInt8(3) & 0x0f;
239
+ if (rcode !== 0) throw new DnsError("dns/no-result", "dns reply rcode " + rcode);
240
+ var qdcount = buf.readUInt16BE(4);
241
+ var ancount = buf.readUInt16BE(6);
242
+ var off = 12;
243
+ for (var q = 0; q < qdcount; q++) {
244
+ while (off < buf.length && buf[off] !== 0) {
245
+ if ((buf[off] & 0xc0) === 0xc0) { off += 2; break; }
246
+ off += buf[off] + 1;
247
+ }
248
+ if (buf[off] === 0) off++;
249
+ off += 4;
250
+ }
251
+ var addrs = [];
252
+ for (var a = 0; a < ancount; a++) {
253
+ while (off < buf.length && buf[off] !== 0) {
254
+ if ((buf[off] & 0xc0) === 0xc0) { off += 2; break; }
255
+ off += buf[off] + 1;
256
+ }
257
+ if (buf[off] === 0) off++;
258
+ var rtype = buf.readUInt16BE(off); off += 2;
259
+ off += 2;
260
+ off += 4;
261
+ var rdlen = buf.readUInt16BE(off); off += 2;
262
+ if (rtype === qtype && qtype === 1 && rdlen === 4) {
263
+ addrs.push(buf[off] + "." + buf[off + 1] + "." + buf[off + 2] + "." + buf[off + 3]);
264
+ } else if (rtype === qtype && qtype === DNS_QTYPE_AAAA && rdlen === IPV6_ADDR_BYTES) {
265
+ var groups = [];
266
+ for (var g = 0; g < IPV6_HEX_GROUPS; g++) {
267
+ groups.push(buf.readUInt16BE(off + g * 2).toString(HEX_RADIX));
268
+ }
269
+ addrs.push(groups.join(":"));
270
+ }
271
+ off += rdlen;
272
+ }
273
+ return addrs;
274
+ }
275
+
276
+ // DoH GET URL length cap. RFC 8484 §4.1 says clients MAY use POST when
277
+ // the GET URL would exceed implementation limits. We pick 2048 bytes
278
+ // (a conservative ceiling well below RFC 7230's recommended 8 KB) so
279
+ // long DNS names (e.g. ESNI / SVCB record queries with operator-side
280
+ // hostname concatenation) fall back cleanly. Operator can force POST
281
+ // always with `useDnsOverHttps({ url, method: "POST" })`.
282
+ var DOH_GET_URL_MAX_BYTES = 2048;
283
+
284
+ async function _dohLookup(host, family) {
285
+ var qtype = family === 6 ? 28 : 1;
286
+ var enc = _encodeDnsQuery(host, qtype);
287
+ var b64 = enc.buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
288
+ var getUrl = STATE.doh.url + (STATE.doh.url.indexOf("?") === -1 ? "?" : "&") + "dns=" + b64;
289
+ var forcedMethod = STATE.doh.method;
290
+ var usePost = forcedMethod === "POST" || (!forcedMethod && getUrl.length > DOH_GET_URL_MAX_BYTES);
291
+ // STATE.doh.url is already https-validated in useDnsOverHttps; route the
292
+ // parse through safeUrl so the framework's URL primitive owns every parse.
293
+ var u = safeUrl.parse(STATE.doh.url, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS });
294
+ return new Promise(function (resolve, reject) {
295
+ var reqOpts = {
296
+ hostname: u.hostname,
297
+ port: u.port || 443,
298
+ path: u.pathname + u.search,
299
+ method: usePost ? "POST" : "GET",
300
+ headers: {
301
+ "accept": "application/dns-message",
302
+ },
303
+ minVersion: "TLSv1.3",
304
+ ecdhCurve: C.TLS_GROUP_CURVE_STR,
305
+ };
306
+ if (STATE.doh.ca) reqOpts.ca = STATE.doh.ca;
307
+ if (usePost) {
308
+ reqOpts.headers["content-type"] = "application/dns-message";
309
+ reqOpts.headers["content-length"] = enc.buf.length;
310
+ } else {
311
+ // getUrl was composed from STATE.doh.url + a base64-url DNS query suffix.
312
+ // safeUrl.parse re-validates the composed URL.
313
+ var parsedGet = safeUrl.parse(getUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS });
314
+ reqOpts.path = parsedGet.pathname + parsedGet.search;
315
+ }
316
+ var req = https.request(reqOpts, function (res) {
317
+ // RFC 8484 caps DoH responses at 64 KiB practical max; raise to
318
+ // 256 KiB to leave headroom for upstream resolvers that pad.
319
+ var collector = safeBuffer.boundedChunkCollector({
320
+ maxBytes: C.BYTES.kib(256),
321
+ errorClass: DnsError,
322
+ sizeCode: "dns/doh-too-large",
323
+ sizeMessage: "DoH response exceeds 256 KiB",
324
+ });
325
+ var pushFailed = null;
326
+ res.on("data", function (c) {
327
+ if (pushFailed) return;
328
+ try { collector.push(c); }
329
+ catch (e) { pushFailed = e; }
330
+ });
331
+ res.on("end", function () {
332
+ try {
333
+ if (pushFailed) { reject(pushFailed); return; }
334
+ var body = collector.result();
335
+ if (res.statusCode !== 200) {
336
+ reject(new DnsError("dns/doh-http", "DoH HTTP " + res.statusCode + " for " + host));
337
+ return;
338
+ }
339
+ resolve(_decodeDnsAnswer(body, qtype));
340
+ } catch (e) { reject(e); }
341
+ });
342
+ });
343
+ req.on("error", function (e) { reject(new DnsError("dns/doh-failed", "DoH request failed: " + e.message)); });
344
+ if (usePost) req.write(enc.buf);
345
+ req.end();
346
+ });
347
+ }
348
+
349
+ // DoT connection pool. Per-(host:port) cached TLS socket so successive
350
+ // lookups amortize the handshake. Sockets idle past the timeout are
351
+ // closed and removed; first lookup after expiry rebuilds. Each socket
352
+ // services one in-flight query at a time (DNS-over-TCP allows pipelining
353
+ // but the framework chooses serialization for simpler back-pressure).
354
+ var DOT_IDLE_TIMEOUT_MS = C.TIME.minutes(2);
355
+ var _dotPool = new Map(); // "host:port" → { sock, lastUsedAt, idle, queue }
356
+
357
+ function _dotPoolKey() {
358
+ return STATE.dot.host + ":" + STATE.dot.port;
359
+ }
360
+
361
+ function _dotConnect() {
362
+ var connectOpts = {
363
+ host: STATE.dot.host,
364
+ port: STATE.dot.port,
365
+ servername: STATE.dot.servername,
366
+ minVersion: "TLSv1.3",
367
+ ecdhCurve: C.TLS_GROUP_CURVE_STR,
368
+ };
369
+ if (STATE.dot.ca) connectOpts.ca = STATE.dot.ca;
370
+ var sock = tls.connect(connectOpts);
371
+ // The pool entry is ref()'d while a query is in flight and unref()'d
372
+ // when idle — _dotLookup toggles this around its query. Calling
373
+ // unref() unconditionally here let node exit during a normal lookup
374
+ // when no other I/O kept the event loop alive.
375
+ return sock;
376
+ }
377
+
378
+ function _dotEvict(key) {
379
+ var entry = _dotPool.get(key);
380
+ if (!entry) return;
381
+ try { entry.sock.destroy(); } catch (_e) { /* best-effort socket teardown */ }
382
+ _dotPool.delete(key);
383
+ }
384
+
385
+ async function _dotLookup(host, family) {
386
+ var qtype = family === 6 ? 28 : 1;
387
+ var enc = _encodeDnsQuery(host, qtype);
388
+ var key = _dotPoolKey();
389
+ var entry = _dotPool.get(key);
390
+ if (entry && (Date.now() - entry.lastUsedAt > DOT_IDLE_TIMEOUT_MS)) {
391
+ _dotEvict(key);
392
+ entry = null;
393
+ }
394
+ if (!entry) {
395
+ var sock = _dotConnect();
396
+ entry = {
397
+ sock: sock,
398
+ lastUsedAt: Date.now(),
399
+ idle: true,
400
+ ready: new Promise(function (res, rej) {
401
+ sock.once("secureConnect", function () { res(); });
402
+ sock.once("error", function (e) {
403
+ rej(new DnsError("dns/dot-handshake",
404
+ "DoT TLS handshake to " + STATE.dot.host + ":" + STATE.dot.port +
405
+ " failed: " + ((e && e.message) || String(e))));
406
+ });
407
+ }),
408
+ };
409
+ // Pre-attach a no-op observer so a handshake failure isn't reported
410
+ // as an unhandledRejection in the window between this assignment
411
+ // and the first lookup awaiting entry.ready. The real reject path
412
+ // routes through _dotLookup's then(_, onErr) handler below.
413
+ entry.ready.catch(function () { /* observed; routed via per-lookup handler */ });
414
+ _dotPool.set(key, entry);
415
+ sock.on("error", function () { _dotEvict(key); });
416
+ sock.on("close", function () { if (_dotPool.get(key) === entry) _dotPool.delete(key); });
417
+ }
418
+ // Serialize: each socket handles one query at a time. If another
419
+ // query is in flight, queue behind it.
420
+ var waitTicket = entry._tail || Promise.resolve();
421
+ entry._tail = waitTicket.then(function () {
422
+ return new Promise(function (resolve, reject) {
423
+ entry.idle = false;
424
+ // Hold the event loop open while a query is in flight.
425
+ try { entry.sock.ref(); } catch (_e) { /* best-effort event-loop hold */ }
426
+ Promise.resolve(entry.ready).then(function () {
427
+ var lenBuf = Buffer.alloc(2);
428
+ lenBuf.writeUInt16BE(enc.buf.length, 0);
429
+ var got = [];
430
+ var expectLen = -1;
431
+ var done = false;
432
+ function settle(err, val) {
433
+ if (done) return;
434
+ done = true;
435
+ entry.sock.removeListener("data", onData);
436
+ entry.sock.removeListener("error", onErr);
437
+ entry.idle = true;
438
+ entry.lastUsedAt = Date.now();
439
+ // Release the event-loop hold so an idle pool socket doesn't
440
+ // keep node alive between queries.
441
+ try { entry.sock.unref(); } catch (_e) { /* best-effort event-loop release */ }
442
+ if (err) reject(err); else resolve(val);
443
+ }
444
+ function onData(chunk) {
445
+ got.push(chunk);
446
+ var all = Buffer.concat(got);
447
+ if (expectLen === -1 && all.length >= 2) expectLen = all.readUInt16BE(0);
448
+ if (expectLen >= 0 && all.length >= expectLen + 2) {
449
+ try {
450
+ settle(null, _decodeDnsAnswer(all.slice(2, 2 + expectLen), qtype));
451
+ } catch (e) { settle(e); }
452
+ }
453
+ }
454
+ function onErr(e) {
455
+ _dotEvict(key);
456
+ settle(new DnsError("dns/dot-failed", "DoT failed: " + e.message));
457
+ }
458
+ entry.sock.on("data", onData);
459
+ entry.sock.on("error", onErr);
460
+ entry.sock.write(lenBuf);
461
+ entry.sock.write(enc.buf);
462
+ }, function (handshakeErr) {
463
+ // entry.ready rejected (TLS handshake / cert verification failure).
464
+ // Route as the lookup's reject so callers see a real DnsError
465
+ // instead of an unhandledRejection from the TLSSocket event.
466
+ entry.idle = true;
467
+ try { entry.sock.unref(); } catch (_e) { /* best-effort event-loop release */ }
468
+ reject(handshakeErr);
469
+ });
470
+ });
471
+ });
472
+ return entry._tail;
473
+ }
474
+
475
+ function _resetDotPool() {
476
+ var keys = Array.from(_dotPool.keys());
477
+ for (var i = 0; i < keys.length; i++) _dotEvict(keys[i]);
478
+ }
479
+
480
+ function _orderAddrs(addrs) {
481
+ if (STATE.resultOrder === "ipv6first") {
482
+ addrs.sort(function (a, b) { return (b.family || 0) - (a.family || 0); });
483
+ } else if (STATE.resultOrder === "ipv4first") {
484
+ addrs.sort(function (a, b) { return (a.family || 0) - (b.family || 0); });
485
+ }
486
+ return addrs;
487
+ }
488
+
489
+ async function _dualStack(queryFn, host, family) {
490
+ if (family === 4 || family === 6) {
491
+ return _withTimeout(queryFn(host, family), STATE.lookupTimeoutMs, host);
492
+ }
493
+ var first = STATE.resultOrder === "ipv6first" ? 6 : 4;
494
+ var second = first === 4 ? 6 : 4;
495
+ var firstResult = await _withTimeout(queryFn(host, first), STATE.lookupTimeoutMs, host).catch(function () { return []; });
496
+ var secondResult = await _withTimeout(queryFn(host, second), STATE.lookupTimeoutMs, host).catch(function () { return []; });
497
+ return (firstResult || []).concat(secondResult || []);
498
+ }
499
+
500
+ async function lookup(host, opts) {
501
+ opts = opts || {};
502
+ validateOpts(opts, ["family", "all"], "dns.lookup");
503
+ var family = opts.family !== undefined ? opts.family : STATE.family;
504
+ if (net.isIP(host)) {
505
+ var fam = net.isIP(host);
506
+ var literal = { address: host, family: fam };
507
+ return opts.all ? [literal] : literal;
508
+ }
509
+ var cacheKey = family || 0;
510
+ var cached = _cacheGet(host, cacheKey);
511
+ if (cached.hit) {
512
+ if (cached.error) throw cached.error;
513
+ return opts.all ? cached.value : cached.value[0];
514
+ }
515
+ _emitObs("network.dns.lookup.requested", { family: cacheKey });
516
+ var startMs = _now();
517
+ try {
518
+ var addrs;
519
+ if (STATE.doh) {
520
+ addrs = await _dualStack(_dohLookup, host, family);
521
+ } else if (STATE.dot) {
522
+ addrs = await _dualStack(_dotLookup, host, family);
523
+ } else {
524
+ var nodeOpts = { all: true };
525
+ if (family === 4 || family === 6) nodeOpts.family = family;
526
+ addrs = await _withTimeout(dnsPromises.lookup(host, nodeOpts), STATE.lookupTimeoutMs, host);
527
+ if (!Array.isArray(addrs)) addrs = [addrs];
528
+ }
529
+ var normalized = (addrs || []).map(function (a) {
530
+ if (typeof a === "string") return { address: a, family: net.isIP(a) || 4 };
531
+ return { address: a.address || a, family: a.family || net.isIP(a.address || a) || 4 };
532
+ });
533
+ _orderAddrs(normalized);
534
+ if (normalized.length === 0) {
535
+ throw new DnsError("dns/no-result", "dns lookup of '" + host + "' returned no addresses");
536
+ }
537
+ _cachePutPositive(host, cacheKey, normalized);
538
+ _emitObs("network.dns.lookup.success", { latencyMs: _now() - startMs, count: normalized.length });
539
+ return opts.all ? normalized : normalized[0];
540
+ } catch (e) {
541
+ _cachePutNegative(host, cacheKey, e);
542
+ _emitObs("network.dns.lookup.failure", { latencyMs: _now() - startMs, code: e.code || "unknown" });
543
+ throw e;
544
+ }
545
+ }
546
+
547
+ async function _resolveProtocol(host, family) {
548
+ if (typeof host !== "string" || host.length === 0) {
549
+ throw new DnsError("dns/bad-host", "dns.resolve" + family + ": host required");
550
+ }
551
+ if (net.isIP(host)) {
552
+ if (net.isIP(host) !== family) {
553
+ throw new DnsError("dns/wrong-family", "dns.resolve" + family + ": IP literal '" + host + "' is not family " + family);
554
+ }
555
+ return [host];
556
+ }
557
+ _emitObs("network.dns.resolve.requested", { family: family });
558
+ var startMs = _now();
559
+ try {
560
+ var addrs;
561
+ if (STATE.doh) {
562
+ addrs = await _withTimeout(_dohLookup(host, family), STATE.lookupTimeoutMs, host);
563
+ } else if (STATE.dot) {
564
+ addrs = await _withTimeout(_dotLookup(host, family), STATE.lookupTimeoutMs, host);
565
+ } else {
566
+ var resolver = family === 6 ? dnsPromises.resolve6 : dnsPromises.resolve4;
567
+ addrs = await _withTimeout(resolver(host), STATE.lookupTimeoutMs, host);
568
+ }
569
+ if (!Array.isArray(addrs)) addrs = [addrs];
570
+ var normalized = addrs.map(function (a) { return typeof a === "string" ? a : (a.address || a); });
571
+ if (normalized.length === 0) {
572
+ throw new DnsError("dns/no-result", "dns.resolve" + family + " of '" + host + "' returned no addresses");
573
+ }
574
+ _emitObs("network.dns.resolve.success", { family: family, latencyMs: _now() - startMs, count: normalized.length });
575
+ return normalized;
576
+ } catch (e) {
577
+ _emitObs("network.dns.resolve.failure", { family: family, latencyMs: _now() - startMs, code: e.code || "unknown" });
578
+ if (e instanceof DnsError) throw e;
579
+ throw new DnsError("dns/resolve-failed",
580
+ "dns.resolve" + family + " of '" + host + "' failed: " + (e.message || String(e)));
581
+ }
582
+ }
583
+
584
+ async function resolve4(host) { return _resolveProtocol(host, 4); }
585
+ async function resolve6(host) { return _resolveProtocol(host, 6); }
586
+ async function resolveAaaa(host) { return _resolveProtocol(host, 6); }
587
+
588
+ function nodeLookup(host, options, callback) {
589
+ if (typeof options === "function") { callback = options; options = {}; }
590
+ options = options || {};
591
+ var fam = options.family !== undefined ? options.family : 0;
592
+ lookup(host, { family: fam, all: !!options.all }).then(
593
+ function (res) {
594
+ if (options.all) callback(null, res);
595
+ else callback(null, res.address, res.family);
596
+ },
597
+ function (err) { callback(err); }
598
+ );
599
+ }
600
+
601
+ function _emitObs(name, fields) {
602
+ try { observability().emit(name, fields || {}); } catch (_e) { /* obs best-effort */ }
603
+ }
604
+
605
+ function _stateForTest() { return STATE; }
606
+ function _resetForTest() {
607
+ STATE.servers = null; STATE.resultOrder = null; STATE.family = 0;
608
+ STATE.lookupTimeoutMs = 0; STATE.cacheTtlMs = 0; STATE.cacheNegativeTtlMs = 0;
609
+ STATE.doh = null; STATE.dot = null;
610
+ _clearCache();
611
+ _resetDotPool();
612
+ }
613
+
614
+ module.exports = {
615
+ setServers: setServers,
616
+ getServers: getServers,
617
+ setResultOrder: setResultOrder,
618
+ setFamily: setFamily,
619
+ setLookupTimeoutMs: setLookupTimeoutMs,
620
+ setCacheTtlMs: setCacheTtlMs,
621
+ useDnsOverHttps: useDnsOverHttps,
622
+ useDnsOverTls: useDnsOverTls,
623
+ lookup: lookup,
624
+ resolve4: resolve4,
625
+ resolve6: resolve6,
626
+ resolveAaaa: resolveAaaa,
627
+ nodeLookup: nodeLookup,
628
+ clearCache: _clearCache,
629
+ DnsError: DnsError,
630
+ _stateForTest: _stateForTest,
631
+ _resetForTest: _resetForTest,
632
+ };