feat(vpn): intégration Tailscale/Headscale + URLs publiques par sous-domaine
- Ajout d'un conteneur Tailscale côté serveur pour joindre les agents via IPs Tailscale - Configuration Headscale exposé en HTTPS via Caddy (headscale.alfrednobel.edudeploy.com) - Caddy configuré pour les sous-domaines avec TLS on-demand - Middleware et route proxy Next.js pour router les sous-domaines vers les agents - Ajout du champ domain sur Establishment et affichage de l'URL publique dans le dashboard - Agent Windows v0.2.3 avec proxy Tailscale par instance pour contourner Docker Desktop - Templates WordPress/PrestaShop bindés sur 0.0.0.0 pour être accessibles via Tailscale
This commit is contained in:
@@ -5,5 +5,6 @@ COPY package.json package-lock.json* ./
|
||||
COPY prisma ./prisma
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
CMD ["node_modules/.bin/next", "start"]
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const MAIN_DOMAIN = process.env.MAIN_DOMAIN || "alfrednobel.edudeploy.com";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const domain = searchParams.get("domain");
|
||||
|
||||
if (!domain) {
|
||||
return NextResponse.json({ ok: false }, { status: 400 });
|
||||
}
|
||||
|
||||
if (domain === MAIN_DOMAIN || domain === `headscale.${MAIN_DOMAIN}`) {
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
if (!domain.endsWith(`.${MAIN_DOMAIN}`)) {
|
||||
return NextResponse.json({ ok: false }, { status: 400 });
|
||||
}
|
||||
|
||||
const subdomain = domain.replace(`.${MAIN_DOMAIN}`, "");
|
||||
const instance = await prisma.instance.findUnique({
|
||||
where: { id: subdomain },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: !!instance });
|
||||
}
|
||||
@@ -18,10 +18,37 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
const instances = await prisma.instance.findMany({
|
||||
where,
|
||||
include: { node: { include: { student: { include: { class: true } } } }, template: true },
|
||||
include: {
|
||||
node: {
|
||||
include: {
|
||||
student: {
|
||||
include: {
|
||||
class: {
|
||||
include: {
|
||||
establishment: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
template: true,
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(instances);
|
||||
|
||||
const enriched = instances.map((inst) => {
|
||||
const domain = inst.node.student?.class.establishment?.domain;
|
||||
const publicUrl = domain
|
||||
? `https://${inst.id}.${domain}`
|
||||
: null;
|
||||
return {
|
||||
...inst,
|
||||
publicUrl,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json(enriched);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -35,12 +62,24 @@ export async function POST(req: NextRequest) {
|
||||
data: { nodeId, templateId, port: port || 8080, status: "stopped" },
|
||||
});
|
||||
|
||||
const node = await prisma.node.findUnique({
|
||||
where: { id: nodeId },
|
||||
include: { student: { include: { class: { include: { establishment: true } } } } },
|
||||
});
|
||||
|
||||
const domain = node?.student?.class.establishment?.domain;
|
||||
const publicUrl = domain ? `https://${instance.id}.${domain}` : null;
|
||||
|
||||
const sent = sendToNode(nodeId, {
|
||||
action: "start",
|
||||
instanceId: instance.id,
|
||||
type: template.type,
|
||||
port: instance.port,
|
||||
composeConfig: template.composeConfig.replace(/{PORT}/g, String(instance.port)).replace(/{INSTANCE_ID}/g, instance.id),
|
||||
composeConfig: template.composeConfig
|
||||
.replace(/{PORT}/g, String(instance.port))
|
||||
.replace(/{INSTANCE_ID}/g, instance.id)
|
||||
.replace(/{PUBLIC_URL}/g, publicUrl || `http://localhost:${instance.port}`)
|
||||
.replace(/{PUBLIC_DOMAIN}/g, domain || "localhost"),
|
||||
});
|
||||
|
||||
if (!sent) {
|
||||
@@ -53,9 +92,12 @@ export async function POST(req: NextRequest) {
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { id, action } = body;
|
||||
const instance = await prisma.instance.findUnique({ where: { id }, include: { template: true } });
|
||||
const instance = await prisma.instance.findUnique({ where: { id }, include: { template: true, node: { include: { student: { include: { class: { include: { establishment: true } } } } } } } });
|
||||
if (!instance) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const domain = instance.node.student?.class.establishment?.domain;
|
||||
const publicUrl = domain ? `https://${instance.id}.${domain}` : null;
|
||||
|
||||
if (action === "stop") {
|
||||
sendToNode(instance.nodeId, { action: "stop", instanceId: instance.id });
|
||||
await prisma.instance.update({ where: { id }, data: { status: "stopped" } });
|
||||
@@ -65,7 +107,11 @@ export async function PATCH(req: NextRequest) {
|
||||
instanceId: instance.id,
|
||||
type: instance.template.type,
|
||||
port: instance.port,
|
||||
composeConfig: instance.template.composeConfig.replace(/{PORT}/g, String(instance.port)).replace(/{INSTANCE_ID}/g, instance.id),
|
||||
composeConfig: instance.template.composeConfig
|
||||
.replace(/{PORT}/g, String(instance.port))
|
||||
.replace(/{INSTANCE_ID}/g, instance.id)
|
||||
.replace(/{PUBLIC_URL}/g, publicUrl || `http://localhost:${instance.port}`)
|
||||
.replace(/{PUBLIC_DOMAIN}/g, domain || "localhost"),
|
||||
});
|
||||
if (!sent) await prisma.instance.update({ where: { id }, data: { status: "error" } });
|
||||
} else if (action === "reset") {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const MAIN_DOMAIN = process.env.MAIN_DOMAIN || "alfrednobel.edudeploy.com";
|
||||
|
||||
async function proxyRequest(req: NextRequest) {
|
||||
const host = req.headers.get("host") || "";
|
||||
const cleanHost = host.split(":")[0];
|
||||
|
||||
if (!cleanHost.endsWith(`.${MAIN_DOMAIN}`)) {
|
||||
return NextResponse.json({ error: "Invalid host" }, { status: 404 });
|
||||
}
|
||||
|
||||
const subdomain = cleanHost.replace(`.${MAIN_DOMAIN}`, "");
|
||||
|
||||
const instance = await prisma.instance.findUnique({
|
||||
where: { id: subdomain },
|
||||
include: { node: true },
|
||||
});
|
||||
|
||||
if (!instance || !instance.node?.tailscaleIp) {
|
||||
return NextResponse.json(
|
||||
{ error: "Instance not found or not connected" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const targetUrl = new URL(req.url);
|
||||
const upstream = `http://${instance.node.tailscaleIp}:${instance.port}${targetUrl.pathname}${targetUrl.search}`;
|
||||
|
||||
const headers = new Headers(req.headers);
|
||||
headers.delete("host");
|
||||
headers.set("host", cleanHost);
|
||||
|
||||
const upstreamRes = await fetch(upstream, {
|
||||
method: req.method,
|
||||
headers,
|
||||
body:
|
||||
req.method !== "GET" && req.method !== "HEAD"
|
||||
? (req.body as BodyInit)
|
||||
: undefined,
|
||||
redirect: "manual",
|
||||
});
|
||||
|
||||
const responseHeaders = new Headers(upstreamRes.headers);
|
||||
// Remove content-encoding because Next.js/fetch handles decompression automatically
|
||||
responseHeaders.delete("content-encoding");
|
||||
responseHeaders.delete("content-length");
|
||||
|
||||
return new Response(upstreamRes.body, {
|
||||
status: upstreamRes.status,
|
||||
statusText: upstreamRes.statusText,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
export const GET = proxyRequest;
|
||||
export const POST = proxyRequest;
|
||||
export const PUT = proxyRequest;
|
||||
export const PATCH = proxyRequest;
|
||||
export const DELETE = proxyRequest;
|
||||
export const HEAD = proxyRequest;
|
||||
export const OPTIONS = proxyRequest;
|
||||
@@ -21,10 +21,18 @@ export default async function InstancesPage() {
|
||||
where: establishmentId
|
||||
? { node: { student: { class: { establishmentId } } } }
|
||||
: {},
|
||||
include: { node: { include: { student: { include: { class: true } } } }, template: true },
|
||||
include: { node: { include: { student: { include: { class: { include: { establishment: true } } } } } }, template: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
const enrichedInstances = instances.map((inst) => {
|
||||
const domain = inst.node.student?.class.establishment?.domain;
|
||||
return {
|
||||
...inst,
|
||||
publicUrl: domain ? `https://${inst.id}.${domain}` : null,
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -44,11 +52,12 @@ export default async function InstancesPage() {
|
||||
<TableHead>Étudiant</TableHead>
|
||||
<TableHead>Port</TableHead>
|
||||
<TableHead>Statut</TableHead>
|
||||
<TableHead>URL publique</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{instances.map((inst) => (
|
||||
{enrichedInstances.map((inst: any) => (
|
||||
<TableRow key={inst.id}>
|
||||
<TableCell className="font-medium">{inst.id.slice(0, 8)}...</TableCell>
|
||||
<TableCell>{inst.template.name}</TableCell>
|
||||
@@ -58,6 +67,9 @@ export default async function InstancesPage() {
|
||||
<TableCell>
|
||||
<Badge variant={inst.status === "running" ? "success" : inst.status === "error" ? "destructive" : "secondary"}>{inst.status}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{inst.publicUrl ? <a href={inst.publicUrl} target="_blank" rel="noopener" className="text-blue-600 hover:underline">{inst.publicUrl}</a> : "-"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<InstanceActions instanceId={inst.id} status={inst.status} />
|
||||
</TableCell>
|
||||
@@ -65,7 +77,7 @@ export default async function InstancesPage() {
|
||||
))}
|
||||
{instances.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="text-center text-muted-foreground">Aucune instance</TableCell>
|
||||
<TableCell colSpan={8} className="text-center text-muted-foreground">Aucune instance</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
|
||||
@@ -11,6 +11,7 @@ interface NodeMessage {
|
||||
composeConfig?: string;
|
||||
studentName?: string;
|
||||
error?: string;
|
||||
tailscaleIp?: string;
|
||||
}
|
||||
|
||||
const nodes = new Map<string, WebSocket>();
|
||||
@@ -66,6 +67,15 @@ export function initWebSocketServer(wss: WebSocketServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.action === "tailscale_ip" && nodeId && msg.tailscaleIp) {
|
||||
await prisma.node.update({
|
||||
where: { id: nodeId },
|
||||
data: { tailscaleIp: msg.tailscaleIp },
|
||||
});
|
||||
console.log("[WS] Tailscale IP updated for", nodeId, ":", msg.tailscaleIp);
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.action === "instance_started" && msg.instanceId) {
|
||||
await prisma.instance.update({
|
||||
where: { id: msg.instanceId },
|
||||
|
||||
+19
-26
@@ -1,35 +1,28 @@
|
||||
import { withAuth } from "next-auth/middleware";
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export default withAuth(
|
||||
function middleware(req) {
|
||||
const { pathname } = req.nextUrl;
|
||||
const role = req.nextauth.token?.role as string;
|
||||
const MAIN_DOMAIN = process.env.MAIN_DOMAIN || "alfrednobel.edudeploy.com";
|
||||
|
||||
if (pathname.startsWith("/superadmin")) {
|
||||
if (role !== "superadmin") {
|
||||
return NextResponse.redirect(new URL("/dashboard", req.url));
|
||||
}
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/dashboard")) {
|
||||
if (!role || (role !== "admin" && role !== "teacher" && role !== "superadmin")) {
|
||||
return NextResponse.redirect(new URL("/login", req.url));
|
||||
}
|
||||
}
|
||||
export function middleware(req: NextRequest) {
|
||||
const host = req.headers.get("host") || "";
|
||||
const cleanHost = host.split(":")[0];
|
||||
|
||||
if (cleanHost === MAIN_DOMAIN || cleanHost === `www.${MAIN_DOMAIN}`) {
|
||||
return NextResponse.next();
|
||||
},
|
||||
{
|
||||
callbacks: {
|
||||
authorized({ req, token }) {
|
||||
if (req.nextUrl.pathname.startsWith("/login")) return true;
|
||||
return !!token;
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!cleanHost.endsWith(`.${MAIN_DOMAIN}`)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
const pathname = req.nextUrl.pathname;
|
||||
const search = req.nextUrl.search;
|
||||
|
||||
// Rewrite to the internal proxy API while preserving the original host header
|
||||
const rewriteUrl = new URL(`/api/proxy${pathname}${search}`, req.url);
|
||||
return NextResponse.rewrite(rewriteUrl);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/dashboard/:path*", "/superadmin/:path*", "/api/protected/:path*"],
|
||||
matcher: ["/((?!api/proxy|_next|static|favicon.ico|.*\\.).*)"],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Establishment" ADD COLUMN "domain" TEXT;
|
||||
@@ -11,6 +11,7 @@ model Establishment {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String @unique
|
||||
domain String?
|
||||
createdAt DateTime @default(now())
|
||||
subscription Subscription?
|
||||
users User[]
|
||||
|
||||
@@ -102,14 +102,14 @@ async function main() {
|
||||
WORDPRESS_DB_PASSWORD: ${t.dbPassword}
|
||||
WORDPRESS_DB_PREFIX: wp_
|
||||
WORDPRESS_CONFIG_EXTRA: |
|
||||
define('WP_HOME', 'http://localhost:{PORT}');
|
||||
define('WP_SITEURL', 'http://localhost:{PORT}');
|
||||
define('WP_HOME', '{PUBLIC_URL}');
|
||||
define('WP_SITEURL', '{PUBLIC_URL}');
|
||||
PS_DB_HOST: ${dbHost}:${dbPort}
|
||||
PS_DB_NAME: ${t.dbName}
|
||||
PS_DB_USER: ${t.dbUser}
|
||||
PS_DB_PASSWORD: ${t.dbPassword}
|
||||
PS_DB_PREFIX: ps_
|
||||
PS_DOMAIN: localhost:{PORT}
|
||||
PS_DOMAIN: {PUBLIC_DOMAIN}
|
||||
PS_SHOP_NAME: ${t.name}
|
||||
PS_INSTALL_AUTO: "0"
|
||||
INSTANCE_ID: {INSTANCE_ID}
|
||||
|
||||
Reference in New Issue
Block a user