@verdaccio/auth 9.0.0-next-9.6 → 9.0.0-next-9.8

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
@@ -2,8 +2,7 @@ const require_runtime = require("./_virtual/_rolldown/runtime.js");
2
2
  const require_utils = require("./utils.js");
3
3
  let debug = require("debug");
4
4
  debug = require_runtime.__toESM(debug);
5
- let lodash = require("lodash");
6
- lodash = require_runtime.__toESM(lodash);
5
+ let lodash_es = require("lodash-es");
7
6
  let verdaccio_htpasswd = require("verdaccio-htpasswd");
8
7
  let _verdaccio_config = require("@verdaccio/config");
9
8
  let _verdaccio_core = require("@verdaccio/core");
@@ -61,9 +60,9 @@ var Auth = class {
61
60
  this.plugins.push(require_utils.getDefaultPluginMethods(this.logger));
62
61
  }
63
62
  changePassword(username, password, newPassword, cb) {
64
- const validPlugins = lodash.default.filter(this.plugins, (plugin) => lodash.default.isFunction(plugin.changePassword));
65
- if (lodash.default.isEmpty(validPlugins)) return cb(_verdaccio_core.errorUtils.getInternalError(_verdaccio_core.SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
66
- for (const plugin of validPlugins) if (lodash.default.isNil(plugin) || lodash.default.isFunction(plugin.changePassword) === false) {
63
+ const validPlugins = (0, lodash_es.filter)(this.plugins, (plugin) => typeof plugin.changePassword === "function");
64
+ if ((0, lodash_es.isEmpty)(validPlugins)) return cb(_verdaccio_core.errorUtils.getInternalError(_verdaccio_core.SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
65
+ for (const plugin of validPlugins) if ((0, lodash_es.isNil)(plugin) || typeof plugin.changePassword !== "function") {
67
66
  debug$1("auth plugin does not implement changePassword, trying next one");
68
67
  continue;
69
68
  } else {
@@ -98,8 +97,8 @@ var Auth = class {
98
97
  return cb(err);
99
98
  }
100
99
  if (!!groups && groups.length !== 0) {
101
- if (lodash.default.isString(groups)) throw new TypeError("plugin group error: invalid type for function");
102
- if (!lodash.default.isArray(groups)) throw new TypeError(_verdaccio_core.API_ERROR.BAD_FORMAT_USER_GROUP);
100
+ if (typeof groups === "string") throw new TypeError("plugin group error: invalid type for function");
101
+ if (!Array.isArray(groups)) throw new TypeError(_verdaccio_core.API_ERROR.BAD_FORMAT_USER_GROUP);
103
102
  debug$1("authentication for user %o was successfully. Groups: %o", username, groups);
104
103
  return cb(err, (0, _verdaccio_config.createRemoteUser)(username, groups));
105
104
  }
@@ -190,7 +189,7 @@ var Auth = class {
190
189
  debug$1("forbidden unpublish. Error: %o", err);
191
190
  return callback(err);
192
191
  }
193
- if (lodash.default.isNil(ok) === true) {
192
+ if ((0, lodash_es.isNil)(ok) === true) {
194
193
  debug$1("bypass unpublish for %o, publish will handle the access", packageName);
195
194
  this.logger.trace({
196
195
  user: user.name,
@@ -277,7 +276,7 @@ var Auth = class {
277
276
  req.remote_user = remoteUser;
278
277
  res.locals.remote_user = remoteUser;
279
278
  const { authorization } = req.headers;
280
- if (lodash.default.isNil(authorization)) {
279
+ if ((0, lodash_es.isNil)(authorization)) {
281
280
  debug$1("jwt, authentication header is missing");
282
281
  return next();
283
282
  }
@@ -358,7 +357,7 @@ var Auth = class {
358
357
  }
359
358
  }
360
359
  _isRemoteUserValid(remote_user) {
361
- return lodash.default.isUndefined(remote_user) === false && lodash.default.isUndefined(remote_user?.name) === false;
360
+ return (0, lodash_es.isUndefined)(remote_user) === false && (0, lodash_es.isUndefined)(remote_user?.name) === false;
362
361
  }
363
362
  /**
364
363
  * JWT middleware for WebUI
@@ -376,7 +375,7 @@ var Auth = class {
376
375
  return _next();
377
376
  };
378
377
  const { authorization } = req.headers;
379
- if (lodash.default.isNil(authorization)) return next();
378
+ if ((0, lodash_es.isNil)(authorization)) return next();
380
379
  if (!require_utils.isAuthHeaderValid(authorization)) return next(_verdaccio_core.errorUtils.getBadRequest(_verdaccio_core.API_ERROR.BAD_AUTH_HEADER));
381
380
  const token = (authorization || "").replace(`${_verdaccio_core.TOKEN_BEARER} `, "");
382
381
  if (!token) return next();
@@ -394,24 +393,19 @@ var Auth = class {
394
393
  async jwtEncrypt(user, signOptions) {
395
394
  const { real_groups, name, groups } = user;
396
395
  debug$1("jwt encrypt %o", name);
397
- const realGroupsValidated = lodash.default.isNil(real_groups) ? [] : real_groups;
396
+ const realGroupsValidated = (0, lodash_es.isNil)(real_groups) ? [] : real_groups;
398
397
  return await (0, _verdaccio_signature.signPayload)({
399
398
  real_groups: realGroupsValidated,
400
399
  name,
401
- groups: lodash.default.isNil(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
400
+ groups: (0, lodash_es.isNil)(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
402
401
  }, this.secret, signOptions);
403
402
  }
404
403
  /**
405
404
  * Encrypt a string.
406
405
  */
407
406
  aesEncrypt(value) {
408
- if (this.secret.length === _verdaccio_config.TOKEN_VALID_LENGTH) {
409
- debug$1("signing with enhanced aes legacy");
410
- return (0, _verdaccio_signature.aesEncrypt)(value, this.secret);
411
- } else {
412
- debug$1("signing with enhanced aes deprecated legacy");
413
- return (0, _verdaccio_signature.aesEncryptDeprecated)(Buffer.from(value), this.secret).toString("base64");
414
- }
407
+ debug$1("signing with aes encryption");
408
+ return (0, _verdaccio_signature.aesEncrypt)(value, this.secret);
415
409
  }
416
410
  };
417
411
  //#endregion
package/build/auth.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport _ from 'lodash';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { TOKEN_VALID_LENGTH, createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport {\n aesEncrypt,\n aesEncryptDeprecated,\n parseBasicPayload,\n signPayload,\n} from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = _.filter(this.plugins, (plugin) => _.isFunction(plugin.changePassword));\n\n if (_.isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (_.isNil(plugin) || _.isFunction(plugin.changePassword) === false) {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (_.isString(groups)) {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = _.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (_.isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return _.isUndefined(remote_user) === false && _.isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = _.isNil(real_groups) ? [] : real_groups;\n const groupedGroups = _.isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n const token: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n if (this.secret.length === TOKEN_VALID_LENGTH) {\n debug('signing with enhanced aes legacy');\n const token = aesEncrypt(value, this.secret);\n return token;\n } else {\n debug('signing with enhanced aes deprecated legacy');\n // deprecated aes (legacy) signature, only must be used for legacy version\n const token = aesEncryptDeprecated(Buffer.from(value), this.secret).toString('base64');\n return token;\n }\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;;;;AAsDA,IAAM,WAAA,GAAA,MAAA,SAAmB,iBAAiB;AAE1C,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAAoB,OAAO,EAAE;AAC1F,OAAK,SAAS;AACd,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS;AACd,OAAK,UAAU,EAAE;AACjB,OAAK,UAAU;AACf,MAAI,CAAC,KAAK,OACR,OAAM,IAAI,UAAU,2DAA2D;;CAInF,MAAa,OAAO;EAClB,IAAI,UAAU,MAAM,KAAK,YAAY;AAErC,UAAM,yBAAyB,QAAQ,OAAO;AAG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AM,WAAW;AACzB,QAAI,eAAA,GAAA,kBAAA,kBAA+B,MAAgB,OAAO;SAE1D,KAAI,eAAA,GAAA,kBAAA,4BAAyC;AAG/C,SAAM;;;CAIV,MAAa,WAAW,MAAkB,aAA8C;EACtF,MAAM,EAAE,aAAa,MAAM,WAAW;AACtC,UAAM,kBAAkB,KAAK;EAC7B,MAAM,sBAAsB,OAAA,QAAE,MAAM,YAAY,GAAG,EAAE,GAAG;AAexD,SANsB,OAAA,GAAA,qBAAA,aALM;GAC1B,aAAa;GACb;GACA,QANoB,OAAA,QAAE,MAAM,OAAO,GACjC,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,oBAAoB,CAAC,CAAC,CAAC;GAK/D,EAGC,KAAK,QACL,YACD;;;;;CAQH,WAAkB,OAA8B;AAC9C,MAAI,KAAK,OAAO,WAAW,kBAAA,oBAAoB;AAC7C,WAAM,mCAAmC;AAEzC,WAAA,GAAA,qBAAA,YADyB,OAAO,KAAK,OAAO;SAEvC;AACL,WAAM,8CAA8C;AAGpD,WAAA,GAAA,qBAAA,sBADmC,OAAO,KAAK,MAAM,EAAE,KAAK,OAAO,CAAC,SAAS,SAAS"}
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { filter, isEmpty, isNil, isUndefined } from 'lodash-es';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = filter(\n this.plugins,\n (plugin) => typeof plugin.changePassword === 'function'\n );\n\n if (isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || typeof plugin.changePassword !== 'function') {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (typeof groups === 'string') {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = Array.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = isNil(real_groups) ? [] : real_groups;\n const groupedGroups = isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n const token: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n debug('signing with aes encryption');\n const token = aesEncrypt(value, this.secret);\n return token;\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;;;AAiDA,IAAM,WAAA,GAAA,MAAA,SAAmB,iBAAiB;AAE1C,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAAoB,OAAO,EAAE;AAC1F,OAAK,SAAS;AACd,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS;AACd,OAAK,UAAU,EAAE;AACjB,OAAK,UAAU;AACf,MAAI,CAAC,KAAK,OACR,OAAM,IAAI,UAAU,2DAA2D;;CAInF,MAAa,OAAO;EAClB,IAAI,UAAU,MAAM,KAAK,YAAY;AAErC,UAAM,yBAAyB,QAAQ,OAAO;AAG9C,MAAI,KAAK,OAAO,SAAS,SAAS,CAAC,WAAW,QAAQ,WAAW,GAC/D,WAAU,KAAK,mBAAmB;AAEpC,OAAK,UAAU;AAEf,OAAK,4BAA4B;;CAGnC,oBAA4B;AAC1B,UAAM,2BAA2B;EACjC,IAAI;AACJ,MAAI;AACF,gBAAa,IAAI,mBAAA,SACf,EAAE,MAAM,cAAc,EACtB;IACE,QAAQ,KAAK;IACb,QAAQ,KAAK;IACd,CACF;AACD,QAAK,OAAO,KACV;IAAE,MAAM;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O,GAC/B,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,oBAAoB,CAAC,CAAC,CAAC;GAK/D,EAGC,KAAK,QACL,YACD;;;;;CAQH,WAAkB,OAA8B;AAC9C,UAAM,8BAA8B;AAEpC,UAAA,GAAA,qBAAA,YADyB,OAAO,KAAK,OAAO"}
package/build/auth.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  import { convertPayloadToBase64, getDefaultPluginMethods, getMiddlewareCredentials, isAESLegacy, isAuthHeaderValid, parseAuthTokenHeader, verifyJWTPayload } from "./utils.mjs";
2
2
  import buildDebug from "debug";
3
- import _ from "lodash";
3
+ import { filter, isEmpty, isNil, isUndefined } from "lodash-es";
4
4
  import { HTPasswd } from "verdaccio-htpasswd";
5
- import { TOKEN_VALID_LENGTH, createAnonymousRemoteUser, createRemoteUser } from "@verdaccio/config";
5
+ import { createAnonymousRemoteUser, createRemoteUser } from "@verdaccio/config";
6
6
  import { API_ERROR, PLUGIN_CATEGORY, PLUGIN_PREFIX, SUPPORT_ERRORS, TOKEN_BASIC, TOKEN_BEARER, authUtils, errorUtils, pluginUtils, warningUtils } from "@verdaccio/core";
7
7
  import { asyncLoadPlugin } from "@verdaccio/loaders";
8
- import { aesEncrypt, aesEncryptDeprecated, parseBasicPayload, signPayload } from "@verdaccio/signature";
8
+ import { aesEncrypt, parseBasicPayload, signPayload } from "@verdaccio/signature";
9
9
  //#region src/auth.ts
10
10
  var debug = buildDebug("verdaccio:auth");
11
11
  var Auth = class {
@@ -58,9 +58,9 @@ var Auth = class {
58
58
  this.plugins.push(getDefaultPluginMethods(this.logger));
59
59
  }
60
60
  changePassword(username, password, newPassword, cb) {
61
- const validPlugins = _.filter(this.plugins, (plugin) => _.isFunction(plugin.changePassword));
62
- if (_.isEmpty(validPlugins)) return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
63
- for (const plugin of validPlugins) if (_.isNil(plugin) || _.isFunction(plugin.changePassword) === false) {
61
+ const validPlugins = filter(this.plugins, (plugin) => typeof plugin.changePassword === "function");
62
+ if (isEmpty(validPlugins)) return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));
63
+ for (const plugin of validPlugins) if (isNil(plugin) || typeof plugin.changePassword !== "function") {
64
64
  debug("auth plugin does not implement changePassword, trying next one");
65
65
  continue;
66
66
  } else {
@@ -95,8 +95,8 @@ var Auth = class {
95
95
  return cb(err);
96
96
  }
97
97
  if (!!groups && groups.length !== 0) {
98
- if (_.isString(groups)) throw new TypeError("plugin group error: invalid type for function");
99
- if (!_.isArray(groups)) throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);
98
+ if (typeof groups === "string") throw new TypeError("plugin group error: invalid type for function");
99
+ if (!Array.isArray(groups)) throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);
100
100
  debug("authentication for user %o was successfully. Groups: %o", username, groups);
101
101
  return cb(err, createRemoteUser(username, groups));
102
102
  }
@@ -187,7 +187,7 @@ var Auth = class {
187
187
  debug("forbidden unpublish. Error: %o", err);
188
188
  return callback(err);
189
189
  }
190
- if (_.isNil(ok) === true) {
190
+ if (isNil(ok) === true) {
191
191
  debug("bypass unpublish for %o, publish will handle the access", packageName);
192
192
  this.logger.trace({
193
193
  user: user.name,
@@ -274,7 +274,7 @@ var Auth = class {
274
274
  req.remote_user = remoteUser;
275
275
  res.locals.remote_user = remoteUser;
276
276
  const { authorization } = req.headers;
277
- if (_.isNil(authorization)) {
277
+ if (isNil(authorization)) {
278
278
  debug("jwt, authentication header is missing");
279
279
  return next();
280
280
  }
@@ -355,7 +355,7 @@ var Auth = class {
355
355
  }
356
356
  }
357
357
  _isRemoteUserValid(remote_user) {
358
- return _.isUndefined(remote_user) === false && _.isUndefined(remote_user?.name) === false;
358
+ return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;
359
359
  }
360
360
  /**
361
361
  * JWT middleware for WebUI
@@ -373,7 +373,7 @@ var Auth = class {
373
373
  return _next();
374
374
  };
375
375
  const { authorization } = req.headers;
376
- if (_.isNil(authorization)) return next();
376
+ if (isNil(authorization)) return next();
377
377
  if (!isAuthHeaderValid(authorization)) return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));
378
378
  const token = (authorization || "").replace(`${TOKEN_BEARER} `, "");
379
379
  if (!token) return next();
@@ -391,24 +391,19 @@ var Auth = class {
391
391
  async jwtEncrypt(user, signOptions) {
392
392
  const { real_groups, name, groups } = user;
393
393
  debug("jwt encrypt %o", name);
394
- const realGroupsValidated = _.isNil(real_groups) ? [] : real_groups;
394
+ const realGroupsValidated = isNil(real_groups) ? [] : real_groups;
395
395
  return await signPayload({
396
396
  real_groups: realGroupsValidated,
397
397
  name,
398
- groups: _.isNil(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
398
+ groups: isNil(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
399
399
  }, this.secret, signOptions);
400
400
  }
401
401
  /**
402
402
  * Encrypt a string.
403
403
  */
404
404
  aesEncrypt(value) {
405
- if (this.secret.length === TOKEN_VALID_LENGTH) {
406
- debug("signing with enhanced aes legacy");
407
- return aesEncrypt(value, this.secret);
408
- } else {
409
- debug("signing with enhanced aes deprecated legacy");
410
- return aesEncryptDeprecated(Buffer.from(value), this.secret).toString("base64");
411
- }
405
+ debug("signing with aes encryption");
406
+ return aesEncrypt(value, this.secret);
412
407
  }
413
408
  };
414
409
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport _ from 'lodash';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { TOKEN_VALID_LENGTH, createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport {\n aesEncrypt,\n aesEncryptDeprecated,\n parseBasicPayload,\n signPayload,\n} from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = _.filter(this.plugins, (plugin) => _.isFunction(plugin.changePassword));\n\n if (_.isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (_.isNil(plugin) || _.isFunction(plugin.changePassword) === false) {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (_.isString(groups)) {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = _.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (_.isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return _.isUndefined(remote_user) === false && _.isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = _.isNil(real_groups) ? [] : real_groups;\n const groupedGroups = _.isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n const token: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n if (this.secret.length === TOKEN_VALID_LENGTH) {\n debug('signing with enhanced aes legacy');\n const token = aesEncrypt(value, this.secret);\n return token;\n } else {\n debug('signing with enhanced aes deprecated legacy');\n // deprecated aes (legacy) signature, only must be used for legacy version\n const token = aesEncryptDeprecated(Buffer.from(value), this.secret).toString('base64');\n return token;\n }\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;AAsDA,IAAM,QAAQ,WAAW,iBAAiB;AAE1C,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAAoB,OAAO,EAAE;AAC1F,OAAK,SAAS;AACd,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS;AACd,OAAK,UAAU,EAAE;AACjB,OAAK,UAAU;AACf,MAAI,CAAC,KAAK,OACR,OAAM,IAAI,UAAU,2DAA2D;;CAInF,MAAa,OAAO;EAClB,IAAI,UAA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,GAAG,OAAO,OAAO,oBAAoB,CAAC,CAAC,CAAC;GAK/D,EAGC,KAAK,QACL,YACD;;;;;CAQH,WAAkB,OAA8B;AAC9C,MAAI,KAAK,OAAO,WAAW,oBAAoB;AAC7C,SAAM,mCAAmC;AAEzC,UADc,WAAW,OAAO,KAAK,OAAO;SAEvC;AACL,SAAM,8CAA8C;AAGpD,UADc,qBAAqB,OAAO,KAAK,MAAM,EAAE,KAAK,OAAO,CAAC,SAAS,SAAS"}
1
+ {"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { filter, isEmpty, isNil, isUndefined } from 'lodash-es';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = filter(\n this.plugins,\n (plugin) => typeof plugin.changePassword === 'function'\n );\n\n if (isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || typeof plugin.changePassword !== 'function') {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (typeof groups === 'string') {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = Array.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = isNil(real_groups) ? [] : real_groups;\n const groupedGroups = isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n const token: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n debug('signing with aes encryption');\n const token = aesEncr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,iBAAiB,MAAgB,OAAO;SAE1D,KAAI,cAAc,2BAA2B;AAG/C,SAAM;;;CAIV,MAAa,WAAW,MAAkB,aAA8C;EACtF,MAAM,EAAE,aAAa,MAAM,WAAW;AACtC,QAAM,kBAAkB,KAAK;EAC7B,MAAM,sBAAsB,MAAM,YAAY,GAAG,EAAE,GAAG;AAetD,SANsB,MAAM,YALA;GAC1B,aAAa;GACb;GACA,QANoB,MAAM,OAAO,GAC/B,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,oBAAoB,CAAC,CAAC,CAAC;GAK/D,EAGC,KAAK,QACL,YACD;;;;;CAQH,WAAkB,OAA8B;AAC9C,QAAM,8BAA8B;AAEpC,SADc,WAAW,OAAO,KAAK,OAAO"}
package/build/utils.js CHANGED
@@ -1,8 +1,7 @@
1
1
  const require_runtime = require("./_virtual/_rolldown/runtime.js");
2
2
  let debug = require("debug");
3
3
  debug = require_runtime.__toESM(debug);
4
- let lodash = require("lodash");
5
- lodash = require_runtime.__toESM(lodash);
4
+ let lodash_es = require("lodash-es");
6
5
  let _verdaccio_config = require("@verdaccio/config");
7
6
  let _verdaccio_core = require("@verdaccio/core");
8
7
  let _verdaccio_signature = require("@verdaccio/signature");
@@ -27,16 +26,7 @@ function parseAESCredentials(authorizationHeader, secret) {
27
26
  return convertPayloadToBase64(token).toString();
28
27
  } else if (scheme.toUpperCase() === _verdaccio_core.TOKEN_BEARER.toUpperCase()) {
29
28
  debug$1("legacy header bearer");
30
- debug$1("secret length %o", secret.length);
31
- const isLegacyUnsecure = secret.length > 32;
32
- debug$1("is legacy unsecure %o", isLegacyUnsecure);
33
- if (isLegacyUnsecure) {
34
- debug$1("legacy unsecure enabled");
35
- return (0, _verdaccio_signature.aesDecryptDeprecated)(convertPayloadToBase64(token), secret).toString("utf-8");
36
- } else {
37
- debug$1("legacy secure enabled");
38
- return (0, _verdaccio_signature.aesDecrypt)(token.toString(), secret);
39
- }
29
+ return (0, _verdaccio_signature.aesDecrypt)(token.toString(), secret);
40
30
  }
41
31
  }
42
32
  function getMiddlewareCredentials(security, secretKey, authorizationHeader) {
@@ -57,11 +47,11 @@ function getMiddlewareCredentials(security, secretKey, authorizationHeader) {
57
47
  }
58
48
  const { scheme, token } = parseAuthTokenHeader(authorizationHeader);
59
49
  debug$1("is jwt");
60
- if (lodash.default.isString(token) && scheme.toUpperCase() === _verdaccio_core.TOKEN_BEARER.toUpperCase()) return verifyJWTPayload(token, secretKey, security);
50
+ if (typeof token === "string" && scheme.toUpperCase() === _verdaccio_core.TOKEN_BEARER.toUpperCase()) return verifyJWTPayload(token, secretKey, security);
61
51
  }
62
52
  function isAESLegacy(security) {
63
53
  const { legacy, jwt } = security.api;
64
- return lodash.default.isNil(legacy) === false && lodash.default.isNil(jwt) && legacy === true;
54
+ return (0, lodash_es.isNil)(legacy) === false && (0, lodash_es.isNil)(jwt) && legacy === true;
65
55
  }
66
56
  async function getApiToken(auth, config, remoteUser, aesPassword) {
67
57
  debug$1("get api token");
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport _ from 'lodash';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport {\n aesDecrypt,\n aesDecryptDeprecated,\n parseBasicPayload,\n verifyPayload,\n} from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n debug('secret length %o', secret.length);\n const isLegacyUnsecure = secret.length > 32;\n debug('is legacy unsecure %o', isLegacyUnsecure);\n if (isLegacyUnsecure) {\n debug('legacy unsecure enabled');\n return aesDecryptDeprecated(convertPayloadToBase64(token), secret).toString('utf-8');\n } else {\n debug('legacy secure enabled');\n return aesDecrypt(token.toString(), secret);\n }\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (_.isString(token) && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return _.isNil(legacy) === false && _.isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n\n if (isAESLegacy(security)) {\n debug('security legacy enabled');\n // fallback all goes to AES encryption\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(remoteUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string): string {\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings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EAAU;AAGlC,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;GAAW,EACtD,8EACD;AACD,SAAO,aAAa,QAAQ,OAAO,CAAC,MAAM,KAAK,SAAS;;;AAI5D,SAAgB,UAAU,MAAc,UAA0B;AAChE,QAAO,OAAO,GAAG,KAAK,GAAG,WAAW;;AAGtC,SAAgB,uBAAuB,SAAyB;AAC9D,QAAO,OAAO,KAAK,SAAS,SAAS"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { isNil } from 'lodash-es';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n return aesDecrypt(token.toString(), secret);\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (typeof token === 'string' && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return isNil(legacy) === false && isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n\n if (isAESLegacy(security)) {\n debug('security legacy enabled');\n // fallback all goes to AES encryption\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(remoteUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string): string {\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;;;AAkBA,IAAM,WAAA,GAAA,MAAA,SAAmB,uBAAuB;;;;;AAMhD,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,IAAI;AAG5C,QAAO;EAAE;EAAQ;EAAO;;AAG1B,SAAgB,oBAAoB,qBAA6B,QAAgB;AAC/E,SAAM,2BAA2B;CACjC,MAAM,EAAE,QAAQ,UAAU,qBAAqB,oBAAoB;AAInE,KAAI,OAAO,aAAa,KAAK,gBAAA,YAAY,aAAa,EAAE;AACtD,UAAM,sBAAsB;AAG5B,SAFoB,uBAAuB,MAAM,CAAC,UAAU;YAGnD,OAAO,aAAa,KAAK,gBAAA,aAAa,aAAa,EAAE;AAC9D,UAAM,uBAAuB;AAC7B,UAAA,GAAA,qBAAA,YAAkB,MAAM,UAAU,EAAE,OAAO;;;AAI/C,SAAgB,yBACd,U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;MAED,UACE,gBAAA,WAAW,gBAAgB,6BAA6B,OAAO,WAAW,IAAI,OAAO,CACtF;;;;;;AAQP,SAAgB,uBAAuB,QAAqB;AAC1D,QAAO,SAAU,MAAkB,KAAuB,UAAqC;EAC7F,MAAM,SAAS;EAEf,MAAM,qBAA8B,CAAC,IAAI;AACzC,UAAM,oCAAoC,mBAAmB;EAC7D,MAAM,YAAqB,qBAAqB,QAAS,IAAI,QAAqB,SAAS;AAC3F,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAW,EAC9C,sEACD;AAED,MAAI,sBAAsB,cAAc,MACtC,QAAO,SAAS,MAAM,KAAA,EAAU;AAGlC,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;GAAW,EACtD,8EACD;AACD,SAAO,aAAa,QAAQ,OAAO,CAAC,MAAM,KAAK,SAAS;;;AAI5D,SAAgB,UAAU,MAAc,UAA0B;AAChE,QAAO,OAAO,GAAG,KAAK,GAAG,WAAW;;AAGtC,SAAgB,uBAAuB,SAAyB;AAC9D,QAAO,OAAO,KAAK,SAAS,SAAS"}
package/build/utils.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import buildDebug from "debug";
2
- import _ from "lodash";
2
+ import { isNil } from "lodash-es";
3
3
  import { createAnonymousRemoteUser } from "@verdaccio/config";
4
4
  import { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from "@verdaccio/core";
5
- import { aesDecrypt, aesDecryptDeprecated, parseBasicPayload, verifyPayload } from "@verdaccio/signature";
5
+ import { aesDecrypt, parseBasicPayload, verifyPayload } from "@verdaccio/signature";
6
6
  //#region src/utils.ts
7
7
  var debug = buildDebug("verdaccio:auth:utils");
8
8
  /**
@@ -24,16 +24,7 @@ function parseAESCredentials(authorizationHeader, secret) {
24
24
  return convertPayloadToBase64(token).toString();
25
25
  } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {
26
26
  debug("legacy header bearer");
27
- debug("secret length %o", secret.length);
28
- const isLegacyUnsecure = secret.length > 32;
29
- debug("is legacy unsecure %o", isLegacyUnsecure);
30
- if (isLegacyUnsecure) {
31
- debug("legacy unsecure enabled");
32
- return aesDecryptDeprecated(convertPayloadToBase64(token), secret).toString("utf-8");
33
- } else {
34
- debug("legacy secure enabled");
35
- return aesDecrypt(token.toString(), secret);
36
- }
27
+ return aesDecrypt(token.toString(), secret);
37
28
  }
38
29
  }
39
30
  function getMiddlewareCredentials(security, secretKey, authorizationHeader) {
@@ -54,11 +45,11 @@ function getMiddlewareCredentials(security, secretKey, authorizationHeader) {
54
45
  }
55
46
  const { scheme, token } = parseAuthTokenHeader(authorizationHeader);
56
47
  debug("is jwt");
57
- if (_.isString(token) && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) return verifyJWTPayload(token, secretKey, security);
48
+ if (typeof token === "string" && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) return verifyJWTPayload(token, secretKey, security);
58
49
  }
59
50
  function isAESLegacy(security) {
60
51
  const { legacy, jwt } = security.api;
61
- return _.isNil(legacy) === false && _.isNil(jwt) && legacy === true;
52
+ return isNil(legacy) === false && isNil(jwt) && legacy === true;
62
53
  }
63
54
  async function getApiToken(auth, config, remoteUser, aesPassword) {
64
55
  debug("get api token");
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport _ from 'lodash';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport {\n aesDecrypt,\n aesDecryptDeprecated,\n parseBasicPayload,\n verifyPayload,\n} from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n debug('secret length %o', secret.length);\n const isLegacyUnsecure = secret.length > 32;\n debug('is legacy unsecure %o', isLegacyUnsecure);\n if (isLegacyUnsecure) {\n debug('legacy unsecure enabled');\n return aesDecryptDeprecated(convertPayloadToBase64(token), secret).toString('utf-8');\n } else {\n debug('legacy secure enabled');\n return aesDecrypt(token.toString(), secret);\n }\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (_.isString(token) && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return _.isNil(legacy) === false && _.isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n\n if (isAESLegacy(security)) {\n debug('security legacy enabled');\n // fallback all goes to AES encryption\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(remoteUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string): string {\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;AAuBA,IAAM,QAAQ,WAAW,uBAAuB;;;;;AAMhD,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,IAAI;AAG5C,QAAO;EAAE;EAAQ;EAAO;;AAG1B,SAAgB,oBAAoB,qBAA6B,QAAgB;AAC/E,OAAM,2BAA2B;CACjC,MAAM,EAAE,QAAQ,UAAU,qBAAqB,oBAAoB;AAInE,KAAI,OAAO,aAAa,KAAK,YAAY,aAAa,EAAE;AACtD,QAAM,sBAAsB;AAG5B,SAFoB,uBAAuB,MAAM,CAAC,UAAU;YAGnD,OAAO,aAAa,KAAK,aAAa,aAAa,EAAE;AAC9D,QAAM,uBAAuB;AAC7B,QAAM,oBAAoB,OAAO,OAAO;EACxC,MAAM,mBAAmB,OAAO,SAAS;AACzC,QAAM,yBAAyB,iBAAiB;AAChD,MAAI,kBAAkB;AACpB,SAAM,0BAA0B;AAChC,UAAO,qBAAqB,uBAAuB,MAAM,EAAE,OAAO,CAAC,SAAS,QAAQ;SAC/E;AACL,SAAM,wBAAwB;AAC9B,UAAO,WAAW,MAAM,UAAU,EAAE,OAAO;;;;AAKjD,SAAgB,yBACd,UACA,WACA,qBACuB;AACvB,OAAM,gCAAgC;AAEtC,KAAI,YAAY,SAAS,EAAE;AACzB,QAAM,YAAY;EAClB,MAAM,cAAc,oBAAoB,qBAAqB,UAAU;AACvE,MAAI,CAAC,aAAa;AAChB,SAAM,kCAAkC;AACxC;;EAGF,MAAM,oBAAoB,kBAAkB,YAAY;AACxD,MAAI,CAAC,mBAAmB;AACtB,SAAM,gDAAgD;AACtD;;AAGF,SAAO;;CAET,MAA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,cAAc,MACtC,QAAO,SAAS,MAAM,KAAA,EAAU;AAGlC,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;GAAW,EACtD,8EACD;AACD,SAAO,aAAa,QAAQ,OAAO,CAAC,MAAM,KAAK,SAAS;;;AAI5D,SAAgB,UAAU,MAAc,UAA0B;AAChE,QAAO,OAAO,GAAG,KAAK,GAAG,WAAW;;AAGtC,SAAgB,uBAAuB,SAAyB;AAC9D,QAAO,OAAO,KAAK,SAAS,SAAS"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { isNil } from 'lodash-es';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n return aesDecrypt(token.toString(), secret);\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (typeof token === 'string' && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return isNil(legacy) === false && isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n\n if (isAESLegacy(security)) {\n debug('security legacy enabled');\n // fallback all goes to AES encryption\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(remoteUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string): string {\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;AAkBA,IAAM,QAAQ,WAAW,uBAAuB;;;;;AAMhD,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,IAAI;AAG5C,QAAO;EAAE;EAAQ;EAAO;;AAG1B,SAAgB,oBAAoB,qBAA6B,QAAgB;AAC/E,OAAM,2BAA2B;CACjC,MAAM,EAAE,QAAQ,UAAU,qBAAqB,oBAAoB;AAInE,KAAI,OAAO,aAAa,KAAK,YAAY,aAAa,EAAE;AACtD,QAAM,sBAAsB;AAG5B,SAFoB,uBAAuB,MAAM,CAAC,UAAU;YAGnD,OAAO,aAAa,KAAK,aAAa,aAAa,EAAE;AAC9D,QAAM,uBAAuB;AAC7B,SAAO,WAAW,MAAM,UAAU,EAAE,OAAO;;;AAI/C,SAAgB,yBACd,UACA,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QAAO,SAAU,MAAkB,KAAuB,UAAqC;EAC7F,MAAM,SAAS;EAEf,MAAM,qBAA8B,CAAC,IAAI;AACzC,QAAM,oCAAoC,mBAAmB;EAC7D,MAAM,YAAqB,qBAAqB,QAAS,IAAI,QAAqB,SAAS;AAC3F,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAW,EAC9C,sEACD;AAED,MAAI,sBAAsB,cAAc,MACtC,QAAO,SAAS,MAAM,KAAA,EAAU;AAGlC,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;GAAW,EACtD,8EACD;AACD,SAAO,aAAa,QAAQ,OAAO,CAAC,MAAM,KAAK,SAAS;;;AAI5D,SAAgB,UAAU,MAAc,UAA0B;AAChE,QAAO,OAAO,GAAG,KAAK,GAAG,WAAW;;AAGtC,SAAgB,uBAAuB,SAAyB;AAC9D,QAAO,OAAO,KAAK,SAAS,SAAS"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verdaccio/auth",
3
- "version": "9.0.0-next-9.6",
3
+ "version": "9.0.0-next-9.8",
4
4
  "description": "Verdaccio Authentication",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -33,18 +33,20 @@
33
33
  },
34
34
  "license": "MIT",
35
35
  "dependencies": {
36
- "@verdaccio/config": "9.0.0-next-9.6",
37
- "@verdaccio/core": "9.0.0-next-9.6",
38
- "@verdaccio/loaders": "9.0.0-next-9.6",
39
- "@verdaccio/signature": "9.0.0-next-9.6",
36
+ "@verdaccio/config": "9.0.0-next-9.8",
37
+ "@verdaccio/core": "9.0.0-next-9.8",
38
+ "@verdaccio/loaders": "9.0.0-next-9.8",
39
+ "@verdaccio/signature": "9.0.0-next-9.8",
40
40
  "debug": "4.4.3",
41
- "lodash": "4.17.23",
42
- "verdaccio-htpasswd": "14.0.0-next-9.6"
41
+ "lodash-es": "4.17.23",
42
+ "verdaccio-htpasswd": "14.0.0-next-9.8"
43
43
  },
44
44
  "devDependencies": {
45
- "@verdaccio/middleware": "9.0.0-next-9.6",
46
- "@verdaccio/types": "14.0.0-next-9.3",
47
- "@verdaccio/logger": "9.0.0-next-9.6",
45
+ "@verdaccio/middleware": "9.0.0-next-9.8",
46
+ "@verdaccio/types": "14.0.0-next-9.4",
47
+ "@verdaccio/logger": "9.0.0-next-9.8",
48
+ "verdaccio-htpasswd": "14.0.0-next-9.8",
49
+ "@types/lodash-es": "4.17.12",
48
50
  "express": "5.2.1",
49
51
  "supertest": "7.1.4",
50
52
  "vitest": "4.1.0"