kjbox: one-tap Google/Apple sign-in for singers; sessions last 30 idle days / 365 max (v0.286.0) (#1226)

## Summary

Backend for one-tap sign-in in the kjbox singer page
(sing.nomadkaraoke.com). At the 2026-10-22 show, typing an email and a
6-digit code was the biggest friction point for singers making a karaoke
video on demand. Plan: kjbox
`docs/archive/2026-10-28-singer-make-it-one-screen-plan.md`.

- **`POST /api/kjbox/auth/google` and `/api/kjbox/auth/apple`** take
`{id_token, locale?, venue?}` and return the same body as
`/api/kjbox/auth/verify-code`, with no code needed.
- The token is checked by `login_code._verify_identity`, so the
audiences match the app's (and `fake:` tokens work only on the local
stack).
- Venue rules are the same as verify-code: no per-IP signup cap,
`KJBOX_SIGNUP_CAP_PER_24H` on new accounts, `signup_source="kjbox"` +
`signup_venue`, no `signup_ip`.
- Send-code's eligibility checks are applied explicitly. A disposable
domain gets 422. A blocked email or IP gets `422 sign_in_not_allowed`.
Apple relay addresses are allowed.
- Code sign-in and social sign-in now share one `_finish_sign_in`
helper.
- **`SESSION_EXPIRY_DAYS` (inactivity) 7 → 30, globally** (Andrew's
call). With weekly shows, every returning singer was signed out by the
next show. **`SESSION_ABSOLUTE_EXPIRY_DAYS` 30 → 365** (Andrew,
2026-10-28), so a weekly regular isn't signed out once a month.
- Version 0.286.0. API.md updated.

This stays inert until kjbox calls the endpoints. Before the singer page
can use them, Andrew needs to:
- add `https://sing.nomadkaraoke.com` as an Authorized JavaScript origin
on the "Nomad Karaoke Web" OAuth client;
- create an Apple web Services ID and add it to
`APPLE_SIGNIN_AUDIENCES`.

## Testing

`backend/tests/test_kjbox_partner_api.py` covers:
- a new singer via Google and via Apple;
- an Apple relay address, which is never treated as disposable;
- a code user who later signs in with Google;
- the signup cap applying to new accounts only;
- an invalid token returning 401;
- the partner secret being required;
- disposable and blocked email/IP refusals;
- 20 days idle still valid and 31 days idle expired; a new session
expires a year from sign-in; a weekly regular is still signed in two
months on.

259 auth/session/kjbox tests pass locally. Local CodeRabbit: 2 cycles.
The first found the missing eligibility checks (fixed) and the
absolute-expiry question (now 365 days). The second found nothing new.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 5.5 authored and GitHub committed 2026-10-28 19:34:00 -04:00
1 parent 5c30fde9b4
commit 331d18ddf8
7 files changed
+272 -26

No files matched your search

+92 -18
View File
@@ -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 <session>)
{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:<email>`` 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,
+4 -2
View File
@@ -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.
+7 -3
View File
@@ -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})")
+125
View File
@@ -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"]
+20
View File
@@ -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": "<Google Identity Services / Sign in with Apple JS 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:<email>` 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
+23 -2
View File
@@ -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:
+1 -1
View File
@@ -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 <andrew@beveridge.uk>"]
license = "MIT"