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.
66 lines
1.7 KiB
TypeScript
66 lines
1.7 KiB
TypeScript
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;
|
|
}
|
|
}
|