SPB Git

Repository Public

analysis.ts 4.5 KB 88 lines typescript

1// Local security analysis (weak / reused / duplicate / expiring) and privacy-preserving breach lookup helpers.2import { type Item, primarySecret } from "./items.ts";3import { parseOrigin } from "./urlmatch.ts";4import { hex } from "./bytes.ts";56const COMMON = new Set(["password", "123456", "123456789", "qwerty", "azerty", "111111", "12345678", "abc123", "password1", "iloveyou", "admin", "letmein", "welcome", "monkey", "dragon", "football", "motdepasse", "soleil", "bonjour", "changeme", "secret", "passw0rd", "p@ssw0rd", "000000", "1q2w3e4r", "qwertyuiop"]);78/** Conservative strength estimate in bits (heuristic, local, no dictionary upload). */9export function estimateBits(pw: string): number {10  if (!pw) return 0;11  const lower = pw.toLowerCase();12  if (COMMON.has(lower) || COMMON.has(lower.replace(/\d+$/, ""))) return 8;13  let pool = 0;14  if (/[a-z]/.test(pw)) pool += 26;15  if (/[A-Z]/.test(pw)) pool += 26;16  if (/\d/.test(pw)) pool += 10;17  if (/[^A-Za-z0-9]/.test(pw)) pool += 30;18  const chars = [...pw];19  // repeated characters and straight sequences contribute little20  let effective = 0;21  for (let i = 0; i < chars.length; i++) {22    const c = chars[i]!.codePointAt(0)!, p = i > 0 ? chars[i - 1]!.codePointAt(0)! : -99;23    effective += c === p || Math.abs(c - p) === 1 ? 0.25 : 1;24  }25  const unique = new Set(chars).size;26  return Math.round(Math.min(effective, unique * 2.5) * Math.log2(Math.max(pool, 2)));27}2829export type Finding =30  | { kind: "weak"; id: string; bits: number }31  | { kind: "reused"; ids: string[] }32  | { kind: "duplicate"; ids: string[] }33  | { kind: "insecure-url"; id: string }34  | { kind: "expiring"; id: string; expiresAt: string; expired: boolean }35  | { kind: "rotation-due"; id: string; dueAt: string }36  | { kind: "breached"; id: string; count: number };3738export function analyze(items: { id: string; item: Item }[], now = Date.now()): Finding[] {39  const out: Finding[] = [];40  const byPassword = new Map<string, string[]>(), byAccount = new Map<string, string[]>();41  for (const { id, item } of items) {42    if (item.trashedAt || item.deleted) continue;43    const pw = item.type === "login" || item.type === "wifi" || item.type === "database" ? item.fields.password : undefined;44    if (pw) {45      const bits = estimateBits(pw);46      if (bits < 50) out.push({ kind: "weak", id, bits });47      if (item.type === "login") byPassword.set(pw, [...(byPassword.get(pw) ?? []), id]);48    }49    if (item.type === "login") {50      for (const u of item.urls) {51        const o = parseOrigin(u.url);52        if (o && /^http:\/\//i.test(u.url.trim()) && o.host !== "localhost") { out.push({ kind: "insecure-url", id }); break; }53      }54      const d = item.urls.map((u) => parseOrigin(u.url)?.domain).find(Boolean);55      if (d && item.fields.username) { const k = `${d}\n${item.fields.username.toLowerCase()}`; byAccount.set(k, [...(byAccount.get(k) ?? []), id]); }56    }57    if (item.expiresAt) {58      const t = Date.parse(item.expiresAt);59      if (!Number.isNaN(t) && t - now < 30 * 86400_000) out.push({ kind: "expiring", id, expiresAt: item.expiresAt, expired: t < now });60    }61    if (item.rotateEveryDays && primarySecret(item)) {62      const last = item.passwordHistory.length ? Date.parse(item.passwordHistory[item.passwordHistory.length - 1]!.at) : Date.parse(item.createdAt);63      const due = last + item.rotateEveryDays * 86400_000;64      if (due < now) out.push({ kind: "rotation-due", id, dueAt: new Date(due).toISOString() });65    }66  }67  for (const ids of byPassword.values()) if (ids.length > 1) out.push({ kind: "reused", ids });68  for (const ids of byAccount.values()) if (ids.length > 1) out.push({ kind: "duplicate", ids });69  return out;70}7172/**73 * Breach check, k-anonymity model (Have I Been Pwned "range" API): only the first 5 hex characters of SHA-1(password)74 * leave the device (≈ 1 M possible prefixes, each shared by ~800 unrelated hashes). The full hash and the password never do.75 * SHA-1 is used here only because the public corpus is indexed by it; it protects nothing.76 */77export async function breachPrefix(password: string): Promise<{ prefix: string; suffix: string }> {78  const h = hex(new Uint8Array(await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password)))).toUpperCase();79  return { prefix: h.slice(0, 5), suffix: h.slice(5) };80}81export function breachCount(rangeBody: string, suffix: string): number {82  for (const line of rangeBody.split(/\r?\n/)) {83    const [s, n] = line.trim().split(":");84    if (s === suffix) return Number(n) || 0;85  }86  return 0;87}88
Files main
Menu

Theme