@alxia/graphql 0.16.5 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +60 -62
  2. package/dist/endpoint.d.ts +14 -2
  3. package/dist/endpoint.d.ts.map +1 -1
  4. package/dist/executor.d.ts +20 -37
  5. package/dist/executor.d.ts.map +1 -1
  6. package/dist/explorer.d.ts +24 -0
  7. package/dist/explorer.d.ts.map +1 -0
  8. package/dist/graphql.d.ts +32 -95
  9. package/dist/graphql.d.ts.map +1 -1
  10. package/dist/handler.d.ts +7 -34
  11. package/dist/handler.d.ts.map +1 -1
  12. package/dist/index.d.ts +3 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +301 -1011
  15. package/dist/index.js.map +14 -23
  16. package/dist/once-per-request.d.ts +5 -0
  17. package/dist/once-per-request.d.ts.map +1 -1
  18. package/dist/operation.d.ts +2 -7
  19. package/dist/operation.d.ts.map +1 -1
  20. package/dist/options.d.ts +38 -0
  21. package/dist/options.d.ts.map +1 -0
  22. package/dist/removed.d.ts +14 -0
  23. package/dist/removed.d.ts.map +1 -0
  24. package/dist/sandbox.d.ts +3 -17
  25. package/dist/sandbox.d.ts.map +1 -1
  26. package/dist/testing/client.d.ts +9 -7
  27. package/dist/testing/client.d.ts.map +1 -1
  28. package/dist/testing/index.js +5 -1
  29. package/dist/testing/index.js.map +3 -3
  30. package/dist/ws.d.ts +18 -30
  31. package/dist/ws.d.ts.map +1 -1
  32. package/docs/README.md +3 -2
  33. package/docs/guide/context.md +40 -32
  34. package/docs/guide/endpoint.md +42 -27
  35. package/docs/guide/executor.md +23 -8
  36. package/docs/guide/ide.md +27 -64
  37. package/docs/guide/{yoga.md → plugins.md} +87 -72
  38. package/docs/guide/production.md +115 -196
  39. package/docs/guide/testing.md +24 -24
  40. package/docs/guide/websockets.md +21 -14
  41. package/docs/migrating-to-graxia.md +283 -0
  42. package/docs/roadmap.md +7 -11
  43. package/docs/troubleshooting.md +231 -248
  44. package/package.json +15 -22
  45. package/dist/body-refusal.d.ts +0 -25
  46. package/dist/body-refusal.d.ts.map +0 -1
  47. package/dist/document-cache.d.ts +0 -39
  48. package/dist/document-cache.d.ts.map +0 -1
  49. package/dist/field-rate-limit/count.d.ts +0 -28
  50. package/dist/field-rate-limit/count.d.ts.map +0 -1
  51. package/dist/field-rate-limit/from-store.d.ts +0 -21
  52. package/dist/field-rate-limit/from-store.d.ts.map +0 -1
  53. package/dist/field-rate-limit/index.d.ts +0 -5
  54. package/dist/field-rate-limit/index.d.ts.map +0 -1
  55. package/dist/field-rate-limit/ipv6-network.d.ts +0 -8
  56. package/dist/field-rate-limit/ipv6-network.d.ts.map +0 -1
  57. package/dist/field-rate-limit/plugin.d.ts +0 -28
  58. package/dist/field-rate-limit/plugin.d.ts.map +0 -1
  59. package/dist/field-rate-limit/types.d.ts +0 -60
  60. package/dist/field-rate-limit/types.d.ts.map +0 -1
  61. package/dist/nesting.d.ts +0 -18
  62. package/dist/nesting.d.ts.map +0 -1
  63. package/dist/parse-limits.d.ts +0 -50
  64. package/dist/parse-limits.d.ts.map +0 -1
  65. package/dist/same-origin/index.d.ts +0 -2
  66. package/dist/same-origin/index.d.ts.map +0 -1
  67. package/dist/same-origin/same-origin.d.ts +0 -30
  68. package/dist/same-origin/same-origin.d.ts.map +0 -1
  69. package/dist/ws-operations.d.ts +0 -31
  70. package/dist/ws-operations.d.ts.map +0 -1
  71. package/dist/ws-server.d.ts +0 -32
  72. package/dist/ws-server.d.ts.map +0 -1
  73. package/dist/yoga.d.ts +0 -12
  74. package/dist/yoga.d.ts.map +0 -1
@@ -8,7 +8,7 @@ attacker. Seven points, each a few lines, from the
8
8
  whose files they are (`src/context.ts` holds the base, which each app builds on with `base.fork()`). Add the packages the snippets use:
