Auth¶
Purpose¶
The auth domain owns every code path that produces a JWT or refresh token: registration, password login, social login (Google, Apple), WebAuthn (passkeys), OTP email verification, password reset, session listing, revocation, linked accounts and account invites. Five services compose together: AuthService does identity, SessionService does refresh tokens and session listing, OTPService does one-time codes for sensitive flows, LinkService does linked accounts, step-up and switching, and InviteService does invites into team account types. What each account type may do comes from the registry in backend/internal/access/accounttypes.go. SessionStore, LinkStore and InviteStore back them, and lean profile/account lifecycle reads come from the user domain.
Responsibilities¶
- Issue HS256-signed JWTs (
UserClaimspayload) and verify them on every protected request - Carry a
token_version(tv) revocation epoch in each JWT and reject tokens whose epoch is stale - Generate, validate, and revoke refresh tokens (web TTL is shorter than native)
- Verify Google ID tokens via
google.golang.org/api/idtoken - Verify Apple ID tokens by fetching and caching Apple's JWKS keys in Redis
- Handle Apple server-to-server consent-revoked / account-delete notifications
- Revoke the Sign in with Apple grant when an Apple-linked user deletes the account or disconnects Apple
- Run WebAuthn registration and login ceremonies (
github.com/go-webauthn/webauthn) - Generate and verify 6-digit OTP codes for
signup,password_reset,email_change,account_deletion, anddata_exportpurposes - Assemble the personal-data export (access and portability requests) from every domain's exporter
- Enforce device-fingerprint registration caps (max 3 accounts/device, 30-day Redis window)
- Reject disposable email domains and accounts under 18
- Record login attempts and expose login history
- List, revoke single, and revoke-all sessions
HTTP endpoints¶
Routes register through the functions in backend/internal/services/auth/routes.go; rate-limit and JWT gates are passed in as func(http.Handler) http.Handler middleware so the package never imports middleware. Composition lives in backend/internal/wiring/router.go.
Public¶
| Method | Path | Description |
|---|---|---|
| POST | /api/v1/auth/register |
Email/password registration (rate-limited). Requires accepted_terms_version + acknowledged_privacy_version from GET /auth/legal/versions (see Policy acceptance) |
| POST | /api/v1/auth/login |
Email-or-username + password (rate-limited). Account types that need a code answer 202 with a challenge |
| POST | /api/v1/auth/login/code |
Challenge + emailed code, the second step for those account types |
| POST | /api/v1/auth/google-login |
Google ID token exchange |
| POST | /api/v1/auth/apple-login |
Apple ID token exchange (verifies via Apple JWKS) |
| POST | /api/v1/auth/refresh |
Exchange refresh token for a new access token |
| POST | /api/v1/auth/logout |
Revoke the current refresh token |
| POST | /api/v1/auth/reset-password |
Finish OTP-verified password reset (requires otpToken) |
| POST | /api/v1/auth/otp/send |
Send a 6-digit code to email |
| POST | /api/v1/auth/otp/verify |
Verify code, return short-lived otpToken JWT |
| POST | /api/v1/auth/webauthn/login/begin |
Start passkey login ceremony |
| POST | /api/v1/auth/webauthn/login/finish |
Finish passkey login |
| POST | /api/v1/auth/apple/notifications |
Apple S2S notifications (ES256-signed; no JWT) |
| GET | /.well-known/webauthn |
RPID-allowed origins for related-origin requests |
Authenticated (reachable before email verification)¶
| Method | Path | Description |
|---|---|---|
| GET | /api/v1/auth/profile |
Current user |
| PATCH | /api/v1/auth/profile |
Update profile fields. The request that first sets date_of_birth completes the profile and carries the clickwrap unless the current versions are already on file |
| DELETE | /api/v1/auth/profile |
Soft-deactivate account (30-day grace). Re-authenticates: body carries password, or otp_token for accounts without a password. Optional apple_authorization_code revokes the Apple grant |
| POST | /api/v1/auth/export-data |
Download the caller's personal data as one JSON attachment. Same re-auth body as deletion (OTP purpose data_export); 5 per account per day |
| POST | /api/v1/auth/link/google |
Connect a verified Google identity to the current account |
| POST | /api/v1/auth/link/apple |
Connect a verified Apple identity to the current account |
| DELETE | /api/v1/auth/link/google |
Disconnect Google (refused if it is the only sign-in method) |
| DELETE | /api/v1/auth/link/apple |
Disconnect Apple (refused if it is the only sign-in method). Optional body apple_authorization_code revokes the Apple grant |
| POST | /api/v1/auth/email/change |
Begin email-change flow (sends OTP to new email) |
| POST | /api/v1/auth/email/change/confirm |
Confirm email change with the code |
| GET | /api/v1/auth/sessions |
List active sessions |
| DELETE | /api/v1/auth/sessions/{id} |
Revoke a single session |
| DELETE | /api/v1/auth/sessions/all |
Sign out everywhere |
| GET | /api/v1/auth/login-history |
Recent login attempts (success + failures) |
| GET | /api/v1/auth/legal/status |
Whether the current Terms + Privacy versions are on file (accepted, pending, current) |
| GET | /api/v1/auth/legal/versions |
Public. Policy versions in force and upcoming |
| GET | /api/v1/auth/links |
The caller's linked accounts, each with its surface and how to switch in |
| POST | /api/v1/auth/step-up/begin |
Open a re-authentication challenge (switch with an account_id, sensitive with the capability it is for, or link). A sensitive token is accepted only by that capability's routes |
| POST | /api/v1/auth/step-up/finish |
Verify the password or passkey; returns a single-use step-up token |
| POST | /api/v1/auth/links/personal |
A Tomoda account links a personal account: link step-up plus any normal sign-in of the personal account (email or username and password, or a Google or Apple ID token); creates the link, audits it, emails the personal account and returns its session |
| DELETE | /api/v1/auth/links/personal |
A Tomoda account removes its own link with a fresh link step-up |
| POST | /api/v1/auth/links/{id}/switch |
Spend the token when the policy needs one; returns a session for the linked account |
| POST | /api/v1/auth/invites/preview, /send-code, /accept |
Optional JWT. Accept an account invite, linked when signed in on a standard account |
These follow the account type registry (backend/internal/access/accounttypes.go); the rules are in Authentication → Account type policies. LinkService implements links and switching (link_service.go), step-up (link_stepup.go), linked-account creation (link_accounts.go) and LinkPersonal/UnlinkPersonal (link_personal.go) over LinkStore (account_links); InviteService (invite_service.go) implements invites over InviteStore (account_invites).
Verified account required¶
| Method | Path | Description |
|---|---|---|
| PUT | /api/v1/auth/profile/password |
Change password (requires current) |
| PUT | /api/v1/auth/profile/name |
Change display name (14-day cooldown) |
| PUT | /api/v1/auth/profile/username |
Change username (uniqueness checked) |
| POST | /api/v1/auth/webauthn/register/begin |
Enroll a passkey (challenge) |
| POST | /api/v1/auth/webauthn/register/finish |
Enroll a passkey (attestation) |
| PUT | /api/v1/users/me/avatar |
Set avatar to a freshly-uploaded key (post-presign confirm). Body: { "key": "avatars/..." }. See storage for the presigned PUT flow. |
| DELETE | /api/v1/users/me/avatar |
Clear the avatar. Idempotent; old object enqueued for async delete. |
Key types¶
type UserClaims struct {
jwt.RegisteredClaims
UserID uuid.UUID
Email string
Role models.UserRole // "base" | "admin" | "curator" | "auditor" | "operator" | "support" | "developer"
AccountType models.AccountType // "standard" | "tomoda" | "synthetic" | "partner" | "external-curators"
EmailVerified bool // always true post-OTP; kept for old-token compat
TokenVersion int64 // "tv": revocation epoch stamped at sign time
}
AuthService (backend/internal/services/auth/auth_service.go) depends on the user domain's UserStore, UserService, and ProfileStore, the local SessionService, platform/cache, platform/assets, platform/email, the AppleTokenRevoker port (deps.go, backed by platform/appleid), and the JWT/Google/Apple/WebAuthn config blocks.
SessionService (session_service.go) exposes GenerateRefreshToken, ValidateRefreshToken, RevokeRefreshToken, RevokeAllUserTokens, GetUserSessions, RevokeSession, RecordLoginAttempt, GetLoginHistory, CheckLoginRateLimit, and CleanupExpiredTokens.
OTPService (otp_service.go) exposes SendOTP(email, purpose), VerifyOTP(email, code, purpose) (otpToken, err), and ValidateOTPToken(token, purpose) (email, err). An otpToken is bound to the purpose it was verified for: reset-password accepts only password_reset tokens, account deletion only account_deletion tokens, and the data export only data_export tokens. SendOTP wraps an email provider failure in ErrOTPDelivery, which the send handlers answer as 503 OTP_SEND_FAILED (retryable, provider detail logged only); any other failure is a logged 500.
Signup sends and email-change requests to an address that already has an account (active, suspended or pending deletion) get 409 with CodeEmailAlreadyExists (email_already_exists), before any code is issued. Password-reset sends answer 200 for an unknown address. The full status table is in Auth Endpoints.
JWT validation¶
Access tokens are JWTs signed with HS256 using JWTConfig.Secret (backend/config.yaml, env override JWT_SECRET). The library is github.com/golang-jwt/jwt/v5. AuthService.ValidateToken rejects anything not signed with HMAC and returns typed UserClaims.
The JWTAuth middleware in backend/internal/middleware/auth.go then does two things on every protected request:
- Puts
user_id,email, andemail_verifiedonto the request context (api.WithIdentity) for downstream handlers, read viaapi.UserID(r),api.Email(r),api.EmailVerified(r). - Compares the token's
TokenVersionagainst the user's currenttoken_version(viaAuthService.CurrentTokenVersion) and confirms the account is still usable (AuthService.AccountUsable). A mismatch or an inactive account is rejected even though the signature is valid. Both checks fail open on a transient infrastructure error and fail closed only on a real signal (a version mismatch, or a missing/inactive account row, detected viaauth.IsUserNotFound), so a DB or Redis blip cannot sign every active user out.
JWTs may be presented two ways:
Authorization: Bearer <token>— normal REST requests.?token=<token>, only on/ws/*WebSocket upgrades, since browserWebSocketconstructors cannot set headers. The middleware checks the header first and falls back to the query string only on those paths. Any other route ignores a query token (JWTAuthreturns 401,OptionalJWTAuthtreats the caller as anonymous), so a token never needs to appear in a REST URL.
token_version is the global revoke lever
AuthService.BumpTokenVersion increments users.token_version, invalidating every outstanding JWT for the user at once. Password reset, revoke-all-sessions, and account suspend/delete call it. Per-device logout instead deletes the single refresh token; the access token expires on its own.
Refresh-token flow¶
Refresh tokens are opaque, server-issued strings (256 random bits). Only their hex SHA-256 is stored: refresh_tokens.token_hash and sessions.refresh_token_hash in Postgres, and the Redis mirror key refresh_token:<sha256(token)>. hashRefreshToken in session_service.go is the one hash function for all three. Refresh, logout and session lookup hash the presented token and match on the hash, so a database dump, a backup or a keyspace read (SCAN, MONITOR, the slowlog, an RDB snapshot) yields no usable credential. They are issued alongside every successful login. The session is sliding: each use updates last_used_at and extends expires_at (and the Redis mirror's TTL) by a full inactivity window, native 180 days and web 30 days, clamped to an absolute lifetime of one year from created_at. An actively-used app re-authenticates once a year, a device left idle for the whole window lapses sooner, and a token past the cap is rejected and deleted.
POST /auth/refresh
refresh_token:<sha256>
refresh_tokens (UPDATE last_used_at)
back to client
last_used_at.ValidateRefreshToken returns ErrRefreshTokenInvalid for an unknown, expired or revoked token (or a deleted user), which the handler answers as 401. Any other store error is transient and returns 503 SERVICE_UNAVAILABLE, so a database blip never signs a client out.
On the client side, frontend/utils/tokenManager.ts schedules a check every 4 minutes via setupTokenRefresh; if isTokenExpiringSoon reports less than 5 minutes of life left, it calls refreshAccessToken, which shares apiFetch's single-flight refreshOnce with reactive 401 refreshes. Only a refused refresh (401/403) emits AUTH_SESSION_EXPIRED, which AuthContext turns into logout(). See Frontend API Client.
Sessions and revocation¶
sessions rows track per-device login state. They are listed via GET /auth/sessions and revoked individually (DELETE /auth/sessions/{id}) or in bulk (DELETE /auth/sessions/all). Revocation deletes both the session row and its refresh token, in Postgres and in Redis.
POST /auth/logout deletes the caller's refresh token, and the client clears its local AsyncStorage keys (@auth_token, @refresh_token, @auth_user). A login_history row is appended on each login and surfaced via GET /auth/login-history.
Policy acceptance¶
Users accept the Terms once, at signup. Later versions bind through notice: they are announced by email at least 30 days before they take effect, and continued use after the effective date is acceptance. A user who disagrees deletes the account.
Policy versions live in one manifest, backend/internal/models/legal_manifest.json: each document has an ordered list of versions with version and last_updated (both the release day, YYYY-MM-DD, which the document prints as "Last updated"), plus a notice block ({"summary": "..."}, one short, general sentence of at most 200 characters, plus the required summary_translations, one per LANGUAGES code other than en-US) for a material change. A change merges as an unreleased entry with no version or last_updated (at most one per document, and last), with the document reading **Last updated: unreleased**; the release's cut job stamps both with the release day (scripts/release/stamp-legal-release.sh). Unreleased entries are ignored everywhere. There is no written effective date. It is derived on load: last_updated for a minor change, last_updated plus 30 days (models.LegalNoticePeriod) for a version with a notice, start of day UTC, and never earlier than the previous version's, so a minor fix released inside a pending notice window takes effect together with the material change. Released last_updated dates must strictly increase. The server is the authority: GET /auth/legal/versions (public) and GET /auth/legal/status report the version in force (current) and the next version to take effect (upcoming, the newest of any sharing that date), each with its derived effective_at, and signup posts back what the server reported.
- Signup clickwrap. The user ticks "I agree to the Terms of Service"; a separate line links the Privacy Policy. The request carries
accepted_terms_versionandacknowledged_privacy_version, each the current or upcoming version, otherwise400 LEGAL_ACCEPTANCE_REQUIRED(the client refetches the versions). Email signup (POST /auth/register) writes the user, its profile and twolegal_acceptancesrows (Termsaccepted, Privacyacknowledged) in one transaction (LegalStore.CreateAccount). Social signup carries the same fields on profile completion, thePATCH /auth/profilethat first setsdate_of_birth, only when the account has no Terms acceptance (previously_acceptedon the status). - Notice ahead of a change. When
legal.policy_notices_enabledis set (prod only), every async worker computes the pending notices at startup: per document, the newest released version with anoticeblock whose effective time is in the future, grouped by effective time into one email each, keeping only notices with someone left to notify. Each group is enqueued as alegal:policy_noticetask with the deterministic task idlegal-notice:{doc@version,...}, so all pods enqueue it once. The handler (LegalNotifier.Send) pages through every live, non-suspended, non-synthetic account with an email that has nolegal_acceptancesrow for some listed version. Per user it inserts anotifiedrow for each version the user lacks (skipping any the user already holds, accepted or notified), mails those documents in one email, and deletes the rows it just inserted if the send fails, so a retry or a later re-enqueue mails only users not yet sent. Sends are paced atlegal.policy_notice_rate(default 4 per second); failures make Asynq retry.tomoda_legal_notice_emails_total{notice,outcome}counts sent, failed and skipped recipients. The email (email.Service.SendPolicyUpdateEmail) goes out in the member's saved language (see email localization) and names the updated documents, the effective date and the summary, links each document, says continued use on or after that date means the update applies, notes in small print that the account can be managed in the app under Hub → Account (linked to/hub/account), and ends with the support address. - Changing a policy. Edit the text in the operations repo with
**Last updated: unreleased**, copy the five files intofrontend/content/legal/, and append an unreleased manifest entry:{}for a minor change,{"notice": {"summary": "..."}}for a material one. The release stamps the date; a minor change takes effect on the release day and a material one 30 days later, and its notice goes out when the prod workers start on that release. The operations text gets the stamped date in a follow-up.scripts/ci/check-legal-sync.sh,TestLegalManifest_MatchesBundledDocsand the vitest version test fail when a bundled document's "Last updated" line and the newest manifest entry disagree (a date for a released entry,unreleasedfor an unreleased one). - New consent. A change that adds processing needing consent (new tracking, marketing, new sharing) gets its own opt-in for that feature; policy acceptance is not consent for it.
- Records. Acceptances and notices appear in the user's data export (
security.legal_acceptances, withkindaccepted,acknowledgedornotified; anotifiedrow is the policy-change email, sent ataccepted_at, and carries no IP or user agent). Only anacceptedTerms row counts as acceptance (previously_accepted); a later acceptance of the same version replaces anotifiedrow. Deactivation leaves them intact (the account can be restored for 30 days); the hard purge deletes them with the user.
Account lockout¶
Password login carries a per-account failure budget on top of the per-IP LoginLimit() (see rate limiting), since a spray that rotates IPs never trips the per-IP limiter. AuthService.Login asks SessionService.CheckLoginRateLimit before comparing the password. Five counted failures in the last 15 minutes lock the account, and every attempt, including the correct password, gets 429 with ErrAccountLockedOut until fewer than five remain in the window.
The count comes from login_histories (CountFailedLoginAttempts):
- A wrong password records
fail_reason = "invalid password"and counts. - An attempt refused by the lockout records
fail_reason = "account locked out"for the audit trail, but does not count. Retries against a locked account therefore can't extend the lockout, and it lifts once the wrong passwords age out of the 15-minute window. - A successful login (any method) resets the budget. Failures recorded before it stop counting.
Unknown emails and usernames return 401 invalid credentials before the lockout check and record nothing, so they never spend any account's budget.
End-to-end: Google login + first profile complete¶
native Google Sign-In
id_token
idtoken.Validate, aud ∈ client IDs
FindByEmail or Create
signed JWT
refresh_token:<sha256>
@auth_token, @refresh_token, @auth_user
After the bearer is set, JWTAuth middleware governs every subsequent call uniformly.
Social identity verification & linking¶
The trust boundary is the provider token, never client-sent profile fields. The Google and Apple verifiers live in auth_service.go (verifyGoogleIDToken, verifyAppleIDToken) and are shared by the login and link paths.
- Google verifies signature,
iss, andexpviaidtoken.Validate, then checksaudagainst every shipped client ID:GOOGLE_CLIENT_ID(web, may also be comma-separated),GOOGLE_IOS_CLIENT_ID, andGOOGLE_ANDROID_CLIENT_ID. All three are projected from GCP Secret Manager in dev and prod. Empty config fails closed. - Apple parses the identity token with
jwt.WithValidMethods(["RS256"]),jwt.WithIssuer(appleIssuer), andjwt.WithExpirationRequired(), thenverifyAppleAudiencechecksaudagainst the configured Bundle ID / Services ID. Unconfigured audience fails closed (APPLE_CLIENT_ID/APPLE_SERVICE_IDmust be set).
Config is required, not optional
Both providers now fail closed. If GOOGLE_CLIENT_ID omits a shipped client ID, tokens minted under it are rejected; if the Apple audience env vars are unset, Apple login refuses. Set all client IDs in every environment.
Linking is keyed on the provider subject, never the email. A social login resolves an account only by google_id / apple_id. If the identity is unknown but its email already belongs to an account, the login returns 409 SOCIAL_LINK_REQUIRED rather than silently merging (that would be an account-takeover vector). To connect a provider after signup, the authenticated POST /auth/link/{google,apple} endpoints attach the verified identity to the current account, refusing with SOCIAL_ALREADY_LINKED (identity belongs to another account) or SOCIAL_LINK_CONFLICT (this account already has a different identity for that provider). A user can link both Google and Apple.
Every login method finishes in finalizeLogin. Password, Google, Apple, and passkey logins all hand the resolved account to finalizeLogin, which refuses inactive accounts and suspended ones (403 ACCOUNT_SUSPENDED with the suspension and, while a review request is open to them, a single-purpose review token, see Report service), reactivates an account inside its deactivation grace period, issues the tokens, and writes the login_histories row. A new social account also passes the device cap (3 accounts per device fingerprint) and, when the provider supplies a birthdate, the 18+ check; an account created without a birthdate stays behind RequireAgeVerified until one is recorded. The DELETE variants disconnect a provider, refused with LAST_LOGIN_METHOD if it would leave the account with no way to sign in (no password, passkey, or other linked provider).
Data model¶
| Table | Used for |
|---|---|
users |
Identity, OAuth IDs (google_id, apple_id), password hash, role, token_version, deactivated_at |
refresh_tokens |
Long-lived tokens, stored and uniquely indexed by token_hash (hex SHA-256) |
sessions |
One row per active device, denormalises device_info + ip + last_active_at; linked to its token by refresh_token_hash |
login_history |
Audit trail of every login attempt (method, success, fail_reason, ip) |
web_authn_credentials |
Passkey credentials per user |
otps |
Short-lived 6-digit codes with a purpose discriminator and used flag |
legal_acceptances |
One row per user, policy document and version: accepted or acknowledged (with the request IP and user agent), or notified when the policy-change email was sent |
Toggleable account preferences (is_location_shared, marketing_consent, notifications_enabled, language, chat/map prefs) live on user_profiles, not users. See user.
Dependencies¶
- user domain —
UserStore,UserService(deactivate/reactivate hook),ProfileStore platform/cache— Apple JWKS cache, refresh-token cache, device fingerprint counters, WebAuthn session blobs, email-change verificationplatform/email— welcome email, OTP email, deactivation email, account-linked notice, policy notice, each in the member's languageplatform/assets— avatar finalize with old-object cleanupplatform/appleid— Sign in with Apple token exchange and revocationSessionStore: persistence for sessions and refresh tokens
Notable behavior¶
OTP-first signup
Email verification is not a separate token flow. Registration sets email_verified = true because callers complete OTP verification before posting /auth/register.
Account deletion re-authenticates
DELETE /auth/profile is not satisfied by the bearer alone. confirmIdentity requires the account password when the account has one, and an otp_token (purpose account_deletion, proving control of the address) when it does not. A missing or wrong credential returns 401 REAUTH_FAILED (the data export does the same), a code clients never read as an expired session. Clients read has_password on the user payload to decide which credential to collect.
Data export re-authenticates and reads every domain
POST /auth/export-data goes through the same confirmIdentity gate, with OTP purpose data_export. platform/dataexport runs one Exporter per domain (wired in ProvideDataExportService, internal/wiring/providers.go); each owns an ExportUser* query in its queries.sql that builds its section as JSON with an explicit column list, so a new column stays out until someone adds it. A domain that starts storing user data registers its exporter there. Any exporter error fails the whole export rather than returning a partial copy.
The bundle carries schema_version, generated_at, data (one key per section) and media (each referenced storage key with a short-lived signed URL from assets.Service.URLFromKey). Never exported: password hash, reset and refresh tokens, token version, push token values, passkey key material, payment processor and OAuth subject ids (providers appear by name), event access codes, plan share tokens, notification actor previews and payloads, and other people's messages or names (other users appear as id and handle). Each export writes an export audit row; the per-account limit is DataExportLimit (data_export_user:{user_id}).
Adding a domain exporter. Export only what the user would recognise as their own data, what they provided or that is plainly about them (account, profile, content they created, messages they sent, social graph, consents, location they shared). Leave out derived or internal signals (ranking affinity, interaction weights, the activity firehose), shared reference or catalogue data that is not about the user, secrets, and any other person's data beyond their id and handle. Saved and derived place data is treated as internal, not personal export data.
Account reactivation on login
finalizeLogin detects DeactivatedAt != nil and reactivates the account within the 30-day grace window before issuing tokens. Beyond 30 days the user is hard-deleted by the scheduled purge job (see user).
Refresh-token TTL by account and client
refreshPolicyFor picks the window and cap. Tomoda accounts (tomoda) chains get a 2-hour window and a 12-hour cap; otherwise the User-Agent decides: browsers (mozilla, chrome, safari, etc.) get a 30-day window, native clients 180 days, both capped at a year. ValidateRefreshToken re-applies the policy from the account type on every use. The same expiry is mirrored into Redis under refresh_token:<sha256(token)>.
Password reset (OTP flow)¶
purpose=password_reset
6-digit code
15-min JWT
otpToken + newPassword
ValidateOTPToken → bcrypt → Update → BumpTokenVersion
The OTP is stored in otps with a 10-minute TTL; the returned otpToken JWT lives 15 minutes. A successful reset terminates every existing session.
OTP tokens are not access tokens
An otpToken carries sub: otp_verification, aud: tomoda-otp, a purpose claim and an expiry, and is signed with a key derived from the JWT secret (HMAC-SHA256(secret, "tomoda/otp-token/v1")). ValidateOTPToken requires all of them, so an access JWT is never accepted where an OTP token is expected. ValidateToken (used by JWTAuth and OptionalJWTAuth) rejects any token with the OTP subject or audience, or without a user_id.
Password changes end every session¶
Both UpdatePassword (in-session, re-authenticates with the current password) and ResetPassword (OTP-gated) finish with TerminateUserSessions: refresh tokens and session rows are deleted, then token_version is bumped to kill live access JWTs.
The caller's own session is not spared. token_version is a single per-user epoch, so it cannot express "every session but this one"; sparing the current device would need a per-session revocation primitive and a session identifier in the JWT, neither of which exists. Bumping token_version alone would also be insufficient, because ValidateRefreshToken does not consult it, so an attacker's refresh token would survive and mint a fresh access JWT. Clients should expect a 401 on the next request after a password change and re-authenticate.
Apple S2S notifications¶
HandleAppleNotification hands the raw payload to VerifyAppleNotification, which parses it as an ES256 JWT against the JWKS key named by its kid (GetApplePublicKeyEC) and rejects anything failing the signature, iss (https://appleid.apple.com), aud (configured Bundle ID or Services ID), or expiry checks. Only then is the events claim decoded, and on consent-revoked / account-delete it invokes DeactivateUserByAppleID, which triggers the standard 30-day purge path.
The kid does not authenticate the payload
Apple's JWKS keys are public and the kid is attacker-supplied, so resolving a key proves nothing on its own. Only the signature binds the claims to Apple. Since the endpoint is unauthenticated and its effect is account deactivation, the signature check is the sole gate.
The handler always answers 200 (Apple retries any non-2xx) and logs rejections rather than surfacing them.
Apple token revocation¶
App Store review requires an app offering Sign in with Apple to revoke the user's Apple tokens when the account is deleted. The server stores no Apple token, so the iOS app runs Apple sign-in again just before the request and sends the fresh authorization code as apple_authorization_code on DELETE /auth/profile and DELETE /auth/link/apple. After re-authentication (delete) or the last-method check (unlink), revokeAppleGrant hands the code to platform/appleid, which signs an ES256 client-secret JWT (iss team id, sub bundle id, kid key id, five-minute expiry), redeems the code at https://appleid.apple.com/auth/token, and revokes the returned refresh token at /auth/revoke. Before revoking it decodes the returned id_token (no signature check: it arrives directly from Apple's token endpoint over TLS) and requires iss https://appleid.apple.com, aud the bundle id, and sub equal to the user's apple_id; a missing token or any mismatch skips the revoke.
Revocation is best effort and never blocks the delete or unlink: a missing code is skipped, an unconfigured client or a code for another Apple user logs a warning, and an Apple error is logged with the user id. Web and Android send no code; Apple's own account-delete and consent-revoked notifications still reach the S2S handler.
Configuration
Revocation needs APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_CLIENT_ID and APPLE_AUTH_KEY_P8. The key is a Sign in with Apple private key created under Certificates, Identifiers & Profiles → Keys in the Apple Developer portal (enable Sign in with Apple, primary App ID the iOS bundle). Store the downloaded .p8 contents in the tomoda-apple-auth-key-p8 secret and its key id in tomoda-apple-key-id; see Secrets management. Without the key, the client stays unconfigured and revocation is skipped.
Where to look¶
backend/internal/services/auth/auth_service.go— identity, OAuth verifiers, token generation,token_versionbackend/internal/services/auth/session_service.go— refresh tokens, sessions, login historybackend/internal/services/auth/otp_service.go— OTP codes + otpToken JWTbackend/internal/services/auth/auth_handler.go,session_handler.go— HTTP surfacebackend/internal/services/auth/routes.go— route registration (gates injected)backend/internal/middleware/auth.go— JWT validation +token_versioncheckbackend/internal/middleware/rate_limiter.go—RegisterLimit,LoginLimit,ResetPasswordLimit