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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user