wire-desktop-core 0.1.2

Wire desktop (Electron) messenger reader — interprets the Chromium IndexedDB-over-LevelDB Dexie object stores into typed Wire records (conversations, events, users, clients) and a timeline; surfaces client-side-encrypted message payloads as unrecoverable rather than fabricating plaintext
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Typed Wire records and the interpretation of IndexedDB records into them.
//!
//! Wire desktop is an Electron wrapper over the Wire web client; all evidence
//! lives in the Chromium IndexedDB (`https_app.wire.com_0.indexeddb.leveldb`),
//! organised as Dexie object stores. This module maps each generic
//! [`IndexedDbRecord`] (already decoded by [`chromium_storage_indexeddb`]) onto a
//! typed [`WireRecord`] by the object-store it came from.
//!
//! The object-store names are Wire web-client schema knowledge (Dexie stores
//! `conversations`, `events`, `users`, `clients`); the profile path and the
//! encryption posture come from the fleet KNOWLEDGE leaf
//! [`forensicnomicon_core::messenger_desktop`].
//!
//! # Encrypted content
//!
//! Message bodies are frequently client-side encrypted (Proteus). Wire's message
//! key is **not** stored in the Chromium OS Safe Storage, so it is not
//! recoverable from this artifact. An encrypted payload is surfaced as
//! [`PayloadState::Encrypted`] with its cleartext metadata (conversation,
//! sender, time) intact; asking for its plaintext fails loud (see
//! [`WireRecord::decrypted_text`]) rather than fabricating bytes.

use crate::error::WireError;
use chromium_storage_indexeddb::{IdbKey, IndexedDbRecord, RecordValue, V8Value};

/// Which Wire object store a record came from — the Dexie store name mapped to a
/// forensic role.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireRecordKind {
    /// `conversations` — conversation/group metadata.
    Conversation,
    /// `events` — message and system events (the chat log).
    Event,
    /// `users` — the contact roster.
    User,
    /// `clients` — registered devices/clients.
    Client,
    /// An object store this reader does not map to a Wire role.
    Unknown,
}

impl WireRecordKind {
    /// Map a Dexie object-store name to its Wire role.
    #[must_use]
    pub fn from_store_name(name: &str) -> WireRecordKind {
        match name {
            "conversations" => WireRecordKind::Conversation,
            "events" => WireRecordKind::Event,
            "users" => WireRecordKind::User,
            "clients" => WireRecordKind::Client,
            _ => WireRecordKind::Unknown,
        }
    }

    /// A stable label for the kind.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            WireRecordKind::Conversation => "conversation",
            WireRecordKind::Event => "event",
            WireRecordKind::User => "user",
            WireRecordKind::Client => "client",
            WireRecordKind::Unknown => "unknown",
        }
    }
}

/// The recoverability state of a record's content.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PayloadState {
    /// The content is in cleartext (metadata records, or a message whose body
    /// was extractable).
    Cleartext,
    /// The content is client-side encrypted and its key is not recoverable from
    /// this artifact.
    Encrypted {
        /// The encryption scheme (Wire uses Proteus for message content).
        scheme: &'static str,
        /// Why the plaintext is unrecoverable.
        reason: &'static str,
    },
    /// The value could not be decoded from its Blink/V8 blob upstream.
    Undecoded {
        /// The upstream decode error, verbatim.
        error: String,
    },
}

/// One interpreted Wire record.
///
/// Fields absent from the source record stay `None`; only fields the record
/// actually carries are populated. `#[non_exhaustive]` so new fields do not
/// break consumers.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct WireRecord {
    /// The object-store name the record came from.
    pub store: String,
    /// The Wire role of the store.
    pub kind: WireRecordKind,
    /// The record's primary key, rendered as text.
    pub primary_key: String,
    /// The record's own `id` field, if present.
    pub id: Option<String>,
    /// The conversation id the record belongs to, if present.
    pub conversation: Option<String>,
    /// The sender/author (`from`) of an event, if present.
    pub sender: Option<String>,
    /// The event/record timestamp as stored (ISO-8601 string), if present.
    pub time: Option<String>,
    /// The Wire event `type` (e.g. `conversation.message-add`), if present.
    pub message_type: Option<String>,
    /// A human name — conversation name, user display name, or device model.
    pub name: Option<String>,
    /// The cleartext message body, when one was recoverable.
    pub text: Option<String>,
    /// Whether the content is cleartext, encrypted, or undecodable.
    pub payload: PayloadState,
    /// LevelDB sequence number (write ordering).
    pub seq: u64,
    /// `true` if this record is a deletion tombstone recovered from the store.
    pub deleted: bool,
}

