// Reads an OpenSSH public key line ("ssh-ed25519 AAAA... comment") and checks that it is what it says. // Only ed25519 and RSA (2048 bits and more) are taken. The comment is dropped: what is kept is exactly // " ", so nothing a user types can add a line or an option to a machine's authorized_keys. import { createHash } from "node:crypto"; const TYPES = new Set(["ssh-ed25519", "ssh-rsa"]); /** The length-prefixed fields of an SSH wire blob, or null when the blob does not parse to its end. */ function fields(buf) { const out = []; let i = 0; while (i < buf.length) { if (i + 4 > buf.length) return null; const len = buf.readUInt32BE(i); i += 4; if (i + len > buf.length) return null; out.push(buf.subarray(i, i + len)); i += len; } return out; } /** * @param {string} text one public key line * @returns {{ok:true, type:string, publicKey:string, fingerprint:string, bits:number} | {ok:false, reason:string}} */ export function parsePublicKey(text) { if (typeof text !== "string" || text.length > 8000) return { ok: false, reason: "expected one public key line" }; const line = text.trim(); if (/[\r\n]/.test(line)) return { ok: false, reason: "one key per entry: the text holds more than one line" }; if (/PRIVATE KEY/.test(line)) return { ok: false, reason: "this is a private key; paste the .pub file instead" }; const [type, b64] = line.split(/\s+/); if (!TYPES.has(type)) return { ok: false, reason: "only ssh-ed25519 and ssh-rsa public keys are taken" }; if (!b64 || !/^[A-Za-z0-9+/]+={0,2}$/.test(b64)) return { ok: false, reason: "the key body is not base64" }; const blob = Buffer.from(b64, "base64"); if (blob.toString("base64") !== b64) return { ok: false, reason: "the key body is not canonical base64" }; const f = fields(blob); if (!f || f.length === 0 || f[0].toString("latin1") !== type) return { ok: false, reason: "the key body does not match its type" }; let bits; if (type === "ssh-ed25519") { if (f.length !== 2 || f[1].length !== 32) return { ok: false, reason: "not a valid ed25519 public key" }; bits = 256; } else { if (f.length !== 3 || f[1].length === 0 || f[2].length === 0) return { ok: false, reason: "not a valid RSA public key" }; let n = f[2]; while (n.length > 1 && n[0] === 0) n = n.subarray(1); bits = (n.length - 1) * 8 + (32 - Math.clz32(n[0])); if (bits < 2048) return { ok: false, reason: `RSA keys must be at least 2048 bits (this one is ${bits})` }; if (bits > 16384) return { ok: false, reason: "RSA key too large" }; } const fingerprint = "SHA256:" + createHash("sha256").update(blob).digest("base64").replace(/=+$/, ""); return { ok: true, type, publicKey: `${type} ${b64}`, fingerprint, bits }; }