SPB Git

Repository Public

generator.ts 6.7 KB 106 lines typescript

1// Password / passphrase generator (unbiased rejection sampling over the OS CSPRNG) and TOTP (RFC 6238).2import { type Bytes, random } from "./bytes.ts";34/** Uniform integer in [0, n) by rejection sampling; never uses a biased modulo and never Math.random. */5export function uniform(n: number, rnd: (len: number) => Bytes = random): number {6  if (!Number.isInteger(n) || n < 1 || n > 0x1_0000_0000) throw new Error("invalid range");7  if (n === 1) return 0;8  const limit = Math.floor(0x1_0000_0000 / n) * n;9  for (;;) {10    const b = rnd(4);11    const x = ((b[0]! << 24) | (b[1]! << 16) | (b[2]! << 8) | b[3]!) >>> 0;12    if (x < limit) return x % n;13  }14}1516export const SETS = {17  lower: "abcdefghijklmnopqrstuvwxyz", upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", digits: "0123456789",18  symbols: "!@#$%^&*()-_=+[]{};:,.<>/?~",19} as const;20const AMBIGUOUS = new Set("Il1O0o|`'\"");2122export interface PasswordOptions { length: number; lower: boolean; upper: boolean; digits: boolean; symbols: boolean; avoidAmbiguous?: boolean }23export const DEFAULT_PASSWORD: PasswordOptions = { length: 24, lower: true, upper: true, digits: true, symbols: true, avoidAmbiguous: false };2425function alphabets(o: PasswordOptions): string[] {26  const sets = (Object.keys(SETS) as (keyof typeof SETS)[]).filter((k) => o[k]).map((k) => SETS[k]);27  return sets.map((s) => (o.avoidAmbiguous ? [...s].filter((c) => !AMBIGUOUS.has(c)).join("") : s)).filter((s) => s.length > 0);28}2930export function generatePassword(o: PasswordOptions = DEFAULT_PASSWORD, rnd: (len: number) => Bytes = random): string {31  const sets = alphabets(o);32  if (sets.length === 0) throw new Error("select at least one character set");33  if (!Number.isInteger(o.length) || o.length < Math.max(4, sets.length) || o.length > 256) throw new Error("length must be between 4 and 256");34  const all = sets.join("");35  // Rejection on the whole password keeps the distribution uniform over "passwords containing every selected class".36  for (;;) {37    let out = "";38    for (let i = 0; i < o.length; i++) out += all[uniform(all.length, rnd)];39    if (sets.every((s) => [...out].some((c) => s.includes(c)))) return out;40  }41}4243/** Entropy in bits of the generator's output space (upper bound; the class constraint removes a negligible part). */44export function passwordEntropyBits(o: PasswordOptions): number {45  const n = alphabets(o).join("").length;46  return n > 1 ? o.length * Math.log2(n) : 0;47}4849export interface PassphraseOptions { words: number; separator: string; capitalize: boolean; number: boolean }50export const DEFAULT_PASSPHRASE: PassphraseOptions = { words: 6, separator: "-", capitalize: false, number: false };5152export function generatePassphrase(wordlist: readonly string[], o: PassphraseOptions = DEFAULT_PASSPHRASE, rnd: (len: number) => Bytes = random): string {53  if (wordlist.length !== 7776) throw new Error("wordlist must be the 7776-word EFF list");54  if (!Number.isInteger(o.words) || o.words < 3 || o.words > 20) throw new Error("words must be between 3 and 20");55  const words = Array.from({ length: o.words }, () => wordlist[uniform(wordlist.length, rnd)]!).map((w) => (o.capitalize ? w[0]!.toUpperCase() + w.slice(1) : w));56  if (o.number) { const i = uniform(words.length, rnd); words[i] = words[i]! + String(uniform(10, rnd)); }57  return words.join(o.separator);58}59export const passphraseEntropyBits = (o: PassphraseOptions) => o.words * Math.log2(7776) + (o.number ? Math.log2(10 * o.words) : 0);6061export function entropyGuidance(bits: number): { level: "weak" | "fair" | "strong" | "excellent"; text: string } {62  if (bits < 50) return { level: "weak", text: "Guessable offline. Use only where a PIN-like value is imposed." };63  if (bits < 75) return { level: "fair", text: "Acceptable for online accounts with rate limiting." };64  if (bits < 100) return { level: "strong", text: "Resists offline attack on a leaked hash." };65  return { level: "excellent", text: "Beyond any practical guessing attack." };66}6768// ── TOTP ──────────────────────────────────────────────────────────────────────────────────────────────────────6970export interface TotpParams { secret: Bytes; digits: number; period: number; algorithm: "SHA-1" | "SHA-256" | "SHA-512"; issuer?: string; account?: string }7172export function base32Decode(s: string): Bytes {73  const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";74  const clean = s.toUpperCase().replace(/[\s=-]/g, "");75  if (!clean || [...clean].some((c) => !A.includes(c))) throw new Error("invalid base32 secret");76  const out: number[] = [];77  let bits = 0, acc = 0;78  for (const c of clean) { acc = (acc << 5) | A.indexOf(c); bits += 5; if (bits >= 8) { out.push((acc >> (bits - 8)) & 0xff); bits -= 8; acc &= (1 << bits) - 1; } }79  return new Uint8Array(out);80}8182/** Accepts an otpauth://totp/… URI or a bare base32 secret. */83export function parseTotp(value: string): TotpParams {84  const v = value.trim();85  if (!/^otpauth:\/\//i.test(v)) return { secret: base32Decode(v), digits: 6, period: 30, algorithm: "SHA-1" };86  const u = new URL(v);87  if (u.protocol !== "otpauth:" || u.host.toLowerCase() !== "totp") throw new Error("only otpauth://totp is supported");88  const p = u.searchParams, alg = (p.get("algorithm") ?? "SHA1").toUpperCase().replace(/^SHA-?/, "SHA-");89  if (alg !== "SHA-1" && alg !== "SHA-256" && alg !== "SHA-512") throw new Error("unsupported TOTP algorithm");90  const digits = Number(p.get("digits") ?? 6), period = Number(p.get("period") ?? 30);91  if (![6, 7, 8].includes(digits) || !Number.isInteger(period) || period < 5 || period > 300) throw new Error("unsupported TOTP parameters");92  const label = decodeURIComponent(u.pathname.replace(/^\//, ""));93  return { secret: base32Decode(p.get("secret") ?? ""), digits, period, algorithm: alg, issuer: p.get("issuer") ?? (label.includes(":") ? label.split(":")[0] : undefined), account: label.includes(":") ? label.split(":").slice(1).join(":").trim() : label || undefined };94}9596export async function totp(p: TotpParams, atMs: number = Date.now()): Promise<{ code: string; remaining: number }> {97  const counter = Math.floor(atMs / 1000 / p.period);98  const msg = new Uint8Array(8);99  new DataView(msg.buffer).setBigUint64(0, BigInt(counter));100  const key = await crypto.subtle.importKey("raw", p.secret as unknown as BufferSource, { name: "HMAC", hash: p.algorithm }, false, ["sign"]);101  const h = new Uint8Array(await crypto.subtle.sign("HMAC", key, msg));102  const o = h[h.length - 1]! & 0xf;103  const bin = ((h[o]! & 0x7f) << 24) | (h[o + 1]! << 16) | (h[o + 2]! << 8) | h[o + 3]!;104  return { code: String(bin % 10 ** p.digits).padStart(p.digits, "0"), remaining: p.period - (Math.floor(atMs / 1000) % p.period) };105}106
Files main
Menu

Theme