Skip to content

Commit

Permalink
feat: add stringIdNonAmbiguous() (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrnagydavid authored Dec 10, 2024
1 parent c175218 commit 345d0ca
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/security/id.util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
stringIdBase62,
stringIdBase64,
stringIdBase64Url,
stringIdNonAmbiguous,
validate,
} from '../index'

Expand Down Expand Up @@ -91,3 +92,24 @@ test('stringIdBase64Url should have no padding', () => {
})
})
})

describe('stringIdNonAmbiguous', () => {
test('default size', () => {
const id = stringIdNonAmbiguous()
expect(id.length).toBe(16)
expect(id).not.toContain('0')
expect(id).not.toContain('O')
expect(id).not.toContain('I')
expect(id).not.toContain('l')
})

test('custom size', () => {
const id = stringIdNonAmbiguous(100)
expect(id.length).toBe(100)
expect(id).not.toContain('0')
expect(id).not.toContain('O')
expect(id).not.toContain('1')
expect(id).not.toContain('I')
expect(id).not.toContain('l')
})
})
11 changes: 11 additions & 0 deletions src/security/id.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import crypto from 'node:crypto'
import {
ALPHABET_ALPHANUMERIC,
ALPHABET_ALPHANUMERIC_LOWERCASE,
ALPHABET_NONAMBIGUOUS,
nanoIdCustomAlphabet,
} from './nanoid'

Expand Down Expand Up @@ -43,3 +44,13 @@ export function stringIdBase64(size = 16): string {
export function stringIdBase64Url(size = 16): string {
return crypto.randomBytes(size * 0.75).toString('base64url')
}

/**
* Generate cryptographically-secure string id with non-ambiguous characters only,
* e.g. missing O and 0, I and 1 and l etc.
*
* Default length is 16.
*/
export function stringIdNonAmbiguous(size = 16): string {
return stringId(size, ALPHABET_NONAMBIGUOUS)
}
1 change: 1 addition & 0 deletions src/security/nanoid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { randomFillSync } from 'node:crypto'

type RandomFn = (bytes: number) => Buffer

export const ALPHABET_NONAMBIGUOUS = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'
export const ALPHABET_NUMBER = '0123456789'
export const ALPHABET_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'
export const ALPHABET_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Expand Down

0 comments on commit 345d0ca

Please sign in to comment.