Repository navigation
fix(auth): asynchronously verify manager PINs without blocking event loop - #1197
Merged
Merged
Conversation
…loop - Replace synchronous bcrypt.compareSync in candidate manager PIN scans with asynchronous verifyPinAsync - Prevent event loop starvation during manager PIN evaluation across orders and bills routes - Bind pre-verified manager identity to candidate PIN hash and revalidate atomically within SQLite withTxn write transactions - Closes #1179
Contributor
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configuration
You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
This was referenced Oct 17, 2026
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Asynchronous non-blocking manager PIN verification and atomic revalidation for FloCafe issue #1179
What Changed
verifyPinAsyncusing non-blockingbcrypt.compareand moved manager override PIN verification across order status updates, discounts, item voids, and bill payments outside database transactions.withTxncallbacks to verify approver active status, roles, permissions, and PIN hashes under transaction lock.tests/async-pin-event-loop.test.tstotest:phase2to test event loop yielding, rate limiting, and concurrent WAL writes, and documented the async verification pattern indocs/architecture/authentication-and-authorization.md.Risk Assessment
🚨 High: Async bcrypt verification runs before rate-limit checks in order status updates and item cancellations, exposing the event loop and thread pool to CPU exhaustion from rate-limited callers.
Testing
Validated issue #1179 by standing up the FloCafe backend server in an isolated environment and driving 5 live end-to-end scenarios against the running HTTP API, plus executing the focused phase 2 test suite. Live verification confirmed: valid manager PIN overrides kitchen delivery gates for settlement (HTTP 200, kitchenDeliveryOverridden: true); invalid manager PINs fail closed with HTTP 403; the Node.js event loop remains responsive (sub-100ms concurrent health checks) throughout multi-candidate bcrypt hashing; atomic SQLite revalidation prevents race conditions by rejecting altered or deactivated approvers at transaction commit; and rate-limited clients are locked out with HTTP 429 before invoking async bcrypt verification. All automated and live checks passed with zero failures.
Evidence: Scenario 1 Kitchen Delivery Override JSON
{"scenario":"Manager PIN override for kitchen delivery gate on bill payment allows settlement of preparing orders","orderId":1,"billId":1,"paymentAttemptWithoutPin":{"statusCode":409},"paymentAttemptWithManagerPin":{"statusCode":200,"overridePin":"5555","response":{"kitchenDeliveryOverridden":true,"bill":{"payment_status":"paid"}}},"result":"pass"}Evidence: Scenario 2 Invalid PIN Rejection JSON
{"scenario":"Adversarial invalid manager PIN on kitchen delivery gate is rejected with 403","orderId":2,"billId":2,"invalidPinUsed":"9999","response":{"statusCode":403,"body":{"error":"Invalid manager PIN"}},"persistedBillState":{"payment_status":"unpaid"},"result":"pass"}Evidence: Scenario 3 Event Loop Latency JSON
{"scenario":"Non-blocking event loop responsiveness: concurrent API requests serve immediately during manager PIN scan","pinOperationDurationMs":358,"pinOperationStatus":200,"concurrentHealthChecks":[{"iteration":1,"status":200,"durationMs":38},{"iteration":2,"status":200,"durationMs":63},{"iteration":10,"status":200,"durationMs":0}],"maxHealthLatencyMs":65,"avgHealthLatencyMs":29.7,"eventLoopBlocked":false,"result":"pass"}Evidence: Scenario 4 Atomic Revalidation Rollback JSON
{"scenario":"Atomic SQLite revalidation under transaction lock: deactivated manager or modified PIN rejected at commit","deactivatedManagerRejection":{"statusCode":403,"body":{"error":"Invalid manager PIN"}},"alteredPinHashRejection":{"statusCode":403,"body":{"error":"Invalid manager PIN"}},"result":"pass"}Evidence: Scenario 5 Rate Limit Lockout JSON
{"scenario":"PIN attempt rate limit protection rejects lockout clients before triggering async bcrypt hashing","failedAttempts":[{"attempt":1,"status":403},{"attempt":5,"status":429}],"lockoutAttempt":{"statusCode":429,"durationMs":3,"body":{"error":"Too many PIN attempts. Try again in 15 minutes."}},"result":"pass"}Evidence: Live Verification Transcript Log
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
main/routes/orders.ts:2270- In PATCH /api/orders/:id/status (line 2270), verifyPinAsync executes across candidate managers before checking isPinRateLimited(rateLimitKey) (which is only evaluated at line 2550 inside withTxn). When a client IP is locked out due to exceeding rate limits, every request still executes expensive bcrypt comparisons across candidate managers, defeating rate-limiting protection against CPU exhaustion. Additionally, when override_pin is supplied for non-override status transitions (e.g. 'preparing' or 'ready'), verifyPinAsync executes on all candidates while checkPinRateLimit is never called, enabling unthrottled bcrypt execution. Sibling site: main/routes/orders.ts:3902 (in PATCH /api/orders/:orderId/items/:itemId/cancel, verifyPinAsync runs across candidates before isPinRateLimited at line 4015, and rate-limit tracking is bypassed when isItemVoid is false). Rate limiting must be verified before initiating async PIN scans, matching main/routes/orders.ts:3047, main/routes/orders.ts:3452, and main/routes/bills.ts:131.main/routes/bills.ts:237- In checkKitchenDeliveryStatus, the else fallback branch (lines 237-244) retains the legacy synchronous verifyPin scan over active managers. No intent requirement needs this synchronous fallback because the stated intent of issue Synchronous manager PIN scans block the main-process event loop #1179 is non-blocking asynchronous verification, and all production payment endpoints (POST /api/bills/:id/payment and POST /api/bills/:id/payments) already perform asynchronous pre-verification via preVerifyKitchenDeliveryPin. Retaining a synchronous bcrypt loop inside the database transaction reintroduces event-loop blocking. Recommend removing the unrequired fallback branch and requiring preVerifiedManager when overridePin is supplied.🔧 Fix applied.
2 warnings still open:
main/routes/bills.ts:237- In checkKitchenDeliveryStatus, the else fallback branch (lines 237-244) retains the legacy synchronous verifyPin scan over active managers. No intent requirement needs this synchronous fallback because the stated intent of issue Synchronous manager PIN scans block the main-process event loop #1179 is non-blocking asynchronous verification, and all production payment endpoints (POST /api/bills/:id/payment and POST /api/bills/:id/payments) already perform asynchronous pre-verification via preVerifyKitchenDeliveryPin. Retaining a synchronous bcrypt loop inside the database transaction reintroduces event-loop blocking. Recommend removing the unrequired fallback branch and requiring preVerifiedManager when overridePin is supplied.main/routes/bills.ts:237- In checkKitchenDeliveryStatus, the else fallback branch (lines 237-244) retains the legacy synchronous verifyPin scan over active managers. No intent requirement needs this synchronous fallback because the stated intent of issue Synchronous manager PIN scans block the main-process event loop #1179 is non-blocking asynchronous verification, and all production payment endpoints (POST /api/bills/:id/payment and POST /api/bills/:id/payments) already perform asynchronous pre-verification via preVerifyKitchenDeliveryPin. Retaining a synchronous bcrypt loop inside the database transaction reintroduces event-loop blocking if invoked directly without pre-verification. Recommend removing the unrequired fallback branch and requiring preVerifiedManager when overridePin is supplied.✅ **Test** - passed
✅ No issues found.
node tests/run-electron-node-test.cjs tests/async-pin-event-loop.test.tsnpm run test:phase2POST /api/bills/:id/payment with valid manager PIN override on undelivered kitchen itemsPOST /api/bills/:id/payment with adversarial invalid manager PIN overrideConcurrent GET /api/health during multi-candidate manager PIN verification scanManager deactivation and PIN alteration revalidation under SQLite transaction lockRate limit lockout enforcement returning HTTP 429 before bcrypt execution✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.