@hilbras/sdk 4.0.0 → 4.0.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/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.0-blue" alt="version">
6
+ <img src="https://img.shields.io/badge/version-4.0.1-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">
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";
@@ -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.0",
3
+ "version": "4.0.1",
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",