feat: habilitar provisionamento desktop e rotas CORS

This commit is contained in:
Esdras Renan 2025-10-08 23:07:49 -03:00
parent 7569986ffc
commit 152550a9a0
19 changed files with 1806 additions and 211 deletions

View file

@ -1,4 +1,3 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"
@ -7,6 +6,7 @@ import type { Id } from "@/convex/_generated/dataModel"
import { env } from "@/lib/env"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { ensureMachineAccount } from "@/server/machines-auth"
import { createCorsPreflight, jsonWithCors } from "@/server/cors"
const registerSchema = z
.object({
@ -29,14 +29,20 @@ const registerSchema = z
{ message: "Informe ao menos um MAC address ou número de série" }
)
const CORS_METHODS = "POST, OPTIONS"
export async function OPTIONS(request: Request) {
return createCorsPreflight(request.headers.get("origin"), CORS_METHODS)
}
export async function POST(request: Request) {
if (request.method !== "POST") {
return NextResponse.json({ error: "Método não permitido" }, { status: 405 })
return jsonWithCors({ error: "Método não permitido" }, 405, request.headers.get("origin"), CORS_METHODS)
}
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
if (!convexUrl) {
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
return jsonWithCors({ error: "Convex não configurado" }, 500, request.headers.get("origin"), CORS_METHODS)
}
let payload
@ -44,7 +50,12 @@ export async function POST(request: Request) {
const raw = await request.json()
payload = registerSchema.parse(raw)
} catch (error) {
return NextResponse.json({ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) }, { status: 400 })
return jsonWithCors(
{ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) },
400,
request.headers.get("origin"),
CORS_METHODS
)
}
const client = new ConvexHttpClient(convexUrl)
@ -75,7 +86,7 @@ export async function POST(request: Request) {
authEmail: account.authEmail,
})
return NextResponse.json(
return jsonWithCors(
{
machineId: registration.machineId,
tenantId: registration.tenantId,
@ -85,10 +96,12 @@ export async function POST(request: Request) {
machineEmail: account.authEmail,
expiresAt: registration.expiresAt,
},
{ status: 201 }
{ status: 201 },
request.headers.get("origin"),
CORS_METHODS
)
} catch (error) {
console.error("[machines.register] Falha no provisionamento", error)
return NextResponse.json({ error: "Falha ao provisionar máquina" }, { status: 500 })
return jsonWithCors({ error: "Falha ao provisionar máquina" }, 500, request.headers.get("origin"), CORS_METHODS)
}
}