fix(compras): revocar el PRO tras un reembolso sin penalizar a quien pago
Build & Deploy PluriWave / Análisis de código (push) Successful in 41s
Build & Deploy PluriWave / Build APK + AAB release (push) Successful in 4m8s

Verificacion silenciosa en segundo plano con queryPastPurchases, al abrir o
volver a la app y al cargar Android Auto. Solo revoca tras dos respuestas
validas de Play sin la compra separadas 12h; sin red o con error no toca nada.
Reactiva el PRO automaticamente si Play confirma la compra.
This commit is contained in:
Javier Bautista Fernández
2026-09-18 11:45:43 +02:00
parent d7366bbf99
commit 0b7919e72e
14 changed files with 1163 additions and 17 deletions
+38
View File
@@ -20,6 +20,7 @@ import 'emisoras_destacadas.dart';
import 'musica_local_auto.dart';
import 'navegacion_auto.dart';
import 'servicio_audio_session.dart';
import 'verificacion_licencia.dart' show CambioLicencia;
/// Estado de reproducción expuesto al UI.
enum EstadoReproduccion {
@@ -383,6 +384,36 @@ void invalidarArbolAuto() {
_invalidarArbolAutoGlobal?.call();
}
/// Silent license re-verification for the headless Android Auto engine,
/// registered from `main.dart` (it owns the purchase port and the prefs).
/// `null` until registered — [dispararVerificacionLicenciaAuto] is then a
/// no-op.
Future<CambioLicencia> Function()? _verificarLicenciaAutoGlobal;
/// Registers (or, with `null`, clears) the verification
/// [dispararVerificacionLicenciaAuto] runs. Module-level like every other
/// `registrar*` seam here, so tests need no real handler.
void registrarVerificacionLicenciaAuto(
Future<CambioLicencia> Function()? verificar,
) {
_verificarLicenciaAutoGlobal = verificar;
}
/// Runs the registered license check and, if it changed the persisted flag
/// in either direction, invalidates the cached car tree (local music is
/// premium-gated). Never throws. The browse path calls it UNAWAITED so a
/// head unit's browse answer is never delayed by a Play query.
Future<void> dispararVerificacionLicenciaAuto() async {
final verificar = _verificarLicenciaAutoGlobal;
if (verificar == null) return;
try {
final cambio = await verificar();
if (cambio != CambioLicencia.sinCambios) invalidarArbolAuto();
} catch (e) {
debugPrint('[PluriWave][licencia] verificacion Auto fallida $e');
}
}
/// Whether a head unit has actually SUBSCRIBED to at least one browse id on
/// the live handler (fix/android-auto-musica-local, item 4 — corrected).
///
@@ -3472,6 +3503,13 @@ class PluriWaveAudioHandler extends BaseAudioHandler
// [resolverLocalizacionesRespaldo], so this works on the engine
// Android Auto starts without an Activity -- which is the only engine
// a Play reviewer ever gets.
// Silent license re-verification (refund revocation), on the root
// only — every car connection asks for it — and fire-and-forget: the
// browse answer below is served from the persisted flag right away,
// and the check is throttled to at most once a day.
if (parentMediaId == AudioService.browsableRootId) {
unawaited(dispararVerificacionLicenciaAuto());
}
final etiquetas = etiquetasArbolAutoDesde(_textos);
final constructor = ConstructorArbolAuto(etiquetas: etiquetas);
// The "recent" root, resolved BEFORE the entitlement gate.
+96 -2
View File
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
/// Outcome kinds the purchase stream can report (Design ADR-2). Mirrors
/// `in_app_purchase`'s [PurchaseStatus] but stays a PluriWave-owned type so
@@ -38,6 +39,25 @@ class EventoCompra {
final String? mensaje;
}
/// Outcome of the SILENT ownership query ([PuertoCompras.consultarPropiedad])
/// used to re-verify the persisted premium flag (refund revocation).
///
/// Only [poseida] and [noPoseida] are definitive answers from Play; anything
/// that is not a clean answer (offline, billing unavailable, query error,
/// exception, timeout, pending purchase) is [desconocido], which the
/// verification policy treats as "change nothing" (fail-open, ADR-2).
enum ResultadoVerificacionLicencia {
/// Play reports the premium product as purchased on this account.
poseida,
/// Play answered successfully and the premium product is NOT among the
/// account's purchases (e.g. refunded or revoked).
noPoseida,
/// No trustworthy answer — never used to revoke.
desconocido,
}
/// Purchase I/O abstraction (Design ADR-2): [EstadoEntitlement] depends on
/// this port, never on `in_app_purchase` directly — matches
/// `EstadoAlarmas(android: PuertoAlarmasAndroid)`'s injection shape, and
@@ -55,13 +75,24 @@ abstract class PuertoCompras {
/// Re-queries Play Billing for a prior purchase on this account.
Future<void> restaurar();
/// Silently asks the store whether this account currently owns the
/// premium product. Unlike [restaurar], it NEVER emits on [eventos] (the
/// premium sheet listens there) and never throws: every failure maps to
/// [ResultadoVerificacionLicencia.desconocido].
Future<ResultadoVerificacionLicencia> consultarPropiedad();
}
/// The SOLE `in_app_purchase` call site (Design ADR-2) — every other file
/// depends on [PuertoCompras] instead.
class ServicioComprasPlayBilling implements PuertoCompras {
ServicioComprasPlayBilling({InAppPurchase? inAppPurchase})
: _iap = inAppPurchase ?? InAppPurchase.instance {
ServicioComprasPlayBilling({
InAppPurchase? inAppPurchase,
Future<QueryPurchaseDetailsResponse> Function()? consultarComprasPasadas,
Duration limiteConsultaPropiedad = const Duration(seconds: 10),
}) : _iap = inAppPurchase ?? InAppPurchase.instance,
_consultarComprasPasadasInyectada = consultarComprasPasadas,
_limiteConsultaPropiedad = limiteConsultaPropiedad {
_sub = _iap.purchaseStream.listen(
_alRecibirCompras,
onError: (Object error) {
@@ -77,6 +108,15 @@ class ServicioComprasPlayBilling implements PuertoCompras {
static const idProducto = 'pluriwave_premium';
final InAppPurchase _iap;
/// Test seam for [consultarPropiedad]; `null` in production, where the
/// Android platform addition's `queryPastPurchases` is used.
final Future<QueryPurchaseDetailsResponse> Function()?
_consultarComprasPasadasInyectada;
/// Upper bound for [consultarPropiedad]: a hung BillingClient connection
/// resolves to [ResultadoVerificacionLicencia.desconocido].
final Duration _limiteConsultaPropiedad;
final _eventos = StreamController<EventoCompra>.broadcast();
StreamSubscription<List<PurchaseDetails>>? _sub;
@@ -125,6 +165,33 @@ class ServicioComprasPlayBilling implements PuertoCompras {
}
}
@override
Future<ResultadoVerificacionLicencia> consultarPropiedad() async {
try {
final disponible = await _iap.isAvailable().timeout(
_limiteConsultaPropiedad,
);
if (!disponible) return ResultadoVerificacionLicencia.desconocido;
final consultar =
_consultarComprasPasadasInyectada ??
() =>
_iap
.getPlatformAddition<InAppPurchaseAndroidPlatformAddition>()
.queryPastPurchases();
// `queryPastPurchases` reads the account's purchases straight from
// the BillingClient: unlike `restorePurchases` it does NOT push them
// into `purchaseStream`, so the premium sheet never sees this check.
final respuesta = await consultar().timeout(_limiteConsultaPropiedad);
return resultadoDesdeComprasPasadas(
respuesta.pastPurchases,
conError: respuesta.error != null,
);
} catch (e) {
debugPrint('[PluriWave][compras] consultarPropiedad -> desconocido $e');
return ResultadoVerificacionLicencia.desconocido;
}
}
void _alRecibirCompras(List<PurchaseDetails> compras) {
if (compras.isEmpty) {
// `restorePurchases()` with nothing to restore pushes an EMPTY batch
@@ -176,6 +243,33 @@ EventoCompra eventoDesdeEstadoCompra(PurchaseStatus status, {String? mensaje}) {
};
}
/// Pure mapping from a `queryPastPurchases` answer to the typed ownership
/// result (same port-boundary rationale as [eventoDesdeEstadoCompra]).
///
/// The premium product present as purchased/restored is proof of ownership
/// even when the answer also carries an error (the query spans in-app AND
/// subscriptions, and a failure of the latter is irrelevant here). A pending
/// entry is not a clean answer. Absence only counts as [noPoseida] when the
/// query succeeded without error.
ResultadoVerificacionLicencia resultadoDesdeComprasPasadas(
List<PurchaseDetails> compras, {
required bool conError,
}) {
final delProducto = compras.where(
(c) => c.productID == ServicioComprasPlayBilling.idProducto,
);
final comprada = delProducto.any(
(c) =>
c.status == PurchaseStatus.purchased ||
c.status == PurchaseStatus.restored,
);
if (comprada) return ResultadoVerificacionLicencia.poseida;
if (conError || delProducto.isNotEmpty) {
return ResultadoVerificacionLicencia.desconocido;
}
return ResultadoVerificacionLicencia.noPoseida;
}
extension<T> on List<T> {
T? get firstOrNull => isEmpty ? null : first;
}
+218
View File
@@ -0,0 +1,218 @@
import 'dart:async';
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:shared_preferences/shared_preferences.dart';
import 'servicio_compras.dart';
export 'servicio_compras.dart' show ResultadoVerificacionLicencia;
/// Versioned persistence key (Design ADR-1) of the permanent, non-consumable
/// premium unlock. Owned here so the headless verification below and
/// `EstadoEntitlement` read/write exactly ONE key.
const claveCompraPremium = 'compra_premium_v1';
/// Epoch millis of the last verification that got a DEFINITIVE answer
/// ([ResultadoVerificacionLicencia.poseida] / [noPoseida]).
const claveUltimaVerificacionLicencia = 'licencia_ultima_verificacion_ms';
/// Epoch millis of the last ATTEMPT, whatever its outcome.
const claveUltimoIntentoLicencia = 'licencia_ultimo_intento_ms';
/// Consecutive definitive "not owned" answers while the flag was premium.
const claveAusenciasLicencia = 'licencia_ausencias_consecutivas';
/// Epoch millis of the FIRST absence of the current streak.
const clavePrimeraAusenciaLicencia = 'licencia_primera_ausencia_ms';
/// After a definitive answer, Play is not asked again for this long.
const intervaloVerificacionLicencia = Duration(hours: 24);
/// After an attempt without a definitive answer (offline, billing
/// unavailable, error), the retry waits at least this long, so resuming the
/// app or reconnecting the car while offline never hammers Play.
const intervaloReintentoLicencia = Duration(hours: 1);
/// Minimum time between the first absence and the one that confirms it —
/// a transient empty Play Store cache must never revoke a paying user.
const separacionMinimaAusencias = Duration(hours: 12);
/// Definitive absences required (spaced by [separacionMinimaAusencias])
/// before the premium flag is revoked.
const ausenciasParaRevocar = 2;
/// What a [verificarLicencia] run changed in the persisted flag.
enum CambioLicencia {
/// Nothing changed (throttled, unknown answer, or state already right).
sinCambios,
/// The flag went false -> true (e.g. a reinstall of a paying user).
desbloqueada,
/// The flag went true -> false (refund confirmed twice, spaced apart).
revocada,
}
/// The run currently in flight, shared by every caller in this isolate
/// (phone UI and Android Auto), so only ONE ownership query runs at a time.
Future<CambioLicencia>? _verificacionEnCurso;
/// Silent, headless-safe license re-verification (refund revocation).
///
/// No `BuildContext`, no purchase-stream events, never throws, and every
/// non-definitive outcome leaves the persisted state untouched (fail-open,
/// ADR-2) — PRO is never removed for lack of connectivity. Callers fire and
/// forget it; it must never sit on a startup or browse path.
///
/// Rules:
/// * throttled by [intervaloVerificacionLicencia] after a definitive answer
/// and by [intervaloReintentoLicencia] after any attempt; a clock that
/// went backwards never blocks it;
/// * [ResultadoVerificacionLicencia.poseida]: flag forced to `true` (silent
/// unlock if it was `false`), absence streak cleared;
/// * [ResultadoVerificacionLicencia.noPoseida] with the flag `true`: the
/// streak grows, and the flag is revoked only once it reaches
/// [ausenciasParaRevocar] AND at least [separacionMinimaAusencias] passed
/// since its first absence; with the flag `false` there is nothing to do;
/// * [ResultadoVerificacionLicencia.desconocido] (or an exception): nothing
/// changes, not even the streak.
Future<CambioLicencia> verificarLicencia({
required Future<ResultadoVerificacionLicencia> Function() consultar,
SharedPreferences? prefs,
DateTime Function()? reloj,
}) {
final enCurso = _verificacionEnCurso;
if (enCurso != null) return enCurso;
final ejecucion = _verificar(
consultar: consultar,
prefs: prefs,
reloj: reloj ?? DateTime.now,
);
_verificacionEnCurso = ejecucion;
unawaited(
ejecucion.whenComplete(() {
if (identical(_verificacionEnCurso, ejecucion)) {
_verificacionEnCurso = null;
}
}),
);
return ejecucion;
}
/// Clears the absence streak — a real purchase/restore is fresh proof of
/// ownership, so a stale streak must not survive it.
Future<void> reiniciarAusenciasLicencia(SharedPreferences prefs) async {
await prefs.remove(claveAusenciasLicencia);
await prefs.remove(clavePrimeraAusenciaLicencia);
}
Future<CambioLicencia> _verificar({
required Future<ResultadoVerificacionLicencia> Function() consultar,
required SharedPreferences? prefs,
required DateTime Function() reloj,
}) async {
try {
final p = prefs ?? await SharedPreferences.getInstance();
final ahora = reloj();
if (_dentroDeVentana(
p,
claveUltimaVerificacionLicencia,
ahora,
intervaloVerificacionLicencia,
) ||
_dentroDeVentana(
p,
claveUltimoIntentoLicencia,
ahora,
intervaloReintentoLicencia,
)) {
return CambioLicencia.sinCambios;
}
await p.setInt(claveUltimoIntentoLicencia, ahora.millisecondsSinceEpoch);
ResultadoVerificacionLicencia resultado;
try {
resultado = await consultar();
} catch (e) {
debugPrint('[PluriWave][licencia] consulta fallida -> sin cambios $e');
resultado = ResultadoVerificacionLicencia.desconocido;
}
switch (resultado) {
case ResultadoVerificacionLicencia.desconocido:
return CambioLicencia.sinCambios;
case ResultadoVerificacionLicencia.poseida:
await p.setInt(
claveUltimaVerificacionLicencia,
ahora.millisecondsSinceEpoch,
);
await reiniciarAusenciasLicencia(p);
if (p.getBool(claveCompraPremium) ?? false) {
return CambioLicencia.sinCambios;
}
await p.setBool(claveCompraPremium, true);
return CambioLicencia.desbloqueada;
case ResultadoVerificacionLicencia.noPoseida:
await p.setInt(
claveUltimaVerificacionLicencia,
ahora.millisecondsSinceEpoch,
);
if (!(p.getBool(claveCompraPremium) ?? false)) {
await reiniciarAusenciasLicencia(p);
return CambioLicencia.sinCambios;
}
return _registrarAusencia(p, ahora);
}
} catch (e) {
// Fail-open (ADR-2): a prefs failure never touches the entitlement.
debugPrint('[PluriWave][licencia] verificacion fallida -> sin cambios $e');
return CambioLicencia.sinCambios;
}
}
Future<CambioLicencia> _registrarAusencia(
SharedPreferences p,
DateTime ahora,
) async {
final ausencias = (p.getInt(claveAusenciasLicencia) ?? 0) + 1;
final primeraMs = p.getInt(clavePrimeraAusenciaLicencia);
if (primeraMs == null || ausencias == 1) {
await p.setInt(claveAusenciasLicencia, 1);
await p.setInt(clavePrimeraAusenciaLicencia, ahora.millisecondsSinceEpoch);
return CambioLicencia.sinCambios;
}
final separacion = ahora.difference(
DateTime.fromMillisecondsSinceEpoch(primeraMs),
);
if (separacion.isNegative) {
// The clock went backwards: restart the spacing from now (delays the
// revocation, never hastens it).
await p.setInt(clavePrimeraAusenciaLicencia, ahora.millisecondsSinceEpoch);
await p.setInt(claveAusenciasLicencia, ausencias);
return CambioLicencia.sinCambios;
}
if (ausencias >= ausenciasParaRevocar &&
separacion >= separacionMinimaAusencias) {
await p.setBool(claveCompraPremium, false);
await reiniciarAusenciasLicencia(p);
return CambioLicencia.revocada;
}
await p.setInt(claveAusenciasLicencia, ausencias);
return CambioLicencia.sinCambios;
}
/// Whether [clave]'s timestamp is less than [ventana] before [ahora]. A
/// timestamp in the future (clock moved backwards) does NOT throttle.
bool _dentroDeVentana(
SharedPreferences p,
String clave,
DateTime ahora,
Duration ventana,
) {
final ms = p.getInt(clave);
if (ms == null) return false;
final transcurrido = ahora.difference(
DateTime.fromMillisecondsSinceEpoch(ms),
);
return !transcurrido.isNegative && transcurrido < ventana;
}