@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.
- package/README.md +60 -62
- package/dist/endpoint.d.ts +14 -2
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/executor.d.ts +20 -37
- package/dist/executor.d.ts.map +1 -1
- package/dist/explorer.d.ts +24 -0
- package/dist/explorer.d.ts.map +1 -0
- package/dist/graphql.d.ts +32 -95
- package/dist/graphql.d.ts.map +1 -1
- package/dist/handler.d.ts +7 -34
- package/dist/handler.d.ts.map +1 -1
- package/dist/index.d.ts +3 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +301 -1011
- package/dist/index.js.map +14 -23
- package/dist/once-per-request.d.ts +5 -0
- package/dist/once-per-request.d.ts.map +1 -1
- package/dist/operation.d.ts +2 -7
- package/dist/operation.d.ts.map +1 -1
- package/dist/options.d.ts +38 -0
- package/dist/options.d.ts.map +1 -0
- package/dist/removed.d.ts +14 -0
- package/dist/removed.d.ts.map +1 -0
- package/dist/sandbox.d.ts +3 -17
- package/dist/sandbox.d.ts.map +1 -1
- package/dist/testing/client.d.ts +9 -7
- package/dist/testing/client.d.ts.map +1 -1
- package/dist/testing/index.js +5 -1
- package/dist/testing/index.js.map +3 -3
- package/dist/ws.d.ts +18 -30
- package/dist/ws.d.ts.map +1 -1
- package/docs/README.md +3 -2
- package/docs/guide/context.md +40 -32
- package/docs/guide/endpoint.md +42 -27
- package/docs/guide/executor.md +23 -8
- package/docs/guide/ide.md +27 -64
- package/docs/guide/{yoga.md → plugins.md} +87 -72
- package/docs/guide/production.md +115 -196
- package/docs/guide/testing.md +24 -24
- package/docs/guide/websockets.md +21 -14
- package/docs/migrating-to-graxia.md +283 -0
- package/docs/roadmap.md +7 -11
- package/docs/troubleshooting.md +231 -248
- package/package.json +15 -22
- package/dist/body-refusal.d.ts +0 -25
- package/dist/body-refusal.d.ts.map +0 -1
- package/dist/document-cache.d.ts +0 -39
- package/dist/document-cache.d.ts.map +0 -1
- package/dist/field-rate-limit/count.d.ts +0 -28
- package/dist/field-rate-limit/count.d.ts.map +0 -1
- package/dist/field-rate-limit/from-store.d.ts +0 -21
- package/dist/field-rate-limit/from-store.d.ts.map +0 -1
- package/dist/field-rate-limit/index.d.ts +0 -5
- package/dist/field-rate-limit/index.d.ts.map +0 -1
- package/dist/field-rate-limit/ipv6-network.d.ts +0 -8
- package/dist/field-rate-limit/ipv6-network.d.ts.map +0 -1
- package/dist/field-rate-limit/plugin.d.ts +0 -28
- package/dist/field-rate-limit/plugin.d.ts.map +0 -1
- package/dist/field-rate-limit/types.d.ts +0 -60
- package/dist/field-rate-limit/types.d.ts.map +0 -1
- package/dist/nesting.d.ts +0 -18
- package/dist/nesting.d.ts.map +0 -1
- package/dist/parse-limits.d.ts +0 -50
- package/dist/parse-limits.d.ts.map +0 -1
- package/dist/same-origin/index.d.ts +0 -2
- package/dist/same-origin/index.d.ts.map +0 -1
- package/dist/same-origin/same-origin.d.ts +0 -30
- package/dist/same-origin/same-origin.d.ts.map +0 -1
- package/dist/ws-operations.d.ts +0 -31
- package/dist/ws-operations.d.ts.map +0 -1
- package/dist/ws-server.d.ts +0 -32
- package/dist/ws-server.d.ts.map +0 -1
- package/dist/yoga.d.ts +0 -12
- package/dist/yoga.d.ts.map +0 -1
package/docs/guide/production.md
CHANGED
|
@@ -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
|
|
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
|
-
|
|
136
|
-
than `
|
|
137
|
-
(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
|
156
|
-
development,
|
|
157
|
-
|
|
158
|
-
|
|
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.
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
status
|
|
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):
|
|
197
|
-
return
|
|
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
|
-
|
|
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
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
-
`
|
|
225
|
-
|
|
226
|
-
|
|
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
|
-
- **`
|
|
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
|
-
|
|
235
|
-
|
|
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. `
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
the
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
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
|
-
- **`
|
|
256
|
-
|
|
257
|
-
A
|
|
258
|
-
|
|
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
|
-
|
|
268
|
-
|
|
240
|
+
limits: { tokens: 20_000 },
|
|
241
|
+
caches: { parse: { max: 256 } },
|
|
269
242
|
});
|
|
270
243
|
```
|
|
271
244
|
|
|
272
245
|
### The body
|
|
273
246
|
|
|
274
|
-
|
|
275
|
-
JSON costs
|
|
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
|
|
280
|
-
and the option wins over it. A query is a few kilobytes, so for an
|
|
281
|
-
takes no uploads, 100 KiB is generous. A mutation that takes a file
|
|
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.**
|
|
286
|
-
body
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
`
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
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
|
-
|
|
316
|
-
|
|
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
|
-
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
-
|
|
333
|
-
|
|
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
|
-
|
|
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`
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
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.
|
|
394
|
-
|
|
395
|
-
|
|
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 {
|
|
400
|
-
import
|
|
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
|
-
|
|
404
|
-
|
|
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
|
-
`
|
|
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 {
|
|
427
|
-
import {
|
|
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
|
-
|
|
444
|
-
|
|
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
|
|
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)).
|
package/docs/guide/testing.md
CHANGED
|
@@ -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,
|
|
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
|
|
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) =>
|
|
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
|
|
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
|
|
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
|
-
|
|
122
|
-
|
|
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
|
|
136
|
-
|
|
137
|
-
`PersistedQueryNotFound
|
|
138
|
-
document sent to an app
|
|
139
|
-
`
|
|
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
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
-
|
|
163
|
-
|
|
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
|