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 4b71859416
commit a109a84714
25 changed files with 597 additions and 33 deletions

View file

@ -1,11 +1,15 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../di/injector.dart' show switchSocialAccount;
import '../i18n/strings.g.dart';
import '../services/profile_cache.dart' show shortPubkey;
import '../services/social_account_store.dart';
import '../services/profile_store.dart';
import '../services/social_service.dart';
import '../services/social_settings.dart';
import 'qr_view.dart';
import 'restart_widget.dart';
import 'theme.dart';
/// Your own profile: the shareable identity (npub) plus a display name and short
@ -16,12 +20,14 @@ class ProfileScreen extends StatefulWidget {
required this.social,
required this.settings,
required this.profileStore,
required this.accounts,
super.key,
});
final SocialService social;
final SocialSettings settings;
final ProfileStore profileStore;
final SocialAccountStore accounts;
@override
State<ProfileScreen> createState() => _ProfileScreenState();
@ -33,6 +39,11 @@ class _ProfileScreenState extends State<ProfileScreen> {
final _g1 = TextEditingController();
bool _loading = true;
bool _saving = false;
bool _switching = false;
/// The identities of this root seed (account index + its npub), for the
/// switcher. Always includes the active one.
List<({int account, String npub})> _identities = const [];
@override
void initState() {
@ -44,7 +55,50 @@ class _ProfileScreenState extends State<ProfileScreen> {
_name.text = await widget.profileStore.name();
_about.text = await widget.profileStore.about();
_g1.text = await widget.profileStore.g1();
if (mounted) setState(() => _loading = false);
final max = await widget.accounts.maxCreated();
final ids = <({int account, String npub})>[];
for (var i = 0; i <= max; i++) {
ids.add((account: i, npub: await widget.social.npubForAccount(i) ?? ''));
}
if (mounted) {
setState(() {
_identities = ids;
_loading = false;
});
}
}
/// Switches to (or creates) an identity and rebuilds the app on the new one.
Future<void> _switchTo(int account, {bool confirm = true}) async {
if (account == widget.social.account || _switching) return;
final t = context.t;
if (confirm) {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(t.profile.switchTitle),
content: Text(t.profile.switchBody),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: Text(t.common.cancel)),
FilledButton(
onPressed: () => Navigator.pop(ctx, true),
child: Text(t.profile.switchAction)),
],
),
);
if (ok != true) return;
}
if (!mounted) return;
setState(() => _switching = true);
await switchSocialAccount(account);
if (mounted) RestartWidget.restart(context);
}
Future<void> _newIdentity() async {
final next = await widget.accounts.maxCreated() + 1;
await _switchTo(next, confirm: false); // creating one is already explicit
}
Future<void> _copyId() async {
@ -143,12 +197,95 @@ class _ProfileScreenState extends State<ProfileScreen> {
)
: Text(t.profile.save),
),
const SizedBox(height: 28),
const Divider(),
const SizedBox(height: 12),
_IdentitiesSection(
identities: _identities,
activeAccount: widget.social.account,
busy: _switching,
onSwitch: (a) => _switchTo(a),
onNew: _newIdentity,
),
],
),
);
}
}
/// The identity switcher: every pseudonymous identity of this root seed, with
/// the active one marked, plus "new identity". Switching keeps chats/contacts
/// separate per identity; all regenerate from the single backup.
class _IdentitiesSection extends StatelessWidget {
const _IdentitiesSection({
required this.identities,
required this.activeAccount,
required this.busy,
required this.onSwitch,
required this.onNew,
});
final List<({int account, String npub})> identities;
final int activeAccount;
final bool busy;
final ValueChanged<int> onSwitch;
final VoidCallback onNew;
@override
Widget build(BuildContext context) {
final t = context.t;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
t.profile.identities,
style: const TextStyle(
fontWeight: FontWeight.w600, color: seedOnSurface),
),
const SizedBox(height: 4),
Text(
t.profile.identitiesHelp,
style: const TextStyle(color: seedMuted, fontSize: 12),
),
const SizedBox(height: 8),
for (final id in identities)
ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(
id.account == activeAccount
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
color: id.account == activeAccount ? seedGreen : seedMuted,
),
title: Text(t.profile.identityLabel(n: id.account + 1)),
subtitle: id.npub.isEmpty
? null
: Text(shortPubkey(id.npub),
style: const TextStyle(
fontFamily: 'monospace', fontSize: 12)),
trailing: id.account == activeAccount
? Text(t.profile.current,
style: const TextStyle(color: seedGreen, fontSize: 12))
: null,
onTap: busy || id.account == activeAccount
? null
: () => onSwitch(id.account),
),
const SizedBox(height: 4),
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton.icon(
key: const Key('profile.newIdentity'),
onPressed: busy ? null : onNew,
icon: const Icon(Icons.add, size: 18),
label: Text(t.profile.newIdentity),
),
),
],
);
}
}
class _IdentityCard extends StatelessWidget {
const _IdentityCard({required this.npub, required this.onCopy});

View file

@ -0,0 +1,30 @@
import 'package:flutter/widgets.dart';
/// Rebuilds its whole subtree from scratch on demand used to apply a social
/// identity switch, which re-registers the social singletons in the locator and
/// needs the widget tree (router, screens, sessions) rebuilt to pick them up.
///
/// [builder] is re-invoked on each restart, so it should read its dependencies
/// fresh (e.g. from the service locator) rather than close over stale ones.
class RestartWidget extends StatefulWidget {
const RestartWidget({required this.builder, super.key});
final Widget Function() builder;
/// Tears down and rebuilds everything under the nearest [RestartWidget].
static void restart(BuildContext context) =>
context.findAncestorStateOfType<_RestartWidgetState>()?.restart();
@override
State<RestartWidget> createState() => _RestartWidgetState();
}
class _RestartWidgetState extends State<RestartWidget> {
Key _key = UniqueKey();
void restart() => setState(() => _key = UniqueKey());
@override
Widget build(BuildContext context) =>
KeyedSubtree(key: _key, child: widget.builder());
}