Something went wrong. Try again.
Sendspin in Zig, both sides: a player client for Music Assistant, and a server streaming to players in sync
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Pairing with a PIN: how a player that has only ever been a guest becomes//! one the server knows, with a key of its own. Nothing here does I/O.//!//! A sealed connection starts on the sentinel PSK, which anyone knows, so//! it proves nothing about either side. Pairing replaces it with a long-term//! PSK the player makes and gives the server, over the sealed channel, in a//! way only a server that knows the PIN can read. From then on each//! connection to that server uses the long-term PSK, and each side knows the//! other is the one it paired with.//!//! This is the dynamic-PIN method, which suits a player with a screen://!//! 1. the server asks for it, with `pairing` in a `server/activate`;//! 2. the player sends `client/pair-init`, committing to a random `nonce_B`;//! 3. the server sends its own random `nonce_A`, and the player derives the//! PIN from both nonces and the handshake hash, and shows it;//! 4. a person types the PIN into the server, and the two run CPace on it,//! each sending a share (`server/pair-auth`, `client/pair-auth`) and a//! confirmation tag (`server/pair-confirm`, `client/pair-confirm`, which//! also reveals `nonce_B`);//! 5. the player sends its new long-term PSK in `client/pair-finalize`,//! encrypted under a key derived from what CPace agreed, and the server//! acknowledges it with `server/pair-finalize`.//!//! The commitment is what stops a server choosing `nonce_A` after seeing//! `nonce_B` to steer the PIN; the handshake hash in the CPace session id is//! what ties the PIN to this one connection. `DynamicPin` is the player's//! side, one message at a time; `Client` drives it.
const std = @import("std");const CPace = @import("std_crypto_ext").CPace;const secure = @import("secure.zig");
const Sha256 = std.crypto.hash.sha2.Sha256;const ChaCha20Poly1305 = std.crypto.aead.chacha_poly.ChaCha20Poly1305;const b64url = std.base64.url_safe_no_pad;
pub const nonce_length = 32;pub const commit_length = Sha256.digest_length;pub const min_pin_digits = 4;pub const max_pin_digits = 12;/// The shortest PIN offered unless a player asks for longer, and the length/// below which a PIN would need a gesture on the player to be allowed.pub const default_min_pin_digits = 6;/// Consecutive wrong PINs after which dynamic PIN pairing wants a gesture/// on the player, which this player cannot make, so it stops.pub const pin_escalation_threshold = 10;/// A wrapped PSK: the PSK and the AEAD's tag.pub const wrapped_length = 32 + ChaCha20Poly1305.tag_length;
const pin_label = "sendspin-pin-derive-v1";const commit_label = "sendspin-pair-commit-v1";const sid_label = "sendspin-pair-pake-v1";const wrap_label = "sendspin-pair-psk-wrap-v1";/// CPace's associated data: the server is the initiator, the player the/// responder.const ad_server = "server";const ad_client = "client";
/// The PIN both sides derive: SHA-256 over a label, the handshake hash and/// both nonces, read as a big-endian number and taken modulo 10^digits,/// zero-padded to `digits`.pub fn derivePin(buf: *[max_pin_digits]u8, handshake_hash: []const u8, nonce_a: *const [nonce_length]u8, nonce_b: *const [nonce_length]u8, digits: usize) []const u8 { std.debug.assert(digits >= min_pin_digits and digits <= max_pin_digits); var h = Sha256.init(.{}); h.update(pin_label); h.update(handshake_hash); h.update(nonce_a); h.update(nonce_b); const digest = h.finalResult(); const modulus = std.math.powi(u64, 10, digits) catch unreachable; // 256 bits mod at most 10^12, a byte at a time: the remainder stays // below 2^40, so shifting it by eight bits fits. var r: u64 = 0; for (digest) |byte| r = (r * 256 + byte) % modulus; var i = digits; while (i > 0) { i -= 1; buf[i] = '0' + @as(u8, @intCast(r % 10)); r /= 10; } return buf[0..digits];}
/// The commitment to `nonce_B` a player sends before it sees `nonce_A`.pub fn commit(nonce: *const [nonce_length]u8) [commit_length]u8 { var h = Sha256.init(.{}); h.update(commit_label); h.update(nonce); return h.finalResult();}
/// The CPace session id for attempt `index` on the connection whose/// handshake hash is `handshake_hash`.pub fn sessionId(buf: []u8, handshake_hash: []const u8, index: u32) []const u8 { const len = sid_label.len + handshake_hash.len + 4; @memcpy(buf[0..sid_label.len], sid_label); @memcpy(buf[sid_label.len..][0..handshake_hash.len], handshake_hash); std.mem.writeInt(u32, buf[len - 4 ..][0..4], index, .big); return buf[0..len];}
/// The key the long-term PSK is sent under: what CPace agreed, and only a/// side that knew the PIN has it.pub fn wrapKey(sid: []const u8, isk: *const [CPace.isk_length]u8) [32]u8 { var h = Sha256.init(.{}); h.update(wrap_label); h.update(sid); h.update(isk); return h.finalResult();}
/// The PSK sealed under the wrap key, as the ChaCha20-Poly1305 suite does/// it: an all-zero nonce, which a key used once allows, and no associated/// data; ciphertext then tag.pub fn wrapPsk(key: [32]u8, psk: [32]u8) [wrapped_length]u8 { var out: [wrapped_length]u8 = undefined; ChaCha20Poly1305.encrypt(out[0..32], out[32..], &psk, "", @splat(0), key); return out;}
/// Why an attempt was abandoned, as `pair/abort` names it.pub const AbortReason = enum { attempt_timeout, concurrent_attempt, method_not_supported, pin_length_unacceptable, pin_mismatch, user_cancelled,
/// Whether whoever sent it closes the connection afterwards; after any /// other, the connection stays up for another attempt. pub fn closes(r: AbortReason) bool { return r == .concurrent_attempt; }};
/// A pairing message from the server, parsed.pub const Incoming = union(enum) { /// `server/pair-init`: the server's nonce. init: [nonce_length]u8, /// `server/pair-auth`: its CPace share. auth: [CPace.share_length]u8, /// `server/pair-confirm`: its confirmation tag. confirm: [CPace.tag_length]u8, /// `server/pair-finalize`: it has the PSK. finalize, /// `pair/abort`, with its reason, or null for one this does not know. abort: ?AbortReason,};
/// Whether a message type is one of pairing's; anything else during an/// attempt means the server has left pairing.pub fn isPairingType(t: []const u8) bool { return std.mem.startsWith(u8, t, "server/pair-") or std.mem.startsWith(u8, t, "client/pair-") or std.mem.eql(u8, t, "pair/abort");}
/// Parse a pairing message the server sent; error.Malformed for one whose/// fields are missing or the wrong size, which fails the attempt.pub fn parse(arena: std.mem.Allocator, v: std.json.Value) error{ Malformed, OutOfMemory }!?Incoming { if (v != .object) return null; const t = v.object.get("type") orelse return null; if (t != .string) return null; _ = arena; const empty: std.json.ObjectMap = .empty; const payload = v.object.get("payload") orelse std.json.Value{ .object = empty }; if (payload != .object) return error.Malformed; const p = payload.object; if (std.mem.eql(u8, t.string, "server/pair-init")) return .{ .init = try field(nonce_length, p, "nonce_A") }; if (std.mem.eql(u8, t.string, "server/pair-auth")) return .{ .auth = try field(CPace.share_length, p, "pake_msg_1") }; if (std.mem.eql(u8, t.string, "server/pair-confirm")) return .{ .confirm = try field(CPace.tag_length, p, "server_kc") }; if (std.mem.eql(u8, t.string, "server/pair-finalize")) return .finalize; if (std.mem.eql(u8, t.string, "pair/abort")) { const reason = p.get("reason") orelse return .{ .abort = null }; if (reason != .string) return .{ .abort = null }; return .{ .abort = std.meta.stringToEnum(AbortReason, reason.string) }; } return null;}
fn field(comptime n: usize, p: std.json.ObjectMap, name: []const u8) error{Malformed}![n]u8 { const value = p.get(name) orelse return error.Malformed; if (value != .string) return error.Malformed; const len = b64url.Decoder.calcSizeForSlice(value.string) catch return error.Malformed; if (len != n) return error.Malformed; var out: [n]u8 = undefined; b64url.Decoder.decode(&out, value.string) catch return error.Malformed; return out;}
/// The player's side of one dynamic-PIN attempt, a message at a time. Each/// step takes what the server sent and gives back what to send, or says the/// attempt is over; the caller shows the PIN and keeps the PSK.pub const DynamicPin = struct { index: u32, digits: usize, handshake_hash: [32]u8, nonce_b: [nonce_length]u8, /// The CPace session id: exactly this long, so the array is the id. sid: [sid_label.len + 32 + 4]u8 = undefined, pin_buf: [max_pin_digits]u8 = undefined, pin: []const u8 = "", cpace: CPace = undefined, psk: [32]u8 = undefined, state: enum { init_sent, pin_shown, auth_sent, confirm_sent, finalize_sent, done } = .init_sent,
pub const Error = error{ /// A message out of its turn, or a CPace share that is a low-order /// point: the attempt fails. UnexpectedMessage, };
/// Begin attempt `index` with a PIN of `digits`, on the connection /// whose handshake hash is `handshake_hash`; `out` receives the /// `client/pair-init` to send. pub fn start(random: std.Random, handshake_hash: []const u8, index: u32, digits: usize, out: *std.Io.Writer) (std.Io.Writer.Error)!DynamicPin { var self: DynamicPin = .{ .index = index, .digits = digits, .handshake_hash = handshake_hash[0..32].*, .nonce_b = undefined, }; random.bytes(&self.nonce_b); _ = sessionId(&self.sid, &self.handshake_hash, index); var c: [b64url.Encoder.calcSize(commit_length)]u8 = undefined; try out.print( \\{{"type":"client/pair-init","payload":{{"pairing_index":{d},"commit_B":"{s}"}}}} , .{ index, b64url.Encoder.encode(&c, &commit(&self.nonce_b)) }); return self; }
/// `server/pair-init` arrived: derive the PIN, which the caller shows, /// and start CPace on it. pub fn onInit(self: *DynamicPin, random: std.Random, nonce_a: [nonce_length]u8) Error![]const u8 { if (self.state != .init_sent) return error.UnexpectedMessage; self.pin = derivePin(&self.pin_buf, &self.handshake_hash, &nonce_a, &self.nonce_b, self.digits); self.cpace = CPace.start(.responder, self.pin, "", &self.sid, ad_client, random) catch return error.UnexpectedMessage; self.state = .pin_shown; return self.pin; }
/// `server/pair-auth` arrived, once a person has typed the PIN into the /// server: `out` receives this side's share. pub fn onAuth(self: *DynamicPin, share: [CPace.share_length]u8, out: *std.Io.Writer) (Error || std.Io.Writer.Error)!void { if (self.state != .pin_shown) return error.UnexpectedMessage; var s: [b64url.Encoder.calcSize(CPace.share_length)]u8 = undefined; try out.print( \\{{"type":"client/pair-auth","payload":{{"pake_msg_2":"{s}"}}}} , .{b64url.Encoder.encode(&s, &self.cpace.share)}); self.cpace.derive(share, ad_server) catch return error.UnexpectedMessage; self.state = .auth_sent; }
/// `server/pair-confirm` arrived: whether the server knew the PIN. If /// it did, `out` receives this side's tag and `nonce_B`; if not, the /// caller aborts with `pin_mismatch`. pub fn onConfirm(self: *DynamicPin, server_tag: [CPace.tag_length]u8, out: *std.Io.Writer) (Error || std.Io.Writer.Error)!bool { if (self.state != .auth_sent) return error.UnexpectedMessage; if (!self.cpace.verify(&server_tag)) return false; var t: [b64url.Encoder.calcSize(CPace.tag_length)]u8 = undefined; var n: [b64url.Encoder.calcSize(nonce_length)]u8 = undefined; try out.print( \\{{"type":"client/pair-confirm","payload":{{"client_kc":"{s}","nonce_B":"{s}"}}}} , .{ b64url.Encoder.encode(&t, &self.cpace.tag()), b64url.Encoder.encode(&n, &self.nonce_b) }); self.state = .confirm_sent; return true; }
/// Make the long-term PSK and put it, wrapped, into `out`'s /// `client/pair-finalize`. The caller keeps `psk` once the server /// acknowledges it. pub fn finalize(self: *DynamicPin, random: std.Random, out: *std.Io.Writer) (Error || std.Io.Writer.Error)!void { if (self.state != .confirm_sent) return error.UnexpectedMessage; random.bytes(&self.psk); const wrapped = wrapPsk(wrapKey(&self.sid, &self.cpace.isk), self.psk); var w: [b64url.Encoder.calcSize(wrapped_length)]u8 = undefined; try out.print( \\{{"type":"client/pair-finalize","payload":{{"wrapped_psk":"{s}"}}}} , .{b64url.Encoder.encode(&w, &wrapped)}); self.state = .finalize_sent; }
/// `server/pair-finalize` arrived: the server has the PSK, which is now /// this connection's and the next ones'. pub fn onFinalize(self: *DynamicPin) Error![32]u8 { if (self.state != .finalize_sent) return error.UnexpectedMessage; self.state = .done; return self.psk; }};
/// A pairing message from a client, parsed: what the server's side reads.pub const ClientIncoming = union(enum) { /// `client/pair-init`: the attempt's index, and the commitment to /// `nonce_B`. init: struct { index: u32, commit: [commit_length]u8 }, /// `client/pair-auth`: its CPace share. auth: [CPace.share_length]u8, /// `client/pair-confirm`: its tag, and `nonce_B` revealed. confirm: struct { tag: [CPace.tag_length]u8, nonce_b: [nonce_length]u8 }, /// `client/pair-finalize`: its long-term PSK, wrapped. finalize: [wrapped_length]u8, /// `client/pair-pending`: it waits for a gesture on the player. pending, /// `pair/abort`, with its reason, or null for one this does not know. abort: ?AbortReason,};
/// Parse a pairing message a client sent; null for any other message, and/// error.Malformed for one whose fields are missing or the wrong size.pub fn parseClient(v: std.json.Value) error{Malformed}!?ClientIncoming { if (v != .object) return null; const t = v.object.get("type") orelse return null; if (t != .string) return null; const empty: std.json.ObjectMap = .empty; const payload = v.object.get("payload") orelse std.json.Value{ .object = empty }; if (payload != .object) return error.Malformed; const p = payload.object; if (std.mem.eql(u8, t.string, "client/pair-init")) { const index = p.get("pairing_index") orelse return error.Malformed; if (index != .integer) return error.Malformed; return .{ .init = .{ .index = std.math.cast(u32, index.integer) orelse return error.Malformed, .commit = try field(commit_length, p, "commit_B"), } }; } if (std.mem.eql(u8, t.string, "client/pair-auth")) return .{ .auth = try field(CPace.share_length, p, "pake_msg_2") }; if (std.mem.eql(u8, t.string, "client/pair-confirm")) return .{ .confirm = .{ .tag = try field(CPace.tag_length, p, "client_kc"), .nonce_b = try field(nonce_length, p, "nonce_B"), } }; if (std.mem.eql(u8, t.string, "client/pair-finalize")) return .{ .finalize = try field(wrapped_length, p, "wrapped_psk") }; if (std.mem.eql(u8, t.string, "client/pair-pending")) return .pending; if (std.mem.eql(u8, t.string, "pair/abort")) { const reason = p.get("reason") orelse return .{ .abort = null }; if (reason != .string) return .{ .abort = null }; return .{ .abort = std.meta.stringToEnum(AbortReason, reason.string) }; } return null;}
/// The server's side of one dynamic-PIN attempt, a message at a time: the/// mirror of `DynamicPin`. The server is CPace's initiator.pub const Verifier = struct { index: u32, digits: usize, handshake_hash: [32]u8, commit_b: [commit_length]u8, nonce_a: [nonce_length]u8 = undefined, sid: [sid_label.len + 32 + 4]u8 = undefined, cpace: CPace = undefined, state: enum { init_sent, auth_sent, confirm_sent, confirmed, done } = .init_sent,
pub const Error = error{ /// A message out of its turn, or a share that is a low-order point. UnexpectedMessage, /// The client revealed a `nonce_B` other than the one it committed /// to: it chose it after seeing `nonce_A`, to steer the PIN. CommitMismatch, /// The client's tag does not verify: it did not have the PIN. PinMismatch, /// The wrapped PSK does not open under the key CPace agreed. BadPsk, };
/// The client's `client/pair-init` arrived, for an attempt with a PIN /// of `digits` on the connection whose handshake hash is /// `handshake_hash`: `out` receives `server/pair-init` with `nonce_A`. pub fn start(random: std.Random, handshake_hash: []const u8, index: u32, commit_b: [commit_length]u8, digits: usize, out: *std.Io.Writer) std.Io.Writer.Error!Verifier { var self: Verifier = .{ .index = index, .digits = digits, .handshake_hash = handshake_hash[0..32].*, .commit_b = commit_b, }; random.bytes(&self.nonce_a); _ = sessionId(&self.sid, &self.handshake_hash, index); var n: [b64url.Encoder.calcSize(nonce_length)]u8 = undefined; try out.print( \\{{"type":"server/pair-init","payload":{{"nonce_A":"{s}"}}}} , .{b64url.Encoder.encode(&n, &self.nonce_a)}); return self; }
/// A person has typed the PIN the player shows: `out` receives /// `server/pair-auth` with this side's share. pub fn auth(self: *Verifier, random: std.Random, pin: []const u8, out: *std.Io.Writer) (Error || std.Io.Writer.Error)!void { if (self.state != .init_sent) return error.UnexpectedMessage; self.cpace = CPace.start(.initiator, pin, "", &self.sid, ad_server, random) catch return error.UnexpectedMessage; var s: [b64url.Encoder.calcSize(CPace.share_length)]u8 = undefined; try out.print( \\{{"type":"server/pair-auth","payload":{{"pake_msg_1":"{s}"}}}} , .{b64url.Encoder.encode(&s, &self.cpace.share)}); self.state = .auth_sent; }
/// The client's share arrived: `out` receives `server/pair-confirm` /// with this side's tag. pub fn onAuth(self: *Verifier, share: [CPace.share_length]u8, out: *std.Io.Writer) (Error || std.Io.Writer.Error)!void { if (self.state != .auth_sent) return error.UnexpectedMessage; self.cpace.derive(share, ad_client) catch return error.UnexpectedMessage; var t: [b64url.Encoder.calcSize(CPace.tag_length)]u8 = undefined; try out.print( \\{{"type":"server/pair-confirm","payload":{{"server_kc":"{s}"}}}} , .{b64url.Encoder.encode(&t, &self.cpace.tag())}); self.state = .confirm_sent; }
/// The client's tag and `nonce_B` arrived: it had the PIN, and the /// nonce is the one it committed to. pub fn onConfirm(self: *Verifier, tag: [CPace.tag_length]u8, nonce_b: [nonce_length]u8) Error!void { if (self.state != .confirm_sent) return error.UnexpectedMessage; if (!self.cpace.verify(&tag)) return error.PinMismatch; if (!std.crypto.timing_safe.eql([commit_length]u8, commit(&nonce_b), self.commit_b)) return error.CommitMismatch; self.state = .confirmed; }
/// The client's long-term PSK arrived, wrapped: unwrapped, and /// `server/pair-finalize` into `out`. The caller keeps the PSK and runs /// the handshake again on it. pub fn onFinalize(self: *Verifier, wrapped: [wrapped_length]u8, out: *std.Io.Writer) (Error || std.Io.Writer.Error)![32]u8 { if (self.state != .confirmed) return error.UnexpectedMessage; var psk: [32]u8 = undefined; ChaCha20Poly1305.decrypt(&psk, wrapped[0..32], wrapped[32..].*, "", @splat(0), wrapKey(&self.sid, &self.cpace.isk)) catch return error.BadPsk; try out.writeAll( \\{"type":"server/pair-finalize","payload":{}} ); self.state = .done; return psk; }};
/// `pair/abort` with `reason`.pub fn writeAbort(w: *std.Io.Writer, reason: AbortReason) std.Io.Writer.Error!void { try w.print( \\{{"type":"pair/abort","payload":{{"reason":"{t}"}}}} , .{reason});}
/// `client/pair-pending`: the attempt waits for a gesture on the player.pub fn writePending(w: *std.Io.Writer, index: u32) std.Io.Writer.Error!void { try w.print( \\{{"type":"client/pair-pending","payload":{{"pairing_index":{d}}}}} , .{index});}
const testing = std.testing;
// Every expected value below is what aiosendspin 9.1.1 computes from the// same inputs: `pin.derive_pin`, `pin.commit`, `pairing._pake_sid`, its wrap// key, and ChaCha20Poly1305 from `cryptography` over the PSK.fn seq(comptime start: u8) [32]u8 { var out: [32]u8 = undefined; for (&out, 0..) |*b, i| b.* = start + @as(u8, @intCast(i)); return out;}
test "the PIN, the commitment and the session id, as aiosendspin has them" { const hh = seq(0); const na = seq(32); const nb = seq(64); var buf: [max_pin_digits]u8 = undefined; try testing.expectEqualStrings("802858", derivePin(&buf, &hh, &na, &nb, 6)); try testing.expectEqualStrings("652760802858", derivePin(&buf, &hh, &na, &nb, 12));
var c: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&c, "f6d431646ea17a4488f6008d0da4dbd79b7c0a898c3631453fb6ffc912d29c18"); try testing.expectEqualSlices(u8, &c, &commit(&nb));
var sid_buf: [64]u8 = undefined; var want_sid: [57]u8 = undefined; _ = try std.fmt.hexToBytes(&want_sid, "73656e647370696e2d706169722d70616b652d7631000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f00000003"); try testing.expectEqualSlices(u8, &want_sid, sessionId(&sid_buf, &hh, 3));}
test "the PSK wrapped as aiosendspin wraps it, and its id" { var sid_buf: [64]u8 = undefined; const sid = sessionId(&sid_buf, &seq(0), 3); var isk: [64]u8 = undefined; for (&isk, 0..) |*b, i| b.* = 100 + @as(u8, @intCast(i)); const key = wrapKey(sid, &isk); var want_key: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&want_key, "2918c8554226f77c7ce038b9fc28059f1be87c49153e24780aa2bf6018d6a7f4"); try testing.expectEqualSlices(u8, &want_key, &key);
const psk = seq(200); var enc: [b64url.Encoder.calcSize(wrapped_length)]u8 = undefined; try testing.expectEqualStrings("dtN-ysTJwefTSkoRrsxsddm7-52lTltch2l8zhP6rNLC6J-bQGFRINy3ZCCYek0s", b64url.Encoder.encode(&enc, &wrapPsk(key, psk))); try testing.expectEqualStrings("XXghF9SONiiTmUW3UVkl6IPjk4jjVFeQz82NrN06usE", &secure.pskId(psk));}
test "an attempt with the right PIN, the server played here" { var prng: std.Random.DefaultPrng = .init(3); const random = prng.random(); const hh = seq(9); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit();
var player = try DynamicPin.start(random, &hh, 1, 6, &out.writer); try testing.expect(std.mem.indexOf(u8, out.written(), "\"pairing_index\":1") != null);
// The server: its nonce, then CPace as the initiator on the PIN a // person reads off the player. const nonce_a = seq(40); const pin = try player.onInit(random, nonce_a); var sid_buf: [64]u8 = undefined; const sid = sessionId(&sid_buf, &hh, 1); var server = try CPace.start(.initiator, pin, "", sid, ad_server, random);
out.clearRetainingCapacity(); try player.onAuth(server.share, &out.writer); try server.derive(player.cpace.share, ad_client); out.clearRetainingCapacity(); try testing.expect(try player.onConfirm(server.tag(), &out.writer)); try testing.expect(server.verify(&player.cpace.tag()));
out.clearRetainingCapacity(); try player.finalize(random, &out.writer); // What the server unwraps with its own CPace key is the player's PSK. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const v = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), out.written(), .{}); const wrapped = v.object.get("payload").?.object.get("wrapped_psk").?.string; var sealed: [wrapped_length]u8 = undefined; try b64url.Decoder.decode(&sealed, wrapped); var psk: [32]u8 = undefined; try ChaCha20Poly1305.decrypt(&psk, sealed[0..32], sealed[32..].*, "", @splat(0), wrapKey(sid, &server.isk)); try testing.expectEqualSlices(u8, &psk, &try player.onFinalize());}
test "a server that does not know the PIN is not confirmed" { var prng: std.Random.DefaultPrng = .init(4); const random = prng.random(); const hh = seq(9); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var player = try DynamicPin.start(random, &hh, 2, 6, &out.writer); _ = try player.onInit(random, seq(1)); var sid_buf: [64]u8 = undefined; var server = try CPace.start(.initiator, "000000", "", sessionId(&sid_buf, &hh, 2), ad_server, random); try player.onAuth(server.share, &out.writer); try server.derive(player.cpace.share, ad_client); try testing.expect(!try player.onConfirm(server.tag(), &out.writer)); try testing.expectError(error.UnexpectedMessage, player.finalize(random, &out.writer));}
test "pairing messages parse, and malformed ones are refused" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const parsed = struct { fn f(al: std.mem.Allocator, text: []const u8) !?Incoming { return parse(al, try std.json.parseFromSliceLeaky(std.json.Value, al, text, .{})); } }.f; const init = (try parsed(a, \\{"type":"server/pair-init","payload":{"nonce_A":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"}} )).?; try testing.expectEqual(@as(u8, 31), init.init[31]); try testing.expectEqual(@as(?AbortReason, .pin_mismatch), (try parsed(a, \\{"type":"pair/abort","payload":{"reason":"pin_mismatch"}} )).?.abort); try testing.expect((try parsed(a, \\{"type":"server/pair-finalize","payload":{}} )).? == .finalize); try testing.expectError(error.Malformed, parsed(a, \\{"type":"server/pair-auth","payload":{"pake_msg_1":"AAEC"}} )); try testing.expectEqual(@as(?Incoming, null), try parsed(a, \\{"type":"server/activate","payload":{"activities":[]}} )); try testing.expect(isPairingType("pair/abort") and !isPairingType("server/activate"));}
/// Run one attempt between a `Verifier` and a `DynamicPin`, the server/// typing `typed`; the PSK both hold, or the error that ended it.fn verifyAttempt(seed: u64, typed: ?[]const u8, forge_nonce: bool) !struct { [32]u8, [32]u8 } { var prng: std.Random.DefaultPrng = .init(seed); const random = prng.random(); const hh = seq(17); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const read = struct { fn client(al: std.mem.Allocator, text: []const u8) !ClientIncoming { return (try parseClient(try std.json.parseFromSliceLeaky(std.json.Value, al, text, .{}))).?; } fn server(al: std.mem.Allocator, text: []const u8) !Incoming { return (try parse(al, try std.json.parseFromSliceLeaky(std.json.Value, al, text, .{}))).?; } };
var player = try DynamicPin.start(random, &hh, 1, 6, &out.writer); const init = (try read.client(a, try a.dupe(u8, out.written()))).init; try testing.expectEqual(@as(u32, 1), init.index); out.clearRetainingCapacity(); var verifier = try Verifier.start(random, &hh, init.index, init.commit, 6, &out.writer); const pin = try player.onInit(random, (try read.server(a, try a.dupe(u8, out.written()))).init);
out.clearRetainingCapacity(); try verifier.auth(random, typed orelse pin, &out.writer); const server_share = (try read.server(a, try a.dupe(u8, out.written()))).auth; out.clearRetainingCapacity(); try player.onAuth(server_share, &out.writer); const client_share = (try read.client(a, try a.dupe(u8, out.written()))).auth; out.clearRetainingCapacity(); try verifier.onAuth(client_share, &out.writer); const server_tag = (try read.server(a, try a.dupe(u8, out.written()))).confirm; out.clearRetainingCapacity(); if (!try player.onConfirm(server_tag, &out.writer)) return error.PinMismatch; var confirm = (try read.client(a, try a.dupe(u8, out.written()))).confirm; if (forge_nonce) confirm.nonce_b[0] ^= 1; try verifier.onConfirm(confirm.tag, confirm.nonce_b); out.clearRetainingCapacity(); try player.finalize(random, &out.writer); const wrapped = (try read.client(a, try a.dupe(u8, out.written()))).finalize; out.clearRetainingCapacity(); const server_psk = try verifier.onFinalize(wrapped, &out.writer); _ = (try read.server(a, try a.dupe(u8, out.written()))).finalize; return .{ server_psk, try player.onFinalize() };}
test "the server's side of an attempt against the player's: the PSK both hold" { const psks = try verifyAttempt(51, null, false); try testing.expectEqualSlices(u8, &psks[0], &psks[1]);}
test "a wrong PIN typed at the server fails the player's check, and a nonce not committed to the server's" { try testing.expectError(error.PinMismatch, verifyAttempt(52, "000000", false)); try testing.expectError(error.CommitMismatch, verifyAttempt(53, null, true));}