Skip to content

feat(backup): add restore-from-file control - #892

Merged
khaira777 merged 4 commits into
mainfrom
fm/flocafe-restore-backup-dialog-r1
Sep 27, 2026
Merged

khaira777 merged 4 commits into
mainfrom
fm/flocafe-restore-backup-dialog-r1

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Closes the missing restore control from S6 of #830, reported from the +961 WhatsApp thread on 21 and 22 September.

A shop on Windows that wanted to restore a backup had no button to press, so the only path a support agent could give them was finding the backup file on disk and copying it over the live database by hand. That workaround is not merely discouraged on Windows. better-sqlite3 opens the database with FILE_SHARE_READ | FILE_SHARE_WRITE and without FILE_SHARE_DELETE (node_modules/better-sqlite3/deps/sqlite3/sqlite3.c:54222-54227, and again for the journal sidecars at :52948 and :52960), so Windows permits the overwrite while the running application keeps its handle and its -wal and -shm mappings pointed at a completely different database image. The only safe sequence is to close the app first, and Flo already knows how to do that correctly: restoreBackup checkpoints the WAL, takes a recovery copy, calls closeDatabase(), removes the database files, copies, and reopens. A customer can now restore without hand-copying a file on Windows, because the application does that whole sequence itself behind one button, and nobody has to find flo.db in Explorer.

The restore control lives at Settings > Data > Backup, next to the managed backup list. It opens the native picker and restores an arbitrary chosen file through the same restoreBackup() mechanism every other path already uses, including the existing validation, the foreign-key and inventory-ledger checks, and the journalled crash recovery. No second restore mechanism and no generalised validation were added.

The second change is the gate. Restore over HTTP is an authorised alternative rather than a removed Master PIN: the route requires a session holding database.manage, the typed phrase RESTORE BACKUP, and a file the operator picked in the native dialog. The picker runs in the main process and hands the chosen path to main/services/restore-file-selection.ts, which returns it exactly once for a single-use token, so the route will not accept a path the renderer invented, which preserves the containment property that #316 established. This is what unblocks the real customer: previously an install with no Master PIN set, or on a machine whose OS keyring reports unavailable, could not restore by any path at all, because the IPC handler authorised the PIN before the file picker was ever reached and the settings tab's own no-keyring fallback called a path that could never succeed. The Master PIN still gates restoring a managed backup from Backup History over IPC. The application menu item still works and now routes to the same settings action rather than a divergent second implementation, so there is one code path for restoring from an arbitrary file.

A restore is now recoverable afterwards. A successful restore was deleting the only copy of the data it replaced, and that copy would not have been recoverable anyway even had it survived, because its flo-restore-recovery- name is invisible to listBackups() and is refused by isManagedBackupFile. The snapshot is now stamped with _flo_meta, copied to flo-backup-<timestamp>-pre-restore-v<version>.db so it appears in Backup History as a one-click undo through the ordinary preset path, and pruned to the three most recent so it cannot grow without limit. It is copied rather than renamed specifically so the replacement journal keeps pointing at a real file and a crash between the committed journal and cleanup can still roll back. A customer who restores the wrong file now has a listed, restorable copy of what was there before.

The confirmation states what will be replaced, that staff accounts, PINs, printers, tax settings and this machine's cloud account are kept, and that a copy is kept so the restore can be undone, in all 24 maintained locales.

One defect surfaced while testing and is fixed here: restoreBackup threw SQLITE_NOTADB on a file that was not a readable SQLite database, despite the documented contract that an unreadable source returns a structured failure. It now returns a refusal.

Red before green. tests/restore-safety-copy.test.ts first failed with SqliteError: file is not a database and then with a successful restore retains exactly one pre-restore copy (found: []). tests/restore-from-file-api.test.ts failed with restore without the confirmation phrase is refused / 404 !== 400 while the route was stashed away. The newer-schema refusal already worked; the new test pins that it is refused without touching live data.

Out of scope and left alone: the downgrader flow, and the fact that POST /api/db/backup and /api/db/import are reachable without a Master PIN when the keyring is unavailable while the sibling delete route is not.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 8 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 10ab99d8-f916-45c0-b624-1808e154d865

📥 Commits

Reviewing files that changed from the base of the PR and between 0e7d9a1 and 8c8e2ec.

