Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions infrastructure/control-panel/.env.example
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,11 @@ LOKI_PASSWORD=admin

# Registry Configuration
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173

# Notification Trigger (for Notifications tab proxy)
NOTIFICATION_TRIGGER_URL=http://localhost:3998

# W3DS Auth Configuration
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
28 changes: 28 additions & 0 deletions infrastructure/control-panel/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,13 @@ A SvelteKit-based control panel for monitoring and managing various services and
- **Pod Details**: Access detailed pod information including YAML configuration and resource usage
- **Metrics**: View pod performance metrics (when metrics-server is available)

### W3DS Admin Authentication

- **W3DS login flow**: `/login` uses `w3ds://auth` offer + wallet signature callback
- **Signature verification**: Auth callback verifies signatures with `signature-validator` against `PUBLIC_REGISTRY_URL`
- **Static admin allowlist**: Access is granted only if the authenticated eName exists in `config/admin-enames.json`
- **No local DB**: Admin authorization is file-based and reloaded from disk when changed

## Prerequisites

### Kubernetes Access
Expand DownExpand Up@@ -107,6 +114,27 @@ Returns detailed information about a specific pod.

## Configuration

### Authentication Setup

1. Copy `.env.example` to `.env` and configure:

```env
PUBLIC_REGISTRY_URL=https://registry.staging.metastate.foundation
PUBLIC_CONTROL_PANEL_URL=http://localhost:5173
CONTROL_PANEL_JWT_SECRET=replace-with-a-strong-secret
CONTROL_PANEL_ADMIN_ENAMES_FILE=config/admin-enames.json
```

2. Add admin eNames to `config/admin-enames.json`:

```json
{
"admins": ["@admin1.w3id", "@admin2.w3id"]
}
```

3. Start the app and open `/login` to authenticate with eID Wallet.

### eVault Detection

The system automatically detects eVault pods by filtering for pods with names containing:
Expand Down
8 changes: 8 additions & 0 deletions infrastructure/control-panel/config/admin-enames.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
{
"admins": [
"@7218b67d-da21-54d6-9a85-7c4db1d09768",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498",
"@35a31f0d-dd76-5780-b383-29f219fcae99",
"@82f7a77a-f03a-52aa-88fc-1b1e488ad498"
]
}
4 changes: 4 additions & 0 deletions infrastructure/control-panel/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,7 @@
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-storybook": "^9.0.17",
Expand All@@ -50,8 +51,11 @@
"flowbite": "^3.1.2",
"flowbite-svelte": "^1.10.7",
"flowbite-svelte-icons": "^2.2.1",
"jose": "^6.2.0",
"lowdb": "^7.0.1",
"lucide-svelte": "^0.561.0",
"qrcode": "^1.5.4",
"signature-validator": "workspace:*",
"tailwind-merge": "^3.0.2"
}
}
12 changes: 10 additions & 2 deletions infrastructure/control-panel/src/app.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,8 +3,16 @@
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
interface Locals {
user: {
ename: string;
} | null;
}
interface PageData {
user: {
ename: string;
} | null;
}
// interface PageState {}
// interface Platform {}
}
Expand Down
67 changes: 67 additions & 0 deletions infrastructure/control-panel/src/hooks.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
import { AUTH_COOKIE_NAME, verifyAuthToken } from '$lib/server/auth/token';
import { json, redirect, type Handle } from '@sveltejs/kit';

const PUBLIC_PATHS = new Set(['/login']);

function isPublicPath(pathname: string): boolean {
if (PUBLIC_PATHS.has(pathname)) return true;
if (pathname.startsWith('/api/auth')) return true;
if (pathname.startsWith('/_app')) return true;
if (pathname === '/favicon.ico') return true;
return false;
}

function withCorsHeaders(response: Response): Response {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
response.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-ENAME, Accept'
);
response.headers.set('Access-Control-Max-Age', '86400');
response.headers.set('Access-Control-Allow-Private-Network', 'true');
return response;
}

export const handle: Handle = async ({ event, resolve }) => {
const token = event.cookies.get(AUTH_COOKIE_NAME);
const auth = token ? await verifyAuthToken(token) : null;

event.locals.user = auth ? { ename: auth.ename } : null;

const pathname = event.url.pathname;
const isApi = pathname.startsWith('/api/');

if (event.request.method === 'OPTIONS') {
if (event.request.headers.get('access-control-request-private-network') === 'true') {
console.info('[auth] Private network preflight detected', { pathname });
}
return withCorsHeaders(new Response(null, { status: 204 }));
}

if (pathname.startsWith('/api/auth')) {
console.info('[auth] Incoming request', {
method: event.request.method,
pathname,
origin: event.url.origin,
contentType: event.request.headers.get('content-type') || null,
userAgent: event.request.headers.get('user-agent') || null
});
}

const isPublic = isPublicPath(pathname);

if (!event.locals.user && !isPublic) {
if (isApi) {
return withCorsHeaders(json({ error: 'Unauthorized' }, { status: 401 }));
}
throw redirect(302, '/login');
}

if (event.locals.user && pathname === '/login') {
throw redirect(302, '/');
}

const response = await resolve(event);
return withCorsHeaders(response);
};
61 changes: 61 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/allowlist.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
import { env } from '$env/dynamic/private';
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';

