bot / scripts / floor-observer.mjs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Read-only headless observer for a rooms-app room — by default bursa's
// public market room ("the floor").
//
// NEVER APPENDS. The guarantee, spelled out: a throwaway identity minted in
// memory (Identity.newSeed — no seed file is read or written), NO hello sent
// on peerReady, no publish, no knock, no mailbox deposit — this script holds
// no reference to any append path and only ever calls loadTail and listens.
// It is safe to point at any production room: on the wire it is
// indistinguishable from a member who joined and said nothing.
//
// It joins via the same boot ladder the bot's stack-B arms use (rooms-kit's
// dist stack, out of stack-b/ — src/bot/bursa.cljs), replays the full history,
// then reports
// peers, hellos and entries for an observation window.
//
// Usage (from the repo root; node >= 22):
//
//   node scripts/floor-observer.mjs [secret] [app-salt] [origin] [window-sec]
//
//   defaults: the bursa floor —
//     secret     bursa.lib.floor/FLOOR-SECRET
//     app-salt   "bursa.ardegazu.ro/v1"
//     origin     "https://bursa.ardegazu.ro"
//     window-sec 120
//
// State goes to a throwaway directory under the OS tmpdir and is never reused.
import path from "node:path";
import fs from "node:fs";
import os from "node:os";

// rooms-kit lives in stack-b's npm root (the libp2p v2 tree — see deps.edn's
// classpath law), and this file sits outside both roots, so a bare specifier
// would not resolve. Name the package directory and let its OWN exports map
// pick the entry files, exactly as `import "ardegazu-rooms-kit/internals"`
// would from inside stack-b.
const KIT = new URL("../stack-b/node_modules/ardegazu-rooms-kit/", import.meta.url);
const EXPORTS = JSON.parse(fs.readFileSync(new URL("package.json", KIT), "utf8")).exports;
const kit = (sub) => import(new URL(EXPORTS[sub].import, KIT).href);

const { installOrigin, installBrowserGlobals, Identity } = await kit(".");
const { Net, newSessionKey, RoomCrypto, RoomLog, openHelia, resolveRelayConfig, IceConfig } =
  await kit("./internals");

// the floor's secret is public by design (bursa.lib.floor commits it — the
// floor is the lobby's default room, not a capability)
const SECRET = process.argv[2] || "n_UlVtmm1SYw_4xcHq9SuHNclDDM1VsdxgHyE-oIHNc";
const SALT = process.argv[3] || "bursa.ardegazu.ro/v1";
const ORIGIN = process.argv[4] || "https://bursa.ardegazu.ro";
const WINDOW_MS = (Number(process.argv[5]) || 120) * 1000;
const BOOT_TIMEOUT_MS = 180000;

// the same production defaults the bot's arms resolve against
const RELAY_DEFAULTS = {
  relayMultiaddr:
    "/dns4/signal.ardegazu.ro/tcp/443/tls/ws/p2p/12D3KooWQzZvygPwd2F4JAqqf6tfBSJ29YtjzzftUyJ37RLCG5WT",
  turnCredsUrl: "https://signal.ardegazu.ro/turn-credentials",
  discoveryTopic: "_peer-discovery._p2p._pubsub",
};

const DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "floor-obs-"));

const t0 = Date.now();
const log = (...a) =>
  console.log(new Date().toISOString(), "+" + ((Date.now() - t0) / 1000).toFixed(1) + "s", ...a);

let phase = "start";
const bootGuard = setTimeout(() => {
  log("FATAL: boot timed out; last phase =", phase);
  process.exit(2);
}, BOOT_TIMEOUT_MS);

process.on("unhandledRejection", (e) => log("unhandledRejection:", e && (e.stack || e.message || e)));
process.on("uncaughtException", (e) => log("uncaughtException:", e && (e.stack || e.message || e)));

// ---- observation state ----
const entries = []; // {t, ts, hash, live}
let live = false; // true after loadTail resolves
const peersSeen = new Map(); // peer -> {states:[], ready:false, gone:false, hello:null}
const hellos = [];
let replayedCount = null;

const peerRec = (p) => {
  const k = String(p);
  if (!peersSeen.has(k)) peersSeen.set(k, { states: [], ready: false, gone: false, hello: null });
  return peersSeen.get(k);
};

const onEntry = (e) => {
  try {
    const op = e && e.op;
    const hash = e && e.hash;
    const rec = {
      t: (op && op.t) ?? "?",
      ts: op && typeof op.ts === "number" ? op.ts : null,
      hash: typeof hash === "string" ? hash.slice(0, 10) : "?",
      live,
    };
    entries.push(rec);
    if (live) {
      log("LIVE entry:", "t=" + rec.t, "ts=" + (rec.ts ? new Date(rec.ts).toISOString() : "n/a"), "hash=" + rec.hash);
    }
  } catch (err) {
    log("onEntry handler error:", err);
  }
};

try {
  phase = "installOrigin";
  installOrigin(ORIGIN);
  phase = "installBrowserGlobals";
  installBrowserGlobals(path.join(DATA_DIR, "kv.json"));

  phase = "identity";
  const seed = Identity.newSeed(); // throwaway, in-memory only
  const identity = await Identity.fromSeed(seed);
  log("throwaway identity pub:", identity.publicKeyB64.slice(0, 12) + "…");

  phase = "newSessionKey";
  const session = await newSessionKey();
  phase = "RoomCrypto.create";
  const roomCrypto = await RoomCrypto.create(SECRET, SALT, session.peerId);
  log("roomId:", roomCrypto.roomId);

  phase = "resolveRelayConfig";
  const cfg = await resolveRelayConfig(RELAY_DEFAULTS);
  log("relay cfg:", JSON.stringify({
    relayMultiaddr: cfg.relayMultiaddr,
    turnCredsUrl: cfg.turnCredsUrl,
    discoveryTopic: cfg.discoveryTopic,
    mailbox: cfg.mailbox ? "advertised" : "absent",
  }));
  const ice = new IceConfig(cfg.turnCredsUrl, false);

  phase = "Net.create";
  const net = await Net.create({
    privateKey: session.privateKey,
    crypto: roomCrypto,
    ice,
    wsOrigin: ORIGIN,
    relayMultiaddr: cfg.relayMultiaddr,
    discoveryTopic: cfg.discoveryTopic,
    myName: () => "observer",
    events: {
      peerState: (peer, state, name) => {
        peerRec(peer).states.push(state);
        log("peerState:", String(peer).slice(-8), "state=" + state, name ? "name=" + name : "");
      },
      peerReady: (peer) => {
        peerRec(peer).ready = true;
        log("peerReady:", String(peer).slice(-8), "(channel OPEN; sending nothing — observer)");
      },
      peerGone: (peer) => {
        peerRec(peer).gone = true;
        log("peerGone:", String(peer).slice(-8));
      },
      message: (from, payload) => {
        const kind = payload && payload.kind;
        const name = payload && payload.name;
        if (kind === "hello") {
          peerRec(from).hello = { name, idPub: payload.idPub && payload.idPub.slice(0, 12) };
          hellos.push({ from: String(from).slice(-8), name, idPub: payload.idPub });
        }
        log("message:", String(from).slice(-8), "kind=" + kind, name ? "name=" + name : "");
      },
      binary: (from, data) => log("binary:", String(from).slice(-8), "bytes=" + (data && data.length)),
      status: (up) => log("net status:", up ? "UP" : "DOWN"),
    },
  });
  log("Net up. self peerId:", session.peerId);

  phase = "openHelia";
  const helia = await openHelia(net.libp2p, {
    blocks: path.join(DATA_DIR, "blocks"),
    data: path.join(DATA_DIR, "data"),
  });

  phase = "RoomLog.open";
  const rlog = await RoomLog.open(helia, roomCrypto, identity, {
    onEntry,
    onError: () => {},
    directory: path.join(DATA_DIR, "orbitdb"),
  });

  phase = "loadTail";
  const restored = await rlog.loadTail(-1);
  replayedCount = restored;
  live = true;
  clearTimeout(bootGuard);
  log("loadTail(-1) resolved — replayed", restored, "entries; observing for", WINDOW_MS / 1000, "s");

  setTimeout(() => {
    log("---- OBSERVATION WINDOW OVER ----");
    const liveEntries = entries.filter((e) => e.live);
    const byType = {};
    for (const e of entries) byType[e.t] = (byType[e.t] || 0) + 1;
    const tss = entries.map((e) => e.ts).filter((x) => x != null);
    log("REPORT replayedByLoadTail =", replayedCount);
    log("REPORT totalEntriesSeen =", entries.length, " liveDuringWindow =", liveEntries.length);
    log("REPORT byType =", JSON.stringify(byType));
    log("REPORT newestOpTs =", tss.length ? new Date(Math.max(...tss)).toISOString() : "none");
    log("REPORT oldestOpTs =", tss.length ? new Date(Math.min(...tss)).toISOString() : "none");
    log("REPORT distinctPeers =", peersSeen.size,
        " ready =", [...peersSeen.values()].filter((p) => p.ready).length,
        " hellos =", hellos.length);
    log("REPORT hellos:", JSON.stringify(hellos.map((h) => ({ from: h.from, name: h.name, idPub: h.idPub && h.idPub.slice(0, 12) }))));
    log("REPORT last 15 entries:", JSON.stringify(entries.slice(-15).map((e) => ({ t: e.t, ts: e.ts && new Date(e.ts).toISOString(), h: e.hash, live: e.live }))));
    process.exit(0);
  }, WINDOW_MS);
} catch (err) {
  clearTimeout(bootGuard);
  log("FATAL at phase", phase, ":", err && (err.stack || err.message || err));
  process.exit(1);
}

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/bot.git