Skip to content
pi-c Artifact [a29bcd8631]
Login

Artifact [a29bcd8631]

Artifact a29bcd863184ddb19646de7c461856f84f7fd76d8f957398337e1a7ae9e18681:


// Reference generator for the pic remote control v1 test vectors.
// Node's built-in crypto only. Prints JSON.
const crypto = require('node:crypto');
const cat = (...b) => Buffer.concat(b.map(x => typeof x === 'string' ? Buffer.from(x, 'utf8') : x));
const sha = (...b) => crypto.createHash('sha256').update(cat(...b)).digest();
const hmac = (k, ...d) => crypto.createHmac('sha256', k).update(cat(...d)).digest();
const seq = (a) => Buffer.from(Array.from({length: 32}, (_, i) => a + i));
const b64u = (b) => Buffer.from(b).toString('base64url');
const hex = (b) => Buffer.from(b).toString('hex');
function hkdf(ck, ikm, n) {
  const t = hmac(ck, ikm), o1 = hmac(t, Buffer.from([1])), o2 = hmac(t, o1, Buffer.from([2]));
  return n === 2 ? [o1, o2] : [o1, o2, hmac(t, o2, Buffer.from([3]))];
}
function pub(priv) { const e = crypto.createECDH('prime256v1'); e.setPrivateKey(priv); return e.getPublicKey(); }
function dh(priv, pk) { const e = crypto.createECDH('prime256v1'); e.setPrivateKey(priv); return e.computeSecret(pk); }
function nonce(n) { const b = Buffer.alloc(12); b.writeBigUInt64BE(BigInt(n), 4); return b; }
function seal(k, n, ad, pt, bits = 256) {
  const c = crypto.createCipheriv(`aes-${bits}-gcm`, k, n); c.setAAD(ad);
  return cat(c.update(pt), c.final(), c.getAuthTag());
}
function open(k, n, ad, ct) {
  const d = crypto.createDecipheriv('aes-256-gcm', k, n); d.setAAD(ad); d.setAuthTag(ct.subarray(ct.length - 16));
  return cat(d.update(ct.subarray(0, ct.length - 16)), d.final());
}
class Sym {
  constructor(name) { const b = Buffer.alloc(32); Buffer.from(name).copy(b); this.h = b; this.ck = b; this.k = null; this.n = 0; }
  mixHash(d) { this.h = sha(this.h, d); }
  mixKey(ikm) { const [ck, k] = hkdf(this.ck, ikm, 2); this.ck = ck; this.k = k; this.n = 0; }
  mixKeyAndHash(ikm) { const [ck, th, k] = hkdf(this.ck, ikm, 3); this.ck = ck; this.mixHash(th); this.k = k; this.n = 0; }
  enc(pt) { if (!this.k) { this.mixHash(pt); return pt; } const c = seal(this.k, nonce(this.n++), this.h, pt); this.mixHash(c); return c; }
  dec(ct) { if (!this.k) { this.mixHash(ct); return ct; } const p = open(this.k, nonce(this.n++), this.h, ct); this.mixHash(ct); return p; }
  split() { return hkdf(this.ck, Buffer.alloc(0), 2); }
}
// IK, or IKpsk1 when psk is given. Initiator is the phone, responder is pic.
function handshake(name, prologue, psk, is, ie, rs, re, p1, p2) {
  const I = new Sym(name), R = new Sym(name), rsp = pub(rs), isp = pub(is), iep = pub(ie), rep = pub(re);
  for (const s of [I, R]) { s.mixHash(prologue); s.mixHash(rsp); }
  // -> e, es, s, ss [, psk]
  I.mixHash(iep); if (psk) I.mixKey(iep);
  I.mixKey(dh(ie, rsp)); const cs = I.enc(isp); I.mixKey(dh(is, rsp)); if (psk) I.mixKeyAndHash(psk);
  const m1 = cat(iep, cs, I.enc(p1));
  R.mixHash(m1.subarray(0, 65)); if (psk) R.mixKey(m1.subarray(0, 65));
  R.mixKey(dh(rs, m1.subarray(0, 65))); const gotS = R.dec(m1.subarray(65, 146)); R.mixKey(dh(rs, gotS)); if (psk) R.mixKeyAndHash(psk);
  const got1 = R.dec(m1.subarray(146));
  if (!gotS.equals(isp) || !got1.equals(p1)) throw new Error('msg1');
  // <- e, ee, se
  R.mixHash(rep); if (psk) R.mixKey(rep);
  R.mixKey(dh(re, iep)); R.mixKey(dh(re, isp));
  const m2 = cat(rep, R.enc(p2));
  I.mixHash(m2.subarray(0, 65)); if (psk) I.mixKey(m2.subarray(0, 65));
  I.mixKey(dh(ie, m2.subarray(0, 65))); I.mixKey(dh(is, m2.subarray(0, 65)));
  if (!I.dec(m2.subarray(65)).equals(p2)) throw new Error('msg2');
  if (!I.h.equals(R.h)) throw new Error('h');
  const [k1, k2] = I.split();
  return { m1, m2, h: I.h, k_up: k1, k_down: k2 };
}
const sas = (h) => String(hmac(h, 'pic-rc/1 sas').readUInt32BE(0) % 1000000).padStart(6, '0');
const record = (type, sid, body) => cat(Buffer.from([type]), sid, body);
function transport(k, sid, n, fin, data) {
  const nb = Buffer.alloc(8); nb.writeBigUInt64BE(BigInt(n));
  return cat(Buffer.from([3]), sid, nb, seal(k, nonce(n), Buffer.alloc(0), cat(Buffer.from([fin]), data)));
}

