netanalyzer/remoteAgent.js
Joseph McQueen b3c37bd7df feat: st command suite, Webex phone + Atlas AV integrations, dockerized remote agent
Rebrand NetAnalyzer -> StoreHealthAnalyzer and consolidate the store
reporting surface into a single `st [number]` command with focused
sub-modes.

Commands
- st [number]                - general info (SIW + brands + Meraki net link)
- st [number] network        - switches, APs, store server
- st [number] pos            - registers, payment terminals, customer display
- st [number] ios            - MDM-tracked iOS hardware
- st [number] phone          - wired 78xx + DECT basestations/handsets with
                               registration state, extensions and main DID
- st [number] av             - Atlas AMPs + MDM-tracked Apple TVs, video
                               walls, music players, LED displays
- Removed `analyze` in favor of the unified `st` surface

Integrations
- integrations/webex: Service App OAuth with rotating refresh tokens,
  seed + cleanup scripts, tokens/ storage (git-ignored)
- integrations/atlas: Xyte client + cached device discovery keyed on
  zero-padded 6-digit store numbers, cold-cache failure -> unavailable
  banner instead of a misleading empty result
- services/webexPhone, services/webexService, services/avService: shape
  raw upstream data into the report layer's contract
- utils/merakiMatcher: FQDN hostname extraction so payment terminals
  match Meraki descriptions; case-insensitive lookup
- utils/chunkReport: split long markdown replies at 7000-char boundaries

Reliability / ops
- server.js: awaited framework.stop() + 8s hard-kill timer so nodemon /
  Docker restarts don't leak WDM device registrations ("excessive device
  registrations")
- nodemon.json: SIGINT so the graceful path always runs
- scripts/cleanupWebexDevices.js: one-shot WDM cleanup utility
- Group-space routing: hears() regexes tolerate the leading @BotName
  prefix Webex prepends to mentions
- Replaced HTML-unsafe <number> placeholders with [number] in all help
  strings

Remote agent containerization
- docker/remote-agent/: multi-stage node:22-alpine image, non-root user,
  tini for signal handling, minimal deps (ws/axios/dotenv)
- docker/remote-agent/package.sh: docker buildx build defaulting to
  linux/amd64 (with override), saves image + assembles deploy/ + writes
  SHA256 + zips for offline transfer
- docker/remote-agent/deploy/: runtime docker-compose.yml, install.sh
  with platform sanity check, remote-host README
- .dockerignore + .gitignore updates for build artifacts and dist bundles
- npm run agent:package convenience script

Cleanup
- Dropped storeHealth.js / HealthReport.js and their tests/mocks in favor
  of the shared storeDetail pipeline
- Store model handles null SIW records gracefully; toSummary always
  ends with a newline so the Meraki link sits on its own line

Tests
- 144 tests across 14 suites passing; new coverage for atlasClient,
  atlasDevices, avService, avCategory classification, webexPhone,
  webexServiceAppAuth, storeDetail integration, siw, chunkReport and
  the updated meraki matcher

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-06 09:54:41 -04:00

120 lines
2.9 KiB
JavaScript

const WebSocket = require('ws');
const axios = require('axios');
require('dotenv').config();
const WS_URL = process.env.WS_URL;
const WS_TOKEN = process.env.WS_TOKEN;
if (!WS_URL) {
console.error('❌ WS_URL is not set in .env');
process.exit(1);
}
const INITIAL_BACKOFF_MS = 2000;
const MAX_BACKOFF_MS = 60000;
const PROXY_TIMEOUT_MS = 30000;
let ws = null;
let reconnectAttempts = 0;
let shuttingDown = false;
/**
* If WS_TOKEN is provided, send it as an Authorization: Bearer header so the
* secret stays out of access logs. (The server still accepts the legacy
* ?token=... query parameter for backward compatibility.)
*/
function buildClientOptions() {
if (!WS_TOKEN) return undefined;
return { headers: { Authorization: `Bearer ${WS_TOKEN}` } };
}
function connect() {
console.log(`🔄 Connecting to ${WS_URL}...`);
ws = new WebSocket(WS_URL, buildClientOptions());
ws.on('open', () => {
console.log('✅ Remote Agent connected to StoreHealthAnalyzer');
reconnectAttempts = 0;
});
ws.on('message', async data => {
let request;
try {
request = JSON.parse(data);
if (request.action !== 'proxyRequest') return;
console.log(`🔄 Proxying ${request.method || 'GET'} ${request.url}`);
const response = await axios({
method: request.method || 'GET',
url: request.url,
headers: request.headers || {},
auth: request.auth || undefined,
data: request.body || undefined,
timeout: PROXY_TIMEOUT_MS,
});
ws.send(
JSON.stringify({
requestId: request.requestId,
status: response.status,
data: response.data,
headers: response.headers,
})
);
} catch (err) {
console.error('Proxy error:', err.message);
ws.send(
JSON.stringify({
requestId: request ? request.requestId : null,
error: err.message,
status: err.response?.status || 500,
data: err.response?.data || null,
})
);
}
});
ws.on('close', code => {
console.log(`❌ Disconnected (code: ${code}).`);
if (!shuttingDown) scheduleReconnect();
});
ws.on('error', err => {
console.error('WebSocket error:', err.message);
});
}
function scheduleReconnect() {
reconnectAttempts++;
const backoff = Math.min(
INITIAL_BACKOFF_MS * Math.pow(1.5, reconnectAttempts - 1),
MAX_BACKOFF_MS
);
console.log(
`⏳ Reconnecting in ${Math.round(backoff / 1000)}s... (attempt ${reconnectAttempts})`
);
setTimeout(connect, backoff);
}
connect();
function shutdownRemote(signal) {
console.log(`🛑 ${signal} received. Shutting down remote agent...`);
shuttingDown = true;
if (ws) {
try {
ws.close();
} catch (_e) {
// ignore close errors during shutdown
}
}
process.exit(0);
}
process.on('SIGINT', () => shutdownRemote('SIGINT'));
process.on('SIGTERM', () => shutdownRemote('SIGTERM'));