iosignal 9.13.0 → 9.19.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.
@@ -9,14 +9,18 @@ import require$$7 from 'url';
9
9
  import require$$0 from 'zlib';
10
10
  import require$$0$1 from 'buffer';
11
11
  import require$$2 from 'util';
12
- import { performance } from 'node:perf_hooks';
12
+ import { performance, monitorEventLoopDelay } from 'node:perf_hooks';
13
13
  import { isIPv6 as isIPv6$1, isIPv4 as isIPv4$1, isIP } from 'node:net';
14
14
  import { networkInterfaces } from 'os';
15
- import fs, { readFileSync } from 'fs';
15
+ import fs, { readFileSync as readFileSync$1 } from 'fs';
16
16
  import { memoryUsage } from 'process';
17
+ import { readFile } from 'node:fs/promises';
18
+ import { timingSafeEqual, createHash } from 'node:crypto';
19
+ import { readFileSync } from 'node:fs';
20
+ import { totalmem } from 'node:os';
17
21
  import path from 'path';
18
22
 
19
- var version$1 = "9.13.0";
23
+ var version$1 = "9.19.0";
20
24
  var pkg = {
21
25
  version: version$1};
22
26
 
@@ -442,6 +446,7 @@ for (let c in ENC_MODE) { ENC_MODE[ENC_MODE[c]] = c; }
442
446
  * @property {number} TAG_LEN2
443
447
  * @property {number} CONNECTION_CHECKER_PERIOD
444
448
  * @property {number} CLIENT_PING_PERIOD
449
+ * @property {number} SERVER_HELLO_TIMEOUT
445
450
  * @property {number} PROMISE_TIMEOUT
446
451
  * @property {number} DID
447
452
  * @property {number} CID
@@ -451,6 +456,9 @@ const SIZE_LIMIT = {
451
456
  TAG_LEN2: 65535,
452
457
  CONNECTION_CHECKER_PERIOD: 3000,
453
458
  CLIENT_PING_PERIOD: 40000,
459
+ // From starting a connection to the server's hello (SERVER_TIME_NONCE). A connection that hangs
460
+ // longer is closed, so the client reconnects to its own URL (after a redirect: the original one).
461
+ SERVER_HELLO_TIMEOUT: 15000,
454
462
  PROMISE_TIMEOUT: 5000,
455
463
  DID: 8,
456
464
  CID: 12
@@ -959,6 +967,7 @@ class IOCore extends EventEmitter {
959
967
  */
960
968
  close() {
961
969
  // console.log('####### IOCOre.js close() called')
970
+ this.clearHelloTimer();
962
971
  // If auto-reconnect is disabled, we must stop the keep-alive timer.
963
972
  if (this.autoReconnect === false) {
964
973
  clearInterval(this.connectionCheckerIntervalID);
@@ -1053,6 +1062,30 @@ class IOCore extends EventEmitter {
1053
1062
  this.stateChange('redirecting','redirecting');
1054
1063
  this.close();
1055
1064
  this.createConnection(url2);
1065
+ this.armHelloTimer();
1066
+ }
1067
+
1068
+ /**
1069
+ * Closes a connection that has not got the server's hello in SIZE_LIMIT.SERVER_HELLO_TIMEOUT
1070
+ * (a server that cannot be reached, or a connection that opens but never answers). With
1071
+ * autoReconnect the client then reconnects to this.url, so a failed redirect falls back to the
1072
+ * original server, as the Arduino library does.
1073
+ */
1074
+ armHelloTimer() {
1075
+ this.clearHelloTimer();
1076
+ if (this._closed || !this.socket) return;
1077
+ const socket = this.socket;
1078
+ this.helloTimerID = setTimeout(() => {
1079
+ this.helloTimerID = null;
1080
+ if (this.socket !== socket) return;
1081
+ this.emit('error', new Error('no reply from the server in ' + SIZE_LIMIT.SERVER_HELLO_TIMEOUT / 1000 + ' s'));
1082
+ this.close();
1083
+ }, SIZE_LIMIT.SERVER_HELLO_TIMEOUT);
1084
+ }
1085
+
1086
+ clearHelloTimer() {
1087
+ if (this.helloTimerID) clearTimeout(this.helloTimerID);
1088
+ this.helloTimerID = null;
1056
1089
  }
1057
1090
 
1058
1091
  /**
@@ -1078,6 +1111,7 @@ class IOCore extends EventEmitter {
1078
1111
  // The actual connection is created here.
1079
1112
  this.createConnection(this.url);
1080
1113
  if (this._closed) return; // A connecting listener may have stopped the client.
1114
+ this.armHelloTimer();
1081
1115
 
1082
1116
  // Ensure the keep-alive timer is running.
1083
1117
  if (!this.connectionCheckerIntervalID) {
@@ -1272,6 +1306,7 @@ class IOCore extends EventEmitter {
1272
1306
  break;
1273
1307
 
1274
1308
  case it.BohoMsg.SERVER_TIME_NONCE: // SERVER_READY
1309
+ this.clearHelloTimer();
1275
1310
  buffer.copy(this.serverTimeNonce);
1276
1311
  if (!this.stateChange('server_ready', 'server_ready')) break;
1277
1312
  if (this.useAuth) {
@@ -2155,8 +2190,15 @@ class IOCongSocket extends IOCore {
2155
2190
 
2156
2191
  createConnection(url) {
2157
2192
  // TCP Socket
2158
- let urlObj = new URL(url);
2159
- if (urlObj.protocol != "cong:") {
2193
+ // 'host:port', 'ip:port' or 'cong://host:port'. 'ip:port' alone is not a URL (a scheme cannot
2194
+ // start with a digit), and 'host:port' parses with 'host:' as its scheme.
2195
+ let urlObj;
2196
+ try {
2197
+ urlObj = new URL(url);
2198
+ } catch {
2199
+ urlObj = null;
2200
+ }
2201
+ if (urlObj?.protocol != "cong:") {
2160
2202
  urlObj = new URL('cong://' + url);
2161
2203
  }
2162
2204
  // URL keeps the brackets of an IPv6 literal ('[::1]'); net expects the bare address.
@@ -8855,6 +8897,23 @@ class Host extends require$$0$3 {
8855
8897
  this.closed = false;
8856
8898
  /** @type {Map<string, Readonly<object>>} cid -> from, connections that sent to this host */
8857
8899
  this._participants = new Map();
8900
+ /** cid -> { inputs, firstAt, lastAt }: activity of each participant, for the dashboard */
8901
+ this._activity = new Map();
8902
+ // Cumulative since the host opened; readers compute rates from deltas (see Dashboard).
8903
+ this.counters = {
8904
+ inbound: 0, // inputs handed to 'message'
8905
+ rejected: 0, // inputs to an inbound tag that were not handed over (E2E, unreadable payload)
8906
+ denied: 0, // client messages to a tag this host owns, dropped
8907
+ published: 0, delivered: 0, // publish() calls and the connections they reached
8908
+ sent: 0, // to() messages sent
8909
+ joins: 0, leaves: 0, errors: 0,
8910
+ handlerMs: 0, // time spent in 'message' and 'leave' handlers
8911
+ };
8912
+ this.handlerMaxMs = 0;
8913
+ this.reported = {}; // last host.report() values
8914
+ this._journal = []; // recent notable events (join, leave, denied, error), oldest first
8915
+ this._journalSeq = 0;
8916
+ this._loops = new Set();
8858
8917
 
8859
8918
  manager.hosts.add(this, [...inbound, ...own]);
8860
8919
  // Values a client retained on these tags before the host claimed them are not the host's.
@@ -8872,6 +8931,7 @@ class Host extends require$$0$3 {
8872
8931
 
8873
8932
  /** Stop tracking a participant; no 'leave' is emitted for it (until it sends again). */
8874
8933
  forget(cid) {
8934
+ this._activity.delete(cid);
8875
8935
  return this._participants.delete(cid)
8876
8936
  }
8877
8937
 
@@ -8887,7 +8947,10 @@ class Host extends require$$0$3 {
8887
8947
  throw new Error(`host ${this.name} does not own channel tag ${tag}`)
8888
8948
  }
8889
8949
  const message = getSignalPack(tag, ...args);
8890
- return this.manager.hostPublish(this, this.manager.CHANNEL_PREFIX + tag, message)
8950
+ const n = this.manager.hostPublish(this, this.manager.CHANNEL_PREFIX + tag, message);
8951
+ this.counters.published++;
8952
+ this.counters.delivered += n;
8953
+ return n
8891
8954
  }
8892
8955
 
8893
8956
  /**
@@ -8904,17 +8967,100 @@ class Host extends require$$0$3 {
8904
8967
  if (!remote || remote._closing) return false
8905
8968
  const skipped = remote.peerRxLimitSkipped;
8906
8969
  remote.send_enc_mode(message);
8907
- return remote.peerRxLimitSkipped === skipped
8970
+ if (remote.peerRxLimitSkipped !== skipped) return false
8971
+ this.counters.sent++;
8972
+ return true
8973
+ }
8974
+
8975
+ /**
8976
+ * Values to show on the server dashboard ("game" panel), e.g. { round: 3, players: 8 }.
8977
+ * Merged into the last report; a key set to null is removed. Numbers, short strings and booleans,
8978
+ * at most 20 keys.
8979
+ */
8980
+ report(values) {
8981
+ if (values === null || typeof values !== 'object') throw new TypeError('report() takes an object')
8982
+ for (const [key, value] of Object.entries(values)) {
8983
+ if (value === null || value === undefined) { delete this.reported[key]; continue }
8984
+ if (!['number', 'string', 'boolean'].includes(typeof value)) throw new TypeError(`report value ${key} must be a number, string or boolean`)
8985
+ if (!(key in this.reported) && Object.keys(this.reported).length >= 20) continue
8986
+ this.reported[String(key).slice(0, 32)] = typeof value === 'string' ? value.slice(0, 64) : value;
8987
+ }
8988
+ return this
8989
+ }
8990
+
8991
+ /**
8992
+ * Run fn(now) every intervalMs, like setInterval, and measure it for the dashboard: the gap between
8993
+ * ticks and how long each tick took. A throwing tick is reported as an 'error' and the loop goes on.
8994
+ * Returns a stop function; close() stops every loop.
8995
+ */
8996
+ loop(intervalMs, fn) {
8997
+ this._open();
8998
+ if (!(Number.isFinite(intervalMs) && intervalMs >= 1)) throw new RangeError('loop interval must be at least 1 ms')
8999
+ if (typeof fn !== 'function') throw new TypeError('loop needs a function')
9000
+ const stats = { intervalMs, ticks: 0, gaps: [], steps: [], last: 0 };
9001
+ const timer = setInterval(() => {
9002
+ const t0 = performance.now();
9003
+ if (stats.last) { stats.gaps.push(t0 - stats.last); if (stats.gaps.length > 200) stats.gaps.shift(); }
9004
+ stats.last = t0;
9005
+ try { fn(Date.now()); } catch (error) { this._failed(error); }
9006
+ stats.steps.push(performance.now() - t0); if (stats.steps.length > 200) stats.steps.shift();
9007
+ stats.ticks++;
9008
+ }, intervalMs);
9009
+ const entry = { timer, stats };
9010
+ this._loops.add(entry);
9011
+ return () => { clearInterval(timer); this._loops.delete(entry); }
9012
+ }
9013
+
9014
+ /** Timing of the loops started with loop(): target, ticks, gap p50/p99 and step average/max (ms). */
9015
+ loopStats() {
9016
+ const pct = (a, p) => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p / 100 * s.length))] };
9017
+ return [...this._loops].map(({ stats: s }) => ({
9018
+ intervalMs: s.intervalMs, ticks: s.ticks,
9019
+ gapP50: pct(s.gaps, 50), gapP99: pct(s.gaps, 99), gapMax: s.gaps.length ? Math.max(...s.gaps) : 0,
9020
+ stepAvg: s.steps.length ? s.steps.reduce((a, b) => a + b, 0) / s.steps.length : 0,
9021
+ stepMax: s.steps.length ? Math.max(...s.steps) : 0,
9022
+ }))
9023
+ }
9024
+
9025
+ /** Participants with their activity: [{ from, inputs, firstAt, lastAt }]. */
9026
+ activity() {
9027
+ return [...this._participants.values()].map((from) => ({ from, ...(this._activity.get(from.cid) ?? { inputs: 0, firstAt: 0, lastAt: 0 }) }))
9028
+ }
9029
+
9030
+ /** Notable events after sequence `after`: [{ seq, at, kind: 'join'|'leave'|'denied'|'error', ... }]. */
9031
+ journal(after = 0) {
9032
+ return this._journal.filter((e) => e.seq > after)
9033
+ }
9034
+
9035
+ _note(kind, data) {
9036
+ this._journal.push({ seq: ++this._journalSeq, at: Date.now(), kind, ...data });
9037
+ if (this._journal.length > 200) this._journal.shift();
9038
+ }
9039
+
9040
+ // A client sent to a tag this host owns (Manager.sender dropped it).
9041
+ _denied(remote, tag) {
9042
+ this.counters.denied++;
9043
+ this._note('denied', { cid: remote.cid, tag });
9044
+ }
9045
+
9046
+ _failed(error) {
9047
+ this.counters.errors++;
9048
+ this._note('error', { message: String(error?.message ?? error).slice(0, 200) });
9049
+ if (this.listenerCount('error')) this.emit('error', error);
9050
+ else console.error(`host ${this.name} error:`, error);
8908
9051
  }
