@hilbras/sdk 3.3.0 → 3.4.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 +45 -2
- package/dist/client/client.d.ts +49 -0
- package/dist/client/client.js +94 -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
|
@@ -1,29 +1,58 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @hilbras/sdk — HMAC Request Signer
|
|
3
3
|
*
|
|
4
|
-
* Signs HTTP requests with HMAC
|
|
5
|
-
*
|
|
4
|
+
* Signs HTTP requests with HMAC for provider authentication and gateway
|
|
5
|
+
* handshakes.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
* provide replay protection. Callers must independently enforce timestamp
|
|
9
|
-
* freshness (e.g. reject requests with a `date` header older than 5 minutes)
|
|
10
|
-
* and/or nonce tracking to prevent replay attacks.
|
|
7
|
+
* ## Signature profiles
|
|
11
8
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
9
|
+
* - **`"v1"` (default, deprecated).** The pre-v3.4.0 wire format, frozen so
|
|
10
|
+
* existing verifiers keep working. Its canonical string covers the method,
|
|
11
|
+
* path, and the headers named in `config.headers`. The body digest is emitted
|
|
12
|
+
* as `x-content-sha256` but is **not** part of that canonical string, so a
|
|
13
|
+
* `v1` signature does not authenticate the body. `verify()` trusts a received
|
|
14
|
+
* digest header when `config.headers` names it. Do not use `v1` for new
|
|
15
|
+
* integrations.
|
|
16
|
+
* - **`"v2"`.** The body digest, the key id, and a per-request nonce are all
|
|
17
|
+
* bound into the canonical string. `verify()` recomputes the digest from the
|
|
18
|
+
* received bytes and never trusts a received digest header, and a mismatched
|
|
19
|
+
* `x-hilbras-key-id` fails verification.
|
|
14
20
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* headers: ["date", "content-type"],
|
|
19
|
-
* });
|
|
21
|
+
* Neither profile provides replay protection. Pair either with
|
|
22
|
+
* {@link ReplayGuard}, or use `RequestSigner.verifyFresh()` which composes
|
|
23
|
+
* signature verification with a freshness window and a seen-signature cache.
|
|
20
24
|
*
|
|
21
|
-
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const signer = new RequestSigner({
|
|
28
|
+
* secret: process.env.API_SIGNING_SECRET!,
|
|
29
|
+
* keyId: "key-2026-09",
|
|
30
|
+
* profile: "v2",
|
|
31
|
+
* });
|
|
32
|
+
*
|
|
33
|
+
* const signed = signer.sign(url, { method: "POST", body, headers });
|
|
34
|
+
* ```
|
|
22
35
|
*/
|
|
23
36
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
37
|
+
import { ReplayGuard } from "./replay-guard.js";
|
|
38
|
+
function defaultNonce() {
|
|
39
|
+
const bytes = new Uint8Array(16);
|
|
40
|
+
const webcrypto = globalThis.crypto;
|
|
41
|
+
if (webcrypto?.getRandomValues) {
|
|
42
|
+
webcrypto.getRandomValues(bytes);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
for (let i = 0; i < bytes.length; i += 1)
|
|
46
|
+
bytes[i] = Math.floor(Math.random() * 256);
|
|
47
|
+
}
|
|
48
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
49
|
+
}
|
|
50
|
+
function isByteBody(body) {
|
|
51
|
+
return typeof body === "string" || body instanceof Uint8Array;
|
|
52
|
+
}
|
|
24
53
|
/**
|
|
25
|
-
* Signs HTTP requests using HMAC
|
|
26
|
-
*
|
|
54
|
+
* Signs HTTP requests using HMAC. See the module documentation for the
|
|
55
|
+
* difference between the `v1` and `v2` profiles.
|
|
27
56
|
*/
|
|
28
57
|
export class RequestSigner {
|
|
29
58
|
_config;
|
|
@@ -35,110 +64,190 @@ export class RequestSigner {
|
|
|
35
64
|
signatureHeader: config.signatureHeader ?? "x-hilbras-signature",
|
|
36
65
|
keyIdHeader: config.keyIdHeader ?? "x-hilbras-key-id",
|
|
37
66
|
algorithm: config.algorithm ?? "sha256",
|
|
67
|
+
profile: config.profile ?? "v1",
|
|
68
|
+
nonceHeader: (config.nonceHeader ?? "x-hilbras-nonce").toLowerCase(),
|
|
69
|
+
contentDigestHeader: (config.contentDigestHeader ?? "x-hilbras-content-digest").toLowerCase(),
|
|
70
|
+
now: config.now ?? (() => Date.now()),
|
|
71
|
+
nonce: config.nonce ?? defaultNonce,
|
|
38
72
|
};
|
|
39
73
|
}
|
|
74
|
+
/** The active wire-format profile. */
|
|
75
|
+
get profile() {
|
|
76
|
+
return this._config.profile;
|
|
77
|
+
}
|
|
78
|
+
/** Current RFC 7231 timestamp from the signer's injected clock. */
|
|
79
|
+
timestamp() {
|
|
80
|
+
return new Date(this._config.now()).toUTCString();
|
|
81
|
+
}
|
|
82
|
+
/** Header names this signer emits, for callers that normalize headers. */
|
|
83
|
+
get signatureHeader() {
|
|
84
|
+
return this._config.signatureHeader;
|
|
85
|
+
}
|
|
86
|
+
_digest(body) {
|
|
87
|
+
return createHmac(this._config.algorithm, this._config.secret)
|
|
88
|
+
.update(typeof body === "string" ? body : Buffer.from(body))
|
|
89
|
+
.digest("hex");
|
|
90
|
+
}
|
|
91
|
+
/** Build the canonical string that the HMAC covers. */
|
|
92
|
+
_canonical(input) {
|
|
93
|
+
const signedHeaderKeys = [...this._config.headers].sort();
|
|
94
|
+
const headerValues = signedHeaderKeys.map((h) => {
|
|
95
|
+
if (h === "(request-target)")
|
|
96
|
+
return `${input.method.toLowerCase()} ${input.path}`;
|
|
97
|
+
return input.headers[h.toLowerCase()] ?? "";
|
|
98
|
+
});
|
|
99
|
+
const base = `${input.method.toLowerCase()} ${input.path}\n${signedHeaderKeys.map((k, i) => `${k}: ${headerValues[i]}`).join("\n")}`;
|
|
100
|
+
if (this._config.profile === "v1")
|
|
101
|
+
return base;
|
|
102
|
+
return [
|
|
103
|
+
base,
|
|
104
|
+
`content-digest: ${input.digest ?? ""}`,
|
|
105
|
+
`key-id: ${this._config.keyId}`,
|
|
106
|
+
`nonce: ${input.nonce ?? ""}`,
|
|
107
|
+
].join("\n");
|
|
108
|
+
}
|
|
109
|
+
_hmac(signingString) {
|
|
110
|
+
return createHmac(this._config.algorithm, this._config.secret)
|
|
111
|
+
.update(signingString)
|
|
112
|
+
.digest("hex");
|
|
113
|
+
}
|
|
40
114
|
/**
|
|
41
115
|
* Sign a request. Returns headers to add to the outgoing request.
|
|
42
|
-
*
|
|
43
|
-
*
|
|
116
|
+
*
|
|
117
|
+
* A body that is not a rewindable byte sequence (for example `FormData`)
|
|
118
|
+
* cannot be content-bound, so no digest header is emitted for it rather than
|
|
119
|
+
* a digest of a placeholder string.
|
|
44
120
|
*/
|
|
45
121
|
sign(url, request) {
|
|
46
122
|
const method = (request.method ?? "GET").toUpperCase();
|
|
47
|
-
const timestamp = request.timestamp ?? new Date().toUTCString();
|
|
48
|
-
// Parse URL for path
|
|
123
|
+
const timestamp = request.timestamp ?? new Date(this._config.now()).toUTCString();
|
|
49
124
|
const parsed = new URL(url);
|
|
50
125
|
const path = parsed.pathname + parsed.search;
|
|
51
|
-
// Build headers record (lowercase keys)
|
|
52
126
|
const hdrs = {};
|
|
53
127
|
for (const [key, value] of Object.entries(request.headers ?? {})) {
|
|
54
128
|
if (value !== undefined)
|
|
55
129
|
hdrs[key.toLowerCase()] = value;
|
|
56
130
|
}
|
|
57
131
|
hdrs.date = timestamp;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
132
|
+
const signable = isByteBody(request.body) ? request.body : undefined;
|
|
133
|
+
const digest = signable !== undefined ? this._digest(signable) : undefined;
|
|
134
|
+
let nonce;
|
|
135
|
+
if (this._config.profile === "v2") {
|
|
136
|
+
nonce = request.nonce ?? this._config.nonce();
|
|
137
|
+
hdrs[this._config.nonceHeader] = nonce;
|
|
138
|
+
// A correctly named header, and only when the body is actually readable.
|
|
139
|
+
if (digest !== undefined)
|
|
140
|
+
hdrs[this._config.contentDigestHeader] = digest;
|
|
66
141
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
const signature = createHmac(this._config.algorithm, this._config.secret)
|
|
77
|
-
.update(signingString)
|
|
78
|
-
.digest("hex");
|
|
79
|
-
// Build signature-input header value (SF-style)
|
|
80
|
-
const signatureInput = `keyId="${this._config.keyId}",algorithm="${this._config.algorithm}",headers="${signedHeaderKeys.join(" ")}",signature="${signature}"`;
|
|
81
|
-
// Build output headers
|
|
142
|
+
else if (digest !== undefined) {
|
|
143
|
+
// Frozen v1 behavior: the header is emitted but is not signed.
|
|
144
|
+
hdrs["x-content-sha256"] = digest;
|
|
145
|
+
}
|
|
146
|
+
const signingString = this._canonical({ method, path, headers: hdrs, digest, nonce });
|
|
147
|
+
const signature = this._hmac(signingString);
|
|
148
|
+
const signedHeaderKeys = [...this._config.headers].sort().join(" ");
|
|
149
|
+
const signatureInput = `keyId="${this._config.keyId}",algorithm="${this._config.algorithm}",` +
|
|
150
|
+
`headers="${signedHeaderKeys}",profile="${this._config.profile}",signature="${signature}"`;
|
|
82
151
|
const outHeaders = { ...hdrs };
|
|
83
152
|
outHeaders[this._config.signatureHeader] = signature;
|
|
84
153
|
if (this._config.keyId) {
|
|
85
154
|
outHeaders[this._config.keyIdHeader] = this._config.keyId;
|
|
86
155
|
}
|
|
87
|
-
return {
|
|
88
|
-
headers: outHeaders,
|
|
89
|
-
signature,
|
|
90
|
-
signatureInput,
|
|
91
|
-
};
|
|
156
|
+
return { headers: outHeaders, signature, signatureInput };
|
|
92
157
|
}
|
|
93
158
|
/**
|
|
94
159
|
* Verify a request signature. Returns true if valid.
|
|
160
|
+
*
|
|
161
|
+
* Under `v2` the body digest is recomputed from the supplied bytes, so a
|
|
162
|
+
* modified body fails even when the digest header is modified to match.
|
|
95
163
|
*/
|
|
96
164
|
verify(url, request, receivedSignature) {
|
|
97
165
|
const method = (request.method ?? "GET").toUpperCase();
|
|
98
|
-
|
|
99
|
-
|
|
166
|
+
let path;
|
|
167
|
+
try {
|
|
168
|
+
const parsed = new URL(url);
|
|
169
|
+
path = parsed.pathname + parsed.search;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
100
174
|
const hdrs = {};
|
|
101
|
-
for (const [key, value] of Object.entries(request.headers)) {
|
|
175
|
+
for (const [key, value] of Object.entries(request.headers ?? {})) {
|
|
102
176
|
if (value !== undefined)
|
|
103
177
|
hdrs[key.toLowerCase()] = value;
|
|
104
178
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
.
|
|
114
|
-
.
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const b = Buffer.from(receivedSignature, "hex");
|
|
119
|
-
if (a.length !== b.length)
|
|
179
|
+
let digest;
|
|
180
|
+
let nonce;
|
|
181
|
+
if (this._config.profile === "v2") {
|
|
182
|
+
// A key id that does not match this signer is a key-confusion attempt.
|
|
183
|
+
const receivedKeyId = hdrs[this._config.keyIdHeader];
|
|
184
|
+
if (this._config.keyId && receivedKeyId !== undefined && receivedKeyId !== this._config.keyId) {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
// Recompute from the received bytes; never trust the received digest.
|
|
188
|
+
if (isByteBody(request.body))
|
|
189
|
+
digest = this._digest(request.body);
|
|
190
|
+
nonce = request.nonce ?? hdrs[this._config.nonceHeader];
|
|
191
|
+
if (nonce === undefined)
|
|
120
192
|
return false;
|
|
121
|
-
return timingSafeEqual(a, b);
|
|
122
193
|
}
|
|
123
|
-
|
|
194
|
+
const expectedSignature = this._hmac(this._canonical({ method, path, headers: hdrs, digest, nonce }));
|
|
195
|
+
return timingSafeEqualHex(expectedSignature, receivedSignature);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Verify a signature and reject replays. Composes {@link verify} with a
|
|
199
|
+
* {@link ReplayGuard}, which enforces a signed-timestamp window and a bounded
|
|
200
|
+
* seen-signature cache.
|
|
201
|
+
*/
|
|
202
|
+
verifyFresh(url, request, receivedSignature, options) {
|
|
203
|
+
const { guard, ...guardOptions } = options ?? {};
|
|
204
|
+
const signatureOk = this.verify(url, request, receivedSignature);
|
|
205
|
+
if (!signatureOk)
|
|
206
|
+
return { valid: false, reason: "signature does not match" };
|
|
207
|
+
const freshness = (guard ?? new ReplayGuard(guardOptions)).verify(request.headers, receivedSignature);
|
|
208
|
+
if (!freshness.valid)
|
|
209
|
+
return { valid: false, reason: freshness.reason };
|
|
210
|
+
return { valid: true };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function timingSafeEqualHex(expected, received) {
|
|
214
|
+
try {
|
|
215
|
+
const a = Buffer.from(expected, "hex");
|
|
216
|
+
const b = Buffer.from(received, "hex");
|
|
217
|
+
if (a.length !== b.length || a.length === 0)
|
|
124
218
|
return false;
|
|
125
|
-
|
|
219
|
+
return timingSafeEqual(a, b);
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
return false;
|
|
126
223
|
}
|
|
127
224
|
}
|
|
128
225
|
/**
|
|
129
|
-
*
|
|
226
|
+
* Create a middleware that signs every outgoing request.
|
|
227
|
+
*
|
|
228
|
+
* The outgoing header bag is normalized to a single lowercase key per name, so
|
|
229
|
+
* merging signed headers cannot produce both `Content-Type` and `content-type`.
|
|
130
230
|
*/
|
|
131
231
|
export function signingMiddleware(signer) {
|
|
132
232
|
return async (ctx) => {
|
|
133
|
-
const
|
|
134
|
-
const
|
|
233
|
+
const timestamp = signer.timestamp();
|
|
234
|
+
const existing = ctx.init.headers ?? {};
|
|
235
|
+
const normalized = {};
|
|
236
|
+
for (const [key, value] of Object.entries(existing)) {
|
|
237
|
+
if (value === undefined)
|
|
238
|
+
continue;
|
|
239
|
+
normalized[key.toLowerCase()] = value;
|
|
240
|
+
}
|
|
241
|
+
const body = ctx.init.body;
|
|
135
242
|
const signed = signer.sign(ctx.url, {
|
|
136
243
|
method: ctx.init.method ?? "GET",
|
|
137
|
-
|
|
138
|
-
|
|
244
|
+
// FormData and other non-rewindable bodies are passed through so the
|
|
245
|
+
// signer can report "no digest" instead of hashing a placeholder.
|
|
246
|
+
body: body,
|
|
247
|
+
headers: normalized,
|
|
139
248
|
timestamp,
|
|
140
249
|
});
|
|
141
|
-
ctx.init.headers = { ...
|
|
250
|
+
ctx.init.headers = { ...normalized, ...signed.headers };
|
|
142
251
|
return ctx.next();
|
|
143
252
|
};
|
|
144
253
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Tool policy
|
|
3
|
+
*
|
|
4
|
+
* `SDKConfig.allowedTools` and `SDKConfig.deniedTools` have always been part of
|
|
5
|
+
* the configuration schema, but nothing consulted them: they were validated for
|
|
6
|
+
* overlap and then ignored. This module makes them enforceable at the point
|
|
7
|
+
* where a tool actually runs.
|
|
8
|
+
*
|
|
9
|
+
* Semantics match the rest of the configuration system: an absent or empty
|
|
10
|
+
* allow-list means every tool is permitted, and a deny-list always wins over an
|
|
11
|
+
* allow-list. A tool policy is a pure value with no I/O, so it can be shared
|
|
12
|
+
* between a client, an agent loop, and a framework handler.
|
|
13
|
+
*/
|
|
14
|
+
/** Plain shape accepted wherever a {@link ToolPolicy} is configured. */
|
|
15
|
+
export interface ToolPolicyInput {
|
|
16
|
+
/** Permitted tool names. Empty or absent means all tools are permitted. */
|
|
17
|
+
allowedTools?: readonly string[];
|
|
18
|
+
/** Tool names that are never permitted. Takes precedence over the allow-list. */
|
|
19
|
+
deniedTools?: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
/** Result of checking one tool name against a policy. */
|
|
22
|
+
export interface ToolPolicyCheck {
|
|
23
|
+
allowed: boolean;
|
|
24
|
+
reason?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare class ToolPolicy {
|
|
27
|
+
private readonly _allowed;
|
|
28
|
+
private readonly _denied;
|
|
29
|
+
constructor(input?: ToolPolicyInput);
|
|
30
|
+
/** True when the policy constrains nothing. */
|
|
31
|
+
isEmpty(): boolean;
|
|
32
|
+
get allowedTools(): readonly string[] | undefined;
|
|
33
|
+
get deniedTools(): readonly string[];
|
|
34
|
+
/** Check a single tool name. */
|
|
35
|
+
check(toolName: string): ToolPolicyCheck;
|
|
36
|
+
isAllowed(toolName: string): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Return the intersection of this policy with a narrower one. A tool must be
|
|
39
|
+
* permitted by both policies to be permitted by the result, so a per-user
|
|
40
|
+
* allow-list can only narrow a client-level policy, never widen it.
|
|
41
|
+
*/
|
|
42
|
+
narrow(other: ToolPolicyInput | ToolPolicy | undefined): ToolPolicy;
|
|
43
|
+
/**
|
|
44
|
+
* Validate a whole tool set at once. Returns the first violation, or `null`
|
|
45
|
+
* when every tool is permitted.
|
|
46
|
+
*/
|
|
47
|
+
checkAll(toolNames: readonly string[]): ToolPolicyCheck | null;
|
|
48
|
+
/** Throw when a tool is not permitted. */
|
|
49
|
+
assertAllowed(toolName: string): void;
|
|
50
|
+
toJSON(): ToolPolicyInput;
|
|
51
|
+
}
|
|
52
|
+
/** Create a tool policy from a plain input. */
|
|
53
|
+
export declare function createToolPolicy(input?: ToolPolicyInput): ToolPolicy;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Tool policy
|
|
3
|
+
*
|
|
4
|
+
* `SDKConfig.allowedTools` and `SDKConfig.deniedTools` have always been part of
|
|
5
|
+
* the configuration schema, but nothing consulted them: they were validated for
|
|
6
|
+
* overlap and then ignored. This module makes them enforceable at the point
|
|
7
|
+
* where a tool actually runs.
|
|
8
|
+
*
|
|
9
|
+
* Semantics match the rest of the configuration system: an absent or empty
|
|
10
|
+
* allow-list means every tool is permitted, and a deny-list always wins over an
|
|
11
|
+
* allow-list. A tool policy is a pure value with no I/O, so it can be shared
|
|
12
|
+
* between a client, an agent loop, and a framework handler.
|
|
13
|
+
*/
|
|
14
|
+
export class ToolPolicy {
|
|
15
|
+
_allowed;
|
|
16
|
+
_denied;
|
|
17
|
+
constructor(input = {}) {
|
|
18
|
+
this._allowed = input.allowedTools && input.allowedTools.length > 0
|
|
19
|
+
? Object.freeze([...input.allowedTools])
|
|
20
|
+
: undefined;
|
|
21
|
+
this._denied = Object.freeze([...(input.deniedTools ?? [])]);
|
|
22
|
+
}
|
|
23
|
+
/** True when the policy constrains nothing. */
|
|
24
|
+
isEmpty() {
|
|
25
|
+
return this._allowed === undefined && this._denied.length === 0;
|
|
26
|
+
}
|
|
27
|
+
get allowedTools() {
|
|
28
|
+
return this._allowed;
|
|
29
|
+
}
|
|
30
|
+
get deniedTools() {
|
|
31
|
+
return this._denied;
|
|
32
|
+
}
|
|
33
|
+
/** Check a single tool name. */
|
|
34
|
+
check(toolName) {
|
|
35
|
+
if (this._denied.includes(toolName)) {
|
|
36
|
+
return { allowed: false, reason: `Tool "${toolName}" is denied by policy` };
|
|
37
|
+
}
|
|
38
|
+
if (this._allowed !== undefined && !this._allowed.includes(toolName)) {
|
|
39
|
+
return {
|
|
40
|
+
allowed: false,
|
|
41
|
+
reason: `Tool "${toolName}" is not in the allowed tool list (${this._allowed.join(", ")})`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return { allowed: true };
|
|
45
|
+
}
|
|
46
|
+
isAllowed(toolName) {
|
|
47
|
+
return this.check(toolName).allowed;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Return the intersection of this policy with a narrower one. A tool must be
|
|
51
|
+
* permitted by both policies to be permitted by the result, so a per-user
|
|
52
|
+
* allow-list can only narrow a client-level policy, never widen it.
|
|
53
|
+
*/
|
|
54
|
+
narrow(other) {
|
|
55
|
+
if (other === undefined)
|
|
56
|
+
return this;
|
|
57
|
+
const narrower = other instanceof ToolPolicy ? other : new ToolPolicy(other);
|
|
58
|
+
const allowed = this._allowed === undefined
|
|
59
|
+
? narrower.allowedTools
|
|
60
|
+
: narrower.allowedTools === undefined
|
|
61
|
+
? this._allowed
|
|
62
|
+
: this._allowed.filter((name) => narrower.allowedTools.includes(name));
|
|
63
|
+
return new ToolPolicy({
|
|
64
|
+
allowedTools: allowed,
|
|
65
|
+
deniedTools: [...this._denied, ...narrower.deniedTools],
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Validate a whole tool set at once. Returns the first violation, or `null`
|
|
70
|
+
* when every tool is permitted.
|
|
71
|
+
*/
|
|
72
|
+
checkAll(toolNames) {
|
|
73
|
+
for (const name of toolNames) {
|
|
74
|
+
const result = this.check(name);
|
|
75
|
+
if (!result.allowed)
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
/** Throw when a tool is not permitted. */
|
|
81
|
+
assertAllowed(toolName) {
|
|
82
|
+
const result = this.check(toolName);
|
|
83
|
+
if (!result.allowed) {
|
|
84
|
+
throw new Error(result.reason ?? `Tool "${toolName}" is not permitted`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
toJSON() {
|
|
88
|
+
return {
|
|
89
|
+
allowedTools: this._allowed ? [...this._allowed] : undefined,
|
|
90
|
+
deniedTools: this._denied.length > 0 ? [...this._denied] : undefined,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Create a tool policy from a plain input. */
|
|
95
|
+
export function createToolPolicy(input = {}) {
|
|
96
|
+
return new ToolPolicy(input);
|
|
97
|
+
}
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* const transport = new MiddlewareTransport(new FetchTransport(), mw);
|
|
18
18
|
* const client = new HilbrasClient({ transport });
|
|
19
19
|
*/
|
|
20
|
+
import { ProviderRequestError } from "../errors/index.js";
|
|
20
21
|
export class MiddlewareTransport {
|
|
21
22
|
_inner;
|
|
22
23
|
_middleware;
|
|
@@ -38,6 +39,14 @@ export class MiddlewareTransport {
|
|
|
38
39
|
init,
|
|
39
40
|
next: () => this._inner.request(url, init),
|
|
40
41
|
});
|
|
42
|
+
// A non-2xx response must not be handed back as a stream. Middleware such
|
|
43
|
+
// as RBAC returns 403/429 with a JSON body; returning it here would look to
|
|
44
|
+
// an adapter like an empty SSE stream, turning a denial into a silent empty
|
|
45
|
+
// completion.
|
|
46
|
+
if (!res.ok) {
|
|
47
|
+
const body = await res.text().catch(() => "");
|
|
48
|
+
throw new ProviderRequestError(res.status, body || res.statusText, "middleware");
|
|
49
|
+
}
|
|
41
50
|
if (!res.body) {
|
|
42
51
|
throw new Error(`Response body is null for ${url}`);
|
|
43
52
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hilbras/sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.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",
|
|
@@ -231,6 +231,7 @@
|
|
|
231
231
|
"build": "node tools/clean-dist.mjs dist && tsc -p tsconfig.build.json",
|
|
232
232
|
"dev": "tsc --watch",
|
|
233
233
|
"pretest": "npx tsc --noEmit",
|
|
234
|
+
"typecheck:examples": "tsc -p tsconfig.examples-check.json",
|
|
234
235
|
"test": "npm run test:root",
|
|
235
236
|
"test:watch": "vitest",
|
|
236
237
|
"test:coverage": "vitest run --coverage",
|