Skip to content

fix: rotate restored JWT & guard status window - #1431

Merged
khaira777 merged 7 commits into
mainfrom
fm/flocafe-restore-jwt-status-r1
Nov 3, 2026
Merged

khaira777 merged 7 commits into
mainfrom
fm/flocafe-restore-jwt-status-r1

Conversation

@khaira777

@khaira777 khaira777 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Resolve the three follow-up findings from the review of commit 26639fdf7e1646da0a82fac91dbb64ee66d9d5ea (PR #1425, tracked in #1427):

  1. Authoritative restore copies settings.jwt_secret (safe-storage:v1) from backups without rotating it, breaking sign-in when OS encryption is unavailable and reusing the target machine's existing key when available:
  • In main/db.ts (restoreBackup()), rotate settings.jwt_secret to a fresh 32-byte hex secret (crypto.randomBytes(32).toString('hex')) alongside updating users.tokens_valid_after, matching restoreCompatibleBackupForDowngrade().
  • Update tests/backup-restore-production.test.ts accordingly and verify that restoring a backup containing settings.jwt_[REDACTED]:v1' rotates settings.jwt_secret so getJWTSecret() works both with and without OS safeStorage.
  1. Failed or timed-out status-window load destroys the only open window during startup without suppressing window-all-closed:
  • During initialize() in main/index.ts, showStatus('starting') opens statusWindow before mainWindow is created. If window.loadURL(...) rejects or times out in openWindow() (main/status-window.ts), or a subsequent showStatus(...) call fails in executeJavaScript, closeStatus() destroys statusWindow. On Windows and Linux (process.platform !== 'darwin'), destroying the only open BrowserWindow fires window-all-closed (main/index.ts) and calls app.quit() mid-startup.
  • Guard window-all-closed / status-window closure during startup (runtimeState === 'starting') and failed/timed-out status-window loads so a status-window failure or close before mainWindow exists cannot quit the application on Windows or Linux.
  1. Unreachable dead code left in main/db.ts (dataOnlyRestore, readRevocations, mergeRevocations) and stale data-only copy in main/ipc.ts:
  • Remove the unreachable private dataOnlyRestore, readRevocations, and mergeRevocations functions (and RevocationRow if unused) in main/db.ts.
  • Update the restore-backup IPC handler in main/ipc.ts so its schema-version-mismatch dialog and completion result message reflect authoritative restore with forward migration rather than legacy data-only mode.

What Changed

  • Rotate settings.jwt_secret to a fresh 32-byte hex secret during restoreBackup() so restored databases do not inherit stale safe-storage:v1 values or reuse the prior signing key.
  • Suppress window-all-closed application termination while runtimeState === 'starting' and destroy/disable the status window when initial loadURL fails or times out so startup continues on Windows and Linux.
  • Remove unreachable legacy dataOnlyRestore and revocation-merging helpers from main/db.ts and update the restore-backup IPC handler and documentation to reflect authoritative restore with forward migration.

Risk Assessment

✅ Low: The changes cleanly rotate the JWT secret on authoritative backup restore, guard status-window failures and all-windows-closed events during startup, remove unreachable legacy data-only restore helpers, and remove the unused 'updating' status key cast from round 1 with matching test and documentation updates.

Testing

Ran the targeted backup/restore, JWT secret, status-messages, window-load-retry, and shutdown-lifecycle test suites, and drove the compiled Electron main-process modules live in isolated disposable environments to verify JWT secret rotation across restore with and without OS safeStorage, older-schema IPC restore dialog and result copy, and real Electron BrowserWindow startup status-window failure handling and screenshots. All checks and live scenarios passed.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Restoring a backup containing settings.jwt_secret = 'safe-storage:v1' when OS safeStorage is unavailable rotates settings.jwt_secret to a fresh 64-character hex secret and allows getJWTSecret() to sig… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/live-restore-and-ipc-verification.json and npm run test:backup (tests/backup-restore-production.test.ts)
Restoring a backup containing settings.jwt_secret = 'safe-storage:v1' when OS safeStorage is available and a pre-restore jwt-secret.enc exists rotates to a new secret instead of reusing the pre-restor… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/live-restore-and-ipc-verification.json and npm run test:backup (tests/backup-restore-production.test.ts)
When the startup status window fails or times out on loadURL or fails in executeJavaScript before mainWindow exists, the broken BrowserWindow is destroyed without showing, subsequent startup showStatu… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/status-window-starting.png, ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/status-window-closing.png, npm…
Restoring an older-schema managed backup over the restore-backup IPC handler prompts with forward-migration copy, runs an authoritative restore (mode: 'direct') migrating the schema to the current ver… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/live-restore-and-ipc-verification.json and npm run test:backup (tests/restore-managed-path.test.ts)

Live Electron startup status window ('starting')
Live Electron shutdown status window ('closing') after startup load-failure recovery

Evidence: Live restore JWT rotation and older-schema IPC restore verification

{ "jwtRotationWithoutSafeStorage": { "restoreSuccess": true, "mode": "direct", "rotatedSecretLength": 64, "rotatedSecretIsHex64": true, "jwtSignAndVerifySucceeded": true }, "jwtRotationWithSafeStorage": { "restoreSuccess": true, "mode": "direct", "rotatedSecretLength": 64, "rotatedSecretIsHex64": true, "differsFromPreRestoreEncFile": true, "persistedMarkerAfterRead": "safe-storage:v1" }, "ipcOlderSchemaRestore": { "response": { "success": true, "mode": "direct", "backupVersion": 123, "currentVersion": 124, "tablesRestored": 69, "message": "Database restored successfully", "cleanupPending": false }, "dialogTitle": "Schema Version Mismatch", "dialogMessage": "Backup was created with Schema v123", "dialogDetail": "Current database uses Schema v124.\n\nRestoring will replace the current database with this backup and migrate its schema to v124.\n\nDo you want to continue?" } }

{
  "jwtRotationWithoutSafeStorage": {
    "restoreSuccess": true,
    "mode": "direct",
    "rotatedSecretLength": 64,
    "rotatedSecretIsHex64": true,
    "jwtSignAndVerifySucceeded": true
  },
  "jwtRotationWithSafeStorage": {
    "restoreSuccess": true,
    "mode": "direct",
    "rotatedSecretLength": 64,
    "rotatedSecretIsHex64": true,
    "differsFromPreRestoreEncFile": true,
    "persistedMarkerAfterRead": "safe-storage:v1"
  },
  "ipcOlderSchemaRestore": {
    "response": {
      "success": true,
      "mode": "direct",
      "backupVersion": 123,
      "currentVersion": 124,
      "tablesRestored": 69,
      "message": "Database restored successfully",
      "cleanupPending": false
    },
    "dialogTitle": "Schema Version Mismatch",
    "dialogMessage": "Backup was created with Schema v123",
    "dialogDetail": "Current database uses Schema v124.\n\nRestoring will replace the current database with this backup and migrate its schema to v124.\n\nDo you want to continue?"
  }
}
- Outcome: 🔧 1 issue found → no changes applied ✅ across 2 runs (35m29s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed ✅
  • ⚠️ main/status-window.ts:96 - showStatus() checks (key as string) === 'updating' using a type cast to bypass the StatusKey union (main/status-messages.ts:1-9), which only defines 'starting' | 'checking' | 'backingUp' | 'services' | 'welcome' | 'closing' | 'shutdownBackup' | 'saved' and has no 'updating' key anywhere in the codebase. Neither the user intent nor any caller requires an 'updating' branch; recommend narrowing the reset condition to if (key === 'closing').

🔧 Fix applied.
✅ Re-checked - no issues remain.

🔧 **Test** - 1 issue found → no changes applied ✅
  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 284ms ago (193 observed); agent reported: antigravity parse events: context deadline exceeded. This is a budget or provider-slowness cut, not a code failure. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.

🔧 No changes applied.
✅ Re-checked - no issues remain.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Restoring a backup containing settings.jwt_secret = 'safe-storage:v1' when OS safeStorage is unavailable rotates settings.jwt_secret to a fresh 64-character hex secret and allows getJWTSecret() to sig… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/live-restore-and-ipc-verification.json and npm run test:backup (tests/backup-restore-production.test.ts)
Restoring a backup containing settings.jwt_secret = 'safe-storage:v1' when OS safeStorage is available and a pre-restore jwt-secret.enc exists rotates to a new secret instead of reusing the pre-restor… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/live-restore-and-ipc-verification.json and npm run test:backup (tests/backup-restore-production.test.ts)
When the startup status window fails or times out on loadURL or fails in executeJavaScript before mainWindow exists, the broken BrowserWindow is destroyed without showing, subsequent startup showStatu… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/status-window-starting.png, ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/status-window-closing.png, npm…
Restoring an older-schema managed backup over the restore-backup IPC handler prompts with forward-migration copy, runs an authoritative restore (mode: 'direct') migrating the schema to the current ver… ✅ pass live ~/.no-mistakes/evidence/01M6H8MAH5JWXEE2Z61HV6DXWM/live-restore-and-ipc-verification.json and npm run test:backup (tests/restore-managed-path.test.ts)
  • npm run test:backup
  • npm run test:shutdown-lifecycle
  • npm run test:status-messages
  • npm run test:window-load-retry
  • npm run test:jwt-secret-safe-storage
  • npm run test:jwt-secret-cache-identity
  • npm run test:jwt-secret-persist-before-cache
  • npm run test:newer-db-recovery
  • electron --no-sandbox <live-status-window-harness> (real Electron BrowserWindow rendering, loadURL rejection, window-all-closed suppression during startup, and 'closing' recovery with PNG screenshots)
  • ELECTRON_RUN_AS_NODE=1 electron -e <live-restore-and-ipc-harness> (compiled dist/main/db.js, dist/main/security/jwt-secret.js, and dist/main/ipc.js verification with safe-storage:v1 backups and older-schema IPC restore)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Fixes #1427

@coderabbitai

coderabbitai Bot commented Nov 3, 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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@khaira777

Copy link
Copy Markdown
Contributor Author

Working on inserting WhatsApp template placeholders at the current textarea cursor/selection position and restoring caret focus.

@FreeOpenSourcePOS FreeOpenSourcePOS deleted a comment from qodo-code-review Bot Nov 3, 2026
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Rotate JWT secrets on restore and protect startup from status-window failures

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Rotate JWT secrets during authoritative restore so backup credentials cannot break or compromise
 sign-in.
• Prevent failed status windows from appearing or quitting the app during startup.
• Remove unreachable restore code and align IPC messages, tests, and documentation with
 authoritative restore.
Diagram

graph TD
  IPC["Restore IPC"] --> Restore["Authoritative restore"] --> DB["Live database"] --> JWT["Rotated JWT secret"]
  Runtime["Startup runtime"] --> Status["Status window"] --> Load{"Load fails?"} -->|Yes: destroy| Quit["All-closed policy"]
  Runtime -->|Starting guard| Quit
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Scope quit suppression to status-window destruction
  • ➕ Limits suppression to closures initiated by status-window cleanup.
  • ➖ Requires every status-window closure path to use the suppression wrapper, including future paths.
  • ➖ Does not protect against the status window closing independently before the main window exists.

Recommendation: Keep the startup-state guard because it covers failed loads, update failures, and other last-window closures before the main window exists. Rotating the secret within authoritative restore is preferable to lazy recovery in the JWT reader: it prevents both an unavailable safe-storage marker and reuse of an existing machine secret.

Files changed (12) +398 / -417

Bug fix (5) +44 / -407
db.tsRotate restored JWT secrets and remove unreachable restore code +7/-371

Rotate restored JWT secrets and remove unreachable restore code

• Writes a fresh 32-byte hex JWT secret alongside session invalidation during authoritative restore. Removes the unused data-only restore implementation and its revocation helpers.

main/db.ts

index.tsKeep the app alive when all windows close during startup +7/-1

Keep the app alive when all windows close during startup

• Passes the starting runtime state to the all-windows-closed policy before deciding whether to quit.

main/index.ts

ipc.tsAlign restore confirmation and results with authoritative restore +5/-29

Align restore confirmation and results with authoritative restore

• Explains replacement and forward migration when confirming an older backup. Removes the duplicate version-mismatch response path and its stale data-only success message.

main/ipc.ts

status-window.tsDiscard status windows whose pages fail to load +19/-4

Discard status windows whose pages fail to load

• Treats rejected and timed-out loads as failures, destroys the affected window without showing it, and avoids recording display time when no window opened.

main/status-window.ts

window-recovery.tsAdd a startup guard to the window-closure policy +6/-2

Add a startup guard to the window-closure policy

• Extends the platform quit decision to suppress automatic quit while the runtime is starting, without changing the post-startup policy.

main/window-recovery.ts

Tests (4) +347 / -5
backup-restore-production.test.tsVerify JWT rotation across safe-storage states +96/-1

Verify JWT rotation across safe-storage states

• Checks that restore replaces existing and safe-storage-marker secrets with fresh hex values. Verifies authentication can read the rotated secret without OS encryption and migrates it into safe storage when available.

tests/backup-restore-production.test.ts

restore-managed-path.test.tsVerify older-backup IPC confirmation and result +50/-2

Verify older-backup IPC confirmation and result

• Restores a managed backup stamped with an older schema version and checks direct mode, the authoritative success message, and migration wording in the confirmation dialog.

tests/restore-managed-path.test.ts

shutdown-lifecycle.test.tsCover the startup all-windows-closed guard +11/-1

Cover the startup all-windows-closed guard

• Adds Windows and Linux assertions that closing every window does not request quit during startup while preserving the normal platform policy.

tests/shutdown-lifecycle.test.ts

status-messages.test.tsExercise status-window failure cleanup during startup +190/-1

Exercise status-window failure cleanup during startup

• Uses a fake BrowserWindow to test rejected loads, timed-out loads, and failed status updates. Verifies broken windows are destroyed without being shown or triggering a startup quit.

tests/status-messages.test.ts

Documentation (3) +7 / -5
data-and-migrations.mdDocument JWT rotation during restore +4/-3

Document JWT rotation during restore

• Adds JWT signing-secret rotation to the documented post-restore credential invalidation steps.

docs/architecture/data-and-migrations.md

runtime-and-lifecycle.mdDocument startup exception to the all-closed quit policy +2/-1

Document startup exception to the all-closed quit policy

• Clarifies that Windows and Linux do not quit on window-all-closed while the runtime is starting.

docs/architecture/runtime-and-lifecycle.md

api.mdCorrect the REST restore API description +1/-1

Correct the REST restore API description

• Replaces the obsolete data-only description with authoritative database replacement and forward migration for supported older backups.

docs/reference/api.md

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Slow status loads add up to ~8s to startup ✓ Resolved
Description
openWindow() now destroys the status window whenever loadURL takes longer than 2s, leaving
statusWindow null, so every later showStatus() call sees !isOpen() and builds a new window
with another 2s timeout. initialize() awaits showStatus('starting'), 'checking', 'backingUp'
and 'services' one after another, so on a slow machine (where the old code showed the window once
and moved on) startup now stalls up to about 8 seconds with no progress window shown.
Code

main/status-window.ts[R158-162]

+  if (!loaded) {
+    if (statusWindow === window) closeStatus();
+    else if (!window.isDestroyed()) window.destroy();
+    return;
+  }
Relevance

●●● Strong

Accepted timeout handling still causes repeated sequential delays; prior status-window review
prioritized bounded startup waits.

PR-#1425

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
After a timeout, closeStatus() sets statusWindow = null. showStatus then calls openWindow
again on its next call because !isOpen() && !opening, and each attempt waits up to 2000ms. Startup
awaits four of these calls in sequence before creating the main window. The old code raced load
against the timeout and still called window.show(), so later updates reused the same window and
only one 2s wait was ever paid.

main/status-window.ts[92-118]
main/status-window.ts[143-164]
main/index.ts[1569-1583]

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

## Issue description
`openWindow()` in main/status-window.ts destroys the status window when the load fails or exceeds 2s. Each later `showStatus()` call then creates a new window and waits another 2s. Startup awaits four status calls in sequence, so slow machines get up to ~8s of extra delay with no visible window.

## Fix Focus Areas
- main/status-window.ts[92-118]
- main/status-window.ts[143-164]

## Recommended Fix
Add a module-level flag (e.g. `statusUnavailable`) and set it in `openWindow()` when `loaded` is false. In `showStatus()`, return early when the flag is set, just like `isSuppressed()`. Reset the flag when shutdown begins, or reset it explicitly, so a shutdown window can still be tried once. Add a test in tests/status-messages.test.ts showing that a timed-out load makes later `showStatus` calls return immediately without creating a new BrowserWindow.

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


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #1425
  🌐 PR #39
  🌐 PR #10
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
✅ REVIEW.md
Review mode: Auto: 🧠 Deep: Security-sensitive restore and lifecycle changes span multiple independent code paths.

Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/status-window.ts Resolved
@khaira777 khaira777 changed the title fix: rotate JWT secret on restore and guard startup status window close fix(db): rotate JWT on restore & guard startup Nov 3, 2026
Rotate settings.jwt_secret to a fresh 32-byte hex secret during authoritative backup restore alongside updating users.tokens_valid_after so backups carrying safe-storage:v1 work both with and without OS safeStorage.

Guard window-all-closed while runtimeState is starting and destroy failed or timed-out status windows in openWindow() so status-window failures before mainWindow creation cannot quit the app on Windows or Linux.

Remove unreachable dataOnlyRestore, readRevocations, mergeRevocations, and RevocationRow from main/db.ts, and update the restore-backup IPC handler dialog and completion message to reflect authoritative restore with forward migration.

Fixes #1427
… Every file changed in the PR diff must conform to the repository's `oxfmt` formatting standard (`scripts/ci/check-changed-format.cjs`), which guarantees that `Lint & Build Validation (Linux)` and the downstream `Required Checks Gate` succeed. - **Violated Sites:** Four files modified in the PR (`main/status-window.ts`, `main/window-recovery.ts`, `tests/shutdown-lifecycle.test.ts`, and `tests/status-messages.test.ts`) failed `oxfmt --check` during `node scripts/ci/check-changed-format.cjs`, causing `Lint & Build Validation (Linux)` (ci-1) and consequently `Required Checks Gate` (ci-2) to fail. ### Fix Applied Formatted the four unformatted changed files using `npx oxfmt --write -- main/status-window.ts main/window-recovery.ts tests/shutdown-lifecycle.test.ts tests/status-messages.test.ts`. ### Verification - `node scripts/ci/check-changed-format.cjs --base 7b18927` (passed) - `npm run lint` (passed) - `npm run build` (passed) - `npx tsx tests/shutdown-lifecycle.test.ts` (passed) - `npx tsx tests/status-messages.test.ts` (passed) - `git diff --check` (passed)
@khaira777
khaira777 force-pushed the fm/flocafe-restore-jwt-status-r1 branch from ed80fab to 93bbbf1 Compare November 3, 2026 18:40
@khaira777 khaira777 changed the title fix(db): rotate JWT on restore & guard startup fix: rotate restored JWT secret and guard startup status window close Nov 3, 2026
@khaira777 khaira777 changed the title fix: rotate restored JWT secret and guard startup status window close fix: rotate restored JWT & guard status window Nov 3, 2026
@khaira777
khaira777 merged commit 01c5d1f into main Nov 3, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-restore-jwt-status-r1 branch November 3, 2026 19:44
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(restore): rotate JWT secret on authoritative restore and guard startup status window

1 participant