/* Official-page automation policy engine. The adapter alone owns the existing * authenticated player, verified new-arrival events, and SOOP sender methods. * This file performs no network, DOM, credential, or storage access. */ (function (root, factory) { 'use strict'; const api = factory(root); root.SoopAutoManagerEngine = api; if (typeof module === 'object' && module.exports) module.exports = api; })(globalThis, function (root) { 'use strict'; const ID = /^[a-z0-9_]{2,32}$/; const WIRE = /^([a-zA-Z0-9_]{2,32})(?:\([0-9]{1,10}\))?$/; const NUMBER = /^[1-9][0-9]{0,19}$/; const SAFE_REASON = /^[a-z0-9_]{1,80}$/; const COOLDOWN_MS = 60000; const MAX_RULES = 100; // Each registered target may have an arrival, repeat and release queued. const MAX_QUEUE = MAX_RULES * 3; const MAX_HISTORY = 100; const is = (pattern, value) => typeof value === 'string' && pattern.test(value); function baseId(value) { const match = typeof value === 'string' && WIRE.exec(value); return match ? match[1].toLowerCase() : ''; } function abort(reason = 'aborted') { const error = new Error(reason); error.code = 'ABORTED'; return error; } function text(value, limit) { return typeof value === 'string' && value.length <= limit && !/[\u0000-\u001f\u007f]/.test(value); } class Engine { constructor(options) { for (const key of ['readContext', 'hasUser', 'sendMute', 'sendKick']) { if (!options || typeof options[key] !== 'function') throw new TypeError('invalid_adapter'); } this.adapter = options; this.clock = options.clock || Date.now; // Window timers reject an Engine receiver in browser main world. // Keep injected timer semantics; native calls retain the global owner. this.setTimer = options.setTimeout || ((...args) => root.setTimeout(...args)); this.clearTimer = options.clearTimeout || ((...args) => root.clearTimeout(...args)); this.requestTimeoutMs = Math.min(15000, Math.max(1, options.requestTimeoutMs ?? 5000)); this.cancelEventWaitMs = Math.min(10000, Math.max(0, options.cancelEventWaitMs ?? 5000)); this.kickEventWaitMs = Math.min(10000, Math.max(0, options.kickEventWaitMs ?? 5000)); this.muteEventWaitMs = Math.min(10000, Math.max(0, options.muteEventWaitMs ?? 5000)); this.contextPollMs = Math.min(1000, Math.max(10, options.contextPollMs ?? 250)); this.lastSendAt = -Infinity; this.enabled = false; this.starting = false; this.reason = 'disabled'; this.context = null; this.rules = new Map(); this.targetEpochs = new Map(); this.cooldowns = new Map(); this.interference = new Map(); this.expectedDepartures = new Map(); this.pending = new Map(); this.awaitingKicks = new Map(); this.muteSeries = new Map(); this.muteRepeats = new Map(); this.consumedBlindReleases = new Set(); this.blindKicks = new Set(); this.actions = []; this.queue = []; this.priorityWaiters = new Set(); this.pumping = false; this.inFlight = new Set(); this.version = 0; this.sequence = 0; this.controller = null; this.watchTimer = null; } _read() { try { const context = this.adapter.readContext(); if (!context || !is(ID, context.bjId) || !is(NUMBER, context.bno) || !is(NUMBER, context.chatNo) || !baseId(context.accountId) || !baseId(context.selfWireId) || baseId(context.selfWireId) !== baseId(context.accountId) || !['bj', 'manager'].includes(context.role) || (context.role === 'bj' && baseId(context.accountId) !== context.bjId) || !context.connectionToken || context.connected !== true || context.joined !== true) return null; return { bjId: context.bjId, bno: context.bno, chatNo: context.chatNo, accountId: context.accountId, selfWireId: context.selfWireId, role: context.role, connectionToken: context.connectionToken, connected: true, joined: true }; } catch (_) { return null; } } _emit(strict = false) { try { if (typeof this.adapter.onChange === 'function') this.adapter.onChange(this.getStatus()); } catch (error) { if (strict) throw error; /* UI cannot authorize actions. */ } } getStatus() { return { enabled: this.enabled, running: this.enabled, busy: this.pumping, bjId: this.context?.bjId || '', bno: this.context?.bno || '', accountId: this.context?.accountId || '', selfWireId: this.context?.selfWireId || '', role: this.context?.role || '', connected: Boolean(this.enabled && this.context?.connected), reason: this.reason, pending: this.pending.size, actions: this.actions.map(action => ({ ...action })) }; } start(rules) { this.stop('restarted'); const version = this.version; const context = this._read(); if (!context) { this.reason = 'permission_unverified'; this._emit(); return { ok: false, reason: this.reason }; } const parsed = new Map(); if (!Array.isArray(rules) || !rules.length || rules.length > MAX_RULES) { this.reason = 'invalid_rules'; this._emit(); return { ok: false, reason: this.reason }; } for (const rule of rules) { const autoCancel = rule?.autoCancel === undefined ? false : rule.autoCancel; const delay = rule?.cancelDelaySeconds === undefined ? 30 : rule.cancelDelaySeconds; const muteCount = rule?.muteCount === undefined ? 1 : rule.muteCount; const repeatMute = rule?.repeatMute ?? false; const targetEnabled = rule?.enabled ?? true; const autoCancelBlindKick = rule?.autoCancelBlindKick ?? false; const blindCancelDelaySeconds = rule?.blindCancelDelaySeconds ?? 1; if (!rule || !is(ID, rule.targetId) || parsed.has(rule.targetId) || !['mute', 'kick'].includes(rule.action) || typeof autoCancel !== 'boolean' || (autoCancel && rule.action !== 'kick') || !Number.isInteger(delay) || delay < 0 || delay > 300 || !Number.isSafeInteger(muteCount) || muteCount < 1 || typeof repeatMute !== 'boolean' || (repeatMute && rule.action !== 'mute') || typeof targetEnabled !== 'boolean' || typeof autoCancelBlindKick !== 'boolean' || !Number.isInteger(blindCancelDelaySeconds) || blindCancelDelaySeconds < 0 || blindCancelDelaySeconds > 300 || rule.targetId === context.bjId || rule.targetId === baseId(context.accountId)) { this.reason = 'invalid_rules'; this._emit(); return { ok: false, reason: this.reason }; } parsed.set(rule.targetId, Object.freeze({ targetId: rule.targetId, action: rule.action, enabled:targetEnabled, autoCancel, cancelDelaySeconds: delay, muteCount, repeatMute, autoCancelBlindKick, blindCancelDelaySeconds })); } let present; try { const rows = this.adapter.getPresentUsers === undefined ? [] : this.adapter.getPresentUsers([...parsed].filter(([,rule])=>rule.enabled).map(([id])=>id)); if (!Array.isArray(rows)) { // The adapter contract is synchronous. Consume an accidental async // rejection without exposing its response/error while rejecting Start. if (rows && typeof rows.then === 'function') Promise.resolve(rows).catch(() => {}); throw new Error('invalid_initial_presence'); } if (rows.length > 10000) throw new Error('invalid_initial_presence'); const seen = new Set(); present = []; for (const row of rows) { const targetId = baseId(row?.wireId); if (!targetId || !text(row.nick, 512)) throw new Error('invalid_initial_presence'); if (parsed.get(targetId)?.enabled && !seen.has(targetId)) { seen.add(targetId); present.push(Object.freeze({ wireId: row.wireId, nick: row.nick })); } } } catch (_) { this.stop('initial_presence_unverified'); return { ok: false, reason: this.reason }; } if (version !== this.version) return { ok: false, reason: this.reason || 'start_aborted' }; try { this.rules = parsed; this.targetEpochs.clear(); this.interference.clear(); this.context = Object.freeze(context); this.controller = new AbortController(); this.starting = true; this.enabled = true; this.reason = ''; this._watch(version); this._emit(true); if (version !== this.version || !this.checkContext()) { this.starting = false; return { ok: false, reason: this.reason || 'start_aborted' }; } // A successful manual Start is a new instruction for the targets // actually present in its verified snapshot. Do not let the previous // run's cooldown silently suppress them. Once submitted, the normal // cooldown still deduplicates this snapshot and live duplicate events. for (const entry of present) this.cooldowns.delete(baseId(entry.wireId)); this.starting = false; } catch (_) { this.stop('start_failed'); return { ok: false, reason: this.reason }; } // A manual Start explicitly includes this one captured presence view. // Subsequent roster refreshes never enter this path. Waiting for each // action avoids dropping rules when the snapshot exceeds queue capacity. Promise.resolve().then(async () => { for (const entry of present) { if (!this.enabled || version !== this.version) return; await this.onEntry(entry); } }).catch(() => { if (this.enabled && version === this.version) this.stop('initial_presence_unverified'); }); return { ok: true, reason: '' }; } setTargetEnabled(targetId, enabled) { const old = this.rules.get(targetId); if (!old || typeof enabled !== 'boolean' || !this.checkContext()) return {ok:false,reason:'permission_or_connection_changed'}; if (old.enabled === enabled) return {ok:true}; let present = null; if (enabled) { try { const rows = this.adapter.getPresentUsers?.([targetId]) ?? []; if (!Array.isArray(rows) || rows.length > 10000) throw abort(); for (const row of rows) { if (!baseId(row?.wireId) || !text(row.nick,512)) throw abort(); if (baseId(row.wireId) === targetId && !present) present = {...row}; } } catch (_) { return {ok:false,reason:'initial_presence_unverified'}; } } if (!this.checkContext() || this.rules.get(targetId) !== old) return {ok:false,reason:'context_changed'}; this.targetEpochs.set(targetId,(this.targetEpochs.get(targetId) || 0)+1); this.rules.set(targetId,Object.freeze({...old,enabled})); this._cancelMuteRepeat(targetId,'target_disabled'); const mute = this.muteSeries.get(targetId); if (mute) { mute.cancelled = true; mute.resolve?.(); } const kick = this.awaitingKicks.get(targetId); if (kick) { this.awaitingKicks.delete(targetId); kick.resolve(); } const pending = this.pending.get(targetId); if (pending) { if (pending.timer !== null) this.clearTimer(pending.timer); this.pending.delete(targetId); pending.resolveCancel?.(); pending.action.cancelState='aborted';pending.action.cancelReason='target_disabled'; } this.expectedDepartures.delete(targetId); this.blindKicks.delete(targetId); this._emit(); if (enabled && present) { this.cooldowns.delete(targetId); this.onEntry(present).catch(()=>{}); } return {ok:true}; } stop(reason = 'user_stop') { this.enabled = false; this.starting = false; this.version++; this.reason = is(SAFE_REASON, reason) ? reason : 'stopped'; if (this.controller) { try { this.controller.abort(); } catch (_) { /* Still revoke locally. */ } } if (this.watchTimer !== null) { try { this.clearTimer(this.watchTimer); } catch (_) { /* Generation guard retires it. */ } } this.watchTimer = null; for (const record of this.pending.values()) { if (record.timer !== null) { try { this.clearTimer(record.timer); } catch (_) { /* Pending identity guard retires it. */ } } if (!record.cancelObserved) { record.action.cancelState = 'aborted'; record.action.cancelReason = this.reason; } } this.pending.clear(); this.awaitingKicks.clear(); for (const record of this.muteSeries.values()) { record.cancelled = true; record.action.state = 'aborted'; record.action.reason = 'mute_series_stopped'; } this.muteSeries.clear(); for (const targetId of this.muteRepeats.keys()) this._cancelMuteRepeat(targetId, this.reason); this.consumedBlindReleases.clear(); this.blindKicks.clear(); this.expectedDepartures.clear(); for (const job of this.queue.splice(0)) job.resolve({ state: 'aborted', reason: this.reason }); try { this._emit(); } catch (_) { /* Cleanup cannot leave activation half-finished. */ } } checkContext() { if (!this.enabled) return false; const current = this._read(); if (!current || !this.context || ['bjId', 'bno', 'chatNo', 'accountId', 'selfWireId', 'role', 'connectionToken'] .some(key => current[key] !== this.context[key])) { this.stop('context_changed'); return false; } return true; } _watch(version) { this.watchTimer = this.setTimer(() => { this.watchTimer = null; if (version === this.version && this.checkContext()) { try { this._watch(version); } catch (_) { this.stop('timer_unavailable'); } } }, this.contextPollMs); } _targetGuard(version, targetId, targetEpoch) { this._guard(version); if (this.rules.get(targetId)?.enabled === false || (targetEpoch !== undefined && (this.targetEpochs.get(targetId) || 0) !== targetEpoch)) throw abort('target_disabled'); } _guard(version, wireId, targetEpoch) { if (version !== this.version || !this.checkContext()) throw abort(); if (wireId) { if (this.rules.get(baseId(wireId))?.enabled === false || (targetEpoch !== undefined && (this.targetEpochs.get(baseId(wireId)) || 0) !== targetEpoch)) throw abort('target_disabled'); let present = false; try { present = this.adapter.hasUser(wireId) === true; } catch (_) { /* Fail closed. */ } if (!present) throw abort('target_not_present'); } if (!this.enabled || version !== this.version) throw abort(); } async _bounded(value, version, timeout = this.requestTimeoutMs) { const operation = Promise.resolve(value); operation.catch(() => {}); // A scope change can abort before race attaches. this._guard(version); const signal = this.controller.signal; let timer, onAbort; const boundary = new Promise((_, reject) => { onAbort = () => reject(abort()); signal.addEventListener('abort', onAbort, { once: true }); timer = this.setTimer(() => reject(new Error('adapter_timeout')), timeout); }); try { return await Promise.race([operation, boundary]); } finally { signal.removeEventListener('abort', onAbort); this.clearTimer(timer); } } async _sleep(ms, version, priority = false) { this._guard(version); const signal = this.controller.signal; let timer, onAbort, wake; try { await new Promise((resolve, reject) => { onAbort = () => reject(abort()); signal.addEventListener('abort', onAbort, { once: true }); if (priority) { wake = resolve; this.priorityWaiters.add(wake); } timer = this.setTimer(resolve, ms); }); } finally { signal.removeEventListener('abort', onAbort); this.clearTimer(timer); if (wake) this.priorityWaiters.delete(wake); } } async _sendGap(version) { for (;;) { await this._drainCancellations(version); this._guard(version); const delay = 1000 - (this.clock() - this.lastSendAt); if (delay <= 0) return; // Cancellation wakes this wait; only a new mute/kick needs the gap. await this._sleep(delay, version, true); } } async _waitResponse(response, version, timeout) { // Adapter sends have completed before entering this wait. Yielding here // keeps one sender owner while letting a confirmed removal be released // without waiting for an unrelated mute/kick acknowledgement timeout. let settled = false; const operation = Promise.resolve(response).then(value => { settled = true; return value; }); operation.catch(() => {}); const until = this.clock() + timeout; for (;;) { this._guard(version); if (settled) return operation; await this._drainCancellations(version); this._guard(version); if (settled) return operation; const remaining = until - this.clock(); if (remaining <= 0) throw new Error('adapter_timeout'); let wake; const priority = new Promise(resolve => { wake = resolve; this.priorityWaiters.add(wake); }); try { await this._bounded(Promise.race([operation, priority]), version, remaining); } finally { this.priorityWaiters.delete(wake); } } } _enqueue(run, version, priority = false) { if (!this.enabled || version !== this.version) return Promise.resolve({ state: 'aborted', reason: 'disabled' }); if (this.queue.length >= MAX_QUEUE) return Promise.resolve({ state: 'skipped', reason: 'queue_limit' }); const promise = new Promise(resolve => { const job = {run,resolve,version,priority}; if (priority) this.queue.unshift(job); else this.queue.push(job); }); if (priority) for (const wake of this.priorityWaiters) wake(); this._pump(); return promise; } async _drainCancellations(version) { for (const [targetId, record] of this.pending) { if (!record.queued && record.action.cancelAt <= this.clock()) this._queueCancel(targetId,record); } while (this.queue[0]?.priority) { this._guard(version); const job = this.queue.shift(); if (job.version !== this.version) { job.resolve({state:'aborted',reason:'disabled'}); continue; } try { job.resolve(await job.run()); } catch (_) { job.resolve({state:'unknown',reason:'operation_unverified'}); } } } async _pump() { if (this.pumping) return; this.pumping = true; try { while (this.queue.length) { const job = this.queue.shift(); if (job.version !== this.version || !this.enabled) { job.resolve({ state: 'aborted', reason: 'disabled' }); continue; } try { job.resolve(await job.run()); } catch (_) { job.resolve({ state: 'unknown', reason: 'operation_unverified' }); } } } finally { this.pumping = false; this._emit(); } } onEntry({ wireId, nick, newArrival = false } = {}) { const targetId = baseId(wireId); if (!targetId || !text(nick, 512)) return Promise.resolve({ state: 'skipped', reason: 'invalid_entry' }); if (this.starting) return Promise.resolve({ state: 'skipped', reason: 'start_pending' }); if (!this.enabled || !this.rules.has(targetId) || this.rules.get(targetId).enabled === false) return Promise.resolve({ state: 'skipped', reason: 'not_target' }); if (!this.checkContext()) return Promise.resolve({ state: 'aborted', reason: 'context_changed' }); if (newArrival === true) { this.onDeparture(wireId); this.blindKicks.delete(targetId); } // A proven re-entry ends the departure expected from our earlier kick. // Never use a later re-kick as authority to release the older sanction. if (newArrival === true && this.pending.get(targetId)?.cancelSent) { this.expectedDepartures.delete(targetId); } else if (this.expectedDepartures.has(targetId)) { this.expectedDepartures.delete(targetId); this.onPotentialKick(wireId); } const version = this.version; const rule = this.rules.get(targetId); const targetEpoch = this.targetEpochs.get(targetId) || 0; // Runtime calls this for proven new arrivals; Start also submits its one // explicitly captured existing-target view. Never submit roster/history. return this._enqueue(() => this._initial({ wireId, nick, targetId, targetEpoch, newArrival: newArrival === true }, rule, version), version); } onPotentialKick(wireId) { const targetId = baseId(wireId); if (!targetId || !this.rules.has(targetId)) return; this._cancelMuteRepeat(targetId, 'intervening_kick'); const expected = this.expectedDepartures.get(targetId); if (expected && expected.version === this.version && expected.wireId === wireId && !expected.seen) { // The 0076 acknowledgement and 0004 departure can arrive in either // order. Consume only the first departure of our exact target; // cancellation still requires the matching successful 0076 response. expected.seen = true; return; } this.interference.set(targetId, (this.interference.get(targetId) || 0) + 1); const record = this.pending.get(targetId); if (record && !record.cancelObserved) { if (record.timer !== null) this.clearTimer(record.timer); this.pending.delete(targetId); this.expectedDepartures.delete(targetId); record.action.cancelState = 'aborted'; record.action.cancelReason = 'intervening_kick'; this._emit(); } } onForcedExit(wireId, nick, reason) { const targetId = baseId(wireId), rule = this.rules.get(targetId); if (!targetId || !text(nick,512) || ![2,3,4,5].includes(reason) || !rule || rule.enabled === false || !this.checkContext()) return false; this.onDeparture(wireId); if (reason !== 5 || !rule.autoCancelBlindKick) { if (reason !== 2) this.expectedDepartures.delete(targetId); this.onPotentialKick(wireId); return false; } // A live 0004 reason 5 explicitly identifies blind-escape removal. Do // not infer it from absence, a mute count, or a kick-list snapshot. if (this.blindKicks.has(targetId)) return false; const version = this.version; this.expectedDepartures.delete(targetId); this.onPotentialKick(wireId); if (version !== this.version || !this.checkContext()) return false; this.blindKicks.add(targetId); const action = this._record({wireId,targetId,nick}, {action:'blind_kick'}); if (version !== this.version || !this.checkContext()) return false; action.state = 'confirmed'; action.reason = 'blind_kick_confirmed'; const row = {id:wireId,nick,time:`0004:${action.id}`}; this.expectedDepartures.set(targetId, {wireId,version,seen:true}); this._scheduleCancel(targetId,row,{cancelDelaySeconds:rule.blindCancelDelaySeconds}, action,version,this.interference.get(targetId) || 0); this._emit(); return true; } onCancellation(wireId) { const targetId = baseId(wireId), record = this.pending.get(targetId); if (!record || !record.cancelSent || record.version !== this.version || !this.checkContext() || record.cancelObserved) return false; record.cancelObserved = true; record.action.cancelState = 'confirmed'; record.action.cancelReason = 'cancel_packet_confirmed'; if (record.resolveCancel) record.resolveCancel(); this._emit(); return true; } onDeparture(wireId) { this.consumedBlindReleases.delete(wireId); const repeat = this.muteRepeats.get(baseId(wireId)); if (repeat?.entry.wireId === wireId) this._cancelMuteRepeat(baseId(wireId), 'target_departed'); const record = this.muteSeries.get(baseId(wireId)); if (!record || record.wireId !== wireId) return; record.cancelled = true; if (record.resolve) record.resolve(); } onMuteAcknowledged(wireId, nick, count, actorId, durationSeconds) { const reject = reason => { this.lastMuteResponseReason = reason; return false; }; const record = this.muteSeries.get(baseId(wireId)); if (!record || !record.sent) return reject('mute_no_pending_request'); if (record.observed) return reject('mute_duplicate_response'); if (record.cancelled || record.version !== this.version || !this.checkContext()) return reject('mute_scope_changed'); // A nickname is mutable display text, not the command identity. The // server may canonicalize a target to its unsuffixed account ID, but an // explicit different target connection must never acknowledge this send. if (wireId !== record.wireId && (wireId.includes('(') || baseId(wireId) !== baseId(record.wireId))) return reject('mute_target_mismatch'); if (!baseId(actorId) || baseId(actorId) !== baseId(this.context.selfWireId)) return reject('mute_actor_mismatch'); if (!Number.isSafeInteger(count) || count < 1 || count < record.lastCount || (count === record.lastCount && count < 3)) return reject('mute_count_mismatch'); this.lastMuteResponseReason = 'mute_packet_confirmed'; record.observed = true; record.lastCount = count; record.lastAckAt = this.clock(); record.durationSeconds = Number.isSafeInteger(durationSeconds) && durationSeconds > 0 && durationSeconds <= 86400 ? durationSeconds : null; record.action.muteConfirmed++; record.action.muteServerCount = count; record.action.muteDurationSeconds = record.durationSeconds; if (text(nick,512) && nick.trim()) record.action.nick = nick; record.resolve(); this._emit(); return true; } _cancelMuteRepeat(targetId, reason) { const record = this.muteRepeats.get(targetId); if (!record) return; this.muteRepeats.delete(targetId); if (record.timer !== null) this.clearTimer(record.timer); record.action.repeatState = 'stopped'; record.action.repeatReason = reason; delete record.action.repeatAt; } _scheduleMuteRepeat(entry, rule, action, version, acknowledgement) { this._guard(version, entry.wireId, entry.targetEpoch); this._cancelMuteRepeat(entry.targetId, 'replaced'); const blind = acknowledgement.lastCount >= 3; if (!blind && acknowledgement.durationSeconds === null) { action.repeatState = 'stopped'; action.repeatReason = 'duration_unverified'; return; } const record = {entry:{...entry}, rule, action, version, timer:null, state:blind ? 'blind' : 'timer', releaseAfter:acknowledgement.lastAckAt + 1000, interference:this.interference.get(entry.targetId) || 0}; // SOOP may broadcast only release transitions, without a matching set // transition. A fresh successful mute ACK arms the next cycle. Ignore // duplicate old releases immediately following that ACK. if (blind) this.consumedBlindReleases.delete(entry.wireId); this.muteRepeats.set(entry.targetId, record); action.repeatState = blind ? 'waiting_blind' : 'waiting_timer'; if (!blind) { action.repeatAt = acknowledgement.lastAckAt + acknowledgement.durationSeconds * 1000; record.timer = this.setTimer(() => { record.timer = null; this._queueMuteRepeat(entry.targetId, record); }, Math.max(0, action.repeatAt - this.clock())); } } onUserFlag(wireId, oldFlag, newFlag) { const targetId = baseId(wireId), record = this.muteRepeats.get(targetId); if (!Number.isInteger(oldFlag) || !Number.isInteger(newFlag) || oldFlag < 0 || newFlag < 0 || oldFlag > 4294967295 || newFlag > 4294967295 || !baseId(wireId) || !this.enabled || !this.rules.has(targetId) || this.rules.get(targetId).enabled === false || !this.checkContext()) return false; if ((newFlag & 2048) && !(oldFlag & 2048)) this.consumedBlindReleases.delete(wireId); if (!record || record.state !== 'blind' || wireId !== record.entry.wireId || !(oldFlag & 2048) || (newFlag & 2048) || this.clock() < record.releaseAfter || this.consumedBlindReleases.has(wireId)) return false; this.consumedBlindReleases.add(wireId); this._queueMuteRepeat(targetId, record); return true; } _queueMuteRepeat(targetId, record) { if (this.muteRepeats.get(targetId) !== record || !['timer','blind'].includes(record.state)) return; try { this._guard(record.version, record.entry.wireId, record.entry.targetEpoch); } catch (_) { this._cancelMuteRepeat(targetId, 'send_guard_changed'); this._emit(); return; } if ((this.interference.get(targetId) || 0) !== record.interference || this.queue.length >= MAX_QUEUE) { this._cancelMuteRepeat(targetId, 'repeat_conditions_changed'); this._emit(); return; } record.state = 'queued'; record.action.repeatState = 'queued'; delete record.action.repeatAt; this._enqueue(async () => { if (this.muteRepeats.get(targetId) !== record) return; try { this._guard(record.version, record.entry.wireId, record.entry.targetEpoch); if ((this.interference.get(targetId) || 0) !== record.interference) throw abort(); this.muteRepeats.delete(targetId); record.action.repeatState = 'sent'; this.inFlight.add(targetId); const nextRule = {...record.rule, muteCount:1}; const action = this._record(record.entry, nextRule); action.repeatFollowup = true; return await this._mute({...record.entry, minimumCount:record.action.muteServerCount}, nextRule, action, record.version); } catch (_) { if (this.muteRepeats.get(targetId) === record) this._cancelMuteRepeat(targetId, 'send_guard_changed'); record.action.repeatState = 'stopped'; record.action.repeatReason = 'send_guard_changed'; } finally { this.inFlight.delete(targetId); this._emit(); } }, record.version); this._emit(); } async _mute(entry, rule, action, version) { const record = {wireId:entry.wireId, nick:entry.nick, version, action, sent:false, observed:false, cancelled:false, lastCount:entry.minimumCount || 0, resolve:null}; action.muteRequested = rule.muteCount; action.muteSent = 0; action.muteConfirmed = 0; this.muteSeries.set(entry.targetId, record); try { for (let index=0; index { record.resolve = resolve; }); action.state = 'requested'; action.reason = 'mute_requested'; action.muteSent++; this.lastSendAt = this.clock(); await this._bounded(this.adapter.sendMute(entry.wireId), version); this._emit(); if (!record.observed && this.muteEventWaitMs) { try { await this._waitResponse(response, version, this.muteEventWaitMs); } catch (error) { if (error?.code === 'ABORTED') throw error; } } record.sent = false; if (record.cancelled) throw abort(); if (!record.observed) { action.state = 'unknown'; action.reason = 'mute_result_unverified'; break; } action.state = 'confirmed'; action.reason = 'mute_packet_confirmed'; if (record.lastCount >= 3) action.reason = 'mute_blind_confirmed'; } if (rule.repeatMute && action.state === 'confirmed' && action.muteConfirmed === rule.muteCount) this._scheduleMuteRepeat(entry, rule, action, version, record); } catch (error) { action.state = error?.code === 'ABORTED' ? 'aborted' : 'unknown'; action.reason = error?.code === 'ABORTED' ? 'mute_series_stopped' : 'mute_result_unverified'; } finally { if (this.muteSeries.get(entry.targetId) === record) this.muteSeries.delete(entry.targetId); this._emit(); } return {...action}; } onKickAcknowledged(wireId, nick) { const record = this.awaitingKicks.get(baseId(wireId)); if (!record || !record.sent || record.version !== this.version || !this.checkContext() || record.observed || !text(nick,512) || nick !== record.nick) return false; record.observed = true; record.row = {id:wireId,nick,time:`0076:${record.action.id}`,actorId:this.context.selfWireId}; record.resolve(); return true; } _record(entry, rule) { const action = { id: ++this.sequence, targetId: entry.targetId, wireId: entry.wireId, nick: text(entry.nick,512) ? entry.nick : '', bjId:this.context?.bjId || '', bno:this.context?.bno || '', accountId:this.context?.accountId || '', action: rule.action, state: 'reserved', reason: '', at: this.clock() }; this.actions.push(action); if (this.actions.length > MAX_HISTORY) this.actions.shift(); this._emit(); return action; } async _initial(entry, rule, version) { let action = null, attempted = false, kickAck = null; const last = this.cooldowns.get(entry.targetId); // A verified absent -> present transition is a new visit, not a retry of // the earlier action. Snapshot duplicates keep their cooldown; a verified // manual Start resets only its captured targets before reaching this path. // The runtime alone marks single live additions after deduplicating them. if (!entry.newArrival && last !== undefined && this.clock() - last < COOLDOWN_MS) return { state: 'skipped', reason: 'target_cooldown' }; if (this.inFlight.has(entry.targetId)) return { state: 'skipped', reason: 'already_pending' }; for (const [target, at] of this.cooldowns) if (this.clock() - at >= COOLDOWN_MS) this.cooldowns.delete(target); if (this.cooldowns.size >= 1000) return { state: 'skipped', reason: 'cooldown_capacity' }; this.inFlight.add(entry.targetId); try { this._guard(version, entry.wireId, entry.targetEpoch); await this._sendGap(version); this._guard(version, entry.wireId, entry.targetEpoch); action = this._record(entry, rule); this.cooldowns.set(entry.targetId, this.clock()); action.state = 'requested'; action.reason = rule.action === 'mute' ? 'mute_requested' : 'kick_requested'; // All async work is complete before this final same-connection check. this._guard(version, entry.wireId, entry.targetEpoch); if (rule.action === 'mute') { attempted = true; return await this._mute(entry, rule, action, version); } this.onPotentialKick(entry.wireId); // Retire an older pending cancellation first. this._guard(version, entry.wireId, entry.targetEpoch); // Retiring may notify a UI callback which stops us. const interference = this.interference.get(entry.targetId) || 0; this.expectedDepartures.set(entry.targetId, {wireId: entry.wireId, version, seen: false}); const ackEvent = new Promise(resolve => { kickAck = {version, nick:entry.nick, action, sent:false, observed:false, row:null, resolve}; }); this.awaitingKicks.set(entry.targetId, kickAck); attempted = true; this.lastSendAt = this.clock(); kickAck.sent = true; await this._bounded(this.adapter.sendKick(entry.wireId, entry.nick, 0), version); // A local send return is not success; only the matching 0076 server // acknowledgement can authorize the optional cancellation. if (!kickAck.observed && this.kickEventWaitMs) { try { await this._waitResponse(ackEvent, version, this.kickEventWaitMs); } catch (error) { if (error?.code === 'ABORTED') throw error; } } this._targetGuard(version,entry.targetId,entry.targetEpoch); const confirmed = kickAck.observed ? kickAck.row : null; if (!confirmed) { action.state = 'unknown'; action.reason = 'kick_result_unverified'; } else { action.state = 'confirmed'; action.reason = 'own_kick_packet_confirmed'; if (rule.autoCancel) { if ((this.interference.get(entry.targetId) || 0) !== interference) { action.cancelState = 'aborted'; action.cancelReason = 'intervening_kick'; } else this._scheduleCancel(entry.targetId, confirmed, rule, action, version, interference); } } } catch (error) { if (action) { action.state = attempted ? 'unknown' : 'aborted'; action.reason = attempted ? 'send_result_unverified' : 'send_guard_changed'; } return action ? { ...action } : { state: error?.code === 'ABORTED' ? 'aborted' : 'skipped', reason: error?.code === 'ABORTED' ? 'send_guard_changed' : 'operation_unverified' }; } finally { this.inFlight.delete(entry.targetId); if (this.awaitingKicks.get(entry.targetId) === kickAck) this.awaitingKicks.delete(entry.targetId); if (!this.pending.has(entry.targetId)) this.expectedDepartures.delete(entry.targetId); this._emit(); } return { ...action }; } _scheduleCancel(targetId, row, rule, action, version, interference) { this._guard(version); const record = { row, action, version, interference, timer: null, targetEpoch:this.targetEpochs.get(targetId) || 0, queued:false, cancelSent:false, cancelObserved:false, resolveCancel:null }; action.cancelState = 'scheduled'; action.cancelAt = this.clock() + rule.cancelDelaySeconds * 1000; this.pending.set(targetId, record); if (rule.cancelDelaySeconds === 0) { // No timer or sender gap: the successful kick ACK / reason 5 already // authorized this release. The priority queue still owns the sender. this._queueCancel(targetId, record); return; } record.timer = this.setTimer(() => { record.timer = null; this._queueCancel(targetId,record); }, rule.cancelDelaySeconds * 1000); } _queueCancel(targetId,record) { if (this.pending.get(targetId) !== record || record.queued) return; record.queued = true; if (record.timer !== null) this.clearTimer(record.timer); record.timer = null; this._enqueue(() => this._cancel(targetId,record),record.version,true).then(result => { if (result.state === 'skipped' && this.pending.get(targetId) === record) { this.pending.delete(targetId); record.action.cancelState = 'aborted'; record.action.cancelReason = result.reason; this._emit(); } }); } async _cancel(targetId, record) { let attempted = false; try { this._targetGuard(record.version,targetId,record.targetEpoch); if (this.pending.get(targetId) !== record || (this.interference.get(targetId) || 0) !== record.interference) throw abort(); // Cancellation targets the exact acknowledged command, never a rule's // bare base ID or a newly reappearing/changed sanction. attempted = true; this.lastSendAt = this.clock(); const cancelEvent = new Promise(resolve => { record.resolveCancel = resolve; }); record.cancelSent = true; await this._bounded(this.adapter.sendKick(record.row.id, record.row.nick, 1), record.version); if (!record.cancelObserved) { record.action.cancelState = 'requested'; record.action.cancelReason = 'cancel_requested'; } this._emit(); // The acting BJ/manager can receive 0076 type 1 directly. Waiting for // that acknowledgement is required before reporting cancellation success. if (!record.cancelObserved && this.cancelEventWaitMs) { try { await this._waitResponse(cancelEvent, record.version, this.cancelEventWaitMs); } catch (error) { if (error?.code === 'ABORTED') throw error; } } if (record.cancelObserved) return {state:'confirmed', reason:record.action.cancelReason}; this._targetGuard(record.version,targetId,record.targetEpoch); if (this.pending.get(targetId) !== record) throw abort(); throw new Error('cancel_result_unverified'); } catch (_) { if (record.cancelObserved) return {state:'confirmed', reason:record.action.cancelReason}; record.action.cancelState = attempted ? 'unknown' : 'aborted'; record.action.cancelReason = attempted ? 'cancel_result_unverified' : 'cancel_guard_changed'; return { state: record.action.cancelState, reason: record.action.cancelReason }; } finally { record.resolveCancel = null; if (this.pending.get(targetId) === record) this.pending.delete(targetId); this.expectedDepartures.delete(targetId); this._emit(); } } } return Object.freeze({ Engine, baseId, COOLDOWN_MS, MAX_RULES }); });