KI-AGENT: Zentralen Push-Server Stack ergänzen
This commit is contained in:
16
push-server/apps/admin/Dockerfile
Normal file
16
push-server/apps/admin/Dockerfile
Normal file
@@ -0,0 +1,16 @@
|
||||
FROM node:22-alpine AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
COPY apps/admin/package.json apps/admin/package.json
|
||||
RUN npm install
|
||||
|
||||
FROM deps AS build
|
||||
COPY . .
|
||||
RUN npm run build --workspace @fedeo/push-admin
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY --from=build /app/apps/admin/.output ./.output
|
||||
EXPOSE 3000
|
||||
CMD ["node", ".output/server/index.mjs"]
|
||||
5
push-server/apps/admin/app.vue
Normal file
5
push-server/apps/admin/app.vue
Normal file
@@ -0,0 +1,5 @@
|
||||
<template>
|
||||
<UApp>
|
||||
<NuxtPage />
|
||||
</UApp>
|
||||
</template>
|
||||
12
push-server/apps/admin/assets/css/main.css
Normal file
12
push-server/apps/admin/assets/css/main.css
Normal file
@@ -0,0 +1,12 @@
|
||||
html,
|
||||
body,
|
||||
#__nuxt {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: #f8fafc;
|
||||
color: #111827;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
31
push-server/apps/admin/components/AdminShell.vue
Normal file
31
push-server/apps/admin/components/AdminShell.vue
Normal file
@@ -0,0 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
const route = useRoute();
|
||||
const items = [
|
||||
{ label: "Übersicht", icon: "i-lucide-layout-dashboard", to: "/" },
|
||||
{ label: "Instanzen", icon: "i-lucide-server-cog", to: "/instances" },
|
||||
{ label: "Zustellungen", icon: "i-lucide-send", to: "/jobs" },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen">
|
||||
<header class="border-b border-gray-200 bg-white">
|
||||
<div class="mx-auto flex max-w-7xl items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
|
||||
<div>
|
||||
<p class="text-xs font-semibold uppercase tracking-wide text-green-700">FEDEO Push</p>
|
||||
<h1 class="text-xl font-bold text-gray-950">Zentraler Push-Server</h1>
|
||||
</div>
|
||||
<UBadge color="success" variant="soft">Admin</UBadge>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="mx-auto grid max-w-7xl gap-6 px-4 py-6 sm:px-6 lg:grid-cols-[220px_1fr] lg:px-8">
|
||||
<aside class="lg:sticky lg:top-6 lg:self-start">
|
||||
<UNavigationMenu orientation="vertical" :items="items" />
|
||||
</aside>
|
||||
<main>
|
||||
<slot />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
25
push-server/apps/admin/components/TokenGate.vue
Normal file
25
push-server/apps/admin/components/TokenGate.vue
Normal file
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
const pushApi = usePushApi();
|
||||
const draft = ref("");
|
||||
|
||||
onMounted(() => {
|
||||
pushApi.hydrateToken();
|
||||
draft.value = pushApi.token.value;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UCard v-if="!pushApi.token.value" class="mx-auto mt-16 max-w-lg">
|
||||
<template #header>
|
||||
<div>
|
||||
<h2 class="text-lg font-bold">Admin-Zugang</h2>
|
||||
<p class="text-sm text-gray-500">Gib den Admin-Token aus der Push-Server-Umgebung ein.</p>
|
||||
</div>
|
||||
</template>
|
||||
<form class="space-y-4" @submit.prevent="pushApi.setToken(draft)">
|
||||
<UInput v-model="draft" type="password" placeholder="ADMIN_TOKEN" icon="i-lucide-key-round" autofocus />
|
||||
<UButton type="submit" block icon="i-lucide-log-in">Verbinden</UButton>
|
||||
</form>
|
||||
</UCard>
|
||||
<slot v-else />
|
||||
</template>
|
||||
40
push-server/apps/admin/composables/usePushApi.ts
Normal file
40
push-server/apps/admin/composables/usePushApi.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
type FetchOptions = {
|
||||
method?: "GET" | "POST" | "PATCH" | "DELETE";
|
||||
body?: unknown;
|
||||
};
|
||||
|
||||
export function usePushApi() {
|
||||
const config = useRuntimeConfig();
|
||||
const token = useState<string>("push-admin-token", () => "");
|
||||
|
||||
const setToken = (nextToken: string) => {
|
||||
token.value = nextToken.trim();
|
||||
if (process.client) {
|
||||
localStorage.setItem("fedeo-push-admin-token", token.value);
|
||||
}
|
||||
};
|
||||
|
||||
const hydrateToken = () => {
|
||||
if (process.client && !token.value) {
|
||||
token.value = localStorage.getItem("fedeo-push-admin-token") || "";
|
||||
}
|
||||
};
|
||||
|
||||
const request = async <T>(path: string, options: FetchOptions = {}) => {
|
||||
hydrateToken();
|
||||
return await $fetch<T>(`${config.public.apiBase}${path}`, {
|
||||
method: options.method || "GET",
|
||||
body: options.body as Record<string, any> | BodyInit | null | undefined,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token.value}`,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
token,
|
||||
setToken,
|
||||
hydrateToken,
|
||||
request,
|
||||
};
|
||||
}
|
||||
11
push-server/apps/admin/nuxt.config.ts
Normal file
11
push-server/apps/admin/nuxt.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export default defineNuxtConfig({
|
||||
modules: ["@nuxt/ui"],
|
||||
css: ["~/assets/css/main.css"],
|
||||
compatibilityDate: "2026-05-22",
|
||||
devtools: { enabled: true },
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
apiBase: process.env.NUXT_PUBLIC_API_BASE || "http://localhost:4020",
|
||||
},
|
||||
},
|
||||
});
|
||||
24
push-server/apps/admin/package.json
Normal file
24
push-server/apps/admin/package.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@fedeo/push-admin",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nuxt dev --host 0.0.0.0",
|
||||
"build": "nuxt build",
|
||||
"preview": "nuxt preview",
|
||||
"typecheck": "nuxt typecheck"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nuxt/ui": "^3.3.7",
|
||||
"nuxt": "^3.14.1592",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.2.5",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.3.0",
|
||||
"typescript": "^5.9.2",
|
||||
"vue-tsc": "^3.1.5"
|
||||
}
|
||||
}
|
||||
55
push-server/apps/admin/pages/index.vue
Normal file
55
push-server/apps/admin/pages/index.vue
Normal file
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
const pushApi = usePushApi();
|
||||
const toast = useToast();
|
||||
|
||||
const { data, pending, refresh, error } = await useAsyncData("summary", () => pushApi.request<{
|
||||
instances: number;
|
||||
devices: number;
|
||||
jobs: number;
|
||||
failedJobs: number;
|
||||
}>("/admin/summary"), { immediate: false });
|
||||
|
||||
onMounted(async () => {
|
||||
pushApi.hydrateToken();
|
||||
if (pushApi.token.value) await refresh();
|
||||
});
|
||||
|
||||
watch(error, (nextError) => {
|
||||
if (nextError) toast.add({ title: "Dashboard konnte nicht geladen werden", color: "error" });
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AdminShell>
|
||||
<TokenGate>
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-gray-950">Übersicht</h2>
|
||||
<p class="text-sm text-gray-500">Technischer Zustand des zentralen Push-Gateways.</p>
|
||||
</div>
|
||||
<UButton icon="i-lucide-refresh-cw" variant="soft" :loading="pending" @click="refresh()">Aktualisieren</UButton>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-4">
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Instanzen</p>
|
||||
<p class="mt-2 text-3xl font-bold">{{ data?.instances ?? 0 }}</p>
|
||||
</UCard>
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Geräte</p>
|
||||
<p class="mt-2 text-3xl font-bold">{{ data?.devices ?? 0 }}</p>
|
||||
</UCard>
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Jobs</p>
|
||||
<p class="mt-2 text-3xl font-bold">{{ data?.jobs ?? 0 }}</p>
|
||||
</UCard>
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Fehler</p>
|
||||
<p class="mt-2 text-3xl font-bold text-red-600">{{ data?.failedJobs ?? 0 }}</p>
|
||||
</UCard>
|
||||
</div>
|
||||
</div>
|
||||
</TokenGate>
|
||||
</AdminShell>
|
||||
</template>
|
||||
162
push-server/apps/admin/pages/instances.vue
Normal file
162
push-server/apps/admin/pages/instances.vue
Normal file
@@ -0,0 +1,162 @@
|
||||
<script setup lang="ts">
|
||||
type Instance = {
|
||||
id: string;
|
||||
instanceId: string;
|
||||
name: string;
|
||||
baseUrl: string;
|
||||
status: "active" | "blocked" | "disabled";
|
||||
mode: "minimal" | "rich";
|
||||
capabilities: string[];
|
||||
currentSecretPreview: string;
|
||||
nextSecretPreview?: string | null;
|
||||
lastHeartbeatAt?: string | null;
|
||||
};
|
||||
|
||||
const pushApi = usePushApi();
|
||||
const toast = useToast();
|
||||
const createOpen = ref(false);
|
||||
const createdSecret = ref("");
|
||||
const form = reactive({
|
||||
name: "",
|
||||
baseUrl: "",
|
||||
mode: "minimal",
|
||||
capabilities: "ios_push,minimal_payload",
|
||||
});
|
||||
|
||||
const { data: instances, pending, refresh } = await useAsyncData("instances", () => pushApi.request<Instance[]>("/admin/instances"), {
|
||||
default: () => [],
|
||||
immediate: false,
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
pushApi.hydrateToken();
|
||||
if (pushApi.token.value) await refresh();
|
||||
});
|
||||
|
||||
async function createInstance() {
|
||||
const created = await pushApi.request<Instance & { clientSecret: string }>("/admin/instances", {
|
||||
method: "POST",
|
||||
body: {
|
||||
name: form.name,
|
||||
baseUrl: form.baseUrl,
|
||||
mode: form.mode,
|
||||
capabilities: form.capabilities.split(",").map((item) => item.trim()).filter(Boolean),
|
||||
},
|
||||
});
|
||||
createdSecret.value = created.clientSecret;
|
||||
createOpen.value = false;
|
||||
form.name = "";
|
||||
form.baseUrl = "";
|
||||
await refresh();
|
||||
toast.add({ title: "Instanz angelegt", color: "success" });
|
||||
}
|
||||
|
||||
async function patchInstance(instance: Instance, status: Instance["status"]) {
|
||||
await pushApi.request(`/admin/instances/${instance.id}`, {
|
||||
method: "PATCH",
|
||||
body: { status },
|
||||
});
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function rotateSecret(instance: Instance) {
|
||||
const result = await pushApi.request<Instance & { nextClientSecret: string }>(`/admin/instances/${instance.id}/rotate-secret`, {
|
||||
method: "POST",
|
||||
body: {},
|
||||
});
|
||||
createdSecret.value = result.nextClientSecret;
|
||||
await refresh();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AdminShell>
|
||||
<TokenGate>
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-gray-950">Instanzen</h2>
|
||||
<p class="text-sm text-gray-500">Selfhosted FEDEO-Instanzen und ihre Gateway-Schlüssel.</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<UButton icon="i-lucide-refresh-cw" variant="soft" :loading="pending" @click="refresh()">Aktualisieren</UButton>
|
||||
<UButton icon="i-lucide-plus" @click="createOpen = true">Instanz</UButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UAlert
|
||||
v-if="createdSecret"
|
||||
color="warning"
|
||||
icon="i-lucide-key-round"
|
||||
title="Schlüssel nur jetzt kopieren"
|
||||
:description="createdSecret"
|
||||
/>
|
||||
|
||||
<div class="grid gap-4">
|
||||
<UCard v-for="instance in instances" :key="instance.id">
|
||||
<div class="flex flex-wrap items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="truncate text-lg font-bold">{{ instance.name }}</h3>
|
||||
<UBadge :color="instance.status === 'active' ? 'success' : instance.status === 'blocked' ? 'error' : 'neutral'" variant="soft">
|
||||
{{ instance.status }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-sm text-gray-500">{{ instance.instanceId }}</p>
|
||||
<p class="mt-1 text-sm text-gray-700">{{ instance.baseUrl }}</p>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<UBadge v-for="capability in instance.capabilities" :key="capability" color="success" variant="subtle">
|
||||
{{ capability }}
|
||||
</UBadge>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<UButton icon="i-lucide-key-round" variant="soft" @click="rotateSecret(instance)">Rotieren</UButton>
|
||||
<UButton v-if="instance.status !== 'active'" color="success" variant="soft" @click="patchInstance(instance, 'active')">Aktivieren</UButton>
|
||||
<UButton v-else color="error" variant="soft" @click="patchInstance(instance, 'blocked')">Sperren</UButton>
|
||||
<UButton icon="i-lucide-arrow-right" variant="ghost" :to="`/instances/${instance.id}`" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 grid gap-3 text-sm md:grid-cols-3">
|
||||
<div>
|
||||
<p class="text-gray-500">Aktueller Schlüssel</p>
|
||||
<p class="font-mono">{{ instance.currentSecretPreview }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-gray-500">Nächster Schlüssel</p>
|
||||
<p class="font-mono">{{ instance.nextSecretPreview || "nicht gesetzt" }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-gray-500">Heartbeat</p>
|
||||
<p>{{ instance.lastHeartbeatAt ? new Date(instance.lastHeartbeatAt).toLocaleString() : "noch keiner" }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</UCard>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UModal v-model:open="createOpen" title="Instanz anlegen">
|
||||
<template #body>
|
||||
<form class="space-y-4" @submit.prevent="createInstance">
|
||||
<UFormField label="Name">
|
||||
<UInput v-model="form.name" placeholder="Kunde / Selfhost-Instanz" />
|
||||
</UFormField>
|
||||
<UFormField label="Basis-URL">
|
||||
<UInput v-model="form.baseUrl" placeholder="https://app.example.com" />
|
||||
</UFormField>
|
||||
<UFormField label="Payload-Modus">
|
||||
<USelect v-model="form.mode" :items="['minimal', 'rich']" />
|
||||
</UFormField>
|
||||
<UFormField label="Fähigkeiten">
|
||||
<UInput v-model="form.capabilities" />
|
||||
</UFormField>
|
||||
<div class="flex justify-end gap-2">
|
||||
<UButton variant="soft" @click="createOpen = false">Abbrechen</UButton>
|
||||
<UButton type="submit">Anlegen</UButton>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
</UModal>
|
||||
</TokenGate>
|
||||
</AdminShell>
|
||||
</template>
|
||||
108
push-server/apps/admin/pages/instances/[id].vue
Normal file
108
push-server/apps/admin/pages/instances/[id].vue
Normal file
@@ -0,0 +1,108 @@
|
||||
<script setup lang="ts">
|
||||
const route = useRoute();
|
||||
const pushApi = usePushApi();
|
||||
const id = route.params.id as string;
|
||||
|
||||
const { data: instance, refresh: refreshInstance } = await useAsyncData(`instance-${id}`, () => pushApi.request<Record<string, any>>(`/admin/instances/${id}`), { immediate: false });
|
||||
const { data: devices, refresh: refreshDevices } = await useAsyncData(`devices-${id}`, () => pushApi.request<Record<string, any>[]>(`/admin/instances/${id}/devices`), { default: () => [], immediate: false });
|
||||
const { data: jobs, refresh: refreshJobs } = await useAsyncData(`jobs-${id}`, () => pushApi.request<Record<string, any>[]>(`/admin/instances/${id}/jobs`), { default: () => [], immediate: false });
|
||||
|
||||
onMounted(async () => {
|
||||
pushApi.hydrateToken();
|
||||
if (pushApi.token.value) {
|
||||
await refreshAll();
|
||||
}
|
||||
});
|
||||
|
||||
async function refreshAll() {
|
||||
await Promise.all([refreshInstance(), refreshDevices(), refreshJobs()]);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AdminShell>
|
||||
<TokenGate>
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<UButton to="/instances" icon="i-lucide-arrow-left" variant="ghost" size="sm">Zurück</UButton>
|
||||
<h2 class="mt-2 text-2xl font-bold">{{ instance?.name || "Instanz" }}</h2>
|
||||
<p class="text-sm text-gray-500">{{ instance?.instanceId }}</p>
|
||||
</div>
|
||||
<UButton icon="i-lucide-refresh-cw" variant="soft" @click="refreshAll">Aktualisieren</UButton>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-3">
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Geräte</p>
|
||||
<p class="mt-2 text-3xl font-bold">{{ instance?.deviceCount ?? 0 }}</p>
|
||||
</UCard>
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Zustelljobs</p>
|
||||
<p class="mt-2 text-3xl font-bold">{{ instance?.jobCount ?? 0 }}</p>
|
||||
</UCard>
|
||||
<UCard>
|
||||
<p class="text-sm text-gray-500">Status</p>
|
||||
<p class="mt-2 text-xl font-bold">{{ instance?.status }}</p>
|
||||
</UCard>
|
||||
</div>
|
||||
|
||||
<UCard>
|
||||
<template #header>
|
||||
<h3 class="font-bold">Geräte</h3>
|
||||
</template>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-left text-sm">
|
||||
<thead class="text-gray-500">
|
||||
<tr>
|
||||
<th class="py-2">Central ID</th>
|
||||
<th>Plattform</th>
|
||||
<th>Status</th>
|
||||
<th>Zuletzt gesehen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="device in devices" :key="device.id" class="border-t border-gray-100">
|
||||
<td class="py-2 font-mono">{{ device.centralDeviceId }}</td>
|
||||
<td>{{ device.platform }}</td>
|
||||
<td>{{ device.status }}</td>
|
||||
<td>{{ new Date(device.lastSeenAt).toLocaleString() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</UCard>
|
||||
|
||||
<UCard>
|
||||
<template #header>
|
||||
<h3 class="font-bold">Letzte Zustelljobs</h3>
|
||||
</template>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-left text-sm">
|
||||
<thead class="text-gray-500">
|
||||
<tr>
|
||||
<th class="py-2">Job</th>
|
||||
<th>Status</th>
|
||||
<th>Angenommen</th>
|
||||
<th>Gesendet</th>
|
||||
<th>Fehler</th>
|
||||
<th>Erstellt</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="job in jobs" :key="job.id" class="border-t border-gray-100">
|
||||
<td class="py-2 font-mono">{{ job.deliveryJobId }}</td>
|
||||
<td>{{ job.status }}</td>
|
||||
<td>{{ job.acceptedCount }}</td>
|
||||
<td>{{ job.sentCount }}</td>
|
||||
<td>{{ job.failedCount }}</td>
|
||||
<td>{{ new Date(job.createdAt).toLocaleString() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</UCard>
|
||||
</div>
|
||||
</TokenGate>
|
||||
</AdminShell>
|
||||
</template>
|
||||
56
push-server/apps/admin/pages/jobs.vue
Normal file
56
push-server/apps/admin/pages/jobs.vue
Normal file
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
const pushApi = usePushApi();
|
||||
const { data: jobs, pending, refresh } = await useAsyncData("jobs", () => pushApi.request<Record<string, any>[]>("/admin/jobs"), {
|
||||
default: () => [],
|
||||
immediate: false,
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
pushApi.hydrateToken();
|
||||
if (pushApi.token.value) await refresh();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AdminShell>
|
||||
<TokenGate>
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-gray-950">Zustellungen</h2>
|
||||
<p class="text-sm text-gray-500">Letzte technische Push-Aufträge aller Instanzen.</p>
|
||||
</div>
|
||||
<UButton icon="i-lucide-refresh-cw" variant="soft" :loading="pending" @click="refresh()">Aktualisieren</UButton>
|
||||
</div>
|
||||
<UCard>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-left text-sm">
|
||||
<thead class="text-gray-500">
|
||||
<tr>
|
||||
<th class="py-2">Job</th>
|
||||
<th>Status</th>
|
||||
<th>Angenommen</th>
|
||||
<th>Gesendet</th>
|
||||
<th>Fehler</th>
|
||||
<th>Letzter Fehler</th>
|
||||
<th>Erstellt</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="job in jobs" :key="job.id" class="border-t border-gray-100">
|
||||
<td class="py-2 font-mono">{{ job.deliveryJobId }}</td>
|
||||
<td>{{ job.status }}</td>
|
||||
<td>{{ job.acceptedCount }}</td>
|
||||
<td>{{ job.sentCount }}</td>
|
||||
<td>{{ job.failedCount }}</td>
|
||||
<td>{{ job.lastErrorCode || "-" }}</td>
|
||||
<td>{{ new Date(job.createdAt).toLocaleString() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</UCard>
|
||||
</div>
|
||||
</TokenGate>
|
||||
</AdminShell>
|
||||
</template>
|
||||
3
push-server/apps/admin/tsconfig.json
Normal file
3
push-server/apps/admin/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./.nuxt/tsconfig.json"
|
||||
}
|
||||
22
push-server/apps/api/Dockerfile
Normal file
22
push-server/apps/api/Dockerfile
Normal file
@@ -0,0 +1,22 @@
|
||||
FROM node:22-alpine AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY packages/db/package.json packages/db/package.json
|
||||
RUN npm install
|
||||
|
||||
FROM deps AS build
|
||||
COPY . .
|
||||
RUN npm run build --workspace @fedeo/push-db && npm run build --workspace @fedeo/push-api
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY --from=build /app/apps/api/dist ./apps/api/dist
|
||||
COPY --from=build /app/packages/db/dist ./packages/db/dist
|
||||
COPY --from=build /app/package.json ./package.json
|
||||
COPY --from=build /app/apps/api/package.json ./apps/api/package.json
|
||||
COPY --from=build /app/packages/db/package.json ./packages/db/package.json
|
||||
EXPOSE 4020
|
||||
CMD ["node", "apps/api/dist/index.js"]
|
||||
29
push-server/apps/api/package.json
Normal file
29
push-server/apps/api/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@fedeo/push-api",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.1.0",
|
||||
"@fedeo/push-db": "file:../../packages/db",
|
||||
"dotenv": "^17.2.3",
|
||||
"drizzle-orm": "^0.45.0",
|
||||
"fastify": "^5.5.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"pg": "^8.16.3",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node": "^24.3.0",
|
||||
"@types/pg": "^8.15.5",
|
||||
"tsx": "^4.20.5",
|
||||
"typescript": "^5.9.2"
|
||||
}
|
||||
}
|
||||
24
push-server/apps/api/src/config/env.ts
Normal file
24
push-server/apps/api/src/config/env.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import "dotenv/config";
|
||||
import { z } from "zod";
|
||||
|
||||
const envSchema = z.object({
|
||||
NODE_ENV: z.string().default("development"),
|
||||
DATABASE_URL: z.string().url(),
|
||||
API_HOST: z.string().default("0.0.0.0"),
|
||||
API_PORT: z.coerce.number().int().positive().default(4020),
|
||||
ADMIN_TOKEN: z.string().min(12),
|
||||
PUSH_SECRET_ENCRYPTION_KEY: z.string().min(24),
|
||||
PUBLIC_BASE_URL: z.string().url().default("http://localhost:4020"),
|
||||
WEB_PUSH_PUBLIC_KEY: z.string().optional().default(""),
|
||||
WEB_PUSH_PRIVATE_KEY: z.string().optional().default(""),
|
||||
IOS_BUNDLE_ID: z.string().default("software.federspiel.fedeo"),
|
||||
APNS_TEAM_ID: z.string().optional().default(""),
|
||||
APNS_KEY_ID: z.string().optional().default(""),
|
||||
APNS_PRIVATE_KEY: z.string().optional().default(""),
|
||||
APNS_PRODUCTION: z.coerce.boolean().default(false),
|
||||
ANDROID_SENDER_ID: z.string().optional().default(""),
|
||||
FCM_PROJECT_ID: z.string().optional().default(""),
|
||||
FCM_SERVICE_ACCOUNT_JSON: z.string().optional().default(""),
|
||||
});
|
||||
|
||||
export const env = envSchema.parse(process.env);
|
||||
10
push-server/apps/api/src/db/client.ts
Normal file
10
push-server/apps/api/src/db/client.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { drizzle } from "drizzle-orm/node-postgres";
|
||||
import pg from "pg";
|
||||
import * as schema from "@fedeo/push-db";
|
||||
import { env } from "../config/env.js";
|
||||
|
||||
export const pool = new pg.Pool({
|
||||
connectionString: env.DATABASE_URL,
|
||||
});
|
||||
|
||||
export const db = drizzle(pool, { schema });
|
||||
51
push-server/apps/api/src/index.ts
Normal file
51
push-server/apps/api/src/index.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import "./types.js";
|
||||
import Fastify from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import { ZodError } from "zod";
|
||||
import { env } from "./config/env.js";
|
||||
import { pool } from "./db/client.js";
|
||||
import { adminRoutes } from "./routes/admin.js";
|
||||
import { instanceRoutes } from "./routes/instance.js";
|
||||
import { publicRoutes } from "./routes/public.js";
|
||||
|
||||
const app = Fastify({
|
||||
logger: true,
|
||||
bodyLimit: 128 * 1024,
|
||||
});
|
||||
|
||||
app.addContentTypeParser("application/json", { parseAs: "string" }, (request, body, done) => {
|
||||
const rawBody = typeof body === "string" ? body : body.toString("utf8");
|
||||
request.rawBody = rawBody;
|
||||
try {
|
||||
done(null, rawBody ? JSON.parse(rawBody) : {});
|
||||
} catch (error) {
|
||||
done(error as Error);
|
||||
}
|
||||
});
|
||||
|
||||
app.setErrorHandler((error, _request, reply) => {
|
||||
if (error instanceof ZodError) {
|
||||
reply.code(400).send({ error: "validation_error", issues: error.issues });
|
||||
return;
|
||||
}
|
||||
app.log.error(error);
|
||||
reply.code(500).send({ error: "internal_error", message: "Interner Fehler im Push-Server." });
|
||||
});
|
||||
|
||||
await app.register(cors, {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
});
|
||||
await app.register(publicRoutes);
|
||||
await app.register(adminRoutes);
|
||||
await app.register(instanceRoutes);
|
||||
|
||||
const close = async () => {
|
||||
await app.close();
|
||||
await pool.end();
|
||||
};
|
||||
|
||||
process.on("SIGINT", () => void close().then(() => process.exit(0)));
|
||||
process.on("SIGTERM", () => void close().then(() => process.exit(0)));
|
||||
|
||||
await app.listen({ host: env.API_HOST, port: env.API_PORT });
|
||||
52
push-server/apps/api/src/lib/auth.ts
Normal file
52
push-server/apps/api/src/lib/auth.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { pushInstances } from "@fedeo/push-db";
|
||||
import { env } from "../config/env.js";
|
||||
import { db } from "../db/client.js";
|
||||
import { decryptSecret, hmacSha256, secureEqual, sha256 } from "./crypto.js";
|
||||
|
||||
export async function requireAdmin(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "") || String(request.headers["x-admin-token"] || "");
|
||||
if (!token || !secureEqual(token, env.ADMIN_TOKEN)) {
|
||||
await reply.code(401).send({ error: "admin_unauthorized", message: "Admin-Token fehlt oder ist ungültig." });
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireInstance(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const instanceId = String(request.headers["x-fedeo-instance-id"] || "");
|
||||
const timestamp = String(request.headers["x-fedeo-timestamp"] || "");
|
||||
const signature = String(request.headers["x-fedeo-signature"] || "");
|
||||
|
||||
if (!instanceId || !timestamp || !signature) {
|
||||
await reply.code(401).send({ error: "instance_auth_missing", message: "Instanzsignatur fehlt." });
|
||||
return;
|
||||
}
|
||||
|
||||
const timestampMs = Date.parse(timestamp);
|
||||
if (!Number.isFinite(timestampMs) || Math.abs(Date.now() - timestampMs) > 5 * 60 * 1000) {
|
||||
await reply.code(401).send({ error: "instance_timestamp_invalid", message: "Instanzsignatur ist abgelaufen oder ungültig." });
|
||||
return;
|
||||
}
|
||||
|
||||
const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.instanceId, instanceId)).limit(1);
|
||||
if (!instance || instance.status !== "active") {
|
||||
await reply.code(403).send({ error: "instance_not_allowed", message: "Instanz ist nicht aktiv." });
|
||||
return;
|
||||
}
|
||||
|
||||
const path = request.url.split("?")[0] || request.url;
|
||||
const bodyHash = sha256(request.rawBody || "");
|
||||
const canonical = [request.method.toUpperCase(), path, timestamp, bodyHash, instanceId].join("\n");
|
||||
const secrets = [instance.currentSecretEncrypted, instance.nextSecretEncrypted].filter(Boolean) as string[];
|
||||
const accepted = secrets.some((encrypted) => {
|
||||
const expected = hmacSha256(decryptSecret(encrypted), canonical);
|
||||
return secureEqual(signature, expected);
|
||||
});
|
||||
|
||||
if (!accepted) {
|
||||
await reply.code(401).send({ error: "instance_signature_invalid", message: "Instanzsignatur ist ungültig." });
|
||||
return;
|
||||
}
|
||||
|
||||
request.pushInstance = instance;
|
||||
}
|
||||
39
push-server/apps/api/src/lib/crypto.ts
Normal file
39
push-server/apps/api/src/lib/crypto.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { env } from "../config/env.js";
|
||||
|
||||
function key(): Buffer {
|
||||
return createHash("sha256").update(env.PUSH_SECRET_ENCRYPTION_KEY).digest();
|
||||
}
|
||||
|
||||
export function encryptSecret(value: string): string {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", key(), iv);
|
||||
const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return [iv.toString("base64url"), tag.toString("base64url"), encrypted.toString("base64url")].join(".");
|
||||
}
|
||||
|
||||
export function decryptSecret(value: string): string {
|
||||
const [ivRaw, tagRaw, encryptedRaw] = value.split(".");
|
||||
if (!ivRaw || !tagRaw || !encryptedRaw) throw new Error("Ungültiges Secret-Format");
|
||||
const decipher = createDecipheriv("aes-256-gcm", key(), Buffer.from(ivRaw, "base64url"));
|
||||
decipher.setAuthTag(Buffer.from(tagRaw, "base64url"));
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(encryptedRaw, "base64url")),
|
||||
decipher.final(),
|
||||
]).toString("utf8");
|
||||
}
|
||||
|
||||
export function sha256(input: string): string {
|
||||
return createHash("sha256").update(input).digest("hex");
|
||||
}
|
||||
|
||||
export function hmacSha256(secret: string, input: string): string {
|
||||
return createHmac("sha256", secret).update(input).digest("hex");
|
||||
}
|
||||
|
||||
export function secureEqual(a: string, b: string): boolean {
|
||||
const left = Buffer.from(a);
|
||||
const right = Buffer.from(b);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
13
push-server/apps/api/src/lib/ids.ts
Normal file
13
push-server/apps/api/src/lib/ids.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
export function createPublicId(prefix: string): string {
|
||||
return `${prefix}_${randomBytes(16).toString("base64url")}`;
|
||||
}
|
||||
|
||||
export function createClientSecret(): string {
|
||||
return `fps_${randomBytes(32).toString("base64url")}`;
|
||||
}
|
||||
|
||||
export function previewSecret(secret: string): string {
|
||||
return `${secret.slice(0, 7)}...${secret.slice(-6)}`;
|
||||
}
|
||||
174
push-server/apps/api/src/routes/admin.ts
Normal file
174
push-server/apps/api/src/routes/admin.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { and, desc, eq, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { auditLogs, deliveryJobs, pushDevices, pushInstances } from "@fedeo/push-db";
|
||||
import { db } from "../db/client.js";
|
||||
import { requireAdmin } from "../lib/auth.js";
|
||||
import { encryptSecret } from "../lib/crypto.js";
|
||||
import { createClientSecret, createPublicId, previewSecret } from "../lib/ids.js";
|
||||
|
||||
const createInstanceSchema = z.object({
|
||||
name: z.string().min(2),
|
||||
baseUrl: z.string().url(),
|
||||
capabilities: z.array(z.string()).default(["ios_push", "minimal_payload"]),
|
||||
rateLimitPerMinute: z.number().int().positive().default(120),
|
||||
dailyQuota: z.number().int().positive().default(10000),
|
||||
mode: z.enum(["minimal", "rich"]).default("minimal"),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
|
||||
const updateInstanceSchema = createInstanceSchema.partial().extend({
|
||||
status: z.enum(["active", "blocked", "disabled"]).optional(),
|
||||
});
|
||||
|
||||
export async function adminRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.addHook("preHandler", requireAdmin);
|
||||
|
||||
app.get("/admin/summary", async () => {
|
||||
const [instances] = await db.select({ count: sql<number>`count(*)::int` }).from(pushInstances);
|
||||
const [devices] = await db.select({ count: sql<number>`count(*)::int` }).from(pushDevices);
|
||||
const [jobs] = await db.select({ count: sql<number>`count(*)::int` }).from(deliveryJobs);
|
||||
const [failedJobs] = await db.select({ count: sql<number>`count(*)::int` }).from(deliveryJobs).where(eq(deliveryJobs.status, "failed"));
|
||||
return {
|
||||
instances: instances?.count || 0,
|
||||
devices: devices?.count || 0,
|
||||
jobs: jobs?.count || 0,
|
||||
failedJobs: failedJobs?.count || 0,
|
||||
};
|
||||
});
|
||||
|
||||
app.get("/admin/instances", async () => {
|
||||
const rows = await db.select().from(pushInstances).orderBy(desc(pushInstances.createdAt));
|
||||
return rows.map(publicInstance);
|
||||
});
|
||||
|
||||
app.post("/admin/instances", async (request, reply) => {
|
||||
const body = createInstanceSchema.parse(request.body);
|
||||
const secret = createClientSecret();
|
||||
const [created] = await db.insert(pushInstances).values({
|
||||
instanceId: createPublicId("inst"),
|
||||
name: body.name,
|
||||
baseUrl: body.baseUrl,
|
||||
capabilities: body.capabilities,
|
||||
rateLimitPerMinute: body.rateLimitPerMinute,
|
||||
dailyQuota: body.dailyQuota,
|
||||
mode: body.mode,
|
||||
notes: body.notes,
|
||||
currentSecretEncrypted: encryptSecret(secret),
|
||||
currentSecretPreview: previewSecret(secret),
|
||||
}).returning();
|
||||
|
||||
await audit("admin", "instance.created", created.id, { instanceId: created.instanceId });
|
||||
return reply.code(201).send({ ...publicInstance(created), clientSecret: secret });
|
||||
});
|
||||
|
||||
app.get("/admin/instances/:id", async (request, reply) => {
|
||||
const params = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.id, params.id)).limit(1);
|
||||
if (!instance) return reply.code(404).send({ error: "instance_not_found" });
|
||||
|
||||
const [deviceCount] = await db.select({ count: sql<number>`count(*)::int` }).from(pushDevices).where(eq(pushDevices.instanceId, instance.id));
|
||||
const [jobCount] = await db.select({ count: sql<number>`count(*)::int` }).from(deliveryJobs).where(eq(deliveryJobs.instanceId, instance.id));
|
||||
return { ...publicInstance(instance), deviceCount: deviceCount?.count || 0, jobCount: jobCount?.count || 0 };
|
||||
});
|
||||
|
||||
app.patch("/admin/instances/:id", async (request, reply) => {
|
||||
const params = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const body = updateInstanceSchema.parse(request.body);
|
||||
const [updated] = await db.update(pushInstances).set({ ...body, updatedAt: new Date() }).where(eq(pushInstances.id, params.id)).returning();
|
||||
if (!updated) return reply.code(404).send({ error: "instance_not_found" });
|
||||
await audit("admin", "instance.updated", updated.id, { fields: Object.keys(body) });
|
||||
return publicInstance(updated);
|
||||
});
|
||||
|
||||
app.post("/admin/instances/:id/rotate-secret", async (request, reply) => {
|
||||
const params = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
const body = z.object({ promote: z.boolean().optional().default(false) }).parse(request.body || {});
|
||||
const [instance] = await db.select().from(pushInstances).where(eq(pushInstances.id, params.id)).limit(1);
|
||||
if (!instance) return reply.code(404).send({ error: "instance_not_found" });
|
||||
|
||||
if (body.promote) {
|
||||
if (!instance.nextSecretEncrypted || !instance.nextSecretPreview) {
|
||||
return reply.code(400).send({ error: "next_secret_missing", message: "Es ist kein nächster Schlüssel hinterlegt." });
|
||||
}
|
||||
const [updated] = await db.update(pushInstances).set({
|
||||
currentSecretEncrypted: instance.nextSecretEncrypted,
|
||||
currentSecretPreview: instance.nextSecretPreview,
|
||||
nextSecretEncrypted: null,
|
||||
nextSecretPreview: null,
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(pushInstances.id, instance.id)).returning();
|
||||
await audit("admin", "instance.secret.promoted", instance.id);
|
||||
return publicInstance(updated);
|
||||
}
|
||||
|
||||
const nextSecret = createClientSecret();
|
||||
const [updated] = await db.update(pushInstances).set({
|
||||
nextSecretEncrypted: encryptSecret(nextSecret),
|
||||
nextSecretPreview: previewSecret(nextSecret),
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(pushInstances.id, instance.id)).returning();
|
||||
await audit("admin", "instance.secret.rotated", instance.id);
|
||||
return { ...publicInstance(updated), nextClientSecret: nextSecret };
|
||||
});
|
||||
|
||||
app.get("/admin/instances/:id/devices", async (request) => {
|
||||
const params = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
return await db.select().from(pushDevices).where(eq(pushDevices.instanceId, params.id)).orderBy(desc(pushDevices.createdAt));
|
||||
});
|
||||
|
||||
app.get("/admin/instances/:id/jobs", async (request) => {
|
||||
const params = z.object({ id: z.string().uuid() }).parse(request.params);
|
||||
return await db.select().from(deliveryJobs).where(eq(deliveryJobs.instanceId, params.id)).orderBy(desc(deliveryJobs.createdAt)).limit(100);
|
||||
});
|
||||
|
||||
app.get("/admin/jobs", async () => {
|
||||
return await db.select({
|
||||
id: deliveryJobs.id,
|
||||
deliveryJobId: deliveryJobs.deliveryJobId,
|
||||
instanceId: deliveryJobs.instanceId,
|
||||
status: deliveryJobs.status,
|
||||
acceptedCount: deliveryJobs.acceptedCount,
|
||||
sentCount: deliveryJobs.sentCount,
|
||||
failedCount: deliveryJobs.failedCount,
|
||||
lastErrorCode: deliveryJobs.lastErrorCode,
|
||||
createdAt: deliveryJobs.createdAt,
|
||||
}).from(deliveryJobs).orderBy(desc(deliveryJobs.createdAt)).limit(100);
|
||||
});
|
||||
|
||||
app.get("/admin/audit-logs", async (request) => {
|
||||
const query = z.object({ instanceId: z.string().uuid().optional() }).parse(request.query);
|
||||
return await db
|
||||
.select()
|
||||
.from(auditLogs)
|
||||
.where(query.instanceId ? eq(auditLogs.instanceId, query.instanceId) : undefined)
|
||||
.orderBy(desc(auditLogs.createdAt))
|
||||
.limit(100);
|
||||
});
|
||||
}
|
||||
|
||||
function publicInstance(instance: typeof pushInstances.$inferSelect) {
|
||||
return {
|
||||
id: instance.id,
|
||||
instanceId: instance.instanceId,
|
||||
name: instance.name,
|
||||
baseUrl: instance.baseUrl,
|
||||
status: instance.status,
|
||||
mode: instance.mode,
|
||||
capabilities: instance.capabilities,
|
||||
rateLimitPerMinute: instance.rateLimitPerMinute,
|
||||
dailyQuota: instance.dailyQuota,
|
||||
currentSecretPreview: instance.currentSecretPreview,
|
||||
nextSecretPreview: instance.nextSecretPreview,
|
||||
notes: instance.notes,
|
||||
lastHeartbeatAt: instance.lastHeartbeatAt,
|
||||
lastHeartbeatVersion: instance.lastHeartbeatVersion,
|
||||
lastHeartbeatIp: instance.lastHeartbeatIp,
|
||||
createdAt: instance.createdAt,
|
||||
updatedAt: instance.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
async function audit(actor: string, action: string, instanceId: string | null, meta: Record<string, unknown> = {}) {
|
||||
await db.insert(auditLogs).values({ actor, action, instanceId, meta });
|
||||
}
|
||||
181
push-server/apps/api/src/routes/instance.ts
Normal file
181
push-server/apps/api/src/routes/instance.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { deliveryJobs, pushDevices, pushInstances } from "@fedeo/push-db";
|
||||
import { db } from "../db/client.js";
|
||||
import { requireInstance } from "../lib/auth.js";
|
||||
import { encryptSecret } from "../lib/crypto.js";
|
||||
import { createPublicId } from "../lib/ids.js";
|
||||
import { deliverJob } from "../services/delivery.js";
|
||||
|
||||
const heartbeatSchema = z.object({
|
||||
fedeoVersion: z.string().optional(),
|
||||
baseUrl: z.string().url().optional(),
|
||||
capabilities: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
const deviceSchema = z.object({
|
||||
localDeviceId: z.string().min(1),
|
||||
platform: z.enum(["web", "ios", "android"]),
|
||||
providerToken: z.string().optional(),
|
||||
subscription: z.record(z.string(), z.unknown()).optional(),
|
||||
meta: z.record(z.string(), z.unknown()).optional().default({}),
|
||||
});
|
||||
|
||||
const pushSchema = z.object({
|
||||
idempotencyKey: z.string().min(1).max(200),
|
||||
devices: z.array(z.string().min(1)).min(1).max(500),
|
||||
priority: z.enum(["normal", "high"]).default("normal"),
|
||||
ttlSeconds: z.number().int().positive().max(2_419_200).default(3600),
|
||||
collapseKey: z.string().max(64).optional(),
|
||||
notification: z.object({
|
||||
title: z.string().max(120).optional(),
|
||||
body: z.string().max(240).optional(),
|
||||
}).optional(),
|
||||
data: z.record(z.string(), z.unknown()).optional().default({}),
|
||||
});
|
||||
|
||||
export async function instanceRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.addHook("preHandler", requireInstance);
|
||||
|
||||
app.post("/v1/instances/heartbeat", async (request) => {
|
||||
const instance = request.pushInstance!;
|
||||
const body = heartbeatSchema.parse(request.body);
|
||||
const [updated] = await db.update(pushInstances).set({
|
||||
baseUrl: body.baseUrl || instance.baseUrl,
|
||||
capabilities: body.capabilities || instance.capabilities,
|
||||
lastHeartbeatAt: new Date(),
|
||||
lastHeartbeatVersion: body.fedeoVersion || null,
|
||||
lastHeartbeatIp: request.ip,
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(pushInstances.id, instance.id)).returning();
|
||||
return {
|
||||
status: updated.status,
|
||||
instanceId: updated.instanceId,
|
||||
payloadMode: updated.mode,
|
||||
capabilities: updated.capabilities,
|
||||
};
|
||||
});
|
||||
|
||||
app.post("/v1/devices", async (request) => {
|
||||
const instance = request.pushInstance!;
|
||||
const body = deviceSchema.parse(request.body);
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(pushDevices)
|
||||
.where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.localDeviceId, body.localDeviceId)))
|
||||
.limit(1);
|
||||
|
||||
const values = {
|
||||
platform: body.platform,
|
||||
status: "active" as const,
|
||||
providerTokenEncrypted: body.providerToken ? encryptSecret(body.providerToken) : null,
|
||||
webPushSubscription: body.subscription || null,
|
||||
meta: body.meta,
|
||||
lastSeenAt: new Date(),
|
||||
disabledAt: null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
if (existing[0]) {
|
||||
const [updated] = await db.update(pushDevices).set(values).where(eq(pushDevices.id, existing[0].id)).returning();
|
||||
return { centralDeviceId: updated.centralDeviceId, status: updated.status };
|
||||
}
|
||||
|
||||
const [created] = await db.insert(pushDevices).values({
|
||||
...values,
|
||||
centralDeviceId: createPublicId("dev"),
|
||||
instanceId: instance.id,
|
||||
localDeviceId: body.localDeviceId,
|
||||
}).returning();
|
||||
return { centralDeviceId: created.centralDeviceId, status: created.status };
|
||||
});
|
||||
|
||||
app.delete("/v1/devices/:centralDeviceId", async (request, reply) => {
|
||||
const instance = request.pushInstance!;
|
||||
const params = z.object({ centralDeviceId: z.string().min(1) }).parse(request.params);
|
||||
const [updated] = await db.update(pushDevices).set({
|
||||
status: "disabled",
|
||||
disabledAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
}).where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.centralDeviceId, params.centralDeviceId))).returning();
|
||||
if (!updated) return reply.code(404).send({ error: "device_not_found" });
|
||||
return { centralDeviceId: updated.centralDeviceId, status: updated.status };
|
||||
});
|
||||
|
||||
app.post("/v1/push", async (request, reply) => {
|
||||
const instance = request.pushInstance!;
|
||||
const body = pushSchema.parse(request.body);
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(deliveryJobs)
|
||||
.where(and(eq(deliveryJobs.instanceId, instance.id), eq(deliveryJobs.idempotencyKey, body.idempotencyKey)))
|
||||
.limit(1);
|
||||
|
||||
if (existing[0]) {
|
||||
return {
|
||||
accepted: existing[0].acceptedCount,
|
||||
rejected: existing[0].rejectedCount,
|
||||
deliveryJobId: existing[0].deliveryJobId,
|
||||
status: existing[0].status,
|
||||
idempotent: true,
|
||||
};
|
||||
}
|
||||
|
||||
const devices = await db
|
||||
.select()
|
||||
.from(pushDevices)
|
||||
.where(and(eq(pushDevices.instanceId, instance.id), eq(pushDevices.status, "active")));
|
||||
const allowed = new Set(devices.map((device) => device.centralDeviceId));
|
||||
const acceptedDevices = body.devices.filter((deviceId) => allowed.has(deviceId));
|
||||
const rejected = body.devices.length - acceptedDevices.length;
|
||||
|
||||
const [job] = await db.insert(deliveryJobs).values({
|
||||
deliveryJobId: createPublicId("job"),
|
||||
instanceId: instance.id,
|
||||
idempotencyKey: body.idempotencyKey,
|
||||
priority: body.priority,
|
||||
ttlSeconds: body.ttlSeconds,
|
||||
collapseKey: body.collapseKey,
|
||||
acceptedCount: acceptedDevices.length,
|
||||
rejectedCount: rejected,
|
||||
status: "processing",
|
||||
}).returning();
|
||||
|
||||
await deliverJob(job, acceptedDevices, {
|
||||
priority: body.priority,
|
||||
ttlSeconds: body.ttlSeconds,
|
||||
collapseKey: body.collapseKey,
|
||||
notification: body.notification,
|
||||
data: body.data,
|
||||
});
|
||||
|
||||
return reply.code(202).send({
|
||||
accepted: acceptedDevices.length,
|
||||
rejected,
|
||||
deliveryJobId: job.deliveryJobId,
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/v1/push/:deliveryJobId", async (request, reply) => {
|
||||
const instance = request.pushInstance!;
|
||||
const params = z.object({ deliveryJobId: z.string().min(1) }).parse(request.params);
|
||||
const [job] = await db
|
||||
.select()
|
||||
.from(deliveryJobs)
|
||||
.where(and(eq(deliveryJobs.instanceId, instance.id), eq(deliveryJobs.deliveryJobId, params.deliveryJobId)))
|
||||
.limit(1);
|
||||
if (!job) return reply.code(404).send({ error: "job_not_found" });
|
||||
return {
|
||||
deliveryJobId: job.deliveryJobId,
|
||||
status: job.status,
|
||||
accepted: job.acceptedCount,
|
||||
rejected: job.rejectedCount,
|
||||
sent: job.sentCount,
|
||||
failed: job.failedCount,
|
||||
lastErrorCode: job.lastErrorCode,
|
||||
lastErrorMessage: job.lastErrorMessage,
|
||||
completedAt: job.completedAt,
|
||||
};
|
||||
});
|
||||
}
|
||||
16
push-server/apps/api/src/routes/public.ts
Normal file
16
push-server/apps/api/src/routes/public.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { env } from "../config/env.js";
|
||||
|
||||
export async function publicRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get("/health", async () => ({
|
||||
status: "ok",
|
||||
service: "fedeo-push-api",
|
||||
}));
|
||||
|
||||
app.get("/v1/public-config", async () => ({
|
||||
webPushPublicKey: env.WEB_PUSH_PUBLIC_KEY || null,
|
||||
iosBundleId: env.IOS_BUNDLE_ID,
|
||||
androidSenderId: env.ANDROID_SENDER_ID || null,
|
||||
capabilities: ["ios_push", "minimal_payload", "instance_hmac"],
|
||||
}));
|
||||
}
|
||||
100
push-server/apps/api/src/services/apns.ts
Normal file
100
push-server/apps/api/src/services/apns.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import http2 from "node:http2";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { env } from "../config/env.js";
|
||||
|
||||
export type ApnsPayload = {
|
||||
aps: {
|
||||
alert?: {
|
||||
title?: string;
|
||||
body?: string;
|
||||
};
|
||||
sound?: string;
|
||||
badge?: number;
|
||||
"content-available"?: 1;
|
||||
"mutable-content"?: 1;
|
||||
};
|
||||
data?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type ApnsResult =
|
||||
| { ok: true; providerMessageId?: string }
|
||||
| { ok: false; code: string; message: string; permanent: boolean };
|
||||
|
||||
export class ApnsClient {
|
||||
isConfigured(): boolean {
|
||||
return Boolean(env.APNS_TEAM_ID && env.APNS_KEY_ID && env.APNS_PRIVATE_KEY && env.IOS_BUNDLE_ID);
|
||||
}
|
||||
|
||||
async send(deviceToken: string, payload: ApnsPayload, options?: { collapseKey?: string; priority?: "normal" | "high"; ttlSeconds?: number }): Promise<ApnsResult> {
|
||||
if (!this.isConfigured()) {
|
||||
return { ok: false, code: "apns_not_configured", message: "APNs ist nicht vollständig konfiguriert.", permanent: false };
|
||||
}
|
||||
|
||||
const host = env.APNS_PRODUCTION ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com";
|
||||
const token = jwt.sign(
|
||||
{ iss: env.APNS_TEAM_ID, iat: Math.floor(Date.now() / 1000) },
|
||||
env.APNS_PRIVATE_KEY.replace(/\\n/g, "\n"),
|
||||
{ algorithm: "ES256", header: { alg: "ES256", kid: env.APNS_KEY_ID } },
|
||||
);
|
||||
|
||||
return await new Promise<ApnsResult>((resolve) => {
|
||||
const client = http2.connect(host);
|
||||
const headers: http2.OutgoingHttpHeaders = {
|
||||
":method": "POST",
|
||||
":path": `/3/device/${deviceToken}`,
|
||||
authorization: `bearer ${token}`,
|
||||
"apns-topic": env.IOS_BUNDLE_ID,
|
||||
"apns-push-type": payload.aps["content-available"] === 1 && !payload.aps.alert ? "background" : "alert",
|
||||
"apns-priority": options?.priority === "high" ? "10" : "5",
|
||||
};
|
||||
|
||||
if (options?.collapseKey) headers["apns-collapse-id"] = options.collapseKey.slice(0, 64);
|
||||
if (options?.ttlSeconds) {
|
||||
headers["apns-expiration"] = String(Math.floor(Date.now() / 1000) + options.ttlSeconds);
|
||||
}
|
||||
|
||||
const req = client.request(headers);
|
||||
const chunks: Buffer[] = [];
|
||||
let statusCode = 0;
|
||||
let apnsId: string | undefined;
|
||||
|
||||
req.setEncoding("utf8");
|
||||
req.on("response", (responseHeaders) => {
|
||||
statusCode = Number(responseHeaders[":status"] || 0);
|
||||
const rawApnsId = responseHeaders["apns-id"];
|
||||
apnsId = Array.isArray(rawApnsId) ? rawApnsId[0] : rawApnsId;
|
||||
});
|
||||
req.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
|
||||
req.on("error", (error) => {
|
||||
client.close();
|
||||
resolve({ ok: false, code: "apns_transport_error", message: error.message, permanent: false });
|
||||
});
|
||||
req.on("end", () => {
|
||||
client.close();
|
||||
if (statusCode >= 200 && statusCode < 300) {
|
||||
resolve({ ok: true, providerMessageId: apnsId });
|
||||
return;
|
||||
}
|
||||
|
||||
const body = Buffer.concat(chunks).toString("utf8");
|
||||
const reason = safeReason(body) || `HTTP ${statusCode}`;
|
||||
resolve({
|
||||
ok: false,
|
||||
code: `apns_${reason.toLowerCase()}`,
|
||||
message: reason,
|
||||
permanent: ["BadDeviceToken", "Unregistered", "DeviceTokenNotForTopic"].includes(reason),
|
||||
});
|
||||
});
|
||||
req.end(JSON.stringify(payload));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function safeReason(body: string): string | null {
|
||||
try {
|
||||
const parsed = JSON.parse(body) as { reason?: string };
|
||||
return parsed.reason || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
104
push-server/apps/api/src/services/delivery.ts
Normal file
104
push-server/apps/api/src/services/delivery.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { deliveryAttempts, deliveryJobs, pushDevices, type DeliveryJob, type PushDevice } from "@fedeo/push-db";
|
||||
import { db } from "../db/client.js";
|
||||
import { decryptSecret } from "../lib/crypto.js";
|
||||
import { ApnsClient, type ApnsPayload } from "./apns.js";
|
||||
|
||||
export type PushCommand = {
|
||||
priority: "normal" | "high";
|
||||
ttlSeconds: number;
|
||||
collapseKey?: string;
|
||||
notification?: {
|
||||
title?: string;
|
||||
body?: string;
|
||||
};
|
||||
data?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
const apns = new ApnsClient();
|
||||
|
||||
export async function deliverJob(job: DeliveryJob, deviceIds: string[], command: PushCommand): Promise<void> {
|
||||
const devices = await db
|
||||
.select()
|
||||
.from(pushDevices)
|
||||
.where(and(inArray(pushDevices.centralDeviceId, deviceIds), eq(pushDevices.instanceId, job.instanceId), eq(pushDevices.status, "active")));
|
||||
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
let lastErrorCode: string | null = null;
|
||||
let lastErrorMessage: string | null = null;
|
||||
|
||||
for (const device of devices) {
|
||||
const result = await deliverToDevice(device, command);
|
||||
if (result.ok) {
|
||||
sent += 1;
|
||||
await db.insert(deliveryAttempts).values({
|
||||
deliveryJobId: job.id,
|
||||
deviceId: device.id,
|
||||
provider: result.provider,
|
||||
status: "sent",
|
||||
providerMessageId: result.providerMessageId,
|
||||
sentAt: new Date(),
|
||||
});
|
||||
} else {
|
||||
failed += 1;
|
||||
lastErrorCode = result.code;
|
||||
lastErrorMessage = result.message;
|
||||
await db.insert(deliveryAttempts).values({
|
||||
deliveryJobId: job.id,
|
||||
deviceId: device.id,
|
||||
provider: result.provider,
|
||||
status: "failed",
|
||||
errorCode: result.code,
|
||||
errorMessage: result.message,
|
||||
});
|
||||
|
||||
if (result.disableDevice) {
|
||||
await db.update(pushDevices).set({ status: "invalid", disabledAt: new Date(), updatedAt: new Date() }).where(eq(pushDevices.id, device.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const status = failed === 0 ? "completed" : sent > 0 ? "partial" : "failed";
|
||||
await db.update(deliveryJobs).set({
|
||||
status,
|
||||
sentCount: sent,
|
||||
failedCount: failed,
|
||||
lastErrorCode,
|
||||
lastErrorMessage,
|
||||
completedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(deliveryJobs.id, job.id));
|
||||
}
|
||||
|
||||
async function deliverToDevice(device: PushDevice, command: PushCommand): Promise<
|
||||
| { ok: true; provider: "apns" | "web_push" | "fcm"; providerMessageId?: string }
|
||||
| { ok: false; provider: "apns" | "web_push" | "fcm"; code: string; message: string; disableDevice: boolean }
|
||||
> {
|
||||
if (device.platform === "ios") {
|
||||
if (!device.providerTokenEncrypted) {
|
||||
return { ok: false, provider: "apns", code: "missing_provider_token", message: "Für das iOS-Gerät ist kein Provider Token gespeichert.", disableDevice: true };
|
||||
}
|
||||
const payload: ApnsPayload = {
|
||||
aps: {
|
||||
alert: command.notification ? { title: command.notification.title, body: command.notification.body } : undefined,
|
||||
sound: command.notification ? "default" : undefined,
|
||||
"content-available": command.notification ? undefined : 1,
|
||||
},
|
||||
data: command.data,
|
||||
};
|
||||
const result = await apns.send(decryptSecret(device.providerTokenEncrypted), payload, {
|
||||
collapseKey: command.collapseKey,
|
||||
priority: command.priority,
|
||||
ttlSeconds: command.ttlSeconds,
|
||||
});
|
||||
if (result.ok) return { ok: true, provider: "apns", providerMessageId: result.providerMessageId };
|
||||
return { ok: false, provider: "apns", code: result.code, message: result.message, disableDevice: result.permanent };
|
||||
}
|
||||
|
||||
if (device.platform === "android") {
|
||||
return { ok: false, provider: "fcm", code: "fcm_not_implemented", message: "FCM ist im Stack vorbereitet, aber noch nicht implementiert.", disableDevice: false };
|
||||
}
|
||||
|
||||
return { ok: false, provider: "web_push", code: "web_push_not_implemented", message: "Web Push ist im Stack vorbereitet, aber noch nicht implementiert.", disableDevice: false };
|
||||
}
|
||||
8
push-server/apps/api/src/types.ts
Normal file
8
push-server/apps/api/src/types.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { PushInstance } from "@fedeo/push-db";
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyRequest {
|
||||
rawBody?: string;
|
||||
pushInstance?: PushInstance;
|
||||
}
|
||||
}
|
||||
13
push-server/apps/api/tsconfig.json
Normal file
13
push-server/apps/api/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user