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/lazy-locations-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/history': patch
---

Avoid generating unused history keys for locations with existing state.
8 changes: 5 additions & 3 deletions packages/history/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -697,8 +697,10 @@ export function parseHref(
const sanitizedHref = normalizeHref(href)
const hashIndex = sanitizedHref.indexOf('#')
const searchIndex = sanitizedHref.indexOf('?')

const addedKey = createRandomKey()
if (!state) {
const key = createRandomKey()
state = { [stateIndexKey]: 0, key, __TSR_key: key }
}

return {
href: sanitizedHref,
Expand All @@ -720,7 +722,7 @@ export function parseHref(
hashIndex === -1 ? undefined : hashIndex,
)
: '',
state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey },
state,
}
}

Expand Down
24 changes: 24 additions & 0 deletions packages/history/tests/parseHref.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,30 @@ describe('parseHref', () => {
expect(parsed.hash).toEqual('#qux')
})

test.each([
{ __TSR_index: 2 },
{ __TSR_index: 2, key: 'legacy-key', __TSR_key: 'current-key' },
])('preserves supplied state %j', (state) => {
Object.freeze(state)
expect(parseHref('/foo', state).state).toBe(state)
})

test('creates independent initial states with matching history keys', () => {
const first = parseHref('/foo', undefined)
const second = parseHref('/bar', undefined)

for (const location of [first, second]) {
expect(location.state).toEqual({
__TSR_index: 0,
key: expect.any(String),
__TSR_key: location.state.key,
})
}

first.state.__TSR_index = 1
expect(second.state.__TSR_index).toBe(0)
})

describe('open redirect prevention', () => {
test('strips CR characters to prevent open redirect', () => {
// If \r (CR) is in the href, it should be stripped
Expand Down
Loading