graphql-http 1.14.0 → 1.16.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 (48) hide show
  1. package/README.md +5 -3
  2. package/lib/audits/index.d.mts +1 -0
  3. package/lib/audits/index.d.ts +1 -0
  4. package/lib/audits/index.js +1 -0
  5. package/lib/audits/index.mjs +1 -0
  6. package/lib/audits/render.d.mts +8 -0
  7. package/lib/audits/render.d.ts +8 -0
  8. package/lib/audits/render.js +134 -0
  9. package/lib/audits/render.mjs +130 -0
  10. package/lib/audits/utils.js +6 -3
  11. package/lib/audits/utils.mjs +6 -3
  12. package/lib/handler.d.mts +3 -3
  13. package/lib/handler.d.ts +3 -3
  14. package/lib/handler.js +3 -3
  15. package/lib/handler.mjs +3 -3
  16. package/lib/use/express.d.mts +9 -3
  17. package/lib/use/express.d.ts +9 -3
  18. package/lib/use/express.js +1 -1
  19. package/lib/use/express.mjs +1 -1
  20. package/lib/use/fastify.d.mts +9 -3
  21. package/lib/use/fastify.d.ts +9 -3
  22. package/lib/use/fastify.js +1 -1
  23. package/lib/use/fastify.mjs +1 -1
  24. package/lib/use/fetch.d.mts +10 -4
  25. package/lib/use/fetch.d.ts +10 -4
  26. package/lib/use/fetch.js +6 -6
  27. package/lib/use/fetch.mjs +6 -6
  28. package/lib/use/http.d.mts +27 -0
  29. package/lib/use/http.d.ts +27 -0
  30. package/lib/use/http.js +72 -0
  31. package/lib/use/http.mjs +68 -0
  32. package/lib/use/http2.d.mts +39 -0
  33. package/lib/use/http2.d.ts +39 -0
  34. package/lib/use/http2.js +90 -0
  35. package/lib/use/http2.mjs +86 -0
  36. package/lib/use/koa.d.mts +9 -3
  37. package/lib/use/koa.d.ts +9 -3
  38. package/lib/use/koa.js +1 -1
  39. package/lib/use/koa.mjs +1 -1
  40. package/lib/use/node.d.mts +14 -4
  41. package/lib/use/node.d.ts +14 -4
  42. package/lib/use/node.js +5 -50
  43. package/lib/use/node.mjs +5 -50
  44. package/package.json +22 -9
  45. package/umd/graphql-http-audits.js +1006 -0
  46. package/umd/graphql-http-audits.min.js +1 -0
  47. package/umd/graphql-http-audits.min.js.gz +0 -0
  48. package/umd/graphql-http.min.js.gz +0 -0
