|
| 1 | +import { GraphQLError } from 'graphql' |
| 2 | + |
| 3 | +/** |
| 4 | + * Maximum allowed query size in bytes (100KB) |
| 5 | + */ |
| 6 | +const MAX_QUERY_SIZE = 102400 |
| 7 | + |
| 8 | +/** |
| 9 | + * Validates request body structure and content |
| 10 | + * @param {unknown} body - Request body to validate |
| 11 | + * @returns {void} |
| 12 | + * @throws {GraphQLError} If validation fails |
| 13 | + */ |
| 14 | +export function validate_request_body(body) { |
| 15 | + // Check if body is an object (not array, null, or primitive) |
| 16 | + if (!body || typeof body !== 'object' || Array.isArray(body)) { |
| 17 | + throw new GraphQLError('Request body must be an object') |
| 18 | + } |
| 19 | + |
| 20 | + // Check if query is provided and is a string |
| 21 | + if (body.query !== undefined && typeof body.query !== 'string') { |
| 22 | + throw new GraphQLError('Query must be a string') |
| 23 | + } |
| 24 | + |
| 25 | + // Check query size limit |
| 26 | + if (body.query && body.query.length > MAX_QUERY_SIZE) { |
| 27 | + throw new GraphQLError( |
| 28 | + `Query too large (${body.query.length} bytes, max ${MAX_QUERY_SIZE} bytes)`, |
| 29 | + ) |
| 30 | + } |
| 31 | + |
| 32 | + // Check variables is object if provided |
| 33 | + if ( |
| 34 | + body.variables !== undefined && |
| 35 | + body.variables !== null && |
| 36 | + typeof body.variables !== 'object' |
| 37 | + ) { |
| 38 | + throw new GraphQLError('Variables must be an object') |
| 39 | + } |
| 40 | + |
| 41 | + // Check operationName is string if provided |
| 42 | + if ( |
| 43 | + body.operationName !== undefined && |
| 44 | + body.operationName !== null && |
| 45 | + typeof body.operationName !== 'string' |
| 46 | + ) { |
| 47 | + throw new GraphQLError('Operation name must be a string') |
| 48 | + } |
| 49 | + |
| 50 | + // Check operation_name is string if provided (snake_case variant) |
| 51 | + if ( |
| 52 | + body.operation_name !== undefined && |
| 53 | + body.operation_name !== null && |
| 54 | + typeof body.operation_name !== 'string' |
| 55 | + ) { |
| 56 | + throw new GraphQLError('Operation name must be a string') |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Wraps build_context with timeout protection |
| 62 | + * @param {Function} build_context - Context builder function |
| 63 | + * @param {number} timeout_ms - Timeout in milliseconds (default 5000) |
| 64 | + * @returns {Function} Wrapped context builder |
| 65 | + */ |
| 66 | +export function with_timeout(build_context, timeout_ms = 5000) { |
| 67 | + return async (...args) => { |
| 68 | + const timeout_promise = new Promise((_, reject) => |
| 69 | + setTimeout( |
| 70 | + () => reject(new Error('Context building timed out')), |
| 71 | + timeout_ms, |
| 72 | + ), |
| 73 | + ) |
| 74 | + |
| 75 | + return Promise.race([build_context(...args), timeout_promise]) |
| 76 | + } |
| 77 | +} |
0 commit comments