const DEFAULT_ALLOWLIST_PATH = 'config/admin-enames.json';

type AllowlistData = {
admins?: string[];
};

let cachedPath: string | null = null;
let cachedMtimeMs = -1;
let cachedAdmins = new Set<string>();

export function normalizeEName(value: string): string {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}

function getAllowlistPath(): string {
const configuredPath = env.CONTROL_PANEL_ADMIN_ENAMES_FILE?.trim();
return resolve(process.cwd(), configuredPath || DEFAULT_ALLOWLIST_PATH);
}

export async function getAdminAllowlist(): Promise<Set<string>> {
const allowlistPath = getAllowlistPath();

try {
const fileStat = await stat(allowlistPath);
const shouldRefresh = allowlistPath !== cachedPath || fileStat.mtimeMs !== cachedMtimeMs;

if (!shouldRefresh) {
return cachedAdmins;
}

const raw = await readFile(allowlistPath, 'utf8');
const parsed = JSON.parse(raw) as AllowlistData;
const admins = Array.isArray(parsed.admins) ? parsed.admins : [];
const normalized = new Set(admins.map(normalizeEName).filter(Boolean));

cachedPath = allowlistPath;
cachedMtimeMs = fileStat.mtimeMs;
cachedAdmins = normalized;

return cachedAdmins;
} catch (error) {
console.error(`[auth] Failed loading admin allowlist from ${allowlistPath}:`, error);
cachedPath = allowlistPath;
cachedMtimeMs = -1;
cachedAdmins = new Set();
return cachedAdmins;
}
}

export async function isAdminEName(ename: string): Promise<boolean> {
const normalized = normalizeEName(ename);
if (!normalized) return false;
const allowlist = await getAdminAllowlist();
return allowlist.has(normalized);
}
91 changes: 91 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/sessions.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
import { randomUUID } from 'node:crypto';

const SESSION_TTL_MS = 5 * 60 * 1000;

export type SessionResult =
| { status: 'success'; ename: string }
| { status: 'error'; message: string };

type SessionRecord = {
id: string;
createdAt: number;
consumed: boolean;
result?: SessionResult;
subscribers: Set<(result: SessionResult) => void>;
};

const sessions = new Map<string, SessionRecord>();

function isExpired(record: SessionRecord, now = Date.now()): boolean {
return now - record.createdAt > SESSION_TTL_MS;
}

function cleanupExpiredSessions(): void {
const now = Date.now();
for (const [id, record] of sessions.entries()) {
if (isExpired(record, now)) {
sessions.delete(id);
}
}
}

export function createAuthSession(): string {
cleanupExpiredSessions();
const id = randomUUID();
sessions.set(id, {
id,
createdAt: Date.now(),
consumed: false,
subscribers: new Set()
});
return id;
}

export function consumeAuthSession(id: string): boolean {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || session.consumed || isExpired(session)) {
return false;
}

session.consumed = true;
return true;
}

export function getAuthSessionResult(id: string): SessionResult | undefined {
cleanupExpiredSessions();
return sessions.get(id)?.result;
}

export function publishAuthSessionResult(id: string, result: SessionResult): void {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session) return;

session.result = result;
for (const subscriber of session.subscribers) {
try {
subscriber(result);
} catch (error) {
console.error('[auth] Failed notifying session subscriber:', error);
}
}
session.subscribers.clear();
}

export function subscribeToAuthSession(
id: string,
listener: (result: SessionResult) => void
): (() => void) | null {
cleanupExpiredSessions();
const session = sessions.get(id);
if (!session || isExpired(session)) {
return null;
}

session.subscribers.add(listener);

return () => {
session.subscribers.delete(listener);
};
}
39 changes: 39 additions & 0 deletions infrastructure/control-panel/src/lib/server/auth/token.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import { jwtVerify, SignJWT } from 'jose';

export const AUTH_COOKIE_NAME = 'control_panel_auth';
const AUTH_TOKEN_EXPIRY = '7d';

type AuthTokenPayload = {
ename: string;
};

function getJwtSecret(): Uint8Array {
const secret = env.CONTROL_PANEL_JWT_SECRET || 'control-panel-dev-secret-change-me';
return new TextEncoder().encode(secret);
}

export async function signAuthToken(payload: AuthTokenPayload): Promise<string> {
const secret = getJwtSecret();
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime(AUTH_TOKEN_EXPIRY)
.sign(secret);
}

export async function verifyAuthToken(token: string): Promise<AuthTokenPayload | null> {
try {
const secret = getJwtSecret();
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256']
});

const ename = typeof payload.ename === 'string' ? payload.ename : null;
if (!ename) return null;

return { ename };
} catch {
return null;
}
}
7 changes: 7 additions & 0 deletions infrastructure/control-panel/src/routes/+layout.server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals }) => {
return {
user: locals.user
};
};
Loading