@@ -0,0 +1,1006 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'graphql'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.graphqlHttpAudits = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ /**
8
+ *
9
+ * utils
10
+ *
11
+ */
12
+ /** @private */
13
+ function extendedTypeof(val) {
14
+ if (val === null) {
15
+ return 'null';
16
+ }
17
+ if (Array.isArray(val)) {
18
+ return 'array';
19
+ }
20
+ return typeof val;
21
+ }
22
+
23
+ /**
24
+ *
25
+ * audit/utils
26
+ *
27
+ */
28
+ /**
29
+ * Wrap and prepare an audit for testing.
30
+ *
31
+ * @private
32
+ */
33
+ function audit(id, name, fn) {
34
+ return {
35
+ id,
36
+ name,
37
+ fn: async () => {
38
+ try {
39
+ await fn();
40
+ return {
41
+ id,
42
+ name,
43
+ status: 'ok',
44
+ };
45
+ }
46
+ catch (err) {
47
+ if (!(err instanceof AuditError)) {
48
+ // anything thrown that is not an assertion error is considered fatal
49
+ throw err;
50
+ }
51
+ return {
52
+ id,
53
+ name,
54
+ status: name.startsWith('MUST')
55
+ ? // only failing MUSTs are considered errors
56
+ 'error'
57
+ : // everything else is optional and considered a warning
58
+ 'warn',
59
+ reason: err.reason,
60
+ response: err.response,
61
+ };
62
+ }
63
+ },
64
+ };
65
+ }
66
+ /**
67
+ * Error thrown when an assertion test fails.
68
+ *
69
+ * @private
70
+ */
71
+ class AuditError {
72
+ constructor(response, reason) {
73
+ this.response = response;
74
+ this.reason = reason;
75
+ }
76
+ }
77
+ /**
78
+ * Will throw an AuditError if the assertion on Response fails.
79
+ *
80
+ * All fatal problems will throw an instance of an Error.
81
+ *
82
+ * The name "ressert" is a wordplay combining "response" and "assert".
83
+ *
84
+ * @private
85
+ */
86
+ function ressert(res) {
87
+ return {
88
+ status: {
89
+ toBe(code) {
90
+ if (res.status !== code) {
91
+ throw new AuditError(res, `Response status code is not ${code}`);
92
+ }
93
+ },
94
+ toBeBetween: (min, max) => {
95
+ if (!(min <= res.status && res.status <= max)) {
96
+ throw new AuditError(res, `Response status is not between ${min} and ${max}`);
97
+ }
98
+ },
99
+ },
100
+ header(key) {
101
+ return {
102
+ toContain(part) {
103
+ var _a;
104
+ if (!((_a = res.headers.get(key)) === null || _a === void 0 ? void 0 : _a.includes(part))) {
105
+ throw new AuditError(res, `Response header ${key} does not contain ${part}`);
106
+ }
107
+ },
108
+ notToContain(part) {
109
+ var _a;
110
+ if ((_a = res.headers.get(key)) === null || _a === void 0 ? void 0 : _a.includes(part)) {
111
+ throw new AuditError(res, `Response header ${key} contains ${part}`);
112
+ }
113
+ },
114
+ };
115
+ },
116
+ bodyAsExecutionResult: {
117
+ data: {
118
+ async toBe(val) {
119
+ const clonedRes = res.clone(); // allow the body to be re-read
120
+ const body = await assertBodyAsExecutionResult(res);
121
+ if (body.data !== val) {
122
+ throw new AuditError(clonedRes, `Response body execution result data is not "${val}"`);
123
+ }
124
+ },
125
+ },
126
+ async toHaveProperty(key) {
127
+ const clonedRes = res.clone(); // allow the body to be re-read
128
+ const body = await assertBodyAsExecutionResult(res);
129
+ if (!(key in body)) {
130
+ throw new AuditError(clonedRes, `Response body execution result does not have a property "${key}"`);
131
+ }
132
+ },
133
+ async notToHaveProperty(key) {
134
+ const clonedRes = res.clone(); // allow the body to be re-read
135
+ const body = await assertBodyAsExecutionResult(res);
136
+ if (key in body) {
137
+ throw new AuditError(clonedRes, `Response body execution result has a property "${key}"`);
138
+ }
139
+ },
140
+ },
141
+ };
142
+ }
143
+ /** @private */
144
+ async function assertBodyAsExecutionResult(res) {
145
+ let decoded;
146
+ try {
147
+ const decoder = new TextDecoder('utf-8');
148
+ const buff = await res.arrayBuffer();
149
+ decoded = decoder.decode(buff);
150
+ }
151
+ catch (err) {
152
+ throw new AuditError(res, 'Response body is not UTF-8 encoded');
153
+ }
154
+ let body;
155
+ try {
156
+ body = JSON.parse(decoded);
157
+ }
158
+ catch (err) {
159
+ throw new AuditError(res, 'Response body is not valid JSON');
160
+ }
161
+ return body;
162
+ }
163
+
164
+ /**
165
+ *
166
+ * audit/server
167
+ *
168
+ */
169
+ /**
170
+ * List of server audits required to check GraphQL over HTTP spec conformance.
171
+ *
172
+ * @category Audits
173
+ */
174
+ function serverAudits(opts) {
175
+ const fetchFn = (opts.fetchFn || fetch);
176
+ return [
177
+ // Media Types
178
+ audit(
179
+ // TODO: convert to MUST after watershed
180
+ '22EB', 'SHOULD accept application/graphql-response+json and match the content-type', async () => {
181
+ const res = await fetchFn(await getUrl(opts.url), {
182
+ method: 'POST',
183
+ headers: {
184
+ 'content-type': 'application/json',
185
+ accept: 'application/graphql-response+json',
186
+ },
187
+ body: JSON.stringify({ query: '{ __typename }' }),
188
+ });
189
+ ressert(res).status.toBe(200);
190
+ ressert(res)
191
+ .header('content-type')
192
+ .toContain('application/graphql-response+json');
193
+ }),
194
+ audit('4655', 'MUST accept application/json and match the content-type', async () => {
195
+ const res = await fetchFn(await getUrl(opts.url), {
196
+ method: 'POST',
197
+ headers: {
198
+ 'content-type': 'application/json',
199
+ accept: 'application/json',
200
+ },
201
+ body: JSON.stringify({ query: '{ __typename }' }),
202
+ });
203
+ ressert(res).status.toBe(200);
204
+ ressert(res).header('content-type').toContain('application/json');
205
+ }),
206
+ audit('47DE', 'SHOULD accept */* and use application/json for the content-type', async () => {
207
+ const res = await fetchFn(await getUrl(opts.url), {
208
+ method: 'POST',
209
+ headers: {
210
+ 'content-type': 'application/json',
211
+ accept: '*/*',
212
+ },
213
+ body: JSON.stringify({ query: '{ __typename }' }),
214
+ });
215
+ ressert(res).status.toBe(200);
216
+ ressert(res).header('content-type').toContain('application/json');
217
+ }),
218
+ audit('80D8', 'SHOULD assume application/json content-type when accept is missing', async () => {
219
+ const url = new URL(await getUrl(opts.url));
220
+ url.searchParams.set('query', '{ __typename }');
221
+ const res = await fetchFn(url.toString());
222
+ ressert(res).status.toBe(200);
223
+ ressert(res).header('content-type').toContain('application/json');
224
+ }),
225
+ audit('82A3', 'MUST use utf-8 encoding when responding', async () => {
226
+ const res = await fetchFn(await getUrl(opts.url), {
227
+ method: 'POST',
228
+ headers: {
229
+ 'content-type': 'application/json',
230
+ },
231
+ body: JSON.stringify({ query: '{ __typename }' }),
232
+ });
233
+ ressert(res).status.toBe(200);
234
+ try {
235
+ const decoder = new TextDecoder('utf-8');
236
+ decoder.decode(await res.arrayBuffer());
237
+ }
238
+ catch (_a) {
239
+ throw new AuditError(res, 'Response body is not UTF-8 encoded');
240
+ }
241
+ }),
242
+ audit('BF61', 'MUST accept utf-8 encoded request', async () => {
243
+ const res = await fetchFn(await getUrl(opts.url), {
244
+ method: 'POST',
245
+ headers: {
246
+ 'content-type': 'application/json; charset=utf-8',
247
+ },
248
+ body: JSON.stringify({ query: '{ __typename }' }),
249
+ });
250
+ ressert(res).status.toBe(200);
251
+ }),
252
+ audit('78D5', 'MUST assume utf-8 in request if encoding is unspecified', async () => {
253
+ const res = await fetchFn(await getUrl(opts.url), {
254
+ method: 'POST',
255
+ headers: {
256
+ 'content-type': 'application/json',
257
+ },
258
+ body: JSON.stringify({ query: '{ __typename }' }),
259
+ });
260
+ ressert(res).status.toBe(200);
261
+ }),
262
+ // Request
263
+ audit('2C94', 'MUST accept POST requests', async () => {
264
+ const res = await fetchFn(await getUrl(opts.url), {
265
+ method: 'POST',
266
+ headers: { 'content-type': 'application/json' },
267
+ body: JSON.stringify({ query: '{ __typename }' }),
268
+ });
269
+ ressert(res).status.toBe(200);
270
+ }),
271
+ audit('5A70', 'MAY accept application/x-www-form-urlencoded formatted GET requests', async () => {
272
+ const url = new URL(await getUrl(opts.url));
273
+ url.searchParams.set('query', '{ __typename }');
274
+ const res = await fetchFn(url.toString());
275
+ ressert(res).status.toBe(200);
276
+ }),
277
+ // Request GET
278
+ // TODO: this is a MUST if the server supports GET requests
279
+ audit('9C48', 'MAY NOT allow executing mutations on GET requests', async () => {
280
+ const url = new URL(await getUrl(opts.url));
281
+ url.searchParams.set('query', 'mutation { __typename }');
282
+ const res = await fetchFn(url.toString(), {
283
+ headers: {
284
+ accept: 'application/graphql-response+json',
285
+ },
286
+ });
287
+ ressert(res).status.toBeBetween(400, 499);
288
+ }),
289
+ // Request POST
290
+ audit('9ABE', 'SHOULD respond with 4xx status code if content-type is not supplied on POST requests', async () => {
291
+ const res = await fetchFn(await getUrl(opts.url), {
292
+ method: 'POST',
293
+ });
294
+ ressert(res).status.toBeBetween(400, 499);
295
+ }),
296
+ audit('03D4', 'MUST accept application/json POST requests', async () => {
297
+ const res = await fetchFn(await getUrl(opts.url), {
298
+ method: 'POST',
299
+ headers: { 'content-type': 'application/json' },
300
+ body: JSON.stringify({ query: '{ __typename }' }),
301
+ });
302
+ ressert(res).status.toBe(200);
303
+ }),
304
+ audit('7267', 'MUST require a request body on POST', async () => {
305
+ var _a;
306
+ const res = await fetchFn(await getUrl(opts.url), {
307
+ method: 'POST',
308
+ headers: { 'content-type': 'application/json' },
309
+ });
310
+ if ((_a = res.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) {
311
+ await ressert(res).bodyAsExecutionResult.toHaveProperty('errors');
312
+ }
313
+ else {
314
+ ressert(res).status.toBe(400);
315
+ }
316
+ }),
317
+ // Request Parameters
318
+ audit(
319
+ // TODO: convert to MUST after watershed
320
+ '6610', 'SHOULD use 400 status code on missing {query} parameter when accepting application/graphql-response+json', async () => {
321
+ const res = await fetchFn(await getUrl(opts.url), {
322
+ method: 'POST',
323
+ headers: {
324
+ 'content-type': 'application/json',
325
+ accept: 'application/graphql-response+json',
326
+ },
327
+ body: JSON.stringify({ notquery: '{ __typename }' }),
328
+ });
329
+ ressert(res).status.toBe(400);
330
+ }),
331
+ audit('3715', 'SHOULD use 200 status code with errors field on missing {query} parameter when accepting application/json', async () => {
332
+ const res = await fetchFn(await getUrl(opts.url), {
333
+ method: 'POST',
334
+ headers: {
335
+ 'content-type': 'application/json',
336
+ accept: 'application/json',
337
+ },
338
+ body: JSON.stringify({ notquery: '{ __typename }' }),
339
+ });
340
+ ressert(res).status.toBe(200);
341
+ await ressert(res).bodyAsExecutionResult.toHaveProperty('errors');
342
+ }),
343
+ ...[{ obj: 'ect' }, 0, false, ['array']].map((invalid, index) => audit(`4F5${index}`,
344
+ // TODO: convert to MUST after watershed
345
+ `SHOULD use 400 status code on ${extendedTypeof(invalid)} {query} parameter when accepting application/graphql-response+json`, async () => {
346
+ const res = await fetchFn(await getUrl(opts.url), {
347
+ method: 'POST',
348
+ headers: {
349
+ 'content-type': 'application/json',
350
+ accept: 'application/graphql-response+json',
351
+ },
352
+ body: JSON.stringify({
353
+ query: invalid,
354
+ }),
355
+ });
356
+ ressert(res).status.toBe(400);
357
+ })),
358
+ ...[{ obj: 'ect' }, 0, false, ['array']].map((invalid, index) => audit(`9FE${index}`, `SHOULD use 200 status code with errors field on ${extendedTypeof(invalid)} {query} parameter when accepting application/json`, async () => {
359
+ const res = await fetchFn(await getUrl(opts.url), {
360
+ method: 'POST',
361
+ headers: {
362
+ 'content-type': 'application/json',
363
+ accept: 'application/json',
364
+ },
365
+ body: JSON.stringify({
366
+ query: invalid,
367
+ }),
368
+ });
369
+ ressert(res).status.toBe(200);
370
+ await ressert(res).bodyAsExecutionResult.toHaveProperty('errors');
371
+ })),
372
+ audit(
373
+ // TODO: convert to MUST after watershed
374
+ '34A2', 'SHOULD allow string {query} parameter when accepting application/graphql-response+json', async () => {
375
+ const res = await fetchFn(await getUrl(opts.url), {
376
+ method: 'POST',
377
+ headers: {
378
+ 'content-type': 'application/json',
379
+ accept: 'application/graphql-response+json',
380
+ },
381
+ body: JSON.stringify({
382
+ query: '{ __typename }',
383
+ }),
384
+ });
385
+ ressert(res).status.toBe(200);
386
+ }),
387
+ audit('13EE', 'MUST allow string {query} parameter when accepting application/json', async () => {
388
+ const res = await fetchFn(await getUrl(opts.url), {
389
+ method: 'POST',
390
+ headers: {
391
+ 'content-type': 'application/json',
392
+ accept: 'application/json',
393
+ },
394
+ body: JSON.stringify({
395
+ query: '{ __typename }',
396
+ }),
397
+ });
398
+ ressert(res).status.toBe(200);
399
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
400
+ }),
401
+ ...[{ obj: 'ect' }, 0, false, ['array']].map((invalid, index) => audit(`E3E${index}`,
402
+ // TODO: convert to MUST after watershed
403
+ `SHOULD use 400 status code on ${extendedTypeof(invalid)} {operationName} parameter when accepting application/graphql-response+json`, async () => {
404
+ const res = await fetchFn(await getUrl(opts.url), {
405
+ method: 'POST',
406
+ headers: {
407
+ 'content-type': 'application/json',
408
+ accept: 'application/graphql-response+json',
409
+ },
410
+ body: JSON.stringify({
411
+ operationName: invalid,
412
+ query: '{ __typename }',
413
+ }),
414
+ });
415
+ ressert(res).status.toBe(400);
416
+ })),
417
+ ...[{ obj: 'ect' }, 0, false, ['array']].map((invalid, index) => audit(`FB9${index}`, `SHOULD use 200 status code with errors field on ${extendedTypeof(invalid)} {operationName} parameter when accepting application/json`, async () => {
418
+ const res = await fetchFn(await getUrl(opts.url), {
419
+ method: 'POST',
420
+ headers: {
421
+ 'content-type': 'application/json',
422
+ accept: 'application/json',
423
+ },
424
+ body: JSON.stringify({
425
+ operationName: invalid,
426
+ query: '{ __typename }',
427
+ }),
428
+ });
429
+ ressert(res).status.toBe(200);
430
+ await ressert(res).bodyAsExecutionResult.toHaveProperty('errors');
431
+ })),
432
+ audit(
433
+ // TODO: convert to MUST after watershed
434
+ '8161', 'SHOULD allow string {operationName} parameter when accepting application/graphql-response+json', async () => {
435
+ const res = await fetchFn(await getUrl(opts.url), {
436
+ method: 'POST',
437
+ headers: {
438
+ 'content-type': 'application/json',
439
+ accept: 'application/graphql-response+json',
440
+ },
441
+ body: JSON.stringify({
442
+ operationName: 'Query',
443
+ query: 'query Query { __typename }',
444
+ }),
445
+ });
446
+ ressert(res).status.toBe(200);
447
+ }),
448
+ audit('B8B3', 'MUST allow string {operationName} parameter when accepting application/json', async () => {
449
+ const res = await fetchFn(await getUrl(opts.url), {
450
+ method: 'POST',
451
+ headers: {
452
+ 'content-type': 'application/json',
453
+ accept: 'application/json',
454
+ },
455
+ body: JSON.stringify({
456
+ operationName: 'Query',
457
+ query: 'query Query { __typename }',
458
+ }),
459
+ });
460
+ ressert(res).status.toBe(200);
461
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
462
+ }),
463
+ ...['variables', 'operationName', 'extensions'].flatMap((parameter, index) => [
464
+ audit(`94B${index}`,
465
+ // TODO: convert to MUST after watershed
466
+ `SHOULD allow null {${parameter}} parameter when accepting application/graphql-response+json`, async () => {
467
+ const res = await fetchFn(await getUrl(opts.url), {
468
+ method: 'POST',
469
+ headers: {
470
+ 'content-type': 'application/json',
471
+ accept: 'application/graphql-response+json',
472
+ },
473
+ body: JSON.stringify({
474
+ query: '{ __typename }',
475
+ [parameter]: null,
476
+ }),
477
+ });
478
+ ressert(res).status.toBe(200);
479
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
480
+ }),
481
+ audit(`022${index}`, `MUST allow null {${parameter}} parameter when accepting application/json`, async () => {
482
+ const res = await fetchFn(await getUrl(opts.url), {
483
+ method: 'POST',
484
+ headers: {
485
+ 'content-type': 'application/json',
486
+ accept: 'application/json',
487
+ },
488
+ body: JSON.stringify({
489
+ query: '{ __typename }',
490
+ [parameter]: null,
491
+ }),
492
+ });
493
+ ressert(res).status.toBe(200);
494
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
495
+ }),
496
+ ]),
497
+ ...['string', 0, false, ['array']].map((invalid, index) => audit(`69B${index}`,
498
+ // TODO: convert to MUST after watershed
499
+ `SHOULD use 400 status code on ${extendedTypeof(invalid)} {variables} parameter when accepting application/graphql-response+json`, async () => {
500
+ const res = await fetchFn(await getUrl(opts.url), {
501
+ method: 'POST',
502
+ headers: {
503
+ 'content-type': 'application/json',
504
+ accept: 'application/graphql-response+json',
505
+ },
506
+ body: JSON.stringify({
507
+ query: '{ __typename }',
508
+ variables: invalid,
509
+ }),
510
+ });
511
+ ressert(res).status.toBe(400);
512
+ })),
513
+ ...['string', 0, false, ['array']].map((invalid, index) => audit(`F05${index}`, `SHOULD use 200 status code with errors field on ${extendedTypeof(invalid)} {variables} parameter when accepting application/json`, async () => {
514
+ const res = await fetchFn(await getUrl(opts.url), {
515
+ method: 'POST',
516
+ headers: {
517
+ 'content-type': 'application/json',
518
+ accept: 'application/json',
519
+ },
520
+ body: JSON.stringify({
521
+ query: '{ __typename }',
522
+ variables: invalid,
523
+ }),
524
+ });
525
+ ressert(res).status.toBe(200);
526
+ await ressert(res).bodyAsExecutionResult.toHaveProperty('errors');
527
+ })),
528
+ audit(
529
+ // TODO: convert to MUST after watershed
530
+ '2EA1', 'SHOULD allow map {variables} parameter when accepting application/graphql-response+json', async () => {
531
+ const res = await fetchFn(await getUrl(opts.url), {
532
+ method: 'POST',
533
+ headers: {
534
+ 'content-type': 'application/json',
535
+ accept: 'application/graphql-response+json',
536
+ },
537
+ body: JSON.stringify({
538
+ query: 'query Type($name: String!) { __type(name: $name) { name } }',
539
+ variables: { name: 'sometype' },
540
+ }),
541
+ });
542
+ ressert(res).status.toBe(200);
543
+ }),
544
+ audit('28B9', 'MUST allow map {variables} parameter when accepting application/json', async () => {
545
+ const res = await fetchFn(await getUrl(opts.url), {
546
+ method: 'POST',
547
+ headers: {
548
+ 'content-type': 'application/json',
549
+ accept: 'application/json',
550
+ },
551
+ body: JSON.stringify({
552
+ query: 'query Type($name: String!) { __type(name: $name) { name } }',
553
+ variables: { name: 'sometype' },
554
+ }),
555
+ });
556
+ ressert(res).status.toBe(200);
557
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
558
+ }),
559
+ audit('D6D5', 'MAY allow URL-encoded JSON string {variables} parameter in GETs when accepting application/graphql-response+json', async () => {
560
+ const url = new URL(await getUrl(opts.url));
561
+ url.searchParams.set('query', 'query Type($name: String!) { __type(name: $name) { name } }');
562
+ url.searchParams.set('variables', JSON.stringify({ name: 'sometype' }));
563
+ const res = await fetchFn(url.toString(), {
564
+ method: 'GET',
565
+ headers: {
566
+ accept: 'application/graphql-response+json',
567
+ },
568
+ });
569
+ ressert(res).status.toBe(200);
570
+ }),
571
+ audit('6A70', 'MAY allow URL-encoded JSON string {variables} parameter in GETs when accepting application/json', async () => {
572
+ const url = new URL(await getUrl(opts.url));
573
+ url.searchParams.set('query', 'query Type($name: String!) { __type(name: $name) { name } }');
574
+ url.searchParams.set('variables', JSON.stringify({ name: 'sometype' }));
575
+ const res = await fetchFn(url.toString(), {
576
+ method: 'GET',
577
+ headers: {
578
+ accept: 'application/json',
579
+ },
580
+ });
581
+ ressert(res).status.toBe(200);
582
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
583
+ }),
584
+ ...['string', 0, false, ['array']].map((invalid, index) => audit(`904${index}`,
585
+ // TODO: convert to MUST after watershed
586
+ `SHOULD use 400 status code on ${extendedTypeof(invalid)} {extensions} parameter when accepting application/graphql-response+json`, async () => {
587
+ const res = await fetchFn(await getUrl(opts.url), {
588
+ method: 'POST',
589
+ headers: {
590
+ 'content-type': 'application/json',
591
+ accept: 'application/graphql-response+json',
592
+ },
593
+ body: JSON.stringify({
594
+ query: '{ __typename }',
595
+ extensions: invalid,
596
+ }),
597
+ });
598
+ ressert(res).status.toBe(400);
599
+ })),
600
+ ...['string', 0, false, ['array']].map((invalid, index) => audit(`368${index}`, `SHOULD use 200 status code with errors field on ${extendedTypeof(invalid)} {extensions} parameter when accepting application/json`, async () => {
601
+ const res = await fetchFn(await getUrl(opts.url), {
602
+ method: 'POST',
603
+ headers: {
604
+ 'content-type': 'application/json',
605
+ accept: 'application/json',
606
+ },
607
+ body: JSON.stringify({
608
+ query: '{ __typename }',
609
+ extensions: invalid,
610
+ }),
611
+ });
612
+ ressert(res).status.toBe(200);
613
+ await ressert(res).bodyAsExecutionResult.toHaveProperty('errors');
614
+ })),
615
+ audit(
616
+ // TODO: convert to MUST after watershed
617
+ '428F', 'SHOULD allow map {extensions} parameter when accepting application/graphql-response+json', async () => {
618
+ const res = await fetchFn(await getUrl(opts.url), {
619
+ method: 'POST',
620
+ headers: {
621
+ 'content-type': 'application/json',
622
+ accept: 'application/graphql-response+json',
623
+ },
624
+ body: JSON.stringify({
625
+ query: '{ __typename }',
626
+ extensions: { some: 'value' },
627
+ }),
628
+ });
629
+ ressert(res).status.toBe(200);
630
+ }),
631
+ audit('1B7A', 'MUST allow map {extensions} parameter when accepting application/json', async () => {
632
+ const res = await fetchFn(await getUrl(opts.url), {
633
+ method: 'POST',
634
+ headers: {
635
+ 'content-type': 'application/json',
636
+ accept: 'application/json',
637
+ },
638
+ body: JSON.stringify({
639
+ query: '{ __typename }',
640
+ extensions: { some: 'value' },
641
+ }),
642
+ });
643
+ ressert(res).status.toBe(200);
644
+ await ressert(res).bodyAsExecutionResult.notToHaveProperty('errors');
645
+ }),
646
+ // TODO: audit('39AA', 'MUST accept a map for the {extensions} parameter'),
647
+ // Response application/json
648
+ audit('D477', 'SHOULD use 200 status code on JSON parsing failure when accepting application/json', async () => {
649
+ const res = await fetchFn(await getUrl(opts.url), {
650
+ method: 'POST',
651
+ headers: {
652
+ 'content-type': 'application/json',
653
+ accept: 'application/json',
654
+ },
655
+ body: '{ "not a JSON',
656
+ });
657
+ ressert(res).status.toBe(200);
658
+ }),
659
+ audit('F5AF', 'SHOULD use 200 status code if parameters are invalid when accepting application/json', async () => {
660
+ const res = await fetchFn(await getUrl(opts.url), {
661
+ method: 'POST',
662
+ headers: {
663
+ 'content-type': 'application/json',
664
+ accept: 'application/json',
665
+ },
666
+ body: JSON.stringify({
667
+ qeury: /* typo */ '{ __typename }',
668
+ }),
669
+ });
670
+ ressert(res).status.toBe(200);
671
+ }),
672
+ audit('572B', 'SHOULD use 200 status code on document parsing failure when accepting application/json', async () => {
673
+ const res = await fetchFn(await getUrl(opts.url), {
674
+ method: 'POST',
675
+ headers: {
676
+ 'content-type': 'application/json',
677
+ accept: 'application/json',
678
+ },
679
+ body: JSON.stringify({ query: '{' }),
680
+ });
681
+ ressert(res).status.toBe(200);
682
+ }),
683
+ audit('FDE2', 'SHOULD use 200 status code on document validation failure when accepting application/json', async () => {
684
+ const res = await fetchFn(await getUrl(opts.url), {
685
+ method: 'POST',
686
+ headers: {
687
+ 'content-type': 'application/json',
688
+ accept: 'application/json',
689
+ },
690
+ body: JSON.stringify({
691
+ query: '{ 8f31403dfe404bccbb0e835f2629c6a7 }', // making sure the field doesnt exist
692
+ }),
693
+ });
694
+ ressert(res).status.toBe(200);
695
+ }),
696
+ // Response application/graphql-response+json
697
+ audit(
698
+ // TODO: convert to MUST after watershed
699
+ '60AA', 'SHOULD use 4xx or 5xx status codes on JSON parsing failure when accepting application/graphql-response+json', async () => {
700
+ const res = await fetchFn(await getUrl(opts.url), {
701
+ method: 'POST',
702
+ headers: {
703
+ 'content-type': 'application/json',
704
+ accept: 'application/graphql-response+json',
705
+ },
706
+ body: '{ "not a JSON',
707
+ });
708
+ ressert(res).status.toBeBetween(400, 499);
709
+ }),
710
+ audit('2163', 'SHOULD use 400 status code on JSON parsing failure when accepting application/graphql-response+json', async () => {
711
+ const res = await fetchFn(await getUrl(opts.url), {
712
+ method: 'POST',
713
+ headers: {
714
+ 'content-type': 'application/json',
715
+ accept: 'application/graphql-response+json',
716
+ },
717
+ body: '{ "not a JSON',
718
+ });
719
+ ressert(res).status.toBe(400);
720
+ }),
721
+ audit(
722
+ // TODO: convert to MUST after watershed
723
+ '3E36', 'SHOULD use 4xx or 5xx status codes if parameters are invalid when accepting application/graphql-response+json', async () => {
724
+ const res = await fetchFn(await getUrl(opts.url), {
725
+ method: 'POST',
726
+ headers: {
727
+ 'content-type': 'application/json',
728
+ accept: 'application/graphql-response+json',
729
+ },
730
+ body: JSON.stringify({
731
+ qeury /* typo */: '{ __typename }',
732
+ }),
733
+ });
734
+ ressert(res).status.toBeBetween(400, 599);
735
+ }),
736
+ audit('17C5', 'SHOULD use 400 status code if parameters are invalid when accepting application/graphql-response+json', async () => {
737
+ const res = await fetchFn(await getUrl(opts.url), {
738
+ method: 'POST',
739
+ headers: {
740
+ 'content-type': 'application/json',
741
+ accept: 'application/graphql-response+json',
742
+ },
743
+ body: JSON.stringify({
744
+ qeury: /* typo */ '{ __typename }',
745
+ }),
746
+ });
747
+ ressert(res).status.toBe(400);
748
+ }),
749
+ audit('34D6', 'SHOULD not contain the data entry if parameters are invalid when accepting application/graphql-response+json', async () => {
750
+ const res = await fetchFn(await getUrl(opts.url), {
751
+ method: 'POST',
752
+ headers: {
753
+ 'content-type': 'application/json',
754
+ accept: 'application/graphql-response+json',
755
+ },
756
+ body: JSON.stringify({
757
+ qeury: /* typo */ '{ __typename }',
758
+ }),
759
+ });
760
+ await ressert(res).bodyAsExecutionResult.data.toBe(undefined);
761
+ }),
762
+ audit(
763
+ // TODO: convert to MUST after watershed
764
+ '865D', 'SHOULD use 4xx or 5xx status codes on document parsing failure when accepting application/graphql-response+json', async () => {
765
+ const res = await fetchFn(await getUrl(opts.url), {
766
+ method: 'POST',
767
+ headers: {
768
+ 'content-type': 'application/json',
769
+ accept: 'application/graphql-response+json',
770
+ },
771
+ body: JSON.stringify({
772
+ query: '{',
773
+ }),
774
+ });
775
+ ressert(res).status.toBeBetween(400, 599);
776
+ }),
777
+ audit('556A', 'SHOULD use 400 status code on document parsing failure when accepting application/graphql-response+json', async () => {
778
+ const res = await fetchFn(await getUrl(opts.url), {
779
+ method: 'POST',
780
+ headers: {
781
+ 'content-type': 'application/json',
782
+ accept: 'application/graphql-response+json',
783
+ },
784
+ body: JSON.stringify({
785
+ query: '{',
786
+ }),
787
+ });
788
+ ressert(res).status.toBe(400);
789
+ }),
790
+ audit('D586', 'SHOULD not contain the data entry on document parsing failure when accepting application/graphql-response+json', async () => {
791
+ const res = await fetchFn(await getUrl(opts.url), {
792
+ method: 'POST',
793
+ headers: {
794
+ 'content-type': 'application/json',
795
+ accept: 'application/graphql-response+json',
796
+ },
797
+ body: JSON.stringify({
798
+ query: '{',
799
+ }),
800
+ });
801
+ await ressert(res).bodyAsExecutionResult.data.toBe(undefined);
802
+ }),
803
+ audit(
804
+ // TODO: convert to MUST after watershed
805
+ '51FE', 'SHOULD use 4xx or 5xx status codes on document validation failure when accepting application/graphql-response+json', async () => {
806
+ const res = await fetchFn(await getUrl(opts.url), {
807
+ method: 'POST',
808
+ headers: {
809
+ 'content-type': 'application/json',
810
+ accept: 'application/graphql-response+json',
811
+ },
812
+ body: JSON.stringify({
813
+ query: '{ 8f31403dfe404bccbb0e835f2629c6a7 }', // making sure the field doesnt exist
814
+ }),
815
+ });
816
+ ressert(res).status.toBeBetween(400, 599);
817
+ }),
818
+ audit('74FF', 'SHOULD use 400 status code on document validation failure when accepting application/graphql-response+json', async () => {
819
+ const res = await fetchFn(await getUrl(opts.url), {
820
+ method: 'POST',
821
+ headers: {
822
+ 'content-type': 'application/json',
823
+ accept: 'application/graphql-response+json',
824
+ },
825
+ body: JSON.stringify({
826
+ query: '{ 8f31403dfe404bccbb0e835f2629c6a7 }', // making sure the field doesnt exist
827
+ }),
828
+ });
829
+ ressert(res).status.toBe(400);
830
+ }),
831
+ audit('5E5B', 'SHOULD not contain the data entry on document validation failure when accepting application/graphql-response+json', async () => {
832
+ const res = await fetchFn(await getUrl(opts.url), {
833
+ method: 'POST',
834
+ headers: {
835
+ 'content-type': 'application/json',
836
+ accept: 'application/graphql-response+json',
837
+ },
838
+ body: JSON.stringify({
839
+ query: '{ 8f31403dfe404bccbb0e835f2629c6a7 }', // making sure the field doesnt exist
840
+ }),
841
+ });
842
+ await ressert(res).bodyAsExecutionResult.data.toBe(undefined);
843
+ }),
844
+ // TODO: how to fail and have the data entry?
845
+ // audit('EE52', 'MUST use 2xx status code if response contains the data entry and it is not null when accepting application/graphql-response+json'),
846
+ // TODO: how to make an unauthorized request?
847
+ // https://graphql.github.io/graphql-over-http/draft/#sel-EANNNDTAAEVBAAqqc
848
+ // audit('BC58', 'SHOULD use 401 or 403 status codes when the request is not permitted')
849
+ ];
850
+ }
851
+ /**
852
+ * Performs the full list of server audits required for GraphQL over HTTP spec conformance.
853
+ *
854
+ * Please consult the `AuditResult` for more information.
855
+ *
856
+ * @category Audits
857
+ */
858
+ async function auditServer(opts) {
859
+ const audits = serverAudits(opts);
860
+ // audit tests will throw only on fatal errors, tests are contained within the AuditResult
861
+ return await Promise.all(audits.map(({ fn }) => fn()));
862
+ }
863
+ /** @private */
864
+ async function getUrl(url) {
865
+ if (typeof url === 'function') {
866
+ return await url();
867
+ }
868
+ return url;
869
+ }
870
+
871
+ /**
872
+ * Renders the provided audit results to well-formatted and valid HTML.
873
+ *
874
+ * Do note that the rendered result is not an HTML document, it's rather
875
+ * just a component with results.
876
+ */
877
+ async function renderAuditResultsToHTML(results) {
878
+ const grouped = {
879
+ total: 0,
880
+ ok: [],
881
+ warn: [],
882
+ error: [],
883
+ };
884
+ for (const result of results) {
885
+ grouped.total++;
886
+ if (result.status === 'ok') {
887
+ grouped[result.status].push(result);
888
+ }
889
+ else {
890
+ grouped[result.status].push(result);
891
+ }
892
+ }
893
+ let report = '<i>* This report was auto-generated by graphql-http</i>\n';
894
+ report += '\n';
895
+ report += '<h1>GraphQL over HTTP audit report</h1>\n';
896
+ report += '\n';
897
+ report += '<ul>\n';
898
+ report += `<li><b>${grouped.total}</b> audits in total</li>\n`;
899
+ // font-family: monospace helps render native emojis in HTML
900
+ if (grouped.ok.length) {
901
+ report += `<li><span style="font-family: monospace">✅</span> <b>${grouped.ok.length}</b> pass</li>\n`;
902
+ }
903
+ if (grouped.warn.length) {
904
+ // TODO: warning sign is rendered as "⚠️" in markdown instead of the emoji
905
+ report += `<li><span style="font-family: monospace">⚠️</span> <b>${grouped.warn.length}</b> warnings (optional)</li>\n`;
906
+ }
907
+ if (grouped.error.length) {
908
+ report += `<li><span style="font-family: monospace">❌</span> <b>${grouped.error.length}</b> errors (required)</li>\n`;
909
+ }
910
+ report += '</ul>\n';
911
+ report += '\n';
912
+ if (grouped.ok.length) {
913
+ report += '<h2>Passing</h2>\n';
914
+ report += '<ol>\n';
915
+ for (const [, result] of grouped.ok.entries()) {
916
+ report += `<li><code>${result.id}</code> ${result.name}</li>\n`;
917
+ }
918
+ report += '</ol>\n';
919
+ report += '\n';
920
+ }
921
+ if (grouped.warn.length) {
922
+ report += `<h2>Warnings</h2>\n`;
923
+ report += 'The server <i>SHOULD</i> support these, but is not required.\n';
924
+ report += '<ol>\n';
925
+ for (const [, result] of grouped.warn.entries()) {
926
+ report += await printAuditFail(result);
927
+ }
928
+ report += '</ol>\n';
929
+ report += '\n';
930
+ }
931
+ if (grouped.error.length) {
932
+ report += `<h2>Errors</h2>\n`;
933
+ report += 'The server <b>MUST</b> support these.\n';
934
+ report += '<ol>\n';
935
+ for (const [, result] of grouped.error.entries()) {
936
+ report += await printAuditFail(result);
937
+ }
938
+ report += '</ol>\n';
939
+ }
940
+ return report;
941
+ }
942
+ async function printAuditFail(result) {
943
+ let report = '';
944
+ report += `<li><code>${result.id}</code> ${result.name}\n`;
945
+ report += '<details>\n';
946
+ report += `<summary>${truncate(result.reason)}</summary>\n`;
947
+ report += '<pre><code class="lang-json">'; // no "\n" because they count in HTML pre tags
948
+ const res = result.response;
949
+ const headers = {};
950
+ for (const [key, val] of res.headers.entries()) {
951
+ // some headers change on each run, dont report it
952
+ if (key === 'date') {
953
+ headers[key] = '<timestamp>';
954
+ }
955
+ else if (['cf-ray', 'server-timing'].includes(key)) {
956
+ headers[key] = '<omitted>';
957
+ }
958
+ else {
959
+ headers[key] = val;
960
+ }
961
+ }
962
+ let text = '', json;
963
+ try {
964
+ text = await res.text();
965
+ json = JSON.parse(text);
966
+ }
967
+ catch (_a) {
968
+ // noop
969
+ }
970
+ const stringified = JSON.stringify({
971
+ status: res.status,
972
+ statusText: res.statusText,
973
+ headers,
974
+ body: json || ((text === null || text === void 0 ? void 0 : text.length) > 5120 ? '<body is too long>' : text) || null,
975
+ }, (_k, v) => {
976
+ if (v != null && typeof v === 'object' && !Array.isArray(v)) {
977
+ // sort object fields for stable stringify
978
+ const acc = {};
979
+ return Object.keys(v)
980
+ .sort()
981
+ .reverse() // body on bottom
982
+ .reduce((acc, k) => {
983
+ acc[k] = v[k];
984
+ return acc;
985
+ }, acc);
986
+ }
987
+ return v;
988
+ }, 2);
989
+ report += stringified + '\n';
990
+ report += '</code></pre>\n';
991
+ report += '</details>\n';
992
+ report += '</li>\n';
993
+ return report;
994
+ }
995
+ function truncate(str, len = 1024) {
996
+ if (str.length > len) {
997
+ return str.substring(0, len) + '...';
998
+ }
999
+ return str;
1000
+ }
1001
+
1002
+ exports.auditServer = auditServer;
1003
+ exports.renderAuditResultsToHTML = renderAuditResultsToHTML;
1004
+ exports.serverAudits = serverAudits;
1005
+
1006
+ }));