diff --git a/packages/api/src/directives.ts b/packages/api/src/directives.ts index b4a32bf5e..435166539 100644 --- a/packages/api/src/directives.ts +++ b/packages/api/src/directives.ts @@ -5,16 +5,18 @@ import { SanitizedString } from './scalars' export const sanitizeDirectiveTransformer = (schema: GraphQLSchema) => { return mapSchema(schema, { [MapperKind.FIELD]: (fieldConfig) => { - const sanitizeDirective = getDirective(schema, fieldConfig, 'sanitize') - if (!sanitizeDirective || sanitizeDirective.length < 1) { + const sanitizeDirective = getDirective( + schema, + fieldConfig, + 'sanitize' + )?.[0] + if (!sanitizeDirective) { return fieldConfig } - const maxLength = sanitizeDirective[0].maxLength as number | undefined - const allowedTags = sanitizeDirective[0].allowedTags as - | string[] - | undefined - const pattern = sanitizeDirective[0].pattern as RegExp | undefined + const maxLength = sanitizeDirective.maxLength as number | undefined + const allowedTags = sanitizeDirective.allowedTags as string[] | undefined + const pattern = sanitizeDirective.pattern as string | undefined if ( fieldConfig.type instanceof GraphQLNonNull && diff --git a/packages/api/src/scalars.ts b/packages/api/src/scalars.ts index 2f0de333a..22404534f 100644 --- a/packages/api/src/scalars.ts +++ b/packages/api/src/scalars.ts @@ -9,10 +9,14 @@ export class SanitizedString extends GraphQLScalarType { type: GraphQLScalarType, allowedTags?: string[], maxLength?: number, - pattern?: RegExp + pattern?: string ) { super({ - name: `SanitizedString_${allowedTags}_${maxLength}_${pattern}`, + // Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ as per graphql-js + name: `SanitizedString_${allowedTags}_${maxLength}_${pattern}`.replace( + /\W/g, + '' + ), description: 'Source string that was sanitized', serialize(value: string) { @@ -26,7 +30,7 @@ export class SanitizedString extends GraphQLScalarType { `Specified value cannot be longer than ${maxLength} characters` ) } - if (pattern && !pattern.test(value)) { + if (pattern && !new RegExp(pattern).test(value)) { throw new Error(`Specified value does not match pattern`) } return sanitize(value, { allowedTags: allowedTags || [] }) @@ -40,7 +44,7 @@ export class SanitizedString extends GraphQLScalarType { `Specified value cannot be longer than ${maxLength} characters` ) } - if (pattern && !pattern.test(value)) { + if (pattern && !new RegExp(pattern).test(value)) { throw new Error(`Specified value does not match pattern`) } return sanitize(value, { allowedTags: allowedTags || [] })