murmur-it 0.2.9 → 0.2.11

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/core.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { basename } from 'node:path';
2
+ import { thisMachine } from './machine.js';
2
3
  import { isAlive, liveTable } from './proc.js';
3
4
  import { DUP_WINDOW_MS, HANDLE_RE, MurmurError, RATE_MAX_SENDS, RATE_WINDOW_MS, THREAD_CAP, UNREAD_CAP, firstLine, renderDelivery, replyFooter, truncateForDelivery, } from './protocol.js';
4
5
  export { HANDLE_RE };
@@ -10,6 +11,14 @@ const UNREAD_STATES = ['queued', 'sent', 'delivered'];
10
11
  // are never acked fill the cap and block every later reply to the asker.
11
12
  const BACKLOG_STATES = ['queued', 'sent'];
12
13
  const OFFLINE_AFTER_MS = 5 * 60 * 1000;
14
+ // A session of another machine counts as alive this long after its last event
15
+ // (its hooks only fire on a prompt or a stop, so an idle session is quiet).
16
+ const REMOTE_LEASE_MS = 12 * 60 * 60 * 1000;
17
+ // After a broker start the connections that kept sessions of other machines
18
+ // alive are gone until their MCP servers reconnect, which they do within 5
19
+ // seconds (20 attempts, 250 ms apart); a minute covers that twelve times over
20
+ // and is short enough not to hold the handle of a session that is really gone.
21
+ const STARTUP_GRACE_MS = 60 * 1000;
13
22
  // A session title as a handle: lowercase, runs of anything else become one
14
23
  // hyphen, trimmed, cut to the handle limit. Not necessarily a valid handle.
15
24
  export function slugify(title) {
@@ -117,14 +126,110 @@ export class MurmurCore {
117
126
  hookOverrides = new Map();
118
127
  // Set by the broker: does the handle have a live mcp or adapter connection.
119
128
  hasTools = () => false;
129
+ // Set by the broker: is a live mcp or adapter connection open from this
130
+ // host. A session on another machine has no process here to look up, so
131
+ // that connection is its liveness.
132
+ hostConnected = () => false;
120
133
  // Process table source for session liveness, asked only for the pids that
121
134
  // matter; injectable for tests.
122
135
  procTable;
123
- constructor(store, events, now, procTable) {
136
+ // Where the boot id of the machine this broker runs on is read ('' when
137
+ // unreadable): its host references are judged by the process table, every
138
+ // other machine's by a connection, a lease or the startup grace. A function
139
+ // is read each time, since the broker retries a read that failed at start.
140
+ machineSource;
141
+ // The own machine as last read, to see it appear.
142
+ seenMachine;
143
+ startedAt;
144
+ constructor(store, events, now, procTable, machine) {
124
145
  this.store = store;
125
146
  this.events = events;
126
147
  this.nowFn = now ?? Date.now;
127
148
  this.procTable = procTable ?? ((pids) => liveTable(pids));
149
+ this.machineSource = typeof machine === 'function' ? machine : machine === undefined ? thisMachine : () => machine;
150
+ this.seenMachine = this.machineSource();
151
+ this.startedAt = this.nowMs();
152
+ }
153
+ // The boot id of this broker's machine. A broker that could not read it at
154
+ // start and now can finds rows that clients wrote under that id while it was
155
+ // taken for another machine: they are its own, so they are re-keyed once, and
156
+ // the process table judges them from then on.
157
+ ownMachine() {
158
+ const read = this.machineSource();
159
+ if (read !== this.seenMachine) {
160
+ // No row is keyed to '', so losing the id re-keys nothing.
161
+ this.store.rekeyMachine(read);
162
+ this.seenMachine = read;
163
+ }
164
+ return read;
165
+ }
166
+ // The machine a host reference names as stored (its boot id): null for this
167
+ // broker's own machine and for a client that sends none (an old client, or one
168
+ // that cannot read a boot id). A broker with no boot id of its own takes every
169
+ // client that sends one for another machine, so handles are never shared.
170
+ // Two names are one machine when their boot ids are; the host name is never
171
+ // compared.
172
+ machineKey(host) {
173
+ const own = this.ownMachine();
174
+ return host.machine === undefined || host.machine === own ? null : host.machine;
175
+ }
176
+ // The machine, label and fingerprint to store on an event of a known session.
177
+ // An event that carries no machine at all (a client whose boot id read
178
+ // failed) leaves what the session had; one that carries a machine sets it, and
179
+ // keeps the label and the fingerprint when it carries none for the same
180
+ // machine.
181
+ machineFields(row, host) {
182
+ if (host.machine === undefined && row.hostMachine !== null) {
183
+ return {};
184
+ }
185
+ const key = this.machineKey(host);
186
+ const same = key === row.hostMachine;
187
+ return {
188
+ hostMachine: key,
189
+ hostLabel: this.labelOf(host) ?? (same ? row.hostLabel : null),
190
+ hostFingerprint: this.fingerprintOf(host) ?? (same ? row.hostFingerprint : null),
191
+ };
192
+ }
193
+ // The fingerprint stored with a machine other than this broker's.
194
+ fingerprintOf(host) {
195
+ return this.machineKey(host) === null ? null : (host.machineFingerprint ?? null);
196
+ }
197
+ // The host name label stored with a machine other than this broker's.
198
+ labelOf(host) {
199
+ return this.machineKey(host) === null ? null : (host.machineName ?? null);
200
+ }
201
+ // The session of this host process. A client that gains a machine id (an
202
+ // upgrade) finds the row an old client of the same process wrote without one,
203
+ // and a client that sends none (its boot id read failed this once) finds the
204
+ // row that carries one, in both cases only when no live process of this
205
+ // machine has that pid and start and the CLI ids do not conflict (an event and
206
+ // a row that both carry one and differ are two sessions). The row takes the
207
+ // machine of the event when it has one, so one session never becomes two. An
208
+ // event and a row that both carry a folder and differ are two sessions too:
209
+ // the same pid and start second can come up on two machines started from one
210
+ // image.
211
+ rowAt(host, cliSessionId = null, cwd) {
212
+ const key = this.machineKey(host);
213
+ const row = this.store.sessionByHost(host.hostPid, host.hostStart, key);
214
+ if (row !== null) {
215
+ return row;
216
+ }
217
+ // The rows of this pid and start that could be this session: rows of one
218
+ // machine only, since the host of an event without a machine could be any.
219
+ const rows = this.store.sessionsOfHost(host.hostPid, host.hostStart).filter((r) => key === null || r.hostMachine === null);
220
+ const table = rows.length === 0 ? new Map() : this.safeProcTable([host.hostPid]);
221
+ const found = rows.filter((r) => r.state !== 'ended' &&
222
+ !(cliSessionId !== null && r.cliSessionId !== null && r.cliSessionId !== cliSessionId) &&
223
+ !(cwd !== undefined && r.cwd !== null && r.cwd !== cwd) &&
224
+ !isAlive(table, r.hostPid, r.hostStart));
225
+ const other = found[0];
226
+ if (other === undefined || found.some((r) => r.hostMachine !== other.hostMachine)) {
227
+ return null;
228
+ }
229
+ if (key !== null) {
230
+ this.store.updateSession(other.id, { hostMachine: key, hostLabel: this.labelOf(host), hostFingerprint: this.fingerprintOf(host) });
231
+ }
232
+ return this.store.sessionById(other.id);
128
233
  }
129
234
  nowMs() {
130
235
  return this.nowFn();
@@ -509,6 +614,7 @@ export class MurmurCore {
509
614
  // online before any; then a live connection; then the legacy hook state;
510
615
  // then the five minute window over last_seen_at, then presumed-offline.
511
616
  status(live) {
617
+ this.ownMachine();
512
618
  const ts = this.nowMs();
513
619
  const byHandle = new Map();
514
620
  for (const row of this.store.listSessions()) {
@@ -527,7 +633,7 @@ export class MurmurCore {
527
633
  const hookState = override !== undefined ? override.state : normalizeHookState(peer.hookState);
528
634
  const hookAt = override !== undefined ? override.at : peer.lastHookActivityAt;
529
635
  const sessions = byHandle.get(peer.handle) ?? [];
530
- const session = sessions.find((row) => row.state !== 'ended' && isAlive(table, row.hostPid, row.hostStart));
636
+ const session = sessions.find((row) => row.state !== 'ended' && this.alive(table, row));
531
637
  let presence;
532
638
  let busySince = null;
533
639
  let idleSince = null;
@@ -651,7 +757,9 @@ export class MurmurCore {
651
757
  sessionEvent(arg) {
652
758
  const ts = this.nowMs();
653
759
  let row = arg.cliSessionId === null ? null : this.store.sessionByCliId(arg.client, arg.cliSessionId);
654
- row ??= this.store.sessionByHost(arg.host.hostPid, arg.host.hostStart);
760
+ row ??= this.rowAt(arg.host, arg.cliSessionId, arg.cwd);
761
+ // Before a new row takes a handle, so it can have the handle of a session that a reboot ended.
762
+ this.endRebootedSessions(row?.id ?? -1, arg.host, ts);
655
763
  if (row === null) {
656
764
  const explicit = arg.handle !== undefined && this.claimable(arg.handle, null);
657
765
  const slug = arg.title === undefined ? '' : slugify(arg.title);
@@ -667,6 +775,9 @@ export class MurmurCore {
667
775
  handle,
668
776
  hostPid: arg.host.hostPid,
669
777
  hostStart: arg.host.hostStart,
778
+ hostMachine: this.machineKey(arg.host),
779
+ hostLabel: this.labelOf(arg.host),
780
+ hostFingerprint: this.fingerprintOf(arg.host),
670
781
  transcriptPath: arg.transcriptPath ?? null,
671
782
  cwd: arg.cwd ?? null,
672
783
  now: ts,
@@ -677,10 +788,18 @@ export class MurmurCore {
677
788
  }
678
789
  }
679
790
  else {
791
+ // A session that comes back after another took its handle must not share it.
792
+ if (row.state === 'ended' && arg.event !== 'session-end' && this.liveHolders(row.handle, row.id).length > 0) {
793
+ const handle = this.allocateHandle(arg.client, arg.cwd ?? row.cwd ?? undefined);
794
+ this.ensurePeer(handle);
795
+ this.store.reassignSession(row.id, row.handle, handle, false);
796
+ row = this.store.sessionById(row.id);
797
+ }
680
798
  this.store.updateSession(row.id, {
681
799
  client: arg.client,
682
800
  hostPid: arg.host.hostPid,
683
801
  hostStart: arg.host.hostStart,
802
+ ...this.machineFields(row, arg.host),
684
803
  updatedAt: ts,
685
804
  ...(arg.cliSessionId !== null ? { cliSessionId: arg.cliSessionId } : {}),
686
805
  ...(arg.transcriptPath !== undefined ? { transcriptPath: arg.transcriptPath } : {}),
@@ -697,10 +816,14 @@ export class MurmurCore {
697
816
  fresh = this.followTitle(fresh, arg.title);
698
817
  }
699
818
  if (arg.native !== undefined) {
700
- this.store.upsertNativeTransport(fresh.handle, arg.native.socketPath, arg.native.token, ts);
819
+ if (!this.sharesHandle(fresh)) {
820
+ this.store.upsertNativeTransport(fresh.handle, arg.native.socketPath, arg.native.token, ts);
821
+ }
701
822
  }
702
823
  if (arg.event === 'session-end') {
703
- this.store.deleteNativeTransport(fresh.handle);
824
+ if (!this.sharesHandle(fresh)) {
825
+ this.store.deleteNativeTransport(fresh.handle);
826
+ }
704
827
  }
705
828
  return fresh;
706
829
  }
@@ -717,11 +840,46 @@ export class MurmurCore {
717
840
  this.store.upsertPeer(current.handle, title, null, false, this.nowMs());
718
841
  return current;
719
842
  }
843
+ // An event that carries a boot id other than the one stored for sessions of
844
+ // the same machine means that machine rebooted, which ended every process on
845
+ // it: those sessions end at once. The same machine is the same fingerprint
846
+ // (a hash of the id the system keeps for itself) and the same host name label:
847
+ // a host name alone is no evidence, two machines can share one (raspberrypi,
848
+ // localhost) and then each one's events would look like a reboot of the other.
849
+ // Without a fingerprint on the event or on the row, or with a changed host
850
+ // name, nothing says it is the same machine and the lease applies. The old
851
+ // sessions must also have been last heard from before the new boot (the
852
+ // uptime), and none of their hosts may be connected. While the broker has just
853
+ // started, connections are still coming back and nothing can be told from
854
+ // their absence.
855
+ endRebootedSessions(id, host, ts) {
856
+ const key = this.machineKey(host);
857
+ const label = this.labelOf(host);
858
+ const fingerprint = this.fingerprintOf(host);
859
+ if (key === null || label === null || fingerprint === null) {
860
+ return;
861
+ }
862
+ if (host.machineUptime === undefined || ts - this.startedAt <= STARTUP_GRACE_MS) {
863
+ return;
864
+ }
865
+ const bootedAt = ts - host.machineUptime * 1000;
866
+ for (const old of this.store.rebootedSessions(fingerprint, label, key, id)) {
867
+ if (this.hostConnected(old) || old.updatedAt >= bootedAt) {
868
+ continue;
869
+ }
870
+ this.store.updateSession(old.id, { state: 'ended', stateAt: ts });
871
+ if (!this.sharesHandle(old)) {
872
+ this.store.deleteNativeTransport(old.handle);
873
+ }
874
+ }
875
+ }
720
876
  // The session running under this exact host process, if one announced
721
877
  // itself. With create, a missing session is made on the spot (an MCP
722
- // server whose hooks never ran still gets an identity).
723
- sessionForHost(host, create) {
724
- const row = this.store.sessionByHost(host.hostPid, host.hostStart);
878
+ // server whose hooks never ran still gets an identity). With match, the CLI
879
+ // id and the folder of the event it is a lookup for, so that a lookup adopts
880
+ // no row that the event itself would not.
881
+ sessionForHost(host, create, match) {
882
+ const row = this.rowAt(host, match?.cliSessionId ?? null, match?.cwd);
725
883
  if (row !== null || create === undefined) {
726
884
  return row;
727
885
  }
@@ -729,12 +887,13 @@ export class MurmurCore {
729
887
  }
730
888
  // The nearest live session whose host is one of these ancestors (nearest
731
889
  // first), or null: a shell command run by an agent speaks as its session.
732
- sessionForAncestors(ancestors) {
890
+ sessionForAncestors(ancestors, machine) {
891
+ const at = this.machineKey({ ...(machine !== undefined ? { machine } : {}) });
733
892
  const candidates = this.store
734
893
  .listSessions()
735
- .filter((row) => row.state !== 'ended' && ancestors.includes(row.hostPid));
894
+ .filter((row) => row.state !== 'ended' && row.hostMachine === at && ancestors.includes(row.hostPid));
736
895
  const table = this.safeProcTable(candidates.map((row) => row.hostPid));
737
- const live = candidates.filter((row) => isAlive(table, row.hostPid, row.hostStart));
896
+ const live = candidates.filter((row) => this.alive(table, row));
738
897
  for (const pid of ancestors) {
739
898
  const match = live.find((row) => row.hostPid === pid);
740
899
  if (match !== undefined) {
@@ -763,12 +922,19 @@ export class MurmurCore {
763
922
  if (!this.claimable(handle, row.id)) {
764
923
  throw new MurmurError('bad_request', 'handle ' + handle + ' is taken by a live session or the owner');
765
924
  }
766
- if (this.store.getPeer(handle) === null) {
925
+ // A handle can still be held by several sessions at once (a client that
926
+ // sends no machine id looks dead to this broker when it runs elsewhere).
927
+ // Renaming the identity would carry them all along and rewrite their
928
+ // history, so while another live session holds the old handle, only this
929
+ // session moves.
930
+ const others = this.store.sessionsForHandle(row.handle).filter((r) => r.id !== row.id);
931
+ const shared = this.liveHolders(row.handle, row.id).length > 0;
932
+ if (!shared && this.store.getPeer(handle) === null) {
767
933
  this.store.renamePeer(row.handle, handle);
768
934
  return handle;
769
935
  }
770
- const others = this.store.sessionsForHandle(row.handle).filter((r) => r.id !== row.id);
771
- this.store.reassignSession(row.id, row.handle, handle);
936
+ this.ensurePeer(handle);
937
+ this.store.reassignSession(row.id, row.handle, handle, !shared);
772
938
  if (others.length === 0 && !this.store.peerHasHistory(row.handle)) {
773
939
  this.store.deletePeer(row.handle);
774
940
  }
@@ -791,9 +957,28 @@ export class MurmurCore {
791
957
  }
792
958
  return removed;
793
959
  }
960
+ // True when a session that has not ended holds the handle, whether or not
961
+ // this machine can see its process.
962
+ holdsHandle(handle) {
963
+ this.ownMachine();
964
+ return this.liveHolders(handle, null).length > 0;
965
+ }
966
+ // True while another live session holds this session's handle:
967
+ // the handle's one native transport is theirs too, so neither may replace
968
+ // or delete it.
969
+ sharesHandle(row) {
970
+ return this.liveHolders(row.handle, row.id).length > 0;
971
+ }
972
+ // The live sessions holding the handle, other than exceptId.
973
+ liveHolders(handle, exceptId) {
974
+ const rows = this.store.sessionsForHandle(handle).filter((r) => r.id !== exceptId && r.state !== 'ended');
975
+ const table = this.safeProcTable(rows.map((r) => r.hostPid));
976
+ return rows.filter((r) => this.alive(table, r));
977
+ }
794
978
  // A handle can be claimed when it is valid, not the owner's, and no live
795
979
  // session other than exceptId holds it.
796
980
  claimable(handle, exceptId) {
981
+ this.ownMachine();
797
982
  if (!HANDLE_RE.test(handle)) {
798
983
  return false;
799
984
  }
@@ -803,7 +988,7 @@ export class MurmurCore {
803
988
  }
804
989
  const holders = this.store.sessionsForHandle(handle).filter((r) => r.id !== exceptId && r.state !== 'ended');
805
990
  const table = this.safeProcTable(holders.map((r) => r.hostPid));
806
- return !holders.some((r) => isAlive(table, r.hostPid, r.hostStart));
991
+ return !holders.some((r) => this.alive(table, r));
807
992
  }
808
993
  // <client>-<cwd basename>, then -2, -3, ... until no live session holds
809
994
  // it. A handle whose sessions are all gone is reused, so a restarted
@@ -817,6 +1002,21 @@ export class MurmurCore {
817
1002
  }
818
1003
  return handle;
819
1004
  }
1005
+ // A session of this machine is alive while its process is, as the process
1006
+ // table shows it. This broker cannot see the process of another machine's
1007
+ // session, so that one is alive while a connection of its host is open or for
1008
+ // a lease after its last event. Callers pass sessions that have not ended.
1009
+ alive(table, row) {
1010
+ if (this.hostConnected(row)) {
1011
+ return true;
1012
+ }
1013
+ if (row.hostMachine === null) {
1014
+ return isAlive(table, row.hostPid, row.hostStart);
1015
+ }
1016
+ // Right after this broker starts no connection has come back yet, so every
1017
+ // session of another machine counts as alive until they have had time to.
1018
+ return this.nowMs() - row.updatedAt <= REMOTE_LEASE_MS || this.nowMs() - this.startedAt <= STARTUP_GRACE_MS;
1019
+ }
820
1020
  safeProcTable(pids) {
821
1021
  try {
822
1022
  return this.procTable(pids);
package/dist/hooks.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
2
2
  import { connectBroker } from './client.js';
3
3
  import { getPaths, readToken } from './config.js';
4
+ import { readUptime, thisMachineRef } from './machine.js';
4
5
  import { currentHost } from './proc.js';
5
6
  export const HOOK_CLIENTS = ['claude', 'codex', 'gemini', 'zcode'];
6
7
  // Hard cap on the broker interaction. A hook runs inline inside a session
@@ -32,7 +33,7 @@ export async function runHook(event, stdinText, env, opts) {
32
33
  conn.close();
33
34
  }, HOOK_DEADLINE_MS);
34
35
  try {
35
- const { handle } = await conn.request(sessionMessage(event, client, input, host, env));
36
+ const { handle } = await conn.request(sessionMessage(event, client, input, host, env, opts?.machine ?? thisMachineRef(), opts?.uptime ?? readUptime()));
36
37
  if (event === 'session-end') {
37
38
  return { exitCode: 0, stdout: '' };
38
39
  }
@@ -55,13 +56,13 @@ export async function runHook(event, stdinText, env, opts) {
55
56
  return { exitCode: 0, stdout: '' };
56
57
  }
57
58
  }
58
- function sessionMessage(event, client, input, host, env) {
59
+ function sessionMessage(event, client, input, host, env, machine, uptime) {
59
60
  const msg = {
60
61
  type: 'session',
61
62
  event,
62
63
  client,
63
64
  cliSessionId: input.sessionId,
64
- host: { hostPid: host.hostPid, hostStart: host.hostStart },
65
+ host: { hostPid: host.hostPid, hostStart: host.hostStart, ...machine, ...(machine.machine !== undefined && uptime !== undefined ? { machineUptime: uptime } : {}) },
65
66
  };
66
67
  // zcode hands hooks a synthetic transcript it deletes afterwards, so it
67
68
  // cannot serve as delivery proof.
@@ -0,0 +1,205 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync, readlinkSync } from 'node:fs';
4
+ import { hostname } from 'node:os';
5
+ // A host reference is a pid and a start time, which only mean something on the
6
+ // machine that ran the process. `machine` names that machine and rides along
7
+ // with every host reference: the boot id, a uuid per machine and boot (a
8
+ // rebooted machine or a clone is another machine). `machineName`, the host
9
+ // name, is only a label: it is never compared for sameness (a host name can
10
+ // change while a machine runs), and only tells the broker that a machine it
11
+ // knew rebooted. A client that cannot read a boot id sends neither field and
12
+ // is judged as one of the broker's own machine, as before this existed.
13
+ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
14
+ // A machine from the wire: a boot id, optionally followed by `:` and the number
15
+ // of its pid namespace (Linux).
16
+ const MACHINE_FULL = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(:[0-9]{1,20})?$/i;
17
+ // What a machine field may hold where it enters the broker.
18
+ const FIELD = /^[^\u0000-\u001f\u007f]{1,255}$/;
19
+ // The boot uuid inside Linux's /proc/sys/kernel/random/boot_id or macOS's
20
+ // `sysctl -n kern.bootsessionuuid` (also with its `name: ` prefix), lower
21
+ // case; empty when the text holds none.
22
+ export function parseBootId(text) {
23
+ return UUID.exec(text)?.[0].toLowerCase() ?? '';
24
+ }
25
+ // Linux reads /proc, macOS asks sysctl by absolute path with a one second
26
+ // limit (the one thing to confirm on a Mac: `sysctl -n kern.bootsessionuuid`
27
+ // prints a uuid). Anything else, or a failure, has no boot id.
28
+ export const SYSCTL_OPTIONS = { encoding: 'utf8', timeout: 1000, stdio: ['ignore', 'pipe', 'ignore'] };
29
+ const defaultRead = (path) => readFileSync(path, 'utf8');
30
+ const defaultRun = (cmd, args) => execFileSync(cmd, args, SYSCTL_OPTIONS);
31
+ export function readBootId(platform = process.platform, readFile = defaultRead, run = defaultRun) {
32
+ try {
33
+ if (platform === 'linux') {
34
+ return parseBootId(readFile('/proc/sys/kernel/random/boot_id'));
35
+ }
36
+ if (platform === 'darwin') {
37
+ return parseBootId(run('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid']));
38
+ }
39
+ }
40
+ catch {
41
+ // No boot id.
42
+ }
43
+ return '';
44
+ }
45
+ // The machine id: the boot id, or '' when there is none. The host name is not
46
+ // part of it (it is only the label of machineRef), so it is not consulted.
47
+ export function machineId(_name = hostname(), bootId = readBootId()) {
48
+ return bootId;
49
+ }
50
+ // Seconds since this machine booted: /proc/uptime on Linux, the boot time that
51
+ // `sysctl -n kern.boottime` prints (`{ sec = 1700000000, usec = 0 } ...`) on
52
+ // macOS; undefined when it cannot be read. Sent with a session event so the
53
+ // broker can tell that a machine booted after the last time it heard from the
54
+ // old sessions it holds under the same host name (src/core.ts).
55
+ export function readUptime(platform = process.platform, readFile = defaultRead, run = defaultRun, nowMs = Date.now()) {
56
+ try {
57
+ if (platform === 'linux') {
58
+ const seconds = Number.parseFloat(readFile('/proc/uptime'));
59
+ return Number.isFinite(seconds) && seconds >= 0 ? Math.floor(seconds) : undefined;
60
+ }
61
+ if (platform === 'darwin') {
62
+ const booted = /sec\s*=\s*(\d+)/.exec(run('/usr/sbin/sysctl', ['-n', 'kern.boottime']))?.[1];
63
+ return booted === undefined ? undefined : Math.max(0, Math.floor(nowMs / 1000) - Number(booted));
64
+ }
65
+ }
66
+ catch {
67
+ // No uptime.
68
+ }
69
+ return undefined;
70
+ }
71
+ // A machine uptime from the wire: finite seconds, 0 to 10 years.
72
+ export function validUptime(value) {
73
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 315_360_000 ? value : undefined;
74
+ }
75
+ // The number inside `/proc/self/ns/pid` (`pid:[4026531836]`): the pid namespace
76
+ // of this process, empty when there is none to read (not Linux, or no access).
77
+ // A process table is only one machine's if its processes share this number.
78
+ export function readPidNamespace(platform = process.platform, readLink = (path) => readlinkSync(path)) {
79
+ try {
80
+ return platform === 'linux' ? (/\[(\d+)\]/.exec(readLink('/proc/self/ns/pid'))?.[1] ?? '') : '';
81
+ }
82
+ catch {
83
+ return '';
84
+ }
85
+ }
86
+ // What tells one machine from a lookalike across reboots: a hash of the id the
87
+ // system keeps for itself (Linux `/etc/machine-id`, else
88
+ // `/var/lib/dbus/machine-id`; macOS the IOPlatformUUID `ioreg` prints). The raw
89
+ // id never leaves the machine: the value is the first 32 hex characters of
90
+ // sha256("murmur-machine:" + id). Unreadable or empty: undefined, and the
91
+ // broker then never reads a boot id change as a reboot.
92
+ // The id systemd keeps in /etc/machine-id: 32 lower case hex characters. A
93
+ // placeholder (`uninitialized`) or one baked into an image names no machine.
94
+ const SYSTEM_ID = /^[0-9a-f]{32}$/;
95
+ const IOREG_UUID = /"IOPlatformUUID"\s*=\s*"([0-9a-f-]{36})"/i;
96
+ export function readFingerprint(platform = process.platform, readFile = defaultRead, run = defaultRun) {
97
+ const attempt = (read) => {
98
+ try {
99
+ return read();
100
+ }
101
+ catch {
102
+ return '';
103
+ }
104
+ };
105
+ let raw = '';
106
+ if (platform === 'linux') {
107
+ raw = attempt(() => readFile('/etc/machine-id').trim());
108
+ raw = SYSTEM_ID.test(raw) ? raw : attempt(() => readFile('/var/lib/dbus/machine-id').trim());
109
+ raw = SYSTEM_ID.test(raw) ? raw : '';
110
+ }
111
+ else if (platform === 'darwin') {
112
+ raw = attempt(() => IOREG_UUID.exec(run('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']))?.[1] ?? '');
113
+ }
114
+ return raw === '' ? undefined : createHash('sha256').update('murmur-machine:' + raw).digest('hex').slice(0, 32);
115
+ }
116
+ // What a client puts next to its host reference: the boot id and the host
117
+ // name, or nothing when there is no boot id.
118
+ export function machineRef(bootId = readBootId(), name = hostname(), pidNamespace = readPidNamespace(), fingerprint = readFingerprint) {
119
+ if (bootId === '') {
120
+ return {};
121
+ }
122
+ const read = fingerprint();
123
+ return {
124
+ machine: pidNamespace === '' ? bootId : bootId + ':' + pidNamespace,
125
+ machineName: name,
126
+ ...(read != null ? { machineFingerprint: read } : {}),
127
+ };
128
+ }
129
+ // A read that happens once: a later failing read cannot change what a process
130
+ // said before.
131
+ export function once(read) {
132
+ let value;
133
+ return () => {
134
+ value ??= { v: read() };
135
+ return value.v;
136
+ };
137
+ }
138
+ // A read kept once it has worked: a failed read is tried again, at most once
139
+ // per `retryMs`, so a boot id that could not be read at start (a sysctl that
140
+ // timed out) is picked up later, while a good value is never replaced.
141
+ export function onceOk(read, ok, retryMs, now = Date.now) {
142
+ let good;
143
+ let last;
144
+ return () => {
145
+ if (good !== undefined) {
146
+ return good.v;
147
+ }
148
+ if (last === undefined || now() - last.at >= retryMs) {
149
+ const v = read();
150
+ last = { v, at: now() };
151
+ if (ok(v)) {
152
+ good = { v };
153
+ }
154
+ }
155
+ return last.v;
156
+ };
157
+ }
158
+ // This machine's reference: read once it has worked, tried again every minute
159
+ // while it has not.
160
+ export function machineReader(read = machineRef, now = Date.now) {
161
+ return onceOk(read, (ref) => ref.machine !== undefined, 60_000, now);
162
+ }
163
+ export const thisMachineRef = machineReader();
164
+ // The machine of a reference (boot id, with the pid namespace on Linux), or ''
165
+ // when it has none.
166
+ export function machineOf(ref) {
167
+ return ref.machine ?? '';
168
+ }
169
+ // This machine's id, or '' when it has none.
170
+ export function thisMachine() {
171
+ return machineOf(thisMachineRef());
172
+ }
173
+ // A machine from the wire: a uuid, lower case, optionally followed by `:` and
174
+ // 1 to 20 digits; undefined for anything else, so one machine is one value
175
+ // however a client writes it.
176
+ export function validBootId(value) {
177
+ return typeof value === 'string' && MACHINE_FULL.test(value) ? value.toLowerCase() : undefined;
178
+ }
179
+ // A fingerprint from the wire: 32 lower case hex characters, else undefined.
180
+ export function validFingerprint(value) {
181
+ return typeof value === 'string' && /^[0-9a-f]{32}$/.test(value) ? value : undefined;
182
+ }
183
+ // What a session event may say about its machine, from the wire: the machine
184
+ // (a boot id, lower case), and, next to it only, the host name as a label, the
185
+ // uptime and the fingerprint. Anything that is not of its shape reads as absent.
186
+ export function parseWireMachine(rec) {
187
+ const machine = validBootId(rec.machine);
188
+ if (machine === undefined) {
189
+ return {};
190
+ }
191
+ const machineName = validField(rec.machineName);
192
+ const machineUptime = validUptime(rec.machineUptime);
193
+ const machineFingerprint = validFingerprint(rec.machineFingerprint);
194
+ return {
195
+ machine,
196
+ ...(machineName !== undefined ? { machineName } : {}),
197
+ ...(machineUptime !== undefined ? { machineUptime } : {}),
198
+ ...(machineFingerprint !== undefined ? { machineFingerprint } : {}),
199
+ };
200
+ }
201
+ // A machine field from the wire: undefined unless it is 1 to 255 printable
202
+ // characters without a line break.
203
+ export function validField(value) {
204
+ return typeof value === 'string' && FIELD.test(value) ? value : undefined;
205
+ }