# Security Audit — toolctrl-boilerplate
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 (new `sanitizeIconSvg`), 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-default `API_KEY_LEGACY_PLAINTEXT_FALLBACK=false`, fail-closed public rate limiters, admin-SSO `returnTo` backslash open-redirect, Meilisearch KB filter escaping, CI `workflow_dispatch` script-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 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 `
`. marked emits this block-level HTML verbatim. During SSR the regex sanitizer leaves `` 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; `` 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):
1. 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.
2. 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.
3. RENDER: KbArticle.tsx:52 -> KbArticleContent.tsx:80 does .
4. 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 `` 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 `
` 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:
), so this is a server-SSR-only bypass that ships to every reader.
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
) through verbatim — confirmed at runtime. (3) The admin edit/write route is permission-gated (verifyUserHasPermission admin.kb.update + CSRF), so only an authenticated KB editor can author the payload — but the READ surface is anonymous public, so any tenant editor (or compromised editor account) achieves stored XSS against all public readers. No write-time sanitization, no allowlist, no DOMPurify/sanitize-html anywhere in the path.
---
## 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 `` 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 `` 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 `` works.
**Evidence**
```
} else if (PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg") {
return ;
}
```
**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 `` 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 @toolctrl/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') && !replace` is 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: }. The endpoint only checks getTenantUserType (any active membership passes) and returns a valid 15-minute JWT for documentName `T:row:`. 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 '' string -> stored verbatim -> rendered as `` with no sanitization of the SVG body/attributes
**Exploit scenario**
An entity/KB administrator stores an icon string containing scriptable SVG, e.g. `` or SVG with ``/`` payloads. When rendered in the sidebar/entity list/public KB grid, the markup runs depending on browser/SVG parsing context. The .replace('
```
**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("` 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("