Skip to content

fix: scope staff PIN lockouts per client IP and make JWT invalidation deterministic - #1510

Merged
khaira777 merged 6 commits into
mainfrom
fm/flocafe-sec-batch2-auth-pin-jwt
Nov 8, 2026
Merged

khaira777 merged 6 commits into
mainfrom
fm/flocafe-sec-batch2-auth-pin-jwt

Conversation

@khaira777

@khaira777 khaira777 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Proceed with sequential local implementation Batch 2 (Items 4 and 6 of the revised security plan), subject to these decisions and acceptance criteria:

  1. Choose Option A for staff PIN lockouts :
  • Scope failed-attempt lockout to (client IP, user ID), retaining the existing five-attempt/15-minute policy and per-account verification serialization.
  • Keep endpoint volume limits and audit attribution. Apply normal limits to loopback too, without an authentication exemption.
  • Explicitly document that this protects terminal availability while reducing resistance to guessing distributed across multiple devices.
  • Test that failures on one client cannot lock out another client.
  1. Approve the token-invalidation goal, subject to deterministic boundary tests :
  • Update all seven issuers, including KDS. Do not assume fractional iat plus <= completely settles ordering.
  • Tests must distinguish pre-change tokens from fresh post-change logins, cover same-second and same-millisecond cases, and define handling of existing integer-timestamp tokens.
  • Skip (preserve existing access-token refresh semantics without immediate predecessor revocation).
  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

  • Scoped POST /api/auth/pin-login failed-attempt lockouts to (normalized client IP, user ID) via normalizeIpForPinRateLimit (collapsing non-loopback IPv6 addresses to /64 while keeping individual IPv4 addresses and loopback in their own buckets), removing the install-wide per-account lockout counter while retaining per-user verification serialization (withPinVerificationLock), endpoint volume limits, and auth_audit_log attribution.
  • Introduced a shared monotonic millisecond auth clock (nextAuthTimestampMs, nextTokenIatSeconds, and nextTokensValidAfterTimestamp) bounded above persisted users.tokens_valid_after values, stamping sub-second iat claims across all seven JWT issuers (:3001 login/PIN-login/tenant-select/refresh/setup, :3002 KDS login, and :3003 Server App login) and updating isTokenStale to compare sub-second iat against tokens_valid_after with <= at millisecond resolution (and integer iat or whole-second timestamps with <= at second resolution).
  • Expanded unit, integration, and E2E test suites and updated authentication and API documentation to cover per-client PIN lockouts and deterministic same-second/same-millisecond JWT invalidation across password/PIN changes, owner recovery, staff deactivation, and backup restores.

Risk Assessment

✅ Low: The changes cleanly scope staff PIN lockouts per client IP (with IPv6 /64 prefix normalization and per-account verification serialization) and enforce deterministic sub-second JWT invalidation across all seven issuers using a shared monotonic clock backed by persisted tokens_valid_after state.

Testing

Kept the normalizeIpForRateLimit import in main/routes/auth.ts and ran the targeted regression test suites (jwt-logout-lifecycle, pin-quick-switch, issue-127-password-recovery, master-pin, restore-from-file-api, and cloud-password-recovery) against live Express API, standalone KDS, and Server App instances backed by isolated SQLite databases; all scenarios passed and execution logs were captured in the evidence directory. No UI layout or visual surface was changed in this backend security and auth lifecycle update.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Five wrong PIN attempts from client IP A lock out (IP A, userId) with HTTP 429 and audit attribution while client IP B can still sign in as that user ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
Adversarial loopback and IPv6 /64 PIN brute-force: loopback enforces the 5-attempt lockout without exemption, and SLAAC addresses within one IPv6 /64 share a lockout bucket while a separate /64 remain… ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
All seven JWT issuers (Main API login, pin-login, tenants/select, refresh, setup/initialize, KDS login, and Server App login) emit monotonic sub-second iat claims, reject pre-change tokens, and accept… ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
Adversarial clock and legacy-token boundaries: legacy integer-second iat tokens, backward wall-clock jumps (>10s), process restarts with persisted future tokens_valid_after, owner recovery, master PIN… ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
Evidence: Targeted PIN Lockout & JWT Token Lifecycle Regression Log

