feat(js): harden global HTTP and module import contracts

This commit is contained in:
2026-04-20 22:41:07 +02:00
parent f189ef9df6
commit 7c47e818f2
12 changed files with 181 additions and 266 deletions

View File

@@ -21,20 +21,20 @@ fail() {
failures=$((failures + 1)) failures=$((failures + 1))
} }
alert_hits="$(rg -n "window\\.alert\\s*\\(" web/js modules/helpdesk/web/js -g '*.js' || true)" alert_hits="$(rg -n "window\\.alert\\s*\\(" web/js modules/*/web/js -g '*.js' || true)"
if [[ -n "${alert_hits}" ]]; then if [[ -n "${alert_hits}" ]]; then
fail "window.alert usage detected:" fail "window.alert usage detected:"
echo "${alert_hits}" >&2 echo "${alert_hits}" >&2
else else
ok "No window.alert usage in web/js and modules/helpdesk/web/js" ok "No window.alert usage in web/js and modules/*/web/js"
fi fi
fetch_hits="$(rg -n "\\bfetch\\s*\\(" modules/helpdesk/web/js -g '*.js' || true)" fetch_hits="$(rg -n "\\bfetch\\s*\\(" web/js modules/*/web/js -g '*.js' -g '!web/js/core/app-http.js' -g '!web/js/core/app-telemetry.js' || true)"
if [[ -n "${fetch_hits}" ]]; then if [[ -n "${fetch_hits}" ]]; then
fail "Direct fetch(...) usage detected in helpdesk JS:" fail "Direct fetch(...) usage detected outside approved HTTP infrastructure:"
echo "${fetch_hits}" >&2 echo "${fetch_hits}" >&2
else else
ok "Helpdesk JS uses centralized app-http (no direct fetch)" ok "Frontend JS uses centralized app-http (except app-http/app-telemetry infrastructure)"
fi fi
runtime_files=( runtime_files=(
@@ -83,14 +83,14 @@ while IFS= read -r line; do
continue continue
fi fi
echo "${file}: invalid import path -> ${import_path}" >&2 echo "${file}: invalid module import path -> ${import_path}" >&2
import_violations=$((import_violations + 1)) import_violations=$((import_violations + 1))
done < <(rg -n "^\\s*import\\s+(?:[^'\\\"]+\\s+from\\s+)?['\\\"][^'\\\"]+['\\\"]" modules/helpdesk/web/js -g '*.js') done < <(rg -n "^\\s*import\\s+(?:[^'\\\"]+\\s+from\\s+)?['\\\"][^'\\\"]+['\\\"]" modules/*/web/js -g '*.js')
if [[ "${import_violations}" -gt 0 ]]; then if [[ "${import_violations}" -gt 0 ]]; then
fail "Helpdesk import policy violations: ${import_violations}" fail "Module import policy violations: ${import_violations}"
else else
ok "Helpdesk import policy valid (core imports absolute /js/...; local imports relative)" ok "Module import policy valid (core imports absolute /js/...; local imports relative)"
fi fi
if [[ "${failures}" -gt 0 ]]; then if [[ "${failures}" -gt 0 ]]; then

View File

@@ -1,9 +1,9 @@
import { initMultiSelect } from '../../../../js/components/app-multiselect-init.js'; import { initMultiSelect } from '/js/components/app-multiselect-init.js';
import { initMultiSelectCascade } from '../../../../js/components/app-multiselect-cascade.js'; import { initMultiSelectCascade } from '/js/components/app-multiselect-cascade.js';
import { initStandardListPage } from '../../../../js/core/app-grid-factory.js'; import { initStandardListPage } from '/js/core/app-grid-factory.js';
import { readPageConfig } from '../../../../js/core/app-page-config.js'; import { readPageConfig } from '/js/core/app-page-config.js';
import { warnOnce } from '../../../../js/core/app-dom.js'; import { warnOnce } from '/js/core/app-dom.js';
import { getAppBase, escapeHtml, buildBadgeList, gridFilterMultiCsv, gridFilterText, withCurrentListReturn } from '../../../../js/pages/app-list-utils.js'; import { getAppBase, escapeHtml, buildBadgeList, gridFilterMultiCsv, gridFilterText, withCurrentListReturn } from '/js/pages/app-list-utils.js';
const config = readPageConfig('address-book-index'); const config = readPageConfig('address-book-index');
if (config) { if (config) {

View File

@@ -4,9 +4,10 @@
* - Reorder bookmarks inside groups (up/down) * - Reorder bookmarks inside groups (up/down)
* - Edit/Delete groups and bookmarks with confirm dialog * - Edit/Delete groups and bookmarks with confirm dialog
*/ */
import { showAsyncFlash } from '../../../../js/components/app-async-flash.js'; import { showAsyncFlash } from '/js/components/app-async-flash.js';
import { warnOnce, resolveHost } from '../../../../js/core/app-dom.js'; import { warnOnce, resolveHost } from '/js/core/app-dom.js';
import { confirmDialog } from '../../../../js/core/app-confirm-dialog.js'; import { confirmDialog } from '/js/core/app-confirm-dialog.js';
import { postForm } from '/js/core/app-http.js';
export function initBookmarkPanel(root = document, options = {}) { export function initBookmarkPanel(root = document, options = {}) {
const host = resolveHost(root); const host = resolveHost(root);
@@ -84,14 +85,6 @@ export function initBookmarkPanel(root = document, options = {}) {
}); });
}; };
const parseJsonSafe = async (response) => {
try {
return await response.json();
} catch {
return null;
}
};
const reportError = (code, message, details = {}) => { const reportError = (code, message, details = {}) => {
warnOnce(code, message, { ...moduleContext, ...details }); warnOnce(code, message, { ...moduleContext, ...details });
showAsyncFlash('error', message); showAsyncFlash('error', message);
@@ -176,16 +169,7 @@ export function initBookmarkPanel(root = document, options = {}) {
setPending(true); setPending(true);
try { try {
const response = await fetch(reorderUrl, { const json = await postForm(reorderUrl, body);
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body
});
const json = await parseJsonSafe(response);
if (!response.ok || !json) {
reportError('FETCH_FAILED', messageReorderFailed, { status: response.status, type });
return;
}
if (!json.ok) { if (!json.ok) {
reportError('FETCH_FAILED', messageReorderFailed, { error: json.error, type }); reportError('FETCH_FAILED', messageReorderFailed, { error: json.error, type });
return; return;
@@ -193,7 +177,7 @@ export function initBookmarkPanel(root = document, options = {}) {
runReload(); runReload();
} catch (error) { } catch (error) {
reportError('FETCH_ERROR', messageReorderFailed, { error, type }); reportError('FETCH_ERROR', messageReorderFailed, { error, status: error?.status, type });
} finally { } finally {
setPending(false); setPending(false);
} }
@@ -317,16 +301,7 @@ export function initBookmarkPanel(root = document, options = {}) {
setPending(true); setPending(true);
try { try {
const response = await fetch(groupDeleteUrl, { const json = await postForm(groupDeleteUrl, body);
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body
});
const json = await parseJsonSafe(response);
if (!response.ok || !json) {
reportError('FETCH_FAILED', messageGroupDeleteFailed, { status: response.status, groupId });
return;
}
if (!json.ok) { if (!json.ok) {
reportError('FETCH_FAILED', messageGroupDeleteFailed, { error: json.error, groupId }); reportError('FETCH_FAILED', messageGroupDeleteFailed, { error: json.error, groupId });
return; return;
@@ -334,7 +309,7 @@ export function initBookmarkPanel(root = document, options = {}) {
runReload(messageGroupDeleted); runReload(messageGroupDeleted);
} catch (error) { } catch (error) {
reportError('FETCH_ERROR', messageGroupDeleteFailed, { error, groupId }); reportError('FETCH_ERROR', messageGroupDeleteFailed, { error, status: error?.status, groupId });
} finally { } finally {
setPending(false); setPending(false);
} }
@@ -368,16 +343,7 @@ export function initBookmarkPanel(root = document, options = {}) {
setPending(true); setPending(true);
try { try {
const response = await fetch(bookmarkDeleteUrl, { const json = await postForm(bookmarkDeleteUrl, body);
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body
});
const json = await parseJsonSafe(response);
if (!response.ok || !json) {
reportError('FETCH_FAILED', messageBookmarkDeleteFailed, { status: response.status, bookmarkId });
return;
}
if (!json.ok) { if (!json.ok) {
reportError('FETCH_FAILED', messageBookmarkDeleteFailed, { error: json.error, bookmarkId }); reportError('FETCH_FAILED', messageBookmarkDeleteFailed, { error: json.error, bookmarkId });
return; return;
@@ -385,7 +351,7 @@ export function initBookmarkPanel(root = document, options = {}) {
runReload(messageBookmarkDeleted); runReload(messageBookmarkDeleted);
} catch (error) { } catch (error) {
reportError('FETCH_ERROR', messageBookmarkDeleteFailed, { error, bookmarkId }); reportError('FETCH_ERROR', messageBookmarkDeleteFailed, { error, status: error?.status, bookmarkId });
} finally { } finally {
setPending(false); setPending(false);
} }

View File

@@ -3,9 +3,10 @@
* Bookmark dialog (create/update) + group dialog (create/update). * Bookmark dialog (create/update) + group dialog (create/update).
*/ */
import { showAsyncFlash } from '../../../../js/components/app-async-flash.js'; import { showAsyncFlash } from '/js/components/app-async-flash.js';
import { warnOnce, resolveHost } from '../../../../js/core/app-dom.js'; import { warnOnce, resolveHost } from '/js/core/app-dom.js';
import { getAppBase } from '../../../../js/pages/app-list-utils.js'; import { postForm } from '/js/core/app-http.js';
import { getAppBase } from '/js/pages/app-list-utils.js';
export function initBookmarkSave(root = document, options = {}) { export function initBookmarkSave(root = document, options = {}) {
const host = resolveHost(root); const host = resolveHost(root);
@@ -133,14 +134,6 @@ export function initBookmarkSave(root = document, options = {}) {
showAsyncFlash('error', message); showAsyncFlash('error', message);
}; };
const parseJsonSafe = async (response) => {
try {
return await response.json();
} catch {
return null;
}
};
const resolveBookmarkApiErrorMessage = (errorCode) => { const resolveBookmarkApiErrorMessage = (errorCode) => {
if (!errorCode) return bookmarkMessageErrorGeneric; if (!errorCode) return bookmarkMessageErrorGeneric;
return bookmarkApiErrorMessages[errorCode] || bookmarkMessageErrorGeneric; return bookmarkApiErrorMessages[errorCode] || bookmarkMessageErrorGeneric;
@@ -348,16 +341,7 @@ export function initBookmarkSave(root = document, options = {}) {
if (editingBookmarkId) { if (editingBookmarkId) {
body.set('id', editingBookmarkId); body.set('id', editingBookmarkId);
try { try {
const response = await fetch(getAppBase() + 'bookmarks/update-data', { const json = await postForm(getAppBase() + 'bookmarks/update-data', body);
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body
});
const json = await parseJsonSafe(response);
if (!response.ok || !json) {
reportError('FETCH_FAILED', bookmarkMessageErrorGeneric, { status: response.status });
return;
}
if (!json.ok) { if (!json.ok) {
reportError('FETCH_FAILED', resolveBookmarkApiErrorMessage(json.error), { error: json.error }); reportError('FETCH_FAILED', resolveBookmarkApiErrorMessage(json.error), { error: json.error });
return; return;
@@ -366,7 +350,7 @@ export function initBookmarkSave(root = document, options = {}) {
closeBookmarkDialog(); closeBookmarkDialog();
runReloadWithSuccess(bookmarkMessageUpdated); runReloadWithSuccess(bookmarkMessageUpdated);
} catch (error) { } catch (error) {
reportError('FETCH_ERROR', bookmarkMessageErrorGeneric, { error }); reportError('FETCH_ERROR', bookmarkMessageErrorGeneric, { error, status: error?.status });
} finally { } finally {
setBookmarkSubmitPending(false); setBookmarkSubmitPending(false);
} }
@@ -375,16 +359,7 @@ export function initBookmarkSave(root = document, options = {}) {
body.set('url', currentRelativeUrl()); body.set('url', currentRelativeUrl());
try { try {
const response = await fetch(getAppBase() + 'bookmarks/save-data', { const json = await postForm(getAppBase() + 'bookmarks/save-data', body);
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body
});
const json = await parseJsonSafe(response);
if (!response.ok || !json) {
reportError('FETCH_FAILED', bookmarkMessageErrorGeneric, { status: response.status });
return;
}
if (!json.ok) { if (!json.ok) {
if (json.error === 'max_reached') { if (json.error === 'max_reached') {
showAsyncFlash('warning', maxBookmarkMessage || 'Maximum bookmarks reached'); showAsyncFlash('warning', maxBookmarkMessage || 'Maximum bookmarks reached');
@@ -397,7 +372,7 @@ export function initBookmarkSave(root = document, options = {}) {
closeBookmarkDialog(); closeBookmarkDialog();
runReloadWithSuccess(json.mode === 'updated' ? bookmarkMessageUpdated : bookmarkMessageSaved); runReloadWithSuccess(json.mode === 'updated' ? bookmarkMessageUpdated : bookmarkMessageSaved);
} catch (error) { } catch (error) {
reportError('FETCH_ERROR', bookmarkMessageErrorGeneric, { error }); reportError('FETCH_ERROR', bookmarkMessageErrorGeneric, { error, status: error?.status });
} finally { } finally {
setBookmarkSubmitPending(false); setBookmarkSubmitPending(false);
} }
@@ -659,16 +634,7 @@ export function initBookmarkSave(root = document, options = {}) {
setGroupSubmitPending(true); setGroupSubmitPending(true);
try { try {
const response = await fetch(getAppBase() + 'bookmarks/group-save-data', { const json = await postForm(getAppBase() + 'bookmarks/group-save-data', body);
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body
});
const json = await parseJsonSafe(response);
if (!response.ok || !json) {
reportError('FETCH_FAILED', groupMessageErrorGeneric, { status: response.status });
return;
}
if (!json.ok) { if (!json.ok) {
if (json.error === 'max_reached') { if (json.error === 'max_reached') {
showAsyncFlash('warning', maxGroupMessage); showAsyncFlash('warning', maxGroupMessage);
@@ -694,7 +660,7 @@ export function initBookmarkSave(root = document, options = {}) {
runReloadWithSuccess(successMessage); runReloadWithSuccess(successMessage);
} }
} catch (error) { } catch (error) {
reportError('FETCH_ERROR', groupMessageErrorGeneric, { error }); reportError('FETCH_ERROR', groupMessageErrorGeneric, { error, status: error?.status });
} finally { } finally {
setGroupSubmitPending(false); setGroupSubmitPending(false);
} }

View File

@@ -5,8 +5,9 @@
* notification list rendering, mark-read and dismiss actions. * notification list rendering, mark-read and dismiss actions.
*/ */
import { telemetry } from '../../../../js/core/app-telemetry.js'; import { telemetry } from '/js/core/app-telemetry.js';
import { getAppBase } from '../../../../js/pages/app-list-utils.js'; import { getJson, postForm } from '/js/core/app-http.js';
import { getAppBase } from '/js/pages/app-list-utils.js';
const POLL_INTERVAL_MS = 60_000; const POLL_INTERVAL_MS = 60_000;
const TYPE_ICONS = { const TYPE_ICONS = {
@@ -43,12 +44,6 @@ function escapeHtml(str) {
return d.innerHTML; return d.innerHTML;
} }
async function fetchJson(url, options = {}) {
const resp = await fetch(url, options);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
return resp.json();
}
export function initNotificationBell(root = document, config = {}) { export function initNotificationBell(root = document, config = {}) {
const details = root.querySelector('[data-notification-bell]'); const details = root.querySelector('[data-notification-bell]');
const dropdown = root.querySelector('[data-notification-dropdown]'); const dropdown = root.querySelector('[data-notification-dropdown]');
@@ -173,7 +168,7 @@ export function initNotificationBell(root = document, config = {}) {
showState('loading'); showState('loading');
list?.querySelectorAll('.app-notification-item').forEach(el => el.remove()); list?.querySelectorAll('.app-notification-item').forEach(el => el.remove());
try { try {
const data = await fetchJson(endpoint('notifications/list-data'), { signal }); const data = await getJson(endpoint('notifications/list-data'), { signal });
if (data.ok) { if (data.ok) {
renderNotifications(data.notifications || []); renderNotifications(data.notifications || []);
updateBadge(data.unread_count ?? 0); updateBadge(data.unread_count ?? 0);
@@ -192,7 +187,7 @@ export function initNotificationBell(root = document, config = {}) {
async function pollUnreadCount() { async function pollUnreadCount() {
try { try {
const data = await fetchJson(endpoint('notifications/unread-count-data'), { signal }); const data = await getJson(endpoint('notifications/unread-count-data'), { signal });
if (data.ok) { if (data.ok) {
updateBadge(data.unread_count ?? 0); updateBadge(data.unread_count ?? 0);
} }
@@ -212,11 +207,7 @@ export function initNotificationBell(root = document, config = {}) {
body.set('id', String(id)); body.set('id', String(id));
if (csrf.key) body.set(csrf.key, csrf.token); if (csrf.key) body.set(csrf.key, csrf.token);
const data = await fetchJson(endpoint('notifications/mark-read-data'), { const data = await postForm(endpoint('notifications/mark-read-data'), body, { signal });
method: 'POST',
body,
signal,
});
if (data.ok) { if (data.ok) {
updateBadge(data.unread_count ?? 0); updateBadge(data.unread_count ?? 0);
if (details.open) loadNotifications(); if (details.open) loadNotifications();
@@ -237,11 +228,7 @@ export function initNotificationBell(root = document, config = {}) {
body.set('all', '1'); body.set('all', '1');
if (csrf.key) body.set(csrf.key, csrf.token); if (csrf.key) body.set(csrf.key, csrf.token);
const data = await fetchJson(endpoint('notifications/mark-read-data'), { const data = await postForm(endpoint('notifications/mark-read-data'), body, { signal });
method: 'POST',
body,
signal,
});
if (data.ok) { if (data.ok) {
updateBadge(data.unread_count ?? 0); updateBadge(data.unread_count ?? 0);
if (details.open) loadNotifications(); if (details.open) loadNotifications();
@@ -262,11 +249,7 @@ export function initNotificationBell(root = document, config = {}) {
body.set('id', String(id)); body.set('id', String(id));
if (csrf.key) body.set(csrf.key, csrf.token); if (csrf.key) body.set(csrf.key, csrf.token);
const data = await fetchJson(endpoint('notifications/delete-data'), { const data = await postForm(endpoint('notifications/delete-data'), body, { signal });
method: 'POST',
body,
signal,
});
if (data.ok) { if (data.ok) {
updateBadge(data.unread_count ?? 0); updateBadge(data.unread_count ?? 0);
const el = list?.querySelector(`[data-notification-id="${id}"]`); const el = list?.querySelector(`[data-notification-id="${id}"]`);

View File

@@ -8,17 +8,17 @@ final class FrontendJsContractsTest extends TestCase
{ {
use ProjectFileAssertionSupport; use ProjectFileAssertionSupport;
public function testNoWindowAlertCallsInCoreAndHelpdeskJs(): void public function testNoWindowAlertCallsInFrontendJsScope(): void
{ {
$violations = array_merge( $violations = $this->findPatternMatchesInFiles('web/js', '/window\.alert\s*\(/', ['js']);
$this->findPatternMatchesInFiles('web/js', '/window\.alert\s*\(/', ['js']), foreach ($this->moduleJsDirectories() as $moduleJsDir) {
$this->findPatternMatchesInFiles('modules/helpdesk/web/js', '/window\.alert\s*\(/', ['js']) $violations = array_merge($violations, $this->findPatternMatchesInFiles($moduleJsDir, '/window\.alert\s*\(/', ['js']));
); }
$violations = array_values(array_unique($violations)); $violations = array_values(array_unique($violations));
sort($violations); sort($violations);
$this->assertSame([], $violations, "window.alert usage found in JS scope:\n" . implode("\n", $violations)); $this->assertSame([], $violations, "window.alert usage found in frontend JS scope:\n" . implode("\n", $violations));
} }
public function testHelpdeskRuntimeComponentsDoNotAutoInitialize(): void public function testHelpdeskRuntimeComponentsDoNotAutoInitialize(): void
@@ -39,53 +39,55 @@ final class FrontendJsContractsTest extends TestCase
} }
} }
public function testHelpdeskJsUsesCentralHttpLayer(): void public function testFrontendJsUsesCentralHttpLayer(): void
{ {
$violations = $this->findPatternMatchesInFiles('modules/helpdesk/web/js', '/\bfetch\s*\(/', ['js']); $violations = $this->findDirectFetchCallsInFrontendScope();
$this->assertSame([], $violations, "Direct fetch(...) found in helpdesk JS:\n" . implode("\n", $violations)); $this->assertSame([], $violations, "Direct fetch(...) found outside approved HTTP infrastructure:\n" . implode("\n", $violations));
} }
public function testHelpdeskImportPolicyForCoreAndSiblingModules(): void public function testModuleImportPolicyForCoreAndSiblingModules(): void
{ {
$root = $this->projectRootPath(); $root = $this->projectRootPath();
$base = $root . '/modules/helpdesk/web/js';
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS));
$violations = []; $violations = [];
/** @var \SplFileInfo $file */ foreach ($this->moduleJsDirectories() as $moduleJsDir) {
foreach ($iterator as $file) { $base = $root . '/' . $moduleJsDir;
if (!$file->isFile() || $file->getExtension() !== 'js') { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS));
continue;
}
$content = file_get_contents($file->getPathname()); /** @var \SplFileInfo $file */
$this->assertNotFalse($content, 'Could not read file: ' . $file->getPathname()); foreach ($iterator as $file) {
$relativePath = str_replace($root . '/', '', $file->getPathname()); if (!$file->isFile() || $file->getExtension() !== 'js') {
preg_match_all('/^\s*import\s+(?:[^\"\']+\s+from\s+)?[\"\']([^\"\']+)[\"\']/m', $content, $matches);
foreach ($matches[1] as $importPathRaw) {
$importPath = (string) $importPathRaw;
if (str_starts_with($importPath, '/js/')) {
continue; continue;
} }
if (str_starts_with($importPath, './') || str_starts_with($importPath, '../')) { $content = file_get_contents($file->getPathname());
if (preg_match('#(?:^|/)js/(core|components|pages)/#', $importPath) === 1) { $this->assertNotFalse($content, 'Could not read file: ' . $file->getPathname());
$violations[] = $relativePath . ' => relative core import: ' . $importPath; $relativePath = str_replace($root . '/', '', $file->getPathname());
preg_match_all('/^\s*import\s+(?:[^\"\']+\s+from\s+)?[\"\']([^\"\']+)[\"\']/m', $content, $matches);
foreach ($matches[1] as $importPathRaw) {
$importPath = (string) $importPathRaw;
if (str_starts_with($importPath, '/js/')) {
continue;
} }
continue;
}
$violations[] = $relativePath . ' => invalid import path: ' . $importPath; if (str_starts_with($importPath, './') || str_starts_with($importPath, '../')) {
if (preg_match('#(?:^|/)js/(core|components|pages)/#', $importPath) === 1) {
$violations[] = $relativePath . ' => relative core import: ' . $importPath;
}
continue;
}
$violations[] = $relativePath . ' => invalid import path: ' . $importPath;
}
} }
} }
$violations = array_values(array_unique($violations)); $violations = array_values(array_unique($violations));
sort($violations); sort($violations);
$this->assertSame([], $violations, "Helpdesk import policy violations:\n" . implode("\n", $violations)); $this->assertSame([], $violations, "Module import policy violations:\n" . implode("\n", $violations));
} }
public function testLookupFieldComponentExportsRuntimeInitializerWithoutAutoInit(): void public function testLookupFieldComponentExportsRuntimeInitializerWithoutAutoInit(): void
@@ -113,4 +115,70 @@ final class FrontendJsContractsTest extends TestCase
'modules/helpdesk/web/js/handover-schema-editor.js', 'modules/helpdesk/web/js/handover-schema-editor.js',
]; ];
} }
/**
* @return list<string>
*/
private function moduleJsDirectories(): array
{
$root = $this->projectRootPath();
$modulesRoot = $root . '/modules';
$this->assertDirectoryExists($modulesRoot, 'Modules root not found.');
$dirs = [];
$entries = scandir($modulesRoot);
$this->assertNotFalse($entries, 'Could not read modules directory.');
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
$jsPath = $modulesRoot . '/' . $entry . '/web/js';
if (is_dir($jsPath)) {
$dirs[] = 'modules/' . $entry . '/web/js';
}
}
sort($dirs);
return $dirs;
}
/**
* @return list<string>
*/
private function findDirectFetchCallsInFrontendScope(): array
{
$root = $this->projectRootPath();
$allowed = [
'web/js/core/app-http.js',
'web/js/core/app-telemetry.js',
];
$scanRoots = array_merge(['web/js'], $this->moduleJsDirectories());
$violations = [];
foreach ($scanRoots as $scanRoot) {
$base = $root . '/' . $scanRoot;
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS));
/** @var \SplFileInfo $file */
foreach ($iterator as $file) {
if (!$file->isFile() || $file->getExtension() !== 'js') {
continue;
}
$relativePath = str_replace($root . '/', '', $file->getPathname());
if (in_array($relativePath, $allowed, true)) {
continue;
}
$content = file_get_contents($file->getPathname());
$this->assertNotFalse($content, 'Could not read file: ' . $file->getPathname());
if (preg_match('/\bfetch\s*\(/', $content) === 1) {
$violations[] = $relativePath;
}
}
}
$violations = array_values(array_unique($violations));
sort($violations);
return $violations;
}
} }

View File

@@ -3,6 +3,7 @@
* Supports slide-out animation and hover-pause. * Supports slide-out animation and hover-pause.
*/ */
import { resolveHost } from '../core/app-dom.js'; import { resolveHost } from '../core/app-dom.js';
import { postForm as postFormRequest } from '../core/app-http.js';
export function initFlashAutoDismiss(root = document, options = {}) { export function initFlashAutoDismiss(root = document, options = {}) {
const { const {
@@ -32,17 +33,14 @@ export function initFlashAutoDismiss(root = document, options = {}) {
const postForm = async (form) => { const postForm = async (form) => {
const action = form.getAttribute('action'); const action = form.getAttribute('action');
if (!action) { if (!action) {
return null; return false;
}
try {
await postFormRequest(action, new FormData(form));
return true;
} catch {
return false;
} }
const body = new URLSearchParams(new FormData(form));
return fetch(action, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'fetch',
},
body,
});
}; };
notices.forEach((notice) => { notices.forEach((notice) => {
@@ -62,8 +60,8 @@ export function initFlashAutoDismiss(root = document, options = {}) {
} }
const form = notice.querySelector('form'); const form = notice.querySelector('form');
if (form) { if (form) {
const response = await postForm(form); const ok = await postForm(form);
if (!response || !response.ok) { if (!ok) {
return; return;
} }
} }
@@ -80,8 +78,8 @@ export function initFlashAutoDismiss(root = document, options = {}) {
if (destroyed) return; if (destroyed) return;
const form = notice.querySelector('form'); const form = notice.querySelector('form');
if (form) { if (form) {
const response = await postForm(form); const ok = await postForm(form);
if (!response || !response.ok) return; if (!ok) return;
} }
dismissNotice(notice); dismissNotice(notice);
}, 1000); }, 1000);

View File

@@ -5,6 +5,7 @@
* preview API and renders them grouped by category with keyboard navigation. * preview API and renders them grouped by category with keyboard navigation.
*/ */
import { warnOnce, resolveHost } from '../core/app-dom.js'; import { warnOnce, resolveHost } from '../core/app-dom.js';
import { getJson } from '../core/app-http.js';
import { isEditableTarget } from '../core/app-form-utils.js'; import { isEditableTarget } from '../core/app-form-utils.js';
const ICON_MAP = { const ICON_MAP = {
@@ -221,13 +222,7 @@ export function initGlobalSearch(root = document, options = {}) {
url.searchParams.set('q', value); url.searchParams.set('q', value);
try { try {
const response = await fetch(url.toString(), { headers: { 'Accept': 'application/json' }, signal }); const data = await getJson(url.toString(), { signal });
if (!response.ok) {
warnOnce('FETCH_FAILED', `Global search failed: ${response.status} ${response.statusText}`, { module: 'global-search' });
setState('error');
return;
}
const data = await response.json();
if (Array.isArray(data)) { if (Array.isArray(data)) {
render(data, value); render(data, value);
} else { } else {
@@ -236,7 +231,7 @@ export function initGlobalSearch(root = document, options = {}) {
} }
} catch (err) { } catch (err) {
if (err.name === 'AbortError') {return;} if (err.name === 'AbortError') {return;}
warnOnce('FETCH_ERROR', 'Global search fetch error', { module: 'global-search', err }); warnOnce('FETCH_ERROR', 'Global search fetch error', { module: 'global-search', err, status: err?.status });
setState('error'); setState('error');
} }
}; };

View File

@@ -2,6 +2,7 @@
* Editor.js integration — lifecycle-managed page editor module. * Editor.js integration — lifecycle-managed page editor module.
*/ */
import EditorJS from '../../vendor/editorjs/editorjs.mjs'; import EditorJS from '../../vendor/editorjs/editorjs.mjs';
import { postForm } from '../core/app-http.js';
import { warnOnce, resolveHost } from '../core/app-dom.js'; import { warnOnce, resolveHost } from '../core/app-dom.js';
const parseData = (value) => { const parseData = (value) => {
@@ -194,21 +195,8 @@ export function initPageEditor(root = document, config = {}) {
form.dataset.submitting = '1'; form.dataset.submitting = '1';
try { try {
const formData = new FormData(form); const data = await postForm(form.action || window.location.pathname, new FormData(form));
const response = await fetch(form.action || window.location.pathname, { if (data && typeof data === 'object' && typeof data.redirect === 'string' && data.redirect.trim() !== '') {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
Accept: 'application/json',
},
body: formData,
});
if (response.redirected) {
window.location.href = response.url;
return;
}
const data = await response.json().catch(() => null);
if (data && data.redirect) {
window.location.href = data.redirect; window.location.href = data.redirect;
return; return;
} }

View File

@@ -2,6 +2,7 @@
* Session expiry warning dialog. * Session expiry warning dialog.
*/ */
import { warnOnce, resolveHost } from '../core/app-dom.js'; import { warnOnce, resolveHost } from '../core/app-dom.js';
import { postForm } from '../core/app-http.js';
const WARNING_LEAD_SECONDS = 120; const WARNING_LEAD_SECONDS = 120;
const TICK_INTERVAL_MS = 1000; const TICK_INTERVAL_MS = 1000;
@@ -211,24 +212,9 @@ export function initSessionWarning(root = document, runtimeConfig = {}) {
extendButton.disabled = true; extendButton.disabled = true;
try { try {
const body = new URLSearchParams({ const data = await postForm(config.pingUrl, {
[config.csrfKey]: config.csrfToken, [config.csrfKey]: config.csrfToken,
}); });
const response = await fetch(config.pingUrl, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
body,
});
if (!response.ok) {
window.location.reload();
return;
}
const data = await response.json();
if (typeof data.idle_timeout_seconds === 'number' && data.idle_timeout_seconds > 0) { if (typeof data.idle_timeout_seconds === 'number' && data.idle_timeout_seconds > 0) {
config.idleSeconds = data.idle_timeout_seconds; config.idleSeconds = data.idle_timeout_seconds;
} }
@@ -267,23 +253,9 @@ export function initSessionWarning(root = document, runtimeConfig = {}) {
hasInteractionSinceLastSync = false; hasInteractionSinceLastSync = false;
try { try {
const body = new URLSearchParams({ const data = await postForm(config.pingUrl, {
[config.csrfKey]: config.csrfToken, [config.csrfKey]: config.csrfToken,
}); });
const response = await fetch(config.pingUrl, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
body,
});
if (!response.ok) {
return;
}
const data = await response.json();
if (typeof data.idle_timeout_seconds === 'number' && data.idle_timeout_seconds > 0) { if (typeof data.idle_timeout_seconds === 'number' && data.idle_timeout_seconds > 0) {
config.idleSeconds = data.idle_timeout_seconds; config.idleSeconds = data.idle_timeout_seconds;
} }

View File

@@ -3,6 +3,7 @@
*/ */
import { showAsyncFlash } from './app-async-flash.js'; import { showAsyncFlash } from './app-async-flash.js';
import { warnOnce, resolveHost } from '../core/app-dom.js'; import { warnOnce, resolveHost } from '../core/app-dom.js';
import { postForm } from '../core/app-http.js';
const SWITCHER_ROOT_SELECTOR = '[data-tenant-switcher]'; const SWITCHER_ROOT_SELECTOR = '[data-tenant-switcher]';
const TENANT_LINK_SELECTOR = '[data-switch-tenant]'; const TENANT_LINK_SELECTOR = '[data-switch-tenant]';
@@ -32,40 +33,22 @@ const switchTenant = async (link) => {
setPending(link, true); setPending(link, true);
try { try {
const body = new URLSearchParams({ const data = await postForm('admin/users/switch-tenant', {
tenant_id: tenantId, tenant_id: tenantId,
[csrfKey]: csrfToken [csrfKey]: csrfToken
}); });
if (data && data.ok) {
const response = await fetch('admin/users/switch-tenant', { if (data.theme) {
method: 'POST', document.documentElement.dataset.theme = data.theme;
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'X-Requested-With': 'fetch'
},
body
});
if (response.ok) {
const data = await response.json();
if (data.ok) {
if (data.theme) {
document.documentElement.dataset.theme = data.theme;
}
window.location.reload();
} else {
warnOnce('FETCH_FAILED', 'Tenant switch failed', { module: 'tenant-switcher', error: data.error });
showAsyncFlash('error', errorMessage);
setPending(link, false);
} }
window.location.reload();
} else { } else {
warnOnce('FETCH_FAILED', `Tenant switch server error: ${response.status}`, { module: 'tenant-switcher' }); warnOnce('FETCH_FAILED', 'Tenant switch failed', { module: 'tenant-switcher', error: data?.error ?? '' });
showAsyncFlash('error', errorMessage); showAsyncFlash('error', errorMessage);
setPending(link, false); setPending(link, false);
} }
} catch (error) { } catch (error) {
warnOnce('FETCH_ERROR', 'Tenant switch network error', { module: 'tenant-switcher', error }); warnOnce('FETCH_ERROR', 'Tenant switch request failed', { module: 'tenant-switcher', error, status: error?.status });
showAsyncFlash('error', errorMessage); showAsyncFlash('error', errorMessage);
setPending(link, false); setPending(link, false);
} }

View File

@@ -2,6 +2,7 @@
* Theme switcher — light/dark toggle and menu with server-side persistence. * Theme switcher — light/dark toggle and menu with server-side persistence.
*/ */
import { warnOnce, resolveHost } from '../core/app-dom.js'; import { warnOnce, resolveHost } from '../core/app-dom.js';
import { postForm } from '../core/app-http.js';
const setTheme = (theme) => { const setTheme = (theme) => {
document.documentElement.dataset.theme = theme; document.documentElement.dataset.theme = theme;
@@ -24,17 +25,12 @@ const updateTheme = async (source, theme) => {
if (!url || !csrfKey || !csrfToken) { if (!url || !csrfKey || !csrfToken) {
return true; return true;
} }
const body = new URLSearchParams({ theme, [csrfKey]: csrfToken }); try {
const response = await fetch(url, { await postForm(url, { theme, [csrfKey]: csrfToken });
method: 'POST', return true;
headers: { } catch {
'Content-Type': 'application/x-www-form-urlencoded', return false;
'Accept': 'application/json', }
'X-Requested-With': 'fetch',
},
body,
});
return response.ok;
}; };
export function initThemeControls(root = document, options = {}) { export function initThemeControls(root = document, options = {}) {