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