@hilbras/sdk 3.2.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 +83 -2
- package/dist/client/client.d.ts +39 -9
- package/dist/client/client.js +101 -44
- package/dist/config/config-resolver.d.ts +3 -0
- package/dist/config/config-resolver.js +187 -0
- package/dist/config/config-schema.d.ts +69 -0
- package/dist/config/config-schema.js +56 -0
- package/dist/config/config.d.ts +10 -17
- package/dist/config/config.js +37 -135
- package/dist/config/index.d.ts +11 -0
- package/dist/config/index.js +8 -0
- package/dist/config/resolved-config.d.ts +15 -0
- package/dist/config/resolved-config.js +60 -0
- package/dist/config/schema.d.ts +5 -59
- package/dist/config/schema.js +4 -28
- package/dist/config/sources/defaults.d.ts +2 -0
- package/dist/config/sources/defaults.js +10 -0
- package/dist/config/sources/environment.d.ts +4 -0
- package/dist/config/sources/environment.js +114 -0
- package/dist/config/sources/file.d.ts +6 -0
- package/dist/config/sources/file.js +33 -0
- package/dist/config/sources/runtime.d.ts +3 -0
- package/dist/config/sources/runtime.js +7 -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 +15 -1
- package/dist/index.js +10 -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 +4 -3
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export function createFileSource(options) {
|
|
2
|
+
return {
|
|
3
|
+
kind: "file",
|
|
4
|
+
load: () => {
|
|
5
|
+
const diagnostics = [];
|
|
6
|
+
let parsed;
|
|
7
|
+
try {
|
|
8
|
+
parsed = JSON.parse(options.readFile(options.path));
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
diagnostics.push({
|
|
12
|
+
code: "CONFIG_FILE_INVALID_JSON",
|
|
13
|
+
message: "configuration file is not valid JSON",
|
|
14
|
+
path: "$",
|
|
15
|
+
severity: "error",
|
|
16
|
+
source: "file",
|
|
17
|
+
});
|
|
18
|
+
return { values: {}, diagnostics };
|
|
19
|
+
}
|
|
20
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
21
|
+
diagnostics.push({
|
|
22
|
+
code: "CONFIG_FILE_INVALID_SHAPE",
|
|
23
|
+
message: "configuration file must contain a JSON object",
|
|
24
|
+
path: "$",
|
|
25
|
+
severity: "error",
|
|
26
|
+
source: "file",
|
|
27
|
+
});
|
|
28
|
+
return { values: {}, diagnostics };
|
|
29
|
+
}
|
|
30
|
+
return { values: parsed, diagnostics };
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -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
|
@@ -69,6 +69,14 @@ export { cacheSystemMessage, cacheLastN, cacheAtIndex, autoCache, supportsCacheC
|
|
|
69
69
|
export type { TokenEstimate, Tokenizer } from "./tokens/counter.js";
|
|
70
70
|
export type { CacheControl, CacheableMessage } from "./tokens/prompt-cache.js";
|
|
71
71
|
export { loadConfig, createConfig, validateConfig } from "./config/config.js";
|
|
72
|
+
export { resolveConfig } from "./config/config-resolver.js";
|
|
73
|
+
export { createDefaultsSource } from "./config/sources/defaults.js";
|
|
74
|
+
export { createEnvironmentSource } from "./config/sources/environment.js";
|
|
75
|
+
export { createFileSource } from "./config/sources/file.js";
|
|
76
|
+
export { createRuntimeSource } from "./config/sources/runtime.js";
|
|
77
|
+
export type { ConfigDiagnostic, ConfigResolutionOptions, ConfigSource, ConfigSourceKind, ConfigSourceResult, SafeProviderConfig, SafeSDKConfig, } from "./config/config-schema.js";
|
|
78
|
+
export type { ResolvedSDKConfig } from "./config/resolved-config.js";
|
|
79
|
+
export { budgetFromConfig, policyFromConfig } from "./config/resolved-config.js";
|
|
72
80
|
export type { SDKConfig } from "./config/schema.js";
|
|
73
81
|
export { DEFAULT_CONFIG } from "./config/schema.js";
|
|
74
82
|
export { buildPrompt, buildToolSection, buildEnvironmentSection, buildCodingAgentPrompt } from "./config/prompts.js";
|
|
@@ -77,7 +85,9 @@ export type { CredentialSource, CredentialProvider } from "./credentials/provide
|
|
|
77
85
|
export { validateBaseUrl } from "./security/url-guard.js";
|
|
78
86
|
export type { UrlGuardOptions, UrlGuardResult } from "./security/url-guard.js";
|
|
79
87
|
export { RequestSigner, signingMiddleware } from "./security/request-signer.js";
|
|
80
|
-
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";
|
|
81
91
|
export { redactPii, detectPii, createPiiRedactor } from "./security/pii-guard.js";
|
|
82
92
|
export type { PiiType, PiiMatch, PiiGuardConfig } from "./security/pii-guard.js";
|
|
83
93
|
export { AuditLogger, createRetentionPolicy } from "./security/audit-logger.js";
|
|
@@ -135,6 +145,10 @@ export type { Plugin, PluginRequestContext, PluginResponseContext, PluginErrorCo
|
|
|
135
145
|
export { PluginRegistry } from "./plugin/registry.js";
|
|
136
146
|
export { createRBACMiddleware, checkPermission } from "./security/rbac.js";
|
|
137
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";
|
|
138
152
|
export { CostAlertMonitor, createCostAlertBudget } from "./cost/alerts.js";
|
|
139
153
|
export type { AlertChannel, ThresholdConfig, CostAlert, CostAlertConfig } from "./cost/alerts.js";
|
|
140
154
|
export { runABTest } from "./features/eval/ab-test.js";
|
package/dist/index.js
CHANGED
|
@@ -50,6 +50,12 @@ export { estimateTokens, estimateMessageTokens, estimateToolTokens, estimateCost
|
|
|
50
50
|
export { cacheSystemMessage, cacheLastN, cacheAtIndex, autoCache, supportsCacheControl } from "./tokens/prompt-cache.js";
|
|
51
51
|
// ─── Config ───────────────────────────────────────────────────────────────
|
|
52
52
|
export { loadConfig, createConfig, validateConfig } from "./config/config.js";
|
|
53
|
+
export { resolveConfig } from "./config/config-resolver.js";
|
|
54
|
+
export { createDefaultsSource } from "./config/sources/defaults.js";
|
|
55
|
+
export { createEnvironmentSource } from "./config/sources/environment.js";
|
|
56
|
+
export { createFileSource } from "./config/sources/file.js";
|
|
57
|
+
export { createRuntimeSource } from "./config/sources/runtime.js";
|
|
58
|
+
export { budgetFromConfig, policyFromConfig } from "./config/resolved-config.js";
|
|
53
59
|
export { DEFAULT_CONFIG } from "./config/schema.js";
|
|
54
60
|
export { buildPrompt, buildToolSection, buildEnvironmentSection, buildCodingAgentPrompt } from "./config/prompts.js";
|
|
55
61
|
// ─── Credentials ────────────────────────────────────────────────────────────
|
|
@@ -57,6 +63,7 @@ export { DefaultCredentialProvider, getCredentialProvider, setCredentialProvider
|
|
|
57
63
|
// ─── Security (v0.9.3: SSRF guard, v0.14.0: HMAC signing, PII, audit) ──────
|
|
58
64
|
export { validateBaseUrl } from "./security/url-guard.js";
|
|
59
65
|
export { RequestSigner, signingMiddleware } from "./security/request-signer.js";
|
|
66
|
+
export { ReplayGuard, createReplayGuard } from "./security/replay-guard.js";
|
|
60
67
|
export { redactPii, detectPii, createPiiRedactor } from "./security/pii-guard.js";
|
|
61
68
|
export { AuditLogger, createRetentionPolicy } from "./security/audit-logger.js";
|
|
62
69
|
export { RateLimiter, createRateLimiter, RateLimiterRegistry } from "./security/rate-limiter.js";
|
|
@@ -104,6 +111,9 @@ export { createSSEStream, createSSEResponse, createObjectSSEStream, createObject
|
|
|
104
111
|
export { PluginRegistry } from "./plugin/registry.js";
|
|
105
112
|
// ─── RBAC (v3.0.0) ─────────────────────────────────────────────────────────
|
|
106
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";
|
|
107
117
|
// ─── Cost Alerts (v3.0.0) ──────────────────────────────────────────────────
|
|
108
118
|
export { CostAlertMonitor, createCostAlertBudget } from "./cost/alerts.js";
|
|
109
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()) {
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Authorization contracts and evaluation
|
|
3
|
+
*
|
|
4
|
+
* This module owns the authorization vocabulary for the SDK: role and policy
|
|
5
|
+
* shapes, the request context a decision is made against, the enforcement
|
|
6
|
+
* modes, diagnostics, and pure policy evaluation.
|
|
7
|
+
*
|
|
8
|
+
* Enforcement modes:
|
|
9
|
+
*
|
|
10
|
+
* - `"permissive"` (default) allows a request whose context cannot be fully
|
|
11
|
+
* resolved and records a diagnostic. Explicit denials (disallowed provider,
|
|
12
|
+
* model, or tool) and rate-limit rejections still return 403/429.
|
|
13
|
+
* - `"strict"` denies with 403 any request whose context cannot be resolved,
|
|
14
|
+
* including a missing role, an unknown role, an unidentifiable provider, or
|
|
15
|
+
* a resolver that throws.
|
|
16
|
+
*
|
|
17
|
+
* The pure evaluators here never perform I/O and never construct a `Response`;
|
|
18
|
+
* {@link createRBACMiddleware} composes them with transport concerns.
|
|
19
|
+
*/
|
|
20
|
+
import type { MiddlewareContext } from "../middleware/middleware.js";
|
|
21
|
+
import type { AuditLogger } from "./audit-logger.js";
|
|
22
|
+
import type { RateLimiterRegistry } from "./rate-limiter.js";
|
|
23
|
+
/** How the middleware treats a request context it cannot fully resolve. */
|
|
24
|
+
export type AuthorizationEnforcement = "permissive" | "strict";
|
|
25
|
+
/** A role definition with access constraints. */
|
|
26
|
+
export interface RBACRole {
|
|
27
|
+
/** Role name. Must match the key it is registered under. */
|
|
28
|
+
name: string;
|
|
29
|
+
/** Allowed provider names (empty or absent = all providers allowed) */
|
|
30
|
+
allowedProviders?: string[];
|
|
31
|
+
/** Allowed model patterns; a trailing `*` is a prefix match (absent = all) */
|
|
32
|
+
allowedModels?: string[];
|
|
33
|
+
/** Maximum tokens per request (undefined = no limit) */
|
|
34
|
+
maxTokensPerRequest?: number;
|
|
35
|
+
/** Maximum budget per session in dollars (undefined = no limit) */
|
|
36
|
+
maxBudgetPerSession?: number;
|
|
37
|
+
/** Per-role request rate limit */
|
|
38
|
+
rateLimit?: {
|
|
39
|
+
/** Maximum requests within the window */
|
|
40
|
+
maxRequests: number;
|
|
41
|
+
/** Window duration in milliseconds */
|
|
42
|
+
windowMs: number;
|
|
43
|
+
};
|
|
44
|
+
/** Allowed tool names (empty or absent = all tools allowed) */
|
|
45
|
+
allowedTools?: string[];
|
|
46
|
+
/** Tool names that are always denied for this role */
|
|
47
|
+
deniedTools?: string[];
|
|
48
|
+
}
|
|
49
|
+
/** Authorization configuration. */
|
|
50
|
+
export interface RBACConfig {
|
|
51
|
+
/** Map of role name to role definition */
|
|
52
|
+
roles: Record<string, RBACRole>;
|
|
53
|
+
/** Role applied when no explicit role is resolved (default: `"default"`) */
|
|
54
|
+
defaultRole?: string;
|
|
55
|
+
/** How to treat an unresolvable request context (default: `"permissive"`) */
|
|
56
|
+
enforcement?: AuthorizationEnforcement;
|
|
57
|
+
}
|
|
58
|
+
/** The facts an authorization decision is made against. */
|
|
59
|
+
export interface RBACRequestContext {
|
|
60
|
+
/** Provider name, or `""` when it could not be identified */
|
|
61
|
+
provider: string;
|
|
62
|
+
/** Model name, or `""` when the request did not carry one */
|
|
63
|
+
model: string;
|
|
64
|
+
/** Requested token count, when the body carried a numeric `max_tokens` */
|
|
65
|
+
tokenCount?: number;
|
|
66
|
+
/** Tool name, when the request is a tool invocation */
|
|
67
|
+
toolName?: string;
|
|
68
|
+
}
|
|
69
|
+
/** Spend attributed to a role, used to enforce `maxBudgetPerSession`. */
|
|
70
|
+
export interface AuthorizationBudgetView {
|
|
71
|
+
/** Dollars already spent for this role and user */
|
|
72
|
+
spent: number;
|
|
73
|
+
/** Dollar ceiling; when absent the role's own limit is used */
|
|
74
|
+
limit?: number;
|
|
75
|
+
}
|
|
76
|
+
/** Supplies a budget view so a declared `maxBudgetPerSession` can be enforced. */
|
|
77
|
+
export type ResolveAuthorizationBudget = (input: {
|
|
78
|
+
ctx: MiddlewareContext;
|
|
79
|
+
role: RBACRole;
|
|
80
|
+
roleName: string;
|
|
81
|
+
userId: string | null;
|
|
82
|
+
}) => AuthorizationBudgetView | null | undefined;
|
|
83
|
+
/** Resolves the provider name implied by a request URL. */
|
|
84
|
+
export type ResolveProviderByUrl = (url: string) => string | null | undefined;
|
|
85
|
+
/** Options accepted by the authorization middleware. */
|
|
86
|
+
export interface AuthorizationOptions {
|
|
87
|
+
/** Enforcement mode override; defaults to `config.enforcement`. */
|
|
88
|
+
enforcement?: AuthorizationEnforcement;
|
|
89
|
+
/**
|
|
90
|
+
* Resolve the caller's role name from the request. When omitted, the
|
|
91
|
+
* middleware falls back to `config.defaultRole ?? "default"`, which is the
|
|
92
|
+
* behavior of every release before v3.4.0.
|
|
93
|
+
*/
|
|
94
|
+
resolveRole?: (ctx: MiddlewareContext) => string | null | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* Resolve the request context. When omitted, the provider is resolved from
|
|
97
|
+
* the request URL and `model` / `max_tokens` are read from a JSON body.
|
|
98
|
+
*/
|
|
99
|
+
resolveRequest?: (ctx: MiddlewareContext) => RBACRequestContext | null | undefined;
|
|
100
|
+
/** Resolves a provider name from a request URL. */
|
|
101
|
+
resolveProviderByUrl?: ResolveProviderByUrl;
|
|
102
|
+
/** Supplies a budget view for `maxBudgetPerSession` enforcement. */
|
|
103
|
+
resolveBudget?: ResolveAuthorizationBudget;
|
|
104
|
+
/** Audit logger for denial and rate-limit events. */
|
|
105
|
+
auditLogger?: AuditLogger;
|
|
106
|
+
/** Rate limiter registry (created automatically if not provided). */
|
|
107
|
+
rateLimiters?: RateLimiterRegistry;
|
|
108
|
+
/** Clock injection for deterministic tests. */
|
|
109
|
+
now?: () => number;
|
|
110
|
+
/** Receives every diagnostic in decision order. */
|
|
111
|
+
onDiagnostic?: (diagnostic: AuthorizationDiagnostic) => void;
|
|
112
|
+
}
|
|
113
|
+
export type AuthorizationDiagnosticSeverity = "info" | "warning" | "error";
|
|
114
|
+
/**
|
|
115
|
+
* A redacted note about an authorization decision or policy problem. Messages
|
|
116
|
+
* never contain credential material.
|
|
117
|
+
*/
|
|
118
|
+
export interface AuthorizationDiagnostic {
|
|
119
|
+
code: string;
|
|
120
|
+
message: string;
|
|
121
|
+
path: string;
|
|
122
|
+
severity: AuthorizationDiagnosticSeverity;
|
|
123
|
+
role?: string;
|
|
124
|
+
userId?: string;
|
|
125
|
+
}
|
|
126
|
+
/** Result of evaluating a single request against a single role. */
|
|
127
|
+
export interface AuthorizationVerdict {
|
|
128
|
+
allow: boolean;
|
|
129
|
+
status?: 403 | 429;
|
|
130
|
+
reason?: string;
|
|
131
|
+
retryAfterMs?: number;
|
|
132
|
+
role?: string;
|
|
133
|
+
/**
|
|
134
|
+
* True when the verdict came from a context the middleware could not fully
|
|
135
|
+
* resolve rather than from an explicit policy violation.
|
|
136
|
+
*/
|
|
137
|
+
unresolved: boolean;
|
|
138
|
+
}
|
|
139
|
+
/** An array whose every element is a non-empty string. Empty arrays are valid. */
|
|
140
|
+
export declare function isStringArray(value: unknown): value is string[];
|
|
141
|
+
/**
|
|
142
|
+
* Validate an `rbac` configuration block. Returns one error diagnostic per
|
|
143
|
+
* problem so the configuration resolver can reject a malformed policy at
|
|
144
|
+
* construction time instead of letting it degrade to "no restrictions" at
|
|
145
|
+
* request time.
|
|
146
|
+
*/
|
|
147
|
+
export declare function validateRbacConfig(value: unknown, basePath?: string): AuthorizationDiagnostic[];
|
|
148
|
+
/**
|
|
149
|
+
* Default request-context resolution.
|
|
150
|
+
*
|
|
151
|
+
* Provider identity comes from the request URL, because no SDK adapter puts
|
|
152
|
+
* `provider` in the request body. `model`, `max_tokens`, and an optional tool
|
|
153
|
+
* name are read from a JSON body when one is present. Returns `null` when
|
|
154
|
+
* nothing identifying could be determined.
|
|
155
|
+
*/
|
|
156
|
+
export declare function resolveRequestFromContext(ctx: MiddlewareContext, resolveProviderByUrl?: ResolveProviderByUrl): RBACRequestContext | null;
|
|
157
|
+
/**
|
|
158
|
+
* Evaluate a resolved request against one role. Pure: performs no I/O and
|
|
159
|
+
* reports policy problems through `report` rather than throwing.
|
|
160
|
+
*/
|
|
161
|
+
export declare function evaluateRoleRequest(input: {
|
|
162
|
+
role: RBACRole;
|
|
163
|
+
roleName: string;
|
|
164
|
+
request: RBACRequestContext;
|
|
165
|
+
enforcement: AuthorizationEnforcement;
|
|
166
|
+
report: (diagnostic: AuthorizationDiagnostic) => void;
|
|
167
|
+
}): AuthorizationVerdict;
|
|
168
|
+
/**
|
|
169
|
+
* Full authorization decision for one request, excluding rate limiting, which
|
|
170
|
+
* the middleware applies because it mutates limiter state.
|
|
171
|
+
*/
|
|
172
|
+
export declare function evaluateAuthorization(input: {
|
|
173
|
+
role: RBACRole | null;
|
|
174
|
+
roleName: string | null;
|
|
175
|
+
request: RBACRequestContext | null;
|
|
176
|
+
enforcement: AuthorizationEnforcement;
|
|
177
|
+
budget?: AuthorizationBudgetView | null | undefined;
|
|
178
|
+
userId: string | null;
|
|
179
|
+
report: (diagnostic: AuthorizationDiagnostic) => void;
|
|
180
|
+
}): AuthorizationVerdict;
|