See how your app actually fits together. An interactive, plain-English map of your codebase, drawn by Claude or Codex.
JavaScript ai-codingarchitecture-diagramclaudeclaude-codeclaude-code-plugincodebase-visualizationcodexcodex-plugindeveloper-toolsonboardingopenaivibe-coding
Add a test suite and run it on every push
Hayden Smitha9ad2583e879
diff --git a/.gitattributes b/.gitattributesindex dcb131d..d4710c8 100644--- a/.gitattributes+++ b/.gitattributes@@ -3,3 +3,4 @@*.png binary*.jpg binary*.webp binary+*.woff2 binarydiff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex ee643a3..1cd530e 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -12,6 +12,6 @@- [ ] Anything the map shows people is in plain language- [ ] No secret values stored or printed- [ ] No details of a real private project in code, comments, docs or screenshots-- [ ] `node --test "tests/**/*.test.mjs"` passes+- [ ] `npm test` passes- [ ] `claude plugin validate .` passes- [ ] `CHANGELOG.md` updated, if people will notice the changediff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlnew file mode 100644index 0000000..af0d75d--- /dev/null+++ b/.github/workflows/test.yml@@ -0,0 +1,27 @@+# Runs the test suite on every push and pull request, on the Node versions and operating systems+# Floorplan supports. No dependencies to install: Node's built-in runner.+name: Tests++on:+ push:+ pull_request:++permissions:+ contents: read++jobs:+ test:+ name: Node ${{ matrix.node }} on ${{ matrix.os }}+ runs-on: ${{ matrix.os }}+ timeout-minutes: 10+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ node: [18, 20, 22]+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node }}+ - run: node --testdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex f943a66..a8f50df 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,10 @@# Changelog+## Unreleased++- **Map server hardening:** the map's local server no longer serves files from a neighbouring folder whose name starts with "floorplan" (like `floorplan-old/`), and a malformed web address now gets an error instead of stopping the server. Both were found by the new tests.+- **Tests:** a test suite now covers how code is read, Health, a whole map of a sample two-repo app, the privacy promises (offline map, no secret values written anywhere) and the map server's security checks. It runs on every push and pull request on Linux, macOS and Windows. Run it with `npm test`.+## 0.1.4 (2026-10-28)- **Safari fix:** cards now show up in Safari (and every browser on iPhone/iPad). Before, only the connection lines were drawn and card text appeared in the top-left corner. Reported by @fpv001 in #1, fixed by @PaulMagos in #3.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9725f47..46edb40 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -31,7 +31,7 @@ Open an issue describing what you were trying to do and what got in the way. Plu5. If you changed behaviour people will notice, add a line to `CHANGELOG.md` under an "Unreleased" heading at the top.6. Before opening the PR, run:```bash- node --test "tests/**/*.test.mjs"+ npm testclaude plugin validate .```diff --git a/README.md b/README.mdindex 2220e2a..2657f96 100644--- a/README.md+++ b/README.md@@ -12,6 +12,7 @@Claude reads your codebase and draws an interactive map of it. Every part, file and web request gets a plain-English name, and every connection between them is shown.[](https://code.claude.com/docs/en/overview)+[](https://github.com/haydenschmitty/floorplan/actions/workflows/test.yml)[](CHANGELOG.md)[](LICENSE)[](https://nodejs.org)diff --git a/docs/development.md b/docs/development.mdindex db5c7fb..eecd4fa 100644--- a/docs/development.md+++ b/docs/development.md@@ -58,10 +58,24 @@ node skills/floorplan/scripts/open.mjs /path/to/project## Tests```bash-node --test "tests/**/*.test.mjs"+npm test```-Each test maps a small sample project from `tests/fixtures/` and checks the result, using Node's built-in test runner. When you fix a bug in what Floorplan detects, add a sample that shows it, and check the test fails without your fix.+The tests use Node's built-in test runner, so there's nothing to install (`npm test` is the same as `node --test`). GitHub runs them on every push and pull request, on Linux, macOS and Windows with Node 18, 20 and 22.++| File | What it checks |+|---|---|+| `parsing.test.mjs` | imports, endpoints, web requests and doc comments, per language and framework |+| `helpers-lib.test.mjs` | globs, file types, command-line flags, fallback names |+| `secrets.test.mjs` | Health finds secrets, masks them, and ignores placeholders |+| `health.test.mjs` | which endpoints Health calls open to anyone (FastAPI sample in `fixtures/`) |+| `sample-app.test.mjs` | a whole map of a two-repo shop: endpoints, cross-repo requests, Health, offline map, no secret values written, updates |+| `serve.test.mjs` | the map's server: 127.0.0.1 only, token and same-origin checks, nothing served from outside its folder |+| `release.test.mjs` | the version agrees across `plugin.json`, the README badge and the changelog |++Sample projects are written to a temp folder by `helpers.mjs` (`shopApp()`) or copied from `tests/fixtures/`. Anything secret-looking is assembled at runtime, so no real-looking key is ever committed.++When you fix a bug in what Floorplan detects, add a sample that shows it, and check the test fails without your fix.## Extending the viewer@@ -112,7 +126,7 @@ Files in `skills/floorplan/assets/ui/` are inlined into every map, in name order1. On an up-to-date `main`, run the tests and check the manifests, including the official plugin directory's requirements:```bash- node --test "tests/**/*.test.mjs"+ npm testclaude plugin validate . --profile directory```2. Bump `version` in `.claude-plugin/plugin.json` and the version badge in `README.md`.diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..dbac2ea--- /dev/null+++ b/package.json@@ -0,0 +1,10 @@+{+ "name": "floorplan",+ "private": true,+ "description": "Floorplan, a Claude Code plugin. No dependencies: this file only gives `npm test` a home.",+ "license": "MIT",+ "engines": { "node": ">=18" },+ "scripts": {+ "test": "node --test"+ }+}diff --git a/skills/floorplan/assets/serve.mjs b/skills/floorplan/assets/serve.mjsindex 52033d6..c7418b1 100644--- a/skills/floorplan/assets/serve.mjs+++ b/skills/floorplan/assets/serve.mjs@@ -290,8 +290,10 @@ const server = http.createServer((req, res) => {res.writeHead(404); return res.end();}if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'Content-Type': TYPES['.html'], 'Cache-Control': 'no-store' }); return res.end(page); }- const file = path.join(here, decodeURIComponent(url.pathname));- if (!file.startsWith(here) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404); return res.end('not found'); }+ let file;+ try { file = path.join(here, decodeURIComponent(url.pathname)); } catch { res.writeHead(400); return res.end('bad address'); }+ // inside this folder only: a neighbour like ../floorplan-old/ also starts with this folder's path+ if (!file.startsWith(here + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404); return res.end('not found'); }res.writeHead(200, { 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream' });fs.createReadStream(file).pipe(res);});diff --git a/tests/helpers-lib.test.mjs b/tests/helpers-lib.test.mjsnew file mode 100644index 0000000..90bbdca--- /dev/null+++ b/tests/helpers-lib.test.mjs@@ -0,0 +1,50 @@+// The small helpers everything else leans on: globs in architecture.json, file classification,+// command-line flags, fallback names, and endpoint path matching.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { lib } from './helpers.mjs';++const { compileGlob, classify, parseArgs } = await lib('common.mjs');+const { humanize, fallbackFileName, fallbackRouteName } = await lib('names.mjs');+const { routeSegments } = await lib('routes.mjs');++test('globs: ** spans folders, * stays in one, braces and bare folders work', () => {+ const g = (glob, p) => compileGlob(glob).test(p);+ assert.ok(g('src/**/*.ts', 'src/a/b.ts'));+ assert.ok(g('src/**/*.ts', 'src/b.ts'));+ assert.ok(!g('src/*.ts', 'src/a/b.ts'));+ assert.ok(g('src/{a,b}', 'src/b/z.js'), 'a braced folder claims everything under it');+ assert.ok(g('src/components', 'src/components/x/y.tsx'), 'a plain folder claims everything under it');+ assert.ok(!g('src/components', 'src/components-old/y.tsx'));+ assert.ok(g('**/*.test.ts', 'x.test.ts'));+ assert.ok(g('./src/', 'src/a.ts'), 'leading ./ and trailing / are ignored');+});++test('globs: a more specific pattern scores higher', () => {+ assert.ok(compileGlob('api/routes/**').specificity > compileGlob('api/**').specificity);+});++test('classify: code, docs, lock files, assets and generated files', () => {+ assert.deepEqual(classify('src/a.ts', 100), { category: 'code', lang: 'typescript' });+ assert.deepEqual(classify('app/main.py', 100), { category: 'code', lang: 'python' });+ assert.equal(classify('README.md', 10).category, 'docs');+ assert.equal(classify('package-lock.json', 10).category, 'lock');+ assert.equal(classify('logo.png', 10).category, 'asset');+ assert.equal(classify('dist/app.min.js', 10).category, 'generated');+});++test('parseArgs: positionals, --flag value, --flag=value and bare flags', () => {+ assert.deepEqual(parseArgs(['root', '--port', '9', '--no-open', '--x=1']), { _: ['root'], port: '9', 'no-open': true, x: '1' });+});++test('fallback names read like plain words', () => {+ assert.equal(humanize('order_service'), 'Order service');+ assert.equal(humanize('OrderService'), 'Order service');+ assert.equal(fallbackFileName('api/routes/order_service.py'), 'Order service');+ assert.equal(fallbackRouteName({ method: 'POST', path: '/orders/:id/refund' }), 'Create orders refund');+});++test('endpoint paths: parameters in every framework style match anything', () => {+ assert.deepEqual(routeSegments('/orders/:id/refund'), ['orders', '*', 'refund']);+ assert.deepEqual(routeSegments('/orders/{id}'), ['orders', '*']);+});diff --git a/tests/helpers.mjs b/tests/helpers.mjsnew file mode 100644index 0000000..be350b3--- /dev/null+++ b/tests/helpers.mjs@@ -0,0 +1,135 @@+// Shared helpers for the tests: build a throwaway project on disk, run the skill's scripts on it,+// and read what they wrote. Every project lives in the OS temp folder and is removed afterwards.+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++export const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+export const SKILL = path.join(REPO, 'skills', 'floorplan');+export const lib = (name) => import(new URL(`../skills/floorplan/scripts/lib/${name}`, import.meta.url));++/**+ * Writes `files` ({ 'relative/path': 'contents' }) into a new temp folder. Each folder in `repos`+ * becomes its own git repo, like a frontend and backend side by side. Returns the folder.+ */+export function makeProject(files, { repos = [], arch } = {}) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'floorplan-test-'));+ for (const [p, src] of Object.entries(files)) {+ fs.mkdirSync(path.dirname(path.join(root, p)), { recursive: true });+ fs.writeFileSync(path.join(root, p), src);+ }+ for (const r of repos) execFileSync('git', ['init', '-q', path.join(root, r)]);+ if (arch) writeJson(path.join(root, 'floorplan', 'architecture.json'), arch);+ return root;+}++/** Runs one of the skill's scripts (scan.mjs, build.mjs, …) on a project and returns what it printed. */+export function run(script, root, ...args) {+ return execFileSync(process.execPath, [path.join(SKILL, 'scripts', script), root, ...args], { encoding: 'utf8', stdio: 'pipe' });+}++/** scan + build, the way the skill does a first map (without touching CLAUDE.local.md). */+export function scanAndBuild(root) {+ return run('scan.mjs', root) + run('build.mjs', root, '--no-claude-md');+}++export const readJson = (file) => JSON.parse(fs.readFileSync(file, 'utf8'));+export const writeJson = (file, data) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(data, null, 2)); };+export const readGraph = (root) => readJson(path.join(root, 'floorplan', 'graph.json'));+export const cleanup = (root) => fs.rmSync(root, { recursive: true, force: true });++/** Every file under a folder, as { path, text }. */+export function allFiles(dir) {+ return fs.readdirSync(dir, { recursive: true, withFileTypes: true })+ .filter((e) => e.isFile())+ .map((e) => { const p = path.join(e.parentPath ?? e.path, e.name); return { path: p, text: fs.readFileSync(p, 'utf8') }; });+}++/** "METHOD /path" for every endpoint on the map. */+export const routeKeys = (graph) => graph.routes.map((r) => `${r.m} ${r.p}`).sort();++/** "METHOD /path" for every endpoint Health reports as callable by anyone. */+export function openEndpoints(graph) {+ return graph.health.issues+ .filter((i) => i.kind === 'unprotected-endpoint')+ .flatMap((i) => i.items.filter((id) => id.startsWith('r:')).map((id) => graph.routes[+id.slice(2)]))+ .map((r) => `${r.m} ${r.p}`)+ .sort();+}++// A fake password for the sample app. It's assembled at runtime so no secret-looking string is+// ever committed to this repo, and the tests can check it never reaches anything Floorplan writes.+export const FAKE_PASSWORD = ['correct', 'horse', 'battery', 'staple', '42'].join('-');++/**+ * A small shop: an Express API and a web app in two repos. It has endpoints protected three ways+ * (middleware on the route, a check where the router is mounted, none at all), cross-repo web+ * requests, and a hard-coded password.+ */+export function shopApp() {+ const files = {+ 'shop-api/package.json': JSON.stringify({ name: 'shop-api', type: 'module', dependencies: { express: '^4.19.0' } }),+ 'shop-api/server.js': [+ `import express from 'express';`,+ `import orders from './routes/orders.js';`,+ `import admin from './routes/admin.js';`,+ `import notes from './routes/notes.js';`,+ `import { requireStaff } from './auth.js';`,+ ``,+ `const app = express();`,+ `app.use('/api', orders);`,+ `app.use('/admin', requireStaff, admin);`,+ `app.use('/api', notes);`,+ `app.listen(3000);`,+ ].join('\n'),+ 'shop-api/auth.js': [+ `/** Rejects requests without a signed-in customer. */`,+ `export function requireAuth(req, res, next) { if (!req.headers.authorization) return res.status(401).end(); next(); }`,+ `/** Rejects requests that aren't from staff. */`,+ `export function requireStaff(req, res, next) { if (!req.user?.staff) return res.status(403).end(); next(); }`,+ ].join('\n'),+ 'shop-api/config.js': `export const DB_PASSWORD = "${FAKE_PASSWORD}";\nexport const PORT = 3000;\n`,+ 'shop-api/routes/orders.js': [+ `import { Router } from 'express';`,+ `import { requireAuth } from '../auth.js';`,+ `import { DB_PASSWORD } from '../config.js';`,+ ``,+ `const router = Router();`,+ `/** Every order for the signed-in customer. */`,+ `router.get('/orders', requireAuth, async (req, res) => { res.json([]); });`,+ `router.post('/orders/:id/refund', requireAuth, async (req, res) => { res.json({ ok: !!DB_PASSWORD }); });`,+ `export default router;`,+ ].join('\n'),+ 'shop-api/routes/admin.js': [+ `import { Router } from 'express';`,+ `const router = Router();`,+ `router.delete('/users/:id', async (req, res) => { res.status(204).end(); });`,+ `export default router;`,+ ].join('\n'),+ 'shop-api/routes/notes.js': [+ `import { Router } from 'express';`,+ `const router = Router();`,+ `router.post('/notes', async (req, res) => { res.json({ saved: true }); });`,+ `export default router;`,+ ].join('\n'),+ 'shop-web/package.json': JSON.stringify({ name: 'shop-web', type: 'module', dependencies: { react: '^18.3.0' } }),+ 'shop-web/src/api.js': [+ `export const listOrders = () => fetch('/api/orders').then((r) => r.json());`,+ 'export const refund = (id) => fetch(`/api/orders/${id}/refund`, { method: \'POST\' });',+ ].join('\n'),+ 'shop-web/src/App.jsx': [+ `import { listOrders, refund } from './api.js';`,+ `export default function App() { return <button onClick={() => listOrders().then((o) => refund(o[0].id))}>Refund</button>; }`,+ ].join('\n'),+ };+ const arch = {+ project: { name: 'Shop', summary: 'A sample shop.' },+ nodes: [+ { id: 'api', label: 'Server', kind: 'service', summary: 'The shop server.', paths: ['shop-api/**'] },+ { id: 'web', label: 'Website', kind: 'ui', summary: 'The shop website.', paths: ['shop-web/**'] },+ ],+ };+ return makeProject(files, { repos: ['shop-api', 'shop-web'], arch });+}diff --git a/tests/parsing.test.mjs b/tests/parsing.test.mjsnew file mode 100644index 0000000..0b60a90--- /dev/null+++ b/tests/parsing.test.mjs@@ -0,0 +1,84 @@+// What Floorplan reads out of source files: imports, endpoints, web requests and doc comments.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { lib } from './helpers.mjs';++const { extract, flattenTemplates, cleanDoc } = await lib('extract.mjs');+const routes = (src, lang, file) => extract(src, lang, file).routes.map((r) => `${r.method} ${r.path}`);++test('JavaScript: imports and Express endpoints', () => {+ const r = extract([+ `import express from 'express';`,+ `import { db, cache as c } from './db.js';`,+ `const router = express.Router();`,+ `router.get('/orders', list);`,+ `router.post('/orders/:id/refund', refund);`,+ ].join('\n'), 'javascript', 'api/orders.js');+ assert.deepEqual(r.imports.map((i) => i.spec), ['express', './db.js']);+ assert.deepEqual(r.imports[1].names, ['db', 'cache']);+ assert.deepEqual(r.routes.map((x) => `${x.method} ${x.path}`), ['GET /orders', 'POST /orders/:id/refund']);+ assert.equal(r.routes[0].var, 'router');+});++test('Next.js app router: each exported method is an endpoint at the folder path', () => {+ assert.deepEqual(+ routes(`export async function GET(req) { return Response.json([]) }\nexport async function POST(req) {}\n`, 'typescript', 'web/app/api/orders/route.ts'),+ ['GET /api/orders', 'POST /api/orders'],+ );+});++test('Flask: blueprint prefix, methods list and handler docstring', () => {+ const r = extract([+ `"""Order endpoints."""`,+ `from flask import Blueprint`,+ `bp = Blueprint('orders', __name__, url_prefix='/api')`,+ ``,+ `@bp.route('/orders', methods=['GET', 'POST'])`,+ `def list_orders():`,+ ` """List them."""`,+ ` return []`,+ ].join('\n'), 'python', 'api/orders.py');+ assert.deepEqual(r.routes.map((x) => `${x.method} ${x.path}`), ['GET /orders', 'POST /orders']);+ assert.equal(r.routes[0].handler, 'list_orders');+ assert.equal(r.routes[0].doc, 'List them.');+ assert.deepEqual(r.routers, { bp: '/api' });+ assert.equal(r.doc, 'Order endpoints.');+});++test('FastAPI: router prefix and path parameters', () => {+ const r = extract([+ `from fastapi import APIRouter`,+ `router = APIRouter(prefix="/items")`,+ `@router.get("/{item_id}")`,+ `async def read_item(item_id: int):`,+ ` return {}`,+ ].join('\n'), 'python', 'api/items.py');+ assert.deepEqual(r.routes.map((x) => `${x.method} ${x.path}`), ['GET /{item_id}']);+ assert.equal(r.routes[0].handler, 'read_item');+ assert.deepEqual(r.routers, { router: '/items' });+});++test('Go: grouped imports and http.HandleFunc endpoints', () => {+ const r = extract(`package main\nimport (\n "net/http"\n "example.com/app/store"\n)\nfunc main() { http.HandleFunc("/health", h) }\n`, 'go', 'cmd/main.go');+ assert.deepEqual(r.imports.map((i) => i.spec), ['net/http', 'example.com/app/store']);+ assert.deepEqual(r.routes.map((x) => `${x.method} ${x.path}`), ['ANY /health']);+});++test('web requests: fetch with template strings and axios with a method', () => {+ const r = extract([+ 'export const load = (id) => fetch(`/api/orders/${id}`);',+ `export const pay = (id) => axios.post('/api/orders/' + id + '/pay');`,+ ].join('\n'), 'typescript', 'web/src/api.ts');+ const calls = r.calls.map((c) => `${c.method || '*'} ${c.path}`);+ assert.ok(calls.includes('* /api/orders/${x}'), calls.join(', '));+ assert.ok(calls.includes('POST /api/orders/'), calls.join(', '));+});++test('flattenTemplates replaces every ${…} with a placeholder, nested or not', () => {+ assert.equal(flattenTemplates('fetch(`${API}/users/${id}`)'), 'fetch(`${x}/users/${x}`)');+});++test('doc comments: JSDoc is cleaned, license headers are ignored', () => {+ assert.equal(cleanDoc('/**\n * Lists orders.\n * @param x\n */'), 'Lists orders.');+ assert.equal(cleanDoc('# Copyright 2020 Example Corp'), null);+});diff --git a/tests/release.test.mjs b/tests/release.test.mjsnew file mode 100644index 0000000..7eebfc8--- /dev/null+++ b/tests/release.test.mjs@@ -0,0 +1,36 @@+// Release hygiene: the plugin manifests, the README badge and the changelog agree on the version,+// so a release never ships half-bumped.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import { REPO, SKILL, readJson } from './helpers.mjs';++const plugin = readJson(path.join(REPO, '.claude-plugin', 'plugin.json'));+const marketplace = readJson(path.join(REPO, '.claude-plugin', 'marketplace.json'));+const read = (p) => fs.readFileSync(path.join(REPO, p), 'utf8');++test('the plugin version is a semantic version', () => {+ assert.match(plugin.version, /^\d+\.\d+\.\d+$/);+});++test('the marketplace lists this plugin, from this repo', () => {+ const entry = marketplace.plugins.find((p) => p.name === plugin.name);+ assert.ok(entry, `marketplace.json lists ${plugin.name}`);+ assert.equal(entry.source, './');+});++test('the README version badge matches plugin.json', () => {+ assert.match(read('README.md'), new RegExp(`badge/version-${plugin.version.replaceAll('.', '\\.')}-`));+});++test('the changelog has an entry for this version', () => {+ assert.match(read('CHANGELOG.md'), new RegExp(`^## ${plugin.version.replaceAll('.', '\\.')} \\(\\d{4}-\\d{2}-\\d{2}\\)$`, 'm'));+});++test('the skill has a name and description, and every file it points to exists', () => {+ const skill = fs.readFileSync(path.join(SKILL, 'SKILL.md'), 'utf8');+ assert.match(skill, /^---\nname: floorplan\ndescription: .{50,}/);+ for (const [, ref] of skill.matchAll(/\]\((references\/[\w.-]+\.md)/g)) assert.ok(fs.existsSync(path.join(SKILL, ref)), ref);+ for (const [, script] of skill.matchAll(/scripts\/(\w+\.mjs)/g)) assert.ok(fs.existsSync(path.join(SKILL, 'scripts', script)), script);+});diff --git a/tests/sample-app.test.mjs b/tests/sample-app.test.mjsnew file mode 100644index 0000000..723cc8d--- /dev/null+++ b/tests/sample-app.test.mjs@@ -0,0 +1,74 @@+// End to end: map a small two-repo shop the way the skill does, then check the map, the Health+// check, the privacy promises (offline, no secret values, nothing committed) and an update.+import { test, before, after } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { shopApp, scanAndBuild, run, readGraph, readJson, writeJson, routeKeys, openEndpoints, allFiles, cleanup, FAKE_PASSWORD } from './helpers.mjs';++let root, graph, output;+before(() => { root = shopApp(); output = scanAndBuild(root); graph = readGraph(root); });+after(() => cleanup(root));++test('both repos are found and every file lands in a part of the map', () => {+ assert.deepEqual(graph.meta.repos.map((r) => r.path).sort(), ['shop-api', 'shop-web']);+ assert.equal(graph.meta.counts.unassigned, 0);+ assert.ok(graph.files.some((f) => f.p === 'shop-web/src/App.jsx' && f.n === 'web'));+});++test('endpoints get the prefix of the router they are mounted under', () => {+ assert.deepEqual(routeKeys(graph), ['DELETE /admin/users/:id', 'GET /api/orders', 'POST /api/notes', 'POST /api/orders/:id/refund']);+});++test("the website's requests are matched to the server's endpoints across repos", () => {+ const http = graph.links.filter((l) => l.k === 'http' && l.a === 'f:shop-web/src/api.js').map((l) => l.b);+ assert.ok(http.includes('f:shop-api/routes/orders.js'), JSON.stringify(graph.links.filter((l) => l.k === 'http')));+ assert.ok(graph.links.some((l) => l.k === 'import' && l.a === 'f:shop-web/src/App.jsx' && l.b === 'f:shop-web/src/api.js'));+});++test('Health flags only the endpoint with no login check, and the hard-coded password', () => {+ // orders use requireAuth on the route, admin is checked where it's mounted, notes has nothing+ assert.deepEqual(openEndpoints(graph), ['POST /api/notes']);+ const secret = graph.health.issues.find((i) => i.kind === 'secret');+ assert.ok(secret, 'the password in config.js is reported');+ assert.deepEqual(secret.locations, [{ file: 'shop-api/config.js', line: 1 }]);+});++test('the secret value is never written anywhere Floorplan writes, or printed', () => {+ assert.ok(!output.includes(FAKE_PASSWORD), 'scan/build output');+ for (const f of allFiles(path.join(root, 'floorplan'))) assert.ok(!f.text.includes(FAKE_PASSWORD), path.relative(root, f.path));+});++test('the map makes no outside requests: scripts, styles and fonts are all inside the file', () => {+ const html = fs.readFileSync(path.join(root, 'floorplan', 'index.html'), 'utf8');+ assert.doesNotMatch(html, /<script[^>]*\ssrc\s*=\s*["']?(https?:)?\/\//i);+ assert.doesNotMatch(html, /<link[^>]*\shref\s*=\s*["']?(https?:)?\/\//i);+ assert.doesNotMatch(html, /url\(\s*["']?(https?:)?\/\//i);+ assert.doesNotMatch(html, /@import/);+ assert.match(html, /@font-face\{font-family:"Inter"/);+});++test('nothing Floorplan makes is committed: floorplan/ ignores itself', () => {+ assert.equal(fs.readFileSync(path.join(root, 'floorplan', '.gitignore'), 'utf8').trim().split('\n').pop(), '*');+});++test('query.mjs finds things on the map by plain words', () => {+ const found = JSON.parse(execFileSync(process.execPath, [path.join(root, 'floorplan', 'query.mjs'), 'find', 'refund'], { encoding: 'utf8' }));+ const ids = JSON.stringify(found);+ assert.ok(ids.includes('r:'), `an endpoint is found: ${ids.slice(0, 300)}`);+});++test('an update carries descriptions over to a renamed file', () => {+ const descFile = path.join(root, 'floorplan', 'descriptions', 'api.json');+ const desc = { name: 'Customer notes', description: 'Saves a note a customer leaves.' };+ writeJson(descFile, { files: { 'shop-api/routes/notes.js': desc } });+ fs.renameSync(path.join(root, 'shop-api/routes/notes.js'), path.join(root, 'shop-api/routes/feedback.js'));+ const server = path.join(root, 'shop-api/server.js');+ fs.writeFileSync(server, fs.readFileSync(server, 'utf8').replaceAll('notes', 'feedback'));+ run('refresh.mjs', root);+ const files = readJson(descFile).files;+ assert.deepEqual(files['shop-api/routes/feedback.js'], desc);+ assert.equal(files['shop-api/routes/notes.js'], undefined);+ assert.equal(readGraph(root).files.find((f) => f.p === 'shop-api/routes/feedback.js').name, 'Customer notes');+});diff --git a/tests/secrets.test.mjs b/tests/secrets.test.mjsnew file mode 100644index 0000000..107fc92--- /dev/null+++ b/tests/secrets.test.mjs@@ -0,0 +1,38 @@+// Health's secret check: it finds keys and passwords written into code, records only where they are+// and a masked hint, and never keeps the value itself. Secret-looking test values are assembled at+// runtime so none is ever committed to this repo.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { lib, FAKE_PASSWORD } from './helpers.mjs';++const { findIssues } = await lib('health.mjs');+const secrets = (src, path = 'app/config.py', lang = 'python') => findIssues(src, { path, category: 'code', lang }).filter((x) => x.k === 'secret');+const FAKE_GITHUB_TOKEN = 'ghp_' + 'aBcD' + '1e2F3g4H5i6J7k8L9m0N1o2P3q4R5s6T7u8V';++test('a hard-coded password is found, with its line, and masked', () => {+ const [s, ...rest] = secrets(`PORT = 3000\nDB_PASSWORD = "${FAKE_PASSWORD}"\n`);+ assert.equal(rest.length, 0);+ assert.equal(s.line, 2);+ assert.equal(s.name, 'DB_PASSWORD');+ assert.equal(s.sev, 'high');+ assert.equal(s.hint, `${FAKE_PASSWORD.length} characters`, 'a password hint gives only its length');+});++test('a known key format is named after its service and shows only its first characters', () => {+ const [s] = secrets(`token = "${FAKE_GITHUB_TOKEN}"`);+ assert.equal(s.svc, 'GitHub');+ assert.match(s.hint, /^starts “ghp_…”, \d+ characters$/);+});++test('the secret value never appears in what Health records', () => {+ for (const found of [secrets(`DB_PASSWORD = "${FAKE_PASSWORD}"`), secrets(`token = "${FAKE_GITHUB_TOKEN}"`)]) {+ const text = JSON.stringify(found);+ assert.ok(!text.includes(FAKE_PASSWORD) && !text.includes(FAKE_GITHUB_TOKEN.slice(4)), text);+ }+});++test('placeholders, values read from the environment and public settings are not flagged', () => {+ assert.deepEqual(secrets('DB_PASSWORD = "changeme"\nAPI_KEY = "your-api-key-here"\nSECRET = "xxx"\n'), []);+ assert.deepEqual(secrets('DB_PASSWORD = os.environ["DB_PASSWORD"]\nAPI_KEY = os.getenv("API_KEY")\n'), []);+ assert.deepEqual(secrets('API_URL = "https://api.example.com/v1/orders"\n'), []);+});diff --git a/tests/serve.test.mjs b/tests/serve.test.mjsnew file mode 100644index 0000000..36302e6--- /dev/null+++ b/tests/serve.test.mjs@@ -0,0 +1,74 @@+// The map's local server: it listens only on this machine, and its API answers only the map page it+// served (a per-start token, from the same origin), so other websites can't use it.+import { test, before, after } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { shopApp, scanAndBuild, cleanup } from './helpers.mjs';++let root, server, base, token;+before(async () => {+ root = shopApp();+ scanAndBuild(root);+ const port = 20000 + Math.floor(Math.random() * 20000);+ // no Claude CLI and no waitlist card: this only exercises the server itself+ server = spawn(process.execPath, [path.join(root, 'floorplan', 'serve.mjs'), '--port', String(port), '--no-open'], {+ cwd: root, env: { ...process.env, FLOORPLAN_CLAUDE: path.join(root, 'no-such-cli'), FLOORPLAN_NO_PROMPTS: '1' }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ base = await new Promise((resolve, reject) => {+ let out = '';+ const timer = setTimeout(() => reject(new Error(`server didn't start: ${out}`)), 20000);+ server.stdout.on('data', (d) => { out += d; const m = /Floorplan: (http:\/\/\S+)/.exec(out); if (m) { clearTimeout(timer); resolve(m[1]); } });+ server.on('exit', (code) => reject(new Error(`server exited (${code}): ${out}`)));+ });+ token = /"token":"([0-9a-f]+)"/.exec(await (await fetch(base + '/')).text())?.[1];+});+after(async () => {+ // wait for the server to exit first: on Windows its working folder can't be removed while it runs+ if (server && server.exitCode === null) await new Promise((resolve) => { server.once('exit', resolve); server.kill(); });+ cleanup(root);+});++const api = (p, { headers = {}, ...opts } = {}) => fetch(base + p, { ...opts, headers: { 'content-type': 'application/json', ...headers } });++test('it listens on 127.0.0.1 only', () => {+ assert.match(base, /^http:\/\/127\.0\.0\.1:\d+$/);+});++test('the page it serves carries a fresh token', () => {+ assert.match(token || '', /^[0-9a-f]{32}$/);+});++test('API calls without the token are refused', async () => {+ assert.equal((await api('/api/flows')).status, 403);+ assert.equal((await api('/api/ask', { method: 'POST', body: '{"question":"hi"}' })).status, 403);+ assert.equal((await api('/api/flows', { headers: { 'x-floorplan-token': 'wrong' } })).status, 403);+});++test('API calls with the token from another website are refused', async () => {+ const r = await api('/api/flows', { headers: { 'x-floorplan-token': token, origin: 'https://evil.example' } });+ assert.equal(r.status, 403);+});++test('API calls with the token from the map itself work', async () => {+ const r = await api('/api/flows', { headers: { 'x-floorplan-token': token } });+ assert.equal(r.status, 200);+ assert.deepEqual(await r.json(), { flows: [] });+});++test('files outside the map folder are never served', async () => {+ // including a neighbouring folder whose name starts with "floorplan"+ fs.mkdirSync(path.join(root, 'floorplan-old'));+ fs.writeFileSync(path.join(root, 'floorplan-old', 'notes.txt'), 'private notes');+ for (const p of ['/../shop-api/config.js', '/%2e%2e/shop-api/config.js', '/..%2fshop-api%2fconfig.js', '/..%2ffloorplan-old%2fnotes.txt']) {+ const r = await fetch(base + p);+ const body = await r.text();+ assert.ok(!body.includes('DB_PASSWORD') && !body.includes('private notes'), `${p} -> ${r.status}`);+ }+});++test('a malformed address gets an error, and the server keeps running', async () => {+ assert.equal((await fetch(base + '/%E0%A4%A')).status, 400);+ assert.equal((await fetch(base + '/')).status, 200);+});