netanalyzer/services/webexService.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

86 lines
2.6 KiB
JavaScript

/**
* Thin axios wrapper for the Webex Service App.
*
* - Pulls the current access token from WebexServiceAppAuth on each call.
* - Retries transient failures via utils/retry.withRetry.
* - On a 401 response (token revoked between cache and call), forces a single
* refresh and retries once. Repeated 401s after that surface as errors so
* the caller can degrade gracefully.
*/
const axios = require('axios');
const config = require('../config');
const WebexServiceAppAuth = require('../integrations/webex/WebexServiceAppAuth');
const { withRetry } = require('../utils/retry');
const logger = require('../utils/logger');
const BASE_URL = 'https://webexapis.com/v1';
const RETRY_OPTS = { retries: 2, initialDelayMs: 500 };
let _auth = null;
function auth() {
if (!_auth) {
_auth = WebexServiceAppAuth.getInstance({
clientId: config.webexServiceApp.clientId,
clientSecret: config.webexServiceApp.clientSecret,
tokensFilePath: config.webexServiceApp.tokensPath,
});
}
return _auth;
}
function resetAuthForTests() {
_auth = null;
}
/**
* Issue a Webex Service App request. Returns response.data (or an empty
* object) on success; throws axios errors on hard failures.
*
* @param {('GET'|'POST'|'PUT'|'DELETE'|'PATCH')} method
* @param {string} pathSuffix - Webex API path relative to /v1 (e.g. "people").
* @param {object|null} body - JSON body for non-GET methods.
* @param {object|null} params - querystring params.
*/
async function request(method, pathSuffix, body = null, params = null) {
const url = `${BASE_URL}/${String(pathSuffix).replace(/^\/+/, '')}`;
const a = auth();
const doRequest = async (forceRefresh = false) => {
const token = forceRefresh ? await a.forceRefresh() : await a.getAccessToken();
return axios({
method,
url,
data: body || undefined,
params: params || undefined,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
timeout: 15000,
});
};
try {
const res = await withRetry(() => doRequest(false), RETRY_OPTS);
return res.data ?? {};
} catch (err) {
if (err.response?.status === 401) {
logger.warn('Webex returned 401 — refreshing and retrying once', { url });
try {
const retry = await doRequest(true);
return retry.data ?? {};
} catch (retryErr) {
logger.error('Webex request failed after forced refresh', {
url,
status: retryErr.response?.status,
error: retryErr.message,
});
throw retryErr;
}
}
throw err;
}
}
module.exports = { request, resetAuthForTests, BASE_URL };