const out = {};
const picS = seq(0x01), phoneS = seq(0x21), e1 = seq(0x41), e2 = seq(0x61), e3 = seq(0x81), e4 = seq(0xa1);
const ps = seq(0xc1), owner = seq(0x10), devtok = seq(0x30);
const mailbox = sha('pic-rc/1 mailbox', owner).subarray(0, 16);
const psk = hmac(ps, 'pic-rc/1 pair psk'), ptok = hmac(ps, 'pic-rc/1 pair token');
const pchan = sha('pic-rc/1 channel', ptok).subarray(0, 16), dchan = sha('pic-rc/1 channel', devtok).subarray(0, 16);
out.keys = { pic_static_private: hex(picS), pic_static_public: hex(pub(picS)), phone_static_private: hex(phoneS), phone_static_public: hex(pub(phoneS)) };
out.derive = { owner_token: hex(owner), mailbox: hex(mailbox), pairing_secret: hex(ps), psk: hex(psk), pair_token: hex(ptok), pair_channel: hex(pchan), device_token: hex(devtok), device_channel: hex(dchan) };
const exp = Buffer.alloc(8); exp.writeBigUInt64BE(1800000000n);
out.offer = { expires: 1800000000, bytes: hex(cat(Buffer.from([1]), mailbox, pub(picS), ps, exp)), url: 'https://relay.example/#p1.' + b64u(cat(Buffer.from([1]), mailbox, pub(picS), ps, exp)) };
{
  const prologue = cat('pic-rc/1', Buffer.from([0]), mailbox, pchan), sid = Buffer.from('0102030405060708', 'hex');
  const p1 = Buffer.from(JSON.stringify({ v: 1, name: 'Test Phone', channel: b64u(dchan) }));
  const p2 = Buffer.from(JSON.stringify({ v: 1, device: b64u(Buffer.from('d0d1d2d3d4d5d6d7d8d9dadbdcdddedf', 'hex')), name: 'test-host', vapid: b64u(pub(seq(0x51))) }));
  const r = handshake('Noise_IKpsk1_P256_AESGCM_SHA256', prologue, psk, phoneS, e1, picS, e2, p1, p2);
  out.pairing = { protocol: 'Noise_IKpsk1_P256_AESGCM_SHA256', prologue: hex(prologue), phone_ephemeral_private: hex(e1), pic_ephemeral_private: hex(e2), sid: hex(sid),
    payload1: p1.toString(), payload2: p2.toString(), record1: hex(record(1, sid, r.m1)), record2: hex(record(2, sid, r.m2)), handshake_hash: hex(r.h), sas: sas(r.h),
    key_up: hex(r.k_up), key_down: hex(r.k_down),
    up0_plain: '{"type":"pair_ready"}', up0: hex(transport(r.k_up, sid, 0, 1, Buffer.from('{"type":"pair_ready"}'))),
    down0_plain: '{"type":"paired"}', down0: hex(transport(r.k_down, sid, 0, 1, Buffer.from('{"type":"paired"}'))) };
}
{
  const prologue = cat('pic-rc/1', Buffer.from([0]), mailbox, dchan), sid = Buffer.from('1112131415161718', 'hex');
  const p1 = Buffer.from('{"v":1}'), p2 = Buffer.from('{"v":1}');
  const r = handshake('Noise_IK_P256_AESGCM_SHA256', prologue, null, phoneS, e3, picS, e4, p1, p2);
  const up0 = '{"type":"sync","session":"w1/c1","seq":-1}';
  const big = Buffer.alloc(20000, 0x61);
  out.session = { protocol: 'Noise_IK_P256_AESGCM_SHA256', prologue: hex(prologue), phone_ephemeral_private: hex(e3), pic_ephemeral_private: hex(e4), sid: hex(sid),
    payload1: p1.toString(), payload2: p2.toString(), record1: hex(record(1, sid, r.m1)), record2: hex(record(2, sid, r.m2)), handshake_hash: hex(r.h),
    key_up: hex(r.k_up), key_down: hex(r.k_down),
    up0_plain: up0, up0: hex(transport(r.k_up, sid, 0, 1, Buffer.from(up0))),
    down0_plain: '{"type":"sync","session":"w1/c1","seq":42,"payload":{"running":false}}',
    down0: hex(transport(r.k_down, sid, 0, 1, Buffer.from('{"type":"sync","session":"w1/c1","seq":42,"payload":{"running":false}}'))),
    down7_plain: '{"type":"pong"}', down7: hex(transport(r.k_down, sid, 7, 1, Buffer.from('{"type":"pong"}'))),
    fragmented: { message: '20000 bytes of 0x61', n: [1, 2], sha256_of_records: [hex(sha(transport(r.k_up, sid, 1, 0, big.subarray(0, 16383)))), hex(sha(transport(r.k_up, sid, 2, 1, big.subarray(16383))))] },
    reset: hex(record(4, sid, Buffer.alloc(0))) };
}
// RFC 6979 ECDSA P-256 SHA-256, raw r||s.
function ecdsa(priv, msg) {
  const q = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
  const big = (b) => BigInt('0x' + hex(b)), bytes = (x) => Buffer.from(x.toString(16).padStart(64, '0'), 'hex');
  const h1 = sha(msg), z = big(h1) % q, x = big(priv);
  let V = Buffer.alloc(32, 1), K = Buffer.alloc(32, 0);
  K = hmac(K, V, Buffer.from([0]), priv, bytes(z)); V = hmac(K, V);
  K = hmac(K, V, Buffer.from([1]), priv, bytes(z)); V = hmac(K, V);
  for (;;) {
    V = hmac(K, V); const k = big(V);
    if (k >= 1n && k < q) {
      const r = big(pub(V).subarray(1, 33)) % q;
      const inv = (a) => { let [o, n, t, nt] = [q, a % q, 0n, 1n]; while (n) { const d = o / n; [o, n] = [n, o - d * n]; [t, nt] = [nt, t - d * nt]; } return (t + q) % q; };
      const s = inv(k) * ((z + r * x) % q) % q;
      if (r && s) return cat(bytes(r), bytes(s));
    }
    K = hmac(K, V, Buffer.from([0])); V = hmac(K, V);
  }
}
{
  const vp = seq(0x51), head = '{"typ":"JWT","alg":"ES256"}', claims = '{"aud":"https://push.example.net","exp":1800000000,"sub":"https://relay.example"}';
  const input = b64u(Buffer.from(head)) + '.' + b64u(Buffer.from(claims)), sig = ecdsa(vp, Buffer.from(input));
  const jwk = { kty: 'EC', crv: 'P-256', x: b64u(pub(vp).subarray(1, 33)), y: b64u(pub(vp).subarray(33)) };
  if (!crypto.verify('sha256', Buffer.from(input), { key: crypto.createPublicKey({ key: jwk, format: 'jwk' }), dsaEncoding: 'ieee-p1363' }, sig)) throw new Error('vapid');
  out.vapid = { private: hex(vp), public: b64u(pub(vp)), header: head, claims, jwt: input + '.' + b64u(sig), authorization: 'vapid t=' + input + '.' + b64u(sig) + ', k=' + b64u(pub(vp)) };
}
function webpush(uaPub, auth, asPriv, salt, pt) {
  const asPub = pub(asPriv), ecdh = dh(asPriv, uaPub);
  const ikm = hmac(hmac(auth, ecdh), 'WebPush: info', Buffer.from([0]), uaPub, asPub, Buffer.from([1]));
  const prk = hmac(salt, ikm);
  const cek = hmac(prk, 'Content-Encoding: aes128gcm', Buffer.from([0, 1])).subarray(0, 16);
  const n = hmac(prk, 'Content-Encoding: nonce', Buffer.from([0, 1])).subarray(0, 12);
  const rs = Buffer.alloc(4); rs.writeUInt32BE(4096);
  return cat(salt, rs, Buffer.from([65]), asPub, seal(cek, n, Buffer.alloc(0), cat(pt, Buffer.from([2])), 128));
}
{
  const d = (s) => Buffer.from(s, 'base64url');
  const body = webpush(pub(d('q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94')), d('BTBZMqHH6r4Tts7J_aSIgg'), d('yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw'), d('DGv6ra1nlYgDCS1FRnbzlw'), Buffer.from('When I grow up, I want to be a watermelon'));
  out.rfc8291_appendix_a = { body: b64u(body), matches_rfc: b64u(body) === 'DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN' };
  const ua = seq(0x71), auth = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'), as = seq(0x91), salt = Buffer.from('f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff', 'hex');
  const pt = '{"v":1,"title":"pi-c","body":"Done: all 41 tests pass.","session":"w1/c1","seq":42}';
  out.push = { ua_private: hex(ua), ua_public: b64u(pub(ua)), auth: b64u(auth), as_private: hex(as), salt: hex(salt), plaintext: pt, body: b64u(webpush(pub(ua), auth, as, salt, Buffer.from(pt))),
    topic: b64u(hmac(auth, 'pic-rc/1 topic', Buffer.from([0]), 'w1/c1').subarray(0, 16)) };
}
console.log(JSON.stringify(out, null, 1));