fix(mobile): bind notification replies to the account they were typed for (#9845)

A notification reply goes out as whatever account its community signs
with when the reply is sent. No sign-in path replaces a community's
account in place today: signing in again as another account adds a new
community, and hosted re-entry refuses a different key. But nothing tied
a reply to the account its notification was for, so a future in-place
credential replacement would let a reply typed for the earlier account
go out as the new one, or land in its drafts.

Each reply is now tied to the account its notification was for:

- The notification service extension records that account in the reply
context, and iOS carries it through the reply journal, so a reply
recovered on a later launch keeps it too.
- The app sends a reply, or keeps it as a draft, only while the
community still signs as that account (the key it signs with). It checks
again after connecting.
- Otherwise the reply ends as lost: iOS shows "Reply not sent" with the
text, and no draft is kept. This is the same path a reply takes when its
community has been removed ([ADR
0004](docs/adr/0004-notification-reply.md), updated here).
- A reply to a notification posted by an earlier build has no recorded
account, so it is checked only by its community, as before.

### Regressions

- A community whose notification snapshot has no account key offers no
reply action. Every signed-in community has one, since the snapshot
falls back to the key derived from its secret.
- No extra work on the send path beyond a key comparison.

### Validation

-
[notification_reply_test.dart](https://github.com/block/buzz/blob/notification-reply-account/mobile/test/features/channels/notification_reply_test.dart):
a live reply for another account and a recovered one for another
community end as lost with their text kept nowhere; a reply whose
community's signing key is replaced while the relay connects (same
community and stored key) is neither sent nor drafted; a reply from an
earlier build without an account is sent.
-
[BuzzNotificationReplyTests.swift](https://github.com/block/buzz/blob/notification-reply-account/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzNotificationReplyTests.swift):
the resolver records the notification's account, lowercased. An empty
account is rejected, and the account survives the journal round trip.
- No simulator run: the reply action needs a real push resolved by the
notification service extension, which the simulator can't receive. The
change is covered at both layers by the tests above, and the iOS app
builds.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
This commit is contained in:
Tom Brow
2026-11-20 20:23:59 -08:00
committed by GitHub
parent 52cbc61131
commit d1236080eb
7 changed files with 148 additions and 24 deletions

View File

@@ -20,14 +20,20 @@ public struct BuzzNotificationReplyContext: Codable, Equatable, Sendable {
/// Whether channel metadata showed a Solo chat, which takes no thread
/// replies; nil when it was unknown.
public let inSolo: Bool?
/// The account the notification was for, which the reply must be sent as,
/// guarding against a community's credentials being replaced in place. nil
/// for a notification an earlier build posted.
public let recipientPubkey: String?
public init(
senderPubkey: String, threadRootID: String? = nil, messageCreatedAt: Int, inSolo: Bool? = nil
senderPubkey: String, threadRootID: String? = nil, messageCreatedAt: Int, inSolo: Bool? = nil,
recipientPubkey: String? = nil
) {
self.senderPubkey = senderPubkey
self.threadRootID = threadRootID
self.messageCreatedAt = messageCreatedAt
self.inSolo = inSolo
self.recipientPubkey = recipientPubkey
}
/// Kinds the app can answer with an ordinary channel or DM message.
@@ -35,14 +41,15 @@ public struct BuzzNotificationReplyContext: Codable, Equatable, Sendable {
static let replyableKinds: Set<Int> = [9, 40002]
static func make(
for event: VerifiedNostrEvent, inSolo: Bool? = nil
for event: VerifiedNostrEvent, recipientPubkey: String, inSolo: Bool? = nil
) -> BuzzNotificationReplyContext? {
guard replyableKinds.contains(event.kind) else { return nil }
return BuzzNotificationReplyContext(
senderPubkey: event.pubkey.lowercased(),
threadRootID: nip10RootID(in: event.tags),
messageCreatedAt: event.createdAt,
inSolo: inSolo
inSolo: inSolo,
recipientPubkey: recipientPubkey.lowercased()
)
}
@@ -72,6 +79,7 @@ public struct BuzzNotificationReplyContext: Codable, Equatable, Sendable {
var value = ["sender_pubkey": senderPubkey, "created_at": String(messageCreatedAt)]
value["thread_root_id"] = threadRootID
value["in_solo"] = inSolo.map { $0 ? "true" : "false" }
value["recipient_pubkey"] = recipientPubkey
return value
}
@@ -80,13 +88,18 @@ public struct BuzzNotificationReplyContext: Codable, Equatable, Sendable {
from userInfo: [AnyHashable: Any]
) -> BuzzNotificationReplyContext? {
guard let raw = userInfo[userInfoKey] as? [String: Any],
Set(raw.keys).isSubset(of: ["sender_pubkey", "thread_root_id", "created_at", "in_solo"]),
Set(raw.keys).isSubset(of: [
"sender_pubkey", "thread_root_id", "created_at", "in_solo", "recipient_pubkey",
]),
let sender = raw["sender_pubkey"] as? String, !sender.isEmpty,
let createdAt = (raw["created_at"] as? String).flatMap(Int.init), createdAt > 0
else { return nil }
if let rawRoot = raw["thread_root_id"] {
guard let root = rawRoot as? String, !root.isEmpty else { return nil }
}
if let rawRecipient = raw["recipient_pubkey"] {
guard let recipient = rawRecipient as? String, !recipient.isEmpty else { return nil }
}
var inSolo: Bool?
if let rawSolo = raw["in_solo"] {
switch rawSolo as? String {
@@ -97,7 +110,8 @@ public struct BuzzNotificationReplyContext: Codable, Equatable, Sendable {
}
return BuzzNotificationReplyContext(
senderPubkey: sender, threadRootID: raw["thread_root_id"] as? String,
messageCreatedAt: createdAt, inSolo: inSolo)
messageCreatedAt: createdAt, inSolo: inSolo,
recipientPubkey: raw["recipient_pubkey"] as? String)
}
}
@@ -169,6 +183,7 @@ public struct BuzzNotificationReplyRequest: Equatable, Sendable {
arguments["messageCreatedAt"] = String(context.messageCreatedAt)
arguments["deadline"] = String(Int64(deadline.timeIntervalSince1970 * 1000))
arguments["inSolo"] = context.inSolo == true ? "true" : nil
arguments["recipientPubkey"] = context.recipientPubkey
return arguments
}
@@ -187,7 +202,8 @@ public struct BuzzNotificationReplyRequest: Equatable, Sendable {
threadRootID: arguments["threadRootId"]),
context: BuzzNotificationReplyContext(
senderPubkey: sender, threadRootID: arguments["replyRootId"],
messageCreatedAt: createdAt, inSolo: arguments["inSolo"] == "true" ? true : nil),
messageCreatedAt: createdAt, inSolo: arguments["inSolo"] == "true" ? true : nil,
recipientPubkey: arguments["recipientPubkey"]),
threadIdentifier: "",
deadline: arguments["deadline"].flatMap(Double.init).map {
Date(timeIntervalSince1970: $0 / 1000)

View File

@@ -557,7 +557,11 @@ public final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
conversationDisplayName: conversation?.displayName,
conversationRecipientCount: conversation?.recipientCount,
replyContext: channelID == nil
? nil : BuzzNotificationReplyContext.make(for: event, inSolo: channel?.isSolo),
? nil
: community.pubkey.flatMap {
BuzzNotificationReplyContext.make(
for: event, recipientPubkey: $0, inSolo: channel?.isSolo)
},
notificationScope: BuzzNotificationCacheScope(community: community)
)
}

View File

@@ -6,6 +6,7 @@ import Testing
private let root = String(repeating: "a", count: 64)
private let parent = String(repeating: "b", count: 64)
private let sender = String(repeating: "C", count: 64)
private let recipient = String(repeating: "F", count: 64)
private func event(kind: Int, tags: [[String]] = []) -> VerifiedNostrEvent {
VerifiedNostrEvent(
@@ -36,8 +37,10 @@ private func event(kind: Int, tags: [[String]] = []) -> VerifiedNostrEvent {
func `Reply context carries the sender and NIP-10 thread root`(
tags: [[String]], expectedRoot: String?
) throws {
let context = try #require(BuzzNotificationReplyContext.make(for: event(kind: 9, tags: tags)))
let context = try #require(
BuzzNotificationReplyContext.make(for: event(kind: 9, tags: tags), recipientPubkey: recipient))
#expect(context.senderPubkey == sender.lowercased())
#expect(context.recipientPubkey == recipient.lowercased())
#expect(context.threadRootID == expectedRoot)
#expect(context.messageCreatedAt == 1_000)
#expect(
@@ -47,7 +50,8 @@ func `Reply context carries the sender and NIP-10 thread root`(
@Test(arguments: [45001, 45003, 7])
func `Forum posts and other kinds offer no reply`(kind: Int) {
#expect(BuzzNotificationReplyContext.make(for: event(kind: kind)) == nil)
#expect(
BuzzNotificationReplyContext.make(for: event(kind: kind), recipientPubkey: recipient) == nil)
}
@Test func `Reply context rejects unexpected or malformed fields`() {
@@ -65,16 +69,21 @@ func `Forum posts and other kinds offer no reply`(kind: Int) {
#expect(
BuzzNotificationReplyContext.decodeIfPresent(
from: [key: ["sender_pubkey": "pk", "created_at": "1", "thread_root_id": ""]]) == nil)
#expect(
BuzzNotificationReplyContext.decodeIfPresent(
from: [key: ["sender_pubkey": "pk", "created_at": "1", "recipient_pubkey": ""]]) == nil)
}
@Test func `Resolution offers reply only for a channel message`() {
let community = PushLeaseCommunity(
id: "community", name: "Community", relayUrl: "https://relay.example.org",
pubkey: String(repeating: "f", count: 64), policies: [])
pubkey: recipient, policies: [])
let inChannel = BuzzPushNotificationResolver.makeResolution(
event: event(kind: 9, tags: [["h", "channel"]]), community: community, profile: nil,
channel: nil)
#expect(inChannel?.replyContext?.senderPubkey == sender.lowercased())
// The reply is bound to the account the notification was for.
#expect(inChannel?.replyContext?.recipientPubkey == recipient.lowercased())
let noChannel = BuzzPushNotificationResolver.makeResolution(
event: event(kind: 9), community: community, profile: nil, channel: nil)
#expect(noChannel != nil)
@@ -200,7 +209,8 @@ func `Forum posts and other kinds offer no reply`(kind: Int) {
target: BuzzPushNavigationTarget(
eventID: parent, communityID: "c", channelID: "ch", threadRootID: "root"),
context: BuzzNotificationReplyContext(
senderPubkey: "pk", threadRootID: "root", messageCreatedAt: 7, inSolo: true),
senderPubkey: "pk", threadRootID: "root", messageCreatedAt: 7, inSolo: true,
recipientPubkey: "me"),
threadIdentifier: "t",
deadline: Date(timeIntervalSince1970: 1_700_000_000.5))
let rebuilt = BuzzNotificationReplyRequest(

View File

@@ -87,8 +87,9 @@ enum NotificationReplyOutcome {
/// Never published, or refused by the relay; its text is kept as a draft.
notSent,
/// Like [notSent], but its community is gone, so no draft is kept. Its
/// "Reply not sent" notification is the only place its text stays.
/// Like [notSent], but its community is gone, or is now signed in as
/// another account, so no draft is kept. Its "Reply not sent" notification
/// is the only place its text stays.
lost,
/// Published, but no answer came from the relay, so it may have gone out.
@@ -221,6 +222,9 @@ Future<void> _send(
active?.id != link.communityId) {
throw StateError('Reply is not for the selected community');
}
if (!_isReplyAccount(reply, active!)) {
throw StateError('Reply community is signed in as another account');
}
// Taken before any wait: its delivery check then refuses to publish if the
// selected community changes.
final send = ref.read(sendMessageProvider);
@@ -235,7 +239,8 @@ Future<void> _send(
.read(relaySessionProvider.notifier)
.connectForBackgroundWork(timeout: connectTimeout);
if (!connected) throw StateError('Relay not reachable');
if (ref.read(activeCommunityProvider).value?.id != link.communityId) {
final current = ref.read(activeCommunityProvider).value;
if (current?.id != link.communityId || !_isReplyAccount(reply, current!)) {
throw StateError('Selected community changed');
}
// Only a current member can be mentioned; a sender who has left still gets
@@ -262,9 +267,18 @@ Future<void> _send(
String? _replyHead(BuzzNotificationReply reply, Channel channel) =>
channel.isSolo ? null : reply.replyRootId ?? reply.link.messageId;
/// Whether [community] is still signed in as the account [reply] was typed
/// for: the key it signs with. A notification from an earlier build doesn't
/// say, so its reply is checked only by its community, as before.
bool _isReplyAccount(BuzzNotificationReply reply, Community community) {
final recipient = reply.recipientPubkey;
final account = pubkeyFromNsec(community.nsec?.trim()) ?? community.pubkey;
return recipient == null || account?.toLowerCase() == recipient.toLowerCase();
}
/// The result for a reply that wasn't published: [NotificationReplyOutcome.notSent]
/// with its draft's thread, or [NotificationReplyOutcome.lost] when its
/// community is gone.
/// community is gone or signed in as another account.
Future<NotificationReplyResult> _notSent(
Ref ref,
BuzzNotificationReply reply,
@@ -282,7 +296,8 @@ Future<NotificationReplyResult> _notSent(
/// reply's own community, and returns the thread it's in once it's saved, or
/// throws: the reply then stays with iOS until a later launch saves it, as it
/// does while this build hides that community. When that community is gone,
/// nothing is kept and this returns null. It
/// or is signed in as another account, nothing is kept and this returns
/// null. It
/// goes where the reply would have gone: the subthread under the notified
/// message, or a Solo chat itself. Whether it's a Solo chat comes from the
/// loaded channel, or else from the notification.
@@ -316,6 +331,8 @@ Future<({String? threadRootId})?> _keepDraft(
// iOS would retry it on every launch.
return null;
}
// Another account's drafts are no place for it.
if (!_isReplyAccount(reply, community)) return null;
await ref
.read(composeDraftsProvider.notifier)
.append(

View File

@@ -65,6 +65,7 @@ class BuzzNotificationReply {
required this.messageCreatedAt,
required this.deadline,
this.replyRootId,
this.recipientPubkey,
this.inSolo = false,
this.recovered = false,
this.mayHavePublished = false,
@@ -82,6 +83,11 @@ class BuzzNotificationReply {
/// NIP-10 thread root of the notified message; null when it is top-level.
final String? replyRootId;
/// The account the notification was for, which the reply must go out as,
/// guarding against a community's credentials being replaced in place. Null
/// for a notification an earlier build posted.
final String? recipientPubkey;
/// When the notified message was created, in Unix seconds.
final int messageCreatedAt;
@@ -114,6 +120,7 @@ class BuzzNotificationReply {
final text = arguments['text'];
final sender = arguments['senderPubkey'];
final root = arguments['replyRootId'];
final recipient = arguments['recipientPubkey'];
final createdAt = switch (arguments['messageCreatedAt']) {
final String value => int.tryParse(value),
_ => null,
@@ -132,7 +139,8 @@ class BuzzNotificationReply {
createdAt == null ||
createdAt <= 0 ||
deadline == null ||
(root != null && (root is! String || root.isEmpty))) {
(root != null && (root is! String || root.isEmpty)) ||
(recipient != null && (recipient is! String || recipient.isEmpty))) {
return null;
}
return BuzzNotificationReply(
@@ -143,6 +151,7 @@ class BuzzNotificationReply {
messageCreatedAt: createdAt,
deadline: DateTime.fromMillisecondsSinceEpoch(deadline),
replyRootId: root as String?,
recipientPubkey: recipient as String?,
inSolo: arguments['inSolo'] == 'true',
recovered: arguments['recovered'] == 'true',
mayHavePublished: arguments['publishing'] == 'true',

View File

@@ -30,6 +30,7 @@ final _community = Community(
id: 'community',
name: 'Example',
relayUrl: 'https://relay.example.org',
pubkey: 'me',
addedAt: DateTime.utc(2026),
);
@@ -37,6 +38,7 @@ final _elsewhere = Community(
id: 'elsewhere',
name: 'Elsewhere',
relayUrl: 'https://other.example.org',
pubkey: 'me elsewhere',
addedAt: DateTime.utc(2026),
);
@@ -67,6 +69,7 @@ Map<String, String> _reply(
String? replyRootId,
int createdAt = 1000,
bool inSolo = false,
String? recipientPubkey,
}) => {
'id': id,
'text': 'reply $id',
@@ -75,6 +78,8 @@ Map<String, String> _reply(
'channelId': channelId,
'threadRootId': ?threadRootId,
'senderPubkey': _sender,
'recipientPubkey':
recipientPubkey ?? (communityId == 'elsewhere' ? 'me elsewhere' : 'me'),
'replyRootId': ?replyRootId,
'messageCreatedAt': '$createdAt',
if (inSolo) 'inSolo': 'true',
@@ -143,6 +148,23 @@ void main() {
// Once iOS has ended a reply as not sent, it never goes out.
_reply('18'),
// A community signed in again as another account on the same relay
// keeps its ID, but the reply was typed for the earlier account: it
// is never sent or kept as the new one's draft, so iOS shows its text
// in a notification, as for a gone community.
_reply('19', recipientPubkey: 'earlier account'),
{
..._reply(
'20',
communityId: 'elsewhere',
recipientPubkey: 'earlier account',
),
'recovered': 'true',
},
// A notification from an earlier build doesn't say whose it was, so
// only its community is checked.
{..._reply('21')}..remove('recipientPubkey'),
];
// What iOS hears, in order, alongside each message sent.
final log = <String>[];
@@ -187,11 +209,14 @@ void main() {
final sender = _RecordingSender(onSend: (text) => log.add('sent $text'));
final session = _Session();
var active = _community;
var communities = [_community, _elsewhere];
final container = ProviderContainer(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
authProvider.overrideWith(_Auth.new),
communityListProvider.overrideWith(_Communities.new),
communityListProvider.overrideWith(
() => _Communities(() => communities),
),
communityStorageProvider.overrideWithValue(_Storage()),
activeCommunityProvider.overrideWith((ref) async => active),
channelsProvider.overrideWith(
@@ -235,6 +260,9 @@ void main() {
'15': 'unknown',
'16': 'no draft',
'18': 'draft in $_message',
'19': 'no draft',
'20': 'no draft',
'21': 'sent',
});
// iOS knows a reply may go out before anything is published.
expect(log, [
@@ -243,6 +271,8 @@ void main() {
'sent reply $id',
],
'may publish 18',
'may publish 21',
'sent reply 21',
]);
expect(sender.calls, [
('general', 'reply 1', _message, _message, _sender),
@@ -250,6 +280,7 @@ void main() {
('solo', 'reply 3', null, null, _sender),
('left', 'reply 10', _message, _message, ''),
('lost', 'reply 11', _message, _message, _sender),
('general', 'reply 21', _message, _message, _sender),
]);
// Read only up to each notified message, so newer ones stay unread.
expect(container.read(readStateProvider).contexts, {
@@ -267,10 +298,13 @@ void main() {
elsewhere,
contains('"key":"own","channel_id":"own","text":"reply 13"'),
);
// The gone community's reply is kept nowhere.
expect([
for (final key in prefs.getKeys()) '${prefs.get(key)}',
], everyElement(isNot(contains('reply 16'))));
// The gone community's reply is kept nowhere, nor is another
// account's.
for (final id in ['16', '19', '20']) {
expect([
for (final key in prefs.getKeys()) '${prefs.get(key)}',
], everyElement(isNot(contains('reply $id'))));
}
expect(
drafts.textFor(composeDraftKey('broken', threadHeadId: _message)),
'reply 5',
@@ -331,6 +365,36 @@ void main() {
contains('"text":"reply 8\\n\\nreply 9"'),
);
expect(prefs.getString(_elsewhereDrafts), isNot(contains('reply 9')));
// Credentials replaced in place while the relay connects: the same
// community and stored key, but it now signs as another account. The
// reply is never sent or kept as that account's draft.
final keys = nostr.Keys.generate();
final signedIn = _community.copyWith(
pubkey: keys.public,
nsec: keys.nsec,
);
final replaced = signedIn.copyWith(nsec: nostr.Keys.generate().nsec);
active = signedIn;
communities = [signedIn, _elsewhere];
container
..invalidate(activeCommunityProvider)
..invalidate(communityListProvider);
await container.read(activeCommunityProvider.future);
session.onConnect = () async {
active = replaced;
communities = [replaced, _elsewhere];
container
..invalidate(activeCommunityProvider)
..invalidate(communityListProvider);
await container.read(activeCommunityProvider.future);
};
await signalReply(_reply('22', recipientPubkey: keys.public));
expect(outcomes['22'], 'no draft');
expect(sender.calls.last.$2, 'reply 7');
expect([
for (final key in prefs.getKeys()) '${prefs.get(key)}',
], everyElement(isNot(contains('reply 22'))));
},
);
@@ -485,8 +549,12 @@ class _Storage extends CommunityStorage {
}
class _Communities extends CommunityListNotifier {
_Communities([this.communities]);
final List<Community> Function()? communities;
@override
Future<List<Community>> build() async => [_community, _elsewhere];
Future<List<Community>> build() async =>
communities?.call() ?? [_community, _elsewhere];
}
class _Session extends RelaySessionNotifier {