#!/usr/bin/env node
// verify-how-long-to-crack-your-password.mjs
//
// Offline gate for /strata/how-long-to-crack-your-password/. It recomputes EVERY number
// the page shows, from first principles, and exits 0 only if all checks pass. It also
// reads the EFF wordlist back OUT of the published page to confirm exactly 7,776 words
// are bundled (the whole 12.925-bits-per-word claim depends on that count).
//
// The maths:
//   naive charset entropy   H = L * log2(N)                       (bits, an UPPER BOUND)
//   EFF Diceware            bits = words * log2(7776), 7776 = 6^5
//   keyspace                K = 2^bits                             (= N^L for random secrets)
//   average crack time      t = (K / 2) / rate                     seconds
//
// Crack rates are a DATED SNAPSHOT: hashcat v6.2.6 on ONE NVIDIA RTX 4090
//   (Chick3nman, Oct 2022): NTLM 288.5 GH/s, MD5 164.1 GH/s, SHA-256 21975.5 MH/s,
//   bcrypt (mode 3200, cost 5 / 32 iterations) 184.0 kH/s.  GPUs get faster; not a law.
//
// Run:  node research/how-long-to-crack-your-password/verify-how-long-to-crack-your-password.mjs

'use strict';

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE = path.resolve(HERE, '../../public/strata/how-long-to-crack-your-password/index.html');

const LOG2 = (x) => Math.log2(x);
const YEAR = 31557600;                 // seconds in a Julian year
const RATES = { online: 1000, bcrypt: 184.0e3, sha256: 22.0e9, unsalted: 164.1e9, ntlm: 288.5e9 };

// ---- read the EFF wordlist back out of the published page --------------------------
function effWordsFromPage() {
  const html = fs.readFileSync(PAGE, 'utf8');
  const m = html.match(/var EFF = "([^"]*)"\.split\(" "\);/);
  if (!m) throw new Error('could not find the bundled EFF wordlist in the page');
  return m[1].split(' ');
}
const EFF = effWordsFromPage();
const EFFSET = new Set(EFF);

// ---- the SAME rough realistic scorer the page uses (mirrored) -----------------------
const COMMON = ('password 123456 123456789 qwerty 12345678 111111 1234567890 1234567 ' +
  'password1 12345 123123 000000 iloveyou 1234 qwertyuiop 123 monkey dragon 654321 123321 ' +
  '666666 121212 qwerty123 letmein admin welcome login master hello abc123 football baseball ' +
  'soccer hockey shadow michael jennifer jordan superman batman trustno1 whatever hunter ' +
  'buster tigger purple orange yellow silver golden princess sunshine summer winter spring ' +
  'autumn flower garden house mouse happy angel devil ninja pirate wizard phoenix eagle tiger ' +
  'lion panda kitty puppy coffee pizza cookie candy sugar honey cherry apple banana guitar ' +
  'piano music dance party magic dream ocean river mountain forest thunder storm cloud rainbow ' +
  'rocket robot computer internet google secret money love god freedom liberty america ' +
  'charlie robert thomas daniel george matthew joshua andrew william jessica michelle amanda ' +
  'ashley nicole chelsea maggie ginger pepper cheese access yankees dallas austin taylor ' +
  'starwars pokemon minecraft samsung google1 changeme default guest test123 ' +
  'rover fido spot rex buddy max bella lucy').split(' ');
const RANK = new Map();
COMMON.forEach((w, i) => { if (!RANK.has(w)) RANK.set(w, i + 1); });

const LEET = { '@':'a','4':'a','8':'b','(':'c','3':'e','6':'g','9':'g','1':'l','!':'i',
               '|':'l','0':'o','5':'s','$':'s','7':'t','+':'t','2':'z' };
