@verdaccio/middleware 8.0.3 → 8.0.4

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.
@@ -15,22 +15,22 @@ const WRITE_METHODS = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);
15
15
  /**
16
16
  * Resolve the client address of an incoming request for CIDR matching.
17
17
  *
18
- * Prefers the `x-forwarded-for` header (taking the first, client-most entry of
19
- * the comma-separated list) and falls back to `req.ip` and then the raw socket
20
- * address. The result is normalized (trimmed and IPv4-mapped IPv6 prefixes
21
- * stripped) via {@link ipUtils.normalizeAddress}.
18
+ * Uses Express' `req.ip`, which already honors the application's `trust proxy`
19
+ * setting (`config.server.trustProxy`): when the operator has declared trusted
20
+ * proxies, `req.ip` is the upstream-most untrusted address parsed from
21
+ * `X-Forwarded-For`; otherwise it is the direct socket peer and the forwarded
22
+ * header is ignored entirely.
23
+ *
24
+ * The middleware must NOT read `X-Forwarded-For` on its own — doing so
25
+ * unconditionally would let any client spoof its address (and bypass a token's
26
+ * CIDR whitelist) simply by sending the header. Falls back to the raw socket
27
+ * address and is normalized (trimmed, IPv4-mapped IPv6 prefix stripped) via
28
+ * {@link ipUtils.normalizeAddress}.
22
29
  *
23
30
  * @param req the incoming Express request
24
31
  * @returns the normalized client address, or `undefined` when none can be determined
25
32
  */
26
33
  function getClientAddress(req) {
27
- const forwardedFor = req.headers['x-forwarded-for'];
28
- if (Array.isArray(forwardedFor)) {
29
- return _core.ipUtils.normalizeAddress(forwardedFor[0]?.split(',')[0]);
30
- }
31
- if (typeof forwardedFor === 'string') {
32
- return _core.ipUtils.normalizeAddress(forwardedFor.split(',')[0]);
33
- }
34
34
  return _core.ipUtils.normalizeAddress(req.ip || req.socket.remoteAddress);
35
35
  }
36
36
 
