feat: separate B2B tenant portal with edge config injection (#458)

## Summary

- Separate whitelabel B2B tenant portals into their own Cloudflare Pages
project (`karaoke-gen-tenant`) with edge-injected tenant config, fixing
the magic link auth bug and eliminating flash of consumer content
- Fix magic link emails to use tenant-specific URLs and branding (emails
now link to `vocalstar.nomadkaraoke.com` instead of always
`gen.nomadkaraoke.com`)
- Add Cloudflare Pages Function that injects `window.__TENANT_CONFIG__`
and CSS variables at the edge for instant branding
- Add `NEXT_PUBLIC_TENANT_PORTAL=true` build flag for tree-shaking
consumer content from tenant builds
- Add admin tenant preview via `?preview_tenant=X` query parameter
- Add tenant-scoped access tokens (tokens with `tenant_id` override
hostname-based detection)
- Dual build+deploy in CI (consumer → `karaoke-gen`, tenant →
`karaoke-gen-tenant`)

## Test plan

- [x] 17 backend tests pass (magic link params, tenant URLs, verify
response, tenant-scoped tokens, require_auth override)
- [x] 35 frontend tests pass (tenant store, edge-injected config, admin
preview, feature flags)
- [x] 181/182 E2E tests pass (1 pre-existing screenshot failure
unrelated to changes)
- [x] Both consumer and tenant portal builds succeed (`npm run build`
with and without `NEXT_PUBLIC_TENANT_PORTAL=true`)
- [ ] Manual: verify vocalstar.nomadkaraoke.com loads with tenant
branding (already deployed)
- [ ] Manual: verify magic link from tenant portal links to correct
domain

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 4.6 authored and GitHub committed 2026-03-03 17:15:17 -05:00
1 parent 6ded014acf
commit 90ce8951f5
21 files changed
+867 -30

No files matched your search

+21 -2
View File
@@ -903,19 +903,38 @@ jobs:
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Build frontend (Next.js static export)
# ===== Consumer Build (gen.nomadkaraoke.com) =====
- name: Build frontend (consumer)
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
run: npm run build
- name: Deploy to Cloudflare Pages
- name: Deploy consumer to Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy frontend/out --project-name=karaoke-gen --branch=main
# ===== Tenant Portal Build (vocalstar.nomadkaraoke.com, singa.nomadkaraoke.com, etc.) =====
# Separate build with NEXT_PUBLIC_TENANT_PORTAL=true which tree-shakes
# consumer marketing content and renders TenantLandingPage at root.
# The Cloudflare Pages Function (frontend/functions/) injects tenant config at the edge.
- name: Build frontend (tenant portal)
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_TENANT_PORTAL: "true"
run: npm run build
- name: Deploy tenant portal to Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy frontend/out --project-name=karaoke-gen-tenant --branch=main
# NOTE: buy-site was consolidated into the main frontend (PR #122, Dec 2024)
# Landing page and payment flow are now at gen.nomadkaraoke.com (root)
# buy.nomadkaraoke.com subdomain has been deleted
+6
View File
@@ -113,6 +113,11 @@ async def require_auth(
detail=f"Authentication failed: {auth_result.message}"
)
# If token has a tenant_id, override the hostname-based tenant detection.
# This allows tenant-scoped tokens to enforce tenant context regardless of domain.
if auth_result.tenant_id:
request.state.tenant_id = auth_result.tenant_id
# Log successful auth with request_id for correlation with request audit
logger.info(
"auth_success",
@@ -122,6 +127,7 @@ async def require_auth(
"user_type": auth_result.user_type.value if auth_result.user_type else None,
"is_admin": auth_result.is_admin,
"remaining_uses": auth_result.remaining_uses,
"tenant_id": auth_result.tenant_id,
"audit_type": "auth_event",
}
)
+24 -4
View File
@@ -186,13 +186,23 @@ async def send_magic_link(
tenant_id=tenant_id
)
# Get tenant-specific sender email
# Get tenant-specific email configuration
sender_email = None
tenant_frontend_url = None
tenant_name = None
if tenant_config:
sender_email = tenant_config.get_sender_email()
tenant_frontend_url = tenant_config.get_frontend_url()
tenant_name = tenant_config.name
# Send email (with tenant-specific sender if configured)
sent = email_service.send_magic_link(email, magic_link.token, sender_email=sender_email)
# Send email (with tenant-specific sender, URL, and name if configured)
sent = email_service.send_magic_link(
email,
magic_link.token,
sender_email=sender_email,
tenant_frontend_url=tenant_frontend_url,
tenant_name=tenant_name,
)
if not sent:
logger.error(f"Failed to send magic link email to {email}")
@@ -269,11 +279,21 @@ async def verify_magic_link(
tenant_id=user.tenant_id,
)
# Resolve tenant subdomain for cross-domain redirect safety
tenant_subdomain = None
if magic_link_tenant_id:
from backend.services.tenant_service import get_tenant_service
tenant_service = get_tenant_service()
tenant_cfg = tenant_service.get_tenant_config(magic_link_tenant_id)
if tenant_cfg:
tenant_subdomain = tenant_cfg.subdomain
return VerifyMagicLinkResponse(
status="success",
session_token=session.token,
user=user_public,
message="Successfully signed in"
message="Successfully signed in",
tenant_subdomain=tenant_subdomain,
)
+4
View File
@@ -139,6 +139,10 @@ class TenantConfig(BaseModel):
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
def get_frontend_url(self) -> str:
"""Get the frontend URL for this tenant's portal."""
return f"https://{self.subdomain}"
def get_sender_email(self) -> str:
"""Get the email sender address for this tenant."""
if self.auth.sender_email:
+1
View File
@@ -177,6 +177,7 @@ class VerifyMagicLinkResponse(BaseModel):
session_token: str
user: "UserPublic"
message: str
tenant_subdomain: Optional[str] = None
class UserPublic(BaseModel):
+24 -11
View File
@@ -49,6 +49,7 @@ class AuthResult:
user_email: Optional[str] = None # Email if authenticated via session/API key
is_admin: bool = False # True if admin token or admin email domain
api_key_id: Optional[str] = None # API key ID if authenticated via API key
tenant_id: Optional[str] = None # Tenant scope from token or session
def __iter__(self):
"""Allow unpacking as tuple for backward compatibility."""
@@ -284,6 +285,7 @@ class AuthService:
# All auth_tokens must have an associated user_email for job ownership
token_user_email = token_data.get("user_email")
api_key_id = token_data.get("api_key_id")
token_tenant_id = token_data.get("tenant_id")
# Require user_email on all auth_tokens (no anonymous token auth)
if not token_user_email:
@@ -307,7 +309,8 @@ class AuthService:
message="Unlimited access granted",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
# LIMITED tokens: check usage count
@@ -320,7 +323,8 @@ class AuthService:
message="Limited token with unlimited uses",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
current_uses = token_data.get("usage_count", 0)
@@ -333,7 +337,8 @@ class AuthService:
remaining_uses=0,
message="Token usage limit exceeded",
user_email=token_user_email,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
return AuthResult(
@@ -343,7 +348,8 @@ class AuthService:
message=f"Limited token: {remaining} uses remaining",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
# STRIPE tokens: check expiration and usage
@@ -357,7 +363,8 @@ class AuthService:
remaining_uses=0,
message="Token has expired",
user_email=token_user_email,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
if max_uses > 0:
@@ -371,7 +378,8 @@ class AuthService:
remaining_uses=0,
message="Token usage limit exceeded",
user_email=token_user_email,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
return AuthResult(
@@ -381,7 +389,8 @@ class AuthService:
message=f"Stripe token: {remaining} uses remaining",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
return AuthResult(
@@ -391,7 +400,8 @@ class AuthService:
message="Stripe access granted",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
# API_KEY tokens
@@ -406,7 +416,8 @@ class AuthService:
remaining_uses=0,
message="API key usage limit exceeded",
user_email=token_user_email,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
return AuthResult(
is_valid=True,
@@ -415,7 +426,8 @@ class AuthService:
message=f"API key valid: {remaining} uses remaining",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
return AuthResult(
@@ -425,7 +437,8 @@ class AuthService:
message="API key access granted",
user_email=token_user_email,
is_admin=token_is_admin,
api_key_id=api_key_id
api_key_id=api_key_id,
tenant_id=token_tenant_id
)
return AuthResult(
+11 -5
View File
@@ -247,6 +247,8 @@ class EmailService:
email: str,
token: str,
sender_email: Optional[str] = None,
tenant_frontend_url: Optional[str] = None,
tenant_name: Optional[str] = None,
) -> bool:
"""
Send a magic link email for authentication.
@@ -255,13 +257,17 @@ class EmailService:
email: User's email address
token: Magic link token
sender_email: Override sender email address (for multi-tenant)
tenant_frontend_url: Override frontend URL for tenant portals (e.g., https://vocalstar.nomadkaraoke.com)
tenant_name: Override brand name for tenant portals (e.g., "Vocal Star")
Returns:
True if email was sent successfully
"""
magic_link_url = f"{self.frontend_url}/auth/verify?token={token}"
base_url = tenant_frontend_url or self.frontend_url
magic_link_url = f"{base_url}/auth/verify?token={token}"
subject = "Sign in to Nomad Karaoke"
brand_name = tenant_name or "Nomad Karaoke"
subject = f"Sign in to {brand_name}"
extra_styles = """
.warning {
@@ -277,7 +283,7 @@ class EmailService:
content = f"""
<p>Hi there,</p>
<p>Click the button below to sign in to Nomad Karaoke:</p>
<p>Click the button below to sign in to {html.escape(brand_name)}:</p>
<p style="text-align: center;">
<a href="{magic_link_url}" class="button">Sign In</a>
@@ -298,7 +304,7 @@ class EmailService:
html_content = self._build_email_html(content, extra_styles)
text_content = f"""
Sign in to Nomad Karaoke
Sign in to {brand_name}
========================
Click this link to sign in:
@@ -309,7 +315,7 @@ This link expires in 15 minutes and can only be used once.
If you didn't request this email, you can safely ignore it.
---
© {self._get_year()} Nomad Karaoke
© {self._get_year()} {brand_name}
"""
return self.provider.send_email(
+310
View File
@@ -0,0 +1,310 @@
"""
Tests for whitelabel tenant separation (magic link redirect fix, frontend URL, verify response,
tenant-scoped tokens).
"""
import pytest
from unittest.mock import MagicMock, patch
from backend.models.tenant import TenantConfig, TenantAuth, TenantBranding
from backend.models.user import VerifyMagicLinkResponse, UserPublic
from backend.services.auth_service import AuthResult, AuthService, UserType
class TestTenantConfigGetFrontendUrl:
"""Tests for TenantConfig.get_frontend_url()."""
def test_returns_https_url_with_subdomain(self):
config = TenantConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
)
assert config.get_frontend_url() == "https://vocalstar.nomadkaraoke.com"
def test_different_tenant(self):
config = TenantConfig(
id="singa",
name="Singa",
subdomain="singa.nomadkaraoke.com",
)
assert config.get_frontend_url() == "https://singa.nomadkaraoke.com"
class TestSendMagicLinkTenantParams:
"""Tests for EmailService.send_magic_link() with tenant parameters."""
@pytest.fixture
def email_service(self):
"""Create an EmailService with a mock provider."""
from backend.services.email_service import EmailService
service = EmailService()
service.provider = MagicMock()
service.provider.send_email = MagicMock(return_value=True)
return service
def test_default_uses_nomad_karaoke_branding(self, email_service):
"""Without tenant params, email uses default Nomad Karaoke branding."""
email_service.send_magic_link("user@test.com", "abc123")
call_args = email_service.provider.send_email.call_args
subject = call_args[0][1]
html_content = call_args[0][2]
text_content = call_args[0][3]
assert subject == "Sign in to Nomad Karaoke"
assert "Nomad Karaoke" in html_content
assert "Nomad Karaoke" in text_content
# Default URL should be used
assert f"{email_service.frontend_url}/auth/verify" in html_content
def test_tenant_url_used_in_magic_link(self, email_service):
"""When tenant_frontend_url is provided, magic link points to tenant domain."""
email_service.send_magic_link(
"user@vocal-star.com",
"abc123",
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
)
call_args = email_service.provider.send_email.call_args
html_content = call_args[0][2]
text_content = call_args[0][3]
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in html_content
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in text_content
# Should NOT contain default URL
assert "gen.nomadkaraoke.com" not in html_content
def test_tenant_name_used_in_subject_and_body(self, email_service):
"""When tenant_name is provided, email uses tenant brand name."""
email_service.send_magic_link(
"user@vocal-star.com",
"abc123",
tenant_name="Vocal Star",
)
call_args = email_service.provider.send_email.call_args
subject = call_args[0][1]
html_content = call_args[0][2]
text_content = call_args[0][3]
assert subject == "Sign in to Vocal Star"
assert "Vocal Star" in html_content
assert "Vocal Star" in text_content
def test_tenant_name_html_escaped(self, email_service):
"""Tenant name is HTML-escaped to prevent XSS."""
email_service.send_magic_link(
"user@test.com",
"abc123",
tenant_name='<script>alert("xss")</script>',
)
call_args = email_service.provider.send_email.call_args
html_content = call_args[0][2]
# Should be escaped in HTML
assert "<script>" not in html_content
assert "&lt;script&gt;" in html_content
def test_all_tenant_params_together(self, email_service):
"""Test sending magic link with all tenant parameters."""
result = email_service.send_magic_link(
"user@vocal-star.com",
"token123",
sender_email="vocalstar@nomadkaraoke.com",
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
tenant_name="Vocal Star",
)
assert result is True
call_args = email_service.provider.send_email.call_args
subject = call_args[0][1]
html_content = call_args[0][2]
assert subject == "Sign in to Vocal Star"
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=token123" in html_content
# Check sender email override was passed through
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
class TestVerifyMagicLinkResponseTenantSubdomain:
"""Tests for tenant_subdomain field in VerifyMagicLinkResponse."""
def test_response_without_tenant(self):
"""Verify response without tenant has null subdomain."""
user = UserPublic(email="user@test.com", role="user", credits=2)
response = VerifyMagicLinkResponse(
status="success",
session_token="sess_123",
user=user,
message="ok",
)
assert response.tenant_subdomain is None
def test_response_with_tenant_subdomain(self):
"""Verify response includes tenant subdomain when provided."""
user = UserPublic(email="user@vocal-star.com", role="user", credits=2)
response = VerifyMagicLinkResponse(
status="success",
session_token="sess_123",
user=user,
message="ok",
tenant_subdomain="vocalstar.nomadkaraoke.com",
)
assert response.tenant_subdomain == "vocalstar.nomadkaraoke.com"
def test_response_serialization_includes_tenant_subdomain(self):
"""Verify response serializes tenant_subdomain correctly."""
user = UserPublic(email="user@test.com", role="user", credits=2)
response = VerifyMagicLinkResponse(
status="success",
session_token="sess_123",
user=user,
message="ok",
tenant_subdomain="singa.nomadkaraoke.com",
)
data = response.model_dump()
assert data["tenant_subdomain"] == "singa.nomadkaraoke.com"
class TestTenantScopedTokens:
"""Tests for tenant_id propagation from Firestore auth tokens to AuthResult."""
@pytest.fixture
def auth_service(self):
"""Create an AuthService with mocked Firestore."""
service = AuthService()
service.firestore = MagicMock()
service.admin_tokens = set()
return service
def test_token_without_tenant_id(self, auth_service):
"""Auth token without tenant_id returns None tenant_id in result."""
auth_service.firestore.get_token.return_value = {
"type": "unlimited",
"active": True,
"user_email": "user@test.com",
}
result = auth_service.validate_token_full("test-token")
assert result.is_valid is True
assert result.tenant_id is None
def test_token_with_tenant_id(self, auth_service):
"""Auth token with tenant_id propagates it to AuthResult."""
auth_service.firestore.get_token.return_value = {
"type": "unlimited",
"active": True,
"user_email": "admin@nomadkaraoke.com",
"tenant_id": "vocalstar",
}
result = auth_service.validate_token_full("test-token")
assert result.is_valid is True
assert result.tenant_id == "vocalstar"
assert result.is_admin is True
def test_limited_token_with_tenant_id(self, auth_service):
"""Limited token with tenant_id propagates it."""
auth_service.firestore.get_token.return_value = {
"type": "limited",
"active": True,
"user_email": "user@test.com",
"tenant_id": "singa",
"max_uses": 10,
"usage_count": 3,
}
result = auth_service.validate_token_full("test-token")
assert result.is_valid is True
assert result.tenant_id == "singa"
assert result.remaining_uses == 7
def test_api_key_with_tenant_id(self, auth_service):
"""API key token with tenant_id propagates it."""
auth_service.firestore.get_token.return_value = {
"type": "api_key",
"active": True,
"user_email": "api@vocal-star.com",
"tenant_id": "vocalstar",
"api_key_id": "ak_123",
}
result = auth_service.validate_token_full("test-token")
assert result.is_valid is True
assert result.tenant_id == "vocalstar"
assert result.api_key_id == "ak_123"
def test_admin_env_token_has_no_tenant_id(self, auth_service):
"""Admin tokens from env var should not have tenant scoping."""
auth_service.admin_tokens = {"admin-secret-token"}
result = auth_service.validate_token_full("admin-secret-token")
assert result.is_valid is True
assert result.is_admin is True
assert result.tenant_id is None
class TestRequireAuthTenantOverride:
"""Tests for tenant_id override logic in require_auth dependency."""
def _make_request(self, initial_tenant_id="hostname-tenant"):
"""Create a mock Request with request.state.tenant_id pre-set."""
request = MagicMock()
request.state.tenant_id = initial_tenant_id
request.state.request_id = "req-123"
request.headers.get.return_value = ""
return request
@pytest.mark.asyncio
async def test_auth_result_with_tenant_id_overrides_request_state(self):
"""When auth_result has tenant_id, it overrides the hostname-based tenant_id."""
from backend.api.dependencies import require_auth
request = self._make_request(initial_tenant_id="hostname-tenant")
mock_auth_result = AuthResult(
is_valid=True,
user_type=UserType.UNLIMITED,
remaining_uses=-1,
message="ok",
tenant_id="token-tenant",
)
mock_auth_service = MagicMock()
mock_auth_service.validate_token_full.return_value = mock_auth_result
with patch("backend.api.dependencies.get_auth_service", return_value=mock_auth_service):
result = await require_auth(
request=request,
auth_service=mock_auth_service,
credentials=MagicMock(credentials="valid-token"),
token=None,
)
assert result.tenant_id == "token-tenant"
assert request.state.tenant_id == "token-tenant"
@pytest.mark.asyncio
async def test_auth_result_without_tenant_id_leaves_request_state_unchanged(self):
"""When auth_result has no tenant_id, request.state.tenant_id is not changed."""
from backend.api.dependencies import require_auth
request = self._make_request(initial_tenant_id="hostname-tenant")
mock_auth_result = AuthResult(
is_valid=True,
user_type=UserType.UNLIMITED,
remaining_uses=-1,
message="ok",
tenant_id=None,
)
mock_auth_service = MagicMock()
mock_auth_service.validate_token_full.return_value = mock_auth_result
with patch("backend.api.dependencies.get_auth_service", return_value=mock_auth_service):
result = await require_auth(
request=request,
auth_service=mock_auth_service,
credentials=MagicMock(credentials="valid-token"),
token=None,
)
assert result.tenant_id is None
assert request.state.tenant_id == "hostname-tenant"
+20
View File
@@ -464,6 +464,26 @@ if tenant_config and not tenant_config.features.audio_search:
- Auth: Restricted to `@singa.com` emails
- Setup: `python scripts/setup-singa-tenant.py`
### Tenant Portal Frontend (B2B Deployment)
B2B tenants are served from a **separate Cloudflare Pages project** (`karaoke-gen-tenant`) built with `NEXT_PUBLIC_TENANT_PORTAL=true`. This build flag enables tree-shaking of consumer-only content (landing page, pricing, beta enrollment) at build time, keeping the bundle lean for white-label deployments.
**Runtime tenant injection**: A Cloudflare Pages edge function intercepts HTML responses and injects tenant-specific configuration before the page reaches the browser:
```javascript
// Injected by edge function into <head>
window.__TENANT_CONFIG__ = { id: "vocalstar", branding: { ... }, features: { ... } }
// CSS variables for dynamic theming
--tenant-primary-color: #ffd700;
--tenant-background-color: #1a1a2e;
```
The frontend's `TenantProvider` reads `window.__TENANT_CONFIG__` on startup (no API round-trip needed for initial render). This approach works for both custom domains (`vocalstar.nomadkaraoke.com`) and the shared tenant portal domain.
**Magic link emails**: When a tenant user requests a magic link, the email uses the tenant-specific URL (e.g., `https://vocalstar.nomadkaraoke.com/auth/verify?token=...`) rather than the main app URL. The `job_notification_service.py` resolves the correct base URL from the tenant config's `subdomain` field.
**Admin preview**: Admins can preview any tenant's branding in the main app by appending `?preview_tenant=<tenant_id>` to any URL. This bypasses subdomain detection and loads the specified tenant config, useful for verifying branding before DNS cutover.
## Tech Stack
- **Backend**: FastAPI, Python 3.12, Cloud Run
+2
View File
@@ -44,6 +44,8 @@
## Recent Changes
- **Tenant Portal Frontend Separation** (2026-03-03): B2B tenants now served from a dedicated Cloudflare Pages project (`karaoke-gen-tenant`) built with `NEXT_PUBLIC_TENANT_PORTAL=true` to tree-shake consumer content. A Cloudflare edge function injects `window.__TENANT_CONFIG__` and CSS variables into HTML at the edge, eliminating the initial API round-trip for tenant config. Magic link emails now use tenant-specific URLs (e.g., `vocalstar.nomadkaraoke.com/auth/verify`). Admins can preview any tenant's branding via `?preview_tenant=<id>`. See [ARCHITECTURE.md](ARCHITECTURE.md#tenant-portal-frontend-b2b-deployment).
- **YouTube Quota-Aware Upload System** (2026-03-03): Replaced the hard-coded YouTube upload limit (10/day) with quota-unit tracking against the YouTube Data API v3's 10,000 units/day quota. **Problem**: 4 jobs on 2026-03-03 had YouTube uploads silently skipped with no user notification. The hard limit of 10 uploads/day was overly conservative (actual capacity: ~33 uploads/day at ~300 units each). **Solution**: (1) `YouTubeQuotaService` tracks quota units consumed per day in Firestore with Pacific Time midnight reset, (2) `YouTubeUploadQueueService` queues uploads when quota is low instead of silently skipping, (3) Hourly Cloud Scheduler job processes the queue when quota is available, (4) Users get a follow-up email with their YouTube link when deferred uploads complete, (5) Admin dashboard shows quota usage progress bar and queue management. New Firestore collections: `youtube_quota` (daily quota tracking), `youtube_upload_queue` (deferred uploads). New config: `YOUTUBE_QUOTA_DAILY_LIMIT`, `YOUTUBE_QUOTA_UPLOAD_COST`, `YOUTUBE_QUOTA_SAFETY_MARGIN`. See [archive/2026-03-03-youtube-quota-fix-plan.md](archive/2026-03-03-youtube-quota-fix-plan.md) and [API.md](API.md#youtube-upload-queue).
- **Singa Whitelabel Tenant** (2026-03-03): Added Singa (singa.com) as second B2B tenant. Green/black branding, file-upload-only mode, locked to "singa" theme, restricted to @singa.com emails. Setup script generates all branding assets (4K backgrounds, CDG backgrounds, logo) programmatically with Pillow. Also fixed critical Zustand getter bug where computed store properties (branding, features, defaults) became stale static values after any `set()` call — `Object.assign` invokes getters and copies return values, destroying the getter. Added `TenantLandingPage` component for minimal tenant portal experience (logo + sign-in). Added Cloudflare Pages `_headers` for proper cache control. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-use-javascript-getters-in-zustand-stores-mar-2026).
+15 -1
View File
@@ -35,7 +35,21 @@ function VerifyMagicLinkContent() {
const success = await verifyMagicLink(token)
if (success) {
setState("success")
// Redirect to main app after short delay
// Check if the verify response included a tenant subdomain
// If we're on the wrong domain, redirect to the correct tenant portal
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
if (lastVerifyResponse?.tenant_subdomain) {
const currentHost = window.location.hostname.toLowerCase()
const tenantSubdomain = lastVerifyResponse.tenant_subdomain.toLowerCase()
if (currentHost !== tenantSubdomain) {
// We're on the wrong domain — redirect to the correct tenant portal
setTimeout(() => {
window.location.href = `https://${tenantSubdomain}/app`
}, 1500)
return
}
}
// Same domain or no tenant — redirect normally
setTimeout(() => {
router.push("/app")
}, 2000)
+13
View File
@@ -26,6 +26,9 @@ import { ThemeToggle } from '@/components/ThemeToggle';
import { useTenant } from '@/lib/tenant';
import { TenantLandingPage } from '@/components/TenantLandingPage';
// Build-time constant: when true, this build is for tenant portals only
const IS_TENANT_PORTAL = process.env.NEXT_PUBLIC_TENANT_PORTAL === 'true';
// FAQ data
const faqs = [
{
@@ -56,6 +59,16 @@ const faqs = [
];
export default function LandingPage() {
// Tenant portal builds always render the tenant landing page
// This is a build-time constant so the consumer code gets tree-shaken
if (IS_TENANT_PORTAL) {
return <TenantLandingPage />;
}
return <ConsumerLandingPage />;
}
function ConsumerLandingPage() {
const router = useRouter();
const { isDefault: isDefaultTenant, isLoading: tenantLoading, isInitialized: tenantInitialized } = useTenant();
const [isCheckingAuth, setIsCheckingAuth] = useState(true);
@@ -1,12 +1,18 @@
"use client"
import { ImpersonationBanner } from "./impersonation-banner"
import { TenantPreviewBanner } from "./tenant-preview-banner"
/**
* Client-side wrapper for the impersonation banner.
* Client-side wrapper for the impersonation and tenant preview banners.
* This is needed because the root layout is a server component,
* but the banner needs access to client-side auth state.
* but the banners need access to client-side auth/tenant state.
*/
export function ImpersonationBannerWrapper() {
return <ImpersonationBanner />
return (
<>
<ImpersonationBanner />
<TenantPreviewBanner />
</>
)
}
@@ -0,0 +1,56 @@
"use client"
import { useEffect, useState } from "react"
import { useTenant, isPreviewingTenant, getPreviewTenantId } from "@/lib/tenant"
import { useAuth } from "@/lib/auth"
import { Button } from "@/components/ui/button"
import { X, Eye } from "lucide-react"
/**
* Banner shown when an admin is previewing a tenant portal via ?preview_tenant=X.
* Only visible to admins. Shows which tenant is being previewed with an exit button.
*/
export function TenantPreviewBanner() {
const { user } = useAuth()
const { tenant } = useTenant()
const [isPreviewing, setIsPreviewing] = useState(false)
useEffect(() => {
setIsPreviewing(isPreviewingTenant())
}, [])
// Only show for admins previewing a tenant
if (!isPreviewing || user?.role !== "admin") {
return null
}
const previewTenantId = getPreviewTenantId()
const tenantName = tenant?.name || previewTenantId
const handleExitPreview = () => {
// Remove preview_tenant param and reload
const url = new URL(window.location.href)
url.searchParams.delete("preview_tenant")
window.location.href = url.toString()
}
return (
<div className="bg-purple-600 text-white px-4 py-2 flex items-center justify-between gap-4 text-sm font-medium">
<div className="flex items-center gap-2">
<Eye className="w-4 h-4" />
<span>
Previewing as <strong>{tenantName}</strong>
</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleExitPreview}
className="bg-purple-100 hover:bg-purple-200 text-purple-950 border-purple-400 h-7 px-3"
>
<X className="w-3 h-3 mr-1" />
Exit Preview
</Button>
</div>
)
}
+180
View File
@@ -0,0 +1,180 @@
/**
* Cloudflare Pages Function for the tenant portal build.
*
* Runs at the edge before serving static files. For HTML responses:
* 1. Detects tenant from hostname
* 2. Fetches tenant config from backend API (with edge caching)
* 3. Injects config as window.__TENANT_CONFIG__ so the frontend has it instantly
* 4. Injects initial CSS variables for instant branding (no FOUC)
*
* Non-HTML requests (JS, CSS, images) pass through unmodified.
*/
interface TenantBranding {
primary_color: string
secondary_color: string
accent_color: string | null
background_color: string | null
favicon_url: string | null
site_title: string
}
interface TenantPublicConfig {
id: string
name: string
subdomain: string
is_active: boolean
branding: TenantBranding
}
interface TenantConfigResponse {
tenant: TenantPublicConfig | null
is_default: boolean
}
const API_BASE_URL = "https://api.nomadkaraoke.com"
const CACHE_TTL_SECONDS = 300 // 5 minutes
/**
* Extract tenant ID from hostname.
* Supports: {tenant}.nomadkaraoke.com and {tenant}.gen.nomadkaraoke.com
*/
function extractTenantFromHost(hostname: string): string | null {
const parts = hostname.toLowerCase().split(".")
const nonTenantSubdomains = ["gen", "api", "www", "buy", "admin", "app", "beta"]
// Accept exactly 3 parts (tenant.nomadkaraoke.com)
// or exactly 4 parts where second is "gen" (tenant.gen.nomadkaraoke.com)
const isThreePart = parts.length === 3 && parts[1] === "nomadkaraoke" && parts[2] === "com"
const isFourPart = parts.length === 4 && parts[1] === "gen" && parts[2] === "nomadkaraoke" && parts[3] === "com"
if ((isThreePart || isFourPart) && !nonTenantSubdomains.includes(parts[0])) {
return parts[0]
}
return null
}
/**
* Fetch tenant config from backend with Cloudflare Cache API caching.
*/
async function fetchTenantConfigCached(
tenantId: string,
cacheKey: string
): Promise<TenantConfigResponse | null> {
// Try cache first
const cache = caches.default
const cachedResponse = await cache.match(cacheKey)
if (cachedResponse) {
try {
return await cachedResponse.json()
} catch {
// Cache corrupted, proceed to fetch
}
}
// Fetch from backend
try {
const response = await fetch(
`${API_BASE_URL}/api/tenant/config?tenant=${encodeURIComponent(tenantId)}`,
{
headers: {
"Content-Type": "application/json",
"X-Tenant-ID": tenantId,
},
}
)
if (!response.ok) {
console.error(`Tenant config fetch failed: ${response.status}`)
return null
}
const data: TenantConfigResponse = await response.json()
// Cache the response
const cacheResponse = new Response(JSON.stringify(data), {
headers: {
"Content-Type": "application/json",
"Cache-Control": `s-maxage=${CACHE_TTL_SECONDS}`,
},
})
// Don't await — fire-and-forget cache put
cache.put(cacheKey, cacheResponse)
return data
} catch (err) {
console.error("Failed to fetch tenant config:", err)
return null
}
}
/**
* Escape a string for safe injection into an HTML <script> tag.
* Prevents XSS via </script> or <!-- injection.
*/
function escapeForScript(json: string): string {
return json
.replace(/</g, "\\u003c")
.replace(/>/g, "\\u003e")
.replace(/&/g, "\\u0026")
}
export const onRequest: PagesFunction = async (context) => {
// Serve the static file first
const response = await context.next()
// Only modify HTML responses
const contentType = response.headers.get("content-type") || ""
if (!contentType.includes("text/html")) {
return response
}
// Extract tenant from hostname
const url = new URL(context.request.url)
const tenantId = extractTenantFromHost(url.hostname)
if (!tenantId) {
return response
}
// Fetch tenant config (cached at edge)
const cacheKey = `${url.origin}/__tenant_config__/${tenantId}`
const config = await fetchTenantConfigCached(tenantId, cacheKey)
if (!config || !config.tenant) {
return response
}
// Build injection: config script + CSS variables for instant branding
const configJson = escapeForScript(JSON.stringify(config))
const branding = config.tenant.branding
const cssVars = [
`--tenant-primary:${branding.primary_color}`,
`--tenant-secondary:${branding.secondary_color}`,
]
if (branding.accent_color) {
cssVars.push(`--tenant-accent:${branding.accent_color}`)
}
if (branding.background_color) {
cssVars.push(`--tenant-background:${branding.background_color}`)
}
const injection = [
`<script>window.__TENANT_CONFIG__=${configJson};</script>`,
`<style>:root{${cssVars.join(";")}}</style>`,
].join("\n")
// Inject before </head>
const html = await response.text()
const modifiedHtml = html.replace("</head>", injection + "\n</head>")
// Return modified response preserving headers
const newHeaders = new Headers(response.headers)
// Remove content-length since we modified the body
newHeaders.delete("content-length")
return new Response(modifiedHtml, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
})
}
+116
View File
@@ -9,6 +9,8 @@ import {
useTenant,
getTenantHeaders,
isFeatureEnabled,
isPreviewingTenant,
getPreviewTenantId,
TenantConfig,
} from "../tenant"
@@ -375,3 +377,117 @@ describe("API fetch behavior", () => {
)
})
})
describe("edge-injected config (window.__TENANT_CONFIG__)", () => {
beforeEach(() => {
jest.clearAllMocks()
resetStore()
// Clean up any injected config
delete (window as any).__TENANT_CONFIG__
})
afterEach(() => {
delete (window as any).__TENANT_CONFIG__
})
it("should use edge-injected config when available", async () => {
;(window as any).__TENANT_CONFIG__ = {
tenant: SAMPLE_VOCALSTAR_CONFIG,
is_default: false,
}
await useTenant.getState().fetchTenantConfig()
const state = useTenant.getState()
expect(state.tenant?.id).toBe("vocalstar")
expect(state.isDefault).toBe(false)
expect(state.isInitialized).toBe(true)
// Should NOT have made a fetch call
expect(global.fetch).not.toHaveBeenCalled()
})
it("should apply branding from edge-injected config", async () => {
;(window as any).__TENANT_CONFIG__ = {
tenant: SAMPLE_VOCALSTAR_CONFIG,
is_default: false,
}
await useTenant.getState().fetchTenantConfig()
expect(mockSetProperty).toHaveBeenCalledWith("--tenant-primary", "#ffff00")
expect(mockSetProperty).toHaveBeenCalledWith("--tenant-secondary", "#006CF9")
})
it("should fall back to API when no edge-injected config", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({ tenant: null, is_default: true }),
})
await useTenant.getState().fetchTenantConfig()
expect(global.fetch).toHaveBeenCalled()
})
it("should handle edge-injected config with null tenant", async () => {
;(window as any).__TENANT_CONFIG__ = {
tenant: null,
is_default: true,
}
await useTenant.getState().fetchTenantConfig()
const state = useTenant.getState()
expect(state.tenant).toBeNull()
expect(state.isDefault).toBe(true)
expect(state.isInitialized).toBe(true)
expect(global.fetch).not.toHaveBeenCalled()
})
})
describe("admin preview (preview_tenant param)", () => {
const originalLocation = window.location
beforeEach(() => {
resetStore()
})
afterEach(() => {
Object.defineProperty(window, "location", {
value: originalLocation,
writable: true,
})
})
it("isPreviewingTenant returns false when no preview param", () => {
Object.defineProperty(window, "location", {
value: { ...originalLocation, search: "" },
writable: true,
})
expect(isPreviewingTenant()).toBe(false)
})
it("isPreviewingTenant returns true when preview_tenant param exists", () => {
Object.defineProperty(window, "location", {
value: { ...originalLocation, search: "?preview_tenant=vocalstar" },
writable: true,
})
expect(isPreviewingTenant()).toBe(true)
})
it("getPreviewTenantId returns null when no preview param", () => {
Object.defineProperty(window, "location", {
value: { ...originalLocation, search: "" },
writable: true,
})
expect(getPreviewTenantId()).toBeNull()
})
it("getPreviewTenantId returns tenant ID when preview param exists", () => {
Object.defineProperty(window, "location", {
value: { ...originalLocation, search: "?preview_tenant=singa" },
writable: true,
})
expect(getPreviewTenantId()).toBe("singa")
})
})
+7
View File
@@ -73,6 +73,13 @@ export const useAuth = create<AuthStore>()(
// Store the session token
setAccessToken(response.session_token)
// Store tenant_subdomain for cross-domain redirect safety
if (typeof window !== 'undefined' && response.tenant_subdomain) {
(window as any).__LAST_VERIFY_RESPONSE__ = {
tenant_subdomain: response.tenant_subdomain,
}
}
// Create user from response
const user: User = {
token: response.session_token,
+44 -3
View File
@@ -113,20 +113,27 @@ function getDefaults(state: TenantStore): TenantDefaults {
}
/**
* Detect tenant from current URL subdomain.
* Returns tenant ID if on a tenant subdomain, null otherwise.
* Detect tenant from current URL subdomain or admin preview param.
* Returns tenant ID if on a tenant subdomain or previewing, null otherwise.
*/
function detectTenantFromUrl(): string | null {
if (typeof window === "undefined") return null
const hostname = window.location.hostname.toLowerCase()
const params = new URLSearchParams(window.location.search)
// Local development - check for tenant query param
if (hostname === "localhost" || hostname === "127.0.0.1") {
const params = new URLSearchParams(window.location.search)
return params.get("tenant")
}
// Admin preview: ?preview_tenant=X on any domain
// The preview banner and auth check happen in the UI layer
const previewTenant = params.get("preview_tenant")
if (previewTenant) {
return previewTenant
}
// Production - check for subdomain
// Strict patterns:
// - {tenant}.nomadkaraoke.com (3 parts)
@@ -150,6 +157,24 @@ function detectTenantFromUrl(): string | null {
return null
}
/**
* Check if admin tenant preview is active (via ?preview_tenant=X query param).
*/
export function isPreviewingTenant(): boolean {
if (typeof window === "undefined") return false
const params = new URLSearchParams(window.location.search)
return !!params.get("preview_tenant")
}
/**
* Get the previewed tenant ID if admin preview is active.
*/
export function getPreviewTenantId(): string | null {
if (typeof window === "undefined") return null
const params = new URLSearchParams(window.location.search)
return params.get("preview_tenant")
}
const useTenantStore = create<TenantStore>()((set, get) => ({
// Initial state
tenant: null,
@@ -163,6 +188,22 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
const state = get()
if (state.isLoading) return // Already loading
// Check for edge-injected config (from Cloudflare Pages Function)
// This provides instant tenant config without a network request
if (typeof window !== "undefined" && (window as any).__TENANT_CONFIG__) {
const data = (window as any).__TENANT_CONFIG__ as TenantConfigResponse
set({
tenant: data.tenant,
isDefault: data.is_default,
isLoading: false,
isInitialized: true,
})
if (data.tenant) {
applyTenantBranding(data.tenant.branding)
}
return
}
set({ isLoading: true, error: null })
try {
+1
View File
@@ -31,6 +31,7 @@ export interface VerifyMagicLinkResponse {
session_token: string
user: UserPublic
message: string
tenant_subdomain?: string | null
}
export interface UserProfileResponse {
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.123.0"
version = "0.124.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"
+2
View File
@@ -0,0 +1,2 @@
name = "karaoke-gen-tenant"
pages_build_output_dir = "frontend/out"