@aikidosec/firewall
Version:
Zen by Aikido is an embedded Application Firewall that autonomously protects Node.js apps against common and critical attacks, provides rate limiting, detects malicious traffic (including bots), and more.
56 lines (55 loc) • 1.89 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDataSchema = getDataSchema;
const getStringFormat_1 = require("./getStringFormat");
// Maximum depth to traverse the data structure to get the schema for improved performance
const maxDepth = 20;
// Maximum number of properties per level
const maxProperties = 100;
// Maximum property key length
const maxPropertyKeyLength = 100;
/**
* Get the schema of the data (for example http json body) as a schema.
*/
function getDataSchema(data, depth = 0) {
// If the data is not an object (or an array), return the type
if (typeof data !== "object") {
if (typeof data === "string") {
const format = (0, getStringFormat_1.getStringFormat)(data);
if (format) {
return { type: "string", format };
}
}
return { type: typeof data };
}
// typeof null is object, but we want to treat it as null
if (data === null) {
return { type: "null" };
}
if (Array.isArray(data)) {
return {
type: "array",
// Assume that the array is homogenous (for performance reasons)
items: data.length > 0 ? getDataSchema(data[0]) : null,
};
}
const schema = {
type: "object",
properties: {},
};
// If the depth is less than the maximum depth, get the schema for each property
if (depth < maxDepth) {
let propertiesCount = 0;
for (const key of Object.keys(data)) {
if (propertiesCount >= maxProperties) {
break;
}
if (key.length > maxPropertyKeyLength) {
continue; // Skip keys that are too long
}
propertiesCount++;
schema.properties[key] = getDataSchema(data[key], depth + 1);
}
}
return schema;
}
;