slower 2.1.8 → 2.2.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/src/utils.js CHANGED
@@ -1,65 +1,85 @@
1
-
2
- const { statSync, readdirSync } = require('node:fs')
1
+ const { statSync, readdirSync } = require('node:fs');
3
2
  const { join } = require('node:path');
4
3
  const { parse } = require('node:querystring');
4
+ const { URLPattern } = require('node:url');
5
5
 
6
6
  function* getFiles(folder) {
7
7
  const files = readdirSync(folder);
8
8
  for (const file of files) {
9
- const absolutePath = join(folder, file)
9
+ const absolutePath = join(folder, file);
10
10
  if (statSync(absolutePath).isDirectory()) {
11
- yield* getFiles(absolutePath)
12
- }
13
- else {
14
- yield absolutePath.replaceAll('..\\','')
11
+ yield* getFiles(absolutePath);
12
+ } else {
13
+ yield absolutePath.replaceAll('..\\', '');
15
14
  }
16
15
  }
17
16
  }
18
17
 
18
+ // This is added to all URLPattern objects, to avoid having it complaining about the
19
+ // absolute URL. As this IP is invalid, it is virtually impossible to receive a request with
20
+ // that origin URL.
21
+ const URL_PATTERN_PREFIX = 'https://0';
22
+ // Wrap the native URLPattern function and add the custom local prefix
23
+ const buildURLPatternFunction = template_url => {
24
+ const matcher = new URLPattern(template_url, URL_PATTERN_PREFIX);
25
+ return function (url) {
26
+ return matcher.test(URL_PATTERN_PREFIX + url) ?
27
+ matcher.exec(URL_PATTERN_PREFIX + url)
28
+ : null;
29
+ };
30
+ };
31
+
19
32
  const getMatchingRoute = (url, method, layers) => {
20
33
  method = method.toLowerCase();
21
34
  let list = [];
22
35
  // Get only the layers from the proper HTTP verb
23
36
  let routes = layers.get(method) || new Map();
24
37
  // Iterate through all routes, and get the one that match
25
- for (let [ pathFn, callback ] of routes) {
26
- let params = pathFn(getURLPathBody(url));
38
+ for (let [pathFn, callback] of routes) {
39
+ let parsed = pathFn(getURLPathBody(url));
27
40
  // Return the matching route
28
- if (!!params) {
41
+ if (parsed) {
29
42
  // add to list
30
- let built = ({ callback });
31
- if (params.params && params.params['0'] === undefined)
32
- built['params'] = params.params;
43
+ let built = { callback, params: {} };
44
+ // Only if the first key in the group is not undefined and not '0'
45
+ if (parsed?.pathname?.groups && !parsed?.pathname?.groups?.['0'])
46
+ built['params'] = parsed.pathname.groups;
33
47
  list.push(built);
34
48
  }
35
49
  }
36
50
  return list;
37
- }
51
+ };
38
52
 
39
- const normalizeAddress = addr => addr.startsWith('::') ? addr : addr.substring(addr.indexOf(':',2)+1);
53
+ const normalizeAddress = addr =>
54
+ addr.startsWith('::') ? addr : addr.substring(addr.indexOf(':', 2) + 1);
40
55
 
41
- const getFileExtension = (fname) => fname.split('.').filter(Boolean).slice(-1)[0];
56
+ const getFileExtension = fname => fname.split('.').filter(Boolean).slice(-1)[0];
42
57
 
43
58
  // /page?foo=bar&abc=123 -> /page
44
59
  const getURLPathBody = (urlPath = '') => urlPath.split('?')[0] || '';
45
60
 
46
61
  // /page?foo=bar&abc=123 -> { foo: 'bar', abc: '123' }
47
- const getURLQueryString = (urlPath = '') => parse((urlPath.split('?')[1] || '').split('#')[0]);
62
+ const getURLQueryString = (urlPath = '') =>
63
+ parse((urlPath.split('?')[1] || '').split('#')[0]);
48
64
 
49
- const noLayersFoundFallback = (req, res) =>
50
- res.status(404).send(
51
- `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">` +
52
- `<title>Error</title></head><body>` +
53
- `<pre>Cannot ${req.method.toUpperCase()} ${req.url}</pre></body></html>`
54
- )
55
- ;
65
+ const noLayersFoundFallback = (req, res) =>
66
+ res
67
+ .status(404)
68
+ .send(
69
+ `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">` +
70
+ `<title>Error</title></head><body>` +
71
+ `<pre>Cannot ${req.method.toUpperCase()} ${
72
+ req.url
73
+ }</pre></body></html>`
74
+ );
56
75
 
57
- module.exports = {
58
- getMatchingRoute,
59
- getFiles,
60
- normalizeAddress,
61
- getFileExtension,
62
- getURLPathBody,
76
+ module.exports = {
77
+ buildURLPatternFunction,
78
+ getMatchingRoute,
79
+ getFiles,
80
+ normalizeAddress,
81
+ getFileExtension,
82
+ getURLPathBody,
63
83
  getURLQueryString,
64
- noLayersFoundFallback
65
- };
84
+ noLayersFoundFallback,
85
+ };
package/readme.md.old DELETED
@@ -1,180 +0,0 @@
1
- # Slower
2
-
3
- Slower is a small web framework, express-like, but simpler and limited.
4
- It allows for generic route-declaration, fallback pages, and multiple middleware functions.
5
-
6
- ### API Methods:
7
-
8
- ```
9
- app.enableStrictHeaders(): this
10
- > Enables the use of the set of 'Strict Headers'.
11
- > These headers increase security levels, and are a good practice to apply.
12
- > However, using these headers in testing scenarios are not a need,
13
- and may have buggy or negative effects. So, apply those to simulate scenarios only.
14
- > Headers configured:
15
- > Content-Security-Policy
16
- > Cross-Origin-Opener-Policy
17
- > Cross-Origin-Resource-Policy
18
- > Origin-Agent-Cluster
19
- > Referrer-Policy
20
- > X-DNS-Prefetch-Control (disabled)
21
- > X-Download-Options
22
- > X-Frame-Options
23
- > X-XSS-Protection (disabled)
24
- > X-Powered-By (removed)
25
- > Returns the own object instance, so that methods can be chained.
26
- ```
27
- ```
28
- app.disableStrictHeaders(): this
29
- > Disables the use of the set of 'Strict Headers'.
30
- > See 'enableStrictHeaders()' for more information.
31
- > Returns the own object instance, so that methods can be chained.
32
- ```
33
- ```
34
- app.setRoute(string: path = '/', string: type = 'GET', function: callback): this
35
- > Creates a new route for path defined in 'path', responding to the HTTP verb defined in 'type' argument.
36
- > The callback is executed when the route is accessed.
37
- > Returns the own object instance, so that methods can be chained.
38
- ```
39
- ```
40
- app.setMiddleware(function: callback): this
41
- > Sets a new middleware function: callback function will be accessed for every server access.
42
- > Many middlewares can be defined, and will be applied in the order they are defined.
43
- > Returns the own object instance, so that methods can be chained.
44
- ```
45
- ```
46
- app.setDynamic(string: path, string: file = '', string: mime = '', object: replacementData = null): this
47
- > Creates a new GET route for path defined in 'path'.
48
- > This is a custom file-response route, configured for template rendering just before response.
49
- > Providing an object as 'replacementData' in this format { valueToBeReplaced: valueToReplace },
50
- allows for template rendering. The value to replace in the file, uses this notation: '<{content}>'.
51
- > URL reference in filename:
52
- > For direct references, it is possible to use the token '{%}' to replace the filename for the URL.
53
- > Ex:
54
- app.setStatic('/login', './templates/{%}.html', 'text/html');
55
- This will access the 'login.html' file when the route '/login' is accessed.
56
- > Example:
57
- Responding a route for '/custom' with file 'custom.html':
58
- app.setDynamic('/custom', './templates/custom.html', 'text/html', { smile: ':)' })
59
- In file './templates/custom.html':
60
- "<h2> This is a custom thing: <{smile}> </h2>"
61
- Rendered in browser:
62
- <h2> This is a custom thing: :) </h2>
63
- > Returns the own object instance, so that methods can be chained.
64
- ```
65
- ```
66
- app.setStatic(string: path, string: file = '', string: mime = ''): this
67
- > Creates a new GET route for path defined in 'path', responding with the specified file and MIME type.
68
- > URL reference in filename:
69
- > For direct references, it is possible to use the token '{%}' to replace the filename for the URL.
70
- > Ex:
71
- app.setStatic('/login', './templates/{%}.html', 'text/html');
72
- This will access the 'login.html' file when the route '/login' is accessed.
73
- > Example: A route for '/login' page, responding with 'login.html' file
74
- setStatic('/login', __dirname+'/public/static/views/login.html', 'text/html');
75
- > Returns the own object instance, so that methods can be chained.
76
- ```
77
- ```
78
- app.setFallback(function: callback): this
79
- > Creates a function for fallback state. When no other routes intercept the route, this will be used.
80
- > Special use for 'page not found' fallback pages or highly customized routes and situations.
81
- > Returns the own object instance, so that methods can be chained.
82
- ```
83
- ```
84
- app.setFallbackFile (string: file = '', string: mime = '', object: replacementData = null): this
85
- > Creates a function for fallback state. When no other routes intercept the route, this will be used.
86
- > Equivalent to setFallback, but responds with a file. Allows for template rendering.
87
- > See 'setDynamic' for more information about template rendering.
88
- > Special use for 'page not found' fallback pages, ex: './e404.html'.
89
- > Returns the own object instance, so that methods can be chained.
90
- ```
91
- ```
92
- app.setAllowedMethods(array: methods = []): this
93
- > Sets a list of methods to respond to.
94
- > By using this, it is possible to restrict the application to avoid
95
- responding to dangerous HTTP verbs, such as 'DELETE'.
96
- > By default, all methods are allowed (see Slower.constructor.http_methods)
97
- > Calling this function without parameters is an easy way to block responses to all requests (lock server).
98
- > Returns the own object instance, so that methods can be chained.
99
- ```
100
- ```
101
- app.start(number|string: port = 8080, string: host = undefined, function: callback = ()=>{}): this
102
- > Starts the server, at a specific host and port, then calling the callback function.
103
- > Not defining a specific port or host will start the server at '0.0.0.0:8080'.
104
- > Returns the own object instance, so that methods can be chained.
105
- ```
106
-
107
- Example usage:
108
- ```
109
- const Slower = require('slower');
110
- const port = 8080;
111
- let app = Slower();
112
- app.setMiddleware((req, res) => {
113
- req.time = Date.now();
114
- console.log(`${req.time} - ${req.method} : ${req.url}`);
115
- });
116
- app.setStatic('/favicon.ico', __dirname+'/public/{%}');
117
- app.setRoute('/', 'GET', (req, res) => {
118
- res.writeHead(200, { 'Content-Type': 'text/html' });
119
- res.write('<html><body><p>This is the / page.</p></body></html>');
120
- res.end();
121
- });
122
- app.setRoute('/{*}.css', 'GET', (req, res) => {
123
- let data = fs.readFileSync(...some.css.file...)
124
- res.writeHead(200, { 'Content-Type': 'text/css' });
125
- res.write(data);
126
- res.end();
127
- });
128
- const generateDownloadNumber = () => { Math.round(Math.random() * 10) }
129
- app.setDynamic('/download/{?}/', './main-download.txt', { DowloadName: generateDownloadNumber });
130
- // Responds to download routes such as '/download/2/'
131
- app.setFallback((req, res) => {
132
- res.writeHead(200, { 'Content-Type': 'text/html' });
133
- res.write('<html><body><p>This is the fallback page.</p></body></html>');
134
- res.end();
135
- });
136
- // Start app listening on all interfaces (0.0.0.0)
137
- app.start(port, null, () => {
138
- console.log(`Running on localhost:${port}`);
139
- console.log(app);
140
- });
141
- ```
142
- ### API modifications on 'net.Socket' instances:
143
- - The API modifies every ```net.Socket``` instance BEFORE it is passed
144
- to ```app.connectionListener```. This means that all events receiving
145
- a socket will receive the modified socket instead.
146
- - The modifications adds the following properties to the socket instance:
147
- ```
148
- <socket>.session: Object => A container for persistent data appended to sockets
149
- <socket>.session.port: Number => The local port number
150
- <socket>.session.rport: Number => The remote port number
151
- <socket>.session.host: String => The local host interface address
152
- <socket>.session.rhost: String => The remote host interface address
153
- ```
154
- - It is possible to use the ```socket.session``` object to append data that will persist
155
- during the lifetime of a single connection. Useful for keeping short-life local variables.
156
-
157
- - In HTTP ```http.IncomingMessage``` instances, the 'socket' instance is found over 'request'.
158
- So, considering the common callback of ```(req, res)```, the session container will be ```req.session```
159
-
160
- ### API security headers implementation:
161
- - It is possible to enforce a higher set of security headers on responses
162
- without having to set them manually. The API 'enableStrictHeaders' and 'disableStrictHeaders'
163
- methods do exacly that. The strict headers are disabled by default, as some resources are too strict,
164
- but it is also possible to enable them all, and then set a middleware to override any header.
165
- - Headers set by 'enableStrictHeaders':
166
- ```
167
- Content-Security-Policy: default-src=none; script-src=self; connect-src=self; img-src=self;
168
- style-src=self; frame-ancestors=none; form-action=self;
169
- Cross-Origin-Opener-Policy: same-origin
170
- Cross-Origin-Resource-Policy: same-site
171
- Origin-Agent-Cluster: ?1
172
- Referrer-Policy: no-referrer
173
- Strict-Transport-Security: max-age=31536000; includeSubDomains // temporarily disabled for maintenance
174
- X-Content-Type-Options: nosniff // temporarily disabled for maintenance
175
- X-DNS-Prefetch-Control: off
176
- X-Download-Options: noopen
177
- X-Frame-Options: DENY
178
- X-Powered-By: (This header is removed if a response includes it)
179
- X-XSS-Protection: 0
180
- ```