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.
79 lines
2.3 KiB
TypeScript
79 lines
2.3 KiB
TypeScript
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,
|
|
} from "../../create/createFlowUploadValidation";
|
|
|
|
export type SaveCreateFlowUploadResult = {
|
|
/** Filename stem (UUID) without extension — used in GET URL. */
|
|
id: string;
|
|
/** Full relative URL path for clients, e.g. `/api/uploads/abc`. */
|
|
urlPath: string;
|
|
mimeType: string;
|
|
byteLength: number;
|
|
};
|
|
|
|
export type SaveCreateFlowUploadFailure = {
|
|
error: "misconfigured" | "validation";
|
|
reason?: CreateFlowUploadValidationReason;
|
|
};
|
|
|
|
/**
|
|
* Writes bytes under `UPLOAD_ROOT/{id}{ext}` and returns a stable app URL path.
|
|
* Trusts sniffed bytes, not the client-declared MIME type.
|
|
*/
|
|
export async function saveCreateFlowUpload(params: {
|
|
purpose: CreateFlowUploadPurpose;
|
|
buffer: Buffer;
|
|
userId?: string | null;
|
|
}): Promise<SaveCreateFlowUploadResult | SaveCreateFlowUploadFailure> {
|
|
const root = getUploadRootFromEnv();
|
|
if (!root) {
|
|
return { error: "misconfigured" };
|
|
}
|
|
|
|
const { purpose, buffer } = params;
|
|
const validated = validateCreateFlowUploadBytes(purpose, buffer);
|
|
if (validated.ok === false) {
|
|
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, 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: stripped.length,
|
|
};
|
|
}
|