| 1 | import { createHash, createPublicKey } from 'node:crypto'; |
| 2 | |
| 3 | import ssh2, { type |
| 4 | |
| 5 | // ssh2 is CommonJS: a named import type-checks and then fails to resolve at runtime under ESM. |
| 6 | const { parseKey } |
| 7 | |
| 8 | /** An uploaded key, reduced to what is stored. The algorithm is read back out of the blob rather than kept beside it, so the two can never disagree. */ |
| 9 | export interface SshPublicKey |
| 10 | type: string; |
| 11 | /** The key blob, base64, as the second field of an authorized_keys line. */ |
| 12 | blob: string; |
| 13 | /** SHA256 of the blob, base64 without padding - what `ssh-keygen -lf` prints after `SHA256:`. */ |
| 14 | fingerprint: string; |
| 15 | comment: string; |
| 16 | } |
| 17 | |
| 18 | /** OpenSSH refuses these too: a 1024-bit RSA key is forgeable by anyone who wants a push badly enough. */ |
| 19 | const MIN_RSA_MODULUS_BITS = 2048 |
| 20 | |
| 21 | /** Reads one authorized_keys line. Throws with a reason a person can act on; the caller turns that into a domain error. */ |
| 22 | export function readPublicKey(line |
| 23 | const text = |
| 24 | if (text.length |
| 25 | |
| 26 | const algorithm = |
| 27 | if (algorithm.endsWith |
| 28 | throw new Error( |
| 29 | } |
| 30 | |
| 31 | const parsed = |
| 32 | if (parsed instanceof |
| 33 | if (parsed.isPrivateKey |
| 34 | throw new Error( |
| 35 | } |
| 36 | |
| 37 | const blob = |
| 38 | if ( |
| 39 | parsed.type === |
| 40 | (createPublicKey(parsed.getPublicPEM |
| 41 | ?.modulusLength ?? 0) |
| 42 | ) { |
| 43 | throw new Error( |
| 44 | } |
| 45 | |
| 46 | return { |
| 47 | type: parsed.type |
| 48 | blob: blob.toString |
| 49 | fingerprint: fingerprintOf(blob |
| 50 | comment: parsed.comment |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | /** The algorithm a stored blob names itself, for display and for rebuilding the key. */ |
| 55 | export function keyTypeOf(blob |
| 56 | return algorithmOf(Buffer |
| 57 | } |
| 58 | |
| 59 | export function fingerprintOf(blob |
| 60 | return createHash('sha256 |
| 61 | } |
| 62 | |
| 63 | /** Rebuilds a stored blob into something that can verify a signature. The algorithm is the blob's own first field, so the line is reconstructed rather than remembered. */ |
| 64 | export function parseStoredKey(blob |
| 65 | const decoded = |
| 66 | const parsed = |
| 67 | if (parsed instanceof |
| 68 | return parsed; |
| 69 | } |
| 70 | |
| 71 | /** ssh-string: four bytes of length, then that many bytes. The first one in any public key blob is its algorithm name. */ |
| 72 | function algorithmOf(blob: |
| 73 | if (blob.length |
| 74 | const length = |
| 75 | if (length === |
| 76 | throw new Error( |
| 77 | } |
| 78 | return blob.toString |
| 79 | } |