Files
buzz/mobile/lib/shared/hosted/organization_sign_in.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

255 lines
7.9 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../relay/relay_provider.dart';
import '../relay/relay_session.dart';
import 'browser_auth.dart';
import 'builderlab_account.dart';
import 'hosted_relay_auth.dart';
enum OrganizationSessionStatus { checking, signedOut, signingIn, signedIn }
/// Browser sign-in to the build's organization account. A completed sign-in
/// reconnects the relay so its next upgrade carries a fresh assertion. Null
/// unless this build configures an organization.
final organizationSignInProvider = Provider<OrganizationSignIn?>((ref) {
final account = ref.watch(organizationAccountProvider);
if (account == null) return null;
final signIn = OrganizationSignIn(
account: account,
browser: BrowserAuth(origin: account.accountOrigin),
// Only the organization's relay needs a fresh assertion.
reconnect: () async {
final config = ref.read(relayConfigProvider);
if (ref.read(hostedRelayAuthProvider).organizationProtects(config)) {
await ref.read(relaySessionProvider.notifier).reconnect();
}
},
);
ref.onDispose(signIn.dispose);
unawaited(signIn.initialize());
return signIn;
});
class OrganizationSignIn extends ChangeNotifier {
OrganizationSignIn({
required this.account,
required this.browser,
required this.reconnect,
});
final BuilderlabAccountClient account;
final BrowserAuth browser;
final Future<void> Function() reconnect;
OrganizationSessionStatus status = OrganizationSessionStatus.checking;
/// The last sign-in or session-check failure, cleared by the next attempt.
Object? failure;
final _subscriptions = <StreamSubscription<Object>>[];
/// Advanced by every start or cancel, so an exchange from an abandoned
/// attempt can never change the state of a newer one.
int _attempt = 0;
bool _initialized = false;
bool _disposed = false;
/// A sign-out whose session is still saved. Until it is cleared, the
/// session counts as signed out and the next sign-in clears it first, so a
/// retired credential is never reused.
bool _retiring = false;
Future<void> initialize() async {
if (_initialized || _disposed) return;
_initialized = true;
account.subjectChanges.addListener(_onSubject);
_subscriptions
..add(browser.codes.listen((code) => unawaited(_exchange(code))))
..add(browser.failures.listen(_onBrowserFailure));
// A sign-in or sign-out started meanwhile owns the status.
final attempt = _attempt;
await browser.initialize();
try {
if (account.account == null) await account.restore();
if (attempt != _attempt) return;
_set(_currentStatus());
} on AccountFailure catch (error) {
if (attempt != _attempt) return;
// Unknown, for example offline. Relay connection retries the restore.
// An unreadable record is kept so the next sign-in can replace it.
if (error == AccountFailure.storage) failure = error;
_set(OrganizationSessionStatus.signedOut);
}
}
Future<void> signIn() =>
// An unreadable saved session blocks every exchange, and its subject is
// unknown. Signing in again explicitly replaces only that session.
_begin(
clear:
_retiring ||
(failure == AccountFailure.storage && account.account == null),
);
/// Drops only the organization session and signs in again, for an account
/// the relay refuses for this key. The hosted account is untouched.
Future<void> changeAccount() => _begin(clear: true);
Future<void> _begin({required bool clear}) async {
if (_disposed || status == OrganizationSessionStatus.signingIn) return;
// Busy before any await, so a second tap cannot start another attempt.
final attempt = ++_attempt;
failure = null;
_set(OrganizationSessionStatus.signingIn);
if (clear) {
try {
await account.clearLocalSession();
} on AccountFailure catch (error) {
if (attempt != _attempt) return;
failure = error;
_set(_currentStatus());
return;
}
_retiring = false;
if (_disposed || attempt != _attempt) return;
}
try {
await browser.start(const {'purpose': 'organization'});
} on BrowserAuthFailure catch (error) {
if (attempt != _attempt) return;
failure = error;
_set(_currentStatus());
}
}
/// Ends the organization session, so the next sign-in goes through single
/// sign-on again.
Future<void> signOut() async {
if (_disposed) return;
final attempt = ++_attempt;
failure = null;
_set(OrganizationSessionStatus.checking);
try {
await account.clearLocalSession();
_retiring = false;
} on AccountFailure catch (error) {
_retiring = true;
if (attempt != _attempt) return;
failure = error;
}
if (attempt != _attempt) return;
_set(_currentStatus());
}
Future<void> cancel() async {
++_attempt;
try {
await browser.cancel();
} on BrowserAuthFailure catch (error) {
failure = error;
} finally {
_set(_currentStatus());
}
}
Future<void> _exchange(BrowserAuthCode code) async {
final attempt = _attempt;
try {
await account.exchange(
code: code.code,
verifier: code.verifier,
// A cancelled attempt must never save its account.
isCurrent: () => !_disposed && attempt == _attempt,
);
} on AccountFailure catch (error) {
if (attempt != _attempt) return;
failure = error;
_set(_currentStatus());
return;
}
if (_disposed || attempt != _attempt) return;
failure = null;
try {
await browser.clearIntent();
} on BrowserAuthFailure catch (error) {
// The session is saved; a leftover intent must not keep sign-in busy.
failure = error;
}
if (_disposed || attempt != _attempt) return;
_set(OrganizationSessionStatus.signedIn);
await reconnect();
}
void _onBrowserFailure(BrowserAuthFailure error) {
if (status != OrganizationSessionStatus.signingIn) return;
failure = error == BrowserAuthFailure.cancelled ? null : error;
_set(_currentStatus());
}
void _onSubject() {
if (status == OrganizationSessionStatus.signingIn ||
status == OrganizationSessionStatus.checking) {
return;
}
if (account.account != null) failure = null;
_set(_currentStatus());
}
OrganizationSessionStatus _currentStatus() =>
account.account == null || _retiring
? OrganizationSessionStatus.signedOut
: OrganizationSessionStatus.signedIn;
void _set(OrganizationSessionStatus next) {
if (_disposed) return;
status = next;
notifyListeners();
}
@override
void dispose() {
_disposed = true;
account.subjectChanges.removeListener(_onSubject);
for (final subscription in _subscriptions) {
unawaited(subscription.cancel());
}
unawaited(browser.dispose());
super.dispose();
}
}
/// The relay's refusal for this community and key, if any.
AccountFailure? organizationRelayFailure(
HostedRelayAuth auth,
RelayConfig config,
) =>
auth.failedRelay == config.baseUrl &&
auth.failedPubkey == pubkeyFromNsec(config.nsec)
? auth.failure
: null;
/// Whether the organization sign-in banner offers an action for [config]. The
/// community switcher closes early on this so the banner is reachable.
bool organizationSignInPromptVisible(
OrganizationSignIn? signIn,
HostedRelayAuth auth,
RelayConfig config,
) {
if (signIn == null || !auth.organizationProtects(config)) return false;
return switch (signIn.status) {
OrganizationSessionStatus.checking => false,
OrganizationSessionStatus.signingIn ||
OrganizationSessionStatus.signedOut => true,
OrganizationSessionStatus.signedIn => switch (organizationRelayFailure(
auth,
config,
)) {
null || AccountFailure.signedOut || AccountFailure.unavailable => false,
_ => true,
},
};
}