@verdaccio/auth 8.0.6 → 8.1.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/build/auth.js CHANGED
@@ -1,687 +1,426 @@
1
- "use strict";
1
+ const require_runtime = require("./_virtual/_rolldown/runtime.js");
2
+ const require_utils = require("./utils.js");
3
+ let debug = require("debug");
4
+ debug = require_runtime.__toESM(debug);
5
+ let lodash = require("lodash");
6
+ lodash = require_runtime.__toESM(lodash);
7
+ let verdaccio_htpasswd = require("verdaccio-htpasswd");
8
+ let _verdaccio_config = require("@verdaccio/config");
9
+ let _verdaccio_core = require("@verdaccio/core");
10
+ let _verdaccio_loaders = require("@verdaccio/loaders");
11
+ let _verdaccio_signature = require("@verdaccio/signature");
12
+ //#region src/auth.ts
13
+ var debug$1 = (0, debug.default)("verdaccio:auth");
14
+ var Auth = class {
15
+ config;
16
+ secret;
17
+ logger;
18
+ plugins;
19
+ options;
20
+ constructor(config, logger, options = { legacyMergeConfigs: false }) {
21
+ this.config = config;
22
+ this.secret = config.secret;
23
+ this.logger = logger;
24
+ this.plugins = [];
25
+ this.options = options;
26
+ if (!this.secret) throw new TypeError("secret it is required value on initialize the auth class");
27
+ }
28
+ async init() {
29
+ let plugins = await this.loadPlugin();
30
+ debug$1("auth plugins found %s", plugins.length);
31
+ if (this.config.auth !== null && (!plugins || plugins.length === 0)) plugins = this.loadDefaultPlugin();
32
+ this.plugins = plugins;
33
+ this.applyFallbackPluginMethods();
34
+ }
35
+ loadDefaultPlugin() {
36
+ debug$1("load default auth plugin");
37
+ let authPlugin;
38
+ try {
39
+ authPlugin = new verdaccio_htpasswd.HTPasswd({ file: "./htpasswd" }, {
40
+ config: this.config,
41
+ logger: this.logger
42
+ });
43
+ this.logger.info({
44
+ name: "verdaccio-htpasswd",
45
+ pluginCategory: _verdaccio_core.PLUGIN_CATEGORY.AUTHENTICATION
46
+ }, "plugin @{name} successfully loaded (@{pluginCategory})");
47
+ } catch (error) {
48
+ debug$1("error on loading auth htpasswd plugin stack: %o", error);
49
+ this.logger.info({}, "no auth plugin has been found");
50
+ return [];
51
+ }
52
+ return [authPlugin];
53
+ }
54
+ async loadPlugin() {
55
+ return (0, _verdaccio_loaders.asyncLoadPlugin)(this.config.auth, {
56
+ config: this.config,
57
+ logger: this.logger
58
+ }, (plugin) => {
59
+ const { authenticate, allow_access, allow_publish } = plugin;
60
+ return typeof authenticate !== "undefined" || typeof allow_access !== "undefined" || typeof allow_publish !== "undefined";
61
+ }, this.options.legacyMergeConfigs, this.config?.server?.pluginPrefix ?? _verdaccio_core.PLUGIN_PREFIX, _verdaccio_core.PLUGIN_CATEGORY.AUTHENTICATION);
62
+ }
63
+ applyFallbackPluginMethods() {
64
+ this.plugins.push(require_utils.getDefaultPluginMethods(this.logger));
65
+ }
66
+ changePassword(username, password, newPassword, cb) {
67
+ const validPlugins = lodash.default.filter(this.plugins, (plugin) => lodash.default.isFunction(plugin.changePassword));
68
+ if (lodash.default.isEmpty(validPlugins)) return cb(_verdaccio_core.errorUtils.getInternalError(_verdaccio_core.SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
69
+ for (const plugin of validPlugins) if (lodash.default.isNil(plugin) || lodash.default.isFunction(plugin.changePassword) === false) {
70
+ debug$1("auth plugin does not implement changePassword, trying next one");
71
+ continue;
72
+ } else {
73
+ debug$1("updating password for %o", username);
74
+ plugin.changePassword(username, password, newPassword, (err, profile) => {
75
+ if (err) {
76
+ this.logger.error({
77
+ username,
78
+ err
79
+ }, `An error has been produced
80
+ updating the password for @{username}. Error: @{err.message}`);
81
+ return cb(err);
82
+ }
83
+ debug$1("updated password for %o was successful", username);
84
+ return cb(null, profile);
85
+ });
86
+ }
87
+ }
88
+ async invalidateToken(token) {
89
+ console.log("invalidate token pending to implement", token);
90
+ return Promise.resolve();
91
+ }
92
+ authenticate(username, password, cb) {
93
+ const plugins = this.plugins.slice(0);
94
+ (function next() {
95
+ const plugin = plugins.shift();
96
+ if (typeof plugin?.authenticate !== "function") return next();
97
+ debug$1("authenticating %o", username);
98
+ plugin.authenticate(username, password, function(err, groups) {
99
+ if (err) {
100
+ debug$1("authenticating for user %o failed. Error: %o", username, err?.message);
101
+ return cb(err);
102
+ }
103
+ if (!!groups && groups.length !== 0) {
104
+ if (lodash.default.isString(groups)) throw new TypeError("plugin group error: invalid type for function");
105
+ if (!lodash.default.isArray(groups)) throw new TypeError(_verdaccio_core.API_ERROR.BAD_FORMAT_USER_GROUP);
106
+ debug$1("authentication for user %o was successfully. Groups: %o", username, groups);
107
+ return cb(err, (0, _verdaccio_config.createRemoteUser)(username, groups));
108
+ }
109
+ next();
110
+ });
111
+ })();
112
+ }
113
+ add_user(user, password, cb) {
114
+ const self = this;
115
+ const plugins = this.plugins.slice(0);
116
+ debug$1("add user %o", user);
117
+ (function next() {
118
+ let method = "adduser";
119
+ const plugin = plugins.shift();
120
+ if (typeof plugin.adduser === "undefined" && typeof plugin.add_user === "function") {
121
+ method = "add_user";
122
+ _verdaccio_core.warningUtils.emit(_verdaccio_core.warningUtils.Codes.VERWAR006);
123
+ }
124
+ if (typeof plugin[method] !== "function") next();
125
+ else plugin[method](user, password, function(err, ok) {
126
+ if (err) {
127
+ debug$1("the user %o could not be added. Error: %o", user, err?.message);
128
+ return cb(err);
129
+ }
130
+ if (ok) {
131
+ debug$1("the user %o has been added", user);
132
+ return self.authenticate(user, password, cb);
133
+ }
134
+ debug$1("user could not be added, skip to next auth plugin");
135
+ next();
136
+ });
137
+ })();
138
+ }
139
+ /**
140
+ * Allow user to access a package.
141
+ */
142
+ allow_access({ packageName, packageVersion }, user, callback) {
143
+ const plugins = this.plugins.slice(0);
144
+ const pkg = Object.assign({
145
+ name: packageName,
146
+ version: packageVersion
147
+ }, _verdaccio_core.authUtils.getMatchedPackagesSpec(packageName, this.config.packages));
148
+ debug$1("check access permissions for user %o to package %o", user.name, packageName);
149
+ const next = () => {
150
+ const plugin = plugins.shift();
151
+ if (typeof plugin?.allow_access !== "function") {
152
+ debug$1("plugin does not implement allow_access");
153
+ return next();
154
+ }
155
+ plugin.allow_access(user, pkg, (err, ok) => {
156
+ if (err) {
157
+ debug$1("forbidden access. Error: %o", err);
158
+ return callback(err);
159
+ }
160
+ if (ok) {
161
+ debug$1("access was granted");
162
+ this.logger.trace({
163
+ user: user.name,
164
+ name: pkg.name
165
+ }, `access was granted for @{name} by @{user}`);
166
+ return callback(null, ok);
167
+ }
168
+ debug$1("access was denied. Rolling to next plugin");
169
+ this.logger.trace({
170
+ user: user.name,
171
+ name: pkg.name
172
+ }, `intermediate access denial for @{name} by @{user}, rolling to next plugin`);
173
+ return next();
174
+ });
175
+ };
176
+ return next();
177
+ }
178
+ allow_unpublish({ packageName, packageVersion }, user, callback) {
179
+ const plugins = this.plugins.slice(0);
180
+ const pkg = Object.assign({
181
+ name: packageName,
182
+ version: packageVersion
183
+ }, _verdaccio_core.authUtils.getMatchedPackagesSpec(packageName, this.config.packages));
184
+ debug$1("check unpublish permissions for user %o to package %o", user.name, packageName);
185
+ const next = () => {
186
+ const plugin = plugins.shift();
187
+ if (typeof plugin?.allow_unpublish !== "function") {
188
+ debug$1("plugin does not implement allow_unpublish");
189
+ return next();
190
+ }
191
+ plugin.allow_unpublish(user, pkg, (err, ok) => {
192
+ if (err) {
193
+ debug$1("forbidden unpublish. Error: %o", err);
194
+ return callback(err);
195
+ }
196
+ if (lodash.default.isNil(ok) === true) {
197
+ debug$1("bypass unpublish for %o, publish will handle the access", packageName);
198
+ this.logger.trace({
199
+ user: user.name,
200
+ name: pkg.name
201
+ }, `bypass unpublish for @{name} by @{user}, publish will handle the access`);
202
+ return this.allow_publish({
203
+ packageName,
204
+ packageVersion
205
+ }, user, callback);
206
+ }
207
+ if (ok) {
208
+ debug$1("unpublish was granted");
209
+ this.logger.trace({
210
+ user: user.name,
211
+ name: pkg.name
212
+ }, `unpublish was granted for @{name} by @{user}`);
213
+ return callback(null, ok);
214
+ }
215
+ debug$1("unpublish was denied. Rolling to next plugin");
216
+ this.logger.trace({
217
+ user: user.name,
218
+ name: pkg.name
219
+ }, `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`);
220
+ return next();
221
+ });
222
+ };
223
+ return next();
224
+ }
225
+ /**
226
+ * Allow user to publish a package.
227
+ */
228
+ allow_publish({ packageName, packageVersion }, user, callback) {
229
+ const plugins = this.plugins.slice(0);
230
+ const pkg = Object.assign({
231
+ name: packageName,
232
+ version: packageVersion
233
+ }, _verdaccio_core.authUtils.getMatchedPackagesSpec(packageName, this.config.packages));
234
+ debug$1("check publish permissions for user %o to package %o", user.name, packageName);
235
+ const next = () => {
236
+ const plugin = plugins.shift();
237
+ if (typeof plugin?.allow_publish !== "function") {
238
+ debug$1("plugin does not implement allow_publish");
239
+ return next();
240
+ }
241
+ plugin.allow_publish(user, pkg, (err, ok) => {
242
+ if (err) {
243
+ debug$1("forbidden publish. Error: %o", err);
244
+ return callback(err);
245
+ }
246
+ if (ok) {
247
+ debug$1("publish was granted");
248
+ this.logger.trace({
249
+ user: user.name,
250
+ name: pkg.name
251
+ }, `publish was granted for @{name} by @{user}`);
252
+ return callback(null, ok);
253
+ }
254
+ debug$1("publish was denied. Rolling to next plugin");
255
+ this.logger.trace({
256
+ user: user.name,
257
+ name: pkg.name
258
+ }, `intermediate publish denial for @{name} by @{user}, rolling to next plugin`);
259
+ return next();
260
+ });
261
+ };
262
+ return next();
263
+ }
264
+ apiJWTmiddleware() {
265
+ debug$1("jwt middleware");
266
+ const plugins = this.plugins.slice(0);
267
+ const helpers = {
268
+ createAnonymousRemoteUser: _verdaccio_config.createAnonymousRemoteUser,
269
+ createRemoteUser: _verdaccio_config.createRemoteUser
270
+ };
271
+ for (const plugin of plugins) if (plugin.apiJWTmiddleware) return plugin.apiJWTmiddleware(helpers);
272
+ return (req, res, _next) => {
273
+ req.pause();
274
+ const next = function(err) {
275
+ req.resume();
276
+ if (err) req.remote_user.error = err.message;
277
+ return _next();
278
+ };
279
+ const remoteUser = (0, _verdaccio_config.createAnonymousRemoteUser)();
280
+ req.remote_user = remoteUser;
281
+ res.locals.remote_user = remoteUser;
282
+ const { authorization } = req.headers;
283
+ if (lodash.default.isNil(authorization)) {
284
+ debug$1("jwt, authentication header is missing");
285
+ return next();
286
+ }
287
+ if (!require_utils.isAuthHeaderValid(authorization)) {
288
+ debug$1("api middleware authentication heather is invalid");
289
+ return next(_verdaccio_core.errorUtils.getBadRequest(_verdaccio_core.API_ERROR.BAD_AUTH_HEADER));
290
+ }
291
+ const { secret, security } = this.config;
292
+ if (require_utils.isAESLegacy(security)) {
293
+ debug$1("api middleware using legacy auth token");
294
+ this.handleAESMiddleware(req, security, secret, authorization, next);
295
+ } else {
296
+ debug$1("api middleware using JWT auth token");
297
+ this.handleJWTAPIMiddleware(req, security, secret, authorization, next);
298
+ }
299
+ };
300
+ }
301
+ handleJWTAPIMiddleware(req, security, secret, authorization, next) {
302
+ debug$1("handle JWT api middleware");
303
+ const { scheme, token } = require_utils.parseAuthTokenHeader(authorization);
304
+ if (scheme.toUpperCase() === _verdaccio_core.TOKEN_BASIC.toUpperCase()) {
305
+ debug$1("handle basic token");
306
+ const parsedCredentials = (0, _verdaccio_signature.parseBasicPayload)(require_utils.convertPayloadToBase64(token).toString());
307
+ if (!parsedCredentials) {
308
+ debug$1("invalid basic credentials format (missing colon separator)");
309
+ next(_verdaccio_core.errorUtils.getBadRequest(_verdaccio_core.API_ERROR.BAD_USERNAME_PASSWORD));
310
+ return;
311
+ }
312
+ const { user, password, tokenKey } = parsedCredentials;
313
+ debug$1("authenticating %o", user);
314
+ this.authenticate(user, password, (err, user) => {
315
+ if (!err) {
316
+ debug$1("generating a remote user");
317
+ req.remote_user = tokenKey ? {
318
+ ...user,
319
+ token: { key: tokenKey }
320
+ } : user;
321
+ next();
322
+ } else {
323
+ debug$1("generating anonymous user");
324
+ req.remote_user = (0, _verdaccio_config.createAnonymousRemoteUser)();
325
+ next(err);
326
+ }
327
+ });
328
+ } else {
329
+ debug$1("handle jwt token");
330
+ const credentials = require_utils.getMiddlewareCredentials(security, secret, authorization);
331
+ if (credentials) {
332
+ req.remote_user = credentials;
333
+ debug$1("generating a remote user");
334
+ next();
335
+ } else {
336
+ debug$1("jwt invalid token");
337
+ next(_verdaccio_core.errorUtils.getForbidden(_verdaccio_core.API_ERROR.BAD_USERNAME_PASSWORD));
338
+ }
339
+ }
340
+ }
341
+ handleAESMiddleware(req, security, secret, authorization, next) {
342
+ debug$1("handle legacy api middleware");
343
+ debug$1("api middleware has a secret? %o", typeof secret === "string");
344
+ debug$1("api middleware authorization %o", typeof authorization === "string");
345
+ const credentials = require_utils.getMiddlewareCredentials(security, secret, authorization);
346
+ debug$1("api middleware credentials %o", credentials?.name);
347
+ if (credentials) {
348
+ const { user, password, tokenKey } = credentials;
349
+ debug$1("authenticating %o", user);
350
+ this.authenticate(user, password, (err, user) => {
351
+ if (!err) {
352
+ req.remote_user = tokenKey ? {
353
+ ...user,
354
+ token: { key: tokenKey }
355
+ } : user;
356
+ debug$1("generating a remote user");
357
+ next();
358
+ } else {
359
+ req.remote_user = (0, _verdaccio_config.createAnonymousRemoteUser)();
360
+ debug$1("generating anonymous user");
361
+ next(err);
362
+ }
363
+ });
364
+ } else {
365
+ debug$1("legacy invalid header");
366
+ return next(_verdaccio_core.errorUtils.getBadRequest(_verdaccio_core.API_ERROR.BAD_AUTH_HEADER));
367
+ }
368
+ }
369
+ _isRemoteUserValid(remote_user) {
370
+ return lodash.default.isUndefined(remote_user) === false && lodash.default.isUndefined(remote_user?.name) === false;
371
+ }
372
+ /**
373
+ * JWT middleware for WebUI
374
+ */
375
+ webUIJWTmiddleware() {
376
+ return (req, res, _next) => {
377
+ if (this._isRemoteUserValid(req.remote_user)) return _next();
378
+ req.pause();
379
+ const next = (err) => {
380
+ req.resume();
381
+ if (err) {
382
+ req.remote_user.error = err.message;
383
+ res.status(err.statusCode).send(err.message);
384
+ }
385
+ return _next();
386
+ };
387
+ const { authorization } = req.headers;
388
+ if (lodash.default.isNil(authorization)) return next();
389
+ if (!require_utils.isAuthHeaderValid(authorization)) return next(_verdaccio_core.errorUtils.getBadRequest(_verdaccio_core.API_ERROR.BAD_AUTH_HEADER));
390
+ const token = (authorization || "").replace(`${_verdaccio_core.TOKEN_BEARER} `, "");
391
+ if (!token) return next();
392
+ let credentials;
393
+ try {
394
+ credentials = require_utils.verifyJWTPayload(token, this.config.secret, this.config.security);
395
+ } catch {}
396
+ if (this._isRemoteUserValid(credentials)) {
397
+ const { name, groups } = credentials;
398
+ req.remote_user = (0, _verdaccio_config.createRemoteUser)(name, groups);
399
+ } else req.remote_user = (0, _verdaccio_config.createAnonymousRemoteUser)();
400
+ next();
401
+ };
402
+ }
403
+ async jwtEncrypt(user, signOptions) {
404
+ const { real_groups, name, groups, token: tokenMetadata } = user;
405
+ debug$1("jwt encrypt %o", name);
406
+ const realGroupsValidated = lodash.default.isNil(real_groups) ? [] : real_groups;
407
+ const payload = {
408
+ real_groups: realGroupsValidated,
409
+ name,
410
+ groups: lodash.default.isNil(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
411
+ };
412
+ if (tokenMetadata?.key) payload.token = { key: tokenMetadata.key };
413
+ return await (0, _verdaccio_signature.signPayload)(payload, this.secret, signOptions);
414
+ }
415
+ /**
416
+ * Encrypt a string.
417
+ */
418
+ aesEncrypt(value) {
419
+ debug$1("signing with aes encryption");
420
+ return (0, _verdaccio_signature.aesEncrypt)(value, this.secret);
421
+ }
422
+ };
423
+ //#endregion
424
+ exports.Auth = Auth;
2
425
 
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.Auth = void 0;
7
- var _debug = _interopRequireDefault(require("debug"));
8
- var _lodash = _interopRequireDefault(require("lodash"));
9
- var _verdaccioHtpasswd = require("verdaccio-htpasswd");
10
- var _config = require("@verdaccio/config");
11
- var _core = require("@verdaccio/core");
12
- var _loaders = require("@verdaccio/loaders");
13
- var _signature = require("@verdaccio/signature");
14
- var _utils = require("./utils");
15
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
16
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
17
- function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
18
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
19
- function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
20
- function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
21
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
22
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
23
- function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
24
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
25
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
26
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
27
- function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
28
- function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
29
- function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
30
- function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
31
- function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
32
- function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
33
- function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
34
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
35
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
36
- var debug = (0, _debug["default"])('verdaccio:auth');
37
- var Auth = exports.Auth = /*#__PURE__*/function () {
38
- function Auth(config, logger) {
39
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
40
- legacyMergeConfigs: false
41
- };
42
- _classCallCheck(this, Auth);
43
- this.config = config;
44
- this.secret = config.secret;
45
- this.logger = logger;
46
- this.plugins = [];
47
- this.options = options;
48
- if (!this.secret) {
49
- throw new TypeError('secret it is required value on initialize the auth class');
50
- }
51
- }
52
- return _createClass(Auth, [{
53
- key: "init",
54
- value: function () {
55
- var _init = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
56
- var plugins;
57
- return _regenerator().w(function (_context) {
58
- while (1) switch (_context.n) {
59
- case 0:
60
- _context.n = 1;
61
- return this.loadPlugin();
62
- case 1:
63
- plugins = _context.v;
64
- debug('auth plugins found %s', plugins.length);
65
- // Missing auth config or no loaded plugins -> load default htpasswd plugin
66
- // Empty auth config (null) -> just use fallback methods
67
- if (this.config.auth !== null && (!plugins || plugins.length === 0)) {
68
- plugins = this.loadDefaultPlugin();
69
- }
70
- this.plugins = plugins;
71
- this.applyFallbackPluginMethods();
72
- case 2:
73
- return _context.a(2);
74
- }
75
- }, _callee, this);
76
- }));
77
- function init() {
78
- return _init.apply(this, arguments);
79
- }
80
- return init;
81
- }()
82
- }, {
83
- key: "loadDefaultPlugin",
84
- value: function loadDefaultPlugin() {
85
- debug('load default auth plugin');
86
- var authPlugin;
87
- try {
88
- authPlugin = new _verdaccioHtpasswd.HTPasswd({
89
- file: './htpasswd'
90
- }, {
91
- config: this.config,
92
- logger: this.logger
93
- });
94
- this.logger.info({
95
- name: 'verdaccio-htpasswd',
96
- pluginCategory: _core.PLUGIN_CATEGORY.AUTHENTICATION
97
- }, 'plugin @{name} successfully loaded (@{pluginCategory})');
98
- } catch (error) {
99
- debug('error on loading auth htpasswd plugin stack: %o', error);
100
- this.logger.info({}, 'no auth plugin has been found');
101
- return [];
102
- }
103
- return [authPlugin];
104
- }
105
- }, {
106
- key: "loadPlugin",
107
- value: function () {
108
- var _loadPlugin = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
109
- var _this$config$server$p, _this$config;
110
- return _regenerator().w(function (_context2) {
111
- while (1) switch (_context2.n) {
112
- case 0:
113
- return _context2.a(2, (0, _loaders.asyncLoadPlugin)(this.config.auth, {
114
- config: this.config,
115
- logger: this.logger
116
- }, function (plugin) {
117
- var authenticate = plugin.authenticate,
118
- allow_access = plugin.allow_access,
119
- allow_publish = plugin.allow_publish;
120
- return typeof authenticate !== 'undefined' || typeof allow_access !== 'undefined' || typeof allow_publish !== 'undefined';
121
- }, this.options.legacyMergeConfigs, (_this$config$server$p = (_this$config = this.config) === null || _this$config === void 0 || (_this$config = _this$config.server) === null || _this$config === void 0 ? void 0 : _this$config.pluginPrefix) !== null && _this$config$server$p !== void 0 ? _this$config$server$p : _core.PLUGIN_PREFIX, _core.PLUGIN_CATEGORY.AUTHENTICATION));
122
- }
123
- }, _callee2, this);
124
- }));
125
- function loadPlugin() {
126
- return _loadPlugin.apply(this, arguments);
127
- }
128
- return loadPlugin;
129
- }()
130
- }, {
131
- key: "applyFallbackPluginMethods",
132
- value: function applyFallbackPluginMethods() {
133
- this.plugins.push((0, _utils.getDefaultPluginMethods)(this.logger));
134
- }
135
- }, {
136
- key: "changePassword",
137
- value: function changePassword(username, password, newPassword, cb) {
138
- var _this = this;
139
- var validPlugins = _lodash["default"].filter(this.plugins, function (plugin) {
140
- return _lodash["default"].isFunction(plugin.changePassword);
141
- });
142
- if (_lodash["default"].isEmpty(validPlugins)) {
143
- return cb(_core.errorUtils.getInternalError(_core.SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
144
- }
145
- var _iterator = _createForOfIteratorHelper(validPlugins),
146
- _step;
147
- try {
148
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
149
- var plugin = _step.value;
150
- if (_lodash["default"].isNil(plugin) || _lodash["default"].isFunction(plugin.changePassword) === false) {
151
- debug('auth plugin does not implement changePassword, trying next one');
152
- continue;
153
- } else {
154
- debug('updating password for %o', username);
155
- plugin.changePassword(username, password, newPassword, function (err, profile) {
156
- if (err) {
157
- _this.logger.error({
158
- username: username,
159
- err: err
160
- }, "An error has been produced\n updating the password for @{username}. Error: @{err.message}");
161
- return cb(err);
162
- }
163
- debug('updated password for %o was successful', username);
164
- return cb(null, profile);
165
- });
166
- }
167
- }
168
- } catch (err) {
169
- _iterator.e(err);
170
- } finally {
171
- _iterator.f();
172
- }
173
- }
174
- }, {
175
- key: "invalidateToken",
176
- value: function () {
177
- var _invalidateToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(token) {
178
- return _regenerator().w(function (_context3) {
179
- while (1) switch (_context3.n) {
180
- case 0:
181
- console.log('invalidate token pending to implement', token);
182
- return _context3.a(2, Promise.resolve());
183
- }
184
- }, _callee3);
185
- }));
186
- function invalidateToken(_x) {
187
- return _invalidateToken.apply(this, arguments);
188
- }
189
- return invalidateToken;
190
- }()
191
- }, {
192
- key: "authenticate",
193
- value: function authenticate(username, password, cb) {
194
- var plugins = this.plugins.slice(0);
195
- (function next() {
196
- var plugin = plugins.shift();
197
- if (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.authenticate) !== 'function') {
198
- return next();
199
- }
200
- debug('authenticating %o', username);
201
- plugin.authenticate(username, password, function (err, groups) {
202
- if (err) {
203
- debug('authenticating for user %o failed. Error: %o', username, err === null || err === void 0 ? void 0 : err.message);
204
- return cb(err);
205
- }
206
-
207
- // Expect: SKIP if groups is falsey and not an array
208
- // with at least one item (truthy length)
209
- // Expect: CONTINUE otherwise (will error if groups is not
210
- // an array, but this is current behavior)
211
- // Caveat: STRING (if valid) will pass successfully
212
- // bug give unexpected results
213
- // Info: Cannot use `== false to check falsey values`
214
- if (!!groups && groups.length !== 0) {
215
- // TODO: create a better understanding of expectations
216
- if (_lodash["default"].isString(groups)) {
217
- throw new TypeError('plugin group error: invalid type for function');
218
- }
219
- var isGroupValid = _lodash["default"].isArray(groups);
220
- if (!isGroupValid) {
221
- throw new TypeError(_core.API_ERROR.BAD_FORMAT_USER_GROUP);
222
- }
223
- debug('authentication for user %o was successfully. Groups: %o', username, groups);
224
- return cb(err, (0, _config.createRemoteUser)(username, groups));
225
- }
226
- next();
227
- });
228
- })();
229
- }
230
- }, {
231
- key: "add_user",
232
- value: function add_user(user, password, cb) {
233
- var self = this;
234
- var plugins = this.plugins.slice(0);
235
- debug('add user %o', user);
236
- (function next() {
237
- var method = 'adduser';
238
- var plugin = plugins.shift();
239
- // @ts-expect-error future major (7.x) should remove this section
240
- if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {
241
- method = 'add_user';
242
- _core.warningUtils.emit(_core.warningUtils.Codes.VERWAR006);
243
- }
244
- // @ts-ignore
245
- if (typeof plugin[method] !== 'function') {
246
- next();
247
- } else {
248
- // TODO: replace by adduser whenever add_user deprecation method has been removed
249
- // @ts-ignore
250
- plugin[method](user, password, function (err, ok) {
251
- if (err) {
252
- debug('the user %o could not be added. Error: %o', user, err === null || err === void 0 ? void 0 : err.message);
253
- return cb(err);
254
- }
255
- if (ok) {
256
- debug('the user %o has been added', user);
257
- return self.authenticate(user, password, cb);
258
- }
259
- debug('user could not be added, skip to next auth plugin');
260
- next();
261
- });
262
- }
263
- })();
264
- }
265
-
266
- /**
267
- * Allow user to access a package.
268
- */
269
- }, {
270
- key: "allow_access",
271
- value: function allow_access(_ref, user, callback) {
272
- var _this2 = this;
273
- var packageName = _ref.packageName,
274
- packageVersion = _ref.packageVersion;
275
- var plugins = this.plugins.slice(0);
276
- var pkg = Object.assign({
277
- name: packageName,
278
- version: packageVersion
279
- }, _core.authUtils.getMatchedPackagesSpec(packageName, this.config.packages));
280
- debug('check access permissions for user %o to package %o', user.name, packageName);
281
-
282
- // Use const instead of function declaration so we can use this.logger
283
- var _next2 = function next() {
284
- var plugin = plugins.shift();
285
- if (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.allow_access) !== 'function') {
286
- debug('plugin does not implement allow_access');
287
- return _next2();
288
- }
289
- plugin.allow_access(user, pkg, function (err, ok) {
290
- if (err) {
291
- debug('forbidden access. Error: %o', err);
292
- return callback(err);
293
- }
294
- if (ok) {
295
- debug('access was granted');
296
- _this2.logger.trace({
297
- user: user.name,
298
- name: pkg.name
299
- }, "access was granted for @{name} by @{user}");
300
- return callback(null, ok);
301
- }
302
-
303
- // cb(null, false) causes next plugin to roll
304
- debug('access was denied. Rolling to next plugin');
305
- _this2.logger.trace({
306
- user: user.name,
307
- name: pkg.name
308
- }, "intermediate access denial for @{name} by @{user}, rolling to next plugin");
309
- return _next2();
310
- });
311
- };
312
- return _next2();
313
- }
314
- }, {
315
- key: "allow_unpublish",
316
- value: function allow_unpublish(_ref2, user, callback) {
317
- var _this3 = this;
318
- var packageName = _ref2.packageName,
319
- packageVersion = _ref2.packageVersion;
320
- var plugins = this.plugins.slice(0);
321
- var pkg = Object.assign({
322
- name: packageName,
323
- version: packageVersion
324
- }, _core.authUtils.getMatchedPackagesSpec(packageName, this.config.packages));
325
- debug('check unpublish permissions for user %o to package %o', user.name, packageName);
326
-
327
- // Use const instead of function declaration so we can use this.logger
328
- var _next3 = function next() {
329
- var plugin = plugins.shift();
330
- if (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.allow_unpublish) !== 'function') {
331
- debug('plugin does not implement allow_unpublish');
332
- return _next3();
333
- }
334
- plugin.allow_unpublish(user, pkg, function (err, ok) {
335
- if (err) {
336
- debug('forbidden unpublish. Error: %o', err);
337
- return callback(err);
338
- }
339
-
340
- // The following is different from the allow_access and allow_publish implementations:
341
- // If the packages config is missing an entry for "unpublish", the built-in default method
342
- // (or a plugin) will return undefined, which will trigger the allow_publish fallback.
343
- // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))
344
- if (_lodash["default"].isNil(ok) === true) {
345
- debug('bypass unpublish for %o, publish will handle the access', packageName);
346
- _this3.logger.trace({
347
- user: user.name,
348
- name: pkg.name
349
- }, "bypass unpublish for @{name} by @{user}, publish will handle the access");
350
- return _this3.allow_publish({
351
- packageName: packageName,
352
- packageVersion: packageVersion
353
- }, user, callback);
354
- }
355
- if (ok) {
356
- debug('unpublish was granted');
357
- _this3.logger.trace({
358
- user: user.name,
359
- name: pkg.name
360
- }, "unpublish was granted for @{name} by @{user}");
361
- return callback(null, ok);
362
- }
363
-
364
- // cb(null, false) causes next plugin to roll
365
- debug('unpublish was denied. Rolling to next plugin');
366
- _this3.logger.trace({
367
- user: user.name,
368
- name: pkg.name
369
- }, "intermediate unpublish denial for @{name} by @{user}, rolling to next plugin");
370
- return _next3();
371
- });
372
- };
373
- return _next3();
374
- }
375
-
376
- /**
377
- * Allow user to publish a package.
378
- */
379
- }, {
380
- key: "allow_publish",
381
- value: function allow_publish(_ref3, user, callback) {
382
- var _this4 = this;
383
- var packageName = _ref3.packageName,
384
- packageVersion = _ref3.packageVersion;
385
- var plugins = this.plugins.slice(0);
386
- var pkg = Object.assign({
387
- name: packageName,
388
- version: packageVersion
389
- }, _core.authUtils.getMatchedPackagesSpec(packageName, this.config.packages));
390
- debug('check publish permissions for user %o to package %o', user.name, packageName);
391
-
392
- // Use const instead of function declaration so we can use this.logger
393
- var _next4 = function next() {
394
- var plugin = plugins.shift();
395
- if (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.allow_publish) !== 'function') {
396
- debug('plugin does not implement allow_publish');
397
- return _next4();
398
- }
399
- plugin.allow_publish(user, pkg, function (err, ok) {
400
- if (err) {
401
- debug('forbidden publish. Error: %o', err);
402
- return callback(err);
403
- }
404
- if (ok) {
405
- debug('publish was granted');
406
- _this4.logger.trace({
407
- user: user.name,
408
- name: pkg.name
409
- }, "publish was granted for @{name} by @{user}");
410
- return callback(null, ok);
411
- }
412
-
413
- // cb(null, false) causes next plugin to roll
414
- debug('publish was denied. Rolling to next plugin');
415
- _this4.logger.trace({
416
- user: user.name,
417
- name: pkg.name
418
- }, "intermediate publish denial for @{name} by @{user}, rolling to next plugin");
419
- return _next4();
420
- });
421
- };
422
- return _next4();
423
- }
424
- }, {
425
- key: "apiJWTmiddleware",
426
- value: function apiJWTmiddleware() {
427
- var _this5 = this;
428
- debug('jwt middleware');
429
- var plugins = this.plugins.slice(0);
430
- var helpers = {
431
- createAnonymousRemoteUser: _config.createAnonymousRemoteUser,
432
- createRemoteUser: _config.createRemoteUser
433
- };
434
- var _iterator2 = _createForOfIteratorHelper(plugins),
435
- _step2;
436
- try {
437
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
438
- var plugin = _step2.value;
439
- if (plugin.apiJWTmiddleware) {
440
- return plugin.apiJWTmiddleware(helpers);
441
- }
442
- }
443
- } catch (err) {
444
- _iterator2.e(err);
445
- } finally {
446
- _iterator2.f();
447
- }
448
- return function (req, res, _next) {
449
- req.pause();
450
- var next = function next(err) {
451
- req.resume();
452
- // uncomment this to reject users with bad auth headers
453
- // return _next.apply(null, arguments)
454
- // swallow error, user remains unauthorized
455
- // set remoteUserError to indicate that user was attempting authentication
456
- if (err) {
457
- req.remote_user.error = err.message;
458
- }
459
- return _next();
460
- };
461
-
462
- // FUTURE: disabled, not removed yet but seems unreacable code
463
- // if (this._isRemoteUserValid(req.remote_user)) {
464
- // debug('jwt has a valid authentication header');
465
- // return next();
466
- // }
467
-
468
- // in case auth header does not exist we return anonymous function
469
- var remoteUser = (0, _config.createAnonymousRemoteUser)();
470
- req.remote_user = remoteUser;
471
- res.locals.remote_user = remoteUser;
472
- var authorization = req.headers.authorization;
473
- if (_lodash["default"].isNil(authorization)) {
474
- debug('jwt, authentication header is missing');
475
- return next();
476
- }
477
- if (!(0, _utils.isAuthHeaderValid)(authorization)) {
478
- debug('api middleware authentication heather is invalid');
479
- return next(_core.errorUtils.getBadRequest(_core.API_ERROR.BAD_AUTH_HEADER));
480
- }
481
- var _this5$config = _this5.config,
482
- secret = _this5$config.secret,
483
- security = _this5$config.security;
484
- if ((0, _utils.isAESLegacy)(security)) {
485
- debug('api middleware using legacy auth token');
486
- _this5.handleAESMiddleware(req, security, secret, authorization, next);
487
- } else {
488
- debug('api middleware using JWT auth token');
489
- _this5.handleJWTAPIMiddleware(req, security, secret, authorization, next);
490
- }
491
- };
492
- }
493
- }, {
494
- key: "handleJWTAPIMiddleware",
495
- value: function handleJWTAPIMiddleware(req, security, secret, authorization, next) {
496
- debug('handle JWT api middleware');
497
- var _parseAuthTokenHeader = (0, _utils.parseAuthTokenHeader)(authorization),
498
- scheme = _parseAuthTokenHeader.scheme,
499
- token = _parseAuthTokenHeader.token;
500
- if (scheme.toUpperCase() === _core.TOKEN_BASIC.toUpperCase()) {
501
- debug('handle basic token');
502
- // this should happen when client tries to login with an existing user
503
- var credentials = (0, _utils.convertPayloadToBase64)(token).toString();
504
- var parsedCredentials = (0, _signature.parseBasicPayload)(credentials);
505
- if (!parsedCredentials) {
506
- debug('invalid basic credentials format (missing colon separator)');
507
- next(_core.errorUtils.getBadRequest(_core.API_ERROR.BAD_USERNAME_PASSWORD));
508
- return;
509
- }
510
- var _ref4 = parsedCredentials,
511
- user = _ref4.user,
512
- password = _ref4.password,
513
- tokenKey = _ref4.tokenKey;
514
- debug('authenticating %o', user);
515
- this.authenticate(user, password, function (err, user) {
516
- if (!err) {
517
- debug('generating a remote user');
518
- req.remote_user = tokenKey ? _objectSpread(_objectSpread({}, user), {}, {
519
- token: {
520
- key: tokenKey
521
- }
522
- }) : user;
523
- next();
524
- } else {
525
- debug('generating anonymous user');
526
- req.remote_user = (0, _config.createAnonymousRemoteUser)();
527
- next(err);
528
- }
529
- });
530
- } else {
531
- debug('handle jwt token');
532
- var _credentials = (0, _utils.getMiddlewareCredentials)(security, secret, authorization);
533
- if (_credentials) {
534
- // if the signature is valid we rely on it
535
- req.remote_user = _credentials;
536
- debug('generating a remote user');
537
- next();
538
- } else {
539
- // with JWT throw 401
540
- debug('jwt invalid token');
541
- next(_core.errorUtils.getForbidden(_core.API_ERROR.BAD_USERNAME_PASSWORD));
542
- }
543
- }
544
- }
545
- }, {
546
- key: "handleAESMiddleware",
547
- value: function handleAESMiddleware(req, security, secret, authorization, next) {
548
- debug('handle legacy api middleware');
549
- debug('api middleware has a secret? %o', typeof secret === 'string');
550
- debug('api middleware authorization %o', typeof authorization === 'string');
551
- var credentials = (0, _utils.getMiddlewareCredentials)(security, secret, authorization);
552
- debug('api middleware credentials %o', credentials === null || credentials === void 0 ? void 0 : credentials.name);
553
- if (credentials) {
554
- var user = credentials.user,
555
- password = credentials.password,
556
- tokenKey = credentials.tokenKey;
557
- debug('authenticating %o', user);
558
- this.authenticate(user, password, function (err, user) {
559
- if (!err) {
560
- req.remote_user = tokenKey ? _objectSpread(_objectSpread({}, user), {}, {
561
- token: {
562
- key: tokenKey
563
- }
564
- }) : user;
565
- debug('generating a remote user');
566
- next();
567
- } else {
568
- req.remote_user = (0, _config.createAnonymousRemoteUser)();
569
- debug('generating anonymous user');
570
- next(err);
571
- }
572
- });
573
- } else {
574
- // we force npm client to ask again with basic authentication
575
- debug('legacy invalid header');
576
- return next(_core.errorUtils.getBadRequest(_core.API_ERROR.BAD_AUTH_HEADER));
577
- }
578
- }
579
- }, {
580
- key: "_isRemoteUserValid",
581
- value: function _isRemoteUserValid(remote_user) {
582
- return _lodash["default"].isUndefined(remote_user) === false && _lodash["default"].isUndefined(remote_user === null || remote_user === void 0 ? void 0 : remote_user.name) === false;
583
- }
584
-
585
- /**
586
- * JWT middleware for WebUI
587
- */
588
- }, {
589
- key: "webUIJWTmiddleware",
590
- value: function webUIJWTmiddleware() {
591
- var _this6 = this;
592
- return function (req, res, _next) {
593
- if (_this6._isRemoteUserValid(req.remote_user)) {
594
- return _next();
595
- }
596
- req.pause();
597
- var next = function next(err) {
598
- req.resume();
599
- if (err) {
600
- req.remote_user.error = err.message;
601
- res.status(err.statusCode).send(err.message);
602
- }
603
- return _next();
604
- };
605
- var authorization = req.headers.authorization;
606
- if (_lodash["default"].isNil(authorization)) {
607
- return next();
608
- }
609
- if (!(0, _utils.isAuthHeaderValid)(authorization)) {
610
- return next(_core.errorUtils.getBadRequest(_core.API_ERROR.BAD_AUTH_HEADER));
611
- }
612
- var token = (authorization || '').replace("".concat(_core.TOKEN_BEARER, " "), '');
613
- if (!token) {
614
- return next();
615
- }
616
- var credentials;
617
- try {
618
- credentials = (0, _utils.verifyJWTPayload)(token, _this6.config.secret, _this6.config.security);
619
- } catch (_unused) {
620
- // FIXME: intended behaviour, do we want it?
621
- }
622
- if (_this6._isRemoteUserValid(credentials)) {
623
- var _ref5 = credentials,
624
- name = _ref5.name,
625
- groups = _ref5.groups;
626
- req.remote_user = (0, _config.createRemoteUser)(name, groups);
627
- } else {
628
- req.remote_user = (0, _config.createAnonymousRemoteUser)();
629
- }
630
- next();
631
- };
632
- }
633
- }, {
634
- key: "jwtEncrypt",
635
- value: function () {
636
- var _jwtEncrypt = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(user, signOptions) {
637
- var real_groups, name, groups, tokenMetadata, realGroupsValidated, groupedGroups, payload, signedToken;
638
- return _regenerator().w(function (_context4) {
639
- while (1) switch (_context4.n) {
640
- case 0:
641
- real_groups = user.real_groups, name = user.name, groups = user.groups, tokenMetadata = user.token;
642
- debug('jwt encrypt %o', name);
643
- realGroupsValidated = _lodash["default"].isNil(real_groups) ? [] : real_groups;
644
- groupedGroups = _lodash["default"].isNil(groups) ? real_groups : Array.from(new Set(_toConsumableArray(groups.concat(realGroupsValidated))));
645
- payload = {
646
- real_groups: realGroupsValidated,
647
- name: name,
648
- groups: groupedGroups
649
- };
650
- if (tokenMetadata !== null && tokenMetadata !== void 0 && tokenMetadata.key) {
651
- payload.token = {
652
- key: tokenMetadata.key
653
- };
654
- }
655
- _context4.n = 1;
656
- return (0, _signature.signPayload)(payload, this.secret, signOptions);
657
- case 1:
658
- signedToken = _context4.v;
659
- return _context4.a(2, signedToken);
660
- }
661
- }, _callee4, this);
662
- }));
663
- function jwtEncrypt(_x2, _x3) {
664
- return _jwtEncrypt.apply(this, arguments);
665
- }
666
- return jwtEncrypt;
667
- }()
668
- /**
669
- * Encrypt a string.
670
- */
671
- }, {
672
- key: "aesEncrypt",
673
- value: function aesEncrypt(value) {
674
- if (this.secret.length === _config.TOKEN_VALID_LENGTH) {
675
- debug('signing with enhanced aes legacy');
676
- var token = (0, _signature.aesEncrypt)(value, this.secret);
677
- return token;
678
- } else {
679
- debug('signing with enhanced aes deprecated legacy');
680
- // deprecated aes (legacy) signature, only must be used for legacy version
681
- var _token = (0, _signature.aesEncryptDeprecated)(Buffer.from(value), this.secret).toString('base64');
682
- return _token;
683
- }
684
- }
685
- }]);
686
- }();
687
426
  //# sourceMappingURL=auth.js.map