8909
9052
 
8910
9053
  /** Release the tags (they become ordinary channels again) and the host's retained values. */
8911
9054
  close() {
8912
9055
  if (this.closed) return
8913
9056
  this.closed = true;
9057
+ for (const { timer } of this._loops) clearInterval(timer);
9058
+ this._loops.clear();
8914
9059
  this.manager.hosts.remove(this);
8915
9060
  const owner = this.manager.retainOwners.get(this.retainOwnerKey);
8916
9061
  if (owner) for (const tag of [...owner.tags]) this.manager.dropChannelRetain(tag);
8917
9062
  this._participants.clear();
9063
+ this._activity.clear();
8918
9064
  this.emit('close');
8919
9065
  }
8920
9066
 
@@ -8947,7 +9093,18 @@ class Host extends require$$0$3 {
8947
9093
  }
8948
9094
  if (!args) return false
8949
9095
  const from = Host.from(remote);
9096
+ const now = Date.now();
9097
+ let act = this._activity.get(from.cid);
9098
+ if (!act) {
9099
+ act = { inputs: 0, firstAt: now, lastAt: now };
9100
+ this._activity.set(from.cid, act);
9101
+ this.counters.joins++;
9102
+ this._note('join', { cid: from.cid, nick: from.nick, authorized: from.authorized });
9103
+ }
9104
+ act.inputs++;
9105
+ act.lastAt = now;
8950
9106
  this._participants.set(from.cid, from);
9107
+ this.counters.inbound++;
8951
9108
  this._emitSafely('message', from, tag, ...args);
8952
9109
  return true
8953
9110
  }
@@ -8956,16 +9113,22 @@ class Host extends require$$0$3 {
8956
9113
  const from = this._participants.get(remote.cid);
8957
9114
  if (!from) return
8958
9115
  this._participants.delete(remote.cid);
9116
+ this._activity.delete(remote.cid);
9117
+ this.counters.leaves++;
9118
+ this._note('leave', { cid: remote.cid, reason: remote.closeReason ?? 'close' });
8959
9119
  this._emitSafely('leave', Host.from(remote), remote.closeReason ?? 'close');
8960
9120
  }
8961
9121
 
8962
9122
  _emitSafely(name, ...args) {
9123
+ const t0 = performance.now();
8963
9124
  try {
8964
9125
  this.emit(name, ...args);
8965
9126
  } catch (error) {
8966
- if (this.listenerCount('error')) this.emit('error', error);
8967
- else console.error(`host ${this.name} ${name} handler error:`, error);
9127
+ this._failed(error);
8968
9128
  }
9129
+ const ms = performance.now() - t0;
9130
+ this.counters.handlerMs += ms;
9131
+ if (ms > this.handlerMaxMs) this.handlerMaxMs = ms;
8969
9132
  }
8970
9133
  }
8971
9134
 
@@ -9304,10 +9467,12 @@ class Manager {
9304
9467
  return ['ok', 1]
9305
9468
  }
9306
9469
  this.counters.hostRejected++;
9470
+ entry.host.counters.rejected++;
9307
9471
  return ['err', 'Not accepted by the host']
9308
9472
  }
9309
9473
  if (entry) {
9310
9474
  this.counters.hostDenied++;
9475
+ entry.host._denied(remote, tag);
9311
9476
  if (this.server?.listenerCount?.('host:denied')) this.server.emit('host:denied', remote, tag, entry.host.name);
9312
9477
  return ['err', 'Tag is reserved by a host']
9313
9478
  }
@@ -9682,12 +9847,81 @@ class Manager {
9682
9847
  }
9683
9848
  }
9684
9849
 
9685
- const STATUS = {
9686
- OK: 0,
9687
- //0~127: success
9688
- //128~255: fail
9689
- ERROR: 255
9690
- };
9850
+ // Live server telemetry, sampled once a second and shared by every reader (the dashboard, the
9851
+ // monitor service): CPU, event-loop delay and utilisation, memory, connections by transport and
9852
+ // state, send queues of slow peers, and per-second rates of the manager's counters.
9853
+ // `value` holds the latest sample. dispose() stops the timer.
9854
+ class ServerStats {
9855
+ // onSample(value): called after each sample (the dashboard keeps its history from it).
9856
+ constructor(server, { onSample = null } = {}) {
9857
+ this.server = server;
9858
+ this.onSample = onSample;
9859
+ // Traffic counters come from the manager's cumulative counters, counted since this service started.
9860
+ this.base = { ...server.manager.counters };
9861
+ this.counters = { opened: 0, closed: 0, authFailed: 0,
9862
+ ...Object.fromEntries(Object.keys(this.base).map(key => [key, 0])) };
9863
+ this.onState = (_peer, _previous) => {
9864
+ if (_peer.state === STATE.OPEN) this.counters.opened++;
9865
+ if (_peer.state === STATE.CLOSED) this.counters.closed++;
9866
+ if (_peer.state === STATE.AUTH_FAIL) this.counters.authFailed++;
9867
+ };
9868
+ server.on('remote:state', this.onState);
9869
+ this.delay = monitorEventLoopDelay({ resolution: 20 }); this.delay.enable();
9870
+ this.cpu = process.cpuUsage(); this.elu = performance.eventLoopUtilization();
9871
+ this.previousAt = performance.now(); this.previous = { ...this.counters };
9872
+ this.sample();
9873
+ this.timer = setInterval(() => this.sample(), 1000); this.timer.unref();
9874
+ }
9875
+ sample() {
9876
+ const now = performance.now(), elapsed = Math.max(1, now - this.previousAt);
9877
+ for (const key in this.base) this.counters[key] = this.server.manager.counters[key] - this.base[key];
9878
+ let authenticated = 0, websocket = 0, queuedBytes = 0, maxQueuedBytes = 0;
9879
+ let txQueuePeakBytes = 0, txWriteFalseCount = 0, txDrainMaxMs = 0;
9880
+ let txBlockedConnections = 0, txBlockedMaxMs = 0;
9881
+ const states = {};
9882
+ const transports = { websocket: { total: 0, authenticated: 0 }, tcp: { total: 0, authenticated: 0 } };
9883
+ for (const peer of this.server.manager.remotes) {
9884
+ const transport = transports[peer.socketType === 'websocket' ? 'websocket' : 'tcp']; transport.total++;
9885
+ if (peer.boho.isAuthorized) { authenticated++; transport.authenticated++; }
9886
+ if (peer.socketType === 'websocket') websocket++;
9887
+ const queued = peer.socket.bufferedAmount ?? peer.socket.writableLength ?? 0;
9888
+ queuedBytes += queued; maxQueuedBytes = Math.max(maxQueuedBytes, queued);
9889
+ txQueuePeakBytes = Math.max(txQueuePeakBytes, peer.txQueuePeakBytes ?? 0);
9890
+ txWriteFalseCount += peer.txWriteFalseCount ?? 0;
9891
+ txDrainMaxMs = Math.max(txDrainMaxMs, peer.txDrainMaxMs ?? 0);
9892
+ if (peer.txBlockedSince != null) {
9893
+ txBlockedConnections++;
9894
+ txBlockedMaxMs = Math.max(txBlockedMaxMs, now - peer.txBlockedSince);
9895
+ }
9896
+ const name = peer.getStateName(); states[name] = (states[name] || 0) + 1;
9897
+ }
9898
+ const rates = Object.fromEntries(Object.entries(this.counters).map(([key, value]) => [key, (value - this.previous[key]) * 1000 / elapsed]));
9899
+ const cpu = process.cpuUsage(), elu = performance.eventLoopUtilization();
9900
+ const delta = performance.eventLoopUtilization(elu, this.elu);
9901
+ const mem = process.memoryUsage(), total = this.server.manager.remotes.size;
9902
+ let hostAvailableBytes = null;
9903
+ if (process.platform === 'linux') {
9904
+ try { const match = readFileSync('/proc/meminfo', 'utf8').match(/^MemAvailable:\s+(\d+) kB/m); if (match) hostAvailableBytes = Number(match[1]) * 1024; }
9905
+ catch { /* Optional host telemetry must not interrupt service. */ }
9906
+ }
9907
+ this.value = { at: Date.now(), total, authenticated, anonymous: total - authenticated, websocket,
9908
+ transports, hostAvailableBytes, hostTotalBytes: totalmem(), channels: this.server.manager.channel_map.size, states, queuedBytes, maxQueuedBytes,
9909
+ txQueuePeakBytes, txWriteFalseCount, txDrainMaxMs, txBlockedConnections, txBlockedMaxMs,
9910
+ counters: { ...this.counters }, rates, rss: mem.rss, heapUsed: mem.heapUsed,
9911
+ cpuPercent: ((cpu.user - this.cpu.user) + (cpu.system - this.cpu.system)) / (elapsed * 10),
9912
+ eventLoopUtilization: delta.utilization,
9913
+ eventLoopP99Ms: this.delay.percentile(99) / 1e6,
9914
+ // anonymous: profile name of unauthenticated connections; profiles: the server's quotas now.
9915
+ quota: { anonymous: this.server.anonymousQuota, profiles: structuredClone(this.server.quotas) } };
9916
+ this.previousAt = now; this.previous = { ...this.counters }; this.cpu = cpu; this.elu = elu; this.delay.reset();
9917
+ if (this.onSample) {
9918
+ try { this.onSample(this.value); } catch (error) { console.error('server stats reader error:', error); }
9919
+ }
9920
+ }
9921
+ dispose() {
9922
+ clearInterval(this.timer); this.delay.disable(); this.server.off('remote:state', this.onState);
9923
+ }
9924
+ }
9691
9925
 
