diff --git a/src/client.js b/src/client.js index c82bd1a..2b34130 100644 --- a/src/client.js +++ b/src/client.js @@ -276,11 +276,16 @@ export default class Client { /** * Creates an enum to be used in a {@link Query} or {@link Mutation}. * + * The key is written into the query document unquoted, so it must be a valid GraphQL + * name. Do not pass untrusted input here without allow-listing it first; prefer sending + * request-derived values as a typed variable (see {@link Client#variable}). + * * @example * const titleEnum = client.enum('TITLE'); * * @param {String} key The key of the enum. * @return {Enum} An enum object that can be used in a {@link Query} or {@link Mutation}. + * @throws {Error} If `key` is not a valid GraphQL name. */ enum(key) { return enumFunction(key); diff --git a/src/enum.js b/src/enum.js index 8fbeab7..9326467 100644 --- a/src/enum.js +++ b/src/enum.js @@ -1,12 +1,21 @@ +// GraphQL `Name` grammar, which every enum value must match: +// https://spec.graphql.org/October2021/#Name +const GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/; + export class Enum { /** * This constructor should not be invoked directly. * Use the factory function {@link Client#enum} to create an Enum. * - * @param {String} key The key of the enum. + * @param {String} key The key of the enum. Must be a valid GraphQL name, since it is + * written into the query document unquoted. + * @throws {Error} If `key` is not a valid GraphQL name. */ constructor(key) { + if (!GRAPHQL_NAME.test(String(key))) { + throw new Error(`Invalid enum key: ${JSON.stringify(key)}. Enum keys must match ${GRAPHQL_NAME}.`); + } this.key = key; } diff --git a/test/format-args-test.js b/test/format-args-test.js index 4fbed34..57f1e0b 100644 --- a/test/format-args-test.js +++ b/test/format-args-test.js @@ -34,6 +34,23 @@ suite('format-args-test', () => { assert.equal(result, ' (list: [ONE TWO])'); }); + test('it rejects enum keys that are not valid GraphQL names', () => { + const payload = 'SAFE) { id } deleteAllWidgets { count } } #'; + + assert.throws(() => formatArgs({mode: _enum(payload)}), /Invalid enum key/); + assert.throws(() => _enum(''), /Invalid enum key/); + assert.throws(() => _enum('ONE TWO'), /Invalid enum key/); + assert.throws(() => _enum('1ONE'), /Invalid enum key/); + assert.throws(() => _enum('ONE\n'), /Invalid enum key/); + assert.throws(() => _enum('ONE)'), /Invalid enum key/); + }); + + test('it still formats enums with valid GraphQL names unquoted', () => { + const result = formatArgs({mode: _enum('SAFE'), other: _enum('_private_1')}); + + assert.equal(result, ' (mode: SAFE other: _private_1)'); + }); + test('it formats args with wrapped scalars', () => { const result = formatArgs({int: new Scalar(1), float: new Scalar(0.1), string: new Scalar('two'), boolean: new Scalar(true)});