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

feat: add stringIdNonAmbiguous() #24

Merged
merged 1 commit into from
Dec 10, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading