Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(contracts): bound request containers and scan raw bodies before parse

Alfredo Lopez8bbe2adab9fb
diff --git a/packages/grok-provider-attempt-contract/bodyStructure.cjs b/packages/grok-provider-attempt-contract/bodyStructure.cjs
new file mode 100644
index 000000000..136794eab
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/bodyStructure.cjs
@@ -0,0 +1,142 @@
+'use strict'
+
+/**
+ * Structural bounds on a raw JSON body, checked before JSON.parse.
+ *
+ * JSON.parse allocates one heap object per container, so a body of `[],`
+ * repeated costs far more heap than its byte count suggests: one 36 MB body
+ * of that shape aborts a proxy running with --max-old-space-size=384, and
+ * three 8 MiB ones at once do the same. A byte limit alone cannot prevent
+ * this. This scan runs as the body-parser `verify` hook, after the body is
+ * read and before it is parsed, and refuses a body whose structure could
+ * not belong to a request the contract accepts:
+ *
+ * - structural bytes: every byte outside string contents that is not JSON
+ * whitespace, both quotes of each string included. A compact body minus its
+ * string contents is never larger than its non-image share, so a bound of
+ * `maxRequestBodyBytes + ENVELOPE_ALLOWANCE_BYTES` refuses no acceptable
+ * request, visual or not. Image data is string content and never counts.
+ * - containers: every `{` and `[`, bounded by the contract's
+ * `maxRequestContainers` plus the envelope's own containers.
+ * - depth: container nesting, bounded by the request depth plus the one
+ * envelope level around it.
+ *
+ * Only UTF-8 is scanned. In UTF-16 or UTF-32 a quote or backslash byte can
+ * be half of another character, so the scan would lose track of strings; any
+ * other declared charset is refused.
+ *
+ * This file is byte-identical in @clerum/grok-provider-attempt-contract and
+ * @clerum/llm-provider-attempt-contract. Each package's index.test.cjs
+ * compares the two files, so neither package imports the other.
+ */
+
+class BodyStructureError extends Error {
+ constructor(status, type, message) {
+ super(message)
+ this.name = 'BodyStructureError'
+ this.status = status
+ this.type = type
+ }
+}
+
+// Index of the quote that closes a string whose contents start at `from`, or
+// `buf.length` when the string is unterminated (JSON.parse then refuses the
+// body). A quote is escaped when an odd run of backslashes precedes it; the
+// run cannot extend past the opening quote, so each byte is read at most
+// twice. 0x22 and 0x5c never occur inside a multi-byte UTF-8 sequence.
+function closingQuote(buf, from) {
+ let quote = buf.indexOf(0x22, from)
+ while (quote !== -1) {
+ let backslashes = 0
+ for (let j = quote - 1; j >= from && buf[j] === 0x5c; j--) backslashes++
+ if (backslashes % 2 === 0) return quote
+ quote = buf.indexOf(0x22, quote + 1)
+ }
+ return buf.length
+}
+
+function tooDense(limits) {
+ return new BodyStructureError(
+ 413,
+ 'body.structure.too.dense',
+ `request body exceeds ${limits.maxStructuralBytes} structural bytes`
+ )
+}
+
+/**
+ * Scans `buf` (a Buffer holding UTF-8 JSON) and throws a BodyStructureError
+ * on the first bound it crosses. Returns the counts it measured. It does not
+ * validate JSON syntax; JSON.parse still does that.
+ */
+function scanJsonStructure(buf, limits) {
+ const { maxStructuralBytes, maxContainers, maxDepth } = limits
+ const length = buf.length
+ let structuralBytes = 0
+ let containers = 0
+ let depth = 0
+ let deepest = 0
+ let i = 0
+ while (i < length) {
+ const byte = buf[i]
+ if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {
+ i++
+ continue
+ }
+ structuralBytes++
+ if (structuralBytes > maxStructuralBytes) throw tooDense(limits)
+ if (byte === 0x22) {
+ i = closingQuote(buf, i + 1)
+ if (i < length) {
+ structuralBytes++
+ if (structuralBytes > maxStructuralBytes) throw tooDense(limits)
+ }
+ } else if (byte === 0x7b || byte === 0x5b) {
+ containers++
+ if (containers > maxContainers) {
+ throw new BodyStructureError(
+ 413,
+ 'body.structure.too.many.containers',
+ `request body exceeds ${maxContainers} containers`
+ )
+ }
+ depth++
+ if (depth > maxDepth) {
+ throw new BodyStructureError(
+ 400,
+ 'body.structure.too.deep',
+ `request body exceeds nesting depth ${maxDepth}`
+ )
+ }
+ if (depth > deepest) deepest = depth
+ } else if (byte === 0x7d || byte === 0x5d) {
+ depth--
+ }
+ i++
+ }
+ return { structuralBytes, containers, deepest }
+}
+
+/**
+ * A body-parser `verify(req, res, buf, encoding)` hook. body-parser passes the
+ * declared charset, lower-cased and defaulting to utf-8. A thrown error
+ * reaches the error handler with its own `status` and `type`, and with the raw
+ * body attached as `err.body`, so a handler must never log the error object.
+ */
+function createBodyStructureVerify(limits) {
+ const bounds = Object.freeze({
+ maxStructuralBytes: limits.maxStructuralBytes,
+ maxContainers: limits.maxContainers,
+ maxDepth: limits.maxDepth,
+ })
+ return function verifyBodyStructure(_req, _res, buf, encoding) {
+ if (encoding !== 'utf-8') {
+ throw new BodyStructureError(415, 'charset.unsupported', 'request body must be UTF-8')
+ }
+ scanJsonStructure(buf, bounds)
+ }
+}
+
+module.exports = {
+ scanJsonStructure,
+ createBodyStructureVerify,
+}
diff --git a/packages/grok-provider-attempt-contract/index.cjs b/packages/grok-provider-attempt-contract/index.cjs
index ac2a4ed08..4744e1c65 100644
--- a/packages/grok-provider-attempt-contract/index.cjs
+++ b/packages/grok-provider-attempt-contract/index.cjs
@@ -12,6 +12,7 @@ const {
MAX_ENCODED_TOTAL_IMAGE_BYTES,
inspectVisualImage,
} = require('./visualPayload.cjs')
+const { createBodyStructureVerify, scanJsonStructure } = require('./bodyStructure.cjs')
const SCHEMA_VERSION = 'grok-completion-request.v1'
const SCHEMA_VERSION_V2 = 'grok-completion-request.v2'
@@ -60,6 +61,15 @@ const LIMITS = Object.freeze({
// Free-form JSON trees (tool parameters, assistant tool-call arguments) may
// nest at most this many containers. Bounds recursion before hashing.
maxNestingDepth: 64,
+ // Objects and arrays in one request, the root included. JSON.parse
+ // allocates a heap object for each, so a request of empty containers fits
+ // maxRequestBodyBytes with about four million of them, and three such
+ // bodies at once exhaust a proxy capped at --max-old-space-size=384. In
+ // the Grok proxy, three ordinary bodies and one visual body at twice this
+ // bound kept 197 MiB resident after a full GC (A8 measurement). A
+ // conversation needs a few thousand containers; tool results are strings
+ // and never count. Must equal the Codex contract's value.
+ maxRequestContainers: 262144,
// How long an execution ticket stays redeemable after authorize. control-api
// signs Grok tickets with this TTL, and the proxy bounds its admission waits
// against the remaining ticket life, so both read it from here (#739).
@@ -81,6 +91,22 @@ const ENVELOPE_ALLOWANCE_BYTES = 16 * 1024
const REQUEST_ENVELOPE_DEPTH = 5
const MAX_REQUEST_DEPTH = LIMITS.maxNestingDepth + REQUEST_ENVELOPE_DEPTH
+// Containers a proxy envelope or an authorize body adds around its request:
+// each is one object whose other members are strings and numbers. 16 is
+// several times that.
+const ENVELOPE_CONTAINER_ALLOWANCE = 16
+
+// Bounds for the raw-body scan (bodyStructure.cjs) that grok-llm-proxy and
+// control-api run before JSON.parse. Each is the matching request bound plus
+// the envelope around the request, so the scan refuses no request this
+// contract accepts: structural bytes never exceed the non-image share, and
+// the envelope adds one nesting level.
+const BODY_STRUCTURE_LIMITS = Object.freeze({
+ maxStructuralBytes: LIMITS.maxRequestBodyBytes + ENVELOPE_ALLOWANCE_BYTES,
+ maxContainers: LIMITS.maxRequestContainers + ENVELOPE_CONTAINER_ALLOWANCE,
+ maxDepth: MAX_REQUEST_DEPTH + 1,
+})
+
const ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/
const SHA256_HEX = /^[a-f0-9]{64}$/
const MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
@@ -329,16 +355,18 @@ function rejectUnknown(obj, allowed, label) {
/**
* Iterative structural pre-check, safe on arbitrarily deep or cyclic input.
- * Returns a failure when containers nest deeper than `maxDepth`, or when the
+ * Returns a failure when containers nest deeper than `maxDepth`, when the
* value holds more elements than a maxRequestBodyBytes JSON document can encode
* (every encoded element takes at least one byte, so no acceptable request
- * reaches that count; shared references are counted per occurrence, as JSON
- * would serialize them).
+ * reaches that count), or when it holds more than maxRequestContainers objects
+ * and arrays. Shared references are counted per occurrence, as JSON would
+ * serialize them.
*/
function checkStructure(value, maxDepth) {
if (value === null || typeof value !== 'object') return null
const stack = [value, 1]
let elements = 1
+ let containers = 1
while (stack.length > 0) {
const depth = stack.pop()
const node = stack.pop()
@@ -363,7 +391,13 @@ function checkStructure(value, maxDepth) {
return fail('limit', 'request exceeds maxRequestBodyBytes element bound', 'size')
}
for (const child of children) {
- if (child !== null && typeof child === 'object') stack.push(child, depth + 1)
+ if (child !== null && typeof child === 'object') {
+ containers++
+ if (containers > LIMITS.maxRequestContainers) {
+ return fail('limit', 'request exceeds maxRequestContainers', 'size')
+ }
+ stack.push(child, depth + 1)
+ }
}
}
return null
@@ -1028,6 +1062,7 @@ module.exports = {
LIMITS,
GROK_VISUAL_LIMITS,
ENVELOPE_ALLOWANCE_BYTES,
+ BODY_STRUCTURE_LIMITS,
TRANSPORT_PROTOCOL_VERSION,
COMPLETIONS_ORIGIN,
CATALOG_ORIGIN,
@@ -1046,4 +1081,6 @@ module.exports = {
parseGrokExecutionTicketClaims,
parseAuthorizeAttemptResponse,
parseGrokAttemptReceiptV1,
+ scanJsonStructure,
+ createBodyStructureVerify,
}
diff --git a/packages/grok-provider-attempt-contract/index.d.ts b/packages/grok-provider-attempt-contract/index.d.ts
index 3b3c12d80..c1421093c 100644
--- a/packages/grok-provider-attempt-contract/index.d.ts
+++ b/packages/grok-provider-attempt-contract/index.d.ts
@@ -31,6 +31,8 @@ export declare const LIMITS: {
readonly maxDeadlineMs: 1800000
readonly maxIdLength: 128
readonly maxNestingDepth: 64
+ /** Objects and arrays in one request, the root included; equal to the Codex contract's. */
+ readonly maxRequestContainers: 262144
/** Execution ticket TTL; control-api signs Grok tickets with it. */
readonly executionTicketTtlMs: 60000
}
@@ -42,6 +44,48 @@ export declare const LIMITS: {
*/
export declare const ENVELOPE_ALLOWANCE_BYTES: 16384
+/**
+ * Bounds for the raw-body scan run before JSON.parse: the request bounds plus
+ * the envelope around the request. Equal to the Codex contract's.
+ */
+export declare const BODY_STRUCTURE_LIMITS: {
+ readonly maxStructuralBytes: 8404992
+ readonly maxContainers: 262160
+ readonly maxDepth: 70
+}
+
+export interface BodyStructureLimits {
+ readonly maxStructuralBytes: number
+ readonly maxContainers: number
+ readonly maxDepth: number
+}
+
+/**
+ * Thrown by the scan. `type` is `body.structure.too.dense` (413),
+ * `body.structure.too.many.containers` (413), `body.structure.too.deep` (400)
+ * or, from the verify hook, `charset.unsupported` (415).
+ */
+export interface BodyStructureError extends Error {
+ readonly name: 'BodyStructureError'
+ readonly status: 400 | 413 | 415
+ readonly type: string
+}
+
+/** Scans a UTF-8 JSON body; throws a BodyStructureError on the first bound crossed. */
+export declare function scanJsonStructure(
+ buf: Uint8Array,
+ limits: BodyStructureLimits
+): { structuralBytes: number; containers: number; deepest: number }
+
+/**
+ * A body-parser `verify` hook running scanJsonStructure. The error it throws
+ * reaches the error handler with the raw body attached as `err.body`, so the
+ * handler must never log the error object.
+ */
+export declare function createBodyStructureVerify(
+ limits: BodyStructureLimits
+): (req: unknown, res: unknown, buf: Uint8Array, encoding: string) => void
+
/**
* Budgets for V2 image parts, from the xAI documentation for api.x.ai/v1
* (20 MiB per image; the 20-image, 20 MiB per-request budget is a local
diff --git a/packages/llm-provider-attempt-contract/bodyStructure.cjs b/packages/llm-provider-attempt-contract/bodyStructure.cjs
new file mode 100644
index 000000000..136794eab
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/bodyStructure.cjs
@@ -0,0 +1,142 @@
+'use strict'
+
+/**
+ * Structural bounds on a raw JSON body, checked before JSON.parse.
+ *
+ * JSON.parse allocates one heap object per container, so a body of `[],`
+ * repeated costs far more heap than its byte count suggests: one 36 MB body
+ * of that shape aborts a proxy running with --max-old-space-size=384, and
+ * three 8 MiB ones at once do the same. A byte limit alone cannot prevent
+ * this. This scan runs as the body-parser `verify` hook, after the body is
+ * read and before it is parsed, and refuses a body whose structure could
+ * not belong to a request the contract accepts:
+ *
+ * - structural bytes: every byte outside string contents that is not JSON
+ * whitespace, both quotes of each string included. A compact body minus its
+ * string contents is never larger than its non-image share, so a bound of
+ * `maxRequestBodyBytes + ENVELOPE_ALLOWANCE_BYTES` refuses no acceptable
+ * request, visual or not. Image data is string content and never counts.
+ * - containers: every `{` and `[`, bounded by the contract's
+ * `maxRequestContainers` plus the envelope's own containers.
+ * - depth: container nesting, bounded by the request depth plus the one
+ * envelope level around it.
+ *
+ * Only UTF-8 is scanned. In UTF-16 or UTF-32 a quote or backslash byte can
+ * be half of another character, so the scan would lose track of strings; any
+ * other declared charset is refused.
+ *
+ * This file is byte-identical in @clerum/grok-provider-attempt-contract and
+ * @clerum/llm-provider-attempt-contract. Each package's index.test.cjs
+ * compares the two files, so neither package imports the other.
+ */
+
+class BodyStructureError extends Error {
+ constructor(status, type, message) {
+ super(message)
+ this.name = 'BodyStructureError'
+ this.status = status
+ this.type = type
+ }
+}
+
+// Index of the quote that closes a string whose contents start at `from`, or
+// `buf.length` when the string is unterminated (JSON.parse then refuses the
+// body). A quote is escaped when an odd run of backslashes precedes it; the
+// run cannot extend past the opening quote, so each byte is read at most
+// twice. 0x22 and 0x5c never occur inside a multi-byte UTF-8 sequence.
+function closingQuote(buf, from) {
+ let quote = buf.indexOf(0x22, from)
+ while (quote !== -1) {
+ let backslashes = 0
+ for (let j = quote - 1; j >= from && buf[j] === 0x5c; j--) backslashes++
+ if (backslashes % 2 === 0) return quote
+ quote = buf.indexOf(0x22, quote + 1)
+ }
+ return buf.length
+}
+
+function tooDense(limits) {
+ return new BodyStructureError(
+ 413,
+ 'body.structure.too.dense',
+ `request body exceeds ${limits.maxStructuralBytes} structural bytes`
+ )
+}
+
+/**
+ * Scans `buf` (a Buffer holding UTF-8 JSON) and throws a BodyStructureError
+ * on the first bound it crosses. Returns the counts it measured. It does not
+ * validate JSON syntax; JSON.parse still does that.
+ */
+function scanJsonStructure(buf, limits) {
+ const { maxStructuralBytes, maxContainers, maxDepth } = limits
+ const length = buf.length
+ let structuralBytes = 0
+ let containers = 0
+ let depth = 0
+ let deepest = 0
+ let i = 0
+ while (i < length) {
+ const byte = buf[i]
+ if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {
+ i++
+ continue
+ }
+ structuralBytes++
+ if (structuralBytes > maxStructuralBytes) throw tooDense(limits)
+ if (byte === 0x22) {
+ i = closingQuote(buf, i + 1)
+ if (i < length) {
+ structuralBytes++
+ if (structuralBytes > maxStructuralBytes) throw tooDense(limits)
+ }
+ } else if (byte === 0x7b || byte === 0x5b) {
+ containers++
+ if (containers > maxContainers) {
+ throw new BodyStructureError(
+ 413,
+ 'body.structure.too.many.containers',
+ `request body exceeds ${maxContainers} containers`
+ )
+ }
+ depth++
+ if (depth > maxDepth) {
+ throw new BodyStructureError(
+ 400,
+ 'body.structure.too.deep',
+ `request body exceeds nesting depth ${maxDepth}`
+ )
+ }
+ if (depth > deepest) deepest = depth
+ } else if (byte === 0x7d || byte === 0x5d) {
+ depth--
+ }
+ i++
+ }
+ return { structuralBytes, containers, deepest }
+}
+
+/**
+ * A body-parser `verify(req, res, buf, encoding)` hook. body-parser passes the
+ * declared charset, lower-cased and defaulting to utf-8. A thrown error
+ * reaches the error handler with its own `status` and `type`, and with the raw
+ * body attached as `err.body`, so a handler must never log the error object.
+ */
+function createBodyStructureVerify(limits) {
+ const bounds = Object.freeze({
+ maxStructuralBytes: limits.maxStructuralBytes,
+ maxContainers: limits.maxContainers,
+ maxDepth: limits.maxDepth,
+ })
+ return function verifyBodyStructure(_req, _res, buf, encoding) {
+ if (encoding !== 'utf-8') {
+ throw new BodyStructureError(415, 'charset.unsupported', 'request body must be UTF-8')
+ }
+ scanJsonStructure(buf, bounds)
+ }
+}
+
+module.exports = {
+ scanJsonStructure,
+ createBodyStructureVerify,
+}
diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjs
index b90f9b7ac..530d5d27f 100644
--- a/packages/llm-provider-attempt-contract/index.cjs
+++ b/packages/llm-provider-attempt-contract/index.cjs
@@ -8,6 +8,7 @@
const { createHash } = require('node:crypto')
const { VISUAL_LIMITS, inspectVisualImage } = require('./visualPayload.cjs')
+const { createBodyStructureVerify, scanJsonStructure } = require('./bodyStructure.cjs')
const SCHEMA_VERSION = 'codex-completion-request.v1'
const SCHEMA_VERSION_V2 = 'codex-completion-request.v2'
@@ -47,6 +48,15 @@ const LIMITS = Object.freeze({
// Free-form JSON trees (tool parameters, assistant tool-call arguments) may
// nest at most this many containers. Bounds recursion before hashing.
maxNestingDepth: 64,
+ // Objects and arrays in one request, the root included. JSON.parse
+ // allocates a heap object for each, so a request of empty containers fits
+ // maxRequestBodyBytes with about four million of them, and three such
+ // bodies at once exhaust a proxy capped at --max-old-space-size=384. A
+ // conversation needs a few thousand containers; tool results are strings
+ // and never count. The A8 measurement of both proxies at this bound is in
+ // codex-llm-proxy/src/requestLimits.ts. Must equal the Grok contract's
+ // value.
+ maxRequestContainers: 262144,
// How long an execution ticket stays redeemable after authorize. control-api
// signs tickets with this TTL, and the proxy bounds its admission waits
// against the remaining ticket life, so both read it from here (#739).
@@ -69,6 +79,22 @@ const ENVELOPE_ALLOWANCE_BYTES = 16 * 1024
const REQUEST_ENVELOPE_DEPTH = 5
const MAX_REQUEST_DEPTH = LIMITS.maxNestingDepth + REQUEST_ENVELOPE_DEPTH
+// Containers a proxy envelope or an authorize body adds around its request:
+// each is one object whose other members are strings and numbers. 16 is
+// several times that.
+const ENVELOPE_CONTAINER_ALLOWANCE = 16
+
+// Bounds for the raw-body scan (bodyStructure.cjs) that codex-llm-proxy and
+// control-api run before JSON.parse. Each is the matching request bound plus
+// the envelope around the request, so the scan refuses no request this
+// contract accepts: structural bytes never exceed the non-image share, and
+// the envelope adds one nesting level.
+const BODY_STRUCTURE_LIMITS = Object.freeze({
+ maxStructuralBytes: LIMITS.maxRequestBodyBytes + ENVELOPE_ALLOWANCE_BYTES,
+ maxContainers: LIMITS.maxRequestContainers + ENVELOPE_CONTAINER_ALLOWANCE,
+ maxDepth: MAX_REQUEST_DEPTH + 1,
+})
+
const ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/
const SHA256_HEX = /^[a-f0-9]{64}$/
const MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
@@ -309,16 +335,18 @@ function rejectUnknown(obj, allowed, label) {
/**
* Iterative structural pre-check, safe on arbitrarily deep or cyclic input.
- * Returns a failure when containers nest deeper than `maxDepth`, or when the
+ * Returns a failure when containers nest deeper than `maxDepth`, when the
* value holds more elements than a maxRequestBodyBytes JSON document can encode
* (every encoded element takes at least one byte, so no acceptable request
- * reaches that count; shared references are counted per occurrence, as JSON
- * would serialize them).
+ * reaches that count), or when it holds more than maxRequestContainers objects
+ * and arrays. Shared references are counted per occurrence, as JSON would
+ * serialize them.
*/
function checkStructure(value, maxDepth) {
if (value === null || typeof value !== 'object') return null
const stack = [value, 1]
let elements = 1
+ let containers = 1
while (stack.length > 0) {
const depth = stack.pop()
const node = stack.pop()
@@ -345,7 +373,13 @@ function checkStructure(value, maxDepth) {
return fail('limit', 'request exceeds maxRequestBodyBytes element bound', 'size')
}
for (const child of children) {
- if (child !== null && typeof child === 'object') stack.push(child, depth + 1)
+ if (child !== null && typeof child === 'object') {
+ containers++
+ if (containers > LIMITS.maxRequestContainers) {
+ return fail('limit', 'request exceeds maxRequestContainers', 'size')
+ }
+ stack.push(child, depth + 1)
+ }
}
}
return null
@@ -1022,6 +1056,7 @@ module.exports = {
TICKET_TYP,
LIMITS,
ENVELOPE_ALLOWANCE_BYTES,
+ BODY_STRUCTURE_LIMITS,
VISUAL_LIMITS,
requestBodyLimitBytes,
measureNonImageAuthorizeBytes,
@@ -1039,4 +1074,6 @@ module.exports = {
parseCodexExecutionTicketClaims,
parseAuthorizeAttemptResponse,
parseCodexAttemptReceiptV1,
+ scanJsonStructure,
+ createBodyStructureVerify,
}
diff --git a/packages/llm-provider-attempt-contract/index.d.ts b/packages/llm-provider-attempt-contract/index.d.ts
index 5e11f09d7..a5d4724eb 100644
--- a/packages/llm-provider-attempt-contract/index.d.ts
+++ b/packages/llm-provider-attempt-contract/index.d.ts
@@ -38,6 +38,8 @@ export declare const LIMITS: {
readonly maxDeadlineMs: 1800000
readonly maxIdLength: 128
readonly maxNestingDepth: 64
+ /** Objects and arrays in one request, the root included; equal to the Grok contract's. */
+ readonly maxRequestContainers: 262144
/** Execution ticket TTL; control-api signs tickets with it. */
readonly executionTicketTtlMs: 60000
}
@@ -50,6 +52,48 @@ export declare const LIMITS: {
*/
export declare const ENVELOPE_ALLOWANCE_BYTES: 16384
+/**
+ * Bounds for the raw-body scan run before JSON.parse: the request bounds plus
+ * the envelope around the request. Equal to the Grok contract's.
+ */
+export declare const BODY_STRUCTURE_LIMITS: {
+ readonly maxStructuralBytes: 8404992
+ readonly maxContainers: 262160
+ readonly maxDepth: 70
+}
+
+export interface BodyStructureLimits {
+ readonly maxStructuralBytes: number
+ readonly maxContainers: number
+ readonly maxDepth: number
+}
+
+/**
+ * Thrown by the scan. `type` is `body.structure.too.dense` (413),
+ * `body.structure.too.many.containers` (413), `body.structure.too.deep` (400)
+ * or, from the verify hook, `charset.unsupported` (415).
+ */
+export interface BodyStructureError extends Error {
+ readonly name: 'BodyStructureError'
+ readonly status: 400 | 413 | 415
+ readonly type: string
+}
+
+/** Scans a UTF-8 JSON body; throws a BodyStructureError on the first bound crossed. */
+export declare function scanJsonStructure(
+ buf: Uint8Array,
+ limits: BodyStructureLimits
+): { structuralBytes: number; containers: number; deepest: number }
+
+/**
+ * A body-parser `verify` hook running scanJsonStructure. The error it throws
+ * reaches the error handler with the raw body attached as `err.body`, so the
+ * handler must never log the error object.
+ */
+export declare function createBodyStructureVerify(
+ limits: BodyStructureLimits
+): (req: unknown, res: unknown, buf: Uint8Array, encoding: string) => void
+
/**
* Conservative local safety/product budgets for V2 image parts. These are
* deliberately not upstream facts: the frozen ChatGPT endpoint is not