import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; import { and, eq, isNull, sql } from 'drizzle-orm'; import { error } from '@sveltejs/kit'; import { db, tables } from './db/index.ts'; import { chapterLocation, projectAccess, sceneLocation } from './access.ts'; import { PROJECT_SCOPE, loadScopeOptions, scopeAllowsChapter, scopeAllowsScene, scopeExists, scopeOptionLabel, scopeValue, type ContentScope } from './scope.ts'; import { contentTargetColumns, contentTargetFromColumns } from '#lib/content-target.ts'; export function requireOwner(userId: string, projectId: string) { const access = projectAccess(userId, projectId); if (access?.role !== 'owner') error(404, 'No such project.'); return access; } export function inviteMember(ownerId: string, projectId: string, email: string, role: string) { requireOwner(ownerId, projectId); if (role !== 'reader' && role !== 'co_author') error(400, 'Choose a reader or co-author.'); const user = db .select() .from(tables.user) .where(sql`lower(${tables.user.email}) = ${email.trim().toLowerCase()}`) .get(); if (!user || user.id === ownerId || projectAccess(user.id, projectId)) error(400, 'Use the email of an existing account that is not already a member.'); db.insert(tables.projectInvitation) .values({ projectId, userId: user.id, role, expiresAt: new Date(Date.now() + 30 * 86400000) }) .onConflictDoUpdate({ target: [tables.projectInvitation.projectId, tables.projectInvitation.userId], set: { role, expiresAt: new Date(Date.now() + 30 * 86400000) } }) .run(); } export function answerInvitation(userId: string, id: string, accept: boolean) { db.transaction(() => { const invite = db .select() .from(tables.projectInvitation) .where(and(eq(tables.projectInvitation.id, id), eq(tables.projectInvitation.userId, userId))) .get(); if (!invite || invite.expiresAt.getTime() <= Date.now()) error(404, 'No such invitation.'); const project = db .select() .from(tables.project) .where(and(eq(tables.project.id, invite.projectId), isNull(tables.project.deletedAt))) .get(); if (!project) error(404, 'No such invitation.'); if (accept) db.insert(tables.projectMember) .values({ projectId: invite.projectId, userId, role: invite.role }) .onConflictDoNothing() .run(); db.delete(tables.projectInvitation).where(eq(tables.projectInvitation.id, id)).run(); }); } export function pendingInvitations(userId: string) { return db .select({ id: tables.projectInvitation.id, title: tables.project.title, role: tables.projectInvitation.role }) .from(tables.projectInvitation) .innerJoin(tables.project, eq(tables.project.id, tables.projectInvitation.projectId)) .where( and( eq(tables.projectInvitation.userId, userId), isNull(tables.project.deletedAt), sql`${tables.projectInvitation.expiresAt} > ${Date.now()}` ) ) .all(); } export function changeMember(ownerId: string, projectId: string, userId: string, role: string) { requireOwner(ownerId, projectId); if (!['reader', 'co_author', 'remove'].includes(role)) error(400, 'Choose a reader or co-author.'); const where = and( eq(tables.projectMember.projectId, projectId), eq(tables.projectMember.userId, userId), sql`${tables.projectMember.role} != 'owner'` ); if (role === 'remove') db.delete(tables.projectMember).where(where).run(); else db.update(tables.projectMember) .set({ role: role as 'reader' | 'co_author' }) .where(where) .run(); } export type SharePermission = 'read' | 'comment' | 'edit'; export function createShare( ownerId: string, projectId: string, label: string, permission: string, days: number, scope: ContentScope = PROJECT_SCOPE ) { requireOwner(ownerId, projectId); if (!['read', 'comment', 'edit'].includes(permission) || ![1, 7, 30, 90].includes(days)) error(400, 'Choose a permission and an expiry.'); if (!scopeExists(projectId, scope)) error(400, 'Choose a book, chapter, or scene from this project.'); const name = label.trim().slice(0, 120) || 'Secret link'; const key = randomBytes(32).toString('hex'); const id = crypto.randomUUID(); const expiresAt = new Date(Date.now() + days * 86400000); db.insert(tables.projectShare) .values({ id, projectId, bookId: scope.kind === 'book' ? scope.bookId : null, chapterId: scope.kind === 'chapter' ? scope.chapterId : null, sceneId: scope.kind === 'scene' ? scope.sceneId : null, label: name, permission: permission as SharePermission, keyHash: hash(key), expiresAt }) .run(); return { id, key, label: name, permission: permission as SharePermission, expiresAt, scope }; } /** The three scope columns name at most one node. A corrupt pair is no link. */ export function shareScope( row: Pick ): ContentScope | null { if ([row.bookId, row.chapterId, row.sceneId].filter(Boolean).length > 1) return null; if (row.sceneId) return { kind: 'scene', sceneId: row.sceneId }; if (row.chapterId) return { kind: 'chapter', chapterId: row.chapterId }; if (row.bookId) return { kind: 'book', bookId: row.bookId }; return PROJECT_SCOPE; } function hash(key: string) { return createHash('sha256').update(key).digest('hex'); } export function shareAccess(id: string, key: string | undefined) { if (!key || !/^[a-f0-9]{64}$/.test(key)) return null; const row = db .select({ share: tables.projectShare, title: tables.project.title }) .from(tables.projectShare) .innerJoin(tables.project, eq(tables.project.id, tables.projectShare.projectId)) .where( and( eq(tables.projectShare.id, id), isNull(tables.projectShare.revokedAt), isNull(tables.project.deletedAt) ) ) .get(); if ( !row || row.share.expiresAt.getTime() <= Date.now() || !timingSafeEqual(Buffer.from(row.share.keyHash, 'hex'), Buffer.from(hash(key), 'hex')) ) return null; // A link to a part that has been deleted or moved out of the project is as // unavailable as an expired one. const scope = shareScope(row.share); if (!scope || !scopeExists(row.share.projectId, scope)) return null; return { ...row.share, title: row.title, scope }; } export function revokeShare(ownerId: string, projectId: string, id: string) { requireOwner(ownerId, projectId); db.update(tables.projectShare) .set({ revokedAt: new Date() }) .where(and(eq(tables.projectShare.id, id), eq(tables.projectShare.projectId, projectId))) .run(); } export function sharingDetails(ownerId: string, projectId: string) { requireOwner(ownerId, projectId); const scopeOptions = loadScopeOptions(projectId); return { members: db .select({ id: tables.projectMember.userId, name: tables.user.name, email: tables.user.email, role: tables.projectMember.role }) .from(tables.projectMember) .innerJoin(tables.user, eq(tables.user.id, tables.projectMember.userId)) .where(eq(tables.projectMember.projectId, projectId)) .all(), invitations: db .select({ id: tables.projectInvitation.id, email: tables.user.email, role: tables.projectInvitation.role, expiresAt: tables.projectInvitation.expiresAt }) .from(tables.projectInvitation) .innerJoin(tables.user, eq(tables.user.id, tables.projectInvitation.userId)) .where(eq(tables.projectInvitation.projectId, projectId)) .all(), shares: db .select({ id: tables.projectShare.id, bookId: tables.projectShare.bookId, chapterId: tables.projectShare.chapterId, sceneId: tables.projectShare.sceneId, label: tables.projectShare.label, permission: tables.projectShare.permission, expiresAt: tables.projectShare.expiresAt, revokedAt: tables.projectShare.revokedAt }) .from(tables.projectShare) .where(eq(tables.projectShare.projectId, projectId)) .all() .map((row) => { const scope = shareScope(row); const value = scope ? scopeValue(scope) : 'project'; return { id: row.id, label: row.label, permission: row.permission, expiresAt: row.expiresAt, revokedAt: row.revokedAt, scopeValue: value, scopeLabel: scope ? scope.kind === 'project' ? 'Whole project' : (scopeOptionLabel(scopeOptions, value) ?? 'Unavailable') : 'Unavailable' }; }), scopeOptions }; } export function addFeedback( projectId: string, sceneId: string | null, author: string, input: { message: string; quote: string; suggestion: string; revision: number; chapterId?: string | null; anchorStart?: number | null; }, shareId: string | null = null, scope: ContentScope = PROJECT_SCOPE ) { const target = contentTargetFromColumns({ sceneId, chapterId: input.chapterId }); if (!target) error(400, 'Choose one scene or chapter.'); if (target.kind === 'scene') { const location = sceneLocation(target.id); if (!location || location.projectId !== projectId || !scopeAllowsScene(scope, location)) error(404, 'No such scene.'); } if (target.kind === 'chapter') { const location = chapterLocation(target.id); if (!location || location.projectId !== projectId || !scopeAllowsChapter(scope, location)) error(404, 'No such chapter.'); } if ( !author.trim() || author.length > 80 || !input.message.trim() || input.message.length > 10000 || input.quote.length > 4000 || input.suggestion.length > 10000 || !Number.isInteger(input.revision) || input.revision < 0 ) error(400, 'Enter a name and feedback within the field limits.'); const scene = target.kind === 'scene' ? db.select().from(tables.scene).where(eq(tables.scene.id, target.id)).get()! : null; if (scene && scene.revision !== input.revision) error(409, 'The scene changed. Reload before leaving feedback.'); if (target.kind === 'chapter' && (input.quote || input.suggestion || input.anchorStart != null)) error(400, 'Chapter feedback cannot name a passage or replacement.'); if (input.quote && !scene?.bodyText.includes(input.quote)) error(400, 'That passage is no longer in this scene.'); const anchorStart = input.anchorStart ?? null; if ( anchorStart !== null && (!Number.isSafeInteger(anchorStart) || anchorStart < 0 || !input.quote || scene?.bodyText.slice(anchorStart, anchorStart + input.quote.length) !== input.quote) ) error(400, 'That passage is no longer in this scene.'); const anchorPrefix = anchorStart !== null ? scene!.bodyText.slice(Math.max(0, anchorStart - 48), anchorStart) : ''; const anchorSuffix = anchorStart !== null ? scene!.bodyText.slice( anchorStart + input.quote.length, anchorStart + input.quote.length + 48 ) : ''; if ( db .select({ count: sql`count(*)` }) .from(tables.sceneFeedback) .where(eq(tables.sceneFeedback.projectId, projectId)) .get()!.count >= 10000 ) error(400, 'This project has reached its feedback limit.'); return db .insert(tables.sceneFeedback) .values({ projectId, ...contentTargetColumns(target), author: author.trim(), message: input.message, quote: input.quote, suggestion: input.suggestion, revision: input.revision, anchorStart, anchorPrefix, anchorSuffix, shareId }) .returning({ id: tables.sceneFeedback.id }) .get()!; } export function listFeedback(projectId: string, shareId?: string) { return db .select() .from(tables.sceneFeedback) .where( and( eq(tables.sceneFeedback.projectId, projectId), shareId ? eq(tables.sceneFeedback.shareId, shareId) : undefined ) ) .all(); } export function moderateFeedback(userId: string, projectId: string, id: string, remove: boolean) { const access = projectAccess(userId, projectId); if (!access || access.role === 'reader') error(404, 'No such project.'); const where = and(eq(tables.sceneFeedback.id, id), eq(tables.sceneFeedback.projectId, projectId)); if (remove) db.delete(tables.sceneFeedback).where(where).run(); else db.update(tables.sceneFeedback).set({ resolved: true }).where(where).run(); }