Files
meshcore-analyzer/test-embed-mode-1369.js
T
Kpa-clawbot 367265eb59 feat(#1369): cross-domain embed support (CORS env override + ?embed=1 chrome suppression) (#1500)
Closes #1369.

## What

Cross-domain embed support, shipped as two halves:

### Part A — CORS env override + read-only contract

* `applyCORSEnv()` reads `CORS_ALLOWED_ORIGINS` (comma-separated,
trimmed, empties dropped). Set in env → overrides
`cfg.CORSAllowedOrigins`. Unset/empty → config.json value wins.
* `Access-Control-Allow-Methods` tightened from `GET, POST, OPTIONS` →
`GET, HEAD, OPTIONS`. The cross-domain surface is read-only by contract;
same-origin admin writes don't go through preflight and are unaffected.
* `config.example.json` adds `corsAllowedOrigins: []` + a comment
explaining the env override and the embed URL pattern.
* No wildcards introduced (still supported as `["*"]` for ops that opt
in). No credentialed CORS.

### Part B — `?embed=1` chrome suppression

* `shouldEmbedRoute(basePage, hashSearch)` — pure helper, allowlisted to
`map` and `channels`, requires `embed=1` in the hash querystring.
* `navigate()` toggles `body.embed` based on the helper.
* CSS hides `.top-nav`, `[data-bottom-nav]`, `.nav-drawer`,
`.nav-drawer-backdrop`, zeroes body padding/margin, reclaims `100dvh`
for `#app.app-fixed`.

Use: `<iframe src="https://analyzer.example/#/map?embed=1">`. For
iframe-only display, no CORS entry is needed (the iframe loads the
document, not a JSON API). The CORS allowlist only matters when the
embedding origin's own JS calls `/api/*` directly.

## Tests

| File | Asserts | Status |
|---|---|---|
| `cmd/server/cors_embed_1369_test.go` | 4 (env override, env-empty,
env-trim, GET/HEAD contract, preflight POST rejected) | green |
| `test-embed-mode-1369.js` | 9 (helper allowlist + param parsing) |
green |
| `cmd/server/cors_test.go` | existing | updated to read-only method-set
assertion |

TDD: 2 red commits (one per part, both compile, both fail on assertions)
→ 2 green commits.

## Out of scope (per the issue's narrow ask)

* Other SPA routes do not honor `?embed=1` (their chrome makes layout
assumptions; defer until requested).
* No iframe sandboxing recommendation — that's the embedder's
responsibility.
* No CSP / `X-Frame-Options` change in this PR — frames are already
permitted; add an explicit `frame-ancestors` policy in a follow-up if
operators want to whitelist embedders at the HTTP layer too.

## Security notes (DJB lens)

* Allowlist is exact-match, case-sensitive string compare — no
normalization, no scheme/host parsing, no surprises.
* No `Access-Control-Allow-Credentials` (would let third parties read
auth'd state via cookies).
* No reflection of arbitrary origins (every echoed origin came from the
allowlist).
* Methods narrowed to read-only; even a misconfigured allowlist can't
grant cross-origin writes through this middleware.

🤖 Generated with OpenClaw

---------

Co-authored-by: bot <bot@corescope.local>
2026-05-30 13:22:41 -07:00

99 lines
4.2 KiB
JavaScript

/* Unit tests for issue #1369 embed-mode helper.
*
* Red commit: shouldEmbedRoute() does not exist yet; this test fails on import.
* Green commit: define shouldEmbedRoute(basePage, hashSearch) in public/app.js
* and expose for tests.
*
* The contract:
* - returns true ONLY when basePage is 'map' or 'channels' AND the hash
* query string contains embed=1 (e.g. '#/map?embed=1' → search='embed=1').
* - false for any other route, false when embed param is missing or != '1'.
* - the route-allowlist is deliberate: other pages have chrome assumptions
* that we are not committing to support in embed mode (Tufte: scope tight,
* ship the two surfaces operators asked for, no more).
*/
'use strict';
const vm = require('vm');
const fs = require('fs');
const path = require('path');
const assert = require('assert');
let passed = 0, failed = 0;
function test(name, fn) {
try { fn(); passed++; console.log(' ✅ ' + name); }
catch (e) { failed++; console.log(' ❌ ' + name + ': ' + e.message); }
}
// Load app.js into a sandbox. We only need the helper, so we wrap with a
// minimal browser shim that no-ops everything app.js touches at import time.
const appSrc = fs.readFileSync(path.join(__dirname, 'public', 'app.js'), 'utf8');
const ctx = {
window: { addEventListener: () => {}, dispatchEvent: () => {}, matchMedia: () => ({ matches: false }) },
document: {
readyState: 'complete',
documentElement: { setAttribute: () => {}, getAttribute: () => null, classList: { add: () => {}, remove: () => {}, toggle: () => {} } },
body: { classList: { add: () => {}, remove: () => {}, toggle: () => {} } },
createElement: () => ({ id: '', textContent: '', innerHTML: '', classList: { add: () => {}, remove: () => {} }, setAttribute: () => {}, appendChild: () => {} }),
head: { appendChild: () => {} },
getElementById: () => null,
addEventListener: () => {},
querySelectorAll: () => [],
querySelector: () => null,
},
console, Date, Math, JSON, RegExp, Error, TypeError, Map, Set,
Array, Object, String, Number, Boolean, parseInt, parseFloat, isNaN, isFinite,
encodeURIComponent, decodeURIComponent, URLSearchParams,
setTimeout: () => 0, clearTimeout: () => {}, setInterval: () => 0, clearInterval: () => {},
fetch: () => Promise.resolve({ json: () => Promise.resolve({}) }),
performance: { now: () => Date.now() },
localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
location: { hash: '', search: '' },
CustomEvent: class {},
navigator: { language: 'en-US' },
requestAnimationFrame: () => 0,
};
ctx.globalThis = ctx;
ctx.self = ctx;
try {
vm.createContext(ctx);
vm.runInContext(appSrc, ctx, { filename: 'app.js' });
} catch (e) {
// app.js does a lot at import; if any helper init blows up, it's fine as
// long as shouldEmbedRoute is bound by the time we test it.
console.log(' (app.js init threw: ' + e.message + ' — proceeding)');
}
console.log('issue #1369 — shouldEmbedRoute');
test('exists', () => {
assert.strictEqual(typeof ctx.shouldEmbedRoute, 'function', 'shouldEmbedRoute must be defined on window/global');
});
test('map + embed=1 → true', () => {
assert.strictEqual(ctx.shouldEmbedRoute('map', 'embed=1'), true);
});
test('channels + embed=1 → true', () => {
assert.strictEqual(ctx.shouldEmbedRoute('channels', 'embed=1'), true);
});
test('map + embed=1 mixed with other params → true', () => {
assert.strictEqual(ctx.shouldEmbedRoute('map', 'region=SFO&embed=1&zoom=8'), true);
});
test('packets + embed=1 → false (route not in allowlist)', () => {
assert.strictEqual(ctx.shouldEmbedRoute('packets', 'embed=1'), false);
});
test('nodes + embed=1 → false', () => {
assert.strictEqual(ctx.shouldEmbedRoute('nodes', 'embed=1'), false);
});
test('map + no embed param → false', () => {
assert.strictEqual(ctx.shouldEmbedRoute('map', 'region=SFO'), false);
});
test('map + embed=0 → false', () => {
assert.strictEqual(ctx.shouldEmbedRoute('map', 'embed=0'), false);
});
test('map + empty search → false', () => {
assert.strictEqual(ctx.shouldEmbedRoute('map', ''), false);
});
console.log('\n' + '═'.repeat(40));
console.log(' embed-mode helper: ' + passed + ' passed, ' + failed + ' failed');
console.log('═'.repeat(40) + '\n');
if (failed > 0) process.exit(1);