@hilbras/sdk 3.3.0 → 3.4.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/README.md +45 -2
- package/dist/client/client.d.ts +21 -0
- package/dist/client/client.js +78 -5
- package/dist/config/config-resolver.js +14 -0
- package/dist/features/agent/tool-loop.d.ts +9 -0
- package/dist/features/agent/tool-loop.js +25 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +4 -0
- package/dist/middleware/middleware.d.ts +10 -0
- package/dist/middleware/middleware.js +15 -6
- package/dist/providers/registry.d.ts +9 -0
- package/dist/providers/registry.js +37 -0
- package/dist/security/authorization.d.ts +180 -0
- package/dist/security/authorization.js +355 -0
- package/dist/security/rate-limiter.d.ts +11 -0
- package/dist/security/rate-limiter.js +14 -0
- package/dist/security/rbac.d.ts +29 -41
- package/dist/security/rbac.js +172 -90
- package/dist/security/replay-guard.d.ts +51 -0
- package/dist/security/replay-guard.js +86 -0
- package/dist/security/request-signer.d.ts +88 -22
- package/dist/security/request-signer.js +185 -76
- package/dist/security/tool-policy.d.ts +53 -0
- package/dist/security/tool-policy.js +97 -0
- package/dist/transport/middleware-transport.js +9 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://img.shields.io/badge/version-3.
|
|
2
|
+
<img src="https://img.shields.io/badge/version-3.4.0-blue" alt="version">
|
|
3
3
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
|
4
4
|
<img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
|
|
5
5
|
<img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
|
|
6
|
-
<img src="https://img.shields.io/badge/tests-
|
|
6
|
+
<img src="https://img.shields.io/badge/tests-1797%20passing-brightgreen" alt="tests">
|
|
7
7
|
<img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
@@ -210,6 +210,7 @@ See [Configuration](docs/configuration.md) and the [v3.2 migration guide](docs/m
|
|
|
210
210
|
| **Reasoning normalization** | Detect & normalize `<thinking>` / `<reasoning>` tags and native fields | [API Reference](docs/api-reference.md) |
|
|
211
211
|
| **Per-client tokenizer** | Scoped BPE tokenizer per client instance — no global singletons | [API Reference](docs/api-reference.md) |
|
|
212
212
|
| **Configuration resolver** | Typed layered configuration with strict validation and redacted diagnostics | [Configuration](docs/configuration.md) |
|
|
213
|
+
| **Authorization enforcement** | RBAC that actually evaluates, enforced tool policy, body-bound request signing with replay protection | [Security](docs/security.md) |
|
|
213
214
|
| **Middleware pipeline** | Transport-level middleware: auth headers, logging, custom request/response transforms | [API Reference](docs/api-reference.md) |
|
|
214
215
|
| **Agent framework** | ToolLoopAgent, ReActAgent, PlanAndExecuteAgent with approval, budget, cost tracking | [Agent](docs/agent.md) |
|
|
215
216
|
| **Evaluation** | LLM output evaluation with built-in metrics (exact_match, similarity, toxicity) | [Eval](docs/eval.md) |
|
|
@@ -225,6 +226,48 @@ See [Configuration](docs/configuration.md) and the [v3.2 migration guide](docs/m
|
|
|
225
226
|
|
|
226
227
|
---
|
|
227
228
|
|
|
229
|
+
## What's New in v3.4.0
|
|
230
|
+
|
|
231
|
+
**Authorization now enforces.** `config.rbac` was accepted by the configuration
|
|
232
|
+
resolver but read by nothing, and even when the RBAC middleware was wired up
|
|
233
|
+
manually its permission check was unreachable: it read `provider` from the
|
|
234
|
+
request body, which no adapter sends. RBAC now resolves the provider from the
|
|
235
|
+
request URL, maps caller identity onto a role, and enforces the result. A
|
|
236
|
+
configured `rbac` block is enforced by the client automatically, and a malformed
|
|
237
|
+
policy is rejected at construction instead of degrading to "no restrictions".
|
|
238
|
+
|
|
239
|
+
**Tool policy is enforced.** `allowedTools` and `deniedTools` were declared,
|
|
240
|
+
overlap-checked, and then ignored. The client now rejects a request that names a
|
|
241
|
+
denied tool, and `ToolLoopAgent` refuses to execute one. See `getToolPolicy()`.
|
|
242
|
+
|
|
243
|
+
**Request signing binds the body.** The HMAC signature covered the method, path,
|
|
244
|
+
and configured headers, but not the request body: the body digest was emitted as
|
|
245
|
+
an unsigned header, and `verify()` trusted a received digest header rather than
|
|
246
|
+
recomputing it. The new `v2` profile binds the body, the key id, and a nonce,
|
|
247
|
+
and recomputes the digest from the received bytes. The `v1` wire format is
|
|
248
|
+
frozen and unchanged, so existing verifiers keep working.
|
|
249
|
+
|
|
250
|
+
**Replay protection.** `ReplayGuard` adds a signed-timestamp window and a
|
|
251
|
+
bounded seen-signature cache. `RequestSigner.verifyFresh()` composes the two.
|
|
252
|
+
|
|
253
|
+
**Middleware and transport fixes.** `composeMiddlewares` used a shared cursor
|
|
254
|
+
that permanently exhausted the chain, so any stage after a retry was skipped on
|
|
255
|
+
every later attempt — a signature computed at T0 was reused unchanged for
|
|
256
|
+
attempts 2..N. Composition now re-enters per attempt. Streaming a non-2xx
|
|
257
|
+
response now throws instead of yielding an empty stream, and signed requests no
|
|
258
|
+
longer emit both `Content-Type` and `content-type`.
|
|
259
|
+
|
|
260
|
+
**Compatibility.** No export is removed. `checkPermission`, `RBACRole`,
|
|
261
|
+
`RBACConfig`, `RequestSigner`, and `signingMiddleware` keep their signatures.
|
|
262
|
+
One intentional behavior change: a malformed `config.rbac` now fails at
|
|
263
|
+
construction. See the [v3.3 migration guide](docs/migration-from-v3.3.md).
|
|
264
|
+
|
|
265
|
+
**Audit.** All 20 audited findings, with a finding-to-test map in
|
|
266
|
+
[`HILBRAS-SDK-FULL-AUDIT.md`](HILBRAS-SDK-FULL-AUDIT.md) and
|
|
267
|
+
[`SPEC-v3.4.0-security.md`](SPEC-v3.4.0-security.md).
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
228
271
|
## What's New in v3.3.0
|
|
229
272
|
|
|
230
273
|
**Canonical configuration** — `resolveConfig()` now provides deterministic layered configuration with defaults, file sources, environment sources, and runtime/client values. The client resolves configuration once during construction.
|
package/dist/client/client.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ import type { EmbeddingResult, ImageResult, SpeechResult, TranscriptionResult, R
|
|
|
21
21
|
import type { ConfigDiagnostic, ConfigSource, SafeSDKConfig } from "../config/config-schema.js";
|
|
22
22
|
import { type ResolvedSDKConfig } from "../config/resolved-config.js";
|
|
23
23
|
import type { SDKConfig } from "../config/schema.js";
|
|
24
|
+
import type { AuthorizationDiagnostic } from "../security/authorization.js";
|
|
25
|
+
import { ToolPolicy } from "../security/tool-policy.js";
|
|
24
26
|
import { AdapterRegistry } from "../providers/adapter-registry.js";
|
|
25
27
|
import { ModelRouter } from "../router/model-router.js";
|
|
26
28
|
import type { StructuredLogger } from "../telemetry/structured-logger.js";
|
|
@@ -132,6 +134,8 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
132
134
|
private _plugins;
|
|
133
135
|
private _requestExecutor;
|
|
134
136
|
private _requestPipeline;
|
|
137
|
+
private _toolPolicy;
|
|
138
|
+
private _authorizationDiagnostics;
|
|
135
139
|
constructor(config?: HilbrasClientConfig);
|
|
136
140
|
/** Subscribe to lifecycle events. Returns an unsubscribe function. */
|
|
137
141
|
on<T extends HookEvent = HookEvent>(event: T["type"], listener: HookListener<T>): () => void;
|
|
@@ -172,6 +176,23 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
172
176
|
getConfigSnapshot(): SafeSDKConfig;
|
|
173
177
|
/** Return configuration diagnostics without secret values. */
|
|
174
178
|
getConfigDiagnostics(): ConfigDiagnostic[];
|
|
179
|
+
/**
|
|
180
|
+
* Return the enforced tool policy derived from `allowedTools` and
|
|
181
|
+
* `deniedTools`. Pass it to a `ToolLoopAgent` to make tool execution obey the
|
|
182
|
+
* same policy the client admits requests under.
|
|
183
|
+
*/
|
|
184
|
+
getToolPolicy(): ToolPolicy;
|
|
185
|
+
/**
|
|
186
|
+
* Return the redacted authorization decision log in decision order, bounded
|
|
187
|
+
* to the most recent entries. Empty when no `rbac` policy is configured.
|
|
188
|
+
*/
|
|
189
|
+
getAuthorizationDiagnostics(): AuthorizationDiagnostic[];
|
|
190
|
+
/**
|
|
191
|
+
* Throw when any of the supplied tool names is not permitted by the client's
|
|
192
|
+
* tool policy. Called on the request-admission path so a request that would
|
|
193
|
+
* use a denied tool fails before a provider call is made.
|
|
194
|
+
*/
|
|
195
|
+
private _assertToolsAllowed;
|
|
175
196
|
/**
|
|
176
197
|
* Add a provider from the built-in catalog with one line.
|
|
177
198
|
*
|
package/dist/client/client.js
CHANGED
|
@@ -13,6 +13,9 @@ import { RequestExecutor } from "../core/execution/request-executor.js";
|
|
|
13
13
|
import { RequestPipeline } from "../core/execution/request-pipeline.js";
|
|
14
14
|
import { resolveConfig } from "../config/config-resolver.js";
|
|
15
15
|
import { budgetFromConfig, policyFromConfig } from "../config/resolved-config.js";
|
|
16
|
+
import { createRBACMiddleware } from "../security/rbac.js";
|
|
17
|
+
import { ToolPolicy } from "../security/tool-policy.js";
|
|
18
|
+
import { composeMiddlewares } from "../middleware/middleware.js";
|
|
16
19
|
import { ProviderRegistry } from "../providers/registry.js";
|
|
17
20
|
import { cloneProviderConfig } from "../config/provider-config.js";
|
|
18
21
|
import { FetchTransport } from "../transport/fetch.js";
|
|
@@ -32,6 +35,11 @@ import { BudgetTracker } from "../cost/tracker.js";
|
|
|
32
35
|
import { estimateTokens } from "../tokens/counter.js";
|
|
33
36
|
import { getProviderCatalog, getModelsForProvider, listProviders } from "../catalog/index.js";
|
|
34
37
|
import { PluginRegistry } from "../plugin/registry.js";
|
|
38
|
+
/**
|
|
39
|
+
* Maximum number of authorization diagnostics retained per client. Older
|
|
40
|
+
* entries are dropped so a long-lived client cannot grow without bound.
|
|
41
|
+
*/
|
|
42
|
+
const AUTHORIZATION_DIAGNOSTIC_LIMIT = 200;
|
|
35
43
|
export class HilbrasClient {
|
|
36
44
|
_registry = new ProviderRegistry();
|
|
37
45
|
_transport;
|
|
@@ -49,12 +57,11 @@ export class HilbrasClient {
|
|
|
49
57
|
_plugins = new PluginRegistry();
|
|
50
58
|
_requestExecutor;
|
|
51
59
|
_requestPipeline;
|
|
60
|
+
_toolPolicy;
|
|
61
|
+
_authorizationDiagnostics = [];
|
|
52
62
|
constructor(config) {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (config?.middleware) {
|
|
56
|
-
this._transport = new MiddlewareTransport(this._transport, config.middleware);
|
|
57
|
-
}
|
|
63
|
+
const baseTransport = config?.transport ?? new FetchTransport();
|
|
64
|
+
this._transport = baseTransport;
|
|
58
65
|
this._adapterRegistry = config?.adapterRegistry ?? getDefaultAdapterRegistry();
|
|
59
66
|
this._router = new ModelRouter();
|
|
60
67
|
this._allowInsecureUrls = config?.allowInsecureUrls ?? false;
|
|
@@ -71,6 +78,37 @@ export class HilbrasClient {
|
|
|
71
78
|
this._defaultPolicy = config?.policy ?? policyFromConfig(resolvedSdk);
|
|
72
79
|
const sdkBudget = budgetFromConfig(resolvedSdk);
|
|
73
80
|
this._budgetTracker = new BudgetTracker(config?.budget ?? sdkBudget);
|
|
81
|
+
// v3.4.0: allowedTools / deniedTools become enforceable. They were part of
|
|
82
|
+
// the schema from the start but nothing consulted them.
|
|
83
|
+
this._toolPolicy = new ToolPolicy({
|
|
84
|
+
allowedTools: resolvedSdk.allowedTools,
|
|
85
|
+
deniedTools: resolvedSdk.deniedTools,
|
|
86
|
+
});
|
|
87
|
+
// v3.4.0: a configured `rbac` block is now live. Provider resolution is
|
|
88
|
+
// read lazily from the registry so providers added after construction are
|
|
89
|
+
// covered by the same policy.
|
|
90
|
+
const middlewareChain = [];
|
|
91
|
+
if (resolvedSdk.rbac) {
|
|
92
|
+
middlewareChain.push(createRBACMiddleware(resolvedSdk.rbac, () => null, {
|
|
93
|
+
resolveProviderByUrl: (url) => this._registry.findByUrl(url),
|
|
94
|
+
resolveBudget: () => ({ spent: this._budgetTracker.report().totalActual }),
|
|
95
|
+
onDiagnostic: (diagnostic) => {
|
|
96
|
+
this._authorizationDiagnostics.push(diagnostic);
|
|
97
|
+
if (this._authorizationDiagnostics.length > AUTHORIZATION_DIAGNOSTIC_LIMIT) {
|
|
98
|
+
this._authorizationDiagnostics.splice(0, this._authorizationDiagnostics.length - AUTHORIZATION_DIAGNOSTIC_LIMIT);
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
// v2.5.0: Wrap transport with middleware pipeline when provided
|
|
104
|
+
if (config?.middleware)
|
|
105
|
+
middlewareChain.push(config.middleware);
|
|
106
|
+
if (middlewareChain.length === 1) {
|
|
107
|
+
this._transport = new MiddlewareTransport(baseTransport, middlewareChain[0]);
|
|
108
|
+
}
|
|
109
|
+
else if (middlewareChain.length > 1) {
|
|
110
|
+
this._transport = new MiddlewareTransport(baseTransport, composeMiddlewares(...middlewareChain));
|
|
111
|
+
}
|
|
74
112
|
this._requestExecutor = new RequestExecutor({
|
|
75
113
|
policy: {
|
|
76
114
|
resolve: (policy) => resolvePolicy(policy ?? this._defaultPolicy),
|
|
@@ -198,6 +236,33 @@ export class HilbrasClient {
|
|
|
198
236
|
getConfigDiagnostics() {
|
|
199
237
|
return this._resolvedConfig.diagnostics.map((diagnostic) => ({ ...diagnostic }));
|
|
200
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* Return the enforced tool policy derived from `allowedTools` and
|
|
241
|
+
* `deniedTools`. Pass it to a `ToolLoopAgent` to make tool execution obey the
|
|
242
|
+
* same policy the client admits requests under.
|
|
243
|
+
*/
|
|
244
|
+
getToolPolicy() {
|
|
245
|
+
return this._toolPolicy;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Return the redacted authorization decision log in decision order, bounded
|
|
249
|
+
* to the most recent entries. Empty when no `rbac` policy is configured.
|
|
250
|
+
*/
|
|
251
|
+
getAuthorizationDiagnostics() {
|
|
252
|
+
return this._authorizationDiagnostics.map((diagnostic) => ({ ...diagnostic }));
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Throw when any of the supplied tool names is not permitted by the client's
|
|
256
|
+
* tool policy. Called on the request-admission path so a request that would
|
|
257
|
+
* use a denied tool fails before a provider call is made.
|
|
258
|
+
*/
|
|
259
|
+
_assertToolsAllowed(toolNames) {
|
|
260
|
+
if (this._toolPolicy.isEmpty())
|
|
261
|
+
return;
|
|
262
|
+
const violation = this._toolPolicy.checkAll(toolNames);
|
|
263
|
+
if (violation)
|
|
264
|
+
throw new Error(violation.reason ?? "tool is not permitted by policy");
|
|
265
|
+
}
|
|
201
266
|
/**
|
|
202
267
|
* Add a provider from the built-in catalog with one line.
|
|
203
268
|
*
|
|
@@ -426,6 +491,10 @@ export class HilbrasClient {
|
|
|
426
491
|
async complete(params) {
|
|
427
492
|
const requestId = this._nextRequestId();
|
|
428
493
|
const startTime = performance.now();
|
|
494
|
+
// v3.4.0: reject a request that would use a tool the policy forbids before
|
|
495
|
+
// any provider call is made.
|
|
496
|
+
if (params.tools)
|
|
497
|
+
this._assertToolsAllowed(params.tools.map((tool) => tool.function.name));
|
|
429
498
|
this._emit({ type: "request.start", requestId, timestamp: startTime, provider: params.provider, model: params.model, task: params.task });
|
|
430
499
|
// Resolve provider + model — either explicit or via router
|
|
431
500
|
const resolved_ = this._resolveProviderModel({ ...params, hasOutput: !!params.output });
|
|
@@ -614,6 +683,10 @@ export class HilbrasClient {
|
|
|
614
683
|
const maxSteps = params.maxSteps ?? 1;
|
|
615
684
|
const messages = this._normalizeMessages(params.messages);
|
|
616
685
|
const allowedToolNames = new Set((params.tools ?? []).map((tool) => tool.function.name));
|
|
686
|
+
// v3.4.0: tool policy is enforced on the tool-execution path, because a
|
|
687
|
+
// denied tool must not run even though the provider already saw its schema.
|
|
688
|
+
if (params.tools)
|
|
689
|
+
this._assertToolsAllowed([...allowedToolNames]);
|
|
617
690
|
let currentMessages = [...messages];
|
|
618
691
|
for (let step = 0; step < maxSteps; step++) {
|
|
619
692
|
let stepText = "";
|
|
@@ -4,6 +4,7 @@ import { createRuntimeSource } from "./sources/runtime.js";
|
|
|
4
4
|
import { createResolvedConfig } from "./resolved-config.js";
|
|
5
5
|
import { CONFIG_KEYS, cloneConfigValue, } from "./config-schema.js";
|
|
6
6
|
import { validateBaseUrl } from "../security/url-guard.js";
|
|
7
|
+
import { validateRbacConfig } from "../security/authorization.js";
|
|
7
8
|
import { ConfigurationError } from "../errors/index.js";
|
|
8
9
|
const LOG_LEVELS = new Set(["none", "error", "info", "debug"]);
|
|
9
10
|
function isPlainObject(value) {
|
|
@@ -125,6 +126,19 @@ function validateValues(values, source) {
|
|
|
125
126
|
diagnostics.push(errorDiagnostic(source, "CONFIG_TOOL_POLICY_CONFLICT", "allowedTools", "allowedTools and deniedTools must not overlap"));
|
|
126
127
|
}
|
|
127
128
|
}
|
|
129
|
+
// A malformed authorization policy is rejected as configuration rather than
|
|
130
|
+
// degrading to "no restrictions" at request time.
|
|
131
|
+
if (values.rbac !== undefined) {
|
|
132
|
+
for (const issue of validateRbacConfig(values.rbac, "rbac")) {
|
|
133
|
+
diagnostics.push({
|
|
134
|
+
code: issue.code,
|
|
135
|
+
message: issue.message,
|
|
136
|
+
path: issue.path,
|
|
137
|
+
severity: issue.severity,
|
|
138
|
+
source,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
128
142
|
return diagnostics;
|
|
129
143
|
}
|
|
130
144
|
function throwForDiagnostics(diagnostics) {
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* - Cancellation via AbortSignal
|
|
12
12
|
*/
|
|
13
13
|
import type { HilbrasClient } from "../../index.js";
|
|
14
|
+
import { ToolPolicy, type ToolPolicyInput } from "../../security/tool-policy.js";
|
|
14
15
|
import type { AgentTool, AgentConfig, AgentResult, AgentEvent } from "./types.js";
|
|
15
16
|
export interface ToolLoopAgentConfig extends AgentConfig {
|
|
16
17
|
/** Tools available to the agent */
|
|
@@ -41,6 +42,14 @@ export interface ToolLoopAgentConfig extends AgentConfig {
|
|
|
41
42
|
promptTokens: number;
|
|
42
43
|
completionTokens: number;
|
|
43
44
|
}, model: string) => number;
|
|
45
|
+
/**
|
|
46
|
+
* Tool policy enforced before every tool execution. A denied tool is not run
|
|
47
|
+
* and the step records the policy error.
|
|
48
|
+
*
|
|
49
|
+
* Tool policy must be applied here rather than at the transport layer,
|
|
50
|
+
* because tools execute locally and never reach a provider request.
|
|
51
|
+
*/
|
|
52
|
+
toolPolicy?: ToolPolicyInput | ToolPolicy;
|
|
44
53
|
/** Approval handler — return true to approve, false to reject */
|
|
45
54
|
onApproval?: (step: number, tool: string, args: Record<string, unknown>) => boolean | Promise<boolean>;
|
|
46
55
|
/** Event listener for agent lifecycle */
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* - Structured output for agent steps
|
|
11
11
|
* - Cancellation via AbortSignal
|
|
12
12
|
*/
|
|
13
|
+
import { ToolPolicy } from "../../security/tool-policy.js";
|
|
13
14
|
function defaultCostEstimator(usage, model) {
|
|
14
15
|
// Rough cost estimates per 1M tokens
|
|
15
16
|
const pricing = {
|
|
@@ -36,6 +37,11 @@ export class ToolLoopAgent {
|
|
|
36
37
|
*/
|
|
37
38
|
async run(initialPrompt) {
|
|
38
39
|
const { tools, maxSteps = 10, budget = null, systemPrompt = "You are a helpful assistant. Use the provided tools to complete the task. When you have the final answer, respond with it directly without calling more tools.", temperature = 0, signal, client, llm = defaultLLM, costEstimator = defaultCostEstimator, onApproval, onEvent, } = this._config;
|
|
40
|
+
const toolPolicy = this._config.toolPolicy === undefined
|
|
41
|
+
? undefined
|
|
42
|
+
: this._config.toolPolicy instanceof ToolPolicy
|
|
43
|
+
? this._config.toolPolicy
|
|
44
|
+
: new ToolPolicy(this._config.toolPolicy);
|
|
39
45
|
// If client is provided, wrap it as an LLM function
|
|
40
46
|
const effectiveLLM = client
|
|
41
47
|
? async (messages) => {
|
|
@@ -137,6 +143,25 @@ export class ToolLoopAgent {
|
|
|
137
143
|
});
|
|
138
144
|
continue;
|
|
139
145
|
}
|
|
146
|
+
// Tool policy check. Tools execute locally, so the transport layer
|
|
147
|
+
// cannot govern them; this is the only place a denied tool can be
|
|
148
|
+
// stopped before it runs.
|
|
149
|
+
if (toolPolicy && !toolPolicy.isEmpty()) {
|
|
150
|
+
const decision = toolPolicy.check(tc.name);
|
|
151
|
+
if (!decision.allowed) {
|
|
152
|
+
stepToolCalls.push({
|
|
153
|
+
name: tc.name,
|
|
154
|
+
args: tc.arguments,
|
|
155
|
+
result: null,
|
|
156
|
+
error: decision.reason ?? `Tool "${tc.name}" is not permitted`,
|
|
157
|
+
});
|
|
158
|
+
onEvent?.({
|
|
159
|
+
type: "error",
|
|
160
|
+
error: new Error(decision.reason ?? `Tool "${tc.name}" is not permitted`),
|
|
161
|
+
});
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
140
165
|
// Approval check
|
|
141
166
|
let approved = true;
|
|
142
167
|
if (onApproval) {
|
package/dist/index.d.ts
CHANGED
|
@@ -85,7 +85,9 @@ export type { CredentialSource, CredentialProvider } from "./credentials/provide
|
|
|
85
85
|
export { validateBaseUrl } from "./security/url-guard.js";
|
|
86
86
|
export type { UrlGuardOptions, UrlGuardResult } from "./security/url-guard.js";
|
|
87
87
|
export { RequestSigner, signingMiddleware } from "./security/request-signer.js";
|
|
88
|
-
export type { RequestSignerConfig, SignedRequest } from "./security/request-signer.js";
|
|
88
|
+
export type { RequestSignerConfig, SignedRequest, SignatureProfile, SignableBody } from "./security/request-signer.js";
|
|
89
|
+
export { ReplayGuard, createReplayGuard } from "./security/replay-guard.js";
|
|
90
|
+
export type { ReplayGuardOptions, ReplayVerdict } from "./security/replay-guard.js";
|
|
89
91
|
export { redactPii, detectPii, createPiiRedactor } from "./security/pii-guard.js";
|
|
90
92
|
export type { PiiType, PiiMatch, PiiGuardConfig } from "./security/pii-guard.js";
|
|
91
93
|
export { AuditLogger, createRetentionPolicy } from "./security/audit-logger.js";
|
|
@@ -143,6 +145,10 @@ export type { Plugin, PluginRequestContext, PluginResponseContext, PluginErrorCo
|
|
|
143
145
|
export { PluginRegistry } from "./plugin/registry.js";
|
|
144
146
|
export { createRBACMiddleware, checkPermission } from "./security/rbac.js";
|
|
145
147
|
export type { RBACRole, RBACConfig, PermissionCheck } from "./security/rbac.js";
|
|
148
|
+
export { evaluateAuthorization, evaluateRoleRequest, resolveRequestFromContext, validateRbacConfig, isStringArray, } from "./security/authorization.js";
|
|
149
|
+
export type { AuthorizationBudgetView, AuthorizationDiagnostic, AuthorizationDiagnosticSeverity, AuthorizationEnforcement, AuthorizationOptions, AuthorizationVerdict, ResolveAuthorizationBudget, ResolveProviderByUrl, RBACRequestContext, } from "./security/authorization.js";
|
|
150
|
+
export { ToolPolicy, createToolPolicy } from "./security/tool-policy.js";
|
|
151
|
+
export type { ToolPolicyInput, ToolPolicyCheck } from "./security/tool-policy.js";
|
|
146
152
|
export { CostAlertMonitor, createCostAlertBudget } from "./cost/alerts.js";
|
|
147
153
|
export type { AlertChannel, ThresholdConfig, CostAlert, CostAlertConfig } from "./cost/alerts.js";
|
|
148
154
|
export { runABTest } from "./features/eval/ab-test.js";
|
package/dist/index.js
CHANGED
|
@@ -63,6 +63,7 @@ export { DefaultCredentialProvider, getCredentialProvider, setCredentialProvider
|
|
|
63
63
|
// ─── Security (v0.9.3: SSRF guard, v0.14.0: HMAC signing, PII, audit) ──────
|
|
64
64
|
export { validateBaseUrl } from "./security/url-guard.js";
|
|
65
65
|
export { RequestSigner, signingMiddleware } from "./security/request-signer.js";
|
|
66
|
+
export { ReplayGuard, createReplayGuard } from "./security/replay-guard.js";
|
|
66
67
|
export { redactPii, detectPii, createPiiRedactor } from "./security/pii-guard.js";
|
|
67
68
|
export { AuditLogger, createRetentionPolicy } from "./security/audit-logger.js";
|
|
68
69
|
export { RateLimiter, createRateLimiter, RateLimiterRegistry } from "./security/rate-limiter.js";
|
|
@@ -110,6 +111,9 @@ export { createSSEStream, createSSEResponse, createObjectSSEStream, createObject
|
|
|
110
111
|
export { PluginRegistry } from "./plugin/registry.js";
|
|
111
112
|
// ─── RBAC (v3.0.0) ─────────────────────────────────────────────────────────
|
|
112
113
|
export { createRBACMiddleware, checkPermission } from "./security/rbac.js";
|
|
114
|
+
// ─── Authorization enforcement (v3.4.0) ───────────────────────────────────
|
|
115
|
+
export { evaluateAuthorization, evaluateRoleRequest, resolveRequestFromContext, validateRbacConfig, isStringArray, } from "./security/authorization.js";
|
|
116
|
+
export { ToolPolicy, createToolPolicy } from "./security/tool-policy.js";
|
|
113
117
|
// ─── Cost Alerts (v3.0.0) ──────────────────────────────────────────────────
|
|
114
118
|
export { CostAlertMonitor, createCostAlertBudget } from "./cost/alerts.js";
|
|
115
119
|
// ─── A/B Prompt Testing (v3.0.0) ───────────────────────────────────────────
|
|
@@ -10,6 +10,16 @@ export interface MiddlewareContext {
|
|
|
10
10
|
next: () => Promise<Response>;
|
|
11
11
|
}
|
|
12
12
|
export type Middleware = (ctx: MiddlewareContext) => Promise<Response>;
|
|
13
|
+
/**
|
|
14
|
+
* Compose middlewares into a single middleware. The leftmost middleware runs
|
|
15
|
+
* first.
|
|
16
|
+
*
|
|
17
|
+
* Each `next()` re-enters the chain at the following index rather than
|
|
18
|
+
* consuming a shared cursor, so a stage that calls `next()` more than once —
|
|
19
|
+
* `retryMiddleware`, for example — re-runs every downstream stage on each
|
|
20
|
+
* attempt. A shared monotonic cursor permanently exhausts the chain after the
|
|
21
|
+
* first attempt, which silently skipped signing and auth on all retries.
|
|
22
|
+
*/
|
|
13
23
|
export declare function composeMiddlewares(...middlewares: Middleware[]): Middleware;
|
|
14
24
|
export declare function authMiddleware(getToken: () => string): Middleware;
|
|
15
25
|
export declare function loggingMiddleware(log?: (msg: string) => void): Middleware;
|
|
@@ -3,16 +3,25 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Interceptors that wrap the transport layer for cross-cutting concerns.
|
|
5
5
|
*/
|
|
6
|
+
/**
|
|
7
|
+
* Compose middlewares into a single middleware. The leftmost middleware runs
|
|
8
|
+
* first.
|
|
9
|
+
*
|
|
10
|
+
* Each `next()` re-enters the chain at the following index rather than
|
|
11
|
+
* consuming a shared cursor, so a stage that calls `next()` more than once —
|
|
12
|
+
* `retryMiddleware`, for example — re-runs every downstream stage on each
|
|
13
|
+
* attempt. A shared monotonic cursor permanently exhausts the chain after the
|
|
14
|
+
* first attempt, which silently skipped signing and auth on all retries.
|
|
15
|
+
*/
|
|
6
16
|
export function composeMiddlewares(...middlewares) {
|
|
7
17
|
return async (ctx) => {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
if (idx >= middlewares.length)
|
|
18
|
+
const invoke = async (index) => {
|
|
19
|
+
if (index >= middlewares.length)
|
|
11
20
|
return ctx.next();
|
|
12
|
-
const mw = middlewares[
|
|
13
|
-
return mw({ ...ctx, next });
|
|
21
|
+
const mw = middlewares[index];
|
|
22
|
+
return mw({ ...ctx, next: () => invoke(index + 1) });
|
|
14
23
|
};
|
|
15
|
-
return
|
|
24
|
+
return invoke(0);
|
|
16
25
|
};
|
|
17
26
|
}
|
|
18
27
|
export function authMiddleware(getToken) {
|
|
@@ -12,6 +12,15 @@ export declare class ProviderRegistry {
|
|
|
12
12
|
get(name: string): ProviderConfig | undefined;
|
|
13
13
|
getOrThrow(name: string): ProviderConfig;
|
|
14
14
|
list(): ProviderConfig[];
|
|
15
|
+
/**
|
|
16
|
+
* Resolve a provider name from a request URL.
|
|
17
|
+
*
|
|
18
|
+
* Authorization decisions happen at the transport layer, where the request
|
|
19
|
+
* body carries a model but never a provider. Matching the URL back to a
|
|
20
|
+
* registered provider is how the provider for a request is identified.
|
|
21
|
+
* Matches on origin, tolerating base-path prefixes and trailing slashes.
|
|
22
|
+
*/
|
|
23
|
+
findByUrl(url: string): string | null;
|
|
15
24
|
/** Find a model across all providers */
|
|
16
25
|
findModel(modelId: string): {
|
|
17
26
|
provider: ProviderConfig;
|
|
@@ -26,6 +26,43 @@ export class ProviderRegistry {
|
|
|
26
26
|
list() {
|
|
27
27
|
return [...this._providers.values()].map(cloneProviderConfig);
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Resolve a provider name from a request URL.
|
|
31
|
+
*
|
|
32
|
+
* Authorization decisions happen at the transport layer, where the request
|
|
33
|
+
* body carries a model but never a provider. Matching the URL back to a
|
|
34
|
+
* registered provider is how the provider for a request is identified.
|
|
35
|
+
* Matches on origin, tolerating base-path prefixes and trailing slashes.
|
|
36
|
+
*/
|
|
37
|
+
findByUrl(url) {
|
|
38
|
+
let target;
|
|
39
|
+
try {
|
|
40
|
+
target = new URL(url);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
const targetOrigin = target.origin.toLowerCase();
|
|
46
|
+
for (const provider of this._providers.values()) {
|
|
47
|
+
let base;
|
|
48
|
+
try {
|
|
49
|
+
base = new URL(provider.baseUrl);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (base.origin.toLowerCase() !== targetOrigin)
|
|
55
|
+
continue;
|
|
56
|
+
const basePath = base.pathname.replace(/\/+$/, "");
|
|
57
|
+
if (basePath.length > 0) {
|
|
58
|
+
const targetPath = target.pathname;
|
|
59
|
+
if (targetPath !== basePath && !targetPath.startsWith(`${basePath}/`))
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
return provider.name;
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
29
66
|
/** Find a model across all providers */
|
|
30
67
|
findModel(modelId) {
|
|
31
68
|
for (const provider of this._providers.values()) {
|