// The opt-out usage ping (fw#503): the switch, the first-run notice, what a // ping carries, and the once-a-day check the hook runs. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import fs from 'fs'; import http from 'http'; import os from 'os'; import path from 'path'; import type { AddressInfo } from 'net'; const spawnMock = vi.hoisted(() => vi.fn()); vi.mock('child_process', async () => { const actual = await vi.importActual('child_process'); return { ...actual, spawn: spawnMock, default: { ...actual, spawn: spawnMock } }; }); vi.mock('../cli/daemon-starter', async () => { const actual = await vi.importActual('../cli/daemon-starter'); return { ...actual, ownLauncher: () => '/opt/node9/dist/cli.js' }; }); import { TELEMETRY_NOTICE, buildTelemetryPing, postTelemetry, readTelemetryChoice, sendTelemetry, showTelemetryNoticeOnce, telemetryStatus, telemetryTarget, writeTelemetryChoice, } from '../telemetry'; import { maybeSendDailyActive } from '../telemetry-switch'; import { getMachineId } from '../machine-id'; let home = ''; beforeEach(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'node9-telemetry-')); vi.stubEnv('HOME', home); vi.stubEnv('USERPROFILE', home); // vitest.config sets NODE9_TESTING for every test; clear it, and every other // off switch, so each test states the one it means. for (const k of [ 'NODE9_TESTING', 'NODE9_NO_TELEMETRY', 'DO_NOT_TRACK', 'CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'TF_BUILD', 'BUILDKITE', 'NODE9_TELEMETRY_URL', ]) vi.stubEnv(k, ''); spawnMock.mockReset(); spawnMock.mockReturnValue({ on: vi.fn(), unref: vi.fn() }); }); afterEach(() => { vi.unstubAllEnvs(); fs.rmSync(home, { recursive: true, force: true }); }); describe('telemetryStatus', () => { it('is off on an install that never saw the notice', () => { expect(telemetryStatus()).toEqual({ on: false, reason: 'never-shown' }); }); it('is on after the choice is on, off after off', () => { writeTelemetryChoice('on'); expect(telemetryStatus()).toEqual({ on: true }); writeTelemetryChoice('off'); expect(telemetryStatus()).toEqual({ on: false, reason: 'off' }); }); it.each([ ['NODE9_NO_TELEMETRY', '1', 'env'], ['DO_NOT_TRACK', '1', 'env'], ['NODE9_TESTING', '1', 'env'], ['CI', 'true', 'ci'], ['GITHUB_ACTIONS', 'true', 'ci'], ])('%s=%s wins over a recorded on', (k, v, reason) => { writeTelemetryChoice('on'); vi.stubEnv(k, v); expect(telemetryStatus()).toEqual({ on: false, reason }); }); it('treats a garbled choice file as no choice', () => { fs.mkdirSync(path.join(home, '.node9'), { recursive: true }); fs.writeFileSync(path.join(home, '.node9', 'telemetry.json'), '{"choice":"yes please"}'); expect(readTelemetryChoice()).toBeNull(); expect(telemetryStatus().on).toBe(false); }); }); describe('showTelemetryNoticeOnce', () => { it('prints the notice once on a fresh machine and turns the ping on', () => { const print = vi.fn(); showTelemetryNoticeOnce(true, print); showTelemetryNoticeOnce(true, print); expect(print).toHaveBeenCalledTimes(1); expect(print).toHaveBeenCalledWith(TELEMETRY_NOTICE); expect(telemetryStatus()).toEqual({ on: true }); }); it('does nothing on an existing install: it stays off', () => { const print = vi.fn(); showTelemetryNoticeOnce(false, print); expect(print).not.toHaveBeenCalled(); expect(readTelemetryChoice()).toBeNull(); }); it('never overrides an earlier off', () => { writeTelemetryChoice('off'); const print = vi.fn(); showTelemetryNoticeOnce(true, print); expect(print).not.toHaveBeenCalled(); expect(readTelemetryChoice()).toBe('off'); }); it('records nothing under DO_NOT_TRACK or in CI', () => { for (const [k, v] of [ ['DO_NOT_TRACK', '1'], ['CI', 'true'], ]) { vi.stubEnv(k, v); const print = vi.fn(); showTelemetryNoticeOnce(true, print); expect(print).not.toHaveBeenCalled(); expect(readTelemetryChoice()).toBeNull(); vi.stubEnv(k, ''); } }); it('says what is sent and how to turn it off, without an em dash', () => { expect(TELEMETRY_NOTICE).toContain('node9 telemetry off'); expect(TELEMETRY_NOTICE).toContain('NODE9_NO_TELEMETRY=1'); expect(TELEMETRY_NOTICE).not.toContain('—'); }); it('does not create config.json, so setup still sees a fresh machine', () => { showTelemetryNoticeOnce(true, () => {}); expect(fs.existsSync(path.join(home, '.node9', 'config.json'))).toBe(false); }); }); describe('the ping body', () => { it('holds only the install id, OS, version, agents, event and choice', () => { const p = buildTelemetryPing('wizard_started', 'local'); expect(Object.keys(p).sort()).toEqual( ['agents_detected', 'choice', 'event', 'machine_id', 'node9_version', 'os'].sort() ); expect(p.machine_id).toBe(getMachineId(home)); expect(p.choice).toBe('local'); expect(Object.keys(buildTelemetryPing('daily_active'))).not.toContain('choice'); }); }); describe('sending', () => { async function capture(run: (port: number) => Promise): Promise { const bodies: string[] = []; const server = http.createServer((req, res) => { let body = ''; req.on('data', (c) => (body += c)); req.on('end', () => { bodies.push(body); res.end('{"ok":true}'); }); }); await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); try { await run((server.address() as AddressInfo).port); } finally { server.close(); } return bodies; } const target = (port: number) => ({ hostname: '127.0.0.1', port, protocol: 'http' as const }); it('sends wizard_started with the chosen path when on', async () => { writeTelemetryChoice('on'); const bodies = await capture((port) => sendTelemetry('wizard_started', 'dashboard', { target: target(port) }) ); expect(bodies).toHaveLength(1); expect(JSON.parse(bodies[0])).toMatchObject({ event: 'wizard_started', choice: 'dashboard', machine_id: getMachineId(home), }); }); it('sends nothing when never shown, when off, or under DO_NOT_TRACK', async () => { const none1 = await capture((port) => sendTelemetry('daily_active', undefined, { target: target(port) }) ); writeTelemetryChoice('off'); const none2 = await capture((port) => sendTelemetry('daily_active', undefined, { target: target(port) }) ); writeTelemetryChoice('on'); vi.stubEnv('DO_NOT_TRACK', '1'); const none3 = await capture((port) => sendTelemetry('daily_active', undefined, { target: target(port) }) ); expect([none1, none2, none3]).toEqual([[], [], []]); }); it('sends no body without a valid machine id', async () => { writeTelemetryChoice('on'); const bodies = await capture((port) => postTelemetry({ machine_id: 'not-a-uuid' }, { target: target(port) }) ); expect(bodies).toEqual([]); }); }); describe('telemetryTarget', () => { it('is production by default', () => { expect(telemetryTarget({})).toBeUndefined(); }); it('accepts a local http server only', () => { expect(telemetryTarget({ NODE9_TELEMETRY_URL: 'http://localhost:3001' })).toEqual({ hostname: '127.0.0.1', port: 3001, protocol: 'http', }); expect(telemetryTarget({ NODE9_TELEMETRY_URL: 'https://evil.example.com' })).toBeUndefined(); expect(telemetryTarget({ NODE9_TELEMETRY_URL: 'http://10.0.0.5:80' })).toBeUndefined(); expect(telemetryTarget({ NODE9_TELEMETRY_URL: 'not a url' })).toBeUndefined(); }); }); describe('maybeSendDailyActive', () => { const day = new Date('2026-12-01T10:00:00Z'); const stamp = () => path.join(home, '.node9', 'telemetry-day'); beforeEach(() => fs.mkdirSync(path.join(home, '.node9'), { recursive: true })); it('starts one detached ping on the first call of a day, none after', () => { writeTelemetryChoice('on'); maybeSendDailyActive(day); maybeSendDailyActive(day); expect(spawnMock).toHaveBeenCalledTimes(1); const [, args, opts] = spawnMock.mock.calls[0]; expect(args).toEqual(['/opt/node9/dist/cli.js', 'telemetry', 'ping']); expect(opts).toMatchObject({ detached: true, stdio: 'ignore', windowsHide: true }); expect(fs.readFileSync(stamp(), 'utf8').trim()).toBe('2026-12-01'); }); it('starts another on the next UTC day', () => { writeTelemetryChoice('on'); maybeSendDailyActive(day); maybeSendDailyActive(new Date('2026-12-02T00:00:01Z')); expect(spawnMock).toHaveBeenCalledTimes(2); }); it('stamps the day but starts nothing when the choice is not on', () => { maybeSendDailyActive(day); expect(spawnMock).not.toHaveBeenCalled(); expect(fs.existsSync(stamp())).toBe(true); }); it('touches nothing at all under NODE9_NO_TELEMETRY or in CI', () => { writeTelemetryChoice('on'); vi.stubEnv('NODE9_NO_TELEMETRY', '1'); maybeSendDailyActive(day); vi.stubEnv('NODE9_NO_TELEMETRY', ''); vi.stubEnv('CI', '1'); maybeSendDailyActive(day); expect(spawnMock).not.toHaveBeenCalled(); expect(fs.existsSync(stamp())).toBe(false); }); it('never throws, even when spawn does', () => { writeTelemetryChoice('on'); spawnMock.mockImplementation(() => { throw new Error('EMFILE'); }); expect(() => maybeSendDailyActive(day)).not.toThrow(); }); });