{"id":20407819,"url":"https://github.com/restorando/graphql-query-whitelist","last_synced_at":"2025-04-12T15:21:33.302Z","repository":{"id":57253564,"uuid":"72154456","full_name":"restorando/graphql-query-whitelist","owner":"restorando","description":"GraphQL query whitelisting middleware","archived":false,"fork":false,"pushed_at":"2017-04-29T19:08:57.000Z","size":48,"stargazers_count":18,"open_issues_count":0,"forks_count":2,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-03-26T09:51:13.643Z","etag":null,"topics":["graphql","graphql-js","graphql-server","middleware","node","nodejs"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/restorando.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-10-27T22:49:59.000Z","updated_at":"2025-02-10T16:47:35.000Z","dependencies_parsed_at":"2022-08-31T22:11:54.792Z","dependency_job_id":null,"html_url":"https://github.com/restorando/graphql-query-whitelist","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/restorando%2Fgraphql-query-whitelist","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/restorando%2Fgraphql-query-whitelist/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/restorando%2Fgraphql-query-whitelist/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/restorando%2Fgraphql-query-whitelist/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/restorando","download_url":"https://codeload.github.com/restorando/graphql-query-whitelist/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248166929,"owners_count":21058481,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","graphql-js","graphql-server","middleware","node","nodejs"],"created_at":"2024-11-15T05:26:25.214Z","updated_at":"2025-04-12T15:21:33.248Z","avatar_url":"https://github.com/restorando.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# graphql-query-whitelist\nA simple GraphQL query whitelist toolkit for `express`.\n\nIt includes:\n\n* An `express` middleware that prevents queries not in the whitelist to be executed. It also allows to execute queries just passing a previously stored `queryId` instead of the full query.\n* A REST API to create/get/list/enable/disable/delete queries from the whitelist\n* A `MemoryStore` and `RedisStore` to store the queries\n* An utility class (`QueryRepository`) to perform CRUD operations programmatically\n* A binary (`gql-whitelist`) that whitelist all the files with `.graphql` extension in a specified directory (useful to automatically whitelist queries on build time)\n\nA UI to manage the whitelisted queries is [available here](https://github.com/restorando/graphql-query-whitelist-ui)\n\n# Rationale\n\nOne of the security concerns for a typical GraphQL app is that it lacks of a security mechanism out of the box.\n\nBy default, anyone can query any field of your GraphQL app, and if your schema supports nested queries, a malicious attacker could make a query that consumes all the resources of the server.\n\nExample:\n\n```\nquery RecursiveQuery {\n  friends {\n    username\n\n    friends {\n      username\n\n      friends {\n        username\n\n        friends { ... }\n      }\n    }\n  }\n}\n```\n\nThis middleware avoids this type of queries checking if the incoming query is whitelisted or not.\n\n(more info: [source 1](https://edgecoders.com/graphql-deep-dive-the-cost-of-flexibility-ee50f131a83d#.6okcpvtri), [source 2](https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a))\n\n# Installation\n\n`npm install --save graphql-query-whitelist graphql body-parser`\n\nIn your app:\n\n```js\nimport express from 'express'\nimport bodyParser from 'body-parser'\nimport graphqlWhitelist, { MemoryStore } from 'graphql-query-whitelist'\n\nconst app = express()\nconst store = new MemoryStore()\n// body-parser must be included before including the query whitelist middleware\napp.use(bodyParser.json())\napp.post('/graphql', graphqlWhitelist({ store }))\n```\n\nBefore each request is processed by GraphQL, it will check if the inbound query is in the whitelist or not.\nIf it's not in the whitelist, it will respond with a 401 status code.\n\n# Running queries only sending the `queryId`\n\nSince the server has access to the query store, and the store has access to the full queries, it's possible to run a query just by sending the queryId.\n\nE.g: `POST /graphql?queryId=dSPDigYWUw2w9wTI9g0RrbakmsJiRFIvTUa59jnZsV4=`\n\n# Storing and retrieving queries\n\nThere are 2 ways of storing and retrieving queries:\n\n### Rest API\n\nNormally you would want to automate the process of storing queries at the build time.\n\nThis library includes a Rest API that you can mount in any `express` app to list, create, get, enable/disable and delete queries.\n\nExample:\n\n```js\nimport { Api as whitelistAPI, RedisStore } from 'graphql-query-whitelist'\napp.use('/whitelist', whitelistAPI(new RedisStore()))\n```\n\nIt will mount these routes:\n\n```\nGET /whitelist/queries\nGET /whitelist/queries/:id\nPOST /whitelist/queries\nPUT /whitelist/queries/:id\nDELETE /whitelist/queries/:id\n```\n\n## Programmatically using the `QueryRepository`\n\nExample:\n\n```js\nimport { QueryRepository, MemoryStore } from 'graphql-query-whitelist'\n\nconst store = new MemoryStore()\nconst repository = new QueryRepository(store)\n\nconst query = `\n  query MyQuery {\n    users {\n      firstName\n    }\n  }\n`\n\nrepository.put(query).then(console.log)\n\n/*\n * Prints:\n * {\n *   id: 'dSPDigYWUw2w9wTI9g0RrbakmsJiRFIvTUa59jnZsV4=',\n *   query: 'query MyQuery {\\n  users {\\n    firstName\\n  }\\n}\\n',\n *   operationName: 'MyQuery',\n *   enabled: true\n *  }\n */\n```\n\nThe `QueryRepository` class exposes the following methods:\n\n* `get(queryId)`\n* `put(query)`\n* `update(queryId, properties)`\n* `entries()`\n* `delete(queryId)`\n\n# Stores\n\nA store is the medium to list, get, store and delete queries.\n\nIt must implement the following methods:\n\n##### `get(key)`\nIt returns a `Promise` that resolves to the value for that key\n\n#### `set(key, value)`\nReturns a `Promise` that is resolved after the value is saved in the store\n\n#### `entries()`\nReturns a `Promise` that resolves to an array of all the entries stored, having the following format:\n`[[key1, val1], [key2, val2], ...]`\n\n#### `delete(key)`\nReturns a `Promise` that is resolved after the element is deleted from the store\n\n#### `clear()`\nReturns a `Promise` that is resolved after all the elements are deleted from the store\n\nIncluding in this library are 2 stores:\n\n* `MemoryStore`\n* `RedisStore` (needs to have [ioredis](https://github.com/luin/ioredis) installed)\n\nThe `RedisStore` receives the [same constructor arguments as ioredis](https://github.com/luin/ioredis#connect-to-redis).\n\n# Middleware Options\n\n### store\n\nThis property is mandatory and must be a valid query store.\n\n### skipValidationFn\n\nThis property is optional and must be a function that receives the `express` request object and returns a boolean value. If a truthy value is returned, the whitelist check is skipped and the query is executed.\n\nThis option is very useful to skip the whitelist check for certain apps that are already sending dynamic queries that are impossible to add to the whitelist.\n\nExample:\n\n```js\nconst skipValidationFn = (req) =\u003e req.get('X-App-Version') !== 'legacy-app-1.0'\n\napp.post('/graphql', graphqlWhitelist({ store, skipValidationFn }))\n```\n\n### validationErrorFn\n\nThis property is optional and must be a function that receives the `express` request object and will be called for every query that is prevented to be executed by this middleware.\n\nExample:\n\n```js\nimport { verbose, warn } from 'utils/log'\n\nconst validationErrorFn = (req) =\u003e {\n  warn(`Query '${req.operationName} (${req.queryId})' is not in the whitelist`)\n  verbose(`Unauthorized query: ${req.body.query}`)\n}\n\napp.post('/graphql', graphqlWhitelist({ store, validationErrorFn }))\n```\n\n### storeIntrospectionQueries\n\nIf this option is set to true, `graphql-query-whitelist` will add to the whitelist all GraphQL and GraphiQL introspection queries.\n\nThis option is disabled by default, but is needed if you are using GraphiQL and need to have the introspection queries whitelisted in order to have the autocompletion feature working.\n\nExample:\n\n```js\napp.post('/graphql', graphqlWhitelist({ store, storeIntrospectionQueries: true }))\n```\n\n### dryRun\n\nIf this option is set to true, `graphql-query-whitelist` will validate the query against the whitelist and the `validationErrorFn` will be called, but the query will be executed as if the middleware is disabled.\n\nThis is useful if you are starting to whitelist the queries long after your GraphQL server was first launched, and you need to log all the queries that are not yet whitelisted.\n\nExample:\n\n```js\napp.post('/graphql', graphqlWhitelist({ store, dryRun: true }))\n```\n\n# Whitelisting queries automatically\n\nYou may want to whitelist new queries everytime a query is added/changed in your project. This depends on `graphql` so make sure `graphql` is installed as well.\n\n```bash\n$ npm install -g graphql-query-whitelist graphql\n\n$ gql-whitelist --endpoint http://your.graphql-endpoint.com/graphql /path/to/directory/containing/.graphql/files\n```\n\nAdditionally, you can specify headers using the option `--header`\n\n```bash\n$ gql-whitelist --endpoint http://your.graphql-endpoint.com/graphql --header key=value --header key2=value2 /path/to/directory/containing/.graphql/files\n```\n\n## License\n\nCopyright (c) 2016 Restorando\n\nMIT License\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frestorando%2Fgraphql-query-whitelist","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frestorando%2Fgraphql-query-whitelist","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frestorando%2Fgraphql-query-whitelist/lists"}