From 0a287b1e4208f40e59a46170051e43cb281ac242 Mon Sep 17 00:00:00 2001 From: Drew Robinson Date: Mon, 23 Nov 2026 21:02:33 +0000 Subject: [PATCH] feat: fall back to a pure-JS chacha20-poly1305 when node:crypto lacks the cipher HAP sessions are encrypted with ChaCha20-Poly1305. hapCrypto.ts asserted at module load that node:crypto's getCiphers() includes it. Every supported Node.js version has it, unless its OpenSSL was built without it or runs in FIPS mode, and runtimes that implement the Node.js API on another crypto backend do not expose it at all: Bun's node:crypto is backed by BoringSSL, which lacks this cipher, so HAP-NodeJS could not start there. Detect the cipher once at load; when it is absent, use the audited pure-JavaScript implementation from @noble/ciphers for the two seal/open helpers. Node.js behaviour is unchanged: the native cipher is still used whenever present. Tests load a copy of the module with getCiphers() mocked to omit the cipher and check the fallback against the existing vectors and the RFC 8439 AEAD test vector. Verified by pairing a Bun-hosted accessory from hap-controller and exchanging characteristic reads and writes over the encrypted session. --- package-lock.json | 13 ++++++++ package.json | 1 + src/lib/util/hapCrypto.spec.ts | 57 +++++++++++++++++++++++++++++++++- src/lib/util/hapCrypto.ts | 33 +++++++++++++++++--- 4 files changed, 99 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3ac6e04e7..265a7eb06 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@homebridge/ciao": "1.4.1-beta.0", + "@noble/ciphers": "^2.4.0", "bonjour-hap": "3.11.1-beta.0", "dbus-native": "^0.16.3", "debug": "^4.4.3", @@ -1333,6 +1334,18 @@ "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, + "node_modules/@noble/ciphers": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz", + "integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@ota-meshi/ast-token-store": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/@ota-meshi/ast-token-store/-/ast-token-store-0.3.0.tgz", diff --git a/package.json b/package.json index ae8b05c18..ccdea98e2 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ }, "dependencies": { "@homebridge/ciao": "1.4.1-beta.0", + "@noble/ciphers": "^2.4.0", "bonjour-hap": "3.11.1-beta.0", "dbus-native": "^0.16.3", "debug": "^4.4.3", diff --git a/src/lib/util/hapCrypto.spec.ts b/src/lib/util/hapCrypto.spec.ts index c1fb5f694..f2c33053a 100644 --- a/src/lib/util/hapCrypto.spec.ts +++ b/src/lib/util/hapCrypto.spec.ts @@ -2,7 +2,7 @@ import { Buffer } from 'node:buffer' import crypto from 'node:crypto' import tweetnacl from 'tweetnacl' -import { beforeEach, describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { HAPEncryption } from './eventedhttp.js' import * as hapCrypto from './hapCrypto.js' @@ -55,6 +55,61 @@ describe('hapCrypto', () => { expect(() => hapCrypto.chacha20_poly1305_decryptAndVerify(key, nonce, aad, manipulated, tag)).toThrow() }) + + describe('without native chacha20-poly1305 (fallback implementation)', () => { + // Runtimes implementing the node:crypto API on another backend (e.g. Bun on BoringSSL) lack this cipher. + // Load a fresh copy of hapCrypto with getCiphers() reporting it absent, so the @noble/ciphers path is used. + async function loadFallback(): Promise { + vi.resetModules() + vi.doMock('node:crypto', async () => { + const actual = await vi.importActual('node:crypto') + const getCiphers = () => actual.getCiphers().filter(name => name !== 'chacha20-poly1305') + return { + ...actual, + getCiphers, + default: { ...actual, getCiphers }, + } + }) + try { + return await import('./hapCrypto.js') + } finally { + vi.doUnmock('node:crypto') + } + } + + it('should produce the same ciphertext and tag as the native implementation', async () => { + const fallback = await loadFallback() + const encrypted = fallback.chacha20_poly1305_encryptAndSeal(key, nonce, aad, input) + expect(encrypted.ciphertext.toString('hex')).toBe(output.toString('hex')) + expect(encrypted.authTag.toString('hex')).toBe(tag.toString('hex')) + }) + + it('should decrypt what the native implementation encrypted', async () => { + const fallback = await loadFallback() + const plaintext = fallback.chacha20_poly1305_decryptAndVerify(key, nonce, aad, output, tag) + expect(plaintext.toString('hex')).toBe(input.toString('hex')) + }) + + it('should fail verification on manipulated data', async () => { + const fallback = await loadFallback() + const manipulated = Buffer.alloc(output.length) + output.copy(manipulated) + manipulated[3] = 5 + + expect(() => fallback.chacha20_poly1305_decryptAndVerify(key, nonce, aad, manipulated, tag)).toThrow() + }) + + it('should match the RFC 8439 section 2.8.2 AEAD test vector without AAD padding tricks', async () => { + const fallback = await loadFallback() + const rfcKey = fromHex('80818283 84858687 88898a8b 8c8d8e8f 90919293 94959697 98999a9b 9c9d9e9f') + const rfcNonce = fromHex('07000000 40414243 44454647') + const rfcAad = fromHex('50515253 c0c1c2c3 c4c5c6c7') + const rfcPlaintext = Buffer.from('Ladies and Gentlemen of the class of \'99: If I could offer you only one tip for the future, sunscreen would be it.') + const encrypted = fallback.chacha20_poly1305_encryptAndSeal(rfcKey, rfcNonce, rfcAad, rfcPlaintext) + expect(encrypted.ciphertext.subarray(0, 16).toString('hex')).toBe('d31a8d34648e60db7b86afbc53ef7ec2') + expect(encrypted.authTag.toString('hex')).toBe('1ae10b594f09e26a7e902ecbd0600691') + }) + }) }) describe('HKDF', () => { diff --git a/src/lib/util/hapCrypto.ts b/src/lib/util/hapCrypto.ts index 70c6b6560..bc1347d0b 100644 --- a/src/lib/util/hapCrypto.ts +++ b/src/lib/util/hapCrypto.ts @@ -4,11 +4,21 @@ import type { HAPEncryption } from './eventedhttp.js' import assert from 'node:assert' import { Buffer } from 'node:buffer' import crypto from 'node:crypto' -import process from 'node:process' -if (!crypto.getCiphers().includes('chacha20-poly1305')) { - // every supported Node.js version has this cipher, unless its OpenSSL was built without it or runs in FIPS mode - assert.fail(`The cipher 'chacha20-poly1305' is not supported by your Node.js ${process.version}. HAP-NodeJS cannot work without it!`) +import { chacha20poly1305 } from '@noble/ciphers/chacha.js' +import createDebug from 'debug' + +const debug = createDebug('HAP-NodeJS:Crypto') + +/** + * Whether `node:crypto` provides the ChaCha20-Poly1305 AEAD that HAP sessions use. + * Every supported Node.js version has it, unless its OpenSSL was built without it or runs in FIPS mode, + * and runtimes that implement the Node.js API on another crypto backend (Bun on BoringSSL) do not expose it. + * When it is missing, the pure-JavaScript implementation from `@noble/ciphers` is used instead. + */ +const NATIVE_CHACHA20_POLY1305 = crypto.getCiphers().includes('chacha20-poly1305') +if (!NATIVE_CHACHA20_POLY1305) { + debug('node:crypto does not provide chacha20-poly1305; using the @noble/ciphers implementation') } const X25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b656e04220420', 'hex') @@ -180,6 +190,12 @@ export function chacha20_poly1305_decryptAndVerify(key: Buffer, nonce: Buffer, a ]) } + if (!NATIVE_CHACHA20_POLY1305) { + // noble expects ciphertext || tag and throws if the tag does not verify + const sealed = Buffer.concat([ciphertext, authTag]) + return Buffer.from(chacha20poly1305(key, nonce, aad ?? undefined).decrypt(sealed)) + } + const decipher = crypto.createDecipheriv('chacha20-poly1305', key, nonce, { authTagLength: 16 }) if (aad) { decipher.setAAD(aad, { plaintextLength: ciphertext.length }) @@ -210,6 +226,15 @@ export function chacha20_poly1305_encryptAndSeal(key: Buffer, nonce: Buffer, aad ]) } + if (!NATIVE_CHACHA20_POLY1305) { + // noble returns ciphertext || tag + const sealed = Buffer.from(chacha20poly1305(key, nonce, aad ?? undefined).encrypt(plaintext)) + return { + ciphertext: sealed.subarray(0, sealed.length - 16), + authTag: sealed.subarray(sealed.length - 16), + } + } + const cipher = crypto.createCipheriv('chacha20-poly1305', key, nonce, { authTagLength: 16 }) if (aad) {