finish up turbo and add stimulus.

This commit is contained in:
KingKDot
2026-07-13 20:00:04 -05:00
parent e390dbc966
commit b08d8ba028
21 changed files with 576 additions and 254 deletions
+2
View File
@@ -19,6 +19,7 @@ import { metrics } from "./metrics";
import { getClientDbSyncStats } from "./client-db-sync";
import { ensureDataDir } from "./paths";
import { handleAuthRoutes } from "./server/routes/auth-routes";
import { handleUiRoutes } from "./server/routes/ui-routes";
import { handleAutoScriptsRoutes } from "./server/routes/auto-scripts-routes";
import { handleSavedScriptsRoutes } from "./server/routes/saved-scripts-routes";
import { handleEnrollmentRoutes, setPostApproveHook } from "./server/routes/enrollment-routes";
@@ -715,6 +716,7 @@ async function startServer() {
...routeDeps.registration,
requestIP: (srv as any).requestIP,
}),
(req, url, srv) => handleUiRoutes(req, url, srv as any),
(req, url, srv) => handleAuthRoutes(req, url, srv as any),
(req, url, srv) => handleOidcRoutes(req, url, srv as any),
(req, url, srv) => handleNotificationsConfigRoutes(req, url, srv as any, routeDeps.notificationsConfig),
@@ -0,0 +1,125 @@
import { afterEach, describe, expect, test } from "bun:test";
import { generateToken } from "../../auth";
import {
createSession,
getSessionById,
hashTokenForSession,
listUserSessions,
revokeSessionById,
} from "../../db";
import { createUser, deleteUser, getUserById } from "../../users";
import { handleUiRoutes } from "./ui-routes";
const PASSWORD = "Aa1!TurboFrameSessionsTest";
const createdUserIds: number[] = [];
const mockServer = { requestIP: () => ({ address: "127.0.0.1" }) };
async function tempUser(userAgent = "Turbo Frame Test") {
const username = `ui_sessions_${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
const created = await createUser(username, PASSWORD, "admin", "test");
expect(created.success).toBe(true);
const user = getUserById(created.userId!);
expect(user).not.toBeNull();
createdUserIds.push(user!.id);
const token = await generateToken(user!, { ip: "127.0.0.1", userAgent });
return { user: user!, token };
}
function call(method: string, path: string, token: string | null) {
const url = new URL(`https://localhost${path}`);
const headers: Record<string, string> = {};
if (token) headers.Authorization = `Bearer ${token}`;
return handleUiRoutes(new Request(url, { method, headers }), url, mockServer);
}
function addSession(userId: number, userAgent: string) {
const now = Math.floor(Date.now() / 1000);
const session = {
id: crypto.randomUUID(),
userId,
tokenHash: crypto.randomUUID().replaceAll("-", ""),
ip: "127.0.0.2",
userAgent,
createdAt: now,
expiresAt: now + 3600,
};
createSession(session);
return session;
}
afterEach(() => {
while (createdUserIds.length > 0) {
const id = createdUserIds.pop();
if (typeof id === "number") deleteUser(id);
}
});
describe("settings sessions Turbo Frame", () => {
test("redirects unauthenticated frame requests to login", async () => {
const response = await call("GET", "/ui/settings/sessions", null);
expect(response!.status).toBe(303);
expect(response!.headers.get("location")).toBe("https://localhost/login.html");
});
test("renders an escaped frame and marks the current session", async () => {
const account = await tempUser('<script>alert("xss")</script>');
const response = await call("GET", "/ui/settings/sessions", account.token);
expect(response!.status).toBe(200);
expect(response!.headers.get("content-type")).toContain("text/html");
expect(response!.headers.get("cache-control")).toBe("no-store");
const body = await response!.text();
expect(body).toContain('<turbo-frame id="section-sessions"');
expect(body).toContain("Current");
expect(body).toContain("&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;");
expect(body).not.toContain('<script>alert("xss")</script>');
expect(body).toContain('data-controller="sessions"');
expect(body).toContain('data-turbo="true"');
});
test("revokes another session and returns the refreshed frame", async () => {
const account = await tempUser();
const added = addSession(account.user.id, "Second browser");
const secondSession = getSessionById(added.id);
expect(secondSession).toBeDefined();
const response = await call(
"POST",
`/ui/settings/sessions/${encodeURIComponent(secondSession!.id)}/revoke`,
account.token,
);
expect(response!.status).toBe(200);
expect(await response!.text()).toContain("Session revoked successfully.");
expect(getSessionById(secondSession!.id)?.revoked).toBe(true);
});
test("revoking the current session clears the cookie and redirects", async () => {
const account = await tempUser();
const currentHash = hashTokenForSession(account.token);
const currentSession = listUserSessions(account.user.id).find((session) => session.tokenHash === currentHash);
expect(currentSession).toBeDefined();
const response = await call(
"POST",
`/ui/settings/sessions/${encodeURIComponent(currentSession!.id)}/revoke`,
account.token,
);
expect(response!.status).toBe(303);
expect(response!.headers.get("location")).toBe("/");
expect(response!.headers.get("set-cookie")).toContain("Max-Age=0");
expect(getSessionById(currentSession!.id)?.revoked).toBe(true);
});
test("removes inactive sessions and reports the count", async () => {
const account = await tempUser();
const added = addSession(account.user.id, "Inactive browser");
const secondSession = getSessionById(added.id);
expect(secondSession).toBeDefined();
revokeSessionById(secondSession!.id);
const response = await call("POST", "/ui/settings/sessions/inactive", account.token);
expect(response!.status).toBe(200);
expect(await response!.text()).toContain("Removed 1 inactive session(s).");
expect(getSessionById(secondSession!.id)).toBeNull();
});
});
@@ -0,0 +1,118 @@
import { authenticateRequest, extractTokenFromRequest } from "../../auth";
import { AuditAction, logAudit } from "../../auditLog";
import {
deleteInactiveSessions,
getSessionById,
hashTokenForSession,
listUserSessions,
persistRevokedTokenHash,
revokeSessionById,
} from "../../db";
import { htmlResponse } from "../ui/html";
import { renderSessionsFrame } from "../ui/sessions-view";
import { makeAuthCookieClear } from "./auth-cookie";
type UiRouteServer = {
requestIP: (req: Request) => { address?: string } | null | undefined;
};
function redirectToLogin(req: Request): Response {
return Response.redirect(new URL("/login.html", req.url), 303);
}
function currentTokenHash(req: Request): string | null {
const token = extractTokenFromRequest(req);
return token ? hashTokenForSession(token) : null;
}
export async function handleUiRoutes(
req: Request,
url: URL,
server: UiRouteServer,
): Promise<Response | null> {
if (!url.pathname.startsWith("/ui/")) return null;
const user = await authenticateRequest(req);
if (!user) return redirectToLogin(req);
if (req.method === "GET" && url.pathname === "/ui/settings/sessions") {
return htmlResponse(renderSessionsFrame(
listUserSessions(user.userId),
currentTokenHash(req),
));
}
if (req.method === "POST" && url.pathname === "/ui/settings/sessions/inactive") {
const removed = deleteInactiveSessions(user.userId);
logAudit({
timestamp: Date.now(),
username: user.username,
ip: server.requestIP(req)?.address || "unknown",
action: AuditAction.LOGOUT,
details: `Removed ${removed} inactive session(s)`,
success: true,
});
return htmlResponse(renderSessionsFrame(
listUserSessions(user.userId),
currentTokenHash(req),
{ text: `Removed ${removed} inactive session(s).` },
));
}
const revokeMatch = req.method === "POST"
? url.pathname.match(/^\/ui\/settings\/sessions\/([^/]+)\/revoke$/)
: null;
if (revokeMatch) {
let sessionId = "";
try {
sessionId = decodeURIComponent(revokeMatch[1]);
} catch {
return htmlResponse(renderSessionsFrame(
listUserSessions(user.userId),
currentTokenHash(req),
{ text: "Invalid session identifier.", type: "error" },
), { status: 400 });
}
const session = getSessionById(sessionId);
if (!session || session.userId !== user.userId) {
return htmlResponse(renderSessionsFrame(
listUserSessions(user.userId),
currentTokenHash(req),
{ text: "Session not found.", type: "error" },
), { status: 404 });
}
const tokenHash = currentTokenHash(req);
const revokingCurrentSession = session.tokenHash === tokenHash;
const result = revokeSessionById(sessionId);
if (result.tokenHash) persistRevokedTokenHash(result.tokenHash, session.expiresAt);
logAudit({
timestamp: Date.now(),
username: user.username,
ip: server.requestIP(req)?.address || "unknown",
action: AuditAction.LOGOUT,
details: `Revoked session ${sessionId}`,
success: true,
});
if (revokingCurrentSession) {
return new Response(null, {
status: 303,
headers: {
"Location": "/",
"Set-Cookie": makeAuthCookieClear(req),
},
});
}
return htmlResponse(renderSessionsFrame(
listUserSessions(user.userId),
tokenHash,
{ text: "Session revoked successfully." },
));
}
return htmlResponse("<h1>Not found</h1>", { status: 404 });
}
+19
View File
@@ -0,0 +1,19 @@
export function escapeHtml(value: unknown): string {
return String(value ?? "")
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;");
}
export function htmlResponse(
html: string,
init: ResponseInit = {},
): Response {
const headers = new Headers(init.headers);
headers.set("Content-Type", "text/html; charset=utf-8");
headers.set("Cache-Control", "no-store");
headers.append("Vary", "Turbo-Frame");
return new Response(html, { ...init, headers });
}
@@ -0,0 +1,108 @@
import type { SessionRecord } from "../../db";
import { escapeHtml } from "./html";
type SessionsMessage = {
text: string;
type?: "success" | "error";
};
function summarizeUserAgent(userAgent: string | null): string {
if (!userAgent) return "Unknown";
return userAgent.length > 80 ? `${userAgent.slice(0, 77)}...` : userAgent;
}
function renderMessage(message?: SessionsMessage): string {
if (!message) return "";
const classes = message.type === "error"
? "text-rose-200 border-rose-700 bg-rose-900/30"
: "text-emerald-200 border-emerald-700 bg-emerald-900/30";
return `<p class="text-sm rounded-lg px-3 py-2 border ${classes}" role="status">${escapeHtml(message.text)}</p>`;
}
function renderSessionRow(
session: SessionRecord,
currentTokenHash: string | null,
now: number,
): string {
const current = session.tokenHash === currentTokenHash;
const expired = session.expiresAt <= now;
const canRevoke = !session.revoked && !expired;
const status = session.revoked
? '<span class="text-rose-400">Revoked</span>'
: expired
? '<span class="text-slate-500">Expired</span>'
: '<span class="text-emerald-400">Active</span>';
const currentBadge = current
? ' <span class="ml-1 px-1.5 py-0.5 text-[10px] rounded bg-sky-600/30 text-sky-300 border border-sky-500/30">Current</span>'
: "";
const confirmation = current
? "This will revoke your current session and log you out. Continue?"
: "Revoke this session?";
return `<tr id="session-${escapeHtml(session.id)}">
<td class="px-3 py-2 font-mono text-xs text-slate-100">${escapeHtml(session.ip || "—")}</td>
<td class="px-3 py-2 text-slate-300 text-xs max-w-[200px] truncate" title="${escapeHtml(session.userAgent || "")}">${escapeHtml(summarizeUserAgent(session.userAgent))}</td>
<td class="px-3 py-2 text-slate-400 text-xs"><time data-sessions-target="time" data-timestamp="${session.createdAt}" datetime="${new Date(session.createdAt * 1000).toISOString()}">—</time></td>
<td class="px-3 py-2 text-slate-400 text-xs"><time data-sessions-target="time" data-format="relative" data-timestamp="${session.lastActivity}" datetime="${new Date(session.lastActivity * 1000).toISOString()}">—</time></td>
<td class="px-3 py-2 text-xs">${status}${currentBadge}</td>
<td class="px-3 py-2 text-right">
${canRevoke ? `<form method="post" action="/ui/settings/sessions/${encodeURIComponent(session.id)}/revoke" data-turbo="true" data-action="submit->sessions#confirm" data-confirm-message="${escapeHtml(confirmation)}" class="inline">
<button type="submit" class="px-2.5 py-1.5 rounded bg-red-700/80 hover:bg-red-600 text-white text-xs disabled:opacity-50">
<i class="fa-solid fa-right-from-bracket mr-1"></i>Revoke
</button>
</form>` : ""}
</td>
</tr>`;
}
export function renderSessionsFrame(
sessions: SessionRecord[],
currentTokenHash: string | null,
message?: SessionsMessage,
): string {
const now = Math.floor(Date.now() / 1000);
const rows = sessions.length > 0
? sessions.map((session) => renderSessionRow(session, currentTokenHash, now)).join("")
: '<tr><td colspan="6" class="px-3 py-6 text-center text-slate-400">No sessions found</td></tr>';
return `<turbo-frame id="section-sessions" class="block bg-slate-900/60 border border-slate-800 rounded-xl p-5 space-y-4 settings-section" data-controller="sessions">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-3">
<div class="flex items-center justify-center w-9 h-9 rounded-lg bg-emerald-500/10 border border-emerald-500/30">
<i class="fa-solid fa-desktop text-emerald-400"></i>
</div>
<div>
<h2 class="text-lg font-semibold">Active Sessions</h2>
<p class="text-sm text-slate-400">View and manage your active login sessions.</p>
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<a href="/ui/settings/sessions" class="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-sm transition-colors">
<i class="fa-solid fa-rotate"></i>Refresh
</a>
<form method="post" action="/ui/settings/sessions/inactive" data-turbo="true" data-action="submit->sessions#confirm" data-confirm-message="Remove all expired and revoked sessions?">
<button type="submit" class="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-red-900/40 hover:bg-red-800/60 text-red-100 border border-red-700/60 text-sm transition-colors disabled:opacity-50">
<i class="fa-solid fa-broom"></i>Remove Inactive
</button>
</form>
</div>
</div>
<div class="overflow-x-auto border border-slate-800 rounded-lg">
<table class="w-full text-sm">
<thead class="bg-slate-800/60 text-slate-300">
<tr>
<th class="text-left px-3 py-2">IP</th>
<th class="text-left px-3 py-2">Browser / Client</th>
<th class="text-left px-3 py-2">Created</th>
<th class="text-left px-3 py-2">Last Active</th>
<th class="text-left px-3 py-2">Status</th>
<th class="text-right px-3 py-2">Action</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-800">${rows}</tbody>
</table>
</div>
${renderMessage(message)}
</turbo-frame>`;
}