Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions astrbot/dashboard/routes/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import uuid
from contextlib import asynccontextmanager
from copy import deepcopy
from pathlib import Path, PurePosixPath
from typing import Any, cast

from quart import Response as QuartResponse
Expand Down Expand Up @@ -32,6 +33,16 @@
SSE_HEARTBEAT = ": heartbeat\n\n"


def _sanitize_upload_filename(filename: str | None) -> str:
if not filename:
return f"{uuid.uuid4()!s}"
normalized = filename.replace("\\", "/")
name = PurePosixPath(normalized).name.replace("\x00", "").strip()
if name in ("", ".", ".."):
return f"{uuid.uuid4()!s}"
return name


@asynccontextmanager
async def track_conversation(convs: dict, conv_id: str):
convs[conv_id] = True
Expand Down Expand Up @@ -333,7 +344,7 @@ async def post_file(self):
return Response().error("Missing key: file").__dict__

file = post_data["file"]
filename = file.filename or f"{uuid.uuid4()!s}"
filename = _sanitize_upload_filename(file.filename)
content_type = file.content_type or "application/octet-stream"

# 根据 content_type 判断文件类型并添加扩展名
Expand All @@ -346,12 +357,16 @@ async def post_file(self):
else:
attach_type = "file"

path = os.path.join(self.attachments_dir, filename)
await file.save(path)
attachments_dir = Path(self.attachments_dir).resolve(strict=False)
file_path = (attachments_dir / filename).resolve(strict=False)
if not file_path.is_relative_to(attachments_dir):
return Response().error("Invalid filename").__dict__

await file.save(str(file_path))

# 创建 attachment 记录
attachment = await self.db.insert_attachment(
path=path,
path=str(file_path),
type=attach_type,
mime_type=content_type,
)
Expand Down
3 changes: 2 additions & 1 deletion dashboard/src/components/chat/ChatMessageList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ import type {
MessagePart,
} from "@/composables/useMessages";
import { useI18n, useModuleI18n } from "@/i18n/composables";
import { copyToClipboard } from "@/utils/clipboard";

