Skip to content

fix: harden KDS WebSocket admission, printer targets, and desktop runtime boundaries - #1511

Merged
khaira777 merged 4 commits into
mainfrom
fm/flocafe-sec-batch3-kds-printers-hardening
Nov 8, 2026
Merged

khaira777 merged 4 commits into
mainfrom
fm/flocafe-sec-batch3-kds-printers-hardening

Conversation

@khaira777

@khaira777 khaira777 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Proceed with sequential local implementation Batch 3 (Items 7, 8, and 9 of the revised security plan), subject to these decisions and acceptance criteria:

  1. Approve KDS connection fairness :
  • Retain the 25 pending-authentication global limit and five-second grace period; use five pending connections per normalized IP initially.
  • Authenticated connections must stop consuming that pending budget.
  • Prefer admission checks before upgrade on both listeners, and ensure rejected connections cannot accumulate while closing.
  • Validate supplied Origins while supporting legitimate clients without Origin headers.
  • Verify simultaneous reconnects, including clients sharing an IP.
  1. Choose printer compatibility over a new private-IP-only policy :
  • Preserve working hostnames, custom ports, LAN/Tailscale/IPv6 configurations, and legitimate link-local printers.
  • Do not blanket-ban public addresses, all link-local addresses, or ports 3001-3003 across the network.
  • Narrow hardening may reject known metadata destinations and FloCafe's actual own listening endpoints, with validation at dispatch as well as configuration.
  • Preserve useful failure classes and troubleshooting detail. Do not describe this limited hardening as complete SSRF remediation.
  1. Approve the remaining small hardening changes with focused verification :
  • Unique, exclusive spool files with restrictive permissions and cleanup of files actually created by this operation .
  • Shared credential redaction at IPC and support-upload boundaries, retaining actionable diagnostic detail .
  • Targeted child-popup navigation guards that preserve printing and local KDS behavior .
  • ETag checking before image decoding and bounds consistent with accepted image data . Defer additional image/API rate-limit thresholds until measured against product-grid loads, polling, proxy traffic, and reconnect bursts. Preserve loopback health probes and existing Server App protection.
  1. Verification & Commit Gate:
  • Run focused regression suites, npm run lint, npm run build, and npm test; run browser/Electron checks for affected flows and documentation checks for changed contracts. Report fresh results, limitations, final diff, and git status.
  • Commit, push, and create the PR using /no-mistakes: yes.

What Changed

  • Enforce pre-upgrade KDS WebSocket admission on both the API (:3001) and standalone KDS (:3002) listeners with Origin validation, a 5-connection-per-IP pending-authentication cap alongside the 25-connection global pending limit, and immediate pruning of closing sockets.
  • Validate network printer targets at configuration and dispatch time to reject cloud-metadata endpoints, multicast/broadcast ranges, and FloCafe's own active listening ports on loopback, wildcard, or local interface addresses while preserving hostname, LAN, Tailscale, IPv6, and link-local printers, and open Windows raw-print spool files exclusively (wx, 0o600) with tracked cleanup.
  • Redact credentials and bearer/OAuth/JWT tokens across get-log-tail IPC and /api/support-ticket log uploads, attach did-create-window navigation and nested-popup guards to Electron child windows while permitting local blob: print previews, and evaluate If-None-Match ETags on GET /api/products/:id/image before decoding image payloads.

Risk Assessment

✅ Low: The security hardening changes across KDS WebSocket admission, network printer target validation, exclusive spool file handling, diagnostic log redaction, child popup navigation guards, and product image ETag/size bounds are well-bounded, linear-time, and thoroughly covered by regression tests.

Testing

Ran 11 targeted regression suites covering KDS WebSocket admission/revalidation, network printer target validation, Windows/CUPS spool file exclusivity, support ticket and IPC log tail redaction, child-popup navigation guards, URL allowlist, CORS, and product image ETag/bounds handling, and stood up the live Express (:3001) and KDS (:3002) servers in an isolated environment to drive all 8 happy-path and adversarial scenarios end-to-end with evidence captured in live-batch3-verification.json (no visual UI layout changes were introduced in this backend/IPC security batch).

  • Live validation: ✅ go - 8 of 8 scenarios driven live against the product
