fix(security): generate OpenSSH-format Ed25519 keys compatible with ssh2

This commit is contained in:
tyuXX 2026-11-26 18:22:13 +00:00
parent 3b9e084916
commit 05abda3417

View file

@ -1,6 +1,7 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import ssh2 from 'ssh2';
import { z } from 'zod';
import {
VaultCredentialSchema,
@ -76,34 +77,18 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload {
}
}
function buildSshEd25519PublicAndFingerprint(spkiDer: Buffer, comment?: string): {
publicKey: string;
fingerprint: string;
} {
// Ed25519 SPKI DER is 44 bytes: 12-byte ASN.1 header + 32-byte raw public key
if (spkiDer.length !== 44) {
throw new Error(`Unexpected Ed25519 SPKI DER length: ${spkiDer.length}`);
export function computeOpenSshFingerprint(publicKeyLine: string): string {
const parsed = ssh2.utils.parseKey(publicKeyLine.trim());
if (parsed instanceof Error) {
throw parsed;
}
const rawPub = spkiDer.subarray(12);
const algBuf = Buffer.from('ssh-ed25519', 'ascii');
const wire = Buffer.allocUnsafe(4 + algBuf.length + 4 + rawPub.length);
wire.writeUInt32BE(algBuf.length, 0);
algBuf.copy(wire, 4);
wire.writeUInt32BE(rawPub.length, 4 + algBuf.length);
rawPub.copy(wire, 8 + algBuf.length);
const publicB64 = wire.toString('base64');
const fingerprintHash = crypto
const key = Array.isArray(parsed) ? parsed[0]! : parsed;
const hash = crypto
.createHash('sha256')
.update(wire)
.update(key.getPublicSSH())
.digest('base64')
.replace(/=+$/, '');
const publicKey = comment ? `ssh-ed25519 ${publicB64} ${comment}` : `ssh-ed25519 ${publicB64}`;
return {
publicKey,
fingerprint: `SHA256:${fingerprintHash}`,
};
return `SHA256:${hash}`;
}
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
@ -333,36 +318,25 @@ export class VaultService {
}): VaultCredentialMeta {
this.assertUnlocked();
const privateKeyEncoding = options.passphrase
? ({
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
const keyPair = options.passphrase
? ssh2.utils.generateKeyPairSync('ed25519', {
comment: options.comment ?? options.id,
passphrase: options.passphrase,
} as const)
: ({
type: 'pkcs8',
format: 'pem',
} as const);
cipher: 'aes256-ctr',
rounds: 16,
})
: ssh2.utils.generateKeyPairSync('ed25519', {
comment: options.comment ?? options.id,
});
const { publicKey: spkiDer, privateKey: privatePem } = crypto.generateKeyPairSync(
'ed25519',
{
publicKeyEncoding: { type: 'spki', format: 'der' },
privateKeyEncoding,
},
);
const { publicKey, fingerprint } = buildSshEd25519PublicAndFingerprint(
spkiDer,
options.comment ?? options.id,
);
const publicKey = keyPair.public.trim();
const fingerprint = computeOpenSshFingerprint(publicKey);
return this.upsertCredential({
id: options.id,
name: options.name,
type: 'ssh-key',
privateKey: privatePem,
privateKey: keyPair.private,
publicKey,
passphrase: options.passphrase || undefined,
fingerprint,