⛔ Files ignored due to path filters (1)
  • package.json is excluded by !package.json
📒 Files selected for processing (43)
  • docs/architecture/data-and-migrations.md
  • docs/reference/api.md
  • frontend/e2e/helpers/electron-fixture.ts
  • frontend/e2e/restore-from-file-deeplink.spec.ts
  • frontend/e2e/title-bar-platform.spec.ts
  • frontend/src/app/(dashboard)/settings/page.tsx
  • frontend/src/components/layout/MenuActionHandler.tsx
  • frontend/src/components/settings/DatabaseSettingsTab.tsx
  • frontend/src/lib/i18n/messages/ar.json
  • frontend/src/lib/i18n/messages/bn.json
  • frontend/src/lib/i18n/messages/de.json
  • frontend/src/lib/i18n/messages/en.json
  • frontend/src/lib/i18n/messages/es.json
  • frontend/src/lib/i18n/messages/fa.json
  • frontend/src/lib/i18n/messages/fil.json
  • frontend/src/lib/i18n/messages/fr.json
  • frontend/src/lib/i18n/messages/hi.json
  • frontend/src/lib/i18n/messages/id.json
  • frontend/src/lib/i18n/messages/it.json
  • frontend/src/lib/i18n/messages/ja.json
  • frontend/src/lib/i18n/messages/ko.json
  • frontend/src/lib/i18n/messages/ne.json
  • frontend/src/lib/i18n/messages/nl.json
  • frontend/src/lib/i18n/messages/pt.json
  • frontend/src/lib/i18n/messages/ru.json
  • frontend/src/lib/i18n/messages/sq.json
  • frontend/src/lib/i18n/messages/th.json
  • frontend/src/lib/i18n/messages/tr.json
  • frontend/src/lib/i18n/messages/ur.json
  • frontend/src/lib/i18n/messages/vi.json
  • frontend/src/lib/i18n/messages/zh-tw.json
  • frontend/src/lib/i18n/messages/zh.json
  • frontend/src/types/electron-api-contract.ts
  • frontend/src/types/electron.d.ts
  • main/db.ts
  • main/index.ts
  • main/ipc.ts
  • main/preload.ts
  • main/routes/database.ts
  • main/services/restore-file-selection.ts
  • tests/electron-api-contract.test.ts
  • tests/restore-from-file-api.test.ts
  • tests/restore-safety-copy.test.ts

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 force-pushed the fm/flocafe-restore-backup-dialog-r1 branch 2 times, most recently from b8a7f8b to 3932eb9 Compare September 26, 2026 23:17
@khaira777

Copy link
Copy Markdown
Contributor Author

The CodeQL "Missing rate limiting" finding from 20:04 is fixed, not suppressed. tests/restore-from-file-api.test.ts now mounts the same expressRateLimit chain main/server.ts mounts, in the same order, with the same private-IP skip, because the test's premise is that it builds the production middleware chain. CodeQL passes on the current head (3932eb93). This pull request has since been rebased onto 56a7ac7b; the rebased-head four-platform matrix is in progress and the previous two matrices both came back 4/4 green.

A shop on Windows that wanted to restore a backup had no button to press,
so the only workaround support could hand them was copying flo.db over the
live database by hand. That workaround is not merely discouraged on Windows
- better-sqlite3 opens the database with FILE_SHARE_READ | FILE_SHARE_WRITE
and without FILE_SHARE_DELETE (deps/sqlite3/sqlite3.c:54222-54227), so
Windows lets the overwrite succeed while the app keeps its handle and its
-wal/-shm mappings pointed at a different database image. Closing the app
first is the only safe sequence, and the app already knows how to do it.

Settings > Data > Backup now has "Restore Backup from File...", which opens
the native picker and restores an arbitrary chosen file through the same
restoreBackup() mechanism every other path uses, so the app does the close,
copy, reopen, integrity check and journalled recovery itself and nobody has
to touch the database file.

