@verdaccio/auth 9.0.0-next-9.17 → 9.0.0-next-9.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/auth.js +9 -4
- package/build/auth.js.map +1 -1
- package/build/auth.mjs +9 -4
- package/build/auth.mjs.map +1 -1
- package/build/types.d.ts +1 -0
- package/build/utils.d.ts +4 -2
- package/build/utils.js +14 -5
- package/build/utils.js.map +1 -1
- package/build/utils.mjs +14 -5
- package/build/utils.mjs.map +1 -1
- package/package.json +11 -11
package/build/auth.js
CHANGED
|
@@ -342,7 +342,10 @@ var Auth = class {
|
|
|
342
342
|
debug$1("authenticating %o", user);
|
|
343
343
|
this.authenticate(user, password, (err, user) => {
|
|
344
344
|
if (!err) {
|
|
345
|
-
req.remote_user =
|
|
345
|
+
req.remote_user = credentials.tokenKey ? {
|
|
346
|
+
...user,
|
|
347
|
+
token: { key: credentials.tokenKey }
|
|
348
|
+
} : user;
|
|
346
349
|
debug$1("generating a remote user");
|
|
347
350
|
next();
|
|
348
351
|
} else {
|
|
@@ -391,14 +394,16 @@ var Auth = class {
|
|
|
391
394
|
};
|
|
392
395
|
}
|
|
393
396
|
async jwtEncrypt(user, signOptions) {
|
|
394
|
-
const { real_groups, name, groups } = user;
|
|
397
|
+
const { real_groups, name, groups, token: tokenMetadata } = user;
|
|
395
398
|
debug$1("jwt encrypt %o", name);
|
|
396
399
|
const realGroupsValidated = (0, lodash_es.isNil)(real_groups) ? [] : real_groups;
|
|
397
|
-
|
|
400
|
+
const payload = {
|
|
398
401
|
real_groups: realGroupsValidated,
|
|
399
402
|
name,
|
|
400
403
|
groups: (0, lodash_es.isNil)(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
|
|
401
|
-
}
|
|
404
|
+
};
|
|
405
|
+
if (tokenMetadata?.key) payload.token = { key: tokenMetadata.key };
|
|
406
|
+
return await (0, _verdaccio_signature.signPayload)(payload, this.secret, signOptions);
|
|
402
407
|
}
|
|
403
408
|
/**
|
|
404
409
|
* Encrypt a string.
|
package/build/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { filter, isEmpty, isNil, isUndefined } from 'lodash-es';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = filter(\n this.plugins,\n (plugin) => typeof plugin.changePassword === 'function'\n );\n\n if (isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || typeof plugin.changePassword !== 'function') {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (typeof groups === 'string') {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = Array.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = isNil(real_groups) ? [] : real_groups;\n const groupedGroups = isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n const token: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n debug('signing with aes encryption');\n const token = aesEncrypt(value, this.secret);\n return token;\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;;;AAiDA,IAAM,WAAA,GAAA,MAAA,SAAmB,iBAAiB;AAE1C,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAA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,gBAAA,aAAa,IAAI,GAAG;AACnE,OAAI,CAAC,MACH,QAAO,MAAM;GAGf,IAAI;AACJ,OAAI;AACF,kBAAc,cAAA,iBAAiB,OAAO,KAAK,OAAO,QAAQ,KAAK,OAAO,SAAS;WACzE;AAIR,OAAI,KAAK,mBAAmB,YAAY,EAAE;IACxC,MAAM,EAAE,MAAM,WAAW;AACzB,QAAI,eAAA,GAAA,kBAAA,kBAA+B,MAAgB,OAAO;SAE1D,KAAI,eAAA,GAAA,kBAAA,4BAAyC;AAG/C,SAAM;;;CAIV,MAAa,WAAW,MAAkB,aAA8C;EACtF,MAAM,EAAE,aAAa,MAAM,WAAW;AACtC,UAAM,kBAAkB,KAAK;EAC7B,MAAM,uBAAA,GAAA,UAAA,OAA4B,YAAY,GAAG,EAAE,GAAG;AAetD,SANsB,OAAA,GAAA,qBAAA,aALM;GAC1B,aAAa;GACb;GACA,SAAA,GAAA,UAAA,OAN0B,OAAO,GAC/B,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,oBAAoB,CAAC,CAAC,CAAC;GAK/D,EAGC,KAAK,QACL,YACD;;;;;CAQH,WAAkB,OAA8B;AAC9C,UAAM,8BAA8B;AAEpC,UAAA,GAAA,qBAAA,YADyB,OAAO,KAAK,OAAO"}
|
|
1
|
+
{"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { filter, isEmpty, isNil, isUndefined } from 'lodash-es';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = filter(\n this.plugins,\n (plugin) => typeof plugin.changePassword === 'function'\n );\n\n if (isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || typeof plugin.changePassword !== 'function') {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (typeof groups === 'string') {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = Array.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = credentials.tokenKey\n ? { ...user, token: { key: credentials.tokenKey } }\n : user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups, token: tokenMetadata } = 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 if (tokenMetadata?.key) {\n payload.token = { key: tokenMetadata.key };\n }\n const signedToken: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return signedToken;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n debug('signing with aes encryption');\n const token = aesEncrypt(value, this.secret);\n return token;\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;;;AAiDA,IAAM,WAAA,GAAA,MAAA,SAAmB,gBAAgB;AAEzC,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAAoB,MAAM,GAAG;EAC1F,KAAK,SAAS;EACd,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS;EACd,KAAK,UAAU,CAAC;EAChB,KAAK,UAAU;EACf,IAAI,CAAC,KAAK,QACR,MAAM,IAAI,UAAU,0DAA0D;CAElF;CAEA,MAAa,OAAO;EAClB,IAAI,UAAU,MAAM,KAAK,WAAW;EAEpC,QAAM,yBAAyB,QAAQ,MAAM;EAG7C,IAAI,KAAK,OAAO,SAAS,SAAS,CAAC,WAAW,QAAQ,WAAW,IAC/D,UAAU,KAAK,kBAAkB;EAEnC,KAAK,UAAU;EAEf,KAAK,2BAA2B;CAClC;CAEA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AGd,IAAI;GACJ,IAAI;IACF,cAAc,cAAA,iBAAiB,OAAO,KAAK,OAAO,QAAQ,KAAK,OAAO,QAAQ;GAChF,QAAQ,CAER;GAEA,IAAI,KAAK,mBAAmB,WAAW,GAAG;IACxC,MAAM,EAAE,MAAM,WAAW;IACzB,IAAI,eAAA,GAAA,kBAAA,kBAA+B,MAAgB,MAAM;GAC3D,OACE,IAAI,eAAA,GAAA,kBAAA,2BAAwC;GAG9C,KAAK;EACP;CACF;CAEA,MAAa,WAAW,MAAkB,aAA8C;EACtF,MAAM,EAAE,aAAa,MAAM,QAAQ,OAAO,kBAAkB;EAC5D,QAAM,kBAAkB,IAAI;EAC5B,MAAM,uBAAA,GAAA,UAAA,OAA4B,WAAW,IAAI,CAAC,IAAI;EAItD,MAAM,UAAsB;GAC1B,aAAa;GACb;GACA,SAAA,GAAA,UAAA,OAN0B,MAAM,IAC9B,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,mBAAmB,CAAC,CAAC,CAAC;EAK/D;EACA,IAAI,eAAe,KACjB,QAAQ,QAAQ,EAAE,KAAK,cAAc,IAAI;EAQ3C,OAAO,OAAA,GAAA,qBAAA,aALL,SACA,KAAK,QACL,WACF;CAGF;;;;CAKA,WAAkB,OAA8B;EAC9C,QAAM,6BAA6B;EAEnC,QAAA,GAAA,qBAAA,YADyB,OAAO,KAAK,MAC9B;CACT;AACF"}
|
package/build/auth.mjs
CHANGED
|
@@ -340,7 +340,10 @@ var Auth = class {
|
|
|
340
340
|
debug("authenticating %o", user);
|
|
341
341
|
this.authenticate(user, password, (err, user) => {
|
|
342
342
|
if (!err) {
|
|
343
|
-
req.remote_user =
|
|
343
|
+
req.remote_user = credentials.tokenKey ? {
|
|
344
|
+
...user,
|
|
345
|
+
token: { key: credentials.tokenKey }
|
|
346
|
+
} : user;
|
|
344
347
|
debug("generating a remote user");
|
|
345
348
|
next();
|
|
346
349
|
} else {
|
|
@@ -389,14 +392,16 @@ var Auth = class {
|
|
|
389
392
|
};
|
|
390
393
|
}
|
|
391
394
|
async jwtEncrypt(user, signOptions) {
|
|
392
|
-
const { real_groups, name, groups } = user;
|
|
395
|
+
const { real_groups, name, groups, token: tokenMetadata } = user;
|
|
393
396
|
debug("jwt encrypt %o", name);
|
|
394
397
|
const realGroupsValidated = isNil(real_groups) ? [] : real_groups;
|
|
395
|
-
|
|
398
|
+
const payload = {
|
|
396
399
|
real_groups: realGroupsValidated,
|
|
397
400
|
name,
|
|
398
401
|
groups: isNil(groups) ? real_groups : Array.from(new Set([...groups.concat(realGroupsValidated)]))
|
|
399
|
-
}
|
|
402
|
+
};
|
|
403
|
+
if (tokenMetadata?.key) payload.token = { key: tokenMetadata.key };
|
|
404
|
+
return await signPayload(payload, this.secret, signOptions);
|
|
400
405
|
}
|
|
401
406
|
/**
|
|
402
407
|
* Encrypt a string.
|
package/build/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { filter, isEmpty, isNil, isUndefined } from 'lodash-es';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = filter(\n this.plugins,\n (plugin) => typeof plugin.changePassword === 'function'\n );\n\n if (isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || typeof plugin.changePassword !== 'function') {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (typeof groups === 'string') {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = Array.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = isNil(real_groups) ? [] : real_groups;\n const groupedGroups = isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n const token: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n debug('signing with aes encryption');\n const token = aesEncrypt(value, this.secret);\n return token;\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;AAiDA,IAAM,QAAQ,WAAW,iBAAiB;AAE1C,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAAoB,OAAO,EAAE;AAC1F,OAAK,SAAS;AACd,OAAK,SAAS,OAAO;AACrB,OAAK,SAAS;AACd,OAAK,UAAU,EAAE;AACjB,OAAK,UAAU;AACf,MAAI,CAAC,KAAK,OACR,OAAM,IAAI,UAAU,2DAA2D;;CAInF,MAAa,OAAO;EAClB,IAAI,UAAU,MAAM,KAAK,YAAY;AAErC,QAAM,yBAAyB,QAAQ,OAAO;AAG9C,MAAI,KAAK,OAAO,SAAS,SAAS,CAAC,WAAW,QAAQ,WAAW,GAC/D,WAAU,KAAK,mBAAmB;AAEpC,OAAK,UAAU;AAEf,OAAK,4BAA4B;;CAGnC,oBAA4B;AAC1B,QAAM,2BAA2B;EACjC,IAAI;AACJ,MAAI;AACF,gBAAa,IAAI,SACf,EAAE,MAAM,cAAc,EACtB;IACE,QAAQ,KAAK;IACb,QAAQ,KAAK;IACd,CACF;AACD,QAAK,OAAO,KACV;IAAE,MAAM;IAAsB,gBAAgB,gBAAgB;IAAgB,EAC9E,yDACD;WACM,OAAY;AACnB,SAAM,mDAAmD,MAAM;AAC/D,QAAK,OAAO,KAAK,EAAE,EAAE,gCAAgC;AACrD,UAAO,EAAE;;AAGX,SAAO,CAAC,WAAW;;C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B,CAAC;GAGlE,MAAM,SAAS,iBAAiB,IAAI,QAAQ,GAAG,aAAa,IAAI,GAAG;AACnE,OAAI,CAAC,MACH,QAAO,MAAM;GAGf,IAAI;AACJ,OAAI;AACF,kBAAc,iBAAiB,OAAO,KAAK,OAAO,QAAQ,KAAK,OAAO,SAAS;WACzE;AAIR,OAAI,KAAK,mBAAmB,YAAY,EAAE;IACxC,MAAM,EAAE,MAAM,WAAW;AACzB,QAAI,cAAc,iBAAiB,MAAgB,OAAO;SAE1D,KAAI,cAAc,2BAA2B;AAG/C,SAAM;;;CAIV,MAAa,WAAW,MAAkB,aAA8C;EACtF,MAAM,EAAE,aAAa,MAAM,WAAW;AACtC,QAAM,kBAAkB,KAAK;EAC7B,MAAM,sBAAsB,MAAM,YAAY,GAAG,EAAE,GAAG;AAetD,SANsB,MAAM,YALA;GAC1B,aAAa;GACb;GACA,QANoB,MAAM,OAAO,GAC/B,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,oBAAoB,CAAC,CAAC,CAAC;GAK/D,EAGC,KAAK,QACL,YACD;;;;;CAQH,WAAkB,OAA8B;AAC9C,QAAM,8BAA8B;AAEpC,SADc,WAAW,OAAO,KAAK,OAAO"}
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { filter, isEmpty, isNil, isUndefined } from 'lodash-es';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport {\n API_ERROR,\n PLUGIN_CATEGORY,\n PLUGIN_PREFIX,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n authUtils,\n errorUtils,\n pluginUtils as pluginSanity,\n warningUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { aesEncrypt, parseBasicPayload, signPayload } from '@verdaccio/signature';\nimport type {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\n\nimport type {\n $RequestExtend,\n $ResponseExtend,\n AESPayload,\n IAuthMiddleware,\n NextFunction,\n TokenEncryption,\n} from './types';\nimport {\n convertPayloadToBase64,\n getDefaultPluginMethods,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public logger: Logger;\n public plugins: pluginUtils.Auth<Config>[];\n public options: { legacyMergeConfigs: boolean };\n\n public constructor(config: Config, logger: Logger, options = { legacyMergeConfigs: false }) {\n this.config = config;\n this.secret = config.secret;\n this.logger = logger;\n this.plugins = [];\n this.options = options;\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = await this.loadPlugin();\n\n debug('auth plugins found %s', plugins.length);\n // Missing auth config or no loaded plugins -> load default htpasswd plugin\n // Empty auth config (null) -> just use fallback methods\n if (this.config.auth !== null && (!plugins || plugins.length === 0)) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this.applyFallbackPluginMethods();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n {\n config: this.config,\n logger: this.logger,\n }\n );\n this.logger.info(\n { name: 'verdaccio-htpasswd', pluginCategory: PLUGIN_CATEGORY.AUTHENTICATION },\n 'plugin @{name} successfully loaded (@{pluginCategory})'\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n this.logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<Config>>(\n this.config.auth,\n {\n config: this.config,\n logger: this.logger,\n },\n pluginSanity.authSanityCheck,\n this.options.legacyMergeConfigs,\n this.config?.server?.pluginPrefix ?? PLUGIN_PREFIX,\n PLUGIN_CATEGORY.AUTHENTICATION\n );\n }\n\n private applyFallbackPluginMethods(): void {\n this.plugins.push(getDefaultPluginMethods(this.logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = filter(\n this.plugins,\n (plugin) => typeof plugin.changePassword === 'function'\n );\n\n if (isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || typeof plugin.changePassword !== 'function') {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n this.logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.authenticate !== 'function') {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (typeof groups === 'string') {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = Array.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n let method = 'adduser';\n const plugin = plugins.shift();\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n method = 'add_user';\n warningUtils.emit(warningUtils.Codes.VERWAR006);\n }\n // @ts-ignore\n if (typeof plugin[method] !== 'function') {\n next();\n } else {\n // TODO: replace by adduser whenever add_user deprecation method has been removed\n // @ts-ignore\n plugin[method](\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not be added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n debug('user could not be added, skip to next auth plugin');\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n\n debug('check access permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_access !== 'function') {\n debug('plugin does not implement allow_access');\n return next();\n }\n\n plugin.allow_access(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden access. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('access was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `access was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('access was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate access denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check unpublish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_unpublish !== 'function') {\n debug('plugin does not implement allow_unpublish');\n return next();\n }\n\n plugin.allow_unpublish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden unpublish. Error: %o', err);\n return callback(err);\n }\n\n // The following is different from the allow_access and allow_publish implementations:\n // If the packages config is missing an entry for \"unpublish\", the built-in default method\n // (or a plugin) will return undefined, which will trigger the allow_publish fallback.\n // (see utils.ts, handleSpecialUnpublish, callback(null, undefined))\n if (isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `bypass unpublish for @{name} by @{user}, publish will handle the access`\n );\n return this.allow_publish({ packageName, packageVersion }, user, callback);\n }\n\n if (ok) {\n debug('unpublish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `unpublish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('unpublish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate unpublish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n authUtils.getMatchedPackagesSpec(packageName, this.config.packages)\n );\n\n debug('check publish permissions for user %o to package %o', user.name, packageName);\n\n // Use const instead of function declaration so we can use this.logger\n const next = (): void => {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('plugin does not implement allow_publish');\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (err) {\n debug('forbidden publish. Error: %o', err);\n return callback(err);\n }\n\n if (ok) {\n debug('publish was granted');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `publish was granted for @{name} by @{user}`\n );\n return callback(null, ok);\n }\n\n // cb(null, false) causes next plugin to roll\n debug('publish was denied. Rolling to next plugin');\n this.logger.trace(\n { user: user.name, name: pkg.name },\n `intermediate publish denial for @{name} by @{user}, rolling to next plugin`\n );\n return next();\n });\n };\n\n return next();\n }\n\n public apiJWTmiddleware(): any {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n const next = function (err?: VerdaccioError): NextFunction {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next() as unknown as NextFunction;\n };\n\n // FUTURE: disabled, not removed yet but seems unreacable code\n // if (this._isRemoteUserValid(req.remote_user)) {\n // debug('jwt has a valid authentication header');\n // return next();\n // }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this.handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this.handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: any\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('invalid basic credentials format (missing colon separator)');\n next(errorUtils.getBadRequest(API_ERROR.BAD_USERNAME_PASSWORD));\n return;\n }\n const { user, password } = parsedCredentials as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware has a secret? %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = credentials.tokenKey\n ? { ...user, token: { key: credentials.tokenKey } }\n : user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return isUndefined(remote_user) === false && isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware() {\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret, this.config.security);\n } catch {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups, token: tokenMetadata } = 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 if (tokenMetadata?.key) {\n payload.token = { key: tokenMetadata.key };\n }\n const signedToken: string = await signPayload(\n payload,\n this.secret,\n signOptions as Parameters<typeof signPayload>[2]\n );\n\n return signedToken;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n debug('signing with aes encryption');\n const token = aesEncrypt(value, this.secret);\n return token;\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;;;AAiDA,IAAM,QAAQ,WAAW,gBAAgB;AAEzC,IAAM,OAAN,MAA+E;CAC7E;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB,UAAU,EAAE,oBAAoB,MAAM,GAAG;EAC1F,KAAK,SAAS;EACd,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS;EACd,KAAK,UAAU,CAAC;EAChB,KAAK,UAAU;EACf,IAAI,CAAC,KAAK,QACR,MAAM,IAAI,UAAU,0DAA0D;CAElF;CAEA,MAAa,OAAO;EAClB,IAAI,UAAU,MAAM,KAAK,WAAW;EAEpC,MAAM,yBAAyB,QAAQ,MAAM;EAG7C,IAAI,KAAK,OAAO,SAAS,SAAS,CAAC,WAAW,QAAQ,WAAW,IAC/D,UAAU,KAAK,kBAAkB;EAEnC,KAAK,UAAU;EAEf,KAAK,2BAA2B;CAClC;CAEA,oBAA4B;EAC1B,MAAM,0BAA0B;EAChC,IAAI;EACJ,I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,MAAM,IAC9B,cACA,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,mBAAmB,CAAC,CAAC,CAAC;EAK/D;EACA,IAAI,eAAe,KACjB,QAAQ,QAAQ,EAAE,KAAK,cAAc,IAAI;EAQ3C,OAAO,MAN2B,YAChC,SACA,KAAK,QACL,WACF;CAGF;;;;CAKA,WAAkB,OAA8B;EAC9C,MAAM,6BAA6B;EAEnC,OADc,WAAW,OAAO,KAAK,MAC9B;CACT;AACF"}
|
package/build/types.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { AuthPackageAllow, JWTSignOptions, Logger, RemoteUser } from '@verdaccio
|
|
|
4
4
|
export interface AESPayload {
|
|
5
5
|
user: string;
|
|
6
6
|
password: string;
|
|
7
|
+
tokenKey?: string;
|
|
7
8
|
}
|
|
8
9
|
export type BasicPayload = AESPayload | void;
|
|
9
10
|
export type AuthMiddlewarePayload = RemoteUser | BasicPayload;
|
package/build/utils.d.ts
CHANGED
|
@@ -9,7 +9,9 @@ export declare function parseAuthTokenHeader(authorizationHeader: string): AuthT
|
|
|
9
9
|
export declare function parseAESCredentials(authorizationHeader: string, secret: string): string | void;
|
|
10
10
|
export declare function getMiddlewareCredentials(security: Security, secretKey: string, authorizationHeader: string): AuthMiddlewarePayload;
|
|
11
11
|
export declare function isAESLegacy(security: Security): boolean;
|
|
12
|
-
export declare function getApiToken(auth: TokenEncryption, config: Config, remoteUser: RemoteUser, aesPassword: string
|
|
12
|
+
export declare function getApiToken(auth: TokenEncryption, config: Config, remoteUser: RemoteUser, aesPassword: string, options?: {
|
|
13
|
+
tokenKey?: string;
|
|
14
|
+
}): Promise<string | void>;
|
|
13
15
|
export declare const expireReasons: string[];
|
|
14
16
|
export declare function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser;
|
|
15
17
|
export declare function isAuthHeaderValid(authorization: string): boolean;
|
|
@@ -24,5 +26,5 @@ export declare function allow_action(action: ActionsAllowed, logger: Logger): Al
|
|
|
24
26
|
*
|
|
25
27
|
*/
|
|
26
28
|
export declare function handleSpecialUnpublish(logger: Logger): any;
|
|
27
|
-
export declare function buildUser(name: string, password: string): string;
|
|
29
|
+
export declare function buildUser(name: string, password: string, tokenKey?: string): string;
|
|
28
30
|
export declare function convertPayloadToBase64(payload: string): Buffer;
|
package/build/utils.js
CHANGED
|
@@ -53,19 +53,23 @@ function isAESLegacy(security) {
|
|
|
53
53
|
const { legacy, jwt } = security.api;
|
|
54
54
|
return (0, lodash_es.isNil)(legacy) === false && (0, lodash_es.isNil)(jwt) && legacy === true;
|
|
55
55
|
}
|
|
56
|
-
async function getApiToken(auth, config, remoteUser, aesPassword) {
|
|
56
|
+
async function getApiToken(auth, config, remoteUser, aesPassword, options = {}) {
|
|
57
57
|
debug$1("get api token");
|
|
58
58
|
const { security } = config;
|
|
59
|
+
const tokenUser = options.tokenKey ? {
|
|
60
|
+
...remoteUser,
|
|
61
|
+
token: { key: options.tokenKey }
|
|
62
|
+
} : remoteUser;
|
|
59
63
|
if (isAESLegacy(security)) {
|
|
60
64
|
debug$1("security legacy enabled");
|
|
61
65
|
return await new Promise((resolve) => {
|
|
62
|
-
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword)));
|
|
66
|
+
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword, options.tokenKey)));
|
|
63
67
|
});
|
|
64
68
|
}
|
|
65
69
|
const { jwt } = security.api;
|
|
66
|
-
if (jwt?.sign) return await auth.jwtEncrypt(
|
|
70
|
+
if (jwt?.sign) return await auth.jwtEncrypt(tokenUser, jwt.sign);
|
|
67
71
|
return await new Promise((resolve) => {
|
|
68
|
-
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword)));
|
|
72
|
+
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword, options.tokenKey)));
|
|
69
73
|
});
|
|
70
74
|
}
|
|
71
75
|
var expireReasons = ["JsonWebTokenError", "TokenExpiredError"];
|
|
@@ -149,7 +153,12 @@ function handleSpecialUnpublish(logger) {
|
|
|
149
153
|
return allow_action(action, logger)(user, pkg, callback);
|
|
150
154
|
};
|
|
151
155
|
}
|
|
152
|
-
function buildUser(name, password) {
|
|
156
|
+
function buildUser(name, password, tokenKey) {
|
|
157
|
+
if (tokenKey) return JSON.stringify({
|
|
158
|
+
user: name,
|
|
159
|
+
password,
|
|
160
|
+
tokenKey
|
|
161
|
+
});
|
|
153
162
|
return String(`${name}:${password}`);
|
|
154
163
|
}
|
|
155
164
|
function convertPayloadToBase64(payload) {
|
package/build/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { isNil } from 'lodash-es';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n return aesDecrypt(token.toString(), secret);\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (typeof token === 'string' && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return isNil(legacy) === false && isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n\n if (isAESLegacy(security)) {\n debug('security legacy enabled');\n // fallback all goes to AES encryption\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(remoteUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string): string {\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;;;AAkBA,IAAM,WAAA,GAAA,MAAA,SAAmB,uBAAuB;;;;;AAMhD,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,IAAI;AAG5C,QAAO;EAAE;EAAQ;EAAO;;AAG1B,SAAgB,oBAAoB,qBAA6B,QAAgB;AAC/E,SAAM,2BAA2B;CACjC,MAAM,EAAE,QAAQ,UAAU,qBAAqB,oBAAoB;AAInE,KAAI,OAAO,aAAa,KAAK,gBAAA,YAAY,aAAa,EAAE;AACtD,UAAM,sBAAsB;AAG5B,SAFoB,uBAAuB,MAAM,CAAC,UAAU;YAGnD,OAAO,aAAa,KAAK,gBAAA,aAAa,aAAa,EAAE;AAC9D,UAAM,uBAAuB;AA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KACF,UACE,gBAAA,WAAW,aAAa,QAAQ,KAAK,qBAAqB,OAAO,WAAW,IAAI,OAAO,CACxF;MAED,UACE,gBAAA,WAAW,gBAAgB,6BAA6B,OAAO,WAAW,IAAI,OAAO,CACtF;;;;;;AAQP,SAAgB,uBAAuB,QAAqB;AAC1D,QAAO,SAAU,MAAkB,KAAuB,UAAqC;EAC7F,MAAM,SAAS;EAEf,MAAM,qBAA8B,CAAC,IAAI;AACzC,UAAM,oCAAoC,mBAAmB;EAC7D,MAAM,YAAqB,qBAAqB,QAAS,IAAI,QAAqB,SAAS;AAC3F,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAW,EAC9C,sEACD;AAED,MAAI,sBAAsB,cAAc,MACtC,QAAO,SAAS,MAAM,KAAA,EAAU;AAGlC,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;GAAW,EACtD,8EACD;AACD,SAAO,aAAa,QAAQ,OAAO,CAAC,MAAM,KAAK,SAAS;;;AAI5D,SAAgB,UAAU,MAAc,UAA0B;AAChE,QAAO,OAAO,GAAG,KAAK,GAAG,WAAW;;AAGtC,SAAgB,uBAAuB,SAAyB;AAC9D,QAAO,OAAO,KAAK,SAAS,SAAS"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { isNil } from 'lodash-es';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n return aesDecrypt(token.toString(), secret);\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (typeof token === 'string' && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return isNil(legacy) === false && isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string,\n options: { tokenKey?: string } = {}\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n const tokenUser: RemoteUser = options.tokenKey\n ? { ...remoteUser, token: { key: options.tokenKey } }\n : remoteUser;\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, options.tokenKey)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(tokenUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword, options.tokenKey)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string, tokenKey?: string): string {\n if (tokenKey) {\n return JSON.stringify({ user: name, password, tokenKey });\n }\n\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;;;AAkBA,IAAM,WAAA,GAAA,MAAA,SAAmB,sBAAsB;;;;;AAM/C,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,GAChB;CAExB,OAAO;EAAE;EAAQ;CAAM;AACzB;AAEA,SAAgB,oBAAoB,qBAA6B,QAAgB;CAC/E,QAAM,0BAA0B;CAChC,MAAM,EAAE,QAAQ,UAAU,qBAAqB,mBAAmB;CAIlE,IAAI,OAAO,YAAY,MAAM,gBAAA,YAAY,YAAY,GAAG;EACtD,QAAM,qBAAqB;EAG3B,OAFoB,uBAAuB,KAAK,EAAE,SAE3C;CACT,OAAO,IAAI,OAAO,YAAY,MAAM,gBAAA,aAAa,YAAY,GAAG;EAC9D,QAAM,sBAAsB;EAC5B,QAAA,GAAA,qBAAA,YAAkB,MAAM,SAAS,GAAG,MAAM;CAC5C;AACF;AAEA,SAAgB,yBACd,UACA,WACA,qBACuB;CACvB,QAAM,+BAA+B;CAErC,IAAI,YAAY,QAAQ,GAAG;EACzB,QAAM,WAAW;EACjB,MAAM,cAAc,oBAAoB,qBAAqB,SAAS;EACtE,IAAI,CAAC,aAAa;GAChB,QAAM,iCAAiC;GACvC;EACF;EAEA,MAAM,qBAAA,GAAA,qBAAA,mBAAsC,WAAW;EACvD,IAAI,CAAC,mBAAmB;GACtB,QAAM,+CAA+C;GACrD;EACF;EAEA,OAAO;CACT;CACA,MAAM,EAAE,QAAQ,UAAU,qBAAqB,mBAAmB;CAElE,QAAM,QAAQ;CACd,IAAI,OAAO,UAAU,YAAY,OAAO,YAAY,MAAM,gBAAA,aAAa,YAAY,GACjF,OAAO,iBAAiB,OAAO,WAAW,QAAQ;AAEtD;AAEA,SAAgB,YAAY,UAA6B;CACvD,MAAM,EAAE,QAAQ,Q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AK;GAAM,MAAM,IAAI;GAAM;EAAU,GAC7C,qEACF;EAEA,IAAI,sBAAsB,cAAc,OACtC,OAAO,SAAS,MAAM,KAAA,CAAS;EAGjC,OAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;EAAU,GACrD,6EACF;EACA,OAAO,aAAa,QAAQ,MAAM,EAAE,MAAM,KAAK,QAAQ;CACzD;AACF;AAEA,SAAgB,UAAU,MAAc,UAAkB,UAA2B;CACnF,IAAI,UACF,OAAO,KAAK,UAAU;EAAE,MAAM;EAAM;EAAU;CAAS,CAAC;CAG1D,OAAO,OAAO,GAAG,KAAK,GAAG,UAAU;AACrC;AAEA,SAAgB,uBAAuB,SAAyB;CAC9D,OAAO,OAAO,KAAK,SAAS,QAAQ;AACtC"}
|
package/build/utils.mjs
CHANGED
|
@@ -51,19 +51,23 @@ function isAESLegacy(security) {
|
|
|
51
51
|
const { legacy, jwt } = security.api;
|
|
52
52
|
return isNil(legacy) === false && isNil(jwt) && legacy === true;
|
|
53
53
|
}
|
|
54
|
-
async function getApiToken(auth, config, remoteUser, aesPassword) {
|
|
54
|
+
async function getApiToken(auth, config, remoteUser, aesPassword, options = {}) {
|
|
55
55
|
debug("get api token");
|
|
56
56
|
const { security } = config;
|
|
57
|
+
const tokenUser = options.tokenKey ? {
|
|
58
|
+
...remoteUser,
|
|
59
|
+
token: { key: options.tokenKey }
|
|
60
|
+
} : remoteUser;
|
|
57
61
|
if (isAESLegacy(security)) {
|
|
58
62
|
debug("security legacy enabled");
|
|
59
63
|
return await new Promise((resolve) => {
|
|
60
|
-
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword)));
|
|
64
|
+
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword, options.tokenKey)));
|
|
61
65
|
});
|
|
62
66
|
}
|
|
63
67
|
const { jwt } = security.api;
|
|
64
|
-
if (jwt?.sign) return await auth.jwtEncrypt(
|
|
68
|
+
if (jwt?.sign) return await auth.jwtEncrypt(tokenUser, jwt.sign);
|
|
65
69
|
return await new Promise((resolve) => {
|
|
66
|
-
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword)));
|
|
70
|
+
resolve(auth.aesEncrypt(buildUser(remoteUser.name, aesPassword, options.tokenKey)));
|
|
67
71
|
});
|
|
68
72
|
}
|
|
69
73
|
var expireReasons = ["JsonWebTokenError", "TokenExpiredError"];
|
|
@@ -147,7 +151,12 @@ function handleSpecialUnpublish(logger) {
|
|
|
147
151
|
return allow_action(action, logger)(user, pkg, callback);
|
|
148
152
|
};
|
|
149
153
|
}
|
|
150
|
-
function buildUser(name, password) {
|
|
154
|
+
function buildUser(name, password, tokenKey) {
|
|
155
|
+
if (tokenKey) return JSON.stringify({
|
|
156
|
+
user: name,
|
|
157
|
+
password,
|
|
158
|
+
tokenKey
|
|
159
|
+
});
|
|
151
160
|
return String(`${name}:${password}`);
|
|
152
161
|
}
|
|
153
162
|
function convertPayloadToBase64(payload) {
|
package/build/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { isNil } from 'lodash-es';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n return aesDecrypt(token.toString(), secret);\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (typeof token === 'string' && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return isNil(legacy) === false && isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n\n if (isAESLegacy(security)) {\n debug('security legacy enabled');\n // fallback all goes to AES encryption\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(remoteUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string): string {\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;AAkBA,IAAM,QAAQ,WAAW,uBAAuB;;;;;AAMhD,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,IAAI;AAG5C,QAAO;EAAE;EAAQ;EAAO;;AAG1B,SAAgB,oBAAoB,qBAA6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AK;GAAM;GAAa,EACpE,gGACD;AAED,MAAI,eAAe;AACjB,UAAO,MAAM,EAAE,QAAQ,KAAK,MAAM,EAAE,kDAAkD;AACtF,UAAO,SAAS,MAAM,KAAK;;AAG7B,MAAI,KACF,UACE,WAAW,aAAa,QAAQ,KAAK,qBAAqB,OAAO,WAAW,IAAI,OAAO,CACxF;MAED,UACE,WAAW,gBAAgB,6BAA6B,OAAO,WAAW,IAAI,OAAO,CACtF;;;;;;AAQP,SAAgB,uBAAuB,QAAqB;AAC1D,QAAO,SAAU,MAAkB,KAAuB,UAAqC;EAC7F,MAAM,SAAS;EAEf,MAAM,qBAA8B,CAAC,IAAI;AACzC,QAAM,oCAAoC,mBAAmB;EAC7D,MAAM,YAAqB,qBAAqB,QAAS,IAAI,QAAqB,SAAS;AAC3F,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAW,EAC9C,sEACD;AAED,MAAI,sBAAsB,cAAc,MACtC,QAAO,SAAS,MAAM,KAAA,EAAU;AAGlC,SAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;GAAW,EACtD,8EACD;AACD,SAAO,aAAa,QAAQ,OAAO,CAAC,MAAM,KAAK,SAAS;;;AAI5D,SAAgB,UAAU,MAAc,UAA0B;AAChE,QAAO,OAAO,GAAG,KAAK,GAAG,WAAW;;AAGtC,SAAgB,uBAAuB,SAAyB;AAC9D,QAAO,OAAO,KAAK,SAAS,SAAS"}
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { isNil } from 'lodash-es';\n\nimport { createAnonymousRemoteUser } from '@verdaccio/config';\nimport type { pluginUtils } from '@verdaccio/core';\nimport { API_ERROR, HTTP_STATUS, TOKEN_BASIC, TOKEN_BEARER, errorUtils } from '@verdaccio/core';\nimport { aesDecrypt, parseBasicPayload, verifyPayload } from '@verdaccio/signature';\nimport type { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';\n\nimport type {\n ActionsAllowed,\n AllowAction,\n AllowActionCallback,\n AuthMiddlewarePayload,\n AuthTokenHeader,\n TokenEncryption,\n} from './types';\n\nconst debug = buildDebug('verdaccio:auth:utils');\n\n/**\n * Split authentication header eg: Bearer [secret_token]\n * @param authorizationHeader auth token\n */\nexport function parseAuthTokenHeader(authorizationHeader: string): AuthTokenHeader {\n const parts = authorizationHeader.split(' ');\n const [scheme, token] = parts;\n\n return { scheme, token };\n}\n\nexport function parseAESCredentials(authorizationHeader: string, secret: string) {\n debug('parseAESCredentials init');\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n // basic is deprecated and should not be enforced\n // basic is currently being used for functional test\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('legacy header basic');\n const credentials = convertPayloadToBase64(token).toString();\n\n return credentials;\n } else if (scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n debug('legacy header bearer');\n return aesDecrypt(token.toString(), secret);\n }\n}\n\nexport function getMiddlewareCredentials(\n security: Security,\n secretKey: string,\n authorizationHeader: string\n): AuthMiddlewarePayload {\n debug('getMiddlewareCredentials init');\n // comment out for debugging purposes\n if (isAESLegacy(security)) {\n debug('is legacy');\n const credentials = parseAESCredentials(authorizationHeader, secretKey);\n if (!credentials) {\n debug('parse legacy credentials failed');\n return;\n }\n\n const parsedCredentials = parseBasicPayload(credentials);\n if (!parsedCredentials) {\n debug('parse legacy basic payload credentials failed');\n return;\n }\n\n return parsedCredentials;\n }\n const { scheme, token } = parseAuthTokenHeader(authorizationHeader);\n\n debug('is jwt');\n if (typeof token === 'string' && scheme.toUpperCase() === TOKEN_BEARER.toUpperCase()) {\n return verifyJWTPayload(token, secretKey, security);\n }\n}\n\nexport function isAESLegacy(security: Security): boolean {\n const { legacy, jwt } = security.api;\n\n return isNil(legacy) === false && isNil(jwt) && legacy === true;\n}\n\nexport async function getApiToken(\n auth: TokenEncryption,\n config: Config,\n remoteUser: RemoteUser,\n aesPassword: string,\n options: { tokenKey?: string } = {}\n): Promise<string | void> {\n debug('get api token');\n const { security } = config;\n const tokenUser: RemoteUser = options.tokenKey\n ? { ...remoteUser, token: { key: options.tokenKey } }\n : remoteUser;\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, options.tokenKey)));\n });\n }\n const { jwt } = security.api;\n\n if (jwt?.sign) {\n return await auth.jwtEncrypt(tokenUser, jwt.sign);\n }\n return await new Promise((resolve): void => {\n resolve(auth.aesEncrypt(buildUser(remoteUser.name as string, aesPassword, options.tokenKey)));\n });\n}\n\nexport const expireReasons: string[] = ['JsonWebTokenError', 'TokenExpiredError'];\n\nexport function verifyJWTPayload(token: string, secret: string, security: Security): RemoteUser {\n try {\n const payload: RemoteUser = verifyPayload(\n token,\n secret,\n security?.api?.jwt?.verify as Parameters<typeof verifyPayload>[2]\n );\n\n return payload;\n } catch (error: any) {\n // #168 this check should be removed as soon AES encrypt is removed.\n if (expireReasons.includes(error.name)) {\n // it might be possible the jwt configuration is enabled and\n // old tokens fails still remains in usage, thus\n // we return an anonymous user to force log in.\n return createAnonymousRemoteUser();\n }\n throw errorUtils.getCode(HTTP_STATUS.UNAUTHORIZED, error.message);\n }\n}\n\nexport function isAuthHeaderValid(authorization: string): boolean {\n return authorization.split(' ').length === 2;\n}\n\n/**\n * Return a default configuration for authentication if none is provided.\n * @param logger {Logger}\n * @returns object of default implementations.\n */\nexport function getDefaultPluginMethods(logger: Logger): pluginUtils.Auth<Config> {\n return {\n authenticate(_user: string, _password: string, cb: pluginUtils.AuthCallback): void {\n debug('triggered default authenticate method');\n cb(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n },\n\n adduser(_user: string, _password: string, cb: pluginUtils.AuthUserCallback): void {\n debug('triggered default adduser method');\n // since adduser is not implemented but optional, continue without error\n // this assumes that the user is added by an external system\n cb(null, true);\n },\n\n // @ts-ignore\n allow_access: allow_action('access', logger),\n // @ts-ignore\n allow_publish: allow_action('publish', logger),\n allow_unpublish: handleSpecialUnpublish(logger),\n };\n}\n\nexport function allow_action(action: ActionsAllowed, logger: Logger): AllowAction {\n return function allowActionCallback(\n user: RemoteUser,\n pkg: AuthPackageAllow,\n callback: AllowActionCallback\n ): void {\n logger.trace({ remote: user.name }, `[auth/allow_action]: user: @{remote}`);\n const { name, groups } = user;\n debug('allow_action \"%s\": groups %s', action, groups);\n const groupAccess = pkg[action] as string[];\n debug('allow_action \"%s\": groupAccess %s', action, groupAccess);\n const hasPermission = groupAccess.some((group) => {\n return name === group || groups.includes(group);\n });\n debug('package \"%s\" has permission \"%s\"', name, hasPermission);\n logger.trace(\n { pkgName: pkg.name, hasPermission, remote: user.name, groupAccess },\n `[auth/allow_action]: hasPermission? @{hasPermission} for user: @{remote}, package: @{pkgName}`\n );\n\n if (hasPermission) {\n logger.trace({ remote: user.name }, `auth/allow_action: access granted to: @{remote}`);\n return callback(null, true);\n }\n\n if (name) {\n callback(\n errorUtils.getForbidden(`user ${name} is not allowed to ${action} package ${pkg.name}`)\n );\n } else {\n callback(\n errorUtils.getUnauthorized(`authorization required to ${action} package ${pkg.name}`)\n );\n }\n };\n}\n\n/**\n *\n */\nexport function handleSpecialUnpublish(logger: Logger): any {\n return function (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback): void {\n const action = 'unpublish';\n // verify whether the unpublish prop has been defined\n const isUnpublishMissing: boolean = !pkg[action];\n debug('is unpublish method missing ? %s', isUnpublishMissing);\n const hasGroups: boolean = isUnpublishMissing ? false : (pkg[action] as string[]).length > 0;\n logger.trace(\n { user: user.name, name: pkg.name, hasGroups },\n `fallback unpublish for @{name} has groups: @{hasGroups} for @{user}`\n );\n\n if (isUnpublishMissing || hasGroups === false) {\n return callback(null, undefined);\n }\n\n logger.trace(\n { user: user.name, name: pkg.name, action, hasGroups },\n `allow_action for @{action} for @{name} has groups: @{hasGroups} for @{user}`\n );\n return allow_action(action, logger)(user, pkg, callback);\n };\n}\n\nexport function buildUser(name: string, password: string, tokenKey?: string): string {\n if (tokenKey) {\n return JSON.stringify({ user: name, password, tokenKey });\n }\n\n return String(`${name}:${password}`);\n}\n\nexport function convertPayloadToBase64(payload: string): Buffer {\n return Buffer.from(payload, 'base64');\n}\n"],"mappings":";;;;;;AAkBA,IAAM,QAAQ,WAAW,sBAAsB;;;;;AAM/C,SAAgB,qBAAqB,qBAA8C;CAEjF,MAAM,CAAC,QAAQ,SADD,oBAAoB,MAAM,GAChB;CAExB,OAAO;EAAE;EAAQ;CAAM;AACzB;AAEA,SAAgB,oBAAoB,qBAA6B,QAAgB;CAC/E,MAAM,0BAA0B;CAChC,MAAM,EAAE,QAAQ,UAAU,qBAAqB,mBAAmB;CAIlE,IAAI,OAAO,YAAY,MAAM,YAAY,YAAY,GAAG;EACtD,MAAM,qBAAqB;EAG3B,OAFoB,uBAAuB,KAAK,EAAE,SAE3C;CACT,OAAO,IAAI,OAAO,YAAY,MAAM,aAAa,YAAY,GAAG;EAC9D,MAAM,sBAAsB;EAC5B,OAAO,WAAW,MAAM,SAAS,GAAG,MAAM;CAC5C;AACF;AAEA,SAAgB,yBACd,UACA,WACA,qBACuB;CACvB,MAAM,+BAA+B;CAErC,IAAI,YAAY,QAAQ,GAAG;EACzB,MAAM,WAAW;EACjB,MAAM,cAAc,oBAAoB,qBAAqB,SAAS;EACtE,IAAI,CAAC,aAAa;GAChB,MAAM,iCAAiC;GACvC;EACF;EAEA,MAAM,oBAAoB,kBAAkB,WAAW;EACvD,IAAI,CAAC,mBAAmB;GACtB,MAAM,+CAA+C;GACrD;EACF;EAEA,OAAO;CACT;CACA,MAAM,EAAE,QAAQ,UAAU,qBAAqB,mBAAmB;CAElE,MAAM,QAAQ;CACd,IAAI,OAAO,UAAU,YAAY,OAAO,YAAY,MAAM,aAAa,YAAY,GACjF,OAAO,iBAAiB,OAAO,W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AI;GAAM;EAAU,GAC7C,qEACF;EAEA,IAAI,sBAAsB,cAAc,OACtC,OAAO,SAAS,MAAM,KAAA,CAAS;EAGjC,OAAO,MACL;GAAE,MAAM,KAAK;GAAM,MAAM,IAAI;GAAM;GAAQ;EAAU,GACrD,6EACF;EACA,OAAO,aAAa,QAAQ,MAAM,EAAE,MAAM,KAAK,QAAQ;CACzD;AACF;AAEA,SAAgB,UAAU,MAAc,UAAkB,UAA2B;CACnF,IAAI,UACF,OAAO,KAAK,UAAU;EAAE,MAAM;EAAM;EAAU;CAAS,CAAC;CAG1D,OAAO,OAAO,GAAG,KAAK,GAAG,UAAU;AACrC;AAEA,SAAgB,uBAAuB,SAAyB;CAC9D,OAAO,OAAO,KAAK,SAAS,QAAQ;AACtC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@verdaccio/auth",
|
|
3
|
-
"version": "9.0.0-next-9.
|
|
3
|
+
"version": "9.0.0-next-9.18",
|
|
4
4
|
"description": "Verdaccio Authentication",
|
|
5
5
|
"main": "./build/index.js",
|
|
6
6
|
"types": "./build/index.d.ts",
|
|
@@ -33,23 +33,23 @@
|
|
|
33
33
|
},
|
|
34
34
|
"license": "MIT",
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@verdaccio/config": "9.0.0-next-9.
|
|
37
|
-
"@verdaccio/core": "9.0.0-next-9.
|
|
38
|
-
"@verdaccio/loaders": "9.0.0-next-9.
|
|
39
|
-
"@verdaccio/signature": "9.0.0-next-9.
|
|
36
|
+
"@verdaccio/config": "9.0.0-next-9.18",
|
|
37
|
+
"@verdaccio/core": "9.0.0-next-9.18",
|
|
38
|
+
"@verdaccio/loaders": "9.0.0-next-9.18",
|
|
39
|
+
"@verdaccio/signature": "9.0.0-next-9.18",
|
|
40
40
|
"debug": "4.4.3",
|
|
41
41
|
"lodash-es": "4.18.1",
|
|
42
|
-
"verdaccio-htpasswd": "14.0.0-next-9.
|
|
42
|
+
"verdaccio-htpasswd": "14.0.0-next-9.18"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@verdaccio/middleware": "9.0.0-next-9.17",
|
|
46
|
-
"@verdaccio/types": "14.0.0-next-9.8",
|
|
47
|
-
"@verdaccio/logger": "9.0.0-next-9.17",
|
|
48
|
-
"verdaccio-htpasswd": "14.0.0-next-9.17",
|
|
49
45
|
"@types/lodash-es": "4.17.12",
|
|
46
|
+
"@verdaccio/logger": "9.0.0-next-9.18",
|
|
47
|
+
"@verdaccio/middleware": "9.0.0-next-9.18",
|
|
48
|
+
"@verdaccio/types": "14.0.0-next-9.9",
|
|
50
49
|
"express": "5.2.1",
|
|
51
50
|
"supertest": "7.1.4",
|
|
52
|
-
"
|
|
51
|
+
"verdaccio-htpasswd": "14.0.0-next-9.18",
|
|
52
|
+
"vitest": "4.1.7"
|
|
53
53
|
},
|
|
54
54
|
"funding": {
|
|
55
55
|
"type": "opencollective",
|