Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -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 <luke.edwards05@gmail.com> (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.
4 changes: 0 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/cac.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import mri from 'mri'
import {
Command,
GlobalCommand,
type CommandConfig,
type CommandExample,
type HelpCallback,
} from './command.ts'
import { mri } from './mri.ts'
import { getRuntimeProcessArgs } from './runtime.ts'
import {
camelcaseOptionName,
Expand Down Expand Up @@ -280,7 +280,7 @@ export class CAC extends EventTarget {
argv = argv.slice(0, doubleDashesIndex)
}

let parsed = mri(argv, mriOptions)
let parsed: Record<string, any> = mri(argv, mriOptions)
parsed = Object.keys(parsed).reduce(
(res, name) => {
return {
Expand Down
117 changes: 117 additions & 0 deletions src/mri.ts
Original file line number Diff line number Diff line change
@@ -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<string, string[]>
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<string, string[]> = 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
}
12 changes: 4 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { MriOptions } from './mri.ts'
import type { Option } from './option.ts'

export function removeBrackets(v: string): string {
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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 ? [] : {}
Expand Down
26 changes: 26 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
15 changes: 1 addition & 14 deletions tsdown.config.ts
Original file line number Diff line number Diff line change
@@ -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()
Loading