@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.
@@ -1,56 +1,56 @@
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 { RateLimiterRegistry } from "./rate-limiter.js";
14
+ import { evaluateAuthorization, resolveRequestFromContext, } from "./authorization.js";
15
+ export { evaluateAuthorization, evaluateRoleRequest, resolveRequestFromContext, validateRbacConfig, } from "./authorization.js";
8
16
  /**
9
17
  * Check if a role has permission to use a specific provider/model.
18
+ *
19
+ * A role that declares no restrictions allows everything. A role whose policy
20
+ * is malformed denies, because an invalid policy must never be treated as an
21
+ * absent one.
10
22
  */
11
23
  export function checkPermission(role, provider, model, tokenCount) {
12
- // Check provider access
13
- if (role.allowedProviders?.length && !role.allowedProviders.includes(provider)) {
14
- return {
15
- allowed: false,
16
- reason: `Provider "${provider}" is not allowed for role "${role.name}". Allowed: ${role.allowedProviders.join(", ")}`,
17
- role: role.name,
18
- };
19
- }
20
- // Check model access
21
- if (role.allowedModels?.length) {
22
- const modelAllowed = role.allowedModels.some((pattern) => {
23
- if (pattern.endsWith("*")) {
24
- return model.startsWith(pattern.slice(0, -1));
25
- }
26
- return model === pattern;
27
- });
28
- if (!modelAllowed) {
29
- return {
30
- allowed: false,
31
- reason: `Model "${model}" is not allowed for role "${role.name}". Allowed: ${role.allowedModels.join(", ")}`,
32
- role: role.name,
33
- };
34
- }
35
- }
36
- // Check token limit
37
- if (role.maxTokensPerRequest !== undefined && tokenCount !== undefined) {
38
- if (tokenCount > role.maxTokensPerRequest) {
39
- return {
40
- allowed: false,
41
- reason: `Token count ${tokenCount} exceeds limit of ${role.maxTokensPerRequest} for role "${role.name}"`,
42
- role: role.name,
43
- };
44
- }
45
- }
46
- return { allowed: true, role: role.name };
24
+ const verdict = evaluateAuthorization({
25
+ role,
26
+ roleName: role.name,
27
+ request: { provider, model, tokenCount },
28
+ enforcement: "permissive",
29
+ userId: null,
30
+ report: () => { },
31
+ });
32
+ if (verdict.allow)
33
+ return { allowed: true, role: role.name };
34
+ return { allowed: false, reason: verdict.reason, role: role.name };
35
+ }
36
+ function jsonResponse(status, payload, headers) {
37
+ return new Response(JSON.stringify(payload), {
38
+ status,
39
+ headers: { "Content-Type": "application/json", ...headers },
40
+ });
47
41
  }