impl WireRecord {
    /// The recoverable plaintext of this record's message body.
    ///
    /// Returns the cleartext body for a [`PayloadState::Cleartext`] record.
    /// For an encrypted or undecodable payload it **fails loud** with a typed
    /// error — it never fabricates plaintext.
    pub fn decrypted_text(&self) -> Result<&str, WireError> {
        match &self.payload {
            PayloadState::Cleartext => Ok(self.text.as_deref().unwrap_or("")),
            PayloadState::Encrypted { .. } => Err(WireError::EncryptedPayloadUnrecoverable),
            PayloadState::Undecoded { error } => Err(WireError::UndecodedValue(error.clone())),
        }
    }

    /// Whether this record's content is client-side encrypted and unrecoverable.
    #[must_use]
    pub fn is_encrypted(&self) -> bool {
        matches!(self.payload, PayloadState::Encrypted { .. })
    }
}

/// Interpret a slice of decoded IndexedDB records into a typed [`WireStore`].
///
/// Every record is passed through as a [`WireRecord`] (store, role, primary key,
/// sequence, tombstone flag, and decode-state payload); per-store field
/// extraction is applied by the `fill_*` handlers. A per-object-store summary is
/// rolled up alongside.
#[must_use]
pub fn interpret_records(records: &[IndexedDbRecord]) -> WireStore {
    let mut out = Vec::with_capacity(records.len());
    let mut summaries: Vec<ObjectStoreSummary> = Vec::new();

    for r in records {
        let store = r.object_store.as_deref().unwrap_or("");
        let wr = interpret_one(store, r);

        if !store.is_empty() {
            let enc = usize::from(wr.is_encrypted());
            let del = usize::from(wr.deleted);
            match summaries.iter_mut().find(|s| s.name == store) {
                Some(sum) => {
                    sum.records += 1;
                    sum.encrypted_payloads += enc;
                    sum.deleted += del;
                }
                None => summaries.push(ObjectStoreSummary {
                    name: store.to_string(),
                    kind: wr.kind,
                    records: 1,
                    encrypted_payloads: enc,
                    deleted: del,
                }),
            }
        }
        out.push(wr);
    }

    WireStore {
        object_stores: summaries,
        records: out,
    }
}

/// Interpret one decoded IndexedDB record into a [`WireRecord`].
///
/// Builds the base record (store, role, primary key, seq, tombstone flag,
/// decode-state payload) then dispatches to the per-store field extractor.
fn interpret_one(store: &str, r: &IndexedDbRecord) -> WireRecord {
    let kind = WireRecordKind::from_store_name(store);
    let mut wr = WireRecord {
        store: store.to_string(),
        kind,
        primary_key: render_key(&r.key),
        id: None,
        conversation: None,
        sender: None,
        time: None,
        message_type: None,
        name: None,
        text: None,
        payload: base_payload(&r.value),
        seq: r.seq,
        deleted: r.deleted,
    };

    if let RecordValue::V8(v) = &r.value {
        match kind {
            WireRecordKind::Conversation => fill_conversation(&mut wr, v),
            WireRecordKind::Event => fill_event(&mut wr, v),
            WireRecordKind::User => fill_user(&mut wr, v),
            WireRecordKind::Client => fill_client(&mut wr, v),
            WireRecordKind::Unknown => {}
        }
    }

    wr
}

/// Extract conversation metadata: the conversation id (its own `id`) and the
/// display `name`.
fn fill_conversation(wr: &mut WireRecord, v: &V8Value) {
    wr.id = obj_field(v, "id").and_then(as_text);
    wr.conversation = wr.id.clone();
    wr.name = obj_field(v, "name").and_then(as_text);
}

