From 798e09b652a06d16aeb791e739bd5efd46034041 Mon Sep 17 00:00:00 2001 From: xianguo Date: Mon, 22 Jun 2026 15:16:25 +0800 Subject: [PATCH] add configurable public server URLs --- README.md | 1 + internal/drop/config.go | 2 + internal/drop/config_test.go | 16 ++++ internal/drop/server.go | 33 +++++++- internal/drop/server_test.go | 59 +++++++++++++ web/app.js | 59 +++++++++++-- web/app.test.mjs | 159 +++++++++++++++++++++++++++++++++++ web/index.html | 5 +- 8 files changed, 325 insertions(+), 9 deletions(-) create mode 100644 web/app.test.mjs diff --git a/README.md b/README.md index 1767646..5f35d10 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Internal Drop is a small LAN text and file transfer app for 2 to 3 internal user | `INTERNAL_DROP_MAX_FILE_SIZE` | `1073741824` | Max single upload bytes | | `INTERNAL_DROP_FILE_TTL` | `2h` | Transfer expiry duration | | `INTERNAL_DROP_ALLOWED_CIDRS` | empty | Optional comma-separated client CIDR allowlist, for example `192.168.1.0/24,10.0.0.0/8` | +| `INTERNAL_DROP_PUBLIC_URLS` | empty | Optional comma-separated URLs to show first in the UI, for example `http://10.20.8.138:10051,https://drop.company.lan` | ## Local Build diff --git a/internal/drop/config.go b/internal/drop/config.go index deddf6a..1b3a7dd 100644 --- a/internal/drop/config.go +++ b/internal/drop/config.go @@ -13,6 +13,7 @@ type Config struct { MaxFileSize int64 FileTTL time.Duration AllowedCIDRs []string + PublicURLs []string } func DefaultConfig() Config { @@ -22,6 +23,7 @@ func DefaultConfig() Config { MaxFileSize: envInt64("INTERNAL_DROP_MAX_FILE_SIZE", 1<<30), FileTTL: envDuration("INTERNAL_DROP_FILE_TTL", 2*time.Hour), AllowedCIDRs: envList("INTERNAL_DROP_ALLOWED_CIDRS"), + PublicURLs: envList("INTERNAL_DROP_PUBLIC_URLS"), } } diff --git a/internal/drop/config_test.go b/internal/drop/config_test.go index 249e893..f5f58f7 100644 --- a/internal/drop/config_test.go +++ b/internal/drop/config_test.go @@ -8,3 +8,19 @@ func TestDefaultConfigUsesPort10051(t *testing.T) { t.Fatalf("default addr = %q, want :10051", cfg.Addr) } } + +func TestDefaultConfigReadsPublicURLs(t *testing.T) { + t.Setenv("INTERNAL_DROP_PUBLIC_URLS", "http://10.20.8.138:10051, https://drop.company.lan ") + + cfg := DefaultConfig() + + want := []string{"http://10.20.8.138:10051", "https://drop.company.lan"} + if len(cfg.PublicURLs) != len(want) { + t.Fatalf("public urls = %#v, want %#v", cfg.PublicURLs, want) + } + for i := range want { + if cfg.PublicURLs[i] != want[i] { + t.Fatalf("public urls = %#v, want %#v", cfg.PublicURLs, want) + } + } +} diff --git a/internal/drop/server.go b/internal/drop/server.go index 2a714b2..de06952 100644 --- a/internal/drop/server.go +++ b/internal/drop/server.go @@ -105,10 +105,20 @@ func (a *App) Routes() http.Handler { mux.HandleFunc("/api/health", a.handleHealth) mux.HandleFunc("/api/server-info", a.handleServerInfo) mux.HandleFunc("/ws", a.handleWebSocket) - mux.Handle("/", http.FileServer(a.static)) + mux.Handle("/", a.staticHandler()) return a.withNetworkPolicy(mux) } +func (a *App) staticHandler() http.Handler { + fileServer := http.FileServer(a.static) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store, max-age=0") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Expires", "0") + fileServer.ServeHTTP(w, r) + }) +} + func (a *App) StartCleaner(stop <-chan struct{}) { ticker := time.NewTicker(time.Minute) defer ticker.Stop() @@ -273,7 +283,7 @@ func (a *App) handleServerInfo(w http.ResponseWriter, r *http.Request) { ListenAddr: a.cfg.Addr, Port: port, CurrentURL: current, - URLs: uniqueStrings(localServerURLs(port)), + URLs: uniqueStrings(append(publicServerURLs(a.cfg.PublicURLs, port), localServerURLs(port)...)), }) } @@ -500,6 +510,25 @@ func localServerURLs(port string) []string { return urls } +func publicServerURLs(values []string, port string) []string { + urls := make([]string, 0, len(values)) + for _, value := range values { + value = strings.TrimSpace(value) + if value == "" { + continue + } + if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") { + urls = append(urls, value) + continue + } + if !strings.Contains(value, ":") && port != "" { + value = net.JoinHostPort(value, port) + } + urls = append(urls, "http://"+value) + } + return urls +} + func isPrivateLANIPv4(ip net.IP) bool { ip = ip.To4() if ip == nil { diff --git a/internal/drop/server_test.go b/internal/drop/server_test.go index 5322656..88a795c 100644 --- a/internal/drop/server_test.go +++ b/internal/drop/server_test.go @@ -9,6 +9,7 @@ import ( "os" "strings" "testing" + "testing/fstest" "time" ) @@ -85,6 +86,64 @@ func TestServerInfoAPIShowsCurrentURLAndPort(t *testing.T) { } } +func TestServerInfoAPIPrioritizesConfiguredPublicURLs(t *testing.T) { + app := NewApp( + Config{ + Addr: ":10051", + TempDir: t.TempDir(), + MaxFileSize: 1024, + FileTTL: time.Hour, + PublicURLs: []string{"http://10.20.8.138:10051", "https://drop.company.lan"}, + }, + nil, + ) + req := httptest.NewRequest(http.MethodGet, "/api/server-info", nil) + rec := httptest.NewRecorder() + + app.Routes().ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } + var info serverInfoResponse + if err := json.NewDecoder(rec.Body).Decode(&info); err != nil { + t.Fatalf("decode server info: %v", err) + } + if len(info.URLs) < 2 { + t.Fatalf("urls = %#v, want configured public urls", info.URLs) + } + want := []string{"http://10.20.8.138:10051", "https://drop.company.lan"} + for i := range want { + if info.URLs[i] != want[i] { + t.Fatalf("urls = %#v, want configured public urls first %#v", info.URLs, want) + } + } +} + +func TestStaticAssetsAreServedWithoutBrowserCaching(t *testing.T) { + app := NewApp( + Config{Addr: ":10051", TempDir: t.TempDir(), MaxFileSize: 1024, FileTTL: time.Hour}, + http.FS(fstest.MapFS{"app.js": {Data: []byte("console.log('ok')")}}), + ) + req := httptest.NewRequest(http.MethodGet, "/app.js", nil) + rec := httptest.NewRecorder() + + app.Routes().ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } + if got := rec.Header().Get("Cache-Control"); got != "no-store, max-age=0" { + t.Fatalf("Cache-Control = %q, want no-store, max-age=0", got) + } + if got := rec.Header().Get("Pragma"); got != "no-cache" { + t.Fatalf("Pragma = %q, want no-cache", got) + } + if got := rec.Header().Get("Expires"); got != "0" { + t.Fatalf("Expires = %q, want 0", got) + } +} + func TestPrivateLANIPv4Filter(t *testing.T) { cases := map[string]bool{ "10.0.1.5": true, diff --git a/web/app.js b/web/app.js index abd82ff..0fa1110 100644 --- a/web/app.js +++ b/web/app.js @@ -17,6 +17,7 @@ const els = { saveName: document.querySelector("#saveName"), regenCode: document.querySelector("#regenCode"), serverAddress: document.querySelector("#serverAddress"), + copyServerAddress: document.querySelector("#copyServerAddress"), connectionState: document.querySelector("#connectionState"), selectedPeer: document.querySelector("#selectedPeer"), dropZone: document.querySelector("#dropZone"), @@ -102,6 +103,7 @@ function bindEvents() { }); els.saveName.addEventListener("click", saveName); els.regenCode.addEventListener("click", regenerateCode); + els.copyServerAddress.addEventListener("click", copyServerAddress); els.sendText.addEventListener("click", sendText); els.fileInput.addEventListener("change", () => { const file = els.fileInput.files[0]; @@ -291,9 +293,12 @@ function addIncomingText(event) { copy.type = "button"; copy.textContent = "复制"; copy.className = "secondary"; - copy.addEventListener("click", () => { - navigator.clipboard.writeText(text); - updateTransferActivity(event.transfer, "已复制", "ok"); + copy.addEventListener("click", async () => { + if (await copyTextToClipboard(text)) { + updateTransferActivity(event.transfer, "已复制", "ok"); + } else { + updateTransferActivity(event.transfer, "复制失败", "bad"); + } }); setActivityActions(item, [copy]); } @@ -378,14 +383,22 @@ function renderIdentity() { function renderServerInfo() { const info = state.serverInfo; if (!info) return; - const urls = (info.urls || []).filter((url) => /^http:\/\/(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(url)); + const urls = (info.urls || []).filter(Boolean); if (urls.length === 0) { - els.serverAddress.textContent = "未检测到内网 IP"; + els.serverAddress.textContent = "未检测到可用地址"; els.serverAddress.title = ""; + els.copyServerAddress.disabled = true; return; } els.serverAddress.textContent = urls[0]; els.serverAddress.title = urls.join("\n"); + els.copyServerAddress.disabled = false; +} + +async function copyServerAddress() { + const text = els.serverAddress.textContent.trim(); + if (!text || text === "检测中" || text.startsWith("未检测到")) return false; + return copyTextToClipboard(text); } function renderUsers() { @@ -489,6 +502,42 @@ function setActivityActions(item, buttons) { for (const button of buttons) actions.append(button); } +async function copyTextToClipboard(text) { + if (globalThis.isSecureContext === false) { + return copyTextWithSelection(text); + } + + const clipboard = navigator.clipboard; + if (clipboard?.writeText) { + try { + await clipboard.writeText(text); + return true; + } catch {} + } + + return copyTextWithSelection(text); +} + +function copyTextWithSelection(text) { + const textArea = document.createElement("textarea"); + textArea.value = text; + textArea.setAttribute("readonly", ""); + textArea.style.position = "fixed"; + textArea.style.top = "-9999px"; + textArea.style.left = "-9999px"; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + textArea.setSelectionRange(0, text.length); + try { + return document.execCommand("copy"); + } catch { + return false; + } finally { + document.body.removeChild(textArea); + } +} + function updateTransferActivity(transfer, status, tone) { if (!transfer) return; const item = upsertActivity({ diff --git a/web/app.test.mjs b/web/app.test.mjs new file mode 100644 index 0000000..6a1389c --- /dev/null +++ b/web/app.test.mjs @@ -0,0 +1,159 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; + +function loadAppContext(overrides = {}) { + const selectors = new Map(); + const body = { + children: [], + appendChild(node) { + node.parentElement = this; + this.children.push(node); + return node; + }, + removeChild(node) { + this.children = this.children.filter((child) => child !== node); + node.parentElement = null; + return node; + } + }; + const document = { + body, + userActivation: true, + execCommand(command) { + if (command !== "copy") return false; + if (!this.userActivation) return false; + this.copiedText = this.activeElement?.value || ""; + return true; + }, + querySelector(selector) { + if (!selectors.has(selector)) { + selectors.set(selector, makeElement()); + } + return selectors.get(selector); + }, + querySelectorAll() { + return []; + }, + createElement(tagName) { + const element = makeElement(tagName); + element.ownerDocument = document; + return element; + } + }; + const context = { + document, + localStorage: { + getItem() { + return ""; + }, + setItem() {} + }, + navigator: {}, + isSecureContext: false, + location: { protocol: "http:", host: "192.168.1.10:10051" }, + setTimeout() {}, + clearTimeout() {}, + WebSocket: { OPEN: 1 } + }; + Object.assign(context, overrides); + const source = readFileSync(new URL("./app.js", import.meta.url), "utf8") + .replace("const state = {", "globalThis.state = {") + .replace(/boot\(\)\.catch\([\s\S]*?\n\}\);?\s*$/, ""); + vm.runInNewContext(source, context); + return context; +} + +function makeElement(tagName = "div") { + return { + tagName, + children: [], + className: "", + style: {}, + value: "", + parentElement: null, + append(...nodes) { + for (const node of nodes) { + node.parentElement = this; + this.children.push(node); + } + }, + focus() { + if (this.ownerDocument) this.ownerDocument.activeElement = this; + }, + select() { + this.selected = true; + }, + setSelectionRange(start, end) { + this.selectionStart = start; + this.selectionEnd = end; + }, + setAttribute() {}, + addEventListener() {}, + querySelector() { + return makeElement(); + } + }; +} + +test("copyTextToClipboard falls back when navigator.clipboard is unavailable", async () => { + const context = loadAppContext(); + const text = '{\n "copy": "json text"\n}'; + + const copied = await context.copyTextToClipboard(text); + + assert.equal(copied, true); + assert.equal(context.document.copiedText, text); +}); + +test("copyTextToClipboard uses the synchronous fallback first on insecure remote pages", async () => { + const context = loadAppContext(); + context.navigator.clipboard = { + async writeText() { + context.document.userActivation = false; + throw new Error("Clipboard API blocked on insecure context"); + } + }; + const text = `[ + { + "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImFlNjc5NWRjLTRiYWUtNDE4YS04NjVkLTA4YTY0MzllZWRhNiIsInR5cCI6IkpXVCJ9..UVl-YCSs3lfN6QLMGH03qfE3pBH7YYuEV2be8hV6VQDFRX0-bMMlWvB9sE0DCnfnDSRCOw4_fh7V72fg", + "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImFlNjc5NWRjLTRiYWUtNDE4YS04NjVkLTA4YTY0MzllZWRhNiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiaHR0cHM6LykJzi2DPDA1mEUCMRCyg_3tGuskm0bQlbo0_ttDv53sF-fO-7nEPHqBDO7KpKPQPvG9w3HdTXtxPktHNkcmO5453BHc61ONukP2QJUp-OBv6T2mvC4ZKq6TlgOaXxrH32sMV4VtixWDbmmlrZ0zbXD72_WMS9mWR7wQLDN21-fCyaLma0cbLuWyxSqyWvkMIeuBEnFcTZVAcrgwd1lTw0e-pdsfVGyDiqDg2ZNs_Bk7vdk8c3VVcpZA5o7SEZUEaJRN-9ncI11INQpf5BubH8zCMnFa5u2fLfvtThZ_JON75mGKPBdwJYpY5FMjscBipu95RXf4ch0PQieCSoROx21YI6z7gSvvMHL-rCc", + "refresh_token": "rt.1.AACMpNpZuZ1c2Q0I9Bdcv7uo-5HKMEM3oz3XDEe_94-NGxq9TPQODzZ6SzYo66U6Ef4Efyub2ocxy4NrJRqtzz-ZthgvY6SG4PvQJYdUH9MZEwFCRsq22FTb__oE_t_QGVqGSbNIhZ2XhT8Lzvb7gI9utaKG9uH3P1zofogkRXlC3Xb8zd8okhjRl8QDFz8", + "account_id": "c1f", + "last_refresh": "", + "email": "l, + "type": "", + "expired": "2Z" + } +]`; + + const copied = await context.copyTextToClipboard(text); + + assert.equal(copied, true); + assert.equal(context.document.copiedText, text); +}); + +test("renderServerInfo displays configured public URLs without private LAN filtering", () => { + const context = loadAppContext(); + const serverAddress = context.document.querySelector("#serverAddress"); + context.state.serverInfo = { + urls: ["https://drop.company.lan", "http://10.20.8.138:10051"] + }; + + context.renderServerInfo(); + + assert.equal(serverAddress.textContent, "https://drop.company.lan"); + assert.equal(serverAddress.title, "https://drop.company.lan\nhttp://10.20.8.138:10051"); +}); + +test("copyServerAddress copies the visible server URL", async () => { + const context = loadAppContext(); + const serverAddress = context.document.querySelector("#serverAddress"); + serverAddress.textContent = "http://10.20.8.138:10051"; + + const copied = await context.copyServerAddress(); + + assert.equal(copied, true); + assert.equal(context.document.copiedText, "http://10.20.8.138:10051"); +}); diff --git a/web/index.html b/web/index.html index acdf7b4..c039359 100644 --- a/web/index.html +++ b/web/index.html @@ -92,12 +92,13 @@ - +