feat(agent): v0.3.5 Windows inbound forwarding, UI actions, lifecycle

- Configure tailscale serve automatically for each instance on Windows userspace networking.
- Add local UI buttons: start/stop/reset/delete instances (stop/start preserve volumes).
- Clean shutdown: stop tailscaled and instances, notify server with instance_stopped.
- Restart tailscaled on agent boot using persisted state when pre-auth key is absent.
- Sync instance stopped/deleted status to dashboard (server/lib/websocket.ts).
- Security: include prior authz/scoping changes across API routes, ephemeral pre-auth keys, ACL policy, internal API key.
- Update SUIVI_VPN_ONDEMAND.md and docs/ONBOARDING_CLIENT.md.
- Bump agent version to 0.3.5.
This commit is contained in:
EduBox Dev
2026-06-25 22:59:09 +00:00
parent 331187e9b5
commit a414f03a59
33 changed files with 3075 additions and 340 deletions
+22 -4
View File
@@ -1,13 +1,20 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth, requireRole, getScopedEstablishmentId, forbidden } from "@/lib/api-auth";
export async function GET(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
if (!establishmentId) return NextResponse.json({ error: "Missing establishmentId" }, { status: 400 });
const requestedId = searchParams.get("establishmentId");
const establishmentId = getScopedEstablishmentId(user, requestedId);
if (establishmentId instanceof NextResponse) return establishmentId;
const where = establishmentId ? { establishmentId } : {};
const classes = await prisma.class.findMany({
where: { establishmentId },
where,
include: { _count: { select: { students: true } } },
orderBy: { createdAt: "desc" },
});
@@ -15,8 +22,19 @@ export async function GET(req: NextRequest) {
}
export async function POST(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin", "admin");
if (denied) return denied;
const body = await req.json();
const { establishmentId, name, level } = body;
const requestedId = body.establishmentId;
const establishmentId = getScopedEstablishmentId(user, requestedId);
if (establishmentId instanceof NextResponse) return establishmentId;
if (!establishmentId) return forbidden();
const { name, level } = body;
const cls = await prisma.class.create({
data: { establishmentId, name, level },
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
const AGENT_VERSION = "0.3.0";
const AGENT_VERSION = "0.3.4";
const AGENT_BIN_NAME = "studioE5-agent";
export async function GET() {
+12
View File
@@ -1,9 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";
import { requireAuth, requireRole } from "@/lib/api-auth";
export async function GET() {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const where = user.role === "superadmin" ? {} : { id: user.establishmentId };
const establishments = await prisma.establishment.findMany({
where,
include: { subscription: true, _count: { select: { users: true, classes: true } } },
orderBy: { createdAt: "desc" },
});
@@ -11,6 +17,12 @@ export async function GET() {
}
export async function POST(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin");
if (denied) return denied;
const body = await req.json();
const { name, slug, adminEmail, adminPassword } = body;
+88 -16
View File
@@ -1,16 +1,54 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { prisma } from "@/lib/prisma";
import { sendToNode } from "@/lib/websocket";
import { authOptions } from "@/lib/auth-config";
async function requireAuth() {
const session = await getServerSession(authOptions);
if (!session?.user) return null;
return session.user as { id: string; email: string; role: string; establishmentId?: string };
}
function userCanAccessNode(user: { role: string; establishmentId?: string }, node: any) {
if (user.role === "superadmin") return true;
const establishmentId = node?.student?.class?.establishmentId;
return establishmentId && establishmentId === user.establishmentId;
}
function userCanAccessInstance(user: { role: string; establishmentId?: string }, instance: any) {
if (user.role === "superadmin") return true;
const establishmentId = instance?.node?.student?.class?.establishmentId;
return establishmentId && establishmentId === user.establishmentId;
}
export async function GET(req: NextRequest) {
const user = await requireAuth();
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { searchParams } = new URL(req.url);
const nodeId = searchParams.get("nodeId");
const establishmentId = searchParams.get("establishmentId");
const establishmentIdParam = searchParams.get("establishmentId");
let where: any = {};
if (nodeId) where.nodeId = nodeId;
if (establishmentId) {
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
if (user.role !== "superadmin") {
const classes = await prisma.class.findMany({
where: { establishmentId: user.establishmentId },
select: { id: true },
});
const students = await prisma.student.findMany({
where: { classId: { in: classes.map((c) => c.id) } },
select: { id: true },
});
const nodes = await prisma.node.findMany({
where: { studentId: { in: students.map((s) => s.id) } },
select: { id: true },
});
where.nodeId = { in: nodes.map((n) => n.id) };
} else if (establishmentIdParam) {
const classes = await prisma.class.findMany({ where: { establishmentId: establishmentIdParam }, select: { id: true } });
const students = await prisma.student.findMany({ where: { classId: { in: classes.map((c) => c.id) } }, select: { id: true } });
const nodes = await prisma.node.findMany({ where: { studentId: { in: students.map((s) => s.id) } }, select: { id: true } });
where.nodeId = { in: nodes.map((n) => n.id) };
@@ -39,12 +77,8 @@ export async function GET(req: NextRequest) {
const enriched = instances.map((inst) => {
const domain = inst.node.student?.class.establishment?.domain;
const publicUrl = domain
? `https://${inst.id}.${domain}`
: null;
const localUrl = inst.node.tailscaleIp
? `http://${inst.node.tailscaleIp}:${inst.port}`
: null;
const publicUrl = domain ? `https://${inst.id}.${domain}` : null;
const localUrl = inst.node.tailscaleIp ? `http://${inst.node.tailscaleIp}:${inst.port}` : null;
return {
...inst,
publicUrl,
@@ -56,22 +90,32 @@ export async function GET(req: NextRequest) {
}
export async function POST(req: NextRequest) {
const user = await requireAuth();
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const body = await req.json();
const { nodeId, templateId, port } = body;
if (!nodeId || !templateId) {
return NextResponse.json({ error: "Missing nodeId or templateId" }, { status: 400 });
}
const template = await prisma.template.findUnique({ where: { id: templateId } });
if (!template) return NextResponse.json({ error: "Template not found" }, { status: 404 });
const instance = await prisma.instance.create({
data: { nodeId, templateId, port: port || 8080, status: "stopped" },
});
const node = await prisma.node.findUnique({
where: { id: nodeId },
include: { student: { include: { class: { include: { establishment: true } } } } },
});
if (!node) return NextResponse.json({ error: "Node not found" }, { status: 404 });
if (!userCanAccessNode(user, node)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const domain = node?.student?.class.establishment?.domain;
const instance = await prisma.instance.create({
data: { nodeId, templateId, port: port || 8080, status: "stopped" },
});
const domain = node.student?.class.establishment?.domain;
const publicDomain = domain ? `${instance.id}.${domain}` : "localhost";
const publicUrl = domain ? `https://${publicDomain}` : null;
const sent = sendToNode(nodeId, {
@@ -94,14 +138,28 @@ export async function POST(req: NextRequest) {
}
export async function PATCH(req: NextRequest) {
const user = await requireAuth();
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const body = await req.json();
const { id, action } = body;
const instance = await prisma.instance.findUnique({ where: { id }, include: { template: true, node: { include: { student: { include: { class: { include: { establishment: true } } } } } } } });
if (!id || !action) {
return NextResponse.json({ error: "Missing id or action" }, { status: 400 });
}
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 });
if (!userCanAccessInstance(user, instance)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const domain = instance.node.student?.class.establishment?.domain;
const publicDomain = domain ? `${instance.id}.${domain}` : "localhost";
const publicUrl = domain ? `https://${publicDomain}` : null;
if (action === "stop") {
sendToNode(instance.nodeId, { action: "delete", instanceId: instance.id });
await prisma.instance.update({ where: { id }, data: { status: "stopped" } });
@@ -131,16 +189,30 @@ export async function PATCH(req: NextRequest) {
.replace(/{PUBLIC_DOMAIN}/g, "localhost"),
});
if (!sent) await prisma.instance.update({ where: { id }, data: { status: "error" } });
} else {
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}
return NextResponse.json({ ok: true });
}
export async function DELETE(req: NextRequest) {
const user = await requireAuth();
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
const instance = await prisma.instance.findUnique({ where: { id } });
const instance = await prisma.instance.findUnique({
where: { id },
include: { node: { include: { student: { include: { class: { include: { establishment: true } } } } } } },
});
if (!instance) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!userCanAccessInstance(user, instance)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
if (instance) sendToNode(instance.nodeId, { action: "delete", instanceId: instance.id });
await prisma.instance.delete({ where: { id } });
return NextResponse.json({ ok: true });
@@ -1,7 +1,22 @@
import { NextRequest, NextResponse } from "next/server";
import { sendToNode } from "@/lib/websocket";
function getBearerToken(req: NextRequest): string | null {
const auth = req.headers.get("authorization") || "";
const match = auth.match(/^Bearer\s+(\S+)$/i);
return match ? match[1] : null;
}
export async function POST(req: NextRequest) {
const apiKey = process.env.INTERNAL_API_KEY;
if (!apiKey) {
return NextResponse.json({ error: "Internal API key not configured" }, { status: 500 });
}
const token = getBearerToken(req);
if (!token || token !== apiKey) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await req.json();
const { nodeId, message } = body;
if (!nodeId || !message) {
+7 -1
View File
@@ -1,9 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth, getScopedEstablishmentId, forbidden } from "@/lib/api-auth";
export async function GET(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
const requestedId = searchParams.get("establishmentId");
const establishmentId = getScopedEstablishmentId(user, requestedId);
if (establishmentId instanceof NextResponse) return establishmentId;
let where: any = {};
if (establishmentId) {
+15
View File
@@ -1,7 +1,22 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
function getBearerToken(req: NextRequest): string | null {
const auth = req.headers.get("authorization") || "";
const match = auth.match(/^Bearer\s+(\S+)$/i);
return match ? match[1] : null;
}
export async function GET(req: NextRequest) {
const apiKey = process.env.INTERNAL_API_KEY;
if (!apiKey) {
return NextResponse.json({ error: "Internal API key not configured" }, { status: 500 });
}
const token = getBearerToken(req);
if (!token || token !== apiKey) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { searchParams } = new URL(req.url);
const subdomain = searchParams.get("subdomain");
+4 -8
View File
@@ -1,12 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
function generateCode(length = 6) {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code = "";
for (let i = 0; i < length; i++) code += chars.charAt(Math.floor(Math.random() * chars.length));
return code;
}
import { generateUniqueActivationCode } from "@/lib/activation";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
@@ -31,13 +25,15 @@ export async function GET(req: NextRequest) {
export async function POST(req: NextRequest) {
const body = await req.json();
const { classId, firstName, lastName, email } = body;
const { code, expiresAt } = await generateUniqueActivationCode();
const student = await prisma.student.create({
data: {
classId,
firstName,
lastName,
email,
activationCode: generateCode(),
activationCode: code,
activationCodeExpiresAt: expiresAt,
},
});
return NextResponse.json(student, { status: 201 });
+63 -8
View File
@@ -1,25 +1,57 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth, requireRole, forbidden } from "@/lib/api-auth";
function templateAccessWhere(user: { role: string; establishmentId?: string }, establishmentId?: string | null) {
if (user.role === "superadmin" && establishmentId) {
return { OR: [{ isPublic: true }, { establishmentId }] };
}
if (user.establishmentId) {
return { OR: [{ isPublic: true }, { establishmentId: user.establishmentId }] };
}
return { isPublic: true };
}
async function canManageTemplate(user: { role: string; establishmentId?: string }, id: string) {
if (user.role === "superadmin") return true;
const template = await prisma.template.findUnique({ where: { id } });
if (!template) return false;
return template.establishmentId === user.establishmentId;
}
export async function GET(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
const requestedEst = searchParams.get("establishmentId");
const where = user.role === "superadmin" && !requestedEst ? {} : templateAccessWhere(user, requestedEst);
const templates = await prisma.template.findMany({
where: {
OR: [
{ isPublic: true },
...(establishmentId ? [{ establishmentId }] : []),
],
},
where,
orderBy: { createdAt: "desc" },
});
return NextResponse.json(templates);
}
export async function POST(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin", "admin");
if (denied) return denied;
const body = await req.json();
const { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
let { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
if (user.role !== "superadmin") {
if (establishmentId && establishmentId !== user.establishmentId) {
return forbidden();
}
establishmentId = user.establishmentId;
}
const template = await prisma.template.create({
data: { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy },
});
@@ -27,16 +59,39 @@ export async function POST(req: NextRequest) {
}
export async function PUT(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin", "admin");
if (denied) return denied;
const body = await req.json();
const { id, ...data } = body;
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
if (!(await canManageTemplate(user, id))) return forbidden();
if (user.role !== "superadmin" && data.establishmentId && data.establishmentId !== user.establishmentId) {
return forbidden();
}
const template = await prisma.template.update({ where: { id }, data });
return NextResponse.json(template);
}
export async function DELETE(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin", "admin");
if (denied) return denied;
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
if (!(await canManageTemplate(user, id))) return forbidden();
await prisma.template.delete({ where: { id } });
return NextResponse.json({ ok: true });
}
+47 -3
View File
@@ -1,14 +1,25 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";
import { requireAuth, requireRole, forbidden } from "@/lib/api-auth";
export async function GET(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
const role = searchParams.get("role");
if (user.role !== "superadmin") {
if (establishmentId && establishmentId !== user.establishmentId) {
return forbidden();
}
}
const where: any = {};
if (establishmentId) where.establishmentId = establishmentId;
else if (user.role !== "superadmin") where.establishmentId = user.establishmentId;
if (role) where.role = role;
const users = await prisma.user.findMany({
@@ -19,23 +30,56 @@ export async function GET(req: NextRequest) {
}
export async function POST(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin", "admin");
if (denied) return denied;
const body = await req.json();
const { email, password, role, establishmentId } = body;
const user = await prisma.user.create({
if (!email || !password || !role) {
return NextResponse.json({ error: "Missing email, password or role" }, { status: 400 });
}
if (user.role === "admin") {
if (role === "superadmin") return forbidden();
if (establishmentId && establishmentId !== user.establishmentId) return forbidden();
}
const finalEstablishmentId = user.role === "superadmin" ? establishmentId : user.establishmentId;
const newUser = await prisma.user.create({
data: {
email,
password: await hashPassword(password),
role,
establishmentId,
establishmentId: finalEstablishmentId,
},
});
return NextResponse.json(user, { status: 201 });
return NextResponse.json(newUser, { status: 201 });
}
export async function DELETE(req: NextRequest) {
const user = await requireAuth();
if (user instanceof NextResponse) return user;
const denied = requireRole(user, "superadmin", "admin");
if (denied) return denied;
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
const target = await prisma.user.findUnique({ where: { id } });
if (!target) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (user.role === "admin") {
if (target.role === "superadmin") return forbidden();
if (target.establishmentId !== user.establishmentId) return forbidden();
}
await prisma.user.delete({ where: { id } });
return NextResponse.json({ ok: true });
}
+3 -10
View File
@@ -3,17 +3,9 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { generateUniqueActivationCode } from "@/lib/activation";
import { redirect } from "next/navigation";
function generateCode(): string {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code = "";
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
export async function deleteStudent(formData: FormData) {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
@@ -54,9 +46,10 @@ export async function generateActivationCodeAction(formData: FormData) {
if (!student) return;
const { code, expiresAt } = await generateUniqueActivationCode();
await prisma.student.update({
where: { id },
data: { activationCode: generateCode() },
data: { activationCode: code, activationCodeExpiresAt: expiresAt },
});
redirect(`/dashboard/students/${id}`);
+4 -10
View File
@@ -1,6 +1,7 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { generateUniqueActivationCode } from "@/lib/activation";
import { redirect } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
@@ -17,15 +18,6 @@ const schema = z.object({
classId: z.string().min(1),
});
function generateActivationCode(): string {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code = "";
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
async function createStudent(formData: FormData) {
"use server";
const session = await getServerSession(authOptions);
@@ -35,13 +27,15 @@ async function createStudent(formData: FormData) {
const parsed = schema.safeParse(Object.fromEntries(formData));
if (!parsed.success) return;
const { code, expiresAt } = await generateUniqueActivationCode();
await prisma.student.create({
data: {
firstName: parsed.data.firstName,
lastName: parsed.data.lastName,
email: parsed.data.email,
classId: parsed.data.classId,
activationCode: generateActivationCode(),
activationCode: code,
activationCodeExpiresAt: expiresAt,
},
});
+25
View File
@@ -0,0 +1,25 @@
import { randomBytes } from "crypto";
import { prisma } from "./prisma";
const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const CODE_LENGTH = 6;
const CODE_TTL_MINUTES = 60;
export function generateActivationCode(): { code: string; expiresAt: Date } {
let code = "";
const bytes = randomBytes(CODE_LENGTH);
for (let i = 0; i < CODE_LENGTH; i++) {
code += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
}
const expiresAt = new Date(Date.now() + CODE_TTL_MINUTES * 60 * 1000);
return { code, expiresAt };
}
export async function generateUniqueActivationCode(retries = 5): Promise<{ code: string; expiresAt: Date }> {
for (let i = 0; i < retries; i++) {
const { code, expiresAt } = generateActivationCode();
const existing = await prisma.student.findUnique({ where: { activationCode: code } });
if (!existing) return { code, expiresAt };
}
throw new Error("Failed to generate a unique activation code");
}
+39
View File
@@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "./auth-config";
export type ApiUser = {
id: string;
email: string;
role: "superadmin" | "admin" | "teacher";
establishmentId?: string;
};
export async function requireAuth(): Promise<ApiUser | NextResponse> {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
return session.user as ApiUser;
}
export function requireRole(user: ApiUser, ...allowed: string[]): NextResponse | null {
if (!allowed.includes(user.role)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
return null;
}
export function forbidden(): NextResponse {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
export function getScopedEstablishmentId(user: ApiUser, requested?: string | null): string | undefined | NextResponse {
if (user.role === "superadmin") {
return requested ?? undefined;
}
if (requested && requested !== user.establishmentId) {
return forbidden();
}
return user.establishmentId;
}
+75
View File
@@ -0,0 +1,75 @@
interface HeadscaleUser {
id: string;
name: string;
}
interface HeadscalePreAuthKey {
key: string;
expiration: string;
aclTags: string[];
}
export async function getHeadscaleUserId(
baseUrl: string,
apiKey: string,
userName: string
): Promise<string> {
const res = await fetch(
`${baseUrl}/api/v1/user?name=${encodeURIComponent(userName)}`,
{
headers: { Authorization: `Bearer ${apiKey}` },
}
);
if (!res.ok) {
throw new Error(
`Headscale list users failed: ${res.status} ${await res.text()}`
);
}
const data = (await res.json()) as { users: HeadscaleUser[] };
const user = data.users.find((u) => u.name === userName);
if (!user) {
throw new Error(`Headscale user not found: ${userName}`);
}
return user.id;
}
export async function createEphemeralPreAuthKey(
baseUrl: string,
apiKey: string,
userId: string,
options: {
expirationMinutes?: number;
aclTags?: string[];
} = {}
): Promise<string> {
const expirationMinutes = options.expirationMinutes ?? 15;
const aclTags = options.aclTags ?? [];
const expiration = new Date(
Date.now() + expirationMinutes * 60 * 1000
).toISOString();
const res = await fetch(`${baseUrl}/api/v1/preauthkey`, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
user: userId,
reusable: false,
ephemeral: false,
expiration,
aclTags,
}),
});
if (!res.ok) {
throw new Error(
`Headscale create preauthkey failed: ${res.status} ${await res.text()}`
);
}
const data = (await res.json()) as { preAuthKey: HeadscalePreAuthKey };
return data.preAuthKey.key;
}
+216 -18
View File
@@ -1,5 +1,8 @@
import { WebSocketServer, WebSocket } from "ws";
import { randomBytes } from "crypto";
import type { IncomingMessage } from "http";
import { prisma } from "./prisma";
import { createEphemeralPreAuthKey, getHeadscaleUserId } from "./headscale";
interface NodeMessage {
action: string;
@@ -12,14 +15,68 @@ interface NodeMessage {
studentName?: string;
error?: string;
tailscaleIp?: string;
token?: string;
}
const nodes = new Map<string, WebSocket>();
interface AttemptWindow {
count: number;
firstAttempt: number;
}
const activationAttemptsByCode = new Map<string, AttemptWindow>();
const activationAttemptsByNode = new Map<string, AttemptWindow>();
const MAX_ACTIVATION_ATTEMPTS = 5;
const ACTIVATION_WINDOW_MS = 15 * 60 * 1000;
const HEADSCALE_USER = "studioe5";
const HEADSCALE_AGENT_TAG = "tag:student-agent";
const HEADSCALE_KEY_EXPIRATION_MINUTES = 15;
let headscaleUserIdCache: string | null = null;
function recordActivationAttempt(map: Map<string, AttemptWindow>, key: string): boolean {
const now = Date.now();
const win = map.get(key);
if (!win || now - win.firstAttempt > ACTIVATION_WINDOW_MS) {
map.set(key, { count: 1, firstAttempt: now });
return true;
}
win.count++;
return win.count <= MAX_ACTIVATION_ATTEMPTS;
}
function clearActivationAttempts(code: string, nodeId: string) {
activationAttemptsByCode.delete(code);
activationAttemptsByNode.delete(nodeId);
}
function generateNodeToken(): string {
return randomBytes(32).toString("hex");
}
function getBearerToken(req: IncomingMessage): string | null {
const auth = req.headers.authorization || "";
const match = auth.match(/^Bearer\s+(\S+)$/i);
return match ? match[1] : null;
}
function close(ws: WebSocket, code: number, reason: string) {
try {
ws.close(code, reason);
} catch {
// ignore
}
}
export function initWebSocketServer(wss: WebSocketServer) {
wss.on("connection", (ws: WebSocket) => {
wss.on("connection", (ws: WebSocket, req: IncomingMessage) => {
let nodeId: string | null = null;
console.log("[WS] New connection");
let authenticated = false;
const token = getBearerToken(req);
console.log("[WS] New connection", token ? "(token provided)" : "(no token)");
ws.on("message", async (raw) => {
try {
@@ -27,19 +84,69 @@ export function initWebSocketServer(wss: WebSocketServer) {
console.log("[WS] Received:", msg.action, "from", msg.nodeId || nodeId);
if (msg.action === "register" && msg.nodeId) {
nodeId = msg.nodeId;
nodes.set(nodeId, ws);
await prisma.node.upsert({
where: { id: nodeId },
update: { status: "online", lastSeen: new Date() },
create: { id: nodeId, status: "online", lastSeen: new Date() },
});
const id = msg.nodeId;
const existing = await prisma.node.findUnique({ where: { id } });
if (token) {
// Token supplied: it must match the stored token for this node.
if (!existing || existing.token !== token) {
console.log("[WS] Invalid token for node", id);
close(ws, 1008, "invalid token");
return;
}
authenticated = true;
} else if (existing && existing.token) {
// Existing node has a token but none was supplied.
console.log("[WS] Missing token for node", id);
close(ws, 1008, "missing token");
return;
} else if (existing) {
// Migration path: existing node without a token gets one on first register.
const newToken = generateNodeToken();
await prisma.node.update({
where: { id },
data: { token: newToken, status: "online", lastSeen: new Date() },
});
ws.send(JSON.stringify({ action: "set_token", token: newToken }));
authenticated = true;
}
// If the node does not exist yet, we stay unauthenticated until activation.
nodeId = id;
if (authenticated) {
const existing = nodes.get(id);
if (existing && existing !== ws && existing.readyState === WebSocket.OPEN) {
console.log("[WS] Superseding previous connection for", id);
existing.close(1008, "superseded");
}
nodes.set(id, ws);
await prisma.node.upsert({
where: { id },
update: { status: "online", lastSeen: new Date() },
create: { id, status: "online", lastSeen: new Date() },
});
}
ws.send(JSON.stringify({ action: "registered" }));
return;
}
if (msg.action === "activate" && msg.code && msg.nodeId) {
nodeId = msg.nodeId;
const id = msg.nodeId;
nodeId = id;
if (!recordActivationAttempt(activationAttemptsByCode, msg.code) ||
!recordActivationAttempt(activationAttemptsByNode, id)) {
console.log("[WS] Too many activation attempts for code/node", msg.code, id);
ws.send(JSON.stringify({ action: "activation_failed", error: "Too many attempts" }));
return;
}
const existing = await prisma.node.findUnique({ where: { id } });
if (existing && existing.token && (!authenticated || nodeId !== id)) {
console.log("[WS] Node already activated and not authenticated:", id);
ws.send(JSON.stringify({ action: "activation_failed", error: "Node already activated" }));
return;
}
const student = await prisma.student.findUnique({
where: { activationCode: msg.code },
});
@@ -48,23 +155,97 @@ export function initWebSocketServer(wss: WebSocketServer) {
ws.send(JSON.stringify({ action: "activation_failed", error: "Invalid code" }));
return;
}
if (!student.activationCodeExpiresAt || student.activationCodeExpiresAt < new Date()) {
console.log("[WS] Expired code:", msg.code);
ws.send(JSON.stringify({ action: "activation_failed", error: "Code expired" }));
return;
}
const newToken = generateNodeToken();
await prisma.node.upsert({
where: { id: nodeId },
update: { studentId: student.id, status: "online", lastSeen: new Date() },
create: { id: nodeId, studentId: student.id, status: "online", lastSeen: new Date() },
where: { id },
update: {
studentId: student.id,
status: "online",
lastSeen: new Date(),
token: newToken,
},
create: {
id,
studentId: student.id,
status: "online",
lastSeen: new Date(),
token: newToken,
},
});
console.log("[WS] Activated:", student.firstName, student.lastName, "on", nodeId);
// Invalidate the activation code so it cannot be reused.
await prisma.student.update({
where: { id: student.id },
data: { activationCode: null, activationCodeExpiresAt: null },
});
clearActivationAttempts(msg.code, id);
authenticated = true;
const previous = nodes.get(id);
if (previous && previous !== ws && previous.readyState === WebSocket.OPEN) {
console.log("[WS] Superseding previous connection for", id);
previous.close(1008, "superseded");
}
nodes.set(id, ws);
const headscaleUrl = process.env.HEADSCALE_URL;
const headscaleApiKey = process.env.HEADSCALE_API_KEY;
const reusableAuthKey = process.env.HEADSCALE_AUTH_KEY;
if (!headscaleUrl) {
console.log("[WS] HEADSCALE_URL missing");
ws.send(JSON.stringify({ action: "activation_failed", error: "Server misconfiguration" }));
return;
}
let headscaleAuthKey: string;
try {
if (headscaleApiKey) {
if (!headscaleUserIdCache) {
headscaleUserIdCache = await getHeadscaleUserId(headscaleUrl, headscaleApiKey, HEADSCALE_USER);
}
headscaleAuthKey = await createEphemeralPreAuthKey(headscaleUrl, headscaleApiKey, headscaleUserIdCache, {
expirationMinutes: HEADSCALE_KEY_EXPIRATION_MINUTES,
aclTags: [HEADSCALE_AGENT_TAG],
});
console.log("[WS] Generated ephemeral Headscale key for", id);
} else if (reusableAuthKey) {
console.log("[WS] HEADSCALE_API_KEY not set, falling back to reusable HEADSCALE_AUTH_KEY");
headscaleAuthKey = reusableAuthKey;
} else {
console.log("[WS] No Headscale key available");
ws.send(JSON.stringify({ action: "activation_failed", error: "Server misconfiguration" }));
return;
}
} catch (err) {
console.error("[WS] Failed to create ephemeral Headscale key:", err);
ws.send(JSON.stringify({ action: "activation_failed", error: "Failed to create VPN key" }));
return;
}
console.log("[WS] Activated:", student.firstName, student.lastName, "on", id);
ws.send(JSON.stringify({
action: "activated",
studentId: student.id,
studentName: `${student.firstName} ${student.lastName}`,
headscaleUrl: process.env.HEADSCALE_URL,
headscaleAuthKey: process.env.HEADSCALE_AUTH_KEY,
headscaleUrl,
headscaleAuthKey,
token: newToken,
}));
return;
}
if (msg.action === "heartbeat" && nodeId) {
if (!authenticated || !nodeId) {
console.log("[WS] Unauthenticated message", msg.action, "ignored");
return;
}
if (msg.action === "heartbeat") {
await prisma.node.upsert({
where: { id: nodeId },
update: { lastSeen: new Date() },
@@ -73,7 +254,7 @@ export function initWebSocketServer(wss: WebSocketServer) {
return;
}
if (msg.action === "tailscale_ip" && nodeId && msg.tailscaleIp) {
if (msg.action === "tailscale_ip" && msg.tailscaleIp) {
await prisma.node.update({
where: { id: nodeId },
data: { tailscaleIp: msg.tailscaleIp },
@@ -90,6 +271,23 @@ export function initWebSocketServer(wss: WebSocketServer) {
return;
}
if (msg.action === "instance_stopped" && msg.instanceId) {
await prisma.instance.update({
where: { id: msg.instanceId },
data: { status: "stopped" },
});
console.log("[WS] Instance stopped:", msg.instanceId);
return;
}
if (msg.action === "instance_deleted" && msg.instanceId) {
await prisma.instance.delete({
where: { id: msg.instanceId },
});
console.log("[WS] Instance deleted:", msg.instanceId);
return;
}
if (msg.action === "instance_error" && msg.instanceId) {
await prisma.instance.update({
where: { id: msg.instanceId },
+11 -9
View File
@@ -50,21 +50,23 @@ model Class {
}
model Student {
id String @id @default(cuid())
classId String
class Class @relation(fields: [classId], references: [id], onDelete: Cascade)
firstName String
lastName String
email String
activationCode String? @unique
createdAt DateTime @default(now())
nodes Node[]
id String @id @default(cuid())
classId String
class Class @relation(fields: [classId], references: [id], onDelete: Cascade)
firstName String
lastName String
email String
activationCode String? @unique
activationCodeExpiresAt DateTime?
createdAt DateTime @default(now())
nodes Node[]
}
model Node {
id String @id
studentId String?
student Student? @relation(fields: [studentId], references: [id], onDelete: Cascade)
token String? @unique
tailscaleIp String?
status String @default("offline")
lastSeen DateTime?
File diff suppressed because one or more lines are too long