File size: 7,297 Bytes
cce9364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Federation transport and peer-key trust: which signing key a peer's key
// document may use (pinning and chained rotation), event signature checks,
// the keys fetch, request/response connections, and the filters on what a
// peer may answer for. Nothing here holds server state.

import http from 'node:http';
import https from 'node:https';
import { paddedJson } from './padding.js';
import { isPlainObject, redactedForm, unpadded, verifyWith } from './events.js';
import { serverOfUser } from './state-res.js';

const ownEntry = (obj, key) => (isPlainObject(obj) && Object.hasOwn(obj, key) ? obj[key] : undefined);

// The one signing key `doc` may use, given the key pinned for `server` (if
// any). The document must hold exactly one current key, be self-signed by
// it, and that key must be the pinned one or reached from it through signed
// rotation proofs. Throws otherwise (unless trustRotation, an operator opt-in).
export function authorizedPeerKey(server, doc, pinned, { trustRotation = false } = {}) {
  if (!isPlainObject(doc) || doc.server_name !== server) throw new Error(`Keys for ${server} are not validly self-signed`);
  const current = Object.entries(isPlainObject(doc.verify_keys) ? doc.verify_keys : {});
  if (current.length !== 1 || typeof current[0][1]?.key !== 'string') throw new Error(`Keys for ${server} must hold exactly one verify key`);
  const [key_id, { key }] = current[0];
  const { signatures, ...signed } = doc;
  if (!verifyWith(key, signed, ownEntry(ownEntry(signatures, server), key_id))) throw new Error(`Keys for ${server} are not validly self-signed`);
  const next = { key_id, key };
  if (!pinned || (pinned.key_id === key_id && pinned.key === key)) return next;
  const seen = new Set();
  for (let cur = pinned; !seen.has(cur.key_id);) {
    seen.add(cur.key_id);
    const old = ownEntry(doc.old_verify_keys, cur.key_id);
    const rot = old?.rotated_to;
    if (old?.key !== cur.key || typeof rot?.key_id !== 'string' || typeof rot.key !== 'string') break;
    const proof = { server_name: server, old_key_id: cur.key_id, new_key_id: rot.key_id, new_key: rot.key, ts: rot.ts };
    if (!verifyWith(cur.key, proof, rot.sig)) break;
    cur = { key_id: rot.key_id, key: rot.key };
    if (cur.key_id === key_id && cur.key === key) return next;
  }
  if (trustRotation) return next;
  throw new Error(`Key pinning violation for ${server}: signing key changed without rotation proof`);
}

// The ID of the key in `keys` (a checked key document) that signed `ev`, or
// null. An old key counts only for events dated before it expired.
export function verifyEventWithKeys(ev, server, keys, skewMs) {
  const sigs = ownEntry(ev.signatures, server);
  if (!isPlainObject(sigs)) return null;
  const form = redactedForm(ev);
  for (const [id, sig] of Object.entries(sigs)) {
    if (verifyWith(ownEntry(keys.verify_keys, id)?.key, form, sig)) return id;
    const old = ownEntry(keys.old_verify_keys, id);
    if (Number.isSafeInteger(old?.expired_ts) && ev.origin_server_ts <= old.expired_ts + skewMs && verifyWith(old.key, form, sig)) return id;
  }
  return null;
}

// A peer speaks only for its own users, and only for those we asked about.
export function fromPeer(answer, server, asked) {
  const out = {};
  for (const [u, v] of Object.entries(isPlainObject(answer) ? answer : {})) {
    if (serverOfUser(u) === server && Object.hasOwn(asked, u) && isPlainObject(v)) out[u] = v;
  }
  return out;
}

// Claimed one-time keys: also only for the devices we asked about.
export function claimFromPeer(answer, server, asked) {
  const out = {};
  for (const [u, devices] of Object.entries(fromPeer(answer, server, asked))) {
    const wanted = isPlainObject(asked[u]) ? asked[u] : {};
    for (const [d, keys] of Object.entries(devices)) {
      if (Object.hasOwn(wanted, d) && isPlainObject(keys)) (out[u] ??= {})[d] = keys;
    }
  }
  return out;
}

// GET a JSON document: no redirects, a status of 200, at most `maxBytes`,
// within `timeoutMs` overall. `tls` applies when there is no agent (with
// Tor, the SOCKS agent brings its own).
export function getJson(url, { agent, tls = {}, timeoutMs = 15_000, maxBytes = 1_048_576 } = {}) {
  return new Promise((resolve, reject) => {
    // Settles once; on failure the request is torn down without raising more errors.
    const done = (err, value) => { clearTimeout(timer); if (err) { req.destroy(); reject(err); } else resolve(value); };
    const req = (url.protocol === 'https:' ? https : http).get(url, agent ? { agent } : tls, (res) => {
      if (res.statusCode !== 200) { res.resume(); done(new Error(`Key fetch failed with HTTP ${res.statusCode}`)); return; }
      const chunks = [];
      let size = 0;
      res.on('data', (c) => { size += c.length; if (size > maxBytes) { res.destroy(); done(new Error('Key document too large')); } else chunks.push(c); });
      res.on('end', () => { try { done(null, JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch (e) { done(e); } });
      res.on('error', done);
    });
    const timer = setTimeout(() => done(new Error('Key fetch timed out')), timeoutMs);
    req.on('error', done);
  });
}

// Wait for the next JSON frame with a given op on a socket.
export function nextFrame(ws, op, ms = 10_000) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => { cleanup(); reject(new Error(`timed out waiting for ${op}`)); }, ms);
    const onMessage = (data, isBinary) => {
      if (isBinary) return;
      let f;
      try { f = JSON.parse(String(data)); } catch { return; }
      if (f?.op === op) { cleanup(); resolve(f); }
    };
    const onClose = () => { cleanup(); reject(new Error('connection closed during handshake')); };
    const cleanup = () => { clearTimeout(timer); ws.off('message', onMessage); ws.off('close', onClose); };
    ws.on('message', onMessage);
    ws.on('close', onClose);
  });
}

export function channelBinding(socket) {
  try {
    return typeof socket?.exportKeyingMaterial === 'function' ? unpadded(socket.exportKeyingMaterial(32, 'EXPORTER-Channel-Binding')) : '';
  } catch {
    return '';
  }
}

// One authenticated connection: request/response by id. A request that gets
// no answer in `timeoutMs` fails, so nothing waits on a silent peer forever.
export class FedConn {
  constructor(ws, peer, timeoutMs = 30_000) {
    this.ws = ws;
    this.peer = peer;
    this.timeoutMs = timeoutMs;
    this.nextId = 1;
    this.pending = new Map();
  }
  onResponse(frame) {
    const p = this.pending.get(frame?.id);
    if (!p) return;
    this.pending.delete(frame.id);
    if (frame.ok) p.resolve(frame.body);
    else p.reject(new Error(`${frame.error?.errcode}: ${frame.error?.error}`));
  }
  request(method, body) {
    const id = this.nextId++;
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`${method} to ${this.peer} timed out`)); }, this.timeoutMs);
      const done = (fn) => (v) => { clearTimeout(timer); fn(v); };
      this.pending.set(id, { resolve: done(resolve), reject: done(reject) });
      this.ws.send(paddedJson({ op: 'request', id, method, body }));
    });
  }
  fail(err) {
    for (const p of this.pending.values()) p.reject(err);
    this.pending.clear();
  }
}