tr-apisrv 2.1.0 → 3.0.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 (4) hide show
  1. package/README.md +169 -1
  2. package/index.js +304 -51
  3. package/package.json +1 -1
  4. package/test/test.js +618 -0
package/README.md CHANGED
@@ -77,6 +77,10 @@ request, `tr-apisrv` returns a canonical JSON error such as
77
77
  | `rejectDangerousPaths` | boolean | `true` | Reject paths containing empty, `.` or `..` segments with HTTP 400. |
78
78
  | `bodyReadTimeoutMs` | number | `2000` | Milliseconds allowed to fully read the request body. Applies to upgrade as well. |
79
79
  | `maxBodySize` | number | `1048576` | Maximum allowed request body size in bytes. `0` allows only empty bodies. |
80
+ | `errorCallback` | function | `undefined` | Called for every error response the server generates itself, so that the application can send its own. See [Custom error responses](#custom-error-responses). |
81
+ | `pathRewrite` | function | `undefined` | `(path) => path`, applied to the request path before handlers are matched. See [Path rewriting](#path-rewriting). |
82
+ | `requireObjectBody` | boolean | `false` | When true, a JSON body that is an array is rejected with HTTP 400. |
83
+ | `rejectDangerousParamNames` | boolean | `false` | When true, a request whose body or query string has a key named `__proto__`, `constructor` or `prototype`, at any depth, is rejected with HTTP 400. |
80
84
  | `debug` | boolean | `false` | Enables verbose logging for authentication failures and handler completion. |
81
85
 
82
86
  The server accepts only `GET`, `POST`, `PUT`, and `DELETE` requests. Other
@@ -145,6 +149,8 @@ return an object.
145
149
  | `bodyParamsValidator` | Validates and can transform `request.bodyParams`. |
146
150
  | `paramsValidator` | Validates the merged `request.params` object. |
147
151
  | `ignoreUrlParams` | When `true`, the query string is ignored and `request.urlParams` is left `undefined`. |
152
+ | `authCallback` | Authentication for this handler only. Runs after the server's `authCallback` has accepted the request and, like it, before any parameters are parsed. Return truthy to continue; when returning falsy, send the response yourself. |
153
+ | `meta` | Any value you want to attach to the handler, for example a name or the scopes it needs. Available as `request.handler.meta` and from `requestHandlerList()`. |
148
154
 
149
155
  #### Validator example
150
156
 
@@ -172,6 +178,25 @@ server.requestHandleAdd('POST', '/import', importHandler, {
172
178
  You can supply the same `options` when adding handlers at runtime with
173
179
  `requestHandleAdd(method, path, callback, options)`.
174
180
 
181
+ #### Per-handler authentication and metadata
182
+
183
+ ```javascript
184
+ server.requestHandleAdd('POST', '/admin/users', createUser, {
185
+ meta: { name: 'create-user', scope: 'admin' },
186
+ authCallback: async (request) => {
187
+ if (await tokenHasScope(request.headers.authorization, request.handler.meta.scope)) {
188
+ return true;
189
+ }
190
+ request.jsonResponse({ code: 403, message: 'Forbidden' }, 403);
191
+ return false;
192
+ }
193
+ });
194
+ ```
195
+
196
+ `request.handler` is `{ method, path, meta }` for a request matched by
197
+ `requestHandlers`, where `path` is the template that matched. It is
198
+ `undefined` when the fallback `callback` serves the request.
199
+
175
200
  ### Runtime updates
176
201
 
177
202
  Handlers may be added, replaced, or removed without restarting the process:
@@ -189,6 +214,16 @@ server.requestHandleDelete('POST', '/status');
189
214
  server.requestHandleDelete('*', '/status');
190
215
  ```
191
216
 
217
+ `requestHandlerList()` returns the registered handlers as
218
+ `{ method, path, meta }` objects, which is useful for generating
219
+ documentation or checking that every route has what it needs:
220
+
221
+ ```javascript
222
+ for (const { method, path, meta } of server.requestHandlerList()) {
223
+ console.log(method, path, meta);
224
+ }
225
+ ```
226
+
192
227
  ## Request object
193
228
 
194
229
  Handlers receive an object that wraps the underlying `http.IncomingMessage` and
@@ -197,7 +232,10 @@ Handlers receive an object that wraps the underlying `http.IncomingMessage` and
197
232
  | Property | Description |
198
233
  | --- | --- |
199
234
  | `method` | Uppercase HTTP method. |
200
- | `url` | Request path without the query string. |
235
+ | `url` | Request path without the query string, after `pathRewrite` when one is configured. |
236
+ | `originalUrl` | Request path without the query string, as received. |
237
+ | `handler` | `{ method, path, meta }` of the matched `requestHandlers` entry, or `undefined` for the fallback `callback`. |
238
+ | `requestPayloadBuffer` | The request body as received, as a `Buffer`. |
201
239
  | `req` | The raw `http.IncomingMessage`. |
202
240
  | `res` | The raw `http.ServerResponse`. |
203
241
  | `headers` | Request headers as received. |
@@ -227,6 +265,28 @@ path. Later sources override earlier ones in `request.params`. When this occurs,
227
265
  * Bodies larger than `maxBodySize` yield `413 Payload Too Large`.
228
266
  * Slow clients that exceed `bodyReadTimeoutMs` cause `408 Request Timeout`.
229
267
 
268
+ ## Path rewriting
269
+
270
+ `pathRewrite` receives the request path (without the query string) and returns
271
+ the path to use for matching handlers. Return `undefined` to keep the path as
272
+ it is. It is the place to strip a deployment prefix, so that one handler table
273
+ serves the same routes under several mount points:
274
+
275
+ ```javascript
276
+ const server = new ApiSrv({
277
+ port: 8808,
278
+ // /api/v1/users, /v1/users and /users all reach the '/users' handler
279
+ pathRewrite: (path) => path.replace(/^\/(api\/)?(v1\/)?/, '/'),
280
+ requestHandlers: { GET: { '/users': listUsers } }
281
+ });
282
+ ```
283
+
284
+ The function must be synchronous and must return a string that starts with
285
+ `/`; anything else, or a thrown error, results in HTTP 500. The dangerous path
286
+ check applies both to the path as received and to the rewritten one.
287
+ `request.url` holds the rewritten path and `request.originalUrl` the original.
288
+ Upgrade requests are rewritten in the same way.
289
+
230
290
  ## Authentication and upgrades
231
291
 
232
292
  Before a handler runs, `authCallback` is awaited with the request object. During
@@ -254,6 +314,65 @@ status text in the `message` property, for example:
254
314
  Additional context is appended in parentheses for 400-series validation errors,
255
315
  matching the format `"Bad Request (detailed reason)"`.
256
316
 
317
+ ### Custom error responses
318
+
319
+ Set `errorCallback` to answer these errors in your own format. It is called
320
+ with one object for every error response that `tr-apisrv` generates itself:
321
+
322
+ | Property | Description |
323
+ | --- | --- |
324
+ | `code` | The HTTP status the server would answer with. |
325
+ | `message` | The message of the default response, e.g. `Bad Request (detailed reason)`. |
326
+ | `detail` | The detail alone, when there is one. |
327
+ | `source` | What produced the error: `request` (malformed request, dangerous path, unsupported method), `limit` (body too large, read timeout), `parser` (unparsable or unacceptable body or parameters), `validator` (a parameter validator threw or returned a non-object), `router` (no handler: 404 or 405, or a failing `pathRewrite`), `handler` (the handler threw). |
328
+ | `stage` | For `validator`: which validator, e.g. `request parameters`. |
329
+ | `cause` | For `validator` and `handler`: the error that was thrown. A validator can attach anything to it, such as a list of problems. |
330
+ | `req`, `res` | The raw request and response. |
331
+ | `request` | The request wrapper. Depending on how far the request got, some of its properties are not set yet. |
332
+
333
+ Send the response and return a truthy value. Return a falsy value to let the
334
+ server send its default response; it does that too when the callback throws
335
+ or leaves the response unsent.
336
+
337
+ ```javascript
338
+ const server = new ApiSrv({
339
+ port: 8808,
340
+ errorCallback: (error) => {
341
+ const body = { status: 'error', code: error.code, message: error.message };
342
+ if (error.source === 'validator' && error.cause && error.cause.problems) {
343
+ body.problems = error.cause.problems;
344
+ }
345
+ error.res.writeHead(error.code, { 'Content-Type': 'application/json; charset=utf-8' });
346
+ error.res.end(JSON.stringify(body));
347
+ return true;
348
+ },
349
+ requestHandlers: {
350
+ POST: {
351
+ '/items': {
352
+ callback: createItem,
353
+ options: {
354
+ paramsValidator: (params) => {
355
+ const problems = checkItem(params);
356
+ if (problems.length > 0) {
357
+ const err = new Error('Invalid item');
358
+ err.problems = problems;
359
+ throw err;
360
+ }
361
+ return params;
362
+ }
363
+ }
364
+ }
365
+ }
366
+ }
367
+ });
368
+ ```
369
+
370
+ The callback may be asynchronous. For errors raised while the request is still
371
+ being read (`limit`, and some of `request`) the connection is closed right
372
+ after the error, so respond synchronously for those. Responses that a handler
373
+ sends with `request.errorResponse()` or `request.jsonResponse()` do not go
374
+ through the callback.
375
+
257
376
  Handlers remain free to craft any response, including non-JSON payloads, by using
258
377
  `request.res` directly. The convenience method `jsonResponse` is suitable for
259
378
  most use cases:
@@ -279,6 +398,55 @@ const srv = new ApiSrv({
279
398
  });
280
399
  ```
281
400
 
401
+ ### Parameter names
402
+
403
+ A parameter named `__proto__` is an ordinary own property of
404
+ `request.params`; it never replaces the prototype of the object. A JSON body
405
+ can nevertheless carry keys such as `__proto__` or `constructor` at any depth,
406
+ and code that later copies such objects with `Object.assign` or a recursive
407
+ merge can be tricked by them. If your API has no use for those names, reject
408
+ them outright:
409
+
410
+ ```javascript
411
+ const srv = new ApiSrv({
412
+ port: 8808,
413
+ rejectDangerousParamNames: true, // 400 for __proto__, constructor, prototype keys
414
+ requireObjectBody: true, // 400 for a JSON array as the body
415
+ callback: handler
416
+ });
417
+ ```
418
+
419
+ Without `requireObjectBody`, the items of a JSON array body become the
420
+ parameters `"0"`, `"1"` and so on.
421
+
422
+ ### Response headers
423
+
424
+ JSON responses, including errors, carry `X-Content-Type-Options: nosniff`.
425
+
426
+ ## Changes in 3.0.0
427
+
428
+ Version 3.0.0 is backwards compatible with 2.1.0: every existing option,
429
+ method and default behaves as before. New:
430
+
431
+ * `errorCallback`, for answering server-generated errors in your own format.
432
+ * `pathRewrite`, and `request.originalUrl`.
433
+ * Handler options `authCallback` and `meta`, and `request.handler`.
434
+ * `requestHandlerList()`.
435
+ * `requireObjectBody` and `rejectDangerousParamNames`.
436
+
437
+ Fixes and hardening that apply without any configuration:
438
+
439
+ * A parameter named `__proto__` in a JSON body used to become the prototype of
440
+ `request.params`, so that its contents appeared as parameters that were not
441
+ own properties. It is now an own property like any other.
442
+ * `__proto__` is rejected as a path template parameter name.
443
+ * A request target that is not a path (for example an absolute URL, when
444
+ `rejectDangerousPaths` is off) matched against `requestHandlers` used to
445
+ end in HTTP 500. It now matches nothing: 404, or the fallback `callback`.
446
+ * JSON responses carry `X-Content-Type-Options: nosniff`.
447
+ * The request body is assembled once instead of being copied for every chunk
448
+ received.
449
+
282
450
  ## License
283
451
 
284
452
  MIT