# CybSin in TypeScript — Node, Electron, browser (WebCrypto + @noble/curves)

X25519 in WebCrypto is not available in every browser yet; use `@noble/curves` for X25519 and
`@noble/ciphers` for ChaCha20-Poly1305 so the same code runs in Node, Electron and browsers.

`npm i @noble/curves @noble/ciphers @noble/hashes` (Node < 22: also `npm i ws`)

```ts
import { x25519 } from "@noble/curves/ed25519";
import { chacha20poly1305 } from "@noble/ciphers/chacha";
import { hkdf } from "@noble/hashes/hkdf";
import { sha256 } from "@noble/hashes/sha256";

const SERVER = "https://cybsin.com";
const APP_KEY = "cs_app_REPLACE_ME";
const BUNDLE_ID = "com.example.notedrop.web";

const te = new TextEncoder();

function deviceIdentity() {
  const ua = typeof navigator !== "undefined" ? navigator.userAgent : `node ${process.version}`;
  return { name: typeof navigator !== "undefined" ? "Browser" : require("os").hostname(),
           platform: typeof navigator !== "undefined" ? "web" : process.platform === "win32" ? "windows" : process.platform === "darwin" ? "macos" : "linux",
           os_version: ua.slice(0, 40), bundle_id: BUNDLE_ID, app_version: "1.0.0",
           locale: typeof navigator !== "undefined" ? navigator.language : Intl.DateTimeFormat().resolvedOptions().locale };
}

export class CybSin {
  token?: string; deviceId?: number;
  private async post(path: string, body: unknown, auth = false) {
    const r = await fetch(SERVER + path, { method: "POST", headers: {
      "X-App-Key": APP_KEY, "Content-Type": "application/json", ...(auth ? { Authorization: `Bearer ${this.token}` } : {}) },
      body: JSON.stringify(body ?? {}) });
    const j = await r.json().catch(() => ({}));
    if (r.status === 402) throw new Error("payment_required: " + JSON.stringify(j.detail));   // show a human message
    if (!r.ok) throw new Error(`HTTP ${r.status}: ${JSON.stringify(j)}`);
    return j;
  }
  async signIn(email: string, password: string, register = false) {
    const r = await this.post(`/api/v1/${register ? "register" : "login"}`, { email, password, device: deviceIdentity() });
    this.token = r.token; this.deviceId = r.device_id;
  }
  pairNew = () => this.post("/api/v1/pair/new", { device_id: this.deviceId }, true) as Promise<{ code: string; session_id: string; qr: string }>;
  pairJoin = (code: string) => this.post("/api/v1/pair/join", { code, device_id: this.deviceId }, true).then(r => r.session_id as string);

  async connect(session: string, role: "host" | "guest", code: string): Promise<Tunnel> {
    const url = `${SERVER.replace(/^http/, "ws")}/ws/relay/${session}?token=${this.token}&role=${role}&app_key=${APP_KEY}&device_id=${this.deviceId ?? 0}`;
    const WS: typeof WebSocket = (globalThis as any).WebSocket ?? (await import("ws")).default;
    const ws = new WS(url); (ws as any).binaryType = "arraybuffer";
    const queue: (ArrayBuffer | string)[] = []; let wake: (() => void) | null = null;
    ws.onmessage = (e: MessageEvent) => { queue.push(e.data); wake?.(); };
    ws.onclose = () => { queue.push('{"t":"peer_left"}'); wake?.(); };
    const next = async () => { while (!queue.length) await new Promise<void>(r => (wake = r)); return queue.shift()!; };
    await new Promise<void>((res, rej) => { ws.onopen = () => res(); ws.onerror = () => rej(new Error("ws error")); });
    for (;;) {                                          // wait for joined
      const m = await next();
      if (typeof m === "string") { const t = JSON.parse(m); if (t.t === "joined") break; if (t.t === "expired" || t.code) throw new Error(JSON.stringify(t)); }
    }
    return Tunnel.handshake(ws, next, role === "host", code);
  }
}

export class Tunnel {
  private tx = 0; private rx = 0; sas = "";
  private constructor(private ws: WebSocket, private next: () => Promise<ArrayBuffer | string>, private key: Uint8Array,
                      private dirMe: number, private dirThem: number) {}
  static async handshake(ws: WebSocket, next: () => Promise<ArrayBuffer | string>, host: boolean, code: string) {
    const priv = x25519.utils.randomPrivateKey(); const mine = x25519.getPublicKey(priv);
    ws.send(mine);
    let theirs: Uint8Array | undefined;
    while (!theirs) { const m = await next(); if (typeof m !== "string" && m.byteLength === 32) theirs = new Uint8Array(m); }
    const shared = x25519.getSharedSecret(priv, theirs);
    const key = hkdf(sha256, shared, te.encode(code), te.encode("cybsin-v1"), 32);
    const [hp, gp] = host ? [mine, theirs] : [theirs, mine];
    const fp = sha256(new Uint8Array([...hp, ...gp]));
    const t = new Tunnel(ws, next, key, host ? 1 : 2, host ? 2 : 1);
    t.sas = `${hex(fp[0])}${hex(fp[1])} · ${hex(fp[2])}${hex(fp[3])}`;
    return t;
  }
  private nonce(dir: number, counter: number) {
    const n = new Uint8Array(12); n[0] = dir; new DataView(n.buffer).setBigUint64(4, BigInt(counter)); return n;
  }
  send(plaintext: Uint8Array) { this.ws.send(chacha20poly1305(this.key, this.nonce(this.dirMe, this.tx++)).encrypt(plaintext)); }  // ciphertext||tag
  /** Uint8Array payload, or null when the peer left. Throws on decryption failure (fatal). */
  async receive(): Promise<Uint8Array | null> {
    for (;;) {
      const m = await this.next();
      if (typeof m === "string") { if (m.includes("peer_left") || m.includes("expired")) return null; continue; }
      return chacha20poly1305(this.key, this.nonce(this.dirThem, this.rx++)).decrypt(new Uint8Array(m));
    }
  }
  close() { this.ws.close(); }
}
const hex = (b: number) => b.toString(16).toUpperCase().padStart(2, "0");
```

Notes
- Browsers cannot report MAC/hostname; `platform: "web"` with the user agent is enough. Electron can add `os.hostname()`, `os.userInfo().username`.
- Store the token in the OS keychain (Electron `safeStorage`) or, in a browser, in memory / `sessionStorage`.
