@hilbras/sdk 4.0.0 → 4.0.2
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/README.md +1 -1
- package/dist/features/agent/schema-validator.js +31 -12
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/security/url-guard.js +13 -0
- package/dist/transport/pinned-dns-transport.d.ts +39 -0
- package/dist/transport/pinned-dns-transport.js +106 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
5
|
<p align="center">
|
|
6
|
-
<img src="https://img.shields.io/badge/version-4.0.
|
|
6
|
+
<img src="https://img.shields.io/badge/version-4.0.2-blue" alt="version">
|
|
7
7
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
|
8
8
|
<img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
|
|
9
9
|
<img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
|
|
@@ -8,19 +8,37 @@
|
|
|
8
8
|
* bounds. Unknown keywords are ignored rather than rejected, so richer
|
|
9
9
|
* schemas still work (they are simply less strictly checked here).
|
|
10
10
|
*/
|
|
11
|
+
/**
|
|
12
|
+
* Maximum nesting depth validated before failing closed.
|
|
13
|
+
*
|
|
14
|
+
* Tool arguments come from model output, which an attacker can shape. Without
|
|
15
|
+
* a bound, a deeply nested payload overflows the call stack and takes down the
|
|
16
|
+
* agent loop (RangeError) instead of being rejected as bad input.
|
|
17
|
+
*/
|
|
18
|
+
const MAX_VALIDATION_DEPTH = 64;
|
|
11
19
|
/** Validate a value against the declared JSON Schema subset. */
|
|
12
20
|
export function validateAgainstSchema(value, schema, path = "args") {
|
|
13
21
|
const errors = [];
|
|
22
|
+
validateNode(value, schema, path, 0, errors);
|
|
23
|
+
return { valid: errors.length === 0, errors };
|
|
24
|
+
}
|
|
25
|
+
function validateNode(value, schema, path, depth, errors) {
|
|
26
|
+
if (depth > MAX_VALIDATION_DEPTH) {
|
|
27
|
+
errors.push(`${path}: nesting deeper than ${MAX_VALIDATION_DEPTH} levels`);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
14
30
|
if (!schema || typeof schema !== "object")
|
|
15
|
-
return
|
|
31
|
+
return;
|
|
16
32
|
const expectedType = schema.type;
|
|
17
33
|
if (typeof expectedType === "string") {
|
|
18
34
|
const actual = jsonType(value);
|
|
19
35
|
if (actual !== expectedType && !(expectedType === "integer" && actual === "number")) {
|
|
20
|
-
|
|
36
|
+
errors.push(`${path}: expected ${expectedType}, got ${actual}`);
|
|
37
|
+
return;
|
|
21
38
|
}
|
|
22
39
|
if (expectedType === "integer" && typeof value === "number" && !Number.isInteger(value)) {
|
|
23
|
-
|
|
40
|
+
errors.push(`${path}: expected integer`);
|
|
41
|
+
return;
|
|
24
42
|
}
|
|
25
43
|
}
|
|
26
44
|
if (Array.isArray(schema.enum) && !schema.enum.some((option) => option === value)) {
|
|
@@ -38,28 +56,29 @@ export function validateAgainstSchema(value, schema, path = "args") {
|
|
|
38
56
|
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
39
57
|
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
40
58
|
for (const key of required) {
|
|
41
|
-
if (!(key
|
|
59
|
+
if (!Object.prototype.hasOwnProperty.call(value, key))
|
|
42
60
|
errors.push(`${path}.${key}: required`);
|
|
43
61
|
}
|
|
44
|
-
for (const
|
|
45
|
-
if (key
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
62
|
+
for (const key of Object.keys(properties)) {
|
|
63
|
+
if (!Object.prototype.hasOwnProperty.call(value, key))
|
|
64
|
+
continue;
|
|
65
|
+
const child = properties[key];
|
|
66
|
+
validateNode(value[key], isRecord(child) ? child : undefined, `${path}.${key}`, depth + 1, errors);
|
|
49
67
|
}
|
|
50
68
|
if (schema.additionalProperties === false) {
|
|
51
69
|
for (const key of Object.keys(value)) {
|
|
52
|
-
if (!(key
|
|
70
|
+
if (!Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
53
71
|
errors.push(`${path}.${key}: additional property not allowed`);
|
|
72
|
+
}
|
|
54
73
|
}
|
|
55
74
|
}
|
|
56
75
|
}
|
|
57
76
|
if (expectedType === "array" && Array.isArray(value) && isRecord(schema.items)) {
|
|
77
|
+
const itemSchema = schema.items;
|
|
58
78
|
value.forEach((item, index) => {
|
|
59
|
-
|
|
79
|
+
validateNode(item, itemSchema, `${path}[${index}]`, depth + 1, errors);
|
|
60
80
|
});
|
|
61
81
|
}
|
|
62
|
-
return { valid: errors.length === 0, errors };
|
|
63
82
|
}
|
|
64
83
|
function jsonType(value) {
|
|
65
84
|
if (value === null)
|
package/dist/index.d.ts
CHANGED
|
@@ -47,6 +47,8 @@ export type { CostEvent, CostReport, BudgetConfig } from "./cost/types.js";
|
|
|
47
47
|
export type { Transport, TransportRequestInit } from "./transport/transport.js";
|
|
48
48
|
export { FetchTransport } from "./transport/fetch.js";
|
|
49
49
|
export { WebSocketTransport } from "./transport/websocket.js";
|
|
50
|
+
export { PinnedDnsTransport } from "./transport/pinned-dns-transport.js";
|
|
51
|
+
export type { PinnedDnsTransportOptions } from "./transport/pinned-dns-transport.js";
|
|
50
52
|
export { MiddlewareTransport } from "./transport/middleware-transport.js";
|
|
51
53
|
export { CircuitBreaker, CircuitBreakerRegistry, getCircuitBreakerRegistry } from "./reliability/circuit-breaker.js";
|
|
52
54
|
export type { CircuitBreakerConfig, CircuitBreakerStats, CircuitState } from "./reliability/circuit-breaker.js";
|
package/dist/index.js
CHANGED
|
@@ -34,6 +34,7 @@ export { BodyLogger } from "./telemetry/body-logger.js";
|
|
|
34
34
|
export { BudgetTracker } from "./cost/tracker.js";
|
|
35
35
|
export { FetchTransport } from "./transport/fetch.js";
|
|
36
36
|
export { WebSocketTransport } from "./transport/websocket.js";
|
|
37
|
+
export { PinnedDnsTransport } from "./transport/pinned-dns-transport.js";
|
|
37
38
|
export { MiddlewareTransport } from "./transport/middleware-transport.js";
|
|
38
39
|
// ─── Reliability ────────────────────────────────────────────────────────────
|
|
39
40
|
export { CircuitBreaker, CircuitBreakerRegistry, getCircuitBreakerRegistry } from "./reliability/circuit-breaker.js";
|
|
@@ -264,6 +264,19 @@ function embeddedIPv4FromIPv6(groups) {
|
|
|
264
264
|
groups[5] === 0) {
|
|
265
265
|
return `${(groups[6] >> 8) & 0xff}.${groups[6] & 0xff}.${(groups[7] >> 8) & 0xff}.${groups[7] & 0xff}`;
|
|
266
266
|
}
|
|
267
|
+
// 6to4 (RFC 3056): 2002:VVVV:VVVV::/48 carries the IPv4 address in bits
|
|
268
|
+
// 16..47 (groups 1 and 2). A 6to4-capable host relays traffic to that
|
|
269
|
+
// address, so `2002:a9fe:a9fe::` reaches 169.254.169.254.
|
|
270
|
+
if (groups[0] === 0x2002) {
|
|
271
|
+
return `${(groups[1] >> 8) & 0xff}.${groups[1] & 0xff}.${(groups[2] >> 8) & 0xff}.${groups[2] & 0xff}`;
|
|
272
|
+
}
|
|
273
|
+
// Teredo (RFC 4380): 2001:0000::/32. The client's IPv4 is stored inverted
|
|
274
|
+
// (XOR 0xffffffff) in the last two groups.
|
|
275
|
+
if (groups[0] === 0x2001 && groups[1] === 0x0000) {
|
|
276
|
+
const a = ~groups[6] & 0xffff;
|
|
277
|
+
const b = ~groups[7] & 0xffff;
|
|
278
|
+
return `${(a >> 8) & 0xff}.${a & 0xff}.${(b >> 8) & 0xff}.${b & 0xff}`;
|
|
279
|
+
}
|
|
267
280
|
// IPv4-compatible (deprecated but still parsed by some stacks): ::a.b.c.d,
|
|
268
281
|
// excluding :: and ::1 which are handled as special cases above.
|
|
269
282
|
if (high.every((group) => group === 0) && groups[5] === 0) {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — DNS-pinned HTTP transport (v4.0.1 follow-up)
|
|
3
|
+
*
|
|
4
|
+
* `validateResolvedHostname()` is a preflight: a hostile DNS server can still
|
|
5
|
+
* return a public address during validation and a private one on the socket
|
|
6
|
+
* opened milliseconds later (DNS rebinding). PinnedDnsTransport closes that
|
|
7
|
+
* window by validating the address at connection time, using Node's `lookup`
|
|
8
|
+
* option on http/https requests. The callback runs for each new socket, so a
|
|
9
|
+
* rebinding answer is rejected before a connection is established.
|
|
10
|
+
*
|
|
11
|
+
* The transport is Node-only and opt-in. Node builtins are loaded with dynamic
|
|
12
|
+
* imports so importing the SDK in a browser bundle stays clean. It implements
|
|
13
|
+
* the same Transport contract as FetchTransport and returns a WHATWG Response
|
|
14
|
+
* with a stream body, so adapters need no changes.
|
|
15
|
+
*/
|
|
16
|
+
import type { Transport, TransportRequestInit } from "./transport.js";
|
|
17
|
+
export interface PinnedDnsTransportOptions {
|
|
18
|
+
/** Called when a resolved address is rejected (for logging/metrics). */
|
|
19
|
+
onBlocked?: (hostname: string, address: string) => void;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Find the first resolved address rejected by the SSRF guard, if any.
|
|
23
|
+
* Exported for direct testing without opening a socket.
|
|
24
|
+
*/
|
|
25
|
+
export declare function firstBlockedAddress(hostname: string, records: Array<{
|
|
26
|
+
address: string;
|
|
27
|
+
family: number;
|
|
28
|
+
}>): {
|
|
29
|
+
address: string;
|
|
30
|
+
family: number;
|
|
31
|
+
} | undefined;
|
|
32
|
+
/** Perform a request whose DNS resolution is validated at connect time. */
|
|
33
|
+
export declare class PinnedDnsTransport implements Transport {
|
|
34
|
+
private readonly _onBlocked;
|
|
35
|
+
constructor(options?: PinnedDnsTransportOptions);
|
|
36
|
+
request(url: string, init: TransportRequestInit): Promise<Response>;
|
|
37
|
+
stream(url: string, init: TransportRequestInit): Promise<ReadableStream<Uint8Array>>;
|
|
38
|
+
abort(): void;
|
|
39
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — DNS-pinned HTTP transport (v4.0.1 follow-up)
|
|
3
|
+
*
|
|
4
|
+
* `validateResolvedHostname()` is a preflight: a hostile DNS server can still
|
|
5
|
+
* return a public address during validation and a private one on the socket
|
|
6
|
+
* opened milliseconds later (DNS rebinding). PinnedDnsTransport closes that
|
|
7
|
+
* window by validating the address at connection time, using Node's `lookup`
|
|
8
|
+
* option on http/https requests. The callback runs for each new socket, so a
|
|
9
|
+
* rebinding answer is rejected before a connection is established.
|
|
10
|
+
*
|
|
11
|
+
* The transport is Node-only and opt-in. Node builtins are loaded with dynamic
|
|
12
|
+
* imports so importing the SDK in a browser bundle stays clean. It implements
|
|
13
|
+
* the same Transport contract as FetchTransport and returns a WHATWG Response
|
|
14
|
+
* with a stream body, so adapters need no changes.
|
|
15
|
+
*/
|
|
16
|
+
import { validateResolvedAddress } from "../security/url-guard.js";
|
|
17
|
+
/**
|
|
18
|
+
* Find the first resolved address rejected by the SSRF guard, if any.
|
|
19
|
+
* Exported for direct testing without opening a socket.
|
|
20
|
+
*/
|
|
21
|
+
export function firstBlockedAddress(hostname, records) {
|
|
22
|
+
return records.find((record) => !validateResolvedAddress(record.address).ok);
|
|
23
|
+
}
|
|
24
|
+
/** Perform a request whose DNS resolution is validated at connect time. */
|
|
25
|
+
export class PinnedDnsTransport {
|
|
26
|
+
_onBlocked;
|
|
27
|
+
constructor(options = {}) {
|
|
28
|
+
this._onBlocked = options.onBlocked;
|
|
29
|
+
}
|
|
30
|
+
async request(url, init) {
|
|
31
|
+
const [{ default: http }, { default: https }, dns] = await Promise.all([
|
|
32
|
+
import("node:http"),
|
|
33
|
+
import("node:https"),
|
|
34
|
+
import("node:dns"),
|
|
35
|
+
]);
|
|
36
|
+
const { URL: NodeURL } = await import("node:url");
|
|
37
|
+
const target = new NodeURL(url);
|
|
38
|
+
if (target.protocol !== "http:" && target.protocol !== "https:") {
|
|
39
|
+
throw new Error(`PinnedDnsTransport supports only http(s), got ${target.protocol}`);
|
|
40
|
+
}
|
|
41
|
+
const client = target.protocol === "https:" ? https : http;
|
|
42
|
+
const lookup = (hostname, options, callback) => {
|
|
43
|
+
dns.lookup(hostname, { all: true }, (error, records) => {
|
|
44
|
+
if (error || !records || records.length === 0) {
|
|
45
|
+
callback(error ?? new Error(`No DNS records for ${hostname}`), [], 0);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const blocked = firstBlockedAddress(hostname, records);
|
|
49
|
+
if (blocked) {
|
|
50
|
+
this._onBlocked?.(hostname, blocked.address);
|
|
51
|
+
callback(new Error(`DNS SSRF guard blocked ${hostname} -> ${blocked.address}`), [], 0);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const wantsAll = Boolean(options?.all);
|
|
55
|
+
if (wantsAll)
|
|
56
|
+
callback(null, records, 0);
|
|
57
|
+
else
|
|
58
|
+
callback(null, records[0].address, records[0].family);
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
const headers = {};
|
|
63
|
+
for (const [key, value] of Object.entries(init.headers ?? {})) {
|
|
64
|
+
if (value !== undefined)
|
|
65
|
+
headers[key] = value;
|
|
66
|
+
}
|
|
67
|
+
if (typeof init.body === "string" && headers["content-length"] === undefined) {
|
|
68
|
+
headers["content-length"] = String(Buffer.byteLength(init.body));
|
|
69
|
+
}
|
|
70
|
+
const req = client.request(target, { method: init.method, headers, lookup: lookup }, (res) => {
|
|
71
|
+
const chunks = [];
|
|
72
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
73
|
+
res.on("error", reject);
|
|
74
|
+
res.on("end", () => {
|
|
75
|
+
const body = Buffer.concat(chunks);
|
|
76
|
+
resolve(new Response(new Uint8Array(body), {
|
|
77
|
+
status: res.statusCode ?? 200,
|
|
78
|
+
statusText: res.statusMessage ?? "",
|
|
79
|
+
headers: Object.fromEntries(Object.entries(res.headers).filter(([, value]) => typeof value === "string")),
|
|
80
|
+
}));
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
req.on("error", reject);
|
|
84
|
+
if (init.signal) {
|
|
85
|
+
if (init.signal.aborted)
|
|
86
|
+
req.destroy(init.signal.reason);
|
|
87
|
+
else {
|
|
88
|
+
const signal = init.signal;
|
|
89
|
+
signal.addEventListener("abort", () => req.destroy(signal.reason), { once: true });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (init.body !== undefined)
|
|
93
|
+
req.write(init.body);
|
|
94
|
+
req.end();
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async stream(url, init) {
|
|
98
|
+
const response = await this.request(url, init);
|
|
99
|
+
if (!response.body)
|
|
100
|
+
throw new Error(`Response body is null for ${url}`);
|
|
101
|
+
return response.body;
|
|
102
|
+
}
|
|
103
|
+
abort() {
|
|
104
|
+
// Requests are short-lived; no shared controllers to abort.
|
|
105
|
+
}
|
|
106
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hilbras/sdk",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.2",
|
|
4
4
|
"description": "Provider-agnostic LLM client SDK — streaming, tool calling, embeddings, image generation, speech synthesis, transcription, reranking, circuit breaker, retry, reasoning normalization, cost enforcement, structured output with schema validation, type-safe tool builder, and SSRF-safe provider registration. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|