Skip to content

security: harden database restore, authentication, and KDS boundaries - #217

Merged
khaira777 merged 76 commits into
mainfrom
chore/code-review-aug-2026
Aug 9, 2026
Merged

khaira777 merged 76 commits into
mainfrom
chore/code-review-aug-2026

Conversation

@khaira777

@khaira777 khaira777 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Security hardening: restore, authentication, authorization, and targeted KDS boundaries

Review status

Ready for maintainer review. This PR is open and must not be merged or released until normal CI and maintainer review complete. No production/customer data, credentials, or private repositories were used.

  • Base: main
  • Head: d6f71b9 (chore/code-review-aug-2026)
  • Scope: S2, S3, S4, and the targeted high-risk S8 KDS slice
  • Out of scope: all remaining sectors and the full S8 OCR pass; those will use separate branches and PRs.

The changes in this PR are security, integrity, privacy, recovery, and compatibility hardening for the reviewed surfaces. No unrelated product behavior or new sector work is being added here.

Scope and findings addressed

Database restore, import, backup, and maintenance

Finding: Restore/import behavior had integrity, cleanup, concurrency, compatibility, and authentication-state risks. These were reproduced or proven with temporary fixtures.

Remediation:

  • Added integrity, foreign-key, schema-version, table/column, metadata, and exact schema-object validation.
  • Added commit-aware prepared/committed restore/reset journals, durable file/directory synchronization, startup recovery, stale-journal cleanup, sidecar/symlink checks, and protected custom backup-target staging.
  • Materialized restore sources through no-follow descriptors, pinned opened file identity, rechecked size/mtime after reading, and rejected live targets and SQLite sidecars.
  • Preserved pre-existing legacy foreign-key violations while rejecting newly introduced violations during data-only restore.
  • Recovery journals record the legacy foreign-key baseline. Prepared/committed recovery accepts only that baseline, so a dirty legacy installation is not bricked while new corruption remains rejected.
  • Committed recovery finalizes a healthy live database before requiring the old recovery snapshot, allowing safe startup when the committed snapshot is missing or stale.
  • Added FIFO database-maintenance locking, synchronous request reservation, IPC gating, maintenance start/end listeners, and Cloud Sync pause/resume coordination.
  • Preserved current users, credentials, roles, active state, token epochs, station assignments, station security, KDS state, revocations, protected settings, and pending outboxes across restore/import.
  • Invalidated pairing tokens and redacted cloud, support-ticket, and diagnostics outboxes from exports/imports.

Authentication and session lifecycle

Finding: Logout revocation was process-local, and stale REST/WebSocket work could retain or restore old session state after deactivation, revocation, password/PIN changes, restore, or maintenance.

Remediation:

  • Added durable hashed token revocations, JWT IDs, expiry-aware cleanup, restore-preserved security state, and token-epoch handling.
  • Added socket/session-generation guards, narrow invalid-session token removal, inactive-station login rejection, idempotent logout, and setup failure recovery.
  • Rechecked token revocation and staleness inside KDS mutation transactions to close middleware-to-write races.
  • Preserved the documented orphaned-owner recovery behavior: staff promotion through /api/auth/recover-password when no owner exists remains an accepted design decision.

KDS authorization, consistency, and privacy

Finding: KDS surfaces did not consistently re-check current role/category/station/session state. Restricted users could receive financial, customer, add-on-price, printer, or network metadata. Stale clients could overwrite terminal or concurrently changed statuses.

Remediation:

  • Applied current role, activity, category, station-assignment, station-category, token-revocation, and token-staleness checks to embedded REST, kitchen REST, standalone REST, WebSocket snapshots/counts, and mutations.
  • Revalidated embedded and standalone mutation authorization inside immediate write transactions.
  • Added compare-and-set status transitions with expected_status and 409 conflicts across embedded REST, order-item REST, standalone REST, WebSocket, and frontend mutation paths.
  • Added restricted projections, terminal-line guards, void handling, inactive-station fail-closed behavior, sticky permission refresh, station-category change detection, and stale-response invalidation.
  • Added disabled-KDS cleanup/reconnect handling, snapshot coalescing, slow-socket backpressure protection, and REST/WebSocket counts parity.
  • Invalidated pairing tokens on disablement/restore and kept KDS disablement as temporary availability state rather than credential failure.

Station routing and broadcast correctness

Finding: Tableless orders disappeared from station views. Category fallback could duplicate explicitly table-assigned orders across stations. Global broadcast suppression could drop distinct rapid updates, and periodic full snapshots were unnecessarily expensive.

