@nikhil-qeas/api-core 0.5.1 → 0.7.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/CHANGELOG.md +52 -0
- package/README.md +141 -5
- package/bin/qe-api.js +4 -4
- package/dist/contracts/assertions.d.ts +11 -0
- package/dist/contracts/assertions.js +31 -0
- package/dist/contracts/openapi.d.ts +28 -1
- package/dist/contracts/openapi.js +113 -0
- package/dist/graphql/graphql.d.ts +86 -0
- package/dist/graphql/graphql.js +312 -0
- package/dist/http/api-client.d.ts +5 -0
- package/dist/http/api-client.js +30 -6
- package/dist/http/cookies.d.ts +32 -0
- package/dist/http/cookies.js +116 -0
- package/dist/http/multipart.d.ts +20 -0
- package/dist/http/multipart.js +48 -0
- package/dist/http/types.d.ts +16 -0
- package/dist/index.d.ts +21 -2
- package/dist/index.js +11 -1
- package/dist/reporting/redaction.d.ts +4 -0
- package/dist/reporting/redaction.js +26 -2
- package/dist/security/authorization-matrix.d.ts +55 -0
- package/dist/security/authorization-matrix.js +102 -0
- package/dist/security/headers.d.ts +21 -0
- package/dist/security/headers.js +45 -0
- package/dist/security/policy.js +3 -2
- package/dist/security/sensitive-data.d.ts +22 -0
- package/dist/security/sensitive-data.js +76 -0
- package/dist/testing/json-path.d.ts +6 -0
- package/dist/testing/json-path.js +97 -0
- package/dist/testing/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +98 -0
- package/dist/testing/spec-cases.js +795 -0
- package/dist/testing/wait-for.d.ts +40 -0
- package/dist/testing/wait-for.js +82 -0
- package/package.json +1 -1
- package/templates/project/README.md +55 -6
- package/templates/project/__dot__env.example +5 -0
- package/templates/project/openapi/openapi.json +243 -19
- package/templates/project/src/clients/api.ts +27 -6
- package/templates/project/src/{config/environment.ts → environment.ts} +16 -1
- package/templates/project/src/observability.ts +1 -1
- package/templates/project/src/{contracts/openapi.ts → openapi.ts} +1 -1
- package/templates/project/tests/contract/openapi.contract.spec.ts +1 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- package/templates/project/tests/security/authorization.spec.ts +29 -0
- package/templates/project/tests/security/hygiene.spec.ts +37 -0
- package/templates/project/tests/security/spec-cases.spec.ts +24 -0
- package/templates/project/tests/security/write-protection.spec.ts +60 -0
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- package/templates/project/tests/support/approved-writes.ts +27 -0
- package/templates/project/tests/support/identities.ts +24 -0
- package/templates/project/tests/support/mock-api.ts +62 -3
- /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { credentialIn } from '../reporting/redaction.js';
|
|
3
|
+
const CLOSERS = new Map([['{', '}'], ['(', ')'], ['[', ']']]);
|
|
4
|
+
const CLOSING = new Set(CLOSERS.values());
|
|
5
|
+
const PUNCTUATION = new Set(['{', '}', '(', ')', '[', ']', ':', '=', '@', '$', '!', '|', '&']);
|
|
6
|
+
const NAME_START = /[A-Za-z_]/;
|
|
7
|
+
const NAME_PART = /[A-Za-z0-9_]/;
|
|
8
|
+
const NUMBER_PART = /[-+0-9.eE]/;
|
|
9
|
+
const SAFE_NAME = /^[A-Za-z0-9_.:$-]{1,64}$/;
|
|
10
|
+
/** Splits a GraphQL document into names and punctuation, skipping comments and strings. Undefined when it is not well-formed. */
|
|
11
|
+
function tokenize(document) {
|
|
12
|
+
const tokens = [];
|
|
13
|
+
const length = document.length;
|
|
14
|
+
let at = 0;
|
|
15
|
+
while (at < length) {
|
|
16
|
+
const c = document.charAt(at);
|
|
17
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === ',' || c === '') {
|
|
18
|
+
at += 1;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (c === '#') {
|
|
22
|
+
while (at < length && document.charAt(at) !== '\n' && document.charAt(at) !== '\r')
|
|
23
|
+
at += 1;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (c === '"') {
|
|
27
|
+
if (document.startsWith('"""', at)) {
|
|
28
|
+
at += 3;
|
|
29
|
+
for (;;) {
|
|
30
|
+
if (at >= length)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (document.startsWith('\\"""', at))
|
|
33
|
+
at += 4;
|
|
34
|
+
else if (document.startsWith('"""', at)) {
|
|
35
|
+
at += 3;
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
else
|
|
39
|
+
at += 1;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
at += 1;
|
|
44
|
+
for (;;) {
|
|
45
|
+
if (at >= length)
|
|
46
|
+
return undefined;
|
|
47
|
+
const d = document.charAt(at);
|
|
48
|
+
if (d === '\n' || d === '\r')
|
|
49
|
+
return undefined;
|
|
50
|
+
if (d === '\\')
|
|
51
|
+
at += 2;
|
|
52
|
+
else if (d === '"') {
|
|
53
|
+
at += 1;
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
at += 1;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
tokens.push({ type: 'other' });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (NAME_START.test(c)) {
|
|
64
|
+
const start = at;
|
|
65
|
+
while (at < length && NAME_PART.test(document.charAt(at)))
|
|
66
|
+
at += 1;
|
|
67
|
+
tokens.push({ type: 'name', value: document.slice(start, at) });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (c === '-' || (c >= '0' && c <= '9')) {
|
|
71
|
+
while (at < length && NUMBER_PART.test(document.charAt(at)))
|
|
72
|
+
at += 1;
|
|
73
|
+
tokens.push({ type: 'other' });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (c === '.') {
|
|
77
|
+
while (at < length && document.charAt(at) === '.')
|
|
78
|
+
at += 1;
|
|
79
|
+
tokens.push({ type: 'other' });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (PUNCTUATION.has(c)) {
|
|
83
|
+
tokens.push({ type: 'punct', value: c });
|
|
84
|
+
at += 1;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
return undefined; // a character GraphQL does not use: do not guess
|
|
88
|
+
}
|
|
89
|
+
return tokens;
|
|
90
|
+
}
|
|
91
|
+
/** Index just after the bracket that closes the one at `start`, or -1 when the brackets do not match. */
|
|
92
|
+
function skipBalanced(tokens, start) {
|
|
93
|
+
const expected = [];
|
|
94
|
+
for (let at = start; at < tokens.length; at += 1) {
|
|
95
|
+
const token = tokens[at];
|
|
96
|
+
if (token?.type !== 'punct')
|
|
97
|
+
continue;
|
|
98
|
+
const closer = CLOSERS.get(token.value);
|
|
99
|
+
if (closer !== undefined)
|
|
100
|
+
expected.push(closer);
|
|
101
|
+
else if (CLOSING.has(token.value)) {
|
|
102
|
+
if (expected.pop() !== token.value)
|
|
103
|
+
return -1;
|
|
104
|
+
if (expected.length === 0)
|
|
105
|
+
return at + 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return -1;
|
|
109
|
+
}
|
|
110
|
+
/** From the token after `query`, `mutation` or `fragment`: the index of the `{` that opens the body, and how many names (not directives) came first. */
|
|
111
|
+
function headerEnd(tokens, from) {
|
|
112
|
+
let names = 0;
|
|
113
|
+
let afterAt = false;
|
|
114
|
+
for (let at = from; at < tokens.length; at += 1) {
|
|
115
|
+
const token = tokens[at];
|
|
116
|
+
if (token?.type === 'name') {
|
|
117
|
+
if (!afterAt)
|
|
118
|
+
names += 1;
|
|
119
|
+
afterAt = false;
|
|
120
|
+
}
|
|
121
|
+
else if (token?.type === 'punct' && token.value === '{') {
|
|
122
|
+
return { brace: at, names };
|
|
123
|
+
}
|
|
124
|
+
else if (token?.type === 'punct' && token.value === '@') {
|
|
125
|
+
afterAt = true;
|
|
126
|
+
}
|
|
127
|
+
else if (token?.type === 'punct' && token.value === '(') {
|
|
128
|
+
const end = skipBalanced(tokens, at);
|
|
129
|
+
if (end < 0)
|
|
130
|
+
return undefined;
|
|
131
|
+
at = end - 1;
|
|
132
|
+
afterAt = false;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The operations a document defines (fragments are not operations), or undefined when the document cannot be read with certainty:
|
|
142
|
+
* unbalanced brackets, an unterminated string, a character GraphQL does not use, or a definition that is not executable.
|
|
143
|
+
* Comments, strings and field names that merely say "mutation" are never mistaken for the keyword.
|
|
144
|
+
*/
|
|
145
|
+
export function parseOperations(document) {
|
|
146
|
+
const tokens = tokenize(document);
|
|
147
|
+
if (tokens === undefined)
|
|
148
|
+
return undefined;
|
|
149
|
+
const operations = [];
|
|
150
|
+
let at = 0;
|
|
151
|
+
while (at < tokens.length) {
|
|
152
|
+
const token = tokens[at];
|
|
153
|
+
if (token?.type === 'punct' && token.value === '{') { // shorthand for an anonymous query
|
|
154
|
+
const end = skipBalanced(tokens, at);
|
|
155
|
+
if (end < 0)
|
|
156
|
+
return undefined;
|
|
157
|
+
operations.push({ kind: 'query' });
|
|
158
|
+
at = end;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (token?.type !== 'name')
|
|
162
|
+
return undefined;
|
|
163
|
+
const keyword = token.value;
|
|
164
|
+
if (keyword !== 'query' && keyword !== 'mutation' && keyword !== 'subscription' && keyword !== 'fragment')
|
|
165
|
+
return undefined;
|
|
166
|
+
const header = headerEnd(tokens, at + 1);
|
|
167
|
+
if (header === undefined)
|
|
168
|
+
return undefined;
|
|
169
|
+
const end = skipBalanced(tokens, header.brace);
|
|
170
|
+
if (end < 0)
|
|
171
|
+
return undefined;
|
|
172
|
+
if (keyword === 'fragment') {
|
|
173
|
+
if (header.names !== 3)
|
|
174
|
+
return undefined; // fragment Name on Type
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
if (header.names > 1)
|
|
178
|
+
return undefined; // at most the operation's name
|
|
179
|
+
const first = tokens[at + 1];
|
|
180
|
+
operations.push({ kind: keyword, name: header.names === 1 && first?.type === 'name' ? first.value : undefined });
|
|
181
|
+
}
|
|
182
|
+
at = end;
|
|
183
|
+
}
|
|
184
|
+
return operations;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* What running the document would do: the kind of the operation the server will select. 'unknown' when that cannot be told for
|
|
188
|
+
* certain (a document that does not parse, several operations and no matching `operationName`), which callers must treat as a write.
|
|
189
|
+
*/
|
|
190
|
+
export function operationKind(document, operationName) {
|
|
191
|
+
const operations = parseOperations(document);
|
|
192
|
+
if (operations === undefined || operations.length === 0)
|
|
193
|
+
return 'unknown';
|
|
194
|
+
if (operationName !== undefined && operationName !== '') {
|
|
195
|
+
const named = operations.filter(operation => operation.name === operationName);
|
|
196
|
+
const only = named[0];
|
|
197
|
+
return named.length === 1 && only !== undefined ? only.kind : 'unknown';
|
|
198
|
+
}
|
|
199
|
+
const only = operations[0];
|
|
200
|
+
return operations.length === 1 && only !== undefined ? only.kind : 'unknown';
|
|
201
|
+
}
|
|
202
|
+
function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
203
|
+
function hasHeader(headers, name) {
|
|
204
|
+
return headers !== undefined && Object.keys(headers).some(key => key.toLowerCase() === name);
|
|
205
|
+
}
|
|
206
|
+
function normalizeError(raw) {
|
|
207
|
+
const error = {};
|
|
208
|
+
if (!isRecord(raw))
|
|
209
|
+
return error;
|
|
210
|
+
if (typeof raw.message === 'string')
|
|
211
|
+
error.message = raw.message;
|
|
212
|
+
if (Array.isArray(raw.path) && raw.path.every(part => typeof part === 'string' || typeof part === 'number'))
|
|
213
|
+
error.path = raw.path;
|
|
214
|
+
if (isRecord(raw.extensions)) {
|
|
215
|
+
error.extensions = raw.extensions;
|
|
216
|
+
if (typeof raw.extensions.code === 'string')
|
|
217
|
+
error.code = raw.extensions.code;
|
|
218
|
+
}
|
|
219
|
+
return error;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* GraphQL over HTTP on top of an `ApiClient`: sends the document as a POST, classifies it, and reads `data` and `errors`.
|
|
223
|
+
*
|
|
224
|
+
* Because a query is a POST, a read-only execution policy would refuse it. The client marks a request `readOnly` (and safe to
|
|
225
|
+
* retry) only when the document provably is a query. A mutation, a subscription and anything it cannot classify are sent as the
|
|
226
|
+
* writes they may be, so a read-only run refuses them before anything is sent and they are never retried after an ambiguous failure.
|
|
227
|
+
* This trusts the GraphQL convention that a query has no side effects.
|
|
228
|
+
*/
|
|
229
|
+
export class GraphQLClient {
|
|
230
|
+
api;
|
|
231
|
+
path;
|
|
232
|
+
constructor(api, options = {}) {
|
|
233
|
+
this.api = api;
|
|
234
|
+
this.path = options.path ?? '/graphql';
|
|
235
|
+
}
|
|
236
|
+
async execute(request) {
|
|
237
|
+
if (request.query.trim() === '')
|
|
238
|
+
throw new Error('A GraphQL request needs a query document');
|
|
239
|
+
const operation = operationKind(request.query, request.operationName);
|
|
240
|
+
const headers = { ...request.headers };
|
|
241
|
+
if (!hasHeader(headers, 'accept'))
|
|
242
|
+
headers.Accept = 'application/graphql-response+json, application/json;q=0.9';
|
|
243
|
+
const response = await this.api.request({
|
|
244
|
+
method: 'POST',
|
|
245
|
+
path: this.path,
|
|
246
|
+
json: { query: request.query, ...(request.variables !== undefined ? { variables: request.variables } : {}), ...(request.operationName !== undefined ? { operationName: request.operationName } : {}) },
|
|
247
|
+
headers,
|
|
248
|
+
...(operation === 'query' ? { readOnly: true, idempotent: true } : {}),
|
|
249
|
+
...(request.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {}),
|
|
250
|
+
...(request.skipAuth !== undefined ? { skipAuth: request.skipAuth } : {})
|
|
251
|
+
});
|
|
252
|
+
const envelope = isRecord(response.body) ? response.body : undefined;
|
|
253
|
+
const rawErrors = envelope?.errors;
|
|
254
|
+
return {
|
|
255
|
+
operation,
|
|
256
|
+
status: response.status,
|
|
257
|
+
data: envelope !== undefined && 'data' in envelope ? envelope.data : undefined,
|
|
258
|
+
errors: Array.isArray(rawErrors) ? rawErrors.map(normalizeError) : (rawErrors === undefined || rawErrors === null ? [] : [{}]),
|
|
259
|
+
extensions: isRecord(envelope?.extensions) ? envelope.extensions : undefined,
|
|
260
|
+
response
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function pathText(path) {
|
|
265
|
+
return path.map(part => typeof part === 'number' ? String(part) : (SAFE_NAME.test(part) ? part : '?')).join('.');
|
|
266
|
+
}
|
|
267
|
+
/** What the errors are, without their messages: codes and paths are short identifiers a server has to choose from. */
|
|
268
|
+
function describeErrors(errors, showMessages) {
|
|
269
|
+
const count = `${errors.length} GraphQL error${errors.length === 1 ? '' : 's'}`;
|
|
270
|
+
const codes = [...new Set(errors.map(error => error.code).filter((code) => code !== undefined && SAFE_NAME.test(code)))].slice(0, 5);
|
|
271
|
+
const paths = [...new Set(errors.flatMap(error => error.path === undefined ? [] : [pathText(error.path)]))].slice(0, 5);
|
|
272
|
+
const parts = [count];
|
|
273
|
+
if (codes.length)
|
|
274
|
+
parts.push(`codes: ${codes.join(', ')}`);
|
|
275
|
+
if (paths.length)
|
|
276
|
+
parts.push(`paths: ${paths.join(', ')}`);
|
|
277
|
+
if (showMessages) {
|
|
278
|
+
const messages = errors.slice(0, 3).flatMap(error => error.message === undefined || credentialIn(error.message) !== undefined ? [] : [JSON.stringify(error.message.slice(0, 200))]);
|
|
279
|
+
if (messages.length)
|
|
280
|
+
parts.push(`messages: ${messages.join(', ')}`);
|
|
281
|
+
}
|
|
282
|
+
return `${parts[0]} (${parts.slice(1).join('; ') || 'no codes or paths'})`;
|
|
283
|
+
}
|
|
284
|
+
/** Fails unless the response is HTTP 2xx, has no GraphQL errors (partial data with errors is a failure) and carries data. */
|
|
285
|
+
export function expectGraphQLSuccess(result, options = {}) {
|
|
286
|
+
const problems = [];
|
|
287
|
+
if (result.status < 200 || result.status >= 300)
|
|
288
|
+
problems.push(`HTTP ${result.status}`);
|
|
289
|
+
if (result.errors.length)
|
|
290
|
+
problems.push(describeErrors(result.errors, options.showMessages === true));
|
|
291
|
+
else if (result.data === undefined || result.data === null)
|
|
292
|
+
problems.push('the response has no data');
|
|
293
|
+
if (problems.length)
|
|
294
|
+
assert.fail(`GraphQL ${result.operation === 'unknown' ? 'request' : result.operation} failed: ${problems.join('; ')}`);
|
|
295
|
+
}
|
|
296
|
+
function samePath(actual, expected) {
|
|
297
|
+
if (actual === undefined)
|
|
298
|
+
return false;
|
|
299
|
+
const wanted = typeof expected === 'string' ? expected.split('.') : expected.map(String);
|
|
300
|
+
return actual.length === wanted.length && actual.every((part, index) => String(part) === wanted[index]);
|
|
301
|
+
}
|
|
302
|
+
/** Fails unless the response carries at least one GraphQL error matching the expectation (any error at all when none is given). */
|
|
303
|
+
export function expectGraphQLError(result, expected = {}, options = {}) {
|
|
304
|
+
const wanted = [expected.code !== undefined ? `code "${expected.code}"` : '', expected.path !== undefined ? `path "${typeof expected.path === 'string' ? expected.path : expected.path.join('.')}"` : ''].filter(Boolean).join(' at ');
|
|
305
|
+
if (!result.errors.length)
|
|
306
|
+
assert.fail(`Expected a GraphQL error${wanted ? ` with ${wanted}` : ''}, but the response has none (HTTP ${result.status})`);
|
|
307
|
+
if (expected.status !== undefined && result.status !== expected.status)
|
|
308
|
+
assert.fail(`Expected HTTP ${expected.status} with a GraphQL error, got HTTP ${result.status}`);
|
|
309
|
+
const matches = result.errors.some(error => (expected.code === undefined || error.code === expected.code) && (expected.path === undefined || samePath(error.path, expected.path)));
|
|
310
|
+
if (!matches)
|
|
311
|
+
assert.fail(`Expected a GraphQL error with ${wanted}, but the response has ${describeErrors(result.errors, options.showMessages === true)}`);
|
|
312
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TokenSource } from '../auth/token-manager.js';
|
|
2
|
+
import { CookieJar } from './cookies.js';
|
|
2
3
|
import type { RetryConfig } from './retry.js';
|
|
3
4
|
import type { ApiRequest, ApiResult, EventSink, RequestSigner } from './types.js';
|
|
4
5
|
export declare class ApiTransportError extends Error {
|
|
@@ -23,6 +24,8 @@ export interface ApiAuth {
|
|
|
23
24
|
export interface ApiClientConfig extends RetryConfig {
|
|
24
25
|
baseUrl: string;
|
|
25
26
|
auth?: ApiAuth;
|
|
27
|
+
/** Keep the cookies the server sets and send them back: `true` for a new jar, or pass your own. Off by default. Reach it as `client.cookies`. */
|
|
28
|
+
cookies?: boolean | CookieJar;
|
|
26
29
|
timeoutMs?: number;
|
|
27
30
|
maxSafeRetries?: number;
|
|
28
31
|
signer?: RequestSigner;
|
|
@@ -37,6 +40,8 @@ export declare class ApiClient {
|
|
|
37
40
|
private readonly url;
|
|
38
41
|
private readonly fetcher;
|
|
39
42
|
private readonly retryPolicy;
|
|
43
|
+
/** The cookie jar, when `cookies` is enabled. */
|
|
44
|
+
readonly cookies: CookieJar | undefined;
|
|
40
45
|
constructor(cfg: ApiClientConfig);
|
|
41
46
|
request<T = unknown>(req: ApiRequest): Promise<ApiResult<T>>;
|
|
42
47
|
}
|
package/dist/http/api-client.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { CookieJar } from './cookies.js';
|
|
3
|
+
import { encodeMultipart } from './multipart.js';
|
|
2
4
|
import { backoffDelay, resolveRetryPolicy, retryDelay } from './retry.js';
|
|
3
5
|
export class ApiTransportError extends Error {
|
|
4
6
|
kind;
|
|
@@ -55,6 +57,8 @@ function retryAllowed(method, idempotent) {
|
|
|
55
57
|
return ['GET', 'HEAD', 'OPTIONS'].includes(method) || idempotent;
|
|
56
58
|
}
|
|
57
59
|
function shouldRetryStatus(status) { return [408, 429, 502, 503, 504].includes(status); }
|
|
60
|
+
const textEncoder = new TextEncoder();
|
|
61
|
+
const textDecoder = new TextDecoder();
|
|
58
62
|
function hasHeader(headers, name) {
|
|
59
63
|
const wanted = name.toLowerCase();
|
|
60
64
|
return Object.keys(headers).some(key => key.toLowerCase() === wanted);
|
|
@@ -65,6 +69,8 @@ export class ApiClient {
|
|
|
65
69
|
url;
|
|
66
70
|
fetcher;
|
|
67
71
|
retryPolicy;
|
|
72
|
+
/** The cookie jar, when `cookies` is enabled. */
|
|
73
|
+
cookies;
|
|
68
74
|
constructor(cfg) {
|
|
69
75
|
this.cfg = cfg;
|
|
70
76
|
this.url = new URL(cfg.baseUrl.endsWith('/') ? cfg.baseUrl : `${cfg.baseUrl}/`);
|
|
@@ -72,13 +78,19 @@ export class ApiClient {
|
|
|
72
78
|
throw new Error('Clean HTTP(S) baseUrl required');
|
|
73
79
|
this.fetcher = cfg.fetchImpl ?? fetch;
|
|
74
80
|
this.retryPolicy = resolveRetryPolicy(cfg);
|
|
81
|
+
this.cookies = cfg.cookies === true ? new CookieJar() : cfg.cookies === false ? undefined : cfg.cookies;
|
|
75
82
|
}
|
|
76
83
|
async request(req) {
|
|
77
84
|
assertPath(req.path);
|
|
78
|
-
const bodyKinds = [req.json !== undefined, req.form !== undefined, req.rawBody !== undefined].filter(Boolean).length;
|
|
85
|
+
const bodyKinds = [req.json !== undefined, req.form !== undefined, req.rawBody !== undefined, req.multipart !== undefined].filter(Boolean).length;
|
|
79
86
|
if (bodyKinds > 1)
|
|
80
87
|
throw new Error('Supply only one body representation');
|
|
88
|
+
const multipart = req.multipart === undefined ? undefined : encodeMultipart(req.multipart);
|
|
89
|
+
if (multipart && hasHeader({ ...this.cfg.defaultHeaders, ...req.headers }, 'content-type'))
|
|
90
|
+
throw new Error('A multipart body sets its own Content-Type, boundary included: do not supply one');
|
|
81
91
|
const raw = req.rawBody ?? (req.form ? encodeForm(req.form) : (req.json === undefined ? '' : JSON.stringify(req.json)));
|
|
92
|
+
const payload = multipart?.body ?? raw;
|
|
93
|
+
const payloadBytes = typeof payload === 'string' ? textEncoder.encode(payload) : payload;
|
|
82
94
|
const url = new URL(this.url.href);
|
|
83
95
|
url.pathname = `${this.url.pathname.replace(/\/$/, '')}${req.path}`;
|
|
84
96
|
for (const [key, value] of Object.entries(req.query ?? {})) {
|
|
@@ -108,6 +120,12 @@ export class ApiClient {
|
|
|
108
120
|
headers['Content-Type'] = 'application/json';
|
|
109
121
|
else if (!hasContentType && req.form !== undefined)
|
|
110
122
|
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
123
|
+
if (multipart)
|
|
124
|
+
headers['Content-Type'] = multipart.contentType;
|
|
125
|
+
// Cookies the server set earlier go back with this request, unless the caller chose its own Cookie header or opted out.
|
|
126
|
+
const cookie = this.cookies !== undefined && req.skipCookies !== true && !hasHeader(headers, 'cookie') ? this.cookies.header(url) : undefined;
|
|
127
|
+
if (cookie !== undefined)
|
|
128
|
+
headers.Cookie = cookie;
|
|
111
129
|
// A header the caller set explicitly (e.g. a deliberately bad token) is never replaced or renewed.
|
|
112
130
|
let usedToken;
|
|
113
131
|
if (auth && req.skipAuth !== true && !hasHeader(headers, authHeader)) {
|
|
@@ -115,12 +133,12 @@ export class ApiClient {
|
|
|
115
133
|
headers[authHeader] = auth.scheme === '' ? usedToken : `${auth.scheme ?? 'Bearer'} ${usedToken}`;
|
|
116
134
|
}
|
|
117
135
|
// Signature is regenerated each attempt; pass the exact body bytes, never a reserialized object.
|
|
118
|
-
Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody:
|
|
136
|
+
Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody: typeof payload === 'string' ? payload : textDecoder.decode(payload), exactBodyBytes: payloadBytes, requestId, attempt }));
|
|
119
137
|
const timeoutMs = req.timeoutMs ?? this.cfg.timeoutMs ?? 15_000;
|
|
120
138
|
let response;
|
|
121
139
|
try {
|
|
122
140
|
response = await this.fetcher(url, {
|
|
123
|
-
method: req.method, headers, ...(
|
|
141
|
+
method: req.method, headers, ...(payloadBytes.length ? { body: payload } : {}),
|
|
124
142
|
redirect: req.followRedirects ? 'follow' : 'manual', signal: AbortSignal.timeout(timeoutMs),
|
|
125
143
|
});
|
|
126
144
|
}
|
|
@@ -137,13 +155,19 @@ export class ApiClient {
|
|
|
137
155
|
throw new ApiTransportError(`${req.method} ${req.path} ${isTimeout ? 'timed out' : 'failed to connect'}`, isTimeout ? 'timeout' : 'network');
|
|
138
156
|
}
|
|
139
157
|
{
|
|
140
|
-
let text;
|
|
158
|
+
let text = '';
|
|
159
|
+
let bytes;
|
|
141
160
|
try {
|
|
142
|
-
|
|
161
|
+
if (req.responseType === 'binary')
|
|
162
|
+
bytes = new Uint8Array(await response.arrayBuffer());
|
|
163
|
+
else
|
|
164
|
+
text = await response.text();
|
|
143
165
|
}
|
|
144
166
|
catch {
|
|
145
167
|
throw new ApiTransportError(`${req.method} ${req.path} response read failed`, 'network');
|
|
146
168
|
}
|
|
169
|
+
if (this.cookies !== undefined && req.skipCookies !== true)
|
|
170
|
+
this.cookies.store(response.headers.getSetCookie(), url);
|
|
147
171
|
if (response.status === 401 && auth && usedToken !== undefined && !reauthenticated && auth.refreshOnUnauthorized !== false) {
|
|
148
172
|
// The server rejected the token we sent. Tell the cache which one, so a burst of 401s renews once.
|
|
149
173
|
auth.tokens.invalidate(usedToken);
|
|
@@ -164,7 +188,7 @@ export class ApiClient {
|
|
|
164
188
|
const elapsed = Math.round(performance.now() - started);
|
|
165
189
|
const marker = reauthenticated ? { reauthenticated: true } : {};
|
|
166
190
|
this.cfg.onEvent?.({ kind: 'success', method: req.method, path: req.path, status: response.status, durationMs: elapsed, attempts: attempt, requestId, ...marker });
|
|
167
|
-
return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), body: parse(text, response.headers.get('content-type')), text, durationMs: elapsed, attempts: attempt, requestId, ...marker };
|
|
191
|
+
return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), body: (bytes ?? parse(text, response.headers.get('content-type'))), text, durationMs: elapsed, attempts: attempt, requestId, ...marker };
|
|
168
192
|
}
|
|
169
193
|
}
|
|
170
194
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface CookieSetOptions {
|
|
2
|
+
/** Default '/'. */
|
|
3
|
+
path?: string | undefined;
|
|
4
|
+
/** Only sent over https. Default false. */
|
|
5
|
+
secure?: boolean | undefined;
|
|
6
|
+
/** Epoch milliseconds after which the cookie is no longer sent. Default: never. */
|
|
7
|
+
expiresAt?: number | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A minimal cookie jar for a client that talks to one origin: it keeps the cookies the server sets and sends them back on matching
|
|
11
|
+
* requests. Path, Secure, Max-Age/Expires and Domain-must-match are honored; SameSite and HttpOnly are browser concerns and are ignored.
|
|
12
|
+
* Cookie values are credentials: the client never puts them in events or error messages.
|
|
13
|
+
*/
|
|
14
|
+
export declare class CookieJar {
|
|
15
|
+
private readonly now;
|
|
16
|
+
private readonly cookies;
|
|
17
|
+
private counter;
|
|
18
|
+
constructor(now?: () => number);
|
|
19
|
+
/** Records the Set-Cookie headers of a response to `url`. An expired or zero Max-Age cookie deletes the one it names. */
|
|
20
|
+
store(setCookie: readonly string[], url: URL): void;
|
|
21
|
+
/** The Cookie header for a request to `url`, or undefined when no cookie applies. Longer paths come first. */
|
|
22
|
+
header(url: URL): string | undefined;
|
|
23
|
+
/** The value of the first unexpired cookie with this name. */
|
|
24
|
+
get(name: string): string | undefined;
|
|
25
|
+
/** Sets a cookie directly, for tests that start from a known session (or a tampered one). */
|
|
26
|
+
set(name: string, value: string, options?: CookieSetOptions): void;
|
|
27
|
+
delete(name: string): void;
|
|
28
|
+
clear(): void;
|
|
29
|
+
/** Names only: values are credentials, so they are never listed. */
|
|
30
|
+
names(): string[];
|
|
31
|
+
get size(): number;
|
|
32
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const MAX_COOKIES = 100;
|
|
2
|
+
const MAX_VALUE_LENGTH = 4096;
|
|
3
|
+
const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
4
|
+
/** True for ASCII control characters (and DEL), which a cookie value must not contain. */
|
|
5
|
+
function hasControlCharacter(value) {
|
|
6
|
+
for (let index = 0; index < value.length; index++) {
|
|
7
|
+
const code = value.charCodeAt(index);
|
|
8
|
+
if (code < 0x20 || code === 0x7f)
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
function defaultPath(url) {
|
|
14
|
+
const path = url.pathname;
|
|
15
|
+
const last = path.lastIndexOf('/');
|
|
16
|
+
return path.startsWith('/') && last > 0 ? path.slice(0, last) : '/';
|
|
17
|
+
}
|
|
18
|
+
function pathMatches(requestPath, cookiePath) {
|
|
19
|
+
if (requestPath === cookiePath)
|
|
20
|
+
return true;
|
|
21
|
+
return requestPath.startsWith(cookiePath) && (cookiePath.endsWith('/') || requestPath[cookiePath.length] === '/');
|
|
22
|
+
}
|
|
23
|
+
/** Parses one Set-Cookie header. Undefined for a cookie that must be ignored (malformed, or meant for another host). */
|
|
24
|
+
function parseSetCookie(header, url, now) {
|
|
25
|
+
const [pair = '', ...attributes] = header.split(';');
|
|
26
|
+
const equals = pair.indexOf('=');
|
|
27
|
+
if (equals <= 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
const name = pair.slice(0, equals).trim();
|
|
30
|
+
const value = pair.slice(equals + 1).trim();
|
|
31
|
+
if (!COOKIE_NAME.test(name) || hasControlCharacter(value) || value.length > MAX_VALUE_LENGTH)
|
|
32
|
+
return undefined;
|
|
33
|
+
let path;
|
|
34
|
+
let secure = false;
|
|
35
|
+
let maxAge;
|
|
36
|
+
let expires;
|
|
37
|
+
let domain;
|
|
38
|
+
for (const attribute of attributes) {
|
|
39
|
+
const separator = attribute.indexOf('=');
|
|
40
|
+
const key = (separator < 0 ? attribute : attribute.slice(0, separator)).trim().toLowerCase();
|
|
41
|
+
const raw = separator < 0 ? '' : attribute.slice(separator + 1).trim();
|
|
42
|
+
if (key === 'path' && raw.startsWith('/'))
|
|
43
|
+
path = raw;
|
|
44
|
+
else if (key === 'secure')
|
|
45
|
+
secure = true;
|
|
46
|
+
else if (key === 'max-age' && /^-?\d+$/.test(raw))
|
|
47
|
+
maxAge = Number(raw);
|
|
48
|
+
else if (key === 'expires' && !Number.isNaN(Date.parse(raw)))
|
|
49
|
+
expires = Date.parse(raw);
|
|
50
|
+
else if (key === 'domain')
|
|
51
|
+
domain = raw.replace(/^\./, '').toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
if (domain !== undefined) {
|
|
54
|
+
const host = url.hostname.toLowerCase();
|
|
55
|
+
if (host !== domain && !host.endsWith(`.${domain}`))
|
|
56
|
+
return undefined; // a cookie for another site is not ours to keep
|
|
57
|
+
}
|
|
58
|
+
return { name, value, path: path ?? defaultPath(url), secure, expiresAt: maxAge !== undefined ? now + maxAge * 1000 : expires };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A minimal cookie jar for a client that talks to one origin: it keeps the cookies the server sets and sends them back on matching
|
|
62
|
+
* requests. Path, Secure, Max-Age/Expires and Domain-must-match are honored; SameSite and HttpOnly are browser concerns and are ignored.
|
|
63
|
+
* Cookie values are credentials: the client never puts them in events or error messages.
|
|
64
|
+
*/
|
|
65
|
+
export class CookieJar {
|
|
66
|
+
now;
|
|
67
|
+
cookies = new Map();
|
|
68
|
+
counter = 0;
|
|
69
|
+
constructor(now = Date.now) {
|
|
70
|
+
this.now = now;
|
|
71
|
+
}
|
|
72
|
+
/** Records the Set-Cookie headers of a response to `url`. An expired or zero Max-Age cookie deletes the one it names. */
|
|
73
|
+
store(setCookie, url) {
|
|
74
|
+
for (const header of setCookie) {
|
|
75
|
+
const cookie = parseSetCookie(header, url, this.now());
|
|
76
|
+
if (!cookie)
|
|
77
|
+
continue;
|
|
78
|
+
const key = `${cookie.name}|${cookie.path}`;
|
|
79
|
+
if (cookie.expiresAt !== undefined && cookie.expiresAt <= this.now()) {
|
|
80
|
+
this.cookies.delete(key);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!this.cookies.has(key) && this.cookies.size >= MAX_COOKIES)
|
|
84
|
+
continue;
|
|
85
|
+
this.cookies.set(key, { ...cookie, order: this.cookies.get(key)?.order ?? this.counter++ });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The Cookie header for a request to `url`, or undefined when no cookie applies. Longer paths come first. */
|
|
89
|
+
header(url) {
|
|
90
|
+
const now = this.now();
|
|
91
|
+
const eligible = [...this.cookies.values()].filter(cookie => (cookie.expiresAt === undefined || cookie.expiresAt > now) && (!cookie.secure || url.protocol === 'https:') && pathMatches(url.pathname, cookie.path));
|
|
92
|
+
eligible.sort((a, b) => b.path.length - a.path.length || a.order - b.order);
|
|
93
|
+
return eligible.length ? eligible.map(cookie => `${cookie.name}=${cookie.value}`).join('; ') : undefined;
|
|
94
|
+
}
|
|
95
|
+
/** The value of the first unexpired cookie with this name. */
|
|
96
|
+
get(name) {
|
|
97
|
+
const now = this.now();
|
|
98
|
+
return [...this.cookies.values()].find(cookie => cookie.name === name && (cookie.expiresAt === undefined || cookie.expiresAt > now))?.value;
|
|
99
|
+
}
|
|
100
|
+
/** Sets a cookie directly, for tests that start from a known session (or a tampered one). */
|
|
101
|
+
set(name, value, options = {}) {
|
|
102
|
+
if (!COOKIE_NAME.test(name) || hasControlCharacter(value) || value.includes(';'))
|
|
103
|
+
throw new Error('Invalid cookie name or value');
|
|
104
|
+
const path = options.path ?? '/';
|
|
105
|
+
this.cookies.set(`${name}|${path}`, { name, value, path, secure: options.secure === true, expiresAt: options.expiresAt, order: this.counter++ });
|
|
106
|
+
}
|
|
107
|
+
delete(name) {
|
|
108
|
+
for (const [key, cookie] of this.cookies)
|
|
109
|
+
if (cookie.name === name)
|
|
110
|
+
this.cookies.delete(key);
|
|
111
|
+
}
|
|
112
|
+
clear() { this.cookies.clear(); }
|
|
113
|
+
/** Names only: values are credentials, so they are never listed. */
|
|
114
|
+
names() { return [...new Set([...this.cookies.values()].map(cookie => cookie.name))]; }
|
|
115
|
+
get size() { return this.cookies.size; }
|
|
116
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** A text field, or a file with its bytes (a string is sent as UTF-8). */
|
|
2
|
+
export type MultipartPart = {
|
|
3
|
+
name: string;
|
|
4
|
+
value: string;
|
|
5
|
+
} | {
|
|
6
|
+
name: string;
|
|
7
|
+
filename: string;
|
|
8
|
+
data: string | Uint8Array;
|
|
9
|
+
contentType?: string;
|
|
10
|
+
};
|
|
11
|
+
export interface EncodedMultipart {
|
|
12
|
+
body: Uint8Array<ArrayBuffer>;
|
|
13
|
+
/** `multipart/form-data; boundary=...`, the Content-Type the request must carry. */
|
|
14
|
+
contentType: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Encodes a multipart/form-data body. The boundary is random and chosen so that it appears nowhere in the data. The result is
|
|
18
|
+
* one fixed byte sequence: a retry or a signature sees exactly the bytes that are sent.
|
|
19
|
+
*/
|
|
20
|
+
export declare function encodeMultipart(parts: ReadonlyArray<MultipartPart>): EncodedMultipart;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
/** Escapes a name or filename for a Content-Disposition parameter the way browsers do: quotes and line breaks become %22, %0D, %0A. */
|
|
4
|
+
function quoted(value, what) {
|
|
5
|
+
if (value.length === 0)
|
|
6
|
+
throw new Error(`Multipart ${what} must not be empty`);
|
|
7
|
+
if (value.includes('\u0000'))
|
|
8
|
+
throw new Error(`Multipart ${what} must not contain a null character`);
|
|
9
|
+
return value.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');
|
|
10
|
+
}
|
|
11
|
+
function bytesOf(data) { return typeof data === 'string' ? encoder.encode(data) : data; }
|
|
12
|
+
function contains(haystack, needle) {
|
|
13
|
+
return Buffer.from(haystack.buffer, haystack.byteOffset, haystack.byteLength).includes(needle);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Encodes a multipart/form-data body. The boundary is random and chosen so that it appears nowhere in the data. The result is
|
|
17
|
+
* one fixed byte sequence: a retry or a signature sees exactly the bytes that are sent.
|
|
18
|
+
*/
|
|
19
|
+
export function encodeMultipart(parts) {
|
|
20
|
+
const contents = parts.map(part => ('value' in part ? encoder.encode(part.value) : bytesOf(part.data)));
|
|
21
|
+
let boundary = '';
|
|
22
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
23
|
+
boundary = `qe-${randomUUID().replace(/-/g, '')}`;
|
|
24
|
+
if (!contents.some(content => contains(content, boundary)))
|
|
25
|
+
break;
|
|
26
|
+
if (attempt === 4)
|
|
27
|
+
throw new Error('Could not find a multipart boundary that is absent from the data');
|
|
28
|
+
}
|
|
29
|
+
const chunks = [];
|
|
30
|
+
parts.forEach((part, index) => {
|
|
31
|
+
let header = `--${boundary}\r\nContent-Disposition: form-data; name="${quoted(part.name, 'field name')}"`;
|
|
32
|
+
if ('filename' in part) {
|
|
33
|
+
const contentType = part.contentType ?? 'application/octet-stream';
|
|
34
|
+
if (/[\r\n]/.test(contentType) || contentType.includes('\u0000'))
|
|
35
|
+
throw new Error('Multipart contentType must not contain line breaks');
|
|
36
|
+
header += `; filename="${quoted(part.filename, 'filename')}"\r\nContent-Type: ${contentType}`;
|
|
37
|
+
}
|
|
38
|
+
chunks.push(encoder.encode(`${header}\r\n\r\n`), contents[index] ?? new Uint8Array(0), encoder.encode('\r\n'));
|
|
39
|
+
});
|
|
40
|
+
chunks.push(encoder.encode(`--${boundary}--\r\n`));
|
|
41
|
+
const body = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
|
|
42
|
+
let offset = 0;
|
|
43
|
+
for (const chunk of chunks) {
|
|
44
|
+
body.set(chunk, offset);
|
|
45
|
+
offset += chunk.byteLength;
|
|
46
|
+
}
|
|
47
|
+
return { body, contentType: `multipart/form-data; boundary=${boundary}` };
|
|
48
|
+
}
|