Step 4 (tests/pin-quick-switch.test.ts): ✓ Concurrent wrong-PIN burst allows exactly 5 attempts (401) before lockout ✓ Remaining 3 concurrent wrong-PIN requests receive 429 rate-limited ✓ Client IP A attempt 1..5 (10.10.0.1) returns 401 and decrements attempts_remaining (4..0) ✓ 6th attempt from client IP A (10.10.0.1) returns 429 for (IP A, userId) ✓ Audit log records rate_limited on 6th attempt from client IP A (10.10.0.1) ✓ Client IP B (10.10.0.2) can still authenticate as cashierId with valid PIN while IP A is locked out ✓ Loopback (127.0.0.1) can still authenticate as cashierId while client IP A is locked out ✓ Loopback (127.0.0.1) is subject to the same 5-attempt lockout on its own IP ✓ 6th attempt from another SLAAC address in the same IPv6 /64 (2001:db8:1:2::30) is locked out with 429 ✓ Client on a different IPv6 /64 prefix (2001:db8:1:3::10) is not locked out and can authenticate Step 10 (tests/jwt-logout-lifecycle.test.ts): ✓ Legacy integer-second iat token minted in the same UTC second as tokens_valid_after is stale ✓ Legacy integer-second iat token minted in a later UTC second than tokens_valid_after is valid ✓ Pre-change token is rejected immediately in the same frozen millisecond after password change ✓ Fresh post-change login token in the same frozen millisecond is accepted by /api/auth/me ✓ Pre-change token is rejected after credential change even when Date.now() jumped backward by > 10s ✓ Fresh login token after simulated process restart is accepted by /api/auth/me ✓ Issuers 1-7 (login, pin-login, tenants/select, refresh, setup/initialize, server-app login, kds-server login) stamp sub-second iat, reject pre-change tokens in the same frozen millisecond after credential change, and accept fresh post-change tokens

Command exited with code 0.

Command output:
Testing JWT Logout & Token Lifecycle (Area E)...
============================================================
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-jwt-test-Waq5Y7/flo.db
[DB] Schema: v0 → v125
[DB] Triggering auto-backup before migrating v0 → v125...
[DB] Auto-backup before migrating v0 → v125 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-jwt-test-Waq5Y7/backups/flo-backup-2026-11-08T04-47-32-135Z-pre-v0-to-v125.db
[DB] Install defaults loaded; first-run setup pending
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[MIGRATION v24] normalized: 0, unparseable: 0
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ Login succeeds
  ✓ Access token returned
  ✓ /api/auth/me succeeds with valid token
  ✓ /api/auth/refresh succeeds with valid token
  ✓ New token returned on refresh
  ✓ Logout succeeds
  ✓ Token reuse after logout fails with 401
  ✓ Refresh with revoked token fails with 401
  ✓ Password change with revoked token fails with 401
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-jwt-test-Waq5Y7/flo.db
[DB] Schema up to date (v125)
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ logged-out token remains rejected after database restart
  ✓ original logout remains revoked after token churn
  ✓ Expired token fails with 401
  ✓ Refreshed token remains valid
  ✓ Manager login succeeds
  ✓ Initial token carries manager role
  ✓ Refresh after role change succeeds
  ✓ Refreshed token carries updated role from database
  ✓ Refresh rejects token stale via tokens_valid_after
  ✓ Refresh rejects token for inactive user

Step 10: Deterministic token invalidation (same-second, same-ms, legacy iat, all 7 issuers)
  ✓ Legacy integer-second iat token minted in the same UTC second as tokens_valid_after is stale
  ✓ Legacy integer-second iat token minted in a later UTC second than tokens_valid_after is valid
  ✓ Issued iat claims at frozen ms 1760000010000 carry sub-second precision
  ✓ Pre-change token is stale when minted in the same frozen millisecond (1760000010000) as tokens_valid_after
  ✓ Post-change token is valid when minted in the same frozen millisecond (1760000010000) after tokens_valid_after
  ✓ Issued iat claims at frozen ms 1760000020500 carry sub-second precision
  ✓ Pre-change token is stale when minted in the same frozen millisecond (1760000020500) as tokens_valid_after
  ✓ Post-change token is valid when minted in the same frozen millisecond (1760000020500) after tokens_valid_after
  ✓ Issued iat claims at frozen ms 1760000030999 carry sub-second precision
  ✓ Pre-change token is stale when minted in the same frozen millisecond (1760000030999) as tokens_valid_after
  ✓ Post-change token is valid when minted in the same frozen millisecond (1760000030999) after tokens_valid_after
  ✓ Pre-change login at frozen ms succeeds
  ✓ Password change in same frozen ms succeeds
  ✓ Pre-change token is rejected immediately in the same frozen millisecond after password change
  ✓ Post-change login in same frozen ms succeeds
  ✓ Fresh post-change login token in the same frozen millisecond is accepted by /api/auth/me
  ✓ Password change after backward wall-clock jump (> 10s) succeeds
  ✓ Pre-change token is rejected after credential change even when Date.now() jumped backward by > 10s
  ✓ Login after simulated process restart with persisted tokens_valid_after ahead of wall clock succeeds
  ✓ Fresh login token after simulated process restart is accepted by /api/auth/me
