AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(desktop): upload images to CloudFlare ImgBed (#740)
yulei666261161314b86
diff --git a/README.ja.md b/README.ja.mdindex 865b5a78..0c8ab1fc 100644--- a/README.ja.md+++ b/README.ja.md@@ -195,7 +195,8 @@ curl -fsSL https://edgeever.org/install.sh | bash### ストレージ拡張とサードパーティ画像ホスティング- **OSS オブジェクトストレージ**:インスタンスのオーナーは **設定 → 詳細 → OSS オブジェクトストレージ** で S3 互換ストレージを設定できます。切り替えは既存添付を移さず、影響しません。-- **デスクトップ版 PicGo 連携**:デスクトップ版は、このパソコンまたは信頼できる別のマシン(NAS など)の PicGo / PicList に挿入画像を渡し、GitHub、SM.MS、又拍雲、七牛雲や自前ホストへアップロードできます。+- **デスクトップ版 PicGo 連携**:デスクトップ版は、このパソコンまたは信頼できる別のマシン(NAS など)の PicGo / PicList に挿入画像を渡し、GitHub、SM.MS、又拍雲、七牛雲や自前ホストへアップロードできます。アドレスは `/upload` で終われば良いので、リバースプロキシ配下の PicList も使えます。+- **デスクトップ版 CloudFlare ImgBed 連携**:デスクトップ版は、API トークンを使って挿入画像を自前の [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed) に直接アップロードすることもできます。アップロード先フォルダーには `{Y}/{m}/{d}` や `{memoId}` など PicList 形式のプレースホルダーを使えます。### プラグインとカスタムテーマdiff --git a/README.md b/README.mdindex df9d1aec..3d4199ca 100644--- a/README.md+++ b/README.md@@ -196,7 +196,8 @@ The instance administrator can create, disable, or reset member accounts in **Pr### Storage Extension & Third-Party Image Hosting- **OSS Object Storage**: The instance owner can configure S3-compatible object storage under **Settings → Advanced → OSS object storage**. Changing storage does not migrate or affect existing attachments.-- **Desktop PicGo integration**: The desktop app can hand inserted images to a PicGo or PicList server on this computer or on another machine you trust, such as a NAS. That server uploads them to GitHub, SM.MS, Upyun, Qiniu, or a custom image host.+- **Desktop PicGo integration**: The desktop app can hand inserted images to a PicGo or PicList server on this computer or on another machine you trust, such as a NAS. That server uploads them to GitHub, SM.MS, Upyun, Qiniu, or a custom image host. The address only needs to end with `/upload`, so a PicList behind a reverse proxy works too.+- **Desktop CloudFlare ImgBed**: The desktop app can also upload inserted images straight to your self-hosted [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed) with an API token. The upload folder accepts PicList-style placeholders such as `{Y}/{m}/{d}` and `{memoId}`.### Plugins and Themesdiff --git a/README.pl-PL.md b/README.pl-PL.mdindex 95f57c83..9d192ee3 100644--- a/README.pl-PL.md+++ b/README.pl-PL.md@@ -196,7 +196,8 @@ Administrator może tworzyć i wyłączać konta oraz resetować ich hasła w **### Rozszerzenia pamięci masowej i zewnętrzny hosting obrazów- **Magazyn obiektów OSS**: Właściciel instancji może skonfigurować magazyn zgodny z S3 w **Profil → Zaawansowane → Magazyn obiektów OSS**. Zmiana magazynu nie przenosi istniejących załączników ani ich nie modyfikuje.-- **Integracja z PicGo na komputerze**: Aplikacja desktopowa może przekazać wstawiane obrazy do PicGo lub PicList na tym komputerze albo na innej zaufanej maszynie, na przykład NAS. Serwer wysyła je do GitHuba, SM.MS, Upyun, Qiniu lub własnego hostingu.+- **Integracja z PicGo na komputerze**: Aplikacja desktopowa może przekazać wstawiane obrazy do PicGo lub PicList na tym komputerze albo na innej zaufanej maszynie, na przykład NAS. Serwer wysyła je do GitHuba, SM.MS, Upyun, Qiniu lub własnego hostingu. Adres musi tylko kończyć się na `/upload`, więc działa też PicList za odwrotnym proxy.+- **CloudFlare ImgBed na komputerze**: Aplikacja desktopowa może też przesyłać wstawiane obrazy bezpośrednio do własnego [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed) przy użyciu tokenu API. Folder docelowy obsługuje symbole zastępcze w stylu PicList, np. `{Y}/{m}/{d}` i `{memoId}`.### Wtyczki i motywydiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 3d0ca15a..1f422d7e 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -194,7 +194,8 @@ curl -fsSL https://edgeever.org/install.sh | bash### 存储扩展与第三方图床- **OSS 对象存储**:实例 Owner 可在**设置 → 高级设置 → OSS 对象存储**中配置兼容 S3 API 的对象存储。切换存储不会迁移或影响已有附件。-- **桌面端 PicGo 图床**:桌面端可以把新插入的图片交给本机或你信任的远程 PicGo、PicList 服务(例如 NAS),再由它上传到 GitHub、SM.MS、又拍云、七牛云或自建图床。+- **桌面端 PicGo 图床**:桌面端可以把新插入的图片交给本机或你信任的远程 PicGo、PicList 服务(例如 NAS),再由它上传到 GitHub、SM.MS、又拍云、七牛云或自建图床。地址只需以 `/upload` 结尾,经过反向代理的 PicList 也能使用。+- **桌面端 CloudFlare ImgBed 图床**:桌面端也可以用 API Token 把新插入的图片直接上传到你自建的 [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed)。上传目录支持 `{Y}/{m}/{d}`、`{memoId}` 等 PicList 风格的占位符。### 插件与个性化主题diff --git a/README.zh-TW.md b/README.zh-TW.mdindex 4a21c157..3532b24d 100644--- a/README.zh-TW.md+++ b/README.zh-TW.md@@ -194,7 +194,8 @@ curl -fsSL https://edgeever.org/install.sh | bash### 儲存擴充與第三方圖床- **OSS 物件儲存**:實例 Owner 可在**設定 → 進階設定 → OSS 物件儲存**中設定相容 S3 API 的物件儲存。切換儲存不會遷移或影響既有附件。-- **桌面端 PicGo 圖床**:桌面端可以把新插入的圖片交給本機或你信任的遠端 PicGo、PicList 服務(例如 NAS),再由它上傳到 GitHub、SM.MS、又拍雲、七牛雲或自建圖床。+- **桌面端 PicGo 圖床**:桌面端可以把新插入的圖片交給本機或你信任的遠端 PicGo、PicList 服務(例如 NAS),再由它上傳到 GitHub、SM.MS、又拍雲、七牛雲或自建圖床。位址只需以 `/upload` 結尾,經過反向代理的 PicList 也能使用。+- **桌面端 CloudFlare ImgBed 圖床**:桌面端也可以用 API Token 把新插入的圖片直接上傳到你自建的 [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed)。上傳目錄支援 `{Y}/{m}/{d}`、`{memoId}` 等 PicList 風格的佔位符。### 外掛與個人化主題diff --git a/apps/desktop/src/main/imgbed.mjs b/apps/desktop/src/main/imgbed.mjsnew file mode 100644index 00000000..8fc91009--- /dev/null+++ b/apps/desktop/src/main/imgbed.mjs@@ -0,0 +1,106 @@+// CloudFlare ImgBed upload bridge. The renderer expands the upload folder in the+// user's local time; this module re-validates every field before posting bytes.+import { lookup } from "node:dns/promises";+import { assertHostShape, assertImageHostAllowed, postImageHostJson } from "./picgo.mjs";++const ADDRESS_ERROR = "Use a CloudFlare ImgBed address such as https://img.example.com";+const LABEL = "ImgBed";+export const IMGBED_NAME_TYPES = ["default", "index", "origin", "short"];+// Defaults follow the ImgBed upload API: telegram channel with server compression on.+export const IMGBED_UPLOAD_CHANNELS = ["telegram", "cfr2", "s3", "discord", "huggingface", "webdav"];+export const IMGBED_MAX_IMAGE_BYTES = 50 * 1024 * 1024;+// 1×1 transparent PNG used by the connection test.+const TEST_IMAGE = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), (c) => c.charCodeAt(0));++// Accepts the site root or a full .../upload address and returns the upload URL.+export const normalizeImgBedEndpoint = (value) => {+ let url;+ try { url = new URL(String(value ?? "").trim()); }+ catch { throw new Error(ADDRESS_ERROR); }+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.search) {+ throw new Error(ADDRESS_ERROR);+ }+ assertHostShape(url.hostname, ADDRESS_ERROR);+ const base = url.pathname.replace(/\/+$/, "").replace(/\/upload$/, "");+ url.pathname = `${base}/upload`;+ return url;+};++export const normalizeImgBedToken = (value) => {+ if (typeof value !== "string") throw new Error("ImgBed API token is invalid");+ const token = value.trim();+ // oxlint-disable-next-line no-control-regex -- rejects control characters and spaces in the ImgBed token+ if (!token || token.length > 1024 || /[\u0000- \u007f]/.test(token)) throw new Error("ImgBed API token is invalid");+ return token;+};++// The folder arrives already expanded. Keep it a plain relative path.+export const normalizeImgBedFolder = (value) => {+ if (value == null || value === "") return "";+ if (typeof value !== "string" || value.length > 200) throw new Error("ImgBed upload folder is invalid");+ // oxlint-disable-next-line no-control-regex -- rejects control characters in the ImgBed upload folder+ if (/[\u0000-\u001f\u007f\\?#%<>:*|"{}]/.test(value)) throw new Error("ImgBed upload folder is invalid");+ const segments = value.split("/").map((segment) => segment.trim()).filter(Boolean);+ if (segments.some((segment) => segment === "." || segment === "..")) throw new Error("ImgBed upload folder is invalid");+ return segments.join("/");+};++const buildUploadUrl = (input) => {+ const url = normalizeImgBedEndpoint(input.endpoint);+ const folder = normalizeImgBedFolder(input.uploadFolder);+ const nameType = input.nameType ?? "default";+ if (!IMGBED_NAME_TYPES.includes(nameType)) throw new Error("ImgBed file naming is invalid");+ const channel = input.uploadChannel ?? "telegram";+ if (!IMGBED_UPLOAD_CHANNELS.includes(channel)) throw new Error("ImgBed upload channel is invalid");+ if (input.serverCompress != null && typeof input.serverCompress !== "boolean") throw new Error("ImgBed server compression is invalid");+ url.searchParams.set("uploadChannel", channel);+ url.searchParams.set("serverCompress", String(input.serverCompress ?? true));+ url.searchParams.set("uploadNameType", nameType);+ if (folder) url.searchParams.set("uploadFolder", folder);+ return url;+};++// Prefer publicUrl; otherwise resolve src against the ImgBed site.+const resultUrl = (data, uploadUrl) => {+ const item = Array.isArray(data) && data.length === 1 ? data[0] : null;+ const raw = typeof item?.publicUrl === "string" && item.publicUrl ? item.publicUrl : item?.src;+ if (typeof raw !== "string" || !raw) throw new Error("ImgBed did not return an uploaded image URL");+ let url;+ try { url = new URL(raw, uploadUrl); }+ catch { throw new Error("ImgBed returned an invalid image URL"); }+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {+ throw new Error("ImgBed returned an invalid image URL");+ }+ return url.href;+};++const post = async (input, file, filename, { fetchImpl, timeoutMs, lookupImpl }) => {+ const url = buildUploadUrl(input);+ const token = normalizeImgBedToken(input.token);+ await assertImageHostAllowed(url.hostname, lookupImpl, { label: LABEL, message: ADDRESS_ERROR });+ const form = new FormData();+ form.append("file", file, filename);+ let data;+ try {+ data = await postImageHostJson(url, form, fetchImpl, timeoutMs, { label: LABEL, headers: { Authorization: `Bearer ${token}` } });+ } catch (error) {+ if (/HTTP (401|403)$/.test(String(error?.message))) throw new Error("ImgBed rejected the API token");+ throw error;+ }+ return { url: resultUrl(data, url) };+};++// ImgBed has no heartbeat, so the test uploads a 1×1 PNG to the configured folder.+export const testImgBedConnection = async (input, { fetchImpl = fetch, timeoutMs = 15000, lookupImpl = lookup } = {}) => {+ await post(input, new Blob([TEST_IMAGE], { type: "image/png" }), "edgeever-connection-test.png", { fetchImpl, timeoutMs, lookupImpl });+ return true;+};++export const uploadImgBedImage = async (input, { fetchImpl = fetch, timeoutMs = 60000, lookupImpl = lookup } = {}) => {+ const bytes = input.bytes;+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > IMGBED_MAX_IMAGE_BYTES+ || typeof input.mimeType !== "string" || !input.mimeType.startsWith("image/")) {+ throw new Error("ImgBed requires an image of up to 50 MB");+ }+ return post(input, new Blob([bytes], { type: input.mimeType }), String(input.filename || "image.png"), { fetchImpl, timeoutMs, lookupImpl });+};diff --git a/apps/desktop/src/main/imgbed.test.mjs b/apps/desktop/src/main/imgbed.test.mjsnew file mode 100644index 00000000..a6630311--- /dev/null+++ b/apps/desktop/src/main/imgbed.test.mjs@@ -0,0 +1,98 @@+import { afterEach, expect, test } from "bun:test";+import { normalizeImgBedEndpoint, normalizeImgBedFolder, normalizeImgBedToken, testImgBedConnection, uploadImgBedImage } from "./imgbed.mjs";++const servers = [];+afterEach(() => { for (const server of servers.splice(0)) server.stop(true); });+const serve = (handler) => {+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler });+ servers.push(server);+ return `http://127.0.0.1:${server.port}`;+};+const image = (endpoint, extra = {}) => ({+ endpoint, token: "imgbed-token", uploadFolder: "notes/2026/10", nameType: "default",+ filename: "截图.png", mimeType: "image/png", bytes: new Uint8Array([137, 80, 78, 71]), ...extra,+});++test("posts the image with bearer token, folder and naming, and prefers publicUrl", async () => {+ const endpoint = serve(async (request) => {+ const url = new URL(request.url);+ expect(url.pathname).toBe("/upload");+ expect(url.searchParams.get("uploadFolder")).toBe("notes/2026/10");+ expect(url.searchParams.get("uploadNameType")).toBe("short");+ expect(url.searchParams.get("uploadChannel")).toBe("cfr2");+ expect(url.searchParams.get("serverCompress")).toBe("false");+ expect(request.headers.get("authorization")).toBe("Bearer imgbed-token");+ const file = (await request.formData()).get("file");+ expect(file.name).toBe("截图.png");+ expect(file.type).toBe("image/png");+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(new Uint8Array([137, 80, 78, 71]));+ return Response.json([{ src: "/file/abc_截图.png", publicUrl: "https://cdn.example.com/abc.png" }]);+ });+ expect(await uploadImgBedImage(image(endpoint, { nameType: "short", uploadChannel: "cfr2", serverCompress: false }))).toEqual({ url: "https://cdn.example.com/abc.png" });+});++test("resolves src against the ImgBed site and omits an empty folder", async () => {+ const endpoint = serve((request) => {+ const params = new URL(request.url).searchParams;+ expect(params.has("uploadFolder")).toBe(false);+ // Unset options follow the ImgBed API defaults.+ expect(params.get("uploadChannel")).toBe("telegram");+ expect(params.get("serverCompress")).toBe("true");+ return Response.json([{ src: "/file/notes/abc.png" }]);+ });+ expect(await uploadImgBedImage(image(`${endpoint}/upload`, { uploadFolder: "" }))).toEqual({ url: `${endpoint}/file/notes/abc.png` });+});++test("connection test uploads a tiny PNG to the configured folder", async () => {+ const seen = [];+ const endpoint = serve(async (request) => {+ const file = (await request.formData()).get("file");+ const bytes = new Uint8Array(await file.arrayBuffer());+ seen.push([new URL(request.url).searchParams.get("uploadFolder"), file.name, file.type, Array.from(bytes.slice(0, 4))]);+ return Response.json([{ src: "/file/notes/edgeever-connection-test.png" }]);+ });+ expect(await testImgBedConnection({ endpoint, token: "imgbed-token", uploadFolder: "notes", nameType: "default" })).toBe(true);+ expect(seen).toEqual([["notes", "edgeever-connection-test.png", "image/png", [137, 80, 78, 71]]]);+});++test("reports rejected tokens and malformed responses without echoing the token", async () => {+ let failure = "";+ try { await uploadImgBedImage(image(serve(() => new Response("nope", { status: 401 })))); }+ catch (error) { failure = String(error); }+ expect(failure).toContain("rejected the API token");+ expect(failure).not.toContain("imgbed-token");+ for (const body of [{ error: "x" }, [], [{}], [{ src: "javascript:alert(1)" }], [{ src: "https://user:[email protected]/a.png" }], [{ src: "/a" }, { src: "/b" }]]) {+ await expect(uploadImgBedImage(image(serve(() => Response.json(body))))).rejects.toThrow();+ }+});++test("normalizes the address, folder and token and rejects unsafe values", () => {+ expect(normalizeImgBedEndpoint("https://img.example.com").href).toBe("https://img.example.com/upload");+ expect(normalizeImgBedEndpoint("https://img.example.com/").href).toBe("https://img.example.com/upload");+ expect(normalizeImgBedEndpoint("https://img.example.com/upload").href).toBe("https://img.example.com/upload");+ expect(normalizeImgBedEndpoint("https://example.com/imgbed/").href).toBe("https://example.com/imgbed/upload");+ for (const endpoint of ["ftp://img.example.com", "https://u:[email protected]", "https://img.example.com/?a=1", "http://169.254.169.254", "not a url"]) {+ expect(() => normalizeImgBedEndpoint(endpoint)).toThrow();+ }+ expect(normalizeImgBedFolder(" /notes//2026/ ")).toBe("notes/2026");+ for (const folder of ["../etc", "a/./b", "a\\b", "a?b", "a#b", "a%2e", "{Y}", "x".repeat(201)]) {+ expect(() => normalizeImgBedFolder(folder)).toThrow();+ }+ expect(normalizeImgBedToken(" token ")).toBe("token");+ for (const token of ["", "two words", 42]) expect(() => normalizeImgBedToken(token)).toThrow();+});++test("only accepts image bytes and refuses link-local hosts before fetching", async () => {+ const endpoint = serve(() => { throw new Error("Should not upload"); });+ await expect(uploadImgBedImage(image(endpoint, { mimeType: "application/pdf" }))).rejects.toThrow();+ await expect(uploadImgBedImage(image(endpoint, { bytes: new Uint8Array() }))).rejects.toThrow();+ await expect(uploadImgBedImage(image(endpoint, { nameType: "random" }))).rejects.toThrow();+ await expect(uploadImgBedImage(image(endpoint, { uploadChannel: "ftp" }))).rejects.toThrow();+ await expect(uploadImgBedImage(image(endpoint, { serverCompress: "yes" }))).rejects.toThrow();+ let fetched = false;+ await expect(uploadImgBedImage(image("https://img.example.com"), {+ lookupImpl: async () => [{ address: "169.254.169.254", family: 4 }],+ fetchImpl: () => { fetched = true; throw new Error("must not fetch"); },+ })).rejects.toThrow();+ expect(fetched).toBe(false);+});diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjsindex 219c0263..81765fa4 100644--- a/apps/desktop/src/main/index.mjs+++ b/apps/desktop/src/main/index.mjs@@ -61,7 +61,8 @@ import { createUpdateDiagnostic } from "./update-diagnostics.mjs";import { createUpdateNetworkDiagnostics } from "./update-network-diagnostics.mjs";import { normalizeUpdateProgress } from "./update-progress.mjs";import { inspectWindowsTaskbarShortcuts } from "./windows-taskbar-diagnostics.mjs";-import { testPicGoConnection, createPicGoUploadQueue } from "./picgo.mjs";+import { testPicGoConnection, createPicGoUploadQueue, uploadPicGoImage } from "./picgo.mjs";+import { testImgBedConnection, uploadImgBedImage } from "./imgbed.mjs";import { createPluginPublicNetworkRuntime } from "./plugin-public-network.mjs";import { createAiDirectRuntime } from "./ai-direct.mjs";import { createAcpPathStore, validateTrustedAcpPath } from "./acp-path-store.mjs";@@ -2049,8 +2050,14 @@ const startApplication = async () => {const target = input && typeof input === "object" ? input : { endpoint: input, serverKey: "" };return testPicGoConnection(target.endpoint, { serverKey: target.serverKey });});- // Serialize uploads and error dialogs across rapid pastes and multi-image batches.+ ipcMain.handle("desktop:imgbed-test", (event, input) => {+ if (!isAppRendererSender(event)) throw new Error("ImgBed requests must come from the main window");+ return testImgBedConnection(input && typeof input === "object" ? input : {});+ });+ // Serialize uploads and error dialogs across rapid pastes and multi-image batches,+ // shared by PicGo and ImgBed so one failure dialog is shown at a time.const queuePicGoUpload = createPicGoUploadQueue({+ upload: (input) => input.provider === "imgbed" ? uploadImgBedImage(input) : uploadPicGoImage(input),isActive: () => Boolean(mainWindow && !mainWindow.webContents.isDestroyed()),chooseFailure: async (input) => {const copy = input.copy;@@ -2065,7 +2072,12 @@ const startApplication = async () => {ipcMain.handle("desktop:picgo-upload", (event, input) => {if (!isAppRendererSender(event)) throw new Error("PicGo requests must come from the main window");const sender = event.sender;- return queuePicGoUpload(input, () => !sender.isDestroyed() && (sender === mainWindow?.webContents || noteWindows.isNoteWindowContents(sender)));+ return queuePicGoUpload({ ...input, provider: "picgo" }, () => !sender.isDestroyed() && (sender === mainWindow?.webContents || noteWindows.isNoteWindowContents(sender)));+ });+ ipcMain.handle("desktop:imgbed-upload", (event, input) => {+ if (!isAppRendererSender(event)) throw new Error("ImgBed requests must come from the main window");+ const sender = event.sender;+ return queuePicGoUpload({ ...input, provider: "imgbed" }, () => !sender.isDestroyed() && (sender === mainWindow?.webContents || noteWindows.isNoteWindowContents(sender)));});ipcMain.handle("desktop:public-network-fetch", async (event, requestId, input) => {if (event.sender !== mainWindow?.webContents) throw new Error("Public network requests must come from the main window");diff --git a/apps/desktop/src/main/picgo.mjs b/apps/desktop/src/main/picgo.mjsindex 3444b559..d6c6ec31 100644--- a/apps/desktop/src/main/picgo.mjs+++ b/apps/desktop/src/main/picgo.mjs@@ -4,7 +4,7 @@import { lookup } from "node:dns/promises";import { BlockList, isIP } from "node:net";-const ADDRESS_ERROR = "Use a PicGo or PicList upload address such as http://127.0.0.1:36677/upload";+const ADDRESS_ERROR = "Use a PicGo or PicList upload address ending in /upload, such as http://127.0.0.1:36677/upload";const BLOCKED_HOSTNAMES = new Set(["metadata.google.internal", "metadata.goog"]);const blockedAddresses = new BlockList();@@ -42,10 +42,10 @@ export const isBlockedPicGoAddress = (address) => {return true;};-const assertHostShape = (hostname) => {+export const assertHostShape = (hostname, message = ADDRESS_ERROR) => {const host = canonicalHost(hostname);- if (!host || BLOCKED_HOSTNAMES.has(host) || /^\d+$/.test(host)) throw new Error(ADDRESS_ERROR);- if (isLiteralHost(host) && isBlockedPicGoAddress(host)) throw new Error(ADDRESS_ERROR);+ if (!host || BLOCKED_HOSTNAMES.has(host) || /^\d+$/.test(host)) throw new Error(message);+ if (isLiteralHost(host) && isBlockedPicGoAddress(host)) throw new Error(message);};export const normalizePicGoServerKey = (value) => {@@ -62,51 +62,55 @@ export const normalizePicGoEndpoint = (value) => {let url;try { url = new URL(value); }catch { throw new Error(ADDRESS_ERROR); }- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.search || url.pathname !== "/upload") {+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.search || !url.pathname.endsWith("/upload")) {throw new Error(ADDRESS_ERROR);}assertHostShape(url.hostname);return url;};-const buildPicGoUrl = (endpoint, serverKey, pathname) => {+// A reverse proxy may mount PicList under a prefix; heartbeat sits beside /upload.+const buildPicGoUrl = (endpoint, serverKey, action) => {const url = normalizePicGoEndpoint(endpoint);- url.pathname = pathname;+ if (action === "heartbeat") url.pathname = `${url.pathname.slice(0, -"/upload".length)}/heartbeat`;const key = normalizePicGoServerKey(serverKey);if (key) url.searchParams.set("key", key);return url;};-const assertPicGoHostAllowed = async (hostname, lookupImpl) => {- assertHostShape(hostname);+export const assertImageHostAllowed = async (hostname, lookupImpl, { label = "PicGo", message = ADDRESS_ERROR } = {}) => {+ assertHostShape(hostname, message);const host = canonicalHost(hostname);if (isLiteralHost(host)) return;let records;try {records = await lookupImpl(host, { all: true, verbatim: true });} catch {- throw new Error("PicGo host could not be resolved");+ throw new Error(`${label} host could not be resolved`);}- if (!Array.isArray(records) || records.length === 0) throw new Error("PicGo host could not be resolved");+ if (!Array.isArray(records) || records.length === 0) throw new Error(`${label} host could not be resolved`);for (const record of records) {- if (!record || typeof record.address !== "string" || isBlockedPicGoAddress(record.address)) throw new Error(ADDRESS_ERROR);+ if (!record || typeof record.address !== "string" || isBlockedPicGoAddress(record.address)) throw new Error(message);}};-const request = async (url, body, fetchImpl, timeoutMs) => {+export const postImageHostJson = async (url, body, fetchImpl, timeoutMs, { label = "PicGo", headers } = {}) => {let response;try {response = await fetchImpl(url, {- method: "POST", body, redirect: "error", signal: AbortSignal.timeout(timeoutMs),+ method: "POST", body, headers, redirect: "error", signal: AbortSignal.timeout(timeoutMs),});} catch (error) {const name = error && typeof error === "object" ? error.name : "";- if (name === "TimeoutError" || name === "AbortError") throw new Error("PicGo did not respond in time");- throw new Error("PicGo could not be reached");+ if (name === "TimeoutError" || name === "AbortError") throw new Error(`${label} did not respond in time`);+ throw new Error(`${label} could not be reached`);+ }+ if (!response.ok) {+ await response.body?.cancel().catch(() => {});+ throw new Error(`${label} HTTP ${response.status}`);}- if (!response.ok) throw new Error(`PicGo HTTP ${response.status}`);const reader = response.body?.getReader();- if (!reader) throw new Error("PicGo returned an empty response");+ if (!reader) throw new Error(`${label} returned an empty response`);const chunks = [];let length = 0;try {@@ -114,7 +118,7 @@ const request = async (url, body, fetchImpl, timeoutMs) => {const { done, value } = await reader.read();if (done) break;length += value.byteLength;- if (length > 65536) throw new Error("PicGo response is too large");+ if (length > 65536) throw new Error(`${label} response is too large`);chunks.push(value);}} finally {@@ -127,21 +131,21 @@ const request = async (url, body, fetchImpl, timeoutMs) => {try {return JSON.parse(new TextDecoder().decode(bytes));} catch {- throw new Error("PicGo returned an unreadable response");+ throw new Error(`${label} returned an unreadable response`);}};export const testPicGoConnection = async (endpoint, { fetchImpl = fetch, timeoutMs = 5000, serverKey = "", lookupImpl = lookup } = {}) => {- const url = buildPicGoUrl(endpoint, serverKey, "/heartbeat");- await assertPicGoHostAllowed(url.hostname, lookupImpl);- const data = await request(url, undefined, fetchImpl, timeoutMs);+ const url = buildPicGoUrl(endpoint, serverKey, "heartbeat");+ await assertImageHostAllowed(url.hostname, lookupImpl);+ const data = await postImageHostJson(url, undefined, fetchImpl, timeoutMs);if (data?.success !== true || data.result !== "alive") throw new Error("The service did not identify itself as PicGo or PicList");return true;};export const uploadPicGoImage = async (input, { fetchImpl = fetch, timeoutMs = 60000, lookupImpl = lookup } = {}) => {- const url = buildPicGoUrl(input.endpoint, input.serverKey, "/upload");- await assertPicGoHostAllowed(url.hostname, lookupImpl);+ const url = buildPicGoUrl(input.endpoint, input.serverKey, "upload");+ await assertImageHostAllowed(url.hostname, lookupImpl);const bytes = input.bytes;if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > 50 * 1024 * 1024|| typeof input.mimeType !== "string" || !input.mimeType.startsWith("image/")) {@@ -149,7 +153,7 @@ export const uploadPicGoImage = async (input, { fetchImpl = fetch, timeoutMs = 6}const form = new FormData();form.append("files", new Blob([bytes], { type: input.mimeType }), String(input.filename || "image.png"));- const data = await request(url, form, fetchImpl, timeoutMs);+ const data = await postImageHostJson(url, form, fetchImpl, timeoutMs);if (data?.success !== true || !Array.isArray(data.result) || data.result.length !== 1) {throw new Error("PicGo did not return an uploaded image URL");}diff --git a/apps/desktop/src/main/picgo.test.mjs b/apps/desktop/src/main/picgo.test.mjsindex cb8a6392..321ebd87 100644--- a/apps/desktop/src/main/picgo.test.mjs+++ b/apps/desktop/src/main/picgo.test.mjs@@ -64,6 +64,22 @@ test("accepts a remote PicList address and keeps its server key on heartbeat andexpect(requests).toEqual([["/heartbeat", "nas-key", "POST"], ["/upload", "nas-key", "POST"]]);});+test("accepts a reverse-proxied address ending in /upload and keeps the prefix for heartbeat", async () => {+ expect(normalizePicGoEndpoint("https://nas.example.com/piclist/upload").pathname).toBe("/piclist/upload");+ const seen = [];+ const fetchImpl = async (url) => {+ const parsed = new URL(url);+ seen.push(parsed.pathname);+ return parsed.pathname.endsWith("/heartbeat")+ ? Response.json({ success: true, result: "alive" })+ : Response.json({ success: true, result: ["https://images.example.com/picture.png"] });+ };+ const lookupImpl = async () => [{ address: "203.0.113.10", family: 4 }];+ await testPicGoConnection("https://nas.example.com/piclist/upload", { fetchImpl, lookupImpl });+ await uploadPicGoImage(image("https://nas.example.com/piclist/upload"), { fetchImpl, lookupImpl });+ expect(seen).toEqual(["/piclist/heartbeat", "/piclist/upload"]);+});+test("resolves a remote name before connecting and refuses link-local targets", async () => {const seen = [];await testPicGoConnection("https://piclist.example.com:8443/upload", {@@ -95,6 +111,9 @@ test("rejects unsafe addresses and does not echo the server key", async () => {"http://0.0.0.0/upload","http://[fe80::1]/upload","http://127.0.0.1/other",+ "http://127.0.0.1/upload/other",+ "http://127.0.0.1/uploads",+ "http://127.0.0.1/my-upload","http://user:pass@localhost/upload","http://localhost/upload?secret=foo","http://localhost/upload?key=hidden",diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjsindex 1b356971..4c9a5ef2 100644--- a/apps/desktop/src/preload/index.cjs+++ b/apps/desktop/src/preload/index.cjs@@ -67,6 +67,8 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({clearSessionToken: () => ipcRenderer.invoke("desktop:clear-session-token"),testPicGoConnection: (input) => ipcRenderer.invoke("desktop:picgo-test", input),uploadPicGoImage: (input) => ipcRenderer.invoke("desktop:picgo-upload", input),+ testImgBedConnection: (input) => ipcRenderer.invoke("desktop:imgbed-test", input),+ uploadImgBedImage: (input) => ipcRenderer.invoke("desktop:imgbed-upload", input),publicNetworkFetch: (requestId, input) => ipcRenderer.invoke("desktop:public-network-fetch", requestId, input),cancelPublicNetworkFetch: async (requestId) => { ipcRenderer.send("desktop:cancel-public-network-fetch", requestId); },openAiProviderStream: (requestId, input) => ipcRenderer.invoke("desktop:ai-direct-open", requestId, input),diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 654565a6..5f239752 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -163,7 +163,7 @@ import { NEW_IMAGE_WIDTH_PERCENT } from "@edgeever/shared/image-display";import { EdgeEverLink } from "@edgeever/shared/editor-link";import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";import { codeBlockLowlight, EdgeEverCodeBlock } from "@/lib/code-block";-import { shouldUploadWithPicGo, uploadImageWithPicGo } from "@/lib/picgo";+import { activeExternalImageHost, uploadImageWithPicGo } from "@/lib/picgo";import { compressImageForUpload } from "@/lib/image-compression";import { LOCAL_DATABASE_INTERRUPTED_EVENT, localDb, selectNewestLocalDraft, type MemoUpdateSyncPayload } from "@/lib/local-db";import { persistEmergencyDraft, readEmergencyDraft, removeEmergencyDraft } from "@/lib/emergency-draft";@@ -1015,12 +1015,14 @@ const RichEditorPane = ({const uploadEditorResource = useCallback(async (targetMemoId: string, uploadFile: File, isImage: boolean) => {const mimeType = resolveResourceUploadMimeType(uploadFile.name, uploadFile.type);if (mimeType !== uploadFile.type) uploadFile = new File([uploadFile], uploadFile.name, { type: mimeType, lastModified: uploadFile.lastModified });- if (isImage && shouldUploadWithPicGo()) {+ const imageHost = isImage ? activeExternalImageHost() : null;+ if (imageHost) {const instanceKey = editorInstanceMemoIdentityRef.current.instanceKey;+ const failure = imageHost === "imgbed" ? "settings.picgo.imgbed" : "settings.picgo";const external = await uploadImageWithPicGo(uploadFile, {- title: t("settings.picgo.failedTitle"), message: t("settings.picgo.failedMessage"),+ title: t(`${failure}.failedTitle`), message: t(`${failure}.failedMessage`),retry: t("settings.picgo.retry"), fallback: t("settings.picgo.fallback"), cancel: t("settings.picgo.cancel"),- });+ }, { memoId: targetMemoId });// PicGo or its failure dialog may outlive the original note/instance.if (memoRef.current?.id !== targetMemoId || editorInstanceMemoIdentityRef.current.instanceKey !== instanceKey) {throw new Error("The active note changed during image upload");diff --git a/apps/web/src/components/settings/PicGoSettingsItem.tsx b/apps/web/src/components/settings/PicGoSettingsItem.tsxindex 6fcb9bb5..c476851d 100644--- a/apps/web/src/components/settings/PicGoSettingsItem.tsx+++ b/apps/web/src/components/settings/PicGoSettingsItem.tsx@@ -4,10 +4,17 @@ import { Image } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";-import { hasPicGoBridge, readPicGoPreference, takePicGoServerKey, writePicGoPreference, type PicGoPreference } from "@/lib/picgo";+import { Switch } from "@/components/ui/switch";+import { expandImgBedFolder, imgBedFolderError, IMGBED_FOLDER_PLACEHOLDERS, IMGBED_NAME_TYPES, IMGBED_SAMPLE_MEMO_ID, IMGBED_UPLOAD_CHANNELS, type ImgBedNameType, type ImgBedUploadChannel } from "@/lib/imgbed";+import { hasImgBedBridge, hasPicGoBridge, readPicGoPreference, takePicGoServerKey, writePicGoPreference, type ImgBedPreference, type PicGoPreference } from "@/lib/picgo";import { SETTINGS_ITEM_DESCRIPTION_CLASSNAME, SETTINGS_ITEM_TITLE_CLASSNAME } from "./settings-ui";-const picGoTargetId = (value: PicGoPreference) => `${value.endpoint}\0${value.serverKey}`;+const picGoTargetId = (value: PicGoPreference) => value.provider === "imgbed"+ ? ["imgbed", value.imgbed.endpoint, value.imgbed.token, value.imgbed.uploadFolder, value.imgbed.nameType,+ value.imgbed.uploadChannel, String(value.imgbed.serverCompress)].join("\0")+ : `${value.endpoint}\0${value.serverKey}`;+const sameImgBed = (left: ImgBedPreference, right: ImgBedPreference) => picGoTargetId({ provider: "imgbed", endpoint: "", serverKey: "", imgbed: left })+ === picGoTargetId({ provider: "imgbed", endpoint: "", serverKey: "", imgbed: right });export const PicGoSettingsItem = () => {const { t } = useTranslation();@@ -16,20 +23,38 @@ export const PicGoSettingsItem = () => {const [testedTarget, setTestedTarget] = useState<string | null>(null);const [busy, setBusy] = useState(false);const [status, setStatus] = useState("");- const desktopAvailable = hasPicGoBridge();- const dirty = draft.provider !== saved.provider || draft.endpoint !== saved.endpoint || draft.serverKey !== saved.serverKey;+ const desktopAvailable = draft.provider === "imgbed" ? hasImgBedBridge() : hasPicGoBridge();+ const dirty = draft.provider !== saved.provider || draft.endpoint !== saved.endpoint || draft.serverKey !== saved.serverKey+ || !sameImgBed(draft.imgbed, saved.imgbed);+ const folderError = imgBedFolderError(draft.imgbed.uploadFolder);+ const imgBedReady = Boolean(draft.imgbed.endpoint.trim() && draft.imgbed.token.trim()) && !folderError;+ const canTest = desktopAvailable && (draft.provider !== "imgbed" || imgBedReady);const canSave = dirty && (draft.provider === "edgeever" || (desktopAvailable && testedTarget === picGoTargetId(draft)));+ const updateImgBed = (patch: Partial<ImgBedPreference>) => {+ setDraft({ ...draft, imgbed: { ...draft.imgbed, ...patch } });+ setTestedTarget(null);+ setStatus("");+ };const testConnection = async () => {setBusy(true);setTestedTarget(null);setStatus("");+ const prefix = draft.provider === "imgbed" ? "settings.picgo.imgbed" : "settings.picgo";try {- await window.edgeeverDesktop!.testPicGoConnection({ endpoint: draft.endpoint, serverKey: draft.serverKey });+ if (draft.provider === "imgbed") {+ await window.edgeeverDesktop!.testImgBedConnection!({+ endpoint: draft.imgbed.endpoint, token: draft.imgbed.token, nameType: draft.imgbed.nameType,+ uploadChannel: draft.imgbed.uploadChannel, serverCompress: draft.imgbed.serverCompress,+ uploadFolder: expandImgBedFolder(draft.imgbed.uploadFolder),+ });+ } else {+ await window.edgeeverDesktop!.testPicGoConnection({ endpoint: draft.endpoint, serverKey: draft.serverKey });+ }setTestedTarget(picGoTargetId(draft));- setStatus(t("settings.picgo.connected"));+ setStatus(t(`${prefix}.connected`));} catch {- setStatus(t("settings.picgo.connectionFailed"));+ setStatus(t(`${prefix}.connectionFailed`));} finally { setBusy(false); }};const save = () => {@@ -55,6 +80,7 @@ export const PicGoSettingsItem = () => {<SelectContent><SelectItem value="edgeever">{t("settings.picgo.builtin")}</SelectItem><SelectItem value="picgo">{t("settings.picgo.external")}</SelectItem>+ <SelectItem value="imgbed">{t("settings.picgo.imgbed.option")}</SelectItem></SelectContent></Select></div>@@ -79,8 +105,65 @@ export const PicGoSettingsItem = () => {<p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.externalImages")}</p></div>) : null}+ {draft.provider === "imgbed" ? (+ <div className="grid gap-2 sm:ml-7">+ {!desktopAvailable ? <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.webPreview")}</p> : null}+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.imgbed.description")}</p>+ <label htmlFor="imgbed-endpoint" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.imgbed.endpoint")}</label>+ <Input id="imgbed-endpoint" value={draft.imgbed.endpoint} disabled={busy} placeholder="https://img.example.com"+ onChange={(event) => updateImgBed({ endpoint: event.target.value.trim() })} spellCheck={false} inputMode="url" autoComplete="off" />+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.imgbed.endpointDescription")}</p>+ <label htmlFor="imgbed-token" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.imgbed.token")}</label>+ <Input id="imgbed-token" name="imgbed-token" type="password" value={draft.imgbed.token} disabled={busy}+ onChange={(event) => updateImgBed({ token: event.target.value.trim() })} spellCheck={false} autoComplete="new-password" maxLength={1024} />+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.imgbed.tokenDescription")}</p>+ <label htmlFor="imgbed-folder" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.imgbed.folder")}</label>+ <Input id="imgbed-folder" value={draft.imgbed.uploadFolder} disabled={busy} placeholder="notes/{Y}/{m}" aria-invalid={folderError ? true : undefined}+ onChange={(event) => updateImgBed({ uploadFolder: event.target.value })} spellCheck={false} autoComplete="off" maxLength={200} />+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.imgbed.folderDescription")}</p>+ <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 text-xs text-slate-500">+ {IMGBED_FOLDER_PLACEHOLDERS.map(({ token, key }) => (+ <div key={key} className="contents">+ <dt><code className="font-mono text-slate-700">{token}</code></dt>+ <dd>{t(`settings.picgo.imgbed.placeholders.${key}`)}</dd>+ </div>+ ))}+ </dl>+ <p className={folderError ? "text-xs text-rose-700" : SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>+ {folderError+ ? t(`settings.picgo.imgbed.folderInvalid.${folderError}`)+ : t("settings.picgo.imgbed.folderPreview", { folder: expandImgBedFolder(draft.imgbed.uploadFolder, new Date(), { memoId: IMGBED_SAMPLE_MEMO_ID }) || "/" })}+ </p>+ <label htmlFor="imgbed-name-type" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.imgbed.nameType")}</label>+ <Select value={draft.imgbed.nameType} disabled={busy} onValueChange={(nameType) => updateImgBed({ nameType: nameType as ImgBedNameType })}>+ <SelectTrigger id="imgbed-name-type" className="h-9 w-full sm:w-80"><SelectValue /></SelectTrigger>+ <SelectContent>+ {IMGBED_NAME_TYPES.map((nameType) => (+ <SelectItem key={nameType} value={nameType}>{t(`settings.picgo.imgbed.nameTypes.${nameType}`)}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ <label htmlFor="imgbed-channel" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.imgbed.channel")}</label>+ <Select value={draft.imgbed.uploadChannel} disabled={busy} onValueChange={(uploadChannel) => updateImgBed({ uploadChannel: uploadChannel as ImgBedUploadChannel })}>+ <SelectTrigger id="imgbed-channel" className="h-9 w-full sm:w-80"><SelectValue /></SelectTrigger>+ <SelectContent>+ {IMGBED_UPLOAD_CHANNELS.map((channel) => (+ <SelectItem key={channel} value={channel}>{t(`settings.picgo.imgbed.channels.${channel}`)}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ <div className="flex items-center justify-between gap-3">+ <label htmlFor="imgbed-compress" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.imgbed.serverCompress")}</label>+ <Switch id="imgbed-compress" checked={draft.imgbed.serverCompress} disabled={busy}+ onCheckedChange={(serverCompress) => updateImgBed({ serverCompress })} />+ </div>+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.imgbed.serverCompressDescription")}</p>+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.imgbed.testDescription")}</p>+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.externalImages")}</p>+ </div>+ ) : null}<div className="flex flex-wrap items-center gap-2 sm:ml-7">- {draft.provider === "picgo" ? <Button variant="outline" size="sm" disabled={busy || !desktopAvailable} onClick={() => void testConnection()}>+ {draft.provider !== "edgeever" ? <Button variant="outline" size="sm" disabled={busy || !canTest} onClick={() => void testConnection()}>{t(busy ? "settings.picgo.testing" : "settings.picgo.test")}</Button> : null}{dirty ? <Button size="sm" disabled={busy || !canSave} onClick={save}>{t("settings.picgo.save")}</Button> : null}diff --git a/apps/web/src/lib/imgbed.test.mjs b/apps/web/src/lib/imgbed.test.mjsnew file mode 100644index 00000000..7d754ffc--- /dev/null+++ b/apps/web/src/lib/imgbed.test.mjs@@ -0,0 +1,58 @@+import { expect, test } from "bun:test";+import { expandImgBedFolder, imgBedFolderError, IMGBED_MAX_FOLDER_LENGTH, IMGBED_MAX_MEMO_ID_LENGTH } from "./imgbed.ts";+import { normalizeImgBedFolder } from "../../../desktop/src/main/imgbed.mjs";++const now = new Date(2026, 0, 5, 7, 8, 9, 42);++test("expands PicList date placeholders in local time with zero padding", () => {+ expect(expandImgBedFolder("notes/{Y}/{y}{m}{d}/{h}-{i}-{s}-{ms}", now)).toBe("notes/2026/260105/07-08-09-042");+ expect(expandImgBedFolder("{timestamp}/{timestampS}", now)).toBe(`${now.getTime()}/${Math.floor(now.getTime() / 1000)}`);+});++test("expands random placeholders and the target note id", () => {+ expect(expandImgBedFolder("a/{uuid}", now)).toMatch(/^a\/[0-9a-f-]{36}$/);+ expect(expandImgBedFolder("{str-6}", now)).toMatch(/^[A-Za-z0-9]{6}$/);+ expect(expandImgBedFolder("notes/{memoId}", now, { memoId: "memo_abc-1" })).toBe("notes/memo_abc-1");+ expect(expandImgBedFolder("notes/{memoId}/{Y}", now)).toBe("notes/2026");+ expect(expandImgBedFolder("notes/{memoId}", now, { memoId: "../x" })).toBe("notes/x");+});++test("normalizes slashes and drops dot segments", () => {+ expect(expandImgBedFolder("", now)).toBe("");+ expect(expandImgBedFolder(" /a// b /./../c/ ", now)).toBe("a/b/c");+});++test("rejects unknown placeholders, stray braces, unsafe characters and long templates", () => {+ for (const template of ["{filename}", "{md5}", "{str-0}", "{str-33}", "{Y", "a}b", "{{Y}}"]) {+ expect(imgBedFolderError(template)).toBe("placeholder");+ expect(() => expandImgBedFolder(template, now)).toThrow();+ }+ for (const template of ["a?b", "a#b", "a%b", "a\\b", "a:b", "a|b"]) expect(imgBedFolderError(template)).toBe("characters");+ expect(imgBedFolderError("x".repeat(201))).toBe("length");+ expect(imgBedFolderError("notes/{Y}/{m}/{memoId}")).toBeNull();+});++// Regression for PR #740 review: the connection test expands {memoId} to nothing,+// so a folder could pass the test and still exceed the main-process limit on upload.+test("rejects a folder that passes the connection test but overflows with a real note id", () => {+ const template = `${"a".repeat(180)}/{memoId}`;+ const realMemoId = `memo_${"0".repeat(32)}`;+ expect(expandImgBedFolder(`${"a".repeat(180)}`, now)).toHaveLength(180);+ expect(() => normalizeImgBedFolder(`${"a".repeat(180)}/${realMemoId}`)).toThrow();+ expect(imgBedFolderError(template)).toBe("length");+ expect(() => expandImgBedFolder(template, now, { memoId: realMemoId })).toThrow();+});++test("an accepted folder always fits the main-process limit at its longest expansion", () => {+ const boundary = `${"a".repeat(IMGBED_MAX_FOLDER_LENGTH - IMGBED_MAX_MEMO_ID_LENGTH - 1)}/{memoId}`;+ expect(imgBedFolderError(boundary)).toBeNull();+ expect(imgBedFolderError(`a${boundary}`)).toBe("length");+ for (const memoId of [`memo_${"f".repeat(32)}`, "m".repeat(200)]) {+ const folder = expandImgBedFolder(boundary, now, { memoId });+ expect(folder.length).toBeLessThanOrEqual(IMGBED_MAX_FOLDER_LENGTH);+ expect(normalizeImgBedFolder(folder)).toBe(folder);+ }+ const busy = "{Y}/{m}/{d}/{uuid}/{timestamp}/{timestampS}/{str-32}/{memoId}";+ expect(imgBedFolderError(busy)).toBeNull();+ expect(normalizeImgBedFolder(expandImgBedFolder(busy, now, { memoId: "m".repeat(200) }))).toBeTruthy();+});diff --git a/apps/web/src/lib/imgbed.ts b/apps/web/src/lib/imgbed.tsnew file mode 100644index 00000000..c7289b58--- /dev/null+++ b/apps/web/src/lib/imgbed.ts@@ -0,0 +1,89 @@+// Upload folder templates use PicList's rename placeholders, expanded in the+// uploader's local time zone, plus EdgeEver's {memoId}. File-specific tokens+// ({filename}, {md5}, ...) are not supported because ImgBed names the file itself.+export const IMGBED_NAME_TYPES = ["default", "index", "origin", "short"] as const;+export type ImgBedNameType = typeof IMGBED_NAME_TYPES[number];+// Defaults follow the ImgBed upload API: telegram channel with server compression on.+export const IMGBED_UPLOAD_CHANNELS = ["telegram", "cfr2", "s3", "discord", "huggingface", "webdav"] as const;+export type ImgBedUploadChannel = typeof IMGBED_UPLOAD_CHANNELS[number];+// `key` names the description in settings.picgo.imgbed.placeholders.+export const IMGBED_FOLDER_PLACEHOLDERS = [+ { token: "{Y}", key: "Y" }, { token: "{y}", key: "y" }, { token: "{m}", key: "m" }, { token: "{d}", key: "d" },+ { token: "{h}", key: "h" }, { token: "{i}", key: "i" }, { token: "{s}", key: "s" }, { token: "{ms}", key: "ms" },+ { token: "{timestamp}", key: "timestamp" }, { token: "{timestampS}", key: "timestampS" }, { token: "{uuid}", key: "uuid" },+ { token: "{str-N}", key: "strN" }, { token: "{memoId}", key: "memoId" },+] as const;+export const IMGBED_SAMPLE_MEMO_ID = "memo_example";++// Matches the main process limit on the expanded folder.+export const IMGBED_MAX_FOLDER_LENGTH = 200;+// Server ids are memo_ + 32 hex characters; restored ids are capped so the worst case stays bounded.+export const IMGBED_MAX_MEMO_ID_LENGTH = 64;+const STRING_PATTERN = /^str-(\d{1,2})$/;+// oxlint-disable-next-line no-control-regex -- rejects control characters in the upload folder+const INVALID_FOLDER_CHARACTERS = /[\u0000-\u001f\u007f\\?#%<>:*|"]/;+const RANDOM_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";++export type ImgBedFolderError = "placeholder" | "characters" | "length";+// Without a note (connection test), {memoId} expands to nothing and its folder level is dropped.+export type ImgBedFolderContext = { memoId?: string };++const pad = (value: number, length = 2) => String(value).padStart(length, "0");++const randomString = (length: number) => {+ const bytes = crypto.getRandomValues(new Uint8Array(length));+ return Array.from(bytes, (byte) => RANDOM_ALPHABET[byte % RANDOM_ALPHABET.length]).join("");+};++const placeholderValue = (name: string, now: Date, context: ImgBedFolderContext = {}): string | null => {+ switch (name) {+ case "memoId": return (context.memoId ?? "").replace(/[^\w-]/g, "").slice(0, IMGBED_MAX_MEMO_ID_LENGTH);+ case "Y": return String(now.getFullYear());+ case "y": return pad(now.getFullYear() % 100);+ case "m": return pad(now.getMonth() + 1);+ case "d": return pad(now.getDate());+ case "h": return pad(now.getHours());+ case "i": return pad(now.getMinutes());+ case "s": return pad(now.getSeconds());+ case "ms": return pad(now.getMilliseconds(), 3);+ case "timestamp": return String(now.getTime());+ case "timestampS": return String(Math.floor(now.getTime() / 1000));+ case "uuid": return crypto.randomUUID();+ }+ const length = Number(STRING_PATTERN.exec(name)?.[1] ?? 0);+ return length >= 1 && length <= 32 ? randomString(length) : null;+};++// Longest value each placeholder can expand to (years beyond 9999 are not considered).+const maxPlaceholderLength = (name: string) => {+ switch (name) {+ case "memoId": return IMGBED_MAX_MEMO_ID_LENGTH;+ case "Y": return 4;+ case "ms": return 3;+ case "timestamp": return 13;+ case "timestampS": return 10;+ case "uuid": return 36;+ }+ const length = Number(STRING_PATTERN.exec(name)?.[1] ?? 0);+ return length || 2;+};++const normalizeFolder = (value: string) => value.split("/").map((segment) => segment.trim())+ .filter((segment) => segment && segment !== "." && segment !== "..").join("/");++// Validates against the longest possible expansion, so a folder that passes the+// connection test (where {memoId} is empty) cannot exceed the limit on a real upload.+export const imgBedFolderError = (template: string): ImgBedFolderError | null => {+ const literal = template.replace(/\{([^{}]*)\}/g, (_match, name: string) => placeholderValue(name, new Date(0)) === null ? "\u0000" : "");+ if (literal.includes("\u0000") || /[{}]/.test(literal)) return "placeholder";+ if (INVALID_FOLDER_CHARACTERS.test(literal)) return "characters";+ const longest = template.replace(/\{([^{}]*)\}/g, (_match, name: string) => "x".repeat(maxPlaceholderLength(name)));+ if (longest.length > IMGBED_MAX_FOLDER_LENGTH) return "length";+ return null;+};++export const expandImgBedFolder = (template: string, now = new Date(), context: ImgBedFolderContext = {}) => {+ const error = imgBedFolderError(template);+ if (error) throw new Error(`ImgBed upload folder is invalid: ${error}`);+ return normalizeFolder(template.replace(/\{([^{}]*)\}/g, (_match, name: string) => placeholderValue(name, now, context) ?? ""));+};diff --git a/apps/web/src/lib/picgo.test.mjs b/apps/web/src/lib/picgo.test.mjsindex 2390cb89..86712c3c 100644--- a/apps/web/src/lib/picgo.test.mjs+++ b/apps/web/src/lib/picgo.test.mjs@@ -1,5 +1,7 @@import { afterEach, expect, test } from "bun:test";-import { PICGO_STORAGE_KEY, DEFAULT_PICGO_ENDPOINT, readPicGoPreference, shouldUploadWithPicGo, takePicGoServerKey, uploadImageWithPicGo, writePicGoPreference } from "./picgo.ts";+import { PICGO_STORAGE_KEY, DEFAULT_PICGO_ENDPOINT, activeExternalImageHost, readPicGoPreference, shouldUploadWithPicGo, takePicGoServerKey, uploadImageWithPicGo, writePicGoPreference } from "./picgo.ts";++const noImgBed = { endpoint: "", token: "", uploadFolder: "", nameType: "default", uploadChannel: "telegram", serverCompress: true };const previousWindow = globalThis.window;afterEach(() => {@@ -19,7 +21,7 @@ const file = () => new File([new Uint8Array([137, 80, 78, 71])], "image.png", {test("default, corrupt settings and ordinary Web runtime retain attachment uploads", async () => {const storage = setup();- expect(readPicGoPreference()).toEqual({ provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT, serverKey: "" });+ expect(readPicGoPreference()).toEqual({ provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT, serverKey: "", imgbed: noImgBed });storage.set(PICGO_STORAGE_KEY, "corrupt");expect(shouldUploadWithPicGo()).toBe(false);writePicGoPreference({ provider: "picgo", endpoint: DEFAULT_PICGO_ENDPOINT, serverKey: "" });@@ -60,7 +62,7 @@ test("only explicit fallback returns to attachment storage; cancellation stays atest("keeps an older saved address and lifts a pasted PicList key out of the address", () => {const storage = setup();storage.set(PICGO_STORAGE_KEY, JSON.stringify({ provider: "picgo", endpoint: "https://piclist.example.com/upload" }));- expect(readPicGoPreference()).toEqual({ provider: "picgo", endpoint: "https://piclist.example.com/upload", serverKey: "" });+ expect(readPicGoPreference()).toEqual({ provider: "picgo", endpoint: "https://piclist.example.com/upload", serverKey: "", imgbed: noImgBed });expect(takePicGoServerKey("https://piclist.example.com/upload?key=nas-key")).toEqual({endpoint: "https://piclist.example.com/upload", serverKey: "nas-key",});@@ -74,3 +76,27 @@ test("keeps an older saved address and lifts a pasted PicList key out of the addwritePicGoPreference({ provider: "picgo", endpoint: "https://piclist.example.com/upload", serverKey: "nas-key" });return uploadImageWithPicGo(file(), copy);});++test("ImgBed expands the folder for the target note and needs its own desktop bridge", async () => {+ const storage = setup();+ const imgbed = { endpoint: "https://img.example.com", token: "imgbed-token", uploadFolder: "notes/{Y}/{memoId}", nameType: "origin", uploadChannel: "cfr2", serverCompress: false };+ storage.set(PICGO_STORAGE_KEY, JSON.stringify({ provider: "imgbed", endpoint: DEFAULT_PICGO_ENDPOINT, imgbed: { ...imgbed, nameType: "bogus", uploadChannel: "ftp", serverCompress: "no" } }));+ expect(readPicGoPreference().imgbed).toEqual({ ...imgbed, nameType: "default", uploadChannel: "telegram", serverCompress: true });+ expect(activeExternalImageHost()).toBeNull();++ globalThis.window.edgeeverDesktop = {+ uploadPicGoImage: () => { throw new Error("Should not use PicGo"); },+ testPicGoConnection: async () => true,+ testImgBedConnection: async () => true,+ uploadImgBedImage: async (input) => {+ expect(input).toMatchObject({ endpoint: imgbed.endpoint, token: "imgbed-token", nameType: "origin", uploadChannel: "cfr2", serverCompress: false, filename: "image.png", mimeType: "image/png", copy });+ expect(input.uploadFolder).toBe(`notes/${new Date().getFullYear()}/memo_123`);+ return { url: "https://img.example.com/file/notes/image.png" };+ },+ };+ writePicGoPreference({ provider: "imgbed", endpoint: DEFAULT_PICGO_ENDPOINT, serverKey: "", imgbed });+ expect(activeExternalImageHost()).toBe("imgbed");+ expect(await uploadImageWithPicGo(file(), copy, { memoId: "memo_123" })).toEqual({+ kind: "image", url: "https://img.example.com/file/notes/image.png", filename: "image.png", mimeType: "image/png", byteSize: 4,+ });+});diff --git a/apps/web/src/lib/picgo.ts b/apps/web/src/lib/picgo.tsindex 2e1e5bc0..95dc70cc 100644--- a/apps/web/src/lib/picgo.ts+++ b/apps/web/src/lib/picgo.ts@@ -1,8 +1,31 @@+import { expandImgBedFolder, IMGBED_NAME_TYPES, IMGBED_UPLOAD_CHANNELS, type ImgBedNameType, type ImgBedUploadChannel } from "./imgbed";+export const PICGO_STORAGE_KEY = "edgeever.desktop.picgo.v1";export const DEFAULT_PICGO_ENDPOINT = "http://127.0.0.1:36677/upload";-export type PicGoPreference = { provider: "edgeever" | "picgo"; endpoint: string; serverKey: string };+export type ImgBedPreference = {+ endpoint: string; token: string; uploadFolder: string; nameType: ImgBedNameType;+ uploadChannel: ImgBedUploadChannel; serverCompress: boolean;+};+export type PicGoPreference = { provider: "edgeever" | "picgo" | "imgbed"; endpoint: string; serverKey: string; imgbed: ImgBedPreference };+export type ExternalImageHost = Exclude<PicGoPreference["provider"], "edgeever">;-const emptyPicGoPreference = (): PicGoPreference => ({ provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT, serverKey: "" });+const emptyImgBedPreference = (): ImgBedPreference => ({+ endpoint: "", token: "", uploadFolder: "", nameType: "default", uploadChannel: "telegram", serverCompress: true,+});+const emptyPicGoPreference = (): PicGoPreference => ({ provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT, serverKey: "", imgbed: emptyImgBedPreference() });++const readImgBedPreference = (value: unknown): ImgBedPreference => {+ const record = value && typeof value === "object" ? value as Record<string, unknown> : {};+ const text = (key: string) => typeof record[key] === "string" ? record[key] as string : "";+ return {+ endpoint: text("endpoint"),+ token: text("token"),+ uploadFolder: text("uploadFolder"),+ nameType: IMGBED_NAME_TYPES.includes(record.nameType as ImgBedNameType) ? record.nameType as ImgBedNameType : "default",+ uploadChannel: IMGBED_UPLOAD_CHANNELS.includes(record.uploadChannel as ImgBedUploadChannel) ? record.uploadChannel as ImgBedUploadChannel : "telegram",+ serverCompress: typeof record.serverCompress === "boolean" ? record.serverCompress : true,+ };+};export const readPicGoPreference = (): PicGoPreference => {const fallback = emptyPicGoPreference();@@ -10,9 +33,10 @@ export const readPicGoPreference = (): PicGoPreference => {const value = JSON.parse(window.localStorage.getItem(PICGO_STORAGE_KEY) ?? "null");if (!value || typeof value.endpoint !== "string") return fallback;return {- provider: value.provider === "picgo" ? "picgo" : "edgeever",+ provider: value.provider === "picgo" || value.provider === "imgbed" ? value.provider : "edgeever",endpoint: value.endpoint,serverKey: typeof value.serverKey === "string" ? value.serverKey : "",+ imgbed: readImgBedPreference(value.imgbed),};} catch { return fallback; }};@@ -38,18 +62,33 @@ export const writePicGoPreference = (value: PicGoPreference) => {};export const hasPicGoBridge = () => Boolean(window.edgeeverDesktop?.uploadPicGoImage && window.edgeeverDesktop?.testPicGoConnection);+export const hasImgBedBridge = () => Boolean(window.edgeeverDesktop?.uploadImgBedImage && window.edgeeverDesktop?.testImgBedConnection);++const hasBridge = (provider: ExternalImageHost) => provider === "imgbed" ? hasImgBedBridge() : hasPicGoBridge();++// The configured external host that will receive new images, or null for EdgeEver storage.+export const activeExternalImageHost = (): ExternalImageHost | null => {+ const { provider } = readPicGoPreference();+ return provider !== "edgeever" && hasBridge(provider) ? provider : null;+};-export const shouldUploadWithPicGo = () => hasPicGoBridge() && readPicGoPreference().provider === "picgo";+export const shouldUploadWithPicGo = () => activeExternalImageHost() !== null;export type PicGoFailureCopy = { title: string; message: string; retry: string; fallback: string; cancel: string };-export const uploadImageWithPicGo = async (file: File, copy: PicGoFailureCopy) => {+export const uploadImageWithPicGo = async (file: File, copy: PicGoFailureCopy, context: { memoId?: string } = {}) => {const preference = readPicGoPreference();- if (preference.provider !== "picgo" || !hasPicGoBridge()) return null;- const result = await window.edgeeverDesktop!.uploadPicGoImage({- endpoint: preference.endpoint, serverKey: preference.serverKey, bytes: new Uint8Array(await file.arrayBuffer()),- filename: file.name, mimeType: file.type, copy,- });+ if (preference.provider === "edgeever" || !hasBridge(preference.provider)) return null;+ const bytes = new Uint8Array(await file.arrayBuffer());+ const result = preference.provider === "imgbed"+ ? await window.edgeeverDesktop!.uploadImgBedImage!({+ endpoint: preference.imgbed.endpoint, token: preference.imgbed.token, nameType: preference.imgbed.nameType,+ uploadChannel: preference.imgbed.uploadChannel, serverCompress: preference.imgbed.serverCompress,+ uploadFolder: expandImgBedFolder(preference.imgbed.uploadFolder, new Date(), { memoId: context.memoId }), bytes, filename: file.name, mimeType: file.type, copy,+ })+ : await window.edgeeverDesktop!.uploadPicGoImage({+ endpoint: preference.endpoint, serverKey: preference.serverKey, bytes, filename: file.name, mimeType: file.type, copy,+ });return "url" in result ? {kind: "image" as const, url: result.url, filename: file.name, mimeType: file.type, byteSize: file.size,} : null;diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex 70f12946..6453c638 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -67,6 +67,13 @@ interface EdgeEverDesktopBridge {endpoint: string; serverKey?: string; bytes: Uint8Array; filename: string; mimeType: string;copy: import("@/lib/picgo").PicGoFailureCopy;}): Promise<{ url: string } | { fallback: true }>;+ testImgBedConnection?(input: { endpoint: string; token: string; uploadFolder: string; nameType: import("@/lib/imgbed").ImgBedNameType;+ uploadChannel: import("@/lib/imgbed").ImgBedUploadChannel; serverCompress: boolean }): Promise<boolean>;+ uploadImgBedImage?(input: {+ endpoint: string; token: string; uploadFolder: string; nameType: import("@/lib/imgbed").ImgBedNameType;+ uploadChannel: import("@/lib/imgbed").ImgBedUploadChannel; serverCompress: boolean;+ bytes: Uint8Array; filename: string; mimeType: string; copy: import("@/lib/picgo").PicGoFailureCopy;+ }): Promise<{ url: string } | { fallback: true }>;publicNetworkFetch(requestId: string, input: import("@edgeever/shared").PluginPublicFetchRequest): Promise<import("@edgeever/shared").PluginPublicFetchResponse>;cancelPublicNetworkFetch(requestId: string): Promise<void>;openAiProviderStream(requestId: string, input: {diff --git a/docs/changes/2026-10-30-desktop-imgbed-image-host.md b/docs/changes/2026-10-30-desktop-imgbed-image-host.mdnew file mode 100644index 00000000..9418fc04--- /dev/null+++ b/docs/changes/2026-10-30-desktop-imgbed-image-host.md@@ -0,0 +1,31 @@+# CloudFlare ImgBed image host (desktop)++[简体中文](2026-10-30-desktop-imgbed-image-host.zh-CN.md)++## Problem and outcome++Implements [Issue #734](https://github.com/tianma-if/edgeever/issues/734). Desktop users who run their own [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed) had to put PicList in between to use it. "CloudFlare ImgBed" is now a third choice in Settings → Image hosting, next to the built-in storage and PicGo / PicList. Like PicGo, the desktop app uploads new images and writes the returned link into the note. The PicGo / PicList address rule is also relaxed: it must end with `/upload` instead of being exactly `/upload`, so a PicList behind a reverse proxy (`https://nas.example.com/piclist/upload`) works.++## Behavior++| ID | Behavior | Acceptance |+| --- | --- | --- |+| B01 | Settings take the ImgBed address (site root or `…/upload`), an API token with the `upload` permission, an optional upload folder, the ImgBed file naming mode (`default`, `index`, `origin`, `short`), the upload channel (`telegram`, `cfr2`, `s3`, `discord`, `huggingface`, `webdav`) and server-side compression. Channel and compression default to the ImgBed API defaults: `telegram` with compression on. Saving requires a successful connection test, as for PicGo. | `imgbed.test.mjs` (desktop): address and token normalization. |+| B02 | The upload folder accepts PicList placeholders `{Y}` `{y}` `{m}` `{d}` `{h}` `{i}` `{s}` `{ms}` `{timestamp}` `{timestampS}` `{uuid}` `{str-N}` plus EdgeEver's `{memoId}` (the note receiving the image). Dates use the uploader's local time zone. Unknown placeholders, stray braces and unsafe characters are rejected before saving, as is a folder whose longest possible expansion exceeds the 200-character limit the main process enforces (each placeholder at its maximum length, `{memoId}` capped at 64 characters), so a folder that passes the connection test cannot fail later with a real note ID; the settings show an expanded preview. | `imgbed.test.mjs` (web). |+| B03 | Uploads send `POST {address}/upload?uploadChannel=…&serverCompress=…&uploadNameType=…&uploadFolder=…` with `Authorization: Bearer <token>` and the image in `file`. The note gets `publicUrl` when ImgBed returns it, otherwise `src` resolved against the ImgBed address. Only a single http(s) link without credentials is accepted. | `imgbed.test.mjs` (desktop). |+| B04 | The connection test uploads a 1×1 transparent PNG named `edgeever-connection-test.png` to the configured folder, because ImgBed has no heartbeat endpoint. The settings say so. | `imgbed.test.mjs` (desktop). |+| B05 | ImgBed and PicGo share one upload queue and the existing failure dialog (Retry / Save to EdgeEver / Cancel), with ImgBed-specific wording. A rejected token (HTTP 401/403) is reported without echoing the token. | `imgbed.test.mjs`, `picgo.test.mjs` (desktop). |+| B06 | The PicGo / PicList address may have any path ending in `/upload`; the connection test calls the sibling `…/heartbeat`. Other address rules (no query, fragment, credentials, link-local or metadata hosts) are unchanged. | `picgo.test.mjs` (desktop). |++## Scope and limits++- Desktop only, like PicGo. The web app shows "Available on desktop only."+- Deleting images from ImgBed is not supported: once the link is in a note, EdgeEver cannot tell whether another note still uses it.+- The token is stored in the renderer's local storage, like the PicGo server key, and is sent with every upload; use an HTTPS address.+- Images on ImgBed are not part of EdgeEver backups.++## Risk and rollback++Desktop renderer and main process only: no server, API, storage or migration changes. Users who keep "Built-in image hosting" are unaffected. The PicGo address rule is more permissive but keeps its host checks. Rollback: switch Settings → Image hosting back to the built-in option, or revert the change.++Not verified: uploads against a real ImgBed instance and a reverse-proxied PicList; interactive checks on Windows and Linux desktop; Japanese, Polish and Russian wording without native-speaker review.diff --git a/docs/changes/2026-10-30-desktop-imgbed-image-host.zh-CN.md b/docs/changes/2026-10-30-desktop-imgbed-image-host.zh-CN.mdnew file mode 100644index 00000000..fbb0afa1--- /dev/null+++ b/docs/changes/2026-10-30-desktop-imgbed-image-host.zh-CN.md@@ -0,0 +1,31 @@+# CloudFlare ImgBed 图床(桌面端)++[English](2026-10-30-desktop-imgbed-image-host.md)++## 问题与结果++实现 [Issue #734](https://github.com/tianma-if/edgeever/issues/734)。自建了 [CloudFlare ImgBed](https://github.com/MarSeventh/CloudFlare-ImgBed) 的桌面端用户,过去必须借助 PicList 中转才能使用。现在"设置 → 图床"新增第三个选项"CloudFlare ImgBed",与内置图床、PicGo / PicList 并列。与 PicGo 一样,桌面端负责上传新插入的图片,并把返回的链接写入笔记。同时放宽了 PicGo / PicList 的地址要求:从"路径必须是 `/upload`"改为"以 `/upload` 结尾",经过反向代理的 PicList(如 `https://nas.example.com/piclist/upload`)也能使用。++## 行为++| 编号 | 行为 | 验收 |+| --- | --- | --- |+| B01 | 设置项包括 ImgBed 地址(站点根地址或 `…/upload`)、具有 `upload` 权限的 API Token、可选的上传目录、ImgBed 的文件命名方式(`default`、`index`、`origin`、`short`)、上传渠道(`telegram`、`cfr2`、`s3`、`discord`、`huggingface`、`webdav`)以及服务端压缩。渠道和压缩的默认值与 ImgBed 接口一致:`telegram`,压缩开启。与 PicGo 一样,测试连接成功后才能保存。 | 桌面端 `imgbed.test.mjs`:地址与 Token 规范化。 |+| B02 | 上传目录支持 PicList 占位符 `{Y}` `{y}` `{m}` `{d}` `{h}` `{i}` `{s}` `{ms}` `{timestamp}` `{timestampS}` `{uuid}` `{str-N}`,以及 EdgeEver 的 `{memoId}`(接收图片的笔记)。日期按上传者本地时区计算。不支持的占位符、多余的花括号和非法字符会在保存前被拒绝;展开后最长可能超过主进程 200 字符上限的目录也会被拒绝(每个占位符按最长取值计算,`{memoId}` 最多 64 个字符),避免测试连接通过、带真实笔记 ID 上传时才失败;设置页显示展开后的预览。 | Web 端 `imgbed.test.mjs`。 |+| B03 | 上传时发送 `POST {地址}/upload?uploadChannel=…&serverCompress=…&uploadNameType=…&uploadFolder=…`,带 `Authorization: Bearer <token>`,图片放在 `file` 字段。ImgBed 返回 `publicUrl` 时写入该链接,否则用 ImgBed 地址解析 `src`。只接受单个不含账号密码的 http(s) 链接。 | 桌面端 `imgbed.test.mjs`。 |+| B04 | ImgBed 没有心跳接口,测试连接会向配置的目录上传一张名为 `edgeever-connection-test.png` 的 1×1 透明 PNG,设置页对此有说明。 | 桌面端 `imgbed.test.mjs`。 |+| B05 | ImgBed 与 PicGo 共用同一个上传队列和现有的失败对话框(重试 / 改存 EdgeEver / 取消),文案按 ImgBed 区分。Token 被拒(HTTP 401/403)时会给出提示,且不回显 Token。 | 桌面端 `imgbed.test.mjs`、`picgo.test.mjs`。 |+| B06 | PicGo / PicList 地址的路径只要以 `/upload` 结尾即可,测试连接调用同级的 `…/heartbeat`。其他地址规则(不能带查询参数、片段、账号密码,不能是链路本地或云元数据地址)保持不变。 | 桌面端 `picgo.test.mjs`。 |++## 范围与限制++- 与 PicGo 一样仅支持桌面端,Web 端显示"仅桌面端可用"。+- 不支持删除 ImgBed 上的图片:链接写入笔记后,EdgeEver 无法判断是否还有其他笔记在使用它。+- Token 与 PicGo 服务密钥一样保存在渲染进程的本地存储中,并随每次上传发送,请使用 HTTPS 地址。+- ImgBed 上的图片不包含在 EdgeEver 备份中。++## 风险与回滚++只改动桌面端的渲染进程和主进程,不涉及服务端、API、存储或 Migration。继续使用"内置图床"的用户不受影响。PicGo 地址规则有所放宽,但主机检查保持不变。回滚:把"设置 → 图床"切回内置图床,或回退此改动。++未验证:针对真实 ImgBed 实例和经反向代理的 PicList 的上传;Windows 和 Linux 桌面端的交互检查;日语、波兰语、俄语文案未经母语者审校。diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 36bfab28..a7a0eb27 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -1067,7 +1067,7 @@ export const enUS = {builtin: "Built-in image hosting (default)",external: "External image hosting (PicGo / PicList)",endpoint: "PicGo server address",- description: "Use PicGo on this computer, or a remote PicList such as one on a NAS. Keep the path as /upload.",+ description: "Use PicGo on this computer, or a remote PicList such as one on a NAS. The address must end with /upload; reverse-proxied addresses such as https://nas.example.com/piclist/upload also work.",serverKey: "Server key",serverKeyDescription: "Fill this in when PicList requires a key. Leave it empty when there is no key. The key is sent with each request, so use HTTPS for a remote server.",externalImages: "Images are stored on the external image host and excluded from EdgeEver backups.",@@ -1083,6 +1083,60 @@ export const enUS = {retry: "Retry",fallback: "Save to EdgeEver",cancel: "Cancel",+ imgbed: {+ option: "CloudFlare ImgBed",+ description: "Upload new images directly to your self-hosted CloudFlare ImgBed and insert the returned image link into the note.",+ endpoint: "ImgBed address",+ endpointDescription: "Enter the ImgBed site address, such as https://img.example.com. Don't include /upload; it is added automatically when uploading.",+ token: "API token",+ tokenDescription: "Create it in the ImgBed admin panel with the upload permission. The token is stored on this computer and sent with every upload, so use an HTTPS address.",+ folder: "Upload folder",+ folderDescription: "Optional. Use / for nested folders. You can use the placeholders below; times use this computer's time zone:",+ placeholders: {+ Y: "Four-digit year, e.g. 2026",+ y: "Two-digit year, e.g. 26",+ m: "Month, 01–12",+ d: "Day, 01–31",+ h: "Hour, 00–23",+ i: "Minute, 00–59",+ s: "Second, 00–59",+ ms: "Millisecond, 000–999",+ timestamp: "Timestamp in milliseconds",+ timestampS: "Timestamp in seconds",+ uuid: "Random UUID",+ strN: "N random letters and digits, N from 1 to 32, e.g. {str-6}",+ memoId: "ID of the note receiving the image; empty during the connection test, so that folder level is skipped",+ },+ folderPreview: "Example: uploads to {{folder}}",+ folderInvalid: {+ placeholder: "The folder contains an unsupported placeholder or a stray brace.",+ characters: "The folder cannot contain characters such as \\ ? # % < > : * | \".",+ length: "The expanded folder could exceed 200 characters (counting each placeholder at its longest value, {memoId} as 64 characters).",+ },+ nameType: "File naming",+ nameTypes: {+ default: "Default (random prefix_original name)",+ index: "Random prefix only",+ origin: "Original name only",+ short: "Short link",+ },+ channel: "Upload channel",+ channels: {+ telegram: "Telegram (default)",+ cfr2: "Cloudflare R2",+ s3: "S3",+ discord: "Discord",+ huggingface: "Hugging Face",+ webdav: "WebDAV",+ },+ serverCompress: "Server-side compression",+ serverCompressDescription: "ImgBed compresses images on the server. Only applies to the Telegram channel. On by default, matching the ImgBed API.",+ testDescription: "Testing uploads a 1×1 transparent image to this folder. You can delete it in ImgBed afterwards.",+ connected: "Connected to ImgBed. You can now save this setting.",+ connectionFailed: "Could not connect. Check the address, the API token, and its upload permission.",+ failedTitle: "ImgBed upload failed",+ failedMessage: "Check the ImgBed address, API token, and upload folder, and confirm ImgBed is reachable. Retrying may upload the image again.",+ },},imageCompressionTitle: "Compress note images",imageCompressionAria: "Compress note images",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex f2ecc063..c6a9e5fa 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -1056,7 +1056,7 @@ export const ja = {builtin: "内蔵画像ホスティング(既定)",external: "外部画像ホスティング(PicGo / PicList)",endpoint: "PicGo サーバーアドレス",- description: "このパソコンの PicGo、または NAS などの遠隔 PicList を指定します。パスは /upload のままにしてください。",+ description: "このパソコンの PicGo、または NAS などの遠隔 PicList を指定します。アドレスは /upload で終わる必要があります。https://nas.example.com/piclist/upload のようなリバースプロキシ経由のアドレスも使えます。",serverKey: "サーバーキー",serverKeyDescription: "PicList がキーを要求するときだけ入力します。不要なら空のままにします。キーはリクエストと一緒に送られるので、遠隔サーバーでは HTTPS を使ってください。",externalImages: "画像は外部ホストに保存され、EdgeEver のバックアップには含まれません。",@@ -1072,6 +1072,60 @@ export const ja = {retry: "再試行",fallback: "EdgeEver に保存",cancel: "キャンセル",+ imgbed: {+ option: "CloudFlare ImgBed",+ description: "新しく挿入した画像を自前の CloudFlare ImgBed に直接アップロードし、返された画像リンクをノートに挿入します。",+ endpoint: "ImgBed アドレス",+ endpointDescription: "ImgBed のサイトアドレス(例:https://img.example.com)を入力します。/upload は含めないでください。アップロード時に自動で付加されます。",+ token: "API トークン",+ tokenDescription: "ImgBed の管理画面で upload 権限付きで作成します。トークンはこのパソコンに保存され、アップロードごとに送信されるため、HTTPS のアドレスを使ってください。",+ folder: "アップロード先フォルダー",+ folderDescription: "任意。/ で階層を区切ります。次のプレースホルダーを使えます(時刻はこのパソコンのタイムゾーン):",+ placeholders: {+ Y: "4 桁の年(例:2026)",+ y: "2 桁の年(例:26)",+ m: "月(01–12)",+ d: "日(01–31)",+ h: "時(00–23)",+ i: "分(00–59)",+ s: "秒(00–59)",+ ms: "ミリ秒(000–999)",+ timestamp: "ミリ秒単位のタイムスタンプ",+ timestampS: "秒単位のタイムスタンプ",+ uuid: "ランダムな UUID",+ strN: "N 文字のランダムな英数字。N は 1–32(例:{str-6})",+ memoId: "画像を挿入するノートの ID。接続テストでは空になり、その階層は省略されます",+ },+ folderPreview: "例:{{folder}} にアップロード",+ folderInvalid: {+ placeholder: "未対応のプレースホルダー、または余分な波括弧があります。",+ characters: "フォルダーに \\ ? # % < > : * | \" などの文字は使えません。",+ length: "展開後のフォルダーが 200 文字を超える可能性があります(各プレースホルダーを最大長で計算し、{memoId} は 64 文字として扱います)。",+ },+ nameType: "ファイル名",+ nameTypes: {+ default: "既定(ランダム接頭辞_元のファイル名)",+ index: "ランダム接頭辞のみ",+ origin: "元のファイル名のみ",+ short: "短縮リンク",+ },+ channel: "アップロードチャネル",+ channels: {+ telegram: "Telegram(既定)",+ cfr2: "Cloudflare R2",+ s3: "S3",+ discord: "Discord",+ huggingface: "Hugging Face",+ webdav: "WebDAV",+ },+ serverCompress: "サーバー側で圧縮",+ serverCompressDescription: "ImgBed がサーバー側で画像を圧縮します。Telegram チャネルにのみ適用されます。ImgBed API と同じく既定でオンです。",+ testDescription: "接続テストではこのフォルダーに 1×1 の透明画像をアップロードします。テスト後に ImgBed で削除できます。",+ connected: "ImgBed に接続しました。設定を保存できます。",+ connectionFailed: "接続できません。アドレス、API トークンとその upload 権限を確認してください。",+ failedTitle: "ImgBed のアップロードに失敗しました",+ failedMessage: "ImgBed のアドレス、API トークン、アップロード先フォルダーを確認し、ImgBed にアクセスできることを確認してください。再試行すると画像が再度アップロードされる場合があります。",+ },},imageCompressionTitle: "ノート内の画像を圧縮",imageCompressionAria: "ノート内の画像を圧縮する",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex 1216510a..aba432b1 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -1056,7 +1056,7 @@ export const pl = {builtin: "Wbudowany hosting obrazów (domyślny)",external: "Zewnętrzny hosting obrazów (PicGo / PicList)",endpoint: "Adres serwera PicGo",- description: "Podaj PicGo na tym komputerze albo zdalny PicList, na przykład na NAS. Ścieżka musi być /upload.",+ description: "Podaj PicGo na tym komputerze albo zdalny PicList, na przykład na NAS. Adres musi kończyć się na /upload; działają też adresy za odwrotnym proxy, np. https://nas.example.com/piclist/upload.",serverKey: "Klucz serwera",serverKeyDescription: "Wpisz tylko wtedy, gdy PicList wymaga klucza. Zostaw puste, gdy klucza nie ma. Klucz jest wysyłany z każdym żądaniem, więc dla zdalnego serwera użyj HTTPS.",externalImages: "Obrazy są przechowywane na zewnętrznym hostingu i nie są uwzględniane w kopiach zapasowych EdgeEver.",@@ -1072,6 +1072,60 @@ export const pl = {retry: "Ponów",fallback: "Zapisz w EdgeEver",cancel: "Anuluj",+ imgbed: {+ option: "CloudFlare ImgBed",+ description: "Przesyłaj nowe obrazy bezpośrednio do własnego CloudFlare ImgBed i wstawiaj zwrócony link do notatki.",+ endpoint: "Adres ImgBed",+ endpointDescription: "Podaj adres witryny ImgBed, np. https://img.example.com. Nie dodawaj /upload — zostanie dodane automatycznie podczas przesyłania.",+ token: "Token API",+ tokenDescription: "Utwórz go w panelu ImgBed z uprawnieniem upload. Token jest zapisywany na tym komputerze i wysyłany przy każdym przesyłaniu, więc użyj adresu HTTPS.",+ folder: "Folder docelowy",+ folderDescription: "Opcjonalnie. Użyj / dla podfolderów. Możesz użyć poniższych symboli zastępczych; czas według strefy tego komputera:",+ placeholders: {+ Y: "Rok czterocyfrowy, np. 2026",+ y: "Rok dwucyfrowy, np. 26",+ m: "Miesiąc, 01–12",+ d: "Dzień, 01–31",+ h: "Godzina, 00–23",+ i: "Minuta, 00–59",+ s: "Sekunda, 00–59",+ ms: "Milisekunda, 000–999",+ timestamp: "Znacznik czasu w milisekundach",+ timestampS: "Znacznik czasu w sekundach",+ uuid: "Losowy UUID",+ strN: "N losowych liter i cyfr, N od 1 do 32, np. {str-6}",+ memoId: "ID notatki, do której wstawiany jest obraz; podczas testu połączenia pusty, więc ten poziom folderu jest pomijany",+ },+ folderPreview: "Przykład: przesyłanie do {{folder}}",+ folderInvalid: {+ placeholder: "Folder zawiera nieobsługiwany symbol zastępczy lub zbędny nawias klamrowy.",+ characters: "Folder nie może zawierać znaków takich jak \\ ? # % < > : * | \".",+ length: "Rozwinięty folder może przekroczyć 200 znaków (każdy symbol zastępczy liczony jest według najdłuższej wartości, {memoId} jako 64 znaki).",+ },+ nameType: "Nazwa pliku",+ nameTypes: {+ default: "Domyślna (losowy prefiks_oryginalna nazwa)",+ index: "Tylko losowy prefiks",+ origin: "Tylko oryginalna nazwa",+ short: "Krótki link",+ },+ channel: "Kanał przesyłania",+ channels: {+ telegram: "Telegram (domyślny)",+ cfr2: "Cloudflare R2",+ s3: "S3",+ discord: "Discord",+ huggingface: "Hugging Face",+ webdav: "WebDAV",+ },+ serverCompress: "Kompresja po stronie serwera",+ serverCompressDescription: "ImgBed kompresuje obrazy na serwerze. Działa tylko dla kanału Telegram. Domyślnie włączona, zgodnie z API ImgBed.",+ testDescription: "Test przesyła do tego folderu przezroczysty obraz 1×1. Po teście możesz go usunąć w ImgBed.",+ connected: "Połączono z ImgBed. Możesz zapisać ustawienie.",+ connectionFailed: "Nie udało się połączyć. Sprawdź adres, token API i jego uprawnienie upload.",+ failedTitle: "Przesyłanie do ImgBed nie powiodło się",+ failedMessage: "Sprawdź adres ImgBed, token API i folder docelowy oraz czy ImgBed jest dostępny. Ponowienie może przesłać obraz ponownie.",+ },},imageCompressionTitle: "Kompresuj obrazy w notatkach",imageCompressionAria: "Kompresuj obrazy w notatkach",diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.tsindex 75ff90e5..bba595bb 100644--- a/packages/shared/src/i18n/ru.ts+++ b/packages/shared/src/i18n/ru.ts@@ -1067,7 +1067,7 @@ export const ru = {builtin: "Встроенный хостинг изображений (по умолчанию)",external: "Внешний хостинг (PicGo / PicList)",endpoint: "Адрес сервера PicGo",- description: "PicGo на этом компьютере или удалённый PicList, например на NAS. Путь оставьте /upload.",+ description: "PicGo на этом компьютере или удалённый PicList, например на NAS. Адрес должен заканчиваться на /upload; подходят и адреса за обратным прокси, например https://nas.example.com/piclist/upload.",serverKey: "Ключ сервера",serverKeyDescription: "Заполните, если PicList требует ключ. Если ключа нет, оставьте пустым. Ключ уходит с каждым запросом, поэтому для удалённого сервера используйте HTTPS.",externalImages: "Изображения хранятся на внешнем хосте и не входят в резервные копии EdgeEver.",@@ -1083,6 +1083,60 @@ export const ru = {retry: "Повторить",fallback: "Сохранить в EdgeEver",cancel: "Отмена",+ imgbed: {+ option: "CloudFlare ImgBed",+ description: "Загружать новые изображения прямо в ваш CloudFlare ImgBed и вставлять полученную ссылку в заметку.",+ endpoint: "Адрес ImgBed",+ endpointDescription: "Укажите адрес сайта ImgBed, например https://img.example.com. Не добавляйте /upload — он подставляется автоматически при загрузке.",+ token: "API-токен",+ tokenDescription: "Создайте его в панели ImgBed с правом upload. Токен хранится на этом компьютере и отправляется с каждой загрузкой, поэтому используйте адрес HTTPS.",+ folder: "Папка загрузки",+ folderDescription: "Необязательно. Вложенные папки разделяйте символом /. Можно использовать заполнители ниже; время — по часовому поясу этого компьютера:",+ placeholders: {+ Y: "Год, четыре цифры, например 2026",+ y: "Год, две цифры, например 26",+ m: "Месяц, 01–12",+ d: "День, 01–31",+ h: "Час, 00–23",+ i: "Минута, 00–59",+ s: "Секунда, 00–59",+ ms: "Миллисекунда, 000–999",+ timestamp: "Метка времени в миллисекундах",+ timestampS: "Метка времени в секундах",+ uuid: "Случайный UUID",+ strN: "N случайных букв и цифр, N от 1 до 32, например {str-6}",+ memoId: "ID заметки, в которую вставляется изображение; при проверке соединения пуст, и этот уровень папки пропускается",+ },+ folderPreview: "Пример: загрузка в {{folder}}",+ folderInvalid: {+ placeholder: "В папке есть неподдерживаемый заполнитель или лишняя фигурная скобка.",+ characters: "Папка не может содержать символы \\ ? # % < > : * | \" и подобные.",+ length: "Раскрытая папка может превысить 200 символов (каждый заполнитель считается по максимальной длине, {memoId} — как 64 символа).",+ },+ nameType: "Имя файла",+ nameTypes: {+ default: "По умолчанию (случайный префикс_исходное имя)",+ index: "Только случайный префикс",+ origin: "Только исходное имя",+ short: "Короткая ссылка",+ },+ channel: "Канал загрузки",+ channels: {+ telegram: "Telegram (по умолчанию)",+ cfr2: "Cloudflare R2",+ s3: "S3",+ discord: "Discord",+ huggingface: "Hugging Face",+ webdav: "WebDAV",+ },+ serverCompress: "Сжатие на сервере",+ serverCompressDescription: "ImgBed сжимает изображения на сервере. Действует только для канала Telegram. Включено по умолчанию, как в API ImgBed.",+ testDescription: "При проверке в эту папку загружается прозрачное изображение 1×1. Потом его можно удалить в ImgBed.",+ connected: "Соединение с ImgBed есть. Теперь настройку можно сохранить.",+ connectionFailed: "Не удалось подключиться. Проверьте адрес, API-токен и его право upload.",+ failedTitle: "Не удалось загрузить в ImgBed",+ failedMessage: "Проверьте адрес ImgBed, API-токен и папку загрузки, а также доступность ImgBed. Повтор может загрузить изображение ещё раз.",+ },},imageCompressionTitle: "Сжимать изображения в заметках",imageCompressionAria: "Сжимать изображения в заметках",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex e8e32f2d..eeb5adc1 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -1067,7 +1067,7 @@ export const zhCN = {builtin: "内置图床(默认)",external: "外链图床(PicGo / PicList)",endpoint: "PicGo 服务地址",- description: "可以填本机 PicGo,或 NAS 等远程 PicList。路径保持为 /upload。",+ description: "可以填本机 PicGo,或 NAS 等远程 PicList。地址以 /upload 结尾,经过反向代理的地址(如 https://nas.example.com/piclist/upload)也可以。",serverKey: "服务密钥",serverKeyDescription: "PicList 开启密钥时填写,没有密钥就留空。密钥会随请求发送,远程服务请用 HTTPS。",externalImages: "图片保存在外部图床,不纳入 EdgeEver 备份。",@@ -1083,6 +1083,60 @@ export const zhCN = {retry: "重试",fallback: "改存 EdgeEver",cancel: "取消",+ imgbed: {+ option: "CloudFlare ImgBed",+ description: "把新插入的图片直接上传到你自建的 CloudFlare ImgBed,并把返回的图片链接写入笔记。",+ endpoint: "ImgBed 地址",+ endpointDescription: "填写 ImgBed 站点地址,例如 https://img.example.com。不要包含 /upload,上传时会自动补上。",+ token: "API Token",+ tokenDescription: "在 ImgBed 管理界面创建,需要 upload 权限。Token 保存在这台电脑上,并随每次上传发送,请使用 HTTPS 地址。",+ folder: "上传目录",+ folderDescription: "可选。用 / 分隔多级目录,可以使用下列占位符,时间按本机时区计算:",+ placeholders: {+ Y: "四位年份,如 2026",+ y: "两位年份,如 26",+ m: "月份,01–12",+ d: "日期,01–31",+ h: "小时,00–23",+ i: "分钟,00–59",+ s: "秒,00–59",+ ms: "毫秒,000–999",+ timestamp: "毫秒时间戳",+ timestampS: "秒级时间戳",+ uuid: "随机 UUID",+ strN: "N 位随机字母数字,N 为 1–32,如 {str-6}",+ memoId: "插入图片的笔记 ID;测试连接时为空,该级目录会被省略",+ },+ folderPreview: "示例:上传到 {{folder}}",+ folderInvalid: {+ placeholder: "目录里有不支持的占位符或多余的花括号。",+ characters: "目录不能包含 \\ ? # % < > : * | \" 等字符。",+ length: "目录展开后可能超过 200 个字符(按占位符的最长取值计算,{memoId} 按 64 个字符计)。",+ },+ nameType: "文件命名",+ nameTypes: {+ default: "默认(随机前缀_原文件名)",+ index: "仅随机前缀",+ origin: "仅原文件名",+ short: "短链接",+ },+ channel: "上传渠道",+ channels: {+ telegram: "Telegram(默认)",+ cfr2: "Cloudflare R2",+ s3: "S3",+ discord: "Discord",+ huggingface: "Hugging Face",+ webdav: "WebDAV",+ },+ serverCompress: "服务端压缩",+ serverCompressDescription: "由 ImgBed 在服务端压缩图片,仅对 Telegram 渠道生效。默认开启,与 ImgBed 接口一致。",+ testDescription: "测试连接会向该目录上传一张 1×1 的透明图片,测试后可在 ImgBed 中删除。",+ connected: "已连接 ImgBed,可以保存设置。",+ connectionFailed: "连接失败。请检查地址、API Token 及其 upload 权限。",+ failedTitle: "ImgBed 上传失败",+ failedMessage: "请检查 ImgBed 地址、API Token 和上传目录,并确认 ImgBed 可以访问。重试可能会再次上传图片。",+ },},imageCompressionTitle: "压缩笔记内图片",imageCompressionAria: "是否压缩笔记内图片",