function deleet(s) {
  let out = '', subs = 0;
  for (const ch of s) { if (LEET[ch] !== undefined) { out += LEET[ch]; subs++; } else out += ch.toLowerCase(); }
  return { word: out, subs };
}
const KEYROWS = ['qwertyuiop','asdfghjkl','zxcvbnm','1234567890','qwertzuiop','azertyuiop'];
function isKeyboardRun(s) {
  if (s.length < 3) return false;
  const t = s.toLowerCase();
  return KEYROWS.some((row) => { const rev = row.split('').reverse().join(''); return row.includes(t) || rev.includes(t); });
}
function charClass(ch) {
  if (ch >= 'a' && ch <= 'z') return 'lower';
  if (ch >= 'A' && ch <= 'Z') return 'upper';
  if (ch >= '0' && ch <= '9') return 'digit';
  return 'symbol';
}
function charsetN(pw) {
  const has = { lower:0, upper:0, digit:0, symbol:0 };
  for (const ch of pw) has[charClass(ch)] = 1;
  return (has.lower?26:0) + (has.upper?26:0) + (has.digit?10:0) + (has.symbol?33:0);
}
function naiveBits(pw) { return pw.length ? pw.length * LOG2(charsetN(pw)) : 0; }
function segCost(sub, N) {
  const costs = [];
  const lower = sub.toLowerCase();
  const upperBits = /[A-Z]/.test(sub) ? 1 : 0;
  const dl = deleet(sub);
  const cand = [[lower, 0], [dl.word, dl.subs]];
  for (const [w, leetBits] of cand) {
    if (w.length >= 3 && RANK.has(w)) costs.push(LOG2(RANK.get(w)) + leetBits + upperBits);
    else if (w.length >= 3 && EFFSET.has(w)) costs.push(LOG2(7776) + leetBits + upperBits);
  }
  if (/^[0-9]+$/.test(sub)) costs.push(/^(19|20)[0-9][0-9]$/.test(sub) ? LOG2(200) : sub.length * LOG2(10));
  if (isKeyboardRun(sub)) costs.push(LOG2(KEYROWS.length * 2) + (sub.length - 1));
  if (/^[ .\-_,]+$/.test(sub)) costs.push(0);
  if (sub.length === 1) costs.push(LOG2(N || 26));
  return costs.length ? Math.min(...costs) : Infinity;
}
function realisticBits(pw) {
  const n = pw.length;
  if (!n) return 0;
  const N = charsetN(pw);
  const best = new Array(n + 1).fill(Infinity); best[0] = 0;
  for (let end = 1; end <= n; end++) {
    const lo = Math.max(0, end - 24);
    for (let start = lo; start < end; start++) {
      const c = segCost(pw.slice(start, end), N);
      if (c === Infinity) continue;
      if (best[start] + c < best[end]) best[end] = best[start] + c;
    }
    if (best[end] === Infinity) best[end] = best[end - 1] + LOG2(N);
  }
  return Math.min(best[n], naiveBits(pw));
}

// ---- crack time (log10 seconds), robust to huge bit counts --------------------------
function log10CrackSec(bits, rate) { return (bits - 1) * Math.log10(2) - Math.log10(rate); }
function crackSec(bits, rate) { return Math.pow(10, log10CrackSec(bits, rate)); }
function cellClass(log10sec) { const y = log10sec - Math.log10(YEAR); return y < 0 ? 'r' : (y < 4 ? 'a' : 'g'); }

