Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): reuse file IDs across messages and servers (#918)
Gustavo Ye2dfb3b196065
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 732c0221d..49c2f3946 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -1460,7 +1460,7 @@ describe("message mark", () => {});describe("message attachment upload", () => {- it("skips a separate thumbnail when the original satisfies both limits", async () => {+ it.each([undefined, "/demo#0042/general"])("uploads with optional legacy target %s and no unnecessary thumbnail", async (target) => {const fs = await import("node:fs")const os = await import("node:os")const path = await import("node:path")@@ -1479,12 +1479,13 @@ describe("message attachment upload", () => {}))setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))try {- await main(["message", "attachment", "upload", "--target", "/demo#0042/general", "--file", file])+ await main(["message", "attachment", "upload", ...(target !== undefined ? ["--target", target] : []), "--file", file])} finally {fs.rmSync(dir, { recursive: true, force: true })}const request = uploadSpy.mock.calls[0]![0]expect(request).toMatchObject({ width: 640, height: 480 })+ expect(request.target).toBe(target)expect(request.thumbnail).toBeUndefined()expect(parseEnvelope(cap.lines())).toMatchObject({ success: { hasThumbnail: false } })})diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex f94cc04e5..58763bd07 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -476,9 +476,8 @@ async function cmdMessageMarkList(opts: Record<string, unknown>): Promise<unknowasync function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unknown> {const api = getApi();const agent = agentId(opts);- const target = opts.target as string;+ const target = opts.target as string | undefined;const filePath = opts.file as string;- if (!target) throw new CliError("message attachment upload: --target <ref> is required");if (!filePath) throw new CliError("message attachment upload: --file <path> is required");const fs = await import("fs/promises");@@ -521,7 +520,7 @@ async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unknoconst result = await api.attachmentUpload({agentId: agent,- target,+ ...(target !== undefined ? { target } : {}),file: { data: new Uint8Array(bytes), filename, contentType },...(thumbnail ? { thumbnail } : {}),...(width !== undefined ? { width } : {}),@@ -894,8 +893,8 @@ function buildProgram(stdin: CliInputStream): Command {attachment.command("upload")- .description("upload a local file as a pending attachment for a future send")- .option("--target <ref>", "destination (channel, DM, or thread ref)")+ .description("upload a local file and get its reusable attachment id")+ .option("--target <ref>", "optional legacy target (channel, DM, or thread ref)").option("--file <path>", "local file to upload").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsindex 38c994f4e..d5bbad025 100644--- a/src/daemon/src/cli/proxyServerApi.test.ts+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -620,7 +620,7 @@ describe("createProxyServerApi — callUpload via parseJsonResponse", () => {).rejects.toThrow(/upstream returned 500 with non-JSON body during attachmentUpload/);});- it("POSTs the canonical attachments door with the ref on ?target= (retargeted, `resolve` placeholder id)", async () => {+ it.each([undefined, "/demo#1234/general"])("keeps the upload API path with optional legacy target %s", async (target) => {const seen: Array<{ url: string; init?: RequestInit }> = [];const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {seen.push({ url, init });@@ -629,13 +629,13 @@ describe("createProxyServerApi — callUpload via parseJsonResponse", () => {const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });const out = await api.attachmentUpload({agentId: "a1",- target: "/demo#1234/general",+ ...(target !== undefined ? { target } : {}),file: { data: new Uint8Array([1, 2, 3]), filename: "x.png", contentType: "image/png" },} as never);expect(out).toEqual({ id: "att_1", filename: "x.png", contentType: "image/png", size: 3 });const u = new URL(seen[0].url);expect(u.pathname).toBe("/api/community/channels/resolve/attachments");- expect(u.searchParams.get("target")).toBe("/demo#1234/general");+ expect(u.searchParams.get("target")).toBe(target ?? null);expect(seen[0].init?.method).toBe("POST");});diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex cbc646d02..6b87cc67e 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -182,12 +182,9 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {}if (req.width !== undefined) form.append("width", String(req.width));if (req.height !== undefined) form.append("height", String(req.height));- // Canonical attachments door: POST channels/{id}/attachments. The bot holds- // a REF (not an id), so it uses the `resolve` placeholder id and carries the- // ref on `?target=` (kept — Gener #68); the door's bot arm resolves it- // member-scoped → 404 (①-C). Same multipart BODY + `?target=` query as the- // old flat `attachmentUpload`; only the PATH changes.- const url = `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/attachments?target=${encodeURIComponent(req.target)}`;+ // Keep the existing API path and optional target query for legacy callers.+ const query = req.target === undefined ? "" : `?target=${encodeURIComponent(req.target)}`;+ const url = `${base}/api/community/channels/${REF_PLACEHOLDER_ID}/attachments${query}`;const res = await fetchImpl(url, {method: "POST",headers: { authorization: `Bearer ${config.voucher}` },diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex b717754a3..33991082e 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -123,12 +123,10 @@ function cliCommandsSection(): string {`2. \`${CLI} message send --target <ref> --remind-after <0|Nm|Nh> --stdin\` — send to a ` +`channel, DM, or thread. ` +`The body is required through \`--stdin\` and limited to 1 KiB of UTF-8. ` +- `Attach uploaded files with \`--attachment <id>\` (repeatable, order matters). ` ++ `Attach files with \`--attachment <id>\` (repeatable, order matters). ` +`\`--remind-after\` accepts \`0\`, or a whole-number duration from \`1m\` to \`24h\`.`,- `3. \`${CLI} message attachment upload --target <ref> --file <path>\` — upload a file; ` +- `returns an id stable across pending→persisted.`,- `4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download any ` +- `attachment you can see (or your own pending uploads).`,+ `3. \`${CLI} message attachment upload --file <path>\` — upload a local file and get a reusable attachment ID.`,+ `4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download an attachment you can read, including your own unsent uploads.`,`5. \`${CLI} message property set --target <full-message-ref> --json <json>\` — add a supported property value to a message.`,`6. \`${CLI} message property list --target <full-message-ref>\` — list the message's current properties and supported capabilities.`,`7. \`${CLI} message property remove --target <full-message-ref> --json <json>\` — remove a supported property value from a message.`,@@ -211,8 +209,11 @@ function messagingSection(): string {"",`- Send body: use \`${CLI} message send --target <ref> --remind-after T --stdin\` with the ` +"quoted-heredoc form under *Message formatting*.",- `- Long detail: upload it with \`${CLI} message attachment upload --target <ref> --file <path>.md\`; ` ++ `- Long detail: upload it with \`${CLI} message attachment upload --file <path>.md\`; ` +"add the returned id as `--attachment <id>` on the short stdin send.",+ "- Reuse files: to forward an attachment or send the same file again, pass its existing ID with `--attachment <id>`. " ++ "Do not download and upload it again. Reuse works across channels, DMs, and threads while you can still read the file. " ++ "Upload only a new or changed file.",`- Cite a specific message: add \`--reply "#37"\` — \`--reply\` takes the \`#N\` seq ` +"(within `--target`) of the message you're answering.","",diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex c5ba68e90..15838f24a 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -364,14 +364,10 @@ export interface SendRequest {nonce?: string;}-/**- * Upload a local file as a pending attachment for a future `send`. The returned- * id is the same one that surfaces on the sent message (id continuity across- * pending → persisted lifecycle).- */+/** Upload a local file and return a reusable ID; target is optional for legacy callers. */export interface AttachmentUploadRequest {agentId: AgentId;- target: ChannelRef;+ target?: ChannelRef;file: FileHandle;thumbnail?: FileHandle;width?: number;diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 787758d4f..b10de20e1 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -402,22 +402,11 @@ export const communityReaction = sqliteTable(]);-// 14. community_attachment-//-// `messageId` is nullable — pending rows created by the agent-// `attachment upload` command exist before the send that links them. The-// human and bot uploads both create pending rows first; send reserves them by-// id and sets `messageId`. `position` is stamped 0-indexed at link time in the-// caller-specified order; NULL on pending rows.export const communityAttachment = sqliteTable("community_attachment",{id: text("id").primaryKey().$defaultFn(() => nanoid()),- messageId: text("message_id").references(() => communityMessage.id, {- onDelete: "cascade",- }),uploaderId: text("uploader_id").notNull(),- targetId: text("target_id").notNull(),r2Key: text("r2_key").notNull(),thumbnailR2Key: text("thumbnail_r2_key"),filename: text("filename").notNull(),@@ -425,17 +414,26 @@ export const communityAttachment = sqliteTable(size: integer("size"),width: integer("width"),height: integer("height"),- position: integer("position"),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),},(t) => [- // (message_id, position) matches ORDER BY position on the read path.- // Drizzle can't express a partial index for the pending lookup here, so- // migration 0071 also creates- // idx_attachment_pending_uploader (uploader_id, target_id)- // WHERE message_id IS NULL- // which the send-time validation query uses.- index("idx_attachment_message").on(t.messageId, t.position),+ index("idx_attachment_uploader").on(t.uploaderId),+ index("idx_attachment_r2_key").on(t.r2Key),+ index("idx_attachment_thumbnail_r2_key").on(t.thumbnailR2Key),+ ]+);++export const communityMessageAttachment = sqliteTable(+ "community_message_attachment",+ {+ messageId: text("message_id").notNull().references(() => communityMessage.id, { onDelete: "cascade" }),+ attachmentId: text("attachment_id").notNull().references(() => communityAttachment.id, { onDelete: "restrict" }),+ position: integer("position").notNull(),+ },+ (t) => [+ primaryKey({ columns: [t.messageId, t.attachmentId] }),+ unique("uq_message_attachment_position").on(t.messageId, t.position),+ index("idx_message_attachment_file").on(t.attachmentId, t.messageId),]);diff --git a/src/shared/src/db/queries/account-deletion.test.ts b/src/shared/src/db/queries/account-deletion.test.tsindex e2ae3de23..f47501791 100644--- a/src/shared/src/db/queries/account-deletion.test.ts+++ b/src/shared/src/db/queries/account-deletion.test.ts@@ -269,12 +269,10 @@ describe("account deletion snapshot and delete queries", () => {)run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'reply', ?, ?, 1)", reply, reader, now, thread)run(- "INSERT INTO community_attachment (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, position, created_at) VALUES ('thread_attachment', ?, ?, ?, 'community/thread/raw', 'community/thread/thumb', 'reply.txt', 0, ?), ('owner_attachment', ?, ?, ?, 'community/owner/raw', NULL, 'owner.txt', 0, ?), ('pending_server_attachment', NULL, ?, ?, 'community/pending-server/raw', NULL, 'pending-server.txt', 0, ?), ('pending_thread_attachment', NULL, ?, ?, 'community/pending-thread/raw', 'community/pending-thread/thumb', 'pending-thread.txt', 0, ?)",- reply, reader, thread, now,- authoredMessage, owner, dm, now,- reader, serverChannel, now,- reader, thread, now,+ "INSERT INTO community_attachment (id, uploader_id, r2_key, thumbnail_r2_key, filename, created_at) VALUES ('thread_attachment', ?, 'community/thread/raw', 'community/thread/thumb', 'reply.txt', ?), ('owner_attachment', ?, 'community/owner/raw', NULL, 'owner.txt', ?), ('pending_server_attachment', ?, 'community/pending-server/raw', NULL, 'pending-server.txt', ?), ('pending_thread_attachment', ?, 'community/pending-thread/raw', 'community/pending-thread/thumb', 'pending-thread.txt', ?), ('owner_draft', ?, 'community/draft/raw', NULL, 'draft.txt', ?)",+ reader, now, owner, now, reader, now, reader, now, owner, now,)+ run("INSERT INTO community_message_attachment VALUES (?, 'thread_attachment', 0), (?, 'owner_attachment', 0), (?, 'owner_attachment', 0)", reply, authoredMessage, priorMessage)const createdAtMs = Date.parse(now)run("INSERT INTO community_diagnostic_report (id, owner_user_id, agent_id, machine_id, client_nonce, rate_bucket, status, from_ms, created_at, deadline_at) VALUES ('dbr_owned', ?, ?, 'community_machine_1', 'nonce_123456789012', ?, 'pending', ?, ?, ?)",@@ -302,12 +300,6 @@ describe("account deletion snapshot and delete queries", () => {expect(snapshot!.media.communityExactKeys).toEqual(expect.arrayContaining([`user-avatar/${owner}`,`bot-avatar/${bot}`,- "community/thread/raw",- "community/thread/thumb",- "community/owner/raw",- "community/pending-server/raw",- "community/pending-thread/raw",- "community/pending-thread/thumb",]))expect(snapshot!.media.emailExactKeys).toEqual(expect.arrayContaining(["artifacts/raw",@@ -334,10 +326,13 @@ describe("account deletion snapshot and delete queries", () => {expect(sqlite.prepare("SELECT id FROM workspace WHERE id = ?").get(ownedWorkspace)).toBeUndefined()expect(sqlite.prepare("SELECT id FROM workspace WHERE id = ?").get(sharedWorkspace)).toEqual({ id: sharedWorkspace })expect(sqlite.prepare("SELECT runtime_id FROM agent WHERE id = ?").get(survivingAgent)).toEqual({ runtime_id: null })- expect(sqlite.prepare("SELECT id FROM community_attachment WHERE id IN (?, ?)").get(- "pending_server_attachment",- "pending_thread_attachment",- )).toBeUndefined()+ expect(sqlite.prepare("SELECT id FROM community_attachment ORDER BY id").all()).toEqual([+ { id: "owner_attachment" }, { id: "pending_server_attachment" }, { id: "pending_thread_attachment" },+ ])+ expect(sqlite.prepare("SELECT message_id,attachment_id FROM community_message_attachment").all()).toEqual([+ { message_id: priorMessage, attachment_id: "owner_attachment" },+ ])+ expect(snapshot!.media.communityExactKeys.some(key => key.startsWith("community/"))).toBe(false)expect(sqlite.prepare("SELECT id FROM user WHERE id = ?").get(reader)).toEqual({ id: reader })expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_push_device WHERE user_id = ?",diff --git a/src/shared/src/db/queries/account-deletion.ts b/src/shared/src/db/queries/account-deletion.tsindex c7d0ae1df..7bb2a7993 100644--- a/src/shared/src/db/queries/account-deletion.ts+++ b/src/shared/src/db/queries/account-deletion.ts@@ -1,4 +1,4 @@-import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"+import { and, eq, inArray, isNull, notExists, or, sql } from "drizzle-orm"import { sqliteTable, text } from "drizzle-orm/sqlite-core"import {account,@@ -19,6 +19,7 @@ import {} from "../schema"import {communityAttachment,+ communityMessageAttachment,communityChannel,communityFriendship,communityMention,@@ -229,10 +230,8 @@ export async function getAccountDeletionSnapshot(botBindings,serverRows,serverMemberRows,- channelRows,impactedReadStateRows,impactedMentionRows,- attachmentRows,artifactRows,deletingEmailRows,meetingRows,@@ -279,9 +278,6 @@ export async function getAccountDeletionSnapshot(db.select({ serverId: communityServerMember.serverId, userId: communityServerMember.userId }).from(communityServerMember).where(inArray(communityServerMember.serverId, ownedServerIdsQuery)),- db.select({ id: communityChannel.id, type: communityChannel.type })- .from(communityChannel)- .where(inArray(communityChannel.id, doomedChannelIdsQuery)),db.selectDistinct({ userId: communityReadState.userId }).from(communityReadState).innerJoin(user, eq(user.id, communityReadState.userId))@@ -302,14 +298,6 @@ export async function getAccountDeletionSnapshot(isNull(user.deletedAt),inArray(communityMention.messageId, doomedMessageIdsQuery),)),- db.select({- r2Key: communityAttachment.r2Key,- thumbnailR2Key: communityAttachment.thumbnailR2Key,- }).from(communityAttachment).where(or(- inArray(communityAttachment.uploaderId, identitiesQuery),- inArray(communityAttachment.targetId, doomedChannelIdsQuery),- inArray(communityAttachment.messageId, doomedMessageIdsQuery),- )),db.select({ r2Key: artifact.r2Key, thumbnailR2Key: artifact.thumbnailR2Key }).from(artifact).where(affectedArtifactCondition),@@ -382,12 +370,10 @@ export async function getAccountDeletionSnapshot(...identities.map((row) => `${row.isBot ? "bot" : "user"}-avatar/${row.id}`),...identities.map((row) => row.avatarObjectKey),...serverRows.map((row) => row.icon),- ...attachmentRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key]),]),communityPrefixes: unique([...identities.map((row) => `${row.isBot ? "bot" : "user"}-avatar/${row.id}/`),...serverRows.map((row) => `server-icon/${row.id}/`),- ...channelRows.map((row) => `${row.type === "dm" ? "dm" : row.type === "thread" ? "thread" : "channel"}/${row.id}/`),]),emailExactKeys: unique([...artifactRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key]),@@ -434,13 +420,6 @@ export async function deleteAccountRows(.select({ id: communityMessage.id }).from(communityMessage).where(inArray(communityMessage.authorId, identitiesQuery))- const doomedChannelIdsQuery = db- .select({ id: communityChannel.id })- .from(communityChannel)- .where(or(- inArray(communityChannel.serverId, ownedServerIdsQuery),- inArray(communityChannel.parentMessageId, authoredMessagesQuery),- ))const affectedChannelIdsQuery = db.select({ id: communityMessage.channelId }).from(communityMessage)@@ -531,12 +510,13 @@ export async function deleteAccountRows(db.delete(machine).where(inArray(machine.ownerId, identitiesQuery)),db.delete(workspace).where(inArray(workspace.id, ownedWorkspaceIdsQuery)),db.delete(agent).where(inArray(agent.ownerId, identitiesQuery)),+ db.delete(communityServer).where(inArray(communityServer.ownerId, identitiesQuery)),db.delete(communityAttachment).where(and(- isNull(communityAttachment.messageId),- inArray(communityAttachment.targetId, doomedChannelIdsQuery),+ inArray(communityAttachment.uploaderId, identitiesQuery),+ notExists(db.select({ id: communityMessageAttachment.messageId })+ .from(communityMessageAttachment)+ .where(eq(communityMessageAttachment.attachmentId, communityAttachment.id))),)),- db.delete(communityServer).where(inArray(communityServer.ownerId, identitiesQuery)),- db.delete(communityAttachment).where(inArray(communityAttachment.uploaderId, identitiesQuery)),db.delete(communityDiagnosticReport).where(inArray(communityDiagnosticReport.ownerUserId, identitiesQuery)),db.delete(communityFriendship).where(inArray(communityFriendship.needsOwnerApproval, identitiesQuery)),db.delete(deviceCode).where(inArray(deviceCode.userId, identitiesQuery)),diff --git a/src/shared/src/db/queries/community/attachment.ts b/src/shared/src/db/queries/community/attachment.tsindex c5960c16d..9af62eebe 100644--- a/src/shared/src/db/queries/community/attachment.ts+++ b/src/shared/src/db/queries/community/attachment.ts@@ -1,234 +1,70 @@-import { and, asc, count, eq, inArray, isNull, sql } from "drizzle-orm";+import { and, asc, eq, exists, getTableColumns, inArray, isNull, ne, notExists, or, sql } from "drizzle-orm";import { alias } from "drizzle-orm/sqlite-core";+import { communityAttachment, communityChannel, communityChannelMember, communityFriendship, communityMessage, communityMessageAttachment } from "../../community-schema";import { nanoid } from "nanoid";-import { communityAttachment, communityChannel } from "../../community-schema";+import { user } from "../../schema";import type { Database } from "../../index";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import { channelReadableSql } from "./channel";-/**- * Insert a pending attachment row (`messageId = NULL`) for the agent- * `attachment upload` command. The caller receives the id and later passes- * it to `send`, at which point `reserveAttachmentsForMessage` sets- * `messageId` and `position`.- */-export async function createPendingAttachment(- db: Database,- data: {- id?: string;- uploaderId: string;- targetId: string;- r2Key: string;- thumbnailR2Key?: string | null;- filename: string;- contentType?: string | null;- size?: number | null;- width?: number | null;- height?: number | null;- }-) {- const id = data.id ?? nanoid();- const createdAt = new Date().toISOString();- const candidate = db- .select({- id: sql<string>`${id}`.as("id"),- messageId: sql<string | null>`NULL`.as("message_id"),- uploaderId: sql<string>`${data.uploaderId}`.as("uploader_id"),- targetId: communityChannel.id,- r2Key: sql<string>`${data.r2Key}`.as("r2_key"),- thumbnailR2Key: sql<string | null>`${data.thumbnailR2Key ?? null}`.as("thumbnail_r2_key"),- filename: sql<string>`${data.filename}`.as("filename"),- contentType: sql<string | null>`${data.contentType ?? null}`.as("content_type"),- size: sql<number | null>`${data.size ?? null}`.as("size"),- width: sql<number | null>`${data.width ?? null}`.as("width"),- height: sql<number | null>`${data.height ?? null}`.as("height"),- position: sql<number | null>`NULL`.as("position"),- createdAt: sql<string>`${createdAt}`.as("created_at"),- })- .from(communityChannel)- .where(eq(communityChannel.id, data.targetId))- .limit(1);-- const [row] = await db- .insert(communityAttachment)- .select(candidate)- .returning();- if (!row) throw new Error("attachment target no longer exists");+export async function createAttachment(db: Database, data: typeof communityAttachment.$inferInsert) {+ const [row] = await db.insert(communityAttachment).select(db.select({+ id: sql<string>`${data.id ?? nanoid()}`.as("id"),+ uploaderId: user.id,+ r2Key: sql<string>`${data.r2Key}`.as("r2_key"),+ thumbnailR2Key: sql<string | null>`${data.thumbnailR2Key ?? null}`.as("thumbnail_r2_key"),+ filename: sql<string>`${data.filename}`.as("filename"),+ contentType: sql<string | null>`${data.contentType ?? null}`.as("content_type"),+ size: sql<number | null>`${data.size ?? null}`.as("size"),+ width: sql<number | null>`${data.width ?? null}`.as("width"),+ height: sql<number | null>`${data.height ?? null}`.as("height"),+ createdAt: sql<string>`${data.createdAt ?? new Date().toISOString()}`.as("created_at"),+ }).from(user).where(and(eq(user.id, data.uploaderId), isNull(user.deletedAt)))).returning();+ if (!row) throw new Error("attachment uploader no longer exists");return row;}-/**- * Send-time validation query: return the pending attachment rows that match- * the (uploader, scope) tuple. Callers compare `rows.length === ids.length`- * to detect any mismatch and reject with a generic 400 that never leaks- * which specific id failed (avoids id enumeration).- *- * Actor-agnostic: the guarantee is keyed entirely on the `uploaderId` param, so- * BOTH the human web composer and the bot flow use it (route/disc step 2b- * unified them onto reserve-by-id). A caller passes its own credential user id;- * the `uploaderId` + `messageId IS NULL` filters make it confused-deputy-safe —- * a caller can only reserve pending rows it uploaded, into the target it- * uploaded them for (the send-side dual of the download door's- * authorize-from-row guard). Named "…ForSender" (not "…ForBot") because the- * sender is whichever actor's credential keys the lookup.- */-export async function findPendingAttachmentsForSender(- db: Database,- data: { ids: string[]; uploaderId: string; targetId: string }-) {- if (data.ids.length === 0) return [];- return db- .select()- .from(communityAttachment)- .where(- and(- inArray(communityAttachment.id, data.ids),- isNull(communityAttachment.messageId),- eq(communityAttachment.uploaderId, data.uploaderId),- eq(communityAttachment.targetId, data.targetId)- )- );-}--/**- * Reserve pending attachments for a pre-minted message id and stamp- * `position` in the caller-specified order (`ids[0]` → position 0). Single- * atomic UPDATE — a partial N-1 success on a per-row loop would leave- * inconsistent state no single rowsAffected check could detect. The CAS- * `messageId IS NULL` gate is the race guard: only rows we win the race for- * are updated. Returns the ids that were actually reserved so the caller- * can compare `returning.length === ids.length` to detect a race-loss.- */-export async function reserveAttachmentsForMessage(- db: Database,- data: { ids: string[]; messageId: string }-): Promise<string[]> {- if (data.ids.length === 0) return [];-- // Build `position = CASE id WHEN ids[0] THEN 0 WHEN ids[1] THEN 1 ... END`.- // No ORM equivalent; hand-rolled `sql` template is the only viable path.- const chunks = data.ids.map(- (id, idx) => sql`WHEN ${id} THEN ${idx}`- );- const positionCase = sql.join(- [sql`CASE ${communityAttachment.id}`, ...chunks, sql`END`],- sql` `- );-- const rows = await db- .update(communityAttachment)- .set({ messageId: data.messageId, position: positionCase })- .where(- and(- inArray(communityAttachment.id, data.ids),- isNull(communityAttachment.messageId)- )- )- .returning({ id: communityAttachment.id });- return rows.map((r) => r.id);-}--export async function rebindPendingAttachmentsToChild(- db: Database,- data: { ids: string[]; uploaderId: string; parentTargetId: string; childTargetId: string }-): Promise<boolean> {- if (data.ids.length === 0) return true;- const eligible = alias(communityAttachment, "eligible_attachment");- const eligibleCount = db- .select({ value: count() })- .from(eligible)- .where(and(- inArray(eligible.id, data.ids),- isNull(eligible.messageId),- eq(eligible.uploaderId, data.uploaderId),- inArray(eligible.targetId, [data.parentTargetId, data.childTargetId])- ));- const rebound = await db- .update(communityAttachment)- .set({ targetId: data.childTargetId })- .where(and(- inArray(communityAttachment.id, data.ids),- isNull(communityAttachment.messageId),- eq(communityAttachment.uploaderId, data.uploaderId),- inArray(communityAttachment.targetId, [data.parentTargetId, data.childTargetId]),- sql`(${eligibleCount}) = ${data.ids.length}`- ))- .returning({ id: communityAttachment.id });- return rebound.length === data.ids.length;+export function attachmentReadableSql(db: Database, userId: string) {+ const peer = alias(communityChannelMember, "attachment_dm_peer");+ const hasPeer = db.select({ id: peer.id }).from(peer)+ .where(and(eq(peer.channelId, communityChannel.id), eq(peer.relation, "access"), ne(peer.userId, userId)));+ const blocked = db.select({ id: communityFriendship.id }).from(communityFriendship)+ .innerJoin(peer, and(eq(peer.channelId, communityChannel.id), eq(peer.relation, "access"), ne(peer.userId, userId)))+ .where(and(eq(communityFriendship.status, "blocked"), or(+ and(eq(communityFriendship.requesterId, userId), eq(communityFriendship.addresseeId, peer.userId)),+ and(eq(communityFriendship.addresseeId, userId), eq(communityFriendship.requesterId, peer.userId)),+ )));+ const readableMessage = db.select({ id: communityMessage.id }).from(communityMessageAttachment)+ .innerJoin(communityMessage, eq(communityMessage.id, communityMessageAttachment.messageId))+ .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .where(and(eq(communityMessageAttachment.attachmentId, communityAttachment.id),+ channelReadableSql(userId, { id: communityChannel.id, type: communityChannel.type, serverId: communityChannel.serverId, parentChannelId: communityChannel.parentChannelId }), or(ne(communityChannel.type, "dm"), and(exists(hasPeer), notExists(blocked)))));+ const activeActor = db.select({ id: user.id }).from(user)+ .where(and(eq(user.id, userId), isNull(user.deletedAt)));+ return and(exists(activeActor), or(eq(communityAttachment.uploaderId, userId), exists(readableMessage)))!;}-/**- * Compensating UPDATE for the three send-time rollback sites:- * (a) reservation-mismatch (partial-overlap race),- * (b) `insertMessageRow` thrown exception,- * (c) `expectedSeq` CAS-null branch.- * Scoped by `messageId = ?` so it only ever touches rows this caller reserved- * with the same pre-minted id.- */-export async function unreserveAttachments(- db: Database,- data: { ids: string[]; messageId: string }-) {- if (data.ids.length === 0) return;- await db- .update(communityAttachment)- .set({ messageId: null, position: null })- .where(- and(- inArray(communityAttachment.id, data.ids),- eq(communityAttachment.messageId, data.messageId)- )- );+export async function getReadableAttachmentById(db: Database, id: string, userId: string) {+ const [row] = await db.select().from(communityAttachment)+ .where(and(eq(communityAttachment.id, id), attachmentReadableSql(db, userId))).limit(1);+ return row ?? null;}-/** Row-by-id lookup for the download route. May return a pending row. */-export async function getAttachmentById(db: Database, id: string) {- const rows = await db- .select()- .from(communityAttachment)- .where(eq(communityAttachment.id, id))- .limit(1);- return rows[0] ?? null;+function messageAttachments(db: Database, ids: string[]) {+ return db.select({ ...getTableColumns(communityAttachment), messageId: communityMessageAttachment.messageId,+ position: communityMessageAttachment.position, targetId: communityMessage.channelId })+ .from(communityMessageAttachment)+ .innerJoin(communityAttachment, eq(communityAttachment.id, communityMessageAttachment.attachmentId))+ .innerJoin(communityMessage, eq(communityMessage.id, communityMessageAttachment.messageId))+ .where(inArray(communityMessageAttachment.messageId, ids))+ .orderBy(asc(communityMessageAttachment.position), asc(communityAttachment.createdAt));}-export async function listMessageAttachments(- db: Database,- messageId: string-) {- return db- .select()- .from(communityAttachment)- .where(eq(communityAttachment.messageId, messageId))- .orderBy(asc(communityAttachment.position), asc(communityAttachment.createdAt));+export async function listMessageAttachments(db: Database, messageId: string) {+ return messageAttachments(db, [messageId]);}-export async function listByMessageIds(- db: Database,- messageIds: string[]-) {- if (messageIds.length === 0) return [];- // Live risk: inboxPull passes a page of up to 200 message ids (> 100). Chunk- // the `inArray` for D1's 100-param limit, concat, then re-sort globally by- // (position, createdAt) — both keys are in the projection, so per-chunk order- // alone would be wrong across chunks.- const rows = (- await Promise.all(- chunk(messageIds, D1_MAX_IN_PARAMS).map((ids) =>- db- .select()- .from(communityAttachment)- .where(inArray(communityAttachment.messageId, ids))- .orderBy(asc(communityAttachment.position), asc(communityAttachment.createdAt))- )- )- ).flat();- rows.sort((a, b) =>- a.position !== b.position- ? (a.position ?? 0) - (b.position ?? 0)- : a.createdAt < b.createdAt- ? -1- : a.createdAt > b.createdAt- ? 1- : 0- );- return rows;+export async function listByMessageIds(db: Database, messageIds: string[]) {+ const rows = (await Promise.all(chunk(messageIds, D1_MAX_IN_PARAMS).map((ids) => messageAttachments(db, ids)))).flat();+ return rows.sort((a, b) => a.position - b.position || a.createdAt.localeCompare(b.createdAt));}diff --git a/src/shared/src/db/queries/community/delete-media.ts b/src/shared/src/db/queries/community/delete-media.tsindex 235e6e137..0ae089fd3 100644--- a/src/shared/src/db/queries/community/delete-media.ts+++ b/src/shared/src/db/queries/community/delete-media.ts@@ -1,6 +1,5 @@-import { and, eq, exists, inArray, isNull, or, sql } from "drizzle-orm"+import { and, eq, exists, inArray, or, sql } from "drizzle-orm"import {- communityAttachment,communityChannel,communityMention,communityMessage,@@ -24,13 +23,6 @@ export type DeleteServerWithMediaResult = DeleteCommunityMediaResult & {iconKey: string | null}-function flattenMediaRows(- rows: Array<{ r2Key: string; thumbnailR2Key: string | null }>,-): string[] {- return rows.flatMap((row) => [row.r2Key, row.thumbnailR2Key]- .filter((key): key is string => key !== null && key.length > 0))-}-export async function deleteChannelWithMedia(db: Database,input: { channelId: string; serverId: string },@@ -127,32 +119,6 @@ async function deleteChannelWithMediaAttempt()`const enumeratedUserHasEffect = scopedHumanEffectSql(sql`CAST(value AS TEXT)`)- const mediaSnapshot = db- .select({- r2Key: communityAttachment.r2Key,- thumbnailR2Key: communityAttachment.thumbnailR2Key,- })- .from(communityAttachment)- .where(and(- rootStillExists,- or(- inArray(communityAttachment.messageId, scopedMessageIds),- and(- isNull(communityAttachment.messageId),- inArray(communityAttachment.targetId, scopedChannelIds),- ),- ),- ))-- const removePendingAttachments = db- .delete(communityAttachment)- .where(and(- rootStillExists,- isNull(communityAttachment.messageId),- inArray(communityAttachment.targetId, scopedChannelIds),- impactedHumansStable,- ))-const deleteRoot = db.delete(communityChannel).where(and(@@ -162,11 +128,9 @@ async function deleteChannelWithMediaAttempt()).returning({ id: communityChannel.id })- const revisionIndex = 2- const deleteIndex = impactedUserIds.length > 0 ? 3 : 2+ const revisionIndex = 0+ const deleteIndex = impactedUserIds.length > 0 ? 1 : 0const results = (await db.batch([- mediaSnapshot,- removePendingAttachments,...(impactedUserIds.length > 0? [advanceReadStateRevisionsForUsersBuilder(db,@@ -176,7 +140,6 @@ async function deleteChannelWithMediaAttempt(: []),deleteRoot,] as any)) as unknown[]- const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>const deletedRows = results[deleteIndex] as Array<{ id: string }>const deleted = deletedRows.length > 0const revisions = impactedUserIds.length > 0@@ -194,7 +157,7 @@ async function deleteChannelWithMediaAttempt(return {deleted,- mediaKeys: deleted ? flattenMediaRows(mediaRows) : [],+ mediaKeys: [],readStateRevisions: deleted ? revisions : [],}}@@ -281,32 +244,6 @@ async function deleteServerWithMediaAttempt()`const enumeratedUserHasEffect = scopedHumanEffectSql(sql`CAST(value AS TEXT)`)- const mediaSnapshot = db- .select({- r2Key: communityAttachment.r2Key,- thumbnailR2Key: communityAttachment.thumbnailR2Key,- })- .from(communityAttachment)- .where(and(- ownedServerStillExists,- or(- inArray(communityAttachment.messageId, scopedMessageIds),- and(- isNull(communityAttachment.messageId),- inArray(communityAttachment.targetId, scopedChannelIds),- ),- ),- ))-- const removePendingAttachments = db- .delete(communityAttachment)- .where(and(- ownedServerStillExists,- isNull(communityAttachment.messageId),- inArray(communityAttachment.targetId, scopedChannelIds),- impactedHumansStable,- ))-const deleteServer = db.delete(communityServer).where(and(@@ -316,11 +253,9 @@ async function deleteServerWithMediaAttempt()).returning({ id: communityServer.id, icon: communityServer.icon })- const revisionIndex = 2- const deleteIndex = impactedUserIds.length > 0 ? 3 : 2+ const revisionIndex = 0+ const deleteIndex = impactedUserIds.length > 0 ? 1 : 0const results = (await db.batch([- mediaSnapshot,- removePendingAttachments,...(impactedUserIds.length > 0? [advanceReadStateRevisionsForUsersBuilder(db,@@ -330,7 +265,6 @@ async function deleteServerWithMediaAttempt(: []),deleteServer,] as any)) as unknown[]- const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>const deletedRows = results[deleteIndex] as Array<{ id: string; icon: string | null }>const deleted = deletedRows.length > 0const revisions = impactedUserIds.length > 0@@ -348,7 +282,7 @@ async function deleteServerWithMediaAttempt(return {deleted,- mediaKeys: deleted ? flattenMediaRows(mediaRows) : [],+ mediaKeys: [],iconKey: deleted ? deletedRows[0]!.icon : null,readStateRevisions: deleted ? revisions : [],}diff --git a/src/shared/src/db/queries/community/forum-post-delete.ts b/src/shared/src/db/queries/community/forum-post-delete.tsindex 1a211142b..e4151a300 100644--- a/src/shared/src/db/queries/community/forum-post-delete.ts+++ b/src/shared/src/db/queries/community/forum-post-delete.ts@@ -1,6 +1,5 @@-import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";+import { and, eq, inArray, or, sql } from "drizzle-orm";import {- communityAttachment,communityChannel,communityMention,communityMessage,@@ -204,21 +203,6 @@ async function deleteForumPostAttempt())`;- const mediaSnapshot = db- .select({- r2Key: communityAttachment.r2Key,- thumbnailR2Key: communityAttachment.thumbnailR2Key,- })- .from(communityAttachment)- .where(or(- eq(communityAttachment.messageId, input.openerId),- inArray(communityAttachment.messageId, childMessageIds),- and(- isNull(communityAttachment.messageId),- eq(communityAttachment.targetId, input.childChannelId),- ),- ));-const repairReadStates = db.update(communityReadState).set({@@ -246,15 +230,6 @@ async function deleteForumPostAttempt(rowBelongsToKnownHumanOrBot,));- const removePendingAttachments = db- .delete(communityAttachment)- .where(and(- isNull(communityAttachment.messageId),- eq(communityAttachment.targetId, input.childChannelId),- openerStillExists,- impactedHumansStable,- ));-const updateForum = db.update(communityChannel).set({@@ -285,10 +260,9 @@ async function deleteForumPostAttempt()).returning({ id: communityMessage.id });- const revisionIndex = 1;- const deleteIndex = impactedUserIds.length > 0 ? 6 : 5;+ const revisionIndex = 0;+ const deleteIndex = impactedUserIds.length > 0 ? 4 : 3;const results = (await db.batch([- mediaSnapshot,...(impactedUserIds.length > 0? [advanceReadStateRevisionsForUsersBuilder(db,@@ -298,11 +272,9 @@ async function deleteForumPostAttempt(: []),repairReadStates,removeEmptyReadStates,- removePendingAttachments,updateForum,deleteOpener,] as any)) as unknown[];- const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>;const deletedRows = results[deleteIndex] as Array<{ id: string }>;const revisions = impactedUserIds.length > 0? results[revisionIndex] as Array<{ userId: string; revision: number }>@@ -326,9 +298,7 @@ async function deleteForumPostAttempt(return {deleted,- mediaKeys: deleted- ? mediaRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key].filter((key): key is string => !!key))- : [],+ mediaKeys: [],readStateRevisions: deleted ? revisions : [],};}diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 82a208caf..635fdec54 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -1,4 +1,4 @@-import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, isNull, count, min, type SQL, type GetColumnData } from "drizzle-orm";+import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, count, min, type SQL, type GetColumnData } from "drizzle-orm";import {communityMessage,communityChannel,@@ -9,10 +9,12 @@ import {communityMention,communityMessageTag,communityAttachment,+ communityMessageAttachment,} from "../../community-schema";import { user } from "../../schema";import { nanoid } from "nanoid";import type { Database } from "../../index";+import { attachmentReadableSql } from "./attachment";import { MAX_ATTACHMENTS_PER_MESSAGE } from "../../../constants/community";import { createLogger } from "../../../logger";import { chunk, D1_MAX_IN_PARAMS, maxRowsPerInsert } from "../_chunk";@@ -151,7 +153,6 @@ export type CreateMessageData = {id: string;serverId: string;name: string;- pendingAttachmentIds: string[];};};@@ -216,19 +217,16 @@ async function insertMessageRow(db: Database, data: CreateMessageData, expectedS.returning({ nextSeq: communityMessageSeq.nextSeq });const attachmentIds = data.attachmentIds ?? [];- const pendingThreadIds = data.forumThread?.pendingAttachmentIds ?? [];- if (attachmentIds.length > MAX_ATTACHMENTS_PER_MESSAGE || pendingThreadIds.length > MAX_ATTACHMENTS_PER_MESSAGE) {+ if (attachmentIds.length > MAX_ATTACHMENTS_PER_MESSAGE) {throw new Error("too many message attachments");}const eligibleAttachments = (ids: string[]) => db.select({ value: count() }).from(communityAttachment).where(and(inArray(communityAttachment.id, ids),- isNull(communityAttachment.messageId),- eq(communityAttachment.uploaderId, data.authorId),- eq(communityAttachment.targetId, data.channelId),+ attachmentReadableSql(db, data.authorId),));- const attachmentChecks = [attachmentIds, pendingThreadIds]+ const attachmentChecks = [attachmentIds].filter((ids) => ids.length > 0).map((ids) => sql`(${eligibleAttachments(ids)}) = ${ids.length}`);const checkedContent = attachmentChecks.length === 0 ? data.content@@ -276,10 +274,7 @@ async function insertMessageRow(db: Database, data: CreateMessageData, expectedSsetWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,});const attachmentStatements = attachmentIds.length === 0 ? [] : [- db.update(communityAttachment).set({- messageId,- position: sql`CASE ${communityAttachment.id} ${sql.join(attachmentIds.map((id, index) => sql`WHEN ${id} THEN ${index}`), sql` `)} END`,- }).where(and(inArray(communityAttachment.id, attachmentIds), isNull(communityAttachment.messageId))),+ db.insert(communityMessageAttachment).values(attachmentIds.map((attachmentId, position) => ({ messageId, attachmentId, position }))),];const threadStatements = data.forumThread ? [db.insert(communityChannel).values({@@ -299,10 +294,6 @@ async function insertMessageRow(db: Database, data: CreateMessageData, expectedSrelation: "notify",source: "spoke",}),- ...(pendingThreadIds.length === 0 ? [] : [- db.update(communityAttachment).set({ targetId: data.forumThread.id })- .where(and(inArray(communityAttachment.id, pendingThreadIds), isNull(communityAttachment.messageId))),- ]),] : [];const mentionStatements = chunk(data.mentions ?? [], maxRowsPerInsert(5)).map((mentions) =>db.insert(communityMention).values(mentions.map((mention) => ({ messageId, ...mention })))diff --git a/src/shared/src/db/queries/community/notification-target.ts b/src/shared/src/db/queries/community/notification-target.tsindex 4ff0006bf..c1fb5035b 100644--- a/src/shared/src/db/queries/community/notification-target.ts+++ b/src/shared/src/db/queries/community/notification-target.ts@@ -1,6 +1,7 @@import { aliasedTable, asc, eq } from "drizzle-orm";import {communityAttachment,+ communityMessageAttachment,communityChannel,communityMessage,communityServer,@@ -62,9 +63,10 @@ export async function getPushNotificationTarget(const attachments = await db.select({ contentType: communityAttachment.contentType }).from(communityAttachment)- .where(eq(communityAttachment.messageId, messageId))+ .innerJoin(communityMessageAttachment, eq(communityMessageAttachment.attachmentId, communityAttachment.id))+ .where(eq(communityMessageAttachment.messageId, messageId)).orderBy(- asc(communityAttachment.position),+ asc(communityMessageAttachment.position),asc(communityAttachment.createdAt),);diff --git a/src/shared/test/community-write-atomic.test.ts b/src/shared/test/community-write-atomic.test.tsindex bd3630050..ba4e4a7ec 100644--- a/src/shared/test/community-write-atomic.test.ts+++ b/src/shared/test/community-write-atomic.test.ts@@ -40,15 +40,13 @@ describe("Community durable writes — real SQLite transactions", () => {it("bounds attachment input and keeps maximum-size statements below D1's bind limit", async () => {const ids = Array.from({ length: 10 }, (_, i) => `attachment-${i}`);- const pending = Array.from({ length: 10 }, (_, i) => `pending-${i}`);- for (const id of [...ids, ...pending]) fixture.sqlite.prepare("INSERT INTO community_attachment (id, uploader_id, target_id) VALUES (?, 'author', 'channel')").run(id);- const forumThread = { id: "post", serverId: "server", name: "post", pendingAttachmentIds: pending };+ for (const id of ids) fixture.sqlite.prepare("INSERT INTO community_attachment (id, uploader_id, r2_key, filename, created_at) VALUES (?, 'author', 'original', 'file', 'now')").run(id);+ const forumThread = { id: "post", serverId: "server", name: "post" };await expect(send({ attachmentIds: [...ids, "extra"] })).rejects.toThrow("too many message attachments");- await expect(send({ forumThread: { ...forumThread, pendingAttachmentIds: [...pending, "extra"] } })).rejects.toThrow("too many message attachments");expect(rows("community_message")).toEqual([]);await send({ attachmentIds: ids, forumThread });expect(Math.max(...fixture.batchSizes.flat())).toBeLessThanOrEqual(100);- expect(rows("community_attachment").filter((row: any) => row.message_id)).toHaveLength(10);+ expect(rows("community_message_attachment")).toHaveLength(10);});it("rejects stale seq in a deletion hole without any writes", async () => {@@ -94,12 +92,12 @@ describe("Community durable writes — real SQLite transactions", () => {});it("commits attachments, mentions, participants and activity together; nonce collision rolls back", async () => {- fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0)");+ fixture.sqlite.exec("INSERT INTO community_attachment (id, uploader_id, r2_key, filename, created_at) VALUES ('a', 'author', 'original', 'file', 'now')");const message = await send({clientNonce: "nonce", attachmentIds: ["a"], mentions: [{ userId: "peer", kind: "mention" }],participants: [{ userId: "author", source: "spoke" }, { userId: "peer", source: "mention" }], extraStatements: [bump()],});- expect(rows("community_attachment")[0]).toMatchObject({ message_id: message!.id });+ expect(rows("community_message_attachment")[0]).toMatchObject({ message_id: message!.id });expect(rows("community_mention")).toHaveLength(1);expect(rows("community_channel_member")).toHaveLength(2);await expect(send({ clientNonce: "nonce", extraStatements: [bump()] })).rejects.toThrow();@@ -107,8 +105,8 @@ describe("Community durable writes — real SQLite transactions", () => {expect(rows("community_message_seq")).toEqual([{ channel_id: "channel", next_seq: 1 }]);});- it("rejects missing, foreign and already reserved attachments without partial writes", async () => {- fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0), ('foreign', 'peer', 'channel', NULL, 0)");+ it("rejects missing, unreadable and duplicate attachments without partial writes; permits reuse", async () => {+ fixture.sqlite.exec("INSERT INTO community_attachment (id, uploader_id, r2_key, filename, created_at) VALUES ('a', 'author', 'original', 'file', 'now'), ('foreign', 'peer', 'original', 'file', 'now')");for (const ids of [["a", "missing"], ["a", "foreign"], ["a", "a"]]) {const error = await send({ attachmentIds: ids }).catch((error) => error);expect(isMessageAttachmentConflict(error)).toBe(true);@@ -116,8 +114,9 @@ describe("Community durable writes — real SQLite transactions", () => {expect(rows("community_message_seq")).toEqual([]);}await send({ attachmentIds: ["a"] });- await expect(send({ attachmentIds: ["a"] })).rejects.toThrow();- expect(rows("community_message")).toHaveLength(1);+ await send({ attachmentIds: ["a"] });+ expect(rows("community_message")).toHaveLength(2);+ expect(rows("community_message_attachment")).toHaveLength(2);});it("a later mention chunk failure rolls back all chunks and same nonce can retry", async () => {@@ -134,10 +133,10 @@ describe("Community durable writes — real SQLite transactions", () => {expect(fixture.batchSizes.flat().every((size) => size <= 100)).toBe(true);});- it("forum structure and pending rebind failure rolls back opener, activity and nonce", async () => {- fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0)");- fixture.sqlite.exec("CREATE TRIGGER fail_rebind BEFORE UPDATE OF target_id ON community_attachment BEGIN SELECT RAISE(ABORT, 'injected rebind failure'); END");- const data = { clientNonce: "forum", forumThread: { id: "thread", name: "title", serverId: "server", pendingAttachmentIds: ["a"] }, extraStatements: [bump()] };+ it("forum structure and association failure rolls back opener, activity and nonce", async () => {+ fixture.sqlite.exec("INSERT INTO community_attachment (id, uploader_id, r2_key, filename, created_at) VALUES ('a', 'author', 'original', 'file', 'now')");+ fixture.sqlite.exec("CREATE TRIGGER fail_rebind BEFORE INSERT ON community_message_attachment BEGIN SELECT RAISE(ABORT, 'injected rebind failure'); END");+ const data = { clientNonce: "forum", attachmentIds: ["a"], forumThread: { id: "thread", name: "title", serverId: "server" }, extraStatements: [bump()] };await expect(send(data)).rejects.toThrow("injected rebind failure");expect(rows("community_message")).toEqual([]);expect(rows("community_channel")).toHaveLength(1);@@ -146,7 +145,7 @@ describe("Community durable writes — real SQLite transactions", () => {fixture.sqlite.exec("DROP TRIGGER fail_rebind");const message = await send(data);expect(rows("community_channel")[1]).toMatchObject({ parent_message_id: message!.id, type: "thread" });- expect(rows("community_attachment")[0]).toMatchObject({ target_id: "thread", message_id: null });+ expect(rows("community_message_attachment")[0]).toMatchObject({ message_id: message!.id });expect(rows("activity")).toEqual([{ sent: 1 }]);});it("later participant chunk failure rolls back the send and all earlier memberships", async () => {@@ -164,12 +163,13 @@ describe("Community durable writes — real SQLite transactions", () => {});it("an attachment write failure rolls back the message, author cursor, counter and sent count", async () => {- fixture.sqlite.exec("INSERT INTO community_attachment VALUES ('a', 'author', 'channel', NULL, 0)");- fixture.sqlite.exec("CREATE TRIGGER fail_attachment BEFORE UPDATE OF message_id ON community_attachment BEGIN SELECT RAISE(ABORT, 'injected attachment failure'); END");+ fixture.sqlite.exec("INSERT INTO community_attachment (id, uploader_id, r2_key, filename, created_at) VALUES ('a', 'author', 'original', 'file', 'now')");+ fixture.sqlite.exec("CREATE TRIGGER fail_attachment BEFORE INSERT ON community_message_attachment BEGIN SELECT RAISE(ABORT, 'injected attachment failure'); END");await expect(send({ attachmentIds: ["a"], extraStatements: [bump()] })).rejects.toThrow("injected attachment failure");for (const table of ["community_message", "community_message_seq", "community_read_state", "community_read_state_revision"]) expect(rows(table)).toEqual([]);expect(rows("activity")).toEqual([{ sent: 0 }]);- expect(rows("community_attachment")[0]).toMatchObject({ message_id: null });+ expect(rows("community_attachment")).toHaveLength(1);+ expect(rows("community_message_attachment")).toEqual([]);});});diff --git a/src/shared/test/helpers/community-write-db.ts b/src/shared/test/helpers/community-write-db.tsindex 2a02445d3..36b5161e2 100644--- a/src/shared/test/helpers/community-write-db.ts+++ b/src/shared/test/helpers/community-write-db.ts@@ -1,3 +1,4 @@+import { readFileSync } from "node:fs";import Sqlite from "better-sqlite3";import { drizzle } from "drizzle-orm/better-sqlite3";import type { Database } from "../../src/db";@@ -43,7 +44,9 @@ export function communityWriteDb() {CREATE TABLE community_read_state_revision (user_id TEXT PRIMARY KEY, revision INTEGER NOT NULL);CREATE TABLE community_attachment (id TEXT PRIMARY KEY, uploader_id TEXT NOT NULL, target_id TEXT NOT NULL REFERENCES community_channel(id),- message_id TEXT REFERENCES community_message(id), position INTEGER DEFAULT 0+ message_id TEXT REFERENCES community_message(id) ON DELETE CASCADE, position INTEGER DEFAULT 0,+ r2_key TEXT NOT NULL DEFAULT 'original', thumbnail_r2_key TEXT, filename TEXT NOT NULL DEFAULT 'file',+ content_type TEXT, size INTEGER, width INTEGER, height INTEGER, created_at TEXT NOT NULL DEFAULT 'now');CREATE TABLE community_mention (id TEXT PRIMARY KEY, message_id TEXT NOT NULL REFERENCES community_message(id), user_id TEXT NOT NULL REFERENCES user(id),@@ -59,10 +62,14 @@ export function communityWriteDb() {created_at TEXT NOT NULL,claimed_at TEXT);+ CREATE TABLE community_category (id TEXT PRIMARY KEY, private INTEGER NOT NULL DEFAULT 0);+ CREATE TABLE community_server_member (id TEXT PRIMARY KEY, server_id TEXT NOT NULL, user_id TEXT NOT NULL);+ CREATE TABLE community_friendship (id TEXT PRIMARY KEY, requester_id TEXT NOT NULL, addressee_id TEXT NOT NULL, status TEXT NOT NULL);CREATE TABLE activity (sent INTEGER NOT NULL);INSERT INTO activity VALUES (0);INSERT INTO community_channel (id, type, created_at) VALUES ('channel', 'text', 'now');`);+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0106_community_attachment_reuse.sql", import.meta.url), "utf8"));const orm = drizzle(sqlite);const batchSizes: number[][] = [];const db = orm as unknown as Database;diff --git a/src/shared/test/migrations/community-attachment-reuse.test.ts b/src/shared/test/migrations/community-attachment-reuse.test.tsnew file mode 100644index 000000000..eb133dc83--- /dev/null+++ b/src/shared/test/migrations/community-attachment-reuse.test.ts@@ -0,0 +1,72 @@+import Sqlite from "better-sqlite3";+import { getTableName } from "drizzle-orm";+import { getTableConfig } from "drizzle-orm/sqlite-core";+import { communityMessageAttachment } from "../../src/db/community-schema";+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++const migration = readFileSync(new URL("../../../web/migrations/0106_community_attachment_reuse.sql", import.meta.url), "utf8");+function oldDatabase() {+ const db = new Sqlite(":memory:"); db.pragma("foreign_keys = ON");+ db.exec(`+ CREATE TABLE community_message (id TEXT PRIMARY KEY);+ INSERT INTO community_message VALUES ('source'), ('destination');+ CREATE TABLE community_attachment (+ id TEXT PRIMARY KEY, message_id TEXT REFERENCES community_message(id) ON DELETE CASCADE,+ uploader_id TEXT NOT NULL, target_id TEXT NOT NULL, r2_key TEXT NOT NULL,+ filename TEXT NOT NULL, content_type TEXT, size INTEGER, width INTEGER, height INTEGER,+ position INTEGER, created_at TEXT NOT NULL, thumbnail_r2_key TEXT+ );+ INSERT INTO community_attachment VALUES+ ('b','source','u','channel','old/b','b.pdf','application/pdf',2,NULL,NULL,1,'now',NULL),+ ('a','source','u','channel','old/a','a.png','image/png',1,10,20,0,'now','old/a.thumb'),+ ('draft',NULL,'u','channel','old/draft','unsent.txt','text/plain',3,NULL,NULL,NULL,'now',NULL);+ `);+ return db;+}++describe("attachment schema migration preserves file identity", () => {+ it("preserves all metadata, ordering and drafts; last-reference deletion cascades only the file with no remaining references", () => {+ const db = oldDatabase();+ try {+ const before = db.prepare("SELECT id,uploader_id,r2_key,thumbnail_r2_key,filename,content_type,size,width,height,created_at FROM community_attachment ORDER BY id").all();+ db.transaction(() => db.exec(migration))();+ const declaredForeignKeys = getTableConfig(communityMessageAttachment).foreignKeys.map((key) => {+ const reference = key.reference();+ return { from: reference.columns[0].name, table: getTableName(reference.foreignTable),+ to: reference.foreignColumns[0].name, on_delete: key.onDelete?.toUpperCase() };+ }).sort((a, b) => a.from.localeCompare(b.from));+ const migratedForeignKeys = (db.pragma("foreign_key_list(community_message_attachment)") as Array<{+ from: string; table: string; to: string; on_delete: string;+ }>).map(({ from, table, to, on_delete }) => ({ from, table, to, on_delete }))+ .sort((a, b) => a.from.localeCompare(b.from));+ expect(migratedForeignKeys).toEqual(declaredForeignKeys);+ expect(db.prepare("SELECT * FROM community_attachment ORDER BY id").all()).toEqual(before);+ expect(db.prepare("SELECT * FROM community_message_attachment ORDER BY position").all()).toEqual([+ { message_id: "source", attachment_id: "a", position: 0 },+ { message_id: "source", attachment_id: "b", position: 1 },+ ]);+ db.exec("INSERT INTO community_message_attachment VALUES ('destination','a',0)");+ expect(() => db.exec("DELETE FROM community_attachment WHERE id = 'a'")).toThrow();+ db.exec("DELETE FROM community_message WHERE id = 'source'");+ expect(db.prepare("SELECT id FROM community_attachment ORDER BY id").all()).toEqual([{ id: "a" }, { id: "draft" }]);+ db.exec("DELETE FROM community_message WHERE id = 'destination'");+ expect(db.prepare("SELECT id FROM community_attachment").all()).toEqual([{ id: "draft" }]);+ expect(db.pragma("foreign_key_check")).toEqual([]);+ } finally { db.close(); }+ });++ it("an invalid old ordering rolls back the complete schema migration; backup restore remains possible before writes resume", () => {+ const db = oldDatabase();+ try {+ db.exec("UPDATE community_attachment SET position = 0 WHERE id = 'b'");+ const before = db.prepare("SELECT * FROM community_attachment ORDER BY id").all();+ expect(() => db.transaction(() => db.exec(migration))()).toThrow();+ expect(db.prepare("SELECT * FROM community_attachment ORDER BY id").all()).toEqual(before);+ expect(db.prepare("SELECT name FROM sqlite_master WHERE name = 'community_message_attachment'").all()).toEqual([]);+ db.exec("UPDATE community_attachment SET position = 1 WHERE id = 'b'");+ db.transaction(() => db.exec(migration))();+ expect(db.pragma("foreign_key_check")).toEqual([]);+ } finally { db.close(); }+ });+});diff --git a/src/shared/test/queries/community-attachment-rebind.test.ts b/src/shared/test/queries/community-attachment-rebind.test.tsdeleted file mode 100644index 6b3a6f0fd..000000000--- a/src/shared/test/queries/community-attachment-rebind.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { describe, expect, it, vi } from "vitest"-import { rebindPendingAttachmentsToChild } from "../../src/db/queries/community/attachment"--function createDb(reboundIds: string[]) {- const countChain: any = {}- countChain.from = vi.fn(() => countChain)- countChain.where = vi.fn(() => countChain)- const updateChain: any = {}- updateChain.set = vi.fn(() => updateChain)- updateChain.where = vi.fn(() => updateChain)- updateChain.returning = vi.fn(async () => reboundIds.map((id) => ({ id })))- return {- select: vi.fn(() => countChain),- update: vi.fn(() => updateChain),- countChain,- updateChain,- }-}--describe("rebindPendingAttachmentsToChild", () => {- it("moves an eligible pending attachment to the direct child target", async () => {- const db = createDb(["attachment_1"])-- const result = await rebindPendingAttachmentsToChild(db as any, {- ids: ["attachment_1"],- uploaderId: "user_1",- parentTargetId: "forum_1",- childTargetId: "thread_1",- })-- expect(result).toBe(true)- expect(db.updateChain.set).toHaveBeenCalledWith({ targetId: "thread_1" })- })-- it("accepts an attachment already pending on the same child for replay", async () => {- const db = createDb(["attachment_1"])-- const result = await rebindPendingAttachmentsToChild(db as any, {- ids: ["attachment_1"],- uploaderId: "user_1",- parentTargetId: "forum_1",- childTargetId: "thread_1",- })-- expect(result).toBe(true)- })-- it("rejects the whole set when any requested attachment is outside the scoped pending rows", async () => {- const db = createDb([])-- const result = await rebindPendingAttachmentsToChild(db as any, {- ids: ["attachment_1", "sibling_or_foreign_attachment"],- uploaderId: "user_1",- parentTargetId: "forum_1",- childTargetId: "thread_1",- })-- expect(result).toBe(false)- expect(db.update).toHaveBeenCalledTimes(1)- expect(db.select).toHaveBeenCalledTimes(1)- })-- it("rejects a partial-overlap race from the guarded statement", async () => {- const db = createDb(["attachment_1"])-- const result = await rebindPendingAttachmentsToChild(db as any, {- ids: ["attachment_1", "attachment_2"],- uploaderId: "user_1",- parentTargetId: "forum_1",- childTargetId: "thread_1",- })-- expect(result).toBe(false)- expect(db.updateChain.returning).toHaveBeenCalledTimes(1)- })-})diff --git a/src/shared/test/queries/community-attachment-reuse.test.ts b/src/shared/test/queries/community-attachment-reuse.test.tsnew file mode 100644index 000000000..91d926715--- /dev/null+++ b/src/shared/test/queries/community-attachment-reuse.test.ts@@ -0,0 +1,136 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { createAttachment, getReadableAttachmentById, listMessageAttachments } from "../../src/db/queries/community/attachment";+import { createMessage, isMessageAttachmentConflict } from "../../src/db/queries/community/message";+import { communityWriteDb } from "../helpers/community-write-db";++describe("reusable files with real SQLite authorization and transactions", () => {+ let fixture: ReturnType<typeof communityWriteDb>;+ beforeEach(() => {+ fixture = communityWriteDb();+ fixture.sqlite.exec(`+ INSERT INTO user(id) VALUES ('recipient'), ('stranger');+ UPDATE community_channel SET server_id = 's1' WHERE id = 'channel';+ INSERT INTO community_channel(id, server_id, type, created_at) VALUES ('destination', 's2', 'text', 'now');+ INSERT INTO community_server_member VALUES ('1','s1','author'), ('2','s1','peer'), ('3','s2','peer'), ('4','s2','recipient');+ `);+ });+ afterEach(() => fixture.sqlite.close());+ const upload = (id: string, overrides = {}) => createAttachment(fixture.db, {+ id, uploaderId: "author", filename: `${id}.pdf`, r2Key: "attachments/sha256/shared", size: 3, ...overrides,+ });+ const send = (authorId: string, channelId: string, attachmentIds: string[], overrides = {}) =>+ createMessage(fixture.db, { authorId, content: "file", channelId, attachmentIds, ...overrides });+ const read = (id: string, userId: string) => getReadableAttachmentById(fixture.db, id, userId);++ it("only the uploader can read or use an unsent file", async () => {+ await upload("a");+ expect(await read("a", "author")).toMatchObject({ id: "a" });+ expect(await read("a", "peer")).toBeNull();+ expect(await read("missing", "author")).toBeNull();+ const error = await send("peer", "destination", ["a"]).catch(e => e);+ expect(isMessageAttachmentConflict(error)).toBe(true);+ expect(fixture.sqlite.prepare("SELECT * FROM community_message").all()).toEqual([]);+ });++ it("an upload finishing after uploader deletion cannot create a dead-owner file", async () => {+ fixture.sqlite.exec("UPDATE user SET deletedAt = 'now' WHERE id = 'author'");+ await expect(upload("deleted")).rejects.toThrow("uploader no longer exists");+ fixture.sqlite.exec("DELETE FROM user WHERE id = 'author'");+ await expect(upload("missing")).rejects.toThrow("uploader no longer exists");+ expect(fixture.sqlite.prepare("SELECT * FROM community_attachment").all()).toEqual([]);+ });++ it("forwards the same ID across servers and preserves each message's order", async () => {+ await upload("a"); await upload("b", { filename: "other.pdf" });+ const source = await send("author", "channel", ["a", "b"]);+ const copies = await Promise.all([send("peer", "destination", ["b", "a"]), send("peer", "destination", ["a"])]);+ expect((await listMessageAttachments(fixture.db, source!.id)).map(r => r.id)).toEqual(["a", "b"]);+ expect((await listMessageAttachments(fixture.db, copies[0]!.id)).map(r => r.id)).toEqual(["b", "a"]);+ expect(await read("a", "recipient")).toMatchObject({ filename: "a.pdf" });+ expect(await read("a", "stranger")).toBeNull();+ fixture.sqlite.prepare("DELETE FROM community_message WHERE id = ?").run(source!.id);+ expect(await read("a", "recipient")).not.toBeNull();+ fixture.sqlite.prepare("DELETE FROM community_message WHERE channel_id = 'destination'").run();+ expect(await read("a", "author")).toBeNull();+ expect(await read("b", "author")).toBeNull();+ });++ it("rechecks source revocation at the message commit boundary", async () => {+ await upload("a"); await send("author", "channel", ["a"]);+ expect(await read("a", "peer")).not.toBeNull();+ const batch = fixture.db.batch.bind(fixture.db);+ fixture.db.batch = ((statements: any[]) => {+ fixture.sqlite.exec("DELETE FROM community_server_member WHERE server_id = 's1' AND user_id = 'peer'");+ return batch(statements as any);+ }) as any;+ const error = await send("peer", "destination", ["a"]).catch(e => e);+ expect(isMessageAttachmentConflict(error)).toBe(true);+ expect(fixture.sqlite.prepare("SELECT * FROM community_message WHERE channel_id = 'destination'").all()).toEqual([]);+ expect(fixture.sqlite.prepare("SELECT * FROM community_message_seq WHERE channel_id = 'destination'").all()).toEqual([]);+ });++ it("last-reference deletion cannot race a stale forwarding permission proof", async () => {+ await upload("a"); const source = await send("author", "channel", ["a"]);+ expect(await read("a", "peer")).not.toBeNull();+ fixture.sqlite.prepare("DELETE FROM community_message WHERE id = ?").run(source!.id);+ const error = await send("peer", "destination", ["a"]).catch(e => e);+ expect(isMessageAttachmentConflict(error)).toBe(true);+ expect(fixture.sqlite.prepare("PRAGMA foreign_key_check").all()).toEqual([]);+ await upload("draft");+ fixture.sqlite.exec("DELETE FROM community_channel WHERE id = 'destination'");+ expect(await read("draft", "author")).not.toBeNull();+ });++ it("a deleted actor cannot retain uploader or source access while another reader can use the file", async () => {+ await upload("a"); await send("author", "channel", ["a"]);+ await send("peer", "destination", ["a"]);+ fixture.sqlite.exec("UPDATE user SET deletedAt = 'now' WHERE id = 'author'");+ expect(await read("a", "author")).toBeNull();+ expect(await read("a", "recipient")).not.toBeNull();+ fixture.sqlite.exec("UPDATE user SET deletedAt = 'now' WHERE id = 'peer'");+ expect(await read("a", "peer")).toBeNull();+ const error = await send("peer", "destination", ["a"]).catch(e => e);+ expect(isMessageAttachmentConflict(error)).toBe(true);+ expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_message WHERE channel_id = 'destination'").get()).toEqual({ count: 1 });+ });++ it("private forum children inherit the parent access roster; removal takes effect", async () => {+ await upload("a");+ fixture.sqlite.exec(`+ INSERT INTO community_category VALUES ('private', 1);+ UPDATE community_channel SET category_id = 'private', type = 'forum', creator_id = 'author' WHERE id = 'channel';+ INSERT INTO community_channel(id, server_id, type, parent_channel_id, created_at) VALUES ('thread','s1','thread','channel','now');+ `);+ await send("author", "thread", ["a"]);+ expect(await read("a", "peer")).toBeNull();+ fixture.sqlite.exec("INSERT INTO community_channel_member(id,channel_id,user_id,relation,added_at) VALUES ('private-access','channel','peer','access','now')");+ expect(await read("a", "peer")).not.toBeNull();+ fixture.sqlite.exec("DELETE FROM community_channel_member WHERE id = 'private-access'");+ expect(await read("a", "peer")).toBeNull();+ });++ it("DM participant access and either direction of blocking apply to file readers", async () => {+ await upload("a");+ fixture.sqlite.exec(`+ INSERT INTO community_channel(id,type,created_at) VALUES ('dm','dm','now');+ INSERT INTO community_channel_member(id,channel_id,user_id,relation,added_at) VALUES ('dm-a','dm','author','access','now'), ('dm-p','dm','peer','access','now');+ `);+ await send("author", "dm", ["a"]);+ expect(await read("a", "peer")).not.toBeNull();+ fixture.sqlite.exec("INSERT INTO community_friendship VALUES ('block','author','peer','blocked')");+ expect(await read("a", "peer")).toBeNull();+ fixture.sqlite.exec("UPDATE community_friendship SET requester_id = 'peer', addressee_id = 'author'");+ expect(await read("a", "peer")).toBeNull();+ expect(await read("a", "author")).not.toBeNull();+ });++ it("file metadata and shared keys are independent, and unreferenced drafts survive other deletion", async () => {+ const a = await upload("a", { thumbnailR2Key: "attachment-thumbnails/sha256/first" });+ const b = await upload("b", { filename: "renamed.pdf", thumbnailR2Key: "attachment-thumbnails/sha256/second" });+ expect(a.id).not.toBe(b.id); expect(a.r2Key).toBe(b.r2Key);+ const source = await send("author", "channel", ["a"]);+ fixture.sqlite.prepare("DELETE FROM community_message WHERE id = ?").run(source!.id);+ expect(await read("a", "author")).toBeNull();+ expect(await read("b", "author")).toMatchObject({ filename: "renamed.pdf", r2Key: a.r2Key });+ });+});diff --git a/src/shared/test/queries/community-attachment-thumbnail.test.ts b/src/shared/test/queries/community-attachment-thumbnail.test.tsdeleted file mode 100644index 6834048f8..000000000--- a/src/shared/test/queries/community-attachment-thumbnail.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, expect, it, vi } from "vitest"-import { createPendingAttachment } from "../../src/db/queries/community/attachment"--function database(row: Record<string, unknown> | null) {- const candidate: any = {}- candidate.from = vi.fn(() => candidate)- candidate.where = vi.fn(() => candidate)- candidate.limit = vi.fn(() => candidate)- const insert: any = {}- insert.select = vi.fn(() => insert)- insert.returning = vi.fn(async () => row ? [row] : [])- return {- select: vi.fn(() => candidate),- insert: vi.fn(() => insert),- candidate,- insertChain: insert,- }-}--describe("community attachment thumbnail persistence", () => {- it("preserves an exact thumbnail key without changing the original", async () => {- const db = database({- id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",- thumbnailR2Key: "original-key.thumbnail.jpg", filename: "photo.png", messageId: null,- })- const row = await createPendingAttachment(db as any, {- id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",- thumbnailR2Key: "original-key.thumbnail.jpg", filename: "photo.png",- })- expect(row).toMatchObject({- r2Key: "original-key",- thumbnailR2Key: "original-key.thumbnail.jpg",- messageId: null,- })- })-- it("writes null for legacy/original-only uploads", async () => {- const db = database({- id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",- thumbnailR2Key: null, filename: "file.txt", messageId: null,- })- const row = await createPendingAttachment(db as any, {- id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key", filename: "file.txt",- })- expect(row.thumbnailR2Key).toBeNull()- })-- it("throws when the target-exists INSERT SELECT returns no row", async () => {- const db = database(null)- await expect(createPendingAttachment(db as any, {- id: "a1", uploaderId: "u1", targetId: "deleted", r2Key: "original-key", filename: "file.txt",- })).rejects.toThrow("attachment target no longer exists")- expect(db.insertChain.select).toHaveBeenCalledWith(db.candidate)- })-})diff --git a/src/shared/test/queries/community-file-delete.test.ts b/src/shared/test/queries/community-file-delete.test.tsnew file mode 100644index 000000000..b574a6a54--- /dev/null+++ b/src/shared/test/queries/community-file-delete.test.ts@@ -0,0 +1,88 @@+import { readFileSync, readdirSync } from "node:fs";+import { resolve } from "node:path";+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { Database } from "../../src/db";+import { deleteChannelWithMedia, deleteServerWithMedia } from "../../src/db/queries/community/delete-media";+import { deleteForumPost } from "../../src/db/queries/community/forum-post-delete";++describe("community file deletion with migrated SQLite", () => {+ let sqlite: Sqlite.Database;+ let db: Database;+ const now = "2026-10-10T00:00:00.000Z";+ const run = (statement: string) => sqlite.exec(statement);+ const rows = (table: string) => sqlite.prepare("SELECT * FROM " + table).all();++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ const migrationRoot = resolve(import.meta.dirname, "../../../web/migrations");+ for (const filename of readdirSync(migrationRoot).filter(name => name.endsWith(".sql")).sort()) {+ sqlite.exec(readFileSync(resolve(migrationRoot, filename), "utf8"));+ }+ sqlite.pragma("foreign_keys = ON");+ const orm = drizzle(sqlite);+ Object.assign(orm, {+ batch: async (statements: Array<{ config: { returning?: unknown }; all: () => unknown[]; run: () => unknown }>) =>+ sqlite.transaction(() => statements.map(statement => statement.config.returning ? statement.all() : statement.run()))(),+ });+ db = orm as unknown as Database;+ run("INSERT INTO user (id,email,name,discriminator) VALUES ('owner','[email protected]','Owner','8101'),('reader','[email protected]','Reader','8102')");+ sqlite.prepare("INSERT INTO community_server (id,name,discriminator,owner_id,icon,created_at) VALUES ('source','Source','8201','owner','servers/source/icon',?),('destination','Destination','8202','owner',NULL,?)").run(now, now);+ sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,created_at) VALUES ('source-channel','source','Source','text',?),('destination-channel','destination','Destination','text',?)").run(now, now);+ sqlite.prepare("INSERT INTO community_message (id,author_id,content,created_at,channel_id,seq) VALUES ('source-message','owner','source',?,'source-channel',1),('destination-message','reader','copy',?,'destination-channel',1)").run(now, now);+ sqlite.prepare("INSERT INTO community_attachment (id,uploader_id,r2_key,thumbnail_r2_key,filename,created_at) VALUES ('copied','owner','attachments/shared','thumb/shared','copied.png',?),('last-reference','owner','attachments/shared','thumb/shared','last.png',?),('draft','owner','attachments/shared','thumb/shared','draft.png',?)").run(now, now, now);+ run("INSERT INTO community_message_attachment VALUES ('source-message','copied',0),('source-message','last-reference',1),('destination-message','copied',0)");+ });++ afterEach(() => sqlite.close());++ function assertRetainedFiles() {+ expect(rows("community_attachment").map(row => (row as { id: string }).id).sort()).toEqual(["copied", "draft"]);+ expect(rows("community_message_attachment")).toEqual([{ message_id: "destination-message", attachment_id: "copied", position: 0 }]);+ expect(sqlite.prepare("SELECT id FROM community_message").all()).toEqual([{ id: "destination-message" }]);+ expect(sqlite.prepare("PRAGMA foreign_key_check").all()).toEqual([]);+ }++ it.each(["channel", "server"] as const)("deleting a %s preserves copies and drafts; advances readers only once", async kind => {+ sqlite.prepare("INSERT INTO community_read_state (id,user_id,channel_id,last_read_message_id,last_read_seq,last_read_at) VALUES ('read','reader','source-channel','source-message',1,?)").run(now);+ const deleteRoot = () => kind === "channel"+ ? deleteChannelWithMedia(db, { channelId: "source-channel", serverId: "source" })+ : deleteServerWithMedia(db, { serverId: "source", ownerId: "owner" });+ const wrongScope = kind === "channel"+ ? await deleteChannelWithMedia(db, { channelId: "source-channel", serverId: "destination" })+ : await deleteServerWithMedia(db, { serverId: "source", ownerId: "reader" });+ expect(wrongScope).toMatchObject({ deleted: false, mediaKeys: [], readStateRevisions: [] });+ expect(rows("community_attachment")).toHaveLength(3);+ expect(await deleteRoot()).toMatchObject({ deleted: true, mediaKeys: [], readStateRevisions: [{ userId: "reader", revision: 1 }] });+ if (kind === "server") expect(sqlite.prepare("SELECT id FROM community_server").all()).toEqual([{ id: "destination" }]);+ assertRetainedFiles();+ expect(rows("community_read_state")).toEqual([]);+ expect(await deleteRoot()).toMatchObject({ deleted: false, mediaKeys: [], readStateRevisions: [] });+ expect(rows("community_read_state_revision")).toEqual([{ user_id: "reader", revision: 1 }]);+ });++ it.each([false, true])("forum deletion repairs prior cursor=%s and cascades its sole files without deleting a copy", async hasPrior => {+ run("UPDATE community_channel SET type='forum',message_count=2 WHERE id='source-channel'");+ run("UPDATE community_message SET seq=2 WHERE id='source-message'");+ if (hasPrior) sqlite.prepare("INSERT INTO community_message (id,author_id,content,created_at,channel_id,seq) VALUES ('prior','owner','prior',?,'source-channel',1)").run(now);+ sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,parent_channel_id,parent_message_id,created_at) VALUES ('child','source','Post','thread','source-channel','source-message',?)").run(now);+ sqlite.prepare("INSERT INTO community_message (id,author_id,content,created_at,channel_id,seq) VALUES ('body','owner','body',?,'child',1)").run(now);+ run("INSERT INTO community_message_attachment VALUES ('body','last-reference',0)");+ sqlite.prepare("INSERT INTO community_read_state (id,user_id,channel_id,last_read_message_id,last_read_seq,last_read_at) VALUES ('parent-read','reader','source-channel','source-message',2,?),('child-read','reader','child','body',1,?)").run(now, now);+ const input = { openerId: "source-message", openerSeq: 2, forumChannelId: "source-channel", childChannelId: "child" };+ expect(await deleteForumPost(db, input)).toEqual({ deleted: true, mediaKeys: [], readStateRevisions: [{ userId: "reader", revision: 1 }] });+ expect(rows("community_attachment").map(row => (row as { id: string }).id).sort()).toEqual(["copied", "draft"]);+ expect(rows("community_message_attachment")).toEqual([{ message_id: "destination-message", attachment_id: "copied", position: 0 }]);+ expect(sqlite.prepare("SELECT id FROM community_channel WHERE id='child'").all()).toEqual([]);+ expect(sqlite.prepare("SELECT message_count FROM community_channel WHERE id='source-channel'").get()).toEqual({ message_count: 1 });+ expect(rows("community_read_state")).toEqual(hasPrior ? [{+ id: "parent-read", user_id: "reader", channel_id: "source-channel",+ last_read_message_id: "prior", last_read_seq: 1, last_read_at: now,+ }] : []);+ expect(await deleteForumPost(db, input)).toEqual({ deleted: false, mediaKeys: [], readStateRevisions: [] });+ expect(rows("community_read_state_revision")).toEqual([{ user_id: "reader", revision: 1 }]);+ expect(sqlite.prepare("SELECT message_count FROM community_channel WHERE id='source-channel'").get()).toEqual({ message_count: 1 });+ expect(sqlite.prepare("PRAGMA foreign_key_check").all()).toEqual([]);+ });+});diff --git a/src/shared/test/queries/community-notification-target.test.ts b/src/shared/test/queries/community-notification-target.test.tsindex 203ca59dd..ef4b6a3e7 100644--- a/src/shared/test/queries/community-notification-target.test.ts+++ b/src/shared/test/queries/community-notification-target.test.ts@@ -35,11 +35,10 @@ describe("community notification target query", () => {);CREATE TABLE community_attachment (id TEXT PRIMARY KEY NOT NULL,- message_id TEXT,content_type TEXT,- position INTEGER,created_at TEXT NOT NULL);+ CREATE TABLE community_message_attachment (message_id TEXT, attachment_id TEXT, position INTEGER);INSERT INTO user (id, name) VALUES('author-1', 'Alice'),('author-blank', ' ');@@ -65,10 +64,11 @@ describe("community notification target query", () => {('message-fallback', 'author-blank', '**hello**', 'thread-blank'),('message-orphan', 'author-1', '**hello**', 'thread-orphan');INSERT INTO community_attachment- (id, message_id, content_type, position, created_at)+ (id, content_type, created_at)VALUES- ('attachment-2', 'message-channel', 'application/pdf', 1, '2026-09-12T00:00:01.000Z'),- ('attachment-1', 'message-channel', 'image/png', 0, '2026-09-12T00:00:00.000Z');+ ('attachment-2', 'application/pdf', '2026-09-12T00:00:01.000Z'),+ ('attachment-1', 'image/png', '2026-09-12T00:00:00.000Z');+ INSERT INTO community_message_attachment VALUES ('message-channel', 'attachment-2', 1), ('message-channel', 'attachment-1', 0);`);db = drizzle(sqlite, { schema }) as unknown as Database;});diff --git a/src/shared/test/queries/param-limit.test.ts b/src/shared/test/queries/param-limit.test.tsindex 87cdbddaf..c8dbe35fc 100644--- a/src/shared/test/queries/param-limit.test.ts+++ b/src/shared/test/queries/param-limit.test.ts@@ -138,6 +138,7 @@ function makeSelectCapture(rowsPerCall: unknown[][]) {select: vi.fn(() => {const chain: any = {};chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);chain.where = vi.fn(() => chain);chain.orderBy = vi.fn(() => Promise.resolve(rowsPerCall[call++] ?? []));return chain;diff --git a/src/web/migrations/0106_community_attachment_reuse.sql b/src/web/migrations/0106_community_attachment_reuse.sqlnew file mode 100644index 000000000..d8285600c--- /dev/null+++ b/src/web/migrations/0106_community_attachment_reuse.sql@@ -0,0 +1,47 @@+CREATE TABLE community_attachment_rebuild (+ id TEXT PRIMARY KEY,+ uploader_id TEXT NOT NULL,+ r2_key TEXT NOT NULL,+ thumbnail_r2_key TEXT,+ filename TEXT NOT NULL,+ content_type TEXT,+ size INTEGER,+ width INTEGER,+ height INTEGER,+ created_at TEXT NOT NULL+);+INSERT INTO community_attachment_rebuild+ SELECT id, uploader_id, r2_key, thumbnail_r2_key, filename, content_type, size, width, height, created_at+ FROM community_attachment;+CREATE TABLE community_attachment_links_backfill (+ message_id TEXT NOT NULL,+ attachment_id TEXT NOT NULL,+ position INTEGER NOT NULL+);+INSERT INTO community_attachment_links_backfill+ SELECT message_id, id, COALESCE(position, 0)+ FROM community_attachment WHERE message_id IS NOT NULL;+DROP TABLE community_attachment;+ALTER TABLE community_attachment_rebuild RENAME TO community_attachment;+CREATE INDEX idx_attachment_uploader ON community_attachment(uploader_id);+CREATE INDEX idx_attachment_r2_key ON community_attachment(r2_key);+CREATE INDEX idx_attachment_thumbnail_r2_key ON community_attachment(thumbnail_r2_key);+CREATE TABLE community_message_attachment (+ message_id TEXT NOT NULL REFERENCES community_message(id) ON DELETE CASCADE,+ attachment_id TEXT NOT NULL REFERENCES community_attachment(id) ON DELETE RESTRICT,+ position INTEGER NOT NULL,+ PRIMARY KEY (message_id, attachment_id),+ UNIQUE (message_id, position)+);+CREATE INDEX idx_message_attachment_file ON community_message_attachment(attachment_id, message_id);+INSERT INTO community_message_attachment SELECT * FROM community_attachment_links_backfill;+DROP TABLE community_attachment_links_backfill;+CREATE TRIGGER delete_attachment_last_message_reference+AFTER DELETE ON community_message_attachment+BEGIN+ DELETE FROM community_attachment+ WHERE id = OLD.attachment_id+ AND NOT EXISTS (+ SELECT 1 FROM community_message_attachment WHERE attachment_id = OLD.attachment_id+ );+END;diff --git a/src/web/scripts/attachment-maintenance.md b/src/web/scripts/attachment-maintenance.mdnew file mode 100644index 000000000..51ea48988--- /dev/null+++ b/src/web/scripts/attachment-maintenance.md@@ -0,0 +1,45 @@+# Reusable attachment rollout++This candidate is ready for isolated validation, not production rollout. Production schema migration and collection remain blocked until the release operator proves that all old writers have stopped. Deploying another Worker version or waiting 30 seconds does not establish this: HTTP requests have no fixed wall-clock limit while their clients remain connected ([Cloudflare duration limits](https://developers.cloudflare.com/workers/platform/limits/#duration)).++## Data and deletion contract++`community_attachment` stores the named file and its stable random ID. `community_message_attachment` stores ordered message references. New uploads with equal content share an original R2 key; new thumbnails use their own content hashes. Legacy files keep their original and thumbnail keys and bytes. No R2 object migration or historical deduplication is performed. Reuploading creates another file ID, including when bytes and name match.++Only active authenticated actors can read or send files. Uploaders can read their unsent files; other actors need a currently readable live message reference. The common query and message batch recheck account existence and deletion status, including when the account changes after middleware authentication. Downloads read primary D1; message insertion checks readability inside its atomic D1 batch. A URL channel component is only a compatible routing anchor.++Deleting a message cascades its associations. A deletion trigger removes the corresponding file only when the last message reference disappears, in the same transaction. Unsent files are not deletion candidates. Consequently, deleting the last reference invalidates the ID for everyone, including its uploader. Forwarded files survive deletion of the source message, channel, forum or uploader account while another reference remains.++Shared R2 objects are not deleted by requests or failed upload compensation. Their physical deletion is delayed until an independently verified offline maintenance window. This candidate defines no automatic retention timer or promised production collection date. The operator must record the actual retention period and approved collection date before production rollout; old keys are retained by default. Account access/DB deletion and byte deletion are distinct events.++## Isolated rehearsal++Use an independent local D1/R2 state directory and test accounts. Do not use an existing task's state or auth profile. Record the commands, working directories and PIDs of every process that can write this state; stop them and verify they have exited before maintenance. Keep only the maintenance process running until verification finishes.++Create a minimal Wrangler config containing only the local `DB` and `COMMUNITY_MEDIA` bindings, matching the isolated state's database ID and bucket name. Do not mark either binding `remote: true`. The maintenance CLI rejects remote apply and forces local bindings for every apply; a hand-written proof never enables production writes.++1. Export/back up the isolated D1 database and copy its R2 state before schema migration. Record the migration ledger and exact candidate commit. Before 0106, export `id,message_id,position,filename,content_type,size,width,height,created_at,r2_key,thumbnail_r2_key`. Check missing objects, duplicate message positions and foreign-key violations; resolve them before applying.+2. Apply migration 0106 through the existing local Wrangler migrations command using the isolated config/state. Existing IDs, metadata, original keys and thumbnail keys stay unchanged; used files gain ordered associations and unsent files remain files. Verify each old ID and each message's ordered list, plus `PRAGMA foreign_key_check`.+3. Compare metadata/lists/keys against the backup, download originals and thumbnails via the old IDs/URLs, then start the new candidate and execute the plan's actual UI/CLI journeys. Do not hash, copy or rewrite legacy objects.+4. Collection is a separate offline operation after its retention decision. Stop all writers again. Content-addressed prefixes enumerate new orphan candidates. Legacy candidates can only be provided as exact keys in an explicit newline-separated file via `--candidate-keys`; legacy prefixes are never swept. Each candidate is checked against every file's original and thumbnail key. Referenced objects remain in place.++Commands, from `src/web` (replace placeholders with the isolated resources). Wrangler uses `STATE_ROOT/v3` inside its `--persist-to STATE_ROOT`; `getPlatformProxy` uses its persist path directly. Therefore the maintenance CLI must receive the actual `STATE_ROOT/v3` directory, not the Wrangler state root. The proof must also record this exact absolute `localState`:++```sh+pnpm exec wrangler d1 migrations apply <local-database-name> --local --config /absolute/local-wrangler.jsonc --persist-to /absolute/STATE_ROOT+pnpm exec tsx scripts/attachment-maintenance.ts collect --config /absolute/local-wrangler.jsonc --local-state /absolute/STATE_ROOT/v3 --manifest /absolute/collection.jsonl+```++The last command is dry-run. Local apply additionally requires `--apply --quiescence-proof`. The local proof records absolute `configPath`, absolute `localState`, `writersStopped: true`, `invocationsDrained: true`, `stoppedWriterPids`, an `evidence` reference and `expiresAt`. These are records of the completed local stop procedure. The script checks that those PIDs remain absent and the record remains current before each write/delete. A proof is not a replacement for enumerating and stopping every writer.++Use owner-only permissions for backup/state/manifest files. They contain private identifiers and storage keys. Do not attach production data or manifests to public channels. Never include credentials in them.++## Production release gate and rollback++The current CLI cannot apply against remote bindings. Keep the PR unmerged while automatic production deployment could run the new schema-dependent code before migration. No version bump or deployment is authorized by this document.++The release operator must first obtain a verified platform termination contract covering old invocations and background cleanup, or a separately reviewed isolation mechanism that prevents old writers from modifying the migrated DB/R2. The current repository has neither verified mechanism. Sampled logs without requests are not a proof. Until this gate is resolved, use collection dry-run only for any approved remote inspection and retain all objects.++With a verified future gate, snapshot D1 before the short write maintenance window, retain the prior Worker artifact and old objects, complete schema verification and confirm legacy object keys/bytes are unchanged, and only then reopen writes on the exact validated candidate. Record the real stop/restore operations, object retention decision, missing-object count and checksums.++Before reopening writes, restore the complete D1 backup and prior Worker together; retained old objects make that restore possible. After new multi-message associations exist, the old schema cannot represent them without loss. Do not roll back only the Worker or collapse references. Fix forward or prepare and validate an explicit reverse transformation while stopped.diff --git a/src/web/scripts/attachment-maintenance.test.ts b/src/web/scripts/attachment-maintenance.test.tsnew file mode 100644index 000000000..eebd53889--- /dev/null+++ b/src/web/scripts/attachment-maintenance.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest"+import { assertLocalMaintenance } from "./attachment-maintenance"++describe("attachment maintenance production restriction", () => {+ it("rejects remote D1 and R2 configurations independently", () => {+ expect(() => assertLocalMaintenance({ d1_databases: [{ remote: true }] })).toThrow("remote apply is disabled")+ expect(() => assertLocalMaintenance({ r2_buckets: [{ remote: true }] })).toThrow("remote apply is disabled")+ expect(() => assertLocalMaintenance({ d1_databases: [{ remote: false }], r2_buckets: [{}] })).not.toThrow()+ })+})++it("a complete hand-filled proof cannot enable remote CLI apply", async () => {+ const { mkdtempSync, writeFileSync, rmSync } = await import("node:fs")+ const { tmpdir } = await import("node:os")+ const { join } = await import("node:path")+ const { createRequire } = await import("node:module")+ const { fileURLToPath } = await import("node:url")+ const { spawnSync } = await import("node:child_process")+ const directory = mkdtempSync(join(tmpdir(), "alook-attachment-guard-"))+ try {+ const configPath = join(directory, "wrangler.jsonc")+ const localState = join(directory, "state")+ const proofPath = join(directory, "proof.json")+ const stopped = spawnSync(process.execPath, ["-e", "process.exit(0)"])+ writeFileSync(configPath, JSON.stringify({+ name: "qa-file-remote-guard", compatibility_date: "2026-10-10",+ d1_databases: [{ binding: "DB", database_name: "qa", database_id: "00000000-0000-0000-0000-000000000001", remote: true }],+ r2_buckets: [{ binding: "COMMUNITY_MEDIA", bucket_name: "qa-file-remote-guard", remote: true }],+ }))+ writeFileSync(proofPath, JSON.stringify({ configPath, localState, writersStopped: true, invocationsDrained: true,+ evidence: "hand-filled, no actual production evidence", stoppedWriterPids: [stopped.pid], expiresAt: new Date(Date.now() + 60_000).toISOString() }))+ const result = spawnSync(process.execPath, [createRequire(import.meta.url).resolve("tsx/cli"), fileURLToPath(new URL("./attachment-maintenance.ts", import.meta.url)),+ "collect", "--config", configPath, "--manifest", join(directory, "manifest.jsonl"), "--apply", "--local-state", localState, "--quiescence-proof", proofPath],+ { encoding: "utf8", timeout: 20_000 })+ expect(result.status).toBe(1)+ expect(result.stderr).toContain("production/remote apply is disabled")+ } finally { rmSync(directory, { recursive: true, force: true }) }+})diff --git a/src/web/scripts/attachment-maintenance.ts b/src/web/scripts/attachment-maintenance.tsnew file mode 100644index 000000000..f4b638467--- /dev/null+++ b/src/web/scripts/attachment-maintenance.ts@@ -0,0 +1,96 @@+import { appendFile, readFile } from "node:fs/promises"+import { resolve } from "node:path"+import { pathToFileURL } from "node:url"++type Bindings = { DB: D1Database; COMMUNITY_MEDIA: R2Bucket }+type RecordEntry = { operation: "collect"; from: string; deleted: boolean }+type MaintenanceOptions = { apply: boolean; beforeWrite?: () => Promise<void>; record: (entry: RecordEntry) => Promise<void> }++async function requireQuiet(options: MaintenanceOptions) {+ if (!options.beforeWrite) throw new Error("mutation requires a current quiescence check")+ await options.beforeWrite()+}++export async function collectAttachmentObjects(env: Bindings, options: MaintenanceOptions, specifiedKeys: ReadonlySet<string> = new Set()) {+ let cursor: string | undefined+ const candidates = new Set(specifiedKeys)+ for (const prefix of ["attachments/sha256/", "attachment-thumbnails/sha256/"]) {+ cursor = undefined+ do {+ const page = await env.COMMUNITY_MEDIA.list({ prefix, cursor })+ for (const object of page.objects) candidates.add(object.key)+ cursor = page.truncated ? page.cursor : undefined+ } while (cursor)+ }+ let count = 0+ for (const key of candidates) {+ const reference = await env.DB.prepare("SELECT id FROM community_attachment WHERE r2_key = ? OR thumbnail_r2_key = ? LIMIT 1").bind(key, key).first<{ id: string }>()+ if (reference) continue+ if (!/^(attachments\/sha256\/|attachment-thumbnails\/sha256\/|channel\/|dm\/|thread\/)/.test(key)) throw new Error("collection key is outside attachment namespaces")+ if (options.apply) { await requireQuiet(options); await env.COMMUNITY_MEDIA.delete(key) }+ await options.record({ operation: "collect", from: key, deleted: options.apply })+ count+++ }+ return count+}++export function assertLocalMaintenance(config: { d1_databases?: { remote?: boolean }[]; r2_buckets?: { remote?: boolean }[] }) {+ if ([...(config.d1_databases ?? []), ...(config.r2_buckets ?? [])].some(binding => binding.remote)) {+ throw new Error("production/remote apply is disabled: no verified invocation drain mechanism")+ }+}++async function main() {+ const args = process.argv.slice(2)+ const value = (name: string) => args[args.indexOf(name) + 1]+ const mode = args[0]+ if (mode !== "collect" || !args.includes("--config") || !args.includes("--manifest")) {+ throw new Error("usage: attachment-maintenance.ts collect --config <isolated-or-approved-wrangler-config> --manifest <jsonl> [--apply --local-state <path> --quiescence-proof <local-stopped-writers-json>] [--candidate-keys <newline-separated-keys>]")+ }+ const apply = args.includes("--apply")+ const configPath = resolve(value("--config"))+ const beforeWrite = async () => {+ if (!args.includes("--quiescence-proof")) throw new Error("apply requires verified stopped writers and drained invocations")+ const proof = JSON.parse(await readFile(value("--quiescence-proof"), "utf8"))+ if (proof.localState !== (args.includes("--local-state") ? resolve(value("--local-state")) : null)+ || !Array.isArray(proof.stoppedWriterPids) || proof.stoppedWriterPids.length === 0+ || proof.configPath !== configPath || !proof.writersStopped || !proof.invocationsDrained+ || !proof.evidence || !Number.isFinite(Date.parse(proof.expiresAt)) || Date.parse(proof.expiresAt) <= Date.now()) {+ throw new Error("missing, expired or mismatched local quiescence proof; dry-run only")+ }+ for (const pid of proof.stoppedWriterPids) {+ if (!Number.isInteger(pid) || pid <= 0) throw new Error("invalid stopped writer PID")+ try { process.kill(pid, 0) } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ESRCH") continue+ throw error+ }+ throw new Error(`writer process is still running: ${pid}`)+ }+ }+ if (apply) await beforeWrite()+ const specifiedKeys = args.includes("--candidate-keys")+ ? new Set((await readFile(value("--candidate-keys"), "utf8")).split("\n").filter(Boolean))+ : new Set<string>()+ const { getPlatformProxy, unstable_readConfig } = await import("wrangler")+ const config = unstable_readConfig({ config: configPath }, { hideWarnings: true })+ if (apply) {+ assertLocalMaintenance(config)+ if (!args.includes("--local-state")) throw new Error("apply is local-only and requires --local-state")+ }+ const proxy = await getPlatformProxy<Bindings>({+ configPath, envFiles: [], remoteBindings: !apply,+ persist: args.includes("--local-state") ? { path: resolve(value("--local-state")) } : true,+ })+ try {+ const record = async (entry: RecordEntry) => { await appendFile(value("--manifest"), `${JSON.stringify(entry)}\n`, { mode: 0o600 }) }+ const options = { apply, record, beforeWrite }+ const count = await collectAttachmentObjects(proxy.env, options, specifiedKeys)+ console.log(JSON.stringify({ mode, apply, storage: apply ? "local-only" : "configured-read-only", count }))+ } finally {+ await proxy.dispose()+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {+ main().catch(error => { console.error(error instanceof Error ? error.message : "attachment maintenance failed"); process.exitCode = 1 })+}diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.tsindex 09ea8a694..9dc41f257 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts@@ -3,11 +3,9 @@ import { NextRequest } from "next/server"const mockR2Get = vi.fn()const mockR2Head = vi.fn()-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))-const mockGetAttachmentById = vi.fn()-const mockGetMessage = vi.fn()-const mockGetChannelType = vi.fn()+const mockGetReadableAttachmentById = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -16,30 +14,15 @@ vi.mock("@alook/shared", async () => {queries: {...actual.queries,communityAttachment: {- getAttachmentById: (...a: unknown[]) => mockGetAttachmentById(...a),+ getReadableAttachmentById: (...a: unknown[]) => mockGetReadableAttachmentById(...a),},communityMessage: {- ...actual.queries.communityMessage,- getMessage: (...a: unknown[]) => mockGetMessage(...a),},communityChannel: {- ...actual.queries.communityChannel,- getChannelType: (...a: unknown[]) => mockGetChannelType(...a),},},}})--const mockRequireChannelMember = vi.fn()-const mockRequireDMAccess = vi.fn()-vi.mock("@/lib/community/permissions", () => ({- requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),- requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),-}))--// Dual-actor: crk_ bearer → bot arm, else human. The route dispatches by-// actor.kind for the RESPONSE shape; the authz core is identical. A test may-// inject a specific actor via ctx.actor.vi.mock("@/lib/middleware/community-actor", async () => {const actual = await vi.importActual<typeof import("@/lib/middleware/community-actor")>("@/lib/middleware/community-actor",@@ -76,9 +59,6 @@ function req(headers: Record<string, string> = {}): NextRequest {headers,})}--// params.id = the PATH channel id (routing anchor only, NEVER trusted for-// authz). params.attachmentId = the authoritative id.const ctx = (attachmentId: string | undefined = "att_1", id = "c1") =>({ params: { id, attachmentId } }) as any@@ -105,17 +85,12 @@ const r2Object = (over: Record<string, unknown> = {}, bytes = new Uint8Array(10)})function allowPersistedHuman(row = persistedRow()): void {- mockGetAttachmentById.mockResolvedValue(row)- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })- mockGetChannelType.mockResolvedValue("text")- mockRequireChannelMember.mockResolvedValue({ ok: true, value: {} })+ mockGetReadableAttachmentById.mockResolvedValue(row)}describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {beforeEach(() => {vi.clearAllMocks()- mockRequireChannelMember.mockResolvedValue({ ok: true, value: {} })- mockRequireDMAccess.mockResolvedValue({ ok: true, value: {} })})it("404 when attachmentId is missing", async () => {@@ -125,36 +100,23 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {})it("404 when the id doesn't exist (bot)", async () => {- mockGetAttachmentById.mockResolvedValue(null)+ mockGetReadableAttachmentById.mockResolvedValue(null)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(404)expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(await res.json()).toEqual({ error: "attachment not found" })})-- // ⚠ CONFUSED-DEPUTY — the top red line. The gate resolves the row's OWN- // channel (row.targetId → row.messageId → message.channelId), NOT the path- // `[id]`. A caller who IS a member of the path channel "c1" but NOT of the- // row's real channel must still 404. We prove it by making the membership- // gate observe the ROW's channel id, and by returning not-a-member there.it("authorizes from the ROW's channel, not the path id — member of path-c1 but not row-channel → 404", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow())- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })- mockGetChannelType.mockResolvedValue("text")- mockRequireChannelMember.mockResolvedValue({ ok: false, status: 403, error: "not a member" })+ mockGetReadableAttachmentById.mockResolvedValue(null)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx("att_1", "c1"))expect(res.status).toBe(404)expect(res.headers.get("Cache-Control")).toBe("private, no-store")- // The membership gate was called with the ROW's message channel, not "c1".- expect(mockRequireChannelMember).toHaveBeenCalledWith({}, "c_real", "bot_1")- // No path-id was consulted for authz.- expect(mockRequireChannelMember).not.toHaveBeenCalledWith({}, "c1", expect.anything())expect(mockR2Get).not.toHaveBeenCalled()})it("404 (not 403) when a pending row belongs to another actor — enumeration-safe", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "other" }))+ mockGetReadableAttachmentById.mockResolvedValue(null)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(404)expect(res.headers.get("Cache-Control")).toBe("private, no-store")@@ -163,7 +125,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {})it("bot: pending row owned by the requesting bot round-trips (200 + X-Alook-Filename)", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))mockR2Get.mockResolvedValue(r2Object())const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(200)@@ -176,7 +138,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {it("bot: ignores Range and preserves the full-download protocol", async () => {const bytes = Uint8Array.from({ length: 10 }, (_, index) => index)- mockGetAttachmentById.mockResolvedValue(persistedRow({+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow({messageId: null,uploaderId: "bot_1",filename: "clip.mp4",@@ -195,7 +157,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {})it("bot: percent-encodes non-ASCII filenames per RFC 5987", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1", filename: "图表.png" }))+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1", filename: "图表.png" }))mockR2Get.mockResolvedValue(r2Object())const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(200)@@ -206,10 +168,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {})it("human: persisted image on a channel the user is a member of → 200 inline + immutable cache, no X-Alook-Filename", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow())- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })- mockGetChannelType.mockResolvedValue("text")- mockRequireChannelMember.mockResolvedValue({ ok: true, value: {} })+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow())mockR2Get.mockResolvedValue(r2Object())const res = await GET(req(), ctx()) // no crk_ → human armexpect(res.status).toBe(200)@@ -217,14 +176,11 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {expect(res.headers.get("Content-Type")).toBe("image/png")expect(res.headers.get("Content-Disposition")).toBe("inline")expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")- // Human arm never emits the bot download header.expect(res.headers.get("X-Alook-Filename")).toBeNull()})it("human: non-image → attachment; Content-Disposition carries the filename", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow({ contentType: "application/pdf", filename: "doc.pdf" }))- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })- mockGetChannelType.mockResolvedValue("text")+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow({ contentType: "application/pdf", filename: "doc.pdf" }))mockR2Get.mockResolvedValue(r2Object({ httpMetadata: { contentType: "application/pdf" } }))const res = await GET(req(), ctx())expect(res.status).toBe(200)@@ -366,29 +322,25 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png")})- it("routes a DM-scoped row through requireDMAccess (block gate), not requireChannelMember", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow())- mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "dm_1" })- mockGetChannelType.mockResolvedValue("dm")- mockRequireDMAccess.mockResolvedValue({ ok: true, value: {} })+ it("uses the shared actor-scoped file query on downloads", async () => {+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow())mockR2Get.mockResolvedValue(r2Object())const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(200)expect(res.headers.get("Vary")).toBe("Authorization")- expect(mockRequireDMAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")- expect(mockRequireChannelMember).not.toHaveBeenCalled()+ expect(mockGetReadableAttachmentById).toHaveBeenCalledWith({}, "att_1", "bot_1")})it("502 when the row exists but R2 has no object (infra drift, not enumeration)", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))mockR2Get.mockResolvedValue(null)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(502)expect(res.headers.get("Cache-Control")).toBe("private, no-store")})- it("getAttachmentById throws → 500 JSON envelope (no binary body leak)", async () => {- mockGetAttachmentById.mockRejectedValueOnce(new Error("d1_transient"))+ it("getReadableAttachmentById throws → 500 JSON envelope (no binary body leak)", async () => {+ mockGetReadableAttachmentById.mockRejectedValueOnce(new Error("d1_transient"))const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(500)expect(res.headers.get("Cache-Control")).toBe("private, no-store")@@ -396,7 +348,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {})it("bot: obj.arrayBuffer() throws mid-read → 500 JSON envelope, NOT a truncated 200", async () => {- mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))+ mockGetReadableAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1" }))mockR2Get.mockResolvedValue(r2Object({arrayBuffer: async () => {diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.tsindex 96e19bcba..02bc27e5c 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts@@ -1,7 +1,7 @@import { contentDisposition, encodeRfc5987 } from "@/lib/content-disposition"import { NextResponse, type NextRequest } from "next/server"import { createLogger } from "@alook/shared"-import { getDb } from "@/lib/db"+import { getPrimaryDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { authorizeAttachment } from "@/lib/community/attachment-authorization"@@ -45,14 +45,7 @@ function parseByteRange(value: string, size: number): ParsedByteRange | null {* - bot/CLI (crk_ bearer) → raw body + `X-Alook-Filename` (RFC 5987), the* shape the daemon `callDownload` buffers and writes to disk.*- * ⚠ CONFUSED-DEPUTY (top red line, Aigneis ② / Blondie): authorization is- * derived from the ATTACHMENT ROW's OWN channel (attachmentId → row →- * row.messageId → message.channelId → membership), NEVER from the path `[id]`.- * The `[id]` segment is a routing anchor only; a member of channel A must not- * reach an attachment of channel B by putting A's id in the path. The old flat- * `attachmentDownload` did this correctly — the fold does not regress it.- *- * Enumeration-safe: every "you can't have this" path (pending non-owner,+ * Enumeration-safe: every "you can't have this" path (unreadable file,* not-a-member, genuine miss) returns the SAME 404. A distinct 502 fires only* when the DB row exists but R2 has drifted (infra fault, not a user-facing* gate). Response FORM forks by actor; the authz core is identical.@@ -65,9 +58,8 @@ export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequconst userId = ctx.actor.userIdtry {- const db = getDb(ctx.env.DB)+ const db = getPrimaryDb(ctx.env.DB)- // Authorize from the ROW's own channel — never trust the path `[id]`.const authz = await authorizeAttachment(ctx.actor, db, attachmentId)if (!authz.ok) {// Enumeration-safe: every deny is an indistinguishable 404.diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.tsindex ff57cd157..6f553c492 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts@@ -4,7 +4,7 @@ import { NextRequest } from "next/server"const mockAuthorizeAttachment = vi.fn()const mockR2Get = vi.fn()-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))vi.mock("@/lib/community/attachment-authorization", () => ({authorizeAttachment: (...args: unknown[]) => mockAuthorizeAttachment(...args),}))diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.tsindex f1810073a..3878b2f92 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts@@ -1,6 +1,6 @@import { NextResponse, type NextRequest } from "next/server"import { createLogger } from "@alook/shared"-import { getDb } from "@/lib/db"+import { getPrimaryDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { authorizeAttachment } from "@/lib/community/attachment-authorization"@@ -15,7 +15,7 @@ export const GET = withPrivateMediaCache(withCommunityActor(async (_req: NextReq}try {- const authz = await authorizeAttachment(ctx.actor, getDb(ctx.env.DB), attachmentId)+ const authz = await authorizeAttachment(ctx.actor, getPrimaryDb(ctx.env.DB), attachmentId)if (!authz.ok || authz.row.thumbnailR2Key === null) {return NextResponse.json({ error: "attachment not found" }, { status: 404 })}diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.tsindex 717da5814..285e59811 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts@@ -37,7 +37,7 @@ const mockGetDM = vi.fn()const mockGetDMBetween = vi.fn()const mockGetDMPeer = vi.fn()const mockAreFriends = vi.fn()-const mockCreatePendingAttachment = vi.fn()+const mockCreateAttachment = vi.fn()const mockLogError = vi.fn()vi.mock("@alook/shared", async () => {@@ -69,7 +69,7 @@ vi.mock("@alook/shared", async () => {areFriends: (...a: unknown[]) => mockAreFriends(...a),},communityAttachment: {- createPendingAttachment: (...a: unknown[]) => mockCreatePendingAttachment(...a),+ createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),},},}@@ -101,7 +101,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacmockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude", isActive: true })- mockCreatePendingAttachment.mockResolvedValue({+ mockCreateAttachment.mockResolvedValue({id: "att_1",filename: "hi.png",contentType: "image/png",@@ -123,9 +123,22 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacexpect(res.status).toBe(401)})- it("400 when target query param is missing", async () => {+ it("accepts target-free upload with the existing response and uploader identity", async () => {const res = await POST(botReq(null, { Authorization: "Bearer crk_abc" }), botCtx)- expect(res.status).toBe(400)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ id: "att_1", filename: "hi.png", contentType: "image/png", size: 10, hasThumbnail: false })+ expect(mockResolveServerByNameForMember).not.toHaveBeenCalled()+ expect(mockCreateAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({ uploaderId: "bot_1" }))+ })++ it("rejects a target-free upload without authentication", async () => {+ expect((await POST(botReq(null), botCtx)).status).toBe(401)+ expect(mockHandleAttachmentUpload).not.toHaveBeenCalled()+ })++ it("preserves rejection of an explicitly empty legacy target", async () => {+ expect((await POST(botReq("", { Authorization: "Bearer crk_abc" }), botCtx)).status).toBe(400)+ expect(mockHandleAttachmentUpload).not.toHaveBeenCalled()})it("returns id + filename + contentType + size — no url, no r2Key", async () => {@@ -150,17 +163,10 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacexpect(body.r2Key).toBeUndefined()// Uploader tag threaded to the R2 primitive; the resolved id is used (not// the placeholder path id).- expect(mockHandleAttachmentUpload).toHaveBeenCalledWith(- expect.anything(),- expect.anything(),- "channel",- "c1",- { uploader: "bot", uploaderUserId: "bot_1" },- )+ expect(mockHandleAttachmentUpload).toHaveBeenCalledWith(expect.anything(), expect.anything())expect(mockGetPrimaryDb).toHaveBeenCalledOnce()- expect(mockCreatePendingAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({+ expect(mockCreateAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({uploaderId: "bot_1",- targetId: "c1",r2Key: "channel/c1/uuid/hi.png",}))})@@ -179,7 +185,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacexpect(res.status).toBe(403)expect(await res.json()).toEqual({ error: "accepted friendship required" })expect(mockHandleAttachmentUpload).not.toHaveBeenCalled()- expect(mockCreatePendingAttachment).not.toHaveBeenCalled()+ expect(mockCreateAttachment).not.toHaveBeenCalled()})it("persists thumbnail key and dimensions, returning hasThumbnail true", async () => {@@ -200,28 +206,28 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac})const response = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(await response.json()).toMatchObject({ hasThumbnail: true })- expect(mockCreatePendingAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({+ expect(mockCreateAttachment).toHaveBeenCalledWith(primaryDb, expect.objectContaining({thumbnailR2Key: "channel/c1/uuid/hi.png.thumbnail.jpg",width: 640,height: 480,}))})- it("createPendingAttachment throws → 500 JSON envelope, R2 delete fired with r2Key", async () => {+ it("createAttachment throws → 500 JSON envelope, shared R2 content preserved", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1", serverId: "srv_1", parentChannelId: null },])mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })- mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1_transient"))+ mockCreateAttachment.mockRejectedValueOnce(new Error("d1_transient"))const res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(500)expect(await res.json()).toEqual({ error: "internal error", code: "internal" })- expect(mockR2Delete).toHaveBeenCalledWith("channel/c1/uuid/hi.png")+ expect(mockR2Delete).not.toHaveBeenCalled()})- it("D1 failure after a thumbnail upload deletes both objects together", async () => {+ it("D1 failure preserves original and thumbnail shared objects", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1", serverId: "srv_1", parentChannelId: null },@@ -235,46 +241,9 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attaccontentType: "image/png",size: 10,})- mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))+ mockCreateAttachment.mockRejectedValueOnce(new Error("d1"))expect((await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)).status).toBe(500)- expect(mockR2Delete).toHaveBeenCalledWith(["original-key", "thumbnail-key"])- })-- it("redacts object keys when compensation cleanup also fails", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])- mockResolveChannelByNameForMember.mockResolvedValue([- { id: "c1", serverId: "srv_1", parentChannelId: null },- ])- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })- mockHandleAttachmentUpload.mockResolvedValue({- ok: true,- r2Key: "secret-original-key",- thumbnailR2Key: "secret-thumbnail-key",- filename: "hi.png",- contentType: "image/png",- size: 10,- })- mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))- mockR2Delete.mockRejectedValueOnce(new Error("secret provider detail"))-- const response = await POST(- botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }),- botCtx,- )-- expect(response.status).toBe(500)- const cleanupLog = mockLogError.mock.calls.find(- ([event]) => event === "attachment_route_r2_cleanup_failed",- )- expect(cleanupLog?.[1]).toEqual({- route: "channels/[id]/attachments",- actor: "bot",- objectCount: 2,- errorCategory: "Error",- })- expect(JSON.stringify(cleanupLog)).not.toContain("secret-original-key")- expect(JSON.stringify(cleanupLog)).not.toContain("secret-thumbnail-key")- expect(JSON.stringify(cleanupLog)).not.toContain("secret provider detail")+ expect(mockR2Delete).not.toHaveBeenCalled()})it("pre-R2 throw (resolveTargetForMember errors) → 500 JSON, R2 delete NOT called", async () => {@@ -298,7 +267,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attacconst res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)expect(res.status).toBe(413)- expect(mockCreatePendingAttachment).not.toHaveBeenCalled()+ expect(mockCreateAttachment).not.toHaveBeenCalled()})})@@ -331,6 +300,6 @@ describe("POST /api/community/channels/[id]/attachments — human arm (re-homes// The human arm forwards the id-in-path so the shared trunk resolves surface.expect(args[1]).toMatchObject({ userId: "u1", params: { id: "c1" } })// Bot-only pending-row insert never runs on the human arm.- expect(mockCreatePendingAttachment).not.toHaveBeenCalled()+ expect(mockCreateAttachment).not.toHaveBeenCalled()})})diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.tsindex 27e5314de..8d67d9ce5 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.ts@@ -8,7 +8,6 @@ import {requireDMCommunicationAccess,} from "@/lib/community/permissions"import { handleAttachmentUpload, runAttachmentUpload } from "@/lib/community/upload"-import { communityMediaCleanupErrorCategory } from "@/lib/community/community-media-cleanup"const log = createLogger({ service: "community-attachments-upload" })@@ -17,24 +16,6 @@ const log = createLogger({ service: "community-attachments-upload" })// which the bot arm ignores — it resolves the ref itself. A human/web caller// puts the real channelId in the path. Mirrors the channels/[id]/members// dual-actor door.-/**- * POST /api/community/channels/[id]/attachments — the canonical- * attachment-upload door. Dual-actor (route/disc trunk — folds the bot- * `attachmentUpload` verb + re-homes the human `channels/[id]/upload` route):- * - human/web (id-in-path) → `runAttachmentUpload`: multipart file →- * surface-derived kind → R2 put; returns the pre-refactor carrier shape- * `{ url, filename, contentType, size }` (the `/media/<key>` URL the- * composer echoes back on send). The composer switches to reserve-by-id in- * step (b); until then the human upload→send round-trip stays key-carried.- * - bot/CLI (ref-in-query) → resolve `?target=<ref>` member-scoped, gate- * write access identical to `send`, upload, then reserve a PENDING row- * (messageId = NULL) and return `{ id, filename, contentType, size }` —- * the bot holds the id and passes it to `send` later.- *- * Response FORM forks by the credential actor (never a field). The bot arm is- * byte-identical to the old flat `attachmentUpload` route; the human arm- * delegates to the same shared trunk the old `channels/[id]/upload` route did.- */export const POST = withCommunityActor(async (req: NextRequest, ctx) => {if (ctx.actor.kind === "bot") {return handleBotAttachmentUpload(req, ctx)@@ -51,13 +32,6 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {})})-/**- * Bot upload arm. Body unchanged from the old flat `attachmentUpload` route- * except that the ref arrives via `?target=` while the path carries the- * `resolve` placeholder (the door is now id-in-path for humans). Best-effort R2- * cleanup on a D1-throw so no orphan blob is left when the pending-row insert- * fails.- */async function handleBotAttachmentUpload(req: NextRequest,ctx: { env: Env; actor: CommunityActor },@@ -69,50 +43,28 @@ async function handleBotAttachmentUpload(if (!gate0.ok) return gate0.responseconst botUserId = gate0.bot.userId- // Track any R2 blob written before the D1 insert throws so the catch below- // can best-effort delete it. Hoisted here so the try/catch can see it.- let r2KeysToCleanUp: string[] = []-try {- const target = req.nextUrl.searchParams.get("target")- if (!target) {- return NextResponse.json({ error: "missing target query param" }, { status: 400 })- }-- // Resolve and authorize against primary before writing R2/D1 so a recent- // unfriend/block cannot be bypassed through a lagging replica.const db = getPrimaryDb(ctx.env.DB)-- const resolved = await resolveTargetForMember(db, botUserId, target)- if ("error" in resolved) return resolveErrorResponse(resolved)-- let kind: "channel" | "dm"- let targetId: string- if (resolved.kind === "dm") {- const gate = await requireDMCommunicationAccess(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- kind = "dm"- targetId = resolved.channelId- } else {- const gate = await requireChannelMember(db, resolved.channelId, botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- kind = "channel"- targetId = resolved.channelId+ const target = req.nextUrl.searchParams.get("target")+ if (target !== null) {+ if (!target) return NextResponse.json({ error: "missing target query param" }, { status: 400 })+ // Legacy callers retain their existing primary target authorization.+ const resolved = await resolveTargetForMember(db, botUserId, target)+ if ("error" in resolved) return resolveErrorResponse(resolved)+ if (resolved.kind === "dm") {+ const gate = await requireDMCommunicationAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ }}- const result = await handleAttachmentUpload(req, ctx.env, kind, targetId, {- uploader: "bot",- uploaderUserId: botUserId,- })+ const result = await handleAttachmentUpload(req, ctx.env)if (!result.ok) return result.response- // R2 blob is committed — remember its key so the D1-throw path can- // compensate.- r2KeysToCleanUp = [result.r2Key, ...(result.thumbnailR2Key ? [result.thumbnailR2Key] : [])]-- const row = await queries.communityAttachment.createPendingAttachment(db, {+ const row = await queries.communityAttachment.createAttachment(db, {uploaderId: botUserId,- targetId,r2Key: result.r2Key,thumbnailR2Key: result.thumbnailR2Key,filename: result.filename,@@ -130,26 +82,9 @@ async function handleBotAttachmentUpload(hasThumbnail: result.thumbnailR2Key !== null,})} catch (err) {- let r2KeyCleaned = false- if (r2KeysToCleanUp.length > 0) {- try {- await ctx.env.COMMUNITY_MEDIA.delete(- r2KeysToCleanUp.length === 1 ? r2KeysToCleanUp[0]! : r2KeysToCleanUp,- )- r2KeyCleaned = true- } catch (cleanupErr) {- log.error("attachment_route_r2_cleanup_failed", {- route: "channels/[id]/attachments",- actor: "bot",- objectCount: r2KeysToCleanUp.length,- errorCategory: communityMediaCleanupErrorCategory(cleanupErr),- })- }- }log.error("attachment_route_failure", {route: "channels/[id]/attachments",botUserId,- r2KeyCleaned,cause: err instanceof Error ? err.stack ?? err.message : String(err),})return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.tsindex f85f3d5d9..e688dd6d9 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts@@ -70,16 +70,8 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {ALTER TABLE user ADD COLUMN email TEXT;ALTER TABLE user ADD COLUMN image TEXT;ALTER TABLE user ADD COLUMN avatarVersion INTEGER DEFAULT 0;- ALTER TABLE community_attachment ADD COLUMN filename TEXT DEFAULT 'a.png';- ALTER TABLE community_attachment ADD COLUMN r2_key TEXT;- ALTER TABLE community_attachment ADD COLUMN thumbnail_r2_key TEXT;- ALTER TABLE community_attachment ADD COLUMN content_type TEXT;- ALTER TABLE community_attachment ADD COLUMN size INTEGER;- ALTER TABLE community_attachment ADD COLUMN width INTEGER;- ALTER TABLE community_attachment ADD COLUMN height INTEGER;- ALTER TABLE community_attachment ADD COLUMN created_at TEXT;CREATE TABLE community_bot_daily_activity (bot_id TEXT NOT NULL, day TEXT NOT NULL, handled_count INTEGER NOT NULL DEFAULT 0, sent_count INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(bot_id, day));- INSERT INTO community_attachment(id, uploader_id, target_id) VALUES ('a', 'author', 'channel');+ INSERT INTO community_attachment(id, uploader_id, r2_key, filename, created_at) VALUES ('a', 'author', 'original', 'a.png', 'now');`)})afterEach(() => fixture.sqlite.close())@@ -100,7 +92,7 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {expect(bodies[0].message.id).toBe(bodies[1].message.id)expect(bodies.filter((body) => body.deduped)).toHaveLength(1)expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_message").get()).toEqual({ count: 1 })- expect(fixture.sqlite.prepare("SELECT message_id FROM community_attachment").get()).toEqual({ message_id: bodies[0].message.id })+ expect(fixture.sqlite.prepare("SELECT message_id FROM community_message_attachment").get()).toEqual({ message_id: bodies[0].message.id })expect(dispatchCommittedMessage).toHaveBeenCalledOnce()if (kind === "bot") expect(fixture.sqlite.prepare("SELECT sent_count FROM community_bot_daily_activity").get()).toEqual({ sent_count: 1 })})@@ -114,7 +106,8 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {expect(bodies[0].threadId).toBe(bodies[1].threadId)expect(bodies[0].threadId).toBeTruthy()expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_channel WHERE type='thread'").get()).toEqual({ count: 1 })- expect(fixture.sqlite.prepare("SELECT target_id, message_id FROM community_attachment").get()).toEqual({ target_id: bodies[0].threadId, message_id: null })+ expect(fixture.sqlite.prepare("SELECT id FROM community_attachment").get()).toEqual({ id: "a" })+ expect(fixture.sqlite.prepare("SELECT * FROM community_message_attachment").all()).toEqual([])expect(fixture.sqlite.prepare("SELECT sent_count FROM community_bot_daily_activity").get()).toEqual({ sent_count: 1 })})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.tsindex 54d1c40fc..fb647a16c 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts@@ -14,7 +14,6 @@ const mockRequireMessageSurfaceAccess = vi.fn()const mockGetLatestSeqForScope = vi.fn()const mockHasDeliverableUnreadForAgentScope = vi.fn()const mockGetReadState = vi.fn()-const mockFindPendingAttachmentsForSender = vi.fn()const mockGetCommunityMessageReplay = vi.fn()vi.mock("@alook/shared", async () => {@@ -36,7 +35,6 @@ vi.mock("@alook/shared", async () => {},communityAttachment: {...actual.queries.communityAttachment,- findPendingAttachmentsForSender: (...args: unknown[]) => mockFindPendingAttachmentsForSender(...args),},},}@@ -94,7 +92,6 @@ describe("forum sends open a thread through the canonical message route", () =>mockGetLatestSeqForScope.mockResolvedValue(4)mockGetReadState.mockResolvedValue({ lastReadSeq: 4 })mockHasDeliverableUnreadForAgentScope.mockResolvedValue(false)- mockFindPendingAttachmentsForSender.mockResolvedValue([{ id: "attachment_1" }])})it("creates only the opener and structural child thread", async () => {@@ -106,7 +103,6 @@ describe("forum sends open a thread through the canonical message route", () =>parentChannelId: "forum_1",serverId: "server_1",body: { content: "Title" },- pendingAttachmentIdsToRebind: [],clientNonce: "command:opener",expectedSeq: 4,}))@@ -119,7 +115,6 @@ describe("forum sends open a thread through the canonical message route", () =>await POST(request({ channel: "/demo/forum", content: { text: "Title" }, attachments: ["attachment_1"] }), ctx)expect(mockCreateMessageWithThread).toHaveBeenCalledWith(expect.objectContaining({- pendingAttachmentIdsToRebind: ["attachment_1"],}))})@@ -142,7 +137,6 @@ describe("forum sends open a thread through the canonical message route", () =>expect(await response.json()).toEqual(expect.objectContaining({ deduped: true, threadId: "thread_1" }))expect(mockGetLatestSeqForScope).not.toHaveBeenCalled()expect(mockHasDeliverableUnreadForAgentScope).not.toHaveBeenCalled()- expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()})it("blocks an unread forum parent before opener or attachment side effects", async () => {@@ -163,7 +157,6 @@ describe("forum sends open a thread through the canonical message route", () =>latestSeq: 5,})expect(mockCreateMessageWithThread).not.toHaveBeenCalled()- expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()})it("returns the fresh forum waterline when the opener loses the seq CAS", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex dbc27711a..63229571e 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -29,8 +29,6 @@ const mockListMessagesAround = vi.fn()const mockListMessagesSince = vi.fn()const mockGetLatestMessageSeq = vi.fn()const mockListByMessageIds = vi.fn()-const mockFindPendingAttachmentsForSender = vi.fn()-const mockReserveAttachmentsForMessage = vi.fn()const mockListReactionsByMessageIds = vi.fn()const mockGetUserInternal = vi.fn()const mockGetDM = vi.fn()@@ -56,7 +54,6 @@ const mockAddThreadParticipant = vi.fn()const mockListThreadParticipantUserIds = vi.fn()const mockDeleteChannel = vi.fn()const mockHardDeleteMessage = vi.fn()-const mockRebindPendingAttachmentsToChild = vi.fn()const mockRecordFirstAgentReplyPersistedStatement = vi.fn(() => ({ kind: "first-agent-reply-statement" }))const mockFanOutToChannel = vi.fn()@@ -121,9 +118,6 @@ vi.mock("@alook/shared", async () => {},communityAttachment: {listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),- findPendingAttachmentsForSender: (...a: unknown[]) => mockFindPendingAttachmentsForSender(...a),- reserveAttachmentsForMessage: (...a: unknown[]) => mockReserveAttachmentsForMessage(...a),- rebindPendingAttachmentsToChild: (...a: unknown[]) => mockRebindPendingAttachmentsToChild(...a),},communityReaction: {listReactionsByMessageIds: (...a: unknown[]) => mockListReactionsByMessageIds(...a),@@ -281,7 +275,6 @@ describe("POST /api/community/channels/[id]/messages", () => {mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })mockCreateChannel.mockResolvedValue({ id: "thread_1", creatorId: "u1", createdAt: "t0", name: "thread" })mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "thread_1", creatorId: "u1", createdAt: "t0", name: "thread" })- mockRebindPendingAttachmentsToChild.mockResolvedValue(true)mockAddThreadParticipant.mockResolvedValue(null)mockListThreadParticipantUserIds.mockResolvedValue([])mockBroadcastToUserSafe.mockResolvedValue(undefined)@@ -321,8 +314,6 @@ describe("POST /api/community/channels/[id]/messages", () => {replay: mockGetMessageByAuthorAndNonce,duplicate: mockDuplicateCheck,rateLimit: mockCheckMessageRateLimit,- pendingAttachments: mockFindPendingAttachmentsForSender,- reserveAttachments: mockReserveAttachmentsForMessage,createChannel: mockCreateChannel,createMessage: mockCreateMessage,createMentions: mockCreateMentions,@@ -579,21 +570,14 @@ describe("POST /api/community/channels/[id]/messages", () => {})it("rejects more than MAX_ATTACHMENTS_PER_MESSAGE attachments with 400", async () => {- // Reserve-by-id: the human arm sends pending-row IDS. All ids validate as- // owned/attachable (findPending echoes them), so the over-cap rejection is- // the message handler's own MAX_ATTACHMENTS_PER_MESSAGE guard, not a- // validation miss.const attachmentIds = Array.from({ length: MAX_ATTACHMENTS_PER_MESSAGE + 1 }, (_, i) => `att_${i}`)- mockFindPendingAttachmentsForSender.mockResolvedValue(attachmentIds.map((id) => ({ id })))const res = await POST(postReq({ content: "ok", attachments: attachmentIds }), ctx)expect(res.status).toBe(400)expect(mockCreateMessage).not.toHaveBeenCalled()})- it("reserve-by-id: validates the pending ids (uploader+target) then passes attachmentIds to the handler", async () => {- mockFindPendingAttachmentsForSender.mockResolvedValue([{ id: "att_1" }, { id: "att_2" }])+ it("passes reusable attachment IDs to the atomic message handler", async () => {mockCreateMessage.mockResolvedValue({ id: "m_new" })- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1", "att_2"])mockListByMessageIds.mockResolvedValue([])const res = await POST(postReq({ content: "pics", attachments: ["att_1", "att_2"] }), ctx)expect(res.status).toBe(201)@@ -602,9 +586,9 @@ describe("POST /api/community/channels/[id]/messages", () => {}))})- it("reserve-by-id confused-deputy guard: a foreign/stolen pending id (count mismatch) → 400, no message", async () => {+ it("an atomic missing-file conflict returns 400 without fanout", async () => {mockCreateMessage.mockRejectedValueOnce(new Error("NOT NULL constraint failed: community_message.content"))- const res = await POST(postReq({ content: "steal", attachments: ["att_mine", "att_theirs"] }), ctx)+ const res = await POST(postReq({ content: "file", attachments: ["att_existing", "att_missing"] }), ctx)expect(res.status).toBe(400)expect(mockFanOutToChannel).not.toHaveBeenCalled()})@@ -721,8 +705,6 @@ describe("POST /api/community/channels/[id]/messages", () => {it("human full-command replay hydrates bound attachments before pending validation", async () => {const stored = { id: "a1", targetId: "c1", filename: "x.png", contentType: "image/png", size: 10, width: 1, height: 1 }- mockFindPendingAttachmentsForSender.mockResolvedValueOnce([stored])- mockReserveAttachmentsForMessage.mockResolvedValueOnce(["a1"])mockListByMessageIds.mockResolvedValue([stored])mockGetMessageByAuthorAndNonce.mockResolvedValueOnce(null)@@ -735,7 +717,6 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(first.status).toBe(201)expect(replay.status).toBe(200)expect(await replay.json()).toEqual(expect.objectContaining({ deduped: true }))- expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()expect(mockCreateMessage).toHaveBeenCalledTimes(1)expect(mockCreateMessage.mock.calls[0][1].attachmentIds).toEqual(["a1"])})@@ -955,8 +936,6 @@ describe("POST /api/community/channels/[id]/messages", () => {const row = { ...await mockGetMessage(), authorId: "bot_1", clientNonce: "cmd:reply" }mockResolveServerByNameForMember.mockResolvedValue([{ id: "s1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1", serverId: "s1", type: "text", parentChannelId: null }])- mockFindPendingAttachmentsForSender.mockResolvedValueOnce([stored])- mockReserveAttachmentsForMessage.mockResolvedValueOnce(["a1"])mockListByMessageIds.mockResolvedValue([stored])mockGetMessageByAuthorAndNonce.mockResolvedValueOnce(null)@@ -972,7 +951,6 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(first.status).toBe(200)expect(replay.status).toBe(200)expect(await replay.json()).toEqual(expect.objectContaining({ state: "sent", deduped: true }))- expect(mockFindPendingAttachmentsForSender).not.toHaveBeenCalled()expect(mockCreateMessage).toHaveBeenCalledTimes(1)expect(mockHasDeliverableUnreadForAgentScope).toHaveBeenCalledTimes(1)})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex b63709453..c20edf990 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -271,7 +271,6 @@ async function handleHumanSend(parentChannelId: target.channelId,serverId: target.serverId,body: { content, mentionType: forumBody.mentionType },- pendingAttachmentIdsToRebind: attachmentIds,clientNonce,source: "web",})@@ -347,7 +346,6 @@ async function handleBotSend(parentChannelId: channelId,serverId,body: { content: body.content.text },- pendingAttachmentIdsToRebind: body.attachments,clientNonce: body.nonce,...(expectedSeq !== undefined ? { expectedSeq } : {}),source: "cli",diff --git a/src/web/src/lib/community/attachment-authorization.test.ts b/src/web/src/lib/community/attachment-authorization.test.tsdeleted file mode 100644index 601bbfc77..000000000--- a/src/web/src/lib/community/attachment-authorization.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest"--const getAttachmentById = vi.fn()-const getMessage = vi.fn()-const getChannelType = vi.fn()-const requireChannelMember = vi.fn()-const requireDMAccess = vi.fn()--vi.mock("@alook/shared", () => ({- queries: {- communityAttachment: { getAttachmentById: (...args: unknown[]) => getAttachmentById(...args) },- communityMessage: { getMessage: (...args: unknown[]) => getMessage(...args) },- communityChannel: { getChannelType: (...args: unknown[]) => getChannelType(...args) },- },-}))-vi.mock("./permissions", () => ({- requireChannelMember: (...args: unknown[]) => requireChannelMember(...args),- requireDMAccess: (...args: unknown[]) => requireDMAccess(...args),-}))--import { authorizeAttachment } from "./attachment-authorization"--const db = {} as any-const actor = { kind: "human", userId: "u1", email: "[email protected]", isBot: false } as any-const row = { id: "a1", messageId: "m1", uploaderId: "u2", targetId: "routing-only" }--describe("authorizeAttachment", () => {- beforeEach(() => vi.clearAllMocks())-- it("allows only the uploader for a pending row", async () => {- getAttachmentById.mockResolvedValue({ ...row, messageId: null, uploaderId: "u1" })- expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(true)- getAttachmentById.mockResolvedValue({ ...row, messageId: null, uploaderId: "u2" })- expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(false)- })-- it("authorizes persisted channel rows from the message channel", async () => {- getAttachmentById.mockResolvedValue(row)- getMessage.mockResolvedValue({ id: "m1", channelId: "actual-channel" })- getChannelType.mockResolvedValue("text")- requireChannelMember.mockResolvedValue({ ok: true })- expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(true)- expect(requireChannelMember).toHaveBeenCalledWith(db, "actual-channel", "u1")- })-- it("uses the DM access gate for persisted DM rows", async () => {- getAttachmentById.mockResolvedValue(row)- getMessage.mockResolvedValue({ id: "m1", channelId: "dm1" })- getChannelType.mockResolvedValue("dm")- requireDMAccess.mockResolvedValue({ ok: false })- expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(false)- expect(requireDMAccess).toHaveBeenCalledWith(db, "dm1", "u1")- expect(requireChannelMember).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/lib/community/attachment-authorization.ts b/src/web/src/lib/community/attachment-authorization.tsindex abb41eb5e..04c18c4f6 100644--- a/src/web/src/lib/community/attachment-authorization.ts+++ b/src/web/src/lib/community/attachment-authorization.ts@@ -1,31 +1,7 @@import { queries, type Database } from "@alook/shared"import type { CommunityActor } from "@/lib/middleware/community-actor"-import { requireChannelMember, requireDMAccess } from "./permissions"-type AuthzOk = {- ok: true- row: NonNullable<Awaited<ReturnType<typeof queries.communityAttachment.getAttachmentById>>>-}--/** Authorize solely from the attachment row; route target ids are never trusted. */-export async function authorizeAttachment(- actor: CommunityActor,- db: Database,- attachmentId: string,-): Promise<AuthzOk | { ok: false }> {- const userId = actor.userId- const row = await queries.communityAttachment.getAttachmentById(db, attachmentId)- if (!row) return { ok: false }-- if (row.messageId === null) {- return row.uploaderId === userId ? { ok: true, row } : { ok: false }- }-- const message = await queries.communityMessage.getMessage(db, row.messageId)- if (!message) return { ok: false }- const channelType = await queries.communityChannel.getChannelType(db, message.channelId)- const gate = channelType === "dm"- ? await requireDMAccess(db, message.channelId, userId)- : await requireChannelMember(db, message.channelId, userId)- return gate.ok ? { ok: true, row } : { ok: false }+export async function authorizeAttachment(actor: CommunityActor, db: Database, attachmentId: string) {+ const row = await queries.communityAttachment.getReadableAttachmentById(db, attachmentId, actor.userId)+ return row ? { ok: true as const, row } : { ok: false as const }}diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.tsindex 8e8fb0d70..fb4f07828 100644--- a/src/web/src/lib/community/create-channels.test.ts+++ b/src/web/src/lib/community/create-channels.test.ts@@ -9,7 +9,6 @@ const mockFanOutToChannel = vi.fn()const mockBroadcastToUserSafe = vi.fn()const mockDeleteChannel = vi.fn()const mockListMessageAttachments = vi.fn()-const mockRebindPendingAttachmentsToChild = vi.fn()const mockGetMessage = vi.fn()const mockRequireChannelMember = vi.fn()@@ -48,7 +47,6 @@ vi.mock("@alook/shared", async () => {communityAttachment: {...actual.queries.communityAttachment,listMessageAttachments: (...a: unknown[]) => mockListMessageAttachments(...a),- rebindPendingAttachmentsToChild: (...a: unknown[]) => mockRebindPendingAttachmentsToChild(...a),},communityThread: {...actual.queries.communityThread,@@ -161,31 +159,19 @@ describe("createMessageWithThread — atomic message composition", () => {mockGetThreadChannelByParentMessage.mockReset().mockResolvedValue(thread)})- it("passes structure, pending attachments and activity to the same message write before broadcasting", async () => {+ it("passes structure, attachments and activity to the same message write before broadcasting", async () => {const broadcast = vi.fn()mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1" }, attachments: [], broadcast })const sent = { statement: "sent" }- const result = await createMessageWithThread({ ...input, expectedSeq: 8, pendingAttachmentIdsToRebind: ["a"], extraStatements: [sent] })+ const result = await createMessageWithThread({ ...input, expectedSeq: 8, attachmentIds: ["a"], extraStatements: [sent] })expect(mockCreateCommunityMessage).toHaveBeenCalledWith(expect.objectContaining({expectedSeq: 8, extraStatements: [sent],- forumThread: { id: expect.any(String), name: "Title", serverId: "s1", pendingAttachmentIds: ["a"] },+ forumThread: { id: expect.any(String), name: "Title", serverId: "s1" },}))expect(result).toEqual({ ok: true, message: { id: "msg_1" }, attachments: [], thread })expect(broadcast).not.toHaveBeenCalled()expect(mockFanOutToChannel).not.toHaveBeenCalled()expect(mockCreateChannel).not.toHaveBeenCalled()- expect(mockRebindPendingAttachmentsToChild).not.toHaveBeenCalled()- })-- it("rejects oversized pending attachments before creating a forum opener", async () => {- const result = await createMessageWithThread({- ...input,- pendingAttachmentIdsToRebind: Array.from({ length: 11 }, (_, i) => `attachment-${i}`),- })- expect(result).toEqual({ ok: false, status: 400, error: "too many attachments (max 10)" })- expect(mockCreateCommunityMessage).not.toHaveBeenCalled()- expect(mockGetThreadChannelByParentMessage).not.toHaveBeenCalled()- expect(mockFanOutToChannel).not.toHaveBeenCalled()})it("bounds explicit and content-derived thread names", async () => {@@ -195,13 +181,12 @@ describe("createMessageWithThread — atomic message composition", () => {expect(mockCreateCommunityMessage.mock.calls[1][0].forumThread.name).toBe("y".repeat(100))})- it("returns complete nonce replay without mutating pending attachments or broadcasting", async () => {+ it("returns complete nonce replay without mutating attachments or broadcasting", async () => {const attachments = [{ id: "a", thumbnailUrl: "/thumbnail" }]mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "msg_1" }, attachments, deduped: true })- const result = await createMessageWithThread({ ...input, clientNonce: "nonce", pendingAttachmentIdsToRebind: ["a"] })+ const result = await createMessageWithThread({ ...input, clientNonce: "nonce", attachmentIds: ["a"] })expect(result).toEqual({ ok: true, message: { id: "msg_1" }, attachments, thread, deduped: true })expect(mockFanOutToChannel).not.toHaveBeenCalled()- expect(mockRebindPendingAttachmentsToChild).not.toHaveBeenCalled()expect(mockAddThreadParticipants).not.toHaveBeenCalled()})diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.tsindex 7b705ba96..95ac32f5c 100644--- a/src/web/src/lib/community/create-channels.ts+++ b/src/web/src/lib/community/create-channels.ts@@ -4,7 +4,6 @@ import {isChannelType,channelCreation,MAX_CHANNEL_NAME_LENGTH,- MAX_ATTACHMENTS_PER_MESSAGE,MAX_CHANNEL_TOPIC_LENGTH,WS_EVENTS,slugify,@@ -307,16 +306,12 @@ export async function createMessageWithThread(params: {suppressBroadcast?: booleansuppressThreadFanout?: booleanattachmentIds?: string[]- pendingAttachmentIdsToRebind?: string[]clientNonce?: stringexpectedSeq?: numbersource?: "cli" | "daemon-http" | "web"extraStatements?: unknown[]}): Promise<CreateMessageWithThreadResult> {const { db, authorId, parentChannelId, serverId } = params- if ((params.pendingAttachmentIdsToRebind?.length ?? 0) > MAX_ATTACHMENTS_PER_MESSAGE) {- return { ok: false, status: 400, error: `too many attachments (max ${MAX_ATTACHMENTS_PER_MESSAGE})` }- }const content = typeof params.body.content === "string" ? params.body.content : ""const threadName = (params.threadName?.trim() || content.trim() || "thread").slice(0, MAX_CHANNEL_NAME_LENGTH)const created = await createCommunityMessage({@@ -336,7 +331,6 @@ export async function createMessageWithThread(params: {id: nanoid(),serverId,name: threadName,- pendingAttachmentIds: params.pendingAttachmentIdsToRebind ?? [],},})if (!created.ok) return { ok: false, status: created.status, error: created.error }diff --git a/src/web/src/lib/community/jev-send-dedup.test.ts b/src/web/src/lib/community/jev-send-dedup.test.tsindex a408b5e92..a0d84deaf 100644--- a/src/web/src/lib/community/jev-send-dedup.test.ts+++ b/src/web/src/lib/community/jev-send-dedup.test.ts@@ -6,7 +6,7 @@ vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return { ...actual, queries: { ...actual.queries, communityMessage: {...actual.queries.communityMessage, listRecentMessagesForDuplicateCheck: mocks.recent,- }, user: { ...actual.queries.user, getUserSelf: mocks.author }, communityAttachment: { findPendingAttachmentsForSender: mocks.pending, listByMessageIds: mocks.previous } } }+ }, user: { ...actual.queries.user, getUserSelf: mocks.author }, communityAttachment: { listByMessageIds: mocks.previous } } }})vi.mock("./jev-wake-gate", async () => {const actual = await vi.importActual<typeof import("./jev-wake-gate")>("./jev-wake-gate")diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 7cb3944e0..3fb35c5b2 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -6,8 +6,6 @@ const mockGetMessageByAuthorAndNonce = vi.fn()const mockGetMessageInScope = vi.fn()const mockHardDeleteMessage = vi.fn()const mockGetUserInternal = vi.fn()-const mockReserveAttachmentsForMessage = vi.fn()-const mockUnreserveAttachments = vi.fn()const mockListByMessageIds = vi.fn()const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()@@ -42,8 +40,6 @@ vi.mock("@alook/shared", async () => {hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),},communityAttachment: {- reserveAttachmentsForMessage: (...a: unknown[]) => mockReserveAttachmentsForMessage(...a),- unreserveAttachments: (...a: unknown[]) => mockUnreserveAttachments(...a),listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),},communityMember: {@@ -339,7 +335,6 @@ describe("createCommunityMessage — committed delivery handoff", () => {// reserved rows are re-read via listByMessageIds after the reserve. There is// no url-carried body path anymore — the caller passes attachmentIds.mockCreateMessage.mockResolvedValue({ id: "msg_1" })- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])mockListByMessageIds.mockResolvedValue([{id: "att_1",@@ -865,7 +860,6 @@ describe("createCommunityMessage — attachment reservation-first flow (agent paexpect(res).toEqual({ ok: false, status: 400, error: "attachment not found or not attachable to this target" })expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ attachmentIds: ["att_1", "att_2"] }))expect(mockHardDeleteMessage).not.toHaveBeenCalled()- expect(mockUnreserveAttachments).not.toHaveBeenCalled()expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()})@@ -882,8 +876,6 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa}),).rejects.toThrow("d1_transient")- expect(mockReserveAttachmentsForMessage).not.toHaveBeenCalled()- expect(mockUnreserveAttachments).not.toHaveBeenCalled()expect(mockHardDeleteMessage).not.toHaveBeenCalled()})@@ -903,13 +895,10 @@ describe("createCommunityMessage — attachment reservation-first flow (agent paif (res.ok) returnexpect(res.status).toBe(409)expect(res.error).toBe("seq_conflict")- expect(mockReserveAttachmentsForMessage).not.toHaveBeenCalled()- expect(mockUnreserveAttachments).not.toHaveBeenCalled()expect(mockHardDeleteMessage).not.toHaveBeenCalled()})it("attachment-only bot send (empty text) is NOT rejected by the empty-body guard", async () => {- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })mockListByMessageIds.mockResolvedValue([{@@ -939,7 +928,6 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa})it("happy path — reserved rows are projected as CreatedAttachment via listByMessageIds", async () => {- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })mockListByMessageIds.mockResolvedValue([{@@ -977,7 +965,6 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pathumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",}),])- expect(mockUnreserveAttachments).not.toHaveBeenCalled()})})diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 9b5226945..652b44f12 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -178,14 +178,6 @@ export async function createCommunityMessage(params: {* cards) opt in — they never mention anyone.*/skipMentions?: boolean- /**- * Reserve-by-id attachment path (the ONLY attachment path — human web and bot- * both use it, route/disc step 2b). Pending attachment ids the caller has- * already validated against (uploader, target). When present, the handler- * pre-mints the message id, reserves the pending rows in a single atomic- * UPDATE, then inserts the message — compensating unreserves on every failure- * path so no message row is ever committed with a partial attachment set.- */attachmentIds?: string[]/*** Do NOT run any WS side effect inline. Instead, on success, return a@@ -274,9 +266,6 @@ export async function createCommunityMessage(params: {// Reserve-by-id is the SINGLE attachment path (route/disc step 2b unified the// human composer onto the bot flow): every caller — human web AND bot — passes- // pre-uploaded pending-row ids via `attachmentIds`; the route already validated- // them against (uploader, target). There is no longer a url-carried inline- // attachment path.const attachmentIdCount = Array.isArray(attachmentIds) ? attachmentIds.length : 0if (attachmentIdCount > MAX_ATTACHMENTS_PER_MESSAGE) {return {diff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.tsindex 09b0d5634..538aa2c9e 100644--- a/src/web/src/lib/community/storage.test.ts+++ b/src/web/src/lib/community/storage.test.ts@@ -1,13 +1,11 @@import { describe, it, expect } from "vitest"import {- buildMediaKey,buildUserAvatarKey,buildUserAvatarObjectKey,buildBotAvatarKey,buildBotAvatarObjectKey,attachmentUrl,attachmentThumbnailUrl,- buildAttachmentThumbnailKey,ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,sanitizeAttachmentFilename,userAvatarUrl,@@ -125,14 +123,6 @@ describe("sanitizeAttachmentFilename", () => {})})-describe("buildMediaKey", () => {- it("emits keys with no leading slash and the sanitized filename component", () => {- const key = buildMediaKey("channel", "c1", "uuid", "../evil.png")- expect(key.startsWith("/")).toBe(false)- expect(key).toBe("channel/c1/uuid/__evil.png")- })-})-describe("isOwnedServerIconKey", () => {it("accepts exactly one non-empty suffix under the expected server", () => {expect(isOwnedServerIconKey("server-icon/s1/icon-a", "s1")).toBe(true)@@ -162,11 +152,7 @@ describe("attachment thumbnail addressing", () => {)})- it("uses a reserved suffix on the complete original key", () => {- expect(buildAttachmentThumbnailKey("channel/c1/id/thumbnail.jpg")).toBe(- "channel/c1/id/thumbnail.jpg.thumbnail.jpg",- )- })+})it("uses a private immutable cache policy for authorized attachment bytes", () => {diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.tsindex 9ef221f44..96491900c 100644--- a/src/web/src/lib/community/storage.ts+++ b/src/web/src/lib/community/storage.ts@@ -16,17 +16,6 @@ export function sanitizeAttachmentFilename(input: string): string {return cleaned.length > 255 ? cleaned.slice(0, 255) : cleaned}-/**- * Read/render URL for a persisted attachment, served by the canonical- * `GET /api/community/channels/{targetId}/attachments/{attachmentId}` door.- * Every read-side call site (`groupAttachments`, the reserve/incoming arms of- * the message-create handler) builds display URLs through this helper so the- * id-addressed attachment scheme lives in one place.- *- * The `{targetId}` path segment is a routing anchor only — the download door- * authorizes from the attachment ROW's own channel, never from the path — so a- * stale/forged targetId can't reach another row's bytes.- */export function attachmentUrl(targetId: string, attachmentId: string): string {return `/api/community/channels/${targetId}/attachments/${attachmentId}`}@@ -35,15 +24,6 @@ export function attachmentThumbnailUrl(targetId: string, attachmentId: string):return `${attachmentUrl(targetId, attachmentId)}/thumbnail`}-export function buildAttachmentThumbnailKey(originalKey: string): string {- return `${originalKey}.thumbnail.jpg`-}--// R2 storage key builders-export function buildMediaKey(type: "channel" | "dm" | "thread", id: string, fileId: string, filename: string): string {- return `${type}/${id}/${fileId}/${sanitizeAttachmentFilename(filename)}`-}-export function buildServerIconKey(serverId: string, fileId: string): string {return `server-icon/${serverId}/${fileId}`}diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.tsindex dde1f57b1..0962cc5fa 100644--- a/src/web/src/lib/community/upload.test.ts+++ b/src/web/src/lib/community/upload.test.ts@@ -19,7 +19,7 @@ vi.mock("@/lib/db", () => ({}))const mockGetChannelType = vi.fn()-const mockCreatePendingAttachment = vi.fn()+const mockCreateAttachment = vi.fn()const mockLogError = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -34,15 +34,12 @@ vi.mock("@alook/shared", async () => {},communityAttachment: {...actual.queries.communityAttachment,- createPendingAttachment: (...a: unknown[]) => mockCreatePendingAttachment(...a),+ createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),},},}})-// runAttachmentUpload now owns access + surface dispatch via-// requireMessageSurfaceCommunicationAccess (kind is DERIVED from its returned surface +-// channel.type, no separate getChannelType re-query). Mock it to drive each arm.const mockRequireMessageSurfaceCommunicationAccess = vi.fn()vi.mock("./permissions", () => ({requireMessageSurfaceCommunicationAccess: (...a: unknown[]) =>@@ -59,7 +56,13 @@ import {import { MAX_ATTACHMENT_SIZE_BYTES, MAX_SERVER_ICON_SIZE_BYTES } from "@alook/shared"function envWithR2(put: ReturnType<typeof vi.fn>, del = vi.fn().mockResolvedValue(undefined)) {- return { COMMUNITY_MEDIA: { put, delete: del } } as unknown as Env+ return { COMMUNITY_MEDIA: {+ put: async (key: string, body: File, options: { sha256?: string }) => {+ const result = await put(key, body, options)+ return result === undefined ? { size: body.size, checksums: { sha256: options?.sha256 ? Uint8Array.from(Buffer.from(options.sha256, "hex")).buffer : undefined } } : result+ },+ delete: del,+ } } as unknown as Env}/**@@ -70,16 +73,13 @@ function envWithR2(put: ReturnType<typeof vi.fn>, del = vi.fn().mockResolvedValufunction reqWithFile(file: unknown | null): NextRequest {const fd = new FormData()if (file) {- // FormData.set requires a real Blob; stash the test object on the- // FormData proxy directly instead.- ; (fd as unknown as { __file: unknown }).__file = file+ ; (fd as unknown as { __file: unknown }).__file = file}const req = new NextRequest("http://localhost/u", { method: "POST" })req.formData = (async () => {const real = new FormData()if (file) {- // get() on FormData looks up by key — we override to return our file.- Object.defineProperty(real, "get", {+ Object.defineProperty(real, "get", {value: (key: string) => (key === "file" ? file : null),})} else {@@ -112,8 +112,11 @@ function fakeFile(name: string, type: string, size: number) {name,type,size,- arrayBuffer: async () => new ArrayBuffer(0),- stream: () => new ReadableStream(),+ arrayBuffer: async () => new ArrayBuffer(size),+ stream() {+ const read = this.arrayBuffer()+ return new ReadableStream({ async start(controller) { controller.enqueue(new Uint8Array(await read)); controller.close() } })+ },}}@@ -164,27 +167,26 @@ function restartMarkerJpegFile() {describe("handleAttachmentUpload", () => {beforeEach(() => vi.clearAllMocks())- const USER_TAG = { uploader: "user" as const, uploaderUserId: "u1" }it("uploads a file under the size cap", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("hi.png", "image/png", 10)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put))expect(res.ok).toBe(true)if (!res.ok) return- expect(res.r2Key).toMatch(/^channel\/c1\/[0-9a-f-]+\/hi\.png$/)+ expect(res.r2Key).toMatch(/^attachments\/sha256\/[0-9a-f]{64}$/)expect(res.contentType).toBe("image/png")expect(res.size).toBe(10)expect(put).toHaveBeenCalledOnce()const [, , options] = put.mock.calls[0]- expect(options.customMetadata).toMatchObject({ uploader: "user" })+ expect(options).toMatchObject({ onlyIf: { etagDoesNotMatch: "*" }, sha256: expect.any(String) })})it("accepts an original-only image at the exact policy boundaries", async () => {const put = vi.fn().mockResolvedValue(undefined)const res = await handleAttachmentUpload(reqWithUpload(fakeFile("edge.png", "image/png", 256 * 1024), null, "720", "540"),- envWithR2(put), "channel", "c1", USER_TAG,+ envWithR2(put),)expect(res.ok).toBe(true)@@ -200,7 +202,7 @@ describe("handleAttachmentUpload", () => {])("rejects a missing required thumbnail proved by %s before either R2 put", async (_label, file, width, height) => {const put = vi.fn()const res = await handleAttachmentUpload(- reqWithUpload(file, null, width, height), envWithR2(put), "channel", "c1", USER_TAG,+ reqWithUpload(file, null, width, height), envWithR2(put),)expect(res.ok).toBe(false)@@ -210,27 +212,19 @@ describe("handleAttachmentUpload", () => {expect(put).not.toHaveBeenCalled()})- it("stores a validated JPEG thumbnail beside the original with matching provenance", async () => {+ it("stores a validated JPEG thumbnail with its own content key", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("hi.png", "image/png", 10)const thumbnail = fakeJpegFile()const res = await handleAttachmentUpload(- reqWithUpload(file, thumbnail), envWithR2(put), "channel", "c1", USER_TAG,+ reqWithUpload(file, thumbnail), envWithR2(put),)expect(res.ok).toBe(true)if (!res.ok) return- expect(res.thumbnailR2Key).toBe(`${res.r2Key}.thumbnail.jpg`)+ expect(res.thumbnailR2Key).toMatch(/^attachment-thumbnails\/sha256\/[0-9a-f]{64}$/)expect(res).toMatchObject({ width: 640, height: 480 })expect(put).toHaveBeenCalledTimes(2)- expect(put.mock.calls[0]?.[2]?.customMetadata).toMatchObject({ variant: "original" })- expect(put.mock.calls[1]).toEqual([- res.thumbnailR2Key,- thumbnail,- expect.objectContaining({- httpMetadata: { contentType: "image/jpeg" },- customMetadata: expect.objectContaining({ uploader: "user", variant: "thumbnail" }),- }),- ])+ expect(put.mock.calls[1]).toEqual([res.thumbnailR2Key, thumbnail, expect.objectContaining({ onlyIf: { etagDoesNotMatch: "*" } })])})it("rejects malformed supplied thumbnails before either R2 put", async () => {@@ -241,7 +235,7 @@ describe("handleAttachmentUpload", () => {}const res = await handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),- envWithR2(put), "channel", "c1", USER_TAG,+ envWithR2(put),)expect(res.ok).toBe(false)expect(put).not.toHaveBeenCalled()@@ -251,7 +245,7 @@ describe("handleAttachmentUpload", () => {const put = vi.fn()const res = await handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), sofOnlyJpegFile()),- envWithR2(put), "channel", "c1", USER_TAG,+ envWithR2(put),)expect(res.ok).toBe(false)@@ -286,7 +280,7 @@ describe("handleAttachmentUpload", () => {const put = vi.fn()const res = await handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),- envWithR2(put), "channel", "c1", USER_TAG,+ envWithR2(put),)expect(res.ok).toBe(false)@@ -299,7 +293,7 @@ describe("handleAttachmentUpload", () => {const put = vi.fn().mockResolvedValue(undefined)const res = await handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), restartMarkerJpegFile()),- envWithR2(put), "channel", "c1", USER_TAG,+ envWithR2(put),)expect(res.ok).toBe(true)@@ -310,7 +304,7 @@ describe("handleAttachmentUpload", () => {const put = vi.fn()const res = await handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), fakeJpegFile(721, 512)),- envWithR2(put), "channel", "c1", USER_TAG,+ envWithR2(put),)expect(res.ok).toBe(false)@@ -338,7 +332,7 @@ describe("handleAttachmentUpload", () => {])("rejects $label before either R2 put", async ({ file, thumbnail }) => {const put = vi.fn()const res = await handleAttachmentUpload(- reqWithUpload(file, thumbnail), envWithR2(put), "channel", "c1", USER_TAG,+ reqWithUpload(file, thumbnail), envWithR2(put),)expect(res.ok).toBe(false)if (res.ok) return@@ -346,58 +340,18 @@ describe("handleAttachmentUpload", () => {expect(put).not.toHaveBeenCalled()})- it.each([- { uploader: "user" as const, uploaderUserId: "u1" },- { uploader: "bot" as const, uploaderUserId: "bot_ada" },- ])("sanitizes $uploader original-compensation failures after a thumbnail put rejects", async (uploaderTag) => {- const thumbnailFailure = new Error("r2 thumbnail")- const put = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(thumbnailFailure)- const cleanupSecret = "provider-secret channel/c1/original.png"- const del = vi.fn().mockRejectedValueOnce(new TypeError(cleanupSecret))- const thumbnail = fakeJpegFile()- const upload = handleAttachmentUpload(- reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),- envWithR2(put, del), "channel", "c1", uploaderTag,- )-- await expect(upload).rejects.toBe(thumbnailFailure)- const originalKey = put.mock.calls[0]?.[0]- expect(originalKey).toMatch(/^channel\/c1\/[0-9a-f-]+\/hi\.png$/)- expect(del).toHaveBeenCalledTimes(1)- expect(del).toHaveBeenCalledWith(originalKey)- expect(mockLogError).toHaveBeenCalledTimes(1)- expect(mockLogError).toHaveBeenCalledWith("attachment_thumbnail_put_cleanup_failed", {- uploader: uploaderTag.uploader,- route: "channels/[id]/attachments",- phase: "thumbnail_put_original_compensation",- objectCount: 1,- errorCategory: "TypeError",- })- const serializedWarning = JSON.stringify(mockLogError.mock.calls)- expect(serializedWarning).not.toContain(cleanupSecret)- expect(serializedWarning).not.toContain(String(originalKey))- })-- it("stamps customMetadata.uploader=bot + bot_user_id when the caller is a bot", async () => {- const put = vi.fn().mockResolvedValue(undefined)- const file = fakeFile("hi.png", "image/png", 10)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", {- uploader: "bot",- uploaderUserId: "bot_ada",- })- expect(res.ok).toBe(true)- const [, , options] = put.mock.calls[0]- expect(options.customMetadata).toEqual({- uploader: "bot",- bot_user_id: "bot_ada",- variant: "original",- })+ it("does not delete shared original content when thumbnail creation fails", async () => {+ const failure = new Error("r2 thumbnail")+ const put = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(failure)+ const del = vi.fn()+ await expect(handleAttachmentUpload(reqWithUpload(fakeFile("hi.png", "image/png", 10), fakeJpegFile()), envWithR2(put, del))).rejects.toBe(failure)+ expect(del).not.toHaveBeenCalled()})it("passes a known-length File body to R2", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("hi.png", "image/png", 10)- await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ await handleAttachmentUpload(reqWithFile(file), envWithR2(put))expect(put).toHaveBeenCalledOnce()const [, body] = put.mock.calls[0]expect(body).toBe(file)@@ -408,7 +362,7 @@ describe("handleAttachmentUpload", () => {it("rejects when no file part is present (400)", async () => {const put = vi.fn()- const res = await handleAttachmentUpload(reqWithFile(null), envWithR2(put), "channel", "c1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(null), envWithR2(put))expect(res.ok).toBe(false)if (res.ok) returnexpect(res.response.status).toBe(400)@@ -418,7 +372,7 @@ describe("handleAttachmentUpload", () => {it("rejects oversize files with 413", async () => {const put = vi.fn()const file = fakeFile("big.png", "image/png", MAX_ATTACHMENT_SIZE_BYTES + 1)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put))expect(res.ok).toBe(false)if (res.ok) returnexpect(res.response.status).toBe(413)@@ -428,22 +382,20 @@ describe("handleAttachmentUpload", () => {it("accepts arbitrary MIME types", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("evil.exe", "application/x-msdownload", 2)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put))expect(res.ok).toBe(true)if (!res.ok) returnexpect(res.contentType).toBe("application/x-msdownload")expect(put).toHaveBeenCalledOnce()- expect(put.mock.calls[0]?.[2]?.httpMetadata).toEqual({ contentType: "application/x-msdownload" })})it("normalizes an empty browser MIME to application/octet-stream", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("unknown.blend", "", 2)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put))expect(res.ok).toBe(true)if (!res.ok) returnexpect(res.contentType).toBe("application/octet-stream")- expect(put.mock.calls[0]?.[2]?.httpMetadata).toEqual({ contentType: "application/octet-stream" })})it("accepts video, audio, pdf and text MIME types", async () => {@@ -456,7 +408,7 @@ describe("handleAttachmentUpload", () => {]for (const { type, name } of cases) {const f = fakeFile(name, type, 1)- const res = await handleAttachmentUpload(reqWithFile(f), envWithR2(put), "dm", "d1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(f), envWithR2(put))expect(res.ok).toBe(true)}expect(put).toHaveBeenCalledTimes(cases.length)@@ -465,13 +417,11 @@ describe("handleAttachmentUpload", () => {it("sanitizes traversal + slash characters out of the R2 key", async () => {const put = vi.fn().mockResolvedValue(undefined)const file = fakeFile("../evil/../name.png", "image/png", 4)- const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put))expect(res.ok).toBe(true)if (!res.ok) return- // No `..`, no `/` beyond the three fixed structural separators.- const trailing = res.r2Key.replace(/^channel\/c1\/[0-9a-f-]+\//, "")- expect(trailing).not.toContain("..")- expect(trailing).not.toContain("/")+ expect(res.r2Key).toMatch(/^attachments\/sha256\/[0-9a-f]{64}$/)+ expect(res.filename).toBe(file.name)})})@@ -637,9 +587,7 @@ describe("handleBotAvatarUpload", () => {describe("runAttachmentUpload", () => {beforeEach(() => {vi.clearAllMocks()- // Reserve-by-id: the human arm now creates a pending row at upload and- // returns its id. Default the query to echo a stable id.- mockCreatePendingAttachment.mockResolvedValue({ id: "att_1", filename: "hi.png" })+ mockCreateAttachment.mockResolvedValue({ id: "att_1", filename: "hi.png" })})function ctxWith(env: Env, params: Record<string, string> | undefined) {@@ -651,9 +599,7 @@ describe("runAttachmentUpload", () => {}}- // Drive the surface dispatch: `surface="dm"` or `surface="channel"` with a- // channel row carrying `.type`. kind is DERIVED from these (no getChannelType).- function surfaceChannel(type: string) {+ function surfaceChannel(type: string) {mockRequireMessageSurfaceCommunicationAccess.mockResolvedValue({ok: true,value: { surface: "channel", channel: { id: "c1", type } },@@ -696,13 +642,8 @@ describe("runAttachmentUpload", () => {expect(put).not.toHaveBeenCalled()})- it("channel (text) surface → kind 'channel', channel/ R2 prefix, creates a pending row + returns its id (reserve-by-id)", async () => {- // Happy path — access passes, streaming upload succeeds, a PENDING row is- // created and its id returned (reserve-by-id, route/disc step 2b). A text- // channel derives kind="channel" (== what the old channels/[id]/upload- // passed). NO `url` in the response anymore — the display url is id-addressed- // and derived client-side.- surfaceChannel("text")+ it("authorized text upload creates a file record and returns its ID", async () => {+ surfaceChannel("text")const put = vi.fn().mockResolvedValue(undefined)const res = await runAttachmentUpload(reqWithFile(fakeFile("hi.png", "image/png", 10)),@@ -720,30 +661,24 @@ describe("runAttachmentUpload", () => {expect(body.filename).toBe("hi.png")expect(body.contentType).toBe("image/png")expect(body.size).toBe(10)- // Single-source: the upload response carries NO url (client derives it).- expect(body.url).toBeUndefined()- // Pending row created with the credential uploaderId + resolved target.- expect(mockCreatePendingAttachment).toHaveBeenCalledWith(+ expect(body.url).toBeUndefined()+ expect(mockCreateAttachment).toHaveBeenCalledWith(primaryDb,- expect.objectContaining({ uploaderId: "u1", targetId: "c1" }),+ expect.objectContaining({ uploaderId: "u1" }),)expect(put).toHaveBeenCalledOnce()- // Known-length R2 body rule applies here too — the shared helper must not- // hand R2 an unknown-length ReadableStream or buffer into ArrayBuffer.- const [key, streamed] = put.mock.calls[0]- expect(key).toMatch(/^channel\/c1\//)+ const [key, streamed] = put.mock.calls[0]+ expect(key).toMatch(/^attachments\/sha256\/[0-9a-f]{64}$/)expect(streamed).toMatchObject({ size: 10, type: "image/png" })expect(streamed).not.toBeInstanceOf(ReadableStream)expect(streamed).not.toBeInstanceOf(ArrayBuffer)})- it("threads client-supplied image dimensions onto the pending row (single source = upload)", async () => {+ it("threads client-supplied image dimensions onto the file record (single source = upload)", async () => {surfaceChannel("text")const put = vi.fn().mockResolvedValue(undefined)const thumbnail = fakeJpegFile()- // reqWithFile only stubs `get('file')`; extend it to also return w/h so the- // form-dimension parse in readFile sees them.- const req = reqWithFile(fakeFile("hi.png", "image/png", 10))+ const req = reqWithFile(fakeFile("hi.png", "image/png", 10))req.formData = (async () => {const real = new FormData()Object.defineProperty(real, "get", {@@ -765,13 +700,13 @@ describe("runAttachmentUpload", () => {const body = (await res.json()) as { width?: number; height?: number }expect(body.width).toBe(1920)expect(body.height).toBe(1080)- expect(mockCreatePendingAttachment).toHaveBeenCalledWith(+ expect(mockCreateAttachment).toHaveBeenCalledWith(primaryDb,expect.objectContaining({ width: 1920, height: 1080 }),)})- it("dm surface → kind 'dm', dm/ R2 prefix (== old dm/[id]/upload's kind, buildMediaKey parity)", async () => {+ it("authorized DM upload uses content keys", async () => {surfaceDm()const put = vi.fn().mockResolvedValue(undefined)const res = await runAttachmentUpload(@@ -780,10 +715,10 @@ describe("runAttachmentUpload", () => {)expect(res.status).toBe(200)const [key] = put.mock.calls[0]- expect(key).toMatch(/^dm\/d1\//)+ expect(key).toMatch(/^attachments\/sha256\/[0-9a-f]{64}$/)})- it("channel surface + type 'thread' → kind 'thread', thread/ R2 prefix (== old threads/[id]/upload's kind)", async () => {+ it("authorized thread upload uses content keys", async () => {surfaceChannel("thread")const put = vi.fn().mockResolvedValue(undefined)const res = await runAttachmentUpload(@@ -792,10 +727,10 @@ describe("runAttachmentUpload", () => {)expect(res.status).toBe(200)const [key] = put.mock.calls[0]- expect(key).toMatch(/^thread\/c1\//)+ expect(key).toMatch(/^attachments\/sha256\/[0-9a-f]{64}$/)})- it("channel surface + forum top-level → kind 'channel' (phase2 forum≡thread write-guard reversal — forum is now a message-bearing surface)", async () => {+ it("authorized forum upload uses content keys", async () => {surfaceChannel("forum")const put = vi.fn().mockResolvedValue(undefined)const res = await runAttachmentUpload(@@ -804,7 +739,7 @@ describe("runAttachmentUpload", () => {)expect(res.status).toBe(200)const [key] = put.mock.calls[0]- expect(key).toMatch(/^channel\/c1\//)+ expect(key).toMatch(/^attachments\/sha256\/[0-9a-f]{64}$/)})it("forwards handleAttachmentUpload errors (e.g. oversize) unchanged", async () => {@@ -818,47 +753,35 @@ describe("runAttachmentUpload", () => {expect(put).not.toHaveBeenCalled()})- it("deletes the original and thumbnail when the human pending-row insert fails", async () => {- surfaceChannel("text")- mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))- const put = vi.fn().mockResolvedValue(undefined)- const del = vi.fn().mockResolvedValue(undefined)- const thumbnail = fakeJpegFile()- const response = await runAttachmentUpload(- reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),- ctxWith(envWithR2(put, del), { id: "c1" }),- )- expect(response.status).toBe(500)- expect(del).toHaveBeenCalledOnce()- const keys = del.mock.calls[0]?.[0] as string[]- expect(keys).toHaveLength(2)- expect(keys[1]).toBe(`${keys[0]}.thumbnail.jpg`)- })+ it.each(["missing", "wrong-size", "missing-checksum", "wrong-checksum"])(+ "rejects an unverifiable existing R2 object (%s) without creating a file or deleting shared content",+ async (failure) => {+ surfaceChannel("text")+ const file = new File(["shared bytes"], "reuse.txt", { type: "text/plain" })+ const head = vi.fn().mockResolvedValue(failure === "missing" ? null : {+ size: failure === "wrong-size" ? file.size + 1 : file.size,+ checksums: { sha256: failure === "missing-checksum" ? undefined : new Uint8Array(32).buffer },+ })+ const put = vi.fn().mockResolvedValue(null)+ const del = vi.fn()+ const env = { COMMUNITY_MEDIA: { put, head, delete: del } } as unknown as Env+ const response = await runAttachmentUpload(reqWithFile(file), ctxWith(env, { id: "c1" }))+ expect(response.status).toBe(500)+ expect(head).toHaveBeenCalledWith(put.mock.calls[0][0])+ expect(mockCreateAttachment).not.toHaveBeenCalled()+ expect(del).not.toHaveBeenCalled()+ },+ )- it("redacts object keys when human compensation cleanup also fails", async () => {+ it("preserves shared content when the human file insert fails", async () => {surfaceChannel("text")- mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))- const put = vi.fn().mockResolvedValue(undefined)- const del = vi.fn().mockRejectedValueOnce(new TypeError("secret provider detail"))- const thumbnail = fakeJpegFile()-+ mockCreateAttachment.mockRejectedValueOnce(new Error("d1"))+ const del = vi.fn()const response = await runAttachmentUpload(- reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),- ctxWith(envWithR2(put, del), { id: "c1" }),+ reqWithUpload(fakeFile("hi.png", "image/png", 10), fakeJpegFile()),+ ctxWith(envWithR2(vi.fn().mockResolvedValue(undefined), del), { id: "c1" }),)-expect(response.status).toBe(500)- const keys = del.mock.calls[0]?.[0] as string[]- const cleanupLog = mockLogError.mock.calls.find(- ([event]) => event === "attachment_upload_r2_cleanup_failed",- )- expect(cleanupLog?.[1]).toEqual({- route: "channels/[id]/attachments",- actor: "human",- objectCount: 2,- errorCategory: "TypeError",- })- for (const key of keys) expect(JSON.stringify(cleanupLog)).not.toContain(key)- expect(JSON.stringify(cleanupLog)).not.toContain("secret provider detail")+ expect(del).not.toHaveBeenCalled()})})diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex cb8ab5224..8f0d2fb4e 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto"import { NextRequest, NextResponse } from "next/server"import {MAX_ATTACHMENT_SIZE_BYTES,@@ -15,10 +16,7 @@ import { writeError, writeJSON } from "@/lib/middleware/helpers"import { getPrimaryDb } from "@/lib/db"import type { AuthContext } from "@/lib/middleware/auth"import { isInlineAttachmentContentType } from "./attachment-content-type"-import { communityMediaCleanupErrorCategory } from "./community-media-cleanup"import {- buildMediaKey,- buildAttachmentThumbnailKey,buildServerIconKey,buildUserAvatarObjectKey,buildBotAvatarObjectKey,@@ -43,11 +41,6 @@ type UploadErr = { ok: false; response: NextResponse }export type UploadResult = UploadOk | UploadErr-/**- * Slim result for the shared attachment-upload primitive. `runAttachmentUpload`- * and the new agent-upload route both build wire responses from this — the- * legacy `UploadResult` shape is preserved by callers that wrap it.- */type AttachmentUploadOk = {ok: truer2Key: string@@ -55,26 +48,11 @@ type AttachmentUploadOk = {filename: stringcontentType: stringsize: number- // Client-computed image dimensions carried on the upload body (thumbnail at- // file-pick). undefined for non-images and bot uploads. Written onto the- // pending row at upload — the single source of an attachment's dimensions.width?: numberheight?: number}export type AttachmentUploadResult = AttachmentUploadOk | UploadErr-type AttachmentKind = "channel" | "dm" | "thread"--/**- * Provenance tag stamped as R2 `customMetadata`. Human uploads set- * `uploader: "user"`; agent uploads set `uploader: "bot"` so a future orphan-- * GC cron can filter cheaply on bot-authored blobs.- */-export type UploaderTag = {- uploader: "user" | "bot"- uploaderUserId: string-}-function mimeAllowed(contentType: string, allowed: readonly string[]): boolean {if (!contentType) return falsereturn allowed.some((entry) =>@@ -82,15 +60,6 @@ function mimeAllowed(contentType: string, allowed: readonly string[]): boolean {)}-/**- * Parsed upload form: the `file` plus optional client-computed image- * dimensions. `width`/`height` are computed browser-side (thumbnail) at- * file-pick time and ride the SAME multipart body as the file — a `FormData`- * body can only be read once, so they're extracted here alongside the file.- * Absent/non-numeric → undefined (a bot upload never sends them; a non-image- * has none). This is the SINGLE source of an attachment's dimensions: they are- * written onto the pending row at upload time and never re-supplied on send.- */type ParsedUpload = {file: Filethumbnail?: File@@ -231,26 +200,34 @@ async function readFile(req: NextRequest): Promise<ParsedUpload | UploadErr> {}}-/**- * Validate + upload an attachment for a channel / DM / thread.- *- * Enforces `MAX_ATTACHMENT_SIZE_BYTES` and `ALLOWED_ATTACHMENT_MIME_PREFIXES`.- * Returns the stored R2 key + parsed metadata (filename, content-type, size,- * and any client-supplied image dimensions). The caller persists a pending- * attachment row keyed by that r2Key; reads then serve it through the canonical- * `channels/{id}/attachments/{attachmentId}` door (there is no `/media/` route).- *- * R2 requires stream bodies to have a known length. Passing the `File` itself- * preserves that length for the Workers runtime while avoiding an explicit- * `arrayBuffer()` copy in application code. Size and content-type are- * read from the `File` object before the put.- */+async function putAttachmentContent(bucket: R2Bucket, file: File, prefix: string): Promise<string> {+ const hash = createHash("sha256")+ const reader = file.stream().getReader()+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ hash.update(value)+ }+ } finally {+ reader.releaseLock()+ }+ const digest = hash.digest("hex")+ const key = `${prefix}/sha256/${digest}`+ const stored = await bucket.put(key, file, {+ onlyIf: { etagDoesNotMatch: "*" },+ sha256: digest,+ }) ?? await bucket.head(key)+ if (!stored || stored.size !== file.size || !stored.checksums.sha256+ || Buffer.from(stored.checksums.sha256).toString("hex") !== digest) {+ throw new Error("attachment content verification failed")+ }+ return key+}+export async function handleAttachmentUpload(req: NextRequest,env: Env,- kind: AttachmentKind,- targetId: string,- uploaderTag: UploaderTag,): Promise<AttachmentUploadResult> {const parsed = await readFile(req)if ("ok" in parsed && parsed.ok === false) return parsed@@ -296,42 +273,10 @@ export async function handleAttachmentUpload(}}- const fileId = crypto.randomUUID()- const key = buildMediaKey(kind, targetId, fileId, file.name)-- const customMetadata = {- uploader: uploaderTag.uploader,- bot_user_id: uploaderTag.uploader === "bot" ? uploaderTag.uploaderUserId : "",- }-- await env.COMMUNITY_MEDIA.put(key, file, {- httpMetadata: { contentType },- customMetadata: { ...customMetadata, variant: "original" },- })-- let thumbnailR2Key: string | null = null- if (thumbnail) {- thumbnailR2Key = buildAttachmentThumbnailKey(key)- try {- await env.COMMUNITY_MEDIA.put(thumbnailR2Key, thumbnail, {- httpMetadata: { contentType: "image/jpeg" },- customMetadata: { ...customMetadata, variant: "thumbnail" },- })- } catch (err) {- try {- await env.COMMUNITY_MEDIA.delete(key)- } catch (cleanupErr) {- log.error("attachment_thumbnail_put_cleanup_failed", {- uploader: uploaderTag.uploader,- route: "channels/[id]/attachments",- phase: "thumbnail_put_original_compensation",- objectCount: 1,- errorCategory: communityMediaCleanupErrorCategory(cleanupErr),- })- }- throw err- }- }+ const key = await putAttachmentContent(env.COMMUNITY_MEDIA, file, "attachments")+ const thumbnailR2Key = thumbnail+ ? await putAttachmentContent(env.COMMUNITY_MEDIA, thumbnail, "attachment-thumbnails")+ : nullreturn {ok: true,@@ -463,31 +408,6 @@ export function handleBotAvatarUpload()}-/**- * Shared body for the unified attachment-upload trunk. One `id`, dispatched by- * the channel's surface — the three old per-type routes- * (`channels/[id]/upload`, `dm/[id]/upload`, `threads/[id]/upload`) have- * collapsed onto this one; the DM/thread routes are now deleted and the web- * client uploads through `channels/[id]/upload` for every surface.- *- * Access + surface come from `requireMessageSurfaceCommunicationAccess`, so a- * DM id requires both participant access and an accepted friendship before any- * R2 object or pending attachment row is written.- *- * `kind` (which feeds `buildMediaKey` → the R2 key path, so its VALUE is- * load-bearing, not just its guard) is DERIVED from `(surface, channel.type)`- * consumed from the dispatch's return — NOT re-queried via a second- * `getChannelType` (that would be a mini re-derive + extra hop; the dispatch- * already fetched the row). `surface` alone is lossy (thread and text both- * present as `surface="channel"`), so the channel arm splits on `channel.type`:- * - dm → kind "dm" (a DM is a legitimate- * attachment target — no bearing guard)- * - channel + thread → kind "thread" (requireChildSurface)- * - channel + text/forum(-top) → kind "channel" (requireMessageBearingSurface)- * These map byte-for-byte to what the three routes passed before, so new- * uploads land under the same R2 key prefix (existing attachments read from the- * stored `r2_key` column and are unaffected — the derivation is write-only).- */export async function runAttachmentUpload(req: NextRequest,ctx: AuthContext & { params?: Record<string, string> },@@ -501,47 +421,19 @@ export async function runAttachmentUpload(const auth = await requireMessageSurfaceCommunicationAccess(db, id, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- // Derive kind + apply the per-surface guard from the dispatch's return — no- // re-query. The DM arm already passed its communication gate.- let kind: AttachmentKind- if (auth.value.surface === "dm") {- kind = "dm"- } else {+ if (auth.value.surface !== "dm") {const channelType = auth.value.channel.type- if (isThread(channelType)) {- const child = requireChildSurface(channelType)- if (!child.ok) return writeError(child.error, child.status)- kind = "thread"- } else {- const surface = requireMessageBearingSurface(channelType)- if (!surface.ok) return writeError(surface.error, surface.status)- kind = "channel"- }+ const surface = isThread(channelType)+ ? requireChildSurface(channelType)+ : requireMessageBearingSurface(channelType)+ if (!surface.ok) return writeError(surface.error, surface.status)}- // Track any R2 blob written before the D1 insert throws so the catch can- // best-effort delete it (mirrors the bot upload route's orphan-cleanup).- let r2KeysToCleanUp: string[] = []try {- const result = await handleAttachmentUpload(req, ctx.env, kind, id, {- uploader: "user",- uploaderUserId: ctx.userId,- })+ const result = await handleAttachmentUpload(req, ctx.env)if (!result.ok) return result.response- r2KeysToCleanUp = [result.r2Key, ...(result.thumbnailR2Key ? [result.thumbnailR2Key] : [])]-- // Reserve-by-id (route/disc step 2b): the human composer now mirrors the- // bot flow — the upload creates a PENDING row (messageId = NULL) and returns- // its stable id. The composer holds the id in-memory and passes it to `send`,- // where `reserveAttachmentsForMessage` links it. `uploaderId` is the- // credential user (self-scope, never from the body); `send` re-verifies the- // id against (uploader, target) before reserving, so a stolen id can't be- // attached to another user's message. Image dimensions are written HERE (the- // single source — they never ride the send body) so the pending row is a- // self-contained, complete entity at upload time; `reserve` only links it.- const row = await queries.communityAttachment.createPendingAttachment(db, {+ const row = await queries.communityAttachment.createAttachment(db, {uploaderId: ctx.userId,- targetId: id,r2Key: result.r2Key,thumbnailR2Key: result.thumbnailR2Key,filename: result.filename,@@ -561,20 +453,6 @@ export async function runAttachmentUpload(...(result.height !== undefined ? { height: result.height } : {}),})} catch (err) {- if (r2KeysToCleanUp.length > 0) {- try {- await ctx.env.COMMUNITY_MEDIA.delete(- r2KeysToCleanUp.length === 1 ? r2KeysToCleanUp[0]! : r2KeysToCleanUp,- )- } catch (cleanupErr) {- log.error("attachment_upload_r2_cleanup_failed", {- route: "channels/[id]/attachments",- actor: "human",- objectCount: r2KeysToCleanUp.length,- errorCategory: communityMediaCleanupErrorCategory(cleanupErr),- })- }- }log.error("attachment_upload_failure", {route: "channels/[id]/attachments",userId: ctx.userId,diff --git a/src/web/src/test/e2e-ui/19-marketing-seo.spec.ts b/src/web/src/test/e2e-ui/19-marketing-seo.spec.tsindex 183fa7ea2..9bbab04de 100644--- a/src/web/src/test/e2e-ui/19-marketing-seo.spec.ts+++ b/src/web/src/test/e2e-ui/19-marketing-seo.spec.ts@@ -245,12 +245,16 @@ for (const width of [1440, 390]) {await expect.poll(contactLayout).toEqual(direct)await page.goto("/pricing")const contact = page.getByRole("link", { name: "Contact us", exact: true })- await expect(contact).toBeInViewport()await expect(page.getByRole("heading", { name: "Free", exact: true }).locator("..").getByRole("button")).not.toHaveText("Loading…")- const box = await contact.boundingBox()- const plans = await page.getByRole("region", { name: "Alook plans" }).boundingBox()- expect(box!.height).toBeGreaterThanOrEqual(44)- expect(box!.y + box!.height).toBeLessThan(plans!.y)+ await expect(contact).toBeInViewport()+ await expect(async () => {+ const box = await contact.boundingBox()+ const plans = await page.getByRole("region", { name: "Alook plans" }).boundingBox()+ expect(box).not.toBeNull()+ expect(plans).not.toBeNull()+ expect(box!.height).toBeGreaterThanOrEqual(44)+ expect(box!.y + box!.height).toBeLessThan(plans!.y)+ }).toPass({ timeout: 10_000 })expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width)await page.screenshot({ path: testInfo.outputPath("pricing-contact.png") })await contact.focus()diff --git a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.tsindex ceacc7c57..c94285c99 100644--- a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts+++ b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts@@ -35,7 +35,7 @@ function headers(key: "alice" | "bob" | "carol") {return { Cookie: sessionCookie(key), Origin: WEB_URL }}-async function uploadPending(+async function uploadFile(key: "alice" | "bob" | "carol",channelId: string,name: string,@@ -96,22 +96,33 @@ async function status(return (await fetch(`${WEB_URL}${path}`, { method, headers: headers(key) })).status}-test("existing channel/server deletes converge UI, WS, pending rows, linked media, and icon reads", async ({ asUser }) => {+test("existing channel/server deletes converge UI, WS, last references, retained files, and icon reads", async ({ asUser }) => {test.setTimeout(210_000)const stamp = Date.now()+ const destinationServerId = await seedServer("alice", `C1 forwards ${stamp}`)+ const destinationId = await seedChannel("alice", destinationServerId, `keep-media-${stamp}`, "text")+ await seedJoinServer("alice", "bob", destinationServerId)+ await seedJoinServer("alice", "carol", destinationServerId)const channelServerId = await seedServer("alice", `C1 channel ${stamp}`)const channelId = await seedChannel("alice", channelServerId, `delete-media-${stamp}`, "text")await seedJoinServer("alice", "bob", channelServerId)- const linkedChannelAttachment = await uploadPending("alice", channelId, "linked-channel.png", true)- const pendingChannelAttachment = await uploadPending("alice", channelId, "pending-channel.png", true)+ const linkedChannelAttachment = await uploadFile("alice", channelId, "linked-channel.png", true)+ const unsentChannelAttachment = await uploadFile("alice", channelId, "unsent-channel.png", true)await linkAttachment("alice", channelId, linkedChannelAttachment)+ const forwardedChannelAttachment = await uploadFile("alice", channelId, "forwarded-channel.png", true)+ await linkAttachment("alice", channelId, forwardedChannelAttachment)+ await linkAttachment("bob", destinationId, forwardedChannelAttachment)+ expect(await status("bob", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}`)).toBe(404)const serverId = await seedServer("alice", `C1 server ${stamp}`)const serverChannelId = await seedChannel("alice", serverId, `delete-server-${stamp}`, "text")await seedJoinServer("alice", "bob", serverId)- const linkedServerAttachment = await uploadPending("alice", serverChannelId, "linked-server.png", true)- const pendingServerAttachment = await uploadPending("alice", serverChannelId, "pending-server.png", true)+ const linkedServerAttachment = await uploadFile("alice", serverChannelId, "linked-server.png", true)+ const unsentServerAttachment = await uploadFile("alice", serverChannelId, "unsent-server.png", true)await linkAttachment("alice", serverChannelId, linkedServerAttachment)+ const forwardedServerAttachment = await uploadFile("alice", serverChannelId, "forwarded-server.png", true)+ await linkAttachment("alice", serverChannelId, forwardedServerAttachment)+ await linkAttachment("bob", destinationId, forwardedServerAttachment)await uploadServerIcon(serverId)const alice = await asUser("alice")@@ -142,7 +153,12 @@ test("existing channel/server deletes converge UI, WS, pending rows, linked mediawait expect.poll(() => aliceDeletes.frames.filter((frame) => frame.channelId === channelId)).toHaveLength(1)await expect.poll(() => bobDeletes.frames.filter((frame) => frame.channelId === channelId)).toHaveLength(1)expect(await status("alice", `/api/community/channels/${channelId}/attachments/${linkedChannelAttachment}`)).toBe(404)- expect(await status("alice", `/api/community/channels/${channelId}/attachments/${pendingChannelAttachment}`)).toBe(404)+ expect(await status("alice", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}`)).toBe(200)+ expect(await status("alice", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}/thumbnail`)).toBe(200)+ expect(await status("bob", `/api/community/channels/${channelId}/attachments/${unsentChannelAttachment}`)).toBe(404)+ expect(await status("bob", `/api/community/channels/${channelId}/attachments/${forwardedChannelAttachment}`)).toBe(200)+ expect(await status("bob", `/api/community/channels/${channelId}/attachments/${forwardedChannelAttachment}/thumbnail`)).toBe(200)+ expect(await status("carol", `/api/community/channels/${destinationId}/attachments/${forwardedChannelAttachment}`)).toBe(200)await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${serverChannelId}`)await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${serverChannelId}`)@@ -189,7 +205,12 @@ test("existing channel/server deletes converge UI, WS, pending rows, linked medi))).toHaveLength(1)expect(await status("alice", `/api/community/servers/${serverId}/icon`)).toBe(404)expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${linkedServerAttachment}`)).toBe(404)- expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${pendingServerAttachment}`)).toBe(404)+ expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${unsentServerAttachment}`)).toBe(200)+ expect(await status("alice", `/api/community/channels/${serverChannelId}/attachments/${unsentServerAttachment}/thumbnail`)).toBe(200)+ expect(await status("bob", `/api/community/channels/${serverChannelId}/attachments/${unsentServerAttachment}`)).toBe(404)+ expect(await status("bob", `/api/community/channels/${serverChannelId}/attachments/${forwardedServerAttachment}`)).toBe(200)+ expect(await status("bob", `/api/community/channels/${serverChannelId}/attachments/${forwardedServerAttachment}/thumbnail`)).toBe(200)+ expect(await status("carol", `/api/community/channels/${destinationId}/attachments/${forwardedServerAttachment}`)).toBe(200)await alice.page.goBack()await expect(alice.page).not.toHaveURL(new RegExp(`/c/channels/${serverId}/`))diff --git a/src/web/test-runtime/account-deletion-minimal.runtime.test.ts b/src/web/test-runtime/account-deletion-minimal.runtime.test.tsindex dea941d1a..bbcd6c8be 100644--- a/src/web/test-runtime/account-deletion-minimal.runtime.test.ts+++ b/src/web/test-runtime/account-deletion-minimal.runtime.test.ts@@ -167,12 +167,12 @@ describe("minimal account deletion real D1 batch", () => {"INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'reply', ?, ?, 1)",reply, reader, now, thread,)- await run(- "INSERT INTO community_attachment (id, message_id, uploader_id, target_id, r2_key, filename, position, created_at) VALUES (?, ?, ?, ?, ?, 'reply.txt', 0, ?), (?, NULL, ?, ?, ?, 'pending-server.txt', 0, ?), (?, NULL, ?, ?, ?, 'pending-thread.txt', 0, ?)",- `attachment_${stamp}`, reply, reader, thread, threadAttachment, now,- pendingServerAttachment, reader, serverChannel, pendingServerAttachmentKey, now,- pendingThreadAttachment, reader, thread, pendingThreadAttachmentKey, now,- )+ await run("INSERT INTO community_attachment(id,uploader_id,r2_key,filename,created_at) VALUES (?,?,?,'reply.txt',?),(?,?,?,'pending-server.txt',?),(?,?,?,'pending-thread.txt',?),(?,?,?,'forwarded.txt',?)",+ `attachment_${stamp}`, reader, threadAttachment, now,+ pendingServerAttachment, reader, pendingServerAttachmentKey, now,+ pendingThreadAttachment, reader, pendingThreadAttachmentKey, now,+ `forwarded_${stamp}`, owner, threadAttachment, now)+ await run("INSERT INTO community_message_attachment VALUES (?,?,0),(?,?,0),(?,?,0)", reply, `attachment_${stamp}`, authored, `forwarded_${stamp}`, prior, `forwarded_${stamp}`)const db = createDb(runtimeEnv.DB)const snapshot = await queries.accountDeletion.getAccountDeletionSnapshot(db, owner)@@ -180,9 +180,9 @@ describe("minimal account deletion real D1 batch", () => {expect(snapshot?.ownedWorkspaceIds).toEqual([workspace])expect(snapshot?.ownedAgentIds.sort()).toEqual([`agent_${stamp}`, ownedSharedAgent].sort())expect(snapshot?.machineTokens.sort()).toEqual([ownerMachineToken, workspaceMachineToken].sort())- expect(snapshot?.media.communityExactKeys).toContain(threadAttachment)- expect(snapshot?.media.communityExactKeys).toContain(pendingServerAttachmentKey)- expect(snapshot?.media.communityExactKeys).toContain(pendingThreadAttachmentKey)+ expect(snapshot?.media.communityExactKeys).not.toContain(threadAttachment)+ expect(snapshot?.media.communityExactKeys).not.toContain(pendingServerAttachmentKey)+ expect(snapshot?.media.communityExactKeys).not.toContain(pendingThreadAttachmentKey)expect(snapshot?.media.deletingEmailAttachments).toContain(JSON.stringify([{ key: sharedDraftKey },{ key: privateDraftKey },@@ -209,7 +209,9 @@ describe("minimal account deletion real D1 batch", () => {expect(await first("SELECT id FROM community_server WHERE id = ?", server)).toBeNull()expect(await first("SELECT id FROM community_channel WHERE id = ?", thread)).toBeNull()expect(await first("SELECT id FROM community_attachment WHERE id = ?", `attachment_${stamp}`)).toBeNull()- expect(await first("SELECT id FROM community_attachment WHERE id IN (?, ?)", pendingServerAttachment, pendingThreadAttachment)).toBeNull()+ expect(await first("SELECT id FROM community_attachment WHERE id IN (?, ?)", pendingServerAttachment, pendingThreadAttachment)).not.toBeNull()+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `forwarded_${stamp}`)).not.toBeNull()+ expect(await first("SELECT attachment_id FROM community_message_attachment WHERE message_id = ?", prior)).toEqual({ attachment_id: `forwarded_${stamp}` })expect(await first("SELECT id FROM user WHERE id = ?", reader)).toEqual({ id: reader })expect(await first("SELECT id FROM deviceCode WHERE userId = ?", owner)).toBeNull()expect(await first("SELECT id FROM verification WHERE id IN (?, ?)", `otp_${stamp}`, `ott_${stamp}`)).toBeNull()diff --git a/src/web/test-runtime/attachment-reuse.runtime.test.ts b/src/web/test-runtime/attachment-reuse.runtime.test.tsnew file mode 100644index 000000000..95d3596fa--- /dev/null+++ b/src/web/test-runtime/attachment-reuse.runtime.test.ts@@ -0,0 +1,118 @@+/// <reference types="@cloudflare/vitest-plugin/types" />+import { env } from "cloudflare:workers"+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import { queries, createDb } from "@alook/shared"+import { handleAttachmentUpload } from "../src/lib/community/upload"+import { collectAttachmentObjects } from "../scripts/attachment-maintenance"+import { structuredJpegFixture } from "../src/test/fixtures/media"+import type { NextRequest } from "next/server"++const bindings = env as unknown as CloudflareEnv+let uploader: string+const files: string[] = []+const keys = new Set<string>()+const request = (name: string, bytes: Uint8Array, type = "application/pdf") => {+ const form = new FormData()+ form.set("file", new File([bytes], name, { type }))+ return { formData: async () => form } as NextRequest+}+beforeEach(async () => {+ uploader = `file-runtime-${crypto.randomUUID()}`+ await bindings.DB.prepare("INSERT INTO user(id,email,name,discriminator) VALUES (?,?,'File QA','0123')").bind(uploader, `${uploader}@example.test`).run()+})+afterEach(async () => {+ for (const id of files.splice(0)) await bindings.DB.prepare("DELETE FROM community_attachment WHERE id = ?").bind(id).run()+ for (const key of keys) await bindings.COMMUNITY_MEDIA.delete(key)+ keys.clear()+ await bindings.DB.prepare("DELETE FROM user WHERE id = ?").bind(uploader).run()+})++describe("file content storage on real D1/R2 bindings", () => {+ it("concurrent equal bytes share one object while file identity and metadata stay separate", async () => {+ const bytes = crypto.getRandomValues(new Uint8Array(32))+ const [a, b] = await Promise.all([+ handleAttachmentUpload(request("a.pdf", bytes), bindings),+ handleAttachmentUpload(request("b.txt", bytes, "text/plain"), bindings),+ ])+ expect(a.ok && b.ok).toBe(true)+ if (!a.ok || !b.ok) return+ keys.add(a.r2Key)+ expect(a.r2Key).toBe(b.r2Key)+ expect(a.filename).toBe("a.pdf"); expect(b.filename).toBe("b.txt")+ const db = createDb(bindings.DB)+ const rows = await Promise.all([a, b].map(result => queries.communityAttachment.createAttachment(db, {+ uploaderId: uploader, filename: result.filename, r2Key: result.r2Key, size: result.size, contentType: result.contentType,+ })))+ files.push(...rows.map(row => row.id))+ expect(rows[0]!.id).not.toBe(rows[1]!.id)+ expect(new Uint8Array(await (await bindings.COMMUNITY_MEDIA.get(a.r2Key))!.arrayBuffer())).toEqual(bytes)+ const listed = await bindings.COMMUNITY_MEDIA.list({ prefix: a.r2Key })+ expect(listed.objects).toHaveLength(1)+ await bindings.DB.prepare("DELETE FROM community_attachment WHERE id = ?").bind(rows[0]!.id).run()+ files.splice(files.indexOf(rows[0]!.id), 1)+ await collectAttachmentObjects(bindings, { apply: true, beforeWrite: async () => {}, record: async () => {} })+ expect(await bindings.COMMUNITY_MEDIA.get(a.r2Key)).not.toBeNull()+ })++ it("the same filename cannot merge different content or trust a client hash", async () => {+ const upload = (bytes: Uint8Array) => {+ const form = new FormData()+ form.set("file", new File([bytes], "same.pdf", { type: "application/pdf" }))+ form.set("sha256", "0".repeat(64))+ return handleAttachmentUpload({ formData: async () => form } as NextRequest, bindings)+ }+ const a = await upload(crypto.getRandomValues(new Uint8Array(16)))+ const b = await upload(crypto.getRandomValues(new Uint8Array(16)))+ expect(a.ok && b.ok).toBe(true)+ if (!a.ok || !b.ok) return+ keys.add(a.r2Key); keys.add(b.r2Key)+ expect(a.r2Key).not.toBe(b.r2Key)+ expect(a.r2Key).not.toContain("0".repeat(64))+ expect(b.r2Key).not.toContain("0".repeat(64))+ })++ it("the same original with different valid thumbnails cannot overwrite either thumbnail", async () => {+ const original = crypto.getRandomValues(new Uint8Array(10))+ const make = (width: number) => {+ const form = new FormData()+ form.set("file", new File([original], "picture.png", { type: "image/png" }))+ form.set("thumbnail", new File([structuredJpegFixture(width, 10)], "thumbnail.jpg", { type: "image/jpeg" }))+ return { formData: async () => form } as NextRequest+ }+ const a = await handleAttachmentUpload(make(10), bindings)+ const b = await handleAttachmentUpload(make(20), bindings)+ expect(a.ok && b.ok).toBe(true)+ if (!a.ok || !b.ok) return+ keys.add(a.r2Key); keys.add(a.thumbnailR2Key!); keys.add(b.thumbnailR2Key!)+ expect(a.r2Key).toBe(b.r2Key)+ expect(a.thumbnailR2Key).not.toBe(b.thumbnailR2Key)+ expect(await (await bindings.COMMUNITY_MEDIA.get(a.thumbnailR2Key!))!.arrayBuffer()).toEqual(Uint8Array.from(structuredJpegFixture(10, 10)).buffer)+ expect(await (await bindings.COMMUNITY_MEDIA.get(b.thumbnailR2Key!))!.arrayBuffer()).toEqual(Uint8Array.from(structuredJpegFixture(20, 10)).buffer)+ })++ it("preserves legacy keys and bytes, and collects only explicit unreferenced objects offline", async () => {+ const id = crypto.randomUUID()+ files.push(id)+ const original = `channel/runtime/${id}/old.pdf`+ const thumb = `thread/runtime/${id}/thumbnail.jpg`+ const orphan = `dm/runtime/${id}/orphan.pdf`+ keys.add(original); keys.add(thumb); keys.add(orphan)+ const bytes = crypto.getRandomValues(new Uint8Array(12))+ const thumbnail = crypto.getRandomValues(new Uint8Array(7))+ await bindings.COMMUNITY_MEDIA.put(original, bytes)+ await bindings.COMMUNITY_MEDIA.put(thumb, thumbnail)+ await bindings.COMMUNITY_MEDIA.put(orphan, bytes)+ await queries.communityAttachment.createAttachment(createDb(bindings.DB), { id, uploaderId: uploader, filename: "old.pdf", r2Key: original, thumbnailR2Key: thumb, size: bytes.length })+ const record = async () => {}+ const candidates = new Set([original, thumb, orphan])+ await collectAttachmentObjects(bindings, { apply: false, record }, candidates)+ expect(await bindings.COMMUNITY_MEDIA.get(orphan)).not.toBeNull()+ await expect(collectAttachmentObjects(bindings, { apply: true, record }, candidates)).rejects.toThrow("quiescence")+ await collectAttachmentObjects(bindings, { apply: true, beforeWrite: async () => {}, record }, candidates)+ expect(await bindings.COMMUNITY_MEDIA.get(orphan)).toBeNull()+ const retained = await bindings.DB.prepare("SELECT r2_key, thumbnail_r2_key, filename FROM community_attachment WHERE id = ?").bind(id).first<any>()+ expect(retained).toEqual({ r2_key: original, thumbnail_r2_key: thumb, filename: "old.pdf" })+ expect(new Uint8Array(await (await bindings.COMMUNITY_MEDIA.get(original))!.arrayBuffer())).toEqual(bytes)+ expect(new Uint8Array(await (await bindings.COMMUNITY_MEDIA.get(thumb))!.arrayBuffer())).toEqual(thumbnail)+ })+})diff --git a/src/web/test-runtime/community-delete-media.runtime.test.ts b/src/web/test-runtime/community-delete-media.runtime.test.tsindex 6f4570009..5c2f20c2c 100644--- a/src/web/test-runtime/community-delete-media.runtime.test.ts+++ b/src/web/test-runtime/community-delete-media.runtime.test.ts@@ -55,7 +55,7 @@ afterEach(async () => {})describe("existing delete media real D1 batches", () => {- it("channel deletion snapshots root/child linked and pending keys for exactly one winner", async () => {+ it("channel deletion removes last references, preserves drafts and advances read state for one winner", async () => {const { owner, server, stamp } = await seedOwnerAndServer()const root = `cdm_root_${stamp}`const child = `cdm_child_${stamp}`@@ -82,20 +82,14 @@ describe("existing delete media real D1 batches", () => {childMessage, owner, child,unrelatedMessage, owner, unrelated,)- await run(- `INSERT INTO community_attachment- (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, created_at) VALUES- (?, ?, ?, ?, 'root/original', 'root/thumb', 'root.png', '2026-08-23T00:00:00.000Z'),- (?, ?, ?, ?, 'child/original', 'child/thumb', 'child.png', '2026-08-23T00:00:00.000Z'),- (?, NULL, ?, ?, 'root/pending', 'root/pending-thumb', 'pending-root.png', '2026-08-23T00:00:00.000Z'),- (?, NULL, ?, ?, 'child/pending', NULL, 'pending-child.png', '2026-08-23T00:00:00.000Z'),- (?, ?, ?, ?, 'other/original', 'other/thumb', 'other.png', '2026-08-23T00:00:00.000Z')`,- `att_root_${stamp}`, rootMessage, owner, unrelated,- `att_child_${stamp}`, childMessage, owner, unrelated,- `att_pending_root_${stamp}`, owner, root,- `att_pending_child_${stamp}`, owner, child,- `att_other_${stamp}`, unrelatedMessage, owner, unrelated,- )+ for (const [id, r2Key, thumbnailR2Key, filename] of [+ [`att_root_${stamp}`, "root/original", "root/thumb", "root.png"],+ [`att_child_${stamp}`, "child/original", "child/thumb", "child.png"],+ [`att_pending_root_${stamp}`, "root/pending", "root/pending-thumb", "pending-root.png"],+ [`att_pending_child_${stamp}`, "child/pending", null, "pending-child.png"],+ [`att_other_${stamp}`, "other/original", "other/thumb", "other.png"],+ ]) await run("INSERT INTO community_attachment(id,uploader_id,r2_key,thumbnail_r2_key,filename,created_at) VALUES (?,?,?,?,?,'now')", id, owner, r2Key, thumbnailR2Key, filename)+ await run("INSERT INTO community_message_attachment VALUES (?,?,0),(?,?,0),(?,?,0)", rootMessage, `att_root_${stamp}`, childMessage, `att_child_${stamp}`, unrelatedMessage, `att_other_${stamp}`)await run(`INSERT INTO community_read_state(id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES@@ -115,10 +109,7 @@ describe("existing delete media real D1 batches", () => {expect(results.filter((result) => result.deleted)).toHaveLength(1)const winner = results.find((result) => result.deleted)!- expect(new Set(winner.mediaKeys)).toEqual(new Set([- "root/original", "root/thumb", "child/original", "child/thumb",- "root/pending", "root/pending-thumb", "child/pending",- ]))+ expect(winner.mediaKeys).toEqual([])expect(winner.readStateRevisions).toEqual([{ userId: owner, revision: 1 }])await expect(queries.communityReadState.getAccountReadStateSnapshot(db, owner)).resolves.toEqual({revision: 1,@@ -132,11 +123,11 @@ describe("existing delete media real D1 batches", () => {expect(results.find((result) => !result.deleted)?.mediaKeys).toEqual([])expect(await first("SELECT id FROM community_channel WHERE id = ?", root)).toBeNull()expect(await first("SELECT id FROM community_channel WHERE id = ?", child)).toBeNull()- expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_pending_child_${stamp}`)).toBeNull()+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_pending_child_${stamp}`)).not.toBeNull()expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_other_${stamp}`)).not.toBeNull()})- it("server deletion is owner-scoped and returns attachment keys plus the winner icon once", async () => {+ it("server deletion is owner-scoped and preserves drafts and returns only the winner icon once", async () => {const icon = "server-icon/runtime/icon-a"const { owner, server, stamp } = await seedOwnerAndServer(icon)const channel = `cdm_server_channel_${stamp}`@@ -149,14 +140,8 @@ describe("existing delete media real D1 batches", () => {"INSERT INTO community_message (id, author_id, content, channel_id, seq, created_at) VALUES (?, ?, 'hello', ?, 1, '2026-08-23T00:00:00.000Z')",message, owner, channel,)- await run(- `INSERT INTO community_attachment- (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, created_at) VALUES- (?, ?, ?, ?, 'server/original', 'server/thumb', 'linked.png', '2026-08-23T00:00:00.000Z'),- (?, NULL, ?, ?, 'server/pending', NULL, 'pending.png', '2026-08-23T00:00:00.000Z')`,- `att_server_${stamp}`, message, owner, channel,- `att_server_pending_${stamp}`, owner, channel,- )+ await run("INSERT INTO community_attachment(id,uploader_id,r2_key,thumbnail_r2_key,filename,created_at) VALUES (?,?, 'server/original','server/thumb','linked.png','now'),(?,?,'server/pending',NULL,'pending.png','now')", `att_server_${stamp}`, owner, `att_server_pending_${stamp}`, owner)+ await run("INSERT INTO community_message_attachment VALUES (?,?,0)", message, `att_server_${stamp}`)await run(`INSERT INTO community_read_state(id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)@@ -177,7 +162,7 @@ describe("existing delete media real D1 batches", () => {expect(results.filter((result) => result.deleted)).toHaveLength(1)expect(results.find((result) => result.deleted)).toEqual({deleted: true,- mediaKeys: ["server/original", "server/thumb", "server/pending"],+ mediaKeys: [],iconKey: icon,readStateRevisions: [{ userId: owner, revision: 1 }],})@@ -191,7 +176,7 @@ describe("existing delete media real D1 batches", () => {})})-describe("guarded pending insert and server icon CAS in real D1", () => {+describe("reusable file insert and server icon CAS in real D1", () => {it("accepts a live DM target with type=dm and server_id NULL", async () => {const { owner, stamp } = await seedOwnerAndServer()const dm = `cdm_dm_${stamp}`@@ -202,20 +187,19 @@ describe("guarded pending insert and server icon CAS in real D1", () => {)const db = createDb(runtimeEnv.DB)- await expect(queries.communityAttachment.createPendingAttachment(db, {+ await expect(queries.communityAttachment.createAttachment(db, {id: attachment,uploaderId: owner,- targetId: dm,r2Key: "pending/dm-live",filename: "dm-live.png",- })).resolves.toMatchObject({ id: attachment, targetId: dm, messageId: null })+ })).resolves.toMatchObject({ id: attachment })expect(await first("SELECT id FROM community_attachment WHERE id = ?", attachment)).not.toBeNull()await run("DELETE FROM community_attachment WHERE id = ?", attachment)await run("DELETE FROM community_channel WHERE id = ?", dm)})- it("inserts only while the target channel exists", async () => {+ it("files survive deleting an upload routing channel without message references", async () => {const { owner, server, stamp } = await seedOwnerAndServer()const channel = `cdm_pending_${stamp}`await run(@@ -223,28 +207,26 @@ describe("guarded pending insert and server icon CAS in real D1", () => {channel, server,)const db = createDb(runtimeEnv.DB)- const inserted = await queries.communityAttachment.createPendingAttachment(db, {+ const inserted = await queries.communityAttachment.createAttachment(db, {id: `att_live_${stamp}`,uploaderId: owner,- targetId: channel,r2Key: "pending/live",thumbnailR2Key: "pending/live-thumb",filename: "live.png",})- expect(inserted.targetId).toBe(channel)+ expect(inserted.id).toBe(`att_live_${stamp}`)await queries.communityDeleteMedia.deleteChannelWithMedia(db, {channelId: channel,serverId: server,})- await expect(queries.communityAttachment.createPendingAttachment(db, {+ await expect(queries.communityAttachment.createAttachment(db, {id: `att_deleted_${stamp}`,uploaderId: owner,- targetId: channel,r2Key: "pending/deleted",filename: "deleted.png",- })).rejects.toThrow("attachment target no longer exists")- expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_deleted_${stamp}`)).toBeNull()+ })).resolves.toMatchObject({ id: `att_deleted_${stamp}` })+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_deleted_${stamp}`)).not.toBeNull()})it("uses a null-safe old-value CAS with exactly one concurrent winner", async () => {diff --git a/src/web/test-runtime/forum-post-delete.runtime.test.ts b/src/web/test-runtime/forum-post-delete.runtime.test.tsindex f6d686b0e..46bd863fb 100644--- a/src/web/test-runtime/forum-post-delete.runtime.test.ts+++ b/src/web/test-runtime/forum-post-delete.runtime.test.ts@@ -98,16 +98,11 @@ async function seedCanonicalPost() {`rs_owner_${id.opener}`, id.owner, id.forum, t3, id.opener,`rs_reader_${id.opener}`, id.reader, id.forum, t3, id.opener,);- await run(- `INSERT INTO community_attachment- (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, created_at)- VALUES (?, ?, ?, ?, ?, ?, 'opener.png', ?),- (?, ?, ?, ?, ?, ?, 'reply.png', ?),- (?, NULL, ?, ?, ?, ?, 'pending.png', ?)`,- `att_opener_${id.opener}`, id.opener, id.owner, id.child, `${id.opener}/original`, `${id.opener}/thumb`, t3,- `att_reply_${id.opener}`, id.reply, id.reader, id.child, `${id.reply}/original`, `${id.reply}/thumb`, childTime,- `att_pending_${id.opener}`, id.owner, id.child, `${id.child}/pending-original`, `${id.child}/pending-thumb`, childTime,- );+ await run("INSERT INTO community_attachment(id,uploader_id,r2_key,thumbnail_r2_key,filename,created_at) VALUES (?,?,?,?, 'opener.png',?),(?,?,?,?, 'reply.png',?),(?,?,?,?, 'pending.png',?)",+ `att_opener_${id.opener}`, id.owner, `${id.opener}/original`, `${id.opener}/thumb`, t3,+ `att_reply_${id.opener}`, id.reader, `${id.reply}/original`, `${id.reply}/thumb`, childTime,+ `att_pending_${id.opener}`, id.owner, `${id.child}/pending-original`, `${id.child}/pending-thumb`, childTime)+ await run("INSERT INTO community_message_attachment VALUES (?,?,0),(?,?,0)", id.opener, `att_opener_${id.opener}`, id.reply, `att_reply_${id.opener}`)await run(`INSERT INTO community_channel_member(id, channel_id, user_id, relation, source, added_at)@@ -291,7 +286,7 @@ describe("deleteForumPost real D1 batch", () => {)).toEqual({ message_count: 2, last_message_at: t2 });});- it("captures all media keys, repairs parent truth, and cascades only the selected post", async () => {+ it("preserves unreferenced drafts, repairs parent truth, and cascades only the selected post", async () => {const { id, t2 } = await seedCanonicalPost();const db = createDb(runtimeEnv.DB);@@ -303,21 +298,14 @@ describe("deleteForumPost real D1 batch", () => {});expect(result.deleted).toBe(true);- expect(new Set(result.mediaKeys)).toEqual(new Set([- `${id.opener}/original`,- `${id.opener}/thumb`,- `${id.reply}/original`,- `${id.reply}/thumb`,- `${id.child}/pending-original`,- `${id.child}/pending-thumb`,- ]));+ expect(result.mediaKeys).toEqual([]);expect(await first<{ message_count: number; last_message_at: string }>("SELECT message_count, last_message_at FROM community_channel WHERE id = ?",id.forum,)).toEqual({ message_count: 2, last_message_at: t2 });expect(await first("SELECT id FROM community_channel WHERE id = ?", id.child)).toBeNull();expect(await first("SELECT id FROM community_message WHERE id IN (?, ?)", id.opener, id.reply)).toBeNull();- expect(await first("SELECT id FROM community_attachment WHERE target_id = ?", id.child)).toBeNull();+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `att_pending_${id.opener}`)).not.toBeNull();for (const [table, rowId] of [["community_channel_member", `participant_${id.opener}`],["community_read_state", `rs_child_${id.opener}`],@@ -536,7 +524,7 @@ describe("deleteForumPost real D1 batch", () => {]);expect(results.filter((result) => result.deleted)).toHaveLength(1);- expect(results.filter((result) => result.mediaKeys.length > 0)).toHaveLength(1);+ expect(results.every((result) => result.mediaKeys.length === 0)).toBe(true);expect(await first<{ message_count: number; last_message_at: string }>("SELECT message_count, last_message_at FROM community_channel WHERE id = ?",id.forum,