@nikhil-qeas/api-core 0.7.0 → 0.8.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 (36) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +82 -7
  3. package/bin/qe-api.js +1 -0
  4. package/dist/http/api-client.d.ts +15 -0
  5. package/dist/http/api-client.js +41 -4
  6. package/dist/http/trace.d.ts +26 -0
  7. package/dist/http/trace.js +43 -0
  8. package/dist/http/types.d.ts +6 -0
  9. package/dist/index.d.ts +11 -4
  10. package/dist/index.js +5 -2
  11. package/dist/integrations/mocha.d.ts +32 -0
  12. package/dist/integrations/mocha.js +81 -0
  13. package/dist/reporting/html-report.d.ts +23 -0
  14. package/dist/reporting/html-report.js +118 -0
  15. package/dist/reporting/junit.d.ts +11 -2
  16. package/dist/reporting/junit.js +9 -3
  17. package/dist/reporting/redaction.d.ts +6 -0
  18. package/dist/reporting/redaction.js +10 -0
  19. package/dist/testing/load.d.ts +85 -0
  20. package/dist/testing/load.js +134 -0
  21. package/dist/testing/spec-cases.d.ts +46 -8
  22. package/dist/testing/spec-cases.js +292 -22
  23. package/package.json +1 -1
  24. package/templates/project/README.md +39 -6
  25. package/templates/project/__dot__env.example +4 -0
  26. package/templates/project/__dot__gitlab-ci.yml +1 -0
  27. package/templates/project/openapi/openapi.json +233 -0
  28. package/templates/project/src/clients/api.ts +4 -2
  29. package/templates/project/src/environment.ts +8 -0
  30. package/templates/project/src/observability.ts +15 -1
  31. package/templates/project/tests/performance/health.spec.ts +22 -0
  32. package/templates/project/tests/security/authentication.spec.ts +3 -1
  33. package/templates/project/tests/security/spec-cases.spec.ts +40 -3
  34. package/templates/project/tests/setup/hooks.ts +32 -5
  35. package/templates/project/tests/smoke/tracing.spec.ts +48 -0
  36. package/templates/project/tests/support/mock-api.ts +114 -5
@@ -1,6 +1,7 @@
1
1
  import { createServer } from 'node:http';
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
3
3
  import { once } from 'node:events';
4
+ import { isIP } from 'node:net';
4
5
  import type { AddressInfo } from 'node:net';
5
6
 
6
7
  /** A local stand-in for an API and its OAuth2 token endpoint, so the sample tests run anywhere without a real environment. */
@@ -13,6 +14,8 @@ export interface MockApi {
13
14
  revokeTokens(): void;
14
15
  /** Every request the server received, as "METHOD /path". Shows that a refused request was never sent. */
15
16
  requests(): readonly string[];
17
+ /** The `traceparent` header of every request that carried one, in order. Shows what the client propagates when QE_TRACE=true. */
18
+ traceparents(): readonly string[];
16
19
  close(): Promise<void>;
17
20
  }
18
21
 
@@ -28,16 +31,85 @@ function send(res: ServerResponse, status: number, body: unknown): void {
28
31
  res.end(JSON.stringify(body));
29
32
  }
30
33
 
