diff --git a/src/main/server/index.ts b/src/main/server/index.ts index 941d1051..90a062bd 100644 --- a/src/main/server/index.ts +++ b/src/main/server/index.ts @@ -206,13 +206,34 @@ const attachment = async (ctx: any, next: any) => { await file.upload(repo, buffer, path) ctx.body = result('ok', 'success', path) } else if (ctx.method === 'GET') { - const { repo, path } = ctx.query + let { repo, path } = ctx.query + + if (!repo || !path) { + const filePath = ctx.path.replace('/api/attachment', '') + const arr = filePath.split('/') + repo = arr[1] + path = decodeURI(arr.slice(2).join('/')) + } + + if (!repo || !path) { + throw new Error('Invalid path.') + } checkPrivateRepo(ctx, repo) noCache(ctx) - ctx.type = mime.getType(path) - ctx.body = await file.read(repo, path) + + try { + ctx.body = await file.read(repo, path) + ctx.type = mime.getType(path) + } catch (error: any) { + if (error.code === 'ENOENT') { + ctx.status = 404 + ctx.body = result('error', 'Not found') + } else { + throw error + } + } } } else { await next() diff --git a/src/renderer/services/base.ts b/src/renderer/services/base.ts index 4f627ab6..cfbf42d1 100644 --- a/src/renderer/services/base.ts +++ b/src/renderer/services/base.ts @@ -3,7 +3,7 @@ import filenamify from 'filenamify/browser' import type { Doc, FindInRepositoryQuery } from '@fe/types' import * as api from '@fe/support/api' import { FLAG_DEMO, HELP_REPO_NAME } from '@fe/support/args' -import { binMd5, quote, fileToBase64URL, getLogger, removeQuery } from '@fe/utils' +import { binMd5, quote, fileToBase64URL, getLogger } from '@fe/utils' import { basename, resolve, extname, dirname, relative, isBelongTo } from '@fe/utils/path' import { dayjs } from '@fe/context/lib' import { useModal } from '@fe/support/ui/modal' @@ -27,13 +27,12 @@ export function getAttachmentURL (doc: Doc, opts: { origin: boolean } = { origin throw new Error('Document type must be file') } - const fileName = removeQuery(doc.name) const repo = doc.repo - const filePath = doc.path + const filePath = resolve(doc.path) const uri = repo === HELP_REPO_NAME ? `/api/help/file?path=${encodeURIComponent(filePath)}` - : `/api/attachment/${encodeURIComponent(fileName)}?repo=${repo}&path=${encodeURIComponent(filePath)}` + : `/api/attachment/${encodeURIComponent(repo)}${encodeURI(filePath)}` if (opts.origin) { return `${window.location.origin}${uri}`