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

154 lines
5.6 KiB
Dart

import 'package:flutter/foundation.dart';
/// Who a build is distributed to. See `CONTEXT.md` and
/// `docs/adr/0001-internal-and-public-mobile-builds.md`.
enum BuilderlabDistribution {
/// An organization's own app: only its Builderlab and its community.
internal,
/// The publicly distributed app: only the public Builderlab.
public,
}
/// Trusted build configuration naming this build's single Builderlab, never
/// supplied by a deep link or relay. With none of the settings present, the
/// build is Nostr-only.
abstract final class BuilderlabBuild {
static final ({
BuilderlabDistribution? distribution,
Uri? origin,
List<String> relayDomains,
})
_config = parse(
distribution: const String.fromEnvironment('BUZZ_DISTRIBUTION'),
url: const String.fromEnvironment('BUZZ_BUILDERLAB_URL'),
relays: const String.fromEnvironment('BUZZ_BUILDERLAB_RELAYS'),
retired: [
if (const bool.hasEnvironment('BUZZ_AUTH_DOMAINS')) 'BUZZ_AUTH_DOMAINS',
if (const bool.hasEnvironment('BUZZ_ORGANIZATION_URL'))
'BUZZ_ORGANIZATION_URL',
if (const bool.hasEnvironment('BUZZ_ORGANIZATION_RELAYS'))
'BUZZ_ORGANIZATION_RELAYS',
],
);
/// Keys the public Builderlab session's storage in builds without a public
/// Builderlab, which an internal build clears at launch.
static final Uri publicStorageOrigin = Uri.parse(
'https://app.builderlab.xyz',
);
/// `BUZZ_DISTRIBUTION`: `internal` or `public`. Null for a Nostr-only build.
static BuilderlabDistribution? get distribution => _config.distribution;
/// `BUZZ_BUILDERLAB_URL`: this build's Builderlab HTTPS origin.
static Uri? get origin => _config.origin;
/// `BUZZ_BUILDERLAB_RELAYS`: comma-separated DNS domains whose relays use
/// this build's Builderlab session. A public build also matches their
/// subdomains; an internal build matches only these exact hosts.
static List<String> get relayDomains => _config.relayDomains;
/// Matches a configured domain and its subdomains, never a string suffix.
static bool matchesHost(String host, List<String> domains) {
final normalized = host.toLowerCase().replaceFirst(RegExp(r'\.+$'), '');
return domains.any(
(domain) => normalized == domain || normalized.endsWith('.$domain'),
);
}
/// Whether [relay] is a plain origin on a configured domain, so this build
/// may send its Builderlab session's assertions there.
static bool matchesRelay(Uri relay, List<String> domains) =>
['wss', 'https'].contains(relay.scheme) &&
relay.userInfo.isEmpty &&
!relay.hasQuery &&
!relay.hasFragment &&
(relay.path.isEmpty || relay.path == '/') &&
(!relay.hasPort || relay.port == 443) &&
!relay.host.endsWith('.') &&
matchesHost(relay.host, domains);
@visibleForTesting
static ({
BuilderlabDistribution? distribution,
Uri? origin,
List<String> relayDomains,
})
parse({
required String distribution,
required String url,
required String relays,
List<String> retired = const [],
}) {
// A pipeline still passing the former settings would otherwise ship a
// Nostr-only build without its organization restriction.
if (retired.isNotEmpty) {
throw StateError(
'${retired.join(', ')} retired: set BUZZ_DISTRIBUTION, '
'BUZZ_BUILDERLAB_URL and BUZZ_BUILDERLAB_RELAYS instead',
);
}
final domains = _parseDomains(relays);
if (distribution.isEmpty && url.isEmpty && domains.isEmpty) {
return (distribution: null, origin: null, relayDomains: const []);
}
if (distribution.isEmpty || url.isEmpty || domains.isEmpty) {
throw StateError(
'BUZZ_DISTRIBUTION, BUZZ_BUILDERLAB_URL and BUZZ_BUILDERLAB_RELAYS must be set together',
);
}
final kind = BuilderlabDistribution.values
.where((value) => value.name == distribution)
.singleOrNull;
if (kind == null) {
throw StateError('BUZZ_DISTRIBUTION must be internal or public');
}
// An internal build reaches one organization community and has no
// switcher, so a second relay could strand its members there.
if (kind == BuilderlabDistribution.internal && domains.length != 1) {
throw StateError('An internal build takes exactly one relay host');
}
final uri = Uri.parse(url);
if (uri.scheme != 'https' ||
uri.host.isEmpty ||
uri.userInfo.isNotEmpty ||
uri.hasPort ||
uri.hasQuery ||
uri.hasFragment ||
(uri.path.isNotEmpty && uri.path != '/')) {
throw StateError('BUZZ_BUILDERLAB_URL must be an HTTPS origin');
}
final origin = Uri.parse(uri.origin);
// Sessions are stored per origin host, so the internal build's cleanup of
// the public session would delete its own.
if (kind == BuilderlabDistribution.internal &&
origin.host == publicStorageOrigin.host) {
throw StateError(
'An internal build needs its own Builderlab, not ${origin.host}',
);
}
return (distribution: kind, origin: origin, relayDomains: domains);
}
static List<String> _parseDomains(String relays) => List.unmodifiable(
relays
.split(',')
.map(
(domain) =>
domain.trim().toLowerCase().replaceFirst(RegExp(r'\.+$'), ''),
)
.where((domain) => domain.isNotEmpty)
.map((domain) {
if (!RegExp(
r'^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$',
).hasMatch(domain)) {
throw StateError(
'BUZZ_BUILDERLAB_RELAYS must contain DNS names, not URLs or wildcards',
);
}
return domain;
}),
);
}