import { and, eq, isNotNull, isNull, or } from 'drizzle-orm'; import { error, fail } from '@sveltejs/kit'; import type { ActionFailure, RequestEvent } from '@sveltejs/kit'; import { db, tables } from './db/index.ts'; import { requireWriter, type Writer } from './guard.ts'; import { failure } from './save-request.ts'; import type { ContentTarget } from '#lib/content-target.ts'; /** * Who can do what to a project and to the rows inside it. Every check in the app * comes from here, and no route builds its own membership query: copies drift * apart and one eventually forgets a deleted row. * * A snapshot, a plot card or a note arrives as a bare id, which says nothing * about the project it belongs to. Checking only the outer project lets a * crafted request name someone else's card inside your own project's URL. * * Access comes from the `project_member` row, not `project.owner_id`: it is * written when a project is created and is the only source of truth. */ export type ProjectRole = 'owner' | 'co_author' | 'reader'; export type Need = 'read' | 'write'; /** The project fields a guarded page reads. */ export type ProjectSummary = { id: string; title: string; subtitle: string | null; isExample: boolean; }; export type Granted = { ok: true; user: Writer; project: ProjectSummary; role: ProjectRole; }; /** A refusal a form action can hand back unchanged. */ export type ActionGuard = Granted | { ok: false; response: ActionFailure<{ message: string }> }; /** A refusal an API route can hand back unchanged. */ export type ApiGuard = Granted | { ok: false; response: Response }; type Refusal = { ok: false; status: 401 | 404; message: string }; /** A missing membership row never passes, whatever the need. */ export function roleAllows(role: ProjectRole | null | undefined, need: Need): boolean { if (!role) return false; if (need === 'read') return true; return role === 'owner' || role === 'co_author'; } /** * The writer's role in one live project, or null. Only the library restore and * purge actions pass `deleted`, and that lookup requires the owner role. */ export function projectAccess( userId: string, projectId: string, deleted = false ): { project: ProjectSummary; role: ProjectRole } | null { const row = db .select({ id: tables.project.id, title: tables.project.title, subtitle: tables.project.subtitle, isExample: tables.project.isExample, role: tables.projectMember.role }) .from(tables.project) .innerJoin(tables.projectMember, eq(tables.projectMember.projectId, tables.project.id)) .where( and( eq(tables.project.id, projectId), eq(tables.projectMember.userId, userId), deleted ? isNotNull(tables.project.deletedAt) : isNull(tables.project.deletedAt) ) ) .get(); if (!row || (deleted && row.role !== 'owner')) return null; return { project: { id: row.id, title: row.title, subtitle: row.subtitle, isExample: row.isExample }, role: row.role }; } /** The one decision every guard shares. */ function decide( user: Writer | undefined, projectId: string, need: Need, message: string ): Granted | Refusal { if (!user) return { ok: false, status: 401, message: 'Not signed in.' }; const access = projectAccess(user.id, projectId); /* * A stranger and a member whose role is too low get the same answer, so a * guessed id never confirms a project exists. The resource guards reuse this, * which is why a missing card and a foreign one both read as "No such card." */ if (!access || !roleAllows(access.role, need)) return { ok: false, status: 404, message }; return { ok: true, user, ...access }; } /** * The workspace and the plot grid are editing surfaces, so they ask for write * access and refuse a reader: neither has a read-only view. */ export function requireProject( event: Pick, projectId: string, need: Need = 'write' ): Granted { const user = requireWriter(event); const decision = decide(user, projectId, need, 'No such project.'); if (!decision.ok) error(decision.status, decision.message); return decision; } export function requireProjectAction( event: Pick, projectId: string, need: Need = 'write' ): ActionGuard { const user = requireWriter(event); const decision = decide(user, projectId, need, 'No such project.'); if (!decision.ok) return { ok: false, response: fail(decision.status, { message: decision.message }) }; return decision; } export function requireDeletedProjectAction( event: Pick, projectId: string ): ActionGuard { const user = requireWriter(event); const access = projectAccess(user.id, projectId, true); if (!access) return { ok: false, response: fail(404, { message: 'No such project.' }) }; return { ok: true, user, ...access }; } export function requireProjectApi( event: Pick, projectId: string, need: Need = 'write' ): ApiGuard { const decision = decide(event.locals.user, projectId, need, 'No such project.'); if (!decision.ok) return { ok: false, response: failure(decision.status, decision.message) }; return decision; } /* * Each lookup below joins through the parent chain and ignores a soft-deleted * row, so an id captured before a delete cannot reach the deleted node. A * function that checks membership takes the project first, so the two ids cannot * be swapped by accident. */ /** Where a live scene sits. A scope check needs the ids, not only the project. */ export type SceneLocation = { projectId: string; bookId: string; chapterId: string; sceneId: string; }; export function sceneLocation(sceneId: string): SceneLocation | null { return ( db .select({ projectId: tables.book.projectId, bookId: tables.chapter.bookId, chapterId: tables.scene.chapterId, sceneId: tables.scene.id }) .from(tables.scene) .innerJoin(tables.chapter, eq(tables.chapter.id, tables.scene.chapterId)) .innerJoin(tables.book, eq(tables.book.id, tables.chapter.bookId)) .leftJoin(tables.part, eq(tables.part.id, tables.chapter.partId)) .innerJoin(tables.project, eq(tables.project.id, tables.book.projectId)) .where( and( eq(tables.scene.id, sceneId), isNull(tables.scene.deletedAt), isNull(tables.chapter.deletedAt), isNull(tables.book.deletedAt), isNull(tables.project.deletedAt), or( isNull(tables.chapter.partId), and(eq(tables.part.bookId, tables.book.id), isNull(tables.part.deletedAt)) ) ) ) .get() ?? null ); } /** Where a live chapter sits. */ export type ChapterLocation = { projectId: string; bookId: string; chapterId: string; }; export function chapterLocation(chapterId: string): ChapterLocation | null { return ( db .select({ projectId: tables.book.projectId, bookId: tables.chapter.bookId, chapterId: tables.chapter.id }) .from(tables.chapter) .innerJoin(tables.book, eq(tables.book.id, tables.chapter.bookId)) .leftJoin(tables.part, eq(tables.part.id, tables.chapter.partId)) .innerJoin(tables.project, eq(tables.project.id, tables.book.projectId)) .where( and( eq(tables.chapter.id, chapterId), isNull(tables.chapter.deletedAt), isNull(tables.book.deletedAt), isNull(tables.project.deletedAt), or( isNull(tables.chapter.partId), and(eq(tables.part.bookId, tables.book.id), isNull(tables.part.deletedAt)) ) ) ) .get() ?? null ); } /** The live project a scene sits in, through chapter and book. */ export function projectIdOfScene(sceneId: string): string | null { return sceneLocation(sceneId)?.projectId ?? null; } export function projectIdOfChapter(chapterId: string): string | null { return chapterLocation(chapterId)?.projectId ?? null; } export function projectIdOfNote(noteId: string): string | null { const row = db .select({ projectId: tables.note.projectId }) .from(tables.note) .innerJoin(tables.project, eq(tables.project.id, tables.note.projectId)) .where( and( eq(tables.note.id, noteId), isNull(tables.note.deletedAt), isNull(tables.project.deletedAt) ) ) .get(); return row?.projectId ?? null; } /** A type with no project is not reachable. */ export function projectIdOfNoteType(noteTypeId: string): string | null { const row = db .select({ projectId: tables.noteType.projectId }) .from(tables.noteType) .innerJoin(tables.project, eq(tables.project.id, tables.noteType.projectId)) .where(and(eq(tables.noteType.id, noteTypeId), isNull(tables.project.deletedAt))) .get(); return row?.projectId ?? null; } /** A card is reached through its storyline. */ export function projectIdOfStoryline(storylineId: string): string | null { const row = db .select({ projectId: tables.storyline.projectId }) .from(tables.storyline) .innerJoin(tables.project, eq(tables.project.id, tables.storyline.projectId)) .where( and( eq(tables.storyline.id, storylineId), isNull(tables.storyline.deletedAt), isNull(tables.project.deletedAt) ) ) .get(); return row?.projectId ?? null; } export function sceneInProject(projectId: string, sceneId: string): boolean { return projectIdOfScene(sceneId) === projectId; } export function chapterInProject(projectId: string, chapterId: string): boolean { return projectIdOfChapter(chapterId) === projectId; } export function contentTargetInProject(projectId: string, target: ContentTarget): boolean { return target.kind === 'scene' ? sceneInProject(projectId, target.id) : chapterInProject(projectId, target.id); } export function noteTypeInProject(projectId: string, noteTypeId: string): boolean { return projectIdOfNoteType(noteTypeId) === projectId; } /** * Checks inside an active write transaction whether a user currently holds * write membership on a live project. Used after async request parsing so * revocations or demotions between admission and commit cannot leak writes. */ export function canWriteProject(userId: string, projectId: string): boolean { const access = projectAccess(userId, projectId); return access !== null && roleAllows(access.role, 'write'); } /* * The API routes that take a bare scene, note or note-type id hide "not yours" * behind the same 404 as "not there". */ export function requireSceneWriteApi( event: Pick, sceneId: string ): ApiGuard { return requireResourceWriteApi(event, projectIdOfScene(sceneId), 'No such scene.'); } export function requireNoteWriteApi(event: Pick, noteId: string): ApiGuard { return requireResourceWriteApi(event, projectIdOfNote(noteId), 'No such note.'); } export function requireNoteTypeWriteApi( event: Pick, noteTypeId: string ): ApiGuard { return requireResourceWriteApi(event, projectIdOfNoteType(noteTypeId), 'No such note type.'); } function requireResourceWriteApi( event: Pick, projectId: string | null, message: string ): ApiGuard { // The empty id finds no project, so a missing row and a foreign row take the // same 404 with the same wording. const decision = decide(event.locals.user, projectId ?? '', 'write', message); if (!decision.ok) return { ok: false, response: failure(decision.status, decision.message) }; return decision; }