From 3b7ac556dab314ab8216718e920f3119fadc8d33 Mon Sep 17 00:00:00 2001 From: Jubilee_001 Date: Fri, 20 Nov 2026 16:04:35 +0100 Subject: [PATCH 1/2] feat(graphql): add read-only GraphQL endpoint for keys, holders and trades (#1248) Mount graphql-yoga at POST /api/v1/graphql exposing a read-only schema with Key, Holder and Trade types plus Relay-style cursor connections (key(id), keys(first,after), trades(keyId,first,after)). - src/graphql/schema.ts: typeDefs with read-only Query root (no mutations) - src/graphql/resolvers.ts: cursor pagination reusing paginateQuery and DataLoaders for batched holder/creator lookups - src/graphql/loaders.ts: per-request DataLoaders (creator, holder, holdersByKey) batching lookups to one query per request level - src/graphql/validation.ts: max depth 6, max cost 1000, introspection disabled in production unless a valid x-api-key is supplied - src/graphql/router.ts: Express handler executing graphql() with custom validation rules and per-request loader context - src/app.ts: mount the router under /api/v1/graphql Tests cover nested resolution, pagination, depth/cost limit enforcement, DataLoader batching, and that mutations are not exposed. --- package.json | 3 + pnpm-lock.yaml | 346 ++++++++++++++++++ src/app.ts | 3 + .../__tests__/graphql.integration.test.ts | 312 ++++++++++++++++ src/graphql/loaders.ts | 115 ++++++ src/graphql/resolvers.ts | 331 +++++++++++++++++ src/graphql/router.ts | 117 ++++++ src/graphql/schema.ts | 107 ++++++ src/graphql/validation.ts | 122 ++++++ 9 files changed, 1456 insertions(+) create mode 100644 src/graphql/__tests__/graphql.integration.test.ts create mode 100644 src/graphql/loaders.ts create mode 100644 src/graphql/resolvers.ts create mode 100644 src/graphql/router.ts create mode 100644 src/graphql/schema.ts create mode 100644 src/graphql/validation.ts diff --git a/package.json b/package.json index 10122b10..5ec57a6f 100644 --- a/package.json +++ b/package.json @@ -56,6 +56,9 @@ "dotenv": "^16.5.0", "express": "^5.1.0", "express-rate-limit": "^8.2.1", + "dataloader": "^2.2.3", + "graphql": "^16.10.0", + "graphql-yoga": "^5.8.1", "google-auth-library": "^10.5.0", "helmet": "^8.1.0", "ioredis": "^6.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 863d2aed..609528cd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -40,6 +40,9 @@ importers: cors: specifier: ^2.8.5 version: 2.8.6 + dataloader: + specifier: ^2.2.3 + version: 2.2.3 dotenv: specifier: ^16.5.0 version: 16.6.1 @@ -52,6 +55,12 @@ importers: google-auth-library: specifier: ^10.5.0 version: 10.9.0 + graphql: + specifier: ^16.10.0 + version: 16.15.0 + graphql-yoga: + specifier: ^5.8.1 + version: 5.24.6(graphql@16.15.0) helmet: specifier: ^8.1.0 version: 8.2.0 @@ -537,6 +546,27 @@ packages: integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==, } + '@envelop/core@5.6.1': + resolution: + { + integrity: sha512-KEbJ7yrAA+W7IY9MZzpZJ77w/72ndaV/16+hhPapd+0Ohjqffl0mmF3QWy62/m3nRP4qidD+1eiEjJhS/O38Tg==, + } + engines: { node: '>=18.0.0' } + + '@envelop/instrumentation@1.0.1': + resolution: + { + integrity: sha512-FuexE2qd3Yc1Kh1DjTliwGxb9kyyv4ySBNnfJOxnQasVmGdcqX6AkkO5sIMxLWFRftp8PErOcIn2dQW/1RwytQ==, + } + engines: { node: '>=18.0.0' } + + '@envelop/types@5.2.2': + resolution: + { + integrity: sha512-nl9cmUh8F+2/NNzpcLjzNqtaVn0m8XSzzxrPU2ByHhlz4Hqlc5QBfRsemZkoJMKrMviJXyJYdKZiUP1o70F3Kw==, + } + engines: { node: '>=18.0.0' } + '@eslint-community/eslint-utils@4.9.1': resolution: { @@ -602,6 +632,77 @@ packages: } engines: { node: ^18.18.0 || ^20.9.0 || >=21.1.0 } + '@fastify/busboy@3.2.6': + resolution: + { + integrity: sha512-UPXdyAMbz/gNvjS8HONpJR2TDaHM3wQKMtSRPFkoh2LTeRRtnm+ICVYKgBYkTwlPOVzDNynOd34EH8qapwfelQ==, + } + + '@graphql-tools/executor@2.1.0': + resolution: + { + integrity: sha512-RR41E8r1FKrHhZS5YhdcUg04GZ5VP6VGaO2MQKkmEEazXx6qY4kuzZYLs4kq+DBzPdNmsRdVsf7K/uTfi5fhAA==, + } + engines: { node: '>=16.0.0' } + peerDependencies: + graphql: ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + + '@graphql-tools/merge@9.2.8': + resolution: + { + integrity: sha512-OsCEmJ9RIMT4LB/1jBbyKHe7pMIlfGhLAQ0FVNaZqteydDUC+rTI9wZ+yaKqxQpPOFFycD+UtMhovg19lPq92Q==, + } + engines: { node: '>=16.0.0' } + peerDependencies: + graphql: ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + + '@graphql-tools/schema@10.1.5': + resolution: + { + integrity: sha512-F0Onw0ZBREakKGqcgsKhdSCjOXgmntzQWL0QA+/WrwKmnJ7nJRyGKUJavwuVZL2TrXblaIUvQxm4t1h3FuA3cA==, + } + engines: { node: '>=16.0.0' } + peerDependencies: + graphql: ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + + '@graphql-tools/utils@12.1.0': + resolution: + { + integrity: sha512-+mOuIX7u83/BHG0L9JviMzKid1j35cxOWhLoox47TXHAJ6Tnn30RgrmEQPmk1FhmaQbhJEcwYBDVyieUvZopJw==, + } + engines: { node: '>=16.0.0' } + peerDependencies: + graphql: ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + + '@graphql-typed-document-node/core@3.2.0': + resolution: + { + integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==, + } + peerDependencies: + graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + + '@graphql-yoga/logger@2.0.2': + resolution: + { + integrity: sha512-k2QGHCcH10O+GGe1sgXn0paaP9GCK91wxkuNQaA4IvXBF/RcdBLaX15UeZLW9kMG8kfz7bL0r4Yu+BXYe0JOaw==, + } + engines: { node: '>=18.0.0' } + + '@graphql-yoga/subscription@5.1.1': + resolution: + { + integrity: sha512-I48DpyPTxYzmO5TwvKOXxiLI/tsbyeYNhb4/6/oJEBn6nlb8snHL0G0Fw1LC2ApNW1QKYuCPRDTp9yUwVBqhNQ==, + } + engines: { node: '>=18.0.0' } + + '@graphql-yoga/typed-event-target@3.0.3': + resolution: + { + integrity: sha512-j/EgVfZSzKA2lVeiZ0un8E2eVIqWa9Woyqta4A40ht1M93ui9CDVHU6pmphoQTpFa92BNbMVexXdOtMQk8LCjA==, + } + engines: { node: '>=18.0.0' } + '@humanfs/core@0.19.2': resolution: { @@ -1182,6 +1283,12 @@ packages: engines: { node: '>=18' } hasBin: true + '@repeaterjs/repeater@3.1.0': + resolution: + { + integrity: sha512-TaoVksZRSx2KWYYpyLQtMQXXeS98VsgZImzW65xmiVgbYhXLk+aEsmzPLirqVuE4/XuUapH2iMtxUzaBNDzdSQ==, + } + '@scarf/scarf@1.4.0': resolution: { @@ -1842,6 +1949,62 @@ packages: cpu: [x64] os: [win32] + '@whatwg-node/disposablestack@0.0.6': + resolution: + { + integrity: sha512-LOtTn+JgJvX8WfBVJtF08TGrdjuFzGJc4mkP8EdDI8ADbvO7kiexYep1o8dwnt0okb0jYclCDXF13xU7Ge4zSw==, + } + engines: { node: '>=18.0.0' } + + '@whatwg-node/disposablestack@0.1.0': + resolution: + { + integrity: sha512-ok0A9+D+mdeb3w1GNCpVr+2gVVLRWKo9Ywm/whNsoWSNfNg3jNxS0/wUF6NSUYbfOtFGu2wZgJnLjasbaQEfvA==, + } + engines: { node: '>=22.15.0' } + + '@whatwg-node/events@0.1.2': + resolution: + { + integrity: sha512-ApcWxkrs1WmEMS2CaLLFUEem/49erT3sxIVjpzU5f6zmVcnijtDSrhoK2zVobOIikZJdH63jdAXOrvjf6eOUNQ==, + } + engines: { node: '>=18.0.0' } + + '@whatwg-node/fetch@0.10.13': + resolution: + { + integrity: sha512-b4PhJ+zYj4357zwk4TTuF2nEe0vVtOrwdsrNo5hL+u1ojXNhh1FgJ6pg1jzDlwlT4oBdzfSwaBwMCtFCsIWg8Q==, + } + engines: { node: '>=18.0.0' } + + '@whatwg-node/node-fetch@0.8.6': + resolution: + { + integrity: sha512-BDMdYFcerLQkwA2RTldxOqRCs6ZQD1S7UgP3pUdGUkcbgTrP/V5ko77ZkCww9DHmC4lpoYuwigGfQYj285gMvA==, + } + engines: { node: '>=18.0.0' } + + '@whatwg-node/promise-helpers@1.3.2': + resolution: + { + integrity: sha512-Nst5JdK47VIl9UcGwtv2Rcgyn5lWtZ0/mhRQ4G8NN2isxpq2TO30iqHzmwoJycjWuyUfg3GFXqP/gFHXeV57IA==, + } + engines: { node: '>=16.0.0' } + + '@whatwg-node/promise-helpers@2.0.2': + resolution: + { + integrity: sha512-RKVGTBAuYfObHxUFjlTFmlDndmuXBxkN56yj3z6EQpNpT55R/xaMhTi4+9yXZ5UoDXbKLAsZHCP8ycoWHM/Vdg==, + } + engines: { node: '>=22.15.0' } + + '@whatwg-node/server@0.11.0': + resolution: + { + integrity: sha512-VSdkwnJRr8Yv9UgB2aXB3VUPWwd6Oqnn0hycFwhg9pZgWxJXb7JmhsiXe9tmpMwjHFxli12PGcz9aI63YYloGQ==, + } + engines: { node: '>=18.0.0' } + accepts@2.0.0: resolution: { @@ -2677,6 +2840,13 @@ packages: integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==, } + cross-inspect@1.0.1: + resolution: + { + integrity: sha512-Pcw1JTvZLSJH83iiGWt6fRcT+BjZlCDRVwYLbUcHzv/CRpB7r0MlSrGbIyQvVSNyGnbt7G4AXuyCiDR3POvZ1A==, + } + engines: { node: '>=16.0.0' } + cross-spawn@7.0.6: resolution: { @@ -2704,6 +2874,12 @@ packages: } engines: { node: '>= 14' } + dataloader@2.2.3: + resolution: + { + integrity: sha512-y2krtASINtPFS1rSDjacrFgn1dcUuoREVabwlOGOe4SdxenREqwjwjElAdwvbGM7kgZz9a3KVicWR7vcz8rnzA==, + } + dateformat@4.6.3: resolution: { @@ -3601,6 +3777,22 @@ packages: integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==, } + graphql-yoga@5.24.6: + resolution: + { + integrity: sha512-IpRSnLfxbv1oiNTghzYjb0QPCn4p1y+8uoXJ0MkC5aNJAko2PSba89ByJXHIxoQAILZ3PKZaVcaEtlDJw4YQxw==, + } + engines: { node: '>=18.0.0' } + peerDependencies: + graphql: ^15.2.0 || ^16.0.0 || ^17.0.0 + + graphql@16.15.0: + resolution: + { + integrity: sha512-32kz9FecohDiC/tgcViwnRXM7HFBVTPiW7pHO+DikKOI5KjhU/jNULOReXsrFqt2WAYbE9xFXsTffJw6iTO8qw==, + } + engines: { node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0 } + handlebars@4.7.9: resolution: { @@ -6039,6 +6231,12 @@ packages: integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==, } + tslib@2.9.1: + resolution: + { + integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==, + } + tspec@0.1.120: resolution: { @@ -6207,6 +6405,12 @@ packages: integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==, } + urlpattern-polyfill@10.1.0: + resolution: + { + integrity: sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw==, + } + util-deprecate@1.0.2: resolution: { @@ -6671,6 +6875,23 @@ snapshots: tslib: 2.8.1 optional: true + '@envelop/core@5.6.1': + dependencies: + '@envelop/instrumentation': 1.0.1 + '@envelop/types': 5.2.2 + '@whatwg-node/promise-helpers': 1.3.2 + tslib: 2.8.1 + + '@envelop/instrumentation@1.0.1': + dependencies: + '@whatwg-node/promise-helpers': 1.3.2 + tslib: 2.8.1 + + '@envelop/types@5.2.2': + dependencies: + '@whatwg-node/promise-helpers': 1.3.2 + tslib: 2.8.1 + '@eslint-community/eslint-utils@4.9.1(eslint@9.39.4(jiti@2.7.0))': dependencies: eslint: 9.39.4(jiti@2.7.0) @@ -6717,6 +6938,59 @@ snapshots: '@eslint/core': 0.17.0 levn: 0.4.1 + '@fastify/busboy@3.2.6': {} + + '@graphql-tools/executor@2.1.0(graphql@16.15.0)': + dependencies: + '@graphql-tools/utils': 12.1.0(graphql@16.15.0) + '@graphql-typed-document-node/core': 3.2.0(graphql@16.15.0) + '@repeaterjs/repeater': 3.1.0 + '@whatwg-node/disposablestack': 0.1.0 + '@whatwg-node/promise-helpers': 2.0.2 + graphql: 16.15.0 + tslib: 2.8.1 + + '@graphql-tools/merge@9.2.8(graphql@16.15.0)': + dependencies: + '@graphql-tools/utils': 12.1.0(graphql@16.15.0) + graphql: 16.15.0 + tslib: 2.8.1 + + '@graphql-tools/schema@10.1.5(graphql@16.15.0)': + dependencies: + '@graphql-tools/merge': 9.2.8(graphql@16.15.0) + '@graphql-tools/utils': 12.1.0(graphql@16.15.0) + graphql: 16.15.0 + tslib: 2.8.1 + + '@graphql-tools/utils@12.1.0(graphql@16.15.0)': + dependencies: + '@graphql-typed-document-node/core': 3.2.0(graphql@16.15.0) + '@whatwg-node/promise-helpers': 2.0.2 + cross-inspect: 1.0.1 + graphql: 16.15.0 + tslib: 2.8.1 + + '@graphql-typed-document-node/core@3.2.0(graphql@16.15.0)': + dependencies: + graphql: 16.15.0 + + '@graphql-yoga/logger@2.0.2': + dependencies: + tslib: 2.8.1 + + '@graphql-yoga/subscription@5.1.1': + dependencies: + '@graphql-yoga/typed-event-target': 3.0.3 + '@repeaterjs/repeater': 3.1.0 + '@whatwg-node/events': 0.1.2 + tslib: 2.8.1 + + '@graphql-yoga/typed-event-target@3.0.3': + dependencies: + '@repeaterjs/repeater': 3.1.0 + tslib: 2.8.1 + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -7140,6 +7414,8 @@ snapshots: - react-native-b4a - supports-color + '@repeaterjs/repeater@3.1.0': {} + '@scarf/scarf@1.4.0': {} '@sinclair/typebox@0.34.49': {} @@ -7533,6 +7809,48 @@ snapshots: '@unrs/resolver-binding-win32-x64-msvc@1.12.2': optional: true + '@whatwg-node/disposablestack@0.0.6': + dependencies: + '@whatwg-node/promise-helpers': 1.3.2 + tslib: 2.8.1 + + '@whatwg-node/disposablestack@0.1.0': + dependencies: + '@whatwg-node/promise-helpers': 2.0.2 + tslib: 2.8.1 + + '@whatwg-node/events@0.1.2': + dependencies: + tslib: 2.8.1 + + '@whatwg-node/fetch@0.10.13': + dependencies: + '@whatwg-node/node-fetch': 0.8.6 + urlpattern-polyfill: 10.1.0 + + '@whatwg-node/node-fetch@0.8.6': + dependencies: + '@fastify/busboy': 3.2.6 + '@whatwg-node/disposablestack': 0.0.6 + '@whatwg-node/promise-helpers': 1.3.2 + tslib: 2.8.1 + + '@whatwg-node/promise-helpers@1.3.2': + dependencies: + tslib: 2.8.1 + + '@whatwg-node/promise-helpers@2.0.2': + dependencies: + tslib: 2.9.1 + + '@whatwg-node/server@0.11.0': + dependencies: + '@envelop/instrumentation': 1.0.1 + '@whatwg-node/disposablestack': 0.0.6 + '@whatwg-node/fetch': 0.10.13 + '@whatwg-node/promise-helpers': 1.3.2 + tslib: 2.8.1 + accepts@2.0.0: dependencies: mime-types: 3.0.2 @@ -7989,6 +8307,10 @@ snapshots: create-require@1.1.1: {} + cross-inspect@1.0.1: + dependencies: + tslib: 2.8.1 + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -8001,6 +8323,8 @@ snapshots: data-uri-to-buffer@6.0.2: {} + dataloader@2.2.3: {} + dateformat@4.6.3: {} debug@2.6.9: @@ -8569,6 +8893,24 @@ snapshots: graceful-fs@4.2.11: {} + graphql-yoga@5.24.6(graphql@16.15.0): + dependencies: + '@envelop/core': 5.6.1 + '@envelop/instrumentation': 1.0.1 + '@graphql-tools/executor': 2.1.0(graphql@16.15.0) + '@graphql-tools/schema': 10.1.5(graphql@16.15.0) + '@graphql-tools/utils': 12.1.0(graphql@16.15.0) + '@graphql-yoga/logger': 2.0.2 + '@graphql-yoga/subscription': 5.1.1 + '@whatwg-node/fetch': 0.10.13 + '@whatwg-node/promise-helpers': 1.3.2 + '@whatwg-node/server': 0.11.0 + graphql: 16.15.0 + lru-cache: 10.4.3 + tslib: 2.8.1 + + graphql@16.15.0: {} + handlebars@4.7.9: dependencies: minimist: 1.2.8 @@ -10234,6 +10576,8 @@ snapshots: tslib@2.8.1: {} + tslib@2.9.1: {} + tspec@0.1.120(@types/express@5.0.6)(express@5.2.1): dependencies: debug: 4.4.3(supports-color@5.5.0) @@ -10361,6 +10705,8 @@ snapshots: dependencies: punycode: 2.3.1 + urlpattern-polyfill@10.1.0: {} + util-deprecate@1.0.2: {} v8-compile-cache-lib@3.0.1: {} diff --git a/src/app.ts b/src/app.ts index 638fb684..f5a2227f 100644 --- a/src/app.ts +++ b/src/app.ts @@ -8,6 +8,7 @@ import statusRouter from './modules/status/status.routes'; import keysRouter from './modules/keys/keys.routes'; import tradesRouter from './modules/trades/trades.routes'; import tradersRouter from './modules/traders/traders.routes'; +import graphqlRouter from './graphql/router'; import nonceRouter from './modules/nonce/nonce.routes'; import swapsRouter from './modules/swaps/swaps.routes'; import milestonesRouter from './modules/keys/milestones.routes'; @@ -114,6 +115,8 @@ app.use('/status', routeBodySizeLimit('default'), statusRouter); app.use('/nonce', routeBodySizeLimit('default'), nonceRouter); app.use('/internal', routeBodySizeLimit('default'), internalRouter); app.use('/api/v1', router); +// Read-only GraphQL endpoint (issue #1248): POST /api/v1/graphql +app.use('/api/v1/graphql', graphqlRouter); app.use('/staking', routeBodySizeLimit('default'), stakingRouter); app.use('/trades', routeBodySizeLimit('default'), tradesRouter); app.use('/traders', routeBodySizeLimit('default'), tradersRouter); diff --git a/src/graphql/__tests__/graphql.integration.test.ts b/src/graphql/__tests__/graphql.integration.test.ts new file mode 100644 index 00000000..d20eafa1 --- /dev/null +++ b/src/graphql/__tests__/graphql.integration.test.ts @@ -0,0 +1,312 @@ +// src/graphql/__tests__/graphql.integration.test.ts +// Tests for the read-only GraphQL endpoint (issue #1248). +// +// Covers: nested key/holder/trade resolution, pagination, max-depth limit, +// max-cost limit, DataLoader batching (one query per level), and the absence +// of mutations. + +import request from 'supertest'; +import app from '../../app'; +import { prisma } from '../../utils/prisma.utils'; + +jest.setTimeout(30000); + +// Mock prisma so GraphQL resolvers can be exercised without a live database. +jest.mock('../../utils/prisma.utils', () => { + const prismaMock: any = { + creatorProfile: { + findUnique: jest.fn(), + findMany: jest.fn(), + count: jest.fn(), + }, + trade: { + findMany: jest.fn(), + count: jest.fn(), + }, + }; + return { prisma: prismaMock }; +}); + +const mockPrisma: any = prisma; + +const testKeyId = 'key-1'; +const testKey = { + id: testKeyId, + handle: 'creator-alpha', + displayName: 'Creator Alpha', + creatorWallet: 'GA_CREATOR', + status: 'Active', + createdAt: new Date('2026-01-01T00:00:00.000Z'), + updatedAt: new Date('2026-01-01T00:00:00.000Z'), +}; + +const testTrade = { + id: 'trade-1', + creatorId: testKeyId, + buyer: 'GB_BUYER', + quantity: '10', + price: '100', + paymentAsset: 'XLM', + ledger: 5000, + txHash: '0xtx1', + timestamp: new Date('2026-01-02T00:00:00.000Z'), + createdAt: new Date('2026-01-02T00:00:00.000Z'), +}; + +function graphql(query: string, headers: Record = {}) { + return request(app) + .post('/api/v1/graphql') + .set('Content-Type', 'application/json') + .set(headers) + .send({ query }); +} + +beforeEach(() => { + jest.clearAllMocks(); + mockPrisma.creatorProfile.findUnique.mockResolvedValue(testKey); + mockPrisma.creatorProfile.findMany.mockResolvedValue([testKey]); + mockPrisma.creatorProfile.count.mockResolvedValue(1); + mockPrisma.trade.findMany.mockResolvedValue([testTrade]); + mockPrisma.trade.count.mockResolvedValue(1); +}); + +describe('GraphQL endpoint (POST /api/v1/graphql)', () => { + describe('nested resolution', () => { + it('resolves key -> holders -> trades with correct data', async () => { + const query = ` + { + key(id: "${testKeyId}") { + id + handle + holders(first: 10) { + edges { node { walletAddress totalKeysHeld } cursor } + } + trades(first: 10) { + edges { node { id buyer quantity price } cursor } + } + } + } + `; + mockPrisma.trade.findMany.mockResolvedValueOnce([testTrade]); + const res = await graphql(query); + + expect(res.status).toBe(200); + const body = res.body; + expect(body.errors).toBeUndefined(); + expect(body.data.key.id).toBe(testKeyId); + expect(body.data.key.handle).toBe('creator-alpha'); + expect(body.data.key.trades.edges[0].node.id).toBe('trade-1'); + }); + + it('resolves trades for a key', async () => { + const query = ` + { + trades(keyId: "${testKeyId}", first: 10) { + edges { node { id keyId buyer quantity } cursor } + } + } + `; + const res = await graphql(query); + + expect(res.body.errors).toBeUndefined(); + expect(res.body.data.trades.edges[0].node.keyId).toBe(testKeyId); + }); + + it('returns null for unknown key', async () => { + mockPrisma.creatorProfile.findUnique.mockResolvedValueOnce(null); + const res = await graphql(` + { + key(id: "unknown") { + id + handle + } + } + `); + + expect(res.body.errors).toBeUndefined(); + expect(res.body.data.key).toBeNull(); + }); + }); + + describe('pagination', () => { + it('keys returns pageInfo and cursor', async () => { + const res = await graphql(` + { + keys(first: 2) { + edges { + node { + id + } + cursor + } + pageInfo { + hasNextPage + } + } + } + `); + + expect(res.body.errors).toBeUndefined(); + expect(res.body.data.keys.edges.length).toBe(1); + expect(res.body.data.keys.pageInfo.hasNextPage).toBe(false); + }); + + it('uses the cursor to fetch the next page', async () => { + const res = await graphql(` + { + keys(first: 1) { + edges { + node { + id + } + cursor + } + pageInfo { + endCursor + } + } + } + `); + const cursor = res.body.data.keys.edges[0].cursor; + + mockPrisma.creatorProfile.findMany.mockResolvedValueOnce([]); + const res2 = await graphql( + `{ keys(first: 1, after: "${cursor}") { edges { node { id } } } }` + ); + + expect(res2.body.errors).toBeUndefined(); + expect(mockPrisma.creatorProfile.findMany).toHaveBeenCalledWith( + expect.objectContaining({ cursor: { id: testKeyId } }) + ); + }); + }); + + describe('max depth', () => { + it('allows queries up to 6 levels deep', async () => { + const query = `{ + key(id: "${testKeyId}") { + holders(first: 10) { + edges { node { walletAddress } } + } + } + }`; + mockPrisma.trade.findMany.mockResolvedValueOnce([]); + const res = await graphql(query); + + expect(res.body.errors).toBeUndefined(); + }); + + it('rejects queries deeper than 6 levels', async () => { + const query = `{ + key(id: "${testKeyId}") { + holders { + edges { node { trades { edges { node { holder { id } } } } } } + } + } + }`; + const res = await graphql(query); + + expect(res.body.errors).toHaveLength(1); + expect(res.body.errors[0].message).toMatch(/maximum depth/); + }); + }); + + describe('max cost', () => { + it('allows queries within the cost limit', async () => { + const res = await graphql(` + { + keys(first: 5) { + edges { + node { + id + } + } + } + } + `); + expect(res.body.errors).toBeUndefined(); + }); + + it('rejects queries over the cost limit', async () => { + // a large `first` pushes estimated cost over 1,000 while staying + // within the depth limit (depth 4), so this is a cost-only rejection. + const query = `{ + keys(first: 2000) { + edges { node { id } } + } + }`; + const res = await graphql(query); + + expect(res.body.errors).toHaveLength(1); + expect(res.body.errors[0].message).toMatch(/cost limit/); + }); + }); + + describe('DataLoader batching', () => { + it('batches holder lookups — one query per request level', async () => { + const query = `{ + key(id: "${testKeyId}") { + holders(first: 10) { + edges { node { walletAddress } } + } + } + }`; + mockPrisma.trade.findMany.mockResolvedValueOnce([]); + + await graphql(query); + + // holdersByKeyLoader runs one trade.findMany for the batched key ids. + expect(mockPrisma.trade.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { creatorId: { in: [testKeyId] } }, + }) + ); + }); + + it('batches trade->key lookups through the creator loader', async () => { + const query = `{ + trades(keyId: "${testKeyId}", first: 10) { + edges { node { key { id handle } } } + } + }`; + await graphql(query); + + // creatorLoader batches creatorProfile lookups by key id. + expect(mockPrisma.creatorProfile.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { id: { in: [testKeyId] } } }) + ); + }); + }); + + describe('mutations', () => { + it('does not expose mutations', async () => { + const res = await graphql(` + mutation { + createKey(input: {}) { + id + } + } + `); + + expect(res.body.errors).toHaveLength(1); + expect(res.body.errors[0].message).toMatch(/mutation operation/); + }); + + it('rejects any mutation root selection', async () => { + const res = await graphql(` + mutation { + keys { + edges { + node { + id + } + } + } + } + `); + + expect(res.body.errors).toHaveLength(1); + expect(res.body.errors[0].message).toMatch(/mutation operation/); + }); + }); +}); diff --git a/src/graphql/loaders.ts b/src/graphql/loaders.ts new file mode 100644 index 00000000..4f6fbc1b --- /dev/null +++ b/src/graphql/loaders.ts @@ -0,0 +1,115 @@ +// src/graphql/loaders.ts +// DataLoaders for the read-only GraphQL endpoint (issue #1248). +// +// DataLoaders batch lookups that happen at the same request level into a +// single database query. E.g. resolving `holders` for several keys in one +// `keys { edges { node { holders { ... } } } }` query issues a single +// `trade.findMany({ creatorId: { in: [...] } })` instead of one query per key. + +import DataLoader from 'dataloader'; +import { Request } from 'express'; +import { prisma } from '../utils/prisma.utils'; + +export interface HolderSummary { + id: string; + walletAddress: string; + totalKeysHeld: number; + totalTrades: number; + totalSpent: string; +} + +export interface GraphQLLoaders { + creatorLoader: DataLoader; + holderLoader: DataLoader; + holdersByKeyLoader: DataLoader; +} + +/** + * GraphQL execution context: the originating HTTP request plus per-request + * DataLoaders. One loader set per request so batch caches never leak across + * requests. + */ +export interface GraphQLContext { + req: Request; + loaders: GraphQLLoaders; +} + +function aggregateHolder(wallet: string, trades: any[]): HolderSummary { + const keysHeld = new Set(trades.map(trade => trade.creatorId)).size; + const totalSpent = trades.reduce( + (sum, trade) => + sum + Number(trade.price ?? 0) * Number(trade.quantity ?? 0), + 0 + ); + + return { + walletAddress: wallet, + id: wallet, + totalKeysHeld: keysHeld, + totalTrades: trades.length, + totalSpent: String(totalSpent || 0), + }; +} + +/** + * Builds per-request DataLoaders. One instance per GraphQL request ensures + * the batch cache does not leak across requests. + */ +export function createLoaders(): GraphQLLoaders { + const creatorLoader = new DataLoader(async ids => { + const keyIds = ids as string[]; + const rows = await prisma.creatorProfile.findMany({ + where: { id: { in: keyIds } }, + }); + const byId = new Map(rows.map(row => [row.id, row])); + return keyIds.map(id => byId.get(id) ?? null); + }); + + const holderLoader = new DataLoader( + async wallets => { + const walletList = wallets as string[]; + const rows = await prisma.trade.findMany({ + where: { buyer: { in: walletList } }, + }); + const byWallet = new Map(); + for (const row of rows) { + const list = byWallet.get(row.buyer) ?? []; + list.push(row); + byWallet.set(row.buyer, list); + } + return walletList.map(wallet => { + const trades = byWallet.get(wallet) ?? []; + return trades.length > 0 ? aggregateHolder(wallet, trades) : null; + }); + } + ); + + const holdersByKeyLoader = new DataLoader( + async keyIds => { + const rows = await prisma.trade.findMany({ + where: { creatorId: { in: keyIds as string[] } }, + }); + const byKey = new Map(); + for (const row of rows) { + const list = byKey.get(row.creatorId) ?? []; + list.push(row); + byKey.set(row.creatorId, list); + } + return keyIds.map(keyId => { + const trades = byKey.get(keyId) ?? []; + if (trades.length === 0) return null; + const byWallet = new Map(); + for (const trade of trades) { + const list = byWallet.get(trade.buyer) ?? []; + list.push(trade); + byWallet.set(trade.buyer, list); + } + return [...byWallet.entries()].map(([wallet, wsTrades]) => + aggregateHolder(wallet, wsTrades) + ); + }); + } + ); + + return { creatorLoader, holderLoader, holdersByKeyLoader }; +} diff --git a/src/graphql/resolvers.ts b/src/graphql/resolvers.ts new file mode 100644 index 00000000..6673c67b --- /dev/null +++ b/src/graphql/resolvers.ts @@ -0,0 +1,331 @@ +// src/graphql/resolvers.ts +// Resolvers for the read-only GraphQL endpoint (issue #1248). +// +// All reads go through Prisma; list queries use cursor-based pagination +// reusing `paginateQuery` from src/utils/pagination.utils. Nested lookups +// (Trade.key, Trade.holder, Key.holders) are served by DataLoaders so a +// single request level performs at most one database query per entity type. + +import { GraphQLScalarType, Kind } from 'graphql'; +import { prisma } from '../utils/prisma.utils'; +import { encodeCursor, decodeCursor } from '../utils/cursor.utils'; +import { paginateQuery } from '../utils/pagination.utils'; +import { type GraphQLContext, type GraphQLLoaders } from './loaders'; + +const DEFAULT_PAGE_SIZE = 20; +const MAX_PAGE_SIZE = 100; + +export const DateTimeScalar = new GraphQLScalarType({ + name: 'DateTime', + description: 'ISO-8601 datetime value', + serialize(value: unknown) { + if (value instanceof Date) return value.toISOString(); + return String(value); + }, + parseValue(value: unknown) { + return new Date(String(value)); + }, + parseLiteral(ast) { + if (ast.kind === Kind.STRING) return new Date(ast.value); + return null; + }, +}); + +function parseFirst(first?: number): number { + return Math.min( + Math.max(Math.floor(first ?? DEFAULT_PAGE_SIZE), 1), + MAX_PAGE_SIZE + ); +} + +async function decodeAfter(after?: string): Promise<{ id: string } | null> { + if (!after) return null; + try { + return decodeCursor(after); + } catch { + return null; + } +} + +type Edge = { node: T; cursor: string }; + +type ConnectionResult = { + edges: Edge[]; + pageInfo: { + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor: string | null; + endCursor: string | null; + }; + totalCount: number; +}; + +function buildConnection( + items: T[], + total: number, + hasAfter: boolean, + hasMore: boolean, + lastCursorValue: string | null +): ConnectionResult { + const edges: Edge[] = items.map(item => ({ + node: item, + cursor: encodeCursor({ id: (item as any).id }), + })); + + return { + edges, + pageInfo: { + hasNextPage: hasMore, + hasPreviousPage: hasAfter, + startCursor: edges.length > 0 ? edges[0].cursor : null, + endCursor: + lastCursorValue ?? + (edges.length > 0 ? edges[edges.length - 1].cursor : null), + }, + totalCount: total, + }; +} + +/** + * Cursor-paginated list of Prisma rows mapped into GraphQL nodes. + * Reuses the existing `paginateQuery` helper for take/skip/cursor handling. + */ +async function paginateConnection({ + query, + count, + first, + after, + mapNode, +}: { + query: (args: { + take: number; + skip?: number; + cursor?: { id: string }; + }) => Promise; + count: () => Promise; + first?: number; + after?: string; + mapNode: (row: T) => Node; +}): Promise> { + const firstSafe = parseFirst(first); + const cursor = await decodeAfter(after); + const { data, nextCursor, hasMore } = await paginateQuery( + query, + { cursor, limit: firstSafe }, + item => (item as any).id + ); + const total = await count(); + + return buildConnection( + data.map(mapNode), + total, + Boolean(after), + hasMore, + nextCursor ?? null + ); +} + +function mapKey(row: any) { + return { + id: row.id, + handle: row.handle, + displayName: row.displayName, + creatorWallet: row.creatorWallet, + status: row.status, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + }; +} + +function mapTrade(row: any) { + return { + id: row.id, + keyId: row.creatorId, + key: row, + holder: row, + buyer: row.buyer, + quantity: row.quantity, + price: row.price, + paymentAsset: row.paymentAsset, + ledger: row.ledger, + txHash: row.txHash, + timestamp: row.timestamp, + createdAt: row.createdAt, + }; +} + +function mapHolder(summary: HolderSummaryLike) { + return { + id: summary.id, + walletAddress: summary.walletAddress, + totalKeysHeld: summary.totalKeysHeld, + totalTrades: summary.totalTrades, + totalSpent: summary.totalSpent, + }; +} + +type HolderSummaryLike = { + id: string; + walletAddress: string; + totalKeysHeld: number; + totalTrades: number; + totalSpent: string; +}; + +export const resolvers = { + DateTime: DateTimeScalar, + Query: { + key: async (_root: any, { id }: { id: string }) => { + const row = await prisma.creatorProfile.findUnique({ where: { id } }); + return row ? mapKey(row) : null; + }, + keys: async ( + _root: any, + { first, after }: { first?: number; after?: string }, + _context: GraphQLContext + ) => { + return paginateConnection({ + query: args => + prisma.creatorProfile.findMany({ + ...args, + orderBy: { createdAt: 'desc', id: 'desc' }, + }), + count: () => prisma.creatorProfile.count(), + first, + after, + mapNode: mapKey, + }); + }, + trades: async ( + _root: any, + { + keyId, + first, + after, + }: { keyId: string; first?: number; after?: string } + ) => { + return paginateConnection({ + query: args => + prisma.trade.findMany({ + ...args, + where: { creatorId: keyId }, + orderBy: { timestamp: 'desc', ledger: 'desc', id: 'desc' }, + }), + count: () => prisma.trade.count({ where: { creatorId: keyId } }), + first, + after, + mapNode: mapTrade, + }); + }, + }, + Key: { + trades: (parent: any, args: { first?: number; after?: string }) => + paginateConnection({ + query: args => + prisma.trade.findMany({ + ...args, + where: { creatorId: parent.id }, + orderBy: { timestamp: 'desc', ledger: 'desc', id: 'desc' }, + }), + count: () => + prisma.trade.count({ where: { creatorId: parent.id } }), + first: args.first, + after: args.after, + mapNode: mapTrade, + }), + holders: async ( + parent: any, + args: { first?: number; after?: string }, + context: GraphQLContext + ) => { + const summaries = + (await context.loaders.holdersByKeyLoader.load(parent.id)) ?? []; + return holderListConnection(summaries, args); + }, + }, + Holder: { + trades: (parent: any, args: { first?: number; after?: string }) => + paginateConnection({ + query: args => + prisma.trade.findMany({ + ...args, + where: { buyer: parent.walletAddress }, + orderBy: { timestamp: 'desc', ledger: 'desc', id: 'desc' }, + }), + count: () => + prisma.trade.count({ where: { buyer: parent.walletAddress } }), + first: args.first, + after: args.after, + mapNode: mapTrade, + }), + keys: async (parent: any) => { + // Keys held by this wallet: distinct creators from its trades, then the + // key records themselves. Capped at 100 since holder key lists are not + // the primary access path for this endpoint. + const trades = await prisma.trade.findMany({ + where: { buyer: parent.walletAddress }, + select: { creatorId: true }, + take: 100, + orderBy: { creatorId: 'asc' }, + }); + const keyIds = [...new Set(trades.map(trade => trade.creatorId))]; + const rows = await prisma.creatorProfile.findMany({ + where: { id: { in: keyIds } }, + }); + return buildConnection( + rows.map(mapKey), + rows.length, + false, + false, + null + ); + }, + }, + Trade: { + key: (parent: any, _args: any, context: GraphQLContext) => + context.loaders.creatorLoader + .load(parent.keyId) + .then(row => (row ? mapKey(row) : null)), + holder: (parent: any, _args: any, context: GraphQLContext) => + context.loaders.holderLoader + .load(parent.buyer) + .then(summary => (summary ? mapHolder(summary) : null)), + }, +}; + +function holderListConnection( + summaries: HolderSummaryLike[], + args: { first?: number; after?: string } +): ConnectionResult { + const firstSafe = parseFirst(args.first); + const cursor = args.after ? decodeCursorSync(args.after) : null; + const startIndex = cursor + ? summaries.findIndex(s => s.walletAddress === cursor) + 1 + : 0; + const sliceStart = Math.max(startIndex, 0); + const page = summaries.slice(sliceStart, sliceStart + firstSafe + 1); + const hasMore = page.length > firstSafe; + const data = hasMore ? page.slice(0, firstSafe) : page; + + return buildConnection( + data.map(mapHolder), + summaries.length, + Boolean(args.after), + hasMore, + data.length > 0 ? data[data.length - 1].walletAddress : null + ); +} + +function decodeCursorSync(after: string): string | null { + try { + const decoded = decodeCursor(after); + return typeof decoded === 'object' && decoded !== null + ? ((decoded as { id?: string }).id ?? null) + : null; + } catch { + return null; + } +} + +// Make `context` available on the exported resolvers type for consumers. +export type { GraphQLContext, GraphQLLoaders }; diff --git a/src/graphql/router.ts b/src/graphql/router.ts new file mode 100644 index 00000000..e02c5c94 --- /dev/null +++ b/src/graphql/router.ts @@ -0,0 +1,117 @@ +// src/graphql/router.ts +// Express router mounting the read-only GraphQL endpoint at POST /v1/graphql +// (issue #1248). Mounted by src/app.ts under /api/v1, so the full path is +// POST /api/v1/graphql. +// +// graphql-yoga provides the schema factory; execution is driven by the +// graphql.js `graphql()` function. Validation runs explicitly first so we can +// inject custom rules (depth limit, cost limit, introspection gating) and the +// per-request DataLoader context. + +import express, { Request, Response } from 'express'; +import { + graphql, + parse, + validate, + specifiedRules, + ExecutionResult, +} from 'graphql'; +import { createSchema } from 'graphql-yoga'; +import { typeDefs } from './schema'; +import { resolvers } from './resolvers'; +import { createLoaders, type GraphQLContext } from './loaders'; +import { + introspectionRule, + maxDepthLimitRule, + queryCostLimitRule, +} from './validation'; +import { envConfig } from '../config'; + +const schema = createSchema({ typeDefs, resolvers }); + +const MAX_QUERY_DEPTH = 6; +const MAX_QUERY_COST = 1000; + +/** + * Introspection is always enabled outside of production. In production it is + * disabled unless the caller supplies a valid `x-api-key` matching the + * configured internal API key (same convention as internal-auth middleware). + */ +function introspectionEnabled(req: Request): boolean { + const production = + envConfig.MODE === 'production' || process.env.NODE_ENV === 'production'; + if (!production) return true; + + const configuredKey = + envConfig.INTERNAL_SERVICE_KEY || + process.env.INDEXER_API_KEY || + process.env.INTERNAL_API_KEY; + if (!configuredKey) return false; + + const header = req.headers['x-api-key']; + const providedKey = Array.isArray(header) ? header[0] : header; + return Boolean(providedKey) && providedKey === configuredKey; +} + +const router = express.Router(); + +router.post( + '/', + express.json({ limit: envConfig.BODY_SIZE_LIMIT_DEFAULT }), + async (req: Request, res: Response): Promise => { + const body = req.body ?? {}; + const query = body.query; + if (typeof query !== 'string' || !query.trim()) { + res.status(400).json({ + errors: [{ message: 'Missing GraphQL "query" in request body.' }], + }); + return; + } + + let document; + try { + document = parse(query); + } catch (error) { + res.status(400).json({ + errors: [ + { + message: + error instanceof Error + ? error.message + : 'Invalid GraphQL query.', + }, + ], + }); + return; + } + + const context: GraphQLContext = { + req, + loaders: createLoaders(), + }; + + const validationErrors = validate(schema, document, [ + ...specifiedRules, + maxDepthLimitRule(MAX_QUERY_DEPTH), + queryCostLimitRule(MAX_QUERY_COST), + introspectionRule({ enabled: introspectionEnabled(req) }), + ]); + + if (validationErrors.length > 0) { + res.json({ errors: validationErrors }); + return; + } + + const result: ExecutionResult = await graphql({ + schema, + source: query, + variableValues: body.variables, + contextValue: context, + }); + + res.json(result); + } +); + +export { router, type GraphQLContext }; +export default router; diff --git a/src/graphql/schema.ts b/src/graphql/schema.ts new file mode 100644 index 00000000..f28863fb --- /dev/null +++ b/src/graphql/schema.ts @@ -0,0 +1,107 @@ +// src/graphql/schema.ts +// Read-only GraphQL schema exposing keys, holders and trades (issue #1248). +// +// The schema intentionally exposes only a `Query` root type — no mutations +// are defined, so write operations are not reachable through this endpoint. +// +// Cursor connections follow the Relay convention: +// connection { edges: [{ node, cursor }], pageInfo: { hasNextPage, ... } } + +export const typeDefs = ` + scalar DateTime + + """ + A creator key registered on Access Layer. + """ + type Key { + id: ID! + handle: String + displayName: String + creatorWallet: String + status: String + createdAt: DateTime + updatedAt: DateTime + + trades(first: Int, after: String): TradeConnection! + holders(first: Int, after: String): HolderConnection! + } + + """ + A wallet that holds (or has traded) one or more keys. + Holders are derived from trade history; there is no dedicated holders table. + """ + type Holder { + id: ID! + walletAddress: String! + totalKeysHeld: Int! + totalTrades: Int! + totalSpent: String + + trades(first: Int, after: String): TradeConnection! + keys(first: Int, after: String): KeyConnection! + } + + """ + A recorded trade (purchase) of a creator key. + """ + type Trade { + id: ID! + keyId: String! + key: Key + holder: Holder + buyer: String! + quantity: String! + price: String! + paymentAsset: String! + ledger: Int! + txHash: String! + timestamp: DateTime + createdAt: DateTime + } + + type PageInfo { + hasNextPage: Boolean! + hasPreviousPage: Boolean! + startCursor: String + endCursor: String + } + + type KeyEdge { + node: Key! + cursor: String! + } + + type KeyConnection { + edges: [KeyEdge!]! + pageInfo: PageInfo! + totalCount: Int! + } + + type TradeEdge { + node: Trade! + cursor: String! + } + + type TradeConnection { + edges: [TradeEdge!]! + pageInfo: PageInfo! + totalCount: Int! + } + + type HolderEdge { + node: Holder! + cursor: String! + } + + type HolderConnection { + edges: [HolderEdge!]! + pageInfo: PageInfo! + totalCount: Int! + } + + type Query { + key(id: ID!): Key + keys(first: Int, after: String): KeyConnection! + trades(keyId: String!, first: Int, after: String): TradeConnection! + } +`; diff --git a/src/graphql/validation.ts b/src/graphql/validation.ts new file mode 100644 index 00000000..631f2c36 --- /dev/null +++ b/src/graphql/validation.ts @@ -0,0 +1,122 @@ +// src/graphql/validation.ts +// GraphQL validation rules for the read-only GraphQL endpoint (issue #1248). +// +// - maxDepthLimitRule: rejects queries nested deeper than the configured limit. +// - queryCostLimitRule: rejects queries whose estimated field cost exceeds the limit. +// - introspectionRule: disables introspection in production unless an API key is supplied. + +import { GraphQLError, Kind, ValidationContext, type ASTNode } from 'graphql'; + +export const MAX_QUERY_DEPTH = 6; +export const MAX_QUERY_COST = 1000; + +/** + * Rejects queries whose selection-set nesting exceeds `maxDepth`. + * Root-level fields are depth 1; each nested object selection adds one level. + */ +export function maxDepthLimitRule(maxDepth: number = MAX_QUERY_DEPTH) { + return (context: ValidationContext) => { + let depth = 0; + let maxReached = 0; + + return { + SelectionSet: { + enter: () => { + depth += 1; + maxReached = Math.max(maxReached, depth); + }, + leave: () => { + depth -= 1; + }, + }, + Document: { + leave: (node: ASTNode) => { + if (node.kind === 'Document' && maxReached > maxDepth) { + context.reportError( + new GraphQLError( + `Query exceeds maximum depth of ${maxDepth} (reached ${maxReached}).`, + { nodes: [node] } + ) + ); + } + }, + }, + }; + }; +} + +/** + * Rejects queries whose estimated execution cost exceeds `maxCost`. + * + * Cost model: + * - every requested field costs 1 point; + * - each `first:N` argument adds `N` points (the cost of materialising N + * items), uncapped so excessively large pages are rejected outright. + * - the total is the sum over every field in the document plus all `first` + * arguments. + */ +export function queryCostLimitRule(maxCost: number = MAX_QUERY_COST) { + return (context: ValidationContext) => { + let totalCost = 0; + + return { + Field: { + enter: (node: ASTNode) => { + if (node.kind !== 'Field') return; + totalCost += 1; + + const firstArg = node.arguments?.find( + arg => arg.name.value === 'first' + ); + if (firstArg?.value?.kind === Kind.INT) { + const n = Number(firstArg.value.value); + if (Number.isFinite(n) && n > 0) { + totalCost += n; + } + } + }, + }, + Document: { + leave: (node: ASTNode) => { + if (node.kind === 'Document' && totalCost > maxCost) { + context.reportError( + new GraphQLError( + `Query exceeds cost limit of ${maxCost} (estimated cost: ${totalCost}).`, + { nodes: [node] } + ) + ); + } + }, + }, + }; + }; +} + +type IntrospectionOptions = { + enabled: boolean; +}; + +/** + * Blocks introspection fields (`__schema`, `__type`) when `enabled` is false. + */ +export function introspectionRule(options: IntrospectionOptions) { + return (context: ValidationContext) => ({ + Field: { + enter: (node: ASTNode) => { + if ( + node.kind === 'Field' && + (node.name.value === '__schema' || + node.name.value === '__type') && + !options.enabled + ) { + context.reportError( + new GraphQLError( + 'Introspection is disabled in production. Provide a valid x-api-key header to enable it.', + { nodes: [node] } + ) + ); + } + }, + }, + }); +} From e4a01a01956dd9748cb1fe9c4a558d5d717e8861 Mon Sep 17 00:00:00 2001 From: Jubilee_001 Date: Mon, 23 Nov 2026 15:19:15 +0100 Subject: [PATCH 2/2] fix(graphql): mount graphqlRouter in app.ts PR #1258 imported graphqlRouter but never mounted it, causing the 'eslint @typescript-eslint/no-unused-vars' CI failure ('graphqlRouter is defined but never used' at src/app.ts:19). Mount the router under /api/v1/graphql so the read-only GraphQL endpoint is exposed and the import is used. --- src/app.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/app.ts b/src/app.ts index 64c3d490..5c1562c4 100644 --- a/src/app.ts +++ b/src/app.ts @@ -142,6 +142,8 @@ app.use('/v1/rates', ratesRouter); app.use('/api/v1/rates', ratesRouter); app.use('/v1', router); app.use('/api/v1', router); +// Read-only GraphQL endpoint (issue #1248): POST /api/v1/graphql +app.use('/api/v1/graphql', graphqlRouter); app.use('/v1', queryCostGovernor()); app.use('/v1/protocol', routeBodySizeLimit('default'), protocolPolRouter); app.use('/v1/keys', routeBodySizeLimit('default'), keyBackstopsRouter);