refactor: 도메인이 100개 1000개씩 늘어나도 유지보수 쉬운 구조로 변경
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
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 });
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user