@dibssoftware/dibs 0.0.0-stage → 0.0.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +577 -0
  2. package/LICENSE +670 -0
  3. package/README.md +234 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +526 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/relay.md +196 -0
  13. package/docs/releasing.md +25 -0
  14. package/docs/scheduling.md +163 -0
  15. package/docs/simulators.md +17 -0
  16. package/package.json +44 -4
  17. package/skills/dibs/SKILL.md +162 -0
  18. package/src/acquire.mjs +697 -0
  19. package/src/admin.mjs +145 -0
  20. package/src/agents.mjs +145 -0
  21. package/src/alerts.mjs +437 -0
  22. package/src/answers.mjs +65 -0
  23. package/src/board.mjs +202 -0
  24. package/src/broker.mjs +369 -0
  25. package/src/commands.mjs +801 -0
  26. package/src/config.mjs +320 -0
  27. package/src/connect.mjs +106 -0
  28. package/src/cool.mjs +160 -0
  29. package/src/diskwarn.mjs +161 -0
  30. package/src/events.mjs +94 -0
  31. package/src/files.mjs +1100 -0
  32. package/src/guard.mjs +583 -0
  33. package/src/history.mjs +247 -0
  34. package/src/hogs.mjs +214 -0
  35. package/src/later.mjs +487 -0
  36. package/src/measure.mjs +262 -0
  37. package/src/nodecheck.mjs +17 -0
  38. package/src/notices.mjs +121 -0
  39. package/src/ondemand.mjs +572 -0
  40. package/src/overlap.mjs +151 -0
  41. package/src/override.mjs +351 -0
  42. package/src/owner.mjs +30 -0
  43. package/src/plain.mjs +467 -0
  44. package/src/platform.mjs +357 -0
  45. package/src/preempt.mjs +438 -0
  46. package/src/primer.mjs +61 -0
  47. package/src/proc.mjs +98 -0
  48. package/src/progress.mjs +158 -0
  49. package/src/qr.mjs +204 -0
  50. package/src/questions.mjs +389 -0
  51. package/src/quota.mjs +81 -0
  52. package/src/reads.mjs +54 -0
  53. package/src/relay.mjs +779 -0
  54. package/src/remote.mjs +584 -0
  55. package/src/reset.mjs +127 -0
  56. package/src/schedule.mjs +995 -0
  57. package/src/scratch.mjs +61 -0
  58. package/src/serve.mjs +736 -0
  59. package/src/service.mjs +221 -0
  60. package/src/shard.mjs +59 -0
  61. package/src/simctl.mjs +42 -0
  62. package/src/simpool.mjs +258 -0
  63. package/src/state.mjs +201 -0
  64. package/src/stats.mjs +328 -0
  65. package/src/style.mjs +44 -0
  66. package/src/talk.mjs +523 -0
  67. package/src/thin.sh +130 -0
  68. package/src/trust.mjs +152 -0
  69. package/src/util.mjs +184 -0
  70. package/src/version.mjs +2 -0
  71. package/src/web.mjs +1117 -0
  72. package/src/worker.mjs +318 -0
