@hilbras/sdk 3.8.1 → 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 +18 -13
- package/dist/adapters/openai-compatible.d.ts +4 -0
- package/dist/adapters/openai-compatible.js +9 -0
- package/dist/adapters/openai.d.ts +4 -0
- package/dist/adapters/openai.js +9 -0
- package/dist/client/client.d.ts +7 -0
- package/dist/client/client.js +34 -9
- package/dist/config/config-schema.d.ts +2 -0
- package/dist/config/config-schema.js +1 -0
- package/dist/config/resolved-config.js +2 -0
- package/dist/core/execution/ports.d.ts +2 -1
- package/dist/core/execution/request-pipeline.js +20 -2
- package/dist/cost/tracker.d.ts +10 -2
- package/dist/cost/tracker.js +11 -2
- package/dist/cost/types.d.ts +9 -0
- package/dist/credentials/provider.js +7 -0
- package/dist/features/agent/schema-validator.d.ts +18 -0
- package/dist/features/agent/schema-validator.js +77 -0
- package/dist/features/agent/tool-loop.js +17 -0
- package/dist/frameworks/nextjs/route-handlers.js +8 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/providers/registry.d.ts +12 -0
- package/dist/providers/registry.js +29 -4
- package/dist/security/dns-guard.d.ts +27 -0
- package/dist/security/dns-guard.js +62 -0
- package/dist/security/request-signer.d.ts +28 -7
- package/dist/security/request-signer.js +77 -8
- package/dist/security/url-guard.js +99 -4
- package/dist/transport/pinned-dns-transport.d.ts +39 -0
- package/dist/transport/pinned-dns-transport.js +106 -0
- package/dist/types/adapter.d.ts +10 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="
|
|
2
|
+
<img src="./brand/logo.svg" alt="@hilbras/sdk" width="96" height="96">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<p align="center">
|
|
6
|
+
<img src="https://img.shields.io/badge/version-4.0.1-blue" alt="version">
|
|
3
7
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
|
4
8
|
<img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
|
|
5
9
|
<img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
|
|
6
|
-
<img src="https://img.shields.io/badge/tests-
|
|
10
|
+
<img src="https://img.shields.io/badge/tests-2114%20passing-brightgreen" alt="tests">
|
|
7
11
|
<img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
|
|
8
12
|
</p>
|
|
9
13
|
|
|
@@ -11,7 +15,8 @@
|
|
|
11
15
|
|
|
12
16
|
<p align="center">
|
|
13
17
|
<strong>Provider-agnostic AI execution engine for TypeScript.</strong><br>
|
|
14
|
-
Streaming, tool calling, structured output, circuit breaker, retry, reasoning normalization, cost enforcement, plugin system, RBAC, SLA monitoring, A/B testing, and SSRF-safe provider registration — for OpenAI, Anthropic, Gemini, Azure, Groq, Ollama, Bedrock, Vertex AI, HuggingFace, Deepgram, ElevenLabs, Voyage AI, and Cohere Rerank. Zero runtime dependencies
|
|
18
|
+
Streaming, tool calling, structured output, circuit breaker, retry, reasoning normalization, cost enforcement, plugin system, RBAC, SLA monitoring, A/B testing, and SSRF-safe provider registration — for OpenAI, Anthropic, Gemini, Azure, Groq, Ollama, Bedrock, Vertex AI, HuggingFace, Deepgram, ElevenLabs, Voyage AI, and Cohere Rerank. Zero runtime dependencies.<br>
|
|
19
|
+
13 named providers are implemented by 23 provider adapters (plus 2 shared helper modules).
|
|
15
20
|
</p>
|
|
16
21
|
|
|
17
22
|
---
|
|
@@ -49,14 +54,17 @@ Application
|
|
|
49
54
|
Groq Ollama Azure
|
|
50
55
|
```
|
|
51
56
|
|
|
52
|
-
**Zero runtime dependencies.**
|
|
57
|
+
**Zero runtime dependencies.** Verified on Node 22 and 24 in CI; the declared
|
|
58
|
+
minimum is Node 18+.
|
|
53
59
|
|
|
54
60
|
The root entry re-exports config loading and request signing, which import
|
|
55
61
|
`node:fs` and `node:crypto`, so `import "@hilbras/sdk"` does not load in a
|
|
56
62
|
browser bundle or an edge runtime without shimming those built-ins. Import the
|
|
57
63
|
subpath entries (for example `@hilbras/sdk/adapters/openai`) where the root
|
|
58
|
-
entry is too broad.
|
|
59
|
-
[
|
|
64
|
+
entry is too broad. As of v4.0.0 the signer exposes an async WebCrypto path for
|
|
65
|
+
browser-compatible runtimes; see [Request signing](docs/security.md). Bun and
|
|
66
|
+
Deno are not yet covered by CI — use the subpath entries there and report any
|
|
67
|
+
compatibility issues.
|
|
60
68
|
|
|
61
69
|
---
|
|
62
70
|
|
|
@@ -66,18 +74,15 @@ entry is too broad. Making the root entry portable is tracked as item 8 in
|
|
|
66
74
|
npm install @hilbras/sdk
|
|
67
75
|
```
|
|
68
76
|
|
|
69
|
-
|
|
77
|
+
For React bindings, install React itself (an optional peer dependency); the SDK
|
|
78
|
+
package is the same:
|
|
70
79
|
|
|
71
80
|
```bash
|
|
72
|
-
npm install @hilbras/sdk
|
|
81
|
+
npm install @hilbras/sdk react react-dom
|
|
73
82
|
```
|
|
74
83
|
|
|
75
84
|
## Quick start
|
|
76
85
|
|
|
77
|
-
```bash
|
|
78
|
-
npm install @hilbras/sdk
|
|
79
|
-
```
|
|
80
|
-
|
|
81
86
|
```typescript
|
|
82
87
|
import { HilbrasClient } from "@hilbras/sdk";
|
|
83
88
|
|
|
@@ -536,7 +541,7 @@ import { exportTrainingData } from "@hilbras/sdk/fine-tune";
|
|
|
536
541
|
```bash
|
|
537
542
|
npm install
|
|
538
543
|
npm run build # Compile TypeScript
|
|
539
|
-
npm test # Run the root test suite (
|
|
544
|
+
npm test # Run the root test suite (2114 tests)
|
|
540
545
|
npm run typecheck:tests # Typecheck the tests (`tsc --noEmit` covers src only)
|
|
541
546
|
npm run test:packages # Build and test companion packages
|
|
542
547
|
npm run test:watch # Watch mode
|
|
@@ -80,6 +80,10 @@ export declare class GenericOpenAIAdapter implements AIProvider {
|
|
|
80
80
|
tools?: Tool[];
|
|
81
81
|
extra?: Record<string, unknown>;
|
|
82
82
|
signal?: AbortSignal;
|
|
83
|
+
onUsage?: (usage: {
|
|
84
|
+
inputTokens?: number;
|
|
85
|
+
outputTokens?: number;
|
|
86
|
+
}) => void;
|
|
83
87
|
}): Promise<string>;
|
|
84
88
|
embed(params: EmbeddingParams): Promise<EmbeddingResult>;
|
|
85
89
|
}
|
|
@@ -316,6 +316,15 @@ export class GenericOpenAIAdapter {
|
|
|
316
316
|
catch {
|
|
317
317
|
return "";
|
|
318
318
|
}
|
|
319
|
+
// Report provider-reported usage (F-07) so the pipeline can settle the
|
|
320
|
+
// budget against actual cost rather than the pre-flight estimate.
|
|
321
|
+
const usage = data.usage;
|
|
322
|
+
if (usage && params.onUsage) {
|
|
323
|
+
params.onUsage({
|
|
324
|
+
inputTokens: typeof usage.prompt_tokens === "number" ? usage.prompt_tokens : undefined,
|
|
325
|
+
outputTokens: typeof usage.completion_tokens === "number" ? usage.completion_tokens : undefined,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
319
328
|
const choices = data.choices;
|
|
320
329
|
if (!choices?.length)
|
|
321
330
|
return "";
|
|
@@ -42,6 +42,10 @@ export declare class OpenAIAdapter implements AIProvider {
|
|
|
42
42
|
tools?: Tool[];
|
|
43
43
|
extra?: Record<string, unknown>;
|
|
44
44
|
signal?: AbortSignal;
|
|
45
|
+
onUsage?: (usage: {
|
|
46
|
+
inputTokens?: number;
|
|
47
|
+
outputTokens?: number;
|
|
48
|
+
}) => void;
|
|
45
49
|
}): Promise<string>;
|
|
46
50
|
embed(params: EmbeddingParams): Promise<EmbeddingResult>;
|
|
47
51
|
generateImage(params: ImageParams): Promise<ImageResult>;
|
package/dist/adapters/openai.js
CHANGED
|
@@ -304,6 +304,15 @@ export class OpenAIAdapter {
|
|
|
304
304
|
// Non-JSON response — return empty string rather than crashing
|
|
305
305
|
return "";
|
|
306
306
|
}
|
|
307
|
+
// Report provider usage so the pipeline can settle budgets against
|
|
308
|
+
// actual cost (F-07). Adapters without a usage payload simply skip this.
|
|
309
|
+
const usage = data.usage;
|
|
310
|
+
if (usage && params.onUsage) {
|
|
311
|
+
params.onUsage({
|
|
312
|
+
inputTokens: typeof usage.prompt_tokens === "number" ? usage.prompt_tokens : undefined,
|
|
313
|
+
outputTokens: typeof usage.completion_tokens === "number" ? usage.completion_tokens : undefined,
|
|
314
|
+
});
|
|
315
|
+
}
|
|
307
316
|
const choices = data.choices;
|
|
308
317
|
if (!choices?.length)
|
|
309
318
|
return "";
|
package/dist/client/client.d.ts
CHANGED
|
@@ -230,6 +230,13 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
230
230
|
* ```
|
|
231
231
|
*/
|
|
232
232
|
addProviderFromCatalog(providerId: string, modelId: string, apiKey: string): string;
|
|
233
|
+
/**
|
|
234
|
+
* v4.0.0: register a catalog provider with an additional DNS-resolution
|
|
235
|
+
* SSRF preflight. The base URL is resolved and every returned address is
|
|
236
|
+
* validated before the provider is added, closing the resolve-time gap
|
|
237
|
+
* that string-only validation cannot cover.
|
|
238
|
+
*/
|
|
239
|
+
addProviderFromCatalogStrict(providerId: string, modelId: string, apiKey: string): Promise<string>;
|
|
233
240
|
/** Access the adapter registry for plugins */
|
|
234
241
|
get adapterRegistry(): AdapterRegistry;
|
|
235
242
|
/**
|
package/dist/client/client.js
CHANGED
|
@@ -338,6 +338,25 @@ export class HilbrasClient {
|
|
|
338
338
|
});
|
|
339
339
|
return provider.name;
|
|
340
340
|
}
|
|
341
|
+
/**
|
|
342
|
+
* v4.0.0: register a catalog provider with an additional DNS-resolution
|
|
343
|
+
* SSRF preflight. The base URL is resolved and every returned address is
|
|
344
|
+
* validated before the provider is added, closing the resolve-time gap
|
|
345
|
+
* that string-only validation cannot cover.
|
|
346
|
+
*/
|
|
347
|
+
async addProviderFromCatalogStrict(providerId, modelId, apiKey) {
|
|
348
|
+
const catalogProviderId = listProviders().find((id) => id.toLowerCase() === providerId.toLowerCase()) ?? providerId;
|
|
349
|
+
const provider = getProviderCatalog(catalogProviderId);
|
|
350
|
+
if (!provider)
|
|
351
|
+
throw new ConfigurationError(`Unknown provider: ${providerId}`);
|
|
352
|
+
const { validateResolvedHostname } = await import("../security/dns-guard.js");
|
|
353
|
+
const hostname = new URL(provider.baseUrl).hostname;
|
|
354
|
+
const dns = await validateResolvedHostname(hostname);
|
|
355
|
+
if (!dns.ok) {
|
|
356
|
+
throw new ConfigurationError(`Provider '${providerId}' rejected by DNS SSRF guard: ${dns.reason ?? "unknown reason"}`);
|
|
357
|
+
}
|
|
358
|
+
return this.addProviderFromCatalog(providerId, modelId, apiKey);
|
|
359
|
+
}
|
|
341
360
|
/** Access the adapter registry for plugins */
|
|
342
361
|
get adapterRegistry() {
|
|
343
362
|
return this._adapterRegistry;
|
|
@@ -417,7 +436,11 @@ export class HilbrasClient {
|
|
|
417
436
|
}
|
|
418
437
|
// ─── Adapter Lookup ─────────────────────────────────────────────────────
|
|
419
438
|
_getAdapter(providerName) {
|
|
420
|
-
|
|
439
|
+
// Provider names are canonical PascalCase in the catalog ("OpenAI"), but
|
|
440
|
+
// requests may use the lowercase catalog id ("openai"). Resolve through
|
|
441
|
+
// the registry so both spellings reach the same adapter (issue #121).
|
|
442
|
+
const canonical = this._registry.canonicalName(providerName) ?? providerName;
|
|
443
|
+
const adapter = this._adapters.get(canonical);
|
|
421
444
|
if (!adapter)
|
|
422
445
|
throw new ProviderNotFoundError(providerName, this._registry.list().map((c) => c.name));
|
|
423
446
|
return adapter;
|
|
@@ -458,10 +481,12 @@ export class HilbrasClient {
|
|
|
458
481
|
}
|
|
459
482
|
// ─── Provider/Model Resolution ──────────────────────────────────────────
|
|
460
483
|
_resolveProviderModel(params) {
|
|
461
|
-
// If explicit provider + model, use them directly
|
|
484
|
+
// If explicit provider + model, use them directly. Canonicalize the
|
|
485
|
+
// provider name so a lowercase catalog id ("openai") resolves to the
|
|
486
|
+
// registered PascalCase entry ("OpenAI") — issue #121.
|
|
462
487
|
if (params.provider && params.model) {
|
|
463
488
|
return {
|
|
464
|
-
providerName: params.provider,
|
|
489
|
+
providerName: this._registry.canonicalName(params.provider) ?? params.provider,
|
|
465
490
|
modelId: params.model,
|
|
466
491
|
score: 0,
|
|
467
492
|
reasons: ["Explicit provider/model"],
|
|
@@ -514,7 +539,7 @@ export class HilbrasClient {
|
|
|
514
539
|
throw new ModelNotFoundError(modelId, providerName, providerConfig.models.map((m) => m.id));
|
|
515
540
|
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score, reasons });
|
|
516
541
|
const messages = this._normalizeMessages(params.messages);
|
|
517
|
-
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))
|
|
542
|
+
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")));
|
|
518
543
|
yield* this._requestPipeline.runStream({
|
|
519
544
|
requestId,
|
|
520
545
|
startTime,
|
|
@@ -534,7 +559,7 @@ export class HilbrasClient {
|
|
|
534
559
|
providerTimeoutMs: providerConfig.timeout,
|
|
535
560
|
callerSignal: params.signal,
|
|
536
561
|
fallbackCandidates: (excludeModels) => this._getFallbacks(excludeModels, params),
|
|
537
|
-
estimateFallbackCost: (candidate) => this._budgetTracker.estimate(candidate.model, candidate.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))
|
|
562
|
+
estimateFallbackCost: (candidate) => this._budgetTracker.estimate(candidate.model, candidate.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))),
|
|
538
563
|
getProviderTimeout: (provider) => this._registry.get(provider)?.timeout,
|
|
539
564
|
});
|
|
540
565
|
}
|
|
@@ -559,7 +584,7 @@ export class HilbrasClient {
|
|
|
559
584
|
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score: resolved_.score, reasons: resolved_.reasons });
|
|
560
585
|
if (!params.output) {
|
|
561
586
|
const messages = this._normalizeMessages(params.messages);
|
|
562
|
-
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))
|
|
587
|
+
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")));
|
|
563
588
|
return this._requestPipeline.runComplete({
|
|
564
589
|
requestId,
|
|
565
590
|
startTime,
|
|
@@ -579,13 +604,13 @@ export class HilbrasClient {
|
|
|
579
604
|
providerTimeoutMs: providerConfig.timeout,
|
|
580
605
|
callerSignal: params.signal,
|
|
581
606
|
fallbackCandidates: (excludeModels) => this._getFallbacks(excludeModels, params),
|
|
582
|
-
estimateFallbackCost: (candidate) => this._budgetTracker.estimate(candidate.model, candidate.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))
|
|
607
|
+
estimateFallbackCost: (candidate) => this._budgetTracker.estimate(candidate.model, candidate.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))),
|
|
583
608
|
getProviderTimeout: (provider) => this._registry.get(provider)?.timeout,
|
|
584
609
|
});
|
|
585
610
|
}
|
|
586
611
|
if (params.output) {
|
|
587
612
|
const messages = this._normalizeMessages(params.messages);
|
|
588
|
-
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))
|
|
613
|
+
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")));
|
|
589
614
|
return this._requestPipeline.runStructuredComplete({
|
|
590
615
|
requestId,
|
|
591
616
|
startTime,
|
|
@@ -610,7 +635,7 @@ export class HilbrasClient {
|
|
|
610
635
|
return adapter ? buildJsonModeParams(adapter.id) : {};
|
|
611
636
|
},
|
|
612
637
|
fallbackCandidates: (excludeModels) => this._getFallbacks(excludeModels, { ...params, needsStructuredOutput: true }),
|
|
613
|
-
estimateFallbackCost: (candidate) => this._budgetTracker.estimate(candidate.model, candidate.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))
|
|
638
|
+
estimateFallbackCost: (candidate) => this._budgetTracker.estimate(candidate.model, candidate.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join(""))),
|
|
614
639
|
getProviderTimeout: (provider) => this._registry.get(provider)?.timeout,
|
|
615
640
|
});
|
|
616
641
|
}
|
|
@@ -59,6 +59,8 @@ export interface SDKConfig {
|
|
|
59
59
|
deniedTools: string[];
|
|
60
60
|
sessionBudget?: number;
|
|
61
61
|
perRequestBudget?: number;
|
|
62
|
+
/** Output tokens assumed when pre-flight estimating unary request cost. */
|
|
63
|
+
estimatedOutputTokens?: number;
|
|
62
64
|
rbac?: import("../security/rbac.js").RBACConfig;
|
|
63
65
|
costAlerts?: import("../cost/alerts.js").CostAlertConfig;
|
|
64
66
|
sla?: Array<import("../telemetry/sla.js").SLADefinition>;
|
|
@@ -34,6 +34,8 @@ export function budgetFromConfig(config) {
|
|
|
34
34
|
budget.sessionBudget = config.sessionBudget;
|
|
35
35
|
if (config.perRequestBudget !== undefined)
|
|
36
36
|
budget.perRequestBudget = config.perRequestBudget;
|
|
37
|
+
if (config.estimatedOutputTokens !== undefined)
|
|
38
|
+
budget.estimatedOutputTokens = config.estimatedOutputTokens;
|
|
37
39
|
return budget;
|
|
38
40
|
}
|
|
39
41
|
export function createSafeSnapshot(values) {
|
|
@@ -29,7 +29,8 @@ export interface AdapterRegistryPort {
|
|
|
29
29
|
get(provider: string): AdapterPort | undefined;
|
|
30
30
|
}
|
|
31
31
|
export interface BudgetPort {
|
|
32
|
-
|
|
32
|
+
/** When `outputTokens` is omitted, the tracker's configured allowance is used. */
|
|
33
|
+
estimate(model: string, provider: string, inputTokens: number, outputTokens?: number): number;
|
|
33
34
|
reserve(requestId: string, estimatedCost: number): unknown;
|
|
34
35
|
settle(requestId: string, actualCost: number, metadata: {
|
|
35
36
|
provider: string;
|
|
@@ -9,6 +9,7 @@ import { CircuitBreakerOpenError, ConfigurationError, ValidationError } from "..
|
|
|
9
9
|
import { calculateBackoff } from "../../reliability/backoff.js";
|
|
10
10
|
import { buildJsonSystemInstruction, buildRepairPrompt, extractJson } from "../../output/structured.js";
|
|
11
11
|
import { shouldRetry, shouldRetryNetworkError } from "../../reliability/retry.js";
|
|
12
|
+
import { estimateCost } from "../../tokens/counter.js";
|
|
12
13
|
const NETWORK_ERROR_CODES = new Set([
|
|
13
14
|
"ECONNREFUSED",
|
|
14
15
|
"ECONNRESET",
|
|
@@ -81,10 +82,27 @@ export class RequestPipeline {
|
|
|
81
82
|
budgetReleased = true;
|
|
82
83
|
}
|
|
83
84
|
};
|
|
85
|
+
// F-07: capture provider-reported usage on unary completions so the
|
|
86
|
+
// budget can settle against actual cost instead of the input-only
|
|
87
|
+
// pre-flight estimate. Adapters that do not report usage leave this
|
|
88
|
+
// undefined and we fall back to the estimate.
|
|
89
|
+
let actualUsage;
|
|
90
|
+
const paramsWithUsage = {
|
|
91
|
+
...input.params,
|
|
92
|
+
onUsage: (usage) => {
|
|
93
|
+
actualUsage = usage;
|
|
94
|
+
},
|
|
95
|
+
};
|
|
84
96
|
for (;;) {
|
|
85
|
-
const result = await this.ports.executor.executeComplete(prepared,
|
|
97
|
+
const result = await this.ports.executor.executeComplete(prepared, paramsWithUsage, { dispose: false, recordCircuitFailure: false });
|
|
86
98
|
if (result.ok) {
|
|
87
|
-
|
|
99
|
+
const usage = actualUsage;
|
|
100
|
+
const hasUsage = usage !== undefined &&
|
|
101
|
+
(usage.inputTokens !== undefined || usage.outputTokens !== undefined);
|
|
102
|
+
const actualCost = hasUsage
|
|
103
|
+
? estimateCost(usage.inputTokens ?? 0, usage.outputTokens ?? 0, input.provider, input.model).totalCost
|
|
104
|
+
: input.estimatedCost;
|
|
105
|
+
this.ports.budget.settle(input.requestId, actualCost, {
|
|
88
106
|
provider: input.provider,
|
|
89
107
|
model: input.model,
|
|
90
108
|
phase: "execute",
|
package/dist/cost/tracker.d.ts
CHANGED
|
@@ -34,9 +34,17 @@ export declare class BudgetTracker {
|
|
|
34
34
|
private _budgetExceededFired;
|
|
35
35
|
constructor(budget?: BudgetConfig);
|
|
36
36
|
/**
|
|
37
|
-
*
|
|
37
|
+
* Default output-token allowance used when a caller does not supply one.
|
|
38
|
+
* Chosen to be conservative enough that output-heavy models are not
|
|
39
|
+
* systematically under-reserved, without making every short reply look
|
|
40
|
+
* expensive. Override via `BudgetConfig.estimatedOutputTokens`.
|
|
38
41
|
*/
|
|
39
|
-
|
|
42
|
+
static readonly DEFAULT_ESTIMATED_OUTPUT_TOKENS = 256;
|
|
43
|
+
/**
|
|
44
|
+
* Estimate cost before execution. When `outputTokens` is omitted, the
|
|
45
|
+
* configured `estimatedOutputTokens` allowance (or the default) is used.
|
|
46
|
+
*/
|
|
47
|
+
estimate(model: string, provider: string, inputTokens: number, outputTokens?: number): number;
|
|
40
48
|
/**
|
|
41
49
|
* Check if a request would exceed the per-request budget.
|
|
42
50
|
*/
|
package/dist/cost/tracker.js
CHANGED
|
@@ -31,10 +31,19 @@ export class BudgetTracker {
|
|
|
31
31
|
this._budget = budget ?? {};
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
34
|
-
*
|
|
34
|
+
* Default output-token allowance used when a caller does not supply one.
|
|
35
|
+
* Chosen to be conservative enough that output-heavy models are not
|
|
36
|
+
* systematically under-reserved, without making every short reply look
|
|
37
|
+
* expensive. Override via `BudgetConfig.estimatedOutputTokens`.
|
|
38
|
+
*/
|
|
39
|
+
static DEFAULT_ESTIMATED_OUTPUT_TOKENS = 256;
|
|
40
|
+
/**
|
|
41
|
+
* Estimate cost before execution. When `outputTokens` is omitted, the
|
|
42
|
+
* configured `estimatedOutputTokens` allowance (or the default) is used.
|
|
35
43
|
*/
|
|
36
44
|
estimate(model, provider, inputTokens, outputTokens) {
|
|
37
|
-
const
|
|
45
|
+
const assumedOutput = outputTokens ?? this._budget.estimatedOutputTokens ?? BudgetTracker.DEFAULT_ESTIMATED_OUTPUT_TOKENS;
|
|
46
|
+
const result = estimateCost(inputTokens, assumedOutput, provider, model);
|
|
38
47
|
return result.totalCost;
|
|
39
48
|
}
|
|
40
49
|
/**
|
package/dist/cost/types.d.ts
CHANGED
|
@@ -55,6 +55,15 @@ export interface BudgetConfig {
|
|
|
55
55
|
sessionBudget?: number;
|
|
56
56
|
/** Maximum cost per individual request (null = unlimited) */
|
|
57
57
|
perRequestBudget?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Output tokens assumed when pre-flight estimating a request's cost.
|
|
60
|
+
*
|
|
61
|
+
* The real output length is unknown before execution, so reserving input
|
|
62
|
+
* cost alone systematically undercounts output-heavy models. Defaults to
|
|
63
|
+
* 256 tokens for unary/structured requests in v4; streaming responses
|
|
64
|
+
* settle against actual usage when the provider reports it.
|
|
65
|
+
*/
|
|
66
|
+
estimatedOutputTokens?: number;
|
|
58
67
|
/** Callback when budget threshold is reached */
|
|
59
68
|
onBudgetWarning?: (report: CostReport) => void;
|
|
60
69
|
/** Callback when budget is exceeded */
|
|
@@ -10,6 +10,13 @@ export class DefaultCredentialProvider {
|
|
|
10
10
|
case "explicit":
|
|
11
11
|
return source.apiKey;
|
|
12
12
|
case "environment": {
|
|
13
|
+
// v4.0.0: ambient environment credentials must never be read in a
|
|
14
|
+
// browser-like runtime. A bundled `process.env` shim could otherwise
|
|
15
|
+
// expose build-time secrets to every visitor; pass an explicit
|
|
16
|
+
// per-request credential in the browser instead.
|
|
17
|
+
if (typeof window !== "undefined" || typeof navigator !== "undefined") {
|
|
18
|
+
throw new Error("Environment credentials are not available in browser runtimes; pass the key explicitly");
|
|
19
|
+
}
|
|
13
20
|
const value = process.env[source.variable];
|
|
14
21
|
if (!value) {
|
|
15
22
|
throw new Error(`Environment variable '${source.variable}' is not set`);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/agent — lightweight tool-argument schema validation
|
|
3
|
+
*
|
|
4
|
+
* v4.0.0 enforces that arguments produced by the model conform to the JSON
|
|
5
|
+
* Schema declared by each tool before the tool is executed. This is a small,
|
|
6
|
+
* dependency-free validator covering the JSON Schema subset tools actually
|
|
7
|
+
* declare: object type, `required`, per-property `type`, `enum`, and numeric
|
|
8
|
+
* bounds. Unknown keywords are ignored rather than rejected, so richer
|
|
9
|
+
* schemas still work (they are simply less strictly checked here).
|
|
10
|
+
*/
|
|
11
|
+
export interface SchemaValidationResult {
|
|
12
|
+
valid: boolean;
|
|
13
|
+
errors: string[];
|
|
14
|
+
}
|
|
15
|
+
type JsonSchema = Record<string, unknown>;
|
|
16
|
+
/** Validate a value against the declared JSON Schema subset. */
|
|
17
|
+
export declare function validateAgainstSchema(value: unknown, schema: JsonSchema | undefined, path?: string): SchemaValidationResult;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/agent — lightweight tool-argument schema validation
|
|
3
|
+
*
|
|
4
|
+
* v4.0.0 enforces that arguments produced by the model conform to the JSON
|
|
5
|
+
* Schema declared by each tool before the tool is executed. This is a small,
|
|
6
|
+
* dependency-free validator covering the JSON Schema subset tools actually
|
|
7
|
+
* declare: object type, `required`, per-property `type`, `enum`, and numeric
|
|
8
|
+
* bounds. Unknown keywords are ignored rather than rejected, so richer
|
|
9
|
+
* schemas still work (they are simply less strictly checked here).
|
|
10
|
+
*/
|
|
11
|
+
/** Validate a value against the declared JSON Schema subset. */
|
|
12
|
+
export function validateAgainstSchema(value, schema, path = "args") {
|
|
13
|
+
const errors = [];
|
|
14
|
+
if (!schema || typeof schema !== "object")
|
|
15
|
+
return { valid: true, errors };
|
|
16
|
+
const expectedType = schema.type;
|
|
17
|
+
if (typeof expectedType === "string") {
|
|
18
|
+
const actual = jsonType(value);
|
|
19
|
+
if (actual !== expectedType && !(expectedType === "integer" && actual === "number")) {
|
|
20
|
+
return { valid: false, errors: [`${path}: expected ${expectedType}, got ${actual}`] };
|
|
21
|
+
}
|
|
22
|
+
if (expectedType === "integer" && typeof value === "number" && !Number.isInteger(value)) {
|
|
23
|
+
return { valid: false, errors: [`${path}: expected integer`] };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (Array.isArray(schema.enum) && !schema.enum.some((option) => option === value)) {
|
|
27
|
+
errors.push(`${path}: must be one of ${JSON.stringify(schema.enum)}`);
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "number") {
|
|
30
|
+
if (typeof schema.minimum === "number" && value < schema.minimum) {
|
|
31
|
+
errors.push(`${path}: must be >= ${schema.minimum}`);
|
|
32
|
+
}
|
|
33
|
+
if (typeof schema.maximum === "number" && value > schema.maximum) {
|
|
34
|
+
errors.push(`${path}: must be <= ${schema.maximum}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (expectedType === "object" && isRecord(value)) {
|
|
38
|
+
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
39
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
40
|
+
for (const key of required) {
|
|
41
|
+
if (!(key in value))
|
|
42
|
+
errors.push(`${path}.${key}: required`);
|
|
43
|
+
}
|
|
44
|
+
for (const [key, child] of Object.entries(properties)) {
|
|
45
|
+
if (key in value) {
|
|
46
|
+
const result = validateAgainstSchema(value[key], isRecord(child) ? child : undefined, `${path}.${key}`);
|
|
47
|
+
errors.push(...result.errors);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (schema.additionalProperties === false) {
|
|
51
|
+
for (const key of Object.keys(value)) {
|
|
52
|
+
if (!(key in properties))
|
|
53
|
+
errors.push(`${path}.${key}: additional property not allowed`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (expectedType === "array" && Array.isArray(value) && isRecord(schema.items)) {
|
|
58
|
+
value.forEach((item, index) => {
|
|
59
|
+
errors.push(...validateAgainstSchema(item, schema.items, `${path}[${index}]`).errors);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return { valid: errors.length === 0, errors };
|
|
63
|
+
}
|
|
64
|
+
function jsonType(value) {
|
|
65
|
+
if (value === null)
|
|
66
|
+
return "null";
|
|
67
|
+
if (Array.isArray(value))
|
|
68
|
+
return "array";
|
|
69
|
+
if (typeof value === "number")
|
|
70
|
+
return "number";
|
|
71
|
+
if (typeof value === "object")
|
|
72
|
+
return "object";
|
|
73
|
+
return typeof value;
|
|
74
|
+
}
|
|
75
|
+
function isRecord(value) {
|
|
76
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
77
|
+
}
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* - Cancellation via AbortSignal
|
|
12
12
|
*/
|
|
13
13
|
import { ToolPolicy } from "../../security/tool-policy.js";
|
|
14
|
+
import { validateAgainstSchema } from "./schema-validator.js";
|
|
14
15
|
function defaultCostEstimator(usage, model) {
|
|
15
16
|
// Rough cost estimates per 1M tokens
|
|
16
17
|
const pricing = {
|
|
@@ -181,6 +182,22 @@ export class ToolLoopAgent {
|
|
|
181
182
|
}
|
|
182
183
|
onEvent?.({ type: "approval_granted", step: stepNum, tool: tc.name });
|
|
183
184
|
}
|
|
185
|
+
// v4.0.0: enforce the tool's declared JSON Schema before execution.
|
|
186
|
+
// Malformed model-generated arguments are recorded as a tool error
|
|
187
|
+
// rather than being passed to the tool implementation.
|
|
188
|
+
const validation = validateAgainstSchema(tc.arguments, tool.parameters);
|
|
189
|
+
if (!validation.valid) {
|
|
190
|
+
const message = `Invalid arguments for tool "${tc.name}": ${validation.errors.join("; ")}`;
|
|
191
|
+
stepToolCalls.push({
|
|
192
|
+
name: tc.name,
|
|
193
|
+
args: tc.arguments,
|
|
194
|
+
result: null,
|
|
195
|
+
error: message,
|
|
196
|
+
approved,
|
|
197
|
+
});
|
|
198
|
+
onEvent?.({ type: "error", error: new Error(message) });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
184
201
|
onEvent?.({ type: "tool_call", step: stepNum, tool: tc.name, args: tc.arguments });
|
|
185
202
|
const toolContext = {
|
|
186
203
|
step: stepNum,
|
|
@@ -27,7 +27,10 @@ export function createChatHandler(options) {
|
|
|
27
27
|
apiKey: options.apiKey,
|
|
28
28
|
});
|
|
29
29
|
const limits = resolveLimits(options.limits);
|
|
30
|
-
|
|
30
|
+
// v4.0.0: secure default. A public route handler must not let a caller
|
|
31
|
+
// override the configured model, tools, sampling limits or step count
|
|
32
|
+
// unless the developer explicitly opts in.
|
|
33
|
+
const trustClientFields = options.trustClientFields ?? false;
|
|
31
34
|
async function POST(req) {
|
|
32
35
|
try {
|
|
33
36
|
const body = await readJsonBody(req, limits);
|
|
@@ -111,7 +114,10 @@ export function createCompletionHandler(options) {
|
|
|
111
114
|
apiKey: options.apiKey,
|
|
112
115
|
});
|
|
113
116
|
const limits = resolveLimits(options.limits);
|
|
114
|
-
|
|
117
|
+
// v4.0.0: secure default. A public route handler must not let a caller
|
|
118
|
+
// override the configured model, tools, sampling limits or step count
|
|
119
|
+
// unless the developer explicitly opts in.
|
|
120
|
+
const trustClientFields = options.trustClientFields ?? false;
|
|
115
121
|
async function POST(req) {
|
|
116
122
|
try {
|
|
117
123
|
const body = await readJsonBody(req, limits);
|
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";
|
|
@@ -97,6 +99,8 @@ export type { RateLimiterConfig, ThrottleInfo, RateLimiterStats } from "./securi
|
|
|
97
99
|
export { detectInjection, scanMessages, createInjectionGuard, INJECTION_PATTERNS, } from "./security/prompt-injection-guard.js";
|
|
98
100
|
export type { InjectionDetection, InjectionMatch, InjectionGuardConfig, } from "./security/prompt-injection-guard.js";
|
|
99
101
|
export { validateResolvedAddress, normalizeHostname, validateUrlForTransport, } from "./security/url-guard.js";
|
|
102
|
+
export { validateResolvedHostname } from "./security/dns-guard.js";
|
|
103
|
+
export type { DnsValidationResult } from "./security/dns-guard.js";
|
|
100
104
|
export { OidcCredentialProvider, OidcError, oidcSource } from "./credentials/oidc.js";
|
|
101
105
|
export type { OidcConfig } from "./credentials/oidc.js";
|
|
102
106
|
export type { UIMessage, UIToolInvocation, DataAnnotation, UIProtocolMessage, UseChatOptions, UseChatState, UseChatActions, UseCompletionOptions, UseCompletionState, UseCompletionActions, } from "./types/ui-protocol.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";
|
|
@@ -71,6 +72,8 @@ export { RateLimiter, createRateLimiter, RateLimiterRegistry } from "./security/
|
|
|
71
72
|
export { detectInjection, scanMessages, createInjectionGuard, INJECTION_PATTERNS, } from "./security/prompt-injection-guard.js";
|
|
72
73
|
// ─── Security: Enhanced SSRF ─────────────────────────────────────────────────
|
|
73
74
|
export { validateResolvedAddress, normalizeHostname, validateUrlForTransport, } from "./security/url-guard.js";
|
|
75
|
+
// v4.0.0: opt-in DNS-resolution SSRF preflight.
|
|
76
|
+
export { validateResolvedHostname } from "./security/dns-guard.js";
|
|
74
77
|
// ─── OIDC Credentials ───────────────────────────────────────────────────────
|
|
75
78
|
export { OidcCredentialProvider, OidcError, oidcSource } from "./credentials/oidc.js";
|
|
76
79
|
// ─── Catalog ────────────────────────────────────────────────────────────────
|
|
@@ -7,8 +7,20 @@ import type { ProviderConfig } from "../types/providers.js";
|
|
|
7
7
|
import type { Model } from "../types/models.js";
|
|
8
8
|
export declare class ProviderRegistry {
|
|
9
9
|
private _providers;
|
|
10
|
+
/**
|
|
11
|
+
* Resolve a registered provider name case-insensitively.
|
|
12
|
+
*
|
|
13
|
+
* Provider names are canonical PascalCase in the catalog ("OpenAI",
|
|
14
|
+
* "Anthropic"), but requests routinely use the catalog id form ("openai").
|
|
15
|
+
* Matching both spellings avoids a confusing "Provider 'openai' not found"
|
|
16
|
+
* immediately after `addProviderFromCatalog("openai", ...)`.
|
|
17
|
+
* Exact matches win when two entries differ only by case.
|
|
18
|
+
*/
|
|
19
|
+
private _resolveKey;
|
|
10
20
|
add(config: ProviderConfig): void;
|
|
11
21
|
remove(name: string): boolean;
|
|
22
|
+
/** Return the canonical registered name for a case-insensitive lookup. */
|
|
23
|
+
canonicalName(name: string): string | undefined;
|
|
12
24
|
get(name: string): ProviderConfig | undefined;
|
|
13
25
|
getOrThrow(name: string): ProviderConfig;
|
|
14
26
|
list(): ProviderConfig[];
|
|
@@ -7,21 +7,46 @@ import { cloneProviderConfig } from "../config/provider-config.js";
|
|
|
7
7
|
import { ProviderNotFoundError } from "../errors/index.js";
|
|
8
8
|
export class ProviderRegistry {
|
|
9
9
|
_providers = new Map();
|
|
10
|
+
/**
|
|
11
|
+
* Resolve a registered provider name case-insensitively.
|
|
12
|
+
*
|
|
13
|
+
* Provider names are canonical PascalCase in the catalog ("OpenAI",
|
|
14
|
+
* "Anthropic"), but requests routinely use the catalog id form ("openai").
|
|
15
|
+
* Matching both spellings avoids a confusing "Provider 'openai' not found"
|
|
16
|
+
* immediately after `addProviderFromCatalog("openai", ...)`.
|
|
17
|
+
* Exact matches win when two entries differ only by case.
|
|
18
|
+
*/
|
|
19
|
+
_resolveKey(name) {
|
|
20
|
+
if (this._providers.has(name))
|
|
21
|
+
return name;
|
|
22
|
+
const lowered = name.toLowerCase();
|
|
23
|
+
for (const key of this._providers.keys()) {
|
|
24
|
+
if (key.toLowerCase() === lowered)
|
|
25
|
+
return key;
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
10
29
|
add(config) {
|
|
11
30
|
this._providers.set(config.name, cloneProviderConfig(config));
|
|
12
31
|
}
|
|
13
32
|
remove(name) {
|
|
14
|
-
|
|
33
|
+
const key = this._resolveKey(name);
|
|
34
|
+
return key === undefined ? false : this._providers.delete(key);
|
|
35
|
+
}
|
|
36
|
+
/** Return the canonical registered name for a case-insensitive lookup. */
|
|
37
|
+
canonicalName(name) {
|
|
38
|
+
return this._resolveKey(name);
|
|
15
39
|
}
|
|
16
40
|
get(name) {
|
|
17
|
-
const
|
|
41
|
+
const key = this._resolveKey(name);
|
|
42
|
+
const config = key === undefined ? undefined : this._providers.get(key);
|
|
18
43
|
return config ? cloneProviderConfig(config) : undefined;
|
|
19
44
|
}
|
|
20
45
|
getOrThrow(name) {
|
|
21
|
-
const config = this.
|
|
46
|
+
const config = this.get(name);
|
|
22
47
|
if (!config)
|
|
23
48
|
throw new ProviderNotFoundError(name, this.list().map((c) => c.name));
|
|
24
|
-
return
|
|
49
|
+
return config;
|
|
25
50
|
}
|
|
26
51
|
list() {
|
|
27
52
|
return [...this._providers.values()].map(cloneProviderConfig);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — opt-in DNS-resolution SSRF guard (v4.0.0)
|
|
3
|
+
*
|
|
4
|
+
* `validateBaseUrl()` checks the URL string. A hostname can still resolve to
|
|
5
|
+
* a private/link-local address at request time (DNS rebinding). This module
|
|
6
|
+
* adds an opt-in preflight: resolve the hostname and validate every returned
|
|
7
|
+
* address with `validateResolvedAddress()` before registering the provider.
|
|
8
|
+
*
|
|
9
|
+
* The `node:dns` import is dynamic so that importing this module in a browser
|
|
10
|
+
* or edge bundle does not pull in a Node builtin. It is only loaded when the
|
|
11
|
+
* caller actually opts into the strict check.
|
|
12
|
+
*/
|
|
13
|
+
import type { UrlGuardOptions } from "./url-guard.js";
|
|
14
|
+
export interface DnsValidationResult {
|
|
15
|
+
ok: boolean;
|
|
16
|
+
addresses: string[];
|
|
17
|
+
blocked?: string[];
|
|
18
|
+
reason?: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Resolve `hostname` and reject if ANY resolved address is disallowed.
|
|
22
|
+
*
|
|
23
|
+
* Checking every answer (not just the first) prevents an attacker from
|
|
24
|
+
* publishing one public A record and one private AAAA record and hoping the
|
|
25
|
+
* runtime picks the safe one.
|
|
26
|
+
*/
|
|
27
|
+
export declare function validateResolvedHostname(hostname: string, _options?: UrlGuardOptions): Promise<DnsValidationResult>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — opt-in DNS-resolution SSRF guard (v4.0.0)
|
|
3
|
+
*
|
|
4
|
+
* `validateBaseUrl()` checks the URL string. A hostname can still resolve to
|
|
5
|
+
* a private/link-local address at request time (DNS rebinding). This module
|
|
6
|
+
* adds an opt-in preflight: resolve the hostname and validate every returned
|
|
7
|
+
* address with `validateResolvedAddress()` before registering the provider.
|
|
8
|
+
*
|
|
9
|
+
* The `node:dns` import is dynamic so that importing this module in a browser
|
|
10
|
+
* or edge bundle does not pull in a Node builtin. It is only loaded when the
|
|
11
|
+
* caller actually opts into the strict check.
|
|
12
|
+
*/
|
|
13
|
+
import { validateResolvedAddress } from "./url-guard.js";
|
|
14
|
+
/**
|
|
15
|
+
* Resolve `hostname` and reject if ANY resolved address is disallowed.
|
|
16
|
+
*
|
|
17
|
+
* Checking every answer (not just the first) prevents an attacker from
|
|
18
|
+
* publishing one public A record and one private AAAA record and hoping the
|
|
19
|
+
* runtime picks the safe one.
|
|
20
|
+
*/
|
|
21
|
+
export async function validateResolvedHostname(hostname, _options = {}) {
|
|
22
|
+
let lookup;
|
|
23
|
+
try {
|
|
24
|
+
// Dynamic import keeps the Node builtin out of browser bundles.
|
|
25
|
+
const dns = await import("node:dns/promises");
|
|
26
|
+
lookup = dns.lookup;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return {
|
|
30
|
+
ok: false,
|
|
31
|
+
addresses: [],
|
|
32
|
+
reason: "DNS resolution is not available in this runtime",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
let records;
|
|
36
|
+
try {
|
|
37
|
+
records = await lookup(hostname, { all: true });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
return {
|
|
41
|
+
ok: false,
|
|
42
|
+
addresses: [],
|
|
43
|
+
reason: `DNS resolution failed for '${hostname}': ${error instanceof Error ? error.message : String(error)}`,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
const addresses = records.map((record) => record.address);
|
|
47
|
+
const blocked = [];
|
|
48
|
+
for (const address of addresses) {
|
|
49
|
+
const result = validateResolvedAddress(address);
|
|
50
|
+
if (!result.ok)
|
|
51
|
+
blocked.push(address);
|
|
52
|
+
}
|
|
53
|
+
if (blocked.length > 0) {
|
|
54
|
+
return {
|
|
55
|
+
ok: false,
|
|
56
|
+
addresses,
|
|
57
|
+
blocked,
|
|
58
|
+
reason: `Hostname '${hostname}' resolves to a disallowed address: ${blocked.join(", ")}`,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return { ok: true, addresses };
|
|
62
|
+
}
|
|
@@ -6,17 +6,22 @@
|
|
|
6
6
|
*
|
|
7
7
|
* ## Signature profiles
|
|
8
8
|
*
|
|
9
|
-
* - **`"
|
|
9
|
+
* - **`"v2"` (default since v4.0.0).** The body digest, the key id, and a
|
|
10
|
+
* per-request nonce are all bound into the canonical string.
|
|
11
|
+
* - **`"v1"` (opt-in, deprecated).** The pre-v3.4.0 wire format, frozen so
|
|
10
12
|
* existing verifiers keep working. Its canonical string covers the method,
|
|
11
13
|
* path, and the headers named in `config.headers`. The body digest is emitted
|
|
12
14
|
* as `x-content-sha256` but is **not** part of that canonical string, so a
|
|
13
15
|
* `v1` signature does not authenticate the body. `verify()` trusts a received
|
|
14
|
-
* digest header when `config.headers` names it.
|
|
15
|
-
* integrations.
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
16
|
+
* digest header when `config.headers` names it. Set `profile: "v1"` explicitly
|
|
17
|
+
* to interoperate with an existing verifier; do not use it for new integrations.
|
|
18
|
+
* `verify()` recomputes the digest from the received bytes and never trusts a
|
|
19
|
+
* received digest header, and a mismatched `x-hilbras-key-id` fails verification.
|
|
20
|
+
*
|
|
21
|
+
* The signer uses WebCrypto (`crypto.subtle`) when available and falls back to
|
|
22
|
+
* `node:crypto` otherwise, so it works in browsers, edge runtimes, Bun and
|
|
23
|
+
* Deno as well as Node. `signAsync()` is the recommended API; sync `sign()`
|
|
24
|
+
* remains available where a WebCrypto fallback is not needed.
|
|
20
25
|
*
|
|
21
26
|
* Neither profile provides replay protection. Pair either with
|
|
22
27
|
* {@link ReplayGuard}, or use `RequestSigner.verifyFresh()` which composes
|
|
@@ -91,6 +96,22 @@ export declare class RequestSigner {
|
|
|
91
96
|
/** Build the canonical string that the HMAC covers. */
|
|
92
97
|
private _canonical;
|
|
93
98
|
private _hmac;
|
|
99
|
+
/**
|
|
100
|
+
* Async signing path backed by WebCrypto (`crypto.subtle`) when available,
|
|
101
|
+
* falling back to the sync Node implementation. This produces byte-for-byte
|
|
102
|
+
* the same signature as `sign()` and is the recommended API for code that
|
|
103
|
+
* must also run in browsers, edge workers, Bun or Deno.
|
|
104
|
+
*/
|
|
105
|
+
signAsync(url: string, request: {
|
|
106
|
+
method?: string;
|
|
107
|
+
body?: SignableBody | FormData;
|
|
108
|
+
headers?: Record<string, string>;
|
|
109
|
+
timestamp?: string;
|
|
110
|
+
nonce?: string;
|
|
111
|
+
}): Promise<SignedRequest>;
|
|
112
|
+
private _digestAsync;
|
|
113
|
+
private _hmacAsync;
|
|
114
|
+
private _hmacBytesAsync;
|
|
94
115
|
/**
|
|
95
116
|
* Sign a request. Returns headers to add to the outgoing request.
|
|
96
117
|
*
|
|
@@ -6,17 +6,22 @@
|
|
|
6
6
|
*
|
|
7
7
|
* ## Signature profiles
|
|
8
8
|
*
|
|
9
|
-
* - **`"
|
|
9
|
+
* - **`"v2"` (default since v4.0.0).** The body digest, the key id, and a
|
|
10
|
+
* per-request nonce are all bound into the canonical string.
|
|
11
|
+
* - **`"v1"` (opt-in, deprecated).** The pre-v3.4.0 wire format, frozen so
|
|
10
12
|
* existing verifiers keep working. Its canonical string covers the method,
|
|
11
13
|
* path, and the headers named in `config.headers`. The body digest is emitted
|
|
12
14
|
* as `x-content-sha256` but is **not** part of that canonical string, so a
|
|
13
15
|
* `v1` signature does not authenticate the body. `verify()` trusts a received
|
|
14
|
-
* digest header when `config.headers` names it.
|
|
15
|
-
* integrations.
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
16
|
+
* digest header when `config.headers` names it. Set `profile: "v1"` explicitly
|
|
17
|
+
* to interoperate with an existing verifier; do not use it for new integrations.
|
|
18
|
+
* `verify()` recomputes the digest from the received bytes and never trusts a
|
|
19
|
+
* received digest header, and a mismatched `x-hilbras-key-id` fails verification.
|
|
20
|
+
*
|
|
21
|
+
* The signer uses WebCrypto (`crypto.subtle`) when available and falls back to
|
|
22
|
+
* `node:crypto` otherwise, so it works in browsers, edge runtimes, Bun and
|
|
23
|
+
* Deno as well as Node. `signAsync()` is the recommended API; sync `sign()`
|
|
24
|
+
* remains available where a WebCrypto fallback is not needed.
|
|
20
25
|
*
|
|
21
26
|
* Neither profile provides replay protection. Pair either with
|
|
22
27
|
* {@link ReplayGuard}, or use `RequestSigner.verifyFresh()` which composes
|
|
@@ -66,7 +71,9 @@ export class RequestSigner {
|
|
|
66
71
|
signatureHeader: config.signatureHeader ?? "x-hilbras-signature",
|
|
67
72
|
keyIdHeader: config.keyIdHeader ?? "x-hilbras-key-id",
|
|
68
73
|
algorithm: config.algorithm ?? "sha256",
|
|
69
|
-
|
|
74
|
+
// v4.0.0: the secure profile is the default. v1 remains available for
|
|
75
|
+
// consumers that need to interoperate with the frozen wire format.
|
|
76
|
+
profile: config.profile ?? "v2",
|
|
70
77
|
nonceHeader: (config.nonceHeader ?? "x-hilbras-nonce").toLowerCase(),
|
|
71
78
|
contentDigestHeader: (config.contentDigestHeader ?? "x-hilbras-content-digest").toLowerCase(),
|
|
72
79
|
now: config.now ?? (() => Date.now()),
|
|
@@ -113,6 +120,68 @@ export class RequestSigner {
|
|
|
113
120
|
.update(signingString)
|
|
114
121
|
.digest("hex");
|
|
115
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Async signing path backed by WebCrypto (`crypto.subtle`) when available,
|
|
125
|
+
* falling back to the sync Node implementation. This produces byte-for-byte
|
|
126
|
+
* the same signature as `sign()` and is the recommended API for code that
|
|
127
|
+
* must also run in browsers, edge workers, Bun or Deno.
|
|
128
|
+
*/
|
|
129
|
+
async signAsync(url, request) {
|
|
130
|
+
const webcrypto = globalThis.crypto;
|
|
131
|
+
if (!webcrypto?.subtle)
|
|
132
|
+
return this.sign(url, request);
|
|
133
|
+
const method = (request.method ?? "GET").toUpperCase();
|
|
134
|
+
const timestamp = request.timestamp ?? new Date(this._config.now()).toUTCString();
|
|
135
|
+
const parsed = new URL(url);
|
|
136
|
+
const path = parsed.pathname + parsed.search;
|
|
137
|
+
const hdrs = {};
|
|
138
|
+
for (const [key, value] of Object.entries(request.headers ?? {})) {
|
|
139
|
+
if (value !== undefined)
|
|
140
|
+
hdrs[key.toLowerCase()] = value;
|
|
141
|
+
}
|
|
142
|
+
hdrs.date = timestamp;
|
|
143
|
+
const signable = isByteBody(request.body) ? request.body : undefined;
|
|
144
|
+
const digest = signable !== undefined ? await this._digestAsync(signable, webcrypto.subtle) : undefined;
|
|
145
|
+
let nonce;
|
|
146
|
+
if (this._config.profile === "v2") {
|
|
147
|
+
nonce = request.nonce ?? this._config.nonce();
|
|
148
|
+
hdrs[this._config.nonceHeader] = nonce;
|
|
149
|
+
if (digest !== undefined)
|
|
150
|
+
hdrs[this._config.contentDigestHeader] = digest;
|
|
151
|
+
}
|
|
152
|
+
else if (digest !== undefined) {
|
|
153
|
+
hdrs["x-content-sha256"] = digest;
|
|
154
|
+
}
|
|
155
|
+
const signingString = this._canonical({ method, path, headers: hdrs, digest, nonce });
|
|
156
|
+
const signature = await this._hmacAsync(signingString, webcrypto.subtle);
|
|
157
|
+
const signedHeaderKeys = [...this._config.headers].sort().join(" ");
|
|
158
|
+
const signatureInput = `keyId="${this._config.keyId}",algorithm="${this._config.algorithm}",` +
|
|
159
|
+
`headers="${signedHeaderKeys}",profile="${this._config.profile}",signature="${signature}"`;
|
|
160
|
+
const outHeaders = { ...hdrs };
|
|
161
|
+
outHeaders[this._config.signatureHeader] = signature;
|
|
162
|
+
if (this._config.keyId)
|
|
163
|
+
outHeaders[this._config.keyIdHeader] = this._config.keyId;
|
|
164
|
+
return { headers: outHeaders, signature, signatureInput };
|
|
165
|
+
}
|
|
166
|
+
async _digestAsync(body, subtle) {
|
|
167
|
+
const bytes = typeof body === "string" ? new TextEncoder().encode(body) : new Uint8Array(body);
|
|
168
|
+
return this._hmacBytesAsync(bytes, subtle);
|
|
169
|
+
}
|
|
170
|
+
async _hmacAsync(signingString, subtle) {
|
|
171
|
+
return this._hmacBytesAsync(new TextEncoder().encode(signingString), subtle);
|
|
172
|
+
}
|
|
173
|
+
async _hmacBytesAsync(bytes, subtle) {
|
|
174
|
+
// Node's algorithm names are lower-case without a dash ("sha256");
|
|
175
|
+
// WebCrypto expects "SHA-256". Accept both spellings.
|
|
176
|
+
const normalized = /^sha\d+$/i.test(this._config.algorithm)
|
|
177
|
+
? this._config.algorithm.toUpperCase().replace(/^SHA(\d+)$/, "SHA-$1")
|
|
178
|
+
: this._config.algorithm.toUpperCase();
|
|
179
|
+
const key = await subtle.importKey("raw", new TextEncoder().encode(this._config.secret), { name: "HMAC", hash: normalized }, false, ["sign"]);
|
|
180
|
+
const signature = await subtle.sign("HMAC", key, bytes);
|
|
181
|
+
return Array.from(new Uint8Array(signature))
|
|
182
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
183
|
+
.join("");
|
|
184
|
+
}
|
|
116
185
|
/**
|
|
117
186
|
* Sign a request. Returns headers to add to the outgoing request.
|
|
118
187
|
*
|
|
@@ -135,6 +135,36 @@ function isMulticastIPv4(normalized) {
|
|
|
135
135
|
function isUnspecifiedIPv4(normalized) {
|
|
136
136
|
return normalized === "0.0.0.0";
|
|
137
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Expand an inet_aton-style abbreviated IPv4 tail inside an IPv6 literal.
|
|
140
|
+
*
|
|
141
|
+
* `::ffff:127.1` is a valid textual spelling of `::ffff:127.0.0.1`, but a
|
|
142
|
+
* strict four-octet parser rejects it. Expanding the tail here closes that
|
|
143
|
+
* bypass while leaving ordinary IPv6 input untouched.
|
|
144
|
+
*/
|
|
145
|
+
function expandAbbreviatedIPv4Tail(host) {
|
|
146
|
+
const colon = host.lastIndexOf(":");
|
|
147
|
+
if (colon < 0)
|
|
148
|
+
return host;
|
|
149
|
+
const tail = host.slice(colon + 1);
|
|
150
|
+
if (!tail.includes("."))
|
|
151
|
+
return host;
|
|
152
|
+
const parts = tail.split(".");
|
|
153
|
+
if (parts.length >= 4 || !parts.every((part) => /^\d{1,3}$/.test(part)))
|
|
154
|
+
return host;
|
|
155
|
+
const nums = parts.map(Number);
|
|
156
|
+
if (nums.some((part) => part > 255))
|
|
157
|
+
return host;
|
|
158
|
+
let value;
|
|
159
|
+
if (parts.length === 1)
|
|
160
|
+
value = nums[0];
|
|
161
|
+
else if (parts.length === 2)
|
|
162
|
+
value = (nums[0] << 24) | nums[1];
|
|
163
|
+
else
|
|
164
|
+
value = (nums[0] << 24) | (nums[1] << 16) | nums[2];
|
|
165
|
+
const dotted = `${(value >>> 24) & 0xff}.${(value >>> 16) & 0xff}.${(value >>> 8) & 0xff}.${value & 0xff}`;
|
|
166
|
+
return host.slice(0, colon + 1) + dotted;
|
|
167
|
+
}
|
|
138
168
|
/** Parse an IPv6 literal into eight 16-bit groups. */
|
|
139
169
|
function parseIPv6(value) {
|
|
140
170
|
let host = value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
|
|
@@ -142,6 +172,7 @@ function parseIPv6(value) {
|
|
|
142
172
|
host = host.split("%")[0];
|
|
143
173
|
if (!host.includes(":"))
|
|
144
174
|
return null;
|
|
175
|
+
host = expandAbbreviatedIPv4Tail(host);
|
|
145
176
|
const doubleColon = host.indexOf("::");
|
|
146
177
|
if (doubleColon !== host.lastIndexOf("::"))
|
|
147
178
|
return null;
|
|
@@ -192,8 +223,59 @@ function isLoopbackIPv6(groups) {
|
|
|
192
223
|
return groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1;
|
|
193
224
|
}
|
|
194
225
|
/**
|
|
195
|
-
*
|
|
196
|
-
*
|
|
226
|
+
* Extract an embedded IPv4 address from translation-prefix IPv6 forms.
|
|
227
|
+
*
|
|
228
|
+
* Three RFC-defined prefixes carry an IPv4 address in their low 32 bits:
|
|
229
|
+
*
|
|
230
|
+
* ::ffff:0:0/96 SIIT / IPv4-translated (RFC 6052 §2.1) e.g. ::ffff:0:127.0.0.1
|
|
231
|
+
* ::ffff:0:0/96 IPv4-mapped (RFC 4291) e.g. ::ffff:127.0.0.1
|
|
232
|
+
* 64:ff9b::/96 NAT64 well-known prefix (RFC 6052 §2.2) e.g. 64:ff9b::a9fe:a9fe
|
|
233
|
+
*
|
|
234
|
+
* Without decoding these, a literal such as `64:ff9b::a9fe:a9fe` (cloud
|
|
235
|
+
* metadata 169.254.169.254) passes the string-level guard, and a resolver
|
|
236
|
+
* returning `::ffff:0:127.0.0.1` passes the resolved-address guard.
|
|
237
|
+
*/
|
|
238
|
+
function embeddedIPv4FromIPv6(groups) {
|
|
239
|
+
const high = groups.slice(0, 5);
|
|
240
|
+
// IPv4-mapped (::ffff:a.b.c.d) and SIIT-translated (::ffff:0:a.b.c.d).
|
|
241
|
+
// `::ffff:127.1` is already expanded by expandAbbreviatedIPv4Tail().
|
|
242
|
+
if (high.every((group) => group === 0) && groups[5] === 0xffff) {
|
|
243
|
+
return `${(groups[6] >> 8) & 0xff}.${groups[6] & 0xff}.${(groups[7] >> 8) & 0xff}.${groups[7] & 0xff}`;
|
|
244
|
+
}
|
|
245
|
+
// SIIT / IPv4-translated prefix ::ffff:0:0:0/96 (RFC 6052 §2.1, RFC 6145):
|
|
246
|
+
// groups[0..3] === 0, groups[4] === 0xffff, groups[5] === 0, IPv4 in 6..7.
|
|
247
|
+
// Note the `ffff` is one group earlier than in the IPv4-mapped form above.
|
|
248
|
+
if (groups.slice(0, 4).every((group) => group === 0) &&
|
|
249
|
+
groups[4] === 0xffff &&
|
|
250
|
+
groups[5] === 0 &&
|
|
251
|
+
(groups[6] !== 0 || groups[7] !== 0)) {
|
|
252
|
+
return `${(groups[6] >> 8) & 0xff}.${groups[6] & 0xff}.${(groups[7] >> 8) & 0xff}.${groups[7] & 0xff}`;
|
|
253
|
+
}
|
|
254
|
+
// Generic IPv4-embedded addresses in the "low groups" position (the
|
|
255
|
+
// ::ffff:0:a.b.c.d spelling without the ffff group) — covered by the
|
|
256
|
+
// IPv4-compatible branch below as well, but be explicit here.
|
|
257
|
+
if (high.every((group) => group === 0) && groups[5] === 0 && (groups[6] !== 0 || groups[7] !== 0)) {
|
|
258
|
+
return `${(groups[6] >> 8) & 0xff}.${groups[6] & 0xff}.${(groups[7] >> 8) & 0xff}.${groups[7] & 0xff}`;
|
|
259
|
+
}
|
|
260
|
+
// NAT64 well-known prefix.
|
|
261
|
+
if (groups[0] === 0x64 &&
|
|
262
|
+
groups[1] === 0xff9b &&
|
|
263
|
+
high.slice(2).every((group) => group === 0) &&
|
|
264
|
+
groups[5] === 0) {
|
|
265
|
+
return `${(groups[6] >> 8) & 0xff}.${groups[6] & 0xff}.${(groups[7] >> 8) & 0xff}.${groups[7] & 0xff}`;
|
|
266
|
+
}
|
|
267
|
+
// IPv4-compatible (deprecated but still parsed by some stacks): ::a.b.c.d,
|
|
268
|
+
// excluding :: and ::1 which are handled as special cases above.
|
|
269
|
+
if (high.every((group) => group === 0) && groups[5] === 0) {
|
|
270
|
+
return `${(groups[6] >> 8) & 0xff}.${groups[6] & 0xff}.${(groups[7] >> 8) & 0xff}.${groups[7] & 0xff}`;
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Check if an IPv6 address is :: (unspecified), loopback, an IPv4-mapped /
|
|
276
|
+
* IPv4-translated / NAT64 address carrying a forbidden IPv4 address, or an
|
|
277
|
+
* IPv4-compatible address. Mapped/translated addresses must be checked as
|
|
278
|
+
* IPv4 against the same private/link-local ranges as plain IPv4 literals.
|
|
197
279
|
*/
|
|
198
280
|
function isSpecialIPv6(normalized) {
|
|
199
281
|
const groups = parseIPv6(normalized);
|
|
@@ -203,9 +285,22 @@ function isSpecialIPv6(normalized) {
|
|
|
203
285
|
return true;
|
|
204
286
|
if (isLoopbackIPv6(groups))
|
|
205
287
|
return true;
|
|
206
|
-
const
|
|
288
|
+
const embedded = embeddedIPv4FromIPv6(groups);
|
|
289
|
+
if (embedded) {
|
|
290
|
+
if (isUnspecifiedIPv4(embedded) ||
|
|
291
|
+
isLoopbackIPv4(embedded) ||
|
|
292
|
+
isLinkLocalIPv4(embedded) ||
|
|
293
|
+
isCgnatIPv4(embedded) ||
|
|
294
|
+
isBenchmarkingIPv4(embedded) ||
|
|
295
|
+
isMulticastIPv4(embedded) ||
|
|
296
|
+
isPrivateIPv4(embedded)) {
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
// IPv4-compatible addresses (::a.b.c.d) were historically interpreted as
|
|
301
|
+
// IPv4 by dual-stack implementations; treat all of them as special.
|
|
207
302
|
const compatible = groups.slice(0, 6).every((group) => group === 0) && groups[6] !== 0;
|
|
208
|
-
return
|
|
303
|
+
return compatible;
|
|
209
304
|
}
|
|
210
305
|
function isLinkLocalIPv6(normalized) {
|
|
211
306
|
const groups = parseIPv6(normalized);
|
|
@@ -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/dist/types/adapter.d.ts
CHANGED
|
@@ -29,6 +29,16 @@ export interface GenerateParams {
|
|
|
29
29
|
tools?: Tool[];
|
|
30
30
|
extra?: Record<string, unknown>;
|
|
31
31
|
signal?: AbortSignal;
|
|
32
|
+
/**
|
|
33
|
+
* Optional callback invoked with provider-reported token usage on a unary
|
|
34
|
+
* completion. The pipeline uses it to settle budgets against actual usage
|
|
35
|
+
* (F-07) rather than the pre-flight estimate. Adapters that receive no
|
|
36
|
+
* usage never call it.
|
|
37
|
+
*/
|
|
38
|
+
onUsage?: (usage: {
|
|
39
|
+
inputTokens?: number;
|
|
40
|
+
outputTokens?: number;
|
|
41
|
+
}) => void;
|
|
32
42
|
}
|
|
33
43
|
/**
|
|
34
44
|
* The universal provider contract. All adapters implement this.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hilbras/sdk",
|
|
3
|
-
"version": "
|
|
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",
|