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