mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-28 01:49:00 +09:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -148,6 +148,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
|
||||
|
||||
@@ -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');
|
||||
@@ -182,7 +182,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"
|
||||
```
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.105.0"
|
||||
version = "0.105.2"
|
||||
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