⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
improved UX
daniel31x133ee9bc8a0e84
diff --git a/apps/mobile/app/subscribe.tsx b/apps/mobile/app/subscribe.tsxindex a34e47cc..93ba6018 100644--- a/apps/mobile/app/subscribe.tsx+++ b/apps/mobile/app/subscribe.tsx@@ -110,6 +110,15 @@ export default function SubscribeScreen() {Platform.OS !== "ios");+ const showForeignPurchaseAlert = () => {+ Alert.alert(+ "Subscription already in use",+ Platform.OS === "ios"+ ? "The App Store subscription on this device belongs to a different Linkwarden account. Sign in with that account to use it, or subscribe with a different Apple Account."+ : "The Google Play subscription on this device belongs to a different Linkwarden account. Sign in with that account to use it, or subscribe with a different Google account."+ );+ };+const activateSubscription = async () => {for (let attempt = 0; attempt < 8; attempt++) {const { data } = await refetchUser();@@ -145,13 +154,15 @@ export default function SubscribeScreen() {purchase);- if (verified) {+ if (verified.active) {// Only finish after the server has validated it — unfinished purchases are// redelivered on the next launch, which is the retry mechanism.await finishTransaction({ purchase, isConsumable: false }).catch(() => {});await activateSubscription();+ } else if (verified.foreignAccount) {+ showForeignPurchaseAlert();} else {Alert.alert("Subscription syncing",@@ -175,6 +186,11 @@ export default function SubscribeScreen() {onPurchaseError: (error) => {setPurchaseLoading(false);+ if (error.code === ErrorCode.AlreadyOwned) {+ restorePurchases();+ return;+ }+if (error.code !== ErrorCode.UserCancelled &&error.code !== ErrorCode.DeferredPayment@@ -334,19 +350,26 @@ export default function SubscribeScreen() {);let restored = false;+ let foreignAccount = false;for (const purchase of owned) {- if (await verifyPurchaseWithServer(auth, purchase)) {+ const result = await verifyPurchaseWithServer(auth, purchase);++ if (result.active) {await finishTransaction({ purchase, isConsumable: false }).catch(() => {});restored = true;break;}++ if (result.foreignAccount) foreignAccount = true;}if (restored) {await activateSubscription();+ } else if (foreignAccount) {+ showForeignPurchaseAlert();} else {Alert.alert("No purchases found", "No active purchases were found.");}@@ -378,13 +401,26 @@ export default function SubscribeScreen() {SUBSCRIPTION_SKUS.includes(purchase.productId));- if (owned && (await verifyPurchaseWithServer(auth, owned))) {- await finishTransaction({ purchase: owned, isConsumable: false }).catch(- () => {}- );- await activateSubscription();- setPurchaseLoading(false);- return;+ if (owned) {+ const result = await verifyPurchaseWithServer(auth, owned);++ if (result.active) {+ await finishTransaction({+ purchase: owned,+ isConsumable: false,+ }).catch(() => {});+ await activateSubscription();+ setPurchaseLoading(false);+ return;+ }++ // The store won't sell this product again to the same store account, so+ // don't even open the payment sheet — explain instead.+ if (result.foreignAccount) {+ showForeignPurchaseAlert();+ setPurchaseLoading(false);+ return;+ }}const { sku, offerToken } = selectedPlan.option;diff --git a/apps/mobile/lib/iap.ts b/apps/mobile/lib/iap.tsindex f1024e74..e1e2caec 100644--- a/apps/mobile/lib/iap.ts+++ b/apps/mobile/lib/iap.ts@@ -154,6 +154,12 @@ export const getPlanOption = (const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+export type VerifyPurchaseResult = {+ active: boolean;+ // The store subscription is linked to a different Linkwarden account+ foreignAccount: boolean;+};+// Asks the server to validate the purchase with Apple/Google and activate the// subscription. The identifiers are only lookup keys — the server re-fetches the// authoritative state from the store, so retrying is always safe.@@ -161,7 +167,7 @@ export const verifyPurchaseWithServer = async (auth: MobileAuth,purchase: Purchase,attempts = 5-): Promise<boolean> => {+): Promise<VerifyPurchaseResult> => {const body =Platform.OS === "ios"? {@@ -188,15 +194,21 @@ export const verifyPurchaseWithServer = async (if (res.ok) {const data = await res.json().catch(() => null);- return Boolean(data?.active);+ return { active: Boolean(data?.active), foreignAccount: false };}// Client errors won't succeed on retry (bad token, foreign purchase, ...)- if (res.status >= 400 && res.status < 500) return false;+ if (res.status >= 400 && res.status < 500) {+ const data = await res.json().catch(() => null);+ return {+ active: false,+ foreignAccount: data?.code === "purchase_linked_to_another_account",+ };+ }} catch {}await wait(1500);}- return false;+ return { active: false, foreignAccount: false };};diff --git a/apps/web/lib/api/billing/syncStoreSubscription.ts b/apps/web/lib/api/billing/syncStoreSubscription.tsindex a673e5cf..7d382204 100644--- a/apps/web/lib/api/billing/syncStoreSubscription.ts+++ b/apps/web/lib/api/billing/syncStoreSubscription.ts@@ -16,6 +16,16 @@ export const UUID_REGEX =export const isStoreBillingConfigured = () =>isAppStoreConfigured() || isGooglePlayConfigured();+// Error code thrown (hint-driven syncs only) when the store purchase is stamped+// with a different Linkwarden account, so the API layer can surface a precise+// error to the app.+export const FOREIGN_PURCHASE = "FOREIGN_PURCHASE";++const foreignPurchaseError = () =>+ Object.assign(new Error("This purchase is linked to another account."), {+ code: FOREIGN_PURCHASE,+ });+// Sandbox/TestFlight and Play license-tester purchases only grant entitlements in// production when explicitly allowed (e.g. during App Review).const acceptsSandbox = () =>@@ -263,7 +273,7 @@ export default async function syncStoreSubscription(console.warn(`App Store transaction ${state.originalTransactionId} belongs to another account.`);- return null;+ throw foreignPurchaseError();}if (!shouldGrant(state) || !state.active)@@ -291,7 +301,7 @@ export default async function syncStoreSubscription(console.warn("Play Store purchase token belongs to another account (obfuscated id mismatch).");- return null;+ throw foreignPurchaseError();}if (!shouldGrant(state) || !state.active)diff --git a/apps/web/pages/api/v1/billing/verify-store-purchase.ts b/apps/web/pages/api/v1/billing/verify-store-purchase.tsindex 4a0f6155..d0b83078 100644--- a/apps/web/pages/api/v1/billing/verify-store-purchase.ts+++ b/apps/web/pages/api/v1/billing/verify-store-purchase.ts@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from "next";import verifyToken from "@/lib/api/verifyToken";import { prisma } from "@linkwarden/prisma";import syncStoreSubscription, {+ FOREIGN_PURCHASE,type StorePurchaseHint,} from "@/lib/api/billing/syncStoreSubscription";import { isAppStoreConfigured } from "@/lib/api/billing/appStore";@@ -74,7 +75,15 @@ export default async function verifyStorePurchase(: "No active subscription found for this purchase.",active: Boolean(subscription?.active),});- } catch (error) {+ } catch (error: any) {+ if (error?.code === FOREIGN_PURCHASE) {+ return res.status(409).json({+ response: "This purchase is linked to another Linkwarden account.",+ code: "purchase_linked_to_another_account",+ active: false,+ });+ }+console.error("Error verifying store purchase:", error);return res.status(500).json({ response: "Server Error" });}