From 269f0b243bbce69a9ed9644f2279e5314aad0008 Mon Sep 17 00:00:00 2001 From: svemagie <869694+svemagie@users.noreply.github.com> Date: Sun, 8 Mar 2026 05:32:47 +0100 Subject: [PATCH] Integrate Cloudron security patch patterns into runtime patch pipeline --- README.md | 6 +- package.json | 4 +- scripts/patch-indieauth-devmode-guard.mjs | 14 +- .../patch-indiekit-error-production-stack.mjs | 84 ++++++++ scripts/patch-indiekit-routes-rate-limits.mjs | 184 ++++++++++++++++++ start.example.sh | 2 + 6 files changed, 289 insertions(+), 5 deletions(-) create mode 100644 scripts/patch-indiekit-error-production-stack.mjs create mode 100644 scripts/patch-indiekit-routes-rate-limits.mjs diff --git a/README.md b/README.md index b02675e1..962b8cc4 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ - `start.sh` is intentionally ignored by Git (`.gitignore`) so server secrets are not committed. - Use `start.example.sh` as the tracked template and keep real credentials in environment variables (or `.env` on the server). - Startup scripts parse `.env` with the `dotenv` parser (not shell `source`), so values containing spaces are handled safely. -- Startup scripts run preflight + patch helpers before boot (`scripts/preflight-production-security.mjs`, `scripts/preflight-mongo-connection.mjs`, `scripts/patch-lightningcss.mjs`, `scripts/patch-endpoint-media-scope.mjs`, `scripts/patch-endpoint-media-sharp-runtime.mjs`, `scripts/patch-frontend-sharp-runtime.mjs`, `scripts/patch-endpoint-files-upload-route.mjs`, `scripts/patch-endpoint-files-upload-locales.mjs`, `scripts/patch-frontend-serviceworker-file.mjs`, `scripts/patch-conversations-collection-guards.mjs`, `scripts/patch-indieauth-devmode-guard.mjs`). +- Startup scripts run preflight + patch helpers before boot (`scripts/preflight-production-security.mjs`, `scripts/preflight-mongo-connection.mjs`, `scripts/patch-lightningcss.mjs`, `scripts/patch-endpoint-media-scope.mjs`, `scripts/patch-endpoint-media-sharp-runtime.mjs`, `scripts/patch-frontend-sharp-runtime.mjs`, `scripts/patch-endpoint-files-upload-route.mjs`, `scripts/patch-endpoint-files-upload-locales.mjs`, `scripts/patch-frontend-serviceworker-file.mjs`, `scripts/patch-conversations-collection-guards.mjs`, `scripts/patch-indiekit-routes-rate-limits.mjs`, `scripts/patch-indiekit-error-production-stack.mjs`, `scripts/patch-indieauth-devmode-guard.mjs`). - The production security preflight blocks startup on insecure auth/session configuration and catches empty-password bcrypt hashes. - One-time recovery mode is available with `INDIEKIT_ALLOW_PASSWORD_SETUP=1` to bootstrap/reset `PASSWORD_SECRET` when locked out. Remove this flag after setting a valid hash. - The media scope patch fixes a known upstream issue where file uploads can fail if the token scope is `create update delete` without explicit `media`. @@ -79,4 +79,6 @@ - The files upload locale patch adds missing `files.upload.dropText`/`files.upload.browse`/`files.upload.submitMultiple` labels in endpoint locale files so UI text does not render raw translation keys. - The frontend serviceworker patch ensures `@indiekit/frontend/lib/serviceworker.js` exists at runtime, forces network-only handling for `/auth` and `/session` pages, patches frontend layout templates to unregister stale service workers and clear caches on load, and suppresses sidebar rendering whenever `app--minimalui` is present. - The conversations guard patch prevents `Cannot read properties of undefined (reading 'find')` when the `conversation_items` collection is temporarily unavailable. -- The indieauth dev-mode guard patch prevents accidental production auth bypass by requiring explicit `INDIEKIT_ALLOW_DEV_AUTH=1` to enable dev auto-login. +- The indiekit routes rate-limit patch (ported from `rmdes/indiekit-cloudron`) keeps strict limits on `/session/*`, applies generous limits to public API/well-known routes, and removes extra rate limiting from authenticated routes to avoid admin-side 429 spikes. +- The indiekit error stack patch (ported from `rmdes/indiekit-cloudron`) suppresses stack traces in production error pages/JSON responses to avoid leaking internal runtime details. +- The indieauth dev-mode guard patch prevents accidental production auth bypass by requiring explicit `INDIEKIT_ALLOW_DEV_AUTH=1` to enable dev auto-login, and broadens safe local redirect validation to allow common path characters (`-`, `.`, `%`) used by routes such as `/auth/new-password`. diff --git a/package.json b/package.json index 9b03ea31..63c31c3a 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,8 @@ "description": "", "main": "index.js", "scripts": { - "postinstall": "node scripts/patch-lightningcss.mjs && node scripts/patch-endpoint-media-scope.mjs && node scripts/patch-endpoint-media-sharp-runtime.mjs && node scripts/patch-frontend-sharp-runtime.mjs && node scripts/patch-endpoint-files-upload-route.mjs && node scripts/patch-endpoint-files-upload-locales.mjs && node scripts/patch-frontend-serviceworker-file.mjs && node scripts/patch-conversations-collection-guards.mjs && node scripts/patch-indieauth-devmode-guard.mjs", - "serve": "export NODE_ENV=${NODE_ENV:-production} INDIEKIT_DEBUG=${INDIEKIT_DEBUG:-0} && node scripts/preflight-production-security.mjs && node scripts/preflight-mongo-connection.mjs && node scripts/patch-lightningcss.mjs && node scripts/patch-endpoint-media-scope.mjs && node scripts/patch-endpoint-media-sharp-runtime.mjs && node scripts/patch-frontend-sharp-runtime.mjs && node scripts/patch-endpoint-files-upload-route.mjs && node scripts/patch-endpoint-files-upload-locales.mjs && node scripts/patch-frontend-serviceworker-file.mjs && node scripts/patch-conversations-collection-guards.mjs && node scripts/patch-indieauth-devmode-guard.mjs && node node_modules/@indiekit/indiekit/bin/cli.js serve --config indiekit.config.mjs", + "postinstall": "node scripts/patch-lightningcss.mjs && node scripts/patch-endpoint-media-scope.mjs && node scripts/patch-endpoint-media-sharp-runtime.mjs && node scripts/patch-frontend-sharp-runtime.mjs && node scripts/patch-endpoint-files-upload-route.mjs && node scripts/patch-endpoint-files-upload-locales.mjs && node scripts/patch-frontend-serviceworker-file.mjs && node scripts/patch-conversations-collection-guards.mjs && node scripts/patch-indiekit-routes-rate-limits.mjs && node scripts/patch-indiekit-error-production-stack.mjs && node scripts/patch-indieauth-devmode-guard.mjs", + "serve": "export NODE_ENV=${NODE_ENV:-production} INDIEKIT_DEBUG=${INDIEKIT_DEBUG:-0} && node scripts/preflight-production-security.mjs && node scripts/preflight-mongo-connection.mjs && node scripts/patch-lightningcss.mjs && node scripts/patch-endpoint-media-scope.mjs && node scripts/patch-endpoint-media-sharp-runtime.mjs && node scripts/patch-frontend-sharp-runtime.mjs && node scripts/patch-endpoint-files-upload-route.mjs && node scripts/patch-endpoint-files-upload-locales.mjs && node scripts/patch-frontend-serviceworker-file.mjs && node scripts/patch-conversations-collection-guards.mjs && node scripts/patch-indiekit-routes-rate-limits.mjs && node scripts/patch-indiekit-error-production-stack.mjs && node scripts/patch-indieauth-devmode-guard.mjs && node node_modules/@indiekit/indiekit/bin/cli.js serve --config indiekit.config.mjs", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], diff --git a/scripts/patch-indieauth-devmode-guard.mjs b/scripts/patch-indieauth-devmode-guard.mjs index a02092e0..cb73d47c 100644 --- a/scripts/patch-indieauth-devmode-guard.mjs +++ b/scripts/patch-indieauth-devmode-guard.mjs @@ -14,6 +14,11 @@ const newDevModeCode = `if (devMode && process.env.INDIEKIT_ALLOW_DEV_AUTH === " request.session.scope = "create update delete media"; } else if (!process.env.PASSWORD_SECRET) {`; +const oldRedirectRegex = + "const validRedirect = redirect.match(/^\\/[\\w&/=?]*$/);"; +const newRedirectRegex = + "const validRedirect = redirect.match(/^\\/[\\w&/=?%.-]*$/);"; + async function exists(path) { try { await access(path); @@ -40,6 +45,13 @@ for (const filePath of candidates) { updated = updated.replace(oldDevModeCode, newDevModeCode); } + if ( + !updated.includes(newRedirectRegex) && + updated.includes(oldRedirectRegex) + ) { + updated = updated.replace(oldRedirectRegex, newRedirectRegex); + } + if (updated !== source) { await writeFile(filePath, updated, "utf8"); patched += 1; @@ -51,5 +63,5 @@ if (checked === 0) { } else if (patched === 0) { console.log("[postinstall] indieauth auth-guard patches already applied"); } else { - console.log(`[postinstall] Patched indieauth auth guards in ${patched} file(s)`); + console.log(`[postinstall] Patched indieauth auth guards/redirect validation in ${patched} file(s)`); } diff --git a/scripts/patch-indiekit-error-production-stack.mjs b/scripts/patch-indiekit-error-production-stack.mjs new file mode 100644 index 00000000..b223afa2 --- /dev/null +++ b/scripts/patch-indiekit-error-production-stack.mjs @@ -0,0 +1,84 @@ +import { access, readFile, writeFile } from "node:fs/promises"; + +const candidates = [ + "node_modules/@indiekit/indiekit/lib/middleware/error.js", +]; + +const marker = 'const isDev = process.env.NODE_ENV !== "production";'; + +const replacements = [ + { + from: " debug(\"Error\", error);\n", + to: ` debug("Error", error);\n\n // Only include stack traces in development\n const isDev = process.env.NODE_ENV !== "production";\n`, + }, + { + from: " stack: error.stack,", + to: " stack: isDev ? error.stack : undefined,", + }, + { + from: " stack: cleanStack(error.stack),", + to: " ...(isDev && { stack: cleanStack(error.stack) }),", + }, + { + from: " ...(error.cause && { cause: error.cause }),", + to: " ...(isDev && error.cause && { cause: error.cause }),", + }, +]; + +async function exists(filePath) { + try { + await access(filePath); + return true; + } catch { + return false; + } +} + +let checked = 0; +let patched = 0; + +for (const filePath of candidates) { + if (!(await exists(filePath))) { + continue; + } + + checked += 1; + const source = await readFile(filePath, "utf8"); + + if (source.includes(marker)) { + continue; + } + + let updated = source; + + for (const replacement of replacements) { + if (updated.includes(replacement.from)) { + updated = updated.replace(replacement.from, replacement.to); + } + } + + const looksPatched = + updated.includes(marker) && + updated.includes("stack: isDev ? error.stack : undefined,") && + updated.includes("...(isDev && { stack: cleanStack(error.stack) }),") && + updated.includes("...(isDev && error.cause && { cause: error.cause }),") && + !updated.includes("stack: error.stack,"); + + if (!looksPatched) { + console.warn( + `[postinstall] Skipping error middleware patch for ${filePath}: upstream format changed`, + ); + continue; + } + + await writeFile(filePath, updated, "utf8"); + patched += 1; +} + +if (checked === 0) { + console.log("[postinstall] No indiekit error middleware files found"); +} else if (patched === 0) { + console.log("[postinstall] indiekit error stack patch already applied"); +} else { + console.log(`[postinstall] Patched indiekit production error stack handling in ${patched} file(s)`); +} \ No newline at end of file diff --git a/scripts/patch-indiekit-routes-rate-limits.mjs b/scripts/patch-indiekit-routes-rate-limits.mjs new file mode 100644 index 00000000..ec6800d0 --- /dev/null +++ b/scripts/patch-indiekit-routes-rate-limits.mjs @@ -0,0 +1,184 @@ +import { access, readFile, writeFile } from "node:fs/promises"; + +const candidates = [ + "node_modules/@indiekit/indiekit/lib/routes.js", +]; + +const patchMarker = "const sessionLimit = rateLimit({"; + +const oldLimitBlock = `const router = express.Router(); +const limit = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 250, + standardHeaders: true, + legacyHeaders: false, + validate: false, +});`; + +const newLimitBlock = `const router = express.Router(); + +// Strict rate limiter for session/auth routes (brute force protection) +const sessionLimit = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, + standardHeaders: true, + legacyHeaders: false, + validate: false, +}); + +// Generous rate limiter for public API endpoints (read-only data) +const apiLimit = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 1000, + standardHeaders: true, + legacyHeaders: false, + validate: false, +});`; + +const replacements = [ + { + label: "session login rate limit", + from: ' router.get("/session/login", limit, sessionController.login);', + to: ' router.get("/session/login", sessionLimit, sessionController.login);', + }, + { + label: "session post rate limit", + from: ' router.post("/session/login", limit, indieauth.login());', + to: ' router.post("/session/login", sessionLimit, indieauth.login());', + }, + { + label: "session auth rate limit", + from: ' router.get("/session/auth", limit, indieauth.authorize());', + to: ' router.get("/session/auth", sessionLimit, indieauth.authorize());', + }, + { + label: "public _routes rate limit", + from: " router.use(endpoint.mountPath, limit, endpoint._routes(Indiekit));", + to: " router.use(endpoint.mountPath, apiLimit, endpoint._routes(Indiekit));", + }, + { + label: "public routesPublic rate limit", + from: ` if (endpoint.mountPath && endpoint.routesPublic) { + router.use(endpoint.mountPath, limit, endpoint.routesPublic); + }`, + to: ` if (endpoint.mountPath && endpoint.routesPublic) { + // Skip rate limiting for root-mounted endpoints (mountPath "/") because + // router.use("/", apiLimit, ...) matches ALL routes, applying the rate + // limiter globally. + if (endpoint.mountPath === "/") { + router.use(endpoint.mountPath, endpoint.routesPublic); + } else { + router.use(endpoint.mountPath, apiLimit, endpoint.routesPublic); + } + }`, + }, + { + label: "well-known rate limit", + from: ' router.use("/.well-known/", limit, endpoint.routesWellKnown);', + to: ' router.use("/.well-known/", apiLimit, endpoint.routesWellKnown);', + }, + { + label: "content negotiation routes", + from: " // Authenticate subsequent requests", + to: ` // Content negotiation routes - serves ActivityPub JSON-LD for post URLs + // and handles NodeInfo data at /nodeinfo/2.1. Mounted at root before auth + // so unauthenticated AP clients can fetch post representations. + for (const endpoint of endpoints) { + if (endpoint.contentNegotiationRoutes) { + router.use("/", endpoint.contentNegotiationRoutes); + } + } + + // Authenticate subsequent requests`, + }, + { + label: "plugin list limit removal", + from: ' router.get("/plugins", limit, pluginController.list);', + to: ' router.get("/plugins", pluginController.list);', + }, + { + label: "plugin view limit removal", + from: ' router.get("/plugins/:pluginId", limit, pluginController.view);', + to: ' router.get("/plugins/:pluginId", pluginController.view);', + }, + { + label: "status limit removal", + from: ' router.get("/status", limit, statusController.viewStatus);', + to: ' router.get("/status", statusController.viewStatus);', + }, + { + label: "authenticated endpoint limit removal", + from: " router.use(endpoint.mountPath, limit, endpoint.routes);", + to: " router.use(endpoint.mountPath, endpoint.routes);", + }, +]; + +async function exists(filePath) { + try { + await access(filePath); + return true; + } catch { + return false; + } +} + +let checked = 0; +let patched = 0; + +for (const filePath of candidates) { + if (!(await exists(filePath))) { + continue; + } + + checked += 1; + const source = await readFile(filePath, "utf8"); + + if (source.includes(patchMarker)) { + continue; + } + + if (!source.includes(oldLimitBlock)) { + console.warn( + `[postinstall] Skipping routes patch for ${filePath}: upstream format changed`, + ); + continue; + } + + let updated = source.replace(oldLimitBlock, newLimitBlock); + + for (const replacement of replacements) { + if (updated.includes(replacement.from)) { + updated = updated.replace(replacement.from, replacement.to); + } else { + console.warn( + `[postinstall] routes patch skipped section (${replacement.label}) in ${filePath}`, + ); + } + } + + const looksPatched = + updated.includes("const sessionLimit = rateLimit({") && + updated.includes("const apiLimit = rateLimit({") && + updated.includes('router.get("/session/login", sessionLimit, sessionController.login);') && + updated.includes("router.use(endpoint.mountPath, endpoint.routes);") && + !updated.includes('router.get("/session/login", limit, sessionController.login);') && + !updated.includes("router.use(endpoint.mountPath, limit, endpoint.routes);"); + + if (!looksPatched) { + console.warn( + `[postinstall] Skipping routes patch for ${filePath}: patch validation failed`, + ); + continue; + } + + await writeFile(filePath, updated, "utf8"); + patched += 1; +} + +if (checked === 0) { + console.log("[postinstall] No indiekit routes files found"); +} else if (patched === 0) { + console.log("[postinstall] indiekit routes rate-limit patch already applied"); +} else { + console.log(`[postinstall] Patched indiekit routes rate limits in ${patched} file(s)`); +} \ No newline at end of file diff --git a/start.example.sh b/start.example.sh index 6116fc41..bc390292 100644 --- a/start.example.sh +++ b/start.example.sh @@ -54,6 +54,8 @@ unset DEBUG /usr/local/bin/node scripts/patch-endpoint-files-upload-locales.mjs /usr/local/bin/node scripts/patch-frontend-serviceworker-file.mjs /usr/local/bin/node scripts/patch-conversations-collection-guards.mjs +/usr/local/bin/node scripts/patch-indiekit-routes-rate-limits.mjs +/usr/local/bin/node scripts/patch-indiekit-error-production-stack.mjs /usr/local/bin/node scripts/patch-indieauth-devmode-guard.mjs exec /usr/local/bin/node node_modules/@indiekit/indiekit/bin/cli.js serve --config indiekit.config.mjs