Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat(mobile): prepare shared creator-code paywall integration (#2334)

Joshuafef65ff823d8
diff --git a/openwhispr-mobile/.env.example b/openwhispr-mobile/.env.example
index 389e1609b..40e57c934 100644
--- a/openwhispr-mobile/.env.example
+++ b/openwhispr-mobile/.env.example
@@ -26,6 +26,12 @@ EXPO_PUBLIC_SUPERWALL_ANDROID_API_KEY=
EXPO_PUBLIC_REVENUECAT_IOS_API_KEY=
EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY=
+# Optional iOS creator offers. Leave BOTH empty for the held release.
+# Development domain: open-whispr-affiliate-sandbox.dub.link
+# Production domain: try.openwhispr.com. Only a public dub_pk_ key belongs here.
+EXPO_PUBLIC_AFFILIATE_DOMAIN=
+EXPO_PUBLIC_AFFILIATE_PUBLISHABLE_KEY=
+
# Optional: Google Calendar OAuth client IDs for iOS. Development builds use
# the development value when present and otherwise fall back to the production
# value. The redirect scheme and URI are derived from the selected client ID.
diff --git a/openwhispr-mobile/app.config.js b/openwhispr-mobile/app.config.js
index a7e02ff2b..fe6221b39 100644
--- a/openwhispr-mobile/app.config.js
+++ b/openwhispr-mobile/app.config.js
@@ -119,12 +119,37 @@ module.exports = () => {
const iosQueries = iosInfoPlist.LSApplicationQueriesSchemes ?? [];
const googleCalendar = createGoogleCalendarConfig(environment);
+ const affiliateDomain = firstNonEmpty(process.env.EXPO_PUBLIC_AFFILIATE_DOMAIN);
+ const affiliatePublishableKey = firstNonEmpty(process.env.EXPO_PUBLIC_AFFILIATE_PUBLISHABLE_KEY);
+ const affiliate =
+ affiliateDomain && affiliatePublishableKey
+ ? { domain: affiliateDomain, publishableKey: affiliatePublishableKey }
+ : undefined;
+ if (
+ affiliate &&
+ (!affiliatePublishableKey.startsWith('dub_pk_') ||
+ affiliateDomain !==
+ (environment.isDevelopment
+ ? 'open-whispr-affiliate-sandbox.dub.link'
+ : 'try.openwhispr.com'))
+ )
+ throw new Error(
+ 'Affiliate configuration must match the app environment and use a publishable key',
+ );
+
return {
...expo,
name: expo.name,
scheme: singleOrMany([environment.scheme, googleCalendar.iosRedirectScheme]),
ios: {
...expo.ios,
+ // Expo writes any associatedDomains array, even an empty one, as a new entitlement.
+ ...(affiliate && {
+ associatedDomains: unique([
+ ...(expo.ios?.associatedDomains ?? []),
+ `applinks:${affiliate.domain}`,
+ ]),
+ }),
bundleIdentifier: environment.iosBundleIdentifier,
entitlements: {
...(expo.ios?.entitlements ?? {}),
@@ -148,6 +173,7 @@ module.exports = () => {
plugins: withBrandFonts(expo.plugins),
extra: {
...expo.extra,
+ affiliate,
openWhispr: {
...environment,
googleCalendar,
diff --git a/openwhispr-mobile/app/+native-intent.tsx b/openwhispr-mobile/app/+native-intent.tsx
new file mode 100644
index 000000000..987dc8524
--- /dev/null
+++ b/openwhispr-mobile/app/+native-intent.tsx
@@ -0,0 +1,5 @@
+import { captureAffiliateArrival, isAffiliateDomainLink } from '@/lib/affiliateLink';
+
+export function redirectSystemPath({ path }: { path: string; initial: boolean }) {
+ return captureAffiliateArrival(path) || isAffiliateDomainLink(path) ? '/' : path;
+}
diff --git a/openwhispr-mobile/app/_layout.tsx b/openwhispr-mobile/app/_layout.tsx
index 33e2ba1a4..4f96d6999 100644
--- a/openwhispr-mobile/app/_layout.tsx
+++ b/openwhispr-mobile/app/_layout.tsx
@@ -25,6 +25,7 @@ import { OnboardingFlow } from '@/screens/onboarding/OnboardingFlow';
import { AnimatedSplash } from '@/components/features/AnimatedSplash';
import { useKeyboardHandoff } from '@/hooks/useKeyboardHandoff';
import { useRevenueCatIdentity } from '@/hooks/useRevenueCatIdentity';
+import { useAffiliateAttribution } from '@/hooks/useAffiliateAttribution';
import { useAnonymousOnboardingSession } from '@/hooks/useAnonymousOnboardingSession';
import { useGuestPrivateMode } from '@/hooks/useGuestPrivateMode';
import { runMigrations } from '@/db/migrate';
@@ -48,6 +49,7 @@ function RootLayout() {
useKeyboardHandoff();
useRevenueCatIdentity();
useAnonymousOnboardingSession();
+ useAffiliateAttribution();
useGuestPrivateMode();
const [fontsLoaded] = useFonts({
diff --git a/openwhispr-mobile/docs/affiliate-integration.md b/openwhispr-mobile/docs/affiliate-integration.md
new file mode 100644
index 000000000..232161bad
--- /dev/null
+++ b/openwhispr-mobile/docs/affiliate-integration.md
@@ -0,0 +1,58 @@
+# Creator codes and verified monthly offers
+
+iOS/iPadOS only; Android is excluded. The feature is off unless both affiliate environment variables are set.
+
+## Configuration
+
+- `EXPO_PUBLIC_AFFILIATE_DOMAIN` and `EXPO_PUBLIC_AFFILIATE_PUBLISHABLE_KEY`. Only a public `dub_pk_` key belongs in the client.
+- Development uses `open-whispr-affiliate-sandbox.dub.link`, production `try.openwhispr.com`. A domain that doesn't match the app environment fails configuration.
+- `applinks:<domain>` is added to Associated Domains only when the feature is configured; an unconfigured build gets no entitlement.
+- The app calls Dub's `/track/open` endpoint directly, always with the explicit link, so nothing reads the clipboard and no extra native SDK is linked.
+- The Account field uses the local `creator-link-input` Expo module (UIKit paste delegate, no pasteboard reads). A binary built without it falls back to a plain text field, so a JS update can't break Account on an older build.
+
+## Consent
+
+Usage Analytics and iOS tracking authorization (`authorized`, or `notSupported`) gate link resolution, claiming, offer allocation and redemption. Permission is checked before each of those steps.
+
+- Onboarding: a user who arrived through a trusted creator link sees the existing tracking step before the paywall, so their offer can be checked. Everyone else keeps the usual order (tracking after signup).
+- An explicit **Use code** on the paywall, or Go/Paste on Account, asks iOS for tracking permission if it hasn't asked yet.
+- With tracking denied, Account offers **Open Settings**; with Usage Analytics off, **Open Privacy & Data**. Ordinary purchasing stays available either way.
+
+## User journeys
+
+- **Inbound link** (cold or warm start): `app/+native-intent.tsx` captures a trusted link (one trailing slash allowed) and opens Home. Any other link on the creator domain also opens Home, never a route. The candidate persists; `inboundOfferPending` is consumed once, for the first onboarding offer.
+- **Onboarding paywall**: only confirmed free Cloud users see it. Monthly shows **Have a creator code?** with an explicit **Use code**; typing never submits. Annual hides the creator controls without deleting saved attribution.
+- **Account**: the creator row expands a field that submits on a completed system Paste or keyboard Go. A verified offer opens the Monthly paywall directly. If the offer is unavailable, or the paywall doesn't show it (skipped or failed), the row offers **View plans**. Dismissal never opens another paywall. Leaving Account cancels pending work.
+- **Anonymous sessions** can redeem and sign up later. An unclaimed candidate follows the anonymous session into the account it becomes; a claimed one transfers through the server's link workflow.
+
+## Attribution and offer stock
+
+Saving attribution (`/api/affiliate/claim`) and allocating an Apple offer (`/api/affiliate/apple-offer`) are separate mutations. Rendering an ordinary paywall calls neither. The server keeps the first saved creator permanently, and commissions are server-owned. A claim the server accepted is recorded locally even if the screen stopped waiting for it, so a retry finds the creator saved.
+
+## Superwall contract
+
+The paywall with the creator-code input runs under its own placement, `creator_code_paywall`. With creator codes configured, every onboarding paywall and Account's verified creator offer register that placement instead of `onboarding_paywall` / `account_billing_open`. Each keeps its own gate rules: onboarding never sends anyone to sign-in and moves on if Superwall fails; Account's offer fails closed. Plans & Billing and the feature paywalls keep their usual placements, and a build without creator codes never uses this one. The placement needs a campaign in Superwall; if Superwall reports it missing, onboarding moves on without a paywall.
+
+Callback variables are flat dictionary keys, including their dots:
+
+| Request | Name | Keys |
+| ------- | -------------------- | ------------------------------------------------------------------------------------------------------ |
+| Apply | `creatorCodeApply` | the creator input's node value, `products.selectedIndex`, `products.secondary.identifier` |
+| Redeem | `creatorOfferRedeem` | `products.selectedIndex`, `products.secondary.identifier`, `callbacks.creatorCodeApply.data.*` results |
+
+- Apply returns `priceText`, `renewalText` and `offerToken`, which Redeem sends back as `callbacks.creatorCodeApply.data.<name>`.
+- Initial Account/inbound offers use the params `creator_offer_ready`, `creator_offer_price`, `creator_offer_renewal` and `creator_offer_token` (`params.` prefix in callbacks). Superwall keeps omitted params on cached reuse, so every presentation sets all four, with false/empty values for an ordinary paywall.
+- `CREATOR_INPUT_KEY` in `src/lib/affiliatePaywall.ts` is the node id of the paywall's creator input. Monthly is `products.selectedIndex === 1` (`secondary`). Update them with the paywall: a mismatch fails closed (codes stop working; ordinary purchase is unaffected).
+- Only display strings and an opaque presentation token reach Superwall, never the Apple URL, code, cookies or billing ids.
+
+## Redemption
+
+Redeeming requires the displayed price, renewal text, product and token. It rechecks identity (user, session, RevenueCat app user id), consent, storefront, the StoreKit monthly product, currency, regular price and expiry, then opens the official Apple offer-code URL. It never calls ordinary Purchase.
+
+On return from Apple the app reconciles billing up to three times over about seven seconds. A confirmed subscription completes the gate as a purchase (AppsFlyer subscription event and the usual purchase completion), then closes the paywall. **Use code** stays locked while that check runs, so a single-use code can't be opened twice.
+
+## Release limits
+
+- The native Account field needs a rebuilt binary; older binaries use the plain-field fallback.
+- Production paywall routing, the production campaign association and activation are separate release work.
+- Workspace members can't yet start a separate personal purchase from Account; this is a deferred case.
diff --git a/openwhispr-mobile/modules/creator-link-input/expo-module.config.json b/openwhispr-mobile/modules/creator-link-input/expo-module.config.json
new file mode 100644
index 000000000..0c14d4596
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/expo-module.config.json
@@ -0,0 +1,4 @@
+{
+ "platforms": ["ios"],
+ "ios": { "modules": ["CreatorLinkInputModule"] }
+}
diff --git a/openwhispr-mobile/modules/creator-link-input/ios/CreatorLinkInput.podspec b/openwhispr-mobile/modules/creator-link-input/ios/CreatorLinkInput.podspec
new file mode 100644
index 000000000..398db15fa
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/ios/CreatorLinkInput.podspec
@@ -0,0 +1,20 @@
+require 'json'
+
+package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
+
+Pod::Spec.new do |s|
+ s.name = 'CreatorLinkInput'
+ s.version = package['version']
+ s.summary = package['description']
+ s.description = package['description']
+ s.license = 'MIT'
+ s.author = 'OpenWhispr Team'
+ s.homepage = 'https://github.com/OpenWhispr/openwhispr'
+ s.platforms = { :ios => '15.1' }
+ s.swift_version = '5.9'
+ s.source = { git: 'https://github.com/OpenWhispr/openwhispr.git' }
+ s.static_framework = true
+ s.dependency 'ExpoModulesCore'
+ s.frameworks = 'UIKit'
+ s.source_files = '**/*.{h,m,swift}'
+end
diff --git a/openwhispr-mobile/modules/creator-link-input/ios/CreatorLinkInputModule.swift b/openwhispr-mobile/modules/creator-link-input/ios/CreatorLinkInputModule.swift
new file mode 100644
index 000000000..627c4c53b
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/ios/CreatorLinkInputModule.swift
@@ -0,0 +1,125 @@
+import ExpoModulesCore
+import UIKit
+
+public class CreatorLinkInputModule: Module {
+ public func definition() -> ModuleDefinition {
+ Name("CreatorLinkInput")
+ View(CreatorLinkInputView.self) {
+ Events("onInput")
+ Prop("value") { (view, value: String) in view.pendingValue = value }
+ Prop("mostRecentEventCount") { (view, count: Int) in view.acknowledgedEventCount = count }
+ Prop("fontFamily") { (view, name: String) in view.setFont(named: name) }
+ Prop("editable") { (view, editable: Bool) in
+ view.field.isEnabled = editable
+ if !editable { view.field.resignFirstResponder() }
+ }
+ OnViewDidUpdateProps { view in view.applyValue() }
+ }
+ }
+}
+
+final class CreatorLinkInputView: ExpoView, UITextFieldDelegate, UITextPasteDelegate, UITextDropDelegate {
+ let field = UITextField()
+ let onInput = EventDispatcher()
+ var pendingValue = ""
+ var acknowledgedEventCount = 0
+ private var eventCount = 0
+ private var replacingPaste = false
+
+ required init(appContext: AppContext? = nil) {
+ super.init(appContext: appContext)
+ field.delegate = self
+ field.pasteDelegate = self
+ field.textDropDelegate = self
+ field.keyboardType = .URL
+ field.returnKeyType = .go
+ field.autocorrectionType = .no
+ field.autocapitalizationType = .none
+ field.smartQuotesType = .no
+ field.smartDashesType = .no
+ field.spellCheckingType = .no
+ field.accessibilityLabel = "Creator code or link"
+ field.placeholder = "Enter a creator code or link"
+ setFont(named: "")
+ field.adjustsFontForContentSizeCategory = true
+ field.textColor = .label
+ field.addTarget(self, action: #selector(changed), for: .editingChanged)
+ addSubview(field)
+ }
+
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ field.frame = bounds.insetBy(dx: 12, dy: 10)
+ }
+
+ // The app passes its regular face. Yowza is embedded under its PostScript name;
+ // without it the app's Space Grotesk alias is an expo-font name UIKit can't
+ // resolve, so fall back to that face's PostScript name.
+ func setFont(named name: String) {
+ let face =
+ UIFont(name: name, size: 16) ?? UIFont(name: "SpaceGrotesk-Regular", size: 16)
+ ?? .systemFont(ofSize: 16)
+ field.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: face)
+ }
+
+ func applyValue() {
+ // A delayed JS render must not replace a newer native edit or its selection.
+ guard acknowledgedEventCount == eventCount, field.text != pendingValue else { return }
+ field.text = pendingValue
+ }
+
+ private func emit(_ source: String) {
+ eventCount += 1
+ onInput(["text": field.text ?? "", "source": source, "eventCount": eventCount])
+ }
+
+ @objc private func changed() {
+ if !replacingPaste { emit("edit") }
+ }
+
+ func textFieldShouldReturn(_ textField: UITextField) -> Bool {
+ guard field.isEnabled else { return false }
+ emit("submit")
+ field.resignFirstResponder()
+ return true
+ }
+
+ func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
+ let result = (textField.text ?? "") as NSString
+ return result.replacingCharacters(in: range, with: string).utf16.count <= 2048
+ }
+
+ func textPasteConfigurationSupporting(_ textPasteConfigurationSupporting: UITextPasteConfigurationSupporting,
+ performPasteOf attributedString: NSAttributedString,
+ to textRange: UITextRange) -> UITextRange {
+ // UIKit invokes this only once the user's paste has resolved. Never read UIPasteboard.
+ guard field.isEnabled, field.isFirstResponder, window != nil,
+ !attributedString.string.isEmpty else { return textRange }
+ let start = field.offset(from: field.beginningOfDocument, to: textRange.start)
+ let length = field.offset(from: textRange.start, to: textRange.end)
+ let proposed = ((field.text ?? "") as NSString).replacingCharacters(
+ in: NSRange(location: start, length: length), with: attributedString.string
+ )
+ guard proposed.utf16.count <= 2048 else {
+ emit("tooLong")
+ return textRange
+ }
+ replacingPaste = true
+ field.replace(textRange, withText: attributedString.string)
+ replacingPaste = false
+ emit("paste")
+ field.resignFirstResponder()
+ let beginning = field.position(from: field.beginningOfDocument, offset: start)
+ let end = field.position(from: field.beginningOfDocument, offset: start + attributedString.length)
+ if let beginning, let end, let inserted = field.textRange(from: beginning, to: end) {
+ return inserted
+ }
+ return textRange
+ }
+
+ func textDroppableView(_ textDroppableView: UIView & UITextDroppable,
+ proposalForDrop drop: UITextDropRequest) -> UITextDropProposal {
+ // Dropping text is not the explicit Paste action that triggers an offer check.
+ UITextDropProposal(operation: .cancel)
+ }
+}
diff --git a/openwhispr-mobile/modules/creator-link-input/package.json b/openwhispr-mobile/modules/creator-link-input/package.json
new file mode 100644
index 000000000..9957d1cfd
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "creator-link-input",
+ "version": "1.0.0",
+ "description": "Native creator-link field with explicit system paste completion",
+ "main": "src/index.tsx",
+ "private": true,
+ "peerDependencies": {
+ "expo": "*",
+ "react": "*",
+ "react-native": "*"
+ }
+}
diff --git a/openwhispr-mobile/modules/creator-link-input/src/__tests__/CreatorLinkInput.test.tsx b/openwhispr-mobile/modules/creator-link-input/src/__tests__/CreatorLinkInput.test.tsx
new file mode 100644
index 000000000..ad4d97801
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/src/__tests__/CreatorLinkInput.test.tsx
@@ -0,0 +1,73 @@
+import React from 'react';
+import { fireEvent, render } from '@testing-library/react-native';
+import { View } from 'react-native';
+import { CreatorLinkInput } from '..';
+
+jest.mock('expo', () => ({
+ requireNativeView: () => require('react-native').View,
+ requireOptionalNativeModule: () => ({}),
+}));
+
+it('treats typing, completed paste and keyboard Go as different user actions', () => {
+ const onChangeText = jest.fn();
+ const onPaste = jest.fn();
+ const onSubmit = jest.fn();
+ const screen = render(
+ <CreatorLinkInput
+ value=""
+ editable
+ fontFamily="Yowza-Std-Regular"
+ onChangeText={onChangeText}
+ onPaste={onPaste}
+ onSubmit={onSubmit}
+ onInvalidPaste={jest.fn()}
+ />,
+ );
+ const input = () => screen.UNSAFE_getByType(View);
+ fireEvent(input(), 'input', {
+ nativeEvent: { text: 'https://sandbox.dub.link/a', source: 'edit', eventCount: 1 },
+ });
+ expect(onChangeText).toHaveBeenCalledWith('https://sandbox.dub.link/a');
+ expect(onPaste).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ fireEvent(input(), 'input', {
+ nativeEvent: { text: 'https://sandbox.dub.link/complete', source: 'paste', eventCount: 2 },
+ });
+ expect(onPaste).toHaveBeenCalledWith('https://sandbox.dub.link/complete');
+ expect(input().props.mostRecentEventCount).toBe(2);
+ fireEvent(input(), 'input', {
+ nativeEvent: { text: 'https://sandbox.dub.link/typed', source: 'submit', eventCount: 3 },
+ });
+ expect(onSubmit).toHaveBeenCalledWith('https://sandbox.dub.link/typed');
+ expect(input().props.fontFamily).toBe('Yowza-Std-Regular');
+});
+
+it('reports oversized paste without submitting old text and ignores disabled callbacks', () => {
+ const onPaste = jest.fn();
+ const onSubmit = jest.fn();
+ const onChangeText = jest.fn();
+ const onInvalidPaste = jest.fn();
+ const props = {
+ value: 'old',
+ fontFamily: 'Yowza-Std-Regular',
+ onChangeText,
+ onPaste,
+ onSubmit,
+ onInvalidPaste,
+ };
+ const screen = render(<CreatorLinkInput {...props} editable />);
+ fireEvent(screen.UNSAFE_getByType(View), 'input', {
+ nativeEvent: { text: 'old', source: 'tooLong', eventCount: 1 },
+ });
+ expect(onInvalidPaste).toHaveBeenCalledTimes(1);
+ expect(onPaste).not.toHaveBeenCalled();
+ screen.rerender(<CreatorLinkInput {...props} editable={false} />);
+ for (const source of ['paste', 'edit', 'submit']) {
+ fireEvent(screen.UNSAFE_getByType(View), 'input', {
+ nativeEvent: { text: 'late', source, eventCount: 2 },
+ });
+ }
+ expect(onPaste).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(onChangeText).not.toHaveBeenCalled();
+});
diff --git a/openwhispr-mobile/modules/creator-link-input/src/__tests__/CreatorLinkInputFallback.test.tsx b/openwhispr-mobile/modules/creator-link-input/src/__tests__/CreatorLinkInputFallback.test.tsx
new file mode 100644
index 000000000..eee041948
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/src/__tests__/CreatorLinkInputFallback.test.tsx
@@ -0,0 +1,31 @@
+import React from 'react';
+import { fireEvent, render } from '@testing-library/react-native';
+import { CreatorLinkInput } from '..';
+
+const mockRequireNativeView = jest.fn();
+jest.mock('expo', () => ({
+ requireNativeView: (name: string) => mockRequireNativeView(name),
+ requireOptionalNativeModule: () => null,
+}));
+
+it('uses a plain field on a binary built without the native view', () => {
+ const onSubmit = jest.fn();
+ const onChangeText = jest.fn();
+ const screen = render(
+ <CreatorLinkInput
+ value=""
+ editable
+ fontFamily="Yowza-Std-Regular"
+ onChangeText={onChangeText}
+ onPaste={jest.fn()}
+ onSubmit={onSubmit}
+ onInvalidPaste={jest.fn()}
+ />,
+ );
+ const field = screen.getByLabelText('Creator code or link');
+ fireEvent.changeText(field, 'creator');
+ fireEvent(field, 'submitEditing', { nativeEvent: { text: 'creator' } });
+ expect(onChangeText).toHaveBeenCalledWith('creator');
+ expect(onSubmit).toHaveBeenCalledWith('creator');
+ expect(mockRequireNativeView).not.toHaveBeenCalled();
+});
diff --git a/openwhispr-mobile/modules/creator-link-input/src/index.tsx b/openwhispr-mobile/modules/creator-link-input/src/index.tsx
new file mode 100644
index 000000000..269c3a152
--- /dev/null
+++ b/openwhispr-mobile/modules/creator-link-input/src/index.tsx
@@ -0,0 +1,93 @@
+import { useState } from 'react';
+import { requireNativeView, requireOptionalNativeModule } from 'expo';
+import {
+ Platform,
+ PlatformColor,
+ TextInput,
+ useWindowDimensions,
+ type NativeSyntheticEvent,
+ type ViewProps,
+} from 'react-native';
+
+type InputEvent = {
+ text: string;
+ source: 'edit' | 'paste' | 'submit' | 'tooLong';
+ eventCount: number;
+};
+type Props = {
+ value: string;
+ editable: boolean;
+ fontFamily: string;
+ onChangeText: (text: string) => void;
+ onPaste: (text: string) => void;
+ onSubmit: (text: string) => void;
+ onInvalidPaste: () => void;
+};
+// A JS update can reach a binary built before this module; use the plain field there.
+const NativeInput =
+ Platform.OS === 'ios' && requireOptionalNativeModule('CreatorLinkInput')
+ ? requireNativeView<
+ ViewProps & {
+ value: string;
+ editable: boolean;
+ fontFamily: string;
+ mostRecentEventCount: number;
+ onInput: (event: NativeSyntheticEvent<InputEvent>) => void;
+ }
+ >('CreatorLinkInput')
+ : null;
+
+export function CreatorLinkInput({
+ value,
+ editable,
+ fontFamily,
+ onChangeText,
+ onPaste,
+ onSubmit,
+ onInvalidPaste,
+}: Props) {
+ const [eventCount, setEventCount] = useState(0);
+ const { fontScale } = useWindowDimensions();
+ if (!NativeInput) {
+ return (
+ <TextInput
+ value={value}
+ editable={editable}
+ onChangeText={onChangeText}
+ onSubmitEditing={(event) => onSubmit(event.nativeEvent.text)}
+ accessibilityLabel="Creator code or link"
+ placeholder="Enter a creator code or link"
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ returnKeyType="go"
+ maxLength={2048}
+ placeholderTextColor={PlatformColor('tertiaryLabel')}
+ style={{
+ minHeight: 50,
+ padding: 12,
+ fontFamily,
+ fontSize: 16,
+ color: PlatformColor('label'),
+ }}
+ />
+ );
+ }
+ return (
+ <NativeInput
+ value={value}
+ editable={editable}
+ fontFamily={fontFamily}
+ mostRecentEventCount={eventCount}
+ style={{ height: Math.max(50, 22 * fontScale + 24) }}
+ onInput={({ nativeEvent }) => {
+ setEventCount(nativeEvent.eventCount);
+ if (!editable) return;
+ if (nativeEvent.source === 'paste') onPaste(nativeEvent.text);
+ else if (nativeEvent.source === 'submit') onSubmit(nativeEvent.text);
+ else if (nativeEvent.source === 'tooLong') onInvalidPaste();
+ else onChangeText(nativeEvent.text);
+ }}
+ />
+ );
+}
diff --git a/openwhispr-mobile/package-lock.json b/openwhispr-mobile/package-lock.json
index 7be718a62..202ec5324 100644
--- a/openwhispr-mobile/package-lock.json
+++ b/openwhispr-mobile/package-lock.json
@@ -23,18 +23,18 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"drizzle-orm": "^0.45.2",
- "expo": "~55.0.31",
+ "expo": "~55.0.32",
"expo-apple-authentication": "~55.0.17",
"expo-application": "~55.0.19",
"expo-asset": "~55.0.20",
"expo-audio": "~55.0.18",
- "expo-auth-session": "~55.0.18",
+ "expo-auth-session": "~55.0.19",
"expo-blur": "~55.0.18",
"expo-build-properties": "~55.0.18",
"expo-clipboard": "~55.0.17",
"expo-constants": "~55.0.17",
"expo-crypto": "~55.0.19",
- "expo-dev-client": "~55.0.40",
+ "expo-dev-client": "~55.0.41",
"expo-document-picker": "~55.0.17",
"expo-file-system": "~55.0.26",
"expo-font": "~55.0.4",
@@ -47,7 +47,7 @@
"expo-notifications": "~55.0.27",
"expo-router": "~55.0.18",
"expo-secure-store": "~55.0.18",
- "expo-sharing": "~55.0.24",
+ "expo-sharing": "~55.0.25",
"expo-splash-screen": "~55.0.25",
"expo-sqlite": "~55.0.20",
"expo-status-bar": "~55.0.6",
@@ -2404,9 +2404,9 @@
}
},
"node_modules/@expo/config-plugins": {
- "version": "55.0.11",
- "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-55.0.11.tgz",
- "integrity": "sha512-85ZSmIK8rMfvYbG/2IHtwnykVdb6LI0ZavduM3ZwUMThyyVegYjVsO5Zek2ec8xzPhCmYX0ar5onnFEcwUDUlw==",
+ "version": "55.0.12",
+ "resolved": "https://registry.npmjs.org/@expo/config-plugins/-/config-plugins-55.0.12.tgz",
+ "integrity": "sha512-Z6KlUKqQDZaGU7jag1AaX2wCyFLvGwH/FTEjjIvLV0wTbrj1I91LhlVKYsI6BhUuzan0DOxvYBs9p88jGY5Lrw==",
"license": "MIT",
"dependencies": {
"@expo/config-types": "^55.0.6",
@@ -2420,7 +2420,7 @@
"resolve-from": "^5.0.0",
"semver": "^7.5.4",
"slugify": "^1.6.6",
- "xcode": "^3.0.1",
+ "xcode": "^4.0.0",
"xml2js": "0.6.0"
}
},
@@ -2455,9 +2455,9 @@
}
},
"node_modules/@expo/devcert": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/@expo/devcert/-/devcert-1.2.1.tgz",
- "integrity": "sha512-qC4eaxmKMTmJC2ahwyui6ud8f3W60Ss7pMkpBq40Hu3zyiAaugPXnZ24145U7K36qO9UHdZUVxsCvIpz2RYYCA==",
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@expo/devcert/-/devcert-1.2.2.tgz",
+ "integrity": "sha512-wz1YedXwdNbYqk/PRr34vixnuw1+l6uSwmPXUj649cot5iYNccb2zIOnK7Nonb1Pfd/dxAY6CvU6KM3uSdxC7A==",
"license": "MIT",
"dependencies": {
"@expo/sudo-prompt": "^9.3.1",
@@ -2723,9 +2723,9 @@
}
},
"node_modules/@expo/osascript": {
- "version": "2.7.1",
- "resolved": "https://registry.npmjs.org/@expo/osascript/-/osascript-2.7.1.tgz",
- "integrity": "sha512-Zn03EX6In7ts2lPUW2ESUSkEhEWQN1qqsiXjadtZMJOuZRkMiAg1ZQHuvz9DjByDWNJ2pBwAGyrts9lj9k389g==",
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/@expo/osascript/-/osascript-2.8.1.tgz",
+ "integrity": "sha512-SCi+6q6uOkGhiAn6AIP/OPFgaIq/iKD2oYpnAOg2rShHStJ8ey7wyT127RbOaZXmlcY/62rHOX1WiiMnD8u/BA==",
"license": "MIT",
"dependencies": {
"@expo/spawn-async": "^1.8.0"
@@ -2735,12 +2735,12 @@
}
},
"node_modules/@expo/package-manager": {
- "version": "1.13.1",
- "resolved": "https://registry.npmjs.org/@expo/package-manager/-/package-manager-1.13.1.tgz",
- "integrity": "sha512-y/K+CaYYpZpNGZhSX4HyLT/vyIunFjNfyoxNysPBCefeLKI/VCx6f9LNPzrxayr3rCYO5bl9O8H+HRQK265Nkg==",
+ "version": "1.14.2",
+ "resolved": "https://registry.npmjs.org/@expo/package-manager/-/package-manager-1.14.2.tgz",
+ "integrity": "sha512-sftl0eRVVCarI6grMdjAB3jX2pX1Mt3cdSnajlXS4QyeDkaKRM/ntBy6dcagj1VL0+cEfEqctlyvinmlZdNubg==",
"license": "MIT",
"dependencies": {
- "@expo/json-file": "^11.0.1",
+ "@expo/json-file": "^11.2.1",
"@expo/spawn-async": "^1.8.0",
"chalk": "^4.0.0",
"npm-package-arg": "^11.0.0",
@@ -2749,9 +2749,9 @@
}
},
"node_modules/@expo/package-manager/node_modules/@expo/json-file": {
- "version": "11.0.1",
- "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.0.1.tgz",
- "integrity": "sha512-zxHWj4MKKMAL29ZQSY/Fssx4Thluk40JmuGNaeS078wy/NhlFhnVi+rHHunulE3xJAJ0CM73m8VK2+GkF9eRwQ==",
+ "version": "11.2.1",
+ "resolved": "https://registry.npmjs.org/@expo/json-file/-/json-file-11.2.1.tgz",
+ "integrity": "sha512-UPhKoFCj8BcwgLB1rKQ1CuR/REITnZLiqxHEHOeH1tPsdXcHGtUDh0P5bLbr7oU0nKVdtJ5rzyKx8jniMQdESQ==",
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.20.0",
@@ -2858,10 +2858,10 @@
"license": "MIT"
},
"node_modules/@expo/xcpretty": {
- "version": "4.4.5",
- "resolved": "https://registry.npmjs.org/@expo/xcpretty/-/xcpretty-4.4.5.tgz",
- "integrity": "sha512-J3eL4n4h5QTwfD0SIz8OIk6/+sOL/hFZAMacgCM07UNlxBQfJipEpIC2AQxvGkbYeStByJ0TVhQAJo+DeNgaSQ==",
- "license": "BSD-3-Clause",
+ "version": "4.4.7",
+ "resolved": "https://registry.npmjs.org/@expo/xcpretty/-/xcpretty-4.4.7.tgz",
+ "integrity": "sha512-EbxYllZ7/ozONVZd425cm4XnolfW+AmSFT5aP7Jdno6oc3WrYQcHz2CO20z/2rwWwYgztmV2PXvYH+BQ8YFjqg==",
+ "license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.20.0",
"chalk": "^4.1.0",
@@ -8933,15 +8933,15 @@
}
},
"node_modules/expo": {
- "version": "55.0.31",
- "resolved": "https://registry.npmjs.org/expo/-/expo-55.0.31.tgz",
- "integrity": "sha512-ZqV6jniU7twd18ADh1xP7moVrgP/BO1OTJwF2OzYnfJI9ak5cXDk+8DrV2jlgj33pMrLKqlnUvNz11zxyhwo7w==",
+ "version": "55.0.32",
+ "resolved": "https://registry.npmjs.org/expo/-/expo-55.0.32.tgz",
+ "integrity": "sha512-w0Y4tstI6+s67Icsrw8/EHnqLPJEtYAikQq2UlWLN0cSEWmQOD5KuxSwmJmNf+4m5aUuWKExwr4B9pw8vLnpHQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.20.0",
- "@expo/cli": "55.0.36",
+ "@expo/cli": "55.0.37",
"@expo/config": "~55.0.21",
- "@expo/config-plugins": "~55.0.11",
+ "@expo/config-plugins": "~55.0.12",
"@expo/devtools": "55.0.3",
"@expo/fingerprint": "0.16.8",
"@expo/local-build-cache-provider": "55.0.16",
@@ -8956,8 +8956,8 @@
"expo-file-system": "~55.0.26",
"expo-font": "~55.0.8",
"expo-keep-awake": "~55.0.8",
- "expo-modules-autolinking": "55.0.27",
- "expo-modules-core": "55.0.26",
+ "expo-modules-autolinking": "55.0.28",
+ "expo-modules-core": "55.0.27",
"pretty-format": "^29.7.0",
"react-refresh": "^0.14.2",
"whatwg-url-minimum": "^0.1.2"
@@ -9033,16 +9033,16 @@
}
},
"node_modules/expo-auth-session": {
- "version": "55.0.18",
- "resolved": "https://registry.npmjs.org/expo-auth-session/-/expo-auth-session-55.0.18.tgz",
- "integrity": "sha512-xyVno/b2DSfSEPcOSLBwMH0w8mc1YVQ3OULsjUxRVhUIa3lPt9l9JibX4LTQqXD3QYVD8o2nb7EqYPazzCwU9Q==",
+ "version": "55.0.19",
+ "resolved": "https://registry.npmjs.org/expo-auth-session/-/expo-auth-session-55.0.19.tgz",
+ "integrity": "sha512-NzZKI4zyfkwrfTQTj5QQeJgY65JuoPA8jrs4rsq2RpoSj1/l+I4DKmF7SqjPzd4yFGV+gqZkrWKwLg/BOWsJYg==",
"license": "MIT",
"dependencies": {
- "expo-application": "~55.0.18",
+ "expo-application": "~55.0.19",
"expo-constants": "~55.0.17",
- "expo-crypto": "~55.0.18",
+ "expo-crypto": "~55.0.19",
"expo-linking": "~55.0.17",
- "expo-web-browser": "~55.0.19",
+ "expo-web-browser": "~55.0.20",
"invariant": "^2.2.4"
},
"peerDependencies": {
@@ -9121,13 +9121,13 @@
}
},
"node_modules/expo-dev-client": {
- "version": "55.0.40",
- "resolved": "https://registry.npmjs.org/expo-dev-client/-/expo-dev-client-55.0.40.tgz",
- "integrity": "sha512-sPRuY2N274oocGN+6MlSVUoHoNxaVoHBlUSTBfD6bfd8hbC4UXiafNbTw4nv3h+88CPkpng0zUGxi2vH4agKnw==",
+ "version": "55.0.41",
+ "resolved": "https://registry.npmjs.org/expo-dev-client/-/expo-dev-client-55.0.41.tgz",
+ "integrity": "sha512-nEVrGdcsDMimSNGDTsNeQsV4KpL63JS8y75azINvwEULaGOZ6mutlFUxed3bsPvhCWc/oT7861XAEWsxpHFBbw==",
"license": "MIT",
"dependencies": {
- "expo-dev-launcher": "55.0.41",
- "expo-dev-menu": "55.0.34",
+ "expo-dev-launcher": "55.0.42",
+ "expo-dev-menu": "55.0.35",
"expo-dev-menu-interface": "55.0.2",
"expo-manifests": "~55.0.21",
"expo-updates-interface": "~55.1.6"
@@ -9137,13 +9137,13 @@
}
},
"node_modules/expo-dev-launcher": {
- "version": "55.0.41",
- "resolved": "https://registry.npmjs.org/expo-dev-launcher/-/expo-dev-launcher-55.0.41.tgz",
- "integrity": "sha512-X/rgO2BE9wzZ2SYQwyTwi1189pyg4YQMq0LkYIjfwuJNIAh+0Ruq0KiVkh4ckD88HQgYHf/DgJ8PjdEF1jeulA==",
+ "version": "55.0.42",
+ "resolved": "https://registry.npmjs.org/expo-dev-launcher/-/expo-dev-launcher-55.0.42.tgz",
+ "integrity": "sha512-kjJT/Hp7pCrJutxRPSvm2xKFORK2elfyJB3G1Bsz/mPKMGvA6WOkEaO703SWEKEfUvw9aUTVcwypMFzlzMYdOg==",
"license": "MIT",
"dependencies": {
"@expo/schema-utils": "^55.0.5",
- "expo-dev-menu": "55.0.34",
+ "expo-dev-menu": "55.0.35",
"expo-manifests": "~55.0.21"
},
"peerDependencies": {
@@ -9151,9 +9151,9 @@
}
},
"node_modules/expo-dev-menu": {
- "version": "55.0.34",
- "resolved": "https://registry.npmjs.org/expo-dev-menu/-/expo-dev-menu-55.0.34.tgz",
- "integrity": "sha512-FowMkhG32iw1qpKSWJI5wl/27DaaJbbMEtK6MQFMGcEgbk7UV42jWDd1AUuUUaf4Euxpgn36KWpG+blh/2gaHA==",
+ "version": "55.0.35",
+ "resolved": "https://registry.npmjs.org/expo-dev-menu/-/expo-dev-menu-55.0.35.tgz",
+ "integrity": "sha512-Dd456WfsAzPTfLrijdsBQ8WcawERsDQM+Pj7/th3mmOl0oZSczBtRU9zQfTByCjdq8rkPR0Tlf4Cz1Qz1zblrQ==",
"license": "MIT",
"dependencies": {
"expo-dev-menu-interface": "55.0.2"
@@ -9317,9 +9317,9 @@
}
},
"node_modules/expo-modules-autolinking": {
- "version": "55.0.27",
- "resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-55.0.27.tgz",
- "integrity": "sha512-gBRONXQT41PwfsQgeZfFlaeK+zrYMYjRMgxocecnQuSXEm7wCTqD8SsTJmWAf3SDayMQGDZFBlMODeVEnv8FmA==",
+ "version": "55.0.28",
+ "resolved": "https://registry.npmjs.org/expo-modules-autolinking/-/expo-modules-autolinking-55.0.28.tgz",
+ "integrity": "sha512-kPdjouLw5QHofEIlpCxAyAcXTDXAL5xiz9QRVF8VUJhBqlekQ/9BSA9/0FafeJVt86gT0TkX45zG88AHp+gi0Q==",
"license": "MIT",
"dependencies": {
"@expo/require-utils": "^55.0.8",
@@ -9332,9 +9332,9 @@
}
},
"node_modules/expo-modules-core": {
- "version": "55.0.26",
- "resolved": "https://registry.npmjs.org/expo-modules-core/-/expo-modules-core-55.0.26.tgz",
- "integrity": "sha512-nyQMIlNuAEif2kZEjaRiWxZsGyT8/pFm7VPwlYI92a0hyRxXrw3jG04I1OgfKy6oDFqMLn17D5C2zIGPP/fPLQ==",
+ "version": "55.0.27",
+ "resolved": "https://registry.npmjs.org/expo-modules-core/-/expo-modules-core-55.0.27.tgz",
+ "integrity": "sha512-YaYxKyL3nSMbsWqFCdDIaOBVwNCtTpJAiX5losi74M8ArEt6P9cetFPSwVfcoocAzjjkvSwGi8xw/gSxLglD0g==",
"license": "MIT",
"dependencies": {
"invariant": "^2.2.4"
@@ -9654,12 +9654,12 @@
}
},
"node_modules/expo-sharing": {
- "version": "55.0.24",
- "resolved": "https://registry.npmjs.org/expo-sharing/-/expo-sharing-55.0.24.tgz",
- "integrity": "sha512-2WXaevJUpNdKvktmboTMtbDPWicU44Vo8z5kyDuYIH7xU6jv411U/Pgk9ljhR3kf0XB34NZfa1QPNs+b25BOkA==",
+ "version": "55.0.25",
+ "resolved": "https://registry.npmjs.org/expo-sharing/-/expo-sharing-55.0.25.tgz",
+ "integrity": "sha512-DCbHXLbLChwwEc6vAyZkGVlzfJohXtcSR+Tf2qsczBtby0GS3cVqeBcH3UmJSG2ogJS18qLj2AYpn+iN/rpfNQ==",
"license": "MIT",
"dependencies": {
- "@expo/config-plugins": "^55.0.11",
+ "@expo/config-plugins": "^55.0.12",
"@expo/config-types": "^55.0.6",
"@expo/plist": "^0.5.4"
},
@@ -9822,14 +9822,14 @@
}
},
"node_modules/expo/node_modules/@expo/cli": {
- "version": "55.0.36",
- "resolved": "https://registry.npmjs.org/@expo/cli/-/cli-55.0.36.tgz",
- "integrity": "sha512-jVMEXmxeUKXAzJdRWQer7fyogjPMYiTbrGOrlioJlwMuFqKfao3FeFInmATMNGLhNN01aBs/s6pnJKqiAdlUQg==",
+ "version": "55.0.37",
+ "resolved": "https://registry.npmjs.org/@expo/cli/-/cli-55.0.37.tgz",
+ "integrity": "sha512-ennGX6iY1Ba/88cKWomD7xCIPEY0FDU14zAHyFpQTQV+9vg32i45sCRzOWUqkDXuZq4QzzznNqq87eFnlKfh/A==",
"license": "MIT",
"dependencies": {
"@expo/code-signing-certificates": "^0.0.6",
"@expo/config": "~55.0.21",
- "@expo/config-plugins": "~55.0.11",
+ "@expo/config-plugins": "~55.0.12",
"@expo/devcert": "^1.2.1",
"@expo/env": "~2.1.3",
"@expo/image-utils": "^0.8.17",
@@ -10114,9 +10114,9 @@
}
},
"node_modules/expo/node_modules/ws": {
- "version": "8.21.3",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
- "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
+ "version": "8.22.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@@ -14987,12 +14987,12 @@
}
},
"node_modules/plist": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",
- "integrity": "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==",
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
+ "integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==",
"license": "MIT",
"dependencies": {
- "@xmldom/xmldom": "^0.8.8",
+ "@xmldom/xmldom": "^0.9.10",
"base64-js": "^1.5.1",
"xmlbuilder": "^15.1.1"
},
@@ -15000,6 +15000,15 @@
"node": ">=10.4.0"
}
},
+ "node_modules/plist/node_modules/@xmldom/xmldom": {
+ "version": "0.9.12",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
+ "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.6"
+ }
+ },
"node_modules/pngjs": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-3.4.0.tgz",
@@ -18849,19 +18858,6 @@
"node": ">= 0.4.0"
}
},
- "node_modules/uuid": {
- "version": "11.1.1",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz",
- "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",
- "funding": [
- "https://github.com/sponsors/broofa",
- "https://github.com/sponsors/ctavan"
- ],
- "license": "MIT",
- "bin": {
- "uuid": "dist/esm/bin/uuid"
- }
- },
"node_modules/v8-to-istanbul": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
@@ -19380,16 +19376,15 @@
}
},
"node_modules/xcode": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz",
- "integrity": "sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==",
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/xcode/-/xcode-4.0.0.tgz",
+ "integrity": "sha512-dDaoWzc9EP2fp9FS9PVZUkyvFxY4y1TOV9pcKaKLk++Ei/qb97XDFEVP7GnW7Osii/TzVABJ0jq2F+9/lq0TVA==",
"license": "Apache-2.0",
"dependencies": {
- "simple-plist": "^1.1.0",
- "uuid": "^7.0.3"
+ "simple-plist": "^1.3.1"
},
"engines": {
- "node": ">=10.0.0"
+ "node": ">=14.17.0"
}
},
"node_modules/xml-name-validator": {
diff --git a/openwhispr-mobile/package.json b/openwhispr-mobile/package.json
index 27eb9400c..943b7c4b7 100644
--- a/openwhispr-mobile/package.json
+++ b/openwhispr-mobile/package.json
@@ -45,18 +45,18 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"drizzle-orm": "^0.45.2",
- "expo": "~55.0.31",
+ "expo": "~55.0.32",
"expo-apple-authentication": "~55.0.17",
"expo-application": "~55.0.19",
"expo-asset": "~55.0.20",
"expo-audio": "~55.0.18",
- "expo-auth-session": "~55.0.18",
+ "expo-auth-session": "~55.0.19",
"expo-blur": "~55.0.18",
"expo-build-properties": "~55.0.18",
"expo-clipboard": "~55.0.17",
"expo-constants": "~55.0.17",
"expo-crypto": "~55.0.19",
- "expo-dev-client": "~55.0.40",
+ "expo-dev-client": "~55.0.41",
"expo-document-picker": "~55.0.17",
"expo-file-system": "~55.0.26",
"expo-font": "~55.0.4",
@@ -69,7 +69,7 @@
"expo-notifications": "~55.0.27",
"expo-router": "~55.0.18",
"expo-secure-store": "~55.0.18",
- "expo-sharing": "~55.0.24",
+ "expo-sharing": "~55.0.25",
"expo-splash-screen": "~55.0.25",
"expo-sqlite": "~55.0.20",
"expo-status-bar": "~55.0.6",
diff --git a/openwhispr-mobile/src/components/AccountCreatorLink.tsx b/openwhispr-mobile/src/components/AccountCreatorLink.tsx
new file mode 100644
index 000000000..c851000ba
--- /dev/null
+++ b/openwhispr-mobile/src/components/AccountCreatorLink.tsx
@@ -0,0 +1,236 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { AccessibilityInfo, Keyboard, Linking, Pressable, View } from 'react-native';
+import { router, useFocusEffect } from 'expo-router';
+import { SettingsRow } from '@/components/ui/SettingsSection';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { Text } from '@/components/ui/Text';
+import { CreatorLinkInput } from '../../modules/creator-link-input/src';
+import { requestTrackingForCreatorCode } from '@/lib/affiliateAttribution';
+import { getAffiliateClientConfig } from '@/lib/affiliateLink';
+import { AppFont } from '@/lib/fonts';
+import { isUsageAnalyticsAllowed } from '@/lib/usageAnalytics';
+import { AFFILIATE_ERRORS, useAffiliateStore } from '@/store/useAffiliateStore';
+import { useAuthStore } from '@/store/useAuthStore';
+import { useConfigStore } from '@/store/useConfigStore';
+
+export type CreatorOfferResult = 'shown' | 'unavailable' | 'invalid' | 'cancelled';
+
+const UNAVAILABLE_TEXT =
+ 'Your creator is saved, but we couldn’t verify an available offer right now.';
+
+// A setting the user can change before trying again.
+const SETTINGS_ACTIONS: Partial<Record<string, { label: string; open: () => void }>> = {
+ [AFFILIATE_ERRORS.tracking]: {
+ label: 'Open Settings',
+ open: () => {
+ Linking.openSettings().catch(() => {});
+ },
+ },
+ [AFFILIATE_ERRORS.analytics]: {
+ label: 'Open Privacy & Data',
+ open: () => router.push('/(account)/privacy'),
+ },
+};
+// Retrying the same entry can't fix these; editing the field clears them.
+const EDIT_ERRORS: readonly string[] = [
+ AFFILIATE_ERRORS.input,
+ AFFILIATE_ERRORS.unavailable,
+ AFFILIATE_ERRORS.review,
+];
+
+export function AccountCreatorLink({
+ onCheckOffer,
+ onViewPlans,
+}: {
+ onCheckOffer: () => Promise<CreatorOfferResult>;
+ onViewPlans: () => void;
+}) {
+ const { link, saved, checking, error, edit } = useAffiliateStore();
+ const [open, setOpen] = useState(Boolean(link && !saved));
+ const [phase, setPhase] = useState<'idle' | 'checking' | 'unavailable'>('idle');
+ const [localError, setLocalError] = useState<string | null>(null);
+ const [focused, setFocused] = useState(true);
+ const { user, sessionCookie } = useAuthStore.getState();
+ const context = useRef({ active: true, generation: 0, pending: false });
+ const renderGeneration = context.current.generation;
+ const isActive = () =>
+ context.current.active &&
+ context.current.generation === renderGeneration &&
+ useAuthStore.getState().user?.id === user?.id &&
+ useAuthStore.getState().sessionCookie === sessionCookie;
+ useFocusEffect(
+ useCallback(() => {
+ context.current.active = true;
+ setFocused(true);
+ setPhase('idle');
+ return () => {
+ context.current.active = false;
+ setFocused(false);
+ setOpen(false);
+ context.current.generation += 1;
+ };
+ }, []),
+ );
+
+ const checkOffer = async (pastedText?: string) => {
+ if (!isActive() || context.current.pending || checking) return;
+ const generation = context.current.generation;
+ const isCurrent = () => isActive() && context.current.generation === generation;
+ context.current.pending = true;
+ setPhase('checking');
+ setLocalError(null);
+ try {
+ if (pastedText !== undefined) await edit(pastedText);
+ if (!isCurrent()) return;
+ if (!useAffiliateStore.getState().link.trim()) {
+ setPhase('idle');
+ return;
+ }
+ Keyboard.dismiss();
+ if (isUsageAnalyticsAllowed(useConfigStore.getState().config))
+ await requestTrackingForCreatorCode();
+ if (!isCurrent()) return;
+ const result = await onCheckOffer();
+ if (isCurrent()) setPhase(result === 'unavailable' ? 'unavailable' : 'idle');
+ } catch {
+ if (isCurrent()) {
+ setPhase('idle');
+ setLocalError('We couldn’t check your offer. Try again.');
+ }
+ } finally {
+ context.current.pending = false;
+ }
+ };
+
+ const busy = phase === 'checking' || checking;
+ const feedback = localError ?? error;
+ const settingsAction = feedback ? SETTINGS_ACTIONS[feedback] : undefined;
+ const canRetry = !(feedback && EDIT_ERRORS.includes(feedback));
+ // accessibilityLiveRegion is Android-only; VoiceOver needs an explicit announcement,
+ // and only for feedback that is on screen.
+ const announcement =
+ busy || !open || !focused
+ ? null
+ : (feedback ?? (phase === 'unavailable' ? UNAVAILABLE_TEXT : null));
+ useEffect(() => {
+ if (announcement) AccessibilityInfo.announceForAccessibility(announcement);
+ }, [announcement]);
+
+ if (!getAffiliateClientConfig()) return null;
+
+ return (
+ <View>
+ <SettingsRow
+ iconStyle="line"
+ icon="link"
+ mdIcon="Link"
+ title={saved ? 'Creator saved' : 'Have a creator code?'}
+ onPress={() => {
+ if (!busy) setOpen(!open);
+ }}
+ accessibilityState={{ expanded: open, busy }}
+ rightElement={
+ <SystemIcon
+ name={open ? 'chevron.down' : 'chevron.right'}
+ mdName={open ? 'ChevronDown' : 'ChevronRight'}
+ size={13}
+ color="tertiaryLabel"
+ />
+ }
+ />
+ {open && (
+ <View className="ml-14 mr-4 pb-4">
+ {!saved && (
+ <>
+ <Text className="mb-2 text-[13px] text-secondaryLabel">Creator code</Text>
+ <View className="rounded-xl border border-separator bg-secondarySystemGroupedBackground">
+ <CreatorLinkInput
+ value={link}
+ editable={!busy && focused}
+ fontFamily={AppFont.regular}
+ onChangeText={(value) => {
+ if (!isActive()) return;
+ setLocalError(null);
+ edit(value);
+ }}
+ onPaste={(value) => {
+ checkOffer(value);
+ }}
+ onSubmit={(value) => {
+ checkOffer(value);
+ }}
+ onInvalidPaste={() =>
+ setLocalError(
+ 'This entry is too long. Enter a creator code or the original link.',
+ )
+ }
+ />
+ </View>
+ </>
+ )}
+ <Text accessibilityLiveRegion="polite" className="mt-2 text-[13px] text-secondaryLabel">
+ {busy
+ ? 'Checking your offer…'
+ : phase === 'unavailable'
+ ? UNAVAILABLE_TEXT
+ : saved
+ ? 'Your creator is saved. You can check your offer whenever you’re ready.'
+ : 'Paste your code or creator link to check your offer. Typing instead? Tap Go.'}
+ </Text>
+ {feedback && (
+ <Text accessibilityLiveRegion="polite" className="mt-2 text-[13px] text-systemRed">
+ {feedback}
+ </Text>
+ )}
+ {!busy && (saved || feedback) && (
+ <View className="mt-1">
+ {settingsAction && (
+ <Pressable
+ accessibilityRole="button"
+ className="min-h-11 justify-center"
+ onPress={settingsAction.open}
+ >
+ <Text className="text-[15px] text-brand">{settingsAction.label}</Text>
+ </Pressable>
+ )}
+ {canRetry && (
+ <Pressable
+ accessibilityRole="button"
+ className="min-h-11 justify-center"
+ onPress={() => {
+ checkOffer();
+ }}
+ >
+ <Text className="text-[15px] text-brand">
+ {feedback || phase === 'unavailable' ? 'Try again' : 'Check offer'}
+ </Text>
+ </Pressable>
+ )}
+ {phase === 'unavailable' && (
+ <>
+ <Pressable
+ accessibilityRole="button"
+ className="min-h-11 justify-center"
+ onPress={onViewPlans}
+ >
+ <Text className="text-[15px] text-brand">View plans</Text>
+ </Pressable>
+ <Pressable
+ accessibilityRole="button"
+ className="min-h-11 justify-center"
+ onPress={() => {
+ setOpen(false);
+ setPhase('idle');
+ }}
+ >
+ <Text className="text-[15px] text-secondaryLabel">Not now</Text>
+ </Pressable>
+ </>
+ )}
+ </View>
+ )}
+ </View>
+ )}
+ </View>
+ );
+}
diff --git a/openwhispr-mobile/src/components/__tests__/AccountCreatorLink.test.tsx b/openwhispr-mobile/src/components/__tests__/AccountCreatorLink.test.tsx
new file mode 100644
index 000000000..a6b6b2e39
--- /dev/null
+++ b/openwhispr-mobile/src/components/__tests__/AccountCreatorLink.test.tsx
@@ -0,0 +1,261 @@
+import React from 'react';
+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+import { AccountCreatorLink } from '../AccountCreatorLink';
+import { AFFILIATE_ERRORS, useAffiliateStore } from '@/store/useAffiliateStore';
+import { getAffiliateClientConfig } from '@/lib/affiliateLink';
+import { requestTrackingForCreatorCode } from '@/lib/affiliateAttribution';
+import { useConfigStore } from '@/store/useConfigStore';
+import { Linking } from 'react-native';
+
+jest.mock('@react-native-async-storage/async-storage', () => ({
+ getItem: jest.fn(),
+ setItem: jest.fn().mockResolvedValue(undefined),
+}));
+jest.mock('@/lib/apiClient', () => ({ ApiError: class ApiError extends Error {} }));
+let mockFocusAccount: () => void;
+let mockBlurAccount: () => void;
+const mockAuth = { user: { id: 'user-a' }, sessionCookie: 'cookie-a' };
+const mockRouterPush = jest.fn();
+jest.mock('expo-router', () => ({
+ router: { push: (path: string) => mockRouterPush(path) },
+ useFocusEffect: (effect: () => () => void) =>
+ require('react').useEffect(() => {
+ mockFocusAccount = effect;
+ mockBlurAccount = effect();
+ return mockBlurAccount;
+ }, [effect]),
+}));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/lib/affiliateLink', () => ({ getAffiliateClientConfig: jest.fn(() => ({})) }));
+jest.mock('@/lib/affiliateAttribution', () => ({
+ checkAndClaimAffiliate: jest.fn(),
+ requestTrackingForCreatorCode: jest.fn(async () => {}),
+}));
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: { getState: () => mockAuth },
+}));
+jest.mock('@/store/useConfigStore', () => ({ useConfigStore: { getState: jest.fn() } }));
+jest.mock('../../../modules/creator-link-input/src', () => ({
+ CreatorLinkInput: (props: object) => {
+ const { View } = require('react-native');
+ return <View {...props} testID="creator-input" />;
+ },
+}));
+
+const link = 'https://sandbox.dub.link/creator';
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockAuth.user = { id: 'user-a' };
+ mockAuth.sessionCookie = 'cookie-a';
+ jest
+ .mocked(getAffiliateClientConfig)
+ .mockReturnValue({ domain: 'sandbox.dub.link', publishableKey: 'test' });
+ jest.mocked(useConfigStore.getState).mockReturnValue({
+ config: { usageAnalyticsEnabled: true },
+ } as ReturnType<typeof useConfigStore.getState>);
+ useAffiliateStore.setState({
+ link: '',
+ saved: false,
+ error: null,
+ checking: false,
+ hydrated: true,
+ ownerId: 'user-a',
+ clickId: null,
+ autoSubmit: false,
+ });
+});
+
+it('expands the menu and auto-checks the exact pasted link once without a billing tap', async () => {
+ let finish!: (result: 'shown') => void;
+ const check = jest.fn(
+ () =>
+ new Promise<'shown'>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const viewPlans = jest.fn();
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={viewPlans} />);
+ expect(screen.queryByTestId('creator-input')).toBeNull();
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ await waitFor(() => expect(check).toHaveBeenCalledTimes(1));
+ expect(useAffiliateStore.getState().link).toBe(link);
+ expect(screen.getByText('Checking your offer…')).toBeTruthy();
+ expect(viewPlans).not.toHaveBeenCalled();
+ await act(async () => {
+ useAffiliateStore.setState({ saved: true });
+ finish('shown');
+ });
+ expect(screen.getByText('Creator saved')).toBeTruthy();
+ expect(screen.getByText('Check offer')).toBeTruthy();
+ expect(screen.queryByText(/couldn’t verify/)).toBeNull();
+ expect(viewPlans).not.toHaveBeenCalled();
+});
+
+it('does not claim during typing and uses the complete native value on Go', async () => {
+ const check = jest.fn().mockResolvedValue('invalid');
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'changeText', link);
+ await act(async () => {});
+ expect(check).not.toHaveBeenCalled();
+ fireEvent(screen.getByTestId('creator-input'), 'submit', `${link}-full`);
+ await waitFor(() => expect(check).toHaveBeenCalledTimes(1));
+ expect(useAffiliateStore.getState().link).toBe(`${link}-full`);
+});
+
+it('keeps an unavailable offer inline and opens ordinary plans only by choice', async () => {
+ const check = jest.fn(async () => {
+ useAffiliateStore.setState({ saved: true });
+ return 'unavailable' as const;
+ });
+ const viewPlans = jest.fn();
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={viewPlans} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ await waitFor(() => expect(screen.getByText('View plans')).toBeTruthy());
+ expect(viewPlans).not.toHaveBeenCalled();
+ fireEvent.press(screen.getByText('Not now'));
+ expect(screen.queryByText('View plans')).toBeNull();
+ fireEvent.press(screen.getByText('Creator saved'));
+ fireEvent.press(screen.getByText('Check offer'));
+ await waitFor(() => expect(screen.getByText('View plans')).toBeTruthy());
+ fireEvent.press(screen.getByText('View plans'));
+ expect(viewPlans).toHaveBeenCalledTimes(1);
+});
+
+it.each([AFFILIATE_ERRORS.tracking, AFFILIATE_ERRORS.analytics, AFFILIATE_ERRORS.check])(
+ 'retains failed input with retry and clearing: %s',
+ async (error) => {
+ const check = jest.fn(async () => {
+ useAffiliateStore.setState({ error });
+ return 'invalid' as const;
+ });
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ await waitFor(() => expect(screen.getByText('Try again')).toBeTruthy());
+ expect(screen.queryByText('Clear link')).toBeNull();
+ expect(screen.getByText(error)).toBeTruthy();
+ expect(useAffiliateStore.getState().link).toBe(link);
+ fireEvent.press(screen.getByText('Try again'));
+ await waitFor(() => expect(check).toHaveBeenCalledTimes(2));
+ await act(async () => {
+ fireEvent(screen.getByTestId('creator-input'), 'changeText', '');
+ });
+ expect(useAffiliateStore.getState().link).toBe('');
+ },
+);
+
+it.each([AFFILIATE_ERRORS.input, AFFILIATE_ERRORS.unavailable, AFFILIATE_ERRORS.review])(
+ 'offers no retry of the same entry for: %s',
+ async (error) => {
+ const check = jest.fn(async () => {
+ useAffiliateStore.setState({ error });
+ return 'invalid' as const;
+ });
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ await waitFor(() => expect(screen.getByText(error)).toBeTruthy());
+ expect(screen.queryByText('Try again')).toBeNull();
+ await act(async () => {
+ fireEvent(screen.getByTestId('creator-input'), 'changeText', 'creator2');
+ });
+ expect(screen.queryByText(error)).toBeNull();
+ },
+);
+
+it('sends a tracking refusal to Settings and Usage Analytics off to Privacy & Data', async () => {
+ const openSettings = jest.spyOn(Linking, 'openSettings').mockResolvedValue();
+ const check = jest.fn(async () => {
+ useAffiliateStore.setState({ error: AFFILIATE_ERRORS.tracking });
+ return 'invalid' as const;
+ });
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ await waitFor(() => expect(screen.getByText('Open Settings')).toBeTruthy());
+ fireEvent.press(screen.getByText('Open Settings'));
+ expect(openSettings).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ useAffiliateStore.setState({ error: AFFILIATE_ERRORS.analytics });
+ });
+ fireEvent.press(screen.getByText('Open Privacy & Data'));
+ expect(mockRouterPush).toHaveBeenCalledWith('/(account)/privacy');
+});
+
+it('asks iOS for tracking before checking, but not with Usage Analytics off', async () => {
+ const check = jest.fn().mockResolvedValue('shown');
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ await waitFor(() => expect(check).toHaveBeenCalledTimes(1));
+ expect(requestTrackingForCreatorCode).toHaveBeenCalledTimes(1);
+ expect(jest.mocked(requestTrackingForCreatorCode).mock.invocationCallOrder[0]).toBeLessThan(
+ check.mock.invocationCallOrder[0],
+ );
+ jest.mocked(useConfigStore.getState).mockReturnValue({
+ config: { usageAnalyticsEnabled: false },
+ } as ReturnType<typeof useConfigStore.getState>);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'submit', link);
+ await waitFor(() => expect(check).toHaveBeenCalledTimes(2));
+ expect(requestTrackingForCreatorCode).toHaveBeenCalledTimes(1);
+});
+
+it('does not submit an empty paste or a paste that completes after leaving Account', async () => {
+ const check = jest.fn();
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ fireEvent(screen.getByTestId('creator-input'), 'paste', '');
+ await act(async () => {});
+ expect(check).not.toHaveBeenCalled();
+ fireEvent(screen.getByTestId('creator-input'), 'paste', link);
+ screen.unmount();
+ await act(async () => {});
+ expect(check).not.toHaveBeenCalled();
+});
+
+it('rejects late paste and typing callbacks after blur, even after returning', async () => {
+ const check = jest.fn();
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ const input = screen.getByTestId('creator-input');
+ const paste = input.props.onPaste;
+ const type = input.props.onChangeText;
+ act(() => {
+ mockBlurAccount();
+ });
+ expect(screen.queryByTestId('creator-input')).toBeNull();
+ await act(async () => {
+ paste(link);
+ type(link);
+ });
+ expect(useAffiliateStore.getState().link).toBe('');
+ act(() => {
+ mockFocusAccount();
+ });
+ await act(async () => {
+ paste(link);
+ });
+ expect(useAffiliateStore.getState().link).toBe('');
+ expect(check).not.toHaveBeenCalled();
+});
+
+it('rejects a callback from the previous account before a React rerender', async () => {
+ const check = jest.fn();
+ const screen = render(<AccountCreatorLink onCheckOffer={check} onViewPlans={jest.fn()} />);
+ fireEvent.press(screen.getByText('Have a creator code?'));
+ const paste = screen.getByTestId('creator-input').props.onPaste;
+ mockAuth.user = { id: 'user-b' };
+ mockAuth.sessionCookie = 'cookie-b';
+ await act(async () => {
+ paste(link);
+ });
+ expect(useAffiliateStore.getState().link).toBe('');
+ expect(check).not.toHaveBeenCalled();
+});
diff --git a/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx b/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx
index 7e9555158..658942d70 100644
--- a/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx
+++ b/openwhispr-mobile/src/components/superwall/SuperwallGateProvider.tsx
@@ -13,6 +13,7 @@ import { requiresRealAccount } from '@/lib/accountAccess';
import { useUsageStore } from '@/store/useUsageStore';
import {
isTransactionalSuperwallPlacement,
+ resolveSuperwallPlacementName,
SUPERWALL_PLACEMENTS,
type SuperwallPlacement,
} from '@/lib/superwall';
@@ -20,6 +21,7 @@ import { Sentry } from '@/lib/sentry';
import { reconcileStoreBilling } from '@/lib/billingReconciliation';
import { logPaywallViewed, logSubscription } from '@/lib/appsflyer';
import { identifyRevenueCatUser, recordRevenueCatPurchase } from '@/lib/revenuecat';
+import { createAffiliatePaywallSession } from '@/lib/affiliatePaywall';
type Props = {
children: React.ReactNode;
@@ -31,46 +33,55 @@ type PendingGate = {
feature?: () => void;
onAccessGrantedWithoutPurchase?: () => void;
onPurchaseComplete?: (completion: SuperwallPurchaseCompletion) => void;
+ onPresent?: () => void;
featureRan: boolean;
accessGrantedWithoutPurchaseReported: boolean;
purchaseCompletionReported: boolean;
terminalEventProcessed: boolean;
closed: boolean;
cancelled?: boolean;
+ awaitingDismissal?: boolean;
removeAbortListener?: () => void;
+ creatorSession?: ReturnType<typeof createAffiliatePaywallSession>;
resolve: (granted: boolean) => void;
};
type PlacementCallbacks = NonNullable<Parameters<typeof usePlacement>[0]>;
type NativeRegister = ReturnType<typeof usePlacement>['registerPlacement'];
-type OnboardingOffer = {
+type Presentation = {
id: number;
gate: PendingGate;
start: (register: NativeRegister) => void;
};
-function OnboardingOfferHandler({
+function PresentationHandler({
offer,
callbacks,
dismiss,
retire,
}: {
- offer: OnboardingOffer;
+ offer: Presentation;
callbacks: PlacementCallbacks;
dismiss: () => void;
retire: (gate: PendingGate) => void;
}): null {
const startedRef = useRef(false);
const { gate } = offer;
- // Each offer gets its own SDK handler identity, including after an explicit
- // onboarding reset. Keep cancelled listeners until native sends a terminal event.
+ // Each presentation has its own SDK handler identity. Keep cancelled listeners
+ // until native sends a terminal event; old callbacks must never reach a new gate.
const { registerPlacement } = usePlacement({
+ onCustomCallback(callback) {
+ return !gate.closed && !gate.cancelled && gate.creatorSession
+ ? gate.creatorSession.handle(callback)
+ : { status: 'failure' };
+ },
onPresent(info) {
if (gate.cancelled) dismiss();
else if (!gate.closed) callbacks.onPresent?.(info);
},
onDismiss(info, result) {
- if (!gate.closed) callbacks.onDismiss?.(info, result);
+ if (!gate.cancelled && (!gate.closed || gate.awaitingDismissal))
+ callbacks.onDismiss?.(info, result);
retire(gate);
},
onSkip(reason) {
@@ -78,7 +89,7 @@ function OnboardingOfferHandler({
retire(gate);
},
onError(error) {
- if (!gate.closed) callbacks.onError?.(error);
+ if (!gate.cancelled && (!gate.closed || gate.awaitingDismissal)) callbacks.onError?.(error);
retire(gate);
},
});
@@ -153,6 +164,7 @@ function completeGate(
if (granted && reportNoPurchaseAccess) reportAccessGrantedWithoutPurchase(gate);
if (gate.closed) return;
gate.closed = true;
+ gate.creatorSession?.close();
gate.removeAbortListener?.();
gate.resolve(granted);
if (runFeature && !gate.featureRan) {
@@ -335,10 +347,10 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
const pendingGateRef = useRef<PendingGate | null>(null);
const presentationGatesRef = useRef<PendingGate[]>([]);
const nextOfferId = useRef(0);
- const [onboardingOffers, setOnboardingOffers] = useState<OnboardingOffer[]>([]);
- const [onboardingState, setOnboardingState] = useState<PaywallState>({ status: 'idle' });
+ const [presentations, setPresentations] = useState<Presentation[]>([]);
+ const [presentationState, setPresentationState] = useState<PaywallState>({ status: 'idle' });
const retireOffer = useCallback((gate: PendingGate): void => {
- setOnboardingOffers((offers) => offers.filter((offer) => offer.gate !== gate));
+ setPresentations((offers) => offers.filter((offer) => offer.gate !== gate));
}, []);
const routeToAuth = useRouteToAuth(activePlacementRef);
@@ -371,11 +383,10 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
const placementCallbacks: PlacementCallbacks = {
onPresent(paywallInfo) {
const gate = pendingGateRef.current;
- if (gate?.placement === SUPERWALL_PLACEMENTS.onboardingPaywall) {
- setOnboardingState({ status: 'presented', paywallInfo });
- }
+ setPresentationState({ status: 'presented', paywallInfo });
if (gate && !presentationGatesRef.current.includes(gate)) {
presentationGatesRef.current.push(gate);
+ gate.onPresent?.();
}
const placement = activePlacementRef.current;
if (placement) logPaywallViewed(placement);
@@ -395,6 +406,8 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
});
},
onDismiss(_paywallInfo, result) {
+ presentationGatesRef.current[0]?.creatorSession?.close();
+ setPresentationState({ status: 'dismissed', result });
const placement = activePlacementRef.current;
debugLog('paywall dismissed', { placement, result: describePaywallResult(result) });
Sentry.addBreadcrumb({
@@ -446,6 +459,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
finishPresentationGate(failOpen, failOpen, failOpen);
},
onSkip(reason) {
+ setPresentationState({ status: 'skipped', reason });
debugLog('paywall SKIPPED', {
placement: activePlacementRef.current,
reason: describePaywallSkip(reason),
@@ -467,6 +481,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
finishActiveGate(granted, granted, granted);
},
onError(error) {
+ setPresentationState({ status: 'error', error });
debugLog('paywall ERROR', { placement: activePlacementRef.current, error });
const presentedGate = presentationGatesRef.current[0];
if (presentedGate) {
@@ -510,24 +525,58 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
});
}, [dismiss]);
- const { registerPlacement, state: billingState } = usePlacement(placementCallbacks);
- const state =
- activePlacementRef.current === SUPERWALL_PLACEMENTS.onboardingPaywall
- ? onboardingState
- : billingState;
+ // Superwall only sees the paywall close after an Apple offer redemption, so the
+ // session reports the confirmed purchase and it completes like any other.
+ const completeCreatorRedemption = useCallback(
+ (gate: PendingGate, productId: string): void => {
+ if (gate.closed) return;
+ gate.terminalEventProcessed = true;
+ presentationGatesRef.current = presentationGatesRef.current.filter((item) => item !== gate);
+ if (pendingGateRef.current === gate) {
+ pendingGateRef.current = null;
+ activePlacementRef.current = null;
+ }
+ completeGate(gate, true, true, false);
+ reportPurchaseCompletion(gate, 'purchased');
+ logSubscription(productId, gate.placement);
+ dismissCancelledOffer();
+ },
+ [dismissCancelledOffer],
+ );
+
+ const state = presentationState;
+ const sessionCookie = useAuthStore((state) => state.sessionCookie);
+ useEffect(() => {
+ // A new account/session invalidates pending creator work and its visible offer.
+ return () => {
+ const gate = pendingGateRef.current;
+ if (!gate) return;
+ gate.cancelled = true;
+ completeGate(gate, false, false, false);
+ pendingGateRef.current = null;
+ activePlacementRef.current = null;
+ presentationGatesRef.current = presentationGatesRef.current.filter((item) => item !== gate);
+ dismissCancelledOffer();
+ };
+ }, [user?.id, sessionCookie, dismissCancelledOffer]);
const register = useCallback(
async ({
placement,
params,
+ creatorOffer,
feature,
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
+ onPresent,
signal,
requiresAccount = isTransactionalSuperwallPlacement(placement),
}: RegisterSuperwallGateOptions): Promise<boolean> => {
const isOnboarding = placement === SUPERWALL_PLACEMENTS.onboardingPaywall;
- if (isOnboarding && signal?.aborted) return false;
+ // A blocked Account creator offer reports failure instead of granting access.
+ // Onboarding still moves on silently, with or without an offer.
+ const passesThroughWhenBlocked = !requiresAccount && (!creatorOffer || isOnboarding);
+ if (signal?.aborted) return false;
debugLog('register', {
placement,
requiresAccount,
@@ -545,7 +594,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
level: 'warning',
data: { placement, activePlacement: pendingGateRef.current.placement },
});
- if (!requiresAccount) {
+ if (passesThroughWhenBlocked) {
feature?.();
runAccessGrantedWithoutPurchaseCallback(onAccessGrantedWithoutPurchase, placement);
return true;
@@ -572,7 +621,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
level: 'warning',
data: { placement, configurationError },
});
- if (!requiresAccount) {
+ if (passesThroughWhenBlocked) {
feature?.();
runAccessGrantedWithoutPurchaseCallback(onAccessGrantedWithoutPurchase, placement);
activePlacementRef.current = null;
@@ -597,7 +646,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
level: 'info',
data: { placement },
});
- if (!requiresAccount) {
+ if (passesThroughWhenBlocked) {
feature?.();
runAccessGrantedWithoutPurchaseCallback(onAccessGrantedWithoutPurchase, placement);
activePlacementRef.current = null;
@@ -621,6 +670,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
feature,
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
+ onPresent,
featureRan: false,
accessGrantedWithoutPurchaseReported: false,
purchaseCompletionReported: false,
@@ -628,9 +678,14 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
closed: false,
resolve,
};
+ gate.creatorSession = createAffiliatePaywallSession(
+ () => !gate.closed && !gate.cancelled && presentationGatesRef.current.includes(gate),
+ (productId) => completeCreatorRedemption(gate, productId),
+ creatorOffer,
+ );
pendingGateRef.current = gate;
- if (isOnboarding && signal) {
+ if (signal) {
const cancel = (): void => {
gate.cancelled = true;
const wasPresented = presentationGatesRef.current.includes(gate);
@@ -659,17 +714,19 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
if (gate.cancelled) return;
const isPresented = presentationGatesRef.current.includes(gate);
if (isOnboarding && isPresented) return;
+ if (isPresented) gate.awaitingDismissal = true;
completeGate(gate, granted, runFeature, reportNoPurchaseAccess && !isPresented);
if (isPresented) return;
if (pendingGateRef.current === gate) pendingGateRef.current = null;
if (activePlacementRef.current === placement) activePlacementRef.current = null;
};
- debugLog('registering placement with Superwall', { placement, params });
+ const superwallPlacement = resolveSuperwallPlacementName(placement, Boolean(creatorOffer));
+ debugLog('registering placement with Superwall', { placement, superwallPlacement, params });
const start = (present: NativeRegister): void => {
present({
- placement,
- params,
+ placement: superwallPlacement,
+ params: { ...params, ...gate.creatorSession?.initialParams },
feature: () => {
if (gate.closed) return;
debugLog('feature gate granted', { placement });
@@ -680,7 +737,7 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
data: { placement },
});
finishGate(true, true, true);
- if (isOnboarding && !presentationGatesRef.current.includes(gate) && !gate.cancelled)
+ if (!presentationGatesRef.current.includes(gate) && !gate.cancelled)
retireOffer(gate);
},
})
@@ -697,32 +754,27 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
});
const billingFallback = canOpenExistingBilling(placement);
const failOpen = !gate.transactional;
- const finish =
- isOnboarding && presentationGatesRef.current.includes(gate)
- ? finishPresentationGate
- : finishGate;
+ const finish = presentationGatesRef.current.includes(gate)
+ ? finishPresentationGate
+ : finishGate;
finish(
failOpen || billingFallback,
failOpen || billingFallback,
failOpen || billingFallback,
);
if (gate.transactional && !billingFallback) showBillingUnavailable();
- if (isOnboarding) retireOffer(gate);
+ retireOffer(gate);
});
};
- if (isOnboarding) {
- setOnboardingState({ status: 'idle' });
- const offer = { id: nextOfferId.current++, gate, start };
- setOnboardingOffers((offers) => [...offers, offer]);
- } else {
- start(registerPlacement);
- }
+ setPresentationState({ status: 'idle' });
+ const offer = { id: nextOfferId.current++, gate, start };
+ setPresentations((offers) => [...offers, offer]);
});
},
[
+ completeCreatorRedemption,
configurationError,
isConfigured,
- registerPlacement,
dismissCancelledOffer,
finishPresentationGate,
retireOffer,
@@ -736,8 +788,8 @@ export function EnabledSuperwallGateProvider({ children }: Props) {
return (
<SuperwallGateContext.Provider value={value}>
{children}
- {onboardingOffers.map((offer) => (
- <OnboardingOfferHandler
+ {presentations.map((offer) => (
+ <PresentationHandler
key={offer.id}
offer={offer}
callbacks={placementCallbacks}
diff --git a/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx b/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx
index c24d6d4a6..964fbdbcb 100644
--- a/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx
+++ b/openwhispr-mobile/src/components/superwall/__tests__/SuperwallGateProvider.test.tsx
@@ -1,5 +1,24 @@
+const mockCreatorSessions: {
+ handle: jest.Mock;
+ close: jest.Mock;
+ onRedeemed: (productId: string) => void;
+}[] = [];
+jest.mock('@/lib/affiliatePaywall', () => ({
+ createAffiliatePaywallSession: (
+ _isPresented: () => boolean,
+ onRedeemed: (productId: string) => void,
+ ) => {
+ const session = {
+ handle: jest.fn(async () => ({ status: 'success' })),
+ close: jest.fn(),
+ onRedeemed,
+ };
+ mockCreatorSessions.push(session);
+ return session;
+ },
+}));
import React, { useState } from 'react';
-import { Pressable, Text } from 'react-native';
+import { Alert, Pressable, Text } from 'react-native';
import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
import {
DisabledSuperwallGateProvider,
@@ -21,7 +40,7 @@ let mockShouldPresent = true;
let mockIsConfigured = true;
let mockConfigurationError: string | null = null;
const mockRegisterPlacement = jest.fn(
- ({ feature }: { feature?: () => void }) =>
+ ({ feature }: { feature?: () => void; placement?: string }) =>
new Promise<void>((resolve) => {
mockNativeFeature = feature;
mockResolveNativePlacement = resolve;
@@ -30,6 +49,11 @@ const mockRegisterPlacement = jest.fn(
}
}),
);
+let mockCreatorCodesEnabled = false;
+jest.mock('@/lib/affiliateLink', () => ({
+ getAffiliateClientConfig: () =>
+ mockCreatorCodesEnabled ? { domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' } : null,
+}));
const mockReconcileStoreBilling = jest.fn();
const mockLogPaywallViewed = jest.fn();
const mockLogSubscription = jest.fn();
@@ -123,15 +147,21 @@ function GateConsumer({
feature,
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
+ onPresent,
label = 'register',
signal,
+ creatorOffer,
+ requiresAccount,
}: {
placement: SuperwallPlacement;
feature?: () => void;
onAccessGrantedWithoutPurchase?: () => void;
onPurchaseComplete?: (completion: SuperwallPurchaseCompletion) => void;
+ onPresent?: () => void;
label?: string;
signal?: AbortSignal;
+ creatorOffer?: RegisterSuperwallGateOptions['creatorOffer'];
+ requiresAccount?: boolean;
}): React.JSX.Element {
const { register } = useSuperwallGate();
const [result, setResult] = useState('pending');
@@ -145,7 +175,10 @@ function GateConsumer({
feature,
onAccessGrantedWithoutPurchase,
onPurchaseComplete,
+ onPresent,
signal,
+ creatorOffer,
+ requiresAccount,
};
register(options).then((granted) => setResult(String(granted)));
}}
@@ -175,12 +208,14 @@ const usage = {
describe('SuperwallGateProvider', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockCreatorSessions.length = 0;
mockPlacementCallbacks = {};
mockNativeFeature = undefined;
mockResolveNativePlacement = undefined;
mockShouldPresent = true;
mockIsConfigured = true;
mockConfigurationError = null;
+ mockCreatorCodesEnabled = false;
mockReconcileStoreBilling.mockResolvedValue(usage);
mockIdentifyRevenueCatUser.mockResolvedValue(true);
mockRecordRevenueCatPurchase.mockResolvedValue(true);
@@ -553,6 +588,101 @@ describe('SuperwallGateProvider', () => {
expect(mockLogSubscription).toHaveBeenCalledTimes(1);
});
+ it('completes a confirmed creator redemption as one purchase, then closes the paywall', async () => {
+ const onPurchaseComplete = jest.fn();
+ const onPresent = jest.fn();
+ const creatorOffer = { productId: 'monthly' } as NonNullable<
+ RegisterSuperwallGateOptions['creatorOffer']
+ >;
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.accountBillingOpen}
+ requiresAccount={false}
+ creatorOffer={creatorOffer}
+ onPurchaseComplete={onPurchaseComplete}
+ onPresent={onPresent}
+ />
+ </EnabledSuperwallGateProvider>,
+ );
+
+ fireEvent.press(screen.getByText('register'));
+ expect(onPresent).toHaveBeenCalledTimes(1);
+ await act(async () => mockCreatorSessions[0].onRedeemed('monthly'));
+ expect(screen.getByTestId('result').props.children).toBe('true');
+ expect(onPurchaseComplete).toHaveBeenCalledWith('purchased');
+ expect(mockLogSubscription).toHaveBeenCalledWith(
+ 'monthly',
+ SUPERWALL_PLACEMENTS.accountBillingOpen,
+ );
+ expect(mockDismiss).toHaveBeenCalledTimes(1);
+
+ // Superwall then reports the programmatic close as an ordinary dismissal.
+ act(() => mockPlacementCallbacks.onDismiss?.({}, { type: 'declined' }));
+ await act(async () => mockCreatorSessions[0].onRedeemed('monthly'));
+ expect(onPurchaseComplete).toHaveBeenCalledTimes(1);
+ expect(mockLogSubscription).toHaveBeenCalledTimes(1);
+ fireEvent.press(screen.getByText('register'));
+ expect(mockRegisterPlacement).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not report a presentation for a paywall that is skipped', async () => {
+ mockShouldPresent = false;
+ const onPresent = jest.fn();
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer placement={SUPERWALL_PLACEMENTS.accountBillingOpen} onPresent={onPresent} />
+ </EnabledSuperwallGateProvider>,
+ );
+ fireEvent.press(screen.getByText('register'));
+ act(() => mockPlacementCallbacks.onSkip?.({ type: 'Holdout', experiment: { id: 'x' } }));
+ expect(onPresent).not.toHaveBeenCalled();
+ });
+
+ it('opens onboarding and creator offers on the creator-code placement when creator codes are on', async () => {
+ mockCreatorCodesEnabled = true;
+ mockShouldPresent = false;
+ const creatorOffer = { productId: 'monthly' } as NonNullable<
+ RegisterSuperwallGateOptions['creatorOffer']
+ >;
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer placement={SUPERWALL_PLACEMENTS.onboardingPaywall} label="onboarding" />
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.accountBillingOpen}
+ requiresAccount={false}
+ creatorOffer={creatorOffer}
+ label="creator offer"
+ />
+ <GateConsumer placement={SUPERWALL_PLACEMENTS.accountBillingOpen} label="plans" />
+ </EnabledSuperwallGateProvider>,
+ );
+
+ for (const label of ['onboarding', 'creator offer', 'plans']) {
+ fireEvent.press(screen.getByText(label));
+ await act(async () => mockResolveNativePlacement?.());
+ }
+ expect(mockRegisterPlacement.mock.calls.map(([options]) => options.placement)).toEqual([
+ 'creator_code_paywall',
+ 'creator_code_paywall',
+ SUPERWALL_PLACEMENTS.accountBillingOpen,
+ ]);
+ });
+
+ it('keeps the usual placements in a build without creator codes', async () => {
+ mockShouldPresent = false;
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer placement={SUPERWALL_PLACEMENTS.onboardingPaywall} />
+ </EnabledSuperwallGateProvider>,
+ );
+ fireEvent.press(screen.getByText('register'));
+ await act(async () => mockResolveNativePlacement?.());
+ expect(mockRegisterPlacement.mock.calls[0][0].placement).toBe(
+ SUPERWALL_PLACEMENTS.onboardingPaywall,
+ );
+ });
+
it('reports a confirmed restoration', async () => {
const onPurchaseComplete = jest.fn();
const screen = render(
@@ -1061,4 +1191,97 @@ describe('SuperwallGateProvider', () => {
await waitFor(() => expect(screen.getByTestId('result').props.children).toBe('true'));
expect(onAccessGrantedWithoutPurchase).toHaveBeenCalledTimes(1);
});
+ it.each([SUPERWALL_PLACEMENTS.onboardingPaywall, SUPERWALL_PLACEMENTS.accountBillingOpen])(
+ 'isolates creator callbacks after closing and reopening %s',
+ async (placement) => {
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer placement={placement} />
+ </EnabledSuperwallGateProvider>,
+ );
+ fireEvent.press(screen.getByText('register'));
+ const oldCallbacks = mockPlacementCallbacks;
+ const first = mockCreatorSessions[0];
+ await act(async () => {
+ await oldCallbacks.onCustomCallback({ name: 'creatorCodeApply' });
+ });
+ expect(first.handle).toHaveBeenCalledTimes(1);
+ act(() => oldCallbacks.onDismiss({}, { type: 'declined' }));
+ fireEvent.press(screen.getByText('register'));
+ expect(mockCreatorSessions).toHaveLength(2);
+ await act(async () => {
+ await oldCallbacks.onCustomCallback({ name: 'creatorOfferRedeem' });
+ });
+ expect(first.handle).toHaveBeenCalledTimes(1);
+ expect(first.close).toHaveBeenCalled();
+ expect(mockCreatorSessions[1].handle).not.toHaveBeenCalled();
+ await act(async () => {
+ await mockPlacementCallbacks.onCustomCallback({ name: 'creatorCodeApply' });
+ });
+ expect(mockCreatorSessions[1].handle).toHaveBeenCalledTimes(1);
+ },
+ );
+ it('releases an ordinary presented gate when native registration rejects', async () => {
+ mockRegisterPlacement.mockImplementationOnce(() => {
+ mockPlacementCallbacks.onPresent({ identifier: 'fixture', name: 'Fixture' });
+ return Promise.reject(new Error('native failure'));
+ });
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer placement={SUPERWALL_PLACEMENTS.accountBillingOpen} />
+ </EnabledSuperwallGateProvider>,
+ );
+ await act(async () => fireEvent.press(screen.getByText('register')));
+ expect(screen.getByTestId('result').props.children).toBe('false');
+ fireEvent.press(screen.getByText('register'));
+ expect(mockRegisterPlacement).toHaveBeenCalledTimes(2);
+ });
+ it.each(['loading', 'error'])(
+ 'does not grant seeded anonymous offer access when SDK is %s',
+ async (state) => {
+ mockIsConfigured = false;
+ mockConfigurationError = state === 'error' ? 'failed' : null;
+ const granted = jest.fn();
+ const creatorOffer = { productId: 'monthly' } as NonNullable<
+ RegisterSuperwallGateOptions['creatorOffer']
+ >;
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.accountBillingOpen}
+ requiresAccount={false}
+ creatorOffer={creatorOffer}
+ onAccessGrantedWithoutPurchase={granted}
+ />
+ </EnabledSuperwallGateProvider>,
+ );
+ await act(async () => fireEvent.press(screen.getByText('register')));
+ expect(screen.getByTestId('result').props.children).toBe('false');
+ expect(granted).not.toHaveBeenCalled();
+ expect(mockRegisterPlacement).not.toHaveBeenCalled();
+ },
+ );
+ it.each(['loading', 'error'])(
+ 'moves onboarding on without a billing alert when its creator offer meets an SDK %s',
+ async (state) => {
+ mockIsConfigured = false;
+ mockConfigurationError = state === 'error' ? 'failed' : null;
+ const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => {});
+ const creatorOffer = { productId: 'monthly' } as NonNullable<
+ RegisterSuperwallGateOptions['creatorOffer']
+ >;
+ const screen = render(
+ <EnabledSuperwallGateProvider>
+ <GateConsumer
+ placement={SUPERWALL_PLACEMENTS.onboardingPaywall}
+ creatorOffer={creatorOffer}
+ />
+ </EnabledSuperwallGateProvider>,
+ );
+ await act(async () => fireEvent.press(screen.getByText('register')));
+ expect(screen.getByTestId('result').props.children).toBe('true');
+ expect(alert).not.toHaveBeenCalled();
+ alert.mockRestore();
+ },
+ );
});
diff --git a/openwhispr-mobile/src/components/ui/SettingsSection.tsx b/openwhispr-mobile/src/components/ui/SettingsSection.tsx
index 5ead69f58..27f724e09 100644
--- a/openwhispr-mobile/src/components/ui/SettingsSection.tsx
+++ b/openwhispr-mobile/src/components/ui/SettingsSection.tsx
@@ -1,5 +1,12 @@
import React from 'react';
-import { View, Pressable, StyleSheet, TextInput, type TextInputProps } from 'react-native';
+import {
+ View,
+ Pressable,
+ StyleSheet,
+ TextInput,
+ type TextInputProps,
+ type AccessibilityState,
+} from 'react-native';
import { Text } from '@/components/ui/Text';
import { SystemIcon, type LucideIconName } from './SystemIcon';
import { BRAND, iosColor } from '@/config/colors';
@@ -18,6 +25,7 @@ type SettingsRowProps = {
destructive?: boolean;
showChevron?: boolean;
selected?: boolean;
+ accessibilityState?: AccessibilityState;
// Shown right after the description, such as a help button.
descriptionAccessory?: React.ReactNode;
// Dims the icon and title and ignores taps; the description stays legible to say why.
@@ -37,6 +45,7 @@ export function SettingsRow({
destructive = false,
showChevron = true,
selected = false,
+ accessibilityState,
descriptionAccessory,
disabled = false,
}: SettingsRowProps) {
@@ -45,8 +54,13 @@ export function SettingsRow({
return (
<Pressable
onPress={disabled ? undefined : onPress}
+ accessibilityRole={onPress ? 'button' : undefined}
disabled={disabled || (!onPress && !rightElement)}
- accessibilityState={{ selected, disabled }}
+ accessibilityState={{
+ selected,
+ ...accessibilityState,
+ disabled: disabled || accessibilityState?.disabled,
+ }}
className={selected ? 'bg-brand/10 active:bg-brand/20' : 'active:bg-tertiarySystemFill'}
>
<View
diff --git a/openwhispr-mobile/src/data/remote/billingApi.ts b/openwhispr-mobile/src/data/remote/billingApi.ts
index 08da8c531..4a068a2c1 100644
--- a/openwhispr-mobile/src/data/remote/billingApi.ts
+++ b/openwhispr-mobile/src/data/remote/billingApi.ts
@@ -26,6 +26,13 @@ export async function createStripeBillingPortalSession(): Promise<string> {
return response.url;
}
-export async function reconcileMobileBilling(platform: 'ios' | 'android'): Promise<UsageInfo> {
- return api.post<UsageInfo>('/api/billing/reconcile', { platform });
+export async function reconcileMobileBilling(
+ platform: 'ios' | 'android',
+ sessionCookie?: string,
+): Promise<UsageInfo> {
+ return api.post<UsageInfo>(
+ '/api/billing/reconcile',
+ { platform },
+ sessionCookie ? { authenticated: false, headers: { Cookie: sessionCookie } } : undefined,
+ );
}
diff --git a/openwhispr-mobile/src/hooks/useAffiliateAttribution.ts b/openwhispr-mobile/src/hooks/useAffiliateAttribution.ts
new file mode 100644
index 000000000..80fd16146
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/useAffiliateAttribution.ts
@@ -0,0 +1,75 @@
+import { useEffect } from 'react';
+import { AppState, Linking } from 'react-native';
+import {
+ captureAffiliateArrival,
+ consumeAffiliateArrival,
+ getAffiliateClientConfig,
+} from '@/lib/affiliateLink';
+import { useAffiliateStore } from '@/store/useAffiliateStore';
+import { useAuthStore } from '@/store/useAuthStore';
+import { useConfigStore } from '@/store/useConfigStore';
+
+export function useAffiliateAttribution(): void {
+ useEffect(() => {
+ if (!getAffiliateClientConfig()) return;
+ let stopped = false;
+ let running = false;
+ let pending = false;
+ async function reconcile() {
+ pending = true;
+ if (running) return;
+ running = true;
+ try {
+ while (pending && !stopped) {
+ pending = false;
+ await useAffiliateStore.getState().hydrate();
+ if (
+ stopped ||
+ !useAuthStore.getState().isInitialized ||
+ !useConfigStore.getState().config
+ )
+ break;
+ await useAffiliateStore.getState().bindSession();
+ // One tap can arrive through several routes; re-editing the same link
+ // would drop its resolved click and record another one.
+ const link = consumeAffiliateArrival();
+ if (link && link !== useAffiliateStore.getState().link)
+ await useAffiliateStore.getState().edit(link, true);
+ if (useAffiliateStore.getState().autoSubmit) await useAffiliateStore.getState().prepare();
+ }
+ } finally {
+ running = false;
+ }
+ }
+ const onLink = (url: string) => {
+ if (captureAffiliateArrival(url)) reconcile().catch(() => {});
+ };
+ const linkSub = Linking.addEventListener('url', ({ url }) => onLink(url));
+ const appSub = AppState.addEventListener('change', (state) => {
+ if (state === 'active') reconcile().catch(() => {});
+ });
+ const authSub = useAuthStore.subscribe(() => {
+ useAffiliateStore
+ .getState()
+ .bindSession()
+ .then(reconcile)
+ .catch(() => {});
+ });
+ const configSub = useConfigStore.subscribe(() => {
+ reconcile().catch(() => {});
+ });
+ Linking.getInitialURL()
+ .then((url) => {
+ if (!stopped && url) onLink(url);
+ })
+ .catch(() => {});
+ reconcile().catch(() => {});
+ return () => {
+ stopped = true;
+ linkSub.remove();
+ appSub.remove();
+ authSub();
+ configSub();
+ };
+ }, []);
+}
diff --git a/openwhispr-mobile/src/hooks/useSuperwallGate.ts b/openwhispr-mobile/src/hooks/useSuperwallGate.ts
index 1e36661fa..6cbfd402d 100644
--- a/openwhispr-mobile/src/hooks/useSuperwallGate.ts
+++ b/openwhispr-mobile/src/hooks/useSuperwallGate.ts
@@ -1,4 +1,5 @@
import { createContext, useContext } from 'react';
+import type { AffiliateOffer } from '@/lib/affiliateOffer';
import type { PaywallState } from 'expo-superwall';
import {
isTransactionalSuperwallPlacement,
@@ -10,12 +11,16 @@ export type SuperwallPurchaseCompletion = 'purchased' | 'restored';
export type RegisterSuperwallGateOptions = {
placement: SuperwallPlacement;
+ /** Verified app-owned offer from an explicit creator submission; never sent to Superwall. */
+ creatorOffer?: AffiliateOffer;
params?: Partial<SuperwallAttributes> & Record<string, unknown>;
feature?: () => void;
onAccessGrantedWithoutPurchase?: () => void;
onPurchaseComplete?: (completion: SuperwallPurchaseCompletion) => void;
+ /** Called once the native paywall is on screen. */
+ onPresent?: () => void;
requiresAccount?: boolean;
- /** Cancels the optional onboarding offer when its screen is left. */
+ /** Cancels the registration when its screen is left. */
signal?: AbortSignal;
};
diff --git a/openwhispr-mobile/src/lib/__tests__/affiliateAttribution.test.ts b/openwhispr-mobile/src/lib/__tests__/affiliateAttribution.test.ts
new file mode 100644
index 000000000..bc69c8823
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/affiliateAttribution.test.ts
@@ -0,0 +1,168 @@
+import { api } from '../apiClient';
+import {
+ AffiliateConsentError,
+ checkAndClaimAffiliate,
+ requestTrackingForCreatorCode,
+} from '../affiliateAttribution';
+import { setAppsFlyerTrackingAuthorizationStatus } from '../appsflyer';
+import {
+ getTrackingAuthorizationStatus,
+ requestTrackingAuthorization,
+} from '../trackingTransparency';
+jest.mock('../trackingTransparency', () => ({
+ getTrackingAuthorizationStatus: jest.fn(),
+ requestTrackingAuthorization: jest.fn(),
+}));
+jest.mock('../appsflyer', () => ({ setAppsFlyerTrackingAuthorizationStatus: jest.fn() }));
+jest.mock('../apiClient', () => ({ api: { post: jest.fn() } }));
+jest.mock('../affiliateLink', () => ({
+ getAffiliateClientConfig: () => ({ domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' }),
+ parseAffiliateInput: jest.requireActual('../affiliateLink').parseAffiliateInput,
+}));
+const link = 'https://sandbox.dub.link/creator';
+const dubOpen = (body: unknown, ok = true) =>
+ ({ ok, json: async () => body }) as unknown as Response;
+const fetchMock = jest.fn<Promise<Response>, Parameters<typeof fetch>>();
+const trackedLinks = () =>
+ fetchMock.mock.calls.map(([, init]) => JSON.parse(String(init?.body)).deepLink);
+beforeAll(() => {
+ global.fetch = fetchMock as unknown as typeof fetch;
+});
+beforeEach(() => {
+ jest.clearAllMocks();
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('authorized');
+ jest.mocked(api.post).mockResolvedValue({ data: { persisted: true, status: 'provisional' } });
+ fetchMock.mockResolvedValue(
+ dubOpen({ clickId: 'click', link: { domain: 'sandbox.dub.link', key: 'creator' } }),
+ );
+});
+it.each(['denied', 'notDetermined'] as const)(
+ 'does not resolve or claim a link when tracking is %s',
+ async (status) => {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue(status);
+ await expect(
+ checkAndClaimAffiliate(link, null, 'session-a', () => true, jest.fn()),
+ ).rejects.toBeInstanceOf(AffiliateConsentError);
+ expect(api.post).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+);
+it('checks with the server, resolves only the explicit URL and uses the captured session for claim', async () => {
+ const remember = jest.fn().mockResolvedValue(undefined);
+ expect(await checkAndClaimAffiliate(link, null, 'session-a', () => true, remember)).toBe(
+ 'provisional',
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.dub.co/track/open',
+ expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({ Authorization: 'Bearer dub_pk_test' }),
+ body: JSON.stringify({ dubDomain: 'sandbox.dub.link', deepLink: link }),
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ expect(remember).toHaveBeenCalledWith('click');
+ expect(api.post).toHaveBeenNthCalledWith(
+ 2,
+ '/api/affiliate/claim',
+ { link, clickId: 'click', source: 'mobile' },
+ expect.objectContaining({ authenticated: false, headers: { Cookie: 'session-a' } }),
+ );
+});
+it('invalid/expired server checks never create a click or claim', async () => {
+ jest.mocked(api.post).mockRejectedValueOnce(new Error('expired'));
+ await expect(
+ checkAndClaimAffiliate(link, null, 'session-a', () => true, jest.fn()),
+ ).rejects.toThrow('expired');
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(api.post).toHaveBeenCalledTimes(1);
+});
+it('account switch during resolution never sends a claim with the new session', async () => {
+ let current = true;
+ fetchMock.mockImplementation(async () => {
+ current = false;
+ return dubOpen({ clickId: 'click', link: { domain: 'sandbox.dub.link', key: 'creator' } });
+ });
+ await expect(
+ checkAndClaimAffiliate(link, null, 'session-a', () => current, jest.fn()),
+ ).rejects.toThrow('interrupted');
+ expect(api.post).toHaveBeenCalledTimes(1);
+});
+it('a hung Dub request cannot leave the CTA checking forever', async () => {
+ jest.useFakeTimers();
+ fetchMock.mockImplementation(() => new Promise(() => {}));
+ const pending = checkAndClaimAffiliate(link, null, 'session-a', () => true, jest.fn());
+ const result = pending.catch((error: Error) => error);
+ await jest.advanceTimersByTimeAsync(10001);
+ expect(await result).toEqual(new Error('Referral check interrupted. Try again.'));
+ expect(api.post).toHaveBeenCalledTimes(1);
+ jest.useRealTimers();
+});
+
+it('a hung native permission read releases the CTA without starting attribution', async () => {
+ jest.useFakeTimers();
+ jest.mocked(getTrackingAuthorizationStatus).mockImplementation(() => new Promise(() => {}));
+ const result = checkAndClaimAffiliate(link, null, 'session-a', () => true, jest.fn()).catch(
+ (error: Error) => error,
+ );
+ await jest.advanceTimersByTimeAsync(10001);
+ expect(await result).toEqual(new Error('Referral check interrupted. Try again.'));
+ expect(api.post).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ jest.useRealTimers();
+});
+
+it('stops before Dub if tracking is revoked while validating the link', async () => {
+ jest.mocked(api.post).mockImplementationOnce(async () => {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('denied');
+ return { data: { valid: true } };
+ });
+ await expect(
+ checkAndClaimAffiliate(link, null, 'session-a', () => true, jest.fn()),
+ ).rejects.toBeInstanceOf(AffiliateConsentError);
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(api.post).toHaveBeenCalledTimes(1);
+});
+
+it('an explicit short-code submission uses the exact trusted full link', async () => {
+ await checkAndClaimAffiliate('creator', null, 'session-a', () => true, jest.fn());
+ expect(trackedLinks()).toEqual([link]);
+ expect(api.post).toHaveBeenNthCalledWith(
+ 1,
+ '/api/affiliate/check-link',
+ { link },
+ expect.any(Object),
+ );
+});
+it('ambiguous short-code case never reaches tracking or claim', async () => {
+ await expect(
+ checkAndClaimAffiliate('Creator', null, 'session-a', () => true, jest.fn()),
+ ).rejects.toThrow();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(api.post).not.toHaveBeenCalled();
+});
+
+it('asks iOS for tracking on an explicit creator submission only while undecided', async () => {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValueOnce('notDetermined');
+ jest.mocked(requestTrackingAuthorization).mockResolvedValueOnce('authorized');
+ await requestTrackingForCreatorCode();
+ expect(setAppsFlyerTrackingAuthorizationStatus).toHaveBeenCalledWith('authorized');
+ for (const status of ['denied', 'authorized', 'notSupported'] as const) {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValueOnce(status);
+ await requestTrackingForCreatorCode();
+ }
+ expect(requestTrackingAuthorization).toHaveBeenCalledTimes(1);
+});
+
+it('reports a claim the server accepted even if the caller stopped waiting', async () => {
+ let current = true;
+ jest.mocked(api.post).mockImplementation(async (path: string) => {
+ if (path !== '/api/affiliate/claim') return { data: {} };
+ await Promise.resolve();
+ current = false;
+ return { data: { persisted: true, status: 'registered' } };
+ });
+ await expect(
+ checkAndClaimAffiliate(link, null, 'session-a', () => current, jest.fn()),
+ ).resolves.toBe('registered');
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/affiliateIntent.test.ts b/openwhispr-mobile/src/lib/__tests__/affiliateIntent.test.ts
new file mode 100644
index 000000000..bd1a36c74
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/affiliateIntent.test.ts
@@ -0,0 +1,41 @@
+import Constants from 'expo-constants';
+import { redirectSystemPath } from '../../../app/+native-intent';
+import { consumeAffiliateArrival } from '../affiliateLink';
+jest.mock('expo-constants', () => ({
+ expoConfig: {
+ extra: { affiliate: { domain: 'try.openwhispr.com', publishableKey: 'dub_pk_TEST' } },
+ },
+}));
+
+it('captures a trusted creator on cold and warm starts', () => {
+ for (const initial of [true, false]) {
+ expect(redirectSystemPath({ path: 'https://try.openwhispr.com/creator', initial })).toBe('/');
+ expect(consumeAffiliateArrival()).toBe('https://try.openwhispr.com/creator');
+ }
+});
+it('captures a short link a share sheet ended with a slash', () => {
+ expect(
+ redirectSystemPath({ path: 'https://try.openwhispr.com/creator/?via=x', initial: true }),
+ ).toBe('/');
+ expect(consumeAffiliateArrival()).toBe('https://try.openwhispr.com/creator?via=x');
+});
+it.each([
+ 'https://try.openwhispr.com/',
+ 'https://try.openwhispr.com/a/b',
+ 'https://try.openwhispr.com/%E2%9C%93',
+])('opens Home for an unusable creator-domain link %s without capturing it', (path) => {
+ expect(redirectSystemPath({ path, initial: false })).toBe('/');
+ expect(consumeAffiliateArrival()).toBeNull();
+});
+it.each([
+ 'openwhispr://keyboard?text=test',
+ 'openwhispr://oauth/callback',
+ 'https://elsewhere.test/creator',
+])('preserves the existing route %s', (path) => {
+ expect(redirectSystemPath({ path, initial: true })).toBe(path);
+});
+it('leaves routes alone in an unconfigured build', () => {
+ Constants.expoConfig!.extra = {};
+ const path = 'https://try.openwhispr.com/creator';
+ expect(redirectSystemPath({ path, initial: true })).toBe(path);
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/affiliateLink.test.ts b/openwhispr-mobile/src/lib/__tests__/affiliateLink.test.ts
new file mode 100644
index 000000000..7072ecca3
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/affiliateLink.test.ts
@@ -0,0 +1,66 @@
+import { Platform } from 'react-native';
+import Constants from 'expo-constants';
+import {
+ captureAffiliateArrival,
+ consumeAffiliateArrival,
+ parseAffiliateLink,
+} from '../affiliateLink';
+jest.mock('expo-constants', () => ({ expoConfig: { extra: {} } }));
+const original = Constants.expoConfig;
+beforeEach(() => {
+ Constants.expoConfig = {
+ ...original,
+ extra: { affiliate: { domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' } },
+ } as typeof original;
+ consumeAffiliateArrival();
+});
+afterEach(() => {
+ Constants.expoConfig = original;
+});
+it.each([
+ 'http://sandbox.dub.link/creator',
+ 'https://sandbox.dub.link.evil.test/creator',
+ 'https://[email protected]/creator',
+ 'https://sandbox.dub.link/',
+ 'https://sandbox.dub.link/creator/nested',
+ 'https://sandbox.dub.link/a%2Fb',
+])('rejects an untrusted URL (%s)', (input) => {
+ expect(() => parseAffiliateLink(input, 'sandbox.dub.link')).toThrow();
+});
+it('preserves explicit cold/warm arrivals without following their destination', () => {
+ expect(captureAffiliateArrival('https://sandbox.dub.link/creator?x=1')).toBe(true);
+ expect(consumeAffiliateArrival()).toBe('https://sandbox.dub.link/creator?x=1');
+ expect(consumeAffiliateArrival()).toBeNull();
+});
+it('disabled builds leave native routes untouched', () => {
+ Constants.expoConfig = { ...original, extra: {} } as typeof original;
+ expect(captureAffiliateArrival('https://sandbox.dub.link/creator')).toBe(false);
+});
+
+it('keeps affiliate UI and capture disabled on Android even with shared config', () => {
+ const previous = Platform.OS;
+ Object.defineProperty(Platform, 'OS', { value: 'android', configurable: true });
+ try {
+ expect(captureAffiliateArrival('https://sandbox.dub.link/creator')).toBe(false);
+ } finally {
+ Object.defineProperty(Platform, 'OS', { value: previous, configurable: true });
+ }
+});
+
+it('maps only bounded lowercase creator keys and preserves full-link key case', () => {
+ const { parseAffiliateInput } = require('../affiliateLink') as typeof import('../affiliateLink');
+ expect(parseAffiliateInput(' demo_creator-1 ', 'sandbox.dub.link').href).toBe(
+ 'https://sandbox.dub.link/demo_creator-1',
+ );
+ expect(parseAffiliateInput('https://sandbox.dub.link/Demo', 'sandbox.dub.link').pathname).toBe(
+ '/Demo',
+ );
+});
+it.each(['Demo', 'démø', 'demo/name', 'demo?x=1', 'demo#tag', 'demo name', 'a'.repeat(65), ''])(
+ 'rejects ambiguous short input %s',
+ (input) => {
+ const { parseAffiliateInput } =
+ require('../affiliateLink') as typeof import('../affiliateLink');
+ expect(() => parseAffiliateInput(input, 'sandbox.dub.link')).toThrow();
+ },
+);
diff --git a/openwhispr-mobile/src/lib/__tests__/affiliateOffer.test.ts b/openwhispr-mobile/src/lib/__tests__/affiliateOffer.test.ts
new file mode 100644
index 000000000..9202b4d72
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/affiliateOffer.test.ts
@@ -0,0 +1,191 @@
+import { getTrackingAuthorizationStatus } from '../trackingTransparency';
+const mockConfig: { config: { usageAnalyticsEnabled?: boolean } } = {
+ config: { usageAnalyticsEnabled: true },
+};
+jest.mock('@/store/useConfigStore', () => ({ useConfigStore: { getState: () => mockConfig } }));
+jest.mock('../trackingTransparency', () => ({
+ getTrackingAuthorizationStatus: jest.fn(async () => 'authorized'),
+}));
+import Purchases from 'react-native-purchases';
+import { api } from '../apiClient';
+import { loadAffiliateOffer, validAffiliateOffer } from '../affiliateOffer';
+import { getAppStorefrontCountryCode } from '../revenuecat';
+const mockAuth = { user: { id: 'buyer' }, sessionCookie: 'session' };
+const mockUsage = { billingUserId: 'billing-id', isSubscribed: false };
+jest.mock('@/store/useAuthStore', () => ({ useAuthStore: { getState: () => mockAuth } }));
+jest.mock('@/store/useUsageStore', () => ({
+ useUsageStore: { getState: () => ({ usage: mockUsage }) },
+}));
+jest.mock('../affiliateLink', () => ({
+ getAffiliateClientConfig: () => ({ domain: 'sandbox.dub.link' }),
+}));
+jest.mock('../apiClient', () => ({ api: { post: jest.fn() } }));
+jest.mock('../revenuecat', () => ({ getAppStorefrontCountryCode: jest.fn() }));
+jest.mock('react-native-purchases', () => ({ getAppUserID: jest.fn(), getProducts: jest.fn() }));
+const offer = {
+ campaign: 'first-three',
+ productId: 'pro.monthly',
+ country: 'USA',
+ currency: 'USD',
+ regularPrice: 9.99,
+ offerPrice: 7.99,
+ months: 3,
+ redemptionUrl: 'https://apps.apple.com/redeem?ctx=offercodes&id=12345&code=TESTCODE',
+ expiresAt: '2099-01-01T00:00:00Z',
+};
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockConfig.config.usageAnalyticsEnabled = true;
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('authorized');
+ mockAuth.user.id = 'buyer';
+ mockUsage.isSubscribed = false;
+ jest.mocked(getAppStorefrontCountryCode).mockResolvedValue('USA');
+ jest.mocked(Purchases.getAppUserID).mockResolvedValue('billing-id');
+ jest.mocked(api.post).mockResolvedValue({ data: offer });
+ jest
+ .mocked(Purchases.getProducts)
+ .mockResolvedValue([
+ { identifier: 'pro.monthly', price: 9.99, currencyCode: 'USD', subscriptionPeriod: 'P1M' },
+ ] as Awaited<ReturnType<typeof Purchases.getProducts>>);
+});
+afterEach(() => jest.useRealTimers());
+it('checks the storefront, billing identity and actual monthly product before offering the code', async () => {
+ expect(await loadAffiliateOffer()).toEqual(offer);
+ expect(api.post).toHaveBeenCalledWith(
+ '/api/affiliate/apple-offer',
+ { country: 'USA' },
+ expect.objectContaining({ authenticated: false, headers: { Cookie: 'session' } }),
+ );
+});
+it('a wrong storefront price, annual product or billing identity does not advertise an offer', async () => {
+ jest
+ .mocked(Purchases.getProducts)
+ .mockResolvedValue([
+ { identifier: 'pro.monthly', price: 10.99, currencyCode: 'USD', subscriptionPeriod: 'P1M' },
+ ] as Awaited<ReturnType<typeof Purchases.getProducts>>);
+ expect(await loadAffiliateOffer()).toBeNull();
+ jest.mocked(Purchases.getAppUserID).mockResolvedValue('another-owner');
+ expect(await loadAffiliateOffer()).toBeNull();
+});
+it('account changes during the product fetch discard the old account offer', async () => {
+ jest.mocked(Purchases.getProducts).mockImplementation(async () => {
+ mockAuth.user.id = 'another';
+ return [
+ { identifier: 'pro.monthly', price: 9.99, currencyCode: 'USD', subscriptionPeriod: 'P1M' },
+ ] as Awaited<ReturnType<typeof Purchases.getProducts>>;
+ });
+ expect(await loadAffiliateOffer()).toBeNull();
+});
+it('a hung native lookup cannot hold the paywall indefinitely', async () => {
+ jest.useFakeTimers();
+ jest.mocked(getAppStorefrontCountryCode).mockImplementation(() => new Promise(() => {}));
+ const pending = loadAffiliateOffer();
+ await jest.advanceTimersByTimeAsync(8001);
+ expect(await pending).toBeNull();
+ expect(api.post).not.toHaveBeenCalled();
+});
+it('refuses expired, mismatched-price or foreign redemption URLs', () => {
+ expect(
+ validAffiliateOffer(
+ { ...offer, redemptionUrl: offer.redemptionUrl.replace('apps.apple.com', 'evil.test') },
+ 'USA',
+ ),
+ ).toBe(false);
+ expect(validAffiliateOffer({ ...offer, expiresAt: '2020-01-01T00:00:00Z' }, 'USA')).toBe(false);
+ expect(validAffiliateOffer({ ...offer, offerPrice: 8.99 }, 'USA')).toBe(false);
+ expect(validAffiliateOffer({ ...offer, months: 12 }, 'USA')).toBe(false);
+});
+it('uses the currency precision for zero- and three-decimal storefronts', () => {
+ expect(
+ validAffiliateOffer(
+ { ...offer, country: 'JPN', currency: 'JPY', regularPrice: 1000, offerPrice: 800 },
+ 'JPN',
+ ),
+ ).toBe(true);
+ expect(
+ validAffiliateOffer(
+ { ...offer, country: 'KWT', currency: 'KWD', regularPrice: 3.499, offerPrice: 2.799 },
+ 'KWT',
+ ),
+ ).toBe(true);
+});
+
+it('does not allocate stock after the presenting caller leaves during storefront lookup', async () => {
+ let current = true;
+ jest.mocked(getAppStorefrontCountryCode).mockImplementation(async () => {
+ current = false;
+ return 'USA';
+ });
+ expect(await loadAffiliateOffer(() => current)).toBeNull();
+ expect(api.post).not.toHaveBeenCalled();
+});
+it('a cancelled caller cannot start an offer lookup', async () => {
+ expect(await loadAffiliateOffer(() => false)).toBeNull();
+ expect(getAppStorefrontCountryCode).not.toHaveBeenCalled();
+ expect(api.post).not.toHaveBeenCalled();
+});
+
+it('does not allocate after dismissal during billing identity lookup', async () => {
+ let current = true;
+ jest.mocked(Purchases.getAppUserID).mockImplementation(async () => {
+ current = false;
+ return 'billing-id';
+ });
+ expect(await loadAffiliateOffer(() => current)).toBeNull();
+ expect(api.post).not.toHaveBeenCalled();
+});
+it('discards an allocation arriving after dismissal without looking up products', async () => {
+ let current = true;
+ jest.mocked(api.post).mockImplementation(async () => {
+ current = false;
+ return { data: offer };
+ });
+ expect(await loadAffiliateOffer(() => current)).toBeNull();
+ expect(Purchases.getProducts).not.toHaveBeenCalled();
+});
+it('discards verified product data arriving after dismissal', async () => {
+ let current = true;
+ jest.mocked(Purchases.getProducts).mockImplementation(async () => {
+ current = false;
+ return [
+ { identifier: 'pro.monthly', price: 9.99, currencyCode: 'USD', subscriptionPeriod: 'P1M' },
+ ] as Awaited<ReturnType<typeof Purchases.getProducts>>;
+ });
+ expect(await loadAffiliateOffer(() => current)).toBeNull();
+});
+
+it('offers the code on the default Usage Analytics setting', async () => {
+ delete mockConfig.config.usageAnalyticsEnabled;
+ expect(await loadAffiliateOffer()).toEqual(offer);
+});
+it('does not allocate stock when a saved creator has Analytics disabled or tracking denied', async () => {
+ mockConfig.config.usageAnalyticsEnabled = false;
+ expect(await loadAffiliateOffer()).toBeNull();
+ mockConfig.config.usageAnalyticsEnabled = true;
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('denied');
+ expect(await loadAffiliateOffer()).toBeNull();
+ expect(api.post).not.toHaveBeenCalled();
+});
+it('rechecks tracking after native identity lookup before allocating stock', async () => {
+ jest.mocked(Purchases.getAppUserID).mockImplementation(async () => {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('denied');
+ return 'billing-id';
+ });
+ expect(await loadAffiliateOffer()).toBeNull();
+ expect(api.post).not.toHaveBeenCalled();
+});
+
+it('rejects an offer which expires during the native product lookup', async () => {
+ jest.useFakeTimers();
+ jest.setSystemTime(new Date('2026-09-25T12:00:00Z'));
+ jest
+ .mocked(api.post)
+ .mockResolvedValue({ data: { ...offer, expiresAt: '2026-09-25T12:00:01Z' } });
+ jest.mocked(Purchases.getProducts).mockImplementation(async () => {
+ jest.setSystemTime(new Date('2026-09-25T12:00:02Z'));
+ return [
+ { identifier: 'pro.monthly', price: 9.99, currencyCode: 'USD', subscriptionPeriod: 'P1M' },
+ ] as Awaited<ReturnType<typeof Purchases.getProducts>>;
+ });
+ expect(await loadAffiliateOffer()).toBeNull();
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/affiliatePaywall.test.ts b/openwhispr-mobile/src/lib/__tests__/affiliatePaywall.test.ts
new file mode 100644
index 000000000..a07e3ce07
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/affiliatePaywall.test.ts
@@ -0,0 +1,378 @@
+jest.mock('@/store/useAuthStore', () => ({
+ useAuthStore: { getState: () => ({ user: { id: 'buyer' }, sessionCookie: 'session' }) },
+}));
+jest.mock('../apiClient', () => ({ api: { post: jest.fn() } }));
+import { AppState, Linking } from 'react-native';
+import Purchases from 'react-native-purchases';
+import {
+ createAffiliatePaywallSession,
+ CREATOR_INPUT_KEY,
+ CREATOR_PLAN_KEY,
+ CREATOR_PRODUCT_KEY,
+ CREATOR_TOKEN_KEY,
+} from '../affiliatePaywall';
+import { loadAffiliateOffer } from '../affiliateOffer';
+import { getTrackingAuthorizationStatus } from '../trackingTransparency';
+import { reconcileStoreBilling } from '../billingReconciliation';
+let mockIdentity: { userId: string; sessionCookie: string; billingUserId: string } | null = {
+ userId: 'buyer',
+ sessionCookie: 'session',
+ billingUserId: 'billing',
+};
+let mockIdentityCurrent = true;
+const mockUsage = {
+ usage: { isSubscribed: false },
+ beginBillingSession: jest.fn(),
+ endBillingSession: jest.fn(),
+ load: jest.fn(),
+};
+const mockConfig: { config: { usageAnalyticsEnabled?: boolean } } = {
+ config: { usageAnalyticsEnabled: true },
+};
+const mockCandidate = {
+ link: '',
+ saved: false,
+ checking: false,
+ hydrate: jest.fn(),
+ bindSession: jest.fn(),
+ edit: jest.fn(),
+ prepare: jest.fn(),
+};
+jest.mock('../billingIdentity', () => ({
+ getBillingIdentity: () => mockIdentity,
+ isBillingIdentityCurrent: () => mockIdentityCurrent,
+}));
+jest.mock('@/store/useAffiliateStore', () => ({
+ useAffiliateStore: { getState: () => mockCandidate },
+}));
+jest.mock('@/store/useUsageStore', () => ({ useUsageStore: { getState: () => mockUsage } }));
+jest.mock('@/store/useConfigStore', () => ({ useConfigStore: { getState: () => mockConfig } }));
+jest.mock('../affiliateLink', () => ({
+ ...jest.requireActual('../affiliateLink'),
+ getAffiliateClientConfig: () => ({ domain: 'creators.example.com' }),
+}));
+jest.mock('../affiliateOffer', () => ({
+ ...jest.requireActual('../affiliateOffer'),
+ loadAffiliateOffer: jest.fn(),
+}));
+jest.mock('../trackingTransparency', () => ({ getTrackingAuthorizationStatus: jest.fn() }));
+jest.mock('../revenuecat', () => ({ getAppStorefrontCountryCode: jest.fn(async () => 'USA') }));
+jest.mock('../billingReconciliation', () => ({ reconcileStoreBilling: jest.fn(async () => {}) }));
+jest.mock('react-native-purchases', () => ({ getAppUserID: jest.fn(), getProducts: jest.fn() }));
+const offer = {
+ campaign: 'fixture',
+ productId: 'monthly',
+ country: 'USA',
+ currency: 'USD',
+ regularPrice: 9.99,
+ offerPrice: 7.99,
+ months: 3 as const,
+ redemptionUrl: 'https://apps.apple.com/redeem?ctx=offercodes&id=123&code=TEST',
+ expiresAt: '2099-01-01T00:00:00Z',
+};
+const apply = () => ({
+ name: 'creatorCodeApply',
+ variables: {
+ [CREATOR_INPUT_KEY]: 'demo',
+ [CREATOR_PLAN_KEY]: 1,
+ [CREATOR_PRODUCT_KEY]: 'monthly',
+ },
+});
+function redeem(data: Record<string, unknown>) {
+ return {
+ name: 'creatorOfferRedeem',
+ variables: {
+ [CREATOR_PLAN_KEY]: 1,
+ [CREATOR_PRODUCT_KEY]: 'monthly',
+ [CREATOR_TOKEN_KEY]: data.offerToken,
+ 'callbacks.creatorCodeApply.data.priceText': data.priceText,
+ 'callbacks.creatorCodeApply.data.renewalText': data.renewalText,
+ },
+ };
+}
+let sessions: ReturnType<typeof createAffiliatePaywallSession>[] = [];
+const start = () => {
+ const session = createAffiliatePaywallSession(() => true, jest.fn());
+ sessions.push(session);
+ return session;
+};
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockIdentityCurrent = true;
+ mockIdentity = { userId: 'buyer', sessionCookie: 'session', billingUserId: 'billing' };
+ mockConfig.config.usageAnalyticsEnabled = true;
+ mockUsage.usage.isSubscribed = false;
+ Object.assign(mockCandidate, { link: '', saved: false, checking: false });
+ mockCandidate.edit.mockImplementation(async (link) => {
+ mockCandidate.link = link;
+ });
+ mockCandidate.prepare.mockImplementation(async () => {
+ mockCandidate.saved = true;
+ return true;
+ });
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(offer);
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('authorized');
+ jest.mocked(Purchases.getAppUserID).mockResolvedValue('billing');
+ jest
+ .mocked(Purchases.getProducts)
+ .mockResolvedValue([
+ { identifier: 'monthly', price: 9.99, currencyCode: 'USD', subscriptionPeriod: 'P1M' },
+ ] as Awaited<ReturnType<typeof Purchases.getProducts>>);
+ jest.spyOn(Linking, 'openURL').mockResolvedValue(true);
+ jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: jest.fn() });
+});
+afterEach(() => {
+ sessions.forEach((s) => s.close());
+ sessions = [];
+ jest.useRealTimers();
+});
+it('only returns display strings and a presentation token after explicit attribution and verified allocation', async () => {
+ const result = await start().handle(apply());
+ expect(result).toMatchObject({
+ status: 'success',
+ data: {
+ priceText: '$7.99',
+ renewalText: expect.stringContaining('$9.99'),
+ offerToken: expect.any(String),
+ },
+ });
+ expect(Object.keys(result.data!).sort()).toEqual(['offerToken', 'priceText', 'renewalText']);
+ expect(JSON.stringify(result)).not.toContain('TEST');
+ expect(JSON.stringify(result)).not.toContain('apps.apple.com');
+ expect(mockCandidate.prepare).toHaveBeenCalledTimes(1);
+ expect(loadAffiliateOffer).toHaveBeenCalledTimes(1);
+ expect(Linking.openURL).not.toHaveBeenCalled();
+});
+it.each([0, '1', null])(
+ 'rejects non-monthly or malformed selected plan %s without a claim',
+ async (selected) => {
+ const request = apply();
+ request.variables[CREATOR_PLAN_KEY] = selected as number;
+ expect((await start().handle(request)).status).toBe('failure');
+ expect(mockCandidate.prepare).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ },
+);
+it.each(['denied', 'notDetermined'] as const)(
+ 'preserves ordinary purchase by refusing creator work when consent is %s',
+ async (status) => {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue(status);
+ expect((await start().handle(apply())).status).toBe('failure');
+ expect(mockCandidate.edit).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ },
+);
+it('applies a code on the default Usage Analytics setting', async () => {
+ delete mockConfig.config.usageAnalyticsEnabled;
+ expect((await start().handle(apply())).status).toBe('success');
+});
+it('refuses a different saved creator instead of treating new text as saved', async () => {
+ mockCandidate.saved = true;
+ mockCandidate.link = 'first';
+ expect((await start().handle(apply())).status).toBe('failure');
+ expect(mockCandidate.edit).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+});
+it.each(['dismissal', 'account switch'])('drops an offer arriving after %s', async (reason) => {
+ let resolve!: (value: typeof offer) => void;
+ jest.mocked(loadAffiliateOffer).mockImplementation(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const session = start();
+ const pending = session.handle(apply());
+ await new Promise<void>((done) => setImmediate(done));
+ if (reason === 'dismissal') session.close();
+ else mockIdentityCurrent = false;
+ resolve(offer);
+ expect((await pending).status).toBe('failure');
+ expect(Linking.openURL).not.toHaveBeenCalled();
+});
+it('ties redemption to the exact displayed private offer and refuses a later presentation', async () => {
+ const first = start();
+ const result = await first.handle(apply());
+ expect((await start().handle(redeem(result.data!))).status).toBe('failure');
+ expect(Linking.openURL).not.toHaveBeenCalled();
+ expect((await first.handle(redeem(result.data!))).status).toBe('success');
+ expect(Linking.openURL).toHaveBeenCalledWith(offer.redemptionUrl);
+ expect(mockUsage.beginBillingSession).toHaveBeenCalledTimes(1);
+});
+it('refuses changed displayed price and a changed catalog before opening Apple', async () => {
+ const session = start();
+ const result = await session.handle(apply());
+ expect((await session.handle(redeem({ ...result.data, priceText: '$1.00' }))).status).toBe(
+ 'failure',
+ );
+ jest.mocked(Purchases.getProducts).mockResolvedValue([]);
+ expect((await session.handle(redeem(result.data!))).status).toBe('failure');
+ expect(Linking.openURL).not.toHaveBeenCalled();
+});
+it('keeps Use code locked while checking a return, then rearms the guard for a retry', async () => {
+ jest.useFakeTimers();
+ const session = start();
+ const applied = await session.handle(apply());
+ const request = redeem(applied.data!);
+ const onAppState = jest.mocked(AppState.addEventListener).mock.calls.at(-1)![1];
+
+ expect((await session.handle(request)).status).toBe('success');
+ expect(mockUsage.beginBillingSession).toHaveBeenCalledTimes(1);
+ onAppState('background');
+ // RootLayout consumes the shared guard on each return from external billing.
+ mockUsage.endBillingSession();
+ onAppState('active');
+ await jest.advanceTimersByTimeAsync(1);
+ expect(await session.handle(request)).toEqual({
+ status: 'failure',
+ data: { message: 'We’re still checking your purchase. Try again in a moment.' },
+ });
+ await jest.advanceTimersByTimeAsync(7_001);
+ expect(reconcileStoreBilling).toHaveBeenCalledTimes(3);
+
+ expect((await session.handle(request)).status).toBe('success');
+ expect(Linking.openURL).toHaveBeenCalledTimes(2);
+ expect(mockUsage.beginBillingSession).toHaveBeenCalledTimes(2);
+});
+it('reports a redemption confirmed on return as a purchase of the offered product', async () => {
+ jest.useFakeTimers();
+ const onRedeemed = jest.fn();
+ const session = createAffiliatePaywallSession(() => true, onRedeemed);
+ sessions.push(session);
+ const applied = await session.handle(apply());
+ const onAppState = jest.mocked(AppState.addEventListener).mock.calls.at(-1)![1];
+ expect((await session.handle(redeem(applied.data!))).status).toBe('success');
+ mockUsage.load.mockImplementation(async () => {
+ if (jest.mocked(reconcileStoreBilling).mock.calls.length === 2)
+ mockUsage.usage.isSubscribed = true;
+ });
+ onAppState('background');
+ onAppState('active');
+ await jest.advanceTimersByTimeAsync(2_001);
+ expect(onRedeemed).toHaveBeenCalledWith('monthly');
+ expect(reconcileStoreBilling).toHaveBeenCalledTimes(2);
+});
+it('does not return success for a different monthly product', async () => {
+ jest.mocked(loadAffiliateOffer).mockResolvedValue({ ...offer, productId: 'other' });
+ expect((await start().handle(apply())).status).toBe('failure');
+});
+it('bounds a hung preparation and prevents its late result from allocating', async () => {
+ jest.useFakeTimers();
+ let finish!: () => void;
+ mockCandidate.hydrate.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const pending = start().handle(apply());
+ await jest.advanceTimersByTimeAsync(20_001);
+ expect((await pending).status).toBe('failure');
+ finish();
+ await jest.advanceTimersByTimeAsync(1);
+ expect(mockCandidate.prepare).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+});
+
+it('binds billing identity after usage loads without replacing the opening account', async () => {
+ mockIdentity = null;
+ const session = start();
+ expect((await session.handle(apply())).status).toBe('failure');
+ mockIdentity = { userId: 'buyer', sessionCookie: 'session', billingUserId: 'billing' };
+ expect((await session.handle(apply())).status).toBe('success');
+});
+it('seeds Account display values while keeping redemption private and avoiding another allocation', async () => {
+ const session = createAffiliatePaywallSession(() => true, jest.fn(), offer);
+ sessions.push(session);
+ expect(Object.keys(session.initialParams).sort()).toEqual([
+ 'creator_offer_price',
+ 'creator_offer_ready',
+ 'creator_offer_renewal',
+ 'creator_offer_token',
+ ]);
+ expect(JSON.stringify(session.initialParams)).not.toContain('apps.apple.com');
+ const request = {
+ name: 'creatorOfferRedeem',
+ variables: {
+ [CREATOR_PLAN_KEY]: 1,
+ [CREATOR_PRODUCT_KEY]: 'monthly',
+ ...Object.fromEntries(
+ Object.entries(session.initialParams).map(([key, value]) => [`params.${key}`, value]),
+ ),
+ },
+ };
+ expect((await session.handle(request)).status).toBe('success');
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockCandidate.prepare).not.toHaveBeenCalled();
+ expect(Linking.openURL).toHaveBeenCalledTimes(1);
+ expect((await session.handle(request)).status).toBe('failure');
+ expect(Linking.openURL).toHaveBeenCalledTimes(1);
+});
+it('keeps a seeded offer redeemable after a refused apply of another code', async () => {
+ mockCandidate.saved = true;
+ mockCandidate.link = 'first';
+ const session = createAffiliatePaywallSession(() => true, jest.fn(), offer);
+ sessions.push(session);
+ expect((await session.handle(apply())).status).toBe('failure');
+ const request = {
+ name: 'creatorOfferRedeem',
+ variables: {
+ [CREATOR_PLAN_KEY]: 1,
+ [CREATOR_PRODUCT_KEY]: 'monthly',
+ ...Object.fromEntries(
+ Object.entries(session.initialParams).map(([key, value]) => [`params.${key}`, value]),
+ ),
+ },
+ };
+ expect((await session.handle(request)).status).toBe('success');
+ expect(Linking.openURL).toHaveBeenCalledWith(offer.redemptionUrl);
+});
+it('keeps a seeded offer redeemable after an apply times out', async () => {
+ jest.useFakeTimers();
+ mockCandidate.hydrate.mockImplementationOnce(() => new Promise<void>(() => {}));
+ const session = createAffiliatePaywallSession(() => true, jest.fn(), offer);
+ sessions.push(session);
+ const pending = session.handle(apply());
+ await jest.advanceTimersByTimeAsync(20_001);
+ expect((await pending).status).toBe('failure');
+ const request = {
+ name: 'creatorOfferRedeem',
+ variables: {
+ [CREATOR_PLAN_KEY]: 1,
+ [CREATOR_PRODUCT_KEY]: 'monthly',
+ ...Object.fromEntries(
+ Object.entries(session.initialParams).map(([key, value]) => [`params.${key}`, value]),
+ ),
+ },
+ };
+ expect((await session.handle(request)).status).toBe('success');
+ expect(Linking.openURL).toHaveBeenCalledWith(offer.redemptionUrl);
+});
+it('clears cached seed parameters for the next ordinary presentation', () => {
+ const seeded = createAffiliatePaywallSession(() => true, jest.fn(), offer);
+ sessions.push(seeded);
+ seeded.close();
+ const ordinary = start();
+ // Model the SDK merging new parameters into its cached presentation data.
+ expect({ ...seeded.initialParams, ...ordinary.initialParams }).toEqual({
+ creator_offer_ready: false,
+ creator_offer_price: '',
+ creator_offer_renewal: '',
+ creator_offer_token: '',
+ });
+});
+it('does not display an allocation after tracking permission is revoked', async () => {
+ jest.mocked(loadAffiliateOffer).mockImplementationOnce(async () => {
+ jest.mocked(getTrackingAuthorizationStatus).mockResolvedValue('denied');
+ return offer;
+ });
+ expect((await start().handle(apply())).status).toBe('failure');
+});
+
+it('matches the same saved trusted creator key despite tracking query and hash', async () => {
+ mockCandidate.saved = true;
+ mockCandidate.link = 'https://creators.example.com/demo?utm_source=creator#offer';
+ expect((await start().handle(apply())).status).toBe('success');
+ expect(mockCandidate.edit).not.toHaveBeenCalled();
+ expect(mockCandidate.link).toContain('?utm_source=creator#offer');
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/billingReconciliation.test.ts b/openwhispr-mobile/src/lib/__tests__/billingReconciliation.test.ts
new file mode 100644
index 000000000..7b575aa1f
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/billingReconciliation.test.ts
@@ -0,0 +1,57 @@
+import { reconcileStoreBilling } from '../billingReconciliation';
+import { reconcileRevenueCatPurchases } from '../revenuecat';
+import { reconcileMobileBilling } from '@/data/remote/billingApi';
+
+let mockAuth = { user: { id: 'a' }, sessionCookie: 'cookie-a' };
+let mockUsage = { billingUserId: 'billing-a' };
+jest.mock('@/store/useAuthStore', () => ({ useAuthStore: { getState: () => mockAuth } }));
+jest.mock('@/store/useUsageStore', () => ({
+ useUsageStore: { getState: () => ({ usage: mockUsage }) },
+}));
+jest.mock('../revenuecat', () => ({ reconcileRevenueCatPurchases: jest.fn() }));
+jest.mock('@/data/remote/billingApi', () => ({ reconcileMobileBilling: jest.fn() }));
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockAuth = { user: { id: 'a' }, sessionCookie: 'cookie-a' };
+ mockUsage = { billingUserId: 'billing-a' };
+ jest.mocked(reconcileRevenueCatPurchases).mockResolvedValue(true);
+ jest.mocked(reconcileMobileBilling).mockResolvedValue({ isSubscribed: true } as never);
+});
+
+it('shares a check only within the same account and retains its original HTTP credentials', async () => {
+ const first = reconcileStoreBilling();
+ expect(reconcileStoreBilling()).toBe(first);
+ await first;
+ expect(reconcileMobileBilling).toHaveBeenCalledWith('ios', 'cookie-a');
+});
+
+it('does not share another account’s check or send its result to the new owner', async () => {
+ let release!: (value: boolean) => void;
+ jest.mocked(reconcileRevenueCatPurchases).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ const first = reconcileStoreBilling();
+ const rejected = expect(first).rejects.toThrow('Billing account changed');
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ mockAuth = { user: { id: 'b' }, sessionCookie: 'cookie-b' };
+ mockUsage = { billingUserId: 'billing-b' };
+ const second = reconcileStoreBilling();
+ expect(second).not.toBe(first);
+ release(true);
+ await rejected;
+ await second;
+ expect(reconcileMobileBilling).toHaveBeenCalledTimes(1);
+ expect(reconcileMobileBilling).toHaveBeenCalledWith('ios', 'cookie-b');
+});
+
+it('discards an HTTP response after a session change', async () => {
+ jest.mocked(reconcileMobileBilling).mockImplementationOnce(async () => {
+ mockAuth.sessionCookie = 'new-cookie';
+ return { isSubscribed: true } as never;
+ });
+ await expect(reconcileStoreBilling()).rejects.toThrow('Billing account changed');
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/revenuecat.test.ts b/openwhispr-mobile/src/lib/__tests__/revenuecat.test.ts
index 6e75c6d28..18e747dd2 100644
--- a/openwhispr-mobile/src/lib/__tests__/revenuecat.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/revenuecat.test.ts
@@ -1,7 +1,10 @@
import Purchases from 'react-native-purchases';
import {
getAppStorefrontCountryCode,
+ reconcileRevenueCatPurchases,
+ identifyRevenueCatUser,
recordRevenueCatPurchase,
+ resetRevenueCatUser,
showAppStoreManageSubscriptions,
} from '../revenuecat';
@@ -10,6 +13,9 @@ jest.mock('react-native-purchases', () => ({
__esModule: true,
default: {
configure: jest.fn(),
+ logIn: jest.fn(),
+ logOut: jest.fn(),
+ syncPurchasesForResult: jest.fn(),
getStorefront: jest.fn(),
recordPurchase: jest.fn(),
showManageSubscriptions: jest.fn(),
@@ -68,3 +74,118 @@ describe('RevenueCat StoreKit helpers', () => {
await expect(recordRevenueCatPurchase('pro.monthly')).resolves.toBe(false);
});
});
+
+it('does not sync an old account when login finishes after an account switch', async () => {
+ let release!: (value: never) => void;
+ let current = true;
+ mockPurchases.logIn.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ const pending = reconcileRevenueCatPurchases('billing-a', () => current);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ current = false;
+ release({} as never);
+ expect(await pending).toBe(false);
+ expect(mockPurchases.syncPurchasesForResult).not.toHaveBeenCalled();
+});
+it('serializes another login behind an in-progress purchase sync', async () => {
+ jest.clearAllMocks();
+ let release!: (value: never) => void;
+ mockPurchases.logIn.mockResolvedValue({} as never);
+ mockPurchases.syncPurchasesForResult.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ const pending = reconcileRevenueCatPurchases('billing-a', () => true);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ const next = identifyRevenueCatUser('billing-b');
+ expect(mockPurchases.logIn).toHaveBeenCalledTimes(1);
+ release({} as never);
+ expect(await pending).toBe(true);
+ expect(await next).toBe(true);
+ expect(mockPurchases.logIn.mock.calls.map(([id]) => id)).toEqual(['billing-a', 'billing-b']);
+});
+
+it('releases a hung call at its deadline and still runs queued identity changes in order', async () => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ let release!: (value: never) => void;
+ mockPurchases.recordPurchase.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ mockPurchases.logIn.mockResolvedValue({} as never);
+ const recording = recordRevenueCatPurchase('monthly');
+ await Promise.resolve();
+ const next = identifyRevenueCatUser('billing-b');
+ const reset = resetRevenueCatUser();
+ await jest.advanceTimersByTimeAsync(10001);
+ expect(await recording).toBe(false);
+ expect(mockPurchases.logIn).not.toHaveBeenCalled();
+ release({} as never);
+ expect(await next).toBe(true);
+ await reset;
+ expect(mockPurchases.logIn).toHaveBeenCalledWith('billing-b');
+ expect(mockPurchases.logOut).toHaveBeenCalledTimes(1);
+ jest.useRealTimers();
+});
+it('releases a caller stuck behind a call that never settles, then still runs its work', async () => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ let release!: (value: never) => void;
+ mockPurchases.recordPurchase.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ mockPurchases.logIn.mockResolvedValue({} as never);
+ const recording = recordRevenueCatPurchase('monthly');
+ const next = identifyRevenueCatUser('billing-b');
+ await jest.advanceTimersByTimeAsync(90001);
+ expect(await recording).toBe(false);
+ expect(await next).toBe(false);
+ expect(mockPurchases.logIn).not.toHaveBeenCalled();
+ release({} as never);
+ await jest.advanceTimersByTimeAsync(1);
+ expect(mockPurchases.logIn).toHaveBeenCalledWith('billing-b');
+ jest.useRealTimers();
+});
+it('starts a queued call’s deadline when it runs, not when it was queued', async () => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ mockPurchases.recordPurchase.mockImplementationOnce(
+ () => new Promise((resolve) => setTimeout(() => resolve({} as never), 9000)),
+ );
+ mockPurchases.logIn.mockImplementation(
+ () => new Promise((resolve) => setTimeout(() => resolve({} as never), 2000)),
+ );
+ mockPurchases.syncPurchasesForResult.mockImplementation(
+ () => new Promise((resolve) => setTimeout(() => resolve({} as never), 2000)),
+ );
+ const recording = recordRevenueCatPurchase('monthly');
+ const reconciling = reconcileRevenueCatPurchases('billing-a', () => true);
+ await jest.advanceTimersByTimeAsync(13001);
+ expect(await recording).toBe(true);
+ expect(await reconciling).toBe(true);
+ jest.useRealTimers();
+});
+it('gives a slow purchase restore time to finish instead of the login deadline', async () => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ mockPurchases.logIn.mockResolvedValue({} as never);
+ mockPurchases.syncPurchasesForResult.mockImplementationOnce(
+ () => new Promise((resolve) => setTimeout(() => resolve({} as never), 30_000)),
+ );
+ const reconciling = reconcileRevenueCatPurchases('billing-a', () => true);
+ await jest.advanceTimersByTimeAsync(30_001);
+ expect(await reconciling).toBe(true);
+ jest.useRealTimers();
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/superwall.test.ts b/openwhispr-mobile/src/lib/__tests__/superwall.test.ts
index fb9d5899c..5bf4c47d0 100644
--- a/openwhispr-mobile/src/lib/__tests__/superwall.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/superwall.test.ts
@@ -1,5 +1,7 @@
import type { UsageInfo } from '@/data/remote/usageApi';
+import { getAffiliateClientConfig } from '@/lib/affiliateLink';
import {
+ CREATOR_CODE_PAYWALL_PLACEMENT,
SUPERWALL_APP_ENTITLEMENT_ID,
SUPERWALL_PLACEMENTS,
SUPERWALL_WORDS_REMAINING_SENTINEL,
@@ -7,8 +9,11 @@ import {
buildSuperwallSubscriptionStatus,
buildUsageGateParams,
isTransactionalSuperwallPlacement,
+ resolveSuperwallPlacementName,
} from '@/lib/superwall';
+jest.mock('@/lib/affiliateLink', () => ({ getAffiliateClientConfig: jest.fn(() => null) }));
+
const baseUsage: UsageInfo = {
billingUserId: '00000000-0000-4000-8000-000000000001',
wordsUsed: 750,
@@ -96,3 +101,32 @@ describe('superwall billing bridge mapping', () => {
});
});
});
+
+describe('creator-code paywall placement', () => {
+ afterEach(() => jest.mocked(getAffiliateClientConfig).mockReturnValue(null));
+
+ it('keeps every placement unchanged in a build without creator codes', () => {
+ for (const placement of Object.values(SUPERWALL_PLACEMENTS)) {
+ expect(resolveSuperwallPlacementName(placement, false)).toBe(placement);
+ expect(resolveSuperwallPlacementName(placement, true)).toBe(placement);
+ }
+ });
+
+ it('sends onboarding and creator offers to the creator-code paywall when creator codes are on', () => {
+ jest
+ .mocked(getAffiliateClientConfig)
+ .mockReturnValue({ domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' });
+ expect(resolveSuperwallPlacementName(SUPERWALL_PLACEMENTS.onboardingPaywall, false)).toBe(
+ CREATOR_CODE_PAYWALL_PLACEMENT,
+ );
+ expect(resolveSuperwallPlacementName(SUPERWALL_PLACEMENTS.accountBillingOpen, true)).toBe(
+ CREATOR_CODE_PAYWALL_PLACEMENT,
+ );
+ expect(resolveSuperwallPlacementName(SUPERWALL_PLACEMENTS.accountBillingOpen, false)).toBe(
+ SUPERWALL_PLACEMENTS.accountBillingOpen,
+ );
+ expect(resolveSuperwallPlacementName(SUPERWALL_PLACEMENTS.cloudUsageLimitReached, false)).toBe(
+ SUPERWALL_PLACEMENTS.cloudUsageLimitReached,
+ );
+ });
+});
diff --git a/openwhispr-mobile/src/lib/__tests__/usageAnalytics.test.ts b/openwhispr-mobile/src/lib/__tests__/usageAnalytics.test.ts
new file mode 100644
index 000000000..404a05127
--- /dev/null
+++ b/openwhispr-mobile/src/lib/__tests__/usageAnalytics.test.ts
@@ -0,0 +1,10 @@
+import { isUsageAnalyticsAllowed } from '../usageAnalytics';
+
+it('defaults to on once config has loaded, and fails closed before that', () => {
+ expect(isUsageAnalyticsAllowed(null)).toBe(false);
+ expect(isUsageAnalyticsAllowed({ defaultMode: 'cloud' })).toBe(true);
+ expect(isUsageAnalyticsAllowed({ defaultMode: 'cloud', usageAnalyticsEnabled: true })).toBe(true);
+ expect(isUsageAnalyticsAllowed({ defaultMode: 'cloud', usageAnalyticsEnabled: false })).toBe(
+ false,
+ );
+});
diff --git a/openwhispr-mobile/src/lib/affiliateAttribution.ts b/openwhispr-mobile/src/lib/affiliateAttribution.ts
new file mode 100644
index 000000000..9cae6debe
--- /dev/null
+++ b/openwhispr-mobile/src/lib/affiliateAttribution.ts
@@ -0,0 +1,120 @@
+import { api } from './apiClient';
+import { getAffiliateClientConfig, parseAffiliateInput } from './affiliateLink';
+import { setAppsFlyerTrackingAuthorizationStatus } from './appsflyer';
+import {
+ getTrackingAuthorizationStatus,
+ requestTrackingAuthorization,
+} from './trackingTransparency';
+
+export type AffiliateClaimStatus = 'provisional' | 'pending' | 'registered' | 'review';
+export class AffiliateConsentError extends Error {}
+
+type DubOpen = { clickId?: string; link?: { domain?: string; key?: string } };
+
+// The one Dub call the app needs. Its SDK would add native clipboard and
+// install-referrer modules, and reads the clipboard when no URL is passed.
+async function trackDubOpen(
+ config: { domain: string; publishableKey: string },
+ deepLink: string,
+ signal: AbortSignal,
+): Promise<DubOpen> {
+ const response = await fetch('https://api.dub.co/track/open', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${config.publishableKey}`,
+ },
+ body: JSON.stringify({ dubDomain: config.domain, deepLink }),
+ signal,
+ });
+ if (!response.ok) throw new Error('We couldn’t check your link. Try again.');
+ return (await response.json()) as DubOpen;
+}
+
+// An explicit creator-code submission is the moment to ask, if iOS hasn't asked yet.
+export async function requestTrackingForCreatorCode(): Promise<void> {
+ if ((await getTrackingAuthorizationStatus()) !== 'notDetermined') return;
+ setAppsFlyerTrackingAuthorizationStatus(await requestTrackingAuthorization());
+}
+
+async function requireTrackingPermission(): Promise<void> {
+ const status = await getTrackingAuthorizationStatus();
+ if (status !== 'authorized' && status !== 'notSupported') throw new AffiliateConsentError();
+}
+
+export async function checkAndClaimAffiliate(
+ input: string,
+ clickId: string | null,
+ sessionCookie: string,
+ isCurrent: () => boolean,
+ rememberClick: (clickId: string) => Promise<void>,
+): Promise<AffiliateClaimStatus> {
+ const config = getAffiliateClientConfig();
+ if (!config) throw new Error('Creator links are not available yet.');
+ const link = parseAffiliateInput(input, config.domain).toString();
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10000);
+ const options = {
+ authenticated: false,
+ headers: { Cookie: sessionCookie },
+ signal: controller.signal,
+ };
+ const assertCurrent = () => {
+ if (!isCurrent() || controller.signal.aborted)
+ throw new Error('Referral check interrupted. Try again.');
+ };
+ const bounded = async <T>(work: Promise<T>): Promise<T> => {
+ assertCurrent();
+ let rejectAborted: () => void = () => {};
+ const aborted = new Promise<never>((_, reject) => {
+ rejectAborted = () => reject(new Error('Referral check interrupted. Try again.'));
+ controller.signal.addEventListener('abort', rejectAborted, { once: true });
+ });
+ return Promise.race([work, aborted]).finally(() => {
+ controller.signal.removeEventListener('abort', rejectAborted);
+ });
+ };
+ try {
+ await bounded(requireTrackingPermission());
+ assertCurrent();
+ await bounded(api.post('/api/affiliate/check-link', { link }, options));
+ assertCurrent();
+ if (!clickId) {
+ await bounded(requireTrackingPermission());
+ assertCurrent();
+ const result = await bounded(trackDubOpen(config, link, controller.signal));
+ assertCurrent();
+ if (
+ !result.clickId ||
+ !/^[A-Za-z0-9_-]{1,128}$/.test(result.clickId) ||
+ result.link?.domain !== config.domain ||
+ `/${result.link.key}` !== new URL(link).pathname
+ ) {
+ throw new Error('We couldn’t check your link. Try again.');
+ }
+ clickId = result.clickId;
+ await bounded(rememberClick(clickId));
+ assertCurrent();
+ }
+ await bounded(requireTrackingPermission());
+ assertCurrent();
+ const result = await bounded(
+ api.post<{ data: { status: AffiliateClaimStatus; persisted: true } }>(
+ '/api/affiliate/claim',
+ { link, clickId, source: 'mobile' },
+ options,
+ ),
+ );
+ // The server has acted on the claim by now, so report its answer even if the
+ // caller moved on; the store decides whether that answer still belongs to it.
+ if (
+ !result.data?.persisted ||
+ !['provisional', 'pending', 'registered', 'review'].includes(result.data.status)
+ ) {
+ throw new Error('We couldn’t save your link. Try again.');
+ }
+ return result.data.status;
+ } finally {
+ clearTimeout(timeout);
+ }
+}
diff --git a/openwhispr-mobile/src/lib/affiliateLink.ts b/openwhispr-mobile/src/lib/affiliateLink.ts
new file mode 100644
index 000000000..bd31bf9db
--- /dev/null
+++ b/openwhispr-mobile/src/lib/affiliateLink.ts
@@ -0,0 +1,93 @@
+import Constants from 'expo-constants';
+import { Platform } from 'react-native';
+
+export function getAffiliateClientConfig(): { domain: string; publishableKey: string } | null {
+ if (Platform.OS !== 'ios') return null;
+ const config = Constants.expoConfig?.extra?.affiliate;
+ if (
+ !config ||
+ typeof config.domain !== 'string' ||
+ !/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/.test(config.domain) ||
+ typeof config.publishableKey !== 'string' ||
+ !config.publishableKey.startsWith('dub_pk_')
+ )
+ return null;
+ return { domain: config.domain, publishableKey: config.publishableKey };
+}
+
+export class AffiliateInputError extends Error {
+ constructor() {
+ super('Enter a valid OpenWhispr creator link.');
+ }
+}
+
+export function parseAffiliateLink(input: string, domain: string): URL {
+ const value = input.trim();
+ if (!value || value.length > 2048) throw new AffiliateInputError();
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new AffiliateInputError();
+ }
+ if (
+ url.protocol !== 'https:' ||
+ url.hostname !== domain ||
+ url.port ||
+ url.username ||
+ url.password ||
+ !/^\/[A-Za-z0-9_-]+$/.test(url.pathname)
+ ) {
+ throw new AffiliateInputError();
+ }
+ return url;
+}
+
+// Short entry is an exact lowercase key, not case folding of a creator identity.
+// Full links preserve their original key case and strict trusted-domain checks.
+export function parseAffiliateInput(input: string, domain: string): URL {
+ const value = input.trim();
+ if (/^[a-z0-9][a-z0-9_-]{0,63}$/.test(value)) {
+ return parseAffiliateLink(`https://${domain}/${value}`, domain);
+ }
+ return parseAffiliateLink(value, domain);
+}
+
+// Native routing can run before auth/config hydration. Keep that explicit arrival
+// until the root hook can bind it to the correct session; never navigate to its destination.
+let arrival: string | null = null;
+let arrivedAt = 0;
+export function captureAffiliateArrival(value: string): boolean {
+ const config = getAffiliateClientConfig();
+ if (!config) return false;
+ try {
+ const url = new URL(value.trim());
+ // Share sheets can append a slash to a short link.
+ url.pathname = url.pathname.replace(/^(\/[^/]+)\/$/, '$1');
+ arrival = parseAffiliateLink(url.toString(), config.domain).toString();
+ arrivedAt = Date.now();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// The creator domain has no app screens, so none of its links may open as a route.
+export function isAffiliateDomainLink(value: string): boolean {
+ const config = getAffiliateClientConfig();
+ if (!config) return false;
+ try {
+ return new URL(value).hostname === config.domain;
+ } catch {
+ return false;
+ }
+}
+export function consumeAffiliateArrival(): string | null {
+ const value = arrival;
+ arrival = null;
+ return value;
+}
+export function isAffiliateArrivalFresh(): boolean {
+ const age = Date.now() - arrivedAt;
+ return arrivedAt > 0 && age >= 0 && age < 5000;
+}
diff --git a/openwhispr-mobile/src/lib/affiliateOffer.ts b/openwhispr-mobile/src/lib/affiliateOffer.ts
new file mode 100644
index 000000000..c781c8a2a
--- /dev/null
+++ b/openwhispr-mobile/src/lib/affiliateOffer.ts
@@ -0,0 +1,118 @@
+import { Platform } from 'react-native';
+import Purchases from 'react-native-purchases';
+import { api } from './apiClient';
+import { getAffiliateClientConfig } from './affiliateLink';
+import { getAppStorefrontCountryCode } from './revenuecat';
+import { useConfigStore } from '@/store/useConfigStore';
+import { isUsageAnalyticsAllowed } from './usageAnalytics';
+import { getTrackingAuthorizationStatus } from './trackingTransparency';
+import { useUsageStore } from '@/store/useUsageStore';
+import { getBillingIdentity, isBillingIdentityCurrent } from './billingIdentity';
+
+export interface AffiliateOffer {
+ campaign: string;
+ productId: string;
+ country: string;
+ currency: string;
+ regularPrice: number;
+ offerPrice: number;
+ months: 3;
+ redemptionUrl: string;
+ expiresAt: string;
+}
+export function validAffiliateOffer(value: unknown, country: string): value is AffiliateOffer {
+ if (!value || typeof value !== 'object') return false;
+ const v = value as AffiliateOffer;
+ try {
+ const url = new URL(v.redemptionUrl);
+ const digits =
+ new Intl.NumberFormat('en', { style: 'currency', currency: v.currency }).resolvedOptions()
+ .maximumFractionDigits ?? 2;
+ return (
+ typeof v.campaign === 'string' &&
+ typeof v.productId === 'string' &&
+ v.country === country &&
+ /^[A-Z]{3}$/.test(v.currency) &&
+ v.months === 3 &&
+ Number.isFinite(v.regularPrice) &&
+ v.regularPrice > 0 &&
+ Number.isFinite(v.offerPrice) &&
+ Math.abs(v.offerPrice * 10 ** digits - Math.round(v.regularPrice * 10 ** digits * 0.8)) <
+ 0.000001 &&
+ Date.parse(v.expiresAt) > Date.now() &&
+ url.protocol === 'https:' &&
+ url.hostname === 'apps.apple.com' &&
+ !url.username &&
+ !url.password &&
+ !url.port &&
+ url.pathname === '/redeem' &&
+ url.searchParams.get('ctx') === 'offercodes' &&
+ /^\d+$/.test(url.searchParams.get('id') ?? '') &&
+ /^[A-Za-z0-9]+$/.test(url.searchParams.get('code') ?? '')
+ );
+ } catch {
+ return false;
+ }
+}
+export async function loadAffiliateOffer(
+ isCallerCurrent: () => boolean = () => true,
+): Promise<AffiliateOffer | null> {
+ if (Platform.OS !== 'ios' || !getAffiliateClientConfig() || !isCallerCurrent()) return null;
+ const identity = getBillingIdentity();
+ if (!identity || useUsageStore.getState().usage?.isSubscribed) return null;
+ const { sessionCookie, billingUserId } = identity;
+ const current = () =>
+ isCallerCurrent() &&
+ isUsageAnalyticsAllowed(useConfigStore.getState().config) &&
+ isBillingIdentityCurrent(identity) &&
+ !useUsageStore.getState().usage?.isSubscribed;
+ let timer: ReturnType<typeof setTimeout>;
+ const controller = new AbortController();
+ const timeout = new Promise<null>((resolve) => {
+ timer = setTimeout(() => {
+ controller.abort();
+ resolve(null);
+ }, 8000);
+ });
+ const permitted = async () => {
+ const status = await getTrackingAuthorizationStatus();
+ return (
+ current() &&
+ !controller.signal.aborted &&
+ (status === 'authorized' || status === 'notSupported')
+ );
+ };
+ const work = (async () => {
+ if (!(await permitted())) return null;
+ const country = await getAppStorefrontCountryCode();
+ if (
+ !country ||
+ !current() ||
+ controller.signal.aborted ||
+ (await Purchases.getAppUserID()) !== billingUserId
+ )
+ return null;
+ if (!(await permitted())) return null;
+ const result = await api.post<{ data: unknown }>(
+ '/api/affiliate/apple-offer',
+ { country },
+ { authenticated: false, headers: { Cookie: sessionCookie }, signal: controller.signal },
+ );
+ if (!current() || controller.signal.aborted || !validAffiliateOffer(result.data, country))
+ return null;
+ const offer = result.data;
+ const products = await Purchases.getProducts([offer.productId]);
+ const product = products.find((p) => p.identifier === offer.productId);
+ if (
+ !current() ||
+ controller.signal.aborted ||
+ !product ||
+ product.currencyCode !== offer.currency ||
+ Math.abs(product.price - offer.regularPrice) > 0.000001 ||
+ product.subscriptionPeriod !== 'P1M'
+ )
+ return null;
+ return (await permitted()) && validAffiliateOffer(offer, country) ? offer : null;
+ })().catch(() => null);
+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
+}
diff --git a/openwhispr-mobile/src/lib/affiliatePaywall.ts b/openwhispr-mobile/src/lib/affiliatePaywall.ts
new file mode 100644
index 000000000..58053453f
--- /dev/null
+++ b/openwhispr-mobile/src/lib/affiliatePaywall.ts
@@ -0,0 +1,282 @@
+import { AppState, Linking } from 'react-native';
+import Purchases from 'react-native-purchases';
+import type { CustomCallback, CustomCallbackResult } from 'expo-superwall';
+import { requestTrackingForCreatorCode } from './affiliateAttribution';
+import { getAffiliateClientConfig, parseAffiliateInput } from './affiliateLink';
+import { loadAffiliateOffer, validAffiliateOffer, type AffiliateOffer } from './affiliateOffer';
+import { getBillingIdentity, isBillingIdentityCurrent } from './billingIdentity';
+import { getTrackingAuthorizationStatus } from './trackingTransparency';
+import { getAppStorefrontCountryCode } from './revenuecat';
+import { reconcileStoreBilling } from './billingReconciliation';
+import { isUsageAnalyticsAllowed } from './usageAnalytics';
+import { useAuthStore } from '@/store/useAuthStore';
+import { useAffiliateStore } from '@/store/useAffiliateStore';
+import { useConfigStore } from '@/store/useConfigStore';
+import { useUsageStore } from '@/store/useUsageStore';
+
+// Superwall callback variables are flat dictionary keys,
+// including their dots, not nested objects. Keep in sync with the paywall.
+export const CREATOR_INPUT_KEY = 'node.o9Et2gOJEgdSPj0nV1CkE.value';
+export const CREATOR_PLAN_KEY = 'products.selectedIndex';
+export const CREATOR_PRODUCT_KEY = 'products.secondary.identifier';
+export const CREATOR_TOKEN_KEY = 'callbacks.creatorCodeApply.data.offerToken';
+const PRICE_KEY = 'callbacks.creatorCodeApply.data.priceText';
+const RENEWAL_KEY = 'callbacks.creatorCodeApply.data.renewalText';
+const REQUEST_TIMEOUT_MS = 20_000;
+// RevenueCat and the backend can take a few seconds to see an offer-code purchase.
+const REDEMPTION_CHECK_DELAYS_MS = [0, 2_000, 5_000];
+let nextPresentation = 0;
+const failure = (
+ message = 'We couldn’t check this code. Try again, or use the regular plan.',
+): CustomCallbackResult => ({
+ status: 'failure',
+ data: { message },
+});
+
+export function formatAffiliateOffer(offer: AffiliateOffer) {
+ const money = (amount: number) =>
+ new Intl.NumberFormat(undefined, { style: 'currency', currency: offer.currency }).format(
+ amount,
+ );
+ return {
+ priceText: money(offer.offerPrice),
+ renewalText: `For your first 3 monthly payments, then ${money(offer.regularPrice)}/month.`,
+ };
+}
+
+/**
+ * One native presentation owns one private offer. Never return the Apple URL or code.
+ * Apple redeems the offer outside Superwall, so a confirmed redemption is reported
+ * through `onRedeemed` rather than as a Superwall purchase.
+ */
+export function createAffiliatePaywallSession(
+ isPresented: () => boolean,
+ onRedeemed: (productId: string) => void,
+ initialOffer?: AffiliateOffer,
+) {
+ const openingAuth = useAuthStore.getState();
+ const openingUserId = openingAuth.user?.id;
+ const openingCookie = openingAuth.sessionCookie;
+ let identity = getBillingIdentity();
+ let offerToken = `creator-${Date.now()}-${++nextPresentation}`;
+ let active = true;
+ let generation = 0;
+ let busy = false;
+ let offer: AffiliateOffer | null =
+ initialOffer && identity && validAffiliateOffer(initialOffer, initialOffer.country)
+ ? initialOffer
+ : null;
+ const initialDisplay = offer && formatAffiliateOffer(offer);
+ const initialParams = initialDisplay
+ ? {
+ creator_offer_ready: true,
+ creator_offer_price: initialDisplay.priceText,
+ creator_offer_renewal: initialDisplay.renewalText,
+ creator_offer_token: offerToken,
+ }
+ : {
+ // Superwall can retain omitted placement parameters on cached reuse.
+ creator_offer_ready: false,
+ creator_offer_price: '',
+ creator_offer_renewal: '',
+ creator_offer_token: '',
+ };
+ let billing = false;
+ let leftApp = false;
+ let handoffPending = false;
+ let redeemingProductId: string | null = null;
+ const alive = () => {
+ const auth = useAuthStore.getState();
+ if (
+ !active ||
+ !isPresented() ||
+ auth.user?.id !== openingUserId ||
+ auth.sessionCookie !== openingCookie
+ )
+ return false;
+ // Usage can finish loading after anonymous onboarding presents its paywall.
+ // Bind billing ownership once, without ever rebinding the opening account.
+ identity ??= getBillingIdentity();
+ return identity !== null && isBillingIdentityCurrent(identity);
+ };
+ const eligible = () =>
+ alive() &&
+ !useUsageStore.getState().usage?.isSubscribed &&
+ isUsageAnalyticsAllowed(useConfigStore.getState().config);
+ const permission = async () => {
+ const status = await getTrackingAuthorizationStatus();
+ return eligible() && (status === 'authorized' || status === 'notSupported');
+ };
+ // Keeps Use code locked until the purchase is confirmed or the checks run out,
+ // so a single-use code that was already redeemed can't be opened again.
+ const confirmRedemption = async (productId: string) => {
+ try {
+ for (const delay of REDEMPTION_CHECK_DELAYS_MS) {
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
+ if (!alive()) return;
+ await reconcileStoreBilling().catch(() => {
+ /* Ordinary restore/reconciliation remains available on a later visit. */
+ });
+ if (!alive()) return;
+ await useUsageStore.getState().load(true);
+ if (alive() && useUsageStore.getState().usage?.isSubscribed) {
+ onRedeemed(productId);
+ return;
+ }
+ }
+ } finally {
+ handoffPending = false;
+ }
+ };
+ const subscription = AppState.addEventListener('change', (state) => {
+ if (!billing || !alive()) return;
+ if (state === 'background') leftApp = true;
+ if (state !== 'active' || !leftApp || !redeemingProductId) return;
+ leftApp = false;
+ const productId = redeemingProductId;
+ redeemingProductId = null;
+ confirmRedemption(productId).catch(() => {});
+ });
+ const close = () => {
+ active = false;
+ generation += 1;
+ offer = null;
+ subscription.remove();
+ if (billing) {
+ billing = false;
+ useUsageStore.getState().endBillingSession();
+ }
+ };
+ const handle = async (callback: CustomCallback): Promise<CustomCallbackResult> => {
+ const variables = callback.variables;
+ if (
+ !eligible() ||
+ !getAffiliateClientConfig() ||
+ busy ||
+ !variables ||
+ variables[CREATOR_PLAN_KEY] !== 1 ||
+ typeof variables[CREATOR_PRODUCT_KEY] !== 'string' ||
+ !variables[CREATOR_PRODUCT_KEY]
+ )
+ return failure();
+ if (callback.name !== 'creatorCodeApply' && callback.name !== 'creatorOfferRedeem')
+ return failure();
+ if (callback.name === 'creatorOfferRedeem' && handoffPending)
+ return failure('We’re still checking your purchase. Try again in a moment.');
+ busy = true;
+ const version = ++generation;
+ const current = () => eligible() && generation === version;
+ let timer: ReturnType<typeof setTimeout>;
+ const work = async (): Promise<CustomCallbackResult> => {
+ if (
+ callback.name === 'creatorCodeApply' &&
+ isUsageAnalyticsAllowed(useConfigStore.getState().config)
+ )
+ await requestTrackingForCreatorCode();
+ if (!(await permission()) || !current())
+ return failure(
+ 'Creator codes are unavailable with your current tracking settings. You can use the regular plan.',
+ );
+ if (callback.name === 'creatorCodeApply') {
+ // A refused apply keeps the offer already on screen redeemable.
+ const input = variables[CREATOR_INPUT_KEY];
+ const config = getAffiliateClientConfig();
+ if (typeof input !== 'string' || input.length > 2048 || !config) return failure();
+ const key = parseAffiliateInput(input, config.domain).pathname;
+ await useAffiliateStore.getState().hydrate();
+ await useAffiliateStore.getState().bindSession();
+ if (!current()) return failure();
+ const saved = useAffiliateStore.getState();
+ if (saved.checking) return failure();
+ if (saved.saved && parseAffiliateInput(saved.link, config.domain).pathname !== key)
+ return failure('Your first creator is already saved and can’t be changed.');
+ if (!saved.saved) await saved.edit(input);
+ if (
+ !current() ||
+ parseAffiliateInput(useAffiliateStore.getState().link, config.domain).pathname !== key
+ )
+ return failure();
+ if (
+ !(await useAffiliateStore.getState().prepare(current)) ||
+ !current() ||
+ !useAffiliateStore.getState().saved
+ )
+ return failure();
+ const loaded = await loadAffiliateOffer(current);
+ if (
+ !loaded ||
+ !(await permission()) ||
+ !current() ||
+ !validAffiliateOffer(loaded, loaded.country) ||
+ loaded.productId !== variables[CREATOR_PRODUCT_KEY]
+ )
+ return failure(
+ 'Your creator is saved, but a monthly offer isn’t available now. You can use the regular plan.',
+ );
+ offer = loaded;
+ offerToken = `creator-${Date.now()}-${++nextPresentation}`;
+ return { status: 'success', data: { ...formatAffiliateOffer(loaded), offerToken } };
+ }
+ const held = offer;
+ const shownToken = variables[CREATOR_TOKEN_KEY] || variables['params.creator_offer_token'];
+ const shownPrice = variables[PRICE_KEY] || variables['params.creator_offer_price'];
+ const shownRenewal = variables[RENEWAL_KEY] || variables['params.creator_offer_renewal'];
+ if (!held || shownToken !== offerToken || variables[CREATOR_PRODUCT_KEY] !== held.productId)
+ return failure();
+ const display = formatAffiliateOffer(held);
+ if (shownPrice !== display.priceText || shownRenewal !== display.renewalText)
+ return failure();
+ const country = await getAppStorefrontCountryCode();
+ if (
+ !current() ||
+ !country ||
+ !validAffiliateOffer(held, country) ||
+ (await Purchases.getAppUserID()) !== identity?.billingUserId
+ )
+ return failure();
+ const products = await Purchases.getProducts([held.productId]);
+ const product = products.find((item) => item.identifier === held.productId);
+ if (
+ !current() ||
+ !product ||
+ product.subscriptionPeriod !== 'P1M' ||
+ product.currencyCode !== held.currency ||
+ Math.abs(product.price - held.regularPrice) > 0.000001 ||
+ !(await permission()) ||
+ !current() ||
+ Date.parse(held.expiresAt) <= Date.now()
+ )
+ return failure();
+ // RootLayout consumes the resume guard after each Apple return.
+ useUsageStore.getState().beginBillingSession();
+ billing = true;
+ handoffPending = true;
+ redeemingProductId = held.productId;
+ try {
+ await Linking.openURL(held.redemptionUrl);
+ } catch (error) {
+ handoffPending = false;
+ redeemingProductId = null;
+ throw error;
+ }
+ return current() ? { status: 'success' } : failure();
+ };
+ const timeout = new Promise<CustomCallbackResult>((resolve) => {
+ timer = setTimeout(() => {
+ // The offer already on screen stays redeemable; only this request is abandoned.
+ if (generation === version) {
+ generation += 1;
+ busy = false;
+ }
+ resolve(failure());
+ }, REQUEST_TIMEOUT_MS);
+ });
+ try {
+ return await Promise.race([work().catch(() => failure()), timeout]);
+ } finally {
+ clearTimeout(timer!);
+ if (generation === version) busy = false;
+ }
+ };
+ return { handle, close, initialParams };
+}
diff --git a/openwhispr-mobile/src/lib/appResume.ts b/openwhispr-mobile/src/lib/appResume.ts
index 05682ddc9..e1d6d7706 100644
--- a/openwhispr-mobile/src/lib/appResume.ts
+++ b/openwhispr-mobile/src/lib/appResume.ts
@@ -2,6 +2,7 @@ import { useGoogleCalendarStore } from '@/store/useGoogleCalendarStore';
import { useHandoffStore } from '@/store/useHandoffStore';
import { isRecoveryDeepLinkFresh, isRecoveryHolding } from '@/store/useKeyboardRecoveryStore';
import { useUsageStore } from '@/store/useUsageStore';
+import { isAffiliateArrivalFresh } from './affiliateLink';
export interface ResumeDecision {
/** Reset the stack to Home — the default for a warm resume. */
@@ -43,6 +44,9 @@ export function resolveResumeAction(alreadyOnHome: boolean): ResumeDecision {
return { resetToHome: false, refreshUsage: true };
}
+ // A creator link just arrived: the app opened for it, so leave the screen alone.
+ if (isAffiliateArrivalFresh()) return STAY;
+
// Already on Home → skip the redundant replace that would slide Home over itself.
return { resetToHome: !alreadyOnHome, refreshUsage: false };
}
diff --git a/openwhispr-mobile/src/lib/billingIdentity.ts b/openwhispr-mobile/src/lib/billingIdentity.ts
new file mode 100644
index 000000000..8aed16311
--- /dev/null
+++ b/openwhispr-mobile/src/lib/billingIdentity.ts
@@ -0,0 +1,25 @@
+import { useAuthStore } from '@/store/useAuthStore';
+import { useUsageStore } from '@/store/useUsageStore';
+
+export interface BillingIdentity {
+ userId: string;
+ sessionCookie: string;
+ billingUserId: string;
+}
+
+export function getBillingIdentity(): BillingIdentity | null {
+ const { user, sessionCookie } = useAuthStore.getState();
+ const billingUserId = useUsageStore.getState().usage?.billingUserId;
+ return user && sessionCookie && billingUserId
+ ? { userId: user.id, sessionCookie, billingUserId }
+ : null;
+}
+
+export function isBillingIdentityCurrent(identity: BillingIdentity): boolean {
+ const current = getBillingIdentity();
+ return (
+ current?.userId === identity.userId &&
+ current.sessionCookie === identity.sessionCookie &&
+ current.billingUserId === identity.billingUserId
+ );
+}
diff --git a/openwhispr-mobile/src/lib/billingReconciliation.ts b/openwhispr-mobile/src/lib/billingReconciliation.ts
index 6c9e4f658..c9ee84f1b 100644
--- a/openwhispr-mobile/src/lib/billingReconciliation.ts
+++ b/openwhispr-mobile/src/lib/billingReconciliation.ts
@@ -1,11 +1,15 @@
import { Platform } from 'react-native';
import type { UsageInfo } from '@/data/remote/usageApi';
-import { useUsageStore } from '@/store/useUsageStore';
+import {
+ getBillingIdentity,
+ isBillingIdentityCurrent,
+ type BillingIdentity,
+} from './billingIdentity';
-let inFlight: Promise<UsageInfo> | null = null;
+let inFlight: { identity: BillingIdentity; promise: Promise<UsageInfo> } | null = null;
export function reconcileStoreBilling(): Promise<UsageInfo> {
- if (inFlight) return inFlight;
+ if (inFlight && isBillingIdentityCurrent(inFlight.identity)) return inFlight.promise;
if (Platform.OS !== 'ios' && Platform.OS !== 'android') {
return Promise.reject(
@@ -14,29 +18,34 @@ export function reconcileStoreBilling(): Promise<UsageInfo> {
}
const platform = Platform.OS;
- const billingUserId = useUsageStore.getState().usage?.billingUserId;
- if (!billingUserId) {
+ const identity = getBillingIdentity();
+ if (!identity) {
return Promise.reject(new Error('Billing identity is unavailable'));
}
- inFlight = performReconciliation(billingUserId, platform).finally(() => {
- inFlight = null;
+ const promise = performReconciliation(identity, platform).finally(() => {
+ if (inFlight?.promise === promise) inFlight = null;
});
- return inFlight;
+ inFlight = { identity, promise };
+ return promise;
}
async function performReconciliation(
- billingUserId: string,
+ identity: BillingIdentity,
platform: 'ios' | 'android',
): Promise<UsageInfo> {
// Load the native billing path only when reconciliation actually runs. This
// keeps screens that merely import a usage gate independent of native SDKs.
- const [{ reconcileMobileBilling }, { identifyRevenueCatUser, syncRevenueCatPurchases }] =
- await Promise.all([import('@/data/remote/billingApi'), import('@/lib/revenuecat')]);
+ const { reconcileMobileBilling } =
+ require('@/data/remote/billingApi') as typeof import('@/data/remote/billingApi');
+ const { reconcileRevenueCatPurchases } =
+ require('@/lib/revenuecat') as typeof import('@/lib/revenuecat');
- const identified = await identifyRevenueCatUser(billingUserId);
- if (!identified) throw new Error('RevenueCat identity is unavailable');
- const synced = await syncRevenueCatPurchases();
+ const current = () => isBillingIdentityCurrent(identity);
+ const synced = await reconcileRevenueCatPurchases(identity.billingUserId, current);
if (!synced) throw new Error('RevenueCat purchase sync is unavailable');
- return reconcileMobileBilling(platform);
+ if (!current()) throw new Error('Billing account changed');
+ const usage = await reconcileMobileBilling(platform, identity.sessionCookie);
+ if (!current()) throw new Error('Billing account changed');
+ return usage;
}
diff --git a/openwhispr-mobile/src/lib/revenuecat.ts b/openwhispr-mobile/src/lib/revenuecat.ts
index 63c38f7ba..83d575e3c 100644
--- a/openwhispr-mobile/src/lib/revenuecat.ts
+++ b/openwhispr-mobile/src/lib/revenuecat.ts
@@ -7,6 +7,40 @@ import Purchases, {
import { Sentry } from '@/lib/sentry';
let configured = false;
+let identityQueue: Promise<unknown> = Promise.resolve();
+
+const IDENTITY_CALL_TIMEOUT_MS = 10_000;
+// Restoring purchases can take far longer than a login on a slow network or a
+// long purchase history, and reconciliation must not give up on it early.
+const PURCHASE_SYNC_TIMEOUT_MS = 60_000;
+// Longer than any one call's deadline, so ordinary queueing behind a sync never fails.
+const IDENTITY_QUEUE_WAIT_MS = 90_000;
+
+// Identity changes run one at a time and in order, so the last login or logout
+// always wins; queued work is never skipped. A call's own deadline starts when it
+// runs, so ordinary queueing never fails it, and a separate cap on the wait
+// releases callers stuck behind a native call that never settles. Native calls
+// cannot be cancelled: a released call still runs, and holds the lock until it
+// settles.
+function withIdentity<T>(
+ operation: () => Promise<T>,
+ timeoutMs = IDENTITY_CALL_TIMEOUT_MS,
+): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const tooLong = () => reject(new Error('RevenueCat identity call timed out'));
+ const waiting = setTimeout(tooLong, IDENTITY_QUEUE_WAIT_MS);
+ const run = () => {
+ clearTimeout(waiting);
+ const timer = setTimeout(tooLong, timeoutMs);
+ const work = Promise.resolve()
+ .then(operation)
+ .finally(() => clearTimeout(timer));
+ work.then(resolve, reject);
+ return work;
+ };
+ identityQueue = identityQueue.then(run).catch(() => {});
+ });
+}
function getRevenueCatApiKey(): string | undefined {
const key =
@@ -49,7 +83,7 @@ export async function identifyRevenueCatUser(userId: string): Promise<boolean> {
if (!configured) configureRevenueCat();
if (!configured) return false;
try {
- await Purchases.logIn(userId);
+ await withIdentity(() => Purchases.logIn(userId));
return true;
} catch (error) {
reportRevenueCatError('identify', error);
@@ -60,20 +94,30 @@ export async function identifyRevenueCatUser(userId: string): Promise<boolean> {
export async function resetRevenueCatUser(): Promise<void> {
if (!configured) return;
try {
- await Purchases.logOut();
+ await withIdentity(() => Purchases.logOut());
} catch (error) {
reportRevenueCatError('reset', error);
}
}
-export async function syncRevenueCatPurchases(): Promise<boolean> {
+// Keep the login and sync together: a sign-out or another account's login must
+// not change the SDK owner halfway through restoring a purchase.
+export async function reconcileRevenueCatPurchases(
+ billingUserId: string,
+ isCurrent: () => boolean,
+): Promise<boolean> {
if (!configured) configureRevenueCat();
if (!configured) return false;
try {
- await Purchases.syncPurchasesForResult();
- return true;
+ return await withIdentity(async () => {
+ if (!isCurrent()) return false;
+ await Purchases.logIn(billingUserId);
+ if (!isCurrent()) return false;
+ await Purchases.syncPurchasesForResult();
+ return isCurrent();
+ }, PURCHASE_SYNC_TIMEOUT_MS);
} catch (error) {
- reportRevenueCatError('sync-purchases', error);
+ reportRevenueCatError('reconcile-purchases', error);
return false;
}
}
@@ -87,7 +131,7 @@ export async function recordRevenueCatPurchase(productId: string): Promise<boole
if (!configured) configureRevenueCat();
if (!configured) return false;
try {
- await Purchases.recordPurchase(productId);
+ await withIdentity(() => Purchases.recordPurchase(productId));
return true;
} catch (error) {
reportRevenueCatError('record-purchase', error);
diff --git a/openwhispr-mobile/src/lib/sentry.ts b/openwhispr-mobile/src/lib/sentry.ts
index a2714b5f0..f3cbcd97a 100644
--- a/openwhispr-mobile/src/lib/sentry.ts
+++ b/openwhispr-mobile/src/lib/sentry.ts
@@ -1,5 +1,6 @@
import * as Sentry from '@sentry/react-native';
import { useConfigStore } from '@/store/useConfigStore';
+import { isUsageAnalyticsAllowed } from '@/lib/usageAnalytics';
let didInit = false;
let watchingConsent = false;
@@ -9,8 +10,7 @@ let closing: Promise<void> | null = null;
// fails closed until then. Once loaded, the saved preference (default on) is
// authoritative — including while a later save is in flight.
function analyticsEnabled(): boolean {
- const { config } = useConfigStore.getState();
- return config !== null && (config.usageAnalyticsEnabled ?? true);
+ return isUsageAnalyticsAllowed(useConfigStore.getState().config);
}
function syncConsent(): void {
diff --git a/openwhispr-mobile/src/lib/superwall.ts b/openwhispr-mobile/src/lib/superwall.ts
index 15d6605be..043cae8f8 100644
--- a/openwhispr-mobile/src/lib/superwall.ts
+++ b/openwhispr-mobile/src/lib/superwall.ts
@@ -2,6 +2,7 @@ import Constants from 'expo-constants';
import type { SubscriptionStatus } from 'expo-superwall';
import type { UsageInfo } from '@/data/remote/usageApi';
import type { ProcessingMode } from '@/types';
+import { getAffiliateClientConfig } from './affiliateLink';
export const SUPERWALL_APP_ENTITLEMENT_ID = 'pro';
export const SUPERWALL_WORDS_REMAINING_SENTINEL = 1_000_000_000;
@@ -23,6 +24,21 @@ export const SUPERWALL_PLACEMENTS = {
export type SuperwallPlacement = (typeof SUPERWALL_PLACEMENTS)[keyof typeof SUPERWALL_PLACEMENTS];
+// The paywall with the creator-code input has its own Superwall placement, so a
+// build without creator codes never shows it. It is only the name sent to
+// Superwall: the gate keeps the rules of the surface that opened it.
+export const CREATOR_CODE_PAYWALL_PLACEMENT = 'creator_code_paywall';
+
+export function resolveSuperwallPlacementName(
+ placement: SuperwallPlacement,
+ hasCreatorOffer: boolean,
+): string {
+ return getAffiliateClientConfig() &&
+ (hasCreatorOffer || placement === SUPERWALL_PLACEMENTS.onboardingPaywall)
+ ? CREATOR_CODE_PAYWALL_PLACEMENT
+ : placement;
+}
+
// Transactional placements require an account and fail closed. onboardingPaywall
// is deliberately absent from both: it must never bounce to sign-in (the account
// step comes after it) and must let the user through if Superwall is missing,
diff --git a/openwhispr-mobile/src/lib/usageAnalytics.ts b/openwhispr-mobile/src/lib/usageAnalytics.ts
new file mode 100644
index 000000000..922c85c1d
--- /dev/null
+++ b/openwhispr-mobile/src/lib/usageAnalytics.ts
@@ -0,0 +1,7 @@
+import type { UserConfig } from '@/types';
+
+// Usage Analytics defaults to on once the saved config has loaded. Before that
+// the preference is unknown, so callers fail closed.
+export function isUsageAnalyticsAllowed(config: UserConfig | null): boolean {
+ return config !== null && (config.usageAnalyticsEnabled ?? true);
+}
diff --git a/openwhispr-mobile/src/screens/AccountScreen.tsx b/openwhispr-mobile/src/screens/AccountScreen.tsx
index e2a58465f..6edd229f3 100644
--- a/openwhispr-mobile/src/screens/AccountScreen.tsx
+++ b/openwhispr-mobile/src/screens/AccountScreen.tsx
@@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useRef } from 'react';
import { Alert, Platform, View, Pressable } from 'react-native';
import { Text } from '@/components/ui/Text';
import Constants from 'expo-constants';
-import { router, useLocalSearchParams } from 'expo-router';
+import { router, useLocalSearchParams, useFocusEffect } from 'expo-router';
import { SettingsRow, SettingsSection } from '@/components/ui/SettingsSection';
import { SettingsScreen } from '@/components/ui/SettingsScreen';
import { PlanBadge } from '@/components/ui/PlanBadge';
@@ -24,6 +24,10 @@ import { safeHaptics } from '@/lib/utils';
import { iosColor } from '@/config/colors';
import { getAccountDisplay } from '@/lib/accountDisplay';
import { useSuperwallGate } from '@/hooks/useSuperwallGate';
+import { useAffiliateStore } from '@/store/useAffiliateStore';
+import { getAffiliateClientConfig } from '@/lib/affiliateLink';
+import { loadAffiliateOffer, type AffiliateOffer } from '@/lib/affiliateOffer';
+import { AccountCreatorLink, type CreatorOfferResult } from '@/components/AccountCreatorLink';
import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';
const MUTED_ICON_BG = iosColor('systemGray2');
@@ -115,7 +119,7 @@ async function openGrantedBillingManagement(usage: UsageInfo): Promise<void> {
export default function AccountScreen() {
const params = useLocalSearchParams<{ superwallPlacement?: string }>();
- const { user, isGuest, signOut, deleteAccount } = useAuthStore();
+ const { user, sessionCookie, isGuest, signOut, deleteAccount } = useAuthStore();
// An anonymous onboarding session: Sign Out would revoke it (and the notes
// and purchase it carries) and the API refuses to delete it, so the one
// account action it needs is creating the account.
@@ -123,8 +127,28 @@ export default function AccountScreen() {
const usage = useUsageStore((s) => s.usage);
const loadUsage = useUsageStore((s) => s.load);
const resetOnboarding = useOnboardingStore((state) => state.reset);
- const { register: registerSuperwallGate } = useSuperwallGate();
+ const { register: registerSuperwallGate, isConfigured: superwallConfigured } = useSuperwallGate();
const handledBillingIntentRef = useRef<string | null>(null);
+ const billingContextRef = useRef({
+ userId: user?.id,
+ sessionCookie,
+ active: true,
+ generation: 0,
+ });
+ billingContextRef.current.userId = user?.id;
+ billingContextRef.current.sessionCookie = sessionCookie;
+ const affiliatePendingRef = useRef(false);
+ const billingRegistrationRef = useRef<AbortController | null>(null);
+ useFocusEffect(
+ useCallback(() => {
+ billingContextRef.current.active = true;
+ return () => {
+ billingContextRef.current.active = false;
+ billingContextRef.current.generation += 1;
+ billingRegistrationRef.current?.abort();
+ };
+ }, []),
+ );
useEffect(() => {
if (user) loadUsage();
@@ -142,42 +166,92 @@ export default function AccountScreen() {
);
}, [signOut, user]);
- const handleBillingPress = useCallback(async (): Promise<void> => {
- let currentUsage = useUsageStore.getState().usage;
- if (user && !currentUsage) {
- const loadResult = await loadUsage(true);
- currentUsage = loadResult.usage ?? useUsageStore.getState().usage;
- if (!currentUsage) {
- Alert.alert("Couldn't Load Billing", 'Please try again in a moment.');
- return;
- }
- }
+ const handleBillingPress = useCallback(
+ async (intent: 'plans' | 'creator' = 'plans'): Promise<CreatorOfferResult> => {
+ if (affiliatePendingRef.current) return 'cancelled';
+ affiliatePendingRef.current = true;
+ try {
+ const context = { ...billingContextRef.current };
+ const isCurrent = () =>
+ billingContextRef.current.active &&
+ billingContextRef.current.generation === context.generation &&
+ useAuthStore.getState().user?.id === context.userId &&
+ useAuthStore.getState().sessionCookie === context.sessionCookie;
+ let currentUsage = useUsageStore.getState().usage;
+ if (user && !currentUsage) {
+ const loadResult = await loadUsage(true);
+ currentUsage = loadResult.usage ?? useUsageStore.getState().usage;
+ if (!isCurrent()) return 'cancelled';
+ if (!currentUsage) {
+ Alert.alert("Couldn't Load Billing", 'Please try again in a moment.');
+ return 'cancelled';
+ }
+ }
- const managementUsage = currentUsage;
+ const managementUsage = currentUsage;
+ if (
+ intent === 'creator' &&
+ (!currentUsage || currentUsage.isSubscribed || !useAffiliateStore.getState().link.trim())
+ )
+ return 'cancelled';
+ if (
+ !currentUsage?.isSubscribed &&
+ intent === 'creator' &&
+ !(await useAffiliateStore.getState().prepare(isCurrent))
+ )
+ return 'invalid';
+ if (!isCurrent()) return 'cancelled';
+ let creatorOffer: AffiliateOffer | undefined;
+ if (!currentUsage?.isSubscribed && intent === 'creator') {
+ // Allocating stock for a paywall that can't open would waste the offer.
+ if (!superwallConfigured) return 'unavailable';
+ creatorOffer = (await loadAffiliateOffer(isCurrent)) ?? undefined;
+ if (!isCurrent()) return 'cancelled';
+ if (!creatorOffer) return 'unavailable';
+ }
+ if (!isCurrent()) return 'cancelled';
- await registerSuperwallGate({
- placement: SUPERWALL_PLACEMENTS.accountBillingOpen,
- params: currentUsage
- ? {
- plan: currentUsage.plan,
- status: currentUsage.status,
- isSubscribed: currentUsage.isSubscribed,
- isTrial: currentUsage.isTrial,
- }
- : undefined,
- onAccessGrantedWithoutPurchase: managementUsage
- ? () => {
- openGrantedBillingManagement(managementUsage).catch(() => {});
- }
- : undefined,
- onPurchaseComplete: (completion) => {
- router.replace({
- pathname: '/(tabs)/(record)',
- params: { proCompletion: completion },
+ const registration = new AbortController();
+ billingRegistrationRef.current = registration;
+ let presented = false;
+ await registerSuperwallGate({
+ signal: registration.signal,
+ onPresent: () => {
+ presented = true;
+ },
+ placement: SUPERWALL_PLACEMENTS.accountBillingOpen,
+ creatorOffer,
+ requiresAccount: creatorOffer ? false : undefined,
+ params: currentUsage
+ ? {
+ plan: currentUsage.plan,
+ status: currentUsage.status,
+ isSubscribed: currentUsage.isSubscribed,
+ isTrial: currentUsage.isTrial,
+ }
+ : undefined,
+ onAccessGrantedWithoutPurchase:
+ managementUsage && !creatorOffer
+ ? () => {
+ openGrantedBillingManagement(managementUsage).catch(() => {});
+ }
+ : undefined,
+ onPurchaseComplete: (completion) => {
+ router.replace({
+ pathname: '/(tabs)/(record)',
+ params: { proCompletion: completion },
+ });
+ },
});
- },
- });
- }, [loadUsage, registerSuperwallGate, user]);
+ // A skipped or failed paywall never showed the offer, so keep the regular plans in reach.
+ if (!creatorOffer) return 'cancelled';
+ return presented ? 'shown' : 'unavailable';
+ } finally {
+ affiliatePendingRef.current = false;
+ }
+ },
+ [loadUsage, registerSuperwallGate, superwallConfigured, user],
+ );
useEffect(() => {
if (!user || params.superwallPlacement !== SUPERWALL_PLACEMENTS.accountBillingOpen) return;
@@ -199,7 +273,7 @@ export default function AccountScreen() {
title="Account"
left={<GlassBackButton fallbackRoute="/(tabs)/(record)" />}
/>
- <SettingsScreen>
+ <SettingsScreen automaticallyAdjustKeyboardInsets keyboardShouldPersistTaps="handled">
{(user || isGuest) && (
<Pressable
onPress={() => router.push('/(account)/profile')}
@@ -279,6 +353,15 @@ export default function AccountScreen() {
) : null}
<SettingsSection title="Subscription">
+ {user && usage && !usage.isSubscribed && getAffiliateClientConfig() ? (
+ <AccountCreatorLink
+ key={user.id}
+ onCheckOffer={() => handleBillingPress('creator')}
+ onViewPlans={() => {
+ handleBillingPress().catch(() => {});
+ }}
+ />
+ ) : null}
<SettingsRow
iconStyle="line"
icon="creditcard"
diff --git a/openwhispr-mobile/src/screens/__tests__/AccountScreen.anonymous.test.tsx b/openwhispr-mobile/src/screens/__tests__/AccountScreen.anonymous.test.tsx
index 727a52a97..843d04895 100644
--- a/openwhispr-mobile/src/screens/__tests__/AccountScreen.anonymous.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/AccountScreen.anonymous.test.tsx
@@ -1,3 +1,6 @@
+jest.mock('@/lib/affiliateOffer', () => ({
+ loadAffiliateOffer: jest.fn().mockResolvedValue(null),
+}));
import React from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react-native';
import { Alert } from 'react-native';
@@ -29,6 +32,11 @@ const mockAuthState: {
signOut: jest.fn(),
deleteAccount: jest.fn(),
};
+const mockPrepareAffiliate = jest.fn().mockResolvedValue(true);
+jest.mock('@/store/useAffiliateStore', () => ({
+ useAffiliateStore: { getState: () => ({ prepare: mockPrepareAffiliate }) },
+}));
+jest.mock('@/components/AccountCreatorLink', () => ({ AccountCreatorLink: () => null }));
const mockRegisterSuperwallGate = jest.fn();
const mockRouterReplace = jest.fn();
const mockCreateStripeBillingPortalSession = jest.fn();
@@ -86,6 +94,7 @@ const mockUsageStoreState: {
const mockRouterPush = jest.fn();
jest.mock('expo-router', () => ({
+ useFocusEffect: (effect: () => void) => require('react').useEffect(effect, [effect]),
router: {
push: (...args: unknown[]) => mockRouterPush(...args),
replace: (...args: unknown[]) => mockRouterReplace(...args),
@@ -180,6 +189,7 @@ const anonymousUser = {
// the API. What it needs is a way to create the account.
describe('AccountScreen with an anonymous session', () => {
beforeEach(() => {
+ mockPrepareAffiliate.mockResolvedValue(true);
jest.clearAllMocks();
mockAuthState.user = anonymousUser;
mockAuthState.sessionCookie = 'session-cookie';
diff --git a/openwhispr-mobile/src/screens/__tests__/AccountScreen.billing.test.tsx b/openwhispr-mobile/src/screens/__tests__/AccountScreen.billing.test.tsx
index 1761d4b3f..b78aa27bf 100644
--- a/openwhispr-mobile/src/screens/__tests__/AccountScreen.billing.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/AccountScreen.billing.test.tsx
@@ -1,5 +1,13 @@
+jest.mock('@/lib/affiliateOffer', () => ({ loadAffiliateOffer: jest.fn() }));
+let mockAffiliateConfig: { domain: string; publishableKey: string } | null = {
+ domain: 'sandbox.dub.link',
+ publishableKey: 'dub_pk_test',
+};
+jest.mock('@/lib/affiliateLink', () => ({ getAffiliateClientConfig: () => mockAffiliateConfig }));
+let mockSuperwallConfigured = true;
import React from 'react';
-import { fireEvent, render, waitFor } from '@testing-library/react-native';
+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+import { loadAffiliateOffer, type AffiliateOffer } from '@/lib/affiliateOffer';
import { Alert } from 'react-native';
import type { UsageInfo } from '@/data/remote/usageApi';
import { ApiError } from '@/lib/apiClient';
@@ -9,6 +17,7 @@ const mockUser = {
name: 'Test User',
emailVerified: true,
+ isAnonymous: false,
};
const mockAuthState: {
user: typeof mockUser | null;
@@ -23,6 +32,35 @@ const mockAuthState: {
signOut: jest.fn(),
deleteAccount: jest.fn(),
};
+const mockPrepareAffiliate = jest.fn().mockResolvedValue(true);
+jest.mock('@/store/useAffiliateStore', () => ({
+ useAffiliateStore: {
+ getState: () => ({ prepare: mockPrepareAffiliate, link: 'https://sandbox.dub.link/creator' }),
+ },
+}));
+jest.mock('@/components/AccountCreatorLink', () => ({
+ AccountCreatorLink: ({
+ onCheckOffer,
+ onViewPlans,
+ }: {
+ onCheckOffer: () => Promise<string>;
+ onViewPlans: () => void;
+ }) => {
+ const { Pressable, Text, View } = require('react-native');
+ const [result, setResult] = require('react').useState('');
+ return (
+ <View>
+ <Pressable onPress={() => onCheckOffer().then(setResult)}>
+ <Text>Submit creator link</Text>
+ </Pressable>
+ <Text testID="creator-result">{result}</Text>
+ <Pressable onPress={onViewPlans}>
+ <Text>View plans</Text>
+ </Pressable>
+ </View>
+ );
+ },
+}));
const mockRegisterSuperwallGate = jest.fn();
const mockRouterReplace = jest.fn();
const mockCreateStripeBillingPortalSession = jest.fn();
@@ -79,6 +117,7 @@ const mockUsageStoreState: {
};
jest.mock('expo-router', () => ({
+ useFocusEffect: (effect: () => void) => require('react').useEffect(effect, [effect]),
router: {
push: jest.fn(),
replace: (...args: unknown[]) => mockRouterReplace(...args),
@@ -101,7 +140,10 @@ jest.mock('@/store/useUsageStore', () => ({
),
}));
jest.mock('@/hooks/useSuperwallGate', () => ({
- useSuperwallGate: () => ({ register: mockRegisterSuperwallGate }),
+ useSuperwallGate: () => ({
+ register: mockRegisterSuperwallGate,
+ isConfigured: mockSuperwallConfigured,
+ }),
}));
jest.mock('@/data/remote/billingApi', () => ({
createStripeBillingPortalSession: (...args: unknown[]) =>
@@ -170,8 +212,20 @@ function getRegisteredGateOptions(): RegisteredGateOptions {
}
describe('AccountScreen billing management', () => {
+ it('opens ordinary plans without claiming a candidate or allocating an offer', async () => {
+ mockUsageStoreState.usage = mockUnsubscribedUsage;
+ mockPrepareAffiliate.mockResolvedValue(false);
+ const { getByText } = render(<AccountScreen />);
+ fireEvent.press(getByText('Plans & Billing'));
+ await waitFor(() => expect(mockRegisterSuperwallGate).toHaveBeenCalled());
+ expect(mockPrepareAffiliate).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ });
+
beforeEach(() => {
- jest.clearAllMocks();
+ jest.resetAllMocks();
+ mockPrepareAffiliate.mockResolvedValue(true);
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(null);
mockAuthState.user = mockUser;
mockAuthState.sessionCookie = 'session-cookie';
mockAuthState.isGuest = false;
@@ -200,6 +254,64 @@ describe('AccountScreen billing management', () => {
jest.restoreAllMocks();
});
+ it('discards a delayed creator check when Account is left', async () => {
+ mockUsageStoreState.usage = mockUnsubscribedUsage;
+ let resolve!: (value: boolean) => void;
+ mockPrepareAffiliate.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ screen.unmount();
+ await act(async () => {
+ resolve(true);
+ });
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
+ it('discards a delayed creator check when the authenticated session changes', async () => {
+ mockUsageStoreState.usage = mockUnsubscribedUsage;
+ let resolve!: (value: boolean) => void;
+ mockPrepareAffiliate.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ mockAuthState.sessionCookie = 'another-session';
+ await act(async () => {
+ resolve(true);
+ });
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
+ it('closes a pending offer on exit without opening a fallback paywall', async () => {
+ mockUsageStoreState.usage = mockUnsubscribedUsage;
+ let resolve!: (value: AffiliateOffer | null) => void;
+ jest.mocked(loadAffiliateOffer).mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(loadAffiliateOffer).toHaveBeenCalled());
+ screen.unmount();
+ expect(jest.mocked(loadAffiliateOffer).mock.calls[0][0]!()).toBe(false);
+ await act(async () => {
+ resolve(null);
+ });
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
it('opens Stripe management only for an authoritative US web subscriber', async () => {
const { getByText } = render(<AccountScreen />);
@@ -511,3 +623,136 @@ describe('AccountScreen billing management', () => {
await waitFor(() => expect(mockGetAppStorefrontCountryCode).toHaveBeenCalled());
});
});
+
+describe('Account creator offer intent', () => {
+ beforeEach(() => {
+ jest.resetAllMocks();
+ mockAuthState.user = mockUser;
+ mockAuthState.sessionCookie = 'session-cookie';
+ mockUsageStoreState.usage = mockUnsubscribedUsage;
+ mockPrepareAffiliate.mockResolvedValue(true);
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(null);
+ mockAffiliateConfig = { domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' };
+ mockSuperwallConfigured = true;
+ });
+
+ it('leaves the Subscription card unchanged when creator codes are not configured', () => {
+ mockAffiliateConfig = null;
+ const screen = render(<AccountScreen />);
+ expect(screen.queryByText('Submit creator link')).toBeNull();
+ expect(screen.getByText('Plans & Billing')).toBeTruthy();
+ });
+
+ it('does not allocate an offer while the paywall cannot open yet', async () => {
+ mockSuperwallConfigured = false;
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(mockPrepareAffiliate).toHaveBeenCalledTimes(1));
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
+ it('checks and shows the offer directly, with no full-price fallback when unavailable', async () => {
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(loadAffiliateOffer).toHaveBeenCalledTimes(1));
+ expect(mockPrepareAffiliate).toHaveBeenCalledWith(expect.any(Function));
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
+ it('opens ordinary plans only on the explicit View plans action', async () => {
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('View plans'));
+ await waitFor(() => expect(mockRegisterSuperwallGate).toHaveBeenCalledTimes(1));
+ expect(mockPrepareAffiliate).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ });
+
+ it('does not present an offer after a failed or denied creator check', async () => {
+ mockPrepareAffiliate.mockResolvedValue(false);
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(mockPrepareAffiliate).toHaveBeenCalledTimes(1));
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
+ it('ignores repeated submits and billing taps while checking and never follows a dismissed offer with Superwall', async () => {
+ let finish!: (offer: AffiliateOffer | null) => void;
+ jest.mocked(loadAffiliateOffer).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(loadAffiliateOffer).toHaveBeenCalledTimes(1));
+ fireEvent.press(screen.getByText('Submit creator link'));
+ fireEvent.press(screen.getByText('Plans & Billing'));
+ await act(async () => {
+ finish(null);
+ });
+ expect(mockPrepareAffiliate).toHaveBeenCalledTimes(1);
+ expect(loadAffiliateOffer).toHaveBeenCalledTimes(1);
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+
+ it('cancels the claim continuation when the screen is left', async () => {
+ let finish!: (ready: boolean) => void;
+ mockPrepareAffiliate.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ const isCurrent = mockPrepareAffiliate.mock.calls[0][0];
+ expect(isCurrent()).toBe(true);
+ screen.unmount();
+ expect(isCurrent()).toBe(false);
+ await act(async () => {
+ finish(true);
+ });
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
+ });
+ it.each([
+ [true, 'shown'],
+ [false, 'unavailable'],
+ ])('reports a creator paywall that presents=%s as %s', async (presents, expected) => {
+ jest.mocked(loadAffiliateOffer).mockResolvedValue({ productId: 'monthly' } as AffiliateOffer);
+ mockRegisterSuperwallGate.mockImplementation(async (options: { onPresent?: () => void }) => {
+ if (presents) options.onPresent?.();
+ return true;
+ });
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(screen.getByTestId('creator-result').props.children).toBe(expected));
+ });
+ it.each([false, true])(
+ 'opens the shared paywall with a private offer for anonymous=%s and aborts on leaving Account',
+ async (anonymous) => {
+ mockAuthState.user = { ...mockUser, isAnonymous: anonymous };
+ const offer = {
+ productId: 'monthly',
+ redemptionUrl: 'https://apps.apple.com/redeem?code=TEST',
+ } as AffiliateOffer;
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(offer);
+ mockRegisterSuperwallGate.mockReturnValue(new Promise(() => {}));
+ const screen = render(<AccountScreen />);
+ fireEvent.press(screen.getByText('Submit creator link'));
+ await waitFor(() => expect(mockRegisterSuperwallGate).toHaveBeenCalledTimes(1));
+ const options = mockRegisterSuperwallGate.mock.calls[0][0];
+ expect(options.creatorOffer).toBe(offer);
+ expect(options.requiresAccount).toBe(false);
+ expect(options.onAccessGrantedWithoutPurchase).toBeUndefined();
+ expect(JSON.stringify(options.params)).not.toContain('apps.apple.com');
+ expect(options.signal.aborted).toBe(false);
+ screen.unmount();
+ expect(options.signal.aborted).toBe(true);
+ expect(mockRegisterSuperwallGate).toHaveBeenCalledTimes(1);
+ },
+ );
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx
index 32e4ef72d..4ccc84b3d 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/PaywallStep.tsx
@@ -5,10 +5,14 @@ import { Text } from '@/components/ui/Text';
import { OnboardingShell } from '@/components/onboarding/OnboardingShell';
import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';
import { useAuthStore } from '@/store/useAuthStore';
+import { useAffiliateStore } from '@/store/useAffiliateStore';
+import { loadAffiliateOffer, type AffiliateOffer } from '@/lib/affiliateOffer';
import { getUsageOwnerKey, useUsageStore } from '@/store/useUsageStore';
import { useSuperwallGate } from '@/hooks/useSuperwallGate';
import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';
import { describeOnboardingError } from '@/lib/onboardingErrors';
+import { getAffiliateClientConfig } from '@/lib/affiliateLink';
+import { TrackingPermissionStep } from './TrackingPermissionStep';
const HIGHLIGHTS: { icon: string; mdIcon: LucideIconName; label: string }[] = [
{ icon: 'cloud', mdIcon: 'Cloud', label: 'Cloud transcription with no word limit' },
@@ -35,6 +39,7 @@ export const PAYWALL_ESCAPE_MS = 8_000;
export function PaywallStep() {
const { goNext } = useOnboardingStep('paywall');
const user = useAuthStore((s) => s.user);
+ const sessionCookie = useAuthStore((s) => s.sessionCookie);
const usage = useUsageStore((s) => s.usage);
const usageOwnerKey = useUsageStore((s) => s.ownerKey);
// Usage is only this account's when the store loaded it for the current
@@ -45,6 +50,12 @@ export function PaywallStep() {
usageOwnerKey === getUsageOwnerKey() &&
!usage.isSubscribed;
const { register, state, isConfigured } = useSuperwallGate();
+ // Creator preparation awaits before registering; by then the SDK may have
+ // finished configuring, so register through the latest gate, not this render's.
+ const registerRef = useRef(register);
+ useEffect(() => {
+ registerRef.current = register;
+ }, [register]);
const hasPresentedRef = useRef(false);
const hasAdvancedRef = useRef(false);
const unmountedRef = useRef(false);
@@ -53,6 +64,31 @@ export function PaywallStep() {
const [presenting, setPresenting] = useState(false);
const [skipping, setSkipping] = useState(false);
const [escapeElapsed, setEscapeElapsed] = useState(false);
+ const affiliateEnabled = Boolean(getAffiliateClientConfig());
+ // Only a trusted inbound creator link brings the tracking question forward, so
+ // its offer can be checked; everyone else meets it at its usual step after signup.
+ const [inboundCreator, setInboundCreator] = useState<boolean | null>(
+ affiliateEnabled ? null : false,
+ );
+ const [consentChecked, setConsentChecked] = useState(false);
+ const completeConsent = useCallback(async () => setConsentChecked(true), []);
+ const consentReady = inboundCreator === false || (inboundCreator === true && consentChecked);
+ const userId = user?.id;
+ useEffect(() => {
+ if (!affiliateEnabled) return;
+ let active = true;
+ (async () => {
+ await useAffiliateStore.getState().hydrate();
+ await useAffiliateStore.getState().bindSession();
+ })()
+ .catch(() => {})
+ .finally(() => {
+ if (active) setInboundCreator(useAffiliateStore.getState().inboundOfferPending);
+ });
+ return () => {
+ active = false;
+ };
+ }, [affiliateEnabled, userId]);
const [advanceError, setAdvanceError] = useState<string | null>(null);
const advance = useCallback(async (): Promise<void> => {
@@ -107,6 +143,8 @@ export function PaywallStep() {
return;
}
+ if (!consentReady) return;
+
if (!isConfigured && !readyGraceElapsed) return;
hasPresentedRef.current = true;
setPresenting(true);
@@ -117,12 +155,54 @@ export function PaywallStep() {
// only thing that cancels the advance; effect re-runs must not.
const controller = new AbortController();
registrationRef.current = controller;
- register({ placement: SUPERWALL_PLACEMENTS.onboardingPaywall, signal: controller.signal })
+ const isCurrent = () =>
+ !unmountedRef.current &&
+ !hasAdvancedRef.current &&
+ !controller.signal.aborted &&
+ useAuthStore.getState().user?.id === user.id &&
+ useAuthStore.getState().sessionCookie === sessionCookie;
+ (async () => {
+ // Only a trusted inbound-link intent can seed this first presentation.
+ // Ordinary rendering and typed candidates never claim or allocate stock.
+ let creatorOffer: AffiliateOffer | undefined;
+ try {
+ if (affiliateEnabled && (await useAffiliateStore.getState().consumeInboundOffer(isCurrent)))
+ creatorOffer = (await loadAffiliateOffer(isCurrent)) ?? undefined;
+ } catch {
+ // Optional referral storage must not skip ordinary purchasing.
+ }
+ if (!isCurrent()) return;
+ const latestUsage = useUsageStore.getState();
+ if (
+ !latestUsage.usage ||
+ !latestUsage.ownerKey ||
+ latestUsage.ownerKey !== getUsageOwnerKey() ||
+ latestUsage.usage.isSubscribed
+ ) {
+ setPresenting(false);
+ setSkipping(true);
+ return;
+ }
+ await registerRef.current({
+ placement: SUPERWALL_PLACEMENTS.onboardingPaywall,
+ signal: controller.signal,
+ creatorOffer,
+ });
+ })()
.catch(() => {})
.finally(() => {
- if (!unmountedRef.current) void advance();
+ if (isCurrent()) void advance();
});
- }, [advance, isConfigured, isConfirmedFree, readyGraceElapsed, register, user]);
+ }, [
+ advance,
+ affiliateEnabled,
+ consentReady,
+ isConfigured,
+ isConfirmedFree,
+ readyGraceElapsed,
+ user,
+ sessionCookie,
+ ]);
// Between registering and the SDK presenting, this backdrop looks like an
// ordinary screen with a primary button; tapping it would mount the next
@@ -146,6 +226,9 @@ export function PaywallStep() {
);
}
+ if (inboundCreator && !consentChecked && user && isConfirmedFree)
+ return <TrackingPermissionStep onComplete={completeConsent} />;
+
return (
<OnboardingShell
title="Go further with OpenWhispr Pro."
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx b/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx
index 50587e862..f363d3792 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/TrackingPermissionStep.tsx
@@ -27,8 +27,11 @@ const BENEFITS: Benefit[] = [
{ icon: 'scope', mdIcon: 'Target', text: 'Make better marketing decisions' },
];
-export function TrackingPermissionStep(): ReactElement {
- const { goNext } = useOnboardingStep('tracking-permission');
+export function TrackingPermissionStep({
+ onComplete,
+}: { onComplete?: () => Promise<void> } = {}): ReactElement {
+ const { goNext: advanceStep } = useOnboardingStep('tracking-permission');
+ const goNext = onComplete ?? advanceStep;
const markRequestAttempted = useOnboardingStore(
(state) => state.markTrackingAuthorizationRequestAttempted,
);
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx
index 6d23dabf8..49b7804a9 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/PaywallStep.test.tsx
@@ -1,4 +1,33 @@
+import { loadAffiliateOffer } from '@/lib/affiliateOffer';
+jest.mock('@/lib/affiliateOffer', () => ({
+ loadAffiliateOffer: jest.fn().mockResolvedValue(null),
+}));
import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+let mockAffiliateEnabled = false;
+let mockInboundPending = false;
+const mockPrepare = jest.fn();
+const mockConsumeInbound = jest.fn();
+jest.mock('@/lib/affiliateLink', () => ({
+ getAffiliateClientConfig: () =>
+ mockAffiliateEnabled ? { domain: 'sandbox.dub.link', publishableKey: 'dub_pk_TEST' } : null,
+}));
+jest.mock('@/store/useAffiliateStore', () => ({
+ useAffiliateStore: {
+ getState: () => ({
+ prepare: mockPrepare,
+ consumeInboundOffer: mockConsumeInbound,
+ hydrate: async () => {},
+ bindSession: async () => {},
+ inboundOfferPending: mockInboundPending,
+ }),
+ },
+}));
+jest.mock('../TrackingPermissionStep', () => ({
+ TrackingPermissionStep: ({ onComplete }: { onComplete: () => Promise<void> }) => {
+ const { Button } = require('react-native');
+ return <Button title="Existing tracking choice" onPress={onComplete} />;
+ },
+}));
jest.mock('@/lib/sentry', () => ({ Sentry: { captureException: jest.fn() } }));
jest.mock('react-native-safe-area-context', () => ({
@@ -16,16 +45,23 @@ jest.mock('@/store/useOnboardingStore', () => ({
}));
const mockRegister = jest.fn();
-type MockGate = { isConfigured: boolean; state: { status: string } };
+type MockGate = {
+ isConfigured: boolean;
+ state: { status: string };
+ register?: jest.Mock;
+};
let mockGate: MockGate = { isConfigured: true, state: { status: 'idle' } };
jest.mock('@/hooks/useSuperwallGate', () => ({
useSuperwallGate: () => ({ register: mockRegister, ...mockGate }),
}));
-type MockAuthState = { user: { id: string; isAnonymous: boolean } | null };
+type MockAuthState = { user: { id: string; isAnonymous: boolean } | null; sessionCookie?: string };
let mockAuthState: MockAuthState = { user: { id: 'anon-user', isAnonymous: true } };
jest.mock('@/store/useAuthStore', () => ({
- useAuthStore: (selector: (s: MockAuthState) => unknown) => selector(mockAuthState),
+ useAuthStore: Object.assign(
+ (selector: (s: MockAuthState) => unknown) => selector(mockAuthState),
+ { getState: () => mockAuthState },
+ ),
}));
type MockUsage = { isSubscribed: boolean };
@@ -52,6 +88,11 @@ import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';
beforeEach(() => {
jest.clearAllMocks();
+ mockAffiliateEnabled = false;
+ mockInboundPending = false;
+ mockPrepare.mockResolvedValue(true);
+ mockConsumeInbound.mockResolvedValue(false);
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(null);
mockGoNext.mockResolvedValue(undefined);
mockRegister.mockResolvedValue(true);
mockAuthState = { user: { id: 'anon-user', isAnonymous: true } };
@@ -60,6 +101,28 @@ beforeEach(() => {
mockGate = { isConfigured: true, state: { status: 'idle' } };
});
+it('keeps the usual order without an inbound creator link: no early tracking step, claim or allocation', async () => {
+ mockAffiliateEnabled = true;
+ const screen = render(<PaywallStep />);
+ await waitFor(() => expect(mockRegister).toHaveBeenCalledTimes(1));
+ expect(screen.queryByText('Existing tracking choice')).toBeNull();
+ expect(mockPrepare).not.toHaveBeenCalled();
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
+});
+it('asks the existing tracking question first for an inbound creator link', async () => {
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ const screen = render(<PaywallStep />);
+ await waitFor(() => expect(screen.getByText('Existing tracking choice')).toBeTruthy());
+ expect(mockRegister).not.toHaveBeenCalled();
+ await act(async () => {
+ fireEvent.press(screen.getByText('Existing tracking choice'));
+ });
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
+});
+
afterEach(() => {
jest.useRealTimers();
});
@@ -346,3 +409,123 @@ it('allows retrying continuation after a progress save fails', async () => {
await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
expect(mockRegister).toHaveBeenCalledTimes(1);
});
+
+it('closing the shared paywall continues once with no second paywall or stock allocation', async () => {
+ render(<PaywallStep />);
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(1));
+ expect(mockRegister).toHaveBeenCalledTimes(1);
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+});
+
+it('seeds the shared Cloud paywall only for an explicit trusted inbound intent', async () => {
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ mockConsumeInbound.mockResolvedValue(true);
+ const offer = { productId: 'monthly' } as Awaited<ReturnType<typeof loadAffiliateOffer>>;
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(offer);
+ const screen = render(<PaywallStep />);
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+ const consent = await screen.findByText('Existing tracking choice');
+ await act(async () => fireEvent.press(consent));
+ expect(loadAffiliateOffer).toHaveBeenCalledTimes(1);
+ expect(mockRegister).toHaveBeenCalledWith(expect.objectContaining({ creatorOffer: offer }));
+});
+it('keeps ordinary Cloud purchasing available when an inbound offer is refused', async () => {
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ mockConsumeInbound.mockResolvedValue(true);
+ jest.mocked(loadAffiliateOffer).mockResolvedValue(null);
+ const screen = render(<PaywallStep />);
+ const consent = await screen.findByText('Existing tracking choice');
+ await act(async () => fireEvent.press(consent));
+ expect(mockRegister).toHaveBeenCalledWith(expect.objectContaining({ creatorOffer: undefined }));
+});
+
+it('registers through the gate current after inbound preparation, not the one it started with', async () => {
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ let finishPreparation!: () => void;
+ mockConsumeInbound.mockReturnValue(
+ new Promise<boolean>((resolve) => {
+ finishPreparation = () => resolve(false);
+ }),
+ );
+ const screen = render(<PaywallStep />);
+ const consent = await screen.findByText('Existing tracking choice');
+ await act(async () => fireEvent.press(consent));
+ const configuredRegister = jest.fn().mockResolvedValue(true);
+ mockGate = { ...mockGate, register: configuredRegister };
+ screen.rerender(<PaywallStep />);
+ await act(async () => finishPreparation());
+ expect(configuredRegister).toHaveBeenCalledTimes(1);
+ expect(mockRegister).not.toHaveBeenCalled();
+});
+it('lets Continue escape a slow creator preparation, which then never registers', async () => {
+ jest.useFakeTimers();
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ let finishPreparation!: () => void;
+ mockConsumeInbound.mockReturnValue(
+ new Promise<boolean>((resolve) => {
+ finishPreparation = () => resolve(false);
+ }),
+ );
+ const screen = render(<PaywallStep />);
+ await act(async () => {});
+ const consent = await screen.findByText('Existing tracking choice');
+ await act(async () => fireEvent.press(consent));
+ await act(async () => fireEvent.press(screen.getByText('Continue')));
+ expect(mockGoNext).not.toHaveBeenCalled();
+ await act(async () => {
+ jest.advanceTimersByTime(PAYWALL_ESCAPE_MS);
+ });
+ await act(async () => fireEvent.press(screen.getByText('Continue')));
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
+ await act(async () => finishPreparation());
+ expect(mockRegister).not.toHaveBeenCalled();
+});
+it('still presents ordinary purchasing if consuming an optional inbound intent fails', async () => {
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ mockConsumeInbound.mockRejectedValueOnce(new Error('storage unavailable'));
+ const screen = render(<PaywallStep />);
+ const consent = await screen.findByText('Existing tracking choice');
+ await act(async () => fireEvent.press(consent));
+ expect(mockRegister).toHaveBeenCalledWith(expect.objectContaining({ creatorOffer: undefined }));
+ expect(loadAffiliateOffer).not.toHaveBeenCalled();
+});
+
+describe.each(['claim', 'offer'])('eligibility while waiting for %s', (phase) => {
+ it.each([
+ ['subscribed', { usage: SUBSCRIBED, ownerKey: OWNER }],
+ ['owned by another session', { usage: FREE, ownerKey: 'old-session' }],
+ ['unknown', { usage: null, ownerKey: null }],
+ ])('skips when usage becomes %s', async (_label, nextUsage) => {
+ mockAffiliateEnabled = true;
+ mockInboundPending = true;
+ let finishPreparation!: () => void;
+ if (phase === 'claim') {
+ mockConsumeInbound.mockReturnValue(
+ new Promise<boolean>((resolve) => {
+ finishPreparation = () => resolve(false);
+ }),
+ );
+ } else {
+ mockConsumeInbound.mockResolvedValue(true);
+ jest.mocked(loadAffiliateOffer).mockReturnValue(
+ new Promise((resolve) => {
+ finishPreparation = () => resolve(null);
+ }),
+ );
+ }
+ const screen = render(<PaywallStep />);
+ const consent = await screen.findByText('Existing tracking choice');
+ await act(async () => fireEvent.press(consent));
+ mockUsageState = nextUsage;
+ screen.rerender(<PaywallStep />);
+ await act(async () => finishPreparation());
+ expect(mockRegister).not.toHaveBeenCalled();
+ expect(mockGoNext).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(PRO_TITLE)).toBeNull();
+ });
+});
diff --git a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx
index 1aae19296..86a2202aa 100644
--- a/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx
+++ b/openwhispr-mobile/src/screens/onboarding/steps/__tests__/TrackingPermissionStep.test.tsx
@@ -230,3 +230,24 @@ it('offers continuation retry when auto-skipping ATT fails to save progress', as
await waitFor(() => expect(mockGoNext).toHaveBeenCalledTimes(2));
expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
});
+
+it.each(['authorized', 'denied'] as const)(
+ 'returns to the early offer after %s without advancing the onboarding route',
+ async (status) => {
+ const onComplete = jest.fn().mockResolvedValue(undefined);
+ mockRequestTrackingAuthorization.mockResolvedValue(status);
+ const screen = render(<TrackingPermissionStep onComplete={onComplete} />);
+ fireEvent.press(await screen.findByText('Continue'));
+ await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));
+ expect(mockMarkRequestAttempted).toHaveBeenCalledTimes(1);
+ expect(mockRequestTrackingAuthorization).toHaveBeenCalledTimes(1);
+ expect(mockGoNext).not.toHaveBeenCalled();
+ },
+);
+
+it('does not repeat the tracking prompt when the ordinary later step is reached', async () => {
+ mockTrackingAuthorizationRequestAttempted = true;
+ render(<TrackingPermissionStep />);
+ await waitFor(() => expect(mockGoNext).toHaveBeenCalledWith('tracking-permission'));
+ expect(mockRequestTrackingAuthorization).not.toHaveBeenCalled();
+});
diff --git a/openwhispr-mobile/src/store/__tests__/useAffiliateStore.test.ts b/openwhispr-mobile/src/store/__tests__/useAffiliateStore.test.ts
new file mode 100644
index 000000000..d010710f2
--- /dev/null
+++ b/openwhispr-mobile/src/store/__tests__/useAffiliateStore.test.ts
@@ -0,0 +1,355 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import { useAffiliateStore } from '../useAffiliateStore';
+import { useAuthStore } from '../useAuthStore';
+import { useConfigStore } from '../useConfigStore';
+import { AffiliateInputError, getAffiliateClientConfig } from '@/lib/affiliateLink';
+import { ApiError } from '@/lib/apiClient';
+import { checkAndClaimAffiliate } from '@/lib/affiliateAttribution';
+
+jest.mock('@react-native-async-storage/async-storage', () => ({
+ getItem: jest.fn(),
+ setItem: jest.fn().mockResolvedValue(undefined),
+}));
+jest.mock('../useAuthStore', () => ({ useAuthStore: { getState: jest.fn() } }));
+jest.mock('../useConfigStore', () => ({ useConfigStore: { getState: jest.fn() } }));
+jest.mock('@/lib/affiliateLink', () => ({
+ getAffiliateClientConfig: jest.fn(),
+ AffiliateInputError: class MockAffiliateInputError extends Error {},
+}));
+jest.mock('@/lib/affiliateAttribution', () => ({
+ checkAndClaimAffiliate: jest.fn(),
+ AffiliateConsentError: class AffiliateConsentError extends Error {},
+}));
+jest.mock('@/lib/apiClient', () => ({
+ ApiError: class MockApiError extends Error {
+ status: number;
+ constructor(message: string, status: number) {
+ super(message);
+ this.status = status;
+ }
+ },
+}));
+
+const claim = jest.mocked(checkAndClaimAffiliate);
+let auth: { user: { id: string } | null; sessionCookie: string | null; isInitialized: boolean };
+let config: { usageAnalyticsEnabled?: boolean };
+beforeEach(async () => {
+ jest.clearAllMocks();
+ jest
+ .mocked(getAffiliateClientConfig)
+ .mockReturnValue({ domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' });
+ auth = { user: { id: 'anonymous-a' }, sessionCookie: 'session-a', isInitialized: true };
+ config = { usageAnalyticsEnabled: true };
+ jest
+ .mocked(useAuthStore.getState)
+ .mockImplementation(() => auth as ReturnType<typeof useAuthStore.getState>);
+ jest
+ .mocked(useConfigStore.getState)
+ .mockImplementation(() => ({ config }) as ReturnType<typeof useConfigStore.getState>);
+ useAffiliateStore.setState({
+ ownerId: 'anonymous-a',
+ ownerAnonymous: false,
+ link: '',
+ clickId: null,
+ saved: false,
+ autoSubmit: false,
+ inboundOfferPending: false,
+ hydrated: true,
+ checking: false,
+ error: null,
+ });
+ claim.mockResolvedValue('provisional');
+});
+
+it('ordinary continuation performs no affiliate request', async () => {
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ expect(claim).not.toHaveBeenCalled();
+});
+it('editing saves locally and only an explicit prepare claims it', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ expect(claim).not.toHaveBeenCalled();
+ expect(AsyncStorage.setItem).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.stringContaining('sandbox.dub.link/creator'),
+ );
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ expect(useAffiliateStore.getState().saved).toBe(true);
+ expect(claim.mock.calls[0][2]).toBe('session-a');
+});
+
+it('navigation cancellation reaches the claim guard, and a claim the server accepted stays saved', async () => {
+ let current = true;
+ let finish!: (status: 'provisional') => void;
+ claim.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ const pending = useAffiliateStore.getState().prepare(() => current);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(claim.mock.calls[0][3]()).toBe(true);
+ current = false;
+ expect(claim.mock.calls[0][3]()).toBe(false);
+ finish('provisional');
+ expect(await pending).toBe(false);
+ expect(useAffiliateStore.getState()).toMatchObject({ saved: true, checking: false });
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ expect(claim).toHaveBeenCalledTimes(1);
+});
+
+it('drops a server answer that arrives after an account switch', async () => {
+ let finish!: (status: 'provisional') => void;
+ claim.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ const pending = useAffiliateStore.getState().prepare();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ auth = { user: { id: 'account-b' }, sessionCookie: 'session-b', isInitialized: true };
+ finish('provisional');
+ expect(await pending).toBe(false);
+ expect(useAffiliateStore.getState().saved).toBe(false);
+});
+
+it('carries an unclaimed link from an anonymous session into the account it becomes', async () => {
+ auth = {
+ user: { id: 'anonymous-a', isAnonymous: true },
+ sessionCookie: 'session-a',
+ isInitialized: true,
+ } as typeof auth;
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator', true);
+ auth = { user: { id: 'account-b' }, sessionCookie: 'session-b', isInitialized: true };
+ await useAffiliateStore.getState().bindSession();
+ expect(useAffiliateStore.getState()).toMatchObject({
+ ownerId: 'account-b',
+ ownerAnonymous: false,
+ link: 'https://sandbox.dub.link/creator',
+ autoSubmit: true,
+ inboundOfferPending: true,
+ });
+});
+
+it('never carries a link between two real accounts, or a claimed one out of an anonymous session', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ auth = { user: { id: 'account-b' }, sessionCookie: 'session-b', isInitialized: true };
+ await useAffiliateStore.getState().bindSession();
+ expect(useAffiliateStore.getState()).toMatchObject({ ownerId: 'account-b', link: '' });
+
+ auth = {
+ user: { id: 'anonymous-c', isAnonymous: true },
+ sessionCookie: 'session-c',
+ isInitialized: true,
+ } as typeof auth;
+ useAffiliateStore.setState({ ownerId: 'anonymous-c', ownerAnonymous: true });
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ auth = { user: { id: 'account-d' }, sessionCookie: 'session-d', isInitialized: true };
+ await useAffiliateStore.getState().bindSession();
+ expect(useAffiliateStore.getState()).toMatchObject({
+ ownerId: 'account-d',
+ link: '',
+ saved: false,
+ });
+});
+
+it('does not start collection if the caller has already left', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ expect(await useAffiliateStore.getState().prepare(() => false)).toBe(false);
+ expect(claim).not.toHaveBeenCalled();
+});
+it('checking twice makes one claim and an offline failure retains input for retry or clearing', async () => {
+ let reject!: (error: Error) => void;
+ claim.mockImplementation(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ }),
+ );
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ const first = useAffiliateStore.getState().prepare();
+ await Promise.resolve();
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ reject(new Error('offline'));
+ expect(await first).toBe(false);
+ expect(claim).toHaveBeenCalledTimes(1);
+ expect(useAffiliateStore.getState().link).toContain('/creator');
+ expect(useAffiliateStore.getState().error).toBe('We couldn’t check your link. Try again.');
+ await useAffiliateStore.getState().edit('');
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+});
+it('a previous account response cannot claim or persist for the next account', async () => {
+ let finish!: (status: 'provisional') => void;
+ claim.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ const pending = useAffiliateStore.getState().prepare();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ auth = { ...auth, user: { id: 'account-b' }, sessionCookie: 'session-b' };
+ await useAffiliateStore.getState().bindSession();
+ expect(claim.mock.calls[0][3]()).toBe(false);
+ finish('provisional');
+ expect(await pending).toBe(false);
+ expect(useAffiliateStore.getState()).toMatchObject({
+ ownerId: 'account-b',
+ link: '',
+ saved: false,
+ checking: false,
+ });
+});
+it('signout clears a saved referral and hydration cannot restore another account’s candidate', async () => {
+ useAffiliateStore.setState({ link: 'https://sandbox.dub.link/creator', saved: true });
+ auth = { ...auth, user: null, sessionCookie: null };
+ await useAffiliateStore.getState().bindSession();
+ expect(useAffiliateStore.getState()).toMatchObject({ link: '', saved: false, ownerId: null });
+ jest.mocked(AsyncStorage.getItem).mockResolvedValue(
+ JSON.stringify({
+ ownerId: 'old-user',
+ link: 'https://sandbox.dub.link/old',
+ clickId: 'click',
+ saved: true,
+ autoSubmit: false,
+ }),
+ );
+ useAffiliateStore.setState({ hydrated: false });
+ await useAffiliateStore.getState().hydrate();
+ await useAffiliateStore.getState().bindSession();
+ expect(useAffiliateStore.getState().link).toBe('');
+});
+it('persists the resolved click before claiming and reuses it after a failed claim', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ claim.mockImplementationOnce(async (_link, _click, _cookie, _current, remember) => {
+ await remember('click-once');
+ throw new Error('claim response lost');
+ });
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ expect(useAffiliateStore.getState().clickId).toBe('click-once');
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ expect(claim.mock.calls[1][1]).toBe('click-once');
+});
+it('analytics refusal prevents collection and review does not show saved success', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ config.usageAnalyticsEnabled = false;
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ expect(claim).not.toHaveBeenCalled();
+ config.usageAnalyticsEnabled = true;
+ claim.mockResolvedValue('review');
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ expect(useAffiliateStore.getState().saved).toBe(false);
+});
+
+it('claims on the default Usage Analytics setting', async () => {
+ delete config.usageAnalyticsEnabled;
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ expect(claim).toHaveBeenCalledTimes(1);
+});
+it.each([
+ ['an invalid entry', () => new AffiliateInputError(), 'Enter your exact creator code'],
+ [
+ 'an unavailable link',
+ () => new ApiError('unavailable', 400),
+ 'This creator link is unavailable',
+ ],
+])('stops retrying an inbound link refused as %s', async (_, makeError, message) => {
+ claim.mockRejectedValue(makeError());
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ expect(useAffiliateStore.getState().error).toContain(message);
+ expect(useAffiliateStore.getState()).toMatchObject({
+ autoSubmit: false,
+ inboundOfferPending: false,
+ });
+});
+it('stops retrying an inbound link the server sends to review', async () => {
+ claim.mockResolvedValue('review');
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ expect(useAffiliateStore.getState()).toMatchObject({
+ saved: false,
+ autoSubmit: false,
+ inboundOfferPending: false,
+ });
+});
+it('keeps retrying an inbound link after a transient failure', async () => {
+ claim.mockRejectedValue(new Error('offline'));
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
+ expect(await useAffiliateStore.getState().prepare()).toBe(false);
+ expect(useAffiliateStore.getState().autoSubmit).toBe(true);
+});
+it('disabling affiliate configuration never blocks ordinary onboarding with a cached link', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
+ jest.mocked(getAffiliateClientConfig).mockReturnValue(null);
+ expect(await useAffiliateStore.getState().prepare()).toBe(true);
+ expect(claim).not.toHaveBeenCalled();
+});
+
+it('keeps inbound intent after claiming, consumes it once, and does not invent it for typing', async () => {
+ await useAffiliateStore.getState().edit('demo');
+ expect(await useAffiliateStore.getState().consumeInboundOffer(() => true)).toBe(false);
+ expect(claim).not.toHaveBeenCalled();
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
+ await useAffiliateStore.getState().prepare();
+ expect(useAffiliateStore.getState()).toMatchObject({
+ saved: true,
+ autoSubmit: false,
+ inboundOfferPending: true,
+ });
+ const results = await Promise.all([
+ useAffiliateStore.getState().consumeInboundOffer(() => true),
+ useAffiliateStore.getState().consumeInboundOffer(() => true),
+ ]);
+ expect(results.filter(Boolean)).toHaveLength(1);
+ expect(claim).toHaveBeenCalledTimes(1);
+});
+it('retains refused inbound intent and cannot consume it after navigation or account changes', async () => {
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
+ config.usageAnalyticsEnabled = false;
+ expect(await useAffiliateStore.getState().consumeInboundOffer(() => true)).toBe(false);
+ expect(claim).not.toHaveBeenCalled();
+ expect(useAffiliateStore.getState().inboundOfferPending).toBe(true);
+ expect(await useAffiliateStore.getState().consumeInboundOffer(() => false)).toBe(false);
+ auth.user = { id: 'other' };
+ expect(await useAffiliateStore.getState().consumeInboundOffer(() => true)).toBe(false);
+ expect(useAffiliateStore.getState().inboundOfferPending).toBe(false);
+});
+it('old persisted candidates do not acquire a new inbound offer intent', async () => {
+ jest.mocked(AsyncStorage.getItem).mockResolvedValue(
+ JSON.stringify({
+ ownerId: 'anonymous-a',
+ link: 'https://sandbox.dub.link/demo',
+ clickId: 'fixture',
+ saved: true,
+ autoSubmit: false,
+ }),
+ );
+ useAffiliateStore.setState({ hydrated: false });
+ await useAffiliateStore.getState().hydrate();
+ expect(useAffiliateStore.getState().inboundOfferPending).toBe(false);
+});
+it('waits for the arrival claim without making a second one', async () => {
+ let finish!: (status: 'provisional') => void;
+ claim.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
+ const preparing = useAffiliateStore.getState().prepare();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ const consuming = useAffiliateStore.getState().consumeInboundOffer(() => true);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(claim).toHaveBeenCalledTimes(1);
+ finish('provisional');
+ await preparing;
+ expect(await consuming).toBe(true);
+});
diff --git a/openwhispr-mobile/src/store/useAffiliateStore.ts b/openwhispr-mobile/src/store/useAffiliateStore.ts
new file mode 100644
index 000000000..a3d7a19f1
--- /dev/null
+++ b/openwhispr-mobile/src/store/useAffiliateStore.ts
@@ -0,0 +1,235 @@
+import { create } from 'zustand';
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import { z } from 'zod';
+import { useAuthStore } from './useAuthStore';
+import { useConfigStore } from './useConfigStore';
+import { AffiliateConsentError, checkAndClaimAffiliate } from '@/lib/affiliateAttribution';
+import { ApiError } from '@/lib/apiClient';
+import { isUsageAnalyticsAllowed } from '@/lib/usageAnalytics';
+import { AffiliateInputError, getAffiliateClientConfig } from '@/lib/affiliateLink';
+
+const STORAGE_KEY = 'openwhispr_affiliate_candidate_v1';
+// Shown as-is; the Account row picks its follow-up action from which one it is.
+export const AFFILIATE_ERRORS = {
+ tracking: 'Creator links need tracking permission. You can allow it in Settings.',
+ analytics: 'Creator links are unavailable while Usage Analytics is off.',
+ input: 'Enter your exact creator code, or paste the original creator link.',
+ unavailable: 'This creator link is unavailable. Try another link.',
+ review: 'We couldn’t confirm this referral.',
+ check: 'We couldn’t check your link. Try again.',
+ save: 'We couldn’t save your link. Try again.',
+} as const;
+const candidateSchema = z.object({
+ ownerId: z.string().nullable(),
+ ownerAnonymous: z.boolean().default(false),
+ link: z.string().max(2048),
+ clickId: z.string().nullable(),
+ saved: z.boolean(),
+ autoSubmit: z.boolean(),
+ inboundOfferPending: z.boolean().default(false),
+});
+type Candidate = z.infer<typeof candidateSchema>;
+const empty: Candidate = {
+ ownerId: null,
+ ownerAnonymous: false,
+ link: '',
+ clickId: null,
+ saved: false,
+ autoSubmit: false,
+ inboundOfferPending: false,
+};
+interface AffiliateState extends Candidate {
+ hydrated: boolean;
+ checking: boolean;
+ error: string | null;
+ hydrate: () => Promise<void>;
+ bindSession: () => Promise<void>;
+ edit: (link: string, autoSubmit?: boolean) => Promise<void>;
+ prepare: (isCallerCurrent?: () => boolean) => Promise<boolean>;
+ consumeInboundOffer: (isCallerCurrent: () => boolean) => Promise<boolean>;
+}
+let revision = 0;
+let writeQueue: Promise<void> = Promise.resolve();
+function persist(candidate: Candidate): Promise<void> {
+ const value = JSON.stringify(candidate);
+ writeQueue = writeQueue.catch(() => {}).then(() => AsyncStorage.setItem(STORAGE_KEY, value));
+ return writeQueue;
+}
+function snapshot(state: Candidate): Candidate {
+ return {
+ ownerId: state.ownerId,
+ ownerAnonymous: state.ownerAnonymous,
+ link: state.link,
+ clickId: state.clickId,
+ saved: state.saved,
+ autoSubmit: state.autoSubmit,
+ inboundOfferPending: state.inboundOfferPending,
+ };
+}
+export const useAffiliateStore = create<AffiliateState>((set, get) => ({
+ ...empty,
+ hydrated: false,
+ checking: false,
+ error: null,
+ hydrate: async () => {
+ if (get().hydrated) return;
+ const version = revision;
+ try {
+ const raw = await AsyncStorage.getItem(STORAGE_KEY);
+ const parsed = candidateSchema.safeParse(raw ? JSON.parse(raw) : empty);
+ if (version === revision) set(parsed.success ? parsed.data : empty);
+ } catch {
+ /* Keep the flow usable if local storage is unavailable. */
+ }
+ set({ hydrated: true });
+ },
+ bindSession: async () => {
+ const auth = useAuthStore.getState();
+ if (!get().hydrated || !auth.isInitialized) return;
+ const ownerId = auth.user?.id ?? null;
+ const ownerAnonymous = auth.user?.isAnonymous === true;
+ const state = get();
+ if (state.ownerId === ownerId) return;
+ revision += 1;
+ // A candidate captured before session creation binds for the first time, and one
+ // not yet claimed follows its anonymous session into the account it becomes.
+ // A claimed one transfers through the server's replayable link workflow.
+ const carriesOver =
+ ownerId !== null && (state.ownerId === null || (state.ownerAnonymous && !state.saved));
+ set(
+ carriesOver
+ ? { ownerId, ownerAnonymous, checking: false }
+ : { ...empty, ownerId, ownerAnonymous, checking: false, error: null },
+ );
+ try {
+ await persist(snapshot(get()));
+ } catch {
+ set({ error: AFFILIATE_ERRORS.save });
+ }
+ },
+ edit: async (link, autoSubmit = false) => {
+ if (get().saved || get().checking) return;
+ revision += 1;
+ set({
+ link: link.slice(0, 2048),
+ clickId: null,
+ error: null,
+ autoSubmit,
+ inboundOfferPending: autoSubmit,
+ ownerId: useAuthStore.getState().user?.id ?? null,
+ ownerAnonymous: useAuthStore.getState().user?.isAnonymous === true,
+ });
+ try {
+ await persist(snapshot(get()));
+ } catch {
+ set({ error: AFFILIATE_ERRORS.save });
+ }
+ },
+ consumeInboundOffer: async (isCallerCurrent) => {
+ await get().hydrate();
+ await get().bindSession();
+ if (!isCallerCurrent() || !get().inboundOfferPending) return false;
+ const version = revision;
+ const current = () => isCallerCurrent() && revision === version;
+ // The arrival hook may already be claiming this exact link after consent.
+ // Let its bounded request settle rather than submitting a duplicate claim.
+ if (get().checking)
+ await new Promise<void>((resolve) => {
+ let unsubscribe = () => {};
+ const finish = () => {
+ clearTimeout(timer);
+ unsubscribe();
+ resolve();
+ };
+ const timer = setTimeout(finish, 10_000);
+ unsubscribe = useAffiliateStore.subscribe((state) => {
+ if (!state.checking || !current()) finish();
+ });
+ });
+ if (
+ !current() ||
+ get().checking ||
+ !(await get().prepare(current)) ||
+ !get().saved ||
+ !current() ||
+ !get().inboundOfferPending
+ )
+ return false;
+ set({ inboundOfferPending: false });
+ await persist(snapshot(get()));
+ return current();
+ },
+ prepare: async (isCallerCurrent = () => true) => {
+ if (!getAffiliateClientConfig()) return true;
+ await get().hydrate();
+ await get().bindSession();
+ if (!isCallerCurrent()) return false;
+ const state = get();
+ if (!state.link.trim() || state.saved) return true;
+ if (state.checking) return false;
+ const auth = useAuthStore.getState();
+ if (!isUsageAnalyticsAllowed(useConfigStore.getState().config)) {
+ set({ error: AFFILIATE_ERRORS.analytics });
+ return false;
+ }
+ if (!auth.user || !auth.sessionCookie || state.ownerId !== auth.user.id) {
+ set({ error: AFFILIATE_ERRORS.check });
+ return false;
+ }
+ const version = revision;
+ const ownsCandidate = () =>
+ revision === version &&
+ useAuthStore.getState().user?.id === auth.user?.id &&
+ useAuthStore.getState().sessionCookie === auth.sessionCookie &&
+ isUsageAnalyticsAllowed(useConfigStore.getState().config);
+ const isCurrent = () => isCallerCurrent() && ownsCandidate();
+ // A refused link stays refused: stop retrying an inbound one on every resume,
+ // and don't claim it again for the onboarding offer.
+ const stopAutoSubmit = async () => {
+ if (!get().autoSubmit && !get().inboundOfferPending) return;
+ set({ autoSubmit: false, inboundOfferPending: false });
+ await persist(snapshot(get())).catch(() => {});
+ };
+ set({ checking: true, error: null });
+ try {
+ const status = await checkAndClaimAffiliate(
+ state.link,
+ state.clickId,
+ auth.sessionCookie,
+ isCurrent,
+ async (clickId) => {
+ if (!isCurrent()) return;
+ set({ clickId });
+ await persist(snapshot(get()));
+ },
+ );
+ // A claim the server accepted is saved even when its caller gave up waiting,
+ // so a retry finds it saved rather than trying to claim another creator.
+ if (!ownsCandidate()) return false;
+ if (status === 'review') {
+ if (isCallerCurrent()) set({ error: AFFILIATE_ERRORS.review });
+ await stopAutoSubmit();
+ return false;
+ }
+ set({ saved: true, autoSubmit: false });
+ await persist(snapshot(get()));
+ return isCurrent();
+ } catch (error) {
+ if (!isCurrent()) return false;
+ if (error instanceof AffiliateConsentError) {
+ set({ error: AFFILIATE_ERRORS.tracking });
+ } else if (error instanceof AffiliateInputError) {
+ set({ error: AFFILIATE_ERRORS.input });
+ await stopAutoSubmit();
+ } else if (error instanceof ApiError && error.status === 400) {
+ set({ error: AFFILIATE_ERRORS.unavailable });
+ await stopAutoSubmit();
+ } else {
+ set({ error: AFFILIATE_ERRORS.check });
+ }
+ return false;
+ } finally {
+ if (revision === version) set({ checking: false });
+ }
+ },
+}));