CVE-2021-41248: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: GraphiQL is the reference implementation of this monorepo, GraphQL IDE, an official project under the GraphQL Foundation. All versions of graphiql older than graphiql@1.4.7 are vulnerable to compromised HTTP schema introspection responses or schema prop values with malicious GraphQL type names, exposing a dynamic XSS attack surface that can allow code injection on operation autocomplete. In order for the attack to take place, the user must load a vulnerable schema in graphiql. There are a number of ways that can occur. By default, the schema URL is not attacker-controllable in graphiql or in its suggested implementations or examples, leaving only very complex attack vectors. If a custom implementation of graphiql's fetcher allows the schema URL to be set dynamically, such as a URL query parameter like ?endpoint= in graphql-playground, or a database provided value, then this custom graphiql implementation is vulnerable to phishing attacks, and thus much more readily available, low or no privelege level xss attacks. The URLs could look like any generic looking graphql schema URL. It should be noted that desktop clients such as Altair, Insomnia, Postwoman, do not appear to be impacted by this. This vulnerability does not impact codemirror-graphql, monaco-graphql or other dependents, as it exists in onHasCompletion.ts in graphiql. It does impact all forks of graphiql, and every released version of graphiql.
CWE description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
CVSS v3 base score: 4.7
Published: 2021-11-04T21:15Z
Repository: https://github.com/graphql/graphiql
Language: Markdown
Files changed: README.md, SECURITY.md, docs/security/2021-introspection-schema-xss.md, packages/graphiql/README.md, packages/graphiql/cypress/integration/init.spec.ts, packages/graphiql/cypress/support/commands.ts, packages/graphiql/package.json, packages/graphiql/resources/renderExample.js, packages/graphiql/src/components/DocExplorer.tsx, packages/graphiql/src/components/GraphiQL.tsx, packages/graphiql/src/utility/onHasCompletion.ts, packages/graphiql/test/bad-schema.js, packages/graphiql/test/beforeDevServer.js, packages/graphiql/test/e2e-server.js, yarn.lock
Commit date: 2021-11-04 18:29:13 +0100
Commit message: Merge pull request from GHSA-x4r7-m2q9-69c8

This change fixes an XSS vulnerability that has been present since the first
commit of GraphiQL when used with an untrusted GraphQL server. It applies three
strategies to fix via defense-in-depth: HTML escaping a string in a contexts
that uses innerHTML; validating incoming schemas with graphql-js validateSchema;
and updating markdown-it to the latest version.

See docs/security/2021-introspection-schema-xss.md for more details.

Co-authored-by: Rikki <rikki.schulte@gmail.com>
Diff: diff --git a/README.md b/README.md
index 728935a7..734f12dd 100644
--- a/README.md
+++ b/README.md
@@ -2,10 +2,12 @@
 
 > # Black Lives Matter 🖤
 
 # GraphQL IDE Monorepo
 
