tr-apisrv 0.1.5 → 1.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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License
2
2
 
3
- Copyright © 2018 Timo J. Rinne <tri@iki.fi>
3
+ Copyright © 2018-2025 Timo J. Rinne <tri@iki.fi>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person
6
6
  obtaining a copy of this software and associated documentation
package/MIT-RINNE CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License
2
2
 
3
- Copyright © 2018 Timo J. Rinne <tri@iki.fi>
3
+ Copyright © 2018-2025 Timo J. Rinne <tri@iki.fi>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person
6
6
  obtaining a copy of this software and associated documentation
package/README.md CHANGED
@@ -5,6 +5,8 @@ This is a simple API server providing with ability to easily create
5
5
  JSON API servers. Accepts also calls in www-form-urlencoded form
6
6
  and treats them identically to flat JSON key-value structure.
7
7
 
8
+ Requires Node.js 18 or newer.
9
+
8
10
  ```
9
11
  const ApiSrv = require('tr-apisrv');
10
12
 
@@ -14,6 +16,7 @@ var srv = new ApiSrv({ port: 8808,
14
16
  authCallback: authCb,
15
17
  prettyPrintJsonResponses: true,
16
18
  bodyReadTimeoutMs: 5000,
19
+ maxBodySize: 1024 * 1024,
17
20
  debug: true });
18
21
 
19
22
  async function authCb(r) {
@@ -21,12 +24,68 @@ async function authCb(r) {
21
24
  }
22
25
 
23
26
  async function cb(r) {
24
- var res = r.res;
25
- delete r.res;
26
27
  r.jsonResponse(r, 200);
27
28
  }
28
29
  ```
29
30
 
31
+ Examples
32
+ ========
33
+
34
+ GET handler with path parameter
35
+ -------------------------------
36
+
37
+ ```javascript
38
+ async function cb(r) {
39
+ if (r.method === 'GET') {
40
+ // Match URL like /user/123 and capture the id
41
+ const m = r.url.match(/^\/user\/([^/]+)$/);
42
+ if (m) {
43
+ const id = m[1];
44
+ // r.params contains parsed query string values
45
+ return r.jsonResponse({ id, params: r.params });
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ POST handler with JSON body
52
+ ---------------------------
53
+
54
+ ```javascript
55
+ async function cb(r) {
56
+ if (r.method === 'POST') {
57
+ // Match URL like /user/123 and capture the id
58
+ const m = r.url.match(/^\/user\/([^/]+)$/);
59
+ if (m) {
60
+ const id = m[1];
61
+ // Body is already parsed into r.params
62
+ return r.jsonResponse({ id, received: r.params });
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ Non‑JSON response
69
+ -----------------
70
+
71
+ Sometimes a handler may need to send a plain text or other custom response.
72
+ The underlying `http.ServerResponse` is available as `r.res`:
73
+
74
+ ```javascript
75
+ async function cb(r) {
76
+ if (r.url === '/plaintext') {
77
+ r.res.writeHead(200, { 'Content-Type': 'text/plain' });
78
+ r.res.end('ok');
79
+ return;
80
+ }
81
+ // default JSON response
82
+ return r.jsonResponse({ ok: true });
83
+ }
84
+ ```
85
+
86
+ `maxBodySize` limits the size of accepted request bodies in bytes. Requests exceeding
87
+ the limit are terminated with HTTP status 413. The default limit is 1 MiB.
88
+
30
89
  Author
31
90
  ======
32
91
 
package/index.js CHANGED
@@ -2,304 +2,415 @@
2
2
 
3
3
  const http = require('http');
4
4
  const https = require('https');
5
- const qs = require('querystring')
5
+ function parseQuery(str) {
6
+ const params = Object.create(null);
7
+ if (!str) {
8
+ return params;
9
+ }
10
+ const usp = new URLSearchParams(str.replace(/\+/g, '%20'));
11
+ for (const [key, value] of usp.entries()) {
12
+ if (Object.prototype.hasOwnProperty.call(params, key)) {
13
+ const cur = params[key];
14
+ if (Array.isArray(cur)) {
15
+ cur.push(value);
16
+ } else {
17
+ params[key] = [cur, value];
18
+ }
19
+ } else {
20
+ params[key] = value;
21
+ }
22
+ }
23
+ return params;
24
+ }
25
+
26
+ function parseContentType(str) {
27
+ const parts = str.split(';').map(p => p.trim()).filter(p => p !== '');
28
+ if (parts.length === 0) {
29
+ return null;
30
+ }
31
+ const type = parts.shift().toLowerCase();
32
+ const params = Object.create(null);
33
+ for (const part of parts) {
34
+ const m = part.match(/^([!#$%&'*+.^_`|~0-9A-Za-z-]+)=((?:"(?:[^"\\]|\\.)*"|[^\s;]+))$/);
35
+ if (!m) {
36
+ return null;
37
+ }
38
+ let val = m[2];
39
+ if (val.startsWith('"')) {
40
+ val = val.slice(1, -1);
41
+ }
42
+ params[m[1].toLowerCase()] = val.toLowerCase();
43
+ }
44
+ return { type, params };
45
+ }
6
46
 
7
47
  var ApiSrv = function(opts) {
8
- var proto = http;
9
- var srvOpts = {};
10
- if (! (opts && (typeof(opts) === 'object'))) {
11
- throw new Error('Bad opts for ApiSrv constructor');
12
- }
13
- if (opts.key && opts.cert) {
14
- srvOpts.key = opts.key;
15
- srvOpts.cert = opts.cert;
16
- proto = https;
17
- } else if (opts.key) {
18
- throw new Error('Key defined without cert');
19
- } else if (opts.cert) {
20
- throw new Error('Cert defined without key');
21
- }
22
- this.debug = opts.debug ? true : false;
23
- this.prettyPrintJsonResponses = opts.prettyPrintJsonResponses ? true : false;
24
- if (Number.isSafeInteger(opts.port) && (opts.port > 0) && (opts.port < 65536)) {
25
- this.port = opts.port;
26
- } else {
27
- throw new Error('Bad port for ApiSrv constructor');
28
- }
29
- if (typeof(opts.address) === 'string') {
30
- this.address = opts.address;
31
- } else if (opts.address) {
32
- throw new Error('Bad address for ApiSrv constructor');
33
- }
34
- if (typeof(opts.callback) === 'function') {
35
- this.callback = opts.callback;
36
- } else {
37
- throw new Error('Bad callback for ApiSrv constructor');
38
- }
39
- if ((opts.authCallback !== undefined) && (opts.authCallback !== null)) {
40
- if (typeof(opts.authCallback) === 'function') {
41
- this.authCallback = opts.authCallback;
42
- } else {
43
- throw new Error('Bad authCallback for ApiSrv constructor');
44
- }
45
- } else {
46
- if (this.debug) {
47
- console.log('No authentication callback set.');
48
- }
49
- this.authCallback = function(r) { return true; }.bind(this);
50
- }
51
- if ((opts.upgradeCallback !== undefined) && (opts.upgradeCallback !== null)) {
52
- if (typeof(opts.upgradeCallback) === 'function') {
53
- this.upgradeCallback = opts.upgradeCallback;
54
- } else {
55
- throw new Error('Bad upgradeCallback for ApiSrv constructor');
56
- }
57
- } else {
58
- this.upgradeCallback = undefined
59
- }
60
- if ((opts.bodyReadTimeoutMs !== undefined) && (opts.bodyReadTimeoutMs !== null)) {
61
- if (Number.isSafeInteger(opts.bodyReadTimeoutMs) && (opts.bodyReadTimeoutMs > 0)) {
62
- this.bodyReadTimeoutMs = opts.bodyReadTimeoutMs;
63
- } else {
64
- throw new Error('Bad bodyReadTimeoutMs for ApiSrv constructor');
65
- }
66
- } else {
67
- this.bodyReadTimeoutMs = 2 * 1000;
68
- }
69
- srvOpts.headersTimeout = this.bodyReadTimeoutMs;
70
- srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
48
+ var proto = http;
49
+ var srvOpts = {};
50
+ if (!(opts && (typeof(opts) === 'object'))) {
51
+ throw new Error(`Bad opts for ApiSrv constructor: ${opts}`);
52
+ }
53
+ if (opts.key && opts.cert) {
54
+ srvOpts.key = opts.key;
55
+ srvOpts.cert = opts.cert;
56
+ proto = https;
57
+ } else if (opts.key) {
58
+ throw new Error('Key defined without cert');
59
+ } else if (opts.cert) {
60
+ throw new Error('Cert defined without key');
61
+ }
62
+ this.debug = opts.debug ? true : false;
63
+ this.prettyPrintJsonResponses = opts.prettyPrintJsonResponses ? true : false;
64
+ if (Number.isSafeInteger(opts.port) && (opts.port > 0) && (opts.port < 65536)) {
65
+ this.port = opts.port;
66
+ } else {
67
+ throw new Error(`Bad port for ApiSrv constructor: ${opts.port}`);
68
+ }
69
+ if (typeof(opts.address) === 'string') {
70
+ this.address = opts.address;
71
+ } else if (opts.address) {
72
+ throw new Error(`Bad address for ApiSrv constructor: ${opts.address}`);
73
+ }
74
+ if (typeof(opts.callback) === 'function') {
75
+ this.callback = opts.callback;
76
+ } else {
77
+ throw new Error(`Bad callback for ApiSrv constructor: ${opts.callback}`);
78
+ }
79
+ if ((opts.authCallback !== undefined) && (opts.authCallback !== null)) {
80
+ if (typeof(opts.authCallback) === 'function') {
81
+ this.authCallback = opts.authCallback;
82
+ } else {
83
+ throw new Error(`Bad authCallback for ApiSrv constructor: ${opts.authCallback}`);
84
+ }
85
+ } else {
86
+ if (this.debug) {
87
+ console.log('No authentication callback set.');
88
+ }
89
+ this.authCallback = function(r) { return true; }.bind(this);
90
+ }
91
+ if ((opts.upgradeCallback !== undefined) && (opts.upgradeCallback !== null)) {
92
+ if (typeof(opts.upgradeCallback) === 'function') {
93
+ this.upgradeCallback = opts.upgradeCallback;
94
+ } else {
95
+ throw new Error(`Bad upgradeCallback for ApiSrv constructor: ${opts.upgradeCallback}`);
96
+ }
97
+ } else {
98
+ this.upgradeCallback = undefined
99
+ }
100
+ if ((opts.bodyReadTimeoutMs !== undefined) && (opts.bodyReadTimeoutMs !== null)) {
101
+ if (Number.isSafeInteger(opts.bodyReadTimeoutMs) && (opts.bodyReadTimeoutMs > 0)) {
102
+ this.bodyReadTimeoutMs = opts.bodyReadTimeoutMs;
103
+ } else {
104
+ throw new Error(`Bad bodyReadTimeoutMs for ApiSrv constructor: ${opts.bodyReadTimeoutMs}`);
105
+ }
106
+ } else {
107
+ this.bodyReadTimeoutMs = 2 * 1000;
108
+ }
109
+ if ((opts.maxBodySize !== undefined) && (opts.maxBodySize !== null)) {
110
+ if (Number.isSafeInteger(opts.maxBodySize) && (opts.maxBodySize >= 0)) {
111
+ this.maxBodySize = opts.maxBodySize;
112
+ } else {
113
+ throw new Error(`Bad maxBodySize for ApiSrv constructor: ${opts.maxBodySize}`);
114
+ }
115
+ } else {
116
+ this.maxBodySize = 1024 * 1024;
117
+ }
118
+ srvOpts.headersTimeout = this.bodyReadTimeoutMs;
119
+ srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
120
+
121
+ var upgradeCb = async function(req, s, head) {
122
+ var m, r = {};
123
+ r.method = req.method;
124
+ if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
125
+ r.url = m[1];
126
+ r.params = parseQuery(m[2].toString('utf8'));
127
+ } else {
128
+ r.url = req.url;
129
+ r.params = {};
130
+ }
131
+ r.headers = req.headers;
132
+ r.req = req;
133
+ try {
134
+ const ret = await this.authCallback(r);
135
+ if (ret) {
136
+ r.head = head;
137
+ r.s = s;
138
+ const cbRet = await opts.upgradeCallback(r);
139
+ if (cbRet && this.debug) {
140
+ console.log('Upgrade successfully processed (resource :' + r.url + ').');
141
+ }
142
+ return cbRet;
143
+ } else {
144
+ s.destroy();
145
+ s = undefined;
146
+ return false;
147
+ }
148
+ } catch (e) {
149
+ if (s) {
150
+ try {
151
+ s.destroy();
152
+ s = undefined;
153
+ } catch(ignored) {
154
+ s = undefined;
155
+ }
156
+ }
157
+ return false;
158
+ }
159
+ }.bind(this);
160
+ var requestCb = function(req, res) {
161
+ var completed = false, body = Buffer.alloc(0), r = {}, timeout, bodySize = 0;
162
+ var contentType, contentTypeArgs;
163
+ var declaredContentLength;
164
+ if (req.headers['transfer-encoding'] && req.headers['content-length']) {
165
+ error(res, 400, 'Both Transfer-Encoding and Content-Length defined.');
166
+ return;
167
+ }
168
+ if (req.headers['content-length']) {
169
+ var cl = parseInt(req.headers['content-length'], 10);
170
+ if (!Number.isSafeInteger(cl) || cl < 0) {
171
+ error(res, 400, 'Bad Content-Length header.');
172
+ return;
173
+ }
174
+ declaredContentLength = cl;
175
+ if (this.maxBodySize && (cl > this.maxBodySize)) {
176
+ error(res, 413, 'Request body too large.');
177
+ try {
178
+ req.destroy();
179
+ } catch (ignored) {
180
+ }
181
+ return;
182
+ }
183
+ }
184
+ var dataCb = function(data) {
185
+ if (completed) {
186
+ return;
187
+ }
188
+ bodySize += data.length;
189
+ if (declaredContentLength !== undefined && (bodySize > declaredContentLength)) {
190
+ completed = true;
191
+ if (timeout) {
192
+ clearTimeout(timeout);
193
+ timeout = undefined;
194
+ }
195
+ error(res, 400, 'Request body longer than Content-Length.');
196
+ try {
197
+ req.destroy();
198
+ } catch (ignored) {
199
+ }
200
+ return;
201
+ }
202
+ if (this.maxBodySize && (bodySize > this.maxBodySize)) {
203
+ completed = true;
204
+ if (timeout) {
205
+ clearTimeout(timeout);
206
+ timeout = undefined;
207
+ }
208
+ error(res, 413, 'Request body too large.');
209
+ try {
210
+ req.destroy();
211
+ } catch (ignored) {
212
+ }
213
+ return;
214
+ }
215
+ body = Buffer.concat( [ body, data ] );
216
+ }.bind(this);
217
+ var endCb = async function() {
218
+ if (completed) {
219
+ return;
220
+ }
221
+ completed = true;
222
+ if (timeout) {
223
+ clearTimeout(timeout);
224
+ timeout = undefined;
225
+ }
226
+ if (declaredContentLength !== undefined && (body.length !== declaredContentLength)) {
227
+ error(res, 400, 'Request body length does not match Content-Length.');
228
+ return;
229
+ }
230
+ if (req.headers['content-type']) {
231
+ let ct = parseContentType(req.headers['content-type']);
232
+ if (ct) {
233
+ contentType = ct.type;
234
+ contentTypeArgs = ct.params;
235
+ } else {
236
+ error(res, 400, 'Unable to parse content-type.');
237
+ return;
238
+ }
239
+ }
240
+ switch (req.method) {
241
+ case 'POST':
242
+ case 'PUT':
243
+ if (req.url.match(/\?/)) {
244
+ error(res, 400, 'URL for POST or PUT must not contain query parameters.');
245
+ return;
246
+ }
247
+ r.url = req.url;
248
+ r.method = req.method;
249
+ switch (contentType) {
250
+ case 'application/x-www-form-urlencoded':
251
+ case 'application/www-form-urlencoded':
252
+ r.params = parseQuery(body.toString('utf8'));
253
+ break;
254
+ case 'application/json':
255
+ if (contentTypeArgs && contentTypeArgs.charset && (contentTypeArgs.charset !== 'utf-8')) {
256
+ error(res, 400, 'Bad charset for JSON content type.');
257
+ return;
258
+ }
259
+ try {
260
+ r.params = JSON.parse(body.toString('utf8'));
261
+ } catch(e) {
262
+ r.params = undefined;
263
+ }
264
+ if (! (r.params && (typeof(r.params) === 'object'))) {
265
+ error(res, 400, 'Unable to parse JSON query parameters.');
266
+ return;
267
+ }
268
+ break;
269
+ case 'multipart/form-data':
270
+ // We know this, but only wankers would use it here.
271
+ // RFC6749 anyways says that application/x-www-form-urlencoded
272
+ // is the "correct" way to go.
273
+ default:
274
+ error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
275
+ return;
276
+ }
277
+ break;
278
+ case 'GET':
279
+ case 'DELETE':
280
+ if (body.length > 0) {
281
+ error(res, 400, 'Empty body required for ' + req.method + ' requests.');
282
+ return;
283
+ }
284
+ var m;
285
+ if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
286
+ r.url = m[1];
287
+ r.params = parseQuery(m[2].toString('utf8'));
288
+ } else {
289
+ r.url = req.url;
290
+ r.params = {};
291
+ }
292
+ r.method = req.method;
293
+ break;
294
+ default:
295
+ error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
296
+ return;
297
+ }
298
+ r.headers = req.headers;
299
+ r.res = res;
300
+ r.jsonResponse = function(data, code, excludeNoCacheHeaders) {
301
+ var headers = { 'Content-Type': 'application/json; charset=utf-8' };
302
+ if (! excludeNoCacheHeaders) {
303
+ headers = Object.assign(headers,
304
+ { 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
305
+ 'Expires': 'Wed, 01 Jan 2020 12:00:00 GMT',
306
+ 'Pragma': 'no-cache' });
307
+ }
308
+ res.writeHead(code ? code : 200, headers);
309
+ if (this.prettyPrintJsonResponses) {
310
+ res.write(JSON.stringify(data, null, 2));
311
+ res.write("\n");
312
+ } else {
313
+ res.write(JSON.stringify(data));
314
+ }
315
+ res.end();
316
+ }.bind(this);
317
+ try {
318
+ const auth = await this.authCallback(r);
319
+ if (auth) {
320
+ const ret = await this.callback(r);
321
+ if (ret !== false && this.debug) {
322
+ console.log('Request successfully processed (resource :' + r.url + ').');
323
+ }
324
+ } else if (this.debug) {
325
+ console.log('Authentication failed (resource :' + r.url + ').');
326
+ }
327
+ } catch (e) {
328
+ if (this.debug) {
329
+ console.log(e);
330
+ }
331
+ try {
332
+ error(res, 500, 'Request handler fails to execute.');
333
+ } catch(e) {
334
+ }
335
+ }
336
+ }.bind(this);
337
+ var errorCb = function() {
338
+ if (completed) {
339
+ return;
340
+ }
341
+ completed = true;
342
+ if (timeout) {
343
+ clearTimeout(timeout);
344
+ timeout = undefined;
345
+ }
346
+ error(res, 400, 'Error occured while reading the request data.');
347
+ }.bind(this);
348
+ var timeoutCb = function() {
349
+ if (completed) {
350
+ return;
351
+ }
352
+ timeout = undefined;
353
+ completed = true;
354
+ error(res, 408, 'Timeout occured while reading the request data.');
355
+ }.bind(this);
356
+ timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
357
+ req.on('data', dataCb);
358
+ req.on('end', endCb);
359
+ req.on('error', errorCb);
360
+ }.bind(this);
361
+ var error = function(res, code, text, RFC6749EC) {
362
+ if (RFC6749EC) {
363
+ // RFC6749 wants these errors to be code 400 except in case of 401
364
+ res.writeHead((code != 401) ? 400 : 401,
365
+ { 'Content-Type': 'application/json; charset=utf-8' });
366
+ res.write(JSON.stringify( { error: RFC6749EC,
367
+ error_description: (text ?
368
+ (text +
369
+ ' (HTTP code ' +
370
+ code.toString() +
371
+ ')') :
372
+ ('HTTP code ' +
373
+ code.toString())) },
374
+ null, 2));
375
+
376
+ res.write("\n");
377
+ } else {
378
+ res.writeHead(code, { 'Content-Type': 'text/plain' });
379
+ res.write(text);
380
+ res.write("\n");
381
+ }
382
+ res.end();
383
+ }.bind(this);
384
+ this.server = proto.createServer(srvOpts, requestCb);
385
+ if (this.upgradeCallback) {
386
+ this.server.on('upgrade', upgradeCb);
387
+ }
388
+ this.server.on('error', (e) => {
389
+ const addr = (this.address !== undefined) ? ` address: ${this.address}` : '';
390
+ console.log(`Unable to start HTTP server (port: ${this.port}${addr})`);
391
+ if (this.debug && e) {
392
+ console.log(e);
393
+ }
394
+ process.exit(1);
395
+ });
396
+ this.server.headersTimeout = this.bodyReadTimeoutMs;
397
+ this.server.requestTimeout = this.bodyReadTimeoutMs + 1;
398
+ this.server.listen(this.port, this.address);
399
+ };
71
400
 
72
- var upgradeCb = function(req, s, head) {
73
- var m, r = {};
74
- r.method = req.method;
75
- if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
76
- r.url = m[1];
77
- if (! (r.params = qs.parse(m[2].toString('utf8')))) {
78
- s.end();
79
- return;
80
- }
81
- } else {
82
- r.url = req.url;
83
- r.params = {};
84
- }
85
- r.headers = req.headers;
86
- r.req = req;
87
- return (Promise.resolve(this.authCallback(r))
88
- .then(function(ret) {
89
- if (ret) {
90
- r.head = head;
91
- r.s = s;
92
- return opts.upgradeCallback(r);
93
- } else {
94
- s.destroy();
95
- s = undefined;
96
- }
97
- }.bind(this))
98
- .then(function(ret) {
99
- if (ret !== false) {
100
- if (this.debug) {
101
- console.log('Upgrade successfully processed (resource :' + r.url + ').');
102
- }
103
- }
104
- }.bind(this))
105
- .catch(function(e) {
106
- if (s) {
107
- try {
108
- s.destroy();
109
- s = undefined;
110
- } catch(ignored) {
111
- s = undefined;
112
- }
113
- return false;
114
- }
115
- }.bind(this)));
116
- }.bind(this);
117
- var requestCb = function(req, res) {
118
- var completed = false, body = Buffer.alloc(0), r = {}, timeout;
119
- var contentType, contentTypeArgs;
120
- var dataCb = function(data) {
121
- if (completed) {
122
- return;
123
- }
124
- body = Buffer.concat( [ body, data ] );
125
- }.bind(this);
126
- var endCb = function() {
127
- if (completed) {
128
- return;
129
- }
130
- completed = true;
131
- if (timeout) {
132
- clearTimeout(timeout);
133
- timeout = undefined;
134
- }
135
- if (req.headers['content-type']) {
136
- let m = req.headers['content-type'].match(/^\s*([^\s;]+)\s*(|;\s*(|.*[^\s]))\s*$/);
137
- if (m) {
138
- contentType = m[1];
139
- contentTypeArgs = (m[3] && m[3] !== '') ? m[3] : undefined;
140
- } else {
141
- error(res, 400, 'Unable to parse content-type.');
142
- return;
143
- }
144
- }
145
- switch (req.method) {
146
- case 'POST':
147
- case 'PUT':
148
- if (req.url.match(/\?/)) {
149
- error(res, 400, 'URL for POST or PUT must not contain query parameters.');
150
- return;
151
- }
152
- r.url = req.url;
153
- r.method = req.method;
154
- switch (contentType) {
155
- case 'application/x-www-form-urlencoded':
156
- case 'application/www-form-urlencoded':
157
- if (! (r.params = qs.parse(body.toString('utf8')))) {
158
- error(res, 400, 'Unable to parse query parameters.');
159
- return;
160
- }
161
- break;
162
- case 'application/json':
163
- if (contentTypeArgs && (contentTypeArgs.toLowerCase() !== 'charset=utf-8')) {
164
- error(res, 400, 'Bad charset for JSON content type.');
165
- }
166
- try {
167
- r.params = JSON.parse(body.toString('utf8'));
168
- } catch(e) {
169
- r.params = undefined;
170
- }
171
- if (! (r.params && (typeof(r.params) === 'object'))) {
172
- error(res, 400, 'Unable to parse JSON query parameters.');
173
- return;
174
- }
175
- break;
176
- case 'multipart/form-data':
177
- // We know this, but only wankers would use it here.
178
- // RFC6749 anyways says that application/x-www-form-urlencoded
179
- // is the "correct" way to go.
180
- default:
181
- error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
182
- return;
183
- }
184
- break;
185
- case 'GET':
186
- case 'DELETE':
187
- if (body.length > 0) {
188
- error(res, 400, 'Empty body required for ' + req.method + ' requests.');
189
- return;
190
- }
191
- var m;
192
- if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
193
- r.url = m[1];
194
- if (! (r.params = qs.parse(m[2].toString('utf8')))) {
195
- error(res, 400, 'Unable to parse query parameters.');
196
- return;
197
- }
198
- } else {
199
- r.url = req.url;
200
- r.params = {};
201
- }
202
- r.method = req.method;
203
- break;
204
- default:
205
- error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
206
- return;
207
- }
208
- r.headers = req.headers;
209
- r.res = res;
210
- r.jsonResponse = function(data, code) {
211
- res.writeHead(code ? code : 200, { 'Content-Type': 'application/json; charset=utf-8' });
212
- if (this.prettyPrintJsonResponses) {
213
- res.write(JSON.stringify(data, null, 2));
214
- res.write("\n");
215
- } else {
216
- res.write(JSON.stringify(data));
217
- }
218
- res.end();
219
- }.bind(this);
220
- return (Promise.resolve(this.authCallback(r))
221
- .then(function(ret) {
222
- if (ret) {
223
- return this.callback(r);
224
- } else if (this.debug) {
225
- console.log('Authentication failed (resource :' + r.url + ').');
226
- }
227
- return false;
228
- }.bind(this))
229
- .then(function(ret) {
230
- if (ret !== false) {
231
- if (this.debug) {
232
- console.log('Request successfully processed (resource :' + r.url + ').');
233
- }
234
- }
235
- }.bind(this))
236
- .catch(function(e) {
237
- if (this.debug) {
238
- console.log(e);
239
- }
240
- try {
241
- error(res, 500, 'Request handler fails to execute.');
242
- } catch(e) {
243
- }
244
- }.bind(this)));
245
- }.bind(this);
246
- var errorCb = function() {
247
- if (completed) {
248
- return;
249
- }
250
- completed = true;
251
- if (timeout) {
252
- clearTimeout(timeout);
253
- timeout = undefined;
254
- }
255
- error(res, 400, 'Error occured while reading the request data.');
256
- }.bind(this);
257
- var timeoutCb = function() {
258
- if (completed) {
259
- return;
260
- }
261
- timeout = undefined;
262
- completed = true;
263
- error(res, 408, 'Timeout occured while reading the request data.');
264
- }.bind(this);
265
- timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
266
- req.on('data', dataCb);
267
- req.on('end', endCb);
268
- req.on('error', errorCb);
269
- }.bind(this);
270
- var error = function(res, code, text, RFC6749EC) {
271
- if (RFC6749EC) {
272
- // RFC6749 wants these errors to be code 400 except in case of 401
273
- res.writeHead((code != 401) ? 400 : 401,
274
- { 'Content-Type': 'application/json; charset=utf-8' });
275
- res.write(JSON.stringify( { error: RFC6749EC,
276
- error_description: (text ?
277
- (text +
278
- ' (HTTP code ' +
279
- code.toString() +
280
- ')') :
281
- ('HTTP code ' +
282
- code.toString())) },
283
- null, 2));
284
-
285
- res.write("\n");
286
- } else {
287
- res.writeHead(code, { 'Content-Type': 'text/plain' });
288
- res.write(text);
289
- res.write("\n");
290
- }
291
- res.end();
292
- }.bind(this);
293
- this.server = proto.createServer(srvOpts, requestCb);
294
- if (this.upgradeCallback) {
295
- this.server.on('upgrade', upgradeCb);
296
- }
297
- this.server.on('error', function(e) {
298
- console.log('Unable to start HTTP server');
299
- process.exit(1);
300
- });
301
- this.server.headersTimeout = 2000;
302
- this.server.listen(this.port, this.address);
401
+ ApiSrv.prototype.close = function() {
402
+ return new Promise((resolve, reject) => {
403
+ this.server.close((err) => {
404
+ if (err) {
405
+ reject(err);
406
+ } else {
407
+ resolve();
408
+ }
409
+ });
410
+ });
303
411
  };
304
412
 
413
+ // Backward compatible shutdown helper
414
+ ApiSrv.prototype.shutdown = ApiSrv.prototype.close;
415
+
305
416
  module.exports = ApiSrv;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "tr-apisrv",
3
- "version": "0.1.5",
3
+ "version": "1.0.0",
4
4
  "description": "A simple asynchronous API server class",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
- "test": "node ./test/test.js"
7
+ "test": "node --test test/test.js"
8
8
  },
9
9
  "engines": {
10
- "node": ">=10.0.0"
10
+ "node": ">=18.0.0"
11
11
  },
12
12
  "dependencies": {
13
13
  },
package/test/test.js CHANGED
@@ -1,3 +1,262 @@
1
1
  'use strict';
2
- const x = require('../index');
3
- process.exit(0);
2
+
3
+ const { test } = require('node:test');
4
+ const assert = require('node:assert');
5
+ const http = require('http');
6
+ const net = require('net');
7
+ const ApiSrv = require('..');
8
+
9
+ function httpRequest(port, { method = 'GET', path = '/', headers = {}, body } = {}) {
10
+ return new Promise((resolve, reject) => {
11
+ const req = http.request({
12
+ port,
13
+ hostname: '127.0.0.1',
14
+ method,
15
+ path,
16
+ headers
17
+ }, (res) => {
18
+ let data = '';
19
+ res.on('data', (d) => data += d);
20
+ res.on('end', () => resolve({ status: res.statusCode, data }));
21
+ });
22
+ req.on('error', reject);
23
+ if (body) {
24
+ req.write(body);
25
+ }
26
+ req.end();
27
+ });
28
+ }
29
+
30
+ function rawRequest(port, raw) {
31
+ return new Promise((resolve, reject) => {
32
+ const socket = net.connect(port, '127.0.0.1');
33
+ let data = '';
34
+ socket.on('connect', () => socket.end(raw));
35
+ socket.on('data', (d) => data += d.toString());
36
+ socket.on('end', () => {
37
+ const m = data.match(/^HTTP\/1\.1\s+(\d+)/);
38
+ resolve(parseInt(m[1], 10));
39
+ });
40
+ socket.on('error', reject);
41
+ });
42
+ }
43
+
44
+ test('handles GET requests', async () => {
45
+ const port = 12350;
46
+ const srv = new ApiSrv({
47
+ port,
48
+ callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
49
+ });
50
+ try {
51
+ const res = await httpRequest(port, { method: 'GET', path: '/?a=1' });
52
+ assert.strictEqual(res.status, 200);
53
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'GET', params: { a: '1' } });
54
+ } finally {
55
+ await srv.shutdown();
56
+ }
57
+ });
58
+
59
+ test('handles POST requests', async () => {
60
+ const port = 12351;
61
+ const srv = new ApiSrv({
62
+ port,
63
+ callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
64
+ });
65
+ try {
66
+ const res = await httpRequest(port, {
67
+ method: 'POST',
68
+ path: '/',
69
+ headers: { 'Content-Type': 'application/json' },
70
+ body: JSON.stringify({ a: 1 })
71
+ });
72
+ assert.strictEqual(res.status, 200);
73
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'POST', params: { a: 1 } });
74
+ } finally {
75
+ await srv.shutdown();
76
+ }
77
+ });
78
+
79
+ test('handles PUT requests', async () => {
80
+ const port = 12352;
81
+ const srv = new ApiSrv({
82
+ port,
83
+ callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
84
+ });
85
+ try {
86
+ const res = await httpRequest(port, {
87
+ method: 'PUT',
88
+ path: '/',
89
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
90
+ body: 'a=1'
91
+ });
92
+ assert.strictEqual(res.status, 200);
93
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'PUT', params: { a: '1' } });
94
+ } finally {
95
+ await srv.shutdown();
96
+ }
97
+ });
98
+
99
+ test('handles DELETE requests', async () => {
100
+ const port = 12353;
101
+ const srv = new ApiSrv({
102
+ port,
103
+ callback: (r) => r.jsonResponse({ method: r.method, params: r.params })
104
+ });
105
+ try {
106
+ const res = await httpRequest(port, { method: 'DELETE', path: '/?a=1' });
107
+ assert.strictEqual(res.status, 200);
108
+ assert.deepStrictEqual(JSON.parse(res.data), { method: 'DELETE', params: { a: '1' } });
109
+ } finally {
110
+ await srv.shutdown();
111
+ }
112
+ });
113
+
114
+ test('authentication callback controls access', async () => {
115
+ const port = 12354;
116
+ let handled = 0;
117
+ let authCalls = 0;
118
+ const srv = new ApiSrv({
119
+ port,
120
+ callback: (r) => {
121
+ handled++;
122
+ r.jsonResponse({ ok: true });
123
+ },
124
+ authCallback: (r) => {
125
+ authCalls++;
126
+ return r.url !== '/deny';
127
+ }
128
+ });
129
+ try {
130
+ const okRes = await httpRequest(port, { method: 'GET', path: '/allow' });
131
+ assert.strictEqual(okRes.status, 200);
132
+ assert.strictEqual(handled, 1);
133
+ assert.strictEqual(authCalls, 1);
134
+
135
+ const unauthorized = new Promise((resolve, reject) => {
136
+ const req = http.request({ port, hostname: '127.0.0.1', method: 'GET', path: '/deny' });
137
+ req.on('response', (res) => {
138
+ res.resume();
139
+ res.on('end', resolve);
140
+ });
141
+ req.on('error', reject);
142
+ req.end();
143
+ setTimeout(() => req.destroy(), 50);
144
+ });
145
+ await assert.rejects(unauthorized);
146
+ assert.strictEqual(handled, 1);
147
+ assert.strictEqual(authCalls, 2);
148
+ } finally {
149
+ await srv.shutdown();
150
+ }
151
+ });
152
+
153
+ test('body read timeout returns 408', async () => {
154
+ const port = 12355;
155
+ const srv = new ApiSrv({
156
+ port,
157
+ bodyReadTimeoutMs: 50,
158
+ callback: () => {}
159
+ });
160
+ try {
161
+ const res = await new Promise((resolve, reject) => {
162
+ const req = http.request({
163
+ port,
164
+ method: 'POST',
165
+ path: '/',
166
+ hostname: '127.0.0.1'
167
+ }, (res) => {
168
+ let data = '';
169
+ res.on('data', (d) => data += d);
170
+ res.on('end', () => resolve({ status: res.statusCode, data }));
171
+ });
172
+ req.on('error', reject);
173
+ req.write('123'); // intentionally never calling end to trigger timeout
174
+ });
175
+ assert.strictEqual(res.status, 408);
176
+ assert.strictEqual(res.data, 'Timeout occured while reading the request data.\n');
177
+ } finally {
178
+ await srv.shutdown();
179
+ }
180
+ });
181
+
182
+ test('shutdown stops listening', async () => {
183
+ const port = 12356;
184
+ const srv = new ApiSrv({
185
+ port,
186
+ callback: () => {}
187
+ });
188
+ await new Promise((resolve) => srv.server.on('listening', resolve));
189
+ await srv.shutdown();
190
+ await assert.rejects(httpRequest(port, { method: 'GET', path: '/' }));
191
+ });
192
+
193
+ test('rejects requests exceeding Content-Length limit without reading body', async () => {
194
+ const port = 12357;
195
+ const srv = new ApiSrv({
196
+ port,
197
+ maxBodySize: 5,
198
+ callback: () => {}
199
+ });
200
+ try {
201
+ const status = await rawRequest(port,
202
+ 'POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: 10\r\n\r\n');
203
+ assert.strictEqual(status, 413);
204
+ } finally {
205
+ await srv.shutdown();
206
+ }
207
+ });
208
+
209
+ test('enforces Content-Length to match body length', async () => {
210
+ const port = 12358;
211
+ const srv = new ApiSrv({
212
+ port,
213
+ callback: () => {}
214
+ });
215
+ try {
216
+ const status = await rawRequest(port,
217
+ 'POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: 5\r\n\r\nabcd');
218
+ assert.strictEqual(status, 400);
219
+ } finally {
220
+ await srv.shutdown();
221
+ }
222
+ });
223
+
224
+ test('allows additional Content-Type parameters', async () => {
225
+ const port = 12359;
226
+ const srv = new ApiSrv({
227
+ port,
228
+ callback: (r) => r.jsonResponse(r.params)
229
+ });
230
+ try {
231
+ const res = await httpRequest(port, {
232
+ method: 'POST',
233
+ path: '/',
234
+ headers: { 'Content-Type': 'application/json; charset=utf-8; version=1' },
235
+ body: JSON.stringify({ a: 1 })
236
+ });
237
+ assert.strictEqual(res.status, 200);
238
+ assert.deepStrictEqual(JSON.parse(res.data), { a: 1 });
239
+ } finally {
240
+ await srv.shutdown();
241
+ }
242
+ });
243
+
244
+ test('rejects unsupported charset parameter', async () => {
245
+ const port = 12360;
246
+ const srv = new ApiSrv({
247
+ port,
248
+ callback: () => {}
249
+ });
250
+ try {
251
+ const res = await httpRequest(port, {
252
+ method: 'POST',
253
+ path: '/',
254
+ headers: { 'Content-Type': 'application/json; charset=iso-8859-1' },
255
+ body: JSON.stringify({ a: 1 })
256
+ });
257
+ assert.strictEqual(res.status, 400);
258
+ } finally {
259
+ await srv.shutdown();
260
+ }
261
+ });
262
+