import { generateKeyPairSync } from "node:crypto";
import { writeFileSync } from "node:fs";

function sshField(value) {
  const data = Buffer.isBuffer(value) ? value : Buffer.from(value);
  const length = Buffer.alloc(4);
  length.writeUInt32BE(data.length);
  return Buffer.concat([length, data]);
}

const { publicKey, privateKey } = generateKeyPairSync("ed25519");
const privatePem = privateKey.export({ type: "pkcs8", format: "pem" });
const publicDer = publicKey.export({ type: "spki", format: "der" });

// Ed25519 SubjectPublicKeyInfo ends with the 32-byte raw public key.
const expectedPrefix = Buffer.from("302a300506032b6570032100", "hex");
if (
  publicDer.length !== expectedPrefix.length + 32 ||
  !publicDer.subarray(0, expectedPrefix.length).equals(expectedPrefix)
) {
  throw new Error("Unexpected Ed25519 public-key format");
}

const rawPublicKey = publicDer.subarray(expectedPrefix.length);
const openSSH = Buffer.concat([
  sshField("ssh-ed25519"),
  sshField(rawPublicKey),
]).toString("base64");

writeFileSync("numus-private.pem", privatePem, { mode: 0o600, flag: "wx" });
writeFileSync(
  "numus-public.pub",
  `ssh-ed25519 ${openSSH} numus-client\n`,
  { mode: 0o644, flag: "wx" },
);

console.log("Created numus-private.pem and numus-public.pub");
