Skip to content
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
245 changes: 245 additions & 0 deletions AUDIT.md

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion apps/desktop-ui/next.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NextConfig } from 'next';
import createNextIntlPlugin from 'next-intl/plugin';
import withBundleAnalyzer from '@next/bundle-analyzer';

const withNextIntl = createNextIntlPlugin();

Expand Down Expand Up @@ -71,4 +72,6 @@ const nextConfig: NextConfig = {
},
};

export default withNextIntl(nextConfig);
const analyzer = (withBundleAnalyzer as any)({ enabled: process.env.ANALYZE === 'true' });

export default analyzer(withNextIntl(nextConfig));
22 changes: 22 additions & 0 deletions scripts/audit/keystroke-cost.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Worst-legal-input main-thread cost of per-keystroke recomputes (Node = same V8 as Chrome).
// Run from repo root: node --experimental-strip-types scripts/audit/keystroke-cost.mts
import { findMatchRanges, MAX_TEST_TEXT_LENGTH } from '../../apps/desktop-ui/src/lib/regex-tester.ts';
import { buildLineDiffRows, countDiffRows, DIFF_MAX_INPUT_CHARS } from '../../apps/desktop-ui/src/lib/text-diff.ts';

const words = ['error', 'warn', 'info', 'debug', 'trace', 'user', 'id', 'value'];
let text = '';
while (text.length < MAX_TEST_TEXT_LENGTH - 100) {
text += `[2026-07-16] ${words[text.length % 8]} message ${text.length} key=val${text.length % 97}\n`;
}
const t0 = performance.now();
for (let i = 0; i < 5; i++) findMatchRanges(text, '\\b(\\w+)=(\\w+)\\b', 'g');
const regexMs = (performance.now() - t0) / 5;

const lines = text.split('\n');
const left = lines.join('\n').slice(0, DIFF_MAX_INPUT_CHARS - 10);
const right = lines.map((l, i) => (i % 20 === 0 ? l + ' CHANGED' : l)).join('\n').slice(0, DIFF_MAX_INPUT_CHARS - 10);
const t1 = performance.now();
for (let i = 0; i < 3; i++) { const r = buildLineDiffRows(left, right); countDiffRows(r); }
const diffMs = (performance.now() - t1) / 3;

console.log(JSON.stringify({ regexTester200kMs: +regexMs.toFixed(1), diffChecker250kMs: +diffMs.toFixed(1) }));
18 changes: 18 additions & 0 deletions scripts/audit/lh-run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash
# Lighthouse matrix runner. Usage: lh-run.sh <name> <url>
# 3 runs mobile + 3 desktop, JSON to $SCRATCH/lh/
set -e
export PATH="/Users/max/.nvm/versions/node/v24.18.0/bin:$PATH"
S=/private/tmp/claude-501/-Users-max-Works-Personal-mydevtools/84bbaabb-6f1a-4567-803d-f1a69bc496a1/scratchpad
export CHROME_PATH="$S/browsers/chrome/mac_arm-150.0.7871.124/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
NAME=$1; URL=$2
mkdir -p "$S/lh"
for i in 1 2 3; do
npx -y lighthouse@12 "$URL" --chrome-flags="--headless=new" \
--only-categories=performance,accessibility \
--output=json --output-path="$S/lh/$NAME-mobile-$i.json" --quiet
npx -y lighthouse@12 "$URL" --preset=desktop --chrome-flags="--headless=new" \
--only-categories=performance,accessibility \
--output=json --output-path="$S/lh/$NAME-desktop-$i.json" --quiet
done
echo "DONE $NAME"
111 changes: 111 additions & 0 deletions scripts/audit/monaco-egress.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Lab-only auth-gate bypass + Monaco egress probe.
// Stubs the Tauri activation call and seeds a persisted Firebase user in
// IndexedDB, loads a Monaco tool page, waits for the editor, and reports
// every third-party host contacted. Usage: node monaco-egress.js <url> <apiKey>
const puppeteer = require("puppeteer-core");

const [url, apiKey] = process.argv.slice(2);

