import { useCallback, useMemo, useRef, useState } from "react"; import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from "react-router"; import { Link, useLoaderData } from "react-router"; import { useTranslation } from "react-i18next"; import { createSlidingWindowRateLimiter } from "@toolctrl/shared-store"; import { getTranslations } from "~/locale/i18next.server"; import { PluginSettingsFrame } from "~/modules/plugins/components/PluginSettingsFrame"; import { loadPluginSettingsPageData, PluginSettingsServiceError, reportPluginSettingsFrameViolation, setPluginUserSetting, type PluginSettingsFrameViolationReason, type PluginSettingValue, type PluginUserSettings, } from "~/modules/plugins/services/.server/PluginSettingsService"; import { isPluginSettingKeyFormatSafe, isPluginSettingKeyReserved, isPluginSettingKeySecretLike, isPluginSettingValueShapeSafe, isPluginSettingValueWithinSize, } from "~/modules/plugins/utils/pluginSettingsValidation"; import { getSharedStore } from "~/shared-store.server"; import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders"; import { appPath } from "~/utils/app/CanonicalUrlUtils"; import { useRootData } from "~/utils/data/useRootData"; import { getUser } from "~/utils/db/users.db.server"; import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import { getUserInfo, validateCSRFToken } from "~/utils/session.server"; type LoaderData = { title: string; tenantSlug: string; plugin: { id: string; pluginId: string; version: string; }; trustedHtml: string; settings: PluginUserSettings; }; const SETTINGS_WRITE_RATE_LIMIT_PREFIX = "plugin-settings-write-route:rl"; const SETTINGS_FRAME_VIOLATION_RATE_LIMIT_PREFIX = "plugin-settings-frame-violation-route:rl"; const PLUGIN_SETTINGS_ROUTE_MAX_BODY_BYTES = 80 * 1024; const PLUGIN_SETTINGS_FRAME_VIOLATION_REPORT_INTERVAL_MS = 60_000; const PLUGIN_SETTINGS_FRAME_VIOLATION_REASONS = new Set([ "wrong_origin", "wrong_source", "invalid_payload", "unexpected_navigation", ]); const PLUGIN_SETTINGS_ROUTE_CSP = [ "default-src 'self'", "script-src 'self'", "connect-src 'self'", "img-src 'self' data: blob:", "font-src 'self' data:", "style-src 'self' 'unsafe-inline'", "frame-src 'self'", "child-src 'self'", "worker-src 'none'", "media-src 'none'", "manifest-src 'none'", "frame-ancestors 'self'", "base-uri 'self'", "object-src 'none'", "form-action 'self'", "navigate-to 'self'", ].join("; "); const PLUGIN_SETTINGS_ROUTE_PERMISSION_POLICY = [ "accelerometer=()", "ambient-light-sensor=()", "autoplay=()", "bluetooth=()", "camera=()", "clipboard-read=()", "clipboard-write=()", "display-capture=()", "encrypted-media=()", "fullscreen=()", "gamepad=()", "geolocation=()", "gyroscope=()", "hid=()", "identity-credentials-get=()", "idle-detection=()", "local-fonts=()", "magnetometer=()", "microphone=()", "midi=()", "otp-credentials=()", "payment=()", "picture-in-picture=()", "publickey-credentials-get=()", "screen-wake-lock=()", "serial=()", "speaker-selection=()", "storage-access=()", "usb=()", "web-share=()", "xr-spatial-tracking=()", ].join(", "); export const headers: HeadersFunction = (args) => { const responseHeaders = new Headers(serverTimingHeaders(args)); responseHeaders.set("Content-Security-Policy", PLUGIN_SETTINGS_ROUTE_CSP); responseHeaders.set("Permissions-Policy", PLUGIN_SETTINGS_ROUTE_PERMISSION_POLICY); responseHeaders.set("X-Frame-Options", "SAMEORIGIN"); return responseHeaders; }; function shouldFailClosedOnRateLimitInfraFailure(): boolean { return process.env.NODE_ENV === "production"; } type JsonObjectResult = { ok: true; value: Record } | { ok: false }; type SettingsWritePayloadError = "settings_key_invalid" | "settings_key_secret_like" | "settings_value_invalid" | "settings_value_too_large"; function hasJsonContentType(request: Request): boolean { const contentType = request.headers.get("content-type")?.toLowerCase() ?? ""; return contentType.split(";", 1)[0]?.trim() === "application/json"; } async function readJsonObject(request: Request): Promise { const contentLength = Number(request.headers.get("content-length") ?? "0"); if (Number.isFinite(contentLength) && contentLength > PLUGIN_SETTINGS_ROUTE_MAX_BODY_BYTES) { return { ok: false }; } try { const text = await readLimitedRequestText(request, PLUGIN_SETTINGS_ROUTE_MAX_BODY_BYTES); if (text === null) return { ok: false }; const value = JSON.parse(text) as unknown; if (!value || typeof value !== "object" || Array.isArray(value)) { return { ok: false }; } return { ok: true, value: value as Record }; } catch { return { ok: false }; } } async function readLimitedRequestText(request: Request, maxBytes: number): Promise { if (!request.body) return null; const reader = request.body.getReader(); const decoder = new TextDecoder(); let bytes = 0; let text = ""; try { while (true) { const { done, value } = await reader.read(); if (done) break; bytes += value.byteLength; if (bytes > maxBytes) { await reader.cancel(); return null; } text += decoder.decode(value, { stream: true }); } text += decoder.decode(); return text; } finally { reader.releaseLock(); } } function resolveSettingsWriteRateLimitPerMin(): number { const raw = process.env.PLUGIN_SETTINGS_WRITE_RATE_LIMIT_PER_MIN; if (typeof raw !== "string" || raw.length === 0) return 60; const parsed = Number.parseInt(raw, 10); if (!Number.isFinite(parsed) || parsed <= 0) return 60; return parsed; } function resolveFrameViolationRateLimitPerMin(): number { const raw = process.env.PLUGIN_SETTINGS_FRAME_VIOLATION_RATE_LIMIT_PER_MIN; if (typeof raw !== "string" || raw.length === 0) return 120; const parsed = Number.parseInt(raw, 10); if (!Number.isFinite(parsed) || parsed <= 0) return 120; return parsed; } function getPluginSettingsLoaderErrorStatus(code: PluginSettingsServiceError["code"]): number { if (code === "settings_ui_file_too_large") return 413; if (code === "settings_ui_entry_unsafe") return 400; return 404; } function getSettingsWritePayloadError(key: string, value: unknown): SettingsWritePayloadError | null { if (!isPluginSettingKeyFormatSafe(key) || isPluginSettingKeyReserved(key)) { return "settings_key_invalid"; } if (isPluginSettingKeySecretLike(key)) { return "settings_key_secret_like"; } if (!isPluginSettingValueShapeSafe(value)) { return "settings_value_invalid"; } return isPluginSettingValueWithinSize(value) ? null : "settings_value_too_large"; } function isPluginSettingsFrameViolationReason(reason: unknown): reason is PluginSettingsFrameViolationReason { return typeof reason === "string" && PLUGIN_SETTINGS_FRAME_VIOLATION_REASONS.has(reason as PluginSettingsFrameViolationReason); } // The settings iframe writes hit this UI route's action through React Router's // single-fetch endpoint (`.data`), so the action's `Response.json(...)` // comes back turbo-stream encoded (`text/x-script`) rather than as raw JSON. // Decode that envelope (`{ data: }`) here; keep the plain-JSON // branch for any caller that still receives a raw JSON response. function pluginSettingsActionUrl(): string { // The component is rendered at the plugin-settings DETAIL route, so the current // pathname IS that route. A bare `fetch(".")` would resolve to the parent // plugins-list route (its action does not handle setSetting), so target the // detail route's single-fetch endpoint explicitly. return `${window.location.pathname.replace(/\/$/u, "")}.data`; } export const loader = async ({ request, params }: LoaderFunctionArgs) => { const tenantId = await getTenantIdFromUrl(params); await verifyUserHasPermission(request, "app.plugins.use", tenantId); const [{ t }, userInfo] = await Promise.all([getTranslations(request), getUserInfo(request)]); if (!userInfo.userId) { throw new Response(t("settings.plugins.settings.errors.unauthorized"), { status: 401 }); } const pluginRowId = params.id ?? ""; if (pluginRowId.length === 0) { throw new Response(t("settings.plugins.errors.notFound"), { status: 404 }); } try { const settingsPage = await loadPluginSettingsPageData({ tenantId, pluginRowId, userId: userInfo.userId }); const data: LoaderData = { title: `${t("settings.plugins.settings.title")} ยท ${settingsPage.plugin.pluginId}`, tenantSlug: params.tenant ?? "", plugin: { id: settingsPage.plugin.id, pluginId: settingsPage.plugin.pluginId, version: settingsPage.plugin.version, }, trustedHtml: settingsPage.trustedHtml, settings: settingsPage.settings, }; return Response.json(data); } catch (error) { if (error instanceof PluginSettingsServiceError) { throw new Response(t(`settings.plugins.settings.errors.${error.code}`), { status: getPluginSettingsLoaderErrorStatus(error.code) }); } throw error; } }; export const action = async ({ request, params }: ActionFunctionArgs) => { const tenantId = await getTenantIdFromUrl(params); await verifyUserHasPermission(request, "app.plugins.use", tenantId); const { t } = await getTranslations(request); const userInfo = await getUserInfo(request); if (!userInfo.userId) { return Response.json({ error: "unauthorized", message: t("settings.plugins.settings.errors.unauthorized") }, { status: 401 }); } const pluginRowId = params.id ?? ""; if (pluginRowId.length === 0) { return Response.json({ error: "plugin_not_found", message: t("settings.plugins.errors.notFound") }, { status: 404 }); } if (!hasJsonContentType(request)) { return Response.json({ error: "unsupported_media_type", message: t("settings.plugins.settings.errors.unsupported_media_type") }, { status: 415 }); } await validateCSRFToken(request, { headerOnly: true }); const parsed = await readJsonObject(request); if (!parsed.ok) { return Response.json({ error: "invalid_json", message: t("settings.plugins.settings.errors.invalid_json") }, { status: 400 }); } const body = parsed.value as { op?: unknown; key?: unknown; value?: unknown; reason?: unknown }; if (body.op === "reportFrameViolation") { if (!isPluginSettingsFrameViolationReason(body.reason)) { return Response.json({ error: "invalid_frame_violation_reason", message: t("settings.plugins.settings.errors.invalid_frame_violation_reason") }, { status: 400 }); } try { const perMin = resolveFrameViolationRateLimitPerMin(); const limiter = createSlidingWindowRateLimiter({ store: getSharedStore(), max: perMin, windowSeconds: 60, prefix: SETTINGS_FRAME_VIOLATION_RATE_LIMIT_PREFIX, }); const decision = await limiter.consume(`tenant:${tenantId}:user:${userInfo.userId}:plugin:${pluginRowId}:reason:${body.reason}`); if (!decision.allowed) { return Response.json( { error: "rate_limited", message: t("settings.plugins.settings.errors.rate_limited", { perMin }) }, { status: 429, headers: { "Retry-After": "60" } } ); } } catch (error) { if (shouldFailClosedOnRateLimitInfraFailure()) { return Response.json( { error: "rate_limit_unavailable", message: t("settings.plugins.settings.errors.rate_limit_unavailable") }, { status: 503, headers: { "Retry-After": "60" } } ); } // eslint-disable-next-line no-console console.warn("[plugin-settings] frame-violation rate-limit infra failure; allowing audit report:", error instanceof Error ? error.message : String(error)); } try { const user = await getUser(userInfo.userId); await reportPluginSettingsFrameViolation({ tenantId, pluginRowId, reason: body.reason, actor: { userId: userInfo.userId, email: user?.email ?? null, ip: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip") ?? null, }, }); return Response.json({ ok: true }); } catch (error) { if (error instanceof PluginSettingsServiceError) { const status = error.code === "plugin_not_found" ? 404 : 400; return Response.json({ error: error.code, message: t(`settings.plugins.settings.errors.${error.code}`) }, { status }); } throw error; } } if (body.op !== "setSetting" || typeof body.key !== "string") { return Response.json({ error: "missing_fields", message: t("settings.plugins.settings.errors.missing_fields") }, { status: 400 }); } const payloadError = getSettingsWritePayloadError(body.key, body.value); if (payloadError) { return Response.json({ error: payloadError, message: t(`settings.plugins.settings.errors.${payloadError}`) }, { status: 400 }); } try { const perMin = resolveSettingsWriteRateLimitPerMin(); const limiter = createSlidingWindowRateLimiter({ store: getSharedStore(), max: perMin, windowSeconds: 60, prefix: SETTINGS_WRITE_RATE_LIMIT_PREFIX, }); const decision = await limiter.consume(`tenant:${tenantId}:user:${userInfo.userId}:plugin:${pluginRowId}`); if (!decision.allowed) { return Response.json( { error: "rate_limited", message: t("settings.plugins.settings.errors.rate_limited", { perMin }) }, { status: 429, headers: { "Retry-After": "60" } } ); } } catch (error) { if (shouldFailClosedOnRateLimitInfraFailure()) { return Response.json( { error: "rate_limit_unavailable", message: t("settings.plugins.settings.errors.rate_limit_unavailable") }, { status: 503, headers: { "Retry-After": "60" } } ); } // Failing open keeps legitimate plugin settings usable outside // production during a transient shared-store outage; the service still // enforces key and value safety before any write reaches the database. // eslint-disable-next-line no-console console.warn("[plugin-settings] rate-limit infra failure; allowing settings write:", error instanceof Error ? error.message : String(error)); } try { const user = await getUser(userInfo.userId); const result = await setPluginUserSetting({ tenantId, pluginRowId, userId: userInfo.userId, key: body.key, value: body.value as PluginSettingValue, actor: { userId: userInfo.userId, email: user?.email ?? null, ip: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip") ?? null, }, }); return Response.json({ ok: true, key: result.key, value: result.value, settings: result.settings }); } catch (error) { if (error instanceof PluginSettingsServiceError) { const status = error.code === "plugin_not_found" ? 404 : 400; return Response.json({ error: error.code, message: t(`settings.plugins.settings.errors.${error.code}`) }, { status }); } throw error; } }; export default function TenantPluginSettingsRoute() { const data = useLoaderData(); const { csrf } = useRootData(); const { t } = useTranslation(); const [settings, setSettings] = useState(data.settings); const frameViolationReportedAtRef = useRef(new Map()); const frameErrorMessages = useMemo( () => ({ invalid_payload: t("settings.plugins.settings.frameErrors.invalid_payload"), settings_unavailable: t("settings.plugins.settings.frameErrors.settings_unavailable"), settings_update_failed: t("settings.plugins.settings.frameErrors.settings_update_failed"), }), [t] ); const getSetting = useCallback((key: string) => settings[key], [settings]); const setSetting = useCallback( async (key: string, value: PluginSettingValue) => { const fallbackMessage = t("settings.plugins.settings.frameErrors.settings_update_failed"); const response = await fetch(pluginSettingsActionUrl(), { method: "POST", headers: { "content-type": "application/json", ...(csrf ? { "x-csrf-token": csrf } : {}), }, body: JSON.stringify({ op: "setSetting", key, value, csrf }), }); // The write reaches this UI route's action through React Router's // single-fetch endpoint, so the response body is turbo-stream encoded // rather than the action's raw JSON. The HTTP status is authoritative // (2xx = persisted, 4xx = rejected with a localized reason), so gate on it // instead of parsing the body, and reflect the written value locally to // keep the settings frame state in sync without a reload. if (!response.ok) { throw new Error(fallbackMessage); } setSettings((current) => ({ ...current, [key]: value ?? null })); }, [csrf] ); const reportFrameViolation = useCallback( (reason: PluginSettingsFrameViolationReason) => { const now = Date.now(); const lastReportedAt = frameViolationReportedAtRef.current.get(reason) ?? 0; if (now - lastReportedAt < PLUGIN_SETTINGS_FRAME_VIOLATION_REPORT_INTERVAL_MS) { return; } frameViolationReportedAtRef.current.set(reason, now); void Promise.resolve( fetch(pluginSettingsActionUrl(), { method: "POST", headers: { "content-type": "application/json", ...(csrf ? { "x-csrf-token": csrf } : {}), }, body: JSON.stringify({ op: "reportFrameViolation", reason, csrf }), }) ).catch(() => undefined); }, [csrf] ); return (

{t("settings.plugins.audit.backToPlugins")}

{t("settings.plugins.settings.heading", { pluginId: data.plugin.pluginId })}

{t("settings.plugins.settings.description")}

); }