@@ -1 +1 @@
1
- {"version":3,"file":"token-auth.js","names":["_core","require","WRITE_METHODS","Set","getClientAddress","req","forwardedFor","headers","Array","isArray","ipUtils","normalizeAddress","split","ip","socket","remoteAddress","findToken","tokens","tokenKey","find","key","enforceGeneratedTokenMetadata","storage","logger","_res","next","remoteUser","remote_user","token","user","name","errorUtils","getForbidden","API_ERROR","UNAUTHORIZED_ACCESS","readTokens","warn","isAddressAllowed","cidr","readonly","has","method","error","msg","getInternalError","message"],"sources":["../../src/middlewares/token-auth.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nimport { API_ERROR, errorUtils, ipUtils } from '@verdaccio/core';\nimport type { Logger, Token } from '@verdaccio/types';\n\nimport type { $RequestExtend } from '../types';\n\nconst WRITE_METHODS = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);\n\n/**\n * Minimal storage surface required to enforce generated token metadata. Typed\n * structurally so this package does not need to depend on `@verdaccio/store`.\n */\nexport interface TokenReadableStorage {\n /**\n * Load the generated tokens stored for a user.\n *\n * @param filter narrows the lookup to a single `user`\n * @returns the user's persisted tokens\n */\n readTokens(filter: { user: string }): Promise<Token[]>;\n}\n\n/**\n * Resolve the client address of an incoming request for CIDR matching.\n *\n * Prefers the `x-forwarded-for` header (taking the first, client-most entry of\n * the comma-separated list) and falls back to `req.ip` and then the raw socket\n * address. The result is normalized (trimmed and IPv4-mapped IPv6 prefixes\n * stripped) via {@link ipUtils.normalizeAddress}.\n *\n * @param req the incoming Express request\n * @returns the normalized client address, or `undefined` when none can be determined\n */\nfunction getClientAddress(req: Request): string | undefined {\n const forwardedFor = req.headers['x-forwarded-for'];\n\n if (Array.isArray(forwardedFor)) {\n return ipUtils.normalizeAddress(forwardedFor[0]?.split(',')[0]);\n }\n\n if (typeof forwardedFor === 'string') {\n return ipUtils.normalizeAddress(forwardedFor.split(',')[0]);\n }\n\n return ipUtils.normalizeAddress(req.ip || req.socket.remoteAddress);\n}\n\n/**\n * Find the stored token whose `key` matches the key carried by the request.\n *\n * @param tokens the tokens persisted for the authenticated user\n * @param tokenKey the key extracted from the presented generated token\n * @returns the matching {@link Token}, or `undefined` when it has been revoked / never existed\n */\nfunction findToken(tokens: Token[], tokenKey: string): Token | undefined {\n return tokens.find(({ key }) => key === tokenKey);\n}\n\n/**\n * Express middleware that enforces the metadata of npm-style generated tokens\n * (created via `POST /-/npm/v1/tokens`).\n *\n * A generated token embeds a server-issued `key` that is recovered from the\n * verified credentials as `remote_user.token.key`. This middleware looks that\n * key up in storage and rejects the request when the token:\n * - is missing from storage (revoked or never issued);\n * - is used from a client address outside its `cidr` whitelist;\n * - is `readonly` and the request uses a write method (`DELETE`/`PATCH`/`POST`/`PUT`).\n *\n * Requests that do not carry a generated token key (e.g. interactive logins)\n * pass through untouched. It must run after the JWT/auth middleware has\n * populated `remote_user`. Failures fail closed: a storage lookup error yields\n * an internal error rather than allowing the request.\n *\n * @param storage storage exposing {@link TokenReadableStorage.readTokens} to load the user's tokens\n * @param logger logger used to record rejected attempts and lookup failures\n * @returns an Express {@link RequestHandler} that calls `next()` to allow or `next(error)` to reject\n */\nexport function enforceGeneratedTokenMetadata(\n storage: TokenReadableStorage,\n logger: Logger\n): RequestHandler {\n return async function (req: Request, _res: Response, next: NextFunction): Promise<void> {\n const remoteUser = (req as $RequestExtend).remote_user;\n const tokenKey = remoteUser?.token?.key;\n\n if (!tokenKey) {\n return next();\n }\n\n const user = remoteUser?.name;\n\n if (typeof user !== 'string') {\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n try {\n const token = findToken(await storage.readTokens({ user }), tokenKey);\n\n if (!token) {\n logger.warn({ tokenKey, user }, 'generated token @{tokenKey} for user @{user} is missing');\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n if (!ipUtils.isAddressAllowed(getClientAddress(req), token.cidr)) {\n logger.warn(\n { tokenKey, user },\n 'generated token @{tokenKey} for user @{user} was used outside its CIDR whitelist'\n );\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n if (token.readonly && WRITE_METHODS.has(req.method)) {\n logger.warn(\n { tokenKey, user },\n 'readonly generated token @{tokenKey} for user @{user} was used for a write request'\n );\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n return next();\n } catch (error: any) {\n logger.error({ error: error.msg }, 'generated token metadata lookup failed: @{error}');\n return next(errorUtils.getInternalError(error.message));\n }\n };\n}\n"],"mappings":";;;;;;AAEA,IAAAA,KAAA,GAAAC,OAAA;AAKA,MAAMC,aAAa,GAAG,IAAIC,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;;AAEjE;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,gBAAgBA,CAACC,GAAY,EAAsB;EAC1D,MAAMC,YAAY,GAAGD,GAAG,CAACE,OAAO,CAAC,iBAAiB,CAAC;EAEnD,IAAIC,KAAK,CAACC,OAAO,CAACH,YAAY,CAAC,EAAE;IAC/B,OAAOI,aAAO,CAACC,gBAAgB,CAACL,YAAY,CAAC,CAAC,CAAC,EAAEM,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;EACjE;EAEA,IAAI,OAAON,YAAY,KAAK,QAAQ,EAAE;IACpC,OAAOI,aAAO,CAACC,gBAAgB,CAACL,YAAY,CAACM,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;EAC7D;EAEA,OAAOF,aAAO,CAACC,gBAAgB,CAACN,GAAG,CAACQ,EAAE,IAAIR,GAAG,CAACS,MAAM,CAACC,aAAa,CAAC;AACrE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,SAASA,CAACC,MAAe,EAAEC,QAAgB,EAAqB;EACvE,OAAOD,MAAM,CAACE,IAAI,CAAC,CAAC;IAAEC;EAAI,CAAC,KAAKA,GAAG,KAAKF,QAAQ,CAAC;AACnD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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MAAM,CAACa,IAAI,CACT;UAAElB,QAAQ;UAAEW;QAAK,CAAC,EAClB,oFACF,CAAC;QACD,OAAOJ,IAAI,CAACM,gBAAU,CAACC,YAAY,CAACC,eAAS,CAACC,mBAAmB,CAAC,CAAC;MACrE;MAEA,OAAOT,IAAI,CAAC,CAAC;IACf,CAAC,CAAC,OAAOiB,KAAU,EAAE;MACnBnB,MAAM,CAACmB,KAAK,CAAC;QAAEA,KAAK,EAAEA,KAAK,CAACC;MAAI,CAAC,EAAE,kDAAkD,CAAC;MACtF,OAAOlB,IAAI,CAACM,gBAAU,CAACa,gBAAgB,CAACF,KAAK,CAACG,OAAO,CAAC,CAAC;IACzD;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"token-auth.js","names":["_core","require","WRITE_METHODS","Set","getClientAddress","req","ipUtils","normalizeAddress","ip","socket","remoteAddress","findToken","tokens","tokenKey","find","key","enforceGeneratedTokenMetadata","storage","logger","_res","next","remoteUser","remote_user","token","user","name","errorUtils","getForbidden","API_ERROR","UNAUTHORIZED_ACCESS","readTokens","warn","isAddressAllowed","cidr","readonly","has","method","error","msg","getInternalError","message"],"sources":["../../src/middlewares/token-auth.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nimport { API_ERROR, errorUtils, ipUtils } from '@verdaccio/core';\nimport type { Logger, Token } from '@verdaccio/types';\n\nimport type { $RequestExtend } from '../types';\n\nconst WRITE_METHODS = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);\n\n/**\n * Minimal storage surface required to enforce generated token metadata. Typed\n * structurally so this package does not need to depend on `@verdaccio/store`.\n */\nexport interface TokenReadableStorage {\n /**\n * Load the generated tokens stored for a user.\n *\n * @param filter narrows the lookup to a single `user`\n * @returns the user's persisted tokens\n */\n readTokens(filter: { user: string }): Promise<Token[]>;\n}\n\n/**\n * Resolve the client address of an incoming request for CIDR matching.\n *\n * Uses Express' `req.ip`, which already honors the application's `trust proxy`\n * setting (`config.server.trustProxy`): when the operator has declared trusted\n * proxies, `req.ip` is the upstream-most untrusted address parsed from\n * `X-Forwarded-For`; otherwise it is the direct socket peer and the forwarded\n * header is ignored entirely.\n *\n * The middleware must NOT read `X-Forwarded-For` on its own — doing so\n * unconditionally would let any client spoof its address (and bypass a token's\n * CIDR whitelist) simply by sending the header. Falls back to the raw socket\n * address and is normalized (trimmed, IPv4-mapped IPv6 prefix stripped) via\n * {@link ipUtils.normalizeAddress}.\n *\n * @param req the incoming Express request\n * @returns the normalized client address, or `undefined` when none can be determined\n */\nfunction getClientAddress(req: Request): string | undefined {\n return ipUtils.normalizeAddress(req.ip || req.socket.remoteAddress);\n}\n\n/**\n * Find the stored token whose `key` matches the key carried by the request.\n *\n * @param tokens the tokens persisted for the authenticated user\n * @param tokenKey the key extracted from the presented generated token\n * @returns the matching {@link Token}, or `undefined` when it has been revoked / never existed\n */\nfunction findToken(tokens: Token[], tokenKey: string): Token | undefined {\n return tokens.find(({ key }) => key === tokenKey);\n}\n\n/**\n * Express middleware that enforces the metadata of npm-style generated tokens\n * (created via `POST /-/npm/v1/tokens`).\n *\n * A generated token embeds a server-issued `key` that is recovered from the\n * verified credentials as `remote_user.token.key`. This middleware looks that\n * key up in storage and rejects the request when the token:\n * - is missing from storage (revoked or never issued);\n * - is used from a client address outside its `cidr` whitelist;\n * - is `readonly` and the request uses a write method (`DELETE`/`PATCH`/`POST`/`PUT`).\n *\n * Requests that do not carry a generated token key (e.g. interactive logins)\n * pass through untouched. It must run after the JWT/auth middleware has\n * populated `remote_user`. Failures fail closed: a storage lookup error yields\n * an internal error rather than allowing the request.\n *\n * @param storage storage exposing {@link TokenReadableStorage.readTokens} to load the user's tokens\n * @param logger logger used to record rejected attempts and lookup failures\n * @returns an Express {@link RequestHandler} that calls `next()` to allow or `next(error)` to reject\n */\nexport function enforceGeneratedTokenMetadata(\n storage: TokenReadableStorage,\n logger: Logger\n): RequestHandler {\n return async function (req: Request, _res: Response, next: NextFunction): Promise<void> {\n const remoteUser = (req as $RequestExtend).remote_user;\n const tokenKey = remoteUser?.token?.key;\n\n if (!tokenKey) {\n return next();\n }\n\n const user = remoteUser?.name;\n\n if (typeof user !== 'string') {\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n try {\n const token = findToken(await storage.readTokens({ user }), tokenKey);\n\n if (!token) {\n logger.warn({ tokenKey, user }, 'generated token @{tokenKey} for user @{user} is missing');\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n if (!ipUtils.isAddressAllowed(getClientAddress(req), token.cidr)) {\n logger.warn(\n { tokenKey, user },\n 'generated token @{tokenKey} for user @{user} was used outside its CIDR whitelist'\n );\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n if (token.readonly && WRITE_METHODS.has(req.method)) {\n logger.warn(\n { tokenKey, user },\n 'readonly generated token @{tokenKey} for user @{user} was used for a write request'\n );\n return next(errorUtils.getForbidden(API_ERROR.UNAUTHORIZED_ACCESS));\n }\n\n return next();\n } catch (error: any) {\n logger.error({ error: error.msg }, 'generated token metadata lookup failed: @{error}');\n return next(errorUtils.getInternalError(error.message));\n }\n };\n}\n"],"mappings":";;;;;;AAEA,IAAAA,KAAA,GAAAC,OAAA;AAKA,MAAMC,aAAa,GAAG,IAAIC,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;;AAEjE;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,gBAAgBA,CAACC,GAAY,EAAsB;EAC1D,OAAOC,aAAO,CAACC,gBAAgB,CAACF,GAAG,CAACG,EAAE,IAAIH,GAAG,CAACI,MAAM,CAACC,aAAa,CAAC;AACrE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,SAASA,CAACC,MAAe,EAAEC,QA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,IAAI,CAACM,gBAAU,CAACC,YAAY,CAACC,eAAS,CAACC,mBAAmB,CAAC,CAAC;MACrE;MAEA,IAAIN,KAAK,CAACW,QAAQ,IAAIhC,aAAa,CAACiC,GAAG,CAAC9B,GAAG,CAAC+B,MAAM,CAAC,EAAE;QACnDlB,MAAM,CAACa,IAAI,CACT;UAAElB,QAAQ;UAAEW;QAAK,CAAC,EAClB,oFACF,CAAC;QACD,OAAOJ,IAAI,CAACM,gBAAU,CAACC,YAAY,CAACC,eAAS,CAACC,mBAAmB,CAAC,CAAC;MACrE;MAEA,OAAOT,IAAI,CAAC,CAAC;IACf,CAAC,CAAC,OAAOiB,KAAU,EAAE;MACnBnB,MAAM,CAACmB,KAAK,CAAC;QAAEA,KAAK,EAAEA,KAAK,CAACC;MAAI,CAAC,EAAE,kDAAkD,CAAC;MACtF,OAAOlB,IAAI,CAACM,gBAAU,CAACa,gBAAgB,CAACF,KAAK,CAACG,OAAO,CAAC,CAAC;IACzD;EACF,CAAC;AACH","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verdaccio/middleware",
3
- "version": "8.0.3",
3
+ "version": "8.0.4",
4
4
  "description": "Verdaccio Express Middleware",
5
5
  "main": "./build/index.js",
6
6
  "types": "build/index.d.ts",