Scenario Result Live Evidence
KDS WebSocket upgrade on both :3001 and :3002 admits legitimate clients without or with local/LAN/Tailscale Origin headers, enforces 5 pending connections per normalized IP, and releases pending budge… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and node tests/run-electron-node-test.cjs tests/kds-websocket-revalidation.test.ts
Adversarial KDS WebSocket upgrade with untrusted Origin (403 Forbidden) or 6th unauthenticated connection from the same IP (429 Too Many Requests) is rejected before upgrade on both :3001 and :3002 wi… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and node tests/run-electron-node-test.cjs tests/kds-websocket-revalidation.test.ts
Network printer configuration and printViaNetwork dispatch preserve LAN, custom port 3001 on remote host, Tailscale, legitimate link-local (169.254.10.20, fe80::1), mDNS hostnames, and loopback therma… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:printer-api
Adversarial network printer configuration (POST/PUT /api/printers) and printViaNetwork dispatch reject cloud metadata endpoints (169.254.169.254, ::ffff:169.254.169.254, fd00:ec2::254, metadata.google… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:printer-api
Raw print spooling creates unique, exclusive (wx, 0600) temporary files with UUID suffixes and refuses to overwrite or unlink pre-existing files on path collision ✅ pass live npx ts-node --transpile-only -P tests/tsconfig.json tests/windows-print-error-detail.test.ts
Shared credential redaction in get-log-tail IPC and POST /api/support-ticket scrubs JWTs, Authorization headers, master PINs, passwords, PINs, API keys (x-api-key, api_key, apiKey), cloud secrets, and… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:support-ticket
Child windows spawned from the main window allow about:blank, local blob: menu print popups, and local KDS URLs while denying nested window.open calls, routing external https: links to shell.openExter… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json, npm run test:update-ipc-sender-validation, and npm run test:url-allowlist
GET /api/products/:id/image short-circuits with 304 Not Modified on matching If-None-Match ETag before Base64 decoding and rejects oversized stored image data with 404 before Base64 decoding ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:product-images
Evidence: Live Batch 3 verification output against running POS and KDS servers

{ "kdsFairnessAndOrigin": { "apiPort": 3001, "kdsPort": 3002, "evilOriginMainStatus": 403, "evilOriginKdsStatus": 403, "clientCountAfterEvilOrigin": 0, "pendingCountWave1": 5, "sixthUnauthenticatedMainStatus": 429, "sixthUnauthenticatedKdsStatus": 429, "countAfterSixthRejected": 5, "totalAuthenticatedCoexisting": 10 }, "printerHardeningAndCompatibility": { "createValidPrinterStatus": 201, "dispatchValidOk": true, "receivedByMockPrinter": "HELLO ESC/POS", "blockedResults": [ { "label": "cloud metadata IPv4", "apiStatus": 400, "dispatchOk": false }, { "label": "cloud metadata FQDN", "apiStatus": 400, "dispatchOk": false }, { "label": "unspecified IPv4", "apiStatus": 400, "dispatchOk": false }, { "label": "own API port", "apiStatus": 400, "dispatchOk": false }, { "label": "own KDS port", "apiStatus": 400, "dispatchOk": false } ] }, "credentialRedaction": { "supportTicketStatus": 202, "containsAnyRawSecret": false, "ipcText": "[2026-11-08 12:20:00.123] [error] [Auth] Handshake failed code=ECONNRESET\nAuthorization: Bearer [REDACTED]\n{"x-master-pin":"[REDACTED]","password":"[REDACTED]","pin":"[REDACTED]"}\nx-api-key=[REDACTED] api_key="[REDACTED]" apiKey=[REDACTED]\noauth access_token="[REDACTED]" refresh_token=[REDACTED]\n at verifySocket (/app/main/services/kds.ts:140:11)" }, "childWindowGuards": { "nestedWindowOpenAction": "deny", "navResults": [ { "url": "about:blank", "prevented": false, "openedExternally": null }, { "url": "blob:http://localhost:3001/menu-print-uuid", "prevented": false, "openedExternally": null }, { "url": "http://localhost:3001/kds", "prevented": false, "openedExternally": null }, { "url": "https://example.com/external-help", "prevented": true, "openedExternally": "https://example.com/external-help" }, { "url": "blob:https://evil.example/payload", "prevented": true, "openedExternally": null }, { "url": "javascript:alert(1)", "prevented": true, "openedExternally": null } ] }, "productImageEtagAndBounds": { "initialGetStatus": 200, "notModifiedStatus": 304, "decodeCountOn304": 0, "oversizedGetStatus": 404, "decodeCountOnOversized": 0 } }

{
  "timestamp": "2026-11-08T17:28:45.550Z",
  "scenarios": {
    "kdsFairnessAndOrigin": {
      "apiPort": 3001,
      "kdsPort": 3002,
      "evilOriginMainStatus": 403,
      "evilOriginKdsStatus": 403,
      "clientCountAfterEvilOrigin": 0,
      "pendingCountWave1": 5,
      "sixthUnauthenticatedMainStatus": 429,
      "sixthUnauthenticatedKdsStatus": 429,
      "countAfterSixthRejected": 5,
      "totalAuthenticatedCoexisting": 10
    },
    "printerHardeningAndCompatibility": {
      "createValidPrinterStatus": 201,
      "printerId": "480a22ea-1631-415d-8dc8-a5780c09554d",
      "dispatchValidOk": true,
      "receivedByMockPrinter": "HELLO ESC/POS",
      "compatibleTargets": [
        {
          "target": "192.168.1.50:9100",
          "validationError": null
        },
        {
          "target": "192.168.1.50:3001",
          "validationError": null
        },
        {
          "target": "100.64.0.25:9100",
          "validationError": null
        },
        {
          "target": "169.254.10.20:9100",
          "validationError": null
        },
        {
          "target": "fe80::1:9100",
          "validationError": null
        },
        {
          "target": "printer.local:9100",
          "validationError": null
        }
      ],
      "blockedResults": [
        {
          "label": "cloud metadata IPv4",
          "apiStatus": 400,
          "apiError": "Printer address cannot target a cloud metadata service",
          "dispatchOk": false,
          "dispatchDetail": "Printer address cannot target a cloud metadata service",
          "dispatchFailureClass": "unknown"
        },
        {
          "label": "cloud metadata FQDN",
          "apiStatus": 400,
          "apiError": "Printer address cannot target a cloud metadata service",
          "dispatchOk": false,
          "dispatchDetail": "Printer address cannot target a cloud metadata service",
          "dispatchFailureClass": "unknown"
        },
        {
          "label": "unspecified IPv4",
          "apiStatus": 400,
          "apiError": "Printer address cannot be an unspecified or broadcast address",
          "dispatchOk": false,
          "dispatchDetail": "Printer address cannot be an unspecified or broadcast address",
          "dispatchFailureClass": "unknown"
        },
        {
          "label": "own API port",
          "apiStatus": 400,
          "apiError": "Printer address cannot target a local FloCafe server port",
          "dispatchOk": false,
          "dispatchDetail": "Printer address cannot target a local FloCafe server port",
          "dispatchFailureClass": "unknown"
        },
        {
          "label": "own KDS port",
          "apiStatus": 400,
          "apiError": "Printer address cannot target a local FloCafe server port",
          "dispatchOk": false,
          "dispatchDetail": "Printer address cannot target a local FloCafe server port",
          "dispatchFailureClass": "unknown"
        }
      ]
    },
    "credentialRedaction": {
      "ipcTruncated": false,
      "ipcText": "[2026-11-08 12:20:00.123] [error] [Auth] Handshake failed code=ECONNRESET\nAuthorization: Bearer [REDACTED]\n{\"x-master-pin\":\"[REDACTED]\",\"password\":\"[REDACTED]\",\"pin\":\"[REDACTED]\"}\nx-api-key=[REDACTED] api_key=\"[REDACTED]\" apiKey=[REDACTED]\noauth access_token=\"[REDACTED]\" refresh_token=[REDACTED]\n    at verifySocket (/app/main/services/kds.ts:140:11)",
      "supportTicketStatus": 202,
      "outboxLogTail": "[2026-11-08 12:20:00.123] [error] [Auth] Handshake failed code=ECONNRESET\nAuthorization: Bearer [REDACTED]\n{\"x-master-pin\":\"[REDACTED]\",\"password\":\"[REDACTED]\",\"pin\":\"[REDACTED]\"}\nx-api-key=[REDACTED] api_key=\"[REDACTED]\" apiKey=[REDACTED]\noauth access_token=\"[REDACTED]\" refresh_token=[REDACTED]\n    at verifySocket (/app/main/services/kds.ts:140:11)",
      "containsAnyRawSecret": false
    },
    "childWindowGuards": {
      "nestedWindowOpenAction": "deny",
      "navResults": [
        {
          "url": "about:blank",
          "prevented": false,
          "openedExternally": null
        },
        {
          "url": "blob:http://localhost:3001/menu-print-uuid",
          "prevented": false,
          "openedExternally": null
        },
        {
          "url": "http://localhost:3001/kds",
          "prevented": false,
          "openedExternally": null
        },
        {
          "url": "https://example.com/external-help",
          "prevented": true,
          "openedExternally": "https://example.com/external-help"
        },
        {
          "url": "blob:https://evil.example/payload",
          "prevented": true,
          "openedExternally": null
        },
        {
          "url": "javascript:alert(1)",
          "prevented": true,
          "openedExternally": null
        }
      ]
    },
    "productImageEtagAndBounds": {
      "initialGetStatus": 200,
      "etag": "\"10a7227ade22bb007518dbb14d064d2f3b0d5a282264d6d94a8682d68866650a\"",
      "notModifiedStatus": 304,
      "decodeCountOn304": 0,
      "oversizedGetStatus": 404,
      "decodeCountOnOversized": 0
    }
  }
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 8 of 8 scenarios driven live against the product
Scenario Result Live Evidence
KDS WebSocket upgrade on both :3001 and :3002 admits legitimate clients without or with local/LAN/Tailscale Origin headers, enforces 5 pending connections per normalized IP, and releases pending budge… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and node tests/run-electron-node-test.cjs tests/kds-websocket-revalidation.test.ts
Adversarial KDS WebSocket upgrade with untrusted Origin (403 Forbidden) or 6th unauthenticated connection from the same IP (429 Too Many Requests) is rejected before upgrade on both :3001 and :3002 wi… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and node tests/run-electron-node-test.cjs tests/kds-websocket-revalidation.test.ts
Network printer configuration and printViaNetwork dispatch preserve LAN, custom port 3001 on remote host, Tailscale, legitimate link-local (169.254.10.20, fe80::1), mDNS hostnames, and loopback therma… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:printer-api
Adversarial network printer configuration (POST/PUT /api/printers) and printViaNetwork dispatch reject cloud metadata endpoints (169.254.169.254, ::ffff:169.254.169.254, fd00:ec2::254, metadata.google… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:printer-api
Raw print spooling creates unique, exclusive (wx, 0600) temporary files with UUID suffixes and refuses to overwrite or unlink pre-existing files on path collision ✅ pass live npx ts-node --transpile-only -P tests/tsconfig.json tests/windows-print-error-detail.test.ts
Shared credential redaction in get-log-tail IPC and POST /api/support-ticket scrubs JWTs, Authorization headers, master PINs, passwords, PINs, API keys (x-api-key, api_key, apiKey), cloud secrets, and… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:support-ticket
Child windows spawned from the main window allow about:blank, local blob: menu print popups, and local KDS URLs while denying nested window.open calls, routing external https: links to shell.openExter… ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json, npm run test:update-ipc-sender-validation, and npm run test:url-allowlist
GET /api/products/:id/image short-circuits with 304 Not Modified on matching If-None-Match ETag before Base64 decoding and rejects oversized stored image data with 404 before Base64 decoding ✅ pass live ~/.no-mistakes/evidence/01M6Y2BD0CCQHVRPP0VKTPPWB4/live-batch3-verification.json and npm run test:product-images
  • node tests/run-electron-node-test.cjs tests/kds-websocket-revalidation.test.ts
  • npm run test:printer-api
  • npm run test:product-images
  • npm run test:support-ticket
  • npm run test:update-ipc-sender-validation
  • npx ts-node --transpile-only -P tests/tsconfig.json tests/windows-print-error-detail.test.ts
  • npm run test:url-allowlist
  • npm run test:cors
  • npm run test:titlebar-window-options
  • npm run test:kds-window-hardening
  • npm run test:script-coverage
  • node tests/run-electron-node-test.cjs /tmp/live-verify-batch3.ts
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@qodo-code-review

Copy link
Copy Markdown

ⓘ Your Qodo trial ends soon. Ask your workspace admin to set up billing to keep reviews running after the trial. Manage billing

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Harden KDS admission, printer dispatch, and desktop boundaries

🐞 Bug fix ✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Limit pending KDS connections per IP and validate Origins before WebSocket upgrades on both
 listeners.
• Reject selected unsafe printer destinations while preserving supported network setups; protect
 spool files and support logs.
• Guard child popups and image decoding, with focused regression tests and updated contracts.
Diagram

graph TD
  KDS["KDS listeners"] --> Admission["Admission checks"] --> Sessions["KDS sessions"]
  PrinterAPI["Printer API"] --> Targets["Target validation"] --> Transport["Print transports"]
  Logs["Diagnostic logs"] --> Sanitizer["Shared sanitizer"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Centralize KDS upgrade handling
  • ➕ Keeps both listeners' rejection and upgrade behavior together.
  • ➖ Requires broader listener refactoring for a focused admission change.
2. Pin resolved printer destinations
  • ➕ Could address hostname resolution changes that the selected-target checks do not cover.
  • ➖ Adds DNS and connection complexity and needs careful compatibility testing for existing printers.

Recommendation: Keep the PR's shared admission and printer-validation functions for this scoped hardening: they cover both relevant entry points without imposing a private-IP-only printer policy. Consider centralized upgrade handling if the listeners diverge, and resolution pinning only as a separately specified, compatibility-tested SSRF effort; these checks are not complete SSRF remediation.

Files changed (23) +1235 / -177

Enhancement (1) +10 / -0
server-state.tsTrack the active standalone KDS port +10/-0

Track the active standalone KDS port

• Adds KDS port accessors so printer validation can recognize the active local listener.

main/server-state.ts

Bug fix (11) +396 / -33
index.tsInstall guards on POS child windows +2/-0

Install guards on POS child windows

• Attaches child-window lifecycle guards alongside the main window's existing popup and navigation handlers.

main/index.ts

ipc.tsRedact credentials from IPC log tails +5/-1

Redact credentials from IPC log tails

• Sanitizes the bounded log tail returned by the get-log-tail handler.

main/ipc.ts

kds-server.tsCheck standalone KDS upgrades before admission +12/-1

Check standalone KDS upgrades before admission

• Applies shared Origin and capacity checks before upgrading standalone KDS sockets. Publishes its active port for printer-target checks.

main/kds-server.ts

log-sanitizer.tsAdd shared diagnostic credential sanitizer +34/-0

Add shared diagnostic credential sanitizer

• Redacts JWTs, authorization credentials, OAuth tokens, and named secret fields while retaining surrounding diagnostic text.

main/lib/log-sanitizer.ts

thermal.tsValidate network targets and protect spool files +176/-11

Validate network targets and protect spool files

• Checks selected metadata, unspecified, broadcast, and local FloCafe endpoint targets before network dispatch without broadly banning printer networks or ports. CUPS and Windows printing now create exclusive per-job spool files and remove only files they created.

main/printers/thermal.ts

printers.tsValidate printer destinations during configuration +11/-0

Validate printer destinations during configuration

• Applies network-target validation to create and update requests, including partial updates resolved against existing host and port values.

main/routes/printers.ts

products.tsBound image decoding and revalidate first +15/-5

Bound image decoding and revalidate first

• Aligns served-image limits with accepted data URIs, rejects oversized stored data before decoding, and returns matching ETags without Base64 decoding.

main/routes/products.ts

support-ticket.tsRedact support-ticket log tails before storage +4/-1

Redact support-ticket log tails before storage

• Sanitizes bounded, user-supplied log tails before queueing support tickets.

main/routes/support-ticket.ts

server.tsCheck main API KDS upgrades before admission +10/-1

Check main API KDS upgrades before admission

• Rejects disallowed Origins and over-capacity KDS requests before the main server upgrades their sockets.

main/server.ts

kds.tsEnforce shared KDS pending-client budgets +97/-13

Enforce shared KDS pending-client budgets

• Tracks normalized client IPs, applies global and per-IP pending limits, and prunes closing sockets during admission. Authenticated clients no longer count toward pending limits, and direct connection events receive the same checks.

main/services/kds.ts

window-options.tsConstrain navigation in child popups +30/-0

Constrain navigation in child popups

• Adds lifecycle hooks that deny nested popups and reuse the main window's navigation policy for child windows.

main/window-options.ts

Refactor (1) +25 / -9
security.tsShare Origin validation with KDS admission +25/-9

Share Origin validation with KDS admission

• Extracts the local, LAN, and Tailscale Origin policy for reuse by CORS and WebSocket admission, including clients without an Origin header.

main/middleware/security.ts

Tests (6) +778 / -117
kds-websocket-revalidation.test.tsCover KDS Origin and per-IP admission +227/-37

Cover KDS Origin and per-IP admission

• Tests pre-upgrade Origin rejection, five pending sockets per IP, repeated over-cap rejection, and new same-IP connections after authentication.

tests/kds-websocket-revalidation.test.ts

printer-api.test.tsCover blocked and compatible printer targets +95/-1

Cover blocked and compatible printer targets

• Exercises configuration and dispatch rejection for selected unsafe targets while checking permitted LAN, Tailscale, link-local, hostname, and custom-port cases.

tests/printer-api.test.ts

product-images.test.tsVerify image revalidation avoids decoding +220/-74

Verify image revalidation avoids decoding

• Checks that a matching ETag returns before Base64 decoding and that oversized stored image data is rejected before decoding.

tests/product-images.test.ts

support-ticket.test.tsVerify support-log redaction and retention +75/-0

Verify support-log redaction and retention

• Tests token and secret removal, preservation of useful diagnostics, and sanitized log tails in queued ticket payloads.

tests/support-ticket.test.ts

update-ipc-sender-validation.test.tsCover child-popup lifecycle restrictions +90/-1

Cover child-popup lifecycle restrictions

• Verifies nested-popup denial, permitted print and local KDS navigation, external-browser routing, and unsafe-scheme blocking.

tests/update-ipc-sender-validation.test.ts

windows-print-error-detail.test.tsVerify exclusive Windows spool behavior +71/-4

Verify exclusive Windows spool behavior

• Checks restrictive spool permissions and confirms a file collision neither invokes the print helper nor removes the pre-existing file.

tests/windows-print-error-detail.test.ts

Documentation (4) +26 / -18
cloud-integrations.mdDocument support-log credential redaction +4/-5

Document support-log credential redaction

• Describes redaction at the IPC and support-ticket boundaries and the diagnostic detail retained.

docs/architecture/cloud-integrations.md

desktop-build.mdDocument child-window navigation guards +3/-1

Document child-window navigation guards

• Explains nested-popup denial and child navigation handling while noting supported print and KDS popups.

docs/architecture/desktop-build.md

printing.mdDocument printer target and spool protections +3/-3

Document printer target and spool protections

• Records the narrow network-target restrictions and exclusive, restrictive temporary files used by CUPS and Windows printing.

docs/architecture/printing.md

api.mdUpdate image and KDS connection contracts +16/-9

Update image and KDS connection contracts

• Clarifies unauthenticated image delivery, size limits, and ETag behavior. Documents pre-upgrade KDS rejections and pending-client limits.

docs/reference/api.md

Comment thread main/printers/thermal.ts Fixed
@qodo-code-review

qodo-code-review Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Desktop menu printing stays blank ✓ Resolved

Resolving commit: 6010612

Resolution reason
main/security/url-allowlist.ts now lets blob: URLs through isAllowedLocalWindowUrl when the embedded
http origin is a local allowed origin (same port), while still rejecting external or wrong-port blob
URLs. The child-window will-navigate guard in main/window-options.ts uses this allowlist, so the
print popup's local blob navigation is permitted. Tests in
tests/update-ipc-sender-validation.test.ts cover local blob allowed and external/wrong-port blob
blocked. This is a narrowly scoped allowance, though it is implemented in the URL allowlist rather
than by designating print popups as the suggested fix describes.
Description
attachChildWindowLifecycleGuards installs the main-window navigation handler on print popups, and
that handler prevents the blob: navigation used by printMenuInBrowser. In Electron, paper menu
printing opens an about:blank child and then navigates it to the generated document, so the print
document never loads and the print trigger does not run.


Remediation recommended

2. Local printers lose unused ports ✓ Resolved

Resolving commit: 6010612

Resolution reason
The hardcoded 3001, 3002, 3003 entries were removed from the ownPorts set in
validateNetworkPrinterTarget; it now contains only the active getServerPort(), getKdsPort(), and
getServerAppPort() values. A test was added verifying that after setServerPort(4301), 127.0.0.1:3001
is allowed while 127.0.0.1:4301 is blocked. This addresses the finding via the same approach of
basing the restriction on actually active listener ports, though it does not explicitly add a
server-state-driven refactor beyond what already existed.
Description
validateNetworkPrinterTarget always adds ports 3001, 3002, and 3003 to the blocked local-port set,
regardless of the active FloCafe listener ports. When the servers bind elsewhere, a legitimate local
printer on one of those now-unused ports is rejected at both configuration and dispatch.

3. Redacted auth headers keep a stray bracket that grows each pass ✓ Resolved

Resolving commit: 6010612

Resolution reason
The commit adds the suggested negative lookahead (?!\[REDACTED\]) to AUTH_HEADER_RE and to
BEARER_TOKEN_RE, so placeholders are no longer re-matched and the trailing ] is no longer appended.
It also adds tests asserting 'Authorization: Bearer [REDACTED]' with no extra ] and that
sanitizeLogTail is idempotent across repeated passes. Additionally, the commit reorders sanitization
in main/ipc.ts so sanitizing happens before slicing, which is consistent with the repeated-pass
concern.
Description
AUTH_HEADER_RE runs after JWT_TOKEN_RE, so the header value it sees is the placeholder
[REDACTED]. Its value class [^\s"',;}\]]+ matches [REDACTED and stops at ], which turns
Bearer <jwt> into Bearer [REDACTED]]; the PR's own sanitizedLogTailSample shows this output.
The function also isn't idempotent: the tail is sanitized in the get-log-tail IPC handler and
again in POST /api/support-ticket, and each pass adds another ], so support staff get corrupted
log lines.

4. Common API keys remain in support logs ✓ Resolved

Resolving commit: 6010612

Resolution reason
Added x-api-key, api_key, and apiKey to SENSITIVE_KEY_PATTERN in main/lib/log-sanitizer.ts so their
values are redacted by the quoted/unquoted key-value regex. Also reordered support-ticket.ts so
sanitizeLogTail runs before the byte-cap slice (closing a boundary-crossing leak), and added tests
in tests/support-ticket.test.ts that exercise these key forms through the /api/support-ticket upload
path.
Description
SENSITIVE_KEY_PATTERN lists cloud-specific key names but omits common fields such as api_key,
apiKey, and x-api-key. A support request containing one of those fields in log_tail retains
its value after sanitizeLogTail, and the resulting tail is placed in the outbox payload sent
upstream.

View medium (3)
5. Printer aliases reach blocked destinations 🐞 Bug ⛨ Security
Description
validateNetworkPrinterTarget checks literal hostnames and IP addresses but accepts other hostnames
without checking their resolved addresses. A configured hostname resolving to a metadata address or
a local FloCafe listening endpoint passes both configuration and dispatch validation before
client.connect resolves and connects to that destination.
Code

main/printers/thermal.ts[R5111-5113]

+  }
+
+  return null;
Relevance

