Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
e584a3c
refactor: implement real-time dispute chat with Nostr events and loca…
AndreaDiazCorreia Oct 1, 2025
c5d4303
feat: implement secure dispute chat messaging using NIP-59 gift wrap …
AndreaDiazCorreia Oct 5, 2025
1ebe0b9
refactor: implement NIP-59 compliant message encryption for Mostro di…
AndreaDiazCorreia Oct 9, 2025
258e52b
fix: only sanitize id/sig fields in NostrEvent JSON to preserve valid…
AndreaDiazCorreia Oct 9, 2025
01a7c71
fix: handle null orderId in dispute chat and convert Nostr timestamps…
AndreaDiazCorreia Oct 12, 2025
de382b7
refactor: extract session role conversion logic into dedicated method
AndreaDiazCorreia Oct 13, 2025
137efa8
feat: add dispute read status tracking with unread indicators
AndreaDiazCorreia Oct 13, 2025
a175df6
refactor: simplify unread indicator logic by removing manual read sta…
AndreaDiazCorreia Oct 13, 2025
7febdec
Merge branch 'main' into andrea/dispute-chat
AndreaDiazCorreia Oct 15, 2025
5029a4d
refactor: convert DisputeMessagesList to ConsumerStatefulWidget for s…
AndreaDiazCorreia Oct 15, 2025
a203bc6
feat: add loading and error states to dispute messages list
AndreaDiazCorreia Oct 15, 2025
b85721c
feat: add security validation for dispute chat message senders
AndreaDiazCorreia Oct 21, 2025
dcecc3c
feat: add message pending state and error handling to dispute chat
AndreaDiazCorreia Oct 21, 2025
3134198
feat: add error handling and rollback for failed message publishing i…
AndreaDiazCorreia Oct 21, 2025
59fe862
Merge branch 'main' into andrea/dispute-chat
grunch Oct 21, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions lib/data/models/dispute_chat.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ class DisputeChat {
final DateTime timestamp;
final bool isFromUser;
final String? adminPubkey;
final bool isPending;
final String? error;

DisputeChat({
required this.id,
required this.message,
required this.timestamp,
required this.isFromUser,
this.adminPubkey,
this.isPending = false,
this.error,
});

factory DisputeChat.fromJson(Map<String, dynamic> json) {
Expand All @@ -21,6 +25,8 @@ class DisputeChat {
timestamp: _parseTimestamp(json['timestamp']),
isFromUser: json['isFromUser'] ?? false,
adminPubkey: json['adminPubkey'],
isPending: json['isPending'] ?? false,
error: json['error'],
);
}

Expand All @@ -31,9 +37,32 @@ class DisputeChat {
'timestamp': timestamp.toIso8601String(),
'isFromUser': isFromUser,
'adminPubkey': adminPubkey,
'isPending': isPending,
'error': error,
};
}

/// Create a copy with updated fields
DisputeChat copyWith({
String? id,
String? message,
DateTime? timestamp,
bool? isFromUser,
String? adminPubkey,
bool? isPending,
String? error,
}) {
return DisputeChat(
id: id ?? this.id,
message: message ?? this.message,
timestamp: timestamp ?? this.timestamp,
isFromUser: isFromUser ?? this.isFromUser,
adminPubkey: adminPubkey ?? this.adminPubkey,
isPending: isPending ?? this.isPending,
error: error ?? this.error,
);
}

