A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(web): Migrate from next-auth to better-auth (#3140)
Mohamed Bassemd3e0b7886c76
diff --git a/README.md b/README.mdindex 23e5c8d0..399ea9d7 100644--- a/README.md+++ b/README.md@@ -70,7 +70,7 @@ The name Karakeep is inspired by the Arabic word "كراكيب" (karakeeb), a co- [NextJS](https://nextjs.org/) for the web app. Using app router.- [Drizzle](https://orm.drizzle.team/) for the database and its migrations.-- [NextAuth](https://next-auth.js.org) for authentication.+- [Better Auth](https://www.better-auth.com) for authentication.- [tRPC](https://trpc.io) for client->server communication.- [Puppeteer](https://pptr.dev/) for crawling the bookmarks.- [OpenAI](https://openai.com/) because AI is so hot right now.diff --git a/apps/cli/src/commands/admin.ts b/apps/cli/src/commands/admin.tsindex 621f10a3..6bc07c37 100644--- a/apps/cli/src/commands/admin.ts+++ b/apps/cli/src/commands/admin.ts@@ -86,15 +86,7 @@ usersCmd});} else {const data: string[][] = [- [- "id",- "Name",- "Email",- "Num Bookmarks",- "Asset Sizes",- "Role",- "Local User",- ],+ ["id", "Name", "Email", "Num Bookmarks", "Asset Sizes", "Role"],];usersResp.users.forEach((user) => {@@ -113,7 +105,6 @@ usersCmdnumBookmarksDisplay,assetSizesDisplay,user.role ?? "",- user.localUser ? "✓" : "✗",]);});diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.jsonindex 07b074a3..e002d6b3 100644--- a/apps/cli/tsconfig.json+++ b/apps/cli/tsconfig.json@@ -7,6 +7,9 @@"baseUrl": ".","tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json","strictNullChecks": true,+ // The tRPC router types pull in shared code that uses DOM types. These+ // used to come in by accident through next-auth's preact dependency.+ "lib": ["es2024", "ESNext.Array", "ESNext.Collection", "ESNext.Iterator", "DOM"],"paths": {"@/*": ["./src/*"]},diff --git a/apps/web/app/api/auth/[...all]/route.tsx b/apps/web/app/api/auth/[...all]/route.tsxnew file mode 100644index 00000000..cbcecba9--- /dev/null+++ b/apps/web/app/api/auth/[...all]/route.tsx@@ -0,0 +1,12 @@+import { auth } from "@/server/auth";++function handler(request: Request) {+ const url = new URL(request.url);+ if (url.pathname === "/api/auth/callback/custom") {+ url.pathname = "/api/auth/oauth2/callback/custom";+ request = new Request(url, request);+ }+ return auth.handler(request);+}++export { handler as GET, handler as POST };diff --git a/apps/web/app/api/auth/[...nextauth]/route.tsx b/apps/web/app/api/auth/[...nextauth]/route.tsxdeleted file mode 100644index 2f7f1cb0..00000000--- a/apps/web/app/api/auth/[...nextauth]/route.tsx+++ /dev/null@@ -1,3 +0,0 @@-import { authHandler } from "@/server/auth";--export { authHandler as GET, authHandler as POST };diff --git a/apps/web/app/check-email/page.tsx b/apps/web/app/check-email/page.tsxindex 50eed4bd..83241fc4 100644--- a/apps/web/app/check-email/page.tsx+++ b/apps/web/app/check-email/page.tsx@@ -11,14 +11,13 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";+import { sendVerificationEmail } from "@/lib/auth/client";import { useMutation } from "@tanstack/react-query";import { Loader2, Mail } from "lucide-react";-import { useTRPC } from "@karakeep/shared-react/trpc";import { validateRedirectUrl } from "@karakeep/shared/utils/redirectUrl";export default function CheckEmailPage() {- const api = useTRPC();const searchParams = useSearchParams();const router = useRouter();const [message, setMessage] = useState("");@@ -27,22 +26,26 @@ export default function CheckEmailPage() {const redirectUrl =validateRedirectUrl(searchParams.get("redirectUrl")) ?? "/";- const resendEmailMutation = useMutation(- api.users.resendVerificationEmail.mutationOptions({- onSuccess: () => {- setMessage(- "A new verification email has been sent to your email address.",- );- },- onError: (error) => {- setMessage(error.message || "Failed to resend verification email.");- },- }),- );+ const resendEmailMutation = useMutation({+ mutationFn: async (input: { email: string; callbackUrl: string }) => {+ const result = await sendVerificationEmail(input);+ if (!result.ok) {+ throw new Error(result.error);+ }+ },+ onSuccess: () => {+ setMessage(+ "A new verification email has been sent to your email address.",+ );+ },+ onError: (error) => {+ setMessage(error.message || "Failed to resend verification email.");+ },+ });const handleResendEmail = () => {if (email) {- resendEmailMutation.mutate({ email, redirectUrl });+ resendEmailMutation.mutate({ email, callbackUrl: redirectUrl });}};diff --git a/apps/web/app/logout/page.tsx b/apps/web/app/logout/page.tsxindex 1820b805..ce96364b 100644--- a/apps/web/app/logout/page.tsx+++ b/apps/web/app/logout/page.tsx@@ -14,10 +14,7 @@ export default function Logout() {removeItem: (k: string) => localStorage.removeItem(k),});useEffect(() => {- signOut({- redirect: false,- callbackUrl: "/",- }).then(() => {+ signOut().then(() => {clearHistory();router.push("/");});diff --git a/apps/web/app/verify-email/page.tsx b/apps/web/app/verify-email/page.tsxindex 5044c63e..2aba8ff1 100644--- a/apps/web/app/verify-email/page.tsx+++ b/apps/web/app/verify-email/page.tsx@@ -11,17 +11,16 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";+import { sendVerificationEmail, verifyEmail } from "@/lib/auth/client";import { useMutation } from "@tanstack/react-query";import { CheckCircle, Loader2, XCircle } from "lucide-react";-import { useTRPC } from "@karakeep/shared-react/trpc";import {isMobileAppRedirect,validateRedirectUrl,} from "@karakeep/shared/utils/redirectUrl";export default function VerifyEmailPage() {- const api = useTRPC();const searchParams = useSearchParams();const router = useRouter();const [status, setStatus] = useState<"loading" | "success" | "error">(@@ -34,61 +33,69 @@ export default function VerifyEmailPage() {const redirectUrl =validateRedirectUrl(searchParams.get("redirectUrl")) ?? "/";- const verifyEmailMutation = useMutation(- api.users.verifyEmail.mutationOptions({- onSuccess: () => {- setStatus("success");- if (isMobileAppRedirect(redirectUrl)) {- setMessage(- "Your email has been successfully verified! Redirecting to the app...",- );- // Redirect to mobile app after a brief delay- setTimeout(() => {- window.location.href = redirectUrl;- }, 1500);- } else {- setMessage(- "Your email has been successfully verified! You can now sign in.",- );- }- },- onError: (error) => {- setStatus("error");+ const verifyEmailMutation = useMutation({+ mutationFn: async (verificationToken: string) => {+ const result = await verifyEmail(verificationToken);+ if (!result.ok) {+ throw new Error(result.error);+ }+ },+ onSuccess: () => {+ setStatus("success");+ if (isMobileAppRedirect(redirectUrl)) {setMessage(- error.message ||- "Failed to verify email. The link may be invalid or expired.",+ "Your email has been successfully verified! Redirecting to the app...",);- },- }),- );-- const resendEmailMutation = useMutation(- api.users.resendVerificationEmail.mutationOptions({- onSuccess: () => {+ // Redirect to mobile app after a brief delay+ setTimeout(() => {+ window.location.href = redirectUrl;+ }, 1500);+ } else {setMessage(- "A new verification email has been sent to your email address.",+ "Your email has been successfully verified! You can now sign in.",);- },- onError: (error) => {- setMessage(error.message || "Failed to resend verification email.");- },- }),- );+ }+ },+ onError: (error) => {+ setStatus("error");+ setMessage(+ error.message ||+ "Failed to verify email. The link may be invalid or expired.",+ );+ },+ });++ const resendEmailMutation = useMutation({+ mutationFn: async (input: { email: string; callbackUrl: string }) => {+ const result = await sendVerificationEmail(input);+ if (!result.ok) {+ throw new Error(result.error);+ }+ },+ onSuccess: () => {+ setMessage(+ "A new verification email has been sent to your email address.",+ );+ },+ onError: (error) => {+ setMessage(error.message || "Failed to resend verification email.");+ },+ });const isMobileRedirect = isMobileAppRedirect(redirectUrl);useEffect(() => {- if (token && email) {- verifyEmailMutation.mutate({ token, email });+ if (token) {+ verifyEmailMutation.mutate(token);} else {setStatus("error");- setMessage("Invalid verification link. Missing token or email.");+ setMessage("Invalid verification link. Missing token.");}- }, [token, email]);+ }, [token]);const handleResendEmail = () => {if (email) {- resendEmailMutation.mutate({ email, redirectUrl });+ resendEmailMutation.mutate({ email, callbackUrl: redirectUrl });}};diff --git a/apps/web/components/admin/UserList.tsx b/apps/web/components/admin/UserList.tsxindex 6789f66a..1bdd9d52 100644--- a/apps/web/components/admin/UserList.tsx+++ b/apps/web/components/admin/UserList.tsx@@ -18,7 +18,7 @@ import {useQueryClient,useSuspenseQuery,} from "@tanstack/react-query";-import { Check, KeyRound, Pencil, Trash, UserPlus, X } from "lucide-react";+import { KeyRound, Pencil, Trash, UserPlus } from "lucide-react";import { useTRPC } from "@karakeep/shared-react/trpc";@@ -83,7 +83,6 @@ export default function UsersSection() {<TableHead>{t("admin.users_list.num_bookmarks")}</TableHead><TableHead>{t("admin.users_list.asset_sizes")}</TableHead><TableHead>{t("common.role")}</TableHead>- <TableHead>{t("admin.users_list.local_user")}</TableHead><TableHead>{t("common.actions")}</TableHead></TableRow></TableHeader>@@ -105,9 +104,6 @@ export default function UsersSection() {<TableCell className="py-1">{u.role && t(`common.roles.${u.role}`)}</TableCell>- <TableCell className="py-1">- {u.localUser ? <Check /> : <X />}- </TableCell><TableCell className="flex gap-1 py-1"><ActionConfirmingDialogtitle={t("admin.users_list.delete_user")}@@ -142,7 +138,7 @@ export default function UsersSection() {<ButtonWithTooltiptooltip={t("admin.users_list.reset_password")}variant="outline"- disabled={session!.user.id == u.id || !u.localUser}+ disabled={session!.user.id == u.id}><KeyRound size={16} color="red" /></ButtonWithTooltip>diff --git a/apps/web/components/invite/InviteAcceptForm.tsx b/apps/web/components/invite/InviteAcceptForm.tsxindex eb1fa5c9..e3e9ff82 100644--- a/apps/web/components/invite/InviteAcceptForm.tsx+++ b/apps/web/components/invite/InviteAcceptForm.tsx@@ -198,7 +198,6 @@ export default function InviteAcceptForm({ token }: InviteAcceptFormProps) {// Sign in the user after successful account creationconst resp = await signIn("credentials", {- redirect: false,email: inviteData.email,password: value.password,});diff --git a/apps/web/components/settings/ChangePassword.tsx b/apps/web/components/settings/ChangePassword.tsxindex cc66bb1d..da2e935e 100644--- a/apps/web/components/settings/ChangePassword.tsx+++ b/apps/web/components/settings/ChangePassword.tsx@@ -13,20 +13,19 @@ import {} from "@/components/ui/form";import { Input } from "@/components/ui/input";import { toast } from "@/components/ui/sonner";+import { changePassword } from "@/lib/auth/client";import { useTranslation } from "@/lib/i18n/client";import { zodResolver } from "@hookform/resolvers/zod";import { useMutation } from "@tanstack/react-query";import { Eye, EyeOff } from "lucide-react";import { useForm } from "react-hook-form";-import { useTRPC } from "@karakeep/shared-react/trpc";import { zChangePasswordSchema } from "@karakeep/shared/types/users";import { Button } from "../ui/button";import { SettingsSection } from "./SettingsPage";export function ChangePassword() {- const api = useTRPC();const { t } = useTranslation();const [showCurrentPassword, setShowCurrentPassword] = useState(false);const [showNewPassword, setShowNewPassword] = useState(false);@@ -40,27 +39,31 @@ export function ChangePassword() {},});- const mutator = useMutation(- api.users.changePassword.mutationOptions({- onSuccess: () => {- toast({ description: "Password changed successfully" });- form.reset();- },- onError: (e) => {- if (e.data?.code == "UNAUTHORIZED") {- toast({- description: "Your current password is incorrect",- variant: "destructive",- });- } else {- toast({- description: "Something went wrong",- variant: "destructive",- });- }- },- }),- );+ const mutator = useMutation({+ mutationFn: async (input: {+ currentPassword: string;+ newPassword: string;+ }) => {+ const result = await changePassword(input);+ if (!result.ok) {+ throw new Error(+ result.code === "INVALID_PASSWORD"+ ? "Your current password is incorrect"+ : "Something went wrong",+ );+ }+ },+ onSuccess: () => {+ toast({ description: "Password changed successfully" });+ form.reset();+ },+ onError: (e) => {+ toast({+ description: e.message,+ variant: "destructive",+ });+ },+ });async function onSubmit(value: z.infer<typeof zChangePasswordSchema>) {mutator.mutate({diff --git a/apps/web/components/signin/CredentialsForm.tsx b/apps/web/components/signin/CredentialsForm.tsxindex 46bffc3d..f69de68e 100644--- a/apps/web/components/signin/CredentialsForm.tsx+++ b/apps/web/components/signin/CredentialsForm.tsx@@ -29,8 +29,6 @@ const signInSchema = z.object({const SIGNIN_FAILED = "Incorrect email or password";const OAUTH_FAILED = "OAuth login failed: ";-const VERIFY_EMAIL_ERROR = "Please verify your email address before signing in";-export default function CredentialsForm() {const [signinError, setSigninError] = useState("");const router = useRouter();@@ -75,19 +73,18 @@ export default function CredentialsForm() {<formonSubmit={form.handleSubmit(async (value) => {const resp = await signIn("credentials", {- redirect: false,email: value.email.trim(),password: value.password,});- if (!resp || !resp?.ok || resp.error) {- if (resp?.error === "CredentialsSignin") {+ if (!resp.ok) {+ if (resp.code === "INVALID_EMAIL_OR_PASSWORD") {setSigninError(SIGNIN_FAILED);- } else if (resp?.error === VERIFY_EMAIL_ERROR) {+ } else if (resp.code === "EMAIL_NOT_VERIFIED") {router.replace(`/check-email?email=${encodeURIComponent(value.email.trim())}`,);} else {- setSigninError(resp?.error ?? SIGNIN_FAILED);+ setSigninError(resp.error ?? SIGNIN_FAILED);}return;}diff --git a/apps/web/components/signin/ForgotPasswordForm.tsx b/apps/web/components/signin/ForgotPasswordForm.tsxindex 7ba37553..8e4a7409 100644--- a/apps/web/components/signin/ForgotPasswordForm.tsx+++ b/apps/web/components/signin/ForgotPasswordForm.tsx@@ -20,21 +20,17 @@ import {FormMessage,} from "@/components/ui/form";import { Input } from "@/components/ui/input";+import { requestPasswordReset } from "@/lib/auth/client";import { zodResolver } from "@hookform/resolvers/zod";-import { useMutation } from "@tanstack/react-query";-import { TRPCClientError } from "@trpc/client";import { AlertCircle, CheckCircle } from "lucide-react";import { useForm } from "react-hook-form";import { z } from "zod";-import { useTRPC } from "@karakeep/shared-react/trpc";-const forgotPasswordSchema = z.object({email: z.string().email("Please enter a valid email address"),});export default function ForgotPasswordForm() {- const api = useTRPC();const [isSubmitted, setIsSubmitted] = useState(false);const [errorMessage, setErrorMessage] = useState("");const router = useRouter();@@ -43,22 +39,16 @@ export default function ForgotPasswordForm() {resolver: zodResolver(forgotPasswordSchema),});- const forgotPasswordMutation = useMutation(- api.users.forgotPassword.mutationOptions(),- );-const onSubmit = async (values: z.infer<typeof forgotPasswordSchema>) => {- try {- setErrorMessage("");- await forgotPasswordMutation.mutateAsync(values);- setIsSubmitted(true);- } catch (error) {- if (error instanceof TRPCClientError) {- setErrorMessage(error.message);- } else {- setErrorMessage("An unexpected error occurred. Please try again.");- }+ setErrorMessage("");+ const result = await requestPasswordReset(values.email);+ if (!result.ok) {+ setErrorMessage(+ result.error ?? "An unexpected error occurred. Please try again.",+ );+ return;}+ setIsSubmitted(true);};return (diff --git a/apps/web/components/signin/ResetPasswordForm.tsx b/apps/web/components/signin/ResetPasswordForm.tsxindex 655f1932..e7b8cae1 100644--- a/apps/web/components/signin/ResetPasswordForm.tsx+++ b/apps/web/components/signin/ResetPasswordForm.tsx@@ -20,14 +20,12 @@ import {FormMessage,} from "@/components/ui/form";import { Input } from "@/components/ui/input";+import { resetPassword } from "@/lib/auth/client";import { zodResolver } from "@hookform/resolvers/zod";-import { useMutation } from "@tanstack/react-query";-import { TRPCClientError } from "@trpc/client";import { AlertCircle, CheckCircle } from "lucide-react";import { useForm } from "react-hook-form";import { z } from "zod";-import { useTRPC } from "@karakeep/shared-react/trpc";import { zResetPasswordSchema } from "@karakeep/shared/types/users";const resetPasswordSchema = z@@ -45,7 +43,6 @@ interface ResetPasswordFormProps {}export default function ResetPasswordForm({ token }: ResetPasswordFormProps) {- const api = useTRPC();const [isSuccess, setIsSuccess] = useState(false);const [errorMessage, setErrorMessage] = useState("");const router = useRouter();@@ -54,25 +51,21 @@ export default function ResetPasswordForm({ token }: ResetPasswordFormProps) {resolver: zodResolver(resetPasswordSchema),});- const resetPasswordMutation = useMutation(- api.users.resetPassword.mutationOptions(),- );-const onSubmit = async (values: z.infer<typeof resetPasswordSchema>) => {- try {- setErrorMessage("");- await resetPasswordMutation.mutateAsync({- token,- newPassword: values.newPassword,- });- setIsSuccess(true);- } catch (error) {- if (error instanceof TRPCClientError) {- setErrorMessage(error.message);- } else {- setErrorMessage("An unexpected error occurred. Please try again.");- }+ setErrorMessage("");+ const result = await resetPassword({+ token,+ newPassword: values.newPassword,+ });+ if (!result.ok) {+ setErrorMessage(+ result.code === "INVALID_TOKEN"+ ? "Invalid or expired reset token"+ : (result.error ?? "An unexpected error occurred. Please try again."),+ );+ return;}+ setIsSuccess(true);};return (diff --git a/apps/web/components/signin/SignInForm.tsx b/apps/web/components/signin/SignInForm.tsxindex 7501b63d..819a7a35 100644--- a/apps/web/components/signin/SignInForm.tsx+++ b/apps/web/components/signin/SignInForm.tsx@@ -6,7 +6,7 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";-import { authOptions } from "@/server/auth";+import { oauthProviders } from "@/server/auth";import { Info } from "lucide-react";import serverConfig from "@karakeep/shared/config";@@ -16,14 +16,7 @@ import OAuthAutoRedirect from "./OAuthAutoRedirect";import SignInProviderButton from "./SignInProviderButton";export default async function SignInForm() {- const providers = authOptions.providers;- let providerValues;- if (providers) {- providerValues = Object.values(providers).filter(- // Credentials are handled manually by the sign in form- (p) => p.id != "credentials",- );- }+ const providerValues = oauthProviders;return (<div className="w-full">diff --git a/apps/web/components/signup/SignUpForm.tsx b/apps/web/components/signup/SignUpForm.tsxindex 379d50d0..eddfcef7 100644--- a/apps/web/components/signup/SignUpForm.tsx+++ b/apps/web/components/signup/SignUpForm.tsx@@ -23,28 +23,22 @@ import {FormMessage,} from "@/components/ui/form";import { Input } from "@/components/ui/input";-import { signIn } from "@/lib/auth/client";+import { signUp } from "@/lib/auth/client";import { useClientConfig } from "@/lib/clientConfig";import { zodResolver } from "@hookform/resolvers/zod";import { Turnstile } from "@marsidev/react-turnstile";-import { useMutation } from "@tanstack/react-query";-import { TRPCClientError } from "@trpc/client";import { AlertCircle, UserX } from "lucide-react";import { useForm } from "react-hook-form";import { z } from "zod";-import { useTRPC } from "@karakeep/shared-react/trpc";import { zSignUpSchema } from "@karakeep/shared/types/users";import { isMobileAppRedirect } from "@karakeep/shared/utils/redirectUrl";-const VERIFY_EMAIL_ERROR = "Please verify your email address before signing in";-interface SignUpFormProps {redirectUrl: string;}export default function SignUpForm({ redirectUrl }: SignUpFormProps) {- const api = useTRPC();const form = useForm<z.infer<typeof zSignUpSchema>>({resolver: zodResolver(zSignUpSchema),defaultValues: {@@ -61,8 +55,6 @@ export default function SignUpForm({ redirectUrl }: SignUpFormProps) {const turnstileSiteKey = clientConfig.turnstile?.siteKey;const turnstileRef = useRef<TurnstileInstance>(null);- const createUserMutation = useMutation(api.users.create.mutationOptions());-if (clientConfig.auth.disableSignups ||clientConfig.auth.disablePasswordAuth@@ -117,37 +109,18 @@ export default function SignUpForm({ redirectUrl }: SignUpFormProps) {return;}form.clearErrors("turnstileToken");- try {- await createUserMutation.mutateAsync({- ...value,- redirectUrl,- });- } catch (e) {- if (e instanceof TRPCClientError) {- setErrorMessage(e.message);- }- // Reset turnstile widget on error to get a new token- if (turnstileSiteKey) {- turnstileRef.current?.reset();- form.setValue("turnstileToken", "");- }- return;- }- const resp = await signIn("credentials", {- redirect: false,- email: value.email.trim(),+ const email = value.email.trim();+ const resp = await signUp({+ name: value.name,+ email,password: value.password,+ callbackUrl: redirectUrl,+ turnstileToken: value.turnstileToken,});- if (!resp || !resp.ok || resp.error) {- if (resp?.error === VERIFY_EMAIL_ERROR) {- router.replace(- `/check-email?email=${encodeURIComponent(value.email.trim())}&redirectUrl=${encodeURIComponent(redirectUrl)}`,- );- } else {- setErrorMessage(- resp?.error ?? "Hit an unexpected error while signing in",- );- }+ if (!resp.ok) {+ setErrorMessage(+ resp.error ?? "Hit an unexpected error while signing up",+ );// Reset turnstile widget on error to get a new tokenif (turnstileSiteKey) {turnstileRef.current?.reset();@@ -155,6 +128,13 @@ export default function SignUpForm({ redirectUrl }: SignUpFormProps) {}return;}+ if (!resp.signedIn) {+ // The email address has to be verified before signing in.+ router.replace(+ `/check-email?email=${encodeURIComponent(email)}&redirectUrl=${encodeURIComponent(redirectUrl)}`,+ );+ return;+ }if (isMobileAppRedirect(redirectUrl)) {window.location.href = redirectUrl;} else {@@ -276,9 +256,7 @@ export default function SignUpForm({ redirectUrl }: SignUpFormProps) {<ActionButtontype="submit"- loading={- form.formState.isSubmitting || createUserMutation.isPending- }+ loading={form.formState.isSubmitting}className="w-full">Sign updiff --git a/apps/web/lib/auth/client.ts b/apps/web/lib/auth/client.tsindex 7e13f798..55589eb4 100644--- a/apps/web/lib/auth/client.ts+++ b/apps/web/lib/auth/client.ts@@ -1,11 +1,185 @@"use client";-/**- * Centralized client-side auth utilities.- * This module re-exports next-auth/react functions to allow for easier- * future migration to a different auth provider.- */+import type { PropsWithChildren } from "react";+import type { auth } from "@/server/auth";+import { createContext, createElement, useContext } from "react";+import { TURNSTILE_TOKEN_HEADER } from "@/lib/auth/constants";+import { createAuthClient } from "better-auth/react";+import {+ genericOAuthClient,+ inferAdditionalFields,+} from "better-auth/client/plugins";-export { SessionProvider, signIn, signOut, useSession } from "next-auth/react";+export interface Session {+ user: {+ id: string;+ name: string;+ email: string;+ image?: string | null;+ role: "admin" | "user";+ };+ expires: string;+}-export type { Session } from "next-auth";+const authClient = createAuthClient({+ plugins: [genericOAuthClient(), inferAdditionalFields<typeof auth>()],+});++type ClientSessionData = NonNullable<+ ReturnType<typeof authClient.useSession>["data"]+>;++function toSession(data: ClientSessionData): Session {+ return {+ user: {+ id: data.user.id,+ name: data.user.name,+ email: data.user.email,+ image: data.user.image,+ role: data.user.role === "admin" ? "admin" : "user",+ },+ expires: new Date(data.session.expiresAt).toISOString(),+ };+}++// The session resolved on the server during SSR. It's used until the client+// side session fetch completes, so that client components don't render as+// logged out (and redirect away) on the initial page load.+const InitialSessionContext = createContext<Session | null>(null);++export function SessionProvider({+ children,+ session,+}: PropsWithChildren<{ session?: Session | null }>) {+ return createElement(+ InitialSessionContext.Provider,+ { value: session ?? null },+ children,+ );+}++export function useSession() {+ const initialSession = useContext(InitialSessionContext);+ const session = authClient.useSession();+ if (session.isPending) {+ return { ...session, data: initialSession };+ }+ return { ...session, data: session.data ? toSession(session.data) : null };+}++export interface AuthResult {+ ok: boolean;+ error?: string;+ // better-auth's error code, e.g. "EMAIL_NOT_VERIFIED".+ code?: string;+}++function toAuthResult(result: {+ error: { message?: string; code?: string } | null;+}): AuthResult {+ return {+ ok: !result.error,+ error: result.error?.message,+ code: result.error?.code,+ };+}++export async function signIn(+ provider: string,+ options: {+ email?: string;+ password?: string;+ callbackUrl?: string;+ } = {},+): Promise<AuthResult> {+ if (provider === "credentials") {+ if (!options.email || options.password === undefined) {+ return { ok: false, error: "Email and password are required" };+ }+ return toAuthResult(+ await authClient.signIn.email({+ email: options.email,+ password: options.password,+ callbackURL: options.callbackUrl,+ }),+ );+ }++ return toAuthResult(+ await authClient.signIn.oauth2({+ providerId: provider,+ callbackURL: options.callbackUrl ?? "/",+ errorCallbackURL: "/signin",+ }),+ );+}++export async function signOut(): Promise<AuthResult> {+ return toAuthResult(await authClient.signOut());+}++export async function signUp(input: {+ name: string;+ email: string;+ password: string;+ callbackUrl?: string;+ turnstileToken?: string;+}): Promise<AuthResult & { signedIn: boolean }> {+ const result = await authClient.signUp.email(+ {+ name: input.name,+ email: input.email,+ password: input.password,+ callbackURL: input.callbackUrl,+ },+ {+ headers: input.turnstileToken+ ? { [TURNSTILE_TOKEN_HEADER]: input.turnstileToken }+ : undefined,+ },+ );+ return {+ ...toAuthResult(result),+ // No session is created when the email address needs to be verified first.+ signedIn: !!result.data?.token,+ };+}++export async function sendVerificationEmail(input: {+ email: string;+ callbackUrl?: string;+}): Promise<AuthResult> {+ return toAuthResult(+ await authClient.sendVerificationEmail({+ email: input.email,+ callbackURL: input.callbackUrl,+ }),+ );+}++export async function verifyEmail(token: string): Promise<AuthResult> {+ return toAuthResult(await authClient.verifyEmail({ query: { token } }));+}++export async function requestPasswordReset(email: string): Promise<AuthResult> {+ return toAuthResult(await authClient.requestPasswordReset({ email }));+}++export async function resetPassword(input: {+ token: string;+ newPassword: string;+}): Promise<AuthResult> {+ return toAuthResult(await authClient.resetPassword(input));+}++export async function changePassword(input: {+ currentPassword: string;+ newPassword: string;+}): Promise<AuthResult> {+ return toAuthResult(+ await authClient.changePassword({+ ...input,+ revokeOtherSessions: true,+ }),+ );+}diff --git a/apps/web/lib/auth/constants.ts b/apps/web/lib/auth/constants.tsnew file mode 100644index 00000000..f76249aa--- /dev/null+++ b/apps/web/lib/auth/constants.ts@@ -0,0 +1,2 @@+// The header the sign up form sends the Turnstile challenge response in.+export const TURNSTILE_TOKEN_HEADER = "x-turnstile-token";diff --git a/apps/web/package.json b/apps/web/package.jsonindex fb20fabf..20c6430c 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -18,7 +18,6 @@"format:fix": "oxfmt --ignore-path=../../.gitignore ."},"dependencies": {- "@auth/drizzle-adapter": "~1.11.3","@emoji-mart/data": "^1.1.2","@emoji-mart/react": "^1.1.1","@hookform/resolvers": "^5.2.2",@@ -34,6 +33,7 @@"@lexical/react": "^0.20.2","@lexical/rich-text": "^0.20.2","@marsidev/react-turnstile": "^1.3.1",+ "@paralleldrive/cuid2": "^2.2.2","@radix-ui/react-avatar": "^1.1.11","@radix-ui/react-collapsible": "^1.1.11","@radix-ui/react-dialog": "^1.1.14",@@ -66,6 +66,7 @@"@trpc/server": "^11.9.0","@trpc/tanstack-react-query": "^11.9.0","ai": "^6.0.286",+ "better-auth": "1.6.25","better-sqlite3": "^13.0.3","cheerio": "^1.2.0","class-variance-authority": "^0.7.0",@@ -82,7 +83,6 @@"modern-screenshot": "^4.6.7","nanoid": "^5.1.16","next": "16.3.8",- "next-auth": "^4.24.15","next-i18next": "^15.3.1","next-themes": "^0.4.6","nuqs": "^2.4.3",diff --git a/apps/web/server/auth.test.ts b/apps/web/server/auth.test.tsnew file mode 100644index 00000000..86539dd9--- /dev/null+++ b/apps/web/server/auth.test.ts@@ -0,0 +1,606 @@+import os from "node:os";+import path from "node:path";+import { isCuid } from "@paralleldrive/cuid2";+import bcrypt from "bcryptjs";+import { eq } from "drizzle-orm";+import { afterEach, describe, expect, test, vi } from "vitest";+import { z } from "zod";++import { getInMemoryDB } from "@karakeep/db/drizzle";+import { accounts, sessions, users } from "@karakeep/db/schema";++const BASE_URL = "http://localhost:3000";++interface SentEmail {+ type: "verify" | "reset";+ email: string;+ url: string;+}++async function setup(env: Record<string, string> = {}) {+ vi.resetModules();+ vi.stubEnv("DATA_DIR", path.join(os.tmpdir(), "karakeep-auth-test"));+ vi.stubEnv("NEXTAUTH_URL", BASE_URL);+ vi.stubEnv("NEXTAUTH_SECRET", "test-secret-test-secret-test-secret");+ for (const [key, value] of Object.entries(env)) {+ vi.stubEnv(key, value);+ }++ const db = getInMemoryDB(true);+ const sent: SentEmail[] = [];+ vi.doMock("@karakeep/db", () => ({ db }));+ vi.doMock("@karakeep/trpc/email", () => ({+ sendVerificationEmail: async (+ email: string,+ _name: string,+ url: string,+ ) => {+ sent.push({ type: "verify", email, url });+ },+ sendPasswordResetEmail: async (+ email: string,+ _name: string,+ url: string,+ ) => {+ sent.push({ type: "reset", email, url });+ },+ }));++ const { auth } = await import("./auth");++ async function call(+ endpoint: string,+ opts: {+ body?: Record<string, unknown>;+ cookie?: string;+ method?: string;+ headers?: Record<string, string>;+ } = {},+ ) {+ const res = await auth.handler(+ new Request(`${BASE_URL}/api/auth${endpoint}`, {+ method: opts.method ?? (opts.body ? "POST" : "GET"),+ headers: {+ "content-type": "application/json",+ origin: BASE_URL,+ ...(opts.cookie ? { cookie: opts.cookie } : {}),+ ...opts.headers,+ },+ body: opts.body ? JSON.stringify(opts.body) : undefined,+ }),+ );+ const text = await res.text();+ const json: unknown = text ? JSON.parse(text) : null;+ const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0];+ return { status: res.status, json, cookie };+ }++ async function signUp(+ email: string,+ password = "password123",+ name = "Test User",+ ) {+ return await call("/sign-up/email", { body: { name, email, password } });+ }++ async function signIn(email: string, password = "password123") {+ return await call("/sign-in/email", { body: { email, password } });+ }++ return { auth, db, sent, call, signUp, signIn };+}++function errorCode(json: unknown) {+ if (json && typeof json === "object" && "code" in json) {+ return json.code;+ }+ return undefined;+}++function tokenFromUrl(url: string) {+ return new URL(url).searchParams.get("token") ?? "";+}++afterEach(() => {+ vi.unstubAllEnvs();+ vi.doUnmock("@karakeep/db");+ vi.doUnmock("@karakeep/trpc/email");+});++describe("better-auth configuration", () => {+ test("sign up creates a user with a credential account", async () => {+ const { db, signUp } = await setup({ FREE_QUOTA_BOOKMARK_LIMIT: "42" });++ const first = await signUp("[email protected]", "password123", " First ");+ expect(first.status).toBe(200);+ // Signed in right away when email verification isn't required.+ expect(first.cookie).toMatch(/session_token=.+/);+ const second = await signUp("[email protected]");+ expect(second.status).toBe(200);++ const rows = await db.query.users.findMany();+ const firstUser = rows.find((u) => u.email === "[email protected]");+ const secondUser = rows.find((u) => u.email === "[email protected]");+ expect(firstUser?.role).toBe("admin");+ expect(firstUser?.name).toBe("First");+ expect(firstUser?.bookmarkQuota).toBe(42);+ expect(firstUser?.emailVerified).toBe(false);+ expect(secondUser?.role).toBe("user");++ const credential = await db.query.accounts.findFirst({+ where: eq(accounts.userId, firstUser?.id ?? ""),+ });+ expect(credential?.providerId).toBe("credential");+ expect(credential?.accountId).toBe(firstUser?.id);+ expect(credential?.password).toMatch(/^\$2[aby]\$/);++ // Ids are generated the same way as for the rest of Karakeep's tables.+ const session = await db.query.sessions.findFirst();+ for (const id of [firstUser?.id, credential?.id, session?.id]) {+ expect(isCuid(id ?? "")).toBe(true);+ }+ });++ test("sign up validates its input", async () => {+ const { db, signUp } = await setup();++ const htmlName = await signUp(+ "[email protected]",+ "password123",+ "<b>name</b>",+ );+ expect(htmlName.status).toBe(400);+ const shortPassword = await signUp("[email protected]", "short");+ expect(shortPassword.status).toBe(400);++ expect(await db.query.users.findMany()).toHaveLength(0);+ });++ test("sign in works with legacy salted passwords", async () => {+ const { db, signIn } = await setup();+ await db.insert(users).values({+ id: "legacy",+ name: "Legacy",+ email: "[email protected]",+ emailVerified: true,+ });+ await db.insert(accounts).values({+ userId: "legacy",+ accountId: "legacy",+ providerId: "credential",+ password: `bcrypt-salted:abc:${await bcrypt.hash("old-password" + "abc", 4)}`,+ });++ const ok = await signIn("[email protected]", "old-password");+ expect(ok.status).toBe(200);+ const wrong = await signIn("[email protected]", "wrong-password");+ expect(wrong.status).toBe(401);+ expect(errorCode(wrong.json)).toBe("INVALID_EMAIL_OR_PASSWORD");+ });++ test("sign in works from an address other than NEXTAUTH_URL", async () => {+ const { signUp, call } = await setup();+ await signUp("[email protected]");+ const body = { email: "[email protected]", password: "password123" };+ const requests: Record<string, string>[] = [+ { origin: "http://192.168.1.10:3000", host: "192.168.1.10:3000" },+ {+ origin: "https://karakeep.example.com",+ host: "localhost:3000",+ "x-forwarded-host": "karakeep.example.com",+ },+ ];+ for (const headers of requests) {+ expect((await call("/sign-in/email", { body, headers })).status).toBe(+ 200,+ );+ }+ });++ test("cross-origin requests and redirects are rejected", async () => {+ const { signUp, call } = await setup();+ await signUp("[email protected]");+ const crossOrigin = await call("/sign-in/email", {+ body: { email: "[email protected]", password: "password123" },+ headers: { origin: "https://evil.example.com", host: "localhost:3000" },+ });+ expect(crossOrigin.status).toBe(403);+ const redirect = await call("/sign-in/email", {+ body: {+ email: "[email protected]",+ password: "password123",+ callbackURL: "https://evil.example.com/",+ },+ });+ expect(redirect.status).toBe(403);+ });++ test("endpoints Karakeep doesn't use are rejected", async () => {+ const { db, call, signUp } = await setup();+ const { cookie } = await signUp("[email protected]");++ const postEndpoints: { endpoint: string; body: Record<string, string> }[] =+ [+ {+ endpoint: "/update-user",+ body: { name: "<img src=x onerror=alert(1)>" },+ },+ { endpoint: "/delete-user", body: {} },+ { endpoint: "/revoke-sessions", body: {} },+ { endpoint: "/unlink-account", body: { providerId: "credential" } },+ { endpoint: "/verify-password", body: { password: "password123" } },+ ];+ for (const { endpoint, body } of postEndpoints) {+ const res = await call(endpoint, { cookie, body });+ expect(res.status, endpoint).toBe(404);+ }+ for (const endpoint of [+ "/list-accounts",+ "/list-sessions",+ "/reset-password/some-token",+ ]) {+ const res = await call(endpoint, { cookie });+ expect(res.status, endpoint).toBe(404);+ }++ const user = await db.query.users.findFirst();+ expect(user?.name).toBe("Test User");+ expect(await db.query.sessions.findMany()).toHaveLength(1);+ });++ test("change password", async () => {+ const { db, call, signUp, signIn } = await setup();+ const { cookie } = await signUp("[email protected]", "old-password");+ await signIn("[email protected]", "old-password");+ expect(await db.query.sessions.findMany()).toHaveLength(2);++ const wrong = await call("/change-password", {+ cookie,+ body: { currentPassword: "nope-nope", newPassword: "new-password" },+ });+ expect(errorCode(wrong.json)).toBe("INVALID_PASSWORD");++ const ok = await call("/change-password", {+ cookie,+ body: {+ currentPassword: "old-password",+ newPassword: "new-password",+ revokeOtherSessions: true,+ },+ });+ expect(ok.status).toBe(200);+ // The other session is revoked, the current one is replaced.+ expect(await db.query.sessions.findMany()).toHaveLength(1);+ expect((await signIn("[email protected]", "old-password")).status).toBe(401);+ expect((await signIn("[email protected]", "new-password")).status).toBe(200);+ });++ test("password reset isn't available without SMTP", async () => {+ const { call, signUp } = await setup();+ await signUp("[email protected]");+ const res = await call("/request-password-reset", {+ body: { email: "[email protected]" },+ });+ expect(res.status).toBe(400);+ });+});++describe("with email verification required", () => {+ const env = {+ EMAIL_VERIFICATION_REQUIRED: "true",+ SMTP_HOST: "smtp.example.com",+ SMTP_FROM: "[email protected]",+ };++ test("users must verify their email before signing in", async () => {+ const { call, sent, signUp, signIn } = await setup(env);++ const res = await call("/sign-up/email", {+ body: {+ name: "User",+ email: "[email protected]",+ password: "password123",+ callbackURL: "karakeep://signin",+ },+ });+ expect(res.status).toBe(200);+ expect(res.cookie).toBe("");++ expect(sent).toHaveLength(1);+ const verificationUrl = new URL(sent[0].url);+ expect(verificationUrl.origin + verificationUrl.pathname).toBe(+ `${BASE_URL}/verify-email`,+ );+ expect(verificationUrl.searchParams.get("email")).toBe("[email protected]");+ expect(verificationUrl.searchParams.get("redirectUrl")).toBe(+ "karakeep://signin",+ );++ // The password is checked before the verification status, so unverified+ // accounts can't be discovered with a wrong password.+ const wrongPassword = await signIn("[email protected]", "wrong-password");+ expect(wrongPassword.status).toBe(401);+ const unverified = await signIn("[email protected]");+ expect(unverified.status).toBe(403);+ expect(errorCode(unverified.json)).toBe("EMAIL_NOT_VERIFIED");++ const verified = await call(+ `/verify-email?token=${tokenFromUrl(sent[0].url)}`,+ );+ expect(verified.status).toBe(200);+ expect((await signIn("[email protected]")).status).toBe(200);++ // Signing up again with the same email doesn't reveal that it's taken.+ const duplicate = await signUp("[email protected]");+ expect(duplicate.status).toBe(200);+ });++ test("password reset", async () => {+ const { db, call, sent, signUp, signIn } = await setup(env);+ await signUp("[email protected]", "old-password");+ await call(`/verify-email?token=${tokenFromUrl(sent[0].url)}`);+ await signIn("[email protected]", "old-password");+ expect(await db.query.sessions.findMany()).toHaveLength(1);++ const requested = await call("/request-password-reset", {+ body: { email: "[email protected]" },+ });+ expect(requested.status).toBe(200);+ const resetEmail = sent.find((e) => e.type === "reset");+ expect(resetEmail?.url).toMatch(`${BASE_URL}/reset-password?token=`);+ const token = tokenFromUrl(resetEmail?.url ?? "");++ const reset = await call("/reset-password", {+ body: { token, newPassword: "new-password" },+ });+ expect(reset.status).toBe(200);+ // Existing sessions are revoked on reset.+ expect(await db.query.sessions.findMany()).toHaveLength(0);+ expect((await signIn("[email protected]", "old-password")).status).toBe(401);+ expect((await signIn("[email protected]", "new-password")).status).toBe(200);++ const reused = await call("/reset-password", {+ body: { token, newPassword: "another-password" },+ });+ expect(errorCode(reused.json)).toBe("INVALID_TOKEN");+ });++ test("password reset emails are only sent to users with a password", async () => {+ const { db, call, sent } = await setup(env);+ await db.insert(users).values({+ id: "oauth",+ name: "OAuth",+ email: "[email protected]",+ emailVerified: true,+ });++ for (const email of ["[email protected]", "[email protected]"]) {+ const res = await call("/request-password-reset", { body: { email } });+ expect(res.status).toBe(200);+ }+ expect(sent).toHaveLength(0);+ });+});++describe("server config restrictions", () => {+ test("signups can be disabled", async () => {+ const { db, signUp, signIn } = await setup({ DISABLE_SIGNUPS: "true" });+ const res = await signUp("[email protected]");+ expect(res.status).toBe(403);+ expect(await db.query.users.findMany()).toHaveLength(0);++ await db.insert(users).values({+ id: "existing",+ name: "Existing",+ email: "[email protected]",+ emailVerified: true,+ });+ await db.insert(accounts).values({+ userId: "existing",+ accountId: "existing",+ providerId: "credential",+ password: await bcrypt.hash("password123", 4),+ });+ expect((await signIn("[email protected]")).status).toBe(200);+ });++ test("password auth can be disabled", async () => {+ const { call, signUp, signIn } = await setup({+ DISABLE_PASSWORD_AUTH: "true",+ });+ expect((await signUp("[email protected]")).status).toBe(403);+ expect((await signIn("[email protected]")).status).toBe(403);+ const reset = await call("/request-password-reset", {+ body: { email: "[email protected]" },+ });+ expect(reset.status).toBe(403);+ });++ test("demo mode allows signing in but not other writes", async () => {+ const { db, call, signUp, signIn } = await setup({ DEMO_MODE: "true" });+ expect((await signUp("[email protected]")).status).toBe(403);++ await db.insert(users).values({+ id: "demo",+ name: "Demo",+ email: "[email protected]",+ emailVerified: true,+ });+ await db.insert(accounts).values({+ userId: "demo",+ accountId: "demo",+ providerId: "credential",+ password: await bcrypt.hash("password123", 4),+ });+ const signedIn = await signIn("[email protected]");+ expect(signedIn.status).toBe(200);++ const changed = await call("/change-password", {+ cookie: signedIn.cookie,+ body: { currentPassword: "password123", newPassword: "new-password" },+ });+ expect(changed.status).toBe(403);+ });++ test("degraded mode rejects writes with a clear error", async () => {+ const { signIn } = await setup({ DEGRADED_MODE: "true" });+ const res = await signIn("[email protected]");+ expect(res.status).toBe(403);+ });++ test("turnstile is required when enabled", async () => {+ const { db, signUp } = await setup({+ TURNSTILE_SITE_KEY: "site-key",+ TURNSTILE_SECRET_KEY: "secret-key",+ });+ expect((await signUp("[email protected]")).status).toBe(400);+ expect(await db.query.users.findMany()).toHaveLength(0);+ });++ test("deleting a user removes their sessions and accounts", async () => {+ const { db, signUp } = await setup();+ await signUp("[email protected]");+ const user = await db.query.users.findFirst();+ await db.delete(users).where(eq(users.id, user?.id ?? ""));+ expect(await db.query.sessions.findMany()).toHaveLength(0);+ expect(+ await db+ .select()+ .from(accounts)+ .where(eq(accounts.userId, user?.id ?? "")),+ ).toHaveLength(0);+ expect(await db.select().from(sessions)).toHaveLength(0);+ });+});++describe("trusted origins", () => {+ const body = { email: "[email protected]", password: "password123" };+ const lanIp = {+ origin: "http://192.168.1.10:3000",+ host: "192.168.1.10:3000",+ };++ test("can be restricted to NEXTAUTH_URL", async () => {+ const { signUp, call } = await setup({ AUTH_TRUSTED_ORIGINS: "" });+ await signUp("[email protected]");+ expect(+ (await call("/sign-in/email", { body, headers: lanIp })).status,+ ).toBe(403);+ expect((await call("/sign-in/email", { body })).status).toBe(200);+ });++ test("can list extra origins", async () => {+ const { signUp, call } = await setup({+ AUTH_TRUSTED_ORIGINS:+ "https://karakeep.example.com, https://other.example.com",+ });+ await signUp("[email protected]");+ expect(+ (await call("/sign-in/email", { body, headers: lanIp })).status,+ ).toBe(403);+ const other = await call("/sign-in/email", {+ body: { ...body, callbackURL: "https://karakeep.example.com/dashboard" },+ headers: { origin: "https://other.example.com" },+ });+ expect(other.status).toBe(200);+ });+});++describe("oauth token endpoint authentication", () => {+ const ISSUER = "https://idp.example.com";++ async function signInWithOAuth(env: Record<string, string>) {+ const tokenRequests: Request[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const request = new Request(input, init);+ const url = new URL(request.url);+ if (url.pathname === "/.well-known/openid-configuration") {+ return Response.json({+ issuer: ISSUER,+ authorization_endpoint: `${ISSUER}/authorize`,+ token_endpoint: `${ISSUER}/token`,+ userinfo_endpoint: `${ISSUER}/userinfo`,+ });+ }+ if (url.pathname === "/token") {+ tokenRequests.push(request);+ return Response.json({ access_token: "at", token_type: "Bearer" });+ }+ if (url.pathname === "/userinfo") {+ return Response.json({+ sub: "oauth-sub",+ email: "[email protected]",+ email_verified: true,+ name: "OAuth User",+ });+ }+ return new Response("not found", { status: 404 });+ }),+ );+ const { auth, db } = await setup({+ OAUTH_WELLKNOWN_URL: `${ISSUER}/.well-known/openid-configuration`,+ OAUTH_CLIENT_ID: "karakeep",+ OAUTH_CLIENT_SECRET: "a+b/c=%41 d",+ ...env,+ });++ const start = await auth.handler(+ new Request(`${BASE_URL}/api/auth/sign-in/oauth2`, {+ method: "POST",+ headers: { "content-type": "application/json", origin: BASE_URL },+ body: JSON.stringify({ providerId: "custom", callbackURL: "/" }),+ }),+ );+ const { url } = z.object({ url: z.string() }).parse(await start.json());+ const state = new URL(url).searchParams.get("state") ?? "";+ const cookie = start.headers+ .getSetCookie()+ .map((c) => c.split(";")[0])+ .join("; ");+ const callback = await auth.handler(+ new Request(+ `${BASE_URL}/api/auth/oauth2/callback/custom?code=the-code&state=${state}`,+ { headers: { cookie } },+ ),+ );+ return { callback, tokenRequests, db };+ }++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ test("defaults to basic auth with form-urlencoded credentials", async () => {+ const { callback, tokenRequests, db } = await signInWithOAuth({});+ expect(callback.headers.get("location")).toBe("/");+ expect(tokenRequests).toHaveLength(1);+ const [request] = tokenRequests;+ expect(request.headers.get("authorization")).toBe(+ `Basic ${Buffer.from("karakeep:a%2Bb%2Fc%3D%2541+d").toString("base64")}`,+ );+ const form = new URLSearchParams(await request.text());+ expect(form.has("client_secret")).toBe(false);+ expect(form.get("redirect_uri")).toBe(+ `${BASE_URL}/api/auth/callback/custom`,+ );+ expect(+ await db.query.accounts.findFirst({+ where: eq(accounts.accountId, "oauth-sub"),+ }),+ ).toBeDefined();+ });++ test("supports client_secret_post", async () => {+ const { callback, tokenRequests } = await signInWithOAuth({+ OAUTH_TOKEN_ENDPOINT_AUTH_METHOD: "client_secret_post",+ });+ expect(callback.headers.get("location")).toBe("/");+ const [request] = tokenRequests;+ expect(request.headers.get("authorization")).toBeNull();+ const form = new URLSearchParams(await request.text());+ expect(form.get("client_id")).toBe("karakeep");+ expect(form.get("client_secret")).toBe("a+b/c=%41 d");+ });+});diff --git a/apps/web/server/auth.ts b/apps/web/server/auth.tsindex 7d6aa1a0..a19197de 100644--- a/apps/web/server/auth.ts+++ b/apps/web/server/auth.ts@@ -1,15 +1,16 @@-import { Adapter, AdapterUser } from "@auth/core/adapters";-import { DrizzleAdapter } from "@auth/drizzle-adapter";-import { count, eq } from "drizzle-orm";-import NextAuth, {- DefaultSession,- getServerSession,- NextAuthOptions,-} from "next-auth";-import { Adapter as NextAuthAdapater } from "next-auth/adapters";-import CredentialsProvider from "next-auth/providers/credentials";-import { Provider } from "next-auth/providers/index";+import { cache } from "react";+import { TURNSTILE_TOKEN_HEADER } from "@/lib/auth/constants";+import { createId } from "@paralleldrive/cuid2";+import { count } from "drizzle-orm";+import { headers } from "next/headers";import requestIp from "request-ip";+import { z } from "zod";++import { betterAuth } from "better-auth";+import { drizzleAdapter } from "better-auth/adapters/drizzle";+import { APIError, createAuthMiddleware, isAPIError } from "better-auth/api";+import { genericOAuth } from "better-auth/plugins";+import type { GenericOAuthConfig } from "better-auth/plugins";import { db } from "@karakeep/db";import {@@ -19,297 +20,608 @@ import {verificationTokens,} from "@karakeep/db/schema";import serverConfig from "@karakeep/shared/config";+import type { RateLimitConfig } from "@karakeep/shared/ratelimiting";import { getRateLimitClient } from "@karakeep/shared/ratelimiting";import { getReadOnlyModeError } from "@karakeep/shared/readOnlyMode";+import {+ PASSWORD_MAX_LENGTH,+ PASSWORD_MIN_LENGTH,+ zUserNameSchema,+} from "@karakeep/shared/types/users";+import { validateRedirectUrl } from "@karakeep/shared/utils/redirectUrl";import {containsUnsafeUserNameMarkup,normalizeUserNameInput,} from "@karakeep/shared/utils/userName";import { logEvent } from "@karakeep/shared-server";-import { validatePassword } from "@karakeep/trpc/auth";-import { User } from "@karakeep/trpc/models/users";+import {+ hashPassword,+ hasPassword,+ verifyPasswordHash,+} from "@karakeep/trpc/auth";+import {+ sendPasswordResetEmail,+ sendVerificationEmail,+} from "@karakeep/trpc/email";+import { verifyTurnstileToken } from "@karakeep/trpc/lib/turnstile";-type UserRole = "admin" | "user";+const CUSTOM_OAUTH_PROVIDER_ID = "custom";+const DEFAULT_DISPLAY_NAME = "User";-declare module "next-auth/jwt" {- export interface JWT {- user: {- id: string;- role: UserRole;- } & DefaultSession["user"];- }-}+// The better-auth endpoints Karakeep uses. Everything else (update-user,+// delete-user, account linking, session listing, ...) is rejected, because+// those endpoints bypass Karakeep's own validation and read-only checks.+const ALLOWED_PATHS = new Set([+ "/ok",+ "/error",+ "/get-session",+ "/sign-in/email",+ "/sign-up/email",+ "/sign-out",+ "/send-verification-email",+ "/verify-email",+ "/request-password-reset",+ "/reset-password",+ "/change-password",+ "/sign-in/oauth2",+ "/oauth2/callback/:providerId",+]);-declare module "next-auth" {- /**- * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context- */- export interface Session {- user: {- id: string;- role: UserRole;- } & DefaultSession["user"];- }+const PASSWORD_PATHS = new Set([+ "/sign-in/email",+ "/sign-up/email",+ "/request-password-reset",+ "/reset-password",+ "/change-password",+]);- export interface DefaultUser {- role: UserRole | null;- }+// Paths that only read from the database. They're the only ones that work in+// degraded mode, where the database is opened read-only.+const READ_ONLY_PATHS = new Set(["/ok", "/error", "/get-session"]);++// Paths that create or destroy sessions. They stay available in demo mode,+// which blocks all other writes.+const SESSION_PATHS = new Set([+ "/sign-in/email",+ "/sign-out",+ "/sign-in/oauth2",+ "/oauth2/callback/:providerId",+]);++const RATE_LIMITS: Record<string, RateLimitConfig> = {+ "/sign-in/email": {+ name: "auth.login",+ windowMs: 15 * 60 * 1000,+ maxRequests: 10,+ },+ "/sign-up/email": {+ name: "auth.signup",+ windowMs: 60 * 1000,+ maxRequests: 3,+ },+ "/send-verification-email": {+ name: "auth.sendVerificationEmail",+ windowMs: 5 * 60 * 1000,+ maxRequests: 3,+ },+ "/verify-email": {+ name: "auth.verifyEmail",+ windowMs: 5 * 60 * 1000,+ maxRequests: 10,+ },+ "/request-password-reset": {+ name: "auth.requestPasswordReset",+ windowMs: 15 * 60 * 1000,+ maxRequests: 3,+ },+ "/reset-password": {+ name: "auth.resetPassword",+ windowMs: 5 * 60 * 1000,+ maxRequests: 10,+ },+ "/change-password": {+ name: "auth.changePassword",+ windowMs: 15 * 60 * 1000,+ maxRequests: 5,+ },+};++const zSignUpBody = z.object({+ name: zUserNameSchema,+ email: z.string().email(),+ password: z.string().min(PASSWORD_MIN_LENGTH).max(PASSWORD_MAX_LENGTH),+});++const zEmailBody = z.object({ email: z.string() });++export interface AuthSession {+ user: {+ id: string;+ name: string;+ email: string;+ image?: string | null;+ role: "admin" | "user";+ };+ expires: string;+}++function normalizeSafeDisplayName(name: string | null | undefined): string {+ const normalizedName = normalizeUserNameInput(name ?? "");+ return !containsUnsafeUserNameMarkup(name ?? "") && normalizedName+ ? normalizedName+ : DEFAULT_DISPLAY_NAME;}-/**- * Returns true if the user table is empty, which indicates that this user is going to be- * the first one. This can be racy if multiple users are created at the same time, but- * that should be fine.- */async function isFirstUser(): Promise<boolean> {const [{ count: userCount }] = await db.select({ count: count() }).from(users);- return userCount == 0;+ return userCount === 0;}-/**- * Returns true if the user is an admin- */-async function isAdmin(email: string): Promise<boolean> {- const res = await db.query.users.findFirst({- columns: { role: true },- where: eq(users.email, email),- });- return res?.role == "admin";+function assertWritesAllowed() {+ const message = getReadOnlyModeError(serverConfig);+ if (message) {+ throw new APIError("FORBIDDEN", { message });+ }}-const DEFAULT_DISPLAY_NAME = "User";+// The origin of the host the request was sent to. next-auth accepted sign-ins+// from any address Karakeep was reached at, even when it didn't match+// NEXTAUTH_URL (e.g. a LAN IP), and trusting the request's own host keeps that+// working. A cross-site request can't make the browser send a Host (or a custom+// X-Forwarded-Host header) other than the server's, so this only ever matches+// same-origin requests and doesn't allow redirects to other sites.+function getRequestOrigins(request: Request | undefined): string[] {+ if (!request) {+ return [];+ }+ const host =+ request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ||+ request.headers.get("host") ||+ new URL(request.url).host;+ if (!host) {+ return [];+ }+ return [`http://${host}`, `https://${host}`];+}-function normalizeSafeDisplayName(name: string | null | undefined): string {- const normalizedName = normalizeUserNameInput(name ?? "");- return !containsUnsafeUserNameMarkup(name ?? "") && normalizedName- ? normalizedName- : DEFAULT_DISPLAY_NAME;+// "*" in AUTH_TRUSTED_ORIGINS stands for the request's own origin rather than+// any origin.+const REQUEST_ORIGIN = "*";++function getTrustedOrigins(request: Request | undefined): string[] {+ // The mobile app's deep links are allowed as callback urls (e.g. after+ // verifying an email address).+ const origins = ["karakeep://"];+ for (const origin of serverConfig.auth.trustedOrigins) {+ if (origin === REQUEST_ORIGIN) {+ origins.push(...getRequestOrigins(request));+ } else {+ origins.push(origin);+ }+ }+ return origins;}-const CustomProvider = (): Adapter => {- const adapter = DrizzleAdapter(db, {- usersTable: users,- accountsTable: accounts,- sessionsTable: sessions,- verificationTokensTable: verificationTokens,+function getClientIp(requestHeaders: Headers | undefined) {+ return requestIp.getClientIp({+ headers: requestHeaders ? Object.fromEntries(requestHeaders.entries()) : {},});+}- const assertWritesAllowed = () => {- const message = getReadOnlyModeError(serverConfig);- if (message) {- throw new Error(message);- }- };+function getRequestEmail(body: unknown) {+ const parsed = zEmailBody.safeParse(body);+ return parsed.success ? parsed.data.email.trim().toLowerCase() : undefined;+}- return {- ...adapter,- createUser: async (user: Omit<AdapterUser, "id">) => {- assertWritesAllowed();- const created = await User.createRaw(db, {- name: normalizeSafeDisplayName(user.name),- email: user.email,- emailVerified: user.emailVerified,- });+async function checkRateLimit(+ path: string,+ ip: string | null,+ email: string | undefined,+) {+ const config = RATE_LIMITS[path];+ if (!config || !serverConfig.rateLimiting.enabled || !ip) {+ return;+ }+ const client = await getRateLimitClient();+ if (!client) {+ return;+ }+ const key =+ path === "/sign-in/email" ? `login:${ip}:${email ?? ""}` : `${ip}:${path}`;+ const result = await client.checkRateLimit(config, key);+ if (!result.allowed) {+ if (path === "/sign-in/email") {logEvent({- "event.name": "user.signup",- "user.id": created.id,- "auth.provider": "oauth",+ "event.name": "user.login_failed",+ "user.email": email,+ "auth.failure_reason": "rate_limited",});- return created;- },- linkAccount: async (account) => {- assertWritesAllowed();- await adapter.linkAccount?.(account);- },- };-};+ }+ throw new APIError("TOO_MANY_REQUESTS", {+ message: `Rate limit exceeded. Try again in ${result.resetInSeconds} seconds.`,+ });+ }+}-const providers: Provider[] = [- CredentialsProvider({- // The name to display on the sign in form (e.g. "Sign in with...")- name: "Credentials",- credentials: {- email: { label: "Email", type: "email", placeholder: "Email" },- password: { label: "Password", type: "password" },- },- async authorize(credentials, req) {- if (!credentials) {- return null;- }+function rejectSignUp(reason: string, message: string): never {+ logEvent({+ "event.name": "user.signup",+ "auth.provider": "credentials",+ "auth.failure_reason": reason,+ });+ throw new APIError("BAD_REQUEST", { message });+}- if (serverConfig.rateLimiting.enabled) {- const ip = requestIp.getClientIp({ headers: req?.headers ?? {} });- const client = ip ? await getRateLimitClient() : null;- if (client) {- const result = await client.checkRateLimit(- { name: "auth.login", windowMs: 15 * 60 * 1000, maxRequests: 10 },- `login:${ip}:${credentials.email.toLowerCase()}`,- );- if (!result.allowed) {- logEvent({- "event.name": "user.login_failed",- "user.email": credentials.email,- "auth.failure_reason": "rate_limited",- });- throw new Error("Too many login attempts. Please try again later.");- }- }- }+async function checkSignUp(body: unknown, requestHeaders: Headers | undefined) {+ if (serverConfig.auth.disableSignups) {+ logEvent({+ "event.name": "user.signup",+ "auth.provider": "credentials",+ "auth.failure_reason": "signups_disabled",+ });+ throw new APIError("FORBIDDEN", {+ message: "Signups are disabled in server config",+ });+ }- try {- return await validatePassword(- credentials?.email,- credentials?.password,- db,- );- } catch (e) {- logEvent({- "event.name": "user.login_failed",- "user.email": credentials?.email,- "auth.failure_reason":- e instanceof Error ? e.message : "invalid_credentials",- });- return null;- }- },- }),-];--const oauth = serverConfig.auth.oauth;-if (oauth.wellKnownUrl) {- providers.push({- id: "custom",- name: oauth.name,- type: "oauth",- wellKnown: oauth.wellKnownUrl,- authorization: { params: { scope: oauth.scope } },- clientId: oauth.clientId,- clientSecret: oauth.clientSecret,- ...(oauth.idTokenSignedResponseAlg- ? {- client: {- id_token_signed_response_alg: oauth.idTokenSignedResponseAlg,- },- }- : {}),- allowDangerousEmailAccountLinking: oauth.allowDangerousEmailAccountLinking,- checks: ["pkce", "state"],- httpOptions: {- timeout: oauth.timeout,- },- async profile(profile: Record<string, string>) {- const [admin, firstUser] = await Promise.all([- isAdmin(profile.email),- isFirstUser(),- ]);+ const parsed = zSignUpBody.safeParse(body);+ if (!parsed.success) {+ rejectSignUp(+ "invalid_input",+ parsed.error.issues[0]?.message ?? "Invalid sign up request",+ );+ }++ if (serverConfig.auth.turnstile.enabled) {+ const result = await verifyTurnstileToken(+ requestHeaders?.get(TURNSTILE_TOKEN_HEADER) ?? "",+ getClientIp(requestHeaders),+ );+ if (!result.success) {+ rejectSignUp("turnstile_failed", "Turnstile verification failed");+ }+ }+}++function checkAllowed(path: string) {+ if (!ALLOWED_PATHS.has(path)) {+ throw new APIError("NOT_FOUND");+ }++ if (serverConfig.auth.disablePasswordAuth && PASSWORD_PATHS.has(path)) {+ throw new APIError("FORBIDDEN", {+ message: "Password authentication is currently disabled",+ });+ }+ if (READ_ONLY_PATHS.has(path)) {+ return;+ }+ const readOnlyError = getReadOnlyModeError(serverConfig);+ if (+ readOnlyError &&+ (serverConfig.degradedMode || !SESSION_PATHS.has(path))+ ) {+ throw new APIError("FORBIDDEN", { message: readOnlyError });+ }+}++function logSignInFailure(path: string, body: unknown, returned: unknown) {+ if (path !== "/sign-in/email" || !isAPIError(returned)) {+ return;+ }+ const failureReason =+ returned.body?.code === "EMAIL_NOT_VERIFIED"+ ? "email_not_verified"+ : returned.statusCode === 401+ ? "invalid_credentials"+ : undefined;+ if (failureReason) {+ logEvent({+ "event.name": "user.login_failed",+ "user.email": getRequestEmail(body),+ "auth.failure_reason": failureReason,+ });+ }+}++function buildVerificationUrl(email: string, token: string, url: string) {+ const verificationUrl = new URL(`${serverConfig.publicUrl}/verify-email`);+ verificationUrl.searchParams.set("token", token);+ verificationUrl.searchParams.set("email", email);+ // better-auth puts the callbackURL the client asked for (e.g. the mobile+ // app's deep link) in its own verification url.+ const redirectUrl = validateRedirectUrl(+ new URL(url).searchParams.get("callbackURL"),+ );+ if (redirectUrl && redirectUrl !== "/") {+ verificationUrl.searchParams.set("redirectUrl", redirectUrl);+ }+ return verificationUrl.toString();+}++// RFC 6749 section 2.3.1 requires the client credentials to be form-urlencoded+// before they're put in the Basic authorization header, as next-auth did.+// better-auth puts them there as is, which breaks secrets containing characters+// like "+" or "%" on providers that decode them (e.g. Keycloak and Dex). With+// client_secret_post, the secret is sent in the (already encoded) form body.+function encodeClientSecret(+ secret: string | undefined,+ authentication: "basic" | "post",+) {+ if (secret === undefined || authentication === "post") {+ return secret;+ }+ return encodeURIComponent(secret).replace(/%20/g, "+");+}++function createOAuthConfig(): GenericOAuthConfig | null {+ const oauth = serverConfig.auth.oauth;+ if (!oauth.wellKnownUrl || !oauth.clientId) {+ return null;+ }+ const authentication =+ oauth.tokenEndpointAuthMethod === "client_secret_post" ? "post" : "basic";++ return {+ providerId: CUSTOM_OAUTH_PROVIDER_ID,+ discoveryUrl: oauth.wellKnownUrl,+ clientId: oauth.clientId,+ clientSecret: encodeClientSecret(oauth.clientSecret, authentication),+ scopes: oauth.scope.split(/\s+/).filter(Boolean),+ // Keep the callback url of the next-auth days so that existing OAuth+ // client configurations keep working. See the auth route handler.+ redirectURI: `${serverConfig.publicUrl}/api/auth/callback/${CUSTOM_OAUTH_PROVIDER_ID}`,+ pkce: true,+ authentication,+ disableSignUp: serverConfig.auth.disableSignups,+ mapProfileToUser(profile: Record<string, unknown>) {return {- id: profile.sub,- name: normalizeSafeDisplayName(profile.name),- email: profile.email,- role: admin || firstUser ? "admin" : "user",+ id: String(profile.sub ?? profile.id ?? ""),+ name: normalizeSafeDisplayName(+ typeof profile.name === "string" ? profile.name : null,+ ),+ email: typeof profile.email === "string" ? profile.email : undefined,+ image:+ typeof profile.picture === "string"+ ? profile.picture+ : typeof profile.image === "string"+ ? profile.image+ : undefined,+ emailVerified:+ profile.email_verified === true || profile.emailVerified === true,};},- });+ };}-export const authOptions: NextAuthOptions = {- // https://github.com/nextauthjs/next-auth/issues/9493- adapter: CustomProvider() as NextAuthAdapater,- providers: providers,+const oauthConfig = createOAuthConfig();++export const oauthProviders = oauthConfig+ ? [{ id: CUSTOM_OAUTH_PROVIDER_ID, name: serverConfig.auth.oauth.name }]+ : [];++export const auth = betterAuth({+ appName: "Karakeep",+ baseURL: serverConfig.publicUrl,+ secret: serverConfig.signingSecret(),+ // NEXTAUTH_URL is always trusted on top of these.+ trustedOrigins: getTrustedOrigins,+ telemetry: { enabled: false },+ advanced: {+ // Same ids as the rest of Karakeep (see the schema's $defaultFn).+ database: { generateId: () => createId() },+ // better-auth skips origin checks when it detects a test environment. Keep+ // them on so that tests exercise them too.+ disableOriginCheck: false,+ },+ // Karakeep's own rate limiter is applied in the before hook instead, so that+ // it honors the rate limiting configuration.+ rateLimit: { enabled: false },+ database: drizzleAdapter(db, {+ provider: "sqlite",+ schema: {+ user: users,+ account: accounts,+ session: sessions,+ verificationToken: verificationTokens,+ },+ }),session: {- strategy: "jwt",+ expiresIn: 30 * 24 * 60 * 60,+ updateAge: 24 * 60 * 60,+ disableSessionRefresh: serverConfig.degradedMode,+ },+ emailAndPassword: {+ enabled: !serverConfig.auth.disablePasswordAuth,+ disableSignUp:+ serverConfig.auth.disableSignups || serverConfig.auth.disablePasswordAuth,+ requireEmailVerification: serverConfig.auth.emailVerificationRequired,+ minPasswordLength: PASSWORD_MIN_LENGTH,+ maxPasswordLength: PASSWORD_MAX_LENGTH,+ revokeSessionsOnPasswordReset: true,+ resetPasswordTokenExpiresIn: 60 * 60,+ password: {+ hash: hashPassword,+ verify: ({ hash, password }) => verifyPasswordHash(hash, password),+ },+ sendResetPassword: serverConfig.email.smtp+ ? async ({ user, token }) => {+ // Users that only sign in with OAuth don't have a password to reset.+ if (!(await hasPassword(db, user.id))) {+ return;+ }+ const resetUrl = `${serverConfig.publicUrl}/reset-password?token=${encodeURIComponent(token)}`;+ // Deliberately not awaited. Delivery latency is only incurred for+ // real accounts, so awaiting it would make the endpoint a timing+ // oracle for which emails are registered.+ void sendPasswordResetEmail(user.email, user.name, resetUrl).catch(+ (error) => {+ console.error("Failed to send password reset email:", error);+ },+ );+ }+ : undefined,+ },+ emailVerification: {+ sendOnSignUp: serverConfig.auth.emailVerificationRequired,+ expiresIn: 24 * 60 * 60,+ sendVerificationEmail: serverConfig.email.smtp+ ? async ({ user, url, token }) => {+ void sendVerificationEmail(+ user.email,+ user.name,+ buildVerificationUrl(user.email, token, url),+ ).catch((error) => {+ console.error("Failed to send verification email:", error);+ });+ }+ : undefined,},- pages: {- signIn: "/signin",- signOut: "/signin",- error: "/signin",- newUser: "/signin",+ user: {+ additionalFields: {+ role: {+ type: ["admin", "user"],+ input: false,+ defaultValue: "user",+ },+ bookmarkQuota: {+ type: "number",+ required: false,+ input: false,+ returned: false,+ },+ storageQuota: {+ type: "number",+ required: false,+ input: false,+ returned: false,+ },+ },},- callbacks: {- async signIn({ user: credUser, credentials, profile }) {- const email = credUser.email || profile?.email;- if (!email) {- throw new Error("Provider didn't provide an email during signin");- }- const user = await db.query.users.findFirst({- columns: { id: true, emailVerified: true },- where: eq(users.email, email),- });-- if (credentials) {- if (!user) {+ account: {+ // Mirrors next-auth's allowDangerousEmailAccountLinking: an OAuth login is+ // only linked to an existing user with the same email when explicitly+ // allowed, and in that case regardless of email verification status.+ accountLinking: {+ enabled: true,+ disableImplicitLinking:+ !serverConfig.auth.oauth.allowDangerousEmailAccountLinking,+ requireLocalEmailVerified: false,+ trustedProviders: serverConfig.auth.oauth+ .allowDangerousEmailAccountLinking+ ? [CUSTOM_OAUTH_PROVIDER_ID]+ : [],+ },+ },+ verification: { modelName: "verificationToken" },+ databaseHooks: {+ user: {+ create: {+ before: async (user) => {+ assertWritesAllowed();+ return {+ data: {+ ...user,+ name: normalizeSafeDisplayName(user.name),+ role: (await isFirstUser()) ? "admin" : "user",+ bookmarkQuota: serverConfig.quotas.free.bookmarkLimit,+ storageQuota: serverConfig.quotas.free.assetSizeBytes,+ },+ };+ },+ after: async (user, context) => {logEvent({- "event.name": "user.login_failed",- "user.email": email,- "auth.failure_reason": "invalid_credentials",+ "event.name": "user.signup",+ "user.id": user.id,+ "auth.provider":+ context?.path === "/sign-up/email" ? "credentials" : "oauth",});- throw new Error("Invalid credentials");- }- if (- serverConfig.auth.emailVerificationRequired &&- !user.emailVerified- ) {+ },+ },+ },+ account: {+ create: {+ before: async () => {+ assertWritesAllowed();+ },+ },+ },+ session: {+ create: {+ after: async (session, context) => {logEvent({- "event.name": "user.login_failed",- "user.email": email,- "auth.failure_reason": "email_not_verified",+ "event.name": "user.login",+ "user.id": session.userId,+ "auth.provider": context?.path.startsWith("/oauth2/")+ ? "oauth"+ : "credentials",});- throw new Error("Please verify your email address before signing in");- }- logEvent({- "event.name": "user.login",- "user.id": user.id,- "auth.provider": "credentials",- });- return true;+ },+ },+ },+ },+ hooks: {+ before: createAuthMiddleware(async (ctx) => {+ checkAllowed(ctx.path);+ await checkRateLimit(+ ctx.path,+ getClientIp(ctx.headers),+ getRequestEmail(ctx.body),+ );+ if (ctx.path === "/sign-up/email") {+ await checkSignUp(ctx.body, ctx.headers);}-- // If it's a new user and signups are disabled, fail the sign in- if (!user && serverConfig.auth.disableSignups) {- logEvent({- "event.name": "user.signup",- "auth.provider": "oauth",- "auth.failure_reason": "signups_disabled",- });- throw new Error("Signups are disabled in server config");+ }),+ after: createAuthMiddleware(async (ctx) => {+ const returned = ctx.context.returned;+ logSignInFailure(ctx.path, ctx.body, returned);+ if (ctx.path === "/change-password" && !isAPIError(returned)) {+ logEvent({ "event.name": "user.password_change" });}+ }),+ },+ onAPIError: {+ errorURL: "/signin",+ },+ plugins: oauthConfig ? [genericOAuth({ config: [oauthConfig] })] : [],+});- // TODO: We're blindly trusting oauth providers to validate emails- // As such, oauth users can sign in even if email verification is enabled.- // We might want to change this in the future.-- if (user) {- logEvent({- "event.name": "user.login",- "user.id": user.id,- "auth.provider": "oauth",- });- }+async function fetchServerAuthSession(): Promise<AuthSession | null> {+ let session;+ try {+ session = await auth.api.getSession({+ headers: await headers(),+ // Server components can't set cookies, so refreshing the session here+ // would extend it in the database without extending the cookie. The+ // client side session fetch refreshes it instead.+ query: { disableRefresh: true },+ });+ } catch (e) {+ // In degraded mode the database is read-only, and better-auth can still+ // try to clean up expired sessions. Treat that as being logged out.+ if (serverConfig.degradedMode) {+ return null;+ }+ throw e;+ }+ if (!session) {+ return null;+ }- return true;- },- async jwt({ token, user }) {- if (user) {- token.user = {- id: user.id,- name: user.name,- email: user.email,- image: user.image,- role: user.role ?? "user",- };- }- return token;- },- async session({ session, token }) {- session.user = { ...token.user };- return session;+ return {+ user: {+ id: session.user.id,+ name: session.user.name,+ email: session.user.email,+ image: session.user.image,+ role: session.user.role === "admin" ? "admin" : "user",},- },-};--export const authHandler = NextAuth(authOptions);+ expires: session.session.expiresAt.toISOString(),+ };+}-export const getServerAuthSession = () => getServerSession(authOptions);+// Deduplicated per request: many server components need the session.+export const getServerAuthSession = cache(fetchServerAuthSession);diff --git a/docs/docs/03-configuration/01-environment-variables.md b/docs/docs/03-configuration/01-environment-variables.mdindex c0e332ba..100b84d5 100644--- a/docs/docs/03-configuration/01-environment-variables.md+++ b/docs/docs/03-configuration/01-environment-variables.md@@ -12,8 +12,9 @@ The app is mainly configured by environment variables. All the used environment| LOG_LEVEL | No | debug | The application log level as defined in the [winston documentation](https://github.com/winstonjs/winston?tab=readme-ov-file#logging-levels). You may want to set this to `notice` or `warning` when running Karakeep in a production environment. || DATA_DIR | Yes | Not set | The path for the persistent data directory. This is where the db lives. Assets are stored here by default unless `ASSETS_DIR` is set. || ASSETS_DIR | No | Not set | The path where crawled assets will be stored. If not set, defaults to `${DATA_DIR}/assets`. |-| NEXTAUTH_URL | Yes | Not set | Should point to the address of your server. The app will function without it, but will redirect you to wrong addresses on signout for example. |-| NEXTAUTH_SECRET | Yes | Not set | Random string used to sign the JWT tokens. Generate one with `openssl rand -base64 36`. |+| NEXTAUTH_URL | Yes | Not set | The address of your server (e.g. `https://karakeep.example.com`). It's used to build the links in emails and the OAuth callback URL, and an `https` address makes authentication cookies secure-only. Sign-ins from other addresses are controlled by `AUTH_TRUSTED_ORIGINS`. |+| NEXTAUTH_SECRET | Yes | Not set | Random string used to secure authentication cookies and tokens. Generate one with `openssl rand -base64 36`. |+| AUTH_TRUSTED_ORIGINS | No | * | Comma-separated list of origins (e.g. `https://karakeep.example.com`) allowed to sign in and to be redirected to after authentication, on top of `NEXTAUTH_URL`. `*` stands for whatever address the request was sent to, so that Karakeep keeps working when it's reached at an address other than `NEXTAUTH_URL` (e.g. a LAN IP). It doesn't allow other sites. Set it to an empty string to only allow `NEXTAUTH_URL`. || MEILI_ADDR | No | Not set | The address of meilisearch. If not set, Search will be disabled. E.g. (`http://meilisearch:7700`) || MEILI_MASTER_KEY | Only in Prod and if search is enabled | Not set | The master key configured for meilisearch. Not needed in development environment. Generate one with `openssl rand -base64 36 \| tr -dc 'A-Za-z0-9'` || MAX_ASSET_SIZE_MB | No | 50 | Sets the maximum allowed asset size (in MB) to be uploaded |@@ -74,13 +75,12 @@ When setting up OAuth, the allowed redirect URLs configured at the provider shou| OAUTH_WELLKNOWN_URL | No | Not set | The "wellknown Url" for openid-configuration as provided by the OAuth provider || OAUTH_CLIENT_SECRET | No | Not set | The "Client Secret" as provided by the OAuth provider || OAUTH_CLIENT_ID | No | Not set | The "Client ID" as provided by the OAuth provider |-| OAUTH_ID_TOKEN_SIGNED_RESPONSE_ALG | No | Not set | The expected JWS signing algorithm for OIDC ID tokens. Set this when your provider signs ID tokens with an algorithm other than the default. If unset, Karakeep leaves the algorithm unspecified and the underlying OIDC client uses its default behavior, which is typically RS256. If this does not match the provider's ID token algorithm, OAuth login can fail during callback with an unexpected JWT algorithm error. Supported values: `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384`, `ES512`, `EdDSA`. || OAUTH_SCOPE | No | "openid email profile" | "Full list of scopes to request (space delimited)" |+| OAUTH_TOKEN_ENDPOINT_AUTH_METHOD | No | client_secret_basic | How Karakeep authenticates to the provider's token endpoint. Either `client_secret_basic` or `client_secret_post`. Set it to `client_secret_post` if your provider doesn't support `client_secret_basic`. || OAUTH_PROVIDER_NAME | No | "Custom Provider" | The name of your provider. Will be shown on the signup page as "Sign in with `<name>`" || OAUTH_ALLOW_DANGEROUS_EMAIL_ACCOUNT_LINKING | No | false | Whether existing accounts in karakeep stored in the database should automatically be linked with your OAuth account. Only enable it if you trust the OAuth provider! |-| OAUTH_TIMEOUT | No | 3500 | The wait time in milliseconds for the OAuth provider response. Increase this if you are having `outgoing request timed out` errors |-For more information on `OAUTH_ALLOW_DANGEROUS_EMAIL_ACCOUNT_LINKING`, check the [next-auth.js documentation](https://next-auth.js.org/configuration/providers/oauth#allowdangerousemailaccountlinking-option).+For more information on `OAUTH_ALLOW_DANGEROUS_EMAIL_ACCOUNT_LINKING`, check the [Better Auth account-linking documentation](https://www.better-auth.com/docs/concepts/users-accounts#account-linking).## Inference Configs (For automatic tagging)diff --git a/docs/docs/08-development/01-setup.md b/docs/docs/08-development/01-setup.mdindex 52d964e7..f2823cb7 100644--- a/docs/docs/08-development/01-setup.md+++ b/docs/docs/08-development/01-setup.md@@ -88,7 +88,7 @@ You can now continue with the rest of this documentation.- Start by copying the template by `cp .env.sample .env`.- The most important env variables to set are:- `DATA_DIR`: Where the database and assets will be stored. This is the only required env variable. You can use an absolute path so that all apps point to the same dir.- - `NEXTAUTH_SECRET`: Random string used to sign the JWT tokens. Generate one with `openssl rand -base64 36`. Logging in will not work if this is missing!+ - `NEXTAUTH_SECRET`: Random string used to secure authentication cookies and tokens. Generate one with `openssl rand -base64 36`. Logging in will not work if this is missing!- `MEILI_ADDR`: If not set, search will be disabled. You can set it to `http://127.0.0.1:7700` if you run meilisearch using the command below.- `OPENAI_API_KEY`: If you want to enable auto tag inference in the dev env.- run `pnpm run db:migrate` in the root of the repo to set up the database.diff --git a/packages/benchmarks/src/seed.ts b/packages/benchmarks/src/seed.tsindex dfb14347..f17d238e 100644--- a/packages/benchmarks/src/seed.ts+++ b/packages/benchmarks/src/seed.ts@@ -5,7 +5,7 @@ import type { ZTagBasic } from "@karakeep/shared/types/tags";import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";import { logInfo, logStep, logSuccess } from "./log";-import { getTrpcClient, TrpcClient } from "./trpc";+import { getTrpcClient, signUpUser, TrpcClient } from "./trpc";import { waitUntil } from "./utils";export interface SeedConfig {@@ -66,11 +66,10 @@ async function seedUserData(const password = "benchmarks1234";logStep(`Creating user ${userIndex + 1}/${config.userCount}`);- await authlessClient.users.create.mutate({+ await signUpUser({name: `Benchmark User ${userIndex + 1}`,email,password,- confirmPassword: password,});const { key } = await authlessClient.apiKeys.exchange.mutate({email,diff --git a/packages/benchmarks/src/trpc.ts b/packages/benchmarks/src/trpc.tsindex 3a8cfe37..776637ae 100644--- a/packages/benchmarks/src/trpc.ts+++ b/packages/benchmarks/src/trpc.ts@@ -24,3 +24,27 @@ export function getTrpcClient(apiKey?: string) {],});}++// Signs up through better-auth's endpoint, the same way the web app does.+export async function signUpUser(input: {+ name: string;+ email: string;+ password: string;+}) {+ const baseUrl = `http://localhost:${process.env.KARAKEEP_PORT}`;+ const response = await fetch(`${baseUrl}/api/auth/sign-up/email`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ // Node's fetch sends Sec-Fetch-* headers but no Origin, which+ // better-auth's CSRF protection rejects. Browsers always send it.+ Origin: baseUrl,+ },+ body: JSON.stringify(input),+ });+ if (!response.ok) {+ throw new Error(+ `Failed to sign up ${input.email}: ${response.status} ${await response.text()}`,+ );+ }+}diff --git a/packages/db/drizzle/0094_migrate_to_better_auth.sql b/packages/db/drizzle/0094_migrate_to_better_auth.sqlnew file mode 100644index 00000000..6edaf76d--- /dev/null+++ b/packages/db/drizzle/0094_migrate_to_better_auth.sql@@ -0,0 +1,123 @@+CREATE TABLE `__new_account` (+ `id` text PRIMARY KEY NOT NULL,+ `accountId` text NOT NULL,+ `providerId` text NOT NULL,+ `userId` text NOT NULL,+ `accessToken` text,+ `refreshToken` text,+ `idToken` text,+ `accessTokenExpiresAt` integer,+ `refreshTokenExpiresAt` integer,+ `scope` text,+ `password` text,+ `createdAt` integer NOT NULL,+ `updatedAt` integer NOT NULL,+ FOREIGN KEY (`userId`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+-- Foreign keys weren't enforced on older installs, so accounts of users that+-- were deleted back then can still be around. They'd fail the foreign key+-- check of the new table and abort the whole migration.+INSERT INTO `__new_account` (+ `id`,+ `accountId`,+ `providerId`,+ `userId`,+ `accessToken`,+ `refreshToken`,+ `idToken`,+ `accessTokenExpiresAt`,+ `scope`,+ `createdAt`,+ `updatedAt`+)+SELECT+ 'legacy-oauth:' || `provider` || ':' || `providerAccountId`,+ `providerAccountId`,+ `provider`,+ `userId`,+ `access_token`,+ `refresh_token`,+ `id_token`,+ CASE WHEN `expires_at` IS NULL THEN NULL ELSE `expires_at` * 1000 END,+ `scope`,+ unixepoch() * 1000,+ unixepoch() * 1000+FROM `account`+WHERE `userId` IN (SELECT `id` FROM `user`);--> statement-breakpoint+-- Passwords move to better-auth's credential accounts. Legacy hashes are+-- bcrypt(password + salt), so the salt is kept alongside the hash.+INSERT INTO `__new_account` (+ `id`,+ `accountId`,+ `providerId`,+ `userId`,+ `password`,+ `createdAt`,+ `updatedAt`+)+SELECT+ 'legacy-credential:' || `id`,+ `id`,+ 'credential',+ `id`,+ CASE+ WHEN `salt` = '' THEN `password`+ ELSE 'bcrypt-salted:' || `salt` || ':' || `password`+ END,+ unixepoch() * 1000,+ unixepoch() * 1000+FROM `user`+WHERE `password` IS NOT NULL;--> statement-breakpoint+DROP TABLE `account`;--> statement-breakpoint+ALTER TABLE `__new_account` RENAME TO `account`;--> statement-breakpoint+CREATE INDEX `accounts_userId_idx` ON `account` (`userId`);--> statement-breakpoint+CREATE UNIQUE INDEX `accounts_providerId_accountId_unique` ON `account` (`providerId`,`accountId`);--> statement-breakpoint+DROP TABLE `verificationToken`;--> statement-breakpoint+CREATE TABLE `verificationToken` (+ `id` text PRIMARY KEY NOT NULL,+ `identifier` text NOT NULL,+ `value` text NOT NULL,+ `expiresAt` integer NOT NULL,+ `createdAt` integer NOT NULL,+ `updatedAt` integer NOT NULL+);+--> statement-breakpoint+CREATE INDEX `verificationTokens_identifier_idx` ON `verificationToken` (`identifier`);--> statement-breakpoint+CREATE UNIQUE INDEX `verificationTokens_identifier_value_unique` ON `verificationToken` (`identifier`,`value`);--> statement-breakpoint+DROP TABLE `session`;--> statement-breakpoint+CREATE TABLE `session` (+ `id` text PRIMARY KEY NOT NULL,+ `token` text NOT NULL,+ `userId` text NOT NULL,+ `expiresAt` integer NOT NULL,+ `ipAddress` text,+ `userAgent` text,+ `createdAt` integer NOT NULL,+ `updatedAt` integer NOT NULL,+ FOREIGN KEY (`userId`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `session_token_unique` ON `session` (`token`);--> statement-breakpoint+CREATE INDEX `sessions_userId_idx` ON `session` (`userId`);--> statement-breakpoint+DROP TABLE `passwordResetToken`;--> statement-breakpoint+ALTER TABLE `user` ADD `createdAt` integer;--> statement-breakpoint+ALTER TABLE `user` ADD `updatedAt` integer;--> statement-breakpoint+-- emailVerified changes from a timestamp to a boolean.+UPDATE `user`+SET+ `emailVerified` = (`emailVerified` IS NOT NULL),+ `createdAt` = unixepoch() * 1000,+ `updatedAt` = unixepoch() * 1000;--> statement-breakpoint+-- better-auth looks users up by lowercased email. Emails that would collide+-- with another user once lowercased are left untouched.+UPDATE `user`+SET `email` = lower(`email`)+WHERE `email` != lower(`email`)+ AND NOT EXISTS (+ SELECT 1 FROM `user` AS `other`+ WHERE lower(`other`.`email`) = lower(`user`.`email`)+ AND `other`.`id` != `user`.`id`+ );--> statement-breakpoint+ALTER TABLE `user` DROP COLUMN `password`;--> statement-breakpoint+ALTER TABLE `user` DROP COLUMN `salt`;diff --git a/packages/db/drizzle/meta/0094_snapshot.json b/packages/db/drizzle/meta/0094_snapshot.jsonnew file mode 100644index 00000000..4b3d7f8e--- /dev/null+++ b/packages/db/drizzle/meta/0094_snapshot.json@@ -0,0 +1,3617 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "09931183-1ed7-40d8-ad30-3b30edf74266",+ "prevId": "21170083-5dab-4bbf-803f-406ea6baeb30",+ "tables": {+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "accountId": {+ "name": "accountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerId": {+ "name": "providerId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "accessToken": {+ "name": "accessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refreshToken": {+ "name": "refreshToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "idToken": {+ "name": "idToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accessTokenExpiresAt": {+ "name": "accessTokenExpiresAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refreshTokenExpiresAt": {+ "name": "refreshTokenExpiresAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "accounts_userId_idx": {+ "name": "accounts_userId_idx",+ "columns": [+ "userId"+ ],+ "isUnique": false+ },+ "accounts_providerId_accountId_unique": {+ "name": "accounts_providerId_accountId_unique",+ "columns": [+ "providerId",+ "accountId"+ ],+ "isUnique": true+ }+ },+ "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": {},+ "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+ },+ "readerViewStatus": {+ "name": "readerViewStatus",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "readerViewScore": {+ "name": "readerViewScore",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "readerViewReasons": {+ "name": "readerViewReasons",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "readerViewClassifierVersion": {+ "name": "readerViewClassifierVersion",+ "type": "integer",+ "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+ },+ "probeMetadataAt": {+ "name": "probeMetadataAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "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_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+ },+ "lastSavedAt": {+ "name": "lastSavedAt",+ "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'"+ },+ "embeddingStatus": {+ "name": "embeddingStatus",+ "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_lastSavedAt_idx": {+ "name": "bookmarks_lastSavedAt_idx",+ "columns": [+ "lastSavedAt"+ ],+ "isUnique": false+ },+ "bookmarks_userId_lastSavedAt_id_idx": {+ "name": "bookmarks_userId_lastSavedAt_id_idx",+ "columns": [+ "userId",+ "lastSavedAt",+ "id"+ ],+ "isUnique": false+ },+ "bookmarks_userId_archived_lastSavedAt_id_idx": {+ "name": "bookmarks_userId_archived_lastSavedAt_id_idx",+ "columns": [+ "userId",+ "archived",+ "lastSavedAt",+ "id"+ ],+ "isUnique": false+ },+ "bookmarks_userId_favourited_lastSavedAt_id_idx": {+ "name": "bookmarks_userId_favourited_lastSavedAt_id_idx",+ "columns": [+ "userId",+ "favourited",+ "lastSavedAt",+ "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_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": {}+ },+ "chatMessages": {+ "name": "chatMessages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "chatId": {+ "name": "chatId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "chatMessages_chatId_idx": {+ "name": "chatMessages_chatId_idx",+ "columns": [+ "chatId"+ ],+ "isUnique": false+ },+ "chatMessages_chatId_createdAt_idx": {+ "name": "chatMessages_chatId_createdAt_idx",+ "columns": [+ "chatId",+ "createdAt"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "chatMessages_chatId_chatSessions_id_fk": {+ "name": "chatMessages_chatId_chatSessions_id_fk",+ "tableFrom": "chatMessages",+ "tableTo": "chatSessions",+ "columnsFrom": [+ "chatId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "chatSessions": {+ "name": "chatSessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "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+ }+ },+ "indexes": {+ "chatSessions_userId_idx": {+ "name": "chatSessions_userId_idx",+ "columns": [+ "userId"+ ],+ "isUnique": false+ },+ "chatSessions_userId_modifiedAt_idx": {+ "name": "chatSessions_userId_modifiedAt_idx",+ "columns": [+ "userId",+ "modifiedAt"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "chatSessions_userId_user_id_fk": {+ "name": "chatSessions_userId_user_id_fk",+ "tableFrom": "chatSessions",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "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_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+ },+ "completedAt": {+ "name": "completedAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "totalBookmarks": {+ "name": "totalBookmarks",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "completedBookmarks": {+ "name": "completedBookmarks",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "failedBookmarks": {+ "name": "failedBookmarks",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "pendingBookmarks": {+ "name": "pendingBookmarks",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "processingBookmarks": {+ "name": "processingBookmarks",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "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+ },+ "importSessions_status_completedAt_idx": {+ "name": "importSessions_status_completedAt_idx",+ "columns": [+ "status",+ "completedAt"+ ],+ "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_resultBookmarkId_idx": {+ "name": "importStaging_resultBookmarkId_idx",+ "columns": [+ "resultBookmarkId"+ ],+ "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": {}+ },+ "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_bookmarkId_idx": {+ "name": "rssFeedImports_bookmarkId_idx",+ "columns": [+ "bookmarkId"+ ],+ "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+ },+ "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"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ipAddress": {+ "name": "ipAddress",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "userAgent": {+ "name": "userAgent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "sessions_userId_idx": {+ "name": "sessions_userId_idx",+ "columns": [+ "userId"+ ],+ "isUnique": false+ }+ },+ "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_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+ },+ "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+ },+ "manualTierName": {+ "name": "manualTierName",+ "type": "text",+ "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+ },+ "createdAt": {+ "name": "createdAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "integer",+ "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": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "verificationTokens_identifier_idx": {+ "name": "verificationTokens_identifier_idx",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ },+ "verificationTokens_identifier_value_unique": {+ "name": "verificationTokens_identifier_value_unique",+ "columns": [+ "identifier",+ "value"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "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": {+ "\"account\".\"providerAccountId\"": "\"account\".\"accountId\"",+ "\"account\".\"provider\"": "\"account\".\"providerId\"",+ "\"account\".\"access_token\"": "\"account\".\"accessToken\"",+ "\"account\".\"refresh_token\"": "\"account\".\"refreshToken\"",+ "\"account\".\"id_token\"": "\"account\".\"idToken\"",+ "\"account\".\"expires_at\"": "\"account\".\"accessTokenExpiresAt\"",+ "\"verificationToken\".\"token\"": "\"verificationToken\".\"value\"",+ "\"verificationToken\".\"expires\"": "\"verificationToken\".\"expiresAt\""+ }+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex af46eb98..655b876a 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -659,6 +659,13 @@"when": 1785586065846,"tag": "0093_reader_view_assessment","breakpoints": true+ },+ {+ "idx": 94,+ "version": "6",+ "when": 1785711744217,+ "tag": "0094_migrate_to_better_auth",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/package.json b/packages/db/package.jsonindex dcd2ac94..2d60848e 100644--- a/packages/db/package.json+++ b/packages/db/package.json@@ -16,7 +16,6 @@"lint:fix": "oxlint --ignore-path=../../.gitignore . --fix"},"dependencies": {- "@auth/core": "^0.41.3","@karakeep/shared": "workspace:*","@opentelemetry/api": "^1.9.0","@paralleldrive/cuid2": "^2.2.2",diff --git a/packages/db/schema.ts b/packages/db/schema.tsindex 9a304e1f..a523fcdd 100644--- a/packages/db/schema.ts+++ b/packages/db/schema.ts@@ -1,4 +1,3 @@-import type { AdapterAccount } from "@auth/core/adapters";import { createId } from "@paralleldrive/cuid2";import { relations, sql, SQL } from "drizzle-orm";import {@@ -49,11 +48,19 @@ export const users = sqliteTable("user", {.$defaultFn(() => createId()),name: text("name").notNull(),email: text("email").notNull().unique(),- emailVerified: integer("emailVerified", { mode: "timestamp_ms" }),+ // Nullable and without a SQL default because SQLite can't add those+ // constraints to an existing column without rebuilding the user table.+ emailVerified: integer("emailVerified", { mode: "boolean" }).$defaultFn(+ () => false,+ ),image: text("image"),- password: text("password"),- salt: text("salt").notNull().default(""),role: text("role", { enum: ["admin", "user"] }).default("user"),+ createdAt: integer("createdAt", { mode: "timestamp_ms" }).$defaultFn(+ () => new Date(),+ ),+ updatedAt: integer("updatedAt", { mode: "timestamp_ms" })+ .$defaultFn(() => new Date())+ .$onUpdate(() => new Date()),// Admin Only SettingsbookmarkQuota: integer("bookmarkQuota"),@@ -120,63 +127,87 @@ export const users = sqliteTable("user", {export const accounts = sqliteTable("account",{+ id: text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => createId()),+ accountId: text("accountId").notNull(),+ providerId: text("providerId").notNull(),userId: text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),- type: text("type").$type<AdapterAccount["type"]>().notNull(),- provider: text("provider").notNull(),- providerAccountId: text("providerAccountId").notNull(),- refresh_token: text("refresh_token"),- access_token: text("access_token"),- expires_at: integer("expires_at"),- token_type: text("token_type"),+ accessToken: text("accessToken"),+ refreshToken: text("refreshToken"),+ idToken: text("idToken"),+ accessTokenExpiresAt: integer("accessTokenExpiresAt", {+ mode: "timestamp_ms",+ }),+ refreshTokenExpiresAt: integer("refreshTokenExpiresAt", {+ mode: "timestamp_ms",+ }),scope: text("scope"),- id_token: text("id_token"),- session_state: text("session_state"),+ password: text("password"),+ createdAt: createdAtMsField(),+ updatedAt: integer("updatedAt", { mode: "timestamp_ms" })+ .notNull()+ .$defaultFn(() => new Date())+ .$onUpdate(() => new Date()),},(account) => [- primaryKey({- columns: [account.provider, account.providerAccountId],- }),+ unique("accounts_providerId_accountId_unique").on(+ account.providerId,+ account.accountId,+ ),+ index("accounts_userId_idx").on(account.userId),],);-export const sessions = sqliteTable("session", {- sessionToken: text("sessionToken")- .notNull()- .primaryKey()- .$defaultFn(() => createId()),- userId: text("userId")- .notNull()- .references(() => users.id, { onDelete: "cascade" }),- expires: integer("expires", { mode: "timestamp_ms" }).notNull(),-});--export const verificationTokens = sqliteTable(- "verificationToken",+export const sessions = sqliteTable(+ "session",{- identifier: text("identifier").notNull(),- token: text("token").notNull(),- expires: integer("expires", { mode: "timestamp_ms" }).notNull(),+ id: text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => createId()),+ token: text("token").notNull().unique(),+ userId: text("userId")+ .notNull()+ .references(() => users.id, { onDelete: "cascade" }),+ expiresAt: integer("expiresAt", { mode: "timestamp_ms" }).notNull(),+ ipAddress: text("ipAddress"),+ userAgent: text("userAgent"),+ createdAt: createdAtMsField(),+ updatedAt: integer("updatedAt", { mode: "timestamp_ms" })+ .notNull()+ .$defaultFn(() => new Date())+ .$onUpdate(() => new Date()),},- (vt) => [primaryKey({ columns: [vt.identifier, vt.token] })],+ (session) => [index("sessions_userId_idx").on(session.userId)],);-export const passwordResetTokens = sqliteTable(- "passwordResetToken",+export const verificationTokens = sqliteTable(+ "verificationToken",{id: text("id").notNull().primaryKey().$defaultFn(() => createId()),- userId: text("userId")+ identifier: text("identifier").notNull(),+ value: text("value").notNull(),+ expiresAt: integer("expiresAt", { mode: "timestamp_ms" }).notNull(),+ createdAt: createdAtMsField(),+ updatedAt: integer("updatedAt", { mode: "timestamp_ms" }).notNull()- .references(() => users.id, { onDelete: "cascade" }),- token: text("token").notNull().unique(),- expires: integer("expires", { mode: "timestamp_ms" }).notNull(),- createdAt: createdAtField(),+ .$defaultFn(() => new Date())+ .$onUpdate(() => new Date()),},- (prt) => [index("passwordResetTokens_userId_idx").on(prt.userId)],+ (verification) => [+ unique("verificationTokens_identifier_value_unique").on(+ verification.identifier,+ verification.value,+ ),+ index("verificationTokens_identifier_idx").on(verification.identifier),+ ],);export const apiKeys = sqliteTable(@@ -1258,16 +1289,6 @@ export const subscriptionsRelations = relations(subscriptions, ({ one }) => ({}),}));-export const passwordResetTokensRelations = relations(- passwordResetTokens,- ({ one }) => ({- user: one(users, {- fields: [passwordResetTokens.userId],- references: [users.id],- }),- }),-);-export const chatSessionsRelations = relations(chatSessions,({ one, many }) => ({diff --git a/packages/e2e_tests/setup/seed.ts b/packages/e2e_tests/setup/seed.tsindex ed3143f6..13c859e8 100644--- a/packages/e2e_tests/setup/seed.ts+++ b/packages/e2e_tests/setup/seed.ts@@ -1,14 +1,14 @@import { TestProject } from "vitest/node";+import { signUpUser } from "../utils/api";import { getTrpcClient } from "../utils/trpc";export async function setup({ provide }: TestProject) {const trpc = getTrpcClient();- await trpc.users.create.mutate({+ await signUpUser({name: "Test User",email: "[email protected]",password: "test1234",- confirmPassword: "test1234",});const { key } = await trpc.apiKeys.exchange.mutate({diff --git a/packages/e2e_tests/utils/api.ts b/packages/e2e_tests/utils/api.tsindex a8eb9ab1..5674b484 100644--- a/packages/e2e_tests/utils/api.ts+++ b/packages/e2e_tests/utils/api.ts@@ -35,17 +35,40 @@ export async function uploadTestAsset(}>;}+// Signs up through better-auth's endpoint, the same way the web app does.+export async function signUpUser(input: {+ name: string;+ email: string;+ password: string;+}) {+ const baseUrl = `http://localhost:${process.env.KARAKEEP_PORT}`;+ const response = await fetch(`${baseUrl}/api/auth/sign-up/email`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ // Node's fetch sends Sec-Fetch-* headers but no Origin, which+ // better-auth's CSRF protection rejects. Browsers always send it.+ Origin: baseUrl,+ },+ body: JSON.stringify(input),+ });+ if (!response.ok) {+ throw new Error(+ `Failed to sign up ${input.email}: ${response.status} ${await response.text()}`,+ );+ }+}+export async function createTestUser(scopes?: ZApiKeyScope[]) {const trpc = getTrpcClient();const random = Math.random().toString(36).substring(7);const email = `testuser+${random}@example.com`;- await trpc.users.create.mutate({+ await signUpUser({name: "Test User",email,password: "test1234",- confirmPassword: "test1234",});const { key } = await trpc.apiKeys.exchange.mutate({diff --git a/packages/shared/config.ts b/packages/shared/config.tsindex d1fb2402..7e607f33 100644--- a/packages/shared/config.ts+++ b/packages/shared/config.ts@@ -16,21 +16,6 @@ const optionalStringBool = () =>.transform((s) => s === "true").optional();-// Only asymmetric algorithms are supported here because ID tokens are verified-// against the provider's JWKS. Do not add "none" or symmetric HS* algorithms.-const oauthIdTokenSignedResponseAlg = z.enum([- "RS256",- "RS384",- "RS512",- "PS256",- "PS384",- "PS512",- "ES256",- "ES384",- "ES512",- "EdDSA",-]);-const allEnv = z.object({PORT: z.coerce.number().default(3000),WORKERS_HOST: z.string().default("127.0.0.1"),@@ -60,6 +45,15 @@ const allEnv = z.object({.prefault("http://localhost:3000").transform((s) => s.replace(/\/+$/, "")),NEXTAUTH_SECRET: z.string().optional(),+ AUTH_TRUSTED_ORIGINS: z+ .string()+ .default("*")+ .transform((val) =>+ val+ .split(",")+ .map((origin) => origin.trim())+ .filter(Boolean),+ ),DISABLE_SIGNUPS: stringBool("false"),DISABLE_PASSWORD_AUTH: stringBool("false"),OAUTH_AUTO_REDIRECT: stringBool("false"),@@ -67,9 +61,10 @@ const allEnv = z.object({OAUTH_WELLKNOWN_URL: z.string().url().optional(),OAUTH_CLIENT_SECRET: z.string().optional(),OAUTH_CLIENT_ID: z.string().optional(),- OAUTH_ID_TOKEN_SIGNED_RESPONSE_ALG: oauthIdTokenSignedResponseAlg.optional(),- OAUTH_TIMEOUT: z.coerce.number().optional().default(3500),OAUTH_SCOPE: z.string().default("openid email profile"),+ OAUTH_TOKEN_ENDPOINT_AUTH_METHOD: z+ .enum(["client_secret_basic", "client_secret_post"])+ .default("client_secret_basic"),OAUTH_PROVIDER_NAME: z.string().default("Custom Provider"),TURNSTILE_SITE_KEY: z.string().optional(),TURNSTILE_SECRET_KEY: z.string().optional(),@@ -319,6 +314,7 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {disableSignups: val.DISABLE_SIGNUPS,disablePasswordAuth: val.DISABLE_PASSWORD_AUTH,emailVerificationRequired: val.EMAIL_VERIFICATION_REQUIRED,+ trustedOrigins: val.AUTH_TRUSTED_ORIGINS,oauth: {autoRedirect: val.OAUTH_AUTO_REDIRECT,allowDangerousEmailAccountLinking:@@ -326,10 +322,9 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {wellKnownUrl: val.OAUTH_WELLKNOWN_URL,clientSecret: val.OAUTH_CLIENT_SECRET,clientId: val.OAUTH_CLIENT_ID,- idTokenSignedResponseAlg: val.OAUTH_ID_TOKEN_SIGNED_RESPONSE_ALG,scope: val.OAUTH_SCOPE,+ tokenEndpointAuthMethod: val.OAUTH_TOKEN_ENDPOINT_AUTH_METHOD,name: val.OAUTH_PROVIDER_NAME,- timeout: val.OAUTH_TIMEOUT,},turnstile: {enabled: val.TURNSTILE_SITE_KEY !== undefined,diff --git a/packages/trpc/auth.test.ts b/packages/trpc/auth.test.tsnew file mode 100644index 00000000..5433a3a2--- /dev/null+++ b/packages/trpc/auth.test.ts@@ -0,0 +1,306 @@+import bcrypt from "bcryptjs";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, test } from "vitest";++import { accounts, users } from "@karakeep/db/schema";+import serverConfig from "@karakeep/shared/config";++import type { CustomTestContext } from "./testUtils";+import {+ CREDENTIAL_PROVIDER_ID,+ hashPassword,+ hasPassword,+ setUserPassword,+ validatePassword,+ verifyPasswordHash,+ verifyUserPassword,+} from "./auth";+import { createTestUser, defaultBeforeEach } from "./testUtils";++beforeEach<CustomTestContext>(defaultBeforeEach(false));++async function legacySaltedHash(password: string, salt: string) {+ return `bcrypt-salted:${salt}:${await bcrypt.hash(password + salt, 10)}`;+}++async function getCredentialAccounts(+ db: CustomTestContext["db"],+ userId: string,+) {+ return await db.select().from(accounts).where(eq(accounts.userId, userId));+}++describe("verifyPasswordHash", () => {+ test("accepts the right password for a plain bcrypt hash", async () => {+ const hash = await hashPassword("pass1234");+ expect(hash).not.toContain("pass1234");+ expect(hash.startsWith("bcrypt-salted:")).toBe(false);+ expect(await verifyPasswordHash(hash, "pass1234")).toBe(true);+ });++ test("rejects the wrong password for a plain bcrypt hash", async () => {+ const hash = await hashPassword("pass1234");+ expect(await verifyPasswordHash(hash, "wrongpass")).toBe(false);+ });++ test("accepts the right password for a legacy salted hash", async () => {+ const hash = await legacySaltedHash("pass1234", "some-salt");+ expect(await verifyPasswordHash(hash, "pass1234")).toBe(true);+ });++ test("rejects the wrong password for a legacy salted hash", async () => {+ const hash = await legacySaltedHash("pass1234", "some-salt");+ expect(await verifyPasswordHash(hash, "wrongpass")).toBe(false);+ // The salt itself must be applied, not just accepted as a prefix+ expect(await verifyPasswordHash(hash, "pass1234some-salt")).toBe(false);+ });++ test("rejects a legacy hash whose salt doesn't match", async () => {+ const hash = await bcrypt.hash("pass1234" + "real-salt", 10);+ expect(+ await verifyPasswordHash(`bcrypt-salted:other-salt:${hash}`, "pass1234"),+ ).toBe(false);+ });++ test("rejects a malformed legacy hash without a separator", async () => {+ const hash = await bcrypt.hash("pass1234", 10);+ // bcrypt hashes contain no `:`, so there's no salt/hash separator+ expect(hash).not.toContain(":");+ expect(await verifyPasswordHash(`bcrypt-salted:${hash}`, "pass1234")).toBe(+ false,+ );+ expect(await verifyPasswordHash("bcrypt-salted:", "pass1234")).toBe(false);+ });+});++describe("setUserPassword", () => {+ test<CustomTestContext>("creates a credential account", async ({ db }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ });+ expect(await getCredentialAccounts(db, user.id)).toHaveLength(0);++ await setUserPassword(db, user.id, "pass1234");++ const userAccounts = await getCredentialAccounts(db, user.id);+ expect(userAccounts).toHaveLength(1);+ expect(userAccounts[0].providerId).toBe(CREDENTIAL_PROVIDER_ID);+ expect(userAccounts[0].accountId).toBe(user.id);+ expect(userAccounts[0].password).not.toBe("pass1234");+ expect(await verifyUserPassword(db, user.id, "pass1234")).toBe(true);+ });++ test<CustomTestContext>("overwrites an existing password", async ({ db }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "oldpass123",+ });++ await setUserPassword(db, user.id, "newpass123");++ expect(await getCredentialAccounts(db, user.id)).toHaveLength(1);+ expect(await verifyUserPassword(db, user.id, "newpass123")).toBe(true);+ expect(await verifyUserPassword(db, user.id, "oldpass123")).toBe(false);+ });++ test<CustomTestContext>("replaces a legacy salted password with a plain bcrypt one", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "Legacy User",+ email: "[email protected]",+ });+ await db.insert(accounts).values({+ userId: user.id,+ accountId: user.id,+ providerId: CREDENTIAL_PROVIDER_ID,+ password: await legacySaltedHash("oldpass123", "salt"),+ });+ expect(await verifyUserPassword(db, user.id, "oldpass123")).toBe(true);++ await setUserPassword(db, user.id, "newpass123");++ const userAccounts = await getCredentialAccounts(db, user.id);+ expect(userAccounts).toHaveLength(1);+ expect(userAccounts[0].password?.startsWith("bcrypt-salted:")).toBe(false);+ expect(await verifyUserPassword(db, user.id, "newpass123")).toBe(true);+ expect(await verifyUserPassword(db, user.id, "oldpass123")).toBe(false);+ });++ test<CustomTestContext>("only touches the given user's account", async ({+ db,+ }) => {+ const user1 = await createTestUser(db, {+ name: "User 1",+ email: "[email protected]",+ password: "user1pass",+ });+ const user2 = await createTestUser(db, {+ name: "User 2",+ email: "[email protected]",+ password: "user2pass",+ });++ await setUserPassword(db, user1.id, "newpass123");++ expect(await verifyUserPassword(db, user2.id, "user2pass")).toBe(true);+ expect(await verifyUserPassword(db, user2.id, "newpass123")).toBe(false);+ });+});++describe("hasPassword", () => {+ test<CustomTestContext>("is true for users with a password", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ });+ expect(await hasPassword(db, user.id)).toBe(true);+ });++ test<CustomTestContext>("is false for users without a credential account", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "OAuth User",+ email: "[email protected]",+ });+ await db.insert(accounts).values({+ userId: user.id,+ providerId: "custom",+ accountId: "oauth-account-id",+ });+ expect(await hasPassword(db, user.id)).toBe(false);+ });++ test<CustomTestContext>("is false for a credential account without a password", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ });+ await db.insert(accounts).values({+ userId: user.id,+ providerId: CREDENTIAL_PROVIDER_ID,+ accountId: user.id,+ password: null,+ });+ expect(await hasPassword(db, user.id)).toBe(false);+ });+});++describe("validatePassword", () => {+ test<CustomTestContext>("returns the user for the right password", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ });++ const validated = await validatePassword(+ "[email protected]",+ "pass1234",+ db,+ );+ expect(validated.id).toBe(user.id);+ });++ test<CustomTestContext>("matches emails case-insensitively", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ });++ const validated = await validatePassword(+ "[email protected]",+ "pass1234",+ db,+ );+ expect(validated.id).toBe(user.id);+ });++ test<CustomTestContext>("accepts legacy salted passwords", async ({ db }) => {+ const user = await createTestUser(db, {+ name: "Legacy User",+ email: "[email protected]",+ });+ await db.insert(accounts).values({+ userId: user.id,+ accountId: user.id,+ providerId: CREDENTIAL_PROVIDER_ID,+ password: await legacySaltedHash("pass1234", "legacy-salt"),+ });++ const validated = await validatePassword("[email protected]", "pass1234", db);+ expect(validated.id).toBe(user.id);+ await expect(() =>+ validatePassword("[email protected]", "wrongpass", db),+ ).rejects.toThrow(/Wrong password/);+ });++ test<CustomTestContext>("rejects the wrong password", async ({ db }) => {+ await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ });++ await expect(() =>+ validatePassword("[email protected]", "wrongpass", db),+ ).rejects.toThrow(/Wrong password/);+ });++ test<CustomTestContext>("rejects unknown users", async ({ db }) => {+ await expect(() =>+ validatePassword("[email protected]", "pass1234", db),+ ).rejects.toThrow(/User not found/);+ });++ test<CustomTestContext>("rejects users without a credential account", async ({+ db,+ }) => {+ const [user] = await db+ .insert(users)+ .values({ name: "OAuth User", email: "[email protected]" })+ .returning();+ await db.insert(accounts).values({+ userId: user.id,+ providerId: "custom",+ accountId: "oauth-account-id",+ });++ await expect(() =>+ validatePassword("[email protected]", "pass1234", db),+ ).rejects.toThrow(/Wrong password/);+ });++ test<CustomTestContext>("rejects everything when password auth is disabled", async ({+ db,+ }) => {+ await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ });++ const originalValue = serverConfig.auth.disablePasswordAuth;+ serverConfig.auth.disablePasswordAuth = true;+ try {+ await expect(() =>+ validatePassword("[email protected]", "pass1234", db),+ ).rejects.toThrow(/Password authentication is currently disabled/);+ } finally {+ serverConfig.auth.disablePasswordAuth = originalValue;+ }+ });+});diff --git a/packages/trpc/auth.ts b/packages/trpc/auth.tsindex 80482625..814840af 100644--- a/packages/trpc/auth.ts+++ b/packages/trpc/auth.ts@@ -2,7 +2,7 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";import bcrypt from "bcryptjs";import { and, eq } from "drizzle-orm";-import { apiKeys } from "@karakeep/db/schema";+import { accounts, 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";@@ -35,10 +35,6 @@ function generateApiKeySecret() {};}-export function generatePasswordSalt() {- return randomBytes(32).toString("hex");-}-export async function regenerateApiKey(id: string,userId: string,@@ -179,8 +175,81 @@ export async function authenticateApiKey(key: string, database: Context["db"]) {};}-export async function hashPassword(password: string, salt: string | null) {- return await bcrypt.hash(password + (salt ?? ""), BCRYPT_SALT_ROUNDS);+// better-auth's provider id for email/password accounts. Their accountId is the+// user's id.+export const CREDENTIAL_PROVIDER_ID = "credential";++// Passwords set before the migration to better-auth were hashed as+// bcrypt(password + salt). They're stored as `bcrypt-salted:<salt>:<hash>`.+const SALTED_BCRYPT_PREFIX = "bcrypt-salted:";++export async function hashPassword(password: string) {+ return await bcrypt.hash(password, BCRYPT_SALT_ROUNDS);+}++export async function verifyPasswordHash(hash: string, password: string) {+ if (!hash.startsWith(SALTED_BCRYPT_PREFIX)) {+ return await bcrypt.compare(password, hash);+ }+ const saltAndHash = hash.slice(SALTED_BCRYPT_PREFIX.length);+ const separator = saltAndHash.indexOf(":");+ if (separator === -1) {+ return false;+ }+ return await bcrypt.compare(+ password + saltAndHash.slice(0, separator),+ saltAndHash.slice(separator + 1),+ );+}++async function getCredentialAccount(database: Context["db"], userId: string) {+ return await database.query.accounts.findFirst({+ columns: { password: true },+ where: and(+ eq(accounts.userId, userId),+ eq(accounts.providerId, CREDENTIAL_PROVIDER_ID),+ ),+ });+}++export async function hasPassword(database: Context["db"], userId: string) {+ const account = await getCredentialAccount(database, userId);+ return !!account?.password;+}++export async function verifyUserPassword(+ database: Context["db"],+ userId: string,+ password: string,+) {+ const account = await getCredentialAccount(database, userId);+ if (!account?.password) {+ // Returning early would make accounts without a password (OAuth-only)+ // measurably faster to probe than password accounts.+ await bcrypt.compare(password, DUMMY_PASSWORD_HASH);+ return false;+ }+ return await verifyPasswordHash(account.password, password);+}++export async function setUserPassword(+ database: Context["db"],+ userId: string,+ password: string,+) {+ const hash = await hashPassword(password);+ await database+ .insert(accounts)+ .values({+ userId,+ accountId: userId,+ providerId: CREDENTIAL_PROVIDER_ID,+ password: hash,+ })+ .onConflictDoUpdate({+ target: [accounts.providerId, accounts.accountId],+ set: { password: hash, updatedAt: new Date() },+ });}export async function validatePassword(@@ -192,7 +261,7 @@ export async function validatePassword(throw new Error("Password authentication is currently disabled");}const user = await database.query.users.findFirst({- where: (u, { eq }) => eq(u.email, email),+ where: (u, { eq }) => eq(u.email, email.toLowerCase()),});if (!user) {@@ -201,18 +270,7 @@ export async function validatePassword(throw new Error("User not found");}- if (!user.password) {- // Same reasoning: returning early here would make accounts without a- // password (OAuth-only) measurably faster to probe than password accounts.- await bcrypt.compare(password, DUMMY_PASSWORD_HASH);- throw new Error("This user doesn't have a password defined");- }-- const validation = await bcrypt.compare(- password + (user.salt ?? ""),- user.password,- );- if (!validation) {+ if (!(await verifyUserPassword(database, user.id, password))) {throw new Error("Wrong password");}diff --git a/packages/trpc/email.ts b/packages/trpc/email.tsindex a8cf4f29..4a056dcf 100644--- a/packages/trpc/email.ts+++ b/packages/trpc/email.ts@@ -55,14 +55,8 @@ export const sendVerificationEmail = withTracing(transporter: Transporter,email: string,name: string,- token: string,- redirectUrl?: string,+ verificationUrl: string,) => {- let verificationUrl = `${serverConfig.publicUrl}/verify-email?token=${encodeURIComponent(token)}&email=${encodeURIComponent(email)}`;- if (redirectUrl) {- verificationUrl += `&redirectUrl=${encodeURIComponent(redirectUrl)}`;- }-const mailOptions = {from: serverConfig.email.smtp!.from,to: email,@@ -152,10 +146,8 @@ export const sendPasswordResetEmail = withTracing(transporter: Transporter,email: string,name: string,- token: string,+ resetUrl: string,) => {- const resetUrl = `${serverConfig.publicUrl}/reset-password?token=${encodeURIComponent(token)}`;-const mailOptions = {from: serverConfig.email.smtp!.from,to: email,diff --git a/packages/trpc/models/users.ts b/packages/trpc/models/users.tsindex 0ad1e926..27350b4d 100644--- a/packages/trpc/models/users.ts+++ b/packages/trpc/models/users.ts@@ -1,4 +1,3 @@-import { randomBytes } from "crypto";import { TRPCError } from "@trpc/server";import { and, count, desc, eq, gte, lte, sql } from "drizzle-orm";import invariant from "tiny-invariant";@@ -6,6 +5,7 @@ import { z } from "zod";import { SqliteError } from "@karakeep/db";import {+ accounts,assets,AssetTypes,bookmarkLinks,@@ -13,17 +13,13 @@ import {bookmarks,bookmarkTags,highlights,- passwordResetTokens,subscriptions,tagsOnBookmarks,users,- verificationTokens,} from "@karakeep/db/schema";import { deleteAsset, deleteUserAssets } from "@karakeep/shared-server";import serverConfig from "@karakeep/shared/config";import {- zResetPasswordSchema,- zSignUpSchema,zUpdateUserSettingsSchema,zUserSettingsSchema,zUserStatsResponseSchema,@@ -32,8 +28,12 @@ import {} from "@karakeep/shared/types/users";import { AuthedContext, Context } from "..";-import { generatePasswordSalt, hashPassword, validatePassword } from "../auth";-import { sendPasswordResetEmail, sendVerificationEmail } from "../email";+import {+ CREDENTIAL_PROVIDER_ID,+ hasPassword,+ hashPassword,+ verifyUserPassword,+} from "../auth";export class User {constructor(@@ -60,48 +60,20 @@ export class User {return this.fromId_DANGEROUS(ctx, ctx.user.id);}- static async create(- ctx: Context,- input: z.infer<typeof zSignUpSchema> & { redirectUrl?: string },- role?: "user" | "admin",- ) {- const salt = generatePasswordSalt();- const user = await User.createRaw(ctx.db, {- name: input.name,- email: input.email,- password: await hashPassword(input.password, salt),- salt,- role,- });-- if (serverConfig.auth.emailVerificationRequired) {- const token = await User.genEmailVerificationToken(ctx.db, input.email);- try {- await sendVerificationEmail(- input.email,- user.name,- token,- input.redirectUrl,- );- } catch (error) {- console.error("Failed to send verification email:", error);- }- }-- return user;- }-static async createRaw(db: Context["db"],input: {name: string;email: string;password?: string;- salt?: string;role?: "user" | "admin";- emailVerified?: Date | null;+ emailVerified?: boolean;},) {+ // Hashing is async, so it has to happen before the synchronous transaction.+ const passwordHash = input.password+ ? await hashPassword(input.password)+ : undefined;// This transaction reads before writing, so reserve the writer slot before// taking a WAL snapshot that another connection could invalidate.return await db.transaction(@@ -120,17 +92,29 @@ export class User {.insert(users).values({name: input.name,- email: input.email,- password: input.password,- salt: input.salt,+ // Emails are stored lowercased, which is what better-auth expects+ // when looking users up by email.+ email: input.email.toLowerCase(),role: userRole,- emailVerified: input.emailVerified,+ emailVerified: input.emailVerified ?? false,bookmarkQuota: serverConfig.quotas.free.bookmarkLimit,storageQuota: serverConfig.quotas.free.assetSizeBytes,}).returning().all();+ if (passwordHash) {+ trx+ .insert(accounts)+ .values({+ userId: result.id,+ accountId: result.id,+ providerId: CREDENTIAL_PROVIDER_ID,+ password: passwordHash,+ })+ .run();+ }+return result;} catch (e) {if (e instanceof SqliteError) {@@ -157,235 +141,6 @@ export class User {return dbUsers.map((u) => new User(ctx, u));}- static async genEmailVerificationToken(- db: Context["db"],- email: string,- ): Promise<string> {- const token = randomBytes(10).toString("hex");- const expires = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours-- await db.insert(verificationTokens).values({- identifier: email,- token,- expires,- });-- return token;- }-- static async verifyEmailToken(- db: Context["db"],- email: string,- token: string,- ): Promise<boolean> {- const verificationToken = await db.query.verificationTokens.findFirst({- where: (vt, { and, eq }) =>- and(eq(vt.identifier, email), eq(vt.token, token)),- });-- if (!verificationToken) {- return false;- }-- if (verificationToken.expires < new Date()) {- await db- .delete(verificationTokens)- .where(- and(- eq(verificationTokens.identifier, email),- eq(verificationTokens.token, token),- ),- );- return false;- }-- await db- .delete(verificationTokens)- .where(- and(- eq(verificationTokens.identifier, email),- eq(verificationTokens.token, token),- ),- );-- return true;- }-- static async verifyEmail(- ctx: Context,- email: string,- token: string,- ): Promise<void> {- const isValid = await User.verifyEmailToken(ctx.db, email, token);- if (!isValid) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Invalid or expired verification token",- });- }-- const result = await ctx.db- .update(users)- .set({ emailVerified: new Date() })- .where(eq(users.email, email));-- if (result.changes === 0) {- throw new TRPCError({- code: "NOT_FOUND",- message: "User not found",- });- }- }-- static async resendVerificationEmail(- ctx: Context,- email: string,- redirectUrl?: string,- ): Promise<void> {- if (- !serverConfig.auth.emailVerificationRequired ||- !serverConfig.email.smtp- ) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Email verification is not enabled",- });- }-- const user = await ctx.db.query.users.findFirst({- where: eq(users.email, email),- });-- if (!user) {- return; // Don't reveal if user exists or not for security- }-- if (user.emailVerified) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Email is already verified",- });- }-- const token = await User.genEmailVerificationToken(ctx.db, email);- try {- await sendVerificationEmail(email, user.name, token, redirectUrl);- } catch (error) {- console.error("Failed to send verification email:", error);- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Failed to send verification email",- });- }- }-- static async forgotPassword(ctx: Context, email: string): Promise<void> {- if (!serverConfig.email.smtp) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Email service is not configured",- });- }-- const user = await ctx.db.query.users.findFirst({- where: eq(users.email, email),- });-- if (!user || !user.password) {- return; // Don't reveal if user exists or not for security- }-- try {- const token = randomBytes(32).toString("hex");- const expires = new Date(Date.now() + 60 * 60 * 1000); // 1 hour-- await ctx.db.transaction((tx) => {- // Invalidate any existing reset tokens for this user- tx.delete(passwordResetTokens)- .where(eq(passwordResetTokens.userId, user.id))- .run();-- tx.insert(passwordResetTokens)- .values({- userId: user.id,- token,- expires,- })- .run();- });-- // Deliberately not awaited. Delivery latency is only incurred for real- // accounts, so awaiting it makes this endpoint a timing oracle for which- // emails are registered -- and a hard oracle whenever SMTP is unhealthy,- // since only real accounts could reach the throw below (500 for a user- // that exists, 200 for one that doesn't).- void sendPasswordResetEmail(email, user.name, token).catch((error) => {- console.error("Failed to send password reset email:", error);- });- } catch (error) {- console.error("Failed to create password reset token:", error);- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Failed to send password reset email",- });- }- }-- static async resetPassword(- ctx: Context,- input: z.infer<typeof zResetPasswordSchema>,- ): Promise<void> {- const resetToken = await ctx.db.query.passwordResetTokens.findFirst({- where: eq(passwordResetTokens.token, input.token),- with: {- user: {- columns: {- id: true,- },- },- },- });-- if (!resetToken) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Invalid or expired reset token",- });- }-- if (resetToken.expires < new Date()) {- await ctx.db- .delete(passwordResetTokens)- .where(eq(passwordResetTokens.token, input.token));- throw new TRPCError({- code: "BAD_REQUEST",- message: "Invalid or expired reset token",- });- }-- if (!resetToken.user) {- throw new TRPCError({- code: "NOT_FOUND",- message: "User not found",- });- }-- const newSalt = generatePasswordSalt();- const hashedPassword = await hashPassword(input.newPassword, newSalt);-- await ctx.db- .update(users)- .set({- password: hashedPassword,- salt: newSalt,- })- .where(eq(users.id, resetToken.user.id));-- await ctx.db- .delete(passwordResetTokens)- .where(eq(passwordResetTokens.token, input.token));- }-private static async assertNoActiveStripeSubscriptionForUser(db: Context["db"],userId: string,@@ -432,7 +187,7 @@ export class User {async deleteAccount(password?: string): Promise<void> {invariant(this.ctx.user.email, "A user always has an email specified");- if (this.user.password) {+ if (await this.isLocalUser()) {if (!password) {throw new TRPCError({code: "BAD_REQUEST",@@ -440,9 +195,7 @@ export class User {});}- try {- await validatePassword(this.ctx.user.email, password, this.ctx.db);- } catch {+ if (!(await verifyUserPassword(this.ctx.db, this.user.id, password))) {throw new TRPCError({code: "UNAUTHORIZED",message: "Invalid password",@@ -453,33 +206,6 @@ export class User {await User.deleteInternal(this.ctx.db, this.user.id);}- async changePassword(- currentPassword: string,- newPassword: string,- ): Promise<void> {- invariant(this.ctx.user.email, "A user always has an email specified");-- try {- const user = await validatePassword(- this.ctx.user.email,- currentPassword,- this.ctx.db,- );- invariant(user.id === this.ctx.user.id);- } catch {- throw new TRPCError({ code: "UNAUTHORIZED" });- }-- const newSalt = generatePasswordSalt();- await this.ctx.db- .update(users)- .set({- password: await hashPassword(newPassword, newSalt),- salt: newSalt,- })- .where(eq(users.id, this.user.id));- }-async getSettings(): Promise<z.infer<typeof zUserSettingsSchema>> {const settings = await this.ctx.db.query.users.findFirst({where: eq(users.id, this.user.id),@@ -1241,21 +967,18 @@ export class User {};}- asWhoAmI(): z.infer<typeof zWhoAmIResponseSchema> {+ // A local user is one that can sign in with a password.+ async isLocalUser(): Promise<boolean> {+ return await hasPassword(this.ctx.db, this.user.id);+ }++ async asWhoAmI(): Promise<z.infer<typeof zWhoAmIResponseSchema>> {return {id: this.user.id,name: this.user.name,email: this.user.email,image: this.user.image,- localUser: this.user.password !== null,- };- }-- asPublicUser() {- const { password, salt: _salt, ...rest } = this.user;- return {- ...rest,- localUser: password !== null,+ localUser: await this.isLocalUser(),};}}diff --git a/packages/trpc/routers/admin.test.ts b/packages/trpc/routers/admin.test.tsindex 301b4115..dd786a6b 100644--- a/packages/trpc/routers/admin.test.ts+++ b/packages/trpc/routers/admin.test.ts@@ -10,17 +10,25 @@ import {} from "vitest";import {+ accounts,bookmarkAssets,bookmarkLinks,bookmarks,+ sessions,users,} from "@karakeep/db/schema";import { QueuePriority } from "@karakeep/shared-server";import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";import type { CustomTestContext } from "../testUtils";+import {+ CREDENTIAL_PROVIDER_ID,+ hasPassword,+ verifyUserPassword,+} from "../auth";import {buildTestContext,+ createTestUser,getApiCaller,getApiKeyCallerForPlainKey,getTestQueueMocks,@@ -408,6 +416,188 @@ describe("Admin Routes", () => {).rejects.toThrow(/FORBIDDEN|admin:bookmarks:readwrite/i);});+ describe("user management", () => {+ async function createAdmin(db: CustomTestContext["db"]) {+ const admin = await createTestUser(db, {+ name: "Admin User",+ email: "[email protected]",+ password: "adminpass123",+ role: "admin",+ });+ return {+ admin,+ adminApi: getApiCaller(db, admin.id, admin.email, "admin"),+ };+ }++ async function createSession(+ db: CustomTestContext["db"],+ userId: string,+ token: string,+ ) {+ await db.insert(sessions).values({+ userId,+ token,+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),+ });+ }++ test<CustomTestContext>("createUser creates a verified user with a password", async ({+ db,+ }) => {+ const { adminApi } = await createAdmin(db);++ const created = await adminApi.admin.createUser({+ name: "Created User",+ email: "[email protected]",+ password: "createdpass123",+ confirmPassword: "createdpass123",+ role: "user",+ });++ expect(created.email).toBe("[email protected]");+ expect(created.role).toBe("user");++ const dbUser = await db.query.users.findFirst({+ where: eq(users.id, created.id),+ });+ expect(dbUser?.emailVerified).toBe(true);+ expect(await verifyUserPassword(db, created.id, "createdpass123")).toBe(+ true,+ );+ });++ test<CustomTestContext>("resetPassword changes the password and signs the user out", async ({+ db,+ }) => {+ const { admin, adminApi } = await createAdmin(db);+ const target = await createTestUser(db, {+ name: "Target User",+ email: "[email protected]",+ password: "oldpass123",+ });+ await createSession(db, target.id, "target-session-1");+ await createSession(db, target.id, "target-session-2");+ await createSession(db, admin.id, "admin-session");++ await adminApi.admin.resetPassword({+ userId: target.id,+ newPassword: "newpass123",+ newPasswordConfirm: "newpass123",+ });++ expect(await verifyUserPassword(db, target.id, "newpass123")).toBe(true);+ expect(await verifyUserPassword(db, target.id, "oldpass123")).toBe(false);++ // Still a single credential account, updated in place+ const targetAccounts = await db+ .select()+ .from(accounts)+ .where(eq(accounts.userId, target.id));+ expect(targetAccounts).toHaveLength(1);++ const targetSessions = await db+ .select()+ .from(sessions)+ .where(eq(sessions.userId, target.id));+ expect(targetSessions).toHaveLength(0);++ // Other users' sessions are untouched+ const adminSessions = await db+ .select()+ .from(sessions)+ .where(eq(sessions.userId, admin.id));+ expect(adminSessions.map((s) => s.token)).toEqual(["admin-session"]);+ });++ test<CustomTestContext>("resetPassword gives a password to a user without one", async ({+ db,+ apiCallers,+ }) => {+ const { adminApi } = await createAdmin(db);+ const { id: oauthUserId } = await apiCallers[0].users.whoami();+ expect(await hasPassword(db, oauthUserId)).toBe(false);++ await adminApi.admin.resetPassword({+ userId: oauthUserId,+ newPassword: "newpass123",+ newPasswordConfirm: "newpass123",+ });++ const credentialAccount = await db.query.accounts.findFirst({+ where: eq(accounts.userId, oauthUserId),+ });+ expect(credentialAccount?.providerId).toBe(CREDENTIAL_PROVIDER_ID);+ expect(credentialAccount?.accountId).toBe(oauthUserId);+ expect(await verifyUserPassword(db, oauthUserId, "newpass123")).toBe(+ true,+ );+ });++ test<CustomTestContext>("resetPassword refuses to reset own password", async ({+ db,+ }) => {+ const { admin, adminApi } = await createAdmin(db);+ await createSession(db, admin.id, "admin-session");++ await expect(() =>+ adminApi.admin.resetPassword({+ userId: admin.id,+ newPassword: "newpass123",+ newPasswordConfirm: "newpass123",+ }),+ ).rejects.toThrow(/Cannot reset own password/);++ expect(await verifyUserPassword(db, admin.id, "adminpass123")).toBe(true);+ const adminSessions = await db+ .select()+ .from(sessions)+ .where(eq(sessions.userId, admin.id));+ expect(adminSessions).toHaveLength(1);+ });++ test<CustomTestContext>("resetPassword fails for unknown users", async ({+ db,+ }) => {+ const { adminApi } = await createAdmin(db);++ await expect(() =>+ adminApi.admin.resetPassword({+ userId: "does-not-exist",+ newPassword: "newpass123",+ newPasswordConfirm: "newpass123",+ }),+ ).rejects.toThrow(/User not found/);++ const orphanAccounts = await db+ .select()+ .from(accounts)+ .where(eq(accounts.userId, "does-not-exist"));+ expect(orphanAccounts).toHaveLength(0);+ });++ test<CustomTestContext>("non-admins cannot reset passwords", async ({+ db,+ apiCallers,+ }) => {+ const target = await createTestUser(db, {+ name: "Target User",+ email: "[email protected]",+ password: "oldpass123",+ });++ await expect(() =>+ apiCallers[0].admin.resetPassword({+ userId: target.id,+ newPassword: "newpass123",+ newPasswordConfirm: "newpass123",+ }),+ ).rejects.toThrow(/FORBIDDEN/);++ expect(await verifyUserPassword(db, target.id, "oldpass123")).toBe(true);+ });+ });+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.tsindex 4e96d880..3411c64a 100644--- a/packages/trpc/routers/admin.ts+++ b/packages/trpc/routers/admin.ts@@ -8,6 +8,7 @@ import {bookmarkAssets,bookmarkLinks,bookmarks,+ sessions,subscriptions,users,} from "@karakeep/db/schema";@@ -41,7 +42,7 @@ import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";import { setUrlHostnameFromResolvedAddress } from "@karakeep/shared/utils/url";import { getVectorStoreClient } from "@karakeep/shared/vectorStore";-import { generatePasswordSalt, hashPassword } from "../auth";+import { setUserPassword } from "../auth";import { createAdminScopedProcedure, router } from "../index";import { Bookmark } from "../models/bookmarks";import { User } from "../models/users";@@ -521,7 +522,14 @@ export const adminAppRouter = router({}),).mutation(async ({ input, ctx }) => {- return await User.create(ctx, input, input.role);+ // Users created by an admin don't need to verify their email.+ return await User.createRaw(ctx.db, {+ name: input.name,+ email: input.email,+ password: input.password,+ role: input.role,+ emailVerified: true,+ });}),updateUser: adminUsersProcedure.input(updateUserSchema)@@ -579,19 +587,20 @@ export const adminAppRouter = router({message: "Cannot reset own password",});}- const newSalt = generatePasswordSalt();- const hashedPassword = await hashPassword(input.newPassword, newSalt);- const result = await ctx.db- .update(users)- .set({ password: hashedPassword, salt: newSalt })- .where(eq(users.id, input.userId));-- if (result.changes == 0) {+ const user = await ctx.db.query.users.findFirst({+ columns: { id: true },+ where: eq(users.id, input.userId),+ });+ if (!user) {throw new TRPCError({code: "NOT_FOUND",message: "User not found",});}+ await setUserPassword(ctx.db, user.id, input.newPassword);+ // Someone else might know the old password, so sign the user out+ // everywhere.+ await ctx.db.delete(sessions).where(eq(sessions.userId, user.id));}),purgeBookmarksOverQuota: adminUsersProcedure.input(diff --git a/packages/trpc/routers/apiKeys.test.ts b/packages/trpc/routers/apiKeys.test.tsindex 20e8187d..b40a46db 100644--- a/packages/trpc/routers/apiKeys.test.ts+++ b/packages/trpc/routers/apiKeys.test.ts@@ -1,11 +1,14 @@+import bcrypt from "bcryptjs";import { eq } from "drizzle-orm";import { beforeEach, describe, expect, test, vi } from "vitest";-import { apiKeys } from "@karakeep/db/schema";+import { accounts, apiKeys } from "@karakeep/db/schema";import { API_KEY_FULL_ACCESS_SCOPE } from "@karakeep/shared/types/apiKeys";import type { CustomTestContext } from "../testUtils";+import { CREDENTIAL_PROVIDER_ID } from "../auth";import {+ createTestUser,defaultBeforeEach,getApiCaller,getApiKeyCallerForPlainKey,@@ -29,15 +32,11 @@ beforeEach<CustomTestContext>(defaultBeforeEach(false));describe("API Keys Routes", () => {describe("create", () => {- test<CustomTestContext>("creates API key successfully", async ({- unauthedAPICaller,- db,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("creates API key successfully", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -51,14 +50,12 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("creates API key with explicit scopes", async ({- unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -80,15 +77,11 @@ describe("API Keys Routes", () => {});describe("list", () => {- test<CustomTestContext>("lists user's API keys", async ({- unauthedAPICaller,- db,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("lists user's API keys", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -110,14 +103,12 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("returns empty list for new user", async ({- unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -127,21 +118,18 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("privacy isolation between users", async ({- unauthedAPICaller,db,}) => {- const user1 = await unauthedAPICaller.users.create({+ const user1 = await createTestUser(db, {name: "User 1",email: "[email protected]",password: "password123",- confirmPassword: "password123",});- const user2 = await unauthedAPICaller.users.create({+ const user2 = await createTestUser(db, {name: "User 2",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api1 = getApiCaller(db, user1.id, user1.email).apiKeys;@@ -173,11 +161,10 @@ describe("API Keys Routes", () => {unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -201,15 +188,11 @@ describe("API Keys Routes", () => {});describe("revoke", () => {- test<CustomTestContext>("revokes API key successfully", async ({- unauthedAPICaller,- db,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("revokes API key successfully", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -226,21 +209,18 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("cannot revoke another user's key", async ({- unauthedAPICaller,db,}) => {- const user1 = await unauthedAPICaller.users.create({+ const user1 = await createTestUser(db, {name: "User 1",email: "[email protected]",password: "password123",- confirmPassword: "password123",});- const user2 = await unauthedAPICaller.users.create({+ const user2 = await createTestUser(db, {name: "User 2",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api1 = getApiCaller(db, user1.id, user1.email).apiKeys;@@ -259,14 +239,12 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("silently handles non-existent key", async ({- unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -288,11 +266,10 @@ describe("API Keys Routes", () => {unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const key = await unauthedAPICaller.apiKeys.exchange({@@ -312,14 +289,12 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("an API key cannot revoke other keys", async ({- unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -344,11 +319,10 @@ describe("API Keys Routes", () => {unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -395,11 +369,10 @@ describe("API Keys Routes", () => {unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -418,11 +391,10 @@ describe("API Keys Routes", () => {unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -442,11 +414,10 @@ describe("API Keys Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const result = await unauthedAPICaller.apiKeys.exchange({@@ -469,15 +440,33 @@ describe("API Keys Routes", () => {expect(dbKeys[0].name).toBe("Extension Key");});+ test<CustomTestContext>("stores emails lowercased and matches them case-insensitively", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "password123",+ });+ expect(user.email).toBe("[email protected]");++ const result = await unauthedAPICaller.apiKeys.exchange({+ keyName: "Extension Key",+ email: "[email protected]",+ password: "password123",+ });+ expect(result.name).toBe("Extension Key");+ });+test<CustomTestContext>("exchanges credentials for API key with explicit scopes", async ({db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Scoped Exchange User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const result = await unauthedAPICaller.apiKeys.exchange({@@ -499,13 +488,13 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("rejects wrong password", async ({+ db,unauthedAPICaller,}) => {- await unauthedAPICaller.users.create({+ await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});await expect(() =>@@ -529,22 +518,71 @@ describe("API Keys Routes", () => {).rejects.toThrow(/UNAUTHORIZED/);});- test<CustomTestContext>("rejects unverified user when email verification is enabled", async ({+ test<CustomTestContext>("exchanges a legacy salted password", async ({db,+ unauthedAPICaller,}) => {- // Import User model to create an unverified user directly- const { User } = await import("../models/users");+ // Users created before the better-auth migration have their password+ // stored as bcrypt(password + salt) in a `bcrypt-salted:` hash.+ const user = await createTestUser(db, {+ name: "Legacy User",+ email: "[email protected]",+ });+ const salt = "legacy-salt";+ await db.insert(accounts).values({+ userId: user.id,+ accountId: user.id,+ providerId: CREDENTIAL_PROVIDER_ID,+ password: `bcrypt-salted:${salt}:${await bcrypt.hash("password123" + salt, 10)}`,+ });+ await expect(() =>+ unauthedAPICaller.apiKeys.exchange({+ keyName: "Legacy Key",+ email: "[email protected]",+ password: "wrongpassword",+ }),+ ).rejects.toThrow(/UNAUTHORIZED/);++ const result = await unauthedAPICaller.apiKeys.exchange({+ keyName: "Legacy Key",+ email: "[email protected]",+ password: "password123",+ });+ expect(result.name).toBe("Legacy Key");++ const validationResult = await unauthedAPICaller.apiKeys.validate({+ apiKey: result.key,+ });+ expect(validationResult.success).toBe(true);+ });++ test<CustomTestContext>("rejects user without a credential account", async ({+ db,+ unauthedAPICaller,+ }) => {+ await createTestUser(db, {+ name: "OAuth User",+ email: "[email protected]",+ });++ await expect(() =>+ unauthedAPICaller.apiKeys.exchange({+ keyName: "Extension Key",+ email: "[email protected]",+ password: "password123",+ }),+ ).rejects.toThrow(/UNAUTHORIZED/);+ });++ test<CustomTestContext>("rejects unverified user when email verification is enabled", async ({+ db,+ }) => {// Create user with password but without email verification- await User.createRaw(db, {+ await createTestUser(db, {name: "Unverified User",email: "[email protected]",- password: await (await import("../auth")).hashPassword(- "password123",- "test-salt",- ),- salt: "test-salt",- emailVerified: null, // User is not verified+ password: "password123",});// Mock serverConfig to enable email verification requirement@@ -582,11 +620,10 @@ describe("API Keys Routes", () => {unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -614,15 +651,11 @@ describe("API Keys Routes", () => {expect(finalListResult.keys).toHaveLength(0);});- test<CustomTestContext>("multiple keys per user", async ({- unauthedAPICaller,- db,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("multiple keys per user", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const api = getApiCaller(db, user.id, user.email).apiKeys;@@ -647,13 +680,13 @@ describe("API Keys Routes", () => {});test<CustomTestContext>("exchange creates usable key", async ({+ db,unauthedAPICaller,}) => {- await unauthedAPICaller.users.create({+ await createTestUser(db, {name: "Exchange User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const exchangedKey = await unauthedAPICaller.apiKeys.exchange({@@ -672,14 +705,12 @@ 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({+ const user = await createTestUser(db, {name: "Meta User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});const sessionCaller = getApiCaller(db, user.id, user.email);@@ -700,14 +731,12 @@ describe("API Keys Routes", () => {describe("backward compatibility", () => {test<CustomTestContext>("validates version 1 keys continues to work", async ({- unauthedAPICaller,db,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "password123",- confirmPassword: "password123",});// Manually generated v1 key and its corresponding hashdiff --git a/packages/trpc/routers/invites.test.ts b/packages/trpc/routers/invites.test.tsindex 29d3891b..497b8a9f 100644--- a/packages/trpc/routers/invites.test.ts+++ b/packages/trpc/routers/invites.test.ts@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import { invites, users } from "@karakeep/db/schema";import type { CustomTestContext } from "../testUtils";-import { defaultBeforeEach, getApiCaller } from "../testUtils";+import { createTestUser, defaultBeforeEach, getApiCaller } from "../testUtils";// Mock server config with email settingsvi.mock("@karakeep/shared/config", async (original) => {@@ -35,15 +35,11 @@ vi.mock("../email", () => ({beforeEach<CustomTestContext>(defaultBeforeEach(false));describe("Invites Router", () => {- test<CustomTestContext>("admin can create invite", async ({- db,- unauthedAPICaller,- }) => {- const admin = await unauthedAPICaller.users.create({+ test<CustomTestContext>("admin can create invite", async ({ db }) => {+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -64,22 +60,17 @@ describe("Invites Router", () => {expect(dbInvite?.token).toBeDefined();});- test<CustomTestContext>("non-admin cannot create invite", async ({- db,- unauthedAPICaller,- }) => {- await unauthedAPICaller.users.create({+ test<CustomTestContext>("non-admin cannot create invite", async ({ db }) => {+ await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Regular User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const userCaller = getApiCaller(db, user.id, user.email);@@ -91,22 +82,17 @@ describe("Invites Router", () => {).rejects.toThrow(/FORBIDDEN/);});- test<CustomTestContext>("cannot invite existing user", async ({- db,- unauthedAPICaller,- }) => {- const admin = await unauthedAPICaller.users.create({+ test<CustomTestContext>("cannot invite existing user", async ({ db }) => {+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});- await unauthedAPICaller.users.create({+ await createTestUser(db, {name: "Existing User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -120,13 +106,11 @@ describe("Invites Router", () => {test<CustomTestContext>("cannot create duplicate pending invite", async ({db,- unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -142,15 +126,11 @@ describe("Invites Router", () => {).rejects.toThrow(/An active invite for this email already exists/);});- test<CustomTestContext>("admin can list invites", async ({- db,- unauthedAPICaller,- }) => {- const admin = await unauthedAPICaller.users.create({+ test<CustomTestContext>("admin can list invites", async ({ db }) => {+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -174,22 +154,17 @@ describe("Invites Router", () => {).toBeTruthy();});- test<CustomTestContext>("non-admin cannot list invites", async ({- db,- unauthedAPICaller,- }) => {- await unauthedAPICaller.users.create({+ test<CustomTestContext>("non-admin cannot list invites", async ({ db }) => {+ await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Regular User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const userCaller = getApiCaller(db, user.id, user.email);@@ -201,11 +176,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -241,11 +215,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -270,11 +243,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -306,11 +278,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -343,11 +314,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -374,11 +344,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -404,11 +373,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -438,15 +406,11 @@ describe("Invites Router", () => {).rejects.toThrow(/Invite not found or has been used/);});- test<CustomTestContext>("admin can revoke invite", async ({- db,- unauthedAPICaller,- }) => {- const admin = await unauthedAPICaller.users.create({+ test<CustomTestContext>("admin can revoke invite", async ({ db }) => {+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -468,22 +432,17 @@ describe("Invites Router", () => {expect(revokedInvite).toBeUndefined();});- test<CustomTestContext>("non-admin cannot revoke invite", async ({- db,- unauthedAPICaller,- }) => {- const admin = await unauthedAPICaller.users.create({+ test<CustomTestContext>("non-admin cannot revoke invite", async ({ db }) => {+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Regular User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -500,15 +459,11 @@ describe("Invites Router", () => {).rejects.toThrow(/FORBIDDEN/);});- test<CustomTestContext>("admin can resend invite", async ({- db,- unauthedAPICaller,- }) => {- const admin = await unauthedAPICaller.users.create({+ test<CustomTestContext>("admin can resend invite", async ({ db }) => {+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -541,11 +496,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -574,13 +528,11 @@ describe("Invites Router", () => {test<CustomTestContext>("invite creation works without expiration", async ({db,- unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -595,13 +547,11 @@ describe("Invites Router", () => {test<CustomTestContext>("invite includes inviter information", async ({db,- unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -622,11 +572,10 @@ describe("Invites Router", () => {db,unauthedAPICaller,}) => {- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");@@ -653,7 +602,6 @@ describe("Invites Router", () => {test<CustomTestContext>("email sending is called during invite creation", async ({db,- unauthedAPICaller,}) => {// Mock the email moduleconst mockSendInviteEmail = vi.fn().mockResolvedValue(undefined);@@ -661,11 +609,10 @@ describe("Invites Router", () => {sendInviteEmail: mockSendInviteEmail,}));- const admin = await unauthedAPICaller.users.create({+ const admin = await createTestUser(db, {name: "Admin User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const adminCaller = getApiCaller(db, admin.id, admin.email, "admin");diff --git a/packages/trpc/routers/invites.ts b/packages/trpc/routers/invites.tsindex 409f9d92..27c343eb 100644--- a/packages/trpc/routers/invites.ts+++ b/packages/trpc/routers/invites.ts@@ -6,7 +6,6 @@ import { z } from "zod";import { invites, users } from "@karakeep/db/schema";import { zUserNameSchema } from "@karakeep/shared/types/users";-import { generatePasswordSalt, hashPassword } from "../auth";import { sendInviteEmail } from "../email";import {createAdminScopedProcedure,@@ -188,14 +187,12 @@ export const invitesAppRouter = router({});}- const salt = generatePasswordSalt();const user = await User.createRaw(ctx.db, {name: input.name,email: invite.email,- password: await hashPassword(input.password, salt),- salt,+ password: input.password,role: "user",- emailVerified: new Date(), // Auto-verify invited users+ emailVerified: true, // Auto-verify invited users});// Delete the invite after successful user creationdiff --git a/packages/trpc/routers/subscriptions.test.ts b/packages/trpc/routers/subscriptions.test.tsindex 8667d57f..a590b734 100644--- a/packages/trpc/routers/subscriptions.test.ts+++ b/packages/trpc/routers/subscriptions.test.ts@@ -8,6 +8,7 @@ import serverConfig from "@karakeep/shared/config";import type { CustomTestContext } from "../testUtils";import {+ createTestUser,defaultBeforeEach,getApiCaller,getApiKeyCallerForPlainKey,@@ -106,13 +107,11 @@ describe("Subscription Routes", () => {describe("getSubscriptionStatus", () => {test<CustomTestContext>("returns free tier when no subscription exists", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -131,13 +130,11 @@ describe("Subscription Routes", () => {test<CustomTestContext>("returns subscription data when subscription exists", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -173,13 +170,11 @@ describe("Subscription Routes", () => {describe("manual tier", () => {test<CustomTestContext>("getSubscriptionStatus returns custom tier when manualTierName is set", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -203,13 +198,11 @@ describe("Subscription Routes", () => {test<CustomTestContext>("getSubscriptionStatus returns custom tier over an inactive subscription", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -237,11 +230,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Manually granted tier with custom quotas@@ -305,11 +297,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});await db@@ -387,11 +378,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});await db@@ -482,14 +472,12 @@ describe("Subscription Routes", () => {test<CustomTestContext>("admin can grant and revoke a manual tier by email", async ({db,- unauthedAPICaller,}) => {const adminApi = await createAdminCaller(db);- const targetUser = await unauthedAPICaller.users.create({+ const targetUser = await createTestUser(db, {name: "Target User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});await adminApi.subscriptions.updateSubscriptionTier({@@ -544,7 +532,6 @@ describe("Subscription Routes", () => {test<CustomTestContext>("fails for unknown emails and actively subscribed users", async ({db,- unauthedAPICaller,}) => {const adminApi = await createAdminCaller(db);@@ -555,11 +542,10 @@ describe("Subscription Routes", () => {}),).rejects.toThrow(/User not found/);- const subscribedUser = await unauthedAPICaller.users.create({+ const subscribedUser = await createTestUser(db, {name: "Subscribed User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});await db.insert(subscriptions).values({userId: subscribedUser.id,@@ -585,14 +571,12 @@ describe("Subscription Routes", () => {test<CustomTestContext>("requires a verified email when verification is enabled", async ({db,- unauthedAPICaller,}) => {const adminApi = await createAdminCaller(db);- const targetUser = await unauthedAPICaller.users.create({+ const targetUser = await createTestUser(db, {name: "Target User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const originalValue = serverConfig.auth.emailVerificationRequired;@@ -613,7 +597,7 @@ describe("Subscription Routes", () => {await db.update(users)- .set({ emailVerified: new Date() })+ .set({ emailVerified: true }).where(eq(users.id, targetUser.id));await adminApi.subscriptions.updateSubscriptionTier({@@ -635,14 +619,12 @@ describe("Subscription Routes", () => {test<CustomTestContext>("requires the admin:subscriptions scope for API keys", async ({db,- unauthedAPICaller,}) => {const adminApi = await createAdminCaller(db);- await unauthedAPICaller.users.create({+ await createTestUser(db, {name: "Target User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const usersScopedKey = await adminApi.apiKeys.create({@@ -678,13 +660,11 @@ describe("Subscription Routes", () => {describe("getSubscriptionPrice", () => {test<CustomTestContext>("returns monthly and yearly prices", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -720,13 +700,11 @@ describe("Subscription Routes", () => {describe("createCheckoutSession", () => {test<CustomTestContext>("creates checkout session for new customer", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -781,13 +759,11 @@ describe("Subscription Routes", () => {test<CustomTestContext>("creates checkout session with yearly price when billingPeriod is yearly", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -823,13 +799,11 @@ describe("Subscription Routes", () => {test<CustomTestContext>("throws error if user already has active subscription", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -850,13 +824,11 @@ describe("Subscription Routes", () => {describe("createPortalSession", () => {test<CustomTestContext>("creates portal session for user with subscription", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -886,13 +858,11 @@ describe("Subscription Routes", () => {test<CustomTestContext>("throws error if user has no subscription", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -905,13 +875,11 @@ describe("Subscription Routes", () => {describe("getQuotaUsage", () => {test<CustomTestContext>("returns quota usage for user with no data", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -933,13 +901,11 @@ describe("Subscription Routes", () => {test<CustomTestContext>("returns quota usage with bookmarks and assets", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -1005,11 +971,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Create existing subscription record@@ -1081,11 +1046,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Create existing subscription@@ -1155,11 +1119,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Create existing subscription@@ -1217,11 +1180,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// User has already upgraded to yearly; the active yearly subscription is@@ -1310,11 +1272,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});await db.insert(subscriptions).values({@@ -1456,11 +1417,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Set initial free tier quotas@@ -1540,11 +1500,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Set initial paid tier quotas (unlimited)@@ -1625,11 +1584,10 @@ describe("Subscription Routes", () => {db,unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});// Set initial paid tier quotas (unlimited)diff --git a/packages/trpc/routers/users.test.ts b/packages/trpc/routers/users.test.tsindex 168d200c..e65fddd1 100644--- a/packages/trpc/routers/users.test.ts+++ b/packages/trpc/routers/users.test.ts@@ -2,18 +2,22 @@ import { eq } from "drizzle-orm";import { assert, beforeEach, describe, expect, test, vi } from "vitest";import {+ accounts,assets,AssetTypes,bookmarks,- passwordResetTokens,subscriptions,users,} from "@karakeep/db/schema";import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";import type { CustomTestContext } from "../testUtils";-import * as emailModule from "../email";-import { defaultBeforeEach, getApiCaller } from "../testUtils";+import {+ CREDENTIAL_PROVIDER_ID,+ setUserPassword,+ verifyPasswordHash,+} from "../auth";+import { createTestUser, defaultBeforeEach, getApiCaller } from "../testUtils";// Mock server config with email settingsvi.mock("@karakeep/shared/config", async (original) => {@@ -40,109 +44,121 @@ vi.mock("@karakeep/shared/config", async (original) => {};});-// Mock email functions-vi.mock("../email", () => ({- sendPasswordResetEmail: vi.fn().mockResolvedValue(undefined),- sendVerificationEmail: vi.fn().mockResolvedValue(undefined),-}));-beforeEach<CustomTestContext>(defaultBeforeEach(false));describe("User Routes", () => {- test<CustomTestContext>("create user", async ({ unauthedAPICaller }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("create user", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",- email: "[email protected]",+ email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});expect(user.name).toEqual("Test User");+ // Emails are stored lowercasedexpect(user.email).toEqual("[email protected]");++ const dbUser = await db.query.users.findFirst({+ where: eq(users.id, user.id),+ });+ expect(dbUser?.emailVerified).toBe(false);++ // The password lives in a credential account, hashed+ const userAccounts = await db+ .select()+ .from(accounts)+ .where(eq(accounts.userId, user.id));+ expect(userAccounts).toHaveLength(1);+ expect(userAccounts[0].providerId).toBe(CREDENTIAL_PROVIDER_ID);+ expect(userAccounts[0].accountId).toBe(user.id);+ expect(userAccounts[0].password).not.toBe("pass1234");+ assert(userAccounts[0].password);+ expect(await verifyPasswordHash(userAccounts[0].password, "pass1234")).toBe(+ true,+ );});- test<CustomTestContext>("create user trims surrounding whitespace in name", async ({- unauthedAPICaller,+ test<CustomTestContext>("create user without password has no credential account", async ({+ db,}) => {- const user = await unauthedAPICaller.users.create({- name: " Test \n User ",- email: "[email protected]",- password: "pass1234",- confirmPassword: "pass1234",+ const user = await createTestUser(db, {+ name: "No Password User",+ email: "[email protected]",});- expect(user.name).toEqual("Test \n User");+ const userAccounts = await db+ .select()+ .from(accounts)+ .where(eq(accounts.userId, user.id));+ expect(userAccounts).toHaveLength(0);});- test<CustomTestContext>("create user rejects raw html in name", async ({- unauthedAPICaller,- }) => {- await expect(() =>- unauthedAPICaller.users.create({- name: "<script>alert('xss')</script>",- email: "[email protected]",- password: "pass1234",- confirmPassword: "pass1234",- }),- ).rejects.toThrow(/Name contains invalid characters/);- });-- test<CustomTestContext>("first user is admin", async ({- unauthedAPICaller,- }) => {- const user1 = await unauthedAPICaller.users.create({+ test<CustomTestContext>("first user is admin", async ({ db }) => {+ const user1 = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});- const user2 = await unauthedAPICaller.users.create({+ const user2 = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",+ });++ // An explicit role wins over the first-user rule+ const user3 = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ role: "admin",});expect(user1.role).toEqual("admin");expect(user2.role).toEqual("user");+ expect(user3.role).toEqual("admin");});- test<CustomTestContext>("unique emails", async ({ unauthedAPICaller }) => {- await unauthedAPICaller.users.create({+ test<CustomTestContext>("unique emails", async ({ db }) => {+ await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});await expect(() =>- unauthedAPICaller.users.create({+ createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",}),).rejects.toThrow(/Email is already taken/);++ // Uniqueness is case-insensitive since emails are stored lowercased+ await expect(() =>+ createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ }),+ ).rejects.toThrow(/Email is already taken/);++ // The failed attempts must not leave credential accounts behind+ const allAccounts = await db.select().from(accounts);+ expect(allAccounts).toHaveLength(1);});- test<CustomTestContext>("privacy checks", async ({- db,- unauthedAPICaller,- }) => {- const adminUser = await unauthedAPICaller.users.create({+ test<CustomTestContext>("privacy checks", async ({ db }) => {+ const adminUser = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const [user1, user2] = await Promise.all(["[email protected]", "[email protected]"].map((e) =>- unauthedAPICaller.users.create({+ createTestUser(db, {name: "Test User",email: e,password: "pass1234",- confirmPassword: "pass1234",}),),);@@ -164,15 +180,11 @@ describe("User Routes", () => {await expect(() => user2Caller.users.list()).rejects.toThrow(/FORBIDDEN/);});- test<CustomTestContext>("get/update user settings", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("get/update user settings", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -247,15 +259,11 @@ describe("User Routes", () => {);});- test<CustomTestContext>("user stats - empty user", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("user stats - empty user", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -290,15 +298,11 @@ describe("User Routes", () => {});});- test<CustomTestContext>("user stats - with data", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("user stats - with data", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -440,23 +444,18 @@ describe("User Routes", () => {expect(stats.bookmarkingActivity.byDayOfWeek).toHaveLength(7);});- test<CustomTestContext>("user stats - privacy isolation", async ({- db,- unauthedAPICaller,- }) => {+ test<CustomTestContext>("user stats - privacy isolation", async ({ db }) => {// Create two users- const user1 = await unauthedAPICaller.users.create({+ const user1 = await createTestUser(db, {name: "User 1",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});- const user2 = await unauthedAPICaller.users.create({+ const user2 = await createTestUser(db, {name: "User 2",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller1 = getApiCaller(db, user1.id);@@ -514,13 +513,11 @@ describe("User Routes", () => {test<CustomTestContext>("user stats - activity time patterns", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id);@@ -586,334 +583,12 @@ describe("User Routes", () => {).toBe(true);});- describe("Password Reset", () => {- test<CustomTestContext>("forgotPassword - successful email sending", async ({- unauthedAPICaller,- }) => {- // Create a user first- await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "pass1234",- confirmPassword: "pass1234",- });-- // With mocked email service, this should succeed- const result = await unauthedAPICaller.users.forgotPassword({- email: "[email protected]",- });-- expect(result.success).toBe(true);-- // Verify that the email function was called with correct parameters- expect(emailModule.sendPasswordResetEmail).toHaveBeenCalledWith(- "[email protected]",- "Test User",- expect.any(String), // token- );- });-- test<CustomTestContext>("forgotPassword - non-existing user", async ({- unauthedAPICaller,- }) => {- // Should not reveal if user exists or not- const result = await unauthedAPICaller.users.forgotPassword({- email: "[email protected]",- });-- expect(result.success).toBe(true);- });-- test<CustomTestContext>("forgotPassword - OAuth user (no password)", async ({- db,- unauthedAPICaller,- }) => {- // Create a user without password (OAuth user)- await db.insert(users).values({- name: "OAuth User",- email: "[email protected]",- password: null,- });-- // Should not send reset email for OAuth users- const result = await unauthedAPICaller.users.forgotPassword({- email: "[email protected]",- });-- expect(result.success).toBe(true);- });-- test<CustomTestContext>("resetPassword - valid token", async ({- db,- unauthedAPICaller,- }) => {- // Create a user- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });-- // Create a password reset token directly in the database- const token = "valid-reset-token";- const expires = new Date(Date.now() + 60 * 60 * 1000); // 1 hour from now-- await db.insert(passwordResetTokens).values({- userId: user.id,- token,- expires,- });-- // Reset the password- const result = await unauthedAPICaller.users.resetPassword({- token,- newPassword: "newpass123",- });-- expect(result.success).toBe(true);-- // Verify the token was consumed (deleted)- const remainingTokens = await db- .select()- .from(passwordResetTokens)- .where(eq(passwordResetTokens.token, token));-- expect(remainingTokens).toHaveLength(0);-- // The password reset was successful if we got here without errors- });-- test<CustomTestContext>("resetPassword - invalid token", async ({- unauthedAPICaller,- }) => {- await expect(- unauthedAPICaller.users.resetPassword({- token: "invalid-token",- newPassword: "newpass123",- }),- ).rejects.toThrow(/Invalid or expired reset token/);- });-- test<CustomTestContext>("resetPassword - expired token", async ({- db,- unauthedAPICaller,- }) => {- // Create a user- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });-- // Create an expired password reset token- const token = "expired-reset-token";- const expires = new Date(Date.now() - 60 * 60 * 1000); // 1 hour ago (expired)-- await db.insert(passwordResetTokens).values({- userId: user.id,- token,- expires,- });-- await expect(- unauthedAPICaller.users.resetPassword({- token,- newPassword: "newpass123",- }),- ).rejects.toThrow(/Invalid or expired reset token/);-- // Verify the expired token was cleaned up- const remainingTokens = await db- .select()- .from(passwordResetTokens)- .where(eq(passwordResetTokens.token, token));-- expect(remainingTokens).toHaveLength(0);- });-- test<CustomTestContext>("resetPassword - user not found", async ({- db,- unauthedAPICaller,- }) => {- // Create a user first, then delete them to create an orphaned token- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });-- // Create a password reset token- const token = "orphaned-token";- const expires = new Date(Date.now() + 60 * 60 * 1000);-- await db.insert(passwordResetTokens).values({- userId: user.id,- token,- expires,- });-- // Delete the user to make the token orphaned- // Due to foreign key cascade, this will also delete the token- // So we expect "Invalid or expired reset token" instead of "User not found"- await db.delete(users).where(eq(users.id, user.id));-- await expect(- unauthedAPICaller.users.resetPassword({- token,- newPassword: "newpass123",- }),- ).rejects.toThrow(/Invalid or expired reset token/);- });- test<CustomTestContext>("resetPassword - password validation", async ({- db,- unauthedAPICaller,- }) => {- // Create a user- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });-- // Create a password reset token- const token = "validation-token";- const expires = new Date(Date.now() + 60 * 60 * 1000);-- await db.insert(passwordResetTokens).values({- userId: user.id,- token,- expires,- });-- // Try to reset with a password that's too short- await expect(- unauthedAPICaller.users.resetPassword({- token,- newPassword: "123", // Too short- }),- ).rejects.toThrow();- });-- test<CustomTestContext>("resetPassword - token reuse prevention", async ({- db,- unauthedAPICaller,- }) => {- // Create a user- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });-- // Create a password reset token- const token = "reuse-token";- const expires = new Date(Date.now() + 60 * 60 * 1000);-- await db.insert(passwordResetTokens).values({- userId: user.id,- token,- expires,- });-- // Use the token once- await unauthedAPICaller.users.resetPassword({- token,- newPassword: "newpass123",- });-- // Try to use the same token again- await expect(- unauthedAPICaller.users.resetPassword({- token,- newPassword: "anotherpass123",- }),- ).rejects.toThrow(/Invalid or expired reset token/);- });- });-- describe("Change Password", () => {- test<CustomTestContext>("changePassword - successful change", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });- const caller = getApiCaller(db, user.id, user.email, user.role || "user");-- await caller.users.changePassword({- currentPassword: "oldpass123",- newPassword: "newpass456",- });-- // Password change should succeed without throwing- });-- test<CustomTestContext>("changePassword - wrong current password", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "oldpass123",- confirmPassword: "oldpass123",- });- const caller = getApiCaller(db, user.id, user.email, user.role || "user");-- await expect(() =>- caller.users.changePassword({- currentPassword: "wrongpassword",- newPassword: "newpass456",- }),- ).rejects.toThrow();- });-- test<CustomTestContext>("changePassword - OAuth user (no password)", async ({- db,- }) => {- // Create OAuth user without password- await db.insert(users).values({- name: "OAuth User",- email: "[email protected]",- password: null,- });-- const oauthUser = await db- .select()- .from(users)- .where(eq(users.email, "[email protected]"))- .then((rows) => rows[0]);-- const caller = getApiCaller(db, oauthUser.id, oauthUser.email, "user");-- await expect(() =>- caller.users.changePassword({- currentPassword: "anypassword",- newPassword: "newpass456",- }),- ).rejects.toThrow();- });- });-describe("Delete Account", () => {- test<CustomTestContext>("deleteAccount - with password", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("deleteAccount - with password", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id, user.email, user.role || "user");@@ -931,13 +606,11 @@ describe("User Routes", () => {test<CustomTestContext>("deleteAccount refuses active Stripe subscription", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id, user.email, user.role || "user");@@ -966,13 +639,11 @@ describe("User Routes", () => {test<CustomTestContext>("deleteAccount - wrong password", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id, user.email, user.role || "user");@@ -986,11 +657,10 @@ describe("User Routes", () => {test<CustomTestContext>("deleteAccount - OAuth user (no password)", async ({db,}) => {- // Create OAuth user without password+ // OAuth users have no credential accountawait db.insert(users).values({name: "OAuth User",email: "[email protected]",- password: null,});const oauthUser = await db@@ -1015,13 +685,11 @@ describe("User Routes", () => {describe("Update Avatar", () => {test<CustomTestContext>("updateAvatar - promotes unknown asset", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Avatar Reject",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id, user.email, user.role || "user");@@ -1048,13 +716,11 @@ describe("User Routes", () => {test<CustomTestContext>("updateAvatar - deletes avatar asset", async ({db,- unauthedAPICaller,}) => {- const user = await unauthedAPICaller.users.create({+ const user = await createTestUser(db, {name: "Avatar Delete",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id, user.email, user.role || "user");@@ -1088,15 +754,11 @@ describe("User Routes", () => {});describe("Who Am I", () => {- test<CustomTestContext>("whoami - returns user info", async ({- db,- unauthedAPICaller,- }) => {- const user = await unauthedAPICaller.users.create({+ test<CustomTestContext>("whoami - returns user info", async ({ db }) => {+ const user = await createTestUser(db, {name: "Test User",email: "[email protected]",password: "pass1234",- confirmPassword: "pass1234",});const caller = getApiCaller(db, user.id, user.email, user.role || "user");@@ -1109,11 +771,10 @@ describe("User Routes", () => {});test<CustomTestContext>("whoami - OAuth user", async ({ db }) => {- // Create OAuth user+ // OAuth users only have a non-credential accountawait db.insert(users).values({name: "OAuth User",email: "[email protected]",- password: null,});const oauthUser = await db@@ -1122,6 +783,12 @@ describe("User Routes", () => {.where(eq(users.email, "[email protected]")).then((rows) => rows[0]);+ await db.insert(accounts).values({+ userId: oauthUser.id,+ providerId: "custom",+ accountId: "oauth-account-id",+ });+const caller = getApiCaller(db, oauthUser.id, oauthUser.email, "user");const whoami = await caller.users.whoami();@@ -1131,77 +798,39 @@ describe("User Routes", () => {expect(whoami.email).toBe("[email protected]");expect(whoami.localUser).toBe(false);});- });-- describe("Email Verification", () => {- test<CustomTestContext>("verifyEmail - invalid token", async ({- unauthedAPICaller,- }) => {- await expect(() =>- unauthedAPICaller.users.verifyEmail({- email: "[email protected]",- token: "invalid-token",- }),- ).rejects.toThrow();- });-- test<CustomTestContext>("verifyEmail - invalid email format", async ({- unauthedAPICaller,- }) => {- await expect(() =>- unauthedAPICaller.users.verifyEmail({- email: "invalid-email",- token: "some-token",- }),- ).rejects.toThrow();- });- });- describe("Resend Verification Email", () => {- test<CustomTestContext>("resendVerificationEmail - existing user", async ({- unauthedAPICaller,+ test<CustomTestContext>("whoami - becomes local once a password is set", async ({+ db,}) => {- // Create user first- await unauthedAPICaller.users.create({- name: "Test User",- email: "[email protected]",- password: "pass1234",- confirmPassword: "pass1234",+ const user = await createTestUser(db, {+ name: "Late Password",+ email: "[email protected]",});+ const caller = getApiCaller(db, user.id, user.email, user.role || "user");- const result = await unauthedAPICaller.users.resendVerificationEmail({- email: "[email protected]",- });+ expect((await caller.users.whoami()).localUser).toBe(false);- expect(result.success).toBe(true);+ await setUserPassword(db, user.id, "pass1234");- // Verify that the email function was called- expect(emailModule.sendVerificationEmail).toHaveBeenCalledWith(- "[email protected]",- "Test User",- expect.any(String), // token- undefined, // redirectUrl- );+ expect((await caller.users.whoami()).localUser).toBe(true);});- test<CustomTestContext>("resendVerificationEmail - non-existing user", async ({- unauthedAPICaller,+ test<CustomTestContext>("whoami - credential account without password is not local", async ({+ db,}) => {- // Should not reveal if user exists or not- const result = await unauthedAPICaller.users.resendVerificationEmail({- email: "[email protected]",+ const user = await createTestUser(db, {+ name: "Empty Credential",+ email: "[email protected]",});- expect(result.success).toBe(true);- });+ await db.insert(accounts).values({+ userId: user.id,+ providerId: CREDENTIAL_PROVIDER_ID,+ accountId: user.id,+ password: null,+ });+ const caller = getApiCaller(db, user.id, user.email, user.role || "user");- test<CustomTestContext>("resendVerificationEmail - invalid email format", async ({- unauthedAPICaller,- }) => {- await expect(() =>- unauthedAPICaller.users.resendVerificationEmail({- email: "invalid-email",- }),- ).rejects.toThrow();+ expect((await caller.users.whoami()).localUser).toBe(false);});});});diff --git a/packages/trpc/routers/users.ts b/packages/trpc/routers/users.tsindex 374cac76..fe2a9cb6 100644--- a/packages/trpc/routers/users.ts+++ b/packages/trpc/routers/users.ts@@ -2,97 +2,26 @@ import { TRPCError } from "@trpc/server";import { z } from "zod";import { addLogFields } from "@karakeep/shared-server";-import serverConfig from "@karakeep/shared/config";import {- zResetPasswordSchema,- zSignUpSchema,zUpdateUserSettingsSchema,zUserSettingsSchema,zUserStatsResponseSchema,zWhoAmIResponseSchema,zWrappedStatsResponseSchema,} from "@karakeep/shared/types/users";-import { validateRedirectUrl } from "@karakeep/shared/utils/redirectUrl";import {createAdminScopedProcedure,createEventLogMiddleware,- 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(- createRateLimitMiddleware({- name: "users.create",- windowMs: 60 * 1000,- maxRequests: 3,- }),- )- .use(createEventLogMiddleware("user.signup"))- .input(zSignUpSchema.safeExtend({ redirectUrl: z.string().optional() }))- .output(- z.object({- id: z.string(),- name: z.string(),- email: z.string(),- role: z.enum(["user", "admin"]).nullable(),- }),- )- .mutation(async ({ input, ctx }) => {- addLogFields<"user.signup">({ "auth.provider": "credentials" });- if (- serverConfig.auth.disableSignups ||- serverConfig.auth.disablePasswordAuth- ) {- const failureReason = serverConfig.auth.disablePasswordAuth- ? "password_auth_disabled"- : "signups_disabled";- const errorMessage = serverConfig.auth.disablePasswordAuth- ? "Local Signups are disabled in the server config. Use OAuth instead!"- : "Signups are disabled in server config";- addLogFields<"user.signup">({ "auth.failure_reason": failureReason });- throw new TRPCError({- code: "FORBIDDEN",- message: errorMessage,- });- }- if (serverConfig.auth.turnstile.enabled) {- const result = await verifyTurnstileToken(- input.turnstileToken ?? "",- ctx.req.ip,- );- if (!result.success) {- addLogFields<"user.signup">({- "auth.failure_reason": "turnstile_failed",- });- throw new TRPCError({- code: "BAD_REQUEST",- message: "Turnstile verification failed",- });- }- }- const validatedRedirectUrl = validateRedirectUrl(input.redirectUrl);- const user = await User.create(ctx, {- ...input,- redirectUrl: validatedRedirectUrl,- });- addLogFields<"user.signup">({ "user.id": user.id });- return {- id: user.id,- name: user.name,- email: user.email,- role: user.role,- };- }),list: adminUsersProcedure.output(z.object({@@ -102,7 +31,6 @@ export const usersAppRouter = router({name: z.string(),email: z.string(),role: z.enum(["user", "admin"]).nullable(),- localUser: z.boolean(),bookmarkQuota: z.number().nullable(),storageQuota: z.number().nullable(),}),@@ -112,28 +40,9 @@ export const usersAppRouter = router({.query(async ({ ctx }) => {const users = await User.getAll(ctx);return {- users: users.map((u) => u.asPublicUser()),+ users: users.map((u) => u.user),};}),- changePassword: usersProcedure- .use(- createRateLimitMiddleware({- name: "users.changePassword",- windowMs: 15 * 60 * 1000,- maxRequests: 5,- }),- )- .use(createEventLogMiddleware("user.password_change"))- .input(- z.object({- currentPassword: z.string(),- newPassword: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- const user = await User.fromCtx(ctx);- await user.changePassword(input.currentPassword, input.newPassword);- }),delete: adminUsersProcedure.use(createEventLogMiddleware("user.delete")).input(@@ -167,7 +76,7 @@ export const usersAppRouter = router({.output(zWhoAmIResponseSchema).query(async ({ ctx }) => {const user = await User.fromCtx(ctx);- return user.asWhoAmI();+ return await user.asWhoAmI();}),stats: usersProcedure.output(zUserStatsResponseSchema)@@ -215,75 +124,4 @@ export const usersAppRouter = router({const user = await User.fromCtx(ctx);await user.updateAvatar(input.assetId);}),- verifyEmail: publicProcedure- .use(- createRateLimitMiddleware({- name: "users.verifyEmail",- windowMs: 5 * 60 * 1000,- maxRequests: 10,- }),- )- .input(- z.object({- email: z.string().email(),- token: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- await User.verifyEmail(ctx, input.email, input.token);- return { success: true };- }),- resendVerificationEmail: publicProcedure- .use(- createRateLimitMiddleware({- name: "users.resendVerificationEmail",- windowMs: 5 * 60 * 1000,- maxRequests: 3,- }),- )- .input(- z.object({- email: z.string().email(),- redirectUrl: z.string().optional(),- }),- )- .mutation(async ({ input, ctx }) => {- const validatedRedirectUrl = validateRedirectUrl(input.redirectUrl);- await User.resendVerificationEmail(- ctx,- input.email,- validatedRedirectUrl,- );- return { success: true };- }),- forgotPassword: publicProcedure- .use(- createRateLimitMiddleware({- name: "users.forgotPassword",- windowMs: 15 * 60 * 1000,- maxRequests: 3,- }),- )- .input(- z.object({- email: z.string().email(),- }),- )- .mutation(async ({ input, ctx }) => {- await User.forgotPassword(ctx, input.email);- return { success: true };- }),- resetPassword: publicProcedure- .use(- createRateLimitMiddleware({- name: "users.resetPassword",- windowMs: 5 * 60 * 1000,- maxRequests: 10,- }),- )- .input(zResetPasswordSchema)- .mutation(async ({ input, ctx }) => {- await User.resetPassword(ctx, input);- return { success: true };- }),});diff --git a/packages/trpc/testUtils.ts b/packages/trpc/testUtils.tsindex 15dcb230..8b7a4598 100644--- a/packages/trpc/testUtils.ts+++ b/packages/trpc/testUtils.ts@@ -5,6 +5,7 @@ import { users } from "@karakeep/db/schema";import type { Context } from "./index";import { createCallerFactory } from "./index";+import { User } from "./models/users";import { appRouter } from "./routers/_app";const testQueueMocks = vi.hoisted(() => ({@@ -49,6 +50,29 @@ export async function seedUsers(db: TestDB) {.returning();}+/**+ * Creates a user (and, when a password is given, its credential account) the+ * same way the app does, returning the shape the old `users.create` procedure+ * returned.+ */+export async function createTestUser(+ db: TestDB,+ input: {+ name: string;+ email: string;+ password?: string;+ role?: "user" | "admin";+ },+) {+ const user = await User.createRaw(db, input);+ return {+ id: user.id,+ name: user.name,+ email: user.email,+ role: user.role,+ };+}+export function getApiCaller(db: TestDB,userId?: string,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 39021936..965cce56 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -332,7 +332,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/mobile:dependencies:@@ -568,9 +568,6 @@ importers:apps/web:dependencies:- '@auth/drizzle-adapter':- specifier: ~1.11.3- version: 1.11.3'@emoji-mart/data':specifier: ^1.1.2version: 1.1.2@@ -616,6 +613,9 @@ importers:'@marsidev/react-turnstile':specifier: ^1.3.1+ '@paralleldrive/cuid2':+ specifier: ^2.2.2+ version: 2.2.2'@radix-ui/react-avatar':specifier: ^1.1.11version: 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -712,6 +712,9 @@ importers:ai:specifier: ^6.0.286version: 6.0.286([email protected])+ better-auth:+ specifier: 1.6.25+ version: 1.6.25(@opentelemetry/[email protected])([email protected])([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])))better-sqlite3:specifier: ^13.0.3version: 13.0.3@@ -735,7 +738,7 @@ importers:version: 3.6.0drizzle-orm:specifier: ^0.45.2+ version: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])fastest-levenshtein:specifier: ^1.0.16version: 1.0.16@@ -760,9 +763,6 @@ importers:next:specifier: 16.3.8version: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])- next-auth:- specifier: ^4.24.15- version: 4.24.15([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])next-i18next:specifier: ^15.3.1version: 15.3.1([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -955,7 +955,7 @@ importers:version: 16.4.5drizzle-orm:specifier: ^0.45.2+ version: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])execa:specifier: 9.3.1version: 9.3.1@@ -979,52 +979,52 @@ importers:version: 24.1.3liteque:specifier: ^0.9.1- version: 0.9.1(@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ version: 0.9.1(@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])lru-cache:specifier: ^11.2.2version: 11.2.2metascraper:specifier: ^5.58.1- version: 5.58.1(@noble/[email protected])([email protected])+ version: 5.58.1(@noble/[email protected])([email protected])metascraper-amazon:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-author:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-date:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-description:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-image:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-logo:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-logo-favicon:specifier: 5.53.0- version: 5.53.0(@noble/[email protected])([email protected])+ version: 5.53.0(@noble/[email protected])([email protected])metascraper-publisher:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-readability:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-title:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-url:specifier: ^5.56.2- version: 5.56.2(@noble/[email protected])([email protected])+ version: 5.56.2(@noble/[email protected])([email protected])metascraper-x:specifier: ^5.58.1- version: 5.58.1(@noble/[email protected])([email protected])+ version: 5.58.1(@noble/[email protected])([email protected])metascraper-youtube:specifier: ^5.58.1- version: 5.58.1(@noble/[email protected])([email protected])+ version: 5.58.1(@noble/[email protected])([email protected])node-cron:specifier: ^3.0.3version: 3.0.3@@ -1161,7 +1161,7 @@ importers:version: 11.9.0([email protected])drizzle-orm:specifier: ^0.45.2+ version: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])file-type:specifier: ^21.3.4version: 21.3.4@@ -1195,7 +1195,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/benchmarks:dependencies:@@ -1233,9 +1233,6 @@ importers:packages/db:dependencies:- '@auth/core':- specifier: ^0.41.3- version: 0.41.3'@karakeep/shared':specifier: workspace:*version: link:../shared@@ -1256,7 +1253,7 @@ importers:version: 0.31.10drizzle-orm:specifier: ^0.45.2+ version: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])tsx:specifier: ^4.23.13version: 4.23.13@@ -1315,7 +1312,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/open-api:dependencies:@@ -1358,7 +1355,7 @@ importers:version: 11.1.0liteque:specifier: ^0.9.1- version: 0.9.1(@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ version: 0.9.1(@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])meilisearch:specifier: ^0.58.0version: 0.58.0@@ -1374,7 +1371,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sdk:dependencies:@@ -1448,7 +1445,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/shared-react:dependencies:@@ -1558,7 +1555,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/trpc:dependencies:@@ -1582,7 +1579,7 @@ importers:version: 2.2.3drizzle-orm:specifier: ^0.45.2+ version: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])nodemailer:specifier: ^9.1.1version: 9.1.1@@ -1625,7 +1622,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))tooling/github: {}@@ -1990,23 +1987,6 @@ packages:'@astrojs/[email protected]':resolution: {integrity: sha512-8oddpOae35pJsXPQXhTkM0ypfKPskVsh2bCxRtbf7e+/Epw2nReakFYpLKjZMEr75CsoF203PMnCocpfz0s69A==}- '@auth/[email protected]':- resolution: {integrity: sha512-sJ3JMHHkXMD3aOjopv7mOBTO1Ocw4b0fAEXJBz6k7YHLpYQI6C40jCUPc5fNvUKxXRXNE1/sRISA15UrwWJBTw==}- peerDependencies:- '@simplewebauthn/browser': ^9.0.1- '@simplewebauthn/server': ^9.0.2- nodemailer: ^7.0.7 || ^8.0.5- peerDependenciesMeta:- '@simplewebauthn/browser':- optional: true- '@simplewebauthn/server':- optional: true- nodemailer:- optional: true-- '@auth/[email protected]':- resolution: {integrity: sha512-TxqVasPVuf7LDAT1Yuu6bftpuet8o0tjdXW+mXpnXWdSRPQsomdzMoz9RsXkFN/JfdK+/DwdgOEmOTv1gbiFNw==}-'@aws-sdk/[email protected]':resolution: {integrity: sha512-6uTniZc87q+B5eXouGTl+7Tmc482rEeCcvxpsvREP8EfF0gvloRZ41UOA9sbSJlyy8TbqIBXb3kKfKarEArUQA==}engines: {node: '>=20.0.0'}@@ -3216,6 +3196,88 @@ packages:resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}engines: {node: '>=6.9.0'}+ '@better-auth/[email protected]':+ resolution: {integrity: sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw==}+ peerDependencies:+ '@better-auth/utils': 0.4.2+ '@better-fetch/fetch': 1.3.1+ '@cloudflare/workers-types': '>=4'+ '@opentelemetry/api': ^1.9.0+ better-call: 1.3.7+ jose: ^6.1.0+ kysely: ^0.28.5 || ^0.29.0+ nanostores: ^1.0.1+ peerDependenciesMeta:+ '@cloudflare/workers-types':+ optional: true+ '@opentelemetry/api':+ optional: true++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-ru/DeKjFPQUVeKkxF/ScazmPqIY7lwfkAV5Yt4j24wmn1Y8vFwoiPRnHgXUeZqBs10+nubaRwEqLF39CP6EhRw==}+ peerDependencies:+ '@better-auth/core': ^1.6.25+ '@better-auth/utils': 0.4.2+ drizzle-orm: ^0.45.2+ peerDependenciesMeta:+ drizzle-orm:+ optional: true++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-zxiePhtN1YClS1irKYPVwWfN6kYp+QoYlz1hdQUOj8hXyo2aE/ny4RNAb6v332b0+U6Vu88EhYITRPdmvCo6uA==}+ peerDependencies:+ '@better-auth/core': ^1.6.25+ '@better-auth/utils': 0.4.2+ kysely: ^0.28.17 || ^0.29.0+ peerDependenciesMeta:+ kysely:+ optional: true++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-GhEzTumc8yfTz+OZ6pMg06BA49xob49x1bX+1mEl/FStDJoSF+6mTfI5M2ytFxaiN89336/aUjkW8u+qRyLexw==}+ peerDependencies:+ '@better-auth/core': ^1.6.25+ '@better-auth/utils': 0.4.2++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-ZtMmjcOdXR2Ziqx5y8ptTOaNpe0snNfALbBUPXJsgeyeRkDJDYzyLZ8MpuvNBTNllNeIFDbiXWAK5k+pEBZrUQ==}+ peerDependencies:+ '@better-auth/core': ^1.6.25+ '@better-auth/utils': 0.4.2+ mongodb: ^6.0.0 || ^7.0.0+ peerDependenciesMeta:+ mongodb:+ optional: true++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-ym7B6Iqcry+/4aQnYpFwqP/GBIiXvjrm/5B6+0qmx8mkTY/apHFTpHuGzUYYNf4vPTtzF3eYY2+s2GOsomKaRg==}+ peerDependencies:+ '@better-auth/core': ^1.6.25+ '@better-auth/utils': 0.4.2+ '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0+ prisma: ^5.0.0 || ^6.0.0 || ^7.0.0+ peerDependenciesMeta:+ '@prisma/client':+ optional: true+ prisma:+ optional: true++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-2ZfC9lp7tU6Jw/q2Lz/bKfQqGMdMwc/IQDTYdBhvtGi24qInYVnhp2ZCW57hHM9j+fq1ULOtxgg6M3T1LEaihw==}+ peerDependencies:+ '@better-auth/core': ^1.6.25+ '@better-auth/utils': 0.4.2+ '@better-fetch/fetch': 1.3.1++ '@better-auth/[email protected]':+ resolution: {integrity: sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A==}++ '@better-fetch/[email protected]':+ resolution: {integrity: sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g==}++ '@better-fetch/[email protected]':+ resolution: {integrity: sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow==}+'@borewit/[email protected]':resolution: {integrity: sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==}@@ -5389,6 +5451,10 @@ packages:cpu: [x64]os: [win32]+ '@noble/[email protected]':+ resolution: {integrity: sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==}+ engines: {node: '>= 20.19.0'}+'@noble/[email protected]':resolution: {integrity: sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==}engines: {node: '>= 16'}@@ -5397,6 +5463,10 @@ packages:resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}engines: {node: ^14.21.3 || >=16}+ '@noble/[email protected]':+ resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}+ engines: {node: '>= 20.19.0'}+'@nodelib/[email protected]':resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}engines: {node: '>= 8'}@@ -5527,6 +5597,10 @@ packages:resolution: {integrity: sha512-kocjix+/sSggfJhwXqClZ3i9Y/MI0fp7b+g7kCRm6psy2dsf8uApTRclwG18h8Avm7C9+fnt+O36PspJ/OzoWg==}engines: {node: '>=14'}+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==}+ engines: {node: '>=14'}+'@opentelemetry/[email protected]':resolution: {integrity: sha512-5HH2a1KwKkXzxzR9Y0l2TIXfVYKtWIZJes2swr8D8KFSZfNceKsBlz3eUCmwe+4FVczsGs9gUKBecwdEMwWSNw==}engines: {node: ^18.19.0 || >=20.6.0}@@ -5788,9 +5862,6 @@ packages:cpu: [x64]os: [win32]- '@panva/[email protected]':- resolution: {integrity: sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==}-'@paralleldrive/[email protected]':resolution: {integrity: sha512-ZOBkgDwEdoYVlSeRbYYXs0S9MejQofiVYoTbKzy/6GQa39/q5tQU2IX46+shYnUkpEl3wc+J6wRlar7r2EK2xA==}@@ -8708,6 +8779,76 @@ packages:resolution: {integrity: sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==}+ resolution: {integrity: sha512-fvoq+oCO+FF5fpP3XfU7znRyGFpHB77UG2EyxsKNy+Cak7Q5pELu+auvvDveQbWQxcoKugZ7jYQQPFQLpUTGOw==}+ peerDependencies:+ '@lynx-js/react': '*'+ '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0+ '@sveltejs/kit': ^2.0.0+ '@tanstack/react-start': ^1.0.0+ '@tanstack/solid-start': ^1.0.0+ better-sqlite3: ^12.0.0+ drizzle-kit: '>=0.31.4'+ drizzle-orm: ^0.45.2+ mongodb: ^6.0.0 || ^7.0.0+ mysql2: ^3.0.0+ next: ^14.0.0 || ^15.0.0 || ^16.0.0+ pg: ^8.0.0+ prisma: ^5.0.0 || ^6.0.0 || ^7.0.0+ react: 19.2.3+ react-dom: 19.2.3+ solid-js: ^1.0.0+ svelte: ^4.0.0 || ^5.0.0+ vitest: ^2.0.0 || ^3.0.0 || ^4.0.0+ vue: ^3.0.0+ peerDependenciesMeta:+ '@lynx-js/react':+ optional: true+ '@prisma/client':+ optional: true+ '@sveltejs/kit':+ optional: true+ '@tanstack/react-start':+ optional: true+ '@tanstack/solid-start':+ optional: true+ better-sqlite3:+ optional: true+ drizzle-kit:+ optional: true+ drizzle-orm:+ optional: true+ mongodb:+ optional: true+ mysql2:+ optional: true+ next:+ optional: true+ pg:+ optional: true+ prisma:+ optional: true+ react:+ optional: true+ react-dom:+ optional: true+ solid-js:+ optional: true+ svelte:+ optional: true+ vitest:+ optional: true+ vue:+ optional: true++ resolution: {integrity: sha512-Al51/hjp2SSp6CRTa3F2ptcx4yQVS1xWKoY6jcVXqNYOap6mHFP2jUBn5EwIL4iIed1/Sq4hlQ+Umm6EflZG+w==}+ peerDependencies:+ zod: ^4.0.0+ peerDependenciesMeta:+ zod:+ optional: true+resolution: {integrity: sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==}engines: {node: '>=22'}@@ -9808,9 +9949,6 @@ packages:resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-pwdBJxJuJXmqrLO6s0VBmfbRz+G7FUzkjldAsdi9Yrv86mPyzq0ll1o8+8gB4Gsr6GJHbK1Lh3ngllgTInDCjA==}-resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==}@@ -11960,9 +12098,6 @@ packages:resolution: {integrity: sha512-ImNZaq/LSysofih+xIGYfR0WUXMA9GLUNB//YTCSrZptoRmVgaNAdJyi6K1kXi9pkLEoSkoI8I4UwtNiu/D7nw==}- resolution: {integrity: sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==}-resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}@@ -12096,6 +12231,10 @@ packages:resolution: {integrity: sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==}+ resolution: {integrity: sha512-hHaB8C/rfzDDtr/t8YZwxAuPJTT0zHyaPoVzcXwDYhYNAgH/4sIfVhi/XLLIY+bL/FqaIJnjATDbi8ObSELmxg==}+ engines: {node: '>=22.0.0'}+resolution: {integrity: sha512-ONPnazC96VKDntab9j9JKwIWhZ4ZUceB4A9Epu4Ssg0hYFmtHZSeQ+n15nIwTFmcBUKtExOer8WTJ4GF9MO64A==}hasBin: true@@ -12396,10 +12535,6 @@ packages:resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}- resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==}- engines: {node: '>=10'}-resolution: {integrity: sha512-S3A4PSEGbZkvHKro6jkmgOBswxd+IYdnfr+xRqPlJHjfqRccTrj0dK5cGQzgLVmXD0e+oKZr17uRVcrr/RQVpw==}peerDependencies:@@ -13184,6 +13319,10 @@ packages:engines: {node: ^18 || >=20}hasBin: true+ resolution: {integrity: sha512-4UXY7OAJEK0Y6V3SudBU7cXjAzTDc189R78dDOh0Xbm19gpKYto6WizSg58LJf12lTsRxKSLGyE117OiLpM4DQ==}+ engines: {node: ^20.0.0 || >=22.0.0}+resolution: {integrity: sha512-kLPRH3Yh/hhIFufXzUZDe39fuK471GwaPBCqYNgcRygILr+obV+wFfDmG+zaJnniVUFFQzYOTCEldem6XktZ+A==}engines: {node: '>=16'}@@ -13213,20 +13352,6 @@ packages:resolution: {integrity: sha512-WmmLty1YWwJl9yZi77v2dVIV6X2kuYV8YYBI/G3LWGKdGHmHUvL1z7FW0iDvEvGAwNEoc5x1tOOOyDnf5jJw/w==}engines: {node: '>= 10'}- resolution: {integrity: sha512-NnjYtjrSOAx/TIVFGTX4IfI/9yHnNpi4B7FuLUwuV20v2Zxgr2OGP/YN0ynJuI7y8QOnTBPitfOdEXZrVvhIuA==}- peerDependencies:- '@auth/core': 0.34.3- next: ^12.2.5 || ^13 || ^14 || ^15 || ^16- nodemailer: ^7.0.7- react: 19.2.3- react-dom: 19.2.3- peerDependenciesMeta:- '@auth/core':- optional: true- nodemailer:- optional: true-resolution: {integrity: sha512-+pa2pZJb7B6k5PKW3TLVMmAodqkNaOBWVYlpWX56mgcEJz0UMW+MKSdKM9Z72CHp6Bp48g7OWwDnLqxXNp/84w==}engines: {node: '>=14'}@@ -13442,12 +13567,6 @@ packages:resolution: {integrity: sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==}- resolution: {integrity: sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==}-- resolution: {integrity: sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==}-resolution: {integrity: sha512-QyQQ6e66f+Ut/qUVjEce0E/wux5nAGLXYZDn1jr15JWstHsCH3l6VVrg8NKDptW9NEiBXKOJeGF/ydxeSDF3IQ==}engines: {node: '>=18.18'}@@ -13464,10 +13583,6 @@ packages:resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}engines: {node: '>=0.10.0'}- resolution: {integrity: sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==}- engines: {node: '>= 6'}-resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==}engines: {node: '>= 6'}@@ -13501,10 +13616,6 @@ packages:resolution: {integrity: sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==}- resolution: {integrity: sha512-y0W+X7Ppo7oZX6eovsRkuzcSM40Bicg2JEJkDJ4irIt1wsYAP5MLSNv+QAogO8xivMffw/9OvV3um1pxXgt1uA==}- engines: {node: ^10.13.0 || >=12.0.0}-resolution: {integrity: sha512-q5LmPtk6GLFouS+3aURIVl+qcAOPC4+Msmx7uBb3pd+fxI55WnGjmLZ0yijI/CYy79x0QPGx3BwC3u5zv9fBvQ==}@@ -13601,9 +13712,6 @@ packages:resolution: {integrity: sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==}hasBin: true- resolution: {integrity: sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==}-resolution: {integrity: sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg==}engines: {node: '>=6'}@@ -14385,22 +14493,6 @@ packages:resolution: {integrity: sha512-EOgUMBazo7JNP4TDrd64TsooCiWzzo4143Ws8E8WYGEpn2PKpq+S4XRTDhuRTYHm3VKOpUZs7ZYZq7zSDuesqA==}engines: {node: '>=10'}- resolution: {integrity: sha512-aPDxUn5o3GhWdtJtW0svRC2SS/l8D9MAgo2+AWml+BhDImb27ALf04Q2d+AHqUUOc6RdSXFIBVa2gxzgMKgtZA==}- peerDependencies:- preact: '>=10'-- resolution: {integrity: sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==}- peerDependencies:- preact: '>=10'-- resolution: {integrity: sha512-eY93IVpod/zG3uMF22Unl8h9KkrcKIRs2EGar8hwLZZDU1lkjph303V9HZBwufh2s736U6VXuhD109LYqPoffg==}-- resolution: {integrity: sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==}-resolution: {integrity: sha512-Puaz+wPUAhFp8Lo9HuciYKM2Y2XExESjeT+9NQoVFXZsPPnc9VYss2SpxdQ6vbatmt8/4+SN0oe0I1cPDABg9Q==}engines: {node: '>=14.21.3'}@@ -14469,9 +14561,6 @@ packages:resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==}engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}- resolution: {integrity: sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==}-resolution: {integrity: sha512-973driJZvxiGOQ5ONsFhOF/DtzPMOMtgC11kCpUrPGMTgqp2q/1gwzCquocrN33is0VZ5GFHXZYMM9l6h67v2Q==}engines: {node: '>=10'}@@ -15375,6 +15464,9 @@ packages:engines: {node: '>=10.0.0'}hasBin: true+ resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==}+resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}@@ -15593,6 +15685,9 @@ packages:resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==}+ resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==}+resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}engines: {node: '>= 0.4'}@@ -16773,10 +16868,6 @@ packages:resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}engines: {node: '>= 0.4.0'}- resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}- hasBin: true-resolution: {integrity: sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==}hasBin: true@@ -17413,9 +17504,6 @@ packages:resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}- resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==}-resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}engines: {node: '>=18'}@@ -17885,22 +17973,6 @@ snapshots:dependencies:yaml: 2.9.1- '@auth/[email protected]':- dependencies:- '@panva/hkdf': 1.2.1- jose: 6.2.12- oauth4webapi: 3.8.8- preact: 10.24.3- preact-render-to-string: 6.5.11([email protected])-- '@auth/[email protected]':- dependencies:- '@auth/core': 0.41.3- transitivePeerDependencies:- - '@simplewebauthn/browser'- - '@simplewebauthn/server'- - nodemailer-'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.978.0@@ -19512,6 +19584,63 @@ snapshots:'@babel/helper-string-parser': 7.29.7'@babel/helper-validator-identifier': 7.29.7+ '@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':+ dependencies:+ '@better-auth/utils': 0.4.2+ '@better-fetch/fetch': 1.3.1+ '@opentelemetry/semantic-conventions': 1.43.0+ '@standard-schema/spec': 1.1.0+ better-call: 1.3.7([email protected])+ jose: 6.2.12+ kysely: 0.29.6+ nanostores: 1.5.4+ zod: 4.6.5+ optionalDependencies:+ '@opentelemetry/api': 1.9.0++ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/utils': 0.4.2+ optionalDependencies:+ drizzle-orm: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])++ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])':+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/utils': 0.4.2+ optionalDependencies:+ kysely: 0.29.6++ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/utils': 0.4.2++ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/utils': 0.4.2++ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/utils': 0.4.2++ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])':+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/utils': 0.4.2+ '@better-fetch/fetch': 1.3.1++ '@better-auth/[email protected]':+ dependencies:+ '@noble/hashes': 2.4.0++ '@better-fetch/[email protected]': {}++ '@better-fetch/[email protected]': {}+'@borewit/[email protected]': {}'@braintree/[email protected]': {}@@ -21285,9 +21414,9 @@ snapshots:'@esbuild/[email protected]':optional: true- '@exodus/[email protected](@noble/[email protected])':+ '@exodus/[email protected](@noble/[email protected])':optionalDependencies:- '@noble/hashes': 1.8.0+ '@noble/hashes': 2.4.0'@exodus/[email protected]': {}@@ -22367,7 +22496,7 @@ snapshots:dependencies:'@chevrotain/types': 11.1.2dependencies:audio-extensions: 0.0.0chrono-node: 2.10.1@@ -22382,7 +22511,7 @@ snapshots:is-uri: 1.2.14iso-639-3: 3.0.1isostring: 0.0.1- jsdom: 30.0.1(@noble/[email protected])+ jsdom: 30.0.1(@noble/[email protected])jsonrepair: 3.15.0lodash: 4.18.1memoize-one: 6.0.0@@ -22399,7 +22528,7 @@ snapshots:- canvas- debugdependencies:audio-extensions: 0.0.0chrono-node: 2.10.1@@ -22414,7 +22543,7 @@ snapshots:is-uri: 1.2.14iso-639-3: 3.0.1isostring: 0.0.1- jsdom: 30.0.1(@noble/[email protected])+ jsdom: 30.0.1(@noble/[email protected])jsonrepair: 3.15.0lodash: 4.18.1memoize-one: 6.0.0@@ -22472,7 +22601,7 @@ snapshots:'@modelcontextprotocol/[email protected]':dependencies:- zod: 4.3.6+ zod: 4.6.5'@modelcontextprotocol/[email protected]':dependencies:@@ -22579,10 +22708,14 @@ snapshots:'@next/[email protected]':optional: true+ '@noble/[email protected]': {}+'@noble/[email protected]': {}'@noble/[email protected]': {}+ '@noble/[email protected]': {}+'@nodelib/[email protected]':dependencies:'@nodelib/fs.stat': 2.0.5@@ -22717,7 +22850,7 @@ snapshots:'@opentelemetry/api': 1.9.0'@opentelemetry/core': 2.8.0(@opentelemetry/[email protected])'@opentelemetry/resources': 2.6.0(@opentelemetry/[email protected])- '@opentelemetry/semantic-conventions': 1.38.0+ '@opentelemetry/semantic-conventions': 1.43.0'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:@@ -22728,6 +22861,8 @@ snapshots:'@opentelemetry/[email protected]': {}+ '@opentelemetry/[email protected]': {}+'@opentelemetry/[email protected]':dependencies:'@opentelemetry/api-logs': 0.213.0@@ -22855,8 +22990,6 @@ snapshots:'@oxlint/[email protected]':optional: true- '@panva/[email protected]': {}-'@paralleldrive/[email protected]':dependencies:'@noble/hashes': 1.8.0@@ -26125,6 +26258,46 @@ snapshots:+ [email protected](@opentelemetry/[email protected])([email protected])([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))):+ dependencies:+ '@better-auth/core': 1.6.25(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/drizzle-adapter': 1.6.25(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]))+ '@better-auth/kysely-adapter': 1.6.25(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])+ '@better-auth/memory-adapter': 1.6.25(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/mongo-adapter': 1.6.25(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/prisma-adapter': 1.6.25(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/telemetry': 1.6.25(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])+ '@better-auth/utils': 0.4.2+ '@better-fetch/fetch': 1.3.1+ '@noble/ciphers': 2.4.0+ '@noble/hashes': 2.4.0+ better-call: 1.3.7([email protected])+ defu: 6.1.7+ jose: 6.2.12+ kysely: 0.29.6+ nanostores: 1.5.4+ zod: 4.6.5+ optionalDependencies:+ better-sqlite3: 13.0.3+ drizzle-kit: 0.31.10+ drizzle-orm: 0.45.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])+ next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ transitivePeerDependencies:+ - '@cloudflare/workers-types'+ - '@opentelemetry/api'++ dependencies:+ '@better-auth/utils': 0.4.2+ '@better-fetch/fetch': 1.3.2+ rou3: 0.7.12+ set-cookie-parser: 3.1.2+ optionalDependencies:+ zod: 4.6.5+dependencies:node-addon-api: 8.9.2@@ -27207,10 +27380,10 @@ snapshots:whatwg-mimetype: 4.0.0whatwg-url: 14.2.0- [email protected](@noble/[email protected]):+ [email protected](@noble/[email protected]):dependencies:whatwg-mimetype: 5.0.0- whatwg-url: 16.0.1(@noble/[email protected])+ whatwg-url: 16.0.1(@noble/[email protected])transitivePeerDependencies:- '@noble/hashes'@@ -27323,8 +27496,6 @@ snapshots:has-property-descriptors: 1.0.2object-keys: 1.1.1- [email protected]: {}-@@ -27537,19 +27708,21 @@ snapshots:esbuild: 0.25.6tsx: 4.23.13- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]):optionalDependencies:'@opentelemetry/api': 1.9.0'@types/better-sqlite3': 7.6.13'@types/react': 19.2.15better-sqlite3: 13.0.3+ kysely: 0.29.6react: 19.2.3+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]):optionalDependencies:'@opentelemetry/api': 1.9.0'@types/better-sqlite3': 7.6.13better-sqlite3: 13.0.3+ kysely: 0.29.6@@ -28988,9 +29161,9 @@ snapshots:dependencies:whatwg-encoding: 3.1.1- [email protected](@noble/[email protected]):+ [email protected](@noble/[email protected]):dependencies:- '@exodus/bytes': 1.15.1(@noble/[email protected])+ '@exodus/bytes': 1.15.1(@noble/[email protected])transitivePeerDependencies:- '@noble/hashes'@@ -29597,8 +29770,6 @@ snapshots:'@sideway/formula': 3.0.1'@sideway/pinpoint': 2.0.0- [email protected]: {}-@@ -29652,17 +29823,17 @@ snapshots:- supports-color- utf-8-validate- [email protected](@noble/[email protected]):+ [email protected](@noble/[email protected]):dependencies:'@asamuzakjp/css-color': 6.0.7'@asamuzakjp/dom-selector': 8.3.2'@bramus/specificity': 2.4.2'@csstools/css-syntax-patches-for-csstree': 1.1.14([email protected])- '@exodus/bytes': 1.15.1(@noble/[email protected])+ '@exodus/bytes': 1.15.1(@noble/[email protected])css-tree: 3.2.1- data-urls: 7.0.0(@noble/[email protected])+ data-urls: 7.0.0(@noble/[email protected])decimal.js: 10.6.0- html-encoding-sniffer: 6.0.0(@noble/[email protected])+ html-encoding-sniffer: 6.0.0(@noble/[email protected])is-potential-custom-element-name: 1.0.1lru-cache: 11.5.2parse5: 8.0.1@@ -29673,7 +29844,7 @@ snapshots:w3c-xmlserializer: 5.0.0webidl-conversions: 8.0.1whatwg-mimetype: 5.0.0- whatwg-url: 17.1.1(@noble/[email protected])+ whatwg-url: 17.1.1(@noble/[email protected])xml-name-validator: 5.0.0transitivePeerDependencies:- '@noble/hashes'@@ -29748,6 +29919,8 @@ snapshots:+ [email protected]: {}+@@ -29890,11 +30063,11 @@ snapshots:- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]):dependencies:async-mutex: 0.4.1better-sqlite3: 13.0.3- drizzle-orm: 0.33.0(@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ drizzle-orm: 0.33.0(@opentelemetry/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])zod: 4.3.6transitivePeerDependencies:- '@aws-sdk/client-rds-data'@@ -30011,10 +30184,6 @@ snapshots:dependencies:yallist: 3.1.1- dependencies:- yallist: 4.0.0-[email protected]([email protected]([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):dependencies:react: 19.2.3@@ -30360,50 +30529,50 @@ snapshots:ts-dedent: 2.2.0uuid: 14.0.1dependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:'@keyvhq/memoize': 2.2.7- '@metascraper/helpers': 5.53.0(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.53.0(@noble/[email protected])([email protected])lodash: 4.18.1reachable-url: 1.8.4transitivePeerDependencies:@@ -30411,26 +30580,26 @@ snapshots:- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])lodash: 4.18.1transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])'@mozilla/readability': 0.6.0async-memoize-one: 1.2.1happy-dom: 20.11.15@@ -30441,33 +30610,33 @@ snapshots:- debug- utf-8-validatedependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])transitivePeerDependencies:- '@noble/hashes'- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])get-video-id: 3.7.0p-locate: 7.0.0reachable-url: 2.1.4@@ -30476,9 +30645,9 @@ snapshots:- canvas- debugdependencies:- '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])+ '@metascraper/helpers': 5.56.2(@noble/[email protected])([email protected])cheerio: 1.2.0debug-logfmt: 1.4.15([email protected])whoops: 5.1.4@@ -31493,6 +31662,8 @@ snapshots:+ [email protected]: {}+[email protected](2b2034160123f96e3dc050e47c8c63e3):dependencies:comment-json: 4.2.5@@ -31533,21 +31704,6 @@ snapshots:- [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected]):- dependencies:- '@babel/runtime': 7.27.6- '@panva/hkdf': 1.2.1- cookie: 0.7.2- jose: 4.15.9- next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])- oauth: 0.9.15- openid-client: 5.7.1- preact: 10.11.3- preact-render-to-string: 5.2.3([email protected])- react: 19.2.3- react-dom: 19.2.3([email protected])- uuid: 11.1.1-[email protected]([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@babel/runtime': 7.27.6@@ -31770,10 +31926,6 @@ snapshots:should: 13.2.3yaml: 1.10.3- [email protected]: {}-- [email protected]: {}-dependencies:flow-enums-runtime: 0.0.6@@ -31788,8 +31940,6 @@ snapshots:- [email protected]: {}-@@ -31822,8 +31972,6 @@ snapshots:- [email protected]: {}-dependencies:whatwg-fetch: 3.6.20@@ -31942,13 +32090,6 @@ snapshots:- dependencies:- jose: 4.15.9- lru-cache: 6.0.0- object-hash: 2.2.0- oidc-token-hash: 5.1.0-dependencies:chalk: 2.4.2@@ -32810,19 +32951,6 @@ snapshots:dependencies:punycode: 2.3.1- dependencies:- preact: 10.11.3- pretty-format: 3.8.0-- dependencies:- preact: 10.24.3-- [email protected]: {}-- [email protected]: {}-dependencies:prettier: 3.9.6@@ -32848,8 +32976,6 @@ snapshots:ansi-styles: 5.2.0react-is: 18.3.1- [email protected]: {}-dependencies:parse-ms: 2.1.0@@ -34037,6 +34163,8 @@ snapshots:optionalDependencies:fsevents: 2.3.3+ [email protected]: {}+dependencies:hachure-fill: 0.5.2@@ -34275,6 +34403,8 @@ snapshots:+ [email protected]: {}+dependencies:define-data-property: 1.1.4@@ -35245,7 +35375,7 @@ snapshots:dependencies:'@quansync/fs': 0.1.3- defu: 6.1.5+ defu: 6.1.7jiti: 2.4.2quansync: 0.2.10@@ -35461,8 +35591,6 @@ snapshots:- [email protected]: {}-@@ -35612,7 +35740,7 @@ snapshots:transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -35638,7 +35766,7 @@ snapshots:'@opentelemetry/api': 1.9.0'@types/node': 26.6.1happy-dom: 20.11.15- jsdom: 30.0.1(@noble/[email protected])+ jsdom: 30.0.1(@noble/[email protected])transitivePeerDependencies:- msw@@ -35967,17 +36095,17 @@ snapshots:tr46: 5.1.1webidl-conversions: 7.0.0- [email protected](@noble/[email protected]):+ [email protected](@noble/[email protected]):dependencies:- '@exodus/bytes': 1.15.1(@noble/[email protected])+ '@exodus/bytes': 1.15.1(@noble/[email protected])tr46: 6.0.0webidl-conversions: 8.0.1transitivePeerDependencies:- '@noble/hashes'- [email protected](@noble/[email protected]):+ [email protected](@noble/[email protected]):dependencies:- '@exodus/bytes': 1.15.1(@noble/[email protected])+ '@exodus/bytes': 1.15.1(@noble/[email protected])tr46: 6.0.0webidl-conversions: 8.0.1transitivePeerDependencies:@@ -36151,8 +36279,6 @@ snapshots:- [email protected]: {}-diff --git a/tools/seed-snapshot/src/index.ts b/tools/seed-snapshot/src/index.tsindex f031a8d5..3766d99a 100644--- a/tools/seed-snapshot/src/index.ts+++ b/tools/seed-snapshot/src/index.ts@@ -284,18 +284,37 @@ async function startContainers(composeDir: string, dataDir: string) {};}+// Signs up through better-auth's endpoint, the same way the web app does.+async function signUpUser(input: {+ name: string;+ email: string;+ password: string;+}) {+ const baseUrl = `http://localhost:${process.env.KARAKEEP_PORT}`;+ const response = await fetch(`${baseUrl}/api/auth/sign-up/email`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ // Node's fetch sends Sec-Fetch-* headers but no Origin, which+ // better-auth's CSRF protection rejects. Browsers always send it.+ Origin: baseUrl,+ },+ body: JSON.stringify(input),+ });+ if (!response.ok) {+ throw new Error(+ `Failed to sign up ${input.email}: ${response.status} ${await response.text()}`,+ );+ }+}+async function createUser(authlessClient: TrpcClient,email: string,name: string,): Promise<TrpcClient> {logInfo(`Creating ${email}`);- await authlessClient.users.create.mutate({- name,- email,- password: PASSWORD,- confirmPassword: PASSWORD,- });+ await signUpUser({ name, email, password: PASSWORD });const keyName = `seed-snapshot-${email}`;const { key } = await authlessClient.apiKeys.exchange.mutate({