@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.
@@ -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;
@@ -0,0 +1,355 @@
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
+ // ─── Small helpers ──────────────────────────────────────────────────────────
21
+ function isPlainObject(value) {
22
+ return !!value && typeof value === "object" && !Array.isArray(value);
23
+ }
24
+ /** An array whose every element is a non-empty string. Empty arrays are valid. */
25
+ export function isStringArray(value) {
26
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0);
27
+ }
28
+ function isFiniteNonNegative(value) {
29
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
30
+ }
31
+ // ─── Configuration validation ───────────────────────────────────────────────
32
+ /**
33
+ * Validate an `rbac` configuration block. Returns one error diagnostic per
34
+ * problem so the configuration resolver can reject a malformed policy at
35
+ * construction time instead of letting it degrade to "no restrictions" at
36
+ * request time.
37
+ */
38
+ export function validateRbacConfig(value, basePath = "rbac") {
39
+ const issues = [];
40
+ const add = (code, path, message) => {
41
+ issues.push({ code, path, message, severity: "error" });
42
+ };
43
+ if (!isPlainObject(value)) {
44
+ add("RBAC_INVALID_ROLES", basePath, `${basePath} must be an object`);
45
+ return issues;
46
+ }
47
+ const roles = value.roles;
48
+ if (!isPlainObject(roles)) {
49
+ add("RBAC_INVALID_ROLES", `${basePath}.roles`, `${basePath}.roles must be an object`);
50
+ return issues;
51
+ }
52
+ if (Object.keys(roles).length === 0) {
53
+ add("RBAC_INVALID_ROLES", `${basePath}.roles`, `${basePath}.roles must define at least one role`);
54
+ }
55
+ for (const [key, raw] of Object.entries(roles)) {
56
+ const path = `${basePath}.roles.${key}`;
57
+ if (!isPlainObject(raw)) {
58
+ add("RBAC_INVALID_ROLE", path, `role "${key}" must be an object`);
59
+ continue;
60
+ }
61
+ const role = raw;
62
+ if (typeof role.name !== "string" || role.name.length === 0) {
63
+ add("RBAC_INVALID_ROLE", `${path}.name`, `role "${key}" must declare a non-empty name`);
64
+ }
65
+ else if (role.name !== key) {
66
+ add("RBAC_INVALID_ROLE", `${path}.name`, `role name "${role.name}" must match its key "${key}"`);
67
+ }
68
+ for (const field of ["allowedProviders", "allowedModels", "allowedTools", "deniedTools"]) {
69
+ const list = role[field];
70
+ if (list === undefined)
71
+ continue;
72
+ if (!isStringArray(list)) {
73
+ add("RBAC_INVALID_RESTRICTION_LIST", `${path}.${field}`, `${field} must be an array of non-empty strings`);
74
+ }
75
+ }
76
+ for (const field of ["maxTokensPerRequest", "maxBudgetPerSession"]) {
77
+ const limit = role[field];
78
+ if (limit === undefined)
79
+ continue;
80
+ if (!isFiniteNonNegative(limit)) {
81
+ add("RBAC_INVALID_NUMERIC_LIMIT", `${path}.${field}`, `${field} must be a finite non-negative number`);
82
+ }
83
+ }
84
+ const rateLimit = role.rateLimit;
85
+ if (rateLimit !== undefined) {
86
+ const valid = isPlainObject(rateLimit) &&
87
+ typeof rateLimit.maxRequests === "number" &&
88
+ Number.isFinite(rateLimit.maxRequests) &&
89
+ rateLimit.maxRequests >= 1 &&
90
+ typeof rateLimit.windowMs === "number" &&
91
+ Number.isFinite(rateLimit.windowMs) &&
92
+ rateLimit.windowMs >= 1;
93
+ if (!valid) {
94
+ add("RBAC_INVALID_RATE_LIMIT", `${path}.rateLimit`, "rateLimit requires maxRequests >= 1 and windowMs >= 1");
95
+ }
96
+ }
97
+ if (isStringArray(role.allowedTools) && isStringArray(role.deniedTools)) {
98
+ const denied = new Set(role.deniedTools);
99
+ if (role.allowedTools.some((tool) => denied.has(tool))) {
100
+ add("RBAC_TOOL_POLICY_CONFLICT", `${path}.allowedTools`, "allowedTools and deniedTools must not overlap");
101
+ }
102
+ }
103
+ }
104
+ const enforcement = value.enforcement;
105
+ if (enforcement !== undefined && enforcement !== "permissive" && enforcement !== "strict") {
106
+ add("RBAC_INVALID_ENFORCEMENT", `${basePath}.enforcement`, 'enforcement must be "permissive" or "strict"');
107
+ }
108
+ const defaultRole = value.defaultRole;
109
+ if (defaultRole !== undefined) {
110
+ if (typeof defaultRole !== "string" || defaultRole.length === 0) {
111
+ add("RBAC_UNKNOWN_DEFAULT_ROLE", `${basePath}.defaultRole`, "defaultRole must be a non-empty string");
112
+ }
113
+ else if (!(defaultRole in roles)) {
114
+ add("RBAC_UNKNOWN_DEFAULT_ROLE", `${basePath}.defaultRole`, `defaultRole "${defaultRole}" is not defined in ${basePath}.roles`);
115
+ }
116
+ }
117
+ return issues;
118
+ }
119
+ // ─── Request context resolution ─────────────────────────────────────────────
120
+ /**
121
+ * Default request-context resolution.
122
+ *
123
+ * Provider identity comes from the request URL, because no SDK adapter puts
124
+ * `provider` in the request body. `model`, `max_tokens`, and an optional tool
125
+ * name are read from a JSON body when one is present. Returns `null` when
126
+ * nothing identifying could be determined.
127
+ */
128
+ export function resolveRequestFromContext(ctx, resolveProviderByUrl) {
129
+ let provider = "";
130
+ if (resolveProviderByUrl) {
131
+ try {
132
+ provider = resolveProviderByUrl(ctx.url) ?? "";
133
+ }
134
+ catch {
135
+ provider = "";
136
+ }
137
+ }
138
+ let model = "";
139
+ let tokenCount;
140
+ let toolName;
141
+ const body = ctx.init.body;
142
+ if (typeof body === "string") {
143
+ try {
144
+ const parsed = JSON.parse(body);
145
+ if (typeof parsed.provider === "string" && parsed.provider.length > 0) {
146
+ provider = parsed.provider;
147
+ }
148
+ if (typeof parsed.model === "string")
149
+ model = parsed.model;
150
+ if (typeof parsed.max_tokens === "number" && Number.isFinite(parsed.max_tokens)) {
151
+ tokenCount = parsed.max_tokens;
152
+ }
153
+ const tool = parsed.tool ?? parsed.tool_name ?? parsed.name;
154
+ if (typeof tool === "string" && tool.length > 0)
155
+ toolName = tool;
156
+ }
157
+ catch {
158
+ // Body is not JSON; the URL-derived provider is still usable.
159
+ }
160
+ }
161
+ if (provider.length === 0 && model.length === 0)
162
+ return null;
163
+ return { provider, model, tokenCount, toolName };
164
+ }
165
+ // ─── Policy evaluation ──────────────────────────────────────────────────────
166
+ function deny(reason, role) {
167
+ return { allow: false, status: 403, reason, role, unresolved: false };
168
+ }
169
+ function matchesModel(model, patterns) {
170
+ return patterns.some((pattern) => pattern.endsWith("*") ? model.startsWith(pattern.slice(0, -1)) : model === pattern);
171
+ }
172
+ /**
173
+ * Evaluate a resolved request against one role. Pure: performs no I/O and
174
+ * reports policy problems through `report` rather than throwing.
175
+ */
176
+ export function evaluateRoleRequest(input) {
177
+ const { role, roleName, request, enforcement, report } = input;
178
+ const unresolvedCode = "RBAC_UNRESOLVED_CONTEXT";
179
+ // A declared restriction whose subject could not be identified cannot be
180
+ // evaluated. Permissive mode skips the check and says so; strict mode denies.
181
+ const handleUnresolved = (field, subject) => {
182
+ report({
183
+ code: unresolvedCode,
184
+ message: `cannot evaluate ${field} for role "${roleName}" because the request did not identify a ${subject}`,
185
+ path: field,
186
+ severity: "warning",
187
+ role: roleName,
188
+ });
189
+ return enforcement === "strict"
190
+ ? deny(`request did not identify a ${subject} required by role "${roleName}"`, roleName)
191
+ : null;
192
+ };
193
+ if (role.allowedProviders !== undefined) {
194
+ if (!isStringArray(role.allowedProviders)) {
195
+ report({
196
+ code: "RBAC_INVALID_POLICY",
197
+ message: `allowedProviders for role "${roleName}" must be an array of strings`,
198
+ path: "allowedProviders",
199
+ severity: "error",
200
+ role: roleName,
201
+ });
202
+ return deny(`policy for role "${roleName}" is invalid`, roleName);
203
+ }
204
+ if (role.allowedProviders.length > 0) {
205
+ if (request.provider.length === 0) {
206
+ const handled = handleUnresolved("allowedProviders", "provider");
207
+ if (handled)
208
+ return handled;
209
+ }
210
+ else if (!role.allowedProviders.includes(request.provider)) {
211
+ return deny(`Provider "${request.provider}" is not allowed for role "${roleName}". Allowed: ${role.allowedProviders.join(", ")}`, roleName);
212
+ }
213
+ }
214
+ }
215
+ if (role.allowedModels !== undefined) {
216
+ if (!isStringArray(role.allowedModels)) {
217
+ report({
218
+ code: "RBAC_INVALID_POLICY",
219
+ message: `allowedModels for role "${roleName}" must be an array of strings`,
220
+ path: "allowedModels",
221
+ severity: "error",
222
+ role: roleName,
223
+ });
224
+ return deny(`policy for role "${roleName}" is invalid`, roleName);
225
+ }
226
+ if (role.allowedModels.length > 0) {
227
+ if (request.model.length === 0) {
228
+ const handled = handleUnresolved("allowedModels", "model");
229
+ if (handled)
230
+ return handled;
231
+ }
232
+ else if (!matchesModel(request.model, role.allowedModels)) {
233
+ return deny(`Model "${request.model}" is not allowed for role "${roleName}". Allowed: ${role.allowedModels.join(", ")}`, roleName);
234
+ }
235
+ }
236
+ }
237
+ if (role.allowedTools !== undefined && !isStringArray(role.allowedTools)) {
238
+ report({
239
+ code: "RBAC_INVALID_POLICY",
240
+ message: `allowedTools for role "${roleName}" must be an array of strings`,
241
+ path: "allowedTools",
242
+ severity: "error",
243
+ role: roleName,
244
+ });
245
+ return deny(`policy for role "${roleName}" is invalid`, roleName);
246
+ }
247
+ if (role.deniedTools !== undefined && !isStringArray(role.deniedTools)) {
248
+ report({
249
+ code: "RBAC_INVALID_POLICY",
250
+ message: `deniedTools for role "${roleName}" must be an array of strings`,
251
+ path: "deniedTools",
252
+ severity: "error",
253
+ role: roleName,
254
+ });
255
+ return deny(`policy for role "${roleName}" is invalid`, roleName);
256
+ }
257
+ if (request.toolName !== undefined && request.toolName.length > 0) {
258
+ if (role.deniedTools?.includes(request.toolName)) {
259
+ return deny(`Tool "${request.toolName}" is denied for role "${roleName}"`, roleName);
260
+ }
261
+ if (role.allowedTools !== undefined &&
262
+ role.allowedTools.length > 0 &&
263
+ !role.allowedTools.includes(request.toolName)) {
264
+ return deny(`Tool "${request.toolName}" is not allowed for role "${roleName}". Allowed: ${role.allowedTools.join(", ")}`, roleName);
265
+ }
266
+ }
267
+ if (role.maxTokensPerRequest !== undefined) {
268
+ if (!isFiniteNonNegative(role.maxTokensPerRequest)) {
269
+ report({
270
+ code: "RBAC_INVALID_POLICY",
271
+ message: `maxTokensPerRequest for role "${roleName}" must be a finite non-negative number`,
272
+ path: "maxTokensPerRequest",
273
+ severity: "error",
274
+ role: roleName,
275
+ });
276
+ return deny(`policy for role "${roleName}" is invalid`, roleName);
277
+ }
278
+ if (request.tokenCount !== undefined && request.tokenCount > role.maxTokensPerRequest) {
279
+ return deny(`Token count ${request.tokenCount} exceeds limit of ${role.maxTokensPerRequest} for role "${roleName}"`, roleName);
280
+ }
281
+ }
282
+ return { allow: true, role: roleName, unresolved: false };
283
+ }
284
+ /**
285
+ * Full authorization decision for one request, excluding rate limiting, which
286
+ * the middleware applies because it mutates limiter state.
287
+ */
288
+ export function evaluateAuthorization(input) {
289
+ const { role, roleName, request, enforcement, budget, userId, report } = input;
290
+ if (role === null || roleName === null) {
291
+ report({
292
+ code: "RBAC_UNRESOLVED_ROLE",
293
+ message: userId === null
294
+ ? "no request identity was resolved and no default role is configured"
295
+ : `no role could be resolved for the request`,
296
+ path: "defaultRole",
297
+ severity: "warning",
298
+ userId: userId ?? undefined,
299
+ });
300
+ return enforcement === "strict"
301
+ ? { allow: false, status: 403, reason: "no role could be resolved for this request", unresolved: true }
302
+ : { allow: true, unresolved: true };
303
+ }
304
+ if (role.maxBudgetPerSession !== undefined) {
305
+ const limit = budget?.limit ?? role.maxBudgetPerSession;
306
+ if (budget === null || budget === undefined) {
307
+ report({
308
+ code: "RBAC_BUDGET_NOT_ENFORCED",
309
+ message: `role "${roleName}" declares maxBudgetPerSession but no budget source is configured, so the limit is not enforced`,
310
+ path: "maxBudgetPerSession",
311
+ severity: "warning",
312
+ role: roleName,
313
+ userId: userId ?? undefined,
314
+ });
315
+ if (enforcement === "strict") {
316
+ return {
317
+ allow: false,
318
+ status: 403,
319
+ reason: `role "${roleName}" requires a budget source that is not configured`,
320
+ role: roleName,
321
+ unresolved: true,
322
+ };
323
+ }
324
+ }
325
+ else if (budget.spent >= limit) {
326
+ return {
327
+ allow: false,
328
+ status: 403,
329
+ reason: `Spend of ${budget.spent} reaches the session budget limit of ${limit} for role "${roleName}"`,
330
+ role: roleName,
331
+ unresolved: false,
332
+ };
333
+ }
334
+ }
335
+ if (request === null) {
336
+ report({
337
+ code: "RBAC_UNRESOLVED_CONTEXT",
338
+ message: `request context could not be resolved, so provider and model restrictions for role "${roleName}" were not evaluated`,
339
+ path: "$",
340
+ severity: "warning",
341
+ role: roleName,
342
+ userId: userId ?? undefined,
343
+ });
344
+ return enforcement === "strict"
345
+ ? {
346
+ allow: false,
347
+ status: 403,
348
+ reason: `request context could not be resolved for role "${roleName}"`,
349
+ role: roleName,
350
+ unresolved: true,
351
+ }
352
+ : { allow: true, role: roleName, unresolved: true };
353
+ }
354
+ return evaluateRoleRequest({ role, roleName, request, enforcement, report });
355
+ }
@@ -66,6 +66,17 @@ export declare class RateLimiter {
66
66
  allowed: boolean;
67
67
  retryAfterMs: number;
68
68
  };
