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/DOCUMENTATION.md +4 -290
- package/LICENSE +1 -1
- package/README.md +14 -321
- package/assets/logo.png +0 -0
- package/example/index.js +8 -10
- package/example/login.js +23 -36
- package/example/secure.js +6 -10
- package/lib/errors.js +58 -0
- package/lib/hook-registry.js +232 -0
- package/lib/hooks.js +302 -0
- package/lib/index.js +15 -1117
- package/lib/lien.js +539 -0
- package/lib/server.js +590 -0
- package/lib/sessions.js +56 -0
- package/lib/to-buffer.js +32 -45
- package/lib/utils.js +75 -0
- package/package.json +34 -21
- package/.github/FUNDING.yml +0 -4
- package/.travis.yml +0 -3
- package/CONTRIBUTING.md +0 -66
- package/test/index.js +0 -280
- package/test/public/foo/index.html +0 -1
- package/test/public/index.html +0 -12
- package/test/public/test.html +0 -1
- package/test/views/main.ajs +0 -1
package/lib/server.js
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { createServer as createHttpServer } from "node:http";
|
|
3
|
+
import { createServer as createHttpsServer } from "node:https";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import express from "express";
|
|
7
|
+
import cookieParser from "cookie-parser";
|
|
8
|
+
import csrf from "@dr.pogodin/csurf";
|
|
9
|
+
import Hooks from "./hooks.js";
|
|
10
|
+
import LienObj from "./lien.js";
|
|
11
|
+
import { configureSession } from "./sessions.js";
|
|
12
|
+
import { configureErrorPages } from "./errors.js";
|
|
13
|
+
import { methods, compileRoute, getHooks, insertHook } from "./hook-registry.js";
|
|
14
|
+
import { asError } from "./utils.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {string|RegExp|Array<string|RegExp>} RoutePattern
|
|
18
|
+
* A route or hook pattern, or an array of patterns.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @callback RouteHandler
|
|
23
|
+
* @param {LienObj} lien The current request.
|
|
24
|
+
* @param {...*} args Additional arguments supplied by error handlers.
|
|
25
|
+
* @returns {*} A return value or promise. Response helpers send the actual response.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {string|RouteHandler} RouteOutput
|
|
30
|
+
* A route handler or a filename relative to the public root.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @callback Middleware
|
|
35
|
+
* @param {object} req The Express request.
|
|
36
|
+
* @param {object} res The Express response.
|
|
37
|
+
* @param {Function} next The next Express middleware.
|
|
38
|
+
* @returns {*} A middleware return value or promise.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @typedef {object} RouteOptions
|
|
43
|
+
* @property {string} method The lowercase HTTP method or all.
|
|
44
|
+
* @property {Middleware|Array<Middleware>} [before] Express middleware before the Lien handler.
|
|
45
|
+
* @property {Middleware|Array<Middleware>} [after] Express middleware reached when the handler delegates.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @typedef {object} ErrorPages
|
|
50
|
+
* @property {RouteOutput} [notFound] Handles missing routes and files.
|
|
51
|
+
* @property {RouteOutput} [serverError] Handles other failures; functions also receive the error.
|
|
52
|
+
* @property {RouteOutput} [badCsrf] Handles invalid CSRF tokens.
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @typedef {object} SessionOptions
|
|
57
|
+
* @property {string|Array<string>} [secret] Signing secret; takes precedence over cookieSecret.
|
|
58
|
+
* @property {boolean} [resave=false] Whether to save unchanged sessions.
|
|
59
|
+
* @property {boolean} [saveUninitialized=true] Whether to save new, unchanged sessions.
|
|
60
|
+
* @property {object} [cookie] Session cookie options.
|
|
61
|
+
* @property {string|Function|object} [store] A module name, factory, provider, class, or store instance.
|
|
62
|
+
* @property {object} [storeOptions] Options for a store created by Lien.
|
|
63
|
+
*/
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @typedef {object} ViewOptions
|
|
67
|
+
* @property {string} path The views directory.
|
|
68
|
+
* @property {string} name The registered or installed view engine name.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @typedef {object} SslOptions
|
|
73
|
+
* @property {string} [key] Private key filename, required unless _key is supplied.
|
|
74
|
+
* @property {string} [cert] Certificate filename, required unless _cert is supplied.
|
|
75
|
+
* @property {string|Buffer} [_key] Private key contents.
|
|
76
|
+
* @property {string|Buffer} [_cert] Certificate contents.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @typedef {object} LienOptions
|
|
81
|
+
* @property {string} [host] The listen address.
|
|
82
|
+
* @property {number|string} [port] The port; defaults to process.env.PORT or 3000. Use 0 for an assigned port.
|
|
83
|
+
* @property {string|Array<Array<string>>} [public=[]] A directory or pairs of mount URL and directory.
|
|
84
|
+
* @property {ViewOptions} [views] Template settings.
|
|
85
|
+
* @property {boolean|SessionOptions} [session=false] Session configuration.
|
|
86
|
+
* @property {string|Array<string>} [cookieSecret] Signing secret; defaults to a random 32-byte secret per server.
|
|
87
|
+
* @property {object} [cookieOptions={}] Options passed to cookie-parser.
|
|
88
|
+
* @property {boolean|object|null} [csrf=null] CSRF options; true enables cookie mode.
|
|
89
|
+
* @property {boolean|object} [bodyParserJson=true] Enables express.json() or supplies its options.
|
|
90
|
+
* @property {boolean|object} [bodyParserUrlEncoded=true] Enables express.urlencoded() or supplies its options.
|
|
91
|
+
* @property {boolean} [cookieParser=true] Whether to parse cookies.
|
|
92
|
+
* @property {boolean} [transformers=true] Legacy option controlling before and after hooks.
|
|
93
|
+
* @property {boolean} [logErrors=true] Whether to log request errors.
|
|
94
|
+
* @property {ErrorPages|boolean} [errorPages={}] Custom error pages, or false to omit default handlers.
|
|
95
|
+
* @property {SslOptions} [ssl] HTTPS certificate settings.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Lien
|
|
100
|
+
* Creates an HTTP or HTTPS server and starts listening after initialization.
|
|
101
|
+
*
|
|
102
|
+
* @extends EventEmitter
|
|
103
|
+
* @fires Lien#load
|
|
104
|
+
* @fires Lien#error
|
|
105
|
+
* @fires Lien#serverError
|
|
106
|
+
* @property {Promise<Lien>} ready Resolves after listening; rejects on startup failure.
|
|
107
|
+
* @property {object} app The Express application.
|
|
108
|
+
* @property {object} router The router for dynamic routes and add().
|
|
109
|
+
* @property {object} beforeRequest The router for routes taking priority over static files.
|
|
110
|
+
* @property {object} staticRouter The router serving public directories.
|
|
111
|
+
* @property {import("node:http").Server|import("node:https").Server} server The underlying server.
|
|
112
|
+
* @property {LienOptions} options The effective configuration, including the bound port.
|
|
113
|
+
* @property {object} transformers Registered hook definitions, grouped by type and method.
|
|
114
|
+
*/
|
|
115
|
+
export default class Lien extends EventEmitter {
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Creates the server. Routes can be registered before ready resolves.
|
|
119
|
+
*
|
|
120
|
+
* @param {LienOptions} [options={}] Server configuration.
|
|
121
|
+
* @throws {Error} If synchronous setup, such as reading TLS certificates, fails.
|
|
122
|
+
*/
|
|
123
|
+
constructor (options = {}) {
|
|
124
|
+
super();
|
|
125
|
+
|
|
126
|
+
this.options = {
|
|
127
|
+
public: [],
|
|
128
|
+
session: false,
|
|
129
|
+
errorPages: {},
|
|
130
|
+
logErrors: true,
|
|
131
|
+
csrf: null,
|
|
132
|
+
port: process.env.PORT || 3000,
|
|
133
|
+
cookieSecret: randomBytes(32).toString("hex"),
|
|
134
|
+
cookieOptions: {},
|
|
135
|
+
bodyParserJson: true,
|
|
136
|
+
bodyParserUrlEncoded: true,
|
|
137
|
+
cookieParser: true,
|
|
138
|
+
transformers: true,
|
|
139
|
+
...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined))
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const config = this.options;
|
|
143
|
+
if (!Array.isArray(config.public)) {
|
|
144
|
+
config.public = [
|
|
145
|
+
["/", config.public]
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
if (config.csrf === true) {
|
|
149
|
+
config.csrf = {
|
|
150
|
+
cookie: true
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
this.csrf = config.csrf ? csrf(config.csrf) : null;
|
|
155
|
+
this.express = express;
|
|
156
|
+
this.app = express();
|
|
157
|
+
this.app.disable("x-powered-by");
|
|
158
|
+
this.app.set("query parser", "extended");
|
|
159
|
+
|
|
160
|
+
if (config.views) {
|
|
161
|
+
this.app.set("views", config.views.path);
|
|
162
|
+
this.app.set("view engine", config.views.name);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (config.bodyParserJson) {
|
|
166
|
+
this.app.use(express.json(config.bodyParserJson === true ? {} : config.bodyParserJson));
|
|
167
|
+
}
|
|
168
|
+
if (config.bodyParserUrlEncoded) {
|
|
169
|
+
this.app.use(express.urlencoded({
|
|
170
|
+
extended: true,
|
|
171
|
+
...(config.bodyParserUrlEncoded === true ? {} : config.bodyParserUrlEncoded)
|
|
172
|
+
}));
|
|
173
|
+
}
|
|
174
|
+
if (config.cookieParser) {
|
|
175
|
+
this.app.use(cookieParser(config.cookieSecret, config.cookieOptions));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
this.SessionStore = null;
|
|
179
|
+
this.SessionStoreModule = null;
|
|
180
|
+
this.app.use((req, res, next) => this.session ? this.session(req, res, next) : next());
|
|
181
|
+
|
|
182
|
+
this.beforeRequest = express.Router();
|
|
183
|
+
this.staticRouter = express.Router();
|
|
184
|
+
this.router = express.Router();
|
|
185
|
+
this.transformers = {
|
|
186
|
+
before: Object.create(null),
|
|
187
|
+
after: Object.create(null)
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
this.app.use(this.beforeRequest, this.staticRouter, this.router);
|
|
191
|
+
for (const [url, localPath] of config.public) {
|
|
192
|
+
this.addStaticPath(url, localPath);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (config.ssl) {
|
|
196
|
+
const { key, cert, _key, _cert } = config.ssl;
|
|
197
|
+
this.server = createHttpsServer({
|
|
198
|
+
key: _key ?? readFileSync(key),
|
|
199
|
+
cert: _cert ?? readFileSync(cert)
|
|
200
|
+
}, this.app);
|
|
201
|
+
} else {
|
|
202
|
+
this.server = createHttpServer(this.app);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
queueMicrotask(() => {
|
|
206
|
+
if (config.errorPages) {
|
|
207
|
+
this.errorPages(config.errorPages);
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
this.ready = this._start();
|
|
212
|
+
this.ready.catch(error => {
|
|
213
|
+
this.emit("load", error);
|
|
214
|
+
if (this.listenerCount("error")) {
|
|
215
|
+
this.emit("error", error);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Initializes sessions, listens, and emits the successful load event.
|
|
222
|
+
*
|
|
223
|
+
* @private
|
|
224
|
+
* @returns {Promise<Lien>} The listening server.
|
|
225
|
+
* @throws {Error} If session initialization or listening fails.
|
|
226
|
+
*/
|
|
227
|
+
async _start () {
|
|
228
|
+
await configureSession(this);
|
|
229
|
+
await new Promise((resolve, reject) => {
|
|
230
|
+
const onError = error => {
|
|
231
|
+
this.server.removeListener("listening", onListen);
|
|
232
|
+
reject(error);
|
|
233
|
+
};
|
|
234
|
+
const onListen = () => {
|
|
235
|
+
this.server.removeListener("error", onError);
|
|
236
|
+
resolve();
|
|
237
|
+
};
|
|
238
|
+
this.server.once("error", onError);
|
|
239
|
+
this.server.once("listening", onListen);
|
|
240
|
+
this.server.listen({
|
|
241
|
+
port: this.options.port,
|
|
242
|
+
host: this.options.host
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
this.options.port = this.server.address().port;
|
|
246
|
+
this.server.on("error", error => this.emit("serverError", error));
|
|
247
|
+
this.emit("load", null);
|
|
248
|
+
return this;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Stops listening and closes stores created by Lien.
|
|
253
|
+
* Repeated calls return the same shutdown promise. Supplied store instances remain owned by the caller.
|
|
254
|
+
*
|
|
255
|
+
* @returns {Promise<void>} Resolves after shutdown.
|
|
256
|
+
* @throws {Error} If the HTTP server or an owned store cannot be closed.
|
|
257
|
+
*/
|
|
258
|
+
close () {
|
|
259
|
+
return this._closing ??= this._shutdown();
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Releases server resources, including after a startup failure.
|
|
264
|
+
*
|
|
265
|
+
* @private
|
|
266
|
+
* @returns {Promise<void>} Resolves when cleanup finishes.
|
|
267
|
+
*/
|
|
268
|
+
async _shutdown () {
|
|
269
|
+
try {
|
|
270
|
+
await this.ready;
|
|
271
|
+
} catch {
|
|
272
|
+
/* A store may exist even if listening failed. */
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
if (this.server.listening) {
|
|
276
|
+
await new Promise((resolve, reject) => {
|
|
277
|
+
this.server.close(error => error ? reject(error) : resolve());
|
|
278
|
+
this.server.closeIdleConnections();
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
} finally {
|
|
282
|
+
await this._ownedSessionStore?.close?.();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Mounts a public directory. Static requests do not execute route hooks.
|
|
288
|
+
*
|
|
289
|
+
* @param {string} url The mount URL.
|
|
290
|
+
* @param {string} localPath The local directory.
|
|
291
|
+
* @returns {void}
|
|
292
|
+
*/
|
|
293
|
+
addStaticPath (url, localPath) {
|
|
294
|
+
this.staticRouter.use(url, express.static(localPath));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Invokes a handler or serves a file, forwarding failures to Express.
|
|
299
|
+
*
|
|
300
|
+
* @private
|
|
301
|
+
* @param {LienObj} lien The request object.
|
|
302
|
+
* @param {RouteOutput} output The handler or public filename.
|
|
303
|
+
* @param {Array<*>} args Arguments passed to the handler.
|
|
304
|
+
* @returns {Promise<void>}
|
|
305
|
+
*/
|
|
306
|
+
async _invokeRoute (lien, output, args) {
|
|
307
|
+
try {
|
|
308
|
+
if (typeof output === "string") {
|
|
309
|
+
await lien.file(output);
|
|
310
|
+
} else {
|
|
311
|
+
await output.apply(this, args);
|
|
312
|
+
}
|
|
313
|
+
} catch (error) {
|
|
314
|
+
lien.next(asError(error, "Route failed."));
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Creates a request object and invokes a route without before hooks.
|
|
320
|
+
*
|
|
321
|
+
* @private
|
|
322
|
+
* @param {object} req The Express request.
|
|
323
|
+
* @param {object} res The Express response.
|
|
324
|
+
* @param {RouteOutput} output The handler or public filename.
|
|
325
|
+
* @param {Array<*>} [args=[]] Extra handler arguments after lien.
|
|
326
|
+
* @param {Function} [next] The next Express middleware.
|
|
327
|
+
* @returns {Promise<void>}
|
|
328
|
+
*/
|
|
329
|
+
_handleRoute (req, res, output, args = [], next = () => {}) {
|
|
330
|
+
const lien = new LienObj(req, res, next, this);
|
|
331
|
+
return this._invokeRoute(lien, output, [lien, ...args]);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Invokes a route using the object already processed by before hooks.
|
|
336
|
+
*
|
|
337
|
+
* @private
|
|
338
|
+
* @param {LienObj} lien The request object.
|
|
339
|
+
* @param {RouteOutput} output The handler or public filename.
|
|
340
|
+
* @returns {Promise<void>}
|
|
341
|
+
*/
|
|
342
|
+
_handleLienRoute (lien, output) {
|
|
343
|
+
return this._invokeRoute(lien, output, [lien]);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Runs before hooks and invokes the route unless the request ended or delegated.
|
|
348
|
+
*
|
|
349
|
+
* @private
|
|
350
|
+
* @param {object} req The Express request.
|
|
351
|
+
* @param {object} res The Express response.
|
|
352
|
+
* @param {RouteOutput} output The handler or public filename.
|
|
353
|
+
* @param {Function} next The next Express middleware.
|
|
354
|
+
* @returns {Promise<void>}
|
|
355
|
+
*/
|
|
356
|
+
async _dispatch (req, res, output, next) {
|
|
357
|
+
const lien = new LienObj(req, res, next, this);
|
|
358
|
+
try {
|
|
359
|
+
await lien._runHooks("before", lien);
|
|
360
|
+
if (!lien._ending && !lien._nextCalled && !res.headersSent && !res.destroyed) {
|
|
361
|
+
await this._handleLienRoute(lien, output);
|
|
362
|
+
}
|
|
363
|
+
} catch (error) {
|
|
364
|
+
lien._hookError(error);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Registers a route. With two arguments, the second is the output and all methods are handled.
|
|
370
|
+
* Object-form before and after options are Express middleware, not Lien hooks.
|
|
371
|
+
*
|
|
372
|
+
* @param {RoutePattern} url The route pattern.
|
|
373
|
+
* @param {string|RouteOptions|RouteOutput} method The method, route options, or output.
|
|
374
|
+
* @param {RouteOutput} [output] The handler or public filename.
|
|
375
|
+
* @returns {void}
|
|
376
|
+
*/
|
|
377
|
+
addPage (url, method, output) {
|
|
378
|
+
if (output === undefined) {
|
|
379
|
+
output = method;
|
|
380
|
+
method = "all";
|
|
381
|
+
}
|
|
382
|
+
const route = typeof method === "object" ? method : {};
|
|
383
|
+
method = route.method ?? method;
|
|
384
|
+
const router = typeof url === "string" && url.includes(":") ? this.router : this.beforeRequest;
|
|
385
|
+
const { regexp, restoreParams } = compileRoute(url);
|
|
386
|
+
const before = [this.csrf, ...[route.before ?? []].flat()].filter(Boolean);
|
|
387
|
+
const after = [route.after ?? []].flat().filter(Boolean);
|
|
388
|
+
router[method](regexp, restoreParams, ...before, (req, res, next) => this._dispatch(req, res, output, next), ...after);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Appends not-found and error handlers to the Express application.
|
|
393
|
+
*
|
|
394
|
+
* @param {ErrorPages} [options={}] Custom handlers or public filenames.
|
|
395
|
+
* @returns {void}
|
|
396
|
+
*/
|
|
397
|
+
errorPages (options) {
|
|
398
|
+
configureErrorPages(this, options);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Returns the matching hook pipeline, combining URL groups in registration order.
|
|
403
|
+
*
|
|
404
|
+
* @param {string} type The hook type, such as before, after, or custom:name.
|
|
405
|
+
* @param {string} url The request path.
|
|
406
|
+
* @param {string} method The lowercase HTTP method.
|
|
407
|
+
* @returns {Hooks|null} A reusable pipeline, or null when no hooks match.
|
|
408
|
+
*/
|
|
409
|
+
getHooks (type, url, method) {
|
|
410
|
+
return getHooks(this.transformers, type, url, method);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Returns hooks registered with the same compiled pattern.
|
|
415
|
+
*
|
|
416
|
+
* @param {string} type The hook type.
|
|
417
|
+
* @param {RoutePattern} url The registered pattern.
|
|
418
|
+
* @param {string} method The lowercase HTTP method.
|
|
419
|
+
* @returns {Hooks|null} The matching pipeline, or null.
|
|
420
|
+
*/
|
|
421
|
+
getHooksStrict (type, url, method) {
|
|
422
|
+
return getHooks(this.transformers, type, url, method, true);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Inserts a native hook pipeline. External Transformer instances are not accepted.
|
|
427
|
+
*
|
|
428
|
+
* @param {string} type The hook type, including custom:name.
|
|
429
|
+
* @param {RoutePattern} url The hook pattern.
|
|
430
|
+
* @param {string} method The lowercase HTTP method.
|
|
431
|
+
* @param {Hooks} pipeline The pipeline to insert.
|
|
432
|
+
* @returns {Hooks} The inserted pipeline.
|
|
433
|
+
* @throws {TypeError} If pipeline is not an instance of Hooks.
|
|
434
|
+
*/
|
|
435
|
+
insertHook (type, url, method, pipeline) {
|
|
436
|
+
return insertHook(this.transformers, type, url, method, pipeline);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Registers hooks for a pattern, URL array, or wildcard.
|
|
441
|
+
* Omitting the method applies to all HTTP methods. Returns the server for chaining.
|
|
442
|
+
*
|
|
443
|
+
* @param {string} where The hook type: before, after, or custom:name.
|
|
444
|
+
* @param {RoutePattern} url The hook pattern or patterns.
|
|
445
|
+
* @param {string|import("./hooks.js").HookCallback} method The method or callback.
|
|
446
|
+
* @param {import("./hooks.js").HookCallback|import("./hooks.js").HookMode} [callback] The callback, or mode when the method is omitted.
|
|
447
|
+
* @param {import("./hooks.js").HookMode} [mode=3] The execution mode.
|
|
448
|
+
* @returns {Lien} The server.
|
|
449
|
+
* @throws {Error} If the hook type, callback, or mode is invalid.
|
|
450
|
+
*/
|
|
451
|
+
hook (where, url, method, callback, mode) {
|
|
452
|
+
if (!this.options.transformers) {
|
|
453
|
+
console.warn("Transformers are disabled.");
|
|
454
|
+
}
|
|
455
|
+
if (typeof method === "function") {
|
|
456
|
+
mode = callback ?? mode;
|
|
457
|
+
callback = method;
|
|
458
|
+
method = "all";
|
|
459
|
+
}
|
|
460
|
+
if (method === "all") {
|
|
461
|
+
for (const name of methods) {
|
|
462
|
+
this.hook(where, url, name, callback, mode);
|
|
463
|
+
}
|
|
464
|
+
return this;
|
|
465
|
+
}
|
|
466
|
+
if (Array.isArray(url)) {
|
|
467
|
+
for (const item of url) {
|
|
468
|
+
this.hook(where, item, method, callback, mode);
|
|
469
|
+
}
|
|
470
|
+
return this;
|
|
471
|
+
}
|
|
472
|
+
if (typeof url === "string" && url.startsWith(":")) {
|
|
473
|
+
url = `/${url}`;
|
|
474
|
+
}
|
|
475
|
+
if (!["before", "after", "custom"].includes(where.split(":")[0])) {
|
|
476
|
+
throw new Error("The hook type should be 'before', 'after' or 'custom'.");
|
|
477
|
+
}
|
|
478
|
+
const pipeline = this.getHooksStrict(where, url, method) ?? this.insertHook(where, url, method, new Hooks());
|
|
479
|
+
pipeline.add(callback, mode);
|
|
480
|
+
return this;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Registers hooks receiving lien before the route handler.
|
|
485
|
+
*
|
|
486
|
+
* @param {RoutePattern} url The hook pattern or patterns.
|
|
487
|
+
* @param {string|import("./hooks.js").HookCallback} method The method or callback.
|
|
488
|
+
* @param {import("./hooks.js").HookCallback|import("./hooks.js").HookMode} [callback] The callback, or mode when the method is omitted.
|
|
489
|
+
* @param {import("./hooks.js").HookMode} [mode=3] The execution mode.
|
|
490
|
+
* @returns {void}
|
|
491
|
+
*/
|
|
492
|
+
before (url, method, callback, mode) {
|
|
493
|
+
this.hook("before", url, method, callback, mode);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Registers hooks receiving response data before end() sends it.
|
|
498
|
+
*
|
|
499
|
+
* @param {RoutePattern} url The hook pattern or patterns.
|
|
500
|
+
* @param {string|import("./hooks.js").HookCallback} method The method or callback.
|
|
501
|
+
* @param {import("./hooks.js").HookCallback|import("./hooks.js").HookMode} [callback] The callback, or mode when the method is omitted.
|
|
502
|
+
* @param {import("./hooks.js").HookMode} [mode=3] The execution mode.
|
|
503
|
+
* @returns {void}
|
|
504
|
+
*/
|
|
505
|
+
after (url, method, callback, mode) {
|
|
506
|
+
this.hook("after", url, method, callback, mode);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Registers before hooks for a URL and its subpaths. Does not protect static files.
|
|
511
|
+
*
|
|
512
|
+
* @param {string} url The base URL.
|
|
513
|
+
* @param {string|import("./hooks.js").HookCallback} method The method or callback.
|
|
514
|
+
* @param {import("./hooks.js").HookCallback|import("./hooks.js").HookMode} [callback] The callback, or mode when the method is omitted.
|
|
515
|
+
* @param {import("./hooks.js").HookMode} [mode=3] The execution mode.
|
|
516
|
+
* @returns {void}
|
|
517
|
+
*/
|
|
518
|
+
use (url, method, callback, mode) {
|
|
519
|
+
url = url.replace(/\/$/, "");
|
|
520
|
+
this.before([url, `${url}/(.*)`], method, callback, mode);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Registers a handler without before hooks. end() still executes after hooks.
|
|
525
|
+
*
|
|
526
|
+
* @param {RoutePattern} url The route pattern.
|
|
527
|
+
* @param {string|RouteHandler} method The HTTP method or handler; omitted methods mean all.
|
|
528
|
+
* @param {RouteHandler} [callback] The handler when a method is provided.
|
|
529
|
+
* @returns {void}
|
|
530
|
+
*/
|
|
531
|
+
add (url, method, callback) {
|
|
532
|
+
if (typeof method === "function") {
|
|
533
|
+
callback = method;
|
|
534
|
+
method = "all";
|
|
535
|
+
}
|
|
536
|
+
const { regexp, restoreParams } = compileRoute(url);
|
|
537
|
+
this.router[method](regexp, restoreParams, (req, res, next) => this._handleRoute(req, res, callback, [], next));
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
for (const method of ["all", ...methods]) {
|
|
541
|
+
if (method in Lien.prototype) {
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Registers a route for the named HTTP method, including all().
|
|
546
|
+
*
|
|
547
|
+
* @this {Lien}
|
|
548
|
+
* @param {RoutePattern} url The route pattern.
|
|
549
|
+
* @param {RouteOutput} output The handler or public filename.
|
|
550
|
+
* @returns {void}
|
|
551
|
+
*/
|
|
552
|
+
Lien.prototype[method] = function (url, output) {
|
|
553
|
+
this.addPage(url, method, output);
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Promise shared by repeated shutdown calls.
|
|
559
|
+
* @name Lien#_closing
|
|
560
|
+
* @type {Promise<void>|undefined}
|
|
561
|
+
* @private
|
|
562
|
+
*/
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* A store created by Lien and released during shutdown.
|
|
566
|
+
* Supplied store instances are owned by their caller.
|
|
567
|
+
* @name Lien#_ownedSessionStore
|
|
568
|
+
* @type {object|undefined}
|
|
569
|
+
* @private
|
|
570
|
+
*/
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Reports that listening succeeded or failed.
|
|
574
|
+
* @event Lien#load
|
|
575
|
+
* @param {Error|null} error The startup failure, or null on success.
|
|
576
|
+
*/
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Reports a startup failure when an error listener is registered.
|
|
580
|
+
* @event Lien#error
|
|
581
|
+
* @param {Error} error The startup failure.
|
|
582
|
+
*/
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Reports a request failure or an error from the listening server.
|
|
586
|
+
* @event Lien#serverError
|
|
587
|
+
* @param {Error} error The failure.
|
|
588
|
+
* @param {object} [req] The Express request, when available.
|
|
589
|
+
* @param {object} [res] The Express response, when available.
|
|
590
|
+
*/
|
package/lib/sessions.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import session from "express-session";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Initializes session middleware before listening.
|
|
5
|
+
* Supports store instances, create() providers, Store subclasses, legacy factories, and imported modules.
|
|
6
|
+
* An explicit session secret takes precedence over the cookie secret.
|
|
7
|
+
*
|
|
8
|
+
* @param {import("./server.js").default} server The server to configure.
|
|
9
|
+
* @returns {Promise<void>} Resolves when middleware and any owned store are ready.
|
|
10
|
+
* @throws {Error} If a store cannot be loaded or initialized.
|
|
11
|
+
* @private
|
|
12
|
+
*/
|
|
13
|
+
export async function configureSession (server) {
|
|
14
|
+
if (!server.options.session) {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
const options = {
|
|
18
|
+
resave: false,
|
|
19
|
+
saveUninitialized: true,
|
|
20
|
+
...server.options.session
|
|
21
|
+
};
|
|
22
|
+
options.secret ??= server.options.cookieSecret;
|
|
23
|
+
const storeOptions = options.storeOptions ?? {};
|
|
24
|
+
let provider = options.store;
|
|
25
|
+
if (typeof provider === "string") {
|
|
26
|
+
try {
|
|
27
|
+
const imported = await import(provider);
|
|
28
|
+
provider = imported.default ?? imported;
|
|
29
|
+
} catch (cause) {
|
|
30
|
+
throw new Error(`Cannot load session store ${options.store}. Install it in your application.`, { cause });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (provider && typeof provider.get !== "function") {
|
|
35
|
+
server.SessionStoreModule = provider;
|
|
36
|
+
server.SessionStore = provider;
|
|
37
|
+
if (typeof provider.create === "function") {
|
|
38
|
+
options.store = await provider.create(storeOptions);
|
|
39
|
+
} else if (provider.prototype instanceof session.Store) {
|
|
40
|
+
options.store = new provider(storeOptions);
|
|
41
|
+
} else if (typeof provider === "function") {
|
|
42
|
+
const Store = await provider(session);
|
|
43
|
+
server.SessionStore = Store;
|
|
44
|
+
options.store = new Store(storeOptions);
|
|
45
|
+
} else {
|
|
46
|
+
throw new TypeError("Invalid session store.");
|
|
47
|
+
}
|
|
48
|
+
server._ownedSessionStore = options.store;
|
|
49
|
+
}
|
|
50
|
+
delete options.storeOptions;
|
|
51
|
+
if (!options.store) {
|
|
52
|
+
delete options.store;
|
|
53
|
+
}
|
|
54
|
+
server.options.session = options;
|
|
55
|
+
server.session = session(options);
|
|
56
|
+
}
|