Files
buzz/mobile/lib/hosted_app_gate.dart
Tom Brow db4478e8d2 feat(mobile): organization sign-in for NIP-FI relays (#8700)
Block is turning on NIP-FI enforcement on the Block relay. Desktop gets
organization sign-in in block/buzz-app#1424. Mobile can already attach
NIP-FI assertions, but only for Builderlab-hosted communities, through
the build's single Builderlab account. The dogfood build needs that
account for public hosted communities, so it can't simply be pointed at
the Block tenant.

This adds a separate **organization realm**, configured at build time:

- `BUZZ_ORGANIZATION_URL`: the tenant's HTTPS origin (for example
`https://block.builderlab.xyz`).
- `BUZZ_ORGANIZATION_RELAYS`: the exact relay hosts that trust that
tenant.

The two must be set together. The app refuses to start if they're
malformed, overlap a hosted community, or reuse the hosted origin.
Without them, nothing changes.

For a configured relay:

- The app keeps its own organization session and signs in through the
browser at the tenant's existing login (`/api/goose/v1/auth/login`).
Block SSO happens there.
- It requests assertions from the same `/v1/buzz/identity/assertions`
route that hosted communities use, and attaches them to the relay
socket, HTTP, media, huddle and remote-agent requests.
- Unlike the hosted path, it doesn't require an identity backup before
the first binding. As on desktop, the tenant binds the member's existing
key on first issuance. A key already bound to a different one is refused
before any request is sent.
- When signed out, it connects without an assertion and lets the relay
decide. A bottom banner offers **Sign in**. After sign-in, the relay
reconnects with a fresh assertion. Hosted communities keep their
existing banner and flow.

The tenant accepts only the registered
`xyz.block.buzz.mobile:/auth/callback` return URL, so both realms share
it. Each `BrowserAuth` owner leaves callbacks whose `state` belongs to
another owner's attempt to that owner.

### Before merge

- [ ] Kenny Lopez reviews the visible changes.

### Validation

Added tests (`organization_relay_auth_test.dart`):

- Configuration parsing and exact host matching.
- An assertion is issued for the exact relay and key, then cached.
- A different bound key is refused.
- Signed out connects without an assertion.
- Other relays never receive the assertion.
- The shared callback is routed between the hosted and organization
owners.

Full `mobile-check` and `mobile-test` pass. RunnerTests pass locally
except `testNativeNavigationTitleExpandsAgainAtTop`, which this PR
doesn't touch.

Added tests (`organization_sign_in_test.dart`,
`relay_auth_isolation_test.dart`, `builderlab_account_test.dart`), each
failing without its fix:

- Concurrent account restores at cold start share one adopted account.
- An exchange from a cancelled attempt never changes a newer sign-in.
- Storage failures while clearing the intent or cancelling leave the
busy state.
- An unreadable saved organization session is replaced by signing in
again.
- A stalled organization issuer never delays a hosted relay's assertion.
This test needs `BUZZ_AUTH_DOMAINS` and skips without it. CI's
configured-auth-domains step doesn't list it yet, because that workflow
change needs a token with `workflow` scope.

Added tests also cover a restore after an offline start (the banner
clears once a relay retry restores the session) and the iOS bridge
allowlist (`/auth/native` and tenant login on Builderlab subdomains;
other hosts, paths, ports, userinfo and fragments refused).

Simulator (iPhone 17, iOS 27) with the dogfood defines against the
production Block relay `buzz.block.builderlab.xyz`, on a WARP Mac:

- The app starts with the organization configuration and connects to the
relay while signed out, showing the organization **Sign in** banner.
- **Sign in** opens the system sign-in session for
`block.builderlab.xyz`, and the banner shows **Finishing organization
sign-in…**. Cancelling returns to **Sign in** with no error. Before the
bridge fix, no browser opened and the banner reported that sign-in did
not finish.
- The bottom banners (organization sign-in, hosted reconnect, and the
sign-in recovery row) now sit above Home's floating Search/New bar,
which used to cover **Sign in**. A journey test checks the banner clears
the bar, and fails without the fix.

