#!/usr/bin/env node
// OFFLINE identity generator for AnyGas Messaging v2 — run on an air-gapped machine.
//   node msg2-keygen-offline.mjs [--out identity.json] [--label name]
// Makes the stealth spend/view keypair + hybrid ML-KEM-768/X25519 keypair, writes the identity 0600, prints
// ONLY the public half (metaAddress, kemPub, fingerprint) so you can carry it to an online machine by QR/paper,
// and never touches the network. Publish the public half with plus/msg2 SDK publishMailbox(wallet, { metaAddress, kemPub })
// from the online side; keep the file (or a sealed copy, e.g. coldbackup) offline.
// Dependencies: npm i @noble/curves @noble/post-quantum   (no ethers, no network)
import crypto from 'node:crypto';
import { writeFileSync, chmodSync, existsSync } from 'node:fs';
import { secp256k1 } from '@noble/curves/secp256k1';
import { KitchenSink_ml_kem768_x25519 as KEM } from '@noble/post-quantum/hybrid.js';

const args = Object.fromEntries(process.argv.slice(2).map((a, i, arr) => a.startsWith('--') ? [a.slice(2), arr[i + 1] && !arr[i + 1].startsWith('--') ? arr[i + 1] : true] : []).filter(Boolean));
const out = String(args.out || 'msg2-identity.json');
if (existsSync(out)) { console.error('refusing to overwrite ' + out); process.exit(2); }
const hex = (u8) => '0x' + Buffer.from(u8).toString('hex');
const spendPriv = secp256k1.utils.randomPrivateKey(), viewPriv = secp256k1.utils.randomPrivateKey();
const spendPub = hex(secp256k1.getPublicKey(spendPriv, true)), viewPub = hex(secp256k1.getPublicKey(viewPriv, true));
const kp = KEM.keygen();
const id = { label: args.label || null, created: new Date().toISOString(), generatedOffline: true,
  spendPriv: hex(spendPriv), viewPriv: hex(viewPriv), spendPub, viewPub,
  metaAddress: 'st:eth:0x' + spendPub.slice(2) + viewPub.slice(2),
  kemPub: Buffer.from(kp.publicKey).toString('base64'), kemSecret: Buffer.from(kp.secretKey).toString('base64') };
writeFileSync(out, JSON.stringify(id, null, 1), { mode: 0o600 }); try { chmodSync(out, 0o600); } catch {}
const fp = crypto.createHash('sha256').update(id.metaAddress + '|' + id.kemPub).digest('hex').slice(0, 16);
console.log('identity written (0600): ' + out);
console.log('PUBLIC HALF — safe to carry to the online machine:');
console.log(JSON.stringify({ metaAddress: id.metaAddress, kemPub: id.kemPub, fingerprint: fp }));
console.log('fingerprint ' + fp + ' — compare it on the online side after publishing (sha256(metaAddress|kemPub)[:16]).');
