tane/apps/app_seeds/lib/services/social_service.dart
vjrj 993f7b37ab feat(identity): switch social identity, all from the one backup
Adds pseudonymous, switchable social identities derived from the SAME root
seed via an account index (NostrKeyDerivation.deriveFromSeed(seed, account)).
HKDF is one-way so accounts are unlinkable to the Ğ1 key; account 0 is the
original identity, byte-for-byte unchanged (no rotation for current users),
and every account regenerates from the single seed — so switching adds
nothing to back up.

- SocialAccountStore: keystore-backed active account + max created.
- Per-identity stores (chats, profile, name cache) namespaced by account
  scope (account 0 = legacy keys, no migration) so identities never mix.
- switchSocialAccount() re-derives the identity, re-scopes the stores and
  restarts the inbox listener; RestartWidget rebuilds the tree to pick up
  the new social singletons. DB/inventory untouched.
- Profile 'Your identities' switcher: list, create, switch (with a note
  that messages/contacts are kept separate per identity). i18n en/es/pt/ast.

Tests: account-indexed derivation (legacy 0 unchanged, accounts distinct
yet deterministic, negatives rejected); SocialAccountStore; per-identity
store scope isolation. Resolves the flagged 'change identity' decision
(open-decisions §B).

Known: switching resets navigation to home (full tree rebuild).
2026-07-10 20:22:24 +02:00

109 lines
3.8 KiB
Dart

import 'dart:typed_data';
import 'package:commons_core/commons_core.dart';
/// The app-side entry point to the (Block 2) social layer.
///
/// Holds the user's Nostr identity — deterministically derived from the same
/// root seed the recovery QR backs up (so it needs no extra backup) — and opens
/// social sessions on demand. Local-first: constructing this is cheap and
/// offline; nothing connects to a relay until [openSession] is called, so the
/// app runs fully without network and the social layer only enriches.
class SocialService {
SocialService({
required this.identity,
this.account = 0,
this.rootSeedHex = '',
List<String> relays = const [],
}) : relays = List.unmodifiable(relays);
/// The derived Nostr identity (secp256k1). Same key across reinstalls that
/// restore the same seed (for a given [account]).
final NostrIdentity identity;
/// Which pseudonymous identity of the root seed this is (0 = the original).
/// Switching account changes the social identity while the backup stays the
/// single root seed. See [NostrKeyDerivation.deriveFromSeed].
final int account;
/// The root-seed hex, kept so the switcher can preview OTHER accounts'
/// identities without re-reading the keystore. Empty when unknown (tests).
final String rootSeedHex;
/// Community relay URLs (may be empty — discovery/publishing degrade to
/// nothing when offline or unconfigured).
final List<String> relays;
/// Shareable public identity (`npub…`) and its hex form.
String get npub => identity.npub;
String get publicKeyHex => identity.publicKeyHex;
/// Derives the identity from the stored root-seed hex (32-byte, 64 chars) for
/// the given [account] (0 = the original identity).
static Future<SocialService> fromRootSeedHex(
String rootSeedHex, {
int account = 0,
List<String> relays = const [],
}) async {
final identity = await NostrKeyDerivation.deriveFromSeed(
_hexToBytes(rootSeedHex),
account: account,
);
return SocialService(
identity: identity,
account: account,
rootSeedHex: rootSeedHex,
relays: relays,
);
}
/// The `npub` for another [account] of the same root seed, so the switcher can
/// show identities before committing to one. Returns null if the seed is
/// unknown (e.g. in tests constructed without it).
Future<String?> npubForAccount(int account) async {
if (rootSeedHex.isEmpty) return null;
final id = await NostrKeyDerivation.deriveFromSeed(
_hexToBytes(rootSeedHex),
account: account,
);
return id.npub;
}
/// Opens a session against [relayUrls]: one fault-tolerant pool carrying all
/// three transports (offers, messaging, trust). Relays that are down are
/// skipped; throws only when none are reachable. Caller closes it.
Future<SocialSession> openSession(List<String> relayUrls) async {
final pool = await RelayPool.connect(relayUrls, identity: identity);
return SocialSession(pool);
}
}
/// One relay channel with the three transports on top — the
/// "one channel, three interfaces" shape, at the app layer.
class SocialSession {
SocialSession(this._channel)
: offers = NostrOfferTransport(_channel),
messages = NostrMessageTransport(_channel),
trust = NostrTrustTransport(_channel),
profile = NostrProfileTransport(_channel);
final NostrChannel _channel;
final OfferTransport offers;
final MessageTransport messages;
final TrustTransport trust;
final ProfileTransport profile;
Future<void> close() => _channel.close();
}
Uint8List _hexToBytes(String hex) {
if (hex.length.isOdd) {
throw ArgumentError('hex string must have an even length');
}
final out = Uint8List(hex.length ~/ 2);
for (var i = 0; i < out.length; i++) {
out[i] = int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16);
}
return out;
}