9
9
 
10
10
  ```sh
11
- bun add @alxia/rate-limit @envelop/depth-limit @graphql-yoga/plugin-csrf-prevention @graphql-yoga/plugin-persisted-operations
11
+ bun add @alxia/rate-limit
12
12
  ```
13
13
 
14
14
  ## Rate limit the endpoint
@@ -132,60 +132,47 @@ What to know when you pick a limit:
132
132
 
133
133
  ## Limit depth and complexity
134
134
 
135
- `useDepthLimit` from `@envelop/depth-limit` refuses a document nested deeper
136
- than `maxDepth` before it executes
137
- ([Yoga's plugins](yoga.md#plugins) shows
138
- it beside the others). Depth is one dimension: aliases, list sizes and
139
- fragments multiply the work at a depth that is allowed, so give every list
140
- argument a maximum in the schema, and add a cost plugin when a client
141
- may write its own documents.
135
+ graxia refuses a document before it executes when it nests deeper than
136
+ `limits.depth` (12 by default), uses more than `limits.aliases` aliases (30),
137
+ `limits.directives` directives (50) or `limits.rootFields` root fields (20), or
138
+ costs more than `limits.cost.max` (5 000). All are on by default; size them
139
+ from your own clients' largest legitimate operation. Depth is one dimension:
140
+ aliases, list sizes and fragments multiply the work at a depth that is
141
+ allowed, so give every list argument a maximum in the schema.
142
142
 
143
143
  ```ts
144
144
  // file: src/depth.ts
145
- import { useDepthLimit } from '@envelop/depth-limit';
146
-
147
- // A document nested deeper than `maxDepth` is refused at validation, before
148
- // a resolver runs: a 200 with `errors`, GraphQL's own format.
149
- export const depthLimit = (maxDepth: number) => useDepthLimit({ maxDepth });
145
+ // A document past a limit is refused at validation, before a resolver runs:
146
+ // a 400 whose error carries `extensions.limit` and `extensions.fix`.
147
+ export const operationLimits = { depth: 8, aliases: 10, rootFields: 10 };
150
148
  ```
151
149
 
152
- ## Introspection off in production
150
+ ## Introspection and suggestions off in production
153
151
 
154
152
  Introspection hands anyone the whole schema, the fields you meant to keep
155
- quiet included. GraphiQL needs it, so it follows the same switch: on in
156
- development, off everywhere else. `isDev(context)` is the `ide`'s own test
157
- (`alxia({ dev })`, else `NODE_ENV=development`), and the plugin adds
158
- graphql-js's rule that refuses `__schema` and `__type` otherwise.
159
-
160
- ```ts
161
- // file: src/introspection.ts
162
- import { isDev } from '@alxia/core';
163
- import { NoSchemaIntrospectionCustomRule } from 'graphql';
164
- import type { Plugin } from 'graphql-yoga';
165
-
166
- export const introspectionOnlyInDev: Plugin = {
167
- onValidate({ addValidationRule, context }) {
168
- if (!isDev(context)) addValidationRule(NoSchemaIntrospectionCustomRule);
169
- },
170
- };
171
- ```
153
+ quiet included, and "Did you mean…" hints leak field names from a typo. Both
154
+ are on for development, where GraphiQL needs them, and off when
155
+ `NODE_ENV=production`. Say so in the app, so it holds whatever the
156
+ environment says: `introspection: false` and `suggestions: false` on
157
+ `graphql()`.
172
158
 
173
159
  This hides the schema from a client that asks, not from one that guesses
174
- field names: it is not authorisation. Yoga's error suggestions ("Did you
175
- mean…") also leak names; the plugin `@escape.tech/graphql-armor-block-field-suggestions`
176
- removes them.
160
+ field names: it is not authorisation.
177
161
 
178
162
  ## Masked errors
179
163
 
180
- Yoga masks errors by default (`maskedErrors: true`): an `Error` a resolver
181
- throws reaches the client as `Unexpected error.`, with its message and stack
182
- kept on the server. Leave it on. To tell the client something, throw a
183
- `GraphQLError`, whose message is shown, with an `extensions.code` the client
184
- can switch on; `extensions.http.status` puts the same refusal on the HTTP
185
- status too (the [layers of an auth error](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#auth-errors-in-three-layers)).
164
+ graxia always masks errors: an `Error` a resolver throws reaches the client
165
+ as `Unexpected error.` with a correlation id (`extensions.reference`), and the
166
+ original goes to `onUnexpected` on the server. Leave it so. To tell the client
167
+ something, throw `exposedError(code, message)` from `@graxia/core`, or a
168
+ `GraphQLError` (shown as it is, so never put a secret in its message), with an
169
+ `extensions.code` the client can switch on. A status for the refusal is not
170
+ read from an `http.status` extension: graxia answers by its own rules (the
171
+ [layers of an auth error](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#auth-errors-in-three-layers)).
186
172
 
187
173
  ```ts
188
174
  // file: src/errors.ts
175
+ import { exposedError } from '@graxia/core';
189
176
  import { GraphQLError } from 'graphql';
190
177
 
191
178
  // What a client may read: a stable `code`, and a message meant for people.
@@ -193,14 +180,14 @@ export function invalid(message: string, field: string): GraphQLError {
193
180
  return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT', field } });
194
181
  }
195
182
 
196
- export function notFound(what: string): GraphQLError {
197
- return new GraphQLError(`No ${what}`, { extensions: { code: 'NOT_FOUND', http: { status: 404 } } });
183
+ export function notFound(what: string): Error {
184
+ return exposedError('NOT_FOUND', `No ${what}`);
198
185
  }
199
186
  ```
200
187
 
201
188
  ## Cap what a request costs
202
189
 
203
- Yoga parses a document before any resolver guard runs, and a parsed
190
+ graxia parses a document before any resolver guard runs, and a parsed
204
191
  document stays in a cache. Both are bounded by default, by the document's
205
192
  **tokens**: the words, names and punctuation the parser reads. Measured on
206
193
  graphql 16 and 17, a parsed token costs between 178 and 509 bytes of heap
@@ -210,110 +197,85 @@ count of tokens is the weight, and 512 bytes per token the upper estimate: a
210
197
  document of 15 000 tokens parses to 7.7 MB at most (15 000 × 512 B); a
211
198
  measured heavy document of about 12 000 tokens weighs about 6 MB.
212
199
 
213
- The cache weighs a document as its tokens (comments included) × 512 B, plus
214
- 4 B per source character, plus 32 B per source character of string literals
215
- with escapes (`\n`, `\u00e9`), whose value graphql 16 builds as a rope; or
216
- 36 B per character in all when the document has no locations (`noLocation`),
217
- since nothing then tells where the strings are. A location-less document of
218
- 1 MB weighs over 8 MiB and is not cached. The weight is an estimate by
219
- design, not an exact measure.
220
-
221
- Yoga's validation results for a cached document (up to about 100 errors
222
- each) sit outside the weight, bounded at roughly 70 KB per document.
200
+ The parse cache counts entries and age, not bytes: it keeps up to
201
+ `caches.parse.max` documents (1 024) for `ttlMs` (one hour). A few thousand
202
+ distinct large documents can therefore hold a lot of memory; lower `max`, or
203
+ send variables so documents repeat.
223
204
 
224
- `maxTokens` does not count comments, yet a
225
- parsed document keeps all of them alive: a 750 KB body of `#` lines holds
226
- about 19.6 MB (one `#` per line, `#\n`: each comment becomes a token the
227
- document keeps), so it weighs more than the cache keeps and is parsed again
228
- each time instead of cached.
205
+ `limits.tokens` does not count comments, yet a parsed document keeps all of
206
+ them alive: a 750 KB body of `#` lines holds about 19.6 MB, which the body
207
+ limit, not the token limit, bounds.
229
208
 
230
- - **`maxTokens`, 15 000 by default** (Apollo Router's own limit). The
209
+ - **`limits.tokens`, 15 000 by default** (Apollo Router's own limit; the
210
+ deprecated `maxTokens` still maps to it). The
231
211
  introspection query is 163 tokens and a large screen query with its
232
212
  fragments a few thousand, so a client written for a federated graph passes.
233
- A longer one is
234
- refused before it runs, as any document the parser cannot read is:
235
- `GRAPHQL_PARSE_FAILED`, `Syntax Error: Document contains more than 15000
236
- tokens. Parsing aborted.` (graphql 16 words it `more that`), HTTP 400 under
213
+ A longer one is refused before it runs, as any document the parser cannot
214
+ read is: `GRAPHQL_PARSE_FAILED`, `Syntax Error: Document contains more than
215
+ 15000 tokens. Parsing aborted.`, HTTP 400 under
237
216
  `application/graphql-response+json` and 200 under `application/json`,
238
217
  never logged. It applies to `POST`, `GET`, each operation of a batch and
239
- each operation over WebSocket. `maxTokens: false` turns it off; a plugin of
240
- yours that sets its own parse function replaces it.
241
- - **`maxNesting`, 1 000 by default.** graphql-js parses by recursion, so a
242
- document nested a few thousand levels deep (`{ a { a { …`, `[[[…`) overflows
243
- the stack while it is still well under `maxTokens`, and would answer a 500
244
- `Unexpected error.` and log it. alxia scans the source for the nesting of
245
- `{`, `(` and `[` first, linearly and ignoring strings, block strings and
246
- comments, and refuses a deeper document as `GRAPHQL_PARSE_FAILED`,
247
- `Syntax Error: Document is nested more than 1000 levels deep. Parsing
248
- aborted.`, with the same status and no log as `maxTokens`. A document that
249
- overflows the stack anyway (`maxNesting: false`, or a limit raised too far)
250
- is refused as `Syntax Error: Document is nested too deeply to parse.`
251
- `maxNesting: false` turns the scan off; a real query nests a dozen levels.
252
- It counts `{`, `(` and `[` together, arguments and lists included, so it
253
- is not a selection-depth rule; use a validation rule for that
218
+ each operation over WebSocket. `limits: { tokens: false }` turns it off.
219
+ - **`limits.nesting`, 1 000 by default** (the deprecated `maxNesting`). graphql-js
220
+ parses by recursion, so a document nested a few thousand levels deep
221
+ (`{ a { a { …`, `[[[…`) overflows the stack while it is still well under
222
+ the token limit. graxia scans the source for the nesting of `{`, `(` and `[`
223
+ first, linearly and ignoring strings, block strings and comments, and
224
+ refuses a deeper document as `GRAPHQL_PARSE_FAILED`, `Syntax Error:
225
+ Document is nested more than 1000 levels deep. Parsing aborted.`, with the
226
+ same status and no log as the token limit. A document that overflows the
227
+ stack anyway (nesting `false`, or a limit raised too far) is refused as
228
+ `Syntax Error: Document is nested too deeply to parse.` A real query nests a
229
+ dozen levels. It counts `{`, `(` and `[` together, arguments and lists
230
+ included, so it is not a selection-depth rule; use `limits.depth` for that
254
231
  ([Limit depth and complexity](#limit-depth-and-complexity)).
255
- - **`parseCache`**, a least-recently-used cache per endpoint, weighed in
256
- bytes: `maxBytes` (64 MiB), `max` documents (1 024) and `ttl` (one hour).
257
- A document heavier than an eighth of `maxBytes` is not kept and is parsed
258
- again each time. Yoga's own cache holds up to 1 024 documents whatever their
259
- size, which is gigabytes for distinct large queries. `parseCache: false`
260
- keeps nothing. An app with its own cache store gives Yoga's
261
- `parserAndValidationCache`, which replaces this one, and must bound it
262
- too; giving both throws where `graphql()` is declared.
232
+ - **`caches.parse`**, a least-recently-used cache per endpoint: `max`
233
+ documents (1 024) and `ttlMs` (one hour). `caches: false` keeps nothing.
234
+ A bad value of these options is not rejected where `graphql()` is declared
235
+ (only `bodyLimit` is); check them in review.
263
236
 
264
237
  ```ts
265
238
  graphql(app, {
266
239
  schema,
267
- maxTokens: 20_000,
268
- parseCache: { maxBytes: 32 * 1024 * 1024 },
240
+ limits: { tokens: 20_000 },
241
+ caches: { parse: { max: 256 } },
269
242
  });
270
243
  ```
271
244
 
272
245
  ### The body
273
246
 
274
- Yoga reads the whole body of a `POST` before it parses it, so a megabyte of
275
- JSON costs a megabyte of memory. The `POST` route has a body limit, counted
276
- as the bytes arrive:
247
+ graxia reads the body of a `POST` as a stream and counts it, so a megabyte of
248
+ JSON never costs more than the limit. The limit is graxia's `limits.bodyBytes`:
277
249
 
278
250
  - **`bodyLimit`, 1 MiB by default.** Give the option to `graphql()`, or
279
- declare core's `bodyLimit(bytes)` before it: that limit is kept as it is,
280
- and the option wins over it. A query is a few kilobytes, so for an API that
281
- takes no uploads, 100 KiB is generous. A mutation that takes a file by
282
- `multipart` needs a larger limit, in the option. A plugin app mounted
251
+ declare core's `bodyLimit(bytes)` before it: that limit is the one graxia
252
+ enforces, and the option wins over it. A query is a few kilobytes, so for an
253
+ API that takes no uploads, 100 KiB is generous. A mutation that takes a file
254
+ by `multipart` needs a larger limit, in the option. A plugin app mounted
283
255
  under a prefix keeps the limit of its own scope; the outer app's
284
256
  `bodyLimit()` does not reach it.
285
- - **The 413.** Yoga would report a body it could not read as `400`, `POST
286
- body sent invalid JSON.`; `@alxia/graphql` throws core's
287
- `ContentTooLargeError` again instead, so a client gets the 413 a plain
288
- route answers, in the app's error format (`application/problem+json` under
289
- `errors: 'problem'`), with a `Content-Length` or without one (a chunked
290
- body). A declared `Content-Length` over the limit is refused by core
291
- where `bodyLimit()` stands, before Yoga runs: that 413 carries no header
292
- Yoga's plugins set. A chunked body is refused at the read, by the
293
- endpoint, and that 413 carries the headers Yoga's plugins set, such as a
294
- `Cache-Control: no-store` from an `onResponse` hook. Headers merge by
295
- name: `Vary` is merged with the app's own, `Set-Cookie` is appended, and any
296
- other header Yoga sets overwrites the app's header of the same name (Yoga's
297
- `Content-Type`, `Content-Length`, `Content-Encoding` and `Transfer-Encoding`
298
- are never carried). A form-urlencoded or
299
- `application/graphql` body past the limit is refused the same way and logs
300
- nothing. Whatever else Yoga cannot parse is still its 400, and its
301
- parser's own error is never sent (`extensions.originalError` is removed).
302
- - **Order.** A declared `Content-Length` over the limit is refused where
303
- `bodyLimit()` stands: the middlewares declared before it run, the ones
304
- after it do not. When the endpoint's own `bodyLimit` option sets the limit,
305
- the check stands at the head of the endpoint's steps, after every
306
- middleware declared before it. A chunked body is read by the endpoint, after
307
- every middleware, `bodyLimit()` included. Declare the cheap observers
308
- first and the costly middlewares (a session lookup, a database call) as
309
- late as you can. A refusal answered before Yoga runs cannot carry Yoga's
310
- headers: set the ones every response needs in a middleware.
257
+ - **The 413.** A body past the limit, with a `Content-Length` or without one
258
+ (a chunked body), is `413` with `extensions.code: 'BODY_TOO_LARGE'`, in
259
+ graxia's JSON format whatever the app's `errors` option says, and with the
260
+ headers the plugins set. Match the code, never the message.
261
+ - **Other refusals.** A `Content-Type` that is not JSON is `415
262
+ UNSUPPORTED_MEDIA_TYPE` (a form or `application/graphql` body too, whatever
263
+ its size), a body that is not JSON is `400 BODY_NOT_JSON`, one that cannot be
264
+ read is `400 BODY_UNREADABLE`, and the parser's own error is never sent. The
265
+ whole list is graxia's [refusal codes](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/http.md#refusal-codes);
266
+ the type of a code is `GraxiaErrorCode`, re-exported by `@alxia/graphql`.
267
+ Under `Accept: application/json` (the default) a 400 refusal is a `200`; `413`, `415`, `404`, `405` and `406` never change.
268
+ - **No double counting.** Core's own counter never runs on the endpoint's
269
+ `POST` (it would turn a chunked body past the limit into an unreadable
270
+ `400`), so the middlewares declared after `bodyLimit()` run for an oversized
271
+ body before graxia refuses it: declare the costly ones (a session lookup, a
272
+ database call) after the cheap guards, or let a gateway cap the size.
311
273
 
312
274
  ```ts
313
275
  graphql(app, {
314
276
  schema,
315
- maxTokens: 20_000,
316
- parseCache: { maxBytes: 32 * 1024 * 1024 },
277
+ limits: { tokens: 20_000 },
278
+ caches: { parse: { max: 512 } },
317
279
  bodyLimit: 100 * 1024,
318
280
  });
319
281
  ```
@@ -325,22 +287,18 @@ A bearer token in a header cannot be sent by another site's form. A
325
287
  cookie to `/graphql`. `SameSite=Lax` on the cookie is the first line (a
326
288
  cross-site `POST` does not carry it); two more close the rest.
327
289
 
328
- - Yoga's CSRF prevention plugin refuses a request without a custom header
329
- (`x-graphql-yoga-csrf` by default): a browser cannot add one to a request
330
- across origins without a CORS preflight, which `@alxia/cors` answers only
331
- for the origins you named.
332
- - Require `application/json` on a `POST`, which an HTML form cannot send. Yoga
333
- also accepts a form-encoded `POST` and a `GET` query, the two a form or a
334
- link can make, so this is a middleware before the endpoint.
290
+ - Graxia's CSRF prevention (on by default, below) refuses a request without a
291
+ custom header: a browser cannot add one to a request across origins without
292
+ a CORS preflight, which `@alxia/cors` answers only for the origins you named.
293
+ - Require `application/json` on a `POST`, which an HTML form cannot send. A
294
+ form-encoded `POST` and a `GET` query are the two a form or a link can make,
295
+ so this is a middleware before the endpoint.
335
296
 
336
297
  ```ts
337
298
  // file: src/csrf.ts
338
299
  import { defineMiddleware, HttpError } from '@alxia/core';
339
- import { useCSRFPrevention } from '@graphql-yoga/plugin-csrf-prevention';
340
300
 
341
- export const csrf = useCSRFPrevention({ requestHeaders: ['x-csrf'] });
342
-
343
- // A POST that is not JSON is refused with a 415 before Yoga reads it.
301
+ // A POST that is not JSON is refused with a 415 before graxia reads it.
344
302
  export const jsonOnly = defineMiddleware(async ({ request }, next) => {
345
303
  if (request.method === 'POST' && !request.headers.get('content-type')?.startsWith('application/json')) {
346
304
  throw new HttpError(415, { error: 'unsupported_media_type' });
@@ -349,73 +307,35 @@ export const jsonOnly = defineMiddleware(async ({ request }, next) => {
349
307
  });
350
308
  ```
351
309
 
352
- `@alxia/graphql` ships the origin check as a Yoga plugin, `sameOrigin`. It
353
- answers 403 `FORBIDDEN` (no CORS header, `cache-control: no-store`) before
354
- anything is parsed when the request has an `Origin` that is not the
355
- endpoint's own host (`Origin: null` included), or when a `POST` is not
356
- `application/json`. A request with no `Origin`, which is not a browser, passes.
357
- List it first:
358
-
359
- ```ts
360
- import { alxia } from '@alxia/core';
361
- import { graphql, sameOrigin } from '@alxia/graphql';
362
- import { createSchema } from 'graphql-yoga';
363
-
364
- const schema = createSchema({
365
- typeDefs: 'type Query { ping: String }',
366
- resolvers: { Query: { ping: () => 'pong' } },
367
- });
368
-
369
- graphql(alxia(), {
370
- schema,
371
- plugins: [
372
- sameOrigin({
373
- // Behind a proxy that rewrites the host, or a trusted sibling:
374
- allow: ['https://app.example.com'],
375
- // json: false lets form-encoded POSTs through; refuse: (request) => Response
376
- // chooses the answer.
377
- }),
378
- ],
379
- });
380
- ```
381
-
382
- It compares hosts, not origins, because behind a TLS-terminating proxy
383
- `request.url` may say `http` while the browser's `Origin` says `https`. Use it
384
- beside `SameSite` on the cookie. For a `POST` it replaces the `jsonOnly`
385
- middleware above (a 403 instead of a 415). A request with no `Origin`, such as
386
- a cross-site `GET` navigation, passes, which the custom header would block. An
387
- origin served by Yoga's `cors` option must also be listed in `allow`, or its
388
- preflight is refused.
310
+ `@alxia/graphql` runs on graxia, whose `csrf` option is on by default: a
311
+ `GET`, or a `POST` that is not JSON, needs one of the headers
312
+ `x-graphql-csrf`, `graphql-require-preflight`, `apollo-require-preflight` or
313
+ `x-apollo-operation-name`, and a WebSocket upgrade from another origin is
314
+ refused. Answer 403 `CSRF_HEADER_REQUIRED` otherwise. Tune it with
315
+ `csrf: { sameOrigin: true }` adds an origin check for a cookie session (off by default), and `csrf: false` turns it all off. Use it beside `SameSite` on
316
+ the cookie.
389
317
 
390
318
  ## Persisted operations, briefly
391
319
 
392
320
  A client that sends only the hash of an operation it registered at build
393
- time cannot send any other: the strongest limit on what it can ask. Yoga's
394
- [persisted operations plugin](https://the-guild.dev/graphql/yoga-server/docs/features/persisted-operations)
395
- works as it does elsewhere, since it is a Yoga plugin in the route:
321
+ time cannot send any other: the strongest limit on what it can ask. Graxia's
322
+ `trustedDocuments` takes the manifest, and its `strict` mode refuses any
323
+ document that was not registered:
396
324
 
397
- ```ts
325
+ ```ts no-check
398
326
  // file: src/persisted.ts
399
- import { usePersistedOperations } from '@graphql-yoga/plugin-persisted-operations';
400
- import type { Plugin } from 'graphql-yoga';
327
+ import { alxia } from '@alxia/core';
328
+ import { graphql } from '@alxia/graphql';
401
329
 
402
330
  // Hash to document: from a file the build wrote, here a literal.
403
- export const operations = new Map([
404
- ['5f1bb2a0c2a0', '{ notes { text } }'],
405
- ]);
406
-
407
- // `allowArbitraryOperations: false` refuses any document that was not
408
- // registered, the point of it. Apollo's `extensions.persistedQuery.sha256Hash`
409
- // names the operation.
410
- export const persisted: Plugin = usePersistedOperations({
411
- allowArbitraryOperations: false,
412
- getPersistedOperation: (hash) => operations.get(hash) ?? null,
413
- });
331
+ const manifest = { '5f1bb2a0c2a0': '{ notes { text } }' };
332
+
333
+ graphql(alxia(), { schema, trustedDocuments: { manifest, mode: 'strict' } });
414
334
  ```
415
335
 
416
336
  ## Together
417
337
 
418
- `maxTokens`, `maxNesting` and `parseCache` need no line here: their defaults apply. The
338
+ `limits` and `caches` need no line here: their defaults apply. The
419
339
  `bodyLimit()` below is the app's own and is kept; without it the `POST` takes
420
340
  1 MiB.
421
341
 
@@ -423,9 +343,8 @@ export const persisted: Plugin = usePersistedOperations({
423
343
  // file: src/production.ts
424
344
  import { logger } from '@alxia/logger';
425
345
  import { base } from './context';
426
- import { csrf, jsonOnly } from './csrf';
427
- import { depthLimit } from './depth';
428
- import { introspectionOnlyInDev } from './introspection';
346
+ import { jsonOnly } from './csrf';
347
+ import { operationLimits } from './depth';
429
348
  import { limitTo } from './limits';
430
349
  import { createLoaders } from './loaders';
431
350
  import { schema } from './schema';
@@ -440,16 +359,16 @@ export const production = base.fork()
440
359
  graphql(app, {
441
360
  schema,
442
361
  context: () => ({ loaders: createLoaders() }),
443
- logging: false,
444
- plugins: [depthLimit(8), introspectionOnlyInDev, csrf],
362
+ limits: operationLimits,
363
+ introspection: false,
364
+ suggestions: false,
445
365
  }),
446
366
  );
447
367
  ```
448
368
 
449
369
  The recipe's spec runs each point against this app and a small schema, in
450
370
  process: the 429 for a viewer and for an address (a batch of three counts
451
- once), a document too deep, introspection refused outside development and
452
- answering in it, a masked `Error` beside a `GraphQLError` with its
371
+ once), a document too deep, introspection refused, a masked `Error` beside a `GraphQLError` with its
453
372
  extensions, the body limit, the CSRF header, the `415`, and a persisted
454
373
  hash running while an arbitrary document is refused
455
374
  ([the recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#7-harden-it-for-production)).
@@ -2,7 +2,7 @@
2
2
 
3
3
  `graphqlClient` sends an operation to an app's GraphQL endpoint in process,
4
4
  through `app.fetch`: no port, no server, and the whole chain in play (the
5
- app's middlewares, its body limit, Yoga's plugins). It is a helper for
5
+ app's middlewares, its body limit, graxia's plugins). It is a helper for
6
6
  specs, so it lives in its own subpath, `@alxia/graphql/testing`: the main
7
7
  entry stays what an app ships, and a production bundle never carries it.
8
8
 
@@ -25,11 +25,11 @@ test('hello', async () => {
25
25
  ## What `app` can be
26
26
 
27
27
  `graphqlClient` calls `app.fetch(request)`, so `app` is an alxia app or anything
28
- with a `fetch(Request)` that answers a `Response`: a Yoga instance, a
28
+ with a `fetch(Request)` that answers a `Response`: a graxia instance (`createGraxia`), a
29
29
  handler of your own, a stub.
30
30
 
31
31
  ```ts
32
- const client = graphqlClient({ fetch: (request) => yoga.fetch(request) });
32
+ const client = graphqlClient({ fetch: (request) => graxia.fetch(request) });
33
33
  ```
34
34
 
35
35
  ## The result
@@ -38,12 +38,12 @@ const client = graphqlClient({ fetch: (request) => yoga.fetch(request) });
38
38
 
39
39
  | field | |
40
40
  | --- | --- |
41
- | `status` | the HTTP status: 200 for a GraphQL answer, errors included; 400 for a request Yoga refuses, 401 or 403 from a guard, 413 over a body limit |
41
+ | `status` | the HTTP status: 200 for a GraphQL answer, errors included; 400 for a request graxia refuses under `application/graphql-response+json` (200 under `application/json`, the client's default), 401 or 403 from a guard or the CSRF check; a 413 over a body limit (`BODY_TOO_LARGE`) and a 415 are the same under either `Accept` |
42
42
  | `data`, `errors` | the JSON body's own, each unset when the body has none |
43
43
  | `response` | the `Response`, its body unread: `headers`, `ok` |
44
44
 
45
45
  A GraphQL error is an entry of `errors`, never a rejection. A body that is
46
- not JSON (a 413, a 404) leaves `data` and `errors` unset: read `status`.
46
+ not JSON (a 404) leaves `data` and `errors` unset: read `status`. A graxia refusal such as a 413 is JSON: read `errors[0].extensions.code`.
47
47
 
48
48
  ## Headers
49
49
 
@@ -118,9 +118,8 @@ A `GET` has no `Content-Type`.
118
118
 
119
119
  `persisted` is the hash of an operation the app registered. It is sent as
120
120
  Apollo's `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape
121
- `@graphql-yoga/plugin-persisted-operations` reads by default. With no
122
- document, only the hash is sent, so an app that allows nothing else
123
- (`allowArbitraryOperations: false`) can be tested; `TData` is yours to name,
121
+ graxia's `trustedDocuments` reads. With no document, only the hash is
122
+ sent, so an app in `strict` mode can be tested; `TData` is yours to name,
124
123
  since nothing types it:
125
124
 
126
125
  ```ts
@@ -132,11 +131,12 @@ const result = await client.query<{ notes: { text: string }[] }>({
132
131
  ```
133
132
 
134
133
  With a document too, both are sent (Apollo's automatic persisted queries
135
- register one that way). An unknown hash is the server's own answer, not a
136
- client error: with the plugin's defaults, `errors[0].message` is
137
- `PersistedQueryNotFound`, with code `PERSISTED_QUERY_NOT_IN_LIST`; a
138
- document sent to an app that allows only persisted ones is
139
- `PersistedQueryOnly`.
134
+ register one that way, when `trustedDocuments.apq` is on). An unknown hash is
135
+ the server's own answer, not a client error: `errors[0].message` is
136
+ `PersistedQueryNotFound` (code `PERSISTED_QUERY_NOT_FOUND`), or
137
+ `PersistedQueryNotSupported` with `apq` off; a document sent to an app in
138
+ `strict` mode is `Only persisted documents are allowed.`
139
+ (`PERSISTED_QUERY_ONLY`).
140
140
 
141
141
  An app that names an operation by an **id** in an extension of its own
142
142
  (a custom `extractPersistedOperationId`) is sent that extension: `extensions`
@@ -148,19 +148,19 @@ await client.query({ extensions: { documentId: 'abc123' } });
148
148
 
149
149
  ## CSRF
150
150
 
151
- The client sends **no CSRF header of its own**: its name belongs to the app
152
- (`x-graphql-yoga-csrf` by default in Yoga's `useCSRFPrevention`, `x-csrf` in
153
- the [recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md)),
154
- and a spec that never sends it could not see the plugin refuse. Put it in the
155
- client's `headers`, as a browser app does in its own client. Yoga's plugin lets
156
- a JSON `POST` through with no header, since a browser needs a preflight for
157
- that content type, but refuses a `GET` (no content type) with a 403
158
- (`Required CSRF header(s) not present`): test that with a `GET` without the
159
- header, and the app's real traffic with it.
151
+ A `GET` carries graxia's CSRF header, `x-graphql-csrf: 1`, by default, so a
152
+ spec passes on an app that keeps `csrf` on (graxia's default). A JSON `POST`
153
+ needs none (a browser preflights that content type) and is sent without.
154
+
155
+ An app that lists its own header (`csrf: { requireHeader: ['x-my-app'] }`)
156
+ names it in `csrfHeader`; `false` sends none, to test the refusal. A header
157
+ you set in `headers` or in a call is kept.
160
158
 
161
159
  ```ts
162
- const production = graphqlClient(app, { headers: { 'x-csrf': '1' } });
163
- expect((await graphqlClient(app).query('{ me { name } }', { method: 'GET' })).status).toBe(403);
160
+ graphqlClient(app); // GET sends x-graphql-csrf
161
+ graphqlClient(app, { csrfHeader: 'x-my-app' });
162
+ const refused = await graphqlClient(app, { csrfHeader: false }).query('{ me { name } }', { method: 'GET' });
163
+ expect(refused.status).toBe(403); // CSRF_HEADER_REQUIRED
164
164
  ```
165
165
 
166
166
  ## Not covered