118 lines
3.9 KiB
TypeScript
118 lines
3.9 KiB
TypeScript
import type { ValidationBudget } from "./validation-budget.ts";
|
|
|
|
/**
|
|
* Spec §20–§22. Size before parse, structure before mapping.
|
|
*
|
|
* `parseBoundedJson` rejects oversized text before `JSON.parse` runs, then
|
|
* walks the parsed value with an explicit stack (never recursion) so an
|
|
* adversarially nested payload cannot overflow the call stack or make the
|
|
* mapper/validator do unbounded work.
|
|
*/
|
|
export type JsonBudgetViolation =
|
|
| "too-large"
|
|
| "too-many-items"
|
|
| "too-deep"
|
|
| "string-too-long"
|
|
| "invalid-json";
|
|
|
|
export class JsonBudgetExceededError extends RangeError {
|
|
readonly violation: JsonBudgetViolation;
|
|
|
|
constructor(violation: JsonBudgetViolation, detail: string) {
|
|
super(`response.${violation}: ${detail}`);
|
|
this.name = "JsonBudgetExceededError";
|
|
this.violation = violation;
|
|
}
|
|
}
|
|
|
|
const UTF8 = new TextEncoder();
|
|
|
|
function utf8Length(text: string, ceiling: number): number {
|
|
// Each UTF-16 unit encodes to at most 3 UTF-8 bytes, so only text that could
|
|
// exceed the ceiling pays for an exact encode.
|
|
if (text.length * 3 <= ceiling) return text.length;
|
|
return UTF8.encode(text).byteLength;
|
|
}
|
|
|
|
export function parseBoundedJson(text: string, budget: ValidationBudget): unknown {
|
|
if (text.length > budget.maxBytes || utf8Length(text, budget.maxBytes) > budget.maxBytes) {
|
|
throw new JsonBudgetExceededError(
|
|
"too-large",
|
|
`payload exceeds ${budget.maxBytes} bytes`,
|
|
);
|
|
}
|
|
let value: unknown;
|
|
try {
|
|
value = JSON.parse(text);
|
|
} catch {
|
|
throw new JsonBudgetExceededError("invalid-json", "payload is not JSON");
|
|
}
|
|
validateJsonStructure(value, budget);
|
|
return value;
|
|
}
|
|
|
|
export type JsonStructureResult =
|
|
| Readonly<{ ok: true; nodes: number }>
|
|
| Readonly<{ ok: false; violation: JsonBudgetViolation; detail: string }>;
|
|
|
|
/**
|
|
* Non-throwing structural check over an already-parsed JSON value. Plain data
|
|
* only: prototypes and accessors are never consulted.
|
|
*/
|
|
export function checkJsonStructure(
|
|
value: unknown,
|
|
budget: ValidationBudget,
|
|
): JsonStructureResult {
|
|
const stack: Array<readonly [unknown, number]> = [[value, 1]];
|
|
let nodes = 0;
|
|
while (stack.length > 0) {
|
|
const [current, depth] = stack.pop() as readonly [unknown, number];
|
|
nodes += 1;
|
|
if (nodes > budget.maxItems) {
|
|
return fail("too-many-items", `more than ${budget.maxItems} nodes`);
|
|
}
|
|
if (typeof current === "string") {
|
|
if (current.length > budget.maxStringLength) {
|
|
return fail(
|
|
"string-too-long",
|
|
`string longer than ${budget.maxStringLength}`,
|
|
);
|
|
}
|
|
continue;
|
|
}
|
|
if (current === null || typeof current !== "object") continue;
|
|
if (depth > budget.maxDepth) {
|
|
return fail("too-deep", `nesting deeper than ${budget.maxDepth}`);
|
|
}
|
|
if (Array.isArray(current)) {
|
|
if (current.length > budget.maxItems) {
|
|
return fail("too-many-items", `array longer than ${budget.maxItems}`);
|
|
}
|
|
for (let index = current.length - 1; index >= 0; index -= 1) {
|
|
stack.push([current[index], depth + 1]);
|
|
}
|
|
continue;
|
|
}
|
|
const keys = Object.keys(current);
|
|
if (keys.length > budget.maxItems) {
|
|
return fail("too-many-items", `object wider than ${budget.maxItems}`);
|
|
}
|
|
for (const key of keys) {
|
|
if (key.length > budget.maxStringLength) {
|
|
return fail("string-too-long", "object key too long");
|
|
}
|
|
stack.push([(current as Record<string, unknown>)[key], depth + 1]);
|
|
}
|
|
}
|
|
return Object.freeze({ ok: true as const, nodes });
|
|
}
|
|
|
|
export function validateJsonStructure(value: unknown, budget: ValidationBudget): void {
|
|
const result = checkJsonStructure(value, budget);
|
|
if (!result.ok) throw new JsonBudgetExceededError(result.violation, result.detail);
|
|
}
|
|
|
|
function fail(violation: JsonBudgetViolation, detail: string): JsonStructureResult {
|
|
return Object.freeze({ ok: false as const, violation, detail });
|
|
}
|