/// Extract event metadata (conversation, sender, time, type) and, when the body
/// is in cleartext, the message text. Encrypted-payload classification is added
/// by the encrypted-event cycle.
fn fill_event(wr: &mut WireRecord, v: &V8Value) {
    wr.id = obj_field(v, "id").and_then(as_text);
    wr.conversation = obj_field(v, "conversation").and_then(as_text);
    wr.sender = obj_field(v, "from")
        .or_else(|| obj_field(v, "sender"))
        .and_then(as_text);
    wr.time = obj_field(v, "time").and_then(as_text);
    wr.message_type = obj_field(v, "type").and_then(as_text);

    if let Some(text) = message_text(v) {
        wr.text = Some(text);
        wr.payload = PayloadState::Cleartext;
    } else if is_encrypted_payload(v) {
        // Wire message content is Proteus-encrypted client-side; its key is not
        // in the Chromium OS Safe Storage, so we mark it unrecoverable rather
        // than fabricate plaintext.
        wr.payload = PayloadState::Encrypted {
            scheme: "Proteus",
            reason: "Wire message key is not held in the Chromium OS Safe Storage",
        };
    }
}

/// Whether an event value carries an opaque/ciphered body with no cleartext.
///
/// General structural rule (not tied to any one fixture): a top-level or nested
/// `data` [`V8Value::ArrayBuffer`], or a documented ciphertext-marker field
/// (`cipher_text` / `cipherText` / `otr` / `encrypted`) at the top level or
/// under `data`.
fn is_encrypted_payload(v: &V8Value) -> bool {
    const CIPHER_MARKERS: [&str; 4] = ["cipher_text", "cipherText", "otr", "encrypted"];

    if matches!(v, V8Value::ArrayBuffer(_)) {
        return true;
    }
    let data = obj_field(v, "data");
    if matches!(data, Some(V8Value::ArrayBuffer(_))) {
        return true;
    }
    CIPHER_MARKERS
        .iter()
        .any(|m| obj_field(v, m).is_some() || data.is_some_and(|d| obj_field(d, m).is_some()))
}

/// Extract a cleartext message body from an event value: the `content`/`text`
/// field of the nested `data` object, or a top-level `content`/`text` field.
/// Returns `None` when no cleartext body is present (e.g. an encrypted or a
/// pure-system event).
fn message_text(v: &V8Value) -> Option<String> {
    if let Some(data) = obj_field(v, "data") {
        if let Some(t) = obj_field(data, "content")
            .or_else(|| obj_field(data, "text"))
            .and_then(as_text)
        {
            return Some(t);
        }
    }
    obj_field(v, "content")
        .or_else(|| obj_field(v, "text"))
        .and_then(as_text)
}

/// Extract user metadata: the user `id` and the display `name`.
fn fill_user(wr: &mut WireRecord, v: &V8Value) {
    wr.id = obj_field(v, "id").and_then(as_text);
    wr.name = obj_field(v, "name").and_then(as_text);
}

/// Extract client/device metadata: the client `id` and a device label (the
/// `model`, falling back to the `class` or `label`).
fn fill_client(wr: &mut WireRecord, v: &V8Value) {
    wr.id = obj_field(v, "id").and_then(as_text);
    wr.name = obj_field(v, "model")
        .or_else(|| obj_field(v, "class"))
        .or_else(|| obj_field(v, "label"))
        .and_then(as_text);
}

/// The interpreted Wire store: a per-object-store summary plus every record.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct WireStore {
    /// One summary per named object store found.
    pub object_stores: Vec<ObjectStoreSummary>,
    /// Every interpreted record, in source order.
    pub records: Vec<WireRecord>,
}

impl WireStore {
    /// Records belonging to `store`.
    pub fn records_in<'a>(&'a self, store: &'a str) -> impl Iterator<Item = &'a WireRecord> {
        self.records.iter().filter(move |r| r.store == store)
    }

    /// All message/system event records.
    pub fn events(&self) -> impl Iterator<Item = &WireRecord> {
        self.records
            .iter()
            .filter(|r| r.kind == WireRecordKind::Event)
    }

    /// Event records whose content is client-side encrypted (unrecoverable).
    pub fn encrypted_events(&self) -> impl Iterator<Item = &WireRecord> {
        self.events().filter(|r| r.is_encrypted())
    }
}

/// A per-object-store roll-up.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectStoreSummary {
    /// The Dexie object-store name.
    pub name: String,
    /// Its Wire role.
    pub kind: WireRecordKind,
    /// How many records it holds (live + tombstoned).
    pub records: usize,
    /// How many of those records carry an encrypted, unrecoverable payload.
    pub encrypted_payloads: usize,
    /// How many are deletion tombstones.
    pub deleted: usize,
}

