From dbede6d16cc043ee597f616681fb1b2660dbb8b1 Mon Sep 17 00:00:00 2001 From: Kevin Bot Date: Sat, 21 Nov 2026 04:12:12 +0900 Subject: [PATCH] fix: prevent prototype pollution via inherited parse results MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mri read previously parsed flags from a plain object without an own-property check, so a `--__proto__` flag replaced the prototype of its result and later flags could hand `Object.prototype` back to cac as an option value. Walking a dotted option name into that value then wrote onto `Object.prototype`, which the existing `UNSAFE_KEYS` check on key names does not catch. mri is no longer maintained, so it is now forked into `src/mri.ts`, trimmed to the options cac uses. Its result object has no prototype, so flags such as `--__proto__` or `--toString` are plain own keys. Parsing is otherwise unchanged, checked against mri 1.2.0 on randomly generated argv. mri's MIT notice is added to LICENSE. `setDotProp()` also stops descending into inherited members, so `--valueOf.x=1` no longer writes onto the built-in `Object.prototype.valueOf`. Reported-by: João Pereira --- LICENSE | 27 ++++++++++ package.json | 4 -- pnpm-lock.yaml | 3 -- src/cac.ts | 4 +- src/mri.ts | 117 ++++++++++++++++++++++++++++++++++++++++++++ src/utils.ts | 12 ++--- tests/index.test.ts | 26 ++++++++++ tsdown.config.ts | 15 +----- 8 files changed, 177 insertions(+), 31 deletions(-) create mode 100644 src/mri.ts diff --git a/LICENSE b/LICENSE index 0fa9bb51..afec841e 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,30 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +src/mri.ts is forked from mri (https://github.com/lukeed/mri), +distributed under the following license: + +The MIT License (MIT) + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/package.json b/package.json index 6063f1cd..0367b030 100644 --- a/package.json +++ b/package.json @@ -39,9 +39,6 @@ "release": "bumpp", "prepublishOnly": "pnpm build" }, - "inlinedDependencies": { - "mri": "1.2.0" - }, "devDependencies": { "@sxzz/eslint-config": "^8.7.0", "@sxzz/prettier-config": "^2.3.3", @@ -52,7 +49,6 @@ "bumpp": "^12.3.0", "eslint": "^10.12.0", "lint-staged": "^17.6.0", - "mri": "^1.2.0", "prettier": "^3.9.10", "simple-git-hooks": "^2.14.0", "tinyexec": "^1.3.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 748449ef..a8b3f359 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -193,9 +193,6 @@ importers: lint-staged: specifier: ^17.6.0 version: 17.6.0 - mri: - specifier: ^1.2.0 - version: 1.2.0 prettier: specifier: ^3.9.10 version: 3.9.10 diff --git a/src/cac.ts b/src/cac.ts index 375ff6cd..c9485afe 100644 --- a/src/cac.ts +++ b/src/cac.ts @@ -1,4 +1,3 @@ -import mri from 'mri' import { Command, GlobalCommand, @@ -6,6 +5,7 @@ import { type CommandExample, type HelpCallback, } from './command.ts' +import { mri } from './mri.ts' import { getRuntimeProcessArgs } from './runtime.ts' import { camelcaseOptionName, @@ -280,7 +280,7 @@ export class CAC extends EventTarget { argv = argv.slice(0, doubleDashesIndex) } - let parsed = mri(argv, mriOptions) + let parsed: Record = mri(argv, mriOptions) parsed = Object.keys(parsed).reduce( (res, name) => { return { diff --git a/src/mri.ts b/src/mri.ts new file mode 100644 index 00000000..7eb6b79f --- /dev/null +++ b/src/mri.ts @@ -0,0 +1,117 @@ +// Forked from mri v1.2.0 (https://github.com/lukeed/mri), trimmed to the +// options cac uses and hardened against prototype pollution. +// mri is MIT licensed, see its notice in the LICENSE file. + +export interface MriOptions { + alias: Record + boolean: string[] +} + +export interface MriResult { + _: string[] + [k: string]: any +} + +function isNumeric(val: string): boolean { + return Number.isFinite(+val) +} + +function toVal( + out: MriResult, + key: string, + val: string | boolean, + booleans: string[], +): void { + let next: string | number | boolean + if (typeof val === 'boolean') { + next = val + } else if (booleans.includes(key)) { + if (val === 'false') { + next = false + } else if (val === 'true') { + next = true + } else { + // A boolean flag does not take a value, so it goes back to the args + out._.push((isNumeric(val) ? +val : val) as string) + next = !!val + } + } else { + next = isNumeric(val) ? +val : val + } + + // `out` has no prototype, so `old` is never an inherited member + const old = out[key] + out[key] = + old == null ? next : Array.isArray(old) ? old.concat(next) : [old, next] +} + +export function mri(args: string[], opts: MriOptions): MriResult { + // A prototype-less result keeps flags like `--__proto__` or `--toString` + // as plain own keys, instead of reading or replacing inherited members + const out: MriResult = Object.create(null) + out._ = [] + + const aliases: Record = Object.create(null) + Object.assign(aliases, opts.alias) + for (const name of Object.keys(aliases)) { + // Read from `aliases` rather than `opts.alias`: an earlier entry may + // already have replaced this one, as upstream mri does + const list = aliases[name] + for (const [i, alias] of list.entries()) { + aliases[alias] = [...list.slice(0, i), ...list.slice(i + 1), name] + } + } + + const booleans = [...opts.boolean] + for (const name of opts.boolean) { + const list = aliases[name] + if (list) booleans.push(...list) + } + + for (let i = 0; i < args.length; i++) { + const arg = args[i] + + if (arg === '--') { + out._ = out._.concat(args.slice(i + 1)) + break + } + + let dashes = 0 + while (arg[dashes] === '-') dashes++ + + if (dashes === 0) { + out._.push(arg) + continue + } + + if (arg.slice(dashes, dashes + 3) === 'no-') { + out[arg.slice(dashes + 3)] = false + continue + } + + let eq = dashes + 1 + while (eq < arg.length && arg[eq] !== '=') eq++ + + const name = arg.slice(dashes, eq) + const val: string | boolean = + arg.slice(eq + 1) || + i + 1 === args.length || + String(args[i + 1]).startsWith('-') || + args[++i] + + // `--foo` is one flag, while `-abc` is three short flags + // where only the last one takes the value + const names = dashes === 2 ? [name] : name.split('') + for (const [idx, flag] of names.entries()) { + toVal(out, flag, idx + 1 < names.length || val, booleans) + } + } + + for (const key of Object.keys(out)) { + const list = aliases[key] + if (!list) continue + for (const alias of list) out[alias] = out[key] + } + + return out +} diff --git a/src/utils.ts b/src/utils.ts index 099642ea..6fe0bac1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,4 @@ +import type { MriOptions } from './mri.ts' import type { Option } from './option.ts' export function removeBrackets(v: string): string { @@ -41,13 +42,6 @@ export function findAllBrackets(v: string): { return res } -interface MriOptions { - alias: { - [k: string]: string[] - } - boolean: string[] -} - export function getMriOptions(options: Option[]): MriOptions { // `alias` is looked up by user-provided option names inside mri, // so it must not inherit from `Object.prototype` @@ -121,7 +115,9 @@ export function setDotProp( return } - if (current[key] == null) { + // Inherited members (e.g. `toString`) are shared built-ins, + // so descending into them would mutate global objects + if (!Object.hasOwn(current, key) || current[key] == null) { const nextKey = keys[i + 1] const nextKeyIsArrayIndex = +nextKey > -1 current[key] = nextKeyIsArrayIndex ? [] : {} diff --git a/tests/index.test.ts b/tests/index.test.ts index 6927d442..68e7086f 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -244,6 +244,32 @@ test('ignore prototype polluting option names', () => { expect(options).toEqual({ '--': [] }) }) +test('ignore inherited members while parsing options', () => { + // `--__proto__=x` used to swap the prototype of mri's result, so `--0=x` + // read `Object.prototype` from it and `--0.0.polluted` wrote onto it. + // The value conflict left behind still throws, same as `--a=1 --a.b=2` + expect(() => + cac().parse(`node bin --__proto__=x --0=x --0.0.polluted=yes`.split(' ')), + ).toThrow(TypeError) + expect(({} as any).polluted).toBeUndefined() + expect(([] as any).polluted).toBeUndefined() + + const { options } = cac().parse( + `node bin --toString=x --valueOf.polluted=yes --a.hasOwnProperty.polluted=yes`.split( + ' ', + ), + ) + + expect((Object.prototype.valueOf as any).polluted).toBeUndefined() + expect((Object.prototype.hasOwnProperty as any).polluted).toBeUndefined() + expect(options).toEqual({ + '--': [], + toString: 'x', + valueOf: { polluted: 'yes' }, + a: { hasOwnProperty: { polluted: 'yes' } }, + }) +}) + test('dot-nested option names', () => { const cli = cac() diff --git a/tsdown.config.ts b/tsdown.config.ts index fe690641..8c16298f 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,16 +1,3 @@ import { lib } from 'tsdown-preset-sxzz' -export default lib( - { - inlineDeps: ['mri'], - }, - { - inputOptions: { - resolve: { - alias: { - mri: 'mri/lib/index.mjs', - }, - }, - }, - }, -) +export default lib()