netanalyzer/integrations/atlas/atlasClient.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

107 lines
3.1 KiB
JavaScript

/**
* Atlas (Xyte) HTTP client.
*
* Atlas is the SaaS that monitors AV hardware (AMPs, displays, etc.) for the
* organization. Auth is a single long-lived API key sent verbatim in the
* `Authorization` header — no OAuth/rotation, in contrast to the Webex
* Service App. Configure with `ATLAS_AUTH_KEY`.
*
* `atlasGet` returns the response body and wraps transient failures via
* withRetry. Missing-key conditions throw `AtlasUnavailableError` so the
* upstream renderer can surface a clean banner instead of a stack trace.
*/
const axios = require('axios');
const { withRetry } = require('../../utils/retry');
const logger = require('../../utils/logger');
const DEFAULT_BASE_URL = 'https://hub.xyte.io/core/v1';
const REQUEST_TIMEOUT_MS = 15000;
const RETRY_OPTS = { retries: 2, initialDelayMs: 500 };
class AtlasUnavailableError extends Error {
constructor(message) {
super(message);
this.name = 'AtlasUnavailableError';
}
}
// We construct the axios instance lazily so process.env changes between test
// cases are picked up, and so importing this module never throws when the
// key is absent (the renderer prefers a banner over a startup failure).
let _client = null;
function getClient() {
if (_client) return _client;
const authKey = process.env.ATLAS_AUTH_KEY;
if (!authKey) {
throw new AtlasUnavailableError(
'ATLAS_AUTH_KEY is not set. Add it to the environment and restart the bot.'
);
}
_client = axios.create({
baseURL: process.env.ATLAS_BASE_URL || DEFAULT_BASE_URL,
timeout: REQUEST_TIMEOUT_MS,
headers: {
'Content-Type': 'application/json',
// Atlas accepts the raw key in the Authorization header (no "Bearer ").
Authorization: authKey,
},
});
return _client;
}
/**
* GET against the Atlas API. Returns `response.data` (or `{}`). Wraps
* transient failures via withRetry.
*
* Throws AtlasUnavailableError when ATLAS_AUTH_KEY is missing, or a plain
* Error with status context on hard transport failures.
*/
async function atlasGet(endpoint, params = {}) {
const client = getClient();
const path = String(endpoint).replace(/^\/+/, '');
try {
const res = await withRetry(
() =>
client.get(`/${path}`, {
params,
// Validate manually so 4xx don't burn retry budget.
validateStatus: status => status >= 200 && status < 500,
}),
RETRY_OPTS
);
if (res.status >= 400) {
const detail =
res.data?.message || res.data?.error || `${res.status} ${res.statusText || ''}`.trim();
throw new Error(`Atlas GET /${path} failed: ${detail}`);
}
return res.data ?? {};
} catch (err) {
if (err instanceof AtlasUnavailableError) throw err;
logger.error('Atlas request failed', {
endpoint: path,
error: err.message,
status: err.response?.status,
});
throw err;
}
}
function resetClientForTests() {
_client = null;
}
module.exports = {
atlasGet,
AtlasUnavailableError,
resetClientForTests,
// Exposed so tests can assert defaults without poking the cached client.
DEFAULT_BASE_URL,
};