@conveno/cli 0.2.0-rc.17 → 0.2.0-rc.18
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.
- package/dist/{acp-C-o3rtAB.js → acp-CFIh624o.js} +3 -3
- package/dist/{agy-relay-D17zTd_Z.js → agy-relay-BZ3d_-FS.js} +2 -2
- package/dist/bin.js +2 -2
- package/dist/daemon.js +4 -3633
- package/dist/{daemonError-BwdtKOCy.js → daemonError-CDgEtvy7.js} +1 -1
- package/dist/{dist-hyKfBSdF.js → dist-B7liMhCw.js} +3 -3
- package/dist/{dist-Bb2opAjB.js → dist-CFsDqevs.js} +1 -1
- package/dist/{dist-Dc50_P_f.js → dist-CSSvrcKr.js} +489 -249
- package/dist/{dist-CTw3arJP.js → dist-D6Xoip5W.js} +1 -1
- package/dist/{dist-BgAfkqeX.js → dist-DAVtixeC.js} +1 -1
- package/dist/{dist-CvKAege3.js → dist-DTMnNySx.js} +1 -1
- package/dist/dist-DV9DhvJC.js +4509 -0
- package/dist/{hook-BLSrNkFF.js → hook-BA-tI6Oc.js} +1 -1
- package/dist/{hook-entry-DYXjVztc.js → hook-entry-BwzBtAnd.js} +27 -24
- package/dist/hook-entry-Cgt5ZH1s.js +1 -0
- package/dist/{main-CQx2xc_w.js → main-BlS8BhhS.js} +10 -10
- package/dist/{pick-iuG24FX9.js → pick-BsMvXuDo.js} +1 -1
- package/dist/{run-B01nDeos.js → run-BtYGSOMi.js} +27 -72
- package/dist/{runtime-hZwjrEPc.js → runtime-CddqMa5-.js} +11 -32
- package/dist/{uninstall-B-deU_wY.js → uninstall-01_NStQ4.js} +4 -4
- package/dist/{watch-CPZ2X-yt.js → watch-BIepRTXJ.js} +4 -4
- package/package.json +13 -13
- package/dist/dist-B1pfP_d5.js +0 -793
- package/dist/hook-entry-B1Yt2cwr.js +0 -1
|
@@ -0,0 +1,4509 @@
|
|
|
1
|
+
import { homedir, hostname } from "node:os";
|
|
2
|
+
import { $n as SESSION_ENDED_TEXT, A as baseName, An as validateRename, Cr as number, Ct as leadLogPath, Dn as turnHops, Dt as markDelivered, En as tooManyUnreadMessage, F as clearOrchestrator, G as dataDir, Gn as Message, H as createWmiWalker, Hn as EVENT_NAMES, I as cliDeliveryTier, J as defaultProcessIo, Jn as PROTOCOL_VERSION, K as dataPaths, Ln as writePrivateFileSync, M as claimOrchestrator, Mt as oneWindowPerHost, O as autoCandidates, Q as effectiveHolder, Qt as readInbox, R as clientProof, Rt as pendingForInjection, Sn as statusAfterLiveness, Sr as literal, St as leadLogLine, Tn as takeWithinChars, Tr as string, U as currentAccessToken, Vn as DeviceId, W as daemonProof, Xn as RelayPayload, Xt as readAncestry, Y as detectRepo, Yn as RELAY_CLIENT_NAME, Yt as readAccountTokens, Zn as RpcErrorCode, _n as signedInAccountApi, _r as socketPathTooLongMessage, _t as isOnline, a as ConvenoError, at as formatContinuation, cr as makeEventNotification, ct as generateSessionName, d as RESPONSE_BUDGET_BYTES, dr as newMessageId, et as evaluateLiveness, fn as restrictToUser, fr as newSessionId, gr as sanitizeLine, hr as safeParse, in as relayUrl, ir as encodeFrame, j as bindAccountDevice, jt as newAuthNonce, k as autoLimitsFromEnv, lr as makeResult, lt as holderAfterDeparture, mr as parseRelayFrame, nr as createLineDecoder, or as isSocketPathTooLong, ot as formatHookContext, pr as parseIpcRequest, q as decideAutoContinue, qn as OWNER_SESSION_ID, qt as proofsMatch, rr as defaultSocketPath, sn as requeueEntries, sr as makeError, t as AccountError, tn as readSettings, tr as SessionId, un as resolveRecipient, ur as newDeviceId, vr as _enum, vt as jwtClaim, w as appendHookLog, wn as takeWithinBytes, wr as object, xr as discriminatedUnion, y as ackEntries, yr as array } from "./dist-CSSvrcKr.js";
|
|
3
|
+
import { randomBytes as randomBytes$1 } from "node:crypto";
|
|
4
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { connect, createServer } from "node:net";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { DatabaseSync } from "node:sqlite";
|
|
8
|
+
import { randomBytes as randomBytes$2 } from "@noble/ciphers/utils.js";
|
|
9
|
+
import { equalBytes } from "@noble/curves/utils.js";
|
|
10
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
11
|
+
import { bytesToHex, concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
12
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
13
|
+
import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
|
|
14
|
+
import { expand, extract } from "@noble/hashes/hkdf.js";
|
|
15
|
+
// ../crypto/dist/index.js
|
|
16
|
+
/** Cryptographically secure random bytes (`crypto.getRandomValues`). */
|
|
17
|
+
const randomBytes = (n) => randomBytes$2(n);
|
|
18
|
+
/** Constant-time comparison of two byte arrays. */
|
|
19
|
+
const bytesEqual = (a, b) => equalBytes(a, b);
|
|
20
|
+
const sha256Bytes = (data) => sha256(data);
|
|
21
|
+
const B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
22
|
+
/** Standard base64 with padding. */
|
|
23
|
+
function toBase64(bytes) {
|
|
24
|
+
let s = "";
|
|
25
|
+
for (let i = 0; i < bytes.length; i += 32768) s += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
26
|
+
return btoa(s);
|
|
27
|
+
}
|
|
28
|
+
/** Strict base64 decode: standard alphabet, padding required. Throws on anything else. */
|
|
29
|
+
function fromBase64(s, expectedLength) {
|
|
30
|
+
if (!B64_RE.test(s)) throw new CryptoError("bad_encoding", "Value is not valid base64.");
|
|
31
|
+
const bin = atob(s);
|
|
32
|
+
const out = new Uint8Array(bin.length);
|
|
33
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
34
|
+
if (expectedLength !== void 0 && out.length !== expectedLength) throw new CryptoError("bad_encoding", `Expected ${expectedLength} bytes, got ${out.length} bytes.`);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** Big-endian unsigned integer of `len` bytes (RFC 8017 I2OSP). */
|
|
38
|
+
function i2osp(n, len) {
|
|
39
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new RangeError("i2osp: not a non-negative integer");
|
|
40
|
+
const out = new Uint8Array(len);
|
|
41
|
+
let v = n;
|
|
42
|
+
for (let i = len - 1; i >= 0; i--) {
|
|
43
|
+
out[i] = v % 256;
|
|
44
|
+
v = Math.floor(v / 256);
|
|
45
|
+
}
|
|
46
|
+
if (v !== 0) throw new RangeError("i2osp: integer too large");
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Unambiguous encoding of a list of fields for signing and hashing: each field is a 4-byte
|
|
51
|
+
* big-endian length followed by its bytes. Strings are UTF-8. Two different field lists never
|
|
52
|
+
* encode to the same bytes, so a signature over one cannot be replayed as a signature over another.
|
|
53
|
+
*/
|
|
54
|
+
function encodeFields(...fields) {
|
|
55
|
+
const parts = [];
|
|
56
|
+
for (const f of fields) {
|
|
57
|
+
const b = typeof f === "string" ? utf8ToBytes(f) : typeof f === "number" ? i2osp(f, 8) : f;
|
|
58
|
+
parts.push(i2osp(b.length, 4), b);
|
|
59
|
+
}
|
|
60
|
+
return concatBytes(...parts);
|
|
61
|
+
}
|
|
62
|
+
/** Every verification failure in this package. `code` is stable; `message` is for people. */
|
|
63
|
+
var CryptoError = class extends Error {
|
|
64
|
+
code;
|
|
65
|
+
constructor(code, message) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.code = code;
|
|
68
|
+
this.name = "CryptoError";
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
const Key32 = string().regex(/^[A-Za-z0-9+/]{43}=$/, "expected 32 bytes as base64");
|
|
72
|
+
/** What other devices know about a device: its id, a display name and its two public keys. */
|
|
73
|
+
const DevicePublic = object({
|
|
74
|
+
deviceId: DeviceId,
|
|
75
|
+
name: string().min(1).max(64),
|
|
76
|
+
/** Ed25519 public key, base64. */
|
|
77
|
+
signingKey: Key32,
|
|
78
|
+
/** X25519 public key, base64. */
|
|
79
|
+
kxKey: Key32
|
|
80
|
+
});
|
|
81
|
+
/** On-disk form of an identity. Holds secret keys: store with mode 0600. */
|
|
82
|
+
const IdentityFile = object({
|
|
83
|
+
version: literal(1),
|
|
84
|
+
deviceId: DeviceId,
|
|
85
|
+
signingSecretKey: Key32,
|
|
86
|
+
kxSecretKey: Key32
|
|
87
|
+
});
|
|
88
|
+
function generateIdentity(deviceId) {
|
|
89
|
+
const sign = ed25519.keygen();
|
|
90
|
+
const kx = x25519.keygen();
|
|
91
|
+
return {
|
|
92
|
+
deviceId,
|
|
93
|
+
signingSecretKey: sign.secretKey,
|
|
94
|
+
signingPublicKey: sign.publicKey,
|
|
95
|
+
kxSecretKey: kx.secretKey,
|
|
96
|
+
kxPublicKey: kx.publicKey
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function serializeIdentity(id) {
|
|
100
|
+
return {
|
|
101
|
+
version: 1,
|
|
102
|
+
deviceId: id.deviceId,
|
|
103
|
+
signingSecretKey: toBase64(id.signingSecretKey),
|
|
104
|
+
kxSecretKey: toBase64(id.kxSecretKey)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Rebuild an identity from its file form; public keys are recomputed from the secret keys. */
|
|
108
|
+
function parseIdentity(input) {
|
|
109
|
+
const f = IdentityFile.parse(input);
|
|
110
|
+
const signingSecretKey = fromBase64(f.signingSecretKey, 32);
|
|
111
|
+
const kxSecretKey = fromBase64(f.kxSecretKey, 32);
|
|
112
|
+
return {
|
|
113
|
+
deviceId: f.deviceId,
|
|
114
|
+
signingSecretKey,
|
|
115
|
+
signingPublicKey: ed25519.getPublicKey(signingSecretKey),
|
|
116
|
+
kxSecretKey,
|
|
117
|
+
kxPublicKey: x25519.getPublicKey(kxSecretKey)
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function publicRecord(id, name) {
|
|
121
|
+
return DevicePublic.parse({
|
|
122
|
+
deviceId: id.deviceId,
|
|
123
|
+
name,
|
|
124
|
+
signingKey: toBase64(id.signingPublicKey),
|
|
125
|
+
kxKey: toBase64(id.kxPublicKey)
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/** Canonical bytes of a device record, for signatures and transcripts. */
|
|
129
|
+
function encodeDevice(d) {
|
|
130
|
+
return encodeFields("device", d.deviceId, d.name, d.signingKey, d.kxKey);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* A short, stable fingerprint of a device's keys (not its name), for display: the first 16 bytes
|
|
134
|
+
* of SHA-256 over both public keys, as hex in groups of four.
|
|
135
|
+
*/
|
|
136
|
+
function deviceFingerprint(d) {
|
|
137
|
+
return bytesToHex(sha256Bytes(encodeFields("fingerprint", d.signingKey, d.kxKey))).slice(0, 32).match(/.{4}/g).join(" ");
|
|
138
|
+
}
|
|
139
|
+
const sign = (sk, msg) => ed25519.sign(msg, sk);
|
|
140
|
+
/**
|
|
141
|
+
* Ed25519 verify with the strict RFC 8032 encoding rules (`zip215: false`: non-canonical point
|
|
142
|
+
* encodings are refused, so signatures are not malleable). Malformed input verifies as false.
|
|
143
|
+
*/
|
|
144
|
+
function verify(pk, msg, sig) {
|
|
145
|
+
try {
|
|
146
|
+
return ed25519.verify(sig, msg, pk, { zip215: false });
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const ChainEntry = object({
|
|
152
|
+
seq: number().int().min(0).max(512),
|
|
153
|
+
/** Hex SHA-256 of the previous entry; empty for the genesis entry. */
|
|
154
|
+
prev: string().regex(/^(?:[0-9a-f]{64})?$/),
|
|
155
|
+
op: _enum(["add", "revoke"]),
|
|
156
|
+
/** For `add`: the device added. */
|
|
157
|
+
device: DevicePublic.optional(),
|
|
158
|
+
/** For `revoke`: the device removed. */
|
|
159
|
+
target: DeviceId.optional(),
|
|
160
|
+
/** The signing device. */
|
|
161
|
+
by: DeviceId,
|
|
162
|
+
/** Unix ms, informational. */
|
|
163
|
+
ts: number().int().nonnegative(),
|
|
164
|
+
/** Ed25519 signature by `by`, base64. */
|
|
165
|
+
sig: string().regex(/^[A-Za-z0-9+/]{86}==$/)
|
|
166
|
+
});
|
|
167
|
+
const DeviceChain = array(ChainEntry).min(1).max(512);
|
|
168
|
+
function payloadBytes(e) {
|
|
169
|
+
const subject = e.op === "add" && e.device ? encodeDevice(e.device) : encodeFields("target", e.target ?? "");
|
|
170
|
+
return encodeFields("conveno/1 device-chain", e.seq, e.prev, e.op, subject, e.by, e.ts);
|
|
171
|
+
}
|
|
172
|
+
function entryHash(e) {
|
|
173
|
+
return bytesToHex(sha256Bytes(encodeFields(payloadBytes(e), e.sig)));
|
|
174
|
+
}
|
|
175
|
+
function fail(message) {
|
|
176
|
+
throw new CryptoError("bad_chain", message);
|
|
177
|
+
}
|
|
178
|
+
/** Verify a whole chain from genesis and return the resulting member set. Throws on any defect. */
|
|
179
|
+
function verifyChain(input, o = {}) {
|
|
180
|
+
const trusted = o.trustedPrefix ?? 0;
|
|
181
|
+
const parsed = DeviceChain.safeParse(input);
|
|
182
|
+
if (!parsed.success) fail("The device list is malformed.");
|
|
183
|
+
const chain = parsed.data;
|
|
184
|
+
const members = /* @__PURE__ */ new Map();
|
|
185
|
+
const revoked = /* @__PURE__ */ new Map();
|
|
186
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
187
|
+
let adds = 0;
|
|
188
|
+
let head = "";
|
|
189
|
+
chain.forEach((e, i) => {
|
|
190
|
+
if (e.seq !== i) fail(`Entry ${i} has sequence number ${e.seq}.`);
|
|
191
|
+
if (e.prev !== head) fail(`Entry ${i} does not follow entry ${i - 1}.`);
|
|
192
|
+
let signer;
|
|
193
|
+
if (i === 0) {
|
|
194
|
+
if (e.op !== "add" || !e.device || e.device.deviceId !== e.by) fail("The first entry must be a device adding itself.");
|
|
195
|
+
signer = e.device;
|
|
196
|
+
} else {
|
|
197
|
+
signer = members.get(e.by);
|
|
198
|
+
if (!signer) fail(`Entry ${i} is signed by a device that is not an active member.`);
|
|
199
|
+
}
|
|
200
|
+
if (i >= trusted) {
|
|
201
|
+
if (!verify(fromBase64(signer.signingKey, 32), payloadBytes(e), fromBase64(e.sig, 64))) fail(`Entry ${i} has an invalid signature.`);
|
|
202
|
+
}
|
|
203
|
+
if (e.op === "add") {
|
|
204
|
+
const d = e.device;
|
|
205
|
+
if (!d || e.target !== void 0) fail(`Entry ${i} is an add without exactly one device.`);
|
|
206
|
+
if (++adds > 256) fail(`Entry ${i} adds more than 256 devices.`);
|
|
207
|
+
if (members.has(d.deviceId) || revoked.has(d.deviceId)) fail(`Entry ${i} adds device ${d.deviceId}, which was already in the list.`);
|
|
208
|
+
if (seenKeys.has(d.signingKey) || seenKeys.has(d.kxKey)) fail(`Entry ${i} reuses a key already in the list.`);
|
|
209
|
+
seenKeys.add(d.signingKey);
|
|
210
|
+
seenKeys.add(d.kxKey);
|
|
211
|
+
members.set(d.deviceId, {
|
|
212
|
+
...d,
|
|
213
|
+
addedAt: e.ts,
|
|
214
|
+
addedBy: e.by
|
|
215
|
+
});
|
|
216
|
+
} else {
|
|
217
|
+
const t = e.target;
|
|
218
|
+
if (!t || e.device !== void 0) fail(`Entry ${i} is a revoke without exactly one target.`);
|
|
219
|
+
const m = members.get(t);
|
|
220
|
+
if (!m) fail(`Entry ${i} revokes ${t}, which is not an active member.`);
|
|
221
|
+
if (members.size === 1) fail(`Entry ${i} revokes the last active device.`);
|
|
222
|
+
members.delete(t);
|
|
223
|
+
const { addedAt: _a, addedBy: _b, ...device } = m;
|
|
224
|
+
revoked.set(t, {
|
|
225
|
+
device,
|
|
226
|
+
revokedAt: e.ts,
|
|
227
|
+
by: e.by
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
head = entryHash(e);
|
|
231
|
+
});
|
|
232
|
+
return {
|
|
233
|
+
members,
|
|
234
|
+
revoked,
|
|
235
|
+
head,
|
|
236
|
+
length: chain.length
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function signEntry(by, e) {
|
|
240
|
+
return {
|
|
241
|
+
...e,
|
|
242
|
+
sig: toBase64(sign(by.signingSecretKey, payloadBytes(e)))
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/** Start a new device list with this device as its only member. */
|
|
246
|
+
function createChain(self, record, ts) {
|
|
247
|
+
if (record.deviceId !== self.deviceId) throw new Error("record is not this device");
|
|
248
|
+
return [signEntry(self, {
|
|
249
|
+
seq: 0,
|
|
250
|
+
prev: "",
|
|
251
|
+
op: "add",
|
|
252
|
+
device: record,
|
|
253
|
+
by: self.deviceId,
|
|
254
|
+
ts
|
|
255
|
+
})];
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Append several operations signed by `self`, which must be an active member. The chain is
|
|
259
|
+
* verified once before and once after, so the result is always a valid chain.
|
|
260
|
+
*/
|
|
261
|
+
function appendOps(chain, self, ops, ts) {
|
|
262
|
+
const state = verifyChain(chain);
|
|
263
|
+
if (!state.members.has(self.deviceId)) throw new CryptoError("bad_chain", "This device is not an active member of the device list.");
|
|
264
|
+
const next = [...chain];
|
|
265
|
+
let prev = state.head;
|
|
266
|
+
for (const o of ops) {
|
|
267
|
+
const e = signEntry(self, {
|
|
268
|
+
seq: next.length,
|
|
269
|
+
prev,
|
|
270
|
+
by: self.deviceId,
|
|
271
|
+
ts,
|
|
272
|
+
...o
|
|
273
|
+
});
|
|
274
|
+
next.push(e);
|
|
275
|
+
prev = entryHash(e);
|
|
276
|
+
}
|
|
277
|
+
verifyChain(next);
|
|
278
|
+
return next;
|
|
279
|
+
}
|
|
280
|
+
function appendAdd(chain, self, device, ts) {
|
|
281
|
+
return appendOps(chain, self, [{
|
|
282
|
+
op: "add",
|
|
283
|
+
device
|
|
284
|
+
}], ts);
|
|
285
|
+
}
|
|
286
|
+
function appendRevoke(chain, self, target, ts) {
|
|
287
|
+
return appendOps(chain, self, [{
|
|
288
|
+
op: "revoke",
|
|
289
|
+
target
|
|
290
|
+
}], ts);
|
|
291
|
+
}
|
|
292
|
+
/** The first entry at which two chains differ, or -1 when one is a prefix of the other. */
|
|
293
|
+
function forkPoint(a, b) {
|
|
294
|
+
const common = Math.min(a.length, b.length);
|
|
295
|
+
for (let i = 0; i < common; i++) if (entryHash(a[i]) !== entryHash(b[i])) return i;
|
|
296
|
+
return -1;
|
|
297
|
+
}
|
|
298
|
+
/** Hash and length of a chain's last entry, as envelopes carry it. */
|
|
299
|
+
function chainHead(chain) {
|
|
300
|
+
return {
|
|
301
|
+
head: entryHash(chain[chain.length - 1]),
|
|
302
|
+
length: chain.length
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Is a list with this head and length consistent with `chain`: the same list or a prefix of it.
|
|
307
|
+
* A list longer than `chain` cannot be checked and counts as inconsistent.
|
|
308
|
+
*/
|
|
309
|
+
function headMatches(chain, head, length) {
|
|
310
|
+
if (length < 1 || length > chain.length) return false;
|
|
311
|
+
return entryHash(chain[length - 1]) === head;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* HPKE, RFC 9180, for exactly one cipher suite:
|
|
315
|
+
*
|
|
316
|
+
* KEM 0x0020 DHKEM(X25519, HKDF-SHA256)
|
|
317
|
+
* KDF 0x0001 HKDF-SHA256
|
|
318
|
+
* AEAD 0x0003 ChaCha20Poly1305
|
|
319
|
+
*
|
|
320
|
+
* Modes `base` (0x00) and `auth` (0x02). The primitives (X25519, HKDF, SHA-256, ChaCha20-Poly1305)
|
|
321
|
+
* come from the audited @noble libraries; this file only wires them together as the RFC specifies,
|
|
322
|
+
* and the tests check it against the RFC's own test vectors (Appendix A.2).
|
|
323
|
+
*
|
|
324
|
+
* https://www.rfc-editor.org/rfc/rfc9180.html
|
|
325
|
+
*/
|
|
326
|
+
const KEM_ID = 32;
|
|
327
|
+
const KDF_ID = 1;
|
|
328
|
+
const AEAD_ID = 3;
|
|
329
|
+
/** Nsecret, Nenc, Npk, Nsk for DHKEM(X25519, HKDF-SHA256); Nk, Nn for ChaCha20Poly1305. */
|
|
330
|
+
const N_SECRET = 32;
|
|
331
|
+
const N_K = 32;
|
|
332
|
+
const N_N = 12;
|
|
333
|
+
const N_H = 32;
|
|
334
|
+
const HPKE_V1 = utf8ToBytes("HPKE-v1");
|
|
335
|
+
const SUITE_KEM = concatBytes(utf8ToBytes("KEM"), i2osp(KEM_ID, 2));
|
|
336
|
+
const SUITE_HPKE = concatBytes(utf8ToBytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
337
|
+
const EMPTY = /* @__PURE__ */ new Uint8Array(0);
|
|
338
|
+
/** RFC 9180 section 4: LabeledExtract. */
|
|
339
|
+
function labeledExtract(suite, salt, label, ikm) {
|
|
340
|
+
return extract(sha256, concatBytes(HPKE_V1, suite, utf8ToBytes(label), ikm), salt);
|
|
341
|
+
}
|
|
342
|
+
/** RFC 9180 section 4: LabeledExpand. */
|
|
343
|
+
function labeledExpand(suite, prk, label, info, len) {
|
|
344
|
+
const labeledInfo = concatBytes(i2osp(len, 2), HPKE_V1, suite, utf8ToBytes(label), info);
|
|
345
|
+
return expand(sha256, prk, labeledInfo, len);
|
|
346
|
+
}
|
|
347
|
+
function generateKeyPair() {
|
|
348
|
+
return x25519.keygen();
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* X25519 with the all-zero check RFC 9180 section 7.1.4 requires. noble already refuses
|
|
352
|
+
* low-order points; the explicit check documents and guarantees it.
|
|
353
|
+
*/
|
|
354
|
+
function dh(sk, pk) {
|
|
355
|
+
let out;
|
|
356
|
+
try {
|
|
357
|
+
out = x25519.getSharedSecret(sk, pk);
|
|
358
|
+
} catch {
|
|
359
|
+
throw new CryptoError("decrypt_failed", "Invalid X25519 public key.");
|
|
360
|
+
}
|
|
361
|
+
if (out.every((b) => b === 0)) throw new CryptoError("decrypt_failed", "Invalid X25519 public key.");
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
364
|
+
function extractAndExpand(dhBytes, kemContext) {
|
|
365
|
+
const eaePrk = labeledExtract(SUITE_KEM, EMPTY, "eae_prk", dhBytes);
|
|
366
|
+
return labeledExpand(SUITE_KEM, eaePrk, "shared_secret", kemContext, N_SECRET);
|
|
367
|
+
}
|
|
368
|
+
/** RFC 9180 section 4.1: Encap / AuthEncap (skS given). `ephemeral` is for test vectors only. */
|
|
369
|
+
function encap(pkR, skS, ephemeral = generateKeyPair()) {
|
|
370
|
+
const enc = ephemeral.publicKey;
|
|
371
|
+
if (skS === void 0) return {
|
|
372
|
+
sharedSecret: extractAndExpand(dh(ephemeral.secretKey, pkR), concatBytes(enc, pkR)),
|
|
373
|
+
enc
|
|
374
|
+
};
|
|
375
|
+
const pkS = x25519.getPublicKey(skS);
|
|
376
|
+
return {
|
|
377
|
+
sharedSecret: extractAndExpand(concatBytes(dh(ephemeral.secretKey, pkR), dh(skS, pkR)), concatBytes(enc, pkR, pkS)),
|
|
378
|
+
enc
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
/** RFC 9180 section 4.1: Decap / AuthDecap (pkS given). */
|
|
382
|
+
function decap(enc, skR, pkS) {
|
|
383
|
+
const pkR = x25519.getPublicKey(skR);
|
|
384
|
+
if (pkS === void 0) return extractAndExpand(dh(skR, enc), concatBytes(enc, pkR));
|
|
385
|
+
return extractAndExpand(concatBytes(dh(skR, enc), dh(skR, pkS)), concatBytes(enc, pkR, pkS));
|
|
386
|
+
}
|
|
387
|
+
/** RFC 9180 section 5.1: KeySchedule, with the default (empty) PSK, as modes base and auth use. */
|
|
388
|
+
function keySchedule(mode, sharedSecret, info) {
|
|
389
|
+
const pskIdHash = labeledExtract(SUITE_HPKE, EMPTY, "psk_id_hash", EMPTY);
|
|
390
|
+
const infoHash = labeledExtract(SUITE_HPKE, EMPTY, "info_hash", info);
|
|
391
|
+
const context = concatBytes(Uint8Array.of(mode), pskIdHash, infoHash);
|
|
392
|
+
const secret = labeledExtract(SUITE_HPKE, sharedSecret, "secret", EMPTY);
|
|
393
|
+
return {
|
|
394
|
+
key: labeledExpand(SUITE_HPKE, secret, "key", context, N_K),
|
|
395
|
+
baseNonce: labeledExpand(SUITE_HPKE, secret, "base_nonce", context, N_N),
|
|
396
|
+
exporterSecret: labeledExpand(SUITE_HPKE, secret, "exp", context, N_H)
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
/** An HPKE encryption context (RFC 9180 section 5.2). Sequence numbers start at 0. */
|
|
400
|
+
var HpkeContext = class {
|
|
401
|
+
schedule;
|
|
402
|
+
sharedSecret;
|
|
403
|
+
seq = 0;
|
|
404
|
+
constructor(schedule, sharedSecret) {
|
|
405
|
+
this.schedule = schedule;
|
|
406
|
+
this.sharedSecret = sharedSecret;
|
|
407
|
+
}
|
|
408
|
+
nonce() {
|
|
409
|
+
const n = this.schedule.baseNonce.slice();
|
|
410
|
+
const s = i2osp(this.seq, N_N);
|
|
411
|
+
for (let i = 0; i < N_N; i++) n[i] = n[i] ^ s[i];
|
|
412
|
+
return n;
|
|
413
|
+
}
|
|
414
|
+
seal(aad, plaintext) {
|
|
415
|
+
const ct = chacha20poly1305(this.schedule.key, this.nonce(), aad).encrypt(plaintext);
|
|
416
|
+
this.seq++;
|
|
417
|
+
return ct;
|
|
418
|
+
}
|
|
419
|
+
open(aad, ciphertext) {
|
|
420
|
+
let pt;
|
|
421
|
+
try {
|
|
422
|
+
pt = chacha20poly1305(this.schedule.key, this.nonce(), aad).decrypt(ciphertext);
|
|
423
|
+
} catch {
|
|
424
|
+
throw new CryptoError("decrypt_failed", "The envelope could not be decrypted.");
|
|
425
|
+
}
|
|
426
|
+
this.seq++;
|
|
427
|
+
return pt;
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
/** RFC 9180 section 5.1.1 / 5.1.3: SetupBaseS / SetupAuthS. */
|
|
431
|
+
function setupSender(o) {
|
|
432
|
+
if (o.mode === 2 && o.skS === void 0) throw new Error("auth mode needs skS");
|
|
433
|
+
const skS = o.mode === 2 ? o.skS : void 0;
|
|
434
|
+
const { sharedSecret, enc } = encap(o.pkR, skS, o.ephemeral);
|
|
435
|
+
return {
|
|
436
|
+
enc,
|
|
437
|
+
ctx: new HpkeContext(keySchedule(o.mode, sharedSecret, o.info), sharedSecret)
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
/** RFC 9180 section 5.1.1 / 5.1.3: SetupBaseR / SetupAuthR. */
|
|
441
|
+
function setupRecipient(o) {
|
|
442
|
+
if (o.mode === 2 && o.pkS === void 0) throw new Error("auth mode needs pkS");
|
|
443
|
+
const pkS = o.mode === 2 ? o.pkS : void 0;
|
|
444
|
+
const sharedSecret = decap(o.enc, o.skR, pkS);
|
|
445
|
+
return new HpkeContext(keySchedule(o.mode, sharedSecret, o.info), sharedSecret);
|
|
446
|
+
}
|
|
447
|
+
const HPKE_INFO = utf8ToBytes("conveno/1 envelope");
|
|
448
|
+
const SIG_DOMAIN = "conveno/1 envelope-sig";
|
|
449
|
+
/** Envelopes older than this are refused. Matches the relay's offline-queue TTL plus slack. */
|
|
450
|
+
const ENVELOPE_MAX_AGE_MS = 6084e5;
|
|
451
|
+
/** Envelopes dated further in the future than this are refused (clock skew allowance). */
|
|
452
|
+
const ENVELOPE_MAX_FUTURE_MS = 3e5;
|
|
453
|
+
function headerBytes(h) {
|
|
454
|
+
return encodeFields("conveno/1 envelope-header", h.v, h.id, h.fromDevice, h.toDevice, h.ts, h.head, h.len, h.enc);
|
|
455
|
+
}
|
|
456
|
+
function signedBytes(h, ciphertext) {
|
|
457
|
+
return concatBytes(encodeFields(SIG_DOMAIN), headerBytes(h), encodeFields(ciphertext));
|
|
458
|
+
}
|
|
459
|
+
function sealEnvelope(o) {
|
|
460
|
+
const { enc, ctx } = setupSender({
|
|
461
|
+
mode: 2,
|
|
462
|
+
pkR: fromBase64(o.recipient.kxKey, 32),
|
|
463
|
+
skS: o.sender.kxSecretKey,
|
|
464
|
+
info: HPKE_INFO
|
|
465
|
+
});
|
|
466
|
+
const header = {
|
|
467
|
+
v: 1,
|
|
468
|
+
id: o.id,
|
|
469
|
+
fromDevice: o.sender.deviceId,
|
|
470
|
+
toDevice: o.recipient.deviceId,
|
|
471
|
+
ts: o.ts,
|
|
472
|
+
head: o.list.head,
|
|
473
|
+
len: o.list.length,
|
|
474
|
+
enc: toBase64(enc)
|
|
475
|
+
};
|
|
476
|
+
const ct = ctx.seal(headerBytes(header), o.plaintext);
|
|
477
|
+
const sig = sign(o.sender.signingSecretKey, signedBytes(header, ct));
|
|
478
|
+
return {
|
|
479
|
+
t: "envelope",
|
|
480
|
+
...header,
|
|
481
|
+
ciphertext: toBase64(ct),
|
|
482
|
+
sig: toBase64(sig)
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Check and decrypt an envelope. Order: recipient, sender membership, time window, replay,
|
|
487
|
+
* signature, decryption. The replay check comes before the signature so a replayed envelope costs
|
|
488
|
+
* a lookup, not a signature verification and a key agreement; refusing an id already seen cannot
|
|
489
|
+
* hurt, since that id was accepted once. The id is recorded as seen only after decryption
|
|
490
|
+
* succeeds, so a forged envelope cannot burn a real id. Throws CryptoError on every failure.
|
|
491
|
+
*/
|
|
492
|
+
function openEnvelope(env, o) {
|
|
493
|
+
if (env.v !== 1) throw new CryptoError("bad_encoding", `Unsupported envelope version ${env.v}.`);
|
|
494
|
+
if (env.toDevice !== o.self.deviceId) throw new CryptoError("wrong_recipient", "The envelope is addressed to another device.");
|
|
495
|
+
const sender = o.sender(env.fromDevice);
|
|
496
|
+
if (!sender || sender.deviceId !== env.fromDevice) throw new CryptoError("unknown_sender", "The sender is not in this device list.");
|
|
497
|
+
if (env.ts < o.now - 6084e5 || env.ts > o.now + 3e5) throw new CryptoError("stale", "The envelope timestamp is outside the accepted window.");
|
|
498
|
+
if (o.replay.has(env.id)) throw new CryptoError("replay", "The envelope was already received.");
|
|
499
|
+
const ct = fromBase64(env.ciphertext);
|
|
500
|
+
const header = {
|
|
501
|
+
v: env.v,
|
|
502
|
+
id: env.id,
|
|
503
|
+
fromDevice: env.fromDevice,
|
|
504
|
+
toDevice: env.toDevice,
|
|
505
|
+
ts: env.ts,
|
|
506
|
+
head: env.head,
|
|
507
|
+
len: env.len,
|
|
508
|
+
enc: env.enc
|
|
509
|
+
};
|
|
510
|
+
if (!verify(fromBase64(sender.signingKey, 32), signedBytes(header, ct), fromBase64(env.sig, 64))) throw new CryptoError("bad_signature", "The envelope signature is not valid.");
|
|
511
|
+
const pt = setupRecipient({
|
|
512
|
+
mode: 2,
|
|
513
|
+
enc: fromBase64(env.enc, 32),
|
|
514
|
+
skR: o.self.kxSecretKey,
|
|
515
|
+
pkS: fromBase64(sender.kxKey, 32),
|
|
516
|
+
info: HPKE_INFO
|
|
517
|
+
}).open(headerBytes(header), ct);
|
|
518
|
+
if (o.record !== false) o.replay.add(env.id, env.ts);
|
|
519
|
+
return pt;
|
|
520
|
+
}
|
|
521
|
+
/** The bytes a device signs to answer the relay's challenge. */
|
|
522
|
+
function helloBytes(nonce, deviceId, signingKey) {
|
|
523
|
+
return encodeFields("conveno/1 relay-hello", nonce, deviceId, signingKey);
|
|
524
|
+
}
|
|
525
|
+
/** Build the `hello` frame answering a relay `challenge` nonce. */
|
|
526
|
+
function signRelayHello(id, nonce) {
|
|
527
|
+
const signingKey = toBase64(id.signingPublicKey);
|
|
528
|
+
const sig = sign(id.signingSecretKey, helloBytes(nonce, id.deviceId, signingKey));
|
|
529
|
+
return {
|
|
530
|
+
t: "hello",
|
|
531
|
+
v: 1,
|
|
532
|
+
deviceId: id.deviceId,
|
|
533
|
+
signingKey,
|
|
534
|
+
sig: toBase64(sig)
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Device pairing with a short authentication string (SAS).
|
|
539
|
+
*
|
|
540
|
+
* The relay carries the pairing messages, so it must be assumed to be an active attacker. The
|
|
541
|
+
* protocol is the commit-then-reveal SAS exchange used by ZRTP (RFC 6189 section 4.4.1) and
|
|
542
|
+
* Bluetooth numeric comparison: the joiner commits to its key record and nonce before it sees
|
|
543
|
+
* the inviter's, so a man in the middle has to fix its own values before it can learn the other
|
|
544
|
+
* side's, and gets one guess at an 8-digit SAS (probability 1e-8).
|
|
545
|
+
*
|
|
546
|
+
* Two 8-digit codes come from the one transcript hash: the inviter shows one, the joiner the
|
|
547
|
+
* other, and the owner types each device's code into the other device, which checks it. A device
|
|
548
|
+
* never asks for the code it shows, so the owner has to read the other screen; a "yes" typed out
|
|
549
|
+
* of habit cannot confirm a pairing. With a man in the middle the two sides hold different
|
|
550
|
+
* transcripts, so each side's check fails except with probability 1e-8.
|
|
551
|
+
*
|
|
552
|
+
* joiner -> all : commit { pairingId, commit = H(pairingId, joinerRecord, nJ) }
|
|
553
|
+
* inviter -> J : offer { pairingId, inviterRecord, nI }
|
|
554
|
+
* joiner -> I : reveal { pairingId, joinerRecord, nJ } both now show their code
|
|
555
|
+
* joiner -> I : confirm { pairingId, sig_J(transcript) } after the owner confirms on J
|
|
556
|
+
* inviter -> J : welcome { pairingId, chain + add(joiner) signed by I } after confirming on I
|
|
557
|
+
*
|
|
558
|
+
* Key confirmation: the joiner's confirm signature and the inviter's signed chain entry prove each
|
|
559
|
+
* side holds the signing key the SAS covered. The X25519 keys are covered by the SAS itself.
|
|
560
|
+
*/
|
|
561
|
+
const PairingId = string().regex(/^[0-9a-f]{32}$/);
|
|
562
|
+
const Nonce = string().regex(/^[A-Za-z0-9+/]{43}=$/);
|
|
563
|
+
const PairMessage = discriminatedUnion("type", [
|
|
564
|
+
object({
|
|
565
|
+
type: literal("commit"),
|
|
566
|
+
pairingId: PairingId,
|
|
567
|
+
commit: Nonce
|
|
568
|
+
}),
|
|
569
|
+
object({
|
|
570
|
+
type: literal("offer"),
|
|
571
|
+
pairingId: PairingId,
|
|
572
|
+
device: DevicePublic,
|
|
573
|
+
nonce: Nonce
|
|
574
|
+
}),
|
|
575
|
+
object({
|
|
576
|
+
type: literal("reveal"),
|
|
577
|
+
pairingId: PairingId,
|
|
578
|
+
device: DevicePublic,
|
|
579
|
+
nonce: Nonce
|
|
580
|
+
}),
|
|
581
|
+
object({
|
|
582
|
+
type: literal("confirm"),
|
|
583
|
+
pairingId: PairingId,
|
|
584
|
+
sig: string().regex(/^[A-Za-z0-9+/]{86}==$/)
|
|
585
|
+
}),
|
|
586
|
+
object({
|
|
587
|
+
type: literal("welcome"),
|
|
588
|
+
pairingId: PairingId,
|
|
589
|
+
chain: DeviceChain
|
|
590
|
+
}),
|
|
591
|
+
object({
|
|
592
|
+
type: literal("abort"),
|
|
593
|
+
pairingId: PairingId,
|
|
594
|
+
reason: string().max(200)
|
|
595
|
+
})
|
|
596
|
+
]);
|
|
597
|
+
function commitment(pairingId, joiner, nonce) {
|
|
598
|
+
return sha256Bytes(encodeFields("conveno/1 pairing-commit", pairingId, encodeDevice(joiner), nonce));
|
|
599
|
+
}
|
|
600
|
+
function transcript(pairingId, inviter, joiner, nI, nJ) {
|
|
601
|
+
return encodeFields("conveno/1 pairing", pairingId, encodeDevice(inviter), encodeDevice(joiner), nI, nJ);
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* The code a device shows: SHA-256 over the transcript; bytes 0-7 (inviter) or 8-15 (joiner) as
|
|
605
|
+
* an unsigned integer, modulo 10^8, shown as two groups of four digits. The modulo bias over a
|
|
606
|
+
* 64-bit value is below 2^-37.
|
|
607
|
+
*/
|
|
608
|
+
function computeSas(t, role) {
|
|
609
|
+
const h = sha256Bytes(encodeFields("conveno/1 pairing-sas", t));
|
|
610
|
+
const at = role === "inviter" ? 0 : 8;
|
|
611
|
+
let n = 0n;
|
|
612
|
+
for (let i = at; i < at + 8; i++) n = n << 8n | BigInt(h[i]);
|
|
613
|
+
const digits = (n % 10n ** BigInt(8)).toString().padStart(8, "0");
|
|
614
|
+
return `${digits.slice(0, 4)} ${digits.slice(4)}`;
|
|
615
|
+
}
|
|
616
|
+
/** Does a code the owner typed (spaces and dashes allowed) equal `expected`. Constant time. */
|
|
617
|
+
function sasMatches(expected, typed) {
|
|
618
|
+
const want = expected.replace(/\D/g, "");
|
|
619
|
+
const got = typed.replace(/[\s-]/g, "");
|
|
620
|
+
if (!/^\d+$/.test(got) || got.length !== want.length) return false;
|
|
621
|
+
const enc = new TextEncoder();
|
|
622
|
+
return bytesEqual(enc.encode(want), enc.encode(got));
|
|
623
|
+
}
|
|
624
|
+
const confirmBytes = (t) => encodeFields("conveno/1 pairing-confirm", t);
|
|
625
|
+
function badPairing(message) {
|
|
626
|
+
throw new CryptoError("bad_pairing", message);
|
|
627
|
+
}
|
|
628
|
+
/** Encode a pairing message for a relay `pair` frame's `data`. */
|
|
629
|
+
function encodePairMessage(m) {
|
|
630
|
+
return toBase64(new TextEncoder().encode(JSON.stringify(m)));
|
|
631
|
+
}
|
|
632
|
+
/** Decode a relay `pair` frame's `data`. Throws CryptoError on anything malformed. */
|
|
633
|
+
function decodePairMessage(data) {
|
|
634
|
+
try {
|
|
635
|
+
return PairMessage.parse(JSON.parse(new TextDecoder().decode(fromBase64(data))));
|
|
636
|
+
} catch {
|
|
637
|
+
return badPairing("The pairing message is malformed.");
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
/** The new device's side. */
|
|
641
|
+
var JoinerPairing = class {
|
|
642
|
+
self;
|
|
643
|
+
record;
|
|
644
|
+
pairingId = bytesToHex(randomBytes(16));
|
|
645
|
+
nonce = toBase64(randomBytes(32));
|
|
646
|
+
inviter;
|
|
647
|
+
inviterNonce;
|
|
648
|
+
t;
|
|
649
|
+
constructor(self, record) {
|
|
650
|
+
this.self = self;
|
|
651
|
+
this.record = record;
|
|
652
|
+
if (record.deviceId !== self.deviceId) throw new Error("record is not this device");
|
|
653
|
+
}
|
|
654
|
+
/** First message, broadcast to the account's other devices. Safe to resend. */
|
|
655
|
+
commit() {
|
|
656
|
+
const c = commitment(this.pairingId, this.record, this.nonce);
|
|
657
|
+
return {
|
|
658
|
+
type: "commit",
|
|
659
|
+
pairingId: this.pairingId,
|
|
660
|
+
commit: toBase64(c)
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
/** The inviter's offer; returns the reveal to send back. Only the first offer is accepted. */
|
|
664
|
+
onOffer(m) {
|
|
665
|
+
if (m.type !== "offer" || m.pairingId !== this.pairingId) badPairing("Unexpected message.");
|
|
666
|
+
if (this.inviter) badPairing("An offer was already accepted for this pairing.");
|
|
667
|
+
if (m.device.deviceId === this.record.deviceId) badPairing("The offer is from this device.");
|
|
668
|
+
this.inviter = m.device;
|
|
669
|
+
this.inviterNonce = m.nonce;
|
|
670
|
+
this.t = transcript(this.pairingId, m.device, this.record, m.nonce, this.nonce);
|
|
671
|
+
return {
|
|
672
|
+
type: "reveal",
|
|
673
|
+
pairingId: this.pairingId,
|
|
674
|
+
device: this.record,
|
|
675
|
+
nonce: this.nonce
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
get peer() {
|
|
679
|
+
return this.inviter;
|
|
680
|
+
}
|
|
681
|
+
/** The code this device shows, for the owner to type on the other device. */
|
|
682
|
+
get sas() {
|
|
683
|
+
return this.t ? computeSas(this.t, "joiner") : void 0;
|
|
684
|
+
}
|
|
685
|
+
/** The code the other device shows, which the owner types here. */
|
|
686
|
+
get peerSas() {
|
|
687
|
+
return this.t ? computeSas(this.t, "inviter") : void 0;
|
|
688
|
+
}
|
|
689
|
+
/** Call only after the owner typed the inviter's code here and it matched (`peerSas`). */
|
|
690
|
+
confirm() {
|
|
691
|
+
if (!this.t) badPairing("No SAS to confirm yet.");
|
|
692
|
+
const sig = sign(this.self.signingSecretKey, confirmBytes(this.t));
|
|
693
|
+
return {
|
|
694
|
+
type: "confirm",
|
|
695
|
+
pairingId: this.pairingId,
|
|
696
|
+
sig: toBase64(sig)
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* The inviter's welcome: the device list, whose last entry must add exactly this device's
|
|
701
|
+
* record and be signed by the inviter whose keys the SAS covered.
|
|
702
|
+
*/
|
|
703
|
+
onWelcome(m) {
|
|
704
|
+
if (m.type !== "welcome" || m.pairingId !== this.pairingId) badPairing("Unexpected message.");
|
|
705
|
+
const inviter = this.inviter;
|
|
706
|
+
if (!inviter || this.inviterNonce === void 0) badPairing("No offer accepted yet.");
|
|
707
|
+
const state = verifyChain(m.chain);
|
|
708
|
+
const last = m.chain[m.chain.length - 1];
|
|
709
|
+
const added = last.device;
|
|
710
|
+
if (last.op !== "add" || last.by !== inviter.deviceId || !added || JSON.stringify(DevicePublic.parse(added)) !== JSON.stringify(this.record)) badPairing("The device list does not add this device by the confirmed inviter.");
|
|
711
|
+
const signer = state.members.get(inviter.deviceId);
|
|
712
|
+
if (!signer || signer.signingKey !== inviter.signingKey || signer.kxKey !== inviter.kxKey) badPairing("The inviter's keys in the device list differ from the confirmed ones.");
|
|
713
|
+
return {
|
|
714
|
+
chain: m.chain,
|
|
715
|
+
state
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
/** The existing device's side. */
|
|
720
|
+
var InviterPairing = class {
|
|
721
|
+
self;
|
|
722
|
+
record;
|
|
723
|
+
nonce = toBase64(randomBytes(32));
|
|
724
|
+
pairingIdValue;
|
|
725
|
+
commitValue;
|
|
726
|
+
joiner;
|
|
727
|
+
t;
|
|
728
|
+
joinerConfirmed = false;
|
|
729
|
+
constructor(self, record) {
|
|
730
|
+
this.self = self;
|
|
731
|
+
this.record = record;
|
|
732
|
+
if (record.deviceId !== self.deviceId) throw new Error("record is not this device");
|
|
733
|
+
}
|
|
734
|
+
get pairingId() {
|
|
735
|
+
return this.pairingIdValue;
|
|
736
|
+
}
|
|
737
|
+
/** A joiner's commit; returns the offer. Only the first commit is taken. */
|
|
738
|
+
onCommit(m) {
|
|
739
|
+
if (m.type !== "commit") badPairing("Unexpected message.");
|
|
740
|
+
if (this.pairingIdValue !== void 0) badPairing("Already pairing with another device.");
|
|
741
|
+
this.pairingIdValue = m.pairingId;
|
|
742
|
+
this.commitValue = fromBase64(m.commit, 32);
|
|
743
|
+
return {
|
|
744
|
+
type: "offer",
|
|
745
|
+
pairingId: m.pairingId,
|
|
746
|
+
device: this.record,
|
|
747
|
+
nonce: this.nonce
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
/** The joiner's reveal: checks it against the commit and fixes the SAS. */
|
|
751
|
+
onReveal(m) {
|
|
752
|
+
if (m.type !== "reveal" || m.pairingId !== this.pairingIdValue) badPairing("Unexpected message.");
|
|
753
|
+
if (this.joiner) badPairing("The joiner already revealed.");
|
|
754
|
+
const c = this.commitValue;
|
|
755
|
+
if (!bytesEqual(c, commitment(m.pairingId, m.device, m.nonce))) badPairing("The joiner's reveal does not match its commitment.");
|
|
756
|
+
if (m.device.deviceId === this.record.deviceId) badPairing("The joiner is this device.");
|
|
757
|
+
this.joiner = m.device;
|
|
758
|
+
this.t = transcript(m.pairingId, this.record, m.device, this.nonce, m.nonce);
|
|
759
|
+
}
|
|
760
|
+
get peer() {
|
|
761
|
+
return this.joiner;
|
|
762
|
+
}
|
|
763
|
+
/** The code this device shows, for the owner to type on the other device. */
|
|
764
|
+
get sas() {
|
|
765
|
+
return this.t ? computeSas(this.t, "inviter") : void 0;
|
|
766
|
+
}
|
|
767
|
+
/** The code the other device shows, which the owner types here. */
|
|
768
|
+
get peerSas() {
|
|
769
|
+
return this.t ? computeSas(this.t, "joiner") : void 0;
|
|
770
|
+
}
|
|
771
|
+
/** The joiner's confirmation, signed with the signing key the SAS covered. */
|
|
772
|
+
onConfirm(m) {
|
|
773
|
+
if (m.type !== "confirm" || m.pairingId !== this.pairingIdValue) badPairing("Unexpected message.");
|
|
774
|
+
if (!this.t || !this.joiner) badPairing("No SAS yet.");
|
|
775
|
+
if (!verify(fromBase64(this.joiner.signingKey, 32), confirmBytes(this.t), fromBase64(m.sig, 64))) badPairing("The joiner's confirmation signature is not valid.");
|
|
776
|
+
this.joinerConfirmed = true;
|
|
777
|
+
}
|
|
778
|
+
get joinerHasConfirmed() {
|
|
779
|
+
return this.joinerConfirmed;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Call only after the owner confirmed the SAS on this device and the joiner confirmed too.
|
|
783
|
+
* Appends the joiner to the device list (creating the list if this device has none yet) and
|
|
784
|
+
* returns the new chain and the welcome message.
|
|
785
|
+
*/
|
|
786
|
+
welcome(chain, ts) {
|
|
787
|
+
if (!this.joiner || !this.joinerConfirmed || this.pairingIdValue === void 0) badPairing("The joiner has not confirmed yet.");
|
|
788
|
+
const next = appendAdd(chain ?? createChain(this.self, this.record, ts), this.self, this.joiner, ts);
|
|
789
|
+
return {
|
|
790
|
+
chain: next,
|
|
791
|
+
message: {
|
|
792
|
+
type: "welcome",
|
|
793
|
+
pairingId: this.pairingIdValue,
|
|
794
|
+
chain: next
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
// ../daemon/dist/main-7HsF67qE.js
|
|
800
|
+
/** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
|
|
801
|
+
var DaemonAlreadyRunningError = class extends Error {
|
|
802
|
+
constructor(detail) {
|
|
803
|
+
super(`The Conveno daemon is already running (${detail}). Run "conveno daemon status" to see it.`);
|
|
804
|
+
this.name = "DaemonAlreadyRunningError";
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
/** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
|
|
808
|
+
function defaultIsAlive(pid) {
|
|
809
|
+
try {
|
|
810
|
+
process.kill(pid, 0);
|
|
811
|
+
return true;
|
|
812
|
+
} catch (e) {
|
|
813
|
+
return e.code === "EPERM";
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/** True when something accepts connections on the socket or pipe. */
|
|
817
|
+
function probeSocket(socketPath, timeoutMs = 500) {
|
|
818
|
+
return new Promise((resolve) => {
|
|
819
|
+
const s = connect(socketPath);
|
|
820
|
+
const done = (alive) => {
|
|
821
|
+
clearTimeout(timer);
|
|
822
|
+
s.destroy();
|
|
823
|
+
resolve(alive);
|
|
824
|
+
};
|
|
825
|
+
const timer = setTimeout(() => done(false), timeoutMs);
|
|
826
|
+
s.once("connect", () => done(true));
|
|
827
|
+
s.once("error", () => done(false));
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
/** A lock younger than this is trusted even if the socket does not answer yet (daemon booting). */
|
|
831
|
+
const LOCK_GRACE_MS = 5e3;
|
|
832
|
+
/**
|
|
833
|
+
* Create the lock file exclusively. The lock records the pid and the socket path of its owner.
|
|
834
|
+
* An existing lock is stale unless its pid is alive and either the socket recorded in the lock
|
|
835
|
+
* answers or the lock is brand new. The recorded socket is probed, not the new daemon's own, so
|
|
836
|
+
* a daemon started with a different socket path is still seen as running. Returns a function that
|
|
837
|
+
* releases the lock.
|
|
838
|
+
*/
|
|
839
|
+
async function acquireLock(lockPath, socketPath) {
|
|
840
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
841
|
+
try {
|
|
842
|
+
writeFileSync(lockPath, JSON.stringify({
|
|
843
|
+
pid: process.pid,
|
|
844
|
+
socketPath
|
|
845
|
+
}), {
|
|
846
|
+
flag: "wx",
|
|
847
|
+
mode: 384
|
|
848
|
+
});
|
|
849
|
+
return () => {
|
|
850
|
+
try {
|
|
851
|
+
unlinkSync(lockPath);
|
|
852
|
+
} catch {}
|
|
853
|
+
};
|
|
854
|
+
} catch (e) {
|
|
855
|
+
if (e.code !== "EEXIST") throw e;
|
|
856
|
+
}
|
|
857
|
+
let pid = 0;
|
|
858
|
+
let lockedSocket = socketPath;
|
|
859
|
+
let ageMs = Number.POSITIVE_INFINITY;
|
|
860
|
+
try {
|
|
861
|
+
const lock = JSON.parse(readFileSync(lockPath, "utf8"));
|
|
862
|
+
pid = lock.pid ?? 0;
|
|
863
|
+
if (typeof lock.socketPath === "string" && lock.socketPath !== "") lockedSocket = lock.socketPath;
|
|
864
|
+
ageMs = Date.now() - statSync(lockPath).mtimeMs;
|
|
865
|
+
} catch {}
|
|
866
|
+
if (pid > 0 && defaultIsAlive(pid) && (ageMs < LOCK_GRACE_MS || await probeSocket(lockedSocket))) throw new DaemonAlreadyRunningError(`pid ${pid}`);
|
|
867
|
+
try {
|
|
868
|
+
unlinkSync(lockPath);
|
|
869
|
+
} catch {}
|
|
870
|
+
}
|
|
871
|
+
throw new DaemonAlreadyRunningError("could not take the lock file");
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* POSIX only: remove a leftover socket file, but only after confirming no live daemon answers on it.
|
|
875
|
+
* Named pipes on Windows vanish with their owner, so there is nothing to remove.
|
|
876
|
+
*/
|
|
877
|
+
async function clearStaleSocket(socketPath) {
|
|
878
|
+
if (process.platform === "win32" || socketPath.startsWith("\\\\")) return;
|
|
879
|
+
if (!existsSync(socketPath)) return;
|
|
880
|
+
if (await probeSocket(socketPath)) throw new DaemonAlreadyRunningError(`socket ${socketPath}`);
|
|
881
|
+
try {
|
|
882
|
+
unlinkSync(socketPath);
|
|
883
|
+
} catch (e) {
|
|
884
|
+
if (e.code !== "ENOENT") throw e;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Read the auth token, creating it (32 random bytes, hex) with mode 0600 on first start, or a
|
|
889
|
+
* user-only ACL on Windows, where the mode is ignored.
|
|
890
|
+
*/
|
|
891
|
+
function loadOrCreateToken(tokenPath) {
|
|
892
|
+
if (existsSync(tokenPath)) {
|
|
893
|
+
const t = readFileSync(tokenPath, "utf8").trim();
|
|
894
|
+
if (t.length >= 32) {
|
|
895
|
+
if (process.platform !== "win32") chmodSync(tokenPath, 384);
|
|
896
|
+
return t;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
const token = randomBytes$1(32).toString("hex");
|
|
900
|
+
writePrivateFileSync(tokenPath, `${token}\n`);
|
|
901
|
+
return token;
|
|
902
|
+
}
|
|
903
|
+
function ensureDir(dir) {
|
|
904
|
+
mkdirSync(dir, {
|
|
905
|
+
recursive: true,
|
|
906
|
+
mode: 448
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
const describeError = (e) => e instanceof Error ? e.stack ?? `${e.name}: ${e.message}` : String(e);
|
|
910
|
+
/**
|
|
911
|
+
* The daemon's own log, for errors it did not expect and for events the owner should be able to
|
|
912
|
+
* see. One file, readable by the user only, with one older generation kept: when the file reaches
|
|
913
|
+
* `maxBytes` it replaces `<path>.1` and a new file starts. Request parameters are never logged,
|
|
914
|
+
* since they can hold message text.
|
|
915
|
+
*/
|
|
916
|
+
function createDaemonLog(path, opts = {}) {
|
|
917
|
+
const maxBytes = opts.maxBytes ?? 1048576;
|
|
918
|
+
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
919
|
+
const append = (text) => {
|
|
920
|
+
try {
|
|
921
|
+
mkdirSync(dirname(path), {
|
|
922
|
+
recursive: true,
|
|
923
|
+
mode: 448
|
|
924
|
+
});
|
|
925
|
+
let size = 0;
|
|
926
|
+
try {
|
|
927
|
+
size = statSync(path).size;
|
|
928
|
+
} catch {}
|
|
929
|
+
if (size >= maxBytes) {
|
|
930
|
+
rmSync(`${path}.1`, { force: true });
|
|
931
|
+
renameSync(path, `${path}.1`);
|
|
932
|
+
}
|
|
933
|
+
appendFileSync(path, text, { mode: 384 });
|
|
934
|
+
if (process.platform !== "win32") chmodSync(path, 384);
|
|
935
|
+
} catch {}
|
|
936
|
+
};
|
|
937
|
+
return {
|
|
938
|
+
path,
|
|
939
|
+
error(what, e) {
|
|
940
|
+
append(`${now().toISOString()} ${what}\n${describeError(e)}\n\n`);
|
|
941
|
+
},
|
|
942
|
+
note(line) {
|
|
943
|
+
append(`${now().toISOString()} ${line.replace(/[\r\n]+/g, " ")}\n`);
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
const DAEMON_VERSION = "0.2.0-rc.18";
|
|
948
|
+
/** A connection that has not finished the handshake by then is closed. */
|
|
949
|
+
const AUTH_TIMEOUT_MS = 5e3;
|
|
950
|
+
/** Sender id on `system` messages made by the daemon itself (no session sent them). */
|
|
951
|
+
const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
|
|
952
|
+
var Daemon = class {
|
|
953
|
+
store;
|
|
954
|
+
token;
|
|
955
|
+
now;
|
|
956
|
+
isAlive;
|
|
957
|
+
idleExitMs;
|
|
958
|
+
requestIdleExit;
|
|
959
|
+
requestShutdown;
|
|
960
|
+
log;
|
|
961
|
+
authTimeoutMs;
|
|
962
|
+
autoLimits;
|
|
963
|
+
processIo;
|
|
964
|
+
platform;
|
|
965
|
+
wakers;
|
|
966
|
+
settingsPath;
|
|
967
|
+
leadLog;
|
|
968
|
+
conns = /* @__PURE__ */ new Set();
|
|
969
|
+
/** Reaches the owner's other devices; set by startDaemon unless disabled. */
|
|
970
|
+
relay;
|
|
971
|
+
deviceId;
|
|
972
|
+
/**
|
|
973
|
+
* The newest idle-wake listener of each session, the ids it replaced, and the connection it
|
|
974
|
+
* asked on. The session counts as wakeable while that connection is open. In memory only.
|
|
975
|
+
*/
|
|
976
|
+
listeners = /* @__PURE__ */ new Map();
|
|
977
|
+
/**
|
|
978
|
+
* Messages the last wake handed each session, until its turn starts or ends. A requeue of
|
|
979
|
+
* these makes the session idle again. In memory only.
|
|
980
|
+
*/
|
|
981
|
+
woken = /* @__PURE__ */ new Map();
|
|
982
|
+
/** Sessions a daemon waker is working on, so one session gets one wake at a time. */
|
|
983
|
+
daemonWaking = /* @__PURE__ */ new Set();
|
|
984
|
+
/** Daemon wakes to try again (after \`failed\` or the wake limit), by session. In memory only. */
|
|
985
|
+
wakeRetry = /* @__PURE__ */ new Map();
|
|
986
|
+
/** Set when the daemon shuts down: closing connections must not touch the store any more. */
|
|
987
|
+
stopping = false;
|
|
988
|
+
/**
|
|
989
|
+
* Sessions whose daemon waker answered \`unsupported\` (no \`queue\` in that binary, an ephemeral
|
|
990
|
+
* thread): not asked again for them while the daemon runs, so a new daemon checks afresh. Other
|
|
991
|
+
* sessions of the same CLI are still woken.
|
|
992
|
+
*/
|
|
993
|
+
wakersOff = /* @__PURE__ */ new Set();
|
|
994
|
+
/** When each session's last daemon wake was handed over, to tell a wake that never became a turn. */
|
|
995
|
+
wokenAt = /* @__PURE__ */ new Map();
|
|
996
|
+
idleSince;
|
|
997
|
+
startedMs;
|
|
998
|
+
/** When each session last sent a message (since this daemon started). */
|
|
999
|
+
lastSent = /* @__PURE__ */ new Map();
|
|
1000
|
+
/** The model label a worker host reported at registration. Memory only. */
|
|
1001
|
+
modelLabels = /* @__PURE__ */ new Map();
|
|
1002
|
+
/** Permission requests of workers that wait for their spawner, by request id. In memory only. */
|
|
1003
|
+
asks = /* @__PURE__ */ new Map();
|
|
1004
|
+
/** When each session went offline, for the removal grace. In memory only. */
|
|
1005
|
+
offlineSince = /* @__PURE__ */ new Map();
|
|
1006
|
+
/**
|
|
1007
|
+
* The MCP processes attached to each session (a window can have several: a reconnect, a thread's
|
|
1008
|
+
* second server). In memory only: a daemon that restarted learns them again, because every
|
|
1009
|
+
* process sends its pid with each heartbeat, and the session's own `pid` seeds the set.
|
|
1010
|
+
*/
|
|
1011
|
+
attached = /* @__PURE__ */ new Map();
|
|
1012
|
+
/** When a hook last touched each session (a turn start or end, a delivery, a bind). In memory only. */
|
|
1013
|
+
hookAt = /* @__PURE__ */ new Map();
|
|
1014
|
+
/**
|
|
1015
|
+
* Sessions retired by an unregister without a pid (a Codex SessionEnd hook, an ACP host exiting).
|
|
1016
|
+
* Their heartbeats are refused, so a leftover MCP process cannot bring them back online.
|
|
1017
|
+
*/
|
|
1018
|
+
retired = /* @__PURE__ */ new Set();
|
|
1019
|
+
constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath, leadLog) {
|
|
1020
|
+
this.store = store;
|
|
1021
|
+
this.token = token;
|
|
1022
|
+
this.now = now;
|
|
1023
|
+
this.isAlive = isAlive;
|
|
1024
|
+
this.idleExitMs = idleExitMs;
|
|
1025
|
+
this.requestIdleExit = requestIdleExit;
|
|
1026
|
+
this.requestShutdown = requestShutdown;
|
|
1027
|
+
this.log = log;
|
|
1028
|
+
this.authTimeoutMs = authTimeoutMs;
|
|
1029
|
+
this.autoLimits = autoLimits;
|
|
1030
|
+
this.processIo = processIo;
|
|
1031
|
+
this.platform = platform;
|
|
1032
|
+
this.wakers = wakers;
|
|
1033
|
+
this.settingsPath = settingsPath;
|
|
1034
|
+
this.leadLog = leadLog;
|
|
1035
|
+
this.deviceId = store.deviceId();
|
|
1036
|
+
this.startedMs = now().getTime();
|
|
1037
|
+
this.idleSince = this.startedMs;
|
|
1038
|
+
}
|
|
1039
|
+
iso = () => this.now().toISOString();
|
|
1040
|
+
};
|
|
1041
|
+
/**
|
|
1042
|
+
* Apply the migrations `db` has not had yet, each in its own transaction, and record each in the
|
|
1043
|
+
* `migrations` table. Used by both of the daemon's databases (conveno.db and relay.db).
|
|
1044
|
+
*/
|
|
1045
|
+
function migrate(db, migrations) {
|
|
1046
|
+
db.exec("CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)");
|
|
1047
|
+
const done = new Set(db.prepare("SELECT name FROM migrations").all().map((r) => r.name));
|
|
1048
|
+
for (const m of migrations) {
|
|
1049
|
+
if (done.has(m.name)) continue;
|
|
1050
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1051
|
+
try {
|
|
1052
|
+
db.exec(m.sql);
|
|
1053
|
+
db.prepare("INSERT INTO migrations (name, applied_at) VALUES (?, ?)").run(m.name, (/* @__PURE__ */ new Date()).toISOString());
|
|
1054
|
+
db.exec("COMMIT");
|
|
1055
|
+
} catch (e) {
|
|
1056
|
+
db.exec("ROLLBACK");
|
|
1057
|
+
throw e;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
/** The names of the migrations `db` has had, in name order. */
|
|
1062
|
+
function migrationNames(db) {
|
|
1063
|
+
return db.prepare("SELECT name FROM migrations ORDER BY name").all().map((r) => r.name);
|
|
1064
|
+
}
|
|
1065
|
+
const MIGRATIONS = [
|
|
1066
|
+
{
|
|
1067
|
+
name: "001_initial",
|
|
1068
|
+
sql: `
|
|
1069
|
+
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
1070
|
+
CREATE TABLE sessions (
|
|
1071
|
+
id TEXT PRIMARY KEY,
|
|
1072
|
+
name TEXT NOT NULL,
|
|
1073
|
+
cli TEXT NOT NULL,
|
|
1074
|
+
cli_version TEXT,
|
|
1075
|
+
device_id TEXT NOT NULL,
|
|
1076
|
+
cwd TEXT NOT NULL,
|
|
1077
|
+
repo_root TEXT,
|
|
1078
|
+
repo_remote_hash TEXT,
|
|
1079
|
+
pid INTEGER,
|
|
1080
|
+
host_pid INTEGER,
|
|
1081
|
+
status TEXT NOT NULL,
|
|
1082
|
+
status_text TEXT,
|
|
1083
|
+
delivery_tier TEXT NOT NULL,
|
|
1084
|
+
spawned_by TEXT,
|
|
1085
|
+
spawn_depth INTEGER NOT NULL DEFAULT 0,
|
|
1086
|
+
started_at TEXT NOT NULL,
|
|
1087
|
+
last_seen_at TEXT NOT NULL
|
|
1088
|
+
);
|
|
1089
|
+
CREATE INDEX sessions_host_pid ON sessions (host_pid);
|
|
1090
|
+
CREATE TABLE messages (
|
|
1091
|
+
id TEXT PRIMARY KEY,
|
|
1092
|
+
json TEXT NOT NULL
|
|
1093
|
+
);
|
|
1094
|
+
CREATE TABLE mailbox (
|
|
1095
|
+
session_id TEXT NOT NULL,
|
|
1096
|
+
message_id TEXT NOT NULL,
|
|
1097
|
+
state TEXT NOT NULL,
|
|
1098
|
+
queued_at TEXT NOT NULL,
|
|
1099
|
+
delivered_at TEXT,
|
|
1100
|
+
read_at TEXT,
|
|
1101
|
+
acked_at TEXT,
|
|
1102
|
+
PRIMARY KEY (session_id, message_id)
|
|
1103
|
+
);
|
|
1104
|
+
CREATE INDEX mailbox_state ON mailbox (session_id, state);
|
|
1105
|
+
CREATE TABLE orchestrator (
|
|
1106
|
+
slot INTEGER PRIMARY KEY CHECK (slot = 1),
|
|
1107
|
+
session_id TEXT
|
|
1108
|
+
);
|
|
1109
|
+
INSERT INTO orchestrator (slot, session_id) VALUES (1, NULL);
|
|
1110
|
+
`
|
|
1111
|
+
},
|
|
1112
|
+
{
|
|
1113
|
+
name: "002_host_pids",
|
|
1114
|
+
sql: `
|
|
1115
|
+
ALTER TABLE sessions ADD COLUMN host_pids TEXT;
|
|
1116
|
+
UPDATE sessions SET host_pids = '[' || host_pid || ']' WHERE host_pid IS NOT NULL;
|
|
1117
|
+
`
|
|
1118
|
+
},
|
|
1119
|
+
{
|
|
1120
|
+
name: "003_spawned",
|
|
1121
|
+
sql: `
|
|
1122
|
+
ALTER TABLE sessions ADD COLUMN spawned INTEGER NOT NULL DEFAULT 0;
|
|
1123
|
+
`
|
|
1124
|
+
},
|
|
1125
|
+
{
|
|
1126
|
+
name: "004_auto_mode",
|
|
1127
|
+
sql: `
|
|
1128
|
+
ALTER TABLE sessions ADD COLUMN auto INTEGER NOT NULL DEFAULT 0;
|
|
1129
|
+
ALTER TABLE sessions ADD COLUMN auto_explicit INTEGER NOT NULL DEFAULT 0;
|
|
1130
|
+
ALTER TABLE sessions ADD COLUMN auto_paused_at TEXT;
|
|
1131
|
+
ALTER TABLE sessions ADD COLUMN auto_paused_by TEXT;
|
|
1132
|
+
ALTER TABLE sessions ADD COLUMN auto_limit INTEGER;
|
|
1133
|
+
ALTER TABLE sessions ADD COLUMN auto_orch_resumed_at TEXT;
|
|
1134
|
+
ALTER TABLE sessions ADD COLUMN auto_runs TEXT NOT NULL DEFAULT '[]';
|
|
1135
|
+
ALTER TABLE sessions ADD COLUMN turn_hops INTEGER NOT NULL DEFAULT 0;
|
|
1136
|
+
ALTER TABLE mailbox ADD COLUMN hops INTEGER NOT NULL DEFAULT 0;
|
|
1137
|
+
`
|
|
1138
|
+
},
|
|
1139
|
+
{
|
|
1140
|
+
name: "005_peek_metadata",
|
|
1141
|
+
sql: `
|
|
1142
|
+
ALTER TABLE sessions ADD COLUMN cli_session_id TEXT;
|
|
1143
|
+
ALTER TABLE sessions ADD COLUMN transcript_path TEXT;
|
|
1144
|
+
ALTER TABLE sessions ADD COLUMN peekable INTEGER NOT NULL DEFAULT 1;
|
|
1145
|
+
`
|
|
1146
|
+
},
|
|
1147
|
+
{
|
|
1148
|
+
name: "006_cleanup",
|
|
1149
|
+
sql: `
|
|
1150
|
+
DROP TABLE IF EXISTS tickets;
|
|
1151
|
+
DROP TABLE IF EXISTS permission_relay;
|
|
1152
|
+
DELETE FROM mailbox WHERE session_id = '${OWNER_SESSION_ID}';
|
|
1153
|
+
DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox);
|
|
1154
|
+
ALTER TABLE sessions DROP COLUMN auto;
|
|
1155
|
+
ALTER TABLE sessions DROP COLUMN auto_explicit;
|
|
1156
|
+
ALTER TABLE sessions DROP COLUMN auto_paused_at;
|
|
1157
|
+
ALTER TABLE sessions DROP COLUMN auto_paused_by;
|
|
1158
|
+
ALTER TABLE sessions DROP COLUMN auto_limit;
|
|
1159
|
+
ALTER TABLE sessions DROP COLUMN auto_orch_resumed_at;
|
|
1160
|
+
ALTER TABLE sessions DROP COLUMN peekable;
|
|
1161
|
+
ALTER TABLE sessions DROP COLUMN cli_session_id;
|
|
1162
|
+
ALTER TABLE sessions DROP COLUMN transcript_path;
|
|
1163
|
+
`
|
|
1164
|
+
},
|
|
1165
|
+
{
|
|
1166
|
+
name: "007_native_id",
|
|
1167
|
+
sql: `
|
|
1168
|
+
ALTER TABLE sessions ADD COLUMN native_id TEXT;
|
|
1169
|
+
CREATE INDEX sessions_native_id ON sessions (native_id);
|
|
1170
|
+
`
|
|
1171
|
+
},
|
|
1172
|
+
{
|
|
1173
|
+
name: "008_variant",
|
|
1174
|
+
sql: "ALTER TABLE sessions ADD COLUMN variant TEXT;"
|
|
1175
|
+
}
|
|
1176
|
+
];
|
|
1177
|
+
const str = (v) => typeof v === "string" ? v : void 0;
|
|
1178
|
+
const num = (v) => typeof v === "number" ? v : void 0;
|
|
1179
|
+
function pidList(v) {
|
|
1180
|
+
if (typeof v !== "string") return void 0;
|
|
1181
|
+
try {
|
|
1182
|
+
const list = JSON.parse(v);
|
|
1183
|
+
if (!Array.isArray(list)) return void 0;
|
|
1184
|
+
const pids = list.filter((p) => Number.isInteger(p) && p > 0);
|
|
1185
|
+
return pids.length > 0 ? pids : void 0;
|
|
1186
|
+
} catch {
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
function isoList(v) {
|
|
1191
|
+
if (typeof v !== "string") return [];
|
|
1192
|
+
try {
|
|
1193
|
+
const list = JSON.parse(v);
|
|
1194
|
+
return Array.isArray(list) ? list.filter((t) => typeof t === "string") : [];
|
|
1195
|
+
} catch {
|
|
1196
|
+
return [];
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
function toSessionRow(r) {
|
|
1200
|
+
const row = {
|
|
1201
|
+
id: r.id,
|
|
1202
|
+
name: r.name,
|
|
1203
|
+
cli: r.cli,
|
|
1204
|
+
deviceId: r.device_id,
|
|
1205
|
+
cwd: r.cwd,
|
|
1206
|
+
status: r.status,
|
|
1207
|
+
deliveryTier: r.delivery_tier,
|
|
1208
|
+
spawned: r.spawned === 1,
|
|
1209
|
+
spawnDepth: r.spawn_depth,
|
|
1210
|
+
autoRuns: isoList(r.auto_runs),
|
|
1211
|
+
turnHops: num(r.turn_hops) ?? 0,
|
|
1212
|
+
startedAt: r.started_at,
|
|
1213
|
+
lastSeenAt: r.last_seen_at
|
|
1214
|
+
};
|
|
1215
|
+
const cliVersion = str(r.cli_version);
|
|
1216
|
+
if (cliVersion !== void 0) row.cliVersion = cliVersion;
|
|
1217
|
+
const repoRoot = str(r.repo_root);
|
|
1218
|
+
if (repoRoot !== void 0) row.repoRoot = repoRoot;
|
|
1219
|
+
const hash = str(r.repo_remote_hash);
|
|
1220
|
+
if (hash !== void 0) row.repoRemoteUrlHash = hash;
|
|
1221
|
+
const pid = num(r.pid);
|
|
1222
|
+
if (pid !== void 0) row.pid = pid;
|
|
1223
|
+
const hostPid = num(r.host_pid);
|
|
1224
|
+
if (hostPid !== void 0) row.hostPid = hostPid;
|
|
1225
|
+
const hostPids = pidList(r.host_pids);
|
|
1226
|
+
if (hostPids !== void 0) row.hostPids = hostPids;
|
|
1227
|
+
const statusText = str(r.status_text);
|
|
1228
|
+
if (statusText !== void 0) row.statusText = statusText;
|
|
1229
|
+
const spawnedBy = str(r.spawned_by);
|
|
1230
|
+
if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
|
|
1231
|
+
const nativeId = str(r.native_id);
|
|
1232
|
+
if (nativeId !== void 0) row.nativeId = nativeId;
|
|
1233
|
+
if (r.variant === "app") row.variant = "app";
|
|
1234
|
+
return row;
|
|
1235
|
+
}
|
|
1236
|
+
/** Wire-format session for a stored row. */
|
|
1237
|
+
function toSession(row, isOrchestrator, unreadCount) {
|
|
1238
|
+
const s = {
|
|
1239
|
+
id: row.id,
|
|
1240
|
+
name: row.name,
|
|
1241
|
+
cli: row.cli,
|
|
1242
|
+
deviceId: row.deviceId,
|
|
1243
|
+
cwd: row.cwd,
|
|
1244
|
+
status: row.status,
|
|
1245
|
+
isOrchestrator,
|
|
1246
|
+
deliveryTier: row.deliveryTier,
|
|
1247
|
+
spawned: row.spawned,
|
|
1248
|
+
spawnDepth: row.spawnDepth,
|
|
1249
|
+
startedAt: row.startedAt,
|
|
1250
|
+
lastSeenAt: row.lastSeenAt
|
|
1251
|
+
};
|
|
1252
|
+
if (unreadCount !== void 0) s.unreadCount = unreadCount;
|
|
1253
|
+
if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
|
|
1254
|
+
if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
|
|
1255
|
+
root: row.repoRoot,
|
|
1256
|
+
remoteUrlHash: row.repoRemoteUrlHash
|
|
1257
|
+
} : { root: row.repoRoot };
|
|
1258
|
+
if (row.pid !== void 0) s.pid = row.pid;
|
|
1259
|
+
if (row.hostPid !== void 0) s.hostPid = row.hostPid;
|
|
1260
|
+
if (row.hostPids !== void 0) s.hostPids = row.hostPids;
|
|
1261
|
+
if (row.statusText !== void 0) s.statusText = row.statusText;
|
|
1262
|
+
if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
|
|
1263
|
+
if (row.nativeId !== void 0) s.nativeId = row.nativeId;
|
|
1264
|
+
if (row.variant !== void 0) s.variant = row.variant;
|
|
1265
|
+
return s;
|
|
1266
|
+
}
|
|
1267
|
+
function toEntry(r) {
|
|
1268
|
+
const entry = {
|
|
1269
|
+
message: Message.parse(JSON.parse(r.json)),
|
|
1270
|
+
state: r.state,
|
|
1271
|
+
queuedAt: r.queued_at
|
|
1272
|
+
};
|
|
1273
|
+
const d = str(r.delivered_at);
|
|
1274
|
+
const rd = str(r.read_at);
|
|
1275
|
+
const a = str(r.acked_at);
|
|
1276
|
+
if (d) entry.deliveredAt = d;
|
|
1277
|
+
if (rd) entry.readAt = rd;
|
|
1278
|
+
if (a) entry.ackedAt = a;
|
|
1279
|
+
const hops = num(r.hops);
|
|
1280
|
+
if (hops !== void 0 && hops > 0) entry.hops = hops;
|
|
1281
|
+
return entry;
|
|
1282
|
+
}
|
|
1283
|
+
/** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
|
|
1284
|
+
var Store = class {
|
|
1285
|
+
db;
|
|
1286
|
+
constructor(path) {
|
|
1287
|
+
this.db = new DatabaseSync(path);
|
|
1288
|
+
this.db.exec("PRAGMA journal_mode = WAL");
|
|
1289
|
+
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
1290
|
+
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
1291
|
+
migrate(this.db, MIGRATIONS);
|
|
1292
|
+
}
|
|
1293
|
+
all(sql, ...params) {
|
|
1294
|
+
return this.db.prepare(sql).all(...params);
|
|
1295
|
+
}
|
|
1296
|
+
run(sql, ...params) {
|
|
1297
|
+
this.db.prepare(sql).run(...params);
|
|
1298
|
+
}
|
|
1299
|
+
tx(fn) {
|
|
1300
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
1301
|
+
try {
|
|
1302
|
+
const out = fn();
|
|
1303
|
+
this.db.exec("COMMIT");
|
|
1304
|
+
return out;
|
|
1305
|
+
} catch (e) {
|
|
1306
|
+
this.db.exec("ROLLBACK");
|
|
1307
|
+
throw e;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
close() {
|
|
1311
|
+
this.db.close();
|
|
1312
|
+
}
|
|
1313
|
+
migrationNames() {
|
|
1314
|
+
return migrationNames(this.db);
|
|
1315
|
+
}
|
|
1316
|
+
/** The device id of this machine, generated on first start. */
|
|
1317
|
+
deviceId() {
|
|
1318
|
+
const r = this.all("SELECT value FROM meta WHERE key = 'device_id'")[0];
|
|
1319
|
+
if (r) return DeviceId.parse(r.value);
|
|
1320
|
+
const id = newDeviceId();
|
|
1321
|
+
this.run("INSERT INTO meta (key, value) VALUES ('device_id', ?)", id);
|
|
1322
|
+
return id;
|
|
1323
|
+
}
|
|
1324
|
+
insertSession(s) {
|
|
1325
|
+
this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
|
|
1326
|
+
pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
|
|
1327
|
+
auto_runs, turn_hops, started_at, last_seen_at, variant)
|
|
1328
|
+
VALUES (?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawned ? 1 : 0, s.spawnDepth, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt, s.variant ?? null);
|
|
1329
|
+
}
|
|
1330
|
+
getSession(id) {
|
|
1331
|
+
const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
|
|
1332
|
+
return r ? toSessionRow(r) : void 0;
|
|
1333
|
+
}
|
|
1334
|
+
/** Every session, oldest first (ids are monotonic ULIDs). */
|
|
1335
|
+
allSessions() {
|
|
1336
|
+
return this.all("SELECT * FROM sessions ORDER BY started_at, id").map(toSessionRow);
|
|
1337
|
+
}
|
|
1338
|
+
updateSession(id, fields) {
|
|
1339
|
+
const sets = [];
|
|
1340
|
+
const vals = [];
|
|
1341
|
+
if (fields.cwd !== void 0) {
|
|
1342
|
+
sets.push("cwd = ?");
|
|
1343
|
+
vals.push(fields.cwd);
|
|
1344
|
+
}
|
|
1345
|
+
if (fields.repoRoot !== void 0) {
|
|
1346
|
+
sets.push("repo_root = ?", "repo_remote_hash = NULL");
|
|
1347
|
+
vals.push(fields.repoRoot);
|
|
1348
|
+
}
|
|
1349
|
+
if (fields.variant !== void 0) {
|
|
1350
|
+
sets.push("variant = ?");
|
|
1351
|
+
vals.push(fields.variant);
|
|
1352
|
+
}
|
|
1353
|
+
if (fields.pid !== void 0) {
|
|
1354
|
+
sets.push("pid = ?");
|
|
1355
|
+
vals.push(fields.pid);
|
|
1356
|
+
}
|
|
1357
|
+
if (fields.nativeId !== void 0) {
|
|
1358
|
+
sets.push("native_id = ?");
|
|
1359
|
+
vals.push(fields.nativeId);
|
|
1360
|
+
}
|
|
1361
|
+
if (fields.turnHops !== void 0) {
|
|
1362
|
+
sets.push("turn_hops = ?");
|
|
1363
|
+
vals.push(fields.turnHops);
|
|
1364
|
+
}
|
|
1365
|
+
if (fields.autoRuns !== void 0) {
|
|
1366
|
+
sets.push("auto_runs = ?");
|
|
1367
|
+
vals.push(JSON.stringify(fields.autoRuns));
|
|
1368
|
+
}
|
|
1369
|
+
if (fields.name !== void 0) {
|
|
1370
|
+
sets.push("name = ?");
|
|
1371
|
+
vals.push(fields.name);
|
|
1372
|
+
}
|
|
1373
|
+
if (fields.status !== void 0) {
|
|
1374
|
+
sets.push("status = ?");
|
|
1375
|
+
vals.push(fields.status);
|
|
1376
|
+
}
|
|
1377
|
+
if (fields.statusText !== void 0) {
|
|
1378
|
+
sets.push("status_text = ?");
|
|
1379
|
+
vals.push(fields.statusText);
|
|
1380
|
+
}
|
|
1381
|
+
if (fields.lastSeenAt !== void 0) {
|
|
1382
|
+
sets.push("last_seen_at = ?");
|
|
1383
|
+
vals.push(fields.lastSeenAt);
|
|
1384
|
+
}
|
|
1385
|
+
if (sets.length === 0) return;
|
|
1386
|
+
this.run(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`, ...vals, id);
|
|
1387
|
+
}
|
|
1388
|
+
holder() {
|
|
1389
|
+
const r = this.all("SELECT session_id FROM orchestrator WHERE slot = 1")[0];
|
|
1390
|
+
return str(r?.session_id) ?? null;
|
|
1391
|
+
}
|
|
1392
|
+
setHolder(id) {
|
|
1393
|
+
this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
|
|
1394
|
+
}
|
|
1395
|
+
/** `hops`: automatic turns behind the message (the wake limit counts them). */
|
|
1396
|
+
insertMessage(message, recipient, at, hops = 0) {
|
|
1397
|
+
this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
|
|
1398
|
+
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
|
|
1399
|
+
}
|
|
1400
|
+
/** Messages queued for a session that no one has been shown yet. */
|
|
1401
|
+
unreadCount(sessionId) {
|
|
1402
|
+
const r = this.all("SELECT COUNT(*) AS n FROM mailbox WHERE session_id = ? AND state = 'queued'", sessionId)[0];
|
|
1403
|
+
return num(r?.n) ?? 0;
|
|
1404
|
+
}
|
|
1405
|
+
hasMessage(id) {
|
|
1406
|
+
return this.all("SELECT 1 AS x FROM messages WHERE id = ?", id).length > 0;
|
|
1407
|
+
}
|
|
1408
|
+
/** Move every mailbox entry of `from` to `to`. An entry `to` already has stays as it is. */
|
|
1409
|
+
moveMailbox(from, to) {
|
|
1410
|
+
this.run("UPDATE OR IGNORE mailbox SET session_id = ? WHERE session_id = ?", to, from);
|
|
1411
|
+
}
|
|
1412
|
+
/** Remove a session, its mailbox, and any message no mailbox refers to any more. */
|
|
1413
|
+
deleteSession(id) {
|
|
1414
|
+
this.run("DELETE FROM mailbox WHERE session_id = ?", id);
|
|
1415
|
+
this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
|
|
1416
|
+
this.run("DELETE FROM sessions WHERE id = ?", id);
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* The newest `limit` messages from one session to another, newest first, with who got each.
|
|
1420
|
+
* Never system messages, nor ones to or from the owner.
|
|
1421
|
+
*/
|
|
1422
|
+
recentMessages(limit) {
|
|
1423
|
+
return this.all(`SELECT m.json, b.session_id FROM mailbox b JOIN messages m ON m.id = b.message_id
|
|
1424
|
+
WHERE b.session_id != ? AND json_extract(m.json, '$.kind') != 'system'
|
|
1425
|
+
AND json_extract(m.json, '$.from') != ?
|
|
1426
|
+
ORDER BY b.queued_at DESC, b.rowid DESC LIMIT ?`, OWNER_SESSION_ID, OWNER_SESSION_ID, limit).map((r) => ({
|
|
1427
|
+
message: Message.parse(JSON.parse(r.json)),
|
|
1428
|
+
recipient: r.session_id
|
|
1429
|
+
}));
|
|
1430
|
+
}
|
|
1431
|
+
/** Mailbox entries of one session, optionally limited to the given states or message ids. */
|
|
1432
|
+
entries(sessionId, filter = {}) {
|
|
1433
|
+
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
|
|
1434
|
+
FROM mailbox b JOIN messages m ON m.id = b.message_id WHERE b.session_id = ?`;
|
|
1435
|
+
const params = [sessionId];
|
|
1436
|
+
if (filter.states) {
|
|
1437
|
+
sql += ` AND b.state IN (${filter.states.map(() => "?").join(",")})`;
|
|
1438
|
+
params.push(...filter.states);
|
|
1439
|
+
}
|
|
1440
|
+
if (filter.ids) {
|
|
1441
|
+
sql += ` AND b.message_id IN (${filter.ids.map(() => "?").join(",")})`;
|
|
1442
|
+
params.push(...filter.ids);
|
|
1443
|
+
}
|
|
1444
|
+
return this.all(sql, ...params).map(toEntry);
|
|
1445
|
+
}
|
|
1446
|
+
saveEntry(sessionId, e) {
|
|
1447
|
+
this.run(`UPDATE mailbox SET state = ?, delivered_at = ?, read_at = ?, acked_at = ?
|
|
1448
|
+
WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
|
|
1449
|
+
}
|
|
1450
|
+
};
|
|
1451
|
+
/** The orchestrator as routing sees it: the holder, if it is online. */
|
|
1452
|
+
function orchestratorNow(daemon) {
|
|
1453
|
+
return effectiveHolder(daemon.store.holder(), namedOf(daemon.store.allSessions()))?.id ?? null;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* The saved preferred lead CLI takes the lead when it registers and nobody online leads. The
|
|
1457
|
+
* settings are read on each register, so a change needs no restart. It is the normal claim.
|
|
1458
|
+
*/
|
|
1459
|
+
function claimPreferredLead(daemon, row) {
|
|
1460
|
+
if (daemon.settingsPath === void 0) return;
|
|
1461
|
+
const settings = readSettings(daemon.settingsPath);
|
|
1462
|
+
if (settings.leadCli !== row.cli) return;
|
|
1463
|
+
if (settings.tools && !settings.tools.includes(row.cli)) return;
|
|
1464
|
+
if (orchestratorNow(daemon) !== null) return;
|
|
1465
|
+
claim(daemon, row.id, "preferred");
|
|
1466
|
+
}
|
|
1467
|
+
function leadName(daemon, id) {
|
|
1468
|
+
return id ? daemon.store.getSession(id)?.name ?? null : null;
|
|
1469
|
+
}
|
|
1470
|
+
/** One line in `<dataDir>/logs/lead.log` when the holder changed. Never throws. */
|
|
1471
|
+
function logLead(daemon, previous, before, after, via) {
|
|
1472
|
+
if (before === after || !daemon.leadLog) return;
|
|
1473
|
+
try {
|
|
1474
|
+
appendHookLog(daemon.leadLog, leadLogLine({
|
|
1475
|
+
at: daemon.now(),
|
|
1476
|
+
lead: leadName(daemon, after),
|
|
1477
|
+
previous,
|
|
1478
|
+
via
|
|
1479
|
+
}));
|
|
1480
|
+
} catch {}
|
|
1481
|
+
}
|
|
1482
|
+
function claim(daemon, sessionId, via) {
|
|
1483
|
+
requireSession(daemon, sessionId);
|
|
1484
|
+
const rows = daemon.store.allSessions();
|
|
1485
|
+
const holder = daemon.store.holder();
|
|
1486
|
+
const res = claimOrchestrator(holder, sessionId, namedOf(rows));
|
|
1487
|
+
const prevName = leadName(daemon, holder);
|
|
1488
|
+
const at = daemon.iso();
|
|
1489
|
+
const sent = [];
|
|
1490
|
+
daemon.store.tx(() => {
|
|
1491
|
+
daemon.store.setHolder(res.orchestrator);
|
|
1492
|
+
for (const n of res.notices) {
|
|
1493
|
+
const m = {
|
|
1494
|
+
id: newMessageId(),
|
|
1495
|
+
from: DAEMON_SENDER_ID,
|
|
1496
|
+
to: n.to,
|
|
1497
|
+
kind: "system",
|
|
1498
|
+
body: {
|
|
1499
|
+
event: n.event,
|
|
1500
|
+
detail: n.detail
|
|
1501
|
+
},
|
|
1502
|
+
urgent: false,
|
|
1503
|
+
createdAt: at
|
|
1504
|
+
};
|
|
1505
|
+
daemon.store.insertMessage(m, n.to, at);
|
|
1506
|
+
sent.push(m);
|
|
1507
|
+
}
|
|
1508
|
+
});
|
|
1509
|
+
logLead(daemon, prevName, holder, res.orchestrator, via);
|
|
1510
|
+
if (res.notices.length > 0) {
|
|
1511
|
+
emit(daemon, {
|
|
1512
|
+
event: "orchestrator.changed",
|
|
1513
|
+
data: {
|
|
1514
|
+
orchestrator: res.orchestrator,
|
|
1515
|
+
previous: res.previous
|
|
1516
|
+
}
|
|
1517
|
+
});
|
|
1518
|
+
emitSession(daemon, sessionId, "updated");
|
|
1519
|
+
if (res.previous) emitSession(daemon, res.previous, "updated");
|
|
1520
|
+
for (const m of sent) emitMessage(daemon, m, m.to);
|
|
1521
|
+
}
|
|
1522
|
+
return {
|
|
1523
|
+
orchestrator: res.orchestrator,
|
|
1524
|
+
previous: res.previous
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
function clearLead(daemon, conn) {
|
|
1528
|
+
requireCli(conn, "clear the lead");
|
|
1529
|
+
const holder = daemon.store.holder();
|
|
1530
|
+
const res = clearOrchestrator(holder, namedOf(daemon.store.allSessions()));
|
|
1531
|
+
const prevName = leadName(daemon, holder);
|
|
1532
|
+
const at = daemon.iso();
|
|
1533
|
+
const sent = [];
|
|
1534
|
+
daemon.store.tx(() => {
|
|
1535
|
+
daemon.store.setHolder(null);
|
|
1536
|
+
for (const n of res.notices) {
|
|
1537
|
+
const m = {
|
|
1538
|
+
id: newMessageId(),
|
|
1539
|
+
from: DAEMON_SENDER_ID,
|
|
1540
|
+
to: n.to,
|
|
1541
|
+
kind: "system",
|
|
1542
|
+
body: {
|
|
1543
|
+
event: n.event,
|
|
1544
|
+
detail: n.detail
|
|
1545
|
+
},
|
|
1546
|
+
urgent: false,
|
|
1547
|
+
createdAt: at
|
|
1548
|
+
};
|
|
1549
|
+
daemon.store.insertMessage(m, n.to, at);
|
|
1550
|
+
sent.push(m);
|
|
1551
|
+
}
|
|
1552
|
+
});
|
|
1553
|
+
logLead(daemon, prevName, holder, null, "clear");
|
|
1554
|
+
if (holder !== null) {
|
|
1555
|
+
emit(daemon, {
|
|
1556
|
+
event: "orchestrator.changed",
|
|
1557
|
+
data: {
|
|
1558
|
+
orchestrator: null,
|
|
1559
|
+
previous: holder
|
|
1560
|
+
}
|
|
1561
|
+
});
|
|
1562
|
+
if (res.previous) emitSession(daemon, res.previous, "updated");
|
|
1563
|
+
for (const m of sent) emitMessage(daemon, m, m.to);
|
|
1564
|
+
}
|
|
1565
|
+
return { previous: res.previous };
|
|
1566
|
+
}
|
|
1567
|
+
/** Permission requests one worker may have waiting at once. */
|
|
1568
|
+
const MAX_ASKS_PER_WORKER = 5;
|
|
1569
|
+
/**
|
|
1570
|
+
* A worker asks its spawner to allow a tool call. Resolves when the spawner answers, when
|
|
1571
|
+
* `timeoutMs` passes, or when the worker goes away. The request lives in memory only.
|
|
1572
|
+
*/
|
|
1573
|
+
function permissionAsk(daemon, p) {
|
|
1574
|
+
const worker = requireOnline(daemon, p.sessionId);
|
|
1575
|
+
const spawner = worker.spawnedBy ? daemon.store.getSession(worker.spawnedBy) : void 0;
|
|
1576
|
+
if (!spawner || spawner.status === "offline") return Promise.resolve({ answer: "no_spawner" });
|
|
1577
|
+
let mine = 0;
|
|
1578
|
+
for (const a of daemon.asks.values()) if (a.worker === worker.id) mine++;
|
|
1579
|
+
if (mine >= MAX_ASKS_PER_WORKER) throw new ConvenoError(RpcErrorCode.LimitExceeded, `Session "${worker.name}" already has ${mine} permission requests waiting. Wait for an answer.`);
|
|
1580
|
+
let id = randomBytes$1(4).toString("base64url").slice(0, 6);
|
|
1581
|
+
while (daemon.asks.has(id)) id = randomBytes$1(4).toString("base64url").slice(0, 6);
|
|
1582
|
+
const what = `${p.title ?? "a tool call"} (${p.kind ?? "other"})`;
|
|
1583
|
+
const fallback = p.unanswered === "allow" ? "allow" : "deny";
|
|
1584
|
+
const at = daemon.iso();
|
|
1585
|
+
const m = {
|
|
1586
|
+
id: newMessageId(),
|
|
1587
|
+
from: DAEMON_SENDER_ID,
|
|
1588
|
+
to: spawner.id,
|
|
1589
|
+
kind: "system",
|
|
1590
|
+
body: {
|
|
1591
|
+
event: "permission.asked",
|
|
1592
|
+
detail: `${worker.name} wants to run: ${what}. Answer with the answer_permission tool: request ${id}, answer allow, always or deny. No answer in ${p.timeoutMs >= 6e4 && p.timeoutMs % 6e4 === 0 ? `${p.timeoutMs / 6e4} min` : `${Math.round(p.timeoutMs / 1e3)} s`}: ${fallback}.`
|
|
1593
|
+
},
|
|
1594
|
+
urgent: false,
|
|
1595
|
+
createdAt: at
|
|
1596
|
+
};
|
|
1597
|
+
daemon.store.insertMessage(m, spawner.id, at);
|
|
1598
|
+
emitMessage(daemon, m, spawner.id);
|
|
1599
|
+
return new Promise((resolve) => {
|
|
1600
|
+
const timer = setTimeout(() => settleAsk(daemon, id, { answer: "unanswered" }), p.timeoutMs);
|
|
1601
|
+
timer.unref();
|
|
1602
|
+
daemon.asks.set(id, {
|
|
1603
|
+
worker: worker.id,
|
|
1604
|
+
spawner: spawner.id,
|
|
1605
|
+
resolve,
|
|
1606
|
+
timer
|
|
1607
|
+
});
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
function permissionAnswer(daemon, p) {
|
|
1611
|
+
requireOnline(daemon, p.sessionId);
|
|
1612
|
+
const ask = daemon.asks.get(p.requestId);
|
|
1613
|
+
if (!ask) throw new ConvenoError(RpcErrorCode.NotFound, `No permission request "${p.requestId}". It was already answered, or it expired.`);
|
|
1614
|
+
if (ask.spawner !== p.sessionId) throw new ConvenoError(RpcErrorCode.PermissionRequired, `Only the session that spawned the worker can answer request "${p.requestId}".`);
|
|
1615
|
+
settleAsk(daemon, p.requestId, {
|
|
1616
|
+
answer: p.answer,
|
|
1617
|
+
by: p.sessionId
|
|
1618
|
+
});
|
|
1619
|
+
return { ok: true };
|
|
1620
|
+
}
|
|
1621
|
+
function settleAsk(daemon, id, result) {
|
|
1622
|
+
const ask = daemon.asks.get(id);
|
|
1623
|
+
if (!ask) return;
|
|
1624
|
+
daemon.asks.delete(id);
|
|
1625
|
+
clearTimeout(ask.timer);
|
|
1626
|
+
ask.resolve(result);
|
|
1627
|
+
}
|
|
1628
|
+
/** The worker left: its waiting requests end as `worker_offline`. */
|
|
1629
|
+
function settleAsksOf(daemon, worker) {
|
|
1630
|
+
for (const [id, a] of daemon.asks) if (a.worker === worker) settleAsk(daemon, id, { answer: "worker_offline" });
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* The user typed a prompt: the session is busy, and messages it sends start a new chain (0 hops).
|
|
1634
|
+
*/
|
|
1635
|
+
function turnStart(daemon, sessionId) {
|
|
1636
|
+
const row = requireOnline(daemon, sessionId);
|
|
1637
|
+
touchHook(daemon, sessionId);
|
|
1638
|
+
const fromWake = daemon.woken.has(sessionId) && row.status === "busy";
|
|
1639
|
+
daemon.woken.delete(sessionId);
|
|
1640
|
+
daemon.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
|
|
1641
|
+
status: "busy",
|
|
1642
|
+
turnHops: 0
|
|
1643
|
+
});
|
|
1644
|
+
emitSession(daemon, sessionId, "updated");
|
|
1645
|
+
return { session: view(daemon, requireSession(daemon, sessionId)) };
|
|
1646
|
+
}
|
|
1647
|
+
/**
|
|
1648
|
+
* Hand the session its waiting messages to continue with, if the wake limit allows it.
|
|
1649
|
+
* On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
|
|
1650
|
+
* handed over means the session is now idle. One transaction.
|
|
1651
|
+
*/
|
|
1652
|
+
function continueWith(daemon, row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES, maxChars) {
|
|
1653
|
+
const nowMs = daemon.now().getTime();
|
|
1654
|
+
const at = daemon.iso();
|
|
1655
|
+
const orchestrator = orchestratorNow(daemon);
|
|
1656
|
+
const res = daemon.store.tx(() => {
|
|
1657
|
+
const queued = daemon.store.entries(row.id, { states: ["queued"] });
|
|
1658
|
+
const candidates = allow ? autoCandidates(queued, row.id) : [];
|
|
1659
|
+
const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, daemon.autoLimits);
|
|
1660
|
+
if (decision.continue) {
|
|
1661
|
+
const fit = takeWithinBytes(candidates.slice(0, 20), maxBytes);
|
|
1662
|
+
const { taken, preview } = maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, maxChars, (ms, cut) => formatContinuation(ms, orchestrator, queued.length - (cut ? 0 : ms.length)));
|
|
1663
|
+
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
1664
|
+
for (const e of updated) daemon.store.saveEntry(row.id, e);
|
|
1665
|
+
daemon.store.updateSession(row.id, {
|
|
1666
|
+
status: "busy",
|
|
1667
|
+
autoRuns: decision.runs,
|
|
1668
|
+
turnHops: turnHops(preview ? fit.slice(0, 1) : taken)
|
|
1669
|
+
});
|
|
1670
|
+
if (preview) return {
|
|
1671
|
+
messages: [preview],
|
|
1672
|
+
remaining: queued.length
|
|
1673
|
+
};
|
|
1674
|
+
return {
|
|
1675
|
+
messages: updated.map((e) => e.message),
|
|
1676
|
+
remaining: queued.length - taken.length
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
if (endOfTurn) daemon.store.updateSession(row.id, {
|
|
1680
|
+
status: "idle",
|
|
1681
|
+
turnHops: 0
|
|
1682
|
+
});
|
|
1683
|
+
return {
|
|
1684
|
+
messages: [],
|
|
1685
|
+
remaining: queued.length
|
|
1686
|
+
};
|
|
1687
|
+
});
|
|
1688
|
+
if (res.messages.length > 0) touchHook(daemon, row.id);
|
|
1689
|
+
if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") emitSession(daemon, row.id, "updated");
|
|
1690
|
+
return {
|
|
1691
|
+
...res,
|
|
1692
|
+
orchestrator
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
function turnEnd(daemon, p) {
|
|
1696
|
+
const row = requireOnline(daemon, p.sessionId);
|
|
1697
|
+
touchHook(daemon, p.sessionId);
|
|
1698
|
+
daemon.woken.delete(p.sessionId);
|
|
1699
|
+
if (row.status === "waiting_on_question") return continueWith(daemon, row, false, false);
|
|
1700
|
+
return continueWith(daemon, row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
|
|
1704
|
+
* `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
|
|
1705
|
+
*/
|
|
1706
|
+
function turnWake(daemon, conn, p) {
|
|
1707
|
+
const row = requireOnline(daemon, p.sessionId);
|
|
1708
|
+
if (p.nativeId !== void 0 && row.nativeId !== void 0 && p.nativeId !== row.nativeId) return {
|
|
1709
|
+
messages: [],
|
|
1710
|
+
remaining: daemon.store.unreadCount(row.id),
|
|
1711
|
+
orchestrator: orchestratorNow(daemon),
|
|
1712
|
+
superseded: true
|
|
1713
|
+
};
|
|
1714
|
+
const known = daemon.listeners.get(row.id);
|
|
1715
|
+
if (known?.retired.includes(p.listenerId)) return {
|
|
1716
|
+
messages: [],
|
|
1717
|
+
remaining: daemon.store.unreadCount(row.id),
|
|
1718
|
+
orchestrator: orchestratorNow(daemon),
|
|
1719
|
+
superseded: true
|
|
1720
|
+
};
|
|
1721
|
+
const wasConnected = listenerConnected(daemon, row.id);
|
|
1722
|
+
if (known?.current !== p.listenerId) {
|
|
1723
|
+
const retired = known ? [...known.retired, known.current].slice(-64) : [];
|
|
1724
|
+
daemon.listeners.set(row.id, {
|
|
1725
|
+
current: p.listenerId,
|
|
1726
|
+
retired,
|
|
1727
|
+
conn
|
|
1728
|
+
});
|
|
1729
|
+
if (known) emit(daemon, {
|
|
1730
|
+
event: "session.updated",
|
|
1731
|
+
data: {
|
|
1732
|
+
session: view(daemon, row),
|
|
1733
|
+
change: "updated"
|
|
1734
|
+
}
|
|
1735
|
+
}, row.id);
|
|
1736
|
+
} else known.conn = conn;
|
|
1737
|
+
if (!wasConnected) daemon.relay?.sessionsChanged();
|
|
1738
|
+
const d = continueWith(daemon, row, row.status === "idle", false, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
1739
|
+
if (d.messages.length > 0) markWoken(daemon, row.id, d.messages);
|
|
1740
|
+
return {
|
|
1741
|
+
...d,
|
|
1742
|
+
superseded: false
|
|
1743
|
+
};
|
|
1744
|
+
}
|
|
1745
|
+
/** Message bytes one daemon wake hands over: the text goes on a command line (\`codex queue\`). */
|
|
1746
|
+
const DAEMON_WAKE_BYTES = 16e3;
|
|
1747
|
+
/** First wait before a daemon wake is tried again; doubles up to the max. */
|
|
1748
|
+
const WAKE_RETRY_MS = 15e3;
|
|
1749
|
+
/** A wake still not a turn after this long counts as unread in status (see `stalledWoken`). */
|
|
1750
|
+
const WOKEN_STALL_MS = 3e4;
|
|
1751
|
+
const WAKE_RETRY_MAX_MS = 3e5;
|
|
1752
|
+
/**
|
|
1753
|
+
* \`acp\` for an ACP host. \`live\` while something can wake the session: a listener's connection
|
|
1754
|
+
* is open, or the session is busy in a turn a listener's CLI ends with its own hook (it continues
|
|
1755
|
+
* with what waits, then arms a new listener), or a daemon waker can reach it. Otherwise the CLI's
|
|
1756
|
+
* own tier.
|
|
1757
|
+
*/
|
|
1758
|
+
function tierFor(daemon, row) {
|
|
1759
|
+
if (row.deliveryTier === "acp") return "acp";
|
|
1760
|
+
if (listenerConnected(daemon, row.id)) return "live";
|
|
1761
|
+
if (row.status === "busy" && daemon.listeners.has(row.id)) return "live";
|
|
1762
|
+
if (daemonWakerFor(daemon, row)) return "live";
|
|
1763
|
+
return row.deliveryTier;
|
|
1764
|
+
}
|
|
1765
|
+
function listenerConnected(daemon, id) {
|
|
1766
|
+
const conn = daemon.listeners.get(id)?.conn;
|
|
1767
|
+
return conn !== void 0 && daemon.conns.has(conn) && !conn.socket.destroyed;
|
|
1768
|
+
}
|
|
1769
|
+
/** A connection closed: a listener that asked on it no longer makes its session wakeable. */
|
|
1770
|
+
function listenerGone(daemon, conn) {
|
|
1771
|
+
if (daemon.stopping) return;
|
|
1772
|
+
for (const [id, rec] of daemon.listeners) {
|
|
1773
|
+
if (rec.conn !== conn) continue;
|
|
1774
|
+
rec.conn = void 0;
|
|
1775
|
+
emitSession(daemon, id, "updated");
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
function daemonWakerFor(daemon, row) {
|
|
1779
|
+
if (row.nativeId === void 0 || daemon.wakersOff.has(row.id)) return void 0;
|
|
1780
|
+
return daemon.wakers[row.cli];
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* A message landed for \`id\`. When its CLI has a daemon waker, no listener is connected and the
|
|
1784
|
+
* session is idle, hand the waiting messages to the waker (under the wake limit, like
|
|
1785
|
+
* \`turn.wake\`, and under \`DAEMON_WAKE_BYTES\`, since they go on a command line). \`queued\`
|
|
1786
|
+
* and \`unknown\` keep them delivered (a wake that timed out may have landed: a requeue could
|
|
1787
|
+
* deliver them twice). \`failed\` and \`unsupported\` put them back; after \`failed\` or the wake
|
|
1788
|
+
* limit, the sweep tries again with a growing delay. One wake per session at a time.
|
|
1789
|
+
*/
|
|
1790
|
+
function daemonWake(daemon, id) {
|
|
1791
|
+
if (daemon.daemonWaking.has(id)) return;
|
|
1792
|
+
const row = daemon.store.getSession(id);
|
|
1793
|
+
const wake = row?.status === "idle" && !listenerConnected(daemon, id) && daemonWakerFor(daemon, row);
|
|
1794
|
+
if (!row || !wake) {
|
|
1795
|
+
daemon.wakeRetry.delete(id);
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
const d = continueWith(daemon, row, true, false, DAEMON_WAKE_BYTES);
|
|
1799
|
+
if (d.messages.length === 0) {
|
|
1800
|
+
const queued = daemon.store.entries(id, { states: ["queued"] });
|
|
1801
|
+
if (autoCandidates(queued, id).length > 0) scheduleWakeRetry(daemon, id);
|
|
1802
|
+
else daemon.wakeRetry.delete(id);
|
|
1803
|
+
return;
|
|
1804
|
+
}
|
|
1805
|
+
markWoken(daemon, id, d.messages);
|
|
1806
|
+
daemon.daemonWaking.add(id);
|
|
1807
|
+
const text = formatContinuation(d.messages, d.orchestrator, d.remaining);
|
|
1808
|
+
const session = view(daemon, requireSession(daemon, id));
|
|
1809
|
+
(async () => {
|
|
1810
|
+
let outcome;
|
|
1811
|
+
try {
|
|
1812
|
+
outcome = await wake({
|
|
1813
|
+
session,
|
|
1814
|
+
text,
|
|
1815
|
+
messages: d.messages,
|
|
1816
|
+
...row.nativeId !== void 0 ? { nativeId: row.nativeId } : {}
|
|
1817
|
+
});
|
|
1818
|
+
} catch (e) {
|
|
1819
|
+
daemon.log.error(`${row.cli} waker failed`, e);
|
|
1820
|
+
outcome = "failed";
|
|
1821
|
+
}
|
|
1822
|
+
daemon.daemonWaking.delete(id);
|
|
1823
|
+
if (outcome === "queued" || outcome === "unknown" || daemon.stopping) {
|
|
1824
|
+
daemon.wakeRetry.delete(id);
|
|
1825
|
+
return;
|
|
1826
|
+
}
|
|
1827
|
+
if (outcome === "unsupported") {
|
|
1828
|
+
daemon.wakeRetry.delete(id);
|
|
1829
|
+
daemon.wakersOff.add(row.id);
|
|
1830
|
+
daemon.relay?.sessionsChanged();
|
|
1831
|
+
}
|
|
1832
|
+
if (daemon.store.getSession(id)?.status === "offline") {
|
|
1833
|
+
daemon.wakeRetry.delete(id);
|
|
1834
|
+
return;
|
|
1835
|
+
}
|
|
1836
|
+
requeueFor(daemon, id, d.messages.map((m) => m.id));
|
|
1837
|
+
if (outcome === "failed") scheduleWakeRetry(daemon, id);
|
|
1838
|
+
})();
|
|
1839
|
+
}
|
|
1840
|
+
/** Try a daemon wake of \`id\` again later, each time waiting twice as long, up to a cap. */
|
|
1841
|
+
function scheduleWakeRetry(daemon, id) {
|
|
1842
|
+
const delayMs = Math.min((daemon.wakeRetry.get(id)?.delayMs ?? 0) * 2 || WAKE_RETRY_MS, WAKE_RETRY_MAX_MS);
|
|
1843
|
+
daemon.wakeRetry.set(id, {
|
|
1844
|
+
atMs: daemon.now().getTime() + delayMs,
|
|
1845
|
+
delayMs
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
/** Run the daemon wakes whose retry is due. Called by the sweep. */
|
|
1849
|
+
function retryDaemonWakes(daemon, nowMs) {
|
|
1850
|
+
for (const [id, r] of [...daemon.wakeRetry]) if (r.atMs <= nowMs) daemonWake(daemon, id);
|
|
1851
|
+
}
|
|
1852
|
+
function markWoken(daemon, id, messages) {
|
|
1853
|
+
daemon.woken.set(id, new Set(messages.map((m) => m.id)));
|
|
1854
|
+
daemon.wokenAt.set(id, daemon.now().getTime());
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Messages a wake handed over that no turn took up: the CLI accepted them but the turn never
|
|
1858
|
+
* started (Codex keeps queued input while a turn is interrupted). Counted as unread so status
|
|
1859
|
+
* shows them. A turn start or end clears \`woken\`.
|
|
1860
|
+
*/
|
|
1861
|
+
function stalledWoken(daemon, id) {
|
|
1862
|
+
const at = daemon.wokenAt.get(id);
|
|
1863
|
+
if (at === void 0 || daemon.now().getTime() - at < WOKEN_STALL_MS) return 0;
|
|
1864
|
+
return daemon.woken.get(id)?.size ?? 0;
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Delivered messages go back to queued. When they are from the last wake and that wake made the
|
|
1868
|
+
* session busy, the wake never became a turn: the session is idle again and the wake does not
|
|
1869
|
+
* count against the limit.
|
|
1870
|
+
*/
|
|
1871
|
+
function requeue(daemon, p) {
|
|
1872
|
+
requireSession(daemon, p.sessionId);
|
|
1873
|
+
return requeueFor(daemon, p.sessionId, p.ids);
|
|
1874
|
+
}
|
|
1875
|
+
function requeueFor(daemon, id, ids) {
|
|
1876
|
+
const woken = daemon.woken.get(id);
|
|
1877
|
+
const fromWake = woken !== void 0 && ids.some((m) => woken.has(m));
|
|
1878
|
+
const res = daemon.store.tx(() => {
|
|
1879
|
+
const r = requeueEntries(daemon.store.entries(id, { ids: [...ids] }), ids);
|
|
1880
|
+
for (const e of r.changed) daemon.store.saveEntry(id, e);
|
|
1881
|
+
const row = requireSession(daemon, id);
|
|
1882
|
+
const idle = fromWake && r.changed.length > 0 && row.status === "busy";
|
|
1883
|
+
if (idle) daemon.store.updateSession(id, {
|
|
1884
|
+
status: "idle",
|
|
1885
|
+
turnHops: 0,
|
|
1886
|
+
autoRuns: row.autoRuns.slice(0, -1)
|
|
1887
|
+
});
|
|
1888
|
+
return {
|
|
1889
|
+
requeued: r.changed.length,
|
|
1890
|
+
idle
|
|
1891
|
+
};
|
|
1892
|
+
});
|
|
1893
|
+
if (fromWake) daemon.woken.delete(id);
|
|
1894
|
+
if (res.idle) emitSession(daemon, id, "updated");
|
|
1895
|
+
return { requeued: res.requeued };
|
|
1896
|
+
}
|
|
1897
|
+
function namedOf(rows) {
|
|
1898
|
+
return rows.map((r) => ({
|
|
1899
|
+
id: r.id,
|
|
1900
|
+
name: r.name,
|
|
1901
|
+
status: r.status
|
|
1902
|
+
}));
|
|
1903
|
+
}
|
|
1904
|
+
function requireSession(daemon, id) {
|
|
1905
|
+
const row = daemon.store.getSession(id);
|
|
1906
|
+
if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${id}. Register the session again.`);
|
|
1907
|
+
return row;
|
|
1908
|
+
}
|
|
1909
|
+
function requireOnline(daemon, id) {
|
|
1910
|
+
const row = requireSession(daemon, id);
|
|
1911
|
+
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
1912
|
+
return row;
|
|
1913
|
+
}
|
|
1914
|
+
/** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
|
|
1915
|
+
function view(daemon, row) {
|
|
1916
|
+
const holder = effectiveHolder(daemon.store.holder(), namedOf([row]));
|
|
1917
|
+
const tier = tierFor(daemon, row);
|
|
1918
|
+
return {
|
|
1919
|
+
...toSession({
|
|
1920
|
+
...row,
|
|
1921
|
+
deliveryTier: tier
|
|
1922
|
+
}, holder?.id === row.id, daemon.store.unreadCount(row.id) + stalledWoken(daemon, row.id)),
|
|
1923
|
+
wakeable: tier === "live" || tier === "acp",
|
|
1924
|
+
...daemon.lastSent.has(row.id) ? { lastSentAt: daemon.lastSent.get(row.id) } : {},
|
|
1925
|
+
...daemon.modelLabels.has(row.id) ? { model: daemon.modelLabels.get(row.id) } : {}
|
|
1926
|
+
};
|
|
1927
|
+
}
|
|
1928
|
+
async function detect(p) {
|
|
1929
|
+
if (p.repo) return p.repo;
|
|
1930
|
+
const found = await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
|
|
1931
|
+
return found.root ? { root: found.root } : void 0;
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* The session an MCP server of a one-window-per-host CLI attaches to: the online, non-ACP
|
|
1935
|
+
* session of the same CLI under the same host process (and in the same folder, for OpenCode,
|
|
1936
|
+
* whose server hosts every folder).
|
|
1937
|
+
*/
|
|
1938
|
+
function attachTarget(daemon, p) {
|
|
1939
|
+
if (p.acp || p.hostPid === void 0 || !oneWindowPerHost(p.cli)) return void 0;
|
|
1940
|
+
return daemon.store.allSessions().find((r) => r.status !== "offline" && r.cli === p.cli && r.deliveryTier !== "acp" && r.hostPid === p.hostPid && (p.cli !== "opencode" || samePath(r.cwd, p.cwd, daemon.platform)));
|
|
1941
|
+
}
|
|
1942
|
+
/** The MCP pids attached to a session; seeded with the pid it registered with. */
|
|
1943
|
+
function attachedOf(daemon, row) {
|
|
1944
|
+
let set = daemon.attached.get(row.id);
|
|
1945
|
+
if (!set) {
|
|
1946
|
+
set = new Set(row.pid === void 0 ? [] : [row.pid]);
|
|
1947
|
+
daemon.attached.set(row.id, set);
|
|
1948
|
+
}
|
|
1949
|
+
return set;
|
|
1950
|
+
}
|
|
1951
|
+
function touchHook(daemon, id) {
|
|
1952
|
+
daemon.hookAt.set(id, daemon.now().getTime());
|
|
1953
|
+
}
|
|
1954
|
+
function register(daemon, p, repo) {
|
|
1955
|
+
const window = attachTarget(daemon, p);
|
|
1956
|
+
if (window) {
|
|
1957
|
+
if (p.pid !== void 0) attachedOf(daemon, window).add(p.pid);
|
|
1958
|
+
daemon.store.updateSession(window.id, { lastSeenAt: daemon.iso() });
|
|
1959
|
+
return { session: view(daemon, daemon.store.getSession(window.id) ?? window) };
|
|
1960
|
+
}
|
|
1961
|
+
const id = newSessionId();
|
|
1962
|
+
const at = daemon.iso();
|
|
1963
|
+
const row = daemon.store.tx(() => {
|
|
1964
|
+
const named = namedOf(daemon.store.allSessions());
|
|
1965
|
+
const base = baseName(repo?.root ?? p.cwd);
|
|
1966
|
+
const name = p.name !== void 0 ? validateRename(id, p.name, named) : generateSessionName(p.cli, base, named);
|
|
1967
|
+
const parent = p.spawnedBy ? daemon.store.getSession(p.spawnedBy) : void 0;
|
|
1968
|
+
const r = {
|
|
1969
|
+
id,
|
|
1970
|
+
name,
|
|
1971
|
+
cli: p.cli,
|
|
1972
|
+
deviceId: daemon.deviceId,
|
|
1973
|
+
cwd: p.cwd,
|
|
1974
|
+
status: "idle",
|
|
1975
|
+
deliveryTier: p.acp ? "acp" : cliDeliveryTier(p.cli),
|
|
1976
|
+
spawned: p.spawned,
|
|
1977
|
+
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
1978
|
+
autoRuns: [],
|
|
1979
|
+
turnHops: 0,
|
|
1980
|
+
startedAt: at,
|
|
1981
|
+
lastSeenAt: at
|
|
1982
|
+
};
|
|
1983
|
+
if (p.cliVersion !== void 0) r.cliVersion = p.cliVersion;
|
|
1984
|
+
if (p.variant !== void 0) r.variant = p.variant;
|
|
1985
|
+
if (repo) {
|
|
1986
|
+
r.repoRoot = repo.root;
|
|
1987
|
+
if (repo.remoteUrlHash !== void 0) r.repoRemoteUrlHash = repo.remoteUrlHash;
|
|
1988
|
+
}
|
|
1989
|
+
if (p.pid !== void 0) r.pid = p.pid;
|
|
1990
|
+
if (p.hostPid !== void 0) r.hostPid = p.hostPid;
|
|
1991
|
+
if (p.hostPids !== void 0) r.hostPids = p.hostPids;
|
|
1992
|
+
if (p.spawnedBy !== void 0) r.spawnedBy = p.spawnedBy;
|
|
1993
|
+
daemon.store.insertSession(r);
|
|
1994
|
+
return r;
|
|
1995
|
+
});
|
|
1996
|
+
attachedOf(daemon, row);
|
|
1997
|
+
if (p.model !== void 0) setModelLabel(daemon, row.id, p.model);
|
|
1998
|
+
emitSession(daemon, row.id, "registered");
|
|
1999
|
+
claimPreferredLead(daemon, row);
|
|
2000
|
+
return { session: view(daemon, daemon.store.getSession(row.id) ?? row) };
|
|
2001
|
+
}
|
|
2002
|
+
async function registerAsync(daemon, p) {
|
|
2003
|
+
return register(daemon, p, await detect(p));
|
|
2004
|
+
}
|
|
2005
|
+
function heartbeat(daemon, sessionId, pid) {
|
|
2006
|
+
const row = requireSession(daemon, sessionId);
|
|
2007
|
+
if (daemon.retired.has(sessionId)) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" ${SESSION_ENDED_TEXT}.`);
|
|
2008
|
+
const at = daemon.iso();
|
|
2009
|
+
if (row.status !== "offline") {
|
|
2010
|
+
if (pid !== void 0) attachedOf(daemon, row).add(pid);
|
|
2011
|
+
daemon.store.updateSession(sessionId, { lastSeenAt: at });
|
|
2012
|
+
return { lastSeenAt: at };
|
|
2013
|
+
}
|
|
2014
|
+
const taken = namedOf(daemon.store.allSessions()).some((s) => s.id !== sessionId && isOnline(s) && s.name === row.name);
|
|
2015
|
+
if (row.hostPid !== void 0 && !daemon.isAlive(row.hostPid) || taken) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline and cannot come back. Register the session again.`);
|
|
2016
|
+
daemon.store.updateSession(sessionId, {
|
|
2017
|
+
status: "idle",
|
|
2018
|
+
lastSeenAt: at
|
|
2019
|
+
});
|
|
2020
|
+
if (pid !== void 0) attachedOf(daemon, row).add(pid);
|
|
2021
|
+
daemon.offlineSince.delete(sessionId);
|
|
2022
|
+
emitSession(daemon, sessionId, "updated");
|
|
2023
|
+
return { lastSeenAt: at };
|
|
2024
|
+
}
|
|
2025
|
+
/** The model label a session reports, as one line of plain text (it is shown in a terminal). */
|
|
2026
|
+
function setModelLabel(daemon, sessionId, model) {
|
|
2027
|
+
const clean = sanitizeLine(model);
|
|
2028
|
+
if (clean === "") daemon.modelLabels.delete(sessionId);
|
|
2029
|
+
else daemon.modelLabels.set(sessionId, clean);
|
|
2030
|
+
}
|
|
2031
|
+
function depart(daemon, sessionId, change) {
|
|
2032
|
+
const before = daemon.store.holder();
|
|
2033
|
+
const after = holderAfterDeparture(before, sessionId);
|
|
2034
|
+
const prevName = leadName(daemon, before);
|
|
2035
|
+
daemon.store.tx(() => {
|
|
2036
|
+
daemon.store.updateSession(sessionId, { status: "offline" });
|
|
2037
|
+
if (after !== before) daemon.store.setHolder(after);
|
|
2038
|
+
});
|
|
2039
|
+
logLead(daemon, prevName, before, after, "departed");
|
|
2040
|
+
daemon.listeners.delete(sessionId);
|
|
2041
|
+
daemon.woken.delete(sessionId);
|
|
2042
|
+
daemon.attached.delete(sessionId);
|
|
2043
|
+
daemon.hookAt.delete(sessionId);
|
|
2044
|
+
settleAsksOf(daemon, sessionId);
|
|
2045
|
+
daemon.offlineSince.set(sessionId, daemon.now().getTime());
|
|
2046
|
+
emitSession(daemon, sessionId, change);
|
|
2047
|
+
if (after !== before) emit(daemon, {
|
|
2048
|
+
event: "orchestrator.changed",
|
|
2049
|
+
data: {
|
|
2050
|
+
orchestrator: after,
|
|
2051
|
+
previous: before
|
|
2052
|
+
}
|
|
2053
|
+
});
|
|
2054
|
+
}
|
|
2055
|
+
/**
|
|
2056
|
+
* With `pid`, that MCP process detaches and the session stays online while another is attached;
|
|
2057
|
+
* the session departs with its last one. Without `pid` it departs at once.
|
|
2058
|
+
*/
|
|
2059
|
+
function unregister(daemon, sessionId, pid) {
|
|
2060
|
+
const row = requireSession(daemon, sessionId);
|
|
2061
|
+
if (row.status === "offline") return { ok: true };
|
|
2062
|
+
if (pid !== void 0) {
|
|
2063
|
+
const set = attachedOf(daemon, row);
|
|
2064
|
+
set.delete(pid);
|
|
2065
|
+
if (set.size > 0) {
|
|
2066
|
+
if (row.pid === pid) daemon.store.updateSession(sessionId, { pid: [...set][0] });
|
|
2067
|
+
return { ok: true };
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
if (pid === void 0) daemon.retired.add(sessionId);
|
|
2071
|
+
depart(daemon, sessionId, "unregistered");
|
|
2072
|
+
return { ok: true };
|
|
2073
|
+
}
|
|
2074
|
+
/**
|
|
2075
|
+
* Delete a session and its mail (the app's "Remove this session"). The lead role goes with it.
|
|
2076
|
+
* A window that is still open registers again on its next heartbeat or tool call.
|
|
2077
|
+
*/
|
|
2078
|
+
function remove(daemon, sessionId) {
|
|
2079
|
+
const shown = {
|
|
2080
|
+
...view(daemon, requireSession(daemon, sessionId)),
|
|
2081
|
+
status: "offline"
|
|
2082
|
+
};
|
|
2083
|
+
const before = daemon.store.holder();
|
|
2084
|
+
const after = holderAfterDeparture(before, sessionId);
|
|
2085
|
+
const prevName = leadName(daemon, before);
|
|
2086
|
+
daemon.store.tx(() => {
|
|
2087
|
+
if (after !== before) daemon.store.setHolder(after);
|
|
2088
|
+
daemon.store.deleteSession(sessionId);
|
|
2089
|
+
});
|
|
2090
|
+
logLead(daemon, prevName, before, after, "removed");
|
|
2091
|
+
daemon.listeners.delete(sessionId);
|
|
2092
|
+
daemon.woken.delete(sessionId);
|
|
2093
|
+
daemon.wokenAt.delete(sessionId);
|
|
2094
|
+
daemon.wakersOff.delete(sessionId);
|
|
2095
|
+
daemon.offlineSince.delete(sessionId);
|
|
2096
|
+
daemon.attached.delete(sessionId);
|
|
2097
|
+
daemon.hookAt.delete(sessionId);
|
|
2098
|
+
daemon.lastSent.delete(sessionId);
|
|
2099
|
+
daemon.modelLabels.delete(sessionId);
|
|
2100
|
+
settleAsksOf(daemon, sessionId);
|
|
2101
|
+
emit(daemon, {
|
|
2102
|
+
event: "session.updated",
|
|
2103
|
+
data: {
|
|
2104
|
+
session: shown,
|
|
2105
|
+
change: "unregistered"
|
|
2106
|
+
}
|
|
2107
|
+
});
|
|
2108
|
+
daemon.relay?.sessionsChanged();
|
|
2109
|
+
if (after !== before) emit(daemon, {
|
|
2110
|
+
event: "orchestrator.changed",
|
|
2111
|
+
data: {
|
|
2112
|
+
orchestrator: after,
|
|
2113
|
+
previous: before
|
|
2114
|
+
}
|
|
2115
|
+
});
|
|
2116
|
+
return { ok: true };
|
|
2117
|
+
}
|
|
2118
|
+
function rename$1(daemon, p) {
|
|
2119
|
+
const row = requireSession(daemon, p.sessionId);
|
|
2120
|
+
const name = validateRename(p.sessionId, p.name, namedOf(daemon.store.allSessions()));
|
|
2121
|
+
if (name !== row.name) {
|
|
2122
|
+
daemon.store.updateSession(p.sessionId, { name });
|
|
2123
|
+
emitSession(daemon, p.sessionId, "updated");
|
|
2124
|
+
}
|
|
2125
|
+
return { session: view(daemon, requireSession(daemon, p.sessionId)) };
|
|
2126
|
+
}
|
|
2127
|
+
function setStatus(daemon, p) {
|
|
2128
|
+
const row = requireSession(daemon, p.sessionId);
|
|
2129
|
+
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
2130
|
+
if (p.status === "offline") throw new ConvenoError(RpcErrorCode.InvalidParams, "Status \"offline\" is set by the daemon. Use idle, busy or waiting_on_question, or unregister the session.");
|
|
2131
|
+
const fields = {};
|
|
2132
|
+
if (p.status !== void 0) fields.status = p.status;
|
|
2133
|
+
if (p.statusText !== void 0) {
|
|
2134
|
+
const clean = p.statusText === null ? "" : sanitizeLine(p.statusText);
|
|
2135
|
+
fields.statusText = clean === "" ? null : clean;
|
|
2136
|
+
}
|
|
2137
|
+
daemon.store.updateSession(p.sessionId, fields);
|
|
2138
|
+
emitSession(daemon, p.sessionId, "updated");
|
|
2139
|
+
return { session: view(daemon, requireSession(daemon, p.sessionId)) };
|
|
2140
|
+
}
|
|
2141
|
+
function list(daemon, p) {
|
|
2142
|
+
const rows = daemon.store.allSessions().filter((r) => {
|
|
2143
|
+
if (r.status === "offline" && !p.includeOffline) return false;
|
|
2144
|
+
if (p.cli && r.cli !== p.cli) return false;
|
|
2145
|
+
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
2146
|
+
return true;
|
|
2147
|
+
});
|
|
2148
|
+
const remote = daemon.relay?.remoteSessions({
|
|
2149
|
+
cli: p.cli,
|
|
2150
|
+
repo: p.repo
|
|
2151
|
+
}) ?? [];
|
|
2152
|
+
return { sessions: [...rows.map((r) => view(daemon, r)), ...remote] };
|
|
2153
|
+
}
|
|
2154
|
+
/** Do two directory paths name the same place, ignoring trailing separators (and case on Windows)? */
|
|
2155
|
+
function samePath(a, b, platform) {
|
|
2156
|
+
const norm = (p) => {
|
|
2157
|
+
const s = p.replace(/[\\/]+$/, "");
|
|
2158
|
+
return platform === "win32" ? s.replace(/\\/g, "/").toLowerCase() : s;
|
|
2159
|
+
};
|
|
2160
|
+
return norm(a) === norm(b);
|
|
2161
|
+
}
|
|
2162
|
+
function emit(daemon, payload, onlyTo) {
|
|
2163
|
+
const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
|
|
2164
|
+
for (const c of daemon.conns) {
|
|
2165
|
+
const sub = c.sub;
|
|
2166
|
+
if (!sub?.topics.has(payload.event)) continue;
|
|
2167
|
+
if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
|
|
2168
|
+
send(c, makeEventNotification(payload));
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
function emitSession(daemon, id, change) {
|
|
2172
|
+
const row = daemon.store.getSession(id);
|
|
2173
|
+
if (row) emit(daemon, {
|
|
2174
|
+
event: "session.updated",
|
|
2175
|
+
data: {
|
|
2176
|
+
session: view(daemon, row),
|
|
2177
|
+
change
|
|
2178
|
+
}
|
|
2179
|
+
});
|
|
2180
|
+
daemon.relay?.sessionsChanged();
|
|
2181
|
+
}
|
|
2182
|
+
/** Every message that lands in a local mailbox goes through here. */
|
|
2183
|
+
function emitMessage(daemon, m, recipient) {
|
|
2184
|
+
emit(daemon, {
|
|
2185
|
+
event: "message.received",
|
|
2186
|
+
data: { message: m }
|
|
2187
|
+
}, recipient);
|
|
2188
|
+
daemonWake(daemon, recipient);
|
|
2189
|
+
}
|
|
2190
|
+
function subscribe(daemon, conn, p) {
|
|
2191
|
+
if (p.sessionId === void 0) {
|
|
2192
|
+
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, "Pass sessionId to subscribe. Only the conveno command and app can subscribe to every event.");
|
|
2193
|
+
} else requireSession(daemon, p.sessionId);
|
|
2194
|
+
const topics = p.topics ?? [...EVENT_NAMES];
|
|
2195
|
+
conn.sub = {
|
|
2196
|
+
...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
|
|
2197
|
+
topics: new Set(topics)
|
|
2198
|
+
};
|
|
2199
|
+
return { subscribed: topics };
|
|
2200
|
+
}
|
|
2201
|
+
/** Time the daemon spends reading the process table for one `session.hostOf`. */
|
|
2202
|
+
const HOST_OF_TIMEOUT_MS = 1500;
|
|
2203
|
+
/**
|
|
2204
|
+
* Find the session a hook belongs to: the one online session whose `hostPid` equals `pid`.
|
|
2205
|
+
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
2206
|
+
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
2207
|
+
* null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
|
|
2208
|
+
* those registered in the same folder (separators, trailing slash, case
|
|
2209
|
+
* on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
|
|
2210
|
+
* folder still match nothing.
|
|
2211
|
+
*/
|
|
2212
|
+
function byHost(daemon, p) {
|
|
2213
|
+
const { pid, cwd, nativeId } = p;
|
|
2214
|
+
const rows = daemon.store.allSessions().filter((r) => p.includeOffline || r.status !== "offline");
|
|
2215
|
+
const live = (list) => {
|
|
2216
|
+
const online = list.filter((r) => r.status !== "offline");
|
|
2217
|
+
return online.length > 0 ? online : list;
|
|
2218
|
+
};
|
|
2219
|
+
if (nativeId !== void 0) {
|
|
2220
|
+
const own = live(rows.filter((r) => r.nativeId === nativeId))[0];
|
|
2221
|
+
if (!own) return { session: null };
|
|
2222
|
+
const pids = [...own.hostPid === void 0 ? [] : [own.hostPid], ...own.hostPids ?? []];
|
|
2223
|
+
if (pids.length === 0 || pids.includes(pid)) return { session: view(daemon, own) };
|
|
2224
|
+
const mine = pidHolders(daemon, rows, pid, cwd, live);
|
|
2225
|
+
return { session: view(daemon, mine.length === 1 ? mine[0] : own) };
|
|
2226
|
+
}
|
|
2227
|
+
const holders = pidHolders(daemon, rows, pid, cwd, live);
|
|
2228
|
+
const only = holders.length === 1 ? holders[0] : void 0;
|
|
2229
|
+
if (only) touchHook(daemon, only.id);
|
|
2230
|
+
return { session: only ? view(daemon, only) : null };
|
|
2231
|
+
}
|
|
2232
|
+
/** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
|
|
2233
|
+
function pidHolders(daemon, rows, pid, cwd, live) {
|
|
2234
|
+
return live(rows.filter((r) => r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, daemon.platform))));
|
|
2235
|
+
}
|
|
2236
|
+
/**
|
|
2237
|
+
* Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
|
|
2238
|
+
* process table itself. With no online session of the hook's CLI there is nothing the hook could
|
|
2239
|
+
* deliver to, so it answers `online: false` without reading anything. The answer is only the
|
|
2240
|
+
* pid: the hook still goes through `byHost`, which decides whether a session owns it.
|
|
2241
|
+
* `complete: false` means the table could not be read here and the hook should read it itself.
|
|
2242
|
+
*/
|
|
2243
|
+
async function hostOf(daemon, p) {
|
|
2244
|
+
if (!daemon.store.allSessions().some((r) => r.status !== "offline" && r.cli === p.cli)) return {
|
|
2245
|
+
online: false,
|
|
2246
|
+
complete: true
|
|
2247
|
+
};
|
|
2248
|
+
const a = await readAncestry({
|
|
2249
|
+
ppid: p.ppid,
|
|
2250
|
+
timeoutMs: HOST_OF_TIMEOUT_MS,
|
|
2251
|
+
launcherPaths: p.launcherPaths ?? [],
|
|
2252
|
+
io: daemon.processIo
|
|
2253
|
+
});
|
|
2254
|
+
return {
|
|
2255
|
+
online: true,
|
|
2256
|
+
complete: a.complete,
|
|
2257
|
+
...a.complete && a.hostPid !== void 0 ? { hostPid: a.hostPid } : {}
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
/**
|
|
2261
|
+
* A hook records the CLI's own id for its session. One online session holds an id at a time,
|
|
2262
|
+
* so a CLI that reuses an id for a new session (a resumed thread) moves it there.
|
|
2263
|
+
*/
|
|
2264
|
+
function setNative(daemon, p) {
|
|
2265
|
+
const row = requireOnline(daemon, p.sessionId);
|
|
2266
|
+
if (row.nativeId === p.nativeId) return { session: view(daemon, row) };
|
|
2267
|
+
const others = daemon.store.allSessions().filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
|
|
2268
|
+
daemon.store.tx(() => {
|
|
2269
|
+
for (const o of others) daemon.store.updateSession(o.id, { nativeId: null });
|
|
2270
|
+
daemon.store.updateSession(row.id, { nativeId: p.nativeId });
|
|
2271
|
+
});
|
|
2272
|
+
for (const o of others) emitSession(daemon, o.id, "updated");
|
|
2273
|
+
emitSession(daemon, row.id, "updated");
|
|
2274
|
+
daemonWake(daemon, row.id);
|
|
2275
|
+
return { session: view(daemon, requireSession(daemon, row.id)) };
|
|
2276
|
+
}
|
|
2277
|
+
/**
|
|
2278
|
+
* A desktop app session learns its workspace from a hook: the app starts Conveno in its install
|
|
2279
|
+
* folder, so the row moves to the folder the user has open. A name made from the old folder
|
|
2280
|
+
* follows it; a name the user chose stays. Only an app session moves (`variant` on the call may
|
|
2281
|
+
* mark one); a CLI row keeps the folder it registered with.
|
|
2282
|
+
*/
|
|
2283
|
+
async function setCwd(daemon, p) {
|
|
2284
|
+
const row = requireOnline(daemon, p.sessionId);
|
|
2285
|
+
if (!(row.variant === "app" || p.variant === "app")) return { session: view(daemon, row) };
|
|
2286
|
+
const found = samePath(row.cwd, p.cwd, daemon.platform) ? void 0 : await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
|
|
2287
|
+
const cur = requireOnline(daemon, p.sessionId);
|
|
2288
|
+
const fields = {};
|
|
2289
|
+
if (cur.variant !== "app") fields.variant = "app";
|
|
2290
|
+
if (found && !samePath(cur.cwd, p.cwd, daemon.platform)) {
|
|
2291
|
+
const oldBase = baseName(cur.repoRoot ?? cur.cwd);
|
|
2292
|
+
const prefix = generateSessionName(cur.cli, oldBase, []).replace(/1$/, "");
|
|
2293
|
+
const auto = cur.name.startsWith(prefix) && /^\d+$/.test(cur.name.slice(prefix.length));
|
|
2294
|
+
fields.cwd = p.cwd;
|
|
2295
|
+
fields.repoRoot = found.root ?? null;
|
|
2296
|
+
if (auto) {
|
|
2297
|
+
const others = namedOf(daemon.store.allSessions().filter((r) => r.id !== cur.id));
|
|
2298
|
+
fields.name = generateSessionName(cur.cli, baseName(found.root ?? p.cwd), others);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
if (Object.keys(fields).length > 0) {
|
|
2302
|
+
daemon.store.updateSession(cur.id, fields);
|
|
2303
|
+
emitSession(daemon, cur.id, "updated");
|
|
2304
|
+
}
|
|
2305
|
+
return { session: view(daemon, requireSession(daemon, cur.id)) };
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* The session of the window a hook runs in, among the online sessions of its CLI: the one under
|
|
2309
|
+
* its host process (and in its folder, when the hook says which). Codex shares one host process
|
|
2310
|
+
* between windows, so there it prefers a session that has no conversation yet, and takes a bound
|
|
2311
|
+
* one only when it is the only one. Null when it is ambiguous or none matches.
|
|
2312
|
+
*/
|
|
2313
|
+
function windowRow(daemon, rows, p) {
|
|
2314
|
+
if (p.hostPid === void 0) return void 0;
|
|
2315
|
+
const { cwd } = p;
|
|
2316
|
+
const cands = rows.filter((r) => r.hostPid === p.hostPid && (cwd === void 0 || samePath(r.cwd, cwd, daemon.platform)));
|
|
2317
|
+
if (oneWindowPerHost(p.cli)) return cands.length === 1 ? cands[0] : void 0;
|
|
2318
|
+
const unbound = cands.filter((r) => r.nativeId === void 0);
|
|
2319
|
+
if (unbound.length > 0) return unbound.length === 1 ? unbound[0] : void 0;
|
|
2320
|
+
return cands.length === 1 ? cands[0] : void 0;
|
|
2321
|
+
}
|
|
2322
|
+
/**
|
|
2323
|
+
* `session.bind` from a hook that has only its parent pid. Answers without the hook walking the
|
|
2324
|
+
* process tree when the conversation settles it: exactly one online session of the CLI holds the
|
|
2325
|
+
* id, and the hook's parent is that session's host, or the hook starts no turn (a Stop or an
|
|
2326
|
+
* idle never moves a window), or that session is already busy. A conversation no window could
|
|
2327
|
+
* take (no session online, or a hook that is no turn start and every session has a
|
|
2328
|
+
* conversation) answers none. Anything else needs the host pid: `needsHost`. So only the turn
|
|
2329
|
+
* start of an idle conversation walks.
|
|
2330
|
+
*/
|
|
2331
|
+
function bindWithoutHost(daemon, rows, p) {
|
|
2332
|
+
if (rows.length === 0) return { session: null };
|
|
2333
|
+
const holders = rows.filter((r) => r.nativeId === p.nativeId);
|
|
2334
|
+
const [holder] = holders;
|
|
2335
|
+
if (holders.length === 1 && holder) {
|
|
2336
|
+
const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
|
|
2337
|
+
if (p.ppid !== void 0 && pids.includes(p.ppid) || !p.turnStart || holder.status === "busy") {
|
|
2338
|
+
touchHook(daemon, holder.id);
|
|
2339
|
+
return { session: view(daemon, holder) };
|
|
2340
|
+
}
|
|
2341
|
+
} else if (holders.length === 0 && !p.turnStart && rows.every((r) => r.nativeId !== void 0)) return { session: null };
|
|
2342
|
+
return {
|
|
2343
|
+
session: null,
|
|
2344
|
+
needsHost: true
|
|
2345
|
+
};
|
|
2346
|
+
}
|
|
2347
|
+
/**
|
|
2348
|
+
* Bind a conversation to the window's session (see `session.bind` in the protocol). The session
|
|
2349
|
+
* that holds the id wins; a caller with a session of its own is merged into it. Otherwise only a
|
|
2350
|
+
* turn start moves the window to the conversation, and a conversation that is not the window's
|
|
2351
|
+
* current one is ignored by every other hook. Replaces `setNative` for hooks and MCP servers.
|
|
2352
|
+
*/
|
|
2353
|
+
function bind(daemon, p) {
|
|
2354
|
+
const caller = p.sessionId === void 0 ? void 0 : requireOnline(daemon, p.sessionId);
|
|
2355
|
+
if (caller && caller.cli !== p.cli) return { session: null };
|
|
2356
|
+
const rows = daemon.store.allSessions().filter((r) => r.status !== "offline" && r.cli === p.cli);
|
|
2357
|
+
if (!caller && p.hostPid === void 0) return bindWithoutHost(daemon, rows, p);
|
|
2358
|
+
let holder = rows.find((r) => r.nativeId === p.nativeId);
|
|
2359
|
+
if (holder && !caller && p.hostPid !== void 0) {
|
|
2360
|
+
const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
|
|
2361
|
+
if (pids.length > 0 && !pids.includes(p.hostPid)) {
|
|
2362
|
+
const mine = rows.filter((r) => r.hostPid === p.hostPid);
|
|
2363
|
+
if (mine.length === 1 && mine[0]?.id !== holder.id) holder = void 0;
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
if (holder) {
|
|
2367
|
+
if (caller && caller.id !== holder.id) return { session: merge(daemon, caller, holder, p.pid) };
|
|
2368
|
+
if (!caller) touchHook(daemon, holder.id);
|
|
2369
|
+
return { session: view(daemon, holder) };
|
|
2370
|
+
}
|
|
2371
|
+
const row = caller ?? windowRow(daemon, rows, p);
|
|
2372
|
+
if (!row) return { session: null };
|
|
2373
|
+
if (!caller) touchHook(daemon, row.id);
|
|
2374
|
+
if (row.nativeId !== void 0 && !p.turnStart) return { session: null };
|
|
2375
|
+
const others = rows.filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
|
|
2376
|
+
const moved = row.nativeId !== void 0;
|
|
2377
|
+
const stale = moved && row.status === "busy";
|
|
2378
|
+
daemon.store.tx(() => {
|
|
2379
|
+
for (const o of others) daemon.store.updateSession(o.id, { nativeId: null });
|
|
2380
|
+
daemon.store.updateSession(row.id, {
|
|
2381
|
+
nativeId: p.nativeId,
|
|
2382
|
+
...stale ? {
|
|
2383
|
+
status: "idle",
|
|
2384
|
+
turnHops: 0
|
|
2385
|
+
} : {}
|
|
2386
|
+
});
|
|
2387
|
+
});
|
|
2388
|
+
if (moved) {
|
|
2389
|
+
daemon.listeners.delete(row.id);
|
|
2390
|
+
daemon.woken.delete(row.id);
|
|
2391
|
+
}
|
|
2392
|
+
for (const o of others) emitSession(daemon, o.id, "updated");
|
|
2393
|
+
emitSession(daemon, row.id, "updated");
|
|
2394
|
+
daemonWake(daemon, row.id);
|
|
2395
|
+
return { session: view(daemon, requireSession(daemon, row.id)) };
|
|
2396
|
+
}
|
|
2397
|
+
/**
|
|
2398
|
+
* Fold the session of an MCP process into the session that holds its conversation: the process
|
|
2399
|
+
* attaches to the survivor, the mail and the lead role move to it, and the caller's row goes.
|
|
2400
|
+
*/
|
|
2401
|
+
function merge(daemon, from, into, pid) {
|
|
2402
|
+
const pids = attachedOf(daemon, into);
|
|
2403
|
+
for (const q of attachedOf(daemon, from)) pids.add(q);
|
|
2404
|
+
if (pid !== void 0) pids.add(pid);
|
|
2405
|
+
const before = daemon.store.holder();
|
|
2406
|
+
const lead = before === from.id;
|
|
2407
|
+
const prevName = leadName(daemon, before);
|
|
2408
|
+
daemon.store.tx(() => {
|
|
2409
|
+
daemon.store.moveMailbox(from.id, into.id);
|
|
2410
|
+
if (lead) daemon.store.setHolder(into.id);
|
|
2411
|
+
daemon.store.updateSession(into.id, { lastSeenAt: daemon.iso() });
|
|
2412
|
+
daemon.store.deleteSession(from.id);
|
|
2413
|
+
});
|
|
2414
|
+
if (lead) logLead(daemon, prevName, before, into.id, "merged");
|
|
2415
|
+
daemon.listeners.delete(from.id);
|
|
2416
|
+
daemon.woken.delete(from.id);
|
|
2417
|
+
daemon.attached.delete(from.id);
|
|
2418
|
+
daemon.hookAt.delete(from.id);
|
|
2419
|
+
daemon.offlineSince.delete(from.id);
|
|
2420
|
+
daemon.lastSent.delete(from.id);
|
|
2421
|
+
daemon.modelLabels.delete(from.id);
|
|
2422
|
+
daemon.relay?.sessionsChanged();
|
|
2423
|
+
if (lead) emit(daemon, {
|
|
2424
|
+
event: "orchestrator.changed",
|
|
2425
|
+
data: {
|
|
2426
|
+
orchestrator: into.id,
|
|
2427
|
+
previous: from.id
|
|
2428
|
+
}
|
|
2429
|
+
});
|
|
2430
|
+
emitSession(daemon, into.id, "updated");
|
|
2431
|
+
daemonWake(daemon, into.id);
|
|
2432
|
+
return view(daemon, requireSession(daemon, into.id));
|
|
2433
|
+
}
|
|
2434
|
+
const HANDSHAKE_TIMEOUT_MS = 15e3;
|
|
2435
|
+
/**
|
|
2436
|
+
* One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
|
|
2437
|
+
* itself; the hub decides when to try again. The access token goes in the Authorization header
|
|
2438
|
+
* of the upgrade request, never in the URL, so it does not end up in access logs.
|
|
2439
|
+
*/
|
|
2440
|
+
var RelayConnection = class {
|
|
2441
|
+
o;
|
|
2442
|
+
ws;
|
|
2443
|
+
pinger;
|
|
2444
|
+
handshake;
|
|
2445
|
+
stateValue = "idle";
|
|
2446
|
+
stopped = false;
|
|
2447
|
+
explaining = false;
|
|
2448
|
+
loggedVersion = false;
|
|
2449
|
+
constructor(o) {
|
|
2450
|
+
this.o = o;
|
|
2451
|
+
}
|
|
2452
|
+
get state() {
|
|
2453
|
+
return this.stateValue;
|
|
2454
|
+
}
|
|
2455
|
+
start() {
|
|
2456
|
+
this.stateValue = "connecting";
|
|
2457
|
+
const ws = new WebSocket(this.o.url, { headers: { Authorization: `Bearer ${this.o.token}` } });
|
|
2458
|
+
this.ws = ws;
|
|
2459
|
+
this.handshake = setTimeout(() => this.fail("The relay did not answer in time."), HANDSHAKE_TIMEOUT_MS);
|
|
2460
|
+
this.handshake.unref();
|
|
2461
|
+
ws.addEventListener("message", (e) => this.onMessage(e.data));
|
|
2462
|
+
ws.addEventListener("error", () => {
|
|
2463
|
+
if (this.stateValue === "connecting") {
|
|
2464
|
+
this.explaining = true;
|
|
2465
|
+
this.explainFailure();
|
|
2466
|
+
} else this.fail("The connection to the relay failed.");
|
|
2467
|
+
});
|
|
2468
|
+
ws.addEventListener("close", (e) => {
|
|
2469
|
+
if (!this.explaining) this.fail(`The relay closed the connection (${e.code} ${e.reason}).`);
|
|
2470
|
+
});
|
|
2471
|
+
}
|
|
2472
|
+
/** Close for good; no `down` event. */
|
|
2473
|
+
stop() {
|
|
2474
|
+
this.stopped = true;
|
|
2475
|
+
this.cleanup();
|
|
2476
|
+
}
|
|
2477
|
+
/** Send a frame if the connection is ready. Returns false when it is not. */
|
|
2478
|
+
send(frame) {
|
|
2479
|
+
if (this.stateValue !== "ready" || !this.ws) return false;
|
|
2480
|
+
try {
|
|
2481
|
+
this.ws.send(JSON.stringify(frame));
|
|
2482
|
+
return true;
|
|
2483
|
+
} catch {
|
|
2484
|
+
return false;
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
onMessage(data) {
|
|
2488
|
+
if (typeof data !== "string" || data === "pong") return;
|
|
2489
|
+
let json;
|
|
2490
|
+
try {
|
|
2491
|
+
json = JSON.parse(data);
|
|
2492
|
+
} catch {
|
|
2493
|
+
return;
|
|
2494
|
+
}
|
|
2495
|
+
const v = json?.v;
|
|
2496
|
+
if (typeof v === "number" && v !== 1) {
|
|
2497
|
+
if (!this.loggedVersion) {
|
|
2498
|
+
this.loggedVersion = true;
|
|
2499
|
+
this.o.log?.(`relay: dropped a frame of relay protocol version ${v}; this client speaks 1`);
|
|
2500
|
+
}
|
|
2501
|
+
if (this.stateValue === "connecting") this.fail("The relay speaks a newer protocol than this version of Conveno.", "upgrade_required");
|
|
2502
|
+
return;
|
|
2503
|
+
}
|
|
2504
|
+
const r = parseRelayFrame(json);
|
|
2505
|
+
if (!r.ok) return;
|
|
2506
|
+
const f = r.value;
|
|
2507
|
+
if (this.stateValue === "connecting") {
|
|
2508
|
+
if (f.t === "challenge") {
|
|
2509
|
+
const hello = signRelayHello(this.o.identity, f.nonce);
|
|
2510
|
+
this.ws?.send(JSON.stringify(this.o.client ? {
|
|
2511
|
+
...hello,
|
|
2512
|
+
client: this.o.client
|
|
2513
|
+
} : hello));
|
|
2514
|
+
} else if (f.t === "ready") {
|
|
2515
|
+
if (this.handshake) clearTimeout(this.handshake);
|
|
2516
|
+
this.stateValue = "ready";
|
|
2517
|
+
this.pinger = setInterval(() => {
|
|
2518
|
+
try {
|
|
2519
|
+
this.ws?.send("ping");
|
|
2520
|
+
} catch {}
|
|
2521
|
+
}, this.o.pingMs ?? 3e4);
|
|
2522
|
+
this.pinger.unref();
|
|
2523
|
+
this.o.events.ready(f.online);
|
|
2524
|
+
} else if (f.t === "error") this.fail(f.message, f.code, f.minVersion);
|
|
2525
|
+
return;
|
|
2526
|
+
}
|
|
2527
|
+
this.o.events.frame(f);
|
|
2528
|
+
}
|
|
2529
|
+
async explainFailure() {
|
|
2530
|
+
const httpUrl = this.o.url.replace(/^ws/, "http");
|
|
2531
|
+
try {
|
|
2532
|
+
const res = await (this.o.fetchImpl ?? fetch)(httpUrl, {
|
|
2533
|
+
headers: { Authorization: `Bearer ${this.o.token}` },
|
|
2534
|
+
signal: AbortSignal.timeout(1e4)
|
|
2535
|
+
});
|
|
2536
|
+
const body = await res.json().catch(() => ({}));
|
|
2537
|
+
if (res.status === 401 || res.status === 403) return this.fail(body.error?.message ?? "The relay refused the access token.", body.error?.code);
|
|
2538
|
+
this.fail(`The relay could not be reached (HTTP ${res.status}).`);
|
|
2539
|
+
} catch {
|
|
2540
|
+
this.fail("The relay could not be reached.");
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
fail(detail, code, minVersion) {
|
|
2544
|
+
if (this.stopped || this.stateValue === "disconnected") return;
|
|
2545
|
+
this.stateValue = "disconnected";
|
|
2546
|
+
this.cleanup();
|
|
2547
|
+
this.o.events.down(detail, code, minVersion);
|
|
2548
|
+
}
|
|
2549
|
+
cleanup() {
|
|
2550
|
+
if (this.handshake) clearTimeout(this.handshake);
|
|
2551
|
+
if (this.pinger) clearInterval(this.pinger);
|
|
2552
|
+
try {
|
|
2553
|
+
this.ws?.close();
|
|
2554
|
+
} catch {}
|
|
2555
|
+
}
|
|
2556
|
+
};
|
|
2557
|
+
const NOT_PRO = "The relay is part of Conveno Pro. This account is on the free plan.";
|
|
2558
|
+
/**
|
|
2559
|
+
* The default `RelayHubOptions.accessToken`, on the login in `accountFile`. With `refresh` false,
|
|
2560
|
+
* the stored token as is, without any network call; with `refresh` true, one renewed if it is about
|
|
2561
|
+
* to expire and bound to `deviceId`, which binds the login to this device on first use.
|
|
2562
|
+
*/
|
|
2563
|
+
function accountAccessToken(accountFile) {
|
|
2564
|
+
return async (refresh, deviceId) => {
|
|
2565
|
+
if (!refresh) return (await readAccountTokens(accountFile))?.accessToken ?? null;
|
|
2566
|
+
const io = { apiBase: signedInAccountApi(accountFile) };
|
|
2567
|
+
const token = await currentAccessToken(accountFile, io);
|
|
2568
|
+
if (token === null || jwtClaim(token, "did") === deviceId) return token;
|
|
2569
|
+
return bindAccountDevice(accountFile, deviceId, io);
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
/** Remote sessions not republished for this many publish periods are dropped. */
|
|
2573
|
+
const REMOTE_EXPIRY_PERIODS = 3;
|
|
2574
|
+
/** A device name as the first part of a remote session name: `[a-z0-9][a-z0-9._-]{0,23}`. */
|
|
2575
|
+
const deviceSlug = (s) => s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 24) || "device";
|
|
2576
|
+
/**
|
|
2577
|
+
* How a session on another device is named here: `<device>:<name>`. Local session names cannot
|
|
2578
|
+
* contain `:`, so the two never collide, and no remote session can pose as a local one or as a
|
|
2579
|
+
* reserved sender such as `conveno`.
|
|
2580
|
+
*/
|
|
2581
|
+
function remoteSessionName(session, device) {
|
|
2582
|
+
return `${deviceSlug(device)}:${session}`;
|
|
2583
|
+
}
|
|
2584
|
+
/** Called by the daemon whenever a local session changed. Publishes shortly after. */
|
|
2585
|
+
function sessionsChanged(hub) {
|
|
2586
|
+
if (!hub.linkReady || hub.publishTimer) return;
|
|
2587
|
+
hub.publishTimer = setTimeout(() => {
|
|
2588
|
+
hub.publishTimer = void 0;
|
|
2589
|
+
publishAll(hub);
|
|
2590
|
+
}, 300);
|
|
2591
|
+
hub.publishTimer.unref();
|
|
2592
|
+
}
|
|
2593
|
+
function publishTo(hub, deviceId) {
|
|
2594
|
+
const sessions = hub.o.host.localSessions().filter((s) => !s.remote).map((s) => {
|
|
2595
|
+
const { pid: _p, hostPid: _h, hostPids: _hs, remote: _r, deviceName: _d, ...rest } = s;
|
|
2596
|
+
return {
|
|
2597
|
+
...rest,
|
|
2598
|
+
deviceId: hub.identity.deviceId
|
|
2599
|
+
};
|
|
2600
|
+
});
|
|
2601
|
+
hub.publishSeq = Math.max(hub.publishSeq + 1, hub.ms());
|
|
2602
|
+
sendPayload(hub, deviceId, {
|
|
2603
|
+
type: "sessions",
|
|
2604
|
+
deviceName: hub.deviceName(),
|
|
2605
|
+
seq: hub.publishSeq,
|
|
2606
|
+
sessions
|
|
2607
|
+
});
|
|
2608
|
+
}
|
|
2609
|
+
function publishAll(hub) {
|
|
2610
|
+
if (!hub.listReceived) return;
|
|
2611
|
+
for (const d of hub.online) publishTo(hub, d);
|
|
2612
|
+
}
|
|
2613
|
+
function expireRemote(hub) {
|
|
2614
|
+
const cutoff = hub.ms() - REMOTE_EXPIRY_PERIODS * hub.publishMs;
|
|
2615
|
+
for (const [id, r] of hub.remote) if (r.receivedAt < cutoff) hub.remote.delete(id);
|
|
2616
|
+
}
|
|
2617
|
+
/**
|
|
2618
|
+
* Sessions on the other devices, as `session.list` shows them: a local alias id and the name
|
|
2619
|
+
* `<device>:<name>`, so none can collide with a local session.
|
|
2620
|
+
*/
|
|
2621
|
+
function remoteSessions(hub, filter = {}) {
|
|
2622
|
+
const out = [];
|
|
2623
|
+
for (const [deviceId, r] of hub.remote) {
|
|
2624
|
+
if (!member(hub, deviceId)) continue;
|
|
2625
|
+
const device = hub.chainState?.members.get(deviceId)?.name ?? r.deviceName;
|
|
2626
|
+
for (const s of r.sessions) {
|
|
2627
|
+
if (filter.cli && s.cli !== filter.cli) continue;
|
|
2628
|
+
const root = s.repo?.root;
|
|
2629
|
+
if (filter.repo && root !== filter.repo && baseName(root ?? s.cwd) !== filter.repo) continue;
|
|
2630
|
+
out.push({
|
|
2631
|
+
...s,
|
|
2632
|
+
id: hub.state.alias(deviceId, s.id),
|
|
2633
|
+
name: remoteSessionName(s.name, device),
|
|
2634
|
+
deviceId,
|
|
2635
|
+
remote: true,
|
|
2636
|
+
deviceName: device
|
|
2637
|
+
});
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
return out;
|
|
2641
|
+
}
|
|
2642
|
+
/** A remote session by its local alias id or its full `<device>:<name>`. */
|
|
2643
|
+
function resolveRemote(hub, to) {
|
|
2644
|
+
const all = remoteSessions(hub).filter((s) => s.status !== "offline");
|
|
2645
|
+
return all.find((s) => s.id === to) ?? all.find((s) => s.name === to);
|
|
2646
|
+
}
|
|
2647
|
+
/** Messages that arrive before the sending device's session list wait this long for it. */
|
|
2648
|
+
const HELD_MESSAGES_PER_DEVICE = 50;
|
|
2649
|
+
const HELD_MESSAGE_MS = 12e4;
|
|
2650
|
+
/** Ids of messages sent to other devices, so only a bounce for one of them is accepted. */
|
|
2651
|
+
const SENT_MAX = 1e3;
|
|
2652
|
+
const SENT_MS = 864e5;
|
|
2653
|
+
/** What the sender shows for each bounce reason. Peers send only the code. */
|
|
2654
|
+
const BOUNCE_TEXT = {
|
|
2655
|
+
session_gone: "the session no longer exists",
|
|
2656
|
+
session_offline: "the session is offline",
|
|
2657
|
+
mailbox_full: "the session has too many unread messages",
|
|
2658
|
+
unknown_sender: "the receiving device did not recognize the sending session",
|
|
2659
|
+
not_allowed: "this kind of message is not carried between devices"
|
|
2660
|
+
};
|
|
2661
|
+
function sendPayload(hub, to, payload) {
|
|
2662
|
+
const recipient = member(hub, to);
|
|
2663
|
+
if (!recipient || !hub.chain || !hub.link || !hub.linkReady || !hub.listReceived) return false;
|
|
2664
|
+
const env = sealEnvelope({
|
|
2665
|
+
sender: hub.identity,
|
|
2666
|
+
recipient,
|
|
2667
|
+
id: newMessageId(),
|
|
2668
|
+
plaintext: new TextEncoder().encode(JSON.stringify(payload)),
|
|
2669
|
+
ts: hub.ms(),
|
|
2670
|
+
list: chainHead(hub.chain)
|
|
2671
|
+
});
|
|
2672
|
+
return hub.link.send(env);
|
|
2673
|
+
}
|
|
2674
|
+
/**
|
|
2675
|
+
* An envelope from another device. It is acknowledged to the relay only after it was handled:
|
|
2676
|
+
* a message is in a local mailbox, or stored in relay.db to wait for its sender's session list.
|
|
2677
|
+
*/
|
|
2678
|
+
function onEnvelope(hub, env) {
|
|
2679
|
+
let pt;
|
|
2680
|
+
try {
|
|
2681
|
+
pt = openEnvelope(env, {
|
|
2682
|
+
self: hub.identity,
|
|
2683
|
+
sender: (d) => member(hub, d),
|
|
2684
|
+
replay: hub.state,
|
|
2685
|
+
now: hub.ms(),
|
|
2686
|
+
record: false
|
|
2687
|
+
});
|
|
2688
|
+
} catch {
|
|
2689
|
+
ack$1(hub, env);
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
if (hub.chain && !headMatches(hub.chain, env.head, env.len)) {
|
|
2693
|
+
const name = hub.chainState?.members.get(env.fromDevice)?.name ?? "another device";
|
|
2694
|
+
setConflict(hub, "split_view", `${name} holds a device list (length ${env.len}) that does not match this device's.`, {
|
|
2695
|
+
deviceId: env.fromDevice,
|
|
2696
|
+
name,
|
|
2697
|
+
head: env.head,
|
|
2698
|
+
length: env.len
|
|
2699
|
+
});
|
|
2700
|
+
hub.state.add(env.id, env.ts);
|
|
2701
|
+
ack$1(hub, env);
|
|
2702
|
+
return;
|
|
2703
|
+
}
|
|
2704
|
+
try {
|
|
2705
|
+
const json = JSON.parse(new TextDecoder().decode(pt));
|
|
2706
|
+
const r = safeParse(RelayPayload, json);
|
|
2707
|
+
hub.state.atomically(() => {
|
|
2708
|
+
if (r.ok) onPayload(hub, env.fromDevice, r.value, env.id);
|
|
2709
|
+
hub.state.add(env.id, env.ts);
|
|
2710
|
+
});
|
|
2711
|
+
} catch (e) {
|
|
2712
|
+
hub.o.host.log.error("relay: an envelope could not be handled", e);
|
|
2713
|
+
}
|
|
2714
|
+
ack$1(hub, env);
|
|
2715
|
+
}
|
|
2716
|
+
function ack$1(hub, env) {
|
|
2717
|
+
hub.link?.send({
|
|
2718
|
+
t: "ack",
|
|
2719
|
+
id: env.id
|
|
2720
|
+
});
|
|
2721
|
+
}
|
|
2722
|
+
function onPayload(hub, from, p, envelopeId) {
|
|
2723
|
+
switch (p.type) {
|
|
2724
|
+
case "sessions": {
|
|
2725
|
+
const last = hub.sessionSeq.get(from);
|
|
2726
|
+
if (last !== void 0 && p.seq <= last) return;
|
|
2727
|
+
hub.sessionSeq.set(from, p.seq);
|
|
2728
|
+
hub.remote.set(from, {
|
|
2729
|
+
deviceName: p.deviceName,
|
|
2730
|
+
sessions: p.sessions.map((s) => ({
|
|
2731
|
+
...s,
|
|
2732
|
+
deviceId: from
|
|
2733
|
+
})),
|
|
2734
|
+
receivedAt: hub.ms()
|
|
2735
|
+
});
|
|
2736
|
+
for (const h of hub.state.held(from)) {
|
|
2737
|
+
hub.state.unhold(h.id);
|
|
2738
|
+
const r = safeParse(RelayPayload, h.payload);
|
|
2739
|
+
if (r.ok && r.value.type === "message") onMessage(hub, from, r.value, h.id, h.since);
|
|
2740
|
+
}
|
|
2741
|
+
return;
|
|
2742
|
+
}
|
|
2743
|
+
case "message":
|
|
2744
|
+
onMessage(hub, from, p, envelopeId);
|
|
2745
|
+
return;
|
|
2746
|
+
case "bounce": {
|
|
2747
|
+
const sent = hub.sent.get(p.messageId);
|
|
2748
|
+
if (!sent || sent.toDevice !== from || sent.toSession !== p.toSession || sent.fromSession !== p.fromSession) return;
|
|
2749
|
+
hub.sent.delete(p.messageId);
|
|
2750
|
+
const device = hub.chainState?.members.get(from)?.name ?? "another device";
|
|
2751
|
+
hub.o.host.notify(sent.fromSession, "message.bounced", `Message ${p.messageId} to session "${sent.toName}" on ${device} was not delivered: ${BOUNCE_TEXT[p.reason]}.`);
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
/**
|
|
2757
|
+
* A message from a session on another device. It is delivered only when `from` is one of the
|
|
2758
|
+
* sessions that device publishes, and it is shown with a local alias id and the name
|
|
2759
|
+
* `<device>:<session>`, with the device name from the signed list, whatever the sender put in
|
|
2760
|
+
* the message. One that arrives before the device's session list is stored durably and waits.
|
|
2761
|
+
*/
|
|
2762
|
+
function onMessage(hub, from, p, id, since = hub.ms()) {
|
|
2763
|
+
const r = hub.remote.get(from);
|
|
2764
|
+
if (!r) {
|
|
2765
|
+
if (hub.state.heldCount(from) >= HELD_MESSAGES_PER_DEVICE) {
|
|
2766
|
+
bounce(hub, from, p, "unknown_sender");
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
hub.state.hold(id, from, p, since);
|
|
2770
|
+
return;
|
|
2771
|
+
}
|
|
2772
|
+
const isOwner = p.message.from === OWNER_SESSION_ID;
|
|
2773
|
+
const sender = isOwner ? void 0 : r.sessions.find((s) => s.id === p.message.from);
|
|
2774
|
+
if (!isOwner && !sender) {
|
|
2775
|
+
bounce(hub, from, p, "unknown_sender");
|
|
2776
|
+
return;
|
|
2777
|
+
}
|
|
2778
|
+
if (p.message.kind === "system") {
|
|
2779
|
+
bounce(hub, from, p, "not_allowed");
|
|
2780
|
+
return;
|
|
2781
|
+
}
|
|
2782
|
+
const device = hub.chainState?.members.get(from)?.name ?? r.deviceName;
|
|
2783
|
+
const { fromCli: _c, ...rest } = p.message;
|
|
2784
|
+
const message = sender ? {
|
|
2785
|
+
...p.message,
|
|
2786
|
+
from: hub.state.alias(from, sender.id),
|
|
2787
|
+
to: p.toSession,
|
|
2788
|
+
fromName: remoteSessionName(sender.name, device),
|
|
2789
|
+
fromCli: sender.cli
|
|
2790
|
+
} : {
|
|
2791
|
+
...rest,
|
|
2792
|
+
from: OWNER_SESSION_ID,
|
|
2793
|
+
to: p.toSession,
|
|
2794
|
+
fromName: "you"
|
|
2795
|
+
};
|
|
2796
|
+
const reason = hub.o.host.deliverLocal(message, p.toSession, p.hops ?? 0);
|
|
2797
|
+
if (reason !== void 0) bounce(hub, from, p, reason);
|
|
2798
|
+
}
|
|
2799
|
+
function bounce(hub, to, p, reason) {
|
|
2800
|
+
sendPayload(hub, to, {
|
|
2801
|
+
type: "bounce",
|
|
2802
|
+
messageId: p.message.id,
|
|
2803
|
+
toSession: p.toSession,
|
|
2804
|
+
fromSession: p.message.from,
|
|
2805
|
+
reason
|
|
2806
|
+
});
|
|
2807
|
+
}
|
|
2808
|
+
function expireHeld(hub) {
|
|
2809
|
+
const now = hub.ms();
|
|
2810
|
+
for (const h of hub.state.held()) {
|
|
2811
|
+
if (now - h.since <= HELD_MESSAGE_MS) continue;
|
|
2812
|
+
hub.state.unhold(h.id);
|
|
2813
|
+
const r = safeParse(RelayPayload, h.payload);
|
|
2814
|
+
if (r.ok && r.value.type === "message") bounce(hub, h.from, r.value, "unknown_sender");
|
|
2815
|
+
}
|
|
2816
|
+
for (const [id, m] of hub.sent) if (now - m.at > SENT_MS) hub.sent.delete(id);
|
|
2817
|
+
}
|
|
2818
|
+
/** Send a message to a session on another device. Throws when that cannot be done now. */
|
|
2819
|
+
function sendRemote(hub, target, message, hops = 0) {
|
|
2820
|
+
if (hub.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict, so nothing is sent to other devices. Run \"conveno devices\".");
|
|
2821
|
+
const real = hub.state.unalias(target.id);
|
|
2822
|
+
if (!real) throw new ConvenoError(RpcErrorCode.NotFound, `No session "${target.name}".`);
|
|
2823
|
+
if (!sendPayload(hub, real.device, {
|
|
2824
|
+
type: "message",
|
|
2825
|
+
toSession: real.remote,
|
|
2826
|
+
message,
|
|
2827
|
+
...hops > 0 ? { hops } : {}
|
|
2828
|
+
})) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${target.name}" is on ${target.deviceName ?? "another device"}, and the relay is not connected. Run "conveno relay status".`);
|
|
2829
|
+
hub.sent.set(message.id, {
|
|
2830
|
+
fromSession: message.from,
|
|
2831
|
+
toDevice: real.device,
|
|
2832
|
+
toSession: real.remote,
|
|
2833
|
+
toName: target.name,
|
|
2834
|
+
at: hub.ms()
|
|
2835
|
+
});
|
|
2836
|
+
if (hub.sent.size > SENT_MAX) {
|
|
2837
|
+
const oldest = hub.sent.keys().next().value;
|
|
2838
|
+
if (oldest !== void 0) hub.sent.delete(oldest);
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
const PAIRING_TIMEOUT_MS = 3e5;
|
|
2842
|
+
/** Wrong codes the owner may type before the pairing fails. */
|
|
2843
|
+
const PAIR_CODE_ATTEMPTS = 3;
|
|
2844
|
+
function pairingActive(hub) {
|
|
2845
|
+
const p = hub.pairing;
|
|
2846
|
+
return !!p && p.state !== "done" && p.state !== "failed";
|
|
2847
|
+
}
|
|
2848
|
+
async function pairStart(hub, p) {
|
|
2849
|
+
if (isRevoked(hub)) throw new ConvenoError(RpcErrorCode.Conflict, "This device was removed from the device list.");
|
|
2850
|
+
if (p.role === "join" && paired(hub)) throw new ConvenoError(RpcErrorCode.Conflict, "This device is already paired. Run \"conveno devices pair\" here to add another device instead.");
|
|
2851
|
+
if (hub.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict. Run \"conveno devices\" and resolve it first.");
|
|
2852
|
+
if (p.role === "invite" && hub.chainState && !hub.chainState.members.has(hub.identity.deviceId)) throw new ConvenoError(RpcErrorCode.Conflict, "This device is not in its own device list.");
|
|
2853
|
+
if (pairingActive(hub)) failPairing(hub, "Replaced by a new pairing.");
|
|
2854
|
+
saveIdentity(hub);
|
|
2855
|
+
const record = hub.record();
|
|
2856
|
+
const pairing = {
|
|
2857
|
+
id: newMessageId(),
|
|
2858
|
+
role: p.role,
|
|
2859
|
+
state: "waiting",
|
|
2860
|
+
localConfirmed: false,
|
|
2861
|
+
createdAt: hub.ms(),
|
|
2862
|
+
wrongCodes: 0
|
|
2863
|
+
};
|
|
2864
|
+
if (p.role === "join") {
|
|
2865
|
+
pairing.joiner = new JoinerPairing(hub.identity, record);
|
|
2866
|
+
pairing.resend = { message: pairing.joiner.commit() };
|
|
2867
|
+
} else pairing.inviter = new InviterPairing(hub.identity, record);
|
|
2868
|
+
hub.pairing = pairing;
|
|
2869
|
+
await evaluate(hub);
|
|
2870
|
+
if (hub.connState === "logged_out" || hub.connState === "not_pro") {
|
|
2871
|
+
const detail = hub.detail ?? "Cannot pair now.";
|
|
2872
|
+
failPairing(hub, detail, false);
|
|
2873
|
+
throw new ConvenoError(RpcErrorCode.PermissionRequired, detail);
|
|
2874
|
+
}
|
|
2875
|
+
const tick = setInterval(() => pairingTick(hub), hub.pairResendMs);
|
|
2876
|
+
tick.unref();
|
|
2877
|
+
hub.timers.push(tick);
|
|
2878
|
+
pairingTick(hub);
|
|
2879
|
+
return pairStatus(hub, { pairingId: pairing.id });
|
|
2880
|
+
}
|
|
2881
|
+
function pairingTick(hub) {
|
|
2882
|
+
const p = hub.pairing;
|
|
2883
|
+
if (!p || !pairingActive(hub)) return;
|
|
2884
|
+
if (hub.ms() - p.createdAt > PAIRING_TIMEOUT_MS) {
|
|
2885
|
+
failPairing(hub, "Pairing timed out. Start it again on both devices.");
|
|
2886
|
+
return;
|
|
2887
|
+
}
|
|
2888
|
+
if (p.resend) sendPair(hub, p.resend.message, p.resend.to);
|
|
2889
|
+
}
|
|
2890
|
+
function sendPair(hub, m, to) {
|
|
2891
|
+
if (!hub.link || !hub.linkReady) return;
|
|
2892
|
+
hub.link.send({
|
|
2893
|
+
t: "pair",
|
|
2894
|
+
v: 1,
|
|
2895
|
+
fromDevice: hub.identity.deviceId,
|
|
2896
|
+
...to ? { toDevice: to } : {},
|
|
2897
|
+
data: encodePairMessage(m)
|
|
2898
|
+
});
|
|
2899
|
+
}
|
|
2900
|
+
function failPairing(hub, error, notify = true) {
|
|
2901
|
+
const p = hub.pairing;
|
|
2902
|
+
if (!p) return;
|
|
2903
|
+
const pairingId = p.joiner?.pairingId ?? p.inviter?.pairingId;
|
|
2904
|
+
if (notify && p.peerDevice && pairingId) sendPair(hub, {
|
|
2905
|
+
type: "abort",
|
|
2906
|
+
pairingId,
|
|
2907
|
+
reason: error.slice(0, 200)
|
|
2908
|
+
}, p.peerDevice);
|
|
2909
|
+
p.state = "failed";
|
|
2910
|
+
p.error = error;
|
|
2911
|
+
p.resend = void 0;
|
|
2912
|
+
evaluate(hub);
|
|
2913
|
+
}
|
|
2914
|
+
function onPair(hub, from, to, data) {
|
|
2915
|
+
const p = hub.pairing;
|
|
2916
|
+
if (!p) return;
|
|
2917
|
+
if (to !== void 0 && to !== hub.identity.deviceId) return;
|
|
2918
|
+
let m;
|
|
2919
|
+
try {
|
|
2920
|
+
m = decodePairMessage(data);
|
|
2921
|
+
} catch {
|
|
2922
|
+
return;
|
|
2923
|
+
}
|
|
2924
|
+
if (m.type === "abort") {
|
|
2925
|
+
if (from === p.peerDevice && p.state !== "done") failPairing(hub, `The other device stopped: ${m.reason}`, false);
|
|
2926
|
+
return;
|
|
2927
|
+
}
|
|
2928
|
+
try {
|
|
2929
|
+
if (p.inviter) onPairAsInviter(hub, p, p.inviter, from, m);
|
|
2930
|
+
else if (p.joiner) onPairAsJoiner(hub, p, p.joiner, from, m);
|
|
2931
|
+
} catch (e) {
|
|
2932
|
+
if (p.state === "done") return;
|
|
2933
|
+
failPairing(hub, e instanceof CryptoError ? e.message : "Pairing failed.");
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2936
|
+
function onPairAsInviter(hub, p, inv, from, m) {
|
|
2937
|
+
if (m.type === "commit") {
|
|
2938
|
+
if (hub.chainState?.members.has(from) || hub.chainState?.revoked.has(from) || !hub.online.has(from)) return;
|
|
2939
|
+
if (inv.pairingId === void 0 && p.state === "waiting") {
|
|
2940
|
+
p.offer = inv.onCommit(m);
|
|
2941
|
+
p.peerDevice = from;
|
|
2942
|
+
sendPair(hub, p.offer, from);
|
|
2943
|
+
} else if (m.pairingId === inv.pairingId && from === p.peerDevice && p.offer) sendPair(hub, p.offer, from);
|
|
2944
|
+
return;
|
|
2945
|
+
}
|
|
2946
|
+
if (from !== p.peerDevice || m.pairingId !== inv.pairingId) return;
|
|
2947
|
+
if (m.type === "reveal") {
|
|
2948
|
+
const key = JSON.stringify(m);
|
|
2949
|
+
if (p.lastReveal === key) return;
|
|
2950
|
+
inv.onReveal(m);
|
|
2951
|
+
p.lastReveal = key;
|
|
2952
|
+
if (p.state === "waiting") p.state = "confirm";
|
|
2953
|
+
} else if (m.type === "confirm") {
|
|
2954
|
+
if (p.state === "done" && p.welcome) {
|
|
2955
|
+
sendPair(hub, p.welcome, from);
|
|
2956
|
+
return;
|
|
2957
|
+
}
|
|
2958
|
+
if (inv.joinerHasConfirmed) return;
|
|
2959
|
+
inv.onConfirm(m);
|
|
2960
|
+
if (p.localConfirmed) finishInvite(hub, p, inv);
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
function onPairAsJoiner(hub, p, j, from, m) {
|
|
2964
|
+
if (m.pairingId !== j.pairingId) return;
|
|
2965
|
+
if (m.type === "offer") {
|
|
2966
|
+
if (p.peerDevice !== void 0) return;
|
|
2967
|
+
const reveal = j.onOffer(m);
|
|
2968
|
+
p.peerDevice = from;
|
|
2969
|
+
p.state = "confirm";
|
|
2970
|
+
p.resend = {
|
|
2971
|
+
to: from,
|
|
2972
|
+
message: reveal
|
|
2973
|
+
};
|
|
2974
|
+
sendPair(hub, reveal, from);
|
|
2975
|
+
} else if (m.type === "welcome" && from === p.peerDevice && p.localConfirmed) {
|
|
2976
|
+
if (p.state === "done") return;
|
|
2977
|
+
const { chain } = j.onWelcome(m);
|
|
2978
|
+
const relay = hub.relayChain;
|
|
2979
|
+
const { head, length } = chainHead(chain);
|
|
2980
|
+
let adopt;
|
|
2981
|
+
if (relay) {
|
|
2982
|
+
if (headMatches(relay, head, length)) adopt = relay;
|
|
2983
|
+
} else if (hub.relayHead?.head === head && hub.relayHead.length === length) adopt = chain;
|
|
2984
|
+
if (!adopt) {
|
|
2985
|
+
failPairing(hub, "The relay does not hold the device list the other device sent.");
|
|
2986
|
+
return;
|
|
2987
|
+
}
|
|
2988
|
+
if (!verifyChain(adopt).members.has(hub.identity.deviceId)) {
|
|
2989
|
+
failPairing(hub, "The relay's device list does not include this device.");
|
|
2990
|
+
return;
|
|
2991
|
+
}
|
|
2992
|
+
setChain(hub, adopt);
|
|
2993
|
+
p.state = "done";
|
|
2994
|
+
p.resend = void 0;
|
|
2995
|
+
evaluate(hub);
|
|
2996
|
+
for (const d of hub.online) greet(hub, d);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
/**
|
|
3000
|
+
* Both owners typed the right codes: add the joiner to the list, and once the relay has
|
|
3001
|
+
* accepted the new list, send the joiner its welcome.
|
|
3002
|
+
*/
|
|
3003
|
+
async function finishInvite(hub, p, inv) {
|
|
3004
|
+
if (p.finishing || p.state === "done") return;
|
|
3005
|
+
p.finishing = true;
|
|
3006
|
+
p.state = "waiting_peer";
|
|
3007
|
+
try {
|
|
3008
|
+
const { chain, message } = inv.welcome(hub.chain, hub.ms());
|
|
3009
|
+
await publishList(hub, chain);
|
|
3010
|
+
p.welcome = message;
|
|
3011
|
+
p.state = "done";
|
|
3012
|
+
p.resend = void 0;
|
|
3013
|
+
if (p.peerDevice) sendPair(hub, message, p.peerDevice);
|
|
3014
|
+
if (p.peerDevice && hub.online.has(p.peerDevice)) publishTo(hub, p.peerDevice);
|
|
3015
|
+
evaluate(hub);
|
|
3016
|
+
} catch (e) {
|
|
3017
|
+
failPairing(hub, e instanceof CryptoError ? e.message : `The relay did not accept the new device list: ${e.message}`);
|
|
3018
|
+
} finally {
|
|
3019
|
+
p.finishing = false;
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
function pairStatus(hub, q) {
|
|
3023
|
+
const p = hub.pairing;
|
|
3024
|
+
if (!p || p.id !== q.pairingId) throw new ConvenoError(RpcErrorCode.NotFound, "No pairing with that id. Start one again.");
|
|
3025
|
+
const flow = p.inviter ?? p.joiner;
|
|
3026
|
+
const out = {
|
|
3027
|
+
pairingId: p.id,
|
|
3028
|
+
role: p.role,
|
|
3029
|
+
state: p.state
|
|
3030
|
+
};
|
|
3031
|
+
const sas = flow?.sas;
|
|
3032
|
+
if (sas !== void 0 && p.state !== "failed") out.sas = sas;
|
|
3033
|
+
const peer = flow?.peer;
|
|
3034
|
+
if (peer) out.peer = {
|
|
3035
|
+
deviceId: peer.deviceId,
|
|
3036
|
+
name: peer.name,
|
|
3037
|
+
fingerprint: deviceFingerprint(peer)
|
|
3038
|
+
};
|
|
3039
|
+
if (p.error !== void 0) out.error = p.error;
|
|
3040
|
+
if (p.state === "waiting" && hub.connState !== "connected") out.error = hub.detail ?? "Connecting to the relay.";
|
|
3041
|
+
return out;
|
|
3042
|
+
}
|
|
3043
|
+
function pairConfirm(hub, q) {
|
|
3044
|
+
const p = hub.pairing;
|
|
3045
|
+
if (!p || p.id !== q.pairingId) throw new ConvenoError(RpcErrorCode.NotFound, "No pairing with that id. Start one again.");
|
|
3046
|
+
if (p.state !== "confirm") throw new ConvenoError(RpcErrorCode.Conflict, `The pairing is "${p.state}", not waiting for a confirmation.`);
|
|
3047
|
+
if (!q.accept) {
|
|
3048
|
+
failPairing(hub, "The owner stopped the pairing.");
|
|
3049
|
+
return pairStatus(hub, q);
|
|
3050
|
+
}
|
|
3051
|
+
const expected = (p.inviter ?? p.joiner)?.peerSas;
|
|
3052
|
+
if (!expected || q.code === void 0 || !sasMatches(expected, q.code)) {
|
|
3053
|
+
p.wrongCodes++;
|
|
3054
|
+
if (p.wrongCodes >= PAIR_CODE_ATTEMPTS) {
|
|
3055
|
+
failPairing(hub, "The code did not match the other device's. Someone may be in between: do not retry on this network until you know why.");
|
|
3056
|
+
return pairStatus(hub, q);
|
|
3057
|
+
}
|
|
3058
|
+
const left = PAIR_CODE_ATTEMPTS - p.wrongCodes;
|
|
3059
|
+
return {
|
|
3060
|
+
...pairStatus(hub, q),
|
|
3061
|
+
error: `That is not the code the other device shows. ${left} ${left === 1 ? "try" : "tries"} left.`
|
|
3062
|
+
};
|
|
3063
|
+
}
|
|
3064
|
+
p.localConfirmed = true;
|
|
3065
|
+
if (p.inviter) {
|
|
3066
|
+
if (p.inviter.joinerHasConfirmed) finishInvite(hub, p, p.inviter);
|
|
3067
|
+
else p.state = "waiting_peer";
|
|
3068
|
+
} else if (p.joiner && p.peerDevice) {
|
|
3069
|
+
const confirm = p.joiner.confirm();
|
|
3070
|
+
p.state = "waiting_peer";
|
|
3071
|
+
p.resend = {
|
|
3072
|
+
to: p.peerDevice,
|
|
3073
|
+
message: confirm
|
|
3074
|
+
};
|
|
3075
|
+
sendPair(hub, confirm, p.peerDevice);
|
|
3076
|
+
}
|
|
3077
|
+
return pairStatus(hub, q);
|
|
3078
|
+
}
|
|
3079
|
+
/**
|
|
3080
|
+
* The schema of relay.db. 001 is the schema from before relay.db had migrations, with
|
|
3081
|
+
* `IF NOT EXISTS` kept: a relay.db made then already has its tables, so 001 changes nothing there
|
|
3082
|
+
* and is only recorded.
|
|
3083
|
+
*/
|
|
3084
|
+
const RELAY_MIGRATIONS = [{
|
|
3085
|
+
name: "001_initial",
|
|
3086
|
+
sql: `
|
|
3087
|
+
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
3088
|
+
CREATE TABLE IF NOT EXISTS seen (id TEXT PRIMARY KEY, ts INTEGER NOT NULL);
|
|
3089
|
+
CREATE INDEX IF NOT EXISTS seen_ts ON seen (ts);
|
|
3090
|
+
-- Messages from another device that arrived before its session list. Stored before the
|
|
3091
|
+
-- envelope is acknowledged, so a restart or a flood cannot lose them.
|
|
3092
|
+
CREATE TABLE IF NOT EXISTS held (
|
|
3093
|
+
id TEXT PRIMARY KEY,
|
|
3094
|
+
from_device TEXT NOT NULL,
|
|
3095
|
+
payload TEXT NOT NULL,
|
|
3096
|
+
since INTEGER NOT NULL
|
|
3097
|
+
);
|
|
3098
|
+
-- Local ids for sessions on other devices, so they can never collide with local ones.
|
|
3099
|
+
CREATE TABLE IF NOT EXISTS alias (
|
|
3100
|
+
alias TEXT PRIMARY KEY,
|
|
3101
|
+
device_id TEXT NOT NULL,
|
|
3102
|
+
remote_id TEXT NOT NULL,
|
|
3103
|
+
UNIQUE (device_id, remote_id)
|
|
3104
|
+
);
|
|
3105
|
+
`
|
|
3106
|
+
}];
|
|
3107
|
+
const restrictIfPresent = (path) => {
|
|
3108
|
+
if (process.platform !== "win32" && existsSync(path)) chmodSync(path, 384);
|
|
3109
|
+
};
|
|
3110
|
+
/**
|
|
3111
|
+
* Rename, retrying for a few seconds while Windows reports the file busy: a virus scanner often
|
|
3112
|
+
* holds a file that was just written (graceful-fs retries renames for the same reason).
|
|
3113
|
+
*/
|
|
3114
|
+
function renameRetrying(from, to) {
|
|
3115
|
+
const wait = new Int32Array(new SharedArrayBuffer(4));
|
|
3116
|
+
for (let attempt = 0;; attempt++) try {
|
|
3117
|
+
renameSync(from, to);
|
|
3118
|
+
return;
|
|
3119
|
+
} catch (e) {
|
|
3120
|
+
const code = e.code;
|
|
3121
|
+
if (attempt >= 30 || code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw e;
|
|
3122
|
+
Atomics.wait(wait, 0, 0, Math.min(25 * (attempt + 1), 200));
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
/**
|
|
3126
|
+
* The user-only directory new key files are written in before they are renamed into place, so a
|
|
3127
|
+
* key file never exists with the data folder's own, possibly broader, permissions. Made private
|
|
3128
|
+
* once; a marker file inside it records that on Windows, where icacls is slow.
|
|
3129
|
+
*/
|
|
3130
|
+
function keyStagingDir(path, o, platform) {
|
|
3131
|
+
const dir = join(dirname(path), ".key-staging");
|
|
3132
|
+
const restrictDir = o.restrictDir ?? ((d) => restrictToUser(d, platform, true));
|
|
3133
|
+
mkdirSync(dir, {
|
|
3134
|
+
recursive: true,
|
|
3135
|
+
mode: 448
|
|
3136
|
+
});
|
|
3137
|
+
const marker = join(dir, ".acl");
|
|
3138
|
+
if (platform !== "win32") restrictDir(dir);
|
|
3139
|
+
else if (!existsSync(marker)) {
|
|
3140
|
+
restrictDir(dir);
|
|
3141
|
+
writeFileSync(marker, "user-only ACL set\n");
|
|
3142
|
+
}
|
|
3143
|
+
return dir;
|
|
3144
|
+
}
|
|
3145
|
+
/**
|
|
3146
|
+
* The identity stored at `path`, or undefined. Upgrades an old Windows key file's ACL once (a
|
|
3147
|
+
* marker file `<key>.acl` records it). The relay device id is separate from the session store's,
|
|
3148
|
+
* so deleting this file (with relay.db) gives the machine a fresh identity that can be paired
|
|
3149
|
+
* again after a revocation.
|
|
3150
|
+
*/
|
|
3151
|
+
function loadIdentity(path, o = {}) {
|
|
3152
|
+
if (!existsSync(path)) return void 0;
|
|
3153
|
+
const platform = o.platform ?? process.platform;
|
|
3154
|
+
const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
|
|
3155
|
+
const marker = `${path}.acl`;
|
|
3156
|
+
const id = parseIdentity(JSON.parse(readFileSync(path, "utf8")));
|
|
3157
|
+
if (platform === "win32") {
|
|
3158
|
+
if (!existsSync(marker)) {
|
|
3159
|
+
restrict(path);
|
|
3160
|
+
writeFileSync(marker, "user-only ACL set\n");
|
|
3161
|
+
}
|
|
3162
|
+
} else restrict(path);
|
|
3163
|
+
return id;
|
|
3164
|
+
}
|
|
3165
|
+
/**
|
|
3166
|
+
* Write a new identity: a temporary file in the user-only staging directory, restricted to the
|
|
3167
|
+
* user itself as well, then renamed into place (a rename on one volume keeps the file's ACL).
|
|
3168
|
+
*/
|
|
3169
|
+
function saveNewIdentity(path, id, o = {}) {
|
|
3170
|
+
const platform = o.platform ?? process.platform;
|
|
3171
|
+
const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
|
|
3172
|
+
const tmp = join(keyStagingDir(path, o, platform), `${randomBytes$1(6).toString("hex")}.tmp`);
|
|
3173
|
+
try {
|
|
3174
|
+
writeFileSync(tmp, `${JSON.stringify(serializeIdentity(id))}\n`, {
|
|
3175
|
+
mode: 384,
|
|
3176
|
+
flag: "wx"
|
|
3177
|
+
});
|
|
3178
|
+
restrict(tmp);
|
|
3179
|
+
renameRetrying(tmp, path);
|
|
3180
|
+
} catch (e) {
|
|
3181
|
+
rmSync(tmp, { force: true });
|
|
3182
|
+
throw e;
|
|
3183
|
+
}
|
|
3184
|
+
if (platform === "win32") writeFileSync(`${path}.acl`, "user-only ACL set\n");
|
|
3185
|
+
}
|
|
3186
|
+
/** SQLite state of the relay client, in its own file so it never touches the session store. */
|
|
3187
|
+
var RelayState = class {
|
|
3188
|
+
path;
|
|
3189
|
+
handle;
|
|
3190
|
+
/**
|
|
3191
|
+
* The file is created only when there is something to keep. Creating it (WAL mode and the
|
|
3192
|
+
* schema) costs tens of milliseconds of disk syncs, which a daemon that never uses the relay
|
|
3193
|
+
* should not pay at every start.
|
|
3194
|
+
*/
|
|
3195
|
+
constructor(path) {
|
|
3196
|
+
this.path = path;
|
|
3197
|
+
}
|
|
3198
|
+
/** The open database, created on first write. */
|
|
3199
|
+
get db() {
|
|
3200
|
+
return this.handle ?? this.open();
|
|
3201
|
+
}
|
|
3202
|
+
/** The database for a read: undefined while the file does not exist, which reads as empty. */
|
|
3203
|
+
get reader() {
|
|
3204
|
+
return this.handle ?? (existsSync(this.path) ? this.open() : void 0);
|
|
3205
|
+
}
|
|
3206
|
+
open() {
|
|
3207
|
+
const path = this.path;
|
|
3208
|
+
const db = new DatabaseSync(path);
|
|
3209
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
3210
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
3211
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
3212
|
+
migrate(db, RELAY_MIGRATIONS);
|
|
3213
|
+
for (const f of [
|
|
3214
|
+
path,
|
|
3215
|
+
`${path}-wal`,
|
|
3216
|
+
`${path}-shm`
|
|
3217
|
+
]) restrictIfPresent(f);
|
|
3218
|
+
this.handle = db;
|
|
3219
|
+
return db;
|
|
3220
|
+
}
|
|
3221
|
+
close() {
|
|
3222
|
+
this.handle?.close();
|
|
3223
|
+
this.handle = void 0;
|
|
3224
|
+
}
|
|
3225
|
+
/** The migrations relay.db has had; none while the file does not exist. */
|
|
3226
|
+
migrationNames() {
|
|
3227
|
+
const db = this.reader;
|
|
3228
|
+
return db ? migrationNames(db) : [];
|
|
3229
|
+
}
|
|
3230
|
+
get(key) {
|
|
3231
|
+
return (this.reader?.prepare("SELECT value FROM kv WHERE key = ?").get(key))?.value;
|
|
3232
|
+
}
|
|
3233
|
+
set(key, value) {
|
|
3234
|
+
if (value === void 0) this.reader?.prepare("DELETE FROM kv WHERE key = ?").run(key);
|
|
3235
|
+
else this.db.prepare("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = ?").run(key, value, value);
|
|
3236
|
+
}
|
|
3237
|
+
/** The device list, or undefined when this device has none yet. Verified by the caller. */
|
|
3238
|
+
chain() {
|
|
3239
|
+
const raw = this.get("chain");
|
|
3240
|
+
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
3241
|
+
}
|
|
3242
|
+
setChain(chain) {
|
|
3243
|
+
this.set("chain", chain === void 0 ? void 0 : JSON.stringify(chain));
|
|
3244
|
+
}
|
|
3245
|
+
/** An unresolved disagreement about the device list, until the owner accepts a head. */
|
|
3246
|
+
conflict() {
|
|
3247
|
+
const raw = this.get("conflict");
|
|
3248
|
+
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
3249
|
+
}
|
|
3250
|
+
setConflict(c) {
|
|
3251
|
+
this.set("conflict", c === void 0 ? void 0 : JSON.stringify(c));
|
|
3252
|
+
}
|
|
3253
|
+
hold(id, from, payload, since) {
|
|
3254
|
+
this.db.prepare("INSERT OR IGNORE INTO held (id, from_device, payload, since) VALUES (?, ?, ?, ?)").run(id, from, JSON.stringify(payload), since);
|
|
3255
|
+
}
|
|
3256
|
+
heldCount(from) {
|
|
3257
|
+
return (this.reader?.prepare("SELECT COUNT(*) AS n FROM held WHERE from_device = ?").get(from))?.n ?? 0;
|
|
3258
|
+
}
|
|
3259
|
+
/** Held messages, oldest first; from one device, or all. */
|
|
3260
|
+
held(from) {
|
|
3261
|
+
const db = this.reader;
|
|
3262
|
+
if (!db) return [];
|
|
3263
|
+
return (from === void 0 ? db.prepare("SELECT * FROM held ORDER BY since, id").all() : db.prepare("SELECT * FROM held WHERE from_device = ? ORDER BY since, id").all(from)).map((r) => ({
|
|
3264
|
+
id: r.id,
|
|
3265
|
+
from: r.from_device,
|
|
3266
|
+
payload: JSON.parse(r.payload),
|
|
3267
|
+
since: r.since
|
|
3268
|
+
}));
|
|
3269
|
+
}
|
|
3270
|
+
unhold(id) {
|
|
3271
|
+
this.reader?.prepare("DELETE FROM held WHERE id = ?").run(id);
|
|
3272
|
+
}
|
|
3273
|
+
/** The local id for a session on another device, made on first use. */
|
|
3274
|
+
alias(device, remote) {
|
|
3275
|
+
const row = this.db.prepare("SELECT alias FROM alias WHERE device_id = ? AND remote_id = ?").get(device, remote);
|
|
3276
|
+
if (row) return row.alias;
|
|
3277
|
+
const id = newSessionId();
|
|
3278
|
+
this.db.prepare("INSERT INTO alias (alias, device_id, remote_id) VALUES (?, ?, ?)").run(id, device, remote);
|
|
3279
|
+
return id;
|
|
3280
|
+
}
|
|
3281
|
+
/** The device and remote id behind a local alias. */
|
|
3282
|
+
unalias(alias) {
|
|
3283
|
+
const row = this.reader?.prepare("SELECT device_id, remote_id FROM alias WHERE alias = ?").get(alias);
|
|
3284
|
+
return row ? {
|
|
3285
|
+
device: row.device_id,
|
|
3286
|
+
remote: row.remote_id
|
|
3287
|
+
} : void 0;
|
|
3288
|
+
}
|
|
3289
|
+
deviceName() {
|
|
3290
|
+
return this.get("device_name");
|
|
3291
|
+
}
|
|
3292
|
+
setDeviceName(name) {
|
|
3293
|
+
this.set("device_name", name);
|
|
3294
|
+
}
|
|
3295
|
+
/** Run `f` in one SQLite transaction: all of its writes happen, or none. */
|
|
3296
|
+
atomically(f) {
|
|
3297
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
3298
|
+
try {
|
|
3299
|
+
f();
|
|
3300
|
+
this.db.exec("COMMIT");
|
|
3301
|
+
} catch (e) {
|
|
3302
|
+
this.db.exec("ROLLBACK");
|
|
3303
|
+
throw e;
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
has(id) {
|
|
3307
|
+
return this.reader?.prepare("SELECT 1 AS x FROM seen WHERE id = ?").get(id) !== void 0;
|
|
3308
|
+
}
|
|
3309
|
+
add(id, ts) {
|
|
3310
|
+
this.db.prepare("INSERT OR IGNORE INTO seen (id, ts) VALUES (?, ?)").run(id, ts);
|
|
3311
|
+
}
|
|
3312
|
+
/** Forget ids that are too old to be accepted again anyway. */
|
|
3313
|
+
pruneSeen(nowMs) {
|
|
3314
|
+
const before = nowMs - ENVELOPE_MAX_AGE_MS - ENVELOPE_MAX_FUTURE_MS;
|
|
3315
|
+
this.reader?.prepare("DELETE FROM seen WHERE ts < ?").run(before);
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
const MAX_BACKOFF_MS = 6e4;
|
|
3319
|
+
/**
|
|
3320
|
+
* Relay error codes after which retrying soon cannot help. `token_expired` is not one: the next
|
|
3321
|
+
* attempt renews the token.
|
|
3322
|
+
*/
|
|
3323
|
+
const AUTH_CODES = /* @__PURE__ */ new Set([
|
|
3324
|
+
"unauthorized",
|
|
3325
|
+
"plan_required",
|
|
3326
|
+
"device_key_mismatch",
|
|
3327
|
+
"device_mismatch",
|
|
3328
|
+
"device_revoked"
|
|
3329
|
+
]);
|
|
3330
|
+
/** What the owner sees when the relay refuses this version of Conveno. */
|
|
3331
|
+
function upgradeText(clientVersion, minVersion) {
|
|
3332
|
+
const pkg = clientVersion?.includes("-") ? "@conveno/cli@next" : "@conveno/cli@latest";
|
|
3333
|
+
return `${minVersion ? `The relay needs Conveno ${minVersion} or newer. ` : ""}Update Conveno to keep using your other computers: npm i -g ${pkg}`;
|
|
3334
|
+
}
|
|
3335
|
+
function start(hub) {
|
|
3336
|
+
evaluate(hub);
|
|
3337
|
+
const t = setInterval(() => {
|
|
3338
|
+
evaluate(hub);
|
|
3339
|
+
if (hub.linkReady) publishAll(hub);
|
|
3340
|
+
expireRemote(hub);
|
|
3341
|
+
expireHeld(hub);
|
|
3342
|
+
}, hub.publishMs);
|
|
3343
|
+
t.unref();
|
|
3344
|
+
hub.timers.push(t);
|
|
3345
|
+
const prune = setInterval(() => hub.state.pruneSeen(hub.ms()), 36e5);
|
|
3346
|
+
prune.unref();
|
|
3347
|
+
hub.timers.push(prune);
|
|
3348
|
+
}
|
|
3349
|
+
function stop(hub) {
|
|
3350
|
+
hub.stopped = true;
|
|
3351
|
+
for (const t of hub.timers) clearInterval(t);
|
|
3352
|
+
if (hub.retryTimer) clearTimeout(hub.retryTimer);
|
|
3353
|
+
if (hub.publishTimer) clearTimeout(hub.publishTimer);
|
|
3354
|
+
disconnect(hub);
|
|
3355
|
+
hub.state.close();
|
|
3356
|
+
}
|
|
3357
|
+
/**
|
|
3358
|
+
* Decide whether to be connected, and connect or disconnect. Called often; runs one check at a
|
|
3359
|
+
* time and once more if asked meanwhile. The returned promise settles when the check is done.
|
|
3360
|
+
*/
|
|
3361
|
+
function evaluate(hub) {
|
|
3362
|
+
if (hub.evaluating) {
|
|
3363
|
+
hub.evaluateAgain = true;
|
|
3364
|
+
return hub.evaluating;
|
|
3365
|
+
}
|
|
3366
|
+
hub.evaluating = (async () => {
|
|
3367
|
+
do {
|
|
3368
|
+
hub.evaluateAgain = false;
|
|
3369
|
+
try {
|
|
3370
|
+
await evaluateOnce(hub);
|
|
3371
|
+
} catch (e) {
|
|
3372
|
+
hub.o.host.log.error("relay: state check failed", e);
|
|
3373
|
+
}
|
|
3374
|
+
} while (hub.evaluateAgain && !hub.stopped);
|
|
3375
|
+
})().finally(() => {
|
|
3376
|
+
hub.evaluating = void 0;
|
|
3377
|
+
});
|
|
3378
|
+
return hub.evaluating;
|
|
3379
|
+
}
|
|
3380
|
+
async function evaluateOnce(hub) {
|
|
3381
|
+
if (hub.stopped) return;
|
|
3382
|
+
if (isRevoked(hub)) return idle(hub, "revoked", "This device was removed from the device list.");
|
|
3383
|
+
if (hub.upgradeRequired) return idle(hub, "upgrade_required", hub.upgradeRequired);
|
|
3384
|
+
const want = paired(hub) || pairingActive(hub);
|
|
3385
|
+
const self = hub.identity.deviceId;
|
|
3386
|
+
if (!want) {
|
|
3387
|
+
const stored = await hub.accessToken(false, self);
|
|
3388
|
+
if (!stored) return idle(hub, "logged_out", "Not logged in. Run \"conveno login\".");
|
|
3389
|
+
if (jwtClaim(stored, "plan") !== "pro") return idle(hub, "not_pro", NOT_PRO);
|
|
3390
|
+
return idle(hub, "unpaired", "Pair this device first: \"conveno devices pair\".");
|
|
3391
|
+
}
|
|
3392
|
+
let token;
|
|
3393
|
+
try {
|
|
3394
|
+
token = await hub.accessToken(true, self);
|
|
3395
|
+
} catch (e) {
|
|
3396
|
+
if (e instanceof AccountError && e.code === "session_expired") return idle(hub, "logged_out", `${e.message} Run "conveno login" again.`);
|
|
3397
|
+
if (!hub.link) {
|
|
3398
|
+
hub.connState = "disconnected";
|
|
3399
|
+
hub.detail = "Could not renew the access token. Retrying.";
|
|
3400
|
+
}
|
|
3401
|
+
return;
|
|
3402
|
+
}
|
|
3403
|
+
if (hub.stopped) return;
|
|
3404
|
+
if (!token) return idle(hub, "logged_out", "Not logged in. Run \"conveno login\".");
|
|
3405
|
+
if (jwtClaim(token, "plan") !== "pro") return idle(hub, "not_pro", NOT_PRO);
|
|
3406
|
+
if (hub.link || hub.retryTimer) return;
|
|
3407
|
+
saveIdentity(hub);
|
|
3408
|
+
hub.connState = "connecting";
|
|
3409
|
+
hub.detail = void 0;
|
|
3410
|
+
hub.link = hub.connectImpl({
|
|
3411
|
+
url: hub.url,
|
|
3412
|
+
identity: hub.identity,
|
|
3413
|
+
token,
|
|
3414
|
+
events: {
|
|
3415
|
+
ready: (online) => onReady(hub, online),
|
|
3416
|
+
frame: (f) => onFrame$1(hub, f),
|
|
3417
|
+
down: (detail, code, min) => onDown(hub, detail, code, min)
|
|
3418
|
+
},
|
|
3419
|
+
...hub.o.clientVersion ? { client: {
|
|
3420
|
+
name: RELAY_CLIENT_NAME,
|
|
3421
|
+
version: hub.o.clientVersion
|
|
3422
|
+
} } : {},
|
|
3423
|
+
log: (line) => hub.o.host.log.note(line)
|
|
3424
|
+
});
|
|
3425
|
+
hub.link.start();
|
|
3426
|
+
}
|
|
3427
|
+
function saveIdentity(hub) {
|
|
3428
|
+
if (hub.identitySaved) return;
|
|
3429
|
+
saveNewIdentity(hub.identityPath, hub.identity);
|
|
3430
|
+
hub.identitySaved = true;
|
|
3431
|
+
}
|
|
3432
|
+
function idle(hub, state, detail) {
|
|
3433
|
+
hub.connState = state;
|
|
3434
|
+
hub.detail = detail;
|
|
3435
|
+
disconnect(hub);
|
|
3436
|
+
}
|
|
3437
|
+
function disconnect(hub) {
|
|
3438
|
+
hub.link?.stop();
|
|
3439
|
+
hub.link = void 0;
|
|
3440
|
+
hub.linkReady = false;
|
|
3441
|
+
hub.listReceived = false;
|
|
3442
|
+
hub.online.clear();
|
|
3443
|
+
hub.remote.clear();
|
|
3444
|
+
failPendingList(hub, "The relay connection closed.");
|
|
3445
|
+
}
|
|
3446
|
+
function onReady(hub, online) {
|
|
3447
|
+
hub.linkReady = true;
|
|
3448
|
+
hub.listReceived = false;
|
|
3449
|
+
hub.failures = 0;
|
|
3450
|
+
hub.connState = "connected";
|
|
3451
|
+
hub.detail = void 0;
|
|
3452
|
+
hub.online.clear();
|
|
3453
|
+
for (const d of online) hub.online.add(d);
|
|
3454
|
+
pairingTick(hub);
|
|
3455
|
+
}
|
|
3456
|
+
function onDown(hub, detail, frameCode, frameMin) {
|
|
3457
|
+
const code = frameCode ?? hub.lastErrorCode;
|
|
3458
|
+
const min = frameMin ?? hub.lastErrorMin;
|
|
3459
|
+
hub.lastErrorCode = void 0;
|
|
3460
|
+
hub.lastErrorMin = void 0;
|
|
3461
|
+
hub.link = void 0;
|
|
3462
|
+
hub.linkReady = false;
|
|
3463
|
+
hub.listReceived = false;
|
|
3464
|
+
hub.online.clear();
|
|
3465
|
+
hub.remote.clear();
|
|
3466
|
+
failPendingList(hub, "The relay connection closed.");
|
|
3467
|
+
if (hub.stopped) return;
|
|
3468
|
+
if (code === "device_revoked") {
|
|
3469
|
+
hub.relayRevoked = true;
|
|
3470
|
+
idle(hub, "revoked", "The relay says the device list revokes this device.");
|
|
3471
|
+
return;
|
|
3472
|
+
}
|
|
3473
|
+
if (code === "upgrade_required") {
|
|
3474
|
+
hub.upgradeRequired = upgradeText(hub.o.clientVersion, min);
|
|
3475
|
+
hub.o.host.log.note(`relay: refused this version of Conveno (${detail})`);
|
|
3476
|
+
idle(hub, "upgrade_required", hub.upgradeRequired);
|
|
3477
|
+
return;
|
|
3478
|
+
}
|
|
3479
|
+
hub.connState = "disconnected";
|
|
3480
|
+
hub.detail = detail;
|
|
3481
|
+
hub.failures++;
|
|
3482
|
+
const backoff = code !== void 0 && AUTH_CODES.has(code) ? MAX_BACKOFF_MS : Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** Math.min(hub.failures - 1, 6));
|
|
3483
|
+
const delay = Math.round(backoff * (.5 + Math.random() / 2));
|
|
3484
|
+
hub.retryTimer = setTimeout(() => {
|
|
3485
|
+
hub.retryTimer = void 0;
|
|
3486
|
+
evaluate(hub);
|
|
3487
|
+
}, delay);
|
|
3488
|
+
hub.retryTimer.unref();
|
|
3489
|
+
}
|
|
3490
|
+
function onFrame$1(hub, f) {
|
|
3491
|
+
switch (f.t) {
|
|
3492
|
+
case "list":
|
|
3493
|
+
onRelayList(hub, f.chain, f.head !== void 0 && f.length !== void 0 ? {
|
|
3494
|
+
head: f.head,
|
|
3495
|
+
length: f.length
|
|
3496
|
+
} : void 0);
|
|
3497
|
+
return;
|
|
3498
|
+
case "envelope":
|
|
3499
|
+
onEnvelope(hub, f);
|
|
3500
|
+
return;
|
|
3501
|
+
case "presence":
|
|
3502
|
+
if (f.online) {
|
|
3503
|
+
hub.online.add(f.deviceId);
|
|
3504
|
+
if (hub.listReceived) greet(hub, f.deviceId);
|
|
3505
|
+
} else {
|
|
3506
|
+
hub.online.delete(f.deviceId);
|
|
3507
|
+
hub.remote.delete(f.deviceId);
|
|
3508
|
+
}
|
|
3509
|
+
return;
|
|
3510
|
+
case "pair":
|
|
3511
|
+
onPair(hub, f.fromDevice, f.toDevice, f.data);
|
|
3512
|
+
return;
|
|
3513
|
+
case "error":
|
|
3514
|
+
hub.detail = `The relay reported: ${f.message}`;
|
|
3515
|
+
hub.lastErrorCode = f.code;
|
|
3516
|
+
hub.lastErrorMin = f.minVersion;
|
|
3517
|
+
if (f.code === "list_rejected") failPendingList(hub, f.message);
|
|
3518
|
+
return;
|
|
3519
|
+
default: return;
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
function loadChain(hub, chain) {
|
|
3523
|
+
if (!chain) {
|
|
3524
|
+
hub.chain = void 0;
|
|
3525
|
+
hub.chainState = void 0;
|
|
3526
|
+
return;
|
|
3527
|
+
}
|
|
3528
|
+
try {
|
|
3529
|
+
hub.chainState = verifyChain(chain);
|
|
3530
|
+
hub.chain = chain;
|
|
3531
|
+
} catch (e) {
|
|
3532
|
+
hub.o.host.log.error("relay: the stored device list does not verify", e);
|
|
3533
|
+
hub.chain = void 0;
|
|
3534
|
+
hub.chainState = void 0;
|
|
3535
|
+
}
|
|
3536
|
+
}
|
|
3537
|
+
function setChain(hub, chain) {
|
|
3538
|
+
hub.state.setChain(chain);
|
|
3539
|
+
loadChain(hub, chain);
|
|
3540
|
+
for (const id of [...hub.remote.keys()]) if (!member(hub, id)) hub.remote.delete(id);
|
|
3541
|
+
}
|
|
3542
|
+
/**
|
|
3543
|
+
* An active device of the list other than this one. While there is a conflict about the list,
|
|
3544
|
+
* none is: nothing is sent and nothing is accepted.
|
|
3545
|
+
*/
|
|
3546
|
+
function member(hub, deviceId) {
|
|
3547
|
+
if (deviceId === hub.identity.deviceId || hub.conflict) return void 0;
|
|
3548
|
+
return hub.chainState?.members.get(deviceId);
|
|
3549
|
+
}
|
|
3550
|
+
function isRevoked(hub) {
|
|
3551
|
+
return hub.relayRevoked || (hub.chainState?.revoked.has(hub.identity.deviceId) ?? false);
|
|
3552
|
+
}
|
|
3553
|
+
function paired(hub) {
|
|
3554
|
+
const s = hub.chainState;
|
|
3555
|
+
return !!s && s.members.has(hub.identity.deviceId) && s.members.size > 1;
|
|
3556
|
+
}
|
|
3557
|
+
function setConflict(hub, kind, detail, peer) {
|
|
3558
|
+
if (hub.conflict) return;
|
|
3559
|
+
const c = {
|
|
3560
|
+
kind,
|
|
3561
|
+
detail,
|
|
3562
|
+
at: hub.now().toISOString()
|
|
3563
|
+
};
|
|
3564
|
+
if (hub.chain) c.local = chainHead(hub.chain);
|
|
3565
|
+
if (hub.relayHead) c.relay = hub.relayHead;
|
|
3566
|
+
if (peer) c.peer = peer;
|
|
3567
|
+
hub.conflict = c;
|
|
3568
|
+
hub.state.setConflict(c);
|
|
3569
|
+
hub.remote.clear();
|
|
3570
|
+
hub.o.host.log.error("relay: device list conflict, nothing is sent until it is resolved", detail);
|
|
3571
|
+
}
|
|
3572
|
+
/**
|
|
3573
|
+
* The relay's list, after `ready` and whenever it changes. Adopted when it extends this
|
|
3574
|
+
* device's list; anything else is a conflict. `headOnly` is what a device that is not a member
|
|
3575
|
+
* of the relay's list gets instead of the list.
|
|
3576
|
+
*/
|
|
3577
|
+
function onRelayList(hub, raw, headOnly) {
|
|
3578
|
+
let relay;
|
|
3579
|
+
if (raw.length > 0) try {
|
|
3580
|
+
verifyChain(raw);
|
|
3581
|
+
relay = raw;
|
|
3582
|
+
} catch {
|
|
3583
|
+
setConflict(hub, "not_prefix", "The relay sent a device list that does not verify.");
|
|
3584
|
+
}
|
|
3585
|
+
hub.relayChain = relay;
|
|
3586
|
+
hub.relayHead = relay ? chainHead(relay) : headOnly;
|
|
3587
|
+
if (!relay && headOnly && hub.chain && !hub.conflict) setConflict(hub, "not_prefix", "The relay holds a device list that does not include this device.");
|
|
3588
|
+
const pending = hub.pendingList;
|
|
3589
|
+
if (relay && pending && chainHead(relay).head === pending.head) {
|
|
3590
|
+
setChain(hub, relay);
|
|
3591
|
+
hub.pendingList = void 0;
|
|
3592
|
+
clearTimeout(pending.timer);
|
|
3593
|
+
pending.resolve();
|
|
3594
|
+
} else if (hub.chain && !hub.conflict && !headOnly) {
|
|
3595
|
+
const at = relay ? forkPoint(hub.chain, relay) : 0;
|
|
3596
|
+
if (!relay || at >= 0 || relay.length < hub.chain.length) setConflict(hub, "not_prefix", relay ? "The relay holds a device list that this device's list is not part of." : "The relay holds no device list, but this device has one.");
|
|
3597
|
+
else if (relay.length > hub.chain.length) setChain(hub, relay);
|
|
3598
|
+
}
|
|
3599
|
+
if (isRevoked(hub)) {
|
|
3600
|
+
evaluate(hub);
|
|
3601
|
+
return;
|
|
3602
|
+
}
|
|
3603
|
+
const first = !hub.listReceived;
|
|
3604
|
+
hub.listReceived = true;
|
|
3605
|
+
if (first) for (const d of hub.online) greet(hub, d);
|
|
3606
|
+
}
|
|
3607
|
+
/**
|
|
3608
|
+
* Ask the relay to store a new version of the list. Resolves once the relay accepted it (and
|
|
3609
|
+
* this device adopted it); rejects when the relay refuses it, does not answer, or the
|
|
3610
|
+
* connection drops.
|
|
3611
|
+
*/
|
|
3612
|
+
function publishList(hub, chain) {
|
|
3613
|
+
if (!hub.link || !hub.linkReady || !hub.listReceived) return Promise.reject(/* @__PURE__ */ new Error("The relay is not connected."));
|
|
3614
|
+
if (hub.pendingList) return Promise.reject(/* @__PURE__ */ new Error("Another device list change is waiting for the relay."));
|
|
3615
|
+
const { head } = chainHead(chain);
|
|
3616
|
+
return new Promise((resolve, reject) => {
|
|
3617
|
+
const timer = setTimeout(() => failPendingList(hub, "The relay did not answer."), hub.listTimeoutMs);
|
|
3618
|
+
timer.unref();
|
|
3619
|
+
hub.pendingList = {
|
|
3620
|
+
head,
|
|
3621
|
+
resolve,
|
|
3622
|
+
reject,
|
|
3623
|
+
timer
|
|
3624
|
+
};
|
|
3625
|
+
hub.link?.send({
|
|
3626
|
+
t: "list",
|
|
3627
|
+
v: 1,
|
|
3628
|
+
chain
|
|
3629
|
+
});
|
|
3630
|
+
});
|
|
3631
|
+
}
|
|
3632
|
+
function failPendingList(hub, why) {
|
|
3633
|
+
const p = hub.pendingList;
|
|
3634
|
+
if (!p) return;
|
|
3635
|
+
hub.pendingList = void 0;
|
|
3636
|
+
clearTimeout(p.timer);
|
|
3637
|
+
p.reject(new Error(why));
|
|
3638
|
+
}
|
|
3639
|
+
/** A device came online: send it our sessions. */
|
|
3640
|
+
function greet(hub, deviceId) {
|
|
3641
|
+
if (!member(hub, deviceId)) return;
|
|
3642
|
+
publishTo(hub, deviceId);
|
|
3643
|
+
}
|
|
3644
|
+
/**
|
|
3645
|
+
* Recover from a conflict: adopt the relay's list, but only if its head is the one the owner
|
|
3646
|
+
* read on a device that is a member of it.
|
|
3647
|
+
*/
|
|
3648
|
+
function accept(hub, p) {
|
|
3649
|
+
if (!hub.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has no conflict.");
|
|
3650
|
+
const relay = hub.relayChain;
|
|
3651
|
+
if (!relay?.length) throw new ConvenoError(RpcErrorCode.NotFound, hub.relayHead ? "The relay's device list does not include this device. Run \"conveno devices reset\", then pair it again." : "The relay holds no device list (the devices were reset). Run \"conveno devices reset\", then pair again.");
|
|
3652
|
+
const head = chainHead(relay);
|
|
3653
|
+
if (head.head !== p.head) throw new ConvenoError(RpcErrorCode.Conflict, `The relay's device list has head ${head.head.slice(0, 16)}, not ${p.head.slice(0, 16)}. Nothing was changed.`);
|
|
3654
|
+
hub.conflict = void 0;
|
|
3655
|
+
hub.state.setConflict(void 0);
|
|
3656
|
+
setChain(hub, relay);
|
|
3657
|
+
const member = hub.chainState?.members.has(hub.identity.deviceId) ?? false;
|
|
3658
|
+
if (hub.linkReady && hub.listReceived) for (const d of hub.online) greet(hub, d);
|
|
3659
|
+
evaluate(hub);
|
|
3660
|
+
return {
|
|
3661
|
+
list: head,
|
|
3662
|
+
member
|
|
3663
|
+
};
|
|
3664
|
+
}
|
|
3665
|
+
/**
|
|
3666
|
+
* Revoke a device: append the revocation, and once the relay has accepted it (which also cuts
|
|
3667
|
+
* the device off at the relay), tell the account service to end the device's sessions.
|
|
3668
|
+
*/
|
|
3669
|
+
async function revoke(hub, p) {
|
|
3670
|
+
if (hub.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict. Run \"conveno devices\" to resolve it first.");
|
|
3671
|
+
const s = hub.chainState;
|
|
3672
|
+
if (!hub.chain || !s?.members.has(hub.identity.deviceId)) throw new ConvenoError(RpcErrorCode.NotFound, "This device has no device list yet.");
|
|
3673
|
+
const byId = s.members.get(p.device);
|
|
3674
|
+
const byName = [...s.members.values()].filter((m) => m.name === p.device);
|
|
3675
|
+
if (!byId && byName.length > 1) throw new ConvenoError(RpcErrorCode.Conflict, `Several devices are named "${p.device}". Revoke by device id instead.`);
|
|
3676
|
+
const target = byId ?? byName[0];
|
|
3677
|
+
if (!target) throw new ConvenoError(RpcErrorCode.NotFound, `No active device "${p.device}". Run "conveno devices" to list them.`);
|
|
3678
|
+
let next;
|
|
3679
|
+
try {
|
|
3680
|
+
next = appendRevoke(hub.chain, hub.identity, target.deviceId, hub.ms());
|
|
3681
|
+
} catch (e) {
|
|
3682
|
+
throw new ConvenoError(RpcErrorCode.InvalidParams, e.message);
|
|
3683
|
+
}
|
|
3684
|
+
try {
|
|
3685
|
+
await publishList(hub, next);
|
|
3686
|
+
} catch (e) {
|
|
3687
|
+
throw new ConvenoError(RpcErrorCode.Conflict, `The relay did not accept the revocation: ${e.message} Nothing was changed.`);
|
|
3688
|
+
}
|
|
3689
|
+
hub.remote.delete(target.deviceId);
|
|
3690
|
+
return { revoked: {
|
|
3691
|
+
deviceId: target.deviceId,
|
|
3692
|
+
name: target.name
|
|
3693
|
+
} };
|
|
3694
|
+
}
|
|
3695
|
+
/**
|
|
3696
|
+
* Forget this device's copy of the list after the owner reset the account's devices, or when
|
|
3697
|
+
* the relay's list no longer includes it. The device is then unpaired and can pair again.
|
|
3698
|
+
*/
|
|
3699
|
+
function reset(hub) {
|
|
3700
|
+
if (!hub.conflict && !isRevoked(hub)) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has no conflict and this device is not revoked, so there is nothing to reset.");
|
|
3701
|
+
hub.conflict = void 0;
|
|
3702
|
+
hub.state.setConflict(void 0);
|
|
3703
|
+
hub.state.setChain(void 0);
|
|
3704
|
+
loadChain(hub, void 0);
|
|
3705
|
+
hub.relayRevoked = false;
|
|
3706
|
+
hub.remote.clear();
|
|
3707
|
+
disconnect(hub);
|
|
3708
|
+
evaluate(hub);
|
|
3709
|
+
return { reset: true };
|
|
3710
|
+
}
|
|
3711
|
+
async function status(hub) {
|
|
3712
|
+
await hub.evaluating;
|
|
3713
|
+
const self = hub.record();
|
|
3714
|
+
const out = {
|
|
3715
|
+
state: hub.connState,
|
|
3716
|
+
relayUrl: hub.url,
|
|
3717
|
+
device: {
|
|
3718
|
+
deviceId: self.deviceId,
|
|
3719
|
+
name: self.name,
|
|
3720
|
+
fingerprint: deviceFingerprint(self)
|
|
3721
|
+
},
|
|
3722
|
+
peers: deviceInfos(hub).filter((d) => !d.self)
|
|
3723
|
+
};
|
|
3724
|
+
if (hub.detail !== void 0) out.detail = hub.detail;
|
|
3725
|
+
if (hub.chain) out.list = chainHead(hub.chain);
|
|
3726
|
+
if (hub.conflict) out.conflict = hub.conflict;
|
|
3727
|
+
return out;
|
|
3728
|
+
}
|
|
3729
|
+
function deviceInfos(hub) {
|
|
3730
|
+
const s = hub.chainState;
|
|
3731
|
+
if (!s?.members.has(hub.identity.deviceId)) {
|
|
3732
|
+
const self = hub.record();
|
|
3733
|
+
return [{
|
|
3734
|
+
deviceId: self.deviceId,
|
|
3735
|
+
name: self.name,
|
|
3736
|
+
fingerprint: deviceFingerprint(self),
|
|
3737
|
+
self: true,
|
|
3738
|
+
online: hub.linkReady,
|
|
3739
|
+
sessions: 0
|
|
3740
|
+
}];
|
|
3741
|
+
}
|
|
3742
|
+
return [...s.members.values()].map((m) => {
|
|
3743
|
+
const self = m.deviceId === hub.identity.deviceId;
|
|
3744
|
+
return {
|
|
3745
|
+
deviceId: m.deviceId,
|
|
3746
|
+
name: m.name,
|
|
3747
|
+
fingerprint: deviceFingerprint(m),
|
|
3748
|
+
self,
|
|
3749
|
+
online: self ? hub.linkReady : hub.online.has(m.deviceId),
|
|
3750
|
+
sessions: self ? 0 : hub.remote.get(m.deviceId)?.sessions.length ?? 0,
|
|
3751
|
+
addedAt: new Date(m.addedAt).toISOString(),
|
|
3752
|
+
addedBy: m.addedBy
|
|
3753
|
+
};
|
|
3754
|
+
});
|
|
3755
|
+
}
|
|
3756
|
+
function devices(hub) {
|
|
3757
|
+
const revoked = [...hub.chainState?.revoked.entries() ?? []].map(([id, r]) => ({
|
|
3758
|
+
deviceId: id,
|
|
3759
|
+
name: r.device.name,
|
|
3760
|
+
revokedAt: new Date(r.revokedAt).toISOString(),
|
|
3761
|
+
revokedBy: r.by
|
|
3762
|
+
}));
|
|
3763
|
+
const out = {
|
|
3764
|
+
devices: deviceInfos(hub),
|
|
3765
|
+
revoked
|
|
3766
|
+
};
|
|
3767
|
+
if (hub.chain) out.list = chainHead(hub.chain);
|
|
3768
|
+
if (hub.conflict) out.conflict = hub.conflict;
|
|
3769
|
+
return out;
|
|
3770
|
+
}
|
|
3771
|
+
function rename(hub, p) {
|
|
3772
|
+
const name = sanitizeName(p.name);
|
|
3773
|
+
hub.state.setDeviceName(name);
|
|
3774
|
+
return { name };
|
|
3775
|
+
}
|
|
3776
|
+
const sanitizeName = (n) => n.replace(/[^\p{L}\p{N}._ -]/gu, "").trim().slice(0, 64) || "device";
|
|
3777
|
+
/**
|
|
3778
|
+
* The relay client inside the daemon. It keeps the device identity and its copy of the signed
|
|
3779
|
+
* device list, holds the WebSocket to the relay while this device is paired (or pairing),
|
|
3780
|
+
* publishes the local sessions to the other devices, keeps theirs, and carries messages between
|
|
3781
|
+
* them.
|
|
3782
|
+
*
|
|
3783
|
+
* The relay holds the account's device list and only accepts strict extensions of it, so the
|
|
3784
|
+
* list is linear. This device adopts a list only from the relay, and only one that extends its
|
|
3785
|
+
* own copy; changes it makes (a pairing, a revocation) count only once the relay accepted them.
|
|
3786
|
+
* When the relay's list is not an extension of this device's, or another device's envelope
|
|
3787
|
+
* carries a list head that does not fit this device's list, the hub records a conflict, warns, and
|
|
3788
|
+
* sends nothing until the owner accepts the relay's head (`devices.accept`).
|
|
3789
|
+
*/
|
|
3790
|
+
var RelayHub = class {
|
|
3791
|
+
o;
|
|
3792
|
+
identity;
|
|
3793
|
+
/** Where the identity is kept, and whether it is there yet. */
|
|
3794
|
+
identityPath;
|
|
3795
|
+
identitySaved;
|
|
3796
|
+
state;
|
|
3797
|
+
now;
|
|
3798
|
+
url;
|
|
3799
|
+
accessToken;
|
|
3800
|
+
evaluating;
|
|
3801
|
+
evaluateAgain = false;
|
|
3802
|
+
connectImpl;
|
|
3803
|
+
publishMs;
|
|
3804
|
+
pairResendMs;
|
|
3805
|
+
listTimeoutMs;
|
|
3806
|
+
chain;
|
|
3807
|
+
chainState;
|
|
3808
|
+
/** The list the relay last sent, verified. */
|
|
3809
|
+
relayChain;
|
|
3810
|
+
/**
|
|
3811
|
+
* Head and length of the relay's list. The relay sends the whole list only to its members; any
|
|
3812
|
+
* other device, such as one being paired, gets just this.
|
|
3813
|
+
*/
|
|
3814
|
+
relayHead;
|
|
3815
|
+
/** The relay's list has arrived since the connection became ready. */
|
|
3816
|
+
listReceived = false;
|
|
3817
|
+
conflict;
|
|
3818
|
+
pendingList;
|
|
3819
|
+
/** The relay refused this device because its list revokes it. */
|
|
3820
|
+
relayRevoked = false;
|
|
3821
|
+
/** The relay refused this version of Conveno: what to tell the owner. No retry until restart. */
|
|
3822
|
+
upgradeRequired;
|
|
3823
|
+
sent = /* @__PURE__ */ new Map();
|
|
3824
|
+
sessionSeq = /* @__PURE__ */ new Map();
|
|
3825
|
+
publishSeq = 0;
|
|
3826
|
+
link;
|
|
3827
|
+
linkReady = false;
|
|
3828
|
+
connState = "logged_out";
|
|
3829
|
+
detail;
|
|
3830
|
+
failures = 0;
|
|
3831
|
+
/** The code of the last `error` frame, for the close that usually follows it. */
|
|
3832
|
+
lastErrorCode;
|
|
3833
|
+
lastErrorMin;
|
|
3834
|
+
online = /* @__PURE__ */ new Set();
|
|
3835
|
+
remote = /* @__PURE__ */ new Map();
|
|
3836
|
+
pairing;
|
|
3837
|
+
timers = [];
|
|
3838
|
+
retryTimer;
|
|
3839
|
+
publishTimer;
|
|
3840
|
+
stopped = false;
|
|
3841
|
+
constructor(o) {
|
|
3842
|
+
this.o = o;
|
|
3843
|
+
const platform = o.platform ?? process.platform;
|
|
3844
|
+
const paths = dataPaths(platform, o.dataDir);
|
|
3845
|
+
this.identityPath = paths.relayIdentity;
|
|
3846
|
+
const stored = loadIdentity(paths.relayIdentity);
|
|
3847
|
+
this.identity = stored ?? generateIdentity(newDeviceId());
|
|
3848
|
+
this.identitySaved = stored !== void 0;
|
|
3849
|
+
this.state = new RelayState(paths.relayDatabase);
|
|
3850
|
+
this.now = o.now ?? (() => /* @__PURE__ */ new Date());
|
|
3851
|
+
this.url = o.relayUrl ?? relayUrl();
|
|
3852
|
+
this.accessToken = o.accessToken ?? accountAccessToken(dataPaths(platform, o.dataDir).account);
|
|
3853
|
+
this.connectImpl = o.connect ?? ((c) => new RelayConnection(c));
|
|
3854
|
+
this.publishMs = o.publishIntervalMs ?? 6e4;
|
|
3855
|
+
this.pairResendMs = o.pairResendMs ?? 2e3;
|
|
3856
|
+
this.listTimeoutMs = o.listTimeoutMs ?? 15e3;
|
|
3857
|
+
this.conflict = this.state.conflict();
|
|
3858
|
+
loadChain(this, this.state.chain());
|
|
3859
|
+
this.state.pruneSeen(this.ms());
|
|
3860
|
+
}
|
|
3861
|
+
ms() {
|
|
3862
|
+
return this.now().getTime();
|
|
3863
|
+
}
|
|
3864
|
+
deviceName() {
|
|
3865
|
+
return this.state.deviceName() ?? sanitizeName(hostname());
|
|
3866
|
+
}
|
|
3867
|
+
record() {
|
|
3868
|
+
return publicRecord(this.identity, this.deviceName());
|
|
3869
|
+
}
|
|
3870
|
+
start() {
|
|
3871
|
+
start(this);
|
|
3872
|
+
}
|
|
3873
|
+
stop() {
|
|
3874
|
+
stop(this);
|
|
3875
|
+
}
|
|
3876
|
+
/**
|
|
3877
|
+
* Decide whether to be connected, and connect or disconnect. Called often; runs one check at a
|
|
3878
|
+
* time and once more if asked meanwhile. The returned promise settles when the check is done.
|
|
3879
|
+
*/
|
|
3880
|
+
evaluate() {
|
|
3881
|
+
return evaluate(this);
|
|
3882
|
+
}
|
|
3883
|
+
/** Called by the daemon whenever a local session changed. Publishes shortly after. */
|
|
3884
|
+
sessionsChanged() {
|
|
3885
|
+
sessionsChanged(this);
|
|
3886
|
+
}
|
|
3887
|
+
/**
|
|
3888
|
+
* Sessions on the other devices, as `session.list` shows them: a local alias id and the name
|
|
3889
|
+
* `<device>:<name>`, so none can collide with a local session.
|
|
3890
|
+
*/
|
|
3891
|
+
remoteSessions(filter = {}) {
|
|
3892
|
+
return remoteSessions(this, filter);
|
|
3893
|
+
}
|
|
3894
|
+
/** A remote session by its local alias id or its full `<device>:<name>`. */
|
|
3895
|
+
resolveRemote(to) {
|
|
3896
|
+
return resolveRemote(this, to);
|
|
3897
|
+
}
|
|
3898
|
+
/** Send a message to a session on another device. Throws when that cannot be done now. */
|
|
3899
|
+
sendRemote(target, message, hops = 0) {
|
|
3900
|
+
sendRemote(this, target, message, hops);
|
|
3901
|
+
}
|
|
3902
|
+
async status() {
|
|
3903
|
+
return status(this);
|
|
3904
|
+
}
|
|
3905
|
+
devices() {
|
|
3906
|
+
return devices(this);
|
|
3907
|
+
}
|
|
3908
|
+
/**
|
|
3909
|
+
* Recover from a conflict: adopt the relay's list, but only if its head is the one the owner
|
|
3910
|
+
* read on a device that is a member of it.
|
|
3911
|
+
*/
|
|
3912
|
+
accept(p) {
|
|
3913
|
+
return accept(this, p);
|
|
3914
|
+
}
|
|
3915
|
+
rename(p) {
|
|
3916
|
+
return rename(this, p);
|
|
3917
|
+
}
|
|
3918
|
+
/**
|
|
3919
|
+
* Revoke a device: append the revocation, and once the relay has accepted it (which also cuts
|
|
3920
|
+
* the device off at the relay), tell the account service to end the device's sessions.
|
|
3921
|
+
*/
|
|
3922
|
+
async revoke(p) {
|
|
3923
|
+
return revoke(this, p);
|
|
3924
|
+
}
|
|
3925
|
+
/**
|
|
3926
|
+
* Forget this device's copy of the list after the owner reset the account's devices, or when
|
|
3927
|
+
* the relay's list no longer includes it. The device is then unpaired and can pair again.
|
|
3928
|
+
*/
|
|
3929
|
+
reset() {
|
|
3930
|
+
return reset(this);
|
|
3931
|
+
}
|
|
3932
|
+
async pairStart(p) {
|
|
3933
|
+
return pairStart(this, p);
|
|
3934
|
+
}
|
|
3935
|
+
pairStatus(q) {
|
|
3936
|
+
return pairStatus(this, q);
|
|
3937
|
+
}
|
|
3938
|
+
pairConfirm(q) {
|
|
3939
|
+
return pairConfirm(this, q);
|
|
3940
|
+
}
|
|
3941
|
+
};
|
|
3942
|
+
function relayCall(daemon, req) {
|
|
3943
|
+
const relay = daemon.relay;
|
|
3944
|
+
if (!relay) throw new ConvenoError(RpcErrorCode.MethodNotFound, "The relay is disabled in this daemon.");
|
|
3945
|
+
switch (req.method) {
|
|
3946
|
+
case "relay.status": return relay.status();
|
|
3947
|
+
case "devices.list": return relay.devices();
|
|
3948
|
+
case "devices.pair": return relay.pairStart(req.params);
|
|
3949
|
+
case "devices.pairStatus": return relay.pairStatus(req.params);
|
|
3950
|
+
case "devices.pairConfirm": return relay.pairConfirm(req.params);
|
|
3951
|
+
case "devices.revoke": return relay.revoke(req.params);
|
|
3952
|
+
case "devices.rename": return relay.rename(req.params);
|
|
3953
|
+
case "devices.accept": return relay.accept(req.params);
|
|
3954
|
+
case "devices.reset": return relay.reset();
|
|
3955
|
+
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
function sendToRemote(daemon, message, target, hops) {
|
|
3959
|
+
daemon.relay.sendRemote(target, message, hops);
|
|
3960
|
+
return {
|
|
3961
|
+
message,
|
|
3962
|
+
delivery: target.deliveryTier,
|
|
3963
|
+
deliveredTo: {
|
|
3964
|
+
id: target.id,
|
|
3965
|
+
name: target.name
|
|
3966
|
+
}
|
|
3967
|
+
};
|
|
3968
|
+
}
|
|
3969
|
+
/** The daemon side of the relay: local sessions out, remote messages in. */
|
|
3970
|
+
function relayHost(daemon) {
|
|
3971
|
+
return {
|
|
3972
|
+
log: daemon.log,
|
|
3973
|
+
localSessions: () => daemon.store.allSessions().filter((r) => r.status !== "offline").map((r) => {
|
|
3974
|
+
const { nativeId: _n, ...s } = view(daemon, r);
|
|
3975
|
+
return s;
|
|
3976
|
+
}),
|
|
3977
|
+
deliverLocal: (m, to, hops = 0) => {
|
|
3978
|
+
if (m.kind === "system") return "not_allowed";
|
|
3979
|
+
const row = daemon.store.getSession(to);
|
|
3980
|
+
if (!row) return "session_gone";
|
|
3981
|
+
if (row.status === "offline") return "session_offline";
|
|
3982
|
+
if (daemon.store.hasMessage(m.id)) return void 0;
|
|
3983
|
+
if (daemon.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
|
|
3984
|
+
daemon.store.insertMessage(m, row.id, daemon.iso(), hops);
|
|
3985
|
+
emitMessage(daemon, m, row.id);
|
|
3986
|
+
},
|
|
3987
|
+
notify: (to, event, detail) => {
|
|
3988
|
+
if (!daemon.store.getSession(to)) return;
|
|
3989
|
+
const m = {
|
|
3990
|
+
id: newMessageId(),
|
|
3991
|
+
from: DAEMON_SENDER_ID,
|
|
3992
|
+
to,
|
|
3993
|
+
kind: "system",
|
|
3994
|
+
body: {
|
|
3995
|
+
event,
|
|
3996
|
+
detail: detail.slice(0, 2e3)
|
|
3997
|
+
},
|
|
3998
|
+
urgent: false,
|
|
3999
|
+
createdAt: daemon.iso()
|
|
4000
|
+
};
|
|
4001
|
+
daemon.store.insertMessage(m, to, daemon.iso());
|
|
4002
|
+
emitMessage(daemon, m, to);
|
|
4003
|
+
}
|
|
4004
|
+
};
|
|
4005
|
+
}
|
|
4006
|
+
/** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
|
|
4007
|
+
function startRelay(daemon, opts, relayOpts) {
|
|
4008
|
+
try {
|
|
4009
|
+
const hub = new RelayHub({
|
|
4010
|
+
clientVersion: DAEMON_VERSION,
|
|
4011
|
+
...relayOpts,
|
|
4012
|
+
dataDir: opts.dataDir,
|
|
4013
|
+
host: relayHost(daemon)
|
|
4014
|
+
});
|
|
4015
|
+
hub.start();
|
|
4016
|
+
daemon.relay = hub;
|
|
4017
|
+
} catch (e) {
|
|
4018
|
+
relayHost(daemon).log.error("relay: could not start; the daemon runs local-only", e);
|
|
4019
|
+
}
|
|
4020
|
+
}
|
|
4021
|
+
/** Unread messages one session may hold. */
|
|
4022
|
+
const MAX_UNREAD_PER_SESSION = 1e3;
|
|
4023
|
+
function sendMessage(daemon, p) {
|
|
4024
|
+
const sender = requireSession(daemon, p.sessionId);
|
|
4025
|
+
if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
|
|
4026
|
+
if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
|
|
4027
|
+
const sent = deliverFrom(daemon, {
|
|
4028
|
+
id: sender.id,
|
|
4029
|
+
name: sender.name,
|
|
4030
|
+
cli: sender.cli,
|
|
4031
|
+
hops: sender.status === "busy" ? sender.turnHops : 0
|
|
4032
|
+
}, p);
|
|
4033
|
+
daemon.lastSent.set(sender.id, daemon.iso());
|
|
4034
|
+
return sent;
|
|
4035
|
+
}
|
|
4036
|
+
/** The recipient names the owner: `you`, or the id of a message the owner sent. */
|
|
4037
|
+
function isOwnerRecipient(to) {
|
|
4038
|
+
return to === "you" || to === OWNER_SESSION_ID;
|
|
4039
|
+
}
|
|
4040
|
+
/**
|
|
4041
|
+
* Route one message from \`sender\` (a session, or the owner) to a session, or to a session on
|
|
4042
|
+
* another device. The owner is not a session and has no inbox: a session cannot message \`you\`.
|
|
4043
|
+
*/
|
|
4044
|
+
function deliverFrom(daemon, sender, p) {
|
|
4045
|
+
if (p.replyTo !== void 0 && !daemon.store.hasMessage(p.replyTo)) throw new ConvenoError(RpcErrorCode.NotFound, `Message ${p.replyTo} does not exist, so it cannot be replied to. Check the message id.`);
|
|
4046
|
+
const at = daemon.iso();
|
|
4047
|
+
const rows = daemon.store.allSessions();
|
|
4048
|
+
const make = (to) => ({
|
|
4049
|
+
id: newMessageId(),
|
|
4050
|
+
from: sender.id,
|
|
4051
|
+
to,
|
|
4052
|
+
kind: p.kind,
|
|
4053
|
+
body: p.body,
|
|
4054
|
+
urgent: p.urgent,
|
|
4055
|
+
createdAt: at,
|
|
4056
|
+
fromName: sender.name,
|
|
4057
|
+
...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
|
|
4058
|
+
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
4059
|
+
});
|
|
4060
|
+
if (isOwnerRecipient(p.to)) throw new ConvenoError(RpcErrorCode.InvalidParams, sender.id === OWNER_SESSION_ID ? "You cannot send a message to yourself." : "The user reads your replies in this session. Answer there instead of sending a message.");
|
|
4061
|
+
let target;
|
|
4062
|
+
try {
|
|
4063
|
+
target = resolveRecipient(p.to, namedOf(rows), daemon.store.holder());
|
|
4064
|
+
} catch (e) {
|
|
4065
|
+
const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? daemon.relay?.resolveRemote(p.to) : void 0;
|
|
4066
|
+
if (!remote) throw e;
|
|
4067
|
+
return sendToRemote(daemon, make(p.to), remote, sender.hops);
|
|
4068
|
+
}
|
|
4069
|
+
const targetRow = rows.find((r) => r.id === target.id);
|
|
4070
|
+
if (daemon.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
4071
|
+
const message = make(p.to);
|
|
4072
|
+
daemon.store.insertMessage(message, targetRow.id, at, sender.hops);
|
|
4073
|
+
emitMessage(daemon, message, targetRow.id);
|
|
4074
|
+
return {
|
|
4075
|
+
message,
|
|
4076
|
+
delivery: tierFor(daemon, targetRow),
|
|
4077
|
+
deliveredTo: {
|
|
4078
|
+
id: targetRow.id,
|
|
4079
|
+
name: targetRow.name
|
|
4080
|
+
}
|
|
4081
|
+
};
|
|
4082
|
+
}
|
|
4083
|
+
/** The last messages between sessions, oldest first, for the app's activity list. */
|
|
4084
|
+
function recent(daemon, conn, p) {
|
|
4085
|
+
requireCli(conn, "list recent messages");
|
|
4086
|
+
return { messages: daemon.store.recentMessages(p.limit).flatMap(({ message: m, recipient }) => {
|
|
4087
|
+
if (m.kind === "system") return [];
|
|
4088
|
+
const to = daemon.store.getSession(recipient);
|
|
4089
|
+
if (!to) return [];
|
|
4090
|
+
const said = sanitizeLine(m.kind === "text" ? firstLineOf(m.body.text) : m.body.goal);
|
|
4091
|
+
const chars = [...said];
|
|
4092
|
+
const text = chars.length > 200 ? `${chars.slice(0, 199).join("")}…` : said;
|
|
4093
|
+
return [{
|
|
4094
|
+
id: m.id,
|
|
4095
|
+
from: m.from,
|
|
4096
|
+
...m.fromName !== void 0 ? { fromName: m.fromName } : {},
|
|
4097
|
+
...m.fromCli !== void 0 ? { fromCli: m.fromCli } : {},
|
|
4098
|
+
to: to.id,
|
|
4099
|
+
toName: to.name,
|
|
4100
|
+
toCli: to.cli,
|
|
4101
|
+
text,
|
|
4102
|
+
createdAt: m.createdAt
|
|
4103
|
+
}];
|
|
4104
|
+
}).reverse() };
|
|
4105
|
+
}
|
|
4106
|
+
function ownerSend(daemon, conn, p) {
|
|
4107
|
+
requireCli(conn, "send as the owner");
|
|
4108
|
+
return deliverFrom(daemon, {
|
|
4109
|
+
id: OWNER_SESSION_ID,
|
|
4110
|
+
name: "you",
|
|
4111
|
+
hops: 0
|
|
4112
|
+
}, {
|
|
4113
|
+
to: p.to,
|
|
4114
|
+
kind: "text",
|
|
4115
|
+
body: { text: p.text },
|
|
4116
|
+
urgent: p.urgent,
|
|
4117
|
+
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
4118
|
+
});
|
|
4119
|
+
}
|
|
4120
|
+
function inbox(daemon, p) {
|
|
4121
|
+
requireSession(daemon, p.sessionId);
|
|
4122
|
+
return readInboxOf(daemon, p.sessionId, p.unreadOnly, p.limit);
|
|
4123
|
+
}
|
|
4124
|
+
/** A mailbox's messages, oldest first, marked read. */
|
|
4125
|
+
function readInboxOf(daemon, id, unreadOnly, limit) {
|
|
4126
|
+
const at = daemon.iso();
|
|
4127
|
+
return daemon.store.tx(() => {
|
|
4128
|
+
const entries = daemon.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
|
|
4129
|
+
const res = readInbox(entries, {
|
|
4130
|
+
unreadOnly,
|
|
4131
|
+
limit,
|
|
4132
|
+
maxBytes: RESPONSE_BUDGET_BYTES
|
|
4133
|
+
}, at);
|
|
4134
|
+
const changed = new Set(res.returned.map((e) => e.message.id));
|
|
4135
|
+
for (const e of res.entries) if (changed.has(e.message.id)) daemon.store.saveEntry(id, e);
|
|
4136
|
+
return {
|
|
4137
|
+
messages: res.returned.map((e) => e.message),
|
|
4138
|
+
unreadCount: res.unreadCount
|
|
4139
|
+
};
|
|
4140
|
+
});
|
|
4141
|
+
}
|
|
4142
|
+
function deliver(daemon, p) {
|
|
4143
|
+
requireSession(daemon, p.sessionId);
|
|
4144
|
+
touchHook(daemon, p.sessionId);
|
|
4145
|
+
const at = daemon.iso();
|
|
4146
|
+
return daemon.store.tx(() => {
|
|
4147
|
+
const pending = pendingForInjection(daemon.store.entries(p.sessionId, { states: ["queued"] }));
|
|
4148
|
+
const fit = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
|
|
4149
|
+
const { taken, preview } = p.maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, p.maxChars, (ms) => formatHookContext(ms));
|
|
4150
|
+
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
4151
|
+
for (const e of updated) daemon.store.saveEntry(p.sessionId, e);
|
|
4152
|
+
if (preview) return {
|
|
4153
|
+
messages: [preview],
|
|
4154
|
+
remaining: pending.length
|
|
4155
|
+
};
|
|
4156
|
+
return {
|
|
4157
|
+
messages: updated.map((e) => e.message),
|
|
4158
|
+
remaining: pending.length - taken.length
|
|
4159
|
+
};
|
|
4160
|
+
});
|
|
4161
|
+
}
|
|
4162
|
+
function ack(daemon, p) {
|
|
4163
|
+
requireSession(daemon, p.sessionId);
|
|
4164
|
+
return ackFor(daemon, p.sessionId, p.ids);
|
|
4165
|
+
}
|
|
4166
|
+
function ackFor(daemon, id, ids) {
|
|
4167
|
+
const at = daemon.iso();
|
|
4168
|
+
return daemon.store.tx(() => {
|
|
4169
|
+
const entries = daemon.store.entries(id, { ids });
|
|
4170
|
+
const res = ackEntries(entries, ids, at);
|
|
4171
|
+
for (const e of res.entries) daemon.store.saveEntry(id, e);
|
|
4172
|
+
return { acked: res.acked };
|
|
4173
|
+
});
|
|
4174
|
+
}
|
|
4175
|
+
/** The first line of a text that has something on it. */
|
|
4176
|
+
function firstLineOf(text) {
|
|
4177
|
+
return text.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";
|
|
4178
|
+
}
|
|
4179
|
+
function attach(daemon, socket) {
|
|
4180
|
+
const conn = {
|
|
4181
|
+
socket,
|
|
4182
|
+
authed: false,
|
|
4183
|
+
queue: Promise.resolve()
|
|
4184
|
+
};
|
|
4185
|
+
daemon.conns.add(conn);
|
|
4186
|
+
const authTimer = setTimeout(() => {
|
|
4187
|
+
if (!conn.authed) socket.destroy();
|
|
4188
|
+
}, daemon.authTimeoutMs);
|
|
4189
|
+
authTimer.unref();
|
|
4190
|
+
const decoder = createLineDecoder();
|
|
4191
|
+
socket.on("data", (chunk) => {
|
|
4192
|
+
for (const frame of decoder.push(chunk)) conn.queue = conn.queue.then(() => onFrame(daemon, conn, frame));
|
|
4193
|
+
});
|
|
4194
|
+
socket.on("close", () => {
|
|
4195
|
+
clearTimeout(authTimer);
|
|
4196
|
+
daemon.conns.delete(conn);
|
|
4197
|
+
listenerGone(daemon, conn);
|
|
4198
|
+
});
|
|
4199
|
+
socket.on("error", () => socket.destroy());
|
|
4200
|
+
}
|
|
4201
|
+
function send(conn, obj, flushed) {
|
|
4202
|
+
if (conn.socket.destroyed) {
|
|
4203
|
+
flushed?.();
|
|
4204
|
+
return;
|
|
4205
|
+
}
|
|
4206
|
+
try {
|
|
4207
|
+
conn.socket.write(encodeFrame(obj), flushed);
|
|
4208
|
+
} catch {
|
|
4209
|
+
const id = obj?.id;
|
|
4210
|
+
if (typeof id === "string" || typeof id === "number") conn.socket.write(encodeFrame(makeError(id, RpcErrorCode.InternalError, "The response was too large to send.")));
|
|
4211
|
+
}
|
|
4212
|
+
}
|
|
4213
|
+
async function onFrame(daemon, conn, frame) {
|
|
4214
|
+
if (!frame.ok) {
|
|
4215
|
+
if (frame.error.code === "invalid_json") send(conn, makeError(null, RpcErrorCode.ParseError, "Parse error: line is not valid JSON."));
|
|
4216
|
+
else send(conn, makeError(null, RpcErrorCode.InvalidRequest, "Line is longer than 1 MiB. Send smaller requests."));
|
|
4217
|
+
return;
|
|
4218
|
+
}
|
|
4219
|
+
const parsed = parseIpcRequest(frame.value);
|
|
4220
|
+
if (!parsed.ok) {
|
|
4221
|
+
const method = frame.value?.method;
|
|
4222
|
+
const needsAuth = !conn.authed && method !== "hello" && method !== "auth";
|
|
4223
|
+
const code = parsed.error.code;
|
|
4224
|
+
if (needsAuth && (code === RpcErrorCode.MethodNotFound || code === RpcErrorCode.InvalidParams)) send(conn, makeError(parsed.id, RpcErrorCode.Unauthorized, unauthorizedMessage));
|
|
4225
|
+
else send(conn, makeError(parsed.id, code, parsed.error.message, parsed.error.data));
|
|
4226
|
+
return;
|
|
4227
|
+
}
|
|
4228
|
+
const req = parsed.request;
|
|
4229
|
+
if (!conn.authed && req.method !== "hello" && req.method !== "auth") {
|
|
4230
|
+
send(conn, makeError(req.id, RpcErrorCode.Unauthorized, unauthorizedMessage));
|
|
4231
|
+
return;
|
|
4232
|
+
}
|
|
4233
|
+
if (req.method === "permission.ask") {
|
|
4234
|
+
(async () => dispatch(daemon, conn, req))().then((result) => send(conn, makeResult(req.id, result)), (e) => sendError(daemon, conn, req.id, req.method, e));
|
|
4235
|
+
return;
|
|
4236
|
+
}
|
|
4237
|
+
try {
|
|
4238
|
+
const result = await dispatch(daemon, conn, req);
|
|
4239
|
+
const flushed = req.method === "daemon.shutdown" ? daemon.requestShutdown : void 0;
|
|
4240
|
+
send(conn, makeResult(req.id, result), flushed);
|
|
4241
|
+
} catch (e) {
|
|
4242
|
+
sendError(daemon, conn, req.id, req.method, e);
|
|
4243
|
+
if (req.method === "hello" || req.method === "auth") conn.socket.end();
|
|
4244
|
+
}
|
|
4245
|
+
}
|
|
4246
|
+
function sendError(daemon, conn, id, method, e) {
|
|
4247
|
+
if (e instanceof ConvenoError) send(conn, makeError(id, e.code, e.message));
|
|
4248
|
+
else {
|
|
4249
|
+
daemon.log.error(`internal error in ${method}`, e);
|
|
4250
|
+
send(conn, makeError(id, RpcErrorCode.InternalError, `The Conveno daemon hit an internal error. Check the daemon log at ${daemon.log.path}, then run "conveno daemon stop" and try again.`));
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
function dispatch(daemon, conn, req) {
|
|
4254
|
+
switch (req.method) {
|
|
4255
|
+
case "hello": return hello(daemon, conn, req.params);
|
|
4256
|
+
case "auth": return auth(daemon, conn, req.params);
|
|
4257
|
+
case "session.register": return registerAsync(daemon, req.params);
|
|
4258
|
+
case "session.heartbeat": {
|
|
4259
|
+
const beat = heartbeat(daemon, req.params.sessionId, req.params.pid);
|
|
4260
|
+
if (req.params.model !== void 0) setModelLabel(daemon, req.params.sessionId, req.params.model);
|
|
4261
|
+
return beat;
|
|
4262
|
+
}
|
|
4263
|
+
case "session.unregister": return unregister(daemon, req.params.sessionId, req.params.pid);
|
|
4264
|
+
case "session.remove": return remove(daemon, req.params.sessionId);
|
|
4265
|
+
case "session.rename": return rename$1(daemon, req.params);
|
|
4266
|
+
case "session.setStatus": return setStatus(daemon, req.params);
|
|
4267
|
+
case "session.list": return list(daemon, req.params);
|
|
4268
|
+
case "session.byHost": return byHost(daemon, req.params);
|
|
4269
|
+
case "session.hostOf": return hostOf(daemon, req.params);
|
|
4270
|
+
case "session.setNative": return setNative(daemon, req.params);
|
|
4271
|
+
case "session.bind": return bind(daemon, req.params);
|
|
4272
|
+
case "session.setCwd": return setCwd(daemon, req.params);
|
|
4273
|
+
case "turn.start": return turnStart(daemon, req.params.sessionId);
|
|
4274
|
+
case "turn.end": return turnEnd(daemon, req.params);
|
|
4275
|
+
case "turn.wake": return turnWake(daemon, conn, req.params);
|
|
4276
|
+
case "daemon.shutdown": return { ok: true };
|
|
4277
|
+
case "orchestrator.claim": return claim(daemon, req.params.sessionId, req.params.via ?? "unknown");
|
|
4278
|
+
case "orchestrator.clear": return clearLead(daemon, conn);
|
|
4279
|
+
case "permission.ask": return permissionAsk(daemon, req.params);
|
|
4280
|
+
case "permission.answer": return permissionAnswer(daemon, req.params);
|
|
4281
|
+
case "message.send": return sendMessage(daemon, req.params);
|
|
4282
|
+
case "owner.send": return ownerSend(daemon, conn, req.params);
|
|
4283
|
+
case "message.recent": return recent(daemon, conn, req.params);
|
|
4284
|
+
case "message.inbox": return inbox(daemon, req.params);
|
|
4285
|
+
case "message.deliver": return deliver(daemon, req.params);
|
|
4286
|
+
case "message.ack": return ack(daemon, req.params);
|
|
4287
|
+
case "message.requeue": return requeue(daemon, req.params);
|
|
4288
|
+
case "events.subscribe": return subscribe(daemon, conn, req.params);
|
|
4289
|
+
case "relay.status":
|
|
4290
|
+
case "devices.list":
|
|
4291
|
+
case "devices.pair":
|
|
4292
|
+
case "devices.pairStatus":
|
|
4293
|
+
case "devices.pairConfirm":
|
|
4294
|
+
case "devices.revoke":
|
|
4295
|
+
case "devices.rename":
|
|
4296
|
+
case "devices.accept":
|
|
4297
|
+
case "devices.reset": return relayCall(daemon, req);
|
|
4298
|
+
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}. This version of the Conveno daemon does not support it. Run "conveno daemon status" to see which version is running.`);
|
|
4299
|
+
}
|
|
4300
|
+
}
|
|
4301
|
+
function hello(daemon, conn, p) {
|
|
4302
|
+
if (conn.challenge !== void 0) throw new ConvenoError(RpcErrorCode.Conflict, "The handshake already started on this connection.");
|
|
4303
|
+
if (p.protocolVersion !== "conveno/1") throw new ConvenoError(RpcErrorCode.VersionMismatch, `Protocol version "${p.protocolVersion}" is not supported. This daemon speaks "${PROTOCOL_VERSION}". Update the client or the daemon so the versions match.`);
|
|
4304
|
+
conn.kind = p.client;
|
|
4305
|
+
conn.challenge = newAuthNonce();
|
|
4306
|
+
conn.client = p.client;
|
|
4307
|
+
return {
|
|
4308
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
4309
|
+
daemonVersion: DAEMON_VERSION,
|
|
4310
|
+
proof: daemonProof(daemon.token, p.nonce),
|
|
4311
|
+
challenge: conn.challenge
|
|
4312
|
+
};
|
|
4313
|
+
}
|
|
4314
|
+
function auth(daemon, conn, p) {
|
|
4315
|
+
if (conn.challenge === void 0) throw new ConvenoError(RpcErrorCode.Unauthorized, unauthorizedMessage);
|
|
4316
|
+
if (!proofsMatch(p.proof, clientProof(daemon.token, conn.challenge))) throw new ConvenoError(RpcErrorCode.Unauthorized, "The auth proof is wrong. The client must use the token in daemon.token in the Conveno data directory.");
|
|
4317
|
+
conn.authed = true;
|
|
4318
|
+
return { ok: true };
|
|
4319
|
+
}
|
|
4320
|
+
function requireCli(conn, what) {
|
|
4321
|
+
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
|
|
4322
|
+
}
|
|
4323
|
+
const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
|
|
4324
|
+
/**
|
|
4325
|
+
* An offline session is removed this long after it went offline. The grace lets a session whose
|
|
4326
|
+
* host process is still alive come back with a heartbeat. Sessions already offline when the daemon
|
|
4327
|
+
* starts are removed at once.
|
|
4328
|
+
*/
|
|
4329
|
+
const OFFLINE_GRACE_MS = 6e4;
|
|
4330
|
+
/** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
|
|
4331
|
+
function removeOffline(daemon, graceMs) {
|
|
4332
|
+
const nowMs = daemon.now().getTime();
|
|
4333
|
+
const gone = daemon.store.allSessions().filter((r) => {
|
|
4334
|
+
if (r.status !== "offline") return false;
|
|
4335
|
+
const since = daemon.offlineSince.get(r.id) ?? Date.parse(r.lastSeenAt);
|
|
4336
|
+
return nowMs - since >= graceMs;
|
|
4337
|
+
});
|
|
4338
|
+
if (gone.length === 0) return;
|
|
4339
|
+
daemon.store.tx(() => {
|
|
4340
|
+
for (const r of gone) daemon.store.deleteSession(r.id);
|
|
4341
|
+
});
|
|
4342
|
+
for (const r of gone) {
|
|
4343
|
+
daemon.listeners.delete(r.id);
|
|
4344
|
+
daemon.woken.delete(r.id);
|
|
4345
|
+
daemon.wokenAt.delete(r.id);
|
|
4346
|
+
daemon.wakersOff.delete(r.id);
|
|
4347
|
+
daemon.offlineSince.delete(r.id);
|
|
4348
|
+
daemon.attached.delete(r.id);
|
|
4349
|
+
daemon.hookAt.delete(r.id);
|
|
4350
|
+
daemon.lastSent.delete(r.id);
|
|
4351
|
+
daemon.modelLabels.delete(r.id);
|
|
4352
|
+
}
|
|
4353
|
+
}
|
|
4354
|
+
/** Remove every offline session at once. The daemon does this when it starts. */
|
|
4355
|
+
function removeAllOffline(daemon) {
|
|
4356
|
+
removeOffline(daemon, 0);
|
|
4357
|
+
}
|
|
4358
|
+
/** A busy session no hook has touched for `STUCK_BUSY_MS` is idle: its turn end never came. */
|
|
4359
|
+
function clearStuckBusy(daemon, row, nowMs) {
|
|
4360
|
+
if (row.status !== "busy") return;
|
|
4361
|
+
if (nowMs - (daemon.hookAt.get(row.id) ?? Math.max(Date.parse(row.startedAt), daemon.startedMs)) <= 18e5) return;
|
|
4362
|
+
daemon.store.updateSession(row.id, {
|
|
4363
|
+
status: "idle",
|
|
4364
|
+
turnHops: 0
|
|
4365
|
+
});
|
|
4366
|
+
daemon.woken.delete(row.id);
|
|
4367
|
+
emitSession(daemon, row.id, "updated");
|
|
4368
|
+
}
|
|
4369
|
+
function sweep(daemon) {
|
|
4370
|
+
const nowMs = daemon.now().getTime();
|
|
4371
|
+
removeOffline(daemon, OFFLINE_GRACE_MS);
|
|
4372
|
+
retryDaemonWakes(daemon, nowMs);
|
|
4373
|
+
let online = 0;
|
|
4374
|
+
const rows = daemon.store.allSessions();
|
|
4375
|
+
for (const row of rows) {
|
|
4376
|
+
if (row.status === "offline") continue;
|
|
4377
|
+
const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), daemon.startedMs);
|
|
4378
|
+
const verdict = evaluateLiveness({
|
|
4379
|
+
lastSeenMs,
|
|
4380
|
+
hostPid: row.hostPid
|
|
4381
|
+
}, nowMs, daemon.isAlive);
|
|
4382
|
+
if (statusAfterLiveness(row.status, verdict) === "offline") {
|
|
4383
|
+
depart(daemon, row.id, "offline");
|
|
4384
|
+
continue;
|
|
4385
|
+
}
|
|
4386
|
+
online++;
|
|
4387
|
+
const pids = daemon.attached.get(row.id);
|
|
4388
|
+
if (pids) {
|
|
4389
|
+
for (const q of [...pids]) if (!daemon.isAlive(q)) pids.delete(q);
|
|
4390
|
+
}
|
|
4391
|
+
clearStuckBusy(daemon, row, nowMs);
|
|
4392
|
+
}
|
|
4393
|
+
if (online > 0) daemon.idleSince = nowMs;
|
|
4394
|
+
else if (nowMs - daemon.idleSince >= daemon.idleExitMs) daemon.requestIdleExit();
|
|
4395
|
+
}
|
|
4396
|
+
/** Start convenod: take the lock, open the database, listen on the socket. */
|
|
4397
|
+
async function startDaemon(opts) {
|
|
4398
|
+
const platform = process.platform;
|
|
4399
|
+
const paths = dataPaths(platform, opts.dataDir);
|
|
4400
|
+
const socketPath = opts.socketPath ?? defaultSocketPath(platform, process.env, homedir());
|
|
4401
|
+
if (isSocketPathTooLong(socketPath, platform)) throw new Error(socketPathTooLongMessage(socketPath, platform));
|
|
4402
|
+
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
4403
|
+
const isAlive = opts.isAlive ?? defaultIsAlive;
|
|
4404
|
+
const walker = opts.processIo === void 0 && platform === "win32" ? createWmiWalker({ scriptPath: join(opts.dataDir, "wmi-walk.js") }) : void 0;
|
|
4405
|
+
const processIo = opts.processIo ?? (walker ? {
|
|
4406
|
+
...defaultProcessIo,
|
|
4407
|
+
walk: walker.walk
|
|
4408
|
+
} : defaultProcessIo);
|
|
4409
|
+
ensureDir(opts.dataDir);
|
|
4410
|
+
const releaseLock = await acquireLock(paths.lock, socketPath);
|
|
4411
|
+
let store;
|
|
4412
|
+
let server;
|
|
4413
|
+
try {
|
|
4414
|
+
const token = loadOrCreateToken(paths.token);
|
|
4415
|
+
store = new Store(paths.database);
|
|
4416
|
+
if (platform !== "win32" && !socketPath.startsWith("\\\\")) ensureDir(dirname(socketPath));
|
|
4417
|
+
await clearStaleSocket(socketPath);
|
|
4418
|
+
let closing;
|
|
4419
|
+
let timer;
|
|
4420
|
+
const daemonLog = createDaemonLog(paths.daemonLog, { now });
|
|
4421
|
+
const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
|
|
4422
|
+
close().then(() => opts.onIdleExit?.());
|
|
4423
|
+
}, () => {
|
|
4424
|
+
close().then(() => opts.onShutdown?.());
|
|
4425
|
+
}, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings, leadLogPath(opts.dataDir));
|
|
4426
|
+
removeAllOffline(daemon);
|
|
4427
|
+
const srv = createServer((socket) => attach(daemon, socket));
|
|
4428
|
+
server = srv;
|
|
4429
|
+
await new Promise((resolve, reject) => {
|
|
4430
|
+
srv.once("error", (e) => reject(e.code === "EADDRINUSE" ? new DaemonAlreadyRunningError(`socket ${socketPath}`) : e));
|
|
4431
|
+
srv.listen(socketPath, () => resolve());
|
|
4432
|
+
});
|
|
4433
|
+
if (platform !== "win32" && !socketPath.startsWith("\\\\")) chmodSync(socketPath, 384);
|
|
4434
|
+
if (opts.relay !== false) startRelay(daemon, opts, opts.relay ?? {});
|
|
4435
|
+
timer = setInterval(() => sweep(daemon), opts.sweepIntervalMs ?? 15e3);
|
|
4436
|
+
timer.unref();
|
|
4437
|
+
const liveStore = store;
|
|
4438
|
+
function close() {
|
|
4439
|
+
closing ??= (async () => {
|
|
4440
|
+
if (timer) clearInterval(timer);
|
|
4441
|
+
daemon.stopping = true;
|
|
4442
|
+
walker?.close();
|
|
4443
|
+
daemon.relay?.stop();
|
|
4444
|
+
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
4445
|
+
for (const c of daemon.conns) c.socket.destroy();
|
|
4446
|
+
await stopped;
|
|
4447
|
+
liveStore.close();
|
|
4448
|
+
if (platform !== "win32" && !socketPath.startsWith("\\\\")) rmSync(socketPath, { force: true });
|
|
4449
|
+
releaseLock();
|
|
4450
|
+
})();
|
|
4451
|
+
return closing;
|
|
4452
|
+
}
|
|
4453
|
+
return {
|
|
4454
|
+
socketPath,
|
|
4455
|
+
close,
|
|
4456
|
+
sweep: () => sweep(daemon),
|
|
4457
|
+
testRelay: {
|
|
4458
|
+
host: () => relayHost(daemon),
|
|
4459
|
+
set: (relay) => {
|
|
4460
|
+
daemon.relay = relay && {
|
|
4461
|
+
sessionsChanged: () => {},
|
|
4462
|
+
...relay
|
|
4463
|
+
};
|
|
4464
|
+
}
|
|
4465
|
+
}
|
|
4466
|
+
};
|
|
4467
|
+
} catch (e) {
|
|
4468
|
+
server?.close();
|
|
4469
|
+
store?.close();
|
|
4470
|
+
releaseLock();
|
|
4471
|
+
throw e;
|
|
4472
|
+
}
|
|
4473
|
+
}
|
|
4474
|
+
/**
|
|
4475
|
+
* Run convenod as this process: start the daemon in the user's data directory, and exit when it
|
|
4476
|
+
* stops. Whoever starts the process passes the per-CLI wakers, so the daemon does not depend on
|
|
4477
|
+
* the adapters.
|
|
4478
|
+
*/
|
|
4479
|
+
function runConvenod(opts = {}) {
|
|
4480
|
+
main(opts).catch((e) => {
|
|
4481
|
+
if (e instanceof DaemonAlreadyRunningError) {
|
|
4482
|
+
process.stderr.write(`${e.message}\n`);
|
|
4483
|
+
process.exit(0);
|
|
4484
|
+
}
|
|
4485
|
+
process.stderr.write(`convenod failed to start: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
4486
|
+
process.exit(1);
|
|
4487
|
+
});
|
|
4488
|
+
}
|
|
4489
|
+
async function main(opts) {
|
|
4490
|
+
const handle = await startDaemon({
|
|
4491
|
+
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
4492
|
+
...opts.wakers ? { wakers: opts.wakers } : {},
|
|
4493
|
+
onIdleExit: () => {
|
|
4494
|
+
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
4495
|
+
process.exit(0);
|
|
4496
|
+
},
|
|
4497
|
+
onShutdown: () => process.exit(0)
|
|
4498
|
+
});
|
|
4499
|
+
process.stderr.write(`convenod: listening on ${handle.socketPath}\n`);
|
|
4500
|
+
let stopping = false;
|
|
4501
|
+
const stop = () => {
|
|
4502
|
+
if (stopping) return;
|
|
4503
|
+
stopping = true;
|
|
4504
|
+
handle.close().then(() => process.exit(0));
|
|
4505
|
+
};
|
|
4506
|
+
process.on("SIGINT", stop);
|
|
4507
|
+
process.on("SIGTERM", stop);
|
|
4508
|
+
}
|
|
4509
|
+
export { runConvenod as n, defaultIsAlive as t };
|