69
+ /**
70
+ * Check availability and consume tokens in one step.
71
+ *
72
+ * Unlike {@link acquire}, this decrements the bucket when the request is
73
+ * allowed, so repeated calls are eventually throttled. Use this when the
74
+ * decision to allow must itself count against the limit.
75
+ */
76
+ tryConsume(cost?: number): {
77
+ allowed: boolean;
78
+ retryAfterMs: number;
79
+ };
69
80
  /**
70
81
  * Consume tokens for a request. Throws if not enough tokens are available.
71
82
  * @throws {Error} when rate limit is exceeded
@@ -60,6 +60,20 @@ export class RateLimiter {
60
60
  const retryAfterMs = Math.ceil((deficit / this._refillRate) * 1000);
61
61
  return { allowed: false, retryAfterMs };
62
62
  }
63
+ /**
64
+ * Check availability and consume tokens in one step.
65
+ *
66
+ * Unlike {@link acquire}, this decrements the bucket when the request is
67
+ * allowed, so repeated calls are eventually throttled. Use this when the
68
+ * decision to allow must itself count against the limit.
69
+ */
70
+ tryConsume(cost) {
71
+ const result = this.acquire(cost);
72
+ if (result.allowed) {
73
+ this._tokens -= this._computeCost(cost);
74
+ }
75
+ return result;
76
+ }
63
77
  /**
64
78
  * Consume tokens for a request. Throws if not enough tokens are available.
65
79
  * @throws {Error} when rate limit is exceeded
@@ -1,41 +1,22 @@
1
1
  /**
2
2
  * @hilbras/sdk — Role-Based Access Control (RBAC)
3
3
  *
4
- * Provides role definitions, permission checking, and RBAC middleware
5
- * for controlling which providers, models, and features each user can access.
4
+ * Provides role definitions, permission checking, and RBAC middleware for
5
+ * controlling which providers, models, and tools each caller may use.
6
+ *
7
+ * The policy vocabulary and the pure evaluators live in
8
+ * `security/authorization.ts`. This module keeps the historical public surface
9
+ * (`RBACRole`, `RBACConfig`, `checkPermission`, `createRBACMiddleware`) and
10
+ * adds transport concerns — rate limiting, audit attribution, and response
11
+ * construction.
6
12
  */
