diff --git a/backend/api/routes/kjbox.py b/backend/api/routes/kjbox.py index 29542dad..5be053f2 100644 --- a/backend/api/routes/kjbox.py +++ b/backend/api/routes/kjbox.py @@ -10,6 +10,8 @@ is configured — deploys dark; 403 if wrong). Contract: - POST /api/kjbox/auth/send-code {email, locale?, venue?} → {"status": "sent"} - POST /api/kjbox/auth/verify-code {email, code} → {session_token, user, credits_granted, credit_status} +- POST /api/kjbox/auth/google | apple {id_token, locale?, venue?} → same as + verify-code (one-tap sign-in in the singer page) - POST /api/kjbox/credits/show-credit (+ Authorization: Bearer ) {idempotency_key, venue?, only_if_empty?} → {granted, credits} @@ -123,6 +125,14 @@ class VerifyCodeRequest(BaseModel): code: str = Field(max_length=32) +class SocialSignInRequest(BaseModel): + # Google Identity Services / Sign in with Apple JS ID token from the singer page + # (or ``fake:`` on the local stack). + id_token: str = Field(min_length=1, max_length=8192) + locale: Optional[str] = None + venue: Optional[str] = Field(default=None, max_length=_MAX_VENUE_LEN) + + class VerifyCodeResponse(BaseModel): session_token: str user: dict @@ -272,27 +282,35 @@ def verify_code( if outcome != VerifyOutcome.OK or record is None: raise HTTPException(status_code=401, detail="expired") - user = user_service.get_user(email) - if user is None: - # No signup_ip: the caller is the kjbox box, whose IP is the whole - # venue's — recording it would trip gen's per-IP cap for everyone there. - user = user_service.get_or_create_user( - email, signup_source=SIGNUP_SOURCE, signup_venue=record.get("venue"), - ) - svc.record_signup(email, record.get("venue")) - logger.info(f"kjbox: created verified gen user {_mask_email(email)} (venue={record.get('venue')!r})") - # Same first-login definition as magic-link verify (checked before last_login_at is set). - is_first_login = user.total_jobs_created == 0 and not user.last_login_at - user = user_service.update_user( - email, email_verified=True, last_login_at=datetime.utcnow(), - ) or user - precomputed_eval = { k: record.get(k) for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error") if record.get(k) is not None } or None - email_locale = record.get("locale") + return _finish_sign_in( + email, http_request, svc=svc, user_service=user_service, email_service=email_service, + venue=record.get("venue"), email_locale=record.get("locale"), + ui_locale=record.get("ui_locale"), precomputed_eval=precomputed_eval, how="verified", + ) + + +def _finish_sign_in(email, http_request, *, svc, user_service, email_service, venue, + email_locale, ui_locale, precomputed_eval, how): + """A proven email (code, or a Google/Apple ID token) → the singer's gen session.""" + user = user_service.get_user(email) + if user is None: + # No signup_ip: the caller is the kjbox box, whose IP is the whole + # venue's — recording it would trip gen's per-IP cap for everyone there. + user = user_service.get_or_create_user( + email, signup_source=SIGNUP_SOURCE, signup_venue=venue, + ) + svc.record_signup(email, venue) + logger.info(f"kjbox: created verified gen user {_mask_email(email)} (venue={venue!r}, via {how})") + # Same first-login definition as magic-link verify (checked before last_login_at is set). + is_first_login = user.total_jobs_created == 0 and not user.last_login_at + user = user_service.update_user( + email, email_verified=True, last_login_at=datetime.utcnow(), + ) or user result = complete_verified_login( user, @@ -303,14 +321,14 @@ def verify_code( grant_welcome_credit=True, referral_code=None, locale=email_locale, - ui_locale=record.get("ui_locale"), + ui_locale=ui_locale, ip_address=get_client_ip(http_request), user_agent=http_request.headers.get("user-agent"), tenant_id=None, device_fingerprint=None, email_locale=email_locale or user.locale or "en", ) - logger.info(f"kjbox: verified {_mask_email(email)} (credit_status={result.credit_status})") + logger.info(f"kjbox: {how} {_mask_email(email)} (credit_status={result.credit_status})") return VerifyCodeResponse( session_token=result.session.token, @@ -320,6 +338,62 @@ def verify_code( ) +def _social_sign_in(provider, body, http_request, svc, user_service, email_service): + """Google / Apple one-tap: the provider has proven the email, so no code. + Same venue rules as verify-code: no per-IP signup cap, the partner-wide 24h + cap on new accounts instead. Apple "Hide My Email" relays are their own account.""" + from backend.api.routes.login_code import APPLE_RELAY_DOMAIN, _verify_identity + + identity = _verify_identity(provider, body.id_token) # 401 invalid_token / 503 + email = _normalize_email(identity.email) + email_locale, ui_locale = _split_locale(body.locale) + + # The same eligibility checks as send-code. There's no email to hide a + # refusal behind, so (like the app's social sign-in) refusals are explicit. + email_validation = get_email_validation_service() + is_relay = provider == "apple" and email.endswith("@" + APPLE_RELAY_DOMAIN) + if not is_relay and email_validation.is_disposable_domain(email): + logger.warning(f"kjbox: {provider} sign-in refused, disposable email {_mask_email(email)}") + raise HTTPException(status_code=422, detail=t(email_locale or "en", "users.disposableEmailBlocked")) + ip_address = get_client_ip(http_request) + if email_validation.is_email_blocked(email) or (ip_address and email_validation.is_ip_blocked(ip_address)): + logger.warning(f"kjbox: {provider} sign-in refused, blocked email/IP {_mask_email(email)}") + raise HTTPException(status_code=422, detail="sign_in_not_allowed") + if user_service.get_user(email) is None and \ + svc.count_recent_signups() >= get_settings().kjbox_signup_cap_per_24h: + logger.warning("kjbox: partner-wide verified-signup cap reached") + raise HTTPException(status_code=429, detail="signup_cap") + return _finish_sign_in( + email, http_request, svc=svc, user_service=user_service, email_service=email_service, + venue=(body.venue or None), email_locale=email_locale, ui_locale=ui_locale, + precomputed_eval=None, how=f"{provider} sign-in", + ) + + +@router.post("/auth/google", response_model=VerifyCodeResponse) +def google_sign_in( + body: SocialSignInRequest, + http_request: Request, + svc: KjboxPartnerService = Depends(get_kjbox_service), + user_service: UserService = Depends(get_user_service), + email_service: EmailService = Depends(get_email_service), +): + """Google ID token (audience ``GOOGLE_OAUTH_CLIENT_IDS``) → singer session.""" + return _social_sign_in("google", body, http_request, svc, user_service, email_service) + + +@router.post("/auth/apple", response_model=VerifyCodeResponse) +def apple_sign_in( + body: SocialSignInRequest, + http_request: Request, + svc: KjboxPartnerService = Depends(get_kjbox_service), + user_service: UserService = Depends(get_user_service), + email_service: EmailService = Depends(get_email_service), +): + """Apple ID token (audience ``APPLE_SIGNIN_AUDIENCES``, incl. the web Services ID) → singer session.""" + return _social_sign_in("apple", body, http_request, svc, user_service, email_service) + + @router.post("/credits/show-credit", response_model=ShowCreditResponse) def show_credit( body: ShowCreditRequest, diff --git a/backend/config.py b/backend/config.py index 54a66710..252c0e33 100644 --- a/backend/config.py +++ b/backend/config.py @@ -426,8 +426,10 @@ class Settings(BaseSettings): "718638054799-hre535n83p8i85tsqf6ai759nlubhd2o.apps.googleusercontent.com", ) # Accepted `aud` values for Apple ID tokens (POST /api/users/auth/apple): - # the app's bundle ID (native iOS), plus any Services ID used for web/Android. - apple_signin_audiences: str = os.getenv("APPLE_SIGNIN_AUDIENCES", "com.nomadkaraoke.mobile") + # the app's bundle ID (native iOS), plus any Services ID used for web/Android: + # com.nomadkaraoke.sing = Sign in with Apple JS on the kjbox singer page + # (sing.nomadkaraoke.com → POST /api/kjbox/auth/apple). + apple_signin_audiences: str = os.getenv("APPLE_SIGNIN_AUDIENCES", "com.nomadkaraoke.mobile,com.nomadkaraoke.sing") # Sign in with Apple token revocation (account deletion). The .p8 PEM text # and key id come from Secret Manager; unset => revocation is skipped. diff --git a/backend/services/user_service.py b/backend/services/user_service.py index 8417f703..e48ea8ea 100644 --- a/backend/services/user_service.py +++ b/backend/services/user_service.py @@ -55,8 +55,12 @@ PROCESSED_STRIPE_SESSIONS_COLLECTION = "processed_stripe_sessions" # Token/session configuration MAGIC_LINK_EXPIRY_MINUTES = 24 * 60 # 24h — buffer for slow email delivery (Yahoo can defer for hours) -SESSION_EXPIRY_DAYS = 7 -SESSION_ABSOLUTE_EXPIRY_DAYS = 30 +# Inactivity window. Was 7 days: kjbox singers at weekly shows were always signed +# out by the next show (2026-10-22), so Andrew set it to 30 days for everyone. +SESSION_EXPIRY_DAYS = 30 +# Hard cap from sign-in, however active. Was 30: a weekly regular was still signed +# out once a month (Andrew, 2026-10-28: 365 days). +SESSION_ABSOLUTE_EXPIRY_DAYS = 365 MAX_CREDIT_TRANSACTIONS = 100 # Keep last N transactions @@ -1050,7 +1054,7 @@ class UserService: logger.warning(f"Session expired for {token_prefix}... (user: {session.user_email}, expired_at: {expires_at}, now: {now})") return False, None, "Session has expired" - # Check inactivity (7 days) + # Check inactivity (SESSION_EXPIRY_DAYS) inactivity_limit = now - timedelta(days=SESSION_EXPIRY_DAYS) if last_activity < inactivity_limit: logger.warning(f"Session inactive for {token_prefix}... (user: {session.user_email}, last_activity: {last_activity}, limit: {inactivity_limit})") diff --git a/backend/tests/test_kjbox_partner_api.py b/backend/tests/test_kjbox_partner_api.py index ee06cc92..2d093946 100644 --- a/backend/tests/test_kjbox_partner_api.py +++ b/backend/tests/test_kjbox_partner_api.py @@ -293,6 +293,7 @@ class TestSecretGate: from backend.main import app paths = {getattr(r, "path", "") for r in app.routes} assert {"/api/kjbox/auth/send-code", "/api/kjbox/auth/verify-code", + "/api/kjbox/auth/google", "/api/kjbox/auth/apple", "/api/kjbox/credits/show-credit"} <= paths @@ -515,6 +516,130 @@ class TestVerifyCode: # --------------------------------------------------------------- show-credit +# ------------------------------------------------- Google / Apple one-tap + +@pytest.fixture +def identities(monkeypatch): + """ID token → verified identity (the provider's signature check is login_code's, + tested there); "bad" tokens raise the same 401 login_code raises.""" + from fastapi import HTTPException + + from backend.api.routes import login_code + from backend.services.social_identity import VerifiedIdentity + + def verify(provider, id_token): + if id_token == "bad": + raise HTTPException(status_code=401, detail="invalid_token") + return VerifiedIdentity(email=id_token.lower(), provider=provider, subject="sub-1") + + monkeypatch.setattr(login_code, "_verify_identity", verify) + + +def _social(client, provider, id_token=EMAIL, **extra): + return client.post(f"/api/kjbox/auth/{provider}", json={"id_token": id_token, **extra}, headers=H) + + +class TestSocialSignIn: + @pytest.mark.parametrize("provider", ["google", "apple"]) + def test_new_singer_gets_a_session_without_a_code( + self, client, db, user_service, email_service, identities, provider): + resp = _social(client, provider, locale="es", venue="The Dive Bar") + assert resp.status_code == 200 + body = resp.json() + assert set(body) == {"session_token", "user", "credits_granted", "credit_status"} + assert body["credits_granted"] == 1 and body["user"]["email"] == EMAIL + created = user_service.get_user(EMAIL) + assert created.signup_source == "kjbox" and created.signup_venue == "The Dive Bar" + assert created.signup_ip is None # venue IP never recorded + assert [d["email"] for d in db.collection(kps.SIGNUPS_COLLECTION).docs.values()] == [EMAIL] + valid, user, _ = user_service.validate_session(body["session_token"]) + assert valid and user.email_verified and user.locale == "es" + email_service.send_kjbox_login_code.assert_not_called() + + def test_apple_relay_address_is_its_own_account(self, client, user_service, identities): + relay = "abc123@privaterelay.appleid.com" + assert _social(client, "apple", id_token=relay).status_code == 200 + assert user_service.get_user(relay) is not None + + def test_returning_code_user_signs_in_with_google(self, client, user_service, email_service, identities): + _send(client) + assert _verify(client, _sent_code(email_service)).status_code == 200 + body = _social(client, "google").json() + assert body["credits_granted"] == 0 and body["credit_status"] == "already_granted" + + def test_signup_cap_applies_to_new_accounts_only(self, client, settings, user_service, identities): + settings.kjbox_signup_cap_per_24h = 1 + assert _social(client, "google", id_token="a@example.com").status_code == 200 + resp = _social(client, "google", id_token="b@example.com") + assert resp.status_code == 429 and resp.json() == {"detail": "signup_cap"} + assert user_service.get_user("b@example.com") is None + settings.kjbox_signup_cap_per_24h = 0 + assert _social(client, "google", id_token="a@example.com").status_code == 200 + + def test_disposable_email_refused(self, client, validation, user_service, identities): + validation.is_disposable_domain.return_value = True + resp = _social(client, "google", id_token="x@mailinator.com") + assert resp.status_code == 422 + assert user_service.get_user("x@mailinator.com") is None + + def test_apple_relay_is_never_treated_as_disposable(self, client, validation, user_service, identities): + validation.is_disposable_domain.return_value = True + relay = "abc123@privaterelay.appleid.com" + assert _social(client, "apple", id_token=relay).status_code == 200 + + @pytest.mark.parametrize("blocked", ["email", "ip"]) + def test_blocked_email_or_ip_refused(self, client, validation, user_service, identities, blocked): + getattr(validation, f"is_{blocked}_blocked").return_value = True + resp = _social(client, "google") + assert resp.status_code == 422 and resp.json() == {"detail": "sign_in_not_allowed"} + assert user_service.get_user(EMAIL) is None + + def test_invalid_token_is_401(self, client, user_service, identities): + resp = _social(client, "google", id_token="bad") + assert resp.status_code == 401 and resp.json() == {"detail": "invalid_token"} + + @pytest.mark.parametrize("provider", ["google", "apple"]) + def test_needs_the_partner_secret(self, client, identities, provider): + resp = client.post(f"/api/kjbox/auth/{provider}", json={"id_token": EMAIL}) + assert resp.status_code == 403 + + +class TestSessionInactivity: + def test_weekly_regular_stays_signed_in_but_a_month_idle_expires(self, client, db, user_service, identities): + # Was 7 days: a singer at weekly shows was always signed out by the next one. + from backend.services.user_service import SESSIONS_COLLECTION + token = _social(client, "google").json()["session_token"] + sessions = db.collection(SESSIONS_COLLECTION).docs + now = datetime.now(timezone.utc) + sessions[token]["last_activity_at"] = now - timedelta(days=20) + assert user_service.validate_session(token)[0] is True + sessions[token]["last_activity_at"] = now - timedelta(days=31) + valid, _, reason = user_service.validate_session(token) + assert valid is False and "inactivity" in reason + + +class TestSessionLifetime: + def test_new_session_lasts_a_year_from_sign_in(self, client, db, identities): + from backend.services.user_service import SESSIONS_COLLECTION + token = _social(client, "google").json()["session_token"] + expires = db.collection(SESSIONS_COLLECTION).docs[token]["expires_at"] + if isinstance(expires, str): + expires = datetime.fromisoformat(expires) + if expires.tzinfo is None: + expires = expires.replace(tzinfo=timezone.utc) + days = (expires - datetime.now(timezone.utc)).days + assert 363 <= days <= 365 + + def test_weekly_regular_still_signed_in_after_two_months(self, client, db, user_service, identities): + from backend.services.user_service import SESSIONS_COLLECTION + token = _social(client, "google").json()["session_token"] + doc = db.collection(SESSIONS_COLLECTION).docs[token] + now = datetime.now(timezone.utc) + doc["created_at"] = now - timedelta(days=60) + doc["last_activity_at"] = now - timedelta(days=6) + assert user_service.validate_session(token)[0] is True + + def _session(client, email_service, email=EMAIL): _send(client, email=email) return _verify(client, _sent_code(email_service), email=email).json()["session_token"] diff --git a/docs/API.md b/docs/API.md index b97b63f1..eff919c0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3382,6 +3382,26 @@ missing/expired/already-used → `401 {"detail": "expired"}`; more than 5 attemp atomic increment before a constant-time compare; single use is enforced by a create()-only marker in `kjbox_login_code_uses`. +### Google / Apple sign-in (one tap) + +```http +POST /api/kjbox/auth/google (or /api/kjbox/auth/apple) +{"id_token": "", "locale": "es", "venue": "The Dive Bar"} +``` + +→ the same `200` body as verify-code, with no code: the provider has proven the +email. The token is checked by the same `_verify_identity` as +`POST /api/users/auth/google|apple` (audiences `GOOGLE_OAUTH_CLIENT_IDS` / +`APPLE_SIGNIN_AUDIENCES`, which must include the web Services ID used on +sing.nomadkaraoke.com; `fake:` tokens on the local stack only). The +venue rules match verify-code: no per-IP signup cap, `KJBOX_SIGNUP_CAP_PER_24H` +on new accounts (`429 {"detail": "signup_cap"}`), `signup_source="kjbox"` + +`signup_venue`, no `signup_ip`. Apple "Hide My Email" relay addresses are +their own account (and never count as disposable). The send-code eligibility +checks apply, explicitly: disposable domain → `422` (magic-link detail); +blocked email or IP → `422 {"detail": "sign_in_not_allowed"}`. Errors: `401 {"detail": "invalid_token"}`, +`503 google_not_configured` / `identity_provider_unavailable`. + ### Show credit ("free at the show") ```http diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index de4938e7..c4d8f006 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -408,17 +408,38 @@ Config (all public, non-secret; env vars override the defaults in `backend/confi | Setting | Default | Purpose | |---------|---------|---------| | `GOOGLE_OAUTH_CLIENT_IDS` | Web + iOS client IDs below | Accepted `aud` of Google ID tokens | -| `APPLE_SIGNIN_AUDIENCES` | `com.nomadkaraoke.mobile` | Accepted `aud` of Apple ID tokens (bundle ID; add a Services ID for web/Android) | +| `APPLE_SIGNIN_AUDIENCES` | `com.nomadkaraoke.mobile,com.nomadkaraoke.sing` | Accepted `aud` of Apple ID tokens: the app's bundle ID + the kjbox singer page's web Services ID | | `MOBILE_APP_SCHEME` | `nomadkaraoke` | Scheme the checkout bounce redirects to | Google OAuth clients (GCP project `nomadkaraoke`, Google Auth Platform, consent screen "Nomad Karaoke"): | Name / type | Client ID | Notes | |-------------|-----------|-------| -| Web application | `718638054799-fush0smd1e4icq9pt0immp8n59jjlebh.apps.googleusercontent.com` | The audience: Android Credential Manager and iOS (with `serverClientId` / `webClientId`) issue tokens for it | +| Web application ("Nomad Karaoke Mobile App (server audience)") | `718638054799-fush0smd1e4icq9pt0immp8n59jjlebh.apps.googleusercontent.com` | The audience: Android Credential Manager and iOS (with `serverClientId` / `webClientId`) issue tokens for it. Authorized JavaScript origins: `https://decide.nomadkaraoke.com`, `https://sing.nomadkaraoke.com` (added 2026-10-28 for the kjbox singer page's Sign in with Google button) | | iOS | `718638054799-hre535n83p8i85tsqf6ai759nlubhd2o.apps.googleusercontent.com` | Also accepted as an audience (iOS SDK tokens can carry it) | | Android | `718638054799-q0f65m68a31du5nn9h5accsauad232ku.apps.googleusercontent.com` | Device-only, never an audience. Package `com.nomadkaraoke.mobile`, SHA-1 `5E:8F:16:06:2E:A3:CD:2C:4A:0D:54:78:76:BA:A6:F3:8C:AB:F6:25` (the RN/Expo template debug keystore); add the release key's SHA-1 before store builds | +### kjbox singer page (sing.nomadkaraoke.com) + +The kjbox singer page signs singers in to their gen account for make-its through the partner endpoints +`POST /api/kjbox/auth/google|apple` ([API.md](API.md)), with the same token checks as above. Console setup, +done 2026-10-28 (no IaC covers these): + +- **Google:** `https://sing.nomadkaraoke.com` added as an Authorized JavaScript origin on the Web application client above + (Google Identity Services button, ID token straight to JS). +- **Apple** (developer team 55B76HN73D, Andrew's Apple ID): + - Services ID **`com.nomadkaraoke.sing`** ("Nomad Karaoke Singer Web"), with Sign in with Apple enabled. + Its primary App ID is `com.nomadkaraoke.mobile`, its domain `sing.nomadkaraoke.com` and its return URL + `https://sing.nomadkaraoke.com/`. Sign in with Apple JS runs in popup mode. + - **Private email relay:** the domain `nomadkaraoke.com` is registered as an email source (SPF ✓). Without it, + Apple drops mail from gen to any `@privaterelay.appleid.com` user, which affects the mobile app's Apple sign-ins too. + +## Session lifetime + +`SESSION_EXPIRY_DAYS = 30` (inactivity) and `SESSION_ABSOLUTE_EXPIRY_DAYS = 365` (from sign-in) in +`backend/services/user_service.py`. Both changed on 2026-10-28: they were 7 and 30, which signed out singers who come +to weekly shows between visits. + ## Firestore Collections karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses separate Firestore collections: diff --git a/pyproject.toml b/pyproject.toml index bddd4fd3..f43fc09a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "karaoke-gen" -version = "0.285.2" +version = "0.286.0" description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens." authors = ["Andrew Beveridge "] license = "MIT"