A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
refactor: split models into repos and services for feed, highlights, webhooks and importSessions (#2613)
Mohamed Bassemddd578cc70ba
diff --git a/packages/trpc/lib/actor.ts b/packages/trpc/lib/actor.tsnew file mode 100644index 00000000..f7921629--- /dev/null+++ b/packages/trpc/lib/actor.ts@@ -0,0 +1,76 @@+import { TRPCError } from "@trpc/server";++import type { AuthedContext } from "../index";++// --- Actor ---++export type Actor =+ | { type: "user"; userId: string; role: "admin" | "user" | null }+ | { type: "system"; userId: string };++export function actorUserId(actor: Actor): string {+ return actor.userId;+}++export function actorFromContext(ctx: AuthedContext): Actor {+ return {+ type: "user",+ userId: ctx.user.id,+ role: ctx.user.role,+ };+}++// --- Authorization checks ---++export function assertOwnership(+ actor: Actor,+ resourceUserId: string,+ opts?: { notFoundOnDeny?: boolean; notFoundMessage?: string },+): void {+ if (actorUserId(actor) === resourceUserId) {+ return;+ }++ if (opts?.notFoundOnDeny) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: opts.notFoundMessage ?? "Resource not found",+ });+ }++ throw new TRPCError({+ code: "FORBIDDEN",+ message: "User is not allowed to access resource",+ });+}++// --- Branded types for compile-time authz enforcement ---++declare const __access: unique symbol;++/**+ * A resource that has been verified for a specific access level.+ * Can only be created via the `authorize()` function after an authz check.+ *+ * For simple ownership: `Authorized<Feed>` (defaults to "owner")+ * For role-based access: `Authorized<List, "editor">`, `Authorized<List, "viewer">`+ */+export type Authorized<T, Access extends string = "owner"> = T & {+ readonly [__access]: Access;+};++/**+ * Brands a resource as authorized for a specific access level.+ * Takes an authorization check as an argument — the check is executed+ * before the resource is branded, making it impossible to skip.+ *+ * @param resource - The resource to authorize+ * @param check - The authorization check to perform (can be sync or async)+ */+export async function authorize<T, Access extends string = "owner">(+ resource: T,+ check: () => void | Promise<void>,+): Promise<Authorized<T, Access>> {+ await check();+ return resource as Authorized<T, Access>;+}diff --git a/packages/trpc/models/feeds.repo.ts b/packages/trpc/models/feeds.repo.tsnew file mode 100644index 00000000..d4ed3e02--- /dev/null+++ b/packages/trpc/models/feeds.repo.ts@@ -0,0 +1,79 @@+import { count, eq } from "drizzle-orm";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import { rssFeedsTable } from "@karakeep/db/schema";+import {+ zNewFeedSchema,+ zUpdateFeedSchema,+} from "@karakeep/shared/types/feeds";++type Feed = typeof rssFeedsTable.$inferSelect;++export class FeedsRepo {+ constructor(private db: DB) {}++ async get(id: string): Promise<Feed | null> {+ const feed = await this.db.query.rssFeedsTable.findFirst({+ where: eq(rssFeedsTable.id, id),+ });+ return feed ?? null;+ }++ async create(+ userId: string,+ input: z.infer<typeof zNewFeedSchema>,+ ): Promise<Feed> {+ const [result] = await this.db+ .insert(rssFeedsTable)+ .values({+ name: input.name,+ url: input.url,+ userId,+ enabled: input.enabled,+ importTags: input.importTags ?? false,+ })+ .returning();++ return result;+ }++ async countByUser(userId: string): Promise<number> {+ const [result] = await this.db+ .select({ count: count() })+ .from(rssFeedsTable)+ .where(eq(rssFeedsTable.userId, userId));+ return result.count;+ }++ async getAll(userId: string): Promise<Feed[]> {+ return await this.db.query.rssFeedsTable.findMany({+ where: eq(rssFeedsTable.userId, userId),+ });+ }++ async delete(id: string): Promise<boolean> {+ const res = await this.db+ .delete(rssFeedsTable)+ .where(eq(rssFeedsTable.id, id));+ return res.changes > 0;+ }++ async update(+ id: string,+ input: z.infer<typeof zUpdateFeedSchema>,+ ): Promise<Feed | null> {+ const result = await this.db+ .update(rssFeedsTable)+ .set({+ name: input.name,+ url: input.url,+ enabled: input.enabled,+ importTags: input.importTags,+ })+ .where(eq(rssFeedsTable.id, id))+ .returning();++ return result[0] ?? null;+ }+}diff --git a/packages/trpc/models/feeds.service.ts b/packages/trpc/models/feeds.service.tsnew file mode 100644index 00000000..6b1799dc--- /dev/null+++ b/packages/trpc/models/feeds.service.ts@@ -0,0 +1,74 @@+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import type { rssFeedsTable } from "@karakeep/db/schema";+import serverConfig from "@karakeep/shared/config";+import {+ zNewFeedSchema,+ zUpdateFeedSchema,+} from "@karakeep/shared/types/feeds";++import type { Actor, Authorized } from "../lib/actor";+import { actorUserId, assertOwnership, authorize } from "../lib/actor";+import { FeedsRepo } from "./feeds.repo";++type Feed = typeof rssFeedsTable.$inferSelect;++export class FeedsService {+ private repo: FeedsRepo;++ constructor(db: DB) {+ this.repo = new FeedsRepo(db);+ }++ async get(actor: Actor, id: string): Promise<Authorized<Feed>> {+ const feed = await this.repo.get(id);+ if (!feed) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Feed not found",+ });+ }+ return authorize(feed, () => assertOwnership(actor, feed.userId));+ }++ async create(+ actor: Actor,+ input: z.infer<typeof zNewFeedSchema>,+ ): Promise<Feed> {+ const userId = actorUserId(actor);+ const feedCount = await this.repo.countByUser(userId);+ const maxFeeds = serverConfig.feeds.maxRssFeedsPerUser;+ if (feedCount >= maxFeeds) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Maximum number of RSS feeds (${maxFeeds}) reached`,+ });+ }++ return await this.repo.create(userId, input);+ }++ async update(+ feed: Authorized<Feed>,+ input: z.infer<typeof zUpdateFeedSchema>,+ ): Promise<Feed> {+ const updated = await this.repo.update(feed.id, input);+ if (!updated) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }+ return updated;+ }++ async getAll(actor: Actor): Promise<Feed[]> {+ return await this.repo.getAll(actorUserId(actor));+ }++ async delete(feed: Authorized<Feed>): Promise<void> {+ const deleted = await this.repo.delete(feed.id);+ if (!deleted) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }+ }+}diff --git a/packages/trpc/models/feeds.ts b/packages/trpc/models/feeds.tsdeleted file mode 100644index ea22da8f..00000000--- a/packages/trpc/models/feeds.ts+++ /dev/null@@ -1,126 +0,0 @@-import { TRPCError } from "@trpc/server";-import { and, count, eq } from "drizzle-orm";-import { z } from "zod";--import { rssFeedsTable } from "@karakeep/db/schema";-import serverConfig from "@karakeep/shared/config";-import {- zFeedSchema,- zNewFeedSchema,- zUpdateFeedSchema,-} from "@karakeep/shared/types/feeds";--import { AuthedContext } from "..";--export class Feed {- constructor(- protected ctx: AuthedContext,- private feed: typeof rssFeedsTable.$inferSelect,- ) {}-- static async fromId(ctx: AuthedContext, id: string): Promise<Feed> {- const feed = await ctx.db.query.rssFeedsTable.findFirst({- where: eq(rssFeedsTable.id, id),- });-- if (!feed) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Feed not found",- });- }-- // If it exists but belongs to another user, throw forbidden error- if (feed.userId !== ctx.user.id) {- throw new TRPCError({- code: "FORBIDDEN",- message: "User is not allowed to access resource",- });- }-- return new Feed(ctx, feed);- }-- static async create(- ctx: AuthedContext,- input: z.infer<typeof zNewFeedSchema>,- ): Promise<Feed> {- // Check if user has reached the maximum number of feeds- const [feedCount] = await ctx.db- .select({ count: count() })- .from(rssFeedsTable)- .where(eq(rssFeedsTable.userId, ctx.user.id));-- const maxFeeds = serverConfig.feeds.maxRssFeedsPerUser;- if (feedCount.count >= maxFeeds) {- throw new TRPCError({- code: "BAD_REQUEST",- message: `Maximum number of RSS feeds (${maxFeeds}) reached`,- });- }-- const [result] = await ctx.db- .insert(rssFeedsTable)- .values({- name: input.name,- url: input.url,- userId: ctx.user.id,- enabled: input.enabled,- importTags: input.importTags ?? false,- })- .returning();-- return new Feed(ctx, result);- }-- static async getAll(ctx: AuthedContext): Promise<Feed[]> {- const feeds = await ctx.db.query.rssFeedsTable.findMany({- where: eq(rssFeedsTable.userId, ctx.user.id),- });-- return feeds.map((f) => new Feed(ctx, f));- }-- async delete(): Promise<void> {- const res = await this.ctx.db- .delete(rssFeedsTable)- .where(- and(- eq(rssFeedsTable.id, this.feed.id),- eq(rssFeedsTable.userId, this.ctx.user.id),- ),- );-- if (res.changes === 0) {- throw new TRPCError({ code: "NOT_FOUND" });- }- }-- async update(input: z.infer<typeof zUpdateFeedSchema>): Promise<void> {- const result = await this.ctx.db- .update(rssFeedsTable)- .set({- name: input.name,- url: input.url,- enabled: input.enabled,- importTags: input.importTags,- })- .where(- and(- eq(rssFeedsTable.id, this.feed.id),- eq(rssFeedsTable.userId, this.ctx.user.id),- ),- )- .returning();-- if (result.length === 0) {- throw new TRPCError({ code: "NOT_FOUND" });- }-- this.feed = result[0];- }-- asPublicFeed(): z.infer<typeof zFeedSchema> {- return this.feed;- }-}diff --git a/packages/trpc/models/highlights.ts b/packages/trpc/models/highlights.repo.tssimilarity index 51%rename from packages/trpc/models/highlights.tsrename to packages/trpc/models/highlights.repo.tsindex 76651c3e..60563c4b 100644--- a/packages/trpc/models/highlights.ts+++ b/packages/trpc/models/highlights.repo.ts@@ -1,7 +1,7 @@-import { TRPCError } from "@trpc/server";import { and, desc, eq, like, lt, lte, or } from "drizzle-orm";import { z } from "zod";+import type { DB } from "@karakeep/db";import { highlights } from "@karakeep/db/schema";import {zHighlightSchema,@@ -10,43 +10,23 @@ import {} from "@karakeep/shared/types/highlights";import { zCursorV2 } from "@karakeep/shared/types/pagination";-import { AuthedContext } from "..";-import { BareBookmark } from "./bookmarks";+type Highlight = z.infer<typeof zHighlightSchema>;-export class Highlight {- constructor(- protected ctx: AuthedContext,- private highlight: typeof highlights.$inferSelect,- ) {}+export class HighlightsRepo {+ constructor(private db: DB) {}- static async fromId(ctx: AuthedContext, id: string): Promise<Highlight> {- const highlight = await ctx.db.query.highlights.findFirst({+ async get(id: string): Promise<Highlight | null> {+ const highlight = await this.db.query.highlights.findFirst({where: eq(highlights.id, id),});-- if (!highlight) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Highlight not found",- });- }-- // If it exists but belongs to another user, throw forbidden error- if (highlight.userId !== ctx.user.id) {- throw new TRPCError({- code: "FORBIDDEN",- message: "User is not allowed to access resource",- });- }-- return new Highlight(ctx, highlight);+ return highlight ?? null;}- static async create(- ctx: AuthedContext,+ async create(+ userId: string,input: z.infer<typeof zNewHighlightSchema>,): Promise<Highlight> {- const [result] = await ctx.db+ const [result] = await this.db.insert(highlights).values({bookmarkId: input.bookmarkId,@@ -55,36 +35,31 @@ export class Highlight {color: input.color,text: input.text,note: input.note,- userId: ctx.user.id,+ userId,}).returning();- return new Highlight(ctx, result);+ return result;}- static async getForBookmark(- ctx: AuthedContext,- bookmark: BareBookmark,- ): Promise<Highlight[]> {- const results = await ctx.db.query.highlights.findMany({- where: eq(highlights.bookmarkId, bookmark.id),+ async getForBookmark(bookmarkId: string): Promise<Highlight[]> {+ return await this.db.query.highlights.findMany({+ where: eq(highlights.bookmarkId, bookmarkId),orderBy: [desc(highlights.createdAt), desc(highlights.id)],});-- return results.map((h) => new Highlight(ctx, h));}- static async getAll(- ctx: AuthedContext,+ async getAll(+ userId: string,cursor?: z.infer<typeof zCursorV2> | null,limit = 50,): Promise<{highlights: Highlight[];nextCursor: z.infer<typeof zCursorV2> | null;}> {- const results = await ctx.db.query.highlights.findMany({+ const results = await this.db.query.highlights.findMany({where: and(- eq(highlights.userId, ctx.user.id),+ eq(highlights.userId, userId),cursor? or(lt(highlights.createdAt, cursor.createdAt),@@ -108,14 +83,11 @@ export class Highlight {};}- return {- highlights: results.map((h) => new Highlight(ctx, h)),- nextCursor,- };+ return { highlights: results, nextCursor };}- static async search(- ctx: AuthedContext,+ async search(+ userId: string,searchText: string,cursor?: z.infer<typeof zCursorV2> | null,limit = 50,@@ -124,9 +96,9 @@ export class Highlight {nextCursor: z.infer<typeof zCursorV2> | null;}> {const searchPattern = `%${searchText}%`;- const results = await ctx.db.query.highlights.findMany({+ const results = await this.db.query.highlights.findMany({where: and(- eq(highlights.userId, ctx.user.id),+ eq(highlights.userId, userId),or(like(highlights.text, searchPattern),like(highlights.note, searchPattern),@@ -154,53 +126,31 @@ export class Highlight {};}- return {- highlights: results.map((h) => new Highlight(ctx, h)),- nextCursor,- };+ return { highlights: results, nextCursor };}- async delete(): Promise<z.infer<typeof zHighlightSchema>> {- const result = await this.ctx.db+ async delete(id: string): Promise<Highlight | null> {+ const result = await this.db.delete(highlights)- .where(- and(- eq(highlights.id, this.highlight.id),- eq(highlights.userId, this.ctx.user.id),- ),- )+ .where(eq(highlights.id, id)).returning();- if (result.length === 0) {- throw new TRPCError({ code: "NOT_FOUND" });- }-- return result[0];+ return result[0] ?? null;}- async update(input: z.infer<typeof zUpdateHighlightSchema>): Promise<void> {- const result = await this.ctx.db+ async update(+ id: string,+ input: z.infer<typeof zUpdateHighlightSchema>,+ ): Promise<Highlight | null> {+ const result = await this.db.update(highlights).set({color: input.color,note: input.note,})- .where(- and(- eq(highlights.id, this.highlight.id),- eq(highlights.userId, this.ctx.user.id),- ),- )+ .where(eq(highlights.id, id)).returning();- if (result.length === 0) {- throw new TRPCError({ code: "NOT_FOUND" });- }-- this.highlight = result[0];- }-- asPublicHighlight(): z.infer<typeof zHighlightSchema> {- return this.highlight;+ return result[0] ?? null;}}diff --git a/packages/trpc/models/highlights.service.ts b/packages/trpc/models/highlights.service.tsnew file mode 100644index 00000000..b972a05e--- /dev/null+++ b/packages/trpc/models/highlights.service.ts@@ -0,0 +1,93 @@+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import {+ zHighlightSchema,+ zNewHighlightSchema,+ zUpdateHighlightSchema,+} from "@karakeep/shared/types/highlights";+import { zCursorV2 } from "@karakeep/shared/types/pagination";++import type { Actor, Authorized } from "../lib/actor";+import { actorUserId, assertOwnership, authorize } from "../lib/actor";+import { HighlightsRepo } from "./highlights.repo";++type Highlight = z.infer<typeof zHighlightSchema>;++export class HighlightsService {+ private repo: HighlightsRepo;++ constructor(db: DB) {+ this.repo = new HighlightsRepo(db);+ }++ async get(actor: Actor, id: string): Promise<Authorized<Highlight>> {+ const highlight = await this.repo.get(id);+ if (!highlight) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Highlight not found",+ });+ }+ return authorize(highlight, () => assertOwnership(actor, highlight.userId));+ }++ async create(+ actor: Actor,+ input: z.infer<typeof zNewHighlightSchema>,+ ): Promise<Highlight> {+ return await this.repo.create(actorUserId(actor), input);+ }++ async getForBookmark(bookmarkId: string): Promise<Highlight[]> {+ return await this.repo.getForBookmark(bookmarkId);+ }++ async getAll(+ actor: Actor,+ cursor?: z.infer<typeof zCursorV2> | null,+ limit = 50,+ ): Promise<{+ highlights: Highlight[];+ nextCursor: z.infer<typeof zCursorV2> | null;+ }> {+ return await this.repo.getAll(actorUserId(actor), cursor, limit);+ }++ async search(+ actor: Actor,+ searchText: string,+ cursor?: z.infer<typeof zCursorV2> | null,+ limit = 50,+ ): Promise<{+ highlights: Highlight[];+ nextCursor: z.infer<typeof zCursorV2> | null;+ }> {+ return await this.repo.search(+ actorUserId(actor),+ searchText,+ cursor,+ limit,+ );+ }++ async delete(highlight: Authorized<Highlight>): Promise<Highlight> {+ const deleted = await this.repo.delete(highlight.id);+ if (!deleted) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }+ return deleted;+ }++ async update(+ highlight: Authorized<Highlight>,+ input: z.infer<typeof zUpdateHighlightSchema>,+ ): Promise<Highlight> {+ const updated = await this.repo.update(highlight.id, input);+ if (!updated) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }+ return updated;+ }+}diff --git a/packages/trpc/models/importSessions.repo.ts b/packages/trpc/models/importSessions.repo.tsnew file mode 100644index 00000000..9f6daedd--- /dev/null+++ b/packages/trpc/models/importSessions.repo.ts@@ -0,0 +1,124 @@+import { and, count, eq, gt } from "drizzle-orm";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import { importSessions, importStagingBookmarks } from "@karakeep/db/schema";+import {+ zCreateImportSessionRequestSchema,+ ZImportSession,+} from "@karakeep/shared/types/importSessions";++type ImportSessionRow = typeof importSessions.$inferSelect;+type StagingBookmarkRow = typeof importStagingBookmarks.$inferSelect;++export class ImportSessionsRepo {+ constructor(private db: DB) {}++ async get(id: string): Promise<ImportSessionRow | null> {+ const session = await this.db.query.importSessions.findFirst({+ where: eq(importSessions.id, id),+ });+ return session ?? null;+ }++ async create(+ userId: string,+ input: z.infer<typeof zCreateImportSessionRequestSchema>,+ ): Promise<ImportSessionRow> {+ const [session] = await this.db+ .insert(importSessions)+ .values({+ name: input.name,+ userId,+ rootListId: input.rootListId,+ })+ .returning();++ return session;+ }++ async getAll(userId: string): Promise<ImportSessionRow[]> {+ return await this.db.query.importSessions.findMany({+ where: eq(importSessions.userId, userId),+ orderBy: (importSessions, { desc }) => [desc(importSessions.createdAt)],+ limit: 50,+ });+ }++ async getStatusCounts(+ sessionId: string,+ ): Promise<{ status: string; count: number }[]> {+ return await this.db+ .select({+ status: importStagingBookmarks.status,+ count: count(),+ })+ .from(importStagingBookmarks)+ .where(eq(importStagingBookmarks.importSessionId, sessionId))+ .groupBy(importStagingBookmarks.status);+ }++ async delete(id: string): Promise<boolean> {+ const result = await this.db+ .delete(importSessions)+ .where(eq(importSessions.id, id));+ return result.changes > 0;+ }++ async insertStagingBookmarks(+ bookmarks: {+ importSessionId: string;+ type: "link" | "text" | "asset";+ url?: string;+ title?: string;+ content?: string;+ note?: string;+ tags: string[];+ listIds: string[];+ sourceAddedAt?: Date;+ status: "pending";+ }[],+ ): Promise<void> {+ await this.db.insert(importStagingBookmarks).values(bookmarks);+ }++ async updateStatus(+ id: string,+ status: ZImportSession["status"],+ ): Promise<void> {+ await this.db+ .update(importSessions)+ .set({ status })+ .where(eq(importSessions.id, id));+ }++ async getStagingBookmarks(+ sessionId: string,+ filter?: "all" | "accepted" | "rejected" | "skipped_duplicate" | "pending",+ cursor?: string,+ limit = 50,+ ): Promise<{ items: StagingBookmarkRow[]; nextCursor: string | null }> {+ const results = await this.db+ .select()+ .from(importStagingBookmarks)+ .where(+ and(+ eq(importStagingBookmarks.importSessionId, sessionId),+ filter && filter !== "all"+ ? filter === "pending"+ ? eq(importStagingBookmarks.status, "pending")+ : eq(importStagingBookmarks.result, filter)+ : undefined,+ cursor ? gt(importStagingBookmarks.id, cursor) : undefined,+ ),+ )+ .orderBy(importStagingBookmarks.id)+ .limit(limit + 1);++ const hasMore = results.length > limit;+ return {+ items: results.slice(0, limit),+ nextCursor: hasMore ? results[limit - 1].id : null,+ };+ }+}diff --git a/packages/trpc/models/importSessions.service.ts b/packages/trpc/models/importSessions.service.tsnew file mode 100644index 00000000..3a56a40d--- /dev/null+++ b/packages/trpc/models/importSessions.service.ts@@ -0,0 +1,205 @@+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import type { importSessions } from "@karakeep/db/schema";+import {+ zCreateImportSessionRequestSchema,+ ZImportSessionWithStats,+} from "@karakeep/shared/types/importSessions";++import type { Actor, Authorized } from "../lib/actor";+import { actorUserId, assertOwnership, authorize } from "../lib/actor";+import { ImportSessionsRepo } from "./importSessions.repo";++type ImportSessionRow = typeof importSessions.$inferSelect;++export class ImportSessionsService {+ private repo: ImportSessionsRepo;++ constructor(db: DB) {+ this.repo = new ImportSessionsRepo(db);+ }++ async create(+ actor: Actor,+ input: z.infer<typeof zCreateImportSessionRequestSchema>,+ ): Promise<ImportSessionRow> {+ return await this.repo.create(actorUserId(actor), input);+ }++ async get(+ actor: Actor,+ sessionId: string,+ ): Promise<Authorized<ImportSessionRow>> {+ const session = await this.repo.get(sessionId);+ if (!session) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Import session not found",+ });+ }+ return authorize(session, () =>+ assertOwnership(actor, session.userId, {+ notFoundOnDeny: true,+ notFoundMessage: "Import session not found",+ }),+ );+ }++ async getWithStats(+ session: Authorized<ImportSessionRow>,+ ): Promise<ZImportSessionWithStats> {+ return await this.buildStats(session);+ }++ async listWithStats(actor: Actor): Promise<ZImportSessionWithStats[]> {+ const sessions = await this.repo.getAll(actorUserId(actor));+ return await Promise.all(+ sessions.map((session) => this.buildStats(session)),+ );+ }++ async delete(session: Authorized<ImportSessionRow>): Promise<void> {+ const deleted = await this.repo.delete(session.id);++ if (!deleted) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Import session not found",+ });+ }+ }++ async stageBookmarks(+ session: Authorized<ImportSessionRow>,+ bookmarks: {+ type: "link" | "text" | "asset";+ url?: string;+ title?: string;+ content?: string;+ note?: string;+ tags: string[];+ listIds: string[];+ sourceAddedAt?: Date;+ }[],+ ): Promise<void> {+ if (session.status !== "staging") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Session not in staging status",+ });+ }++ // Filter out invalid bookmarks (link without url, text without content)+ const validBookmarks = bookmarks.filter((bookmark) => {+ if (bookmark.type === "link" && !bookmark.url) return false;+ if (bookmark.type === "text" && !bookmark.content) return false;+ return true;+ });++ if (validBookmarks.length === 0) {+ return;+ }++ await this.repo.insertStagingBookmarks(+ validBookmarks.map((bookmark) => ({+ importSessionId: session.id,+ type: bookmark.type,+ url: bookmark.url,+ title: bookmark.title,+ content: bookmark.content,+ note: bookmark.note,+ tags: bookmark.tags,+ listIds: bookmark.listIds,+ sourceAddedAt: bookmark.sourceAddedAt,+ status: "pending" as const,+ })),+ );+ }++ async finalize(session: Authorized<ImportSessionRow>): Promise<void> {+ if (session.status !== "staging") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Session not in staging status",+ });+ }++ await this.repo.updateStatus(session.id, "pending");+ }++ async pause(session: Authorized<ImportSessionRow>): Promise<void> {+ if (!["pending", "running"].includes(session.status)) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Session cannot be paused in current status",+ });+ }++ await this.repo.updateStatus(session.id, "paused");+ }++ async resume(session: Authorized<ImportSessionRow>): Promise<void> {+ if (session.status !== "paused") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Session not paused",+ });+ }++ await this.repo.updateStatus(session.id, "pending");+ }++ async getStagingBookmarks(+ session: Authorized<ImportSessionRow>,+ filter?: "all" | "accepted" | "rejected" | "skipped_duplicate" | "pending",+ cursor?: string,+ limit = 50,+ ) {+ return await this.repo.getStagingBookmarks(+ session.id,+ filter,+ cursor,+ limit,+ );+ }++ private async buildStats(+ session: ImportSessionRow,+ ): Promise<ZImportSessionWithStats> {+ const statusCounts = await this.repo.getStatusCounts(session.id);++ const stats = {+ totalBookmarks: 0,+ completedBookmarks: 0,+ failedBookmarks: 0,+ pendingBookmarks: 0,+ processingBookmarks: 0,+ };++ statusCounts.forEach(({ status, count: itemCount }) => {+ stats.totalBookmarks += itemCount;++ switch (status) {+ case "pending":+ stats.pendingBookmarks += itemCount;+ break;+ case "processing":+ stats.processingBookmarks += itemCount;+ break;+ case "completed":+ stats.completedBookmarks += itemCount;+ break;+ case "failed":+ stats.failedBookmarks += itemCount;+ break;+ }+ });++ return {+ ...session,+ ...stats,+ };+ }+}diff --git a/packages/trpc/models/importSessions.ts b/packages/trpc/models/importSessions.tsdeleted file mode 100644index ee0eb5b2..00000000--- a/packages/trpc/models/importSessions.ts+++ /dev/null@@ -1,230 +0,0 @@-import { TRPCError } from "@trpc/server";-import { and, count, eq } from "drizzle-orm";-import { z } from "zod";--import { importSessions, importStagingBookmarks } from "@karakeep/db/schema";-import {- zCreateImportSessionRequestSchema,- ZImportSession,- ZImportSessionWithStats,-} from "@karakeep/shared/types/importSessions";--import type { AuthedContext } from "../index";--export class ImportSession {- protected constructor(- protected ctx: AuthedContext,- public session: ZImportSession,- ) {}-- static async fromId(- ctx: AuthedContext,- importSessionId: string,- ): Promise<ImportSession> {- const session = await ctx.db.query.importSessions.findFirst({- where: and(- eq(importSessions.id, importSessionId),- eq(importSessions.userId, ctx.user.id),- ),- });-- if (!session) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Import session not found",- });- }-- return new ImportSession(ctx, session);- }-- static async create(- ctx: AuthedContext,- input: z.infer<typeof zCreateImportSessionRequestSchema>,- ): Promise<ImportSession> {- const [session] = await ctx.db- .insert(importSessions)- .values({- name: input.name,- userId: ctx.user.id,- rootListId: input.rootListId,- })- .returning();-- return new ImportSession(ctx, session);- }-- static async getAll(ctx: AuthedContext): Promise<ImportSession[]> {- const sessions = await ctx.db.query.importSessions.findMany({- where: eq(importSessions.userId, ctx.user.id),- orderBy: (importSessions, { desc }) => [desc(importSessions.createdAt)],- limit: 50,- });-- return sessions.map((session) => new ImportSession(ctx, session));- }-- static async getAllWithStats(- ctx: AuthedContext,- ): Promise<ZImportSessionWithStats[]> {- const sessions = await this.getAll(ctx);-- return await Promise.all(- sessions.map(async (session) => {- return await session.getWithStats();- }),- );- }-- async getWithStats(): Promise<ZImportSessionWithStats> {- // Count by staging status - this now reflects the true state since- // items stay in "processing" until downstream crawl/tag is complete- const statusCounts = await this.ctx.db- .select({- status: importStagingBookmarks.status,- count: count(),- })- .from(importStagingBookmarks)- .where(eq(importStagingBookmarks.importSessionId, this.session.id))- .groupBy(importStagingBookmarks.status);-- const stats = {- totalBookmarks: 0,- completedBookmarks: 0,- failedBookmarks: 0,- pendingBookmarks: 0,- processingBookmarks: 0,- };-- statusCounts.forEach(({ status, count: itemCount }) => {- stats.totalBookmarks += itemCount;-- switch (status) {- case "pending":- stats.pendingBookmarks += itemCount;- break;- case "processing":- stats.processingBookmarks += itemCount;- break;- case "completed":- stats.completedBookmarks += itemCount;- break;- case "failed":- stats.failedBookmarks += itemCount;- break;- }- });-- return {- ...this.session,- ...stats,- };- }-- async delete(): Promise<void> {- // Delete the session (cascade will handle the bookmarks)- const result = await this.ctx.db- .delete(importSessions)- .where(- and(- eq(importSessions.id, this.session.id),- eq(importSessions.userId, this.ctx.user.id),- ),- );-- if (result.changes === 0) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Import session not found",- });- }- }-- async stageBookmarks(- bookmarks: {- type: "link" | "text" | "asset";- url?: string;- title?: string;- content?: string;- note?: string;- tags: string[];- listIds: string[];- sourceAddedAt?: Date;- }[],- ): Promise<void> {- if (this.session.status !== "staging") {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Session not in staging status",- });- }-- // Filter out invalid bookmarks (link without url, text without content)- const validBookmarks = bookmarks.filter((bookmark) => {- if (bookmark.type === "link" && !bookmark.url) return false;- if (bookmark.type === "text" && !bookmark.content) return false;- return true;- });-- if (validBookmarks.length === 0) {- return;- }-- await this.ctx.db.insert(importStagingBookmarks).values(- validBookmarks.map((bookmark) => ({- importSessionId: this.session.id,- type: bookmark.type,- url: bookmark.url,- title: bookmark.title,- content: bookmark.content,- note: bookmark.note,- tags: bookmark.tags,- listIds: bookmark.listIds,- sourceAddedAt: bookmark.sourceAddedAt,- status: "pending" as const,- })),- );- }-- async finalize(): Promise<void> {- if (this.session.status !== "staging") {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Session not in staging status",- });- }-- await this.ctx.db- .update(importSessions)- .set({ status: "pending" })- .where(eq(importSessions.id, this.session.id));- }-- async pause(): Promise<void> {- if (!["pending", "running"].includes(this.session.status)) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Session cannot be paused in current status",- });- }-- await this.ctx.db- .update(importSessions)- .set({ status: "paused" })- .where(eq(importSessions.id, this.session.id));- }-- async resume(): Promise<void> {- if (this.session.status !== "paused") {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Session not paused",- });- }-- await this.ctx.db- .update(importSessions)- .set({ status: "pending" })- .where(eq(importSessions.id, this.session.id));- }-}diff --git a/packages/trpc/models/webhooks.repo.ts b/packages/trpc/models/webhooks.repo.tsnew file mode 100644index 00000000..3e5c6e5a--- /dev/null+++ b/packages/trpc/models/webhooks.repo.ts@@ -0,0 +1,77 @@+import { count, eq } from "drizzle-orm";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import { webhooksTable } from "@karakeep/db/schema";+import {+ zNewWebhookSchema,+ zUpdateWebhookSchema,+} from "@karakeep/shared/types/webhooks";++type Webhook = typeof webhooksTable.$inferSelect;++export class WebhooksRepo {+ constructor(private db: DB) {}++ async get(id: string): Promise<Webhook | null> {+ const webhook = await this.db.query.webhooksTable.findFirst({+ where: eq(webhooksTable.id, id),+ });+ return webhook ?? null;+ }++ async create(+ userId: string,+ input: z.infer<typeof zNewWebhookSchema>,+ ): Promise<Webhook> {+ const [result] = await this.db+ .insert(webhooksTable)+ .values({+ url: input.url,+ events: input.events,+ token: input.token ?? null,+ userId,+ })+ .returning();++ return result;+ }++ async countByUser(userId: string): Promise<number> {+ const [result] = await this.db+ .select({ count: count() })+ .from(webhooksTable)+ .where(eq(webhooksTable.userId, userId));+ return result.count;+ }++ async getAll(userId: string): Promise<Webhook[]> {+ return await this.db.query.webhooksTable.findMany({+ where: eq(webhooksTable.userId, userId),+ });+ }++ async delete(id: string): Promise<boolean> {+ const res = await this.db+ .delete(webhooksTable)+ .where(eq(webhooksTable.id, id));+ return res.changes > 0;+ }++ async update(+ id: string,+ input: z.infer<typeof zUpdateWebhookSchema>,+ ): Promise<Webhook | null> {+ const result = await this.db+ .update(webhooksTable)+ .set({+ url: input.url,+ events: input.events,+ token: input.token,+ })+ .where(eq(webhooksTable.id, id))+ .returning();++ return result[0] ?? null;+ }+}diff --git a/packages/trpc/models/webhooks.service.ts b/packages/trpc/models/webhooks.service.tsnew file mode 100644index 00000000..b1b5e327--- /dev/null+++ b/packages/trpc/models/webhooks.service.ts@@ -0,0 +1,74 @@+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import type { DB } from "@karakeep/db";+import type { webhooksTable } from "@karakeep/db/schema";+import serverConfig from "@karakeep/shared/config";+import {+ zNewWebhookSchema,+ zUpdateWebhookSchema,+} from "@karakeep/shared/types/webhooks";++import type { Actor, Authorized } from "../lib/actor";+import { actorUserId, assertOwnership, authorize } from "../lib/actor";+import { WebhooksRepo } from "./webhooks.repo";++type Webhook = typeof webhooksTable.$inferSelect;++export class WebhooksService {+ private repo: WebhooksRepo;++ constructor(db: DB) {+ this.repo = new WebhooksRepo(db);+ }++ async get(actor: Actor, id: string): Promise<Authorized<Webhook>> {+ const webhook = await this.repo.get(id);+ if (!webhook) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Webhook not found",+ });+ }+ return authorize(webhook, () => assertOwnership(actor, webhook.userId));+ }++ async create(+ actor: Actor,+ input: z.infer<typeof zNewWebhookSchema>,+ ): Promise<Webhook> {+ const userId = actorUserId(actor);+ const webhookCount = await this.repo.countByUser(userId);+ const maxWebhooks = serverConfig.webhook.maxWebhooksPerUser;+ if (webhookCount >= maxWebhooks) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Maximum number of webhooks (${maxWebhooks}) reached`,+ });+ }++ return await this.repo.create(userId, input);+ }++ async update(+ webhook: Authorized<Webhook>,+ input: z.infer<typeof zUpdateWebhookSchema>,+ ): Promise<Webhook> {+ const updated = await this.repo.update(webhook.id, input);+ if (!updated) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }+ return updated;+ }++ async getAll(actor: Actor): Promise<Webhook[]> {+ return await this.repo.getAll(actorUserId(actor));+ }++ async delete(webhook: Authorized<Webhook>): Promise<void> {+ const deleted = await this.repo.delete(webhook.id);+ if (!deleted) {+ throw new TRPCError({ code: "NOT_FOUND" });+ }+ }+}diff --git a/packages/trpc/models/webhooks.ts b/packages/trpc/models/webhooks.tsdeleted file mode 100644index 12281ec7..00000000--- a/packages/trpc/models/webhooks.ts+++ /dev/null@@ -1,128 +0,0 @@-import { TRPCError } from "@trpc/server";-import { and, count, eq } from "drizzle-orm";-import { z } from "zod";--import { webhooksTable } from "@karakeep/db/schema";-import serverConfig from "@karakeep/shared/config";-import {- zNewWebhookSchema,- zUpdateWebhookSchema,- zWebhookSchema,-} from "@karakeep/shared/types/webhooks";--import { AuthedContext } from "..";--export class Webhook {- constructor(- protected ctx: AuthedContext,- public webhook: typeof webhooksTable.$inferSelect,- ) {}-- static async fromId(ctx: AuthedContext, id: string): Promise<Webhook> {- const webhook = await ctx.db.query.webhooksTable.findFirst({- where: eq(webhooksTable.id, id),- });-- if (!webhook) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Webhook not found",- });- }-- // If it exists but belongs to another user, throw forbidden error- if (webhook.userId !== ctx.user.id) {- throw new TRPCError({- code: "FORBIDDEN",- message: "User is not allowed to access resource",- });- }-- return new Webhook(ctx, webhook);- }-- static async create(- ctx: AuthedContext,- input: z.infer<typeof zNewWebhookSchema>,- ): Promise<Webhook> {- // Check if user has reached the maximum number of webhooks- const [webhookCount] = await ctx.db- .select({ count: count() })- .from(webhooksTable)- .where(eq(webhooksTable.userId, ctx.user.id));-- const maxWebhooks = serverConfig.webhook.maxWebhooksPerUser;- if (webhookCount.count >= maxWebhooks) {- throw new TRPCError({- code: "BAD_REQUEST",- message: `Maximum number of webhooks (${maxWebhooks}) reached`,- });- }-- const [result] = await ctx.db- .insert(webhooksTable)- .values({- url: input.url,- events: input.events,- token: input.token ?? null,- userId: ctx.user.id,- })- .returning();-- return new Webhook(ctx, result);- }-- static async getAll(ctx: AuthedContext): Promise<Webhook[]> {- const webhooks = await ctx.db.query.webhooksTable.findMany({- where: eq(webhooksTable.userId, ctx.user.id),- });-- return webhooks.map((w) => new Webhook(ctx, w));- }-- async delete(): Promise<void> {- const res = await this.ctx.db- .delete(webhooksTable)- .where(- and(- eq(webhooksTable.id, this.webhook.id),- eq(webhooksTable.userId, this.ctx.user.id),- ),- );-- if (res.changes === 0) {- throw new TRPCError({ code: "NOT_FOUND" });- }- }-- async update(input: z.infer<typeof zUpdateWebhookSchema>): Promise<void> {- const result = await this.ctx.db- .update(webhooksTable)- .set({- url: input.url,- events: input.events,- token: input.token,- })- .where(- and(- eq(webhooksTable.id, this.webhook.id),- eq(webhooksTable.userId, this.ctx.user.id),- ),- )- .returning();-- if (result.length === 0) {- throw new TRPCError({ code: "NOT_FOUND" });- }-- this.webhook = result[0];- }-- asPublicWebhook(): z.infer<typeof zWebhookSchema> {- const { token, ...rest } = this.webhook;- return {- ...rest,- hasToken: token !== null,- };- }-}diff --git a/packages/trpc/routers/feeds.test.ts b/packages/trpc/routers/feeds.test.tsindex e80aab0a..ef7fa031 100644--- a/packages/trpc/routers/feeds.test.ts+++ b/packages/trpc/routers/feeds.test.ts@@ -1,5 +1,6 @@-import { beforeEach, describe, expect, test } from "vitest";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { FeedsRepo } from "../models/feeds.repo";import type { CustomTestContext } from "../testUtils";import { defaultBeforeEach } from "../testUtils";@@ -99,6 +100,27 @@ describe("Feed Routes", () => {).rejects.toThrow(/Feed not found/);});+ test<CustomTestContext>("delete feed returns not found when the row disappears after ownership check", async ({+ apiCallers,+ }) => {+ const api = apiCallers[0].feeds;+ const createdFeed = await api.create({+ name: "Test Feed",+ url: "https://example.com/feed.xml",+ enabled: true,+ });++ const deleteSpy = vi+ .spyOn(FeedsRepo.prototype, "delete")+ .mockResolvedValueOnce(false);++ await expect(() => api.delete({ feedId: createdFeed.id })).rejects.toThrow(+ /NOT_FOUND/,+ );++ deleteSpy.mockRestore();+ });+test<CustomTestContext>("privacy for feeds", async ({ apiCallers }) => {const user1Feed = await apiCallers[0].feeds.create({name: "User 1 Feed",diff --git a/packages/trpc/routers/feeds.ts b/packages/trpc/routers/feeds.tsindex 8591c98c..31e9e15b 100644--- a/packages/trpc/routers/feeds.ts+++ b/packages/trpc/routers/feeds.ts@@ -1,3 +1,4 @@+import { experimental_trpcMiddleware } from "@trpc/server";import { z } from "zod";import { FeedQueue } from "@karakeep/shared-server";@@ -7,59 +8,83 @@ import {zUpdateFeedSchema,} from "@karakeep/shared/types/feeds";+import type { AuthedContext } from "../index";import { authedProcedure, router } from "../index";-import { Feed } from "../models/feeds";+import { actorFromContext } from "../lib/actor";+import { FeedsService } from "../models/feeds.service";++const feedsProcedure = authedProcedure.use((opts) => {+ return opts.next({+ ctx: {+ ...opts.ctx,+ actor: actorFromContext(opts.ctx),+ feedsService: new FeedsService(opts.ctx.db),+ },+ });+});++type FeedsContext = AuthedContext & {+ actor: ReturnType<typeof actorFromContext>;+ feedsService: FeedsService;+};++const ensureFeedOwnership = experimental_trpcMiddleware<{+ ctx: FeedsContext;+ input: { feedId: string };+}>().create(async (opts) => {+ const feed = await opts.ctx.feedsService.get(+ opts.ctx.actor,+ opts.input.feedId,+ );++ return opts.next({+ ctx: {+ ...opts.ctx,+ feed,+ },+ });+});export const feedsAppRouter = router({- create: authedProcedure+ create: feedsProcedure.input(zNewFeedSchema).output(zFeedSchema).mutation(async ({ input, ctx }) => {- const feed = await Feed.create(ctx, input);- return feed.asPublicFeed();+ return await ctx.feedsService.create(ctx.actor, input);}),- update: authedProcedure+ update: feedsProcedure.input(zUpdateFeedSchema).output(zFeedSchema)+ .use(ensureFeedOwnership).mutation(async ({ input, ctx }) => {- const feed = await Feed.fromId(ctx, input.feedId);- await feed.update(input);- return feed.asPublicFeed();+ return await ctx.feedsService.update(ctx.feed, input);}),- get: authedProcedure- .input(- z.object({- feedId: z.string(),- }),- )+ get: feedsProcedure+ .input(z.object({ feedId: z.string() })).output(zFeedSchema)- .query(async ({ ctx, input }) => {- const feed = await Feed.fromId(ctx, input.feedId);- return feed.asPublicFeed();+ .use(ensureFeedOwnership)+ .query(({ ctx }) => {+ return ctx.feed;}),- list: authedProcedure+ list: feedsProcedure.output(z.object({ feeds: z.array(zFeedSchema) })).query(async ({ ctx }) => {- const feeds = await Feed.getAll(ctx);- return { feeds: feeds.map((f) => f.asPublicFeed()) };+ const feeds = await ctx.feedsService.getAll(ctx.actor);+ return { feeds };}),- delete: authedProcedure- .input(- z.object({- feedId: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- const feed = await Feed.fromId(ctx, input.feedId);- await feed.delete();+ delete: feedsProcedure+ .input(z.object({ feedId: z.string() }))+ .use(ensureFeedOwnership)+ .mutation(async ({ ctx }) => {+ await ctx.feedsService.delete(ctx.feed);}),- fetchNow: authedProcedure+ fetchNow: feedsProcedure.input(z.object({ feedId: z.string() }))- .mutation(async ({ input, ctx }) => {- await Feed.fromId(ctx, input.feedId);+ .use(ensureFeedOwnership)+ .mutation(async ({ ctx }) => {await FeedQueue.enqueue({- feedId: input.feedId,+ feedId: ctx.feed.id,},{groupId: ctx.user.id,diff --git a/packages/trpc/routers/highlights.ts b/packages/trpc/routers/highlights.tsindex 7338077a..606e0daf 100644--- a/packages/trpc/routers/highlights.ts+++ b/packages/trpc/routers/highlights.ts@@ -1,3 +1,4 @@+import { experimental_trpcMiddleware } from "@trpc/server";import { z } from "zod";import {@@ -9,35 +10,70 @@ import {} from "@karakeep/shared/types/highlights";import { zCursorV2 } from "@karakeep/shared/types/pagination";+import type { AuthedContext } from "../index";import { authedProcedure, router } from "../index";-import { Highlight } from "../models/highlights";+import { actorFromContext } from "../lib/actor";+import { HighlightsService } from "../models/highlights.service";import { ensureBookmarkAccess, ensureBookmarkOwnership } from "./bookmarks";+const highlightsProcedure = authedProcedure.use((opts) => {+ return opts.next({+ ctx: {+ ...opts.ctx,+ actor: actorFromContext(opts.ctx),+ highlightsService: new HighlightsService(opts.ctx.db),+ },+ });+});++type HighlightsContext = AuthedContext & {+ actor: ReturnType<typeof actorFromContext>;+ highlightsService: HighlightsService;+};++const ensureHighlightOwnership = experimental_trpcMiddleware<{+ ctx: HighlightsContext;+ input: { highlightId: string };+}>().create(async (opts) => {+ const highlight = await opts.ctx.highlightsService.get(+ opts.ctx.actor,+ opts.input.highlightId,+ );++ return opts.next({+ ctx: {+ ...opts.ctx,+ highlight,+ },+ });+});+export const highlightsAppRouter = router({- create: authedProcedure+ create: highlightsProcedure.input(zNewHighlightSchema).output(zHighlightSchema).use(ensureBookmarkOwnership).mutation(async ({ input, ctx }) => {- const highlight = await Highlight.create(ctx, input);- return highlight.asPublicHighlight();+ return await ctx.highlightsService.create(ctx.actor, input);}),- getForBookmark: authedProcedure+ getForBookmark: highlightsProcedure.input(z.object({ bookmarkId: z.string() })).output(z.object({ highlights: z.array(zHighlightSchema) })).use(ensureBookmarkAccess).query(async ({ ctx }) => {- const highlights = await Highlight.getForBookmark(ctx, ctx.bookmark);- return { highlights: highlights.map((h) => h.asPublicHighlight()) };+ const highlights = await ctx.highlightsService.getForBookmark(+ ctx.bookmark.id,+ );+ return { highlights };}),- get: authedProcedure+ get: highlightsProcedure.input(z.object({ highlightId: z.string() })).output(zHighlightSchema)- .query(async ({ input, ctx }) => {- const highlight = await Highlight.fromId(ctx, input.highlightId);- return highlight.asPublicHighlight();+ .use(ensureHighlightOwnership)+ .query(({ ctx }) => {+ return ctx.highlight;}),- getAll: authedProcedure+ getAll: highlightsProcedure.input(z.object({cursor: z.any().nullish(),@@ -46,13 +82,13 @@ export const highlightsAppRouter = router({).output(zGetAllHighlightsResponseSchema).query(async ({ input, ctx }) => {- const result = await Highlight.getAll(ctx, input.cursor, input.limit);- return {- highlights: result.highlights.map((h) => h.asPublicHighlight()),- nextCursor: result.nextCursor,- };+ return await ctx.highlightsService.getAll(+ ctx.actor,+ input.cursor,+ input.limit,+ );}),- search: authedProcedure+ search: highlightsProcedure.input(z.object({text: z.string(),@@ -62,30 +98,25 @@ export const highlightsAppRouter = router({).output(zGetAllHighlightsResponseSchema).query(async ({ input, ctx }) => {- const result = await Highlight.search(- ctx,+ return await ctx.highlightsService.search(+ ctx.actor,input.text,input.cursor,input.limit,);- return {- highlights: result.highlights.map((h) => h.asPublicHighlight()),- nextCursor: result.nextCursor,- };}),- delete: authedProcedure+ delete: highlightsProcedure.input(z.object({ highlightId: z.string() })).output(zHighlightSchema)- .mutation(async ({ input, ctx }) => {- const highlight = await Highlight.fromId(ctx, input.highlightId);- return await highlight.delete();+ .use(ensureHighlightOwnership)+ .mutation(async ({ ctx }) => {+ return await ctx.highlightsService.delete(ctx.highlight);}),- update: authedProcedure+ update: highlightsProcedure.input(zUpdateHighlightSchema).output(zHighlightSchema)+ .use(ensureHighlightOwnership).mutation(async ({ input, ctx }) => {- const highlight = await Highlight.fromId(ctx, input.highlightId);- await highlight.update(input);- return highlight.asPublicHighlight();+ return await ctx.highlightsService.update(ctx.highlight, input);}),});diff --git a/packages/trpc/routers/importSessions.ts b/packages/trpc/routers/importSessions.tsindex 62263bdd..bac013ac 100644--- a/packages/trpc/routers/importSessions.ts+++ b/packages/trpc/routers/importSessions.ts@@ -1,8 +1,6 @@import { experimental_trpcMiddleware } from "@trpc/server";-import { and, eq, gt } from "drizzle-orm";import { z } from "zod";-import { importStagingBookmarks } from "@karakeep/db/schema";import {zCreateImportSessionRequestSchema,zDeleteImportSessionRequestSchema,@@ -14,16 +12,33 @@ import {import type { AuthedContext } from "../index";import { authedProcedure, router } from "../index";-import { ImportSession } from "../models/importSessions";+import { actorFromContext } from "../lib/actor";+import { ImportSessionsService } from "../models/importSessions.service";++const importSessionsProcedure = authedProcedure.use((opts) => {+ return opts.next({+ ctx: {+ ...opts.ctx,+ actor: actorFromContext(opts.ctx),+ importSessionsService: new ImportSessionsService(opts.ctx.db),+ },+ });+});++type ImportSessionsContext = AuthedContext & {+ actor: ReturnType<typeof actorFromContext>;+ importSessionsService: ImportSessionsService;+};const ensureImportSessionAccess = experimental_trpcMiddleware<{- ctx: AuthedContext;+ ctx: ImportSessionsContext;input: { importSessionId: string };}>().create(async (opts) => {- const importSession = await ImportSession.fromId(- opts.ctx,+ const importSession = await opts.ctx.importSessionsService.get(+ opts.ctx.actor,opts.input.importSessionId,);+return opts.next({ctx: {...opts.ctx,@@ -33,40 +48,40 @@ const ensureImportSessionAccess = experimental_trpcMiddleware<{});export const importSessionsRouter = router({- createImportSession: authedProcedure+ createImportSession: importSessionsProcedure.input(zCreateImportSessionRequestSchema).output(z.object({ id: z.string() })).mutation(async ({ input, ctx }) => {- const session = await ImportSession.create(ctx, input);- return { id: session.session.id };+ const session = await ctx.importSessionsService.create(ctx.actor, input);+ return { id: session.id };}),- getImportSessionStats: authedProcedure+ getImportSessionStats: importSessionsProcedure.input(zGetImportSessionStatsRequestSchema).output(zImportSessionWithStatsSchema)- .query(async ({ input, ctx }) => {- const session = await ImportSession.fromId(ctx, input.importSessionId);- return await session.getWithStats();+ .use(ensureImportSessionAccess)+ .query(async ({ ctx }) => {+ return await ctx.importSessionsService.getWithStats(ctx.importSession);}),- listImportSessions: authedProcedure+ listImportSessions: importSessionsProcedure.input(zListImportSessionsRequestSchema).output(zListImportSessionsResponseSchema).query(async ({ ctx }) => {- const sessions = await ImportSession.getAllWithStats(ctx);+ const sessions = await ctx.importSessionsService.listWithStats(ctx.actor);return { sessions };}),- deleteImportSession: authedProcedure+ deleteImportSession: importSessionsProcedure.input(zDeleteImportSessionRequestSchema).output(z.object({ success: z.boolean() }))- .mutation(async ({ input, ctx }) => {- const session = await ImportSession.fromId(ctx, input.importSessionId);- await session.delete();+ .use(ensureImportSessionAccess)+ .mutation(async ({ ctx }) => {+ await ctx.importSessionsService.delete(ctx.importSession);return { success: true };}),- stageImportedBookmarks: authedProcedure+ stageImportedBookmarks: importSessionsProcedure.input(z.object({importSessionId: z.string(),@@ -88,31 +103,34 @@ export const importSessionsRouter = router({).use(ensureImportSessionAccess).mutation(async ({ input, ctx }) => {- await ctx.importSession.stageBookmarks(input.bookmarks);+ await ctx.importSessionsService.stageBookmarks(+ ctx.importSession,+ input.bookmarks,+ );}),- finalizeImportStaging: authedProcedure+ finalizeImportStaging: importSessionsProcedure.input(z.object({ importSessionId: z.string() })).use(ensureImportSessionAccess).mutation(async ({ ctx }) => {- await ctx.importSession.finalize();+ await ctx.importSessionsService.finalize(ctx.importSession);}),- pauseImportSession: authedProcedure+ pauseImportSession: importSessionsProcedure.input(z.object({ importSessionId: z.string() })).use(ensureImportSessionAccess).mutation(async ({ ctx }) => {- await ctx.importSession.pause();+ await ctx.importSessionsService.pause(ctx.importSession);}),- resumeImportSession: authedProcedure+ resumeImportSession: importSessionsProcedure.input(z.object({ importSessionId: z.string() })).use(ensureImportSessionAccess).mutation(async ({ ctx }) => {- await ctx.importSession.resume();+ await ctx.importSessionsService.resume(ctx.importSession);}),- getImportSessionResults: authedProcedure+ getImportSessionResults: importSessionsProcedure.input(z.object({importSessionId: z.string(),@@ -125,33 +143,11 @@ export const importSessionsRouter = router({).use(ensureImportSessionAccess).query(async ({ ctx, input }) => {- const results = await ctx.db- .select()- .from(importStagingBookmarks)- .where(- and(- eq(- importStagingBookmarks.importSessionId,- ctx.importSession.session.id,- ),- input.filter && input.filter !== "all"- ? input.filter === "pending"- ? eq(importStagingBookmarks.status, "pending")- : eq(importStagingBookmarks.result, input.filter)- : undefined,- input.cursor- ? gt(importStagingBookmarks.id, input.cursor)- : undefined,- ),- )- .orderBy(importStagingBookmarks.id)- .limit(input.limit + 1);-- // Return with pagination info- const hasMore = results.length > input.limit;- return {- items: results.slice(0, input.limit),- nextCursor: hasMore ? results[input.limit - 1].id : null,- };+ return await ctx.importSessionsService.getStagingBookmarks(+ ctx.importSession,+ input.filter,+ input.cursor,+ input.limit,+ );}),});diff --git a/packages/trpc/routers/webhooks.test.ts b/packages/trpc/routers/webhooks.test.tsindex de27b11e..978c6aff 100644--- a/packages/trpc/routers/webhooks.test.ts+++ b/packages/trpc/routers/webhooks.test.ts@@ -1,5 +1,6 @@-import { beforeEach, describe, expect, test } from "vitest";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { WebhooksRepo } from "../models/webhooks.repo";import type { CustomTestContext } from "../testUtils";import { defaultBeforeEach } from "../testUtils";@@ -96,6 +97,26 @@ describe("Webhook Routes", () => {).rejects.toThrow(/Webhook not found/);});+ test<CustomTestContext>("delete webhook returns not found when the row disappears after ownership check", async ({+ apiCallers,+ }) => {+ const api = apiCallers[0].webhooks;+ const createdWebhook = await api.create({+ url: "https://example.com/webhook",+ events: ["created"],+ });++ const deleteSpy = vi+ .spyOn(WebhooksRepo.prototype, "delete")+ .mockResolvedValueOnce(false);++ await expect(() =>+ api.delete({ webhookId: createdWebhook.id }),+ ).rejects.toThrow(/NOT_FOUND/);++ deleteSpy.mockRestore();+ });+test<CustomTestContext>("privacy for webhooks", async ({ apiCallers }) => {const user1Webhook = await apiCallers[0].webhooks.create({url: "https://user1-webhook.com",diff --git a/packages/trpc/routers/webhooks.ts b/packages/trpc/routers/webhooks.tsindex 5d30969b..cd7659bf 100644--- a/packages/trpc/routers/webhooks.ts+++ b/packages/trpc/routers/webhooks.ts@@ -1,6 +1,7 @@import { experimental_trpcMiddleware } from "@trpc/server";import { z } from "zod";+import { webhooksTable } from "@karakeep/db/schema";import {zNewWebhookSchema,zUpdateWebhookSchema,@@ -9,13 +10,41 @@ import {import type { AuthedContext } from "../index";import { authedProcedure, router } from "../index";-import { Webhook } from "../models/webhooks";+import { actorFromContext } from "../lib/actor";+import { WebhooksService } from "../models/webhooks.service";-export const ensureWebhookOwnership = experimental_trpcMiddleware<{- ctx: AuthedContext;+function toPublicWebhook(webhook: typeof webhooksTable.$inferSelect) {+ const { token, ...rest } = webhook;+ return {+ ...rest,+ hasToken: token !== null,+ };+}++const webhooksProcedure = authedProcedure.use((opts) => {+ return opts.next({+ ctx: {+ ...opts.ctx,+ actor: actorFromContext(opts.ctx),+ webhooksService: new WebhooksService(opts.ctx.db),+ },+ });+});++type WebhooksContext = AuthedContext & {+ actor: ReturnType<typeof actorFromContext>;+ webhooksService: WebhooksService;+};++const ensureWebhookOwnership = experimental_trpcMiddleware<{+ ctx: WebhooksContext;input: { webhookId: string };}>().create(async (opts) => {- const webhook = await Webhook.fromId(opts.ctx, opts.input.webhookId);+ const webhook = await opts.ctx.webhooksService.get(+ opts.ctx.actor,+ opts.input.webhookId,+ );+return opts.next({ctx: {...opts.ctx,@@ -25,35 +54,31 @@ export const ensureWebhookOwnership = experimental_trpcMiddleware<{});export const webhooksAppRouter = router({- create: authedProcedure+ create: webhooksProcedure.input(zNewWebhookSchema).output(zWebhookSchema).mutation(async ({ input, ctx }) => {- const webhook = await Webhook.create(ctx, input);- return webhook.asPublicWebhook();+ const webhook = await ctx.webhooksService.create(ctx.actor, input);+ return toPublicWebhook(webhook);}),- update: authedProcedure+ update: webhooksProcedure.input(zUpdateWebhookSchema).output(zWebhookSchema).use(ensureWebhookOwnership).mutation(async ({ input, ctx }) => {- await ctx.webhook.update(input);- return ctx.webhook.asPublicWebhook();+ const updated = await ctx.webhooksService.update(ctx.webhook, input);+ return toPublicWebhook(updated);}),- list: authedProcedure+ list: webhooksProcedure.output(z.object({ webhooks: z.array(zWebhookSchema) })).query(async ({ ctx }) => {- const webhooks = await Webhook.getAll(ctx);- return { webhooks: webhooks.map((w) => w.asPublicWebhook()) };+ const webhooks = await ctx.webhooksService.getAll(ctx.actor);+ return { webhooks: webhooks.map(toPublicWebhook) };}),- delete: authedProcedure- .input(- z.object({- webhookId: z.string(),- }),- )+ delete: webhooksProcedure+ .input(z.object({ webhookId: z.string() })).use(ensureWebhookOwnership).mutation(async ({ ctx }) => {- await ctx.webhook.delete();+ await ctx.webhooksService.delete(ctx.webhook);}),});