7
13
  import type { Middleware, MiddlewareContext } from "../middleware/middleware.js";
8
- import { RateLimiterRegistry } from "./rate-limiter.js";
9
- import { AuditLogger } from "./audit-logger.js";
10
- /** A role definition with access constraints */
11
- export interface RBACRole {
12
- /** Role name */
13
- name: string;
14
- /** Allowed provider names (empty = all providers allowed) */
15
- allowedProviders?: string[];
16
- /** Allowed model patterns (empty = all models allowed) */
17
- allowedModels?: string[];
18
- /** Maximum tokens per request (undefined = no limit) */
19
- maxTokensPerRequest?: number;
20
- /** Maximum budget per session in dollars (undefined = no limit) */
21
- maxBudgetPerSession?: number;
22
- /** Rate limit configuration */
23
- rateLimit?: {
24
- /** Maximum requests within the window */
25
- maxRequests: number;
26
- /** Window duration in milliseconds */
27
- windowMs: number;
28
- };
29
- }
14
+ import { type AuthorizationOptions, type RBACConfig, type RBACRole } from "./authorization.js";
15
+ export type { RBACRole, RBACConfig } from "./authorization.js";
16
+ export type { AuthorizationBudgetView, AuthorizationDiagnostic, AuthorizationEnforcement, AuthorizationOptions, AuthorizationVerdict, RBACRequestContext, } from "./authorization.js";
17
+ export { evaluateAuthorization, evaluateRoleRequest, resolveRequestFromContext, validateRbacConfig, } from "./authorization.js";
30
18
  /** @deprecated Use RBACRole instead */