const props = withDefaults(
defineProps<{
Expand Down Expand Up @@ -809,7 +810,7 @@ function toolCallStatusText(tool: Record<string, unknown>) {
async function copyMessage(message: ChatRecord) {
const text = plainTextFromMessage(message);
if (!text) return;
await navigator.clipboard?.writeText(text);
await copyToClipboard(text);
}

async function downloadPart(part: MessagePart) {
Expand Down
3 changes: 2 additions & 1 deletion dashboard/src/components/chat/MessageList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ import type {
MessagePart,
} from "@/composables/useMessages";
import { useModuleI18n } from "@/i18n/composables";
import { copyToClipboard } from "@/utils/clipboard";

const props = withDefaults(
defineProps<{
Expand Down Expand Up @@ -470,7 +471,7 @@ function parseJsonSafe(value: unknown) {
async function copyMessage(message: ChatRecord) {
const text = plainTextFromMessage(message);
if (!text) return;
await navigator.clipboard?.writeText(text);
await copyToClipboard(text, { container: messageListRoot.value });
}

async function downloadPart(part: MessagePart) {
Expand Down
32 changes: 4 additions & 28 deletions dashboard/src/components/shared/ReadmeDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import MarkdownIt from "markdown-it";
import axios from "axios";
import DOMPurify from "dompurify";
import { useI18n } from "@/i18n/composables";
import { copyToClipboard } from "@/utils/clipboard";
import {
escapeHtml,
ensureShikiLanguages,
Expand Down Expand Up @@ -349,19 +350,13 @@ watch([content, locale, isDark], () => {
updateRenderedHtml();
}, { immediate: true });

function handleContainerClick(event) {
async function handleContainerClick(event) {
const btn = event.target.closest(".copy-code-btn");
if (btn) {
const code = btn.closest(".code-block-wrapper")?.querySelector("code");
if (code) {
if (navigator.clipboard?.writeText) {
navigator.clipboard
.writeText(code.textContent)
.then(() => showCopyFeedback(btn, true))
.catch(() => tryFallbackCopy(code.textContent, btn));
} else {
tryFallbackCopy(code.textContent, btn);
}
const success = await copyToClipboard(code.textContent || "");
showCopyFeedback(btn, success);
}
return;
}
Expand All @@ -382,25 +377,6 @@ function handleContainerClick(event) {
target.scrollIntoView({ behavior: "smooth", block: "start" });
}

function tryFallbackCopy(text, btn) {
try {
const textArea = document.createElement("textarea");
textArea.value = text;
Object.assign(textArea.style, {
position: "absolute",
opacity: "0",
zIndex: "-1",
});
btn.parentNode.appendChild(textArea);
textArea.select();
const success = document.execCommand("copy");
btn.parentNode.removeChild(textArea);
showCopyFeedback(btn, success);
} catch (err) {
showCopyFeedback(btn, false);
}
}

function showCopyFeedback(btn, success) {
if (copyFeedbackTimer.value) clearTimeout(copyFeedbackTimer.value);
btn.setAttribute("title", t(`core.common.${success ? "copied" : "error"}`));
Expand Down
92 changes: 92 additions & 0 deletions dashboard/src/utils/clipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
interface CopyToClipboardOptions {
container?: HTMLElement | null;
}

export async function copyToClipboard(
text: string,
options: CopyToClipboardOptions = {},
): Promise<boolean> {
const container = options.container;
const debugInfo = {
length: text?.length ?? 0,
trimmedLength: text?.trim().length ?? 0,
isSecureContext: typeof window !== "undefined" ? window.isSecureContext : false,
hasClipboardApi:
typeof navigator !== "undefined" && !!navigator.clipboard?.writeText,
containerTag: container?.tagName ?? null,
containerInBody:
typeof document !== "undefined" && !!container && document.body.contains(container),
};

if (!text) {
console.debug("[clipboard] empty text payload", debugInfo);
return false;
}

console.debug("[clipboard] copy request", debugInfo);

if (typeof navigator !== "undefined" && navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
console.info("[clipboard] copied via Clipboard API", debugInfo);
return true;
} catch (err) {
console.warn("[clipboard] Clipboard API failed, falling back:", err, debugInfo);
}
}

const fallbackOk = fallbackCopy(text, container);
if (fallbackOk) {
console.info("[clipboard] fallback succeeded via document.execCommand('copy')", debugInfo);
} else {
console.warn("[clipboard] fallback failed via document.execCommand('copy')", debugInfo);
}
return fallbackOk;
}

function fallbackCopy(text: string, container?: HTMLElement | null): boolean {
if (typeof document === "undefined" || !document.body) return false;

const mountTarget =
container && document.body.contains(container) ? container : document.body;
const textArea = document.createElement("textarea");
const activeElement =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
const selection = document.getSelection();
const selectedRanges = selection
? Array.from({ length: selection.rangeCount }, (_, index) =>
selection.getRangeAt(index).cloneRange(),
)
: [];

textArea.value = text;
textArea.readOnly = true;
Object.assign(textArea.style, {
position: "fixed",
left: "-9999px",
top: "0",
opacity: "0",
pointerEvents: "none",
});

mountTarget.appendChild(textArea);
textArea.focus();
textArea.select();
textArea.setSelectionRange(0, text.length);

try {
return document.execCommand("copy");
} catch (err) {
console.error("Fallback copy failed:", err);
return false;
} finally {
if (textArea.parentNode) {
textArea.parentNode.removeChild(textArea);
}
if (selection) {
selection.removeAllRanges();
selectedRanges.forEach((range) => selection.addRange(range));
}
activeElement?.focus?.();
}
}
7 changes: 4 additions & 3 deletions dashboard/src/views/ConversationPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ import {
askForConfirmation as askForConfirmationDialog,
useConfirmDialog
} from '@/utils/confirmDialog';
import { copyToClipboard } from '@/utils/clipboard';

export default {
name: 'ConversationPage',
Expand Down Expand Up @@ -638,10 +639,10 @@ export default {
},

async copyUmoSource(item) {
try {
await navigator.clipboard.writeText(this.formatUmoSource(item));
const ok = await copyToClipboard(this.formatUmoSource(item));
if (ok) {
this.showSuccessMessage(this.tm('messages.copySuccess'));
} catch (error) {
} else {
this.showErrorMessage(this.tm('messages.copyError'));
}
},
Expand Down
7 changes: 4 additions & 3 deletions dashboard/src/views/PlatformPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ import {
askForConfirmation as askForConfirmationDialog,
useConfirmDialog
} from '@/utils/confirmDialog';
import { copyToClipboard } from '@/utils/clipboard';

export default {
name: 'PlatformPage',
Expand Down Expand Up @@ -608,10 +609,10 @@ export default {

async copyWebhookUrl(webhookUuid) {
const url = this.getWebhookUrl(webhookUuid);
try {
await navigator.clipboard.writeText(url);
const ok = await copyToClipboard(url);
if (ok) {
this.showSuccess(this.tm('webhookCopied'));
} catch (err) {
} else {
this.showError(this.tm('webhookCopyFailed'));
}
}
Expand Down
44 changes: 2 additions & 42 deletions dashboard/src/views/Settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ import SidebarCustomizer from '@/components/shared/SidebarCustomizer.vue';
import BackupDialog from '@/components/shared/BackupDialog.vue';
import StorageCleanupPanel from '@/components/shared/StorageCleanupPanel.vue';
import { restartAstrBot as restartAstrBotRuntime } from '@/utils/restartAstrBot';
import { copyToClipboard } from '@/utils/clipboard';
import { useModuleI18n } from '@/i18n/composables';
import { useTheme } from 'vuetify';
import { PurpleTheme } from '@/theme/LightTheme';
Expand Down Expand Up @@ -338,50 +339,9 @@ const loadApiKeys = async () => {
}
};

const tryExecCommandCopy = (text) => {
let textArea = null;
try {
if (typeof document === 'undefined' || !document.body) return false;
textArea = document.createElement('textarea');
textArea.value = text;
textArea.setAttribute('readonly', '');
textArea.style.position = 'fixed';
textArea.style.opacity = '0';
textArea.style.pointerEvents = 'none';
textArea.style.left = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
textArea.setSelectionRange(0, text.length);
return document.execCommand('copy');
} catch (_) {
return false;
} finally {
try {
if (textArea?.parentNode) {
textArea.parentNode.removeChild(textArea);
}
} catch (_) {
// ignore cleanup errors
}
}
};

const copyTextToClipboard = async (text) => {
if (!text) return false;
if (tryExecCommandCopy(text)) return true;
if (typeof navigator === 'undefined' || !navigator.clipboard?.writeText) return false;
try {
await navigator.clipboard.writeText(text);
return true;
} catch (_) {
return false;
}
};

const copyCreatedApiKey = async () => {
if (!createdApiKeyPlaintext.value) return;
const ok = await copyTextToClipboard(createdApiKeyPlaintext.value);
const ok = await copyToClipboard(createdApiKeyPlaintext.value);
if (ok) {
showToast(tm('apiKey.messages.copySuccess'), 'success');
} else {
Expand Down
32 changes: 32 additions & 0 deletions tests/unit/test_upload_filename_sanitization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Tests for upload filename sanitization."""

from astrbot.dashboard.routes.chat import _sanitize_upload_filename


def test_sanitize_upload_filename_strips_posix_traversal():
assert _sanitize_upload_filename("../../outside.txt") == "outside.txt"


def test_sanitize_upload_filename_strips_windows_traversal():
assert _sanitize_upload_filename(r"..\\..\\outside.txt") == "outside.txt"


def test_sanitize_upload_filename_strips_fakepath():
assert _sanitize_upload_filename(r"C:\\fakepath\\photo.png") == "photo.png"


def test_sanitize_upload_filename_falls_back_for_empty_values():
generated = _sanitize_upload_filename("")

assert generated
assert generated not in {".", ".."}
assert "/" not in generated
assert "\\" not in generated


def test_sanitize_upload_filename_removes_embedded_null_bytes():
assert _sanitize_upload_filename("evil\x00.txt") == "evil.txt"
assert _sanitize_upload_filename("\x00leading.txt") == "leading.txt"
assert _sanitize_upload_filename("trailing\x00.txt\x00") == "trailing.txt"
assert _sanitize_upload_filename("mid\x00dle.txt") == "middle.txt"

Loading