@opengeni/network 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,695 @@
1
+ // The explicit entrypoint avoids Bun's native `undici` compatibility shim,
2
+ // which exposes an Agent-shaped object without Dispatcher methods.
3
+ import { Agent, fetch as undiciFetchImpl } from "undici/index.js";
4
+ import { lookup as nodeLookup } from "node:dns/promises";
5
+ import { isIP } from "node:net";
6
+
7
+ export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
8
+
9
+ export type DnsAddress = {
10
+ address: string;
11
+ family: 4 | 6;
12
+ };
13
+
14
+ export type DnsLookup = (hostname: string) => Promise<readonly DnsAddress[]>;
15
+
16
+ export type OutboundNetworkSettings = {
17
+ environment: string;
18
+ integrationsAllowPrivateNetworkTargets: boolean;
19
+ };
20
+
21
+ export type PinnedDestination = {
22
+ url: URL;
23
+ hostname: string;
24
+ addresses: readonly DnsAddress[];
25
+ };
26
+
27
+ export type DispatcherLifecycle = {
28
+ /** The raw dispatcher handed to fetch; omitted for test-only lifecycle fakes. */
29
+ dispatcher?: unknown;
30
+ close: () => Promise<void> | void;
31
+ destroy: (error?: unknown) => Promise<void> | void;
32
+ };
33
+
34
+ export type PinnedFetchOptions = {
35
+ fetchImpl?: FetchLike;
36
+ dnsLookup?: DnsLookup;
37
+ agentFactory?: (addresses: readonly DnsAddress[]) => DispatcherLifecycle;
38
+ label?: string;
39
+ requireHttpsOutsideLocalTest?: boolean;
40
+ };
41
+
42
+ export const OAUTH_MAX_RESPONSE_BYTES = 1024 * 1024;
43
+
44
+ export type HttpUrlValidationOptions = {
45
+ allowLoopbackHttp?: boolean;
46
+ label?: string;
47
+ };
48
+
49
+ /** Validate a protocol endpoint before it is persisted, returned, or opened. */
50
+ export function validateHttpUrl(rawUrl: string, options: HttpUrlValidationOptions = {}): string {
51
+ const label = options.label ?? "HTTP endpoint";
52
+ let url: URL;
53
+ try {
54
+ url = new URL(rawUrl);
55
+ } catch {
56
+ throw new DestinationPolicyError("invalid_url", `${label} URL is invalid`);
57
+ }
58
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
59
+ throw new DestinationPolicyError(
60
+ "unsupported_protocol",
61
+ `${label} only supports http and https URLs`,
62
+ );
63
+ }
64
+ if (url.username || url.password) {
65
+ throw new DestinationPolicyError("invalid_url", `${label} URL may not contain credentials`);
66
+ }
67
+ if (url.hash) {
68
+ throw new DestinationPolicyError("invalid_url", `${label} URL may not contain a fragment`);
69
+ }
70
+ if (
71
+ url.protocol === "http:" &&
72
+ !(options.allowLoopbackHttp && isLoopbackHostname(url.hostname))
73
+ ) {
74
+ throw new DestinationPolicyError("https_required", `${label} must use https`);
75
+ }
76
+ return url.toString();
77
+ }
78
+
79
+ /**
80
+ * Raised when a response cannot be safely consumed within its caller's byte
81
+ * budget. The error intentionally contains no response bytes or provider
82
+ * message: these readers are used on credential-bearing paths.
83
+ */
84
+ export class ResponseBodyLimitError extends Error {
85
+ constructor(
86
+ readonly label: string,
87
+ readonly actualBytes: number,
88
+ readonly maxBytes: number,
89
+ readonly reason: "declared_length" | "stream_overflow" | "invalid_content_length",
90
+ ) {
91
+ super(`${label} exceeded its ${maxBytes}-byte response limit`);
92
+ this.name = "ResponseBodyLimitError";
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Read a response through its stream with a hard byte ceiling.
98
+ *
99
+ * A declared Content-Length above the ceiling is rejected before reading. A
100
+ * body exactly at the ceiling is accepted; the first byte beyond it cancels
101
+ * the stream and rejects. Cancellation is important because pinnedFetch owns a
102
+ * per-response dispatcher which must be closed on every exit path.
103
+ */
104
+ export async function readResponseBodyBounded(
105
+ response: Response,
106
+ maxBytes: number,
107
+ label: string,
108
+ ): Promise<Uint8Array> {
109
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
110
+ throw new RangeError("response body limit must be a non-negative safe integer");
111
+ }
112
+ const declared = response.headers.get("content-length");
113
+ if (declared !== null) {
114
+ const normalized = declared.trim();
115
+ if (!/^\d+$/.test(normalized)) {
116
+ await cancelResponse(response);
117
+ throw new ResponseBodyLimitError(label, 0, maxBytes, "invalid_content_length");
118
+ }
119
+ const declaredBytes = Number(normalized);
120
+ if (!Number.isSafeInteger(declaredBytes) || declaredBytes > maxBytes) {
121
+ await cancelResponse(response);
122
+ throw new ResponseBodyLimitError(label, declaredBytes, maxBytes, "declared_length");
123
+ }
124
+ }
125
+ if (!response.body) {
126
+ return new Uint8Array();
127
+ }
128
+
129
+ const reader = response.body.getReader();
130
+ const chunks: Uint8Array[] = [];
131
+ let receivedBytes = 0;
132
+ try {
133
+ for (;;) {
134
+ const result = await reader.read();
135
+ if (result.done) {
136
+ break;
137
+ }
138
+ receivedBytes += result.value.byteLength;
139
+ if (receivedBytes > maxBytes) {
140
+ await reader.cancel().catch(() => undefined);
141
+ throw new ResponseBodyLimitError(label, receivedBytes, maxBytes, "stream_overflow");
142
+ }
143
+ chunks.push(result.value);
144
+ }
145
+ } catch (error) {
146
+ await reader.cancel().catch(() => undefined);
147
+ throw error;
148
+ } finally {
149
+ reader.releaseLock();
150
+ }
151
+
152
+ const body = new Uint8Array(receivedBytes);
153
+ let offset = 0;
154
+ for (const chunk of chunks) {
155
+ body.set(chunk, offset);
156
+ offset += chunk.byteLength;
157
+ }
158
+ return body;
159
+ }
160
+
161
+ export async function readResponseTextBounded(
162
+ response: Response,
163
+ maxBytes: number,
164
+ label: string,
165
+ ): Promise<string> {
166
+ return new TextDecoder().decode(await readResponseBodyBounded(response, maxBytes, label));
167
+ }
168
+
169
+ export async function readResponseJsonBounded<T = unknown>(
170
+ response: Response,
171
+ maxBytes: number,
172
+ label: string,
173
+ ): Promise<T> {
174
+ return JSON.parse(await readResponseTextBounded(response, maxBytes, label)) as T;
175
+ }
176
+
177
+ export type ResolvePinnedDestinationOptions = {
178
+ dnsLookup?: DnsLookup;
179
+ label?: string;
180
+ requireHttpsOutsideLocalTest?: boolean;
181
+ };
182
+
183
+ export type DestinationPolicyReason =
184
+ | "invalid_url"
185
+ | "unsupported_protocol"
186
+ | "https_required"
187
+ | "dns_failed"
188
+ | "dns_empty"
189
+ | "invalid_dns_answer"
190
+ | "private_or_special_use";
191
+
192
+ export class DestinationPolicyError extends Error {
193
+ constructor(
194
+ readonly reason: DestinationPolicyReason,
195
+ message: string,
196
+ ) {
197
+ super(message);
198
+ this.name = "DestinationPolicyError";
199
+ }
200
+ }
201
+
202
+ const defaultDnsLookup: DnsLookup = async (hostname) => {
203
+ const answers = await nodeLookup(hostname, { all: true });
204
+ return answers.map((entry) => normalizeDnsAnswer(entry));
205
+ };
206
+
207
+ const defaultFetch: FetchLike = (input, init) =>
208
+ (undiciFetchImpl as unknown as FetchLike)(input, init);
209
+
210
+ /** Undici fetch used by the pinned transport; Bun callers should prefer this over native fetch. */
211
+ export const undiciFetch: FetchLike = defaultFetch;
212
+
213
+ /**
214
+ * Resolve and policy-check one destination. The returned address set is the
215
+ * complete DNS answer that the caller is allowed to use; the transport never
216
+ * performs a second resolver call.
217
+ */
218
+ export async function resolvePinnedDestination(
219
+ rawUrl: string | URL,
220
+ settings: OutboundNetworkSettings,
221
+ options: ResolvePinnedDestinationOptions = {},
222
+ ): Promise<PinnedDestination> {
223
+ const label = options.label ?? "Outbound request";
224
+ let url: URL;
225
+ try {
226
+ url = new URL(rawUrl);
227
+ } catch {
228
+ throw new DestinationPolicyError("invalid_url", `${label} URL is invalid`);
229
+ }
230
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
231
+ throw new DestinationPolicyError(
232
+ "unsupported_protocol",
233
+ `${label} only supports http and https URLs`,
234
+ );
235
+ }
236
+ const localTestEscape = isLocalTestEnvironment(settings.environment);
237
+ if (options.requireHttpsOutsideLocalTest && !localTestEscape && url.protocol !== "https:") {
238
+ throw new DestinationPolicyError(
239
+ "https_required",
240
+ `${label} must use https outside local/test`,
241
+ );
242
+ }
243
+
244
+ const hostname = normalizeHostname(url.hostname);
245
+ if (!hostname) {
246
+ throw new DestinationPolicyError("invalid_url", `${label} URL has no hostname`);
247
+ }
248
+
249
+ const literalFamily = isIP(hostname);
250
+ let addresses: readonly DnsAddress[];
251
+ try {
252
+ addresses = literalFamily
253
+ ? [{ address: hostname, family: literalFamily === 6 ? 6 : 4 }]
254
+ : await (options.dnsLookup ?? defaultDnsLookup)(hostname);
255
+ } catch (error) {
256
+ if (error instanceof DestinationPolicyError && error.reason === "invalid_dns_answer") {
257
+ throw error;
258
+ }
259
+ throw new DestinationPolicyError("dns_failed", `${label} hostname could not be resolved`);
260
+ }
261
+
262
+ const normalizedAddresses = dedupeAddresses(addresses);
263
+ if (normalizedAddresses.length === 0) {
264
+ throw new DestinationPolicyError("dns_empty", `${label} hostname has no addresses`);
265
+ }
266
+ if (normalizedAddresses.some((entry) => isInvalidAddress(entry.address))) {
267
+ throw new DestinationPolicyError(
268
+ "invalid_dns_answer",
269
+ `${label} hostname returned an invalid address`,
270
+ );
271
+ }
272
+
273
+ const privateEscape = localTestEscape || settings.integrationsAllowPrivateNetworkTargets === true;
274
+ if (
275
+ !privateEscape &&
276
+ (isLocalHostname(hostname) ||
277
+ normalizedAddresses.some((entry) => isNonPublicAddress(entry.address)))
278
+ ) {
279
+ throw new DestinationPolicyError(
280
+ "private_or_special_use",
281
+ `${label} may not target a private or special-use network address`,
282
+ );
283
+ }
284
+ return { url, hostname, addresses: normalizedAddresses };
285
+ }
286
+
287
+ /**
288
+ * Fetch through a dispatcher whose lookup is pinned to the result of exactly
289
+ * one policy resolution. The response body owns the agent until completion,
290
+ * cancellation, or stream failure.
291
+ */
292
+ export async function pinnedFetch(
293
+ input: string | URL | Request,
294
+ init: RequestInit | undefined,
295
+ settings: OutboundNetworkSettings,
296
+ options: PinnedFetchOptions = {},
297
+ ): Promise<Response> {
298
+ const rawUrl = input instanceof Request ? input.url : input;
299
+ const destination = await resolvePinnedDestination(rawUrl, settings, options);
300
+ const dispatcher =
301
+ options.agentFactory?.(destination.addresses) ?? createPinnedAgent(destination.addresses);
302
+ const fetchImpl = options.fetchImpl ?? defaultFetch;
303
+ const fetchInit = {
304
+ ...init,
305
+ redirect: "manual" as const,
306
+ dispatcher: dispatcher.dispatcher ?? dispatcher,
307
+ } as RequestInit & { dispatcher: DispatcherLifecycle };
308
+ let response: Response;
309
+ try {
310
+ response = await fetchImpl(input, fetchInit);
311
+ } catch (error) {
312
+ await destroyDispatcher(dispatcher, error);
313
+ throw error;
314
+ }
315
+ if (!response.body) {
316
+ await closeDispatcher(dispatcher);
317
+ return response;
318
+ }
319
+ return responseWithDispatcherLifecycle(response, dispatcher);
320
+ }
321
+
322
+ export function isLocalTestEnvironment(environment: string): boolean {
323
+ return environment === "local" || environment === "test";
324
+ }
325
+
326
+ /** Return true for malformed, non-IPv4, and non-IPv6 address strings. */
327
+ export function isInvalidAddress(address: string): boolean {
328
+ return isIP(stripAddressBrackets(address.trim())) === 0;
329
+ }
330
+
331
+ /**
332
+ * Classify private, reserved, documentation, benchmark, multicast, and other
333
+ * special-use answers. IPv4-mapped IPv6 addresses are classified through their
334
+ * embedded IPv4 value.
335
+ */
336
+ export function isNonPublicAddress(address: string): boolean {
337
+ const normalized = stripAddressBrackets(address.trim().toLowerCase());
338
+ const family = isIP(normalized);
339
+ if (family === 0) {
340
+ return true;
341
+ }
342
+ if (family === 4) {
343
+ return isNonPublicIpv4(normalized);
344
+ }
345
+ const mappedText = ipv4FromMappedText(normalized);
346
+ if (mappedText !== null) {
347
+ return isNonPublicIpv4(mappedText);
348
+ }
349
+ const value = parseIpv6(normalized);
350
+ if (value === null) {
351
+ return true;
352
+ }
353
+ const mapped = ipv4FromMappedIpv6(value);
354
+ if (mapped !== null) {
355
+ return isNonPublicIpv4(mapped);
356
+ }
357
+ // Fail closed on unallocated/non-global IPv6 space. Current globally routed
358
+ // unicast addresses live in 2000::/3; local, transition, multicast, and
359
+ // future-use ranges must not become credential-bearing egress merely because
360
+ // they were absent from a denylist.
361
+ if (!hasIpv6Prefix(value, IPV6_GLOBAL_UNICAST_PREFIX, 3)) {
362
+ return true;
363
+ }
364
+ return IPV6_SPECIAL_PREFIXES.some(([prefix, bits]) => hasIpv6Prefix(value, prefix, bits));
365
+ }
366
+
367
+ // Backwards-compatible name used by the database token-broker API.
368
+ export const isPrivateAddress = isNonPublicAddress;
369
+
370
+ function createPinnedAgent(addresses: readonly DnsAddress[]): DispatcherLifecycle {
371
+ const agent = new Agent({
372
+ connect: {
373
+ lookup: ((
374
+ _hostname: string,
375
+ options: { all?: boolean; family?: number },
376
+ callback: (
377
+ error: Error | null,
378
+ address?: string | Array<{ address: string; family: number }>,
379
+ family?: number,
380
+ ) => void,
381
+ ) => {
382
+ const candidates =
383
+ options.family === 4 || options.family === 6
384
+ ? addresses.filter((entry) => entry.family === options.family)
385
+ : addresses;
386
+ if (candidates.length === 0) {
387
+ callback(new Error("pinned DNS answer has no address for requested family"));
388
+ return;
389
+ }
390
+ if (options.all) {
391
+ callback(
392
+ null,
393
+ candidates.map((entry) => ({ address: entry.address, family: entry.family })),
394
+ );
395
+ return;
396
+ }
397
+ const first = candidates[0]!;
398
+ callback(null, first.address, first.family);
399
+ }) as never,
400
+ },
401
+ });
402
+ return {
403
+ dispatcher: agent,
404
+ close: async () => {
405
+ await agent.close();
406
+ },
407
+ destroy: async (error) => {
408
+ await agent.destroy(error instanceof Error ? error : null);
409
+ },
410
+ };
411
+ }
412
+
413
+ function responseWithDispatcherLifecycle(
414
+ response: Response,
415
+ dispatcher: DispatcherLifecycle,
416
+ ): Response {
417
+ const reader = response.body!.getReader();
418
+ let disposed: Promise<void> | null = null;
419
+ let cancelled = false;
420
+ const finish = (destroy: boolean, error?: unknown): Promise<void> => {
421
+ if (!disposed) {
422
+ disposed = destroy ? destroyDispatcher(dispatcher, error) : closeDispatcher(dispatcher);
423
+ }
424
+ return disposed;
425
+ };
426
+ const body = new ReadableStream<Uint8Array>({
427
+ async pull(controller) {
428
+ try {
429
+ const chunk = await reader.read();
430
+ if (chunk.done) {
431
+ await finish(cancelled);
432
+ controller.close();
433
+ return;
434
+ }
435
+ controller.enqueue(chunk.value);
436
+ } catch (error) {
437
+ await finish(true, error);
438
+ controller.error(error);
439
+ }
440
+ },
441
+ async cancel(reason) {
442
+ cancelled = true;
443
+ try {
444
+ await reader.cancel(reason);
445
+ } finally {
446
+ await finish(true, reason);
447
+ }
448
+ },
449
+ });
450
+ const wrapped = new Response(body, {
451
+ status: response.status,
452
+ statusText: response.statusText,
453
+ headers: response.headers,
454
+ });
455
+ Object.defineProperties(wrapped, {
456
+ redirected: { value: response.redirected },
457
+ type: { value: response.type },
458
+ url: { value: response.url },
459
+ });
460
+ return wrapped;
461
+ }
462
+
463
+ async function closeDispatcher(dispatcher: DispatcherLifecycle): Promise<void> {
464
+ try {
465
+ await dispatcher.close();
466
+ } catch {
467
+ await destroyDispatcher(dispatcher);
468
+ }
469
+ }
470
+
471
+ async function destroyDispatcher(dispatcher: DispatcherLifecycle, error?: unknown): Promise<void> {
472
+ try {
473
+ await dispatcher.destroy(error);
474
+ } catch {
475
+ // Cleanup is best effort after the dispatcher has already failed.
476
+ }
477
+ }
478
+
479
+ async function cancelResponse(response: Response): Promise<void> {
480
+ await response.body?.cancel().catch(() => undefined);
481
+ }
482
+
483
+ function normalizeHostname(hostname: string): string {
484
+ return stripAddressBrackets(hostname.trim().toLowerCase()).replace(/\.$/, "");
485
+ }
486
+
487
+ function stripAddressBrackets(address: string): string {
488
+ return address.startsWith("[") && address.endsWith("]") ? address.slice(1, -1) : address;
489
+ }
490
+
491
+ function isLocalHostname(hostname: string): boolean {
492
+ return hostname === "localhost" || hostname.endsWith(".localhost");
493
+ }
494
+
495
+ function isLoopbackHostname(hostname: string): boolean {
496
+ const normalized = normalizeHostname(hostname);
497
+ return (
498
+ normalized === "localhost" ||
499
+ normalized.endsWith(".localhost") ||
500
+ normalized === "::1" ||
501
+ isLoopbackIpv4(normalized)
502
+ );
503
+ }
504
+
505
+ function isLoopbackIpv4(hostname: string): boolean {
506
+ if (isIP(hostname) !== 4) return false;
507
+ return hostname.split(".")[0] === "127";
508
+ }
509
+
510
+ function dedupeAddresses(addresses: readonly DnsAddress[]): DnsAddress[] {
511
+ const out: DnsAddress[] = [];
512
+ const seen = new Set<string>();
513
+ if (!Array.isArray(addresses)) {
514
+ throw invalidDnsAnswer();
515
+ }
516
+ for (const entry of addresses) {
517
+ const normalized = normalizeDnsAnswer(entry);
518
+ const key = `${normalized.family}:${normalized.address}`;
519
+ if (!seen.has(key)) {
520
+ seen.add(key);
521
+ out.push(normalized);
522
+ }
523
+ }
524
+ return out;
525
+ }
526
+
527
+ /**
528
+ * Validate resolver metadata before it can influence either policy checks or
529
+ * the pinned dispatcher. Never infer a family from the address while retaining
530
+ * a conflicting resolver claim: an invalid answer is an invalid answer.
531
+ */
532
+ function normalizeDnsAnswer(entry: unknown): DnsAddress {
533
+ if (!entry || typeof entry !== "object") {
534
+ throw invalidDnsAnswer();
535
+ }
536
+ const candidate = entry as { address?: unknown; family?: unknown };
537
+ if (typeof candidate.address !== "string") {
538
+ throw invalidDnsAnswer();
539
+ }
540
+ const family = candidate.family;
541
+ if (family !== 4 && family !== 6) {
542
+ throw invalidDnsAnswer();
543
+ }
544
+ const address = stripAddressBrackets(candidate.address.trim().toLowerCase());
545
+ const actualFamily = isIP(address);
546
+ if (actualFamily !== family) {
547
+ throw invalidDnsAnswer();
548
+ }
549
+ return { address, family };
550
+ }
551
+
552
+ function invalidDnsAnswer(): DestinationPolicyError {
553
+ return new DestinationPolicyError(
554
+ "invalid_dns_answer",
555
+ "hostname returned an invalid DNS answer",
556
+ );
557
+ }
558
+
559
+ function isNonPublicIpv4(address: string): boolean {
560
+ const parts = address.split(".").map(Number);
561
+ if (
562
+ parts.length !== 4 ||
563
+ parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)
564
+ ) {
565
+ return true;
566
+ }
567
+ const value = (parts[0]! << 24) | (parts[1]! << 16) | (parts[2]! << 8) | parts[3]!;
568
+ const unsigned = value >>> 0;
569
+ return (
570
+ inIpv4Range(unsigned, 0x00000000, 0x00ffffff) ||
571
+ inIpv4Range(unsigned, 0x0a000000, 0x0affffff) ||
572
+ inIpv4Range(unsigned, 0x64400000, 0x647fffff) ||
573
+ inIpv4Range(unsigned, 0x7f000000, 0x7fffffff) ||
574
+ inIpv4Range(unsigned, 0xa9fe0000, 0xa9feffff) ||
575
+ inIpv4Range(unsigned, 0xac100000, 0xac1fffff) ||
576
+ inIpv4Range(unsigned, 0xc0000000, 0xc00000ff) ||
577
+ inIpv4Range(unsigned, 0xc0000200, 0xc00002ff) ||
578
+ inIpv4Range(unsigned, 0xc01fc400, 0xc01fc4ff) ||
579
+ inIpv4Range(unsigned, 0xc034c100, 0xc034c1ff) ||
580
+ inIpv4Range(unsigned, 0xc0586300, 0xc05863ff) ||
581
+ inIpv4Range(unsigned, 0xc0a80000, 0xc0a8ffff) ||
582
+ inIpv4Range(unsigned, 0xc0af3000, 0xc0af30ff) ||
583
+ inIpv4Range(unsigned, 0xc6120000, 0xc613ffff) ||
584
+ inIpv4Range(unsigned, 0xc6336400, 0xc63364ff) ||
585
+ inIpv4Range(unsigned, 0xcb007100, 0xcb0071ff) ||
586
+ inIpv4Range(unsigned, 0xe0000000, 0xffffffff)
587
+ );
588
+ }
589
+
590
+ function inIpv4Range(value: number, start: number, end: number): boolean {
591
+ return value >= start && value <= end;
592
+ }
593
+
594
+ const IPV6_GLOBAL_UNICAST_PREFIX = ipv6Constant("2000::");
595
+
596
+ const IPV6_SPECIAL_PREFIXES: readonly [bigint, number][] = [
597
+ [ipv6Constant("::"), 96],
598
+ [ipv6Constant("64:ff9b::"), 96],
599
+ [ipv6Constant("64:ff9b:1::"), 48],
600
+ [ipv6Constant("100::"), 64],
601
+ // IETF protocol assignments contain globally reachable carve-outs, but they
602
+ // are control-plane anycast/protocol addresses rather than integration
603
+ // endpoints. Credential-bearing MCP/OAuth egress fails closed on the full
604
+ // special-purpose block.
605
+ [ipv6Constant("2001::"), 23],
606
+ [ipv6Constant("2001:db8::"), 32],
607
+ [ipv6Constant("2002::"), 16],
608
+ [ipv6Constant("2620:4f:8000::"), 48],
609
+ [ipv6Constant("3ffe::"), 16],
610
+ [ipv6Constant("3fff::"), 20],
611
+ [ipv6Constant("5f00::"), 16],
612
+ [ipv6Constant("fc00::"), 7],
613
+ [ipv6Constant("fe80::"), 10],
614
+ [ipv6Constant("fec0::"), 10],
615
+ [ipv6Constant("ff00::"), 8],
616
+ ];
617
+
618
+ function hasIpv6Prefix(value: bigint, prefix: bigint, bits: number): boolean {
619
+ const shift = 128n - BigInt(bits);
620
+ return value >> shift === prefix >> shift;
621
+ }
622
+
623
+ function ipv4FromMappedIpv6(value: bigint): string | null {
624
+ if (value >> 32n !== 0xffffn) {
625
+ return null;
626
+ }
627
+ const embedded = Number(value & 0xffffffffn);
628
+ return `${embedded >>> 24}.${(embedded >>> 16) & 0xff}.${(embedded >>> 8) & 0xff}.${embedded & 0xff}`;
629
+ }
630
+
631
+ function ipv4FromMappedText(address: string): string | null {
632
+ if (!address.startsWith("::ffff:")) {
633
+ return null;
634
+ }
635
+ const embedded = address.slice("::ffff:".length);
636
+ if (isIP(embedded) === 4) {
637
+ return embedded;
638
+ }
639
+ const parts = embedded.split(":");
640
+ if (parts.length !== 2 || parts.some((part) => !/^[0-9a-f]{1,4}$/.test(part))) {
641
+ return null;
642
+ }
643
+ const high = Number.parseInt(parts[0]!, 16);
644
+ const low = Number.parseInt(parts[1]!, 16);
645
+ return `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`;
646
+ }
647
+
648
+ function parseIpv6(address: string): bigint | null {
649
+ const percent = address.indexOf("%");
650
+ if (percent >= 0) {
651
+ return null;
652
+ }
653
+ let value = address;
654
+ if (value.includes(".")) {
655
+ const lastColon = value.lastIndexOf(":");
656
+ const dotted = value.slice(lastColon + 1);
657
+ const parts = dotted.split(".").map(Number);
658
+ if (
659
+ parts.length !== 4 ||
660
+ parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)
661
+ ) {
662
+ return null;
663
+ }
664
+ const hex =
665
+ ((parts[0]! << 8) | parts[1]!).toString(16).padStart(4, "0") +
666
+ ((parts[2]! << 8) | parts[3]!).toString(16).padStart(4, "0");
667
+ value = `${value.slice(0, lastColon + 1)}${hex}`;
668
+ }
669
+ const halves = value.split("::");
670
+ if (halves.length > 2) {
671
+ return null;
672
+ }
673
+ const left = halves[0] ? halves[0].split(":") : [];
674
+ const right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
675
+ if (left.concat(right).some((part) => !/^[0-9a-f]{1,4}$/i.test(part))) {
676
+ return null;
677
+ }
678
+ const missing = halves.length === 2 ? 8 - left.length - right.length : 0;
679
+ if (missing < 0 || (halves.length === 1 && missing !== 0)) {
680
+ return null;
681
+ }
682
+ const groups = [...left, ...Array.from({ length: missing }, () => "0"), ...right];
683
+ if (groups.length !== 8) {
684
+ return null;
685
+ }
686
+ return groups.reduce((acc, group) => (acc << 16n) | BigInt(`0x${group}`), 0n);
687
+ }
688
+
689
+ function ipv6Constant(address: string): bigint {
690
+ const value = parseIpv6(address);
691
+ if (value === null) {
692
+ throw new Error(`invalid IPv6 constant: ${address}`);
693
+ }
694
+ return value;
695
+ }