@schmock/faker 1.9.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,415 @@
1
+ import { ResourceLimitError, SchemaValidationError } from "@schmock/core";
2
+ import type { JSONSchema7 } from "json-schema";
3
+ import {
4
+ DEEP_NESTING_THRESHOLD,
5
+ DEFAULT_ARRAY_COUNT,
6
+ LARGE_ARRAY_THRESHOLD,
7
+ MAX_ARRAY_SIZE,
8
+ MAX_NESTING_DEPTH,
9
+ } from "./constants.js";
10
+ import { createFakerInstance } from "./jsf-config.js";
11
+
12
+ export function isJSONSchema7(value: unknown): value is JSONSchema7 {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+
16
+ /**
17
+ * Validate JSON Schema structure and enforce resource limits
18
+ * Checks for malformed schemas, circular references, excessive nesting,
19
+ * and dangerous patterns that could cause memory issues
20
+ * @param schema - JSON Schema to validate
21
+ * @param path - Current path in schema tree (for error messages)
22
+ * @throws {SchemaValidationError} When schema structure is invalid
23
+ * @throws {ResourceLimitError} When schema exceeds safety limits
24
+ */
25
+ export function validateSchema(schema: JSONSchema7, path = "$"): void {
26
+ if (!schema || typeof schema !== "object") {
27
+ throw new SchemaValidationError(
28
+ path,
29
+ "Schema must be a valid JSON Schema object",
30
+ );
31
+ }
32
+
33
+ if (Object.keys(schema).length === 0) {
34
+ throw new SchemaValidationError(path, "Schema cannot be empty");
35
+ }
36
+
37
+ // Check for invalid schema types
38
+ const validTypes = [
39
+ "object",
40
+ "array",
41
+ "string",
42
+ "number",
43
+ "integer",
44
+ "boolean",
45
+ "null",
46
+ ];
47
+ if (
48
+ schema.type &&
49
+ typeof schema.type === "string" &&
50
+ !validTypes.includes(schema.type)
51
+ ) {
52
+ throw new SchemaValidationError(
53
+ path,
54
+ `Invalid schema type: "${schema.type}"`,
55
+ "Supported types are: object, array, string, number, integer, boolean, null",
56
+ );
57
+ }
58
+
59
+ // Check for malformed properties (must be object, not string)
60
+ if (schema.type === "object" && schema.properties) {
61
+ if (
62
+ typeof schema.properties !== "object" ||
63
+ Array.isArray(schema.properties)
64
+ ) {
65
+ throw new SchemaValidationError(
66
+ `${path}.properties`,
67
+ "Properties must be an object mapping property names to schemas",
68
+ 'Use { "propertyName": { "type": "string" } } format',
69
+ );
70
+ }
71
+
72
+ // Validate each property recursively
73
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
74
+ if (typeof propSchema === "object" && propSchema !== null) {
75
+ // Check for invalid faker methods in property schemas
76
+ const fakerProp =
77
+ "faker" in propSchema ? String(propSchema.faker) : undefined;
78
+ if (fakerProp) {
79
+ try {
80
+ validateFakerMethod(fakerProp);
81
+ } catch (error: unknown) {
82
+ // Re-throw with proper path context
83
+ if (error instanceof SchemaValidationError) {
84
+ const ctx = error.context;
85
+ let issue = "Invalid faker method";
86
+ let suggestion: string | undefined;
87
+ if (ctx && typeof ctx === "object") {
88
+ if ("issue" in ctx && typeof ctx.issue === "string")
89
+ issue = ctx.issue;
90
+ if ("suggestion" in ctx && typeof ctx.suggestion === "string")
91
+ suggestion = ctx.suggestion;
92
+ }
93
+ throw new SchemaValidationError(
94
+ `${path}.properties.${propName}.faker`,
95
+ issue,
96
+ suggestion,
97
+ );
98
+ }
99
+ if (error instanceof Error) throw error;
100
+ throw new Error(String(error));
101
+ }
102
+ }
103
+ validateSchema(propSchema, `${path}.properties.${propName}`);
104
+ }
105
+ }
106
+ }
107
+
108
+ // Check for invalid array items
109
+ if (schema.type === "array") {
110
+ // Array must have items defined and non-null
111
+ if (schema.items === null || schema.items === undefined) {
112
+ throw new SchemaValidationError(
113
+ `${path}.items`,
114
+ "Array schema must have valid items definition",
115
+ "Define items as a schema object or array of schemas",
116
+ );
117
+ }
118
+
119
+ if (Array.isArray(schema.items)) {
120
+ if (schema.items.length === 0) {
121
+ throw new SchemaValidationError(
122
+ `${path}.items`,
123
+ "Array items cannot be empty array",
124
+ "Provide at least one item schema",
125
+ );
126
+ }
127
+ schema.items.forEach((item, index) => {
128
+ if (typeof item === "object" && item !== null) {
129
+ validateSchema(item, `${path}.items[${index}]`);
130
+ }
131
+ });
132
+ } else if (typeof schema.items === "object" && schema.items !== null) {
133
+ validateSchema(schema.items, `${path}.items`);
134
+ }
135
+ }
136
+
137
+ // Check for circular references
138
+ if (hasCircularReference(schema)) {
139
+ throw new SchemaValidationError(
140
+ path,
141
+ "Schema contains circular references which are not supported",
142
+ );
143
+ }
144
+
145
+ // Check nesting depth
146
+ const depth = calculateNestingDepth(schema);
147
+ if (depth > MAX_NESTING_DEPTH) {
148
+ throw new ResourceLimitError(
149
+ "schema_nesting_depth",
150
+ MAX_NESTING_DEPTH,
151
+ depth,
152
+ );
153
+ }
154
+
155
+ // Check for dangerous combination of deep nesting + large arrays
156
+ if (depth >= 4) {
157
+ checkForDeepNestingWithArrays(schema, path);
158
+ }
159
+
160
+ // Check for potentially dangerous array sizes in schema definition
161
+ checkArraySizeLimits(schema, path);
162
+
163
+ // Check for forbidden features
164
+ if (schema.$ref === "#") {
165
+ throw new SchemaValidationError(
166
+ path,
167
+ "Self-referencing schemas are not supported",
168
+ );
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Detect circular references in JSON Schema using path-based traversal
174
+ * Uses backtracking to distinguish between cycles and legitimate schema reuse
175
+ * @param schema - Schema to check for cycles
176
+ * @param currentPath - Set of schemas currently in traversal path
177
+ * @returns true if circular reference detected, false otherwise
178
+ * @example
179
+ * // Detects: schema A -> B -> A (cycle)
180
+ * // Allows: schema A -> B, A -> C (reuse of A)
181
+ */
182
+ function hasCircularReference(
183
+ schema: JSONSchema7,
184
+ currentPath = new Set(),
185
+ ): boolean {
186
+ // Check if this schema is currently being traversed (cycle detected)
187
+ if (currentPath.has(schema)) {
188
+ return true;
189
+ }
190
+
191
+ if (schema.$ref === "#") {
192
+ return true;
193
+ }
194
+
195
+ // Add to current path for this traversal branch
196
+ currentPath.add(schema);
197
+
198
+ if (schema.type === "object" && schema.properties) {
199
+ for (const prop of Object.values(schema.properties)) {
200
+ if (isJSONSchema7(prop)) {
201
+ if (hasCircularReference(prop, currentPath)) {
202
+ return true;
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ if (schema.type === "array" && schema.items) {
209
+ const items = Array.isArray(schema.items) ? schema.items : [schema.items];
210
+ for (const item of items) {
211
+ if (isJSONSchema7(item)) {
212
+ if (hasCircularReference(item, currentPath)) {
213
+ return true;
214
+ }
215
+ }
216
+ }
217
+ }
218
+
219
+ // Remove from current path after checking all children (backtrack)
220
+ currentPath.delete(schema);
221
+
222
+ return false;
223
+ }
224
+
225
+ /**
226
+ * Calculate maximum nesting depth of a JSON Schema
227
+ * Recursively traverses object properties and array items
228
+ * @param schema - Schema to measure
229
+ * @param depth - Current depth (internal recursion parameter)
230
+ * @returns Maximum nesting depth found
231
+ */
232
+ function calculateNestingDepth(schema: JSONSchema7, depth = 0): number {
233
+ if (depth > MAX_NESTING_DEPTH) {
234
+ return depth;
235
+ }
236
+
237
+ let maxDepth = depth;
238
+
239
+ if (schema.type === "object" && schema.properties) {
240
+ for (const prop of Object.values(schema.properties)) {
241
+ if (isJSONSchema7(prop)) {
242
+ maxDepth = Math.max(maxDepth, calculateNestingDepth(prop, depth + 1));
243
+ }
244
+ }
245
+ }
246
+
247
+ if (schema.type === "array" && schema.items) {
248
+ const items = Array.isArray(schema.items) ? schema.items : [schema.items];
249
+ for (const item of items) {
250
+ if (isJSONSchema7(item)) {
251
+ maxDepth = Math.max(maxDepth, calculateNestingDepth(item, depth + 1));
252
+ }
253
+ }
254
+ }
255
+
256
+ return maxDepth;
257
+ }
258
+
259
+ /**
260
+ * Check for dangerous patterns of deep nesting combined with large arrays
261
+ * Prevents memory issues from schemas like: depth 3+ with 100+ item arrays
262
+ * @param schema - Schema to check
263
+ * @param _path - Path in schema (unused but kept for signature consistency)
264
+ * @throws {ResourceLimitError} When dangerous nesting pattern detected
265
+ */
266
+ function checkForDeepNestingWithArrays(
267
+ schema: JSONSchema7,
268
+ _path: string,
269
+ ): void {
270
+ // Look for arrays in deeply nested structures that could cause memory issues
271
+ function findArraysInDeepNesting(
272
+ node: JSONSchema7,
273
+ currentDepth: number,
274
+ ): boolean {
275
+ const schemaType = node.type;
276
+ const isArray = Array.isArray(schemaType)
277
+ ? schemaType.includes("array")
278
+ : schemaType === "array";
279
+
280
+ if (isArray) {
281
+ const maxItems = node.maxItems || DEFAULT_ARRAY_COUNT;
282
+ // Be more aggressive about deep nesting detection
283
+ if (
284
+ currentDepth >= DEEP_NESTING_THRESHOLD &&
285
+ maxItems >= LARGE_ARRAY_THRESHOLD
286
+ ) {
287
+ throw new ResourceLimitError(
288
+ "deep_nesting_memory_risk",
289
+ DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD,
290
+ currentDepth * maxItems,
291
+ );
292
+ }
293
+
294
+ // Check items if they exist
295
+ if (node.items) {
296
+ const items = Array.isArray(node.items) ? node.items : [node.items];
297
+ for (const item of items) {
298
+ if (isJSONSchema7(item)) {
299
+ if (findArraysInDeepNesting(item, currentDepth + 1)) {
300
+ return true;
301
+ }
302
+ }
303
+ }
304
+ }
305
+
306
+ return true;
307
+ }
308
+
309
+ if (schemaType === "object" && node.properties) {
310
+ for (const prop of Object.values(node.properties)) {
311
+ if (isJSONSchema7(prop)) {
312
+ if (findArraysInDeepNesting(prop, currentDepth + 1)) {
313
+ return true;
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ return false;
320
+ }
321
+
322
+ findArraysInDeepNesting(schema, 0);
323
+ }
324
+
325
+ function checkArraySizeLimits(schema: JSONSchema7, path: string): void {
326
+ // Recursively check all array constraints in the schema
327
+ if (schema.type === "array") {
328
+ // Check for dangerously large maxItems
329
+ if (schema.maxItems && schema.maxItems > MAX_ARRAY_SIZE) {
330
+ throw new ResourceLimitError(
331
+ "array_max_items",
332
+ MAX_ARRAY_SIZE,
333
+ schema.maxItems,
334
+ );
335
+ }
336
+
337
+ // Check for combination of deep nesting and large arrays
338
+ const depth = calculateNestingDepth(schema);
339
+ const estimatedSize =
340
+ schema.maxItems || schema.minItems || DEFAULT_ARRAY_COUNT;
341
+
342
+ // If we have deep nesting and large arrays, it could cause memory issues
343
+ if (
344
+ depth > DEEP_NESTING_THRESHOLD &&
345
+ estimatedSize > LARGE_ARRAY_THRESHOLD
346
+ ) {
347
+ throw new ResourceLimitError(
348
+ "memory_estimation",
349
+ DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD,
350
+ depth * estimatedSize,
351
+ );
352
+ }
353
+ }
354
+
355
+ // Recursively check nested schemas
356
+ if (schema.type === "object" && schema.properties) {
357
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
358
+ if (isJSONSchema7(propSchema)) {
359
+ checkArraySizeLimits(propSchema, `${path}.properties.${propName}`);
360
+ }
361
+ }
362
+ }
363
+
364
+ if (schema.type === "array" && schema.items) {
365
+ if (Array.isArray(schema.items)) {
366
+ schema.items.forEach((item, index) => {
367
+ if (isJSONSchema7(item)) {
368
+ checkArraySizeLimits(item, `${path}.items[${index}]`);
369
+ }
370
+ });
371
+ } else if (isJSONSchema7(schema.items)) {
372
+ checkArraySizeLimits(schema.items, `${path}.items`);
373
+ }
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Validate that faker method string references a valid Faker.js API
379
+ * Checks format (namespace.method) and validates against known namespaces
380
+ * @param fakerMethod - Faker method string (e.g., "person.fullName")
381
+ * @throws {SchemaValidationError} When faker method format or namespace is invalid
382
+ */
383
+ export function validateFakerMethod(fakerMethod: string): void {
384
+ // Check if faker method follows valid format (namespace.method)
385
+ const parts = fakerMethod.split(".");
386
+ if (parts.length < 2) {
387
+ throw new SchemaValidationError(
388
+ "$.faker",
389
+ `Invalid faker method format: "${fakerMethod}"`,
390
+ "Use format like 'person.firstName' or 'internet.email'",
391
+ );
392
+ }
393
+
394
+ // Validate by resolving the method path on a real faker instance
395
+ const faker = createFakerInstance();
396
+ let current: any = faker;
397
+ for (const part of parts) {
398
+ if (current && typeof current === "object" && part in current) {
399
+ current = current[part];
400
+ } else {
401
+ throw new SchemaValidationError(
402
+ "$.faker",
403
+ `Invalid faker method: "${fakerMethod}"`,
404
+ "Check faker.js documentation for valid methods",
405
+ );
406
+ }
407
+ }
408
+ if (typeof current !== "function") {
409
+ throw new SchemaValidationError(
410
+ "$.faker",
411
+ `Invalid faker method: "${fakerMethod}" is not a function`,
412
+ "Check faker.js documentation for valid methods",
413
+ );
414
+ }
415
+ }