31
- /** Why a POST /accounts body is invalid, or undefined when it is valid. Mirrors NewAccount in openapi/openapi.json. */
34
+ /** True for an http or https address on the public internet: not a file, localhost, a private network or the cloud metadata service. */
35
+ function isPublicAddress(value: string): boolean {
36
+ let url: URL;
37
+ try {
38
+ url = new URL(value);
39
+ } catch {
40
+ return false;
41
+ }
42
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
43
+ const host = url.hostname.replace(/^\[|\]$/g, '');
44
+ if (host === 'localhost' || host.endsWith('.localhost')) return false;
45
+ if (isIP(host) === 6) return !(host === '::1' || /^(fc|fd|fe80)/i.test(host));
46
+ if (isIP(host) === 4) {
47
+ const [first = 0, second = 0] = host.split('.').map(Number);
48
+ return !(first === 0 || first === 10 || first === 127 || (first === 169 && second === 254) || (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168));
49
+ }
50
+ return true;
51
+ }
52
+
53
+ /**
54
+ * Why a POST /accounts body is invalid, or undefined when it is valid. Mirrors NewAccount in openapi/openapi.json.
55
+ * `accountNumber` is read-only: the API accepts it and ignores it (it never applies, or returns, a value a client sends).
56
+ * `webhookUrl` must be a public address, so the API cannot be pointed at internal systems.
57
+ */
32
58
  function newAccountProblem(body: unknown): string | undefined {
33
59
  if (typeof body !== 'object' || body === null || Array.isArray(body)) return 'the body must be an object';
34
60
  const fields = body as Record<string, unknown>;
35
- const unexpected = Object.keys(fields).find(key => !['name', 'currency', 'initialDeposit'].includes(key));
61
+ const unexpected = Object.keys(fields).find(key => !['name', 'currency', 'initialDeposit', 'webhookUrl', 'accountNumber'].includes(key));
36
62
  if (unexpected !== undefined) return 'unexpected property';
37
- const { name, currency, initialDeposit } = fields;
63
+ const { name, currency, initialDeposit, webhookUrl } = fields;
38
64
  if (typeof name !== 'string' || name.length < 1 || name.length > 50) return 'name must be 1 to 50 characters';
39
65
  if (typeof currency !== 'string' || !CURRENCIES.includes(currency)) return 'currency must be USD, EUR or GBP';
40
66
  if (initialDeposit !== undefined && (typeof initialDeposit !== 'number' || initialDeposit < 0)) return 'initialDeposit must be a number of at least 0';
67
+ if (webhookUrl !== undefined && (typeof webhookUrl !== 'string' || !isPublicAddress(webhookUrl))) return 'webhookUrl must be a public http or https address';
68
+ return undefined;
69
+ }
70
+
71
+ /**
72
+ * Reads a form or multipart body the way a server framework does (here: the platform's own parser).
73
+ * 'unsupported' when it is neither, 'malformed' when it does not parse.
74
+ */
75
+ async function readForm(req: IncomingMessage, body: Buffer): Promise<FormData | 'unsupported' | 'malformed'> {
76
+ const contentType = req.headers['content-type'] ?? '';
77
+ const kind = contentType.split(';', 1)[0]?.trim().toLowerCase();
78
+ if (kind !== 'application/x-www-form-urlencoded' && kind !== 'multipart/form-data') return 'unsupported';
79
+ try {
80
+ return await new Request('http://localhost/', { method: 'POST', headers: { 'content-type': contentType }, body: body.length ? new Uint8Array(body) : null }).formData();
81
+ } catch {
82
+ return 'malformed';
83
+ }
84
+ }
85
+
86
+ /** The one text value of a field, or undefined when it is missing, repeated, or a file. */
87
+ function textField(form: FormData, name: string): string | undefined {
88
+ const values = form.getAll(name);
89
+ const [value] = values;
90
+ return values.length === 1 && typeof value === 'string' ? value : undefined;
91
+ }
92
+
93
+ /** Why a POST /oauth/token form is invalid, or undefined when it is valid. Mirrors TokenRequest in openapi/openapi.json. */
94
+ function tokenRequestProblem(form: FormData): string | undefined {
95
+ for (const name of form.keys()) if (!['grant_type', 'client_id', 'client_secret', 'scope'].includes(name)) return 'unexpected field';
96
+ if (textField(form, 'grant_type') !== 'client_credentials') return 'grant_type must be client_credentials';
97
+ const clientId = textField(form, 'client_id');
98
+ if (clientId === undefined || clientId.length < 1 || clientId.length > 100) return 'client_id must be 1 to 100 characters';
99
+ const clientSecret = textField(form, 'client_secret');
100
+ if (clientSecret === undefined || clientSecret.length < 1 || clientSecret.length > 200) return 'client_secret must be 1 to 200 characters';
101
+ if (form.has('scope') && (textField(form, 'scope') ?? 'x'.repeat(201)).length > 200) return 'scope must be at most 200 characters';
102
+ return undefined;
103
+ }
104
+
105
+ /** Why a document upload is invalid, or undefined when it is valid. Mirrors DocumentUpload in openapi/openapi.json. */
106
+ function documentProblem(form: FormData): string | undefined {
107
+ for (const name of form.keys()) if (!['file', 'kind', 'note'].includes(name)) return 'unexpected field';
108
+ const files = form.getAll('file');
109
+ if (files.length !== 1 || !(files[0] instanceof File)) return 'file must be exactly one file';
110
+ const kind = textField(form, 'kind');
111
+ if (kind === undefined || !['statement', 'identity', 'other'].includes(kind)) return 'kind must be statement, identity or other';
112
+ if (form.has('note') && (textField(form, 'note') ?? 'x'.repeat(101)).length > 100) return 'note must be at most 100 characters';
41
113
  return undefined;
42
114
  }