package/src/relay.mjs ADDED
@@ -0,0 +1,779 @@
1
+ // dibs relay: the person's dibs page from any browser, a phone included, through
2
+ // a relay that can't read or forge anything. The page at https://app.dibs.cc talks
3
+ // to this Mac over a WebSocket the relay (relay/ in this repo, a Cloudflare Worker)
4
+ // only forwards. Everything between the page and this Mac is end-to-end encrypted
5
+ // and authenticated, so whoever runs the relay sees opaque frames and their sizes.
6
+ //
7
+ // Keys, all made here on first use and kept in relay-keys.json (0600), never sent:
8
+ // identity Ed25519. Signs every session handshake. Browsers pin its fingerprint.
9
+ // relay Ed25519. Proves to the relay that this Mac owns its machine id, which
10
+ // is a hash of this key. It opens no session and decrypts nothing.
11
+ //
12
+ // Pairing: `dibs pair --remote` prints https://app.dibs.cc/#p=<machine id>.<secret>.<fingerprint>.
13
+ // The fragment never reaches a server. The browser makes its own Ed25519 key, and
14
+ // both pairing messages carry an HMAC under a key derived from the 256-bit secret,
15
+ // so only someone holding the link can pair, and the browser checks this Mac's key
16
+ // against the fingerprint, so a relay that swaps keys is caught. One use, ten
17
+ // minutes, spent on success.
18
+ //
19
+ // Sessions: each browser connection runs a fresh X25519 exchange, signed by this
20
+ // Mac's identity key and the device's key over the whole transcript (forward
21
+ // secrecy, mutual authentication). HKDF gives one AES-256-GCM key per direction.
22
+ // Every frame carries a sequence number in its nonce and associated data, and must
23
+ // be exactly the next one: a replayed, dropped, reordered or altered frame closes
24
+ // the session. Frames are padded to fixed sizes so their lengths say little.
25
+ //
26
+ // The protocol, message by message, is written out in docs/relay.md.
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+ import crypto from 'node:crypto';
30
+ import { HOME } from './config.mjs';
31
+ import { die, now, log, sleep, dur } from './util.mjs';
32
+ import { makeAlive, singleInstance } from './proc.mjs';
33
+ import { qr, render } from './qr.mjs';
34
+ import { logChange } from './owner.mjs';
35
+ import { remoteAccess, LOCAL_ONLY_TEXT, lookOnlyText, remoteMcp, MCP_ORIGIN, mcpCodes } from './web.mjs';
36
+
37
+ export const PAGE = process.env.DIBS_RELAY_PAGE || 'https://app.dibs.cc/';
38
+ export const RELAY = process.env.DIBS_RELAY_URL || 'wss://app.dibs.cc';
39
+ const KEYS = path.join(HOME, 'relay-keys.json');
40
+ const FILE = path.join(HOME, 'relay.json');
41
+ const LOCK = path.join(HOME, 'relay.lock');
42
+ export const STATUS = path.join(HOME, 'relay-status.json');
43
+ const PIDFILE = path.join(HOME, 'relay.pid');
44
+
45
+ const MIN = 6e4, HOUR = 36e5;
46
+ // Same as the local codes: long enough to walk to the phone, dead by the time a screenshot leaks.
47
+ const PAIR_LIFE = 10 * MIN;
48
+ // Pending links at once. A new one past this drops the oldest.
49
+ const MAX_PAIRS = 5;
50
+ // Wrong MACs a link takes before it's thrown away. Only someone without the secret sends one.
51
+ const PAIR_FAILS = 3;
52
+ // A session is re-keyed by reconnecting at least this often.
53
+ const SESSION_LIFE = 12 * HOUR;
54
+ // A browser that hasn't finished its handshake by then is dropped.
55
+ const HANDSHAKE_TIME = 20e3;
56
+ // Channels (browser tabs) at once; the relay caps them too.
57
+ const MAX_CHANNELS = 16;
58
+ // A call api() hasn't answered by then gets a 504, so a page never waits forever.
59
+ const CALL_TIME = 30e3;
60
+ // Pings keep the relay's idle timer and NATs happy, and tell a dead connection from a quiet one.
61
+ const PING_EVERY = 25e3;
62
+ const PONG_WAIT = 60e3;
63
+ const BACKOFF_MIN = 1000, BACKOFF_MAX = 60e3;
64
+ // How often relay.json is checked for changes the relay must hear about. A stat and a read; cheap.
65
+ const TOKEN_SYNC = 1000;
66
+ // How often a Mac that belongs to an account looks for its new browsers waiting for the key.
67
+ const APPROVAL_POLL = 3000;
68
+ // Request frames are small; responses carry the board.
69
+ export const MAX_REQUEST = 64 * 1024;
70
+ export const BUCKETS = [1024, 4096, 16384, 65536, 262144, 1048576, 4194304];
71
+ const NAME_MAX = 60;
72
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
73
+
74
+ export const T_HS = 1, T_FRAME = 2;
75
+ const DIR_B2M = 1, DIR_M2B = 2;
76
+
77
+ export const b64u = b => Buffer.from(b).toString('base64url');
78
+ // Strict: only the base64url alphabet, and exactly the length expected, or null.
79
+ export function unb64u(s, len) {
80
+ if (typeof s !== 'string' || !/^[A-Za-z0-9_-]*$/.test(s)) return null;
81
+ const b = Buffer.from(s, 'base64url');
82
+ return b64u(b) === s && (len == null || b.length === len) ? b : null;
83
+ }
84
+ const u32 = n => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };
85
+ const utf8 = s => Buffer.from(String(s), 'utf8');
86
+ // Every field length-prefixed after a label, so no two different transcripts encode the same.
87
+ export const tx = (label, ...fields) => Buffer.concat([label, ...fields].flatMap(f => { const b = Buffer.isBuffer(f) ? f : typeof f === 'string' ? utf8(f) : Buffer.from(f); return [u32(b.length), b]; }));
88
+ const sha = b => crypto.createHash('sha256').update(b).digest();
89
+ const hkdf = (ikm, salt, info, n) => Buffer.from(crypto.hkdfSync('sha256', ikm, salt, utf8(info), n));
90
+ const rawPub = k => Buffer.from(k.export({ format: 'jwk' }).x, 'base64url');
91
+ const okp = (crv, raw) => crypto.createPublicKey({ key: { kty: 'OKP', crv, x: b64u(raw) }, format: 'jwk' });
92
+ export const machineId = relayPub => b64u(sha(Buffer.concat([utf8('dibs-mid-v1\0'), relayPub])).subarray(0, 16));
93
+ export const fingerprint = idPub => b64u(sha(Buffer.concat([utf8('dibs-fp-v1\0'), idPub])));
94
+ export const pairId = secret => hkdf(secret, Buffer.alloc(0), 'dibs-relay-v1 pair id', 16);
95
+ export const pairKey = secret => hkdf(secret, Buffer.alloc(0), 'dibs-relay-v1 pair key', 32);
96
+ // The device's name travels encrypted, and so does its relay token: the relay has no
97
+ // business knowing it's "Safari on iPhone", and must only ever see the token's hash from us.
98
+ export const nameKey = secret => hkdf(secret, Buffer.alloc(0), 'dibs-relay-v1 pair name', 32);
99
+ // What lets a tab into the relay's pairing pool: only someone holding the link can derive it,
100
+ // and the relay holds only its hash, so it can't tell an open link from a closed one by asking.
101
+ export const pairTicket = secret => hkdf(secret, Buffer.alloc(0), 'dibs-relay-v1 pair ticket', 32);
102
+ const NAME_AAD = utf8('dibs-pair-name-v1');
103
+ // 12-byte nonce, then AES-GCM of the name padded to NAME_PAD bytes and the 32-byte relay token, then the tag.
104
+ const NAME_PAD = 64, TOKEN_LEN = 32;
105
+ const BOX_LEN = 12 + NAME_PAD + TOKEN_LEN + 16;
106
+ // What the relay checks a tab's token against (relay/src/index.js tokenHash()).
107
+ export const tokenHash = rt => b64u(sha(Buffer.concat([utf8('dibs-relay-token-v1\0'), rt])).subarray(0, 16));
108
+ // The hashes the relay may hold in the Mac socket's attachment (relay/src/index.js MAX_HASHES).
109
+ const MAX_HASHES = 56;
110
+ // Sign-in codes the relay's index takes from one machine at once (relay/src/index.js MAX_CODES).
111
+ const MAX_CODES = 10;
112
+ function openBox(key, box) {
113
+ if (box.length !== BOX_LEN) return null;
114
+ try {
115
+ const d = crypto.createDecipheriv('aes-256-gcm', key, box.subarray(0, 12));
116
+ d.setAAD(NAME_AAD);
117
+ d.setAuthTag(box.subarray(box.length - 16));
118
+ const p = Buffer.concat([d.update(box.subarray(12, box.length - 16)), d.final()]);
119
+ const names = p.subarray(0, NAME_PAD), n = names.indexOf(0);
120
+ return { name: names.subarray(0, n < 0 ? NAME_PAD : n).toString('utf8'), rt: p.subarray(NAME_PAD) };
121
+ } catch { return null; }
122
+ }
123
+ const hmac = (k, ...parts) => crypto.createHmac('sha256', k).update(Buffer.concat(parts)).digest();
124
+ const sameBytes = (a, b) => a.length === b.length && crypto.timingSafeEqual(a, b);
125
+ const ZERO = Buffer.alloc(32);
126
+
127
+ // The keys: made once, and never replaced by a second process racing the first
128
+ // (link fails if one exists, and then that one is read).
129
+ export function keys() {
130
+ try { return parseKeys(fs.readFileSync(KEYS, 'utf8')); } catch (e) { if (e.code !== 'ENOENT') throw e; }
131
+ fs.mkdirSync(HOME, { recursive: true });
132
+ const pem = () => crypto.generateKeyPairSync('ed25519').privateKey.export({ type: 'pkcs8', format: 'pem' });
133
+ const tmp = `${KEYS}.${process.pid}`;
134
+ fs.writeFileSync(tmp, JSON.stringify({ v: 1, identity: pem(), relay: pem(), created: now() }), { mode: 0o600 });
135
+ try { fs.linkSync(tmp, KEYS); } catch (e) { if (e.code !== 'EEXIST') throw e; }
136
+ fs.rmSync(tmp, { force: true });
137
+ return parseKeys(fs.readFileSync(KEYS, 'utf8'));
138
+ }
139
+ function parseKeys(s) {
140
+ const j = JSON.parse(s);
141
+ const identity = crypto.createPrivateKey(j.identity), relay = crypto.createPrivateKey(j.relay);
142
+ const idPub = rawPub(crypto.createPublicKey(identity)), relayPub = rawPub(crypto.createPublicKey(relay));
143
+ return { identity, relay, idPub, relayPub, mid: machineId(relayPub), fp: fingerprint(idPub) };
144
+ }
145
+
146
+ // relay.json: { devices: {id: {pub, name, created, seen, act}}, pairs: [{pid, key, nk, exp, fails, act}], mcp }
147
+ // mcp: the person turned on remote MCP (dibs relay mcp on). Off unless they did.
148
+ // act: the device may change things (any call but GET). Absent means look only.
149
+ export function load() {
150
+ try {
151
+ const j = JSON.parse(fs.readFileSync(FILE, 'utf8'));
152
+ const obj = k => (j[k] && typeof j[k] === 'object' && !Array.isArray(j[k]) ? j[k] : {});
153
+ return { devices: obj('devices'), pairs: Array.isArray(j.pairs) ? j.pairs : [], mcp: j.mcp === true, accounts: obj('accounts'), approvals: obj('approvals'), pins: obj('pins'), conn: typeof j.conn === 'string' ? j.conn : null };
154
+ } catch { return { devices: {}, pairs: [], mcp: false, accounts: {}, approvals: {}, pins: {}, conn: null }; }
155
+ }
156
+
157
+ // `dibs pair` and the connector both write relay.json; this keeps one from undoing the other.
158
+ function locked(fn) {
159
+ fs.mkdirSync(HOME, { recursive: true });
160
+ const t0 = now();
161
+ for (;;) {
162
+ try { fs.mkdirSync(LOCK); break; } catch (e) {
163
+ if (e.code !== 'EEXIST') throw e;
164
+ try {
165
+ if (now() - fs.statSync(LOCK).mtimeMs > 5000) {
166
+ const aside = `${LOCK}.stale.${process.pid}`;
167
+ fs.renameSync(LOCK, aside);
168
+ fs.rmSync(aside, { recursive: true, force: true });
169
+ }
170
+ } catch {}
171
+ if (now() - t0 > 5000) throw new Error(`${LOCK} stayed locked; remove it if no dibs is running`);
172
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
173
+ }
174
+ }
175
+ try {
176
+ const w = load();
177
+ const out = fn(w);
178
+ w.pairs = w.pairs.filter(p => p.exp > now());
179
+ const tmp = `${FILE}.${process.pid}`;
180
+ fs.writeFileSync(tmp, JSON.stringify(w), { mode: 0o600 });
181
+ fs.renameSync(tmp, FILE);
182
+ return out;
183
+ } finally { fs.rmSync(LOCK, { recursive: true, force: true }); }
184
+ }
185
+
186
+ // A one-time pairing link. The secret is shown once and only its derived pieces are kept.
187
+ // act: the device it pairs may change things, not only look. account: it pairs a dibs account
188
+ // (the page at /account opens it), which may then give this Mac its account key (join, below).
189
+ export function newPairing({ act = false, account = false } = {}) {
190
+ const k = keys();
191
+ const secret = crypto.randomBytes(32);
192
+ locked(w => {
193
+ w.pairs.push({ pid: b64u(pairId(secret)), key: b64u(pairKey(secret)), nk: b64u(nameKey(secret)), th: tokenHash(pairTicket(secret)), exp: now() + PAIR_LIFE, fails: 0, ...(act ? { act: true } : {}), ...(account ? { acct: true } : {}) });
194
+ w.pairs = w.pairs.slice(-MAX_PAIRS);
195
+ });
196
+ const frag = `${k.mid}.${b64u(secret)}.${k.fp}`;
197
+ return { link: account ? `${PAGE}account#join=${frag}` : `${PAGE}#p=${frag}`, mid: k.mid, fp: k.fp, life: PAIR_LIFE, exp: now() + PAIR_LIFE, act };
198
+ }
199
+
200
+ export const devices = () => Object.entries(load().devices).map(([id, d]) => ({ id, ...d }));
201
+
202
+ // Removes every device whose id starts with `which` (or all). Live sessions end on their next frame.
203
+ export function revoke(which) {
204
+ return locked(w => {
205
+ let n = 0;
206
+ for (const id of Object.keys(w.devices)) if (which === 'all' || id.startsWith(which)) { delete w.devices[id]; n++; }
207
+ if (which === 'all') w.pairs = [];
208
+ return n;
209
+ });
210
+ }
211
+
212
+ // No control or format characters: a name with a bidi override could pass for another
213
+ // device's in dibs pair --list, and a line break for another line in the history.
214
+ const cleanName = s => (typeof s === 'string' ? s.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, NAME_MAX) : '') || 'a browser';
215
+
216
+ // Padding: a 4-byte length, the JSON, zeros up to the next bucket.
217
+ export function pad(obj, max = BUCKETS.at(-1)) {
218
+ const j = utf8(JSON.stringify(obj));
219
+ const size = BUCKETS.find(b => b >= j.length + 4);
220
+ if (!size || size > max) return null;
221
+ const out = Buffer.alloc(size);
222
+ out.writeUInt32BE(j.length);
223
+ j.copy(out, 4);
224
+ return out;
225
+ }
226
+ export function unpad(b) {
227
+ if (b.length < 4 || !BUCKETS.includes(b.length)) return null;
228
+ const n = b.readUInt32BE(0);
229
+ if (n > b.length - 4) return null;
230
+ try { return JSON.parse(b.subarray(4, 4 + n).toString('utf8')); } catch { return null; }
231
+ }
232
+
233
+ const nonce = seq => { const n = Buffer.alloc(12); n.writeBigUInt64BE(BigInt(seq), 4); return n; };
234
+ const frameAad = (sid, dir, head) => Buffer.concat([utf8('dibs-frame-v1'), sid, Buffer.from([dir]), head]);
235
+ export function seal(key, sid, dir, seq, plain) {
236
+ const head = Buffer.alloc(9);
237
+ head[0] = T_FRAME;
238
+ head.writeBigUInt64BE(BigInt(seq), 1);
239
+ const c = crypto.createCipheriv('aes-256-gcm', key, nonce(seq));
240
+ c.setAAD(frameAad(sid, dir, head));
241
+ const body = Buffer.concat([c.update(plain), c.final()]);
242
+ return Buffer.concat([head, body, c.getAuthTag()]);
243
+ }
244
+ // The plaintext, or null for anything that isn't exactly frame `seq` under this key.
245
+ export function open(key, sid, dir, seq, buf) {
246
+ if (buf.length < 9 + 16 || buf[0] !== T_FRAME) return null;
247
+ const head = buf.subarray(0, 9);
248
+ if (head.readBigUInt64BE(1) !== BigInt(seq)) return null;
249
+ try {
250
+ const d = crypto.createDecipheriv('aes-256-gcm', key, nonce(seq));
251
+ d.setAAD(frameAad(sid, dir, head));
252
+ d.setAuthTag(buf.subarray(buf.length - 16));
253
+ return Buffer.concat([d.update(buf.subarray(9, buf.length - 16)), d.final()]);
254
+ } catch { return null; }
255
+ }
256
+ const hs = obj => Buffer.concat([Buffer.from([T_HS]), utf8(JSON.stringify(obj))]);
257
+
258
+ // Joining an account: its id, the secret this Mac shows the relay to see the account's
259
+ // waiting browsers (the relay keeps only its hash), and the account key itself. Kept in
260
+ // relay.json (0600), never sent anywhere but sealed to a browser the person approves.
261
+ const B64_32 = /^[A-Za-z0-9_-]{43}$/, B64_16 = /^[A-Za-z0-9_-]{22}$/;
262
+ function joinAccount(dev, did, b) {
263
+ if (!dev.acct) return { status: 403, json: { error: 'Only a dibs account paired with dibs connect --account can join this Mac to it.' } };
264
+ if (!b || !B64_16.test(b.aid) || !B64_32.test(b.secret) || !B64_32.test(b.ak)) return { status: 400, json: { error: 'bad account' } };
265
+ locked(w => { w.accounts = { ...w.accounts, [b.aid]: { secret: b.secret, ak: b.ak, device: did, joined: now(), label: cleanName(b.label) } }; });
266
+ logChange('account join', { account: b.aid.slice(0, 8) });
267
+ return { status: 200, json: { ok: true } };
268
+ }
269
+
270
+ // Handing the account key to a new browser of that account, in the four steps the relay's
271
+ // mailbox carries (relay/src/accountbook.js): the browser's commitment, this Mac's ephemeral
272
+ // key, the browser's reveal, then the 6-digit code both show. Only when the person types that
273
+ // code here (dibs connect --approve <code>) does the key go, sealed to the shared secret, and
274
+ // the browser opens it only once the person types the second code this Mac then prints.
275
+ //
276
+ // Everything in the relay's list is the relay's word, so this Mac pins what it saw first: the
277
+ // commitment, the label and its own deadline, with its key, in round 1. A later list that
278
+ // changes the commitment is refused, and no request gets a second key: otherwise a relay could
279
+ // see this Mac's key, then grind one of its own until the code matched the person's. The keys
280
+ // live in this connection's memory, but which ids were pinned is kept in relay.json until their
281
+ // deadline, so dropping this Mac's socket doesn't start a request over: a relay that did could
282
+ // replay an approved id with keys of its own. An approval also records the keys its codes came
283
+ // from, and the account key is sealed only to those.
284
+ export const commitOf = (B, n) => b64u(sha(Buffer.concat([utf8('dibs-approve-commit-v1\0'), B, n])));
285
+ const sixDigits = b => String(b.readUInt32BE(0) % 1e6).padStart(6, '0');
286
+ export function approvalKeys(ss, aid, id, B, M) {
287
+ const salt = sha(tx('dibs-approve-v1', aid, id, B, M));
288
+ const key = hkdf(ss, salt, 'dibs-approve-v1 key', 32);
289
+ return { key, sas: sixDigits(hkdf(ss, salt, 'dibs-approve-v1 sas', 4)), confirm: sixDigits(hkdf(ss, salt, 'dibs-approve-v1 confirm', 4)) };
290
+ }
291
+ // Browsers of one account that may wait on this Mac at once (the relay keeps at most as many),
292
+ // and how long one may: this Mac's clock, never the relay's expires.
293
+ export const MAX_WAITING = 5;
294
+ const APPROVAL_LIFE = 10 * MIN;
295
+ const APPROVAL_ID = /^[A-Za-z0-9_-]{12}$/;
296
+ export function sealFor(key, aid, id, ak) {
297
+ const iv = crypto.randomBytes(12);
298
+ const c = crypto.createCipheriv('aes-256-gcm', key, iv);
299
+ c.setAAD(utf8(`dibs-approve-v1 ${aid}.${id}`));
300
+ return b64u(Buffer.concat([iv, c.update(ak), c.final(), c.getAuthTag()]));
301
+ }
302
+ // One round for one account, given the mailbox's pending list: what to send back.
303
+ // eph: this connection's pins, by request id. A pin outlives its answer until its deadline,
304
+ // so a request can't start over with a new key from this Mac.
305
+ export function approvalStep(aid, list, eph, t = now()) {
306
+ const out = [];
307
+ const acct = load().accounts[aid];
308
+ if (!acct) return out;
309
+ for (const [id, pin] of eph) if (pin.exp <= t) eph.delete(id);
310
+ const done = (p, pin, step) => { pin.done = true; out.push({ id: p.id, step }); };
311
+ // Round 1 for a new id, recorded in relay.json first: once per id, and at most MAX_WAITING per
312
+ // account until their deadlines, whatever happens to this connection.
313
+ const pinNew = p => locked(w => {
314
+ for (const [id, x] of Object.entries(w.pins)) if (x.exp <= t) delete w.pins[id];
315
+ if (w.pins[p.id] || w.approvals[p.id]) return false;
316
+ if (Object.values(w.pins).filter(x => x.aid === aid).length >= MAX_WAITING) return false;
317
+ w.pins = { ...w.pins, [p.id]: { aid, exp: t + APPROVAL_LIFE, ...(eph.conn && { conn: eph.conn }) } };
318
+ return true;
319
+ });
320
+ for (const p of Array.isArray(list) ? list : []) {
321
+ if (!p || typeof p.id !== 'string' || !APPROVAL_ID.test(p.id)) continue;
322
+ const pin = eph.get(p.id);
323
+ if (!pin) {
324
+ // Refused on an earlier connection (dibs connect --approve found it stale): tell the browser.
325
+ const old = load().approvals[p.id];
326
+ if (old?.refused && old.aid === aid) {
327
+ out.push({ id: p.id, step: { refuse: true } });
328
+ locked(w => { delete w.approvals[p.id]; });
329
+ continue;
330
+ }
331
+ // Round 1, once per request: a fresh one (no key on it yet), while there's room.
332
+ if (p.mac || typeof p.commit !== 'string' || !B64_32.test(p.commit)) continue;
333
+ if (!pinNew(p)) continue;
334
+ const e = crypto.generateKeyPairSync('x25519');
335
+ eph.set(p.id, { aid, e, commit: p.commit, label: cleanName(p.label), exp: t + APPROVAL_LIFE });
336
+ out.push({ id: p.id, step: { mac: b64u(rawPub(e.publicKey)) } });
337
+ continue;
338
+ }
339
+ if (pin.done || pin.aid !== aid || !p.pub || !p.nonce) continue;
340
+ const B = unb64u(p.pub, 32), n = unb64u(p.nonce, 32), M = rawPub(pin.e.publicKey);
341
+ if (!B || !n || p.mac !== b64u(M) || p.commit !== pin.commit || commitOf(B, n) !== pin.commit) { done(p, pin, { refuse: true }); continue; }
342
+ let ss;
343
+ try { ss = crypto.diffieHellman({ privateKey: pin.e.privateKey, publicKey: okp('X25519', B) }); } catch { done(p, pin, { refuse: true }); continue; }
344
+ if (sameBytes(ss, ZERO)) { done(p, pin, { refuse: true }); continue; }
345
+ const { key, sas, confirm } = approvalKeys(ss, aid, p.id, B, M);
346
+ const keys = b64u(sha(tx('dibs-approve-keys-v1', aid, p.id, B, M)));
347
+ const ap = load().approvals[p.id];
348
+ if (ap && (ap.aid !== aid || ap.keys !== keys)) {
349
+ done(p, pin, { refuse: true });
350
+ locked(w => { delete w.approvals[p.id]; });
351
+ } else if (ap?.approved) {
352
+ done(p, pin, { sealed: sealFor(key, aid, p.id, unb64u(acct.ak, 32)) });
353
+ locked(w => { delete w.approvals[p.id]; });
354
+ } else if (ap?.refused) {
355
+ done(p, pin, { refuse: true });
356
+ locked(w => { delete w.approvals[p.id]; });
357
+ } else if (!ap) {
358
+ locked(w => {
359
+ for (const [id, a] of Object.entries(w.approvals)) if (a.exp <= t) delete w.approvals[id];
360
+ w.approvals = { ...w.approvals, [p.id]: { aid, label: pin.label, sas, confirm, keys, exp: pin.exp, ...(eph.conn && { conn: eph.conn }) } };
361
+ });
362
+ }
363
+ }
364
+ return out;
365
+ }
366
+ // dibs connect --approve <code>: the code the new browser shows. Returns what was approved, with
367
+ // the code to type back into that browser; { ambiguous } when more than one browser shows it,
368
+ // which only a go-between guessing codes makes likely: those are all refused.
369
+ export function approve(code, t = now()) {
370
+ return locked(w => {
371
+ for (const [id, a] of Object.entries(w.approvals)) if (a.exp <= t) delete w.approvals[id];
372
+ const hits = Object.entries(w.approvals).filter(([, a]) => a.sas === code && !a.approved && !a.refused);
373
+ if (!hits.length) return null;
374
+ if (hits.length > 1) { for (const [, a] of hits) a.refused = true; return { ambiguous: hits.length }; }
375
+ // Pinned on a connection that's gone: the key that would seal is gone with it, so this one
376
+ // can never be sent. Refused, so the browser hears so, and the person asks again.
377
+ const [id, a] = hits[0];
378
+ if (a.conn && a.conn !== w.conn) { a.refused = true; return { id, ...a, stale: true }; }
379
+ a.approved = true;
380
+ return { id, ...a };
381
+ });
382
+ }
383
+ // dibs connect --refuse <id>: no to one waiting browser. The browser hears it on the next round.
384
+ export function refuseApproval(id, t = now()) {
385
+ return locked(w => {
386
+ const a = w.approvals[id];
387
+ if (!a || a.exp <= t || a.approved || a.refused) return null;
388
+ a.refused = true;
389
+ return { id, ...a };
390
+ });
391
+ }
392
+ export const waitingApprovals = (t = now()) => Object.entries(load().approvals).filter(([, a]) => a.exp > t && !a.approved && !a.refused).map(([id, a]) => ({ id, ...a }));
393
+ export function removeAccount(which) {
394
+ return locked(w => {
395
+ let n = 0;
396
+ for (const [aid, a] of Object.entries(w.accounts)) if (which === 'all' || aid.startsWith(which)) {
397
+ delete w.accounts[aid];
398
+ if (a.device) delete w.devices[a.device];
399
+ n++;
400
+ }
401
+ return n;
402
+ });
403
+ }
404
+
405
+ // The Mac's half of the protocol, for every channel (one per browser tab) the relay
406
+ // opens. No sockets in here: `send(ch, bytes)` and `kick(ch, why)` go to the relay,
407
+ // and `call({method, path, body, session})` is src/web.mjs's api().
408
+ // admit(ch, hash): tell the relay a pairing tab is now a paired one (after its token's hash is registered).
409
+ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock = now }) {
410
+ const chans = new Map();
411
+ const drop = (ch, why) => { clearTimeout(chans.get(ch)?.timer); chans.delete(ch); kick(ch, why); };
412
+ // Errors before a session exists are unauthenticated hints for the page, nothing more.
413
+ const refuse = (ch, code) => { send(ch, hs({ t: 'err', code })); drop(ch, code); };
414
+
415
+ function opened(ch) {
416
+ if (chans.size >= MAX_CHANNELS) {
417
+ const oldest = [...chans.keys()][0];
418
+ drop(oldest, 'too many tabs');
419
+ }
420
+ const timer = setTimeout(() => chans.get(ch)?.stage !== 'ready' && drop(ch, 'handshake took too long'), HANDSHAKE_TIME);
421
+ timer.unref?.();
422
+ chans.set(ch, { stage: 'new', at: clock(), timer });
423
+ }
424
+
425
+ function pair1(ch, m) {
426
+ const pid = unb64u(m.pid, 16), d = unb64u(m.d, 32), nb = unb64u(m.nb, 32), sig = unb64u(m.sig, 64), mac = unb64u(m.mac, 32), box = unb64u(m.name, BOX_LEN);
427
+ if (!pid || !d || !nb || !sig || !mac || !box) return refuse(ch, 'bad-pair');
428
+ const t1 = tx('dibs-pair1-v1', k.mid, pid, d, nb, box);
429
+ let name, rth;
430
+ // Look up, check and spend under one lock, so a link can't pair twice.
431
+ const r = locked(w => {
432
+ const p = w.pairs.find(x => x.pid === b64u(pid) && x.exp > clock());
433
+ if (!p) return { err: 'pair-expired' };
434
+ if (!sameBytes(hmac(unb64u(p.key, 32), t1, sig), mac)) {
435
+ if (++p.fails >= PAIR_FAILS) w.pairs = w.pairs.filter(x => x !== p);
436
+ return { err: 'bad-pair' };
437
+ }
438
+ let devKey;
439
+ try { devKey = okp('Ed25519', d); } catch { return { err: 'bad-pair' }; }
440
+ if (!crypto.verify(null, t1, devKey, sig)) return { err: 'bad-pair' };
441
+ const opened = openBox(unb64u(p.nk, 32), box);
442
+ if (!opened) return { err: 'bad-pair' };
443
+ name = cleanName(opened.name);
444
+ rth = tokenHash(opened.rt);
445
+ w.pairs = w.pairs.filter(x => x !== p);
446
+ const did = b64u(crypto.randomBytes(16));
447
+ w.devices[did] = { pub: b64u(d), name, rth, created: clock(), ...(p.act === true ? { act: true } : {}), ...(p.acct === true ? { acct: true } : {}) };
448
+ return { did, key: unb64u(p.key, 32) };
449
+ });
450
+ if (r.err) return refuse(ch, r.err);
451
+ const nm = crypto.randomBytes(32);
452
+ const t2 = tx('dibs-pair2-v1', k.mid, pid, d, nb, box, k.idPub, nm, utf8(r.did));
453
+ const s2 = crypto.sign(null, t2, k.identity);
454
+ send(ch, hs({ t: 'pair2', m: b64u(k.idPub), nm: b64u(nm), did: r.did, sig: b64u(s2), mac: b64u(hmac(r.key, t2, s2)) }));
455
+ // The relay lets this tab stay once it knows the new token's hash.
456
+ admit(ch, rth);
457
+ log(`relay: paired ${name} (${r.did.slice(0, 8)})`);
458
+ }
459
+
460
+ function hello1(ch, c, m) {
461
+ const eb = unb64u(m.eb, 32), nb = unb64u(m.nb, 32);
462
+ const ds = load().devices;
463
+ const dev = typeof m.did === 'string' && Object.hasOwn(ds, m.did) ? ds[m.did] : null;
464
+ if (!eb || !nb) return refuse(ch, 'bad-hello');
465
+ if (!dev) return refuse(ch, 'unpaired');
466
+ const D = unb64u(dev.pub, 32);
467
+ const eph = crypto.generateKeyPairSync('x25519');
468
+ const em = rawPub(eph.publicKey), nm = crypto.randomBytes(32);
469
+ let ss;
470
+ try { ss = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: okp('X25519', eb) }); } catch { return refuse(ch, 'bad-hello'); }
471
+ // A low-order point gives all zeros: an attacker's attempt to fix the secret.
472
+ if (sameBytes(ss, ZERO)) return refuse(ch, 'bad-hello');
473
+ const th = tx('dibs-hs-v1', k.mid, utf8(m.did), D, eb, nb, k.idPub, em, nm);
474
+ const sigM = crypto.sign(null, tx('dibs-hs2-v1', th), k.identity);
475
+ Object.assign(c, { stage: 'hello', did: m.did, D, ss, th, sigM });
476
+ send(ch, hs({ t: 'hello2', em: b64u(em), nm: b64u(nm), sig: b64u(sigM) }));
477
+ }
478
+
479
+ function hello3(ch, c, m) {
480
+ const sigD = unb64u(m.sig, 64);
481
+ if (!sigD || !crypto.verify(null, tx('dibs-hs3-v1', c.th, c.sigM), okp('Ed25519', c.D), sigD)) return drop(ch, 'device signature failed');
482
+ // Revoked between hello1 and now: no session.
483
+ if (load().devices[c.did]?.pub !== b64u(c.D)) return drop(ch, 'unpaired');
484
+ const salt = sha(tx('dibs-hs-keys-v1', c.th, c.sigM, sigD));
485
+ Object.assign(c, {
486
+ stage: 'ready', kIn: hkdf(c.ss, salt, 'dibs-relay-v1 key b2m', 32), kOut: hkdf(c.ss, salt, 'dibs-relay-v1 key m2b', 32),
487
+ sid: hkdf(c.ss, salt, 'dibs-relay-v1 sid', 32), seqIn: 0, seqOut: 0, began: clock(), ss: null, th: null,
488
+ });
489
+ try { locked(w => { if (w.devices[c.did]) w.devices[c.did].seen = clock(); }); } catch {}
490
+ // Key confirmation: the page waits for this before it sends a call.
491
+ out(ch, c, { t: 'ready' });
492
+ }
493
+
494
+ function out(ch, c, obj) {
495
+ const p = pad(obj) || pad({ t: 'res', id: obj.id, status: 500, json: { error: 'the answer was too big to send through the relay' } });
496
+ send(ch, seal(c.kOut, c.sid, DIR_M2B, c.seqOut++, p));
497
+ }
498
+
499
+ async function frame(ch, c, buf) {
500
+ if (buf.length > 9 + MAX_REQUEST + 16) return drop(ch, 'request frame too big');
501
+ const p = open(c.kIn, c.sid, DIR_B2M, c.seqIn, buf);
502
+ if (!p || p.length > MAX_REQUEST) return drop(ch, 'a frame failed to decrypt, or came out of order');
503
+ c.seqIn++;
504
+ const m = unpad(p);
505
+ if (!m || m.t !== 'req' || !Number.isSafeInteger(m.id)) return drop(ch, 'malformed request');
506
+ if (clock() - c.began > SESSION_LIFE) return drop(ch, 'session too old; reconnecting makes new keys');
507
+ const dev = load().devices[c.did];
508
+ if (!dev || dev.pub !== b64u(c.D)) return drop(ch, 'unpaired');
509
+ let res;
510
+ // The route as api() will see it (src/web.mjs parses it the same way), so /api/x/../hook is /api/hook here too.
511
+ let route = null;
512
+ try { if (typeof m.path === 'string' && m.path.startsWith('/api/') && m.path.length <= 512) route = new URL(m.path, 'http://dibs').pathname; } catch {}
513
+ const refused = route && remoteAccess(m.method, route, dev.act === true);
514
+ // An account paired through dibs connect --account gives this Mac its account key, so it can
515
+ // hand that key on to the account's new browsers (approve, below). Only such a device may.
516
+ if (route === '/api/account/join' && m.method === 'POST') res = joinAccount(dev, c.did, m.body);
517
+ else if (!METHODS.includes(m.method) || !route?.startsWith('/api/')) res = { status: 400, json: { error: 'not an API call' } };
518
+ else if (refused) res = { status: 403, json: { error: refused === 'look' ? lookOnlyText(c.did) : LOCAL_ONLY_TEXT } };
519
+ else {
520
+ let timer;
521
+ try {
522
+ res = await Promise.race([
523
+ call({ method: m.method, path: m.path, body: m.body ?? null, session: { kind: 'remote', device: c.did, name: dev.name, act: dev.act === true } }),
524
+ new Promise(r => { timer = setTimeout(() => r({ status: 504, json: { error: 'dibs took too long to answer' } }), CALL_TIME); }),
525
+ ]);
526
+ } catch (e) { res = { status: e.status || 500, json: { error: e.status ? e.message : 'dibs hit a bug answering that' } }; }
527
+ clearTimeout(timer);
528
+ }
529
+ // The channel may have closed while api() worked.
530
+ if (chans.get(ch) === c) out(ch, c, { t: 'res', id: m.id, status: res.status, json: res.json ?? null });
531
+ }
532
+
533
+ function data(ch, buf) {
534
+ const c = chans.get(ch);
535
+ if (!c) return;
536
+ if (buf[0] === T_FRAME) return c.stage === 'ready' ? frame(ch, c, buf) : drop(ch, 'frame before handshake');
537
+ if (buf[0] !== T_HS || buf.length > 8192) return drop(ch, 'malformed');
538
+ let m;
539
+ try { m = JSON.parse(buf.subarray(1).toString('utf8')); } catch { return drop(ch, 'malformed'); }
540
+ if (c.stage === 'new' && m?.t === 'pair1') { c.stage = 'paired'; return pair1(ch, m); }
541
+ if ((c.stage === 'new' || c.stage === 'paired') && m?.t === 'hello1') return hello1(ch, c, m);
542
+ if (c.stage === 'hello' && m?.t === 'hello3') return hello3(ch, c, m);
543
+ drop(ch, 'unexpected handshake message');
544
+ }
545
+
546
+ return {
547
+ open: opened,
548
+ data,
549
+ gone: ch => { clearTimeout(chans.get(ch)?.timer); chans.delete(ch); },
550
+ // After a revoke: sessions of devices no longer paired end now, not on their next call.
551
+ sweep() { const d = load().devices; for (const [ch, c] of chans) if (c.did && d[c.did]?.pub !== b64u(c.D)) drop(ch, 'unpaired'); },
552
+ closeAll() { for (const ch of [...chans.keys()]) drop(ch, 'Mac going offline'); },
553
+ get size() { return chans.size; },
554
+ };
555
+ }
556
+
557
+ // What the relay needs to know whom to let in: the hashes of paired browsers' relay tokens
558
+ // (the newest MAX_HASHES), the hashes of open links' pairing tickets, and, while remote MCP
559
+ // is on, the index hashes of live sign-in codes, so https://mcp.dibs.cc can route a code here.
560
+ export function relayTokens(w = load(), t = now()) {
561
+ const h = Object.values(w.devices).filter(d => typeof d.rth === 'string').sort((a, b) => (b.seen || b.created) - (a.seen || a.created)).slice(0, MAX_HASHES).map(d => d.rth);
562
+ return { t: 'tokens', h, p: w.pairs.filter(p => p.exp > t && typeof p.th === 'string').map(p => p.th), c: w.mcp ? mcpCodes().slice(-MAX_CODES) : [] };
563
+ }
564
+
565
+ function status(state, extra = {}) {
566
+ try {
567
+ const tmp = `${STATUS}.${process.pid}`;
568
+ fs.writeFileSync(tmp, JSON.stringify({ state, since: now(), pid: process.pid, ...extra }));
569
+ fs.renameSync(tmp, STATUS);
570
+ } catch {}
571
+ }
572
+
573
+ // One line for `dibs service status relay`.
574
+ export function statusLine() {
575
+ try {
576
+ const s = JSON.parse(fs.readFileSync(STATUS, 'utf8'));
577
+ if (!makeAlive([s.pid])(s.pid)) return 'not running';
578
+ return `${s.state} ${dur(now() - s.since)}${s.state === 'connected' ? ` to ${s.url}` : s.error ? ` (${s.error})` : ''}, ${devices().length} device${devices().length === 1 ? '' : 's'} paired, ${mcpLine()}`;
579
+ } catch { return null; }
580
+ }
581
+ // The one to give an MCP client. https://mcp.dibs.cc/<machine id>/mcp works too.
582
+ const mcpUrl = () => `${MCP_ORIGIN}/mcp`;
583
+ const mcpLine = () => (load().mcp ? `remote MCP on at ${mcpUrl()}` : 'remote MCP off (dibs relay mcp on)');
584
+
585
+ // What a forwarded MCP request may carry in, and its answer out. Nothing else crosses.
586
+ const MCP_IN = ['content-type', 'authorization', 'origin', 'accept', 'mcp-protocol-version'];
587
+ const MCP_OUT = ['Content-Type', 'WWW-Authenticate', 'Allow'];
588
+ const MCP_BODY_MAX = 64 * 1024;
589
+ // The whole http-res message, after JSON: under the relay's 4 MiB socket limit with room to
590
+ // spare, so a big answer is a 502 for that request, never a closed connection for everyone.
591
+ const MCP_ANSWER_MAX = 3.5 * 1024 * 1024;
592
+ // The message carrying an answer back, or a 502 in its place when it would be too big to send.
593
+ export function httpRes(id, r) {
594
+ const msg = JSON.stringify({ t: 'http-res', id, ...r });
595
+ return Buffer.byteLength(msg) > MCP_ANSWER_MAX ? JSON.stringify({ t: 'http-res', id, ...offJson(502) }) : msg;
596
+ }
597
+ const offJson = status => ({ status, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'not here' }) });
598
+
599
+ // One request the relay forwarded from mcp.dibs.cc: answered by src/web.mjs's own MCP and
600
+ // sign-in, only while the person has remote MCP on, read fresh each time so `off` is immediate.
601
+ const mcpHandles = {};
602
+ export async function mcpAnswer(m, k = keys()) {
603
+ if (!load().mcp) return offJson(404);
604
+ if (!['GET', 'POST'].includes(m.method) || typeof m.path !== 'string' || !m.path.startsWith('/') || m.path.length > 2048) return offJson(400);
605
+ const body = typeof m.body === 'string' ? m.body : '';
606
+ if (Buffer.byteLength(body) > MCP_BODY_MAX) return offJson(413);
607
+ const headers = {};
608
+ for (const h of MCP_IN) if (typeof m.headers?.[h] === 'string' && m.headers[h].length <= 4096) headers[h] = m.headers[h];
609
+ // bare: sent to https://mcp.dibs.cc itself and routed here by code or token tag.
610
+ const bare = m.bare === true;
611
+ mcpHandles[bare] ||= remoteMcp(k.mid, MCP_ORIGIN, bare);
612
+ const ip = typeof m.ip === 'string' ? m.ip.slice(0, 64) : 'unknown';
613
+ const r = await mcpHandles[bare]({ method: m.method, path: m.path, headers, body, ip });
614
+ const out = {};
615
+ for (const h of MCP_OUT) if (r.headers[h] != null) out[h] = String(r.headers[h]);
616
+ return { status: r.status, headers: out, body: r.body };
617
+ }
618
+
619
+ function relayUrl(u) {
620
+ let x;
621
+ try { x = new URL(u); } catch { die(`${u} isn't a URL. dibs relay [--url wss://app.dibs.cc]`); }
622
+ // ws:// only to this machine (the local test relay): elsewhere the relay's own
623
+ // authentication would travel in the clear. The frames are end-to-end encrypted either way.
624
+ const local = ['127.0.0.1', 'localhost', '[::1]'].includes(x.hostname);
625
+ if (!(x.protocol === 'wss:' || (x.protocol === 'ws:' && local))) die(`the relay has to be wss:// (ws:// only on this machine), not ${u}`);
626
+ return x;
627
+ }
628
+
629
+ // dibs relay [--url wss://app.dibs.cc]: keeps one outbound connection to the relay
630
+ // up, with backoff. Off until the person turns it on (dibs service install relay).
631
+ export async function relay(args) {
632
+ // dibs relay mcp on|off: whether MCP clients may reach this Mac through mcp.dibs.cc.
633
+ if (args[0] === 'mcp') {
634
+ if (args[1] !== 'on' && args[1] !== 'off') return console.log(`${mcpLine()}. dibs relay mcp on|off`);
635
+ const on = args[1] === 'on';
636
+ locked(w => { w.mcp = on; });
637
+ logChange('relay mcp', { on });
638
+ if (!on) return console.log('Remote MCP is off: requests through mcp.dibs.cc get 404. Clients signed in through it stay listed in dibs pair --list until you revoke them.');
639
+ return console.log(`Remote MCP is on. Add ${mcpUrl()} as a connector in Claude (or any MCP client) and sign in with a code from dibs pair (12 characters while remote MCP is on).\nThe relay carries this traffic decrypted (TLS ends at Cloudflare), unlike the page. It stays read-only. Turn it off: dibs relay mcp off`);
640
+ }
641
+ let url = RELAY;
642
+ for (let i = 0; i < args.length; i++) {
643
+ if (args[i] === '--url') url = args[++i] || die('--url needs the relay address');
644
+ else die(`unknown ${args[i]}. dibs relay [--url ${RELAY}]`);
645
+ }
646
+ const base = relayUrl(url);
647
+ await singleInstance(PIDFILE, 'dibs relay is already running');
648
+ const k = keys();
649
+ const { api } = await import('./web.mjs');
650
+ log(`dibs relay: machine ${k.mid}, fingerprint ${k.fp.slice(0, 16)}...; pair a browser with dibs pair --remote`);
651
+ let wait = BACKOFF_MIN;
652
+ for (;;) {
653
+ const began = now();
654
+ const why = await connectOnce(base, k, api);
655
+ // A connection that held a while starts the backoff over.
656
+ if (now() - began > BACKOFF_MAX) wait = BACKOFF_MIN;
657
+ status('reconnecting', { url: base.origin, error: why });
658
+ log(`relay: ${why}; trying again in ${dur(wait)}`);
659
+ await sleep(wait * (0.75 + Math.random() / 2));
660
+ wait = Math.min(wait * 2, BACKOFF_MAX);
661
+ }
662
+ }
663
+
664
+ // One connection, until it drops. Resolves with why.
665
+ export function connectOnce(base, k, call) {
666
+ return new Promise(resolve => {
667
+ const url = new URL(`/ws/m/${k.mid}`, base);
668
+ status('connecting', { url: base.origin });
669
+ let ws;
670
+ try { ws = new WebSocket(url); } catch (e) { return resolve(e.message); }
671
+ ws.binaryType = 'arraybuffer';
672
+ let authed = false, lastHeard = now(), done = false, sentTokens = '';
673
+ const finish = why => { if (done) return; done = true; clearInterval(beat); clearInterval(watch); clearInterval(approvals); peer.closeAll(); try { ws.close(); } catch {} resolve(why); };
674
+ // The relay's list of who may connect follows relay.json within a second: a new link opens
675
+ // the pairing pool, a pairing adds a hash, a revoke removes one (and its open sessions end).
676
+ const syncTokens = () => {
677
+ if (!authed || ws.readyState !== 1) return;
678
+ const t = JSON.stringify(relayTokens());
679
+ if (t === sentTokens) return;
680
+ sentTokens = t;
681
+ ws.send(t);
682
+ peer.sweep();
683
+ };
684
+ const watch = setInterval(syncTokens, TOKEN_SYNC);
685
+ // Browsers of this Mac's accounts waiting for its key: asked for every few seconds, only
686
+ // while this Mac belongs to an account.
687
+ // eph.conn names this connection in relay.json, so dibs connect --approve can tell when the
688
+ // key a request was pinned with went with an earlier one (a restart, a dropped socket).
689
+ const eph = Object.assign(new Map(), { conn: b64u(crypto.randomBytes(9)) });
690
+ locked(w => { w.conn = eph.conn; });
691
+ const askApprovals = () => {
692
+ if (!authed || ws.readyState !== 1) return;
693
+ for (const [aid, a] of Object.entries(load().accounts)) ws.send(JSON.stringify({ t: 'acct-pending', aid, secret: a.secret, ref: aid }));
694
+ };
695
+ const approvals = setInterval(askApprovals, APPROVAL_POLL);
696
+ const peer = macPeer({
697
+ k, call,
698
+ send: (ch, buf) => ws.readyState === 1 && ws.send(Buffer.concat([Buffer.from(ch, 'base64url'), buf])),
699
+ kick: ch => ws.readyState === 1 && ws.send(JSON.stringify({ t: 'kick', ch })),
700
+ admit: (ch, h) => { syncTokens(); if (ws.readyState === 1) ws.send(JSON.stringify({ t: 'admit', ch, h })); },
701
+ });
702
+ const beat = setInterval(() => {
703
+ if (now() - lastHeard > PONG_WAIT) return finish('the relay stopped answering');
704
+ if (ws.readyState === 1) ws.send('{"t":"ping"}');
705
+ }, PING_EVERY);
706
+ ws.onmessage = e => {
707
+ lastHeard = now();
708
+ if (typeof e.data === 'string') {
709
+ let m;
710
+ try { m = JSON.parse(e.data); } catch { return; }
711
+ if (m.t === 'challenge' && !authed) {
712
+ const n = unb64u(m.n, 32);
713
+ if (!n) return finish('the relay sent a bad challenge');
714
+ const sig = crypto.sign(null, tx('dibs-relay-auth-v1', k.mid, n, base.host), k.relay);
715
+ return ws.send(JSON.stringify({ t: 'auth', pub: b64u(k.relayPub), sig: b64u(sig) }));
716
+ }
717
+ if (m.t === 'ok') { authed = true; syncTokens(); status('connected', { url: base.origin }); return log(`relay: connected to ${base.origin}`); }
718
+ if (!authed) return;
719
+ if (m.t === 'acct-pending-res' && typeof m.ref === 'string' && Array.isArray(m.pending)) {
720
+ for (const s of approvalStep(m.ref, m.pending, eph)) ws.send(JSON.stringify({ t: 'acct-answer', aid: m.ref, secret: load().accounts[m.ref]?.secret, id: s.id, step: s.step }));
721
+ return;
722
+ }
723
+ if (m.t === 'http' && typeof m.id === 'string') {
724
+ return mcpAnswer(m, k).catch(() => offJson(500)).then(r => { if (ws.readyState === 1) ws.send(httpRes(m.id, r)); });
725
+ }
726
+ if (m.t === 'open' && unb64u(m.ch, 16)) return peer.open(m.ch);
727
+ if (m.t === 'gone' && unb64u(m.ch, 16)) return peer.gone(m.ch);
728
+ return;
729
+ }
730
+ if (!authed) return;
731
+ const b = Buffer.from(e.data);
732
+ if (b.length < 17) return;
733
+ peer.data(b64u(b.subarray(0, 16)), b.subarray(16));
734
+ };
735
+ ws.onclose = e => finish(e.code === 4401 ? 'the relay refused this machine\'s signature' : `connection closed (${e.code}${e.reason ? ` ${e.reason}` : ''})`);
736
+ ws.onerror = e => finish(`couldn't reach ${base.origin}: ${e.message || e.error?.message || 'connection failed'}`);
737
+ });
738
+ }
739
+
740
+ const ago = t => (t ? `${dur(now() - t)} ago` : 'never');
741
+
742
+ // The remote half of `dibs pair`: --remote [--allow-actions], and its rows in --list and --revoke.
743
+ export function pairRemote({ act = false } = {}) {
744
+ const p = newPairing({ act });
745
+ logChange('pair remote', { actions: act });
746
+ console.log(`${render(qr(p.link))}\n${p.link}\n`);
747
+ console.log(`Scan the code with the phone you want to use, or open the link in that browser. Don't paste it into a chat: whoever opens it first gets in.`);
748
+ console.log(`One use, until ${clockOf(p.exp)} (${p.life / MIN} minutes). That browser checks it reached this Mac by its fingerprint ${p.fp.slice(0, 16)}...`);
749
+ console.log(act ? 'It can act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never message agents, answer their questions, or change the hook or your hours. Revoke it if the device is lost.'
750
+ : 'It can only look. To let a browser change things too: dibs pair --remote --allow-actions');
751
+ const s = statusLine();
752
+ if (!s || s.startsWith('not running')) console.log(`\nThis Mac isn't connected to the relay yet. Turn it on: dibs service install relay`);
753
+ }
754
+ // dibs connect --account: a link a browser signed in to a dibs account opens, to add this Mac to
755
+ // the account. Every browser of the account then reaches this Mac, and this Mac can hand the
756
+ // account's key to its new browsers (dibs connect --approve).
757
+ export function pairAccount({ act = false } = {}) {
758
+ const p = newPairing({ act, account: true });
759
+ logChange('connect account', { actions: act });
760
+ console.log(`${render(qr(p.link))}\n${p.link}\n`);
761
+ console.log('Open it in a browser signed in to your dibs account (app.dibs.cc/account), or scan it with a phone that is.');
762
+ console.log(`One use, until ${clockOf(p.exp)} (${p.life / MIN} minutes). After that, every browser you sign in to the account with opens this Mac.`);
763
+ console.log(act ? 'Those browsers can act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs.'
764
+ : 'Those browsers can only look. To let them change things: dibs connect --account --allow-actions');
765
+ const s = statusLine();
766
+ if (!s || s.startsWith('not running')) console.log(`\nThis Mac isn't connected to the relay yet. Turn it on: dibs service install relay`);
767
+ }
768
+ const clockOf = t => new Date(t).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
769
+
770
+ export function listRemote() {
771
+ const ds = devices();
772
+ if (load().mcp) console.log(`(${mcpLine()})`);
773
+ for (const d of ds) console.log(`${d.id.slice(0, 8)} ${d.acct ? 'account' : 'remote'}: ${d.name}, ${d.act === true ? 'can act' : 'look only'} paired ${new Date(d.created).toLocaleString()}, last connected ${ago(d.seen)}`);
774
+ const accts = Object.entries(load().accounts);
775
+ for (const [aid, a] of accts) console.log(`${aid.slice(0, 8)} dibs account${a.label && a.label !== 'a browser' ? ` ${a.label}` : ''}: this Mac holds its key and approves its new browsers (dibs connect --approve) joined ${new Date(a.joined).toLocaleString()}`);
776
+ const wait = waitingApprovals();
777
+ if (wait.length) console.log(`${wait.length} browser${wait.length > 1 ? 's' : ''} waiting for approval: type the 6-digit code it shows, dibs connect --approve <code>`);
778
+ return ds.length + accts.length;
779
+ }