![Home with the organization sign-in banner above the floating
bar](https://github.com/user-attachments/assets/c6ab74f4-3d88-4fe0-ae16-042a548056fe)
- The simulator run stopped at the system consent prompt (SSO does not
work in the simulator). The app calls were driven through the VM service
(the same `signIn()`/`cancel()` the banner buttons call) because the
simulator could not be tapped.

Device (iPhone 12 mini) against bb-block staging in enforce mode, where
every probe without an assertion gets 401:

- Signed out, the organization banner shows and the app stays
responsive. Cancel at the consent prompt returns to **Sign in**, and
retry works.
- Block SSO through Okta completes, and the relay admits the reconnect
with the assertion.
- After relaunch the app connects, loads channel history, and shows no
banner for over 60 seconds.
- Before the restore fix, 2 of 4 cold starts showed "cannot use this
community with this key" although the session was valid. With it, 8 of 8
cold starts connected.

Known limitation: adding an enforcing organization relay by community
link is tracked in #8791.

The dogfood build enables this in squareup/buzz-releases
(`tomb/dogfood-organization-sign-in`). App Store builds stay unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 07:23:12 -08:00

212 lines
7.9 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'features/channels/deep_link_dispatcher.dart';
import 'features/profile/profile_setup_page.dart';
import 'features/onboarding/hosted_connect_page.dart';
import 'features/onboarding/self_hosted_entry_sheet.dart';
import 'shared/auth/auth.dart';
import 'shared/theme/grid.dart';
import 'shared/theme/theme_extensions.dart';
import 'shared/widgets/mobile_tab_footer_backdrop.dart';
import 'shared/deeplink/deep_link.dart';
import 'shared/hosted/hosted_community_connection.dart';
import 'shared/hosted/hosted_flow.dart';
import 'shared/hosted/hosted_environment.dart';
import 'features/onboarding/hosted_reconnect_banner.dart';
import 'features/onboarding/organization_sign_in_banner.dart';
import 'shared/hosted/hosted_flow_provider.dart';
import 'shared/hosted/organization_sign_in.dart';
/// Composition seam shared by signed-in and signed-out application states.
class HostedAppGate extends HookConsumerWidget {
const HostedAppGate({
super.key,
required this.child,
required this.authenticated,
});
final Widget child;
final bool authenticated;
@override
Widget build(BuildContext context, WidgetRef ref) {
final flow = HostedEnvironment.enabled
? ref.watch(hostedFlowProvider)
: null;
useListenable(flow);
useEffect(() {
if (flow == null) return null;
void onFlowChanged() {
if (flow.stage == HostedFlowStage.complete) {
ref.read(hostedInlineEntryProvider.notifier).setActive(false);
}
}
flow.addListener(onFlowChanged);
unawaited(flow.initialize());
return () => flow.removeListener(onFlowChanged);
}, [flow]);
final inlineEntry = ref.watch(hostedInlineEntryProvider);
// Create the organization's browser owner before any callback is handled.
ref.watch(organizationSignInProvider);
final visible =
flow != null &&
flow.stage != HostedFlowStage.idle &&
flow.stage != HostedFlowStage.complete;
// Native browser authentication presents its own alert over the current
// screen. Keep that screen in place while checking the session/opening it.
final openingSignIn =
flow != null &&
(flow.stage == HostedFlowStage.signIn ||
(flow.accountOnly &&
flow.stage == HostedFlowStage.working &&
flow.account.account == null));
final fullScreenSetup = visible && !openingSignIn;
return DeepLinkDispatcher(
dispatchMessageLinks: authenticated && !visible,
onboardingHandler: (routeContext, link) async {
final relay = link.relayUrl;
if (relay != null) {
final host = Uri.parse(relay).host.toLowerCase();
final requiresAuth = HostedEnvironment.requiresAuth(host);
if (link is InviteDeepLink && !requiresAuth) return false;
final communities = await ref
.read(communityStorageProvider)
.loadAll();
final existing = communities
.where(
(item) => relayIdentity(item.relayUrl) == relayIdentity(relay),
)
.firstOrNull;
if (existing != null &&
!(existing.starterSetupIncomplete && requiresAuth)) {
await ref
.read(communityListProvider.notifier)
.switchCommunity(existing.id);
if (context.mounted) {
ref.read(communityEntryCompletionProvider.notifier).complete();
}
return true;
}
if (!requiresAuth && link is AddCommunityDeepLink) {
if (routeContext.mounted) {
final joined = await showSelfHostedEntry(
routeContext,
relay: link.relayUrl,
name: link.name,
fullScreen: inlineEntry,
);
if (joined && context.mounted) {
ref.read(communityEntryCompletionProvider.notifier).complete();
}
}
return true;
}
if (requiresAuth &&
!HostedEnvironment.supportsRelay(Uri.parse(relay))) {
if (routeContext.mounted) {
await showDialog<void>(
context: routeContext,
builder: (context) => AlertDialog(
title: const Text('Community setup unavailable'),
content: const Text(
'This community needs a different or unsupported Builderlab environment. Use an app build configured for this community.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
),
],
),
);
}
return true;
}
}
if (flow == null) return false;
await flow.start(link);
return true;
},
child: Stack(
fit: StackFit.expand,
children: [
ExcludeFocus(
excluding: fullScreenSetup,
child: ExcludeSemantics(
excluding: fullScreenSetup,
child: Offstage(offstage: fullScreenSetup, child: child),
),
),
if (fullScreenSetup) ColoredBox(color: context.colors.surface),
// These overlays only show over Home, so keep them above its
// floating tab bar.
Positioned.fill(
child: MediaQuery(
data: MediaQuery.of(context).copyWith(
padding: MediaQuery.paddingOf(
context,
).copyWith(bottom: mobileTabBarTop(context) + Grid.xxs),
),
child: Stack(
// Banners with their own Stack need the full layer to place
// bottom-anchored content inside hit-testable bounds.
fit: StackFit.expand,
children: [
if (authenticated && !visible)
const OrganizationSignInBanner(),
if (flow != null && authenticated && !visible)
HostedReconnectBanner(flow: flow),
if (flow != null &&
flow.stage == HostedFlowStage.signIn &&
authenticated &&
!inlineEntry)
Positioned(
left: Grid.sm,
right: Grid.sm,
bottom: 0,
child: SafeArea(
child: Material(
color: Colors.transparent,
child: Wrap(
alignment: WrapAlignment.center,
children: [
TextButton(
onPressed: flow.retry,
child: const Text('Start login again'),
),
TextButton(
onPressed: flow.leave,
child: Text(
flow.reconnecting
? 'Cancel sign-in'
: 'Leave setup',
),
),
],
),
),
),
),
],
),
),
),
if (flow != null) ...[
if (fullScreenSetup)
HostedConnectPage(
flow: flow,
onClose: () => unawaited(flow.leave()),
profileBuilder: (_) => ProfileSetupPage(flow: flow),
),
],
],
),
);
}
}