Initial commit

This commit is contained in:
Jarek Krochmalski
2025-12-28 21:16:03 +01:00
commit 62e3c6439e
552 changed files with 104858 additions and 0 deletions

View File

@@ -0,0 +1,88 @@
import { json } from '@sveltejs/kit';
import { getContainerEvents, getContainerEventContainers, getContainerEventActions, getContainerEventStats, clearContainerEvents, type ContainerEventFilters, type ContainerEventAction } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
// Parse query parameters
const filters: ContainerEventFilters = {};
const envId = url.searchParams.get('environmentId');
const envIdNum = envId ? parseInt(envId) : undefined;
// Permission check with environment context
if (auth.authEnabled && !await auth.can('activity', 'view', envIdNum)) {
return json({ error: 'Permission denied' }, { status: 403 });
}
try {
if (envIdNum) {
// Specific environment requested - use it
filters.environmentId = envIdNum;
} else if (auth.isEnterprise && auth.authEnabled && !auth.isAdmin) {
// Enterprise with auth enabled and non-admin: filter by accessible environments
const accessibleEnvIds = await auth.getAccessibleEnvironmentIds();
if (accessibleEnvIds !== null) {
// User has limited access - filter by their accessible environments
if (accessibleEnvIds.length === 0) {
// No access to any environment - return empty
return json({ events: [], total: 0, limit: 100, offset: 0 });
}
filters.environmentIds = accessibleEnvIds;
}
// If accessibleEnvIds is null, user has access to all environments
}
const containerId = url.searchParams.get('containerId');
if (containerId) filters.containerId = containerId;
const containerName = url.searchParams.get('containerName');
if (containerName) filters.containerName = containerName;
// Support multi-select actions filter (comma-separated)
const actions = url.searchParams.get('actions');
if (actions) filters.actions = actions.split(',').filter(Boolean) as ContainerEventAction[];
// Labels filter (comma-separated)
const labels = url.searchParams.get('labels');
if (labels) filters.labels = labels.split(',').filter(Boolean);
const fromDate = url.searchParams.get('fromDate');
if (fromDate) filters.fromDate = fromDate;
const toDate = url.searchParams.get('toDate');
if (toDate) filters.toDate = toDate;
const limit = url.searchParams.get('limit');
if (limit) filters.limit = parseInt(limit);
const offset = url.searchParams.get('offset');
if (offset) filters.offset = parseInt(offset);
const result = await getContainerEvents(filters);
return json(result);
} catch (error) {
console.error('Error fetching container events:', error);
return json({ error: 'Failed to fetch container events' }, { status: 500 });
}
};
export const DELETE: RequestHandler = async ({ cookies }) => {
const auth = await authorize(cookies);
// Check permission - admins or users with activity delete permission
// In free edition, all authenticated users can delete
if (auth.authEnabled && !await auth.can('activity', 'delete')) {
return json({ error: 'Permission denied' }, { status: 403 });
}
try {
await clearContainerEvents();
return json({ success: true });
} catch (error) {
console.error('Error clearing container events:', error);
return json({ error: 'Failed to clear container events' }, { status: 500 });
}
};

View File

@@ -0,0 +1,42 @@
import { json } from '@sveltejs/kit';
import { getContainerEventContainers } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
const envId = url.searchParams.get('environment_id');
const envIdNum = envId ? parseInt(envId) : undefined;
// Permission check for activity viewing
if (auth.authEnabled && !await auth.can('activity', 'view', envIdNum)) {
return json({ error: 'Permission denied' }, { status: 403 });
}
try {
let environmentIds: number[] | undefined;
if (envIdNum) {
// Specific environment requested
const containers = await getContainerEventContainers(envIdNum);
return json(containers);
} else if (auth.isEnterprise && auth.authEnabled && !auth.isAdmin) {
// Enterprise with auth enabled and non-admin: filter by accessible environments
const accessibleEnvIds = await auth.getAccessibleEnvironmentIds();
if (accessibleEnvIds !== null) {
if (accessibleEnvIds.length === 0) {
// No access to any environment - return empty list
return json([]);
}
environmentIds = accessibleEnvIds;
}
}
const containers = await getContainerEventContainers(undefined, environmentIds);
return json(containers);
} catch (error) {
console.error('Error fetching container names:', error);
return json({ error: 'Failed to fetch container names' }, { status: 500 });
}
};

