/** * Shared previews (WEBSITE-1.0-PLAN ยง4): a link for someone without an account (the pastor), that * shows the working copy as it is when opened, for 7 days or until revoked. It can't edit or * publish, and its pages are `noindex`. Only the token's hash is stored; the link is shown once. */ import type { Ctx } from '../context.js'; import { ApiError } from '../http.js'; import { audit } from '../lib/audit.js'; import { hashToken, randomToken } from '../lib/crypto.js'; export const PREVIEW_DAYS = 7; export async function createPreviewLink(ctx: Ctx, by: { id: string; role: string }) { const token = randomToken(); const now = ctx.now(); const row = await ctx.db.previewLink.create({ data: { tokenHash: hashToken(token), createdBy: by.id, createdAt: now, expiresAt: new Date(now.getTime() + PREVIEW_DAYS * 864e5) } }); await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_created', targetType: 'preview_link', targetId: row.id }); return { id: row.id, url: `${ctx.config.publicUrl}/preview/${token}`, expiresAt: row.expiresAt.toISOString() }; } export async function listPreviewLinks(ctx: Ctx) { const now = ctx.now(); const rows = await ctx.db.previewLink.findMany({ orderBy: { createdAt: 'desc' } }); const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name])); return rows.map((r) => ({ id: r.id, createdAt: r.createdAt.toISOString(), expiresAt: r.expiresAt.toISOString(), by: names.get(r.createdBy) ?? null, active: !r.revokedAt && r.expiresAt > now, revokedAt: r.revokedAt?.toISOString() ?? null, })); } export async function revokePreviewLink(ctx: Ctx, id: string, by: { id: string; role: string }) { const row = await ctx.db.previewLink.findUnique({ where: { id } }); if (!row) throw new ApiError(404, 'NOT_FOUND', 'That preview link doesn\'t exist.'); await ctx.db.previewLink.update({ where: { id }, data: { revokedAt: ctx.now() } }); await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_revoked', targetType: 'preview_link', targetId: id }); } export async function previewTokenValid(ctx: Ctx, token: string | undefined): Promise { if (!token || token.length > 200) return false; const row = await ctx.db.previewLink.findUnique({ where: { tokenHash: hashToken(token) } }); return !!row && !row.revokedAt && row.expiresAt > ctx.now(); }