import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { GraphQLSchema } from 'graphql'; import { loadDocuments } from '@graphql-tools/load'; import { CodeFileLoader } from '@graphql-tools/code-file-loader'; import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'; import { config as getGraphweaverConfig, TrustedDocumentAllowList, } from '@exogee/graphweaver-config'; import { buildTrustedDocuments, ExtractedDocument, TrustedDocument, TrustedDocumentError, } from './extract'; export { TrustedDocumentError, buildTrustedDocuments, hashDocument } from './extract'; export type { TrustedDocument } from './extract'; /** The reserved list holding everything the Admin UI can send. */ export const ADMIN_UI_ALLOW_LIST = 'admin-ui'; /** The query the Admin UI introspects the schema with, added only when it's switched on. */ export const ADMIN_UI_METADATA_QUERY = '_graphweaver'; /** * Whether this project serves the Admin UI. * * Projects that pass `adminMetadata: { enabled: false }` to Graphweaver don't get the * `_graphweaver` query, and the Admin UI can't do anything without it, so its absence from the * built schema is the same thing as "nobody is running the Admin UI against this API". Those * projects shouldn't have a few hundred generated documents they'll never send trusted on their * behalf. * * Without a schema we can't tell, and silently trusting documents is the worse mistake of the * two, so we say no. */ export const servesAdminUi = (schema?: GraphQLSchema) => Boolean(schema?.getQueryType()?.getFields()?.[ADMIN_UI_METADATA_QUERY]); export const GENERATED_FILE = path.join('src', 'trusted-documents.generated.ts'); export const MANIFEST_DIRECTORY = path.join('dist', 'trusted-documents'); const BANNER = `/* * This file is auto-generated by Graphweaver. * Please do not edit it directly. */`; const pathsFor = (allowList: TrustedDocumentAllowList) => Array.isArray(allowList) ? allowList : allowList.paths; const additionalDocumentsPathFor = (allowList: TrustedDocumentAllowList) => Array.isArray(allowList) ? undefined : allowList.additionalDocumentsPath; /** Scan a list's globs for `.graphql` files and `gql` tags in source files. */ const loadFromPaths = async (paths: string[]): Promise => { if (!paths.length) return []; let sources; try { sources = await loadDocuments(paths, { cwd: process.cwd(), loaders: [new GraphQLFileLoader(), new CodeFileLoader()], ignore: ['**/node_modules/**'], }); } catch (error: any) { // Globs that match nothing throw rather than coming back empty. That's expected for the // Admin UI's custom page and CSV override paths, which most projects don't have, so treat // it as "no documents here" the way codegen does. Anything else is a real problem. if (error.message?.includes('Unable to find any GraphQL type definitions for the following')) { return []; } throw error; } return sources.flatMap((source) => source.document ? [{ document: source.document, source: source.location ?? '(unknown file)' }] : [] ); }; /** * Pull in documents the static scan can't see - CSV export overrides that build their query at * runtime, and anything else generated rather than written down. */ const loadAdditionalDocuments = async ( modulePath: string, context: { schema?: GraphQLSchema; metadata?: unknown } ): Promise => { const resolved = path.resolve(process.cwd(), modulePath); const imported = await import(`file://${resolved}`); const exported = imported.default ?? imported; const documents = typeof exported === 'function' ? await exported(context) : await exported; if (!Array.isArray(documents)) { throw new TrustedDocumentError( `${modulePath} should default export an array of documents, or a function returning one, but it gave us ${typeof documents}.` ); } const { parse } = await import('graphql'); return documents.map((document: unknown, index: number) => ({ document: typeof document === 'string' ? parse(document) : (document as any), source: `${modulePath}[${index}]`, })); }; /** * Ask the Admin UI which operations it's capable of sending for this schema. * * Most of them are built at runtime from `_graphweaver` metadata, so they can't be found by * scanning source. We import the Admin UI's own generators and run them, which means the * safelist can't drift from what the Admin UI actually sends. */ const loadAdminUiDocuments = async (metadata: any): Promise => { if (!metadata?.entities) return []; try { const { enumerateAdminUiDocuments } = await import('@exogee/graphweaver-admin-ui-components/documents'); return enumerateAdminUiDocuments(metadata); } catch (error) { console.warn( 'Could not enumerate the Admin UI documents, so they will not be in the trusted document manifest. The Admin UI will not work while trusted documents are enforced.', error ); return []; } }; /** * The metadata the Admin UI would receive from `_graphweaver`. * * We call the resolver directly rather than executing the query. Going through GraphQL would * boot the whole request pipeline, which needs a live database connection we don't have at build * time, and would be subject to whatever access control list the project puts on `_graphweaver`. * The resolver itself reads nothing but the static entity metadata, so it's safe to call cold. * * Core has to be resolved from the user's project, not ours: the metadata lives in a module * level registry, so a different copy of the package would hand us an empty one. */ export const readAdminUiMetadata = async () => { try { // eslint-disable-next-line @typescript-eslint/no-require-imports const corePath = require.resolve('@exogee/graphweaver', { paths: [process.cwd()] }); const { resolveAdminUiMetadata, hookManagerMap } = await import(pathToFileURL(corePath).href); // If the project uses `@exogee/graphweaver-auth`, it will have registered an access control // hook on this metadata, and that hook expects to be inside a request: it reads the roles of // the signed in user out of async local storage and throws when there isn't one. There is no // user here, and no request - we're a build step reading the static shape of the schema, and // we want all of it rather than the slice some particular role can see. So lift the hook for // the duration of the call. This process does nothing else and exits immediately afterwards. const hooks = hookManagerMap.get('AdminUiMetadata'); hookManagerMap.delete('AdminUiMetadata'); try { // `fields` has to be undefined rather than empty: the same hook checks it for a GraphQL // selection set and blows up on an object that hasn't got one. return await resolveAdminUiMetadata()({ context: {}, fields: undefined }); } finally { if (hooks) hookManagerMap.set('AdminUiMetadata', hooks); } } catch (error: any) { console.warn( `Could not read the Admin UI metadata, so its documents will not be in the manifest and the Admin UI will not work while trusted documents are enforced: ${error.message}` ); return undefined; } }; export type GenerateOptions = { schema?: GraphQLSchema; /** The `_graphweaver` metadata, used to enumerate the Admin UI's documents. */ metadata?: unknown; /** * Whether to generate the Admin UI allow list. Defaults to whether the schema serves the * Admin UI's metadata query, so projects that have turned the Admin UI off don't safelist * its documents. */ includeAdminUi?: boolean; }; export type GeneratedTrustedDocuments = { allowLists: Record; total: number; }; export const generateTrustedDocuments = async ({ schema, metadata, includeAdminUi, }: GenerateOptions = {}): Promise => { const { trustedDocuments, adminUI } = getGraphweaverConfig(); const configured = Object.entries(trustedDocuments?.allowLists ?? {}); if (!configured.length) return undefined; const adminUiIsServed = servesAdminUi(schema); if (includeAdminUi === undefined && !adminUiIsServed) { console.log( `This project doesn't serve the Admin UI, so the "${ADMIN_UI_ALLOW_LIST}" allow list has been left out of the manifest.` ); } const allowLists: Record = {}; for (const [name, allowList] of configured) { if (name === ADMIN_UI_ALLOW_LIST) { throw new TrustedDocumentError( `"${ADMIN_UI_ALLOW_LIST}" is reserved for the documents Graphweaver generates for the Admin UI, so it can't be used as an allow list name.` ); } const extracted = await loadFromPaths(pathsFor(allowList)); const additionalDocumentsPath = additionalDocumentsPathFor(allowList); if (additionalDocumentsPath) { extracted.push( ...(await loadAdditionalDocuments(additionalDocumentsPath, { schema, metadata })) ); } allowLists[name] = buildTrustedDocuments(extracted, schema); if (!allowLists[name].length) { console.warn( `The "${name}" allow list didn't match any operations, so every request claiming that list will be rejected. Check the paths in your graphweaver-config file.` ); } } if (includeAdminUi ?? adminUiIsServed) { const adminUiDocuments = await loadAdminUiDocuments(metadata); // Anything the developer wrote into their custom pages or CSV export overrides is sent by // the Admin UI too, so it belongs in the same list. const customPaths = [adminUI?.customPagesPath, adminUI?.csvExportOverridesPath] .filter((candidate): candidate is string => Boolean(candidate)) .map((candidate) => path.join(candidate, '**/*.{ts,tsx,js,jsx,graphql,gql}')); adminUiDocuments.push(...(await loadFromPaths(customPaths))); if (adminUiDocuments.length) { allowLists[ADMIN_UI_ALLOW_LIST] = buildTrustedDocuments(adminUiDocuments, schema, { onInvalid: 'skip', }); } } const total = Object.values(allowLists).reduce((sum, documents) => sum + documents.length, 0); return { allowLists, total }; }; /** The module the backend imports, so the manifest ends up inside the server bundle. */ export const writeGeneratedManifest = ({ allowLists }: GeneratedTrustedDocuments) => { const manifest = { format: 'graphweaver-trusted-documents', version: 1, allowLists: Object.fromEntries( Object.entries(allowLists).map(([name, documents]) => [ name, Object.fromEntries( // An entry per variant, so an operation is accepted whether the client sent it as // written or as Apollo rewrote it, and either way we execute the document it asked // for. See `TrustedDocument.apollo`. documents.flatMap((document) => [document, document.apollo].filter(Boolean).map((variant) => [ variant!.id, { body: variant!.body, operationName: document.operationName, operationType: document.operationType, }, ]) ) ), ]) ), }; const contents = `${BANNER} import type { TrustedDocumentManifest } from '@exogee/graphweaver-server'; export const trustedDocuments = ${JSON.stringify(manifest, null, '\t')} as const satisfies TrustedDocumentManifest; `; fs.mkdirSync(path.dirname(GENERATED_FILE), { recursive: true }); fs.writeFileSync(GENERATED_FILE, contents, 'utf8'); return GENERATED_FILE; }; /** * One manifest per allow list, so each client only ever ships the ids it's allowed to use and * we don't leak one client's operations to another. */ export const writeClientManifests = ({ allowLists }: GeneratedTrustedDocuments) => { fs.mkdirSync(MANIFEST_DIRECTORY, { recursive: true }); return Object.entries(allowLists).map(([name, documents]) => { const file = path.join(MANIFEST_DIRECTORY, `${name}.persisted-query-manifest.json`); fs.writeFileSync( file, JSON.stringify( { format: 'apollo-persisted-query-manifest', version: 1, // Apollo's manifest format is keyed on the operation name, so this is one entry per // operation, not per variant. It's the Apollo variant that goes in: this file exists // for Apollo clients, and its whole job is to hand them the id they'd otherwise have // to hash. A client that sends operations as written doesn't need a manifest at all. operations: documents.map((document) => { const variant = document.apollo ?? document; return { id: variant.id, name: document.operationName, type: document.operationType, body: variant.body, }; }), }, null, 2 ), 'utf8' ); return file; }); }; /** * Write the manifest we can build without a schema, before we build the backend that imports it. * * There's a chicken and egg here: the full manifest needs the schema and the Admin UI metadata, * which we only get by building and importing the backend, which can't build until this file * exists. So we do the part that needs nothing first - scanning the developer's own globs - and * fill in schema validation and the Admin UI list once the backend has been built. * * Deliberately not a stub: an empty manifest would be enforced, locking every client out. */ export const generateStaticTrustedDocuments = async () => { const { trustedDocuments } = getGraphweaverConfig(); if (!Object.keys(trustedDocuments?.allowLists ?? {}).length) return; const generated = await generateTrustedDocuments({ includeAdminUi: false }); if (!generated) return; writeGeneratedManifest(generated); };