[KDS Server] Static build not found. Run `npm run build:frontend` first.
[KDS Server] HTTP server running on http://localhost:51084
[KDS] WebSocket server setup complete
[KDS Server] WebSocket running on ws://localhost:51084/kds
[Server App] Static build not found. Run `npm run build:frontend` first.
[Server App] HTTP server running on http://localhost:51085
  ✓ Issuer 1 (/api/auth/login) succeeds
  ✓ Issuer 2 (/api/auth/pin-login) succeeds
  ✓ Issuer 3 (/api/auth/tenants/select) succeeds
  ✓ Issuer 4 (/api/auth/refresh) succeeds
  ✓ Issuer 6 (server-app /api/auth/login) succeeds
  ✓ Issuer 7 (kds-server /api/auth/login) succeeds
  ✓ Issuer login stamps sub-second iat (1794113253.209)
  ✓ Issuer pin-login stamps sub-second iat (1794113253.21)
  ✓ Issuer tenants/select stamps sub-second iat (1794113253.211)
  ✓ Issuer refresh stamps sub-second iat (1794113253.212)
  ✓ Issuer server-app login stamps sub-second iat (1794113253.213)
  ✓ Issuer kds-server login stamps sub-second iat (1794113253.214)
  ✓ Staff PIN change in same frozen millisecond succeeds
  ✓ Pre-change token from login rejected on Main API
  ✓ Pre-change token from pin-login rejected on Main API
  ✓ Pre-change token from tenants/select rejected on Main API
  ✓ Pre-change token from refresh rejected on Main API
  ✓ Pre-change token from server-app login rejected on Main API
  ✓ Pre-change token from kds-server login rejected on Main API
  ✓ Pre-change token from server-app login rejected on Server App /api/auth/me
  ✓ Pre-change token from kds-server login rejected on KDS /api/auth/me
  ✓ Post-change /api/auth/login in same ms succeeds
  ✓ Post-change /api/auth/pin-login in same ms succeeds
  ✓ Post-change /api/auth/tenants/select in same ms succeeds
  ✓ Post-change /api/auth/refresh in same ms succeeds
  ✓ Post-change server-app /api/auth/login in same ms succeeds
  ✓ Post-change kds-server /api/auth/login in same ms succeeds
  ✓ Post-change token from login accepted on Main API
  ✓ Post-change token from pin-login accepted on Main API
  ✓ Post-change token from tenants/select accepted on Main API
  ✓ Post-change token from refresh accepted on Main API
  ✓ Post-change token from server-app login accepted on Server App /api/auth/me
  ✓ Post-change token from kds-server login accepted on KDS /api/auth/me
  ✓ Issuer 5 (/api/auth/setup/initialize) succeeds
  ✓ Issuer setup/initialize stamps sub-second iat (1794113253.222)
  ✓ Token from setup/initialize is accepted before credential change
  ✓ Password change after setup/initialize in same frozen ms succeeds
  ✓ Token from setup/initialize is invalidated in the same frozen millisecond after password change
[Server App] HTTP server stopped
[KDS Server] HTTP/WebSocket server stopped