31
19
  export type Role = RBACRole;
32
- /** RBAC configuration */
33
- export interface RBACConfig {
34
- /** Map of role name to role definition */
35
- roles: Record<string, RBACRole>;
36
- /** Default role for users without an explicit role */
37
- defaultRole?: string;
38
- }
39
20
  /** Result of a permission check */
40
21
  export interface PermissionCheck {
41
22
  /** Whether the action is allowed */
@@ -47,14 +28,24 @@ export interface PermissionCheck {
47
28
  }
48
29
  /**
49
30
  * Check if a role has permission to use a specific provider/model.
31
+ *
32
+ * A role that declares no restrictions allows everything. A role whose policy
33
+ * is malformed denies, because an invalid policy must never be treated as an
34
+ * absent one.
50
35
  */
51
36
  export declare function checkPermission(role: RBACRole, provider: string, model: string, tokenCount?: number): PermissionCheck;
52
37
  /**
53
38
  * Create RBAC middleware that enforces role-based access control.
54
39
  *
55
- * The `getUserId` callback extracts the user identity from the request
56
- * (e.g., from an auth header, API key, or session). The middleware
57
- * checks the user's role against the requested provider/model.
40
+ * The `getUserId` callback extracts the caller identity from the request. Pass
41
+ * `options.resolveRole` to map that identity onto a role name; without it the
42
+ * middleware applies `config.defaultRole`, which is the behavior of every
43
+ * release before v3.4.0.
44
+ *
45
+ * Enforcement is `"permissive"` by default: a request whose context cannot be
46
+ * resolved is allowed and recorded as a diagnostic, while explicit policy
47
+ * violations and rate-limit rejections still return 403/429. Set
48
+ * `enforcement: "strict"` to deny any unresolvable context with 403.
58
49
  *
59
50
  * @example
60
51
  * ```ts
@@ -62,19 +53,16 @@ export declare function checkPermission(role: RBACRole, provider: string, model:
62
53
  * {
63
54
  * roles: {
64
55
  * viewer: { name: "viewer", allowedProviders: ["openai"], maxTokensPerRequest: 4096 },
65
- * admin: { name: "admin" }, // no restrictions
56
+ * admin: { name: "admin" },
66
57
  * },
67
58
  * defaultRole: "viewer",
59
+ * enforcement: "strict",
68
60
  * },
69
61
  * (ctx) => extractUserIdFromHeader(ctx.init),
62
+ * { resolveRole: (ctx) => roleForUser(extractUserIdFromHeader(ctx.init)) },
70
63
  * );
71
64
  *
72
65
  * const client = new HilbrasClient({ middleware: rbacMiddleware });
73
66
  * ```
74
67
  */
75
- export declare function createRBACMiddleware(config: RBACConfig, getUserId: (ctx: MiddlewareContext) => string | null, options?: {
76
- /** Audit logger for access-denied events */
77
- auditLogger?: AuditLogger;
78
- /** Rate limiter registry (created automatically if not provided) */
79
- rateLimiters?: RateLimiterRegistry;
80
- }): Middleware;
68
+ export declare function createRBACMiddleware(config: RBACConfig, getUserId: (ctx: MiddlewareContext) => string | null, options?: AuthorizationOptions): Middleware;