feat: import Chinese-localized Buzz source snapshot
Docker image / Build (linux/amd64) (push) Has been cancelled
Docker image / Build (linux/arm64) (push) Has been cancelled
Docker image / Merge release multi-arch manifest (push) Has been cancelled
Docker image / Merge debug multi-arch manifest (push) Has been cancelled
Docker image / Build public push gateway (linux/amd64) (push) Has been cancelled
Docker image / Build public push gateway (linux/arm64) (push) Has been cancelled
Docker image / Publish public push gateway image (push) Has been cancelled
Sprig image / Build (linux/amd64) (push) Has been cancelled
Sprig image / Build (linux/arm64) (push) Has been cancelled
Sprig image / Merge multi-arch manifest (push) Has been cancelled
Harbor Buzz Orchestra / Python tests and lint (push) Has been cancelled
CI / Detect Changed Paths (push) Has been cancelled
CI / Rust Lint (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Desktop Core (push) Has been cancelled
CI / Desktop Smoke E2E (1) (push) Has been cancelled
CI / Desktop Smoke E2E (2) (push) Has been cancelled
CI / Desktop Smoke E2E (3) (push) Has been cancelled
CI / Desktop Smoke E2E (4) (push) Has been cancelled
CI / Desktop (push) Has been cancelled
CI / Desktop E2E Relay (push) Has been cancelled
CI / Desktop E2E Integration (1/2) (push) Has been cancelled
CI / Desktop E2E Integration (2/2) (push) Has been cancelled
CI / Desktop E2E Integration (push) Has been cancelled
CI / Backend Integration (relay e2e) (push) Has been cancelled
CI / Relay E2E (push) Has been cancelled
CI / Web (push) Has been cancelled
CI / Mobile (push) Has been cancelled
CI / Security (push) Has been cancelled
CI / Dead Token Reference Guard (push) Has been cancelled
CI / Server Cross-Compile (aarch64-unknown-linux-musl) (push) Has been cancelled
CI / Server Cross-Compile (x86_64-unknown-linux-musl) (push) Has been cancelled
CI / Windows Rust (x86_64-pc-windows-msvc) (push) Has been cancelled
CI / Desktop Build (macOS) (push) Has been cancelled
helm chart / lint + unittest + render matrix (push) Has been cancelled
helm chart / install on kind (gated) (push) Has been cancelled
helm chart / publish chart to GHCR (push) Has been cancelled
Mesh Lifecycle / Relay-Driven Mesh Lifecycle Smoke (push) Has been cancelled
Sprig / Build (aarch64-unknown-linux-musl) (push) Has been cancelled
Sprig / Build (x86_64-unknown-linux-musl) (push) Has been cancelled
Sprig / Publish rolling release (push) Has been cancelled
Sprig / Publish tagged release (push) Has been cancelled
Docker image / Build (linux/amd64) (push) Has been cancelled
Docker image / Build (linux/arm64) (push) Has been cancelled
Docker image / Merge release multi-arch manifest (push) Has been cancelled
Docker image / Merge debug multi-arch manifest (push) Has been cancelled
Docker image / Build public push gateway (linux/amd64) (push) Has been cancelled
Docker image / Build public push gateway (linux/arm64) (push) Has been cancelled
Docker image / Publish public push gateway image (push) Has been cancelled
Sprig image / Build (linux/amd64) (push) Has been cancelled
Sprig image / Build (linux/arm64) (push) Has been cancelled
Sprig image / Merge multi-arch manifest (push) Has been cancelled
Harbor Buzz Orchestra / Python tests and lint (push) Has been cancelled
CI / Detect Changed Paths (push) Has been cancelled
CI / Rust Lint (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Desktop Core (push) Has been cancelled
CI / Desktop Smoke E2E (1) (push) Has been cancelled
CI / Desktop Smoke E2E (2) (push) Has been cancelled
CI / Desktop Smoke E2E (3) (push) Has been cancelled
CI / Desktop Smoke E2E (4) (push) Has been cancelled
CI / Desktop (push) Has been cancelled
CI / Desktop E2E Relay (push) Has been cancelled
CI / Desktop E2E Integration (1/2) (push) Has been cancelled
CI / Desktop E2E Integration (2/2) (push) Has been cancelled
CI / Desktop E2E Integration (push) Has been cancelled
CI / Backend Integration (relay e2e) (push) Has been cancelled
CI / Relay E2E (push) Has been cancelled
CI / Web (push) Has been cancelled
CI / Mobile (push) Has been cancelled
CI / Security (push) Has been cancelled
CI / Dead Token Reference Guard (push) Has been cancelled
CI / Server Cross-Compile (aarch64-unknown-linux-musl) (push) Has been cancelled
CI / Server Cross-Compile (x86_64-unknown-linux-musl) (push) Has been cancelled
CI / Windows Rust (x86_64-pc-windows-msvc) (push) Has been cancelled
CI / Desktop Build (macOS) (push) Has been cancelled
helm chart / lint + unittest + render matrix (push) Has been cancelled
helm chart / install on kind (gated) (push) Has been cancelled
helm chart / publish chart to GHCR (push) Has been cancelled
Mesh Lifecycle / Relay-Driven Mesh Lifecycle Smoke (push) Has been cancelled
Sprig / Build (aarch64-unknown-linux-musl) (push) Has been cancelled
Sprig / Build (x86_64-unknown-linux-musl) (push) Has been cancelled
Sprig / Publish rolling release (push) Has been cancelled
Sprig / Publish tagged release (push) Has been cancelled
Signed-off-by: cls_宁波本机 <908705107@qq.com>
This commit is contained in:
@@ -0,0 +1,350 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:buzz/features/pairing/pairing_page.dart';
|
||||
import 'package:buzz/features/pairing/pairing_provider.dart';
|
||||
import 'package:buzz/shared/theme/theme.dart';
|
||||
import 'package:buzz/shared/l10n/l10n.dart';
|
||||
import 'package:buzz/shared/widgets/buzz_loading_indicator.dart';
|
||||
import 'package:buzz/shared/widgets/tappable_flapping_bee.dart';
|
||||
|
||||
import '../../helpers/widget_helpers.dart';
|
||||
|
||||
void main() {
|
||||
group('PairingPage', () {
|
||||
testWidgets('renders branding and progressive pairing actions', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(child: const PairingPage()),
|
||||
);
|
||||
|
||||
expect(find.byType(TappableFlappingBee), findsOneWidget);
|
||||
expect(find.text('Welcome to Buzz'), findsOneWidget);
|
||||
expect(find.text('Scan a QR code'), findsOneWidget);
|
||||
expect(find.text('Use pairing code'), findsOneWidget);
|
||||
expect(find.text('Connect'), findsNothing);
|
||||
expect(find.byType(TextField), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('uses compact desktop-style onboarding actions', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(child: const PairingPage()),
|
||||
);
|
||||
|
||||
final scanButton = tester.getSize(
|
||||
find.widgetWithText(FilledButton, 'Scan a QR code'),
|
||||
);
|
||||
final pairingCodeButton = tester.getSize(
|
||||
find.widgetWithText(TextButton, 'Use pairing code'),
|
||||
);
|
||||
|
||||
expect(scanButton.width, lessThan(440));
|
||||
expect(pairingCodeButton.width, lessThan(440));
|
||||
expect(find.byType(OutlinedButton), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('uses dark status-bar icons on the onboarding surface', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(child: const PairingPage()),
|
||||
);
|
||||
|
||||
final overlay = tester.widget<AnnotatedRegion<SystemUiOverlayStyle>>(
|
||||
find.byKey(const Key('pairing-onboarding-system-overlay')),
|
||||
);
|
||||
|
||||
expect(overlay.value.statusBarIconBrightness, Brightness.dark);
|
||||
expect(overlay.value.statusBarColor, Colors.transparent);
|
||||
});
|
||||
|
||||
testWidgets('uses light status-bar icons for dark-theme SAS verification', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
pairingProvider.overrideWith(() => _ConfirmingSasPairingNotifier()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: AppTheme.dark(),
|
||||
home: const PairingPage(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final overlay = tester.widget<AnnotatedRegion<SystemUiOverlayStyle>>(
|
||||
find.byKey(const Key('pairing-sas-system-overlay')),
|
||||
);
|
||||
|
||||
expect(overlay.value.statusBarIconBrightness, Brightness.light);
|
||||
expect(overlay.value.statusBarColor, Colors.transparent);
|
||||
expect(find.text('Verify Security Code'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('reveals pairing code field and connect action', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(child: const PairingPage()),
|
||||
);
|
||||
|
||||
await _expandPairingCode(tester);
|
||||
|
||||
expect(find.text('Hide pairing code'), findsOneWidget);
|
||||
expect(find.text('Connect'), findsOneWidget);
|
||||
expect(find.byType(TextField), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('connect button is below text field, not beside it', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(child: const PairingPage()),
|
||||
);
|
||||
await _expandPairingCode(tester);
|
||||
|
||||
final textField = tester.getBottomLeft(find.byType(TextField));
|
||||
final connectButton = tester.getTopLeft(
|
||||
find.widgetWithText(FilledButton, 'Connect'),
|
||||
);
|
||||
|
||||
// The connect button should be below the text field.
|
||||
expect(connectButton.dy, greaterThan(textField.dy));
|
||||
});
|
||||
|
||||
testWidgets('connect button is full width', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(child: const PairingPage()),
|
||||
);
|
||||
await _expandPairingCode(tester);
|
||||
|
||||
final connectButton = tester.getSize(
|
||||
find.widgetWithText(FilledButton, 'Connect'),
|
||||
);
|
||||
final textField = tester.getSize(find.byType(TextField));
|
||||
|
||||
// Button width should be close to the text field width (both full-width).
|
||||
expect(connectButton.width, closeTo(textField.width, 2.0));
|
||||
});
|
||||
|
||||
testWidgets('shows error container when pairing fails', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(
|
||||
overrides: [
|
||||
pairingProvider.overrideWith(
|
||||
() => _ErrorPairingNotifier('Invalid pairing code: bad input'),
|
||||
),
|
||||
],
|
||||
child: const PairingPage(),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('Invalid pairing code: bad input'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('shows spinner when connecting', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(
|
||||
overrides: [
|
||||
pairingProvider.overrideWith(() => _ConnectingPairingNotifier()),
|
||||
],
|
||||
child: const PairingPage(),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(BuzzLoadingIndicator), findsOneWidget);
|
||||
// Connect text should be replaced by spinner.
|
||||
expect(find.text('Connect'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('pairing actions are disabled when connecting', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(
|
||||
overrides: [
|
||||
pairingProvider.overrideWith(() => _ConnectingPairingNotifier()),
|
||||
],
|
||||
child: const PairingPage(),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
final scanButton = tester.widget<FilledButton>(find.byType(FilledButton));
|
||||
final pairingCodeButton = tester.widget<TextButton>(
|
||||
find.widgetWithText(TextButton, 'Use pairing code'),
|
||||
);
|
||||
|
||||
expect(scanButton.onPressed, isNull);
|
||||
expect(pairingCodeButton.onPressed, isNull);
|
||||
});
|
||||
|
||||
testWidgets('recovery entry rejects ordinary nostrpair codes', (
|
||||
tester,
|
||||
) async {
|
||||
final notifier = _RecordingPairingNotifier();
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(
|
||||
overrides: [pairingProvider.overrideWith(() => notifier)],
|
||||
child: const PairingPage(
|
||||
addingCommunity: true,
|
||||
identityRecoveryOnly: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await _expandPairingCode(tester);
|
||||
await tester.enterText(find.byType(TextField), 'nostrpair://ordinary');
|
||||
await tester.tap(find.text('Connect'));
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('Scan a desktop recovery code.'), findsOneWidget);
|
||||
expect(notifier.pairedCodes, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('recovery entry accepts mode=recover codes', (tester) async {
|
||||
final notifier = _RecordingPairingNotifier();
|
||||
await tester.pumpWidget(
|
||||
WidgetHelpers.testable(
|
||||
overrides: [pairingProvider.overrideWith(() => notifier)],
|
||||
child: const PairingPage(
|
||||
addingCommunity: true,
|
||||
identityRecoveryOnly: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await _expandPairingCode(tester);
|
||||
const code = 'nostrpair://desktop?mode=recover';
|
||||
await tester.enterText(find.byType(TextField), code);
|
||||
await tester.tap(find.text('Connect'));
|
||||
await tester.pump();
|
||||
|
||||
expect(notifier.pairedCodes, [code]);
|
||||
});
|
||||
|
||||
testWidgets('recovery SAS warns about permanent desktop access', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
pairingProvider.overrideWith(
|
||||
() => _ConfirmingSasPairingNotifier(sendsIdentityToDesktop: true),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: AppTheme.dark(),
|
||||
home: const PairingPage(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.textContaining('full Buzz identity'), findsOneWidget);
|
||||
expect(find.textContaining('permanent access'), findsOneWidget);
|
||||
expect(find.text('Codes Match'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _expandPairingCode(WidgetTester tester) async {
|
||||
await tester.tap(find.text('Use pairing code'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
class _ErrorPairingNotifier extends Notifier<PairingState>
|
||||
implements PairingNotifier {
|
||||
final String error;
|
||||
_ErrorPairingNotifier(this.error);
|
||||
|
||||
@override
|
||||
PairingState build() =>
|
||||
PairingState(status: PairingStatus.error, errorMessage: error);
|
||||
|
||||
@override
|
||||
Future<void> pair(String rawInput) async {}
|
||||
|
||||
@override
|
||||
void reset() {}
|
||||
|
||||
@override
|
||||
void confirmSas() {}
|
||||
|
||||
@override
|
||||
void denySas() {}
|
||||
}
|
||||
|
||||
class _ConnectingPairingNotifier extends Notifier<PairingState>
|
||||
implements PairingNotifier {
|
||||
@override
|
||||
PairingState build() => const PairingState(status: PairingStatus.connecting);
|
||||
|
||||
@override
|
||||
Future<void> pair(String rawInput) async {}
|
||||
|
||||
@override
|
||||
void reset() {}
|
||||
|
||||
@override
|
||||
void confirmSas() {}
|
||||
|
||||
@override
|
||||
void denySas() {}
|
||||
}
|
||||
|
||||
class _RecordingPairingNotifier extends Notifier<PairingState>
|
||||
implements PairingNotifier {
|
||||
final pairedCodes = <String>[];
|
||||
|
||||
@override
|
||||
PairingState build() => const PairingState();
|
||||
|
||||
@override
|
||||
Future<void> pair(String rawInput) async => pairedCodes.add(rawInput);
|
||||
|
||||
@override
|
||||
void reset() {}
|
||||
|
||||
@override
|
||||
void confirmSas() {}
|
||||
|
||||
@override
|
||||
void denySas() {}
|
||||
}
|
||||
|
||||
class _ConfirmingSasPairingNotifier extends Notifier<PairingState>
|
||||
implements PairingNotifier {
|
||||
_ConfirmingSasPairingNotifier({this.sendsIdentityToDesktop = false});
|
||||
|
||||
final bool sendsIdentityToDesktop;
|
||||
|
||||
@override
|
||||
PairingState build() => PairingState(
|
||||
status: PairingStatus.confirmingSas,
|
||||
sasCode: '123456',
|
||||
sendsIdentityToDesktop: sendsIdentityToDesktop,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<void> pair(String rawInput) async {}
|
||||
|
||||
@override
|
||||
void reset() {}
|
||||
|
||||
@override
|
||||
void confirmSas() {}
|
||||
|
||||
@override
|
||||
void denySas() {}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
import 'package:buzz/features/pairing/pairing_crypto.dart';
|
||||
import 'package:buzz/features/pairing/pairing_provider.dart';
|
||||
import 'package:buzz/features/pairing/pairing_socket.dart';
|
||||
import 'package:buzz/shared/auth/auth.dart';
|
||||
import 'package:buzz/shared/crypto/ecdh.dart';
|
||||
import 'package:buzz/shared/crypto/nip44.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
|
||||
/// Tests for [PairingNotifier]'s legacy `buzz://` payload parsing and
|
||||
/// SSRF-prevention validation.
|
||||
///
|
||||
/// The pairing flow used to validate by calling `GET /api/users/me/profile`
|
||||
/// over HTTP. That has been replaced with a NIP-42 WebSocket handshake via
|
||||
/// [RelaySocket], which is constructed directly inside the provider with no
|
||||
/// dependency-injection hook — so the "happy path" that exercises the
|
||||
/// network is no longer mockable in a unit test.
|
||||
///
|
||||
/// What we still cover here:
|
||||
/// - Initial state.
|
||||
/// - Parsing every documented payload format (raw base64, `buzz://`
|
||||
/// prefix, whitespace).
|
||||
/// - Failure modes that return BEFORE any network call: invalid base64,
|
||||
/// wrong shape (non-object, missing fields, missing nsec), and SSRF
|
||||
/// guards (private IPs, non-http schemes).
|
||||
/// - `reset()` returning to idle from an error state.
|
||||
void main() {
|
||||
group('PairingNotifier', () {
|
||||
late ProviderContainer container;
|
||||
late FakeAuthNotifier fakeAuth;
|
||||
|
||||
ProviderContainer createContainer() {
|
||||
fakeAuth = FakeAuthNotifier();
|
||||
return ProviderContainer(
|
||||
overrides: [authProvider.overrideWith(() => fakeAuth)],
|
||||
);
|
||||
}
|
||||
|
||||
tearDown(() => container.dispose());
|
||||
|
||||
test('starts in idle state', () {
|
||||
container = createContainer();
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.idle);
|
||||
expect(state.errorMessage, isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'disconnect during connect does not null-dereference the socket',
|
||||
() async {
|
||||
final notifier = PairingNotifier(
|
||||
socketFactory:
|
||||
({
|
||||
required wsUrl,
|
||||
required ephemeralPrivkey,
|
||||
required onMessage,
|
||||
required void Function(Object? error) onDisconnected,
|
||||
}) => _DisconnectingSocket(disconnectCallback: onDisconnected),
|
||||
);
|
||||
container = ProviderContainer(
|
||||
overrides: [pairingProvider.overrideWith(() => notifier)],
|
||||
);
|
||||
const code =
|
||||
'nostrpair://62287897da61e3fa294b4570575f7db8bea147d6631150f2e4656714c645fb1e'
|
||||
'?secret=abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789'
|
||||
'&relay=wss%3A%2F%2Fpairing.buzz.xyz&v=1';
|
||||
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
|
||||
expect(container.read(pairingProvider).status, PairingStatus.error);
|
||||
expect(
|
||||
container.read(pairingProvider).errorMessage,
|
||||
contains('internal error'),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('payload missing nsec errors before contacting relay', () async {
|
||||
container = createContainer();
|
||||
|
||||
// Valid payload shape but no nsec — provider should refuse without
|
||||
// attempting any network call.
|
||||
final code = _encodePairingCode();
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('missing nsec'));
|
||||
expect(fakeAuth.lastCommunity, isNull);
|
||||
});
|
||||
|
||||
test('accepts buzz scheme prefix', () async {
|
||||
container = createContainer();
|
||||
|
||||
final code = 'buzz://${_encodePairingCode()}';
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('missing nsec'));
|
||||
expect(fakeAuth.lastCommunity, isNull);
|
||||
});
|
||||
|
||||
test('invalid base64 sets format error', () async {
|
||||
container = createContainer();
|
||||
|
||||
await container.read(pairingProvider.notifier).pair('not-valid!!!');
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('Invalid pairing code'));
|
||||
});
|
||||
|
||||
test('base64 with valid JSON but missing fields errors', () async {
|
||||
container = createContainer();
|
||||
|
||||
final code = base64Url.encode(utf8.encode(jsonEncode({'foo': 'bar'})));
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('Missing relayUrl'));
|
||||
});
|
||||
|
||||
test('empty input errors', () async {
|
||||
container = createContainer();
|
||||
|
||||
await container.read(pairingProvider.notifier).pair('');
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
});
|
||||
|
||||
test('rejects private IP relay URLs (SSRF)', () async {
|
||||
container = createContainer();
|
||||
|
||||
for (final ip in [
|
||||
'10.0.0.1',
|
||||
'172.16.0.1',
|
||||
'192.168.1.1',
|
||||
'169.254.169.254',
|
||||
]) {
|
||||
final code = _encodePairingCode(relayUrl: 'http://$ip:3000');
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error, reason: 'should reject $ip');
|
||||
expect(state.errorMessage, contains('private network'));
|
||||
container.read(pairingProvider.notifier).reset();
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects non-http/https schemes', () async {
|
||||
container = createContainer();
|
||||
|
||||
final code = _encodePairingCode(relayUrl: 'file:///etc/passwd');
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('Invalid pairing code'));
|
||||
});
|
||||
|
||||
test('rejects JSON array payload', () async {
|
||||
container = createContainer();
|
||||
|
||||
final code = base64Url.encode(utf8.encode(jsonEncode([1, 2, 3])));
|
||||
await container.read(pairingProvider.notifier).pair(code);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('not a JSON object'));
|
||||
});
|
||||
|
||||
test('reset returns to idle from error state', () async {
|
||||
container = createContainer();
|
||||
|
||||
// Trigger an error.
|
||||
await container.read(pairingProvider.notifier).pair('not-valid!!!');
|
||||
expect(container.read(pairingProvider).status, PairingStatus.error);
|
||||
|
||||
container.read(pairingProvider.notifier).reset();
|
||||
expect(container.read(pairingProvider).status, PairingStatus.idle);
|
||||
});
|
||||
|
||||
group('desktop identity recovery', () {
|
||||
const sourceSecret =
|
||||
'09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506';
|
||||
const sessionSecretHex =
|
||||
'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';
|
||||
late _ControllableSocket socket;
|
||||
late PairingNotifier notifier;
|
||||
late String recoveryCode;
|
||||
|
||||
setUp(() {
|
||||
final source = nostr.Keys(sourceSecret);
|
||||
recoveryCode =
|
||||
'nostrpair://${source.public}'
|
||||
'?secret=$sessionSecretHex'
|
||||
'&relay=wss%3A%2F%2Fpairing.buzz.xyz&v=1&mode=recover';
|
||||
notifier = PairingNotifier(
|
||||
socketFactory:
|
||||
({
|
||||
required wsUrl,
|
||||
required ephemeralPrivkey,
|
||||
required onMessage,
|
||||
required onDisconnected,
|
||||
}) {
|
||||
socket = _ControllableSocket(
|
||||
ephemeralPrivkey: ephemeralPrivkey,
|
||||
onMessage: onMessage,
|
||||
onDisconnected: onDisconnected,
|
||||
);
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
container = ProviderContainer(
|
||||
overrides: [
|
||||
pairingProvider.overrideWith(() => notifier),
|
||||
relayConfigProvider.overrideWith(_RecoveryRelayConfig.new),
|
||||
],
|
||||
);
|
||||
container.read(pairingProvider);
|
||||
notifier = container.read(pairingProvider.notifier);
|
||||
});
|
||||
|
||||
test('recovery URI enables phone-to-desktop transfer', () async {
|
||||
await notifier.pair(recoveryCode);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.confirmingSas);
|
||||
expect(state.sendsIdentityToDesktop, isTrue);
|
||||
expect(state.sasCode, hasLength(6));
|
||||
});
|
||||
|
||||
test(
|
||||
'matching SAS sends nsec and successful completion finishes',
|
||||
() async {
|
||||
await notifier.pair(recoveryCode);
|
||||
notifier.confirmSas();
|
||||
expect(container.read(pairingProvider).userConfirmedSas, isTrue);
|
||||
|
||||
socket.sendSourceMessage(
|
||||
sourceSecret: sourceSecret,
|
||||
sessionSecretHex: sessionSecretHex,
|
||||
message: {'type': 'sas-confirm'},
|
||||
includeTranscriptHash: true,
|
||||
);
|
||||
|
||||
expect(
|
||||
container.read(pairingProvider).status,
|
||||
PairingStatus.transferring,
|
||||
);
|
||||
final sentMessages = socket.decryptedPublishedMessages(sourceSecret);
|
||||
expect(
|
||||
sentMessages.any(
|
||||
(message) =>
|
||||
message['type'] == 'payload' &&
|
||||
message['payload_type'] == 'nsec' &&
|
||||
message['payload'] == _RecoveryRelayConfig.nsec,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
|
||||
socket.sendSourceMessage(
|
||||
sourceSecret: sourceSecret,
|
||||
sessionSecretHex: sessionSecretHex,
|
||||
message: {'type': 'complete', 'success': true},
|
||||
);
|
||||
expect(container.read(pairingProvider).status, PairingStatus.success);
|
||||
},
|
||||
);
|
||||
|
||||
test('desktop storage failure surfaces an error', () async {
|
||||
await notifier.pair(recoveryCode);
|
||||
notifier.confirmSas();
|
||||
socket.sendSourceMessage(
|
||||
sourceSecret: sourceSecret,
|
||||
sessionSecretHex: sessionSecretHex,
|
||||
message: {'type': 'sas-confirm'},
|
||||
includeTranscriptHash: true,
|
||||
);
|
||||
socket.sendSourceMessage(
|
||||
sourceSecret: sourceSecret,
|
||||
sessionSecretHex: sessionSecretHex,
|
||||
message: {'type': 'complete', 'success': false},
|
||||
);
|
||||
|
||||
final state = container.read(pairingProvider);
|
||||
expect(state.status, PairingStatus.error);
|
||||
expect(state.errorMessage, contains('could not store'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Encode a credentials payload the same way the desktop app would.
|
||||
String _encodePairingCode({
|
||||
String relayUrl = 'http://test:3000',
|
||||
String? pubkey,
|
||||
String? nsec,
|
||||
}) {
|
||||
final json = <String, dynamic>{
|
||||
'relayUrl': relayUrl,
|
||||
// ignore: use_null_aware_elements
|
||||
if (pubkey != null) 'pubkey': pubkey,
|
||||
// ignore: use_null_aware_elements
|
||||
if (nsec != null) 'nsec': nsec,
|
||||
};
|
||||
return base64Url.encode(utf8.encode(jsonEncode(json)));
|
||||
}
|
||||
|
||||
/// A fake [AuthNotifier] that records calls instead of touching secure storage.
|
||||
class FakeAuthNotifier extends AsyncNotifier<AuthState>
|
||||
implements AuthNotifier {
|
||||
Community? lastCommunity;
|
||||
bool signedOut = false;
|
||||
|
||||
@override
|
||||
Future<AuthState> build() async =>
|
||||
const AuthState(status: AuthStatus.unauthenticated);
|
||||
|
||||
@override
|
||||
Future<void> signOut() async {
|
||||
signedOut = true;
|
||||
state = const AsyncData(AuthState(status: AuthStatus.unauthenticated));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> authenticateWithCommunity(Community community) async {
|
||||
lastCommunity = community;
|
||||
state = AsyncData(
|
||||
AuthState(status: AuthStatus.authenticated, community: community),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DisconnectingSocket extends PairingSocket {
|
||||
final void Function(Object? error) disconnectCallback;
|
||||
|
||||
_DisconnectingSocket({required this.disconnectCallback})
|
||||
: super(
|
||||
wsUrl: 'ws://unused',
|
||||
ephemeralPrivkey:
|
||||
'09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506',
|
||||
onMessage: (_) {},
|
||||
onDisconnected: (_) {},
|
||||
);
|
||||
|
||||
@override
|
||||
Future<void> connect() async {
|
||||
disconnectCallback(Exception('Connection closed'));
|
||||
}
|
||||
}
|
||||
|
||||
class _RecoveryRelayConfig extends RelayConfigNotifier {
|
||||
static final nsec = nostr.Keys(
|
||||
'1111111111111111111111111111111111111111111111111111111111111111',
|
||||
).nsec;
|
||||
|
||||
@override
|
||||
RelayConfig build() => RelayConfig(baseUrl: 'https://relay.test', nsec: nsec);
|
||||
}
|
||||
|
||||
class _ControllableSocket extends PairingSocket {
|
||||
final String ephemeralPrivkey;
|
||||
final void Function(List<dynamic> message) relayMessageCallback;
|
||||
final List<Map<String, dynamic>> published = [];
|
||||
bool _connected = false;
|
||||
int _eventSequence = 0;
|
||||
|
||||
_ControllableSocket({
|
||||
required this.ephemeralPrivkey,
|
||||
required super.onMessage,
|
||||
required super.onDisconnected,
|
||||
}) : relayMessageCallback = onMessage,
|
||||
super(wsUrl: 'ws://unused', ephemeralPrivkey: ephemeralPrivkey);
|
||||
|
||||
@override
|
||||
bool get isConnected => _connected;
|
||||
|
||||
@override
|
||||
Future<void> connect() async => _connected = true;
|
||||
|
||||
@override
|
||||
void subscribe(String subId, int kind, String pubkeyHex) {}
|
||||
|
||||
@override
|
||||
void publishEvent(Map<String, dynamic> event) => published.add(event);
|
||||
|
||||
@override
|
||||
void dispose() => _connected = false;
|
||||
|
||||
List<Map<String, dynamic>> decryptedPublishedMessages(String sourceSecret) {
|
||||
final key = getConversationKey(
|
||||
sourceSecret,
|
||||
nostr.Keys(ephemeralPrivkey).public,
|
||||
);
|
||||
return published
|
||||
.map(
|
||||
(event) =>
|
||||
jsonDecode(nip44Decrypt(key, event['content'] as String))
|
||||
as Map<String, dynamic>,
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
void sendSourceMessage({
|
||||
required String sourceSecret,
|
||||
required String sessionSecretHex,
|
||||
required Map<String, dynamic> message,
|
||||
bool includeTranscriptHash = false,
|
||||
}) {
|
||||
final source = nostr.Keys(sourceSecret);
|
||||
final targetPubkey = nostr.Keys(ephemeralPrivkey).public;
|
||||
final sessionSecret = hexToBytes(sessionSecretHex);
|
||||
final body = Map<String, dynamic>.from(message);
|
||||
if (includeTranscriptHash) {
|
||||
final shared = ecdhSharedSecret(sourceSecret, targetPubkey);
|
||||
final (_, sasInput) = deriveSas(shared, sessionSecret);
|
||||
body['transcript_hash'] = bytesToHex(
|
||||
deriveTranscriptHash(
|
||||
deriveSessionId(sessionSecret),
|
||||
hexToBytes(source.public),
|
||||
hexToBytes(targetPubkey),
|
||||
sasInput,
|
||||
sessionSecret,
|
||||
),
|
||||
);
|
||||
}
|
||||
final key = getConversationKey(sourceSecret, targetPubkey);
|
||||
final event = nostr.Event.from(
|
||||
kind: 24134,
|
||||
content: nip44Encrypt(key, jsonEncode(body)),
|
||||
tags: [
|
||||
['p', targetPubkey],
|
||||
],
|
||||
secretKey: sourceSecret,
|
||||
createdAt: 1_700_000_000 + _eventSequence++,
|
||||
);
|
||||
relayMessageCallback(['EVENT', 'pair', event.toMap()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:buzz/features/pairing/pairing_qr_scanner.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
|
||||
const _qrScannerPlatformChannel = MethodChannel('buzz/qr_scanner');
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final defaultScannerPlatform = MobileScannerPlatform.instance;
|
||||
late _FakeMobileScannerPlatform fakeScannerPlatform;
|
||||
|
||||
setUp(() {
|
||||
fakeScannerPlatform = _FakeMobileScannerPlatform();
|
||||
MobileScannerPlatform.instance = fakeScannerPlatform;
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(_qrScannerPlatformChannel, null);
|
||||
await fakeScannerPlatform.dispose();
|
||||
MobileScannerPlatform.instance = defaultScannerPlatform;
|
||||
});
|
||||
|
||||
group('DynamicIslandQrScannerGeometry', () {
|
||||
const viewport = Size(393, 852);
|
||||
const geometry = DynamicIslandQrScannerGeometry(
|
||||
viewport: viewport,
|
||||
safeAreaTop: 59,
|
||||
);
|
||||
|
||||
test('starts at the physical Dynamic Island frame', () {
|
||||
expect(geometry.collapsedFrame, const Rect.fromLTWH(136.5, 11, 120, 36));
|
||||
});
|
||||
|
||||
test('keeps the top edge fixed while the camera grows down', () {
|
||||
final start = geometry.frameAt(0);
|
||||
final middle = geometry.frameAt(0.5);
|
||||
final end = geometry.frameAt(1);
|
||||
|
||||
expect(middle.top, start.top);
|
||||
expect(end.top, start.top);
|
||||
expect(middle.bottom, greaterThan(start.bottom));
|
||||
expect(end.bottom, greaterThan(middle.bottom));
|
||||
expect(end, const Rect.fromLTWH(15, 11, 363, 363));
|
||||
});
|
||||
|
||||
test('delays the camera until the portal has left the island', () {
|
||||
expect(geometry.scannerOpacityAt(0.18), 0);
|
||||
expect(geometry.scannerOpacityAt(0.5), greaterThan(0));
|
||||
expect(geometry.scannerOpacityAt(1), 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('usesDynamicIslandQrScannerPortal', () {
|
||||
test('asks the native bridge on iOS', () async {
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
|
||||
expect(call.method, 'usesDynamicIslandQrScannerPortal');
|
||||
return true;
|
||||
});
|
||||
|
||||
expect(await usesDynamicIslandQrScannerPortal(), isTrue);
|
||||
});
|
||||
|
||||
test('uses the fallback without asking native code on Android', () async {
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
||||
var nativeCalls = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
|
||||
nativeCalls += 1;
|
||||
return true;
|
||||
});
|
||||
|
||||
expect(await usesDynamicIslandQrScannerPortal(), isFalse);
|
||||
expect(nativeCalls, 0);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('fallback reveals the camera behind the current app surface', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(375, 667));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
|
||||
var scannerClosed = false;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: FallbackPairingQrScanner(
|
||||
appSurface: const ColoredBox(
|
||||
color: Colors.white,
|
||||
child: Center(child: Text('Current app surface')),
|
||||
),
|
||||
onClosed: (_) {
|
||||
scannerClosed = true;
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final sheet = find.byKey(const ValueKey('fallback-qr-scanner-app-sheet'));
|
||||
expect(tester.getRect(sheet).top, 0);
|
||||
expect(find.text('Current app surface'), findsOneWidget);
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 420));
|
||||
expect(tester.getRect(sheet).top, closeTo(555, 0.1));
|
||||
|
||||
await tester.tapAt(const Offset(187.5, 100));
|
||||
await tester.pump();
|
||||
expect(scannerClosed, isFalse);
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 320));
|
||||
await tester.pumpAndSettle();
|
||||
expect(scannerClosed, isTrue);
|
||||
expect(tester.getRect(sheet).top, 0);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'portal route opens from the island and an outside tap reverses it closed',
|
||||
(tester) async {
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
|
||||
return switch (call.method) {
|
||||
'usesDynamicIslandQrScannerPortal' => true,
|
||||
'setDynamicIslandScannerStatusBarHidden' => null,
|
||||
_ => null,
|
||||
};
|
||||
});
|
||||
await tester.binding.setSurfaceSize(const Size(393, 852));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
|
||||
var scannerClosed = false;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: MediaQuery(
|
||||
data: const MediaQueryData(
|
||||
size: Size(393, 852),
|
||||
viewPadding: EdgeInsets.only(top: 59),
|
||||
),
|
||||
child: Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () async {
|
||||
await showDynamicIslandPairingQrScanner(context);
|
||||
scannerClosed = true;
|
||||
},
|
||||
child: const Text('Open scanner'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Open scanner'));
|
||||
await tester.pump();
|
||||
|
||||
final portal = find.byKey(
|
||||
const ValueKey('dynamic-island-qr-scanner-portal'),
|
||||
);
|
||||
expect(tester.getRect(portal), const Rect.fromLTWH(136.5, 11, 120, 36));
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 460));
|
||||
expect(tester.getRect(portal).top, 11);
|
||||
expect(
|
||||
find.byKey(const ValueKey('dynamic-island-qr-scanner-close')),
|
||||
findsNothing,
|
||||
);
|
||||
|
||||
await tester.tapAt(const Offset(196.5, 700));
|
||||
await tester.pump();
|
||||
expect(scannerClosed, isFalse);
|
||||
|
||||
await tester.pump(const Duration(milliseconds: 340));
|
||||
await tester.pumpAndSettle();
|
||||
expect(scannerClosed, isTrue);
|
||||
expect(portal, findsNothing);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('tapping the scanner closes it without a separate control', (
|
||||
tester,
|
||||
) async {
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(_qrScannerPlatformChannel, (call) async {
|
||||
return switch (call.method) {
|
||||
'usesDynamicIslandQrScannerPortal' => true,
|
||||
'setDynamicIslandScannerStatusBarHidden' => null,
|
||||
_ => null,
|
||||
};
|
||||
});
|
||||
await tester.binding.setSurfaceSize(const Size(393, 852));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
|
||||
var scannerClosed = false;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
builder: (context, child) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(disableAnimations: true),
|
||||
child: child!,
|
||||
),
|
||||
home: Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () async {
|
||||
await showDynamicIslandPairingQrScanner(context);
|
||||
scannerClosed = true;
|
||||
},
|
||||
child: const Text('Open scanner'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Open scanner'));
|
||||
await tester.pump();
|
||||
|
||||
final portal = find.byKey(
|
||||
const ValueKey('dynamic-island-qr-scanner-portal'),
|
||||
);
|
||||
expect(tester.getRect(portal), const Rect.fromLTWH(15, 11, 363, 363));
|
||||
|
||||
await tester.tapAt(tester.getCenter(portal));
|
||||
await tester.pump();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(scannerClosed, isTrue);
|
||||
expect(portal, findsNothing);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
}
|
||||
|
||||
class _FakeMobileScannerPlatform extends MobileScannerPlatform {
|
||||
final _barcodes = StreamController<BarcodeCapture?>.broadcast();
|
||||
var _isDisposed = false;
|
||||
|
||||
@override
|
||||
Stream<BarcodeCapture?> get barcodesStream => _barcodes.stream;
|
||||
|
||||
@override
|
||||
Stream<TorchState> get torchStateStream =>
|
||||
Stream.value(TorchState.unavailable);
|
||||
|
||||
@override
|
||||
Stream<double> get zoomScaleStateStream => Stream.value(1);
|
||||
|
||||
@override
|
||||
Future<MobileScannerViewAttributes> start(StartOptions startOptions) async {
|
||||
return const MobileScannerViewAttributes(
|
||||
cameraDirection: CameraFacing.back,
|
||||
currentTorchMode: TorchState.unavailable,
|
||||
size: Size(200, 200),
|
||||
numberOfCameras: 1,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildCameraView() => const SizedBox.expand();
|
||||
|
||||
@override
|
||||
Future<void> stop() async {}
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
if (_isDisposed) {
|
||||
return;
|
||||
}
|
||||
_isDisposed = true;
|
||||
await _barcodes.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:buzz/features/pairing/pairing_socket.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
|
||||
const _privateKey =
|
||||
'09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506';
|
||||
|
||||
void main() {
|
||||
group('PairingSocket', () {
|
||||
test('connects when the pairing relay sends no AUTH challenge', () async {
|
||||
final server = await _TestRelay.start((_) {});
|
||||
addTearDown(server.close);
|
||||
final socket = _socket(
|
||||
server.url,
|
||||
authChallengeTimeout: const Duration(milliseconds: 30),
|
||||
);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await socket.connect();
|
||||
|
||||
expect(socket.isConnected, isTrue);
|
||||
});
|
||||
|
||||
test('answers an AUTH challenge and requires an accepted OK', () async {
|
||||
final authReceived = Completer<List<dynamic>>();
|
||||
final server = await _TestRelay.start((webSocket) async {
|
||||
webSocket.add(jsonEncode(['AUTH', 'challenge']));
|
||||
final auth =
|
||||
jsonDecode(await webSocket.first as String) as List<dynamic>;
|
||||
authReceived.complete(auth);
|
||||
final event = auth[1] as Map<String, dynamic>;
|
||||
webSocket.add(jsonEncode(['OK', event['id'], true, 'authenticated']));
|
||||
});
|
||||
addTearDown(server.close);
|
||||
final socket = _socket(server.url);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await socket.connect();
|
||||
|
||||
expect(socket.isConnected, isTrue);
|
||||
expect((await authReceived.future).first, 'AUTH');
|
||||
});
|
||||
|
||||
test('fails when the pairing relay rejects AUTH', () async {
|
||||
final server = await _TestRelay.start((webSocket) async {
|
||||
webSocket.add(jsonEncode(['AUTH', 'challenge']));
|
||||
final auth =
|
||||
jsonDecode(await webSocket.first as String) as List<dynamic>;
|
||||
final event = auth[1] as Map<String, dynamic>;
|
||||
webSocket.add(jsonEncode(['OK', event['id'], false, 'bad auth']));
|
||||
});
|
||||
addTearDown(server.close);
|
||||
var disconnectCount = 0;
|
||||
final socket = _socket(
|
||||
server.url,
|
||||
onDisconnected: (_) => disconnectCount++,
|
||||
);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await expectLater(socket.connect(), throwsA(isA<PairingAuthException>()));
|
||||
|
||||
expect(socket.isConnected, isFalse);
|
||||
expect(disconnectCount, 1);
|
||||
});
|
||||
|
||||
test(
|
||||
'answers a challenge after the optional AUTH wait completes',
|
||||
() async {
|
||||
final authReceived = Completer<void>();
|
||||
final server = await _TestRelay.start((webSocket) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 80));
|
||||
webSocket.add(jsonEncode(['AUTH', 'late-challenge']));
|
||||
final auth =
|
||||
jsonDecode(await webSocket.first as String) as List<dynamic>;
|
||||
final event = auth[1] as Map<String, dynamic>;
|
||||
webSocket.add(jsonEncode(['OK', event['id'], true, 'authenticated']));
|
||||
authReceived.complete();
|
||||
});
|
||||
addTearDown(server.close);
|
||||
final socket = _socket(
|
||||
server.url,
|
||||
authChallengeTimeout: const Duration(milliseconds: 30),
|
||||
);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await socket.connect();
|
||||
await authReceived.future;
|
||||
|
||||
expect(socket.isConnected, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('fails when AUTH receives no OK response', () async {
|
||||
final server = await _TestRelay.start((webSocket) {
|
||||
webSocket.add(jsonEncode(['AUTH', 'challenge']));
|
||||
});
|
||||
addTearDown(server.close);
|
||||
final socket = _socket(
|
||||
server.url,
|
||||
authResponseTimeout: const Duration(milliseconds: 100),
|
||||
);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await expectLater(socket.connect(), throwsA(isA<PairingAuthException>()));
|
||||
|
||||
expect(socket.isConnected, isFalse);
|
||||
});
|
||||
|
||||
test('notifies once when a connected stream emits an error', () async {
|
||||
var disconnectCount = 0;
|
||||
final channel = _ControlledWebSocketChannel();
|
||||
final socket = _socket(
|
||||
'ws://unused',
|
||||
onDisconnected: (_) => disconnectCount++,
|
||||
channelFactory: (_) => channel,
|
||||
authChallengeTimeout: Duration.zero,
|
||||
);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await socket.connect();
|
||||
channel.emitError(Exception('stream failed'));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(disconnectCount, 1);
|
||||
});
|
||||
|
||||
test('notifies once when a connected stream closes', () async {
|
||||
var disconnectCount = 0;
|
||||
final channel = _ControlledWebSocketChannel();
|
||||
final socket = _socket(
|
||||
'ws://unused',
|
||||
onDisconnected: (_) => disconnectCount++,
|
||||
channelFactory: (_) => channel,
|
||||
authChallengeTimeout: Duration.zero,
|
||||
);
|
||||
addTearDown(socket.disconnect);
|
||||
|
||||
await socket.connect();
|
||||
await channel.closeStream();
|
||||
|
||||
expect(disconnectCount, 1);
|
||||
});
|
||||
|
||||
test(
|
||||
'does not notify when deliberately disconnected or disposed',
|
||||
() async {
|
||||
var disconnectCount = 0;
|
||||
final disconnectChannel = _ControlledWebSocketChannel();
|
||||
final disconnectingSocket = _socket(
|
||||
'ws://unused',
|
||||
onDisconnected: (_) => disconnectCount++,
|
||||
channelFactory: (_) => disconnectChannel,
|
||||
authChallengeTimeout: Duration.zero,
|
||||
);
|
||||
await disconnectingSocket.connect();
|
||||
|
||||
await disconnectingSocket.disconnect();
|
||||
|
||||
final disposeChannel = _ControlledWebSocketChannel();
|
||||
final disposingSocket = _socket(
|
||||
'ws://unused',
|
||||
onDisconnected: (_) => disconnectCount++,
|
||||
channelFactory: (_) => disposeChannel,
|
||||
authChallengeTimeout: Duration.zero,
|
||||
);
|
||||
await disposingSocket.connect();
|
||||
|
||||
disposingSocket.dispose();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(disconnectCount, 0);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
PairingSocket _socket(
|
||||
String url, {
|
||||
Duration authChallengeTimeout = const Duration(milliseconds: 500),
|
||||
Duration authResponseTimeout = const Duration(seconds: 10),
|
||||
void Function(Object? error)? onDisconnected,
|
||||
WebSocketChannel Function(Uri uri)? channelFactory,
|
||||
}) => PairingSocket(
|
||||
wsUrl: url,
|
||||
ephemeralPrivkey: _privateKey,
|
||||
onMessage: (_) {},
|
||||
onDisconnected: onDisconnected ?? (_) {},
|
||||
authChallengeTimeout: authChallengeTimeout,
|
||||
authResponseTimeout: authResponseTimeout,
|
||||
channelFactory: channelFactory ?? WebSocketChannel.connect,
|
||||
);
|
||||
|
||||
class _ControlledWebSocketChannel implements WebSocketChannel {
|
||||
final StreamController<dynamic> _streamController = StreamController();
|
||||
final WebSocketSink _sink = _ControlledWebSocketSink();
|
||||
|
||||
void emitError(Object error) => _streamController.addError(error);
|
||||
|
||||
Future<void> closeStream() => _streamController.close();
|
||||
|
||||
@override
|
||||
Future<void> get ready => Future.value();
|
||||
|
||||
@override
|
||||
Stream<dynamic> get stream => _streamController.stream;
|
||||
|
||||
@override
|
||||
WebSocketSink 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);
|
||||
}
|
||||
|
||||
class _ControlledWebSocketSink implements WebSocketSink {
|
||||
@override
|
||||
void add(dynamic event) {}
|
||||
|
||||
@override
|
||||
void addError(Object error, [StackTrace? stackTrace]) {}
|
||||
|
||||
@override
|
||||
Future<void> addStream(Stream<dynamic> stream) async {
|
||||
await stream.drain<void>();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close([int? closeCode, String? closeReason]) async {}
|
||||
|
||||
@override
|
||||
Future<void> get done => Future.value();
|
||||
}
|
||||
|
||||
class _TestRelay {
|
||||
final HttpServer _server;
|
||||
final List<WebSocket> _sockets = [];
|
||||
|
||||
_TestRelay._(this._server);
|
||||
|
||||
String get url => 'ws://${_server.address.host}:${_server.port}';
|
||||
|
||||
static Future<_TestRelay> start(
|
||||
FutureOr<void> Function(WebSocket socket) onConnected,
|
||||
) async {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final relay = _TestRelay._(server);
|
||||
server.listen((request) async {
|
||||
final socket = await WebSocketTransformer.upgrade(request);
|
||||
relay._sockets.add(socket);
|
||||
await onConnected(socket);
|
||||
});
|
||||
return relay;
|
||||
}
|
||||
|
||||
Future<void> close() async {
|
||||
for (final socket in _sockets) {
|
||||
await socket.close();
|
||||
}
|
||||
await _server.close(force: true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user