(async () => {
const browser = await puppeteer.launch({
executablePath: process.env.CHROME_PATH,
headless: "new",
});
const page = await browser.newPage();

const hosts = new Map();
page.on("request", (r) => {
const h = new URL(r.url()).host;
hosts.set(h, (hosts.get(h) || 0) + 1);
});
// Firebase validates persisted users on init; a network failure keeps the
// user (offline path). Blocking identitytoolkit keeps the lab user alive.
const cdp2 = await page.createCDPSession();
await cdp2.send("Network.enable");
await cdp2.send("Network.setBlockedURLs", {
urls: ["*identitytoolkit*", "*securetoken*"],
});

// Tauri activation stub on every document
await page.evaluateOnNewDocument(() => {
window.__TAURI_INTERNALS__ = {
invoke: (cmd, args) => {
if (cmd === "local_api" && args?.path === "/desktop/activation") {
return Promise.resolve({
status: 200,
body: JSON.stringify({ uid: "lab", email: "lab@example.com" }),
});
}
return Promise.resolve({ status: 404, body: "" });
},
};
});

// Seed the persisted Firebase user on a throwaway same-origin page and wait
// for the IndexedDB write to land BEFORE the app boots (avoids init race).
const origin = new URL(url).origin;
await page.goto(origin + "/robots.txt", { waitUntil: "domcontentloaded" });
await page.evaluate((key) => {
const user = {
uid: "lab",
email: "lab@example.com",
emailVerified: true,
isAnonymous: false,
providerData: [],
stsTokenManager: {
refreshToken: "lab-refresh",
accessToken: "e30.e30.e30",
expirationTime: Date.now() + 3600e3,
},
createdAt: "0",
lastLoginAt: "0",
apiKey: key,
appName: "[DEFAULT]",
};
return new Promise((resolve, reject) => {
const open = indexedDB.open("firebaseLocalStorageDb", 1);
open.onupgradeneeded = () =>
open.result.createObjectStore("firebaseLocalStorage", {
keyPath: "fbase_key",
});
open.onerror = () => reject(open.error);
open.onsuccess = () => {
const tx = open.result.transaction("firebaseLocalStorage", "readwrite");
tx.objectStore("firebaseLocalStorage").put({
fbase_key: `firebase:authUser:${key}:[DEFAULT]`,
value: user,
});
tx.oncomplete = () => resolve(true);
tx.onerror = () => reject(tx.error);
};
});
}, apiKey);
hosts.clear();

await page.goto(url, { waitUntil: "networkidle2", timeout: 90000 });
const editorFound = await page
.waitForSelector(".monaco-editor", { timeout: 45000 })
.then(() => true)
.catch(() => false);
await new Promise((r) => setTimeout(r, 3000));

const third = [...hosts.entries()].filter(
([h]) => !h.startsWith("localhost")
);
console.log(
JSON.stringify(
{
url,
finalUrl: page.url(),
editorFound,
thirdPartyHosts: Object.fromEntries(third),
jsdelivrRequests: [...hosts.entries()]
.filter(([h]) => h.includes("jsdelivr"))
.reduce((n, [, c]) => n + c, 0),
},
null,
1
)
);
await browser.close();
})();
32 changes: 32 additions & 0 deletions scripts/audit/route-sweep.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// First Load JS per route: fetch each route's HTML from a running `next start`,
// collect <script src> + modulepreload chunks, sum their gzipped sizes.
// Usage: node route-sweep.js <baseUrl> <appDir> <route1> <route2> ...
const zlib = require('zlib');
const fs = require('fs');
const path = require('path');

const [base, appDir, ...routes] = process.argv.slice(2);

async function firstLoadJs(route) {
const res = await fetch(base + route);
const html = await res.text();
const srcs = new Set();
for (const m of html.matchAll(/<script[^>]+src="([^"]+\.js)[^"]*"/g)) srcs.add(m[1]);
for (const m of html.matchAll(/<link[^>]+rel="preload"[^>]+href="([^"]+\.js)[^"]*"/g)) srcs.add(m[1]);
let total = 0, n = 0;
for (const src of srcs) {
const rel = src.replace(/^\/_next\//, '').split('?')[0];
const file = path.join(appDir, '.next', rel);
if (!fs.existsSync(file)) continue;
total += zlib.gzipSync(fs.readFileSync(file)).length;
n++;
}
return { route, kb: +(total / 1024).toFixed(1), scripts: n, status: res.status };
}

(async () => {
for (const r of routes) {
const x = await firstLoadJs(r);
console.log(`${String(x.kb).padStart(8)} KB gz ${String(x.scripts).padStart(3)} js [${x.status}] ${x.route}`);
}
})();