Skip to content
Closed
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
14 changes: 12 additions & 2 deletions lib/utils/resolve-file-proxy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { FileProxy } from "../db/schema"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import { resolve, sep } from "node:path"
import { normalizePath } from "./normalize-path"

export async function resolveFileProxy(
Expand All @@ -14,6 +14,12 @@ export async function resolveFileProxy(
// Pattern: "prefix/*" -> prefix is "prefix/"
const prefix = pattern.slice(0, -1) // Remove "*" to get "prefix/"
const relativePath = normalizedPath.slice(prefix.length)
if (
normalizedPath.split("/").some((seg) => seg === ".." || seg === ".") ||
relativePath.split("/").some((seg) => seg === ".." || seg === ".")
) {
return new Response("Invalid file path", { status: 400 })
}

if (proxy.proxy_type === "disk") {
return resolveDiskProxy(proxy.disk_path, relativePath)
Expand All @@ -26,7 +32,11 @@ async function resolveDiskProxy(
diskPath: string,
relativePath: string,
): Promise<Response> {
const fullPath = join(diskPath, relativePath)
const rootPath = resolve(diskPath)
const fullPath = resolve(rootPath, relativePath.replace(/^\/+/, ""))
if (fullPath !== rootPath && !fullPath.startsWith(rootPath + sep)) {
return new Response("Invalid file path", { status: 400 })
}

try {
const content = await readFile(fullPath)
Expand Down
23 changes: 23 additions & 0 deletions routes/files/download/[[file_path]].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["GET"],
pathParams: z.object({
file_path: z.string(),
}),
})((req, ctx) => {
const { file_path } = req.routeParams as { file_path: string }
const file = ctx.db.getFile({ file_path: `/${file_path}` })

if (!file) {
return new Response("File not found", { status: 404 })
}

return new Response(file.text_content, {
headers: {
"Content-Type": "text/plain",
"Content-Disposition": `attachment; filename="${file.file_path.split("/").pop()}"`,
},
})
})
Loading