Files
buzz/mobile/lib/hosted_app_gate.dart
Tom Brow 12f3d51001 feat(mobile): one Builderlab per build, internal and public distributions (#9224)
The mobile app can now be built as a public build or an internal build,
set explicitly with `BUZZ_DISTRIBUTION=internal|public`. Each build
trusts exactly one Builderlab (`BUZZ_BUILDERLAB_URL`), and sends that
Builderlab's relay assertions only to the relays in
`BUZZ_BUILDERLAB_RELAYS`. The three settings are set together or not at
all; with none set, the app is a Nostr-only development build. The
decision is recorded in
`docs/adr/0001-internal-and-public-mobile-builds.md`, and the terms are
defined in `CONTEXT.md`.

Before this change, one build supported a public Builderlab and an
organization Builderlab at the same time, with two sessions. An
organization's members could reach public communities from the
organization's app.

### Behavior

- **Public build:** QR pairing, email sign-in and multiple communities
are unchanged. It has no knowledge of any organization. An
organization's relay already rejects clients that can't present its
Builderlab's assertion, and the public build relies on that.
- **Internal build:** the first screen has a single **Sign in** button
that goes straight to the organization's single sign-on and then joins
the organization's community. There is no QR pairing, community link or
community creation, and the community switcher is hidden. Only the exact
relay hosts listed in `BUZZ_BUILDERLAB_RELAYS` are reachable.
- **Identity (internal):** a member whose account has no Nostr identity
yet gets a new key on first sign-in; the first relay assertion binds it,
and the app backs it up to the organization automatically. A member
whose account is already bound uses that key from this device, or
restores it from the organization's backup. If neither is possible, Sign
in says it couldn't restore the identity and saves nothing.
- **Sign-out (internal):** a destructive **Sign out** row at the bottom
of Settings, the build's only way out. It removes the community, closes
Settings and returns to Sign in. The Builderlab session is cleared from
storage immediately and can never be reused to sign back in. The relay
push-stop keeps the retired credential in memory only, for up to 10
minutes, and uses it only to get an assertion for a key that is already
bound. It is a best-effort request.
- **Upgrade to an internal build:** a saved public Builderlab session is
cleared. Communities on other relays are hidden, not deleted, and their
keys stay on the device.
- `BUZZ_HOSTED_RELAY_AUTH` is unchanged here.

### Screenshots (internal build)

| Sign in | Community menu | Settings |
| --- | --- | --- |
| ![Internal build landing with a single Sign in
button](https://github.com/user-attachments/assets/05f076a2-1552-4095-8322-626754a8765b)
| ![Community menu with Agents, Appearance and Settings, without Switch
community](https://github.com/user-attachments/assets/0c0cf4e0-3fa9-458e-817f-b4665374505b)
| ![Settings ending with a red Sign out
row](https://github.com/user-attachments/assets/f3d60dc1-8170-45e3-a16d-0a1156fdae1a)
|

Gateway-side push revocation, which needs no Builderlab session, is
planned as a separate PR.

### Validation

Added tests:
- An internal-build journey: one Sign in creates and binds a key, and a
retry after a cancelled join reuses it. The app uploads that key's
backup itself. Sign out from Settings closes it and returns to the
landing, which ends the session, and Sign in then restores the same
identity from the backup. Communities on other relays stay stored but
hidden.
- Internal Sign in for a bound account: the key on this device, a key
restored from backup, and no backup (clear error, nothing saved). Each
guard was shown to fail when removed.
- Organization relay assertions: assertions go only to exact listed
hosts, not subdomains. After sign-out, only a push stop for a bound key
gets an assertion, and nothing can sign back in. Proven to fail without
the fix.
- Builderlab build setting parsing.

CI runs the internal and public journeys in their own lanes with those
settings. The full suite passes in the default configuration. The full
suite isn't meant to run under the internal configuration, because most
fixtures use relays that an internal build hides.

Automated full-app run on an iPhone 17 Pro simulator at the current
head:
- Public build, upgraded in place over a signed-in install: home loads,
a channel opens and a message sends.
- Internal build: a fresh install shows only Sign in. With a saved
organization community, the community menu has no Switch community, and
Settings → Sign out → confirm returns to Sign in.

Real single sign-on can't run in the simulator.

🤖 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: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-06 21:27:14 -08:00

251 lines
9.2 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 'shared/hosted/hosted_relay_auth.dart';
import 'shared/hosted/organization_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);
useEffect(() {
// An internal build keeps one Builderlab session: drop any public
// session a previous build saved. Its communities stay stored, hidden.
if (OrganizationEnvironment.enabled) {
unawaited(
ref
.read(builderlabAccountProvider)
.clearLocalSession()
.catchError(
(Object error) => debugPrint('Public session cleanup: $error'),
),
);
}
return null;
}, const []);
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 &&
OrganizationEnvironment.enabled &&
!OrganizationEnvironment.protects(Uri.parse(relay))) {
if (routeContext.mounted) {
await showDialog<void>(
context: routeContext,
builder: (context) => AlertDialog(
title: const Text('Community unavailable'),
content: const Text(
'This app connects only to your organization’s community.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
),
],
),
);
}
return true;
}
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),
),
],
],
),
);
}
}