@jwn-js/common 2.0.9 → 2.0.14

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/Jwt.js CHANGED
@@ -2,9 +2,43 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- require('crypto');
6
- var Jwt = require('./Jwt-e49753f6.js');
5
+ var crypto = require('crypto');
6
+ var decoders = require('./decoders-ee9f4396.js');
7
7
 
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
9
 
10
+ var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
9
11
 
10
- exports.Jwt = Jwt.Jwt;
12
+ class Jwt {
13
+ constructor(secret, opt) {
14
+ this.algorithm = "SHA256";
15
+ this.secret = secret;
16
+ this.algorithm = opt?.algorithm || this.algorithm;
17
+ this.algorithm = this.algorithm.replace("-", "");
18
+ }
19
+ verify(jwt) {
20
+ if (!jwt) {
21
+ return false;
22
+ }
23
+ const parts = jwt.split(".");
24
+ const signature = decoders.urlEncode(crypto__default["default"].createHmac(this.algorithm, this.secret).update(`${parts[0]}.${parts[1]}`).digest("base64"));
25
+ return signature === parts[2];
26
+ }
27
+ sign(data) {
28
+ const head = decoders.toBase64url({
29
+ alg: this.algorithm.replace("SHA", "HS"),
30
+ typ: "JWT"
31
+ });
32
+ const body = decoders.toBase64url(data);
33
+ const signature = decoders.urlEncode(crypto__default["default"].createHmac(this.algorithm, this.secret).update(`${head}.${body}`).digest("base64"));
34
+ return `${head}.${body}.${signature}`;
35
+ }
36
+ decode(jwt) {
37
+ const parts = (jwt || "").split(".");
38
+ const head = decoders.fromBase64url(parts[0]);
39
+ const body = decoders.fromBase64url(parts[1]);
40
+ return { head, body };
41
+ }
42
+ }
43
+
44
+ exports.Jwt = Jwt;
package/Memcached.d.ts CHANGED
@@ -16,6 +16,10 @@ declare class Memcached {
16
16
  constructor(memjs: Client | null, specialHeaders?: {
17
17
  'x-cache': string;
18
18
  }, maxKeyLength?: number, debug?: number);
19
+ /**
20
+ * Is Client exists
21
+ */
22
+ isClient(): boolean;
19
23
  /**
20
24
  * Set value to memcache
21
25
  * @param key string key
package/Memcached.js CHANGED
@@ -11,6 +11,9 @@ class Memcached {
11
11
  this.debug = debug;
12
12
  this.prefix = process.env.NODE_ENV !== "production" ? "dev::" : "";
13
13
  }
14
+ isClient() {
15
+ return !!this.memjs;
16
+ }
14
17
  async setValue(key, value, expires) {
15
18
  if ((expires || expires === 0) && key.length <= this.maxKeyLength && this.memjs) {
16
19
  try {
package/Server.js CHANGED
@@ -2,11 +2,235 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- require('dns');
6
- require('uWebSockets.js');
7
- var Server = require('./Server-dadc1f87.js');
5
+ var dns = require('dns');
6
+ var uws = require('uWebSockets.js');
7
+ var cookieParse = require('./cookieParse-49f1da46.js');
8
8
 
9
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
10
 
11
+ var dns__default = /*#__PURE__*/_interopDefaultLegacy(dns);
12
+ var uws__default = /*#__PURE__*/_interopDefaultLegacy(uws);
10
13
 
11
- exports.Server = Server.Server;
12
- exports.codeToStatus = Server.codeToStatus;
14
+ const status = {
15
+ 100: "100 Continue",
16
+ 101: "101 Switching Protocols",
17
+ 200: "200 OK",
18
+ 201: "201 Created",
19
+ 202: "202 Accepted",
20
+ 203: "203 Non-Authoritative Information",
21
+ 204: "No Content",
22
+ 205: "205 Reset Content",
23
+ 206: "206 Partial Content",
24
+ 300: "300 Multiple Choices",
25
+ 301: "301 Moved Permanently",
26
+ 302: "302 Found",
27
+ 303: "303 See Other",
28
+ 304: "304 Not Modified",
29
+ 305: "305 Use Proxy",
30
+ 306: "306 (Unused)",
31
+ 307: "307 Temporary Redirect",
32
+ 400: "400 Bad Request",
33
+ 401: "401 Unauthorized",
34
+ 402: "402 Payment Required",
35
+ 403: "403 Forbidden",
36
+ 404: "404 Not Found",
37
+ 405: "405 Method Not Allowed",
38
+ 406: "406 Not Acceptable",
39
+ 407: "407 Proxy Authentication Required",
40
+ 408: "408 Request Timeout",
41
+ 409: "409 Conflict",
42
+ 410: "410 Gone",
43
+ 411: "411 Length Required",
44
+ 412: "412 Precondition Failed",
45
+ 413: "413 Request Entity Too Large",
46
+ 414: "414 Request-URI Too Long",
47
+ 415: "415 Unsupported Media Type",
48
+ 416: "416 Requested Range Not Satisfiable",
49
+ 417: "417 Expectation Failed",
50
+ 500: "500 Internal Server Error",
51
+ 501: "501 Not Implemented",
52
+ 502: "502 Bad Gateway",
53
+ 503: "503 Service Unavailable",
54
+ 504: "504 Gateway Timeout",
55
+ 505: "505 HTTP Version Not Supported"
56
+ };
57
+ const codeToStatus = (code) => {
58
+ return status.hasOwnProperty(code) ? status[code] : `${code}`;
59
+ };
60
+ class Server {
61
+ constructor(options) {
62
+ this._socket = null;
63
+ this._timeout = 0;
64
+ this._routes = [];
65
+ this._host = "localhost";
66
+ this._port = 3e3;
67
+ this._mode = "production";
68
+ this._appOptions = {};
69
+ this._defaultRoute = {
70
+ method: "get",
71
+ pattern: "/*",
72
+ handler: (res, req, next) => next()
73
+ };
74
+ this._routes = options.routes || this._routes;
75
+ this._host = options.host || this._host;
76
+ this._port = options.port || this._port;
77
+ this._timeout = options.timeout || this._timeout;
78
+ this._mode = options.mode || this._mode;
79
+ this._appOptions = options.appOptions || this._appOptions;
80
+ }
81
+ getApp() {
82
+ return this._app;
83
+ }
84
+ app() {
85
+ this._protocol = "http";
86
+ this._app = uws__default["default"].App(this._appOptions);
87
+ return this;
88
+ }
89
+ sslApp() {
90
+ this._protocol = "https";
91
+ this._app = uws__default["default"].SSLApp(this._appOptions);
92
+ return this;
93
+ }
94
+ push(route) {
95
+ this._routes.push(route);
96
+ return this;
97
+ }
98
+ unshift(route) {
99
+ this._routes.unshift(route);
100
+ return this;
101
+ }
102
+ listen(host, port, fn = () => {
103
+ }) {
104
+ if (typeof port === "number") {
105
+ this._port = port;
106
+ this._host = host;
107
+ } else if (typeof host === "number") {
108
+ if (typeof port === "function") {
109
+ fn = port;
110
+ }
111
+ this._port = host;
112
+ } else if (typeof host === "function") {
113
+ fn = host;
114
+ }
115
+ if (!this._app) {
116
+ throw new Error("Create app or sslApp first");
117
+ }
118
+ this._lookup(this._host, (ip) => {
119
+ for (let route of this._routes) {
120
+ route = typeof route === "function" ? { handler: route } : route;
121
+ route = Object.assign({}, this._defaultRoute, route);
122
+ switch (route.method) {
123
+ case "ws":
124
+ this._app[route.method](route.pattern, route.behavior);
125
+ break;
126
+ default:
127
+ const routeHandler = route;
128
+ this._app[routeHandler.method](route.pattern, (res, req) => {
129
+ res.redirect = (url, code = 307) => this.constructor._redirect(res, req, url, code);
130
+ req.cookies = cookieParse.cookieParse(req.getHeader("cookie"));
131
+ Promise.race([
132
+ this._abortTimeout(res, req),
133
+ this._createHandler(res, req, routeHandler.handler)
134
+ ]);
135
+ });
136
+ }
137
+ }
138
+ this._app.listen(ip, this._port, (listenSocket) => {
139
+ fn(listenSocket);
140
+ if (listenSocket) {
141
+ this._socket = listenSocket;
142
+ if (this._mode === "development") {
143
+ console.log(`Listening ${this._protocol}://${this._host}:${this._port}`);
144
+ }
145
+ } else {
146
+ console.error(`Error start server on ${this._protocol}://${this._host}:${this._port}`);
147
+ }
148
+ });
149
+ });
150
+ return this;
151
+ }
152
+ async close() {
153
+ if (this._socket) {
154
+ await uws__default["default"].us_listen_socket_close(this._socket);
155
+ while (true) {
156
+ await new Promise((resolve) => setTimeout(resolve, 50));
157
+ if (await this.socketPort() < 0) {
158
+ break;
159
+ }
160
+ }
161
+ this._socket = null;
162
+ }
163
+ return this;
164
+ }
165
+ async socketPort() {
166
+ if (!this._socket) {
167
+ return -1;
168
+ }
169
+ return uws__default["default"].us_socket_local_port(this._socket);
170
+ }
171
+ _createHandler(res, req, fn) {
172
+ return new Promise(async (resolve) => {
173
+ const end = () => {
174
+ clearTimeout(this._timeoutId);
175
+ resolve();
176
+ };
177
+ try {
178
+ const next = (param, code = 307) => {
179
+ if (typeof param === "boolean") {
180
+ req.setYield(param);
181
+ }
182
+ if (param instanceof Error) {
183
+ throw param;
184
+ }
185
+ if (typeof param === "string") {
186
+ res.redirect(param, code);
187
+ }
188
+ end();
189
+ };
190
+ const result = fn(res, req, next);
191
+ if (result instanceof Promise) {
192
+ next(await result);
193
+ }
194
+ } catch (e) {
195
+ const body = this._mode === "development" ? e.message : "";
196
+ try {
197
+ res.writeStatus("404 Not Found").end(body);
198
+ } catch (e2) {
199
+ }
200
+ end();
201
+ }
202
+ });
203
+ }
204
+ static _redirect(res, req, url, code = 307) {
205
+ let status2 = "307 Temporary Redirect";
206
+ if (code === 301) {
207
+ status2 = "301 Moved Permanently";
208
+ }
209
+ res.writeStatus(status2).writeHeader("location", url).end();
210
+ }
211
+ _abortTimeout(res, req) {
212
+ return new Promise((resolve) => {
213
+ if (this._timeout && !req.getHeader("x-no-timeout")) {
214
+ this._timeoutId = setTimeout(() => {
215
+ try {
216
+ res.writeStatus("408 Request Timeout").end();
217
+ resolve();
218
+ } catch (e) {
219
+ }
220
+ }, this._timeout);
221
+ }
222
+ });
223
+ }
224
+ _lookup(host, resolve) {
225
+ dns__default["default"].lookup(this._host, (err, addresses) => {
226
+ if (err) {
227
+ console.log(`${this._host} error: ${err.message}`);
228
+ } else {
229
+ resolve(Buffer.from(addresses));
230
+ }
231
+ });
232
+ }
233
+ }
234
+
235
+ exports.Server = Server;
236
+ exports.codeToStatus = codeToStatus;
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const cookieParse = (str) => {
4
+ if (!str) {
5
+ return {};
6
+ }
7
+ return str.split(/; */).reduce((obj, str2) => {
8
+ if (str2 === "") {
9
+ return obj;
10
+ }
11
+ const eq = str2.indexOf("=");
12
+ const key = eq > 0 ? str2.slice(0, eq) : str2;
13
+ let val = eq > 0 ? str2.slice(eq + 1) : null;
14
+ if (val != null) {
15
+ try {
16
+ val = decodeURIComponent(val);
17
+ } catch (ex) {
18
+ }
19
+ }
20
+ obj[key] = val;
21
+ return obj;
22
+ }, {});
23
+ };
24
+
25
+ exports.cookieParse = cookieParse;
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ const urlEncode = (str) => {
4
+ return str.replace(/\+/ig, "-").replace(/\//ig, "_").replace(/=+$/, "");
5
+ };
6
+ const urlDecode = (str) => {
7
+ return str.replace(/-/ig, "+").replace(/_/ig, "/");
8
+ };
9
+ const toBase64url = (params) => {
10
+ return urlEncode(Buffer.from(JSON.stringify(params)).toString("base64"));
11
+ };
12
+ const fromBase64url = (str) => {
13
+ return JSON.parse(Buffer.from(urlDecode(str), "base64").toString());
14
+ };
15
+
16
+ exports.fromBase64url = fromBase64url;
17
+ exports.toBase64url = toBase64url;
18
+ exports.urlEncode = urlEncode;