✅ JWT Logout & Token Lifecycle tests passed!
[DB] Database closed
Testing PIN Quick User Switch & Approval Hardening (#1338)...
================================================================
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-pin-quick-switch-VBwdqZ/flo.db
[DB] Schema: v0 → v125
[DB] Triggering auto-backup before migrating v0 → v125...
[DB] Auto-backup before migrating v0 → v125 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-pin-quick-switch-VBwdqZ/backups/flo-backup-2026-11-08T04-47-35-916Z-pre-v0-to-v125.db
[DB] Install defaults loaded; first-run setup pending
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[MIGRATION v24] normalized: 0, unparseable: 0
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected a

... [26806 bytes truncated] ...

in (~/.no-mistakes/worktrees/de2296f2e6f8/01M6WNAPBRXTBM0AP027X1PY18/tests/cloud-password-recovery.test.ts:224:17)
    at processTicksAndRejections (node:internal/process/task_queues:104:5)
  ✓ redeem network failure maps to 502
  ✓ password is unchanged when FloAdmin is unreachable
[Auth] Password recovery: owner password was reset locally via FloAdmin email approval for user owner-1
  ✓ approved reset sets the new password
  ✓ old password stops working
  ✓ new password works
  ✓ recovery is recorded in the audit settings
  ✓ recovery does not add or remove users
  ✓ DEFAULT_CLOUD_SERVER_URL is trusted for password recovery
  ✓ email recovery is available with DEFAULT_CLOUD_SERVER_URL
  ✓ custom cloud_server_url is untrusted for password recovery
  ✓ email recovery is unavailable when cloud_server_url points to a custom server
  ✓ requestPasswordReset rejects with 403 CloudRequestError on untrusted server URL
  ✓ redeemPasswordReset rejects with 403 CloudRequestError on untrusted server URL
23:47:52.458 › [CloudSync] started {
  server: 'https://evil.example.com',
  sync: true,
  commands: true,
  registered: true
}
  ✓ isTrustedRecoveryServerUrl rejects when in-memory server_url is untrusted despite SQLite default URL
  ✓ isEmailRecoveryAvailable is false when in-memory server_url is untrusted
  ✓ requestPasswordReset rejects when in-memory server_url is untrusted
  ✓ no network call is dispatched when in-memory server_url is untrusted
  ✓ isOwnerEmailVerified rejects when in-memory server_url is untrusted
23:47:52.462 › [CloudSync] started {
  server: 'https://blue.flopos.com',
  sync: true,
  commands: true,
  registered: true
}
  ✓ trusted recovery request dispatches one fetch
  ✓ trusted recovery request dispatches to DEFAULT_CLOUD_SERVER_URL (got https://blue.flopos.com/api/pos/password-reset/request)
  ✓ POST /api/settings/cloud/register returns 409 when cloud_deletion_blocked is true
  ✓ blocked cloud register does not write cloud_server_url to SQLite before early return
  ✓ manager cannot overwrite cloud_api_key via PUT /cloud
  ✓ manager cannot overwrite cloud_store_id via PUT /cloud
  ✓ manager cannot reset cloud_server_url to DEFAULT_CLOUD_SERVER_URL via PUT /cloud
  ✓ manager cannot set cloud_server_url via POST /cloud/register
  ✓ cloud_api_key remains unchanged after rejected manager requests
  ✓ cloud_store_id remains unchanged after rejected manager requests
  ✓ cloud_server_url remains unchanged after rejected manager requests
23:47:52.553 › [CloudSync] started {
  server: 'https://custom-owner.example.com',
  sync: true,
  commands: true,
  registered: true
}
  ✓ manager with cloud.manage can still toggle cloud sync/orders flags
23:47:52.555 › [CloudSync] started {
  server: 'https://blue.flopos.com',
  sync: true,
  commands: true,
  registered: true
}
  ✓ owner can update cloud_server_url, cloud_api_key, and cloud_store_id
23:47:52.557 › [CloudSync] started {
  server: 'https://blue.flopos.com',
  sync: true,
  commands: true,
  registered: true
}
  ✓ owner email update via PUT /api/staff/:id succeeds
  ✓ PUT /api/staff/:id syncs settings.email when active owner email changes
  ✓ email recovery remains available after owner email update
[DB] createBackup: Starting...
[DB] createBackup: Backing up to temp: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-cloud-recovery-MCwQxH/backups/flo-backup-2026-11-08T04-47-52-560Z-9ded7d0f.db
[DB] Install defaults loaded; first-run setup pending
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[MIGRATION v24] normalized: 0, unparseable: 0
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] Backup saved to: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-cloud-recovery-MCwQxH/stale-email-backup.db (schema v125)
  ✓ captureRestoreProtectedSettings and mergeRestoreProtectedSettings preserve settings.email
[DB] restoreBackup: Starting restore from: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-cloud-recovery-MCwQxH/stale-email-backup.db
[DB] Backup schema version: 125, SQLite: 125, Current: 125
[DB] Install defaults loaded; first-run setup pending
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[MIGRATION v24] normalized: 0, unparseable: 0
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] restoreBackup: Authoritative restore (schema v125 → v125)
[DB] Database closed
[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-cloud-recovery-MCwQxH/flo.db
[DB] Schema up to date (v125)
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ restoreBackup succeeds
  ✓ restoreBackup applies settings.email from the selected backup
  ✓ isEmailRecoveryAvailable is false when settings.email matches only a non-owner account
  ✓ POST /recover-password/cloud/request rejects when registered email does not match an active owner
  ✓ POST /recover-password/cloud/complete refuses to match a non-owner even when the store is stranded
  ✓ stranded non-owner complete attempt does not consume the reset grant
  ✓ cashier-1 is not promoted to owner on a stranded store via stale cloud email
  ✓ recovery method initializes to email
  ✓ emailStep initializes to idle
  ✓ send button found before method-switch race
  ✓ loading is true while requestEmailReset is in-flight
  ✓ PIN method toggle button found
  ✓ method switches to pin
  ✓ method switch resets loading while request is in-flight
  ✓ loading remains false after superseded requestEmailReset settles
  ✓ superseded requestEmailReset does not transition emailStep
  ✓ superseded requestEmailReset does not set resetId
  ✓ superseded requestEmailReset does not start polling
  ✓ Email method toggle button found
  ✓ method switches back to email
  ✓ send button found for verify_email step
  ✓ requestEmailReset transitions emailStep to verifying
  ✓ verification polling timer registered
  ✓ pollInFlight is true while verification poll is pending
  ✓ resend button found while verifying
  ✓ manual resend calls requestEmailReset once
  ✓ stopPolling resets pollInFlight on verification resend
  ✓ superseded verification poll does not auto-trigger requestEmailReset
  ✓ superseded verification poll does not clobber pollInFlight
  ✓ send button found for email recovery
  ✓ requestEmailReset transitions emailStep to waiting
  ✓ requestEmailReset sets resetId to reset-A
  ✓ status polling timer registered for reset-A
  ✓ pollInFlight is true while status poll A is pending
  ✓ resend button found while waiting
  ✓ emailStep remains waiting for reset-B
  ✓ resend updates resetId to reset-B
  ✓ stopPolling increments pollGeneration on resend
  ✓ stopPolling resets pollInFlight on resend
  ✓ superseded poll A does not transition emailStep to approved for reset-B
  ✓ resetId remains reset-B after superseded poll A resolves
  ✓ superseded poll A does not clobber pollInFlight
  ✓ interval timer active for reset-B
  ✓ reset B poll transitions emailStep to approved
  ✓ resetId matches approved reset B
cloud-password-recovery: all assertions passed
[DB] Database closed
- Outcome: 🔧 2 issues found → no changes applied ✅ across 2 runs (32m16s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

🔧 **Test** - 2 issues 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 736ms ago (105 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.
  • 🚨 Approval is refused: the run worktree at ~/.no-mistakes/worktrees/de2296f2e6f8/01M6WNAPBRXTBM0AP027X1PY18 holds work no Test turn validated, and the steps after Test would commit and publish it. It holds uncommitted changes to main/routes/auth.ts (inspect with git -C ~/.no-mistakes/worktrees/de2296f2e6f8/01M6WNAPBRXTBM0AP027X1PY18 status and git -C ~/.no-mistakes/worktrees/de2296f2e6f8/01M6WNAPBRXTBM0AP027X1PY18 diff). Respond with fix to validate it, or abort.

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

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Five wrong PIN attempts from client IP A lock out (IP A, userId) with HTTP 429 and audit attribution while client IP B can still sign in as that user ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
Adversarial loopback and IPv6 /64 PIN brute-force: loopback enforces the 5-attempt lockout without exemption, and SLAAC addresses within one IPv6 /64 share a lockout bucket while a separate /64 remain… ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
All seven JWT issuers (Main API login, pin-login, tenants/select, refresh, setup/initialize, KDS login, and Server App login) emit monotonic sub-second iat claims, reject pre-change tokens, and accept… ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
Adversarial clock and legacy-token boundaries: legacy integer-second iat tokens, backward wall-clock jumps (>10s), process restarts with persisted future tokens_valid_after, owner recovery, master PIN… ✅ pass live ~/.no-mistakes/evidence/01M6WNAPBRXTBM0AP027X1PY18/targeted-regression-suites.log
  • node tests/run-electron-node-test.cjs tests/jwt-logout-lifecycle.test.ts
  • node tests/run-electron-node-test.cjs tests/pin-quick-switch.test.ts
  • node tests/run-electron-node-test.cjs tests/issue-127-password-recovery.test.ts
  • node tests/run-electron-node-test.cjs tests/master-pin.test.ts
  • node tests/run-electron-node-test.cjs tests/restore-from-file-api.test.ts
  • node tests/run-electron-node-test.cjs tests/cloud-password-recovery.test.ts
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@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

@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

PR Summary by Qodo

Scope PIN lockouts per client IP and make JWT invalidation deterministic

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Scope staff PIN lockouts per client IP and user, preventing failures elsewhere from blocking a
 terminal.
• Coordinate token issuance and credential-change timestamps so old tokens fail and immediate new
 logins succeed.
• Document the security trade-off and test timing boundaries, legacy tokens, and all seven issuers.
Diagram

graph TD
  Client["LAN client"] --> Pin["PIN login"] --> Counters["Per-IP counters"]
  Pin --> Issuers["JWT issuers"] --> Guard["Token guard"]
  Clock["Auth clock"] --> Changes["Credential changes"] --> Users[("Users table")] --> Guard
  Clock --> Issuers
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Per-user token generation counter
  • ➕ Avoids ordering tokens and credential changes by wall-clock timestamp.
  • ➕ Could provide a clearer invalidation boundary across independent processes.
  • ➖ Requires a schema and token-contract change.
  • ➖ Needs a migration policy for existing JWTs and updates to every issuer.

Recommendation: The shared clock is the more contained choice for these existing timestamp-based contracts and the local server listeners. A generation counter merits consideration if issuance moves to independent processes, where a process-local ordering clock would not coordinate them.

Files changed (13) +774 / -179

Bug fix (6) +110 / -38
db.tsAdd shared authentication timestamps +29/-2

Add shared authentication timestamps

• Adds a process-local millisecond clock used for JWT issuance and token-validity cutoffs. Uses the new cutoff timestamp when disabling restored-only users and invalidating users during backup restore.

main/db.ts

kds-server.tsStamp KDS login tokens with ordered issuance times +8/-1

Stamp KDS login tokens with ordered issuance times

• Adds a sub-second iat claim to JWTs issued by KDS login.

main/kds-server.ts

security.tsCompare token staleness at the appropriate precision +19/-10

Compare token staleness at the appropriate precision

• Stops clearing a separate account-wide PIN counter on successful login. Compares sub-second token timestamps against millisecond cutoffs, while retaining second-resolution handling for legacy integer iat claims and whole-second cutoffs.

main/middleware/security.ts

auth.tsIsolate PIN lockouts and order main API token issuance +40/-21

Isolate PIN lockouts and order main API token issuance

• Removes the account-wide failed-PIN bucket while retaining per-user verification serialization and audit records. Stamps tokens on the main API's five issuance paths and writes ordered validity cutoffs for password changes and owner recovery.

main/routes/auth.ts

staff.tsUse precise cutoffs for staff security changes +6/-3

Use precise cutoffs for staff security changes

• Writes a millisecond token-validity cutoff when staff credentials change or an account is deactivated.

main/routes/staff.ts

server-app.tsStamp Server App login tokens with ordered issuance times +8/-1

Stamp Server App login tokens with ordered issuance times

• Adds a sub-second iat claim to JWTs issued by Server App login.

main/server-app.ts

Tests (5) +639 / -129
cloud-password-recovery.test.tsAlign recovery test tokens with new issuance precision +2/-1

Align recovery test tokens with new issuance precision

• Stamps the test's manually signed owner token using the shared issuance clock.

tests/cloud-password-recovery.test.ts

issue-127-password-recovery.test.tsKeep password-recovery test authentication current +214/-84

Keep password-recovery test authentication current

• Stamps the manually signed password-change test token with a sub-second iat. Reformats surrounding test code without changing its assertions.

tests/issue-127-password-recovery.test.ts

jwt-logout-lifecycle.test.tsExercise token invalidation across timing boundaries and issuers +352/-2

Exercise token invalidation across timing boundaries and issuers

• Tests legacy integer timestamps and pre-change versus post-change tokens within frozen seconds and milliseconds. Exercises issuance and invalidation across the main API, KDS, and Server App, including setup initialization.

tests/jwt-logout-lifecycle.test.ts

pin-quick-switch.test.tsVerify independent PIN lockouts for clients and loopback +51/-37

Verify independent PIN lockouts for clients and loopback

• Replaces account-wide cross-IP lockout expectations with tests showing one client's failures do not block another. Confirms loopback has its own five-attempt lockout and rate-limited attempts remain audited.

tests/pin-quick-switch.test.ts

restore-from-file-api.test.tsUse current issuance timestamps in restore API tests +20/-5

Use current issuance timestamps in restore API tests

• Stamps manually signed owner and server test tokens through the shared issuance clock so they follow the new validity comparison.

tests/restore-from-file-api.test.ts

Documentation (2) +25 / -12
authentication-and-authorization.mdExplain PIN isolation and token staleness boundaries +23/-10

Explain PIN isolation and token staleness boundaries

• Documents all seven JWT issuance paths, millisecond token invalidation, and legacy integer-timestamp handling. Explains the terminal-availability benefit and distributed-guessing trade-off of per-client PIN lockouts.

docs/architecture/authentication-and-authorization.md

api.mdCorrect the PIN login rate-limit contract +2/-2

Correct the PIN login rate-limit contract

• Describes PIN failed-attempt lockouts as applying to each client-IP and user pair, including loopback, rather than across source IPs.

docs/reference/api.md

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Old sessions survive a backward clock jump 🐞 Bug ⛨ Security
Description
nextAuthTimestampMs() returns the wall clock without checking the last logical timestamp when the
wall clock moves backward by more than one second. If a credential change then writes that lower
value to tokens_valid_after, a token issued before the change with a higher iat passes
isTokenStale() and remains usable.
Code

main/db.ts[11513]

+  let nextMs = wallMs < lastAuthWallMs - 1000 ? wallMs : Math.max(wallMs, lastAuthLogicalMs + 1);
Relevance

●● Moderate

Backward clock jump is an intentional branch in the new clock; security-relevant, but no close
historical precedent either way.

PR-#1425

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new rollback branch selects wallMs directly, while password changes persist the helper's
result as the cutoff. The new staleness comparison only rejects an iat at or below that cutoff.

main/db.ts[11507-11530]
main/routes/auth.ts[783-789]
main/middleware/security.ts[355-367]

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

## Issue description
The rollback branch can write a credential-invalidation cutoff earlier than an already-issued token.
## Fix Focus Areas
- main/db.ts[11507-11520]
- main/routes/auth.ts[783-789]
## Recommended Fix
Keep the next authentication timestamp strictly greater than the last issued timestamp even after a large backward wall-clock jump. Add a regression test that issues a token, moves the wall clock backward by more than one second, changes credentials, and verifies that the earlier token is rejected.

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

Dismiss ↗ | View ↗



Remediation recommended

2. One device can bypass the PIN lockout by switching addresses ✓ Resolved

Resolving commit: e4d9f82

Resolution reason
The PIN lockout key now uses normalizeIpForPinRateLimit(ip), which collapses non-loopback IPv6
addresses to their first four hextets (/64) and keeps IPv4 and loopback addresses in their own
buckets. The pin-login route builds pinRateKey from this canonical IP (auth.ts), so addresses within
the same /64 share one 5-attempt lockout. Tests in pin-quick-switch.test.ts cover the shared /64
bucket and a separate /64 staying independent. The optional per-account cap across all addresses was
not added, so the fix is a prefix-collapse variant rather than the exact suggested approach.
Description
The PIN lockout is now keyed only on ${normalizeIpForRateLimit(ip)}:pin:${userId}, and
normalizeIpForRateLimit only lowercases the address and strips the ::ffff: prefix. It does not
group IPv6 addresses by prefix. So a single LAN host can cycle through addresses in its IPv6 /64, or
add IPv4 aliases, and get five fresh guesses against the same staff PIN on each address. The only
remaining cap is the 600-failure endpoint limiter, which works out to roughly 600 guesses per 15
minutes instead of 5. At that rate a 4-digit PIN can be brute-forced in a few hours.

3. Fresh logins can fail after a restart 🐞 Bug ☼ Reliability
Description
nextAuthTimestampMs() keeps its logical timestamp only in module variables, while credential
changes persist its value in users.tokens_valid_after. If several authentication timestamps
advance beyond wall time and the process restarts before wall time catches up, a fresh login
receives an earlier iat and is rejected as stale.
Code

main/db.ts[R11507-11508]

+let lastAuthWallMs = 0;
+let lastAuthLogicalMs = 0;
Relevance

●● Moderate

Narrow restart race in in-memory logical clock; no closely matching accept or reject precedent for
auth timestamp monotonicity. Reliability findings are mixed.

PR-#1425

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The helper can advance its logical value by one millisecond per call beyond Date.now(), but only
tokens_valid_after survives a restart. Verification rejects a newly issued token whose reset clock
places its iat at or below that stored value.

main/db.ts[11507-11530]
main/routes/auth.ts[783-789]
main/middleware/security.ts[355-367]
main/server.ts[113-127]

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

## Issue description
A process restart discards logical clock state even though its latest credential cutoff remains in the database.
## Fix Focus Areas
- main/db.ts[11507-11530]
- main/routes/auth.ts[783-789]
## Recommended Fix
Ensure issuance after startup is ordered after any persisted authentication cutoff it must honor, rather than relying solely on process-local counters. Test a frozen wall clock with multiple timestamps, a persisted credential change, and issuance from a fresh module instance.

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

Dismiss ↗ | View ↗


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #10
  🌐 PR #34
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
  Explored: repo: FreeOpenSourcePOS/docs.flopos.com (sha: abe7cff3) — View relationship
✅ REVIEW.md
Review mode: Auto: 🧠 Deep: Dense auth changes: PIN lockout, monotonic clock, staleness logic, seven issuers, many mutation paths.

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/db.ts Resolved
Comment thread main/db.ts Resolved
Comment thread main/routes/auth.ts Resolved
…ss Shards 1, 2, and 3 (which cascaded to End-to-End Playwright Tests and Required Checks Gate): 1. Invariant: Any JWT minted after a user's credential update (`tokens_valid_after`) must carry a monotonic sub-second `iat` strictly greater than `tokens_valid_after`, and any E2E test that updates a user's credentials (`PUT /api/staff/:id`) must not reuse a token minted for that user prior to the credential update. 2. Root causes and fixes: - `frontend/e2e/helpers/test-auth.ts` (`getE2eToken`): The shared E2E test JWT helper still stamped `iat: Math.floor(Date.now() / 1000)` (an integer second). Under the deterministic `isTokenStale` check (`Math.floor(iat) <= Math.floor(validAfterMs / 1000)` for integer `iat`), any `getE2eToken()` call within the same UTC second after a credential update (such as `ops-admin/order-history.spec.ts` after `dashboard-reconciliation.spec.ts` cleared the owner PIN, `ops-admin/staff-roles.spec.ts` after `orders-lifecycle.spec.ts` cleared the owner PIN, and `approval-manager-selection.spec.ts` `afterEach`) was rejected as stale with `401`. Updated `getE2eToken()` to stamp a monotonic sub-second `iat` (`nextE2eTokenIatSeconds()`). - `frontend/e2e/pin-quick-switch.spec.ts`: `test.beforeAll` minted `ownerToken` / `ownerHeaders`, updated `e2e-owner`'s PIN via `PUT /api/staff/e2e-owner` (which updates `tokens_valid_after` and invalidates prior tokens for `e2e-owner`), and then reused the pre-change `ownerHeaders` on subsequent `/api/staff` and cleanup requests. Refreshed `ownerToken` and `ownerHeaders` immediately after the owner PIN update. 3. Verification: - `npm run build` (passed) - `npm run build:frontend` (passed) - `npm run lint` (passed, 0 errors) - `npx playwright test --config=playwright.config.ts --project=chromium --retries=0 e2e/pin-quick-switch.spec.ts e2e/approval-manager-selection.spec.ts e2e/ops-admin/dashboard-reconciliation.spec.ts e2e/ops-admin/order-history.spec.ts e2e/ops-admin/orders-lifecycle.spec.ts e2e/ops-admin/staff-roles.spec.ts --grep-invert='FINDING:|a paid order offers a refund, and issuing it settles against the recorded sale'` (29 passed, 0 failed) - `npx playwright test --config=playwright.config.ts --project=chromium --retries=0 e2e/pin-quick-switch.spec.ts` (1 passed on fresh server) - `npx ts-node --transpile-only -P tests/tsconfig.json tests/jwt-logout-lifecycle.test.ts` (passed) - `npx ts-node --transpile-only -P tests/tsconfig.json tests/pin-quick-switch.test.ts` (passed) - `git diff --check` (passed)
…Validation (Linux)` (which cascaded to `Required Checks Gate`): 1. **Invariant**: Every JS/TS file touched by the pull request must pass Oxfmt whole-file formatting verification (`scripts/ci/check-changed-format.cjs`). 2. **Root cause & fix**: - [test-auth.ts](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M6WH5SC31ZK3NKWMJR7GZCKG/frontend/e2e/helpers/test-auth.ts): In the previous round, `frontend/e2e/helpers/test-auth.ts` was modified without running `oxfmt --write` across the full file, leaving unformatted lines in `ordersLayoutToken` and `setLanguage` that failed `node scripts/ci/check-changed-format.cjs`. Formatted `frontend/e2e/helpers/test-auth.ts` with `oxfmt`. 3. **Verification**: - `node scripts/ci/check-changed-format.cjs --base 7726206` (passed across all 11 root and 2 frontend changed files) - `npm run lint` (passed, 0 errors) - `npm run lint:budget` (passed) - `git diff --check` (passed)
@khaira777
khaira777 force-pushed the fm/flocafe-sec-batch2-auth-pin-jwt branch from 3a240f2 to e4d9f82 Compare November 8, 2026 04:53
@khaira777 khaira777 changed the title fix(main): scope PIN lockout per client IP and make JWT invalidation monotonic fix: scope staff PIN lockouts per client IP and make JWT invalidation deterministic Nov 8, 2026
@khaira777
khaira777 merged commit d518460 into main Nov 8, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-sec-batch2-auth-pin-jwt branch November 8, 2026 05:06
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