-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Generate the list of sensitive operations dynamically from schema (#1478
- Loading branch information
Showing
3 changed files
with
50 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,49 @@ | ||
import { plugin as basePlugin } from '@graphql-codegen/named-operations-object'; | ||
import type { PluginFunction } from '@graphql-codegen/plugin-helpers'; | ||
import { concatAST, FieldNode, visit } from 'graphql'; | ||
|
||
export const plugin: PluginFunction = async (...args) => { | ||
const result = await basePlugin(...args); | ||
return result ? result + ' as const' : result; | ||
let result = await basePlugin(...args); | ||
result = result ? result + ' as const;' : result; | ||
|
||
const [schema, documents] = args; | ||
|
||
const queries = Object.values(schema.getQueryType()?.getFields() ?? {}); | ||
const mutations = Object.values(schema.getMutationType()?.getFields() ?? {}); | ||
const sensitiveQueries = new Set( | ||
[...queries, ...mutations] | ||
.filter( | ||
(f) => f.description && /^\s*@sensitive-secrets$/m.test(f.description) | ||
) | ||
.map((f) => f.name) | ||
); | ||
const sensitiveOperationsNames = new Set(); | ||
const allAst = concatAST(documents.flatMap((v) => v.document ?? [])); | ||
visit(allAst, { | ||
OperationDefinition: (node) => { | ||
if ( | ||
!node.name || | ||
(node.operation !== 'query' && node.operation !== 'mutation') | ||
) { | ||
return; | ||
} | ||
const fields = node.selectionSet.selections | ||
.filter((s): s is FieldNode => s.kind === 'Field') | ||
.map((s) => s.name.value); | ||
for (const field of fields) { | ||
if (sensitiveQueries.has(field)) { | ||
sensitiveOperationsNames.add(node.name.value); | ||
} | ||
} | ||
}, | ||
}); | ||
|
||
result += ` | ||
export const GqlSensitiveOperations: ReadonlySet<string> = new Set([ | ||
${[...sensitiveOperationsNames].map((n) => ` '${n}'`).join(',\n')} | ||
]); | ||
`; | ||
|
||
return result; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters