@verdaccio/auth 6.0.0-6-next.41 → 6.0.0-6-next.42
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/CHANGELOG.md +18 -0
- package/build/auth.js +4 -6
- package/build/auth.js.map +1 -1
- package/build/index.d.ts +1 -4
- package/build/index.js +1 -44
- package/build/index.js.map +1 -1
- package/build/utils.js +4 -6
- package/build/utils.js.map +1 -1
- package/jest.config.js +1 -1
- package/package.json +9 -9
- package/src/auth.ts +2 -3
- package/src/index.ts +1 -4
- package/src/utils.ts +1 -3
- package/test/auth-utils.spec.ts +4 -5
- package/tsconfig.json +3 -0
- package/build/jwt-token.d.ts +0 -10
- package/build/jwt-token.js +0 -40
- package/build/jwt-token.js.map +0 -1
- package/build/legacy-token.d.ts +0 -3
- package/build/legacy-token.js +0 -66
- package/build/legacy-token.js.map +0 -1
- package/build/token.d.ts +0 -2
- package/build/token.js +0 -19
- package/build/token.js.map +0 -1
- package/src/jwt-token.ts +0 -42
- package/src/legacy-token.ts +0 -67
- package/src/token.ts +0 -13
- package/test/legacy-token.spec.ts +0 -19
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @verdaccio/auth
|
|
2
2
|
|
|
3
|
+
## 6.0.0-6-next.42
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- ddb6a223: feat: signature package
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [ddb6a223]
|
|
12
|
+
- Updated dependencies [dc571aab]
|
|
13
|
+
- @verdaccio/config@6.0.0-6-next.63
|
|
14
|
+
- @verdaccio/signature@6.0.0-6-next.2
|
|
15
|
+
- @verdaccio/core@6.0.0-6-next.63
|
|
16
|
+
- @verdaccio/loaders@6.0.0-6-next.32
|
|
17
|
+
- verdaccio-htpasswd@11.0.0-6-next.33
|
|
18
|
+
- @verdaccio/utils@6.0.0-6-next.31
|
|
19
|
+
- @verdaccio/logger@6.0.0-6-next.31
|
|
20
|
+
|
|
3
21
|
## 6.0.0-6-next.41
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/build/auth.js
CHANGED
|
@@ -11,10 +11,8 @@ var _config = require("@verdaccio/config");
|
|
|
11
11
|
var _core = require("@verdaccio/core");
|
|
12
12
|
var _loaders = require("@verdaccio/loaders");
|
|
13
13
|
var _logger = require("@verdaccio/logger");
|
|
14
|
+
var _signature = require("@verdaccio/signature");
|
|
14
15
|
var _utils = require("@verdaccio/utils");
|
|
15
|
-
var _jwtToken = require("./jwt-token");
|
|
16
|
-
var _legacyToken = require("./legacy-token");
|
|
17
|
-
var _token = require("./token");
|
|
18
16
|
var _utils2 = require("./utils");
|
|
19
17
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
20
18
|
const debug = (0, _debug.default)('verdaccio:auth');
|
|
@@ -343,7 +341,7 @@ class Auth {
|
|
|
343
341
|
const {
|
|
344
342
|
user,
|
|
345
343
|
password
|
|
346
|
-
} = (0,
|
|
344
|
+
} = (0, _signature.parseBasicPayload)(credentials);
|
|
347
345
|
debug('authenticating %o', user);
|
|
348
346
|
this.authenticate(user, password, (err, user) => {
|
|
349
347
|
if (!err) {
|
|
@@ -467,7 +465,7 @@ class Auth {
|
|
|
467
465
|
name,
|
|
468
466
|
groups: groupedGroups
|
|
469
467
|
};
|
|
470
|
-
const token = await (0,
|
|
468
|
+
const token = await (0, _signature.signPayload)(payload, this.secret, signOptions);
|
|
471
469
|
return token;
|
|
472
470
|
}
|
|
473
471
|
|
|
@@ -475,7 +473,7 @@ class Auth {
|
|
|
475
473
|
* Encrypt a string.
|
|
476
474
|
*/
|
|
477
475
|
aesEncrypt(value) {
|
|
478
|
-
return (0,
|
|
476
|
+
return (0, _signature.aesEncrypt)(value, this.secret);
|
|
479
477
|
}
|
|
480
478
|
}
|
|
481
479
|
exports.Auth = Auth;
|
package/build/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","names":["debug","buildDebug","Auth","constructor","config","secret","plugins","TypeError","init","loadPlugin","length","loadDefaultPlugin","_applyDefaultPlugins","pluginOptions","logger","authPlugin","HTPasswd","file","error","info","asyncLoadPlugin","auth","plugin","authenticate","allow_access","allow_publish","serverSettings","pluginPrefix","push","getDefaultPlugins","changePassword","username","password","newPassword","cb","validPlugins","_","filter","isFunction","isEmpty","errorUtils","getInternalError","SUPPORT_ERRORS","PLUGIN_MISSING_INTERFACE","isNil","err","profile","invalidateToken","token","console","log","Promise","resolve","slice","next","shift","groups","message","isString","isGroupValid","isArray","API_ERROR","BAD_FORMAT_USER_GROUP","createRemoteUser","add_user","user","self","adduser","ok","packageName","packageVersion","callback","pkgAllowAccess","name","version","pkg","Object","assign","getMatchedPackagesSpec","packages","allow_unpublish","arguments","isError","apiJWTmiddleware","helpers","createAnonymousRemoteUser","req","res","_next","pause","resume","remote_user","_isRemoteUserValid","remoteUser","locals","authorization","headers","isAuthHeaderValid","getBadRequest","BAD_AUTH_HEADER","security","isAESLegacy","_handleAESMiddleware","_handleJWTAPIMiddleware","scheme","parseAuthTokenHeader","toUpperCase","TOKEN_BASIC","credentials","convertPayloadToBase64","toString","parseBasicPayload","getMiddlewareCredentials","getForbidden","BAD_USERNAME_PASSWORD","isUndefined","webUIJWTmiddleware","status","statusCode","send","replace","TOKEN_BEARER","verifyJWTPayload","jwtEncrypt","signOptions","real_groups","realGroupsValidated","groupedGroups","Array","from","Set","concat","payload","signPayload","aesEncrypt","value"],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { NextFunction, Request, RequestHandler, Response } from 'express';\nimport _ from 'lodash';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport {\n API_ERROR,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n VerdaccioError,\n errorUtils,\n pluginUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { logger } from '@verdaccio/logger';\nimport {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\nimport { getMatchedPackagesSpec, isFunction, isNil } from '@verdaccio/utils';\n\nimport { signPayload } from './jwt-token';\nimport { aesEncrypt } from './legacy-token';\nimport { parseBasicPayload } from './token';\nimport {\n convertPayloadToBase64,\n getDefaultPlugins,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nexport interface TokenEncryption {\n jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string>;\n aesEncrypt(buf: string): string | void;\n}\n\nexport interface AESPayload {\n user: string;\n password: string;\n}\nexport interface IAuthMiddleware {\n apiJWTmiddleware(): $NextFunctionVer;\n webUIJWTmiddleware(): $NextFunctionVer;\n}\n\nexport type $RequestExtend = Request & { remote_user?: any; log: Logger };\nexport type $ResponseExtend = Response & { cookies?: any };\nexport type $NextFunctionVer = NextFunction & any;\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public plugins: pluginUtils.Auth<Config>[];\n\n public constructor(config: Config) {\n this.config = config;\n this.secret = config.secret;\n this.plugins = [];\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()) as pluginUtils.Auth<unknown>[];\n debug('auth plugins found %s', plugins.length);\n if (!plugins || plugins.length === 0) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this._applyDefaultPlugins();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n const pluginOptions: pluginUtils.PluginOptions = {\n config: this.config,\n logger,\n };\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n pluginOptions as any as pluginUtils.PluginOptions\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n 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<unknown>>(\n this.config.auth,\n {\n config: this.config,\n logger,\n },\n (plugin): boolean => {\n const { authenticate, allow_access, allow_publish } = plugin;\n\n return (\n typeof authenticate !== 'undefined' ||\n typeof allow_access !== 'undefined' ||\n typeof allow_publish !== 'undefined'\n );\n },\n this.config?.serverSettings?.pluginPrefix\n );\n }\n\n private _applyDefaultPlugins(): void {\n // TODO: rename to applyFallbackPluginMethods\n this.plugins.push(getDefaultPlugins(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 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() as pluginUtils.Auth<Config>;\n\n if (isFunction(plugin.authenticate) === false) {\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 const plugin = plugins.shift() as pluginUtils.Auth<Config>;\n if (typeof plugin.adduser !== 'function') {\n next();\n } else {\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n throw errorUtils.getInternalError(\n 'add_user method not longer supported, rename to adduser'\n );\n }\n\n plugin.adduser(\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not being 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 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 pkgAllowAccess: AllowAccess = { name: packageName, version: packageVersion };\n const pkg = Object.assign(\n {},\n pkgAllowAccess,\n getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n debug('allow access for %o', packageName);\n\n (function next(): void {\n const plugin: pluginUtils.Auth<unknown> = plugins.shift() as pluginUtils.Auth<unknown>;\n\n if (_.isNil(plugin) || isFunction(plugin.allow_access) === false) {\n return next();\n }\n\n plugin.allow_access!(user, pkg, function (err: VerdaccioError | null, ok?: boolean): void {\n if (err) {\n debug('forbidden access for %o. Error: %o', packageName, err?.message);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed access for %o', packageName);\n return callback(null, ok);\n }\n\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n getMatchedPackagesSpec(packageName, this.config.packages)\n );\n debug('allow unpublish for %o', packageName);\n\n for (const plugin of this.plugins) {\n if (_.isNil(plugin) || isFunction(plugin.allow_unpublish) === false) {\n debug('allow unpublish for %o plugin does not implement allow_unpublish', packageName);\n continue;\n } else {\n // @ts-ignore\n plugin.allow_unpublish!(user, pkg, (err, ok: boolean): void => {\n if (err) {\n debug(\n 'forbidden publish for %o, it will fallback on unpublish permissions',\n packageName\n );\n return callback(err);\n }\n\n if (_.isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n // @ts-ignore\n // eslint-disable-next-line\n return this.allow_publish(...arguments);\n }\n\n if (ok) {\n debug('allowed unpublish for %o', packageName);\n return callback(null, ok);\n }\n });\n }\n }\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 getMatchedPackagesSpec(packageName, this.config.packages)\n ) as any;\n debug('allow publish for %o init | plugins: %o', packageName, plugins.length);\n\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('allow publish for %o plugin does not implement allow_publish', packageName);\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (_.isNil(err) === false && _.isError(err)) {\n debug('forbidden publish for %o', packageName);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed publish for %o', packageName);\n return callback(null, ok);\n }\n\n debug('allow publish skip validation for %o', packageName);\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public apiJWTmiddleware(): RequestHandler {\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 // @ts-ignore\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n\n const next = function (err?: VerdaccioError): any {\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();\n };\n\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: Function\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 { user, password } = parseBasicPayload(credentials) 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 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(): RequestHandler {\n // @ts-ignore\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);\n } catch (err: any) {\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\n const token: string = await signPayload(payload, this.secret, signOptions);\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n return aesEncrypt(value, this.secret);\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;AAAA;AAEA;AACA;AAEA;AACA;AASA;AACA;AAWA;AAEA;AACA;AACA;AACA;AAQiB;AAEjB,MAAMA,KAAK,GAAG,IAAAC,cAAU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M;QACL8B,GAAG,CAACK,WAAW,GAAG,IAAAN,iCAAyB,GAAE;MAC/C;MAEA/B,IAAI,EAAE;IACR,CAAC;EACH;EAEA,MAAaqE,UAAU,CAAC1D,IAAgB,EAAE2D,WAA2B,EAAmB;IACtF,MAAM;MAAEC,WAAW;MAAEpD,IAAI;MAAEjB;IAAO,CAAC,GAAGS,IAAI;IAC1CjE,KAAK,CAAC,gBAAgB,EAAEyE,IAAI,CAAC;IAC7B,MAAMqD,mBAAmB,GAAG1F,eAAC,CAACQ,KAAK,CAACiF,WAAW,CAAC,GAAG,EAAE,GAAGA,WAAW;IACnE,MAAME,aAAa,GAAG3F,eAAC,CAACQ,KAAK,CAACY,MAAM,CAAC,GACjCqE,WAAW,GACXG,KAAK,CAACC,IAAI,CAAC,IAAIC,GAAG,CAAC,CAAC,GAAG1E,MAAM,CAAC2E,MAAM,CAACL,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAChE,MAAMM,OAAmB,GAAG;MAC1BP,WAAW,EAAEC,mBAAmB;MAChCrD,IAAI;MACJjB,MAAM,EAAEuE;IACV,CAAC;IAED,MAAM/E,KAAa,GAAG,MAAM,IAAAqF,qBAAW,EAACD,OAAO,EAAE,IAAI,CAAC/H,MAAM,EAAEuH,WAAW,CAAC;IAE1E,OAAO5E,KAAK;EACd;;EAEA;AACF;AACA;EACSsF,UAAU,CAACC,KAAa,EAAiB;IAC9C,OAAO,IAAAD,uBAAU,EAACC,KAAK,EAAE,IAAI,CAAClI,MAAM,CAAC;EACvC;AACF;AAAC"}
|
|
1
|
+
{"version":3,"file":"auth.js","names":["debug","buildDebug","Auth","constructor","config","secret","plugins","TypeError","init","loadPlugin","length","loadDefaultPlugin","_applyDefaultPlugins","pluginOptions","logger","authPlugin","HTPasswd","file","error","info","asyncLoadPlugin","auth","plugin","authenticate","allow_access","allow_publish","serverSettings","pluginPrefix","push","getDefaultPlugins","changePassword","username","password","newPassword","cb","validPlugins","_","filter","isFunction","isEmpty","errorUtils","getInternalError","SUPPORT_ERRORS","PLUGIN_MISSING_INTERFACE","isNil","err","profile","invalidateToken","token","console","log","Promise","resolve","slice","next","shift","groups","message","isString","isGroupValid","isArray","API_ERROR","BAD_FORMAT_USER_GROUP","createRemoteUser","add_user","user","self","adduser","ok","packageName","packageVersion","callback","pkgAllowAccess","name","version","pkg","Object","assign","getMatchedPackagesSpec","packages","allow_unpublish","arguments","isError","apiJWTmiddleware","helpers","createAnonymousRemoteUser","req","res","_next","pause","resume","remote_user","_isRemoteUserValid","remoteUser","locals","authorization","headers","isAuthHeaderValid","getBadRequest","BAD_AUTH_HEADER","security","isAESLegacy","_handleAESMiddleware","_handleJWTAPIMiddleware","scheme","parseAuthTokenHeader","toUpperCase","TOKEN_BASIC","credentials","convertPayloadToBase64","toString","parseBasicPayload","getMiddlewareCredentials","getForbidden","BAD_USERNAME_PASSWORD","isUndefined","webUIJWTmiddleware","status","statusCode","send","replace","TOKEN_BEARER","verifyJWTPayload","jwtEncrypt","signOptions","real_groups","realGroupsValidated","groupedGroups","Array","from","Set","concat","payload","signPayload","aesEncrypt","value"],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { NextFunction, Request, RequestHandler, Response } from 'express';\nimport _ from 'lodash';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport {\n API_ERROR,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n VerdaccioError,\n errorUtils,\n pluginUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { logger } from '@verdaccio/logger';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\nimport { getMatchedPackagesSpec, isFunction, isNil } from '@verdaccio/utils';\n\nimport {\n convertPayloadToBase64,\n getDefaultPlugins,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nexport interface TokenEncryption {\n jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string>;\n aesEncrypt(buf: string): string | void;\n}\n\n// remove\nexport interface AESPayload {\n user: string;\n password: string;\n}\nexport interface IAuthMiddleware {\n apiJWTmiddleware(): $NextFunctionVer;\n webUIJWTmiddleware(): $NextFunctionVer;\n}\n\nexport type $RequestExtend = Request & { remote_user?: any; log: Logger };\nexport type $ResponseExtend = Response & { cookies?: any };\nexport type $NextFunctionVer = NextFunction & any;\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public plugins: pluginUtils.Auth<Config>[];\n\n public constructor(config: Config) {\n this.config = config;\n this.secret = config.secret;\n this.plugins = [];\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()) as pluginUtils.Auth<unknown>[];\n debug('auth plugins found %s', plugins.length);\n if (!plugins || plugins.length === 0) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this._applyDefaultPlugins();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n const pluginOptions: pluginUtils.PluginOptions = {\n config: this.config,\n logger,\n };\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n pluginOptions as any as pluginUtils.PluginOptions\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n 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<unknown>>(\n this.config.auth,\n {\n config: this.config,\n logger,\n },\n (plugin): boolean => {\n const { authenticate, allow_access, allow_publish } = plugin;\n\n return (\n typeof authenticate !== 'undefined' ||\n typeof allow_access !== 'undefined' ||\n typeof allow_publish !== 'undefined'\n );\n },\n this.config?.serverSettings?.pluginPrefix\n );\n }\n\n private _applyDefaultPlugins(): void {\n // TODO: rename to applyFallbackPluginMethods\n this.plugins.push(getDefaultPlugins(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 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() as pluginUtils.Auth<Config>;\n\n if (isFunction(plugin.authenticate) === false) {\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 const plugin = plugins.shift() as pluginUtils.Auth<Config>;\n if (typeof plugin.adduser !== 'function') {\n next();\n } else {\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n throw errorUtils.getInternalError(\n 'add_user method not longer supported, rename to adduser'\n );\n }\n\n plugin.adduser(\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not being 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 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 pkgAllowAccess: AllowAccess = { name: packageName, version: packageVersion };\n const pkg = Object.assign(\n {},\n pkgAllowAccess,\n getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n debug('allow access for %o', packageName);\n\n (function next(): void {\n const plugin: pluginUtils.Auth<unknown> = plugins.shift() as pluginUtils.Auth<unknown>;\n\n if (_.isNil(plugin) || isFunction(plugin.allow_access) === false) {\n return next();\n }\n\n plugin.allow_access!(user, pkg, function (err: VerdaccioError | null, ok?: boolean): void {\n if (err) {\n debug('forbidden access for %o. Error: %o', packageName, err?.message);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed access for %o', packageName);\n return callback(null, ok);\n }\n\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n getMatchedPackagesSpec(packageName, this.config.packages)\n );\n debug('allow unpublish for %o', packageName);\n\n for (const plugin of this.plugins) {\n if (_.isNil(plugin) || isFunction(plugin.allow_unpublish) === false) {\n debug('allow unpublish for %o plugin does not implement allow_unpublish', packageName);\n continue;\n } else {\n // @ts-ignore\n plugin.allow_unpublish!(user, pkg, (err, ok: boolean): void => {\n if (err) {\n debug(\n 'forbidden publish for %o, it will fallback on unpublish permissions',\n packageName\n );\n return callback(err);\n }\n\n if (_.isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n // @ts-ignore\n // eslint-disable-next-line\n return this.allow_publish(...arguments);\n }\n\n if (ok) {\n debug('allowed unpublish for %o', packageName);\n return callback(null, ok);\n }\n });\n }\n }\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 getMatchedPackagesSpec(packageName, this.config.packages)\n ) as any;\n debug('allow publish for %o init | plugins: %o', packageName, plugins.length);\n\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('allow publish for %o plugin does not implement allow_publish', packageName);\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (_.isNil(err) === false && _.isError(err)) {\n debug('forbidden publish for %o', packageName);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed publish for %o', packageName);\n return callback(null, ok);\n }\n\n debug('allow publish skip validation for %o', packageName);\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public apiJWTmiddleware(): RequestHandler {\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 // @ts-ignore\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n\n const next = function (err?: VerdaccioError): any {\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();\n };\n\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: Function\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 { user, password } = parseBasicPayload(credentials) 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 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(): RequestHandler {\n // @ts-ignore\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);\n } catch (err: any) {\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\n const token: string = await signPayload(payload, this.secret, signOptions);\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n return aesEncrypt(value, this.secret);\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;AAAA;AAEA;AACA;AAEA;AACA;AASA;AACA;AACA;AAWA;AAEA;AAQiB;AAEjB,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,gBAAgB,CAAC;AAqB1C,MAAMC,IAAI,CAAqE;EAKtEC,WAAW,CAACC,MAAc,EAAE;IACjC,IAAI,CAACA,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACC,MAAM,GAAGD,MAAM,CAACC,MAAM;IAC3B,IAAI,CAACC,OAAO,GAAG,EAAE;IACjB,IAAI,CAAC,IAAI,CAACD,MAAM,EAAE;MAChB,MAAM,IAAIE,SAAS,CAAC,0DAA0D,CAAC;IACjF;EACF;EAEA,MAAaC,IAAI,GAAG;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K,CAACiF,WAAW,CAAC,GAAG,EAAE,GAAGA,WAAW;IACnE,MAAME,aAAa,GAAG3F,eAAC,CAACQ,KAAK,CAACY,MAAM,CAAC,GACjCqE,WAAW,GACXG,KAAK,CAACC,IAAI,CAAC,IAAIC,GAAG,CAAC,CAAC,GAAG1E,MAAM,CAAC2E,MAAM,CAACL,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAChE,MAAMM,OAAmB,GAAG;MAC1BP,WAAW,EAAEC,mBAAmB;MAChCrD,IAAI;MACJjB,MAAM,EAAEuE;IACV,CAAC;IAED,MAAM/E,KAAa,GAAG,MAAM,IAAAqF,sBAAW,EAACD,OAAO,EAAE,IAAI,CAAC/H,MAAM,EAAEuH,WAAW,CAAC;IAE1E,OAAO5E,KAAK;EACd;;EAEA;AACF;AACA;EACSsF,UAAU,CAACC,KAAa,EAAiB;IAC9C,OAAO,IAAAD,qBAAU,EAACC,KAAK,EAAE,IAAI,CAAClI,MAAM,CAAC;EACvC;AACF;AAAC"}
|
package/build/index.d.ts
CHANGED
package/build/index.js
CHANGED
|
@@ -4,8 +4,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
var _exportNames = {
|
|
7
|
-
Auth: true
|
|
8
|
-
TokenEncryption: true
|
|
7
|
+
Auth: true
|
|
9
8
|
};
|
|
10
9
|
Object.defineProperty(exports, "Auth", {
|
|
11
10
|
enumerable: true,
|
|
@@ -13,12 +12,6 @@ Object.defineProperty(exports, "Auth", {
|
|
|
13
12
|
return _auth.Auth;
|
|
14
13
|
}
|
|
15
14
|
});
|
|
16
|
-
Object.defineProperty(exports, "TokenEncryption", {
|
|
17
|
-
enumerable: true,
|
|
18
|
-
get: function () {
|
|
19
|
-
return _auth.TokenEncryption;
|
|
20
|
-
}
|
|
21
|
-
});
|
|
22
15
|
var _auth = require("./auth");
|
|
23
16
|
var _utils = require("./utils");
|
|
24
17
|
Object.keys(_utils).forEach(function (key) {
|
|
@@ -32,40 +25,4 @@ Object.keys(_utils).forEach(function (key) {
|
|
|
32
25
|
}
|
|
33
26
|
});
|
|
34
27
|
});
|
|
35
|
-
var _legacyToken = require("./legacy-token");
|
|
36
|
-
Object.keys(_legacyToken).forEach(function (key) {
|
|
37
|
-
if (key === "default" || key === "__esModule") return;
|
|
38
|
-
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
39
|
-
if (key in exports && exports[key] === _legacyToken[key]) return;
|
|
40
|
-
Object.defineProperty(exports, key, {
|
|
41
|
-
enumerable: true,
|
|
42
|
-
get: function () {
|
|
43
|
-
return _legacyToken[key];
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
});
|
|
47
|
-
var _jwtToken = require("./jwt-token");
|
|
48
|
-
Object.keys(_jwtToken).forEach(function (key) {
|
|
49
|
-
if (key === "default" || key === "__esModule") return;
|
|
50
|
-
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
51
|
-
if (key in exports && exports[key] === _jwtToken[key]) return;
|
|
52
|
-
Object.defineProperty(exports, key, {
|
|
53
|
-
enumerable: true,
|
|
54
|
-
get: function () {
|
|
55
|
-
return _jwtToken[key];
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
var _token = require("./token");
|
|
60
|
-
Object.keys(_token).forEach(function (key) {
|
|
61
|
-
if (key === "default" || key === "__esModule") return;
|
|
62
|
-
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
63
|
-
if (key in exports && exports[key] === _token[key]) return;
|
|
64
|
-
Object.defineProperty(exports, key, {
|
|
65
|
-
enumerable: true,
|
|
66
|
-
get: function () {
|
|
67
|
-
return _token[key];
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
});
|
|
71
28
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export { Auth
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export { Auth } from './auth';\nexport * from './utils';\n"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"}
|
package/build/utils.js
CHANGED
|
@@ -20,9 +20,7 @@ var _debug = _interopRequireDefault(require("debug"));
|
|
|
20
20
|
var _lodash = _interopRequireDefault(require("lodash"));
|
|
21
21
|
var _config = require("@verdaccio/config");
|
|
22
22
|
var _core = require("@verdaccio/core");
|
|
23
|
-
var
|
|
24
|
-
var _legacyToken = require("./legacy-token");
|
|
25
|
-
var _token = require("./token");
|
|
23
|
+
var _signature = require("@verdaccio/signature");
|
|
26
24
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
27
25
|
const debug = (0, _debug.default)('verdaccio:auth:utils');
|
|
28
26
|
/**
|
|
@@ -52,7 +50,7 @@ function parseAESCredentials(authorizationHeader, secret) {
|
|
|
52
50
|
return credentials;
|
|
53
51
|
} else if (scheme.toUpperCase() === _core.TOKEN_BEARER.toUpperCase()) {
|
|
54
52
|
debug('legacy header bearer');
|
|
55
|
-
const credentials = (0,
|
|
53
|
+
const credentials = (0, _signature.aesDecrypt)(token, secret);
|
|
56
54
|
return credentials;
|
|
57
55
|
}
|
|
58
56
|
}
|
|
@@ -66,7 +64,7 @@ function getMiddlewareCredentials(security, secretKey, authorizationHeader) {
|
|
|
66
64
|
debug('parse legacy credentials failed');
|
|
67
65
|
return;
|
|
68
66
|
}
|
|
69
|
-
const parsedCredentials = (0,
|
|
67
|
+
const parsedCredentials = (0, _signature.parseBasicPayload)(credentials);
|
|
70
68
|
if (!parsedCredentials) {
|
|
71
69
|
debug('parse legacy basic payload credentials failed');
|
|
72
70
|
return;
|
|
@@ -115,7 +113,7 @@ const expireReasons = ['JsonWebTokenError', 'TokenExpiredError'];
|
|
|
115
113
|
exports.expireReasons = expireReasons;
|
|
116
114
|
function verifyJWTPayload(token, secret) {
|
|
117
115
|
try {
|
|
118
|
-
const payload = (0,
|
|
116
|
+
const payload = (0, _signature.verifyPayload)(token, secret);
|
|
119
117
|
return payload;
|
|
120
118
|
} catch (error) {
|
|
121
119
|
// #168 this check should be removed as soon AES encrypt is removed.
|
package/build/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["debug","buildDebug","parseAuthTokenHeader","authorizationHeader","parts","split","scheme","token","parseAESCredentials","secret","toUpperCase","TOKEN_BASIC","credentials","convertPayloadToBase64","toString","TOKEN_BEARER","aesDecrypt","getMiddlewareCredentials","security","secretKey","isAESLegacy","parsedCredentials","parseBasicPayload","_","isString","verifyJWTPayload","legacy","jwt","api","isNil","getApiToken","auth","config","remoteUser","aesPassword","Promise","resolve","aesEncrypt","buildUser","name","sign","jwtEncrypt","expireReasons","payload","verifyPayload","error","includes","createAnonymousRemoteUser","errorUtils","getCode","HTTP_STATUS","UNAUTHORIZED","message","isAuthHeaderValid","authorization","length","getDefaultPlugins","logger","authenticate","_user","_password","cb","getForbidden","API_ERROR","BAD_USERNAME_PASSWORD","adduser","getConflict","allow_access","allow_action","allow_publish","allow_unpublish","handleSpecialUnpublish","action","allowActionCallback","user","pkg","callback","trace","remote","groups","groupAccess","hasPermission","some","group","pkgName","getUnauthorized","isUnpublishMissing","hasGroups","undefined","password","String","Buffer","from"],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport _ from 'lodash';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport {\n API_ERROR,\n HTTP_STATUS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n VerdaccioError,\n errorUtils,\n pluginUtils,\n} from '@verdaccio/core';\nimport { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport { AESPayload, TokenEncryption } from './auth';\nimport { verifyPayload } from './jwt-token';\nimport { aesDecrypt } from './legacy-token';\nimport { parseBasicPayload } from './token';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\nexport type BasicPayload = AESPayload | void;\nexport type AuthMiddlewarePayload = RemoteUser | BasicPayload;\n\nexport interface AuthTokenHeader {\n scheme: string;\n token: string;\n}\nexport type AllowActionCallbackResponse = boolean | undefined;\nexport type AllowActionCallback = (\n error: VerdaccioError | null,\n allowed?: AllowActionCallbackResponse\n) => void;\n\nexport type AllowAction = (\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n) => void;\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');\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 const credentials = aesDecrypt(token, secret);\n\n return credentials;\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials');\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);\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): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(token, secret);\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 getDefaultPlugins(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n return cb(errorUtils.getConflict(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n // FIXME: allow_action and allow_publish should be in the @verdaccio/types\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 type ActionsAllowed = 'publish' | 'unpublish' | 'access';\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 const groupAccess = pkg[action] as string[];\n const hasPermission = groupAccess.some((group) => name === group || groups.includes(group));\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 = _.isNil(pkg[action]);\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":";;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;AACA;AAYA;AACA;AACA;AAA4C;AAE5C,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,sBAAsB,CAAC;AAqBhD;AACA;AACA;AACA;AACO,SAASC,oBAAoB,CAACC,mBAA2B,EAAmB;EACjF,MAAMC,KAAK,GAAGD,mBAAmB,CAACE,KAAK,CAAC,GAAG,CAAC;EAC5C,MAAM,CAACC,MAAM,EAAEC,KAAK,CAAC,GAAGH,KAAK;EAE7B,OAAO;IAAEE,MAAM;IAAEC;EAAM,CAAC;AAC1B;AAEO,SAASC,mBAAmB,CAACL,mBAA2B,EAAEM,MAAc,EAAE;EAC/ET,KAAK,CAAC,qBAAqB,CAAC;EAC5B,MAAM;IAAEM,MAAM;IAAEC;EAAM,CAAC,GAAGL,oBAAoB,CAACC,mBAAmB,CAAC;;EAEnE;EACA;EACA,IAAIG,MAAM,CAACI,WAAW,EAAE,KAAKC,iBAAW,CAACD,WAAW,EAAE,EAAE;IACtDV,KAAK,CAAC,qBAAqB,CAAC;IAC5B,MAAMY,WAAW,GAAGC,sBAAsB,CAACN,KAAK,CAAC,CAACO,QAAQ,EAAE;IAE5D,OAAOF,WAAW;EACpB,CAAC,MAAM,IAAIN,MAAM,CAACI,WAAW,EAAE,KAAKK,kBAAY,CAACL,WAAW,EAAE,EAAE;IAC9DV,KAAK,CAAC,sBAAsB,CAAC;IAC7B,MAAMY,WAAW,GAAG,IAAAI,uBAAU,EAACT,KAAK,EAAEE,MAAM,CAAC;IAE7C,OAAOG,WAAW;EACpB;AACF;AAEO,SAASK,wBAAwB,CACtCC,QAAkB,EAClBC,SAAiB,EACjBhB,mBAA2B,EACJ;EACvBH,KAAK,CAAC,0BAA0B,CAAC;EACjC;EACA,IAAIoB,WAAW,CAACF,QAAQ,CAA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AC1D,CAAC;AACH;AAEO,SAAStC,SAAS,CAACC,IAAY,EAAEkD,QAAgB,EAAU;EAChE,OAAOC,MAAM,CAAE,GAAEnD,IAAK,IAAGkD,QAAS,EAAC,CAAC;AACtC;AAEO,SAAS5E,sBAAsB,CAAC8B,OAAe,EAAU;EAC9D,OAAOgD,MAAM,CAACC,IAAI,CAACjD,OAAO,EAAE,QAAQ,CAAC;AACvC"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["debug","buildDebug","parseAuthTokenHeader","authorizationHeader","parts","split","scheme","token","parseAESCredentials","secret","toUpperCase","TOKEN_BASIC","credentials","convertPayloadToBase64","toString","TOKEN_BEARER","aesDecrypt","getMiddlewareCredentials","security","secretKey","isAESLegacy","parsedCredentials","parseBasicPayload","_","isString","verifyJWTPayload","legacy","jwt","api","isNil","getApiToken","auth","config","remoteUser","aesPassword","Promise","resolve","aesEncrypt","buildUser","name","sign","jwtEncrypt","expireReasons","payload","verifyPayload","error","includes","createAnonymousRemoteUser","errorUtils","getCode","HTTP_STATUS","UNAUTHORIZED","message","isAuthHeaderValid","authorization","length","getDefaultPlugins","logger","authenticate","_user","_password","cb","getForbidden","API_ERROR","BAD_USERNAME_PASSWORD","adduser","getConflict","allow_access","allow_action","allow_publish","allow_unpublish","handleSpecialUnpublish","action","allowActionCallback","user","pkg","callback","trace","remote","groups","groupAccess","hasPermission","some","group","pkgName","getUnauthorized","isUnpublishMissing","hasGroups","undefined","password","String","Buffer","from"],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport _ from 'lodash';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport {\n API_ERROR,\n HTTP_STATUS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n VerdaccioError,\n errorUtils,\n pluginUtils,\n} from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport { AESPayload, TokenEncryption } from './auth';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\nexport type BasicPayload = AESPayload | void;\nexport type AuthMiddlewarePayload = RemoteUser | BasicPayload;\n\nexport interface AuthTokenHeader {\n scheme: string;\n token: string;\n}\nexport type AllowActionCallbackResponse = boolean | undefined;\nexport type AllowActionCallback = (\n error: VerdaccioError | null,\n allowed?: AllowActionCallbackResponse\n) => void;\n\nexport type AllowAction = (\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n) => void;\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');\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 const credentials = aesDecrypt(token, secret);\n\n return credentials;\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials');\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);\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): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(token, secret);\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 getDefaultPlugins(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n return cb(errorUtils.getConflict(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n // FIXME: allow_action and allow_publish should be in the @verdaccio/types\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 type ActionsAllowed = 'publish' | 'unpublish' | 'access';\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 const groupAccess = pkg[action] as string[];\n const hasPermission = groupAccess.some((group) => name === group || groups.includes(group));\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 = _.isNil(pkg[action]);\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":";;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;AACA;AASA;AAAoF;AAKpF,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,sBAAsB,CAAC;AAqBhD;AACA;AACA;AACA;AACO,SAASC,oBAAoB,CAACC,mBAA2B,EAAmB;EACjF,MAAMC,KAAK,GAAGD,mBAAmB,CAACE,KAAK,CAAC,GAAG,CAAC;EAC5C,MAAM,CAACC,MAAM,EAAEC,KAAK,CAAC,GAAGH,KAAK;EAE7B,OAAO;IAAEE,MAAM;IAAEC;EAAM,CAAC;AAC1B;AAEO,SAASC,mBAAmB,CAACL,mBAA2B,EAAEM,MAAc,EAAE;EAC/ET,KAAK,CAAC,qBAAqB,CAAC;EAC5B,MAAM;IAAEM,MAAM;IAAEC;EAAM,CAAC,GAAGL,oBAAoB,CAACC,mBAAmB,CAAC;;EAEnE;EACA;EACA,IAAIG,MAAM,CAACI,WAAW,EAAE,KAAKC,iBAAW,CAACD,WAAW,EAAE,EAAE;IACtDV,KAAK,CAAC,qBAAqB,CAAC;IAC5B,MAAMY,WAAW,GAAGC,sBAAsB,CAACN,KAAK,CAAC,CAACO,QAAQ,EAAE;IAE5D,OAAOF,WAAW;EACpB,CAAC,MAAM,IAAIN,MAAM,CAACI,WAAW,EAAE,KAAKK,kBAAY,CAACL,WAAW,EAAE,EAAE;IAC9DV,KAAK,CAAC,sBAAsB,CAAC;IAC7B,MAAMY,WAAW,GAAG,IAAAI,qBAAU,EAACT,KAAK,EAAEE,MAAM,CAAC;IAE7C,OAAOG,WAAW;EACpB;AACF;AAEO,SAASK,wBAAwB,CACtCC,QAAkB,EAClBC,SAAiB,EACjBhB,mBAA2B,EACJ;EACvBH,KAAK,CAAC,0BAA0B,CAAC;EACjC;EACA,IAAIoB,WAAW,CAACF,QAAQ,CAAC,EAAE;IACzBlB,KAAK,CA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AStC,SAAS,CAACC,IAAY,EAAEkD,QAAgB,EAAU;EAChE,OAAOC,MAAM,CAAE,GAAEnD,IAAK,IAAGkD,QAAS,EAAC,CAAC;AACtC;AAEO,SAAS5E,sBAAsB,CAAC8B,OAAe,EAAU;EAC9D,OAAOgD,MAAM,CAACC,IAAI,CAACjD,OAAO,EAAE,QAAQ,CAAC;AACvC"}
|
package/jest.config.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@verdaccio/auth",
|
|
3
|
-
"version": "6.0.0-6-next.
|
|
3
|
+
"version": "6.0.0-6-next.42",
|
|
4
4
|
"description": "logger",
|
|
5
5
|
"main": "./build/index.js",
|
|
6
6
|
"types": "./build/index.d.ts",
|
|
@@ -30,19 +30,19 @@
|
|
|
30
30
|
},
|
|
31
31
|
"license": "MIT",
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@verdaccio/core": "6.0.0-6-next.
|
|
34
|
-
"@verdaccio/config": "6.0.0-6-next.
|
|
35
|
-
"@verdaccio/loaders": "6.0.0-6-next.
|
|
36
|
-
"@verdaccio/logger": "6.0.0-6-next.
|
|
37
|
-
"@verdaccio/
|
|
33
|
+
"@verdaccio/core": "6.0.0-6-next.63",
|
|
34
|
+
"@verdaccio/config": "6.0.0-6-next.63",
|
|
35
|
+
"@verdaccio/loaders": "6.0.0-6-next.32",
|
|
36
|
+
"@verdaccio/logger": "6.0.0-6-next.31",
|
|
37
|
+
"@verdaccio/signature": "6.0.0-6-next.2",
|
|
38
|
+
"@verdaccio/utils": "6.0.0-6-next.31",
|
|
38
39
|
"debug": "4.3.4",
|
|
39
40
|
"express": "4.18.2",
|
|
40
|
-
"jsonwebtoken": "9.0.0",
|
|
41
41
|
"lodash": "4.17.21",
|
|
42
|
-
"verdaccio-htpasswd": "11.0.0-6-next.
|
|
42
|
+
"verdaccio-htpasswd": "11.0.0-6-next.33"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@verdaccio/types": "11.0.0-6-next.
|
|
45
|
+
"@verdaccio/types": "11.0.0-6-next.22"
|
|
46
46
|
},
|
|
47
47
|
"funding": {
|
|
48
48
|
"type": "opencollective",
|
package/src/auth.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
} from '@verdaccio/core';
|
|
16
16
|
import { asyncLoadPlugin } from '@verdaccio/loaders';
|
|
17
17
|
import { logger } from '@verdaccio/logger';
|
|
18
|
+
import { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';
|
|
18
19
|
import {
|
|
19
20
|
AllowAccess,
|
|
20
21
|
Callback,
|
|
@@ -27,9 +28,6 @@ import {
|
|
|
27
28
|
} from '@verdaccio/types';
|
|
28
29
|
import { getMatchedPackagesSpec, isFunction, isNil } from '@verdaccio/utils';
|
|
29
30
|
|
|
30
|
-
import { signPayload } from './jwt-token';
|
|
31
|
-
import { aesEncrypt } from './legacy-token';
|
|
32
|
-
import { parseBasicPayload } from './token';
|
|
33
31
|
import {
|
|
34
32
|
convertPayloadToBase64,
|
|
35
33
|
getDefaultPlugins,
|
|
@@ -47,6 +45,7 @@ export interface TokenEncryption {
|
|
|
47
45
|
aesEncrypt(buf: string): string | void;
|
|
48
46
|
}
|
|
49
47
|
|
|
48
|
+
// remove
|
|
50
49
|
export interface AESPayload {
|
|
51
50
|
user: string;
|
|
52
51
|
password: string;
|
package/src/index.ts
CHANGED
package/src/utils.ts
CHANGED
|
@@ -11,12 +11,10 @@ import {
|
|
|
11
11
|
errorUtils,
|
|
12
12
|
pluginUtils,
|
|
13
13
|
} from '@verdaccio/core';
|
|
14
|
+
import { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';
|
|
14
15
|
import { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';
|
|
15
16
|
|
|
16
17
|
import { AESPayload, TokenEncryption } from './auth';
|
|
17
|
-
import { verifyPayload } from './jwt-token';
|
|
18
|
-
import { aesDecrypt } from './legacy-token';
|
|
19
|
-
import { parseBasicPayload } from './token';
|
|
20
18
|
|
|
21
19
|
const debug = buildDebug('verdaccio:auth:utils');
|
|
22
20
|
|
package/test/auth-utils.spec.ts
CHANGED
|
@@ -17,24 +17,22 @@ import {
|
|
|
17
17
|
errorUtils,
|
|
18
18
|
} from '@verdaccio/core';
|
|
19
19
|
import { setup } from '@verdaccio/logger';
|
|
20
|
+
import { aesDecrypt, signPayload, verifyPayload } from '@verdaccio/signature';
|
|
20
21
|
import { Config, RemoteUser, Security } from '@verdaccio/types';
|
|
21
22
|
import { buildToken, buildUserBuffer, getAuthenticatedMessage } from '@verdaccio/utils';
|
|
22
|
-
import type { AllowActionCallbackResponse } from '@verdaccio/utils';
|
|
23
23
|
|
|
24
24
|
import {
|
|
25
25
|
ActionsAllowed,
|
|
26
|
+
AllowActionCallbackResponse,
|
|
26
27
|
Auth,
|
|
27
|
-
aesDecrypt,
|
|
28
28
|
allow_action,
|
|
29
29
|
getApiToken,
|
|
30
30
|
getDefaultPlugins,
|
|
31
31
|
getMiddlewareCredentials,
|
|
32
|
-
signPayload,
|
|
33
32
|
verifyJWTPayload,
|
|
34
|
-
verifyPayload,
|
|
35
33
|
} from '../src';
|
|
36
34
|
|
|
37
|
-
setup(
|
|
35
|
+
setup({});
|
|
38
36
|
|
|
39
37
|
const parseConfigurationFile = (conf) => {
|
|
40
38
|
const { name, ext } = path.parse(conf);
|
|
@@ -452,6 +450,7 @@ describe('Auth utilities', () => {
|
|
|
452
450
|
const config: Config = getConfig('security-legacy', secret);
|
|
453
451
|
const auth: Auth = new Auth(config);
|
|
454
452
|
await auth.init();
|
|
453
|
+
// @ts-expect-error
|
|
455
454
|
const token = auth.aesEncrypt(null);
|
|
456
455
|
const security: Security = config.security;
|
|
457
456
|
const credentials = getMiddlewareCredentials(
|
package/tsconfig.json
CHANGED
package/build/jwt-token.d.ts
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { JWTSignOptions, RemoteUser } from '@verdaccio/types';
|
|
2
|
-
/**
|
|
3
|
-
* Sign the payload and return JWT
|
|
4
|
-
* https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
|
|
5
|
-
* @param payload
|
|
6
|
-
* @param secretOrPrivateKey
|
|
7
|
-
* @param options
|
|
8
|
-
*/
|
|
9
|
-
export declare function signPayload(payload: RemoteUser, secretOrPrivateKey: string, options?: JWTSignOptions): Promise<string>;
|
|
10
|
-
export declare function verifyPayload(token: string, secretOrPrivateKey: string): RemoteUser;
|
package/build/jwt-token.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.signPayload = signPayload;
|
|
7
|
-
exports.verifyPayload = verifyPayload;
|
|
8
|
-
var _debug = _interopRequireDefault(require("debug"));
|
|
9
|
-
var _jsonwebtoken = _interopRequireDefault(require("jsonwebtoken"));
|
|
10
|
-
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
11
|
-
const debug = (0, _debug.default)('verdaccio:auth:token:jwt');
|
|
12
|
-
/**
|
|
13
|
-
* Sign the payload and return JWT
|
|
14
|
-
* https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
|
|
15
|
-
* @param payload
|
|
16
|
-
* @param secretOrPrivateKey
|
|
17
|
-
* @param options
|
|
18
|
-
*/
|
|
19
|
-
async function signPayload(payload, secretOrPrivateKey, options = {}) {
|
|
20
|
-
return new Promise(function (resolve, reject) {
|
|
21
|
-
debug('sign jwt token');
|
|
22
|
-
return _jsonwebtoken.default.sign(payload, secretOrPrivateKey,
|
|
23
|
-
// FIXME: upgrade to the latest library and types
|
|
24
|
-
// @ts-ignore
|
|
25
|
-
{
|
|
26
|
-
// 1 === 1ms (one millisecond)
|
|
27
|
-
notBefore: '1',
|
|
28
|
-
// Make sure the time will not rollback :)
|
|
29
|
-
...options
|
|
30
|
-
}, (error, token) => {
|
|
31
|
-
debug('error on sign jwt token');
|
|
32
|
-
return error ? reject(error) : resolve(token);
|
|
33
|
-
});
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
function verifyPayload(token, secretOrPrivateKey) {
|
|
37
|
-
debug('verify jwt token');
|
|
38
|
-
return _jsonwebtoken.default.verify(token, secretOrPrivateKey);
|
|
39
|
-
}
|
|
40
|
-
//# sourceMappingURL=jwt-token.js.map
|
package/build/jwt-token.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jwt-token.js","names":["debug","buildDebug","signPayload","payload","secretOrPrivateKey","options","Promise","resolve","reject","jwt","sign","notBefore","error","token","verifyPayload","verify"],"sources":["../src/jwt-token.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport jwt from 'jsonwebtoken';\n\nimport { JWTSignOptions, RemoteUser } from '@verdaccio/types';\n\nconst debug = buildDebug('verdaccio:auth:token:jwt');\n/**\n * Sign the payload and return JWT\n * https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback\n * @param payload\n * @param secretOrPrivateKey\n * @param options\n */\nexport async function signPayload(\n payload: RemoteUser,\n secretOrPrivateKey: string,\n options: JWTSignOptions = {}\n): Promise<string> {\n return new Promise(function (resolve, reject): Promise<string> {\n debug('sign jwt token');\n return jwt.sign(\n payload,\n secretOrPrivateKey,\n // FIXME: upgrade to the latest library and types\n // @ts-ignore\n {\n // 1 === 1ms (one millisecond)\n notBefore: '1', // Make sure the time will not rollback :)\n ...options,\n },\n (error, token: string) => {\n debug('error on sign jwt token');\n return error ? reject(error) : resolve(token);\n }\n );\n });\n}\n\nexport function verifyPayload(token: string, secretOrPrivateKey: string): RemoteUser {\n debug('verify jwt token');\n return jwt.verify(token, secretOrPrivateKey) as RemoteUser;\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAA+B;AAI/B,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,0BAA0B,CAAC;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeC,WAAW,CAC/BC,OAAmB,EACnBC,kBAA0B,EAC1BC,OAAuB,GAAG,CAAC,CAAC,EACX;EACjB,OAAO,IAAIC,OAAO,CAAC,UAAUC,OAAO,EAAEC,MAAM,EAAmB;IAC7DR,KAAK,CAAC,gBAAgB,CAAC;IACvB,OAAOS,qBAAG,CAACC,IAAI,CACbP,OAAO,EACPC,kBAAkB;IAClB;IACA;IACA;MACE;MACAO,SAAS,EAAE,GAAG;MAAE;MAChB,GAAGN;IACL,CAAC,EACD,CAACO,KAAK,EAAEC,KAAa,KAAK;MACxBb,KAAK,CAAC,yBAAyB,CAAC;MAChC,OAAOY,KAAK,GAAGJ,MAAM,CAACI,KAAK,CAAC,GAAGL,OAAO,CAACM,KAAK,CAAC;IAC/C,CAAC,CACF;EACH,CAAC,CAAC;AACJ;AAEO,SAASC,aAAa,CAACD,KAAa,EAAET,kBAA0B,EAAc;EACnFJ,KAAK,CAAC,kBAAkB,CAAC;EACzB,OAAOS,qBAAG,CAACM,MAAM,CAACF,KAAK,EAAET,kBAAkB,CAAC;AAC9C"}
|
package/build/legacy-token.d.ts
DELETED
package/build/legacy-token.js
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.aesDecrypt = aesDecrypt;
|
|
7
|
-
exports.aesEncrypt = aesEncrypt;
|
|
8
|
-
exports.defaultAlgorithm = void 0;
|
|
9
|
-
var _crypto = require("crypto");
|
|
10
|
-
var _debug = _interopRequireDefault(require("debug"));
|
|
11
|
-
var _config = require("@verdaccio/config");
|
|
12
|
-
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
13
|
-
const debug = (0, _debug.default)('verdaccio:auth:token:legacy');
|
|
14
|
-
const defaultAlgorithm = process.env.VERDACCIO_LEGACY_ALGORITHM || 'aes-256-ctr';
|
|
15
|
-
exports.defaultAlgorithm = defaultAlgorithm;
|
|
16
|
-
const inputEncoding = 'utf8';
|
|
17
|
-
const outputEncoding = 'hex';
|
|
18
|
-
// For AES, this is always 16
|
|
19
|
-
const IV_LENGTH = 16;
|
|
20
|
-
// Must be 256 bits (32 characters)
|
|
21
|
-
// https://stackoverflow.com/questions/50963160/invalid-key-length-in-crypto-createcipheriv#50963356
|
|
22
|
-
const VERDACCIO_LEGACY_ENCRYPTION_KEY = process.env.VERDACCIO_LEGACY_ENCRYPTION_KEY;
|
|
23
|
-
function aesEncrypt(value, key) {
|
|
24
|
-
// https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options
|
|
25
|
-
// https://www.grainger.xyz/changing-from-cipher-to-cipheriv/
|
|
26
|
-
debug('encrypt %o', value);
|
|
27
|
-
debug('algorithm %o', defaultAlgorithm);
|
|
28
|
-
const iv = Buffer.from((0, _crypto.randomBytes)(IV_LENGTH));
|
|
29
|
-
const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;
|
|
30
|
-
const isKeyValid = (secretKey === null || secretKey === void 0 ? void 0 : secretKey.length) === _config.TOKEN_VALID_LENGTH;
|
|
31
|
-
debug('length secret key %o', secretKey === null || secretKey === void 0 ? void 0 : secretKey.length);
|
|
32
|
-
debug('is valid secret %o', isKeyValid);
|
|
33
|
-
if (!value || !secretKey || !isKeyValid) {
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
const cipher = (0, _crypto.createCipheriv)(defaultAlgorithm, secretKey, iv);
|
|
37
|
-
let encrypted = cipher.update(value, inputEncoding, outputEncoding);
|
|
38
|
-
// @ts-ignore
|
|
39
|
-
encrypted += cipher.final(outputEncoding);
|
|
40
|
-
const token = `${iv.toString('hex')}:${encrypted.toString()}`;
|
|
41
|
-
debug('token generated successfully');
|
|
42
|
-
return Buffer.from(token).toString('base64');
|
|
43
|
-
}
|
|
44
|
-
function aesDecrypt(value, key) {
|
|
45
|
-
try {
|
|
46
|
-
const buff = Buffer.from(value, 'base64');
|
|
47
|
-
const textParts = buff.toString().split(':');
|
|
48
|
-
|
|
49
|
-
// extract the IV from the first half of the value
|
|
50
|
-
// @ts-ignore
|
|
51
|
-
const IV = Buffer.from(textParts.shift(), outputEncoding);
|
|
52
|
-
// extract the encrypted text without the IV
|
|
53
|
-
const encryptedText = Buffer.from(textParts.join(':'), outputEncoding);
|
|
54
|
-
const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;
|
|
55
|
-
// decipher the string
|
|
56
|
-
const decipher = (0, _crypto.createDecipheriv)(defaultAlgorithm, secretKey, IV);
|
|
57
|
-
// FIXME: fix type here should allow Buffer
|
|
58
|
-
let decrypted = decipher.update(encryptedText, outputEncoding, inputEncoding);
|
|
59
|
-
decrypted += decipher.final(inputEncoding);
|
|
60
|
-
debug('token decrypted successfully');
|
|
61
|
-
return decrypted.toString();
|
|
62
|
-
} catch (_) {
|
|
63
|
-
return;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
//# sourceMappingURL=legacy-token.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"legacy-token.js","names":["debug","buildDebug","defaultAlgorithm","process","env","VERDACCIO_LEGACY_ALGORITHM","inputEncoding","outputEncoding","IV_LENGTH","VERDACCIO_LEGACY_ENCRYPTION_KEY","aesEncrypt","value","key","iv","Buffer","from","randomBytes","secretKey","isKeyValid","length","TOKEN_VALID_LENGTH","cipher","createCipheriv","encrypted","update","final","token","toString","aesDecrypt","buff","textParts","split","IV","shift","encryptedText","join","decipher","createDecipheriv","decrypted","_"],"sources":["../src/legacy-token.ts"],"sourcesContent":["import {\n BinaryToTextEncoding,\n CharacterEncoding,\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from 'crypto';\nimport buildDebug from 'debug';\n\nimport { TOKEN_VALID_LENGTH } from '@verdaccio/config';\n\nconst debug = buildDebug('verdaccio:auth:token:legacy');\n\nexport const defaultAlgorithm = process.env.VERDACCIO_LEGACY_ALGORITHM || 'aes-256-ctr';\nconst inputEncoding: CharacterEncoding = 'utf8';\nconst outputEncoding: BinaryToTextEncoding = 'hex';\n// For AES, this is always 16\nconst IV_LENGTH = 16;\n// Must be 256 bits (32 characters)\n// https://stackoverflow.com/questions/50963160/invalid-key-length-in-crypto-createcipheriv#50963356\nconst VERDACCIO_LEGACY_ENCRYPTION_KEY = process.env.VERDACCIO_LEGACY_ENCRYPTION_KEY;\n\nexport function aesEncrypt(value: string, key: string): string | void {\n // https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options\n // https://www.grainger.xyz/changing-from-cipher-to-cipheriv/\n debug('encrypt %o', value);\n debug('algorithm %o', defaultAlgorithm);\n const iv = Buffer.from(randomBytes(IV_LENGTH));\n const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;\n const isKeyValid = secretKey?.length === TOKEN_VALID_LENGTH;\n debug('length secret key %o', secretKey?.length);\n debug('is valid secret %o', isKeyValid);\n if (!value || !secretKey || !isKeyValid) {\n return;\n }\n\n const cipher = createCipheriv(defaultAlgorithm, secretKey, iv);\n let encrypted = cipher.update(value, inputEncoding, outputEncoding);\n // @ts-ignore\n encrypted += cipher.final(outputEncoding);\n const token = `${iv.toString('hex')}:${encrypted.toString()}`;\n debug('token generated successfully');\n return Buffer.from(token).toString('base64');\n}\n\nexport function aesDecrypt(value: string, key: string): string | void {\n try {\n const buff = Buffer.from(value, 'base64');\n const textParts = buff.toString().split(':');\n\n // extract the IV from the first half of the value\n // @ts-ignore\n const IV = Buffer.from(textParts.shift(), outputEncoding);\n // extract the encrypted text without the IV\n const encryptedText = Buffer.from(textParts.join(':'), outputEncoding);\n const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;\n // decipher the string\n const decipher = createDecipheriv(defaultAlgorithm, secretKey, IV);\n // FIXME: fix type here should allow Buffer\n let decrypted = decipher.update(encryptedText as any, outputEncoding, inputEncoding);\n decrypted += decipher.final(inputEncoding);\n debug('token decrypted successfully');\n return decrypted.toString();\n } catch (_: any) {\n return;\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAOA;AAEA;AAAuD;AAEvD,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,6BAA6B,CAAC;AAEhD,MAAMC,gBAAgB,GAAGC,OAAO,CAACC,GAAG,CAACC,0BAA0B,IAAI,aAAa;AAAC;AACxF,MAAMC,aAAgC,GAAG,MAAM;AAC/C,MAAMC,cAAoC,GAAG,KAAK;AAClD;AACA,MAAMC,SAAS,GAAG,EAAE;AACpB;AACA;AACA,MAAMC,+BAA+B,GAAGN,OAAO,CAACC,GAAG,CAACK,+BAA+B;AAE5E,SAASC,UAAU,CAACC,KAAa,EAAEC,GAAW,EAAiB;EACpE;EACA;EACAZ,KAAK,CAAC,YAAY,EAAEW,KAAK,CAAC;EAC1BX,KAAK,CAAC,cAAc,EAAEE,gBAAgB,CAAC;EACvC,MAAMW,EAAE,GAAGC,MAAM,CAACC,IAAI,CAAC,IAAAC,mBAAW,EAACR,SAAS,CAAC,CAAC;EAC9C,MAAMS,SAAS,GAAGR,+BAA+B,IAAIG,GAAG;EACxD,MAAMM,UAAU,GAAG,CAAAD,SAAS,aAATA,SAAS,uBAATA,SAAS,CAAEE,MAAM,MAAKC,0BAAkB;EAC3DpB,KAAK,CAAC,sBAAsB,EAAEiB,SAAS,aAATA,SAAS,uBAATA,SAAS,CAAEE,MAAM,CAAC;EAChDnB,KAAK,CAAC,oBAAoB,EAAEkB,UAAU,CAAC;EACvC,IAAI,CAACP,KAAK,IAAI,CAACM,SAAS,IAAI,CAACC,UAAU,EAAE;IACvC;EACF;EAEA,MAAMG,MAAM,GAAG,IAAAC,sBAAc,EAACpB,gBAAgB,EAAEe,SAAS,EAAEJ,EAAE,CAAC;EAC9D,IAAIU,SAAS,GAAGF,MAAM,CAACG,MAAM,CAACb,KAAK,EAAEL,a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DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.parseBasicPayload = parseBasicPayload;
|
|
7
|
-
function parseBasicPayload(credentials) {
|
|
8
|
-
const index = credentials.indexOf(':');
|
|
9
|
-
if (index < 0) {
|
|
10
|
-
return;
|
|
11
|
-
}
|
|
12
|
-
const user = credentials.slice(0, index);
|
|
13
|
-
const password = credentials.slice(index + 1);
|
|
14
|
-
return {
|
|
15
|
-
user,
|
|
16
|
-
password
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
//# sourceMappingURL=token.js.map
|
package/build/token.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"token.js","names":["parseBasicPayload","credentials","index","indexOf","user","slice","password"],"sources":["../src/token.ts"],"sourcesContent":["import { BasicPayload } from './utils';\n\nexport function parseBasicPayload(credentials: string): BasicPayload {\n const index = credentials.indexOf(':');\n if (index < 0) {\n return;\n }\n\n const user: string = credentials.slice(0, index);\n const password: string = credentials.slice(index + 1);\n\n return { user, password };\n}\n"],"mappings":";;;;;;AAEO,SAASA,iBAAiB,CAACC,WAAmB,EAAgB;EACnE,MAAMC,KAAK,GAAGD,WAAW,CAACE,OAAO,CAAC,GAAG,CAAC;EACtC,IAAID,KAAK,GAAG,CAAC,EAAE;IACb;EACF;EAEA,MAAME,IAAY,GAAGH,WAAW,CAACI,KAAK,CAAC,CAAC,EAAEH,KAAK,CAAC;EAChD,MAAMI,QAAgB,GAAGL,WAAW,CAACI,KAAK,CAACH,KAAK,GAAG,CAAC,CAAC;EAErD,OAAO;IAAEE,IAAI;IAAEE;EAAS,CAAC;AAC3B"}
|
package/src/jwt-token.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import buildDebug from 'debug';
|
|
2
|
-
import jwt from 'jsonwebtoken';
|
|
3
|
-
|
|
4
|
-
import { JWTSignOptions, RemoteUser } from '@verdaccio/types';
|
|
5
|
-
|
|
6
|
-
const debug = buildDebug('verdaccio:auth:token:jwt');
|
|
7
|
-
/**
|
|
8
|
-
* Sign the payload and return JWT
|
|
9
|
-
* https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
|
|
10
|
-
* @param payload
|
|
11
|
-
* @param secretOrPrivateKey
|
|
12
|
-
* @param options
|
|
13
|
-
*/
|
|
14
|
-
export async function signPayload(
|
|
15
|
-
payload: RemoteUser,
|
|
16
|
-
secretOrPrivateKey: string,
|
|
17
|
-
options: JWTSignOptions = {}
|
|
18
|
-
): Promise<string> {
|
|
19
|
-
return new Promise(function (resolve, reject): Promise<string> {
|
|
20
|
-
debug('sign jwt token');
|
|
21
|
-
return jwt.sign(
|
|
22
|
-
payload,
|
|
23
|
-
secretOrPrivateKey,
|
|
24
|
-
// FIXME: upgrade to the latest library and types
|
|
25
|
-
// @ts-ignore
|
|
26
|
-
{
|
|
27
|
-
// 1 === 1ms (one millisecond)
|
|
28
|
-
notBefore: '1', // Make sure the time will not rollback :)
|
|
29
|
-
...options,
|
|
30
|
-
},
|
|
31
|
-
(error, token: string) => {
|
|
32
|
-
debug('error on sign jwt token');
|
|
33
|
-
return error ? reject(error) : resolve(token);
|
|
34
|
-
}
|
|
35
|
-
);
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function verifyPayload(token: string, secretOrPrivateKey: string): RemoteUser {
|
|
40
|
-
debug('verify jwt token');
|
|
41
|
-
return jwt.verify(token, secretOrPrivateKey) as RemoteUser;
|
|
42
|
-
}
|
package/src/legacy-token.ts
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BinaryToTextEncoding,
|
|
3
|
-
CharacterEncoding,
|
|
4
|
-
createCipheriv,
|
|
5
|
-
createDecipheriv,
|
|
6
|
-
randomBytes,
|
|
7
|
-
} from 'crypto';
|
|
8
|
-
import buildDebug from 'debug';
|
|
9
|
-
|
|
10
|
-
import { TOKEN_VALID_LENGTH } from '@verdaccio/config';
|
|
11
|
-
|
|
12
|
-
const debug = buildDebug('verdaccio:auth:token:legacy');
|
|
13
|
-
|
|
14
|
-
export const defaultAlgorithm = process.env.VERDACCIO_LEGACY_ALGORITHM || 'aes-256-ctr';
|
|
15
|
-
const inputEncoding: CharacterEncoding = 'utf8';
|
|
16
|
-
const outputEncoding: BinaryToTextEncoding = 'hex';
|
|
17
|
-
// For AES, this is always 16
|
|
18
|
-
const IV_LENGTH = 16;
|
|
19
|
-
// Must be 256 bits (32 characters)
|
|
20
|
-
// https://stackoverflow.com/questions/50963160/invalid-key-length-in-crypto-createcipheriv#50963356
|
|
21
|
-
const VERDACCIO_LEGACY_ENCRYPTION_KEY = process.env.VERDACCIO_LEGACY_ENCRYPTION_KEY;
|
|
22
|
-
|
|
23
|
-
export function aesEncrypt(value: string, key: string): string | void {
|
|
24
|
-
// https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options
|
|
25
|
-
// https://www.grainger.xyz/changing-from-cipher-to-cipheriv/
|
|
26
|
-
debug('encrypt %o', value);
|
|
27
|
-
debug('algorithm %o', defaultAlgorithm);
|
|
28
|
-
const iv = Buffer.from(randomBytes(IV_LENGTH));
|
|
29
|
-
const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;
|
|
30
|
-
const isKeyValid = secretKey?.length === TOKEN_VALID_LENGTH;
|
|
31
|
-
debug('length secret key %o', secretKey?.length);
|
|
32
|
-
debug('is valid secret %o', isKeyValid);
|
|
33
|
-
if (!value || !secretKey || !isKeyValid) {
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const cipher = createCipheriv(defaultAlgorithm, secretKey, iv);
|
|
38
|
-
let encrypted = cipher.update(value, inputEncoding, outputEncoding);
|
|
39
|
-
// @ts-ignore
|
|
40
|
-
encrypted += cipher.final(outputEncoding);
|
|
41
|
-
const token = `${iv.toString('hex')}:${encrypted.toString()}`;
|
|
42
|
-
debug('token generated successfully');
|
|
43
|
-
return Buffer.from(token).toString('base64');
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function aesDecrypt(value: string, key: string): string | void {
|
|
47
|
-
try {
|
|
48
|
-
const buff = Buffer.from(value, 'base64');
|
|
49
|
-
const textParts = buff.toString().split(':');
|
|
50
|
-
|
|
51
|
-
// extract the IV from the first half of the value
|
|
52
|
-
// @ts-ignore
|
|
53
|
-
const IV = Buffer.from(textParts.shift(), outputEncoding);
|
|
54
|
-
// extract the encrypted text without the IV
|
|
55
|
-
const encryptedText = Buffer.from(textParts.join(':'), outputEncoding);
|
|
56
|
-
const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;
|
|
57
|
-
// decipher the string
|
|
58
|
-
const decipher = createDecipheriv(defaultAlgorithm, secretKey, IV);
|
|
59
|
-
// FIXME: fix type here should allow Buffer
|
|
60
|
-
let decrypted = decipher.update(encryptedText as any, outputEncoding, inputEncoding);
|
|
61
|
-
decrypted += decipher.final(inputEncoding);
|
|
62
|
-
debug('token decrypted successfully');
|
|
63
|
-
return decrypted.toString();
|
|
64
|
-
} catch (_: any) {
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
}
|
package/src/token.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { BasicPayload } from './utils';
|
|
2
|
-
|
|
3
|
-
export function parseBasicPayload(credentials: string): BasicPayload {
|
|
4
|
-
const index = credentials.indexOf(':');
|
|
5
|
-
if (index < 0) {
|
|
6
|
-
return;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
const user: string = credentials.slice(0, index);
|
|
10
|
-
const password: string = credentials.slice(index + 1);
|
|
11
|
-
|
|
12
|
-
return { user, password };
|
|
13
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { aesDecrypt, aesEncrypt } from '../src/legacy-token';
|
|
2
|
-
|
|
3
|
-
describe('test crypto utils', () => {
|
|
4
|
-
test('decrypt payload flow', () => {
|
|
5
|
-
const secret = 'f5bb945cc57fea2f25961e1bd6fb3c89';
|
|
6
|
-
const payload = 'juan:password';
|
|
7
|
-
const token = aesEncrypt(payload, secret) as string;
|
|
8
|
-
const data = aesDecrypt(token, secret);
|
|
9
|
-
|
|
10
|
-
expect(payload).toEqual(data);
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
test('crypt fails if secret is incorrect', () => {
|
|
14
|
-
const secret = 'f5bb945cc57fea2f25961e1bd6fb3c89_TO_LONG';
|
|
15
|
-
const payload = 'juan';
|
|
16
|
-
const token = aesEncrypt(payload, secret) as string;
|
|
17
|
-
expect(token).toBeUndefined();
|
|
18
|
-
});
|
|
19
|
-
});
|