Remediation:

  • Category fallback now applies only to tableless orders; explicit station assignment takes precedence.
  • Persisted station_assignments_configured in migration v56 so removing the final assignment remains fail-closed instead of being interpreted as unrestricted access.
  • Removed lossy suppression and adjacent duplicate notifications, made heartbeat refreshes event-driven, and added tableless/no-duplicate regression assertions.

Cloud Sync deletion and privacy lifecycle

Finding: Cloud deletion could race enqueue, registration, heartbeat, polling, relay, email, diagnostics, support, pairing, cancellation, settings reload, response processing, and restart recovery. Remote deletion could also be accepted before local disabled state was durable.

Remediation:

  • Persisted disabled/pending deletion intent and cleared all three outboxes before issuing the remote purge.
  • Tracked and drained in-flight cloud response bodies, including non-2xx and no-body paths, before the purge request can proceed.
  • Fenced registration, auto-registration retries, settings reload, connection tests, email, diagnostics, pairing, command polling/results, relay reconnects/frames, heartbeats, outbox flushes, support tickets, and post-response settings mutations.
  • Recorded deletion outcome (unknown, rejected, or final status), blocked unresolved deletion states from re-enabling Cloud Sync, and preserved a safe retry/cancel path.
  • Cleared API/device/request credentials for approved, completed, and deleted outcomes; cancellation clears stale request identifiers and tokens.
  • Failed or ambiguous deletion leaves cloud services disconnected and disabled rather than silently resuming with old credentials.

Compatibility and behavior decisions

  • Pre-existing legacy foreign-key violations are preserved for upgraded installations; newly introduced violations are rejected.
  • KDS disablement is temporary availability state; credentials remain valid when KDS is re-enabled.
  • Restricted projections are access-based: station-only chefs receive redacted payloads even without category restrictions.
  • Cloud deletion is intentionally conservative: unresolved or ambiguous deletion state blocks automatic restart, registration, and settings-based re-enable until the deletion is retried, cancelled, or resolved.
  • No unrelated sector behavior is intentionally changed in this PR.

Verification evidence

Passed on the current head or isolated equivalent environment:

  • npm run build
  • npm run lint — 0 errors; existing warnings remain
  • git diff --check
  • PORT=3011 KDS_PORT=3012 npm test — full suite passed in an isolated port environment
  • npm run test:recovery-cloud
    • Legacy FK committed/prepared recovery
    • Missing committed recovery snapshot finalization
    • Failed/ambiguous Cloud deletion and safe retry state
  • Production backup/restore tests
  • Database-tools API: 33/33
  • Database maintenance-lock tests
  • Setup failure recovery
  • JWT/logout lifecycle tests
  • KDS contract, integration, and WebSocket revalidation tests
  • Focused authorization, routing, restore, migration, and outbox tests

The default-port full-suite attempt encountered an already-running local Electron process; rerunning with isolated PORT=3011 KDS_PORT=3012 completed successfully. No process was terminated.

Commit-by-commit audit trail