48
42
  /**
49
43
  * Create RBAC middleware that enforces role-based access control.
50
44
  *
51
- * The `getUserId` callback extracts the user identity from the request
52
- * (e.g., from an auth header, API key, or session). The middleware
53
- * checks the user's role against the requested provider/model.
45
+ * The `getUserId` callback extracts the caller identity from the request. Pass
46
+ * `options.resolveRole` to map that identity onto a role name; without it the
47
+ * middleware applies `config.defaultRole`, which is the behavior of every
48
+ * release before v3.4.0.
49
+ *
50
+ * Enforcement is `"permissive"` by default: a request whose context cannot be
51
+ * resolved is allowed and recorded as a diagnostic, while explicit policy
52
+ * violations and rate-limit rejections still return 403/429. Set
53
+ * `enforcement: "strict"` to deny any unresolvable context with 403.
54
54
  *
55
55
  * @example
56
56
  * ```ts
@@ -58,11 +58,13 @@ export function checkPermission(role, provider, model, tokenCount) {
58
58
  * {
59
59
  * roles: {
60
60
  * viewer: { name: "viewer", allowedProviders: ["openai"], maxTokensPerRequest: 4096 },
61
- * admin: { name: "admin" }, // no restrictions
61
+ * admin: { name: "admin" },
62
62
  * },
63
63
  * defaultRole: "viewer",
64
+ * enforcement: "strict",
64
65
  * },
65
66
  * (ctx) => extractUserIdFromHeader(ctx.init),
67
+ * { resolveRole: (ctx) => roleForUser(extractUserIdFromHeader(ctx.init)) },
66
68
  * );
67
69
  *
68
70
  * const client = new HilbrasClient({ middleware: rbacMiddleware });
@@ -72,67 +74,147 @@ export function createRBACMiddleware(config, getUserId, options) {
72
74
  const rateLimiters = options?.rateLimiters ?? new RateLimiterRegistry();
73
75
  const auditLogger = options?.auditLogger;
74
76
  return async (ctx) => {
75
- const userId = getUserId(ctx);
76
- // If no user ID, apply default role or allow through
77
- const roleId = config.defaultRole ?? "default";
78
- const role = config.roles[roleId];
79
- if (!role) {
80
- // No role configured, allow through
81
- return ctx.next();
77
+ const report = (diagnostic) => {
78
+ options?.onDiagnostic?.(diagnostic);
79
+ };
80
+ const enforcement = options?.enforcement ?? config.enforcement ?? "permissive";
81
+ // Resolve the caller identity. A resolver that throws is reported rather
82
+ // than propagated, so an identity backend outage cannot bypass policy.
83
+ let userId = null;
84
+ if (typeof getUserId === "function") {
85
+ try {
86
+ userId = getUserId(ctx) ?? null;
87
+ }
88
+ catch {
89
+ report({
90
+ code: "RBAC_IDENTITY_RESOLVER_FAILED",
91
+ message: "the identity resolver threw; treating the request as unidentified",
92
+ path: "$",
93
+ severity: "warning",
94
+ });
95
+ }
82
96
  }
83
- // Extract provider/model from the request body if available
84
- let provider = "";
85
- let model = "";
86
- let tokenCount;
87
- try {
88
- const body = ctx.init.body;
89
- if (typeof body === "string") {
90
- const parsed = JSON.parse(body);
91
- provider = parsed.provider ?? "";
92
- model = parsed.model ?? "";
93
- tokenCount = parsed.max_tokens;
97
+ // Resolve the role name. A resolver returning nothing falls back to the
98
+ // default role, which preserves pre-v3.4.0 behavior for anonymous callers.
99
+ let roleName = null;
100
+ if (options?.resolveRole) {
101
+ try {
102
+ const resolved = options.resolveRole(ctx);
103
+ if (typeof resolved === "string" && resolved.length > 0)
104
+ roleName = resolved;
94
105
  }
106
+ catch {
107
+ report({
108
+ code: "RBAC_ROLE_RESOLVER_FAILED",
109
+ message: "the role resolver threw; falling back to the default role",
110
+ path: "defaultRole",
111
+ severity: "warning",
112
+ userId: userId ?? undefined,
113
+ });
114
+ }
115
+ }
116
+ if (roleName === null)
117
+ roleName = config.defaultRole ?? "default";
118
+ const role = config.roles?.[roleName] ?? null;
119
+ if (roleName === null || role === null) {
120
+ report({
121
+ code: "RBAC_UNRESOLVED_ROLE",
122
+ message: `role "${roleName}" is not defined in the configured roles`,
123
+ path: "defaultRole",
124
+ severity: "warning",
125
+ userId: userId ?? undefined,
126
+ });
95
127
  }
96
- catch { /* body may not be JSON — skip extraction */ }
97
- // Check permissions
98
- if (provider && model) {
99
- const check = checkPermission(role, provider, model, tokenCount);
100
- if (!check.allowed) {
101
- auditLogger?.logSecurity({
102
- eventType: "custom",
103
- action: "rbac_denied",
104
- description: check.reason ?? "Access denied",
128
+ // Rate limiting runs before the permission check because it does not depend
129
+ // on the request context, and an allowed-then-denied request must still
130
+ // count against the limit.
131
+ if (role?.rateLimit) {
132
+ if (userId === null) {
133
+ report({
134
+ code: "RBAC_RATE_LIMIT_UNKEYED",
135
+ message: `role "${role.name}" declares a rate limit but no request identity was resolved, so the limit was not applied`,
136
+ path: "rateLimit",
105
137
  severity: "warning",
138
+ role: role.name,
106
139
  });
107
- return new Response(JSON.stringify({ error: check.reason }), {
108
- status: 403,
109
- headers: { "Content-Type": "application/json" },
140
+ }
141
+ else {
142
+ const limiter = rateLimiters.getOrCreate(`rbac:${userId}:${role.name}`, {
143
+ maxTokens: role.rateLimit.maxRequests,
144
+ refillRate: role.rateLimit.maxRequests / (role.rateLimit.windowMs / 1000),
110
145
  });
146
+ const result = limiter.tryConsume();
147
+ if (!result.allowed) {
148
+ auditLogger?.logSecurity({
149
+ eventType: "rate_limit",
150
+ action: "rbac_rate_limit",
151
+ userId,
152
+ description: `Rate limit exceeded (role: ${role.name})`,
153
+ severity: "warning",
154
+ meta: { role: role.name, retryAfterMs: result.retryAfterMs },
155
+ });
156
+ return jsonResponse(429, { error: "Rate limit exceeded", retryAfterMs: result.retryAfterMs }, { "Retry-After": String(Math.ceil((result.retryAfterMs || 1000) / 1000)) });
157
+ }
111
158
  }
112
159
  }
113
- // Check rate limit
114
- if (role.rateLimit && userId) {
115
- const limiter = rateLimiters.getOrCreate(`rbac:${userId}`, {
116
- maxTokens: role.rateLimit.maxRequests,
117
- refillRate: role.rateLimit.maxRequests / (role.rateLimit.windowMs / 1000),
160
+ // Resolve the request context. Provider identity comes from the URL, since
161
+ // no adapter places `provider` in the request body.
162
+ let request = null;
163
+ try {
164
+ request = options?.resolveRequest
165
+ ? options.resolveRequest(ctx) ?? null
166
+ : resolveRequestFromContext(ctx, options?.resolveProviderByUrl);
167
+ }
168
+ catch {
169
+ report({
170
+ code: "RBAC_REQUEST_RESOLVER_FAILED",
171
+ message: "the request-context resolver threw; treating the request as unresolved",
172
+ path: "$",
173
+ severity: "warning",
174
+ role: roleName ?? undefined,
175
+ userId: userId ?? undefined,
118
176
  });
119
- const result = limiter.acquire();
120
- if (!result.allowed) {
121
- auditLogger?.logSecurity({
122
- eventType: "rate_limit",
123
- action: "rbac_rate_limit",
124
- description: `Rate limit exceeded for user ${userId} (role: ${role.name})`,
177
+ request = null;
178
+ }
179
+ let budget;
180
+ if (options?.resolveBudget && role) {
181
+ try {
182
+ budget = options.resolveBudget({ ctx, role, roleName: role.name, userId });
183
+ }
184
+ catch {
185
+ report({
186
+ code: "RBAC_BUDGET_RESOLVER_FAILED",
187
+ message: "the budget resolver threw; the session budget was not evaluated",
188
+ path: "maxBudgetPerSession",
125
189
  severity: "warning",
190
+ role: role.name,
191
+ userId: userId ?? undefined,
126
192
  });
127
- return new Response(JSON.stringify({ error: "Rate limit exceeded", retryAfterMs: result.retryAfterMs }), {
128
- status: 429,
129
- headers: {
130
- "Content-Type": "application/json",
131
- "Retry-After": String(Math.ceil((result.retryAfterMs ?? 1000) / 1000)),
132
- },
133
- });
193
+ budget = null;
134
194
  }
135
195
  }
136
- return ctx.next();
196
+ const verdict = evaluateAuthorization({
197
+ role,
198
+ roleName: role === null ? null : roleName,
199
+ request,
200
+ enforcement,
201
+ budget,
202
+ userId,
203
+ report,
204
+ });
205
+ if (verdict.allow)
206
+ return ctx.next();
207
+ auditLogger?.logSecurity({
208
+ eventType: "custom",
209
+ action: "rbac_denied",
210
+ userId: userId ?? undefined,
211
+ description: verdict.reason ?? "Access denied",
212
+ severity: "warning",
213
+ meta: { role: verdict.role, unresolved: verdict.unresolved },
214
+ });
215
+ if (verdict.status === 429) {
216
+ return jsonResponse(429, { error: verdict.reason, retryAfterMs: verdict.retryAfterMs });
217
+ }
218
+ return jsonResponse(403, { error: verdict.reason ?? "Access denied" });
137
219
  };
138
220
  }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @hilbras/sdk — Replay guard
3
+ *
4
+ * An HMAC signature proves a request was produced by a holder of the secret.
5
+ * It does not prove the request is fresh. This module supplies the other half:
6
+ * a bounded window on the signed timestamp and a bounded cache of already-seen
7
+ * signatures.
8
+ *
9
+ * The cache is a fixed-size FIFO, so a long-lived process cannot grow without
10
+ * bound. Eviction means a very old signature could in principle be replayed
11
+ * after falling out of the window, which is why `maxAgeMs` should be the
12
+ * binding limit rather than the cache size.
13
+ */
14
+ export interface ReplayGuardOptions {
15
+ /** Maximum age of a signed request. Default: 5 minutes. */
16
+ maxAgeMs?: number;
17
+ /** Tolerance for a request dated slightly in the future. Default: 30 seconds. */
18
+ maxSkewMs?: number;
19
+ /** Maximum number of remembered signatures. Default: 10,000. */
20
+ maxEntries?: number;
21
+ /** Header carrying the signed timestamp. Default: `"date"`. */
22
+ dateHeader?: string;
23
+ /** Clock injection for deterministic tests. */
24
+ now?: () => number;
25
+ }
26
+ export interface ReplayVerdict {
27
+ valid: boolean;
28
+ reason?: string;
29
+ }
30
+ export declare class ReplayGuard {
31
+ private readonly _maxAgeMs;
32
+ private readonly _maxSkewMs;
33
+ private readonly _maxEntries;
34
+ private readonly _dateHeader;
35
+ private readonly _now;
36
+ private readonly _seen;
37
+ constructor(options?: ReplayGuardOptions);
38
+ /**
39
+ * Verify that a request is fresh and has not been seen before. A signature
40
+ * is recorded only when it passes the window, so a flood of stale requests
41
+ * cannot evict live entries from the cache.
42
+ */
43
+ verify(headers: Record<string, string>, signature: string): ReplayVerdict;
44
+ /** Number of signatures currently remembered. */
45
+ get size(): number;
46
+ /** Forget every remembered signature. */
47
+ clear(): void;
48
+ private _remember;
49
+ }
50
+ /** Create a replay guard. */
51
+ export declare function createReplayGuard(options?: ReplayGuardOptions): ReplayGuard;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @hilbras/sdk — Replay guard
3
+ *
4
+ * An HMAC signature proves a request was produced by a holder of the secret.
5
+ * It does not prove the request is fresh. This module supplies the other half:
6
+ * a bounded window on the signed timestamp and a bounded cache of already-seen
7
+ * signatures.
8
+ *
9
+ * The cache is a fixed-size FIFO, so a long-lived process cannot grow without
10
+ * bound. Eviction means a very old signature could in principle be replayed
11
+ * after falling out of the window, which is why `maxAgeMs` should be the
12
+ * binding limit rather than the cache size.
13
+ */
14
+ const DEFAULTS = {
15
+ maxAgeMs: 5 * 60_000,
16
+ maxSkewMs: 30_000,
17
+ maxEntries: 10_000,
18
+ dateHeader: "date",
19
+ };
20
+ export class ReplayGuard {
21
+ _maxAgeMs;
22
+ _maxSkewMs;
23
+ _maxEntries;
24
+ _dateHeader;
25
+ _now;
26
+ _seen = new Set();
27
+ constructor(options = {}) {
28
+ this._maxAgeMs = options.maxAgeMs ?? DEFAULTS.maxAgeMs;
29
+ this._maxSkewMs = options.maxSkewMs ?? DEFAULTS.maxSkewMs;
30
+ this._maxEntries = Math.max(1, options.maxEntries ?? DEFAULTS.maxEntries);
31
+ this._dateHeader = (options.dateHeader ?? DEFAULTS.dateHeader).toLowerCase();
32
+ this._now = options.now ?? (() => Date.now());
33
+ }
34
+ /**
35
+ * Verify that a request is fresh and has not been seen before. A signature
36
+ * is recorded only when it passes the window, so a flood of stale requests
37
+ * cannot evict live entries from the cache.
38
+ */
39
+ verify(headers, signature) {
40
+ const lower = {};
41
+ for (const [key, value] of Object.entries(headers)) {
42
+ if (value !== undefined)
43
+ lower[key.toLowerCase()] = value;
44
+ }
45
+ const raw = lower[this._dateHeader];
46
+ if (!raw)
47
+ return { valid: false, reason: `missing ${this._dateHeader} header` };
48
+ const timestamp = Date.parse(raw);
49
+ if (Number.isNaN(timestamp)) {
50
+ return { valid: false, reason: `unparseable ${this._dateHeader} header` };
51
+ }
52
+ const age = this._now() - timestamp;
53
+ if (age > this._maxAgeMs) {
54
+ return { valid: false, reason: `request is ${Math.round(age / 1000)}s old, older than the ${Math.round(this._maxAgeMs / 1000)}s window` };
55
+ }
56
+ if (age < -this._maxSkewMs) {
57
+ return { valid: false, reason: `request is dated ${Math.round(-age / 1000)}s in the future` };
58
+ }
59
+ if (this._seen.has(signature)) {
60
+ return { valid: false, reason: "signature has already been used" };
61
+ }
62
+ this._remember(signature);
63
+ return { valid: true };
64
+ }
65
+ /** Number of signatures currently remembered. */
66
+ get size() {
67
+ return this._seen.size;
68
+ }
69
+ /** Forget every remembered signature. */
70
+ clear() {
71
+ this._seen.clear();
72
+ }
73
+ _remember(signature) {
74
+ this._seen.add(signature);
75
+ while (this._seen.size > this._maxEntries) {
76
+ const oldest = this._seen.values().next();
77
+ if (oldest.done)
78
+ break;
79
+ this._seen.delete(oldest.value);
80
+ }
81
+ }
82
+ }
83
+ /** Create a replay guard. */
84
+ export function createReplayGuard(options = {}) {
85
+ return new ReplayGuard(options);
86
+ }
@@ -1,30 +1,48 @@
1
1
  /**
2
2
  * @hilbras/sdk — HMAC Request Signer
3
3
  *
4
- * Signs HTTP requests with HMAC-SHA256 for provider authentication.
5
- * Supports custom headers and timestamp inclusion for request integrity.
4
+ * Signs HTTP requests with HMAC for provider authentication and gateway
5
+ * handshakes.
6
6
  *
7
- * Note: This signer provides integrity and authentication only — it does NOT
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
- * Usage:
13
- * import { RequestSigner } from "@hilbras/sdk";
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
- * const signer = new RequestSigner({
16
- * secret: process.env.API_SIGNING_SECRET,
17
- * keyId: "key-2026-09",
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
- * const signed = await signer.sign(url, { method: "POST", body, headers });
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
  */
36
+ import { ReplayGuard, type ReplayGuardOptions } from "./replay-guard.js";
37
+ /** Wire-format version. See the module documentation. */
38
+ export type SignatureProfile = "v1" | "v2";
39
+ /** Body types that can be content-bound. `Buffer` is a `Uint8Array`. */
40
+ export type SignableBody = string | Uint8Array;
23
41
  /** Configuration for request signing */
24
42
  export interface RequestSignerConfig {
25
43
  /** HMAC signing secret (symmetric key) */
26
44
  secret: string;
27
- /** Optional key ID included in the signature header */
45
+ /** Optional key ID bound into `v2` signatures */
28
46
  keyId?: string;
29
47
  /** Headers to include in the signature (default: ["date", "content-type"]) */
30
48
  headers?: string[];
@@ -34,6 +52,19 @@ export interface RequestSignerConfig {
34
52
  keyIdHeader?: string;
35
53
  /** Algorithm (default: "sha256") */
36
54
  algorithm?: "sha256" | "sha512";
55
+ /**
56
+ * Signature wire format (default: `"v1"`, which is frozen and does not
57
+ * authenticate the body). Use `"v2"` for new integrations.
58
+ */
59
+ profile?: SignatureProfile;
60
+ /** Header carrying the `v2` nonce (default: "x-hilbras-nonce") */
61
+ nonceHeader?: string;
62
+ /** Header carrying the `v2` body digest (default: "x-hilbras-content-digest") */
63
+ contentDigestHeader?: string;
64
+ /** Clock injection for deterministic timestamps. */
65
+ now?: () => number;
66
+ /** Nonce source injection; defaults to `crypto.getRandomValues`. */
67
+ nonce?: () => string;
37
68
  }
38
69
  /** Signed request result */
39
70
  export interface SignedRequest {
@@ -42,33 +73,68 @@ export interface SignedRequest {
42
73
  signatureInput: string;
43
74
  }
44
75
  /**
45
- * Signs HTTP requests using HMAC-SHA256.
46
- * Provides request integrity and authentication for provider communication.
76
+ * Signs HTTP requests using HMAC. See the module documentation for the
77
+ * difference between the `v1` and `v2` profiles.
47
78
  */
48
79
  export declare class RequestSigner {
49
80
  private _config;
50
81
  constructor(config: RequestSignerConfig);
82
+ /** The active wire-format profile. */
83
+ get profile(): SignatureProfile;
84
+ /** Current RFC 7231 timestamp from the signer's injected clock. */
85
+ timestamp(): string;
86
+ /** Header names this signer emits, for callers that normalize headers. */
87
+ get signatureHeader(): string;
88
+ private _digest;
89
+ /** Build the canonical string that the HMAC covers. */
90
+ private _canonical;
91
+ private _hmac;
51
92
  /**
52
93
  * Sign a request. Returns headers to add to the outgoing request.
53
- * The timestamp is included in the signing string for integrity, but
54
- * callers must independently verify freshness to prevent replay.
94
+ *
95
+ * A body that is not a rewindable byte sequence (for example `FormData`)
96
+ * cannot be content-bound, so no digest header is emitted for it rather than
97
+ * a digest of a placeholder string.
55
98
  */
56
99
  sign(url: string, request: {
57
100
  method?: string;
58
- body?: string | Buffer;
101
+ body?: SignableBody | FormData;
59
102
  headers?: Record<string, string>;
60
103
  timestamp?: string;
104
+ nonce?: string;
61
105
  }): SignedRequest;
62
106
  /**
63
107
  * Verify a request signature. Returns true if valid.
108
+ *
109
+ * Under `v2` the body digest is recomputed from the supplied bytes, so a
110
+ * modified body fails even when the digest header is modified to match.
64
111
  */
65
112
  verify(url: string, request: {
66
113
  method?: string;
67
- body?: string | Buffer;
114
+ body?: SignableBody | FormData;
68
115
  headers: Record<string, string>;
116
+ nonce?: string;
69
117
  }, receivedSignature: string): boolean;
118
+ /**
119
+ * Verify a signature and reject replays. Composes {@link verify} with a
120
+ * {@link ReplayGuard}, which enforces a signed-timestamp window and a bounded
121
+ * seen-signature cache.
122
+ */
123
+ verifyFresh(url: string, request: {
124
+ method?: string;
125
+ body?: SignableBody | FormData;
126
+ headers: Record<string, string>;
127
+ }, receivedSignature: string, options?: ReplayGuardOptions & {
128
+ guard?: ReplayGuard;
129
+ }): {
130
+ valid: boolean;
131
+ reason?: string;
132
+ };
70
133
  }
71
134
  /**
72
- * Creates a middleware that signs every outgoing request.
135
+ * Create a middleware that signs every outgoing request.
136
+ *
137
+ * The outgoing header bag is normalized to a single lowercase key per name, so
138
+ * merging signed headers cannot produce both `Content-Type` and `content-type`.
73
139
  */
74
140
  export declare function signingMiddleware(signer: RequestSigner): import("../middleware/middleware.js").Middleware;