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:
adilallo committed 2026-11-09 19:54:04 -07:00
1 parent 642551064c
commit 5cbda35e32
50 files changed
+2429 -219

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
import { logger } from "../logger";
import { prisma } from "./db";
/** Best-effort audit row. Never throws to the caller. */
export async function logAdminRuleRead(opts: {
ruleId: string;
adminEmail: string;
adminUserId: string | null;
path: string;
}): Promise<void> {
try {
await prisma.adminRuleReadLog.create({
data: {
ruleId: opts.ruleId,
adminEmail: opts.adminEmail.trim().toLowerCase(),
adminUserId: opts.adminUserId,
path: opts.path.slice(0, 500),
},
});
} catch (err) {
logger.warn("[admin-rule-read] failed to write log", err);
}
}
+10
View File
@@ -29,3 +29,13 @@ export function getSmtpUrl(): string | undefined {
export function isDatabaseConfigured(): boolean {
return Boolean(getDatabaseUrl());
}
/** Named admins who may open a private Rule. Comma-separated emails. */
export function getRuleAdminEmails(): string[] {
const raw = process.env.RULE_ADMIN_EMAILS?.trim();
if (!raw) return [];
return raw
.split(",")
.map((item) => item.trim().toLowerCase())
.filter((item) => item.length > 0);
}
+27
View File
@@ -69,6 +69,33 @@ async function clearGuestRuleClaimCookie(): Promise<void> {
});
}
/** True when this browser's claim cookie hashes to `claimTokenHash`. */
export async function browserHoldsClaimForHash(
claimTokenHash: string | null | undefined,
): Promise<boolean> {
if (typeof claimTokenHash !== "string" || claimTokenHash.length === 0) {
return false;
}
try {
const store = await cookies();
const tokens = parseClaimTokens(
store.get(GUEST_RULE_CLAIM_COOKIE_NAME)?.value,
);
if (tokens.length === 0) return false;
let pepper: string;
try {
pepper = getSessionPepper();
} catch {
return false;
}
return tokens.some(
(token) => hashRuleClaimToken(token, pepper) === claimTokenHash,
);
} catch {
return false;
}
}
/**
* Attach ownerless published rules whose claim secrets are in this browser's
* cookie to `userId`, then drop the cookie. Never throws to the caller.
+138 -32
View File
@@ -1,14 +1,22 @@
import type { User } from "@prisma/client";
import {
LISTED_PUBLISHED_RULE_WHERE,
canReadPublishedRule,
isListedPublishedRule,
isPrivilegedAdminRead,
type RuleVisibility,
} from "../publishedRuleAccess";
import { prisma } from "./db";
import { isDatabaseConfigured } from "./env";
import { browserHoldsClaimForHash } from "./guestRuleClaim";
import { isRuleAdminEmail } from "./ruleAdmins";
import { logAdminRuleRead } from "./adminRuleReadLog";
/**
* Public fields safe to expose via the unauthenticated rule detail surfaces
* (`GET /api/rules/[id]` and `/rules/[id]`). `userId` and `claimTokenHash`
* stay server-side; callers get {@link PublicPublishedRule.isListed} instead.
* Public fields safe to expose via readable rule detail surfaces
* (`GET /api/rules/[id]` and `/rules/[id]` / `/r/[shareSlug]`).
* `userId` and `claimTokenHash` stay server-side; callers get
* {@link PublicPublishedRule.isListed} instead.
*/
const PUBLISHED_RULE_PUBLIC_SELECT = {
id: true,
@@ -26,38 +34,136 @@ export type PublicPublishedRule = {
document: unknown;
createdAt: Date;
updatedAt: Date;
/** False for guest-claim rows; true for owned and orphaned-after-delete rows. */
/** True only for public-and-featured Rules. */
isListed: boolean;
};
/**
* Fetch a single published rule by id for public read surfaces.
*
* Returns `null` when the database is not configured, the id does not match
* any row, or the query throws — callers render a 404 in all missing cases
* and are expected to surface the "DB not configured" state separately if
* they care about distinguishing it (the API route does; the page does not).
*/
export async function getPublicPublishedRuleById(
id: string,
): Promise<PublicPublishedRule | null> {
if (!isDatabaseConfigured()) return null;
if (typeof id !== "string" || id.trim() === "") return null;
try {
const rule = await prisma.publishedRule.findUnique({
where: { id },
select: {
...PUBLISHED_RULE_PUBLIC_SELECT,
userId: true,
claimTokenHash: true,
},
export type ReadablePublishedRule = {
rule: PublicPublishedRule;
viewerIsOwner: boolean;
visibility: RuleVisibility;
shareSlug: string | null;
};
const RULE_ACCESS_SELECT = {
...PUBLISHED_RULE_PUBLIC_SELECT,
userId: true,
claimTokenHash: true,
visibility: true,
shareSlug: true,
stakeholders: {
select: { email: true, userId: true },
},
} as const;
function toPublicRule(row: {
id: string;
title: string;
summary: string | null;
document: unknown;
createdAt: Date;
updatedAt: Date;
visibility: RuleVisibility;
}): PublicPublishedRule {
return {
id: row.id,
title: row.title,
summary: row.summary,
document: row.document,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
isListed: isListedPublishedRule({ visibility: row.visibility }),
};
}
async function resolveAccessForRow(opts: {
row: {
id: string;
title: string;
summary: string | null;
document: unknown;
createdAt: Date;
updatedAt: Date;
userId: string | null;
claimTokenHash: string | null;
visibility: RuleVisibility;
shareSlug: string | null;
stakeholders: Array<{ email: string; userId: string | null }>;
};
viaShareSlug: boolean;
user: User | null;
requestPath: string;
}): Promise<ReadablePublishedRule | null> {
const { row, viaShareSlug, user, requestPath } = opts;
const viewerEmail = user?.email.trim().toLowerCase() ?? null;
const invitedEmails = row.stakeholders.map((s) => s.email.toLowerCase());
const invitedUserIds = row.stakeholders
.map((s) => s.userId)
.filter((id): id is string => typeof id === "string" && id.length > 0);
const isAdmin = isRuleAdminEmail(user?.email ?? null);
const holdsGuestClaim = await browserHoldsClaimForHash(row.claimTokenHash);
const access = {
visibility: row.visibility,
viaShareSlug,
userId: user?.id ?? null,
ownerUserId: row.userId,
viewerEmail,
invitedEmails,
invitedUserIds,
isAdmin,
holdsGuestClaim,
};
if (!canReadPublishedRule(access)) return null;
if (isPrivilegedAdminRead(access) && viewerEmail) {
await logAdminRuleRead({
ruleId: row.id,
adminEmail: viewerEmail,
adminUserId: user?.id ?? null,
path: requestPath,
});
}
return {
rule: toPublicRule(row),
viewerIsOwner: user != null && row.userId === user.id,
visibility: row.visibility,
shareSlug: row.shareSlug,
};
}
/**
* Fetch a published rule the viewer is allowed to read.
*
* Lookup is by internal id unless `viaShareSlug` is set. Shared-by-link
* strangers must use the rotating slug so turning the link off invalidates it.
* Returns `null` for missing rows, denied readers, and DB failures — callers
* render the same 404 as a missing Rule.
*/
export async function getReadablePublishedRule(opts: {
idOrSlug: string;
user: User | null;
viaShareSlug: boolean;
requestPath: string;
}): Promise<ReadablePublishedRule | null> {
if (!isDatabaseConfigured()) return null;
const idOrSlug = opts.idOrSlug.trim();
if (idOrSlug.length === 0) return null;
try {
const row = opts.viaShareSlug
? await prisma.publishedRule.findUnique({
where: { shareSlug: idOrSlug },
select: RULE_ACCESS_SELECT,
})
: await prisma.publishedRule.findUnique({
where: { id: idOrSlug },
select: RULE_ACCESS_SELECT,
});
if (!row) return null;
return resolveAccessForRow({
row,
viaShareSlug: opts.viaShareSlug,
user: opts.user,
requestPath: opts.requestPath,
});
if (!rule) return null;
const { userId, claimTokenHash, ...publicFields } = rule;
return {
...publicFields,
isListed: isListedPublishedRule({ userId, claimTokenHash }),
};
} catch {
return null;
}
@@ -89,7 +195,7 @@ const LISTED_PUBLISHED_RULE_SITEMAP_CAP = 10_000;
/**
* Public catalog of listed published rules (**most recently updated first**,
* then stable `id` tie-break). Guest-claim rows are omitted.
* then stable `id` tie-break). Only public-and-featured rows.
* Returns `null` when the database is not configured or the query throws.
*/
export async function listListedPublishedRules(
+8
View File
@@ -0,0 +1,8 @@
import { getRuleAdminEmails } from "./env";
export function isRuleAdminEmail(email: string | null | undefined): boolean {
if (typeof email !== "string") return false;
const needle = email.trim().toLowerCase();
if (needle.length === 0) return false;
return getRuleAdminEmails().includes(needle);
}
+167
View File
@@ -0,0 +1,167 @@
import type { User } from "@prisma/client";
import { RULE_VISIBILITY, type RuleVisibility } from "../ruleVisibility";
import {
emailInitials,
type RuleShareSettings,
type SharePerson,
} from "../ruleShareTypes";
import { formatShareUrlDisplay, shareCopyUrl } from "../sharePaths";
import { prisma } from "./db";
import { isRuleAdminEmail } from "./ruleAdmins";
import { allocateShareSlug } from "./shareSlug";
function toShareSettings(opts: {
visibility: RuleVisibility;
shareSlug: string | null;
title: string;
origin: string;
ruleId: string;
ownerEmail: string;
readers: SharePerson[];
}): RuleShareSettings {
const shareUrl = shareCopyUrl({
origin: opts.origin,
ruleId: opts.ruleId,
shareSlug: opts.shareSlug,
visibility: opts.visibility,
});
const shareUrlDisplay =
opts.shareSlug &&
(opts.visibility === RULE_VISIBILITY.shared_by_link ||
opts.visibility === RULE_VISIBILITY.public_and_featured)
? formatShareUrlDisplay(opts.origin, opts.shareSlug)
: null;
return {
visibility: opts.visibility,
shareSlug: opts.shareSlug,
shareUrl,
shareUrlDisplay,
title: opts.title,
ownerEmail: opts.ownerEmail,
ownerInitials: emailInitials(opts.ownerEmail),
readers: opts.readers,
copyEnabled: true,
};
}
export async function getOwnedRuleShareSettings(opts: {
ruleId: string;
user: User;
origin: string;
}): Promise<RuleShareSettings | "not_found" | "forbidden"> {
const row = await prisma.publishedRule.findUnique({
where: { id: opts.ruleId },
select: {
id: true,
title: true,
userId: true,
visibility: true,
shareSlug: true,
user: { select: { email: true } },
stakeholders: {
select: { email: true },
orderBy: [{ invitedAt: "asc" }, { id: "asc" }],
},
},
});
if (!row) return "not_found";
const isOwner = row.userId === opts.user.id;
const isAdmin = isRuleAdminEmail(opts.user.email);
if (!isOwner && !isAdmin) return "forbidden";
const ownerEmail = (
row.user?.email ?? opts.user.email
)
.trim()
.toLowerCase();
const readers: SharePerson[] = row.stakeholders
.map((s) => s.email.trim().toLowerCase())
.filter((email) => email.length > 0 && email !== ownerEmail)
.map((email) => ({
email,
initials: emailInitials(email),
role: "reader" as const,
}));
return toShareSettings({
visibility: row.visibility,
shareSlug: row.shareSlug,
title: row.title,
origin: opts.origin,
ruleId: row.id,
ownerEmail,
readers,
});
}
export async function patchOwnedRuleShare(opts: {
ruleId: string;
user: User;
origin: string;
visibility: RuleVisibility;
communityAgreed?: boolean;
}): Promise<
| { ok: true; settings: RuleShareSettings }
| { ok: false; reason: "not_found" | "forbidden" | "community_agreed" }
> {
const row = await prisma.publishedRule.findUnique({
where: { id: opts.ruleId },
select: {
id: true,
userId: true,
visibility: true,
shareSlug: true,
},
});
if (!row) return { ok: false, reason: "not_found" };
const isOwner = row.userId === opts.user.id;
const isAdmin = isRuleAdminEmail(opts.user.email);
if (!isOwner && !isAdmin) return { ok: false, reason: "forbidden" };
if (
opts.visibility === RULE_VISIBILITY.public_and_featured &&
!isAdmin
) {
return { ok: false, reason: "forbidden" };
}
if (
opts.visibility === RULE_VISIBILITY.shared_by_link &&
row.visibility !== RULE_VISIBILITY.shared_by_link &&
row.visibility !== RULE_VISIBILITY.public_and_featured &&
opts.communityAgreed !== true
) {
return { ok: false, reason: "community_agreed" };
}
if (!isOwner && opts.visibility !== RULE_VISIBILITY.public_and_featured) {
return { ok: false, reason: "forbidden" };
}
let shareSlug = row.shareSlug;
if (opts.visibility === RULE_VISIBILITY.private) {
shareSlug = null;
} else if (
opts.visibility === RULE_VISIBILITY.shared_by_link &&
(row.visibility === RULE_VISIBILITY.private || shareSlug == null)
) {
shareSlug = await allocateShareSlug();
}
await prisma.publishedRule.update({
where: { id: row.id },
data: {
visibility: opts.visibility,
shareSlug,
},
});
const settings = await getOwnedRuleShareSettings({
ruleId: row.id,
user: opts.user,
origin: opts.origin,
});
if (settings === "not_found" || settings === "forbidden") {
return { ok: false, reason: settings };
}
return { ok: true, settings };
}
+32
View File
@@ -0,0 +1,32 @@
import { randomBytes } from "node:crypto";
import { isShareSlug } from "../sharePaths";
import { prisma } from "./db";
/** Unambiguous lowercase alphabet (no 0/o/1/i/l). */
const SHARE_SLUG_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
function randomChunk(length: number): string {
const bytes = randomBytes(length);
let out = "";
for (let i = 0; i < length; i += 1) {
out += SHARE_SLUG_ALPHABET[bytes[i]! % SHARE_SLUG_ALPHABET.length];
}
return out;
}
export function generateShareSlug(): string {
return `${randomChunk(4)}-${randomChunk(4)}`;
}
export async function allocateShareSlug(): Promise<string> {
for (let attempt = 0; attempt < 8; attempt += 1) {
const shareSlug = generateShareSlug();
if (!isShareSlug(shareSlug)) continue;
const existing = await prisma.publishedRule.findUnique({
where: { shareSlug },
select: { id: true },
});
if (!existing) return shareSlug;
}
throw new Error("Could not allocate a unique share slug");
}
+77
View File
@@ -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);
}
+20
View File
@@ -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];
}
+44
View File
@@ -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);
}
}
+21 -2
View File
@@ -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,
};
}
+86
View File
@@ -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);
}
+65
View File
@@ -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;
}
}
@@ -219,6 +219,13 @@ export const publishRuleBodySchema = z.object({
export type PublishRuleBody = z.infer<typeof publishRuleBodySchema>;
export const patchRuleShareBodySchema = z.object({
visibility: z.enum(["private", "shared_by_link", "public_and_featured"]),
communityAgreed: z.boolean().optional(),
});
export type PatchRuleShareBody = z.infer<typeof patchRuleShareBodySchema>;
export const postRuleStakeholderBodySchema = z.object({
email: stakeholderEmailSchema,
});