// ─── value helpers (shared by the per-store fill_* handlers) ─────────────────

/// Render an [`IdbKey`] to a stable text form for the record's `primary_key`.
pub(crate) fn render_key(key: &IdbKey) -> String {
    match key {
        IdbKey::String(s) => s.clone(),
        IdbKey::Number(n) | IdbKey::Date(n) => n.to_string(),
        IdbKey::Binary(b) => format!("0x{}", hex(b)),
        IdbKey::Array(items) => {
            let parts: Vec<String> = items.iter().map(render_key).collect();
            format!("[{}]", parts.join(","))
        }
        IdbKey::Null => "null".to_string(),
        IdbKey::Min => "min".to_string(),
        IdbKey::Invalid(b) => format!("invalid:0x{}", hex(b)),
    }
}

fn hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(char::from_digit(u32::from(b >> 4), 16).unwrap_or('0'));
        s.push(char::from_digit(u32::from(b & 0x0f), 16).unwrap_or('0'));
    }
    s
}

/// A record value that decoded to a V8 object; `None` for non-objects.
pub(crate) fn obj_field<'a>(v: &'a V8Value, key: &str) -> Option<&'a V8Value> {
    match v {
        V8Value::Object(kv) => kv.iter().find(|(k, _)| k == key).map(|(_, val)| val),
        _ => None,
    }
}