View File

@@ -0,0 +1,107 @@
import type { RequestHandler } from './$types';
import { containerEventEmitter } from '$lib/server/event-collector';
import { authorize } from '$lib/server/authorize';
import { json } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ cookies }) => {
const auth = await authorize(cookies);
// Permission check for activity viewing
if (auth.authEnabled && !await auth.can('activity', 'view')) {
return json({ error: 'Permission denied' }, { status: 403 });
}
// Get accessible environment IDs for filtering (enterprise only)
let accessibleEnvIds: number[] | null = null;
if (auth.isEnterprise && auth.authEnabled && !auth.isAdmin) {
accessibleEnvIds = await auth.getAccessibleEnvironmentIds();
// If user has no access to any environment, return empty stream
if (accessibleEnvIds !== null && accessibleEnvIds.length === 0) {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
controller.enqueue(encoder.encode(`event: connected\ndata: ${JSON.stringify({ timestamp: new Date().toISOString() })}\n\n`));
}
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no'
}
});
}
}
let heartbeatInterval: ReturnType<typeof setInterval>;
let handleEvent: ((event: any) => void) | null = null;
let handleEnvStatus: ((status: any) => void) | null = null;
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const sendEvent = (type: string, data: any) => {
try {
const event = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
controller.enqueue(encoder.encode(event));
} catch {
// Ignore errors when client disconnects
}
};
// Send initial connection event
sendEvent('connected', { timestamp: new Date().toISOString() });
// Send heartbeat to keep connection alive (every 5s to prevent Traefik 10s idle timeout)
heartbeatInterval = setInterval(() => {
try {
sendEvent('heartbeat', { timestamp: new Date().toISOString() });
} catch {
clearInterval(heartbeatInterval);
}
}, 5000);
// Listen for new container events (filter by accessible environments)
handleEvent = (event: any) => {
// If accessibleEnvIds is null, user has access to all environments
// Otherwise, filter by accessible environment IDs
if (accessibleEnvIds === null || (event.environmentId && accessibleEnvIds.includes(event.environmentId))) {
sendEvent('activity', event);
}
};
// Listen for environment status changes (online/offline)
handleEnvStatus = (status: any) => {
if (accessibleEnvIds === null || (status.envId && accessibleEnvIds.includes(status.envId))) {
sendEvent('env_status', status);
}
};
containerEventEmitter.on('event', handleEvent);
containerEventEmitter.on('env_status', handleEnvStatus);
},
cancel() {
// Cleanup when client disconnects
clearInterval(heartbeatInterval);
if (handleEvent) {
containerEventEmitter.off('event', handleEvent);
handleEvent = null;
}
if (handleEnvStatus) {
containerEventEmitter.off('env_status', handleEnvStatus);
handleEnvStatus = null;
}
}
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no'
}
});
};

View File

@@ -0,0 +1,42 @@
import { json } from '@sveltejs/kit';
import { getContainerEventStats } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
const envId = url.searchParams.get('environment_id');
const envIdNum = envId ? parseInt(envId) : undefined;
// Permission check for activity viewing
if (auth.authEnabled && !await auth.can('activity', 'view', envIdNum)) {
return json({ error: 'Permission denied' }, { status: 403 });
}
try {
let environmentIds: number[] | undefined;
if (envIdNum) {
// Specific environment requested
const stats = await getContainerEventStats(envIdNum);
return json(stats);
} else if (auth.isEnterprise && auth.authEnabled && !auth.isAdmin) {
// Enterprise with auth enabled and non-admin: filter by accessible environments
const accessibleEnvIds = await auth.getAccessibleEnvironmentIds();
if (accessibleEnvIds !== null) {
if (accessibleEnvIds.length === 0) {
// No access to any environment - return empty stats
return json({ total: 0, today: 0, byAction: {} });
}
environmentIds = accessibleEnvIds;
}
}
const stats = await getContainerEventStats(undefined, environmentIds);
return json(stats);
} catch (error) {
console.error('Error fetching container event stats:', error);
return json({ error: 'Failed to fetch stats' }, { status: 500 });
}
};