netanalyzer/tests/webexServiceAppAuth.test.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

194 lines
5.9 KiB
JavaScript

const fs = require('fs').promises;
const os = require('os');
const path = require('path');
const WebexServiceAppAuth = require('../integrations/webex/WebexServiceAppAuth');
function makeMockAxios(impl) {
return { post: jest.fn(impl) };
}
describe('WebexServiceAppAuth', () => {
let tmpFile;
beforeEach(async () => {
WebexServiceAppAuth.resetForTests();
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'webex-auth-'));
tmpFile = path.join(tmpDir, 'tokens.json');
});
afterEach(async () => {
WebexServiceAppAuth.resetForTests();
try {
await fs.rm(path.dirname(tmpFile), { recursive: true, force: true });
} catch (_e) {
/* tmp cleanup failures shouldn't fail the suite */
}
});
it('refuses to construct without client id / secret', () => {
WebexServiceAppAuth.resetForTests();
expect(() => new WebexServiceAppAuth({ clientId: '', clientSecret: 's' })).toThrow(
/WEBEX_CLIENT_ID/
);
expect(() => new WebexServiceAppAuth({ clientId: 'c', clientSecret: '' })).toThrow(
/WEBEX_CLIENT_SECRET/
);
});
it('round-trips tokens through the tokens file', async () => {
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
});
auth.accessToken = 'at-1';
auth.refreshToken = 'rt-1';
auth.expiresAt = 1234567890000;
await auth.saveTokens();
const auth2 = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
});
await auth2.loadTokens();
expect(auth2.accessToken).toBe('at-1');
expect(auth2.refreshToken).toBe('rt-1');
expect(auth2.expiresAt).toBe(1234567890000);
});
it('loadTokens rejects with ENOENT when file is missing', async () => {
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: path.join(path.dirname(tmpFile), 'no-such-file.json'),
});
await expect(auth.loadTokens()).rejects.toMatchObject({ code: 'ENOENT' });
});
it('refresh() persists rotated tokens and applies the 5-min safety buffer', async () => {
const expiresIn = 3600; // 1 hour
const mockHttp = makeMockAxios(async () => ({
data: {
access_token: 'new-access',
refresh_token: 'new-refresh',
expires_in: expiresIn,
},
}));
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
httpClient: mockHttp,
});
auth.refreshToken = 'old-refresh';
const beforeMs = Date.now();
const token = await auth.refresh();
const afterMs = Date.now();
expect(token).toBe('new-access');
expect(auth.refreshToken).toBe('new-refresh');
expect(mockHttp.post).toHaveBeenCalledTimes(1);
// Buffer = 5 minutes early ⇒ expiresAt ≈ now + expiresIn*1000 - 5min.
const expectedLow = beforeMs + expiresIn * 1000 - 5 * 60 * 1000;
const expectedHigh = afterMs + expiresIn * 1000 - 5 * 60 * 1000;
expect(auth.expiresAt).toBeGreaterThanOrEqual(expectedLow);
expect(auth.expiresAt).toBeLessThanOrEqual(expectedHigh);
// And it persisted on disk:
const raw = await fs.readFile(tmpFile, 'utf8');
expect(JSON.parse(raw)).toMatchObject({
accessToken: 'new-access',
refreshToken: 'new-refresh',
});
});
it('refresh() throws a re-seed hint on 400/401 from Webex', async () => {
const mockHttp = makeMockAxios(async () => {
const err = new Error('Bad Request');
err.response = { status: 400, data: { error: 'invalid_grant' } };
throw err;
});
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
httpClient: mockHttp,
});
auth.refreshToken = 'old';
await expect(auth.refresh()).rejects.toThrow(/webex:seed/);
});
it('refresh() throws clearly when no refresh token is available', async () => {
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
});
await expect(auth.refresh()).rejects.toThrow(/No refresh token/);
});
it('getAccessToken() refreshes when expiresAt is past', async () => {
const mockHttp = makeMockAxios(async () => ({
data: { access_token: 'refreshed', refresh_token: 'rt2', expires_in: 3600 },
}));
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
httpClient: mockHttp,
});
auth.accessToken = 'stale';
auth.refreshToken = 'old';
auth.expiresAt = Date.now() - 1000; // already expired
const token = await auth.getAccessToken();
expect(token).toBe('refreshed');
expect(mockHttp.post).toHaveBeenCalledTimes(1);
});
it('getAccessToken() returns the cached token when not expired', async () => {
const mockHttp = makeMockAxios(async () => {
throw new Error('should not be called');
});
const auth = new WebexServiceAppAuth({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
httpClient: mockHttp,
});
auth.accessToken = 'fresh';
auth.refreshToken = 'rt';
auth.expiresAt = Date.now() + 60 * 1000;
const token = await auth.getAccessToken();
expect(token).toBe('fresh');
expect(mockHttp.post).not.toHaveBeenCalled();
});
it('getInstance() returns a singleton until resetForTests is called', () => {
const a1 = WebexServiceAppAuth.getInstance({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
});
const a2 = WebexServiceAppAuth.getInstance({
clientId: 'other',
clientSecret: 'x',
tokensFilePath: tmpFile,
});
expect(a2).toBe(a1);
WebexServiceAppAuth.resetForTests();
const a3 = WebexServiceAppAuth.getInstance({
clientId: 'c',
clientSecret: 's',
tokensFilePath: tmpFile,
});
expect(a3).not.toBe(a1);
});
});