mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-25 16:39:03 +09:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac811d598b | ||
|
|
9426c8427e | ||
|
|
0a2f99bc5d | ||
|
|
1686c2afc6 | ||
|
|
49fef0d209 | ||
|
|
0c4e946bb8 | ||
|
|
082d36a3c9 | ||
|
|
402eb9d86b |
No files matched your search
+1
-2
@@ -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
|
||||
|
||||
|
||||
@@ -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"
|
||||
```
|
||||
|
||||
|
||||
@@ -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 && \
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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');
|
||||
@@ -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"
|
||||
```
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user