Skip to content

Commit d3ad3b4

Browse files
thommymothommym
andauthored
feat: disable introspection by default (#335)
Co-authored-by: thommym <[email protected]>
1 parent 632a107 commit d3ad3b4

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/api/execute.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import { makeExecutableSchema } from '@graphql-tools/schema';
22
import { IResolvers } from '@graphql-tools/utils';
3-
import { GraphQLResolveInfo, Source, execute as graphqlExecute, parse } from 'graphql';
3+
import { GraphQLResolveInfo, Source, execute as graphqlExecute, parse, specifiedRules, validate } from 'graphql';
44
import merge from 'lodash/merge';
55
import { Context, generate, get, getResolvers } from '..';
6+
import { noIntrospection } from '../utils/rules';
67

78
export const execute = async ({
89
additionalResolvers,
910
body,
11+
introspection = false,
1012
...ctx
1113
}: {
1214
additionalResolvers?: IResolvers<any, any>;
15+
introspection?: boolean;
1316
body: any;
1417
} & Omit<Context, 'document'>) => {
1518
const document = generate(ctx.models);
@@ -21,14 +24,26 @@ export const execute = async ({
2124
resolvers: merge(generatedResolvers, additionalResolvers),
2225
});
2326

27+
const parsedDocument = parse(new Source(body.query, 'GraphQL request'));
28+
29+
const validationErrors = validate(
30+
schema,
31+
parsedDocument,
32+
introspection ? specifiedRules : [...specifiedRules, noIntrospection],
33+
);
34+
35+
if (validationErrors.length > 0) {
36+
return { errors: validationErrors };
37+
}
38+
2439
const contextValue: Context = {
2540
document,
2641
...ctx,
2742
};
2843

2944
const result = await graphqlExecute({
3045
schema,
31-
document: parse(new Source(body.query, 'GraphQL request')),
46+
document: parsedDocument,
3247
contextValue,
3348
variableValues: body.variables,
3449
operationName: body.operationName,

src/utils/rules.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { ValidationContext } from 'graphql';
2+
import { ForbiddenError } from '../errors';
3+
4+
export const noIntrospection = (context: ValidationContext) => ({
5+
Field(node) {
6+
const name = node.name.value;
7+
if (name === '__schema' || name === '__type') {
8+
context.reportError(new ForbiddenError('GraphQL introspection is disabled'));
9+
}
10+
},
11+
});

0 commit comments

Comments
 (0)