Skip to content

fix(main): harden IPC, telemetry & restore token - #1316

Merged
khaira777 merged 9 commits into
mainfrom
fm/ship-c7755f35-ipc-telemetry-schema-restore
Oct 22, 2026
Merged

khaira777 merged 9 commits into
mainfrom
fm/ship-c7755f35-ipc-telemetry-schema-restore

Conversation

@khaira777

@khaira777 khaira777 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1296

Intent

Fix the double-verified backend security, crash-safety, schema-health caching, and restore-token defects from the architecture audit (c7755f35, GitHub Issue #1296):

  1. main/ipc.ts:208-213: handle() validates isTrustedSender(event.senderFrame) instead of isTrustedMainWindowSender(event), allowing secondary Electron windows (customer display, print preview) to invoke privileged main-window IPC handlers. Enforce isTrustedMainWindowSender(event) in handle().
  2. main/services/telemetry.ts:144, 153, 186 & main/services/posthog.ts:132-139: telemetry.ts calls raw app.getVersion() instead of electronApp()?.getVersion() ?? '0.0.0' in sendEvent, sendCrashReport, and trackEvent; posthog.ts runs an uncached synchronous SQLite query SELECT value FROM settings WHERE key = 'analytics_consent_level' on every captureEvent call when consent is 'full'.
  3. main/services/schema-health.ts:292: runHealthCheck() rebuilds buildIdealSchemaDb() (~55ms synchronous in-memory 117-migration build) on every /api/health/detailed call instead of caching the ideal schema metadata once per process.
  4. main/routes/database.ts:794-807 & main/services/restore-file-selection.ts:34: POST /api/db/restore consumes the single-use selection_token before getSchemaVersionFromBackup(resolvedPath) runs, forcing the user to reopen the native file dialog if they first picked an invalid backup file.
  5. main/services/kds.ts:682-690: buildActiveOrdersSnapshot calls orders.find(...) 3 times per item inside allItems.map(...) (O(N * M)) instead of indexing orders in a Map (O(N + M)).

What Changed

  • Enforce isTrustedMainWindowSender in the main/ipc.ts handle() wrapper so privileged IPC handlers require the active main BrowserWindow, top-level mainFrame, and local server port, and validate the restore selection_token with peekRestoreFileSelection before consuming it in POST /api/db/restore after file-existence and backup schema-version checks pass.
  • Replace raw app.getVersion() and app.isPackaged accesses in main/services/telemetry.ts with electronApp() guards, and cache PostHog consent, identity, and diagnostics state in main/services/posthog.ts for up to 30 seconds with immediate invalidation on settings and users table mutations via getSettingsRevision() and SQLite temp triggers in main/db.ts.
  • Cache the in-memory ideal DbSchemaSnapshot in main/services/schema-health.ts across runHealthCheck() calls keyed by migration registry identity, and index orders in a Map in main/services/kds.ts (buildActiveOrdersSnapshot) to avoid repeated linear orders.find lookups per item.

Risk Assessment

✅ Low: The changes cleanly enforce main-window IPC sender validation, guard telemetry Electron app access, cache PostHog consent and ideal schema snapshots with revision-based invalidation, preserve restore selection tokens across pre-validation failures, and index active KDS orders in a Map, with comprehensive behavioral test coverage.

Testing

Built the backend and drove all seven happy-path and adversarial scenarios live against a real Electron 44.9.0 process with main and secondary BrowserWindows, the Express HTTP/KDS server on an isolated port, and a disposable SQLite database, capturing a rendered window screenshot and JSON verification report alongside passing targeted test suites for IPC hardening, telemetry/PostHog caching, schema health, backup/restore tokens, KDS contracts, and script coverage.

  • Live validation: ✅ go - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Active main POS BrowserWindow invokes privileged IPC handlers (get-app-info, db-health-check, get-settings, master-pin-status) via preload bridge and receives valid payloads ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-electron-verification.…
Adversarial secondary BrowserWindow on the same localhost:13001 origin invokes privileged IPC handlers (get-app-info, db-health-check, get-settings, pick-restore-file, backup-database) and is rejected… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-electron-verification.…
Headless/non-Electron Node process executes telemetry.isTelemetrySuppressed, sendEvent, and sendAnonymousDiagnosticReport without Electron app object and falls back to app_version '0.0.0' without thro… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; npm run test:telemetry-install-provenance; npm run test:telemetry
Warm PostHog usage and exception captures with full analytics consent perform 0 synchronous SQLite queries, while a direct SQLite settings update fires the revision trigger and invalidates the consent… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; node tests/run-electron-node-test.cjs tests/posthog-client.test.ts
Repeated schema health checks via IPC db-health-check and GET /api/db-tools/health-check build the in-memory ideal schema once per process (0 :memory: DB opens on warm calls) while detecting and repai… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; npm run test:schema-health
POST /api/db/restore preserves the single-use selection_token across failed pre-validation (400 invalid backup and 404 missing file), succeeds (200) when retried with the same token after placing a va… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; node tests/run-electron-node-test.cjs tests/restore-from-file-api.test.ts; node tests/run-electron…
KDS active orders snapshot (buildActiveOrdersSnapshot and GET /api/kds/display) returns all station-routed orders and items while indexing orders in a Map with 0 calls to orders.find ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; npm run test:kds-contract

Live Electron main and secondary window verification screenshot

Evidence: Live Electron and Express end-to-end verification report JSON

{ "timestamp": "2026-10-22T21:50:01.424Z", "serverPort": 13001, "scenarios": { "ipcSenderEnforcement": { "mainWindow": { "origin": "http://localhost:13001",
"appInfo": { "version": "44.9.0", "name": "Electron", "electron": "44.9.0", "node": "24.22.0", "platform": "darwin" }, "healthSummary": { "safeCount": 0, "manualReviewCount": 0 }, "settingsCount": 85, "pinStatus": { "available": true, "isSet": false } }, "secondaryWindow": { "origin": "http://localhost:13001",
"appInfo": { "error": "Unauthorized sender" }, "health": { "error": "Unauthorized sender" }, "settings": { "error": "Unauthorized sender" }, "pickRestore": { "error": "Unauthorized sender" }, "backup": { "error": "Unauthorized sender" } } }, "telemetryAndPostHog": { "headlessTelemetry": { "sentPing": true, "sentDiagDisposition": "accepted", "pingAppVersion": "0.0.0", "diagAppVersion": "0.0.0" }, "postHogCache": { "warmPrepareCountAcross20Captures": 0, "revisionBeforeDirectSqlUpdate": 141, "revisionAfterDirectSqlUpdate": 142, "prepareCallsOnNextCaptureAfterTrigger": 8, "collectorRequestsReceived": 1 } }, "schemaHealthCaching": { "totalMemoryDbBuildsAcrossProcess": 1, "memoryDbOpensDuringSubsequentChecks": 0, "detectedFinding": "missing_table:held_orders", "appliedFixes": ["missing_table:held_orders"], "findingsAfterFix": 0 }, "restoreSelectionToken": { "attempt1InvalidBackup": { "status": 400, "error": "Invalid backup file: missing schema version metadata. This backup may have been created with an older version of Flo." }, "attempt2MissingBackup": { "status": 404, "error": "Backup file no longer exists" }, "attempt3RetrySameTokenWithValidBackup": { "status": 200, "body": { "success": true, "mode": "direct", "backupVersion": 116, "currentVersion": 116, "tablesRestored": 66, "cleanupPending": false }, "transientCategoryRemoved": true }, "attempt4ReplayConsumedToken": { "status": 400, "error": "Choose a backup file in the restore dialog before confirming" } }, "kdsSnapshotMapIndexing": { "stationId": "station-bar", "activeOrdersReturned": 5, "httpDisplayOrdersReturned": 5, "orderNumbers": ["KDS-101", "KDS-102", "KDS-103", "KDS-104", "KDS-105"], "orderArrayFindCalls": 0 } } }

{
  "timestamp": "2026-10-22T21:50:01.424Z",
  "serverPort": 13001,
  "scenarios": {
    "ipcSenderEnforcement": {
      "mainWindow": {
        "origin": "http://localhost:13001",
        "appInfo": {
          "version": "44.9.0",
          "name": "Electron",
          "electron": "44.9.0",
          "node": "24.22.0",
          "platform": "darwin"
        },
        "healthSummary": {
          "safeCount": 0,
          "manualReviewCount": 0
        },
        "settingsCount": 85,
        "pinStatus": {
          "available": true,
          "isSet": false
        }
      },
      "secondaryWindow": {
        "origin": "http://localhost:13001",
        "appInfo": {
          "error": "Unauthorized sender"
        },
        "health": {
          "error": "Unauthorized sender"
        },
        "settings": {
          "error": "Unauthorized sender"
        },
        "pickRestore": {
          "error": "Unauthorized sender"
        },
        "backup": {
          "error": "Unauthorized sender"
        }
      }
    },
    "telemetryAndPostHog": {
      "headlessTelemetry": {
        "sentPing": true,
        "sentDiagDisposition": "accepted",
        "pingAppVersion": "0.0.0",
        "diagAppVersion": "0.0.0"
      },
      "postHogCache": {
        "warmPrepareCountAcross20Captures": 0,
        "revisionBeforeDirectSqlUpdate": 141,
        "revisionAfterDirectSqlUpdate": 142,
        "prepareCallsOnNextCaptureAfterTrigger": 8,
        "collectorRequestsReceived": 1
      }
    },
    "schemaHealthCaching": {
      "totalMemoryDbBuildsAcrossProcess": 1,
      "memoryDbOpensDuringSubsequentChecks": 0,
      "detectedFinding": "missing_table:held_orders",
      "appliedFixes": [
        "missing_table:held_orders"
      ],
      "findingsAfterFix": 0
    },
    "restoreSelectionToken": {
      "attempt1InvalidBackup": {
        "status": 400,
        "error": "Invalid backup file: missing schema version metadata. This backup may have been created with an older version of Flo."
      },
      "attempt2MissingBackup": {
        "status": 404,
        "error": "Backup file no longer exists"
      },
      "attempt3RetrySameTokenWithValidBackup": {
        "status": 200,
        "body": {
          "success": true,
          "mode": "direct",
          "backupVersion": 116,
          "currentVersion": 116,
          "tablesRestored": 66,
          "cleanupPending": false
        },
        "transientCategoryRemoved": true
      },
      "attempt4ReplayConsumedToken": {
        "status": 400,
        "error": "Choose a backup file in the restore dialog before confirming"
      }
    },
    "kdsSnapshotMapIndexing": {
      "stationId": "station-bar",
      "activeOrdersReturned": 5,
      "httpDisplayOrdersReturned": 5,
      "orderNumbers": [
        "KDS-101",
        "KDS-102",
        "KDS-103",
        "KDS-104",
        "KDS-105"
      ],
      "orderArrayFindCalls": 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 - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Active main POS BrowserWindow invokes privileged IPC handlers (get-app-info, db-health-check, get-settings, master-pin-status) via preload bridge and receives valid payloads ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-electron-verification.…
Adversarial secondary BrowserWindow on the same localhost:13001 origin invokes privileged IPC handlers (get-app-info, db-health-check, get-settings, pick-restore-file, backup-database) and is rejected… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-electron-verification.…
Headless/non-Electron Node process executes telemetry.isTelemetrySuppressed, sendEvent, and sendAnonymousDiagnosticReport without Electron app object and falls back to app_version '0.0.0' without thro… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; npm run test:telemetry-install-provenance; npm run test:telemetry
Warm PostHog usage and exception captures with full analytics consent perform 0 synchronous SQLite queries, while a direct SQLite settings update fires the revision trigger and invalidates the consent… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; node tests/run-electron-node-test.cjs tests/posthog-client.test.ts
Repeated schema health checks via IPC db-health-check and GET /api/db-tools/health-check build the in-memory ideal schema once per process (0 :memory: DB opens on warm calls) while detecting and repai… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; npm run test:schema-health
POST /api/db/restore preserves the single-use selection_token across failed pre-validation (400 invalid backup and 404 missing file), succeeds (200) when retried with the same token after placing a va… ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; node tests/run-electron-node-test.cjs tests/restore-from-file-api.test.ts; node tests/run-electron…
KDS active orders snapshot (buildActiveOrdersSnapshot and GET /api/kds/display) returns all station-routed orders and items while indexing orders in a Map with 0 calls to orders.find ✅ pass live ~/.no-mistakes/evidence/01M5JRP143CCKA3B8FHS8K8KMT/live-verification-report.json; npm run test:kds-contract
  • npm run build
  • NODE_PATH="$(pwd)/node_modules" ./node_modules/.bin/electron --no-sandbox /tmp/flo-live-verify-01M5JRP143CCKA3B8FHS8K8KMT.cjs
  • npm run test:kds-window-hardening
  • npm run test:printer-ipc
  • npm run test:orders-layout-settings
  • npm run test:theme-mode-settings
  • node tests/run-electron-node-test.cjs tests/restore-managed-path.test.ts
  • node tests/run-electron-node-test.cjs tests/restore-from-file-api.test.ts
  • node tests/run-electron-node-test.cjs tests/posthog-client.test.ts
  • npm run test:telemetry-install-provenance
  • npm run test:schema-health
  • npm run test:kds-contract
  • npm run test:telemetry
  • npm run test:backup
  • npm run test:script-coverage
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 22, 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

Comment @coderabbitai help to get the list of available commands.

@khaira777 khaira777 changed the title fix(main): harden IPC sender check, schema/telemetry caching, and restore token fix(main): harden IPC, telemetry & restore token Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@greptile-apps

greptile-apps Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: apex

[Medium impact] The PR affects several bounded backend workflows in the desktop app.

Fix the database startup failure before merging so a missing users table does not block recovery tools.

Findings

  1. P1 Missing table blocks recovery ▶

Summary

This PR tightens main-window IPC checks, makes telemetry safe without Electron, caches PostHog policy and ideal schema data, preserves restore tokens through file pre-validation, and replaces repeated KDS order searches with a Map.

  • Privileged IPC channels accept calls only from the active main window.
  • Restore tokens remain available until the selected backup passes validation.
  • Telemetry uses safe version lookups and reuses its consent and identity state.
  • Schema health checks reuse the expected schema snapshot.
  • KDS snapshots look up each item’s order through an ID map.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  W["Settings or users change"] --> R["Revision increases"]
  R --> C{"Cached PostHog state still valid?"}
  E["Environment changes or cache expires"] --> C
  C -->|No| D["Read consent, identity and configuration"]
  C -->|Yes| U["Reuse cached state"]
  D --> G["Check consent and scrub events"]
  U --> G
Loading

Reviews (1) · Last reviewed commit: "no-mistakes(document): Format PostHog cl..." · Reviewed by Greptile

Comment thread main/db.ts Resolved
Fixes #1296

- Enforce isTrustedMainWindowSender(event) in main/ipc.ts handle() so secondary Electron windows cannot invoke privileged main-window IPC handlers.
- Guard app.getVersion() / app.isPackaged in main/services/telemetry.ts via electronApp() and cache resolved analytics consent level and identity in main/services/posthog.ts with settings revision invalidation.
- Cache the ideal schema inspection snapshot in main/services/schema-health.ts once per process (closing the temporary in-memory DB immediately) and invalidate if MIGRATIONS identity changes.
- Peek and validate backup file existence and schema version before consuming the single-use selection_token in POST /api/db/restore.
- Index active KDS orders by ID in a Map in buildActiveOrdersSnapshot instead of calling orders.find per item.
@khaira777
khaira777 force-pushed the fm/ship-c7755f35-ipc-telemetry-schema-restore branch from 82237a0 to b9ac11a Compare October 22, 2026 21:55
@khaira777 khaira777 changed the title fix(main): harden IPC, telemetry & restore token fix(main): harden IPC sender validation, telemetry, schema caching, and restore tokens Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Greptile has paused reviews on this repository — it used its 750 free open-source review credits for this billing period. Reviews resume automatically on November 2. To continue before then, an organization admin can keep reviews running past the free credits — those bill as normal usage.

@khaira777 khaira777 changed the title fix(main): harden IPC sender validation, telemetry, schema caching, and restore tokens fix(main): harden IPC, telemetry & restore token Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@khaira777
khaira777 merged commit 7fdb09b into main Oct 22, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/ship-c7755f35-ipc-telemetry-schema-restore branch October 22, 2026 22:42
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.

fix(main): harden IPC main-window check, telemetry Electron guard, schema-health cache, and restore token

1 participant