43
115
 
@@ -46,16 +118,50 @@ export async function startMockApi(): Promise<MockApi> {
46
118
  let created = 0;
47
119
  let validToken: string | undefined;
48
120
  const received: string[] = [];
121
+ const traces: string[] = [];
49
122
 
50
- const route = (req: IncomingMessage, res: ServerResponse, rawBody: string): void => {
123
+ let uploaded = 0;
124
+
125
+ const route = async (req: IncomingMessage, res: ServerResponse, body: Buffer): Promise<void> => {
126
+ const rawBody = body.toString('utf8');
51
127
  const { pathname } = new URL(req.url ?? '/', 'http://localhost');
52
128
  received.push(`${req.method ?? ''} ${pathname}`);
129
+ if (typeof req.headers.traceparent === 'string') traces.push(req.headers.traceparent);
53
130
  if (req.method === 'POST' && pathname === '/oauth/token') {
131
+ const form = await readForm(req, body);
132
+ if (form === 'unsupported') {
133
+ send(res, 415, { error: 'unsupported_media_type' });
134
+ return;
135
+ }
136
+ if (form === 'malformed' || tokenRequestProblem(form) !== undefined) {
137
+ send(res, 400, { error: 'invalid_request' });
138
+ return;
139
+ }
54
140
  issued++;
55
141
  validToken = `tok-${issued}`;
56
142
  send(res, 200, { access_token: validToken, token_type: 'Bearer', expires_in: 3600 });
57
143
  return;
58
144
  }
145
+ const documents = /^\/accounts\/([^/]+)\/documents$/.exec(pathname);
146
+ if (req.method === 'POST' && documents) {
147
+ const form = await readForm(req, body);
148
+ if (form === 'unsupported') {
149
+ send(res, 415, { error: 'unsupported_media_type' });
150
+ return;
151
+ }
152
+ if (form === 'malformed' || documentProblem(form) !== undefined) {
153
+ send(res, 400, { error: 'invalid_request' });
154
+ return;
155
+ }
156
+ if (decodeURIComponent(documents[1] ?? '') === 'missing') {
157
+ send(res, 404, { error: 'not_found' });
158
+ return;
159
+ }
160
+ uploaded++;
161
+ const file = form.get('file') as File;
162
+ send(res, 201, { id: `doc-${uploaded}`, kind: textField(form, 'kind'), size: file.size });
163
+ return;
164
+ }
59
165
  if (req.method === 'GET' && pathname === '/health') {
60
166
  send(res, 200, { status: 'ok' });
61
167
  return;
@@ -106,7 +212,9 @@ export async function startMockApi(): Promise<MockApi> {
106
212
  const server = createServer((req, res) => {
107
213
  const chunks: Buffer[] = [];
108
214
  req.on('data', (chunk: Buffer) => chunks.push(chunk));
109
- req.on('end', () => route(req, res, Buffer.concat(chunks).toString('utf8')));
215
+ req.on('end', () => {
216
+ route(req, res, Buffer.concat(chunks)).catch(() => { send(res, 500, { error: 'internal_error' }); });
217
+ });
110
218
  });
111
219
  server.listen(0, '127.0.0.1');
112
220
  await once(server, 'listening');
@@ -117,6 +225,7 @@ export async function startMockApi(): Promise<MockApi> {
117
225
  tokensIssued: () => issued,
118
226
  revokeTokens: () => { validToken = undefined; },
119
227
  requests: () => received,
228
+ traceparents: () => traces,
120
229
  close: () => new Promise<void>(resolve => {
121
230
  server.closeAllConnections();
122
231
  server.close(() => resolve());