@verdaccio/auth 6.0.0-6-next.30 → 6.0.0-6-next.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/build/auth.d.ts +3 -3
- package/build/auth.js +19 -115
- package/build/auth.js.map +1 -1
- package/build/index.js +0 -9
- package/build/index.js.map +1 -1
- package/build/jwt-token.js +2 -7
- package/build/jwt-token.js.map +1 -1
- package/build/legacy-token.js +15 -23
- package/build/legacy-token.js.map +1 -1
- package/build/token.js +0 -3
- package/build/token.js.map +1 -1
- package/build/utils.d.ts +6 -6
- package/build/utils.js +11 -50
- package/build/utils.js.map +1 -1
- package/package.json +7 -7
package/build/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","names":["debug","buildDebug","Auth","constructor","config","secret","plugins","TypeError","init","loadPlugin","length","loadDefaultPlugin","_applyDefaultPlugins","pluginOptions","logger","authPlugin","HTPasswd","file","error","info","asyncLoadPlugin","auth","plugin","authenticate","allow_access","allow_publish","serverSettings","pluginPrefix","push","getDefaultPlugins","changePassword","username","password","newPassword","cb","validPlugins","_","filter","isFunction","isEmpty","errorUtils","getInternalError","SUPPORT_ERRORS","PLUGIN_MISSING_INTERFACE","isNil","err","profile","invalidateToken","token","console","log","Promise","resolve","slice","next","shift","groups","message","isString","isGroupValid","isArray","API_ERROR","BAD_FORMAT_USER_GROUP","createRemoteUser","add_user","user","self","adduser","ok","packageName","packageVersion","callback","pkgAllowAccess","name","version","pkg","Object","assign","getMatchedPackagesSpec","packages","allow_unpublish","arguments","isError","apiJWTmiddleware","helpers","createAnonymousRemoteUser","req","res","_next","pause","resume","remote_user","_isRemoteUserValid","remoteUser","locals","authorization","headers","isAuthHeaderValid","getBadRequest","BAD_AUTH_HEADER","security","isAESLegacy","_handleAESMiddleware","_handleJWTAPIMiddleware","scheme","parseAuthTokenHeader","toUpperCase","TOKEN_BASIC","credentials","convertPayloadToBase64","toString","parseBasicPayload","getMiddlewareCredentials","getForbidden","BAD_USERNAME_PASSWORD","isUndefined","webUIJWTmiddleware","status","statusCode","send","replace","TOKEN_BEARER","verifyJWTPayload","jwtEncrypt","signOptions","real_groups","realGroupsValidated","groupedGroups","Array","from","Set","concat","payload","signPayload","aesEncrypt","value"],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { NextFunction, Request, RequestHandler, Response } from 'express';\nimport _ from 'lodash';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport {\n API_ERROR,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n VerdaccioError,\n errorUtils,\n pluginUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { logger } from '@verdaccio/logger';\nimport {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\nimport { getMatchedPackagesSpec, isFunction, isNil } from '@verdaccio/utils';\n\nimport { signPayload } from './jwt-token';\nimport { aesEncrypt } from './legacy-token';\nimport { parseBasicPayload } from './token';\nimport {\n convertPayloadToBase64,\n getDefaultPlugins,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nexport interface TokenEncryption {\n jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string>;\n aesEncrypt(buf: string): string | void;\n}\n\nexport interface AESPayload {\n user: string;\n password: string;\n}\nexport interface IAuthMiddleware {\n apiJWTmiddleware(): $NextFunctionVer;\n webUIJWTmiddleware(): $NextFunctionVer;\n}\n\nexport type $RequestExtend = Request & { remote_user?: any; log: Logger };\nexport type $ResponseExtend = Response & { cookies?: any };\nexport type $NextFunctionVer = NextFunction & any;\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public plugins: pluginUtils.Auth<Config>[];\n\n public constructor(config: Config) {\n this.config = config;\n this.secret = config.secret;\n this.plugins = [];\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = (await this.loadPlugin()) as pluginUtils.Auth<unknown>[];\n debug('auth plugins found %s', plugins.length);\n if (!plugins || plugins.length === 0) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this._applyDefaultPlugins();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n const pluginOptions: pluginUtils.PluginOptions = {\n config: this.config,\n logger,\n };\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n pluginOptions as any as pluginUtils.PluginOptions\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<unknown>>(\n this.config.auth,\n {\n config: this.config,\n logger,\n },\n (plugin): boolean => {\n const { authenticate, allow_access, allow_publish } = plugin;\n\n return (\n typeof authenticate !== 'undefined' ||\n typeof allow_access !== 'undefined' ||\n typeof allow_publish !== 'undefined'\n );\n },\n this.config?.serverSettings?.pluginPrefix\n );\n }\n\n private _applyDefaultPlugins(): void {\n // TODO: rename to applyFallbackPluginMethods\n this.plugins.push(getDefaultPlugins(logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = _.filter(this.plugins, (plugin) => isFunction(plugin.changePassword));\n\n if (_.isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || isFunction(plugin.changePassword) === false) {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift() as pluginUtils.Auth<Config>;\n\n if (isFunction(plugin.authenticate) === false) {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (_.isString(groups)) {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = _.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n const plugin = plugins.shift() as pluginUtils.Auth<Config>;\n if (typeof plugin.adduser !== 'function') {\n next();\n } else {\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n throw errorUtils.getInternalError(\n 'add_user method not longer supported, rename to adduser'\n );\n }\n\n plugin.adduser(\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not being added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkgAllowAccess: AllowAccess = { name: packageName, version: packageVersion };\n const pkg = Object.assign(\n {},\n pkgAllowAccess,\n getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n debug('allow access for %o', packageName);\n\n (function next(): void {\n const plugin: pluginUtils.Auth<unknown> = plugins.shift() as pluginUtils.Auth<unknown>;\n\n if (_.isNil(plugin) || isFunction(plugin.allow_access) === false) {\n return next();\n }\n\n plugin.allow_access!(user, pkg, function (err: VerdaccioError | null, ok?: boolean): void {\n if (err) {\n debug('forbidden access for %o. Error: %o', packageName, err?.message);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed access for %o', packageName);\n return callback(null, ok);\n }\n\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n getMatchedPackagesSpec(packageName, this.config.packages)\n );\n debug('allow unpublish for %o', packageName);\n\n for (const plugin of this.plugins) {\n if (_.isNil(plugin) || isFunction(plugin.allow_unpublish) === false) {\n debug('allow unpublish for %o plugin does not implement allow_unpublish', packageName);\n continue;\n } else {\n // @ts-ignore\n plugin.allow_unpublish!(user, pkg, (err, ok: boolean): void => {\n if (err) {\n debug(\n 'forbidden publish for %o, it will fallback on unpublish permissions',\n packageName\n );\n return callback(err);\n }\n\n if (_.isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n // @ts-ignore\n // eslint-disable-next-line\n return this.allow_publish(...arguments);\n }\n\n if (ok) {\n debug('allowed unpublish for %o', packageName);\n return callback(null, ok);\n }\n });\n }\n }\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n getMatchedPackagesSpec(packageName, this.config.packages)\n ) as any;\n debug('allow publish for %o init | plugins: %o', packageName, plugins.length);\n\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('allow publish for %o plugin does not implement allow_publish', packageName);\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (_.isNil(err) === false && _.isError(err)) {\n debug('forbidden publish for %o', packageName);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed publish for %o', packageName);\n return callback(null, ok);\n }\n\n debug('allow publish skip validation for %o', packageName);\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public apiJWTmiddleware(): RequestHandler {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n // @ts-ignore\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n\n const next = function (err?: VerdaccioError): any {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next();\n };\n\n if (this._isRemoteUserValid(req.remote_user)) {\n debug('jwt has a valid authentication header');\n return next();\n }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this._handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this._handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private _handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const { user, password } = parseBasicPayload(credentials) as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private _handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware secret %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return _.isUndefined(remote_user) === false && _.isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware(): RequestHandler {\n // @ts-ignore\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n // req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret);\n } catch (err: any) {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = _.isNil(real_groups) ? [] : real_groups;\n const groupedGroups = _.isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n\n const token: string = await signPayload(payload, this.secret, signOptions);\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n return aesEncrypt(value, this.secret);\n }\n}\n\nexport { Auth };\n"],"mappings":";;;;;;;AAAA;;AAEA;;AACA;;AAEA;;AACA;;AASA;;AACA;;AAWA;;AAEA;;AACA;;AACA;;AACA;;;;AAUA,MAAMA,KAAK,GAAG,IAAAC,cAAA,EAAW,gBAAX,CAAd;;AAoBA,MAAMC,IAAN,CAA+E;EAKtEC,WAAW,CAACC,MAAD,EAAiB;IACjC,KAAKA,MAAL,GAAcA,MAAd;IACA,KAAKC,MAAL,GAAcD,MAAM,CAACC,MAArB;IACA,KAAKC,OAAL,GAAe,EAAf;;IACA,IAAI,CAAC,KAAKD,MAAV,EAAkB;MAChB,MAAM,IAAIE,SAAJ,CAAc,0DAAd,CAAN;IACD;EACF;;EAEgB,MAAJC,IAAI,GAAG;IAClB,IAAIF,OAAO,GAAI,MAAM,KAAKG,UAAL,EAArB;IACAT,KAAK,CAAC,uBAAD,EAA0BM,OAAO,CAACI,MAAlC,CAAL;;IACA,IAAI,CAACJ,OAAD,IAAYA,OAAO,CAACI,MAAR,KAAmB,CAAnC,EAAsC;MACpCJ,OAAO,GAAG,KAAKK,iBAAL,EAAV;IACD;;IACD,KAAKL,OAAL,GAAeA,OAAf;;IAEA,KAAKM,oBAAL;EACD;;EAEOD,iBAAiB,GAAG;IAC1BX,KAAK,CAAC,0BAAD,CAAL;IACA,MAAMa,aAAwC,GAAG;MAC/CT,MAAM,EAAE,KAAKA,MADkC;MAE/CU,MAAM,EAANA;IAF+C,CAAjD;IAIA,IAAIC,UAA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O5E,KAAP;EACD;EAED;AACF;AACA;;;EACSsF,UAAU,CAACC,KAAD,EAA+B;IAC9C,OAAO,IAAAD,uBAAA,EAAWC,KAAX,EAAkB,KAAKlI,MAAvB,CAAP;EACD;;AArhB4E"}
|
|
1
|
+
{"version":3,"file":"auth.js","names":["debug","buildDebug","Auth","constructor","config","secret","plugins","TypeError","init","loadPlugin","length","loadDefaultPlugin","_applyDefaultPlugins","pluginOptions","logger","authPlugin","HTPasswd","file","error","info","asyncLoadPlugin","auth","plugin","authenticate","allow_access","allow_publish","serverSettings","pluginPrefix","push","getDefaultPlugins","changePassword","username","password","newPassword","cb","validPlugins","_","filter","isFunction","isEmpty","errorUtils","getInternalError","SUPPORT_ERRORS","PLUGIN_MISSING_INTERFACE","isNil","err","profile","invalidateToken","token","console","log","Promise","resolve","slice","next","shift","groups","message","isString","isGroupValid","isArray","API_ERROR","BAD_FORMAT_USER_GROUP","createRemoteUser","add_user","user","self","adduser","ok","packageName","packageVersion","callback","pkgAllowAccess","name","version","pkg","Object","assign","getMatchedPackagesSpec","packages","allow_unpublish","arguments","isError","apiJWTmiddleware","helpers","createAnonymousRemoteUser","req","res","_next","pause","resume","remote_user","_isRemoteUserValid","remoteUser","locals","authorization","headers","isAuthHeaderValid","getBadRequest","BAD_AUTH_HEADER","security","isAESLegacy","_handleAESMiddleware","_handleJWTAPIMiddleware","scheme","parseAuthTokenHeader","toUpperCase","TOKEN_BASIC","credentials","convertPayloadToBase64","toString","parseBasicPayload","getMiddlewareCredentials","getForbidden","BAD_USERNAME_PASSWORD","isUndefined","webUIJWTmiddleware","status","statusCode","send","replace","TOKEN_BEARER","verifyJWTPayload","jwtEncrypt","signOptions","real_groups","realGroupsValidated","groupedGroups","Array","from","Set","concat","payload","signPayload","aesEncrypt","value"],"sources":["../src/auth.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { NextFunction, Request, RequestHandler, Response } from 'express';\nimport _ from 'lodash';\nimport { HTPasswd } from 'verdaccio-htpasswd';\n\nimport { createAnonymousRemoteUser, createRemoteUser } from '@verdaccio/config';\nimport {\n API_ERROR,\n SUPPORT_ERRORS,\n TOKEN_BASIC,\n TOKEN_BEARER,\n VerdaccioError,\n errorUtils,\n pluginUtils,\n} from '@verdaccio/core';\nimport { asyncLoadPlugin } from '@verdaccio/loaders';\nimport { logger } from '@verdaccio/logger';\nimport {\n AllowAccess,\n Callback,\n Config,\n JWTSignOptions,\n Logger,\n PackageAccess,\n RemoteUser,\n Security,\n} from '@verdaccio/types';\nimport { getMatchedPackagesSpec, isFunction, isNil } from '@verdaccio/utils';\n\nimport { signPayload } from './jwt-token';\nimport { aesEncrypt } from './legacy-token';\nimport { parseBasicPayload } from './token';\nimport {\n convertPayloadToBase64,\n getDefaultPlugins,\n getMiddlewareCredentials,\n isAESLegacy,\n isAuthHeaderValid,\n parseAuthTokenHeader,\n verifyJWTPayload,\n} from './utils';\n\nconst debug = buildDebug('verdaccio:auth');\n\nexport interface TokenEncryption {\n jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string>;\n aesEncrypt(buf: string): string | void;\n}\n\nexport interface AESPayload {\n user: string;\n password: string;\n}\nexport interface IAuthMiddleware {\n apiJWTmiddleware(): $NextFunctionVer;\n webUIJWTmiddleware(): $NextFunctionVer;\n}\n\nexport type $RequestExtend = Request & { remote_user?: any; log: Logger };\nexport type $ResponseExtend = Response & { cookies?: any };\nexport type $NextFunctionVer = NextFunction & any;\n\nclass Auth implements IAuthMiddleware, TokenEncryption, pluginUtils.IBasicAuth {\n public config: Config;\n public secret: string;\n public plugins: pluginUtils.Auth<Config>[];\n\n public constructor(config: Config) {\n this.config = config;\n this.secret = config.secret;\n this.plugins = [];\n if (!this.secret) {\n throw new TypeError('secret it is required value on initialize the auth class');\n }\n }\n\n public async init() {\n let plugins = (await this.loadPlugin()) as pluginUtils.Auth<unknown>[];\n debug('auth plugins found %s', plugins.length);\n if (!plugins || plugins.length === 0) {\n plugins = this.loadDefaultPlugin();\n }\n this.plugins = plugins;\n\n this._applyDefaultPlugins();\n }\n\n private loadDefaultPlugin() {\n debug('load default auth plugin');\n const pluginOptions: pluginUtils.PluginOptions = {\n config: this.config,\n logger,\n };\n let authPlugin;\n try {\n authPlugin = new HTPasswd(\n { file: './htpasswd' },\n pluginOptions as any as pluginUtils.PluginOptions\n );\n } catch (error: any) {\n debug('error on loading auth htpasswd plugin stack: %o', error);\n logger.info({}, 'no auth plugin has been found');\n return [];\n }\n\n return [authPlugin];\n }\n\n private async loadPlugin() {\n return asyncLoadPlugin<pluginUtils.Auth<unknown>>(\n this.config.auth,\n {\n config: this.config,\n logger,\n },\n (plugin): boolean => {\n const { authenticate, allow_access, allow_publish } = plugin;\n\n return (\n typeof authenticate !== 'undefined' ||\n typeof allow_access !== 'undefined' ||\n typeof allow_publish !== 'undefined'\n );\n },\n this.config?.serverSettings?.pluginPrefix\n );\n }\n\n private _applyDefaultPlugins(): void {\n // TODO: rename to applyFallbackPluginMethods\n this.plugins.push(getDefaultPlugins(logger));\n }\n\n public changePassword(\n username: string,\n password: string,\n newPassword: string,\n cb: Callback\n ): void {\n const validPlugins = _.filter(this.plugins, (plugin) => isFunction(plugin.changePassword));\n\n if (_.isEmpty(validPlugins)) {\n return cb(errorUtils.getInternalError(SUPPORT_ERRORS.PLUGIN_MISSING_INTERFACE));\n }\n\n for (const plugin of validPlugins) {\n if (isNil(plugin) || isFunction(plugin.changePassword) === false) {\n debug('auth plugin does not implement changePassword, trying next one');\n continue;\n } else {\n debug('updating password for %o', username);\n plugin.changePassword!(username, password, newPassword, (err, profile): void => {\n if (err) {\n logger.error(\n { username, err },\n `An error has been produced\n updating the password for @{username}. Error: @{err.message}`\n );\n return cb(err);\n }\n\n debug('updated password for %o was successful', username);\n return cb(null, profile);\n });\n }\n }\n }\n\n public async invalidateToken(token: string) {\n // eslint-disable-next-line no-console\n console.log('invalidate token pending to implement', token);\n return Promise.resolve();\n }\n\n public authenticate(\n username: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const plugins = this.plugins.slice(0);\n (function next(): void {\n const plugin = plugins.shift() as pluginUtils.Auth<Config>;\n\n if (isFunction(plugin.authenticate) === false) {\n return next();\n }\n\n debug('authenticating %o', username);\n plugin.authenticate(username, password, function (err: VerdaccioError | null, groups): void {\n if (err) {\n debug('authenticating for user %o failed. Error: %o', username, err?.message);\n return cb(err);\n }\n\n // Expect: SKIP if groups is falsey and not an array\n // with at least one item (truthy length)\n // Expect: CONTINUE otherwise (will error if groups is not\n // an array, but this is current behavior)\n // Caveat: STRING (if valid) will pass successfully\n // bug give unexpected results\n // Info: Cannot use `== false to check falsey values`\n if (!!groups && groups.length !== 0) {\n // TODO: create a better understanding of expectations\n if (_.isString(groups)) {\n throw new TypeError('plugin group error: invalid type for function');\n }\n const isGroupValid: boolean = _.isArray(groups);\n if (!isGroupValid) {\n throw new TypeError(API_ERROR.BAD_FORMAT_USER_GROUP);\n }\n\n debug('authentication for user %o was successfully. Groups: %o', username, groups);\n return cb(err, createRemoteUser(username, groups));\n }\n next();\n });\n })();\n }\n\n public add_user(\n user: string,\n password: string,\n cb: (error: VerdaccioError | null, user?: RemoteUser) => void\n ): void {\n const self = this;\n const plugins = this.plugins.slice(0);\n debug('add user %o', user);\n\n (function next(): void {\n const plugin = plugins.shift() as pluginUtils.Auth<Config>;\n if (typeof plugin.adduser !== 'function') {\n next();\n } else {\n // @ts-expect-error future major (7.x) should remove this section\n if (typeof plugin.adduser === 'undefined' && typeof plugin.add_user === 'function') {\n throw errorUtils.getInternalError(\n 'add_user method not longer supported, rename to adduser'\n );\n }\n\n plugin.adduser(\n user,\n password,\n function (err: VerdaccioError | null, ok?: boolean | string): void {\n if (err) {\n debug('the user %o could not being added. Error: %o', user, err?.message);\n return cb(err);\n }\n if (ok) {\n debug('the user %o has been added', user);\n return self.authenticate(user, password, cb);\n }\n next();\n }\n );\n }\n })();\n }\n\n /**\n * Allow user to access a package.\n */\n public allow_access(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: pluginUtils.AccessCallback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkgAllowAccess: AllowAccess = { name: packageName, version: packageVersion };\n const pkg = Object.assign(\n {},\n pkgAllowAccess,\n getMatchedPackagesSpec(packageName, this.config.packages)\n ) as AllowAccess & PackageAccess;\n debug('allow access for %o', packageName);\n\n (function next(): void {\n const plugin: pluginUtils.Auth<unknown> = plugins.shift() as pluginUtils.Auth<unknown>;\n\n if (_.isNil(plugin) || isFunction(plugin.allow_access) === false) {\n return next();\n }\n\n plugin.allow_access!(user, pkg, function (err: VerdaccioError | null, ok?: boolean): void {\n if (err) {\n debug('forbidden access for %o. Error: %o', packageName, err?.message);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed access for %o', packageName);\n return callback(null, ok);\n }\n\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public allow_unpublish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n getMatchedPackagesSpec(packageName, this.config.packages)\n );\n debug('allow unpublish for %o', packageName);\n\n for (const plugin of this.plugins) {\n if (_.isNil(plugin) || isFunction(plugin.allow_unpublish) === false) {\n debug('allow unpublish for %o plugin does not implement allow_unpublish', packageName);\n continue;\n } else {\n // @ts-ignore\n plugin.allow_unpublish!(user, pkg, (err, ok: boolean): void => {\n if (err) {\n debug(\n 'forbidden publish for %o, it will fallback on unpublish permissions',\n packageName\n );\n return callback(err);\n }\n\n if (_.isNil(ok) === true) {\n debug('bypass unpublish for %o, publish will handle the access', packageName);\n // @ts-ignore\n // eslint-disable-next-line\n return this.allow_publish(...arguments);\n }\n\n if (ok) {\n debug('allowed unpublish for %o', packageName);\n return callback(null, ok);\n }\n });\n }\n }\n }\n\n /**\n * Allow user to publish a package.\n */\n public allow_publish(\n { packageName, packageVersion }: pluginUtils.AuthPluginPackage,\n user: RemoteUser,\n callback: Callback\n ): void {\n const plugins = this.plugins.slice(0);\n const pkg = Object.assign(\n { name: packageName, version: packageVersion },\n getMatchedPackagesSpec(packageName, this.config.packages)\n ) as any;\n debug('allow publish for %o init | plugins: %o', packageName, plugins.length);\n\n (function next(): void {\n const plugin = plugins.shift();\n\n if (typeof plugin?.allow_publish !== 'function') {\n debug('allow publish for %o plugin does not implement allow_publish', packageName);\n return next();\n }\n\n plugin.allow_publish(user, pkg, (err: VerdaccioError | null, ok?: boolean): void => {\n if (_.isNil(err) === false && _.isError(err)) {\n debug('forbidden publish for %o', packageName);\n return callback(err);\n }\n\n if (ok) {\n debug('allowed publish for %o', packageName);\n return callback(null, ok);\n }\n\n debug('allow publish skip validation for %o', packageName);\n next(); // cb(null, false) causes next plugin to roll\n });\n })();\n }\n\n public apiJWTmiddleware(): RequestHandler {\n debug('jwt middleware');\n const plugins = this.plugins.slice(0);\n const helpers = { createAnonymousRemoteUser, createRemoteUser };\n for (const plugin of plugins) {\n if (plugin.apiJWTmiddleware) {\n return plugin.apiJWTmiddleware(helpers);\n }\n }\n\n // @ts-ignore\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction) => {\n req.pause();\n\n const next = function (err?: VerdaccioError): any {\n req.resume();\n // uncomment this to reject users with bad auth headers\n // return _next.apply(null, arguments)\n // swallow error, user remains unauthorized\n // set remoteUserError to indicate that user was attempting authentication\n if (err) {\n req.remote_user.error = err.message;\n }\n\n return _next();\n };\n\n if (this._isRemoteUserValid(req.remote_user)) {\n debug('jwt has a valid authentication header');\n return next();\n }\n\n // in case auth header does not exist we return anonymous function\n const remoteUser = createAnonymousRemoteUser();\n req.remote_user = remoteUser;\n res.locals.remote_user = remoteUser;\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n debug('jwt, authentication header is missing');\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n debug('api middleware authentication heather is invalid');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n const { secret, security } = this.config;\n\n if (isAESLegacy(security)) {\n debug('api middleware using legacy auth token');\n this._handleAESMiddleware(req, security, secret, authorization, next);\n } else {\n debug('api middleware using JWT auth token');\n this._handleJWTAPIMiddleware(req, security, secret, authorization, next);\n }\n };\n }\n\n private _handleJWTAPIMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle JWT api middleware');\n const { scheme, token } = parseAuthTokenHeader(authorization);\n if (scheme.toUpperCase() === TOKEN_BASIC.toUpperCase()) {\n debug('handle basic token');\n // this should happen when client tries to login with an existing user\n const credentials = convertPayloadToBase64(token).toString();\n const { user, password } = parseBasicPayload(credentials) as AESPayload;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err: VerdaccioError | null, user): void => {\n if (!err) {\n debug('generating a remote user');\n req.remote_user = user;\n next();\n } else {\n debug('generating anonymous user');\n req.remote_user = createAnonymousRemoteUser();\n next(err);\n }\n });\n } else {\n debug('handle jwt token');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n if (credentials) {\n // if the signature is valid we rely on it\n req.remote_user = credentials;\n debug('generating a remote user');\n next();\n } else {\n // with JWT throw 401\n debug('jwt invalid token');\n next(errorUtils.getForbidden(API_ERROR.BAD_USERNAME_PASSWORD));\n }\n }\n }\n\n private _handleAESMiddleware(\n req: $RequestExtend,\n security: Security,\n secret: string,\n authorization: string,\n next: Function\n ): void {\n debug('handle legacy api middleware');\n debug('api middleware secret %o', typeof secret === 'string');\n debug('api middleware authorization %o', typeof authorization === 'string');\n const credentials: any = getMiddlewareCredentials(security, secret, authorization);\n debug('api middleware credentials %o', credentials?.name);\n if (credentials) {\n const { user, password } = credentials;\n debug('authenticating %o', user);\n this.authenticate(user, password, (err, user): void => {\n if (!err) {\n req.remote_user = user;\n debug('generating a remote user');\n next();\n } else {\n req.remote_user = createAnonymousRemoteUser();\n debug('generating anonymous user');\n next(err);\n }\n });\n } else {\n // we force npm client to ask again with basic authentication\n debug('legacy invalid header');\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n }\n\n private _isRemoteUserValid(remote_user?: RemoteUser): boolean {\n return _.isUndefined(remote_user) === false && _.isUndefined(remote_user?.name) === false;\n }\n\n /**\n * JWT middleware for WebUI\n */\n public webUIJWTmiddleware(): RequestHandler {\n // @ts-ignore\n return (req: $RequestExtend, res: $ResponseExtend, _next: NextFunction): void => {\n if (this._isRemoteUserValid(req.remote_user)) {\n return _next();\n }\n\n req.pause();\n const next = (err: VerdaccioError | void): void => {\n req.resume();\n if (err) {\n // req.remote_user.error = err.message;\n res.status(err.statusCode).send(err.message);\n }\n\n return _next();\n };\n\n const { authorization } = req.headers;\n if (_.isNil(authorization)) {\n return next();\n }\n\n if (!isAuthHeaderValid(authorization)) {\n return next(errorUtils.getBadRequest(API_ERROR.BAD_AUTH_HEADER));\n }\n\n const token = (authorization || '').replace(`${TOKEN_BEARER} `, '');\n if (!token) {\n return next();\n }\n\n let credentials: RemoteUser | undefined;\n try {\n credentials = verifyJWTPayload(token, this.config.secret);\n } catch (err: any) {\n // FIXME: intended behaviour, do we want it?\n }\n\n if (this._isRemoteUserValid(credentials)) {\n const { name, groups } = credentials as RemoteUser;\n req.remote_user = createRemoteUser(name as string, groups);\n } else {\n req.remote_user = createAnonymousRemoteUser();\n }\n\n next();\n };\n }\n\n public async jwtEncrypt(user: RemoteUser, signOptions: JWTSignOptions): Promise<string> {\n const { real_groups, name, groups } = user;\n debug('jwt encrypt %o', name);\n const realGroupsValidated = _.isNil(real_groups) ? [] : real_groups;\n const groupedGroups = _.isNil(groups)\n ? real_groups\n : Array.from(new Set([...groups.concat(realGroupsValidated)]));\n const payload: RemoteUser = {\n real_groups: realGroupsValidated,\n name,\n groups: groupedGroups,\n };\n\n const token: string = await signPayload(payload, this.secret, signOptions);\n\n return token;\n }\n\n /**\n * Encrypt a string.\n */\n public aesEncrypt(value: string): string | void {\n return aesEncrypt(value, this.secret);\n }\n}\n\nexport { Auth };\n"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AO,CAAC,GAAGoD,WAAyB;QAClDtB,GAAG,CAACK,WAAW,GAAG,IAAA5B,wBAAgB,EAACU,IAAI,EAAYjB,MAAM,CAAC;MAC5D,CAAC,MAAM;QACL8B,GAAG,CAACK,WAAW,GAAG,IAAAN,iCAAyB,GAAE;MAC/C;MAEA/B,IAAI,EAAE;IACR,CAAC;EACH;EAEA,MAAaqE,UAAU,CAAC1D,IAAgB,EAAE2D,WAA2B,EAAmB;IACtF,MAAM;MAAEC,WAAW;MAAEpD,IAAI;MAAEjB;IAAO,CAAC,GAAGS,IAAI;IAC1CjE,KAAK,CAAC,gBAAgB,EAAEyE,IAAI,CAAC;IAC7B,MAAMqD,mBAAmB,GAAG1F,eAAC,CAACQ,KAAK,CAACiF,WAAW,CAAC,GAAG,EAAE,GAAGA,WAAW;IACnE,MAAME,aAAa,GAAG3F,eAAC,CAACQ,KAAK,CAACY,MAAM,CAAC,GACjCqE,WAAW,GACXG,KAAK,CAACC,IAAI,CAAC,IAAIC,GAAG,CAAC,CAAC,GAAG1E,MAAM,CAAC2E,MAAM,CAACL,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAChE,MAAMM,OAAmB,GAAG;MAC1BP,WAAW,EAAEC,mBAAmB;MAChCrD,IAAI;MACJjB,MAAM,EAAEuE;IACV,CAAC;IAED,MAAM/E,KAAa,GAAG,MAAM,IAAAqF,qBAAW,EAACD,OAAO,EAAE,IAAI,CAAC/H,MAAM,EAAEuH,WAAW,CAAC;IAE1E,OAAO5E,KAAK;EACd;;EAEA;AACF;AACA;EACSsF,UAAU,CAACC,KAAa,EAAiB;IAC9C,OAAO,IAAAD,uBAAU,EAACC,KAAK,EAAE,IAAI,CAAClI,MAAM,CAAC;EACvC;AACF;AAAC"}
|
package/build/index.js
CHANGED
|
@@ -19,11 +19,8 @@ Object.defineProperty(exports, "TokenEncryption", {
|
|
|
19
19
|
return _auth.TokenEncryption;
|
|
20
20
|
}
|
|
21
21
|
});
|
|
22
|
-
|
|
23
22
|
var _auth = require("./auth");
|
|
24
|
-
|
|
25
23
|
var _utils = require("./utils");
|
|
26
|
-
|
|
27
24
|
Object.keys(_utils).forEach(function (key) {
|
|
28
25
|
if (key === "default" || key === "__esModule") return;
|
|
29
26
|
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
@@ -35,9 +32,7 @@ Object.keys(_utils).forEach(function (key) {
|
|
|
35
32
|
}
|
|
36
33
|
});
|
|
37
34
|
});
|
|
38
|
-
|
|
39
35
|
var _legacyToken = require("./legacy-token");
|
|
40
|
-
|
|
41
36
|
Object.keys(_legacyToken).forEach(function (key) {
|
|
42
37
|
if (key === "default" || key === "__esModule") return;
|
|
43
38
|
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
@@ -49,9 +44,7 @@ Object.keys(_legacyToken).forEach(function (key) {
|
|
|
49
44
|
}
|
|
50
45
|
});
|
|
51
46
|
});
|
|
52
|
-
|
|
53
47
|
var _jwtToken = require("./jwt-token");
|
|
54
|
-
|
|
55
48
|
Object.keys(_jwtToken).forEach(function (key) {
|
|
56
49
|
if (key === "default" || key === "__esModule") return;
|
|
57
50
|
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
@@ -63,9 +56,7 @@ Object.keys(_jwtToken).forEach(function (key) {
|
|
|
63
56
|
}
|
|
64
57
|
});
|
|
65
58
|
});
|
|
66
|
-
|
|
67
59
|
var _token = require("./token");
|
|
68
|
-
|
|
69
60
|
Object.keys(_token).forEach(function (key) {
|
|
70
61
|
if (key === "default" || key === "__esModule") return;
|
|
71
62
|
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export { Auth, TokenEncryption } from './auth';\nexport * from './utils';\nexport * from './legacy-token';\nexport * from './jwt-token';\nexport * from './token';\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export { Auth, TokenEncryption } from './auth';\nexport * from './utils';\nexport * from './legacy-token';\nexport * from './jwt-token';\nexport * from './token';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"}
|
package/build/jwt-token.js
CHANGED
|
@@ -5,13 +5,9 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
exports.signPayload = signPayload;
|
|
7
7
|
exports.verifyPayload = verifyPayload;
|
|
8
|
-
|
|
9
8
|
var _debug = _interopRequireDefault(require("debug"));
|
|
10
|
-
|
|
11
9
|
var _jsonwebtoken = _interopRequireDefault(require("jsonwebtoken"));
|
|
12
|
-
|
|
13
10
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
14
|
-
|
|
15
11
|
const debug = (0, _debug.default)('verdaccio:auth:token:jwt');
|
|
16
12
|
/**
|
|
17
13
|
* Sign the payload and return JWT
|
|
@@ -20,11 +16,11 @@ const debug = (0, _debug.default)('verdaccio:auth:token:jwt');
|
|
|
20
16
|
* @param secretOrPrivateKey
|
|
21
17
|
* @param options
|
|
22
18
|
*/
|
|
23
|
-
|
|
24
19
|
async function signPayload(payload, secretOrPrivateKey, options = {}) {
|
|
25
20
|
return new Promise(function (resolve, reject) {
|
|
26
21
|
debug('sign jwt token');
|
|
27
|
-
return _jsonwebtoken.default.sign(payload, secretOrPrivateKey,
|
|
22
|
+
return _jsonwebtoken.default.sign(payload, secretOrPrivateKey,
|
|
23
|
+
// FIXME: upgrade to the latest library and types
|
|
28
24
|
// @ts-ignore
|
|
29
25
|
{
|
|
30
26
|
// 1 === 1ms (one millisecond)
|
|
@@ -37,7 +33,6 @@ async function signPayload(payload, secretOrPrivateKey, options = {}) {
|
|
|
37
33
|
});
|
|
38
34
|
});
|
|
39
35
|
}
|
|
40
|
-
|
|
41
36
|
function verifyPayload(token, secretOrPrivateKey) {
|
|
42
37
|
debug('verify jwt token');
|
|
43
38
|
return _jsonwebtoken.default.verify(token, secretOrPrivateKey);
|
package/build/jwt-token.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt-token.js","names":["debug","buildDebug","signPayload","payload","secretOrPrivateKey","options","Promise","resolve","reject","jwt","sign","notBefore","error","token","verifyPayload","verify"],"sources":["../src/jwt-token.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport jwt from 'jsonwebtoken';\n\nimport { JWTSignOptions, RemoteUser } from '@verdaccio/types';\n\nconst debug = buildDebug('verdaccio:auth:token:jwt');\n/**\n * Sign the payload and return JWT\n * https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback\n * @param payload\n * @param secretOrPrivateKey\n * @param options\n */\nexport async function signPayload(\n payload: RemoteUser,\n secretOrPrivateKey: string,\n options: JWTSignOptions = {}\n): Promise<string> {\n return new Promise(function (resolve, reject): Promise<string> {\n debug('sign jwt token');\n return jwt.sign(\n payload,\n secretOrPrivateKey,\n // FIXME: upgrade to the latest library and types\n // @ts-ignore\n {\n // 1 === 1ms (one millisecond)\n notBefore: '1', // Make sure the time will not rollback :)\n ...options,\n },\n (error, token: string) => {\n debug('error on sign jwt token');\n return error ? reject(error) : resolve(token);\n }\n );\n });\n}\n\nexport function verifyPayload(token: string, secretOrPrivateKey: string): RemoteUser {\n debug('verify jwt token');\n return jwt.verify(token, secretOrPrivateKey) as RemoteUser;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"jwt-token.js","names":["debug","buildDebug","signPayload","payload","secretOrPrivateKey","options","Promise","resolve","reject","jwt","sign","notBefore","error","token","verifyPayload","verify"],"sources":["../src/jwt-token.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport jwt from 'jsonwebtoken';\n\nimport { JWTSignOptions, RemoteUser } from '@verdaccio/types';\n\nconst debug = buildDebug('verdaccio:auth:token:jwt');\n/**\n * Sign the payload and return JWT\n * https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback\n * @param payload\n * @param secretOrPrivateKey\n * @param options\n */\nexport async function signPayload(\n payload: RemoteUser,\n secretOrPrivateKey: string,\n options: JWTSignOptions = {}\n): Promise<string> {\n return new Promise(function (resolve, reject): Promise<string> {\n debug('sign jwt token');\n return jwt.sign(\n payload,\n secretOrPrivateKey,\n // FIXME: upgrade to the latest library and types\n // @ts-ignore\n {\n // 1 === 1ms (one millisecond)\n notBefore: '1', // Make sure the time will not rollback :)\n ...options,\n },\n (error, token: string) => {\n debug('error on sign jwt token');\n return error ? reject(error) : resolve(token);\n }\n );\n });\n}\n\nexport function verifyPayload(token: string, secretOrPrivateKey: string): RemoteUser {\n debug('verify jwt token');\n return jwt.verify(token, secretOrPrivateKey) as RemoteUser;\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAA+B;AAI/B,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,0BAA0B,CAAC;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeC,WAAW,CAC/BC,OAAmB,EACnBC,kBAA0B,EAC1BC,OAAuB,GAAG,CAAC,CAAC,EACX;EACjB,OAAO,IAAIC,OAAO,CAAC,UAAUC,OAAO,EAAEC,MAAM,EAAmB;IAC7DR,KAAK,CAAC,gBAAgB,CAAC;IACvB,OAAOS,qBAAG,CAACC,IAAI,CACbP,OAAO,EACPC,kBAAkB;IAClB;IACA;IACA;MACE;MACAO,SAAS,EAAE,GAAG;MAAE;MAChB,GAAGN;IACL,CAAC,EACD,CAACO,KAAK,EAAEC,KAAa,KAAK;MACxBb,KAAK,CAAC,yBAAyB,CAAC;MAChC,OAAOY,KAAK,GAAGJ,MAAM,CAACI,KAAK,CAAC,GAAGL,OAAO,CAACM,KAAK,CAAC;IAC/C,CAAC,CACF;EACH,CAAC,CAAC;AACJ;AAEO,SAASC,aAAa,CAACD,KAAa,EAAET,kBAA0B,EAAc;EACnFJ,KAAK,CAAC,kBAAkB,CAAC;EACzB,OAAOS,qBAAG,CAACM,MAAM,CAACF,KAAK,EAAET,kBAAkB,CAAC;AAC9C"}
|
package/build/legacy-token.js
CHANGED
|
@@ -6,26 +6,20 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.aesDecrypt = aesDecrypt;
|
|
7
7
|
exports.aesEncrypt = aesEncrypt;
|
|
8
8
|
exports.defaultAlgorithm = void 0;
|
|
9
|
-
|
|
10
9
|
var _crypto = require("crypto");
|
|
11
|
-
|
|
12
10
|
var _debug = _interopRequireDefault(require("debug"));
|
|
13
|
-
|
|
14
11
|
var _config = require("@verdaccio/config");
|
|
15
|
-
|
|
16
12
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
17
|
-
|
|
18
13
|
const debug = (0, _debug.default)('verdaccio:auth:token:legacy');
|
|
19
14
|
const defaultAlgorithm = process.env.VERDACCIO_LEGACY_ALGORITHM || 'aes-256-ctr';
|
|
20
15
|
exports.defaultAlgorithm = defaultAlgorithm;
|
|
21
16
|
const inputEncoding = 'utf8';
|
|
22
|
-
const outputEncoding = 'hex';
|
|
23
|
-
|
|
24
|
-
const IV_LENGTH = 16;
|
|
17
|
+
const outputEncoding = 'hex';
|
|
18
|
+
// For AES, this is always 16
|
|
19
|
+
const IV_LENGTH = 16;
|
|
20
|
+
// Must be 256 bits (32 characters)
|
|
25
21
|
// https://stackoverflow.com/questions/50963160/invalid-key-length-in-crypto-createcipheriv#50963356
|
|
26
|
-
|
|
27
22
|
const VERDACCIO_LEGACY_ENCRYPTION_KEY = process.env.VERDACCIO_LEGACY_ENCRYPTION_KEY;
|
|
28
|
-
|
|
29
23
|
function aesEncrypt(value, key) {
|
|
30
24
|
// https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options
|
|
31
25
|
// https://www.grainger.xyz/changing-from-cipher-to-cipheriv/
|
|
@@ -36,33 +30,31 @@ function aesEncrypt(value, key) {
|
|
|
36
30
|
const isKeyValid = (secretKey === null || secretKey === void 0 ? void 0 : secretKey.length) === _config.TOKEN_VALID_LENGTH;
|
|
37
31
|
debug('length secret key %o', secretKey === null || secretKey === void 0 ? void 0 : secretKey.length);
|
|
38
32
|
debug('is valid secret %o', isKeyValid);
|
|
39
|
-
|
|
40
33
|
if (!value || !secretKey || !isKeyValid) {
|
|
41
34
|
return;
|
|
42
35
|
}
|
|
43
|
-
|
|
44
36
|
const cipher = (0, _crypto.createCipheriv)(defaultAlgorithm, secretKey, iv);
|
|
45
|
-
let encrypted = cipher.update(value, inputEncoding, outputEncoding);
|
|
46
|
-
|
|
37
|
+
let encrypted = cipher.update(value, inputEncoding, outputEncoding);
|
|
38
|
+
// @ts-ignore
|
|
47
39
|
encrypted += cipher.final(outputEncoding);
|
|
48
40
|
const token = `${iv.toString('hex')}:${encrypted.toString()}`;
|
|
49
41
|
debug('token generated successfully');
|
|
50
42
|
return Buffer.from(token).toString('base64');
|
|
51
43
|
}
|
|
52
|
-
|
|
53
44
|
function aesDecrypt(value, key) {
|
|
54
45
|
try {
|
|
55
46
|
const buff = Buffer.from(value, 'base64');
|
|
56
|
-
const textParts = buff.toString().split(':');
|
|
57
|
-
// @ts-ignore
|
|
58
|
-
|
|
59
|
-
const IV = Buffer.from(textParts.shift(), outputEncoding); // extract the encrypted text without the IV
|
|
47
|
+
const textParts = buff.toString().split(':');
|
|
60
48
|
|
|
49
|
+
// extract the IV from the first half of the value
|
|
50
|
+
// @ts-ignore
|
|
51
|
+
const IV = Buffer.from(textParts.shift(), outputEncoding);
|
|
52
|
+
// extract the encrypted text without the IV
|
|
61
53
|
const encryptedText = Buffer.from(textParts.join(':'), outputEncoding);
|
|
62
|
-
const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;
|
|
63
|
-
|
|
64
|
-
const decipher = (0, _crypto.createDecipheriv)(defaultAlgorithm, secretKey, IV);
|
|
65
|
-
|
|
54
|
+
const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;
|
|
55
|
+
// decipher the string
|
|
56
|
+
const decipher = (0, _crypto.createDecipheriv)(defaultAlgorithm, secretKey, IV);
|
|
57
|
+
// FIXME: fix type here should allow Buffer
|
|
66
58
|
let decrypted = decipher.update(encryptedText, outputEncoding, inputEncoding);
|
|
67
59
|
decrypted += decipher.final(inputEncoding);
|
|
68
60
|
debug('token decrypted successfully');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacy-token.js","names":["debug","buildDebug","defaultAlgorithm","process","env","VERDACCIO_LEGACY_ALGORITHM","inputEncoding","outputEncoding","IV_LENGTH","VERDACCIO_LEGACY_ENCRYPTION_KEY","aesEncrypt","value","key","iv","Buffer","from","randomBytes","secretKey","isKeyValid","length","TOKEN_VALID_LENGTH","cipher","createCipheriv","encrypted","update","final","token","toString","aesDecrypt","buff","textParts","split","IV","shift","encryptedText","join","decipher","createDecipheriv","decrypted","_"],"sources":["../src/legacy-token.ts"],"sourcesContent":["import {\n BinaryToTextEncoding,\n CharacterEncoding,\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from 'crypto';\nimport buildDebug from 'debug';\n\nimport { TOKEN_VALID_LENGTH } from '@verdaccio/config';\n\nconst debug = buildDebug('verdaccio:auth:token:legacy');\n\nexport const defaultAlgorithm = process.env.VERDACCIO_LEGACY_ALGORITHM || 'aes-256-ctr';\nconst inputEncoding: CharacterEncoding = 'utf8';\nconst outputEncoding: BinaryToTextEncoding = 'hex';\n// For AES, this is always 16\nconst IV_LENGTH = 16;\n// Must be 256 bits (32 characters)\n// https://stackoverflow.com/questions/50963160/invalid-key-length-in-crypto-createcipheriv#50963356\nconst VERDACCIO_LEGACY_ENCRYPTION_KEY = process.env.VERDACCIO_LEGACY_ENCRYPTION_KEY;\n\nexport function aesEncrypt(value: string, key: string): string | void {\n // https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options\n // https://www.grainger.xyz/changing-from-cipher-to-cipheriv/\n debug('encrypt %o', value);\n debug('algorithm %o', defaultAlgorithm);\n const iv = Buffer.from(randomBytes(IV_LENGTH));\n const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;\n const isKeyValid = secretKey?.length === TOKEN_VALID_LENGTH;\n debug('length secret key %o', secretKey?.length);\n debug('is valid secret %o', isKeyValid);\n if (!value || !secretKey || !isKeyValid) {\n return;\n }\n\n const cipher = createCipheriv(defaultAlgorithm, secretKey, iv);\n let encrypted = cipher.update(value, inputEncoding, outputEncoding);\n // @ts-ignore\n encrypted += cipher.final(outputEncoding);\n const token = `${iv.toString('hex')}:${encrypted.toString()}`;\n debug('token generated successfully');\n return Buffer.from(token).toString('base64');\n}\n\nexport function aesDecrypt(value: string, key: string): string | void {\n try {\n const buff = Buffer.from(value, 'base64');\n const textParts = buff.toString().split(':');\n\n // extract the IV from the first half of the value\n // @ts-ignore\n const IV = Buffer.from(textParts.shift(), outputEncoding);\n // extract the encrypted text without the IV\n const encryptedText = Buffer.from(textParts.join(':'), outputEncoding);\n const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;\n // decipher the string\n const decipher = createDecipheriv(defaultAlgorithm, secretKey, IV);\n // FIXME: fix type here should allow Buffer\n let decrypted = decipher.update(encryptedText as any, outputEncoding, inputEncoding);\n decrypted += decipher.final(inputEncoding);\n debug('token decrypted successfully');\n return decrypted.toString();\n } catch (_: any) {\n return;\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"legacy-token.js","names":["debug","buildDebug","defaultAlgorithm","process","env","VERDACCIO_LEGACY_ALGORITHM","inputEncoding","outputEncoding","IV_LENGTH","VERDACCIO_LEGACY_ENCRYPTION_KEY","aesEncrypt","value","key","iv","Buffer","from","randomBytes","secretKey","isKeyValid","length","TOKEN_VALID_LENGTH","cipher","createCipheriv","encrypted","update","final","token","toString","aesDecrypt","buff","textParts","split","IV","shift","encryptedText","join","decipher","createDecipheriv","decrypted","_"],"sources":["../src/legacy-token.ts"],"sourcesContent":["import {\n BinaryToTextEncoding,\n CharacterEncoding,\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from 'crypto';\nimport buildDebug from 'debug';\n\nimport { TOKEN_VALID_LENGTH } from '@verdaccio/config';\n\nconst debug = buildDebug('verdaccio:auth:token:legacy');\n\nexport const defaultAlgorithm = process.env.VERDACCIO_LEGACY_ALGORITHM || 'aes-256-ctr';\nconst inputEncoding: CharacterEncoding = 'utf8';\nconst outputEncoding: BinaryToTextEncoding = 'hex';\n// For AES, this is always 16\nconst IV_LENGTH = 16;\n// Must be 256 bits (32 characters)\n// https://stackoverflow.com/questions/50963160/invalid-key-length-in-crypto-createcipheriv#50963356\nconst VERDACCIO_LEGACY_ENCRYPTION_KEY = process.env.VERDACCIO_LEGACY_ENCRYPTION_KEY;\n\nexport function aesEncrypt(value: string, key: string): string | void {\n // https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options\n // https://www.grainger.xyz/changing-from-cipher-to-cipheriv/\n debug('encrypt %o', value);\n debug('algorithm %o', defaultAlgorithm);\n const iv = Buffer.from(randomBytes(IV_LENGTH));\n const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;\n const isKeyValid = secretKey?.length === TOKEN_VALID_LENGTH;\n debug('length secret key %o', secretKey?.length);\n debug('is valid secret %o', isKeyValid);\n if (!value || !secretKey || !isKeyValid) {\n return;\n }\n\n const cipher = createCipheriv(defaultAlgorithm, secretKey, iv);\n let encrypted = cipher.update(value, inputEncoding, outputEncoding);\n // @ts-ignore\n encrypted += cipher.final(outputEncoding);\n const token = `${iv.toString('hex')}:${encrypted.toString()}`;\n debug('token generated successfully');\n return Buffer.from(token).toString('base64');\n}\n\nexport function aesDecrypt(value: string, key: string): string | void {\n try {\n const buff = Buffer.from(value, 'base64');\n const textParts = buff.toString().split(':');\n\n // extract the IV from the first half of the value\n // @ts-ignore\n const IV = Buffer.from(textParts.shift(), outputEncoding);\n // extract the encrypted text without the IV\n const encryptedText = Buffer.from(textParts.join(':'), outputEncoding);\n const secretKey = VERDACCIO_LEGACY_ENCRYPTION_KEY || key;\n // decipher the string\n const decipher = createDecipheriv(defaultAlgorithm, secretKey, IV);\n // FIXME: fix type here should allow Buffer\n let decrypted = decipher.update(encryptedText as any, outputEncoding, inputEncoding);\n decrypted += decipher.final(inputEncoding);\n debug('token decrypted successfully');\n return decrypted.toString();\n } catch (_: any) {\n return;\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAOA;AAEA;AAAuD;AAEvD,MAAMA,KAAK,GAAG,IAAAC,cAAU,EAAC,6BAA6B,CAAC;AAEhD,MAAMC,gBAAgB,GAAGC,OAAO,CAACC,GAAG,CAACC,0BAA0B,IAAI,aAAa;AAAC;AACxF,MAAMC,aAAgC,GAAG,MAAM;AAC/C,MAAMC,cAAoC,GAAG,KAAK;AAClD;AACA,MAAMC,SAAS,GAAG,EAAE;AACpB;AACA;AACA,MAAMC,+BAA+B,GAAGN,OAAO,CAACC,GAAG,CAACK,+BAA+B;AAE5E,SAASC,UAAU,CAACC,KAAa,EAAEC,GAAW,EAAiB;EACpE;EACA;EACAZ,KAAK,CAAC,YAAY,EAAEW,KAAK,CAAC;EAC1BX,KAAK,CAAC,cAAc,EAAEE,gBAAgB,CAAC;EACvC,MAAMW,EAAE,GAAGC,MAAM,CAACC,IAAI,CAAC,IAAAC,mBAAW,EAACR,SAAS,CAAC,CAAC;EAC9C,MAAMS,SAAS,GAAGR,+BAA+B,IAAIG,GAAG;EACxD,MAAMM,UAAU,GAAG,CAAAD,SAAS,aAATA,SAAS,uBAATA,SAAS,CAAEE,MAAM,MAAKC,0BAAkB;EAC3DpB,KAAK,CAAC,sBAAsB,E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S,EAAEe,EAAE,CAAC;IAClE;IACA,IAAIM,SAAS,GAAGF,QAAQ,CAACZ,MAAM,CAACU,aAAa,EAAS3B,cAAc,EAAED,aAAa,CAAC;IACpFgC,SAAS,IAAIF,QAAQ,CAACX,KAAK,CAACnB,aAAa,CAAC;IAC1CN,KAAK,CAAC,8BAA8B,CAAC;IACrC,OAAOsC,SAAS,CAACX,QAAQ,EAAE;EAC7B,CAAC,CAAC,OAAOY,CAAM,EAAE;IACf;EACF;AACF"}
|
package/build/token.js
CHANGED
|
@@ -4,14 +4,11 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports.parseBasicPayload = parseBasicPayload;
|
|
7
|
-
|
|
8
7
|
function parseBasicPayload(credentials) {
|
|
9
8
|
const index = credentials.indexOf(':');
|
|
10
|
-
|
|
11
9
|
if (index < 0) {
|
|
12
10
|
return;
|
|
13
11
|
}
|
|
14
|
-
|
|
15
12
|
const user = credentials.slice(0, index);
|
|
16
13
|
const password = credentials.slice(index + 1);
|
|
17
14
|
return {
|
package/build/token.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.js","names":["parseBasicPayload","credentials","index","indexOf","user","slice","password"],"sources":["../src/token.ts"],"sourcesContent":["import { BasicPayload } from './utils';\n\nexport function parseBasicPayload(credentials: string): BasicPayload {\n const index = credentials.indexOf(':');\n if (index < 0) {\n return;\n }\n\n const user: string = credentials.slice(0, index);\n const password: string = credentials.slice(index + 1);\n\n return { user, password };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"token.js","names":["parseBasicPayload","credentials","index","indexOf","user","slice","password"],"sources":["../src/token.ts"],"sourcesContent":["import { BasicPayload } from './utils';\n\nexport function parseBasicPayload(credentials: string): BasicPayload {\n const index = credentials.indexOf(':');\n if (index < 0) {\n return;\n }\n\n const user: string = credentials.slice(0, index);\n const password: string = credentials.slice(index + 1);\n\n return { user, password };\n}\n"],"mappings":";;;;;;AAEO,SAASA,iBAAiB,CAACC,WAAmB,EAAgB;EACnE,MAAMC,KAAK,GAAGD,WAAW,CAACE,OAAO,CAAC,GAAG,CAAC;EACtC,IAAID,KAAK,GAAG,CAAC,EAAE;IACb;EACF;EAEA,MAAME,IAAY,GAAGH,WAAW,CAACI,KAAK,CAAC,CAAC,EAAEH,KAAK,CAAC;EAChD,MAAMI,QAAgB,GAAGL,WAAW,CAACI,KAAK,CAACH,KAAK,GAAG,CAAC,CAAC;EAErD,OAAO;IAAEE,IAAI;IAAEE;EAAS,CAAC;AAC3B"}
|
package/build/utils.d.ts
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
import { VerdaccioError, pluginUtils } from '@verdaccio/core';
|
|
3
3
|
import { AuthPackageAllow, Config, Logger, RemoteUser, Security } from '@verdaccio/types';
|
|
4
4
|
import { AESPayload, TokenEncryption } from './auth';
|
|
5
|
-
export
|
|
6
|
-
export
|
|
5
|
+
export type BasicPayload = AESPayload | void;
|
|
6
|
+
export type AuthMiddlewarePayload = RemoteUser | BasicPayload;
|
|
7
7
|
export interface AuthTokenHeader {
|
|
8
8
|
scheme: string;
|
|
9
9
|
token: string;
|
|
10
10
|
}
|
|
11
|
-
export
|
|
12
|
-
export
|
|
13
|
-
export
|
|
11
|
+
export type AllowActionCallbackResponse = boolean | undefined;
|
|
12
|
+
export type AllowActionCallback = (error: VerdaccioError | null, allowed?: AllowActionCallbackResponse) => void;
|
|
13
|
+
export type AllowAction = (user: RemoteUser, pkg: AuthPackageAllow, callback: AllowActionCallback) => void;
|
|
14
14
|
/**
|
|
15
15
|
* Split authentication header eg: Bearer [secret_token]
|
|
16
16
|
* @param authorizationHeader auth token
|
|
@@ -29,7 +29,7 @@ export declare function isAuthHeaderValid(authorization: string): boolean;
|
|
|
29
29
|
* @returns object of default implementations.
|
|
30
30
|
*/
|
|
31
31
|
export declare function getDefaultPlugins(logger: Logger): pluginUtils.Auth<Config>;
|
|
32
|
-
export
|
|
32
|
+
export type ActionsAllowed = 'publish' | 'unpublish' | 'access';
|
|
33
33
|
export declare function allow_action(action: ActionsAllowed, logger: Logger): AllowAction;
|
|
34
34
|
/**
|
|
35
35
|
*
|