mindmeld-mcp 0.4.2 → 0.7.0
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/README.md +25 -2
- package/dist/answerer.js +52 -10
- package/dist/auth/config.js +7 -0
- package/dist/auth/github.js +60 -0
- package/dist/auth/session.js +101 -0
- package/dist/channel.js +117 -0
- package/dist/cli.js +186 -11
- package/dist/config.js +55 -3
- package/dist/crypto.js +24 -8
- package/dist/daemon.js +182 -83
- package/dist/identity.js +58 -0
- package/dist/mcp.js +116 -32
- package/dist/mcpteam.js +317 -0
- package/dist/protocol.js +26 -5
- package/dist/relay.js +82 -11
- package/dist/teamapi.js +234 -0
- package/dist/teamchannel.js +486 -0
- package/dist/teamcrypto.js +130 -0
- package/dist/teamkeys.js +245 -0
- package/dist/version.js +13 -0
- package/package.json +3 -2
package/dist/daemon.js
CHANGED
|
@@ -1,70 +1,131 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { EventEmitter } from "node:events";
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
|
|
3
|
+
import { GroupChannel } from "./channel.js";
|
|
4
|
+
import { ACTIVITY_CHECK_MS, ACTIVITY_RESOLUTION_MS, PROTOCOL_VERSION } from "./protocol.js";
|
|
5
|
+
/** A directed payload the channel could not address (e.g. the peer's device is no longer on the team roster). */
|
|
6
|
+
const unreachable = (name) => `can't reach ${name}'s session right now`;
|
|
7
|
+
/** Peer-id ownership bindings kept, so hello spam with random peer ids stays bounded. */
|
|
8
|
+
const MAX_PEER_OWNERS = 1000;
|
|
6
9
|
export class Daemon extends EventEmitter {
|
|
7
10
|
opts;
|
|
8
11
|
peerId = randomUUID();
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
stopped = false;
|
|
12
|
+
channel;
|
|
13
|
+
activityTimer = null;
|
|
14
|
+
lastSentActive = 0;
|
|
15
|
+
_stopped = false;
|
|
14
16
|
peers = new Map();
|
|
15
17
|
pending = new Map();
|
|
16
18
|
inbox = [];
|
|
17
19
|
askLog = new Map();
|
|
20
|
+
/**
|
|
21
|
+
* Verified login that first used each peer id (only for channels that report logins). A hello,
|
|
22
|
+
* bye or reply for that peer id from any other login is ignored. Bounded by MAX_PEER_OWNERS: beyond
|
|
23
|
+
* it, the oldest bindings of peers that are not online are forgotten.
|
|
24
|
+
*/
|
|
25
|
+
peerOwner = new Map();
|
|
18
26
|
share;
|
|
19
27
|
constructor(opts) {
|
|
20
28
|
super();
|
|
21
29
|
this.opts = opts;
|
|
22
30
|
this.share = opts.share === undefined ? { label: opts.project } : opts.share;
|
|
23
|
-
|
|
24
|
-
|
|
31
|
+
if (!opts.channel && !opts.secret)
|
|
32
|
+
throw new Error("no group secret and no channel");
|
|
33
|
+
this.channel = opts.channel ?? new GroupChannel({ secret: opts.secret, relay: opts.relay, version: opts.version });
|
|
34
|
+
this.wireChannel();
|
|
35
|
+
}
|
|
36
|
+
/** Encrypted frames this client has sent (only transports that count them report it). */
|
|
37
|
+
get framesSent() {
|
|
38
|
+
return this.channel.framesSent ?? 0;
|
|
39
|
+
}
|
|
40
|
+
/** No reconnect and no "disconnected" event once stopped. Also forwarded to the channel (tests crash a daemon this way). */
|
|
41
|
+
get stopped() {
|
|
42
|
+
return this._stopped;
|
|
43
|
+
}
|
|
44
|
+
set stopped(v) {
|
|
45
|
+
this._stopped = v;
|
|
46
|
+
if ("stopped" in this.channel)
|
|
47
|
+
this.channel.stopped = v;
|
|
48
|
+
}
|
|
49
|
+
/** The channel's socket, if it has one. Kept so tests can kill the connection. */
|
|
50
|
+
get ws() {
|
|
51
|
+
return this.channel.ws ?? null;
|
|
25
52
|
}
|
|
26
53
|
start() {
|
|
27
|
-
this.
|
|
28
|
-
|
|
54
|
+
this.channel.start();
|
|
55
|
+
// Re-announce only when "last active" moved enough to matter for routing; no heartbeat.
|
|
56
|
+
this.activityTimer = setInterval(() => {
|
|
57
|
+
if (!this.share)
|
|
58
|
+
return;
|
|
59
|
+
const at = this.activeAt();
|
|
60
|
+
if (at && at - this.lastSentActive >= ACTIVITY_RESOLUTION_MS)
|
|
61
|
+
this.sendHello();
|
|
62
|
+
}, this.opts.activityCheckMs ?? ACTIVITY_CHECK_MS);
|
|
63
|
+
this.activityTimer.unref?.();
|
|
64
|
+
}
|
|
65
|
+
/** Version info from the relay: latest, minimum, and how many teammates run an old client. */
|
|
66
|
+
get server() {
|
|
67
|
+
return this.channel.server;
|
|
29
68
|
}
|
|
30
69
|
async stop() {
|
|
31
|
-
this.
|
|
32
|
-
if (this.
|
|
33
|
-
clearInterval(this.
|
|
70
|
+
this._stopped = true;
|
|
71
|
+
if (this.activityTimer)
|
|
72
|
+
clearInterval(this.activityTimer);
|
|
34
73
|
this.send({ type: "bye", peer: this.peerId });
|
|
35
|
-
this.
|
|
74
|
+
const stopping = this.channel.stop();
|
|
36
75
|
for (const p of this.pending.values())
|
|
37
76
|
p.resolve({ error: "daemon stopped" });
|
|
77
|
+
await stopping;
|
|
38
78
|
}
|
|
79
|
+
/** Peers present right now. The relay reports leaves, so there is no timeout to wait out. */
|
|
39
80
|
onlinePeers() {
|
|
40
|
-
|
|
41
|
-
return [...this.peers.values()].filter((p) => now - p.lastSeen < PEER_TIMEOUT_MS);
|
|
81
|
+
return [...this.peers.values()];
|
|
42
82
|
}
|
|
43
|
-
// ──
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
83
|
+
// ── channel events ──────────────────────────────────────────────────
|
|
84
|
+
wireChannel() {
|
|
85
|
+
const ch = this.channel;
|
|
86
|
+
ch.on("connected", () => {
|
|
87
|
+
// Connection ids from a previous connection are meaningless now; shared peers re-announce
|
|
88
|
+
// themselves in response to our "joined".
|
|
89
|
+
this.peers.clear();
|
|
48
90
|
this.emit("connected");
|
|
49
91
|
this.sendHello();
|
|
50
92
|
});
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (this.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
93
|
+
ch.on("disconnected", () => {
|
|
94
|
+
for (const peer of [...this.peers.values()])
|
|
95
|
+
this.dropPeer(peer.peer, "disconnected from the relay");
|
|
96
|
+
if (!this._stopped)
|
|
97
|
+
this.emit("disconnected");
|
|
98
|
+
});
|
|
99
|
+
ch.on("relay-error", (e) => this.emit("relay-error", e));
|
|
100
|
+
ch.on("server", (info) => this.emit("server", info));
|
|
101
|
+
ch.on("blocked", (info) => {
|
|
102
|
+
this._stopped = true;
|
|
103
|
+
this.emit("blocked", info);
|
|
104
|
+
});
|
|
105
|
+
ch.on("joined", () => {
|
|
106
|
+
if (this.share)
|
|
107
|
+
this.sendHello(); // let the newcomer see this shared session
|
|
58
108
|
});
|
|
109
|
+
ch.on("left", (cid) => {
|
|
110
|
+
for (const p of [...this.peers.values()])
|
|
111
|
+
if (p.cid === cid)
|
|
112
|
+
this.dropPeer(p.peer, "closed");
|
|
113
|
+
});
|
|
114
|
+
ch.on("payload", (p, from) => this.handlePayload(p, from));
|
|
59
115
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Hand a payload to the channel. Directed payloads carry their recipient (`to`); presence (hello,
|
|
118
|
+
* bye) never does. False when the channel cannot resolve the recipient (nothing was sent).
|
|
119
|
+
*/
|
|
120
|
+
send(p, to) {
|
|
121
|
+
return this.channel.send(p, to);
|
|
65
122
|
}
|
|
66
123
|
get connected() {
|
|
67
|
-
return this.
|
|
124
|
+
return this.channel.connected;
|
|
125
|
+
}
|
|
126
|
+
/** The name this daemon announces itself as (the login, on a team). */
|
|
127
|
+
get name() {
|
|
128
|
+
return this.opts.name;
|
|
68
129
|
}
|
|
69
130
|
get sharing() {
|
|
70
131
|
return this.share;
|
|
@@ -81,13 +142,10 @@ export class Daemon extends EventEmitter {
|
|
|
81
142
|
sendHello() {
|
|
82
143
|
if (!this.share)
|
|
83
144
|
return; // unshared sessions never announce themselves
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
catch {
|
|
89
|
-
// best-effort metadata
|
|
90
|
-
}
|
|
145
|
+
const activeAt = this.activeAt();
|
|
146
|
+
if (activeAt)
|
|
147
|
+
this.lastSentActive = activeAt;
|
|
148
|
+
const info = { activeAt };
|
|
91
149
|
this.send({
|
|
92
150
|
type: "hello",
|
|
93
151
|
peer: this.peerId,
|
|
@@ -97,54 +155,88 @@ export class Daemon extends EventEmitter {
|
|
|
97
155
|
v: PROTOCOL_VERSION,
|
|
98
156
|
});
|
|
99
157
|
}
|
|
100
|
-
|
|
101
|
-
let frame;
|
|
158
|
+
activeAt() {
|
|
102
159
|
try {
|
|
103
|
-
|
|
160
|
+
return this.opts.sessionInfo?.().activeAt;
|
|
104
161
|
}
|
|
105
162
|
catch {
|
|
106
|
-
return;
|
|
163
|
+
return undefined; // best-effort metadata
|
|
107
164
|
}
|
|
108
|
-
|
|
109
|
-
|
|
165
|
+
}
|
|
166
|
+
/** Forget a peer, and fail any question still waiting on it instead of letting it time out. */
|
|
167
|
+
dropPeer(peerId, why) {
|
|
168
|
+
const info = this.peers.get(peerId);
|
|
169
|
+
if (!info)
|
|
110
170
|
return;
|
|
111
|
-
|
|
112
|
-
|
|
171
|
+
this.peers.delete(peerId);
|
|
172
|
+
this.emit("peer-left", info);
|
|
173
|
+
for (const [id, p] of this.pending) {
|
|
174
|
+
if (p.target === peerId) {
|
|
175
|
+
this.pending.delete(id);
|
|
176
|
+
p.resolve({ error: `${info.name}'s session ${why} before answering` });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/** False if `login` (a verified identity key) is set and the peer id was first seen from a different one; binds it otherwise. */
|
|
181
|
+
ownsPeer(peerId, login) {
|
|
182
|
+
if (login === undefined)
|
|
183
|
+
return true;
|
|
184
|
+
const owner = this.peerOwner.get(peerId);
|
|
185
|
+
if (owner === undefined) {
|
|
186
|
+
this.peerOwner.set(peerId, login);
|
|
187
|
+
if (this.peerOwner.size > MAX_PEER_OWNERS) {
|
|
188
|
+
for (const old of this.peerOwner.keys()) {
|
|
189
|
+
if (this.peerOwner.size <= MAX_PEER_OWNERS)
|
|
190
|
+
break;
|
|
191
|
+
if (!this.peers.has(old) && old !== peerId)
|
|
192
|
+
this.peerOwner.delete(old);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return owner === undefined || owner === login;
|
|
197
|
+
}
|
|
198
|
+
/** False if a reply to a question came from a login other than the one that owns the asked peer. */
|
|
199
|
+
fromTarget(pending, login) {
|
|
200
|
+
if (login === undefined)
|
|
201
|
+
return true;
|
|
202
|
+
const owner = this.peerOwner.get(pending.target);
|
|
203
|
+
return owner === undefined || owner === login;
|
|
204
|
+
}
|
|
205
|
+
handlePayload(p, from) {
|
|
206
|
+
// An authenticated login beats any name the payload claims for itself (it is the display name).
|
|
207
|
+
const login = from.login;
|
|
208
|
+
// Ownership binds to the most stable verified identity: the GitHub id on a team, else the login.
|
|
209
|
+
const owner = from.uid !== undefined ? `uid:${from.uid}` : login;
|
|
210
|
+
if ((p.type === "hello" || p.type === "bye") && !this.ownsPeer(p.peer, owner))
|
|
113
211
|
return;
|
|
114
|
-
const p = parsed.data;
|
|
115
212
|
switch (p.type) {
|
|
116
213
|
case "hello": {
|
|
117
|
-
const isNew = !this.
|
|
214
|
+
const isNew = !this.peers.has(p.peer);
|
|
118
215
|
this.peers.set(p.peer, {
|
|
119
216
|
peer: p.peer,
|
|
120
|
-
name: p.name,
|
|
217
|
+
name: login ?? p.name,
|
|
121
218
|
project: p.project,
|
|
122
219
|
session: p.session,
|
|
123
220
|
activeAt: p.activeAt,
|
|
124
221
|
v: p.v,
|
|
222
|
+
cid: from.cid,
|
|
125
223
|
lastSeen: Date.now(),
|
|
126
224
|
});
|
|
127
|
-
if (isNew)
|
|
225
|
+
if (isNew)
|
|
128
226
|
this.emit("peer-joined", this.peers.get(p.peer));
|
|
129
|
-
this.sendHello(); // let the newcomer see us immediately
|
|
130
|
-
}
|
|
131
227
|
break;
|
|
132
228
|
}
|
|
133
|
-
case "bye":
|
|
134
|
-
|
|
135
|
-
this.peers.delete(p.peer);
|
|
136
|
-
if (info)
|
|
137
|
-
this.emit("peer-left", info);
|
|
229
|
+
case "bye":
|
|
230
|
+
this.dropPeer(p.peer, "stopped sharing");
|
|
138
231
|
break;
|
|
139
|
-
}
|
|
140
232
|
case "ask":
|
|
141
233
|
// Only a shared session answers, and only questions addressed to it (or legacy broadcasts).
|
|
142
234
|
if (this.share && (!p.to || p.to === this.opts.name || p.to === this.peerId))
|
|
143
|
-
void this.handleAsk(p);
|
|
235
|
+
void this.handleAsk(p, login, owner, from.device);
|
|
144
236
|
break;
|
|
145
237
|
case "status": {
|
|
146
238
|
const pending = this.pending.get(p.id);
|
|
147
|
-
if (pending) {
|
|
239
|
+
if (pending && this.fromTarget(pending, owner)) {
|
|
148
240
|
pending.acked = true;
|
|
149
241
|
pending.onStatus?.(p.state);
|
|
150
242
|
}
|
|
@@ -152,17 +244,17 @@ export class Daemon extends EventEmitter {
|
|
|
152
244
|
}
|
|
153
245
|
case "answer": {
|
|
154
246
|
const pending = this.pending.get(p.id);
|
|
155
|
-
if (pending) {
|
|
247
|
+
if (pending && this.fromTarget(pending, owner)) {
|
|
156
248
|
this.pending.delete(p.id);
|
|
157
|
-
pending.resolve({ from: this.nameOf(p.from), text: p.text });
|
|
249
|
+
pending.resolve({ from: this.nameOf(p.from, undefined, login), text: p.text });
|
|
158
250
|
}
|
|
159
251
|
break;
|
|
160
252
|
}
|
|
161
253
|
case "decline": {
|
|
162
254
|
const pending = this.pending.get(p.id);
|
|
163
|
-
if (!pending)
|
|
255
|
+
if (!pending || !this.fromTarget(pending, owner))
|
|
164
256
|
break;
|
|
165
|
-
pending.declines.push(`${this.nameOf(p.from)}: ${p.reason}`);
|
|
257
|
+
pending.declines.push(`${this.nameOf(p.from, undefined, login)}: ${p.reason}`);
|
|
166
258
|
if (pending.declines.length >= pending.expected) {
|
|
167
259
|
this.pending.delete(p.id);
|
|
168
260
|
pending.resolve({ error: `declined — ${pending.declines.join("; ")}` });
|
|
@@ -171,14 +263,14 @@ export class Daemon extends EventEmitter {
|
|
|
171
263
|
}
|
|
172
264
|
case "snippet":
|
|
173
265
|
if (!p.to || p.to === this.opts.name || p.to === this.peerId) {
|
|
174
|
-
this.inbox.push({ ...p, from: this.nameOf(p.from) });
|
|
266
|
+
this.inbox.push({ ...p, from: this.nameOf(p.from, undefined, login) });
|
|
175
267
|
this.emit("snippet", p);
|
|
176
268
|
}
|
|
177
269
|
break;
|
|
178
270
|
}
|
|
179
271
|
}
|
|
180
|
-
nameOf(peerId, fallback) {
|
|
181
|
-
return this.peers.get(peerId)?.name ?? fallback ?? peerId.slice(0, 8);
|
|
272
|
+
nameOf(peerId, fallback, login) {
|
|
273
|
+
return login ?? this.peers.get(peerId)?.name ?? fallback ?? peerId.slice(0, 8);
|
|
182
274
|
}
|
|
183
275
|
rateLimited(from) {
|
|
184
276
|
const { max, windowMs } = this.opts.rateLimit ?? { max: 10, windowMs: 10 * 60_000 };
|
|
@@ -189,23 +281,26 @@ export class Daemon extends EventEmitter {
|
|
|
189
281
|
return recent.length > max;
|
|
190
282
|
}
|
|
191
283
|
seenAsks = new Set();
|
|
192
|
-
async handleAsk(ask) {
|
|
284
|
+
async handleAsk(ask, login, owner, device) {
|
|
193
285
|
if (this.seenAsks.has(ask.id))
|
|
194
286
|
return; // a resend of a question already being handled
|
|
195
287
|
this.seenAsks.add(ask.id);
|
|
288
|
+
// Replies go back to the device the question came from (askers never send a hello).
|
|
289
|
+
const asker = { device };
|
|
196
290
|
const reply = (d) => d.action === "send"
|
|
197
|
-
? this.send({ type: "answer", id: ask.id, from: this.peerId, text: d.text })
|
|
198
|
-
: this.send({ type: "decline", id: ask.id, from: this.peerId, reason: d.reason });
|
|
199
|
-
const report = (state) => this.send({ type: "status", id: ask.id, from: this.peerId, state });
|
|
291
|
+
? this.send({ type: "answer", id: ask.id, from: this.peerId, text: d.text }, asker)
|
|
292
|
+
: this.send({ type: "decline", id: ask.id, from: this.peerId, reason: d.reason }, asker);
|
|
293
|
+
const report = (state) => void this.send({ type: "status", id: ask.id, from: this.peerId, state }, asker);
|
|
200
294
|
report("received");
|
|
201
|
-
|
|
295
|
+
// A verified identity cannot dodge the limit by rotating peer ids.
|
|
296
|
+
if (this.rateLimited(owner ?? login ?? ask.from)) {
|
|
202
297
|
reply({ action: "decline", reason: "rate limited — too many questions, try again later" });
|
|
203
298
|
return;
|
|
204
299
|
}
|
|
205
|
-
const from = this.nameOf(ask.from, ask.fromName);
|
|
300
|
+
const from = this.nameOf(ask.from, ask.fromName, login);
|
|
206
301
|
this.emit("question", { from, question: ask.question });
|
|
207
302
|
try {
|
|
208
|
-
const d = await this.opts.decide({ ...ask, from }, report);
|
|
303
|
+
const d = await this.opts.decide({ ...ask, from, fromName: from }, report);
|
|
209
304
|
this.emit("handled", { from, question: ask.question, action: d.action });
|
|
210
305
|
reply(d);
|
|
211
306
|
}
|
|
@@ -257,27 +352,31 @@ export class Daemon extends EventEmitter {
|
|
|
257
352
|
};
|
|
258
353
|
timers.push(setTimeout(() => finish({ error: `no answer within ${timeoutSec}s` }), timeoutSec * 1000));
|
|
259
354
|
// Peers from 0.4 on acknowledge at once; older ones don't, so only hold newer ones to it.
|
|
355
|
+
const to = { peer: target.peer };
|
|
260
356
|
const payload = { type: "ask", id, from: this.peerId, fromName: this.opts.name, to: target.peer, question, context: opts.context };
|
|
261
357
|
if ((target.v ?? 0) >= 2) {
|
|
262
358
|
// Not acknowledged halfway through the window: resend once (a frame can be lost while
|
|
263
359
|
// the socket reconnects). The answering side ignores duplicate ids.
|
|
264
360
|
const ackMs = this.opts.ackTimeoutMs ?? 15_000;
|
|
265
|
-
timers.push(setTimeout(() => !this.pending.get(id)?.acked && this.send(payload), ackMs / 2));
|
|
361
|
+
timers.push(setTimeout(() => !this.pending.get(id)?.acked && this.send(payload, to), ackMs / 2));
|
|
266
362
|
timers.push(setTimeout(() => {
|
|
267
363
|
if (!this.pending.get(id)?.acked) {
|
|
268
364
|
finish({ error: `${target.name}'s session didn't acknowledge the question. It may have just closed or stopped sharing.` });
|
|
269
365
|
}
|
|
270
366
|
}, ackMs));
|
|
271
367
|
}
|
|
272
|
-
this.pending.set(id, { resolve: finish, onStatus: opts.onStatus, acked: false, expected: 1, declines: [] });
|
|
273
|
-
this.send(payload)
|
|
368
|
+
this.pending.set(id, { target: target.peer, resolve: finish, onStatus: opts.onStatus, acked: false, expected: 1, declines: [] });
|
|
369
|
+
if (!this.send(payload, to))
|
|
370
|
+
finish({ error: unreachable(target.name) });
|
|
274
371
|
});
|
|
275
372
|
}
|
|
276
373
|
snippet(title, text, peer) {
|
|
277
374
|
const target = this.route(peer);
|
|
278
375
|
if ("error" in target)
|
|
279
376
|
return target;
|
|
280
|
-
this.send({ type: "snippet", id: randomUUID(), from: this.peerId, to: target.peer, title, text })
|
|
377
|
+
if (!this.send({ type: "snippet", id: randomUUID(), from: this.peerId, to: target.peer, title, text }, { peer: target.peer })) {
|
|
378
|
+
return { error: unreachable(target.name) };
|
|
379
|
+
}
|
|
281
380
|
return { ok: true, to: target.name };
|
|
282
381
|
}
|
|
283
382
|
drainInbox() {
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
5
|
+
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
|
|
6
|
+
import { homeDir } from "./config.js";
|
|
7
|
+
const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
8
|
+
/** Parse and verify an existing identity file; never regenerates, since that would change the device identity. */
|
|
9
|
+
function readIdentity(path) {
|
|
10
|
+
const bad = (why) => new Error(`${path} is corrupt (${why}). Repair it or delete it to create a new device identity.`);
|
|
11
|
+
let raw;
|
|
12
|
+
try {
|
|
13
|
+
raw = JSON.parse(readFileSync(path, "utf8"));
|
|
14
|
+
}
|
|
15
|
+
catch (e) {
|
|
16
|
+
throw bad(e.message);
|
|
17
|
+
}
|
|
18
|
+
const keys = ["deviceId", "signPub", "signPriv", "boxPub", "boxPriv"];
|
|
19
|
+
if (!raw || typeof raw !== "object" || keys.some((k) => typeof raw[k] !== "string"))
|
|
20
|
+
throw bad("missing or non-string fields");
|
|
21
|
+
const id = raw;
|
|
22
|
+
try {
|
|
23
|
+
if (id.deviceId !== sha256Hex(hexToBytes(id.signPub)).slice(0, 16) ||
|
|
24
|
+
id.signPub !== bytesToHex(ed25519.getPublicKey(hexToBytes(id.signPriv))) ||
|
|
25
|
+
id.boxPub !== bytesToHex(x25519.getPublicKey(hexToBytes(id.boxPriv))))
|
|
26
|
+
throw new Error("mismatch");
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw bad("keys do not match");
|
|
30
|
+
}
|
|
31
|
+
return id;
|
|
32
|
+
}
|
|
33
|
+
/** Read `identity.json` from the mindmeld home, creating it (mode 600) on first use. */
|
|
34
|
+
export function loadOrCreateIdentity() {
|
|
35
|
+
const path = join(homeDir(), "identity.json");
|
|
36
|
+
if (existsSync(path))
|
|
37
|
+
return readIdentity(path);
|
|
38
|
+
const signPriv = ed25519.utils.randomSecretKey();
|
|
39
|
+
const signPub = ed25519.getPublicKey(signPriv);
|
|
40
|
+
const boxPriv = x25519.utils.randomSecretKey();
|
|
41
|
+
const boxPub = x25519.getPublicKey(boxPriv);
|
|
42
|
+
const id = {
|
|
43
|
+
deviceId: sha256Hex(signPub).slice(0, 16),
|
|
44
|
+
signPub: bytesToHex(signPub),
|
|
45
|
+
signPriv: bytesToHex(signPriv),
|
|
46
|
+
boxPub: bytesToHex(boxPub),
|
|
47
|
+
boxPriv: bytesToHex(boxPriv),
|
|
48
|
+
};
|
|
49
|
+
mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
|
|
50
|
+
writeFileSync(path, JSON.stringify(id, null, 2) + "\n", { mode: 0o600 });
|
|
51
|
+
chmodSync(path, 0o600);
|
|
52
|
+
return id;
|
|
53
|
+
}
|
|
54
|
+
/** Human-comparable key fingerprint: first 16 bytes of sha256(signPub) as groups of 4 hex chars. */
|
|
55
|
+
export function fingerprint(signPub) {
|
|
56
|
+
const hex = sha256Hex(hexToBytes(signPub)).slice(0, 32);
|
|
57
|
+
return hex.match(/.{4}/g).join(" ");
|
|
58
|
+
}
|