HMRC OAuth Flow
Authorisation and callback
- A signed-in user opens
GET /api/hmrc/userRestrictedAuth/authorise. The route idempotently creates or finds theirpublic.usersrow using the Auth0 sessionsub. - The route creates a short-lived, HTTP-only
SameSite=Laxstate cookie and sends the matching state to HMRC. The cookie signature binds the state to the signed-in Auth0 subject; the callback rejects missing, mismatched, or wrong-user state. - HMRC redirects to
GET /api/hmrc/userRestrictedAuth/callbackwith an authorization code or an error. - The callback requires the same signed-in Auth0 user, exchanges every new authorization code directly with HMRC, validates the token response, encrypts the tokens, stores them against that user's database row, and redirects to
/account. It does not reuse an old access token or expose tokens to browser code.
The authorization URLs currently target HMRC Sandbox through config/hmrc.ts. This flow is not evidence of production HMRC access or a live filing.
Token storage and refresh
HMRC documents access tokens as valid for 4 hours and refresh tokens as single-use; HMRC says refresh tokens stop working after 18 months, after which the user must authorize again. See HMRC user-restricted endpoint authorization. The app does not force the user to relink at each Auth0 login.
Tokens are stored in public.hmrc_user_tokens, associated with public.users.id, encrypted in the application with AES-256-GCM, and never stored in cookies or returned to the browser. The encryption key is configured as HMRC_TOKEN_ENCRYPTION_KEY, a base64-encoded 32-byte value held in deployment secrets—not in Supabase or source control. Every app instance that reads these tokens must use the same key. Keep the key stable; replacing it without first re-encrypting stored tokens makes them unreadable.
Every user-restricted HMRC API route gets its access token through getCurrentHmrcAccessToken. If expiry is within 60 seconds, it refreshes the token and stores both returned tokens before making the HMRC API call. A PostgreSQL row lock serializes refresh attempts for one user, so parallel requests cannot race with a single-use refresh token. GET /api/hmrc/userRestrictedAuth/refresh uses the same path; neither route nor helper returns token values to browser code.
If HMRC rejects a refresh token with invalid_grant, or a user-restricted HMRC API returns 401, the authorization is marked as requiring relinking, and the account page offers the link action again. Other refresh failures are returned as errors without discarding the stored tokens. The exact interpretation of HMRC's 18-month refresh-token lifetime is not inferred by the app; HMRC rejection is the signal to reauthorize.
Production OAuth review (10 November 2026)
The application currently uses HMRC Sandbox OAuth and API hosts only. The OAuth guide directs Production authorization through https://www.tax.service.gov.uk/oauth, and token/API requests through https://api.service.hmrc.gov.uk; Sandbox uses https://test-www.tax.service.gov.uk/oauth and https://test-api.service.hmrc.gov.uk. There is an official-documentation inconsistency: the current per-API OpenAPI security metadata lists https://api.service.hmrc.gov.uk/oauth/authorize as its authorizationUrl (and /oauth/refresh as refreshUrl), while the OAuth guide directs authorization to the tax-service host and refreshes through /oauth/token. The app currently follows the OAuth guide for Sandbox; do not infer a Production endpoint from either conflicting document without confirming with HMRC.
The app requests read:self-assessment write:self-assessment, the scopes listed by the Self Employment Business v5.0 OpenAPI security scheme, and uses the authorization-code grant with a short-lived state cookie. HMRC says the authorization code is single-use and must be exchanged within 10 minutes; access tokens last 4 hours, refresh tokens are single-use, and refresh tokens stop working after 18 months.
The current official user-restricted authorization guide says authorization lasts 18 months unless the user revokes access, but does not document an application token-revocation endpoint or request. This is not confirmation that HMRC offers no revocation facility; confirm the supported user-disconnection/revocation process with HMRC before Production. The application currently has no revoke operation. Token-key rotation also needs an explicit re-encryption procedure: the present token store only supports key version v1, so changing HMRC_TOKEN_ENCRYPTION_KEY without migrating stored tokens makes them unreadable.
Production use additionally requires HMRC's production credentials/access approval, exact registered redirect URI, production scopes, current API availability/version review, fraud-prevention review, and distinct Production configuration. No Production OAuth endpoints, credentials, approval, secret rotation, or live authorization have been configured or verified by this review. Do not switch the current Sandbox URLs by assumption.
Setup and rollout
Before deploying this flow:
- The connected Supabase database was checked on 7 November 2026:
public.hmrc_user_tokensexists with the expected columns, constraints, row-level security, and API-role privileges, andpublic.usersremains in place. Do not rerun the table creation SQL on that database. - The connected database's existing schema is captured in the baseline migration and recorded as applied in its migration history. The earlier token-table SQL is historical reference only; do not run it after the baseline.
- Configure the same base64-encoded 32-byte
HMRC_TOKEN_ENCRYPTION_KEYin each server environment sharing the token table. A key was created in this development environment's ignored.env, and the operator confirmed the same key is used on the Raspberry Pi. Confirm any other environments separately. Do not commit the value or generate a different key for an environment sharing the table. - Verify account-row creation, HMRC linking, a refresh near access-token expiry, refresh failure handling, and reuse from a second browser/device against Sandbox.
Existing browser-only token cookies cannot be safely migrated into the per-user token store. After the schema and key are configured, an existing linked user may need to authorize once more; subsequent logins and devices use the server-side account connection.
Raspberry Pi and Sandbox verification
The operator confirmed the Pi uses the same HMRC_TOKEN_ENCRYPTION_KEY as the development instance that uses the shared token table. Keep it in the Pi's protected PM2 deployment configuration. Do not print or paste the key into chat, commit it, generate a replacement, or place it in a shell command/history. If configuration changes, ensure the running process receives the configured value, restart or reload using the existing deployment procedure, and persist the PM2 configuration if appropriate. Do not expose PM2 environment output, which may contain secrets.
The operator confirmed that an existing HMRC Sandbox connection and its business list were available on a second browser/device without relinking. They also confirmed that the authenticated same-origin GET /api/hmrc/userRestrictedAuth/refresh forced a successful refresh and the business list remained available, and that the connection and business list remained available after more than four hours of inactivity across devices.
The operator signed up a new app account, saw it initially unlinked, linked a Sandbox test user, and loaded its business list. On switching accounts, both displayed their respective email, saved NI number and linked status. The operator also declined a new authorization for the linked account, received the expected failure message, and confirmed the existing connection and business list remained available. These observations do not independently verify the first-login database row, which HMRC identity a stored token belongs to, or financial-data isolation.
Both test users displayed the same business ID, consistent with the default simulated self-employment scenario described in HMRC's Business Details v2.0 Sandbox reference. Identical simulated business details do not by themselves establish that tokens or stored records are shared.
Do not alter stored tokens to force a failure; automated tests cover invalid_grant, but the declined-authorization test does not. A confirmed safe Sandbox refresh-failure scenario and its observable relink state still need end-to-end verification.
Production readiness
Before enabling live credentials, separately verify production OAuth endpoints, credentials, scopes, approved redirect URI, production access, revocation behavior, deployment secret configuration, and HMRC's current production requirements. Keep HMRC tokens out of logs, browser responses, ordinary exports, and source control. Supabase Free has no managed database backups for this project; configure encrypted off-site backups and test restores before storing customer records.
