Files
buzz/mobile/lib/features/onboarding/self_hosted_entry_sheet.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

389 lines
14 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/auth/auth.dart';
import '../../shared/hosted/device_identity_source.dart';
import '../../shared/hosted/hosted_relay_auth.dart';
import '../../shared/relay/relay_provider.dart';
import '../../shared/hosted/self_hosted_entry.dart';
import '../../shared/identity_transfer/nsec_import_sheet.dart';
import '../../shared/identity_transfer/native_community_entry.dart';
import '../../shared/theme/theme.dart';
import '../../shared/hosted/hosted_environment.dart';
import 'saved_identity_card.dart';
import '../../shared/widgets/modal_presentation.dart';
import '../../shared/widgets/onboarding_step_page.dart';
import '../../shared/widgets/onboarding_loading_page.dart';
import '../../shared/widgets/buzz_titled_sheet_layout.dart';
/// The socket boundary every entry probe connects through.
final relayProbeProvider =
Provider<Future<void> Function(Community, Map<String, String>)>(
(ref) => SelfHostedEntry.probeRelay,
);
/// Local preparation seam; the production service validates and retains keys.
/// An organization relay refuses the upgrade without the session's assertion,
/// so its probe carries one; every other relay gets none.
final selfHostedEntryProvider = Provider<SelfHostedEntry>((ref) {
final auth = ref.watch(hostedRelayAuthProvider);
final probe = ref.watch(relayProbeProvider);
return SelfHostedEntry(
probe: (community) async {
final config = RelayConfig(
baseUrl: community.relayUrl,
nsec: community.nsec,
);
await probe(
community,
auth.organizationProtects(config) ? await auth.headers(config) : {},
);
},
);
});
/// Uses an explicit identity choice without involving a hosted account.
Future<bool> showSelfHostedEntry(
BuildContext context, {
required String relay,
required String name,
bool fullScreen = false,
}) async {
if (fullScreen) {
return await Navigator.of(context, rootNavigator: true).push<bool>(
MaterialPageRoute(
builder: (_) => SelfHostedEntrySheet(
relay: relay,
name: name,
fullScreen: true,
),
),
) ??
false;
}
if (defaultTargetPlatform == TargetPlatform.iOS) {
final container = ProviderScope.containerOf(context);
final service = container.read(selfHostedEntryProvider);
final auth = container.read(authProvider.notifier);
final storage = container.read(communityStorageProvider);
final dark = context.theme.brightness == Brightness.dark;
final primary = context.colors.primary.toARGB32();
// Keep the existing Flutter error state if saved identities are unreadable.
List<DeviceIdentityChoice>? choices;
try {
final inventory = await service.choices();
if (inventory.complete) choices = inventory.choices;
} catch (_) {}
if (!context.mounted) return false;
if (choices != null) {
final result = await NativeCommunityEntry.show(
name: HostedEnvironment.communityDisplayName(
name.isEmpty ? Uri.parse(relay).host : name,
relay,
),
dark: dark,
primaryArgb: primary,
onPrimaryArgb: context.colors.onPrimary.toARGB32(),
choices: choices,
connect: (pubkey, nsec, create, current) async {
final community = await service.prepare(
relay: relay,
name: name,
savedPubkey: pubkey,
nsec: nsec,
create: create,
isCurrent: current,
);
if (!current()) return;
await auth.authenticateWithCommunity(
community,
shouldContinue: current,
);
final saved = await storage.loadAll();
if (saved.any(
(item) => item.id == community.id && item.nsec == community.nsec,
)) {
await service.complete(community);
}
},
);
if (result != null) return result;
}
if (!context.mounted) return false;
}
return await showBuzzModalBottomSheet<bool>(
context: context,
showCloseButton: false,
isScrollControlled: true,
useRootNavigator: true,
useSafeArea: true,
// This sheet owns equal content gutters on all three lower edges.
padBottom: false,
builder: (_) => SelfHostedEntrySheet(relay: relay, name: name),
) ??
false;
}
class SelfHostedEntrySheet extends HookConsumerWidget {
const SelfHostedEntrySheet({
super.key,
required this.relay,
required this.name,
this.fullScreen = false,
});
final String relay;
final String name;
final bool fullScreen;
@override
Widget build(BuildContext context, WidgetRef ref) {
final service = ref.watch(selfHostedEntryProvider);
final choices = useFuture(useMemoized(service.choices));
final busy = useState(false);
final importing = useState(false);
final importFocusReady = useState(false);
final generation = useRef(0);
final error = useState<String?>(null);
bool mounted() => context.mounted;
Future<void> connect({
String? pubkey,
String? nsec,
bool create = false,
bool close = true,
}) async {
if (busy.value) return;
final attempt = ++generation.value;
bool current() => mounted() && generation.value == attempt;
busy.value = true;
error.value = null;
final storage = ref.read(communityStorageProvider);
try {
final community = await service.prepare(
relay: relay,
name: name,
savedPubkey: pubkey,
nsec: nsec,
create: create,
isCurrent: current,
);
if (!current()) return;
await ref
.read(authProvider.notifier)
.authenticateWithCommunity(community, shouldContinue: current);
// Admission can return early after cancellation. Check the durable
// record before retiring the only retry copy of a generated key.
final saved = await storage.loadAll();
if (saved.any(
(item) => item.id == community.id && item.nsec == community.nsec,
)) {
await service.complete(community);
}
if (close && current() && context.mounted) {
Navigator.of(context).pop(true);
}
} catch (_) {
if (current()) {
error.value =
'Could not join. Check this community accepts your identity, then try again. Your saved keys have been kept.';
}
rethrow;
} finally {
if (current()) busy.value = false;
}
}
Future<void> select({String? pubkey, bool create = false}) async {
try {
await connect(pubkey: pubkey, create: create);
} catch (_) {}
}
Widget button({
required VoidCallback? onPressed,
required Widget child,
bool primary = false,
}) {
return primary
? FilledButton(
style: FilledButton.styleFrom(
backgroundColor: context.colors.primary,
foregroundColor: context.colors.onPrimary,
minimumSize: const Size.fromHeight(52),
shape: const StadiumBorder(),
),
onPressed: onPressed,
child: child,
)
: TextButton(
style: TextButton.styleFrom(
foregroundColor: context.colors.onSurface,
minimumSize: const Size.fromHeight(52),
shape: const StadiumBorder(),
),
onPressed: onPressed,
child: child,
);
}
final saved = choices.data?.choices ?? const <DeviceIdentityChoice>[];
final identityTitle = saved.isEmpty
? 'Choose an identity'
: saved.length == 1
? 'You already have a saved identity'
: 'You already have saved identities';
final destination = HostedEnvironment.communityDisplayName(
name.isEmpty ? Uri.parse(relay).host : name,
relay,
);
final identitySubtitle =
'Join $destination. ${saved.length == 1 ? 'Use this identity or import a Nostr key.' : 'Choose an identity or import a Nostr key.'}';
final identityCards = <Widget>[
for (final identity in saved)
SavedIdentityCard(
identity: identity,
onSelect: busy.value ? null : () => select(pubkey: identity.pubkey),
),
];
final joinActions = <Widget>[
if (choices.connectionState == ConnectionState.done) ...[
button(
onPressed: busy.value
? null
: () async {
if (fullScreen) {
final imported = await Navigator.of(context).push<bool>(
MaterialPageRoute(
builder: (importContext) => NsecImportSheet(
fullScreen: true,
onBack: () {
generation.value++;
busy.value = false;
error.value = null;
Navigator.of(importContext).pop(false);
},
onImport: (nsec) => connect(nsec: nsec, close: false),
),
),
);
if (imported == true && context.mounted) {
Navigator.of(context).pop(true);
}
} else {
importFocusReady.value = false;
importing.value = true;
}
},
child: const Text('Import a Nostr key'),
),
if (saved.isEmpty && choices.data?.complete == true)
button(
primary: true,
onPressed: busy.value ? null : () => select(create: true),
child: const Text('Create an identity and join'),
),
if (saved.isEmpty && choices.data?.complete == true)
const Text(
'Export a backup in Settings after joining. This device will hold your only copy until you back it up.',
),
],
if (busy.value)
const Padding(
padding: EdgeInsets.all(Grid.sm),
child: Text('Joining…'),
),
if (error.value != null)
Text(error.value!, style: TextStyle(color: context.colors.error)),
];
final joinContent = Padding(
padding: fullScreen ? EdgeInsets.zero : const EdgeInsets.all(Grid.gutter),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (choices.hasError || choices.data?.complete == false)
const Text(
'Some saved identities could not be read. You can use an available identity or import a key.',
),
if (!fullScreen) ...[
Text(identitySubtitle, style: context.textTheme.bodyMedium),
const SizedBox(height: Grid.sm),
],
// The full-screen page already provides 16 px below its subtitle.
if (fullScreen && identityCards.isNotEmpty)
const SizedBox(height: Grid.xxs),
for (var i = 0; i < identityCards.length; i++) ...[
if (i > 0) const SizedBox(height: Grid.xxs),
identityCards[i],
],
if (!fullScreen) ...[
if (identityCards.isNotEmpty) const SizedBox(height: Grid.xxs),
for (var i = 0; i < joinActions.length; i++) ...[
if (i > 0) const SizedBox(height: Grid.xxs),
joinActions[i],
],
],
],
),
),
);
if (fullScreen && busy.value) {
return OnboardingLoadingPage(
title: 'Getting ready',
onCancel: () {
generation.value++;
busy.value = false;
},
);
}
if (fullScreen) {
return OnboardingStepPage(
title: identityTitle,
subtitle: identitySubtitle,
onBack: () {
generation.value++;
Navigator.of(context).pop(false);
},
content: joinContent,
actions: joinActions,
);
}
return AnimatedSize(
duration: MediaQuery.disableAnimationsOf(context)
? Duration.zero
: const Duration(milliseconds: 250),
curve: Curves.easeOutCubic,
alignment: Alignment.bottomCenter,
onEnd: () {
if (context.mounted && importing.value) importFocusReady.value = true;
},
child: BuzzTitledSheetLayout(
title: importing.value ? 'Import identity' : 'Choose an identity',
onClose: importing.value
? () {
generation.value++;
FocusManager.instance.primaryFocus?.unfocus();
busy.value = false;
error.value = null;
importFocusReady.value = false;
importing.value = false;
}
: null,
child: importing.value
? SizedBox(
height: MediaQuery.sizeOf(context).height * 0.8,
child: NsecImportSheet(
autofocus:
importFocusReady.value ||
MediaQuery.disableAnimationsOf(context),
onImport: (nsec) => connect(nsec: nsec, close: false),
),
)
: joinContent,
),
);
}
}