Restore over HTTP is the authorised alternative to the Master PIN gate rather
than its removal. It requires a session holding database.manage, the typed
phrase RESTORE BACKUP, and a file the operator picked in the native dialog:
the picker runs in the main process and hands the path to
services/restore-file-selection as a single-use token, so the route will not
accept a path the renderer invented. This is the change that lets a shop with
no Master PIN set, or on a machine whose OS keyring is unavailable, recover at
all; previously every restore path returned "Master PIN is not available"
before the file picker was ever reached. The Master PIN still gates restoring
a managed backup from Backup History over IPC. The application menu item now
routes to the settings action rather than a second implementation.

A successful restore also keeps the data it replaced. The replacement-journal
snapshot was being deleted on the way out and, had it survived, its
flo-restore-recovery name would have been invisible to listBackups() and
refused by isManagedBackupFile. It is now stamped with _flo_meta, copied to
flo-backup-<timestamp>-pre-restore-v<version>.db so it appears in Backup
History as a one-click undo, and pruned to the three most recent. The
snapshot is copied rather than renamed so the journal keeps pointing at a real
file for crash recovery.

restoreBackup also no longer throws when the source is not a readable SQLite
file; it returns a structured refusal, as it already claimed to in the docs.

Red before green: tests/restore-safety-copy.test.ts showed the throw, then
"retains exactly one pre-restore copy (found: [])"; tests/restore-from-file-api.test.ts
showed 404 before the route existed.

Refs #830
The new section duplicated an existing '### Database' heading, which
markdownlint MD024 rejects. Record the route as a row in the table that
already owns main/routes/database.ts.
The application menu opens the restore control through a ?action= deep link
that was never cleared, which caused two user-visible failures. After a
successful restore the page reloads still carrying the parameter and
immediately opens the file picker again, so an operator who just restored a
database is suddenly asked to pick another file with no explanation. And a
cancelled picker leaves the parameter armed, so the next menu click pushes a
URL that has not changed and does nothing at all.

Strip the parameter with router.replace before the action runs, so neither
outcome can re-arm it. frontend/e2e/restore-from-file-deeplink.spec.ts covers
both sequences and fails without the change with the address still carrying
action=restore-from-file.

Also delete the tRestore handle left unused in MenuActionHandler once the
restore action moved into settings; it was the sixth frontend warning and
over budget. The budget is not raised.

Mount the same express-rate-limit chain main/server.ts mounts, in the same
order, in the restore-from-file API test. The test claims to build the
production middleware chain, so it should reach the route the way production
does rather than through a quieter variant.

Both new test files now clean up their temporary directory and database in a
finally rather than only on failure, matching backup-restore-production.

Correct the architecture docs: the pre-restore safety copy is copied, not
renamed, so the replacement journal keeps pointing at a valid file for crash
recovery.
The browser e2e job runs eslint over frontend/e2e and rejected the four
no-explicit-any casts the new deep-link test introduced. Declare
__floPickerCalls on the fixture's existing Window augmentation so the count is
typed on both the fixture and the spec.
@khaira777
khaira777 force-pushed the fm/flocafe-restore-backup-dialog-r1 branch from 3932eb9 to 8c8e2ec Compare September 26, 2026 23:56
@khaira777
khaira777 merged commit fab030e into main Sep 27, 2026
20 checks passed
@khaira777
khaira777 deleted the fm/flocafe-restore-backup-dialog-r1 branch September 27, 2026 00:13
khaira777 pushed a commit that referenced this pull request Sep 27, 2026
The transmission state started as false, so until the settings request
returned the screen rendered the off-state claim, and the toggle flipped
the state optimistically, so switching it off showed that claim before
the server had agreed. That is the same false claim the conditional
hint was meant to remove, reintroduced for the loading and saving
windows. The state is now null until confirmed, a save shows a neutral
sentence that asserts neither way, and the transmission value is applied
only after the PUT succeeds. The neutral sentence is each locale's own
first sentence, so it is 24 additions and no rewrites.

A successful clear now drops the local snapshot before refreshing, so a
failed refresh cannot leave deleted failures on screen under a "cleared"
message.

Also fixes settings.restoreSafetyCopyDetail in Vietnamese, which
contained the Indonesian "ada perubahan" inside a Vietnamese sentence.
That string came from #892, not from this branch, but it is in the
diff this pull request ships and it is user-facing, so it is corrected
here rather than left for a Vietnamese user to hit.
khaira777 pushed a commit that referenced this pull request Sep 27, 2026
The transmission state started as false, so until the settings request
returned the screen rendered the off-state claim, and the toggle flipped
the state optimistically, so switching it off showed that claim before
the server had agreed. That is the same false claim the conditional
hint was meant to remove, reintroduced for the loading and saving
windows. The state is now null until confirmed, a save shows a neutral
sentence that asserts neither way, and the transmission value is applied
only after the PUT succeeds. The neutral sentence is each locale's own
first sentence, so it is 24 additions and no rewrites.

