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
18 changes: 17 additions & 1 deletion api/routers/wiki.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import asyncio
import os
import re
from datetime import datetime
from typing import Optional, Literal
from urllib.parse import quote

from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import JSONResponse, Response, StreamingResponse
Expand Down Expand Up @@ -34,6 +36,20 @@
router = APIRouter(tags=["wiki"])


def _attachment_header(filename: str) -> str:
"""Build a Content-Disposition value that is safe for any file name.

Header values are encoded as latin-1, so a non-ASCII name (for example a
local repository in a Chinese directory) cannot go in ``filename=``. Send
an ASCII fallback there and the real name in ``filename*`` (RFC 6266).
"""
fallback = re.sub(r'[^A-Za-z0-9._-]', "_", filename)
return (
f'attachment; filename="{fallback}"; '
f"filename*=UTF-8''{quote(filename, safe='')}"
)


@router.post("/export/wiki")
async def post_export_wiki(request: WikiExportRequest):
"""
Expand Down Expand Up @@ -74,7 +90,7 @@ async def post_export_wiki(request: WikiExportRequest):
return Response(
content=content,
media_type=media_type,
headers={"Content-Disposition": f"attachment; filename={filename}"},
headers={"Content-Disposition": _attachment_header(filename)},
)


Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"dev": "next dev --turbopack --port 3000",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"test": "node --test \"tests/frontend/*.test.mjs\""
},
"dependencies": {
"mermaid": "^11.17.2",
Expand Down
14 changes: 5 additions & 9 deletions src/app/[owner]/[repo]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import ThemeToggle from '@/components/theme-toggle';
import WikiTreeView from '@/components/WikiTreeView';
import { useLanguage } from '@/contexts/LanguageContext';
import { RepoInfo } from '@/types/repoinfo';
import { filenameFromContentDisposition } from '@/utils/contentDisposition';
import getRepoUrl from '@/utils/getRepoUrl';
import {
submitWikiTask,
Expand Down Expand Up @@ -620,15 +621,10 @@ export default function RepoWikiPage() {
}

// Get the filename from the Content-Disposition header if available
const contentDisposition = response.headers.get('Content-Disposition');
let filename = `${effectiveRepoInfo.repo}_wiki.${format === 'markdown' ? 'md' : 'json'}`;

if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename=(.+)/);
if (filenameMatch && filenameMatch[1]) {
filename = filenameMatch[1].replace(/"/g, '');
}
}
const filename = filenameFromContentDisposition(
response.headers.get('Content-Disposition'),
`${effectiveRepoInfo.repo}_wiki.${format === 'markdown' ? 'md' : 'json'}`
);

// Convert the response to a blob and download it
const blob = await response.blob();
Expand Down
24 changes: 24 additions & 0 deletions src/utils/contentDisposition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export function filenameFromContentDisposition(header: string | null, fallback: string): string {
if (!header) {
return fallback;
}

const encodedMatch = header.match(/filename\*=UTF-8''([^;]+)/i);
if (encodedMatch && encodedMatch[1]) {
try {
const decoded = decodeURIComponent(encodedMatch[1].trim());
if (decoded) {
return decoded;
}
} catch {
// malformed percent-encoding, fall back to filename=
}
}

const plainMatch = header.match(/filename="?([^";]+)"?/i);
if (plainMatch && plainMatch[1]) {
return plainMatch[1].trim();
}

return fallback;
}
49 changes: 49 additions & 0 deletions tests/backend/routers/test_wiki_export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from urllib.parse import unquote

import pytest
from fastapi.testclient import TestClient


def _export(repo_url: str):
from api.main import app

client = TestClient(app, raise_server_exceptions=False)
return client.post(
"/export/wiki",
json={
"repo_url": repo_url,
"type": "local",
"format": "markdown",
"pages": [
{
"id": "page-1",
"title": "P1",
"content": "body",
"filePaths": [],
"importance": "high",
"relatedPages": [],
}
],
},
)


@pytest.mark.parametrize(
"repo_url, repo_name",
[
("https://github.com/owner/repo", "repo"),
("/home/user/项目", "项目"),
("/home/user/my repo", "my repo"),
],
)
def test_export_wiki_content_disposition(repo_url, repo_name):
response = _export(repo_url)

assert response.status_code == 200
header = response.headers["content-disposition"]
header.encode("ascii")
assert header.startswith('attachment; filename="')
encoded = header.split("filename*=UTF-8''", 1)[1]
filename = unquote(encoded)
assert filename.startswith(f"{repo_name}_wiki_")
assert filename.endswith(".md")
35 changes: 35 additions & 0 deletions tests/frontend/contentDisposition.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';

import { filenameFromContentDisposition } from '../../src/utils/contentDisposition.ts';

const fallback = 'repo_wiki.md';

test('filename* takes precedence over filename=', () => {
const header = `attachment; filename="____wiki_20260101.md"; filename*=UTF-8''%E9%A1%B9%E7%9B%AE_wiki_20260101.md`;
assert.equal(filenameFromContentDisposition(header, fallback), '项目_wiki_20260101.md');
});

test('filename* is used when it comes first', () => {
const header = `attachment; filename*=UTF-8''my%20repo_wiki.md; filename="my_repo_wiki.md"`;
assert.equal(filenameFromContentDisposition(header, fallback), 'my repo_wiki.md');
});

test('malformed percent-encoding falls back to filename=', () => {
const header = `attachment; filename="broken_wiki.md"; filename*=UTF-8''%E9%A1%ZZ_wiki.md`;
assert.equal(filenameFromContentDisposition(header, fallback), 'broken_wiki.md');
});

test('unquoted filename= is read without trailing parameters', () => {
const header = 'attachment; filename=deepwiki_wiki.json; size=10';
assert.equal(filenameFromContentDisposition(header, fallback), 'deepwiki_wiki.json');
});

test('missing header keeps the default name', () => {
assert.equal(filenameFromContentDisposition(null, fallback), fallback);
assert.equal(filenameFromContentDisposition('', fallback), fallback);
});

test('header without a filename keeps the default name', () => {
assert.equal(filenameFromContentDisposition('attachment', fallback), fallback);
});
Loading