fix(iap): keep store Pro when the support chat creates an anonymous session

IAPManager.isLoggedIn was `currentSession != null`, so the anonymous
session the support chat creates switched off the local (RevenueCat)
entitlement path: store-bought Pro users who never signed in lost Pro as
soon as they opened the chat.

isLoggedIn now uses hasAccount(). Related anonymous-session leaks:
- The auth listener no longer logs RevenueCat in as the anonymous user
  (and no longer runs sync-subscriptions for it). A pure
  revenueCatLogin() decides; it also syncs when an anonymous session
  becomes an account by linking (same id, userUpdated event).
- The Windows post-login checkout resume only runs for a real account.
- RevenueCatService: no anonymous appUserID at configure time, no
  bikecontrol_user attribute for it, and _syncRevenueCatUser leaves the
  RevenueCat identity alone for an anonymous session.
- WindowsStripeService.isLoggedIn uses hasAccount, so Stripe checkout /
  portal gate behind sign-in instead of running under the anonymous user.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jonas Bark
2026-09-16 21:15:48 +02:00
parent 154ae178b8
commit 2d04e710cf
4 changed files with 181 additions and 12 deletions

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:bike_control/utils/auth/account_session.dart';
import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/models/device_limit_reached_error.dart';
import 'package:bike_control/pages/paywall.dart';
@@ -59,7 +60,32 @@ class IAPManager {
IAPManager._();
bool get isLoggedIn => core.supabase.auth.currentSession != null;
/// Signed into a real account. The anonymous session the support chat
/// creates on demand doesn't count, so a store-bought Pro user who never
/// signed in keeps the local (RevenueCat) entitlement path.
bool get isLoggedIn => hasAccount(core.supabase.auth.currentSession?.user);
/// The Supabase user id RevenueCat was last logged in as by
/// [_handleAuthStateChange]; null while there's no account.
String? _revenueCatUserId;
/// Pure decision behind the RevenueCat login in [_handleAuthStateChange]:
/// who to log in as and whether to run `sync-subscriptions`, or null to
/// leave RevenueCat alone. Anonymous users are never used as a RevenueCat
/// identity. Syncs on a fresh sign-in or launch, and whenever the account
/// differs from [previousUserId] — e.g. an anonymous session that just
/// became an account by linking an email keeps its id but only fires
/// `userUpdated`.
@visibleForTesting
static ({String userId, bool performSync})? revenueCatLogin({
required AuthChangeEvent event,
required User? user,
required String? previousUserId,
}) {
if (user == null || !hasAccount(user)) return null;
final freshSession = event == AuthChangeEvent.initialSession || event == AuthChangeEvent.signedIn;
return (userId: user.id, performSync: freshSession || user.id != previousUserId);
}
/// Whether the logged-in user is flagged for the Shorebird beta update
/// track (a manual `beta_access` entitlement granted from the admin
@@ -460,12 +486,10 @@ class IAPManager {
case AuthChangeEvent.tokenRefreshed:
case AuthChangeEvent.userUpdated:
case AuthChangeEvent.mfaChallengeVerified:
final userId = session?.user.id;
if (userId != null) {
await _revenueCatService?.logInWithSupabaseUserId(
userId,
performSync: [AuthChangeEvent.initialSession, AuthChangeEvent.signedIn].contains(event),
);
final login = revenueCatLogin(event: event, user: session?.user, previousUserId: _revenueCatUserId);
if (login != null) {
_revenueCatUserId = login.userId;
await _revenueCatService?.logInWithSupabaseUserId(login.userId, performSync: login.performSync);
}
await _revenueCatService?.setAttributes();
await entitlements.refresh(force: true);
@@ -474,13 +498,14 @@ class IAPManager {
// sent to the login gate; a genuine `signedIn` is our cue to finish the
// checkout they started. Skip token refreshes / the initial session,
// which are not a fresh login and would fire on every launch.
if (event == AuthChangeEvent.signedIn) {
if (event == AuthChangeEvent.signedIn && isLoggedIn) {
await _windowsIapService?.resumePendingPurchaseAfterLogin(isAlreadyPro: isProEnabled);
}
return;
case AuthChangeEvent.signedOut:
// ignore: deprecated_member_use
case AuthChangeEvent.userDeleted:
_revenueCatUserId = null;
await _revenueCatService?.logOut();
await entitlements.clearCache();
// reset isPurchased value

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:bike_control/utils/auth/account_session.dart';
import 'package:bike_control/bluetooth/messages/notification.dart';
import 'package:bike_control/main.dart';
import 'package:bike_control/services/entitlements_service.dart';
@@ -117,8 +118,11 @@ class RevenueCatService {
// Configure RevenueCat
final configuration = PurchasesConfiguration(apiKey);
// Only a real account becomes the RevenueCat identity, never the
// support chat's anonymous session. Without one, RevenueCat keeps its
// cached (or anonymous) app user id.
final session = core.supabase.auth.currentSession;
if (session != null) {
if (session != null && hasAccount(session.user)) {
configuration.appUserID = session.user.id;
}
@@ -570,7 +574,7 @@ class RevenueCatService {
// attributes are fully anonymous
await Purchases.setAttributes({
...campaign,
if (session?.user.id != null) "bikecontrol_user": session!.user.id,
if (session != null && hasAccount(session.user)) "bikecontrol_user": session.user.id,
"bikecontrol_trainer": core.settings.getTrainerApp()?.name ?? '-',
"bikecontrol_target": core.settings.getLastTarget()?.name ?? '-',
if (core.connection.controllerDevices.isNotEmpty)
@@ -590,6 +594,10 @@ class RevenueCatService {
await logOut();
return;
}
// Anonymous support-chat session: leave the RevenueCat identity as it is.
// Logging out would drop a store purchase made without an account from
// view, logging in would tie it to a throwaway user.
if (!hasAccount(session.user)) return;
await logInWithSupabaseUserId(session.user.id, performSync: false);
}

View File

@@ -1,3 +1,4 @@
import 'package:bike_control/utils/auth/account_session.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -22,8 +23,9 @@ class WindowsStripeService {
WindowsStripeService(this._supabase);
/// Check if the user is logged in
bool get isLoggedIn => _supabase.auth.currentSession != null;
/// Check if the user is signed into a real account. An anonymous
/// support-chat session doesn't count: a checkout must never be tied to it.
bool get isLoggedIn => hasAccount(_supabase.auth.currentSession?.user);
/// Get the current session
Session? get _session => _supabase.auth.currentSession;

View File

@@ -0,0 +1,134 @@
// Opening the support chat without an account creates an anonymous Supabase
// session. That session is not an account: a rider who bought Pro in the
// store (RevenueCat, never signed in) must keep Pro, and the anonymous user
// id must never become their RevenueCat identity.
import 'dart:convert';
import 'package:bike_control/utils/iap/iap_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
Map<String, dynamic> _sessionJson({required bool anonymous, String? email, String id = 'user-id'}) => {
'access_token': 'test-access-token',
'token_type': 'bearer',
'expires_in': 3600,
'refresh_token': 'test-refresh-token',
'user': {
'id': id,
'aud': 'authenticated',
'created_at': '2026-08-24T00:00:00Z',
'app_metadata': <String, dynamic>{},
'user_metadata': <String, dynamic>{},
'is_anonymous': anonymous,
if (email != null) 'email': email,
},
};
User _user({required bool anonymous, String? email, String id = 'user-id'}) =>
User.fromJson(_sessionJson(anonymous: anonymous, email: email, id: id)['user'] as Map<String, dynamic>)!;
IAPManager get iap => IAPManager.instance;
GoTrueClient get auth => Supabase.instance.client.auth;
Future<void> main() async {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
await Supabase.initialize(
url: 'http://127.0.0.1:9',
anonKey: 'iap-manager-test-anon-key',
debug: false,
authOptions: const FlutterAuthClientOptions(
localStorage: EmptyLocalStorage(),
detectSessionInUri: false,
autoRefreshToken: false,
),
);
});
group('store-bought Pro with an anonymous support-chat session', () {
setUp(() => iap.setProForTesting(enabled: true));
tearDown(() => iap.setProForTesting(enabled: false));
test('is not logged in', () async {
await auth.recoverSession(jsonEncode(_sessionJson(anonymous: true, email: '')));
expect(iap.isLoggedIn, isFalse);
});
test('keeps Pro', () async {
await auth.recoverSession(jsonEncode(_sessionJson(anonymous: true, email: '')));
expect(iap.hasActiveSubscription, isTrue);
expect(iap.isProEnabled, isTrue);
expect(iap.isProEnabledForCurrentDevice, isTrue);
});
test('a real account is logged in and no longer uses the local store entitlement', () async {
await auth.recoverSession(jsonEncode(_sessionJson(anonymous: false, email: 'rider@example.com')));
expect(iap.isLoggedIn, isTrue);
// No server entitlement cached for this account in the test.
expect(iap.isProEnabledForCurrentDevice, isFalse);
});
});
group('revenueCatLogin', () {
test('never logs RevenueCat in as an anonymous user', () {
for (final event in AuthChangeEvent.values) {
expect(
IAPManager.revenueCatLogin(
event: event,
user: _user(anonymous: true, email: ''),
previousUserId: null,
),
isNull,
reason: '$event',
);
}
});
test('does nothing without a user', () {
expect(
IAPManager.revenueCatLogin(event: AuthChangeEvent.signedIn, user: null, previousUserId: null),
isNull,
);
});
test('logs an account in and syncs on a fresh sign-in or launch', () {
final user = _user(anonymous: false, email: 'rider@example.com');
for (final event in [AuthChangeEvent.signedIn, AuthChangeEvent.initialSession]) {
expect(
IAPManager.revenueCatLogin(event: event, user: user, previousUserId: 'user-id'),
(userId: 'user-id', performSync: true),
);
}
});
test('a token refresh for the same account logs in without syncing', () {
expect(
IAPManager.revenueCatLogin(
event: AuthChangeEvent.tokenRefreshed,
user: _user(anonymous: false, email: 'rider@example.com'),
previousUserId: 'user-id',
),
(userId: 'user-id', performSync: false),
);
});
test('an anonymous session that just became an account (email linked) syncs', () {
// Linking keeps the user id but fires userUpdated, not signedIn, and the
// anonymous phase never logged RevenueCat in.
expect(
IAPManager.revenueCatLogin(
event: AuthChangeEvent.userUpdated,
user: _user(anonymous: false, email: 'rider@example.com'),
previousUserId: null,
),
(userId: 'user-id', performSync: true),
);
});
});
}