KI-AGENT: Zentralen Push-Server Stack ergänzen
This commit is contained in:
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user