@venturekit/integrations 0.0.50 → 0.0.52

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.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @venturekit/integrations/net — outbound-request security.
3
+ *
4
+ * Use {@link secureFetch} for every URL your server fetches on behalf of
5
+ * someone else (customer webhook endpoints, user-supplied media URLs, link
6
+ * previews). Vendor APIs at fixed, trusted hosts may keep using `fetch`.
7
+ */
8
+ export { classifyAddress, isPublicAddress } from './address.js';
9
+ export type { AddressCategory } from './address.js';
10
+ export { DEFAULT_OUTBOUND_LIMITS, assertDestinationAllowed, matchesHostPattern, resolveOutboundPolicy, systemResolver, validateOutboundUrl, } from './policy.js';
11
+ export type { AddressResolver, HostMatcher, OutboundDestination, OutboundPolicy, OutboundPolicyOverrides, OutboundProtocol, ResolvedAddress, } from './policy.js';
12
+ export { secureFetch } from './secure-fetch.js';
13
+ export type { SecureFetchBody, SecureFetchInit } from './secure-fetch.js';
14
+ export { OutboundRequestBlockedError, OutboundResponseTooLargeError, isOutboundPolicyError, } from './errors.js';
15
+ export type { OutboundBlockReason } from './errors.js';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/net/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAChE,YAAY,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,kBAAkB,EAClB,qBAAqB,EACrB,cAAc,EACd,mBAAmB,GACpB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,eAAe,EACf,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,uBAAuB,EACvB,gBAAgB,EAChB,eAAe,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @venturekit/integrations/net — outbound-request security.
3
+ *
4
+ * Use {@link secureFetch} for every URL your server fetches on behalf of
5
+ * someone else (customer webhook endpoints, user-supplied media URLs, link
6
+ * previews). Vendor APIs at fixed, trusted hosts may keep using `fetch`.
7
+ */
8
+ export { classifyAddress, isPublicAddress } from './address.js';
9
+ export { DEFAULT_OUTBOUND_LIMITS, assertDestinationAllowed, matchesHostPattern, resolveOutboundPolicy, systemResolver, validateOutboundUrl, } from './policy.js';
10
+ export { secureFetch } from './secure-fetch.js';
11
+ export { OutboundRequestBlockedError, OutboundResponseTooLargeError, isOutboundPolicyError, } from './errors.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/net/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEhE,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,kBAAkB,EAClB,qBAAqB,EACrB,cAAc,EACd,mBAAmB,GACpB,MAAM,aAAa,CAAC;AAUrB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Outbound-request policy: which URLs this process may fetch on behalf of
3
+ * someone else.
4
+ *
5
+ * The policy is a plain value — protocols, an address rule, an optional host
6
+ * allow-list and resource limits — resolved once from secure defaults plus
7
+ * caller overrides ({@link resolveOutboundPolicy}). The transport
8
+ * (`secure-fetch.ts`) enforces it at every hop: on the URL before any I/O
9
+ * ({@link validateOutboundUrl}) and on every address DNS answers, at connect
10
+ * time ({@link assertDestinationAllowed}), so a hostname that resolves to the
11
+ * VPC — or re-resolves there between a check and the connection — is refused.
12
+ *
13
+ * Defaults: `https:` only, public addresses only. Under `vk dev`
14
+ * (`VENTURE_LOCAL=true`) plain `http:` and non-public addresses are allowed,
15
+ * because the services a developer integrates against (MinIO, a webhook
16
+ * receiver on localhost) live there.
17
+ */
18
+ import { type EnvironmentVariables } from '@venturekit/core';
19
+ import { type AddressCategory } from './address.js';
20
+ /** One address a hostname resolved to. */
21
+ export interface ResolvedAddress {
22
+ address: string;
23
+ family: 4 | 6;
24
+ }
25
+ /** Resolves a hostname to EVERY address it maps to. Injectable for tests. */
26
+ export type AddressResolver = (hostname: string) => Promise<ResolvedAddress[]>;
27
+ /** A concrete connection target, as the address rule sees it. */
28
+ export interface OutboundDestination {
29
+ hostname: string;
30
+ address: string;
31
+ category: AddressCategory;
32
+ }
33
+ export type OutboundProtocol = 'http:' | 'https:';
34
+ /** Host patterns: exact `host[:port]` or a dot-prefixed apex (`.example.com`), or a predicate. */
35
+ export type HostMatcher = ReadonlyArray<string> | ((hostname: string) => boolean);
36
+ export interface OutboundPolicy {
37
+ /** URL schemes that may be fetched. */
38
+ protocols: ReadonlyArray<OutboundProtocol>;
39
+ /**
40
+ * Whether non-public addresses (loopback, private, link-local, …) may be
41
+ * reached — `true`, `false`, or a per-destination decision for deployments
42
+ * that legitimately reach one internal service.
43
+ */
44
+ allowNonPublic: boolean | ((destination: OutboundDestination) => boolean);
45
+ /** When set, only these hosts may be fetched (checked before DNS). */
46
+ allowedHosts?: HostMatcher;
47
+ /** Redirect hops followed before giving up. Every hop is re-validated. */
48
+ maxRedirects: number;
49
+ /** Largest response body accepted, in bytes. */
50
+ maxResponseBytes: number;
51
+ /** Wall-clock budget for the whole exchange, redirects included. */
52
+ timeoutMs: number;
53
+ /** DNS resolution used at connect time. */
54
+ resolve: AddressResolver;
55
+ }
56
+ export type OutboundPolicyOverrides = Partial<OutboundPolicy>;
57
+ /** Resource limits applied when the caller does not set its own. */
58
+ export declare const DEFAULT_OUTBOUND_LIMITS: Readonly<{
59
+ maxRedirects: 5;
60
+ maxResponseBytes: number;
61
+ timeoutMs: 15000;
62
+ }>;
63
+ /** System resolver returning every A / AAAA answer, in resolver order. */
64
+ export declare const systemResolver: AddressResolver;
65
+ /**
66
+ * Secure defaults, overridden field by field. Overrides set to `undefined`
67
+ * are ignored, so callers can forward optional options verbatim.
68
+ */
69
+ export declare function resolveOutboundPolicy(overrides?: OutboundPolicyOverrides, env?: EnvironmentVariables): OutboundPolicy;
70
+ /** True when `hostname` (lower-cased, optional `:port`) matches one of `patterns`. */
71
+ export declare function matchesHostPattern(hostname: string, patterns: HostMatcher): boolean;
72
+ /**
73
+ * Refuse a connection to `address` (what `hostname` resolved to) unless the
74
+ * policy allows its category. Message names the category, never the address,
75
+ * so it is safe to surface.
76
+ */
77
+ export declare function assertDestinationAllowed(hostname: string, address: string, policy: OutboundPolicy): void;
78
+ /**
79
+ * Static validation of a URL, before any I/O: scheme, embedded credentials,
80
+ * host allow-list, IP literals and loopback names. DNS answers are checked
81
+ * separately at connect time — a name that validates here can still be
82
+ * refused when it resolves to the VPC.
83
+ */
84
+ export declare function validateOutboundUrl(input: string | URL, policy: OutboundPolicy): URL;
85
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../src/net/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,OAAO,EAAsB,KAAK,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAmB,KAAK,eAAe,EAAE,MAAM,cAAc,CAAC;AAGrE,0CAA0C;AAC1C,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM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sF;AACtF,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,OAAO,CAYnF;AAiBD;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAQxG;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,MAAM,EAAE,cAAc,GAAG,GAAG,CA2BpF"}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Outbound-request policy: which URLs this process may fetch on behalf of
3
+ * someone else.
4
+ *
5
+ * The policy is a plain value — protocols, an address rule, an optional host
6
+ * allow-list and resource limits — resolved once from secure defaults plus
7
+ * caller overrides ({@link resolveOutboundPolicy}). The transport
8
+ * (`secure-fetch.ts`) enforces it at every hop: on the URL before any I/O
9
+ * ({@link validateOutboundUrl}) and on every address DNS answers, at connect
10
+ * time ({@link assertDestinationAllowed}), so a hostname that resolves to the
11
+ * VPC — or re-resolves there between a check and the connection — is refused.
12
+ *
13
+ * Defaults: `https:` only, public addresses only. Under `vk dev`
14
+ * (`VENTURE_LOCAL=true`) plain `http:` and non-public addresses are allowed,
15
+ * because the services a developer integrates against (MinIO, a webhook
16
+ * receiver on localhost) live there.
17
+ */
18
+ import { lookup } from 'node:dns/promises';
19
+ import { isIP } from 'node:net';
20
+ import { isLocalDevelopment } from '@venturekit/core';
21
+ import { classifyAddress } from './address.js';
22
+ import { OutboundRequestBlockedError } from './errors.js';
23
+ /** Resource limits applied when the caller does not set its own. */
24
+ export const DEFAULT_OUTBOUND_LIMITS = Object.freeze({
25
+ maxRedirects: 5,
26
+ maxResponseBytes: 10 * 1024 * 1024,
27
+ timeoutMs: 15_000,
28
+ });
29
+ /** System resolver returning every A / AAAA answer, in resolver order. */
30
+ export const systemResolver = async (hostname) => {
31
+ const answers = await lookup(hostname, { all: true, verbatim: true });
32
+ return answers.map((a) => ({ address: a.address, family: a.family === 6 ? 6 : 4 }));
33
+ };
34
+ /**
35
+ * Secure defaults, overridden field by field. Overrides set to `undefined`
36
+ * are ignored, so callers can forward optional options verbatim.
37
+ */
38
+ export function resolveOutboundPolicy(overrides = {}, env) {
39
+ const local = isLocalDevelopment(env);
40
+ const defaults = {
41
+ protocols: local ? ['https:', 'http:'] : ['https:'],
42
+ allowNonPublic: local,
43
+ maxRedirects: DEFAULT_OUTBOUND_LIMITS.maxRedirects,
44
+ maxResponseBytes: DEFAULT_OUTBOUND_LIMITS.maxResponseBytes,
45
+ timeoutMs: DEFAULT_OUTBOUND_LIMITS.timeoutMs,
46
+ resolve: systemResolver,
47
+ };
48
+ const defined = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined));
49
+ return { ...defaults, ...defined };
50
+ }
51
+ /** True when `hostname` (lower-cased, optional `:port`) matches one of `patterns`. */
52
+ export function matchesHostPattern(hostname, patterns) {
53
+ const host = hostname.toLowerCase();
54
+ if (typeof patterns === 'function')
55
+ return patterns(host);
56
+ const bare = host.replace(/:\d+$/, '');
57
+ return patterns.some((pattern) => {
58
+ const p = pattern.toLowerCase();
59
+ if (p.startsWith('.')) {
60
+ const apex = p.slice(1);
61
+ return bare === apex || bare.endsWith(`.${apex}`);
62
+ }
63
+ return host === p || bare === p;
64
+ });
65
+ }
66
+ function stripBrackets(hostname) {
67
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
68
+ }
69
+ /** Names RFC 6761 reserves for the local machine — refused before any DNS lookup. */
70
+ function isLoopbackName(hostname) {
71
+ const host = hostname.toLowerCase().replace(/\.$/, '');
72
+ return host === 'localhost' || host.endsWith('.localhost');
73
+ }
74
+ function nonPublicAllowed(policy, destination) {
75
+ const rule = policy.allowNonPublic;
76
+ return typeof rule === 'function' ? rule(destination) : rule;
77
+ }
78
+ /**
79
+ * Refuse a connection to `address` (what `hostname` resolved to) unless the
80
+ * policy allows its category. Message names the category, never the address,
81
+ * so it is safe to surface.
82
+ */
83
+ export function assertDestinationAllowed(hostname, address, policy) {
84
+ const category = classifyAddress(address);
85
+ if (category === 'public')
86
+ return;
87
+ if (nonPublicAllowed(policy, { hostname, address, category }))
88
+ return;
89
+ throw new OutboundRequestBlockedError('non_public_address', `Refusing to connect to ${hostname}: it resolves to a ${category} address`);
90
+ }
91
+ /**
92
+ * Static validation of a URL, before any I/O: scheme, embedded credentials,
93
+ * host allow-list, IP literals and loopback names. DNS answers are checked
94
+ * separately at connect time — a name that validates here can still be
95
+ * refused when it resolves to the VPC.
96
+ */
97
+ export function validateOutboundUrl(input, policy) {
98
+ let url;
99
+ try {
100
+ url = input instanceof URL ? new URL(input.toString()) : new URL(input);
101
+ }
102
+ catch {
103
+ throw new OutboundRequestBlockedError('invalid_url', 'Not a valid absolute URL');
104
+ }
105
+ if (!policy.protocols.includes(url.protocol)) {
106
+ throw new OutboundRequestBlockedError('protocol_not_allowed', `URL scheme ${url.protocol} is not allowed (allowed: ${policy.protocols.join(', ')})`);
107
+ }
108
+ if (url.username || url.password) {
109
+ throw new OutboundRequestBlockedError('credentials_in_url', 'URLs carrying credentials are not allowed');
110
+ }
111
+ const hostname = stripBrackets(url.hostname);
112
+ if (!hostname)
113
+ throw new OutboundRequestBlockedError('invalid_url', 'URL has no host');
114
+ if (policy.allowedHosts && !matchesHostPattern(url.host, policy.allowedHosts)) {
115
+ throw new OutboundRequestBlockedError('host_not_allowed', `Host ${url.hostname} is not in the allow-list`);
116
+ }
117
+ if (isIP(hostname)) {
118
+ assertDestinationAllowed(hostname, hostname, policy);
119
+ }
120
+ else if (isLoopbackName(hostname)) {
121
+ assertDestinationAllowed(hostname, '127.0.0.1', policy);
122
+ }
123
+ return url;
124
+ }
125
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.js","sourceRoot":"","sources":["../../src/net/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GA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ose.
3
+ *
4
+ * The global `fetch` cannot be told which addresses it may connect to: it
5
+ * resolves the hostname itself, follows redirects itself, and buffers
6
+ * whatever the server sends. Checking a URL before calling it is not enough —
7
+ * DNS can answer differently at connect time (rebinding), and a redirect can
8
+ * point anywhere. This transport is built on `node:http` / `node:https` so the
9
+ * policy runs INSIDE the connection path:
10
+ *
11
+ * - every hop's URL is validated before I/O (`validateOutboundUrl`);
12
+ * - the socket's DNS lookup is replaced by one that checks EVERY answer
13
+ * against the address rule and refuses the connection otherwise — the
14
+ * address checked is the address connected to;
15
+ * - redirects are followed manually, re-validated, capped, and drop
16
+ * credentials when they leave the origin;
17
+ * - the body is size-capped after decompression and the whole exchange
18
+ * shares one deadline.
19
+ *
20
+ * It returns a standard `Response`, so call sites keep `res.ok`,
21
+ * `res.status`, `await res.arrayBuffer()` and friends.
22
+ */
23
+ import { type OutboundPolicyOverrides } from './policy.js';
24
+ export type SecureFetchBody = string | Uint8Array | ArrayBuffer | URLSearchParams;
25
+ export interface SecureFetchInit {
26
+ method?: string;
27
+ headers?: Record<string, string> | Iterable<readonly [string, string]>;
28
+ body?: SecureFetchBody | null;
29
+ signal?: AbortSignal;
30
+ /**
31
+ * `follow` (default) re-validates and follows up to `maxRedirects` hops;
32
+ * `manual` returns the 3xx response as is; `error` refuses any redirect.
33
+ */
34
+ redirect?: 'follow' | 'manual' | 'error';
35
+ }
36
+ /**
37
+ * Fetch `input` under the outbound policy (secure defaults, overridden by
38
+ * `policy`). Throws {@link OutboundRequestBlockedError} for a refused
39
+ * destination, {@link OutboundResponseTooLargeError} for an oversized body
40
+ * (possibly while the body is being read), and the usual network /
41
+ * `TimeoutError` / `AbortError` errors otherwise.
42
+ */
43
+ export declare function secureFetch(input: string | URL, init?: SecureFetchInit, policy?: OutboundPolicyOverrides): Promise<Response>;
44
+ //# sourceMappingURL=secure-fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secure-fetch.d.ts","sourceRoot":"","sources":["../../src/net/secure-fetch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAQH,OAAO,EAKL,KAAK,uBAAuB,EAC7B,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,UAAU,GAAG,WAAW,GAAG,eAAe,CAAC;AAElF,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACvE,IAAI,CAAC,EAAE,eAAe,GAAG,IAAI,CAAC;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAC;CAC1C;AA2KD;;;;;;GAMG;AACH,wBAAsB,WAAW,CAC/B,KAAK,EAAE,MAAM,GAAG,GAAG,EACnB,IAAI,GAAE,eAAoB,EAC1B,MAAM,GAAE,uBAA4B,GACnC,OAAO,CAAC,QAAQ,CAAC,CAmCnB"}
@@ -0,0 +1,233 @@
1
+ /**
2
+ * `secureFetch` — `fetch` for URLs this process did not choose.
3
+ *
4
+ * The global `fetch` cannot be told which addresses it may connect to: it
5
+ * resolves the hostname itself, follows redirects itself, and buffers
6
+ * whatever the server sends. Checking a URL before calling it is not enough —
7
+ * DNS can answer differently at connect time (rebinding), and a redirect can
8
+ * point anywhere. This transport is built on `node:http` / `node:https` so the
9
+ * policy runs INSIDE the connection path:
10
+ *
11
+ * - every hop's URL is validated before I/O (`validateOutboundUrl`);
12
+ * - the socket's DNS lookup is replaced by one that checks EVERY answer
13
+ * against the address rule and refuses the connection otherwise — the
14
+ * address checked is the address connected to;
15
+ * - redirects are followed manually, re-validated, capped, and drop
16
+ * credentials when they leave the origin;
17
+ * - the body is size-capped after decompression and the whole exchange
18
+ * shares one deadline.
19
+ *
20
+ * It returns a standard `Response`, so call sites keep `res.ok`,
21
+ * `res.status`, `await res.arrayBuffer()` and friends.
22
+ */
23
+ import { request as httpRequest } from 'node:http';
24
+ import { request as httpsRequest } from 'node:https';
25
+ import { isIP } from 'node:net';
26
+ import { Readable, Transform, pipeline } from 'node:stream';
27
+ import { createBrotliDecompress, createGunzip, createInflate } from 'node:zlib';
28
+ import { OutboundRequestBlockedError, OutboundResponseTooLargeError } from './errors.js';
29
+ import { assertDestinationAllowed, resolveOutboundPolicy, validateOutboundUrl, } from './policy.js';
30
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
31
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
32
+ const CROSS_ORIGIN_STRIPPED = ['authorization', 'cookie', 'proxy-authorization'];
33
+ /** Computed by the transport — a caller-supplied value would only desynchronize the framing. */
34
+ const TRANSPORT_HEADERS = new Set(['host', 'connection', 'content-length', 'transfer-encoding', 'keep-alive', 'upgrade']);
35
+ function normalizeHeaders(headers) {
36
+ const out = { 'accept-encoding': 'gzip, deflate, br', 'user-agent': 'VentureKit' };
37
+ if (!headers)
38
+ return out;
39
+ const pairs = Symbol.iterator in Object(headers)
40
+ ? headers
41
+ : Object.entries(headers);
42
+ for (const [name, value] of pairs) {
43
+ const key = name.toLowerCase();
44
+ if (!TRANSPORT_HEADERS.has(key))
45
+ out[key] = String(value);
46
+ }
47
+ return out;
48
+ }
49
+ function encodeBody(body, headers) {
50
+ if (body === undefined || body === null)
51
+ return undefined;
52
+ if (typeof body === 'string')
53
+ return Buffer.from(body, 'utf8');
54
+ if (body instanceof URLSearchParams) {
55
+ headers['content-type'] ??= 'application/x-www-form-urlencoded;charset=UTF-8';
56
+ return Buffer.from(body.toString(), 'utf8');
57
+ }
58
+ if (body instanceof ArrayBuffer)
59
+ return Buffer.from(body);
60
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
61
+ }
62
+ function combineSignals(signals) {
63
+ const present = signals.filter((s) => s !== undefined);
64
+ return AbortSignal.any(present);
65
+ }
66
+ /** The socket's DNS lookup, replaced by one that applies the address rule to every answer. */
67
+ function guardedLookup(policy) {
68
+ return (hostname, options, callback) => {
69
+ policy
70
+ .resolve(hostname)
71
+ .then((answers) => {
72
+ if (answers.length === 0) {
73
+ throw new OutboundRequestBlockedError('unresolvable_host', `${hostname} did not resolve`);
74
+ }
75
+ // Every answer, not just the one used: a mixed answer set is how a
76
+ // rebinding attacker hides an internal address behind a public one.
77
+ for (const answer of answers)
78
+ assertDestinationAllowed(hostname, answer.address, policy);
79
+ const family = options.family === 4 || options.family === 6 ? options.family : undefined;
80
+ const usable = family ? answers.filter((a) => a.family === family) : answers;
81
+ const chosen = usable.length > 0 ? usable : answers;
82
+ if (options.all) {
83
+ callback(null, chosen.map((a) => ({ address: a.address, family: a.family })));
84
+ }
85
+ else {
86
+ callback(null, chosen[0].address, chosen[0].family);
87
+ }
88
+ })
89
+ .catch((err) => callback(err, '', 0));
90
+ };
91
+ }
92
+ function sendOnce(url, method, headers, body, policy, signal) {
93
+ const host = url.hostname.replace(/^\[|\]$/g, '');
94
+ if (isIP(host))
95
+ assertDestinationAllowed(host, host, policy);
96
+ const options = {
97
+ method,
98
+ headers: body ? { ...headers, 'content-length': String(body.byteLength) } : headers,
99
+ signal,
100
+ // A fresh agent: a pooled socket would skip the guarded lookup.
101
+ agent: false,
102
+ lookup: guardedLookup(policy),
103
+ };
104
+ const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
105
+ return new Promise((resolve, reject) => {
106
+ const req = send(url, options, resolve);
107
+ req.on('error', reject);
108
+ req.end(body);
109
+ });
110
+ }
111
+ function byteLimit(limit) {
112
+ let seen = 0;
113
+ return new Transform({
114
+ transform(chunk, _encoding, callback) {
115
+ seen += chunk.length;
116
+ if (seen > limit)
117
+ callback(new OutboundResponseTooLargeError(limit));
118
+ else
119
+ callback(null, chunk);
120
+ },
121
+ });
122
+ }
123
+ function decoderFor(encoding) {
124
+ switch (encoding.trim().toLowerCase()) {
125
+ case 'gzip':
126
+ case 'x-gzip':
127
+ return createGunzip();
128
+ case 'deflate':
129
+ return createInflate();
130
+ case 'br':
131
+ return createBrotliDecompress();
132
+ default:
133
+ return null;
134
+ }
135
+ }
136
+ function toResponse(res, url, method, maxBytes, redirected) {
137
+ const status = res.statusCode ?? 0;
138
+ if (status < 200 || status > 599) {
139
+ res.destroy();
140
+ throw new Error(`Upstream answered with an invalid HTTP status (${status})`);
141
+ }
142
+ const declared = Number(res.headers['content-length']);
143
+ if (Number.isFinite(declared) && declared > maxBytes) {
144
+ res.destroy();
145
+ throw new OutboundResponseTooLargeError(maxBytes);
146
+ }
147
+ const decoder = decoderFor(String(res.headers['content-encoding'] ?? ''));
148
+ const headers = new Headers();
149
+ for (let i = 0; i < res.rawHeaders.length; i += 2) {
150
+ const name = res.rawHeaders[i];
151
+ const lower = name.toLowerCase();
152
+ if (decoder && (lower === 'content-encoding' || lower === 'content-length'))
153
+ continue;
154
+ try {
155
+ headers.append(name, res.rawHeaders[i + 1]);
156
+ }
157
+ catch {
158
+ // A header value the WHATWG Headers class rejects is dropped, not fatal.
159
+ }
160
+ }
161
+ let body = null;
162
+ if (method === 'HEAD' || NULL_BODY_STATUSES.has(status)) {
163
+ res.resume();
164
+ }
165
+ else {
166
+ const limiter = byteLimit(maxBytes);
167
+ const stages = decoder ? [decoder, limiter] : [limiter];
168
+ pipeline([res, ...stages], () => {
169
+ // Errors surface to the reader through the limiter's web stream.
170
+ });
171
+ body = Readable.toWeb(limiter);
172
+ }
173
+ const response = new Response(body, { status, statusText: res.statusMessage ?? '', headers });
174
+ Object.defineProperties(response, {
175
+ url: { value: url.href },
176
+ redirected: { value: redirected },
177
+ });
178
+ return response;
179
+ }
180
+ function nextHop(location, current, policy) {
181
+ let target;
182
+ try {
183
+ target = new URL(location, current).href;
184
+ }
185
+ catch {
186
+ throw new OutboundRequestBlockedError('invalid_url', 'Redirect target is not a valid URL');
187
+ }
188
+ return validateOutboundUrl(target, policy);
189
+ }
190
+ /**
191
+ * Fetch `input` under the outbound policy (secure defaults, overridden by
192
+ * `policy`). Throws {@link OutboundRequestBlockedError} for a refused
193
+ * destination, {@link OutboundResponseTooLargeError} for an oversized body
194
+ * (possibly while the body is being read), and the usual network /
195
+ * `TimeoutError` / `AbortError` errors otherwise.
196
+ */
197
+ export async function secureFetch(input, init = {}, policy = {}) {
198
+ const resolved = resolveOutboundPolicy(policy);
199
+ const redirectMode = init.redirect ?? 'follow';
200
+ const signal = combineSignals([init.signal, AbortSignal.timeout(resolved.timeoutMs)]);
201
+ const headers = normalizeHeaders(init.headers);
202
+ let body = encodeBody(init.body, headers);
203
+ let method = (init.method ?? 'GET').toUpperCase();
204
+ let url = validateOutboundUrl(input, resolved);
205
+ for (let hop = 0;; hop++) {
206
+ const res = await sendOnce(url, method, headers, body, resolved, signal);
207
+ const status = res.statusCode ?? 0;
208
+ const location = res.headers.location;
209
+ if (!REDIRECT_STATUSES.has(status) || !location || redirectMode === 'manual') {
210
+ return toResponse(res, url, method, resolved.maxResponseBytes, hop > 0);
211
+ }
212
+ res.resume();
213
+ if (redirectMode === 'error') {
214
+ throw new OutboundRequestBlockedError('redirect_not_allowed', `Upstream redirected (${status}) and redirects are disabled`);
215
+ }
216
+ if (hop >= resolved.maxRedirects) {
217
+ throw new OutboundRequestBlockedError('too_many_redirects', `More than ${resolved.maxRedirects} redirects`);
218
+ }
219
+ const next = nextHop(location, url, resolved);
220
+ if (next.origin !== url.origin) {
221
+ for (const name of CROSS_ORIGIN_STRIPPED)
222
+ delete headers[name];
223
+ }
224
+ // Same method-rewriting rules as the Fetch standard.
225
+ if ((status === 303 && method !== 'HEAD') || ((status === 301 || status === 302) && method === 'POST')) {
226
+ method = 'GET';
227
+ body = undefined;
228
+ delete headers['content-type'];
229
+ }
230
+ url = next;
231
+ }
232
+ }
233
+ //# sourceMappingURL=secure-fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secure-fetch.js","sourceRoot":"","sources":["../../src/net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