●● Moderate

Hostname resolution is a semantic, architectural hardening question. The PR explicitly scopes this
as narrow hardening, so acceptance is uncertain.

PR-#899

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Unknown hostname text falls through the literal checks; the same hostname is subsequently passed to
the TCP connection. Printer configuration calls the validator but does not resolve the name either.
This is a blind TCP-write path, not a path for reading metadata responses.

main/printers/thermal.ts[5048-5056]
main/printers/thermal.ts[5079-5113]
main/printers/thermal.ts[5122-5135]
main/printers/thermal.ts[5155-5165]
main/routes/printers.ts[124-142]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
DNS aliases bypass the new restrictions on metadata destinations and local FloCafe endpoints because validation precedes hostname resolution.
## Fix Focus Areas
- main/printers/thermal.ts[5037-5113]
- main/printers/thermal.ts[5122-5155]
## Recommended Fix
Resolve hostnames at dispatch, validate the selected resolved address against the restricted destinations, and connect to that validated address rather than resolving the hostname again inside `connect`. Preserve supported hostnames and address families.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


6. Failed spool writes leave receipt files ✓ Resolved

Resolving commit: 6010612

Resolution reason
Spool files are now created via openSync with 'wx' and tmpFileCreated is set right after creation,
before the write. The write goes through the file descriptor and is closed in a finally block, so if
writeFileSync fails the outer cleanup sees tmpFileCreated=true and unlinks the partially written
file. Applied to both printViaCups and printViaUSBWindows.
Description
printViaCups and printViaUSBWindows set tmpFileCreated only after writeFileSync returns
successfully. If an exclusive write creates the file but then fails, such as when the disk fills
mid-write, both finally blocks skip unlinking the partially written receipt file.

7. Cut-off credentials escape redaction ✓ Resolved

Resolving commit: 6010612

Resolution reason
Both boundaries now sanitize before the byte cap: in main/ipc.ts sanitizeLogTail(filteredText) runs
before Buffer slicing, and in main/routes/support-ticket.ts sanitizeLogTail(body.log_tail) runs on
the full text before subarray(-LOG_TAIL_MAX_BYTES). A new test uses a password crossing the 200KB
boundary and asserts it is redacted. The fix reorders sanitize-then-cap rather than
cap-then-sanitize, and does not drop a partial leading line as the prompt suggests, but it addresses
the credential-fragment leakage the finding describes. Regex hardening (word boundaries, lookahead
for [REDACTED]) and extra key names also reduce the fragment risk.
Description
get-log-tail and submitTicketHandler take the last 200,000 raw bytes before calling
sanitizeLogTail, whose patterns need a complete credential prefix. If that cut removes a field
name, Authorization: Bearer, or a JWT’s eyJ prefix while retaining its value, the support-ticket
path can queue the unredacted fragment for upload; a JWT payload.signature fragment may be
reconstructable into a usable token.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #12
  🌐 PR #8
  🌐 PR #39
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
  Explored: repo: FreeOpenSourcePOS/FloAdmin (sha: 8a02fb6f) — View relationship
  Explored: repo: FreeOpenSourcePOS/docs.flopos.com (sha: abe7cff3) — View relationship
✅ REVIEW.md
Review mode: Auto: 🧠 Deep: Security-sensitive, 86 hunks across many independent subsystems: WebSocket admission, printer SSRF, redaction, spool files.

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/window-options.ts Resolved
Comment thread main/printers/thermal.ts Resolved
Comment thread main/lib/log-sanitizer.ts Resolved
Comment thread main/routes/support-ticket.ts Resolved
Comment thread main/printers/thermal.ts Resolved
Comment thread main/printers/thermal.ts Resolved
Comment thread main/lib/log-sanitizer.ts Resolved
…n/printers/thermal.ts` (and audited all sibling string-parsing sites introduced in this PR): 1. **Invariant**: All string normalization and redaction on untrusted/user-provided inputs must execute in linear time $O(n)$ without polynomial regex backtracking. 2. **Fixes**: - [`validateNetworkPrinterTarget`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M6WSBE3T8M3N1EPPT13YJSBN/main/printers/thermal.ts#L5039-L5058): Replaced `.replace(/\.+$/, '')` with a backward index scan trimming trailing dots in $O(n)$ time and rejecting dot-only hostnames. - [`expandPrinterIpv6Groups`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M6WSBE3T8M3N1EPPT13YJSBN/main/printers/thermal.ts#L4982-L4993): Replaced `/^(.*:)(\d{1,3}(?:\.\d{1,3}){3})$/` with `lastIndexOf(':')` and explicit octet splitting to avoid greedy prefix backtracking. - [`sanitizeLogTail`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M6WSBE3T8M3N1EPPT13YJSBN/main/lib/log-sanitizer.ts#L1-L21): Anchored `AUTH_HEADER_RE` and `QUOTED_KEY_VALUE_RE` with word boundaries and removed overlapping `\s*["']?\s*` quantifiers. - [`tests/printer-api.test.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M6WSBE3T8M3N1EPPT13YJSBN/tests/printer-api.test.ts#L862-L877): Added regression cases for trailing-dot FQDNs (`metadata.google.internal.`, `localhost.`) and dot-only hostnames (`...`). 3. **Verification**: `npm run lint`, `npm run build`, `npx tsx tests/printer-api.test.ts`, `npx tsx tests/support-ticket.test.ts`, `npx tsx tests/update-ipc-sender-validation.test.ts`, and `git diff --check` all passed
@khaira777 khaira777 changed the title fix: harden KDS WebSocket admission, printer targets, and desktop boundaries fix: harden KDS WebSocket admission, printer targets, and desktop runtime boundaries Nov 8, 2026
@khaira777
khaira777 merged commit e8454c6 into main Nov 8, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-sec-batch3-kds-printers-hardening branch November 8, 2026 17:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants