lien 4.0.0 → 5.0.1

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/lib/lien.js ADDED
@@ -0,0 +1,539 @@
1
+ import path from "node:path";
2
+ import { realpath } from "node:fs/promises";
3
+ import { promisify } from "node:util";
4
+ import toBuffer from "./to-buffer.js";
5
+ import { asError, getData, mergeData } from "./utils.js";
6
+
7
+ /**
8
+ * @typedef {object} ResponseData
9
+ * @property {*} content The response body, mutated in place by after hooks.
10
+ * @property {number} status The HTTP status.
11
+ * @property {string} [contentType] The content type, inferred from content when omitted.
12
+ * @property {Object<string, *>} headers Additional response headers.
13
+ * @property {LienObj} lien The request producing the response.
14
+ */
15
+
16
+ /**
17
+ * Marks requests whose error responses must bypass after hooks.
18
+ * @private
19
+ * @type {symbol}
20
+ */
21
+ export const hookError = Symbol("lien hook error");
22
+
23
+ /**
24
+ * LienObj
25
+ * Request and response helpers.
26
+ *
27
+ * @property {object} req The Express request.
28
+ * @property {object} res The Express response.
29
+ * @property {import("./server.js").default} server The Lien server.
30
+ * @property {string} path The request path with its trailing slash removed, except for root.
31
+ * @property {string} pathname The mounted request pathname.
32
+ * @property {string} full_path The original URL, including its query string.
33
+ * @property {string} host The request hostname.
34
+ * @property {string} protocol The request protocol.
35
+ * @property {string} domain The origin, including the Host header's port.
36
+ * @property {string} href The origin and original URL.
37
+ * @property {string} method The lowercase HTTP method.
38
+ * @property {Object<string, *>} params The decoded route parameters.
39
+ * @property {Object<string, *>} query The parsed query parameters.
40
+ * @property {*} data The parsed request body.
41
+ * @property {Object<string, *>} cookies The parsed cookies.
42
+ * @property {object|undefined} session The current session, when enabled.
43
+ * @property {Function} accepts Express content negotiation, bound to the request.
44
+ */
45
+ export default class LienObj {
46
+
47
+ /**
48
+ * Creates the request object passed to route handlers and before hooks.
49
+ *
50
+ * @param {object} req The Express request.
51
+ * @param {object} res The Express response.
52
+ * @param {Function} next The next Express middleware.
53
+ * @param {import("./server.js").default} server The Lien server.
54
+ */
55
+ constructor (req, res, next, server) {
56
+ this.req = req;
57
+ this.res = res;
58
+ this.server = server;
59
+ /**
60
+ * The next Express middleware for this request.
61
+ *
62
+ * @private
63
+ * @type {Function}
64
+ */
65
+ this._next = next;
66
+ /**
67
+ * Whether this request has already delegated to Express.
68
+ *
69
+ * @private
70
+ * @type {boolean}
71
+ */
72
+ this._nextCalled = false;
73
+ /**
74
+ * Whether a response helper has claimed the response.
75
+ *
76
+ * @private
77
+ * @type {boolean}
78
+ */
79
+ this._ending = false;
80
+ this.path = req.path.replace(/\/$/, "") || "/";
81
+ this.accepts = req.accepts.bind(req);
82
+ this.host = req.hostname;
83
+ this.params = req.params;
84
+ this.query = req.query;
85
+ this.pathname = req.baseUrl + req.path;
86
+ this.full_path = req.originalUrl;
87
+ this.method = req.method.toLowerCase();
88
+ this.cookies = req.cookies ?? {};
89
+ this.data = req.body;
90
+ this.session = req.session;
91
+ this.protocol = req.protocol;
92
+ this.domain = `${req.protocol}://${req.get("host")}`;
93
+ this.href = `${this.domain}${req.originalUrl}`;
94
+ }
95
+
96
+ /**
97
+ * Returns a CSRF token, or an empty string when CSRF is disabled.
98
+ *
99
+ * @returns {string}
100
+ */
101
+ get csrfToken () {
102
+ return this.req.csrfToken?.() ?? "";
103
+ }
104
+
105
+ /**
106
+ * Returns the hidden CSRF input, or an empty string when CSRF is disabled.
107
+ *
108
+ * @returns {string}
109
+ */
110
+ get csrfInput () {
111
+ return this.req.csrfToken ? `<input type="hidden" name="_csrf" value="${this.csrfToken}">` : "";
112
+ }
113
+
114
+ /**
115
+ * Delegates to Express once and cancels remaining hook execution.
116
+ *
117
+ * @param {Error|string} [error] An error or an Express routing directive.
118
+ * @param {*} [data] Additional data passed to the next middleware.
119
+ * @returns {LienObj} This request object.
120
+ */
121
+ next (error, data) {
122
+ if (this._nextCalled) {
123
+ return this;
124
+ }
125
+ this._nextCalled = true;
126
+ this._beforeHooks?.abort();
127
+ this._afterHooks?.abort();
128
+ this._next(error, data);
129
+ return this;
130
+ }
131
+
132
+ /**
133
+ * Forwards a hook failure and prevents error responses from repeating after hooks.
134
+ *
135
+ * @private
136
+ * @param {*} error The failure reason.
137
+ * @returns {void}
138
+ */
139
+ _hookError (error) {
140
+ this.req[hookError] = true;
141
+ this.next(asError(error));
142
+ }
143
+
144
+ /**
145
+ * Claims the response so another helper cannot send it again.
146
+ *
147
+ * @private
148
+ * @returns {boolean} Whether this response may be sent.
149
+ */
150
+ _beginResponse () {
151
+ if (this._ending || this._nextCalled || this.res.headersSent || this.res.destroyed) {
152
+ return false;
153
+ }
154
+ this._ending = true;
155
+ return true;
156
+ }
157
+
158
+ /**
159
+ * Runs matching hooks and removes cancellation listeners when execution ends.
160
+ *
161
+ * @private
162
+ * @param {"before"|"after"} type The hook stage.
163
+ * @param {LienObj|ResponseData} data The request or pending response.
164
+ * @returns {Promise<void>}
165
+ * @throws {Error} If a hook fails.
166
+ */
167
+ async _runHooks (type, data) {
168
+ if (!this.server.options.transformers || this.req[hookError]) {
169
+ return;
170
+ }
171
+ const hooks = this.server.getHooks(type, this.path, this.method);
172
+ if (!hooks) {
173
+ return;
174
+ }
175
+ const controller = new AbortController();
176
+ const field = type === "before" ? "_beforeHooks" : "_afterHooks";
177
+ this[field] = controller;
178
+ const onClose = () => controller.abort();
179
+ this.res.once("close", onClose);
180
+ try {
181
+ await hooks.run(data, {
182
+ signal: controller.signal,
183
+ isStopped: () => this._nextCalled || this.res.headersSent || this.res.destroyed || type === "before" && this._ending
184
+ });
185
+ } finally {
186
+ this[field] = null;
187
+ this.res.removeListener("close", onClose);
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Redirects the client, optionally merging query parameters and preserving the fragment.
193
+ *
194
+ * @param {string} newUrl The redirect target.
195
+ * @param {boolean|Object<string, *>} [query] True copies the request query; an object overrides its values.
196
+ * @returns {LienObj} This request object.
197
+ */
198
+ redirect (newUrl, query) {
199
+ if (!this._beginResponse()) {
200
+ return this;
201
+ }
202
+ if (query) {
203
+ const hashIndex = newUrl.indexOf("#");
204
+ const hash = hashIndex < 0 ? "" : newUrl.slice(hashIndex);
205
+ const target = hashIndex < 0 ? newUrl : newUrl.slice(0, hashIndex);
206
+ const queryIndex = target.indexOf("?");
207
+ const base = queryIndex < 0 ? target : target.slice(0, queryIndex);
208
+ const params = new URLSearchParams(queryIndex < 0 ? "" : target.slice(queryIndex + 1));
209
+ const extra = {
210
+ ...this.query,
211
+ ...(query === true ? {} : query)
212
+ };
213
+ for (const [key, value] of Object.entries(extra)) {
214
+ params.delete(key);
215
+ for (const item of Array.isArray(value) ? value : [value]) {
216
+ params.append(key, item ?? "");
217
+ }
218
+ }
219
+ const encoded = params.toString();
220
+ newUrl = `${base}${encoded ? `?${encoded}` : ""}${hash}`;
221
+ }
222
+ this.res.redirect(newUrl);
223
+ return this;
224
+ }
225
+
226
+ /**
227
+ * Renders a template and sends it without after hooks. Failures are forwarded to Express.
228
+ *
229
+ * @param {string} template The template name.
230
+ * @param {object} [data] Template locals.
231
+ * @returns {Promise<void>} Resolves after rendering and initiating the response.
232
+ */
233
+ async render (template, data) {
234
+ if (!this._beginResponse()) {
235
+ return;
236
+ }
237
+ try {
238
+ const html = await promisify(this.res.render.bind(this.res))(template, data);
239
+ if (!this.res.destroyed && !this._nextCalled) {
240
+ this.res.send(html);
241
+ }
242
+ } catch (error) {
243
+ this.next(asError(error));
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Checks whether sessions are available and warns when they are disabled.
249
+ *
250
+ * @private
251
+ * @returns {boolean}
252
+ */
253
+ _checkSessionSupport () {
254
+ if (this.session) {
255
+ return true;
256
+ }
257
+ console.warn("You're trying to use a session feature, but you didn't enable the session support.");
258
+ return false;
259
+ }
260
+
261
+ /**
262
+ * Initializes or updates application data in the current session.
263
+ *
264
+ * @param {object} data The session data to merge.
265
+ * @returns {LienObj|undefined} This request object, or undefined when sessions are disabled.
266
+ */
267
+ startSession (data) {
268
+ return this.setSessionData(data);
269
+ }
270
+
271
+ /**
272
+ * Merges session data recursively without accepting prototype keys.
273
+ *
274
+ * @param {object} data New values; undefined entries leave existing values unchanged.
275
+ * @returns {LienObj|undefined} This request object, or undefined when sessions are disabled.
276
+ */
277
+ setSessionData (data) {
278
+ if (!this._checkSessionSupport()) {
279
+ return;
280
+ }
281
+ this.session._sessionData = mergeData(this.session._sessionData, data);
282
+ return this;
283
+ }
284
+
285
+ /**
286
+ * Returns application session data or a nested field, preserving falsy values.
287
+ *
288
+ * @param {string} [field] A dot-separated field path.
289
+ * @returns {*} The data, null for a missing field, or undefined when unavailable.
290
+ */
291
+ getSessionData (field) {
292
+ if (!this._checkSessionSupport()) {
293
+ return;
294
+ }
295
+ return field ? getData(this.session._sessionData, field) : this.session._sessionData;
296
+ }
297
+
298
+ /**
299
+ * Removes the current session from its store.
300
+ *
301
+ * @returns {Promise<void>} Resolves after destruction, or immediately when sessions are disabled.
302
+ * @throws {Error} If the store cannot destroy the session.
303
+ */
304
+ async destroySession () {
305
+ if (!this._checkSessionSupport()) {
306
+ return;
307
+ }
308
+ await promisify(this.session.destroy.bind(this.session))();
309
+ }
310
+
311
+ /**
312
+ * Reads request headers or sets/removes response headers.
313
+ * With no arguments, returns all request headers. A headers object sets multiple response headers.
314
+ *
315
+ * @param {string|Object<string, *>} [name] The header name or headers to set.
316
+ * @param {string|Array<string>|number|null} [value] The response value; null removes the header.
317
+ * @returns {LienObj|object|string|undefined} The request value, this object after setting, or undefined after removal.
318
+ */
319
+ header (name, value) {
320
+ if (!name && !value) {
321
+ return this.req.headers;
322
+ }
323
+ if (value === null) {
324
+ return this.res.removeHeader(name);
325
+ }
326
+ if (value === undefined && typeof name === "string") {
327
+ return this.req.get(name);
328
+ }
329
+ if (typeof name === "object") {
330
+ this.res.set(name);
331
+ } else {
332
+ this.res.set(name, value);
333
+ }
334
+ return this;
335
+ }
336
+
337
+ /**
338
+ * Sends a JSON response containing the message field, including after hooks.
339
+ *
340
+ * @param {*} message The message value.
341
+ * @param {number} [status=200] The HTTP status.
342
+ * @returns {Promise<void>|undefined} The response promise, or undefined if already responding.
343
+ */
344
+ apiMsg (message, status = 200) {
345
+ return this.end({ message }, status);
346
+ }
347
+
348
+ /**
349
+ * Sends an API error message, using an Error object's message when supplied.
350
+ *
351
+ * @param {string|Error} message The error message.
352
+ * @param {number} [status=422] The HTTP status.
353
+ * @returns {Promise<void>|undefined} The response promise, or undefined if already responding.
354
+ */
355
+ apiError (message, status = 422) {
356
+ return this.apiMsg(message?.message ?? message, status);
357
+ }
358
+
359
+ /**
360
+ * Runs after hooks, serializes content, and ends the response.
361
+ * Also accepts end(content, status, headers) and end(status, headers).
362
+ * A numeric first argument is a status, and an omitted status preserves res.statusCode.
363
+ *
364
+ * @param {*} [content] The response body or numeric status.
365
+ * @param {number|Object<string, *>} [status] The status, or headers after a numeric first argument.
366
+ * @param {string|Object<string, *>} [contentType] The content type or headers.
367
+ * @param {Object<string, *>} [headers] Additional response headers.
368
+ * @returns {Promise<void>|undefined} Resolves after hook processing; failures go to Express.
369
+ */
370
+ end (content, status, contentType, headers) {
371
+ if (!this._beginResponse()) {
372
+ return;
373
+ }
374
+ if (typeof contentType === "object") {
375
+ headers = contentType;
376
+ contentType = undefined;
377
+ }
378
+ if (typeof content === "number") {
379
+ if (status && typeof status === "object") {
380
+ headers = status;
381
+ }
382
+ status = content;
383
+ content = "";
384
+ }
385
+ return this._finishResponse({
386
+ content,
387
+ status: status ?? this.res.statusCode,
388
+ contentType: contentType ?? this.res.get("Content-Type"),
389
+ headers: headers ?? {},
390
+ lien: this
391
+ });
392
+ }
393
+
394
+ /**
395
+ * Processes after hooks and forwards hook or serialization failures to Express.
396
+ *
397
+ * @private
398
+ * @param {ResponseData} data The pending response.
399
+ * @returns {Promise<void>}
400
+ */
401
+ async _finishResponse (data) {
402
+ try {
403
+ if (data.content instanceof Error) {
404
+ throw data.content;
405
+ }
406
+ await this._runHooks("after", data);
407
+ if (!this._nextCalled && !this.res.destroyed && !this.res.writableEnded) {
408
+ this._sendResponse(data);
409
+ }
410
+ } catch (error) {
411
+ this._hookError(error);
412
+ }
413
+ }
414
+
415
+ /**
416
+ * Serializes and sends the prepared response without running hooks.
417
+ *
418
+ * @private
419
+ * @param {ResponseData} data The prepared response.
420
+ * @returns {void}
421
+ * @throws {Error} If serialization or sending fails.
422
+ */
423
+ _sendResponse (data) {
424
+ if (this.res.headersSent) {
425
+ return;
426
+ }
427
+ const { buffer, contentType } = toBuffer(data.content);
428
+ this.res.status(data.status);
429
+ this.header(data.headers);
430
+ this.res.type(data.contentType || contentType);
431
+ this.res.end(buffer);
432
+ }
433
+
434
+ /**
435
+ * Reads, sets, or clears a cookie. Clear operations preserve the supplied options.
436
+ *
437
+ * @param {string} name The cookie name.
438
+ * @param {*} [value] The value to set; null clears the cookie.
439
+ * @param {object} [options] Express cookie options, including path and domain.
440
+ * @returns {*} The stored value when reading, or this request object when setting/clearing.
441
+ */
442
+ cookie (name, value, options) {
443
+ if (value === undefined) {
444
+ return this.cookies[name];
445
+ }
446
+ if (value === null) {
447
+ this.res.clearCookie(name, options);
448
+ } else {
449
+ this.res.cookie(name, value, options);
450
+ }
451
+ return this;
452
+ }
453
+
454
+ /**
455
+ * Serves a file inside a root, rejecting traversal and escaping symlinks.
456
+ * Leading slashes are relative to the root. File errors are forwarded to Express.
457
+ *
458
+ * @param {string} filePath The rooted filename.
459
+ * @param {string} [customRoot] The root directory; defaults to the first public directory.
460
+ * @returns {Promise<void>} Resolves after serving or forwarding the error.
461
+ */
462
+ async file (filePath, customRoot = this.server.options.public[0]?.[1]) {
463
+ if (!this._beginResponse()) {
464
+ return;
465
+ }
466
+ try {
467
+ if (typeof filePath !== "string" || typeof customRoot !== "string") {
468
+ throw new TypeError("file() requires a filename and a configured public root.");
469
+ }
470
+ const root = await realpath(customRoot);
471
+ const target = path.resolve(root, filePath.replace(/^[/\\]+/, ""));
472
+ ensureContained(root, target);
473
+ const filename = await realpath(target);
474
+ ensureContained(root, filename);
475
+ if (!this.res.destroyed && !this._nextCalled) {
476
+ await promisify(this.res.sendFile.bind(this.res))(filename);
477
+ }
478
+ } catch (error) {
479
+ this.next(asError(error));
480
+ }
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Verifies that a resolved filename stays within the configured root.
486
+ *
487
+ * @private
488
+ * @param {string} root The absolute root.
489
+ * @param {string} filename The absolute filename.
490
+ * @returns {void}
491
+ * @throws {Error} With status 403 if the filename escapes the root.
492
+ */
493
+ function ensureContained (root, filename) {
494
+ const relative = path.relative(root, filename);
495
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
496
+ const error = new Error("File is outside the configured root.");
497
+ error.status = 403;
498
+ throw error;
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Cancellation controller for the current before-hook execution.
504
+ * @name LienObj#_beforeHooks
505
+ * @type {AbortController|null|undefined}
506
+ * @private
507
+ */
508
+
509
+ /**
510
+ * Cancellation controller for the current after-hook execution.
511
+ * @name LienObj#_afterHooks
512
+ * @type {AbortController|null|undefined}
513
+ * @private
514
+ */
515
+
516
+ /**
517
+ * Express helpers that claim the response before sending it.
518
+ *
519
+ * @private
520
+ * @type {Set<string>}
521
+ */
522
+ const terminalMethods = new Set(["download", "json", "jsonp"]);
523
+ for (const method of ["append", "attachment", "download", "json", "jsonp", "links", "vary", "status"]) {
524
+ /**
525
+ * Calls the corresponding Express response helper and preserves chaining.
526
+ * Includes append(), attachment(), download(), json(), jsonp(), links(), vary(), and status().
527
+ *
528
+ * @this {LienObj}
529
+ * @param {...*} args Arguments accepted by the Express helper.
530
+ * @returns {LienObj} This request object.
531
+ */
532
+ LienObj.prototype[method] = function (...args) {
533
+ if (terminalMethods.has(method) && !this._beginResponse()) {
534
+ return this;
535
+ }
536
+ this.res[method](...args);
537
+ return this;
538
+ };
539
+ }