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).
This commit is contained in:
vjrj 2026-07-10 20:20:04 +02:00
parent d36fd05741
commit 993f7b37ab
25 changed files with 597 additions and 33 deletions

View file

@ -23,9 +23,13 @@ class ChatSummary {
}
class MessageStore {
MessageStore(this._store);
/// [accountScope] namespaces the keys per social identity (empty = the
/// original identity's legacy keys). See [socialAccountScope].
MessageStore(this._store, {String accountScope = ''})
: _base = accountScope.isEmpty ? 'tane.social.' : 'tane.social.$accountScope.';
final SecretStore _store;
final String _base;
/// Serializes [append]'s read-modify-write. Several sources now write the same
/// conversation concurrently (the app-wide inbox listener and an open chat's
@ -33,17 +37,15 @@ class MessageStore {
/// read the same history and the second write would clobber the first.
Future<void> _writeTail = Future.value();
static const _prefix = 'tane.social.chat.';
/// Index of peers we have a conversation with (the keystore is key/value with
/// no key enumeration, so we track the list ourselves).
static const _indexKey = 'tane.social.chats';
String get _indexKey => '${_base}chats';
/// Keep only the most recent [_cap] messages per conversation, to bound the
/// keystore entry size.
static const _cap = 200;
String _key(String peerPubkey) => '$_prefix$peerPubkey';
String _key(String peerPubkey) => '${_base}chat.$peerPubkey';
/// Messages exchanged with [peerPubkey], oldest first.
Future<List<PrivateMessage>> history(String peerPubkey) async {

View file

@ -4,10 +4,15 @@ import '../security/secret_store.dart';
/// `name`), so the inbox and chat show a human name instead of a raw key
/// even offline. Keystore-backed (no plaintext at rest).
class ProfileCache {
ProfileCache(this._store);
/// [accountScope] namespaces the keys per social identity (empty = the
/// original identity's legacy keys). See [socialAccountScope].
ProfileCache(this._store, {String accountScope = ''})
: _prefix = accountScope.isEmpty
? 'tane.social.name.'
: 'tane.social.$accountScope.name.';
final SecretStore _store;
static const _prefix = 'tane.social.name.';
final String _prefix;
/// The cached name for [pubkeyHex], or null if none is known.
Future<String?> name(String pubkeyHex) async {

View file

@ -4,12 +4,19 @@ import '../security/secret_store.dart';
/// no plaintext at rest). The network copy is a published NIP-01 kind:0 event;
/// this local copy prefills the editor and works offline.
class ProfileStore {
ProfileStore(this._store);
/// [accountScope] namespaces the keys per social identity (empty = the
/// original identity's legacy keys). See [socialAccountScope].
ProfileStore(this._store, {String accountScope = ''})
: _base = accountScope.isEmpty
? 'tane.social.profile.'
: 'tane.social.$accountScope.profile.';
final SecretStore _store;
static const _nameKey = 'tane.social.profile.name';
static const _aboutKey = 'tane.social.profile.about';
static const _g1Key = 'tane.social.profile.g1';
final String _base;
String get _nameKey => '${_base}name';
String get _aboutKey => '${_base}about';
String get _g1Key => '${_base}g1';
Future<String> name() async => (await _store.read(_nameKey)) ?? '';
Future<String> about() async => (await _store.read(_aboutKey)) ?? '';

View file

@ -0,0 +1,60 @@
import '../security/secret_store.dart';
/// The per-identity key scope for [account]: empty for the original identity
/// (account 0, so its data keeps the legacy un-namespaced keys), otherwise a
/// distinct namespace. Used by the per-identity stores (chats, profile, name
/// cache) so switching identity never mixes one identity's data into another.
String socialAccountScope(int account) => account == 0 ? '' : 'acct$account';
/// Remembers which social identity ("account") of the root seed is active, and
/// how many the user has created, so identities can be switched and listed.
///
/// Each account is a pseudonymous Nostr identity deterministically derived from
/// the SAME root seed (see `NostrKeyDerivation.deriveFromSeed`), so switching
/// never adds anything to back up the one seed still regenerates them all.
/// Keystore-backed: no plaintext at rest.
class SocialAccountStore {
SocialAccountStore(this._store);
final SecretStore _store;
static const _activeKey = 'tane.social.account.active';
static const _maxKey = 'tane.social.account.max';
/// The active account index (0 = the original identity).
Future<int> active() async => _readInt(_activeKey);
/// The highest account index ever created (so the list is 0..max and a new
/// identity takes max + 1). At least the active one always exists.
Future<int> maxCreated() async {
final max = await _readInt(_maxKey);
final activeIdx = await active();
return max > activeIdx ? max : activeIdx;
}
/// Switches the active identity to [account] (must already be within
/// 0..maxCreated, or be maxCreated + 1 for a freshly created one).
Future<void> setActive(int account) async {
if (account < 0) {
throw ArgumentError.value(account, 'account', 'must be >= 0');
}
await _store.write(_activeKey, '$account');
if (account > await _readInt(_maxKey)) {
await _store.write(_maxKey, '$account');
}
}
/// Creates a brand-new identity (the next index) and makes it active. Returns
/// the new account index.
Future<int> createNew() async {
final next = await maxCreated() + 1;
await setActive(next);
return next;
}
Future<int> _readInt(String key) async {
final raw = await _store.read(key);
if (raw == null || raw.isEmpty) return 0;
return int.tryParse(raw) ?? 0;
}
}

View file

@ -10,13 +10,26 @@ import 'package:commons_core/commons_core.dart';
/// 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, List<String> relays = const []})
: relays = List.unmodifiable(relays);
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.
/// 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;
@ -25,15 +38,35 @@ class SocialService {
String get npub => identity.npub;
String get publicKeyHex => identity.publicKeyHex;
/// Derives the identity from the stored root-seed hex (32-byte, 64 chars).
/// 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, relays: relays);
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