Files
buzz/mobile/lib/features/activity/compose_drafts_provider.dart
Krishna CandGitHub 047533c56c fix(mobile): keep TLS on relays joined by invite (#3139)
## Summary

Communities joined via an invite link never connect: the app dials
`ws://` on port 80 instead of `wss://` on 443 and sits on
"Reconnecting…" indefinitely.

`RelayConfig.baseUrl` is documented as an HTTP origin, but the two
onboarding flows disagree on what they persist:

- **Device pairing** validates and stores `https://` —
`pairing_provider.dart:657` throws on anything else.
- **Invite join** stores the relay URL straight off the invite link, and
`deep_link.dart:165` always emits `ws://` or `wss://`.

`wsUrl` only special-cased `https://`, so a `wss://` base fell through
to the plaintext branch:

```dart
final scheme = uri.scheme == 'https' ? 'wss' : 'ws';   // 'wss' is not 'https'
```

The claim request itself succeeds, because `_claimUrlFromRelay`
(`invite_join_provider.dart:242`) maps `wss → https` explicitly. Only
the socket path is missing that conversion — which is why the community
appears, correctly named, and then never loads.

The same `baseUrl` also feeds `/query` (`relay_session.dart:136`), media
upload (`media_upload.dart:765`), Blossom auth (`media_auth.dart:128`)
and `relayClientProvider` (`relay_provider.dart:113`), so those requests
were malformed too. Where port 80 *does* answer, it is additionally a
silent TLS downgrade after `validateInviteRelayUri` insisted on
`wss://`.

This folds the websocket schemes back to their HTTP equivalents in
`baseUrl` itself, so every consumer is correct by construction rather
than needing a second getter remembered at each call site, and
communities **already persisted** with `wss://` are repaired on read
without a migration. `community_icon_provider.dart:46` already performs
this same conversion locally.

One subtlety worth flagging for review: the normalization is derived in
the getter rather than applied in the constructor, so the constructor
stays `const`. The compile-time fallback at `relay_provider.dart:77`
relies on const canonicalization for a stable identity across rebuilds,
and Riverpod's `defaultUpdateShouldNotify` is `previous != next`
(`element.dart:361`), which falls back to identity for this class. A
`factory` constructor here yields a fresh instance per rebuild, which
tears down and resubscribes every listener —
`channels_provider_test.dart` catches it as an unexpected unsubscribe
during reconnect.

### Related issue

Fixes #2662.

### Testing

`flutter test` — **705 passed, 1 skipped, 0 failed**
`flutter analyze` — No issues found
`dart format --set-exit-if-changed .` — 249 files, 0 changed

Run against the Hermit-pinned SDK (Flutter 3.41.7 / Dart 3.11.5),
matching CI.

10 new unit tests in `mobile/test/shared/relay/relay_config_test.dart`
covering both onboarding schemes, `http`/`https` passthrough,
non-default ports, and agreement between the invite and pairing paths
for the same relay.

Verified end-to-end against a self-hosted relay behind `tailscale
serve`, which terminates TLS on 443 and leaves port 80 closed. Relay
logs show the invite claim succeeding over HTTPS at the moment of
joining, while no WebSocket connection ever arrives — no `WebSocket
connection established`, no NIP-42 auth, no `kind:0` profile, no push
registration — across the relay's entire history, even though the member
row is present and correct. Port-80 refusals are not logged by
`tailscaled`'s netstack, which is why the retries leave no trace
server-side. Reproduced on both iOS and Android.

---------

Signed-off-by: Krishna C <github@kumb.uk>
2026-07-29 12:02:42 -07:00

151 lines
4.5 KiB
Dart

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/relay/relay.dart';
import '../../shared/theme/theme_provider.dart';
const _draftsPrefsKey = 'compose_drafts_v1';
const _maxDrafts = 50;
/// A locally persisted, unsent composer draft.
///
/// Mobile has no durable relay-backed draft store (desktop keeps drafts
/// locally too), so drafts are device-local by design: the inbox Drafts
/// filter reflects what this device's composer has in flight.
@immutable
class ComposeDraft {
/// `<channelId>` for channel composers, `<channelId>:<threadHeadId>` for
/// thread composers.
final String key;
final String channelId;
final String? threadHeadId;
final String text;
final int updatedAt; // unix seconds
const ComposeDraft({
required this.key,
required this.channelId,
required this.threadHeadId,
required this.text,
required this.updatedAt,
});
Map<String, dynamic> toJson() => {
'key': key,
'channel_id': channelId,
if (threadHeadId != null) 'thread_head_id': threadHeadId,
'text': text,
'updated_at': updatedAt,
};
static ComposeDraft? fromJson(Object? raw) {
if (raw is! Map<String, dynamic>) return null;
final key = raw['key'];
final channelId = raw['channel_id'];
final text = raw['text'];
final updatedAt = raw['updated_at'];
if (key is! String || channelId is! String || text is! String) return null;
if (text.trim().isEmpty) return null;
return ComposeDraft(
key: key,
channelId: channelId,
threadHeadId: raw['thread_head_id'] as String?,
text: text,
updatedAt: updatedAt is int ? updatedAt : 0,
);
}
}
String composeDraftKey(String channelId, {String? threadHeadId}) =>
threadHeadId == null ? channelId : '$channelId:$threadHeadId';
/// SharedPreferences-backed store of unsent composer drafts, newest first.
///
/// Drafts are plaintext, so persistence is namespaced by community (relay)
/// and account pubkey: switching community or account rebuilds this provider
/// against that identity's own store and can never surface another
/// identity's draft text.
class ComposeDraftsNotifier extends Notifier<List<ComposeDraft>> {
late String _prefsKey;
@override
List<ComposeDraft> build() {
// Rebuild (and re-read the identity-scoped store) whenever the active
// community or the derived account pubkey changes.
final config = ref.watch(relayConfigProvider);
final pubkey = ref.watch(myPubkeyProvider) ?? 'anon';
_prefsKey = '$_draftsPrefsKey:${config.baseUrl}:$pubkey';
final prefs = ref.read(savedPrefsProvider);
final raw = readMigratedPref<String>(
prefs,
canonicalKey: _prefsKey,
legacyKey: '$_draftsPrefsKey:${config.storedOrigin}:$pubkey',
read: prefs.getString,
write: prefs.setString,
);
if (raw == null) return const [];
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return const [];
final drafts = decoded
.map(ComposeDraft.fromJson)
.whereType<ComposeDraft>()
.toList();
drafts.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
return drafts;
} catch (_) {
return const [];
}
}
/// Persist [text] for the composer identified by [key]. Empty text removes
/// the draft.
void save({
required String key,
required String channelId,
String? threadHeadId,
required String text,
}) {
if (text.trim().isEmpty) {
remove(key);
return;
}
final existing = state.where((d) => d.key == key).firstOrNull;
if (existing?.text == text) return;
final draft = ComposeDraft(
key: key,
channelId: channelId,
threadHeadId: threadHeadId,
text: text,
updatedAt: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
final next = [draft, ...state.where((d) => d.key != key)];
_persist(next.length > _maxDrafts ? next.sublist(0, _maxDrafts) : next);
}
void remove(String key) {
if (!state.any((d) => d.key == key)) return;
_persist([...state.where((d) => d.key != key)]);
}
String? textFor(String key) =>
state.where((d) => d.key == key).firstOrNull?.text;
void _persist(List<ComposeDraft> drafts) {
state = List.unmodifiable(drafts);
final prefs = ref.read(savedPrefsProvider);
prefs.setString(
_prefsKey,
jsonEncode([for (final d in drafts) d.toJson()]),
);
}
}
final composeDraftsProvider =
NotifierProvider<ComposeDraftsNotifier, List<ComposeDraft>>(
ComposeDraftsNotifier.new,
);