+> **Security Notice:** All versions of `graphiql` < `1.4.3` are vulnerable to an XSS attack in cases where the GraphQL server to which the GraphiQL web app connects is not trusted. Learn more [in the graphiql SECURITY.md](./packages/graphiql/SECURITY.md)
+
 > **Looking for the [GraphiQL Docs?](packages/graphiql/README.md)**: This is the root of the monorepo! The full GraphiQL docs are located at [`packages/graphiql`](packages/graphiql)
 
 [![Build Status](https://github.com/graphql/graphiql/workflows/Node.JS%20CI/badge.svg)](https://github.com/graphql/graphiql/actions?query=workflow%3A%22Node.JS+CI%22)
 [![Discord](https://img.shields.io/discord/625400653321076807.svg)](https://discord.gg/NP5vbPeUFp)
 [![Code Coverage](https://img.shields.io/codecov/c/github/graphql/graphiql)](https://codecov.io/gh/graphql/graphiql)
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 00000000..70f301c9
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,9 @@
+# GraphiQL Ecosystem Security Advisories
+
+Security Advisories for packages in this repository will be listed here
+
+## GraphiQL
+
+### 2021
+
+- [Introspection Schema XSS Attack](./docs/security/2021-introspection-schema-xss.md)
diff --git a/docs/security/2021-introspection-schema-xss.md b/docs/security/2021-introspection-schema-xss.md
new file mode 100644
index 00000000..597ec1cd
--- /dev/null
+++ b/docs/security/2021-introspection-schema-xss.md
@@ -0,0 +1,150 @@
+- [1. GraphiQL introspection schema template injection attack: Advisory Statement](#1-graphiql-introspection-schema-template-injection-attack-advisory-statement)
+  - [1.1. Impact](#11-impact)
+  - [1.2. Scope](#12-scope)
+  - [1.3. Patches](#13-patches)
+  - [1.3.1 CDN bundle implementations may be automatically patched](#131-cdn-bundle-implementations-may-be-automatically-patched)
+  - [1.4. Workarounds for Older Versions](#14-workarounds-for-older-versions)
+  - [1.5. How to Re-create the Exploit](#15-how-to-re-create-the-exploit)
+  - [1.6. Credit](#16-credit)
+  - [1.7. References](#17-references)
+  - [1.8. For more information](#18-for-more-information)
+- [2. More Details on the Vulnerability](#2-more-details-on-the-vulnerability)
+- [3. Compromised introspection Schema Example](#3-compromised-introspection-schema-example)
+
+## 1. GraphiQL introspection schema template injection attack: Advisory Statement
+
+This is a security advisory for an XSS vulnerability in `graphiql`.
+
+A similar vulnerability affects `graphql-playground`, a fork of `graphiql`. There is a corresponding `graphql-playground` [advisory](https://github.com/graphql/graphql-playground/security/advisories/GHSA-59r9-6jp6-jcm7) and [Apollo Server advisory](https://github.com/apollographql/apollo-server/security/advisories/GHSA-qm7x-rc44-rrqw).
+
+### 1.1. Impact
+
+All versions of `graphiql` older than [`graphiql@1.4.3`](https://github.com/graphql/graphiql/releases/tag/v1.4.3) are vulnerable to compromised HTTP schema introspection responses or `schema` prop values with malicious GraphQL type names, exposing a dynamic XSS attack surface that can allow code injection on operation autocomplete.
+
+In order for the attack to take place, the user must load a vulnerable schema in `graphiql`. There are a number of ways that can occur.
+
+By default, the schema URL is _not_ attacker-controllable in `graphiql` or in its suggested implementations or examples, leaving only very complex attack vectors.
+
+If a custom implementation of `graphiql`'s `fetcher` allows the schema URL to be set dynamically, such as a URL query parameter like `?endpoint=` in `graphql-playground`, or a database provided value, then this custom `graphiql` implementation is _vulnerable to phishing attacks_, and thus much more readily available, low or no privelege level xss attacks. The URLs could look like any generic looking graphql schema URL.
+
+Because this exposes an XSS attack surface, it would be possible for a threat actor to exfiltrate user credentials, data, etc. using arbitrary malicious scripts, without it being known to the user.
+
+### 1.2. Scope
+
+This advisory describes the impact on the `graphiql` package. The vulnerability also affects other projects forked from `graphiql` such as [`graphql-playground`](https://github.com/graphql/graphql-playground/security/advisories/GHSA-59r9-6jp6-jcm7) and the `graphql-playground` fork distributed by Apollo Server. The impact is more severe in the `graphql-playground` implementations; see the [`graphql-playground` advisory](https://github.com/graphql/graphql-playground/security/advisories/GHSA-59r9-6jp6-jcm7) and [Apollo Server advisory](https://github.com/apollographql/apollo-server/security/advisories/GHSA-qm7x-rc44-rrqw) for details.
+
+This vulnerability does not impact `codemirror-graphql`, `monaco-graphql` or other dependents, as it exists in `onHasCompletion.ts` in `graphiql`. It does impact all forks of `graphiql`, and every released version of `graphiql`.
+
+It should be noted that desktop clients such as Altair, Insomnia, Postwoman, do not appear to be impacted by this.
+
+### 1.3. Patches
+
+`graphiql@1.4.3` addresses this issue via defense in depth.
+
+- **HTML-escaping text** that should be treated as text rather than HTML. In most of the app, this happens automatically because React escapes all interpolated text by default. However, one vulnerable component uses the unsafe `innerHTML` API and interpolated type names directly into HTML. We now properly escape that type name, which fixes the known vulnerability.
+
+- **Validates the schema** upon receiving the introspection response or schema changes. Schemas with names that violate the GraphQL spec will no longer be loaded. (This includes preventing the Doc Explorer from loading.) This change is also sufficient to fix the known vulnerability. You can disable this validation by setting `dangerouslyAssumeSchemaIsValid={true}`, which means you are relying only on escaping values to protect you from this attack.
+
+- **Ensuring that user-generated HTML is safe**. Schemas can contain Markdown in `description` and `deprecationReason` fields, and the web app renders them to HTML using the `markdown-it` library. As part of the development of `graphiql@1.4.3`, we verified that our use of `markdown-it` prevents the inclusion of arbitrary HTML. We use `markdown-it` without setting `html: true`, so we are comfortable relying on [`markdown-it`'s HTML escaping](https://github.com/markdown-it/markdown-it/blob/master/docs/security.md) here. We considered running a second level of sanitization over all rendered Markdown using a library such as `dompurify` but believe that is unnecessary as `markdown-it`'s sanitization appears to be adequate. `graphiql@1.4.3` does update to the latest version of `markdown-it` (v12, from v10) so that any security fixes in v11 and v12 will take effect.
+
+### 1.3.1 CDN bundle implementations may be automatically patched
+
+Note that if your implementation is depending on a CDN version of `graphiql`, and is pointed to the `latest` tag (usually the default for most cdns if no version is specified) then this issue is already mitigated, in case you were vulnerable to it before.
+
+### 1.4. Workarounds for Older Versions
+
+If you cannot use `graphiql@1.4.3` or later
+
+- Always use a static URL to a trusted server that is serving a trusted GraphQL schema.
+
+- If you have a custom implementation that allows using user-provided schema URLs via a query parameter, database value, etc, you must either disable this customization, or only allow trusted URLs.
+
+### 1.5. How to Re-create the Exploit
+
+You can see an example on [codesandbox](https://codesandbox.io/s/graphiql-xss-exploit-gr22f?file=/src/App.js). These are both fixed to the last `graphiql` release `1.4.2` which is the last vulnerable release; however it would work with any previous release of `graphiql`.
+
+Both of these examples are meant to demonstrate the phishing attack surface, so they are customized to accept a `url` parameter. To demonstrate the phishing attack, add `?url=https://graphql-xss-schema.netlify.app/graphql` to the in-codesandbox browser.
+
+Erase the contents of the given query and type `{u`. You will see an alert window open, showing that attacker-controlled code was executed.
+
+Note that when React is in development mode, a validation exception is thrown visibly; however that exception is usually buried in the browser console in a production build of `graphiql`. This validation exception comes from `getDiagnostics`, which invokes `graphql` `validate()` which in turn will `assertValidSchema()`, as `apollo-server-core` does on executing each operation. This validation does not prevent the exploit from being successful.
+
+Note that something like the `url` parameter is not required for the attack to happen if `graphiql`'s `fetcher` is configured in a different way to communicate with a compromised GraphQL server.
+
+### 1.6. Credit
+
+This vulnerability was discovered by [@Ry0taK](https://github.com/Ry0taK), thank you! :1st_place_medal:
+
+Others who contributed:
+
+- [@imolorhe](https://github.com/imolorhe)
+- [@glasser](https://github.com/glasser)
+- [@divyenduz](https://github.com/divyenduz)
+- [@dotansimha](https://github.com/dotansimha)
+- [@acao](https://github.com/acao)
+- [@benjie](https://github.com/benjie) and many others who provided morale support
+
+### 1.7. References
+
+**The vulnerability has always been present**
+
+[In the first commit](https://github.com/graphql/graphiql/commit/b9dec272d89d9c590727fd10d62e4a47e0317fc7#diff-855b77f6310b7e4fb1bcac779cd945092ed49fd759f4684ea391b45101166437R87)
+
+[And later moved to onHasCompletion.js in 2016](https://github.com/graphql/graphiql/commit/6701b0b626e43800e32413590a295e5c1e3d5419#diff-d45eb76aebcffd27d3a123214487116fa95e0b5a11d70a94a0ce3033ce09f879R110) (now `.ts` after the typescript migration)
+
+### 1.8. For more information
+
+If you have any questions or comments about this advisory:
+
+- Open an issue in [graphiql repo](https://github.com/graphql/graphiql/new/issues)
+
+## 2. More Details on the Vulnerability
+
+This section provides more details in addition to the advisory.
+
+An installation of the GraphiQL web app is vulnerable if two conditions are met:
+
+- The web app trusts information from its corresponding GraphQL server by interpolating information such as GraphQL type names directly into HTML instead of appropriately escaping or sanitizing the information.
+- The victim can load the web app in a way where it speaks to a GraphQL server controlled by the attacker.
+
+All versions of `graphiql` prior to 1.4.3 inappropriately trust type names provided by the GraphQL server. They additionally rely on XSS filtering in the `markdown-it` package to try to protect themselves from XSS attacks in GraphQL descriptions and deprecation reasons.
+
+By default, `graphiql` does _not_ allow the attacker to control what GraphQL server it speaks to. Therefore, many installations of `graphiql` are not affected by this advisory. Installations are only affected if the `fetcher` argument provided to GraphiQL allows arbitrary customization of the GraphQL endpoint (eg, reading a GraphQL URL from an URL parameter), or if the attacker has another way of affecting the introspection schema returned by the GraphQL server. (Note that `graphql-playground`, a project which started as a fork of `graphiql`, does this sort of URL parsing by default, so `graphql-playground` installations _are_ affected by a corresponding vulnerability in their default configuration.)
+
+One example of "another way of affecting the introspection schema" would be if you served `graphiql` as part of a PAAS platform that allows users to define their own GraphQL schemas. In this case, even though the `graphiql` installation might be hard-wired to a single GraphQL endpoint, the attacker has control over that GraphQL endpoint and could use it to inject scripts into `graphiql`. In this case, your `graphiql` installation could be vulnerable if it responds to introspection requests without first validating its schema. GraphQL servers can prevent this by refusing to execute operations (including introspection operations) on invalid schemas; any server built with `graphql-js` properly validates its schema prior to execution.
+
+## 3. Compromised introspection Schema Example
+
+You can view the code for the exploited schema [on codesandbox](https://codesandbox.io/s/graphql-xss-compromised-schema-3wdq7?file=/src/bad-schema.js) or [in the repository](../../packages/graphiql/test/bad-schema.js)
+
+As you can see, the introspection schema must contain items with a compromised `name` value. this could be fields, input object names, enum names, variable names, etc any graphql [NamedType](https://github.com/graphql/graphql-spec/blob/main/spec/Section%202%20--%20Language.md#type-references) in the schema with it's name rendered in the autocomplete list.
+
+```json
+{
+  "kind": "OBJECT",
+  "name": "<img src=x onerror=alert(document.domain)>",
+  "description": null,
+  "fields": [
+    {
+      "name": "name",
+      "description": null,
+      "args": [],
+      "type": {
+        "kind": "NON_NULL",
+        "name": null,
+        "ofType": {
+          "kind": "SCALAR",
+          "name": "String",
+          "ofType": null
+        }
+      },
+      "isDeprecated": false,
+      "deprecationReason": null
+    }
+  ],
+  "inputFields": null,
+  "interfaces": [],
+  "enumValues": null,
+  "possibleTypes": null
+}
+```
diff --git a/packages/graphiql/README.md b/packages/graphiql/README.md
index 6389d776..cc06c35f 100644
--- a/packages/graphiql/README.md
+++ b/packages/graphiql/README.md
@@ -1,10 +1,10 @@
 # GraphiQL
 
-> **Breaking Changes & Improvements:** several interfaces are being dropped for new ones for GraphiQL 2.0.0! Read more in [this issue](https://github.com/graphql/graphiql/issues/1165)
+> **Security Notice:** All versions of `graphiql` < `1.4.3` are vulnerable to an XSS attack in cases where the GraphQL server to which the GraphiQL web app connects is not trusted. Learn more in [our security advisory](https://github.com/graphql/graphiql/tree/main/docs/security/2021-introspection-schema-xss.md).
 
-> **[`graphiql@1.0.0`](https://github.com/graphql/graphiql/milestone/3)** is coming soon & will provide a stable release with react 16, graphql 15 support, fixes, and a headers tab
+> **Breaking Changes & Improvements:** several interfaces are being dropped for new ones for GraphiQL 2.0.0! Read more in [this issue](https://github.com/graphql/graphiql/issues/1165)
 
 > **[`graphiql@2.0.0-beta`](https://github.com/graphql/graphiql/issues/983)** is a much larger ongoing effort that introduces plugins, i18n, and so many more features after a substantial rewrite using modern react.
 
 [![NPM](https://img.shields.io/npm/v/graphiql.svg)](https://npmjs.com/graphiql)
 ![jsDelivr hits (npm)](https://img.shields.io/jsdelivr/npm/hm/graphiql)
@@ -187,38 +187,39 @@ GraphiQL supports customization in UI and behavior by accepting React props and
 
 `fetcher` is the only required prop for `<GraphiQL />`.
 
 For more details on props, see the [API Docs](https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops)
 
-| Prop                         | Type                                                                                                  | Description                                                                                                                                                                                     |
-| ---------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `fetcher`                    | [`Fetcher function`](https://graphiql-test.netlify.app/typedoc/modules/graphiql-toolkit.html#fetcher) | **Required.** a function which accepts GraphQL-HTTP parameters and returns a Promise, Observable or AsyncIterable which resolves to the GraphQL parsed JSON response.                           |  |
-| `schema`                     | [`GraphQLSchema`](https://graphql.org/graphql-js/type/#graphqlschema)                                 | a GraphQLSchema instance or `null` if one is not to be used. If `undefined` is provided, GraphiQL will send an introspection query using the fetcher to produce a schema.                       |
-| `query`                      | `string` (GraphQL)                                                                                    | initial displayed query, if `undefined` is provided, the stored query or `defaultQuery` will be used. You can also set this value at runtime to override the current operation editor state.    |
-| `validationRules`            | `ValidationRule[]`                                                                                    | A array of validation rules that will be used for validating the GraphQL operations. If `undefined` is provided, the default rules (exported as `specifiedRules` from `graphql`) will be used.  |
-| `variables`                  | `string` (JSON)                                                                                       | initial displayed query variables, if `undefined` is provided, the stored variables will be used.                                                                                               |
-| `headers`                    | `string`                                                                                              | initial displayed request headers. if not defined, it will default to the stored headers if `shouldPersistHeaders` is enabled.                                                                  |
-| `externalFragments`          | `string \| FragmentDefinitionNode[]`                                                                  | provide fragments external to the operation for completion, validation, and for selective use when executing operations.                                                                        |
-| `operationName`              | `string`                                                                                              | an optional name of which GraphQL operation should be executed.                                                                                                                                 |
-| `response`                   | `string` (JSON)                                                                                       | an optional JSON string to use as the initial displayed response. If not provided, no response will be initially shown. You might provide this if illustrating the result of the initial query. |
-| `storage`                    | [`Storage`](https://graphiql-test.netlify.app/typedoc/interfaces/graphiql.storage.html)               | **Default:** `window.localStorage`. an interface that matches `window.localStorage` signature that GraphiQL will use to persist state.                                                          |
-| `defaultQuery`               | `string`                                                                                              | **Default:** graphiql help text. Provides default query if no user state is present.                                                                                                            | default graphiql help text |
-| `defaultVariableEditorOpen`  | `boolean`                                                                                             | sets whether or not to show the variables pane on startup. overridden by user state (**deprecated** in favor of `defaultSecondaryEditorOpen`)                                                   |
-| `defaultSecondaryEditorOpen` | `boolean`                                                                                             | sets whether or not to show the variables/headers pane on startup. If not defined, it will be based off whether or not variables and/or headers are present.                                    |
-| `getDefaultFieldNames`       | `Function`                                                                                            | **Default:** `defaultGetDefaultFieldNames`. provides default field values for incomplete queries                                                                                                | `defaultGetDefaultFieldNames` |
-| `editorTheme`                | `string`                                                                                              | **Default:** `graphiql`. names a CodeMirror theme to be applied to the `QueryEditor`, `ResultViewer`, and `Variables` panes. See below for full usage.                                          |
-| `readOnly`                   | `boolean`                                                                                             | when `true` will make the `QueryEditor` and `Variables` panes readOnly.                                                                                                                         |
-| `docExplorerOpen`            | `boolean`                                                                                             | when `true` will ensure the `DocExplorer` is open by default when the user first renders the component. Overridden by user's toggle state                                                       |
-| `headerEditorEnabled`        | `boolean`                                                                                             | **Default:** `false`. enables the header editor when `true`.                                                                                                                                    |
-| `shouldPersistHeaders`       | `boolean`                                                                                             | **Default:** `false`. o persist headers to storage when `true`                                                                                                                                  |
-| `toolbar.additionalContent`  | `React.Component[]`                                                                                   | pass additional toolbar react components inside a fragment                                                                                                                                      | `null` |
-| `onEditQuery`                | `Function`                                                                                            | called when the Query editor changes. The argument to the function will be the query string.                                                                                                    |
-| `onEditVariables`            | `Function`                                                                                            | called when the Query variable editor changes. The argument to the function will be the variables string.                                                                                       |
-| `onEditHeaders`              | `Function`                                                                                            | called when the request headers editor changes. The argument to the function will be the headers string.                                                                                        |
-| `onEditOperationName`        | `Function`                                                                                            | called when the operation name to be executed changes.                                                                                                                                          |
-| `onToggleDocs`               | `Function`                                                                                            | called when the docs will be toggled. The argument to the function will be a boolean whether the docs are now open or closed.                                                                   |
-| `maxHistoryLength`           | `number`                                                                                              | **Default:** 20. allows you to increase the number of queries in the history component                                                                                                          | 20 |
+| Prop                             | Type                                                                                                  | Description                                                                                                                                                                                     |
+| -------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `fetcher`                        | [`Fetcher function`](https://graphiql-test.netlify.app/typedoc/modules/graphiql-toolkit.html#fetcher) | **Required.** a function which accepts GraphQL-HTTP parameters and returns a Promise, Observable or AsyncIterable which resolves to the GraphQL parsed JSON response.                           |  |
+| `schema`                         | [`GraphQLSchema`](https://graphql.org/graphql-js/type/#graphqlschema)                                 | a GraphQLSchema instance or `null` if one is not to be used. If `undefined` is provided, GraphiQL will send an introspection query using the fetcher to produce a schema.                       |
+| `query`                          | `string` (GraphQL)                                                                                    | initial displayed query, if `undefined` is provided, the stored query or `defaultQuery` will be used. You can also set this value at runtime to override the current operation editor state.    |
+| `validationRules`                | `ValidationRule[]`                                                                                    | A array of validation rules that will be used for validating the GraphQL operations. If `undefined` is provided, the default rules (exported as `specifiedRules` from `graphql`) will be used.  |
+| `variables`                      | `string` (JSON)                                                                                       | initial displayed query variables, if `undefined` is provided, the stored variables will be used.                                                                                               |
+| `headers`                        | `string`                                                                                              | initial displayed request headers. if not defined, it will default to the stored headers if `shouldPersistHeaders` is enabled.                                                                  |
+| `externalFragments`              | `string \| FragmentDefinitionNode[]`                                                                  | provide fragments external to the operation for completion, validation, and for selective use when executing operations.                                                                        |
+| `operationName`                  | `string`                                                                                              | an optional name of which GraphQL operation should be executed.                                                                                                                                 |
+| `response`                       | `string` (JSON)                                                                                       | an optional JSON string to use as the initial displayed response. If not provided, no response will be initially shown. You might provide this if illustrating the result of the initial query. |
+| `storage`                        | [`Storage`](https://graphiql-test.netlify.app/typedoc/interfaces/graphiql.storage.html)               | **Default:** `window.localStorage`. an interface that matches `window.localStorage` signature that GraphiQL will use to persist state.                                                          |
+| `defaultQuery`                   | `string`                                                                                              | **Default:** graphiql help text. Provides default query if no user state is present.                                                                                                            | default graphiql help text |
+| `defaultVariableEditorOpen`      | `boolean`                                                                                             | sets whether or not to show the variables pane on startup. overridden by user state (**deprecated** in favor of `defaultSecondaryEditorOpen`)                                                   |
+| `defaultSecondaryEditorOpen`     | `boolean`                                                                                             | sets whether or not to show the variables/headers pane on startup. If not defined, it will be based off whether or not variables and/or headers are present.                                    |
+| `getDefaultFieldNames`           | `Function`                                                                                            | **Default:** `defaultGetDefaultFieldNames`. provides default field values for incomplete queries                                                                                                | `defaultGetDefaultFieldNames` |
+| `editorTheme`                    | `string`                                                                                              | **Default:** `graphiql`. names a CodeMirror theme to be applied to the `QueryEditor`, `ResultViewer`, and `Variables` panes. See below for full usage.                                          |
+| `readOnly`                       | `boolean`                                                                                             | when `true` will make the `QueryEditor` and `Variables` panes readOnly.                                                                                                                         |
+| `dangerouslyAssumeSchemaIsValid` | `boolean`                                                                                             | **Default:** `false`. When true, don't check that the loaded schema is valid; this can make the app vulnerable to XSS attacks and is not recommended.                                           |
+| `docExplorerOpen`                | `boolean`                                                                                             | when `true` will ensure the `DocExplorer` is open by default when the user first renders the component. Overridden by user's toggle state                                                       |
+| `headerEditorEnabled`            | `boolean`                                                                                             | **Default:** `false`. enables the header editor when `true`.                                                                                                                                    |
+| `shouldPersistHeaders`           | `boolean`                                                                                             | **Default:** `false`. o persist headers to storage when `true`                                                                                                                                  |
+| `toolbar.additionalContent`      | `React.Component[]`                                                                                   | pass additional toolbar react components inside a fragment                                                                                                                                      | `null` |
+| `onEditQuery`                    | `Function`                                                                                            | called when the Query editor changes. The argument to the function will be the query string.                                                                                                    |
+| `onEditVariables`                | `Function`                                                                                            | called when the Query variable editor changes. The argument to the function will be the variables string.                                                                                       |
+| `onEditHeaders`                  | `Function`                                                                                            | called when the request headers editor changes. The argument to the function will be the headers string.                                                                                        |
+| `onEditOperationName`            | `Function`                                                                                            | called when the operation name to be executed changes.                                                                                                                                          |
+| `onToggleDocs`                   | `Function`                                                                                            | called when the docs will be toggled. The argument to the function will be a boolean whether the docs are now open or closed.                                                                   |
+| `maxHistoryLength`               | `number`                                                                                              | **Default:** 20. allows you to increase the number of queries in the history component                                                                                                          | 20 |
 
 ### Children (this pattern will be dropped in 2.0.0)
 
 - `<GraphiQL.Logo>`: Replace the GraphiQL logo with your own.
 
diff --git a/packages/graphiql/cypress/integration/init.spec.ts b/packages/graphiql/cypress/integration/init.spec.ts
index 0c698d11..c93c0d72 100644
--- a/packages/graphiql/cypress/integration/init.spec.ts
+++ b/packages/graphiql/cypress/integration/init.spec.ts
@@ -42,6 +42,17 @@ describe('GraphiQL On Initialization', () => {
   });
 
   it('Executes a GraphQL query over HTTP that has the expected result', () => {
     cy.assertQueryResult({ query: testQuery }, mockSuccess);
   });
+  it('Shows the expected error when the schema is invalid', () => {
+    cy.visit(`/?bad=true`);
+    cy.assertResult({
+      errors: [
+        {
+          message:
+            'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "<img src=x onerror=alert(document.domain)>" does not.',
+        },
+      ],
+    });
+  });
 });
diff --git a/packages/graphiql/cypress/support/commands.ts b/packages/graphiql/cypress/support/commands.ts
index a6fdc018..28acf216 100644
--- a/packages/graphiql/cypress/support/commands.ts
+++ b/packages/graphiql/cypress/support/commands.ts
@@ -17,11 +17,12 @@ declare namespace Cypress {
     variablesString?: string;
   };
   type MockResult =
     | { data: any }
     | { data: any; hasNext?: boolean }
-    | { error: any[] };
+    | { error: any[] }
+    | { errors: any[] };
   interface Chainable<Subject = any> {
     /**
      * Custom command to select DOM element by data-cy attribute.
      * @example cy.dataCy('greeting')
      */
@@ -29,10 +30,11 @@ declare namespace Cypress {
     getCy(cyName: string): Chainable<Element>;
     clickExecuteQuery(): Chainable<Element>;
     visitWithOp(op: Op): Chainable<Element>;
     clickPrettify(): Chainable<Element>;
     assertHasValues(op: Op): Chainable<Element>;
+    assertResult(result: MockResult): Chainable<Element>;
     assertQueryResult(
       op: Op,
       expectedResult: MockResult,
       timeout?: number,
     ): Chainable<Element>;
@@ -89,5 +91,14 @@ Cypress.Commands.add('assertQueryResult', (op, mockSuccess, timeout = 200) => {
     // @ts-ignore
     const value = w.g.resultComponent.viewer.getValue();
     expect(value).to.deep.equal(JSON.stringify(mockSuccess, null, 2));
   });
 });
+
+Cypress.Commands.add('assertResult', (expectedResult, timeout = 200) => {
+  cy.wait(timeout);
+  cy.window().then(w => {
+    // @ts-ignore
+    const value = w.g.resultComponent.viewer.getValue();
+    expect(value).to.deep.equal(JSON.stringify(expectedResult, null, 2));
+  });
+});
diff --git a/packages/graphiql/package.json b/packages/graphiql/package.json
index 1437c5ae..a0455d9c 100644
--- a/packages/graphiql/package.json
+++ b/packages/graphiql/package.json
@@ -47,23 +47,25 @@
     "codemirror": "^5.58.2",
     "codemirror-graphql": "^1.0.3",
     "copy-to-clipboard": "^3.2.0",
     "dset": "^3.1.0",
     "entities": "^2.0.0",
+    "escape-html": "^1.0.3",
     "graphql-language-service": "^3.1.6",
-    "markdown-it": "^10.0.0"
+    "markdown-it": "^12.2.0"
   },
   "peerDependencies": {
     "graphql": ">= v14.5.0 <= 15.5.0",
     "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
     "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
   },
   "devDependencies": {
     "@testing-library/jest-dom": "^5.4.0",
     "@testing-library/react": "9.4.1",
     "@types/codemirror": "^0.0.90",
-    "@types/markdown-it": "^0.0.9",
+    "@types/escape-html": "^1.0.1",
+    "@types/markdown-it": "^12.2.3",
     "@types/node": "^14.14.22",
     "@types/testing-library__jest-dom": "^5.0.1",
     "babel-loader": "^8.1.0",
     "babel-plugin-macros": "^2.8.0",
     "cross-env": "^7.0.2",
diff --git a/packages/graphiql/resources/renderExample.js b/packages/graphiql/resources/renderExample.js
index 1f18f8d0..16172441 100644
--- a/packages/graphiql/resources/renderExample.js
+++ b/packages/graphiql/resources/renderExample.js
@@ -89,20 +89,31 @@ function updateURL() {
       })
       .join('&');
   history.replaceState(null, null, newSearch);
 }
 
-const isDev = window.location.hostname.match(/localhost$/);
-const api = isDev ? '/graphql' : '/.netlify/functions/schema-demo';
+function getSchemaUrl() {
+  const isDev = window.location.hostname.match(/localhost$/);
+
+  if (isDev) {
+    // This supports an e2e test which ensures that invalid schemas do not load.
+    if (parameters.bad && parameters.bad === 'true') {
+      return '/bad/graphql';
+    } else {
+      return '/graphql';
+    }
+  }
+  return '/.netlify/functions/schema-demo';
+}
 
 // Render <GraphiQL /> into the body.
 // See the README in the top level of this module to learn more about
 // how you can customize GraphiQL by providing different values or
 // additional child elements.
 ReactDOM.render(
   React.createElement(GraphiQL, {
-    fetcher: GraphiQL.createFetcher({ url: api }),
+    fetcher: GraphiQL.createFetcher({ url: getSchemaUrl() }),
     query: parameters.query,
     variables: parameters.variables,
     headers: parameters.headers,
     operationName: parameters.operationName,
     onEditQuery: onEditQuery,
diff --git a/packages/graphiql/src/components/DocExplorer.tsx b/packages/graphiql/src/components/DocExplorer.tsx
index 1b2ed337..4b8616a4 100644
--- a/packages/graphiql/src/components/DocExplorer.tsx
+++ b/packages/graphiql/src/components/DocExplorer.tsx
@@ -4,11 +4,11 @@
  *  This source code is licensed under the MIT license found in the
  *  LICENSE file in the root directory of this source tree.
  */
 
 import React from 'react';
-import { GraphQLSchema, isType, GraphQLNamedType } from 'graphql';
+import { GraphQLSchema, isType, GraphQLNamedType, GraphQLError } from 'graphql';
 import { FieldType } from './DocExplorer/types';
 
 import FieldDoc from './DocExplorer/FieldDoc';
 import SchemaDoc from './DocExplorer/SchemaDoc';
 import SearchBox from './DocExplorer/SearchBox';
@@ -27,10 +27,11 @@ const initialNav: NavStackItem = {
   title: 'Documentation Explorer',
 };
 
 type DocExplorerProps = {
   schema?: GraphQLSchema | null;
+  schemaErrors?: readonly GraphQLError[];
 };
 
 type DocExplorerState = {
   navStack: NavStackItem[];
 };
@@ -66,21 +67,26 @@ export class DocExplorer extends React.Component<
     nextProps: DocExplorerProps,
     nextState: DocExplorerState,
   ) {
     return (
       this.props.schema !== nextProps.schema ||
-      this.state.navStack !== nextState.navStack
+      this.state.navStack !== nextState.navStack ||
+      this.props.schemaErrors !== nextProps.schemaErrors
     );
   }
 
   render() {
-    const { schema } = this.props;
+    const { schema, schemaErrors } = this.props;
     const navStack = this.state.navStack;
     const navItem = navStack[navStack.length - 1];
 
     let content;
-    if (schema === undefined) {
+    if (schemaErrors) {
+      content = (
+        <div className="error-container">{'Error fetching schema'}</div>
+      );
+    } else if (schema === undefined) {
       // Schema is undefined when it is being loaded via introspection.
       content = (
         <div className="spinner-container">
           <div className="spinner" />
         </div>
diff --git a/packages/graphiql/src/components/GraphiQL.tsx b/packages/graphiql/src/components/GraphiQL.tsx
index c9027635..bacf352d 100644
--- a/packages/graphiql/src/components/GraphiQL.tsx
+++ b/packages/graphiql/src/components/GraphiQL.tsx
@@ -21,10 +21,13 @@ import {
   OperationDefinitionNode,
   GraphQLType,
   ValidationRule,
   FragmentDefinitionNode,
   DocumentNode,
+  GraphQLError,
+  formatError as formatGraphQLError,
+  GraphQLFormattedError,
 } from 'graphql';
 import copyToClipboard from 'copy-to-clipboard';
 import { getFragmentDependenciesForAST } from 'graphql-language-service-utils';
 
 import { ExecuteButton } from './ExecuteButton';
@@ -64,10 +67,12 @@ import type {
   Unsubscribable,
   FetcherResultPayload,
 } from '@graphiql/toolkit';
 import HistoryStore from '../utility/HistoryStore';
 
+import { validateSchema } from 'graphql';
+
 const DEFAULT_DOC_EXPLORER_WIDTH = 350;
 
 const majorVersion = parseInt(React.version.slice(0, 2), 10);
 
 if (majorVersion < 16) {
@@ -93,10 +98,18 @@ type OnMouseUpFn = Maybe<() => void>;
 
 export type GraphiQLToolbarConfig = {
   additionalContent?: React.ReactNode;
 };
 
+export type GenericError =
+  | Error
+  | string
+  | readonly Error[]
+  | readonly string[]
+  | GraphQLError
+  | readonly GraphQLError[];
+
 export type GraphiQLProps = {
   fetcher: Fetcher;
   schema?: GraphQLSchema;
   validationRules?: ValidationRule[];
   query?: string;
@@ -119,10 +132,14 @@ export type GraphiQLProps = {
   onToggleDocs?: (docExplorerOpen: boolean) => void;
   getDefaultFieldNames?: GetDefaultFieldNamesFn;
   editorTheme?: string;
   onToggleHistory?: (historyPaneOpen: boolean) => void;
   ResultsTooltip?: typeof Component | FunctionComponent;
+  /**
+   * decide whether schema responses should be validated. false by default
+   */
+  dangerouslyAssumeSchemaIsValid?: boolean;
   readOnly?: boolean;
   docExplorerOpen?: boolean;
   toolbar?: GraphiQLToolbarConfig;
   maxHistoryLength?: number;
 };
@@ -141,19 +158,43 @@ export type GraphiQLState = {
   variableEditorActive: boolean;
   headerEditorActive: boolean;
   headerEditorEnabled: boolean;
   shouldPersistHeaders: boolean;
   historyPaneOpen: boolean;
+  schemaErrors?: readonly GraphQLError[];
   docExplorerWidth: number;
   isWaitingForResponse: boolean;
   subscription?: Unsubscribable | null;
   variableToType?: VariableToType;
   operations?: OperationDefinitionNode[];
   documentAST?: DocumentNode;
   maxHistoryLength: number;
 };
 
+const stringify = (obj: unknown): string => JSON.stringify(obj, null, 2);
+
+const formatSingleError = (error: Error): Error => ({
+  ...error,
+  // Raise these details even if they're non-enumerable
+  message: error.message,
+  stack: error.stack,
+});
+
+type InputError = Error | GraphQLError | string;
+
+const handleSingleError = (
+  error: InputError,
+): GraphQLFormattedError | Error | string => {
+  if (error instanceof GraphQLError) {
+    return formatGraphQLError(error);
+  }
+  if (error instanceof Error) {
+    return formatSingleError(error);
+  }
+  return error;
+};
+
 /**
  * The top-level React component for GraphiQL, intended to encompass the entire
  * browser viewport.
  *
  * @see https://github.com/graphql/graphiql#usage
@@ -164,16 +205,19 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
    */
   static formatResult(result: any) {
     return JSON.stringify(result, null, 2);
   }
 
-  static formatError(rawError: Error) {
-    const result = Array.isArray(rawError)
-      ? rawError.map(formatSingleError)
-      : formatSingleError(rawError);
-    return JSON.stringify(result, null, 2);
-  }
+  static formatError = (error: GenericError): string => {
+    if (Array.isArray(error)) {
+      return stringify({
+        errors: error.map((e: InputError) => handleSingleError(e)),
+      });
+    }
+    // @ts-ignore
+    return stringify({ errors: handleSingleError(error) });
+  };
 
   // Ensure only the last executed editor query is rendered.
   _editorQueryID = 0;
   _storage: StorageAPI;
 
@@ -264,19 +308,34 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
     }
 
     const headerEditorEnabled = props.headerEditorEnabled ?? false;
     const shouldPersistHeaders = props.shouldPersistHeaders ?? false;
 
+    let schema = props.schema;
+    let response = props.response;
+    let schemaErrors: readonly GraphQLError[] | undefined = undefined;
+    if (schema && !this.props.dangerouslyAssumeSchemaIsValid) {
+      const validationErrors = validateSchema(schema);
+      if (validationErrors && validationErrors.length > 0) {
+        // This is equivalent to handleSchemaErrors, but it's too early
+        // to call setState.
+        response = GraphiQL.formatError(validationErrors);
+        schema = undefined;
+        schemaErrors = validationErrors;
+      }
+    }
+
     // Initialize state
     this.state = {
-      schema: props.schema,
+      schema,
       query,
       variables: variables as string,
       headers: headers as string,
       operationName,
       docExplorerOpen,
-      response: props.response,
+      schemaErrors,
+      response,
       editorFlex: Number(this._storage.get('editorFlex')) || 1,
       secondaryEditorOpen,
       secondaryEditorHeight:
         Number(this._storage.get('secondaryEditorHeight')) || 200,
       variableEditorActive:
@@ -355,10 +414,18 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
       nextSchema &&
       (nextSchema !== this.state.schema ||
         nextQuery !== this.state.query ||
         nextOperationName !== this.state.operationName)
     ) {
+      if (!this.props.dangerouslyAssumeSchemaIsValid) {
+        const validationErrors = validateSchema(nextSchema);
+        if (validationErrors && validationErrors.length > 0) {
+          this.handleSchemaErrors(validationErrors);
+          nextSchema = undefined;
+        }
+      }
+
       const updatedQueryAttributes = this._updateQueryFacts(
         nextQuery,
         nextOperationName,
         this.state.operations,
         nextSchema,
@@ -663,10 +730,11 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
             />
             <DocExplorer
               ref={c => {
                 this.docExplorerComponent = c;
               }}
+              schemaErrors={this.state.schemaErrors}
               schema={this.state.schema}>
               <button
                 className="docExplorerHide"
                 onClick={this.handleToggleDocs}
                 aria-label="Close Documentation Explorer">
@@ -869,31 +937,51 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
         if (this.state.schema !== undefined) {
           return;
         }
 
         if (typeof result !== 'string' && 'data' in result) {
-          const schema = buildClientSchema(result.data);
-          const queryFacts = getOperationFacts(schema, this.state.query);
-          this.safeSetState({ schema, ...queryFacts });
+          let schema: GraphQLSchema | undefined = buildClientSchema(
+            result.data,
+          );
+          if (!this.props.dangerouslyAssumeSchemaIsValid) {
+            const errors = validateSchema(schema);
+            // if there are errors, don't set schema
+            if (errors && errors.length > 0) {
+              schema = undefined;
+              this.handleSchemaErrors(errors);
+            }
+          }
+          if (schema) {
+            const queryFacts = getOperationFacts(schema, this.state.query);
+            this.safeSetState({
+              schema,
+              ...queryFacts,
+              schemaErrors: undefined,
+            });
+          }
         } else {
+          // handle as if it were an error if the fetcher response is not a string or response.data is not present
           const responseString =
             typeof result === 'string' ? result : GraphiQL.formatResult(result);
-          this.safeSetState({
-            // Set schema to `null` to explicitly indicate that no schema exists.
-            schema: undefined,
-            response: responseString,
-          });
+          this.handleSchemaErrors([responseString]);
         }
       })
       .catch(error => {
-        this.safeSetState({
-          schema: undefined,
-          response: error ? GraphiQL.formatError(error) : undefined,
-        });
+        this.handleSchemaErrors([error]);
       });
   }
 
+  private handleSchemaErrors(
+    schemaErrors: readonly GraphQLError[] | readonly string[],
+  ) {
+    this.safeSetState({
+      response: schemaErrors ? GraphiQL.formatError(schemaErrors) : undefined,
+      schema: undefined,
+      schemaErrors,
+    });
+  }
+
   private async _fetchQuery(
     query: string,
     variables: string,
     headers: string,
     operationName: string,
@@ -906,22 +994,24 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
 
     try {
       jsonVariables =
         variables && variables.trim() !== '' ? JSON.parse(variables) : null;
     } catch (error) {
-      throw new Error(`Variables are invalid JSON: ${error.message}.`);
+      throw new Error(
+        `Variables are invalid JSON: ${(error as Error).message}.`,
+      );
     }
 
     if (typeof jsonVariables !== 'object') {
       throw new Error('Variables are not a JSON object.');
     }
 
     try {
       jsonHeaders =
         headers && headers.trim() !== '' ? JSON.parse(headers) : null;
     } catch (error) {
-      throw new Error(`Headers are invalid JSON: ${error.message}.`);
+      throw new Error(`Headers are invalid JSON: ${(error as Error).message}.`);
     }
 
     if (typeof jsonHeaders !== 'object') {
       throw new Error('Headers are not a JSON object.');
     }
@@ -1006,11 +1096,13 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
                 subscription: null,
               });
             } catch (error) {
               this.safeSetState({
                 isWaitingForResponse: false,
-                response: error ? GraphiQL.formatError(error) : undefined,
+                response: error
+                  ? GraphiQL.formatError(error as Error)
+                  : undefined,
                 subscription: null,
               });
             }
           })();
 
@@ -1165,11 +1257,11 @@ export class GraphiQL extends React.Component<GraphiQLProps, GraphiQLState> {
 
       this.setState({ subscription });
     } catch (error) {
       this.setState({
         isWaitingForResponse: false,
-        response: error.message,
+        response: (error as Error).message,
       });
     }
   };
 
   handleStopQuery = () => {
@@ -1697,17 +1789,10 @@ GraphiQLToolbar.displayName = 'GraphiQLToolbar';
 function GraphiQLFooter<TProps>(props: PropsWithChildren<TProps>) {
   return <div className="footer">{props.children}</div>;
 }
 GraphiQLFooter.displayName = 'GraphiQLFooter';
 
-const formatSingleError = (error: Error) => ({
-  ...error,
-  // Raise these details even if they're non-enumerable
-  message: error.message,
-  stack: error.stack,
-});
-
 const defaultQuery = `# Welcome to GraphiQL
 #
 # GraphiQL is an in-browser tool for writing, validating, and
 # testing GraphQL queries.
 #
diff --git a/packages/graphiql/src/utility/onHasCompletion.ts b/packages/graphiql/src/utility/onHasCompletion.ts
index 5e15cee2..e85654f3 100644
--- a/packages/graphiql/src/utility/onHasCompletion.ts
+++ b/packages/graphiql/src/utility/onHasCompletion.ts
@@ -10,10 +10,11 @@ import {
   GraphQLNonNull,
   GraphQLList,
   GraphQLType,
   GraphQLField,
 } from 'graphql';
+import escapeHTML from 'escape-html';
 import MD from 'markdown-it';
 
 const md = new MD();
 
 /**
@@ -106,7 +107,7 @@ function renderType(type: GraphQLType): string {
     return `${renderType(type.ofType)}!`;
   }
   if (type instanceof GraphQLList) {
     return `[${renderType(type.ofType)}]`;
   }
-  return `<a class="typeName">${type.name}</a>`;
+  return `<a class="typeName">${escapeHTML(type.name)}</a>`;
 }
diff --git a/packages/graphiql/test/bad-schema.js b/packages/graphiql/test/bad-schema.js
new file mode 100644
index 00000000..6f41ab31
--- /dev/null
+++ b/packages/graphiql/test/bad-schema.js
@@ -0,0 +1,99 @@
+const { buildClientSchema } = require('graphql');
+
+module.exports.schema = {
+  __schema: {
+    queryType: {
+      name: 'Query',
+    },
+    mutationType: null,
+    subscriptionType: null,
+    types: [
+      {
+        kind: 'OBJECT',
+        name: 'Query',
+        description: null,
+        fields: [
+          {
+            name: 'user',
+            description: null,
+            args: [
+              {
+                name: 'id',
+                description: null,
+                type: {
+                  kind: 'NON_NULL',
+                  name: null,
+                  ofType: {
+                    kind: 'SCALAR',
+                    name: 'ID',
+                    ofType: null,
+                  },
+                },
+                defaultValue: null,
+              },
+            ],
+            type: {
+              kind: 'OBJECT',
+              name: '<img src=x onerror=alert(document.domain)>',
+              ofType: null,
+            },
+            isDeprecated: false,
+            deprecationReason: null,
+          },
+        ],
+        inputFields: null,
+        interfaces: [],
+        enumValues: null,
+        possibleTypes: null,
+      },
+      {
+        kind: 'SCALAR',
+        name: 'ID',
+        description: '',
+        fields: null,
+        inputFields: null,
+        interfaces: null,
+        enumValues: null,
+        possibleTypes: null,
+      },
+      {
+        kind: 'OBJECT',
+        name: '<img src=x onerror=alert(document.domain)>',
+        description: null,
+        fields: [
+          {
+            name: 'name',
+            description: null,
+            args: [],
+            type: {
+              kind: 'NON_NULL',
+              name: null,
+              ofType: {
+                kind: 'SCALAR',
+                name: 'String',
+                ofType: null,
+              },
+            },
+            isDeprecated: false,
+            deprecationReason: null,
+          },
+        ],
+        inputFields: null,
+        interfaces: [],
+        enumValues: null,
+        possibleTypes: null,
+      },
+      {
+        kind: 'SCALAR',
+        name: 'String',
+        description: '',
+        fields: null,
+        inputFields: null,
+        interfaces: null,
+        enumValues: null,
+        possibleTypes: null,
+      },
+    ],
+    directives: [],
+  },
+};
diff --git a/packages/graphiql/test/beforeDevServer.js b/packages/graphiql/test/beforeDevServer.js
index 97fd298b..0b4e0bd2 100644
--- a/packages/graphiql/test/beforeDevServer.js
+++ b/packages/graphiql/test/beforeDevServer.js
@@ -7,15 +7,21 @@
 
 const express = require('express');
 const path = require('path');
 const { graphqlHTTP } = require('express-graphql');
 const schema = require('./schema');
+const { schema: badSchema } = require('./bad-schema');
 
 module.exports = function beforeDevServer(app, _server, _compiler) {
   // GraphQL Server
   app.post('/graphql', graphqlHTTP({ schema }));
 
+  app.post('/bad/graphql', (_req, res, next) => {
+    res.json({ data: badSchema });
+    next();
+  });
+
   app.get(
     '/graphql',
     graphqlHTTP({
       schema,
     }),
diff --git a/packages/graphiql/test/e2e-server.js b/packages/graphiql/test/e2e-server.js
index 878d3c05..25231c22 100644
--- a/packages/graphiql/test/e2e-server.js
+++ b/packages/graphiql/test/e2e-server.js
@@ -8,12 +8,12 @@
 /* eslint-disable no-console */
 const express = require('express');
 const path = require('path');
 const { graphqlHTTP } = require('express-graphql');
 const schema = require('./schema');
-
 const app = express();
+const { schema: badSchema } = require('./bad-schema');
 
 // Server
 app.post('/graphql', graphqlHTTP({ schema }));
 
 app.get(
@@ -21,10 +21,15 @@ app.get(
   graphqlHTTP({
     schema,
   }),
 );
 
+app.post('/bad/graphql', (_req, res, next) => {
+  res.json({ data: badSchema });
+  next();
+});
+
 app.use(express.static(path.resolve(__dirname, '../')));
 
 app.listen(process.env.PORT || 0, function () {
   const port = this.address().port;
 
diff --git a/yarn.lock b/yarn.lock
index 31209bb3..5aeb1c6e 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3286,11 +3286,11 @@
   version "0.2.5"
   resolved "https://registry.yarnpkg.com/@emotion/weak-memoize/-/weak-memoize-0.2.5.tgz#8eed982e2ee6f7f4e44c253e12962980791efd46"
   integrity sha512-6U71C2Wp7r5XtFtQzYrW5iKFT67OixrSxjI4MptCHzdSVlgabczzqLe0ZSgnub/5Kp4hSbpDB1tMytZY9pwxxA==
 
 "@graphiql/toolkit@file:packages/graphiql-toolkit":
-  version "0.3.0"
+  version "0.3.2"
   dependencies:
     "@n1ru4l/push-pull-async-iterable-iterator" "^3.0.0"
     graphql-ws "^4.9.0"
     meros "^1.1.4"
 
@@ -4879,10 +4879,15 @@
   resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.34.tgz#170a40223a6d666006d93ca128af2beb1d9b1901"
   integrity sha512-ePPA/JuI+X0vb+gSWlPKOY0NdNAie/rPUqX2GUPpbZwiKTkSPhjXWuee47E4MtE54QVzGCQMQkAL6JhV2E1+cQ==
   dependencies:
     "@types/node" "*"
 
+"@types/escape-html@^1.0.1":
+  version "1.0.1"
+  resolved "https://registry.yarnpkg.com/@types/escape-html/-/escape-html-1.0.1.tgz#b19b4646915f0ae2c306bf984dc0a59c5cfc97ba"
+  integrity sha512-4mI1FuUUZiuT95fSVqvZxp/ssQK9zsa86S43h9x3zPOSU9BBJ+BfDkXwuaU7BfsD+e7U0/cUUfJFk3iW2M4okA==
+
 "@types/eslint-visitor-keys@^1.0.0":
   version "1.0.0"
   resolved "https://registry.yarnpkg.com/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#1ee30d79544ca84d68d4b3cdb0af4f205663dd2d"
   integrity sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==
 
@@ -5019,10 +5024,23 @@
   resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-0.0.9.tgz#a5d552f95216c478e0a27a5acc1b28dcffd989ce"
   integrity sha512-IFSepyZXbF4dgSvsk8EsgaQ/8Msv1I5eTL0BZ0X3iGO9jw6tCVtPG8HchIPm3wrkmGdqZOD42kE0zplVi1gYDA==
   dependencies:
     "@types/linkify-it" "*"
 
+"@types/markdown-it@^12.2.3":
+  version "12.2.3"
+  resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-12.2.3.tgz#0d6f6e5e413f8daaa26522904597be3d6cd93b51"
+  integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ==
+  dependencies:
+    "@types/linkify-it" "*"
+    "@types/mdurl" "*"
+
+"@types/mdurl@*":
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-1.0.2.tgz#e2ce9d83a613bacf284c7be7d491945e39e1f8e9"
+  integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA==
+
 "@types/mime@^1":
   version "1.3.2"
   resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a"
   integrity sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==
 
@@ -6119,10 +6137,15 @@ argparse@^1.0.7:
   resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
   integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==
   dependencies:
     sprintf-js "~1.0.2"
 
+argparse@^2.0.1:
+  version "2.0.1"
+  resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
+  integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==
+
 aria-query@^3.0.0:
   version "3.0.0"
   resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-3.0.0.tgz#65b3fcc1ca1155a8c9ae64d6eee297f15d5133cc"
   integrity sha1-ZbP8wcoRVajJrmTW7uKX8V1RM8w=
   dependencies:
@@ -9584,10 +9607,15 @@ entities@^2.0.0:
 entities@~2.0.0:
   version "2.0.3"
   resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.3.tgz#5c487e5742ab93c15abb5da22759b8590ec03b7f"
   integrity sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ==
 
+entities@~2.1.0:
+  version "2.1.0"
+  resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5"
+  integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==
+
 envinfo@^7.3.1:
   version "7.8.1"
   resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475"
   integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==
 
@@ -9749,11 +9777,11 @@ escalade@^3.0.2:
 escalade@^3.1.1:
   version "3.1.1"
   resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40"
   integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==
 
-escape-html@~1.0.3:
+escape-html@^1.0.3, escape-html@~1.0.3:
   version "1.0.3"
   resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988"
   integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=
 
 escape-string-regexp@1.0.5, escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5:
@@ -11510,20 +11538,21 @@ grapheme-splitter@^1.0.4:
   version "1.0.4"
   resolved "https://registry.yarnpkg.com/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz#9cf3a665c6247479896834af35cf1dbb4400767e"
   integrity sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==
 
 "graphiql@file:packages/graphiql":
-  version "1.4.3"
+  version "1.4.6"
   dependencies:
-    "@graphiql/toolkit" "^0.3.0"
+    "@graphiql/toolkit" "^0.3.2"
     codemirror "^5.58.2"
-    codemirror-graphql "^1.0.0"
+    codemirror-graphql "^1.0.3"
     copy-to-clipboard "^3.2.0"
     dset "^3.1.0"
     entities "^2.0.0"
-    graphql-language-service "^3.1.5"
-    markdown-it "^10.0.0"
+    escape-html "^1.0.3"
+    graphql-language-service "^3.1.6"
+    markdown-it "^12.2.0"
 
 graphql-config@^3.0.2:
   version "3.0.3"
   resolved "https://registry.yarnpkg.com/graphql-config/-/graphql-config-3.0.3.tgz#58907c65ed7d6e04132321450b60e57863ea9a5f"
   integrity sha512-MBY0wEjvcgJtZUyoqpPvOE1e5qPI0hJaa1gKTqjonSFiCsNHX2lykNjpOPcodmAgH1V06ELxhGnm9kcVzqvi/g==
@@ -14278,10 +14307,17 @@ linkify-it@^2.0.0:
   resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.2.0.tgz#e3b54697e78bf915c70a38acd78fd09e0058b1cf"
   integrity sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==
   dependencies:
     uc.micro "^1.0.1"
 
+linkify-it@^3.0.1:
+  version "3.0.3"
+  resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.3.tgz#a98baf44ce45a550efb4d49c769d07524cc2fa2e"
+  integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==
+  dependencies:
+    uc.micro "^1.0.1"
+
 lint-staged@^10.1.2:
   version "10.1.3"
   resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-10.1.3.tgz#da27713d3ac519da305381b4de87d5f866b1d2f1"
   integrity sha512-o2OkLxgVns5RwSC5QF7waeAjJA5nz5gnUfqL311LkZcFipKV7TztrSlhNUK5nQX9H0E5NELAdduMQ+M/JPT7RQ==
   dependencies:
@@ -14709,10 +14745,21 @@ markdown-it@^10.0.0:
     entities "~2.0.0"
     linkify-it "^2.0.0"
     mdurl "^1.0.1"
     uc.micro "^1.0.5"
 
+markdown-it@^12.2.0:
+  version "12.2.0"
+  resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.2.0.tgz#091f720fd5db206f80de7a8d1f1a7035fd0d38db"
+  integrity sha512-Wjws+uCrVQRqOoJvze4HCqkKl1AsSh95iFAeQDwnyfxM09divCBSXlDR1uTvyUP3Grzpn4Ru8GeCxYPM8vkCQg==
+  dependencies:
+    argparse "^2.0.1"
+    entities "~2.1.0"
+    linkify-it "^3.0.1"
+    mdurl "^1.0.1"
+    uc.micro "^1.0.5"
+
 markdown-to-jsx@^6.11.4:
   version "6.11.4"
   resolved "https://registry.yarnpkg.com/markdown-to-jsx/-/markdown-to-jsx-6.11.4.tgz#b4528b1ab668aef7fe61c1535c27e837819392c5"
   integrity sha512-3lRCD5Sh+tfA52iGgfs/XZiw33f7fFX9Bn55aNnVNUd2GzLDkOWyKYYD8Yju2B1Vn+feiEdgJs8T6Tg0xNokPw==
   dependencies:

Vulnerable code: > **Breaking Changes & Improvements:** several interfaces are being dropped for new ones for GraphiQL 2.0.0! Read more in [this issue](https://github.com/graphql/graphiql/issues/1165)
> **[`graphiql@1.0.0`](https://github.com/graphql/graphiql/milestone/3)** is coming soon & will provide a stable release with react 16, graphql 15 support, fixes, and a headers tab
| Prop                         | Type                                                                                                  | Description                                                                                                                                                                                     |
| ---------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetcher`                    | [`Fetcher function`](https://graphiql-test.netlify.app/typedoc/modules/graphiql-toolkit.html#fetcher) | **Required.** a function which accepts GraphQL-HTTP parameters and returns a Promise, Observable or AsyncIterable which resolves to the GraphQL parsed JSON response.                           |  |
| `schema`                     | [`GraphQLSchema`](https://graphql.org/graphql-js/type/#graphqlschema)                                 | a GraphQLSchema instance or `null` if one is not to be used. If `undefined` is provided, GraphiQL will send an introspection query using the fetcher to produce a schema.                       |
| `query`                      | `string` (GraphQL)                                                                                    | initial displayed query, if `undefined` is provided, the stored query or `defaultQuery` will be used. You can also set this value at runtime to override the current operation editor state.    |
| `validationRules`            | `ValidationRule[]`                                                                                    | A array of validation rules that will be used for validating the GraphQL operations. If `undefined` is provided, the default rules (exported as `specifiedRules` from `graphql`) will be used.  |
| `variables`                  | `string` (JSON)                                                                                       | initial displayed query variables, if `undefined` is provided, the stored variables will be used.                                                                                               |
| `headers`                    | `string`                                                                                              | initial displayed request headers. if not defined, it will default to the stored headers if `shouldPersistHeaders` is enabled.                                                                  |
| `externalFragments`          | `string \| FragmentDefinitionNode[]`                                                                  | provide fragments external to the operation for completion, validation, and for selective use when executing operations.                                                                        |
| `operationName`              | `string`                                                                                              | an optional name of which GraphQL operation should be executed.                                                                                                                                 |
| `response`                   | `string` (JSON)                                                                                       | an optional JSON string to use as the initial displayed response. If not provided, no response will be initially shown. You might provide this if illustrating the result of the initial query. |
| `storage`                    | [`Storage`](https://graphiql-test.netlify.app/typedoc/interfaces/graphiql.storage.html)               | **Default:** `window.localStorage`. an interface that matches `window.localStorage` signature that GraphiQL will use to persist state.                                                          |
| `defaultQuery`               | `string`                                                                                              | **Default:** graphiql help text. Provides default query if no user state is present.                                                                                                            | default graphiql help text |
| `defaultVariableEditorOpen`  | `boolean`                                                                                             | sets whether or not to show the variables pane on startup. overridden by user state (**deprecated** in favor of `defaultSecondaryEditorOpen`)                                                   |
| `defaultSecondaryEditorOpen` | `boolean`                                                                                             | sets whether or not to show the variables/headers pane on startup. If not defined, it will be based off whether or not variables and/or headers are present.                                    |
| `getDefaultFieldNames`       | `Function`                                                                                            | **Default:** `defaultGetDefaultFieldNames`. provides default field values for incomplete queries                                                                                                | `defaultGetDefaultFieldNames` |
| `editorTheme`                | `string`                                                                                              | **Default:** `graphiql`. names a CodeMirror theme to be applied to the `QueryEditor`, `ResultViewer`, and `Variables` panes. See below for full usage.                                          |
| `readOnly`                   | `boolean`                                                                                             | when `true` will make the `QueryEditor` and `Variables` panes readOnly.                                                                                                                         |
| `docExplorerOpen`            | `boolean`                                                                                             | when `true` will ensure the `DocExplorer` is open by default when the user first renders the component. Overridden by user's toggle state                                                       |
| `headerEditorEnabled`        | `boolean`                                                                                             | **Default:** `false`. enables the header editor when `true`.                                                                                                                                    |
| `shouldPersistHeaders`       | `boolean`                                                                                             | **Default:** `false`. o persist headers to storage when `true`                                                                                                                                  |
| `toolbar.additionalContent`  | `React.Component[]`                                                                                   | pass additional toolbar react components inside a fragment                                                                                                                                      | `null` |
| `onEditQuery`                | `Function`                                                                                            | called when the Query editor changes. The argument to the function will be the query string.                                                                                                    |
| `onEditVariables`            | `Function`                                                                                            | called when the Query variable editor changes. The argument to the function will be the variables string.                                                                                       |
| `onEditHeaders`              | `Function`                                                                                            | called when the request headers editor changes. The argument to the function will be the headers string.                                                                                        |
| `onEditOperationName`        | `Function`                                                                                            | called when the operation name to be executed changes.                                                                                                                                          |
| `onToggleDocs`               | `Function`                                                                                            | called when the docs will be toggled. The argument to the function will be a boolean whether the docs are now open or closed.                                                                   |
| `maxHistoryLength`           | `number`                                                                                              | **Default:** 20. allows you to increase the number of queries in the history component                                                                                                          | 20 |
    | { error: any[] };
    "markdown-it": "^10.0.0"
    "@types/markdown-it": "^0.0.9",
const isDev = window.location.hostname.match(/localhost$/);
const api = isDev ? '/graphql' : '/.netlify/functions/schema-demo';
    fetcher: GraphiQL.createFetcher({ url: api }),
import { GraphQLSchema, isType, GraphQLNamedType } from 'graphql';
      this.state.navStack !== nextState.navStack
    const { schema } = this.props;
    if (schema === undefined) {
  static formatError(rawError: Error) {
    const result = Array.isArray(rawError)
      ? rawError.map(formatSingleError)
      : formatSingleError(rawError);
    return JSON.stringify(result, null, 2);
  }
      schema: props.schema,
      response: props.response,
          const schema = buildClientSchema(result.data);
          const queryFacts = getOperationFacts(schema, this.state.query);
          this.safeSetState({ schema, ...queryFacts });
          this.safeSetState({
            // Set schema to `null` to explicitly indicate that no schema exists.
            schema: undefined,
            response: responseString,
          });
        this.safeSetState({
          schema: undefined,
          response: error ? GraphiQL.formatError(error) : undefined,
        });
      throw new Error(`Variables are invalid JSON: ${error.message}.`);
      throw new Error(`Headers are invalid JSON: ${error.message}.`);
                response: error ? GraphiQL.formatError(error) : undefined,
        response: error.message,
const formatSingleError = (error: Error) => ({
  ...error,
  // Raise these details even if they're non-enumerable
  message: error.message,
  stack: error.stack,
});

  return `<a class="typeName">${type.name}</a>`;

  version "0.3.0"
escape-html@~1.0.3:
  version "1.4.3"
    "@graphiql/toolkit" "^0.3.0"
    codemirror-graphql "^1.0.0"
    graphql-language-service "^3.1.5"
    markdown-it "^10.0.0"
Fixed code: > **Security Notice:** All versions of `graphiql` < `1.4.3` are vulnerable to an XSS attack in cases where the GraphQL server to which the GraphiQL web app connects is not trusted. Learn more [in the graphiql SECURITY.md](./packages/graphiql/SECURITY.md)

# GraphiQL Ecosystem Security Advisories

Security Advisories for packages in this repository will be listed here

## GraphiQL

### 2021

- [Introspection Schema XSS Attack](./docs/security/2021-introspection-schema-xss.md)
- [1. GraphiQL introspection schema template injection attack: Advisory Statement](#1-graphiql-introspection-schema-template-injection-attack-advisory-statement)
  - [1.1. Impact](#11-impact)
  - [1.2. Scope](#12-scope)
  - [1.3. Patches](#13-patches)
  - [1.3.1 CDN bundle implementations may be automatically patched](#131-cdn-bundle-implementations-may-be-automatically-patched)
  - [1.4. Workarounds for Older Versions](#14-workarounds-for-older-versions)
  - [1.5. How to Re-create the Exploit](#15-how-to-re-create-the-exploit)
  - [1.6. Credit](#16-credit)
  - [1.7. References](#17-references)
  - [1.8. For more information](#18-for-more-information)
- [2. More Details on the Vulnerability](#2-more-details-on-the-vulnerability)
- [3. Compromised introspection Schema Example](#3-compromised-introspection-schema-example)

## 1. GraphiQL introspection schema template injection attack: Advisory Statement

This is a security advisory for an XSS vulnerability in `graphiql`.

A similar vulnerability affects `graphql-playground`, a fork of `graphiql`. There is a corresponding `graphql-playground` [advisory](https://github.com/graphql/graphql-playground/security/advisories/GHSA-59r9-6jp6-jcm7) and [Apollo Server advisory](https://github.com/apollographql/apollo-server/security/advisories/GHSA-qm7x-rc44-rrqw).

### 1.1. Impact

All versions of `graphiql` older than [`graphiql@1.4.3`](https://github.com/graphql/graphiql/releases/tag/v1.4.3) are vulnerable to compromised HTTP schema introspection responses or `schema` prop values with malicious GraphQL type names, exposing a dynamic XSS attack surface that can allow code injection on operation autocomplete.

In order for the attack to take place, the user must load a vulnerable schema in `graphiql`. There are a number of ways that can occur.

By default, the schema URL is _not_ attacker-controllable in `graphiql` or in its suggested implementations or examples, leaving only very complex attack vectors.

If a custom implementation of `graphiql`'s `fetcher` allows the schema URL to be set dynamically, such as a URL query parameter like `?endpoint=` in `graphql-playground`, or a database provided value, then this custom `graphiql` implementation is _vulnerable to phishing attacks_, and thus much more readily available, low or no privelege level xss attacks. The URLs could look like any generic looking graphql schema URL.

Because this exposes an XSS attack surface, it would be possible for a threat actor to exfiltrate user credentials, data, etc. using arbitrary malicious scripts, without it being known to the user.

### 1.2. Scope

This advisory describes the impact on the `graphiql` package. The vulnerability also affects other projects forked from `graphiql` such as [`graphql-playground`](https://github.com/graphql/graphql-playground/security/advisories/GHSA-59r9-6jp6-jcm7) and the `graphql-playground` fork distributed by Apollo Server. The impact is more severe in the `graphql-playground` implementations; see the [`graphql-playground` advisory](https://github.com/graphql/graphql-playground/security/advisories/GHSA-59r9-6jp6-jcm7) and [Apollo Server advisory](https://github.com/apollographql/apollo-server/security/advisories/GHSA-qm7x-rc44-rrqw) for details.

This vulnerability does not impact `codemirror-graphql`, `monaco-graphql` or other dependents, as it exists in `onHasCompletion.ts` in `graphiql`. It does impact all forks of `graphiql`, and every released version of `graphiql`.

It should be noted that desktop clients such as Altair, Insomnia, Postwoman, do not appear to be impacted by this.

### 1.3. Patches

`graphiql@1.4.3` addresses this issue via defense in depth.

- **HTML-escaping text** that should be treated as text rather than HTML. In most of the app, this happens automatically because React escapes all interpolated text by default. However, one vulnerable component uses the unsafe `innerHTML` API and interpolated type names directly into HTML. We now properly escape that type name, which fixes the known vulnerability.

- **Validates the schema** upon receiving the introspection response or schema changes. Schemas with names that violate the GraphQL spec will no longer be loaded. (This includes preventing the Doc Explorer from loading.) This change is also sufficient to fix the known vulnerability. You can disable this validation by setting `dangerouslyAssumeSchemaIsValid={true}`, which means you are relying only on escaping values to protect you from this attack.

- **Ensuring that user-generated HTML is safe**. Schemas can contain Markdown in `description` and `deprecationReason` fields, and the web app renders them to HTML using the `markdown-it` library. As part of the development of `graphiql@1.4.3`, we verified that our use of `markdown-it` prevents the inclusion of arbitrary HTML. We use `markdown-it` without setting `html: true`, so we are comfortable relying on [`markdown-it`'s HTML escaping](https://github.com/markdown-it/markdown-it/blob/master/docs/security.md) here. We considered running a second level of sanitization over all rendered Markdown using a library such as `dompurify` but believe that is unnecessary as `markdown-it`'s sanitization appears to be adequate. `graphiql@1.4.3` does update to the latest version of `markdown-it` (v12, from v10) so that any security fixes in v11 and v12 will take effect.

### 1.3.1 CDN bundle implementations may be automatically patched

Note that if your implementation is depending on a CDN version of `graphiql`, and is pointed to the `latest` tag (usually the default for most cdns if no version is specified) then this issue is already mitigated, in case you were vulnerable to it before.

### 1.4. Workarounds for Older Versions

If you cannot use `graphiql@1.4.3` or later

- Always use a static URL to a trusted server that is serving a trusted GraphQL schema.

- If you have a custom implementation that allows using user-provided schema URLs via a query parameter, database value, etc, you must either disable this customization, or only allow trusted URLs.

### 1.5. How to Re-create the Exploit

You can see an example on [codesandbox](https://codesandbox.io/s/graphiql-xss-exploit-gr22f?file=/src/App.js). These are both fixed to the last `graphiql` release `1.4.2` which is the last vulnerable release; however it would work with any previous release of `graphiql`.

Both of these examples are meant to demonstrate the phishing attack surface, so they are customized to accept a `url` parameter. To demonstrate the phishing attack, add `?url=https://graphql-xss-schema.netlify.app/graphql` to the in-codesandbox browser.

Erase the contents of the given query and type `{u`. You will see an alert window open, showing that attacker-controlled code was executed.

Note that when React is in development mode, a validation exception is thrown visibly; however that exception is usually buried in the browser console in a production build of `graphiql`. This validation exception comes from `getDiagnostics`, which invokes `graphql` `validate()` which in turn will `assertValidSchema()`, as `apollo-server-core` does on executing each operation. This validation does not prevent the exploit from being successful.

Note that something like the `url` parameter is not required for the attack to happen if `graphiql`'s `fetcher` is configured in a different way to communicate with a compromised GraphQL server.

### 1.6. Credit

This vulnerability was discovered by [@Ry0taK](https://github.com/Ry0taK), thank you! :1st_place_medal:

Others who contributed:

- [@imolorhe](https://github.com/imolorhe)
- [@glasser](https://github.com/glasser)
- [@divyenduz](https://github.com/divyenduz)
- [@dotansimha](https://github.com/dotansimha)
- [@acao](https://github.com/acao)
- [@benjie](https://github.com/benjie) and many others who provided morale support

### 1.7. References

**The vulnerability has always been present**

[In the first commit](https://github.com/graphql/graphiql/commit/b9dec272d89d9c590727fd10d62e4a47e0317fc7#diff-855b77f6310b7e4fb1bcac779cd945092ed49fd759f4684ea391b45101166437R87)

[And later moved to onHasCompletion.js in 2016](https://github.com/graphql/graphiql/commit/6701b0b626e43800e32413590a295e5c1e3d5419#diff-d45eb76aebcffd27d3a123214487116fa95e0b5a11d70a94a0ce3033ce09f879R110) (now `.ts` after the typescript migration)

### 1.8. For more information

If you have any questions or comments about this advisory:

- Open an issue in [graphiql repo](https://github.com/graphql/graphiql/new/issues)

## 2. More Details on the Vulnerability

This section provides more details in addition to the advisory.

An installation of the GraphiQL web app is vulnerable if two conditions are met:

- The web app trusts information from its corresponding GraphQL server by interpolating information such as GraphQL type names directly into HTML instead of appropriately escaping or sanitizing the information.
- The victim can load the web app in a way where it speaks to a GraphQL server controlled by the attacker.

All versions of `graphiql` prior to 1.4.3 inappropriately trust type names provided by the GraphQL server. They additionally rely on XSS filtering in the `markdown-it` package to try to protect themselves from XSS attacks in GraphQL descriptions and deprecation reasons.

By default, `graphiql` does _not_ allow the attacker to control what GraphQL server it speaks to. Therefore, many installations of `graphiql` are not affected by this advisory. Installations are only affected if the `fetcher` argument provided to GraphiQL allows arbitrary customization of the GraphQL endpoint (eg, reading a GraphQL URL from an URL parameter), or if the attacker has another way of affecting the introspection schema returned by the GraphQL server. (Note that `graphql-playground`, a project which started as a fork of `graphiql`, does this sort of URL parsing by default, so `graphql-playground` installations _are_ affected by a corresponding vulnerability in their default configuration.)

One example of "another way of affecting the introspection schema" would be if you served `graphiql` as part of a PAAS platform that allows users to define their own GraphQL schemas. In this case, even though the `graphiql` installation might be hard-wired to a single GraphQL endpoint, the attacker has control over that GraphQL endpoint and could use it to inject scripts into `graphiql`. In this case, your `graphiql` installation could be vulnerable if it responds to introspection requests without first validating its schema. GraphQL servers can prevent this by refusing to execute operations (including introspection operations) on invalid schemas; any server built with `graphql-js` properly validates its schema prior to execution.

## 3. Compromised introspection Schema Example

You can view the code for the exploited schema [on codesandbox](https://codesandbox.io/s/graphql-xss-compromised-schema-3wdq7?file=/src/bad-schema.js) or [in the repository](../../packages/graphiql/test/bad-schema.js)

As you can see, the introspection schema must contain items with a compromised `name` value. this could be fields, input object names, enum names, variable names, etc any graphql [NamedType](https://github.com/graphql/graphql-spec/blob/main/spec/Section%202%20--%20Language.md#type-references) in the schema with it's name rendered in the autocomplete list.

```json
{
  "kind": "OBJECT",
  "name": "<img src=x onerror=alert(document.domain)>",
  "description": null,
  "fields": [
    {
      "name": "name",
      "description": null,
      "args": [],
      "type": {
        "kind": "NON_NULL",
        "name": null,
        "ofType": {
          "kind": "SCALAR",
          "name": "String",
          "ofType": null
        }
      },
      "isDeprecated": false,
      "deprecationReason": null
    }
  ],
  "inputFields": null,
  "interfaces": [],
  "enumValues": null,
  "possibleTypes": null
}
```
> **Security Notice:** All versions of `graphiql` < `1.4.3` are vulnerable to an XSS attack in cases where the GraphQL server to which the GraphiQL web app connects is not trusted. Learn more in [our security advisory](https://github.com/graphql/graphiql/tree/main/docs/security/2021-introspection-schema-xss.md).
> **Breaking Changes & Improvements:** several interfaces are being dropped for new ones for GraphiQL 2.0.0! Read more in [this issue](https://github.com/graphql/graphiql/issues/1165)
| Prop                             | Type                                                                                                  | Description                                                                                                                                                                                     |
| -------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetcher`                        | [`Fetcher function`](https://graphiql-test.netlify.app/typedoc/modules/graphiql-toolkit.html#fetcher) | **Required.** a function which accepts GraphQL-HTTP parameters and returns a Promise, Observable or AsyncIterable which resolves to the GraphQL parsed JSON response.                           |  |
| `schema`                         | [`GraphQLSchema`](https://graphql.org/graphql-js/type/#graphqlschema)                                 | a GraphQLSchema instance or `null` if one is not to be used. If `undefined` is provided, GraphiQL will send an introspection query using the fetcher to produce a schema.                       |
| `query`                          | `string` (GraphQL)                                                                                    | initial displayed query, if `undefined` is provided, the stored query or `defaultQuery` will be used. You can also set this value at runtime to override the current operation editor state.    |
| `validationRules`                | `ValidationRule[]`                                                                                    | A array of validation rules that will be used for validating the GraphQL operations. If `undefined` is provided, the default rules (exported as `specifiedRules` from `graphql`) will be used.  |
| `variables`                      | `string` (JSON)                                                                                       | initial displayed query variables, if `undefined` is provided, the stored variables will be used.                                                                                               |
| `headers`                        | `string`                                                                                              | initial displayed request headers. if not defined, it will default to the stored headers if `shouldPersistHeaders` is enabled.                                                                  |
| `externalFragments`              | `string \| FragmentDefinitionNode[]`                                                                  | provide fragments external to the operation for completion, validation, and for selective use when executing operations.                                                                        |
| `operationName`                  | `string`                                                                                              | an optional name of which GraphQL operation should be executed.                                                                                                                                 |
| `response`                       | `string` (JSON)                                                                                       | an optional JSON string to use as the initial displayed response. If not provided, no response will be initially shown. You might provide this if illustrating the result of the initial query. |
| `storage`                        | [`Storage`](https://graphiql-test.netlify.app/typedoc/interfaces/graphiql.storage.html)               | **Default:** `window.localStorage`. an interface that matches `window.localStorage` signature that GraphiQL will use to persist state.                                                          |
| `defaultQuery`                   | `string`                                                                                              | **Default:** graphiql help text. Provides default query if no user state is present.                                                                                                            | default graphiql help text |
| `defaultVariableEditorOpen`      | `boolean`                                                                                             | sets whether or not to show the variables pane on startup. overridden by user state (**deprecated** in favor of `defaultSecondaryEditorOpen`)                                                   |
| `defaultSecondaryEditorOpen`     | `boolean`                                                                                             | sets whether or not to show the variables/headers pane on startup. If not defined, it will be based off whether or not variables and/or headers are present.                                    |
| `getDefaultFieldNames`           | `Function`                                                                                            | **Default:** `defaultGetDefaultFieldNames`. provides default field values for incomplete queries                                                                                                | `defaultGetDefaultFieldNames` |
| `editorTheme`                    | `string`                                                                                              | **Default:** `graphiql`. names a CodeMirror theme to be applied to the `QueryEditor`, `ResultViewer`, and `Variables` panes. See below for full usage.                                          |
| `readOnly`                       | `boolean`                                                                                             | when `true` will make the `QueryEditor` and `Variables` panes readOnly.                                                                                                                         |
| `dangerouslyAssumeSchemaIsValid` | `boolean`                                                                                             | **Default:** `false`. When true, don't check that the loaded schema is valid; this can make the app vulnerable to XSS attacks and is not recommended.                                           |
| `docExplorerOpen`                | `boolean`                                                                                             | when `true` will ensure the `DocExplorer` is open by default when the user first renders the component. Overridden by user's toggle state                                                       |
| `headerEditorEnabled`            | `boolean`                                                                                             | **Default:** `false`. enables the header editor when `true`.                                                                                                                                    |
| `shouldPersistHeaders`           | `boolean`                                                                                             | **Default:** `false`. o persist headers to storage when `true`                                                                                                                                  |
| `toolbar.additionalContent`      | `React.Component[]`                                                                                   | pass additional toolbar react components inside a fragment                                                                                                                                      | `null` |
| `onEditQuery`                    | `Function`                                                                                            | called when the Query editor changes. The argument to the function will be the query string.                                                                                                    |
| `onEditVariables`                | `Function`                                                                                            | called when the Query variable editor changes. The argument to the function will be the variables string.                                                                                       |
| `onEditHeaders`                  | `Function`                                                                                            | called when the request headers editor changes. The argument to the function will be the headers string.                                                                                        |
| `onEditOperationName`            | `Function`                                                                                            | called when the operation name to be executed changes.                                                                                                                                          |
| `onToggleDocs`                   | `Function`                                                                                            | called when the docs will be toggled. The argument to the function will be a boolean whether the docs are now open or closed.                                                                   |
| `maxHistoryLength`               | `number`                                                                                              | **Default:** 20. allows you to increase the number of queries in the history component                                                                                                          | 20 |
  it('Shows the expected error when the schema is invalid', () => {
    cy.visit(`/?bad=true`);
    cy.assertResult({
      errors: [
        {
          message:
            'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "<img src=x onerror=alert(document.domain)>" does not.',
        },
      ],
    });
  });
    | { error: any[] }
    | { errors: any[] };
    assertResult(result: MockResult): Chainable<Element>;

Cypress.Commands.add('assertResult', (expectedResult, timeout = 200) => {
  cy.wait(timeout);
  cy.window().then(w => {
    // @ts-ignore
    const value = w.g.resultComponent.viewer.getValue();
    expect(value).to.deep.equal(JSON.stringify(expectedResult, null, 2));
  });
});
    "escape-html": "^1.0.3",
    "markdown-it": "^12.2.0"
    "@types/escape-html": "^1.0.1",
    "@types/markdown-it": "^12.2.3",
function getSchemaUrl() {
  const isDev = window.location.hostname.match(/localhost$/);

  if (isDev) {
    // This supports an e2e test which ensures that invalid schemas do not load.
    if (parameters.bad && parameters.bad === 'true') {
      return '/bad/graphql';
    } else {
      return '/graphql';
    }
  }
  return '/.netlify/functions/schema-demo';
}
    fetcher: GraphiQL.createFetcher({ url: getSchemaUrl() }),
import { GraphQLSchema, isType, GraphQLNamedType, GraphQLError } from 'graphql';
  schemaErrors?: readonly GraphQLError[];
      this.state.navStack !== nextState.navStack ||
      this.props.schemaErrors !== nextProps.schemaErrors
    const { schema, schemaErrors } = this.props;
    if (schemaErrors) {
      content = (
        <div className="error-container">{'Error fetching schema'}</div>
      );
    } else if (schema === undefined) {
  GraphQLError,
  formatError as formatGraphQLError,
  GraphQLFormattedError,
import { validateSchema } from 'graphql';

export type GenericError =
  | Error
  | string
  | readonly Error[]
  | readonly string[]
  | GraphQLError
  | readonly GraphQLError[];

  /**
   * decide whether schema responses should be validated. false by default
   */
  dangerouslyAssumeSchemaIsValid?: boolean;
  schemaErrors?: readonly GraphQLError[];
const stringify = (obj: unknown): string => JSON.stringify(obj, null, 2);

const formatSingleError = (error: Error): Error => ({
  ...error,
  // Raise these details even if they're non-enumerable
  message: error.message,
  stack: error.stack,
});

type InputError = Error | GraphQLError | string;

const handleSingleError = (
  error: InputError,
): GraphQLFormattedError | Error | string => {
  if (error instanceof GraphQLError) {
    return formatGraphQLError(error);
  }
  if (error instanceof Error) {
    return formatSingleError(error);
  }
  return error;
};

  static formatError = (error: GenericError): string => {
    if (Array.isArray(error)) {
      return stringify({
        errors: error.map((e: InputError) => handleSingleError(e)),
      });
    }
    // @ts-ignore
    return stringify({ errors: handleSingleError(error) });
  };
    let schema = props.schema;
    let response = props.response;
    let schemaErrors: readonly GraphQLError[] | undefined = undefined;
    if (schema && !this.props.dangerouslyAssumeSchemaIsValid) {
      const validationErrors = validateSchema(schema);
      if (validationErrors && validationErrors.length > 0) {
        // This is equivalent to handleSchemaErrors, but it's too early
        // to call setState.
        response = GraphiQL.formatError(validationErrors);
        schema = undefined;
        schemaErrors = validationErrors;
      }
    }

      schema,
      schemaErrors,
      response,
      if (!this.props.dangerouslyAssumeSchemaIsValid) {
        const validationErrors = validateSchema(nextSchema);
        if (validationErrors && validationErrors.length > 0) {
          this.handleSchemaErrors(validationErrors);
          nextSchema = undefined;
        }
      }

              schemaErrors={this.state.schemaErrors}
          let schema: GraphQLSchema | undefined = buildClientSchema(
            result.data,
          );
          if (!this.props.dangerouslyAssumeSchemaIsValid) {
            const errors = validateSchema(schema);
            // if there are errors, don't set schema
            if (errors && errors.length > 0) {
              schema = undefined;
              this.handleSchemaErrors(errors);
            }
          }
          if (schema) {
            const queryFacts = getOperationFacts(schema, this.state.query);
            this.safeSetState({
              schema,
              ...queryFacts,
              schemaErrors: undefined,
            });
          }
          // handle as if it were an error if the fetcher response is not a string or response.data is not present
          this.handleSchemaErrors([responseString]);
        this.handleSchemaErrors([error]);
  private handleSchemaErrors(
    schemaErrors: readonly GraphQLError[] | readonly string[],
  ) {
    this.safeSetState({
      response: schemaErrors ? GraphiQL.formatError(schemaErrors) : undefined,
      schema: undefined,
      schemaErrors,
    });
  }

      throw new Error(
        `Variables are invalid JSON: ${(error as Error).message}.`,
      );
      throw new Error(`Headers are invalid JSON: ${(error as Error).message}.`);
                response: error
                  ? GraphiQL.formatError(error as Error)
                  : undefined,
        response: (error as Error).message,
import escapeHTML from 'escape-html';
  return `<a class="typeName">${escapeHTML(type.name)}</a>`;
const { buildClientSchema } = require('graphql');

module.exports.schema = {
  __schema: {
    queryType: {
      name: 'Query',
    },
    mutationType: null,
    subscriptionType: null,
    types: [
      {
        kind: 'OBJECT',
        name: 'Query',
        description: null,
        fields: [
          {
            name: 'user',
            description: null,
            args: [
              {
                name: 'id',
                description: null,
                type: {
                  kind: 'NON_NULL',
                  name: null,
                  ofType: {
                    kind: 'SCALAR',
                    name: 'ID',
                    ofType: null,
                  },
                },
                defaultValue: null,
              },
            ],
            type: {
              kind: 'OBJECT',
              name: '<img src=x onerror=alert(document.domain)>',
              ofType: null,
            },
            isDeprecated: false,
            deprecationReason: null,
          },
        ],
        inputFields: null,
        interfaces: [],
        enumValues: null,
        possibleTypes: null,
      },
      {
        kind: 'SCALAR',
        name: 'ID',
        description: '',
        fields: null,
        inputFields: null,
        interfaces: null,
        enumValues: null,
        possibleTypes: null,
      },
      {
        kind: 'OBJECT',
        name: '<img src=x onerror=alert(document.domain)>',
        description: null,
        fields: [
          {
            name: 'name',
            description: null,
            args: [],
            type: {
              kind: 'NON_NULL',
              name: null,
              ofType: {
                kind: 'SCALAR',
                name: 'String',
                ofType: null,
              },
            },
            isDeprecated: false,
            deprecationReason: null,
          },
        ],
        inputFields: null,
        interfaces: [],
        enumValues: null,
        possibleTypes: null,
      },
      {
        kind: 'SCALAR',
        name: 'String',
        description: '',
        fields: null,
        inputFields: null,
        interfaces: null,
        enumValues: null,
        possibleTypes: null,
      },
    ],
    directives: [],
  },
};
const { schema: badSchema } = require('./bad-schema');
  app.post('/bad/graphql', (_req, res, next) => {
    res.json({ data: badSchema });
    next();
  });

const { schema: badSchema } = require('./bad-schema');
app.post('/bad/graphql', (_req, res, next) => {
  res.json({ data: badSchema });
  next();
});

  version "0.3.2"
"@types/escape-html@^1.0.1":
  version "1.0.1"
  resolved "https://registry.yarnpkg.com/@types/escape-html/-/escape-html-1.0.1.tgz#b19b4646915f0ae2c306bf984dc0a59c5cfc97ba"
  integrity sha512-4mI1FuUUZiuT95fSVqvZxp/ssQK9zsa86S43h9x3zPOSU9BBJ+BfDkXwuaU7BfsD+e7U0/cUUfJFk3iW2M4okA==

"@types/markdown-it@^12.2.3":
  version "12.2.3"
  resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-12.2.3.tgz#0d6f6e5e413f8daaa26522904597be3d6cd93b51"
  integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ==
  dependencies:
    "@types/linkify-it" "*"
    "@types/mdurl" "*"

"@types/mdurl@*":
  version "1.0.2"
  resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-1.0.2.tgz#e2ce9d83a613bacf284c7be7d491945e39e1f8e9"
  integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA==

argparse@^2.0.1:
  version "2.0.1"
  resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
  integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==

entities@~2.1.0:
  version "2.1.0"
  resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5"
  integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w==

escape-html@^1.0.3, escape-html@~1.0.3:
  version "1.4.6"
    "@graphiql/toolkit" "^0.3.2"
    codemirror-graphql "^1.0.3"
    escape-html "^1.0.3"
    graphql-language-service "^3.1.6"
    markdown-it "^12.2.0"
linkify-it@^3.0.1:
  version "3.0.3"
  resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.3.tgz#a98baf44ce45a550efb4d49c769d07524cc2fa2e"
  integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==
  dependencies:
    uc.micro "^1.0.1"

markdown-it@^12.2.0:
  version "12.2.0"
  resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.2.0.tgz#091f720fd5db206f80de7a8d1f1a7035fd0d38db"
  integrity sha512-Wjws+uCrVQRqOoJvze4HCqkKl1AsSh95iFAeQDwnyfxM09divCBSXlDR1uTvyUP3Grzpn4Ru8GeCxYPM8vkCQg==
  dependencies:
    argparse "^2.0.1"
    entities "~2.1.0"
    linkify-it "^3.0.1"
    mdurl "^1.0.1"
    uc.micro "^1.0.5"