Skip to content

A top-level number at the end of the input is never emitted (no way to signal end of input) #50

Open

Description

@joszamama

When the input ends right after a top-level number, onValue is never called for it. The tokenizer only knows a number is complete when it sees a byte that cannot continue it, and the parser has no end() (or similar) method to say that no more bytes will come. Strings, literals, arrays and objects at the top level are emitted as soon as their last byte is written. So a stream or file whose whole content is a number (a valid JSON text) gives no value, and the caller cannot tell it apart from empty input.

Environment: jsonparse 1.3.1 (npm) and master at b2d8bc6, Node 26.10.0, macOS 27.0.1.

The five inputs are the JSON texts 1 (1 byte), 1 followed by a newline, "a", true and [1]. The script prints each one before the values it got. Paste into an empty folder:

npm install --ignore-scripts jsonparse@1.3.1 >/dev/null
echo 'MQ==' | base64 -d > number.json
echo 'MQo=' | base64 -d > number-newline.json
echo 'ImEi' | base64 -d > string.json
echo 'dHJ1ZQ==' | base64 -d > true.json
echo 'WzFd' | base64 -d > array.json
cat > repro.js <<'EOF'
const { readFileSync } = require('node:fs')
const Parser = require('jsonparse')

for (const file of process.argv.slice(2)) {
  const bytes = readFileSync(file)
  const p = new Parser()
  const values = []
  p.onValue = function (value) { if (this.stack.length === 0) values.push(value) }
  p.write(bytes)
  console.log(file.padEnd(20), JSON.stringify(bytes.toString()).padEnd(8), '->', JSON.stringify(values))
}
console.log('typeof Parser.prototype.end:', typeof Parser.prototype.end)
EOF
node repro.js number.json number-newline.json string.json true.json array.json

Output:

number.json          "1"      -> []
number-newline.json  "1\n"    -> [1]
string.json          "\"a\""  -> ["a"]
true.json            "true"   -> [true]
array.json           "[1]"    -> [[1]]
typeof Parser.prototype.end: undefined

Expected: [1] for number.json once the end of input is signalled. RFC 8259, section 2: "A JSON text is a serialized value", and a number is a value.

Cause: the NUMBER1/NUMBER3 branch of write (jsonparse.js L240-L281 in 1.3.1, L244-L277 on master) appends digits and emits the token only from its default: case, when a non-number byte arrives; nothing else flushes this.string.

I found this with the Fandango fuzzer.

Fix: #51

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions