⚡️⚡️⚡️ 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
store Google Play purchase token & reset store fields on provider/store switch
daniel31x134cac137572c8
diff --git a/apps/mobile/app/subscribe.tsx b/apps/mobile/app/subscribe.tsxindex d060d576..eca4bf2c 100644--- a/apps/mobile/app/subscribe.tsx+++ b/apps/mobile/app/subscribe.tsx@@ -8,7 +8,7 @@ import { ensureCloudIsReachable } from "@/lib/ensureCloudIsReachable";import useAuthStore from "@/store/auth";import { useConfig } from "@linkwarden/router/config";import { useUser } from "@linkwarden/router/user";-import { Plan } from "@linkwarden/types/global";+import { MobileAuth, Plan } from "@linkwarden/types/global";import { router } from "expo-router";import { useColorScheme } from "nativewind";import {@@ -44,6 +44,37 @@ import {const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+const saveGooglePurchaseToken = async (+ auth: MobileAuth,+ purchaseToken: string,+ attempts = 5+) => {+ for (let attempt = 0; attempt < attempts; attempt++) {+ try {+ const res = await fetch(+ `${auth.instance}/api/v1/billing/google-purchase-token`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${auth.session}`,+ },+ body: JSON.stringify({ purchaseToken }),+ }+ );++ if (res.ok) {+ const data = await res.json().catch(() => null);+ if (data?.updated > 0) return;+ } else if (res.status === 409) {+ return;+ }+ } catch {}++ await wait(1500);+ }+};+const features = [{ title: "Save & organize", icon: Bookmark },{ title: "Permanent archives", icon: Archive },@@ -297,10 +328,16 @@ export default function SubscribeScreen() {if (alreadySubscribed) return;- const { customerInfo } = await Purchases.purchasePackage(+ const { customerInfo, transaction } = await Purchases.purchasePackage(selectedPlan.package);await activateSubscription(customerInfo);++ // Android only: persist the Google Play purchase token (null on iOS). Fire-and-forget+ // after activation, by which point the subscription row exists server-side.+ if (transaction?.purchaseToken) {+ saveGooglePurchaseToken(auth, transaction.purchaseToken);+ }} catch (error: any) {if (!error?.userCancelled) {Alert.alert("Purchase failed", "Could not complete purchase.");diff --git a/apps/web/lib/api/billing/handleStripeSubscription.ts b/apps/web/lib/api/billing/handleStripeSubscription.tsindex ab350654..d136bdf0 100644--- a/apps/web/lib/api/billing/handleStripeSubscription.ts+++ b/apps/web/lib/api/billing/handleStripeSubscription.ts@@ -1,6 +1,7 @@import Stripe from "stripe";import { prisma } from "@linkwarden/prisma";import stripeSDK from "./stripeSDK";+import { stripeStoreReset } from "./stripeStoreReset";type Data = {id: string;@@ -36,6 +37,7 @@ export default async function handleSubscription({data: {active,provider: "STRIPE",+ ...stripeStoreReset,quantity,currentPeriodStart: new Date(periodStart * 1000),currentPeriodEnd: new Date(periodEnd * 1000),@@ -77,6 +79,7 @@ export default async function handleSubscription({create: {active,provider: "STRIPE",+ ...stripeStoreReset,stripeSubscriptionId: id,quantity,currentPeriodStart: new Date(periodStart * 1000),@@ -90,6 +93,7 @@ export default async function handleSubscription({update: {active,provider: "STRIPE",+ ...stripeStoreReset,stripeSubscriptionId: id,quantity,currentPeriodStart: new Date(periodStart * 1000),diff --git a/apps/web/lib/api/billing/stripeStoreReset.ts b/apps/web/lib/api/billing/stripeStoreReset.tsnew file mode 100644index 00000000..136ba151--- /dev/null+++ b/apps/web/lib/api/billing/stripeStoreReset.ts@@ -0,0 +1,14 @@+import { Prisma } from "@linkwarden/prisma/client";++// A Stripe subscription is web-only, so every write that sets `provider: "STRIPE"`+// clears the RevenueCat/IAP-store fields. This keeps a row that switched over from+// RevenueCat from carrying stale store identifiers, and is shared across every Stripe+// write path so they can't drift apart.+export const stripeStoreReset = {+ store: null,+ revenueCatAppUserId: null,+ storeOriginalTransactionId: null,+ storeProductId: null,+ googlePurchaseToken: null,+ revenuecatMetadata: Prisma.DbNull,+};diff --git a/apps/web/lib/api/billing/syncRevenuecatSubscription.ts b/apps/web/lib/api/billing/syncRevenuecatSubscription.tsindex e55f5d84..eb3e9036 100644--- a/apps/web/lib/api/billing/syncRevenuecatSubscription.ts+++ b/apps/web/lib/api/billing/syncRevenuecatSubscription.ts@@ -1,5 +1,5 @@import { prisma } from "@linkwarden/prisma";-import type { Prisma, Subscription, User } from "@linkwarden/prisma/client";+import type { Prisma, User } from "@linkwarden/prisma/client";import checkRevenuecatSubscription from "./checkRevenuecatSubscription";const hasRevenuecatCredentials = () =>@@ -32,17 +32,24 @@ export default async function syncRevenuecatSubscription(return null;}+ const isGooglePlay = subscription.store === "PLAY_STORE";+const data = {active: subscription.active,provider: "REVENUECAT" as const,+ // Clear any leftover Stripe identifier when switching Stripe -> RevenueCat.+ stripeSubscriptionId: null,revenueCatAppUserId: user.uuid,store: subscription.store,storeOriginalTransactionId: subscription.storeOriginalTransactionId,storeProductId: subscription.storeProductId,- revenuecatMetadata: subscription.raw,+ revenuecatMetadata: subscription.raw as Prisma.InputJsonValue,currentPeriodStart: subscription.currentPeriodStart,currentPeriodEnd: subscription.currentPeriodEnd,quantity: 1,+ // Leave the client-captured token alone for Google Play; clear a stale one+ // when switching to a non-Google store (e.g. Google -> Apple).+ ...(isGooglePlay ? {} : { googlePurchaseToken: null }),};const existingSubscription = await prisma.subscription.findUnique({diff --git a/apps/web/lib/api/billing/verifySubscription.ts b/apps/web/lib/api/billing/verifySubscription.tsindex 59b92436..a8540b58 100644--- a/apps/web/lib/api/billing/verifySubscription.ts+++ b/apps/web/lib/api/billing/verifySubscription.ts@@ -2,6 +2,7 @@ import { prisma } from "@linkwarden/prisma";import { Subscription, User } from "@linkwarden/prisma/client";import checkStripeSubscriptionByEmail from "./checkStripeSubscriptionByEmail";import syncRevenuecatSubscription from "./syncRevenuecatSubscription";+import { stripeStoreReset } from "./stripeStoreReset";interface UserIncludingSubscription extends User {subscriptions: Subscription | null;@@ -62,6 +63,7 @@ export default async function verifySubscription(create: {active,provider: "STRIPE",+ ...stripeStoreReset,stripeSubscriptionId,currentPeriodStart: new Date(currentPeriodStart),currentPeriodEnd: new Date(currentPeriodEnd),@@ -71,6 +73,7 @@ export default async function verifySubscription(update: {active,provider: "STRIPE",+ ...stripeStoreReset,stripeSubscriptionId,currentPeriodStart: new Date(currentPeriodStart),currentPeriodEnd: new Date(currentPeriodEnd),diff --git a/apps/web/pages/api/v1/billing/google-purchase-token.ts b/apps/web/pages/api/v1/billing/google-purchase-token.tsnew file mode 100644index 00000000..bba43f79--- /dev/null+++ b/apps/web/pages/api/v1/billing/google-purchase-token.ts@@ -0,0 +1,56 @@+import type { NextApiRequest, NextApiResponse } from "next";+import { prisma } from "@linkwarden/prisma";+import verifyToken from "@/lib/api/verifyToken";++export default async function googlePurchaseToken(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method !== "POST") {+ return res.status(405).json({ response: "Method not allowed." });+ }++ if (process.env.NEXT_PUBLIC_DEMO === "true")+ return res.status(400).json({+ response:+ "This action is disabled because this is a read-only demo of Linkwarden.",+ });++ if (!process.env.REVENUECAT_WEBHOOK_AUTHORIZATION) {+ return res.status(400).json({+ response:+ "This action is disabled because RevenueCat is not initialized.",+ });+ }++ const token = await verifyToken({ req });++ if (typeof token === "string") {+ return res.status(401).json({ response: token });+ }++ const purchaseToken = req.body?.purchaseToken;++ if (typeof purchaseToken !== "string" || !purchaseToken.trim()) {+ return res.status(400).json({ response: "Missing purchase token." });+ }++ try {+ const { count } = await prisma.subscription.updateMany({+ where: {+ userId: token.id,+ provider: "REVENUECAT",+ store: "PLAY_STORE",+ },+ data: {+ googlePurchaseToken: purchaseToken,+ },+ });++ return res.status(200).json({ response: "Done!", updated: count });+ } catch (error) {+ return res+ .status(409)+ .json({ response: "Purchase token already in use.", updated: 0 });+ }+}diff --git a/apps/web/pages/api/v1/webhooks/revenuecat.ts b/apps/web/pages/api/v1/webhooks/revenuecat.tsindex 90f795b8..18ed82e0 100644--- a/apps/web/pages/api/v1/webhooks/revenuecat.ts+++ b/apps/web/pages/api/v1/webhooks/revenuecat.ts@@ -80,12 +80,18 @@ export default async function revenueCatWebhook(const currentPeriodEnd = new Date(event.expiration_at_ms);const active = event.type !== "EXPIRATION" && currentPeriodEnd > new Date();+ const mappedStore = mapStore(event.store);+const storeData = {- store: mapStore(event.store),+ // Clear any leftover Stripe identifier when switching Stripe -> RevenueCat.+ stripeSubscriptionId: null,+ store: mappedStore,storeOriginalTransactionId: event.original_transaction_id ?? undefined,storeProductId: event.product_id ?? undefined,- storeEnvironment: event.environment,revenuecatMetadata: req.body.event,+ // Leave the client-captured token alone for Google Play; clear a stale one+ // when this isn't a Google Play subscription (e.g. Google -> Apple).+ ...(mappedStore === "PLAY_STORE" ? {} : { googlePurchaseToken: null }),};try {diff --git a/packages/prisma/migrations/20260617150934_replace_store_environment_with_google_purchase_token/migration.sql b/packages/prisma/migrations/20260617150934_replace_store_environment_with_google_purchase_token/migration.sqlnew file mode 100644index 00000000..c82e0cce--- /dev/null+++ b/packages/prisma/migrations/20260617150934_replace_store_environment_with_google_purchase_token/migration.sql@@ -0,0 +1,10 @@+-- AlterTable+ALTER TABLE "Subscription" DROP COLUMN "storeEnvironment",+ADD COLUMN "googlePurchaseToken" TEXT;++-- DropEnum+DROP TYPE "SubscriptionEnvironment";++-- CreateIndex+CREATE UNIQUE INDEX "Subscription_googlePurchaseToken_key" ON "Subscription"("googlePurchaseToken");+diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex 718ee2ff..14850c4c 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -229,9 +229,9 @@ model Subscription {provider SubscriptionProviderstore SubscriptionStore?- storeOriginalTransactionId String? @unique+ storeOriginalTransactionId String? @uniquestoreProductId String?- storeEnvironment SubscriptionEnvironment?+ googlePurchaseToken String? @unique // Google Play purchase token — captured client-side; RevenueCat never exposes it, and Google's API needs itrevenuecatMetadata Json?user User @relation(fields: [userId], references: [id], onDelete: Cascade)@@ -251,11 +251,6 @@ enum SubscriptionStore {PLAY_STORE}-enum SubscriptionEnvironment {- PRODUCTION- SANDBOX-}-model AccessToken {id Int @id @default(autoincrement())name String