Files
buzz/mobile/test/shared/huddle/huddle_transport_test.dart
Wes b6aa5539e3 feat(mobile): account onboarding, key recovery and hosted reconnect (#8375)
## Behavior

Adds optional mobile Builderlab sign-in, identity backup/recovery,
community discovery/creation, and account-aware reconnect. **Builderlab
features are disabled by default:** when `BUZZ_AUTH_DOMAINS` is unset or
empty, account login, creation, backup/recovery, reconnect prompts, and
background account restoration are hidden/disabled. QR/code pairing,
links, and invites retain Nostr-only entry. Saved account state is
retained for later opt-in.


`--dart-define=BUZZ_AUTH_DOMAINS=communities.buzz.xyz,communities.public.builderlabstaging.xyz`
opts those DNS domains and their subdomains into required account setup.
The same policy gates pairing, deep links, durable community admission,
and reconnect. A nonempty list enables Builderlab features;
`BUZZ_BUILDERLAB_URL` alone does not. Enabled flows still require their
backend services. Existing Nostr relay authentication remains mandatory.

`BUZZ_HOSTED_RELAY_AUTH=true` enables scoped relay assertions and
reconnect prompts only for configured authentication domains. Configure
assertion issuance and each community's issuer binding before enabling
assertions; enable relay enforcement last. Account credentials stay at
Builderlab. Wrong-account recovery preserves keys; failed writes are not
replayed; authentication is bounded by request deadlines.

Hosted flows preserve keys across cancellation/restart, reconcile
interrupted creation/invitation acceptance, and support manual nsec file
import/export. Account identities are scoped to backend and
authenticated subject; reusing an existing local key for an unbound
account requires an explicit selection. Recovery reconciles the
advertised and recovered inventories before automatic selection.
Successful self-hosted admission retires its pending key, and iOS
startup removes interrupted export files. Adds authenticated relay `GET
/operator/communities/joined` for the companion Builderlab membership
endpoint.

## Validation

- Follow-up review repair at `66a12ac92`: self-hosted entry presents
readable choices and import despite incomplete enumeration, while
generation still requires a complete empty inventory; explicit selection
uses exact-key lookup. Consuming a value-equal duplicate now advances
dispatch. Reconnect requires an existing account binding or a
subject-scoped backup receipt before signing an assertion, and pins the
subject inside the serialized account request. An empty different
account is refused without sending key proof. Focused checks: configured
domains 58 passed; default 49 passed, 9 hosted-only skips. Separate
isolated mutations fail the incomplete-inventory sheet, exact-key reuse,
duplicate dispatch and reconnect journeys (including an
empty-account-only bypass); restored controls pass. Evidence uses
synthetic storage/network boundaries, not physical Android or live
backend association. All mandatory commit/push hooks passed; fresh
GitHub CI is pending.

- Bounded review repair at `d3cc0003f`: incomplete secure-storage
enumeration now blocks automatic identity generation while explicit
known-key reads retain their fallback; declined/failed onboarding links
release the queue; HTTP 429/5xx keeps Retry regardless of response
encoding. Default app-gate coverage exercises a bind link followed by
ordinary community entry. Focused checks: configured domains 47 passed;
default 38 passed, 9 hosted-only skips. Removing the three production
fixes in an isolated source/Git/build copy fails the
identity-resolution, declined/failed queue, and Retry journey
assertions; clean and restored controls pass. Storage and HTTP failures
are synthetic; physical Android and live outage behavior were not
exercised. Published after all mandatory commit/push hooks passed
(mobile analysis/tests, branch-skew and file-size gates); fresh GitHub
CI remains pending.

- Existing whole-PR source review cleared the reconnect defects at
`fb15d5b82`.
- Domain-policy increment: focused environment, entry, app-gate, pairing
and onboarding journeys pass with empty and configured domains. Existing
pairing provider/page tests pass. Changed Dart files analyze cleanly.
- Isolated source/Git/build mutation: forcing paired credentials through
hosted login fails the default-build journey; clean and restored
controls pass. CI now runs configured-domain journeys in addition to the
default-build suite.
- Integrated main through `5b433d929` at `0067c069c`, including its
pinned Flutter upgrade. Preserved the PR welcome UI with the updated
transition API and added Material surfaces around onboarding
selection/consent rows. Focused post-merge runs pass in both
configurations; all mandatory local push gates passed (mobile
analysis/tests, Rust tests, desktop-native checks, branch-skew and
file-size checks).

- Merge-review repair at `a315bce11`: focused identity/storage/admission
and widget journeys pass, including account switching with an empty or
already-bound second account, explicit reuse, and self-hosted
removal/rejoin with another key. Default-domain journeys pass too
(hosted-only cases intentionally skip there).
- Isolated source/Git/build mutation checks: bypassing account scoping,
reuse consent, pending-key retirement, or recovery inventory
reconciliation fails the relevant journey/invariant assertions; clean
and restored controls pass.
- Native `RunnerTests/IdentityFilePluginTests`: both tests pass on the
iPhone 18 Pro iOS 27 simulator with an isolated app identifier. At
`24a0dcaac`, the picker journey seeds residue in Library/Caches,
matching path_provider_foundation, and verifies plugin startup removes
it while preserving an unrelated file. The earlier tmp-only fixture did
not exercise the actual export location. This is synthetic native
cleanup/picker evidence, not a real terminated-share or live account
round trip.

- Follow-up: Caches and tmp cleanup; fallback to individually known
identity slots when Android bulk enumeration fails; explicit replacement
of a refused self-hosted key preserves its original before swapping the
retry slot. Configured-domain journeys/invariants: 34 passed; default:
31 passed, 3 hosted-only skips. Isolated enumeration/retry mutations
fail with passing controls. Bulk-read fallback preserves but cannot
enumerate arbitrary other-account slots until bulk reads recover.

- Configured-domain CI exposed a stale pairing-status assertion after
account scoping. The repaired test checks the admission mismatch,
preserved account/transfer keys, and no admitted community. The
configured-domain CI selection passes locally (56 tests); removing the
production mismatch guard fails the updated test, with clean/restored
controls passing. This is synthetic coordinator evidence, not physical
QR acceptance.

- Final review repair (`40e1e6101`): native iOS export creation uses
atomic complete file protection; normal and restart cleanup remain.
Account/policy/claim HTTP uses one 30-second total deadline with request
abort and body cancellation. Removed the unrelated NIP-FA spec edit.
- Focused account/admission/export tests: 25 pass; configured-domain
account/admission/onboarding journeys: 33 pass. Isolated deadline and
native-dispatch mutations fail, with passing clean/restored controls.
Native export/picker tests: 2 pass on iOS 27 simulator. The real
file-protection attribute assertion is physical-device-only because
simulator provides no Data Protection attribute; locked-device
protection and interrupted real sharing have not been observed.

- Opt-in UI: configured-domain CI selection passes (57 tests); default
selection passes (7 tests, 10 hosted-only skips); URL-only plus
whitespace/empty domains passes (6 tests, 9 hosted-only skips). Changed
Dart files analyze cleanly. Independent mutations that unconditionally
initialize the coordinator in the app gate, welcome entry, or link form
fail the default journey; clean/restored controls pass.
- Native welcome screens exercised on iPhone 18 Pro / iOS 27 simulator
in default and configured builds: default exposes community link / QR /
pairing code only; configured build additionally exposes Builderlab
connection and community creation. No live hosted login was exercised in
this check.

- Delivery at `e48fe73a9`: all mandatory push hooks passed (full mobile
analysis/tests, Rust tests, desktop-native checks, branch and file-size
checks). GitHub checks had not yet populated at the immediate post-push
snapshot.

## Review disposition

| Feedback | Disposition |
| --- | --- |
| Explicit self-hosted entry under unreadable inventory, duplicate
invite dispatch, reconnect cross-account binding
([entry](https://github.com/block/buzz/pull/8375#discussion_r4318421622),
[queue](https://github.com/block/buzz/pull/8375#discussion_r4318421640),
[reconnect](https://github.com/block/buzz/pull/8375#discussion_r4318455512))
| Repaired at `66a12ac92`; evidence above. Reconnect refuses unproven
ownership rather than silently establishing a binding. |
| Incomplete Android identity inventory, stranded deep-link queue,
transient HTTP retry classification
([review](https://github.com/block/buzz/pull/8375#pullrequestreview-5576864143))
| All three repaired in `d3cc0003f`; focused journeys and isolated
mutation evidence above. |
| Account cross-link, incomplete recovery inventory, committed invite
checkpoint, pending local key retirement/replacement | Repaired in the
preceding commits; journey and mutation evidence above. |
| iOS interrupted key export
([review](https://github.com/block/buzz/pull/8375#pullrequestreview-5575253252))
| Native cleanup plus complete protection at creation implemented.
Physical-device lock and real interrupted sharing acceptance remains
pending. |
| Trickle responses bypass idle timeout; unrelated NIP-FA edit
([review](https://github.com/block/buzz/pull/8375#pullrequestreview-5575764556))
| Total request deadline/abort implemented; spec edit removed. |
| Production domains rejected | Ordinary entry now needs no Builderlab
configuration. Opt-in account-required domains must still use supported
community mappings. |
| Lost Android Keystore recovery | Backup exclusions prevent the
reviewed stale-restore scenario; genuine key loss still has no in-app
recovery/reset and remains deferred. |
| Native secp256k1 dependency question | Obsolete against the current
base: upstream C integration landed in #8398; no package diff remains
here. |
| Operator membership endpoint contract | Documentation now states the
operator chooses the pubkey; no end-user session binding is implied.
Additional handler-level coverage is optional follow-up. |
| Optional Android partial document cleanup/activity retention; local
work after backup cancellation | Follow-up hardening, not claimed
implemented. Cancellation prevents remote backup upload. |
| Semgrep crypto inventory notices | Informational inventory, not
demonstrated defects. |

## Remaining draft gates

Native QR/browser-return acceptance remains unverified for this
revision. Optional Builderlab onboarding still needs backend
backup-status and joined-community routes, recovery
policy/configuration, and real backup/recovery/reconnect acceptance. The
empty-domain build removes these services as prerequisites for ordinary
pairing; it does not make the optional hosted flows backend-ready. Human
acceptance and current CI are still required before merge.



Review dispositions retained: production auth-domain configuration must
use supported community mappings; enabling `builderlab.xyz` does not add
support for `buzz.block.builderlab.xyz`. Recovery after genuinely losing
an Android Keystore key remains a follow-up, not a newly implemented
capability.


Human acceptance steps: build once without `BUZZ_AUTH_DOMAINS`
(including with a previously saved account) and confirm no Builderlab
controls/restoration while ordinary link and QR/code entry work. Build
with supported domains and confirm connection/creation appear; exercise
browser return and live backup/recovery/reconnect. On physical iOS,
exercise export and interrupted sharing/locked-device protection. Record
results before marking review complete.

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@wes.communities.public.builderlabstaging.xyz>
2026-10-19 15:46:58 -06:00

920 lines
28 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:buzz/shared/huddle/huddle_auth.dart';
import 'package:buzz/shared/huddle/huddle_transport.dart';
import 'package:buzz/shared/huddle/huddle_wire.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
const _privateKey =
'09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506';
const _parentChannelId = '11111111-2222-4333-8444-555555555555';
const _ephemeralChannelId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
void main() {
test('authenticates with object JSON and admits a v2 room', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
final connect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
channel.emitText(jsonEncode({'type': 'challenge', 'challenge': 'abc'}));
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
final auth = jsonDecode(channel.sink.sent.single as String);
expect(auth, isA<Map<String, dynamic>>());
expect(auth['type'], 'auth');
expect(auth['parent_channel_id'], _parentChannelId);
expect(auth['protocol_version'], 2);
channel.emitText(
jsonEncode({
'type': 'joined',
'pubkey': 'self',
'peer_index': 3,
'peers': [
{'pubkey': 'desktop', 'peer_index': 1},
],
}),
);
await connect;
expect(transport.state.phase, HuddleTransportPhase.connected);
expect(transport.state.localPeerIndex, 3);
expect(transport.state.peers.keys, containsAll([1, 3]));
final stalled = Completer<Map<String, String>>();
var opened = false;
final waiting = HuddleTransport(
parameters: transport.parameters,
headers: () => stalled.future,
channelFactory: (_) {
opened = true;
return _ControlledWebSocketChannel();
},
connectTimeout: const Duration(milliseconds: 20),
);
addTearDown(waiting.dispose);
await expectLater(waiting.connect(), throwsA(isA<HuddleTransportError>()));
stalled.complete({});
await Future<void>.delayed(Duration.zero);
expect(opened, isFalse);
});
test(
'parses inbound relay media and encodes outbound client media',
() async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
peers: const [
{'pubkey': 'remote', 'peer_index': 4},
],
);
final inbound = expectLater(
transport.remoteAudioFrames,
emits(
isA<HuddleRemoteAudioFrame>()
.having((frame) => frame.peerIndex, 'peer index', 4)
.having((frame) => frame.epoch, 'epoch', 0)
.having((frame) => frame.header.sequence, 'sequence', 9)
.having((frame) => frame.opusPayload, 'Opus', [0xaa]),
),
);
channel.emitBinary(
Uint8List.fromList([4, 0, 9, 0, 0, 3, 0xc0, 0xd8, 0, 0xaa]),
);
await inbound;
transport.sendOpusFrame(
header: const HuddleAudioHeader(
sequence: 10,
timestamp48k: 1920,
levelDbov: -40,
flags: 0,
),
opusPayload: Uint8List.fromList([0xbb]),
);
expect(
channel.sink.sent.last,
Uint8List.fromList([0, 10, 0, 0, 7, 0x80, 0xd8, 0, 0xbb]),
);
},
);
test('surfaces malformed media as recoverable issue', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(channel, transport);
final issue = expectLater(
transport.issues,
emits(
isA<HuddleTransportError>().having(
(error) => error.code,
'code',
HuddleTransportErrorCode.protocolViolation,
),
),
);
channel.emitBinary(Uint8List.fromList([1, 2, 3]));
await issue;
expect(transport.state.phase, HuddleTransportPhase.connected);
});
test(
'revisioned roster is authoritative and deltas are sequential',
() async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 4,
peers: const [
{'pubkey': 'desktop', 'peer_index': 1},
],
);
expect(transport.state.peers.keys, [1]);
expect(transport.state.rosterRevision, 4);
channel.emitText(
jsonEncode({
'type': 'joined',
'revision': 5,
'pubkey': 'agent',
'peer_index': 2,
'peers': [
{'pubkey': 'agent', 'peer_index': 2},
],
}),
);
await _waitForRevision(transport, 5);
expect(transport.state.peers.keys, containsAll([1, 2]));
channel.emitText(
jsonEncode({
'type': 'roster',
'revision': 6,
'peers': [
{'pubkey': 'replacement', 'peer_index': 2},
],
}),
);
await _waitForRevision(transport, 6);
expect(transport.state.peers.keys, [2]);
expect(transport.state.peers[2]?.pubkey, 'replacement');
channel.emitText(
jsonEncode({'type': 'roster', 'revision': 5, 'peers': const []}),
);
await Future<void>.delayed(Duration.zero);
expect(transport.state.rosterRevision, 6);
expect(transport.state.peers[2]?.pubkey, 'replacement');
},
);
test(
'newer roster arriving before admission remains authoritative',
() async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
final connect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
channel.emitText(jsonEncode({'type': 'challenge', 'challenge': 'abc'}));
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
channel.emitText(
jsonEncode({
'type': 'roster',
'revision': 6,
'peers': [
{'pubkey': 'new', 'peer_index': 4},
],
}),
);
channel.emitText(
jsonEncode({
'type': 'joined',
'revision': 5,
'pubkey': 'self',
'peer_index': 3,
'peers': [
{'pubkey': 'old', 'peer_index': 1},
],
}),
);
await connect;
expect(transport.state.localPeerIndex, 3);
expect(transport.state.rosterRevision, 6);
expect(transport.state.peers.keys, [4]);
expect(transport.state.peers[4]?.pubkey, 'new');
},
);
test('revision gap reconnects without applying the gap', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 2,
peers: const [
{'pubkey': 'desktop', 'peer_index': 1},
],
);
channel.emitText(
jsonEncode({
'type': 'left',
'revision': 4,
'pubkey': 'desktop',
'peer_index': 1,
}),
);
await _waitForPhase(transport, HuddleTransportPhase.failed);
expect(transport.state.rosterRevision, 2);
expect(transport.state.peers[1]?.pubkey, 'desktop');
expect(transport.state.error?.message, contains('revision gap'));
});
test('revisioned admission does not inject an absent local user', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 8,
peers: const [
{'pubkey': 'desktop', 'peer_index': 1},
],
);
expect(transport.state.localPeerIndex, 3);
expect(transport.state.peers.keys, [1]);
});
test('revisioned joined delta reports index reuse', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 1,
peers: const [
{'pubkey': 'old', 'peer_index': 4},
],
);
final events = <HuddlePeerEvent>[];
final subscription = transport.peerEvents.listen(events.add);
addTearDown(subscription.cancel);
channel.emitText(
jsonEncode({
'type': 'joined',
'revision': 2,
'pubkey': 'new',
'peer_index': 4,
'peers': [
{'pubkey': 'new', 'peer_index': 4},
],
}),
);
await _waitForRevision(transport, 2);
expect(events.single.type, HuddlePeerEventType.replaced);
expect(events.single.peer.pubkey, 'old');
expect(events.single.replacement?.pubkey, 'new');
expect(transport.state.peers[4]?.pubkey, 'new');
});
test('revisioned joined delta reports same-pubkey epoch reuse', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 1,
peers: const [
{'pubkey': 'same', 'peer_index': 4, 'epoch': 2},
],
);
final events = <HuddlePeerEvent>[];
final subscription = transport.peerEvents.listen(events.add);
addTearDown(subscription.cancel);
channel.emitText(
jsonEncode({
'type': 'joined',
'revision': 2,
'pubkey': 'same',
'peer_index': 4,
'epoch': 3,
'peers': [
{'pubkey': 'same', 'peer_index': 4, 'epoch': 3},
],
}),
);
await _waitForRevision(transport, 2);
expect(events.single.type, HuddlePeerEventType.replaced);
expect(events.single.peer.epoch, 2);
expect(events.single.replacement?.epoch, 3);
});
test('index replacement is emitted before new media is admitted', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 1,
peers: const [
{'pubkey': 'old', 'peer_index': 4},
],
);
final events = <HuddlePeerEvent>[];
final subscription = transport.peerEvents.listen(events.add);
addTearDown(subscription.cancel);
channel.emitText(
jsonEncode({
'type': 'roster',
'revision': 2,
'peers': [
{'pubkey': 'new', 'peer_index': 4},
],
}),
);
await _waitForRevision(transport, 2);
expect(events.single.type, HuddlePeerEventType.replaced);
expect(events.single.peer.pubkey, 'old');
expect(events.single.replacement?.pubkey, 'new');
});
test('exposes relay rejection code and failed lifecycle state', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
final connect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
channel.emitText(jsonEncode({'type': 'challenge', 'challenge': 'abc'}));
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
channel.emitText(
jsonEncode({
'type': 'error',
'code': 'upgrade_required',
'message': 'room is pinned to v1',
}),
);
await expectLater(
connect,
throwsA(
isA<HuddleTransportError>()
.having(
(error) => error.code,
'code',
HuddleTransportErrorCode.relayRejected,
)
.having(
(error) => error.relayCode,
'relay code',
'upgrade_required',
),
),
);
expect(transport.state.phase, HuddleTransportPhase.failed);
});
test('bounds transport audio ingress', () async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 1,
peers: const [
{'pubkey': 'remote', 'peer_index': 4},
],
);
final received = <int>[];
final drained = Completer<void>();
final subscription = transport.remoteAudioFrames.listen((frame) {
received.add(frame.header.sequence);
if (frame.header.sequence == 99 && !drained.isCompleted) {
drained.complete();
}
});
addTearDown(subscription.cancel);
for (var sequence = 0; sequence < 100; sequence++) {
channel.emitBinary(_relayFrame(peerIndex: 4, sequence: sequence));
}
await drained.future.timeout(const Duration(seconds: 1));
expect(received, hasLength(50));
expect(received.first, 50);
expect(received.last, 99);
});
test(
'authoritative left purges queued media before same-index rejoin',
() async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 1,
peers: const [
{'pubkey': 'old', 'peer_index': 4},
],
);
final received = <int>[];
final subscription = transport.remoteAudioFrames.listen(
(frame) => received.add(frame.header.sequence),
);
addTearDown(subscription.cancel);
for (var sequence = 0; sequence < 50; sequence++) {
channel.emitBinary(_relayFrame(peerIndex: 4, sequence: sequence));
}
channel.emitText(
jsonEncode({
'type': 'left',
'revision': 2,
'pubkey': 'old',
'peer_index': 4,
}),
);
channel.emitText(
jsonEncode({
'type': 'joined',
'revision': 3,
'pubkey': 'new',
'peer_index': 4,
}),
);
channel.emitBinary(_relayFrame(peerIndex: 4, sequence: 50));
await _waitForRevision(transport, 3);
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(transport.state.peers[4]?.pubkey, 'new');
expect(received, [50]);
},
);
test(
'v2 media routes through the current peer-index occupant after reuse',
() async {
// Protocol v2 exposes only the peer index on media. After the roster
// reassigns that index, subsequent frames route to the current occupant.
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(
channel,
transport,
revision: 1,
peers: const [
{'pubkey': 'old', 'peer_index': 4, 'epoch': 0},
],
);
final received = <int>[];
final subscription = transport.remoteAudioFrames.listen(
(frame) => received.add(frame.header.sequence),
);
addTearDown(subscription.cancel);
// 'old' (epoch 0) leaves and 'new' reuses index 4 at epoch 1.
channel.emitText(
jsonEncode({
'type': 'joined',
'revision': 2,
'pubkey': 'new',
'peer_index': 4,
'epoch': 1,
'peers': [
{'pubkey': 'new', 'peer_index': 4, 'epoch': 1},
],
}),
);
await _waitForRevision(transport, 2);
expect(transport.state.peers[4]?.pubkey, 'new');
expect(transport.state.peers[4]?.epoch, 1);
// V2 cannot distinguish delayed media from the old occupancy, so both
// packets are delivered through the currently occupied index.
channel.emitBinary(_relayFrame(peerIndex: 4, epoch: 0, sequence: 7));
channel.emitBinary(_relayFrame(peerIndex: 4, epoch: 1, sequence: 8));
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(received, [7, 8]);
},
);
test(
're-admission reports departed and reused peer indexes before new media',
() async {
final firstChannel = _ControlledWebSocketChannel();
final secondChannel = _ControlledWebSocketChannel();
var connection = 0;
final transport = HuddleTransport(
parameters: HuddleConnectionParameters(
relayWebSocketUrl: 'wss://buzz.example',
nsec: _privateKey,
parentChannelId: _parentChannelId,
ephemeralChannelId: _ephemeralChannelId,
),
channelFactory: (_) => connection++ == 0 ? firstChannel : secondChannel,
connectTimeout: const Duration(seconds: 1),
handshakeTimeout: const Duration(seconds: 1),
);
addTearDown(transport.dispose);
await _connect(
firstChannel,
transport,
revision: 1,
peers: const [
{'pubkey': 'old', 'peer_index': 4},
{'pubkey': 'departed', 'peer_index': 5},
],
);
final events = <HuddlePeerEvent>[];
final subscription = transport.peerEvents.listen(events.add);
addTearDown(subscription.cancel);
firstChannel.emitError(StateError('socket lost'));
await _waitForPhase(transport, HuddleTransportPhase.failed);
final reconnect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
secondChannel.emitText(
jsonEncode({'type': 'challenge', 'challenge': 'reconnect'}),
);
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
secondChannel.emitText(
jsonEncode({
'type': 'joined',
'revision': 4,
'pubkey': 'self',
'peer_index': 3,
'peers': [
{'pubkey': 'new', 'peer_index': 4},
{'pubkey': 'self', 'peer_index': 3},
],
}),
);
await reconnect;
expect(transport.state.peers[4]?.pubkey, 'new');
expect(events, hasLength(2));
expect(events[0].type, HuddlePeerEventType.replaced);
expect(events[0].peer.pubkey, 'old');
expect(events[0].replacement?.pubkey, 'new');
expect(events[1].type, HuddlePeerEventType.left);
expect(events[1].peer.pubkey, 'departed');
},
);
test('re-admission resets same-pubkey slot when its epoch changes', () async {
final firstChannel = _ControlledWebSocketChannel();
final secondChannel = _ControlledWebSocketChannel();
var connection = 0;
final transport = HuddleTransport(
parameters: HuddleConnectionParameters(
relayWebSocketUrl: 'wss://buzz.example',
nsec: _privateKey,
parentChannelId: _parentChannelId,
ephemeralChannelId: _ephemeralChannelId,
),
channelFactory: (_) => connection++ == 0 ? firstChannel : secondChannel,
connectTimeout: const Duration(seconds: 1),
handshakeTimeout: const Duration(seconds: 1),
);
addTearDown(transport.dispose);
await _connect(
firstChannel,
transport,
revision: 1,
peers: const [
{'pubkey': 'same', 'peer_index': 4, 'epoch': 0},
],
);
final events = <HuddlePeerEvent>[];
final subscription = transport.peerEvents.listen(events.add);
addTearDown(subscription.cancel);
firstChannel.emitError(StateError('relay restarted'));
await _waitForPhase(transport, HuddleTransportPhase.failed);
final reconnect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
secondChannel.emitText(
jsonEncode({'type': 'challenge', 'challenge': 'reconnect'}),
);
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
secondChannel.emitText(
jsonEncode({
'type': 'joined',
'revision': 1,
'pubkey': 'self',
'peer_index': 3,
'epoch': 0,
'peers': [
{'pubkey': 'same', 'peer_index': 4, 'epoch': 1},
{'pubkey': 'self', 'peer_index': 3, 'epoch': 0},
],
}),
);
await reconnect;
expect(events, hasLength(1));
expect(events.single.type, HuddlePeerEventType.replaced);
expect(events.single.peer.epoch, 0);
expect(events.single.replacement?.epoch, 1);
});
test('re-admission resets same slot even when its epoch is reused', () async {
final firstChannel = _ControlledWebSocketChannel();
final secondChannel = _ControlledWebSocketChannel();
var connection = 0;
final transport = HuddleTransport(
parameters: HuddleConnectionParameters(
relayWebSocketUrl: 'wss://buzz.example',
nsec: _privateKey,
parentChannelId: _parentChannelId,
ephemeralChannelId: _ephemeralChannelId,
),
channelFactory: (_) => connection++ == 0 ? firstChannel : secondChannel,
connectTimeout: const Duration(seconds: 1),
handshakeTimeout: const Duration(seconds: 1),
);
addTearDown(transport.dispose);
await _connect(
firstChannel,
transport,
revision: 9,
peers: const [
{'pubkey': 'same', 'peer_index': 4, 'epoch': 0},
],
);
final events = <HuddlePeerEvent>[];
final subscription = transport.peerEvents.listen(events.add);
addTearDown(subscription.cancel);
firstChannel.emitError(StateError('relay restarted'));
await _waitForPhase(transport, HuddleTransportPhase.failed);
final reconnect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
secondChannel.emitText(
jsonEncode({'type': 'challenge', 'challenge': 'reconnect'}),
);
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
secondChannel.emitText(
jsonEncode({
'type': 'joined',
'revision': 1,
'pubkey': 'self',
'peer_index': 3,
'epoch': 0,
'peers': [
{'pubkey': 'same', 'peer_index': 4, 'epoch': 0},
{'pubkey': 'self', 'peer_index': 3, 'epoch': 0},
],
}),
);
await reconnect;
expect(events, hasLength(1));
expect(events.single.type, HuddlePeerEventType.replaced);
expect(events.single.peer.pubkey, 'same');
expect(events.single.replacement?.pubkey, 'same');
expect(events.single.replacement?.epoch, 0);
});
test('re-admission accepts a lower revision after relay restart', () async {
final firstChannel = _ControlledWebSocketChannel();
final secondChannel = _ControlledWebSocketChannel();
var connection = 0;
final transport = HuddleTransport(
parameters: HuddleConnectionParameters(
relayWebSocketUrl: 'wss://buzz.example',
nsec: _privateKey,
parentChannelId: _parentChannelId,
ephemeralChannelId: _ephemeralChannelId,
),
channelFactory: (_) => connection++ == 0 ? firstChannel : secondChannel,
connectTimeout: const Duration(seconds: 1),
handshakeTimeout: const Duration(seconds: 1),
);
addTearDown(transport.dispose);
await _connect(
firstChannel,
transport,
revision: 9,
peers: const [
{'pubkey': 'stale', 'peer_index': 4},
],
);
firstChannel.emitError(StateError('relay restarted'));
await _waitForPhase(transport, HuddleTransportPhase.failed);
final reconnect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
secondChannel.emitText(
jsonEncode({'type': 'challenge', 'challenge': 'reconnect'}),
);
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
secondChannel.emitText(
jsonEncode({
'type': 'joined',
'revision': 1,
'pubkey': 'self',
'peer_index': 3,
'peers': [
{'pubkey': 'fresh', 'peer_index': 4},
{'pubkey': 'self', 'peer_index': 3},
],
}),
);
await reconnect;
expect(transport.state.rosterRevision, 1);
expect(transport.state.peers[4]?.pubkey, 'fresh');
secondChannel.emitText(
jsonEncode({
'type': 'joined',
'revision': 2,
'pubkey': 'next',
'peer_index': 5,
}),
);
await _waitForRevision(transport, 2);
expect(transport.state.peers[5]?.pubkey, 'next');
});
test(
'intentional disconnect reaches disconnected without an error',
() async {
final channel = _ControlledWebSocketChannel();
final transport = _transport(channel);
addTearDown(transport.dispose);
await _connect(channel, transport);
await transport.disconnect();
expect(transport.state.phase, HuddleTransportPhase.disconnected);
expect(transport.state.error, isNull);
},
);
}
HuddleTransport _transport(_ControlledWebSocketChannel channel) =>
HuddleTransport(
parameters: HuddleConnectionParameters(
relayWebSocketUrl: 'wss://buzz.example',
nsec: _privateKey,
parentChannelId: _parentChannelId,
ephemeralChannelId: _ephemeralChannelId,
),
channelFactory: (_) => channel,
connectTimeout: const Duration(seconds: 1),
handshakeTimeout: const Duration(seconds: 1),
);
Future<void> _connect(
_ControlledWebSocketChannel channel,
HuddleTransport transport, {
int? revision,
List<Map<String, Object>> peers = const [],
}) async {
final connect = transport.connect();
await _waitForPhase(transport, HuddleTransportPhase.awaitingChallenge);
channel.emitText(jsonEncode({'type': 'challenge', 'challenge': 'abc'}));
await _waitForPhase(transport, HuddleTransportPhase.authenticating);
final admission = <String, Object>{
'type': 'joined',
'pubkey': 'self',
'peer_index': 3,
'peers': peers,
};
if (revision != null) admission['revision'] = revision;
channel.emitText(jsonEncode(admission));
await connect;
}
Uint8List _relayFrame({
required int peerIndex,
required int sequence,
int epoch = 0,
}) {
final header = HuddleAudioHeader(
sequence: sequence,
timestamp48k: sequence * 960,
levelDbov: -30,
flags: 0,
);
final clientFrame = HuddleWireV2.encodeClientFrame(
header,
Uint8List.fromList([sequence & 0xff]),
);
return Uint8List.fromList([peerIndex, ...clientFrame]);
}
Future<void> _waitForPhase(
HuddleTransport transport,
HuddleTransportPhase phase,
) async {
for (var attempt = 0; attempt < 100; attempt++) {
if (transport.state.phase == phase) return;
await Future<void>.delayed(const Duration(milliseconds: 1));
}
fail('Transport never reached ${phase.name}; was ${transport.state.phase}.');
}
Future<void> _waitForRevision(HuddleTransport transport, int revision) async {
for (var attempt = 0; attempt < 100; attempt++) {
if (transport.state.rosterRevision == revision) return;
await Future<void>.delayed(const Duration(milliseconds: 1));
}
fail(
'Transport never reached roster revision $revision; '
'was ${transport.state.rosterRevision}.',
);
}
final class _ControlledWebSocketChannel implements WebSocketChannel {
final StreamController<dynamic> _streamController = StreamController();
final _RecordingWebSocketSink _sink = _RecordingWebSocketSink();
void emitText(String value) => _streamController.add(value);
void emitBinary(Uint8List value) => _streamController.add(value);
void emitError(Object error) => _streamController.addError(error);
@override
Future<void> get ready => Future.value();
@override
Stream<dynamic> get stream => _streamController.stream;
@override
_RecordingWebSocketSink get sink => _sink;
@override
int? get closeCode => null;
@override
String? get closeReason => null;
@override
String? get protocol => null;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
final class _RecordingWebSocketSink implements WebSocketSink {
final List<dynamic> sent = [];
@override
void add(dynamic event) => sent.add(event);
@override
void addError(Object error, [StackTrace? stackTrace]) {}
@override
Future<void> addStream(Stream<dynamic> stream) async {
await for (final event in stream) {
sent.add(event);
}
}
@override
Future<void> close([int? closeCode, String? closeReason]) async {}
@override
Future<void> get done => Future.value();
}