Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

feat: add granular API key scopes (#2731)

Mohamed Bassemd95e6f8f5d08
diff --git a/apps/web/app/settings/api-keys/page.tsx b/apps/web/app/settings/api-keys/page.tsx
index 828548de..2ddfcb1f 100644
--- a/apps/web/app/settings/api-keys/page.tsx
+++ b/apps/web/app/settings/api-keys/page.tsx
@@ -3,6 +3,7 @@ import AddApiKey from "@/components/settings/AddApiKey";
import ApiKeySettings from "@/components/settings/ApiKeySettings";
import { SettingsPage } from "@/components/settings/SettingsPage";
import { useTranslation } from "@/lib/i18n/server";
+import { getServerAuthSession } from "@/server/auth";
export async function generateMetadata(): Promise<Metadata> {
// oxlint-disable-next-line rules-of-hooks
@@ -15,12 +16,14 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function ApiKeysPage() {
// oxlint-disable-next-line rules-of-hooks
const { t } = await useTranslation();
+ const session = await getServerAuthSession();
+ const isAdmin = session?.user.role === "admin";
return (
<SettingsPage
title={t("settings.api_keys.api_keys")}
- action={<AddApiKey />}
+ action={<AddApiKey isAdmin={isAdmin} />}
>
- <ApiKeySettings />
+ <ApiKeySettings isAdmin={isAdmin} />
</SettingsPage>
);
}
diff --git a/apps/web/components/settings/AddApiKey.tsx b/apps/web/components/settings/AddApiKey.tsx
index b6612a51..9bf49113 100644
--- a/apps/web/components/settings/AddApiKey.tsx
+++ b/apps/web/components/settings/AddApiKey.tsx
@@ -1,7 +1,7 @@
"use client";
import type { SubmitErrorHandler } from "react-hook-form";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ActionButton } from "@/components/ui/action-button";
import { Button } from "@/components/ui/button";
@@ -24,24 +24,154 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
-import { toast } from "@/components/ui/sonner";
+import { Label } from "@/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { toast } from "sonner";
import { useTranslation } from "@/lib/i18n/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
-import { PlusCircle } from "lucide-react";
+import { HelpCircle, PlusCircle } from "lucide-react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useTRPC } from "@karakeep/shared-react/trpc";
+import { API_KEY_FULL_ACCESS_SCOPE } from "@karakeep/shared/types/apiKeys";
+import type { ZApiKeyScope } from "@karakeep/shared/types/apiKeys";
import ApiKeySuccess from "./ApiKeySuccess";
+import type { ScopeAccessChoice, ScopeOption } from "./apiKeyScopes";
+import {
+ API_KEY_ADMIN_SCOPE_OPTIONS,
+ API_KEY_SCOPE_OPTIONS,
+ FULL_ACCESS_SCOPE_OPTION,
+} from "./apiKeyScopes";
+
+const DIALOG_CLOSE_RESET_DELAY_MS = 200;
+
+function ScopeDescriptionPopover({
+ label,
+ description,
+ ariaLabel,
+}: {
+ label: string;
+ description: string;
+ ariaLabel: string;
+}) {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 text-muted-foreground hover:text-foreground"
+ aria-label={ariaLabel}
+ >
+ <HelpCircle className="h-3.5 w-3.5" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-72">
+ <div className="space-y-1">
+ <div className="text-sm font-medium">{label}</div>
+ <p className="text-sm leading-5 text-muted-foreground">
+ {description}
+ </p>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function ScopeChoiceRow({
+ option,
+ value,
+ disabled,
+ onChange,
+}: {
+ option: ScopeOption;
+ value: ScopeAccessChoice;
+ disabled: boolean;
+ onChange: (value: ScopeAccessChoice) => void;
+}) {
+ const { t } = useTranslation();
+ const label = t(option.labelKey);
+ const description = t(option.descriptionKey);
+ const readId = `${option.id}-read`;
+ const readwriteId = `${option.id}-readwrite`;
+ const noneId = `${option.id}-none`;
-function AddApiKeyForm({ onSuccess }: { onSuccess: (key: string) => void }) {
+ return (
+ <div className="flex flex-col gap-2 rounded-md border px-3 py-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
+ <div className="flex min-w-0 items-center gap-1 sm:flex-1">
+ <div className="text-sm font-medium">{label}</div>
+ <ScopeDescriptionPopover
+ label={label}
+ description={description}
+ ariaLabel={t("settings.api_keys.scopes.scope_details", {
+ scope: label,
+ })}
+ />
+ </div>
+ <RadioGroup
+ value={value}
+ onValueChange={(next) => onChange(next as ScopeAccessChoice)}
+ disabled={disabled}
+ className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 sm:shrink-0 sm:flex-nowrap sm:justify-end"
+ >
+ <div className="flex items-center gap-2">
+ <RadioGroupItem id={noneId} value="none" />
+ <Label
+ htmlFor={noneId}
+ className="whitespace-nowrap text-xs font-normal"
+ >
+ {t("settings.api_keys.scopes.access.none")}
+ </Label>
+ </div>
+ <div className="flex items-center gap-2">
+ <RadioGroupItem id={readId} value="read" />
+ <Label
+ htmlFor={readId}
+ className="whitespace-nowrap text-xs font-normal"
+ >
+ {t("settings.api_keys.scopes.access.read")}
+ </Label>
+ </div>
+ <div className="flex items-center gap-2">
+ <RadioGroupItem id={readwriteId} value="readwrite" />
+ <Label
+ htmlFor={readwriteId}
+ className="whitespace-nowrap text-xs font-normal"
+ >
+ {t("settings.api_keys.scopes.access.readwrite")}
+ </Label>
+ </div>
+ </RadioGroup>
+ </div>
+ );
+}
+
+function AddApiKeyForm({
+ isAdmin,
+ onSuccess,
+}: {
+ isAdmin: boolean;
+ onSuccess: (key: string) => void;
+}) {
const api = useTRPC();
const { t } = useTranslation();
const formSchema = z.object({
name: z.string(),
});
+ const [useFullAccess, setUseFullAccess] = useState(true);
+ const [scopeChoices, setScopeChoices] = useState<
+ Record<string, ScopeAccessChoice>
+ >({});
const router = useRouter();
const mutator = useMutation(
api.apiKeys.create.mutationOptions({
@@ -50,9 +180,8 @@ function AddApiKeyForm({ onSuccess }: { onSuccess: (key: string) => void }) {
router.refresh();
},
onError: () => {
- toast({
+ toast.error(undefined, {
description: t("common.something_went_wrong"),
- variant: "destructive",
});
},
}),
@@ -62,24 +191,54 @@ function AddApiKeyForm({ onSuccess }: { onSuccess: (key: string) => void }) {
resolver: zodResolver(formSchema),
});
+ const scopeOptions = isAdmin
+ ? [...API_KEY_SCOPE_OPTIONS, ...API_KEY_ADMIN_SCOPE_OPTIONS]
+ : API_KEY_SCOPE_OPTIONS;
+
+ function selectedScopes(): ZApiKeyScope[] {
+ if (useFullAccess) {
+ return [API_KEY_FULL_ACCESS_SCOPE];
+ }
+
+ const scopes = scopeOptions.flatMap((option) => {
+ const access = scopeChoices[option.id] ?? "none";
+ if (access === "read") {
+ return [option.readScope];
+ }
+ if (access === "readwrite") {
+ return [option.readwriteScope];
+ }
+ return [];
+ });
+
+ return scopes;
+ }
+
async function onSubmit(value: z.infer<typeof formSchema>) {
- mutator.mutate({ name: value.name });
+ const scopes = selectedScopes();
+ if (scopes.length === 0) {
+ toast.error(undefined, {
+ description: t("settings.api_keys.scopes.choose_at_least_one"),
+ });
+ return;
+ }
+ mutator.mutate({ name: value.name, scopes });
}
const onError: SubmitErrorHandler<z.infer<typeof formSchema>> = (errors) => {
- toast({
+ toast.error(undefined, {
description: Object.values(errors)
.map((v) => v.message)
.join("\n"),
- variant: "destructive",
});
};
return (
<Form {...form}>
<form
+ id="add-api-key-form"
onSubmit={form.handleSubmit(onSubmit, onError)}
- className="flex w-full space-x-3 space-y-8 pt-4"
+ className="flex min-h-0 flex-col gap-4 pt-4"
>
<FormField
control={form.control}
@@ -103,27 +262,134 @@ function AddApiKeyForm({ onSuccess }: { onSuccess: (key: string) => void }) {
);
}}
/>
- <ActionButton type="submit" loading={mutator.isPending}>
- {t("actions.create")}
- </ActionButton>
+ <div className="space-y-3">
+ <div>
+ <div className="text-sm font-medium">
+ {t("settings.api_keys.scopes.scopes")}
+ </div>
+ </div>
+ <RadioGroup
+ value={useFullAccess ? "fullaccess" : "scoped"}
+ onValueChange={(value) => setUseFullAccess(value === "fullaccess")}
+ className="grid gap-2 sm:grid-cols-2"
+ >
+ <div className="flex items-start gap-3 rounded-md border p-3">
+ <RadioGroupItem
+ id="api-key-fullaccess"
+ value="fullaccess"
+ className="mt-1"
+ />
+ <div className="flex min-w-0 items-center gap-1">
+ <Label
+ htmlFor="api-key-fullaccess"
+ className="text-sm font-medium"
+ >
+ {t(FULL_ACCESS_SCOPE_OPTION.labelKey)}
+ </Label>
+ <ScopeDescriptionPopover
+ label={t(FULL_ACCESS_SCOPE_OPTION.labelKey)}
+ description={t(FULL_ACCESS_SCOPE_OPTION.descriptionKey)}
+ ariaLabel={t("settings.api_keys.scopes.scope_details", {
+ scope: t(FULL_ACCESS_SCOPE_OPTION.labelKey),
+ })}
+ />
+ </div>
+ </div>
+ <div className="flex items-start gap-3 rounded-md border p-3">
+ <RadioGroupItem
+ id="api-key-custom-scopes"
+ value="scoped"
+ className="mt-1"
+ />
+ <div className="flex min-w-0 items-center gap-1">
+ <Label
+ htmlFor="api-key-custom-scopes"
+ className="text-sm font-medium"
+ >
+ {t("settings.api_keys.scopes.limited_scopes.label")}
+ </Label>
+ <ScopeDescriptionPopover
+ label={t("settings.api_keys.scopes.limited_scopes.label")}
+ description={t(
+ "settings.api_keys.scopes.limited_scopes.description",
+ )}
+ ariaLabel={t("settings.api_keys.scopes.scope_details", {
+ scope: t("settings.api_keys.scopes.limited_scopes.label"),
+ })}
+ />
+ </div>
+ </div>
+ </RadioGroup>
+ {!useFullAccess && (
+ <ScrollArea className="h-[44vh] max-h-[28rem] min-h-48 pr-3">
+ <div className="space-y-1.5">
+ {scopeOptions
+ .filter((option) => !option.hidden)
+ .map((option) => (
+ <ScopeChoiceRow
+ key={option.id}
+ option={option}
+ value={scopeChoices[option.id] ?? "none"}
+ disabled={useFullAccess}
+ onChange={(value) =>
+ setScopeChoices((current) => ({
+ ...current,
+ [option.id]: value,
+ }))
+ }
+ />
+ ))}
+ </div>
+ </ScrollArea>
+ )}
+ </div>
+ <div className="flex justify-end gap-2">
+ <DialogClose asChild>
+ <Button type="button" variant="outline">
+ {t("actions.close")}
+ </Button>
+ </DialogClose>
+ <ActionButton type="submit" loading={mutator.isPending}>
+ {t("actions.create")}
+ </ActionButton>
+ </div>
</form>
</Form>
);
}
-export default function AddApiKey() {
+export default function AddApiKey({ isAdmin }: { isAdmin: boolean }) {
const { t } = useTranslation();
const [key, setKey] = useState<string | undefined>(undefined);
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
+ useEffect(() => {
+ if (dialogOpen) {
+ return;
+ }
+
+ const timeoutId = window.setTimeout(
+ () => setKey(undefined),
+ DIALOG_CLOSE_RESET_DELAY_MS,
+ );
+ return () => window.clearTimeout(timeoutId);
+ }, [dialogOpen]);
+
+ function handleOpenChange(open: boolean) {
+ if (open) {
+ setKey(undefined);
+ }
+ setDialogOpen(open);
+ }
+
return (
- <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <Dialog open={dialogOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button>
<PlusCircle className="mr-2 h-4 w-4" />
{t("settings.api_keys.new_api_key")}
</Button>
</DialogTrigger>
- <DialogContent>
+ <DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-3xl">
<DialogHeader>
<DialogTitle>
{key
@@ -137,19 +403,17 @@ export default function AddApiKey() {
message={t("settings.api_keys.key_success")}
/>
) : (
- <AddApiKeyForm onSuccess={setKey} />
+ <AddApiKeyForm isAdmin={isAdmin} onSuccess={setKey} />
+ )}
+ {key && (
+ <DialogFooter className="sm:justify-end">
+ <DialogClose asChild>
+ <Button type="button" variant="outline">
+ {t("actions.close")}
+ </Button>
+ </DialogClose>
+ </DialogFooter>
)}
- <DialogFooter className="sm:justify-end">
- <DialogClose asChild>
- <Button
- type="button"
- variant="outline"
- onClick={() => setKey(undefined)}
- >
- {t("actions.close")}
- </Button>
- </DialogClose>
- </DialogFooter>
</DialogContent>
</Dialog>
);
diff --git a/apps/web/components/settings/ApiKeySettings.tsx b/apps/web/components/settings/ApiKeySettings.tsx
index 4e0f5dc3..90646b3f 100644
--- a/apps/web/components/settings/ApiKeySettings.tsx
+++ b/apps/web/components/settings/ApiKeySettings.tsx
@@ -1,3 +1,4 @@
+import { Badge } from "@/components/ui/badge";
import {
Table,
TableBody,
@@ -13,8 +14,9 @@ import { formatDistanceToNow } from "date-fns";
import DeleteApiKey from "./DeleteApiKey";
import RegenerateApiKey from "./RegenerateApiKey";
import { SettingsSection } from "./SettingsPage";
+import { isAdminScope, scopeLabel } from "./apiKeyScopes";
-export default async function ApiKeys() {
+export default async function ApiKeys({ isAdmin }: { isAdmin: boolean }) {
// oxlint-disable-next-line rules-of-hooks
const { t } = await useTranslation();
const keys = await api.apiKeys.list();
@@ -25,6 +27,7 @@ export default async function ApiKeys() {
<TableRow>
<TableHead>{t("common.name")}</TableHead>
<TableHead>{t("common.key")}</TableHead>
+ <TableHead>{t("settings.api_keys.scopes.scopes")}</TableHead>
<TableHead>{t("common.created_at")}</TableHead>
<TableHead>{t("common.last_used")}</TableHead>
<TableHead>{t("common.action")}</TableHead>
@@ -32,10 +35,22 @@ export default async function ApiKeys() {
</TableHeader>
<TableBody>
{keys.keys.map((key) => {
+ const visibleScopes = key.scopes.filter(
+ (scope) => isAdmin || !isAdminScope(scope),
+ );
return (
<TableRow key={key.id}>
<TableCell>{key.name}</TableCell>
<TableCell>**_{key.keyId}_**</TableCell>
+ <TableCell>
+ <div className="flex max-w-72 flex-wrap gap-1">
+ {visibleScopes.map((scope) => (
+ <Badge key={scope} variant="outline">
+ {scopeLabel(t, scope)}
+ </Badge>
+ ))}
+ </div>
+ </TableCell>
<TableCell>
{formatDistanceToNow(key.createdAt, { addSuffix: true })}
</TableCell>
diff --git a/apps/web/components/settings/apiKeyScopes.ts b/apps/web/components/settings/apiKeyScopes.ts
new file mode 100644
index 00000000..76cef8b2
--- /dev/null
+++ b/apps/web/components/settings/apiKeyScopes.ts
@@ -0,0 +1,195 @@
+import type {
+ ZApiKeyAdminScopeResource,
+ ZApiKeyScope,
+ ZApiKeyScopeAccess,
+ ZApiKeyScopeResource,
+} from "@karakeep/shared/types/apiKeys";
+import type { TFunction } from "i18next";
+import {
+ API_KEY_ADMIN_SCOPE_RESOURCES,
+ API_KEY_FULL_ACCESS_SCOPE,
+ API_KEY_SCOPE_RESOURCES,
+ getAdminApiKeyScope,
+ getApiKeyScope,
+} from "@karakeep/shared/types/apiKeys";
+
+export type ScopeAccessChoice = "none" | ZApiKeyScopeAccess;
+
+export interface ScopeOption {
+ id: ZApiKeyScopeResource | `admin:${ZApiKeyAdminScopeResource}`;
+ labelKey: ApiKeyScopeTranslationKey;
+ descriptionKey: ApiKeyScopeTranslationKey;
+ readScope: ZApiKeyScope;
+ readwriteScope: ZApiKeyScope;
+ adminOnly?: boolean;
+ hidden: boolean;
+}
+
+const RESOURCE_TRANSLATION_KEYS = {
+ assets: {
+ labelKey: "settings.api_keys.scopes.resources.assets.label",
+ descriptionKey: "settings.api_keys.scopes.resources.assets.description",
+ hidden: false,
+ },
+ backups: {
+ labelKey: "settings.api_keys.scopes.resources.backups.label",
+ descriptionKey: "settings.api_keys.scopes.resources.backups.description",
+ hidden: false,
+ },
+ bookmarks: {
+ labelKey: "settings.api_keys.scopes.resources.bookmarks.label",
+ descriptionKey: "settings.api_keys.scopes.resources.bookmarks.description",
+ hidden: false,
+ },
+ feeds: {
+ labelKey: "settings.api_keys.scopes.resources.feeds.label",
+ descriptionKey: "settings.api_keys.scopes.resources.feeds.description",
+ hidden: false,
+ },
+ highlights: {
+ labelKey: "settings.api_keys.scopes.resources.highlights.label",
+ descriptionKey: "settings.api_keys.scopes.resources.highlights.description",
+ hidden: false,
+ },
+ lists: {
+ labelKey: "settings.api_keys.scopes.resources.lists.label",
+ descriptionKey: "settings.api_keys.scopes.resources.lists.description",
+ hidden: false,
+ },
+ prompts: {
+ labelKey: "settings.api_keys.scopes.resources.prompts.label",
+ descriptionKey: "settings.api_keys.scopes.resources.prompts.description",
+ hidden: false,
+ },
+ rules: {
+ labelKey: "settings.api_keys.scopes.resources.rules.label",
+ descriptionKey: "settings.api_keys.scopes.resources.rules.description",
+ hidden: false,
+ },
+ tags: {
+ labelKey: "settings.api_keys.scopes.resources.tags.label",
+ descriptionKey: "settings.api_keys.scopes.resources.tags.description",
+ hidden: false,
+ },
+ users: {
+ labelKey: "settings.api_keys.scopes.resources.users.label",
+ descriptionKey: "settings.api_keys.scopes.resources.users.description",
+ hidden: false,
+ },
+ webhooks: {
+ labelKey: "settings.api_keys.scopes.resources.webhooks.label",
+ descriptionKey: "settings.api_keys.scopes.resources.webhooks.description",
+ hidden: false,
+ },
+ importSessions: {
+ labelKey: "settings.api_keys.scopes.resources.importSessions.label",
+ descriptionKey:
+ "settings.api_keys.scopes.resources.importSessions.description",
+ hidden: true,
+ },
+ subscriptions: {
+ labelKey: "settings.api_keys.scopes.resources.subscriptions.label",
+ descriptionKey:
+ "settings.api_keys.scopes.resources.subscriptions.description",
+ hidden: true,
+ },
+} as const satisfies Record<
+ ZApiKeyScopeResource,
+ { labelKey: string; descriptionKey: string; hidden: boolean }
+>;
+
+const ADMIN_RESOURCE_TRANSLATION_KEYS = {
+ bookmarks: {
+ labelKey: "settings.api_keys.scopes.admin_resources.bookmarks.label",
+ descriptionKey:
+ "settings.api_keys.scopes.admin_resources.bookmarks.description",
+ },
+ jobs: {
+ labelKey: "settings.api_keys.scopes.admin_resources.jobs.label",
+ descriptionKey: "settings.api_keys.scopes.admin_resources.jobs.description",
+ },
+ system: {
+ labelKey: "settings.api_keys.scopes.admin_resources.system.label",
+ descriptionKey:
+ "settings.api_keys.scopes.admin_resources.system.description",
+ },
+ users: {
+ labelKey: "settings.api_keys.scopes.admin_resources.users.label",
+ descriptionKey:
+ "settings.api_keys.scopes.admin_resources.users.description",
+ },
+} as const satisfies Record<
+ ZApiKeyAdminScopeResource,
+ { labelKey: string; descriptionKey: string }
+>;
+
+type ResourceTranslationKey =
+ | (typeof RESOURCE_TRANSLATION_KEYS)[keyof typeof RESOURCE_TRANSLATION_KEYS]["labelKey"]
+ | (typeof RESOURCE_TRANSLATION_KEYS)[keyof typeof RESOURCE_TRANSLATION_KEYS]["descriptionKey"];
+
+type AdminResourceTranslationKey =
+ | (typeof ADMIN_RESOURCE_TRANSLATION_KEYS)[keyof typeof ADMIN_RESOURCE_TRANSLATION_KEYS]["labelKey"]
+ | (typeof ADMIN_RESOURCE_TRANSLATION_KEYS)[keyof typeof ADMIN_RESOURCE_TRANSLATION_KEYS]["descriptionKey"];
+
+export type ApiKeyScopeTranslationKey =
+ | ResourceTranslationKey
+ | AdminResourceTranslationKey
+ | "settings.api_keys.scopes.full_access.label"
+ | "settings.api_keys.scopes.full_access.description";
+
+export const FULL_ACCESS_SCOPE_OPTION = {
+ scope: API_KEY_FULL_ACCESS_SCOPE,
+ labelKey: "settings.api_keys.scopes.full_access.label",
+ descriptionKey: "settings.api_keys.scopes.full_access.description",
+} as const;
+
+export const API_KEY_SCOPE_OPTIONS: ScopeOption[] = API_KEY_SCOPE_RESOURCES.map(
+ (resource) => ({
+ id: resource,
+ labelKey: RESOURCE_TRANSLATION_KEYS[resource].labelKey,
+ descriptionKey: RESOURCE_TRANSLATION_KEYS[resource].descriptionKey,
+ readScope: getApiKeyScope(resource, "read"),
+ readwriteScope: getApiKeyScope(resource, "readwrite"),
+ hidden: RESOURCE_TRANSLATION_KEYS[resource].hidden,
+ }),
+);
+
+export const API_KEY_ADMIN_SCOPE_OPTIONS: ScopeOption[] =
+ API_KEY_ADMIN_SCOPE_RESOURCES.map((resource) => ({
+ id: `admin:${resource}`,
+ labelKey: ADMIN_RESOURCE_TRANSLATION_KEYS[resource].labelKey,
+ descriptionKey: ADMIN_RESOURCE_TRANSLATION_KEYS[resource].descriptionKey,
+ readScope: getAdminApiKeyScope(resource, "read"),
+ readwriteScope: getAdminApiKeyScope(resource, "readwrite"),
+ adminOnly: true,
+ hidden: false,
+ }));
+
+export const API_KEY_ALL_SCOPE_OPTIONS = [
+ ...API_KEY_SCOPE_OPTIONS,
+ ...API_KEY_ADMIN_SCOPE_OPTIONS,
+];
+
+export function scopeLabel(t: TFunction, scope: ZApiKeyScope) {
+ if (scope === API_KEY_FULL_ACCESS_SCOPE) {
+ return t(FULL_ACCESS_SCOPE_OPTION.labelKey);
+ }
+
+ const option = API_KEY_ALL_SCOPE_OPTIONS.find(
+ (candidate) =>
+ candidate.readScope === scope || candidate.readwriteScope === scope,
+ );
+ if (!option) {
+ return scope;
+ }
+
+ const accessLabel = scope.endsWith(":readwrite")
+ ? t("settings.api_keys.scopes.access.readwrite")
+ : t("settings.api_keys.scopes.access.read");
+
+ return `${t(option.labelKey)}: ${accessLabel}`;
+}
+
+export function isAdminScope(scope: ZApiKeyScope) {
+ return scope.startsWith("admin:");
+}
diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.json
index 07d43701..3e9d592b 100644
--- a/apps/web/lib/i18n/locales/en/translation.json
+++ b/apps/web/lib/i18n/locales/en/translation.json
@@ -326,7 +326,97 @@
"key_regenerated": "Key was successfully regenerated",
"key_regenerated_please_copy": "Please copy the new key and store it somewhere safe. The old key has been revoked and will no longer work.",
"regenerate_warning": "Are you sure you want to regenerate the API key \"{{name}}\"?",
- "regenerate_confirmation": "This will revoke the current key and generate a new one. Any applications using the current key will stop working."
+ "regenerate_confirmation": "This will revoke the current key and generate a new one. Any applications using the current key will stop working.",
+ "scopes": {
+ "scopes": "Scopes",
+ "choose_at_least_one": "Choose at least one scope or select full access.",
+ "scope_details": "{{scope}} scope details",
+ "access": {
+ "none": "None",
+ "read": "Read",
+ "readwrite": "Read/write"
+ },
+ "full_access": {
+ "label": "Full access",
+ "description": "Access all supported API operations."
+ },
+ "limited_scopes": {
+ "label": "Limited scopes",
+ "description": "Choose the resource types this key can access."
+ },
+ "resources": {
+ "assets": {
+ "label": "Assets",
+ "description": "Access files and other stored bookmark content."
+ },
+ "backups": {
+ "label": "Backups",
+ "description": "Manage account backups."
+ },
+ "bookmarks": {
+ "label": "Bookmarks",
+ "description": "Access and manage bookmarks."
+ },
+ "feeds": {
+ "label": "Feeds",
+ "description": "Manage RSS feeds and related feed data."
+ },
+ "highlights": {
+ "label": "Highlights",
+ "description": "Manage saved bookmark highlights."
+ },
+ "lists": {
+ "label": "Lists",
+ "description": "Manage lists and list membership."
+ },
+ "prompts": {
+ "label": "Prompts",
+ "description": "Manage saved AI prompt configuration."
+ },
+ "rules": {
+ "label": "Rules",
+ "description": "Access automation rules."
+ },
+ "tags": {
+ "label": "Tags",
+ "description": "Access and modify tags."
+ },
+ "users": {
+ "label": "User account",
+ "description": "Access account profile and settings."
+ },
+ "webhooks": {
+ "label": "Webhooks",
+ "description": "Access webhook configuration."
+ },
+ "subscriptions": {
+ "label": "Subscriptions",
+ "description": "Access subscription management."
+ },
+ "importSessions": {
+ "label": "Import Sessions",
+ "description": "Access import sessions."
+ }
+ },
+ "admin_resources": {
+ "bookmarks": {
+ "label": "Admin: bookmarks",
+ "description": "Access administrative bookmark tools."
+ },
+ "jobs": {
+ "label": "Admin: jobs",
+ "description": "Access background job controls."
+ },
+ "system": {
+ "label": "Admin: system",
+ "description": "Access system status and diagnostics."
+ },
+ "users": {
+ "label": "Admin: users",
+ "description": "Access administrative user management."
+ }
+ }
+ }
},
"broken_links": {
"broken_links": "Broken Links",
diff --git a/apps/web/server/api/client.ts b/apps/web/server/api/client.ts
index 0795d8c3..028c2ddf 100644
--- a/apps/web/server/api/client.ts
+++ b/apps/web/server/api/client.ts
@@ -17,9 +17,14 @@ export async function createContextFromRequest(req: Request) {
if (authorizationHeader && authorizationHeader.startsWith("Bearer ")) {
const token = authorizationHeader.split(" ")[1];
try {
- const user = await authenticateApiKey(token, db);
+ const authResult = await authenticateApiKey(token, db);
return {
- user,
+ user: authResult.user,
+ auth: {
+ type: "apiKey" as const,
+ keyId: authResult.apiKey.keyId,
+ scopes: authResult.apiKey.scopes,
+ },
db,
req: {
ip,
@@ -46,6 +51,11 @@ export const createContext = async (
}
return {
user: session?.user ?? null,
+ auth: session?.user
+ ? {
+ type: "session" as const,
+ }
+ : null,
db: database ?? db,
req: {
ip,
diff --git a/packages/api/middlewares/apiKeyScopes.ts b/packages/api/middlewares/apiKeyScopes.ts
new file mode 100644
index 00000000..96ddcd5a
--- /dev/null
+++ b/packages/api/middlewares/apiKeyScopes.ts
@@ -0,0 +1,39 @@
+import { createMiddleware } from "hono/factory";
+import { HTTPException } from "hono/http-exception";
+
+import {
+ apiKeyScopesGrantScope,
+ getApiKeyScope,
+} from "@karakeep/shared/types/apiKeys";
+import type {
+ ZApiKeyScopeAccess,
+ ZApiKeyScopeResource,
+} from "@karakeep/shared/types/apiKeys";
+import type { AuthedContext } from "@karakeep/trpc";
+
+export function apiKeyScopeMiddleware(
+ resource: ZApiKeyScopeResource,
+ access: ZApiKeyScopeAccess,
+) {
+ return createMiddleware<{
+ Variables: {
+ ctx: AuthedContext;
+ };
+ }>(async (c, next) => {
+ const auth = c.var.ctx.auth;
+ if (auth?.type !== "apiKey") {
+ await next();
+ return;
+ }
+
+ const scope = getApiKeyScope(resource, access);
+ if (apiKeyScopesGrantScope(auth.scopes, scope)) {
+ await next();
+ return;
+ }
+
+ throw new HTTPException(403, {
+ message: `API key is missing required scope: ${scope}`,
+ });
+ });
+}
diff --git a/packages/api/routes/assets.ts b/packages/api/routes/assets.ts
index 0b05518d..f73852b7 100644
--- a/packages/api/routes/assets.ts
+++ b/packages/api/routes/assets.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { Asset } from "@karakeep/trpc/models/assets";
+import { apiKeyScopeMiddleware } from "../middlewares/apiKeyScopes";
import { authMiddleware } from "../middlewares/auth";
import { createRateLimitMiddleware } from "../middlewares/rateLimit";
import { serveAsset } from "../utils/assets";
@@ -13,6 +14,7 @@ const app = new Hono()
.use(authMiddleware)
.post(
"/",
+ apiKeyScopeMiddleware("assets", "readwrite"),
createRateLimitMiddleware({
name: "assets.upload",
windowMs: 60 * 1000,
@@ -38,7 +40,7 @@ const app = new Hono()
});
},
)
- .get("/:assetId", async (c) => {
+ .get("/:assetId", apiKeyScopeMiddleware("assets", "read"), async (c) => {
const assetId = c.req.param("assetId");
const asset = await Asset.fromId(c.var.ctx, assetId);
diff --git a/packages/api/routes/bookmarks.ts b/packages/api/routes/bookmarks.ts
index 3217243f..d0fd03c3 100644
--- a/packages/api/routes/bookmarks.ts
+++ b/packages/api/routes/bookmarks.ts
@@ -10,6 +10,7 @@ import {
zUpdateBookmarksRequestSchema,
} from "@karakeep/shared/types/bookmarks";
+import { apiKeyScopeMiddleware } from "../middlewares/apiKeyScopes";
import { authMiddleware } from "../middlewares/auth";
import { adaptPagination, zPagination } from "../utils/pagination";
import {
@@ -109,6 +110,8 @@ const app = new Hono()
.post(
"/singlefile",
+ apiKeyScopeMiddleware("assets", "readwrite"),
+ apiKeyScopeMiddleware("bookmarks", "readwrite"),
zValidator(
"query",
z.object({
diff --git a/packages/db/drizzle/0083_add_api_key_scopes.sql b/packages/db/drizzle/0083_add_api_key_scopes.sql
new file mode 100644
index 00000000..d3f282fe
--- /dev/null
+++ b/packages/db/drizzle/0083_add_api_key_scopes.sql
@@ -0,0 +1 @@
+ALTER TABLE `apiKey` ADD `scopes` text DEFAULT '["fullaccess"]' NOT NULL;
diff --git a/packages/db/drizzle/meta/0083_snapshot.json b/packages/db/drizzle/meta/0083_snapshot.json
new file mode 100644
index 00000000..851ca082
--- /dev/null
+++ b/packages/db/drizzle/meta/0083_snapshot.json
@@ -0,0 +1,3370 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "324628ba-d45a-40f9-8b5b-87fdfaa61837",
+ "prevId": "7e3724a4-7348-4f8f-afd3-12bfce51e5f3",
+ "tables": {
+ "account": {
+ "name": "account",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "account_provider_providerAccountId_pk": {
+ "columns": [
+ "provider",
+ "providerAccountId"
+ ],
+ "name": "account_provider_providerAccountId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "apiKey": {
+ "name": "apiKey",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "keyId": {
+ "name": "keyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyHash": {
+ "name": "keyHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "apiKey_keyId_unique": {
+ "name": "apiKey_keyId_unique",
+ "columns": [
+ "keyId"
+ ],
+ "isUnique": true
+ },
+ "apiKey_name_userId_unique": {
+ "name": "apiKey_name_userId_unique",
+ "columns": [
+ "name",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "apiKey_userId_user_id_fk": {
+ "name": "apiKey_userId_user_id_fk",
+ "tableFrom": "apiKey",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "assets": {
+ "name": "assets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetType": {
+ "name": "assetType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "contentType": {
+ "name": "contentType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fileName": {
+ "name": "fileName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "assets_bookmarkId_idx": {
+ "name": "assets_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "assets_assetType_idx": {
+ "name": "assets_assetType_idx",
+ "columns": [
+ "assetType"
+ ],
+ "isUnique": false
+ },
+ "assets_userId_idx": {
+ "name": "assets_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "assets_bookmarkId_bookmarks_id_fk": {
+ "name": "assets_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "assets",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "assets_userId_user_id_fk": {
+ "name": "assets_userId_user_id_fk",
+ "tableFrom": "assets",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "backups": {
+ "name": "backups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetId": {
+ "name": "assetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkCount": {
+ "name": "bookmarkCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "errorMessage": {
+ "name": "errorMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "backups_userId_idx": {
+ "name": "backups_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "backups_createdAt_idx": {
+ "name": "backups_createdAt_idx",
+ "columns": [
+ "createdAt"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "backups_userId_user_id_fk": {
+ "name": "backups_userId_user_id_fk",
+ "tableFrom": "backups",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "backups_assetId_assets_id_fk": {
+ "name": "backups_assetId_assets_id_fk",
+ "tableFrom": "backups",
+ "tableTo": "assets",
+ "columnsFrom": [
+ "assetId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkAssets": {
+ "name": "bookmarkAssets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetType": {
+ "name": "assetType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "assetId": {
+ "name": "assetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fileName": {
+ "name": "fileName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sourceUrl": {
+ "name": "sourceUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "bookmarkAssets_id_bookmarks_id_fk": {
+ "name": "bookmarkAssets_id_bookmarks_id_fk",
+ "tableFrom": "bookmarkAssets",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkLinks": {
+ "name": "bookmarkLinks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "publisher": {
+ "name": "publisher",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "datePublished": {
+ "name": "datePublished",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dateModified": {
+ "name": "dateModified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "imageUrl": {
+ "name": "imageUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "favicon": {
+ "name": "favicon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "htmlContent": {
+ "name": "htmlContent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "contentAssetId": {
+ "name": "contentAssetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "crawledAt": {
+ "name": "crawledAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "crawlStatus": {
+ "name": "crawlStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "crawlStatusCode": {
+ "name": "crawlStatusCode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 200
+ }
+ },
+ "indexes": {
+ "bookmarkLinks_url_idx": {
+ "name": "bookmarkLinks_url_idx",
+ "columns": [
+ "url"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bookmarkLinks_id_bookmarks_id_fk": {
+ "name": "bookmarkLinks_id_bookmarks_id_fk",
+ "tableFrom": "bookmarkLinks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkLists": {
+ "name": "bookmarkLists",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "query": {
+ "name": "query",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rssToken": {
+ "name": "rssToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "bookmarkLists_userId_idx": {
+ "name": "bookmarkLists_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "bookmarkLists_userId_id_idx": {
+ "name": "bookmarkLists_userId_id_idx",
+ "columns": [
+ "userId",
+ "id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bookmarkLists_userId_user_id_fk": {
+ "name": "bookmarkLists_userId_user_id_fk",
+ "tableFrom": "bookmarkLists",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bookmarkLists_parentId_bookmarkLists_id_fk": {
+ "name": "bookmarkLists_parentId_bookmarkLists_id_fk",
+ "tableFrom": "bookmarkLists",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "parentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkTags": {
+ "name": "bookmarkTags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "normalizedName": {
+ "name": "normalizedName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "generated": {
+ "as": "(lower(replace(replace(replace(\"name\", ' ', ''), '-', ''), '_', '')))",
+ "type": "virtual"
+ }
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "bookmarkTags_name_idx": {
+ "name": "bookmarkTags_name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": false
+ },
+ "bookmarkTags_userId_idx": {
+ "name": "bookmarkTags_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "bookmarkTags_normalizedName_idx": {
+ "name": "bookmarkTags_normalizedName_idx",
+ "columns": [
+ "normalizedName"
+ ],
+ "isUnique": false
+ },
+ "bookmarkTags_userId_name_unique": {
+ "name": "bookmarkTags_userId_name_unique",
+ "columns": [
+ "userId",
+ "name"
+ ],
+ "isUnique": true
+ },
+ "bookmarkTags_userId_id_idx": {
+ "name": "bookmarkTags_userId_id_idx",
+ "columns": [
+ "userId",
+ "id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bookmarkTags_userId_user_id_fk": {
+ "name": "bookmarkTags_userId_user_id_fk",
+ "tableFrom": "bookmarkTags",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarkTexts": {
+ "name": "bookmarkTexts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sourceUrl": {
+ "name": "sourceUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "bookmarkTexts_id_bookmarks_id_fk": {
+ "name": "bookmarkTexts_id_bookmarks_id_fk",
+ "tableFrom": "bookmarkTexts",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarks": {
+ "name": "bookmarks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "favourited": {
+ "name": "favourited",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "taggingStatus": {
+ "name": "taggingStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "summarizationStatus": {
+ "name": "summarizationStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "bookmarks_userId_idx": {
+ "name": "bookmarks_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_createdAt_idx": {
+ "name": "bookmarks_createdAt_idx",
+ "columns": [
+ "createdAt"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_userId_createdAt_id_idx": {
+ "name": "bookmarks_userId_createdAt_id_idx",
+ "columns": [
+ "userId",
+ "createdAt",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_userId_archived_createdAt_id_idx": {
+ "name": "bookmarks_userId_archived_createdAt_id_idx",
+ "columns": [
+ "userId",
+ "archived",
+ "createdAt",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "bookmarks_userId_favourited_createdAt_id_idx": {
+ "name": "bookmarks_userId_favourited_createdAt_id_idx",
+ "columns": [
+ "userId",
+ "favourited",
+ "createdAt",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bookmarks_userId_user_id_fk": {
+ "name": "bookmarks_userId_user_id_fk",
+ "tableFrom": "bookmarks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bookmarksInLists": {
+ "name": "bookmarksInLists",
+ "columns": {
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedAt": {
+ "name": "addedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "listMembershipId": {
+ "name": "listMembershipId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "bookmarksInLists_bookmarkId_idx": {
+ "name": "bookmarksInLists_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "bookmarksInLists_listId_idx": {
+ "name": "bookmarksInLists_listId_idx",
+ "columns": [
+ "listId"
+ ],
+ "isUnique": false
+ },
+ "bookmarksInLists_listId_bookmarkId_idx": {
+ "name": "bookmarksInLists_listId_bookmarkId_idx",
+ "columns": [
+ "listId",
+ "bookmarkId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bookmarksInLists_bookmarkId_bookmarks_id_fk": {
+ "name": "bookmarksInLists_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "bookmarksInLists",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bookmarksInLists_listId_bookmarkLists_id_fk": {
+ "name": "bookmarksInLists_listId_bookmarkLists_id_fk",
+ "tableFrom": "bookmarksInLists",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "listId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bookmarksInLists_listMembershipId_listCollaborators_id_fk": {
+ "name": "bookmarksInLists_listMembershipId_listCollaborators_id_fk",
+ "tableFrom": "bookmarksInLists",
+ "tableTo": "listCollaborators",
+ "columnsFrom": [
+ "listMembershipId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "bookmarksInLists_bookmarkId_listId_pk": {
+ "columns": [
+ "bookmarkId",
+ "listId"
+ ],
+ "name": "bookmarksInLists_bookmarkId_listId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "config": {
+ "name": "config",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "customPrompts": {
+ "name": "customPrompts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appliesTo": {
+ "name": "appliesTo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "customPrompts_userId_idx": {
+ "name": "customPrompts_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "customPrompts_userId_user_id_fk": {
+ "name": "customPrompts_userId_user_id_fk",
+ "tableFrom": "customPrompts",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "highlights": {
+ "name": "highlights",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "startOffset": {
+ "name": "startOffset",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endOffset": {
+ "name": "endOffset",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'yellow'"
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "highlights_bookmarkId_idx": {
+ "name": "highlights_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "highlights_userId_idx": {
+ "name": "highlights_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "highlights_bookmarkId_bookmarks_id_fk": {
+ "name": "highlights_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "highlights",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "highlights_userId_user_id_fk": {
+ "name": "highlights_userId_user_id_fk",
+ "tableFrom": "highlights",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "importSessionBookmarks": {
+ "name": "importSessionBookmarks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "importSessionId": {
+ "name": "importSessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "importSessionBookmarks_sessionId_idx": {
+ "name": "importSessionBookmarks_sessionId_idx",
+ "columns": [
+ "importSessionId"
+ ],
+ "isUnique": false
+ },
+ "importSessionBookmarks_bookmarkId_idx": {
+ "name": "importSessionBookmarks_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "importSessionBookmarks_importSessionId_bookmarkId_unique": {
+ "name": "importSessionBookmarks_importSessionId_bookmarkId_unique",
+ "columns": [
+ "importSessionId",
+ "bookmarkId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "importSessionBookmarks_importSessionId_importSessions_id_fk": {
+ "name": "importSessionBookmarks_importSessionId_importSessions_id_fk",
+ "tableFrom": "importSessionBookmarks",
+ "tableTo": "importSessions",
+ "columnsFrom": [
+ "importSessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "importSessionBookmarks_bookmarkId_bookmarks_id_fk": {
+ "name": "importSessionBookmarks_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "importSessionBookmarks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "importSessions": {
+ "name": "importSessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rootListId": {
+ "name": "rootListId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staging'"
+ },
+ "lastProcessedAt": {
+ "name": "lastProcessedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "importSessions_userId_idx": {
+ "name": "importSessions_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "importSessions_status_idx": {
+ "name": "importSessions_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "importSessions_userId_user_id_fk": {
+ "name": "importSessions_userId_user_id_fk",
+ "tableFrom": "importSessions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "importSessions_rootListId_bookmarkLists_id_fk": {
+ "name": "importSessions_rootListId_bookmarkLists_id_fk",
+ "tableFrom": "importSessions",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "rootListId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "importStagingBookmarks": {
+ "name": "importStagingBookmarks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "importSessionId": {
+ "name": "importSessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "listIds": {
+ "name": "listIds",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sourceAddedAt": {
+ "name": "sourceAddedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "processingStartedAt": {
+ "name": "processingStartedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resultReason": {
+ "name": "resultReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resultBookmarkId": {
+ "name": "resultBookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "completedAt": {
+ "name": "completedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "importStaging_session_status_idx": {
+ "name": "importStaging_session_status_idx",
+ "columns": [
+ "importSessionId",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "importStaging_completedAt_idx": {
+ "name": "importStaging_completedAt_idx",
+ "columns": [
+ "completedAt"
+ ],
+ "isUnique": false
+ },
+ "importStaging_status_idx": {
+ "name": "importStaging_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ },
+ "importStaging_status_processingStartedAt_idx": {
+ "name": "importStaging_status_processingStartedAt_idx",
+ "columns": [
+ "status",
+ "processingStartedAt"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "importStagingBookmarks_importSessionId_importSessions_id_fk": {
+ "name": "importStagingBookmarks_importSessionId_importSessions_id_fk",
+ "tableFrom": "importStagingBookmarks",
+ "tableTo": "importSessions",
+ "columnsFrom": [
+ "importSessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "importStagingBookmarks_resultBookmarkId_bookmarks_id_fk": {
+ "name": "importStagingBookmarks_resultBookmarkId_bookmarks_id_fk",
+ "tableFrom": "importStagingBookmarks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "resultBookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "invites": {
+ "name": "invites",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "usedAt": {
+ "name": "usedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "invites_token_unique": {
+ "name": "invites_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "invites_invitedBy_user_id_fk": {
+ "name": "invites_invitedBy_user_id_fk",
+ "tableFrom": "invites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "listCollaborators": {
+ "name": "listCollaborators",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedBy": {
+ "name": "addedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "listCollaborators_listId_idx": {
+ "name": "listCollaborators_listId_idx",
+ "columns": [
+ "listId"
+ ],
+ "isUnique": false
+ },
+ "listCollaborators_userId_idx": {
+ "name": "listCollaborators_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "listCollaborators_listId_userId_unique": {
+ "name": "listCollaborators_listId_userId_unique",
+ "columns": [
+ "listId",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "listCollaborators_listId_bookmarkLists_id_fk": {
+ "name": "listCollaborators_listId_bookmarkLists_id_fk",
+ "tableFrom": "listCollaborators",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "listId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listCollaborators_userId_user_id_fk": {
+ "name": "listCollaborators_userId_user_id_fk",
+ "tableFrom": "listCollaborators",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listCollaborators_addedBy_user_id_fk": {
+ "name": "listCollaborators_addedBy_user_id_fk",
+ "tableFrom": "listCollaborators",
+ "tableTo": "user",
+ "columnsFrom": [
+ "addedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "listInvitations": {
+ "name": "listInvitations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "invitedAt": {
+ "name": "invitedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedEmail": {
+ "name": "invitedEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "listInvitations_listId_idx": {
+ "name": "listInvitations_listId_idx",
+ "columns": [
+ "listId"
+ ],
+ "isUnique": false
+ },
+ "listInvitations_userId_idx": {
+ "name": "listInvitations_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "listInvitations_status_idx": {
+ "name": "listInvitations_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ },
+ "listInvitations_listId_userId_unique": {
+ "name": "listInvitations_listId_userId_unique",
+ "columns": [
+ "listId",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "listInvitations_listId_bookmarkLists_id_fk": {
+ "name": "listInvitations_listId_bookmarkLists_id_fk",
+ "tableFrom": "listInvitations",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "listId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listInvitations_userId_user_id_fk": {
+ "name": "listInvitations_userId_user_id_fk",
+ "tableFrom": "listInvitations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "listInvitations_invitedBy_user_id_fk": {
+ "name": "listInvitations_invitedBy_user_id_fk",
+ "tableFrom": "listInvitations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "passwordResetToken": {
+ "name": "passwordResetToken",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "passwordResetToken_token_unique": {
+ "name": "passwordResetToken_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "passwordResetTokens_userId_idx": {
+ "name": "passwordResetTokens_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "passwordResetToken_userId_user_id_fk": {
+ "name": "passwordResetToken_userId_user_id_fk",
+ "tableFrom": "passwordResetToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "rssFeedImports": {
+ "name": "rssFeedImports",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "entryId": {
+ "name": "entryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rssFeedId": {
+ "name": "rssFeedId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "rssFeedImports_feedIdIdx_idx": {
+ "name": "rssFeedImports_feedIdIdx_idx",
+ "columns": [
+ "rssFeedId"
+ ],
+ "isUnique": false
+ },
+ "rssFeedImports_entryIdIdx_idx": {
+ "name": "rssFeedImports_entryIdIdx_idx",
+ "columns": [
+ "entryId"
+ ],
+ "isUnique": false
+ },
+ "rssFeedImports_rssFeedId_bookmarkId_idx": {
+ "name": "rssFeedImports_rssFeedId_bookmarkId_idx",
+ "columns": [
+ "rssFeedId",
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "rssFeedImports_rssFeedId_entryId_unique": {
+ "name": "rssFeedImports_rssFeedId_entryId_unique",
+ "columns": [
+ "rssFeedId",
+ "entryId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "rssFeedImports_rssFeedId_rssFeeds_id_fk": {
+ "name": "rssFeedImports_rssFeedId_rssFeeds_id_fk",
+ "tableFrom": "rssFeedImports",
+ "tableTo": "rssFeeds",
+ "columnsFrom": [
+ "rssFeedId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rssFeedImports_bookmarkId_bookmarks_id_fk": {
+ "name": "rssFeedImports_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "rssFeedImports",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "rssFeeds": {
+ "name": "rssFeeds",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "importTags": {
+ "name": "importTags",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lastFetchedAt": {
+ "name": "lastFetchedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastSuccessfulFetchAt": {
+ "name": "lastSuccessfulFetchAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastFetchedStatus": {
+ "name": "lastFetchedStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "rssFeeds_userId_idx": {
+ "name": "rssFeeds_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "rssFeeds_userId_user_id_fk": {
+ "name": "rssFeeds_userId_user_id_fk",
+ "tableFrom": "rssFeeds",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ruleEngineActions": {
+ "name": "ruleEngineActions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ruleId": {
+ "name": "ruleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ruleEngineActions_userId_idx": {
+ "name": "ruleEngineActions_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "ruleEngineActions_ruleId_idx": {
+ "name": "ruleEngineActions_ruleId_idx",
+ "columns": [
+ "ruleId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ruleEngineActions_userId_user_id_fk": {
+ "name": "ruleEngineActions_userId_user_id_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineActions_ruleId_ruleEngineRules_id_fk": {
+ "name": "ruleEngineActions_ruleId_ruleEngineRules_id_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "ruleEngineRules",
+ "columnsFrom": [
+ "ruleId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineActions_userId_tagId_fk": {
+ "name": "ruleEngineActions_userId_tagId_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "bookmarkTags",
+ "columnsFrom": [
+ "userId",
+ "tagId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineActions_userId_listId_fk": {
+ "name": "ruleEngineActions_userId_listId_fk",
+ "tableFrom": "ruleEngineActions",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "userId",
+ "listId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ruleEngineRules": {
+ "name": "ruleEngineRules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event": {
+ "name": "event",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "condition": {
+ "name": "condition",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "listId": {
+ "name": "listId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ruleEngine_userId_idx": {
+ "name": "ruleEngine_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ruleEngineRules_userId_user_id_fk": {
+ "name": "ruleEngineRules_userId_user_id_fk",
+ "tableFrom": "ruleEngineRules",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineRules_userId_tagId_fk": {
+ "name": "ruleEngineRules_userId_tagId_fk",
+ "tableFrom": "ruleEngineRules",
+ "tableTo": "bookmarkTags",
+ "columnsFrom": [
+ "userId",
+ "tagId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ruleEngineRules_userId_listId_fk": {
+ "name": "ruleEngineRules_userId_listId_fk",
+ "tableFrom": "ruleEngineRules",
+ "tableTo": "bookmarkLists",
+ "columnsFrom": [
+ "userId",
+ "listId"
+ ],
+ "columnsTo": [
+ "userId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tier": {
+ "name": "tier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'free'"
+ },
+ "priceId": {
+ "name": "priceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancelAtPeriodEnd": {
+ "name": "cancelAtPeriodEnd",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "startDate": {
+ "name": "startDate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "endDate": {
+ "name": "endDate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subscriptions_userId_unique": {
+ "name": "subscriptions_userId_unique",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": true
+ },
+ "subscriptions_userId_idx": {
+ "name": "subscriptions_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "subscriptions_stripeCustomerId_idx": {
+ "name": "subscriptions_stripeCustomerId_idx",
+ "columns": [
+ "stripeCustomerId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subscriptions_userId_user_id_fk": {
+ "name": "subscriptions_userId_user_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagsOnBookmarks": {
+ "name": "tagsOnBookmarks",
+ "columns": {
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attachedAt": {
+ "name": "attachedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attachedBy": {
+ "name": "attachedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tagsOnBookmarks_tagId_idx": {
+ "name": "tagsOnBookmarks_tagId_idx",
+ "columns": [
+ "tagId"
+ ],
+ "isUnique": false
+ },
+ "tagsOnBookmarks_bookmarkId_idx": {
+ "name": "tagsOnBookmarks_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "tagsOnBookmarks_tagId_bookmarkId_idx": {
+ "name": "tagsOnBookmarks_tagId_bookmarkId_idx",
+ "columns": [
+ "tagId",
+ "bookmarkId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "tagsOnBookmarks_bookmarkId_bookmarks_id_fk": {
+ "name": "tagsOnBookmarks_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "tagsOnBookmarks",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tagsOnBookmarks_tagId_bookmarkTags_id_fk": {
+ "name": "tagsOnBookmarks_tagId_bookmarkTags_id_fk",
+ "tableFrom": "tagsOnBookmarks",
+ "tableTo": "bookmarkTags",
+ "columnsFrom": [
+ "tagId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "tagsOnBookmarks_bookmarkId_tagId_pk": {
+ "columns": [
+ "bookmarkId",
+ "tagId"
+ ],
+ "name": "tagsOnBookmarks_bookmarkId_tagId_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "userReadingProgress": {
+ "name": "userReadingProgress",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bookmarkId": {
+ "name": "bookmarkId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "readingProgressOffset": {
+ "name": "readingProgressOffset",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "readingProgressAnchor": {
+ "name": "readingProgressAnchor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readingProgressPercent": {
+ "name": "readingProgressPercent",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "userReadingProgress_bookmarkId_idx": {
+ "name": "userReadingProgress_bookmarkId_idx",
+ "columns": [
+ "bookmarkId"
+ ],
+ "isUnique": false
+ },
+ "userReadingProgress_userId_idx": {
+ "name": "userReadingProgress_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "userReadingProgress_bookmarkId_userId_unique": {
+ "name": "userReadingProgress_bookmarkId_userId_unique",
+ "columns": [
+ "bookmarkId",
+ "userId"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "userReadingProgress_bookmarkId_bookmarks_id_fk": {
+ "name": "userReadingProgress_bookmarkId_bookmarks_id_fk",
+ "tableFrom": "userReadingProgress",
+ "tableTo": "bookmarks",
+ "columnsFrom": [
+ "bookmarkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "userReadingProgress_userId_user_id_fk": {
+ "name": "userReadingProgress_userId_user_id_fk",
+ "tableFrom": "userReadingProgress",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "bookmarkQuota": {
+ "name": "bookmarkQuota",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageQuota": {
+ "name": "storageQuota",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "browserCrawlingEnabled": {
+ "name": "browserCrawlingEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bookmarkClickAction": {
+ "name": "bookmarkClickAction",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open_original_link'"
+ },
+ "archiveDisplayBehaviour": {
+ "name": "archiveDisplayBehaviour",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'show'"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'UTC'"
+ },
+ "backupsEnabled": {
+ "name": "backupsEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "backupsFrequency": {
+ "name": "backupsFrequency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'weekly'"
+ },
+ "backupsRetentionDays": {
+ "name": "backupsRetentionDays",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 30
+ },
+ "readerFontSize": {
+ "name": "readerFontSize",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readerLineHeight": {
+ "name": "readerLineHeight",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readerFontFamily": {
+ "name": "readerFontFamily",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "autoTaggingEnabled": {
+ "name": "autoTaggingEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "autoSummarizationEnabled": {
+ "name": "autoSummarizationEnabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tagStyle": {
+ "name": "tagStyle",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'titlecase-spaces'"
+ },
+ "curatedTagIds": {
+ "name": "curatedTagIds",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "inferredTagLang": {
+ "name": "inferredTagLang",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verificationToken": {
+ "name": "verificationToken",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verificationToken_identifier_token_pk": {
+ "columns": [
+ "identifier",
+ "token"
+ ],
+ "name": "verificationToken_identifier_token_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "webhooks": {
+ "name": "webhooks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "webhooks_userId_idx": {
+ "name": "webhooks_userId_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "webhooks_userId_user_id_fk": {
+ "name": "webhooks_userId_user_id_fk",
+ "tableFrom": "webhooks",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 517a6fb3..840c0997 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -582,6 +582,13 @@
"when": 1775816137345,
"tag": "0082_add_feed_last_successful_fetch",
"breakpoints": true
+ },
+ {
+ "idx": 83,
+ "version": "6",
+ "when": 1776948580025,
+ "tag": "0083_add_api_key_scopes",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/schema.ts b/packages/db/schema.ts
index 9000f4b6..41205f85 100644
--- a/packages/db/schema.ts
+++ b/packages/db/schema.ts
@@ -13,6 +13,8 @@ import {
unique,
} from "drizzle-orm/sqlite-core";
+import type { ZApiKeyScope } from "@karakeep/shared/types/apiKeys";
+import { API_KEY_FULL_ACCESS_SCOPE } from "@karakeep/shared/types/apiKeys";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
function createdAtField() {
@@ -172,6 +174,10 @@ export const apiKeys = sqliteTable(
lastUsedAt: integer("lastUsedAt", { mode: "timestamp" }),
keyId: text("keyId").notNull().unique(),
keyHash: text("keyHash").notNull(),
+ scopes: text("scopes", { mode: "json" })
+ .$type<ZApiKeyScope[]>()
+ .notNull()
+ .$defaultFn(() => [API_KEY_FULL_ACCESS_SCOPE]),
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
diff --git a/packages/e2e_tests/tests/api/assets.test.ts b/packages/e2e_tests/tests/api/assets.test.ts
index 62b9a1e2..c5352928 100644
--- a/packages/e2e_tests/tests/api/assets.test.ts
+++ b/packages/e2e_tests/tests/api/assets.test.ts
@@ -49,6 +49,56 @@ describe("Assets API", () => {
expect(resp.status).toBe(200);
});
+ it("should require assets:readwrite to upload an asset", async () => {
+ const scopedApiKey = await createTestUser(["assets:read"]);
+ const formData = new FormData();
+ formData.append("file", createTestPdfFile());
+
+ const response = await fetch(`http://localhost:${port}/api/v1/assets`, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${scopedApiKey}`,
+ },
+ body: formData,
+ });
+
+ expect(response.status).toBe(403);
+ });
+
+ it("should allow assets:readwrite to retrieve an uploaded asset", async () => {
+ const scopedApiKey = await createTestUser(["assets:readwrite"]);
+ const uploadResponse = await uploadTestAsset(
+ scopedApiKey,
+ port,
+ createTestPdfFile(),
+ );
+
+ const response = await fetch(
+ `http://localhost:${port}/api/v1/assets/${uploadResponse.assetId}`,
+ {
+ headers: {
+ authorization: `Bearer ${scopedApiKey}`,
+ },
+ },
+ );
+
+ expect(response.status).toBe(200);
+ });
+
+ it("should require an asset scope before retrieving an asset", async () => {
+ const scopedApiKey = await createTestUser(["bookmarks:read"]);
+ const response = await fetch(
+ `http://localhost:${port}/api/v1/assets/asset-id`,
+ {
+ headers: {
+ authorization: `Bearer ${scopedApiKey}`,
+ },
+ },
+ );
+
+ expect(response.status).toBe(403);
+ });
+
it("should attach an asset to a bookmark", async () => {
// Create a test file
const file = createTestPdfFile();
diff --git a/packages/e2e_tests/tests/api/bookmarks.test.ts b/packages/e2e_tests/tests/api/bookmarks.test.ts
index f8e7998c..3b867774 100644
--- a/packages/e2e_tests/tests/api/bookmarks.test.ts
+++ b/packages/e2e_tests/tests/api/bookmarks.test.ts
@@ -547,7 +547,7 @@ describe("Bookmarks API", () => {
});
describe("singlefile", () => {
- async function uploadSinglefileAsset(ifexists?: string) {
+ async function uploadSinglefileAsset(ifexists?: string, key = apiKey) {
const file = new File(["<html>HELLO WORLD</html>"], "test.html", {
type: "text/html",
});
@@ -566,7 +566,7 @@ describe("Bookmarks API", () => {
const response = await fetch(url.toString(), {
method: "POST",
headers: {
- authorization: `Bearer ${apiKey}`,
+ authorization: `Bearer ${key}`,
},
body: formData,
});
@@ -579,6 +579,12 @@ describe("Bookmarks API", () => {
return [data, response] as const;
}
+ it("should require assets:readwrite to upload singlefile assets", async () => {
+ const scopedApiKey = await createTestUser(["bookmarks:readwrite"]);
+ const [, response] = await uploadSinglefileAsset(undefined, scopedApiKey);
+ expect(response.status).toBe(403);
+ });
+
it("should support precrawling via singlefile with ifexists=skip", async () => {
// First upload: create a bookmark
const [data, response] = await uploadSinglefileAsset();
diff --git a/packages/e2e_tests/utils/api.ts b/packages/e2e_tests/utils/api.ts
index 45aea93c..a8eb9ab1 100644
--- a/packages/e2e_tests/utils/api.ts
+++ b/packages/e2e_tests/utils/api.ts
@@ -1,4 +1,5 @@
import { getTrpcClient } from "./trpc";
+import type { ZApiKeyScope } from "@karakeep/shared/types/apiKeys";
export function getAuthHeader(apiKey: string) {
return {
@@ -34,7 +35,7 @@ export async function uploadTestAsset(
}>;
}
-export async function createTestUser() {
+export async function createTestUser(scopes?: ZApiKeyScope[]) {
const trpc = getTrpcClient();
const random = Math.random().toString(36).substring(7);
@@ -51,13 +52,20 @@ export async function createTestUser() {
email,
password: "test1234",
keyName: "test-key",
+ scopes,
});
- const authedTrpc = getTrpcClient(key);
- await authedTrpc.users.updateSettings.mutate({
- autoTaggingEnabled: false,
- autoSummarizationEnabled: false,
- });
+ if (
+ !scopes ||
+ scopes.includes("fullaccess") ||
+ scopes.includes("users:readwrite")
+ ) {
+ const authedTrpc = getTrpcClient(key);
+ await authedTrpc.users.updateSettings.mutate({
+ autoTaggingEnabled: false,
+ autoSummarizationEnabled: false,
+ });
+ }
return key;
}
diff --git a/packages/shared/types/apiKeys.ts b/packages/shared/types/apiKeys.ts
new file mode 100644
index 00000000..8277b630
--- /dev/null
+++ b/packages/shared/types/apiKeys.ts
@@ -0,0 +1,105 @@
+import { z } from "zod";
+
+export const API_KEY_FULL_ACCESS_SCOPE = "fullaccess";
+
+export const API_KEY_SCOPE_RESOURCES = [
+ "assets",
+ "backups",
+ "bookmarks",
+ "feeds",
+ "highlights",
+ "lists",
+ "prompts",
+ "rules",
+ "tags",
+ "users",
+ "webhooks",
+ "importSessions",
+ "subscriptions",
+] as const;
+
+export const API_KEY_ADMIN_SCOPE_RESOURCES = [
+ "bookmarks",
+ "jobs",
+ "system",
+ "users",
+] as const;
+
+export const API_KEY_SCOPE_ACCESS = ["read", "readwrite"] as const;
+
+export const zApiKeyScopeResourceSchema = z.enum(API_KEY_SCOPE_RESOURCES);
+export type ZApiKeyScopeResource = z.infer<typeof zApiKeyScopeResourceSchema>;
+
+export const zApiKeyAdminScopeResourceSchema = z.enum(
+ API_KEY_ADMIN_SCOPE_RESOURCES,
+);
+export type ZApiKeyAdminScopeResource = z.infer<
+ typeof zApiKeyAdminScopeResourceSchema
+>;
+
+export const zApiKeyScopeAccessSchema = z.enum(API_KEY_SCOPE_ACCESS);
+export type ZApiKeyScopeAccess = z.infer<typeof zApiKeyScopeAccessSchema>;
+
+export const API_KEY_RESOURCE_SCOPES = API_KEY_SCOPE_RESOURCES.flatMap(
+ (resource) =>
+ API_KEY_SCOPE_ACCESS.map((access) => `${resource}:${access}` as const),
+);
+
+export const API_KEY_ADMIN_SCOPES = API_KEY_ADMIN_SCOPE_RESOURCES.flatMap(
+ (resource) =>
+ API_KEY_SCOPE_ACCESS.map(
+ (access) => `admin:${resource}:${access}` as const,
+ ),
+);
+
+export const API_KEY_SCOPES = [
+ API_KEY_FULL_ACCESS_SCOPE,
+ ...API_KEY_RESOURCE_SCOPES,
+ ...API_KEY_ADMIN_SCOPES,
+] as const;
+
+export const API_KEY_SCOPES_WITHOUT_FULL_ACCESS = [
+ ...API_KEY_RESOURCE_SCOPES,
+ ...API_KEY_ADMIN_SCOPES,
+] as const;
+
+export const zApiKeyScopeSchema = z.enum(API_KEY_SCOPES);
+export type ZApiKeyScope = z.infer<typeof zApiKeyScopeSchema>;
+
+export const zApiKeyScopesSchema = z.array(zApiKeyScopeSchema).min(1);
+
+export function getApiKeyScope(
+ resource: ZApiKeyScopeResource,
+ access: ZApiKeyScopeAccess,
+): ZApiKeyScope {
+ return `${resource}:${access}`;
+}
+
+export function getAdminApiKeyScope(
+ resource: ZApiKeyAdminScopeResource,
+ access: ZApiKeyScopeAccess,
+): ZApiKeyScope {
+ return `admin:${resource}:${access}`;
+}
+
+function getReadWriteScopeForReadScope(scope: ZApiKeyScope) {
+ return scope.endsWith(":read")
+ ? (scope.replace(/:read$/, ":readwrite") as ZApiKeyScope)
+ : null;
+}
+
+export function apiKeyScopesGrantScope(
+ grantedScopes: ZApiKeyScope[],
+ requiredScope: ZApiKeyScope,
+) {
+ if (grantedScopes.includes(API_KEY_FULL_ACCESS_SCOPE)) {
+ return true;
+ }
+
+ if (grantedScopes.includes(requiredScope)) {
+ return true;
+ }
+
+ const readWriteScope = getReadWriteScopeForReadScope(requiredScope);
+ return readWriteScope ? grantedScopes.includes(readWriteScope) : false;
+}
diff --git a/packages/trpc/auth.ts b/packages/trpc/auth.ts
index 764a0904..2ba5017b 100644
--- a/packages/trpc/auth.ts
+++ b/packages/trpc/auth.ts
@@ -3,6 +3,8 @@ import * as bcrypt from "bcryptjs";
import { and, eq } from "drizzle-orm";
import { apiKeys } from "@karakeep/db/schema";
+import type { ZApiKeyScope } from "@karakeep/shared/types/apiKeys";
+import { API_KEY_FULL_ACCESS_SCOPE } from "@karakeep/shared/types/apiKeys";
import serverConfig from "@karakeep/shared/config";
import type { Context } from "./index";
@@ -51,6 +53,7 @@ export async function generateApiKey(
name: string,
userId: string,
database: Context["db"],
+ scopes: ZApiKeyScope[],
) {
const { keyId, secret, secretHash } = generateApiKeySecret();
@@ -64,6 +67,7 @@ export async function generateApiKey(
userId: userId,
keyId,
keyHash: secretHash,
+ scopes,
})
.returning()
)[0];
@@ -72,10 +76,17 @@ export async function generateApiKey(
id: key.id,
name: key.name,
createdAt: key.createdAt,
+ scopes: normalizeApiKeyScopes(key.scopes),
key: plain,
};
}
+function normalizeApiKeyScopes(
+ scopes: ZApiKeyScope[] | null | undefined,
+): ZApiKeyScope[] {
+ return scopes?.length ? scopes : [API_KEY_FULL_ACCESS_SCOPE];
+}
+
function parseApiKey(plain: string) {
const parts = plain.split("_");
if (parts.length != 3) {
@@ -138,7 +149,14 @@ export async function authenticateApiKey(key: string, database: Context["db"]) {
});
}
- return apiKey.user;
+ return {
+ user: apiKey.user,
+ apiKey: {
+ id: apiKey.id,
+ keyId: apiKey.keyId,
+ scopes: normalizeApiKeyScopes(apiKey.scopes),
+ },
+ };
}
export async function hashPassword(password: string, salt: string | null) {
diff --git a/packages/trpc/index.ts b/packages/trpc/index.ts
index 5959f7cf..2a738a33 100644
--- a/packages/trpc/index.ts
+++ b/packages/trpc/index.ts
@@ -3,6 +3,16 @@ import superjson from "superjson";
import { ZodError, z } from "zod";
import type { db } from "@karakeep/db";
+import type {
+ ZApiKeyAdminScopeResource,
+ ZApiKeyScope,
+ ZApiKeyScopeResource,
+} from "@karakeep/shared/types/apiKeys";
+import {
+ apiKeyScopesGrantScope,
+ getAdminApiKeyScope,
+ getApiKeyScope,
+} from "@karakeep/shared/types/apiKeys";
import serverConfig from "@karakeep/shared/config";
import { createRateLimitMiddleware } from "./lib/rateLimit";
@@ -20,8 +30,20 @@ interface User {
role: "admin" | "user" | null;
}
+export type RequestAuth =
+ | {
+ type: "apiKey";
+ keyId: string;
+ scopes: ZApiKeyScope[];
+ }
+ | {
+ type: "session";
+ }
+ | null;
+
export interface Context {
user: User | null;
+ auth?: RequestAuth;
db: typeof db;
req: {
ip: string | null;
@@ -30,6 +52,7 @@ export interface Context {
export interface AuthedContext {
user: User;
+ auth?: RequestAuth;
db: typeof db;
req: {
ip: string | null;
@@ -128,13 +151,80 @@ export const authedProcedure = procedure
});
});
-export const adminProcedure = authedProcedure.use(function isAdmin(opts) {
- const user = opts.ctx.user;
- if (user.role != "admin") {
- throw new TRPCError({ code: "FORBIDDEN" });
- }
- return opts.next(opts);
-});
+function hasRequiredApiKeyScopes(
+ grantedScopes: ZApiKeyScope[],
+ requiredScopes: ZApiKeyScope[],
+) {
+ return requiredScopes.every((scope) =>
+ apiKeyScopesGrantScope(grantedScopes, scope),
+ );
+}
+
+function rejectApiKeyAuth(
+ message = "API keys are not allowed for this endpoint",
+) {
+ return t.middleware((opts) => {
+ if (opts.ctx.auth?.type === "apiKey") {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message,
+ });
+ }
+ return opts.next();
+ });
+}
+
+export function createScopedAuthedProcedure(resource: ZApiKeyScopeResource) {
+ return authedProcedure.use((opts) => {
+ if (opts.ctx.auth?.type !== "apiKey") {
+ return opts.next();
+ }
+
+ const access = opts.type === "query" ? "read" : "readwrite";
+ const scope = getApiKeyScope(resource, access);
+
+ if (hasRequiredApiKeyScopes(opts.ctx.auth.scopes, [scope])) {
+ return opts.next();
+ }
+
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: `API key is missing required scope: ${scope}`,
+ });
+ });
+}
+
+export const sessionProcedure = authedProcedure.use(rejectApiKeyAuth());
+
+export function createAdminScopedProcedure(
+ resource: ZApiKeyAdminScopeResource,
+) {
+ return authedProcedure
+ .use((opts) => {
+ if (opts.ctx.auth?.type !== "apiKey") {
+ return opts.next();
+ }
+
+ const access = opts.type === "query" ? "read" : "readwrite";
+ const scope = getAdminApiKeyScope(resource, access);
+
+ if (hasRequiredApiKeyScopes(opts.ctx.auth.scopes, [scope])) {
+ return opts.next();
+ }
+
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: `API key is missing required scope: ${scope}`,
+ });
+ })
+ .use(function isAdmin(opts) {
+ const user = opts.ctx.user;
+ if (user.role != "admin") {
+ throw new TRPCError({ code: "FORBIDDEN" });
+ }
+ return opts.next(opts);
+ });
+}
// Export the rate limiting middleware for use in routers
export { createRateLimitMiddleware } from "./lib/rateLimit";
diff --git a/packages/trpc/routers/admin.test.ts b/packages/trpc/routers/admin.test.ts
index 2f80d9c0..b923f608 100644
--- a/packages/trpc/routers/admin.test.ts
+++ b/packages/trpc/routers/admin.test.ts
@@ -5,7 +5,11 @@ import { bookmarkLinks, users } from "@karakeep/db/schema";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import type { CustomTestContext } from "../testUtils";
-import { buildTestContext, getApiCaller } from "../testUtils";
+import {
+ buildTestContext,
+ getApiCaller,
+ getApiKeyCallerForPlainKey,
+} from "../testUtils";
beforeEach<CustomTestContext>(async (context) => {
const testContext = await buildTestContext(true);
@@ -13,6 +17,41 @@ beforeEach<CustomTestContext>(async (context) => {
});
describe("Admin Routes", () => {
+ test<CustomTestContext>("admin API key uses granular admin scopes", async ({
+ apiCallers,
+ db,
+ }) => {
+ const [adminUser] = await db
+ .insert(users)
+ .values({
+ name: "Admin User",
+ email: "[email protected]",
+ role: "admin",
+ })
+ .returning();
+ const adminApi = getApiCaller(db, adminUser.id, adminUser.email, "admin");
+
+ const bookmark = await apiCallers[0].bookmarks.createBookmark({
+ url: "https://example.com",
+ type: BookmarkTypes.LINK,
+ });
+
+ const scopedKey = await adminApi.apiKeys.create({
+ name: "Admin Read Bookmarks Key",
+ scopes: ["admin:bookmarks:read"],
+ });
+ const apiKeyCaller = await getApiKeyCallerForPlainKey(db, scopedKey.key);
+
+ const debugInfo = await apiKeyCaller.admin.getBookmarkDebugInfo({
+ bookmarkId: bookmark.id,
+ });
+ expect(debugInfo.id).toEqual(bookmark.id);
+
+ await expect(() =>
+ apiKeyCaller.admin.adminRetagBookmark({ bookmarkId: bookmark.id }),
+ ).rejects.toThrow(/FORBIDDEN|admin:bookmarks:readwrite/i);
+ });
+
describe("getBookmarkDebugInfo", () => {
test<CustomTestContext>("admin can access bookmark debug info for link bookmark", async ({
apiCallers,
diff --git a/packages/trpc/routers/admin.ts b/packages/trpc/routers/admin.ts
index e8881c28..f705ec76 100644
--- a/packages/trpc/routers/admin.ts
+++ b/packages/trpc/routers/admin.ts
@@ -31,12 +31,17 @@ import {
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import { generatePasswordSalt, hashPassword } from "../auth";
-import { adminProcedure, router } from "../index";
+import { createAdminScopedProcedure, router } from "../index";
import { Bookmark } from "../models/bookmarks";
import { User } from "../models/users";
+const adminBookmarksProcedure = createAdminScopedProcedure("bookmarks");
+const adminJobsProcedure = createAdminScopedProcedure("jobs");
+const adminSystemProcedure = createAdminScopedProcedure("system");
+const adminUsersProcedure = createAdminScopedProcedure("users");
+
export const adminAppRouter = router({
- stats: adminProcedure
+ stats: adminSystemProcedure
.output(
z.object({
numUsers: z.number(),
@@ -55,7 +60,7 @@ export const adminAppRouter = router({
numBookmarks,
};
}),
- backgroundJobsStats: adminProcedure
+ backgroundJobsStats: adminJobsProcedure
.output(
z.object({
crawlStats: z.object({
@@ -210,7 +215,7 @@ export const adminAppRouter = router({
},
};
}),
- recrawlLinks: adminProcedure
+ recrawlLinks: adminBookmarksProcedure
.input(
z.object({
crawlStatus: z.enum(["success", "failure", "pending", "all"]),
@@ -240,7 +245,7 @@ export const adminAppRouter = router({
}),
);
}),
- reindexAllBookmarks: adminProcedure.mutation(async ({ ctx }) => {
+ reindexAllBookmarks: adminBookmarksProcedure.mutation(async ({ ctx }) => {
const searchIdx = await getSearchClient();
await searchIdx?.clearIndex();
const bookmarkIds = await ctx.db.query.bookmarks.findMany({
@@ -257,7 +262,7 @@ export const adminAppRouter = router({
),
);
}),
- reprocessAssetsFixMode: adminProcedure.mutation(async ({ ctx }) => {
+ reprocessAssetsFixMode: adminBookmarksProcedure.mutation(async ({ ctx }) => {
const bookmarkIds = await ctx.db.query.bookmarkAssets.findMany({
columns: {
id: true,
@@ -278,7 +283,7 @@ export const adminAppRouter = router({
),
);
}),
- reRunInferenceOnAllBookmarks: adminProcedure
+ reRunInferenceOnAllBookmarks: adminBookmarksProcedure
.input(
z.object({
type: z.enum(["tag", "summarize"]),
@@ -313,12 +318,12 @@ export const adminAppRouter = router({
),
);
}),
- runAdminMaintenanceTask: adminProcedure
+ runAdminMaintenanceTask: adminJobsProcedure
.input(zAdminMaintenanceTaskSchema)
.mutation(async ({ input }) => {
await AdminMaintenanceQueue.enqueue(input);
}),
- userStats: adminProcedure
+ userStats: adminUsersProcedure
.output(
z.record(
z.string(),
@@ -360,7 +365,7 @@ export const adminAppRouter = router({
return results;
}),
- createUser: adminProcedure
+ createUser: adminUsersProcedure
.input(zAdminCreateUserSchema)
.output(
z.object({
@@ -373,7 +378,7 @@ export const adminAppRouter = router({
.mutation(async ({ input, ctx }) => {
return await User.create(ctx, input, input.role);
}),
- updateUser: adminProcedure
+ updateUser: adminUsersProcedure
.input(updateUserSchema)
.mutation(async ({ input, ctx }) => {
if (ctx.user.id == input.userId) {
@@ -420,7 +425,7 @@ export const adminAppRouter = router({
});
}
}),
- resetPassword: adminProcedure
+ resetPassword: adminUsersProcedure
.input(resetPasswordSchema)
.mutation(async ({ input, ctx }) => {
if (ctx.user.id == input.userId) {
@@ -443,7 +448,7 @@ export const adminAppRouter = router({
});
}
}),
- getAdminNoticies: adminProcedure
+ getAdminNoticies: adminSystemProcedure
.output(
z.object({
// Unused for now
@@ -454,7 +459,7 @@ export const adminAppRouter = router({
// Unused for now
};
}),
- checkConnections: adminProcedure
+ checkConnections: adminSystemProcedure
.output(
z.object({
searchEngine: z.object({
@@ -569,7 +574,7 @@ export const adminAppRouter = router({
queue: queueStatus,
};
}),
- getBookmarkDebugInfo: adminProcedure
+ getBookmarkDebugInfo: adminBookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.output(
z.object({
@@ -648,7 +653,7 @@ export const adminAppRouter = router({
return await Bookmark.buildDebugInfo(ctx, input.bookmarkId);
}),
- adminRecrawlBookmark: adminProcedure
+ adminRecrawlBookmark: adminBookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.mutation(async ({ input, ctx }) => {
// Verify bookmark exists and is a link
@@ -677,7 +682,7 @@ export const adminAppRouter = router({
idempotencyKey: buildCrawlIdempotencyKey(payload),
});
}),
- adminReindexBookmark: adminProcedure
+ adminReindexBookmark: adminBookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.mutation(async ({ input, ctx }) => {
// Verify bookmark exists
@@ -697,7 +702,7 @@ export const adminAppRouter = router({
groupId: "admin",
});
}),
- adminRetagBookmark: adminProcedure
+ adminRetagBookmark: adminBookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.mutation(async ({ input, ctx }) => {
// Verify bookmark exists
@@ -723,7 +728,7 @@ export const adminAppRouter = router({
},
);
}),
- adminResummarizeBookmark: adminProcedure
+ adminResummarizeBookmark: adminBookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.mutation(async ({ input, ctx }) => {
// Verify bookmark exists and is a link
diff --git a/packages/trpc/routers/apiKeys.test.ts b/packages/trpc/routers/apiKeys.test.ts
index 24866444..f0a5a745 100644
--- a/packages/trpc/routers/apiKeys.test.ts
+++ b/packages/trpc/routers/apiKeys.test.ts
@@ -2,9 +2,14 @@ import { eq } from "drizzle-orm";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { apiKeys } from "@karakeep/db/schema";
+import { API_KEY_FULL_ACCESS_SCOPE } from "@karakeep/shared/types/apiKeys";
import type { CustomTestContext } from "../testUtils";
-import { defaultBeforeEach, getApiCaller } from "../testUtils";
+import {
+ defaultBeforeEach,
+ getApiCaller,
+ getApiKeyCallerForPlainKey,
+} from "../testUtils";
vi.mock("@karakeep/shared/config", async (original) => {
const mod = (await original()) as typeof import("@karakeep/shared/config");
@@ -42,6 +47,27 @@ describe("API Keys Routes", () => {
expect(result.id).toBeDefined();
expect(result.key).toMatch(/^ak2_[a-f0-9]{20}_[a-f0-9]{32}$/);
expect(result.createdAt).toBeInstanceOf(Date);
+ expect(result.scopes).toEqual([API_KEY_FULL_ACCESS_SCOPE]);
+ });
+
+ test<CustomTestContext>("creates API key with explicit scopes", async ({
+ unauthedAPICaller,
+ db,
+ }) => {
+ const user = await unauthedAPICaller.users.create({
+ name: "Test User",
+ email: "[email protected]",
+ password: "password123",
+ confirmPassword: "password123",
+ });
+
+ const api = getApiCaller(db, user.id, user.email).apiKeys;
+ const result = await api.create({
+ name: "Scoped Key",
+ scopes: ["bookmarks:read", "users:read"],
+ });
+
+ expect(result.scopes).toEqual(["bookmarks:read", "users:read"]);
});
test<CustomTestContext>("requires authentication", async ({
@@ -78,6 +104,7 @@ describe("API Keys Routes", () => {
name: expect.any(String),
createdAt: expect.any(Date),
keyId: expect.any(String),
+ scopes: [API_KEY_FULL_ACCESS_SCOPE],
});
expect(result.keys[0]).not.toHaveProperty("key");
});
@@ -377,6 +404,7 @@ describe("API Keys Routes", () => {
expect(result.name).toBe("Extension Key");
expect(result.key).toMatch(/^ak2_[a-f0-9]{20}_[a-f0-9]{32}$/);
expect(result.createdAt).toBeInstanceOf(Date);
+ expect(result.scopes).toEqual([API_KEY_FULL_ACCESS_SCOPE]);
const dbKeys = await db
.select()
@@ -387,6 +415,35 @@ describe("API Keys Routes", () => {
expect(dbKeys[0].name).toBe("Extension Key");
});
+ test<CustomTestContext>("exchanges credentials for API key with explicit scopes", async ({
+ db,
+ unauthedAPICaller,
+ }) => {
+ const user = await unauthedAPICaller.users.create({
+ name: "Scoped Exchange User",
+ email: "[email protected]",
+ password: "password123",
+ confirmPassword: "password123",
+ });
+
+ const result = await unauthedAPICaller.apiKeys.exchange({
+ keyName: "Scoped Extension Key",
+ email: "[email protected]",
+ password: "password123",
+ scopes: ["bookmarks:read", "users:read"],
+ });
+
+ expect(result.scopes).toEqual(["bookmarks:read", "users:read"]);
+
+ const dbKeys = await db
+ .select()
+ .from(apiKeys)
+ .where(eq(apiKeys.userId, user.id));
+
+ expect(dbKeys).toHaveLength(1);
+ expect(dbKeys[0].scopes).toEqual(["bookmarks:read", "users:read"]);
+ });
+
test<CustomTestContext>("rejects wrong password", async ({
unauthedAPICaller,
}) => {
@@ -559,6 +616,34 @@ describe("API Keys Routes", () => {
});
});
+ describe("scope enforcement", () => {
+ test<CustomTestContext>("fullaccess API key auth cannot manage API keys", async ({
+ unauthedAPICaller,
+ db,
+ }) => {
+ const user = await unauthedAPICaller.users.create({
+ name: "Meta User",
+ email: "[email protected]",
+ password: "password123",
+ confirmPassword: "password123",
+ });
+
+ const sessionCaller = getApiCaller(db, user.id, user.email);
+ const fullAccessKey = await sessionCaller.apiKeys.create({
+ name: "Full Access Key",
+ });
+
+ const apiKeyCaller = await getApiKeyCallerForPlainKey(
+ db,
+ fullAccessKey.key,
+ );
+
+ await expect(() => apiKeyCaller.apiKeys.list()).rejects.toThrow(
+ /FORBIDDEN|API keys are not allowed for this endpoint/i,
+ );
+ });
+ });
+
describe("backward compatibility", () => {
test<CustomTestContext>("validates version 1 keys continues to work", async ({
unauthedAPICaller,
diff --git a/packages/trpc/routers/apiKeys.ts b/packages/trpc/routers/apiKeys.ts
index 90de824a..e62bd7fe 100644
--- a/packages/trpc/routers/apiKeys.ts
+++ b/packages/trpc/routers/apiKeys.ts
@@ -4,6 +4,10 @@ import { z } from "zod";
import { apiKeys } from "@karakeep/db/schema";
import serverConfig from "@karakeep/shared/config";
+import {
+ API_KEY_FULL_ACCESS_SCOPE,
+ zApiKeyScopesSchema,
+} from "@karakeep/shared/types/apiKeys";
import {
authenticateApiKey,
@@ -12,10 +16,10 @@ import {
validatePassword,
} from "../auth";
import {
- authedProcedure,
createRateLimitMiddleware,
publicProcedure,
router,
+ sessionProcedure,
} from "../index";
const zApiKeySchema = z.object({
@@ -23,20 +27,25 @@ const zApiKeySchema = z.object({
name: z.string(),
key: z.string(),
createdAt: z.date(),
+ scopes: zApiKeyScopesSchema,
});
export const apiKeysAppRouter = router({
- create: authedProcedure
+ create: sessionProcedure
.input(
z.object({
name: z.string(),
+ scopes: zApiKeyScopesSchema.optional(),
}),
)
.output(zApiKeySchema)
.mutation(async ({ input, ctx }) => {
- return await generateApiKey(input.name, ctx.user.id, ctx.db);
+ // Omitted scopes preserve the existing API behavior: a new key gets
+ // explicit full access unless the caller asks for granular scopes.
+ const scopes = input.scopes ?? [API_KEY_FULL_ACCESS_SCOPE];
+ return await generateApiKey(input.name, ctx.user.id, ctx.db, scopes);
}),
- regenerate: authedProcedure
+ regenerate: sessionProcedure
.input(
z.object({
id: z.string(),
@@ -60,10 +69,11 @@ export const apiKeysAppRouter = router({
id: existingKey.id,
name: existingKey.name,
createdAt: existingKey.createdAt,
+ scopes: existingKey.scopes,
key: await regenerateApiKey(existingKey.id, ctx.user.id, ctx.db),
};
}),
- revoke: authedProcedure
+ revoke: sessionProcedure
.input(
z.object({
id: z.string(),
@@ -74,7 +84,7 @@ export const apiKeysAppRouter = router({
.delete(apiKeys)
.where(and(eq(apiKeys.id, input.id), eq(apiKeys.userId, ctx.user.id)));
}),
- list: authedProcedure
+ list: sessionProcedure
.output(
z.object({
keys: z.array(
@@ -84,6 +94,7 @@ export const apiKeysAppRouter = router({
createdAt: z.date(),
keyId: z.string(),
lastUsedAt: z.date().nullish(),
+ scopes: zApiKeyScopesSchema,
}),
),
}),
@@ -97,6 +108,7 @@ export const apiKeysAppRouter = router({
createdAt: true,
lastUsedAt: true,
keyId: true,
+ scopes: true,
},
orderBy: desc(apiKeys.createdAt),
});
@@ -117,6 +129,7 @@ export const apiKeysAppRouter = router({
keyName: z.string(),
email: z.string(),
password: z.string(),
+ scopes: zApiKeyScopesSchema.optional(),
}),
)
.output(zApiKeySchema)
@@ -144,7 +157,10 @@ export const apiKeysAppRouter = router({
});
}
- return await generateApiKey(input.keyName, user.id, ctx.db);
+ // Omitted scopes preserve the existing API behavior: a new key gets
+ // explicit full access unless the caller asks for granular scopes.
+ const scopes = input.scopes ?? [API_KEY_FULL_ACCESS_SCOPE];
+ return await generateApiKey(input.keyName, user.id, ctx.db, scopes);
}),
validate: publicProcedure
.use(
diff --git a/packages/trpc/routers/assets.ts b/packages/trpc/routers/assets.ts
index c75f1e2e..2af66e1b 100644
--- a/packages/trpc/routers/assets.ts
+++ b/packages/trpc/routers/assets.ts
@@ -5,12 +5,14 @@ import {
zAssetTypesSchema,
} from "@karakeep/shared/types/bookmarks";
-import { authedProcedure, router } from "../index";
+import { createScopedAuthedProcedure, router } from "../index";
import { Asset } from "../models/assets";
import { ensureBookmarkOwnership } from "./bookmarks";
+const assetsProcedure = createScopedAuthedProcedure("assets");
+
export const assetsAppRouter = router({
- list: authedProcedure
+ list: assetsProcedure
.input(
z.object({
limit: z.number().min(1).max(100).default(20),
@@ -39,7 +41,7 @@ export const assetsAppRouter = router({
cursor: input.cursor ?? null,
});
}),
- attachAsset: authedProcedure
+ attachAsset: assetsProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -54,7 +56,7 @@ export const assetsAppRouter = router({
.mutation(async ({ input, ctx }) => {
return await Asset.attachAsset(ctx, input);
}),
- replaceAsset: authedProcedure
+ replaceAsset: assetsProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -67,7 +69,7 @@ export const assetsAppRouter = router({
.mutation(async ({ input, ctx }) => {
await Asset.replaceAsset(ctx, input);
}),
- detachAsset: authedProcedure
+ detachAsset: assetsProcedure
.input(
z.object({
bookmarkId: z.string(),
diff --git a/packages/trpc/routers/backups.ts b/packages/trpc/routers/backups.ts
index 7a7a9896..e3c7b602 100644
--- a/packages/trpc/routers/backups.ts
+++ b/packages/trpc/routers/backups.ts
@@ -2,18 +2,24 @@ import { z } from "zod";
import { zBackupSchema } from "@karakeep/shared/types/backups";
-import { authedProcedure, createRateLimitMiddleware, router } from "../index";
+import {
+ createRateLimitMiddleware,
+ createScopedAuthedProcedure,
+ router,
+} from "../index";
import { Backup } from "../models/backups";
+const backupsProcedure = createScopedAuthedProcedure("backups");
+
export const backupsAppRouter = router({
- list: authedProcedure
+ list: backupsProcedure
.output(z.object({ backups: z.array(zBackupSchema) }))
.query(async ({ ctx }) => {
const backups = await Backup.getAll(ctx);
return { backups: backups.map((b) => b.asPublic()) };
}),
- get: authedProcedure
+ get: backupsProcedure
.input(
z.object({
backupId: z.string(),
@@ -25,7 +31,7 @@ export const backupsAppRouter = router({
return backup.asPublic();
}),
- delete: authedProcedure
+ delete: backupsProcedure
.input(
z.object({
backupId: z.string(),
@@ -36,7 +42,7 @@ export const backupsAppRouter = router({
await backup.delete();
}),
- triggerBackup: authedProcedure
+ triggerBackup: backupsProcedure
.use(
createRateLimitMiddleware({
name: "backups.triggerBackup",
diff --git a/packages/trpc/routers/bookmarks.test.ts b/packages/trpc/routers/bookmarks.test.ts
index 47029f41..95c5116d 100644
--- a/packages/trpc/routers/bookmarks.test.ts
+++ b/packages/trpc/routers/bookmarks.test.ts
@@ -12,7 +12,7 @@ import * as sharedServer from "@karakeep/shared-server";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import type { APICallerType, CustomTestContext } from "../testUtils";
-import { defaultBeforeEach } from "../testUtils";
+import { defaultBeforeEach, getApiKeyCallerForPlainKey } from "../testUtils";
vi.mock("@karakeep/shared-server", async (original) => {
const mod = (await original()) as typeof import("@karakeep/shared-server");
@@ -71,6 +71,71 @@ describe("Bookmark Routes", () => {
expect(res.content.type).toEqual(BookmarkTypes.LINK);
});
+ test<CustomTestContext>("api key with read scope can read bookmarks but not write", async ({
+ apiCallers,
+ db,
+ }) => {
+ await apiCallers[0].bookmarks.createBookmark({
+ type: BookmarkTypes.TEXT,
+ text: "seed bookmark",
+ });
+
+ const scopedKey = await apiCallers[0].apiKeys.create({
+ name: "Read Bookmark Key",
+ scopes: ["bookmarks:read", "users:read"],
+ });
+ const apiKeyCaller = await getApiKeyCallerForPlainKey(db, scopedKey.key);
+
+ const bookmarks = await apiKeyCaller.bookmarks.getBookmarks({});
+ expect(bookmarks.bookmarks).toHaveLength(1);
+
+ await expect(() =>
+ apiKeyCaller.bookmarks.createBookmark({
+ type: BookmarkTypes.TEXT,
+ text: "should fail",
+ }),
+ ).rejects.toThrow(/FORBIDDEN|missing required scope/i);
+ });
+
+ test<CustomTestContext>("api key with readwrite scope can read bookmarks", async ({
+ apiCallers,
+ db,
+ }) => {
+ await apiCallers[0].bookmarks.createBookmark({
+ type: BookmarkTypes.TEXT,
+ text: "seed bookmark",
+ });
+
+ const scopedKey = await apiCallers[0].apiKeys.create({
+ name: "Readwrite Bookmark Key",
+ scopes: ["bookmarks:readwrite"],
+ });
+ const apiKeyCaller = await getApiKeyCallerForPlainKey(db, scopedKey.key);
+
+ const bookmarks = await apiKeyCaller.bookmarks.getBookmarks({});
+ expect(bookmarks.bookmarks).toHaveLength(1);
+ });
+
+ test<CustomTestContext>("fullaccess API key can write bookmarks", async ({
+ apiCallers,
+ db,
+ }) => {
+ const fullAccessKey = await apiCallers[0].apiKeys.create({
+ name: "Full Access Bookmark Key",
+ });
+ const apiKeyCaller = await getApiKeyCallerForPlainKey(
+ db,
+ fullAccessKey.key,
+ );
+
+ const created = await apiKeyCaller.bookmarks.createBookmark({
+ type: BookmarkTypes.TEXT,
+ text: "allowed",
+ });
+
+ expect(created.content.type).toBe(BookmarkTypes.TEXT);
+ });
+
test<CustomTestContext>("delete bookmark", async ({ apiCallers }) => {
const api = apiCallers[0].bookmarks;
diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.ts
index 94c9749f..cde5fa6f 100644
--- a/packages/trpc/routers/bookmarks.ts
+++ b/packages/trpc/routers/bookmarks.ts
@@ -52,13 +52,19 @@ import { ANCHOR_TEXT_MAX_LENGTH } from "@karakeep/shared/utils/reading-progress-
import { normalizeTagName } from "@karakeep/shared/utils/tag";
import type { AuthedContext } from "../index";
-import { authedProcedure, createRateLimitMiddleware, router } from "../index";
+import {
+ createRateLimitMiddleware,
+ createScopedAuthedProcedure,
+ router,
+} from "../index";
import { RuleEngine } from "../lib/ruleEngine";
import { getBookmarkIdsFromMatcher } from "../lib/search";
import { Asset } from "../models/assets";
import { BareBookmark, Bookmark } from "../models/bookmarks";
import { WebhooksService } from "../models/webhooks.service";
+const bookmarksProcedure = createScopedAuthedProcedure("bookmarks");
+
export const ensureBookmarkOwnership = experimental_trpcMiddleware<{
ctx: AuthedContext;
input: { bookmarkId: string };
@@ -143,7 +149,7 @@ async function shouldUseLowPriorityQueues(
}
export const bookmarksAppRouter = router({
- createBookmark: authedProcedure
+ createBookmark: bookmarksProcedure
.use(
createRateLimitMiddleware({
name: "bookmarks.createBookmark",
@@ -389,7 +395,7 @@ export const bookmarksAppRouter = router({
return bookmark;
}),
- updateBookmark: authedProcedure
+ updateBookmark: bookmarksProcedure
.input(zUpdateBookmarksRequestSchema)
.output(zBookmarkSchema)
.use(ensureBookmarkOwnership)
@@ -561,7 +567,7 @@ export const bookmarksAppRouter = router({
}),
// DEPRECATED: use updateBookmark instead
- updateBookmarkText: authedProcedure
+ updateBookmarkText: bookmarksProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -609,14 +615,14 @@ export const bookmarksAppRouter = router({
]);
}),
- deleteBookmark: authedProcedure
+ deleteBookmark: bookmarksProcedure
.input(z.object({ bookmarkId: z.string() }))
.use(ensureBookmarkOwnership)
.mutation(async ({ input, ctx }) => {
const bookmark = await Bookmark.fromId(ctx, input.bookmarkId, false);
await bookmark.delete();
}),
- recrawlBookmark: authedProcedure
+ recrawlBookmark: bookmarksProcedure
.use(
createRateLimitMiddleware({
name: "bookmarks.recrawlBookmark",
@@ -644,7 +650,7 @@ export const bookmarksAppRouter = router({
idempotencyKey: buildCrawlIdempotencyKey(payload),
});
}),
- updateReadingProgress: authedProcedure
+ updateReadingProgress: bookmarksProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -685,7 +691,7 @@ export const bookmarksAppRouter = router({
},
});
}),
- getReadingProgress: authedProcedure
+ getReadingProgress: bookmarksProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -705,7 +711,7 @@ export const bookmarksAppRouter = router({
readingProgressPercent: progress?.readingProgressPercent ?? null,
};
}),
- getBookmark: authedProcedure
+ getBookmark: bookmarksProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -719,7 +725,7 @@ export const bookmarksAppRouter = router({
await Bookmark.fromId(ctx, input.bookmarkId, input.includeContent)
).asZBookmark();
}),
- searchBookmarks: authedProcedure
+ searchBookmarks: bookmarksProcedure
.input(zSearchBookmarksRequestSchema)
.output(
z.object({
@@ -809,7 +815,7 @@ export const bookmarksAppRouter = router({
},
};
}),
- checkUrl: authedProcedure
+ checkUrl: bookmarksProcedure
.input(
z.object({
url: z.string(),
@@ -857,7 +863,7 @@ export const bookmarksAppRouter = router({
return { bookmarkId: exactMatch?.id ?? null };
}),
- getBookmarks: authedProcedure
+ getBookmarks: bookmarksProcedure
.input(zGetBookmarksRequestSchema)
.output(zGetBookmarksResponseSchema)
.query(async ({ input, ctx }) => {
@@ -868,7 +874,7 @@ export const bookmarksAppRouter = router({
};
}),
- updateTags: authedProcedure
+ updateTags: bookmarksProcedure
.input(
z.object({
bookmarkId: z.string(),
@@ -1068,7 +1074,7 @@ export const bookmarksAppRouter = router({
}
return res;
}),
- getBrokenLinks: authedProcedure
+ getBrokenLinks: bookmarksProcedure
.output(
z.object({
bookmarks: z.array(
@@ -1116,7 +1122,7 @@ export const bookmarksAppRouter = router({
})),
};
}),
- summarizeBookmark: authedProcedure
+ summarizeBookmark: bookmarksProcedure
.use(
createRateLimitMiddleware({
name: "bookmarks.summarizeBookmark",
diff --git a/packages/trpc/routers/feeds.ts b/packages/trpc/routers/feeds.ts
index 31e9e15b..a92c00ea 100644
--- a/packages/trpc/routers/feeds.ts
+++ b/packages/trpc/routers/feeds.ts
@@ -9,11 +9,11 @@ import {
} from "@karakeep/shared/types/feeds";
import type { AuthedContext } from "../index";
-import { authedProcedure, router } from "../index";
+import { createScopedAuthedProcedure, router } from "../index";
import { actorFromContext } from "../lib/actor";
import { FeedsService } from "../models/feeds.service";
-const feedsProcedure = authedProcedure.use((opts) => {
+const feedsProcedure = createScopedAuthedProcedure("feeds").use((opts) => {
return opts.next({
ctx: {
...opts.ctx,
diff --git a/packages/trpc/routers/highlights.ts b/packages/trpc/routers/highlights.ts
index 606e0daf..012b1ed0 100644
--- a/packages/trpc/routers/highlights.ts
+++ b/packages/trpc/routers/highlights.ts
@@ -11,20 +11,22 @@ import {
import { zCursorV2 } from "@karakeep/shared/types/pagination";
import type { AuthedContext } from "../index";
-import { authedProcedure, router } from "../index";
+import { createScopedAuthedProcedure, router } from "../index";
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),
- },
- });
-});
+const highlightsProcedure = createScopedAuthedProcedure("highlights").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>;
diff --git a/packages/trpc/routers/importSessions.ts b/packages/trpc/routers/importSessions.ts
index 2d71e5b6..9be38449 100644
--- a/packages/trpc/routers/importSessions.ts
+++ b/packages/trpc/routers/importSessions.ts
@@ -11,11 +11,13 @@ import {
} from "@karakeep/shared/types/importSessions";
import type { AuthedContext } from "../index";
-import { authedProcedure, router } from "../index";
+import { createScopedAuthedProcedure, router } from "../index";
import { actorFromContext } from "../lib/actor";
import { ImportSessionsService } from "../models/importSessions.service";
-const importSessionsProcedure = authedProcedure.use((opts) => {
+const importSessionsProcedure = createScopedAuthedProcedure(
+ "importSessions",
+).use((opts) => {
return opts.next({
ctx: {
...opts.ctx,
diff --git a/packages/trpc/routers/invites.ts b/packages/trpc/routers/invites.ts
index 94b8fc35..409f9d92 100644
--- a/packages/trpc/routers/invites.ts
+++ b/packages/trpc/routers/invites.ts
@@ -9,15 +9,17 @@ import { zUserNameSchema } from "@karakeep/shared/types/users";
import { generatePasswordSalt, hashPassword } from "../auth";
import { sendInviteEmail } from "../email";
import {
- adminProcedure,
+ createAdminScopedProcedure,
createRateLimitMiddleware,
publicProcedure,
router,
} from "../index";
import { User } from "../models/users";
+const adminUsersProcedure = createAdminScopedProcedure("users");
+
export const invitesAppRouter = router({
- create: adminProcedure
+ create: adminUsersProcedure
.input(
z.object({
email: z.string().email(),
@@ -75,7 +77,7 @@ export const invitesAppRouter = router({
};
}),
- list: adminProcedure
+ list: adminUsersProcedure
.output(
z.object({
invites: z.array(
@@ -206,7 +208,7 @@ export const invitesAppRouter = router({
};
}),
- revoke: adminProcedure
+ revoke: adminUsersProcedure
.input(
z.object({
inviteId: z.string(),
@@ -230,7 +232,7 @@ export const invitesAppRouter = router({
return { success: true };
}),
- resend: adminProcedure
+ resend: adminUsersProcedure
.input(
z.object({
inviteId: z.string(),
diff --git a/packages/trpc/routers/lists.ts b/packages/trpc/routers/lists.ts
index bca3dc53..201c12b4 100644
--- a/packages/trpc/routers/lists.ts
+++ b/packages/trpc/routers/lists.ts
@@ -9,11 +9,17 @@ import {
} from "@karakeep/shared/types/lists";
import type { AuthedContext } from "../index";
-import { authedProcedure, createRateLimitMiddleware, router } from "../index";
+import {
+ createRateLimitMiddleware,
+ createScopedAuthedProcedure,
+ router,
+} from "../index";
import { ListInvitation } from "../models/listInvitations";
import { List } from "../models/lists";
import { ensureBookmarkOwnership } from "./bookmarks";
+const listsProcedure = createScopedAuthedProcedure("lists");
+
export const ensureListAtLeastViewer = experimental_trpcMiddleware<{
ctx: AuthedContext;
input: { listId: string };
@@ -65,13 +71,13 @@ export const ensureInvitationAccess = experimental_trpcMiddleware<{
});
export const listsAppRouter = router({
- create: authedProcedure
+ create: listsProcedure
.input(zNewBookmarkListSchema)
.output(zBookmarkListSchema)
.mutation(async ({ input, ctx }) => {
return await List.create(ctx, input).then((l) => l.asZBookmarkList());
}),
- edit: authedProcedure
+ edit: listsProcedure
.input(zEditBookmarkListSchemaWithValidation)
.output(zBookmarkListSchema)
.use(ensureListAtLeastViewer)
@@ -80,7 +86,7 @@ export const listsAppRouter = router({
await ctx.list.update(input);
return ctx.list.asZBookmarkList();
}),
- merge: authedProcedure
+ merge: listsProcedure
.input(zMergeListSchema)
.mutation(async ({ input, ctx }) => {
const [sourceList, targetList] = await Promise.all([
@@ -94,7 +100,7 @@ export const listsAppRouter = router({
input.deleteSourceAfterMerge,
);
}),
- delete: authedProcedure
+ delete: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -110,7 +116,7 @@ export const listsAppRouter = router({
}
await ctx.list.delete();
}),
- addToList: authedProcedure
+ addToList: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -123,7 +129,7 @@ export const listsAppRouter = router({
.mutation(async ({ input, ctx }) => {
await ctx.list.addBookmark(input.bookmarkId);
}),
- removeFromList: authedProcedure
+ removeFromList: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -135,7 +141,7 @@ export const listsAppRouter = router({
.mutation(async ({ input, ctx }) => {
await ctx.list.removeBookmark(input.bookmarkId);
}),
- get: authedProcedure
+ get: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -146,7 +152,7 @@ export const listsAppRouter = router({
.query(async ({ ctx }) => {
return ctx.list.asZBookmarkList();
}),
- list: authedProcedure
+ list: listsProcedure
.output(
z.object({
lists: z.array(zBookmarkListSchema),
@@ -156,7 +162,7 @@ export const listsAppRouter = router({
const results = await List.getAll(ctx);
return { lists: results.map((l) => l.asZBookmarkList()) };
}),
- getListsOfBookmark: authedProcedure
+ getListsOfBookmark: listsProcedure
.input(z.object({ bookmarkId: z.string() }))
.output(
z.object({
@@ -168,7 +174,7 @@ export const listsAppRouter = router({
const lists = await List.forBookmark(ctx, input.bookmarkId);
return { lists: lists.map((l) => l.asZBookmarkList()) };
}),
- stats: authedProcedure
+ stats: listsProcedure
.output(
z.object({
stats: z.map(z.string(), z.number()),
@@ -181,7 +187,7 @@ export const listsAppRouter = router({
}),
// Rss endpoints
- regenRssToken: authedProcedure
+ regenRssToken: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -198,7 +204,7 @@ export const listsAppRouter = router({
const token = await ctx.list.regenRssToken();
return { token: token! };
}),
- clearRssToken: authedProcedure
+ clearRssToken: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -209,7 +215,7 @@ export const listsAppRouter = router({
.mutation(async ({ ctx }) => {
await ctx.list.clearRssToken();
}),
- getRssToken: authedProcedure
+ getRssToken: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -227,7 +233,7 @@ export const listsAppRouter = router({
}),
// Collaboration endpoints
- addCollaborator: authedProcedure
+ addCollaborator: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -257,7 +263,7 @@ export const listsAppRouter = router({
),
};
}),
- removeCollaborator: authedProcedure
+ removeCollaborator: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -269,7 +275,7 @@ export const listsAppRouter = router({
.mutation(async ({ input, ctx }) => {
await ctx.list.removeCollaborator(input.userId);
}),
- updateCollaboratorRole: authedProcedure
+ updateCollaboratorRole: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -282,7 +288,7 @@ export const listsAppRouter = router({
.mutation(async ({ input, ctx }) => {
await ctx.list.updateCollaboratorRole(input.userId, input.role);
}),
- getCollaborators: authedProcedure
+ getCollaborators: listsProcedure
.input(
z.object({
listId: z.string(),
@@ -321,7 +327,7 @@ export const listsAppRouter = router({
return await ctx.list.getCollaborators();
}),
- acceptInvitation: authedProcedure
+ acceptInvitation: listsProcedure
.input(
z.object({
invitationId: z.string(),
@@ -332,7 +338,7 @@ export const listsAppRouter = router({
await ctx.invitation.accept();
}),
- declineInvitation: authedProcedure
+ declineInvitation: listsProcedure
.input(
z.object({
invitationId: z.string(),
@@ -343,7 +349,7 @@ export const listsAppRouter = router({
await ctx.invitation.decline();
}),
- revokeInvitation: authedProcedure
+ revokeInvitation: listsProcedure
.input(
z.object({
invitationId: z.string(),
@@ -354,7 +360,7 @@ export const listsAppRouter = router({
await ctx.invitation.revoke();
}),
- getPendingInvitations: authedProcedure
+ getPendingInvitations: listsProcedure
.output(
z.array(
z.object({
@@ -382,7 +388,7 @@ export const listsAppRouter = router({
return ListInvitation.pendingForUser(ctx);
}),
- leaveList: authedProcedure
+ leaveList: listsProcedure
.input(
z.object({
listId: z.string(),
diff --git a/packages/trpc/routers/prompts.ts b/packages/trpc/routers/prompts.ts
index d3942e69..d64691c1 100644
--- a/packages/trpc/routers/prompts.ts
+++ b/packages/trpc/routers/prompts.ts
@@ -9,7 +9,9 @@ import {
zUpdatePromptSchema,
} from "@karakeep/shared/types/prompts";
-import { authedProcedure, Context, router } from "../index";
+import { Context, createScopedAuthedProcedure, router } from "../index";
+
+const promptsProcedure = createScopedAuthedProcedure("prompts");
export const ensurePromptOwnership = experimental_trpcMiddleware<{
ctx: Context;
@@ -44,7 +46,7 @@ export const ensurePromptOwnership = experimental_trpcMiddleware<{
});
export const promptsAppRouter = router({
- create: authedProcedure
+ create: promptsProcedure
.input(zNewPromptSchema)
.output(zPromptSchema)
.mutation(async ({ input, ctx }) => {
@@ -59,7 +61,7 @@ export const promptsAppRouter = router({
.returning();
return prompt;
}),
- update: authedProcedure
+ update: promptsProcedure
.input(zUpdatePromptSchema)
.output(zPromptSchema)
.use(ensurePromptOwnership)
@@ -83,7 +85,7 @@ export const promptsAppRouter = router({
}
return res[0];
}),
- list: authedProcedure
+ list: promptsProcedure
.output(z.array(zPromptSchema))
.query(async ({ ctx }) => {
const prompts = await ctx.db.query.customPrompts.findMany({
@@ -91,7 +93,7 @@ export const promptsAppRouter = router({
});
return prompts;
}),
- delete: authedProcedure
+ delete: promptsProcedure
.input(
z.object({
promptId: z.string(),
diff --git a/packages/trpc/routers/rules.ts b/packages/trpc/routers/rules.ts
index 5def8003..282b64f7 100644
--- a/packages/trpc/routers/rules.ts
+++ b/packages/trpc/routers/rules.ts
@@ -10,10 +10,12 @@ import {
zUpdateRuleEngineRuleSchema,
} from "@karakeep/shared/types/rules";
-import { AuthedContext, authedProcedure, router } from "../index";
+import { AuthedContext, createScopedAuthedProcedure, router } from "../index";
import { List } from "../models/lists";
import { RuleEngineRuleModel } from "../models/rules";
+const rulesProcedure = createScopedAuthedProcedure("rules");
+
const ensureRuleOwnership = experimental_trpcMiddleware<{
ctx: AuthedContext;
input: { id: string };
@@ -83,7 +85,7 @@ const ensureTagListOwnership = experimental_trpcMiddleware<{
});
export const rulesAppRouter = router({
- create: authedProcedure
+ create: rulesProcedure
.input(zNewRuleEngineRuleSchema)
.output(zRuleEngineRuleSchema)
.use(ensureTagListOwnership)
@@ -91,7 +93,7 @@ export const rulesAppRouter = router({
const newRule = await RuleEngineRuleModel.create(ctx, input);
return newRule.rule;
}),
- update: authedProcedure
+ update: rulesProcedure
.input(zUpdateRuleEngineRuleSchema)
.output(zRuleEngineRuleSchema)
.use(ensureRuleOwnership)
@@ -100,13 +102,13 @@ export const rulesAppRouter = router({
await ctx.rule.update(input);
return ctx.rule.rule;
}),
- delete: authedProcedure
+ delete: rulesProcedure
.input(z.object({ id: z.string() }))
.use(ensureRuleOwnership)
.mutation(async ({ ctx }) => {
await ctx.rule.delete();
}),
- list: authedProcedure
+ list: rulesProcedure
.output(
z.object({
rules: z.array(zRuleEngineRuleSchema),
diff --git a/packages/trpc/routers/subscriptions.ts b/packages/trpc/routers/subscriptions.ts
index c148dcfe..619f7e78 100644
--- a/packages/trpc/routers/subscriptions.ts
+++ b/packages/trpc/routers/subscriptions.ts
@@ -8,7 +8,12 @@ import { z } from "zod";
import { assets, bookmarks, subscriptions, users } from "@karakeep/db/schema";
import serverConfig from "@karakeep/shared/config";
-import { authedProcedure, Context, publicProcedure, router } from "../index";
+import {
+ Context,
+ publicProcedure,
+ router,
+ createScopedAuthedProcedure,
+} from "../index";
const stripe = serverConfig.stripe.secretKey
? new Stripe(serverConfig.stripe.secretKey, {
@@ -185,8 +190,10 @@ async function processEvent(event: Stripe.Event, db: Context["db"]) {
return await syncStripeDataToDatabase(customerId, db);
}
+const subscriptionsProcedure = createScopedAuthedProcedure("subscriptions");
+
export const subscriptionsRouter = router({
- getSubscriptionStatus: authedProcedure.query(async ({ ctx }) => {
+ getSubscriptionStatus: subscriptionsProcedure.query(async ({ ctx }) => {
const subscription = await ctx.db.query.subscriptions.findFirst({
where: eq(subscriptions.userId, ctx.user.id),
});
@@ -213,7 +220,7 @@ export const subscriptionsRouter = router({
};
}),
- getSubscriptionPrice: authedProcedure.query(async () => {
+ getSubscriptionPrice: subscriptionsProcedure.query(async () => {
if (!stripe) {
throw new TRPCError({
code: "PRECONDITION_FAILED",
@@ -253,7 +260,7 @@ export const subscriptionsRouter = router({
return result;
}),
- createCheckoutSession: authedProcedure
+ createCheckoutSession: subscriptionsProcedure
.input(
z
.object({
@@ -350,7 +357,7 @@ export const subscriptionsRouter = router({
};
}),
- syncWithStripe: authedProcedure.mutation(async ({ ctx }) => {
+ syncWithStripe: subscriptionsProcedure.mutation(async ({ ctx }) => {
const subscription = await ctx.db.query.subscriptions.findFirst({
where: eq(subscriptions.userId, ctx.user.id),
});
@@ -364,7 +371,7 @@ export const subscriptionsRouter = router({
return { success: true };
}),
- createPortalSession: authedProcedure.mutation(async ({ ctx }) => {
+ createPortalSession: subscriptionsProcedure.mutation(async ({ ctx }) => {
const { stripe } = requireStripeConfig();
const subscription = await ctx.db.query.subscriptions.findFirst({
@@ -388,7 +395,7 @@ export const subscriptionsRouter = router({
};
}),
- getQuotaUsage: authedProcedure.query(async ({ ctx }) => {
+ getQuotaUsage: subscriptionsProcedure.query(async ({ ctx }) => {
const user = await ctx.db.query.users.findFirst({
where: eq(users.id, ctx.user.id),
columns: {
diff --git a/packages/trpc/routers/tags.ts b/packages/trpc/routers/tags.ts
index 5713c192..1007307f 100644
--- a/packages/trpc/routers/tags.ts
+++ b/packages/trpc/routers/tags.ts
@@ -11,9 +11,11 @@ import {
} from "@karakeep/shared/types/tags";
import type { AuthedContext } from "../index";
-import { authedProcedure, router } from "../index";
+import { createScopedAuthedProcedure, router } from "../index";
import { Tag } from "../models/tags";
+const tagsProcedure = createScopedAuthedProcedure("tags");
+
export const ensureTagOwnership = experimental_trpcMiddleware<{
ctx: AuthedContext;
input: { tagId: string };
@@ -28,7 +30,7 @@ export const ensureTagOwnership = experimental_trpcMiddleware<{
});
export const tagsAppRouter = router({
- create: authedProcedure
+ create: tagsProcedure
.input(zCreateTagRequestSchema)
.output(zTagBasicSchema)
.mutation(async ({ input, ctx }) => {
@@ -36,7 +38,7 @@ export const tagsAppRouter = router({
return tag.asBasicTag();
}),
- get: authedProcedure
+ get: tagsProcedure
.input(
z.object({
tagId: z.string(),
@@ -47,7 +49,7 @@ export const tagsAppRouter = router({
.query(async ({ ctx }) => {
return await ctx.tag.getStats();
}),
- delete: authedProcedure
+ delete: tagsProcedure
.input(
z.object({
tagId: z.string(),
@@ -57,7 +59,7 @@ export const tagsAppRouter = router({
.mutation(async ({ ctx }) => {
await ctx.tag.delete();
}),
- deleteUnused: authedProcedure
+ deleteUnused: tagsProcedure
.output(
z.object({
deletedTags: z.number(),
@@ -67,7 +69,7 @@ export const tagsAppRouter = router({
const deletedCount = await Tag.deleteUnused(ctx);
return { deletedTags: deletedCount };
}),
- update: authedProcedure
+ update: tagsProcedure
.input(zUpdateTagRequestSchema)
.output(zTagBasicSchema)
.use(ensureTagOwnership)
@@ -75,7 +77,7 @@ export const tagsAppRouter = router({
await ctx.tag.update(input);
return ctx.tag.asBasicTag();
}),
- merge: authedProcedure
+ merge: tagsProcedure
.input(
z.object({
intoTagId: z.string(),
@@ -91,7 +93,7 @@ export const tagsAppRouter = router({
.mutation(async ({ input, ctx }) => {
return await Tag.merge(ctx, input);
}),
- list: authedProcedure
+ list: tagsProcedure
.input(
// TODO: Remove the optional and default once the next release is out.
zTagListValidatedRequestSchema
diff --git a/packages/trpc/routers/users.ts b/packages/trpc/routers/users.ts
index 0610305e..1e681135 100644
--- a/packages/trpc/routers/users.ts
+++ b/packages/trpc/routers/users.ts
@@ -14,15 +14,18 @@ import {
import { validateRedirectUrl } from "@karakeep/shared/utils/redirectUrl";
import {
- adminProcedure,
- authedProcedure,
+ createAdminScopedProcedure,
createRateLimitMiddleware,
+ createScopedAuthedProcedure,
publicProcedure,
router,
} from "../index";
import { verifyTurnstileToken } from "../lib/turnstile";
import { User } from "../models/users";
+const usersProcedure = createScopedAuthedProcedure("users");
+const adminUsersProcedure = createAdminScopedProcedure("users");
+
export const usersAppRouter = router({
create: publicProcedure
.use(
@@ -78,7 +81,7 @@ export const usersAppRouter = router({
role: user.role,
};
}),
- list: adminProcedure
+ list: adminUsersProcedure
.output(
z.object({
users: z.array(
@@ -100,7 +103,7 @@ export const usersAppRouter = router({
users: users.map((u) => u.asPublicUser()),
};
}),
- changePassword: authedProcedure
+ changePassword: usersProcedure
.use(
createRateLimitMiddleware({
name: "users.changePassword",
@@ -118,7 +121,7 @@ export const usersAppRouter = router({
const user = await User.fromCtx(ctx);
await user.changePassword(input.currentPassword, input.newPassword);
}),
- delete: adminProcedure
+ delete: adminUsersProcedure
.input(
z.object({
userId: z.string(),
@@ -127,7 +130,7 @@ export const usersAppRouter = router({
.mutation(async ({ input, ctx }) => {
await User.deleteAsAdmin(ctx, input.userId);
}),
- deleteAccount: authedProcedure
+ deleteAccount: usersProcedure
.input(
z.object({
password: z.string().optional(),
@@ -137,19 +140,19 @@ export const usersAppRouter = router({
const user = await User.fromCtx(ctx);
await user.deleteAccount(input.password);
}),
- whoami: authedProcedure
+ whoami: usersProcedure
.output(zWhoAmIResponseSchema)
.query(async ({ ctx }) => {
const user = await User.fromCtx(ctx);
return user.asWhoAmI();
}),
- stats: authedProcedure
+ stats: usersProcedure
.output(zUserStatsResponseSchema)
.query(async ({ ctx }) => {
const user = await User.fromCtx(ctx);
return await user.getStats();
}),
- wrapped: authedProcedure
+ wrapped: usersProcedure
.output(zWrappedStatsResponseSchema)
.query(async ({ ctx }) => {
throw new TRPCError({
@@ -159,7 +162,7 @@ export const usersAppRouter = router({
const user = await User.fromCtx(ctx);
return await user.getWrappedStats(2025);
}),
- hasWrapped: authedProcedure.output(z.boolean()).query(async ({ ctx }) => {
+ hasWrapped: usersProcedure.output(z.boolean()).query(async ({ ctx }) => {
throw new TRPCError({
code: "BAD_REQUEST",
message: "This endpoint is currently disabled",
@@ -167,19 +170,19 @@ export const usersAppRouter = router({
const user = await User.fromCtx(ctx);
return await user.hasWrapped();
}),
- settings: authedProcedure
+ settings: usersProcedure
.output(zUserSettingsSchema)
.query(async ({ ctx }) => {
const user = await User.fromCtx(ctx);
return await user.getSettings();
}),
- updateSettings: authedProcedure
+ updateSettings: usersProcedure
.input(zUpdateUserSettingsSchema)
.mutation(async ({ input, ctx }) => {
const user = await User.fromCtx(ctx);
await user.updateSettings(input);
}),
- updateAvatar: authedProcedure
+ updateAvatar: usersProcedure
.input(
z.object({
assetId: z.string().nullable(),
diff --git a/packages/trpc/routers/webhooks.ts b/packages/trpc/routers/webhooks.ts
index cd7659bf..39563cd9 100644
--- a/packages/trpc/routers/webhooks.ts
+++ b/packages/trpc/routers/webhooks.ts
@@ -9,7 +9,7 @@ import {
} from "@karakeep/shared/types/webhooks";
import type { AuthedContext } from "../index";
-import { authedProcedure, router } from "../index";
+import { createScopedAuthedProcedure, router } from "../index";
import { actorFromContext } from "../lib/actor";
import { WebhooksService } from "../models/webhooks.service";
@@ -21,15 +21,17 @@ function toPublicWebhook(webhook: typeof webhooksTable.$inferSelect) {
};
}
-const webhooksProcedure = authedProcedure.use((opts) => {
- return opts.next({
- ctx: {
- ...opts.ctx,
- actor: actorFromContext(opts.ctx),
- webhooksService: new WebhooksService(opts.ctx.db),
- },
- });
-});
+const webhooksProcedure = createScopedAuthedProcedure("webhooks").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>;
diff --git a/packages/trpc/testUtils.ts b/packages/trpc/testUtils.ts
index d439c64c..174b8822 100644
--- a/packages/trpc/testUtils.ts
+++ b/packages/trpc/testUtils.ts
@@ -3,6 +3,7 @@ import { vi } from "vitest";
import { getInMemoryDB } from "@karakeep/db/drizzle";
import { users } from "@karakeep/db/schema";
+import type { Context } from "./index";
import { createCallerFactory } from "./index";
import { appRouter } from "./routers/_app";
@@ -37,6 +38,7 @@ export function getApiCaller(
userId?: string,
email?: string,
role: "user" | "admin" = "user",
+ auth: Context["auth"] = userId ? { type: "session" } : null,
) {
const createCaller = createCallerFactory(appRouter);
return createCaller({
@@ -47,6 +49,7 @@ export function getApiCaller(
role,
}
: null,
+ auth,
db,
req: {
ip: null,
@@ -54,6 +57,22 @@ export function getApiCaller(
});
}
+export async function getApiKeyCallerForPlainKey(db: TestDB, plainKey: string) {
+ const { authenticateApiKey } = await import("./auth");
+ const authResult = await authenticateApiKey(plainKey, db);
+ return getApiCaller(
+ db,
+ authResult.user.id,
+ authResult.user.email ?? undefined,
+ authResult.user.role === "admin" ? "admin" : "user",
+ {
+ type: "apiKey",
+ keyId: authResult.apiKey.keyId,
+ scopes: authResult.apiKey.scopes,
+ },
+ );
+}
+
export type APICallerType = ReturnType<typeof getApiCaller>;
export interface CustomTestContext {