work in progress

This commit is contained in:
2026-08-16 22:00:08 +02:00
parent a914ef1ec4
commit 3c11a88a33
60 changed files with 4487 additions and 41 deletions
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env node
// Protocol-level stand-in for the companion app (mobile/claude.md's real
// target — this is not a preview of it, per the run-flow plan's explicit
// scope note). Drives the companion's real cryptographic and network
// responsibilities against the real server and a real running extension,
// so the run flow can be verified end-to-end without the companion app
// existing yet — same "curl/Puppeteer instead of mocks" approach used
// throughout this project.
//
// Subcommands, in increasing order of manual effort:
//
// node companion-harness.mjs run <signed_token> [username] [password]
// The easy path for manual testing. Does the key exchange, prints the
// PIN, then polls interfaces.md's PIN confirmation endpoint — the real
// signal, not a human keypress standing in for it — before delivering
// a credential (defaults: alice@example.com / hunter2). One paste, no
// keypress needed.
//
// node companion-harness.mjs key-exchange <signed_token>
// node companion-harness.mjs deliver-credential <runId> <runKeyB64> <username> <password>
// The two steps split apart, for scripted/automated use.
//
// This is a real two-way handshake now, not the companion proceeding on
// its own schedule: the extension posts its confirmation when the user
// clicks Confirm, and the companion (real or, here, this harness) is
// expected to wait for it before it ever selects/sends a credential —
// `run` above does exactly that via waitForPinConfirmation(). Calling
// `deliver-credential` directly, without confirmation ever having been
// posted, is still possible (nothing here stops you) but the extension
// will just discard it — the actual gate lives there, not in this script.
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { webcrypto } from 'node:crypto';
import { Agent, setGlobalDispatcher } from 'undici';
import { ed25519, x25519 } from '@noble/curves/ed25519.js';
import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
import canonicalize from 'canonicalize';
const __dirname = dirname(fileURLToPath(import.meta.url));
const API_BASE = process.env.LOCQR_API_BASE ?? 'https://api.locqr.dev:3000';
// dev/keys/ed25519-public.b64 — same pinned dev constant compiled into the
// extension (crypto.md's ED25519_PUBLIC_KEY_B64); must match or every
// signature check below fails.
const ED25519_PUBLIC_KEY_B64 = 'Z9ppr33AB5gznf-mQU2F9Y3E-MEoNcGHtmlh7rzaTh4';
// interfaces.md: 30s clock-skew leeway past expires_at is the only clock
// tolerance in the protocol.
const EXPIRY_LEEWAY_SECONDS = 30;
// Trust the local mkcert CA (dev.md) for the harness's own TLS connections —
// Node doesn't consult the system/NSS trust stores the browsers use.
setGlobalDispatcher(new Agent({ connect: { ca: readFileSync(join(__dirname, '..', 'dev', 'certs', 'rootCA.pem')) } }));
function b64urlDecode(s) {
return new Uint8Array(Buffer.from(s, 'base64url'));
}
function b64urlEncode(bytes) {
return Buffer.from(bytes).toString('base64url');
}
function concat(...parts) {
const total = parts.reduce((n, p) => n + p.length, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const p of parts) {
out.set(p, offset);
offset += p.length;
}
return out;
}
async function hkdfSha256(ikm, salt, info, lengthBytes) {
const key = await webcrypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
const bits = await webcrypto.subtle.deriveBits(
{ name: 'HKDF', hash: 'SHA-256', salt, info: new TextEncoder().encode(info) },
key,
lengthBytes * 8,
);
return new Uint8Array(bits);
}
// crypto.md: run_key = HKDF-SHA256(x25519_shared || kem_shared_secret, salt=runId_utf8, info="locqr-run-key-v1", 32).
async function deriveRunKey(x25519Shared, kemSharedSecret, runId) {
const ikm = concat(x25519Shared, kemSharedSecret);
const salt = new TextEncoder().encode(runId);
return hkdfSha256(ikm, salt, 'locqr-run-key-v1', 32);
}
// mobile/claude.md: PIN = HKDF-SHA256(run_key, salt=[], info="locqr-pin-v1", 4) -> big-endian uint32 -> mod 1e6 -> zero-padded.
// Must match extension/src/background/crypto.ts's derivePin() exactly, or the two sides' PINs never agree.
async function derivePin(runKey) {
const bits = await hkdfSha256(runKey, new Uint8Array(0), 'locqr-pin-v1', 4);
const value = new DataView(bits.buffer, bits.byteOffset, bits.byteLength).getUint32(0, false);
return (value % 1_000_000).toString().padStart(6, '0');
}
async function sha256(...parts) {
const digest = await webcrypto.subtle.digest('SHA-256', concat(...parts));
return new Uint8Array(digest);
}
function bytesEqual(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
async function postRelay(runId, type, payloadB64) {
const response = await fetch(`${API_BASE}/run/relay/${runId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, payload_b64: payloadB64 }),
});
if (!response.ok) {
throw new Error(`POST /run/relay/${runId} (${type}) failed: ${response.status}`);
}
}
async function keyExchange(signedToken) {
const envelope = JSON.parse(Buffer.from(signedToken, 'base64url').toString('utf8'));
const { v, runId, url, expires_at: expiresAt, alpha_hash: alphaHashB64, sig } = envelope;
if (v !== 1) throw new Error(`unsupported token version: ${v}`);
// interfaces.md: signed payload is the envelope minus `sig`, JCS-canonicalised.
const payload = { v, runId, url, expires_at: expiresAt, alpha_hash: alphaHashB64 };
const signatureValid = ed25519.verify(b64urlDecode(sig), Buffer.from(canonicalize(payload), 'utf8'), b64urlDecode(ED25519_PUBLIC_KEY_B64));
if (!signatureValid) throw new Error('token_signature_invalid');
const nowSeconds = Date.now() / 1000;
if (nowSeconds > expiresAt + EXPIRY_LEEWAY_SECONDS) throw new Error('ttl_expired');
const bundleResponse = await fetch(`${API_BASE}/run/bundle/${runId}`);
if (!bundleResponse.ok) throw new Error(`bundle_consumed_or_expired (${bundleResponse.status})`);
const { x25519_pubkey: x25519PubB64, kem_pubkey: kemPubB64 } = await bundleResponse.json();
const extensionX25519Pub = b64urlDecode(x25519PubB64);
const extensionKemPub = b64urlDecode(kemPubB64);
const recomputedAlphaHash = await sha256(extensionX25519Pub, extensionKemPub);
if (!bytesEqual(recomputedAlphaHash, b64urlDecode(alphaHashB64))) throw new Error('alpha_hash_mismatch');
const companionX25519 = x25519.keygen();
const x25519Shared = x25519.getSharedSecret(companionX25519.secretKey, extensionX25519Pub);
const { cipherText: kemCiphertext, sharedSecret: kemSharedSecret } = ml_kem768.encapsulate(extensionKemPub);
const runKey = await deriveRunKey(x25519Shared, kemSharedSecret, runId);
const pin = await derivePin(runKey);
await postRelay(runId, 'kem_ciphertext', b64urlEncode(concat(companionX25519.publicKey, kemCiphertext)));
return { runId, pin, runKey: b64urlEncode(runKey) };
}
async function deliverCredential(runId, runKeyB64, username, password) {
const runKey = b64urlDecode(runKeyB64);
const nonce = webcrypto.getRandomValues(new Uint8Array(12));
const plaintext = new TextEncoder().encode(JSON.stringify({ username, password }));
const key = await webcrypto.subtle.importKey('raw', runKey, 'AES-GCM', false, ['encrypt']);
const ciphertextAndTag = new Uint8Array(await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, key, plaintext));
await postRelay(runId, 'credential', b64urlEncode(concat(nonce, ciphertextAndTag)));
}
const CONFIRMATION_POLL_INTERVAL_MS = 1000;
const CONFIRMATION_POLL_TIMEOUT_MS = 180_000; // generous safety net — the extension's own pin_ttl alarm is the real, authoritative deadline
/**
* Polls interfaces.md's PIN confirmation endpoint rather than trusting a
* human keypress to mean "I've confirmed and the browser has processed
* it" — those aren't the same thing (a click can be sent and still not
* have landed yet, e.g. a slow service worker wake). This waits for the
* real signal instead of a proxy for it.
*/
async function waitForPinConfirmation(runId) {
const deadline = Date.now() + CONFIRMATION_POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
const response = await fetch(`${API_BASE}/run/relay/${runId}/confirm`);
if (response.ok) {
const { confirmed } = await response.json();
if (confirmed) return;
}
await new Promise((resolve) => setTimeout(resolve, CONFIRMATION_POLL_INTERVAL_MS));
}
throw new Error('timed out waiting for PIN confirmation from the browser');
}
async function runInteractive(signedToken, username, password) {
const { runId, pin, runKey } = await keyExchange(signedToken);
console.log(`\nPIN: ${pin}`);
console.log('Compare that against the PIN shown in the extension popup, then click Confirm there.');
console.log('Waiting for the browser to confirm...');
await waitForPinConfirmation(runId);
console.log('Confirmed by the browser.');
await deliverCredential(runId, runKey, username, password);
console.log(`Delivered credential (${username} / ${password}). The popup should now show "Signed in".`);
}
async function main() {
const [command, ...args] = process.argv.slice(2);
if (command === 'run') {
const [signedToken, username = 'alice@example.com', password = 'hunter2'] = args;
if (!signedToken) throw new Error('usage: companion-harness.mjs run <signed_token> [username] [password]');
await runInteractive(signedToken, username, password);
return;
}
if (command === 'key-exchange') {
const [signedToken] = args;
if (!signedToken) throw new Error('usage: companion-harness.mjs key-exchange <signed_token>');
console.log(JSON.stringify(await keyExchange(signedToken)));
return;
}
if (command === 'deliver-credential') {
const [runId, runKeyB64, username, password] = args;
if (!runId || !runKeyB64 || !username || !password) {
throw new Error('usage: companion-harness.mjs deliver-credential <runId> <runKeyB64> <username> <password>');
}
await deliverCredential(runId, runKeyB64, username, password);
console.log(JSON.stringify({ ok: true }));
return;
}
throw new Error(`unknown command: ${command ?? '(none)'} — expected "run", "key-exchange", or "deliver-credential"`);
}
main().catch((err) => {
console.error(err instanceof Error ? err.message : err);
process.exitCode = 1;
});
+135
View File
@@ -0,0 +1,135 @@
{
"name": "locqr-dev-setup",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "locqr-dev-setup",
"version": "0.1.0",
"dependencies": {
"@noble/curves": "^2.3.0",
"@noble/post-quantum": "0.6.1",
"@oqs/liboqs-js": "0.15.1",
"canonicalize": "3.0.0",
"undici": "^8.10.0"
}
},
"node_modules/@noble/ciphers": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.2.0.tgz",
"integrity": "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/curves": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.3.0.tgz",
"integrity": "sha512-v7cY+4oWYPQszRj6ZFGzTVL7uP2TaLo1xMhWHzYC5wj0ZhOXQ5x+sBre8rF3hi8cAoi0bh1qXoovoOkdFtvqEg==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.3.0"
},
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",
"integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/post-quantum": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/@noble/post-quantum/-/post-quantum-0.6.1.tgz",
"integrity": "sha512-+pormrDZwjRw05U8ADK4JpHejo87+gBd+muRBB/ozztH5yhDLMDF4jHQWN3NQQAsu1zBNPWTG0ZwVI0CR29H0A==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "~2.2.0",
"@noble/curves": "~2.2.0",
"@noble/hashes": "~2.2.0"
},
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/post-quantum/node_modules/@noble/curves": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz",
"integrity": "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.2.0"
},
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/post-quantum/node_modules/@noble/hashes": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz",
"integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oqs/liboqs-js": {
"version": "0.15.1",
"resolved": "https://registry.npmjs.org/@oqs/liboqs-js/-/liboqs-js-0.15.1.tgz",
"integrity": "sha512-nt1M2CuI4JC1FGoLeD0771C/BcisCuJqh8o/54dcUY0nU88Bf7Qv8vF05SA+wLAVf8UTuZD/l6FlS2LI8NjGbg==",
"license": "MIT",
"bin": {
"liboqs": "bin/cli.js"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/canonicalize": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/canonicalize/-/canonicalize-3.0.0.tgz",
"integrity": "sha512-yYLfHyDMIXRyRqsKBRLX023riFLpXY2YOfdtqKXZRZy9qsfOJ9U+4F9YZL7MEzL5+ziN2x2nlBvY/Voi3EBljA==",
"license": "Apache-2.0",
"bin": {
"canonicalize": "bin/canonicalize.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/undici": {
"version": "8.10.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.10.0.tgz",
"integrity": "sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "locqr-dev-setup",
"private": true,
"version": "0.1.0",
"description": "Dev environment bootstrapping for LOCQR (dev.md). Node.js per crypto.md's pinned Node.js-setup-script row for ML-KEM-768/ML-DSA-44.",
"type": "module",
"scripts": {
"setup": "node setup-dev.js",
"companion": "node companion-harness.mjs"
},
"dependencies": {
"@noble/curves": "^2.3.0",
"@noble/post-quantum": "0.6.1",
"@oqs/liboqs-js": "0.15.1",
"canonicalize": "3.0.0",
"undici": "^8.10.0"
}
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env node
// Serves website/ over HTTPS using the mkcert-issued test.locqr.dev cert
// (dev.md — HTTPS is required, externally_connectable needs a secure
// context). Also mounts sdk/dist under /sdk/, since the test page imports
// the SDK directly and there's no build step tying the two together
// (sdk/claude.md: packaging/distribution is deferred).
//
// Plain Node https + fs — no extra dependency for something this small.
import { createServer } from 'node:https';
import { readFile, stat } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const WEBSITE_DIR = join(ROOT, 'website');
const SDK_DIST_DIR = join(ROOT, 'sdk', 'dist');
const PORT = 5173;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
};
async function resolveFile(urlPath) {
const [mountPath, baseDir] = urlPath.startsWith('/sdk/')
? [urlPath.slice('/sdk'.length), SDK_DIST_DIR]
: [urlPath, WEBSITE_DIR];
const safePath = normalize(mountPath === '/' ? '/index.html' : mountPath).replace(/^(\.\.[/\\])+/, '');
const filePath = join(baseDir, safePath);
if (!filePath.startsWith(baseDir)) return null; // path traversal guard
try {
const stats = await stat(filePath);
return stats.isFile() ? filePath : null;
} catch {
return null;
}
}
const options = {
cert: await readFile(join(ROOT, 'dev', 'certs', 'test.locqr.dev.pem')),
key: await readFile(join(ROOT, 'dev', 'certs', 'test.locqr.dev-key.pem')),
};
createServer(options, async (req, res) => {
const url = new URL(req.url ?? '/', 'https://test.locqr.dev');
const filePath = await resolveFile(url.pathname);
if (!filePath) {
res.writeHead(404).end('Not found');
return;
}
const body = await readFile(filePath);
res.writeHead(200, { 'Content-Type': MIME[extname(filePath)] ?? 'application/octet-stream' });
res.end(body);
}).listen(PORT, () => {
console.log(`Serving website/ (and sdk/dist/ at /sdk/) -> https://test.locqr.dev:${PORT}`);
});
+302
View File
@@ -0,0 +1,302 @@
#!/usr/bin/env node
// LOCQR dev environment bootstrapping — see ../dev.md.
//
// Scope: dev signing keypairs (Ed25519, ML-DSA-44), the signed test
// registration certificate, mkcert local-CA TLS certs, and the extension's
// stable dev identity (key.pem). Pinned-constant patching
// (extension/src/constants.ts, companion's equivalent) is still deferred —
// added once there's a real constants file to patch rather than a
// hand-set one.
//
// Node.js, not shell or Java: crypto.md pins `@oqs/liboqs-js` specifically
// for "Node.js setup script" ML-DSA-44 work — this script runs in plain
// Node, not a service worker, so the WASM-dynamic-import restriction that
// ruled that library out for the extension (crypto.md, "Resolved
// 2026-08-16") doesn't apply here.
//
// Idempotent: every artifact here is checked for existence before being
// generated. Re-running this script on an existing environment changes
// nothing. To rotate keys, delete the relevant dev/keys or dev/certs file(s)
// first — see dev.md, "Rotating dev keys".
import { createMLDSA44 } from '@oqs/liboqs-js';
import canonicalize from 'canonicalize';
import { execFileSync } from 'node:child_process';
import { createHash, createPublicKey, generateKeyPairSync } from 'node:crypto';
import { mkdirSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = dirname(dirname(fileURLToPath(import.meta.url))); // repo root, one up from scripts/
const KEYS_DIR = join(ROOT, 'dev', 'keys');
const CERTS_DIR = join(ROOT, 'dev', 'certs');
const EXTENSION_DIR = join(ROOT, 'extension');
const TEST_DOMAIN = 'test.locqr.dev';
const API_DOMAIN = 'api.locqr.dev';
const CERT_LIFETIME_SECONDS = 10 * 365 * 24 * 60 * 60; // 10 years — a dev cert that outlives the dev cycle
function readIfPresent(path) {
return existsSync(path) ? readFileSync(path, 'utf8').trim() : null;
}
function writeAndAnnounce(path, contents, label) {
writeFileSync(path, contents + '\n');
console.log(` generated ${label} -> ${path}`);
}
/**
* @oqs/liboqs-js validates key/message arguments by strict duck-typing
* (`value.constructor.name === 'Uint8Array'`, not `instanceof`) — a Node
* `Buffer` fails that check even though it *is* a Uint8Array by
* inheritance, since its constructor is named `Buffer`. Every byte array
* handed to sign()/verify() has to go through this first.
*/
function toUint8Array(buffer) {
return Uint8Array.from(buffer);
}
/**
* Ed25519 dev keypair for the backend's key-exchange-token signing (crypto.md,
* server/claude.md). JWK export gives the raw 32-byte scalar directly as
* base64url (RFC 4648 §5, matching interfaces.md's shared conventions) — no
* PKCS8 wrapping, no manual point encoding.
*/
function ensureEd25519Keys() {
const secretPath = join(KEYS_DIR, 'ed25519-secret.b64');
const publicPath = join(KEYS_DIR, 'ed25519-public.b64');
const existingSecret = readIfPresent(secretPath);
const existingPublic = readIfPresent(publicPath);
if (existingSecret && existingPublic) {
console.log(' Ed25519 dev keypair already present, skipping.');
return { secretB64: existingSecret, publicB64: existingPublic };
}
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
const secretB64 = privateKey.export({ format: 'jwk' }).d;
const publicB64 = publicKey.export({ format: 'jwk' }).x;
writeAndAnnounce(secretPath, secretB64, 'Ed25519 secret key');
writeAndAnnounce(publicPath, publicB64, 'Ed25519 public key');
console.log(' NEW Ed25519 keypair — remember to commit both files (dev.md).');
return { secretB64, publicB64 };
}
/**
* ML-DSA-44 dev keypair for signing the domain registration certificate
* (crypto.md). Only ever used offline, by this script — the running server
* never signs with it live (server/claude.md).
*/
async function ensureMlDsaKeys() {
const secretPath = join(KEYS_DIR, 'ml-dsa-44-secret.b64');
const publicPath = join(KEYS_DIR, 'ml-dsa-44-public.b64');
const existingSecret = readIfPresent(secretPath);
const existingPublic = readIfPresent(publicPath);
if (existingSecret && existingPublic) {
console.log(' ML-DSA-44 dev keypair already present, skipping.');
return { secretB64: existingSecret, publicB64: existingPublic };
}
const signer = await createMLDSA44();
let secretB64;
let publicB64;
try {
const { publicKey, secretKey } = signer.generateKeyPair();
secretB64 = Buffer.from(secretKey).toString('base64url');
publicB64 = Buffer.from(publicKey).toString('base64url');
} finally {
signer.destroy(); // WASM memory isn't GC'd — see @oqs/liboqs-js README
}
writeAndAnnounce(secretPath, secretB64, 'ML-DSA-44 secret key');
writeAndAnnounce(publicPath, publicB64, 'ML-DSA-44 public key');
console.log(' NEW ML-DSA-44 keypair — remember to commit both files (dev.md).');
return { secretB64, publicB64 };
}
/**
* Issues and signs the test registration certificate for TEST_DOMAIN
* (interfaces.md, "Registration certificate"). Stable/committed like the
* keys — re-running this script does not reissue it, so its issued_at/
* expires_at don't churn on every developer's machine.
*/
async function ensureTestRegistrationCert(mlDsaKeys) {
const certPath = join(CERTS_DIR, 'test-registration.b64');
if (existsSync(certPath)) {
console.log(' Test registration certificate already present, skipping.');
return;
}
const issuedAt = Math.floor(Date.now() / 1000);
const payload = {
v: 1,
domain: TEST_DOMAIN,
issued_at: issuedAt,
expires_at: issuedAt + CERT_LIFETIME_SECONDS,
features: ['login'],
};
const canonical = canonicalize(payload);
const message = new TextEncoder().encode(canonical);
const secretKey = toUint8Array(Buffer.from(mlDsaKeys.secretB64, 'base64url'));
const publicKey = toUint8Array(Buffer.from(mlDsaKeys.publicB64, 'base64url'));
const signer = await createMLDSA44();
let signature;
try {
signature = signer.sign(message, secretKey);
// Self-check before writing anything to disk: sign() and verify() are
// independent code paths in the library: this catches a broken pairing
// (e.g. mismatched key files) at generation time, not at first
// extension-side verification.
const verifies = signer.verify(message, signature, publicKey);
if (!verifies) {
throw new Error('ML-DSA-44 self-check failed: signature does not verify against its own public key.');
}
} finally {
signer.destroy();
}
const envelope = { ...payload, sig: Buffer.from(signature).toString('base64url') };
const encoded = Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url');
writeAndAnnounce(certPath, encoded, 'test registration certificate');
console.log(` NEW registration cert for ${TEST_DOMAIN}, valid ${CERT_LIFETIME_SECONDS / (365 * 24 * 60 * 60)} years — remember to commit (dev.md).`);
}
/**
* mkcert local CA — installs it into the system/browser trust stores
* (idempotent by mkcert's own design; safe to call every run) and exports
* rootCA.pem for other developers to import (dev.md, "Committed artifacts").
*/
function ensureMkcertRootCa() {
const dest = join(CERTS_DIR, 'rootCA.pem');
execFileSync('mkcert', ['-install'], { stdio: 'inherit' });
if (existsSync(dest)) {
console.log(' rootCA.pem already exported, skipping.');
return;
}
const caRoot = execFileSync('mkcert', ['-CAROOT'], { encoding: 'utf8' }).trim();
writeFileSync(dest, readFileSync(join(caRoot, 'rootCA.pem')));
console.log(` exported mkcert root CA -> ${dest}`);
}
/** TLS cert+key for one local dev domain, via mkcert. */
function ensureDomainCert(domain) {
const certPath = join(CERTS_DIR, `${domain}.pem`);
const keyPath = join(CERTS_DIR, `${domain}-key.pem`);
if (existsSync(certPath) && existsSync(keyPath)) {
console.log(` ${domain} cert already present, skipping.`);
return;
}
execFileSync('mkcert', ['-cert-file', certPath, '-key-file', keyPath, domain], { stdio: 'inherit' });
console.log(` generated ${domain} cert -> ${certPath}`);
}
/**
* dev.md is explicit that this script checks for the required /etc/hosts
* entries and prints instructions if missing, but never edits the file
* itself — hosts file changes need root and are exactly the kind of system
* change a script shouldn't make unannounced.
*/
function checkHostsFile() {
let hosts;
try {
hosts = readFileSync('/etc/hosts', 'utf8');
} catch {
console.log(' Could not read /etc/hosts — add these entries manually:');
console.log(` 127.0.0.1 ${TEST_DOMAIN}`);
console.log(` 127.0.0.1 ${API_DOMAIN}`);
return;
}
const missing = [TEST_DOMAIN, API_DOMAIN].filter((d) => !hosts.includes(d));
if (missing.length === 0) {
console.log(' /etc/hosts already has the required entries.');
return;
}
console.log(' /etc/hosts is missing entries for: ' + missing.join(', '));
console.log(' Add these lines yourself (this script does not modify /etc/hosts):');
for (const d of missing) console.log(` 127.0.0.1 ${d}`);
}
/** Chrome's extension-ID derivation: SHA-256(DER SPKI public key), first 16
* bytes, each nibble mapped to a letter a-p. Unrelated to our Ed25519/
* ML-DSA-44 protocol keys — this is Chrome's own extension identity
* mechanism (RSA), used only to pin a stable ID for the unpacked dev build. */
function computeExtensionId(publicKeyDer) {
const hash = createHash('sha256').update(publicKeyDer).digest();
let id = '';
for (const byte of hash.subarray(0, 16)) {
id += String.fromCharCode(97 + (byte >> 4));
id += String.fromCharCode(97 + (byte & 0x0f));
}
return id;
}
/**
* extension/key.pem pins the unpacked extension's ID across machines and
* rebuilds (dev.md). The "key" field it produces goes in manifest.json.
*/
function ensureExtensionKeyPem() {
const keyPath = join(EXTENSION_DIR, 'key.pem');
let publicKeyDer;
if (existsSync(keyPath)) {
console.log(' extension/key.pem already present, skipping.');
publicKeyDer = createPublicKey(readFileSync(keyPath, 'utf8')).export({ type: 'spki', format: 'der' });
} else {
mkdirSync(EXTENSION_DIR, { recursive: true });
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'der' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});
writeFileSync(keyPath, privateKey);
console.log(` generated extension/key.pem -> ${keyPath}`);
console.log(' NEW extension identity — remember to commit (dev.md).');
publicKeyDer = publicKey;
}
console.log(` dev extension ID: ${computeExtensionId(publicKeyDer)}`);
console.log(` manifest.json "key": ${publicKeyDer.toString('base64')}`);
}
async function main() {
mkdirSync(KEYS_DIR, { recursive: true });
mkdirSync(CERTS_DIR, { recursive: true });
console.log('Ed25519 signing key (key exchange tokens):');
ensureEd25519Keys();
console.log('ML-DSA-44 signing key (domain registration certs):');
const mlDsaKeys = await ensureMlDsaKeys();
console.log(`Test registration certificate (${TEST_DOMAIN}):`);
await ensureTestRegistrationCert(mlDsaKeys);
console.log('mkcert local CA:');
ensureMkcertRootCa();
console.log(`TLS certs (${TEST_DOMAIN}, ${API_DOMAIN}):`);
ensureDomainCert(TEST_DOMAIN);
ensureDomainCert(API_DOMAIN);
console.log('/etc/hosts:');
checkHostsFile();
console.log('Extension dev identity:');
ensureExtensionKeyPem();
console.log('\nDone. Not yet covered by this script (see dev.md): pinned-constant');
console.log('patching (extension/src/constants.ts, companion equivalent) —');
console.log('added once those files exist to patch.');
}
main().catch((err) => {
console.error('setup-dev.js failed:', err);
process.exitCode = 1;
});