Apply a confirmed age restriction to Android push wakes (#9925)

Follow-up to [#9804 handle Android push
wakes](https://github.com/block/buzz/pull/9804), from its review: a
confirmed age restriction now applies to Android push wakes, as it
already does on iOS.

## What it does

- A new native `AgeRestriction` holds a confirmed restriction for the
life of the app process. Like the iOS restriction session, nothing is
saved: a later launch starts unrestricted and the age check runs again.
- The age gate's purge (`purgeAgeRestrictedNotifications`) now runs on
Android. It sets the restriction and cancels every notification Buzz has
posted. Restore (`restoreAgeRestrictedNotifications`) clears it. Both
were iOS-only before.
- On Android the restriction is released only when an age check in the
current engine finishes without restricting (allowed, or failing open).
The process can outlive the engine, for example after Back from the
restricted screen, and a reopened app starts its age state as allowed,
so releasing on that first build would lift a restriction the process
still holds before the new check answers. A retired check releases
nothing. iOS keeps restoring from the push bootstrap as before.
- The purge starts as soon as the age check confirms a restriction, not
when the restricted screen first draws. The check can answer while Buzz
is in the background, where Flutter draws no frames until the user
returns, so before this wakes kept posting until then. This also closes
the same gap on iOS. The restricted screen still retries a failed purge,
and a retry that a resume has replaced stays quiet, so a late failure
can't purge again.
- While the restriction holds, a push wake is skipped before it fetches
anything, the same way as when notifications are turned off.
- Every post from a wake (conversations and the generic "New activity")
checks the restriction under the same lock the purge takes. So a wake
already running when the restriction arrives posts nothing after the
purge, and a post already in progress finishes before the purge cancels
it.

## Decisions

- **Process lifetime, as on iOS.** Wakes run in the app's process, so an
in-memory flag covers every wake while the confirming process lives. A
wake that starts a fresh process (after the app was killed) is not
restricted until the app runs its check again. That matches iOS, where
the restriction ends with the process holding its lock.
- **No release-config change here.** `BUZZ_AGE_GATING_ENABLED` is still
set only for iOS builds, and no build sets the Firebase config yet.
Adding either to an Android build is a separate release change.

### Validation

Added tests:
[`AgeRestrictionTest.kt`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt)
covers restrict, release and a post that is in progress when the
restriction arrives.
[`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/shared/push/push_bridge_test.dart)
now covers the purge and restore calls on iOS and Android. The age
gate's outcome table now runs on Android and counts releases: none while
the check is pending, one after an adult, error, malformed or timed-out
result, none after a minor.


[`age_signal_provider_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_signal_provider_test.dart)'s
upper-bound table now also checks that a confirmed restriction starts
the purge with no widget or frame involved.
[`age_gate_app_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_gate_app_test.dart)'s
purge retry test now uses the real notifier, with a resume while the
first purge is still running.

On a Pixel 9a (Android 16), a debug build with a local test relay. A
temporary debug hook called the native restrict and release directly,
because the phone was locked and Flutter doesn't draw frames behind the
lock screen:

1. Allowed: a wake posted the new message.
2. Restrict: the posted notification was removed.
3. While restricted: a wake logged `wake ignored foreground=false
restricted=true` and posted nothing.
4. Release: the next wake posted both the message that arrived during
the restriction and the new one.

The Dart side calling purge and restore is covered by the bridge test
above.

## Regressions

None expected: without age gating enabled, the restriction is never set
on Android.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Tom Brow
2026-11-24 22:14:05 -08:00
committed by GitHub
parent 9bddaa1b64
commit 2f1be86525
12 changed files with 289 additions and 64 deletions

View File

@@ -4,6 +4,8 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/push/push_bridge.dart';
const ageSignalChannel = MethodChannel('buzz/age_signal');
/// Maximum lifetime of a launch age check. Access never waits for this timer.
@@ -27,6 +29,18 @@ bool shouldBlockForAgeSignal(Map<Object?, Object?> response) {
return upper is int && upper >= 0 && upper < 18;
}
/// Native notification purge performed once restriction is confirmed.
final ageRestrictedNotificationPurgerProvider =
Provider<Future<void> Function()>(
(ref) => purgeAgeRestrictedBuzzNotifications,
);
/// Releases only the current process's confirmed notification restriction.
final ageAllowedNotificationRestorerProvider =
Provider<Future<void> Function()>(
(ref) => restoreAgeRestrictedBuzzNotifications,
);
/// Access decision, independent of whether a platform check has completed.
enum AgeSignalState { allowed, restricted }
@@ -41,6 +55,7 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
final AgeSignalRequest _requestSignal;
final Duration _requestTimeout;
Future<void>? _attempt;
Future<bool>? _confirmedPurge;
int _generation = 0;
@override
@@ -49,6 +64,7 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
// later. A new provider lifecycle starts allowed, without cached denial.
_generation += 1;
_attempt = null;
_confirmedPurge = null;
ref.onDispose(() => _generation += 1);
return AgeSignalState.allowed;
}
@@ -56,6 +72,14 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
/// Checks once. Failure ends the attempt; neither retry nor cleanup gates UI.
Future<void> request() => _attempt ??= _check(++_generation);
/// Hands over, once, the purge started when restriction was confirmed.
/// Completes with whether it succeeded; its error is already reported.
Future<bool>? takeConfirmedPurge() {
final purge = _confirmedPurge;
_confirmedPurge = null;
return purge;
}
Future<void> _check(int generation) async {
try {
final response = await Future.sync(
@@ -67,6 +91,19 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
_generation += 1;
if (response != null && shouldBlockForAgeSignal(response)) {
state = AgeSignalState.restricted;
// The check can answer while Buzz is in the background, where no
// frame mounts the push cleanup until the user returns. Purge now,
// so wakes stop posting at once; the cleanup retries a failure.
_confirmedPurge =
Future.sync(ref.read(ageRestrictedNotificationPurgerProvider)).then(
(_) => true,
onError: (Object error, StackTrace stackTrace) {
reportPushLeaseCleanupError(error, stackTrace);
return false;
},
);
} else {
_releaseNativeRestriction();
}
} catch (error) {
if (generation != _generation) return;
@@ -76,8 +113,24 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
debugPrint(
'Age check unavailable (${error.runtimeType}); access allowed.',
);
_releaseNativeRestriction();
}
}
/// On Android a confirmed restriction lives in the process, which can
/// outlive this engine: reopening Buzz builds a new notifier that starts
/// allowed. So only a check that finishes here without restricting lifts
/// it, never the initial allowed state. iOS restores from the push
/// bootstrap instead.
void _releaseNativeRestriction() {
if (defaultTargetPlatform != TargetPlatform.android) return;
unawaited(
Future.sync(ref.read(ageAllowedNotificationRestorerProvider)).catchError(
(Object error, StackTrace stackTrace) =>
reportPushLeaseCleanupError(error, stackTrace),
),
);
}
}
/// Explicit pre-release testing opt-in. Production builds keep enforcement disabled.

View File

@@ -35,18 +35,6 @@ final ageSignalPushSnapshotRetryWaitProvider =
return Future<void>.delayed;
});
/// Releases only the current process's confirmed notification restriction.
final ageAllowedNotificationRestorerProvider =
Provider<Future<void> Function()>(
(ref) => restoreAgeRestrictedBuzzNotifications,
);
/// Native notification purge performed once restriction is confirmed.
final ageRestrictedNotificationPurgerProvider =
Provider<Future<void> Function()>(
(ref) => purgeAgeRestrictedBuzzNotifications,
);
/// Delay between successful maintenance purges while restriction remains active.
const ageRestrictedNotificationMaintenanceDelay = Duration(seconds: 30);
@@ -91,7 +79,13 @@ class AgeSignalPushBootstrap extends HookConsumerWidget {
previousState.value = state;
consecutiveFailures.value = 0;
}
if (state == AgeSignalState.restricted) return null;
// On Android the age check itself releases the restriction once it
// finishes allowed (see AgeSignalNotifier). Restoring here would lift a
// restriction the process still holds from an earlier engine.
if (state == AgeSignalState.restricted ||
defaultTargetPlatform == TargetPlatform.android) {
return null;
}
var cancelled = false;
unawaited(() async {
try {
@@ -156,7 +150,12 @@ class _AgeRestrictedPushCleanup extends HookConsumerWidget {
VoidCallback? cancelMaintenancePurge;
unawaited(() async {
try {
await purgeNotifications();
final confirmed = ref
.read(ageSignalProvider.notifier)
.takeConfirmedPurge();
final needsPurge = confirmed == null || !await confirmed;
if (cancelled) return;
if (needsPurge) await purgeNotifications();
consecutivePurgeFailures.value = 0;
if (!cancelled && remainingMaintenancePurges.value > 0) {
remainingMaintenancePurges.value -= 1;

View File

@@ -530,15 +530,20 @@ void reportPushLeaseCleanupError(Object error, StackTrace stackTrace) {
debugPrintStack(stackTrace: stackTrace);
}
/// Platforms whose native push code honors a confirmed age restriction.
bool get _ageRestrictionPlatform =>
defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.android;
/// Restores notification presentation without reading community storage.
Future<void> restoreAgeRestrictedBuzzNotifications() async {
if (defaultTargetPlatform != TargetPlatform.iOS) return;
if (!_ageRestrictionPlatform) return;
await _channel.invokeMethod<void>('restoreAgeRestrictedNotifications');
}
/// Removes notifications rendered before a confirmed age restriction.
Future<void> purgeAgeRestrictedBuzzNotifications() async {
if (defaultTargetPlatform != TargetPlatform.iOS) return;
if (!_ageRestrictionPlatform) return;
await _channel.invokeMethod<void>('purgeAgeRestrictedNotifications');
}