noise-js.ts

12.6 KB · raw

1/**2 * Noise NK initiator for browser-to-browser sync.3 * Pattern: Noise_NK_25519_ChaChaPoly_BLAKE2s4 *5 * The protocol state machine lives in the canonical Rust `snow` core and is6 * compiled to WASM here and JNI on Android. This file keeps the stable7 * TypeScript orchestration API plus the post-handshake proof helpers.8 */910import { sharedKey } from "@stablelib/x25519";11import { BLAKE2s } from "@stablelib/blake2s";12import { SHA256 } from "@stablelib/sha256";13import { HMAC } from "@stablelib/hmac";14import {15  rustNoiseKkInitiator,16  rustNoiseKkResponder,17  rustNoiseNkInitiator,18  rustNoiseNkResponder,19} from "./noise-core";2021const PROTOCOL_NAME = "Noise_NK_25519_ChaChaPoly_BLAKE2s";2223// libhydrogen's contributory-behaviour blocklist: the nine small-order X2551924// u-coordinates. Mirrors X25519_SMALL_ORDER_PUBKEYS in crypto-core (PB-26-014)25// so the TS-side DH boundaries fail before the DH, not just the WASM core.26const X25519_SMALL_ORDER_PUBKEYS = new Set([27  "00".repeat(32),28  "01" + "00".repeat(31),29  "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",30  "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",31  "ec" + "ff".repeat(30) + "7f",32  "ed" + "ff".repeat(30) + "7f",33  "ee" + "ff".repeat(30) + "7f",34  "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",35  "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",36]);3738export function isSmallOrderPubkey(publicKey: Uint8Array): boolean {39  return publicKey.length === 32 && X25519_SMALL_ORDER_PUBKEYS.has(bytesToHex(publicKey));40}4142function initProtocolHash(protocolName: string): Uint8Array {43  const nameBytes = new TextEncoder().encode(protocolName);44  if (nameBytes.length <= 32) {45    const h = new Uint8Array(32);46    h.set(nameBytes);47    return h;48  }49  // PCH-01-002: the named pattern hash is BLAKE2s; the protocol-name init hash50  // MUST use it too (Noise spec §5.2), not SHA-256.51  return new BLAKE2s(32).update(nameBytes).digest();52}5354export function initHash(): Uint8Array {55  return initProtocolHash(PROTOCOL_NAME);56}5758export function hkdf2(ck: Uint8Array, ikm: Uint8Array): [Uint8Array, Uint8Array] {59  // PCH-01-002: HKDF must run over the named hash (BLAKE2s), not SHA-256.60  // @stablelib's HKDF reuses one HMAC across blocks and BLAKE2s's restoreState()61  // never clears its `finished` flag, so `new HKDF(BLAKE2s, …)` throws. Run62  // standard HKDF-Expand (RFC 5869, empty info) with a FRESH HMAC-BLAKE2s per63  // block — byte-identical to BouncyCastle `HKDFBytesGenerator(Blake2sDigest)`64  // on peach-android. NOTE: the HMAC-SHA256 post-handshake auth proof is a65  // SEPARATE construction, intentionally unchanged (so the SHA256 import stays).66  const prk = new HMAC(BLAKE2s, ck).update(ikm).digest(); // Extract (salt=ck)67  const k1 = new HMAC(BLAKE2s, prk).update(Uint8Array.of(1)).digest();68  const k2 = new HMAC(BLAKE2s, prk).update(k1).update(Uint8Array.of(2)).digest();69  return [k1, k2];70}7172export interface NoiseNKSession {73  encrypt(plaintext: Uint8Array): Uint8Array;74  decrypt(ciphertext: Uint8Array): Uint8Array;75  readonly handshakeHash: Uint8Array;76  rekeyOutgoing(): void;77  rekeyIncoming(): void;78  close(): void;79}8081/**82 * Standard Noise KK initiator for reconnects.83 *84 * Pre-messages: -> s, <- s85 * Message 1:    -> e, es, ss86 * Message 2:    <- e, ee, se87 *88 * Both static keys are local inputs. There is no negotiation and no fallback89 * to NK: a mismatch hard-fails this handshake.90 */91export async function noiseKKInitiator(92  ourStaticPrivateKey: Uint8Array,93  ourStaticPublicKey: Uint8Array,94  responderStaticPublicKey: Uint8Array,95  send: (msg: Uint8Array) => Promise<void>,96  receive: () => Promise<Uint8Array>,97): Promise<NoiseNKSession> {98  if (isSmallOrderPubkey(responderStaticPublicKey)) {99    throw new Error("noise: small-order X25519 responder static key");100  }101  return rustNoiseKkInitiator(102    ourStaticPrivateKey,103    ourStaticPublicKey,104    responderStaticPublicKey,105    send,106    receive,107  );108}109110/**111 * Standard Noise KK responder. The expected initiator key must come from the112 * local paired-device registry before this function is called.113 */114export async function noiseKKResponder(115  ourStaticPrivateKey: Uint8Array,116  ourStaticPublicKey: Uint8Array,117  expectedInitiatorStaticPublicKey: Uint8Array,118  send: (msg: Uint8Array) => Promise<void>,119  receive: () => Promise<Uint8Array>,120): Promise<NoiseNKSession> {121  return rustNoiseKkResponder(122    ourStaticPrivateKey,123    ourStaticPublicKey,124    expectedInitiatorStaticPublicKey,125    send,126    receive,127  );128}129130/**131 * Run the initiator side of the Noise NK handshake. The caller provides132 * `send` / `receive` for the two transport-side handshake messages and gets133 * back a session object that encrypts/decrypts subsequent transport frames.134 */135export async function noiseNKInitiator(136  responderStaticPublicKey: Uint8Array,137  send: (msg: Uint8Array) => Promise<void>,138  receive: () => Promise<Uint8Array>,139): Promise<NoiseNKSession> {140  if (isSmallOrderPubkey(responderStaticPublicKey)) {141    throw new Error("noise: small-order X25519 responder static key");142  }143  return rustNoiseNkInitiator(144    responderStaticPublicKey,145    send,146    receive,147  );148}149150/**151 * Compute the post-handshake auth proof.152 *153 * proof = HMAC-SHA256(154 *   key   = X25519(local_priv, remote_pub),  // 32-byte DH shared155 *   data  = "peach-sync-v1-initiator-auth"156 *        || initiator_public157 *        || responder_public158 *        || nonce_32159 * )160 *161 * Both sides pass the same DH peer key (their PEER's public key) and the same162 * initiator_public/responder_public ordering so the MAC matches. This helper163 * targets the initiator-side: `local_priv` is the initiator's private key,164 * `remote_pub` is the responder's public key.165 */166const AUTH_DOMAIN = new TextEncoder().encode("peach-sync-v1-initiator-auth");167168export function computeAuthProof(169  initiatorPrivate: Uint8Array,170  initiatorPublic: Uint8Array,171  responderPublic: Uint8Array,172  nonce: Uint8Array,173  handshakeHash: Uint8Array,174): Uint8Array {175  if (nonce.length !== 32) throw new Error("auth nonce must be 32 bytes");176  if (handshakeHash.length !== 32) throw new Error("handshake hash must be 32 bytes");177  if (isSmallOrderPubkey(responderPublic)) {178    throw new Error("small-order X25519 responder public key");179  }180181  const dh = sharedKey(initiatorPrivate, responderPublic, true);182  const mac = new HMAC(SHA256, dh);183  // PCH-01-003b: bind the proof to THIS Noise session so it cannot be replayed184  // onto a different handshake. handshakeHash is prepended; both sides hold the185  // identical value and feed it in the same position.186  mac.update(handshakeHash);187  mac.update(AUTH_DOMAIN);188  mac.update(initiatorPublic);189  mac.update(responderPublic);190  mac.update(nonce);191  return mac.digest();192}193194interface AuthChallengeFrame {195  type: "CHALLENGE";196  nonce_hex: string;197  responder_public_key_hex: string;198}199200interface AuthProofFrame {201  type: "PROOF";202  initiator_public_key_hex: string;203  proof_hex: string;204}205206function bytesToHex(bytes: Uint8Array): string {207  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");208}209210function hexToBytes(hex: string): Uint8Array {211  if (hex.length % 2 !== 0) throw new Error("invalid hex");212  const bytes = new Uint8Array(hex.length / 2);213  for (let i = 0; i < hex.length; i += 2) {214    bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);215  }216  return bytes;217}218219/**220 * Drive the initiator side of the post-handshake challenge/proof round. The221 * responder sends a `Challenge` JSON frame; we compute the HMAC and reply222 * with a `Proof` frame. Both frames are encrypted via the post-handshake223 * Noise transport (caller owns the `sendEncrypted` / `receiveEncrypted` pair).224 */225/**226 * Run the responder side of the Noise NK handshake. Symmetric with227 * `noiseNKInitiator` — the caller provides `send` / `receive` for the two228 * handshake messages and gets back a session for transport-phase frames.229 *230 * The Rust core runs the same state machine as the browser initiator and the231 * Android JNI adapter.232 */233export async function noiseNKResponder(234  ourStaticPrivateKey: Uint8Array,235  ourStaticPublicKey: Uint8Array,236  send: (msg: Uint8Array) => Promise<void>,237  receive: () => Promise<Uint8Array>,238): Promise<NoiseNKSession> {239  return rustNoiseNkResponder(240    ourStaticPrivateKey,241    ourStaticPublicKey,242    send,243    receive,244  );245}246247/**248 * Constant-time 32-byte equality. The MAC comparison in `verifyAuthProof`249 * goes through this so a same-LAN attacker can't time the HMAC compare.250 */251function constantTimeEq(a: Uint8Array, b: Uint8Array): boolean {252  if (a.length !== b.length) return false;253  let diff = 0;254  for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;255  return diff === 0;256}257258/**259 * Drive the responder side of the post-handshake challenge/proof round. We260 * generate a random 32-byte nonce, send `Challenge`, receive `Proof`, and261 * verify. Returns the initiator's authenticated public key on success.262 *263 * The MAC key is X25519(our_priv, initiator_pub) and the data is the same264 * domain-separated transcript both sides feed into HMAC-SHA256.265 */266export async function performResponderAuth(267  session: NoiseNKSession,268  ourPrivateKey: Uint8Array,269  ourPublicKey: Uint8Array,270  sendEncryptedJson: (data: Uint8Array) => Promise<void>,271  receiveEncryptedJson: () => Promise<Uint8Array>,272): Promise<{ initiatorPublicKey: Uint8Array }> {273  // PCH-01-003b: bind the verifier's recomputed MAC to this Noise session.274275  const nonce = new Uint8Array(32);276  crypto.getRandomValues(nonce);277278  const challenge: AuthChallengeFrame = {279    type: "CHALLENGE",280    nonce_hex: bytesToHex(nonce),281    responder_public_key_hex: bytesToHex(ourPublicKey),282  };283  await sendEncryptedJson(new TextEncoder().encode(JSON.stringify(challenge)));284285  const proofBytes = await receiveEncryptedJson();286  const proofFrame = JSON.parse(new TextDecoder().decode(proofBytes)) as AuthProofFrame;287  if (proofFrame.type !== "PROOF") {288    throw new Error("expected PROOF frame");289  }290291  const initiatorPublicKey = hexToBytes(proofFrame.initiator_public_key_hex);292  const claimedProof = hexToBytes(proofFrame.proof_hex);293  if (initiatorPublicKey.length !== 32) {294    throw new Error("initiator public key must be 32 bytes");295  }296  if (claimedProof.length !== 32) {297    throw new Error("proof must be 32 bytes");298  }299  if (isSmallOrderPubkey(initiatorPublicKey)) {300    throw new Error("small-order X25519 initiator public key");301  }302303  // mac_for(our_priv, initiator_pub_for_dh, initiator_pub, our_pub, nonce)304  const dh = sharedKey(ourPrivateKey, initiatorPublicKey, true);305  const mac = new HMAC(SHA256, dh);306  // PCH-01-003b: must mirror computeAuthProof — handshakeHash first, then the307  // existing domain/keys/nonce transcript. Same value, same position on both ends.308  mac.update(session.handshakeHash);309  mac.update(AUTH_DOMAIN);310  mac.update(initiatorPublicKey);311  mac.update(ourPublicKey);312  mac.update(nonce);313  const expected = mac.digest();314315  if (!constantTimeEq(expected, claimedProof)) {316    throw new Error("auth proof did not verify");317  }318  return { initiatorPublicKey };319}320321export async function performInitiatorAuth(322  session: NoiseNKSession,323  ourPrivateKey: Uint8Array,324  ourPublicKey: Uint8Array,325  responderPublicKey: Uint8Array,326  sendEncryptedJson: (data: Uint8Array) => Promise<void>,327  receiveEncryptedJson: () => Promise<Uint8Array>,328): Promise<void> {329  // PCH-01-003b: the Noise handshake hash is now mixed into the proof, binding330  // it to this exact session (was previously bound via the DH key only).331332  const challengeBytes = await receiveEncryptedJson();333  const challenge = JSON.parse(new TextDecoder().decode(challengeBytes)) as AuthChallengeFrame;334  if (challenge.type !== "CHALLENGE") {335    throw new Error("expected CHALLENGE frame");336  }337  const nonce = hexToBytes(challenge.nonce_hex);338  const responderKeyFromChallenge = hexToBytes(challenge.responder_public_key_hex);339  // Defence against an off-key challenge: the responder's claimed key MUST be340  // the one we Noise-NK-handshook against, otherwise an active MITM that341  // managed to substitute a different key is rerouting the auth round.342  if (343    responderKeyFromChallenge.length !== responderPublicKey.length ||344    !responderKeyFromChallenge.every((b, i) => b === responderPublicKey[i])345  ) {346    throw new Error("responder key in challenge does not match Noise handshake");347  }348349  const proof = computeAuthProof(350    ourPrivateKey,351    ourPublicKey,352    responderPublicKey,353    nonce,354    session.handshakeHash,355  );356  const proofFrame: AuthProofFrame = {357    type: "PROOF",358    initiator_public_key_hex: bytesToHex(ourPublicKey),359    proof_hex: bytesToHex(proof),360  };361  await sendEncryptedJson(new TextEncoder().encode(JSON.stringify(proofFrame)));362}363364export { bytesToHex, hexToBytes };