Files
buzz/mobile/lib/shared/crypto/nip44.dart
Wes 8827f986e4 mobile: follow desktop's unified sidebar workspaces (#9745)
Mobile Home now reads desktop's unified sidebar from block/buzz-app#3791
and shows the same workspaces, filings, icons and section order as the
desktop sidebar. It is read-only while a unified record exists.

## What changed

- **Reads desktop's records.** Mobile reads `channel-workspaces` and
`channel-workspace-sort`. Until the unified record exists, it falls back
to the legacy `channel-sections` and Solo groups, merging them the way
desktop imports them (`expandWorkspaceRecord`,
`importWorkspaceFallback`, `mergeLegacyWorkspaces`). Sort follows
desktop's `meta.g` registers.
- **Layout.** Sections are Starred, then the workspaces, Team, Solo and
Direct messages, in desktop's `sectionOrder`. A workspace holds Team
channels and Solo chats alike, and shows its icon: Unicode emoji as
text, `:shortcode:` as the community's custom emoji, and nothing for an
unknown shortcode.
- **Read-only lock.** While a unified record exists, mobile hides
rename, delete, move, New project and sort edits, and never publishes
the legacy records desktop would ignore. That includes:
  - an edit queued before the lock;
- a unified head arriving during a relay rate-limit wait (`mayPublish`);
  - a Team publish whose preflight read failed;
- a New project or workspace pick opened before the lock (the chat is
still created, without the filing).
- **Recovery.** A foreground refresh with a pending legacy sort still
applies a missed unified head.
- **No All/Solo/Team filter.** Desktop removed its tabs in #3791, since
workspaces now hold Solo and team chats together, so Home drops its
chips too. The Messages header keeps its title and actions and no longer
collapses on scroll.
- **Filters.** The Unreads filter uses Solo's own unread state for Solo
rows.
- **NIP-44.** Decryption accepts the extended length prefix for payloads
over 65535 bytes. A nostr-tools vector is included.

## Tests

- `workspace_layout_interop_test.dart`: a table generated by running
desktop's TypeScript from buzz-app `main` (11 layouts and 10 invalid
records). It checks that mobile computes the same sections, assignments
and order.
- `sidebar_workspaces_journey_test.dart`: Home runs on the real sections
and sort notifiers over the relay fixture. It starts on legacy sections,
receives desktop's signed heads live, then checks the order, filings,
icon, read-only sheet and Unreads. It also checks that only the filter
choice is published.
- `unified_sidebar_records_test.dart`: Team and sort publish nothing
once a unified head is seen: before an edit, while one waits, or past a
failed preflight.
- `project_creation_test.dart`: the unified layout arrives while a
workspace is being named. Nothing is written, and nothing is left to
resume.

- `solo_creation_tags_test.dart` and `me_sync_test.dart`: a project
picked or a filing queued before the lock doesn't stop a new Solo chat
from being created.

Each new guard was mutation-checked: removing it fails its test.
`flutter analyze` is clean and `flutter test` passes (5450).

## Not in this PR (open questions)

- **Forums** stay hidden on Home, as before. Desktop shows them, so a
forum filed into a workspace or starred on desktop doesn't appear on
mobile. Should mobile add a Forums section?
- **Filters** still use the legacy `channel-filter` record. Desktop
prefers `channel-workspace-filter`.
- **Solo creation without a unified record** still writes the legacy
Solo groups, as before.
- **Empty workspaces** are shown, as on desktop. Mobile rejects a
unified record that carries `meta` without `filings`; desktop never
writes that shape.
- Built-in titles now match desktop: "Team" (was "Channels") and "Direct
messages" (was "DMs").

## How to test

