Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/big-integer-search-params.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/router-core': patch
---

fix: preserve integer search param literals beyond Number.MAX_SAFE_INTEGER as strings — JSON.parse silently rounds them (e.g. an 18-digit ad id `120247103250460643` becomes `120247103250460640`), corrupting the value on any redirect or link re-serialization
22 changes: 20 additions & 2 deletions packages/router-core/src/searchParams.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
import { decode, encode } from './qss'
import type { AnySchema } from './validators'

const integerLiteralRegex = /^-?\d+$/

/**
* `JSON.parse`, except integer literals beyond `Number.MAX_SAFE_INTEGER` are
* rejected (kept as strings by the callers below): parsing them to a float64
* silently rounds the value (e.g. "120247103250460643" becomes
* 120247103250460640), so any re-serialization corrupts the original — a
* common hazard with 18-digit ad/click ids in marketing URLs.
*/
function parseJsonPreservingUnsafeIntegers(str: string): any {
if (integerLiteralRegex.test(str) && !Number.isSafeInteger(Number(str))) {
throw new Error('Integer literal exceeds safe integer range')
}
return JSON.parse(str)
}
Comment on lines +4 to +18

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Account for leading and trailing whitespace in safety checks.

JSON.parse natively ignores leading and trailing whitespace. A value like ?foo=%20120247103250460643%20 will bypass the strict regex check due to the spaces, but will still be successfully parsed and silently rounded by JSON.parse, ultimately corrupting the value on re-serialization.

Updating the regex to allow whitespace ensures these values are properly protected. Number() natively parses whitespace-padded numbers, so the check inside the function will continue to work exactly as expected.

🛡️ Proposed fix to handle whitespace
-const integerLiteralRegex = /^-?\d+$/
+const integerLiteralRegex = /^\s*-?\d+\s*$/
 
 /**
  * `JSON.parse`, except integer literals beyond `Number.MAX_SAFE_INTEGER` are
  * rejected (kept as strings by the callers below): parsing them to a float64
  * silently rounds the value (e.g. "120247103250460643" becomes
  * 120247103250460640), so any re-serialization corrupts the original — a
  * common hazard with 18-digit ad/click ids in marketing URLs.
  */
 function parseJsonPreservingUnsafeIntegers(str: string): any {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const integerLiteralRegex = /^-?\d+$/
/**
* `JSON.parse`, except integer literals beyond `Number.MAX_SAFE_INTEGER` are
* rejected (kept as strings by the callers below): parsing them to a float64
* silently rounds the value (e.g. "120247103250460643" becomes
* 120247103250460640), so any re-serialization corrupts the original a
* common hazard with 18-digit ad/click ids in marketing URLs.
*/
function parseJsonPreservingUnsafeIntegers(str: string): any {
if (integerLiteralRegex.test(str) && !Number.isSafeInteger(Number(str))) {
throw new Error('Integer literal exceeds safe integer range')
}
return JSON.parse(str)
}
const integerLiteralRegex = /^\s*-?\d+\s*$/
/**
* `JSON.parse`, except integer literals beyond `Number.MAX_SAFE_INTEGER` are
* rejected (kept as strings by the callers below): parsing them to a float64
* silently rounds the value (e.g. "120247103250460643" becomes
* 120247103250460640), so any re-serialization corrupts the original a
* common hazard with 18-digit ad/click ids in marketing URLs.
*/
function parseJsonPreservingUnsafeIntegers(str: string): any {
if (integerLiteralRegex.test(str) && !Number.isSafeInteger(Number(str))) {
throw new Error('Integer literal exceeds safe integer range')
}
return JSON.parse(str)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/router-core/src/searchParams.ts` around lines 4 - 18, Update
integerLiteralRegex used by parseJsonPreservingUnsafeIntegers to match JSON
integer literals with leading and trailing whitespace, while preserving the
existing optional-negative-sign and digit constraints. Keep the
Number.isSafeInteger(Number(str)) validation and JSON.parse behavior unchanged.


/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
export const defaultParseSearch = parseSearchWith(JSON.parse)
export const defaultParseSearch = parseSearchWith(
parseJsonPreservingUnsafeIntegers,
)
/** Default `stringifySearch` using JSON.stringify for complex values. */
export const defaultStringifySearch = stringifySearchWith(
JSON.stringify,
JSON.parse,
parseJsonPreservingUnsafeIntegers,
)

/**
Expand Down
26 changes: 26 additions & 0 deletions packages/router-core/tests/searchParams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,29 @@ describe('Search Params serialization and deserialization', () => {
)
})
})

describe('Unsafe integer literals', () => {
/*
* Integer literals beyond Number.MAX_SAFE_INTEGER cannot survive a trip
* through float64 — JSON.parse would silently round them (e.g. an 18-digit
* ad id "120247103250460643" becomes 120247103250460640). They are kept as
* strings so they round-trip losslessly.
*/
test.each([
['120247103250460643'],
['-120247103250460643'],
['9007199254740993'],
])('unsafe integer literal %s is preserved as a string', (literal) => {
const parsed = defaultParseSearch(`?foo=${literal}`)
expect(parsed).toEqual({ foo: literal })
const restringified = defaultStringifySearch(parsed)
expect(defaultParseSearch(restringified)).toEqual({ foo: literal })
})

test('safe integer literals still parse as numbers', () => {
expect(defaultParseSearch('?foo=123')).toEqual({ foo: 123 })
expect(defaultParseSearch(`?foo=${Number.MAX_SAFE_INTEGER}`)).toEqual({
foo: Number.MAX_SAFE_INTEGER,
})
})
})