Each commit is intentionally small enough to explain and review independently:

  • 8b46d67 — Hardened database restore and maintenance locking.
  • ccbf2ad — Added durable KDS session/logout foundations.
  • 12ecfe1 — Closed early restore and logout gaps.
  • 59b3cc6 — Invalidated stale KDS/import sessions.
  • f14e625 — Tightened cache/import safety.
  • a9423c3 — Closed session and migration gaps.
  • 4eaf21c — Added frontend async/session-generation guards.
  • e38fe4a — Enforced category-scoped kitchen access.
  • 9df3e8a — Applied category authorization consistently across KDS paths.
  • b71c33c — Hardened KDS payloads and mutations.
  • accbda2 — Added restricted item/station projections.
  • f51369b — Closed remaining KDS session/privacy and station/category gaps.
  • 02c0bde — Propagated station assignments and protected terminal items.
  • a024936 — Preserved restore authentication state and display-only fields.
  • 6efc6bf — Reinserted current-only users and hardened fallback behavior.
  • 553fba3 — Aligned station-filtered counts and REST fallback behavior.
  • da3d7da — Added station/category routing for tableless orders.
  • ec909e8 — Reduced redundant periodic KDS refreshes.
  • b5f0149 — Closed routing, inactive-station, restore-FK, and REST 403 gaps.
  • b5dac02 — Tightened final KDS auth failures and restore/FK identity handling.
  • 8f9f4a4 — Merged the latest origin/main into the review branch.
  • 08f03ca — Made KDS routing/broadcasts lossless and strengthened restore schema checks.
  • 139f6aa — Removed unused KDS notifier imports.
  • 9c08b50 — Closed standalone terminal races and filtered station-scoped responses.
  • 22439be — Added active-request maintenance gating and exact schema-object validation.
  • f2458a0 — Coordinated KDS WebSocket activity with maintenance.
  • 6d83ff5 — Closed maintenance clients immediately and normalized ownership.
  • a820aa2 — Removed the final unused WebSocket import.
  • d68c10b — Reconnected KDS automatically after maintenance.
  • 024ee7e — Added prepared/committed journals, outbox recovery, KDS CAS, counts parity, pairing-token invalidation, backpressure protection, and broadcast coalescing.
  • 9a61a0d — Closed recovery/outbox edge cases and serialized Cloud Sync database sections.
  • 1bcee0b — Hardened journal path/schema validation, stale cleanup, reset durability, and current-outbox preservation.
  • 874fee2 — Added recovery symlink, journal-name, schema, and durable-directory checks.
  • b0cb907 — Added canonical metadata/header checks, critical-table validation, and custom-target protection.
  • 3210cb2 — Re-read live KDS ACLs and strengthened migration-derived recovery validation.
  • 3280927 — Closed live-DB sidecar aliases, dangling-journal ordering, strict import schema parsing, and relay maintenance gating.
  • d3677a5 — Closed standalone assignment-removal fail-open and dangling-sidecar cleanup gaps.
  • 4341411 — Added active event-flush waiting, migration-derived recovery schema generation, and canonical metadata/header checks.
  • fd8c007 — Closed support/diagnostics flush waiting, malformed station-category fail-open handling, migration-derived schema/FK validation, and journal cleanup gaps.
  • f055382 — Persisted station-assignment scope and preserved it through restore.
  • 5799074 — Made migration v56 idempotent for upgrade-path simulations.
  • a606d2a — Fenced Cloud Sync deletion, restore sources, standalone ACL revalidation, and durable pre-migration backups.
  • ea56ceb — Closed Cloud Sync reload, registration, heartbeat, polling, and flush race windows.
  • 4d28bb5 — Added tracked cloud-operation draining and no-follow restore-source materialization.
  • 1c90935 — Added response-body lifetime fencing and transactional embedded KDS ACL revalidation.
  • 1d1d7e0 — Drained cloud error responses and rechecked standalone KDS roles.
  • 8dcfa01 — Closed auto-registration retry and late error-continuation races.
  • 0081a82 — Revalidated restore-source identity, size, mtime, and post-read sidecars.
  • ef2e5ad — Hardened deletion lifecycle state and token staleness checks.
  • cbd2d62 — Rechecked KDS token validity during mutation.
  • d3b2e43 — Persisted deletion intent before the remote purge.
  • 89d7ea1 — Added legacy-FK recovery and Cloud deletion regression coverage.
  • be18da7 — Added exact legacy-FK baselines, unresolved-deletion blocking, deletion outcomes, settings re-enable guards, and expanded ambiguous-deletion tests.
  • 4fe186c — Validated deletion statuses and tracking details, staged restore sources in OS temp space, refreshed KDS state after every CAS conflict, rejected concurrent maintenance routes before auth/DB access, and added focused regression coverage.

Sector status and follow-up work

Sector Status
S1 Electron/runtime/IPC Pending — separate PR
S2 Authentication/authorization Complete in this PR
S3 API/network boundaries Complete in this PR
S4 Database/backups/migrations Complete in this PR
S5 Products/categories/imports/inventory Pending — separate PR
S6 Orders/checkout/payments/loyalty Pending — separate PR
S7 Tax/financial calculations Pending; requires domain validation and separate PR
S8 KDS/kitchen Targeted high-risk slice complete; full OCR pass separate PR
S9 Printing/receipts Pending — separate PR
S10 Integrations/data egress Pending — separate PR
S11 Frontend/accessibility Pending — separate PR
S12 Release/supply chain/scripts/tests Pending — separate PR

Future sector work starts from the latest origin/main on a new chore/audit-sXX-<name> branch. No additional sector findings or unrelated fixes should be added to this PR.

Latest focused follow-up

The latest review claims were verified before implementation. Cloud deletion now accepts only known statuses and requires effective tracking identifiers for non-final states; malformed/unknown responses become blocked, retryable local failures. Restore staging no longer requires write access beside the selected backup. KDS refreshes REST state after every 409, including active WebSocket sessions. Concurrent maintenance requests receive 503 before later authentication or route middleware.

Focused checks passed: build, cloud/recovery regression tests, read-only-source production restore, maintenance-lock concurrency, KDS frontend conflict regression, KDS contract, and git diff --check.

Cloud deletion is explicitly included in this PR's reviewed scope because it protects restore/import privacy and deletion-state integrity. Broader integrations/data-egress work remains separate.

Merge-readiness after main drift

origin/main was merged into this branch in 517c25d, including the latest tax-configuration, support, frontend, printer, and documentation changes from main. The three textual conflicts in main/db.ts, main/routes/support-ticket.ts, and main/services/cloud-sync.ts were resolved by preserving both main's current behavior and this PR's restore/KDS/Cloud deletion hardening. No unrelated main changes were reverted. Commit d6f71b9 then fixed a pre-merge production deadlock in the maintenance middleware: lock-owning HTTP routes are excluded from the active-request count, and drain waiters are separate from requests queued behind maintenance.

Post-merge verification passed:

  • npm run build
  • npm run build:frontend
  • npm run lint — 0 errors; existing warnings remain
  • PORT=3011 KDS_PORT=3012 npm test
  • npm run test:backup
  • npm run test:recovery-cloud
  • database maintenance-lock production-stack regression, KDS integration, KDS contract, and frontend conflict regression tests
  • git diff --check

The worktree is clean and the branch is conflict-free with origin/main. Independent review also audited migrations and all 15 commits added to main in the prior three days. Pending follow-ups are tracked in #220. PR #217 remains open and ready for review; no merge or release action has been taken.

Maintainer handoff

This PR is finalized for review of the stated scope. Please review the structured remediation and verification evidence above, run CI on the current head, and merge only after normal maintainer approval. No merge, release, or production action has been taken by this change.

@khaira777

khaira777 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up review fixes are now pushed in commit 4fe186c.

Verified claims before implementing changes:

  • Cloud deletion now accepts only known statuses and requires effective request ID/status-token tracking for non-final states. Malformed or unknown responses become blocked, retryable local failures.
  • Restore staging now uses an application-owned OS temporary directory, so the selected backup directory only needs read access.
  • KDS refreshes REST state after every 409 CAS conflict, including while WebSocket mode is active.
  • Concurrent maintenance routes are rejected with 503 before later authentication or route middleware can access the database.

Added regression coverage for malformed/unknown deletion responses, legacy-FK recovery, read-only backup sources, maintenance-route concurrency, and WebSocket-active KDS conflict refresh. Focused build and tests pass. PR #217 remains ready for review; no merge or release action was taken.

@khaira777
khaira777 marked this pull request as ready for review August 6, 2026 04:39
@khaira777
khaira777 requested a review from itsbkm as a code owner August 6, 2026 04:39
…-2026

# Conflicts:
#	main/db.ts
#	main/routes/support-ticket.ts
#	main/services/cloud-sync.ts
Exclude lock-owning HTTP maintenance routes from the active-request counter so backup, import, download, and initialize handlers do not wait for their own responses. Keep a separate drain waiter queue so pre-existing requests still block maintenance without starving database requests queued behind an active maintenance operation. Add production-stack regression coverage for both the drain and route completion paths.
@khaira777
khaira777 merged commit 9cfb5f6 into main Aug 9, 2026
5 checks passed
khaira777 added a commit that referenced this pull request Aug 9, 2026
Fix Windows database durability flushing after the post-merge cross-platform matrix exposed an `EPERM` failure.

Root cause:
- `syncFile()` opened application-owned database, journal, and backup files with a read-only `r` handle.
- Windows rejects `fsyncSync()` on that handle during the pre-migration backup path.

Fix:
- Open those application-owned durability targets with `r+` before calling `fsyncSync()`.
- Preserve the existing fail-closed durability behavior and recovery guarantees.

Verification:
- `npm run build`
- `npm run test:backup`
- `npm run test:recovery-cloud`
- Electron smoke test
- All PR checks passed
- Manual Full Cross-Platform Matrix run `31291071323` passed on Windows, Ubuntu, macOS x64, and macOS ARM64

This is the single targeted follow-up to merged PR #217; no unrelated changes are included.
@khaira777
khaira777 deleted the chore/code-review-aug-2026 branch August 13, 2026 01:00
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.

1 participant