9692
9926
  const decoder = new TextDecoder();
9693
9927
  const DUPLICATE_LOGIN_POLICIES = ['keepOld', 'keepNew'];
@@ -9805,6 +10039,32 @@ class BohoAuth {
9805
10039
  }
9806
10040
 
9807
10041
 
10042
+ /**
10043
+ * Hook for a subclass: decide where a verified login belongs before it is accepted.
10044
+ * Called after the key and role checks, before quotas and the duplicate login check.
10045
+ * Return null to accept the login here, or a message (e.g. SERVER_REDIRECT) that is sent to the
10046
+ * client instead of AUTH_RES before the connection is closed. The default accepts every login.
10047
+ * @param {object} peer the connection
10048
+ * @param {object} authInfo the key provider's entry for the login ID (cid, uid, role, quota, ...)
10049
+ * @param {string} role resolved role
10050
+ * @param {string} id login ID
10051
+ * @returns {Promise<Uint8Array | null> | Uint8Array | null}
10052
+ */
10053
+ beforeAccept(peer, authInfo, role, id) {
10054
+ return null
10055
+ }
10056
+
10057
+ // An error in the hook accepts the login: placement must never lock clients out.
10058
+ async #beforeAcceptSafe(peer, authInfo, role, id) {
10059
+ try {
10060
+ const result = await this.beforeAccept(peer, authInfo, role, id);
10061
+ return result instanceof Uint8Array && result.byteLength > 0 ? result : null
10062
+ } catch (error) {
10063
+ console.error('BohoAuth.beforeAccept error:', error);
10064
+ return null
10065
+ }
10066
+ }
10067
+
9808
10068
  async verify_auth_req(auth_req, peer) {
9809
10069
  try {
9810
10070
  if (!peer.checkAuthChallenge()) return;
@@ -9870,6 +10130,16 @@ class BohoAuth {
9870
10130
  this.send_auth_fail(peer, 'unknown auth.role: ' + authInfo.role);
9871
10131
  return
9872
10132
  }
10133
+ // A login another server should take (beforeAccept) goes there before it is counted here or
10134
+ // replaces a connection here.
10135
+ const redirect = await this.#beforeAcceptSafe(peer, authInfo, role, id);
10136
+ if (peer._closing) return; // closed while deciding
10137
+ if (redirect) {
10138
+ peer.boho.isAuthorized = false;
10139
+ peer.send(redirect);
10140
+ peer.close();
10141
+ return
10142
+ }
9873
10143
  const quotaName = await this.resolveQuota(authInfo, role);
9874
10144
  const quota = Object.hasOwn(peer.manager.quotas, quotaName) ? peer.manager.quotas[quotaName] : undefined;
9875
10145
  if (!quota) {
@@ -9992,6 +10262,718 @@ class BohoAuth {
9992
10262
 
9993
10263
  }
9994
10264
 
10265
+ // The dashboard web page, kept as a string so it ships inside the package (no CDN, works offline).
10266
+ // No backticks or template placeholders inside: the page is plain HTML, CSS and ES5-ish JavaScript.
10267
+ const PAGE = String.raw`<!doctype html>
10268
+ <html lang="ko">
10269
+ <head>
10270
+ <meta charset="utf-8">
10271
+ <meta name="viewport" content="width=device-width, initial-scale=1">
10272
+ <title>IOSignal Dashboard</title>
10273
+ <style>
10274
+ :root {
10275
+ --bg: #f3f5fa; --panel: #ffffff; --ink: #172036; --muted: #5f6a85; --line: #dde3ef; --grid: #e9edf5;
10276
+ --a: #0ea5a0; --b: #4f6bed; --c: #f59e0b; --d: #e5484d; --e: #8b5cf6; --ok: #22b573;
10277
+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
10278
+ --sans: system-ui, -apple-system, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif;
10279
+ color-scheme: light;
10280
+ }
10281
+ @media (prefers-color-scheme: dark) {
10282
+ :root { --bg: #0d1220; --panel: #151c30; --ink: #e6ebf7; --muted: #8e99b8; --line: #263050; --grid: #1d2640;
10283
+ --a: #2dd4bf; --b: #7c93ff; --c: #fbbf24; --d: #ff6b6b; --e: #a78bfa; --ok: #34d399; color-scheme: dark; }
10284
+ }
10285
+ * { box-sizing: border-box; }
10286
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 var(--sans); }
10287
+ header { position: sticky; top: 0; z-index: 5; display: flex; flex-wrap: wrap; gap: 10px 16px; align-items: center;
10288
+ padding: 10px max(16px, env(safe-area-inset-left)); background: color-mix(in srgb, var(--bg) 88%, transparent);
10289
+ backdrop-filter: blur(8px); border-bottom: 1px solid var(--line); }
10290
+ h1 { font-size: 16px; margin: 0; letter-spacing: .01em; }
10291
+ h1 b { color: var(--a); }
10292
+ .pill { font: 600 12px var(--mono); padding: 3px 10px; border-radius: 99px; background: var(--grid); color: var(--muted); }
10293
+ .pill.live { background: color-mix(in srgb, var(--ok) 18%, transparent); color: var(--ok); }
10294
+ .pill.live::before { content: ""; display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--ok); margin-right: 6px; animation: blink 1.2s infinite; }
10295
+ .pill.bad { background: color-mix(in srgb, var(--d) 18%, transparent); color: var(--d); }
10296
+ @keyframes blink { 50% { opacity: .25; } }
10297
+ .meta { font: 12px var(--mono); color: var(--muted); }
10298
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin-left: auto; }
10299
+ .chip { font: 600 12px var(--sans); border: 1px solid var(--line); background: var(--panel); color: var(--muted); border-radius: 99px; padding: 4px 11px; cursor: pointer; }
10300
+ .chip[aria-pressed="true"] { background: var(--ink); color: var(--panel); border-color: var(--ink); }
10301
+ .chip:focus-visible, button:focus-visible, input:focus-visible { outline: 2px solid var(--a); outline-offset: 2px; }
10302
+ main { padding: 16px max(16px, env(safe-area-inset-left)) 40px; display: grid; gap: 14px; grid-template-columns: repeat(12, minmax(0, 1fr)); }
10303
+ section.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; min-width: 0; display: grid; gap: 10px; align-content: start; }
10304
+ section.panel h2 { font-size: 13px; margin: 0; color: var(--muted); font-weight: 700; letter-spacing: .06em; text-transform: uppercase; display: flex; gap: 8px; align-items: baseline; }
10305
+ section.panel h2 small { text-transform: none; letter-spacing: 0; font-weight: 500; font-family: var(--mono); }
10306
+ .w12 { grid-column: span 12; } .w8 { grid-column: span 8; } .w6 { grid-column: span 6; } .w4 { grid-column: span 4; }
10307
+ @media (max-width: 1100px) { .w8, .w4 { grid-column: span 12; } .w6 { grid-column: span 12; } }
10308
+ .gauges { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
10309
+ @media (max-width: 640px) { .gauges { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
10310
+ .gauge { display: grid; justify-items: center; gap: 2px; }
10311
+ .gauge canvas { width: 100%; max-width: 150px; aspect-ratio: 1.45; }
10312
+ .gauge span { font-size: 12px; color: var(--muted); }
10313
+ canvas.chart { width: 100%; height: 150px; display: block; }
10314
+ canvas.chart.tall { height: 190px; }
10315
+ .legend { display: flex; flex-wrap: wrap; gap: 12px; font: 12px var(--mono); color: var(--muted); }
10316
+ .legend i { display: inline-block; width: 10px; height: 3px; border-radius: 2px; margin-right: 5px; vertical-align: middle; }
10317
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(118px, 1fr)); gap: 8px; }
10318
+ .stat { border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; display: grid; gap: 2px; }
10319
+ .stat b { font: 700 20px var(--mono); font-variant-numeric: tabular-nums; }
10320
+ .stat span { font-size: 12px; color: var(--muted); }
10321
+ .stat.flash { animation: flash .8s ease-out; }
10322
+ @keyframes flash { from { background: color-mix(in srgb, var(--d) 30%, transparent); } }
10323
+ .hosts { display: grid; grid-template-columns: repeat(auto-fit, minmax(270px, 1fr)); gap: 12px; }
10324
+ .host { border: 1px solid var(--line); border-radius: 12px; padding: 12px; display: grid; gap: 8px; position: relative; overflow: hidden; }
10325
+ .host header { all: unset; display: flex; align-items: center; gap: 8px; }
10326
+ .host h3 { margin: 0; font: 700 15px var(--mono); }
10327
+ .pulse { width: 12px; height: 12px; border-radius: 50%; background: var(--a); box-shadow: 0 0 0 0 color-mix(in srgb, var(--a) 60%, transparent); }
10328
+ .host .big { font: 800 30px var(--mono); line-height: 1; font-variant-numeric: tabular-nums; }
10329
+ .host .row { display: flex; flex-wrap: wrap; gap: 4px 14px; font: 12px var(--mono); color: var(--muted); }
10330
+ .host .row b { color: var(--ink); font-weight: 600; }
10331
+ .host canvas { width: 100%; height: 56px; display: block; }
10332
+ .shield { position: absolute; right: 10px; top: 10px; font: 700 11px var(--mono); color: var(--d); opacity: 0; transition: opacity .3s; }
10333
+ .shield.on { opacity: 1; }
10334
+ .loop { display: grid; gap: 6px; }
10335
+ .bar { height: 10px; border-radius: 6px; background: var(--grid); position: relative; overflow: hidden; }
10336
+ .bar > i { position: absolute; inset: 0 auto 0 0; border-radius: 6px; background: var(--a); transition: width .4s; }
10337
+ .bar > em { position: absolute; top: -2px; bottom: -2px; width: 2px; background: var(--ink); opacity: .6; }
10338
+ .kv { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 6px; }
10339
+ .kv div { background: var(--grid); border-radius: 8px; padding: 6px 9px; display: grid; }
10340
+ .kv span { font-size: 11px; color: var(--muted); } .kv b { font: 700 16px var(--mono); overflow-wrap: anywhere; }
10341
+ .table { overflow-x: auto; }
10342
+ table { border-collapse: collapse; width: 100%; font: 12.5px var(--mono); }
10343
+ th, td { padding: 6px 8px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
10344
+ th { color: var(--muted); font-weight: 600; font-family: var(--sans); }
10345
+ .act { display: inline-block; height: 8px; border-radius: 4px; background: var(--b); vertical-align: middle; min-width: 2px; }
10346
+ .badge { font-size: 11px; padding: 1px 6px; border-radius: 6px; background: var(--grid); color: var(--muted); }
10347
+ .badge.auth { background: color-mix(in srgb, var(--ok) 20%, transparent); color: var(--ok); }
10348
+ .events { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; max-height: 340px; overflow: auto; font: 12.5px var(--mono); }
10349
+ .events li { display: flex; gap: 8px; align-items: baseline; padding: 4px 6px; border-radius: 6px; animation: slide .5s ease-out; }
10350
+ @keyframes slide { from { background: color-mix(in srgb, var(--a) 22%, transparent); transform: translateX(-6px); } }
10351
+ .events time { color: var(--muted); }
10352
+ .k { font: 700 11px var(--sans); padding: 1px 7px; border-radius: 6px; }
10353
+ .k.join { background: color-mix(in srgb, var(--ok) 22%, transparent); color: var(--ok); }
10354
+ .k.leave { background: var(--grid); color: var(--muted); }
10355
+ .k.denied { background: color-mix(in srgb, var(--d) 22%, transparent); color: var(--d); }
10356
+ .k.error { background: color-mix(in srgb, var(--c) 25%, transparent); color: var(--c); }
10357
+ .empty { color: var(--muted); font-size: 13px; padding: 6px 0; }
10358
+ .overlay { position: fixed; inset: 0; z-index: 10; display: grid; place-items: center; background: color-mix(in srgb, var(--bg) 80%, transparent); backdrop-filter: blur(6px); padding: 16px; }
10359
+ .overlay form { background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 20px; width: min(360px, 100%); display: grid; gap: 10px; box-shadow: 0 20px 50px rgba(0,0,0,.2); }
10360
+ .overlay h2 { margin: 0; font-size: 18px; }
10361
+ .overlay input { padding: 9px 11px; border-radius: 9px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); font: 14px var(--mono); }
10362
+ .overlay button { padding: 10px; border: 0; border-radius: 10px; background: var(--a); color: #fff; font-weight: 700; cursor: pointer; }
10363
+ .overlay p { margin: 0; color: var(--muted); font-size: 13px; }
10364
+ .overlay .err { color: var(--d); }
10365
+ [hidden] { display: none !important; }
10366
+ @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
10367
+ </style>
10368
+ </head>
10369
+ <body>
10370
+ <header>
10371
+ <h1><b>IOSignal</b> Dashboard</h1>
10372
+ <span id="status" class="pill">연결 중</span>
10373
+ <span id="meta" class="meta"></span>
10374
+ <nav class="chips" id="chips" aria-label="패널"></nav>
10375
+ </header>
10376
+ <main id="main">
10377
+ <section class="panel w12" data-panel="server">
10378
+ <h2>서버 <small id="uptime"></small></h2>
10379
+ <div class="gauges">
10380
+ <div class="gauge"><canvas id="gCpu"></canvas><span>CPU</span></div>
10381
+ <div class="gauge"><canvas id="gEld"></canvas><span>이벤트 루프 지연 p99</span></div>
10382
+ <div class="gauge"><canvas id="gElu"></canvas><span>이벤트 루프 사용률</span></div>
10383
+ <div class="gauge"><canvas id="gMem"></canvas><span>메모리 (RSS)</span></div>
10384
+ </div>
10385
+ <canvas class="chart" id="cLoad"></canvas>
10386
+ <div class="legend"><span><i style="background:var(--a)"></i>CPU %</span><span><i style="background:var(--c)"></i>지연 p99 ms</span><span><i style="background:var(--e)"></i>연결 수</span></div>
10387
+ <div class="stats" id="sConn"></div>
10388
+ </section>
10389
+ <section class="panel w8" data-panel="traffic">
10390
+ <h2>트래픽 <small>초당</small></h2>
10391
+ <canvas class="chart tall" id="cMsg"></canvas>
10392
+ <div class="legend"><span><i style="background:var(--b)"></i>받은 메시지</span><span><i style="background:var(--a)"></i>보낸 메시지</span><span><i style="background:var(--d)"></i>버린 메시지(쿼터)</span></div>
10393
+ <canvas class="chart" id="cBytes"></canvas>
10394
+ <div class="legend"><span><i style="background:var(--b)"></i>받은 바이트</span><span><i style="background:var(--a)"></i>보낸 바이트</span></div>
10395
+ </section>
10396
+ <section class="panel w4" data-panel="traffic">
10397
+ <h2>전송 상태</h2>
10398
+ <div class="stats" id="sTraffic"></div>
10399
+ </section>
10400
+ <section class="panel w12" data-panel="hosts">
10401
+ <h2>호스트 <small id="hostCount"></small></h2>
10402
+ <div class="hosts" id="hosts"></div>
10403
+ </section>
10404
+ <section class="panel w6" data-panel="game">
10405
+ <h2>게임 루프</h2>
10406
+ <div id="game" class="loop"></div>
10407
+ </section>
10408
+ <section class="panel w6" data-panel="events">
10409
+ <h2>이벤트 <small>입장 · 퇴장 · 위조 차단 · 오류</small></h2>
10410
+ <ul class="events" id="events"></ul>
10411
+ </section>
10412
+ <section class="panel w12" data-panel="participants">
10413
+ <h2>참가자</h2>
10414
+ <div class="table" id="players"></div>
10415
+ </section>
10416
+ </main>
10417
+
10418
+ <div class="overlay" id="gate" hidden>
10419
+ <form id="gateForm">
10420
+ <h2 id="gateTitle">대시보드 로그인</h2>
10421
+ <p id="gateHelp"></p>
10422
+ <input id="gateId" placeholder="ID" autocomplete="username">
10423
+ <input id="gateKey" type="password" placeholder="키" autocomplete="current-password">
10424
+ <p id="gateErr" class="err" hidden></p>
10425
+ <button type="submit">보기</button>
10426
+ </form>
10427
+ </div>
10428
+
10429
+ <script>var CONFIG = __CONFIG__;</script>
10430
+ <script src="__IO__"></script>
10431
+ <script>
10432
+ (function () {
10433
+ "use strict";
10434
+ var $ = function (id) { return document.getElementById(id); };
10435
+ var css = function (name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); };
10436
+ var store = { get: function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } },
10437
+ set: function (k, v) { try { localStorage.setItem(k, v); } catch (e) {} },
10438
+ sget: function (k) { try { return sessionStorage.getItem(k); } catch (e) { return null; } },
10439
+ sset: function (k, v) { try { sessionStorage.setItem(k, v); } catch (e) {} } };
10440
+ var esc = function (s) { return String(s == null ? "" : s).replace(/[&<>"]/g, function (c) { return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]; }); };
10441
+ var fmtB = function (n) { n = n || 0; return n >= 1048576 ? (n / 1048576).toFixed(1) + " MB" : n >= 1024 ? (n / 1024).toFixed(1) + " KB" : Math.round(n) + " B"; };
10442
+ var fmtN = function (n) { n = n || 0; return n >= 10000 ? (n / 1000).toFixed(1) + "k" : n >= 100 ? Math.round(n) + "" : (Math.round(n * 10) / 10) + ""; };
10443
+ var fmtT = function (ms) { var s = Math.floor(ms / 1000), h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60); return (h ? h + "시간 " : "") + m + "분 " + (s % 60) + "초"; };
10444
+
10445
+ // ------------------------------------------------ panels the viewer turns on and off
10446
+ var NAMES = { server: "서버", traffic: "트래픽", hosts: "호스트", game: "게임 루프", participants: "참가자", events: "이벤트" };
10447
+ var saved = store.get("iosignal.dashboard.panels");
10448
+ var shown = saved ? saved.split(",") : CONFIG.panels.slice();
10449
+ function applyPanels() {
10450
+ var nodes = document.querySelectorAll("[data-panel]");
10451
+ for (var i = 0; i < nodes.length; i++) nodes[i].hidden = shown.indexOf(nodes[i].getAttribute("data-panel")) < 0;
10452
+ var chips = $("chips").children;
10453
+ for (var j = 0; j < chips.length; j++) chips[j].setAttribute("aria-pressed", String(shown.indexOf(chips[j].getAttribute("data-p")) >= 0));
10454
+ store.set("iosignal.dashboard.panels", shown.join(","));
10455
+ draw();
10456
+ }
10457
+ Object.keys(NAMES).forEach(function (p) {
10458
+ var b = document.createElement("button");
10459
+ b.className = "chip"; b.type = "button"; b.textContent = NAMES[p]; b.setAttribute("data-p", p);
10460
+ b.onclick = function () { var i = shown.indexOf(p); if (i >= 0) shown.splice(i, 1); else shown.push(p); applyPanels(); };
10461
+ $("chips").appendChild(b);
10462
+ });
10463
+
10464
+ // ------------------------------------------------ state
10465
+ var series = [], latest = null, hosts = [], events = [], info = null, startedAt = 0, hostHist = {};
10466
+ var pulses = {};
10467
+
10468
+ // ------------------------------------------------ canvas helpers
10469
+ function fit(cv) {
10470
+ var r = cv.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1);
10471
+ var w = Math.max(10, Math.round(r.width * d)), h = Math.max(10, Math.round(r.height * d));
10472
+ if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
10473
+ var c = cv.getContext("2d"); c.setTransform(d, 0, 0, d, 0, 0);
10474
+ return { c: c, w: r.width, h: r.height };
10475
+ }
10476
+ // Lines over time with a soft area under the first one. lines: [{ values, color, scale? }]
10477
+ function chart(cv, lines, opts) {
10478
+ if (!cv.offsetParent) return;
10479
+ var f = fit(cv), c = f.c, w = f.w, h = f.h, pad = { l: 58, r: 12, t: 8, b: 18 };
10480
+ c.clearRect(0, 0, w, h);
10481
+ var max = (opts && opts.max) || 1;
10482
+ lines.forEach(function (l) { if (!l.own) l.values.forEach(function (v) { if (v > max) max = v; }); });
10483
+ max = niceMax(max);
10484
+ var n = Math.max(2, CONFIG.history), x0 = pad.l, x1 = w - pad.r, y0 = h - pad.b, y1 = pad.t;
10485
+ c.strokeStyle = css("--grid"); c.lineWidth = 1; c.fillStyle = css("--muted"); c.font = "11px " + css("--mono"); c.textAlign = "right";
10486
+ for (var g = 0; g <= 3; g++) {
10487
+ var y = y0 - (y0 - y1) * g / 3;
10488
+ c.beginPath(); c.moveTo(x0, y); c.lineTo(x1, y); c.stroke();
10489
+ c.fillText((opts && opts.fmt ? opts.fmt(max * g / 3) : fmtN(max * g / 3)), x0 - 6, y + 4);
10490
+ }
10491
+ c.textAlign = "left"; c.fillText("-" + Math.round(n / 60) + "분", x0, h - 3); c.textAlign = "right"; c.fillText("지금", x1, h - 3);
10492
+ lines.forEach(function (l, li) {
10493
+ var v = l.values, m = l.own ? niceMax(Math.max.apply(null, v.concat([1]))) : max;
10494
+ if (!v.length) return;
10495
+ var X = function (i) { return x1 - (v.length - 1 - i) * (x1 - x0) / (n - 1); };
10496
+ var Y = function (val) { return y0 - (y0 - y1) * Math.min(1, (val || 0) / m); };
10497
+ c.beginPath();
10498
+ for (var i = 0; i < v.length; i++) { var px = X(i), py = Y(v[i]); if (i) c.lineTo(px, py); else c.moveTo(px, py); }
10499
+ c.strokeStyle = css(l.color); c.lineWidth = 2; c.lineJoin = "round"; c.stroke();
10500
+ if (li === 0) {
10501
+ c.lineTo(X(v.length - 1), y0); c.lineTo(X(0), y0); c.closePath();
10502
+ var grad = c.createLinearGradient(0, y1, 0, y0);
10503
+ grad.addColorStop(0, hexA(css(l.color), 0.28)); grad.addColorStop(1, hexA(css(l.color), 0));
10504
+ c.fillStyle = grad; c.fill();
10505
+ }
10506
+ var lx = X(v.length - 1), ly = Y(v[v.length - 1]);
10507
+ c.fillStyle = css(l.color); c.beginPath(); c.arc(lx, ly, 3.5, 0, 6.3); c.fill();
10508
+ });
10509
+ }
10510
+ function niceMax(v) { var p = Math.pow(10, Math.floor(Math.log10(Math.max(v, 1e-9)))); var m = v / p; return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p; }
10511
+ function hexA(col, a) {
10512
+ if (col.charAt(0) === "#") { var n = parseInt(col.slice(1), 16); return "rgba(" + (n >> 16) + "," + ((n >> 8) & 255) + "," + (n & 255) + "," + a + ")"; }
10513
+ return col;
10514
+ }
10515
+ // Half-ring gauge with an animated needle value.
10516
+ var gaugeNow = {};
10517
+ function gauge(id, value, max, label, color) {
10518
+ var cv = $(id); if (!cv.offsetParent) return;
10519
+ var cur = gaugeNow[id] == null ? value : gaugeNow[id] + (value - gaugeNow[id]) * 0.18;
10520
+ gaugeNow[id] = cur;
10521
+ var f = fit(cv), c = f.c, w = f.w, h = f.h, r = Math.min(w / 2, h) * 0.86, cx = w / 2, cy = h * 0.9;
10522
+ c.clearRect(0, 0, w, h);
10523
+ c.lineCap = "round"; c.lineWidth = r * 0.17;
10524
+ c.strokeStyle = css("--grid"); c.beginPath(); c.arc(cx, cy, r, Math.PI, 2 * Math.PI); c.stroke();
10525
+ var frac = Math.max(0, Math.min(1, cur / max));
10526
+ var col = frac > 0.85 ? css("--d") : frac > 0.6 ? css("--c") : css(color);
10527
+ c.strokeStyle = col; c.beginPath(); c.arc(cx, cy, r, Math.PI, Math.PI + Math.PI * Math.max(0.01, frac)); c.stroke();
10528
+ c.fillStyle = css("--ink"); c.textAlign = "center"; c.font = "700 " + Math.round(r * 0.36) + "px " + css("--mono");
10529
+ c.fillText(label(cur), cx, cy - r * 0.2);
10530
+ }
10531
+ function spark(cv, values, color) {
10532
+ if (!cv.offsetParent) return;
10533
+ var f = fit(cv), c = f.c, w = f.w, h = f.h; c.clearRect(0, 0, w, h);
10534
+ if (!values.length) return;
10535
+ var m = niceMax(Math.max.apply(null, values.concat([1]))), n = 60;
10536
+ c.beginPath();
10537
+ for (var i = 0; i < values.length; i++) {
10538
+ var x = w - (values.length - 1 - i) * w / (n - 1), y = h - 3 - (h - 6) * values[i] / m;
10539
+ if (i) c.lineTo(x, y); else c.moveTo(x, y);
10540
+ }
10541
+ c.strokeStyle = css(color); c.lineWidth = 1.8; c.stroke();
10542
+ c.lineTo(w, h); c.lineTo(w - (values.length - 1) * w / (n - 1), h); c.closePath();
10543
+ c.fillStyle = hexA(css(color), 0.18); c.fill();
10544
+ }
10545
+
10546
+ // ------------------------------------------------ render
10547
+ function stat(label, value, flash) { return '<div class="stat' + (flash ? " flash" : "") + '"><b>' + value + "</b><span>" + label + "</span></div>"; }
10548
+ var prevDropped = 0, prevDenied = {};
10549
+ function render() {
10550
+ if (!latest) return;
10551
+ var p = latest.point, s = latest.server;
10552
+ $("uptime").textContent = "가동 " + fmtT(s.uptime);
10553
+ $("meta").textContent = "시청 " + s.own.viewers + "명" + (info ? " · Node " + info.node : "");
10554
+ $("sConn").innerHTML = stat("연결", p.conns) + stat("WebSocket", p.ws) + stat("TCP (보드)", p.tcp) + stat("로그인", p.auth) + stat("채널", s.channels);
10555
+ var dropped = s.counters.rateLimited + s.counters.oversizeRejected;
10556
+ $("sTraffic").innerHTML = stat("버린 메시지 (누적)", fmtN(dropped), dropped > prevDropped) +
10557
+ stat("느린 연결", s.txBlockedConnections) + stat("밀린 송신", fmtB(s.queuedBytes)) +
10558
+ stat("가장 많이 밀린 연결", fmtB(s.maxQueuedBytes)) + stat("수신 버퍼 초과로 안 보냄", fmtN(s.counters.peerRxLimitSkipped));
10559
+ prevDropped = dropped;
10560
+ renderHosts();
10561
+ renderGame();
10562
+ renderPlayers();
10563
+ }
10564
+ function renderHosts() {
10565
+ $("hostCount").textContent = hosts.length ? hosts.length + "개" : "";
10566
+ if (!hosts.length) { $("hosts").innerHTML = '<p class="empty">등록된 호스트가 없습니다. server.host()로 게임을 올리면 여기에 나옵니다.</p>'; return; }
10567
+ var box = $("hosts");
10568
+ hosts.forEach(function (h) {
10569
+ var el = box.querySelector('[data-host="' + CSS.escape(h.name) + '"]');
10570
+ if (!el) {
10571
+ el = document.createElement("div"); el.className = "host"; el.setAttribute("data-host", h.name);
10572
+ el.innerHTML = '<header><span class="pulse"></span><h3></h3></header><span class="shield">위조 차단!</span>' +
10573
+ '<div><span class="big"></span> <span class="meta">참가자</span></div><canvas></canvas><div class="row"></div>';
10574
+ el.querySelector("h3").textContent = h.name;
10575
+ box.appendChild(el);
10576
+ }
10577
+ el.querySelector(".big").textContent = h.participants;
10578
+ var r = h.rates;
10579
+ el.querySelector(".row").innerHTML = "<span>입력 <b>" + fmtN(r.inbound) + "/s</b></span><span>방송 <b>" + fmtN(r.published) + "/s</b></span>" +
10580
+ "<span>1:1 <b>" + fmtN(r.sent) + "/s</b></span><span>처리 <b>" + h.handlerAvgMs.toFixed(2) + "ms</b> (최대 " + h.handlerMaxMs.toFixed(1) + ")</span>" +
10581
+ "<span>차단 <b>" + h.totals.denied + "</b></span><span>오류 <b>" + h.totals.errors + "</b></span>";
10582
+ var shield = el.querySelector(".shield");
10583
+ if ((prevDenied[h.name] || 0) < h.totals.denied) { shield.classList.add("on"); setTimeout(function () { shield.classList.remove("on"); }, 1500); }
10584
+ prevDenied[h.name] = h.totals.denied;
10585
+ pulses[h.name] = r.inbound;
10586
+ spark(el.querySelector("canvas"), (hostHist[h.name] || []).map(function (x) { return x.in || 0; }), "--a");
10587
+ });
10588
+ Array.prototype.slice.call(box.children).forEach(function (el) {
10589
+ if (!hosts.some(function (h) { return h.name === el.getAttribute("data-host"); })) el.remove();
10590
+ });
10591
+ }
10592
+ function renderGame() {
10593
+ if (!hosts.length) { $("game").innerHTML = '<p class="empty">호스트가 없습니다.</p>'; return; }
10594
+ var html = "";
10595
+ hosts.forEach(function (h) {
10596
+ html += '<div><b style="font-family:var(--mono)">' + esc(h.name) + "</b></div>";
10597
+ if (!h.loops.length) html += '<p class="empty">host.loop(ms, fn)를 쓰면 틱 간격과 처리 시간이 여기에 나옵니다.</p>';
10598
+ h.loops.forEach(function (l) {
10599
+ var scale = l.intervalMs * 2, gap = Math.min(1, l.gapP99 / scale), target = l.intervalMs / scale;
10600
+ html += '<div class="row" style="display:flex;gap:12px;font:12px var(--mono);color:var(--muted)"><span>목표 <b style="color:var(--ink)">' + l.intervalMs + 'ms</b></span><span>틱 간격 p50 <b style="color:var(--ink)">' + l.gapP50.toFixed(1) + '</b> · p99 <b style="color:var(--ink)">' + l.gapP99.toFixed(1) + '</b></span><span>처리 평균 <b style="color:var(--ink)">' + l.stepAvg.toFixed(2) + 'ms</b> · 최대 ' + l.stepMax.toFixed(1) + '</span><span>' + l.ticks + '틱</span></div>' +
10601
+ '<div class="bar" title="틱 간격 p99 (선: 목표)"><i style="width:' + (gap * 100).toFixed(1) + '%;background:' + (l.gapP99 > l.intervalMs * 1.5 ? "var(--d)" : l.gapP99 > l.intervalMs * 1.15 ? "var(--c)" : "var(--a)") + '"></i><em style="left:' + (target * 100).toFixed(1) + '%"></em></div>' +
10602
+ '<div class="bar" title="처리 시간 / 목표"><i style="width:' + Math.min(100, l.stepAvg / l.intervalMs * 100).toFixed(1) + '%;background:var(--b)"></i></div>';
10603
+ });
10604
+ var keys = Object.keys(h.report || {});
10605
+ if (keys.length) {
10606
+ html += '<div class="kv">' + keys.map(function (k) { return "<div><span>" + esc(k) + "</span><b>" + esc(h.report[k]) + "</b></div>"; }).join("") + "</div>";
10607
+ } else html += '<p class="empty">host.report({ ... })로 보낸 값이 여기에 나옵니다.</p>';
10608
+ });
10609
+ $("game").innerHTML = html;
10610
+ }
10611
+ function renderPlayers() {
10612
+ var rows = [];
10613
+ hosts.forEach(function (h) { (h.players || []).forEach(function (p) { rows.push([h.name, p]); }); });
10614
+ if (!rows.length) { $("players").innerHTML = '<p class="empty">아직 입력을 보낸 참가자가 없습니다.</p>'; return; }
10615
+ var max = Math.max.apply(null, rows.map(function (r) { return r[1].inputs; }).concat([1]));
10616
+ $("players").innerHTML = "<table><thead><tr><th>호스트</th><th>CID</th><th>이름</th><th>로그인</th><th>입력</th><th>참가</th><th>마지막 입력</th></tr></thead><tbody>" +
10617
+ rows.map(function (r) {
10618
+ var p = r[1];
10619
+ return "<tr><td>" + esc(r[0]) + "</td><td>" + esc(p.cid) + "</td><td>" + esc(p.nick || "-") + "</td><td>" +
10620
+ (p.authorized ? '<span class="badge auth">로그인</span>' : '<span class="badge">익명</span>') + '</td><td><span class="act" style="width:' + Math.round(80 * p.inputs / max) + 'px"></span> ' + p.inputs +
10621
+ "</td><td>" + fmtT(p.since) + "</td><td>" + (p.idle < 1000 ? "방금" : Math.round(p.idle / 1000) + "초 전") + "</td></tr>";
10622
+ }).join("") + "</tbody></table>";
10623
+ }
10624
+ var KIND = { join: "입장", leave: "퇴장", denied: "위조 차단", error: "오류" };
10625
+ function addEvents(list, initial) {
10626
+ if (!list || !list.length) return;
10627
+ var ul = $("events");
10628
+ list.forEach(function (e) {
10629
+ events.push(e);
10630
+ var li = document.createElement("li");
10631
+ var t = new Date(e.at);
10632
+ var detail = e.kind === "denied" ? (e.cid || "") + " → " + (e.tag || "") : e.kind === "error" ? (e.message || "") : (e.cid || "") + (e.reason ? " (" + e.reason + ")" : "");
10633
+ li.innerHTML = "<time>" + t.toLocaleTimeString() + '</time><span class="k ' + e.kind + '">' + (KIND[e.kind] || e.kind) + "</span><span>" + esc(e.host) + "</span><span>" + esc(detail) + "</span>";
10634
+ if (initial) li.style.animation = "none";
10635
+ ul.insertBefore(li, ul.firstChild);
10636
+ });
10637
+ while (ul.children.length > 120) ul.removeChild(ul.lastChild);
10638
+ if (!ul.children.length) ul.innerHTML = '<li class="empty">아직 이벤트가 없습니다.</li>';
10639
+ }
10640
+
10641
+ function draw() {
10642
+ var pick = function (k) { return series.map(function (p) { return p[k] || 0; }); };
10643
+ chart($("cLoad"), [{ values: pick("cpu"), color: "--a" }, { values: pick("eld"), color: "--c" }, { values: pick("conns"), color: "--e", own: true }], { max: 10 });
10644
+ chart($("cMsg"), [{ values: pick("rxMsg"), color: "--b" }, { values: pick("txMsg"), color: "--a" }, { values: pick("dropped"), color: "--d" }], { max: 10 });
10645
+ chart($("cBytes"), [{ values: pick("rxB"), color: "--b" }, { values: pick("txB"), color: "--a" }], { max: 1024, fmt: fmtB });
10646
+ }
10647
+ // Gauges and host pulses move every frame; charts redraw on each sample.
10648
+ function frame(t) {
10649
+ if (latest) {
10650
+ var p = latest.point, total = latest.server.hostTotalBytes || 1;
10651
+ gauge("gCpu", p.cpu, 100, function (v) { return Math.round(v) + "%"; }, "--a");
10652
+ gauge("gEld", p.eld, 100, function (v) { return v.toFixed(1) + "ms"; }, "--c");
10653
+ gauge("gElu", p.elu * 100, 100, function (v) { return Math.round(v) + "%"; }, "--b");
10654
+ gauge("gMem", p.rss / 1048576, Math.max(256, Math.min(total / 1048576, 2048)), function (v) { return Math.round(v) + "MB"; }, "--e");
10655
+ }
10656
+ var dots = document.querySelectorAll(".host");
10657
+ for (var i = 0; i < dots.length; i++) {
10658
+ var rate = pulses[dots[i].getAttribute("data-host")] || 0;
10659
+ var speed = Math.min(8, 0.6 + rate / 8);
10660
+ var k = (Math.sin(t / 1000 * speed * Math.PI) + 1) / 2;
10661
+ var dot = dots[i].querySelector(".pulse");
10662
+ dot.style.boxShadow = rate > 0 ? "0 0 0 " + (k * 7).toFixed(1) + "px " + hexA(css("--a"), 0.35 * (1 - k)) : "none";
10663
+ dot.style.background = rate > 0 ? css("--a") : css("--muted");
10664
+ }
10665
+ requestAnimationFrame(frame);
10666
+ }
10667
+ requestAnimationFrame(frame);
10668
+ addEventListener("resize", draw);
10669
+
10670
+ // ------------------------------------------------ IOSignal connection
10671
+ var io = null, helloTimer = 0, cred = {};
10672
+ function status(text, cls) { var el = $("status"); el.textContent = text; el.className = "pill" + (cls ? " " + cls : ""); }
10673
+ function connect() {
10674
+ if (io) { try { io.destroy(); } catch (e) {} }
10675
+ io = new IO();
10676
+ if (CONFIG.access === "login" && cred.id) io.auth(cred.id, cred.key);
10677
+ io.on("change", function () {
10678
+ if (io.stateName !== "ready") status(io.stateName === "closed" ? "연결 끊김" : "연결 중", io.stateName === "closed" ? "bad" : "");
10679
+ });
10680
+ io.on("ready", function () { hello(); });
10681
+ io.on(CONFIG.topic, function (tag, msg) { onMessage(msg); });
10682
+ io.open((location.protocol === "https:" ? "wss://" : "ws://") + location.host + CONFIG.ws);
10683
+ clearInterval(helloTimer);
10684
+ helloTimer = setInterval(hello, 5000);
10685
+ }
10686
+ function hello() { if (io && io.stateName === "ready") io.signal(CONFIG.tag, { op: "hello", token: cred.token }); }
10687
+ function onMessage(m) {
10688
+ if (!m || !m.type) return;
10689
+ if (m.type === "denied") { status("권한 없음", "bad"); askAccess(true); return; }
10690
+ if (m.type === "full") { status("시청자가 가득 찼습니다", "bad"); return; }
10691
+ if (m.type === "init") {
10692
+ $("gate").hidden = true;
10693
+ status("실시간", "live");
10694
+ info = m.server; startedAt = m.startedAt; series = m.series.slice();
10695
+ hostHist = {};
10696
+ series.forEach(function (p) { Object.keys(p.hosts || {}).forEach(function (n) { (hostHist[n] = hostHist[n] || []).push(p.hosts[n]); }); });
10697
+ $("events").innerHTML = "";
10698
+ addEvents(m.events, true);
10699
+ if (!saved) { shown = m.panels.slice(); applyPanels(); }
10700
+ return;
10701
+ }
10702
+ if (m.type === "tick") {
10703
+ latest = m; hosts = m.hosts;
10704
+ series.push(m.point); if (series.length > CONFIG.history) series.shift();
10705
+ Object.keys(m.point.hosts || {}).forEach(function (n) { var a = (hostHist[n] = hostHist[n] || []); a.push(m.point.hosts[n]); if (a.length > 60) a.shift(); });
10706
+ addEvents(m.events, false);
10707
+ render(); draw();
10708
+ }
10709
+ }
10710
+ function askAccess(failed) {
10711
+ var gate = $("gate");
10712
+ $("gateErr").hidden = !failed; $("gateErr").textContent = failed ? "확인하지 못했습니다. 다시 입력해 주세요." : "";
10713
+ if (CONFIG.access === "token") {
10714
+ $("gateTitle").textContent = "대시보드 토큰"; $("gateHelp").textContent = "서버 설정의 dashboard.access.token 값을 입력하세요.";
10715
+ $("gateId").hidden = true; $("gateKey").placeholder = "토큰";
10716
+ } else {
10717
+ $("gateTitle").textContent = "대시보드 로그인"; $("gateHelp").textContent = "이 서버에 로그인할 수 있는 ID와 키를 입력하세요(허용된 역할 또는 CID).";
10718
+ }
10719
+ gate.hidden = false;
10720
+ (CONFIG.access === "token" ? $("gateKey") : $("gateId")).focus();
10721
+ }
10722
+ $("gateForm").addEventListener("submit", function (e) {
10723
+ e.preventDefault();
10724
+ if (CONFIG.access === "token") { cred = { token: $("gateKey").value }; store.sset("iosignal.dashboard.token", cred.token); hello(); }
10725
+ else { cred = { id: $("gateId").value.trim(), key: $("gateKey").value }; connect(); }
10726
+ });
10727
+ addEventListener("pagehide", function () { if (io && io.stateName === "ready") io.signal(CONFIG.tag, { op: "bye" }); });
10728
+
10729
+ applyPanels();
10730
+ addEvents([], true);
10731
+ if (CONFIG.access === "token") { var t = store.sget("iosignal.dashboard.token") || new URLSearchParams(location.search).get("key"); if (t) cred = { token: t }; }
10732
+ connect();
10733
+ if (CONFIG.access === "login" || (CONFIG.access === "token" && !cred.token)) askAccess(false);
10734
+ })();
10735
+ </script>
10736
+ </body>
10737
+ </html>`;
10738
+
10739
+ /** The page with its settings: { io, ws, access, panels, history, tag, topic }. */
10740
+ function dashboardPage(config) {
10741
+ const json = JSON.stringify(config).replace(/</g, '\\u003c');
10742
+ return PAGE.replace('__CONFIG__', json).replace('__IO__', config.io.replace(/"/g, ''))
10743
+ }
10744
+
10745
+ /** Tags of the dashboard's own host. Viewers send to IN; the host sends to one viewer as '@' + TOPIC. */
10746
+ const DASHBOARD = { HOST: 'iosignal.dashboard', IN: 'iosignal.dashboard#in', TOPIC: 'iosignal.dashboard' };
10747
+ const DASHBOARD_PANELS = ['server', 'traffic', 'hosts', 'game', 'participants', 'events'];
10748
+
10749
+ const IO_BUNDLE = new URL('../../dist/browser/iife/io.js', import.meta.url);
10750
+ const VIEWER_TTL_MS = 15000;
10751
+ const PARTICIPANT_LIMIT = 60;
10752
+ const sha = (s) => createHash('sha256').update(String(s)).digest();
10753
+
10754
+ /**
10755
+ * The server dashboard: a web page (options.path) that shows the server and its hosts live.
10756
+ * It talks to the page through IOSignal itself: viewers send 'hello' to DASHBOARD.IN, a host checks
10757
+ * access, and every second it sends the latest sample to each viewer with host.to().
10758
+ *
10759
+ * options (all optional):
10760
+ * path: '/dashboard'
10761
+ * access: 'open' | { token: '...' } | { login: { roles: ['admin'], cids: [] } }
10762
+ * panels: panels shown first (DASHBOARD_PANELS); viewers can switch them
10763
+ * history: seconds kept for the charts (default 300, 10-3600)
10764
+ * maxViewers: default 20
10765
+ * showIdentities: show participant CIDs and names (default: true unless access is 'open')
10766
+ */
10767
+ class Dashboard {
10768
+ constructor(server, options = {}) {
10769
+ if (options === true) options = {};
10770
+ if (options === null || typeof options !== 'object') throw new TypeError('dashboard options must be an object or true')
10771
+ for (const key of Object.keys(options)) {
10772
+ if (!['path', 'access', 'panels', 'history', 'maxViewers', 'showIdentities'].includes(key)) {
10773
+ throw new TypeError(`unknown dashboard option: ${key}`)
10774
+ }
10775
+ }
10776
+ const path = options.path ?? '/dashboard';
10777
+ if (typeof path !== 'string' || !/^\/[A-Za-z0-9._~\-/]*$/.test(path) || path.length > 64) {
10778
+ throw new TypeError("dashboard path must start with '/' and use URL-safe characters")
10779
+ }
10780
+ this.path = path.length > 1 ? path.replace(/\/+$/, '') : path;
10781
+ this.access = this.#access(options.access ?? 'open');
10782
+ const panels = options.panels ?? DASHBOARD_PANELS;
10783
+ if (!Array.isArray(panels) || panels.some((p) => !DASHBOARD_PANELS.includes(p))) {
10784
+ throw new TypeError(`dashboard panels must be some of: ${DASHBOARD_PANELS.join(', ')}`)
10785
+ }
10786
+ this.panels = [...new Set(panels)];
10787
+ this.history = Number.isInteger(options.history) && options.history >= 10 && options.history <= 3600 ? options.history : 300;
10788
+ if (options.history !== undefined && this.history !== options.history) throw new RangeError('dashboard history: 10-3600 seconds')
10789
+ this.maxViewers = options.maxViewers ?? 20;
10790
+ if (!Number.isInteger(this.maxViewers) || this.maxViewers < 1 || this.maxViewers > 200) throw new RangeError('dashboard maxViewers: 1-200')
10791
+ this.showIdentities = options.showIdentities ?? this.access.mode !== 'open';
10792
+
10793
+ this.server = server;
10794
+ this.startedAt = Date.now();
10795
+ this.viewers = new Map(); // cid -> { lastAt }
10796
+ this.series = []; // [{ at, ... }] one point a second, at most `history`
10797
+ this.lastHostCounters = new Map();
10798
+ this.lastJournal = new Map(); // host name -> last journal seq sent
10799
+ this.events = []; // recent events for a viewer that just arrived
10800
+
10801
+ this.host = server.host(DASHBOARD.HOST, { inbound: [DASHBOARD.IN], own: ['@' + DASHBOARD.TOPIC] });
10802
+ this.host.on('message', (from, tag, msg) => this.#onViewer(from, msg));
10803
+ this.host.on('leave', (from) => this.viewers.delete(from.cid));
10804
+ this.host.on('error', (error) => console.error('dashboard error:', error));
10805
+ this.stats = new ServerStats(server, { onSample: (value) => this.#onSample(value) });
10806
+ }
10807
+
10808
+ #access(access) {
10809
+ if (access === 'open') return { mode: 'open' }
10810
+ if (access && typeof access === 'object' && typeof access.token === 'string') {
10811
+ if (access.token.length < 8) throw new RangeError('dashboard token: at least 8 characters')
10812
+ return { mode: 'token', hash: sha(access.token) }
10813
+ }
10814
+ if (access && typeof access === 'object' && access.login && typeof access.login === 'object') {
10815
+ const roles = access.login.roles ?? ['admin'];
10816
+ const cids = access.login.cids ?? [];
10817
+ if (!Array.isArray(roles) || !Array.isArray(cids)) throw new TypeError('dashboard login: roles and cids are arrays')
10818
+ for (const role of roles) if (!ROLES.includes(role)) throw new RangeError(`dashboard login role must be one of: ${ROLES.join(', ')}`)
10819
+ return { mode: 'login', roles, cids: new Set(cids) }
10820
+ }
10821
+ throw new TypeError("dashboard access must be 'open', { token } or { login: { roles, cids } }")
10822
+ }
10823
+
10824
+ /** Whether this viewer (the server's view of it) may watch. */
10825
+ allowed(from, msg) {
10826
+ const a = this.access;
10827
+ if (a.mode === 'open') return true
10828
+ if (a.mode === 'token') return typeof msg?.token === 'string' && timingSafeEqual(sha(msg.token), a.hash)
10829
+ if (!from.authorized) return false
10830
+ return a.cids.has(from.cid) || a.roles.some((role) => hasRole({ role: from.role, boho: { isAuthorized: true } }, role))
10831
+ }
10832
+
10833
+ #onViewer(from, msg) {
10834
+ if (msg?.op === 'bye') { this.viewers.delete(from.cid); return }
10835
+ if (msg?.op !== 'hello') return
10836
+ const known = this.viewers.get(from.cid);
10837
+ if (!this.allowed(from, msg)) { this.host.to(from.cid, DASHBOARD.TOPIC, { type: 'denied', mode: this.access.mode }); return }
10838
+ if (!known && this.viewers.size >= this.maxViewers) { this.host.to(from.cid, DASHBOARD.TOPIC, { type: 'full' }); return }
10839
+ this.viewers.set(from.cid, { lastAt: Date.now() });
10840
+ if (!known) this.host.to(from.cid, DASHBOARD.TOPIC, this.#init());
10841
+ }
10842
+
10843
+ #init() {
10844
+ return {
10845
+ type: 'init', at: Date.now(), startedAt: this.startedAt, panels: this.panels, history: this.history,
10846
+ showIdentities: this.showIdentities, server: this.#serverInfo(), series: this.series, events: this.events.slice(-60),
10847
+ }
10848
+ }
10849
+
10850
+ #serverInfo() {
10851
+ const s = this.server;
10852
+ return {
10853
+ ws: s.port ?? null, tcp: s.congPort ?? null, membersOnly: s.membersOnly, anonymousQuota: s.anonymousQuota,
10854
+ quota: s.quotas?.[s.anonymousQuota] ?? null, node: process.version,
10855
+ }
10856
+ }
10857
+
10858
+ #mask(cid) {
10859
+ if (this.showIdentities) return cid
10860
+ const s = String(cid ?? '');
10861
+ return s.length <= 2 ? '••' : s.slice(0, 2) + '•'.repeat(Math.min(4, s.length - 2))
10862
+ }
10863
+
10864
+ #hosts(now) {
10865
+ const out = [];
10866
+ for (const host of this.server.hosts) {
10867
+ if (host === this.host || host.closed) continue
10868
+ const c = host.counters;
10869
+ const prev = this.lastHostCounters.get(host) ?? { ...c, at: now - 1000 };
10870
+ const sec = Math.max(0.001, (now - prev.at) / 1000);
10871
+ const rate = (k) => (c[k] - prev[k]) / sec;
10872
+ const handled = (c.inbound - prev.inbound) + (c.leaves - prev.leaves);
10873
+ this.lastHostCounters.set(host, { ...c, at: now });
10874
+ const item = {
10875
+ name: host.name, participants: host.participants.size,
10876
+ rates: { inbound: rate('inbound'), denied: rate('denied'), rejected: rate('rejected'), published: rate('published'), delivered: rate('delivered'), sent: rate('sent'), errors: rate('errors') },
10877
+ totals: { inbound: c.inbound, denied: c.denied, rejected: c.rejected, joins: c.joins, leaves: c.leaves, errors: c.errors },
10878
+ handlerAvgMs: handled > 0 ? (c.handlerMs - prev.handlerMs) / handled : 0,
10879
+ handlerMaxMs: host.handlerMaxMs,
10880
+ loops: host.loopStats(), report: host.reported,
10881
+ };
10882
+ {
10883
+ item.players = host.activity()
10884
+ .sort((a, b) => b.lastAt - a.lastAt).slice(0, PARTICIPANT_LIMIT)
10885
+ .map(({ from, inputs, firstAt, lastAt }) => ({
10886
+ cid: this.#mask(from.cid), nick: this.showIdentities ? from.nick : '', authorized: from.authorized,
10887
+ inputs, since: now - firstAt, idle: now - lastAt,
10888
+ }));
10889
+ }
10890
+ const after = this.lastJournal.get(host.name) ?? 0;
10891
+ const fresh = host.journal(after);
10892
+ if (fresh.length) this.lastJournal.set(host.name, fresh.at(-1).seq);
10893
+ for (const e of fresh) {
10894
+ this.events.push({ host: host.name, at: e.at, kind: e.kind, cid: e.cid ? this.#mask(e.cid) : undefined, tag: e.tag, reason: e.reason, message: e.message });
10895
+ }
10896
+ out.push(item);
10897
+ }
10898
+ if (this.events.length > 200) this.events.splice(0, this.events.length - 200);
10899
+ return out
10900
+ }
10901
+
10902
+ #onSample(v) {
10903
+ const now = v.at;
10904
+ for (const [cid, viewer] of this.viewers) if (now - viewer.lastAt > VIEWER_TTL_MS) this.viewers.delete(cid);
10905
+ const eventsBefore = this.events.length;
10906
+ const hosts = this.#hosts(now);
10907
+ // The dashboard's own traffic, so it can be told apart from the game's.
10908
+ const own = { viewers: this.viewers.size };
10909
+ const point = {
10910
+ at: now, cpu: v.cpuPercent, elu: v.eventLoopUtilization, eld: v.eventLoopP99Ms, rss: v.rss, heap: v.heapUsed,
10911
+ conns: v.total, ws: v.websocket, tcp: v.total - v.websocket, auth: v.authenticated,
10912
+ rxMsg: v.rates.rxMessages ?? 0, txMsg: v.rates.txMessages ?? 0, rxB: v.rates.rxBytes ?? 0, txB: v.rates.txBytes ?? 0,
10913
+ dropped: (v.rates.rateLimited ?? 0) + (v.rates.oversizeRejected ?? 0),
10914
+ hosts: Object.fromEntries(hosts.map((h) => [h.name, { in: h.rates.inbound, denied: h.rates.denied, players: h.participants, step: h.loops[0]?.stepAvg ?? null, gap: h.loops[0]?.gapP99 ?? null }])),
10915
+ };
10916
+ this.series.push(point);
10917
+ if (this.series.length > this.history) this.series.shift();
10918
+ if (!this.viewers.size) return
10919
+ const frame = {
10920
+ type: 'tick', point,
10921
+ server: {
10922
+ uptime: now - this.startedAt, states: v.states, queuedBytes: v.queuedBytes, maxQueuedBytes: v.maxQueuedBytes,
10923
+ txBlockedConnections: v.txBlockedConnections, channels: v.channels, hostTotalBytes: v.hostTotalBytes,
10924
+ counters: { rateLimited: v.counters.rateLimited, oversizeRejected: v.counters.oversizeRejected, peerRxLimitSkipped: v.counters.peerRxLimitSkipped },
10925
+ own,
10926
+ },
10927
+ hosts, events: this.events.slice(eventsBefore),
10928
+ };
10929
+ for (const cid of this.viewers.keys()) this.host.to(cid, DASHBOARD.TOPIC, frame);
10930
+ }
10931
+
10932
+ /**
10933
+ * Serves the page (GET path) and the browser client (path + '/io.js'). Returns true when it
10934
+ * answered. A Server with `port` calls it itself; with your own httpServer call it first in
10935
+ * your request handler: if (server.dashboard.handle(req, res)) return
10936
+ */
10937
+ handle(req, res) {
10938
+ let pathname;
10939
+ try { pathname = new URL(req.url || '/', 'http://localhost').pathname; } catch { return false }
10940
+ const root = this.path === '/' ? '' : this.path;
10941
+ if (pathname !== this.path && pathname !== root + '/' && pathname !== root + '/io.js') return false
10942
+ if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { Allow: 'GET, HEAD' }); res.end(); return true }
10943
+ const headers = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' };
10944
+ if (pathname === root + '/io.js') {
10945
+ readFile(IO_BUNDLE).then((js) => {
10946
+ res.writeHead(200, { ...headers, 'Content-Type': 'text/javascript; charset=utf-8' });
10947
+ res.end(req.method === 'HEAD' ? undefined : js);
10948
+ }, () => { res.writeHead(500); res.end('IOSignal browser bundle not found (build dist first)'); });
10949
+ return true
10950
+ }
10951
+ const config = {
10952
+ io: root + '/io.js', ws: this.server.wsPath || '/', access: this.access.mode, panels: this.panels,
10953
+ history: this.history, tag: DASHBOARD.IN, topic: '@' + DASHBOARD.TOPIC,
10954
+ };
10955
+ res.writeHead(200, {
10956
+ ...headers, 'Content-Type': 'text/html; charset=utf-8',
10957
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; img-src 'self' data:",
10958
+ });
10959
+ res.end(req.method === 'HEAD' ? undefined : dashboardPage(config));
10960
+ return true
10961
+ }
10962
+
10963
+ close() {
10964
+ this.stats.dispose();
10965
+ this.host.close();
10966
+ this.viewers.clear();
10967
+ }
10968
+ }
10969
+
10970
+ const STATUS = {
10971
+ OK: 0,
10972
+ //0~127: success
10973
+ //128~255: fail
10974
+ ERROR: 255
10975
+ };
10976
+
9995
10977
  /**
9996
10978
  * LocalKeyProvider.js
9997
10979
  *
@@ -10164,6 +11146,9 @@ class Server extends require$$0$3 {
10164
11146
  * options.anonymousQuota: profile of a connection that has not authenticated (default 'anonymous').
10165
11147
  * options.duplicateLogin: 'keepOld' | 'keepNew' for this Server's connections; overrides the auth
10166
11148
  * manager's own policy without changing it, so an auth manager can be shared between servers.
11149
+ * options.dashboard: true or { path, access, panels, history, maxViewers, showIdentities } shows a live
11150
+ * status page of the server and its hosts (see Dashboard.js); off by default. With `port` the Server
11151
+ * serves it itself; with your own httpServer call server.dashboard.handle(req, res) in its handler.
10167
11152
  * A failed listen (e.g. EADDRINUSE) is emitted as 'error'.
10168
11153
  * @param {any} [authManager] Optional authentication manager.
10169
11154
  */
@@ -10236,6 +11221,16 @@ class Server extends require$$0$3 {
10236
11221
  }
10237
11222
 
10238
11223
  this.manager = new Manager(this, authManager);
11224
+ // The status page; null when off.
11225
+ this.dashboard = null;
11226
+ if (options.dashboard) {
11227
+ try {
11228
+ this.dashboard = new Dashboard(this, options.dashboard);
11229
+ } catch (error) {
11230
+ this.manager.close(); // a bad dashboard option must not leave the heartbeat timer running
11231
+ throw error
11232
+ }
11233
+ }
10239
11234
 
10240
11235
  this.serverCountToListen = 0;
10241
11236
  this.listeningServerCount = 0;
@@ -10254,7 +11249,15 @@ class Server extends require$$0$3 {
10254
11249
 
10255
11250
  startWSServer() {
10256
11251
  // console.log('optoins', options )
10257
- if (this.port || this.port == 0) {
11252
+ if ((this.port || this.port == 0) && this.dashboard) {
11253
+ // The WebSocket server alone answers plain HTTP with 426; the dashboard needs pages too.
11254
+ this.ownHttp = require$$2$1.createServer((req, res) => {
11255
+ if (!this.dashboard.handle(req, res)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); }
11256
+ });
11257
+ this.ownHttp.on('error', (err) => this.onListenerError('ws', err));
11258
+ this.wss = new WebSocketServer({ server: this.ownHttp, path: this.wsPath, maxPayload: this.maxPayload });
11259
+ this.ownHttp.listen(this.port);
11260
+ } else if (this.port || this.port == 0) {
10258
11261
  this.wss = new WebSocketServer({ port: this.port , path: this.wsPath, maxPayload: this.maxPayload });
10259
11262
  } else if (this.httpServer ) {
10260
11263
  this.wss = new WebSocketServer({ server: this.httpServer, path: this.wsPath, maxPayload: this.maxPayload });
@@ -10406,6 +11409,7 @@ class Server extends require$$0$3 {
10406
11409
  */
10407
11410
  close(callback) {
10408
11411
  console.log('closing iosignal server...');
11412
+ if (this.dashboard) this.dashboard.close();
10409
11413
  for (const host of [...this.hosts]) host.close();
10410
11414
  if (this.manager) {
10411
11415
  this.manager.close();
@@ -10436,7 +11440,10 @@ class Server extends require$$0$3 {
10436
11440
  if (this.wss) {
10437
11441
  this.wss.close(() => {
10438
11442
  // console.log('wss server closed.')
10439
- onClosed();
11443
+ if (!this.ownHttp) return onClosed()
11444
+ // The HTTP server this Server made for the dashboard closes with it.
11445
+ this.ownHttp.close(() => onClosed());
11446
+ this.ownHttp.closeAllConnections?.();
10440
11447
  });
10441
11448
  }
10442
11449
 
@@ -10484,7 +11491,7 @@ class FileKeyProvider {
10484
11491
  }
10485
11492
 
10486
11493
  loadAuthInfoFile_JSON(path) {
10487
- let file = readFileSync(path);
11494
+ let file = readFileSync$1(path);
10488
11495
  file = new TextDecoder().decode(file);
10489
11496
  let list = JSON.parse(file);
10490
11497
  list.forEach(item => {
@@ -10534,11 +11541,26 @@ class RedisKeyProvider {
10534
11541
 
10535
11542
  //sudoService call
10536
11543
  async getAuthIdList() {
10537
- let result = await this.redis.keys(DEVICE_PREFIX + '*');
10538
- result = result.map(v => {
10539
- return v.split(':')[1]
10540
- });
10541
- if (result) return result
11544
+ const keys = await this.scanKeys(DEVICE_PREFIX + '*');
11545
+ return keys.map(key => key.slice(DEVICE_PREFIX.length))
11546
+ }
11547
+
11548
+ // Keys matching pattern, by SCAN: KEYS blocks Redis until it has walked every key.
11549
+ // Falls back to KEYS for a client without scan, or a redis-service from before 2026-11-17 that refuses it
11550
+ // (RemoteRedisClient answers a refused command with undefined).
11551
+ async scanKeys(pattern) {
11552
+ if (typeof this.redis.scan === 'function') {
11553
+ const keys = new Set(); // SCAN may return a key more than once
11554
+ let cursor = '0';
11555
+ do {
11556
+ const reply = await this.redis.scan(cursor, { MATCH: pattern, COUNT: 1000 });
11557
+ if (!reply || !Array.isArray(reply.keys)) break
11558
+ for (const key of reply.keys) keys.add(key);
11559
+ cursor = String(reply.cursor);
11560
+ if (cursor === '0') return [...keys]
11561
+ } while (true)
11562
+ }
11563
+ return (await this.redis.keys(pattern)) ?? []
10542
11564
  }
10543
11565
 
10544
11566
  // add device auth info
@@ -10756,12 +11778,13 @@ var sudoService = /*#__PURE__*/Object.freeze({
10756
11778
  *
10757
11779
  */
10758
11780
 
11781
+ // KEYS stays for older clients; new ones list keys with SCAN (RedisKeyProvider.scanKeys).
10759
11782
  const COMMANDS = [
10760
11783
  'GET', 'SET', 'HGETALL', 'HGET', 'HSET', 'SADD', 'SISMEMBER',
10761
- 'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SAVE',
11784
+ 'SMEMBERS', 'EXISTS', 'SREM', 'DEL', 'KEYS', 'SCAN', 'SAVE',
10762
11785
  'LPUSH', 'LTRIM', 'LRANGE', 'LINDEX', 'LSET', 'EXPIRE',
10763
11786
  'get', 'set', 'hGetAll', 'hGet', 'hSet', 'sAdd', 'sIsMember',
10764
- 'sMembers', 'exists', 'sRem', 'del', 'keys', 'save',
11787
+ 'sMembers', 'exists', 'sRem', 'del', 'keys', 'scan', 'save',
10765
11788
  'lPush', 'lTrim', 'lRange', 'lIndex', 'lSet', 'expire'
10766
11789
  ];
10767
11790