Start every Rule private, with a rotating link and files that follow its readers.
New Rules stay off lists until the person who holds the pen turns on a share link, or the team features one. Uploaded files are readable only by those readers, stripped of location metadata, and deleted with the Rule, draft, or account.
This commit is contained in:
1 parent
642551064c
commit
5cbda35e32
50 files changed
+2429
-219
No files matched your search
@@ -0,0 +1,77 @@
|
||||
import { unlink } from "node:fs/promises";
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import { resolveUploadedFileById } from "./resolveUploadedFile";
|
||||
|
||||
async function unlinkResolved(id: string): Promise<void> {
|
||||
const resolved = await resolveUploadedFileById(id);
|
||||
if (!resolved) return;
|
||||
try {
|
||||
await unlink(resolved.absolutePath);
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to unlink file", id, err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteDiskFilesForUploadIds(
|
||||
ids: string[],
|
||||
): Promise<void> {
|
||||
const unique = [...new Set(ids)];
|
||||
for (const id of unique) {
|
||||
await unlinkResolved(id);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteUploadsForRule(ruleId: string): Promise<void> {
|
||||
const rows = await prisma.upload.findMany({
|
||||
where: { ruleId },
|
||||
select: { id: true },
|
||||
});
|
||||
await deleteDiskFilesForUploadIds(rows.map((r) => r.id));
|
||||
}
|
||||
|
||||
export async function deleteUploadsForDraft(draftId: string): Promise<void> {
|
||||
const rows = await prisma.upload.findMany({
|
||||
where: { draftId },
|
||||
select: { id: true },
|
||||
});
|
||||
await deleteDiskFilesForUploadIds(rows.map((r) => r.id));
|
||||
}
|
||||
|
||||
export async function deleteUploadsForUser(userId: string): Promise<void> {
|
||||
const [ownedRules, draft, ownedUploads] = await Promise.all([
|
||||
prisma.publishedRule.findMany({
|
||||
where: { userId },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.ruleDraft.findUnique({
|
||||
where: { userId },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.upload.findMany({
|
||||
where: { userId },
|
||||
select: { id: true },
|
||||
}),
|
||||
]);
|
||||
const ruleIds = ownedRules.map((r) => r.id);
|
||||
const [ruleUploads, draftUploads] = await Promise.all([
|
||||
ruleIds.length === 0
|
||||
? Promise.resolve([] as Array<{ id: string }>)
|
||||
: prisma.upload.findMany({
|
||||
where: { ruleId: { in: ruleIds } },
|
||||
select: { id: true },
|
||||
}),
|
||||
draft
|
||||
? prisma.upload.findMany({
|
||||
where: { draftId: draft.id },
|
||||
select: { id: true },
|
||||
})
|
||||
: Promise.resolve([] as Array<{ id: string }>),
|
||||
]);
|
||||
const ids = [
|
||||
...ownedUploads.map((r) => r.id),
|
||||
...ruleUploads.map((r) => r.id),
|
||||
...draftUploads.map((r) => r.id),
|
||||
];
|
||||
await deleteDiskFilesForUploadIds(ids);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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;
|
||||
|
||||
/** 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 ids = new Set<string>();
|
||||
for (const match of text.matchAll(UPLOAD_PATH_RE)) {
|
||||
const id = match[1]?.toLowerCase();
|
||||
if (id && isValidUploadFileId(id)) ids.add(id);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import { extractUploadIdsFromUnknown } from "./extractUploadIds";
|
||||
|
||||
export async function linkUploadsToRule(opts: {
|
||||
ruleId: string;
|
||||
document: unknown;
|
||||
userId: string | null;
|
||||
}): Promise<void> {
|
||||
const ids = extractUploadIdsFromUnknown(opts.document);
|
||||
if (ids.length === 0) return;
|
||||
try {
|
||||
await prisma.upload.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: {
|
||||
ruleId: opts.ruleId,
|
||||
draftId: null,
|
||||
...(opts.userId ? { userId: opts.userId } : {}),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to link uploads to rule", opts.ruleId, err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function linkUploadsToDraft(opts: {
|
||||
draftId: string;
|
||||
payload: unknown;
|
||||
userId: string;
|
||||
}): Promise<void> {
|
||||
const ids = extractUploadIdsFromUnknown(opts.payload);
|
||||
if (ids.length === 0) return;
|
||||
try {
|
||||
await prisma.upload.updateMany({
|
||||
where: { id: { in: ids }, ruleId: null },
|
||||
data: {
|
||||
draftId: opts.draftId,
|
||||
userId: opts.userId,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to link uploads to draft", opts.draftId, err);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import type { CreateFlowUploadPurpose } from "./uploadConstants";
|
||||
import { extensionForMime } from "./uploadConstants";
|
||||
import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot";
|
||||
import { stripImageMetadata } from "./stripImageMetadata";
|
||||
import {
|
||||
validateCreateFlowUploadBytes,
|
||||
type CreateFlowUploadValidationReason,
|
||||
@@ -30,6 +33,7 @@ export type SaveCreateFlowUploadFailure = {
|
||||
export async function saveCreateFlowUpload(params: {
|
||||
purpose: CreateFlowUploadPurpose;
|
||||
buffer: Buffer;
|
||||
userId?: string | null;
|
||||
}): Promise<SaveCreateFlowUploadResult | SaveCreateFlowUploadFailure> {
|
||||
const root = getUploadRootFromEnv();
|
||||
if (!root) {
|
||||
@@ -42,18 +46,33 @@ export async function saveCreateFlowUpload(params: {
|
||||
return { error: "validation", reason: validated.reason };
|
||||
}
|
||||
|
||||
const stripped = stripImageMetadata(buffer, validated.mimeType);
|
||||
const id = randomUUID();
|
||||
const ext = extensionForMime(validated.mimeType);
|
||||
const fileName = `${id}${ext}`;
|
||||
const absolutePath = path.join(root, fileName);
|
||||
|
||||
await ensureUploadRootExists(root);
|
||||
await writeFile(absolutePath, buffer, { mode: 0o644 });
|
||||
await writeFile(absolutePath, stripped, { mode: 0o644 });
|
||||
|
||||
try {
|
||||
await prisma.upload.create({
|
||||
data: {
|
||||
id,
|
||||
mimeType: validated.mimeType,
|
||||
byteLength: stripped.length,
|
||||
purpose,
|
||||
userId: params.userId ?? null,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to record upload row", id, err);
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
urlPath: `/api/uploads/${id}`,
|
||||
mimeType: validated.mimeType,
|
||||
byteLength: buffer.length,
|
||||
byteLength: stripped.length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Strip GPS/author metadata from image bytes. JPEG APP1 (EXIF) and PNG
|
||||
* text / eXIf chunks are dropped. Other types are returned unchanged.
|
||||
*/
|
||||
export function stripImageMetadata(buffer: Buffer, mimeType: string): Buffer {
|
||||
const mime = mimeType.toLowerCase().split(";")[0]?.trim() ?? "";
|
||||
if (mime === "image/jpeg" || mime === "image/jpg") {
|
||||
return stripJpegExif(buffer);
|
||||
}
|
||||
if (mime === "image/png") {
|
||||
return stripPngMetadata(buffer);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function stripJpegExif(buffer: Buffer): Buffer {
|
||||
if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) {
|
||||
return buffer;
|
||||
}
|
||||
const out: Buffer[] = [buffer.subarray(0, 2)];
|
||||
let i = 2;
|
||||
while (i + 3 < buffer.length) {
|
||||
if (buffer[i] !== 0xff) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
const marker = buffer[i + 1]!;
|
||||
if (marker === 0xda) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
if (marker === 0xd9) {
|
||||
out.push(buffer.subarray(i, i + 2));
|
||||
break;
|
||||
}
|
||||
if (marker >= 0xd0 && marker <= 0xd7) {
|
||||
out.push(buffer.subarray(i, i + 2));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (marker === 0x01 || marker === 0xd8) {
|
||||
out.push(buffer.subarray(i, i + 2));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (i + 3 >= buffer.length) break;
|
||||
const size = buffer.readUInt16BE(i + 2);
|
||||
const next = i + 2 + size;
|
||||
if (size < 2 || next > buffer.length) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
const isApp1 = marker === 0xe1;
|
||||
const isApp13 = marker === 0xed;
|
||||
if (!isApp1 && !isApp13) {
|
||||
out.push(buffer.subarray(i, next));
|
||||
}
|
||||
i = next;
|
||||
}
|
||||
return Buffer.concat(out);
|
||||
}
|
||||
|
||||
function stripPngMetadata(buffer: Buffer): Buffer {
|
||||
const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
if (buffer.length < 16 || !buffer.subarray(0, 8).equals(sig)) {
|
||||
return buffer;
|
||||
}
|
||||
const skip = new Set(["tEXt", "iTXt", "zTXt", "eXIf", "tIME"]);
|
||||
const out: Buffer[] = [buffer.subarray(0, 8)];
|
||||
let i = 8;
|
||||
while (i + 12 <= buffer.length) {
|
||||
const length = buffer.readUInt32BE(i);
|
||||
const type = buffer.subarray(i + 4, i + 8).toString("ascii");
|
||||
const chunkEnd = i + 12 + length;
|
||||
if (chunkEnd > buffer.length) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
if (!skip.has(type)) {
|
||||
out.push(buffer.subarray(i, chunkEnd));
|
||||
}
|
||||
i = chunkEnd;
|
||||
if (type === "IEND") break;
|
||||
}
|
||||
return Buffer.concat(out);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { isValidUploadFileId } from "./uploadConstants";
|
||||
|
||||
const UPLOAD_GRANT_COOKIE_NAME = "cr_upload_grant";
|
||||
const MAX_GRANT_IDS = 16;
|
||||
const COOKIE_MAX_AGE_SEC = 60 * 60 * 24 * 30;
|
||||
|
||||
function cookieOptions(): {
|
||||
httpOnly: true;
|
||||
secure: boolean;
|
||||
sameSite: "lax";
|
||||
path: "/";
|
||||
maxAge: number;
|
||||
} {
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: COOKIE_MAX_AGE_SEC,
|
||||
};
|
||||
}
|
||||
|
||||
function parseGrantIds(raw: string | undefined): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
const ids: string[] = [];
|
||||
for (const item of parsed) {
|
||||
if (typeof item !== "string") continue;
|
||||
if (!isValidUploadFileId(item)) continue;
|
||||
ids.push(item.toLowerCase());
|
||||
}
|
||||
return ids.slice(-MAX_GRANT_IDS);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function issueGuestUploadGrantCookie(id: string): Promise<void> {
|
||||
if (!isValidUploadFileId(id)) return;
|
||||
const store = await cookies();
|
||||
const existing = parseGrantIds(store.get(UPLOAD_GRANT_COOKIE_NAME)?.value);
|
||||
const next = [
|
||||
...existing.filter((item) => item !== id),
|
||||
id.toLowerCase(),
|
||||
].slice(-MAX_GRANT_IDS);
|
||||
store.set(
|
||||
UPLOAD_GRANT_COOKIE_NAME,
|
||||
JSON.stringify(next),
|
||||
cookieOptions(),
|
||||
);
|
||||
}
|
||||
|
||||
export async function browserHoldsUploadGrant(id: string): Promise<boolean> {
|
||||
if (!isValidUploadFileId(id)) return false;
|
||||
try {
|
||||
const store = await cookies();
|
||||
const ids = parseGrantIds(store.get(UPLOAD_GRANT_COOKIE_NAME)?.value);
|
||||
return ids.includes(id.toLowerCase());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user