52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
/**
|
|
* Spec §22. Structural limits for data that crosses a trust boundary.
|
|
*
|
|
* Every value is a finite positive safe integer: there is no "unbounded"
|
|
* validation configuration. These limits protect local CPU/memory cost; they
|
|
* never replace backend validation.
|
|
*/
|
|
export interface ValidationBudget {
|
|
readonly maxBytes: number;
|
|
readonly maxItems: number;
|
|
readonly maxDepth: number;
|
|
readonly maxStringLength: number;
|
|
}
|
|
|
|
const VALIDATION_BUDGET_KEYS = [
|
|
"maxBytes",
|
|
"maxItems",
|
|
"maxDepth",
|
|
"maxStringLength",
|
|
] as const satisfies readonly (keyof ValidationBudget)[];
|
|
|
|
export function defineValidationBudget(budget: ValidationBudget): ValidationBudget {
|
|
for (const key of VALIDATION_BUDGET_KEYS) {
|
|
const value = budget[key];
|
|
if (!Number.isSafeInteger(value) || value < 1) {
|
|
throw new TypeError(
|
|
`validation budget ${key} must be a finite positive safe integer: ${value}`,
|
|
);
|
|
}
|
|
}
|
|
return Object.freeze({
|
|
maxBytes: budget.maxBytes,
|
|
maxItems: budget.maxItems,
|
|
maxDepth: budget.maxDepth,
|
|
maxStringLength: budget.maxStringLength,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The structure budget applied to an HTTP response already bounded by its
|
|
* operation's `responseByteLimit`. `maxItems` bounds every array/object
|
|
* member count and the total node count; `maxDepth` bounds nesting.
|
|
*/
|
|
export function responseValidationBudget(responseByteLimit: number): ValidationBudget {
|
|
return defineValidationBudget({
|
|
maxBytes: responseByteLimit,
|
|
maxItems: 100_000,
|
|
maxDepth: 64,
|
|
maxStringLength: responseByteLimit,
|
|
});
|
|
}
|