Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix collision by proxy number #328

Merged
merged 1 commit into from Jan 11, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions index.js
Expand Up @@ -23,7 +23,8 @@ let fillPool = bytes => {
}

let random = bytes => {
fillPool(bytes)
// `-=` convert `bytes` to number to prevent `valueOf` abusing
fillPool((bytes -= 0))
return pool.subarray(poolOffset - bytes, poolOffset)
}

Expand Down Expand Up @@ -65,7 +66,8 @@ let customRandom = (alphabet, size, getRandom) => {
let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)

let nanoid = (size = 21) => {
fillPool(size)
// `-=` convert `size` to number to prevent `valueOf` abusing
fillPool((size -= 0))
let id = ''
// We are reading directly from the random pool to avoid creating new array
for (let i = poolOffset - size; i < poolOffset; i++) {
Expand Down
36 changes: 36 additions & 0 deletions test/index.test.js
Expand Up @@ -151,5 +151,41 @@ for (let type of ['node', 'browser']) {
}
})
})

if (type === 'node') {
describe('proxy number', () => {
it('prevent collision', () => {
let makeProxyNumberToReproducePreviousID = () => {
let step = 0
return {
valueOf() {
// "if (!pool || pool.length < bytes) {"
if (step === 0) {
step++
return 0
}
// "} else if (poolOffset + bytes > pool.length) {"
if (step === 1) {
step++
return -Infinity
}
// "poolOffset += bytes"
if (step === 2) {
step++
return 0
}

return 21
}
}
}

let ID1 = nanoid()
let ID2 = nanoid(makeProxyNumberToReproducePreviousID())

expect(ID1).not.toBe(ID2)
})
})
}
})
}