File size: 5,984 Bytes
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// WebSocket test client for the Taper gateway, shared by the test files.

import { solveChallenge } from '../client/pow.js';
import { parseBinaryFrame } from '../client/media.js';
import { padJson } from '../client/crypto.js';
import * as opaque from '../client/opaque.js';

// Minimal client: request/response by id, dispatch queue, close tracking.
export class Client {
  // `open(url)` may return any WHATWG-style WebSocket, for example one that
  // goes through Tor (test-tor-live.js).
  // `timeoutMs` is the default wait for frames: raise it for slow transports (Tor).
  // `heartbeat` keeps the connection alive, as a real client does, for tests
  // that stay connected longer than the server's heartbeat timeout.
  static async connectTo(url, { open = (u) => new WebSocket(u), timeoutMs = 2000, heartbeat = false } = {}) {
    const c = new Client();
    c.timeoutMs = timeoutMs;
    c.ws = open(url);
    c.nextId = 1;
    c.pending = new Map();
    c.frames = [];
    c.waiters = [];
    c.handlers = [];
    c.downloads = new Map(); // download_id -> Map(index -> chunk), filled from binary frames
    c.ws.binaryType = 'arraybuffer';
    c.closed = new Promise((resolve) => c.ws.addEventListener('close', (e) => resolve({ code: e.code, reason: e.reason })));
    c.sizes = { text: [], binary: [] }; // byte length of every frame received
    c.ws.addEventListener('message', (e) => {
      if (typeof e.data === 'string') c.sizes.text.push(new TextEncoder().encode(e.data).length);
      else c.sizes.binary.push(e.data.byteLength);
      if (typeof e.data !== 'string') {
        const frame = parseBinaryFrame(new Uint8Array(e.data));
        if (frame?.op === 2) c.downloads.get(frame.id)?.set(frame.index, frame.data.slice());
        return;
      }
      const f = JSON.parse(e.data);
      if (f.op === 'response') {
        c.pending.get(f.id)?.(f);
        c.pending.delete(f.id);
        return;
      }
      if (f.op === 'hello') c.connectionId = f.body.connection_id;
      if (f.op === 'ready' || f.op === 'resumed') c.sessionId = f.body.session_id;
      if (c.handlers.some((h) => h(f))) return;
      c.frames.push(f);
      c.waiters = c.waiters.filter((w) => !w(f));
    });
    await new Promise((resolve, reject) => {
      c.ws.addEventListener('open', resolve, { once: true });
      c.ws.addEventListener('error', reject, { once: true });
    });
    c.hello = await c.next((f) => f.op === 'hello');
    if (heartbeat) {
      const timer = setInterval(() => c.send({ op: 'heartbeat' }), c.hello.body.heartbeat_interval_ms / 2);
      c.handlers.push((f) => f.op === 'heartbeat_ack');
      c.closed.then(() => clearInterval(timer));
    }
    return c;
  }
  send(frame) {
    const text = JSON.stringify(padJson(frame));
    (this.sent ??= []).push(text); // every text frame sent, for leak checks
    this.ws.send(text);
  }
  sendBinary(bytes) { this.ws.send(bytes); }
  // Resolves with the response frame. Rejects if the connection closes first,
  // or (with a long timeoutMs, for slow transports) if no answer comes in time.
  request(method, body = {}, extra = {}) {
    const id = this.nextId++;
    return new Promise((resolve, reject) => {
      const fail = (err) => { this.pending.delete(id); reject(err); };
      const timer = this.timeoutMs > 2000 ? setTimeout(() => fail(new Error(`${method}: no response in ${this.timeoutMs} ms`)), this.timeoutMs) : null;
      this.closed.then(() => { if (this.pending.has(id)) fail(new Error(`${method}: connection closed`)); });
      this.pending.set(id, (f) => { clearTimeout(timer); resolve(f); });
      this.send({ op: 'request', id, method, body, ...extra });
    });
  }
  // Like request(), but behaves as a real client does: waits out short rate
  // limits, and solves proof-of-work challenges.
  async call(method, body) {
    let extra = {};
    for (let attempt = 0; ; attempt++) {
      const r = await this.request(method, body, extra);
      if (r.ok) return r.body;
      extra = {};
      if (r.error?.errcode === 'T_LIMIT_EXCEEDED' && attempt < 5 && (r.error.retry_after_ms ?? 0) <= 5000) {
        await new Promise((resolve) => setTimeout(resolve, r.error.retry_after_ms ?? 100));
        continue;
      }
      if (r.error?.errcode === 'T_CHALLENGE_REQUIRED' && attempt < 5) {
        extra = { challenge_response: await solveChallenge(r.error.challenge, this.sessionId ?? this.connectionId) };
        continue;
      }
      throw new Error(`${method} failed: ${JSON.stringify(r.error)}`);
    }
  }
  // Resolve with the first (already received or future) frame matching `pred`.
  next(pred, timeoutMs = this.timeoutMs ?? 2000) {
    const idx = this.frames.findIndex(pred);
    if (idx !== -1) return Promise.resolve(this.frames.splice(idx, 1)[0]);
    return new Promise((resolve, reject) => {
      const t = setTimeout(() => reject(new Error('timed out waiting for frame')), timeoutMs);
      this.waiters.push((f) => {
        if (!pred(f)) return false;
        clearTimeout(t);
        this.frames.splice(this.frames.indexOf(f), 1);
        resolve(f);
        return true;
      });
    });
  }
  // OPAQUE registration and login, as a real client does them.
  register(username, password) { return opaque.register((m, b) => this.call(m, b), this.hello.body.server_name, username, password); }
  login(username, password) { return opaque.login((m, b) => this.call(m, b), this.hello.body.server_name, username, password); }
  reauth(username, password) { return opaque.reauth((m, b) => this.call(m, b), this.hello.body.server_name, username, password); }
  async identify(access_token) {
    this.send({ op: 'identify', body: { access_token } });
    return (await this.next((f) => f.op === 'ready')).body;
  }
  close() { this.ws.close(); return this.closed; }
}

// A Client subclass whose connect() targets a fixed gateway URL.
export function withUrl(url) {
  return class extends Client {
    static connect() { return Client.connectTo(url); }
  };
}