Skip to content

Commit

Permalink
fix collision by proxy number
Browse files Browse the repository at this point in the history
  • Loading branch information
artalar committed Jan 11, 2022
1 parent 3b56634 commit 397c549
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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)
})
})
}
})
}

0 comments on commit 397c549

Please sign in to comment.