Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.5 ac811d598b fix(auth): Remove token expiry for review/instrumental tokens (#284)
## Summary
- Remove 48-hour expiry from review and instrumental tokens
- Tokens are job-scoped (low risk) and become useless when job completes
anyway
- Frontend: prefer full auth token from localStorage for audio elements
(defense-in-depth)

## Problem
Users were getting 401 errors on review/instrumental pages when tokens
expired after 48 hours:
- `https://gen.nomadkaraoke.com/instrumental/?...` - audio wouldn't load
- `https://gen.nomadkaraoke.com/lyrics/?...` - page wouldn't load

## Root Cause
Both `review_token` and `instrumental_token` had 48-hour expiry, but
users often don't complete reviews within that window.

## Solution
Since these tokens are:
1. **Job-scoped** - can only access one specific job
2. **Non-destructive** - only used for reviewing/selecting, not creating
or deleting
3. **Naturally expiring** - become useless once job completes

There's no security benefit to expiring them. Removed expiry and added
frontend fallback to use full auth token when available.

## Test plan
- [x] Backend tests pass (1590 passed)
- [x] Frontend tests pass (181 passed)
- [x] Cleared expiry on affected jobs in prod - user to verify pages
work
- [ ] Verify instrumental review page loads:
https://gen.nomadkaraoke.com/instrumental/?baseApiUrl=https%3A%2F%2Fapi.nomadkaraoke.com%2Fapi%2Fjobs%2F7b5b21c1&instrumentalToken=Fh_RdPJz-PZ1jxOaJrwBVHufw_4OhtuN4PAWtIMLB0o
- [ ] Verify lyrics review page loads:
https://gen.nomadkaraoke.com/lyrics//?baseApiUrl=https%3A%2F%2Fapi.nomadkaraoke.com%2Fapi%2Freview%2F8a5b3822&reviewToken=wSvPSoG537CKv45DNw_lSgQggTU2D-818UYIp64MRSE

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 15:47:32 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 9426c8427e feat(infra): make GitHub runners org-wide (#283)
## Summary
- Change GitHub Actions runner registration from repository-level to
organization-level
- All 20 runners will now be available to any repo in the `nomadkaraoke`
org, not just karaoke-gen

## Changes
- Update registration API endpoint from
`/repos/nomadkaraoke/karaoke-gen/...` to `/orgs/nomadkaraoke/...`
- Update runner URL from `https://github.com/nomadkaraoke/karaoke-gen`
to `https://github.com/nomadkaraoke`
- Document `admin:org` PAT scope requirement in README (existing PAT
already has this scope)

## Test plan
- [ ] Merge PR and let Pulumi update infrastructure
- [ ] Restart runner VMs to re-register at org level
- [ ] Verify runners appear at
https://github.com/organizations/nomadkaraoke/settings/actions/runners
- [ ] Test workflow runs from another nomadkaraoke repo

## Post-deployment steps
After merge, restart VMs to re-register:
```bash
for i in {1..20}; do
  gcloud compute instances reset github-runner-$i --zone=us-central1-a
done
```

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 22:11:42 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 0a2f99bc5d chore: trigger deployment (#282)
Empty commit to trigger fresh deployment after GitHub Pages artifact
conflict.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **New Features**
* Enhanced authentication flow with automatic fallback between multiple
authentication methods, preventing logged-in users from being
interrupted when temporary credentials expire and improving access
continuity.

* **Documentation**
* Updated lessons learned guide with best practices for authentication
token management, including recommended prioritization strategies and
fallback approaches for standalone applications.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 11:27:07 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 1686c2afc6 fix(instrumental): Use localStorage auth token when available (#281)
## Summary

Fixes 401 errors on the instrumental selection page when users return
after the 48-hour magic link token has expired.

- The instrumental review page now checks localStorage for user auth
token before falling back to the URL token
- Logged-in users will always be able to access their jobs' instrumental
selection

## Changes

- Added `fullAuthToken` check from
`localStorage.getItem('karaoke_access_token')`
- Created `authFetch()` helper with priority: full auth (Bearer header)
> instrumental token (query param)
- Updated all 5 fetch calls to use `authFetch()`
- Added lesson learned to documentation

## Testing

- [x] All 98 tests pass (`make test`)
- [x] CodeRabbit CLI review completed locally

## Review

- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (none found)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 10:48:19 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 49fef0d209 fix(admin): Fix impersonate button not working due to AuthResult subscripting (#280)
## Summary

- Fixed impersonate button returning 500 error due to incorrect
AuthResult access
- Backend was using `auth_data[0]` but AuthResult doesn't support
subscripting
- Added loading indicator and error feedback for better UX

## Changes

### Backend
- Changed `auth_data[0]` to `auth_data.user_email` in impersonate
endpoint
- Fixed type hint from `Tuple[str, UserType, int]` to `AuthResult`
- Updated test mocks to return `AuthResult` instead of tuple

### Frontend
- Added loading spinner on impersonate button during API call
- Added toast notification when impersonation fails (previously silent
failure)
- Added E2E test for impersonate button click functionality

## Test plan

- [x] Backend unit tests pass (1590 passed)
- [x] Frontend E2E tests pass (98 passed)
- [x] Impersonation-specific tests pass
- [ ] Manual test: Click impersonate button in admin panel
- [ ] Verify redirect to /app as impersonated user
- [ ] Verify impersonation banner shows

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 05:29:26 +00:00
Andrew Beveridge ☄️andClaude Opus 4.5 0c4e946bb8 fix(gce): Use version sort for wheel selection in encoding worker (#277)
## Summary
- Fixed encoding worker startup script to use version sort (`sort -V`)
instead of time sort (`ls -t`) when selecting the wheel to install
- All wheels download simultaneously with identical timestamps, so time
sort picked arbitrarily (0.99.9) instead of the latest (0.105.0)
- Fixed zone references in CLAUDE.md and infrastructure/README.md
(us-central1-a → us-central1-c)
- Added lesson learned about version sorting for artifact selection

## Test plan
- [x] Shell script syntax validated
- [x] Manually verified fix on running VM - worker now reports version
0.105.0
- [ ] Future restarts will correctly select highest version wheel

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-11 10:39:31 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 082d36a3c9 fix(pwa): Add service worker file that was gitignored (#276)
## Summary
- Adds the service worker file that was previously gitignored
- Updates gitignore to allow sw.js (hand-written) while still ignoring
auto-generated PWA files

## Context
The sw.js service worker file was created in PR #274 but was blocked
from being tracked by a gitignore rule meant for auto-generated PWA
files. Without this file, push notifications cannot work because the
browser has no service worker to receive push events.

## Test plan
- [ ] CI passes
- [ ] `curl https://gen.nomadkaraoke.com/sw.js` returns JavaScript after
deploy

@coderabbitai ignore

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 18:14:51 -05:00
Andrew Beveridge ☄️andClaude Opus 4.5 402eb9d86b fix(docker): Add missing backend directory to Dockerfile.base (#275)
## Summary
- Fixes Docker base image build failure by adding missing `backend`
directory to COPY command

## Context
The `backend` package was previously added to `pyproject.toml` packages
list but `Dockerfile.base` wasn't updated to copy the directory. This
caused the editable install to fail with:

```
ValueError: /app/backend does not contain any element
```

This was discovered when the push notifications PR (#274) triggered a
base image rebuild.

## Test plan
- [ ] CI passes (specifically Deploy - Backend job should succeed now)

@coderabbitai ignore

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 17:38:26 -05:00
16 changed files with 374 additions and 41 deletions

No files matched your search

+1 -2
View File
@@ -58,8 +58,7 @@ frontend/.eslintcache
# Storybook
frontend/storybook-static/
# PWA files
frontend/**/public/sw.js
# PWA auto-generated files (our sw.js is hand-written and should be tracked)
frontend/**/public/workbox-*.js
frontend/**/public/swe-worker-*.js
+2 -2
View File
@@ -105,11 +105,11 @@ EOF
### GCE Encoding Worker
```bash
# SSH to restart service (clears in-memory job queue)
gcloud compute ssh encoding-worker --zone=us-central1-a --project=nomadkaraoke \
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
# Check health
gcloud compute ssh encoding-worker --zone=us-central1-a --project=nomadkaraoke \
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health"
```
+1
View File
@@ -54,6 +54,7 @@ WORKDIR /app
COPY pyproject.toml README.md LICENSE /app/
COPY karaoke_gen /app/karaoke_gen
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
COPY backend /app/backend
# Install all Python dependencies (the slow part - cached in base image)
RUN pip install --no-cache-dir --upgrade pip && \
+2 -2
View File
@@ -1509,7 +1509,7 @@ class ImpersonateUserResponse(BaseModel):
@router.post("/users/{email}/impersonate", response_model=ImpersonateUserResponse)
async def impersonate_user(
email: str,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
@@ -1531,7 +1531,7 @@ async def impersonate_user(
user_email: The impersonated user's email
message: Success message
"""
admin_email = auth_data[0]
admin_email = auth_data.user_email or "unknown"
target_email = email.lower()
# Cannot impersonate yourself
+9 -9
View File
@@ -374,22 +374,22 @@ class JobManager:
updates['progress'] = progress
# Generate review token when entering AWAITING_REVIEW state
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
if new_status == JobStatus.AWAITING_REVIEW:
from backend.api.dependencies import generate_review_token, get_review_token_expiry
from backend.api.dependencies import generate_review_token
review_token = generate_review_token()
review_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
updates['review_token'] = review_token
updates['review_token_expires_at'] = review_token_expires
logger.info(f"Generated review token for job {job_id}, expires in 48 hours")
updates['review_token_expires_at'] = None # No expiry - token is job-scoped
logger.info(f"Generated review token for job {job_id} (no expiry)")
# Generate instrumental token when entering AWAITING_INSTRUMENTAL_SELECTION state
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
from backend.api.dependencies import generate_review_token, get_review_token_expiry
from backend.api.dependencies import generate_review_token
instrumental_token = generate_review_token() # Reuse same token generator
instrumental_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
updates['instrumental_token'] = instrumental_token
updates['instrumental_token_expires_at'] = instrumental_token_expires
logger.info(f"Generated instrumental token for job {job_id}, expires in 48 hours")
updates['instrumental_token_expires_at'] = None # No expiry - token is job-scoped
logger.info(f"Generated instrumental token for job {job_id} (no expiry)")
# If we have state_data_updates, merge them with existing state_data
merged_state_data = None
+18 -3
View File
@@ -11,6 +11,7 @@ from fastapi import FastAPI
from backend.api.routes.admin import router
from backend.api.dependencies import require_admin
from backend.services.user_service import get_user_service
from backend.services.auth_service import AuthResult, UserType
from backend.models.user import User, Session
@@ -20,15 +21,29 @@ app.include_router(router, prefix="/api")
def get_mock_admin():
"""Override for require_admin dependency - returns admin user."""
return ("admin@nomadkaraoke.com", "admin", 1)
"""Override for require_admin dependency - returns admin AuthResult."""
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="Admin session valid",
user_email="admin@nomadkaraoke.com",
is_admin=True,
)
def get_mock_regular_user():
"""Override for require_admin dependency - returns regular user (should fail)."""
# This simulates what happens when a non-admin tries to access
# In reality, require_admin raises 403, but we test the logic
return ("user@example.com", "user", 0)
return AuthResult(
is_valid=True,
user_type=UserType.LIMITED,
remaining_uses=5,
message="User session valid",
user_email="user@example.com",
is_admin=False,
)
@pytest.fixture
+7
View File
@@ -48,6 +48,9 @@ HTTP calls to services that can restart (VMs, containers) need retry logic with
### Cross-Domain localStorage
Auth tokens in localStorage are domain-isolated. Keep auth on a single domain or use cookies with `domain=.example.com`.
### Standalone HTML Pages Need Auth Fallback
Standalone HTML pages (like instrumental review) that use magic link tokens should also check localStorage for user auth tokens. Priority: full auth token (doesn't expire) > magic link token (expires). This prevents logged-in users from being blocked when their magic link expires.
### Tab Visibility Refresh
Use `visibilitychange` event for immediate refresh when user returns to tab, not just polling intervals.
@@ -148,6 +151,9 @@ Use `pulumi up --skip-preview --yes` when CI service account can't run preview.
### Docker Disk Management
Self-hosted runners need aggressive disk cleanup. Use threshold-based (70%) not age-based cleanup.
### Version Sort for Artifact Selection
When downloading multiple versioned files (wheels, tarballs), use `sort -V | tail -1` not `ls -t | head -1`. Files downloaded simultaneously have the same timestamp, so time-based sorting picks arbitrarily. Version sorting (`sort -V`) correctly identifies the highest semantic version.
---
## Performance Patterns
@@ -240,3 +246,4 @@ When mocking tenant middleware, patch both the middleware import path AND the se
3. **Design for async human review upfront** - Avoided rearchitecting later
4. **Keep docs minimal and current** - Less documentation, always accurate
5. **Check gitignore early for new directories** - Especially frontend `lib/` dirs
+20 -2
View File
@@ -70,6 +70,9 @@ export default function AdminUsersPage() {
const [creditReason, setCreditReason] = useState("")
const [addingCredits, setAddingCredits] = useState(false)
// Impersonation state - tracks which user is being impersonated (for loading indicator)
const [impersonatingEmail, setImpersonatingEmail] = useState<string | null>(null)
const loadUsers = useCallback(async () => {
try {
setLoading(true)
@@ -158,6 +161,7 @@ export default function AdminUsersPage() {
return
}
setImpersonatingEmail(user.email)
try {
const success = await startImpersonation(user.email)
if (success) {
@@ -167,6 +171,14 @@ export default function AdminUsersPage() {
})
// Redirect to main app to see the user's view
router.push("/app")
} else {
// startImpersonation returned false - get the error from auth store
const authError = useAuth.getState().error
toast({
title: "Impersonation Failed",
description: authError || "Unable to impersonate user. Please try again.",
variant: "destructive",
})
}
} catch (err: any) {
toast({
@@ -174,6 +186,8 @@ export default function AdminUsersPage() {
description: err.message || "Failed to impersonate user",
variant: "destructive",
})
} finally {
setImpersonatingEmail(null)
}
}
@@ -298,9 +312,13 @@ export default function AdminUsersPage() {
size="icon"
onClick={() => handleImpersonate(user)}
title="Impersonate user"
disabled={user.email === currentUser?.email}
disabled={user.email === currentUser?.email || impersonatingEmail !== null}
>
<LogIn className="w-4 h-4" />
{impersonatingEmail === user.email ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<LogIn className="w-4 h-4" />
)}
</Button>
</div>
</TableCell>
@@ -190,6 +190,86 @@ test.describe('User Impersonation', () => {
const impersonateButton = adminRow.locator('button[title="Impersonate user"]');
await expect(impersonateButton).toBeDisabled();
});
test('clicking impersonate button makes API call', async ({ page }) => {
await setAuthToken(page, 'admin-test-token');
// Track if impersonate API was called
const impersonateCalls: string[] = [];
await setupApiFixtures(page, {
mocks: [
{
method: 'GET',
path: '/api/users/me',
response: { body: { user: mockAdminUser } },
},
{
method: 'GET',
path: '/api/users/admin/users',
response: { body: mockUserList },
},
{
method: 'GET',
path: '/api/tenant/config',
response: { body: { brand_code: null, is_white_label: false } },
},
// Mock the impersonate endpoint
{
method: 'POST',
path: '/api/admin/users/:email/impersonate',
response: {
body: {
session_token: 'impersonation-token-123',
user_email: 'user@example.com',
message: 'Impersonation started',
},
},
},
],
});
// Also add a listener to track the actual impersonate call
await page.route('**/api/admin/users/*/impersonate', async (route) => {
const url = route.request().url();
const match = url.match(/\/api\/admin\/users\/([^/]+)\/impersonate/);
if (match) {
impersonateCalls.push(decodeURIComponent(match[1]));
}
// Continue to the mock server
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
session_token: 'impersonation-token-123',
user_email: decodeURIComponent(match?.[1] || ''),
message: 'Impersonation started',
}),
});
});
await page.goto('/admin/users');
await page.waitForLoadState('networkidle');
// Find the row for the target user (not admin)
const targetUserRow = page.locator('tr').filter({ hasText: 'user@example.com' });
await expect(targetUserRow).toBeVisible();
// Get the impersonate button
const impersonateButton = targetUserRow.locator('button[title="Impersonate user"]');
await expect(impersonateButton).toBeVisible();
await expect(impersonateButton).toBeEnabled();
// Click the impersonate button
await impersonateButton.click();
// Wait a bit for the API call to be made
await page.waitForTimeout(1000);
// Verify the API was called
expect(impersonateCalls.length).toBeGreaterThan(0);
expect(impersonateCalls[0]).toBe('user@example.com');
});
});
test.describe('Impersonation Security', () => {
+183
View File
@@ -0,0 +1,183 @@
/**
* Service Worker for Web Push Notifications
*
* Handles push events and notification clicks for the Karaoke Generator PWA.
* This service worker is registered by the ServiceWorkerRegistration component.
*/
// Cache name for static assets (versioned for updates)
const CACHE_VERSION = 'v1';
const STATIC_CACHE = `karaoke-gen-static-${CACHE_VERSION}`;
// Assets to cache for offline support
const STATIC_ASSETS = [
'/nomad-logo.png',
'/nomad-karaoke-logo.svg',
'/favicon.ico',
];
/**
* Install event - cache static assets
*/
self.addEventListener('install', (event) => {
console.log('[SW] Installing service worker...');
event.waitUntil(
caches.open(STATIC_CACHE).then((cache) => {
return cache.addAll(STATIC_ASSETS);
}).then(() => {
console.log('[SW] Static assets cached');
return self.skipWaiting(); // Activate immediately
})
);
});
/**
* Activate event - clean up old caches
*/
self.addEventListener('activate', (event) => {
console.log('[SW] Activating service worker...');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name.startsWith('karaoke-gen-') && name !== STATIC_CACHE)
.map((name) => {
console.log('[SW] Deleting old cache:', name);
return caches.delete(name);
})
);
}).then(() => {
console.log('[SW] Service worker activated');
return self.clients.claim(); // Take control of all pages
})
);
});
/**
* Push event - show notification when push message received
*/
self.addEventListener('push', (event) => {
console.log('[SW] Push event received');
let data = {
title: 'Karaoke Generator',
body: 'You have a notification',
icon: '/nomad-logo.png',
tag: 'default',
url: '/app/',
};
// Parse push data if available
if (event.data) {
try {
const payload = event.data.json();
data = {
title: payload.title || data.title,
body: payload.body || data.body,
icon: payload.icon || data.icon,
tag: payload.tag || data.tag,
url: payload.url || data.url,
};
} catch (err) {
console.error('[SW] Error parsing push data:', err);
// Try as text
const text = event.data.text();
if (text) {
data.body = text;
}
}
}
// Show the notification
const options = {
body: data.body,
icon: data.icon,
badge: '/favicon-32x32.png',
tag: data.tag, // Replaces notifications with same tag
renotify: true, // Vibrate/sound even if replacing
requireInteraction: true, // Don't auto-dismiss
data: {
url: data.url,
},
// Actions for the notification (optional)
actions: [
{
action: 'open',
title: 'Open',
},
{
action: 'dismiss',
title: 'Dismiss',
},
],
};
event.waitUntil(
self.registration.showNotification(data.title, options)
);
});
/**
* Notification click event - open the app or focus existing window
*/
self.addEventListener('notificationclick', (event) => {
console.log('[SW] Notification clicked:', event.action);
event.notification.close();
// Handle dismiss action
if (event.action === 'dismiss') {
return;
}
// Get the URL to open
const url = event.notification.data?.url || '/app/';
const fullUrl = new URL(url, self.location.origin).href;
// Try to focus an existing window or open a new one
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
// Check if there's already a window open
for (const client of clients) {
// If we find a matching URL, focus it
if (client.url === fullUrl && 'focus' in client) {
return client.focus();
}
}
// Check if there's any window from our origin
for (const client of clients) {
if (client.url.startsWith(self.location.origin) && 'focus' in client) {
// Navigate the existing window and focus it
return client.navigate(fullUrl).then((client) => client?.focus());
}
}
// No existing window, open a new one
if (self.clients.openWindow) {
return self.clients.openWindow(fullUrl);
}
})
);
});
/**
* Notification close event - cleanup if needed
*/
self.addEventListener('notificationclose', (event) => {
console.log('[SW] Notification closed');
// Could track analytics here if desired
});
/**
* Message event - handle messages from the main app
*/
self.addEventListener('message', (event) => {
console.log('[SW] Message received:', event.data);
if (event.data?.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
console.log('[SW] Service worker loaded');
+6 -4
View File
@@ -124,7 +124,7 @@ echo -n "key" | gcloud secrets versions add genius-api-key --data-file=-
echo -n "key" | gcloud secrets versions add red-api-key --data-file=-
echo -n "url" | gcloud secrets versions add red-api-url --data-file=-
# GitHub runner PAT (repo scope)
# GitHub runner PAT (admin:org scope for org-level runners)
echo -n "ghp_xxx" | gcloud secrets versions add github-runner-pat --data-file=-
```
@@ -146,12 +146,14 @@ Note: `deploy.sh` uploads the source ZIP to GCS. Pulumi creates the function res
## Self-Hosted GitHub Runners
20 GCP VMs serve as self-hosted runners with:
20 GCP VMs serve as organization-level self-hosted runners, available to all repos in the `nomadkaraoke` org:
- 200GB SSD (vs 14GB on GitHub-hosted)
- Pre-installed: Docker, Python 3.13, Node 20, Java 21, FFmpeg
- Labels: `self-hosted`, `linux`, `x64`, `gcp`, `large-disk`
**Usage in workflows:**
**PAT Requirements:** The `github-runner-pat` secret requires `admin:org` scope (specifically `manage_runners:org`) for organization-level runner registration.
**Usage in workflows (any nomadkaraoke repo):**
```yaml
runs-on: [self-hosted, linux, gcp]
```
@@ -182,7 +184,7 @@ High-performance VM for video encoding:
**Troubleshooting:**
```bash
gcloud compute ssh encoding-worker --zone=us-central1-a -- \
gcloud compute ssh encoding-worker --zone=us-central1-c -- \
"sudo systemctl status encoding-worker"
```
+1 -1
View File
@@ -20,7 +20,7 @@ def create_github_runners(
Create GitHub Actions self-hosted runner VM instances.
Creates NUM_GITHUB_RUNNERS VMs, each configured as a GitHub Actions
self-hosted runner for the karaoke-gen repository.
self-hosted runner for the nomadkaraoke organization (available to all repos).
Args:
service_account: The GitHub runner service account.
@@ -124,23 +124,23 @@ if [ -z "$GITHUB_PAT" ]; then
exit 1
fi
# Get runner registration token using PAT
# Get runner registration token using PAT (organization-level)
echo "Getting runner registration token..."
REGISTRATION_TOKEN=$(curl -s -X POST \
-H "Authorization: token $GITHUB_PAT" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/nomadkaraoke/karaoke-gen/actions/runners/registration-token | jq -r .token)
https://api.github.com/orgs/nomadkaraoke/actions/runners/registration-token | jq -r .token)
if [ -z "$REGISTRATION_TOKEN" ] || [ "$REGISTRATION_TOKEN" = "null" ]; then
echo "ERROR: Failed to get registration token"
exit 1
fi
# Configure runner (non-interactive)
# Configure runner (non-interactive) - registered at organization level
echo "Configuring runner..."
cd $RUNNER_DIR
sudo -u runner ./config.sh \
--url https://github.com/nomadkaraoke/karaoke-gen \
--url https://github.com/nomadkaraoke \
--token "$REGISTRATION_TOKEN" \
--name "gcp-runner-$(hostname)" \
--labels "self-hosted,linux,x64,gcp,large-disk" \
@@ -154,7 +154,7 @@ echo "Installing runner service..."
./svc.sh start
echo "GitHub Actions runner setup complete at $(date)"
echo "Runner registered with labels: self-hosted,linux,x64,gcp,large-disk"
echo "Runner registered at organization level (nomadkaraoke) with labels: self-hosted,linux,x64,gcp,large-disk"
# ==================== Setup Python in tool cache ====================
# setup-python action looks for Python in RUNNER_TOOL_CACHE/_tool/Python
+3 -1
View File
@@ -118,7 +118,9 @@ echo "ENCODING_API_KEY=${ENCODING_API_KEY}" > /opt/encoding-worker/env
# This enables hot code updates without rebuilding the image
echo "Installing latest karaoke-gen wheel from GCS..."
gsutil cp "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl" /tmp/ 2>/dev/null || true
WHEEL_FILE=$(ls -t /tmp/karaoke_gen-*.whl 2>/dev/null | head -1)
# Use version sort (-V) to get the highest version, not time sort (-t)
# All wheels download at the same time, so -t picks arbitrarily
WHEEL_FILE=$(ls /tmp/karaoke_gen-*.whl 2>/dev/null | sort -V | tail -1)
if [ -n "$WHEEL_FILE" ]; then
echo "Installing wheel: $WHEEL_FILE"
/opt/encoding-worker/venv/bin/pip install --upgrade --quiet "$WHEEL_FILE" || echo "WARNING: Failed to install wheel"
@@ -750,18 +750,44 @@
const urlParams = new URLSearchParams(window.location.search);
const encodedBaseApiUrl = urlParams.get('baseApiUrl');
const instrumentalToken = urlParams.get('instrumentalToken');
// Check localStorage for full auth token (logged-in users)
// This takes priority over instrumentalToken which can expire
const fullAuthToken = localStorage.getItem('karaoke_access_token');
// Determine API base URL - cloud mode uses provided URL, local mode uses default
const API_BASE = encodedBaseApiUrl
const API_BASE = encodedBaseApiUrl
? decodeURIComponent(encodedBaseApiUrl)
: '/api/jobs/local';
// Helper to add token to URL if available
// Helper to add auth token to URL
// Priority: fullAuthToken (doesn't expire) > instrumentalToken (expires after 48h)
// This is essential for audio elements which can't use Bearer headers
function addTokenToUrl(url) {
// Prefer full auth token - it doesn't have the short expiry that magic link tokens have
if (fullAuthToken) {
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}token=${encodeURIComponent(fullAuthToken)}`;
}
// Fall back to instrumental token for non-logged-in users
if (!instrumentalToken) return url;
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}instrumental_token=${encodeURIComponent(instrumentalToken)}`;
}
// Auth-aware fetch helper
// Priority: fullAuthToken (Bearer header) > instrumentalToken (query param)
function authFetch(url, options = {}) {
if (fullAuthToken) {
// Use Bearer auth for logged-in users
const headers = new Headers(options.headers || {});
headers.set('Authorization', `Bearer ${fullAuthToken}`);
return fetch(url, { ...options, headers });
} else {
// Fall back to instrumental token in URL
return fetch(addTokenToUrl(url), options);
}
}
// HTML escape helper to prevent XSS
function escapeHtml(str) {
@@ -780,8 +806,8 @@
async function init() {
try {
const [analysisRes, waveformRes] = await Promise.all([
fetch(addTokenToUrl(`${API_BASE}/instrumental-analysis`)),
fetch(addTokenToUrl(`${API_BASE}/waveform-data?num_points=1000`))
authFetch(`${API_BASE}/instrumental-analysis`),
authFetch(`${API_BASE}/waveform-data?num_points=1000`)
]);
if (!analysisRes.ok) throw new Error('Failed to load analysis');
@@ -1484,7 +1510,7 @@
const formData = new FormData();
formData.append('file', file);
const response = await fetch(addTokenToUrl(`${API_BASE}/upload-instrumental`), {
const response = await authFetch(`${API_BASE}/upload-instrumental`, {
method: 'POST',
body: formData
});
@@ -1543,7 +1569,7 @@
}
try {
const response = await fetch(addTokenToUrl(`${API_BASE}/create-custom-instrumental`), {
const response = await authFetch(`${API_BASE}/create-custom-instrumental`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mute_regions: muteRegions })
@@ -1593,7 +1619,7 @@
}
try {
const response = await fetch(addTokenToUrl(`${API_BASE}/select-instrumental`), {
const response = await authFetch(`${API_BASE}/select-instrumental`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ selection: selectedOption })
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.105.0"
version = "0.105.4"
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"