@verdaccio/api 9.0.0-next-9.19 → 9.0.0-next-9.20

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/publish.js CHANGED
@@ -147,7 +147,6 @@ function publish(router, auth, storage, config, logger) {
147
147
  const version = _verdaccio_core.tarballUtils.getVersionFromTarball(filename);
148
148
  const metadata = {
149
149
  name: packageName,
150
- version,
151
150
  _rev: revision
152
151
  };
153
152
  const publishedPackage = version ? `${packageName}@${version}` : packageName;
@@ -1 +1 @@
1
- {"version":3,"file":"publish.js","names":[],"sources":["../src/publish.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport type { Router } from 'express';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { API_MESSAGE, HEADERS, HTTP_STATUS, tarballUtils } from '@verdaccio/core';\nimport { notify } from '@verdaccio/hooks';\nimport {\n PUBLISH_API_ENDPOINTS,\n allow,\n expectJson,\n getRequestOptions,\n media,\n} from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, Manifest } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types/custom';\n\nconst debug = buildDebug('verdaccio:api:publish');\n\n/**\n * Publish a package / update package\n *\n * There are multiples scenarios here to be considered:\n *\n * 1. Publish scenario\n *\n * Publish a package consist of at least 1 step (PUT) with a metadata payload.\n * When a package is published, an _attachment property is present that contains the data\n * of the tarball.\n *\n * Example flow of publish.\n *\n * npm http fetch PUT 201 http://localhost:4873/@scope%2ftest1 9627ms\n npm info lifecycle @scope/test1@1.0.1~publish: @scope/test1@1.0.1\n npm info lifecycle @scope/test1@1.0.1~postpublish: @scope/test1@1.0.1\n + @scope/test1@1.0.1\n npm verb exit [ 0, true ]\n *\n *\n * 2. Unpublish scenario\n *\n * Unpublish consist in 3 steps.\n * 1. Try to fetch metadata -> if it fails, return 404\n * 2. Compute metadata locally (client side) and send a mutate payload excluding the version to\n * be unpublished\n * eg: if metadata reflects 1.0.1, 1.0.2 and 1.0.3, the computed metadata won't include 1.0.3.\n * 3. Once the second step has been successfully finished, delete the tarball.\n *\n * All these steps are consecutive and required, there is no transacions here, if step 3 fails,\n * metadata might get corrupted.\n *\n * Note the unpublish call will suffix in the url a /-rev/14-5d500cfce92f90fd revision number,\n * this not\n * used internally.\n *\n *\n * Example flow of unpublish.\n *\n * There are two possible flows:\n *\n * - Remove all packages (entirely)\n * eg: npm unpublish package-name@* --force\n * eg: npm unpublish package-name --force\n *\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * - Remove a specific version\n * eg: npm unpublish package-name@1.0.0 --force\n *\n * Get fresh manifest\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * Update manifest without the version to be unpublished\n * npm http fetch PUT 201 http://localhost:4873/custom-name/-rev/14-5d500cfce92f90fd 956606ms\n * Get fresh manifest (revision should be different)\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1601ms\n * Remove the tarball\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * 3. Change owners of a package\n *\n * Changing owners (maintainers) of a package uses the publish endpoint.\n *\n * The body includes a list of the new owners with the following format\n *\n * {\n \"_id\": pkgName,\n \"_rev\": \"4-b0cdaefc9bdb77c8\",\n \"maintainers\": [\n { \"name\": \"first owner\", \"email\": \"me@verdaccio.org\" },\n { \"name\": \"second owner\", \"email\": \"you@verdaccio.org\" },\n ...\n ]\n }\n *\n */\nexport default function publish(\n router: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n const can = allow(auth, {\n beforeAll: (a, b) => logger.trace(a, b),\n afterAll: (a, b) => logger.trace(a, b),\n });\n router.put(\n PUBLISH_API_ENDPOINTS.add_package,\n can('publish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish one version')\n );\n\n router.put(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish with revision')\n );\n\n /**\n * Un-publishing an entire package.\n *\n * This scenario happens when any of these scenarios happens:\n * - the first call detect there is only one version remaining\n * - no version is specified in the unpublish call\n * - all versions are removed npm unpublish package@*\n * - there is no versions on the metadata\n\n * then the client decides to DELETE the resource\n * Example:\n * Get fresh manifest (write=true is a flag to get the latest revision)\n * npm http fetch GET 304 http://localhost:4873/package-name?write=true 1076ms (from cache)\n * Send request to delete the package, this includes the revision number that must match\n * and the package name, it will delete the entire package and all tarballs (or tarball depends the scenario)\n * npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n async function (req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer) {\n const packageName = req.params.package;\n const rev = req.params.revision;\n const username = req?.remote_user?.name;\n\n logger.debug({ packageName }, `unpublishing @{packageName}`);\n try {\n await storage.removePackage(packageName, rev, username);\n debug('package %s unpublished', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of package removal\n const metadata: Partial<Manifest> = { name: packageName, _rev: rev };\n\n void notify(metadata, config, req.remote_user, packageName, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.PKG_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n\n /*\n Remove a tarball, this happens when npm unpublish a package unique version.\n npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.remove_tarball,\n can('unpublish'),\n async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n const packageName = req.params.package;\n const { filename, revision } = req.params;\n const username = req?.remote_user?.name;\n\n logger.debug(\n { packageName, filename, revision },\n `removing a tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n try {\n await storage.removeTarball(packageName, filename, revision, username);\n res.status(HTTP_STATUS.CREATED);\n\n logger.debug(\n { packageName, filename, revision },\n `success remove tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n\n // send notification of version removal\n // getVersionFromTarball returns undefined when the filename is not parseable;\n // fall back to the package name so we never report `name@undefined`\n const version = tarballUtils.getVersionFromTarball(filename);\n const metadata: Partial<Manifest> = { name: packageName, version, _rev: revision };\n const publishedPackage = version ? `${packageName}@${version}` : packageName;\n\n void notify(metadata, config, req.remote_user, publishedPackage, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.TARBALL_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n}\n\nexport function publishPackage(\n storage: Storage,\n config: Config,\n logger: Logger,\n origin: string\n): any {\n return async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n debug(origin);\n const ac = new AbortController();\n const packageName = req.params.package;\n const { revision } = req.params;\n debug('publishing package %s', packageName);\n debug('revision %s', revision);\n if (debug.enabled) {\n debug('body %o', req.body);\n }\n const metadata = req.body;\n\n logger.debug({ packageName }, `publishing package @{packageName}`);\n\n const requestOptions = getRequestOptions(req);\n\n try {\n const message = await storage.updateManifest(metadata, {\n name: packageName,\n revision,\n signal: ac.signal,\n requestOptions,\n uplinksLook: false,\n });\n debug('package %s published', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of publication (notification step, non transactional)\n // a publish body is a packument; the published version is the single entry\n // under `versions` (see storage.updateManifest), not a top-level field\n const [version] = Object.keys(metadata.versions ?? {});\n void notify(\n metadata,\n config,\n req.remote_user,\n `${metadata.name}@${version}`,\n 'publish'\n ).catch((error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n });\n\n return next({\n success: true,\n ok: message,\n });\n } catch (err: any) {\n // TODO: review if we need the abort controller here\n next(err);\n }\n };\n}\n"],"mappings":";;;;;;;AAkBA,IAAM,WAAA,GAAA,MAAA,SAAmB,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EhD,SAAwB,QACtB,QACA,MACA,SACA,QACA,QACM;CACN,MAAM,OAAA,GAAA,sBAAA,OAAY,MAAM;EACtB,YAAY,GAAG,MAAM,OAAO,MAAM,GAAG,CAAC;EACtC,WAAW,GAAG,MAAM,OAAO,MAAM,GAAG,CAAC;CACvC,CAAC;CACD,OAAO,IACL,sBAAA,sBAAsB,aACtB,IAAI,SAAS,IAAA,GAAA,sBAAA,OACP,gBAAA,QAAQ,IAAI,GAClB,sBAAA,YACA,eAAe,SAAS,QAAQ,QAAQ,qBAAqB,CAC/D;CAEA,OAAO,IACL,sBAAA,sBAAsB,iBACtB,IAAI,WAAW,IAAA,GAAA,sBAAA,OACT,gBAAA,QAAQ,IAAI,GAClB,sBAAA,YACA,eAAe,SAAS,QAAQ,QAAQ,uBAAuB,CACjE;;;;;;;;;;;;;;;;;;CAmBA,OAAO,OACL,sBAAA,sBAAsB,iBACtB,IAAI,WAAW,GACf,eAAgB,KAAqB,KAAsB,MAAwB;EACjF,MAAM,cAAc,IAAI,OAAO;EAC/B,MAAM,MAAM,IAAI,OAAO;EACvB,MAAM,WAAW,KAAK,aAAa;EAEnC,OAAO,MAAM,EAAE,YAAY,GAAG,6BAA6B;EAC3D,IAAI;GACF,MAAM,QAAQ,cAAc,aAAa,KAAK,QAAQ;GACtD,QAAM,0BAA0B,WAAW;GAC3C,IAAI,OAAO,gBAAA,YAAY,OAAO;GAK9B,CAAA,GAAA,iBAAA,QAAY;IAF0B,MAAM;IAAa,MAAM;GAEnD,GAAU,QAAQ,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B,WAAW;EAC1C,QAAM,eAAe,QAAQ;EAC7B,IAAI,QAAM,SACR,QAAM,WAAW,IAAI,IAAI;EAE3B,MAAM,WAAW,IAAI;EAErB,OAAO,MAAM,EAAE,YAAY,GAAG,mCAAmC;EAEjE,MAAM,kBAAA,GAAA,sBAAA,mBAAmC,GAAG;EAE5C,IAAI;GACF,MAAM,UAAU,MAAM,QAAQ,eAAe,UAAU;IACrD,MAAM;IACN;IACA,QAAQ,GAAG;IACX;IACA,aAAa;GACf,CAAC;GACD,QAAM,wBAAwB,WAAW;GACzC,IAAI,OAAO,gBAAA,YAAY,OAAO;GAK9B,MAAM,CAAC,WAAW,OAAO,KAAK,SAAS,YAAY,CAAC,CAAC;GACrD,CAAA,GAAA,iBAAA,QACE,UACA,QACA,IAAI,aACJ,GAAG,SAAS,KAAK,GAAG,WACpB,SACF,EAAE,OAAO,UAAe;IACtB,OAAO,MAAM,EAAE,OAAO,OAAO,QAAQ,GAAG,2CAA2C;GACrF,CAAC;GAED,OAAO,KAAK;IACV,SAAS;IACT,IAAI;GACN,CAAC;EACH,SAAS,KAAU;GAEjB,KAAK,GAAG;EACV;CACF;AACF"}
1
+ {"version":3,"file":"publish.js","names":[],"sources":["../src/publish.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport type { Router } from 'express';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { API_MESSAGE, HEADERS, HTTP_STATUS, tarballUtils } from '@verdaccio/core';\nimport { notify } from '@verdaccio/hooks';\nimport {\n PUBLISH_API_ENDPOINTS,\n allow,\n expectJson,\n getRequestOptions,\n media,\n} from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, Manifest } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types/custom';\n\nconst debug = buildDebug('verdaccio:api:publish');\n\n/**\n * Publish a package / update package\n *\n * There are multiples scenarios here to be considered:\n *\n * 1. Publish scenario\n *\n * Publish a package consist of at least 1 step (PUT) with a metadata payload.\n * When a package is published, an _attachment property is present that contains the data\n * of the tarball.\n *\n * Example flow of publish.\n *\n * npm http fetch PUT 201 http://localhost:4873/@scope%2ftest1 9627ms\n npm info lifecycle @scope/test1@1.0.1~publish: @scope/test1@1.0.1\n npm info lifecycle @scope/test1@1.0.1~postpublish: @scope/test1@1.0.1\n + @scope/test1@1.0.1\n npm verb exit [ 0, true ]\n *\n *\n * 2. Unpublish scenario\n *\n * Unpublish consist in 3 steps.\n * 1. Try to fetch metadata -> if it fails, return 404\n * 2. Compute metadata locally (client side) and send a mutate payload excluding the version to\n * be unpublished\n * eg: if metadata reflects 1.0.1, 1.0.2 and 1.0.3, the computed metadata won't include 1.0.3.\n * 3. Once the second step has been successfully finished, delete the tarball.\n *\n * All these steps are consecutive and required, there is no transacions here, if step 3 fails,\n * metadata might get corrupted.\n *\n * Note the unpublish call will suffix in the url a /-rev/14-5d500cfce92f90fd revision number,\n * this not\n * used internally.\n *\n *\n * Example flow of unpublish.\n *\n * There are two possible flows:\n *\n * - Remove all packages (entirely)\n * eg: npm unpublish package-name@* --force\n * eg: npm unpublish package-name --force\n *\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * - Remove a specific version\n * eg: npm unpublish package-name@1.0.0 --force\n *\n * Get fresh manifest\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * Update manifest without the version to be unpublished\n * npm http fetch PUT 201 http://localhost:4873/custom-name/-rev/14-5d500cfce92f90fd 956606ms\n * Get fresh manifest (revision should be different)\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1601ms\n * Remove the tarball\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * 3. Change owners of a package\n *\n * Changing owners (maintainers) of a package uses the publish endpoint.\n *\n * The body includes a list of the new owners with the following format\n *\n * {\n \"_id\": pkgName,\n \"_rev\": \"4-b0cdaefc9bdb77c8\",\n \"maintainers\": [\n { \"name\": \"first owner\", \"email\": \"me@verdaccio.org\" },\n { \"name\": \"second owner\", \"email\": \"you@verdaccio.org\" },\n ...\n ]\n }\n *\n */\nexport default function publish(\n router: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n const can = allow(auth, {\n beforeAll: (a, b) => logger.trace(a, b),\n afterAll: (a, b) => logger.trace(a, b),\n });\n router.put(\n PUBLISH_API_ENDPOINTS.add_package,\n can('publish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish one version')\n );\n\n router.put(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish with revision')\n );\n\n /**\n * Un-publishing an entire package.\n *\n * This scenario happens when any of these scenarios happens:\n * - the first call detect there is only one version remaining\n * - no version is specified in the unpublish call\n * - all versions are removed npm unpublish package@*\n * - there is no versions on the metadata\n\n * then the client decides to DELETE the resource\n * Example:\n * Get fresh manifest (write=true is a flag to get the latest revision)\n * npm http fetch GET 304 http://localhost:4873/package-name?write=true 1076ms (from cache)\n * Send request to delete the package, this includes the revision number that must match\n * and the package name, it will delete the entire package and all tarballs (or tarball depends the scenario)\n * npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n async function (req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer) {\n const packageName = req.params.package;\n const rev = req.params.revision;\n const username = req?.remote_user?.name;\n\n logger.debug({ packageName }, `unpublishing @{packageName}`);\n try {\n await storage.removePackage(packageName, rev, username);\n debug('package %s unpublished', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of package removal\n const metadata: Partial<Manifest> = { name: packageName, _rev: rev };\n\n void notify(metadata, config, req.remote_user, packageName, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.PKG_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n\n /*\n Remove a tarball, this happens when npm unpublish a package unique version.\n npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.remove_tarball,\n can('unpublish'),\n async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n const packageName = req.params.package;\n const { filename, revision } = req.params;\n const username = req?.remote_user?.name;\n\n logger.debug(\n { packageName, filename, revision },\n `removing a tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n try {\n await storage.removeTarball(packageName, filename, revision, username);\n res.status(HTTP_STATUS.CREATED);\n\n logger.debug(\n { packageName, filename, revision },\n `success remove tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n\n // send notification of version removal\n // getVersionFromTarball returns undefined when the filename is not parseable;\n // fall back to the package name so we never report `name@undefined`\n const version = tarballUtils.getVersionFromTarball(filename);\n const metadata: Partial<Manifest> = { name: packageName, _rev: revision };\n const publishedPackage = version ? `${packageName}@${version}` : packageName;\n\n void notify(metadata, config, req.remote_user, publishedPackage, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.TARBALL_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n}\n\nexport function publishPackage(\n storage: Storage,\n config: Config,\n logger: Logger,\n origin: string\n): any {\n return async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n debug(origin);\n const ac = new AbortController();\n const packageName = req.params.package;\n const { revision } = req.params;\n debug('publishing package %s', packageName);\n debug('revision %s', revision);\n if (debug.enabled) {\n debug('body %o', req.body);\n }\n const metadata = req.body;\n\n logger.debug({ packageName }, `publishing package @{packageName}`);\n\n const requestOptions = getRequestOptions(req);\n\n try {\n const message = await storage.updateManifest(metadata, {\n name: packageName,\n revision,\n signal: ac.signal,\n requestOptions,\n uplinksLook: false,\n });\n debug('package %s published', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of publication (notification step, non transactional)\n // a publish body is a packument; the published version is the single entry\n // under `versions` (see storage.updateManifest), not a top-level field\n const [version] = Object.keys(metadata.versions ?? {});\n void notify(\n metadata,\n config,\n req.remote_user,\n `${metadata.name}@${version}`,\n 'publish'\n ).catch((error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n });\n\n return next({\n success: true,\n ok: message,\n });\n } catch (err: any) {\n // TODO: review if we need the abort controller here\n next(err);\n }\n };\n}\n"],"mappings":";;;;;;;AAkBA,IAAM,WAAA,GAAA,MAAA,SAAmB,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EhD,SAAwB,QACtB,QACA,MACA,SACA,QACA,QACM;CACN,MAAM,OAAA,GAAA,sBAAA,OAAY,MAAM;EACtB,YAAY,GAAG,MAAM,OAAO,MAAM,GAAG,CAAC;EACtC,WAAW,GAAG,MAAM,OAAO,MAAM,GAAG,CAAC;CACvC,CAAC;CACD,OAAO,IACL,sBAAA,sBAAsB,aACtB,IAAI,SAAS,IAAA,GAAA,sBAAA,OACP,gBAAA,QAAQ,IAAI,GAClB,sBAAA,YACA,eAAe,SAAS,QAAQ,QAAQ,qBAAqB,CAC/D;CAEA,OAAO,IACL,sBAAA,sBAAsB,iBACtB,IAAI,WAAW,IAAA,GAAA,sBAAA,OACT,gBAAA,QAAQ,IAAI,GAClB,sBAAA,YACA,eAAe,SAAS,QAAQ,QAAQ,uBAAuB,CACjE;;;;;;;;;;;;;;;;;;CAmBA,OAAO,OACL,sBAAA,sBAAsB,iBACtB,IAAI,WA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EAAE,OAAO,OAAO,QAAQ,GAAG,2CAA2C;GACrF,CACF;GAEA,OAAO,KAAK,EAAE,IAAI,gBAAA,YAAY,gBAAgB,CAAC;EACjD,SAAS,KAAK;GACZ,OAAO,KAAK,GAAG;EACjB;CACF,CACF;AACF;AAEA,SAAgB,eACd,SACA,QACA,QACA,QACK;CACL,OAAO,eACL,KACA,KACA,MACe;EACf,QAAM,MAAM;EACZ,MAAM,KAAK,IAAI,gBAAgB;EAC/B,MAAM,cAAc,IAAI,OAAO;EAC/B,MAAM,EAAE,aAAa,IAAI;EACzB,QAAM,yBAAyB,WAAW;EAC1C,QAAM,eAAe,QAAQ;EAC7B,IAAI,QAAM,SACR,QAAM,WAAW,IAAI,IAAI;EAE3B,MAAM,WAAW,IAAI;EAErB,OAAO,MAAM,EAAE,YAAY,GAAG,mCAAmC;EAEjE,MAAM,kBAAA,GAAA,sBAAA,mBAAmC,GAAG;EAE5C,IAAI;GACF,MAAM,UAAU,MAAM,QAAQ,eAAe,UAAU;IACrD,MAAM;IACN;IACA,QAAQ,GAAG;IACX;IACA,aAAa;GACf,CAAC;GACD,QAAM,wBAAwB,WAAW;GACzC,IAAI,OAAO,gBAAA,YAAY,OAAO;GAK9B,MAAM,CAAC,WAAW,OAAO,KAAK,SAAS,YAAY,CAAC,CAAC;GACrD,CAAA,GAAA,iBAAA,QACE,UACA,QACA,IAAI,aACJ,GAAG,SAAS,KAAK,GAAG,WACpB,SACF,EAAE,OAAO,UAAe;IACtB,OAAO,MAAM,EAAE,OAAO,OAAO,QAAQ,GAAG,2CAA2C;GACrF,CAAC;GAED,OAAO,KAAK;IACV,SAAS;IACT,IAAI;GACN,CAAC;EACH,SAAS,KAAU;GAEjB,KAAK,GAAG;EACV;CACF;AACF"}
package/build/publish.mjs CHANGED
@@ -145,7 +145,6 @@ function publish(router, auth, storage, config, logger) {
145
145
  const version = tarballUtils.getVersionFromTarball(filename);
146
146
  const metadata = {
147
147
  name: packageName,
148
- version,
149
148
  _rev: revision
150
149
  };
151
150
  const publishedPackage = version ? `${packageName}@${version}` : packageName;
@@ -1 +1 @@
1
- {"version":3,"file":"publish.mjs","names":[],"sources":["../src/publish.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport type { Router } from 'express';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { API_MESSAGE, HEADERS, HTTP_STATUS, tarballUtils } from '@verdaccio/core';\nimport { notify } from '@verdaccio/hooks';\nimport {\n PUBLISH_API_ENDPOINTS,\n allow,\n expectJson,\n getRequestOptions,\n media,\n} from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, Manifest } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types/custom';\n\nconst debug = buildDebug('verdaccio:api:publish');\n\n/**\n * Publish a package / update package\n *\n * There are multiples scenarios here to be considered:\n *\n * 1. Publish scenario\n *\n * Publish a package consist of at least 1 step (PUT) with a metadata payload.\n * When a package is published, an _attachment property is present that contains the data\n * of the tarball.\n *\n * Example flow of publish.\n *\n * npm http fetch PUT 201 http://localhost:4873/@scope%2ftest1 9627ms\n npm info lifecycle @scope/test1@1.0.1~publish: @scope/test1@1.0.1\n npm info lifecycle @scope/test1@1.0.1~postpublish: @scope/test1@1.0.1\n + @scope/test1@1.0.1\n npm verb exit [ 0, true ]\n *\n *\n * 2. Unpublish scenario\n *\n * Unpublish consist in 3 steps.\n * 1. Try to fetch metadata -> if it fails, return 404\n * 2. Compute metadata locally (client side) and send a mutate payload excluding the version to\n * be unpublished\n * eg: if metadata reflects 1.0.1, 1.0.2 and 1.0.3, the computed metadata won't include 1.0.3.\n * 3. Once the second step has been successfully finished, delete the tarball.\n *\n * All these steps are consecutive and required, there is no transacions here, if step 3 fails,\n * metadata might get corrupted.\n *\n * Note the unpublish call will suffix in the url a /-rev/14-5d500cfce92f90fd revision number,\n * this not\n * used internally.\n *\n *\n * Example flow of unpublish.\n *\n * There are two possible flows:\n *\n * - Remove all packages (entirely)\n * eg: npm unpublish package-name@* --force\n * eg: npm unpublish package-name --force\n *\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * - Remove a specific version\n * eg: npm unpublish package-name@1.0.0 --force\n *\n * Get fresh manifest\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * Update manifest without the version to be unpublished\n * npm http fetch PUT 201 http://localhost:4873/custom-name/-rev/14-5d500cfce92f90fd 956606ms\n * Get fresh manifest (revision should be different)\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1601ms\n * Remove the tarball\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * 3. Change owners of a package\n *\n * Changing owners (maintainers) of a package uses the publish endpoint.\n *\n * The body includes a list of the new owners with the following format\n *\n * {\n \"_id\": pkgName,\n \"_rev\": \"4-b0cdaefc9bdb77c8\",\n \"maintainers\": [\n { \"name\": \"first owner\", \"email\": \"me@verdaccio.org\" },\n { \"name\": \"second owner\", \"email\": \"you@verdaccio.org\" },\n ...\n ]\n }\n *\n */\nexport default function publish(\n router: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n const can = allow(auth, {\n beforeAll: (a, b) => logger.trace(a, b),\n afterAll: (a, b) => logger.trace(a, b),\n });\n router.put(\n PUBLISH_API_ENDPOINTS.add_package,\n can('publish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish one version')\n );\n\n router.put(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish with revision')\n );\n\n /**\n * Un-publishing an entire package.\n *\n * This scenario happens when any of these scenarios happens:\n * - the first call detect there is only one version remaining\n * - no version is specified in the unpublish call\n * - all versions are removed npm unpublish package@*\n * - there is no versions on the metadata\n\n * then the client decides to DELETE the resource\n * Example:\n * Get fresh manifest (write=true is a flag to get the latest revision)\n * npm http fetch GET 304 http://localhost:4873/package-name?write=true 1076ms (from cache)\n * Send request to delete the package, this includes the revision number that must match\n * and the package name, it will delete the entire package and all tarballs (or tarball depends the scenario)\n * npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n async function (req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer) {\n const packageName = req.params.package;\n const rev = req.params.revision;\n const username = req?.remote_user?.name;\n\n logger.debug({ packageName }, `unpublishing @{packageName}`);\n try {\n await storage.removePackage(packageName, rev, username);\n debug('package %s unpublished', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of package removal\n const metadata: Partial<Manifest> = { name: packageName, _rev: rev };\n\n void notify(metadata, config, req.remote_user, packageName, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.PKG_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n\n /*\n Remove a tarball, this happens when npm unpublish a package unique version.\n npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.remove_tarball,\n can('unpublish'),\n async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n const packageName = req.params.package;\n const { filename, revision } = req.params;\n const username = req?.remote_user?.name;\n\n logger.debug(\n { packageName, filename, revision },\n `removing a tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n try {\n await storage.removeTarball(packageName, filename, revision, username);\n res.status(HTTP_STATUS.CREATED);\n\n logger.debug(\n { packageName, filename, revision },\n `success remove tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n\n // send notification of version removal\n // getVersionFromTarball returns undefined when the filename is not parseable;\n // fall back to the package name so we never report `name@undefined`\n const version = tarballUtils.getVersionFromTarball(filename);\n const metadata: Partial<Manifest> = { name: packageName, version, _rev: revision };\n const publishedPackage = version ? `${packageName}@${version}` : packageName;\n\n void notify(metadata, config, req.remote_user, publishedPackage, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.TARBALL_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n}\n\nexport function publishPackage(\n storage: Storage,\n config: Config,\n logger: Logger,\n origin: string\n): any {\n return async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n debug(origin);\n const ac = new AbortController();\n const packageName = req.params.package;\n const { revision } = req.params;\n debug('publishing package %s', packageName);\n debug('revision %s', revision);\n if (debug.enabled) {\n debug('body %o', req.body);\n }\n const metadata = req.body;\n\n logger.debug({ packageName }, `publishing package @{packageName}`);\n\n const requestOptions = getRequestOptions(req);\n\n try {\n const message = await storage.updateManifest(metadata, {\n name: packageName,\n revision,\n signal: ac.signal,\n requestOptions,\n uplinksLook: false,\n });\n debug('package %s published', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of publication (notification step, non transactional)\n // a publish body is a packument; the published version is the single entry\n // under `versions` (see storage.updateManifest), not a top-level field\n const [version] = Object.keys(metadata.versions ?? {});\n void notify(\n metadata,\n config,\n req.remote_user,\n `${metadata.name}@${version}`,\n 'publish'\n ).catch((error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n });\n\n return next({\n success: true,\n ok: message,\n });\n } catch (err: any) {\n // TODO: review if we need the abort controller here\n next(err);\n }\n };\n}\n"],"mappings":";;;;;AAkBA,IAAM,QAAQ,WAAW,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EhD,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AS,KAAK,GAAG,WACpB,SACF,EAAE,OAAO,UAAe;IACtB,OAAO,MAAM,EAAE,OAAO,OAAO,QAAQ,GAAG,2CAA2C;GACrF,CAAC;GAED,OAAO,KAAK;IACV,SAAS;IACT,IAAI;GACN,CAAC;EACH,SAAS,KAAU;GAEjB,KAAK,GAAG;EACV;CACF;AACF"}
1
+ {"version":3,"file":"publish.mjs","names":[],"sources":["../src/publish.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport type { Router } from 'express';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { API_MESSAGE, HEADERS, HTTP_STATUS, tarballUtils } from '@verdaccio/core';\nimport { notify } from '@verdaccio/hooks';\nimport {\n PUBLISH_API_ENDPOINTS,\n allow,\n expectJson,\n getRequestOptions,\n media,\n} from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, Manifest } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend, $ResponseExtend } from '../types/custom';\n\nconst debug = buildDebug('verdaccio:api:publish');\n\n/**\n * Publish a package / update package\n *\n * There are multiples scenarios here to be considered:\n *\n * 1. Publish scenario\n *\n * Publish a package consist of at least 1 step (PUT) with a metadata payload.\n * When a package is published, an _attachment property is present that contains the data\n * of the tarball.\n *\n * Example flow of publish.\n *\n * npm http fetch PUT 201 http://localhost:4873/@scope%2ftest1 9627ms\n npm info lifecycle @scope/test1@1.0.1~publish: @scope/test1@1.0.1\n npm info lifecycle @scope/test1@1.0.1~postpublish: @scope/test1@1.0.1\n + @scope/test1@1.0.1\n npm verb exit [ 0, true ]\n *\n *\n * 2. Unpublish scenario\n *\n * Unpublish consist in 3 steps.\n * 1. Try to fetch metadata -> if it fails, return 404\n * 2. Compute metadata locally (client side) and send a mutate payload excluding the version to\n * be unpublished\n * eg: if metadata reflects 1.0.1, 1.0.2 and 1.0.3, the computed metadata won't include 1.0.3.\n * 3. Once the second step has been successfully finished, delete the tarball.\n *\n * All these steps are consecutive and required, there is no transacions here, if step 3 fails,\n * metadata might get corrupted.\n *\n * Note the unpublish call will suffix in the url a /-rev/14-5d500cfce92f90fd revision number,\n * this not\n * used internally.\n *\n *\n * Example flow of unpublish.\n *\n * There are two possible flows:\n *\n * - Remove all packages (entirely)\n * eg: npm unpublish package-name@* --force\n * eg: npm unpublish package-name --force\n *\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * - Remove a specific version\n * eg: npm unpublish package-name@1.0.0 --force\n *\n * Get fresh manifest\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1680ms\n * Update manifest without the version to be unpublished\n * npm http fetch PUT 201 http://localhost:4873/custom-name/-rev/14-5d500cfce92f90fd 956606ms\n * Get fresh manifest (revision should be different)\n * npm http fetch GET 200 http://localhost:4873/custom-name?write=true 1601ms\n * Remove the tarball\n * npm http fetch DELETE 201 http://localhost:4873/custom-name/-/test1-1.0.3.tgz/-rev/16-e11c8db282b2d992 19ms\n *\n * 3. Change owners of a package\n *\n * Changing owners (maintainers) of a package uses the publish endpoint.\n *\n * The body includes a list of the new owners with the following format\n *\n * {\n \"_id\": pkgName,\n \"_rev\": \"4-b0cdaefc9bdb77c8\",\n \"maintainers\": [\n { \"name\": \"first owner\", \"email\": \"me@verdaccio.org\" },\n { \"name\": \"second owner\", \"email\": \"you@verdaccio.org\" },\n ...\n ]\n }\n *\n */\nexport default function publish(\n router: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n const can = allow(auth, {\n beforeAll: (a, b) => logger.trace(a, b),\n afterAll: (a, b) => logger.trace(a, b),\n });\n router.put(\n PUBLISH_API_ENDPOINTS.add_package,\n can('publish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish one version')\n );\n\n router.put(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n media(HEADERS.JSON),\n expectJson,\n publishPackage(storage, config, logger, 'publish with revision')\n );\n\n /**\n * Un-publishing an entire package.\n *\n * This scenario happens when any of these scenarios happens:\n * - the first call detect there is only one version remaining\n * - no version is specified in the unpublish call\n * - all versions are removed npm unpublish package@*\n * - there is no versions on the metadata\n\n * then the client decides to DELETE the resource\n * Example:\n * Get fresh manifest (write=true is a flag to get the latest revision)\n * npm http fetch GET 304 http://localhost:4873/package-name?write=true 1076ms (from cache)\n * Send request to delete the package, this includes the revision number that must match\n * and the package name, it will delete the entire package and all tarballs (or tarball depends the scenario)\n * npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.publish_package,\n can('unpublish'),\n async function (req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer) {\n const packageName = req.params.package;\n const rev = req.params.revision;\n const username = req?.remote_user?.name;\n\n logger.debug({ packageName }, `unpublishing @{packageName}`);\n try {\n await storage.removePackage(packageName, rev, username);\n debug('package %s unpublished', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of package removal\n const metadata: Partial<Manifest> = { name: packageName, _rev: rev };\n\n void notify(metadata, config, req.remote_user, packageName, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.PKG_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n\n /*\n Remove a tarball, this happens when npm unpublish a package unique version.\n npm http fetch DELETE 201 http://localhost:4873/package-name/-rev/18-d8ebe3020bd4ac9c 22ms\n */\n router.delete(\n PUBLISH_API_ENDPOINTS.remove_tarball,\n can('unpublish'),\n async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n const packageName = req.params.package;\n const { filename, revision } = req.params;\n const username = req?.remote_user?.name;\n\n logger.debug(\n { packageName, filename, revision },\n `removing a tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n try {\n await storage.removeTarball(packageName, filename, revision, username);\n res.status(HTTP_STATUS.CREATED);\n\n logger.debug(\n { packageName, filename, revision },\n `success remove tarball for @{packageName}-@{tarballName}-@{revision}`\n );\n\n // send notification of version removal\n // getVersionFromTarball returns undefined when the filename is not parseable;\n // fall back to the package name so we never report `name@undefined`\n const version = tarballUtils.getVersionFromTarball(filename);\n const metadata: Partial<Manifest> = { name: packageName, _rev: revision };\n const publishedPackage = version ? `${packageName}@${version}` : packageName;\n\n void notify(metadata, config, req.remote_user, publishedPackage, 'unpublish').catch(\n (error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n }\n );\n\n return next({ ok: API_MESSAGE.TARBALL_REMOVED });\n } catch (err) {\n return next(err);\n }\n }\n );\n}\n\nexport function publishPackage(\n storage: Storage,\n config: Config,\n logger: Logger,\n origin: string\n): any {\n return async function (\n req: $RequestExtend,\n res: $ResponseExtend,\n next: $NextFunctionVer\n ): Promise<void> {\n debug(origin);\n const ac = new AbortController();\n const packageName = req.params.package;\n const { revision } = req.params;\n debug('publishing package %s', packageName);\n debug('revision %s', revision);\n if (debug.enabled) {\n debug('body %o', req.body);\n }\n const metadata = req.body;\n\n logger.debug({ packageName }, `publishing package @{packageName}`);\n\n const requestOptions = getRequestOptions(req);\n\n try {\n const message = await storage.updateManifest(metadata, {\n name: packageName,\n revision,\n signal: ac.signal,\n requestOptions,\n uplinksLook: false,\n });\n debug('package %s published', packageName);\n res.status(HTTP_STATUS.CREATED);\n\n // send notification of publication (notification step, non transactional)\n // a publish body is a packument; the published version is the single entry\n // under `versions` (see storage.updateManifest), not a top-level field\n const [version] = Object.keys(metadata.versions ?? {});\n void notify(\n metadata,\n config,\n req.remote_user,\n `${metadata.name}@${version}`,\n 'publish'\n ).catch((error: any) => {\n logger.error({ error: error?.message }, 'notify batch service has failed: @{error}');\n });\n\n return next({\n success: true,\n ok: message,\n });\n } catch (err: any) {\n // TODO: review if we need the abort controller here\n next(err);\n }\n };\n}\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BAAwB,WAAW;GACzC,IAAI,OAAO,YAAY,OAAO;GAK9B,MAAM,CAAC,WAAW,OAAO,KAAK,SAAS,YAAY,CAAC,CAAC;GACrD,OACE,UACA,QACA,IAAI,aACJ,GAAG,SAAS,KAAK,GAAG,WACpB,SACF,EAAE,OAAO,UAAe;IACtB,OAAO,MAAM,EAAE,OAAO,OAAO,QAAQ,GAAG,2CAA2C;GACrF,CAAC;GAED,OAAO,KAAK;IACV,SAAS;IACT,IAAI;GACN,CAAC;EACH,SAAS,KAAU;GAEjB,KAAK,GAAG;EACV;CACF;AACF"}
package/build/v1/token.js CHANGED
@@ -3,6 +3,17 @@ let _verdaccio_core = require("@verdaccio/core");
3
3
  let _verdaccio_auth = require("@verdaccio/auth");
4
4
  let lodash_es = require("lodash-es");
5
5
  //#region src/v1/token.ts
6
+ var UNSUPPORTED_TOKEN_OPTIONS = [
7
+ "packages_and_scopes_permission",
8
+ "packages",
9
+ "packages_all",
10
+ "scopes",
11
+ "orgs",
12
+ "orgs_permission",
13
+ "expires",
14
+ "description",
15
+ "bypass_2fa"
16
+ ];
6
17
  function normalizeToken(token) {
7
18
  return {
8
19
  ...token,
@@ -29,9 +40,16 @@ function token_default(route, auth, storage, config, logger) {
29
40
  return next(_verdaccio_core.errorUtils.getUnauthorized());
30
41
  });
31
42
  route.post(_verdaccio_middleware.TOKEN_API_ENDPOINTS.get_tokens, (0, _verdaccio_middleware.rateLimit)(config?.userRateLimit), function(req, res, next) {
32
- const { password, readonly, cidr_whitelist } = req.body;
43
+ const { password } = req.body;
33
44
  const { name } = req.remote_user;
45
+ const readonly = req.body.readonly ?? false;
46
+ const cidr_whitelist = req.body.cidr_whitelist ?? [];
34
47
  if (!(0, lodash_es.isBoolean)(readonly) || !Array.isArray(cidr_whitelist)) return next(_verdaccio_core.errorUtils.getCode(_verdaccio_core.HTTP_STATUS.BAD_DATA, _verdaccio_core.SUPPORT_ERRORS.PARAMETERS_NOT_VALID));
48
+ const unsupportedOptions = UNSUPPORTED_TOKEN_OPTIONS.filter((option) => (0, lodash_es.isNil)(req.body[option]) === false);
49
+ if (unsupportedOptions.length > 0) logger.warn({
50
+ options: unsupportedOptions.join(", "),
51
+ userAgent: req.get("user-agent") ?? "unknown"
52
+ }, "granular access token options are not supported yet and will be ignored: @{options} (client: @{userAgent})");
35
53
  auth.authenticate(name, password, async (err, user) => {
36
54
  if (err) {
37
55
  const errorCode = err.message ? _verdaccio_core.HTTP_STATUS.UNAUTHORIZED : _verdaccio_core.HTTP_STATUS.INTERNAL_ERROR;
@@ -1 +1 @@
1
- {"version":3,"file":"token.js","names":[],"sources":["../../src/v1/token.ts"],"sourcesContent":["import type { Response, Router } from 'express';\nimport { isBoolean, isNil } from 'lodash-es';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { getApiToken } from '@verdaccio/auth';\nimport { HEADERS, HTTP_STATUS, SUPPORT_ERRORS, cryptoUtils, errorUtils } from '@verdaccio/core';\nimport { TOKEN_API_ENDPOINTS, rateLimit } from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, RemoteUser, Token } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend } from '../../types/custom';\n\nexport type NormalizeToken = Token & {\n cidr_whitelist: string[];\n created: string;\n};\n\n// npm expects \"cidr_whitelist\" for token list\nfunction normalizeToken(token: Token): NormalizeToken {\n return {\n ...token,\n cidr_whitelist: token.cidr || [],\n created: new Date(token.created).toISOString(),\n };\n}\n\n// https://github.com/npm/npm-profile/blob/latest/lib/index.js\nexport default function (\n route: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n route.get(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n async function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n try {\n const tokens = await storage.readTokens({ user: name });\n const totalTokens = tokens.length;\n logger.debug({ totalTokens }, 'token list retrieved: @{totalTokens}');\n\n res.status(HTTP_STATUS.OK);\n return next({\n objects: tokens.map(normalizeToken),\n urls: {\n next: '', // TODO: pagination?\n },\n });\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token list has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n\n route.post(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { password, readonly, cidr_whitelist } = req.body;\n const { name } = req.remote_user;\n\n if (!isBoolean(readonly) || !Array.isArray(cidr_whitelist)) {\n return next(errorUtils.getCode(HTTP_STATUS.BAD_DATA, SUPPORT_ERRORS.PARAMETERS_NOT_VALID));\n }\n\n auth.authenticate(name, password, async (err, user?: RemoteUser) => {\n if (err) {\n const errorCode = err.message ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.INTERNAL_ERROR;\n return next(errorUtils.getCode(errorCode, err.message));\n }\n\n req.remote_user = user;\n\n if (typeof storage.saveToken !== 'function') {\n return next(\n errorUtils.getCode(HTTP_STATUS.NOT_IMPLEMENTED, SUPPORT_ERRORS.STORAGE_NOT_IMPLEMENT)\n );\n }\n\n try {\n const key = cryptoUtils.generateRandomHexString(16);\n const token = await getApiToken(auth, config, user as RemoteUser, password, {\n tokenKey: key,\n });\n if (!token) {\n throw errorUtils.getInternalError();\n }\n\n // TODO: use a utility here\n const maskedToken = cryptoUtils.mask(token, 5);\n const created = new Date().getTime();\n\n /**\n * cidr_whitelist: is not being used, we pass it through\n * token: we do not store the real token (it is generated once and retrieved\n * to the user), just a mask of it.\n */\n const saveToken: Token = {\n user: name,\n token: maskedToken,\n key,\n cidr: cidr_whitelist,\n readonly,\n created,\n };\n\n await storage.saveToken(saveToken);\n logger.debug({ key, name }, 'token @{key} was created for user @{name}');\n res.set(HEADERS.CACHE_CONTROL, HEADERS.NO_CACHE);\n return next(\n normalizeToken({\n token,\n user: name,\n key: saveToken.key,\n cidr: cidr_whitelist,\n readonly,\n created: saveToken.created,\n })\n );\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getInternalError(error.message));\n }\n });\n }\n );\n\n route.delete(\n TOKEN_API_ENDPOINTS.delete_token,\n rateLimit(config?.userRateLimit),\n async (req: $RequestExtend, res: Response, next: $NextFunctionVer) => {\n const {\n params: { tokenKey },\n } = req;\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n logger.debug({ name }, '@{name} has requested remove a token');\n try {\n await storage.deleteToken(name, tokenKey);\n logger.info({ tokenKey, name }, 'token id @{tokenKey} was revoked for user @{name}');\n return next({});\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n}\n"],"mappings":";;;;;AAkBA,SAAS,eAAe,OAA8B;CACpD,OAAO;EACL,GAAG;EACH,gBAAgB,MAAM,QAAQ,CAAC;EAC/B,SAAS,IAAI,KAAK,MAAM,OAAO,EAAE,YAAY;CAC/C;AACF;AAGA,SAAA,cACE,OACA,MACA,SACA,QACA,QACM;CACN,MAAM,IACJ,sBAAA,oBAAoB,aAAA,GAAA,sBAAA,WACV,QAAQ,aAAa,GAC/B,eAAgB,KAAqB,KAAe,MAAwB;EAC1E,MAAM,EAAE,SAAS,IAAI;EAErB,KAAA,GAAA,UAAA,OAAU,IAAI,MAAM,OAClB,IAAI;GACF,MAAM,SAAS,MAAM,QAAQ,WAAW,EAAE,MAAM,KAAK,CAAC;GACtD,MAAM,cAAc,OAAO;GAC3B,OAAO,MAAM,EAAE,YAAY,GAAG,sCAAsC;GAEpE,IAAI,OAAO,gBAAA,YAAY,EAAE;GACzB,OAAO,KAAK;IACV,SAAS,OAAO,IAAI,cAAc;IAClC,MAAM,EACJ,MAAM,GACR;GACF,CAAC;EACH,SAAS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EA,MAAM,QAAQ,UAAU,SAAS;IACjC,OAAO,MAAM;KAAE;KAAK;IAAK,GAAG,2CAA2C;IACvE,IAAI,IAAI,gBAAA,QAAQ,eAAe,gBAAA,QAAQ,QAAQ;IAC/C,OAAO,KACL,eAAe;KACb;KACA,MAAM;KACN,KAAK,UAAU;KACf,MAAM;KACN;KACA,SAAS,UAAU;IACrB,CAAC,CACH;GACF,SAAS,OAAY;IACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,qCAAqC;IACxE,OAAO,KAAK,gBAAA,WAAW,iBAAiB,MAAM,OAAO,CAAC;GACxD;EACF,CAAC;CACH,CACF;CAEA,MAAM,OACJ,sBAAA,oBAAoB,eAAA,GAAA,sBAAA,WACV,QAAQ,aAAa,GAC/B,OAAO,KAAqB,KAAe,SAA2B;EACpE,MAAM,EACJ,QAAQ,EAAE,eACR;EACJ,MAAM,EAAE,SAAS,IAAI;EAErB,KAAA,GAAA,UAAA,OAAU,IAAI,MAAM,OAAO;GACzB,OAAO,MAAM,EAAE,KAAK,GAAG,sCAAsC;GAC7D,IAAI;IACF,MAAM,QAAQ,YAAY,MAAM,QAAQ;IACxC,OAAO,KAAK;KAAE;KAAU;IAAK,GAAG,mDAAmD;IACnF,OAAO,KAAK,CAAC,CAAC;GAChB,SAAS,OAAY;IACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,qCAAqC;IACxE,OAAO,KAAK,gBAAA,WAAW,QAAQ,gBAAA,YAAY,gBAAgB,MAAM,OAAO,CAAC;GAC3E;EACF;EACA,OAAO,KAAK,gBAAA,WAAW,gBAAgB,CAAC;CAC1C,CACF;AACF"}
1
+ {"version":3,"file":"token.js","names":[],"sources":["../../src/v1/token.ts"],"sourcesContent":["import type { Response, Router } from 'express';\nimport { isBoolean, isNil } from 'lodash-es';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { getApiToken } from '@verdaccio/auth';\nimport { HEADERS, HTTP_STATUS, SUPPORT_ERRORS, cryptoUtils, errorUtils } from '@verdaccio/core';\nimport { TOKEN_API_ENDPOINTS, rateLimit } from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, RemoteUser, Token } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend } from '../../types/custom';\n\n// Granular access token options (npm >= 11) that Verdaccio does not implement\n// yet. They are accepted so `npm token create` succeeds, but the restrictions\n// they express are NOT enforced — warn so the operator is not misled.\nconst UNSUPPORTED_TOKEN_OPTIONS = [\n 'packages_and_scopes_permission',\n 'packages',\n 'packages_all',\n 'scopes',\n 'orgs',\n 'orgs_permission',\n 'expires',\n 'description',\n 'bypass_2fa',\n];\n\nexport type NormalizeToken = Token & {\n cidr_whitelist: string[];\n created: string;\n};\n\n// npm expects \"cidr_whitelist\" for token list\nfunction normalizeToken(token: Token): NormalizeToken {\n return {\n ...token,\n cidr_whitelist: token.cidr || [],\n created: new Date(token.created).toISOString(),\n };\n}\n\n// https://github.com/npm/npm-profile/blob/latest/lib/index.js\nexport default function (\n route: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n route.get(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n async function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n try {\n const tokens = await storage.readTokens({ user: name });\n const totalTokens = tokens.length;\n logger.debug({ totalTokens }, 'token list retrieved: @{totalTokens}');\n\n res.status(HTTP_STATUS.OK);\n return next({\n objects: tokens.map(normalizeToken),\n urls: {\n next: '', // TODO: pagination?\n },\n });\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token list has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n\n route.post(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { password } = req.body;\n const { name } = req.remote_user;\n // `readonly` and `cidr_whitelist` are optional: npm >= 11 rewrote\n // `npm token create` to omit them (and only sends `cidr_whitelist` with\n // `--cidr`), so default them rather than rejecting the request. A wrong\n // type is still rejected.\n const readonly = req.body.readonly ?? false;\n const cidr_whitelist = req.body.cidr_whitelist ?? [];\n\n if (!isBoolean(readonly) || !Array.isArray(cidr_whitelist)) {\n return next(errorUtils.getCode(HTTP_STATUS.BAD_DATA, SUPPORT_ERRORS.PARAMETERS_NOT_VALID));\n }\n\n const unsupportedOptions = UNSUPPORTED_TOKEN_OPTIONS.filter(\n (option) => isNil(req.body[option]) === false\n );\n if (unsupportedOptions.length > 0) {\n logger.warn(\n { options: unsupportedOptions.join(', '), userAgent: req.get('user-agent') ?? 'unknown' },\n 'granular access token options are not supported yet and will be ignored: @{options} (client: @{userAgent})'\n );\n }\n\n auth.authenticate(name, password, async (err, user?: RemoteUser) => {\n if (err) {\n const errorCode = err.message ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.INTERNAL_ERROR;\n return next(errorUtils.getCode(errorCode, err.message));\n }\n\n req.remote_user = user;\n\n if (typeof storage.saveToken !== 'function') {\n return next(\n errorUtils.getCode(HTTP_STATUS.NOT_IMPLEMENTED, SUPPORT_ERRORS.STORAGE_NOT_IMPLEMENT)\n );\n }\n\n try {\n const key = cryptoUtils.generateRandomHexString(16);\n const token = await getApiToken(auth, config, user as RemoteUser, password, {\n tokenKey: key,\n });\n if (!token) {\n throw errorUtils.getInternalError();\n }\n\n // TODO: use a utility here\n const maskedToken = cryptoUtils.mask(token, 5);\n const created = new Date().getTime();\n\n /**\n * cidr_whitelist: is not being used, we pass it through\n * token: we do not store the real token (it is generated once and retrieved\n * to the user), just a mask of it.\n */\n const saveToken: Token = {\n user: name,\n token: maskedToken,\n key,\n cidr: cidr_whitelist,\n readonly,\n created,\n };\n\n await storage.saveToken(saveToken);\n logger.debug({ key, name }, 'token @{key} was created for user @{name}');\n res.set(HEADERS.CACHE_CONTROL, HEADERS.NO_CACHE);\n return next(\n normalizeToken({\n token,\n user: name,\n key: saveToken.key,\n cidr: cidr_whitelist,\n readonly,\n created: saveToken.created,\n })\n );\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getInternalError(error.message));\n }\n });\n }\n );\n\n route.delete(\n TOKEN_API_ENDPOINTS.delete_token,\n rateLimit(config?.userRateLimit),\n async (req: $RequestExtend, res: Response, next: $NextFunctionVer) => {\n const {\n params: { tokenKey },\n } = req;\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n logger.debug({ name }, '@{name} has requested remove a token');\n try {\n await storage.deleteToken(name, tokenKey);\n logger.info({ tokenKey, name }, 'token id @{tokenKey} was revoked for user @{name}');\n return next({});\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n}\n"],"mappings":";;;;;AAeA,IAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAQA,SAAS,eAAe,OAA8B;CACpD,OAAO;EACL,GAAG;EACH,gBAAgB,MAAM,QAAQ,CAAC;EAC/B,SAAS,IAAI,KAAK,MAAM,OAAO,EAAE,YAAY;CAC/C;AACF;AAGA,SAAA,cACE,OACA,MACA,SACA,QACA,QACM;CACN,MAAM,IACJ,sBAAA,oBAAoB,aAAA,GAAA,sBAAA,WACV,QAAQ,aAAa,GAC/B,eAAgB,KAAqB,KAAe,MAAwB;EAC1E,MAAM,EAAE,SAAS,IAAI;EAErB,KAAA,GAAA,UAAA,OAAU,IAAI,MAAM,OAClB,IAAI;GACF,MAAM,SAAS,MAAM,QAAQ,WAAW,EAAE,MAAM,KAAK,CAAC;GACtD,MAAM,cAAc,OAAO;GAC3B,OAAO,MAAM,EAAE,YAAY,GAAG,sCAAsC;GAEpE,I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Y;IACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,qCAAqC;IACxE,OAAO,KAAK,gBAAA,WAAW,QAAQ,gBAAA,YAAY,gBAAgB,MAAM,OAAO,CAAC;GAC3E;EACF;EACA,OAAO,KAAK,gBAAA,WAAW,gBAAgB,CAAC;CAC1C,CACF;AACF"}
@@ -3,6 +3,17 @@ import { HEADERS, HTTP_STATUS, SUPPORT_ERRORS, cryptoUtils, errorUtils } from "@
3
3
  import { getApiToken } from "@verdaccio/auth";
4
4
  import { isBoolean, isNil } from "lodash-es";
5
5
  //#region src/v1/token.ts
6
+ var UNSUPPORTED_TOKEN_OPTIONS = [
7
+ "packages_and_scopes_permission",
8
+ "packages",
9
+ "packages_all",
10
+ "scopes",
11
+ "orgs",
12
+ "orgs_permission",
13
+ "expires",
14
+ "description",
15
+ "bypass_2fa"
16
+ ];
6
17
  function normalizeToken(token) {
7
18
  return {
8
19
  ...token,
@@ -29,9 +40,16 @@ function token_default(route, auth, storage, config, logger) {
29
40
  return next(errorUtils.getUnauthorized());
30
41
  });
31
42
  route.post(TOKEN_API_ENDPOINTS.get_tokens, rateLimit(config?.userRateLimit), function(req, res, next) {
32
- const { password, readonly, cidr_whitelist } = req.body;
43
+ const { password } = req.body;
33
44
  const { name } = req.remote_user;
45
+ const readonly = req.body.readonly ?? false;
46
+ const cidr_whitelist = req.body.cidr_whitelist ?? [];
34
47
  if (!isBoolean(readonly) || !Array.isArray(cidr_whitelist)) return next(errorUtils.getCode(HTTP_STATUS.BAD_DATA, SUPPORT_ERRORS.PARAMETERS_NOT_VALID));
48
+ const unsupportedOptions = UNSUPPORTED_TOKEN_OPTIONS.filter((option) => isNil(req.body[option]) === false);
49
+ if (unsupportedOptions.length > 0) logger.warn({
50
+ options: unsupportedOptions.join(", "),
51
+ userAgent: req.get("user-agent") ?? "unknown"
52
+ }, "granular access token options are not supported yet and will be ignored: @{options} (client: @{userAgent})");
35
53
  auth.authenticate(name, password, async (err, user) => {
36
54
  if (err) {
37
55
  const errorCode = err.message ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.INTERNAL_ERROR;
@@ -1 +1 @@
1
- {"version":3,"file":"token.mjs","names":[],"sources":["../../src/v1/token.ts"],"sourcesContent":["import type { Response, Router } from 'express';\nimport { isBoolean, isNil } from 'lodash-es';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { getApiToken } from '@verdaccio/auth';\nimport { HEADERS, HTTP_STATUS, SUPPORT_ERRORS, cryptoUtils, errorUtils } from '@verdaccio/core';\nimport { TOKEN_API_ENDPOINTS, rateLimit } from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, RemoteUser, Token } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend } from '../../types/custom';\n\nexport type NormalizeToken = Token & {\n cidr_whitelist: string[];\n created: string;\n};\n\n// npm expects \"cidr_whitelist\" for token list\nfunction normalizeToken(token: Token): NormalizeToken {\n return {\n ...token,\n cidr_whitelist: token.cidr || [],\n created: new Date(token.created).toISOString(),\n };\n}\n\n// https://github.com/npm/npm-profile/blob/latest/lib/index.js\nexport default function (\n route: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n route.get(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n async function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n try {\n const tokens = await storage.readTokens({ user: name });\n const totalTokens = tokens.length;\n logger.debug({ totalTokens }, 'token list retrieved: @{totalTokens}');\n\n res.status(HTTP_STATUS.OK);\n return next({\n objects: tokens.map(normalizeToken),\n urls: {\n next: '', // TODO: pagination?\n },\n });\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token list has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n\n route.post(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { password, readonly, cidr_whitelist } = req.body;\n const { name } = req.remote_user;\n\n if (!isBoolean(readonly) || !Array.isArray(cidr_whitelist)) {\n return next(errorUtils.getCode(HTTP_STATUS.BAD_DATA, SUPPORT_ERRORS.PARAMETERS_NOT_VALID));\n }\n\n auth.authenticate(name, password, async (err, user?: RemoteUser) => {\n if (err) {\n const errorCode = err.message ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.INTERNAL_ERROR;\n return next(errorUtils.getCode(errorCode, err.message));\n }\n\n req.remote_user = user;\n\n if (typeof storage.saveToken !== 'function') {\n return next(\n errorUtils.getCode(HTTP_STATUS.NOT_IMPLEMENTED, SUPPORT_ERRORS.STORAGE_NOT_IMPLEMENT)\n );\n }\n\n try {\n const key = cryptoUtils.generateRandomHexString(16);\n const token = await getApiToken(auth, config, user as RemoteUser, password, {\n tokenKey: key,\n });\n if (!token) {\n throw errorUtils.getInternalError();\n }\n\n // TODO: use a utility here\n const maskedToken = cryptoUtils.mask(token, 5);\n const created = new Date().getTime();\n\n /**\n * cidr_whitelist: is not being used, we pass it through\n * token: we do not store the real token (it is generated once and retrieved\n * to the user), just a mask of it.\n */\n const saveToken: Token = {\n user: name,\n token: maskedToken,\n key,\n cidr: cidr_whitelist,\n readonly,\n created,\n };\n\n await storage.saveToken(saveToken);\n logger.debug({ key, name }, 'token @{key} was created for user @{name}');\n res.set(HEADERS.CACHE_CONTROL, HEADERS.NO_CACHE);\n return next(\n normalizeToken({\n token,\n user: name,\n key: saveToken.key,\n cidr: cidr_whitelist,\n readonly,\n created: saveToken.created,\n })\n );\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getInternalError(error.message));\n }\n });\n }\n );\n\n route.delete(\n TOKEN_API_ENDPOINTS.delete_token,\n rateLimit(config?.userRateLimit),\n async (req: $RequestExtend, res: Response, next: $NextFunctionVer) => {\n const {\n params: { tokenKey },\n } = req;\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n logger.debug({ name }, '@{name} has requested remove a token');\n try {\n await storage.deleteToken(name, tokenKey);\n logger.info({ tokenKey, name }, 'token id @{tokenKey} was revoked for user @{name}');\n return next({});\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n}\n"],"mappings":";;;;;AAkBA,SAAS,eAAe,OAA8B;CACpD,OAAO;EACL,GAAG;EACH,gBAAgB,MAAM,QAAQ,CAAC;EAC/B,SAAS,IAAI,KAAK,MAAM,OAAO,EAAE,YAAY;CAC/C;AACF;AAGA,SAAA,cACE,OACA,MACA,SACA,QACA,QACM;CACN,MAAM,IACJ,oBAAoB,YACpB,UAAU,QAAQ,aAAa,GAC/B,eAAgB,KAAqB,KAAe,MAAwB;EAC1E,MAAM,EAAE,SAAS,IAAI;EAErB,IAAI,MAAM,IAAI,MAAM,OAClB,IAAI;GACF,MAAM,SAAS,MAAM,QAAQ,WAAW,EAAE,MAAM,KAAK,CAAC;GACtD,MAAM,cAAc,OAAO;GAC3B,OAAO,MAAM,EAAE,YAAY,GAAG,sCAAsC;GAEpE,IAAI,OAAO,YAAY,EAAE;GACzB,OAAO,KAAK;IACV,SAAS,OAAO,IAAI,cAAc;IAClC,MAAM,EACJ,MAAM,GACR;GACF,CAAC;EACH,SAAS,OAAY;GACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,iCAAiC;GACpE,OAAO,KAAK,WAAW,QAAQ,YAAY,gBAAgB,MAAM,OAAO,CAAC;EAC3E;EAEF,OAAO,KAAK,WAAW,gBAAgB,CAAC;CAC1C,CACF;CAEA,MAAM,KACJ,oBAAoB,YACpB,UAAU,QAAQ,aAAa,GAC/B,SAAU,KAAqB,KAAe,MAAwB;EACpE,MAAM,EAAE,U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O,KAAqB,KAAe,SAA2B;EACpE,MAAM,EACJ,QAAQ,EAAE,eACR;EACJ,MAAM,EAAE,SAAS,IAAI;EAErB,IAAI,MAAM,IAAI,MAAM,OAAO;GACzB,OAAO,MAAM,EAAE,KAAK,GAAG,sCAAsC;GAC7D,IAAI;IACF,MAAM,QAAQ,YAAY,MAAM,QAAQ;IACxC,OAAO,KAAK;KAAE;KAAU;IAAK,GAAG,mDAAmD;IACnF,OAAO,KAAK,CAAC,CAAC;GAChB,SAAS,OAAY;IACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,qCAAqC;IACxE,OAAO,KAAK,WAAW,QAAQ,YAAY,gBAAgB,MAAM,OAAO,CAAC;GAC3E;EACF;EACA,OAAO,KAAK,WAAW,gBAAgB,CAAC;CAC1C,CACF;AACF"}
1
+ {"version":3,"file":"token.mjs","names":[],"sources":["../../src/v1/token.ts"],"sourcesContent":["import type { Response, Router } from 'express';\nimport { isBoolean, isNil } from 'lodash-es';\n\nimport type { Auth } from '@verdaccio/auth';\nimport { getApiToken } from '@verdaccio/auth';\nimport { HEADERS, HTTP_STATUS, SUPPORT_ERRORS, cryptoUtils, errorUtils } from '@verdaccio/core';\nimport { TOKEN_API_ENDPOINTS, rateLimit } from '@verdaccio/middleware';\nimport type { Storage } from '@verdaccio/store';\nimport type { Config, Logger, RemoteUser, Token } from '@verdaccio/types';\n\nimport type { $NextFunctionVer, $RequestExtend } from '../../types/custom';\n\n// Granular access token options (npm >= 11) that Verdaccio does not implement\n// yet. They are accepted so `npm token create` succeeds, but the restrictions\n// they express are NOT enforced — warn so the operator is not misled.\nconst UNSUPPORTED_TOKEN_OPTIONS = [\n 'packages_and_scopes_permission',\n 'packages',\n 'packages_all',\n 'scopes',\n 'orgs',\n 'orgs_permission',\n 'expires',\n 'description',\n 'bypass_2fa',\n];\n\nexport type NormalizeToken = Token & {\n cidr_whitelist: string[];\n created: string;\n};\n\n// npm expects \"cidr_whitelist\" for token list\nfunction normalizeToken(token: Token): NormalizeToken {\n return {\n ...token,\n cidr_whitelist: token.cidr || [],\n created: new Date(token.created).toISOString(),\n };\n}\n\n// https://github.com/npm/npm-profile/blob/latest/lib/index.js\nexport default function (\n route: Router,\n auth: Auth,\n storage: Storage,\n config: Config,\n logger: Logger\n): void {\n route.get(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n async function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n try {\n const tokens = await storage.readTokens({ user: name });\n const totalTokens = tokens.length;\n logger.debug({ totalTokens }, 'token list retrieved: @{totalTokens}');\n\n res.status(HTTP_STATUS.OK);\n return next({\n objects: tokens.map(normalizeToken),\n urls: {\n next: '', // TODO: pagination?\n },\n });\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token list has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n\n route.post(\n TOKEN_API_ENDPOINTS.get_tokens,\n rateLimit(config?.userRateLimit),\n function (req: $RequestExtend, res: Response, next: $NextFunctionVer) {\n const { password } = req.body;\n const { name } = req.remote_user;\n // `readonly` and `cidr_whitelist` are optional: npm >= 11 rewrote\n // `npm token create` to omit them (and only sends `cidr_whitelist` with\n // `--cidr`), so default them rather than rejecting the request. A wrong\n // type is still rejected.\n const readonly = req.body.readonly ?? false;\n const cidr_whitelist = req.body.cidr_whitelist ?? [];\n\n if (!isBoolean(readonly) || !Array.isArray(cidr_whitelist)) {\n return next(errorUtils.getCode(HTTP_STATUS.BAD_DATA, SUPPORT_ERRORS.PARAMETERS_NOT_VALID));\n }\n\n const unsupportedOptions = UNSUPPORTED_TOKEN_OPTIONS.filter(\n (option) => isNil(req.body[option]) === false\n );\n if (unsupportedOptions.length > 0) {\n logger.warn(\n { options: unsupportedOptions.join(', '), userAgent: req.get('user-agent') ?? 'unknown' },\n 'granular access token options are not supported yet and will be ignored: @{options} (client: @{userAgent})'\n );\n }\n\n auth.authenticate(name, password, async (err, user?: RemoteUser) => {\n if (err) {\n const errorCode = err.message ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.INTERNAL_ERROR;\n return next(errorUtils.getCode(errorCode, err.message));\n }\n\n req.remote_user = user;\n\n if (typeof storage.saveToken !== 'function') {\n return next(\n errorUtils.getCode(HTTP_STATUS.NOT_IMPLEMENTED, SUPPORT_ERRORS.STORAGE_NOT_IMPLEMENT)\n );\n }\n\n try {\n const key = cryptoUtils.generateRandomHexString(16);\n const token = await getApiToken(auth, config, user as RemoteUser, password, {\n tokenKey: key,\n });\n if (!token) {\n throw errorUtils.getInternalError();\n }\n\n // TODO: use a utility here\n const maskedToken = cryptoUtils.mask(token, 5);\n const created = new Date().getTime();\n\n /**\n * cidr_whitelist: is not being used, we pass it through\n * token: we do not store the real token (it is generated once and retrieved\n * to the user), just a mask of it.\n */\n const saveToken: Token = {\n user: name,\n token: maskedToken,\n key,\n cidr: cidr_whitelist,\n readonly,\n created,\n };\n\n await storage.saveToken(saveToken);\n logger.debug({ key, name }, 'token @{key} was created for user @{name}');\n res.set(HEADERS.CACHE_CONTROL, HEADERS.NO_CACHE);\n return next(\n normalizeToken({\n token,\n user: name,\n key: saveToken.key,\n cidr: cidr_whitelist,\n readonly,\n created: saveToken.created,\n })\n );\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getInternalError(error.message));\n }\n });\n }\n );\n\n route.delete(\n TOKEN_API_ENDPOINTS.delete_token,\n rateLimit(config?.userRateLimit),\n async (req: $RequestExtend, res: Response, next: $NextFunctionVer) => {\n const {\n params: { tokenKey },\n } = req;\n const { name } = req.remote_user;\n\n if (isNil(name) === false) {\n logger.debug({ name }, '@{name} has requested remove a token');\n try {\n await storage.deleteToken(name, tokenKey);\n logger.info({ tokenKey, name }, 'token id @{tokenKey} was revoked for user @{name}');\n return next({});\n } catch (error: any) {\n logger.error({ error: error.msg }, 'token creation has failed: @{error}');\n return next(errorUtils.getCode(HTTP_STATUS.INTERNAL_ERROR, error.message));\n }\n }\n return next(errorUtils.getUnauthorized());\n }\n );\n}\n"],"mappings":";;;;;AAeA,IAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAQA,SAAS,eAAe,OAA8B;CACpD,OAAO;EACL,GAAG;EACH,gBAAgB,MAAM,QAAQ,CAAC;EAC/B,SAAS,IAAI,KAAK,MAAM,OAAO,EAAE,YAAY;CAC/C;AACF;AAGA,SAAA,cACE,OACA,MACA,SACA,QACA,QACM;CACN,MAAM,IACJ,oBAAoB,YACpB,UAAU,QAAQ,aAAa,GAC/B,eAAgB,KAAqB,KAAe,MAAwB;EAC1E,MAAM,EAAE,SAAS,IAAI;EAErB,IAAI,MAAM,IAAI,MAAM,OAClB,IAAI;GACF,MAAM,SAAS,MAAM,QAAQ,WAAW,EAAE,MAAM,KAAK,CAAC;GACtD,MAAM,cAAc,OAAO;GAC3B,OAAO,MAAM,EAAE,YAAY,GAAG,sCAAsC;GAEpE,IAAI,OAAO,YAAY,EAAE;GACzB,OAAO,KAAK;IACV,SAAS,OAAO,IAAI,cAAc;IAClC,MAAM,EACJ,MAAM,GACR;GACF,CAAC;EACH,SAAS,OAAY;GACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,iCAAiC;GACpE,OAAO,KAAK,WAAW,QAAQ,YAAY,gBAAgB,MAAM,OAAO,CAAC;EAC3E;EAEF,OAAO,KAAK,WAAW,gBAAgB,CAAC;CAC1C,CACF;CAEA,MAAM,KACJ,oBAAoB,YACpB,UAAU,QAAQ,aAAa,GAC/B,SAAU,KAAqB,KAAe,MAAwB;EACpE,MAAM,EAAE,aAAa,IAAI;EACzB,MAAM,EAAE,SAAS,IAAI;EAKrB,MAAM,WAAW,IAAI,KAAK,YAAY;EACtC,MAAM,iBAAiB,IAAI,KAAK,kBAAkB,CAAC;EAEnD,IAAI,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;IACxE,OAAO,KAAK,WAAW,iBAAiB,MAAM,OAAO,CAAC;GACxD;EACF,CAAC;CACH,CACF;CAEA,MAAM,OACJ,oBAAoB,cACpB,UAAU,QAAQ,aAAa,GAC/B,OAAO,KAAqB,KAAe,SAA2B;EACpE,MAAM,EACJ,QAAQ,EAAE,eACR;EACJ,MAAM,EAAE,SAAS,IAAI;EAErB,IAAI,MAAM,IAAI,MAAM,OAAO;GACzB,OAAO,MAAM,EAAE,KAAK,GAAG,sCAAsC;GAC7D,IAAI;IACF,MAAM,QAAQ,YAAY,MAAM,QAAQ;IACxC,OAAO,KAAK;KAAE;KAAU;IAAK,GAAG,mDAAmD;IACnF,OAAO,KAAK,CAAC,CAAC;GAChB,SAAS,OAAY;IACnB,OAAO,MAAM,EAAE,OAAO,MAAM,IAAI,GAAG,qCAAqC;IACxE,OAAO,KAAK,WAAW,QAAQ,YAAY,gBAAgB,MAAM,OAAO,CAAC;GAC3E;EACF;EACA,OAAO,KAAK,WAAW,gBAAgB,CAAC;CAC1C,CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verdaccio/api",
3
- "version": "9.0.0-next-9.19",
3
+ "version": "9.0.0-next-9.20",
4
4
  "description": "Verdaccio Registry API",
5
5
  "main": "./build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -33,21 +33,21 @@
33
33
  },
34
34
  "license": "MIT",
35
35
  "dependencies": {
36
- "@verdaccio/auth": "9.0.0-next-9.19",
37
- "@verdaccio/config": "9.0.0-next-9.19",
38
- "@verdaccio/core": "9.0.0-next-9.19",
39
- "@verdaccio/hooks": "9.0.0-next-9.19",
40
- "@verdaccio/logger": "9.0.0-next-9.19",
41
- "@verdaccio/middleware": "9.0.0-next-9.19",
42
- "@verdaccio/store": "9.0.0-next-9.19",
36
+ "@verdaccio/auth": "9.0.0-next-9.20",
37
+ "@verdaccio/config": "9.0.0-next-9.20",
38
+ "@verdaccio/core": "9.0.0-next-9.20",
39
+ "@verdaccio/hooks": "9.0.0-next-9.20",
40
+ "@verdaccio/logger": "9.0.0-next-9.20",
41
+ "@verdaccio/middleware": "9.0.0-next-9.20",
42
+ "@verdaccio/store": "9.0.0-next-9.20",
43
43
  "debug": "4.4.3",
44
44
  "express": "5.2.1",
45
45
  "lodash-es": "4.18.1"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/lodash-es": "4.17.12",
49
- "@verdaccio/test-helper": "5.0.0-next-9.20",
50
- "@verdaccio/types": "14.0.0-next-9.10",
49
+ "@verdaccio/test-helper": "5.0.0-next-9.21",
50
+ "@verdaccio/types": "14.0.0-next-9.11",
51
51
  "mockdate": "3.0.5",
52
52
  "nock": "13.5.6",
53
53
  "rimraf": "6.1.3",