A successful clear now drops the local snapshot before refreshing, so a
failed refresh cannot leave deleted failures on screen under a "cleared"
message.

Also fixes settings.restoreSafetyCopyDetail in Vietnamese, which
contained the Indonesian "ada perubahan" inside a Vietnamese sentence.
That string came from #892, not from this branch, but it is in the
diff this pull request ships and it is user-facing, so it is corrected
here rather than left for a Vietnamese user to hit.
khaira777 added a commit that referenced this pull request Sep 27, 2026
* chore: rebase resolution for locale files

Automated union: upstream's file as the base, plus the keys this branch
adds. 552 keys = 23 new diagnostics keys x 24 locales, with no
pre-existing key's value taken from either side.

* fix: close the dotted-token leak in diagnostic signatures

The classifier kept a dotted token whenever the word before it was a
structural word, and that list held ordinary prepositions and verbs.
So `connect to api.stripe.com` reduced to `to api.stripe.com` and
`auth failed by user.name` reduced to `failed by user.name`: a hostname
and a username survived verbatim into a stored signature. The comment
above the line stated the opposite of what the code did.

The escape hatch is now a short set of genuine SQL clause and schema-slot
introducers, so `orders.customer_id` and `no such table: orders` still
read and a dotted value after "to", "by" or "not found" is dropped. A URL
is additionally recognised as a whole structure and replaced with a single
typed placeholder rather than matched as a substring, so a host cannot
survive by standing beside other text, and the pattern is deliberately
over-inclusive because under-redacting is the failure this exists to
prevent. No host blocklist: the stored value stays derived.

Also gate the transmission switch on settings.manage, which is what
PUT /settings/:key enforces. A server holds the support permission that
opens the screen but not the settings permission, so the switch is now
visibly unavailable rather than an enabled control that 403s.

* fix: stop the screen claiming nothing is sent when transmission is on

diagnosticsLocalOnlyHint rendered unconditionally and says that nothing
leaves the till automatically. That is true while
diagnostics_transmission_enabled is off and false the moment an operator
turns it on, so the screen was telling a shop owner something untrue
about their own data at exactly the moment they were deciding whether to
turn it on. The hint is now conditional on the setting.

The transmission-on wording says recorded problems *may* be sent, not
that they are: transmission can be on while cloud sync is off or the
store has no key, in which case nothing is enqueued, and a wording that
asserted sending would be false in that state too.

All twenty-four locales get the new string, built from that locale's
own already-reviewed first sentence so the wording stays consistent, and
each locale's own clause rather than an English template. Also
corrects the Filipino "plain language" to "payak na wika", which is the
established term, in place of "madaling salamin" ("easy to read").

Reported by CodeRabbit on ar, bn, de, es, sq, th, tr, ur and zh. A new
end-to-end case turns transmission on and asserts the absolute claim is
withdrawn; it fails against the previous render.

* fix: three P1s from review - clear authz, backup leak, eviction order

Any staff member holding the default support.use permission could DELETE
the whole local failure history, which is the one thing a diagnostics
feature must never allow. The read path stays support.use so any staff
member can still read a failure out and copy the bundle; erasing it now
takes settings.manage, the same permission the transmission setting
already required, and the Clear button is disabled without it rather
than being a control that 403s.

A SQLite backup copies the whole file, so excluding local_diagnostics
from the JSON export did not stop another till's failures arriving on a
restore. They are now captured and merged across a restore like the
outbox state, so the receiving device keeps its own log, drops the
incoming one, and re-caps it.

Outbox eviction took the oldest rows, which during a long outage are
exactly the pending and failed rows still waiting to be sent. It now
evicts delivered rows first and only falls back to undelivered ones when
there are not enough delivered rows to make room. Every write in the
bounds test is now awaited individually so completion is proven rather
than timed, and the fixture puts the delivered rows newest so the two
policies cannot pick the same rows.

