#!/usr/bin/env node // OTA key vault envelope: round trip, binding to the app, tamper and wrong-secret rejection, // and reuse of the decrypted key in the existing bundle signing helpers. import assert from 'node:assert/strict' import { generateKeyPairSync } from 'node:crypto' const vault = await import('../src/key/vault-envelope.ts') const { createRSA, decryptChecksum, encryptChecksum } = await import('../src/api/crypto.ts') const { assertKeyVaultOptions, pushKeyVault } = await import('../src/key/vault.ts') const appId = 'com.example.vault' const { publicKey, privateKey } = createRSA() const secret = vault.generateVaultSecret() assert.match(secret, /^capgo-vault-[\w-]{43}$/) // Fingerprint is identical whether computed from the public key or derived from the private key. const fingerprint = await vault.rsaPublicKeyFingerprint(publicKey) assert.equal(await vault.rsaPrivateKeyFingerprint(privateKey), fingerprint) assert.equal(vault.rsaPublicKeyPemFromPrivateKey(privateKey), publicKey) const pkcs8 = generateKeyPairSync('rsa', { modulusLength: 2048 }) assert.equal( await vault.rsaPrivateKeyFingerprint(pkcs8.privateKey.export({ type: 'pkcs8', format: 'pem' })), await vault.rsaPublicKeyFingerprint(pkcs8.publicKey.export({ type: 'pkcs1', format: 'pem' })), ) const sealed = await vault.sealOtaPrivateKey({ appId, privateKeyPem: privateKey, secret }) assert.equal(sealed.publicKeySha256, fingerprint) assert.equal(sealed.envelope.kdf.iterations, vault.OTA_KEY_VAULT_DEFAULT_ITERATIONS) assert.ok(!JSON.stringify(sealed.envelope).includes('PRIVATE KEY'), 'envelope must not contain the plaintext key') const roundTrip = JSON.parse(JSON.stringify(sealed.envelope)) const opened = await vault.openOtaPrivateKey({ appId, envelope: roundTrip, secret }) assert.equal(opened.trim(), privateKey.trim()) // The decrypted key signs exactly like the key file does. const checksum = 'a'.repeat(64) assert.equal(decryptChecksum(encryptChecksum(checksum, opened), publicKey), checksum) async function rejects(envelope, overrides = {}, pattern = /Cannot decrypt|Invalid key vault envelope/) { await assert.rejects(vault.openOtaPrivateKey({ appId, envelope, secret, ...overrides }), pattern) } await rejects(sealed.envelope, { secret: `${secret}x` }) await rejects(sealed.envelope, { appId: 'com.example.other' }) const flipped = Buffer.from(sealed.envelope.ciphertext, 'base64') flipped[0] ^= 1 await rejects({ ...sealed.envelope, ciphertext: flipped.toString('base64') }) await rejects({ ...sealed.envelope, kdf: { ...sealed.envelope.kdf, iterations: 700_000 } }) await rejects({ ...sealed.envelope, public_key_sha256: 'b'.repeat(64) }) await rejects({ ...sealed.envelope, kdf: { ...sealed.envelope.kdf, iterations: 1000 } }, {}, /unsupported key derivation/) await rejects({ ...sealed.envelope, version: 2 }, {}, /unsupported format/) await assert.rejects(vault.sealOtaPrivateKey({ appId, privateKeyPem: privateKey, secret: 'short' }), /at least 16/) await assert.rejects(vault.sealOtaPrivateKey({ appId, privateKeyPem: publicKey, secret }), /Expected a PEM/) // A "private key" holding only version, modulus and exponent cannot sign: refuse it. const pubDer = Buffer.from(publicKey.replace(/-----[^-]+-----|\s/g, ''), 'base64') const publicOnly = Buffer.concat([Buffer.from([0x30, 0x82, (pubDer.length - 1) >> 8, (pubDer.length - 1) & 0xFF, 0x02, 0x01, 0x00]), pubDer.subarray(4)]) await assert.rejects(vault.sealOtaPrivateKey({ appId, privateKeyPem: `-----BEGIN RSA PRIVATE KEY-----\n${publicOnly.toString('base64')}\n-----END RSA PRIVATE KEY-----`, secret }), /missing private fields/) // Every private field present but zeroed: structurally complete, unusable. Refuse it. { const der = Buffer.from(privateKey.replace(/-----[^-]+-----|\s/g, ''), 'base64') const readLen = (o) => { const l = der[o + 1]; if (!(l & 0x80)) return [o + 2, l]; const c = l & 0x7F; let v = 0; for (let i = 0; i < c; i++) v = v * 256 + der[o + 2 + i]; return [o + 2 + c, v] } let [pos] = readLen(0) const ints = [] for (let i = 0; i < 9; i++) { const [start, len] = readLen(pos); ints.push(der.subarray(pos, start + len)); pos = start + len } const zero = Buffer.from([0x02, 0x01, 0x00]) const body = Buffer.concat([...ints.slice(0, 3), zero, zero, zero, zero, zero, zero]) const zeroed = Buffer.concat([Buffer.from([0x30, 0x82, body.length >> 8, body.length & 0xFF]), body]) await assert.rejects(vault.sealOtaPrivateKey({ appId, privateKeyPem: `-----BEGIN RSA PRIVATE KEY-----\n${zeroed.toString('base64')}\n-----END RSA PRIVATE KEY-----`, secret }), /inconsistent private parameters/) } // pull never writes through a symlink, even a dangling one, and writes owner-only. const { writePrivateKeyFile } = await import('../src/key/vault.ts') const { mkdtempSync, symlinkSync, existsSync, statSync, readFileSync } = await import('node:fs') const { tmpdir } = await import('node:os') const { join } = await import('node:path') const dir = mkdtempSync(join(tmpdir(), 'capgo-vault-')) symlinkSync(join(dir, 'public', 'ota.pem'), join(dir, 'link.pem')) assert.throws(() => writePrivateKeyFile(join(dir, 'link.pem'), opened, true), /symbolic link/) assert.equal(existsSync(join(dir, 'public', 'ota.pem')), false) writePrivateKeyFile(join(dir, 'key.pem'), opened, false) assert.equal(readFileSync(join(dir, 'key.pem'), 'utf8'), opened) if (process.platform !== 'win32') assert.equal(statSync(join(dir, 'key.pem')).mode & 0o777, 0o600) assert.throws(() => writePrivateKeyFile(join(dir, 'key.pem'), privateKey.replace('A', 'B'), false), /different key/) assert.throws(() => assertKeyVaultOptions({ keyV2: '.capgo_key_v2' }), /cannot be combined/) assert.throws(() => assertKeyVaultOptions({ key: false }), /--no-key/) assert.throws(() => assertKeyVaultOptions({ external: 'https://example.com' }), /external/) assertKeyVaultOptions({}) // --key-vault enables encryption, so it must be rejected with --force-crc32-checksum like --key-data-v2. const { checkValidOptions } = await import('../src/bundle/upload.ts') assert.throws(() => checkValidOptions({ apikey: 'x', keyVault: true, forceCrc32Checksum: true }), /force-crc32-checksum/) // --generate-secret always makes a new secret: it cannot be mixed with a supplied secret file. await assert.rejects(pushKeyVault(appId, { generateSecret: true, vaultSecretFile: 'secret.txt' }), /--generate-secret cannot be combined with --vault-secret-file/) console.log('✅ key vault envelope tests passed')