From d7f2a4f398bb361b01c6d56f576a4b8e3faea2a5 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:05:23 +0800 Subject: [PATCH 1/2] feat(files): extend patch file endpoint with name and folderId Support renaming and moving files via PATCH /api/files/:id with validation, conflict checks, and preservation of R2 keys and shares. Checkpoint: jeIm07FRyt8ipQ-pMLlfK --- worker/src/db/queries/files.ts | 115 +++-- worker/src/routes/files.ts | 141 +++++- worker/test/files-upload-download.test.ts | 496 ++++++++++++++++++++++ 3 files changed, 700 insertions(+), 52 deletions(-) diff --git a/worker/src/db/queries/files.ts b/worker/src/db/queries/files.ts index 157a20f..56e2b6f 100644 --- a/worker/src/db/queries/files.ts +++ b/worker/src/db/queries/files.ts @@ -153,26 +153,45 @@ export async function checkFileNameConflict( prefix: string, userId: number, folderId: string | null, - name: string + name: string, + excludeFileId?: string ): Promise { const statement = folderId === null - ? db - .prepare( - `SELECT 1 AS exists_row - FROM ${filesTable(prefix)} - WHERE user_id = ? AND folder_id IS NULL AND name = ? COLLATE NOCASE - LIMIT 1` - ) - .bind(userId, name) - : db - .prepare( - `SELECT 1 AS exists_row - FROM ${filesTable(prefix)} - WHERE user_id = ? AND folder_id = ? AND name = ? COLLATE NOCASE - LIMIT 1` - ) - .bind(userId, folderId, name) + ? excludeFileId + ? db + .prepare( + `SELECT 1 AS exists_row + FROM ${filesTable(prefix)} + WHERE user_id = ? AND folder_id IS NULL AND name = ? COLLATE NOCASE AND id != ? + LIMIT 1` + ) + .bind(userId, name, excludeFileId) + : db + .prepare( + `SELECT 1 AS exists_row + FROM ${filesTable(prefix)} + WHERE user_id = ? AND folder_id IS NULL AND name = ? COLLATE NOCASE + LIMIT 1` + ) + .bind(userId, name) + : excludeFileId + ? db + .prepare( + `SELECT 1 AS exists_row + FROM ${filesTable(prefix)} + WHERE user_id = ? AND folder_id = ? AND name = ? COLLATE NOCASE AND id != ? + LIMIT 1` + ) + .bind(userId, folderId, name, excludeFileId) + : db + .prepare( + `SELECT 1 AS exists_row + FROM ${filesTable(prefix)} + WHERE user_id = ? AND folder_id = ? AND name = ? COLLATE NOCASE + LIMIT 1` + ) + .bind(userId, folderId, name) const row = await statement.first<{ exists_row: number }>() return row !== null @@ -258,27 +277,53 @@ export async function deleteFileRecord( return result.meta.changes > 0 } -export async function updateFileExpiration( +export interface UpdateFileInput { + name?: string + folderId?: string | null + expiresAt?: string | null +} + +export async function updateFileRecord( db: D1Database, prefix: string, userId: number, fileId: string, - newExpiresAt: string | null + patch: UpdateFileInput ): Promise { const file = await findFileById(db, prefix, userId, fileId) if (!file) return null - await db - .prepare( - `UPDATE ${filesTable(prefix)} - SET expires_at = ? - WHERE id = ? AND user_id = ?` - ) - .bind(newExpiresAt, fileId, userId) - .run() + const assignments: string[] = [] + const values: Array = [] + + if (patch.name !== undefined) { + assignments.push("name = ?") + values.push(patch.name) + } + + if (patch.folderId !== undefined) { + assignments.push("folder_id = ?") + values.push(patch.folderId) + } + + if (patch.expiresAt !== undefined) { + assignments.push("expires_at = ?") + values.push(patch.expiresAt) + } + + if (assignments.length > 0) { + await db + .prepare( + `UPDATE ${filesTable(prefix)} + SET ${assignments.join(", ")} + WHERE id = ? AND user_id = ?` + ) + .bind(...values, fileId, userId) + .run() + } // 若缩短了过期时间,同步截断越过新到期时间的分享行(规格 §5.4 / §6) - if (newExpiresAt !== null) { + if (patch.expiresAt !== undefined && patch.expiresAt !== null) { await db .prepare( `UPDATE ${sharesTable(prefix)} @@ -286,9 +331,21 @@ export async function updateFileExpiration( WHERE file_id = ? AND (expires_at IS NULL OR expires_at > ?)` ) - .bind(newExpiresAt, fileId, newExpiresAt) + .bind(patch.expiresAt, fileId, patch.expiresAt) .run() } return await findFileById(db, prefix, userId, fileId) } + +export async function updateFileExpiration( + db: D1Database, + prefix: string, + userId: number, + fileId: string, + newExpiresAt: string | null +): Promise { + return await updateFileRecord(db, prefix, userId, fileId, { + expiresAt: newExpiresAt + }) +} diff --git a/worker/src/routes/files.ts b/worker/src/routes/files.ts index 149e256..c281d59 100644 --- a/worker/src/routes/files.ts +++ b/worker/src/routes/files.ts @@ -12,9 +12,9 @@ import { isFileExpired, isValidExpiresInPreset, toFileView, - updateFileExpiration + updateFileRecord } from "../db/queries/files" -import { findFolderById } from "../db/queries/folders" +import { findFolderById, isValidFolderName } from "../db/queries/folders" import { createShareRecord, listSharesByFile } from "../db/queries/shares" import { completeFileUpload, @@ -526,18 +526,119 @@ fileRoutes.patch("/:id", async (c) => { const prefix = getTablePrefix(c.env) const fileId = c.req.param("id")?.trim() - const body = await readJsonBody<{ expiresIn?: unknown }>(c) + if (!fileId) { + return apiError(c, 404, "FILE_NOT_FOUND", "File not found") + } + + const body = await readJsonBody<{ + name?: unknown + folderId?: unknown + expiresIn?: unknown + }>(c) if (!body) { return apiError(c, 400, "INVALID_REQUEST", "Invalid request body") } - let preset: string | null = null - if (typeof body.expiresIn === "string") { - if ( - body.expiresIn !== "" && - body.expiresIn !== "never" && - !isValidExpiresInPreset(body.expiresIn) - ) { + const hasName = body.name !== undefined + const hasFolderId = body.folderId !== undefined + const hasExpiresIn = body.expiresIn !== undefined + + if (!hasName && !hasFolderId && !hasExpiresIn) { + return apiError( + c, + 400, + "INVALID_REQUEST", + "At least one field (name, folderId, expiresIn) is required" + ) + } + + const file = await findFileById(c.env.DB, prefix, userId, fileId) + if (!file) { + return apiError(c, 404, "FILE_NOT_FOUND", "File not found") + } + + let targetFolderId: string | null = file.folder_id + if (hasFolderId) { + if (body.folderId === null) { + targetFolderId = null + } else if (typeof body.folderId === "string") { + const trimmedFolderId = body.folderId.trim() + if (!trimmedFolderId) { + return apiError(c, 404, "FOLDER_NOT_FOUND", "Folder not found") + } + const folder = await findFolderById( + c.env.DB, + prefix, + userId, + trimmedFolderId + ) + if (!folder) { + return apiError(c, 404, "FOLDER_NOT_FOUND", "Folder not found") + } + targetFolderId = trimmedFolderId + } else { + return apiError( + c, + 400, + "INVALID_REQUEST", + "folderId must be a string or null" + ) + } + } + + let targetName = file.name + if (hasName) { + if (typeof body.name !== "string" || !isValidFolderName(body.name)) { + return apiError( + c, + 400, + "INVALID_FILENAME", + "File name must be between 1 and 255 characters and cannot contain slashes" + ) + } + targetName = body.name.trim() + } + + if (hasName || hasFolderId) { + const isConflict = await checkFileNameConflict( + c.env.DB, + prefix, + userId, + targetFolderId, + targetName, + file.id + ) + if (isConflict) { + return apiError( + c, + 409, + "FILE_NAME_CONFLICT", + "A file with the same name already exists in this folder" + ) + } + } + + let newExpiresAt: string | null | undefined + if (hasExpiresIn) { + let preset: string | null = null + if (typeof body.expiresIn === "string") { + const trimmed = body.expiresIn.trim() + if ( + trimmed !== "" && + trimmed !== "never" && + !isValidExpiresInPreset(trimmed) + ) { + return apiError( + c, + 400, + "INVALID_EXPIRES_IN", + "Invalid expiration preset (allowed: never, 1h, 24h, 7d, 30d)" + ) + } + preset = trimmed === "" ? null : trimmed + } else if (body.expiresIn === null) { + preset = null + } else { return apiError( c, 400, @@ -545,26 +646,20 @@ fileRoutes.patch("/:id", async (c) => { "Invalid expiration preset (allowed: never, 1h, 24h, 7d, 30d)" ) } - preset = body.expiresIn + newExpiresAt = calculateExpiresAt(preset) } - const newExpiresAt = calculateExpiresAt(preset) - const updated = await updateFileExpiration( - c.env.DB, - prefix, - userId, - fileId, - newExpiresAt - ) + const updated = await updateFileRecord(c.env.DB, prefix, userId, fileId, { + ...(hasName ? { name: targetName } : {}), + ...(hasFolderId ? { folderId: targetFolderId } : {}), + ...(hasExpiresIn ? { expiresAt: newExpiresAt } : {}) + }) if (!updated) { return apiError(c, 404, "FILE_NOT_FOUND", "File not found") } - return c.json({ - id: updated.id, - expiresAt: updated.expires_at - }) + return c.json(toFileView(updated)) }) fileRoutes.post("/:id/shares", async (c) => { diff --git a/worker/test/files-upload-download.test.ts b/worker/test/files-upload-download.test.ts index 41c522e..281cdb6 100644 --- a/worker/test/files-upload-download.test.ts +++ b/worker/test/files-upload-download.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest" +import { createFolder } from "../src/db/queries/folders" import { filesTable, sharesTable, userLimitsTable } from "../src/lib/tables" import { activePrefix, @@ -416,4 +417,499 @@ describe("文件上传、流式下载、改期与删除(规格 §5、§10)", .first() expect(sRow).toBeNull() }) + + describe("PATCH /api/files/:id 改名与移动(扩展 name / folderId)", () => { + it("改名成功:文件列表与下载文件名同步为新名、已有分享链接照常且下载为新名、R2 对象与文件内容不变", async () => { + const { env, db, r2 } = await initializedContext() + const prefix = activePrefix(env) + const user = await seedSession(db, prefix, { role: "user" }) + + const content = "content-for-rename-test" + const up = await directUpload(env, user.cookie, { + filename: "old-name.txt", + content + }) + expect(up.status).toBe(200) + const file = (await up.json()) as { id: string; name: string } + const expectedR2Key = `u${user.userId}/${file.id}` + + // 创建一个分享 + const shareRes = await request(env, `/api/files/${file.id}/shares`, { + method: "POST", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ expiresIn: "file" }) + }) + expect(shareRes.status).toBe(201) + const share = (await shareRes.json()) as { url: string } + const shareToken = share.url.split("/s/")[1] + + // 发起 PATCH 改名 + const patchRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "new-name.txt" }) + }) + expect(patchRes.status).toBe(200) + const patched = (await patchRes.json()) as { id: string; name: string } + expect(patched.id).toBe(file.id) + expect(patched.name).toBe("new-name.txt") + + // 1. 文件列表同步为新名 + const folderRes = await request(env, "/api/folders", { + headers: { cookie: user.cookie } + }) + expect(folderRes.status).toBe(200) + const folderData = (await folderRes.json()) as { + files: Array<{ id: string; name: string }> + } + expect(folderData.files.find((f) => f.id === file.id)?.name).toBe( + "new-name.txt" + ) + + // 2. 登录态下载 Content-Disposition 为新名 + const downRes = await request(env, `/api/files/${file.id}/download`, { + headers: { cookie: user.cookie } + }) + expect(downRes.status).toBe(200) + expect(downRes.headers.get("content-disposition")).toContain( + "new-name.txt" + ) + expect(await downRes.text()).toBe(content) + + // 3. 已有分享链接照常可用且下载名为新名 + const shareDownRes = await request(env, `/s/${shareToken}`) + expect(shareDownRes.status).toBe(200) + expect(shareDownRes.headers.get("content-disposition")).toContain( + "new-name.txt" + ) + expect(await shareDownRes.text()).toBe(content) + + // 4. R2 对象与文件内容不变 + const r2Obj = await r2.get(expectedR2Key) + expect(r2Obj).not.toBeNull() + expect(await r2Obj?.text()).toBe(content) + + // 5. 改名为自身当前名:幂等成功,不报错 409 + const selfRenameRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "new-name.txt" }) + }) + expect(selfRenameRes.status).toBe(200) + }) + + it("移动成功:从原文件夹消失、出现在目标文件夹、移到根目录可用、空间用量不变", async () => { + const { env, db } = await initializedContext() + const prefix = activePrefix(env) + const user = await seedSession(db, prefix, { role: "user" }) + + // 创建文件夹 A 与文件夹 B + const folderA = await createFolder(env.DB, prefix, user.userId, { + parentId: null, + name: "FolderA" + }) + const folderB = await createFolder(env.DB, prefix, user.userId, { + parentId: null, + name: "FolderB" + }) + + // 上传文件到根目录 + const up = await directUpload(env, user.cookie, { + filename: "doc.pdf", + content: "pdf-document-content" + }) + expect(up.status).toBe(200) + const file = (await up.json()) as { id: string } + + // 记录初始用量 + const initFolderRes = await request(env, "/api/folders", { + headers: { cookie: user.cookie } + }) + const initUsage = (await initFolderRes.json()) as { + usage: { usedBytes: number } + } + expect(initUsage.usage.usedBytes).toBe("pdf-document-content".length) + + // 移动到文件夹 A + const moveARes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: folderA.id }) + }) + expect(moveARes.status).toBe(200) + const movedA = (await moveARes.json()) as { + id: string + folderId: string | null + } + expect(movedA.folderId).toBe(folderA.id) + + // 验证:根目录没有该文件 + const rootCheck = await request(env, "/api/folders", { + headers: { cookie: user.cookie } + }) + const rootData = (await rootCheck.json()) as { + files: Array<{ id: string }> + usage: { usedBytes: number } + } + expect(rootData.files.find((f) => f.id === file.id)).toBeUndefined() + // 空间用量保持不变 + expect(rootData.usage.usedBytes).toBe(initUsage.usage.usedBytes) + + // 验证:文件夹 A 中出现该文件 + const folderACheck = await request( + env, + `/api/folders?parentId=${folderA.id}`, + { + headers: { cookie: user.cookie } + } + ) + const folderAData = (await folderACheck.json()) as { + files: Array<{ id: string }> + } + expect(folderAData.files.find((f) => f.id === file.id)).toBeDefined() + + // 从文件夹 A 移动到文件夹 B + const moveBRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: folderB.id }) + }) + expect(moveBRes.status).toBe(200) + + // 验证:文件夹 A 中消失,文件夹 B 中出现 + const folderACheck2 = await request( + env, + `/api/folders?parentId=${folderA.id}`, + { + headers: { cookie: user.cookie } + } + ) + expect( + ((await folderACheck2.json()) as any).files.find( + (f: any) => f.id === file.id + ) + ).toBeUndefined() + + const folderBCheck = await request( + env, + `/api/folders?parentId=${folderB.id}`, + { + headers: { cookie: user.cookie } + } + ) + expect( + ((await folderBCheck.json()) as any).files.find( + (f: any) => f.id === file.id + ) + ).toBeDefined() + + // 移回根目录 (folderId: null) + const moveRootRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: null }) + }) + expect(moveRootRes.status).toBe(200) + expect(((await moveRootRes.json()) as any).folderId).toBeNull() + + const rootFinalCheck = await request(env, "/api/folders", { + headers: { cookie: user.cookie } + }) + const rootFinalData = (await rootFinalCheck.json()) as { + files: Array<{ id: string }> + usage: { usedBytes: number } + } + expect(rootFinalData.files.find((f) => f.id === file.id)).toBeDefined() + expect(rootFinalData.usage.usedBytes).toBe(initUsage.usage.usedBytes) + }) + + it("同名冲突(409 FILE_NAME_CONFLICT)且原文件不变", async () => { + const { env, db } = await initializedContext() + const prefix = activePrefix(env) + const user = await seedSession(db, prefix, { role: "user" }) + + const folder = await createFolder(env.DB, prefix, user.userId, { + parentId: null, + name: "TargetDir" + }) + + // 在根目录下上传 file1.txt 和 file2.txt + const up1 = await directUpload(env, user.cookie, { + filename: "file1.txt", + content: "1" + }) + const f1 = (await up1.json()) as { id: string } + + await directUpload(env, user.cookie, { + filename: "file2.txt", + content: "2" + }) + + // 1. 同目录改名重名(不区分大小写 FILE2.TXT) + const conflictRename = await request(env, `/api/files/${f1.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "FILE2.TXT" }) + }) + expect(conflictRename.status).toBe(409) + expect((await conflictRename.json()) as any).toMatchObject({ + code: "FILE_NAME_CONFLICT" + }) + + // 验证 f1 名字未改变 + const checkF1 = await request(env, "/api/folders", { + headers: { cookie: user.cookie } + }) + expect( + ((await checkF1.json()) as any).files.find((f: any) => f.id === f1.id) + ?.name + ).toBe("file1.txt") + + // 在 TargetDir 下也上传一个 file1.txt + await directUpload(env, user.cookie, { + filename: "file1.txt", + folderId: folder.id, + content: "target-1" + }) + + // 2. 移动到 TargetDir,同名冲突 + const conflictMove = await request(env, `/api/files/${f1.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: folder.id }) + }) + expect(conflictMove.status).toBe(409) + expect((await conflictMove.json()) as any).toMatchObject({ + code: "FILE_NAME_CONFLICT" + }) + + // 验证 f1 仍在根目录 + const checkF1AfterMove = await request(env, "/api/folders", { + headers: { cookie: user.cookie } + }) + expect( + ((await checkF1AfterMove.json()) as any).files.find( + (f: any) => f.id === f1.id + ) + ).toBeDefined() + + // 3. 同时改名 + 移动:只校验最终落点 + // TargetDir 下已有 file1.txt,但没有 file-renamed.txt + const moveAndRenameOk = await request(env, `/api/files/${f1.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ + name: "file-renamed.txt", + folderId: folder.id + }) + }) + expect(moveAndRenameOk.status).toBe(200) + const movedResult = (await moveAndRenameOk.json()) as any + expect(movedResult.name).toBe("file-renamed.txt") + expect(movedResult.folderId).toBe(folder.id) + + // 若同时改名 + 移动到 TargetDir,但新名在 TargetDir 已存在(如 file1.txt) + // 此时 f1 在 TargetDir 下名为 file-renamed.txt,尝试改名为 file1.txt + const moveAndRenameConflict = await request(env, `/api/files/${f1.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ + name: "file1.txt", + folderId: folder.id + }) + }) + expect(moveAndRenameConflict.status).toBe(409) + expect((await moveAndRenameConflict.json()) as any).toMatchObject({ + code: "FILE_NAME_CONFLICT" + }) + }) + + it("参数校验与归属隔离:空请求体/空名/超长/含斜杠/他人文件夹/他人文件被拒", async () => { + const { env, db } = await initializedContext() + const prefix = activePrefix(env) + const user1 = await seedSession(db, prefix, { + role: "user", + email: "u1-check@example.test" + }) + const user2 = await seedSession(db, prefix, { + role: "user", + email: "u2-check@example.test" + }) + + const up = await directUpload(env, user1.cookie, { + filename: "valid.txt", + content: "hello" + }) + const file = (await up.json()) as { id: string } + + // 1. 无任何字段或空请求体 -> 400 + const emptyRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({}) + }) + expect(emptyRes.status).toBe(400) + expect((await emptyRes.json()) as any).toMatchObject({ + code: "INVALID_REQUEST" + }) + + // 2. 空文件名 -> 400 + const emptyNameRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "" }) + }) + expect(emptyNameRes.status).toBe(400) + expect((await emptyNameRes.json()) as any).toMatchObject({ + code: "INVALID_FILENAME" + }) + + // 3. 纯空格文件名 -> 400 + const spaceNameRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: " " }) + }) + expect(spaceNameRes.status).toBe(400) + expect((await spaceNameRes.json()) as any).toMatchObject({ + code: "INVALID_FILENAME" + }) + + // 4. 超长文件名 (>255 字符) -> 400 + const longName = "a".repeat(256) + const longNameRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: longName }) + }) + expect(longNameRes.status).toBe(400) + expect((await longNameRes.json()) as any).toMatchObject({ + code: "INVALID_FILENAME" + }) + + // 5. 含正斜杠或反斜杠 -> 400 + const slashRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "sub/test.txt" }) + }) + expect(slashRes.status).toBe(400) + expect((await slashRes.json()) as any).toMatchObject({ + code: "INVALID_FILENAME" + }) + + const backslashRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "sub\\test.txt" }) + }) + expect(backslashRes.status).toBe(400) + expect((await backslashRes.json()) as any).toMatchObject({ + code: "INVALID_FILENAME" + }) + + // 6. . 与 .. -> 400 + const dotRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "." }) + }) + expect(dotRes.status).toBe(400) + expect((await dotRes.json()) as any).toMatchObject({ + code: "INVALID_FILENAME" + }) + + // 7. 移动到不存在的文件夹 -> 404 FOLDER_NOT_FOUND + const nonExistFolderRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: "non-existent-uuid" }) + }) + expect(nonExistFolderRes.status).toBe(404) + expect((await nonExistFolderRes.json()) as any).toMatchObject({ + code: "FOLDER_NOT_FOUND" + }) + + // 8. 移动到其他用户的文件夹 -> 404 FOLDER_NOT_FOUND + const user2Folder = await createFolder(env.DB, prefix, user2.userId, { + parentId: null, + name: "User2Dir" + }) + const otherFolderRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user1.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: user2Folder.id }) + }) + expect(otherFolderRes.status).toBe(404) + expect((await otherFolderRes.json()) as any).toMatchObject({ + code: "FOLDER_NOT_FOUND" + }) + + // 9. 操作其他用户的文件 -> 404 FILE_NOT_FOUND + const otherFileRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user2.cookie, "content-type": "application/json" }, + body: JSON.stringify({ name: "hacked.txt" }) + }) + expect(otherFileRes.status).toBe(404) + expect((await otherFileRes.json()) as any).toMatchObject({ + code: "FILE_NOT_FOUND" + }) + }) + + it("组合修改:一次请求同时改名 + 移动 + 改有效期,且超出新有效期的分享被同步截断", async () => { + const { env, db } = await initializedContext() + const prefix = activePrefix(env) + const user = await seedSession(db, prefix, { role: "user" }) + + const targetFolder = await createFolder(env.DB, prefix, user.userId, { + parentId: null, + name: "ComboTarget" + }) + + const up = await directUpload(env, user.cookie, { + filename: "initial.txt", + expiresIn: "30d", + content: "combo-test" + }) + const file = (await up.json()) as { id: string } + + // 建立一个 30d 有效期的分享 + const shareRes = await request(env, `/api/files/${file.id}/shares`, { + method: "POST", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ expiresIn: "file" }) + }) + expect(shareRes.status).toBe(201) + const share = (await shareRes.json()) as { + id: string + expires_at: string + } + expect(share.expires_at).not.toBeNull() + + // 一次性提交:改名为 combo-done.txt、移动到 ComboTarget、有效期缩短到 1h + const comboRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ + name: "combo-done.txt", + folderId: targetFolder.id, + expiresIn: "1h" + }) + }) + expect(comboRes.status).toBe(200) + const comboData = (await comboRes.json()) as any + expect(comboData.name).toBe("combo-done.txt") + expect(comboData.folderId).toBe(targetFolder.id) + expect(comboData.expiresAt).not.toBeNull() + + // 验证分享记录的到期时间被同步截断至新到期时间 + const updatedShareRow = await env.DB.prepare( + `SELECT expires_at FROM ${sharesTable(prefix)} WHERE id = ?` + ) + .bind(share.id) + .first<{ expires_at: string }>() + expect(updatedShareRow?.expires_at).toBe(comboData.expiresAt) + }) + }) }) From 2457d6875da92bc7c0298c170474ec8dded5e388 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:21:07 +0800 Subject: [PATCH 2/2] fix(files): treat empty folderId as root to align with upload Empty string or whitespace folderId in PATCH /files/:id is now treated as null (root directory), consistent with upload route. Checkpoint: toimCK-PW4mTk6Sv-G6eu --- worker/src/routes/files.ts | 23 ++++++++++++----------- worker/test/files-upload-download.test.ts | 16 +++++++++++++++- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/worker/src/routes/files.ts b/worker/src/routes/files.ts index c281d59..cce107e 100644 --- a/worker/src/routes/files.ts +++ b/worker/src/routes/files.ts @@ -564,18 +564,19 @@ fileRoutes.patch("/:id", async (c) => { } else if (typeof body.folderId === "string") { const trimmedFolderId = body.folderId.trim() if (!trimmedFolderId) { - return apiError(c, 404, "FOLDER_NOT_FOUND", "Folder not found") - } - const folder = await findFolderById( - c.env.DB, - prefix, - userId, - trimmedFolderId - ) - if (!folder) { - return apiError(c, 404, "FOLDER_NOT_FOUND", "Folder not found") + targetFolderId = null + } else { + const folder = await findFolderById( + c.env.DB, + prefix, + userId, + trimmedFolderId + ) + if (!folder) { + return apiError(c, 404, "FOLDER_NOT_FOUND", "Folder not found") + } + targetFolderId = trimmedFolderId } - targetFolderId = trimmedFolderId } else { return apiError( c, diff --git a/worker/test/files-upload-download.test.ts b/worker/test/files-upload-download.test.ts index 281cdb6..47e62bb 100644 --- a/worker/test/files-upload-download.test.ts +++ b/worker/test/files-upload-download.test.ts @@ -603,7 +603,7 @@ describe("文件上传、流式下载、改期与删除(规格 §5、§10)", ) ).toBeDefined() - // 移回根目录 (folderId: null) + // 移回根目录 (folderId: null 或空字符串/纯空白对齐上传口径) const moveRootRes = await request(env, `/api/files/${file.id}`, { method: "PATCH", headers: { cookie: user.cookie, "content-type": "application/json" }, @@ -612,6 +612,20 @@ describe("文件上传、流式下载、改期与删除(规格 §5、§10)", expect(moveRootRes.status).toBe(200) expect(((await moveRootRes.json()) as any).folderId).toBeNull() + // 再移入 folderA 后通过 folderId: "" 移回根目录验证空串对齐口径 + await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: folderA.id }) + }) + const moveEmptyStrRes = await request(env, `/api/files/${file.id}`, { + method: "PATCH", + headers: { cookie: user.cookie, "content-type": "application/json" }, + body: JSON.stringify({ folderId: " " }) + }) + expect(moveEmptyStrRes.status).toBe(200) + expect(((await moveEmptyStrRes.json()) as any).folderId).toBeNull() + const rootFinalCheck = await request(env, "/api/folders", { headers: { cookie: user.cookie } })