Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 96 ยท Projects

Project: Password Generator and Unicode Finder

Build two small tools in TypeScript - a secure password generator using crypto.getRandomValues with typed options and entropy, and a Unicode finder that inspects code points and graphemes.

This project builds two small utilities that look unrelated but share a theme: text is more subtle than it seems. A password generator must use real randomness and avoid subtle bias. A Unicode finder has to cope with the fact that one visible character can be several code units, or several code points.

Along the way you will practice typing an options object, using readonly tuples and as const for character sets, writing a small unbiased random helper over crypto.getRandomValues, narrowing user input, and working with codePointAt, String.fromCodePoint, Unicode property escapes and Intl.Segmenter. Everything runs in the editor; the same code works in a browser, because crypto.getRandomValues is a Web API that Node supports too.

Stage 1: secure random numbers

Math.random() is not suitable for passwords. It is predictable by design. The Web Crypto API offers crypto.getRandomValues, which fills a typed array with cryptographically strong random numbers.

Picking a random index sounds easy, but random % n introduces modulo bias: when 2^32 is not a multiple of n, small values appear slightly more often. The fix is rejection sampling: throw away values from the unfair tail of the range.

TypeScript Stage 1: an unbiased secure random helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that pick accepts a readonly T[], so you can hand it frozen arrays and as const tuples, and it never mutates its input. shuffle copies first for the same reason.

Stage 2: the password generator

A password policy is a bundle of options. Typing them well prevents invalid combinations. We use a literal union for character classes and a Record for their alphabets:

TypeScript Stage 2: typed options, guaranteed classes and entropy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The tuple type readonly [CharClass, ...CharClass[]] means "at least one element", so an empty list of classes is rejected at compile time (see the commented line). Entropy is length x log2(pool size): a 16-character password drawn from about 80 symbols carries roughly 100 bits. This estimate is only valid for passwords generated randomly like this; it says nothing about passwords a human invented.

The guarantee step is a design decision. Forcing one character from each class slightly reduces entropy compared with pure random picks, but it satisfies the "must contain a digit" rules many sites impose. Because we shuffle afterwards, no one can predict where those characters sit.

Never log or store generated passwords in real applications, and never send them over analytics. This demo prints one only to show the shape of the result.

Stage 3: the Unicode finder

Strings in JavaScript are sequences of UTF-16 code units, so '๐Ÿ˜€'.length is 2. A code point is one Unicode character number, such as U+1F600, and a grapheme cluster is what a person sees as one character, which may be several code points (a flag, or e plus a combining accent).

The finder accepts text, or a code point written as U+1F600, and reports what it finds. Input is parsed into a discriminated union so each case is handled separately:

TypeScript Stage 3: inspecting characters, code points and graphemes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Three details are worth a second look. [...text] iterates by code point, not by code unit, so an emoji counts once. codePointAt(0) returns number | undefined for strings, which is why the code asserts as number for a character we just took from the iterator; with a guard instead you would avoid the assertion. And Intl.Segmenter is the correct way to count what a user sees: the accented e is 2 code points but 1 grapheme, and the Japan flag is 2 code points but 1 grapheme.

The property escapes (\p{Lu}, \p{Sc}) need the u flag. They ask the Unicode database for characters with a property, so they cover every script without you listing ranges.

Extending the project

  • Add a passphrase mode that picks random words from a list (each word from a 7,776-word list gives 12.9 bits).
  • Add a copy-to-clipboard button (browser only; remember the clipboard is unavailable in the sandboxed editors).
  • Add a name search to the Unicode finder with a small Map<string, number> of common characters.
  • Normalize text with text.normalize('NFC') and show that eฬ and รฉ become the same string.
  • Turn the options into a discriminated union ({ mode: 'random'; ... } | { mode: 'passphrase'; words: number }) and write one generate function that switches on mode.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is Math.random() a poor choice for generating passwords?

    Use crypto.getRandomValues, which draws from the operating system's secure random source.
  2. 2. What does rejection sampling in randomInt prevent?

    When 2^32 is not a multiple of n, value % n favors small results. Rejecting the tail makes every result equally likely.
  3. 3. What does the type readonly [CharClass, ...CharClass[]] guarantee?

    A tuple with a required first element and a rest element means "one or more".
  4. 4. What is '๐Ÿ˜€'.length in JavaScript?

    The emoji lies outside the Basic Multilingual Plane, so UTF-16 stores it as a surrogate pair of two code units.
  5. 5. Which API counts the characters a person actually sees?

    Grapheme clusters can contain several code points, such as a flag or a letter with a combining accent.

Summary

  • Use crypto.getRandomValues for secrets, and remove modulo bias with rejection sampling.
  • Model options with literal unions, Record and tuple types; a rest tuple can enforce "at least one" at compile time.
  • Entropy is length x log2(pool size) for random passwords and says nothing about human-chosen ones.
  • JavaScript strings are UTF-16: code units, code points and grapheme clusters are different counts.
  • codePointAt, String.fromCodePoint, \p{...} escapes and Intl.Segmenter are the tools for inspecting text.
  • Parse free-form input into a discriminated union so each case is handled and checked.

Next: Project: Typing Speed Test