feat(#627): add a contact from a key alone, with no advert

Adds MeshCoreConnector.addContactByKey, the device-side half of the
identity exchange. It uses the stock CMD_ADD_UPDATE_CONTACT (command 9),
whose handler creates the contact outright when the public key is
unknown. Verified byte-identical to upstream meshcore-dev/MeshCore at
0679dbef, so this needs no capability gate and works on stock firmware,
not only Offband builds.

buildUpdateContactPathFrame gains an optional lastAdvert. It defaults to
now, leaving all three existing path-update callers byte-identical, and
addContactByKey passes the epoch.

That epoch is the whole point. The firmware compares this field against
every incoming advert with 'timestamp <= last_advert_timestamp' and
silently discards the non-greater ones as replay attacks
(BaseChatMesh.cpp:142-145). Advert timestamps come from the sender's
clock, and two nodes on this mesh currently advertise with 2024 clocks,
so stamping now would leave a key-added contact permanently deaf to its
own adverts. A negative input clamps to zero rather than wrapping to a
huge value, which would be the worst case for that guard.

The frame is sent at full length with the 0xFF flood sentinel. The
firmware length guard is only 'len >= 36' but updateContactFromFrame
reads through offset 136 regardless (MyMesh.cpp:295-318), so the frame
must never be trimmed. A test pins that too.

Local state keeps lastSeen at the epoch so the contact reads as
unverified until a real advert upgrades it (#630).

Epic #619.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
pull/655/head
Strycher 3 months ago
parent bbea912cb0
commit 9b63983033

@ -4073,6 +4073,48 @@ class MeshCoreConnector extends ChangeNotifier {
notifyListeners();
}
/// Adds a contact from an identity alone: a public key, a name and a type,
/// with no advert behind it. (#627)
///
/// This is the path behind manual key entry, a scanned QR, and a pasted
/// `meshcore://contact/add` card. It uses the stock `CMD_ADD_UPDATE_CONTACT`
/// (command 9), whose handler creates the contact outright when the key is
/// unknown, so it needs no capability gate and works on stock firmware, not
/// just Offband builds.
///
/// Returns false when not connected. The radio answers with a generic OK, or
/// an error when its contact table is full.
Future<bool> addContactByKey(Contact stub) async {
if (!isConnected) return false;
await sendFrame(
buildUpdateContactPathFrame(
stub.publicKey,
// No path is known, so send an empty one and let the flood sentinel
// below carry the meaning. The builder pads this to the full width.
Uint8List(0),
// Negative maps to the firmware's OUT_PATH_UNKNOWN (0xFF): flood until
// the mesh teaches us a route back.
-1,
type: stub.type,
flags: 0,
name: stub.name,
// The whole point of this path. Anything else here would trip the
// firmware advert replay guard and leave the contact permanently deaf
// to its own adverts. See buildUpdateContactPathFrame. (#620)
lastAdvert: DateTime.fromMillisecondsSinceEpoch(0),
),
expectsGenericAck: true,
);
// Mirror the device write into local state, keeping lastSeen at the epoch
// so the contact continues to read as unverified until a real advert
// arrives and upgrades it. (#630)
_handleContactAdvert(stub);
notifyListeners();
return true;
}
Future<void> importDiscoveredContact(Contact contact) async {
if (!isConnected) return;

@ -1188,6 +1188,7 @@ Uint8List buildUpdateContactPathFrame(
double? lat,
double? lon,
DateTime? lastModified,
DateTime? lastAdvert,
}) {
final writer = BufferWriter();
writer.writeByte(cmdAddUpdateContact);
@ -1202,9 +1203,20 @@ Uint8List buildUpdateContactPathFrame(
// Name (32 bytes, null-padded)
writer.writeCString(name, maxNameSize);
// Timestamp
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
writer.writeUInt32LE(timestamp);
// Mandatory last_advert_timestamp. Defaults to now, which is right for the
// path-update callers: they refresh a contact the radio already learned from
// a real advert.
//
// A key-only add MUST pass the epoch instead (#627). The firmware compares
// this field against every incoming advert with
// `timestamp <= last_advert_timestamp` and silently discards the non-greater
// ones as replay attacks (`BaseChatMesh.cpp:142-145`). Advert timestamps come
// from the SENDER's clock, and clocks in the field run years behind, so
// stamping "now" on a contact that has never adverted would leave it
// permanently deaf to its own adverts. Zero lets any genuine advert win.
final advertSeconds =
(lastAdvert ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000;
writer.writeUInt32LE(advertSeconds < 0 ? 0 : advertSeconds);
// Optional [Lat x4, Lon x4][timestamp x4] tail per the doc comment above.
// Emit 8 bytes of position (zero-filled when only lastModified is provided)

@ -155,4 +155,69 @@ void main() {
expect(lonBytes.getInt32(0, Endian.little), (-123.123456 * 1e6).round());
});
});
group('last_advert_timestamp for key-only adds (#627)', () {
// 1 cmd + 32 pubKey + 1 type + 1 flags + 1 pathLen + 64 path + 32 name.
const int advertTsOffset = 132;
int advertTs(Uint8List frame) => ByteData.sublistView(
frame,
advertTsOffset,
advertTsOffset + 4,
).getUint32(0, Endian.little);
test('a key-only add writes zero, not the current time', () {
// The whole point. The firmware discards any advert whose timestamp is
// <= this value as a replay attack (BaseChatMesh.cpp:142-145), and
// advert timestamps come from the SENDER's clock. Writing "now" here
// would leave a key-added contact permanently deaf to its own adverts.
final frame = buildUpdateContactPathFrame(
pubKey,
Uint8List(0),
-1,
name: 'Bob',
lastAdvert: DateTime.fromMillisecondsSinceEpoch(0),
);
expect(advertTs(frame), 0);
});
test(
'omitting lastAdvert still stamps now, so path updates are unchanged',
() {
final before = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final frame = buildUpdateContactPathFrame(pubKey, path, 1);
final after = DateTime.now().millisecondsSinceEpoch ~/ 1000;
expect(advertTs(frame), greaterThanOrEqualTo(before));
expect(advertTs(frame), lessThanOrEqualTo(after));
},
);
test('a pre-epoch value clamps to zero rather than wrapping', () {
// writeUInt32LE on a negative would wrap to a huge timestamp, which is
// the worst possible value for the replay guard.
final frame = buildUpdateContactPathFrame(
pubKey,
Uint8List(0),
-1,
lastAdvert: DateTime.fromMillisecondsSinceEpoch(-86400000),
);
expect(advertTs(frame), 0);
});
test('a key-only add is a full-length frame with the flood sentinel', () {
// The firmware guard is only `len >= 36`, but updateContactFromFrame
// reads through offset 136 regardless (MyMesh.cpp:295-318), so a short
// frame would have it read past what we sent. Never trim this.
final frame = buildUpdateContactPathFrame(
pubKey,
Uint8List(0),
-1,
name: 'Bob',
lastAdvert: DateTime.fromMillisecondsSinceEpoch(0),
);
expect(frame.length, greaterThanOrEqualTo(baseFrameLength));
expect(frame[pathLenOffset], 0xFF);
});
});
}

Loading…
Cancel
Save

Powered by TurnKey Linux.