Also: condense the new comments to the repository's 1-2 line standard,
convert the three new suites to the throwing assertion helpers, and
restore the transmission setting in a finally block so a failed
assertion cannot leave it on in the shared end-to-end database.

* fix: only claim nothing is sent once the setting is confirmed

The transmission state started as false, so until the settings request
returned the screen rendered the off-state claim, and the toggle flipped
the state optimistically, so switching it off showed that claim before
the server had agreed. That is the same false claim the conditional
hint was meant to remove, reintroduced for the loading and saving
windows. The state is now null until confirmed, a save shows a neutral
sentence that asserts neither way, and the transmission value is applied
only after the PUT succeeds. The neutral sentence is each locale's own
first sentence, so it is 24 additions and no rewrites.

A successful clear now drops the local snapshot before refreshing, so a
failed refresh cannot leave deleted failures on screen under a "cleared"
message.

Also fixes settings.restoreSafetyCopyDetail in Vietnamese, which
contained the Indonesian "ada perubahan" inside a Vietnamese sentence.
That string came from #892, not from this branch, but it is in the
diff this pull request ships and it is user-facing, so it is corrected
here rather than left for a Vietnamese user to hit.

* test: make the eviction waits prove the write actually landed

The overflow and probe checks settled on a row count of 200, which is
already true before the background write runs, so they could pass without
checking anything and leave the following ordering assertions reading an
earlier state. Each write is now awaited on a unique marker in the local
log, which keeps the newest rows, so the marker is present exactly when
that write's background task has completed. The count assertions remain,
but now measure something that has actually happened. Verified red before
green: against the old insertion-order eviction the delivered-first
assertion still fails with these sound waits in place.

* fix: a stale settings read must not undo a confirmed transmission save

If an owner enabled transmission while the initial load or a refresh was
still in flight, the older settings response could arrive after the save
and replace the confirmed ON state with OFF. The switch then showed off
and the screen claimed nothing left the till, while the backend could in
fact transmit - the same false promise as before, in the direction that
leaves a shop believing it is safe.

A save now increments a counter, each read records the counter value it
started at, and a response only writes the transmission state when
nothing has been saved since. So a save beats a read that started before
it, and a refresh that begins after a save still reflects the saved
value.

Two end-to-end cases cover both orderings. The first has the server
answer the settings read before the save and the response delivered
after, which is the actual race; against the unguarded component it
fails with the switch reading aria-checked="false". The second saves,
refreshes, and asserts the switch and the transmitting wording both hold.

* test: make the post-save refresh test fail when the refresh is broken

The refresh test asserted the switch and the wording after clicking
Refresh, but the save had already set both, so it passed whether or not
the refresh did anything. A green test that cannot fail is worse than a
missing one, because it is misleading to whoever reads the result next.

The refresh path is now the thing under test rather than a bystander:
the save turns transmission on through the UI, the server value is then
changed directly, and the refresh has to bring that new value on screen.
The assertions are on the switch and the off-state wording, neither of
which the save produced. Deliberately breaking refresh() makes this test
fail; restoring it makes it pass.

Two comments that exceeded the repository's one-to-two line limit are
condensed, and the stale-read comment in the component with it.

* refactor: apply the comment rule across the whole change

Deleted the comments that restate the test, the method name or the code
around them, and kept only those carrying rationale a reader could not
reconstruct: why the settings response is fetched before being fulfilled
rather than the request being delayed, why asserting the switch after a
save would prove nothing, why a server account is the one used for the
permission case, and why a late read must not overwrite a saved value.

Swept the backend and component comments in the same pass rather than
only the three flagged lines, so this does not open another round: the
route and cloud-sync block comments are now one to two lines, and each
states the non-obvious reason rather than narrating the code.

* fix: renumber the local diagnostics migration to 95

The courier slip landed its own migration as 94, so the registry now has
two entries claiming 94. The registry requires unique increasing
versions, so the local diagnostics migration moves to 95, after the
courier slip's.

The authorization-permission schema check keeps main's floor assertion
rather than my exact pin: a floor of 93 already survives this branch
adding a migration, and it stops the next one needing the same fix.
The screen test's schema assertion becomes a floor for the same reason.

---------

Co-authored-by: firstmate <firstmate@local>
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