// ---- test harness -------------------------------------------------------------------
let pass = 0, fail = 0;
const approx = (a, b, tol = 1e-3) => Math.abs(a - b) <= tol;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  PASS  ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? '  ' + detail : ''}`); }
}

console.log('how-long-to-crack-your-password :: offline verifier');
console.log('crack rates as of hashcat v6.2.6, 1x NVIDIA RTX 4090 (Chick3nman, Oct 2022)');
console.log('');

// [1] per-character entropy log2(N)
console.log('[1] per-character entropy  log2(N)');
check('log2(26) = 4.700', approx(LOG2(26), 4.700), LOG2(26).toFixed(3));
check('log2(36) = 5.170', approx(LOG2(36), 5.170), LOG2(36).toFixed(3));
check('log2(62) = 5.954', approx(LOG2(62), 5.954), LOG2(62).toFixed(3));
check('log2(95) = 6.570', approx(LOG2(95), 6.570), LOG2(95).toFixed(3));
check('one extra CLASS adds < 2 bits/char (95 vs 26)', (LOG2(95) - LOG2(26)) < 2, (LOG2(95)-LOG2(26)).toFixed(3) + ' bits');

// [2] EFF Diceware ladder + the bundled list actually has 7776 words
console.log('\n[2] EFF Diceware  bits = words * log2(7776),  7776 = 6^5');
check('bundled EFF list has exactly 7776 words', EFF.length === 7776, EFF.length + ' words');
check('7776 = 6^5', 7776 === Math.pow(6, 5));
check('log2(7776) = 12.925', approx(LOG2(7776), 12.925), LOG2(7776).toFixed(3));
check('3 words = 38.77 bits', approx(3 * LOG2(7776), 38.77, 0.01), (3*LOG2(7776)).toFixed(2));
check('4 words = 51.70 bits', approx(4 * LOG2(7776), 51.70, 0.01), (4*LOG2(7776)).toFixed(2));
check('5 words = 64.62 bits', approx(5 * LOG2(7776), 64.62, 0.01), (5*LOG2(7776)).toFixed(2));
check('6 words = 77.55 bits (EFF recommendation)', approx(6 * LOG2(7776), 77.55, 0.01), (6*LOG2(7776)).toFixed(2));
{
  const avg = EFF.reduce((s, w) => s + w.length, 0) / EFF.length;
  check('average EFF word length ~ 7.0 chars', approx(avg, 7.0, 0.1), avg.toFixed(3) + ' chars');
}

// [3] xkcd-936 reference values
console.log('\n[3] xkcd-936 reference values (at 1000 guesses/sec)');
check('correct horse battery staple = 4 * log2(2048) = 44 bits', approx(4 * LOG2(2048), 44.0, 1e-9), (4*LOG2(2048)).toFixed(2));
check("Tr0ub4dor&3 = 28 bits (comic's stated components sum)", (16 + 3 + 1 + 4 + 4) === 28, '16+3(subs)+1(caps)+4(num)+4(punct)=28');

// [4] keyspace + crack times for the 4-word / 51.70-bit passphrase
console.log('\n[4] keyspace = N^L and crack time = (keyspace/2)/rate');
{
  const keyspace = Math.pow(7776, 4);
  check('keyspace 7776^4 = 3.656e15', approx(keyspace / 1e15, 3.656, 0.01), keyspace.toExponential(4));
  check('7776^4 == 2^(4*log2(7776))', approx(Math.log2(keyspace), 4 * LOG2(7776), 1e-9));
  const bits = 4 * LOG2(7776);
  const hrs = (rate) => crackSec(bits, rate) / 3600;
  const yrs = (rate) => crackSec(bits, rate) / YEAR;
  check('vs MD5 164.1 GH/s ~ 3.1 hours', approx(hrs(RATES.unsalted), 3.1, 0.2), hrs(RATES.unsalted).toFixed(2) + ' h');
  check('vs NTLM 288.5 GH/s ~ 1.8 hours', approx(hrs(RATES.ntlm), 1.76, 0.2), hrs(RATES.ntlm).toFixed(2) + ' h');
  check('vs SHA-256 22.0 GH/s ~ 23 hours', approx(hrs(RATES.sha256), 23.1, 1.0), hrs(RATES.sha256).toFixed(2) + ' h');
  check('vs bcrypt 184.0 kH/s ~ 315 years', approx(yrs(RATES.bcrypt), 315, 10), yrs(RATES.bcrypt).toFixed(0) + ' yr');
  check('online 1000/s ~ 58,000 years', approx(yrs(RATES.online), 57928, 500), Math.round(yrs(RATES.online)) + ' yr');
}

// [5] the reversal: genuine random 4 words beat P@ssw0rd1!, whose naive bits are an upper bound
console.log('\n[5] the reversal (formula + upper-bound relationship; no live crack)');
{
  const pNaive = naiveBits('P@ssw0rd1!');
  const pReal = realisticBits('P@ssw0rd1!');
  check('P@ssw0rd1! naive charset ~ 65.7 bits (upper bound)', approx(pNaive, 65.7, 0.2), pNaive.toFixed(2) + ' bits');
  check('P@ssw0rd1! realistic << its naive (a top-wordlist mangle)', pReal < 30 && pReal < pNaive - 40, pReal.toFixed(2) + ' bits');
  const four = 4 * LOG2(7776);
  check('random 4-word (51.70) strictly exceeds P@ssw0rd1! realistic', four > pReal, four.toFixed(2) + ' > ' + pReal.toFixed(2));
  // a truly random 4-EFF-word phrase scores at its Diceware entropy under the same scorer
  const phrase = 'abacus zoom truffle plywood';
  const okWords = phrase.split(' ').every((w) => EFFSET.has(w));
  check('test phrase words are all in the EFF list', okWords, phrase);
  const rp = realisticBits(phrase);
  check('scorer rates 4 random EFF words at ~51.70 bits (separators free)', approx(rp, 51.70, 0.01), rp.toFixed(2) + ' bits');
  // and a naive charset meter would wildly OVER-report the same passphrase
  check('naive charset over-reports the passphrase (upper bound, not truth)', naiveBits(phrase) > rp + 40, naiveBits(phrase).toFixed(1) + ' vs ' + rp.toFixed(1));
}

// [6] the six-orders-of-magnitude spread: bcrypt vs NTLM
console.log('\n[6] hash choice you do not control: NTLM/bcrypt slowdown');
check('288.5 GH/s / 184.0 kH/s > 1,000,000', RATES.ntlm / RATES.bcrypt > 1e6, (RATES.ntlm / RATES.bcrypt).toExponential(3));
check('same 4-word phrase: bcrypt years vs MD5 hours span > 1e5x',
  (crackSec(4*LOG2(7776), RATES.bcrypt) / crackSec(4*LOG2(7776), RATES.unsalted)) > 1e5,
  (crackSec(4*LOG2(7776), RATES.bcrypt) / crackSec(4*LOG2(7776), RATES.unsalted)).toExponential(2) + 'x');

// [7] the reference grid: reproduce every cell colour (1x hardware) shown on the page
console.log('\n[7] reference grid cell colours (1x RTX 4090)');
{
  const order = ['online','bcrypt','sha256','unsalted'];
  const rows = [
    { s: 'P@ssw0rd1!', bits: realisticBits('P@ssw0rd1!'), want: ['r','r','r','r'] },
    { s: 'correct horse battery staple', bits: 44.0,        want: ['a','a','r','r'] },
    { s: 'fresh 6-word Diceware',        bits: 77.55,       want: ['g','g','g','g'] },
  ];
  for (const row of rows) {
    const got = order.map((m) => cellClass(log10CrackSec(row.bits, RATES[m])));
    const ok = got.join('') === row.want.join('');
    check(`grid "${row.s}" = [${got.join(',')}]`, ok, ok ? '' : 'wanted [' + row.want.join(',') + ']');
  }
}

// ---- summary ------------------------------------------------------------------------
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
