sync-wire.ts

1.1 KB · raw

1import type { SyncMessage } from './sync-types';23// Sync messages are JSON-encoded and then Noise NK encrypted. The encrypted4// binary is base64-encoded for transmission over the text-only WS server.5// This layer only handles the JSON ↔ SyncMessage boundary; the caller6// is responsible for the encrypt/decrypt step around it.78export function encodeSyncMessage(msg: SyncMessage): Uint8Array {9  return new TextEncoder().encode(JSON.stringify(msg));10}1112export function decodeSyncMessage(data: Uint8Array): SyncMessage {13  const parsed = JSON.parse(new TextDecoder().decode(data));14  if (typeof parsed?.type !== 'string') throw new Error('invalid sync message');15  return parsed as SyncMessage;16}1718// Base64 helpers for the WS text-frame transport layer.1920export function bytesToBase64(bytes: Uint8Array): string {21  let binary = '';22  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);23  return btoa(binary);24}2526export function base64ToBytes(b64: string): Uint8Array {27  const binary = atob(b64);28  const bytes = new Uint8Array(binary.length);29  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);30  return bytes;31}