sync-padding.ts

5.9 KB · raw

1// E7: frame padding at the relay boundary.2//3// A relay forwards only Noise ciphertext it cannot read, so the one thing it4// can still learn is traffic SHAPE — frame sizes and timing. Sizes alone5// distinguish a SYNC_HELLO from a SYNC_ENTRIES carrying a whole vault, and6// track how a vault grows over time. Padding to size buckets removes that7// resolution.8//9// Wire format of a padded plaintext, BEFORE Noise encryption:10//11//     [4-byte big-endian payload length][payload][zero padding to bucket size]12//13// The length header is what makes unpadding unambiguous, so the padding may be14// any bytes; zeros are used because they compress and cost nothing.15//16// COORDINATED WIRE CHANGE — peach-android's SyncPadding must bucket17// identically. A mismatch is loud, not silent: the receiver reads a length18// that does not fit its frame and rejects it.1920/** Bytes of the big-endian payload length that starts every padded frame. */21export const PADDED_FRAME_HEADER_BYTES = 4;2223/** Below this, every frame looks the same — covers HELLO/REQUEST/DONE and any24 *  other small control frame. */25const MIN_BUCKET = 256;26/** Above this, buckets grow linearly instead of doubling: doubling a 12 MiB27 *  frame would blow past the 24 MiB cap for no extra privacy. */28const LINEAR_BUCKET_STEP = 64 * 1024;2930/**31 * Round a total frame size up to the next bucket: powers of two while small,32 * then multiples of LINEAR_BUCKET_STEP. Exported for the cross-platform KAT.33 */34export function syncFrameBucket(totalBytes: number): number {35  if (totalBytes <= MIN_BUCKET) return MIN_BUCKET;36  if (totalBytes <= LINEAR_BUCKET_STEP) {37    let bucket = MIN_BUCKET;38    while (bucket < totalBytes) bucket *= 2;39    return bucket;40  }41  return Math.ceil(totalBytes / LINEAR_BUCKET_STEP) * LINEAR_BUCKET_STEP;42}4344export function padSyncFrame(payload: Uint8Array): Uint8Array {45  const bucket = syncFrameBucket(PADDED_FRAME_HEADER_BYTES + payload.length);46  const out = new Uint8Array(bucket);47  new DataView(out.buffer).setUint32(0, payload.length, false);48  out.set(payload, PADDED_FRAME_HEADER_BYTES);49  return out;50}5152export function unpadSyncFrame(padded: Uint8Array): Uint8Array {53  if (padded.length < PADDED_FRAME_HEADER_BYTES) {54    throw new Error("padded sync frame is shorter than its length header");55  }56  const length = new DataView(57    padded.buffer,58    padded.byteOffset,59    padded.byteLength,60  ).getUint32(0, false);61  if (length > padded.length - PADDED_FRAME_HEADER_BYTES) {62    throw new Error("padded sync frame declares more payload than it carries");63  }64  return padded.slice(65    PADDED_FRAME_HEADER_BYTES,66    PADDED_FRAME_HEADER_BYTES + length,67  );68}6970/**71 * Padded size a frame's own length header declares. The prefix must already72 * hold the header; fewer bytes is a caller bug, not a frame the wire can73 * produce. Receivers use the result to size one reassembly buffer, which74 * bounds what is stored — the frame ends once its declared bytes have75 * arrived.76 */77export function declaredPaddedFrameBytes(paddedPrefix: Uint8Array): number {78  if (paddedPrefix.length < PADDED_FRAME_HEADER_BYTES) {79    throw new Error(80      "padded sync frame prefix is shorter than its length header",81    );82  }83  const length = new DataView(84    paddedPrefix.buffer,85    paddedPrefix.byteOffset,86    PADDED_FRAME_HEADER_BYTES,87  ).getUint32(0, false);88  return syncFrameBucket(PADDED_FRAME_HEADER_BYTES + length);89}9091/**92 * Maximum plaintext bytes that fit in a single Noise transport message.93 * Noise caps a ciphertext at 65535 bytes, of which 16 are the Poly1305 auth94 * tag (see `crypto-core/src/lib.rs`), so a 65519-byte plaintext is the limit95 * before the core refuses with "Noise plaintext exceeds transport limit".96 *97 * The padded-frame ladder (above) can legitimately produce a frame up to the98 * 24 MiB relay cap. That is a multi-megabyte number of Noise messages; the99 * send/receive path chunks across this limit, not the frame.100 */101export const MAX_NOISE_PLAINTEXT_BYTES = 65519;102103/**104 * The first byte of a chunked padded frame. Every chunk carries it except the105 * last, so a receiver keeps reading until a chunk arrives without it and only106 * then hands the frame to the unpadder. A final chunk may itself begin with107 * this byte, so a receiver that has read the frame's declared size uses that108 * size for one case only: a message whose length exactly equals the bytes still109 * missing is that final chunk, and its first byte is data. A marked message110 * longer than the bytes still missing stays a continuation, so a chunker that111 * ends a frame with a final chunk of one byte or less is not supported — a lone112 * marker byte there is indistinguishable from a continuation carrying no data.113 * The frame's own length header, not the number of chunks, bounds how much of114 * those bytes it keeps. A frame that fits one Noise message is sent as one115 * unmarked chunk, as before.116 */117export const FRAME_CONTINUATION_MARKER: number = 0x01;118119/**120 * Split one already-padded frame into Noise-sized plaintext chunks.121 *122 * Non-final chunks reserve one byte for the continuation marker. Keeping this123 * math here, rather than open-coding it in the WebSocket transport, lets the124 * production path and its boundary test share the exact implementation.125 */126export function chunkPaddedSyncFrame(padded: Uint8Array): Uint8Array[] {127  if (padded.byteLength <= MAX_NOISE_PLAINTEXT_BYTES) return [padded];128129  const chunks: Uint8Array[] = [];130  for (let offset = 0; offset < padded.byteLength; ) {131    const remaining = padded.byteLength - offset;132    const isLast = remaining <= MAX_NOISE_PLAINTEXT_BYTES;133    const payloadLength = isLast134      ? remaining135      : MAX_NOISE_PLAINTEXT_BYTES - 1;136    const payload = padded.subarray(offset, offset + payloadLength);137138    if (isLast) {139      chunks.push(payload);140    } else {141      const marked = new Uint8Array(payload.byteLength + 1);142      marked[0] = FRAME_CONTINUATION_MARKER;143      marked.set(payload, 1);144      chunks.push(marked);145    }146    offset += payloadLength;147  }148  return chunks;149}