This commit is contained in:
Mateusz Gruszczyński committed 2026-11-19 12:40:17 +01:00
1 parent d4a604970e
commit 38a23e2210
40 files changed
+928 -532

No files matched your search

-82
View File
@@ -1,82 +0,0 @@
#!/usr/bin/env python3
"""Browser smoke test for the optional semantic SVG interface icons.
Uses a locally installed Chromium when available and otherwise exits successfully
with a skip message. It exercises the real index.html plus the embedded icon
module without requiring a running RustProxy backend.
"""
from __future__ import annotations
from pathlib import Path
import html
import re
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
WEB = ROOT / "src/admin/web"
chromium = next((shutil.which(name) for name in ("chromium", "chromium-browser", "google-chrome") if shutil.which(name)), None)
if not chromium:
print("Panel SVG icon browser smoke: SKIP (Chromium not installed)")
raise SystemExit(0)
page = (WEB / "index.html").read_text(encoding="utf-8")
page = re.sub(r'<script\s+defer=""\s+src="/assets/app___RUSTPROXY_ASSET_ID__\.js"></script>', "", page, count=1)
icons = (WEB / "app/icons.js").read_text(encoding="utf-8")
script = r'''
const $ = id => document.getElementById(id);
const translations = { edit: "Edit", remove: "Remove", copyValue: "Copy value", previous: "Previous", next: "Next" };
function t(key) { return translations[key] || key; }
''' + icons + r'''
(() => {
const fail = message => { document.getElementById("browser-icon-test").textContent = `FAIL: ${message}`; throw new Error(message); };
const result = document.getElementById("browser-icon-test");
const eligible = [...document.querySelectorAll("button, a.primary, a.outline, a.quiet")].filter(node => window.rustProxyIcons.iconFor(node) !== null);
if (document.querySelectorAll("svg.ui-icon").length !== 0) fail("icons must be absent before enabling the preference");
window.rustProxyIcons.setEnabled(true);
const decorated = eligible.filter(node => node.querySelector(":scope > svg.ui-icon"));
if (decorated.length !== eligible.length) fail(`expected ${eligible.length} decorated controls, got ${decorated.length}`);
if ([...document.querySelectorAll("svg.ui-icon")].some(icon => icon.getAttribute("aria-hidden") !== "true")) fail("SVG icons must be aria-hidden");
const expectedPanels = { overview: "grid", vhosts: "network", "web-server": "globe", "docker-vhosts": "box", redirects: "route", notfound: "fileX", streams: "transfer", "acl-profiles": "shield", tls: "certificate", traffic: "activity", cache: "database", transform: "wand", settings: "settings" };
for (const [panel, icon] of Object.entries(expectedPanels)) {
const button = document.querySelector(`[data-panel="${panel}"]`);
if (button?.querySelector(":scope > svg.ui-icon")?.dataset.uiIcon !== icon) fail(`panel ${panel} must use ${icon}`);
}
const dynamic = document.createElement("button"); dynamic.type = "button"; dynamic.className = "quiet"; dynamic.textContent = "Edit"; document.body.append(dynamic);
window.rustProxyIcons.refresh(dynamic);
if (dynamic.querySelector("svg.ui-icon")?.dataset.uiIcon !== "edit") fail("translated dynamic Edit action must use edit icon");
dynamic.textContent = "Remove item"; dynamic.setAttribute("aria-label", "Remove item"); window.rustProxyIcons.refresh(dynamic);
if (dynamic.querySelector("svg.ui-icon")?.dataset.uiIcon !== "trash") fail("dynamic Remove action must use trash icon");
const visibility = document.createElement("button"); visibility.dataset.dashboardWidgetAction = "toggle"; visibility.className = "dashboard-widget-toggle is-hidden"; document.body.append(visibility);
window.rustProxyIcons.refresh(visibility);
if (visibility.querySelector("svg.ui-icon")?.dataset.uiIcon !== "eyeOff") fail("hidden widget action must use eyeOff");
visibility.classList.remove("is-hidden"); window.rustProxyIcons.refresh(visibility);
if (visibility.querySelector("svg.ui-icon")?.dataset.uiIcon !== "eye") fail("visible widget action must use eye");
window.rustProxyIcons.setEnabled(false);
if (document.querySelectorAll("svg.ui-icon").length !== 0) fail("disabling preference must remove all injected icons");
result.textContent = `OK ${eligible.length} controls`;
})();
'''
page = page.replace("</body>", '<pre id="browser-icon-test">PENDING</pre><script>' + script + "</script></body>", 1)
with tempfile.TemporaryDirectory(prefix="rustproxy-icons-") as tmp:
target = Path(tmp) / "icons-test.html"
target.write_text(page, encoding="utf-8")
try:
proc = subprocess.run(
[chromium, "--headless", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--virtual-time-budget=1000", "--dump-dom", target.as_uri()],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=8,
check=False,
)
except subprocess.TimeoutExpired:
print("Panel SVG icon browser smoke: SKIP (Chromium cannot start in this environment)")
raise SystemExit(0)
match = re.search(r'<pre id="browser-icon-test">([^<]+)</pre>', proc.stdout)
status = html.unescape(match.group(1)) if match else "missing result marker"
if proc.returncode != 0 or not status.startswith("OK "):
raise SystemExit(f"Panel SVG icon browser smoke failed: {status}\n{proc.stderr[-4000:]}")
print(f"Panel SVG icon browser smoke: {status}")
-127
View File
@@ -1,127 +0,0 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const root = path.join(__dirname, "..");
const read = relative => fs.readFileSync(path.join(root, relative), "utf8");
const preferences = read("src/admin/web/app/preferences.js");
const icons = read("src/admin/web/app/icons.js");
const core = read("src/admin/web/app/core.js");
const html = read("src/admin/web/index.html");
const css = read("src/admin/web/css/10-base.css");
const overviewCss = read("src/admin/web/css/30-overview.css");
const integrations = read("src/admin/web/integrations.js");
const metricsPartial = read("src/admin/web/partials/overview-metrics.html");
const pl = JSON.parse(read("langs/pl_pl.json"));
const openapi = JSON.parse(read("src/admin/openapi.json"));
assert.match(html, /id="ui-interface-icons"[^>]*type="checkbox"/);
assert.match(preferences, /interface_icons:\s*false/);
assert.match(preferences, /applyAdminInterfaceIcons\(value\.interface_icons\)/);
assert.match(preferences, /saveAppearancePreference\(\{ interface_icons: next \}/);
assert.match(preferences, /interface:\s*\{[^}]*interface_icons:\s*false/);
assert.match(core, /rustProxyIcons\?\.refresh\?\.\(\)/);
assert.match(icons, /dataset\.interfaceIcons !== "true"/);
assert.match(icons, /aria-hidden", "true"/);
assert.match(icons, /data\.panel|dataset\.panel/);
assert.match(icons, /MutationObserver/);
assert.match(icons, /if \(target\.dataset\.httpSettingsTab\) return "network"/);
assert.match(icons, /#web-service-preset-apply.*return "wand"/);
assert.match(icons, /vhost-quick-toggle\.is-enable.*return "toggleOn"/);
assert.match(icons, /vhost-quick-toggle\.is-disable.*return "toggleOff"/);
assert.equal((html.match(/class="outline about-repository" data-ui-icon-name="none"/g) || []).length, 4);
assert.match(metricsPartial, /backend-latency-stat[\s\S]*backend-health-origins[\s\S]*backend-dashboard-latency-detail/);
assert.equal(JSON.parse(read("langs/en_US.json")).translations.backendWidgetProbeCount, "Health Origins");
assert.match(icons, /#tunnels-open.*return null/);
assert.match(icons, /#logs-menu > summary/);
assert.match(integrations, /listener-h2-settings-link.*uiIconName = "settings"/);
assert.match(integrations, /listener-h3-settings-link.*uiIconName = "settings"/);
assert.match(metricsPartial, /stat-corner-badge[^>]+data-ui-icon-name="none"[^>]+id="tunnels-open"/);
assert.match(overviewCss, /\.stat-corner-badge/);
assert.equal(pl.translations.interfaceIconsHelp, "Dodaje semantyczne ikony SVG do nawigacji, akcji, zakładek i okien dialogowych.");
assert.match(css, /html\[data-interface-icons="true"\]/);
assert.equal(openapi.components.schemas.AdminPreferences.properties.interface_icons.default, false);
assert.equal(openapi.components.schemas.AdminPreferences.properties.interface_icons.type, "boolean");
for (const icon of ["plus", "save", "check", "trash", "edit", "refresh", "settings", "search", "key", "certificate", "shield", "network", "database", "wand", "grid", "activity", "book", "toggleOn", "toggleOff"]) {
assert.ok(new RegExp(`\\b${icon}:`).test(icons), `missing semantic SVG icon definition: ${icon}`);
}
const explicitIcons = { "overview-layout-unlock": "unlock", "overview-inline-save": "lock", "overview-layout-open": "layers", "docker-settings-open": "settings", "login-submit": "login", "revoke-sessions": "logout", "about-open": "info" };
for (const [id, icon] of Object.entries(explicitIcons)) assert.match(icons, new RegExp(`"${id}": "${icon}"`), `${id} must use ${icon}`);
assert.match(icons, /\(\^\|\[\^p\]\)reset/, "preset buttons must not match the reset rule");
assert.match(icons, /UI_GLYPH_LABEL/);
assert.match(icons, /raw === key/, "English labels equal to their key must still count as translated");
for (const icon of ["unlock", "layers", "expand", "collapse", "ban", "eraser", "hash", "info", "plug", "transfer", "mapPin", "compare"]) {
assert.ok(new RegExp(`\\b${icon}:`).test(icons), `missing semantic SVG icon definition: ${icon}`);
}
const logo = read("src/admin/web/app/logo-animation.js");
const router = read("src/admin/router.rs");
const shellCss = read("src/admin/web/css/20-shell.css");
assert.match(html, /id="ui-logo-animation"[^>]*type="checkbox"/);
assert.match(router, /web\/app\/logo-animation\.js/);
assert.match(preferences, /logo_animation:\s*false/);
assert.match(preferences, /applyAdminLogoAnimation\(value\.logo_animation\)/);
assert.match(preferences, /saveAppearancePreference\(\{ logo_animation: next \}/);
assert.match(logo, /prefers-reduced-motion: reduce/);
assert.match(logo, /document\.hidden/);
assert.match(shellCss, /prefers-reduced-motion: reduce[\s\S]*data-logo-effect/);
assert.equal(openapi.components.schemas.AdminPreferences.properties.logo_animation.default, false);
assert.ok(pl.translations.logoAnimation && pl.translations.logoAnimationHelp);
const runtimeJs = read("src/admin/web/app/runtime.js");
const scalesJs = read("src/admin/web/app/chart-scales.js");
const editorsCss = read("src/admin/web/css/40-editors.css");
assert.match(runtimeJs, /row\.querySelector\("svg:not\(\.ui-icon\)"\)/);
assert.doesNotMatch(runtimeJs, /row\.querySelector\("svg"\)/);
assert.match(runtimeJs, /querySelector\(":scope > svg\.ui-icon"\)/);
assert.match(scalesJs, /svg\.classList\.contains\("ui-icon"\)/);
assert.match(scalesJs, /querySelectorAll\("svg:not\(\.ui-icon\)"\)/);
for (const source of [css, overviewCss, editorsCss]) assert.doesNotMatch(source, /(^|\n)[^\n{}]*(\.network-interface-row|\.stat-chart|\.activity-card|\.system-card|\.function-live-chart|\.mini-live-chart|\.vhost-chart|\.connection-card) svg[ ,{]/, "descendant chart svg rules must exclude .ui-icon");
assert.match(css, /html\[data-interface-icons="true"\] :is\(button, a, summary\)>svg\.ui-icon/);
assert.match(icons, /\.mobile-menu-toggle"\) return null|draft-dock-toggle, \.mobile-menu-toggle/);
assert.match(editorsCss, /\.vhost-backend-protocol-badge \{[^}]*letter-spacing: 1px;[^}]*\}/);
assert.match(editorsCss, /\.tls-pqc-control>a/);
console.log("Panel SVG icon preference contract: OK");
{
const cssDir = path.join(__dirname, "..", "src", "admin", "web", "css");
for (const name of fs.readdirSync(cssDir).filter((file) => file.endsWith(".css"))) {
assert.doesNotMatch(fs.readFileSync(path.join(cssDir, name), "utf8"), /body\[data-density/, `${name} still has legacy body[data-density] rules`);
}
}
{
const rt = fs.readFileSync(path.join(__dirname, "..", "src", "admin", "web", "app", "runtime.js"), "utf8");
assert.match(rt, /function fitCacheMixLabels/);
assert.match(rt, /segment\.textContent = mix && pct > 0/);
}
{
const css = fs.readFileSync(path.join(__dirname, "..", "src", "admin", "web", "css", "50-settings.css"), "utf8");
assert.match(css, /#settings-page-appearance \.appearance-settings-grid>label \{/);
assert.match(css, /#panel-settings \.settings-tabs\.sub-tabs \{\s*display: flex;\s*flex-direction: row;/);
}
{
const root = path.join(__dirname, "..");
const read = (file) => fs.readFileSync(path.join(root, file), "utf8");
const styles = ["default", "soft", "technical", "high_contrast", "neon", "monochrome", "warm", "cool", "sunset", "aurora", "ocean", "forest", "pastel", "terminal", "blueprint", "colorblind"];
const rust = read("src/admin/preferences.rs"), js = read("src/admin/web/app/preferences.js"), tokens = read("src/admin/web/css/00-tokens.css"), html = read("src/admin/web/index.html");
const openapi = JSON.parse(read("src/admin/openapi.json")).components.schemas;
const enumValues = JSON.stringify(openapi).match(/"chart_style":\{"type":"string","enum":(\[[^\]]*\])/);
assert.ok(enumValues, "chart_style enum must be present in OpenAPI");
const documented = JSON.parse(enumValues[1]);
for (const style of styles) {
assert.ok(documented.includes(style), `OpenAPI chart_style missing ${style}`);
assert.ok(rust.includes(`"${style}"`), `Rust validation missing ${style}`);
assert.ok(js.includes(`"${style}"`), `preferences.js missing ${style}`);
assert.ok(tokens.includes(`html[data-chart-style=${style}]`), `tokens missing ${style}`);
assert.ok(tokens.includes(`.chart-style-choice[data-chart-preset=${style}]`), `swatches missing ${style}`);
assert.ok(html.includes(`value="${style}"`), `selector missing ${style}`);
}
assert.equal(documented.length, styles.length, "OpenAPI chart_style enum must list exactly the supported styles");
}
-124
View File
@@ -1,124 +0,0 @@
#!/usr/bin/env python3
"""Static integrity checks for the embedded administration interface.
The test intentionally uses only the Python standard library. It verifies the
actual HTML assembly and JavaScript files embedded by src/admin/router.rs; it is
not a replacement for Rust/browser integration tests.
"""
from __future__ import annotations
from collections import Counter
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
WEB = ROOT / "src/admin/web"
ROUTER = (ROOT / "src/admin/router.rs").read_text(encoding="utf-8")
def assembled_html() -> str:
html = (WEB / "index.html").read_text(encoding="utf-8")
metrics = (WEB / "partials/overview-metrics.html").read_text(encoding="utf-8")
charts = (WEB / "partials/overview-charts.html").read_text(encoding="utf-8")
metrics_main, metrics_web = metrics.split("<!-- RP_METRICS_SPLIT -->", 1)
charts_main, charts_web = charts.split("<!-- RP_CHARTS_SPLIT -->", 1)
return (
html.replace("<!-- RP_METRICS_MAIN -->", metrics_main)
.replace("<!-- RP_METRICS_WEB -->", metrics_web)
.replace("<!-- RP_CHARTS_MAIN -->", charts_main)
.replace("<!-- RP_CHARTS_WEB -->", charts_web)
)
def embedded_app_sources() -> list[Path]:
start = ROUTER.index("fn admin_app_javascript()")
end = ROUTER.index("fn admin_vhosts_javascript()", start)
app_block = ROUTER[start:end]
paths = [WEB / rel for rel in re.findall(r'include_str!\("web/([^"\n]+\.js)"\)', app_block)]
vstart = end
vend = ROUTER.index("pub fn router", vstart)
vhost_block = ROUTER[vstart:vend]
vhost_paths = [WEB / rel for rel in re.findall(r'include_str!\("web/([^"\n]+\.js)"\)', vhost_block)]
result: list[Path] = []
for path in [*paths, *vhost_paths]:
if path not in result:
result.append(path)
return result
def attribute_values(html: str, name: str) -> set[str]:
return set(re.findall(rf'\b{re.escape(name)}=["\']([^"\']+)', html))
html = assembled_html()
ids = re.findall(r'\bid=["\']([^"\']+)', html)
duplicates = sorted(name for name, count in Counter(ids).items() if count > 1)
assert not duplicates, f"duplicate panel DOM ids: {duplicates}"
id_set = set(ids)
sources = embedded_app_sources()
assert sources, "no embedded administration JavaScript sources found"
missing_files = [str(path.relative_to(ROOT)) for path in sources if not path.is_file()]
assert not missing_files, f"missing embedded JS sources: {missing_files}"
literal_refs: dict[str, set[str]] = {}
patterns = [
re.compile(r'\$\(["\']([^"\']+)["\']\)'),
re.compile(r'document\.getElementById\(["\']([^"\']+)["\']\)'),
]
for path in sources:
source = path.read_text(encoding="utf-8")
for pattern in patterns:
for dom_id in pattern.findall(source):
literal_refs.setdefault(dom_id, set()).add(str(path.relative_to(ROOT)))
missing_refs = {dom_id: sorted(paths) for dom_id, paths in literal_refs.items() if dom_id not in id_set}
assert not missing_refs, f"embedded panel JS references missing DOM ids: {missing_refs}"
assert "ui-interface-icons" in id_set, "Appearance must expose the SVG icon toggle"
assert "ui-stable-dialog-position" in id_set, "Appearance must expose the stable dialog position toggle"
preferences_js = (WEB / "app/preferences.js").read_text(encoding="utf-8")
editors_css = (WEB / "css/40-editors.css").read_text(encoding="utf-8")
openapi = __import__("json").loads((ROOT / "src/admin/openapi.json").read_text(encoding="utf-8"))
pl = __import__("json").loads((ROOT / "langs/pl_pl.json").read_text(encoding="utf-8"))["translations"]
assert re.search(r"stable_dialog_position:\s*true", preferences_js), "stable dialog position must default on in the panel"
assert "applyAdminStableDialogPosition(value.stable_dialog_position)" in preferences_js
assert "saveAppearancePreference({ stable_dialog_position: next }" in preferences_js
assert 'html[data-stable-dialog-position="true"] dialog.vhost-dialog[open]' in editors_css
assert openapi["components"]["schemas"]["AdminPreferences"]["properties"]["stable_dialog_position"]["default"] is True
assert pl.get("stableDialogPosition") and pl.get("stableDialogPositionHelp")
assert "ui-switch-controls" in id_set, "Appearance must expose the switch controls toggle"
assert "ui-chart-tooltips" in id_set, "Appearance must expose the chart value tooltip toggle"
assert re.search(r"chart_tooltips:\s*false", preferences_js), "chart tooltips must default off in the panel"
assert "saveAppearancePreference({ chart_tooltips: next }" in preferences_js
assert openapi["components"]["schemas"]["AdminPreferences"]["properties"]["chart_tooltips"]["default"] is False
assert pl.get("chartTooltips") and pl.get("chartTooltipsHelp")
assert re.search(r"switch_controls:\s*true", preferences_js), "switch controls must default on in the panel"
assert "applyAdminSwitchControls(value.switch_controls)" in preferences_js
assert "saveAppearancePreference({ switch_controls: next }" in preferences_js
assert openapi["components"]["schemas"]["AdminPreferences"]["properties"]["switch_controls"]["default"] is True
assert pl.get("switchControls") and pl.get("switchControlsHelp")
assert any(path.name == "icons.js" for path in sources), "semantic icon module must be embedded in app.js"
assert 'data-i18n="overviewExtraRecentSamples"' not in html, "Overview metric tiles must not show the redundant Recent samples footer"
overview_extra = (WEB / "app/overview-extra-metrics.js").read_text(encoding="utf-8")
assert 't("overviewExtraRecentSamples")' not in overview_extra, "Overview metric details must not fall back to the generic Recent samples label"
# Every visible primary navigation target must have a panel section. filelogs is
# intentionally opened from the Logs menu rather than the main navigation.
panel_targets = attribute_values(html, "data-panel")
panel_sections = {value.removeprefix("panel-") for value in id_set if value.startswith("panel-")}
assert panel_targets <= panel_sections, f"navigation targets without panels: {sorted(panel_targets - panel_sections)}"
assert panel_sections - panel_targets <= {"filelogs"}, f"unexpected orphan panels: {sorted(panel_sections - panel_targets)}"
# Tab/page contracts used by the generic tab handlers in the embedded JS.
for prefix in ("settings", "policy-settings", "cache-settings", "logging-settings", "traffic"):
tabs = attribute_values(html, f"data-{prefix}-tab")
pages = attribute_values(html, f"data-{prefix}-page")
assert tabs == pages, f"{prefix} tab/page mismatch: tabs={sorted(tabs - pages)}, pages={sorted(pages - tabs)}"
print(
f"Panel interface contract: OK ({len(ids)} unique DOM ids, "
f"{len(literal_refs)} literal JS references, {len(sources)} embedded JS files)"
)
-55
View File
@@ -1,55 +0,0 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const root = path.join(__dirname, "..");
const read = relative => fs.readFileSync(path.join(root, relative), "utf8");
const settings = read("src/admin/web/settings.js");
const certificateApi = read("src/admin/web/certificate-api.js");
const core = read("src/admin/web/app/core.js");
const cache = read("src/admin/web/cache-panel.js");
const transform = read("src/admin/web/transform-panel.js");
const traffic = read("src/admin/web/traffic-panel.js");
const refresh = read("src/admin/web/app/refresh.js");
const management = read("src/admin/web/management.js");
const loggingApi = read("src/admin/logging_api.rs");
const openapi = JSON.parse(read("src/admin/openapi.json"));
assert.match(settings, /authenticated && name === "certificate-api"[^\n]+rustProxyCertificateApi\?\.load/);
assert.match(settings, /authenticated && active === "certificate-api"[^\n]+rustProxyCertificateApi\?\.load/);
assert.ok(!/renderCertificateApi\(\);\s*loadCertificateApi\(\);\s*\}\)\(\);\s*$/.test(certificateApi),
"Certificate API must not fetch credentials when its module is initialized");
assert.match(core, /async function refresh\(force = false\)/);
assert.doesNotMatch(core, /includeLogs/);
assert.match(core, /new EventSource\(`\/api\/events\?interval=\$\{seconds\}&logs=false`\)/);
assert.match(loggingApi, /logs: Option<bool>/);
assert.match(loggingApi, /let include_logs = query\.logs\.unwrap_or\(true\)/);
assert.match(loggingApi, /if include_logs[\s\S]+logs_payload\(&state\)[\s\S]+else[\s\S]+live_status_payload/);
assert.match(core, /if \(payload\.logs\) renderLogs\(payload\.logs\)/);
assert.match(refresh, /active: \(\) => !!window\.rustProxyLogs\?\.active\?\.\(\)/);
assert.doesNotMatch(refresh, /manual\("logs-fallback"\).*manual\("system-info"\)/);
assert.match(management, /function active\(\) \{ return dialog\.open && !paused && !expanded; \}/);
assert.match(management, /syncLivePolling\(true\)/);
for (const [name, source, endpoint] of [
["cache", cache, "/api/cache"],
["transform", transform, "/api/transform"],
["traffic", traffic, "/api/traffic"],
]) {
assert.ok(/view=live/.test(source) || /set\(\"view\", \"live\"\)/.test(source), `${name} panel must use the lightweight polling view`);
assert.match(source, /data\.revision !== staticRevision/, `${name} panel must invalidate static data on config revision changes`);
assert.match(source, /reset\(\)[\s\S]{0,220}staticData = null[\s\S]{0,120}staticRevision = null/, `${name} panel reset must discard static cached API data`);
const operation = openapi.paths[endpoint].get;
const view = (operation.parameters || []).find(parameter => parameter.name === "view");
assert.deepEqual(view?.schema?.enum, ["live"], `${endpoint} must document view=live`);
}
const events = openapi.paths["/api/events"].get;
const logsFlag = (events.parameters || []).find(parameter => parameter.name === "logs");
assert.equal(logsFlag?.schema?.type, "boolean");
assert.equal(logsFlag?.schema?.default, true);
assert.equal(openapi.info.version, "0.38.6");
console.log("Panel refresh/API contract checks: OK");
-54
View File
@@ -1,54 +0,0 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const editor = fs.readFileSync(path.join(__dirname, "../src/admin/web/vhosts/editor.js"), "utf8");
const begin = editor.indexOf("const authMethodsByProvider = {");
const end = editor.indexOf("function load(value = defaults()", begin);
assert.ok(begin >= 0 && end > begin);
const values = new Map();
const context = vm.createContext({
str: key => values.get(key) || "",
yes: () => false,
num: () => 5,
nullable: () => null,
lines: () => []
});
const selection = vm.runInContext(editor.slice(begin, end) +
"\n({ authMethodsByProvider, inferredAuthentication, selectedAuthentication, readForwardProvider })", context);
const legacy = [
[{ basic_auth: { enabled: true } }, "basic", "basic"],
[{ tinyauth: { enabled: true } }, "tinyauth", "forward_auth"],
[{ authelia: { enabled: true } }, "authelia", "forward_auth"],
[{ authentik: { enabled: true } }, "authentik", "forward_auth"],
[{ oidc: { enabled: true } }, "custom", "oidc"],
[{}, "none", "none"]
];
for (const [vhost, provider, method] of legacy) {
const actual = selection.inferredAuthentication(vhost);
assert.equal(actual.provider, provider);
assert.equal(actual.method, method);
}
for (const provider of ["tinyauth", "authelia", "authentik", "pocket_id", "custom"]) {
const selected = { provider, method: "oidc" };
const actual = selection.inferredAuthentication({ authentication: selected, oidc: { enabled: true } });
assert.equal(actual.provider, provider);
assert.equal(actual.method, "oidc");
values.set("auth-provider", provider);
values.set("auth-method", "oidc");
assert.equal(selection.selectedAuthentication().method, "oidc");
for (const forward of ["authelia", "authentik"]) assert.equal(selection.readForwardProvider(forward).enabled, false);
}
for (const provider of ["authelia", "authentik"]) {
values.set("auth-provider", provider);
values.set("auth-method", "forward_auth");
assert.equal(selection.readForwardProvider(provider).enabled, true);
}
values.set("auth-provider", "none");
values.set("auth-method", "");
assert.equal(selection.selectedAuthentication().method, "none");
assert.deepEqual(Array.from(selection.authMethodsByProvider.pocket_id), ["oidc"]);
assert.deepEqual(Array.from(selection.authMethodsByProvider.basic), ["basic"]);
assert.deepEqual(Array.from(selection.authMethodsByProvider.authelia), ["forward_auth", "oidc"]);
console.log("Vhost provider/method UI selection checks: OK");