1. On desktop (buzz-app with #3791), create two workspaces, give one an
emoji icon, and file a Team channel and a Solo chat into it. Reorder the
sections.
2. Open mobile Home in the same community. The sections, order, icon and
filings should match desktop.
3. Open a workspace's options. You should see only Sort (disabled) and
Show. Long-press a channel: there's no "Move to section…".
4. There is no All/Solo/Team filter row under the Messages title.
5. Change the order on desktop. Mobile should follow live, or after you
foreground the app.

Screenshots are in the comment below.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-19 18:49:12 -07:00

178 lines
6.2 KiB
Dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/digests/sha256.dart';
import 'package:pointycastle/macs/hmac.dart';
import 'package:pointycastle/stream/chacha7539.dart';
import 'ecdh.dart';
import 'hkdf.dart';
/// NIP-44 v2 conversation key derivation.
///
/// conversation_key = HKDF-Extract(salt="nip44-v2", ikm=ecdh_shared_secret)
Uint8List getConversationKey(String senderPrivHex, String receiverPubHex) {
final shared = ecdhSharedSecret(senderPrivHex, receiverPubHex);
final salt = utf8.encode('nip44-v2');
return hkdfExtract(Uint8List.fromList(salt), shared);
}
/// NIP-44 v2 encrypt.
///
/// Returns base64-encoded payload: version(1) || nonce(32) || ciphertext || mac(32)
String nip44Encrypt(Uint8List conversationKey, String plaintext) {
final plaintextBytes = utf8.encode(plaintext);
if (plaintextBytes.isEmpty || plaintextBytes.length > 65535) {
throw ArgumentError('Plaintext must be 1-65535 bytes');
}
final padded = _pad(Uint8List.fromList(plaintextBytes));
final nonce = secureRandomBytes(32);
// Derive message keys: chacha_key(32) + chacha_nonce(12) + hmac_key(32) = 76
final messageKeys = hkdfExpand(conversationKey, nonce, 76);
final chachaKey = Uint8List.sublistView(messageKeys, 0, 32);
final chachaNonce = Uint8List.sublistView(messageKeys, 32, 44);
final hmacKey = Uint8List.sublistView(messageKeys, 44, 76);
final ciphertext = _chacha20(chachaKey, chachaNonce, padded);
// HMAC-SHA256 over nonce || ciphertext.
final mac = _hmacSha256(hmacKey, _concat([nonce, ciphertext]));
// Assemble: version(0x02) || nonce(32) || ciphertext || mac(32)
final payload = _concat([
Uint8List.fromList([0x02]),
nonce,
ciphertext,
mac,
]);
return base64.encode(payload);
}
/// NIP-44 v2 decrypt.
///
/// Takes base64-encoded payload, returns plaintext string.
String nip44Decrypt(Uint8List conversationKey, String payloadBase64) {
final payload = base64.decode(payloadBase64);
// Minimum: version(1) + nonce(32) + min_ciphertext(32) + mac(32) = 97
if (payload.length < 97) {
throw FormatException('NIP-44 payload too short: ${payload.length}');
}
if (payload[0] != 0x02) {
throw FormatException('NIP-44 unsupported version: ${payload[0]}');
}
final nonce = Uint8List.sublistView(payload, 1, 33);
final ciphertext = Uint8List.sublistView(payload, 33, payload.length - 32);
final receivedMac = Uint8List.sublistView(payload, payload.length - 32);
final messageKeys = hkdfExpand(conversationKey, nonce, 76);
final chachaKey = Uint8List.sublistView(messageKeys, 0, 32);
final chachaNonce = Uint8List.sublistView(messageKeys, 32, 44);
final hmacKey = Uint8List.sublistView(messageKeys, 44, 76);
// Verify HMAC.
final expectedMac = _hmacSha256(hmacKey, _concat([nonce, ciphertext]));
if (!constantTimeEquals(receivedMac, expectedMac)) {
throw FormatException('NIP-44 HMAC verification failed');
}
final padded = _chacha20(chachaKey, chachaNonce, ciphertext);
return _unpad(padded);
}
// ── Padding ─────────────────────────────────────────────────────────────────
int _calcPaddedLen(int unpaddedLen) {
if (unpaddedLen <= 0) throw ArgumentError('Length must be > 0');
if (unpaddedLen <= 32) return 32;
final nextPower = 1 << (_log2(unpaddedLen - 1) + 1);
final chunk = nextPower <= 256 ? 32 : nextPower ~/ 8;
return chunk * (((unpaddedLen - 1) ~/ chunk) + 1);
}
int _log2(int x) {
var result = 0;
while ((1 << (result + 1)) <= x) {
result++;
}
return result;
}
Uint8List _pad(Uint8List plaintext) {
final len = plaintext.length;
final paddedLen = _calcPaddedLen(len);
// Result: [2-byte BE length][plaintext][zero padding]
final result = Uint8List(2 + paddedLen);
result[0] = (len >> 8) & 0xFF;
result[1] = len & 0xFF;
result.setRange(2, 2 + len, plaintext);
return result;
}
String _unpad(Uint8List padded) {
if (padded.length < 2) throw FormatException('Padded data too short');
var len = (padded[0] << 8) | padded[1];
var prefix = 2;
// Plaintexts of 64 KiB or more use a zero u16 then a u32 big-endian length,
// as nostr-tools writes them.
if (len == 0 && padded.length >= 6) {
len = ByteData.sublistView(padded, 2, 6).getUint32(0);
prefix = 6;
if (len < 65536) throw FormatException('Invalid padding length: $len');
}
if (len == 0 || prefix + len > padded.length) {
throw FormatException('Invalid padding length: $len');
}
return utf8.decode(padded.sublist(prefix, prefix + len));
}
// ── ChaCha20 (IETF, 12-byte nonce) ─────────────────────────────────────────
Uint8List _chacha20(Uint8List key, Uint8List nonce, Uint8List data) {
final cipher = ChaCha7539Engine();
cipher.init(false, ParametersWithIV(KeyParameter(key), nonce));
return cipher.process(data);
}
// ── HMAC-SHA256 ─────────────────────────────────────────────────────────────
Uint8List _hmacSha256(Uint8List key, Uint8List data) {
final hmac = HMac(SHA256Digest(), 64);
hmac.init(KeyParameter(key));
hmac.update(data, 0, data.length);
final out = Uint8List(32);
hmac.doFinal(out, 0);
return out;
}
// ── Helpers ─────────────────────────────────────────────────────────────────
Uint8List _concat(List<Uint8List> parts) {
final totalLen = parts.fold<int>(0, (sum, p) => sum + p.length);
final result = Uint8List(totalLen);
var offset = 0;
for (final part in parts) {
result.setRange(offset, offset + part.length, part);
offset += part.length;
}
return result;
}
/// Constant-time byte comparison to prevent timing side-channels.
bool constantTimeEquals(Uint8List a, Uint8List b) {
if (a.length != b.length) return false;
var result = 0;
for (var i = 0; i < a.length; i++) {
result |= a[i] ^ b[i];
}
return result == 0;
}