Stop a saved Rule from taking uploads it does not own.
A named path no longer moves another Rules file. Duplicate and Make a copy write their own copies of files they keep.
This commit is contained in:
1 parent
9621fa4d7d
commit
94cee1dc5b
10 files changed
+757
-10
No files matched your search
@@ -9,6 +9,7 @@ import {
|
||||
} from "../../../../../lib/server/responses";
|
||||
import { getSessionUser } from "../../../../../lib/server/session";
|
||||
import { apiRoute } from "../../../../../lib/server/apiRoute";
|
||||
import { copyNamedUploadsForRule } from "../../../../../lib/server/uploads/copyNamedUploads";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -44,6 +45,12 @@ export const POST = apiRoute<RouteContext>(
|
||||
document: source.document,
|
||||
},
|
||||
});
|
||||
await copyNamedUploadsForRule({
|
||||
document: source.document,
|
||||
sourceRuleId: source.id,
|
||||
destRuleId: newRule.id,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
rule: {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
findCopiedNameHit,
|
||||
stripCopiedRuleDocument,
|
||||
} from "../../../../../lib/create/copiedRuleDocument";
|
||||
import { copyNamedUploadsForRule } from "../../../../../lib/server/uploads/copyNamedUploads";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -88,13 +89,19 @@ export const POST = apiRoute<RouteContext>(
|
||||
document: documentParsed.data as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
const document = await copyNamedUploadsForRule({
|
||||
document: documentParsed.data,
|
||||
sourceRuleId: stakeholder.rule.id,
|
||||
destRuleId: newRule.id,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
rule: {
|
||||
id: newRule.id,
|
||||
title: newRule.title,
|
||||
summary: newRule.summary,
|
||||
document: documentParsed.data,
|
||||
document,
|
||||
copiedFromTitle: stakeholder.rule.title,
|
||||
copiedNameHit,
|
||||
createdAt: newRule.createdAt,
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { copyFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import {
|
||||
extractUploadIdsFromUnknown,
|
||||
rewriteUploadIdsInUnknown,
|
||||
} from "./extractUploadIds";
|
||||
import { resolveUploadedFileById } from "./resolveUploadedFile";
|
||||
import { extensionForMime } from "./uploadConstants";
|
||||
import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot";
|
||||
|
||||
type SourceUploadRow = {
|
||||
id: string;
|
||||
mimeType: string;
|
||||
byteLength: number;
|
||||
purpose: string;
|
||||
};
|
||||
|
||||
async function copyOneUpload(opts: {
|
||||
row: SourceUploadRow;
|
||||
root: string;
|
||||
destRuleId: string;
|
||||
userId: string;
|
||||
}): Promise<string | null> {
|
||||
const resolved = await resolveUploadedFileById(opts.row.id);
|
||||
if (!resolved) {
|
||||
logger.warn("[uploads] skip copy; missing file", opts.row.id);
|
||||
return null;
|
||||
}
|
||||
|
||||
const newId = randomUUID();
|
||||
const ext =
|
||||
extensionForMime(opts.row.mimeType) || path.extname(resolved.absolutePath);
|
||||
const destPath = path.join(opts.root, `${newId}${ext}`);
|
||||
|
||||
try {
|
||||
await copyFile(resolved.absolutePath, destPath);
|
||||
await prisma.upload.create({
|
||||
data: {
|
||||
id: newId,
|
||||
mimeType: opts.row.mimeType,
|
||||
byteLength: opts.row.byteLength,
|
||||
purpose: opts.row.purpose,
|
||||
userId: opts.userId,
|
||||
ruleId: opts.destRuleId,
|
||||
},
|
||||
});
|
||||
return newId;
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to copy upload", opts.row.id, err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Give `destRuleId` its own copies of files this document names that belong
|
||||
* to `sourceRuleId`, rewrite paths, and persist the rewritten document.
|
||||
*/
|
||||
export async function copyNamedUploadsForRule(opts: {
|
||||
document: unknown;
|
||||
sourceRuleId: string;
|
||||
destRuleId: string;
|
||||
userId: string;
|
||||
}): Promise<unknown> {
|
||||
const ids = extractUploadIdsFromUnknown(opts.document);
|
||||
if (ids.length === 0) return opts.document;
|
||||
|
||||
const rows = await prisma.upload.findMany({
|
||||
where: { id: { in: ids }, ruleId: opts.sourceRuleId },
|
||||
select: {
|
||||
id: true,
|
||||
mimeType: true,
|
||||
byteLength: true,
|
||||
purpose: true,
|
||||
},
|
||||
});
|
||||
if (rows.length === 0) return opts.document;
|
||||
|
||||
const root = getUploadRootFromEnv();
|
||||
if (!root) {
|
||||
logger.warn("[uploads] skip copy; UPLOAD_ROOT unset");
|
||||
return opts.document;
|
||||
}
|
||||
await ensureUploadRootExists(root);
|
||||
|
||||
const replacements = new Map<string, string>();
|
||||
for (const row of rows) {
|
||||
const copiedId = await copyOneUpload({
|
||||
row,
|
||||
root,
|
||||
destRuleId: opts.destRuleId,
|
||||
userId: opts.userId,
|
||||
});
|
||||
if (copiedId) replacements.set(row.id, copiedId);
|
||||
}
|
||||
if (replacements.size === 0) return opts.document;
|
||||
|
||||
const document = rewriteUploadIdsInUnknown(opts.document, replacements);
|
||||
try {
|
||||
await prisma.publishedRule.update({
|
||||
where: { id: opts.destRuleId },
|
||||
data: { document: document as Prisma.InputJsonValue },
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
"[uploads] failed to persist copied upload paths",
|
||||
opts.destRuleId,
|
||||
err,
|
||||
);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
@@ -3,14 +3,19 @@ import { isValidUploadFileId } from "./uploadConstants";
|
||||
const UPLOAD_PATH_RE =
|
||||
/\/api\/uploads\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/gi;
|
||||
|
||||
function stringifyUnknown(value: unknown): string | null {
|
||||
try {
|
||||
return JSON.stringify(value ?? null);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** UUID stems referenced as `/api/uploads/{id}` inside JSON. */
|
||||
export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
||||
let text: string;
|
||||
try {
|
||||
text = JSON.stringify(value ?? null);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const text = stringifyUnknown(value);
|
||||
if (text == null) return [];
|
||||
UPLOAD_PATH_RE.lastIndex = 0;
|
||||
const ids = new Set<string>();
|
||||
for (const match of text.matchAll(UPLOAD_PATH_RE)) {
|
||||
const id = match[1]?.toLowerCase();
|
||||
@@ -18,3 +23,23 @@ export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/** Rewrite `/api/uploads/{id}` paths using `replacements` (old id → new id). */
|
||||
export function rewriteUploadIdsInUnknown(
|
||||
value: unknown,
|
||||
replacements: ReadonlyMap<string, string>,
|
||||
): unknown {
|
||||
if (replacements.size === 0) return value;
|
||||
const text = stringifyUnknown(value);
|
||||
if (text == null) return value;
|
||||
UPLOAD_PATH_RE.lastIndex = 0;
|
||||
const rewritten = text.replace(UPLOAD_PATH_RE, (full, id: string) => {
|
||||
const next = replacements.get(id.toLowerCase());
|
||||
return next ? `/api/uploads/${next}` : full;
|
||||
});
|
||||
try {
|
||||
return JSON.parse(rewritten) as unknown;
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,67 @@
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import { extractUploadIdsFromUnknown } from "./extractUploadIds";
|
||||
import { browserHoldsUploadGrant } from "./uploadGrantCookie";
|
||||
|
||||
type UploadClaimRow = {
|
||||
id: string;
|
||||
userId: string | null;
|
||||
ruleId: string | null;
|
||||
draftId: string | null;
|
||||
};
|
||||
|
||||
async function loadUploadRows(ids: string[]): Promise<UploadClaimRow[]> {
|
||||
if (ids.length === 0) return [];
|
||||
return prisma.upload.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, userId: true, ruleId: true, draftId: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A save may take a file only when it is unlinked (or already on this Rule)
|
||||
* and was made by this account or browser.
|
||||
*/
|
||||
async function idsClaimableForRule(
|
||||
rows: UploadClaimRow[],
|
||||
opts: { ruleId: string; userId: string | null },
|
||||
): Promise<string[]> {
|
||||
const out: string[] = [];
|
||||
for (const row of rows) {
|
||||
if (row.ruleId != null && row.ruleId !== opts.ruleId) continue;
|
||||
if (row.ruleId === opts.ruleId) {
|
||||
out.push(row.id);
|
||||
continue;
|
||||
}
|
||||
if (opts.userId != null && row.userId === opts.userId) {
|
||||
out.push(row.id);
|
||||
continue;
|
||||
}
|
||||
if (row.userId == null && (await browserHoldsUploadGrant(row.id))) {
|
||||
out.push(row.id);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function idsClaimableForDraft(
|
||||
rows: UploadClaimRow[],
|
||||
opts: { draftId: string; userId: string },
|
||||
): Promise<string[]> {
|
||||
const out: string[] = [];
|
||||
for (const row of rows) {
|
||||
if (row.ruleId != null) continue;
|
||||
if (row.draftId != null && row.draftId !== opts.draftId) continue;
|
||||
if (row.userId === opts.userId) {
|
||||
out.push(row.id);
|
||||
continue;
|
||||
}
|
||||
if (row.userId == null && (await browserHoldsUploadGrant(row.id))) {
|
||||
out.push(row.id);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function linkUploadsToRule(opts: {
|
||||
ruleId: string;
|
||||
@@ -10,8 +71,19 @@ export async function linkUploadsToRule(opts: {
|
||||
const ids = extractUploadIdsFromUnknown(opts.document);
|
||||
if (ids.length === 0) return;
|
||||
try {
|
||||
const rows = await loadUploadRows(ids);
|
||||
const claimable = await idsClaimableForRule(rows, opts);
|
||||
if (claimable.length === 0) return;
|
||||
await prisma.upload.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
where: {
|
||||
id: { in: claimable },
|
||||
AND: [
|
||||
{ OR: [{ ruleId: null }, { ruleId: opts.ruleId }] },
|
||||
opts.userId
|
||||
? { OR: [{ userId: opts.userId }, { userId: null }] }
|
||||
: { userId: null },
|
||||
],
|
||||
},
|
||||
data: {
|
||||
ruleId: opts.ruleId,
|
||||
draftId: null,
|
||||
@@ -31,8 +103,18 @@ export async function linkUploadsToDraft(opts: {
|
||||
const ids = extractUploadIdsFromUnknown(opts.payload);
|
||||
if (ids.length === 0) return;
|
||||
try {
|
||||
const rows = await loadUploadRows(ids);
|
||||
const claimable = await idsClaimableForDraft(rows, opts);
|
||||
if (claimable.length === 0) return;
|
||||
await prisma.upload.updateMany({
|
||||
where: { id: { in: ids }, ruleId: null },
|
||||
where: {
|
||||
id: { in: claimable },
|
||||
ruleId: null,
|
||||
AND: [
|
||||
{ OR: [{ draftId: null }, { draftId: opts.draftId }] },
|
||||
{ OR: [{ userId: opts.userId }, { userId: null }] },
|
||||
],
|
||||
},
|
||||
data: {
|
||||
draftId: opts.draftId,
|
||||
userId: opts.userId,
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const getUploadRootFromEnvMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
const createMock = vi.fn();
|
||||
const updateRuleMock = vi.fn();
|
||||
let uploadRoot: string | null = null;
|
||||
|
||||
vi.mock("../../lib/server/uploads/uploadRoot", async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import("../../lib/server/uploads/uploadRoot")
|
||||
>("../../lib/server/uploads/uploadRoot");
|
||||
return {
|
||||
...actual,
|
||||
getUploadRootFromEnv: () => getUploadRootFromEnvMock(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
upload: {
|
||||
findMany: (...args: unknown[]) => findManyMock(...args),
|
||||
create: (...args: unknown[]) => createMock(...args),
|
||||
},
|
||||
publishedRule: {
|
||||
update: (...args: unknown[]) => updateRuleMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { copyNamedUploadsForRule } from "../../lib/server/uploads/copyNamedUploads";
|
||||
|
||||
const SOURCE_ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const OTHER_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||
const PNG_1X1 = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||
"base64",
|
||||
);
|
||||
|
||||
describe("copyNamedUploadsForRule", () => {
|
||||
beforeEach(async () => {
|
||||
uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-copy-"));
|
||||
getUploadRootFromEnvMock.mockReset();
|
||||
getUploadRootFromEnvMock.mockImplementation(() => uploadRoot);
|
||||
findManyMock.mockReset();
|
||||
createMock.mockReset();
|
||||
updateRuleMock.mockReset();
|
||||
createMock.mockImplementation(async ({ data }: { data: { id: string } }) => data);
|
||||
updateRuleMock.mockResolvedValue({});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
uploadRoot = null;
|
||||
});
|
||||
|
||||
it("copies files owned by the source Rule and rewrites the dest document", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${SOURCE_ID}.png`), PNG_1X1);
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: SOURCE_ID,
|
||||
mimeType: "image/png",
|
||||
byteLength: PNG_1X1.length,
|
||||
purpose: "communityAvatar",
|
||||
},
|
||||
]);
|
||||
|
||||
const document = {
|
||||
communityAvatarUrl: `/api/uploads/${SOURCE_ID}`,
|
||||
leftover: `/api/uploads/${OTHER_ID}`,
|
||||
};
|
||||
const result = (await copyNamedUploadsForRule({
|
||||
document,
|
||||
sourceRuleId: "rule-src",
|
||||
destRuleId: "rule-dest",
|
||||
userId: "user-1",
|
||||
})) as {
|
||||
communityAvatarUrl: string;
|
||||
leftover: string;
|
||||
};
|
||||
|
||||
expect(findManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: { in: [SOURCE_ID, OTHER_ID] }, ruleId: "rule-src" },
|
||||
}),
|
||||
);
|
||||
expect(createMock).toHaveBeenCalledTimes(1);
|
||||
const createdId = createMock.mock.calls[0]![0].data.id as string;
|
||||
expect(createdId).not.toBe(SOURCE_ID);
|
||||
expect(createMock.mock.calls[0]![0].data).toEqual(
|
||||
expect.objectContaining({
|
||||
mimeType: "image/png",
|
||||
purpose: "communityAvatar",
|
||||
userId: "user-1",
|
||||
ruleId: "rule-dest",
|
||||
}),
|
||||
);
|
||||
expect(result.communityAvatarUrl).toBe(`/api/uploads/${createdId}`);
|
||||
expect(result.leftover).toBe(`/api/uploads/${OTHER_ID}`);
|
||||
expect(updateRuleMock).toHaveBeenCalledWith({
|
||||
where: { id: "rule-dest" },
|
||||
data: { document: result },
|
||||
});
|
||||
const files = await readdir(uploadRoot!);
|
||||
expect(files).toContain(`${SOURCE_ID}.png`);
|
||||
expect(files).toContain(`${createdId}.png`);
|
||||
expect(await readFile(path.join(uploadRoot!, `${createdId}.png`))).toEqual(
|
||||
PNG_1X1,
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves the document unchanged when the source Rule owns none of the named files", async () => {
|
||||
const document = { logo: `/api/uploads/${SOURCE_ID}` };
|
||||
findManyMock.mockResolvedValueOnce([]);
|
||||
const result = await copyNamedUploadsForRule({
|
||||
document,
|
||||
sourceRuleId: "rule-src",
|
||||
destRuleId: "rule-dest",
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(result).toBe(document);
|
||||
expect(createMock).not.toHaveBeenCalled();
|
||||
expect(updateRuleMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractUploadIdsFromUnknown } from "../../lib/server/uploads/extractUploadIds";
|
||||
import {
|
||||
extractUploadIdsFromUnknown,
|
||||
rewriteUploadIdsInUnknown,
|
||||
} from "../../lib/server/uploads/extractUploadIds";
|
||||
|
||||
const ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const NEXT = "550e8400-e29b-41d4-a716-446655440001";
|
||||
|
||||
describe("extractUploadIdsFromUnknown", () => {
|
||||
it("collects unique upload ids from nested JSON", () => {
|
||||
@@ -18,3 +22,27 @@ describe("extractUploadIdsFromUnknown", () => {
|
||||
expect(extractUploadIdsFromUnknown({ text: "no files" })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rewriteUploadIdsInUnknown", () => {
|
||||
it("rewrites matching paths and leaves others", () => {
|
||||
expect(
|
||||
rewriteUploadIdsInUnknown(
|
||||
{
|
||||
logo: `/api/uploads/${ID}`,
|
||||
nested: { also: `/api/uploads/${ID}` },
|
||||
other: `/api/uploads/${NEXT}`,
|
||||
},
|
||||
new Map([[ID, "6ba7b810-9dad-41d1-80b4-00c04fd430c8"]]),
|
||||
),
|
||||
).toEqual({
|
||||
logo: "/api/uploads/6ba7b810-9dad-41d1-80b4-00c04fd430c8",
|
||||
nested: { also: "/api/uploads/6ba7b810-9dad-41d1-80b4-00c04fd430c8" },
|
||||
other: `/api/uploads/${NEXT}`,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the original value when there is nothing to replace", () => {
|
||||
const value = { text: "no files" };
|
||||
expect(rewriteUploadIdsInUnknown(value, new Map())).toBe(value);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const findManyMock = vi.fn();
|
||||
const updateManyMock = vi.fn();
|
||||
const browserHoldsUploadGrantMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
upload: {
|
||||
findMany: (...args: unknown[]) => findManyMock(...args),
|
||||
updateMany: (...args: unknown[]) => updateManyMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/uploadGrantCookie", () => ({
|
||||
browserHoldsUploadGrant: (...args: unknown[]) =>
|
||||
browserHoldsUploadGrantMock(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
linkUploadsToDraft,
|
||||
linkUploadsToRule,
|
||||
} from "../../lib/server/uploads/linkUploads";
|
||||
|
||||
const OWNED = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const FOREIGN = "550e8400-e29b-41d4-a716-446655440001";
|
||||
const UNOWNED = "550e8400-e29b-41d4-a716-446655440002";
|
||||
|
||||
beforeEach(() => {
|
||||
findManyMock.mockReset();
|
||||
updateManyMock.mockReset();
|
||||
browserHoldsUploadGrantMock.mockReset();
|
||||
updateManyMock.mockResolvedValue({ count: 0 });
|
||||
browserHoldsUploadGrantMock.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
describe("linkUploadsToRule", () => {
|
||||
it("does not query when the document names no uploads", async () => {
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: { text: "none" },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(findManyMock).not.toHaveBeenCalled();
|
||||
expect(updateManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not take a file already linked to another Rule", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: OWNED,
|
||||
userId: "user-1",
|
||||
ruleId: "rule-other",
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: { logo: `/api/uploads/${OWNED}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not take another account's unlinked file", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: FOREIGN,
|
||||
userId: "user-2",
|
||||
ruleId: null,
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: { logo: `/api/uploads/${FOREIGN}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("links this account's unlinked file and skips a foreign one named beside it", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: OWNED,
|
||||
userId: "user-1",
|
||||
ruleId: null,
|
||||
draftId: "draft-1",
|
||||
},
|
||||
{
|
||||
id: FOREIGN,
|
||||
userId: "user-2",
|
||||
ruleId: "rule-other",
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: {
|
||||
logo: `/api/uploads/${OWNED}`,
|
||||
other: `/api/uploads/${FOREIGN}`,
|
||||
},
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
id: { in: [OWNED] },
|
||||
}),
|
||||
data: expect.objectContaining({
|
||||
ruleId: "rule-1",
|
||||
draftId: null,
|
||||
userId: "user-1",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("links an unowned file when this browser holds the grant", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: UNOWNED,
|
||||
userId: null,
|
||||
ruleId: null,
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
browserHoldsUploadGrantMock.mockResolvedValueOnce(true);
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: { logo: `/api/uploads/${UNOWNED}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(browserHoldsUploadGrantMock).toHaveBeenCalledWith(UNOWNED);
|
||||
expect(updateManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
id: { in: [UNOWNED] },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not take an unowned file without a grant", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: UNOWNED,
|
||||
userId: null,
|
||||
ruleId: null,
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: { logo: `/api/uploads/${UNOWNED}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("may restamp files already on this Rule", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: OWNED,
|
||||
userId: null,
|
||||
ruleId: "rule-1",
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToRule({
|
||||
ruleId: "rule-1",
|
||||
document: { logo: `/api/uploads/${OWNED}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
id: { in: [OWNED] },
|
||||
}),
|
||||
data: expect.objectContaining({
|
||||
ruleId: "rule-1",
|
||||
userId: "user-1",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("linkUploadsToDraft", () => {
|
||||
it("does not take a file already on a Rule", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: OWNED,
|
||||
userId: "user-1",
|
||||
ruleId: "rule-1",
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToDraft({
|
||||
draftId: "draft-1",
|
||||
payload: { logo: `/api/uploads/${OWNED}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not take a file linked to another draft", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: FOREIGN,
|
||||
userId: "user-2",
|
||||
ruleId: null,
|
||||
draftId: "draft-other",
|
||||
},
|
||||
]);
|
||||
await linkUploadsToDraft({
|
||||
draftId: "draft-1",
|
||||
payload: { logo: `/api/uploads/${FOREIGN}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("links this account's unlinked file", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: OWNED,
|
||||
userId: "user-1",
|
||||
ruleId: null,
|
||||
draftId: null,
|
||||
},
|
||||
]);
|
||||
await linkUploadsToDraft({
|
||||
draftId: "draft-1",
|
||||
payload: { logo: `/api/uploads/${OWNED}` },
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(updateManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
id: { in: [OWNED] },
|
||||
}),
|
||||
data: {
|
||||
draftId: "draft-1",
|
||||
userId: "user-1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,12 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/copyNamedUploads", () => ({
|
||||
copyNamedUploadsForRule: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
|
||||
import { POST } from "../../app/api/rules/[id]/duplicate/route";
|
||||
import { copyNamedUploadsForRule } from "../../lib/server/uploads/copyNamedUploads";
|
||||
|
||||
function makeContext(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
@@ -34,6 +39,8 @@ beforeEach(() => {
|
||||
findUniqueMock.mockReset();
|
||||
createMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
vi.mocked(copyNamedUploadsForRule).mockReset();
|
||||
vi.mocked(copyNamedUploadsForRule).mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe("POST /api/rules/[id]/duplicate", () => {
|
||||
@@ -101,5 +108,11 @@ describe("POST /api/rules/[id]/duplicate", () => {
|
||||
const body = (await res.json()) as { rule: { id: string; title: string } };
|
||||
expect(body.rule.id).toBe("r2");
|
||||
expect(body.rule.title).toBe("Original (Copy)");
|
||||
expect(copyNamedUploadsForRule).toHaveBeenCalledWith({
|
||||
document: { x: 1 },
|
||||
sourceRuleId: "r1",
|
||||
destRuleId: "r2",
|
||||
userId: "u1",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,14 @@ vi.mock("../../lib/server/db", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/copyNamedUploads", () => ({
|
||||
copyNamedUploadsForRule: vi.fn(
|
||||
async ({ document }: { document: unknown }) => document,
|
||||
),
|
||||
}));
|
||||
|
||||
import { POST } from "../../app/api/rules/[id]/make-copy/route";
|
||||
import { copyNamedUploadsForRule } from "../../lib/server/uploads/copyNamedUploads";
|
||||
|
||||
const viewer = { id: "user-2", email: "reader@example.com" };
|
||||
const routeCtx = { params: Promise.resolve({ id: "rule-1" }) };
|
||||
@@ -47,6 +54,10 @@ beforeEach(() => {
|
||||
rateLimitKeyMock.mockReset();
|
||||
rateLimitKeyMock.mockReturnValue({ ok: true as const });
|
||||
getSessionUserMock.mockResolvedValue(viewer);
|
||||
vi.mocked(copyNamedUploadsForRule).mockReset();
|
||||
vi.mocked(copyNamedUploadsForRule).mockImplementation(
|
||||
async ({ document }: { document: unknown }) => document,
|
||||
);
|
||||
});
|
||||
|
||||
describe("POST /api/rules/[id]/make-copy", () => {
|
||||
@@ -141,5 +152,86 @@ describe("POST /api/rules/[id]/make-copy", () => {
|
||||
expect(body.rule.id).toBe("rule-copy");
|
||||
expect(body.rule.copiedFromTitle).toBe("Juniper Street Food Share");
|
||||
expect(body.rule.copiedNameHit?.entryTitle).toBe("Care");
|
||||
expect(copyNamedUploadsForRule).toHaveBeenCalledWith({
|
||||
document: expect.not.objectContaining({
|
||||
communityAvatarUrl: "https://example.test/a.png",
|
||||
}),
|
||||
sourceRuleId: "rule-1",
|
||||
destRuleId: "rule-copy",
|
||||
userId: viewer.id,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns copied attachment paths from the new Rule's files", async () => {
|
||||
const ATTACH = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const COPIED = "550e8400-e29b-41d4-a716-446655440099";
|
||||
findFirstStakeholderMock.mockResolvedValueOnce({
|
||||
id: "st-1",
|
||||
rule: {
|
||||
id: "rule-1",
|
||||
title: "Juniper Street Food Share",
|
||||
userId: "owner-1",
|
||||
document: {
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Care",
|
||||
body: "We care.",
|
||||
blocks: [{ assetUrl: `/api/uploads/${ATTACH}` }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
createRuleMock.mockResolvedValueOnce({
|
||||
id: "rule-copy",
|
||||
title: "New group",
|
||||
summary: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00Z"),
|
||||
});
|
||||
vi.mocked(copyNamedUploadsForRule).mockResolvedValueOnce({
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Care",
|
||||
body: "We care.",
|
||||
blocks: [{ assetUrl: `/api/uploads/${COPIED}` }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const res = await POST(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/make-copy", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ title: "New group" }),
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
routeCtx,
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { rule: { document: unknown } };
|
||||
expect(body.rule.document).toEqual({
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Care",
|
||||
body: "We care.",
|
||||
blocks: [{ assetUrl: `/api/uploads/${COPIED}` }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user