KI-AGENT: Zentralen Push-Server Stack ergänzen
This commit is contained in:
19
push-server/.env.example
Normal file
19
push-server/.env.example
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
NODE_ENV=development
|
||||||
|
DATABASE_URL=postgres://fedeo_push:fedeo_push@localhost:5442/fedeo_push
|
||||||
|
API_HOST=0.0.0.0
|
||||||
|
API_PORT=4020
|
||||||
|
ADMIN_TOKEN=change-me-admin-token
|
||||||
|
PUSH_SECRET_ENCRYPTION_KEY=change-me-32-byte-minimum-secret
|
||||||
|
PUBLIC_BASE_URL=http://localhost:4020
|
||||||
|
WEB_PUSH_PUBLIC_KEY=
|
||||||
|
WEB_PUSH_PRIVATE_KEY=
|
||||||
|
IOS_BUNDLE_ID=software.federspiel.fedeo
|
||||||
|
APNS_TEAM_ID=
|
||||||
|
APNS_KEY_ID=
|
||||||
|
APNS_PRIVATE_KEY=
|
||||||
|
APNS_PRODUCTION=false
|
||||||
|
ANDROID_SENDER_ID=
|
||||||
|
FCM_PROJECT_ID=
|
||||||
|
FCM_SERVICE_ACCOUNT_JSON=
|
||||||
|
NUXT_PUBLIC_API_BASE=http://localhost:4020
|
||||||
|
NUXT_ADMIN_TOKEN=change-me-admin-token
|
||||||
7
push-server/.gitignore
vendored
Normal file
7
push-server/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
.nuxt
|
||||||
|
.output
|
||||||
|
dist
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
*.log
|
||||||
115
push-server/README.md
Normal file
115
push-server/README.md
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
# FEDEO Push Server
|
||||||
|
|
||||||
|
Eigenständiger Stack für den zentralen FEDEO Push-Transportdienst. Selfhosted FEDEO-Instanzen registrieren Geräte lokal und leiten nur technische Push-Aufträge an diesen Dienst weiter. Die Instanzen authentifizieren sich mit einem rotierbaren Schlüssel, der im Admin-Dashboard gepflegt wird.
|
||||||
|
|
||||||
|
## Bestandteile
|
||||||
|
|
||||||
|
- `apps/api`: Fastify API für Admin-Dashboard und Selfhost-Instanzen
|
||||||
|
- `apps/admin`: Nuxt Admin Dashboard mit Nuxt UI
|
||||||
|
- `packages/db`: Drizzle Schema und Migrationen für PostgreSQL
|
||||||
|
- `docker-compose.yml`: lokaler Stack aus Postgres, API und Admin
|
||||||
|
|
||||||
|
## Entwicklung
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd push-server
|
||||||
|
cp .env.example .env
|
||||||
|
npm install
|
||||||
|
npm run db:migrate
|
||||||
|
npm run dev:api
|
||||||
|
npm run dev:admin
|
||||||
|
```
|
||||||
|
|
||||||
|
Standardports:
|
||||||
|
|
||||||
|
- API: `http://localhost:4020`
|
||||||
|
- Admin: `http://localhost:3000` lokal oder `http://localhost:3020` über Docker Compose
|
||||||
|
- Postgres: `localhost:5442`
|
||||||
|
|
||||||
|
## Admin-Zugang
|
||||||
|
|
||||||
|
Das Dashboard nutzt den Wert aus `ADMIN_TOKEN`. Der Token wird im Browser nur lokal gespeichert und als `Authorization: Bearer ...` an die API gesendet.
|
||||||
|
|
||||||
|
## Instanz-Authentifizierung
|
||||||
|
|
||||||
|
Instanzaufrufe verwenden HMAC-SHA256:
|
||||||
|
|
||||||
|
```text
|
||||||
|
X-Fedeo-Instance-Id: inst_...
|
||||||
|
X-Fedeo-Timestamp: 2026-05-22T10:00:00.000Z
|
||||||
|
X-Fedeo-Signature: <hex-hmac>
|
||||||
|
```
|
||||||
|
|
||||||
|
Signiert wird:
|
||||||
|
|
||||||
|
```text
|
||||||
|
METHOD
|
||||||
|
PATH
|
||||||
|
TIMESTAMP
|
||||||
|
SHA256(BODY)
|
||||||
|
INSTANCE_ID
|
||||||
|
```
|
||||||
|
|
||||||
|
Beispiel:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { createHash, createHmac } from "node:crypto";
|
||||||
|
|
||||||
|
const body = JSON.stringify(payload);
|
||||||
|
const timestamp = new Date().toISOString();
|
||||||
|
const bodyHash = createHash("sha256").update(body).digest("hex");
|
||||||
|
const canonical = ["POST", "/v1/push", timestamp, bodyHash, instanceId].join("\n");
|
||||||
|
const signature = createHmac("sha256", clientSecret).update(canonical).digest("hex");
|
||||||
|
```
|
||||||
|
|
||||||
|
## Wichtige API-Endpunkte
|
||||||
|
|
||||||
|
- `GET /v1/public-config`
|
||||||
|
- `POST /v1/instances/heartbeat`
|
||||||
|
- `POST /v1/devices`
|
||||||
|
- `DELETE /v1/devices/:centralDeviceId`
|
||||||
|
- `POST /v1/push`
|
||||||
|
- `GET /v1/push/:deliveryJobId`
|
||||||
|
|
||||||
|
Admin:
|
||||||
|
|
||||||
|
- `GET /admin/summary`
|
||||||
|
- `GET /admin/instances`
|
||||||
|
- `POST /admin/instances`
|
||||||
|
- `PATCH /admin/instances/:id`
|
||||||
|
- `POST /admin/instances/:id/rotate-secret`
|
||||||
|
- `GET /admin/instances/:id/devices`
|
||||||
|
- `GET /admin/instances/:id/jobs`
|
||||||
|
|
||||||
|
## Apple Push Notification service
|
||||||
|
|
||||||
|
Für iOS müssen diese Werte gesetzt sein:
|
||||||
|
|
||||||
|
```env
|
||||||
|
IOS_BUNDLE_ID=software.federspiel.fedeo
|
||||||
|
APNS_TEAM_ID=...
|
||||||
|
APNS_KEY_ID=...
|
||||||
|
APNS_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
|
||||||
|
APNS_PRODUCTION=false
|
||||||
|
```
|
||||||
|
|
||||||
|
Solange APNs nicht vollständig konfiguriert ist, nimmt die API Push-Aufträge an, markiert iOS-Zustellversuche aber mit `apns_not_configured`.
|
||||||
|
|
||||||
|
## Aktueller Umfang
|
||||||
|
|
||||||
|
Implementiert:
|
||||||
|
|
||||||
|
- Instanzverwaltung im Admin-Dashboard
|
||||||
|
- rotierbare Instanzschlüssel mit verschlüsselter Speicherung
|
||||||
|
- HMAC-authentifizierte Instanzbefehle
|
||||||
|
- Geräte-Registry für `web`, `ios` und `android`
|
||||||
|
- Zustelljobs mit Idempotenzschlüssel
|
||||||
|
- APNs-Zustellung für iOS
|
||||||
|
- technische Status- und Fehlererfassung
|
||||||
|
|
||||||
|
Vorbereitet, aber noch nicht vollständig implementiert:
|
||||||
|
|
||||||
|
- Web Push Zustellung
|
||||||
|
- FCM Zustellung
|
||||||
|
- asynchrone Queue/Worker-Verarbeitung
|
||||||
|
- produktive Rate-Limits pro Instanz
|
||||||
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"]
|
||||||
|
}
|
||||||
44
push-server/docker-compose.yml
Normal file
44
push-server/docker-compose.yml
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: fedeo_push
|
||||||
|
POSTGRES_USER: fedeo_push
|
||||||
|
POSTGRES_PASSWORD: fedeo_push
|
||||||
|
ports:
|
||||||
|
- "5442:5432"
|
||||||
|
volumes:
|
||||||
|
- push_postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U fedeo_push -d fedeo_push"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: apps/api/Dockerfile
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgres://fedeo_push:fedeo_push@postgres:5432/fedeo_push
|
||||||
|
ports:
|
||||||
|
- "4020:4020"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
admin:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: apps/admin/Dockerfile
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
NUXT_PUBLIC_API_BASE: http://localhost:4020
|
||||||
|
ports:
|
||||||
|
- "3020:3000"
|
||||||
|
depends_on:
|
||||||
|
- api
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
push_postgres_data:
|
||||||
37
push-server/docs/instance-client.md
Normal file
37
push-server/docs/instance-client.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Selfhost-Instanz anbinden
|
||||||
|
|
||||||
|
1. Instanz im Admin-Dashboard anlegen.
|
||||||
|
2. `instanceId` und den einmalig angezeigten `clientSecret` in der Selfhost-Instanz speichern.
|
||||||
|
3. Selfhost-Instanz sendet regelmäßig `POST /v1/instances/heartbeat`.
|
||||||
|
4. Geräte werden über `POST /v1/devices` registriert.
|
||||||
|
5. Push-Aufträge werden über `POST /v1/push` gesendet.
|
||||||
|
|
||||||
|
## Umgebungsvariablen der Selfhost-Instanz
|
||||||
|
|
||||||
|
```env
|
||||||
|
FEDEO_PUSH_MODE=central
|
||||||
|
FEDEO_PUSH_GATEWAY_URL=https://push.fedeo.cloud
|
||||||
|
FEDEO_PUSH_INSTANCE_ID=inst_...
|
||||||
|
FEDEO_PUSH_CLIENT_SECRET=fps_...
|
||||||
|
FEDEO_PUSH_PAYLOAD_MODE=minimal
|
||||||
|
```
|
||||||
|
|
||||||
|
## Minimaler Push-Auftrag
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"idempotencyKey": "notification-item-id:dev_...",
|
||||||
|
"devices": ["dev_..."],
|
||||||
|
"priority": "normal",
|
||||||
|
"ttlSeconds": 3600,
|
||||||
|
"collapseKey": "communication.message.new",
|
||||||
|
"notification": {
|
||||||
|
"title": "Neue FEDEO-Benachrichtigung",
|
||||||
|
"body": "Öffne FEDEO, um die Details anzusehen."
|
||||||
|
},
|
||||||
|
"data": {
|
||||||
|
"notificationId": "lokale-notification-id",
|
||||||
|
"link": "/communication"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
14914
push-server/package-lock.json
generated
Normal file
14914
push-server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
push-server/package.json
Normal file
21
push-server/package.json
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "@fedeo/push-server",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"workspaces": [
|
||||||
|
"apps/*",
|
||||||
|
"packages/*"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"dev": "npm run dev --workspace @fedeo/push-api",
|
||||||
|
"dev:api": "npm run dev --workspace @fedeo/push-api",
|
||||||
|
"dev:admin": "npm run dev --workspace @fedeo/push-admin",
|
||||||
|
"build": "npm run build --workspaces --if-present",
|
||||||
|
"typecheck": "npm run typecheck --workspaces --if-present",
|
||||||
|
"db:generate": "npm run db:generate --workspace @fedeo/push-db",
|
||||||
|
"db:migrate": "npm run db:migrate --workspace @fedeo/push-db"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
}
|
||||||
|
}
|
||||||
10
push-server/packages/db/drizzle.config.ts
Normal file
10
push-server/packages/db/drizzle.config.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from "drizzle-kit";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: "./src/schema.ts",
|
||||||
|
out: "./drizzle",
|
||||||
|
dialect: "postgresql",
|
||||||
|
dbCredentials: {
|
||||||
|
url: process.env.DATABASE_URL || "postgres://fedeo_push:fedeo_push@localhost:5442/fedeo_push",
|
||||||
|
},
|
||||||
|
});
|
||||||
106
push-server/packages/db/drizzle/0000_big_devos.sql
Normal file
106
push-server/packages/db/drizzle/0000_big_devos.sql
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
CREATE TYPE "public"."attempt_provider" AS ENUM('web_push', 'apns', 'fcm');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."attempt_status" AS ENUM('pending', 'sent', 'failed', 'skipped');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."delivery_status" AS ENUM('accepted', 'processing', 'completed', 'failed', 'partial');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."device_platform" AS ENUM('web', 'ios', 'android');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."device_status" AS ENUM('active', 'disabled', 'invalid');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."instance_status" AS ENUM('active', 'blocked', 'disabled');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."payload_mode" AS ENUM('minimal', 'rich');--> statement-breakpoint
|
||||||
|
CREATE TABLE "audit_logs" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"actor" text NOT NULL,
|
||||||
|
"action" text NOT NULL,
|
||||||
|
"instance_id" uuid,
|
||||||
|
"meta" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "delivery_attempts" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"delivery_job_id" uuid NOT NULL,
|
||||||
|
"device_id" uuid NOT NULL,
|
||||||
|
"provider" "attempt_provider" NOT NULL,
|
||||||
|
"status" "attempt_status" DEFAULT 'pending' NOT NULL,
|
||||||
|
"provider_message_id" text,
|
||||||
|
"error_code" text,
|
||||||
|
"error_message" text,
|
||||||
|
"sent_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "delivery_jobs" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"delivery_job_id" text NOT NULL,
|
||||||
|
"instance_id" uuid NOT NULL,
|
||||||
|
"idempotency_key" text NOT NULL,
|
||||||
|
"status" "delivery_status" DEFAULT 'accepted' NOT NULL,
|
||||||
|
"priority" text DEFAULT 'normal' NOT NULL,
|
||||||
|
"collapse_key" text,
|
||||||
|
"ttl_seconds" integer DEFAULT 3600 NOT NULL,
|
||||||
|
"accepted_count" integer DEFAULT 0 NOT NULL,
|
||||||
|
"rejected_count" integer DEFAULT 0 NOT NULL,
|
||||||
|
"sent_count" integer DEFAULT 0 NOT NULL,
|
||||||
|
"failed_count" integer DEFAULT 0 NOT NULL,
|
||||||
|
"last_error_code" text,
|
||||||
|
"last_error_message" text,
|
||||||
|
"completed_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "delivery_jobs_delivery_job_id_unique" UNIQUE("delivery_job_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "push_devices" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"central_device_id" text NOT NULL,
|
||||||
|
"instance_id" uuid NOT NULL,
|
||||||
|
"local_device_id" text NOT NULL,
|
||||||
|
"platform" "device_platform" NOT NULL,
|
||||||
|
"status" "device_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"provider_token_encrypted" text,
|
||||||
|
"web_push_subscription" jsonb,
|
||||||
|
"meta" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||||
|
"last_seen_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"disabled_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "push_devices_central_device_id_unique" UNIQUE("central_device_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "push_instances" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"instance_id" text NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"base_url" text NOT NULL,
|
||||||
|
"status" "instance_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"payload_mode" "payload_mode" DEFAULT 'minimal' NOT NULL,
|
||||||
|
"capabilities" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||||
|
"rate_limit_per_minute" integer DEFAULT 120 NOT NULL,
|
||||||
|
"daily_quota" integer DEFAULT 10000 NOT NULL,
|
||||||
|
"current_secret_encrypted" text NOT NULL,
|
||||||
|
"current_secret_preview" text NOT NULL,
|
||||||
|
"next_secret_encrypted" text,
|
||||||
|
"next_secret_preview" text,
|
||||||
|
"notes" text,
|
||||||
|
"last_heartbeat_at" timestamp with time zone,
|
||||||
|
"last_heartbeat_version" text,
|
||||||
|
"last_heartbeat_ip" text,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "push_instances_instance_id_unique" UNIQUE("instance_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_instance_id_push_instances_id_fk" FOREIGN KEY ("instance_id") REFERENCES "public"."push_instances"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "delivery_attempts" ADD CONSTRAINT "delivery_attempts_delivery_job_id_delivery_jobs_id_fk" FOREIGN KEY ("delivery_job_id") REFERENCES "public"."delivery_jobs"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "delivery_attempts" ADD CONSTRAINT "delivery_attempts_device_id_push_devices_id_fk" FOREIGN KEY ("device_id") REFERENCES "public"."push_devices"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "delivery_jobs" ADD CONSTRAINT "delivery_jobs_instance_id_push_instances_id_fk" FOREIGN KEY ("instance_id") REFERENCES "public"."push_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "push_devices" ADD CONSTRAINT "push_devices_instance_id_push_instances_id_fk" FOREIGN KEY ("instance_id") REFERENCES "public"."push_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "audit_logs_instance_created_idx" ON "audit_logs" USING btree ("instance_id","created_at");--> statement-breakpoint
|
||||||
|
CREATE INDEX "delivery_attempts_job_idx" ON "delivery_attempts" USING btree ("delivery_job_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "delivery_attempts_device_idx" ON "delivery_attempts" USING btree ("device_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "delivery_jobs_delivery_job_id_idx" ON "delivery_jobs" USING btree ("delivery_job_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "delivery_jobs_instance_idempotency_idx" ON "delivery_jobs" USING btree ("instance_id","idempotency_key");--> statement-breakpoint
|
||||||
|
CREATE INDEX "delivery_jobs_instance_created_idx" ON "delivery_jobs" USING btree ("instance_id","created_at");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "push_devices_central_device_id_idx" ON "push_devices" USING btree ("central_device_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "push_devices_instance_local_device_idx" ON "push_devices" USING btree ("instance_id","local_device_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "push_devices_instance_status_idx" ON "push_devices" USING btree ("instance_id","status");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "push_instances_instance_id_idx" ON "push_instances" USING btree ("instance_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "push_instances_status_idx" ON "push_instances" USING btree ("status");
|
||||||
870
push-server/packages/db/drizzle/meta/0000_snapshot.json
Normal file
870
push-server/packages/db/drizzle/meta/0000_snapshot.json
Normal file
@@ -0,0 +1,870 @@
|
|||||||
|
{
|
||||||
|
"id": "bcd8b541-814a-4dfb-8cb8-b677d1218da4",
|
||||||
|
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"tables": {
|
||||||
|
"public.audit_logs": {
|
||||||
|
"name": "audit_logs",
|
||||||
|
"schema": "",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "gen_random_uuid()"
|
||||||
|
},
|
||||||
|
"actor": {
|
||||||
|
"name": "actor",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"action": {
|
||||||
|
"name": "action",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"instance_id": {
|
||||||
|
"name": "instance_id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"meta": {
|
||||||
|
"name": "meta",
|
||||||
|
"type": "jsonb",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'{}'::jsonb"
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"audit_logs_instance_created_idx": {
|
||||||
|
"name": "audit_logs_instance_created_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "instance_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expression": "created_at",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": false,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"audit_logs_instance_id_push_instances_id_fk": {
|
||||||
|
"name": "audit_logs_instance_id_push_instances_id_fk",
|
||||||
|
"tableFrom": "audit_logs",
|
||||||
|
"tableTo": "push_instances",
|
||||||
|
"columnsFrom": [
|
||||||
|
"instance_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "set null",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {},
|
||||||
|
"policies": {},
|
||||||
|
"checkConstraints": {},
|
||||||
|
"isRLSEnabled": false
|
||||||
|
},
|
||||||
|
"public.delivery_attempts": {
|
||||||
|
"name": "delivery_attempts",
|
||||||
|
"schema": "",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "gen_random_uuid()"
|
||||||
|
},
|
||||||
|
"delivery_job_id": {
|
||||||
|
"name": "delivery_job_id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"device_id": {
|
||||||
|
"name": "device_id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"provider": {
|
||||||
|
"name": "provider",
|
||||||
|
"type": "attempt_provider",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"name": "status",
|
||||||
|
"type": "attempt_status",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'pending'"
|
||||||
|
},
|
||||||
|
"provider_message_id": {
|
||||||
|
"name": "provider_message_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"error_code": {
|
||||||
|
"name": "error_code",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"error_message": {
|
||||||
|
"name": "error_message",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"sent_at": {
|
||||||
|
"name": "sent_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"delivery_attempts_job_idx": {
|
||||||
|
"name": "delivery_attempts_job_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "delivery_job_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": false,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
},
|
||||||
|
"delivery_attempts_device_idx": {
|
||||||
|
"name": "delivery_attempts_device_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "device_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": false,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"delivery_attempts_delivery_job_id_delivery_jobs_id_fk": {
|
||||||
|
"name": "delivery_attempts_delivery_job_id_delivery_jobs_id_fk",
|
||||||
|
"tableFrom": "delivery_attempts",
|
||||||
|
"tableTo": "delivery_jobs",
|
||||||
|
"columnsFrom": [
|
||||||
|
"delivery_job_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "cascade",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"delivery_attempts_device_id_push_devices_id_fk": {
|
||||||
|
"name": "delivery_attempts_device_id_push_devices_id_fk",
|
||||||
|
"tableFrom": "delivery_attempts",
|
||||||
|
"tableTo": "push_devices",
|
||||||
|
"columnsFrom": [
|
||||||
|
"device_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "cascade",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {},
|
||||||
|
"policies": {},
|
||||||
|
"checkConstraints": {},
|
||||||
|
"isRLSEnabled": false
|
||||||
|
},
|
||||||
|
"public.delivery_jobs": {
|
||||||
|
"name": "delivery_jobs",
|
||||||
|
"schema": "",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "gen_random_uuid()"
|
||||||
|
},
|
||||||
|
"delivery_job_id": {
|
||||||
|
"name": "delivery_job_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"instance_id": {
|
||||||
|
"name": "instance_id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"idempotency_key": {
|
||||||
|
"name": "idempotency_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"name": "status",
|
||||||
|
"type": "delivery_status",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'accepted'"
|
||||||
|
},
|
||||||
|
"priority": {
|
||||||
|
"name": "priority",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'normal'"
|
||||||
|
},
|
||||||
|
"collapse_key": {
|
||||||
|
"name": "collapse_key",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"ttl_seconds": {
|
||||||
|
"name": "ttl_seconds",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 3600
|
||||||
|
},
|
||||||
|
"accepted_count": {
|
||||||
|
"name": "accepted_count",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 0
|
||||||
|
},
|
||||||
|
"rejected_count": {
|
||||||
|
"name": "rejected_count",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 0
|
||||||
|
},
|
||||||
|
"sent_count": {
|
||||||
|
"name": "sent_count",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 0
|
||||||
|
},
|
||||||
|
"failed_count": {
|
||||||
|
"name": "failed_count",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 0
|
||||||
|
},
|
||||||
|
"last_error_code": {
|
||||||
|
"name": "last_error_code",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"last_error_message": {
|
||||||
|
"name": "last_error_message",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"completed_at": {
|
||||||
|
"name": "completed_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"delivery_jobs_delivery_job_id_idx": {
|
||||||
|
"name": "delivery_jobs_delivery_job_id_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "delivery_job_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": true,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
},
|
||||||
|
"delivery_jobs_instance_idempotency_idx": {
|
||||||
|
"name": "delivery_jobs_instance_idempotency_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "instance_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expression": "idempotency_key",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": true,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
},
|
||||||
|
"delivery_jobs_instance_created_idx": {
|
||||||
|
"name": "delivery_jobs_instance_created_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "instance_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expression": "created_at",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": false,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"delivery_jobs_instance_id_push_instances_id_fk": {
|
||||||
|
"name": "delivery_jobs_instance_id_push_instances_id_fk",
|
||||||
|
"tableFrom": "delivery_jobs",
|
||||||
|
"tableTo": "push_instances",
|
||||||
|
"columnsFrom": [
|
||||||
|
"instance_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "cascade",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {
|
||||||
|
"delivery_jobs_delivery_job_id_unique": {
|
||||||
|
"name": "delivery_jobs_delivery_job_id_unique",
|
||||||
|
"nullsNotDistinct": false,
|
||||||
|
"columns": [
|
||||||
|
"delivery_job_id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"policies": {},
|
||||||
|
"checkConstraints": {},
|
||||||
|
"isRLSEnabled": false
|
||||||
|
},
|
||||||
|
"public.push_devices": {
|
||||||
|
"name": "push_devices",
|
||||||
|
"schema": "",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "gen_random_uuid()"
|
||||||
|
},
|
||||||
|
"central_device_id": {
|
||||||
|
"name": "central_device_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"instance_id": {
|
||||||
|
"name": "instance_id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"local_device_id": {
|
||||||
|
"name": "local_device_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"platform": {
|
||||||
|
"name": "platform",
|
||||||
|
"type": "device_platform",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"name": "status",
|
||||||
|
"type": "device_status",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'active'"
|
||||||
|
},
|
||||||
|
"provider_token_encrypted": {
|
||||||
|
"name": "provider_token_encrypted",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"web_push_subscription": {
|
||||||
|
"name": "web_push_subscription",
|
||||||
|
"type": "jsonb",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"meta": {
|
||||||
|
"name": "meta",
|
||||||
|
"type": "jsonb",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'{}'::jsonb"
|
||||||
|
},
|
||||||
|
"last_seen_at": {
|
||||||
|
"name": "last_seen_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"disabled_at": {
|
||||||
|
"name": "disabled_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"push_devices_central_device_id_idx": {
|
||||||
|
"name": "push_devices_central_device_id_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "central_device_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": true,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
},
|
||||||
|
"push_devices_instance_local_device_idx": {
|
||||||
|
"name": "push_devices_instance_local_device_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "instance_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expression": "local_device_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": true,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
},
|
||||||
|
"push_devices_instance_status_idx": {
|
||||||
|
"name": "push_devices_instance_status_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "instance_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expression": "status",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": false,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"push_devices_instance_id_push_instances_id_fk": {
|
||||||
|
"name": "push_devices_instance_id_push_instances_id_fk",
|
||||||
|
"tableFrom": "push_devices",
|
||||||
|
"tableTo": "push_instances",
|
||||||
|
"columnsFrom": [
|
||||||
|
"instance_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "cascade",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {
|
||||||
|
"push_devices_central_device_id_unique": {
|
||||||
|
"name": "push_devices_central_device_id_unique",
|
||||||
|
"nullsNotDistinct": false,
|
||||||
|
"columns": [
|
||||||
|
"central_device_id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"policies": {},
|
||||||
|
"checkConstraints": {},
|
||||||
|
"isRLSEnabled": false
|
||||||
|
},
|
||||||
|
"public.push_instances": {
|
||||||
|
"name": "push_instances",
|
||||||
|
"schema": "",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "gen_random_uuid()"
|
||||||
|
},
|
||||||
|
"instance_id": {
|
||||||
|
"name": "instance_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"base_url": {
|
||||||
|
"name": "base_url",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"name": "status",
|
||||||
|
"type": "instance_status",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'active'"
|
||||||
|
},
|
||||||
|
"payload_mode": {
|
||||||
|
"name": "payload_mode",
|
||||||
|
"type": "payload_mode",
|
||||||
|
"typeSchema": "public",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'minimal'"
|
||||||
|
},
|
||||||
|
"capabilities": {
|
||||||
|
"name": "capabilities",
|
||||||
|
"type": "jsonb",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "'[]'::jsonb"
|
||||||
|
},
|
||||||
|
"rate_limit_per_minute": {
|
||||||
|
"name": "rate_limit_per_minute",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 120
|
||||||
|
},
|
||||||
|
"daily_quota": {
|
||||||
|
"name": "daily_quota",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": 10000
|
||||||
|
},
|
||||||
|
"current_secret_encrypted": {
|
||||||
|
"name": "current_secret_encrypted",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"current_secret_preview": {
|
||||||
|
"name": "current_secret_preview",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"next_secret_encrypted": {
|
||||||
|
"name": "next_secret_encrypted",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"next_secret_preview": {
|
||||||
|
"name": "next_secret_preview",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"notes": {
|
||||||
|
"name": "notes",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"last_heartbeat_at": {
|
||||||
|
"name": "last_heartbeat_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"last_heartbeat_version": {
|
||||||
|
"name": "last_heartbeat_version",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"last_heartbeat_ip": {
|
||||||
|
"name": "last_heartbeat_ip",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"push_instances_instance_id_idx": {
|
||||||
|
"name": "push_instances_instance_id_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "instance_id",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": true,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
},
|
||||||
|
"push_instances_status_idx": {
|
||||||
|
"name": "push_instances_status_idx",
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"expression": "status",
|
||||||
|
"isExpression": false,
|
||||||
|
"asc": true,
|
||||||
|
"nulls": "last"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"isUnique": false,
|
||||||
|
"concurrently": false,
|
||||||
|
"method": "btree",
|
||||||
|
"with": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {
|
||||||
|
"push_instances_instance_id_unique": {
|
||||||
|
"name": "push_instances_instance_id_unique",
|
||||||
|
"nullsNotDistinct": false,
|
||||||
|
"columns": [
|
||||||
|
"instance_id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"policies": {},
|
||||||
|
"checkConstraints": {},
|
||||||
|
"isRLSEnabled": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {
|
||||||
|
"public.attempt_provider": {
|
||||||
|
"name": "attempt_provider",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"web_push",
|
||||||
|
"apns",
|
||||||
|
"fcm"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"public.attempt_status": {
|
||||||
|
"name": "attempt_status",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"pending",
|
||||||
|
"sent",
|
||||||
|
"failed",
|
||||||
|
"skipped"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"public.delivery_status": {
|
||||||
|
"name": "delivery_status",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"accepted",
|
||||||
|
"processing",
|
||||||
|
"completed",
|
||||||
|
"failed",
|
||||||
|
"partial"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"public.device_platform": {
|
||||||
|
"name": "device_platform",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"web",
|
||||||
|
"ios",
|
||||||
|
"android"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"public.device_status": {
|
||||||
|
"name": "device_status",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"active",
|
||||||
|
"disabled",
|
||||||
|
"invalid"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"public.instance_status": {
|
||||||
|
"name": "instance_status",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"active",
|
||||||
|
"blocked",
|
||||||
|
"disabled"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"public.payload_mode": {
|
||||||
|
"name": "payload_mode",
|
||||||
|
"schema": "public",
|
||||||
|
"values": [
|
||||||
|
"minimal",
|
||||||
|
"rich"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"schemas": {},
|
||||||
|
"sequences": {},
|
||||||
|
"roles": {},
|
||||||
|
"policies": {},
|
||||||
|
"views": {},
|
||||||
|
"_meta": {
|
||||||
|
"columns": {},
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
13
push-server/packages/db/drizzle/meta/_journal.json
Normal file
13
push-server/packages/db/drizzle/meta/_journal.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"idx": 0,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1779461560095,
|
||||||
|
"tag": "0000_big_devos",
|
||||||
|
"breakpoints": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
22
push-server/packages/db/package.json
Normal file
22
push-server/packages/db/package.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "@fedeo/push-db",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"main": "src/index.ts",
|
||||||
|
"scripts": {
|
||||||
|
"db:generate": "drizzle-kit generate",
|
||||||
|
"db:migrate": "drizzle-kit migrate",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"drizzle-orm": "^0.45.0",
|
||||||
|
"pg": "^8.16.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.3.0",
|
||||||
|
"@types/pg": "^8.15.5",
|
||||||
|
"drizzle-kit": "^0.31.8",
|
||||||
|
"typescript": "^5.9.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
1
push-server/packages/db/src/index.ts
Normal file
1
push-server/packages/db/src/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from "./schema.js";
|
||||||
154
push-server/packages/db/src/schema.ts
Normal file
154
push-server/packages/db/src/schema.ts
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import {
|
||||||
|
boolean,
|
||||||
|
index,
|
||||||
|
integer,
|
||||||
|
jsonb,
|
||||||
|
pgEnum,
|
||||||
|
pgTable,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
uniqueIndex,
|
||||||
|
uuid,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
import { sql } from "drizzle-orm";
|
||||||
|
|
||||||
|
export const instanceStatus = pgEnum("instance_status", ["active", "blocked", "disabled"]);
|
||||||
|
export const payloadMode = pgEnum("payload_mode", ["minimal", "rich"]);
|
||||||
|
export const devicePlatform = pgEnum("device_platform", ["web", "ios", "android"]);
|
||||||
|
export const deviceStatus = pgEnum("device_status", ["active", "disabled", "invalid"]);
|
||||||
|
export const deliveryStatus = pgEnum("delivery_status", ["accepted", "processing", "completed", "failed", "partial"]);
|
||||||
|
export const attemptStatus = pgEnum("attempt_status", ["pending", "sent", "failed", "skipped"]);
|
||||||
|
export const attemptProvider = pgEnum("attempt_provider", ["web_push", "apns", "fcm"]);
|
||||||
|
|
||||||
|
export const pushInstances = pgTable(
|
||||||
|
"push_instances",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
instanceId: text("instance_id").notNull().unique(),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
baseUrl: text("base_url").notNull(),
|
||||||
|
status: instanceStatus("status").notNull().default("active"),
|
||||||
|
mode: payloadMode("payload_mode").notNull().default("minimal"),
|
||||||
|
capabilities: jsonb("capabilities").$type<string[]>().notNull().default(sql`'[]'::jsonb`),
|
||||||
|
rateLimitPerMinute: integer("rate_limit_per_minute").notNull().default(120),
|
||||||
|
dailyQuota: integer("daily_quota").notNull().default(10000),
|
||||||
|
currentSecretEncrypted: text("current_secret_encrypted").notNull(),
|
||||||
|
currentSecretPreview: text("current_secret_preview").notNull(),
|
||||||
|
nextSecretEncrypted: text("next_secret_encrypted"),
|
||||||
|
nextSecretPreview: text("next_secret_preview"),
|
||||||
|
notes: text("notes"),
|
||||||
|
lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }),
|
||||||
|
lastHeartbeatVersion: text("last_heartbeat_version"),
|
||||||
|
lastHeartbeatIp: text("last_heartbeat_ip"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
instanceIdIdx: uniqueIndex("push_instances_instance_id_idx").on(table.instanceId),
|
||||||
|
statusIdx: index("push_instances_status_idx").on(table.status),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const pushDevices = pgTable(
|
||||||
|
"push_devices",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
centralDeviceId: text("central_device_id").notNull().unique(),
|
||||||
|
instanceId: uuid("instance_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pushInstances.id, { onDelete: "cascade" }),
|
||||||
|
localDeviceId: text("local_device_id").notNull(),
|
||||||
|
platform: devicePlatform("platform").notNull(),
|
||||||
|
status: deviceStatus("status").notNull().default("active"),
|
||||||
|
providerTokenEncrypted: text("provider_token_encrypted"),
|
||||||
|
webPushSubscription: jsonb("web_push_subscription").$type<Record<string, unknown>>(),
|
||||||
|
meta: jsonb("meta").$type<Record<string, unknown>>().notNull().default(sql`'{}'::jsonb`),
|
||||||
|
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
disabledAt: timestamp("disabled_at", { withTimezone: true }),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
centralDeviceIdIdx: uniqueIndex("push_devices_central_device_id_idx").on(table.centralDeviceId),
|
||||||
|
instanceLocalDeviceIdx: uniqueIndex("push_devices_instance_local_device_idx").on(table.instanceId, table.localDeviceId),
|
||||||
|
instanceStatusIdx: index("push_devices_instance_status_idx").on(table.instanceId, table.status),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const deliveryJobs = pgTable(
|
||||||
|
"delivery_jobs",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
deliveryJobId: text("delivery_job_id").notNull().unique(),
|
||||||
|
instanceId: uuid("instance_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pushInstances.id, { onDelete: "cascade" }),
|
||||||
|
idempotencyKey: text("idempotency_key").notNull(),
|
||||||
|
status: deliveryStatus("status").notNull().default("accepted"),
|
||||||
|
priority: text("priority").notNull().default("normal"),
|
||||||
|
collapseKey: text("collapse_key"),
|
||||||
|
ttlSeconds: integer("ttl_seconds").notNull().default(3600),
|
||||||
|
acceptedCount: integer("accepted_count").notNull().default(0),
|
||||||
|
rejectedCount: integer("rejected_count").notNull().default(0),
|
||||||
|
sentCount: integer("sent_count").notNull().default(0),
|
||||||
|
failedCount: integer("failed_count").notNull().default(0),
|
||||||
|
lastErrorCode: text("last_error_code"),
|
||||||
|
lastErrorMessage: text("last_error_message"),
|
||||||
|
completedAt: timestamp("completed_at", { withTimezone: true }),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
deliveryJobIdIdx: uniqueIndex("delivery_jobs_delivery_job_id_idx").on(table.deliveryJobId),
|
||||||
|
instanceIdempotencyIdx: uniqueIndex("delivery_jobs_instance_idempotency_idx").on(table.instanceId, table.idempotencyKey),
|
||||||
|
instanceCreatedIdx: index("delivery_jobs_instance_created_idx").on(table.instanceId, table.createdAt),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const deliveryAttempts = pgTable(
|
||||||
|
"delivery_attempts",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
deliveryJobId: uuid("delivery_job_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => deliveryJobs.id, { onDelete: "cascade" }),
|
||||||
|
deviceId: uuid("device_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pushDevices.id, { onDelete: "cascade" }),
|
||||||
|
provider: attemptProvider("provider").notNull(),
|
||||||
|
status: attemptStatus("status").notNull().default("pending"),
|
||||||
|
providerMessageId: text("provider_message_id"),
|
||||||
|
errorCode: text("error_code"),
|
||||||
|
errorMessage: text("error_message"),
|
||||||
|
sentAt: timestamp("sent_at", { withTimezone: true }),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
jobIdx: index("delivery_attempts_job_idx").on(table.deliveryJobId),
|
||||||
|
deviceIdx: index("delivery_attempts_device_idx").on(table.deviceId),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const auditLogs = pgTable(
|
||||||
|
"audit_logs",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
actor: text("actor").notNull(),
|
||||||
|
action: text("action").notNull(),
|
||||||
|
instanceId: uuid("instance_id").references(() => pushInstances.id, { onDelete: "set null" }),
|
||||||
|
meta: jsonb("meta").$type<Record<string, unknown>>().notNull().default(sql`'{}'::jsonb`),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
instanceCreatedIdx: index("audit_logs_instance_created_idx").on(table.instanceId, table.createdAt),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export type PushInstance = typeof pushInstances.$inferSelect;
|
||||||
|
export type NewPushInstance = typeof pushInstances.$inferInsert;
|
||||||
|
export type PushDevice = typeof pushDevices.$inferSelect;
|
||||||
|
export type NewPushDevice = typeof pushDevices.$inferInsert;
|
||||||
|
export type DeliveryJob = typeof deliveryJobs.$inferSelect;
|
||||||
|
export type NewDeliveryJob = typeof deliveryJobs.$inferInsert;
|
||||||
|
export type DeliveryAttempt = typeof deliveryAttempts.$inferSelect;
|
||||||
|
export type NewDeliveryAttempt = typeof deliveryAttempts.$inferInsert;
|
||||||
14
push-server/packages/db/tsconfig.json
Normal file
14
push-server/packages/db/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"declaration": true,
|
||||||
|
"outDir": "dist"
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "drizzle.config.ts"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user