chahinebrini 677b67902b feat(devices): protected device enrollment + mobileconfig generator
Backend:
- ProtectedDevice prisma model + migration add_protected_devices
- DB helpers: list/count/get/create/confirm/revoke
- mobileconfig.ts utility — XML-escape, unique UUIDs per request
- 5 endpoints under /api/devices/* (avoid /api/devices conflict with existing
  Capacitor UserDevice route by using /api/devices/protected for list)

Phase 1: backend ready. DoH-server token-routing comes in phase 2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 04:06:49 +02:00

77 lines
2.2 KiB
TypeScript

import { randomBytes } from "crypto";
import { getProfile } from "../../db/profile";
import {
countActiveProtectedDevices,
createProtectedDevice,
} from "../../db/protectedDevices";
/**
* POST /api/devices/enroll
*
* Legend-only. User klickt "Mac hinzufügen" in der App.
* Legt ein ProtectedDevice (status=pending) an und gibt die Download-URL
* für das mobileconfig-Profil zurück.
*
* Body: { platform: "mac" | "windows" | "ios" | "android", label: string }
* Response: { deviceId, dnsToken, downloadUrl }
*/
export default defineEventHandler(async (event) => {
const user = await requireUser(event);
const profile = await getProfile(user.id);
if (profile?.plan !== "legend") {
throw createError({
statusCode: 403,
data: { error: "LEGEND_REQUIRED" },
});
}
const body = await readBody(event);
const platform = body?.platform as string | undefined;
const label = body?.label as string | undefined;
const VALID_PLATFORMS = ["mac", "windows", "ios", "android"];
if (!platform || !VALID_PLATFORMS.includes(platform)) {
throw createError({
statusCode: 400,
data: { error: "INVALID_PLATFORM", validValues: VALID_PLATFORMS },
});
}
if (!label || typeof label !== "string" || label.trim().length === 0) {
throw createError({ statusCode: 400, data: { error: "LABEL_REQUIRED" } });
}
const trimmedLabel = label.trim().slice(0, 100);
// Limit: max 3 active+pending Devices
const activeCount = await countActiveProtectedDevices(user.id);
if (activeCount >= 3) {
throw createError({
statusCode: 409,
data: { error: "DEVICE_LIMIT_REACHED", max: 3, current: activeCount },
});
}
// 32-char hex token — kryptografisch sicher
const dnsToken = randomBytes(16).toString("hex");
const device = await createProtectedDevice({
userId: user.id,
dnsToken,
platform,
label: trimmedLabel,
});
const config = useRuntimeConfig(event);
const apiBase =
(config.public as any)?.apiBase ?? "https://api.rebreak.org";
return {
success: true,
data: {
deviceId: device.id,
dnsToken: device.dnsToken,
downloadUrl: `${apiBase}/api/devices/${device.id}/profile.mobileconfig`,
},
};
});