diff --git a/cmd/server/station_block_1017_test.go b/cmd/server/station_block_1017_test.go new file mode 100644 index 000000000..c6d67228c --- /dev/null +++ b/cmd/server/station_block_1017_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "strings" + "testing" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// #1017 (public Station block): the node page shows whatever /station +// serves, so the read side is the privacy gate. A claim carrying every +// public station field reaches /station only once approved; in any other +// status it serves nothing at all, and the owner-only administrator +// contact is never in the answer. +func TestStationBlock1017_OnlyApprovedServesEveryField(t *testing.T) { + full := func(id, pk, status string) claimRow898 { + c := withStationFields1017(stationRow(id, pk)) + c.status = status + c.hardware = "heltec-v3" + return c + } + fields := []string{`"hardware":"heltec-v3"`, `"antennaType":"yagi"`, `"gainDbi":5.8`, `"azimuthDeg":135`, + `"beamwidthDeg":40`, `"txPowerDbm":27.5`, `"cableLossDb":1.5`, `"power":["solar","battery"]`, + `"batteryWh":33.3`, `"solarW":20`, `"installation":"mast"`, `"contactPublic":"` + publicContact898 + `"`} + + t.Run(antennaclaim.StatusApproved, func(t *testing.T) { + env := newClaim789Env(t, claimAdminKey, detailsOn(nil), nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.insert898(t, full("a000000000000001", pk, antennaclaim.StatusApproved)) + body := env.do("GET", "/api/nodes/"+pk+"/station", "", "").Body.String() + for _, f := range fields { + if !strings.Contains(body, f) { + t.Errorf("approved /station %s lacks %s", body, f) + } + } + if strings.Contains(body, adminContact898) { + t.Errorf("approved /station %s carries the administrator contact", body) + } + }) + for _, status := range []string{antennaclaim.StatusPending, antennaclaim.StatusProven, antennaclaim.StatusRejected, + antennaclaim.StatusRevoked, antennaclaim.StatusExpired, antennaclaim.StatusSuperseded} { + t.Run(status, func(t *testing.T) { + env := newClaim789Env(t, claimAdminKey, detailsOn(nil), nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.insert898(t, full("a000000000000001", pk, status)) + if got := env.station(t, pk); got.Details != nil || got.ApprovedAt != nil { + t.Fatalf("a %s claim was served: %+v", status, got.Details) + } + body := env.do("GET", "/api/nodes/"+pk+"/station", "", "").Body.String() + for _, s := range []string{"heltec", "yagi", "txPowerDbm", "azimuthDeg", "batteryWh", publicContact898, adminContact898} { + if strings.Contains(body, s) { + t.Errorf("a %s claim's /station %s carries %s", status, body, s) + } + } + }) + } +} diff --git a/public/antenna-claims.js b/public/antenna-claims.js index 145737bbc..468544364 100644 --- a/public/antenna-claims.js +++ b/public/antenna-claims.js @@ -234,23 +234,78 @@ } // detailValues lists a StationDetails' public values in display order: - // [label, text] pairs, unknown enum values left out. - function detailValues(d) { + // [label, text] pairs, unknown enum values left out. full (the public + // Station block, #1017) adds the M3 radio, direction and power values; + // the admin row lists those through keptValues instead. + function detailValues(d, full) { var out = []; if (!d) return out; var t = labelOf(ANTENNA_TYPES, d.antennaType); if (t) out.push(['Antenna', t]); var g = fmtGain(d.gainDbi); if (g) out.push(['Gain', g]); + if (full) { + var dir = directionText(d); + if (dir) out.push(['Direction', dir]); + var radio = radioText(d); + if (radio) out.push(['Radio', radio]); + } + var power = []; if (Array.isArray(d.power)) { var p = d.power.map(function (v) { return labelOf(POWER, v); }).filter(Boolean); - if (p.length) out.push(['Power', p.join(' + ')]); + if (p.length) power.push(p.join(' + ')); + } + if (full) { + if (isNum(d.batteryWh)) power.push(fmtOne(d.batteryWh) + ' Wh battery'); + if (isNum(d.solarW)) power.push(fmtOne(d.solarW) + ' W solar panel'); } + if (power.length) out.push(['Power', power.join(SEP)]); var inst = labelOf(INSTALLATIONS, d.installation); if (inst) out.push(['Installation', inst]); return out; } + var SEP = ' · '; + var COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; + + // fmtOne is a value on the 0.1 grid as text, without "-0.0". + function fmtOne(v) { + var s = v.toFixed(1); + return s === '-0.0' ? '0.0' : s; + } + + // compassPoint is the eight-point compass name of a whole number of + // degrees 0-359 from true north, or '' for anything else. + function compassPoint(deg) { + if (typeof deg !== 'number' || deg % 1 !== 0 || deg < 0 || deg > 359) return ''; + return COMPASS[Math.round(deg / 45) % 8]; + } + + // directionText is "135° (SE) · 40° beam", or '' without a direction: + // a beamwidth alone says nothing (it needs azimuthDeg, #1017 M3). + function directionText(d) { + var c = compassPoint(d.azimuthDeg); + if (!c) return ''; + var s = d.azimuthDeg + '° (' + c + ')'; + if (isNum(d.beamwidthDeg)) s += SEP + d.beamwidthDeg + '° beam'; + return s; + } + + // radioText is the TX power at the antenna port, the cable loss and, + // with a TX power, the EIRP it gives (TX − cable loss + gain; a missing + // gain is counted as 0 dBi and said so, #1017 M0 §9.2), or ''. + function radioText(d) { + var parts = []; + var tx = isNum(d.txPowerDbm), loss = isNum(d.cableLossDb), gain = isNum(d.gainDbi); + if (tx) parts.push(fmtOne(d.txPowerDbm) + ' dBm at the antenna port'); + if (loss) parts.push('cable loss ' + fmtOne(d.cableLossDb) + ' dB'); + if (tx) { + var eirp = d.txPowerDbm - (loss ? d.cableLossDb : 0) + (gain ? d.gainDbi : 0); + parts.push('≈ ' + fmtOne(eirp) + ' dBm EIRP' + (gain ? '' : ' (0 dBi antenna assumed)')); + } + return parts.join(SEP); + } + // stationHardwareKey is the hardware key a /station answer shows, or '': // the catalogue is asked for only then (#1017, +0 requests without). function stationHardwareKey(r) { @@ -267,7 +322,7 @@ // The server answers details:null when stale; the guard holds even if a // stale answer ever carries them (review PR#908 F4). if (!d || typeof d !== 'object' || r.stale) return null; - var rows = detailValues(d); + var rows = detailValues(d, true); var hwText = hardwareText(entries, stationHardwareKey(r), d.hardwareModel); if (hwText) rows.unshift(['Hardware', hwText]); var contact = typeof d.contactPublic === 'string' && d.contactPublic ? d.contactPublic : ''; @@ -1755,6 +1810,7 @@ partsOf: partsOf, describeClaim: describeClaim, stationView: stationView, + compassPoint: compassPoint, stationPrefill: stationPrefill, keptStationFields: keptStationFields, stationHardwareKey: stationHardwareKey, diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 643104ee2..cf07343d8 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -241,6 +241,7 @@ {"file":"test-1018-m1b-signin-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":0,"measurementNote":"New suite; #1018 M1b sign in with Bluetooth/USB: a fake companion replaces navigator.serial and navigator.bluetooth before the app loads and answers the companion protocol byte for byte ('<'/'>' frames over the port, one frame per Nordic UART write and notification), signing in Node with a TEST ed25519 key; the account API is answered by Playwright routes (the CI server runs with accounts off) and the signed-login route verifies the signature over the challenge it issued. At 375x560 in light and dark with real taps over USB: Bluetooth and USB above the code flow, the challenge for the SELF_INFO key, only commands 1/33/34/35 reach the companion, queued then proven, the redeem with the secret, Signed in without the rename note, nothing secret in the URL, the port closed at 115200; at 1280x800 the same over Bluetooth with the NUS filter and a disconnect; another key's signature shows the 401 and re-enables the buttons; without Web Serial and Web Bluetooth the fallback text and the working code flow. 5 cases, about 25s locally; no CI duration measured yet. Assigned to shard 3, the lightest by the sum of meanSeconds."}, {"file":"test-antenna-claims-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":0,"measurementNote":"New suite; #789 M2b owner antenna-height claim flow on the node page and the admin queue (Tools > Antenna Height Claims) with the antenna-claim API answered by Playwright routes (the CI server runs with the feature off) and the page timers on Playwright's clock, moved in 1 s steps that each wait for every status check to settle: feature off shows no section, a repeater gets the section (deep link scrolls to it) and a companion never, a height off the 0.1 m grid is refused before any request, the code, the 23-byte name check (and a longer name with the code inside it) and the set name command, status queued to pending to proven to approved then no more polling with no two checks closer than 2 s across a theme refresh, the deep link restores the claim after a reload, the clear path and a 429, bounded polling with a status-aware give-up text and Check again, leaving the node page stops the view and coming back starts a live one, the admin key kept in memory only, markup in a node name kept as text, the 409 newer-approved refusal, reject, revoke with a confirm, the filter deep link, the owner flow plus an admin decision with real taps at 375x560 from a cold start (44 px buttons and links), and with 11 queued claims at 375x560 and 1280x800 a decision's result on screen. 10 cases, about 19s locally; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds."}, {"file":"test-issue-911-gesture-hints-non-blocking-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":0,"measurementNote":"New suite; #911 a first-visit gesture hint never swallows a tap meant for a page control: cold start (nothing pre-seeded) at 375x560 and 360x640 with real taps, a probe that compares what each point hits with and without the hints (a 6 px grid over every pill outside Got it, and the middle of every visible control); the first tap on I know what I'm doing, on the Nodes search field through the edge-swipe pill and on a node row through the row-swipe pill (Home > More > Nodes) reaches the control and dismisses only the hint it went through; taps outside every pill and a touch scroll that starts on a pill dismiss nothing; the tab-swipe hint gives way to the row-swipe one on Nodes and one hint per slot on Packets, no two pills overlapping; only the edge-swipe hint on the node page, Back to nodes, the claim height field, Get code and Start over; Got it hit by the first tap during the fade-in; with a control put under each Got it the hint moves off it and Got it still takes a tap; and a self-check that a blocking pill and a covered control turn the probe red. 18 cases, about 40s locally; no CI duration measured yet."}, + {"file":"test-issue-1017-station-block-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":8,"measurementNote":"New suite; #1017 the public Station block on the node page shows every approved public station value (hardware, antenna, gain, direction with compass point and beam, TX power at the antenna port, cable loss and EIRP, power sources with battery Wh and solar panel W, installation, public contact) with the owner note, with GET /api/antenna-claims/config and /station answered by Playwright routes (the CI server has claims off): nothing for a pending answer (details:null), a hidden node (404) or a stale answer, owner-only contactAdmin and claim-state fields never in the page, missing values give no row, phone 375x560 light and dark from a cold start on Home with real taps and desktop 1280x800 dark with every row inside the screen and no sideways scroll. 10 cases, about 8s locally; no CI duration measured yet. Assigned to shard 2, the lightest by the sum of meanSeconds."}, {"file":"test-issue-1017-m2-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":17,"measurementNote":"New suite; #1017 M2 the station hardware picker in the owner claim form, the Hardware row of the node page Station block and the hardware label in the admin queue, with the real GET /api/hardware and the claim routes, /station and the observer record answered by Playwright routes: +0 catalogue and observer requests without hardware, the Station row from one catalogue request (other + model as text, an unknown key no row), at most 61 options in four optgroups, the search only after the 100 ms debounce, Use only for an empty field, the other model field shown and hidden, the body is exactly the visible fields, and phone 375x560 from a cold start on Home with real taps plus desktop 1280x800 (44 px controls, no sideways scroll). 11 cases, about 17s locally; no CI duration measured yet. Assigned to shard 3, the lightest by the sum of meanSeconds."}, {"file":"test-issue-898-m2-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":0,"measurementNote":"New suite; #898 M2 owner station details on the node page and in the admin queue, with the claim API and GET /api/nodes/{pk}/station answered by Playwright routes where the CI server has the feature off (the real config and /station answers are checked too): with details off no Station block, no details fieldset and no /station request; the public Station block with the public contact as text, asked once per node-page view across a theme re-render and Start over, nothing for stale, none or empty details; a /station answer that leaked contactAdmin shows it nowhere, does not pre-fill the admin field and is not sent, next to a public contact and with the public contact empty (no fallback); Keep + Keep cannot be sent; a combined claim posts the exact body and keeps no contact or detail in the URL, sessionStorage or localStorage; Remove details posts clearDetails; bad contacts and gain refused before any request; admin per-part lines, the replaced marker, contactAdmin for proven and approved only, markup in both contacts as text, the per-part 409; axe in light and dark; 375x560 (light, dark) and 360x640 from a cold start with real taps and 44 px targets, plus an admin decision at 375x560; consecutive taps at one point are spaced past Chromium's double-tap window by tests/e2e-tap.js. 22 cases, about 60s locally; no CI duration measured yet. Assigned to shard 3, the lightest by meanSeconds."}, {"file":"test-issue-880-live-follow-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1","BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":76,"measurementNote":"New suite; #880 M1 Live \"Follow a packet\" with a stubbed /api/packets/ (an ADVERT over three fixture relays heard by six observers: one late, one naive clock, one skewed), stubbed /api/observers and /api/observers/clock-skew: desktop 1440x900 cold start, line popup Follow with one packet fetch, hop progress, live packets buffered but not animated, summary values and caption, close tears down card, layers, URL, Esc listener and frames; deep link and invalid deep link; reduced motion draws the end state with no follow frames; leaving Live mid-replay leaks nothing; feed card Follow at 700px waits out the settle window for a fresh packet and fetches at once for an older one; Follow next as a feed-header icon that moves no panel control, arm, cancel and pick, skipping packets the favourites, node or region filter hides, disarmed on leaving Live; VCR replay (Rewind) does not arm Follow next and does not animate under a follow; phone 360x640 with the panel pinned open folds it when a follow starts and keeps every marker above the full sheet; phone 375x560 with touch from a cold start by real taps (gear, Follow next folds the panel, 44px View packet and popup Follow, close) with the sheet above the bottom nav and no sideways scroll. About 76s locally (review round 1); no CI duration measured yet. Assigned to shard 2."}, diff --git a/test-all.sh b/test-all.sh index 36af686b9..c12ae0773 100755 --- a/test-all.sh +++ b/test-all.sh @@ -147,6 +147,7 @@ run test-channel-proposals.js run test-admin-key.js run test-hardware.js run test-antenna-claims.js +run test-issue-1017-station-block.js run test-1018-account.js run test-1018-companion-link.js run test-1018-m2a-links.js diff --git a/test-issue-1017-station-block-e2e.js b/test-issue-1017-station-block-e2e.js new file mode 100644 index 000000000..a1c6570f0 --- /dev/null +++ b/test-issue-1017-station-block-e2e.js @@ -0,0 +1,265 @@ +/** + * E2E (#1017): the public Station block on the node page shows every + * approved public station value (#1017 M1-M3 fields) — against a running + * server with the CI fixture. + * + * GET /api/hardware is the real server's (embedded catalogue, not gated). + * The CI server runs with antenna claims off, so GET /api/antenna-claims/ + * config and GET /api/nodes/{pk}/station are answered by Playwright in the + * shapes of cmd/server/antenna_claims.go (NodeStationResponse); nothing is + * written. Which claims reach /station at all (approved only, never + * pending/proven/rejected, never the administrator contact) is pinned on + * the server by TestStationBlock1017_OnlyApprovedServesEveryField. + * + * Asserts: + * 1. an approved claim with every field shows each value as one row, in + * order, with units, plus "Given by the node owner, confirmed …"; + * 2. what the server answers for a pending/unapproved claim + * ({details:null}), a hidden or unknown node (404), and a stale claim + * shows no Station block; + * 3. owner-only fields (contactAdmin) and claim-state fields that leaked + * into a /station answer show nowhere on the page, and markup in a + * value stays text; + * 4. missing values give no row (no empty dd); + * 5. phone 375x560 (light and dark) from a cold start on Home with real + * taps, and desktop 1280x800 dark: every row inside the screen and no + * sideways scroll. + * + * Usage: + * BASE_URL=http://localhost:13581 node test-issue-1017-station-block-e2e.js + * E2E_SHOTS=/some/dir … also writes screenshots for browser validation. + */ +'use strict'; +const { chromium } = require('playwright'); +const { tapWhenSettled } = require('./tests/e2e-tap'); + +const BASE = process.env.BASE_URL || 'http://localhost:13581'; +const SHOTS = process.env.E2E_SHOTS || ''; +const SECTION = '[data-testid="antenna-claim"]'; +const STATION = '[data-testid="ac-station"]'; +const XSS = ''; +const APPROVED_AT = Date.UTC(2026, 10, 28, 12, 0, 0); + +// Every public station value an owner can set (#1017 M1-M3, #898). +const FULL = { + hardware: 'heltec-v3', antennaType: 'yagi', gainDbi: 9, azimuthDeg: 135, beamwidthDeg: 40, + txPowerDbm: 27.5, cableLossDb: 1.5, power: ['solar', 'battery'], batteryWh: 33.3, solarW: 20, + installation: 'mast', contactPublic: 'OZ1ABC' +}; +const FULL_ROWS = [ + ['Hardware', 'Heltec v3 · ESP32-S3 · SX1262'], + ['Antenna', 'Yagi'], + ['Gain', '9.0 dBi'], + ['Direction', '135° (SE) · 40° beam'], + ['Radio', '27.5 dBm at the antenna port · cable loss 1.5 dB · ≈ 35.0 dBm EIRP'], + ['Power', 'Solar + Battery · 33.3 Wh battery · 20.0 W solar panel'], + ['Installation', 'Mast'], + ['Owner contact', 'OZ1ABC'] +]; + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.error(' ✗ ' + name + ': ' + (e && e.stack || e)); } +} +function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } +function pathOf(url) { return new URL(url).pathname; } +const json = (body, status) => ({ status: status || 200, contentType: 'application/json', body: JSON.stringify(body) }); + +(async () => { + const browser = await chromium.launch({ + headless: true, + executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], + }); + console.log(`\n=== #1017 public Station block against ${BASE} ===\n`); + + const nodes = await (await fetch(BASE + '/api/nodes?limit=500')).json(); + const list = nodes.nodes || []; + const repeater = list.find(n => n.role === 'repeater' && n.lat && n.lon && n.name); + assert(repeater, 'fixture needs a positioned repeater'); + const PK = repeater.public_key; + const positioned = new Set(list.filter(n => (n.role === 'repeater' || n.role === 'room') && n.lat && n.lon).map(n => n.public_key)); + + // newCtx answers the claim config and /station. o.answer: the /station + // response {status, body}; default an approved FULL claim. + async function newCtx(o) { + o = o || {}; + const ctx = await browser.newContext({ + viewport: o.viewport || { width: 1280, height: 800 }, + hasTouch: !!o.touch, isMobile: !!o.touch, + }); + const rec = { station: 0 }; + await ctx.route(u => pathOf(u) === '/api/antenna-claims/config', r => r.fulfill(json({ enabled: true, detailsEnabled: true }))); + await ctx.route(u => /^\/api\/nodes\/[0-9a-f]{64}\/antenna$/.test(pathOf(u)), r => + r.fulfill(json({ antennaM: 12, antennaSource: 'owner', assumed: false }))); + await ctx.route(u => /^\/api\/nodes\/[0-9a-f]{64}\/station$/.test(pathOf(u)), r => { + rec.station++; + const a = o.answer || { body: { details: FULL, approvedAt: APPROVED_AT } }; + return r.fulfill(json(a.body, a.status)); + }); + await ctx.addInitScript((theme) => { + try { + localStorage.setItem('meshcore-theme', theme); + localStorage.setItem('meshcore-map-clustering', 'false'); + ['row-swipe', 'tab-swipe', 'edge-drawer', 'pull-refresh'] + .forEach(k => localStorage.setItem('meshcore-gesture-hints-' + k, 'seen')); + } catch (_) {} + const apply = () => document.documentElement && document.documentElement.setAttribute('data-theme', theme); + apply(); + document.addEventListener('DOMContentLoaded', apply); + }, o.theme || 'light'); + const page = await ctx.newPage(); + const errors = []; + page.on('pageerror', e => errors.push(String(e))); + return { ctx, page, rec, errors }; + } + + async function openNode(page, pk) { + await page.goto(BASE + '/#/nodes/' + pk, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#nodeFullBody .node-full-card', { timeout: 15000 }); + await page.waitForSelector(SECTION + ':visible', { timeout: 15000 }); + } + async function shot(page, name) { + if (!SHOTS) return; + await page.waitForFunction(() => document.getAnimations().every(a => a.playState !== 'running')); + await page.locator(SECTION + ':visible').first().screenshot({ path: require('path').join(SHOTS, name + '.png') }); + } + const stationRows = (page) => page.$$eval(STATION + ' .ac-station-row', rs => rs.map(r => [r.querySelector('dt').textContent, r.querySelector('dd').textContent])); + const settle = (page) => page.waitForLoadState('networkidle').catch(() => {}); + const sideways = (page) => page.evaluate(() => document.scrollingElement.scrollWidth - window.innerWidth); + // rowsInside: every Station dt/dd box lies inside the viewport width. + const rowsInside = (page) => page.$$eval(STATION + ' dt, ' + STATION + ' dd', (els) => els + .map(e => e.getBoundingClientRect()) + .filter(b => b.left < -0.5 || b.right > window.innerWidth + 0.5 || b.width <= 0) + .map(b => [b.left, b.right])); + const waitRows = (page, n) => page.waitForFunction((a) => document.querySelectorAll(a.s + ' .ac-station-row').length === a.n, + { s: STATION, n }, { timeout: 10000 }); + + // ── 1. An approved claim with every field ─────────────────────────────── + await step('approved claim with every field: each value is one row, in order, with units and the owner note', async () => { + const { ctx, page, rec, errors } = await newCtx(); + await openNode(page, PK); + await waitRows(page, FULL_ROWS.length); + const rows = await stationRows(page); + assert(JSON.stringify(rows) === JSON.stringify(FULL_ROWS), JSON.stringify(rows)); + const note = await page.textContent(STATION + ' .ac-station-note'); + assert(/^Given by the node owner, confirmed .+\.$/.test(note), note); + await settle(page); + assert(rec.station === 1, '/station asked ' + rec.station + ' times'); + assert(errors.length === 0, errors.join('; ')); + await shot(page, 'station-desktop-light'); + await ctx.close(); + }); + + // ── 2. Nothing for what is not approved ───────────────────────────────── + const NOT_SHOWN = { + 'pending or unapproved claim (the server answers details:null)': { body: { details: null } }, + 'hidden or unknown node (the server answers 404)': { status: 404, body: { error: 'Not found' } }, + 'stale claim (moved node)': { body: { details: null, stale: true } }, + 'stale answer that still carries details': { body: { details: FULL, approvedAt: APPROVED_AT, stale: true } }, + }; + for (const name of Object.keys(NOT_SHOWN)) { + await step('no Station block: ' + name, async () => { + const { ctx, page, rec, errors } = await newCtx({ answer: NOT_SHOWN[name] }); + await openNode(page, PK); + await page.waitForFunction(() => true); + await settle(page); + assert(rec.station === 1, '/station asked ' + rec.station + ' times'); + assert(await page.locator(STATION + ':visible').count() === 0, 'a Station block is shown'); + const text = await page.textContent('#nodeFullBody'); + for (const v of ['27.5 dBm', '135°', '33.3 Wh', 'OZ1ABC', 'Heltec v3']) assert(text.indexOf(v) < 0, 'the page shows ' + v); + assert(errors.length === 0, errors.join('; ')); + await ctx.close(); + }); + } + + // ── 3. Owner-only and markup ─────────────────────────────────────────── + await step('owner-only fields that leaked into /station show nowhere; markup stays text', async () => { + const leaked = Object.assign({}, FULL, { contactPublic: XSS, contactAdmin: 'ZZADMIN9', status: 'pending', proofHash: 'ZZPROOF7' }); + const { ctx, page, errors } = await newCtx({ answer: { body: { details: leaked, approvedAt: APPROVED_AT } } }); + await openNode(page, PK); + await waitRows(page, FULL_ROWS.length); + const html = await page.content(); + assert(!/ZZADMIN9|ZZPROOF7/.test(html), 'an owner-only value is in the page'); + const rows = await stationRows(page); + assert(rows[rows.length - 1][1] === XSS, JSON.stringify(rows[rows.length - 1])); + assert(await page.evaluate(() => window.__xss === undefined), 'markup in a value ran'); + // The admin contact is never pre-filled into the form either. + await page.check('[data-testid="ac-details-set"]'); + const admin = await page.$$eval('input, textarea', es => es.map(e => e.value).join('|')); + assert(!/ZZADMIN9/.test(admin), 'the admin contact was pre-filled'); + assert(errors.length === 0, errors.join('; ')); + await ctx.close(); + }); + + // ── 4. Missing values ───────────────────────────────────────────────── + await step('missing values: no row and no empty text', async () => { + const some = { antennaType: 'panel', azimuthDeg: 0, txPowerDbm: 22, power: ['mains'] }; + const { ctx, page, errors } = await newCtx({ answer: { body: { details: some, approvedAt: APPROVED_AT } } }); + await openNode(page, PK); + await waitRows(page, 4); + const rows = await stationRows(page); + const want = [['Antenna', 'Panel'], ['Direction', '0° (N)'], + ['Radio', '22.0 dBm at the antenna port · ≈ 22.0 dBm EIRP (0 dBi antenna assumed)'], ['Power', 'Mains']]; + assert(JSON.stringify(rows) === JSON.stringify(want), JSON.stringify(rows)); + assert(rows.every(r => r[0] && r[1]), 'an empty row'); + assert(errors.length === 0, errors.join('; ')); + await ctx.close(); + }); + + // ── 5. Layout: phone and desktop, light and dark ─────────────────────── + for (const theme of ['light', 'dark']) { + await step('phone 375x560 ' + theme + ', cold start on Home, real taps: every row inside the screen, no sideways scroll', async () => { + const vp = { width: 375, height: 560 }; + const { ctx, page, errors } = await newCtx({ viewport: vp, touch: true, theme }); + const tap = (sel, minH) => tapWhenSettled(page, sel, { minHeight: minH }); + await page.goto(BASE + '/#/home', { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('[data-bottom-nav-tab="more"]', { timeout: 15000 }); + await tap('[data-bottom-nav-tab="more"]'); + await tap('[data-bottom-nav-more-route="nodes"]'); + await page.waitForSelector('tr[data-key]', { timeout: 15000 }); + const keys = await page.$$eval('tr[data-key]', rs => rs.map(r => r.getAttribute('data-key'))); + const pk = keys.find(k => positioned.has(k)); + assert(pk, 'no positioned repeater or room in the list'); + await tap('tr[data-key="' + pk + '"]', 30); + await page.waitForFunction((p) => location.hash.indexOf('#/nodes/' + p) === 0, pk, { timeout: 10000 }); + await page.waitForSelector(SECTION + ':visible', { timeout: 15000 }); + await waitRows(page, FULL_ROWS.length); + await page.locator(STATION).scrollIntoViewIfNeeded(); + const rows = await stationRows(page); + assert(JSON.stringify(rows) === JSON.stringify(FULL_ROWS), JSON.stringify(rows)); + const out = await rowsInside(page); + assert(out.length === 0, 'Station boxes outside the screen: ' + JSON.stringify(out)); + const side = await sideways(page); + assert(side <= 0, 'the node page scrolls sideways by ' + side + ' px'); + await shot(page, 'station-375-' + theme); + assert(errors.length === 0, errors.join('; ')); + await ctx.close(); + }); + } + + await step('desktop 1280x800 dark: every row inside the screen, no sideways scroll', async () => { + const vp = { width: 1280, height: 800 }; + const { ctx, page, errors } = await newCtx({ viewport: vp, theme: 'dark' }); + await openNode(page, PK); + await waitRows(page, FULL_ROWS.length); + const out = await rowsInside(page); + assert(out.length === 0, 'Station boxes outside the screen: ' + JSON.stringify(out)); + const side = await sideways(page); + assert(side <= 0, 'the node page scrolls sideways by ' + side + ' px'); + // Colours come from the theme: dt muted, dd the text colour. + const colours = await page.$eval(STATION + ' dt', (dt) => { + const cs = getComputedStyle(document.documentElement); + return [getComputedStyle(dt).color, cs.getPropertyValue('--text-muted').trim()]; + }); + assert(colours[1], 'no --text-muted variable'); + await shot(page, 'station-desktop-dark'); + assert(errors.length === 0, errors.join('; ')); + await ctx.close(); + }); + + await browser.close(); + console.log(`\n${passed} passed, ${failed} failed\n`); + process.exit(failed ? 1 : 0); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/test-issue-1017-station-block.js b/test-issue-1017-station-block.js new file mode 100644 index 000000000..d1eb99709 --- /dev/null +++ b/test-issue-1017-station-block.js @@ -0,0 +1,139 @@ +#!/usr/bin/env node +/* #1017 — the public Station block on the node page shows every approved + * public station value (M1-M3 fields): unit tests for the formatting in + * public/antenna-claims.js, the real production file loaded into a vm + * context (no copies of the code under test). + * + * Covers: units and wording, the compass point from degrees, missing values + * omitted (no empty rows), rounding to the 0.1 grid without "-0.0", values + * of the wrong type left out, the EIRP sum, owner-only fields never shown, + * and the admin row unchanged (no duplicated M3 values). */ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const SRC_PATH = path.join(__dirname, 'public', 'antenna-claims.js'); +const HEIGHT_SRC_PATH = path.join(__dirname, 'public', 'antenna-height.js'); +const ADMIN_KEY_PATH = path.join(__dirname, 'public', 'admin-key.js'); +const HARDWARE_SRC_PATH = path.join(__dirname, 'public', 'hardware.js'); +const HW_ENTRIES = JSON.parse(fs.readFileSync(path.join(__dirname, 'internal', 'channelregistry', 'hardware', 'catalogue.json'), 'utf8')).entries; + +function load() { + const ctx = { console, Promise, Math, JSON, Object, Array, String, Number, encodeURIComponent, URLSearchParams }; + ctx.window = ctx; + ctx.setTimeout = setTimeout; + ctx.clearTimeout = clearTimeout; + vm.createContext(ctx); + for (const p of [HEIGHT_SRC_PATH, ADMIN_KEY_PATH, HARDWARE_SRC_PATH, SRC_PATH]) { + vm.runInContext(fs.readFileSync(p, 'utf8'), ctx, { filename: p }); + } + return ctx.AntennaClaims; +} + +const AC = load(); +const tests = []; +function test(name, fn) { tests.push({ name, fn }); } +// Values from the vm context are from another realm: compare as JSON. +function eq(a, b, m) { const x = JSON.stringify(a), y = JSON.stringify(b); assert.ok(x === y, (m ? m + ": " : "") + x + " !== " + y); } +const rows = (details, entries) => { + const v = AC.stationView({ details, approvedAt: 1700000000000 }, entries); + return v ? v.rows : null; +}; + +// Every approved public value, in display order. +const FULL = { + hardware: 'heltec-v3', antennaType: 'yagi', gainDbi: 9, azimuthDeg: 135, beamwidthDeg: 40, + txPowerDbm: 27.5, cableLossDb: 1.5, power: ['solar', 'battery'], batteryWh: 33.3, solarW: 20, + installation: 'mast', contactPublic: 'OZ1ABC' +}; + +test('every approved public value has a row, in order, with units', () => { + eq(rows(FULL, HW_ENTRIES), [ + ['Hardware', 'Heltec v3 · ESP32-S3 · SX1262'], + ['Antenna', 'Yagi'], + ['Gain', '9.0 dBi'], + ['Direction', '135° (SE) · 40° beam'], + ['Radio', '27.5 dBm at the antenna port · cable loss 1.5 dB · ≈ 35.0 dBm EIRP'], + ['Power', 'Solar + Battery · 33.3 Wh battery · 20.0 W solar panel'], + ['Installation', 'Mast'], + ['Owner contact', 'OZ1ABC'] + ]); +}); + +test('compassPoint: eight points, the boundaries, wrap-around and bad input', () => { + const C = AC.compassPoint; + const cases = { 0: 'N', 22: 'N', 23: 'NE', 45: 'NE', 67: 'NE', 68: 'E', 90: 'E', 135: 'SE', 180: 'S', + 225: 'SW', 270: 'W', 315: 'NW', 337: 'NW', 338: 'N', 359: 'N' }; + for (const k of Object.keys(cases)) assert.strictEqual(C(Number(k)), cases[k], k + '°'); + for (const bad of [-1, 360, 12.5, NaN, Infinity, null, undefined, '90']) assert.strictEqual(C(bad), '', String(bad)); +}); + +test('direction: due north is a value; no beam without a direction; a bad direction no row', () => { + eq(rows({ antennaType: 'panel', azimuthDeg: 0 }), [['Antenna', 'Panel'], ['Direction', '0° (N)']]); + eq(rows({ antennaType: 'yagi', azimuthDeg: 270, beamwidthDeg: 60 }), [['Antenna', 'Yagi'], ['Direction', '270° (W) · 60° beam']]); + eq(rows({ antennaType: 'yagi', beamwidthDeg: 60 }), [['Antenna', 'Yagi']], 'a beam alone says nothing'); + eq(rows({ antennaType: 'yagi', azimuthDeg: 360, beamwidthDeg: 60 }), [['Antenna', 'Yagi']]); + eq(rows({ antennaType: 'yagi', azimuthDeg: '135' }), [['Antenna', 'Yagi']], 'a string is not a value'); + eq(rows({ antennaType: 'yagi', azimuthDeg: 90, beamwidthDeg: 'wide' }), [['Antenna', 'Yagi'], ['Direction', '90° (E)']]); +}); + +test('radio: each part only when given; EIRP only with TX power, gain taken as 0 dBi and said so', () => { + eq(rows({ txPowerDbm: 22 }), [['Radio', '22.0 dBm at the antenna port · ≈ 22.0 dBm EIRP (0 dBi antenna assumed)']]); + eq(rows({ cableLossDb: 1.5 }), [['Radio', 'cable loss 1.5 dB']], 'no EIRP without TX power'); + eq(rows({ cableLossDb: 0 }), [['Radio', 'cable loss 0.0 dB']], 'no cable loss is a value'); + eq(rows({ gainDbi: 5.8, txPowerDbm: 20, cableLossDb: 0 }), [['Gain', '5.8 dBi'], ['Radio', '20.0 dBm at the antenna port · cable loss 0.0 dB · ≈ 25.8 dBm EIRP']]); + eq(rows({ gainDbi: -2, txPowerDbm: -9 }), [['Gain', '-2.0 dBi'], ['Radio', '-9.0 dBm at the antenna port · ≈ -11.0 dBm EIRP']]); +}); + +test('rounding: one decimal, float noise rounded, never "-0.0"', () => { + eq(rows({ txPowerDbm: 27.549999999 }), [['Radio', '27.5 dBm at the antenna port · ≈ 27.5 dBm EIRP (0 dBi antenna assumed)']]); + // 27.3 - 1.1 + 5.8 is 31.999999999999996 in floating point. + eq(rows({ gainDbi: 5.8, txPowerDbm: 27.3, cableLossDb: 1.1 })[1], ['Radio', '27.3 dBm at the antenna port · cable loss 1.1 dB · ≈ 32.0 dBm EIRP']); + eq(rows({ txPowerDbm: -0.04 }), [['Radio', '0.0 dBm at the antenna port · ≈ 0.0 dBm EIRP (0 dBi antenna assumed)']]); + eq(rows({ power: ['battery'], batteryWh: 1234.56 }), [['Power', 'Battery · 1234.6 Wh battery']]); +}); + +test('power: battery and panel sizes join the sources; each only when given', () => { + eq(rows({ power: ['mains'] }), [['Power', 'Mains']]); + eq(rows({ power: ['mains', 'battery'], batteryWh: 100 }), [['Power', 'Mains + Battery · 100.0 Wh battery']]); + eq(rows({ power: ['solar'], solarW: 0.5 }), [['Power', 'Solar · 0.5 W solar panel']]); + eq(rows({ batteryWh: 33.3 }), [['Power', '33.3 Wh battery']], 'a size without the source list still shows'); + eq(rows({ power: ['solar'], solarW: '20' }), [['Power', 'Solar']], 'a string is not a value'); +}); + +test('missing or broken values give no row and no empty text', () => { + eq(rows({ txPowerDbm: null, cableLossDb: undefined, azimuthDeg: NaN, batteryWh: Infinity, solarW: -Infinity, antennaType: 'omni' }), [['Antenna', 'Omni']]); + assert.strictEqual(rows({ txPowerDbm: '22', azimuthDeg: null }), null, 'nothing to show is no block'); + for (const r of rows(FULL, HW_ENTRIES)) assert.ok(r[1] && !/undefined|null|NaN|\(\)/.test(r[1]), JSON.stringify(r)); +}); + +test('stale, missing or null answers show nothing, whatever fields they carry', () => { + assert.strictEqual(AC.stationView({ details: FULL, stale: true, approvedAt: 1 }, HW_ENTRIES), null); + assert.strictEqual(AC.stationView({ details: null }), null); + assert.strictEqual(AC.stationView(null), null); +}); + +test('owner-only fields never show, even if an answer leaked them', () => { + const leaked = Object.assign({}, FULL, { contactAdmin: 'ZZADMIN9', status: 'pending', proofHash: 'ZZPROOF' }); + const text = JSON.stringify(AC.stationView({ details: leaked, approvedAt: 1 }, HW_ENTRIES)); + assert.ok(!/ZZADMIN9|ZZPROOF|pending/.test(text), text); +}); + +test('the admin row is unchanged: the M3 values listed once, no Direction or Radio label', () => { + const p = AC.adminParts({ status: 'approved', detailsOp: 'set', detailsInForce: true, details: FULL }, HW_ENTRIES); + const t = p.lines[0].text; + assert.strictEqual((t.match(/33\.3 Wh/g) || []).length, 1, t); + assert.strictEqual((t.match(/27\.5 dBm/g) || []).length, 1, t); + assert.ok(/^Yagi · 9\.0 dBi · Solar \+ Battery · Mast · TX 27\.5 dBm/.test(t), t); +}); + +let passed = 0; +for (const { name, fn } of tests) { + try { fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { console.error(' ✗ ' + name + '\n ' + (e && e.message)); } +} +console.log('\n' + passed + '/' + tests.length + ' passed'); +if (passed !== tests.length) process.exit(1);