varfetch 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
2
+ EUPL © the European Union 2007, 2016
3
+
4
+ This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the
5
+ terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
6
+ use is covered by a right of the copyright holder of the Work).
7
+ The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
8
+ notice immediately following the copyright notice for the Work:
9
+ Licensed under the EUPL
10
+ or has expressed by any other means his willingness to license under the EUPL.
11
+
12
+ 1.Definitions
13
+ In this Licence, the following terms have the following meaning:
14
+ — ‘The Licence’:this Licence.
15
+ — ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available
16
+ as Source Code and also as Executable Code as the case may be.
17
+ — ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or
18
+ modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
19
+ required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
20
+ the country mentioned in Article 15.
21
+ — ‘The Work’:the Original Work or its Derivative Works.
22
+ — ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and
23
+ modify.
24
+ — ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by
25
+ a computer as a program.
26
+ — ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence.
27
+ — ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
28
+ the creation of a Derivative Work.
29
+ — ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the
30
+ Licence.
31
+ — ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating,
32
+ transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
33
+ functionalities at the disposal of any other natural or legal person.
34
+
35
+ 2.Scope of the rights granted by the Licence
36
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
37
+ the duration of copyright vested in the Original Work:
38
+ — use the Work in any circumstance and for all usage,
39
+ — reproduce the Work,
40
+ — modify the Work, and make Derivative Works based upon the Work,
41
+ — communicate to the public, including the right to make available or display the Work or copies thereof to the public
42
+ and perform publicly, as the case may be, the Work,
43
+ — distribute the Work or copies thereof,
44
+ — lend and rent the Work or copies thereof,
45
+ — sublicense rights in the Work or copies thereof.
46
+ Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
47
+ applicable law permits so.
48
+ In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
49
+ by law in order to make effective the licence of the economic rights here above listed.
50
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
51
+ extent necessary to make use of the rights granted on the Work under this Licence.
52
+
53
+ 3.Communication of the Source Code
54
+ The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
55
+ Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
56
+ each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
57
+ the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
58
+ distribute or communicate the Work.
59
+
60
+ 4.Limitations on copyright
61
+ Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
62
+ exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
63
+ thereto.
64
+
65
+ 5.Obligations of the Licensee
66
+ The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
67
+ obligations are the following:
68
+
69
+ Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
70
+ the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
71
+ Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
72
+ to carry prominent notices stating that the Work has been modified and the date of modification.
73
+
74
+ Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
75
+ Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
76
+ the Original Work is expressly distributed only under this version of the Licence — for example by communicating
77
+ ‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
78
+ Work or Derivative Work that alter or restrict the terms of the Licence.
79
+
80
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
81
+ the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
82
+ under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed
83
+ in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
84
+ his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
85
+
86
+ Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide
87
+ a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
88
+ for as long as the Licensee continues to distribute or communicate the Work.
89
+ Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
90
+ of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
91
+ reproducing the content of the copyright notice.
92
+
93
+ 6.Chain of Authorship
94
+ The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
95
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
96
+ Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
97
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
98
+ Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
99
+ to the Work, under the terms of this Licence.
100
+
101
+ 7.Disclaimer of Warranty
102
+ The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
103
+ and may therefore contain defects or ‘bugs’ inherent to this type of development.
104
+ For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind
105
+ concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
106
+ errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
107
+ Licence.
108
+ This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
109
+
110
+ 8.Disclaimer of Liability
111
+ Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
112
+ liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
113
+ Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
114
+ of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
115
+ the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
116
+
117
+ 9.Additional agreements
118
+ While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
119
+ consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
120
+ responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
121
+ defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
122
+ the fact You have accepted any warranty or additional liability.
123
+
124
+ 10.Acceptance of the Licence
125
+ The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window
126
+ displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
127
+ applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
128
+ and conditions.
129
+ Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
130
+ by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
131
+ or Communication by You of the Work or copies thereof.
132
+
133
+ 11.Information to the public
134
+ In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
135
+ by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
136
+ must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
137
+ and the way it may be accessible, concluded, stored and reproduced by the Licensee.
138
+
139
+ 12.Termination of the Licence
140
+ The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
141
+ of the Licence.
142
+ Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
143
+ the Licence, provided such persons remain in full compliance with the Licence.
144
+
145
+ 13.Miscellaneous
146
+ Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
147
+ Work.
148
+ If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
149
+ enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
150
+ and enforceable.
151
+ The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
152
+ the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
153
+ New versions of the Licence will be published with a unique version number.
154
+ All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
155
+ advantage of the linguistic version of their choice.
156
+
157
+ 14.Jurisdiction
158
+ Without prejudice to specific agreement between parties,
159
+ — any litigation resulting from the interpretation of this License, arising between the European Union institutions,
160
+ bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
161
+ of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
162
+ — any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
163
+ the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
164
+
165
+ 15.Applicable Law
166
+ Without prejudice to specific agreement between parties,
167
+ — this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
168
+ resides or has his registered office,
169
+ — this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
170
+ a European Union Member State.
171
+
172
+
173
+ Appendix
174
+
175
+ ‘Compatible Licences’ according to Article 5 EUPL are:
176
+ — GNU General Public License (GPL) v. 2, v. 3
177
+ — GNU Affero General Public License (AGPL) v. 3
178
+ — Open Software License (OSL) v. 2.1, v. 3.0
179
+ — Eclipse Public License (EPL) v. 1.0
180
+ — CeCILL v. 2.0, v. 2.1
181
+ — Mozilla Public Licence (MPL) v. 2
182
+ — GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
183
+ — Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
184
+ — European Union Public Licence (EUPL) v. 1.1, v. 1.2
185
+ — Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
186
+
187
+ The European Commission may update this Appendix to later versions of the above licences without producing
188
+ a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
189
+ covered Source Code from exclusive appropriation.
190
+ All other changes or additions to this Appendix require the production of a new EUPL version.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # varfetch
2
+
3
+ Fire a configured HTTP request, with `{{variable}}` values in its path, query, headers and body, and map the JSON response onto named variables. No dependencies, ESM, Node 18+.
4
+
5
+ It is the small, database-free core of a "connector" feature: the application stores connectors and requests however it likes (a database, a config file) and passes them to `fireRequest`.
6
+
7
+ ```js
8
+ import { fireRequest } from 'varfetch';
9
+
10
+ const connector = {
11
+ baseUrl: 'https://api.example.org',
12
+ auth: { type: 'bearer', token: '...' }, // none | bearer | api_key | basic | custom
13
+ headers: [{ key: 'Accept-Language', value: 'fi' }],
14
+ };
15
+
16
+ const request = {
17
+ method: 'GET',
18
+ path: '/api/v1/date/{{date}}',
19
+ query: [{ key: 'cycles', value: 'false' }],
20
+ mappings: [
21
+ { jsonPath: '$.holyDay.name', variable: 'holyday' },
22
+ { jsonPath: '$.holyDay.texts.gospel.reference', variable: 'gospel' },
23
+ ],
24
+ };
25
+
26
+ const result = await fireRequest({ connector, request, variables: { date: '2026-10-11' } });
27
+ // { ok: true, status: 200, values: { holyday: '...', gospel: '...' }, body: {...} }
28
+ ```
29
+
30
+ ## What it does
31
+
32
+ - **Interpolation:** `{{name}}` in path, query values, header values, auth values and body. Missing variables become an empty string.
33
+ - **JSON path:** `$`, `$.a.b`, `$.items[0].name`, `$['key']`. Own properties only.
34
+ - **Mapping:** each mapping writes a string (or JSON text for objects and arrays) to a variable; `skipIfNull` (default true) leaves unresolved paths out.
35
+ - **SSRF guard:** every URL, redirects included, is resolved and checked. Loopback, private, link-local, CGNAT, reserved and multicast addresses are blocked unless you allow them: `network: { allow: ['10.1.0.0/16', 'anno.internal:3000'], deny: ['*.blocked.example'] }`. `deny` wins over `allow`. The check happens before the connection and does not defend against DNS rebinding.
36
+ - **Limits:** 10 s timeout and 5 MiB response by default (`timeoutMs`, `maxBytes`), at most 5 redirects, credentials and other connector headers are not forwarded to another origin.
37
+
38
+ Variable values are put into the path as given. A value containing `/`, `?` or `#` changes the URL, so run untrusted values through `encodeURIComponent`, or use them in a query parameter, which is encoded for you.
39
+
40
+ ## API
41
+
42
+ `fireRequest({ connector, request, variables, network, fetch, timeoutMs, maxBytes })` returns `{ ok, status?, values, body?, error? }` and never throws.
43
+
44
+ Building blocks: `buildRequest(connector, request, variables)`, `buildAuthHeaders`, `mapResponse(mappings, body)`, `interpolate`, `interpolatePairs`, `extractVariableNames`, `evaluateJsonPath`, `checkUrlAllowed(url, { allow, deny })`, `parsePattern`. Types are in `src/index.d.ts`.
45
+
46
+ ## License
47
+
48
+ EUPL-1.2.
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "varfetch",
3
+ "version": "0.1.0",
4
+ "description": "Fire configured HTTP requests with {{variable}} interpolation, an SSRF guard and JSON path mapping of the response onto named variables.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "types": "src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "default": "./src/index.js"
12
+ }
13
+ },
14
+ "files": ["src", "LICENSE", "README.md"],
15
+ "scripts": {
16
+ "test": "node --test test/*.test.js"
17
+ },
18
+ "keywords": ["http", "variables", "api", "connector", "ssrf", "jsonpath"],
19
+ "author": "Juha Itäleino <jsilvanus@gmail.com>",
20
+ "license": "EUPL-1.2",
21
+ "engines": {
22
+ "node": ">=18.0.0"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/jsilvanus/varfetch.git"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/jsilvanus/varfetch/issues"
30
+ },
31
+ "homepage": "https://github.com/jsilvanus/varfetch#readme"
32
+ }
package/src/fire.js ADDED
@@ -0,0 +1,101 @@
1
+ import { buildRequest, mapResponse } from './request.js';
2
+ import { checkUrlAllowed } from './network-guard.js';
3
+
4
+ const MAX_REDIRECTS = 5;
5
+ const DEFAULT_TIMEOUT_MS = 10_000;
6
+ const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
7
+
8
+ /**
9
+ * Send a request and map the response onto variables.
10
+ *
11
+ * Every URL is checked with the SSRF guard, redirects included (they are
12
+ * followed here, up to 5, instead of by fetch).
13
+ *
14
+ * @param {object} args
15
+ * @param {import('./index.js').Connector} args.connector
16
+ * @param {import('./index.js').RequestDef} args.request
17
+ * @param {Record<string, unknown>} [args.variables] values for {{name}}
18
+ * @param {{ allow?: string[], deny?: string[] }} [args.network] extra guard patterns, see network-guard.js
19
+ * @param {typeof fetch} [args.fetch]
20
+ * @param {number} [args.timeoutMs] default 10000
21
+ * @param {number} [args.maxBytes] response size limit, default 5 MiB
22
+ * @returns {Promise<import('./index.js').FireResult>}
23
+ */
24
+ export async function fireRequest({ connector, request, variables = {}, network = {}, fetch: fetchImpl = fetch, timeoutMs, maxBytes = DEFAULT_MAX_BYTES }) {
25
+ let built;
26
+ try {
27
+ built = buildRequest(connector, request, variables);
28
+ } catch (err) {
29
+ return { ok: false, values: {}, error: `Invalid request: ${err.message}` };
30
+ }
31
+
32
+ const timeout = timeoutMs ?? request.timeoutMs ?? DEFAULT_TIMEOUT_MS;
33
+ const signal = AbortSignal.timeout(timeout);
34
+
35
+ try {
36
+ let url = built.url;
37
+ let method = built.method;
38
+ let body = built.body;
39
+ let headers = built.headers;
40
+ let response;
41
+
42
+ for (let hop = 0; ; hop++) {
43
+ const guard = await checkUrlAllowed(url, network);
44
+ if (!guard.allowed) return { ok: false, values: {}, error: guard.reason };
45
+
46
+ response = await fetchImpl(url, { method, headers, body, redirect: 'manual', signal });
47
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get('location') : null;
48
+ if (!location) break;
49
+ if (hop >= MAX_REDIRECTS) return { ok: false, values: {}, status: response.status, error: 'Too many redirects' };
50
+
51
+ const next = new URL(location, url);
52
+ if (next.origin !== url.origin) {
53
+ // Credentials and every other connector header stay with the original origin.
54
+ headers = Object.fromEntries(Object.entries(headers).filter(([name]) => /^(content-type|accept)$/i.test(name)));
55
+ }
56
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === 'POST')) {
57
+ method = 'GET';
58
+ body = undefined;
59
+ }
60
+ url = next;
61
+ }
62
+
63
+ const text = await readLimited(response, maxBytes);
64
+ if (!response.ok) return { ok: false, status: response.status, values: {}, error: `HTTP ${response.status}` };
65
+
66
+ const contentType = response.headers.get('content-type') || '';
67
+ const wantsJson = request.responseType === 'json' || ((request.responseType ?? 'auto') === 'auto' && /json/i.test(contentType));
68
+ let parsed = text;
69
+ if (wantsJson) {
70
+ try {
71
+ parsed = text ? JSON.parse(text) : null;
72
+ } catch {
73
+ return { ok: false, status: response.status, values: {}, error: 'Response is not valid JSON' };
74
+ }
75
+ }
76
+ return { ok: true, status: response.status, values: mapResponse(request.mappings, parsed), body: parsed };
77
+ } catch (err) {
78
+ const message = err?.name === 'TimeoutError' ? `Timed out after ${timeout} ms` : err?.message ?? String(err);
79
+ return { ok: false, values: {}, error: message };
80
+ }
81
+ }
82
+
83
+ async function readLimited(response, maxBytes) {
84
+ const declared = Number(response.headers.get('content-length'));
85
+ if (declared > maxBytes) throw new Error(`Response larger than ${maxBytes} bytes`);
86
+ if (!response.body) return '';
87
+ const reader = response.body.getReader();
88
+ const chunks = [];
89
+ let size = 0;
90
+ for (;;) {
91
+ const { done, value } = await reader.read();
92
+ if (done) break;
93
+ size += value.byteLength;
94
+ if (size > maxBytes) {
95
+ await reader.cancel();
96
+ throw new Error(`Response larger than ${maxBytes} bytes`);
97
+ }
98
+ chunks.push(value);
99
+ }
100
+ return Buffer.concat(chunks).toString('utf8');
101
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ export type Variables = Record<string, unknown>;
2
+ export interface Pair { key: string; value: string }
3
+
4
+ export type Auth =
5
+ | { type: 'none' }
6
+ | { type: 'bearer'; token: string }
7
+ | { type: 'api_key'; headerName: string; value: string }
8
+ | { type: 'basic'; username: string; password?: string }
9
+ | { type: 'custom'; headers: Record<string, string> };
10
+
11
+ export interface Connector {
12
+ baseUrl: string;
13
+ auth?: Auth;
14
+ /** Extra headers sent with every request of this connector. */
15
+ headers?: Pair[];
16
+ }
17
+
18
+ export interface Mapping {
19
+ /** `$`, `$.a.b`, `$.items[0].name` or `$['key']`. */
20
+ jsonPath: string;
21
+ /** Name of the variable that receives the value. */
22
+ variable: string;
23
+ /** Default true: leave the variable out when the path does not resolve. */
24
+ skipIfNull?: boolean;
25
+ }
26
+
27
+ export interface RequestDef {
28
+ method?: string;
29
+ /** May contain {{name}}. */
30
+ path?: string;
31
+ query?: Pair[];
32
+ bodyType?: 'none' | 'json' | 'text';
33
+ body?: string;
34
+ responseType?: 'auto' | 'json' | 'text';
35
+ mappings?: Mapping[];
36
+ timeoutMs?: number;
37
+ }
38
+
39
+ export interface NetworkRules { allow?: string[]; deny?: string[] }
40
+
41
+ export interface FireResult {
42
+ ok: boolean;
43
+ status?: number;
44
+ /** Variable name to value; non-string values are JSON text. */
45
+ values: Record<string, string | null>;
46
+ /** Parsed JSON, or the text for a non-JSON response. */
47
+ body?: unknown;
48
+ error?: string;
49
+ }
50
+
51
+ export function interpolate(text: string, variables?: Variables): string;
52
+ export function interpolatePairs(pairs: Pair[] | undefined, variables?: Variables): Pair[];
53
+ export function extractVariableNames(text: string): string[];
54
+ export function evaluateJsonPath(data: unknown, path: string): unknown;
55
+ export function parsePattern(pattern: string): { kind: 'host' | 'ip' | 'cidr'; value: string; port: number | null };
56
+ export function checkUrlAllowed(
57
+ url: URL,
58
+ options?: NetworkRules & { lookup?: (host: string, opts: { all: true; verbatim: true }) => Promise<Array<{ address: string; family: number }>> },
59
+ ): Promise<{ allowed: boolean; reason?: string }>;
60
+ export function buildAuthHeaders(auth: Auth | undefined, variables?: Variables): Record<string, string>;
61
+ export function buildRequest(
62
+ connector: Connector,
63
+ request: RequestDef,
64
+ variables?: Variables,
65
+ ): { url: URL; method: string; headers: Record<string, string>; body?: string };
66
+ export function mapResponse(mappings: Mapping[] | undefined, body: unknown): Record<string, string | null>;
67
+ export function fireRequest(args: {
68
+ connector: Connector;
69
+ request: RequestDef;
70
+ variables?: Variables;
71
+ network?: NetworkRules;
72
+ fetch?: typeof fetch;
73
+ timeoutMs?: number;
74
+ maxBytes?: number;
75
+ }): Promise<FireResult>;
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { interpolate, interpolatePairs, extractVariableNames } from './interpolate.js';
2
+ export { evaluateJsonPath } from './json-path.js';
3
+ export { checkUrlAllowed, parsePattern } from './network-guard.js';
4
+ export { buildRequest, buildAuthHeaders, mapResponse } from './request.js';
5
+ export { fireRequest } from './fire.js';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * {{name}} interpolation. Pure: reads whatever a variable currently holds.
3
+ */
4
+
5
+ const VAR_RE = /\{\{\s*([\p{L}_][\p{L}\p{N}_-]*)\s*\}\}/gu;
6
+
7
+ /**
8
+ * Replace every {{name}} in a string with its value from `variables`.
9
+ * A missing variable renders as an empty string.
10
+ * @param {string} text
11
+ * @param {Record<string, unknown>} [variables]
12
+ */
13
+ export function interpolate(text, variables) {
14
+ if (typeof text !== 'string' || !text.includes('{{')) return text;
15
+ return text.replace(VAR_RE, (_match, name) => {
16
+ const value = variables?.[name];
17
+ return value === undefined || value === null ? '' : String(value);
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Interpolate the value of each `{ key, value }` pair (headers and query parameters).
23
+ * @param {Array<{ key: string, value: string }>} pairs
24
+ * @param {Record<string, unknown>} [variables]
25
+ */
26
+ export function interpolatePairs(pairs, variables) {
27
+ if (!Array.isArray(pairs)) return [];
28
+ return pairs.map(({ key, value }) => ({ key, value: interpolate(value, variables) }));
29
+ }
30
+
31
+ /** Unique {{name}} references of a string, in order of first use. */
32
+ export function extractVariableNames(text) {
33
+ if (typeof text !== 'string') return [];
34
+ const names = new Set();
35
+ for (const match of text.matchAll(VAR_RE)) names.add(match[1]);
36
+ return [...names];
37
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Minimal JSONPath subset: `$` (whole body), dot access (`$.foo.bar`), numeric
3
+ * index (`$.items[0].name`) and quoted keys (`$['weird key']`). No wildcards,
4
+ * filters or recursive descent.
5
+ *
6
+ * @param {unknown} data parsed JSON body
7
+ * @param {string} path
8
+ * @returns {unknown} the value, or undefined when the path does not resolve
9
+ */
10
+ export function evaluateJsonPath(data, path) {
11
+ if (!path || path === '$') return data;
12
+
13
+ let current = data;
14
+ for (const token of tokenize(path)) {
15
+ if (current === undefined || current === null) return undefined;
16
+ // Own properties only, so paths like `$.constructor` or `$.__proto__` resolve to nothing.
17
+ if (!Object.prototype.hasOwnProperty.call(Object(current), token)) return undefined;
18
+ current = current[token];
19
+ }
20
+ return current;
21
+ }
22
+
23
+ function tokenize(path) {
24
+ let rest = path.trim();
25
+ if (rest.startsWith('$')) rest = rest.slice(1);
26
+ if (rest.startsWith('.')) rest = rest.slice(1);
27
+
28
+ const tokens = [];
29
+ const re = /([^[.\]]+)|\[(\d+)\]|\['([^']*)'\]|\["([^"]*)"\]/g;
30
+ let m;
31
+ while ((m = re.exec(rest)) !== null) {
32
+ if (m[1] !== undefined) tokens.push(m[1]);
33
+ else if (m[2] !== undefined) tokens.push(Number(m[2]));
34
+ else if (m[3] !== undefined) tokens.push(m[3]);
35
+ else if (m[4] !== undefined) tokens.push(m[4]);
36
+ }
37
+ return tokens;
38
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Outbound request SSRF guard.
3
+ *
4
+ * Without it, a connector's base URL is user-controlled and the server would
5
+ * fetch whatever it points at (cloud metadata endpoints, internal services).
6
+ *
7
+ * Defaults: block loopback, private, link-local, CGNAT, reserved and multicast
8
+ * addresses. The check runs on the DNS-resolved addresses, not only on the
9
+ * hostname string, so a public-looking name that resolves to a private IP is
10
+ * caught too. Callers add their own `allow` and `deny` patterns on top.
11
+ *
12
+ * Evaluation order (first match wins):
13
+ * 1. scheme other than http/https -> blocked, no override
14
+ * 2. a `deny` pattern matches -> blocked
15
+ * 3. an `allow` pattern matches -> allowed
16
+ * 4. resolves to a restricted address -> blocked
17
+ * 5. otherwise -> allowed
18
+ *
19
+ * Pattern syntax:
20
+ * - exact hostname: "api.example.com" or "api.example.com:8443"
21
+ * - wildcard subdomain: "*.example.com"
22
+ * - exact IP: "127.0.0.1" or "127.0.0.1:11434"
23
+ * - CIDR: "10.0.0.0/8" or "[fc00::]/7"
24
+ * - bracketed IPv6 + port "[::1]:11434"
25
+ * A pattern without a port matches that host or IP on any port.
26
+ *
27
+ * The addresses are resolved once, before the fetch. This does not defend
28
+ * against DNS rebinding between the check and the connection.
29
+ */
30
+ import { BlockList, isIP } from 'node:net';
31
+ import { lookup as dnsLookup } from 'node:dns/promises';
32
+
33
+ const DEFAULT_BLOCKED_V4 = [
34
+ ['0.0.0.0', 8], // "this network" / unspecified
35
+ ['10.0.0.0', 8], // private
36
+ ['100.64.0.0', 10], // carrier-grade NAT
37
+ ['127.0.0.0', 8], // loopback
38
+ ['169.254.0.0', 16], // link-local — includes cloud metadata (169.254.169.254)
39
+ ['172.16.0.0', 12], // private
40
+ ['192.0.0.0', 24], // IETF protocol assignments
41
+ ['192.168.0.0', 16], // private
42
+ ['198.18.0.0', 15], // benchmarking
43
+ ['224.0.0.0', 4], // multicast
44
+ ['240.0.0.0', 4], // reserved
45
+ ];
46
+ const DEFAULT_BLOCKED_V6 = [
47
+ ['::1', 128], // loopback
48
+ ['::', 128], // unspecified
49
+ ['fc00::', 7], // unique local (ULA)
50
+ ['fe80::', 10], // link-local
51
+ ['ff00::', 8], // multicast
52
+ // No explicit IPv4-mapped (::ffff:x.x.x.x) rule needed: net.BlockList
53
+ // already matches a mapped address checked as 'ipv6' against the
54
+ // corresponding plain-IPv4 rule above checked as 'ipv4' — adding an
55
+ // explicit ::ffff:0:0/96 rule here double-counts that and, empirically,
56
+ // corrupts unrelated 'ipv4' checks against the same BlockList instance.
57
+ ];
58
+
59
+ const defaultBlockList = new BlockList();
60
+ for (const [addr, prefix] of DEFAULT_BLOCKED_V4) defaultBlockList.addSubnet(addr, prefix, 'ipv4');
61
+ for (const [addr, prefix] of DEFAULT_BLOCKED_V6) defaultBlockList.addSubnet(addr, prefix, 'ipv6');
62
+
63
+ function isDefaultRestricted(address, family) {
64
+ return defaultBlockList.check(address, family === 6 ? 'ipv6' : 'ipv4');
65
+ }
66
+
67
+ /** Parse a rule pattern into { kind: 'host'|'ip'|'cidr', value, port|null }. */
68
+ export function parsePattern(pattern) {
69
+ let value = pattern.trim();
70
+ let port = null;
71
+
72
+ if (value.startsWith('[')) {
73
+ const close = value.indexOf(']');
74
+ if (close !== -1) {
75
+ const host = value.slice(1, close);
76
+ const rest = value.slice(close + 1);
77
+ const portMatch = rest.match(/^:(\d+)$/);
78
+ value = host;
79
+ if (portMatch) port = Number(portMatch[1]);
80
+ }
81
+ } else {
82
+ const lastColon = value.lastIndexOf(':');
83
+ if (lastColon > -1) {
84
+ const maybePort = value.slice(lastColon + 1);
85
+ const maybeHost = value.slice(0, lastColon);
86
+ // Only treat trailing ":N" as a port if the remainder isn't itself a
87
+ // bare (colon-bearing) IPv6 literal.
88
+ if (/^\d+$/.test(maybePort) && !maybeHost.includes(':')) {
89
+ value = maybeHost;
90
+ port = Number(maybePort);
91
+ }
92
+ }
93
+ }
94
+
95
+ if (value.includes('/')) return { kind: 'cidr', value, port };
96
+ if (isIP(value)) return { kind: 'ip', value, port };
97
+ return { kind: 'host', value: value.toLowerCase(), port };
98
+ }
99
+
100
+ function hostMatches(pattern, hostname) {
101
+ if (pattern.startsWith('*.')) {
102
+ const suffix = pattern.slice(2);
103
+ return hostname === suffix || hostname.endsWith(`.${suffix}`);
104
+ }
105
+ return pattern === hostname;
106
+ }
107
+
108
+ function ruleMatches(pattern, { hostname, addresses, port }) {
109
+ const parsed = parsePattern(pattern);
110
+ if (parsed.port != null && parsed.port !== port) return false;
111
+
112
+ if (parsed.kind === 'host') return hostMatches(parsed.value, hostname);
113
+ if (parsed.kind === 'ip') return addresses.some((a) => a.address === parsed.value);
114
+
115
+ // CIDR
116
+ try {
117
+ const [net, prefixStr] = parsed.value.split('/');
118
+ const prefix = Number(prefixStr);
119
+ const family = isIP(net) === 6 ? 'ipv6' : 'ipv4';
120
+ const bl = new BlockList();
121
+ bl.addSubnet(net, prefix, family);
122
+ return addresses.some((a) => bl.check(a.address, a.family === 6 ? 'ipv6' : 'ipv4'));
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * @param {URL} url
130
+ * @param {{ allow?: string[], deny?: string[], lookup?: typeof dnsLookup }} [options]
131
+ * @returns {Promise<{ allowed: boolean, reason?: string }>}
132
+ */
133
+ export async function checkUrlAllowed(url, { allow = [], deny = [], lookup = dnsLookup } = {}) {
134
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
135
+ return { allowed: false, reason: `Unsupported protocol: ${url.protocol}` };
136
+ }
137
+
138
+ // WHATWG URL keeps brackets around an IPv6 literal in .hostname ("[::1]").
139
+ const hostname = url.hostname.replace(/^\[|\]$/g, '').toLowerCase();
140
+ const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80);
141
+
142
+ let addresses;
143
+ try {
144
+ addresses = await lookup(hostname, { all: true, verbatim: true });
145
+ } catch {
146
+ addresses = [];
147
+ }
148
+ if (addresses.length === 0) {
149
+ return { allowed: false, reason: `Could not resolve host: ${hostname}` };
150
+ }
151
+
152
+ const match = { hostname, addresses, port };
153
+ if (deny.some((pattern) => ruleMatches(pattern, match))) {
154
+ return { allowed: false, reason: 'Blocked by network policy' };
155
+ }
156
+ if (allow.some((pattern) => ruleMatches(pattern, match))) {
157
+ return { allowed: true };
158
+ }
159
+ if (addresses.some((a) => isDefaultRestricted(a.address, a.family))) {
160
+ return { allowed: false, reason: 'Blocked: target resolves to a private/internal/reserved address' };
161
+ }
162
+ return { allowed: true };
163
+ }
package/src/request.js ADDED
@@ -0,0 +1,85 @@
1
+ import { interpolate, interpolatePairs } from './interpolate.js';
2
+ import { evaluateJsonPath } from './json-path.js';
3
+
4
+ /**
5
+ * Headers a connector's auth settings add.
6
+ * `auth` is `{ type: 'none' }`, `{ type: 'bearer', token }`, `{ type: 'api_key', headerName, value }`,
7
+ * `{ type: 'basic', username, password }` or `{ type: 'custom', headers: { name: value } }`.
8
+ * Values are interpolated, so `{{token}}` works.
9
+ */
10
+ export function buildAuthHeaders(auth, variables) {
11
+ if (!auth) return {};
12
+ switch (auth.type) {
13
+ case 'bearer':
14
+ return auth.token ? { Authorization: `Bearer ${interpolate(auth.token, variables)}` } : {};
15
+ case 'api_key':
16
+ return auth.headerName ? { [auth.headerName]: interpolate(auth.value ?? '', variables) } : {};
17
+ case 'basic': {
18
+ if (!auth.username) return {};
19
+ const raw = `${interpolate(auth.username, variables)}:${interpolate(auth.password ?? '', variables)}`;
20
+ return { Authorization: `Basic ${Buffer.from(raw).toString('base64')}` };
21
+ }
22
+ case 'custom':
23
+ return auth.headers && typeof auth.headers === 'object'
24
+ ? Object.fromEntries(Object.entries(auth.headers).map(([name, value]) => [name, interpolate(String(value), variables)]))
25
+ : {};
26
+ default:
27
+ return {};
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Build the URL, method, headers and body of a request without sending it.
33
+ * Path, query, headers and body are interpolated with `variables`.
34
+ *
35
+ * Variable values are put into the path as given, so a value containing `/`,
36
+ * `?` or `#` changes the URL. Pass untrusted values through `encodeURIComponent`
37
+ * yourself, or write `{{name}}` into a query parameter, which is encoded for you.
38
+ *
39
+ * @param {import('./index.js').Connector} connector
40
+ * @param {import('./index.js').RequestDef} request
41
+ * @param {Record<string, unknown>} [variables]
42
+ */
43
+ export function buildRequest(connector, request, variables = {}) {
44
+ const base = connector.baseUrl.replace(/\/+$/, '');
45
+ const path = interpolate(request.path || '', variables);
46
+ const url = new URL(base + (path.startsWith('/') ? path : `/${path}`));
47
+ for (const { key, value } of interpolatePairs(request.query, variables)) {
48
+ if (key) url.searchParams.append(key, value ?? '');
49
+ }
50
+
51
+ const headers = {
52
+ ...Object.fromEntries(interpolatePairs(connector.headers, variables).filter((p) => p.key).map(({ key, value }) => [key, value])),
53
+ ...buildAuthHeaders(connector.auth, variables),
54
+ };
55
+
56
+ const method = (request.method || 'GET').toUpperCase();
57
+ let body;
58
+ if (request.bodyType && request.bodyType !== 'none' && request.body && method !== 'GET' && method !== 'HEAD') {
59
+ body = interpolate(request.body, variables);
60
+ const hasContentType = Object.keys(headers).some((name) => name.toLowerCase() === 'content-type');
61
+ if (!hasContentType) headers['Content-Type'] = request.bodyType === 'json' ? 'application/json' : 'text/plain';
62
+ }
63
+
64
+ return { url, method, headers, body };
65
+ }
66
+
67
+ /**
68
+ * Map a response body onto variables with the request's mappings.
69
+ * A non-string value is stored as JSON text. With `skipIfNull` (default true) an
70
+ * unresolved path leaves the variable out; otherwise it is `null`.
71
+ *
72
+ * @param {import('./index.js').Mapping[]} mappings
73
+ * @param {unknown} body parsed JSON, or the response text
74
+ * @returns {Record<string, string | null>}
75
+ */
76
+ export function mapResponse(mappings, body) {
77
+ const values = {};
78
+ for (const mapping of mappings ?? []) {
79
+ const extracted = evaluateJsonPath(body, mapping.jsonPath);
80
+ const missing = extracted === undefined || extracted === null;
81
+ if (missing && mapping.skipIfNull !== false) continue;
82
+ values[mapping.variable] = missing ? null : typeof extracted === 'string' ? extracted : JSON.stringify(extracted);
83
+ }
84
+ return values;
85
+ }