/// Render a scalar V8 value to text; `None` for containers/binary.
pub(crate) fn as_text(v: &V8Value) -> Option<String> {
    match v {
        V8Value::String(s) | V8Value::StringObject(s) | V8Value::BigInt(s) => Some(s.clone()),
        V8Value::Int(i) => Some(i.to_string()),
        V8Value::Double(d) | V8Value::Date(d) | V8Value::NumberObject(d) => Some(d.to_string()),
        V8Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

/// The decode-state of a record value, independent of its object-store role.
pub(crate) fn base_payload(value: &RecordValue) -> PayloadState {
    match value {
        RecordValue::V8(_) => PayloadState::Cleartext,
        RecordValue::Undecoded { error, .. } => PayloadState::Undecoded {
            error: error.clone(),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::WireError;

    #[test]
    fn render_key_covers_every_idbkey_variant() {
        assert_eq!(render_key(&IdbKey::String("k".into())), "k");
        assert_eq!(render_key(&IdbKey::Number(3.0)), "3");
        assert_eq!(render_key(&IdbKey::Date(5.0)), "5");
        assert_eq!(render_key(&IdbKey::Binary(vec![0xab, 0x0f])), "0xab0f");
        assert_eq!(render_key(&IdbKey::Null), "null");
        assert_eq!(render_key(&IdbKey::Min), "min");
        assert_eq!(render_key(&IdbKey::Invalid(vec![0x01])), "invalid:0x01");
        assert_eq!(
            render_key(&IdbKey::Array(vec![
                IdbKey::String("a".into()),
                IdbKey::Number(1.0)
            ])),
            "[a,1]"
        );
    }

    #[test]
    fn as_text_covers_scalar_and_container_variants() {
        assert_eq!(as_text(&V8Value::String("s".into())).as_deref(), Some("s"));
        assert_eq!(
            as_text(&V8Value::StringObject("o".into())).as_deref(),
            Some("o")
        );
        assert_eq!(as_text(&V8Value::BigInt("9".into())).as_deref(), Some("9"));
        assert_eq!(as_text(&V8Value::Int(7)).as_deref(), Some("7"));
        assert_eq!(as_text(&V8Value::Double(2.0)).as_deref(), Some("2"));
        assert_eq!(as_text(&V8Value::Date(4.0)).as_deref(), Some("4"));
        assert_eq!(as_text(&V8Value::NumberObject(6.0)).as_deref(), Some("6"));
        assert_eq!(as_text(&V8Value::Bool(true)).as_deref(), Some("true"));
        assert_eq!(as_text(&V8Value::Null), None);
        assert_eq!(as_text(&V8Value::Array(vec![])), None);
    }

    #[test]
    fn obj_field_returns_none_for_non_objects_and_missing_keys() {
        assert!(obj_field(&V8Value::Null, "x").is_none());
        let o = V8Value::Object(vec![("a".into(), V8Value::Int(1))]);
        assert!(obj_field(&o, "missing").is_none());
        assert!(obj_field(&o, "a").is_some());
    }

    #[test]
    fn base_payload_maps_decode_state() {
        assert_eq!(
            base_payload(&RecordValue::V8(V8Value::Null)),
            PayloadState::Cleartext
        );
        let u = RecordValue::Undecoded {
            raw: vec![0xff],
            error: "boom".into(),
        };
        assert!(matches!(base_payload(&u), PayloadState::Undecoded { .. }));
    }

    #[test]
    fn kind_mapping_and_labels() {
        assert_eq!(
            WireRecordKind::from_store_name("conversations"),
            WireRecordKind::Conversation
        );
        assert_eq!(
            WireRecordKind::from_store_name("events"),
            WireRecordKind::Event
        );
        assert_eq!(
            WireRecordKind::from_store_name("users"),
            WireRecordKind::User
        );
        assert_eq!(
            WireRecordKind::from_store_name("clients"),
            WireRecordKind::Client
        );
        assert_eq!(
            WireRecordKind::from_store_name("keys"),
            WireRecordKind::Unknown
        );
        for k in [
            WireRecordKind::Conversation,
            WireRecordKind::Event,
            WireRecordKind::User,
            WireRecordKind::Client,
            WireRecordKind::Unknown,
        ] {
            assert!(!k.as_str().is_empty());
        }
    }

    fn rec(payload: PayloadState, text: Option<&str>) -> WireRecord {
        WireRecord {
            store: "events".into(),
            kind: WireRecordKind::Event,
            primary_key: "k".into(),
            id: None,
            conversation: None,
            sender: None,
            time: None,
            message_type: None,
            name: None,
            text: text.map(str::to_string),
            payload,
            seq: 0,
            deleted: false,
        }
    }

    #[test]
    fn decrypted_text_returns_or_fails_loud_per_payload() {
        assert_eq!(
            rec(PayloadState::Cleartext, Some("hi"))
                .decrypted_text()
                .unwrap(),
            "hi"
        );
        // Cleartext with no text yields an empty body, not an error.
        assert_eq!(
            rec(PayloadState::Cleartext, None).decrypted_text().unwrap(),
            ""
        );
        let enc = rec(
            PayloadState::Encrypted {
                scheme: "Proteus",
                reason: "no key",
            },
            None,
        );
        assert!(matches!(
            enc.decrypted_text(),
            Err(WireError::EncryptedPayloadUnrecoverable)
        ));
        let und = rec(
            PayloadState::Undecoded {
                error: "bad".into(),
            },
            None,
        );
        assert!(matches!(
            und.decrypted_text(),
            Err(WireError::UndecodedValue(_))
        ));
    }

    #[test]
    fn is_encrypted_payload_covers_top_level_and_marker_paths() {
        // Bare ArrayBuffer value (top-level).
        assert!(is_encrypted_payload(&V8Value::ArrayBuffer(vec![1, 2])));
        // Top-level cipher-marker field.
        let top_marker = V8Value::Object(vec![("otr".into(), V8Value::String("x".into()))]);
        assert!(is_encrypted_payload(&top_marker));
        // data.encrypted marker.
        let nested = V8Value::Object(vec![(
            "data".into(),
            V8Value::Object(vec![("encrypted".into(), V8Value::Bool(true))]),
        )]);
        assert!(is_encrypted_payload(&nested));
        // A plain cleartext object is not encrypted.
        let plain = V8Value::Object(vec![("content".into(), V8Value::String("hi".into()))]);
        assert!(!is_encrypted_payload(&plain));
    }

    #[test]
    fn interpret_skips_summary_for_unnamed_store() {
        // A record with no object_store name is still passed through, but not
        // counted in any object-store summary.
        let r = IndexedDbRecord {
            database_id: 0,
            object_store_id: 0,
            database: None,
            object_store: None,
            key: IdbKey::Null,
            value: RecordValue::V8(V8Value::Null),
            seq: 0,
            deleted: false,
        };
        let store = interpret_records(&[r]);
        assert_eq!(store.records.len(), 1);
        assert!(store.object_stores.is_empty());
        assert!(store.records_in("").next().is_some());
    }
}