diff --git a/Cargo.lock b/Cargo.lock index 4020d14..002a01e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + [[package]] name = "aead" version = "0.6.1" @@ -15,7 +25,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ "crypto-common 0.2.2", - "inout", + "inout 0.2.6", ] [[package]] @@ -24,7 +34,7 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" dependencies = [ - "cipher", + "cipher 0.5.2", "cpubits", "cpufeatures 0.3.1", ] @@ -35,9 +45,9 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" dependencies = [ - "aead", + "aead 0.6.1", "aes", - "cipher", + "cipher 0.5.2", "ctr", "ctutils", "ghash", @@ -482,8 +492,8 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0be9b34d99d395af800e996c5784f810f8400ccd64202f91859dc677825b5378" dependencies = [ - "aead", - "cipher", + "aead 0.6.1", + "cipher 0.5.2", "ctr", "ctutils", ] @@ -521,6 +531,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.2" @@ -528,21 +549,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cipher", + "cipher 0.5.2", "cpufeatures 0.3.1", "rand_core 0.10.1", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead 0.5.2", + "chacha20 0.9.1", + "cipher 0.4.4", + "poly1305 0.8.0", + "zeroize", +] + [[package]] name = "chacha20poly1305" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" dependencies = [ - "aead", - "chacha20", - "cipher", - "poly1305", + "aead 0.6.1", + "chacha20 0.10.2", + "cipher 0.5.2", + "poly1305 0.9.1", ] [[package]] @@ -551,6 +585,17 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", + "zeroize", +] + [[package]] name = "cipher" version = "0.5.2" @@ -559,7 +604,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ "block-buffer 0.12.1", "crypto-common 0.2.2", - "inout", + "inout 0.2.6", ] [[package]] @@ -926,6 +971,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core 0.6.4", "typenum", ] @@ -973,7 +1019,7 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -986,6 +1032,21 @@ dependencies = [ "subtle", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "fiat-crypto 0.2.9", + "rand_core 0.6.4", + "rustc_version", + "subtle", +] + [[package]] name = "curve25519-dalek" version = "5.0.0" @@ -995,7 +1056,7 @@ dependencies = [ "cfg-if", "cpufeatures 0.3.1", "curve25519-dalek-derive", - "fiat-crypto", + "fiat-crypto 0.3.0", "rustc_version", "subtle", "zeroize", @@ -1183,6 +1244,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -1208,12 +1270,12 @@ dependencies = [ "arrayvec", "aws-lc-rs", "ccm", - "chacha20", - "chacha20poly1305", + "chacha20 0.10.2", + "chacha20poly1305 0.11.0", "der", "ecdsa", - "hkdf", - "hmac", + "hkdf 0.13.0", + "hmac 0.13.0", "log", "nom 8.0.0", "once_cell", @@ -1758,7 +1820,7 @@ dependencies = [ "digest 0.11.3", "ff", "group", - "hkdf", + "hkdf 0.13.0", "hybrid-array", "pem-rfc7468", "pkcs8", @@ -1882,6 +1944,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "fiat-crypto" version = "0.3.0" @@ -2476,13 +2544,31 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac 0.12.1", +] + [[package]] name = "hkdf" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", ] [[package]] @@ -2719,6 +2805,15 @@ dependencies = [ "cfb", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "inout" version = "0.2.6" @@ -3315,9 +3410,14 @@ name = "mullion-host" version = "0.1.0" dependencies = [ "anyhow", + "base64", "block2", + "chacha20poly1305 0.10.1", "clap", "dispatch2", + "getrandom 0.2.17", + "hkdf 0.12.4", + "hmac 0.12.1", "hostname", "local-ip-address", "mullion-proto", @@ -3331,10 +3431,14 @@ dependencies = [ "objc2-screen-capture-kit", "objc2-video-toolbox", "objc2-web-kit", + "rand 0.8.8", "serde", "serde_json", + "sha2 0.10.9", + "spake2", "str0m", "str0m-rust-crypto", + "subtle", "tiny_http", "tracing", "tracing-subscriber", @@ -3858,6 +3962,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "openssl" version = "0.10.82" @@ -3928,7 +4038,7 @@ checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" dependencies = [ "ecdsa", "elliptic-curve", - "fiat-crypto", + "fiat-crypto 0.3.0", "primefield", "primeorder", "sha2 0.11.1", @@ -4203,6 +4313,17 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash 0.5.1", +] + [[package]] name = "poly1305" version = "0.9.1" @@ -4210,7 +4331,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" dependencies = [ "cpufeatures 0.3.1", - "universal-hash", + "universal-hash 0.6.1", ] [[package]] @@ -4221,7 +4342,7 @@ checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" dependencies = [ "cpubits", "cpufeatures 0.3.1", - "universal-hash", + "universal-hash 0.6.1", ] [[package]] @@ -4463,7 +4584,7 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20", + "chacha20 0.10.2", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -4687,7 +4808,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ "crypto-bigint", - "hmac", + "hmac 0.13.0", ] [[package]] @@ -5237,6 +5358,18 @@ dependencies = [ "system-deps", ] +[[package]] +name = "spake2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" +dependencies = [ + "curve25519-dalek 4.1.3", + "hkdf 0.12.4", + "rand_core 0.6.4", + "sha2 0.10.9", +] + [[package]] name = "spki" version = "0.8.1" @@ -5298,7 +5431,7 @@ dependencies = [ "aes-gcm", "ctr", "dimpl", - "hmac", + "hmac 0.13.0", "p256", "sha1 0.11.0", "sha2 0.11.1", @@ -5894,6 +6027,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + [[package]] name = "universal-hash" version = "0.6.1" @@ -6783,7 +6926,7 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6" dependencies = [ - "curve25519-dalek", + "curve25519-dalek 5.0.0", "getrandom 0.4.3", "rand_core 0.10.1", "zeroize", diff --git a/README.md b/README.md index 0ce47cf..fa7746d 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,23 @@ hosts show up at once. ![Nearby hosts](docs/ui/nearby.png) +## Pairing and encryption + +The first time a device connects, the Mac shows a 6-digit code and the +device asks for it. The code never goes over the network: both sides run +SPAKE2 with it, so someone listening learns nothing they could test guesses +against, and a wrong code three times ends the attempt. The device then keeps +its own secret for that Mac, and connects without a code from then on. + +Every connection after that is sealed with the device's secret and a +one-time challenge from the Mac, both ways (ChaCha20-Poly1305). Nobody else on +the network can start a stream, replay an offer, or read or change the +setup, which carries the keys of the video's own encryption (DTLS-SRTP). +The layout map takes requests signed with the same secret. + +To make every device pair again, choose Forget Paired Devices… in the menu. +The protocol is in `crates/host/src/pairing.rs` and `crates/app/assets/pair.js`. + ## Arranging screens **Screens** (toolbar while streaming, or **Arrange screens** on the setup card) diff --git a/crates/app/assets/layout.js b/crates/app/assets/layout.js index 802d67b..aa94e79 100644 --- a/crates/app/assets/layout.js +++ b/crates/app/assets/layout.js @@ -61,11 +61,18 @@ scrim.addEventListener('click', close); document.addEventListener('keydown', (e) => { if (opened && e.key === 'Escape') close(); }); + // The Mac lets only paired devices see or move its screens. + function needPairing() { + if (!opened) return; + subEl.textContent = ''; + hint(`Connect to ${hostIp} first. The Mac shows a code to pair this device, then its screens open here.`, true); + } function hint(text, err) { hintEl.textContent = text; hintEl.classList.toggle('err', !!err); } async function load(first) { try { - const r = await fetch(baseUrl(hostIp) + '/screens', { cache: 'no-store' }); + const r = await fetch(baseUrl(hostIp) + '/screens', { cache: 'no-store', headers: mullion.authHeaders(hostIp, 'GET', '/screens') }); + if (r.status === 401) { needPairing(); return; } if (!r.ok) throw new Error((await r.text()).trim() || r.status); const v = await r.json(); if (!opened || drag || busy) return; @@ -367,8 +374,9 @@ busy = true; board.setAttribute('aria-busy', 'true'); try { + const body = JSON.stringify({ cells }); const r = await fetch(baseUrl(hostIp) + '/screens/layout', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cells }), + method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, mullion.authHeaders(hostIp, 'POST', '/screens/layout', body)), body, }); const text = await r.text(); if (!r.ok) throw new Error(text.trim() || `HTTP ${r.status}`); diff --git a/crates/app/assets/pair.js b/crates/app/assets/pair.js new file mode 100644 index 0000000..2dc85c1 --- /dev/null +++ b/crates/app/assets/pair.js @@ -0,0 +1,146 @@ +// Pairing and sealed signaling, the receiver's side of crates/host/src/pairing.rs. +// The two must match byte for byte. Crypto comes from vendor/noble.js +// (window.MullionNoble) because a page served over http:// is not a +// secure context and has no crypto.subtle; crypto.getRandomValues works there. +// +// pair(base, { name, askCode }) first time: SPAKE2 with the code the Mac shows +// load(hostId) / forget(hostId) the stored credential for a host +// sealOffer / openAnswer the offer and answer, sealed with the device secret +// signed(cred, method, path, body) X-Mullion-Auth header for other requests +(function () { + 'use strict'; + const N = window.MullionNoble; + const P = N.ed25519.Point; + const L = P.Fn.ORDER; + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const KEY = 'mullion.pair.'; + + // --- bytes --- + const concat = (...parts) => { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + for (const p of parts) { out.set(p, o); o += p.length; } + return out; + }; + const fromHex = (h) => Uint8Array.from(h.match(/../g).map((b) => parseInt(b, 16))); + const toBig = (b) => b.reduce((n, x) => (n << 8n) | BigInt(x), 0n); // big-endian + const b64 = (b) => { let s = ''; for (const x of b) s += String.fromCharCode(x); return btoa(s); }; + const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); + const random = (n) => crypto.getRandomValues(new Uint8Array(n)); + + // --- SPAKE2, as the Rust spake2 0.4 crate does it on Ed25519 --- + const M = P.fromBytes(fromHex('15cfd18e385952982b6a8f8c7854963b58e34388c8e6dae891db756481a02312')); + const NN = P.fromBytes(fromHex('f04f2e7eb734b2a8f8b472eaf9c3c632576ac64aea650b496a8a20ff00e583c3')); + const ID_A = enc.encode('mullion receiver'); + // Password scalar: HKDF-SHA256(salt "", info "SPAKE2 pw", 48 bytes), read big-endian, mod L. + const pwScalar = (pw) => toBig(N.hkdf(N.sha256, pw, new Uint8Array(0), enc.encode('SPAKE2 pw'), 48)) % L; + function randomScalar() { + for (;;) { const s = toBig(random(64)) % L; if (s !== 0n) return s; } + } + // Side A. `x` is for tests only. + function spakeA(code, hostId, x) { + const pw = enc.encode(code); + const idB = enc.encode('mullion host ' + hostId); + const w = pwScalar(pw); + x = x || randomScalar(); + const Xb = P.BASE.multiply(x).add(M.multiply(w)).toBytes(); + return { + msg: concat([0x41], Xb), + finish(msgB) { + if (msgB.length !== 33 || msgB[0] !== 0x42) throw new Error('bad SPAKE2 message'); + const Yb = msgB.subarray(1); + const K = P.fromBytes(Yb).add(NN.multiply(w).negate()).multiply(x); + return N.sha256(concat(N.sha256(pw), N.sha256(ID_A), N.sha256(idB), Xb, Yb, K.toBytes())); + }, + }; + } + + // --- keys, MACs, sealing --- + const derive = (ikm, salt, info) => N.hkdf(N.sha256, ikm, salt, enc.encode(info), 32); + const mac = (key, msg) => N.hmac(N.sha256, key, typeof msg === 'string' ? enc.encode(msg) : msg); + function seal(key, aad, plain) { + const n = random(12); + return { n: b64(n), c: b64(N.chacha20poly1305(key, n, enc.encode(aad)).encrypt(plain)) }; + } + const open = (key, aad, s) => N.chacha20poly1305(key, unb64(s.n), enc.encode(aad)).decrypt(unb64(s.c)); + function sameBytes(a, b) { + if (a.length !== b.length) return false; + let d = 0; for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]; + return d === 0; + } + + // --- stored credentials, one per host --- + function load(hostId) { + try { return JSON.parse(localStorage.getItem(KEY + hostId) || 'null'); } catch (e) { return null; } + } + function store(cred) { try { localStorage.setItem(KEY + cred.host_id, JSON.stringify(cred)); } catch (e) { /* */ } } + function forget(hostId) { try { localStorage.removeItem(KEY + hostId); } catch (e) { /* */ } } + + async function post(url, body) { + const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', credentials: 'omit' }); + let data = null; + try { data = await r.json(); } catch (e) { /* plain text error */ } + return { status: r.status, data }; + } + + // First connection to a host: ask it to show a code, ask the person for it, + // and run SPAKE2. askCode({ hostName, error }) resolves to the typed code, + // or null to give up. Resolves to the stored credential, or null. + async function pair(base, opts) { + const s = await post(base + '/pair/start', { name: opts.name }); + if (s.status === 429) throw new Error('Another device is pairing with this Mac. Try again in a few seconds.'); + if (s.status !== 200 || !s.data) throw new Error('This Mac did not start pairing.'); + const { pairing, host_id: hostId } = s.data; + let error = ''; + for (;;) { + const code = await opts.askCode({ hostName: opts.hostName, error }); + if (code == null) { + post(base + '/pair/cancel', { pairing }).catch(() => {}); + return null; + } + const a = spakeA(code.replace(/\D/g, ''), hostId); + const x = await post(base + '/pair/exchange', { pairing, msg: b64(a.msg) }); + if (x.status === 410) throw new Error('The code expired. Connect again for a new one.'); + if (x.status !== 200) throw new Error('Pairing failed.'); + const key = a.finish(unb64(x.data.msg)); + const k = { r: derive(key, undefined, 'mullion pair receiver'), h: derive(key, undefined, 'mullion pair host'), s: derive(key, undefined, 'mullion pair seal') }; + const c = await post(base + '/pair/confirm', { pairing, mac: b64(mac(k.r, 'receiver')) }); + if (c.status === 403) { + const left = c.data && c.data.left; + if (!left) throw new Error('Wrong code too many times. Connect again for a new one.'); + error = `That code is not the one on the Mac. ${left === 1 ? '1 try' : left + ' tries'} left.`; + continue; + } + if (c.status === 410) throw new Error('The code expired. Connect again for a new one.'); + if (c.status !== 200) throw new Error('Pairing failed.'); + // The Mac proves it knew the code too, so this is the Mac that showed it. + if (!sameBytes(unb64(c.data.mac), mac(k.h, 'host'))) throw new Error('This Mac could not prove the code. Pairing stopped.'); + const plain = JSON.parse(dec.decode(open(k.s, 'mullion pair seal', c.data.credential))); + const cred = { host_id: plain.host_id, host_name: plain.host_name, device: plain.device, secret: plain.secret }; + store(cred); + return cred; + } + } + + // Offer and answer, sealed with keys from the device secret and the host's + // one-time challenge. + function sealOffer(cred, nonce, obj) { + const key = derive(unb64(cred.secret), unb64(nonce), 'mullion offer'); + return seal(key, 'offer:' + cred.device, enc.encode(JSON.stringify(obj))); + } + function openAnswer(cred, nonce, sealed) { + const key = derive(unb64(cred.secret), unb64(nonce), 'mullion answer'); + return JSON.parse(dec.decode(open(key, 'answer:' + cred.device, sealed))); + } + + // X-Mullion-Auth for requests other than the offer (layout map). + function signed(cred, method, path, body) { + const ts = String(Date.now()); + const key = derive(unb64(cred.secret), undefined, 'mullion request'); + const msg = concat(enc.encode(`${method}\n${path}\n${ts}\n`), body ? enc.encode(body) : new Uint8Array(0)); + return `${cred.device}.${ts}.${b64(mac(key, msg))}`; + } + + window.mullionPair = { pair, load, forget, sealOffer, openAnswer, signed, _test: { spakeA, derive, mac, b64, unb64 } }; +})(); diff --git a/crates/app/assets/receiver.js b/crates/app/assets/receiver.js index b8cc379..53911d3 100644 --- a/crates/app/assets/receiver.js +++ b/crates/app/assets/receiver.js @@ -201,6 +201,41 @@ return caps; } + async function postJSON(url, body) { + const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', credentials: 'omit' }); + let data = null; + try { data = await r.json(); } catch (e) { /* plain text */ } + return { status: r.status, data }; + } + + // A paired host (one that names itself with host_id) takes only sealed + // offers (pair.js). Pair first if this device has no credential for it, + // then get the one-time challenge the offer is sealed with. Resolves to + // { cred, nonce }, null for an older host (plain offer), or false when the + // person cancelled pairing. + async function prepareAuth(hostIp, port, opts) { + const base = `http://${hostIp}:${port}`; + const h = await hello(hostIp, port, 3000); + if (!h) throw new Error(`Can't reach ${hostIp}. Check that Mullion is running on it.`); + if (!h.host_id || !window.mullionPair) return null; + let cred = mullionPair.load(h.host_id); + for (let round = 0; round < 2; round++) { + if (!cred) { + if (!opts.askCode) throw new Error('Pair this device with the Mac first.'); + setStatus('pairing'); + cred = await mullionPair.pair(base, { name: opts.name || deviceName(), hostName: h.name, askCode: opts.askCode }); + if (!cred) return false; + setStatus('connecting'); + } + const c = await postJSON(base + '/challenge', { device: cred.device }); + if (c.status === 200 && c.data && c.data.nonce) return { cred, nonce: c.data.nonce }; + // The Mac forgot this device: pair again, once. + if (c.status === 401) { mullionPair.forget(h.host_id); cred = null; continue; } + throw new Error(`${h.name || hostIp} did not answer.`); + } + throw new Error('Pairing did not finish.'); + } + async function connect(hostIp, videoEl, opts) { opts = opts || {}; const port = opts.port || portFor(hostIp); @@ -210,6 +245,14 @@ state.g2g = []; state.samples = []; state.offset = null; state.presented = 0; state.decoded = 0; state.decodeFail = 0; state.dropped = 0; state.lastFrameTs = 0; state.probe = null; state.stripMisses = 0; state.nextSampleAt = 0; setStatus('connecting'); + let auth; + try { + auth = await prepareAuth(hostIp, port, opts); + } catch (e) { + setStatus('error', { error: String(e.message || e) }); + return; + } + if (auth === false) { state.error = null; setStatus('idle'); return; } const pc = new RTCPeerConnection({ iceServers: [] }); state.pc = pc; pc.addTransceiver('video', { direction: 'recvonly' }); @@ -242,15 +285,28 @@ try { const ctrl = new AbortController(); const to = setTimeout(() => ctrl.abort(), 5000); + const plain = { type: 'offer', sdp: pc.localDescription.sdp, mode, device_name: opts.name || deviceName() }; + const body = auth + ? { device: auth.cred.device, sealed: mullionPair.sealOffer(auth.cred, auth.nonce, plain) } + : Object.assign({ device_id: deviceId() }, plain); const resp = await fetch(`http://${hostIp}:${port}/offer`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ type: 'offer', sdp: pc.localDescription.sdp, mode, device_id: deviceId(), device_name: opts.name || deviceName() }), signal: ctrl.signal, + body: JSON.stringify(body), signal: ctrl.signal, }); clearTimeout(to); + if (resp.status === 401) { + let j = {}; + try { j = await resp.json(); } catch (e) { /* */ } + if (j.pair && auth) mullionPair.forget(auth.cred.host_id); + throw new Error(j.error || 'Pair this device with the Mac first.'); + } if (!resp.ok) throw new Error(`${resp.status} ${await resp.text()}`); - answer = await resp.json(); + answer = auth ? mullionPair.openAnswer(auth.cred, auth.nonce, (await resp.json()).sealed) : await resp.json(); } catch (e) { - setStatus('error', { error: `Can't reach ${hostIp}. ${e.name === 'AbortError' ? 'No answer in 5 s.' : e.message}` }); + // Network failures read as "can't reach"; the host's or pairing's own reasons as they are. + const why = e.name === 'AbortError' ? `Can't reach ${hostIp}. No answer in 5 s.` + : e instanceof TypeError ? `Can't reach ${hostIp}. ${e.message}` : String(e.message || e); + setStatus('error', { error: why }); disconnect(); return; } @@ -288,6 +344,15 @@ // Port of each host we have heard from, so a host on a non-default port is // dialled where it answered. const knownPorts = new Map(); + // host_id of each host heard from, to find this device's pairing for it. + const hostIds = new Map(); + // X-Mullion-Auth for a request to a paired host (layout.js); none when this + // device has no pairing for it (this Mac's own page works without one). + function authHeaders(ip, method, path, body) { + const id = hostIds.get(ip); + const cred = id && window.mullionPair && mullionPair.load(id); + return cred ? { 'X-Mullion-Auth': mullionPair.signed(cred, method, path, body || '') } : {}; + } function portFor(ip) { if (knownPorts.has(ip)) return knownPorts.get(ip); if (/^https?:$/.test(location.protocol) && location.hostname === ip) { @@ -335,6 +400,7 @@ const h = await r.json(); if (!h || h.app !== 'mullion') return null; knownPorts.set(ip, port); + if (h.host_id) hostIds.set(ip, h.host_id); return Object.assign({}, h, { ip, port, ms: Math.round(performance.now() - t0) }); } catch (e) { return null; @@ -410,7 +476,7 @@ } window.mullion = { connect, disconnect, leave, stats: snapshot, onStatus: (fn) => state.listeners.push(fn), decodeStrip, unwrapMs, deviceId, deviceName, setDeviceName, - scan, hello, recentHosts, rememberHost, isLastUsed, portFor, parseTarget, + scan, hello, recentHosts, rememberHost, isLastUsed, portFor, parseTarget, authHeaders, // UI work without a host: feed a fake stream and status through the real paths. _simulate(status, videoEl, hostName) { if (videoEl && !videoEl.srcObject) { diff --git a/crates/app/assets/ui.css b/crates/app/assets/ui.css index 0d82b71..a0c0ae6 100644 --- a/crates/app/assets/ui.css +++ b/crates/app/assets/ui.css @@ -110,6 +110,11 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify- .ghost:active { transform: scale(0.97); } .ghost:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .hint { font-size: 13px; opacity: .7; min-height: 1.5em; } +/* Pairing: the 6-digit code the Mac shows. */ +/* Buttons set their own display, which would beat the hidden attribute. */ +.pair[hidden], #card button[hidden] { display: none; } +.pair input { font: 600 26px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .25em; text-align: center; font-variant-numeric: tabular-nums; } +.pair-actions { display: grid; gap: 6px; margin-top: 6px; } .hint.err { opacity: 1; } /* Project links: bottom-right of the setup screen, quiet until touched. diff --git a/crates/app/assets/ui.html b/crates/app/assets/ui.html index cdf4fc9..9c8dd32 100644 --- a/crates/app/assets/ui.html +++ b/crates/app/assets/ui.html @@ -56,6 +56,14 @@ +
diff --git a/crates/app/assets/ui.js b/crates/app/assets/ui.js index 6d7e6dc..138f362 100644 --- a/crates/app/assets/ui.js +++ b/crates/app/assets/ui.js @@ -41,6 +41,7 @@ const segMirror = $('segMirror'), segExtend = $('segExtend'), thumb = $('thumb'); const nameOut = $('nameOut'), modeBtn = $('modeBtn'), fsBtn = $('fsBtn'), dcBtn = $('dcBtn'); const screensBtn = $('screensBtn'), screensSetupBtn = $('screensSetupBtn'); + const pairBox = $('pairBox'), codeEl = $('code'), codeLabel = $('codeLabel'), pairGo = $('pairGo'), pairCancel = $('pairCancel'); const modeIcon = $('modeIcon'), modeLabel = $('modeLabel'), fsIcon = $('fsIcon'), fsLabel = $('fsLabel'); // Buttons hold an icon plus a label span; change the parts, never textContent. const setIcon = (use, name) => use.setAttribute('href', '#i-' + name); @@ -136,7 +137,36 @@ mullion.setDeviceName(nameEl.value); nameOut.textContent = nameEl.value || mullion.deviceName(); hint.textContent = `Connecting to ${ip}`; hint.classList.remove('err'); - mullion.connect(ip, video, { mode, name: nameEl.value, port: target.port }); + mullion.connect(ip, video, { mode, name: nameEl.value, port: target.port, askCode }); + } + + // Pairing (pair.js): the first time this device connects to a Mac, the Mac + // shows a 6-digit code and the person types it here. Resolves to the code, + // or null when they cancel. + function askCode({ hostName, error }) { + const who = hostName || 'the Mac'; + codeLabel.textContent = `Code shown on ${who}`; + hint.textContent = error || `${who} now shows a 6-digit code. Enter it to pair this device.`; + hint.classList.toggle('err', !!error); + codeEl.value = ''; + pairBox.hidden = false; goBtn.hidden = true; screensSetupBtn.hidden = true; + setTimeout(() => codeEl.focus(), 50); + return new Promise((resolve) => { + const done = (v) => { + pairGo.onclick = pairCancel.onclick = codeEl.onkeydown = null; + pairBox.hidden = true; goBtn.hidden = false; screensSetupBtn.hidden = false; + if (v != null) { hint.textContent = `Pairing with ${who}`; hint.classList.remove('err'); } + resolve(v); + }; + const submit = () => { + const digits = codeEl.value.replace(/\D/g, ''); + if (digits.length !== 6) { hint.textContent = 'The code has 6 digits.'; hint.classList.add('err'); codeEl.focus(); return; } + done(digits); + }; + pairGo.onclick = submit; + pairCancel.onclick = () => done(null); + codeEl.onkeydown = (e) => { if (e.key === 'Enter') submit(); else if (e.key === 'Escape') done(null); }; + }); } // --- Nearby: Mullion hosts found on this network (receiver.js scan) --- const hostsEl = $('hosts'), nearbyStatus = $('nearbyStatus'), nearbyEmpty = $('nearbyEmpty'); @@ -279,7 +309,8 @@ if (s.status === 'streaming') mullion.rememberHost(s.hostIp, mullion.portFor(s.hostIp)); if ((s.status === 'idle' || s.status === 'lost' || s.status === 'error') && !scanCtl && Date.now() - lastScan > 30000) setTimeout(runScan, 400); switch (s.status) { - case 'connecting': hint.textContent = `Connecting to ${s.hostIp}`; break; + case 'connecting': hint.textContent = `Connecting to ${s.hostIp}`; hint.classList.remove('err'); break; + case 'pairing': break; // askCode owns the hint while the code is asked for case 'connected': hint.textContent = `Connected to ${host}`; break; case 'streaming': stage.classList.add('live'); diff --git a/crates/app/assets/vendor/noble.js b/crates/app/assets/vendor/noble.js new file mode 100644 index 0000000..7d8e303 --- /dev/null +++ b/crates/app/assets/vendor/noble.js @@ -0,0 +1,5 @@ +/* Mullion vendor bundle: @noble/curves, @noble/hashes, @noble/ciphers 2.4.0 + (c) Paul Miller, MIT License, https://paulmillr.com/noble/ + Built by tools/vendor-crypto/build.sh; do not edit. Exposes window.MullionNoble. */ +var __mullionNoble=(()=>{var Zt=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var Jn=Object.prototype.hasOwnProperty;var tr=(e,t,n)=>t in e?Zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var er=(e,t)=>{for(var n in t)Zt(e,n,{get:t[n],enumerable:!0})},nr=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Qn(t))!Jn.call(e,r)&&r!==n&&Zt(e,r,{get:()=>t[r],enumerable:!(o=Vn(t,r))||o.enumerable});return e};var rr=e=>nr(Zt({},"__esModule",{value:!0}),e);var h=(e,t,n)=>tr(e,typeof t!="symbol"?t+"":t,n);var co={};er(co,{chacha20poly1305:()=>Kn,ed25519:()=>Hn,hkdf:()=>Fn,hmac:()=>Dt,sha256:()=>nn,sha512:()=>It});var zt=BigInt(4294967295),Ce=BigInt(32);function or(e,t=!1){return t?{h:Number(e&zt),l:Number(e>>Ce&zt)}:{h:Number(e>>Ce&zt)|0,l:Number(e&zt)|0}}function Me(e,t=!1){let n=e.length,o=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;se/2**32|0,ir=e=>e>>>0;function je(e,t,n,o){let r=sr(n),s=ir(n);e.setUint32(t,o?s:r,o),e.setUint32(t+4,o?r:s,o)}var ce=(e,t,n)=>e>>>n,ae=(e,t,n)=>e<<32-n|t>>>n,bt=(e,t,n)=>e>>>n|t<<32-n,gt=(e,t,n)=>e<<32-n|t>>>n,Lt=(e,t,n)=>e<<64-n|t>>>n-32,Rt=(e,t,n)=>e>>>n-32|t<<64-n;function et(e,t,n,o){let r=(t>>>0)+(o>>>0);return{h:e+n+(r/2**32|0)|0,l:r|0}}var ke=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ze=(e,t,n,o)=>t+n+o+(e/2**32|0)|0,ze=(e,t,n,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),$e=(e,t,n,o,r)=>t+n+o+r+(e/2**32|0)|0,Ye=(e,t,n,o,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0)+(r>>>0),Xe=(e,t,n,o,r,s)=>t+n+o+r+s+(e/2**32|0)|0;function $t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ue=e=>e?`"${e}" `:"";function ot(e,t=""){if(typeof e!="number")throw new TypeError(ue(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ue(t)+"expected integer >= 0, got "+e);return e}function G(e,t,n=""){if($t(e)&&(t===void 0||e.length===t))return e;t!==void 0&&ot(t,"length");let o=$t(e),r=t!==void 0?` of length ${t}`:"",s=o?`length=${e.length}`:`type=${typeof e}`,i=ue(n)+"expected Uint8Array"+r+", got "+s;throw o?new RangeError(i):new TypeError(i)}function _t(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ot(e.outputLen),ot(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var cr=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Ge=(e,t)=>{cr(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Bt(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Yt(e,t){G(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function K(...e){for(let t=0;t>>t}var We=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ar=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gt(e){if(G(e),We)return e.toHex();let t="";for(let n=0;n=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Pt(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(We)try{return Uint8Array.fromHex(e)}catch(r){throw r instanceof SyntaxError?new RangeError(r.message):r}let t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(n);for(let r=0,s=0;r 0");if(e.ORDER<=k)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Jt(e,t,n=!1){Tt(e),Kt(t,"nums"),st(n,"passZero");let o=e,r=new Array(t.length).fill(n?o.ZERO:void 0),s=t.reduce((f,c,a)=>o.is0(c)?f:(r[a]=f,o.mul(f,c)),o.ONE),i=o.inv(s);return t.reduceRight((f,c,a)=>o.is0(c)?f:(r[a]=o.mul(f,r[a]),o.mul(f,c)),i),r}function Ht(e,t){Tt(e);let n=e;Le(n.ORDER,"FpLegendre");let o=(n.ORDER-k)/mt,r=n.pow(t,o),s=n.eql(r,n.ONE),i=n.eql(r,n.ZERO),f=n.eql(r,n.neg(n.ONE));if(!s&&!i&&!f)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Tr(e,t){if(t!==void 0&&ge(t),e<=$)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let n=Oe(e);if(t!==void 0&&t= bitLen(n) (${n})`);let o=t!==void 0?t:n,r=Math.ceil(o/8);return{nBitLength:o,nByteLength:r}}var dn=new WeakMap,Qt=class{constructor(t,n={}){h(this,"ORDER");h(this,"BITS");h(this,"BYTES");h(this,"isLE");h(this,"ZERO",$);h(this,"ONE",k);h(this,"_lengths");h(this,"_mod");if(t<=k)throw new Error("invalid field: expected ORDER > 1, got "+t);let o;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(o=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:r,nByteLength:s}=Tr(t,o);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=r,this.BYTES=s,Object.freeze(this)}create(t){return z(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return $<=t&&tr)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let a=new Uint8Array(r);a.set(t,s?0:a.length-t.length),t=a}if(t.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let c=s?Ot(t):Vt(t);if(f&&(c=z(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Jt(this,t,!0)}cmov(t,n,o){return st(o,"condition"),o?n:t}};function te(e,t={}){return Object.freeze(Qt.prototype),new Qt(e,t)}var ve=BigInt(0),Ft=BigInt(1),Sr=BigInt(4),Re=16,wn=128,Lr=5,mn=2**31;function qt(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);wt(t.fromAffine,"Point.fromAffine"),wt(t.fromBytes,"Point.fromBytes"),wt(t.fromHex,"Point.fromHex"),dt(t.BASE,"Point.BASE"),dt(t.ZERO,"Point.ZERO"),Tt(t.Fp),Tt(t.Fn)}function Bn(e,t){qt(e),An(t,e);let n=Jt(e.Fp,t.map(o=>o.Z));return t.map((o,r)=>e.fromAffine(o.toAffine(n[r])))}function Rr(e,t,n=1){if(!Number.isSafeInteger(e)||et)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function _r(e,t){let n=e*(4*t+128);if(n>mn)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+mn/2**20+" MiB")}function vr(e,t){if(e!==void 0){wt(e,"randomBytes");try{let n=e(t);if(!Nt(n)||n.length!==t)return}catch{return}return e}}function An(e,t){Kt(e,"points"),e.forEach((n,o)=>{if(!(n instanceof t))throw new Error("invalid point at index "+o)})}function Ir(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((o,r)=>{if(!(n===void 0?t.isValid(o):lt(o)&&ove;){let i=0;e&Ft&&(i=Number(e&r),i>=o&&(i-=n),e-=BigInt(i)),s.push(i),e>>=Ft}return s}function Hr(e,t,n){let o=2**t,r=o/2,s=BigInt(o-1),i=BigInt(t),f=[];for(let c=0;c>=i,a>r&&(a-=o,e+=Ft),f.push(a)}if(e!==ve)throw new Error("invalid wnaf");return f}function Fr(e,t,n){let o=0;for(let s of n)o=Math.max(o,s.length);let r=e;for(let s=o-1;s>=0;s--){s!==o-1&&(r=r.double());for(let i=0;i>1];r=r.add(f<0?c.negate():c)}}}return r}var ee=class{constructor(t,n){h(this,"Point");h(this,"BASE");h(this,"ZERO");h(this,"randomBytes");h(this,"wnafPrecomputes",new WeakMap);h(this,"baseCanBeBlinded");h(this,"bits");qt(t),this.randomBytes=vr(n,Re),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,o){let r=Math.ceil(o/n)+1,s=2**(n-1),i=[],f=t;for(let c=0;cf.W===t&&f.bits===o);return i||(i=this.buildWnafTable(n,t,o),typeof r=="function"&&(i={...i,comp:r(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!Be(n,Ft,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,o,r){let s=_e(t);return s===1?this.fixedWindowCT(t,n,o):this.wnafCachedCT(this.getWnafPrecomputes(s,t,o,r),n)}mulCT(t,n,o){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,o)}mulCTBlinded(t,n,o){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let r=this.Point.Fn.BITS+wn,s=this.randomBytes(Re);if(!Nt(s)||s.length!==Re)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=n+Vt(s)*this.Point.Fn.ORDER;return this.runCT(t,i,r,o)}fixedWindowCT(t,n,o){let r=Lr,s=1<=0;u--){if(u!==c-1)for(let y=0;y>BigInt(u*r)&i),l=f[0];for(let y=1;y=this.Point.Fn.ORDER)return qr(this.Point,[t],[n],!0);let s=this.getWnafPrecomputes(r,t,this.bits,o);return this.wnafCachedCT(s,n).p}setWindowSize(t,n){this.assertPoint(t),Rr(n,this.bits);let o=Math.ceil((this.bits+wn)/n)+1;_r(o*2**(n-1),this.Point.Fp.BYTES),On.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return _e(t)!==1}};function qr(e,t,n,o=!1){if(qt(e),An(t,e),st(o,"allowOversized"),Ir(n,e.Fn,o?e.Fn.ORDER**Sr:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let r=t.map(i=>Nr(i,4)),s=n.map(i=>Ur(i,4));return Fr(e.ZERO,r,s)}function En(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Tt(t),t}else return te(e,{isLE:n})}function Tn(e,t,n={},o){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(o===void 0&&(o=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);ht(n);for(let c of["p","n","h"]){let a=t[c];if(!(lt(a)&&a!==ve))throw new Error(`CURVE.${c} must be positive bigint`)}let r=En(t.p,n.Fp,o),s=En(t.n,n.Fn,o),f=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of f)if(!r.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:r,Fn:s}}function Sn(e,t){return function(o){let r=e(o);return{secretKey:r,publicKey:t(r)}}}var ne=BigInt(0),re=BigInt(1),oe=BigInt(2),Dr=BigInt(4),Ln=BigInt(8);function Cr(e,t,n,o){let r=e.sqr(n),s=e.sqr(o),i=e.add(e.mul(t.a,r),s),f=e.add(e.ONE,e.mul(t.d,e.mul(r,s)));return e.eql(i,f)}function Rn(e,t={}){ht(t,{},{},"extraOpts");let n=t,o=Tn("edwards",e,n,n.FpFnLE),{Fp:r,Fn:s}=o,i=o.CURVE,{h:f}=i;if(Ht(r,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Ht(r,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ht(n,{},{uvRatio:"function",randomBytes:"function"});let c=n.randomBytes===void 0?me:n.randomBytes,a=oe<{try{return{isValid:!0,value:r.sqrt(r.div(q,p))}}catch{return{isValid:!1,value:ne}}}:n.uvRatio;if(!Cr(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let l=r.eql(i.a,r.neg(r.ONE))?q=>r.neg(q):r.eql(i.a,r.ONE)?q=>q:q=>r.mul(i.a,q);function y(q,p,O=!1){let w=O?re:ne;return Ae("coordinate "+q,p,w,a),p}function g(q){if(!(q instanceof E))throw new Error("EdwardsPoint expected")}let _=class _{constructor(p,O,w,H){h(this,"X");h(this,"Y");h(this,"Z");h(this,"T");this.X=y("x",p),this.Y=y("y",O),this.Z=y("z",w,!0),this.T=y("t",H),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){if(p instanceof _)throw new Error("extended point not allowed");let{x:O,y:w}=p||{};return y("x",O),y("y",w),new _(O,w,r.ONE,r.mul(O,w))}static fromBytes(p,O=!1){let w=r.BYTES,{a:H,d:F}=i;p=Ut(W(p,w,"point")),st(O,"zip215");let B=Ut(p),S=p[w-1];B[w-1]=S&-129;let I=Ot(B),N=O?a:r.ORDER;Ae("point.y",I,ne,N);let v=r.sqr(I),x=r.sub(v,r.ONE),A=r.sub(r.mulN(F,v),H),{isValid:T,value:L}=d(x,A);if(!T)throw new Error("bad point: invalid y coordinate");let U=u(L),b=(S&128)!==0;if(!O&&r.is0(L)&&b)throw new Error("bad point: x=0 and x_0=1");return b!==U&&(L=r.neg(L)),_.fromAffine({x:L,y:I})}static fromHex(p,O=!1){return _.fromBytes(sn(p),O)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,O=!0){return R.setWindowSize(this,p),O||this.multiply(oe),this}assertValidity(){let p=this,{a:O,d:w}=i;if(p.is0())throw new Error("bad point: ZERO");let{X:H,Y:F,Z:B,T:S}=p,I=r.sqr(H),N=r.sqr(F),v=r.sqr(B),x=r.sqr(v),A=r.mul(I,O),T=r.mul(r.add(A,N),v),L=r.add(x,r.mul(w,r.mul(I,N)));if(!r.eql(T,L))throw new Error("bad point: equation left != right (1)");let U=r.mul(H,F),b=r.mul(B,S);if(!r.eql(U,b))throw new Error("bad point: equation left != right (2)")}equals(p){g(p);let{X:O,Y:w,Z:H}=this,{X:F,Y:B,Z:S}=p,I=r.mul(O,S),N=r.mul(F,H),v=r.mul(w,S),x=r.mul(B,H);return r.eql(I,N)&&r.eql(v,x)}is0(){return this.equals(_.ZERO)}negate(){return new _(r.neg(this.X),this.Y,this.Z,r.neg(this.T))}double(){let{X:p,Y:O,Z:w}=this,H=r.sqr(p),F=r.sqr(O),B=r.mul(r.sqr(w),oe),S=l(H),I=r.addN(p,O),N=r.sub(r.subN(r.sqr(I),H),F),v=r.addN(S,F),x=r.subN(v,B),A=r.subN(S,F),T=r.mul(N,x),L=r.mul(v,A),U=r.mul(N,A),b=r.mul(x,v);return new _(T,L,b,U)}add(p){g(p);let{d:O}=i,{X:w,Y:H,Z:F,T:B}=this,{X:S,Y:I,Z:N,T:v}=p,x=r.mul(w,S),A=r.mul(H,I),T=r.mul(r.mulN(B,O),v),L=r.mul(F,N),U=r.sub(r.subN(r.mulN(r.addN(w,H),r.addN(S,I)),x),A),b=r.subN(L,T),C=r.addN(L,T),M=r.sub(A,l(x)),j=r.mul(U,b),X=r.mul(C,M),P=r.mul(U,M),V=r.mul(b,C);return new _(j,X,V,P)}subtract(p){return g(p),this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:O,f:w}=R.mulSecret(this,p,f,m);return m([O,w])[0]}multiplyUnsafe(p){if(!s.isValid(p))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return p===ne?_.ZERO:this.is0()||p===re?this:R.mulUnsafe(this,p,m)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return R.mulUnsafe(this,i.n).is0()}toAffine(p){let O=this,w=p;if(w!=null&&typeof w!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof w);let{X:H,Y:F,Z:B}=O,S=O.is0();w==null&&(w=S?r.create(Ln):r.inv(B));let I=r.mul(H,w),N=r.mul(F,w),v=r.mul(B,w);if(S)return{x:r.ZERO,y:r.ONE};if(!r.eql(v,r.ONE))throw new Error("invZ was invalid");return{x:I,y:N}}clearCofactor(){return f===re?this:f===oe?this.double():f===Dr?this.double().double():f===Ln?this.double().double().double():this.multiplyUnsafe(f)}toBytes(){let{x:p,y:O}=this.toAffine(),w=r.toBytes(O);return w[w.length-1]|=u(p)?128:0,w}toHex(){return on(this.toBytes())}toString(){return``}};h(_,"BASE",new _(i.Gx,i.Gy,r.ONE,r.mul(i.Gx,i.Gy))),h(_,"ZERO",new _(r.ZERO,r.ONE,r.ONE,r.ZERO)),h(_,"Fp",r),h(_,"Fn",s);let E=_,m=q=>Bn(E,q),R=new ee(E,c);return R.bits>=6&&E.BASE.precompute(6),Object.freeze(E.prototype),Object.freeze(E),E}function _n(e,t,n={}){if(qt(e),typeof t!="function")throw new Error('"hash" function param is required');let o=t,r=n;ht(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=r,{BASE:i,Fp:f,Fn:c}=e,a=o.outputLen,u=2*f.BYTES;if(a!==void 0&&(At(a,"hash.outputLen"),a!==u))throw new Error(`hash.outputLen must be ${u}, got ${a}`);let d=r.randomBytes===void 0?me:r.randomBytes,l=r.toMontgomery,y=r.toMontgomerySecret,g=r.adjustScalarBytes===void 0?x=>x:r.adjustScalarBytes,E=r.domain===void 0?(x,A,T)=>{if(st(T,"phflag"),A.length||T)throw new Error("Contexts/pre-hash are not supported");return x}:r.domain;function m(x){return c.create(Ot(x))}function R(x){let A=B.secretKey;W(x,B.secretKey,"secretKey");let T=W(o(x),2*A,"hashedSecretKey"),L=g(T.slice(0,A)),U=T.slice(A,2*A),b=m(L);return{head:L,prefix:U,scalar:b}}function _(x){let{head:A,prefix:T,scalar:L}=R(x),U=i.multiply(L),b=U.toBytes();return{head:A,prefix:T,scalar:L,point:U,pointBytes:b}}function q(x){return _(x).pointBytes}function p(x=Uint8Array.of(),...A){let T=we(...A);return m(o(E(T,W(x,void 0,"context"),!!s)))}function O(x,A,T={}){ht(T,{},{},"options"),x=Ut(W(x,void 0,"message")),s&&(x=s(x));let{prefix:L,scalar:U,pointBytes:b}=_(A),C=p(T.context,L,x),M=i.multiply(C).toBytes(),j=p(T.context,M,b,x),X=c.create(C+j*U);if(!c.isValid(X))throw new Error("sign failed: invalid s");let P=we(M,c.toBytes(X));return W(P,B.signature,"result")}let w={zip215:r.zip215};function H(x,A,T,L=w){ht(L);let{context:U}=L,b=L.zip215===void 0?!!w.zip215:L.zip215,C=B.signature;x=W(x,C,"signature"),A=W(A,void 0,"message"),T=W(T,B.publicKey,"publicKey"),b!==void 0&&st(b,"zip215"),s&&(A=s(A));let M=C/2,j=x.subarray(0,M),X=Ot(x.subarray(M,C)),P,V,rt;try{P=e.fromBytes(T,b),V=e.fromBytes(j,b),rt=i.multiplyUnsafe(X)}catch{return!1}if(!b&&P.isSmallOrder())return!1;let ft=p(U,j,T,A);return V.add(P.multiplyUnsafe(ft)).subtract(rt).clearCofactor().is0()}let F=f.BYTES,B={secretKey:F,publicKey:F,signature:2*F,seed:F};function S(x){return x=x===void 0?d(B.seed):x,W(x,B.seed,"seed")}function I(x){return Nt(x)&&x.length===B.secretKey}function N(x,A){try{return!!e.fromBytes(x,A===void 0?w.zip215:A)}catch{return!1}}let v={getExtendedPublicKey:_,randomSecretKey:S,isValidSecretKey:I,isValidPublicKey:N,toMontgomery(x){if(l===void 0)throw new Error("Montgomery conversion is not supported for this curve");return l(e.fromBytes(x))},toMontgomerySecret(x){if(y===void 0)throw new Error("Montgomery conversion is not supported for this curve");return y(x)}};return Object.freeze(B),Object.freeze(v),Object.freeze({keygen:Sn(S,q),getPublicKey:q,sign:O,verify:H,utils:v,Point:e,lengths:B})}var Ie=BigInt(1),vn=BigInt(2);var Mr=BigInt(5),jr=BigInt(8),Ne=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),kr={p:Ne,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:jr,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Zr(e){let t=BigInt(10),n=BigInt(20),o=BigInt(40),r=BigInt(80),s=Ne,f=e*e%s*e%s,c=J(f,vn,s)*f%s,a=J(c,Ie,s)*e%s,u=J(a,Mr,s)*a%s,d=J(u,t,s)*u%s,l=J(d,n,s)*d%s,y=J(l,o,s)*l%s,g=J(y,r,s)*y%s,E=J(g,r,s)*y%s,m=J(E,t,s)*u%s;return{pow_p_5_8:J(m,vn,s)*e%s,b2:f}}function Un(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var In=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zr(e,t){let n=Ne,o=z(t*t*t,n),r=z(o*o*t,n),s=Zr(e*r).pow_p_5_8,i=z(e*o*s,n),f=z(t*i*i,n),c=i,a=z(i*In,n),u=f===e,d=f===z(-e,n),l=f===z(-e*In,n);return u&&(i=c),(d||l)&&(i=a),gn(i,n)&&(i=z(-i,n)),{isValid:u||d,value:i}}var Ue=Rn(kr,{uvRatio:zr}),Nn=Ue.Fp;function $r(e){let{y:t}=e;return Nn.toBytes(Nn.div(Ie+t,Ie-t))}function Yr(e){let t=Ue.Fp.BYTES;return G(e,t),Un(It(e.subarray(0,t))).subarray(0,t)}function Xr(e){return _n(Ue,It,Object.assign({adjustScalarBytes:Un,toMontgomery:$r,toMontgomerySecret:Yr,zip215:!0},e))}var Hn=Xr({});var se=class{constructor(t,n){h(this,"oHash");h(this,"iHash");h(this,"blockLen");h(this,"outputLen");h(this,"canXOF",!1);h(this,"finished",!1);h(this,"destroyed",!1);if(_t(t),G(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,r=new Uint8Array(o);r.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s{let e=((t,n,o)=>new se(t,n).update(o).digest());return e.create=(t,n)=>new se(t,n),e})();var Ct=Uint8Array.of(0),Gr=Uint8Array.of();function Pr(e,t,n,o=32,r){_t(e),ot(o,"length"),G(t,void 0,"prk");let s=e.outputLen;if(t.length255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(o/s);if(n===void 0?n=Gr:G(n,void 0,"info"),!i)return r&&K(t),new Uint8Array;let f=r&&i===1?t:new Uint8Array(i*s),{iHash:c,oHash:a}=Dt.create(e,t),u=r?t:new Uint8Array(s),d=i>1?r?.iHash||e.create():void 0;for(let y=0;y1&&c.update(u),c.update(n).update(Ct).digestInto(u),a.update(u).digestInto(u),f.set(u,s*(i-1)),c.destroy(),a.destroy(),d?.destroy(),u!==f&&K(u),K(Ct),o===f.length)return f;let l=f.slice(0,o);return K(f),l}var Fn=(e,t,n,o,r)=>{_t(e),n===void 0&&(n=new Uint8Array(e.outputLen));let s=Dt.create(e,n).update(t);return Pr(e,s.digest(),o,r,s)};function He(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ie=e=>e?`"${e}" `:"";function fe(e,t=""){if(typeof e!="boolean")throw new TypeError(ie(t)+"expected boolean, got type="+typeof e);return e}function Et(e,t=""){if(typeof e!="number")throw new TypeError(ie(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ie(t)+"expected integer >= 0, got "+e);return e}function Z(e,t,n=""){if(He(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Et(t,"length");let o=He(e),r=t!==void 0?` of length ${t}`:"",s=o?`length=${e.length}`:`type=${typeof e}`,i=ie(n)+"expected Uint8Array"+r+", got "+s;throw o?new RangeError(i):new TypeError(i)}var qn=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function Fe(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Dn(e,t){Z(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function nt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function tt(...e){for(let t=0;t>>8&65280|e>>>24&255}function Vr(e){for(let t=0;te:Vr;function Qr(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset[]),s=(f,c)=>o(c,...r(f)).update(f).digest(),i=o(new Uint8Array(e),...r(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(f,...c)=>o(f,...c),s}var Zn=(e,t)=>{function n(o,...r){if(Z(o,void 0,"key"),e.nonceLength!==void 0){let d=r[0];Z(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength,i=e.nonceLength!==void 0?1:0;if(!e.withAAD){for(let d=i;d{if(l!==void 0){if(d!==2)throw new Error("cipher output not supported");Z(l,void 0,"output")}},a=!1;return{encrypt(d,l){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,Z(d,void 0,"data"),c(f.encrypt.length,l),f.encrypt(d,l)},decrypt(d,l){if(Z(d,void 0,"data"),s&&d.length= tagLength='+s);return c(f.decrypt.length,l),f.decrypt(d,l)}}}return Object.assign(n,e),n};function Mt(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(Z(t,e,"output"),n&&!jt(t))throw new Error("invalid output, must be aligned");return t}function zn(e,t,n){Et(e),Et(t),fe(n);let o=new Uint8Array(16),r=Wr(o);return r.setBigUint64(0,BigInt(t),n),r.setBigUint64(8,BigInt(e),n),o}function jt(e){return e.byteOffset%4===0}function St(e){return Uint8Array.from(Z(e))}var Yn=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),Jr=it(nt(Yn("expand 16-byte k"))),to=it(nt(Yn("expand 32-byte k")));function D(e,t){return e<>>32-t}var kt=64,eo=16,qe=2**32-1,$n=Uint32Array.of();function no(e,t,n,o,r,s,i,f){let c=r.length,a=new Uint8Array(kt),u=nt(a),d=pt&&jt(r)&&jt(s),l=d?nt(r):$n,y=d?nt(s):$n;if(!pt){for(let g=0;g=qe)throw new Error("arx: counter overflow");let E=Math.min(kt,c-g);for(let m=0,R;m=qe)throw new Error("arx: counter overflow");let E=Math.min(kt,c-g);if(d&&E===kt){let m=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let R=0,_;R{Z(f,void 0,"key"),Z(c,void 0,"nonce"),Z(a,void 0,"data");let l=a.length,y=u!==void 0;if(u=Mt(l,u,!1),y&&Cn(a,u),Et(d),d<0||d>=qe)throw new Error("arx: counter overflow");let g=[],E=f.length,m,R;if(E===32)g.push(m=St(f)),R=to;else if(E===16&&n)m=new Uint8Array(32),m.set(f),m.set(f,16),R=Jr,g.push(m);else throw Z(f,32,"arx key"),new Error("invalid key size");(!pt||!jt(c))&&g.push(c=St(c));let _=nt(m);if(o){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let O=c.subarray(0,16);if(pt)o(R,_,nt(O),_);else{let w=it(Uint32Array.from(R));o(w,_,nt(O),_),tt(w),it(_)}c=c.subarray(16)}else pt||it(_);let q=16-r;if(q!==c.length)throw new Error(`arx: nonce must be ${q} or 16 bytes`);if(q!==12){let O=new Uint8Array(12);O.set(c,s?0:12-c.length),c=O,g.push(c)}let p=it(nt(c));try{return no(e,R,_,p,a,u,d,i),u}finally{tt(...g)}}}function Y(e,t){return e[t++]&255|(e[t++]&255)<<8}var De=class{constructor(t){h(this,"blockLen",16);h(this,"outputLen",16);h(this,"buffer",new Uint8Array(16));h(this,"r",new Uint16Array(10));h(this,"h",new Uint16Array(10));h(this,"pad",new Uint16Array(8));h(this,"pos",0);h(this,"finished",!1);h(this,"destroyed",!1);t=St(Z(t,32,"key"));let n=Y(t,0),o=Y(t,2),r=Y(t,4),s=Y(t,6),i=Y(t,8),f=Y(t,10),c=Y(t,12),a=Y(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|o<<3)&8191,this.r[2]=(o>>>10|r<<6)&7939,this.r[3]=(r>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|f<<2)&8191,this.r[7]=(f>>>11|c<<5)&8065,this.r[8]=(c>>>8|a<<8)&8191,this.r[9]=a>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Y(t,16+2*u)}process(t,n,o=!1){let r=o?0:2048,{h:s,r:i}=this,f=i[0],c=i[1],a=i[2],u=i[3],d=i[4],l=i[5],y=i[6],g=i[7],E=i[8],m=i[9],R=Y(t,n+0),_=Y(t,n+2),q=Y(t,n+4),p=Y(t,n+6),O=Y(t,n+8),w=Y(t,n+10),H=Y(t,n+12),F=Y(t,n+14),B=s[0]+(R&8191),S=s[1]+((R>>>13|_<<3)&8191),I=s[2]+((_>>>10|q<<6)&8191),N=s[3]+((q>>>7|p<<9)&8191),v=s[4]+((p>>>4|O<<12)&8191),x=s[5]+(O>>>1&8191),A=s[6]+((O>>>14|w<<2)&8191),T=s[7]+((w>>>11|H<<5)&8191),L=s[8]+((H>>>8|F<<8)&8191),U=s[9]+(F>>>5|r),b=0,C=b+B*f+S*(5*m)+I*(5*E)+N*(5*g)+v*(5*y);b=C>>>13,C&=8191,C+=x*(5*l)+A*(5*d)+T*(5*u)+L*(5*a)+U*(5*c),b+=C>>>13,C&=8191;let M=b+B*c+S*f+I*(5*m)+N*(5*E)+v*(5*g);b=M>>>13,M&=8191,M+=x*(5*y)+A*(5*l)+T*(5*d)+L*(5*u)+U*(5*a),b+=M>>>13,M&=8191;let j=b+B*a+S*c+I*f+N*(5*m)+v*(5*E);b=j>>>13,j&=8191,j+=x*(5*g)+A*(5*y)+T*(5*l)+L*(5*d)+U*(5*u),b+=j>>>13,j&=8191;let X=b+B*u+S*a+I*c+N*f+v*(5*m);b=X>>>13,X&=8191,X+=x*(5*E)+A*(5*g)+T*(5*y)+L*(5*l)+U*(5*d),b+=X>>>13,X&=8191;let P=b+B*d+S*u+I*a+N*c+v*f;b=P>>>13,P&=8191,P+=x*(5*m)+A*(5*E)+T*(5*g)+L*(5*y)+U*(5*l),b+=P>>>13,P&=8191;let V=b+B*l+S*d+I*u+N*a+v*c;b=V>>>13,V&=8191,V+=x*f+A*(5*m)+T*(5*E)+L*(5*g)+U*(5*y),b+=V>>>13,V&=8191;let rt=b+B*y+S*l+I*d+N*u+v*a;b=rt>>>13,rt&=8191,rt+=x*c+A*f+T*(5*m)+L*(5*E)+U*(5*g),b+=rt>>>13,rt&=8191;let ft=b+B*g+S*y+I*l+N*d+v*u;b=ft>>>13,ft&=8191,ft+=x*a+A*c+T*f+L*(5*m)+U*(5*E),b+=ft>>>13,ft&=8191;let xt=b+B*E+S*g+I*y+N*l+v*d;b=xt>>>13,xt&=8191,xt+=x*u+A*a+T*c+L*f+U*(5*m),b+=xt>>>13,xt&=8191;let yt=b+B*m+S*E+I*g+N*y+v*l;b=yt>>>13,yt&=8191,yt+=x*d+A*u+T*a+L*c+U*f,b+=yt>>>13,yt&=8191,b=(b<<2)+b|0,b=b+C|0,C=b&8191,b=b>>>13,M+=b,s[0]=C,s[1]=M,s[2]=j,s[3]=X,s[4]=P,s[5]=V,s[6]=rt,s[7]=ft,s[8]=xt,s[9]=yt}finalize(){let{h:t,pad:n}=this,o=new Uint16Array(10),r=t[1]>>>13;t[1]&=8191;for(let f=2;f<10;f++)t[f]+=r,r=t[f]>>>13,t[f]&=8191;t[0]+=r*5,r=t[0]>>>13,t[0]&=8191,t[1]+=r,r=t[1]>>>13,t[1]&=8191,t[2]+=r,o[0]=t[0]+5,r=o[0]>>>13,o[0]&=8191;for(let f=1;f<10;f++)o[f]=t[f]+r,r=o[f]>>>13,o[f]&=8191;o[9]-=8192;let s=(r^1)-1;for(let f=0;f<10;f++)o[f]&=s;s=~s;for(let f=0;f<10;f++)t[f]=t[f]&s|o[f];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+n[0];t[0]=i&65535;for(let f=1;f<8;f++)i=(t[f]+n[f]|0)+(i>>>16)|0,t[f]=i&65535;tt(o)}update(t){Fe(this),Z(t),t=St(t);let{buffer:n,blockLen:o}=this,r=t.length;for(let s=0;s>>0,t[s++]=o[i]>>>8}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let o=t.slice(0,n);return this.destroy(),o}},Gn=kn(32,e=>new De(e));function ro(e,t,n,o,r,s=20){let i=e[0],f=e[1],c=e[2],a=e[3],u=t[0],d=t[1],l=t[2],y=t[3],g=t[4],E=t[5],m=t[6],R=t[7],_=r,q=n[0],p=n[1],O=n[2],w=i,H=f,F=c,B=a,S=u,I=d,N=l,v=y,x=g,A=E,T=m,L=R,U=_,b=q,C=p,M=O;for(let X=0;X{e.update(t);let n=t.length%16;n&&e.update(so.subarray(n))},io=new Uint8Array(32);function Wn(e,t,n,o,r){r!==void 0&&Z(r,void 0,"AAD");let s=e(t,n,io),i=zn(o.length,r?r.length:0,!0),f=Gn.create(s);r&&Pn(f,r),Pn(f,o),f.update(i);let c=f.digest();return tt(s,i),c}var fo=e=>(t,n,o)=>({encrypt(s,i){let f=s.length;i=Mt(f+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,n,c,c,1);let a=Wn(e,t,n,c,o);return i.set(a,f),tt(a),i},decrypt(s,i){i=Mt(s.length-16,i,!1);let f=s.subarray(0,-16),c=s.subarray(-16),a=Wn(e,t,n,f,o);if(!jn(c,a))throw tt(a),new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,n,i,i,1),tt(a),i}}),Kn=Zn({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},fo(oo));return rr(co);})(); +window.MullionNoble=__mullionNoble; diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 85b8321..e531cb8 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -13,6 +13,8 @@ use dioxus::document::eval; use dioxus::prelude::*; +const NOBLE_JS: &str = include_str!("../assets/vendor/noble.js"); +const PAIR_JS: &str = include_str!("../assets/pair.js"); const RECEIVER_JS: &str = include_str!("../assets/receiver.js"); const UI_JS: &str = include_str!("../assets/ui.js"); const LAYOUT_JS: &str = include_str!("../assets/layout.js"); @@ -53,6 +55,8 @@ fn App() -> Element { // Boot the shared scripts once the shared markup is in the document. use_future(move || async move { let _ = eval(&format!("window.MULLION_VERSION = {:?};", mullion_proto::version::VERSION)).await; + let _ = eval(NOBLE_JS).await; + let _ = eval(PAIR_JS).await; let _ = eval(RECEIVER_JS).await; let _ = eval(UI_JS).await; let _ = eval(LAYOUT_JS).await; diff --git a/crates/host/Cargo.toml b/crates/host/Cargo.toml index 5a7faa3..d46264a 100644 --- a/crates/host/Cargo.toml +++ b/crates/host/Cargo.toml @@ -21,6 +21,14 @@ tiny_http = "0.12" clap = { version = "4", features = ["derive"] } hostname = "0.4" local-ip-address = "0.6" +spake2 = { version = "0.4.0", features = ["getrandom"] } +chacha20poly1305 = "0.10" +hkdf = "0.12" +hmac = "0.12" +sha2 = "0.10" +getrandom = "0.2" +base64 = "0.22" +subtle = "2" [target.'cfg(target_os = "macos")'.dependencies] objc2 = "0.6" @@ -39,4 +47,5 @@ dispatch2 = "0.3" block2 = "0.6" [dev-dependencies] +rand = "0.8" ureq = { version = "2", default-features = false, features = ["json"] } diff --git a/crates/host/src/main.rs b/crates/host/src/main.rs index 89d3120..cd39f4b 100644 --- a/crates/host/src/main.rs +++ b/crates/host/src/main.rs @@ -11,6 +11,7 @@ mod config; mod menubar; mod platform; mod probe_page; +mod pairing; mod screens; mod session; mod signaling; @@ -90,6 +91,10 @@ struct Args { menu_bar: bool, } +/// The pairing store, for the code prompt's "Don't Allow" (the notifier is +/// built before the `Arc` exists). +static PAIRING: std::sync::OnceLock> = std::sync::OnceLock::new(); + /// Where Mullion.app keeps its files. struct AppPaths { logs: PathBuf, @@ -254,6 +259,32 @@ fn run(args: Args, app: Option) -> Result<()> { log.clone(), )?; + // Pairing: receivers must be let in with a code shown here. Kept with the + // app's other files, also when run from a terminal. + let pairing = Arc::new(pairing::Pairing::load( + Some(AppPaths::new().support.join("paired.json")), + Box::new({ + let in_app = app.is_some(); + move |n| match n { + pairing::Notice::Code { name, code } => { + println!("Pairing code for {name}: {} {}", &code[..3], &code[3..]); + #[cfg(target_os = "macos")] + if in_app { + let p = PAIRING.get().cloned(); + menubar::show_pair_code(name, code, Box::new(move || if let Some(p) = &p { p.cancel() })); + } + } + pairing::Notice::Closed => { + #[cfg(target_os = "macos")] + if in_app { + menubar::close_pair_code(); + } + } + } + }), + )); + let _ = PAIRING.set(pairing.clone()); + let addr = SocketAddr::new(args.bind, sw.port); let shared = Arc::new(session::SharedHandle(Mutex::new(handle))); let signaling = match signaling::Signaling::bind(addr, shared.clone(), host_name.clone()) { @@ -267,6 +298,7 @@ fn run(args: Args, app: Option) -> Result<()> { } .with_config(serde_json::to_value(&sw)?) .with_lan_ips(ips.iter().filter(|ip| !ip.is_loopback()).map(|ip| ip.to_string()).collect()) + .with_pairing(pairing.clone()) .with_web_port(sw.web_port); let lan = ips.first().map(|ip| ip.to_string()).unwrap_or_else(|| "127.0.0.1".into()); // What to type in a browser: the bare address when port 80 is ours, @@ -303,6 +335,18 @@ fn run(args: Args, app: Option) -> Result<()> { port: sw.port, logs_dir: a.logs.clone(), devices: Box::new(move || shared_for_menu.devices()), + paired: Box::new({ + let p = pairing.clone(); + move || p.paired_count() + }), + forget_paired: Box::new({ + let p = pairing.clone(); + let s = shared.clone(); + move || { + p.forget_all(); + s.0.lock().unwrap_or_else(|e| e.into_inner()).end_all(); + } + }), on_quit: Box::new(move || log_for_quit.flush()), updater: { let u = update::Updater::default(); diff --git a/crates/host/src/menubar.rs b/crates/host/src/menubar.rs index 8ed552f..a0885ed 100644 --- a/crates/host/src/menubar.rs +++ b/crates/host/src/menubar.rs @@ -62,6 +62,9 @@ pub struct MenuModel { /// Flush logs before the process exits. pub on_quit: Box, pub updater: Updater, + /// How many receivers are paired, and forgetting them all. + pub paired: Box usize>, + pub forget_paired: Box, } pub struct Ivars { @@ -158,6 +161,22 @@ define_class!( } } + #[unsafe(method(forgetPaired:))] + fn forget_paired(&self, _sender: Option<&AnyObject>) { + let m = &self.ivars().model; + let n = (m.paired)(); + let msg = format!("Forget {}?", if n == 1 { "the paired device".to_string() } else { format!("all {n} paired devices") }); + if alert_with( + self.mtm(), + &msg, + "Each one will need a new code from this Mac before it can show it again. Devices showing it now are disconnected.", + "Forget", + Some("Cancel"), + ) { + (m.forget_paired)(); + } + } + #[unsafe(method(showLogs:))] fn show_logs(&self, _sender: Option<&AnyObject>) { let dir = &self.ivars().model.logs_dir; @@ -252,6 +271,10 @@ impl Controller { if !CGPreflightScreenCaptureAccess() { self.action(menu, "Allow Screen Recording…", sel!(allowScreenRecording:), ""); } + let paired = (m.paired)(); + if paired > 0 { + self.action(menu, &format!("Forget Paired Devices ({paired})…"), sel!(forgetPaired:), ""); + } self.action(menu, "Show Logs", sel!(showLogs:), ""); menu.addItem(&NSMenuItem::separatorItem(mtm)); match update { @@ -281,6 +304,44 @@ fn on_main(f: impl FnOnce(MainThreadMarker) + Send + 'static) { DispatchQueue::main().exec_async(move || f(MainThreadMarker::new().expect("main queue runs on the main thread"))); } +/// Set while the pairing code is on screen, so closing it never closes some +/// other alert. +static PAIR_PROMPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Show the code a receiver must type to pair. `on_refuse` runs when the +/// owner says no. Called from any thread. +pub fn show_pair_code(name: String, code: String, on_refuse: Box) { + on_main(move |mtm| { + close_pair_code_now(mtm); + PAIR_PROMPT.store(true, std::sync::atomic::Ordering::SeqCst); + let spaced = format!("{} {}", &code[..3], &code[3..]); + let refused = !alert_with( + mtm, + &format!("{name} wants to show this Mac"), + &format!("Enter this code on {name}:\n\n{spaced}\n\nThe code works for 2 minutes. If you are not connecting {name}, click Don't Allow."), + "OK", + Some("Don't Allow"), + ); + if PAIR_PROMPT.swap(false, std::sync::atomic::Ordering::SeqCst) && refused { + on_refuse(); + } + }); +} + +/// Take the pairing code off screen (paired, expired or replaced). +pub fn close_pair_code() { + on_main(close_pair_code_now); +} + +fn close_pair_code_now(mtm: MainThreadMarker) { + if PAIR_PROMPT.swap(false, std::sync::atomic::Ordering::SeqCst) { + let app = NSApplication::sharedApplication(mtm); + if app.modalWindow().is_some() { + app.abortModal(); + } + } +} + /// A modal message with an OK button (and optionally a second one). Returns /// true when the first button was chosen. pub fn alert(mtm: MainThreadMarker, message: &str, detail: &str, second: Option<&str>) -> bool { diff --git a/crates/host/src/pairing.rs b/crates/host/src/pairing.rs new file mode 100644 index 0000000..d3907af --- /dev/null +++ b/crates/host/src/pairing.rs @@ -0,0 +1,659 @@ +//! Pairing: a receiver may stream only after the Mac's owner has let it in. +//! +//! First time: the receiver asks to pair (`/pair/start`) and the Mac shows a +//! 6-digit code. The person types it on the receiver, and both sides run +//! SPAKE2 with it (`/pair/exchange`, `/pair/confirm`). The code never crosses +//! the network, and someone listening learns nothing they could test guesses +//! against; someone in the middle gets one guess per attempt, and a pairing +//! allows three. On success the host gives the receiver its own device id and +//! a 32-byte secret, sealed with the SPAKE2 key. +//! +//! Every connection after that: the receiver gets a one-time challenge +//! (`/challenge`) and sends its offer sealed with a key from its secret and +//! that challenge. The host answers the same way. So only a paired receiver +//! can start a stream, an offer cannot be replayed, and nobody on the LAN can +//! read or change the SDP. The SDP carries the DTLS fingerprints, so the +//! media (already DTLS-SRTP encrypted) is bound to the paired pair of ends. +//! +//! Other requests from paired receivers (the layout map) carry +//! `X-Mullion-Auth: ..` over method, path, time and +//! body. The JS side is crates/app/assets/pair.js; the two must match. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use anyhow::{anyhow, Context, Result}; +use base64::{engine::general_purpose::STANDARD as B64, Engine}; +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use chacha20poly1305::{ChaCha20Poly1305, Nonce}; +use hkdf::Hkdf; +use hmac::{Hmac, Mac}; +use serde::{Deserialize, Serialize}; +use sha2::Sha256; +use spake2::{Ed25519Group, Identity, Password, Spake2}; +use subtle::ConstantTimeEq; +use tracing::{info, warn}; + +/// SPAKE2 identity of the receiver side (A). The host side (B) is +/// `"mullion host " + host_id`, so a code is good for this host only. +pub const ID_RECEIVER: &[u8] = b"mullion receiver"; +/// How long a pairing code is good for. +const CODE_TTL: Duration = Duration::from_secs(120); +/// Wrong codes before the pairing is cancelled. +const MAX_FAILURES: u8 = 3; +/// A new pairing may replace a pending one only after this long, so a +/// stream of requests cannot keep the owner's prompt flickering. +const MIN_RESTART: Duration = Duration::from_secs(5); +const CHALLENGE_TTL: Duration = Duration::from_secs(30); +/// Allowed clock difference for signed requests. +const AUTH_SKEW_MS: u64 = 60_000; +const MAX_DEVICES: usize = 64; + +/// What the owner should see. Called outside the lock. +pub enum Notice { + /// Show `code` for the device named `name`. + Code { name: String, code: String }, + /// Hide the code: paired, cancelled, expired or replaced. + Closed, +} + +/// A failed pairing step, with the HTTP status it maps to. +#[derive(Debug, PartialEq)] +pub enum PairError { + /// 400: malformed request. + Bad(&'static str), + /// 410: no pairing with that id, or it expired. + Gone, + /// 429: another device started pairing a moment ago. + Busy, + /// 403: the code was wrong; `left` attempts remain (0 = pairing cancelled). + WrongCode { left: u8 }, + /// 507: too many paired devices. + Full, +} + +#[derive(Serialize, Deserialize, Default)] +struct Store { + host_id: String, + devices: Vec, +} + +#[derive(Serialize, Deserialize, Clone)] +struct Device { + id: String, + name: String, + /// 32 bytes, base64. + secret: String, + paired_at: u64, +} + +struct Pending { + id: String, + code: String, + name: String, + started: Instant, + failures: u8, + /// SPAKE2 key from the latest `/pair/exchange`. + key: Option>, +} + +struct Inner { + store: Store, + pending: Option, + challenges: HashMap, +} + +pub struct Pairing { + path: Option, + inner: Mutex, + notify: Box, +} + +/// `/pair/start` reply. +#[derive(Serialize)] +pub struct Started { + pub pairing: String, + pub host_id: String, + pub expires_in: u64, +} + +/// `/pair/confirm` reply: the host's confirmation and the sealed credential. +#[derive(Serialize)] +pub struct Confirmed { + pub mac: String, + pub credential: Sealed, +} + +/// ChaCha20-Poly1305 output on the wire. +#[derive(Serialize, Deserialize, Clone)] +pub struct Sealed { + /// 12-byte nonce, base64. + pub n: String, + /// Ciphertext and tag, base64. + pub c: String, +} + +/// A verified offer: who sent it, and the key to seal the answer with. +pub struct OfferCtx { + pub device_id: String, + pub device_name: String, + answer_key: [u8; 32], +} + +impl Pairing { + /// Load paired devices from `path` (created on first pairing). `None` + /// keeps everything in memory (tests). + pub fn load(path: Option, notify: Box) -> Self { + let mut store: Store = path + .as_ref() + .and_then(|p| std::fs::read(p).ok()) + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + let fresh = store.host_id.is_empty(); + if fresh { + store.host_id = hex(&random::<16>()); + } + let p = Self { + path, + inner: Mutex::new(Inner { store, pending: None, challenges: HashMap::new() }), + notify, + }; + if fresh { + p.save(&p.lock().store); + } + p + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn host_id(&self) -> String { + self.lock().store.host_id.clone() + } + + pub fn is_paired(&self, device: &str) -> bool { + self.lock().store.devices.iter().any(|d| d.id == device) + } + + pub fn paired_count(&self) -> usize { + self.lock().store.devices.len() + } + + /// `/pair/start`: open a pairing and show its code on the Mac. + pub fn start(&self, name: &str) -> Result { + let (started, replaced) = { + let mut g = self.lock(); + if let Some(p) = &g.pending { + if p.started.elapsed() < MIN_RESTART { + return Err(PairError::Busy); + } + } + if g.store.devices.len() >= MAX_DEVICES { + return Err(PairError::Full); + } + let replaced = g.pending.is_some(); + let p = Pending { + id: hex(&random::<16>()), + code: six_digits(), + name: name.to_string(), + started: Instant::now(), + failures: 0, + key: None, + }; + let out = Started { pairing: p.id.clone(), host_id: g.store.host_id.clone(), expires_in: CODE_TTL.as_secs() }; + let notice = Notice::Code { name: p.name.clone(), code: p.code.clone() }; + g.pending = Some(p); + ((out, notice), replaced) + }; + info!("pairing requested by {name}"); + if replaced { + (self.notify)(Notice::Closed); + } + (self.notify)(started.1); + Ok(started.0) + } + + /// `/pair/exchange`: run the host side of SPAKE2 with the receiver's + /// message. Returns the host's message. Learns nothing about the code + /// yet; `/pair/confirm` does. + pub fn exchange(&self, pairing: &str, msg_a: &str) -> Result { + let msg_a = B64.decode(msg_a).map_err(|_| PairError::Bad("msg is not base64"))?; + let mut g = self.lock(); + let id_b = host_identity(&g.store.host_id); + let p = self.live_pending(&mut g, pairing)?; + let (spake, msg_b) = Spake2::::start_b( + &Password::new(p.code.as_bytes()), + &Identity::new(ID_RECEIVER), + &Identity::new(&id_b), + ); + let key = spake.finish(&msg_a).map_err(|_| PairError::Bad("bad SPAKE2 message"))?; + p.key = Some(key); + Ok(B64.encode(msg_b)) + } + + /// `/pair/confirm`: check the receiver's confirmation. Right code: the + /// device is paired and gets its credential. Wrong code: one attempt used. + pub fn confirm(&self, pairing: &str, mac: &str, host_name: &str) -> Result { + let mac = B64.decode(mac).map_err(|_| PairError::Bad("mac is not base64"))?; + let (result, closed) = { + let mut g = self.lock(); + let host_id = g.store.host_id.clone(); + let p = self.live_pending(&mut g, pairing)?; + let key = p.key.clone().ok_or(PairError::Bad("exchange first"))?; + let keys = PairKeys::new(&key); + if !bool::from(keys.receiver_mac().ct_eq(&mac)) { + p.failures += 1; + let left = MAX_FAILURES.saturating_sub(p.failures); + p.key = None; + warn!("pairing {}: wrong code ({left} attempts left)", p.name); + if left == 0 { + g.pending = None; + } + (Err(PairError::WrongCode { left }), left == 0) + } else { + let name = p.name.clone(); + g.pending = None; + let secret = random::<32>(); + let device = Device { + id: format!("d{}", hex(&random::<8>())), + name: name.clone(), + secret: B64.encode(secret), + paired_at: unix_ms() / 1000, + }; + let plain = serde_json::json!({ + "device": device.id, "secret": device.secret, "host_id": host_id, "host_name": host_name, + }); + let credential = seal(&keys.seal, b"mullion pair seal", plain.to_string().as_bytes()); + g.store.devices.push(device); + self.save(&g.store); + info!("paired {name}"); + (Ok(Confirmed { mac: B64.encode(keys.host_mac()), credential }), true) + } + }; + if closed { + (self.notify)(Notice::Closed); + } + result + } + + /// The owner pressed Cancel on the code prompt. + pub fn cancel(&self) { + if self.lock().pending.take().is_some() { + info!("pairing cancelled on the Mac"); + } + } + + /// The receiver gave up (`/pair/cancel`): take the code off the Mac. + pub fn abandon(&self, pairing: &str) { + let gone = { + let mut g = self.lock(); + let mine = g.pending.as_ref().is_some_and(|p| p.id == pairing); + if mine { + g.pending = None; + } + mine + }; + if gone { + (self.notify)(Notice::Closed); + } + } + + /// Forget every paired device: each has to pair again. + pub fn forget_all(&self) { + let mut g = self.lock(); + g.store.devices.clear(); + g.challenges.clear(); + self.save(&g.store); + info!("forgot all paired devices"); + } + + fn live_pending<'a>(&self, g: &'a mut Inner, pairing: &str) -> Result<&'a mut Pending, PairError> { + match &g.pending { + Some(p) if p.id == pairing && p.started.elapsed() <= CODE_TTL => {} + Some(p) if p.id == pairing => { + g.pending = None; + (self.notify)(Notice::Closed); + return Err(PairError::Gone); + } + _ => return Err(PairError::Gone), + } + Ok(g.pending.as_mut().unwrap()) + } + + /// `/challenge`: a one-time nonce for the next offer from `device`. + /// `None` when the device is not paired (it must pair first). + pub fn challenge(&self, device: &str) -> Option { + let mut g = self.lock(); + g.store.devices.iter().find(|d| d.id == device)?; + g.challenges.retain(|_, (_, t)| t.elapsed() < CHALLENGE_TTL); + let nonce = random::<16>(); + g.challenges.insert(device.to_string(), (nonce, Instant::now())); + Some(B64.encode(nonce)) + } + + /// Open a sealed offer. Uses up the device's challenge either way. + pub fn open_offer(&self, device: &str, sealed: &Sealed) -> Result<(Vec, OfferCtx)> { + let mut g = self.lock(); + let (nonce, at) = g.challenges.remove(device).ok_or_else(|| anyhow!("no challenge for this device"))?; + if at.elapsed() > CHALLENGE_TTL { + return Err(anyhow!("challenge expired")); + } + let d = g.store.devices.iter().find(|d| d.id == device).ok_or_else(|| anyhow!("not paired"))?; + let secret = B64.decode(&d.secret).context("stored secret")?; + let offer_key = derive(&secret, Some(&nonce), b"mullion offer"); + let plain = open(&offer_key, format!("offer:{device}").as_bytes(), sealed)?; + let ctx = OfferCtx { + device_id: d.id.clone(), + device_name: d.name.clone(), + answer_key: derive(&secret, Some(&nonce), b"mullion answer"), + }; + Ok((plain, ctx)) + } + + pub fn seal_answer(&self, ctx: &OfferCtx, plain: &[u8]) -> Sealed { + seal(&ctx.answer_key, format!("answer:{}", ctx.device_id).as_bytes(), plain) + } + + /// Check `X-Mullion-Auth` on a request from a paired device. Returns the + /// device id when the signature is good and fresh. + pub fn verify_request(&self, header: &str, method: &str, path: &str, body: &[u8]) -> Option { + let mut it = header.splitn(3, '.'); + let (device, ts, mac) = (it.next()?, it.next()?, it.next()?); + let ts_ms: u64 = ts.parse().ok()?; + if unix_ms().abs_diff(ts_ms) > AUTH_SKEW_MS { + return None; + } + let mac = B64.decode(mac).ok()?; + let g = self.lock(); + let d = g.store.devices.iter().find(|d| d.id == device)?; + let secret = B64.decode(&d.secret).ok()?; + let want = request_mac(&secret, method, path, ts, body); + bool::from(want.ct_eq(&mac)).then(|| d.id.clone()) + } + + fn save(&self, store: &Store) { + let Some(path) = &self.path else { return }; + if let Err(e) = write_private(path, &serde_json::to_vec_pretty(store).unwrap_or_default()) { + warn!("can't save paired devices to {}: {e:#}", path.display()); + } + } +} + +/// Keys from the SPAKE2 secret: one per direction for confirmation, one to +/// seal the credential. +pub(crate) struct PairKeys { + receiver: [u8; 32], + host: [u8; 32], + pub(crate) seal: [u8; 32], +} + +impl PairKeys { + pub(crate) fn new(spake_key: &[u8]) -> Self { + Self { + receiver: derive(spake_key, None, b"mullion pair receiver"), + host: derive(spake_key, None, b"mullion pair host"), + seal: derive(spake_key, None, b"mullion pair seal"), + } + } + pub(crate) fn receiver_mac(&self) -> Vec { + hmac(&self.receiver, b"receiver") + } + pub(crate) fn host_mac(&self) -> Vec { + hmac(&self.host, b"host") + } +} + +pub(crate) fn host_identity(host_id: &str) -> Vec { + format!("mullion host {host_id}").into_bytes() +} + +pub(crate) fn derive(ikm: &[u8], salt: Option<&[u8]>, info: &[u8]) -> [u8; 32] { + let mut out = [0u8; 32]; + Hkdf::::new(salt, ikm).expand(info, &mut out).expect("32 bytes is a valid HKDF length"); + out +} + +fn hmac(key: &[u8], msg: &[u8]) -> Vec { + let mut m = as Mac>::new_from_slice(key).expect("HMAC takes any key length"); + m.update(msg); + m.finalize().into_bytes().to_vec() +} + +pub(crate) fn request_mac(secret: &[u8], method: &str, path: &str, ts: &str, body: &[u8]) -> Vec { + let key = derive(secret, None, b"mullion request"); + let mut msg = format!("{method}\n{path}\n{ts}\n").into_bytes(); + msg.extend_from_slice(body); + hmac(&key, &msg) +} + +pub(crate) fn seal(key: &[u8; 32], aad: &[u8], plain: &[u8]) -> Sealed { + let nonce = random::<12>(); + let ct = ChaCha20Poly1305::new(key.into()) + .encrypt(Nonce::from_slice(&nonce), Payload { msg: plain, aad }) + .expect("encrypting in memory cannot fail"); + Sealed { n: B64.encode(nonce), c: B64.encode(ct) } +} + +pub(crate) fn open(key: &[u8; 32], aad: &[u8], s: &Sealed) -> Result> { + let nonce = B64.decode(&s.n).context("nonce")?; + let ct = B64.decode(&s.c).context("ciphertext")?; + if nonce.len() != 12 { + return Err(anyhow!("nonce must be 12 bytes")); + } + ChaCha20Poly1305::new(key.into()) + .decrypt(Nonce::from_slice(&nonce), Payload { msg: &ct, aad }) + .map_err(|_| anyhow!("does not decrypt: wrong key or tampered")) +} + +fn random() -> [u8; N] { + let mut b = [0u8; N]; + getrandom::getrandom(&mut b).expect("the OS random source is available"); + b +} + +/// Uniform 000000-999999. +fn six_digits() -> String { + loop { + let n = u32::from_le_bytes(random::<4>()); + // Reject the top sliver so every code is equally likely. + if n < 4_294_000_000 { + return format!("{:06}", n % 1_000_000); + } + } +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +pub(crate) fn unix_ms() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) +} + +/// Write `bytes` readable by this user only (the file holds device secrets). +fn write_private(path: &std::path::Path, bytes: &[u8]) -> Result<()> { + use std::io::Write; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("tmp"); + let mut o = std::fs::OpenOptions::new(); + o.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); + o.open(&tmp)?.write_all(bytes)?; + std::fs::rename(&tmp, path)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + /// A pairing and the code it showed. + fn pairing() -> (Pairing, Arc>>) { + let shown = Arc::new(Mutex::new(Vec::new())); + let s = shown.clone(); + let p = Pairing::load(None, Box::new(move |n| { + if let Notice::Code { code, .. } = n { + s.lock().unwrap().push(code); + } + })); + (p, shown) + } + + /// The receiver's side, as pair.js does it. + fn receiver(p: &Pairing, pairing: &str, code: &str) -> Result { + let id_b = host_identity(&p.host_id()); + let (spake, msg_a) = + Spake2::::start_a(&Password::new(code.as_bytes()), &Identity::new(ID_RECEIVER), &Identity::new(&id_b)); + let msg_b = B64.decode(p.exchange(pairing, &B64.encode(msg_a))?).unwrap(); + let keys = PairKeys::new(&spake.finish(&msg_b).unwrap()); + let c = p.confirm(pairing, &B64.encode(keys.receiver_mac()), "Mac")?; + assert_eq!(B64.decode(&c.mac).unwrap(), keys.host_mac(), "host proves it knew the code"); + let cred: serde_json::Value = serde_json::from_slice(&open(&keys.seal, b"mullion pair seal", &c.credential).unwrap()).unwrap(); + assert_eq!(cred["host_id"], p.host_id()); + Ok(c) + } + + #[test] + fn right_code_pairs_and_wrong_codes_run_out() { + let (p, shown) = pairing(); + let s = p.start("iPad").unwrap(); + let code = shown.lock().unwrap()[0].clone(); + assert_eq!(code.len(), 6); + let wrong = if code == "000000" { "111111" } else { "000000" }; + assert_eq!(receiver(&p, &s.pairing, wrong).err(), Some(PairError::WrongCode { left: 2 })); + assert!(receiver(&p, &s.pairing, &code).is_ok()); + assert_eq!(p.paired_count(), 1); + // A finished pairing cannot be reused. + assert_eq!(receiver(&p, &s.pairing, &code).err(), Some(PairError::Gone)); + + p.lock().pending = None; + let s = p.start("Pixel").unwrap(); + let code = shown.lock().unwrap()[1].clone(); + let wrong = if code == "000000" { "111111" } else { "000000" }; + for left in [2, 1, 0] { + assert_eq!(receiver(&p, &s.pairing, wrong).err(), Some(PairError::WrongCode { left })); + } + assert_eq!(receiver(&p, &s.pairing, &code).err(), Some(PairError::Gone), "three wrong codes end the pairing"); + assert_eq!(p.paired_count(), 1); + } + + /// pair.js and the spake2 crate agree. The receiver half comes from + /// `node tools/pair-vectors.mjs ` with a fixed scalar; the host half + /// uses a seeded RNG. Same code, ids and messages must give the same key. + #[test] + fn js_and_rust_agree() { + use rand::SeedableRng; + let (spake, msg_b) = Spake2::::start_b_with_rng( + &Password::new(b"482913"), + &Identity::new(ID_RECEIVER), + &Identity::new(&host_identity("cafe0123")), + rand::rngs::StdRng::seed_from_u64(7), + ); + assert_eq!(B64.encode(msg_b), "QoDhvUnKUD79cyOl9/XYCHhm4fsOoCqAuKvLwJOKkyXm"); + let msg_a = B64.decode("Qf68NRRbowfCin/xPzWi9LHL78uyHmJ9Ws+FGjsWUfGQ").unwrap(); + let key = spake.finish(&msg_a).unwrap(); + assert_eq!(hex(&key), "2cf7f820018b00c4bf72c547258b68d225b514e49b62e848cc36cbfad1534691"); + assert_eq!(B64.encode(PairKeys::new(&key).receiver_mac()), "Wxz+wml1hXz6lntChcerOHQSxf427BkJRUs0he5KAEM="); + + // An offer sealed by pair.js (secret 9s, challenge 5s) opens here. + let sealed = Sealed { n: "CVRRmdltZaTU8rPu".into(), c: "89z8t3KJsirxvVtWFnQpm2MnGSdF6j/oLtEupLyTvt2r6dIMtO/GSFu+jkcm".into() }; + let plain = open(&derive(&[9u8; 32], Some(&[5u8; 16]), b"mullion offer"), b"offer:dabc", &sealed).unwrap(); + assert_eq!(plain, br#"{"sdp":"v=0","mode":"extend"}"#); + // And its signed request header matches. + let mac = request_mac(&[9u8; 32], "POST", "/screens/layout", "1700000000000", br#"{"cells":[]}"#); + assert_eq!(B64.encode(mac), "sDGScS+0z/QvRvk0xJqALguLSXiaSVKpUOMZVKb1JmI="); + } + + #[test] + fn a_second_request_cannot_replace_a_fresh_one() { + let (p, _) = pairing(); + p.start("A").unwrap(); + assert!(matches!(p.start("B"), Err(PairError::Busy))); + } + + #[test] + fn sealed_offer_needs_the_secret_and_a_fresh_challenge() { + let (p, shown) = pairing(); + let s = p.start("iPad").unwrap(); + let code = shown.lock().unwrap()[0].clone(); + receiver(&p, &s.pairing, &code).unwrap(); + let (device, secret) = { + let g = p.lock(); + let d = &g.store.devices[0]; + (d.id.clone(), B64.decode(&d.secret).unwrap()) + }; + assert!(p.challenge("d-unknown").is_none(), "unpaired devices get no challenge"); + + let nonce = B64.decode(p.challenge(&device).unwrap()).unwrap(); + let key = derive(&secret, Some(&nonce), b"mullion offer"); + let sealed = seal(&key, format!("offer:{device}").as_bytes(), b"{\"sdp\":\"v=0\"}"); + let (plain, ctx) = p.open_offer(&device, &sealed).unwrap(); + assert_eq!(plain, b"{\"sdp\":\"v=0\"}"); + let answer = p.seal_answer(&ctx, b"answer"); + assert_eq!(open(&derive(&secret, Some(&nonce), b"mullion answer"), format!("answer:{device}").as_bytes(), &answer).unwrap(), b"answer"); + // Replay: the challenge is used up. + assert!(p.open_offer(&device, &sealed).is_err()); + // Wrong secret. + p.challenge(&device).unwrap(); + let bad = seal(&[7u8; 32], format!("offer:{device}").as_bytes(), b"x"); + assert!(p.open_offer(&device, &bad).is_err()); + } + + #[test] + fn signed_requests_check_device_time_and_body() { + let (p, shown) = pairing(); + let s = p.start("iPad").unwrap(); + let code = shown.lock().unwrap()[0].clone(); + receiver(&p, &s.pairing, &code).unwrap(); + let (device, secret) = { + let g = p.lock(); + (g.store.devices[0].id.clone(), B64.decode(&g.store.devices[0].secret).unwrap()) + }; + let ts = unix_ms().to_string(); + let mac = B64.encode(request_mac(&secret, "POST", "/screens/layout", &ts, b"{}")); + let h = format!("{device}.{ts}.{mac}"); + assert_eq!(p.verify_request(&h, "POST", "/screens/layout", b"{}"), Some(device.clone())); + assert_eq!(p.verify_request(&h, "POST", "/screens/layout", b"{\"x\":1}"), None, "body is signed"); + assert_eq!(p.verify_request(&h, "GET", "/screens", b"{}"), None, "path and method are signed"); + let old = (unix_ms() - 120_000).to_string(); + let mac = B64.encode(request_mac(&secret, "GET", "/screens", &old, b"")); + assert_eq!(p.verify_request(&format!("{device}.{old}.{mac}"), "GET", "/screens", b""), None, "stale"); + p.forget_all(); + let ts = unix_ms().to_string(); + let mac = B64.encode(request_mac(&secret, "GET", "/screens", &ts, b"")); + assert_eq!(p.verify_request(&format!("{device}.{ts}.{mac}"), "GET", "/screens", b""), None, "forgotten"); + } + + #[test] + fn store_survives_a_restart_and_is_private() { + let dir = std::env::temp_dir().join(format!("mullion-pair-test-{}", hex(&random::<4>()))); + let path = dir.join("paired.json"); + let shown = Arc::new(Mutex::new(Vec::::new())); + let s2 = shown.clone(); + let p = Pairing::load(Some(path.clone()), Box::new(move |n| { + if let Notice::Code { code, .. } = n { + s2.lock().unwrap().push(code); + } + })); + let s = p.start("iPad").unwrap(); + let code = shown.lock().unwrap()[0].clone(); + receiver(&p, &s.pairing, &code).unwrap(); + let again = Pairing::load(Some(path.clone()), Box::new(|_| {})); + assert_eq!(again.host_id(), p.host_id()); + assert_eq!(again.paired_count(), 1); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + } + let _ = std::fs::remove_dir_all(dir); + } +} + diff --git a/crates/host/src/probe_page.rs b/crates/host/src/probe_page.rs index 8564140..db03bf1 100644 --- a/crates/host/src/probe_page.rs +++ b/crates/host/src/probe_page.rs @@ -54,14 +54,19 @@ requestAnimationFrame(paint); /// `port` is the host's main (signaling) port; the page may have been loaded /// from the web port (80), so it is told where offers go. pub fn receiver_html(host_ip: &str, port: u16) -> String { + let noble = include_str!("../../app/assets/vendor/noble.js"); + let pair = include_str!("../../app/assets/pair.js"); let js = include_str!("../../app/assets/receiver.js"); let ui_js = include_str!("../../app/assets/ui.js"); let layout_js = include_str!("../../app/assets/layout.js"); let css = include_str!("../../app/assets/ui.css"); let version = mullion_proto::version::VERSION; + // From the request's Host header: keep only what an address can hold, so + // nothing else reaches the attribute. + let host_ip: String = host_ip.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')).take(253).collect(); let body = include_str!("../../app/assets/ui.html").replace(r#"\n\n\n\nMullion\n{ICON_LINKS}\n\n{body}\n\n\n\n\n" + "\n\n\n\nMullion\n{ICON_LINKS}\n\n{body}\n\n\n\n\n\n\n" ) } diff --git a/crates/host/src/session.rs b/crates/host/src/session.rs index ecd5754..8f6b538 100644 --- a/crates/host/src/session.rs +++ b/crates/host/src/session.rs @@ -76,6 +76,7 @@ pub enum Msg { NewRtc(Rtc, Mode, DeviceInfo), Packet { at: Instant, source: SocketAddr, destination: SocketAddr, data: Vec }, Frame(Source, EncodedFrame), + EndAll, Shutdown, } @@ -96,25 +97,47 @@ impl SessionHandle { } pub fn answer(&self, offer_sdp: &str, mode: Mode, device: DeviceInfo) -> Result { - let offer = SdpOffer::from_sdp_string(offer_sdp).map_err(|e| anyhow!("bad SDP: {e}"))?; - let mut rtc = Rtc::builder() - .set_ice_lite(true) - .clear_codecs() - .enable_h264(true) - .build(Instant::now()); - // Only Constrained Baseline, packetization-mode 1 (SRS A-6). - rtc.codec_config().params().to_vec(); // touch to keep API usage visible - for addr in &self.local_addrs { - let c = Candidate::host(*addr, "udp").map_err(|e| anyhow!("candidate {addr}: {e}"))?; - if rtc.add_local_candidate(c).is_none() { - warn!("candidate {addr} rejected"); - } - } - let answer = rtc.sdp_api().accept_offer(offer).map_err(|e| anyhow!("accept offer: {e}"))?; + // str0m can panic on some well-formed but unusual offers (several + // video m-lines sharing H.264 payload types). Contain it: one bad + // offer must not take signaling down (audit: offer-accept-panic). + let (rtc, answer) = build_rtc_contained(&self.local_addrs, offer_sdp)?; self.tx.send(Msg::NewRtc(rtc, mode, device)).map_err(|_| anyhow!("session thread gone"))?; - Ok(answer.to_sdp_string()) + Ok(answer) + } + + /// End every session (devices were forgotten). + pub fn end_all(&self) { + let _ = self.tx.send(Msg::EndAll); + } +} + +/// [`build_rtc`], with a panic inside str0m turned into an error. +fn build_rtc_contained(local_addrs: &[SocketAddr], offer_sdp: &str) -> Result<(Rtc, String)> { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| build_rtc(local_addrs, offer_sdp))) + .map_err(|_| anyhow!("unsupported SDP"))? +} + +/// An ice-lite, H.264-only `Rtc` that has accepted `offer_sdp`, and its answer. +fn build_rtc(local_addrs: &[SocketAddr], offer_sdp: &str) -> Result<(Rtc, String)> { + let offer = SdpOffer::from_sdp_string(offer_sdp).map_err(|e| anyhow!("bad SDP: {e}"))?; + let mut rtc = Rtc::builder() + .set_ice_lite(true) + .clear_codecs() + .enable_h264(true) + .build(Instant::now()); + // Only Constrained Baseline, packetization-mode 1 (SRS A-6). + rtc.codec_config().params().to_vec(); // touch to keep API usage visible + for addr in local_addrs { + let c = Candidate::host(*addr, "udp").map_err(|e| anyhow!("candidate {addr}: {e}"))?; + if rtc.add_local_candidate(c).is_none() { + warn!("candidate {addr} rejected"); + } } + let answer = rtc.sdp_api().accept_offer(offer).map_err(|e| anyhow!("accept offer: {e}"))?; + Ok((rtc, answer.to_sdp_string())) +} +impl SessionHandle { /// The layout map: every display, its grid cell and its owner. pub fn screens(&self) -> Result { let owners = self.devices.lock().unwrap().screens.clone(); @@ -299,6 +322,7 @@ impl SessionLoop { let mut touched: Vec = Vec::new(); match msg { Some(Msg::Shutdown) => break, + Some(Msg::EndAll) => self.end_all("the Mac forgot its paired devices"), Some(Msg::NewRtc(rtc, mode, device)) => { self.next_id += 1; if !self.multi_session { @@ -744,22 +768,43 @@ fn write_frame(a: &mut Active, frame: &EncodedFrame, log: &TimingLog, log_it: bo } /// Shared so the signaling thread can call `answer` through `Arc`. +/// A panic while the lock is held must not leave it poisoned for every later +/// request and the menu bar, so each access takes the guard back. pub struct SharedHandle(pub Mutex); +impl SharedHandle { + fn get(&self) -> std::sync::MutexGuard<'_, SessionHandle> { + self.0.lock().unwrap_or_else(|e| e.into_inner()) + } +} + impl crate::signaling::OfferHandler for SharedHandle { fn answer(&self, offer_sdp: &str, mode: Mode, device: DeviceInfo, _peer: SocketAddr) -> Result { - self.0.lock().unwrap().answer(offer_sdp, mode, device) + self.get().answer(offer_sdp, mode, device) } fn devices(&self) -> DevicesSnapshot { - self.0.lock().unwrap().devices() + self.get().devices() } fn screens(&self) -> Result { - self.0.lock().unwrap().screens() + self.get().screens() } fn set_layout(&self, cells: &[CellAssign]) -> Result { - self.0.lock().unwrap().set_layout(cells) + self.get().set_layout(cells) + } +} + +#[cfg(test)] +mod offer_tests { + /// The offer that made str0m 0.25 panic in accept_offer (audit finding + /// offer-accept-panic-poisons-sharedhandle) is now a plain error. + #[test] + fn str0m_panic_on_an_offer_is_contained() { + let sdp = include_str!("testdata-str0m-panic.sdp"); + let addrs = ["127.0.0.1:47901".parse().unwrap()]; + let err = super::build_rtc_contained(&addrs, sdp).err().expect("this offer is refused"); + assert!(err.to_string().contains("unsupported SDP"), "{err:#}"); } } diff --git a/crates/host/src/signaling.rs b/crates/host/src/signaling.rs index 0746cf7..92c9a23 100644 --- a/crates/host/src/signaling.rs +++ b/crates/host/src/signaling.rs @@ -16,6 +16,14 @@ //! Web port: the same routes are also served on port 80 by default, so the //! bare address (http://10.43.77.126) opens the receiver in any browser. If //! that port cannot be had, the host carries on with the main port only. +//! +//! Pairing (pairing.rs): with a `Pairing` attached, only paired receivers may +//! stream. `POST /pair/start|exchange|confirm|cancel` pair a new receiver with the +//! code the Mac shows; `POST /challenge` then `POST /offer` carry a sealed +//! offer and answer. `/devices`, `/screens` and `/screens/layout` take a +//! request signed by a paired receiver (`X-Mullion-Auth`), or come from this +//! Mac itself (loopback, no foreign Origin). Without a `Pairing` (tests) the +//! host takes plain offers as before. use std::io::Read; use std::net::SocketAddr; @@ -29,6 +37,7 @@ use serde::Serialize; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; use tracing::{info, warn}; +use crate::pairing::{PairError, Pairing, Sealed}; use crate::probe_page::{icon_file, receiver_html, PROBE_HTML}; /// What the server hands a validated offer to. Returns the answer SDP. @@ -47,6 +56,8 @@ pub trait OfferHandler: Send + Sync + 'static { /// Largest `POST /screens/layout` body: a few dozen cells. const MAX_LAYOUT_BYTES: usize = 16 * 1024; +/// Largest pairing or challenge request body. +const MAX_PAIR_BYTES: usize = 4 * 1024; impl OfferHandler for F where @@ -75,6 +86,7 @@ pub struct Signaling { host_name: String, config: serde_json::Value, lan_ips: Vec, + pairing: Option>, } /// `GET /hello`: enough for a receiver to list this host and connect to it. @@ -92,6 +104,10 @@ struct Hello<'a> { extend: bool, /// Receivers connected right now. receivers: usize, + /// Stable id of this host; a receiver keeps its pairing under it. + /// Absent: an older host that takes plain offers. + #[serde(skip_serializing_if = "Option::is_none")] + host_id: Option, } fn platform_name() -> &'static str { @@ -110,7 +126,7 @@ impl Signaling { let server = Server::http(addr).map_err(|e| { anyhow!("Can't listen on port {}: {}. Pick another with --port.", addr.port(), e) })?; - Ok(Self { server, web: None, handler, host_name, config: serde_json::Value::Null, lan_ips: Vec::new() }) + Ok(Self { server, web: None, handler, host_name, config: serde_json::Value::Null, lan_ips: Vec::new(), pairing: None }) } /// Effective switches, served at `/config`. @@ -150,6 +166,12 @@ impl Signaling { }) } + /// Require pairing: only paired receivers may stream or read the layout. + pub fn with_pairing(mut self, pairing: Arc) -> Self { + self.pairing = Some(pairing); + self + } + /// LAN addresses listed by `/hello`. pub fn with_lan_ips(mut self, ips: Vec) -> Self { self.lan_ips = ips; @@ -214,24 +236,55 @@ impl Signaling { if n > MAX_BODY_BYTES { return respond_status(req, 413, "Offer too large"); } + // Paired hosts take only a sealed offer from a paired device. + let (body, ctx) = match &self.pairing { + None => (body, None), + Some(p) => { + #[derive(serde::Deserialize)] + struct SealedOffer { + device: String, + sealed: Sealed, + } + let Ok(so) = serde_json::from_slice::(&body) else { + return respond_json(req, 401, &serde_json::json!({"pair": true, "error": "Pair this device with the Mac first."})); + }; + if !p.is_paired(&so.device) { + return respond_json(req, 401, &serde_json::json!({"pair": true, "error": "This Mac no longer knows this device. Pair again."})); + } + match p.open_offer(&so.device, &so.sealed) { + Ok((plain, ctx)) => (plain, Some(ctx)), + Err(e) => { + warn!("offer from {peer} refused: {e:#}"); + return respond_json(req, 401, &serde_json::json!({"pair": false, "error": "The offer did not check out. Connect again."})); + } + } + } + }; let offer = match parse_offer(&body) { Ok(o) => o, Err(413) => return respond_status(req, 413, "Offer too large"), Err(_) => return respond_status(req, 400, "Body must be JSON {\"sdp\":\"v=0...\"}"), }; - let device = DeviceInfo { - id: valid_device_id(&offer.device_id).map(str::to_string), - name: clean_device_name(&offer.device_name, &format!("Tablet {}", peer.ip())), + let device = match &ctx { + // The device is who the pairing says, whatever the offer claims. + Some(c) => DeviceInfo { id: Some(c.device_id.clone()), name: clean_device_name(&offer.device_name, &c.device_name) }, + None => DeviceInfo { + id: valid_device_id(&offer.device_id).map(str::to_string), + name: clean_device_name(&offer.device_name, &format!("Tablet {}", peer.ip())), + }, }; match self.handler.answer(&offer.sdp, offer.mode, device, peer) { Ok(sdp) => { info!("offer from {peer} answered ({:?})", offer.mode); - let body = serde_json::to_vec(&AnswerBody { + let mut body = serde_json::to_vec(&AnswerBody { r#type: "answer", sdp: &sdp, host_name: &self.host_name, probe: self.config.get("probe").and_then(|v| v.as_bool()).unwrap_or(false), })?; + if let (Some(p), Some(c)) = (&self.pairing, &ctx) { + body = serde_json::to_vec(&serde_json::json!({ "sealed": p.seal_answer(c, &body) }))?; + } let resp = Response::from_data(body) .with_header(Header::from_bytes("Content-Type", "application/json").unwrap()); req.respond(with_cors(resp)).context("respond") @@ -242,6 +295,36 @@ impl Signaling { } } } + ("/pair/start" | "/pair/exchange" | "/pair/confirm" | "/pair/cancel" | "/challenge", Method::Post) => { + let Some(p) = self.pairing.clone() else { return respond_status(req, 404, "Not found") }; + let Some(body) = read_body(&mut req, MAX_PAIR_BYTES) else { return respond_status(req, 413, "Too large") }; + let Ok(v) = serde_json::from_slice::(&body) else { return respond_status(req, 400, "Body must be JSON") }; + let field = |k: &str| v.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string(); + let out: Result = match path.as_str() { + "/pair/start" => { + let name = clean_device_name(&field("name"), &format!("Device {}", peer.ip())); + p.start(&name).map(|s| serde_json::to_value(s).unwrap_or_default()) + } + "/pair/exchange" => p.exchange(&field("pairing"), &field("msg")).map(|m| serde_json::json!({ "msg": m })), + "/pair/cancel" => { + p.abandon(&field("pairing")); + Ok(serde_json::json!({})) + } + "/pair/confirm" => p.confirm(&field("pairing"), &field("mac"), &self.host_name).map(|c| serde_json::to_value(c).unwrap_or_default()), + _ => match p.challenge(&field("device")) { + Some(nonce) => Ok(serde_json::json!({ "nonce": nonce })), + None => return respond_json(req, 401, &serde_json::json!({"pair": true, "error": "Pair this device with the Mac first."})), + }, + }; + match out { + Ok(v) => respond_json(req, 200, &v), + Err(PairError::Bad(why)) => respond_json(req, 400, &serde_json::json!({ "error": why })), + Err(PairError::Gone) => respond_json(req, 410, &serde_json::json!({ "error": "No pairing in progress, or it expired." })), + Err(PairError::Busy) => respond_json(req, 429, &serde_json::json!({ "error": "Another device is pairing. Try again in a few seconds." })), + Err(PairError::WrongCode { left }) => respond_json(req, 403, &serde_json::json!({ "error": "Wrong code.", "left": left })), + Err(PairError::Full) => respond_json(req, 507, &serde_json::json!({ "error": "Too many paired devices. Forget some on the Mac." })), + } + } ("/offer", _) => respond_status(req, 405, "Use POST"), ("/probe", Method::Get) => { let resp = Response::from_string(PROBE_HTML) @@ -267,11 +350,17 @@ impl Signaling { req.respond(with_cors(resp)).context("respond") } ("/devices", Method::Get) => { + if !self.allowed(&req, peer, &path, b"") { + return respond_status(req, 401, "Pair this device with the Mac first"); + } let body = serde_json::to_vec(&self.handler.devices())?; let resp = Response::from_data(body).with_header(Header::from_bytes("Content-Type", "application/json").unwrap()); req.respond(with_cors(resp)).context("respond") } ("/screens", Method::Get) => { + if !self.allowed(&req, peer, &path, b"") { + return respond_status(req, 401, "Pair this device with the Mac first"); + } let view = self.handler.screens(); self.respond_screens(req, view) } @@ -282,6 +371,9 @@ impl Signaling { if n > MAX_LAYOUT_BYTES { return respond_status(req, 413, "Layout too large"); } + if !self.allowed(&req, peer, &path, &body) { + return respond_status(req, 401, "Pair this device with the Mac first"); + } let Ok(layout) = serde_json::from_slice::(&body) else { return respond_status(req, 400, "Body must be JSON {\"cells\":[{\"display_id\":7,\"col\":1,\"row\":0}]}"); }; @@ -307,6 +399,7 @@ impl Signaling { ips: &self.lan_ips, extend: self.config.get("extend").and_then(|v| v.as_bool()).unwrap_or(true), receivers: self.handler.devices().devices.iter().filter(|d| d.connected).count(), + host_id: self.pairing.as_ref().map(|p| p.host_id()), }; let resp = Response::from_data(serde_json::to_vec(&hello)?) .with_header(Header::from_bytes("Content-Type", "application/json").unwrap()) @@ -337,6 +430,18 @@ impl Signaling { } impl Signaling { + /// May this request read or change the layout? Yes for this Mac itself + /// (loopback, and no Origin or a loopback one, so a web page cannot + /// borrow it) and for a request signed by a paired device. Without + /// pairing (tests), everything is allowed as before. + fn allowed(&self, req: &Request, peer: SocketAddr, path: &str, body: &[u8]) -> bool { + let Some(p) = &self.pairing else { return true }; + if peer.ip().is_loopback() && header(req, "Origin").map_or(true, |o| loopback_origin(&o)) { + return true; + } + header(req, "X-Mullion-Auth").is_some_and(|h| p.verify_request(&h, req.method().as_str(), path, body).is_some()) + } + fn respond_screens(&self, req: Request, view: Result) -> Result<()> { match view { Ok(mut v) => { @@ -362,12 +467,38 @@ impl Signaling { fn with_cors(r: Response) -> Response { r.with_header(Header::from_bytes("Access-Control-Allow-Origin", "*").unwrap()) .with_header(Header::from_bytes("Access-Control-Allow-Methods", "POST, GET, OPTIONS").unwrap()) - .with_header(Header::from_bytes("Access-Control-Allow-Headers", "Content-Type").unwrap()) + .with_header(Header::from_bytes("Access-Control-Allow-Headers", "Content-Type, X-Mullion-Auth").unwrap()) // Private Network Access: a receiver page from another origin (the app's // WebView, a page saved on the tablet) may ask a LAN address. .with_header(Header::from_bytes("Access-Control-Allow-Private-Network", "true").unwrap()) } +fn header(req: &Request, name: &'static str) -> Option { + req.headers().iter().find(|h| h.field.equiv(name)).map(|h| h.value.as_str().to_string()) +} + +/// `http://127.0.0.1:8080`, `http://localhost`, `http://[::1]:47100`. +fn loopback_origin(origin: &str) -> bool { + let host = origin.split("://").nth(1).unwrap_or(""); + let host = if let Some(rest) = host.strip_prefix('[') { rest.split(']').next().unwrap_or("") } else { host.split(':').next().unwrap_or("") }; + host == "localhost" || host.parse::().is_ok_and(|ip| ip.is_loopback()) +} + +/// The whole body, or `None` when it is longer than `limit`. +fn read_body(req: &mut Request, limit: usize) -> Option> { + let mut body = Vec::new(); + let n = req.as_reader().take(limit as u64 + 1).read_to_end(&mut body).unwrap_or(0); + (n <= limit).then_some(body) +} + +fn respond_json(req: Request, code: u16, v: &serde_json::Value) -> Result<()> { + let resp = Response::from_data(serde_json::to_vec(v)?) + .with_status_code(StatusCode(code)) + .with_header(Header::from_bytes("Content-Type", "application/json").unwrap()) + .with_header(Header::from_bytes("Cache-Control", "no-store").unwrap()); + req.respond(with_cors(resp)).context("respond") +} + fn respond_status(req: Request, code: u16, msg: &str) -> Result<()> { let resp = Response::from_string(format!("{msg}\n")).with_status_code(StatusCode(code)); req.respond(with_cors(resp)).context("respond") @@ -488,8 +619,8 @@ mod tests { } impl OfferHandler for FakeDesk { - fn answer(&self, _: &str, _: Mode, _: DeviceInfo, _: SocketAddr) -> Result { - Err(anyhow!("no offers here")) + fn answer(&self, sdp: &str, mode: Mode, _: DeviceInfo, peer: SocketAddr) -> Result { + echo_handler(sdp, mode, peer) } fn screens(&self) -> Result { Ok(self.view()) @@ -589,6 +720,90 @@ mod tests { assert!(matches!(r, ureq::Error::Status(413, _)), "{r:?}"); } + /// With pairing on: plain offers are refused, a receiver pairs with the + /// code over HTTP, its sealed offer gets a sealed answer, a replay is + /// refused, and the layout map takes this Mac or a signed request only. + #[test] + fn paired_host_takes_only_sealed_offers_and_signed_layout_requests() { + use crate::pairing::{self as pr, Pairing, PairKeys}; + use base64::{engine::general_purpose::STANDARD as B64, Engine}; + use spake2::{Ed25519Group, Identity, Password, Spake2}; + + let codes = Arc::new(std::sync::Mutex::new(Vec::::new())); + let c2 = codes.clone(); + let pairing = Arc::new(Pairing::load(None, Box::new(move |n| { + if let pr::Notice::Code { code, .. } = n { + c2.lock().unwrap().push(code); + } + }))); + let desk = FakeDesk::new(); + let s = Signaling::bind("127.0.0.1:0".parse().unwrap(), Arc::new(desk), "TEST-MAC".into()).unwrap().with_pairing(pairing.clone()); + let addr = s.local_addr(); + std::thread::spawn(move || s.run()); + let a = agent(); + let url = |p: &str| format!("http://{addr}{p}"); + let post = |p: &str, v: serde_json::Value| -> (u16, serde_json::Value) { + match a.post(&url(p)).send_json(v) { + Ok(r) => (r.status(), r.into_json().unwrap_or_default()), + Err(ureq::Error::Status(c, r)) => (c, r.into_json().unwrap_or_default()), + Err(e) => panic!("{e}"), + } + }; + + // /hello names the host; a plain offer is refused with "pair". + let hello: serde_json::Value = a.get(&url("/hello")).call().unwrap().into_json().unwrap(); + let host_id = hello["host_id"].as_str().unwrap().to_string(); + let (code, v) = post("/offer", serde_json::json!({"type": "offer", "sdp": "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 108\r\n"})); + assert_eq!((code, v["pair"].as_bool()), (401, Some(true))); + + // Pair: start, SPAKE2 with the code the Mac showed, confirm. + let (code, v) = post("/pair/start", serde_json::json!({"name": "iPad"})); + assert_eq!(code, 200); + let pid = v["pairing"].as_str().unwrap().to_string(); + let shown = codes.lock().unwrap()[0].clone(); + let (spake, msg_a) = Spake2::::start_a( + &Password::new(shown.as_bytes()), + &Identity::new(pr::ID_RECEIVER), + &Identity::new(&pr::host_identity(&host_id)), + ); + let (_, v) = post("/pair/exchange", serde_json::json!({"pairing": pid, "msg": B64.encode(msg_a)})); + let keys = PairKeys::new(&spake.finish(&B64.decode(v["msg"].as_str().unwrap()).unwrap()).unwrap()); + let (code, v) = post("/pair/confirm", serde_json::json!({"pairing": pid, "mac": B64.encode(keys.receiver_mac())})); + assert_eq!(code, 200, "{v}"); + let sealed: pr::Sealed = serde_json::from_value(v["credential"].clone()).unwrap(); + let cred: serde_json::Value = serde_json::from_slice(&pr::open(&keys.seal, b"mullion pair seal", &sealed).unwrap()).unwrap(); + let device = cred["device"].as_str().unwrap().to_string(); + let secret = B64.decode(cred["secret"].as_str().unwrap()).unwrap(); + + // Connect: challenge, sealed offer, sealed answer. + let (_, v) = post("/challenge", serde_json::json!({"device": device})); + let nonce = B64.decode(v["nonce"].as_str().unwrap()).unwrap(); + let offer = serde_json::json!({"type": "offer", "sdp": "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 108\r\n", "mode": "extend", "device_name": "iPad"}); + let sealed = pr::seal(&pr::derive(&secret, Some(&nonce), b"mullion offer"), format!("offer:{device}").as_bytes(), offer.to_string().as_bytes()); + let body = serde_json::json!({"device": device, "sealed": sealed}); + let (code, v) = post("/offer", body.clone()); + assert_eq!(code, 200, "{v}"); + let answer: pr::Sealed = serde_json::from_value(v["sealed"].clone()).unwrap(); + let answer: serde_json::Value = + serde_json::from_slice(&pr::open(&pr::derive(&secret, Some(&nonce), b"mullion answer"), format!("answer:{device}").as_bytes(), &answer).unwrap()).unwrap(); + assert_eq!(answer["type"], "answer"); + assert_eq!(answer["host_name"], "TEST-MAC"); + // The same sealed offer again: its challenge is spent. + let (code, v) = post("/offer", body); + assert_eq!((code, v["pair"].as_bool()), (401, Some(false))); + + // Layout map: this Mac (loopback, no Origin) yes; a web page's Origin no; signed yes. + assert_eq!(a.get(&url("/screens")).call().unwrap().status(), 200); + let r = a.get(&url("/screens")).set("Origin", "https://evil.example").call().unwrap_err(); + assert!(matches!(r, ureq::Error::Status(401, _)), "{r:?}"); + let r = a.get(&url("/devices")).set("Origin", "https://evil.example").call().unwrap_err(); + assert!(matches!(r, ureq::Error::Status(401, _)), "{r:?}"); + let ts = pr::unix_ms().to_string(); + let mac = B64.encode(pr::request_mac(&secret, "GET", "/screens", &ts, b"")); + let r = a.get(&url("/screens")).set("Origin", "https://evil.example").set("X-Mullion-Auth", &format!("{device}.{ts}.{mac}")).call().unwrap(); + assert_eq!(r.status(), 200); + } + #[test] fn t10_chunked_body_over_limit_is_413() { let addr = start(echo_handler); diff --git a/crates/host/src/testdata-str0m-panic.sdp b/crates/host/src/testdata-str0m-panic.sdp new file mode 100644 index 0000000..786f519 --- /dev/null +++ b/crates/host/src/testdata-str0m-panic.sdp @@ -0,0 +1,92 @@ +v=0 +o=str0m-0.25.0 1734316875287876653 2 IN IP4 0.0.0.0 +s=- +t=0 0 +a=group:BUNDLE yQG K1n YpC 5YG +m=video 9 UDP/TLS/RTP/SAVPF 102 103 98 99 100 101 45 46 127 121 125 107 108 109 124 120 123 119 35 36 114 115 96 97 +a=mid:yQG +a=recvonly +a=rtpmap:102 H265/90000 +a=rtpmap:103 rtx/90000 +a=rtpmap:98 VP9/90000 +a=rtpmap:99 rtx/90000 +a=rtpmap:100 VP9/90000 +a=rtpmap:101 rtx/90000 +a=rtpmap:45 AV1/90000 +a=rtpmap:46 rtx/90000 +a=rtpmap:127 H264/90000 +a=rtpmap:121 rtx/90000 +a=rtpmap:125 H264/90000 +a=rtpmap:107 rtx/90000 +a=rtpmap:108 H264/90000 +a=rtpmap:109 rtx/90000 +a=rtpmap:124 H264/90000 +a=rtpmap:120 rtx/90000 +a=rtpmap:123 H264/90000 +a=rtpmap:119 rtx/90000 +a=rtpmap:35 H264/90000 +a=rtpmap:36 rtx/90000 +a=rtpmap:114 H264/90000 +a=rtpmap:115 rtx/90000 +a=rtpmap:96 VP8/90000 +a=rtpmap:97 rtx/90000 +m=video 9 UDP/TLS/RTP/SAVPF 102 103 98 99 100 101 45 46 127 121 125 107 108 109 124 120 123 119 35 36 114 115 96 97 +a=mid:K1n +a=sendrecv +a=rtpmap:102 H265/90000 +a=rtpmap:103 rtx/90000 +a=rtpmap:98 VP9/90000 +a=rtpmap:99 rtx/90000 +a=rtpmap:100 VP9/90000 +a=rtpmap:101 rtx/90000 +a=rtpmap:45 AV1/90000 +a=rtpmap:46 rtx/90000 +a=rtpmap:127 H264/90000 +a=rtpmap:121 rtx/90000 +a=rtpmap:125 H264/90000 +a=rtpmap:107 rtx/90000 +a=rtpmap:109 rtx/90000 +a=rtpmap:124 H264/90000 +a=rtpmap:120 rtx/90000 +a=rtpmap:123 H264/90000 +a=rtpmap:119 rtx/90000 +a=rtpmap:35 H264/90000 +a=rtpmap:108 H264/90000 +a=rtpmap:36 rtx/90000 +a=rtpmap:114 H264/90000 +a=rtpmap:115 rtx/90000 +a=rtpmap:96 VP8/90000 +a=rtpmap:97 rtx/90000 +m=video 9 UDP/TLS/RTP/SAVPF 102 103 98 99 100 101 45 46 127 121 125 107 108 109 124 120 123 119 35 36 114 115 96 97 +a=mid:YpC +a=recvonly +a=rtpmap:102 H265/90000 +a=rtpmap:103 rtx/90000 +a=rtpmap:98 VP9/90000 +a=rtpmap:99 rtx/90000 +a=rtpmap:100 VP9/90000 +a=rtpmap:101 rtx/90000 +a=rtpmap:45 AV1/90000 +a=rtpmap:46 rtx/90000 +a=rtpmap:127 H264/90000 +a=rtpmap:121 rtx/90000 +a=rtpmap:125 H264/90000 +a=rtpmap:107 rtx/90000 +a=rtpmap:108 H264/90000 +a=rtpmap:109 rtx/90000 +a=rtpmap:124 H264/90000 +a=rtpmap:120 rtx/90000 +a=rtpmap:123 H264/90000 +a=rtpmap:119 rtx/90000 +a=rtpmap:35 H264/90000 +a=rtpmap:36 rtx/90000 +a=rtpmap:114 H264/90000 +a=fmtp:114 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f +a=rtpmap:115 rtx/90000 +a=rtpmap:96 VP8/90000 +a=rtpmap:97 rtx/90000 +m=application 9 UDP/DTLS/SCTP webrtc-datachannel +a=ice-ufrag:iKK5gDMzkNVMNiu1 +a=ice-pwd:1QNRoqvDPtnD3UXfantoBQ +a=fingerprint:sha-256 94:AD:BB:A2:85:C1:3F:6E:04:29:FD:AD:5E:CF:CA:59:83:26:03:E7:89:1C:CA:17:F6:40:98:AF:2A:7D:6F:8F +a=mid:5YG diff --git a/docs/evidence/pairing/0-mac-code-dialog.png b/docs/evidence/pairing/0-mac-code-dialog.png new file mode 100644 index 0000000..9134bee Binary files /dev/null and b/docs/evidence/pairing/0-mac-code-dialog.png differ diff --git a/docs/evidence/pairing/0b-code-typed.png b/docs/evidence/pairing/0b-code-typed.png new file mode 100644 index 0000000..ec7787e Binary files /dev/null and b/docs/evidence/pairing/0b-code-typed.png differ diff --git a/docs/evidence/pairing/1-start.png b/docs/evidence/pairing/1-start.png new file mode 100644 index 0000000..d462901 Binary files /dev/null and b/docs/evidence/pairing/1-start.png differ diff --git a/docs/evidence/pairing/2-code-prompt.png b/docs/evidence/pairing/2-code-prompt.png new file mode 100644 index 0000000..6134300 Binary files /dev/null and b/docs/evidence/pairing/2-code-prompt.png differ diff --git a/docs/evidence/pairing/3-wrong-code.png b/docs/evidence/pairing/3-wrong-code.png new file mode 100644 index 0000000..8b58067 Binary files /dev/null and b/docs/evidence/pairing/3-wrong-code.png differ diff --git a/docs/evidence/pairing/README.md b/docs/evidence/pairing/README.md new file mode 100644 index 0000000..537d372 --- /dev/null +++ b/docs/evidence/pairing/README.md @@ -0,0 +1,23 @@ +# Pairing evidence (PR #21) + +Captured on 2026-11-12 against a dev host built from this branch +(`mullion-host --port 47200 --web-port 0 --no-extend`), with the receiver page in +Chrome on the same Mac. The Mac's host name is shown as `[Mac name]` and the +stream itself is not shown: it is this Mac's desktop. The stream's numbers are +in `browser-checks.json`. + +| File | What it shows | +|---|---| +| `0-mac-code-dialog.png` | **Where the code comes from**: the dialog the Mac app shows when a device asks to pair (Mullion.app built from this branch, run as the menu bar app). | +| `0b-code-typed.png` | The same code typed on the device. | +| `mac-app-log.txt` | The Mac app's side: pairing requested by "iPad test", paired, streaming; the dialog closed itself once the code was accepted. | +| `1-start.png` | The receiver before connecting. | +| `2-code-prompt.png` | After Connect: the page asks for the code the Mac shows. | +| `3-wrong-code.png` | A wrong code: "That code is not the one on the Mac. 2 tries left." | +| `host-log.txt` | Host side: pairing requested, the code it showed, the wrong code, paired, sealed offer answered, ICE completed, capture started; then a reconnect with no code. | +| `browser-checks.json` | From the page: streaming after pairing (1920x1080), reconnect without a code, signed `/screens` 200, unsigned `/screens` and `/devices` 401, a plain unsealed offer 401. | +| `cargo-test.txt` | The pairing tests and the totals (68 passed). | +| `interop-vectors.json` | `node tools/pair-vectors.mjs `: pair.js's SPAKE2 message, key and confirmation for a fixed exchange; `pairing::tests::js_and_rust_agree` checks the same values against the Rust `spake2` crate. The sealed offer uses a fresh nonce on every run. | +| `store-permissions.txt` | `paired.json` is readable by this user only. | + +The test pairings were removed from `paired.json` afterwards. diff --git a/docs/evidence/pairing/browser-checks.json b/docs/evidence/pairing/browser-checks.json new file mode 100644 index 0000000..154a816 --- /dev/null +++ b/docs/evidence/pairing/browser-checks.json @@ -0,0 +1,9 @@ +{ + "first_connection_after_pairing": { "status": "streaming", "frames_presented": 333, "video": "1920x1080" }, + "reconnect": { "asked_for_code_again": false, "status": "streaming", "frames_presented": 314 }, + "signed_GET_screens": 200, + "unsigned_GET_screens_from_LAN": 401, + "unsigned_GET_devices_from_LAN": 401, + "plain_unsealed_offer": { "status": 401, "body": { "error": "Pair this device with the Mac first.", "pair": true } }, + "hello_has_host_id": true +} diff --git a/docs/evidence/pairing/cargo-test.txt b/docs/evidence/pairing/cargo-test.txt new file mode 100644 index 0000000..1104825 --- /dev/null +++ b/docs/evidence/pairing/cargo-test.txt @@ -0,0 +1,11 @@ +test pairing::tests::a_second_request_cannot_replace_a_fresh_one ... ok +test pairing::tests::js_and_rust_agree ... ok +test pairing::tests::signed_requests_check_device_time_and_body ... ok +test pairing::tests::store_survives_a_restart_and_is_private ... ok +test pairing::tests::sealed_offer_needs_the_secret_and_a_fresh_challenge ... ok +test signaling::tests::paired_host_takes_only_sealed_offers_and_signed_layout_requests ... ok +test pairing::tests::right_code_pairs_and_wrong_codes_run_out ... ok +test session::offer_tests::str0m_panic_on_an_offer_is_contained ... ok +test result: ok. 26 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.07s +test result: ok. 42 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.22s +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s diff --git a/docs/evidence/pairing/host-log.txt b/docs/evidence/pairing/host-log.txt new file mode 100644 index 0000000..9367fc2 --- /dev/null +++ b/docs/evidence/pairing/host-log.txt @@ -0,0 +1,12 @@ +2026-11-11T17:01:48.258072Z INFO mullion_host::pairing: pairing requested by Mac +Pairing code for Mac: 263 091 +2026-11-11T17:02:13.181664Z WARN mullion_host::pairing: pairing Mac: wrong code (2 attempts left) +2026-11-11T17:03:38.162262Z INFO mullion_host::pairing: paired Mac +2026-11-11T17:03:38.446577Z INFO mullion_host::signaling: offer from 10.43.77.126:62817 answered (Mirror) +2026-11-11T17:03:38.454988Z INFO mullion_host::session: #1 ice: Checking +2026-11-11T17:03:38.512719Z INFO mullion_host::session: #1 ice: Completed +2026-11-11T17:03:38.991091Z INFO mullion_host::platform::macos: pipeline started for Main: 1920x1080 @ 60 fps, 10000 kbps +2026-11-11T17:04:17.550826Z INFO mullion_host::signaling: offer from 10.43.77.126:62817 answered (Mirror) +2026-11-11T17:04:17.560682Z INFO mullion_host::session: #2 ice: Checking +2026-11-11T17:04:17.621290Z INFO mullion_host::session: #2 ice: Completed +2026-11-11T17:04:17.760238Z INFO mullion_host::platform::macos: pipeline started for Main: 1920x1080 @ 60 fps, 10000 kbps diff --git a/docs/evidence/pairing/interop-vectors.json b/docs/evidence/pairing/interop-vectors.json new file mode 100644 index 0000000..4bdd913 --- /dev/null +++ b/docs/evidence/pairing/interop-vectors.json @@ -0,0 +1 @@ +{"msg_a":"Qf68NRRbowfCin/xPzWi9LHL78uyHmJ9Ws+FGjsWUfGQ","key":"2cf7f820018b00c4bf72c547258b68d225b514e49b62e848cc36cbfad1534691","receiver_mac":"Wxz+wml1hXz6lntChcerOHQSxf427BkJRUs0he5KAEM=","offer":{"n":"Sb2h6MehxeFVWHpn","c":"o/C0OkcT9V4Xs2sLvGqkyY1tNEldkaUB4Vy3EylzbEyzng7w4dDjn+5HWiWK"},"auth":"dabc.1700000000000.sDGScS+0z/QvRvk0xJqALguLSXiaSVKpUOMZVKb1JmI="} diff --git a/docs/evidence/pairing/mac-app-log.txt b/docs/evidence/pairing/mac-app-log.txt new file mode 100644 index 0000000..5ddf979 --- /dev/null +++ b/docs/evidence/pairing/mac-app-log.txt @@ -0,0 +1,11 @@ +# Mullion.app built from this branch (0.1.0-pr21), signed like the releases, run as the menu bar app on port 47201. +# Device: the receiver page in Chrome, named "iPad test". Mac host name replaced with [Mac name]. + +2026-11-11T17:15:44.552110Z INFO mullion_host::pairing: pairing requested by iPad test +2026-11-11T17:16:21.912714Z INFO mullion_host::pairing: paired iPad test +2026-11-11T17:16:22.122002Z INFO mullion_host::signaling: offer from 10.43.77.126:52550 answered (Mirror) +2026-11-11T17:16:22.196293Z INFO mullion_host::session: #1 ice: Completed +2026-11-11T17:16:22.606579Z INFO mullion_host::platform::macos: pipeline started for Main: 1920x1080 @ 60 fps, 10000 kbps + +# On-screen windows of the app at modal level, 4 s after the code was entered: none (the code dialog closed itself). +# Page after pairing: {"status":"streaming","frames_presented":417,"video":"1920x1080"} diff --git a/docs/evidence/pairing/store-permissions.txt b/docs/evidence/pairing/store-permissions.txt new file mode 100644 index 0000000..8fbf34e --- /dev/null +++ b/docs/evidence/pairing/store-permissions.txt @@ -0,0 +1 @@ +-rw-------@ paired.json diff --git a/tools/pair-vectors.mjs b/tools/pair-vectors.mjs new file mode 100644 index 0000000..cc2219b --- /dev/null +++ b/tools/pair-vectors.mjs @@ -0,0 +1,23 @@ +// Prints the receiver side of a fixed SPAKE2 exchange with pair.js, for the +// interop test in crates/host/src/pairing.rs (js_and_rust_agree). +// node tools/pair-vectors.mjs +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +const ctx = { window: {}, crypto: globalThis.crypto, TextEncoder, TextDecoder, btoa, atob, localStorage: { getItem() {}, setItem() {}, removeItem() {} } }; +ctx.window = ctx; vm.createContext(ctx); +for (const f of ['vendor/noble.js', 'pair.js']) vm.runInContext(readFileSync(new URL(`../crates/app/assets/${f}`, import.meta.url), 'utf8'), ctx); +const t = ctx.mullionPair._test; +const a = t.spakeA('482913', 'cafe0123', 0x1234567890abcdef1234567890abcdefn); +const out = { msg_a: t.b64(a.msg) }; +if (process.argv[2]) { + const key = a.finish(t.unb64(process.argv[2])); + out.key = Buffer.from(key).toString('hex'); + out.receiver_mac = t.b64(t.mac(t.derive(key, undefined, 'mullion pair receiver'), 'receiver')); +} +// Sealed offer and signed request with a fixed secret and challenge. +const cred = { device: 'dabc', secret: t.b64(new Uint8Array(32).fill(9)) }; +out.offer = ctx.mullionPair.sealOffer(cred, t.b64(new Uint8Array(16).fill(5)), { sdp: 'v=0', mode: 'extend' }); +const realNow = Date.now; ctx.Date = { now: () => 1700000000000 }; +vm.runInContext('Date = globalThis.Date', ctx); +out.auth = ctx.mullionPair.signed(cred, 'POST', '/screens/layout', '{"cells":[]}'); +console.log(JSON.stringify(out)); diff --git a/tools/vendor-crypto/.gitignore b/tools/vendor-crypto/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/tools/vendor-crypto/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/tools/vendor-crypto/build.sh b/tools/vendor-crypto/build.sh new file mode 100755 index 0000000..5f797f9 --- /dev/null +++ b/tools/vendor-crypto/build.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Rebuild crates/app/assets/vendor/noble.js from the versions pinned in +# package-lock.json (npm ci checks every package against its recorded hash). +set -euo pipefail +cd "$(dirname "$0")" +npm ci --no-audit --no-fund --silent +out=../../crates/app/assets/vendor/noble.js +mkdir -p "$(dirname "$out")" +{ + echo "/* Mullion vendor bundle: @noble/curves, @noble/hashes, @noble/ciphers $(node -p "require('./package.json').dependencies['@noble/curves']")" + echo " (c) Paul Miller, MIT License, https://paulmillr.com/noble/" + echo " Built by tools/vendor-crypto/build.sh; do not edit. Exposes window.MullionNoble. */" + # Assign window.MullionNoble explicitly: the app evals each script inside a + # function (Dioxus eval), where a top-level var would stay local. + npx esbuild entry.js --bundle --minify --format=iife --global-name=__mullionNoble --target=es2020 --legal-comments=none \ + --footer:js='window.MullionNoble=__mullionNoble;' +} > "$out" +echo "$out: $(wc -c < "$out") bytes" diff --git a/tools/vendor-crypto/entry.js b/tools/vendor-crypto/entry.js new file mode 100644 index 0000000..46392f4 --- /dev/null +++ b/tools/vendor-crypto/entry.js @@ -0,0 +1,6 @@ +// Only the primitives pair.js uses. Exposed as window.MullionNoble. +export { ed25519 } from '@noble/curves/ed25519.js'; +export { sha256, sha512 } from '@noble/hashes/sha2.js'; +export { hkdf } from '@noble/hashes/hkdf.js'; +export { hmac } from '@noble/hashes/hmac.js'; +export { chacha20poly1305 } from '@noble/ciphers/chacha.js'; diff --git a/tools/vendor-crypto/package-lock.json b/tools/vendor-crypto/package-lock.json new file mode 100644 index 0000000..da6b628 --- /dev/null +++ b/tools/vendor-crypto/package-lock.json @@ -0,0 +1,541 @@ +{ + "name": "mullion-vendor-crypto", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mullion-vendor-crypto", + "dependencies": { + "@noble/ciphers": "2.4.0", + "@noble/curves": "2.4.0", + "@noble/hashes": "2.4.0" + }, + "devDependencies": { + "esbuild": "0.28.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "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/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + } + } +} diff --git a/tools/vendor-crypto/package.json b/tools/vendor-crypto/package.json new file mode 100644 index 0000000..a9d116d --- /dev/null +++ b/tools/vendor-crypto/package.json @@ -0,0 +1,13 @@ +{ + "name": "mullion-vendor-crypto", + "private": true, + "description": "Builds crates/app/assets/vendor/noble.js: the crypto primitives the receiver page needs for pairing (build.sh).", + "dependencies": { + "@noble/ciphers": "2.4.0", + "@noble/curves": "2.4.0", + "@noble/hashes": "2.4.0" + }, + "devDependencies": { + "esbuild": "0.28.2" + } +}