Back to Logbook
Jun 07, 2026 Project: #Biznetrix

OAuth Refactor — HMAC State, Instagram Fixed, 467 Tests Green

accomplished

The existing OAuth implementation used database-backed state storage. Every cross-site redirect from Facebook or Instagram was losing the session because the browser's SameSite cookie policy drops the session cookie on the redirect back from the OAuth provider. After multiple attempts to fix session persistence (session save handlers, cookie flags, session restoration tricks), the conclusion was clear: database-backed state is the wrong architecture for this problem.

Refactored to HMAC self-validating state tokens. State format encodes the platform and app identifier with an HMAC signature. No database lookup needed on callback — just re-compute the HMAC and compare. The callback routes are now public with HMAC validation instead of admin-protected routes requiring a live session. Session is restored after HMAC validation from the admin ID stored at connect time.

Instagram Business token exchange was also corrected. It was hitting the Instagram Basic Display endpoint, which is wrong — Instagram Business accounts are linked to Facebook Pages and use Facebook's Graph API for token exchange. Changed the endpoint and it works correctly.

API health check fixed: tokens are cleaned of whitespace before use in Authorization headers to prevent RFC 7230 header validation errors. WhatsApp webhook GET verification wired (Meta sends a GET challenge before starting POST delivery). Webhook signature filter skips validation for GET requests.

All 467 tests passing, 2086 assertions, no errors. The test suite now covers HMAC state validation, token exchange for both platforms, account saving with encryption, session handling, and webhook verification.

Lessons Learned

HMAC-based self-validating state tokens are the correct pattern for OAuth state across cross-site redirects. They require no server-side storage, survive session loss, and validate entirely on the callback. Database-backed state should be the last resort, not the first.