Files
Andrew Beveridge ☄️andClaude Opus 5.5 695b8ddf84 feat: mobile app backend — handoff token, app checkout return, Google/Apple sign-in (v0.278.0) (#1178)
## Summary
Backend support for the Nomad Karaoke mobile app (nomad-mobile Phase 1,
"Make it").

- **`POST /api/users/auth/handoff-token`**: the app opens a job's web
review already signed in. The token is a single-use, 120s
`job_review:<id>` magic link, returned as
`{FRONTEND_URL}/{locale}/auth/verify?token=…&handoff=1`.
- The verify page skips the "Complete Sign-In" tap only when the URL has
`handoff=1` **and** the server confirms the token was minted as a
handoff (`link-status` → `handoff: true`). Emailed links keep the
scanner guard.
  - The web locale is validated against the 33 web locales.
- **Checkout `return_to: "app"`**: Stripe success and cancel go to `GET
/api/users/credits/app-return`, which 302s to
`nomadkaraoke://checkout?status=success|cancelled`.
  - The client never supplies a URL, so this adds no open redirect.
  - `session_id` is never forwarded.
- **`POST /api/users/auth/google` and `/auth/apple`**: ID-token sign-in
(PyJWT + JWKS: RS256, issuer, audience, expiry, `email_verified`). It
returns the same `VerifyMagicLinkResponse` as email-code sign-in,
through a shared `finish_verified_sign_in`.
- Email-code, Google and Apple all share the same abuse checks
(`_sign_in_checks`).
  - A JWKS outage returns 503 `identity_provider_unavailable`.
- Google audiences default to the new mobile web and iOS OAuth clients,
which are recorded in ARCHITECTURE.md.
- **Job summary** now includes `credit_refunded`.
- **Local stack:**
- fake-config `search_confidence` (perfect / recommended / unsure), with
a drift guard tied to the frontend `getSearchConfidence`
  - `youtube_url_enabled`
  - `fake:<email>` social tokens, accepted only in fake mode
- PyJWT is now a direct dependency (`pyjwt[crypto]`). Before this it was
only present transitively.
- Version 0.278.0.

## Testing
- `make test` is green:
  - CLI: 2088 passed
  - backend unit: 6360 passed
  - emulator: 156 passed, plus 4 handoff lifecycle tests
  - frontend jest: 1751 passed
- New suites:
  - `test_handoff_token.py`
  - `emulator/test_handoff_token_lifecycle.py`
  - `test_checkout_app_return.py`
  - `test_social_signin.py`
  - `test_magic_link_status.py`
  - `fake-search-tiers.test.ts`
  - verify-page tests
- Reviews:
- An independent code review was approved, and its hardening suggestions
were applied.
  - A local CodeRabbit review found nothing.

Plan: `docs/archive/2026-10-17-mobile-app-auth-handoff-plan.md`. Spec:
nomad-mobile
`docs/superpowers/specs/2026-10-17-mobile-phase1-make-it-design.md`.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_011yLH4kWXMqjeKfZUG3ZiWZ

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 04:03:05 -04:00

145 lines
4.8 KiB
Python

"""
Lightweight i18n utility for backend translations.
Usage:
from backend.i18n import t, get_locale_from_request, SUPPORTED_LOCALES
# In a route handler:
locale = get_locale_from_request(request)
message = t(locale, "auth.userNotFound")
message = t(locale, "jobs.notFound", job_id="abc123")
"""
import json
from functools import lru_cache
from pathlib import Path
from typing import Any
from starlette.requests import Request
SUPPORTED_LOCALES = ("en", "es", "de")
# Every locale the web app serves (frontend/i18n/routing.ts, frontend/messages/*.json;
# a test keeps them in sync). Use for web URL prefixes; SUPPORTED_LOCALES is the
# backend's own (email / API message) translations.
WEB_LOCALES = (
"en", "es", "de", "pt", "fr", "ja", "ko", "zh", "it", "nl",
"pl", "tr", "ru", "th", "id", "vi", "tl", "hi", "ar", "sv",
"nb", "da", "fi", "cs", "ro", "hu", "el", "he", "ms", "uk",
"hr", "sk", "ca",
)
DEFAULT_LOCALE = "en"
TRANSLATIONS_DIR = Path(__file__).parent / "translations"
@lru_cache(maxsize=len(SUPPORTED_LOCALES))
def _load_translations(locale: str) -> dict[str, Any]:
"""Load and cache translation file for a locale."""
path = TRANSLATIONS_DIR / f"{locale}.json"
if not path.exists():
if locale != DEFAULT_LOCALE:
return _load_translations(DEFAULT_LOCALE)
return {}
with open(path, encoding="utf-8") as f:
result: dict[str, Any] = json.load(f)
return result
def t(locale: str, key: str, **kwargs: Any) -> str:
"""Get a translated string by dotted key path.
Args:
locale: Language code (en, es, de)
key: Dotted path like "auth.userNotFound" or "emails.magicLink.subject"
**kwargs: Interpolation variables (e.g., job_id="abc123")
Returns:
Translated string with variables interpolated, or the key itself if not found.
"""
if locale not in SUPPORTED_LOCALES:
locale = DEFAULT_LOCALE
translations = _load_translations(locale)
# Walk the dotted path
value: Any = translations
for part in key.split("."):
if isinstance(value, dict) and part in value:
value = value[part]
else:
# Key not found — fall back to English
if locale != DEFAULT_LOCALE:
return t(DEFAULT_LOCALE, key, **kwargs)
return key # Return the key itself as last resort
if not isinstance(value, str):
return key
result: str = value
# Interpolate variables
if kwargs:
try:
result = result.format(**kwargs)
except KeyError:
pass # Missing variable — return template as-is
return result
def get_locale_from_request(request: Request) -> str:
"""Extract locale from Accept-Language header.
Returns the first supported locale found, or DEFAULT_LOCALE.
"""
accept_lang = request.headers.get("accept-language", "")
# Simple parsing — Accept-Language can be "de", "de-DE", "en-US,en;q=0.9,de;q=0.8"
for part in accept_lang.split(","):
lang = part.split(";")[0].strip().split("-")[0].lower()
if lang in SUPPORTED_LOCALES:
return lang
return DEFAULT_LOCALE
def get_full_locale_from_request(request: Request) -> str | None:
"""Extract the user's actual UI language tag from Accept-Language.
Unlike :func:`get_locale_from_request`, this does NOT narrow to the 3
email-supported locales (en/es/de). It returns the primary language subtag
of the first entry in the header (e.g. ``pt``, ``ja``, ``zh``) so the admin
UI can show the real language a customer was using the product in.
Returns the lowercased language subtag, or ``None`` if the header is absent
or unparseable.
"""
accept_lang = request.headers.get("accept-language", "")
for part in accept_lang.split(","):
# Each part looks like "en-US;q=0.9" — take the language-region token
# before the quality factor, then the primary subtag before any region.
segments = part.split(";")
token = segments[0].strip()
if not token or token == "*":
continue
# Skip ranges the client explicitly rejects with q=0.
if any(seg.strip().lower().replace(" ", "") in ("q=0", "q=0.0", "q=0.00", "q=0.000")
for seg in segments[1:]):
continue
lang = token.split("-")[0].strip().lower()
if lang.isalpha() and len(lang) >= 2:
return lang
return None
def get_web_locale_prefix(locale: str) -> str:
"""Web URL locale prefix for any of the web app's locales (fallback '/en')."""
return f"/{locale if locale in WEB_LOCALES else DEFAULT_LOCALE}"
def get_locale_prefix(locale: str) -> str:
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
if locale not in SUPPORTED_LOCALES:
locale = DEFAULT_LOCALE
return f"/{locale}"