From 74eb525413df6caada65cab9d02aa1851b18f3e3 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sun, 22 Nov 2026 20:04:02 -0500 Subject: [PATCH] CI phase 5: stricter eslint, design system integrity check, PR screenshots - eslint: errors for ==, unused or shadowed variables, eval and friends, prefer-const, curly, throw literals, useless catch/escape, constant conditions (loops allowed), unused expressions (short-circuit allowed); --max-warnings 0. Fixed the few violations (two unused requires in server.js, a shadowed mock argument in a test). - Scan job: scripts/ci/check-web-template.sh fails if public/web_template differs from upstream at the commit in its VERSION (change it upstream, then scripts/sync-web-template.sh). - New job UI screenshots (before/after), PRs only, when public/, views/ or the render/nav code changed: runs the base branch and the PR side by side with the same seeded data and uploads one before/after image per page, desktop and phone (scripts/ci/screenshots.js). Not required. Co-Authored-By: Claude Opus 5.5 --- .eslintrc.json | 57 ++++++++++++-- .gitea/workflows/ci.yml | 51 +++++++++++++ README.md | 14 +++- package.json | 2 +- scripts/ci/check-web-template.sh | 27 +++++++ scripts/ci/screenshots.js | 126 +++++++++++++++++++++++++++++++ server.js | 2 - tests/pageauth.test.js | 2 +- 8 files changed, 270 insertions(+), 11 deletions(-) create mode 100755 scripts/ci/check-web-template.sh create mode 100644 scripts/ci/screenshots.js diff --git a/.eslintrc.json b/.eslintrc.json index 02db55b..dcf0938 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -9,15 +9,62 @@ "sourceType": "commonjs" }, "rules": { - "no-unused-vars": "warn", - "no-empty": "warn", - "no-constant-condition": "warn", - "no-useless-escape": "warn", "semi": [ "error", "always" ], - "eqeqeq": "warn" + "no-unused-vars": [ + "error", + { + "args": "after-used", + "argsIgnorePattern": "^_", + "caughtErrors": "none" + } + ], + "no-empty": [ + "error", + { + "allowEmptyCatch": true + } + ], + "no-constant-condition": [ + "error", + { + "checkLoops": false + } + ], + "no-useless-escape": "error", + "eqeqeq": [ + "error", + "always", + { + "null": "ignore" + } + ], + "prefer-const": "error", + "curly": [ + "error", + "multi-line" + ], + "no-eval": "error", + "no-implied-eval": "error", + "no-new-func": "error", + "no-throw-literal": "error", + "no-useless-catch": "error", + "no-prototype-builtins": "error", + "no-shadow": [ + "error", + { + "builtinGlobals": false + } + ], + "no-unused-expressions": [ + "error", + { + "allowShortCircuit": true, + "allowTernary": true + } + ] }, "overrides": [ { diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 94b28d1..d3b1df7 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -121,6 +121,8 @@ jobs: run: actionlint .gitea/workflows/*.yml - name: Shell scripts (shellcheck) run: git ls-files -z '*.sh' | xargs -0 shellcheck + - name: Vendored design system matches upstream + run: scripts/ci/check-web-template.sh - name: Code patterns (semgrep) # Rule packs come from the semgrep registry, so new rules can surface new # findings: fix them, or suppress one line with `nosemgrep: ` and a reason. @@ -167,6 +169,55 @@ jobs: test-results/ retention-days: 14 + ui-screenshots: + name: UI screenshots (before/after) + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' + container: mcr.microsoft.com/playwright:v1.64.1-noble + env: + DB_HOST: 127.0.0.1 + DB_PORT: '3306' + DB_NAME: pulse + DB_USER: pulse + DB_PASSWORD: ci-only + BASE_SHA: ${{ github.event.pull_request.base.sha }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 + - name: Did this PR change the UI? + id: ui + run: | + if git diff --quiet "$BASE_SHA" HEAD -- public/ views/ lib/render.js lib/nav.js; then + echo "No UI files changed; no screenshots needed." + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + - name: Start MariaDB + if: steps.ui.outputs.changed == 'true' + run: | + scripts/ci/mariadb.sh + mariadb -e "CREATE DATABASE pulse_base; GRANT ALL ON pulse_base.* TO 'pulse'@'127.0.0.1';" + - name: Start this PR's Pulse (port 8400) + if: steps.ui.outputs.changed == 'true' + run: npm ci && scripts/ci/ui-stack.sh start + - name: Start the base branch's Pulse (port 8401) + if: steps.ui.outputs.changed == 'true' + run: | + git worktree add /tmp/base "$BASE_SHA" + cd /tmp/base && npm ci + DB_NAME=pulse_base PULSE_UI_PORT=8401 scripts/ci/ui-stack.sh start + - name: Capture before/after screenshots + if: steps.ui.outputs.changed == 'true' + run: node scripts/ci/screenshots.js ui-screenshots before=http://127.0.0.1:8401 after=http://127.0.0.1:8400 + - name: Upload screenshots + if: steps.ui.outputs.changed == 'true' + uses: actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 (v4 is unsupported on Gitea) + with: + name: ui-screenshots + path: ui-screenshots/ + retention-days: 30 + deploy: name: Deploy runs-on: ubuntu-latest diff --git a/README.md b/README.md index 725b8cf..3c396ee 100644 --- a/README.md +++ b/README.md @@ -586,12 +586,13 @@ Everything runs from `.gitea/workflows/ci.yml`: | Job | What it does | When | |---|---|---| -| `Lint (eslint)` | `npm run lint`, plus a check that fails on em or en dashes anywhere in the repo, including the vendored design system | Every push and PR | +| `Lint (eslint)` | `npm run lint` (errors on bugs-in-waiting such as `==`, shadowed or unused variables and `eval`; no warnings allowed), plus a check that fails on em or en dashes anywhere in the repo, including the vendored design system | Every push and PR | | `Test (jest)` | `npm test`: unit tests for `lib/` and the worker, and the deploy-script sandbox tests. Fails if coverage drops below the floors in `package.json` (`lib/` 90% lines, `worker/` 40%) | Every push and PR | | `Security (npm audit)` | `npm audit --audit-level=high`, plus a CycloneDX SBOM of production dependencies (kept 90 days as the `sbom-cyclonedx` artifact of each `main` build) | Every push and PR, and weekly (Monday 06:00) | -| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint on the workflow files (with shellcheck on their scripts), shellcheck on every `*.sh`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs). Suppress a reviewed false positive on its line with `nosemgrep: ` and a comment saying why | Every push and PR | +| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint on the workflow files (with shellcheck on their scripts), shellcheck on every `*.sh`, a check that `public/web_template` is byte-identical to upstream at the commit in its `VERSION`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs). Suppress a reviewed false positive on its line with `nosemgrep: ` and a comment saying why | Every push and PR | | `Integration (api)` | Starts the real server and three workers on Node 20 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR | | `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR | +| `UI screenshots (before/after)` | On PRs that touch `public/`, `views/` or the render/nav code: runs the base branch and the PR side by side with the same seeded data and uploads a `ui-screenshots` artifact with one before/after image per page (desktop and phone). Pages that came out identical are listed in `unchanged.txt`. Not a required check; attach the relevant images to the PR for review | Pull requests | | `Deploy` | Calls the `pulse-deploy` webhook on CT 122, waits until `/healthz` reports the tested commit, then tags it `deploy-*` | Push to `main`, only after all six checks pass | | `Notify` | Matrix alert on any failure on `main` or in the weekly audit, and on every deploy | As needed | @@ -613,6 +614,15 @@ DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=... DB_NAME=pulse scrip npm run test:integration ``` +### Design system + +`public/web_template/` is vendored from LotusGuild/web_template; never edit it here (CI checks it is +byte-identical to upstream). Change the design system upstream, then vendor it: + +```bash +scripts/sync-web-template.sh +``` + ### UI tests The Playwright tests drive the real UI end to end: every page loads with no page errors, console diff --git a/package.json b/package.json index 42c61fe..400c93b 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "start": "node server.js", "test": "jest --coverage", - "lint": "eslint --ext .js .", + "lint": "eslint --ext .js --max-warnings 0 .", "test:ui": "playwright test", "test:integration": "jest --config tests/integration/jest.config.js" }, diff --git a/scripts/ci/check-web-template.sh b/scripts/ci/check-web-template.sh new file mode 100755 index 0000000..0fd18e7 --- /dev/null +++ b/scripts/ci/check-web-template.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# Fails if public/web_template/{base.css,base.js} differ from LotusGuild/web_template at +# the commit recorded in public/web_template/VERSION. Change the design system upstream, +# then vendor it with scripts/sync-web-template.sh; never edit the copies here. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +DEST="$ROOT/public/web_template" +UPSTREAM=${WEB_TEMPLATE_RAW_URL:-https://code.lotusguild.org/LotusGuild/web_template/raw/commit} + +sha=$(awk '{print $2}' "$DEST/VERSION") +[[ "$sha" =~ ^[0-9a-f]{7,40}$ ]] || { echo "::error::public/web_template/VERSION has no commit sha"; exit 1; } + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +status=0 +for f in base.css base.js; do + curl -fsS --retry 2 --max-time 30 -o "$tmp/$f" "$UPSTREAM/$sha/$f" + if cmp -s "$tmp/$f" "$DEST/$f"; then + echo "$f matches web_template@$sha" + else + echo "::error::public/web_template/$f differs from web_template@$sha. Change it upstream and resync with scripts/sync-web-template.sh." + diff -u "$tmp/$f" "$DEST/$f" | head -40 || true + status=1 + fi +done +exit $status diff --git a/scripts/ci/screenshots.js b/scripts/ci/screenshots.js new file mode 100644 index 0000000..ab3de26 --- /dev/null +++ b/scripts/ci/screenshots.js @@ -0,0 +1,126 @@ +'use strict'; +/* eslint-env node, browser */ + +// Before/after screenshots for UI pull requests (#45 phase 5). +// +// node scripts/ci/screenshots.js before= after= +// +// Seeds the same demo data into each running Pulse stack (scripts/ci/ui-stack.sh), +// captures every page on desktop and on a phone, then composes one side-by-side +// image per page and viewport (-.png), rendered in the browser so +// no image tooling is needed. Pages that look identical are listed in unchanged.txt. +const fs = require('fs'); +const path = require('path'); +const { chromium, devices } = require('@playwright/test'); + +const SSO = { + 'Remote-User': 'ci.screens', + 'Remote-Name': 'CI Screens', + 'Remote-Email': 'ci@example.invalid', + 'Remote-Groups': 'admin,employee', +}; +const PAGES = ['/', '/workers', '/workflows', '/executions', '/quick', '/scheduler']; +const VIEWPORTS = { + desktop: { viewport: { width: 1440, height: 900 } }, + phone: { ...devices['Pixel 7'] }, +}; +const isLocal = url => /^(https?|wss?):\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(url); + +async function api(base, method, url, body) { + const res = await fetch(base + url, { + method, + headers: { ...SSO, ...(body ? { 'Content-Type': 'application/json' } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }); + return res.ok ? res.json().catch(() => ({})) : null; +} + +// The same data on both sides, so differences come from the code, not the data. +async function seed(base) { + const workers = (await api(base, 'GET', '/api/workers')) || []; + for (const w of workers) { + await api(base, 'POST', `/api/workers/${w.id}/command`, { command: `echo hello from ${w.name}` }); + } + if (workers[0]) await api(base, 'POST', `/api/workers/${workers[0].id}/command`, { command: 'echo oops >&2; exit 2' }); + await api(base, 'POST', '/api/workflows', { + name: 'Node health check', + description: 'Uptime and disk on every worker', + definition: { steps: [ + { id: 'uptime', name: 'Uptime', type: 'execute', command: 'uptime', targets: ['all'] }, + { id: 'disk', name: 'Disk', type: 'execute', command: 'df -h / | tail -1', targets: ['all'] }, + ] }, + }); + await new Promise(r => setTimeout(r, 3000)); // let the commands finish +} + +async function capture(browser, label, base, dir) { + const shots = {}; + for (const [vp, opts] of Object.entries(VIEWPORTS)) { + // reducedMotion instead of injected CSS: Pulse's CSP rightly blocks inline styles. + const ctx = await browser.newContext({ ...opts, extraHTTPHeaders: SSO, reducedMotion: 'reduce' }); + await ctx.route(u => !isLocal(u.href), r => r.abort()); + await ctx.addInitScript(() => { + try { localStorage.setItem('lt_theme', 'dark'); sessionStorage.setItem('lt_boot', '1'); } catch (e) { /* ignore */ } + }); + const page = await ctx.newPage(); + for (const p of PAGES) { + await page.goto(base + p); + await page.waitForLoadState('networkidle'); + await page.waitForTimeout(500); + const name = (p === '/' ? 'dashboard' : p.slice(1)) + '-' + vp; + const file = path.join(dir, `${label}-${name}.png`); + await page.screenshot({ path: file, fullPage: true }); + shots[name] = file; + } + await ctx.close(); + } + return shots; +} + +async function compose(browser, name, before, after, out) { + const b64 = f => 'data:image/png;base64,' + fs.readFileSync(f).toString('base64'); + const html = `
+

BEFORE (base) ${name}

+

AFTER (this PR) ${name}

+
`; + const page = await browser.newPage({ viewport: { width: 1600, height: 800 } }); + await page.setContent(html); + await page.screenshot({ path: out, fullPage: true }); + await page.close(); +} + +(async () => { + const [outDir, ...targets] = process.argv.slice(2); + const urls = Object.fromEntries(targets.map(t => t.split('='))); + if (!outDir || !urls.before || !urls.after) { + console.error('usage: screenshots.js before= after='); + process.exit(2); + } + const raw = path.join(outDir, 'raw'); + fs.mkdirSync(raw, { recursive: true }); + + await Promise.all([seed(urls.before), seed(urls.after)]); + const browser = await chromium.launch(); + try { + const before = await capture(browser, 'before', urls.before, raw); + const after = await capture(browser, 'after', urls.after, raw); + const unchanged = []; + for (const name of Object.keys(after)) { + if (before[name] && fs.readFileSync(before[name]).equals(fs.readFileSync(after[name]))) { + unchanged.push(name); + continue; + } + await compose(browser, name, before[name], after[name], path.join(outDir, `${name}.png`)); + console.log(`changed: ${name}`); + } + fs.writeFileSync(path.join(outDir, 'unchanged.txt'), unchanged.join('\n') + '\n'); + console.log(`unchanged: ${unchanged.length ? unchanged.join(', ') : 'none'}`); + } finally { + await browser.close(); + } +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/server.js b/server.js index d18ae93..15a3da9 100644 --- a/server.js +++ b/server.js @@ -3,9 +3,7 @@ const http = require('http'); const WebSocket = require('ws'); const mysql = require('mysql2/promise'); const crypto = require('crypto'); -const vm = require('vm'); const rateLimit = require('express-rate-limit'); -const cronParser = require('cron-parser'); const path = require('path'); const fs = require('fs'); const helmet = require('helmet'); diff --git a/tests/pageauth.test.js b/tests/pageauth.test.js index 00ebe58..82bbcd9 100644 --- a/tests/pageauth.test.js +++ b/tests/pageauth.test.js @@ -1,7 +1,7 @@ 'use strict'; jest.mock('../lib/render', () => ({ - renderError: jest.fn((req, res, status) => res.status(status).send('error page')) + renderError: jest.fn((_req, response, status) => response.status(status).send('error page')) })); const {