diff --git a/Overlord-Server/public/assets/file-share.js b/Overlord-Server/public/assets/file-share.js
new file mode 100644
index 0000000..b9948b2
--- /dev/null
+++ b/Overlord-Server/public/assets/file-share.js
@@ -0,0 +1,389 @@
+const fileList = document.getElementById("file-list");
+const uploadSection = document.getElementById("upload-section");
+const uploadForm = document.getElementById("upload-form");
+const uploadInfinite = document.getElementById("upload-infinite");
+const uploadMaxDownloads = document.getElementById("upload-max-downloads");
+
+let currentUser = null;
+
+function formatBytes(bytes) {
+ if (bytes === 0) return "0 B";
+ const k = 1024;
+ const sizes = ["B", "KB", "MB", "GB", "TB"];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
+}
+
+function timeAgo(ts) {
+ const seconds = Math.floor((Date.now() - ts) / 1000);
+ if (seconds < 60) return "just now";
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ return new Date(ts).toLocaleDateString();
+}
+
+function escapeHtml(str) {
+ const div = document.createElement("div");
+ div.textContent = str;
+ return div.innerHTML;
+}
+
+function getDownloadUrl(fileId) {
+ return `${window.location.origin}/api/file-share/${fileId}/download`;
+}
+
+uploadInfinite?.addEventListener("change", () => {
+ if (uploadInfinite.checked) {
+ uploadMaxDownloads.value = "";
+ uploadMaxDownloads.disabled = true;
+ } else {
+ uploadMaxDownloads.disabled = false;
+ uploadMaxDownloads.focus();
+ }
+});
+if (uploadMaxDownloads) uploadMaxDownloads.disabled = true;
+
+const passwordInfoBtn = document.getElementById("password-info-btn");
+const passwordInfoPanel = document.getElementById("password-info-panel");
+passwordInfoBtn?.addEventListener("click", () => {
+ passwordInfoPanel?.classList.toggle("hidden");
+});
+
+async function loadCurrentUser() {
+ try {
+ const res = await fetch("/api/auth/me");
+ if (!res.ok) {
+ window.location.href = "/";
+ return;
+ }
+ currentUser = await res.json();
+ if (currentUser.role === "viewer") {
+ window.location.href = "/";
+ return;
+ }
+ } catch {
+ window.location.href = "/";
+ }
+}
+
+async function loadFiles() {
+ try {
+ const res = await fetch("/api/file-share");
+ if (!res.ok) {
+ fileList.innerHTML = `
| Failed to load files |
`;
+ return;
+ }
+ const data = await res.json();
+
+ if (data.canUpload && uploadSection) {
+ uploadSection.classList.remove("hidden");
+ }
+
+ if (!data.files || data.files.length === 0) {
+ fileList.innerHTML = `|
+ No files shared yet
+ |
`;
+ return;
+ }
+
+ fileList.innerHTML = data.files
+ .map((f) => {
+ const isOwner = currentUser && f.uploadedBy === currentUser.userId;
+ const isAdmin = currentUser && currentUser.role === "admin";
+ const canManage = isOwner || isAdmin;
+
+ const expired = f.expiresAt && f.expiresAt < Date.now();
+ const limitReached = f.maxDownloads !== null && f.downloadCount >= f.maxDownloads;
+
+ let statusBadges = "";
+ if (f.hasPassword) {
+ statusBadges += `Password `;
+ }
+ if (expired) {
+ statusBadges += `Expired `;
+ } else if (limitReached) {
+ statusBadges += `Limit Reached `;
+ } else if (f.expiresAt) {
+ statusBadges += `Timed `;
+ }
+ if (!statusBadges) {
+ statusBadges = `Active`;
+ }
+
+ const downloadStr = f.maxDownloads !== null
+ ? `${f.downloadCount} / ${f.maxDownloads}`
+ : `${f.downloadCount} / ∞`;
+
+ return `
+
+
+
+
+
+ ${escapeHtml(f.filename)}
+ ${f.description ? `${escapeHtml(f.description)}` : ""}
+
+
+ |
+ ${formatBytes(f.size)} |
+ ${escapeHtml(f.uploadedByUsername)} |
+ ${downloadStr} |
+ ${statusBadges} |
+ ${timeAgo(f.createdAt)} |
+
+
+
+ ${canManage ? `
+
+
+ ` : ""}
+
+ |
+
`;
+ })
+ .join("");
+
+ attachActionListeners();
+ } catch (err) {
+ console.error("Load files error:", err);
+ fileList.innerHTML = `| Failed to load files |
`;
+ }
+}
+
+function attachActionListeners() {
+ fileList.addEventListener("click", (e) => {
+ const btn = e.target.closest(".action-btn");
+ if (!btn) return;
+
+ const action = btn.dataset.action;
+ const fileId = btn.dataset.fileId;
+
+ switch (action) {
+ case "copy-link":
+ copyDownloadLink(fileId);
+ break;
+ case "edit":
+ openEditModal(btn);
+ break;
+ case "delete":
+ deleteFile(fileId, btn.dataset.filename);
+ break;
+ }
+ });
+}
+
+function copyDownloadLink(fileId) {
+ const url = getDownloadUrl(fileId);
+ navigator.clipboard.writeText(url).then(() => {
+ if (window.showToast) {
+ window.showToast("Download link copied to clipboard!", "success");
+ }
+ }).catch(() => {
+ const input = document.createElement("input");
+ input.value = url;
+ document.body.appendChild(input);
+ input.select();
+ document.execCommand("copy");
+ document.body.removeChild(input);
+ if (window.showToast) {
+ window.showToast("Download link copied!", "success");
+ }
+ });
+}
+
+async function deleteFile(fileId, filename) {
+ if (!confirm(`Delete "${filename}"? This cannot be undone.`)) return;
+
+ try {
+ const res = await fetch(`/api/file-share/${fileId}`, { method: "DELETE" });
+ if (res.ok) {
+ if (window.showToast) window.showToast("File deleted", "success");
+ loadFiles();
+ } else {
+ const data = await res.json().catch(() => ({}));
+ alert(data.error || "Failed to delete file");
+ }
+ } catch (err) {
+ console.error("Delete error:", err);
+ alert("Network error. Please try again.");
+ }
+}
+
+const editModal = document.getElementById("edit-modal");
+const editFileId = document.getElementById("edit-file-id");
+const editPassword = document.getElementById("edit-password");
+const editMaxDownloads = document.getElementById("edit-max-downloads");
+const editInfinite = document.getElementById("edit-infinite");
+const editExpiry = document.getElementById("edit-expiry");
+const editDescription = document.getElementById("edit-description");
+
+function openEditModal(btn) {
+ editFileId.value = btn.dataset.fileId;
+ editPassword.value = "";
+ editDescription.value = btn.dataset.description || "";
+
+ const maxDl = btn.dataset.maxDownloads;
+ if (maxDl === "" || maxDl === "null") {
+ editInfinite.checked = true;
+ editMaxDownloads.value = "";
+ editMaxDownloads.disabled = true;
+ } else {
+ editInfinite.checked = false;
+ editMaxDownloads.value = maxDl;
+ editMaxDownloads.disabled = false;
+ }
+
+ const expiresAt = btn.dataset.expiresAt;
+ if (expiresAt && expiresAt !== "null" && expiresAt !== "") {
+ const d = new Date(parseInt(expiresAt));
+ editExpiry.value = d.toISOString().slice(0, 16);
+ } else {
+ editExpiry.value = "";
+ }
+
+ editModal.classList.remove("hidden");
+}
+
+editInfinite?.addEventListener("change", () => {
+ if (editInfinite.checked) {
+ editMaxDownloads.value = "";
+ editMaxDownloads.disabled = true;
+ } else {
+ editMaxDownloads.disabled = false;
+ editMaxDownloads.focus();
+ }
+});
+
+document.getElementById("edit-cancel")?.addEventListener("click", () => {
+ editModal.classList.add("hidden");
+});
+
+editModal?.addEventListener("click", (e) => {
+ if (e.target === editModal) editModal.classList.add("hidden");
+});
+
+document.getElementById("edit-save")?.addEventListener("click", async () => {
+ const fileId = editFileId.value;
+ const body = {};
+
+ const pw = editPassword.value;
+ if (pw !== "") {
+ body.password = pw;
+ }
+
+ if (editInfinite.checked) {
+ body.maxDownloads = null;
+ } else {
+ const val = parseInt(editMaxDownloads.value, 10);
+ if (!isNaN(val) && val > 0) {
+ body.maxDownloads = val;
+ }
+ }
+
+ if (editExpiry.value) {
+ body.expiresAt = new Date(editExpiry.value).getTime();
+ } else {
+ body.expiresAt = null;
+ }
+
+ body.description = editDescription.value || null;
+
+ try {
+ const res = await fetch(`/api/file-share/${fileId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+ if (res.ok) {
+ editModal.classList.add("hidden");
+ if (window.showToast) window.showToast("Settings updated", "success");
+ loadFiles();
+ } else {
+ const data = await res.json().catch(() => ({}));
+ alert(data.error || "Failed to update");
+ }
+ } catch (err) {
+ console.error("Edit error:", err);
+ alert("Network error. Please try again.");
+ }
+});
+
+uploadForm?.addEventListener("submit", async (e) => {
+ e.preventDefault();
+
+ const fileInput = document.getElementById("upload-file");
+ const file = fileInput.files[0];
+ if (!file) return;
+
+ const btn = document.getElementById("upload-btn");
+ btn.disabled = true;
+ btn.innerHTML = ' Uploading...';
+
+ const formData = new FormData();
+ formData.append("file", file);
+
+ const password = document.getElementById("upload-password").value;
+ if (password) formData.append("password", password);
+
+ if (!uploadInfinite.checked) {
+ const maxDl = uploadMaxDownloads.value;
+ if (maxDl) formData.append("maxDownloads", maxDl);
+ }
+
+ const expiry = document.getElementById("upload-expiry").value;
+ if (expiry) {
+ formData.append("expiresAt", String(new Date(expiry).getTime()));
+ }
+
+ const description = document.getElementById("upload-description").value;
+ if (description) formData.append("description", description);
+
+ try {
+ const res = await fetch("/api/file-share/upload", {
+ method: "POST",
+ body: formData,
+ });
+
+ const data = await res.json();
+
+ if (res.ok) {
+ if (window.showToast) window.showToast(`"${data.filename}" uploaded successfully!`, "success");
+ uploadForm.reset();
+ uploadInfinite.checked = true;
+ uploadMaxDownloads.disabled = true;
+ loadFiles();
+ } else {
+ alert(data.error || "Upload failed");
+ }
+ } catch (err) {
+ console.error("Upload error:", err);
+ alert("Network error. Please try again.");
+ } finally {
+ btn.disabled = false;
+ btn.innerHTML = ' Upload';
+ }
+});
+
+(async () => {
+ await loadCurrentUser();
+ await loadFiles();
+})();
diff --git a/Overlord-Server/public/assets/nav.js b/Overlord-Server/public/assets/nav.js
index f43ed4c..ecce22d 100644
--- a/Overlord-Server/public/assets/nav.js
+++ b/Overlord-Server/public/assets/nav.js
@@ -30,6 +30,7 @@ if (host) {
"/users": "users-link",
"/user-client-access": "users-link",
"/notifications": "notifications-link",
+ "/file-share": "file-share-link",
};
const activeId = activeMap[path];
if (activeId) {
diff --git a/Overlord-Server/public/assets/nav/role-ui.js b/Overlord-Server/public/assets/nav/role-ui.js
index 321db7c..4ba7a41 100644
--- a/Overlord-Server/public/assets/nav/role-ui.js
+++ b/Overlord-Server/public/assets/nav/role-ui.js
@@ -10,6 +10,7 @@ export function applyUserRoleUI(user, refs) {
logsLink,
notificationsLink,
enrollmentLink,
+ fileShareLink,
} = refs;
if (!user || !usernameDisplay || !roleBadge) return;
@@ -77,5 +78,6 @@ export function applyUserRoleUI(user, refs) {
}
if (user.role !== "viewer") {
scriptsLink?.classList.remove("hidden");
+ fileShareLink?.classList.remove("hidden");
}
}
diff --git a/Overlord-Server/public/assets/nav/template.js b/Overlord-Server/public/assets/nav/template.js
index 5396c59..9d65212 100644
--- a/Overlord-Server/public/assets/nav/template.js
+++ b/Overlord-Server/public/assets/nav/template.js
@@ -40,6 +40,9 @@ function mountTopbar(host) {
Proxies
+ File Share
Plugins
@@ -104,6 +107,7 @@ function mountTopbar(host) {
notificationsLink: document.getElementById("notifications-link"),
enrollmentLink: document.getElementById("enrollment-link"),
enrollmentBadge: document.getElementById("enrollment-badge"),
+ fileShareLink: document.getElementById("file-share-link"),
};
}
@@ -141,6 +145,10 @@ function mountSidebar(host) {
Proxies
+
+
+ File Share
+
Plugins
@@ -235,6 +243,7 @@ function mountSidebar(host) {
notificationsLink: document.getElementById("notifications-link"),
enrollmentLink: document.getElementById("enrollment-link"),
enrollmentBadge: document.getElementById("enrollment-badge"),
+ fileShareLink: document.getElementById("file-share-link"),
};
}
diff --git a/Overlord-Server/public/assets/users.js b/Overlord-Server/public/assets/users.js
index 9253503..e7fa99f 100644
--- a/Overlord-Server/public/assets/users.js
+++ b/Overlord-Server/public/assets/users.js
@@ -159,6 +159,11 @@ function renderUsers() {
title="${user.can_build ? 'Can build (click to revoke)' : 'Cannot build (click to grant)'}">
${user.can_build ? 'Build' : 'No Build'}
+
+ ${user.can_upload_files ? 'Upload' : 'No Upload'}
+
` : ''}
@@ -254,6 +259,15 @@ function attachActionListeners() {
return;
}
+ const toggleUpload = e.target.closest("[data-action='toggle-upload']");
+ if (toggleUpload) {
+ const userId = parseInt(toggleUpload.dataset.userId);
+ const username = toggleUpload.dataset.username;
+ const canUpload = toggleUpload.dataset.canUpload === "1";
+ toggleUploadPermission(userId, username, canUpload);
+ return;
+ }
+
const btn = e.target.closest(".user-action-btn");
if (!btn) return;
@@ -473,5 +487,29 @@ window.toggleBuildPermission = async function (userId, username, currentCanBuild
}
};
+window.toggleUploadPermission = async function (userId, username, currentCanUpload) {
+ const newVal = !currentCanUpload;
+ if (!confirm(`${newVal ? 'Grant' : 'Revoke'} file upload permission for ${username}?`)) return;
+
+ try {
+ const res = await fetch(`/api/users/${userId}/can-upload-files`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ canUploadFiles: newVal }),
+ });
+
+ const data = await res.json();
+
+ if (res.ok) {
+ await loadUsers();
+ } else {
+ alert(data.error || "Failed to update upload permission");
+ }
+ } catch (err) {
+ console.error("Toggle upload permission error:", err);
+ alert("Network error. Please try again.");
+ }
+};
+
getCurrentUser();
loadUsers();
diff --git a/Overlord-Server/public/file-share.html b/Overlord-Server/public/file-share.html
new file mode 100644
index 0000000..e1988e4
--- /dev/null
+++ b/Overlord-Server/public/file-share.html
@@ -0,0 +1,173 @@
+
+
+
+
+
+ File Share - Overlord
+
+
+
+
+
+
+
+
+
+
+
+
+
+ File Share
+
+
+
+
+
+
+
+
+
+
+
+
+ | File |
+ Size |
+ Uploader |
+ Downloads |
+ Status |
+ Uploaded |
+ Actions |
+
+
+
+
+ |
+ Loading...
+ |
+
+
+
+
+
+
+
+
+
+
+
+ Edit File Settings
+
+
+
+
+
+
+ Enter new password or leave blank to remove
+
+
+
+
+
+ Clear to remove expiry
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Overlord-Server/src/db.ts b/Overlord-Server/src/db.ts
index 7a20c49..0b33fdf 100644
--- a/Overlord-Server/src/db.ts
+++ b/Overlord-Server/src/db.ts
@@ -244,6 +244,174 @@ db.run(
`CREATE INDEX IF NOT EXISTS idx_auto_deploy_runs_ts ON auto_deploy_runs(ts DESC);`,
);
+db.run(`
+ CREATE TABLE IF NOT EXISTS shared_files (
+ id TEXT PRIMARY KEY,
+ filename TEXT NOT NULL,
+ stored_path TEXT NOT NULL,
+ size INTEGER NOT NULL,
+ mime_type TEXT NOT NULL,
+ uploaded_by INTEGER NOT NULL,
+ uploaded_by_username TEXT NOT NULL,
+ password_hash TEXT,
+ max_downloads INTEGER,
+ download_count INTEGER NOT NULL DEFAULT 0,
+ expires_at INTEGER,
+ created_at INTEGER NOT NULL,
+ description TEXT
+ );
+`);
+db.run(
+ `CREATE INDEX IF NOT EXISTS idx_shared_files_created_at ON shared_files(created_at DESC);`,
+);
+db.run(
+ `CREATE INDEX IF NOT EXISTS idx_shared_files_uploaded_by ON shared_files(uploaded_by);`,
+);
+
+export type SharedFileRecord = {
+ id: string;
+ filename: string;
+ storedPath: string;
+ size: number;
+ mimeType: string;
+ uploadedBy: number;
+ uploadedByUsername: string;
+ passwordHash: string | null;
+ maxDownloads: number | null;
+ downloadCount: number;
+ expiresAt: number | null;
+ createdAt: number;
+ description: string | null;
+};
+
+export function insertSharedFile(file: SharedFileRecord): void {
+ db.run(
+ `INSERT INTO shared_files (id, filename, stored_path, size, mime_type, uploaded_by, uploaded_by_username, password_hash, max_downloads, download_count, expires_at, created_at, description)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ file.id,
+ file.filename,
+ file.storedPath,
+ file.size,
+ file.mimeType,
+ file.uploadedBy,
+ file.uploadedByUsername,
+ file.passwordHash,
+ file.maxDownloads,
+ file.downloadCount,
+ file.expiresAt,
+ file.createdAt,
+ file.description,
+ );
+}
+
+export function getSharedFile(id: string): SharedFileRecord | null {
+ const row = db.query(`SELECT * FROM shared_files WHERE id=?`).get(id);
+ if (!row) return null;
+ return {
+ id: row.id,
+ filename: row.filename,
+ storedPath: row.stored_path,
+ size: row.size,
+ mimeType: row.mime_type,
+ uploadedBy: row.uploaded_by,
+ uploadedByUsername: row.uploaded_by_username,
+ passwordHash: row.password_hash,
+ maxDownloads: row.max_downloads,
+ downloadCount: row.download_count,
+ expiresAt: row.expires_at,
+ createdAt: row.created_at,
+ description: row.description,
+ };
+}
+
+export function listSharedFiles(): SharedFileRecord[] {
+ return db
+ .query(`SELECT * FROM shared_files ORDER BY created_at DESC`)
+ .all()
+ .map((row: any) => ({
+ id: row.id,
+ filename: row.filename,
+ storedPath: row.stored_path,
+ size: row.size,
+ mimeType: row.mime_type,
+ uploadedBy: row.uploaded_by,
+ uploadedByUsername: row.uploaded_by_username,
+ passwordHash: row.password_hash,
+ maxDownloads: row.max_downloads,
+ downloadCount: row.download_count,
+ expiresAt: row.expires_at,
+ createdAt: row.created_at,
+ description: row.description,
+ }));
+}
+
+export function deleteSharedFile(id: string): boolean {
+ const result = db.run(`DELETE FROM shared_files WHERE id=?`, id);
+ return (result as any)?.changes ? (result as any).changes > 0 : false;
+}
+
+export function updateSharedFile(
+ id: string,
+ updates: {
+ passwordHash?: string | null;
+ maxDownloads?: number | null;
+ expiresAt?: number | null;
+ description?: string | null;
+ },
+): boolean {
+ const setClauses: string[] = [];
+ const values: any[] = [];
+
+ if (updates.passwordHash !== undefined) {
+ setClauses.push("password_hash=?");
+ values.push(updates.passwordHash);
+ }
+ if (updates.maxDownloads !== undefined) {
+ setClauses.push("max_downloads=?");
+ values.push(updates.maxDownloads);
+ }
+ if (updates.expiresAt !== undefined) {
+ setClauses.push("expires_at=?");
+ values.push(updates.expiresAt);
+ }
+ if (updates.description !== undefined) {
+ setClauses.push("description=?");
+ values.push(updates.description);
+ }
+
+ if (setClauses.length === 0) return false;
+
+ values.push(id);
+ const result = db.run(
+ `UPDATE shared_files SET ${setClauses.join(", ")} WHERE id=?`,
+ ...values,
+ );
+ return (result as any)?.changes ? (result as any).changes > 0 : false;
+}
+
+export function incrementSharedFileDownloadCount(id: string): boolean {
+ const result = db.run(
+ `UPDATE shared_files SET download_count = download_count + 1 WHERE id=?`,
+ id,
+ );
+ return (result as any)?.changes ? (result as any).changes > 0 : false;
+}
+
+export function deleteExpiredSharedFiles(): string[] {
+ const now = Date.now();
+ const expired = db
+ .query(`SELECT id, stored_path FROM shared_files WHERE expires_at IS NOT NULL AND expires_at < ?`)
+ .all(now);
+ const ids = expired.map((r: any) => r.id);
+ const paths = expired.map((r: any) => r.stored_path);
+ if (ids.length > 0) {
+ for (const id of ids) {
+ db.run(`DELETE FROM shared_files WHERE id=?`, id);
+ }
+ }
+ return paths;
+}
+
export function upsertClientRow(
partial: Partial & {
id: string;
diff --git a/Overlord-Server/src/main-server.ts b/Overlord-Server/src/main-server.ts
index c505f19..e3bc828 100644
--- a/Overlord-Server/src/main-server.ts
+++ b/Overlord-Server/src/main-server.ts
@@ -3,7 +3,8 @@ import { decodeMessage, encodeMessage, type WireMessage, type PluginManifest } f
import { logger } from "./logger";
import { fileURLToPath } from "url";
import path from "path";
-import { upsertClientRow, setOnlineState, listClients, markAllClientsOffline, getBuild, getBuildByTag, getAllBuilds, deleteExpiredBuilds, deleteBuild, getNotificationScreenshot, clearNotificationScreenshots, deleteClientRow, getClientIp, banIp, isIpBanned, clientExists } from "./db";
+import fs from "fs/promises";
+import { upsertClientRow, setOnlineState, listClients, markAllClientsOffline, getBuild, getBuildByTag, getAllBuilds, deleteExpiredBuilds, deleteBuild, getNotificationScreenshot, clearNotificationScreenshots, deleteClientRow, getClientIp, banIp, isIpBanned, clientExists, deleteExpiredSharedFiles } from "./db";
import { handleFrame, handleHello, handlePing, handlePong } from "./wsHandlers";
import { getMessageByteLength, getMaxPayloadLimit, isAllowedClientMessageType } from "./wsValidation";
import { ClientInfo, ClientRole } from "./types";
@@ -29,6 +30,7 @@ import { handleMiscRoutes } from "./server/routes/misc-routes";
import { handleNotificationsConfigRoutes } from "./server/routes/notifications-config-routes";
import { handlePageRoutes } from "./server/routes/page-routes";
import { handlePluginRoutes } from "./server/routes/plugin-routes";
+import { handleFileShareRoutes } from "./server/routes/file-share-routes";
import { handleUsersRoutes } from "./server/routes/users-routes";
import { handleWebSocketClose, handleWebSocketMessage, handleWebSocketOpen } from "./server/routes/websocket-lifecycle-routes";
import { handleWsUpgradeRoutes } from "./server/routes/ws-upgrade-routes";
@@ -146,6 +148,7 @@ const PLUGIN_STATE_PATH = path.join(PLUGIN_ROOT, ".plugin-state.json");
const DATA_DIR = ensureDataDir();
const DEPLOY_ROOT = path.join(DATA_DIR, "deploy");
const WINRE_ROOT = path.join(DATA_DIR, "winre");
+const FILE_SHARE_ROOT = path.join(DATA_DIR, "file-share");
const TLS_CERT_PATH = config.tls.certPath;
const TLS_KEY_PATH = config.tls.keyPath;
@@ -395,6 +398,9 @@ async function startServer() {
securePluginHeaders,
mimeType,
},
+ fileShare: {
+ FILE_SHARE_ROOT,
+ },
misc: {
CORS_HEADERS,
SERVER_VERSION,
@@ -562,6 +568,7 @@ async function startServer() {
handleWinRERoutes,
handleFileDownloadRoutes,
handlePluginRoutes,
+ handleFileShareRoutes,
handleMiscRoutes,
handleAssetsRoutes,
handlePageRoutes,
@@ -587,6 +594,12 @@ async function startServer() {
deleteExpiredBuilds();
logger.info(`[db] Cleaned up expired builds`);
+ const expiredPaths = deleteExpiredSharedFiles();
+ for (const p of expiredPaths) {
+ try { const dir = path.dirname(p); await fs.rm(dir, { recursive: true, force: true }); } catch {}
+ }
+ if (expiredPaths.length) logger.info(`[db] Cleaned up ${expiredPaths.length} expired shared files`);
+
startMaintenanceLoops({
getClients: clientManager.getAllClients,
setOnlineState,
diff --git a/Overlord-Server/src/server/http-dispatch.ts b/Overlord-Server/src/server/http-dispatch.ts
index f89568b..a585203 100644
--- a/Overlord-Server/src/server/http-dispatch.ts
+++ b/Overlord-Server/src/server/http-dispatch.ts
@@ -27,6 +27,7 @@ type HttpDispatchDeps<
TWinRE,
TFileDownload,
TPlugin,
+ TFileShare,
TMisc,
TAssets,
TPage,
@@ -47,6 +48,7 @@ type HttpDispatchDeps<
handleWinRERoutes: RouteHandlerWithServerDeps;
handleFileDownloadRoutes: RouteHandlerWithServerDeps;
handlePluginRoutes: RouteHandlerWithDeps;
+ handleFileShareRoutes: RouteHandlerWithDeps;
handleMiscRoutes: RouteHandlerWithDeps;
handleAssetsRoutes: RouteHandlerWithDeps;
handlePageRoutes: RouteHandlerWithDeps;
@@ -60,6 +62,7 @@ type HttpDispatchDeps<
winre: TWinRE;
fileDownload: TFileDownload;
plugin: TPlugin;
+ fileShare: TFileShare;
misc: TMisc;
assets: TAssets;
page: TPage;
@@ -77,6 +80,7 @@ export function createHttpFetchHandler<
TWinRE,
TFileDownload,
TPlugin,
+ TFileShare,
TMisc,
TAssets,
TPage,
@@ -92,6 +96,7 @@ export function createHttpFetchHandler<
TWinRE,
TFileDownload,
TPlugin,
+ TFileShare,
TMisc,
TAssets,
TPage,
@@ -144,6 +149,9 @@ export function createHttpFetchHandler<
const pluginResponse = await deps.handlePluginRoutes(req, url, deps.routeDeps.plugin);
if (pluginResponse) return pluginResponse;
+ const fileShareResponse = await deps.handleFileShareRoutes(req, url, deps.routeDeps.fileShare);
+ if (fileShareResponse) return fileShareResponse;
+
const miscResponse = await deps.handleMiscRoutes(req, url, deps.routeDeps.misc);
if (miscResponse) return miscResponse;
diff --git a/Overlord-Server/src/server/routes/file-share-routes.ts b/Overlord-Server/src/server/routes/file-share-routes.ts
new file mode 100644
index 0000000..0b4e066
--- /dev/null
+++ b/Overlord-Server/src/server/routes/file-share-routes.ts
@@ -0,0 +1,353 @@
+import fs from "fs/promises";
+import path from "path";
+import { v4 as uuidv4 } from "uuid";
+import { authenticateRequest } from "../../auth";
+import { AuditAction, logAudit } from "../../auditLog";
+import { logger } from "../../logger";
+import {
+ getSharedFile,
+ listSharedFiles,
+ insertSharedFile,
+ deleteSharedFile,
+ updateSharedFile,
+ incrementSharedFileDownloadCount,
+} from "../../db";
+import { getUserById, canUploadFiles } from "../../users";
+
+type FileShareRouteDeps = {
+ FILE_SHARE_ROOT: string;
+};
+
+function guessMimeType(filename: string): string {
+ const ext = path.extname(filename).toLowerCase();
+ const map: Record = {
+ ".txt": "text/plain",
+ ".html": "text/html",
+ ".css": "text/css",
+ ".js": "application/javascript",
+ ".json": "application/json",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".svg": "image/svg+xml",
+ ".pdf": "application/pdf",
+ ".zip": "application/zip",
+ ".gz": "application/gzip",
+ ".tar": "application/x-tar",
+ ".7z": "application/x-7z-compressed",
+ ".rar": "application/vnd.rar",
+ ".exe": "application/vnd.microsoft.portable-executable",
+ ".dll": "application/vnd.microsoft.portable-executable",
+ ".iso": "application/x-iso9660-image",
+ ".mp4": "video/mp4",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".doc": "application/msword",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".xls": "application/vnd.ms-excel",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ".csv": "text/csv",
+ ".xml": "application/xml",
+ };
+ return map[ext] || "application/octet-stream";
+}
+
+export async function handleFileShareRoutes(
+ req: Request,
+ url: URL,
+ deps: FileShareRouteDeps,
+): Promise {
+
+ const infoMatch = url.pathname.match(/^\/api\/file-share\/([^/]+)\/info$/);
+ if (req.method === "GET" && infoMatch) {
+ const fileId = infoMatch[1];
+ const file = getSharedFile(fileId);
+ if (!file) {
+ return Response.json({ error: "File not found" }, { status: 404 });
+ }
+
+ if (file.expiresAt && file.expiresAt < Date.now()) {
+ return Response.json({ error: "File has expired" }, { status: 410 });
+ }
+
+ if (file.maxDownloads !== null && file.downloadCount >= file.maxDownloads) {
+ return Response.json({ error: "Download limit reached" }, { status: 410 });
+ }
+
+ return Response.json({
+ id: file.id,
+ filename: file.filename,
+ size: file.size,
+ mimeType: file.mimeType,
+ hasPassword: !!file.passwordHash,
+ maxDownloads: file.maxDownloads,
+ downloadCount: file.downloadCount,
+ expiresAt: file.expiresAt,
+ createdAt: file.createdAt,
+ uploadedByUsername: file.uploadedByUsername,
+ description: file.description,
+ });
+ }
+
+ const downloadMatch = url.pathname.match(/^\/api\/file-share\/([^/]+)\/download$/);
+ if (req.method === "GET" && downloadMatch) {
+ const fileId = downloadMatch[1];
+ const file = getSharedFile(fileId);
+ if (!file) {
+ return Response.json({ error: "File not found" }, { status: 404 });
+ }
+
+ if (file.expiresAt && file.expiresAt < Date.now()) {
+ return Response.json({ error: "File has expired" }, { status: 410 });
+ }
+
+ if (file.maxDownloads !== null && file.downloadCount >= file.maxDownloads) {
+ return Response.json({ error: "Download limit reached" }, { status: 410 });
+ }
+
+ if (file.passwordHash) {
+ const providedPassword = req.headers.get("X-Download-Password") || url.searchParams.get("password") || "";
+ if (!providedPassword) {
+ return Response.json({ error: "Password required" }, { status: 401 });
+ }
+ const valid = await Bun.password.verify(providedPassword, file.passwordHash);
+ if (!valid) {
+ return Response.json({ error: "Invalid password" }, { status: 403 });
+ }
+ }
+
+ const diskFile = Bun.file(file.storedPath);
+ if (!(await diskFile.exists())) {
+ return Response.json({ error: "File not found on disk" }, { status: 404 });
+ }
+
+ incrementSharedFileDownloadCount(file.id);
+
+ const sanitizedFilename = file.filename.replace(/[^\w.\-() ]/g, "_");
+
+ return new Response(diskFile, {
+ headers: {
+ "Content-Type": file.mimeType || "application/octet-stream",
+ "Content-Disposition": `attachment; filename="${sanitizedFilename}"`,
+ "Content-Length": String(file.size),
+ },
+ });
+ }
+
+ if (!url.pathname.startsWith("/api/file-share")) {
+ return null;
+ }
+
+ let user;
+ try {
+ user = await authenticateRequest(req);
+ } catch {
+ return null;
+ }
+ if (!user) return null;
+
+ if (user.role === "viewer") {
+ return Response.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ if (req.method === "GET" && url.pathname === "/api/file-share") {
+ const files = listSharedFiles();
+ const userCanUpload = canUploadFiles(user.userId, user.role);
+ return Response.json({
+ files: files.map((f) => ({
+ id: f.id,
+ filename: f.filename,
+ size: f.size,
+ mimeType: f.mimeType,
+ uploadedBy: f.uploadedBy,
+ uploadedByUsername: f.uploadedByUsername,
+ hasPassword: !!f.passwordHash,
+ maxDownloads: f.maxDownloads,
+ downloadCount: f.downloadCount,
+ expiresAt: f.expiresAt,
+ createdAt: f.createdAt,
+ description: f.description,
+ })),
+ canUpload: userCanUpload,
+ });
+ }
+
+ if (req.method === "POST" && url.pathname === "/api/file-share/upload") {
+ if (!canUploadFiles(user.userId, user.role)) {
+ return Response.json({ error: "You do not have upload permission" }, { status: 403 });
+ }
+
+ let form: FormData;
+ try {
+ form = await req.formData();
+ } catch {
+ return Response.json({ error: "Invalid form data" }, { status: 400 });
+ }
+
+ const file = form.get("file");
+ if (!(file instanceof File)) {
+ return Response.json({ error: "Missing file" }, { status: 400 });
+ }
+
+ const filename = path.basename(file.name || "upload.bin");
+ const id = uuidv4();
+
+ await fs.mkdir(deps.FILE_SHARE_ROOT, { recursive: true });
+ const folder = path.join(deps.FILE_SHARE_ROOT, id);
+ await fs.mkdir(folder, { recursive: true });
+ const targetPath = path.join(folder, filename);
+
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ await fs.writeFile(targetPath, bytes);
+
+ const password = form.get("password")?.toString() || "";
+ let passwordHash: string | null = null;
+ if (password) {
+ passwordHash = await Bun.password.hash(password, {
+ algorithm: "bcrypt",
+ cost: 10,
+ });
+ }
+
+ const maxDownloadsStr = form.get("maxDownloads")?.toString();
+ let maxDownloads: number | null = null;
+ if (maxDownloadsStr && maxDownloadsStr !== "" && maxDownloadsStr !== "0") {
+ const parsed = parseInt(maxDownloadsStr, 10);
+ if (!isNaN(parsed) && parsed > 0) {
+ maxDownloads = parsed;
+ }
+ }
+
+ const expiresAtStr = form.get("expiresAt")?.toString();
+ let expiresAt: number | null = null;
+ if (expiresAtStr && expiresAtStr !== "") {
+ const parsed = parseInt(expiresAtStr, 10);
+ if (!isNaN(parsed) && parsed > Date.now()) {
+ expiresAt = parsed;
+ }
+ }
+
+ const description = form.get("description")?.toString() || null;
+
+ const dbUser = getUserById(user.userId);
+
+ const record = {
+ id,
+ filename,
+ storedPath: targetPath,
+ size: bytes.length,
+ mimeType: guessMimeType(filename),
+ uploadedBy: user.userId,
+ uploadedByUsername: dbUser?.username || user.username || "unknown",
+ passwordHash,
+ maxDownloads,
+ downloadCount: 0,
+ expiresAt,
+ createdAt: Date.now(),
+ description,
+ };
+
+ insertSharedFile(record);
+
+ logger.info(`[file-share] ${record.uploadedByUsername} uploaded "${filename}" (${bytes.length} bytes) id=${id}`);
+
+ return Response.json({
+ ok: true,
+ id,
+ filename,
+ size: bytes.length,
+ });
+ }
+
+ const deleteMatch = url.pathname.match(/^\/api\/file-share\/([^/]+)$/);
+ if (req.method === "DELETE" && deleteMatch) {
+ const fileId = deleteMatch[1];
+ const file = getSharedFile(fileId);
+ if (!file) {
+ return Response.json({ error: "File not found" }, { status: 404 });
+ }
+
+ if (file.uploadedBy !== user.userId && user.role !== "admin") {
+ return Response.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ try {
+ const folder = path.dirname(file.storedPath);
+ await fs.rm(folder, { recursive: true, force: true });
+ } catch (err) {
+ logger.warn(`[file-share] Failed to remove file from disk: ${file.storedPath}`, err);
+ }
+
+ deleteSharedFile(fileId);
+ logger.info(`[file-share] ${user.username} deleted file "${file.filename}" id=${fileId}`);
+
+ return Response.json({ ok: true });
+ }
+
+ const patchMatch = url.pathname.match(/^\/api\/file-share\/([^/]+)$/);
+ if (req.method === "PATCH" && patchMatch) {
+ const fileId = patchMatch[1];
+ const file = getSharedFile(fileId);
+ if (!file) {
+ return Response.json({ error: "File not found" }, { status: 404 });
+ }
+
+ if (file.uploadedBy !== user.userId && user.role !== "admin") {
+ return Response.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ let body: any;
+ try {
+ body = await req.json();
+ } catch {
+ return Response.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const updates: Record = {};
+
+ if (body.password !== undefined) {
+ if (body.password === "" || body.password === null) {
+ updates.passwordHash = null;
+ } else {
+ updates.passwordHash = await Bun.password.hash(body.password, {
+ algorithm: "bcrypt",
+ cost: 10,
+ });
+ }
+ }
+
+ if (body.maxDownloads !== undefined) {
+ if (body.maxDownloads === null || body.maxDownloads === 0 || body.maxDownloads === "") {
+ updates.maxDownloads = null;
+ } else {
+ const parsed = parseInt(body.maxDownloads, 10);
+ if (!isNaN(parsed) && parsed > 0) {
+ updates.maxDownloads = parsed;
+ }
+ }
+ }
+
+ if (body.expiresAt !== undefined) {
+ if (body.expiresAt === null || body.expiresAt === "") {
+ updates.expiresAt = null;
+ } else {
+ const parsed = parseInt(body.expiresAt, 10);
+ if (!isNaN(parsed)) {
+ updates.expiresAt = parsed;
+ }
+ }
+ }
+
+ if (body.description !== undefined) {
+ updates.description = body.description || null;
+ }
+
+ updateSharedFile(fileId, updates);
+
+ return Response.json({ ok: true });
+ }
+
+ return null;
+}
diff --git a/Overlord-Server/src/server/routes/page-routes.ts b/Overlord-Server/src/server/routes/page-routes.ts
index 6e896ca..d1795bc 100644
--- a/Overlord-Server/src/server/routes/page-routes.ts
+++ b/Overlord-Server/src/server/routes/page-routes.ts
@@ -76,6 +76,7 @@ const STATIC_PAGES: StaticPageDef[] = [
{ path: "/scripts", file: "scripts.html", access: "no-viewer" },
{ path: "/deploy", file: "deploy.html", access: "admin" },
{ path: "/socks5-manager", file: "socks5-manager.html", access: "no-viewer", checkPasswordChange: true },
+ { path: "/file-share", file: "file-share.html", access: "no-viewer", checkPasswordChange: true },
{ path: "/purgatory", file: "purgatory.html", access: "admin-or-operator", checkPasswordChange: true },
];
diff --git a/Overlord-Server/src/server/routes/users-routes.ts b/Overlord-Server/src/server/routes/users-routes.ts
index 5c9e2c8..c6db1f1 100644
--- a/Overlord-Server/src/server/routes/users-routes.ts
+++ b/Overlord-Server/src/server/routes/users-routes.ts
@@ -15,6 +15,7 @@ import {
setUserClientAccessRule,
setUserClientAccessScope,
setUserCanBuild,
+ setUserCanUploadFiles,
updateUserPassword,
updateUserRole,
} from "../../users";
@@ -353,6 +354,34 @@ export async function handleUsersRoutes(
return Response.json({ success: true, canBuild });
}
+ if (req.method === "PUT" && url.pathname.match(/^\/api\/users\/\d+\/can-upload-files$/)) {
+ const authedUser = requirePermission(user, "users:manage");
+ const userId = parseInt(url.pathname.split("/")[3]);
+ const targetUser = getUserById(userId);
+ if (!targetUser) {
+ return Response.json({ error: "User not found" }, { status: 404 });
+ }
+
+ const body = await req.json();
+ const canUploadFiles = !!body?.canUploadFiles;
+ const result = setUserCanUploadFiles(userId, canUploadFiles);
+ if (!result.success) {
+ return Response.json({ error: result.error }, { status: 400 });
+ }
+
+ const ip = server.requestIP(req)?.address || "unknown";
+ logAudit({
+ timestamp: Date.now(),
+ username: authedUser.username,
+ ip,
+ action: AuditAction.COMMAND,
+ details: `${canUploadFiles ? "Granted" : "Revoked"} file upload permission for ${targetUser.username}`,
+ success: true,
+ });
+
+ return Response.json({ success: true, canUploadFiles });
+ }
+
return new Response("Not found", { status: 404 });
} catch (error) {
if (error instanceof Response) {
diff --git a/Overlord-Server/src/users.ts b/Overlord-Server/src/users.ts
index aab5332..d2c5b02 100644
--- a/Overlord-Server/src/users.ts
+++ b/Overlord-Server/src/users.ts
@@ -23,6 +23,7 @@ export interface User {
must_change_password: number;
client_scope: ClientAccessScope;
can_build: number;
+ can_upload_files: number;
telegram_chat_id: string | null;
}
@@ -35,6 +36,7 @@ export interface UserInfo {
created_by: string | null;
client_scope: ClientAccessScope;
can_build: number;
+ can_upload_files: number;
telegram_chat_id: string | null;
}
@@ -157,6 +159,23 @@ for (const col of notificationColumns) {
}
}
+try {
+ db.exec(
+ `ALTER TABLE users ADD COLUMN can_upload_files INTEGER NOT NULL DEFAULT 0`,
+ );
+ logger.info("[users] Added can_upload_files column to existing database");
+
+ try {
+ db.exec(`UPDATE users SET can_upload_files=1 WHERE role='admin'`);
+ } catch (err: any) {
+ logger.error("[users] Failed to backfill admin can_upload_files:", err);
+ }
+} catch (err: any) {
+ if (!err.message?.includes("duplicate column name")) {
+ logger.error("[users] Migration error:", err);
+ }
+}
+
const userCount = db.prepare("SELECT COUNT(*) as count FROM users").get() as {
count: number;
};
@@ -172,8 +191,8 @@ if (userCount.count === 0) {
});
db.prepare(
- "INSERT INTO users (username, password_hash, role, created_at, created_by, must_change_password, client_scope, can_build) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
- ).run(initialUsername, defaultPassword, "admin", Date.now(), "system", 1, "all", 1);
+ "INSERT INTO users (username, password_hash, role, created_at, created_by, must_change_password, client_scope, can_build, can_upload_files) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ ).run(initialUsername, defaultPassword, "admin", Date.now(), "system", 1, "all", 1, 1);
const createdUser = db
.prepare("SELECT * FROM users WHERE username = ?")
@@ -209,7 +228,7 @@ export function getUserByUsername(username: string): User | null {
export function listUsers(): UserInfo[] {
const users = db
.prepare(
- "SELECT id, username, role, created_at, last_login, created_by, client_scope, can_build, telegram_chat_id FROM users ORDER BY created_at DESC",
+ "SELECT id, username, role, created_at, last_login, created_by, client_scope, can_build, can_upload_files, telegram_chat_id FROM users ORDER BY created_at DESC",
)
.all() as UserInfo[];
return users;
@@ -425,9 +444,9 @@ export async function createUser(
const result = db
.prepare(
- "INSERT INTO users (username, password_hash, role, created_at, created_by, client_scope, can_build) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO users (username, password_hash, role, created_at, created_by, client_scope, can_build, can_upload_files) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
)
- .run(username, passwordHash, role, Date.now(), createdBy, role === "admin" ? "all" : "none", role === "admin" || role === "operator" ? 1 : 0);
+ .run(username, passwordHash, role, Date.now(), createdBy, role === "admin" ? "all" : "none", role === "admin" || role === "operator" ? 1 : 0, role === "admin" ? 1 : 0);
invalidateNotificationDeliveryCache();
@@ -584,6 +603,25 @@ export function setUserCanBuild(
}
}
+export function canUploadFiles(userId: number, role: UserRole): boolean {
+ if (role === "admin") return true;
+ const user = getUserById(userId);
+ return user ? user.can_upload_files === 1 : false;
+}
+
+export function setUserCanUploadFiles(
+ userId: number,
+ canUpload: boolean,
+): { success: boolean; error?: string } {
+ try {
+ db.prepare("UPDATE users SET can_upload_files = ? WHERE id = ?").run(canUpload ? 1 : 0, userId);
+ return { success: true };
+ } catch (err: any) {
+ logger.error("[users] setUserCanUploadFiles error:", err);
+ return { success: false, error: err.message || "Failed to update upload permission" };
+ }
+}
+
export function setUserTelegramChatId(
userId: number,
chatId: string | null,
|