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:
@@ -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");
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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 },
|
||||
|
||||
Reference in New Issue
Block a user