static DateTime _parseTimestamp(dynamic v) {
if (v is int) {
// Treat values < 1e12 as seconds, convert to milliseconds
Expand Down
189 changes: 132 additions & 57 deletions lib/data/models/nostr_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,101 +84,176 @@ extension NostrEventExtensions on NostrEvent {
);
}

/// Unwraps a Gift Wrap (kind 1059) following NIP-59 for Mostro dispute chat
///
/// Flow (as per mostro-cli):
/// 1. Decrypt Gift Wrap (1059) with ephemeral_pubkey + receiver_private_key → SEAL (13)
/// 2. Decrypt SEAL (13) with sender_pubkey + receiver_private_key → RUMOR (1, unsigned)
/// 3. Return RUMOR with Mostro message content
/// Helper to sanitize JSON for NostrEvent.deserialized
/// Only sets empty strings for id and sig (which can be null in unsigned events)
/// Preserves other fields as-is to avoid breaking validation
String _sanitizeEventJson(String eventJson) {
try {
final Map<String, dynamic> eventMap = jsonDecode(eventJson);

// Only sanitize id and sig - these can be null in RUMORs (unsigned events)
// Don't touch pubkey or content as they have validation that requires real values
if (eventMap['id'] == null) {
eventMap['id'] = '';
}
if (eventMap['sig'] == null) {
eventMap['sig'] = '';
}

return jsonEncode(eventMap);
} catch (e) {
// If parsing fails, return original
return eventJson;
}
}

Future<NostrEvent> mostroUnWrap(NostrKeyPairs receiver) async {
if (kind != 1059) {
throw ArgumentError('Expected kind 1059, got: $kind');
throw ArgumentError('Expected kind 1059 (Gift Wrap), got: $kind');
}

if (content == null || content!.isEmpty) {
throw ArgumentError('Event content is empty');
throw ArgumentError('Gift Wrap content is empty');
}

try {
final decryptedContent = await NostrUtils.decryptNIP44(
content!,
receiver.private,
pubkey,
);
// STEP 1: Decrypt Gift Wrap with ephemeral key
// The Gift Wrap pubkey is the ephemeral public key
final ephemeralPubkey = pubkey; // From the Gift Wrap event

try {
final decryptedSeal = await NostrUtils.decryptNIP44(
content!,
receiver.private,
ephemeralPubkey,
);

final innerEvent = NostrEvent.deserialized(
'["EVENT", "", $decryptedContent]',
);
final sanitizedSeal = _sanitizeEventJson(decryptedSeal);
final sealEvent = NostrEvent.deserialized(
'["EVENT", "", $sanitizedSeal]',
);

// STEP 2: Verify it's a SEAL (kind 13)
if (sealEvent.kind != 13) {
throw Exception('Expected SEAL (kind 13), got: ${sealEvent.kind}');
}

if (innerEvent.kind == 13) {
try {
final messageContent = await NostrUtils.decryptNIP44(
innerEvent.content!,
receiver.private,
innerEvent.pubkey,
);

final messageEvent = NostrEvent.deserialized(
'["EVENT", "", $messageContent]',
);

if (messageEvent.kind != 14) {
throw Exception(
'Not a NIP-17 direct message: ${messageEvent.toString()}');
}

return messageEvent;
} catch (e) {
return innerEvent;
if (sealEvent.content == null || sealEvent.content!.isEmpty) {
throw Exception('SEAL content is empty');
}
} else if (innerEvent.kind == 1) {
return innerEvent;
} else {
return innerEvent;

// STEP 3: Decrypt SEAL with sender's pubkey (from SEAL)
// The SEAL pubkey identifies the actual sender (admin or user)
final senderPubkey = sealEvent.pubkey;

final decryptedRumor = await NostrUtils.decryptNIP44(
sealEvent.content!,
receiver.private,
senderPubkey,
);

final sanitizedRumor = _sanitizeEventJson(decryptedRumor);
final rumorEvent = NostrEvent.deserialized(
'["EVENT", "", $sanitizedRumor]',
);

// STEP 4: Verify it's a RUMOR (kind 1, unsigned)
if (rumorEvent.kind != 1) {
throw Exception('Expected RUMOR (kind 1), got: ${rumorEvent.kind}');
}

return rumorEvent;
} catch (e) {
// Add more context about which step failed
if (e.toString().contains('type cast')) {
throw Exception('Type cast error during unwrap - likely null value in event structure: $e');
}
rethrow;
}
} catch (e) {
throw Exception('Failed to unwrap Mostro chat message: $e');
}
}

Future<NostrEvent> mostroWrap(NostrKeyPairs sharedKey) async {
/// Wraps a RUMOR (kind 1) into a Gift Wrap (kind 1059) following NIP-59
///
/// Flow (as per mostro-cli):
/// 1. Create RUMOR (kind 1, unsigned) with Mostro message content
/// 2. Encrypt RUMOR with sender_private_key + receiver_pubkey → SEAL (13)
/// 3. Encrypt SEAL with ephemeral_key + receiver_pubkey → Gift Wrap (1059)
///
/// Parameters:
/// - senderKeys: The sender's key pair (trade keys)
/// - receiverPubkey: The receiver's public key (admin pubkey for disputes)
Future<NostrEvent> mostroWrap(NostrKeyPairs senderKeys, String receiverPubkey) async {
if (kind != 1) {
throw ArgumentError('Expected kind 1, got: $kind');
throw ArgumentError('Expected kind 1 (RUMOR), got: $kind');
}

if (content == null || content!.isEmpty) {
throw ArgumentError('Event content is empty');
throw ArgumentError('RUMOR content is empty');
}

try {
final innerEvent = NostrEvent(
id: id,
kind: kind,
content: content,
pubkey: pubkey,
sig: sig,
createdAt: createdAt,
tags: [
["p", sharedKey.public],
...(tags?.where((tag) => tag.isNotEmpty && tag[0] != 'p') ?? []),
],
// STEP 1: Prepare the RUMOR (already a kind 1 event, unsigned)
// The rumor should NOT have an 'id' or 'sig' field
final rumorMap = {
'kind': 1,
'content': content,
'pubkey': senderKeys.public,
'created_at': ((createdAt ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000),
'tags': tags ?? [],
};

final rumorJson = jsonEncode(rumorMap);

// STEP 2: Create SEAL (kind 13)
// Encrypt the rumor with sender's private key + receiver's public key
final encryptedRumor = await NostrUtils.encryptNIP44(
rumorJson,
senderKeys.private,
receiverPubkey,
);

final ephemeralKeyPair = NostrUtils.generateKeyPair();
final seal = NostrEvent.fromPartialData(
kind: 13,
content: encryptedRumor,
keyPairs: senderKeys,
tags: [], // SEAL always has empty tags
createdAt: DateTime.now(),
);

final sealJson = jsonEncode(seal.toMap());

final innerEventJson = jsonEncode(innerEvent.toMap());
// STEP 3: Create Gift Wrap (kind 1059)
// Generate ephemeral key pair (single-use)
final ephemeralKeyPair = NostrUtils.generateKeyPair();

final encryptedContent = await NostrUtils.encryptNIP44(
innerEventJson,
// Encrypt the seal with ephemeral key + receiver's public key
final encryptedSeal = await NostrUtils.encryptNIP44(
sealJson,
ephemeralKeyPair.private,
sharedKey.public,
receiverPubkey,
);

final wrapperEvent = NostrEvent.fromPartialData(
// Create Gift Wrap with randomized timestamp (±2 days)
final giftWrap = NostrEvent.fromPartialData(
kind: 1059,
content: encryptedContent,
content: encryptedSeal,
keyPairs: ephemeralKeyPair,
tags: [
["p", sharedKey.public],
["p", receiverPubkey], // Identifies the receiver
],
createdAt: _randomizedTimestamp(),
);

return wrapperEvent;
return giftWrap;
} catch (e) {
throw Exception('Failed to wrap Mostro chat message: $e');
}
Expand Down
3 changes: 3 additions & 0 deletions lib/data/models/payload.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:mostro_mobile/data/models/payment_failed.dart';
import 'package:mostro_mobile/data/models/payment_request.dart';
import 'package:mostro_mobile/data/models/peer.dart';
import 'package:mostro_mobile/data/models/rating_user.dart';
import 'package:mostro_mobile/data/models/text_message.dart';

abstract class Payload {
String get type;
Expand All @@ -28,6 +29,8 @@ abstract class Payload {
return PaymentFailed.fromJson(json['payment_failed']);
} else if (json.containsKey('next_trade')) {
return NextTrade.fromJson(json['next_trade']);
} else if (json.containsKey('text_message')) {
return TextMessage.fromJson(json);
} else {
throw UnsupportedError('Unknown payload type');
}
Expand Down
23 changes: 18 additions & 5 deletions lib/features/chat/notifiers/chat_room_notifier.dart
Original file line number Diff line number Diff line change
Expand Up @@ -188,22 +188,35 @@ class ChatRoomNotifier extends StateNotifier<ChatRoom> {
);

try {
final wrappedEvent = await innerEvent.mostroWrap(session.sharedKey!);
final wrappedEvent = await innerEvent.mostroWrap(
session.tradeKey,
session.sharedKey!.public,
);

final allMessages = [...state.messages, innerEvent];
final deduped = {for (var m in allMessages) m.id: m}.values.toList();
deduped.sort((a, b) => b.createdAt!.compareTo(a.createdAt!));
state = state.copy(messages: deduped);

// Notify the chat rooms list to update immediately
// Publish to network - await to catch network/initialization errors
try {
await ref.read(nostrServiceProvider).publishEvent(wrappedEvent);
_logger.d('Message sent successfully to network');
} catch (publishError, publishStack) {
_logger.e('Failed to publish message: $publishError', stackTrace: publishStack);
// Remove from local state if publish failed
final updatedMessages =
state.messages.where((msg) => msg.id != innerEvent.id).toList();
state = state.copy(messages: updatedMessages);
rethrow; // Re-throw to be caught by outer catch
}

// Notify the chat rooms list to update after successful publish
try {
ref.read(chatRoomsNotifierProvider.notifier).refreshChatList();
} catch (e) {
_logger.w('Could not refresh chat list after sending message: $e');
}

ref.read(nostrServiceProvider).publishEvent(wrappedEvent);
_logger.d('Message sent successfully to network');
} catch (e, stackTrace) {
_logger.e('Failed to send message: $e', stackTrace: stackTrace);
// Remove from local state if sending failed
Expand Down
Loading