395 lines
11 KiB
TypeScript
395 lines
11 KiB
TypeScript
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 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,
|
|
title: true,
|
|
summary: true,
|
|
document: true,
|
|
createdAt: true,
|
|
updatedAt: true,
|
|
} as const;
|
|
|
|
export type PublicPublishedRule = {
|
|
id: string;
|
|
title: string;
|
|
summary: string | null;
|
|
document: unknown;
|
|
createdAt: Date;
|
|
updatedAt: Date;
|
|
/** True only for public-and-featured Rules. */
|
|
isListed: boolean;
|
|
};
|
|
|
|
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. Pass `lookup: "id"`
|
|
* when the caller already has the Rule id but link visitors should still
|
|
* count as readers (file URLs on a shared Rule). Shared-by-link strangers
|
|
* opening the Rule itself 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;
|
|
lookup?: "id" | "shareSlug";
|
|
}): Promise<ReadablePublishedRule | null> {
|
|
if (!isDatabaseConfigured()) return null;
|
|
const idOrSlug = opts.idOrSlug.trim();
|
|
if (idOrSlug.length === 0) return null;
|
|
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
|
|
try {
|
|
const row =
|
|
lookup === "shareSlug"
|
|
? 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,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Metadata for signed-in “my rules” profile list (no full `document` JSON). */
|
|
const PUBLISHED_RULE_OWNER_LIST_SELECT = {
|
|
id: true,
|
|
title: true,
|
|
summary: true,
|
|
createdAt: true,
|
|
updatedAt: true,
|
|
} as const;
|
|
|
|
export type OwnerPublishedRuleListItem = {
|
|
id: string;
|
|
title: string;
|
|
summary: string | null;
|
|
createdAt: Date;
|
|
updatedAt: Date;
|
|
};
|
|
|
|
const LISTED_RULE_SITEMAP_SELECT = {
|
|
id: true,
|
|
updatedAt: true,
|
|
} as const;
|
|
|
|
const LISTED_PUBLISHED_RULE_SITEMAP_CAP = 10_000;
|
|
|
|
/**
|
|
* Public catalog of listed published rules (**most recently updated first**,
|
|
* 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(
|
|
take: number,
|
|
): Promise<OwnerPublishedRuleListItem[] | null> {
|
|
if (!isDatabaseConfigured()) return null;
|
|
const clamped = Math.min(Math.max(0, take), 100);
|
|
if (clamped === 0) return [];
|
|
try {
|
|
return await prisma.publishedRule.findMany({
|
|
where: LISTED_PUBLISHED_RULE_WHERE,
|
|
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
|
|
take: clamped,
|
|
select: PUBLISHED_RULE_OWNER_LIST_SELECT,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Listed published-rule ids for `/sitemap.xml`. Empty when the database is
|
|
* not configured or the query throws (marketing URLs still render).
|
|
*/
|
|
export async function listListedPublishedRulesForSitemap(
|
|
take: number = LISTED_PUBLISHED_RULE_SITEMAP_CAP,
|
|
): Promise<Array<{ id: string; updatedAt: Date }>> {
|
|
if (!isDatabaseConfigured()) return [];
|
|
const clamped = Math.min(
|
|
Math.max(0, take),
|
|
LISTED_PUBLISHED_RULE_SITEMAP_CAP,
|
|
);
|
|
if (clamped === 0) return [];
|
|
try {
|
|
return await prisma.publishedRule.findMany({
|
|
where: LISTED_PUBLISHED_RULE_WHERE,
|
|
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
|
|
take: clamped,
|
|
select: LISTED_RULE_SITEMAP_SELECT,
|
|
});
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Lists published rules owned by the given user (**most recently updated first**,
|
|
* then stable `id` tie-break).
|
|
* Returns `null` when the database is not configured or the query throws.
|
|
*/
|
|
export async function listPublishedRulesForUser(
|
|
userId: string,
|
|
take: number,
|
|
): Promise<OwnerPublishedRuleListItem[] | null> {
|
|
if (!isDatabaseConfigured()) return null;
|
|
if (typeof userId !== "string" || userId.trim() === "") return null;
|
|
const clamped = Math.min(Math.max(0, take), 100);
|
|
if (clamped === 0) return [];
|
|
try {
|
|
return await prisma.publishedRule.findMany({
|
|
where: { userId },
|
|
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
|
|
take: clamped,
|
|
select: PUBLISHED_RULE_OWNER_LIST_SELECT,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export type ProfileRuleListItem = OwnerPublishedRuleListItem & {
|
|
role: "owner" | "stakeholder";
|
|
};
|
|
|
|
/**
|
|
* Published rules the user can access as an **accepted** stakeholder (`userId` set).
|
|
* Same metadata shape as {@link listPublishedRulesForUser}; no `document`.
|
|
*/
|
|
export async function listStakeholderRulesForUser(
|
|
userId: string,
|
|
take: number,
|
|
): Promise<OwnerPublishedRuleListItem[] | null> {
|
|
if (!isDatabaseConfigured()) return null;
|
|
if (typeof userId !== "string" || userId.trim() === "") return null;
|
|
const clamped = Math.min(Math.max(0, take), 100);
|
|
if (clamped === 0) return [];
|
|
try {
|
|
const rows = await prisma.ruleStakeholder.findMany({
|
|
where: { userId },
|
|
take: clamped,
|
|
orderBy: [{ rule: { updatedAt: "desc" } }, { id: "asc" }],
|
|
select: {
|
|
rule: { select: PUBLISHED_RULE_OWNER_LIST_SELECT },
|
|
},
|
|
});
|
|
return rows.map((r) => r.rule);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Profile list: owned rules plus stakeholder access, **owner wins** if both,
|
|
* sorted by `updatedAt` desc (then `id`).
|
|
*/
|
|
export async function listProfileRulesForUser(
|
|
userId: string,
|
|
take: number,
|
|
): Promise<ProfileRuleListItem[] | null> {
|
|
const cap = Math.min(Math.max(0, take), 100);
|
|
if (cap === 0) return [];
|
|
/** Merge then slice so ordering is global by `updatedAt`. */
|
|
const fetchCap = 100;
|
|
const [owned, stakeholderRules] = await Promise.all([
|
|
listPublishedRulesForUser(userId, fetchCap),
|
|
listStakeholderRulesForUser(userId, fetchCap),
|
|
]);
|
|
if (owned === null || stakeholderRules === null) return null;
|
|
const ownerIds = new Set(owned.map((r) => r.id));
|
|
const stakeholderOnly = stakeholderRules.filter((r) => !ownerIds.has(r.id));
|
|
const combined: ProfileRuleListItem[] = [
|
|
...owned.map((r) => ({ ...r, role: "owner" as const })),
|
|
...stakeholderOnly.map((r) => ({
|
|
...r,
|
|
role: "stakeholder" as const,
|
|
})),
|
|
];
|
|
combined.sort((a, b) => {
|
|
const t = b.updatedAt.getTime() - a.updatedAt.getTime();
|
|
if (t !== 0) return t;
|
|
return a.id.localeCompare(b.id);
|
|
});
|
|
return combined.slice(0, cap);
|
|
}
|
|
|
|
export type StakeholderInviteView = {
|
|
ruleId: string;
|
|
title: string;
|
|
summary: string | null;
|
|
document: Record<string, unknown>;
|
|
updatedAt: string;
|
|
inviterEmail: string | null;
|
|
};
|
|
|
|
/**
|
|
* Published rule an accepted stakeholder may read with invited chrome.
|
|
* `userId` is set only after the invite link is used.
|
|
*/
|
|
export async function getAcceptedStakeholderInviteView(opts: {
|
|
userId: string;
|
|
ruleId: string;
|
|
}): Promise<StakeholderInviteView | null> {
|
|
if (!isDatabaseConfigured()) return null;
|
|
const userId = opts.userId.trim();
|
|
const ruleId = opts.ruleId.trim();
|
|
if (userId.length === 0 || ruleId.length === 0) return null;
|
|
try {
|
|
const row = await prisma.ruleStakeholder.findFirst({
|
|
where: { ruleId, userId },
|
|
select: {
|
|
invitedBy: { select: { email: true } },
|
|
rule: {
|
|
select: {
|
|
id: true,
|
|
title: true,
|
|
summary: true,
|
|
document: true,
|
|
updatedAt: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
if (!row) return null;
|
|
const document =
|
|
row.rule.document !== null &&
|
|
typeof row.rule.document === "object" &&
|
|
!Array.isArray(row.rule.document)
|
|
? (row.rule.document as Record<string, unknown>)
|
|
: {};
|
|
return {
|
|
ruleId: row.rule.id,
|
|
title: row.rule.title,
|
|
summary: row.rule.summary,
|
|
document,
|
|
updatedAt: row.rule.updatedAt.toISOString(),
|
|
inviterEmail: row.invitedBy?.email ?? null,
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|