A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(mobile): in-app subscriptions for cloud via RevenueCat (#3236)
Mohamed Bassem849a68648ab4
diff --git a/apps/mobile/app/dashboard/_layout.tsx b/apps/mobile/app/dashboard/_layout.tsxindex fb9d15fc..f67ee8fb 100644--- a/apps/mobile/app/dashboard/_layout.tsx+++ b/apps/mobile/app/dashboard/_layout.tsx@@ -333,6 +333,15 @@ export default function Dashboard() {headerBackTitle: "Back",}}/>+ <Stack.Screen+ name="settings/subscription"+ options={{+ ...settingsScreenOptions,+ title: "Subscription",+ headerTitle: "Subscription",+ headerBackTitle: "Back",+ }}+ /><Stack.Screenname="settings/usage"options={{diff --git a/apps/mobile/app/dashboard/settings/index.tsx b/apps/mobile/app/dashboard/settings/index.tsxindex da655df0..54951b5d 100644--- a/apps/mobile/app/dashboard/settings/index.tsx+++ b/apps/mobile/app/dashboard/settings/index.tsx@@ -19,6 +19,7 @@ import {} from "@/components/settings/settings-list";import { UserProfileHeader } from "@/components/settings/UserProfileHeader";import { Text } from "@/components/ui/Text";+import { useClientConfig } from "@/lib/client-config";import { useServerVersion } from "@/lib/hooks";import {getOfflineLibraryScope,@@ -47,6 +48,9 @@ export default function Settings() {isLoading: isServerVersionLoading,error: serverVersionError,} = useServerVersion();+ const clientConfig = useClientConfig();+ const showSubscription =+ clientConfig.stripe.isConfigured || clientConfig.revenueCat.isConfigured;const [showPasswordModal, setShowPasswordModal] = useState(false);const [password, setPassword] = useState("");@@ -73,7 +77,7 @@ export default function Settings() {useEffect(() => {if (error?.data?.code === "UNAUTHORIZED") {- logout();+ void logout();}}, [error?.data?.code, logout]);@@ -154,6 +158,15 @@ export default function Settings() {</SettingsGroup><SettingsGroup header="Account">+ {showSubscription ? (+ <>+ <SettingsNavigationRow+ label="Subscription"+ onPress={() => router.push("/dashboard/settings/subscription")}+ />+ <SettingsSeparator />+ </>+ ) : null}<SettingsActionRow label="Log Out" onPress={logout} /><SettingsSeparator /><SettingsActionRowdiff --git a/apps/mobile/app/dashboard/settings/subscription.tsx b/apps/mobile/app/dashboard/settings/subscription.tsxnew file mode 100644index 00000000..94910c1b--- /dev/null+++ b/apps/mobile/app/dashboard/settings/subscription.tsx@@ -0,0 +1,287 @@+import { useState } from "react";+import { Linking, Platform } from "react-native";+import Purchases from "react-native-purchases";+import RevenueCatUI, { PAYWALL_RESULT } from "react-native-purchases-ui";+import {+ SettingsActionRow,+ SettingsGroup,+ SettingsScreen,+ SettingsSeparator,+ SettingsValueRow,+} from "@/components/settings/settings-list";+import { useToast } from "@/components/ui/Toast";+import { useInAppPurchases } from "@/lib/purchases";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++import { useTRPC } from "@karakeep/shared-react/trpc";++const STORE_SUBSCRIPTIONS_URL = Platform.select({+ ios: "https://apps.apple.com/account/subscriptions",+ default: "https://play.google.com/store/account/subscriptions",+});++const countFormatter = new Intl.NumberFormat();+const storageFormatter = new Intl.NumberFormat(undefined, {+ maximumFractionDigits: 1,+});++function formatBytes(bytes: number) {+ if (bytes < 1024) return `${countFormatter.format(bytes)} B`;++ const units = ["KB", "MB", "GB", "TB"];+ let value = bytes / 1024;+ let unitIndex = 0;+ while (value >= 1024 && unitIndex < units.length - 1) {+ value /= 1024;+ unitIndex += 1;+ }+ return `${storageFormatter.format(value)} ${units[unitIndex]}`;+}++function formatDate(date: Date | null | undefined) {+ if (!date) return null;+ return new Intl.DateTimeFormat(undefined, {+ year: "numeric",+ month: "long",+ day: "numeric",+ }).format(date);+}++function formatUsage(+ used: number,+ quota: number | null,+ format: (n: number) => string,+) {+ return quota === null+ ? `${format(used)} (unlimited)`+ : `${format(used)} of ${format(quota)}`;+}++function formatBillingSource(+ provider: string | null | undefined,+ store: string | null | undefined,+) {+ if (provider === "stripe") return "Web";+ if (provider !== "in_app") return null;+ switch (store) {+ case "app_store":+ case "mac_app_store":+ return "App Store";+ case "play_store":+ return "Google Play";+ default:+ return "Mobile app";+ }+}++export default function SubscriptionSettings() {+ const api = useTRPC();+ const queryClient = useQueryClient();+ const { toast } = useToast();+ const { isAvailable: canPurchase } = useInAppPurchases();+ const [pendingAction, setPendingAction] = useState<+ "upgrade" | "restore" | "manage" | null+ >(null);++ const { data: status, isLoading: isStatusLoading } = useQuery(+ api.subscriptions.getSubscriptionStatus.queryOptions(),+ );+ const { data: usage } = useQuery(+ api.subscriptions.getQuotaUsage.queryOptions(),+ );+ const { mutateAsync: syncWithRevenueCat } = useMutation(+ api.subscriptions.syncWithRevenueCat.mutationOptions(),+ );++ // The server is the source of truth for the plan, so after any purchase,+ // ask it to pull the latest state from RevenueCat instead of waiting for+ // the webhook.+ const refreshEntitlements = async () => {+ const { hasActiveSubscription } = await syncWithRevenueCat();+ await queryClient.invalidateQueries(api.subscriptions.pathFilter());+ return hasActiveSubscription;+ };++ const runAction = async (+ action: NonNullable<typeof pendingAction>,+ fn: () => Promise<void>,+ ) => {+ setPendingAction(action);+ try {+ await fn();+ } catch (error) {+ console.warn(`Subscription ${action} failed`, error);+ toast({+ message: "Something went wrong. Please try again.",+ variant: "destructive",+ });+ } finally {+ setPendingAction(null);+ }+ };++ const upgrade = () =>+ runAction("upgrade", async () => {+ const result = await RevenueCatUI.presentPaywall();+ // Failures resolve instead of rejecting, so surface them as errors.+ if (+ result === PAYWALL_RESULT.ERROR ||+ result === PAYWALL_RESULT.NOT_PRESENTED+ ) {+ throw new Error(`Paywall failed: ${result}`);+ }+ if (+ result === PAYWALL_RESULT.PURCHASED ||+ result === PAYWALL_RESULT.RESTORED+ ) {+ if (await refreshEntitlements()) {+ toast({+ message: "You're now on the Paid plan.",+ variant: "success",+ });+ } else {+ toast({+ message:+ "We couldn't confirm your purchase yet. Try Restore Purchases in a moment.",+ variant: "destructive",+ });+ }+ }+ });++ const restore = () =>+ runAction("restore", async () => {+ await Purchases.restorePurchases();+ toast({+ message: (await refreshEntitlements())+ ? "Purchases restored"+ : "No active subscription found",+ });+ });++ const manage = () =>+ runAction("manage", async () => {+ const customerInfo = await Purchases.getCustomerInfo();+ await Linking.openURL(+ customerInfo.managementURL ?? STORE_SUBSCRIPTIONS_URL,+ );+ });++ const planLabel =+ status?.tier === "custom"+ ? (status.manualTierName ?? "Custom")+ : status?.tier === "paid"+ ? "Paid"+ : "Free";+ const billingSource = status?.hasActiveSubscription+ ? formatBillingSource(status.provider, status.store)+ : null;+ const endDate = formatDate(status?.endDate);+ const isInAppSubscriber =+ status?.hasActiveSubscription && status.provider === "in_app";+ const isWebSubscriber =+ status?.hasActiveSubscription && status.provider === "stripe";++ let renewalLabel: string | null = null;+ if (status?.hasActiveSubscription && endDate) {+ renewalLabel = status.cancelAtPeriodEnd ? "Ends on" : "Renews on";+ }++ let planFooter: string | undefined;+ if (status?.status === "past_due" && isInAppSubscriber) {+ planFooter =+ "There's a problem with your payment method. Update it in your store's subscription settings to keep your plan.";+ } else if (isWebSubscriber) {+ planFooter =+ "Your subscription is managed from the Karakeep web app's settings.";+ } else if (status?.tier === "custom") {+ planFooter = "Your plan is managed by the Karakeep team.";+ }++ const canUpgrade =+ canPurchase &&+ !!status &&+ !status.hasActiveSubscription &&+ status.tier !== "custom";++ return (+ <SettingsScreen>+ <SettingsGroup header="Plan" footer={planFooter}>+ <SettingsValueRow+ label="Current plan"+ value={isStatusLoading ? "Loading..." : planLabel}+ />+ {billingSource ? (+ <>+ <SettingsSeparator />+ <SettingsValueRow label="Billed through" value={billingSource} />+ </>+ ) : null}+ {renewalLabel && endDate ? (+ <>+ <SettingsSeparator />+ <SettingsValueRow label={renewalLabel} value={endDate} />+ </>+ ) : null}+ </SettingsGroup>++ {usage ? (+ <SettingsGroup header="Usage">+ <SettingsValueRow+ label="Bookmarks"+ value={formatUsage(+ usage.bookmarks.used,+ usage.bookmarks.quota,+ (n) => countFormatter.format(n),+ )}+ />+ <SettingsSeparator />+ <SettingsValueRow+ label="Storage"+ value={formatUsage(+ usage.storage.used,+ usage.storage.quota,+ formatBytes,+ )}+ />+ </SettingsGroup>+ ) : null}++ {canPurchase && !isWebSubscriber ? (+ <SettingsGroup>+ {canUpgrade ? (+ <>+ <SettingsActionRow+ disabled={pendingAction !== null}+ isLoading={pendingAction === "upgrade"}+ label="Upgrade"+ onPress={upgrade}+ tone="primary"+ />+ <SettingsSeparator />+ </>+ ) : null}+ {isInAppSubscriber ? (+ <>+ <SettingsActionRow+ disabled={pendingAction !== null}+ isLoading={pendingAction === "manage"}+ label="Manage Subscription"+ onPress={manage}+ tone="primary"+ />+ <SettingsSeparator />+ </>+ ) : null}+ <SettingsActionRow+ disabled={pendingAction !== null}+ isLoading={pendingAction === "restore"}+ label="Restore Purchases"+ onPress={restore}+ tone="default"+ />+ </SettingsGroup>+ ) : null}+ </SettingsScreen>+ );+}diff --git a/apps/mobile/lib/purchases.ts b/apps/mobile/lib/purchases.tsnew file mode 100644index 00000000..c17bff1c--- /dev/null+++ b/apps/mobile/lib/purchases.ts@@ -0,0 +1,82 @@+import { useEffect, useState } from "react";+import { Platform } from "react-native";+import Purchases from "react-native-purchases";+import { useQuery } from "@tanstack/react-query";++import { useTRPC } from "@karakeep/shared-react/trpc";++import { useClientConfig } from "./client-config";++// RevenueCat public SDK keys. These are only set for official builds, so+// purchases are never offered in builds that can't process them.+const REVENUECAT_API_KEY = Platform.select({+ ios: process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY,+ android: process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY,+});++async function identifyPurchasesUser(apiKey: string, userId: string) {+ // The Karakeep user ID is the RevenueCat app user ID, which is how the+ // server links purchases to accounts.+ if (!(await Purchases.isConfigured())) {+ Purchases.configure({ apiKey, appUserID: userId });+ } else if ((await Purchases.getAppUserID()) !== userId) {+ await Purchases.logIn(userId);+ }+}++export async function resetPurchasesUser() {+ try {+ if (!(await Purchases.isConfigured())) {+ return;+ }+ if (!(await Purchases.isAnonymous())) {+ await Purchases.logOut();+ }+ } catch (error) {+ console.warn("Failed to log out of RevenueCat", error);+ }+}++/**+ * In-app purchases are available when this build ships a RevenueCat key and+ * the connected server is set up to receive them (i.e. the hosted service)+ * and has enabled purchases for this platform. Self-hosted servers never get+ * purchase options.+ */+export function useInAppPurchases() {+ const api = useTRPC();+ const config = useClientConfig();+ const isSupported =+ !!REVENUECAT_API_KEY &&+ config.revenueCat.isConfigured &&+ config.revenueCat.purchasePlatforms.some((p) => p === Platform.OS);+ const { data: user } = useQuery({+ ...api.users.whoami.queryOptions(),+ enabled: isSupported,+ });+ const userId = user?.id;+ const [readyUserId, setReadyUserId] = useState<string | null>(null);++ useEffect(() => {+ if (!isSupported || !REVENUECAT_API_KEY || !userId) {+ return;+ }+ let cancelled = false;+ identifyPurchasesUser(REVENUECAT_API_KEY, userId)+ .then(() => {+ if (!cancelled) {+ setReadyUserId(userId);+ }+ })+ .catch((error) => {+ console.warn("Failed to set up in-app purchases", error);+ });+ return () => {+ cancelled = true;+ };+ }, [isSupported, userId]);++ return {+ isAvailable: isSupported && !!userId && readyUserId === userId,+ };+}diff --git a/apps/mobile/lib/session.ts b/apps/mobile/lib/session.tsindex f1629edb..abd1309d 100644--- a/apps/mobile/lib/session.ts+++ b/apps/mobile/lib/session.ts@@ -7,6 +7,7 @@ import { clearPersistedCache } from "./offlineCache";import { clearOfflineDownloadStorage } from "./offlineDownloadPrefs";import { clearOfflineLibrary } from "./offlineLibrary";import { resetOfflineDownloads } from "./offlineSync";+import { resetPurchasesUser } from "./purchases";import useAppSettings from "./settings";export function useSession() {@@ -18,7 +19,10 @@ export function useSession() {api.apiKeys.revoke.mutationOptions(),);- const logout = useCallback(() => {+ const logout = useCallback(async () => {+ // Finish signing out of RevenueCat before the next user can sign in, so+ // a late reset can't log out the next user's purchases identity.+ await resetPurchasesUser();if (settings.apiKeyId) {deleteKey({ id: settings.apiKeyId });}diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 1f90152b..8bb52c9b 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -78,6 +78,8 @@"react-native-mmkv": "^4.3.2","react-native-nitro-modules": "^0.36.1","react-native-pdf": "7.0.3",+ "react-native-purchases": "^10.12.2",+ "react-native-purchases-ui": "^10.12.2","react-native-reanimated": "4.5.1","react-native-safe-area-context": "~5.7.0","react-native-screens": "~4.26.0",diff --git a/apps/web/app/settings/layout.tsx b/apps/web/app/settings/layout.tsxindex 8d211e53..93bfdc84 100644--- a/apps/web/app/settings/layout.tsx+++ b/apps/web/app/settings/layout.tsx@@ -50,7 +50,7 @@ const settingsSidebarItems = (icon: <BarChart3 size={18} />,path: "/settings/stats",},- ...(serverConfig.stripe.isConfigured+ ...(serverConfig.stripe.isConfigured || serverConfig.revenueCat.isConfigured? [{name: t("settings.subscription.subscription"),diff --git a/apps/web/app/settings/subscription/page.tsx b/apps/web/app/settings/subscription/page.tsxindex ac2933cf..94610437 100644--- a/apps/web/app/settings/subscription/page.tsx+++ b/apps/web/app/settings/subscription/page.tsx@@ -16,7 +16,10 @@ export async function generateMetadata(): Promise<Metadata> {}export default async function SubscriptionPage() {- if (!serverConfig.stripe.isConfigured) {+ if (+ !serverConfig.stripe.isConfigured &&+ !serverConfig.revenueCat.isConfigured+ ) {redirect("/settings");}diff --git a/apps/web/components/settings/SubscriptionSettings.tsx b/apps/web/components/settings/SubscriptionSettings.tsxindex 3eadab3d..56d5de68 100644--- a/apps/web/components/settings/SubscriptionSettings.tsx+++ b/apps/web/components/settings/SubscriptionSettings.tsx@@ -2,6 +2,7 @@import { useEffect, useState } from "react";import { toast } from "@/components/ui/sonner";+import { useClientConfig } from "@/lib/clientConfig";import { useTranslation } from "@/lib/i18n/client";import { useMutation, useQuery } from "@tanstack/react-query";import { Check, Loader2, TriangleAlert } from "lucide-react";@@ -17,6 +18,10 @@ import { SettingsSection } from "./SettingsPage";export default function SubscriptionSettings() {const api = useTRPC();const { t } = useTranslation();+ // Servers that only sell in-app subscriptions can't check out on the web.+ const clientConfig = useClientConfig();+ const isStripeConfigured = clientConfig.stripe.isConfigured;+ const canPurchaseInApp = clientConfig.revenueCat.purchasePlatforms.length > 0;const [billingPeriod, setBillingPeriod] = useState<"monthly" | "yearly">("monthly",);@@ -26,9 +31,10 @@ export default function SubscriptionSettings() {isLoading: isQueryLoading,} = useQuery(api.subscriptions.getSubscriptionStatus.queryOptions());- const { data: subscriptionPrice } = useQuery(- api.subscriptions.getSubscriptionPrice.queryOptions(),- );+ const { data: subscriptionPrice } = useQuery({+ ...api.subscriptions.getSubscriptionPrice.queryOptions(),+ enabled: isStripeConfigured,+ });const { mutate: syncStripeState } = useMutation(api.subscriptions.syncWithStripe.mutationOptions({@@ -185,106 +191,117 @@ export default function SubscriptionSettings() {<div className="space-y-4">{!subscriptionStatus?.hasActiveSubscription ? (- <div className="space-y-4">- <div className="rounded-lg border p-6">- <h3 className="font-semibold">- {t("settings.subscription.paid_plan")}- </h3>- <p className="mt-1 text-sm text-muted-foreground">- {t("settings.subscription.unlock_bigger_quota")}+ !isStripeConfigured ? (+ canPurchaseInApp && (+ <p className="text-sm text-muted-foreground">+ {t("settings.subscription.upgrade_from_mobile_app")}</p>+ )+ ) : (+ <div className="space-y-4">+ <div className="rounded-lg border p-6">+ <h3 className="font-semibold">+ {t("settings.subscription.paid_plan")}+ </h3>+ <p className="mt-1 text-sm text-muted-foreground">+ {t("settings.subscription.unlock_bigger_quota")}+ </p>- <ul className="mt-4 space-y-1.5">- {(- ["pro_feature_bookmarks", "pro_feature_storage"] as const- ).map((key) => (- <li key={key} className="flex items-center text-sm">- <Check className="mr-2 h-4 w-4 shrink-0 text-green-500" />- {t(`settings.subscription.${key}`)}- </li>- ))}- </ul>+ <ul className="mt-4 space-y-1.5">+ {(+ [+ "pro_feature_bookmarks",+ "pro_feature_storage",+ ] as const+ ).map((key) => (+ <li key={key} className="flex items-center text-sm">+ <Check className="mr-2 h-4 w-4 shrink-0 text-green-500" />+ {t(`settings.subscription.${key}`)}+ </li>+ ))}+ </ul>- <div className="mt-4 flex items-end justify-between border-t pt-4">- <div>- {hasYearlyPricing && (- <div className="mb-2 inline-flex items-center rounded-lg bg-muted p-1">- <button- type="button"- onClick={() => setBillingPeriod("monthly")}- className={`rounded-md px-3 py-1 text-sm font-medium transition-colors ${- billingPeriod === "monthly"- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground"- }`}- >- {t("settings.subscription.monthly")}- </button>- <button- type="button"- onClick={() => setBillingPeriod("yearly")}- className={`rounded-md px-3 py-1 text-sm font-medium transition-colors ${- billingPeriod === "yearly"- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground"- }`}- >- {t("settings.subscription.yearly")}- {subscriptionPrice?.monthly?.amount &&- subscriptionPrice?.yearly?.amount && (- <span className="ml-1.5 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">- {t("settings.subscription.yearly_savings", {- percent: Math.round(- (1 -- subscriptionPrice.yearly.amount /- (subscriptionPrice.monthly.amount *- 12)) *- 100,- ),- })}- </span>+ <div className="mt-4 flex items-end justify-between border-t pt-4">+ <div>+ {hasYearlyPricing && (+ <div className="mb-2 inline-flex items-center rounded-lg bg-muted p-1">+ <button+ type="button"+ onClick={() => setBillingPeriod("monthly")}+ className={`rounded-md px-3 py-1 text-sm font-medium transition-colors ${+ billingPeriod === "monthly"+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ }`}+ >+ {t("settings.subscription.monthly")}+ </button>+ <button+ type="button"+ onClick={() => setBillingPeriod("yearly")}+ className={`rounded-md px-3 py-1 text-sm font-medium transition-colors ${+ billingPeriod === "yearly"+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground"+ }`}+ >+ {t("settings.subscription.yearly")}+ {subscriptionPrice?.monthly?.amount &&+ subscriptionPrice?.yearly?.amount && (+ <span className="ml-1.5 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">+ {t("settings.subscription.yearly_savings", {+ percent: Math.round(+ (1 -+ subscriptionPrice.yearly.amount /+ (subscriptionPrice.monthly.amount *+ 12)) *+ 100,+ ),+ })}+ </span>+ )}+ </button>+ </div>+ )}+ {currentPrice && currentPrice.amount ? (+ <span className="flex items-baseline gap-2">+ <span className="text-2xl font-bold">+ {formatPrice(+ currentPrice.amount,+ currentPrice.currency,)}- </button>- </div>- )}- {currentPrice && currentPrice.amount ? (- <span className="flex items-baseline gap-2">- <span className="text-2xl font-bold">- {formatPrice(- currentPrice.amount,- currentPrice.currency,- )}- </span>- <span className="text-sm text-muted-foreground">- /- {billingPeriod === "yearly"- ? t("settings.subscription.per_year")- : t("settings.subscription.per_month")}+ </span>+ <span className="text-sm text-muted-foreground">+ /+ {billingPeriod === "yearly"+ ? t("settings.subscription.per_year")+ : t("settings.subscription.per_month")}+ </span>+ <span className="text-xs italic text-muted-foreground">+ ({t("settings.subscription.excl_vat")})+ </span></span>- <span className="text-xs italic text-muted-foreground">- ({t("settings.subscription.excl_vat")})- </span>- </span>- ) : (- <Skeleton className="h-6 w-24" />- )}+ ) : (+ <Skeleton className="h-6 w-24" />+ )}+ </div>+ <Button+ onClick={() =>+ createCheckoutSession.mutate({ billingPeriod })+ }+ disabled={isLoading}+ size="lg"+ className="shadow-md transition-all hover:scale-[1.02] hover:shadow-lg active:scale-[0.98]"+ >+ {isLoading && (+ <Loader2 className="h-4 w-4 animate-spin" />+ )}+ {t("settings.subscription.subscribe_now")}+ </Button></div>- <Button- onClick={() =>- createCheckoutSession.mutate({ billingPeriod })- }- disabled={isLoading}- size="lg"- className="shadow-md transition-all hover:scale-[1.02] hover:shadow-lg active:scale-[0.98]"- >- {isLoading && (- <Loader2 className="h-4 w-4 animate-spin" />- )}- {t("settings.subscription.subscribe_now")}- </Button></div></div>- </div>+ )) : (<div className="space-y-4">{subscriptionStatus.paymentFailed && (@@ -294,25 +311,41 @@ export default function SubscriptionSettings() {{t("settings.subscription.payment_failed_title")}</AlertTitle><AlertDescription>- {t("settings.subscription.payment_failed_description")}+ {subscriptionStatus.provider === "in_app"+ ? t(+ "settings.subscription.payment_failed_description_in_app",+ )+ : t("settings.subscription.payment_failed_description")}</AlertDescription></Alert>)}- <div className="flex gap-2">- <Button- onClick={() => createPortalSession.mutate()}- disabled={isLoading}- variant={- subscriptionStatus.paymentFailed ? "default" : "outline"- }- >- {isLoading && <Loader2 className="h-4 w-4 animate-spin" />}- {subscriptionStatus.paymentFailed- ? t("settings.subscription.update_payment_method")- : t("settings.subscription.manage_billing")}- </Button>- </div>+ {subscriptionStatus.provider === "in_app" ? (+ <p className="text-sm text-muted-foreground">+ {subscriptionStatus.store === "app_store"+ ? t("settings.subscription.managed_by_app_store")+ : subscriptionStatus.store === "play_store"+ ? t("settings.subscription.managed_by_play_store")+ : t("settings.subscription.managed_by_mobile_app")}+ </p>+ ) : (+ <div className="flex gap-2">+ <Button+ onClick={() => createPortalSession.mutate()}+ disabled={isLoading}+ variant={+ subscriptionStatus.paymentFailed ? "default" : "outline"+ }+ >+ {isLoading && (+ <Loader2 className="h-4 w-4 animate-spin" />+ )}+ {subscriptionStatus.paymentFailed+ ? t("settings.subscription.update_payment_method")+ : t("settings.subscription.manage_billing")}+ </Button>+ </div>+ )}{subscriptionStatus.cancelAtPeriodEnd && (<Alert>diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.jsonindex 6a205751..58e9c17a 100644--- a/apps/web/lib/i18n/locales/en/translation.json+++ b/apps/web/lib/i18n/locales/en/translation.json@@ -548,6 +548,11 @@"payment_failed": "Payment failed","payment_failed_title": "Your last payment failed","payment_failed_description": "We couldn't charge your payment method. Update it to keep your Paid plan. We'll retry the charge in the meantime, and your plan will switch to Free if all retries fail.",+ "payment_failed_description_in_app": "We couldn't charge your payment method. Update it in your App Store or Google Play subscription settings to keep your Paid plan.",+ "upgrade_from_mobile_app": "To upgrade to the Paid plan, use the Karakeep mobile app.",+ "managed_by_app_store": "Your subscription was purchased through the App Store. You can manage it from your Apple account's subscription settings.",+ "managed_by_play_store": "Your subscription was purchased through Google Play. You can manage it from the Google Play Store's subscription settings.",+ "managed_by_mobile_app": "Your subscription was purchased through the mobile app. You can manage it from your device's subscription settings.","subscription_canceled": "Your subscription has been canceled and will end on {{date}}. You can resubscribe at any time.","usage_quotas": "Usage & Quotas","track_usage": "Track your current usage against your plan limits",diff --git a/packages/api/routes/webhooks.ts b/packages/api/routes/webhooks.tsindex 66ce96d3..9a3b5319 100644--- a/packages/api/routes/webhooks.ts+++ b/packages/api/routes/webhooks.ts@@ -1,3 +1,4 @@+import { TRPCError } from "@trpc/server";import { Hono } from "hono";import { Context, createCallerFactory } from "@karakeep/trpc";@@ -9,36 +10,64 @@ const app = new Hono<{Variables: {ctx: Context;};-}>().post("/stripe", async (c) => {- const body = await c.req.text();- const signature = c.req.header("stripe-signature");-- if (!signature) {- return c.json({ error: "Missing stripe-signature header" }, 400);- }-- try {- const api = createCaller(c.get("ctx"));- const result = await api.subscriptions.handleWebhook({- body,- signature,- });-- return c.json(result);- } catch (error) {- console.error("Webhook processing failed:", error);-- if (error instanceof Error) {- if (error.message.includes("Invalid signature")) {- return c.json({ error: "Invalid signature" }, 400);- }- if (error.message.includes("not configured")) {- return c.json({ error: "Stripe is not configured" }, 400);+}>()+ .post("/stripe", async (c) => {+ const body = await c.req.text();+ const signature = c.req.header("stripe-signature");++ if (!signature) {+ return c.json({ error: "Missing stripe-signature header" }, 400);+ }++ try {+ const api = createCaller(c.get("ctx"));+ const result = await api.subscriptions.handleWebhook({+ body,+ signature,+ });++ return c.json(result);+ } catch (error) {+ console.error("Webhook processing failed:", error);++ if (error instanceof Error) {+ if (error.message.includes("Invalid signature")) {+ return c.json({ error: "Invalid signature" }, 400);+ }+ if (error.message.includes("not configured")) {+ return c.json({ error: "Stripe is not configured" }, 400);+ }}++ return c.json({ error: "Internal server error" }, 500);}+ })+ .post("/revenuecat", async (c) => {+ const body = await c.req.text();++ try {+ const api = createCaller(c.get("ctx"));+ const result = await api.subscriptions.handleRevenueCatWebhook({+ body,+ authorization: c.req.header("authorization"),+ });++ return c.json(result);+ } catch (error) {+ console.error("RevenueCat webhook processing failed:", error);- return c.json({ error: "Internal server error" }, 500);- }-});+ if (error instanceof TRPCError) {+ switch (error.code) {+ case "UNAUTHORIZED":+ return c.json({ error: error.message }, 401);+ case "BAD_REQUEST":+ case "PRECONDITION_FAILED":+ return c.json({ error: error.message }, 400);+ }+ }++ return c.json({ error: "Internal server error" }, 500);+ }+ });export default app;diff --git a/packages/db/drizzle/0095_add_in_app_subscriptions.sql b/packages/db/drizzle/0095_add_in_app_subscriptions.sqlnew file mode 100644index 00000000..b7a45577--- /dev/null+++ b/packages/db/drizzle/0095_add_in_app_subscriptions.sql@@ -0,0 +1,17 @@+CREATE TABLE `inAppSubscriptions` (+ `id` text PRIMARY KEY NOT NULL,+ `userId` text NOT NULL,+ `store` text,+ `productId` text,+ `status` text NOT NULL,+ `cancelAtPeriodEnd` integer DEFAULT false NOT NULL,+ `billingIssue` integer DEFAULT false NOT NULL,+ `isSandbox` integer DEFAULT false NOT NULL,+ `startDate` integer,+ `endDate` integer,+ `createdAt` integer NOT NULL,+ `modifiedAt` integer,+ FOREIGN KEY (`userId`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `inAppSubscriptions_userId_unique` ON `inAppSubscriptions` (`userId`);\ No newline at end of filediff --git a/packages/db/drizzle/meta/0095_snapshot.json b/packages/db/drizzle/meta/0095_snapshot.jsonnew file mode 100644index 00000000..ffcd5425--- /dev/null+++ b/packages/db/drizzle/meta/0095_snapshot.json@@ -0,0 +1,3727 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "8d59e336-76ef-4c54-b24d-599885947f0c",+ "prevId": "09931183-1ed7-40d8-ad30-3b30edf74266",+ "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": {}+ },+ "inAppSubscriptions": {+ "name": "inAppSubscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "store": {+ "name": "store",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "productId": {+ "name": "productId",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cancelAtPeriodEnd": {+ "name": "cancelAtPeriodEnd",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "billingIssue": {+ "name": "billingIssue",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "isSandbox": {+ "name": "isSandbox",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "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": {+ "inAppSubscriptions_userId_unique": {+ "name": "inAppSubscriptions_userId_unique",+ "columns": [+ "userId"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "inAppSubscriptions_userId_user_id_fk": {+ "name": "inAppSubscriptions_userId_user_id_fk",+ "tableFrom": "inAppSubscriptions",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "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'"+ },+ "createdAt": {+ "name": "createdAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "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+ }+ },+ "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": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 655b876a..7af14c44 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -666,6 +666,13 @@"when": 1785711744217,"tag": "0094_migrate_to_better_auth","breakpoints": true+ },+ {+ "idx": 95,+ "version": "6",+ "when": 1791654223159,+ "tag": "0095_add_in_app_subscriptions",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/schema.ts b/packages/db/schema.tsindex a523fcdd..3e1213c1 100644--- a/packages/db/schema.ts+++ b/packages/db/schema.ts@@ -69,8 +69,8 @@ export const users = sqliteTable("user", {mode: "boolean",}),// Admin-granted plan label (e.g. a collaborator name). While set, Stripe- // sync doesn't downgrade the user's entitlements; it's cleared when the- // user gets an active Stripe subscription.+ // and in-app purchase syncs don't downgrade the user's entitlements; it's+ // cleared when the user gets an active paid subscription.manualTierName: text("manualTierName"),// User Settings@@ -959,6 +959,37 @@ export const subscriptions = sqliteTable(],);+// Subscriptions purchased through the mobile app stores (App Store / Google+// Play). These are managed by RevenueCat, which is the source of truth; this+// table mirrors the state of the configured RevenueCat entitlement.+export const inAppSubscriptions = sqliteTable("inAppSubscriptions", {+ id: text("id")+ .notNull()+ .primaryKey()+ .$defaultFn(() => createId()),+ userId: text("userId")+ .notNull()+ .references(() => users.id, { onDelete: "cascade" })+ .unique(),+ // The RevenueCat store identifier (e.g. "app_store", "play_store").+ store: text("store"),+ productId: text("productId"),+ status: text("status", {+ enum: ["active", "expired"],+ }).notNull(),+ cancelAtPeriodEnd: integer("cancelAtPeriodEnd", { mode: "boolean" })+ .notNull()+ .default(false),+ billingIssue: integer("billingIssue", { mode: "boolean" })+ .notNull()+ .default(false),+ isSandbox: integer("isSandbox", { mode: "boolean" }).notNull().default(false),+ startDate: integer("startDate", { mode: "timestamp" }),+ endDate: integer("endDate", { mode: "timestamp" }),+ createdAt: createdAtField(),+ modifiedAt: modifiedAtField(),+});+export const importSessions = sqliteTable("importSessions",{@@ -1097,6 +1128,7 @@ export const userRelations = relations(users, ({ many, one }) => ({chatSessions: many(chatSessions),invites: many(invites),subscription: one(subscriptions),+ inAppSubscription: one(inAppSubscriptions),importSessions: many(importSessions),listCollaborations: many(listCollaborators),backups: many(backupsTable),@@ -1289,6 +1321,16 @@ export const subscriptionsRelations = relations(subscriptions, ({ one }) => ({}),}));+export const inAppSubscriptionsRelations = relations(+ inAppSubscriptions,+ ({ one }) => ({+ user: one(users, {+ fields: [inAppSubscriptions.userId],+ references: [users.id],+ }),+ }),+);+export const chatSessionsRelations = relations(chatSessions,({ one, many }) => ({diff --git a/packages/shared-react/providers/client-config-provider.tsx b/packages/shared-react/providers/client-config-provider.tsxindex d38bd749..71da99e8 100644--- a/packages/shared-react/providers/client-config-provider.tsx+++ b/packages/shared-react/providers/client-config-provider.tsx@@ -29,6 +29,10 @@ export const DEFAULT_CLIENT_CONFIG: ZClientConfig = {crawler: {videoDownloadOnDemand: false,},+ revenueCat: {+ isConfigured: false,+ purchasePlatforms: [],+ },legal: {},disableNewReleaseCheck: true,};@@ -72,6 +76,10 @@ export function ClientConfigProvider({...DEFAULT_CLIENT_CONFIG.crawler,...value?.crawler,},+ revenueCat: {+ ...DEFAULT_CLIENT_CONFIG.revenueCat,+ ...value?.revenueCat,+ },legal: {...DEFAULT_CLIENT_CONFIG.legal,...value?.legal,diff --git a/packages/shared-server/src/eventLogTypes.ts b/packages/shared-server/src/eventLogTypes.tsindex 8bc7b201..b343f751 100644--- a/packages/shared-server/src/eventLogTypes.ts+++ b/packages/shared-server/src/eventLogTypes.ts@@ -204,6 +204,22 @@ type EventLogInternal =["event.name"]: "subscription.webhook_received";"stripe.event_type": string;"stripe.customer_id"?: string;+ }+ | {+ ["event.name"]: "subscription.in_app_synced";+ "revenuecat.store"?: string;+ "revenuecat.product_id"?: string;+ "subscription.status"?: string;+ "subscription.prev_status"?: string;+ "subscription.tier"?: "paid" | "free" | "manual";+ "subscription.cancel_at_period_end"?: boolean;+ "subscription.is_sandbox"?: boolean;+ "subscription.sync_skipped_reason"?: "no_entitlement";+ }+ | {+ ["event.name"]: "subscription.in_app_webhook_received";+ "revenuecat.event_type"?: string;+ "revenuecat.synced_users_count"?: number;};interface CommonEventLogFields {diff --git a/packages/shared/config.ts b/packages/shared/config.tsindex 4a5048d1..7589bf13 100644--- a/packages/shared/config.ts+++ b/packages/shared/config.ts@@ -233,6 +233,28 @@ const allEnv = z.object({STRIPE_PRICE_ID: z.string().optional(),STRIPE_YEARLY_PRICE_ID: z.string().optional(),+ // RevenueCat (mobile in-app purchases) configuration+ REVENUECAT_PROJECT_ID: z.string().optional(),+ REVENUECAT_SECRET_API_KEY: z.string().optional(),+ REVENUECAT_WEBHOOK_AUTH_TOKEN: z.string().optional(),+ REVENUECAT_ENTITLEMENT_ID: z.string().default("pro"),+ // App Store review and TestFlight purchase in the sandbox against the+ // production server, so sandbox purchases need to grant the paid tier+ // unless explicitly disabled.+ REVENUECAT_ALLOW_SANDBOX_PURCHASES: stringBool("true"),+ // The platforms whose mobile apps offer purchases (e.g. "ios,android").+ // None by default, so app builds can ship before billing gets enabled.+ REVENUECAT_PURCHASE_PLATFORMS: z+ .string()+ .prefault("")+ .transform((val) =>+ val+ .split(",")+ .map((p) => p.trim())+ .filter((p) => p),+ )+ .pipe(z.array(z.enum(["ios", "android"]))),+FREE_QUOTA_BOOKMARK_LIMIT: z.coerce.number().optional(),FREE_QUOTA_ASSET_SIZE_BYTES: z.coerce.number().optional(),FREE_BROWSER_CRAWLING_ENABLED: optionalStringBool(),@@ -537,6 +559,18 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {yearlyPriceId: val.STRIPE_YEARLY_PRICE_ID,isConfigured: !!val.STRIPE_SECRET_KEY && !!val.STRIPE_PUBLISHABLE_KEY,},+ revenueCat: {+ projectId: val.REVENUECAT_PROJECT_ID,+ secretApiKey: val.REVENUECAT_SECRET_API_KEY,+ webhookAuthToken: val.REVENUECAT_WEBHOOK_AUTH_TOKEN,+ entitlementId: val.REVENUECAT_ENTITLEMENT_ID,+ allowSandboxPurchases: val.REVENUECAT_ALLOW_SANDBOX_PURCHASES,+ purchasePlatforms: val.REVENUECAT_PURCHASE_PLATFORMS,+ isConfigured:+ !!val.REVENUECAT_PROJECT_ID &&+ !!val.REVENUECAT_SECRET_API_KEY &&+ !!val.REVENUECAT_WEBHOOK_AUTH_TOKEN,+ },quotas: {free: {bookmarkLimit: val.FREE_QUOTA_BOOKMARK_LIMIT ?? null,@@ -648,6 +682,10 @@ export const clientConfig = {crawler: {videoDownloadOnDemand: serverConfig.crawler.downloadVideoOnDemand,},+ revenueCat: {+ isConfigured: serverConfig.revenueCat.isConfigured,+ purchasePlatforms: serverConfig.revenueCat.purchasePlatforms,+ },legal: {termsOfServiceUrl: serverConfig.legal.termsOfServiceUrl,privacyPolicyUrl: serverConfig.legal.privacyPolicyUrl,diff --git a/packages/shared/types/config.ts b/packages/shared/types/config.tsindex 8305e9c6..06d8f0b6 100644--- a/packages/shared/types/config.ts+++ b/packages/shared/types/config.ts@@ -37,6 +37,10 @@ export const zClientConfigSchema = z.object({crawler: z.object({videoDownloadOnDemand: z.boolean(),}),+ revenueCat: z.object({+ isConfigured: z.boolean(),+ purchasePlatforms: z.array(z.enum(["ios", "android"])),+ }),legal: z.object({termsOfServiceUrl: z.string().optional(),privacyPolicyUrl: z.string().optional(),diff --git a/packages/trpc/lib/__tests__/revenueCat.test.ts b/packages/trpc/lib/__tests__/revenueCat.test.tsnew file mode 100644index 00000000..25e3b614--- /dev/null+++ b/packages/trpc/lib/__tests__/revenueCat.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from "vitest";++import type {+ RevenueCatCustomer,+ RevenueCatPurchase,+ RevenueCatSubscription,+} from "../revenueCat";+import {+ computeInAppSubscriptionState,+ getRevenueCatWebhookAppUserIds,+} from "../revenueCat";++const opts = { entitlementId: "pro", allowSandboxPurchases: true };++function subscription(+ overrides: Partial<RevenueCatSubscription> = {},+): RevenueCatSubscription {+ return {+ product_id: "karakeep_monthly",+ starts_at: Date.parse("2026-01-01T00:00:00Z"),+ current_period_ends_at: Date.parse("2026-02-01T00:00:00Z"),+ gives_access: true,+ auto_renewal_status: "will_renew",+ status: "active",+ environment: "production",+ store: "app_store",+ entitlements: { items: [{ lookup_key: "pro" }] },+ ...overrides,+ };+}++function purchase(+ overrides: Partial<RevenueCatPurchase> = {},+): RevenueCatPurchase {+ return {+ product_id: "karakeep_lifetime",+ purchased_at: Date.parse("2026-01-01T00:00:00Z"),+ status: "owned",+ environment: "production",+ store: "app_store",+ entitlements: { items: [{ lookup_key: "pro" }] },+ ...overrides,+ };+}++function customer(+ overrides: Partial<RevenueCatCustomer> = {},+): RevenueCatCustomer {+ return { subscriptions: [subscription()], purchases: [], ...overrides };+}++describe("computeInAppSubscriptionState", () => {+ it("returns null when the customer never had the entitlement", () => {+ expect(+ computeInAppSubscriptionState(customer({ subscriptions: [] }), opts),+ ).toBeNull();+ expect(+ computeInAppSubscriptionState(+ customer({+ subscriptions: [+ subscription({+ entitlements: { items: [{ lookup_key: "other" }] },+ }),+ ],+ }),+ opts,+ ),+ ).toBeNull();+ });++ it("returns an active subscription", () => {+ expect(computeInAppSubscriptionState(customer(), opts)).toEqual({+ status: "active",+ store: "app_store",+ productId: "karakeep_monthly",+ cancelAtPeriodEnd: false,+ billingIssue: false,+ isSandbox: false,+ startDate: new Date("2026-01-01T00:00:00Z"),+ endDate: new Date("2026-02-01T00:00:00Z"),+ });+ });++ it("returns an expired subscription", () => {+ const state = computeInAppSubscriptionState(+ customer({+ subscriptions: [+ subscription({ gives_access: false, status: "expired" }),+ ],+ }),+ opts,+ );+ expect(state?.status).toBe("expired");+ });++ it("prefers the subscription that gives access", () => {+ const state = computeInAppSubscriptionState(+ customer({+ subscriptions: [+ subscription({+ product_id: "karakeep_yearly",+ current_period_ends_at: Date.parse("2027-01-01T00:00:00Z"),+ gives_access: false,+ status: "expired",+ }),+ subscription(),+ ],+ }),+ opts,+ );+ expect(state).toMatchObject({+ status: "active",+ productId: "karakeep_monthly",+ });+ });++ it("keeps the subscription active during a billing grace period", () => {+ const state = computeInAppSubscriptionState(+ customer({+ subscriptions: [+ subscription({ status: "in_grace_period", store: "play_store" }),+ ],+ }),+ opts,+ );+ expect(state).toMatchObject({+ status: "active",+ billingIssue: true,+ store: "play_store",+ });+ });++ it("treats a one-time purchase as a lifetime entitlement", () => {+ const state = computeInAppSubscriptionState(+ customer({ subscriptions: [], purchases: [purchase()] }),+ opts,+ );+ expect(state).toMatchObject({+ status: "active",+ store: "app_store",+ productId: "karakeep_lifetime",+ endDate: null,+ });+ });++ it("doesn't grant the entitlement for a refunded purchase", () => {+ const state = computeInAppSubscriptionState(+ customer({+ subscriptions: [],+ purchases: [purchase({ status: "refunded" })],+ }),+ opts,+ );+ expect(state?.status).toBe("expired");+ });++ it("reports a scheduled cancellation", () => {+ const state = computeInAppSubscriptionState(+ customer({+ subscriptions: [+ subscription({ auto_renewal_status: "will_not_renew" }),+ ],+ }),+ opts,+ );+ expect(state).toMatchObject({ status: "active", cancelAtPeriodEnd: true });+ });++ it("ignores sandbox purchases when they're not allowed", () => {+ const sandboxCustomer = customer({+ subscriptions: [subscription({ environment: "sandbox" })],+ });+ expect(computeInAppSubscriptionState(sandboxCustomer, opts)).toMatchObject({+ status: "active",+ isSandbox: true,+ });+ expect(+ computeInAppSubscriptionState(sandboxCustomer, {+ ...opts,+ allowSandboxPurchases: false,+ })?.status,+ ).toBe("expired");+ });+});++describe("getRevenueCatWebhookAppUserIds", () => {+ it("collects all the affected users, without anonymous ones", () => {+ expect(+ getRevenueCatWebhookAppUserIds({+ type: "TRANSFER",+ app_user_id: "user1",+ original_app_user_id: "$RCAnonymousID:abc",+ aliases: ["user1", "$RCAnonymousID:abc"],+ transferred_from: ["user2"],+ transferred_to: ["user1"],+ }).sort(),+ ).toEqual(["user1", "user2"]);+ });+});diff --git a/packages/trpc/lib/revenueCat.ts b/packages/trpc/lib/revenueCat.tsnew file mode 100644index 00000000..ccff56f1--- /dev/null+++ b/packages/trpc/lib/revenueCat.ts@@ -0,0 +1,382 @@+import { timingSafeEqual } from "node:crypto";+import { eq } from "drizzle-orm";+import { z } from "zod";++import { inAppSubscriptions } from "@karakeep/db/schema";+import { addLogFields, withEventLog } from "@karakeep/shared-server";+import serverConfig from "@karakeep/shared/config";++import type { Context } from "../index";+import { applyUserTierQuotas } from "./subscriptionEntitlements";++const REVENUECAT_API_ORIGIN = "https://api.revenuecat.com";+const REVENUECAT_ANONYMOUS_ID_PREFIX = "$RCAnonymousID:";++// Only the fields we care about from+// https://www.revenuecat.com/docs/api-v2#tag/Customer-Information. All the+// timestamps are in ms since epoch.+// This list is paginated too, but only its first page (20 items) is read: a+// product grants far fewer entitlements than that.+const zEntitlementList = z.object({+ items: z.array(z.object({ lookup_key: z.string() })),+});++const zSubscription = z.object({+ product_id: z.string().nullable(),+ starts_at: z.number(),+ current_period_ends_at: z.number().nullable(),+ gives_access: z.boolean(),+ auto_renewal_status: z.string(),+ status: z.string(),+ environment: z.string(),+ store: z.string(),+ entitlements: zEntitlementList,+});++const zPurchase = z.object({+ product_id: z.string(),+ purchased_at: z.number(),+ status: z.string(),+ environment: z.string(),+ store: z.string(),+ entitlements: zEntitlementList,+});++export type RevenueCatSubscription = z.infer<typeof zSubscription>;+export type RevenueCatPurchase = z.infer<typeof zPurchase>;++export interface RevenueCatCustomer {+ subscriptions: RevenueCatSubscription[];+ purchases: RevenueCatPurchase[];+}++export const zRevenueCatWebhookBody = z.object({+ event: z.object({+ type: z.string(),+ app_user_id: z.string().nullish(),+ original_app_user_id: z.string().nullish(),+ aliases: z.array(z.string()).nullish(),+ transferred_from: z.array(z.string()).nullish(),+ transferred_to: z.array(z.string()).nullish(),+ }),+});++export type RevenueCatWebhookEvent = z.infer<+ typeof zRevenueCatWebhookBody+>["event"];++export interface InAppSubscriptionState {+ status: "active" | "expired";+ store: string | null;+ productId: string;+ cancelAtPeriodEnd: boolean;+ billingIssue: boolean;+ isSandbox: boolean;+ startDate: Date | null;+ endDate: Date | null;+}++function subscriptionState(+ subscription: RevenueCatSubscription,+ isActive: boolean,+): InAppSubscriptionState {+ return {+ status: isActive ? "active" : "expired",+ store: subscription.store,+ productId: subscription.product_id ?? "",+ cancelAtPeriodEnd: subscription.auto_renewal_status === "will_not_renew",+ billingIssue:+ subscription.status === "in_grace_period" ||+ subscription.status === "in_billing_retry",+ isSandbox: subscription.environment === "sandbox",+ startDate: new Date(subscription.starts_at),+ // Null while a subscription is paused indefinitely.+ endDate:+ subscription.current_period_ends_at === null+ ? null+ : new Date(subscription.current_period_ends_at),+ };+}++function purchaseState(+ purchase: RevenueCatPurchase,+ isActive: boolean,+): InAppSubscriptionState {+ return {+ status: isActive ? "active" : "expired",+ store: purchase.store,+ productId: purchase.product_id,+ cancelAtPeriodEnd: false,+ billingIssue: false,+ isSandbox: purchase.environment === "sandbox",+ startDate: new Date(purchase.purchased_at),+ // One-time purchases grant a lifetime entitlement.+ endDate: null,+ };+}++/**+ * Derives the state of the configured entitlement from a RevenueCat+ * customer. Returns null if the customer never had the entitlement.+ */+export function computeInAppSubscriptionState(+ customer: RevenueCatCustomer,+ opts: {+ entitlementId: string;+ allowSandboxPurchases: boolean;+ },+): InAppSubscriptionState | null {+ const grantsEntitlement = (item: {+ entitlements: { items: { lookup_key: string }[] };+ }) =>+ item.entitlements.items.some((e) => e.lookup_key === opts.entitlementId);+ const isAllowed = (item: { environment: string }) =>+ opts.allowSandboxPurchases || item.environment !== "sandbox";+ // A null period end means paused indefinitely, so it sorts last.+ const latestFirst = (a: RevenueCatSubscription, b: RevenueCatSubscription) =>+ (b.current_period_ends_at ?? Infinity) -+ (a.current_period_ends_at ?? Infinity);++ const subscriptions = customer.subscriptions+ .filter(grantsEntitlement)+ .sort(latestFirst);+ const purchases = customer.purchases+ .filter(grantsEntitlement)+ .sort((a, b) => b.purchased_at - a.purchased_at);++ // RevenueCat's `gives_access` already accounts for grace periods.+ const activeSubscription = subscriptions.find(+ (s) => s.gives_access && isAllowed(s),+ );+ if (activeSubscription) {+ return subscriptionState(activeSubscription, true);+ }+ const ownedPurchase = purchases.find(+ (p) => p.status === "owned" && isAllowed(p),+ );+ if (ownedPurchase) {+ return purchaseState(ownedPurchase, true);+ }+ if (subscriptions[0]) {+ return subscriptionState(subscriptions[0], false);+ }+ if (purchases[0]) {+ return purchaseState(purchases[0], false);+ }+ return null;+}++async function fetchRevenueCatList<T extends z.ZodTypeAny>(+ path: string,+ item: T,+): Promise<z.infer<T>[]> {+ const secretApiKey = serverConfig.revenueCat.secretApiKey;+ if (!secretApiKey) {+ throw new Error("RevenueCat is not configured");+ }+ const zPage = z.object({+ items: z.array(item),+ next_page: z.string().nullish(),+ });+ const items: z.infer<T>[] = [];+ let nextPath: string | null | undefined = `${path}?limit=100`;+ while (nextPath) {+ const response = await fetch(`${REVENUECAT_API_ORIGIN}${nextPath}`, {+ headers: {+ Authorization: `Bearer ${secretApiKey}`,+ Accept: "application/json",+ },+ signal: AbortSignal.timeout(10_000),+ });+ // A customer that RevenueCat has never seen has no purchases.+ if (response.status === 404) {+ return [];+ }+ if (!response.ok) {+ throw new Error(+ `RevenueCat API request failed with status ${response.status}`,+ );+ }+ const page = zPage.parse(await response.json());+ items.push(...page.items);+ nextPath = page.next_page;+ }+ return items;+}++export async function fetchRevenueCatCustomer(+ appUserId: string,+): Promise<RevenueCatCustomer> {+ const projectId = serverConfig.revenueCat.projectId;+ if (!projectId) {+ throw new Error("RevenueCat is not configured");+ }+ const customerPath = `/v2/projects/${encodeURIComponent(projectId)}/customers/${encodeURIComponent(appUserId)}`;+ const [subscriptions, purchases] = await Promise.all([+ fetchRevenueCatList(`${customerPath}/subscriptions`, zSubscription),+ fetchRevenueCatList(`${customerPath}/purchases`, zPurchase),+ ]);+ return { subscriptions, purchases };+}++interface UserSyncQueue {+ // Settles once every sync queued for the user so far has finished.+ tail: Promise<void>;+ // A queued sync that hasn't fetched from RevenueCat yet.+ pending: Promise<InAppSubscriptionState | null> | null;+}++const userSyncQueues = new Map<string, UserSyncQueue>();++/**+ * Fetches the user's entitlement from RevenueCat (the source of truth) and+ * mirrors it into the database, updating the user's quotas accordingly. The+ * Karakeep user ID is used as the RevenueCat app user ID.+ *+ * Syncs of the same user run one at a time, so a slow RevenueCat response+ * can't overwrite the state written by a newer one. Callers that arrive while+ * a sync is waiting to start share it, as it will fetch fresh data anyway.+ * This only serializes syncs within this process.+ */+export function syncRevenueCatDataToDatabase(+ userId: string,+ db: Context["db"],+): Promise<InAppSubscriptionState | null> {+ let queue = userSyncQueues.get(userId);+ if (!queue) {+ queue = { tail: Promise.resolve(), pending: null };+ userSyncQueues.set(userId, queue);+ }+ if (queue.pending) {+ return queue.pending;+ }+ const q = queue;+ const sync = q.tail.then(() => {+ // From here on, the fetch might miss newer changes, so later callers+ // need a sync of their own.+ q.pending = null;+ return fetchAndStoreRevenueCatState(userId, db);+ });+ q.pending = sync;+ // Drop the queue once nothing else got queued behind this sync.+ const cleanUp = () => {+ if (q.tail === tail) {+ userSyncQueues.delete(userId);+ }+ };+ const tail = sync.then(cleanUp, cleanUp);+ q.tail = tail;+ return sync;+}++async function fetchAndStoreRevenueCatState(+ userId: string,+ db: Context["db"],+): Promise<InAppSubscriptionState | null> {+ return withEventLog("subscription.in_app_synced", async () => {+ addLogFields<"subscription.in_app_synced">({ "user.id": userId });++ const customer = await fetchRevenueCatCustomer(userId);+ let state = computeInAppSubscriptionState(customer, {+ entitlementId: serverConfig.revenueCat.entitlementId,+ allowSandboxPurchases: serverConfig.revenueCat.allowSandboxPurchases,+ });++ const existing = await db.query.inAppSubscriptions.findFirst({+ where: eq(inAppSubscriptions.userId, userId),+ });++ if (!state) {+ if (!existing) {+ addLogFields<"subscription.in_app_synced">({+ "subscription.sync_skipped_reason": "no_entitlement",+ });+ return null;+ }+ // The entitlement disappeared entirely (e.g. the purchase got+ // transferred to another user), so it's no longer active.+ state = {+ status: "expired",+ store: existing.store,+ productId: existing.productId ?? "",+ cancelAtPeriodEnd: false,+ billingIssue: false,+ isSandbox: existing.isSandbox,+ startDate: existing.startDate,+ endDate: existing.endDate,+ };+ }++ const row = {+ store: state.store,+ productId: state.productId || null,+ status: state.status,+ cancelAtPeriodEnd: state.cancelAtPeriodEnd,+ billingIssue: state.billingIssue,+ isSandbox: state.isSandbox,+ startDate: state.startDate,+ endDate: state.endDate,+ };++ const tier = db.transaction((trx) => {+ trx+ .insert(inAppSubscriptions)+ .values({ userId, ...row })+ .onConflictDoUpdate({+ target: inAppSubscriptions.userId,+ set: { ...row, modifiedAt: new Date() },+ })+ .run();+ return applyUserTierQuotas(trx, userId);+ });++ addLogFields<"subscription.in_app_synced">({+ "revenuecat.store": state.store ?? undefined,+ "revenuecat.product_id": state.productId,+ "subscription.status": state.status,+ "subscription.prev_status": existing?.status,+ "subscription.tier": tier,+ "subscription.cancel_at_period_end": state.cancelAtPeriodEnd,+ "subscription.is_sandbox": state.isSandbox,+ });++ return state;+ });+}++/**+ * RevenueCat sends the configured authorization header value verbatim. Accept+ * both a raw token and a "Bearer <token>" value.+ */+export function isValidRevenueCatWebhookAuthorization(+ authorization: string | undefined,+): boolean {+ const token = serverConfig.revenueCat.webhookAuthToken;+ if (!token || !authorization) {+ return false;+ }+ const provided = Buffer.from(authorization.replace(/^Bearer\s+/i, ""));+ const expected = Buffer.from(token.replace(/^Bearer\s+/i, ""));+ return (+ provided.length === expected.length && timingSafeEqual(provided, expected)+ );+}++/**+ * Returns all the app user IDs that an event might affect. Transfers move+ * entitlements between users, so both sides need to be re-synced.+ */+export function getRevenueCatWebhookAppUserIds(+ event: RevenueCatWebhookEvent,+): string[] {+ const ids = new Set<string>([+ ...(event.app_user_id ? [event.app_user_id] : []),+ ...(event.original_app_user_id ? [event.original_app_user_id] : []),+ ...(event.aliases ?? []),+ ...(event.transferred_from ?? []),+ ...(event.transferred_to ?? []),+ ]);+ return [...ids].filter(+ (id) => id && !id.startsWith(REVENUECAT_ANONYMOUS_ID_PREFIX),+ );+}diff --git a/packages/trpc/lib/subscriptionEntitlements.ts b/packages/trpc/lib/subscriptionEntitlements.tsnew file mode 100644index 00000000..152e051f--- /dev/null+++ b/packages/trpc/lib/subscriptionEntitlements.ts@@ -0,0 +1,87 @@+import { eq } from "drizzle-orm";++import type { KarakeepDBTransaction } from "@karakeep/db";+import { inAppSubscriptions, subscriptions, users } from "@karakeep/db/schema";+import serverConfig from "@karakeep/shared/config";++// Statuses that keep the paid entitlements. `past_due` means a renewal charge+// failed and Stripe is still retrying it; the user keeps the paid tier during+// that window and gets downgraded once Stripe gives up and moves the+// subscription to `canceled` or `unpaid`.+export function isPaidStatus(status: string | null | undefined) {+ return status === "active" || status === "trialing" || status === "past_due";+}++export function getActivePaidSubscriptionProvider(+ trx: KarakeepDBTransaction,+ userId: string,+): "stripe" | "in_app" | null {+ const stripeSubscription = trx+ .select({ status: subscriptions.status })+ .from(subscriptions)+ .where(eq(subscriptions.userId, userId))+ .get();+ if (isPaidStatus(stripeSubscription?.status)) {+ return "stripe";+ }++ const inAppSubscription = trx+ .select({ status: inAppSubscriptions.status })+ .from(inAppSubscriptions)+ .where(eq(inAppSubscriptions.userId, userId))+ .get();+ if (inAppSubscription?.status === "active") {+ return "in_app";+ }++ return null;+}++/**+ * Recomputes the user's quotas from all of their subscription sources (Stripe+ * and in-app purchases). Must be called after the subscription rows are+ * updated, within the same transaction.+ *+ * - Any active paid subscription grants the paid tier, and supersedes a+ * manually granted tier (which gets cleared).+ * - Otherwise, a manually granted tier is left untouched.+ * - Otherwise, the user is moved to the free tier.+ */+export function applyUserTierQuotas(+ trx: KarakeepDBTransaction,+ userId: string,+): "paid" | "free" | "manual" {+ if (getActivePaidSubscriptionProvider(trx, userId) !== null) {+ trx+ .update(users)+ .set({+ bookmarkQuota: serverConfig.quotas.paid.bookmarkLimit,+ storageQuota: serverConfig.quotas.paid.assetSizeBytes,+ browserCrawlingEnabled: serverConfig.quotas.paid.browserCrawlingEnabled,+ manualTierName: null,+ })+ .where(eq(users.id, userId))+ .run();+ return "paid";+ }++ const user = trx+ .select({ manualTierName: users.manualTierName })+ .from(users)+ .where(eq(users.id, userId))+ .get();+ if (user?.manualTierName) {+ return "manual";+ }++ trx+ .update(users)+ .set({+ bookmarkQuota: serverConfig.quotas.free.bookmarkLimit,+ storageQuota: serverConfig.quotas.free.assetSizeBytes,+ browserCrawlingEnabled: serverConfig.quotas.free.browserCrawlingEnabled,+ })+ .where(eq(users.id, userId))+ .run();+ return "free";+}diff --git a/packages/trpc/routers/subscriptions.revenueCat.test.ts b/packages/trpc/routers/subscriptions.revenueCat.test.tsnew file mode 100644index 00000000..068f2bc4--- /dev/null+++ b/packages/trpc/routers/subscriptions.revenueCat.test.ts@@ -0,0 +1,602 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { inAppSubscriptions, subscriptions, users } from "@karakeep/db/schema";++import type { CustomTestContext, TestDB } from "../testUtils";+import { createTestUser, defaultBeforeEach, getApiCaller } from "../testUtils";++const mockStripeInstance = vi.hoisted(() => ({+ customers: { create: vi.fn() },+ checkout: { sessions: { create: vi.fn() } },+ subscriptions: { list: vi.fn() },+ webhooks: { constructEvent: vi.fn() },+}));++vi.mock("stripe", () => ({+ default: vi.fn(function () {+ return mockStripeInstance;+ }),+}));++vi.mock("@karakeep/shared/config", async (original) => {+ const mod = (await original()) as typeof import("@karakeep/shared/config");+ return {+ ...mod,+ default: {+ ...mod.default,+ stripe: {+ secretKey: "sk_test_123",+ priceId: "price_123",+ webhookSecret: "whsec_123",+ isConfigured: true,+ },+ revenueCat: {+ projectId: "proj_123",+ secretApiKey: "sk_rc_123",+ webhookAuthToken: "rc_webhook_token",+ entitlementId: "pro",+ allowSandboxPurchases: true,+ purchasePlatforms: ["ios", "android"],+ isConfigured: true,+ },+ publicUrl: "https://test.karakeep.com",+ quotas: {+ free: {+ bookmarkLimit: 100,+ assetSizeBytes: 1000000,+ browserCrawlingEnabled: false,+ },+ paid: {+ bookmarkLimit: null,+ assetSizeBytes: null,+ browserCrawlingEnabled: true,+ },+ },+ },+ };+});++const AUTH = "Bearer rc_webhook_token";+const FUTURE = "2099-01-01T00:00:00Z";+const PAST = "2020-01-01T00:00:00Z";++// RevenueCat customers keyed by app user ID, served by the mocked fetch.+// Unknown customers get a 404, like the real API.+let rcCustomers: Record<+ string,+ { subscriptions: unknown[]; purchases: unknown[] }+>;+const mockFetch = vi.fn(async (url: string | URL) => {+ const match = new URL(url).pathname.match(+ /^\/v2\/projects\/proj_123\/customers\/([^/]+)\/(subscriptions|purchases)$/,+ );+ const customer = match && rcCustomers[decodeURIComponent(match[1])];+ if (!customer) {+ return new Response(JSON.stringify({ type: "resource_missing" }), {+ status: 404,+ });+ }+ return new Response(+ JSON.stringify({+ object: "list",+ items: customer[match[2] as "subscriptions" | "purchases"],+ }),+ { status: 200 },+ );+});++function rcCustomer(endDate: string, store = "app_store") {+ const endsAt = Date.parse(endDate);+ return {+ subscriptions: [+ {+ product_id: "karakeep_monthly",+ starts_at: Date.parse("2019-12-01T00:00:00Z"),+ current_period_ends_at: endsAt,+ gives_access: endsAt > Date.now(),+ auto_renewal_status: "will_renew",+ status: endsAt > Date.now() ? "active" : "expired",+ environment: "production",+ store,+ entitlements: { items: [{ lookup_key: "pro" }] },+ },+ ],+ purchases: [],+ };+}++function webhookBody(event: Record<string, unknown>) {+ return JSON.stringify({ api_version: "1.0", event });+}++async function getQuotas(db: TestDB, userId: string) {+ return db.query.users.findFirst({+ where: eq(users.id, userId),+ columns: {+ bookmarkQuota: true,+ storageQuota: true,+ browserCrawlingEnabled: true,+ manualTierName: true,+ },+ });+}++async function createFreeUser(db: TestDB, email = "[email protected]") {+ const user = await createTestUser(db, {+ name: "Test User",+ email,+ password: "pass1234",+ });+ await db+ .update(users)+ .set({ bookmarkQuota: 100, storageQuota: 1000000 })+ .where(eq(users.id, user.id));+ return user;+}++beforeEach<CustomTestContext>(defaultBeforeEach(false));++describe("RevenueCat subscriptions", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ rcCustomers = {};+ vi.stubGlobal("fetch", mockFetch);+ });++ describe("handleRevenueCatWebhook", () => {+ test<CustomTestContext>("rejects requests with an invalid authorization", async ({+ unauthedAPICaller,+ }) => {+ await expect(+ unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "TEST", app_user_id: "x" }),+ authorization: "Bearer wrong",+ }),+ ).rejects.toThrow(/Invalid authorization/);+ await expect(+ unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "TEST", app_user_id: "x" }),+ }),+ ).rejects.toThrow(/Invalid authorization/);+ expect(mockFetch).not.toHaveBeenCalled();+ });++ test<CustomTestContext>("rejects malformed bodies", async ({+ unauthedAPICaller,+ }) => {+ await expect(+ unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: "not json",+ authorization: AUTH,+ }),+ ).rejects.toThrow(/Invalid webhook body/);+ });++ test<CustomTestContext>("upgrades the user on purchase", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);+ rcCustomers[user.id] = rcCustomer(FUTURE);++ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "INITIAL_PURCHASE", app_user_id: user.id }),+ authorization: AUTH,+ });++ expect(mockFetch).toHaveBeenCalledWith(+ `https://api.revenuecat.com/v2/projects/proj_123/customers/${user.id}/subscriptions?limit=100`,+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: "Bearer sk_rc_123",+ }),+ }),+ );+ expect(await getQuotas(db, user.id)).toEqual({+ bookmarkQuota: null,+ storageQuota: null,+ browserCrawlingEnabled: true,+ manualTierName: null,+ });++ const status = await getApiCaller(+ db,+ user.id,+ ).subscriptions.getSubscriptionStatus();+ expect(status).toEqual({+ tier: "paid",+ manualTierName: null,+ status: "active",+ startDate: new Date("2019-12-01T00:00:00Z"),+ endDate: new Date(FUTURE),+ hasActiveSubscription: true,+ paymentFailed: false,+ cancelAtPeriodEnd: false,+ provider: "in_app",+ store: "app_store",+ });+ });++ test<CustomTestContext>("downgrades the user on expiration", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);+ rcCustomers[user.id] = rcCustomer(FUTURE);+ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "INITIAL_PURCHASE", app_user_id: user.id }),+ authorization: AUTH,+ });++ rcCustomers[user.id] = rcCustomer(PAST);+ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "EXPIRATION", app_user_id: user.id }),+ authorization: AUTH,+ });++ expect(await getQuotas(db, user.id)).toMatchObject({+ bookmarkQuota: 100,+ storageQuota: 1000000,+ browserCrawlingEnabled: false,+ });+ const status = await getApiCaller(+ db,+ user.id,+ ).subscriptions.getSubscriptionStatus();+ expect(status).toMatchObject({+ tier: "free",+ status: "canceled",+ hasActiveSubscription: false,+ provider: "in_app",+ });+ });++ test<CustomTestContext>("ignores anonymous and unknown users", async ({+ unauthedAPICaller,+ db,+ }) => {+ const result =+ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({+ type: "INITIAL_PURCHASE",+ app_user_id: "$RCAnonymousID:abc",+ aliases: ["unknown-user"],+ }),+ authorization: AUTH,+ });++ expect(result).toEqual({ received: true });+ expect(mockFetch).not.toHaveBeenCalled();+ expect(await db.query.inAppSubscriptions.findMany()).toHaveLength(0);+ });++ test<CustomTestContext>("doesn't create a row for users without the entitlement", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);++ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "TEST", app_user_id: user.id }),+ authorization: AUTH,+ });++ // One request for the subscriptions, one for the purchases.+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(await db.query.inAppSubscriptions.findMany()).toHaveLength(0);+ });++ test<CustomTestContext>("re-syncs both sides of a transfer", async ({+ db,+ unauthedAPICaller,+ }) => {+ const from = await createFreeUser(db, "[email protected]");+ const to = await createFreeUser(db, "[email protected]");++ rcCustomers[from.id] = rcCustomer(FUTURE);+ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "INITIAL_PURCHASE", app_user_id: from.id }),+ authorization: AUTH,+ });++ // After the transfer, the entitlement belongs to the other user.+ rcCustomers[to.id] = rcCustomers[from.id];+ delete rcCustomers[from.id];+ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({+ type: "TRANSFER",+ transferred_from: [from.id],+ transferred_to: [to.id],+ }),+ authorization: AUTH,+ });++ expect(await getQuotas(db, from.id)).toMatchObject({+ bookmarkQuota: 100,+ });+ expect(+ await db.query.inAppSubscriptions.findFirst({+ where: eq(inAppSubscriptions.userId, from.id),+ }),+ ).toMatchObject({ status: "expired" });+ expect(await getQuotas(db, to.id)).toMatchObject({+ bookmarkQuota: null,+ });+ });++ test<CustomTestContext>("returns an error when RevenueCat is unreachable so it retries", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);+ mockFetch.mockResolvedValueOnce(new Response("boom", { status: 500 }));++ await expect(+ unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "RENEWAL", app_user_id: user.id }),+ authorization: AUTH,+ }),+ ).rejects.toThrow(/Internal server error/);+ });+ });++ describe("syncWithRevenueCat", () => {+ test<CustomTestContext>("syncs the current user", async ({ db }) => {+ const user = await createFreeUser(db);+ rcCustomers[user.id] = rcCustomer(FUTURE, "play_store");++ expect(+ await getApiCaller(db, user.id).subscriptions.syncWithRevenueCat(),+ ).toEqual({ success: true, hasActiveSubscription: true });++ expect(+ await db.query.inAppSubscriptions.findFirst({+ where: eq(inAppSubscriptions.userId, user.id),+ }),+ ).toMatchObject({ status: "active", store: "play_store" });+ expect(await getQuotas(db, user.id)).toMatchObject({+ bookmarkQuota: null,+ });+ });++ test<CustomTestContext>("reports when the sync found no active subscription", async ({+ db,+ }) => {+ const user = await createFreeUser(db);+ rcCustomers[user.id] = rcCustomer(PAST);++ expect(+ await getApiCaller(db, user.id).subscriptions.syncWithRevenueCat(),+ ).toEqual({ success: true, hasActiveSubscription: false });+ });++ test<CustomTestContext>("flags billing issues of active in-app subscriptions", async ({+ db,+ }) => {+ const user = await createFreeUser(db);+ const customer = rcCustomer(FUTURE);+ customer.subscriptions[0].status = "in_grace_period";+ rcCustomers[user.id] = customer;+ const caller = getApiCaller(db, user.id);+ await caller.subscriptions.syncWithRevenueCat();++ expect(await caller.subscriptions.getSubscriptionStatus()).toMatchObject({+ tier: "paid",+ status: "past_due",+ hasActiveSubscription: true,+ paymentFailed: true,+ provider: "in_app",+ });+ });++ test<CustomTestContext>("overlapping syncs apply the newest state and share a fetch", async ({+ db,+ }) => {+ const user = await createFreeUser(db);+ const caller = getApiCaller(db, user.id);++ // Hold the first sync's (stale) RevenueCat responses until the user's+ // state changes and more syncs come in.+ let releaseFirstSync!: () => void;+ const firstSyncGate = new Promise<void>((resolve) => {+ releaseFirstSync = resolve;+ });+ const defaultFetch = mockFetch.getMockImplementation()!;+ const delayedFetch = async (url: string | URL) => {+ const response = await defaultFetch(url);+ await firstSyncGate;+ return response;+ };+ mockFetch+ .mockImplementationOnce(delayedFetch)+ .mockImplementationOnce(delayedFetch);++ rcCustomers[user.id] = rcCustomer(PAST);+ const first = caller.subscriptions.syncWithRevenueCat();+ await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(2));++ rcCustomers[user.id] = rcCustomer(FUTURE);+ const later = [+ caller.subscriptions.syncWithRevenueCat(),+ caller.subscriptions.syncWithRevenueCat(),+ ];+ releaseFirstSync();+ await Promise.all([first, ...later]);++ expect(+ await db.query.inAppSubscriptions.findFirst({+ where: eq(inAppSubscriptions.userId, user.id),+ }),+ ).toMatchObject({ status: "active" });+ expect(await getQuotas(db, user.id)).toMatchObject({+ bookmarkQuota: null,+ });+ // The first sync, then a single sync shared by the two later calls.+ expect(mockFetch).toHaveBeenCalledTimes(4);+ });+ });++ describe("interaction with other tiers", () => {+ test<CustomTestContext>("in-app expiry doesn't downgrade an active Stripe subscriber", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);+ await db.insert(subscriptions).values({+ userId: user.id,+ stripeCustomerId: "cus_123",+ status: "active",+ tier: "paid",+ });+ rcCustomers[user.id] = rcCustomer(PAST);++ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "EXPIRATION", app_user_id: user.id }),+ authorization: AUTH,+ });++ expect(await getQuotas(db, user.id)).toMatchObject({+ bookmarkQuota: null,+ storageQuota: null,+ });+ const status = await getApiCaller(+ db,+ user.id,+ ).subscriptions.getSubscriptionStatus();+ expect(status).toMatchObject({ tier: "paid", provider: "stripe" });+ });++ test<CustomTestContext>("Stripe cancellation doesn't downgrade an active in-app subscriber", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);+ await db.insert(subscriptions).values({+ userId: user.id,+ stripeCustomerId: "cus_123",+ status: "active",+ tier: "paid",+ });+ rcCustomers[user.id] = rcCustomer(FUTURE);+ await getApiCaller(db, user.id).subscriptions.syncWithRevenueCat();++ mockStripeInstance.webhooks.constructEvent.mockReturnValue({+ type: "customer.subscription.deleted",+ data: { object: { customer: "cus_123" } },+ });+ mockStripeInstance.subscriptions.list.mockResolvedValue({ data: [] });+ await unauthedAPICaller.subscriptions.handleWebhook({+ body: "body",+ signature: "sig",+ });++ expect(await getQuotas(db, user.id)).toMatchObject({+ bookmarkQuota: null,+ storageQuota: null,+ });+ const status = await getApiCaller(+ db,+ user.id,+ ).subscriptions.getSubscriptionStatus();+ expect(status).toMatchObject({ tier: "paid", provider: "in_app" });+ });++ test<CustomTestContext>("in-app expiry keeps a manually granted tier", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await createFreeUser(db);+ await db+ .update(users)+ .set({ manualTierName: "Acme", bookmarkQuota: 5000 })+ .where(eq(users.id, user.id));+ rcCustomers[user.id] = rcCustomer(PAST);+ await db.insert(inAppSubscriptions).values({+ userId: user.id,+ status: "active",+ });++ await unauthedAPICaller.subscriptions.handleRevenueCatWebhook({+ body: webhookBody({ type: "EXPIRATION", app_user_id: user.id }),+ authorization: AUTH,+ });++ expect(await getQuotas(db, user.id)).toMatchObject({+ manualTierName: "Acme",+ bookmarkQuota: 5000,+ });+ });++ test<CustomTestContext>("blocks Stripe checkout for active in-app subscribers", async ({+ db,+ }) => {+ const user = await createFreeUser(db);+ rcCustomers[user.id] = rcCustomer(FUTURE);+ const caller = getApiCaller(db, user.id);+ await caller.subscriptions.syncWithRevenueCat();++ await expect(+ caller.subscriptions.createCheckoutSession({}),+ ).rejects.toThrow(/through the mobile app/);+ expect(mockStripeInstance.customers.create).not.toHaveBeenCalled();+ });++ test<CustomTestContext>("blocks granting a manual tier to active in-app subscribers", async ({+ db,+ }) => {+ const user = await createFreeUser(db);+ const admin = await createTestUser(db, {+ name: "Admin",+ email: "[email protected]",+ password: "pass1234",+ role: "admin",+ });+ rcCustomers[user.id] = rcCustomer(FUTURE);+ await getApiCaller(db, user.id).subscriptions.syncWithRevenueCat();++ await expect(+ getApiCaller(+ db,+ admin.id,+ admin.email,+ "admin",+ ).subscriptions.updateSubscriptionTier({+ email: user.email,+ manualTierName: "Acme",+ }),+ ).rejects.toThrow(/active in-app subscription/);+ });++ test<CustomTestContext>("removing a manual tier keeps an active in-app subscriber paid", async ({+ db,+ }) => {+ const user = await createFreeUser(db);+ const admin = await createTestUser(db, {+ name: "Admin",+ email: "[email protected]",+ password: "pass1234",+ role: "admin",+ });+ rcCustomers[user.id] = rcCustomer(FUTURE);+ await getApiCaller(db, user.id).subscriptions.syncWithRevenueCat();++ await getApiCaller(+ db,+ admin.id,+ admin.email,+ "admin",+ ).subscriptions.updateSubscriptionTier({+ email: user.email,+ manualTierName: null,+ });++ expect(await getQuotas(db, user.id)).toEqual({+ bookmarkQuota: null,+ storageQuota: null,+ browserCrawlingEnabled: true,+ manualTierName: null,+ });+ });+ });+});diff --git a/packages/trpc/routers/subscriptions.test.ts b/packages/trpc/routers/subscriptions.test.tsindex d574da1c..a371c491 100644--- a/packages/trpc/routers/subscriptions.test.ts+++ b/packages/trpc/routers/subscriptions.test.ts@@ -126,6 +126,8 @@ describe("Subscription Routes", () => {hasActiveSubscription: false,paymentFailed: false,cancelAtPeriodEnd: false,+ provider: null,+ store: null,});});@@ -165,6 +167,8 @@ describe("Subscription Routes", () => {hasActiveSubscription: true,paymentFailed: false,cancelAtPeriodEnd: true,+ provider: "stripe",+ store: null,});});@@ -221,6 +225,8 @@ describe("Subscription Routes", () => {hasActiveSubscription: false,paymentFailed: false,cancelAtPeriodEnd: false,+ provider: null,+ store: null,});});diff --git a/packages/trpc/routers/subscriptions.ts b/packages/trpc/routers/subscriptions.tsindex 3df5ebf4..cdbbb64f 100644--- a/packages/trpc/routers/subscriptions.ts+++ b/packages/trpc/routers/subscriptions.ts@@ -1,11 +1,17 @@// Thanks to @t3dotgg for the recommendations (https://github.com/t3dotgg/stripe-recommendations)!import { TRPCError } from "@trpc/server";-import { count, eq, sum } from "drizzle-orm";+import { count, eq, inArray, sum } from "drizzle-orm";import Stripe from "stripe";import { z } from "zod";-import { assets, bookmarks, subscriptions, users } from "@karakeep/db/schema";+import {+ assets,+ bookmarks,+ inAppSubscriptions,+ subscriptions,+ users,+} from "@karakeep/db/schema";import { addLogFields, withEventLog } from "@karakeep/shared-server";import serverConfig from "@karakeep/shared/config";@@ -15,8 +21,19 @@ import {createEventLogMiddleware,publicProcedure,router,+ createRateLimitMiddleware,createScopedAuthedProcedure,} from "../index";+import {+ getRevenueCatWebhookAppUserIds,+ isValidRevenueCatWebhookAuthorization,+ syncRevenueCatDataToDatabase,+ zRevenueCatWebhookBody,+} from "../lib/revenueCat";+import {+ applyUserTierQuotas,+ isPaidStatus,+} from "../lib/subscriptionEntitlements";const stripe = serverConfig.stripe.secretKey? new Stripe(serverConfig.stripe.secretKey, {@@ -62,14 +79,6 @@ const allowedEvents: Stripe.Event.Type[] = ["payment_intent.canceled",];-// Statuses that keep the paid entitlements. `past_due` means a renewal charge-// failed and Stripe is still retrying it; the user keeps the paid tier during-// that window and gets downgraded once Stripe gives up and moves the-// subscription to `canceled` or `unpaid`.-function isPaidStatus(status: string | null | undefined) {- return status === "active" || status === "trialing" || status === "past_due";-}-type SubscriptionTransition =| "upgrade"| "downgrade"@@ -182,17 +191,9 @@ export async function syncStripeDataToDatabase(.where(eq(subscriptions.stripeCustomerId, customerId)).run();- // Update user quotas to free tier limits and disable browser crawling- trx- .update(users)- .set({- bookmarkQuota: serverConfig.quotas.free.bookmarkLimit,- storageQuota: serverConfig.quotas.free.assetSizeBytes,- browserCrawlingEnabled:- serverConfig.quotas.free.browserCrawlingEnabled,- })- .where(eq(users.id, existingSubscription.userId))- .run();+ // Moves the user to the free tier, unless they're still entitled to+ // the paid tier through an in-app purchase.+ applyUserTierQuotas(trx, existingSubscription.userId);});addLogFields<"subscription.synced">({"subscription.tier": "free",@@ -265,33 +266,10 @@ export async function syncStripeDataToDatabase(.where(eq(subscriptions.stripeCustomerId, customerId)).run();- if (subData.tier === "paid") {- // Enable paid tier quotas and browser crawling. A real subscription- // supersedes a manually granted tier, so clear it.- trx- .update(users)- .set({- bookmarkQuota: serverConfig.quotas.paid.bookmarkLimit,- storageQuota: serverConfig.quotas.paid.assetSizeBytes,- browserCrawlingEnabled:- serverConfig.quotas.paid.browserCrawlingEnabled,- manualTierName: null,- })- .where(eq(users.id, existingSubscription.userId))- .run();- } else {- // Set free tier quotas and disable browser crawling- trx- .update(users)- .set({- bookmarkQuota: serverConfig.quotas.free.bookmarkLimit,- storageQuota: serverConfig.quotas.free.assetSizeBytes,- browserCrawlingEnabled:- serverConfig.quotas.free.browserCrawlingEnabled,- })- .where(eq(users.id, existingSubscription.userId))- .run();- }+ // An active subscription enables the paid tier quotas (and supersedes+ // a manually granted tier). Otherwise, the user goes back to the free+ // tier unless they have an active in-app purchase.+ applyUserTierQuotas(trx, existingSubscription.userId);});addLogFields<"subscription.synced">({@@ -347,7 +325,7 @@ const adminSubscriptionsProcedure = createAdminScopedProcedure("subscriptions");export const subscriptionsRouter = router({getSubscriptionStatus: subscriptionsProcedure.query(async ({ ctx }) => {- const [user, subscription] = await Promise.all([+ const [user, subscription, inAppSubscription] = await Promise.all([ctx.db.query.users.findFirst({where: eq(users.id, ctx.user.id),columns: {@@ -357,9 +335,40 @@ export const subscriptionsRouter = router({ctx.db.query.subscriptions.findFirst({where: eq(subscriptions.userId, ctx.user.id),}),+ ctx.db.query.inAppSubscriptions.findFirst({+ where: eq(inAppSubscriptions.userId, ctx.user.id),+ }),]);const manualTierName = user?.manualTierName ?? null;+ // Report the subscription that's currently granting the paid tier. If+ // none is, prefer reporting the Stripe one, as it has the richer status.+ const stripeActive = isPaidStatus(subscription?.status);+ const inAppActive = inAppSubscription?.status === "active";++ if (inAppSubscription && (inAppActive || !subscription) && !stripeActive) {+ return {+ tier: manualTierName+ ? ("custom" as const)+ : inAppActive+ ? ("paid" as const)+ : ("free" as const),+ manualTierName,+ status: inAppActive+ ? inAppSubscription.billingIssue+ ? ("past_due" as const)+ : ("active" as const)+ : ("canceled" as const),+ startDate: inAppSubscription.startDate,+ endDate: inAppSubscription.endDate,+ hasActiveSubscription: inAppActive,+ paymentFailed: inAppActive && inAppSubscription.billingIssue,+ cancelAtPeriodEnd: inAppSubscription.cancelAtPeriodEnd,+ provider: "in_app" as const,+ store: inAppSubscription.store,+ };+ }+if (!subscription) {return {tier: manualTierName ? ("custom" as const) : ("free" as const),@@ -370,6 +379,8 @@ export const subscriptionsRouter = router({hasActiveSubscription: false,paymentFailed: false,cancelAtPeriodEnd: false,+ provider: null,+ store: null,};}@@ -379,9 +390,11 @@ export const subscriptionsRouter = router({status: subscription.status,startDate: subscription.startDate,endDate: subscription.endDate,- hasActiveSubscription: isPaidStatus(subscription.status),+ hasActiveSubscription: stripeActive,paymentFailed: subscription.status === "past_due",cancelAtPeriodEnd: subscription.cancelAtPeriodEnd || false,+ provider: "stripe" as const,+ store: null,};}),@@ -452,6 +465,7 @@ export const subscriptionsRouter = router({},with: {subscription: true,+ inAppSubscription: true,},});@@ -471,6 +485,14 @@ export const subscriptionsRouter = router({});}+ if (user.inAppSubscription?.status === "active") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "User already has an active subscription through the mobile app",+ });+ }+let customerId = existingSubscription?.stripeCustomerId;if (!customerId) {@@ -632,6 +654,7 @@ export const subscriptionsRouter = router({},with: {subscription: true,+ inAppSubscription: true,},});@@ -660,34 +683,138 @@ export const subscriptionsRouter = router({});}- const updateData: Partial<typeof users.$inferInsert> =- input.manualTierName === null- ? {- manualTierName: null,- bookmarkQuota: serverConfig.quotas.free.bookmarkLimit,- storageQuota: serverConfig.quotas.free.assetSizeBytes,- browserCrawlingEnabled:- serverConfig.quotas.free.browserCrawlingEnabled,- }- : { manualTierName: input.manualTierName };-- if (input.manualTierName !== null) {- if (input.bookmarkQuota !== undefined) {- updateData.bookmarkQuota = input.bookmarkQuota;- }+ if (input.manualTierName && user.inAppSubscription?.status === "active") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "User already has an active in-app subscription",+ });+ }- if (input.storageQuota !== undefined) {- updateData.storageQuota = input.storageQuota;- }+ if (input.manualTierName === null) {+ // Fall back to the quotas of the user's subscriptions, if any.+ await ctx.db.transaction((trx) => {+ trx+ .update(users)+ .set({ manualTierName: null })+ .where(eq(users.id, user.id))+ .run();+ applyUserTierQuotas(trx, user.id);+ });+ return;+ }- if (input.browserCrawlingEnabled !== undefined) {- updateData.browserCrawlingEnabled = input.browserCrawlingEnabled;- }+ const updateData: Partial<typeof users.$inferInsert> = {+ manualTierName: input.manualTierName,+ };+ if (input.bookmarkQuota !== undefined) {+ updateData.bookmarkQuota = input.bookmarkQuota;+ }++ if (input.storageQuota !== undefined) {+ updateData.storageQuota = input.storageQuota;+ }++ if (input.browserCrawlingEnabled !== undefined) {+ updateData.browserCrawlingEnabled = input.browserCrawlingEnabled;}await ctx.db.update(users).set(updateData).where(eq(users.id, user.id));}),+ // Called by the mobile app right after a purchase/restore so that the+ // entitlement is reflected without waiting for the RevenueCat webhook.+ syncWithRevenueCat: subscriptionsProcedure+ // Each sync makes two requests against RevenueCat's API, whose rate+ // limit is shared by all users and the webhook.+ .use(+ createRateLimitMiddleware({+ name: "subscriptions.syncWithRevenueCat",+ windowMs: 60 * 1000,+ maxRequests: 10,+ }),+ )+ .mutation(async ({ ctx }) => {+ if (!serverConfig.revenueCat.isConfigured) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: "In-app purchases are not configured",+ });+ }++ const state = await syncRevenueCatDataToDatabase(ctx.user.id, ctx.db);+ return {+ success: true,+ hasActiveSubscription: state?.status === "active",+ };+ }),++ handleRevenueCatWebhook: publicProcedure+ .use(createEventLogMiddleware("subscription.in_app_webhook_received"))+ .input(+ z.object({+ body: z.string(),+ authorization: z.string().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ if (!serverConfig.revenueCat.isConfigured) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: "RevenueCat is not configured",+ });+ }++ if (!isValidRevenueCatWebhookAuthorization(input.authorization)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Invalid authorization",+ });+ }++ let event;+ try {+ event = zRevenueCatWebhookBody.parse(JSON.parse(input.body)).event;+ } catch {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid webhook body",+ });+ }++ addLogFields<"subscription.in_app_webhook_received">({+ "revenuecat.event_type": event.type,+ });++ // The event payload is only used as a trigger; the subscriber state is+ // always re-fetched from RevenueCat. Ignore IDs that aren't Karakeep+ // users (e.g. anonymous RevenueCat users).+ const appUserIds = getRevenueCatWebhookAppUserIds(event);+ const knownUsers =+ appUserIds.length > 0+ ? await ctx.db.query.users.findMany({+ where: inArray(users.id, appUserIds),+ columns: { id: true },+ })+ : [];++ try {+ for (const user of knownUsers) {+ await syncRevenueCatDataToDatabase(user.id, ctx.db);+ }+ } catch (error) {+ console.error("Error processing RevenueCat webhook:", error);+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Internal server error",+ });+ }++ addLogFields<"subscription.in_app_webhook_received">({+ "revenuecat.synced_users_count": knownUsers.length,+ });+ return { received: true };+ }),+handleWebhook: publicProcedure.use(createEventLogMiddleware("subscription.webhook_received")).input(diff --git a/packages/trpc/stats.ts b/packages/trpc/stats.tsindex 05c5f7e7..98dbe9b3 100644--- a/packages/trpc/stats.ts+++ b/packages/trpc/stats.ts@@ -3,7 +3,13 @@ import { Counter, Gauge, Histogram, register } from "prom-client";import type { Metric } from "prom-client";import { db } from "@karakeep/db";-import { assets, bookmarks, subscriptions, users } from "@karakeep/db/schema";+import {+ assets,+ bookmarks,+ inAppSubscriptions,+ subscriptions,+ users,+} from "@karakeep/db/schema";import {AdminMaintenanceQueue,AssetPreprocessingQueue,@@ -153,6 +159,40 @@ if (serverConfig.stripe.isConfigured) {);}+if (serverConfig.revenueCat.isConfigured) {+ const store = sql<string>`coalesce(${inAppSubscriptions.store}, 'unknown')`;+ getOrCreateMetric(+ "karakeep_in_app_subscription_status",+ () =>+ new Gauge({+ name: "karakeep_in_app_subscription_status",+ help: "Total number of users per in-app subscription status and store",+ labelNames: ["status", "store"],+ async collect() {+ this.reset();+ try {+ const results = await db+ .select({+ status: inAppSubscriptions.status,+ store,+ count: count(),+ })+ .from(inAppSubscriptions)+ .groupBy(inAppSubscriptions.status, store);+ for (const result of results) {+ this.set(+ { status: result.status, store: result.store },+ result.count,+ );+ }+ } catch (error) {+ console.error("Failed to get in-app subscription status:", error);+ }+ },+ }),+ );+}+// Asset metricsconst totalAssetSizeGauge = getOrCreateMetric("karakeep_total_asset_size_bytes",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4e3987d9..737c87ac 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -508,6 +508,12 @@ importers:react-native-pdf:specifier: 7.0.3version: 7.0.3([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])+ react-native-purchases:+ specifier: ^10.12.2+ version: 10.12.2([email protected]([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])+ react-native-purchases-ui:+ specifier: ^10.12.2+ version: 10.12.2([email protected]([email protected]([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]))([email protected]([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])react-native-reanimated:specifier: 4.5.1version: 4.5.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[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])@@ -6692,6 +6698,15 @@ packages:'@restatedev/[email protected]':resolution: {integrity: sha512-L2XqUukvdGYmqCqsFvJzTsaU3JiuFzsYSh6nK19Q1yKNOr/bBBZKdic0o0hza5P5QdiiFC5jLHJ5wCWt77IO0Q==}+ '@revenuecat/[email protected]':+ resolution: {integrity: sha512-oHS+x18B2Q6dtaZJPuicJorhR+xUaAdt/tpLE1wQQHngkHksKN6AwbZDdt3x3rHHmEDjqgircORCbe5EwLF4hA==}++ '@revenuecat/[email protected]':+ resolution: {integrity: sha512-07e1rzlk9bMbMTthJduhcOwbQQhvFZJiFKskmoqOVnEYmQaRq/PayxtYgHhpK5UnmqOhzqRUzXfNqpvUggEP4w==}++ '@revenuecat/[email protected]':+ resolution: {integrity: sha512-uf/I9z+d2eU2bfEXe/pODyd2EUP137PqqtcC1YyU9Mr0KBptMDqbGKdfiZeRDShbUcX7d6D3lEhQA32hQQNX0w==}+'@rn-primitives/[email protected]':resolution: {integrity: sha512-BR97reSu7uVDpyMeQdRJHT0w8KdS6jdYnOL6xQtqS2q3H6N7vXBlX4LFERqJZphD+aziJFIAJ3HJF1vtt6XlpQ==}peerDependencies:@@ -14451,6 +14466,27 @@ packages:react-native: '*'react-native-blob-util: '>=0.13.7'+ resolution: {integrity: sha512-8fPyN1JzRVrjjTAMGKsek1NCeUhr02DDHSNwDryumXw5wEkzx2u/c+cJgz0ksRNw5dC2382P0b+zVi6zB6qgRA==}+ peerDependencies:+ react: 19.2.3+ react-native: '>= 0.73.0'+ react-native-purchases: 10.12.2+ react-native-web: '*'+ peerDependenciesMeta:+ react-native-web:+ optional: true++ resolution: {integrity: sha512-gM6gp3N8zBDyDuTa0YRErsX+Xr2dfM93brkfDYfGuTec8gqzdU1KjgGvA//kk9h52d7E89rD93lIgqdsGxLfpA==}+ peerDependencies:+ react: 19.2.3+ react-native: '>= 0.73.0'+ react-native-web: '*'+ peerDependenciesMeta:+ react-native-web:+ optional: true+resolution: {integrity: sha512-RnMvtDuR+68ig864gAvZCOdZehqhC5rFmMo0kn+ARfgVSTvFeF6IFLBVgMPUu0KwihaapEyW24WRi6nEyy1kSA==}peerDependencies:@@ -23217,9 +23253,7 @@ snapshots:metro-runtime: 0.84.6transitivePeerDependencies:- '@babel/core'- - bufferutil- supports-color- - utf-8-validate'@react-native/[email protected]': {}@@ -23352,6 +23386,14 @@ snapshots:dependencies:'@restatedev/restate-sdk-core': 1.16.2+ '@revenuecat/[email protected]':+ dependencies:+ '@revenuecat/purchases-js': 1.70.0++ '@revenuecat/[email protected]': {}++ '@revenuecat/[email protected]': {}+'@rn-primitives/[email protected]([email protected]([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:'@rn-primitives/types': 1.2.0([email protected]([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])@@ -32189,6 +32231,24 @@ snapshots:react-native: 0.86.3(patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])react-native-blob-util: 0.21.2([email protected](patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])+ [email protected]([email protected]([email protected]([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]))([email protected]([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:+ '@revenuecat/purchases-typescript-internal': 19.10.0+ react: 19.2.3+ react-native: 0.86.3(patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])+ react-native-purchases: 10.12.2([email protected]([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])+ optionalDependencies:++ [email protected]([email protected]([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:+ '@revenuecat/purchases-js-hybrid-mappings': 19.10.0+ '@revenuecat/purchases-typescript-internal': 19.10.0+ react: 19.2.3+ react-native: 0.86.3(patch_hash=7d74c7fbd33e9f3f3f8a8ba47a013acfc098948e39c7faab1232e6edca358ac1)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])+ optionalDependencies:+[email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[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