discord_desktop_core/lib.rs
1//! Discord **desktop** (Electron/Chromium) artifact reader.
2//!
3//! Discord is an Electron app: its account/session state lives in Chromium
4//! **Local Storage** (a per-profile LevelDB at `Local Storage/leveldb/`), not in a
5//! chat database — Discord keeps **no local message DB** (messages are fetched
6//! from the server and only cached). This crate sits on top of the Wave-2
7//! [`chromium_storage_localstorage`] reader and interprets the Discord-specific
8//! records inside it:
9//!
10//! * the auth **`token`** record — a session credential, surfaced as a
11//! [`token::TokenRecord`] whose value is a [`token::SensitiveToken`] that
12//! **redacts by default** (presence + length + location, never the secret in
13//! `Debug`/`Display`/serde output);
14//! * **account identity** — the `MultiAccountStore` / `user_id_cache` /
15//! `email_cache` records, parsed into [`account::Account`];
16//! * **recent channels / guilds** — the `SelectedGuildStore` /
17//! `RecentVoiceChannelStore` records, parsed into [`channel::RecentChannel`].
18//!
19//! The Discord store paths and the Chromium Local Storage key/encoding constants
20//! come from the fleet KNOWLEDGE leaf [`forensicnomicon_core::messenger_desktop`]
21//! / [`forensicnomicon_core::chromium_local_storage`] — this crate re-uses them
22//! and never re-hardcodes a path or a marker byte.
23//!
24//! # Sources
25//!
26//! - AhnLab ASEC, *Distribution of Infostealer Made with Electron* — the Discord
27//! `Local Storage\leveldb` token store and the `discordptb`/`discordcanary`
28//! variants: <https://asec.ahnlab.com/en/24512/>
29//! - forensafe, *Investigating Discord*: <https://www.forensafe.com/blogs/discord.html>
30//! - Discord snowflake ID epoch (2015-01-01): <https://discord.com/developers/docs/reference#snowflakes>
31#![forbid(unsafe_code)]
32#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
33
34pub mod account;
35pub mod channel;
36pub mod error;
37pub mod timeline;
38pub mod token;
39
40pub use account::Account;
41pub use channel::RecentChannel;
42pub use error::Error;
43pub use token::TokenRecord;
44
45use chromium_storage_localstorage::LocalStorageRecord;
46use forensicnomicon_core::messenger_desktop::{self, StoreRole};
47use forensicnomicon_core::report::TimelineEvent;
48use serde::Serialize;
49use std::path::Path;
50
51/// The canonical app name for the Discord messenger spec in the KNOWLEDGE leaf.
52const DISCORD_APP: &str = "Discord";
53
54/// Does this Local Storage origin belong to Discord?
55///
56/// Matches the stable client (`https://discord.com`) and the test-build variants
57/// (`https://ptb.discord.com`, `https://canary.discord.com`) by the shared
58/// `discord.com` host — the general rule, not one hardcoded origin.
59#[must_use]
60pub fn is_discord_origin(origin: &str) -> bool {
61 origin.contains("discord.com")
62}
63
64/// A per-origin Local Storage metadata record (`META:`) — the store's declared
65/// size and its last-modified time.
66#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
67pub struct OriginMeta {
68 /// The Discord origin this metadata describes.
69 pub origin: String,
70 /// Last-modified time as Unix milliseconds (decoded from WebKit µs), when
71 /// representable.
72 pub last_modified_unix_ms: Option<u64>,
73 /// Declared store size in bytes, if the record carried it.
74 pub size: Option<u64>,
75 /// LevelDB sequence number.
76 pub seq: u64,
77}
78
79/// Extract per-origin `META:` metadata for Discord origins.
80#[must_use]
81pub fn extract_origin_meta(records: &[LocalStorageRecord]) -> Vec<OriginMeta> {
82 records
83 .iter()
84 .filter_map(|record| match record {
85 LocalStorageRecord::Meta {
86 origin,
87 timestamp_webkit_micros,
88 size,
89 seq,
90 deleted: false,
91 } if is_discord_origin(origin) => Some(OriginMeta {
92 origin: origin.clone(),
93 last_modified_unix_ms: timeline::webkit_micros_to_unix_ms(*timestamp_webkit_micros),
94 size: *size,
95 seq: *seq,
96 }),
97 _ => None,
98 })
99 .collect()
100}
101
102/// Everything the reader recovered from a Discord Local Storage store.
103///
104/// A missing or malformed individual record degrades to an empty vec (the store
105/// open in [`read_profile`] is the only fail-loud point).
106#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
107pub struct DiscordArtifacts {
108 /// Auth-token records (secret redacted by default). Superseded versions and
109 /// tombstones surface too.
110 pub tokens: Vec<TokenRecord>,
111 /// Recovered account identities.
112 pub accounts: Vec<Account>,
113 /// Recent guild / voice-channel references.
114 pub recents: Vec<RecentChannel>,
115 /// Per-origin store metadata (last-modified time / size).
116 pub origins: Vec<OriginMeta>,
117}
118
119impl DiscordArtifacts {
120 /// The ascending timeline reconstructed from these artifacts (snowflake
121 /// creation times + per-origin last-modified times).
122 #[must_use]
123 pub fn timeline(&self) -> Vec<TimelineEvent> {
124 timeline::build_timeline(self)
125 }
126}
127
128/// Interpret already-decoded Local Storage records into typed Discord artifacts.
129///
130/// Pure and I/O-free — the counterpart to [`read_profile`] for callers that
131/// already hold records from the [`chromium_storage_localstorage`] reader.
132#[must_use]
133pub fn decode_local_storage(records: &[LocalStorageRecord]) -> DiscordArtifacts {
134 DiscordArtifacts {
135 tokens: token::extract_tokens(records),
136 accounts: account::extract_accounts(records),
137 recents: channel::extract_recent_channels(records),
138 origins: extract_origin_meta(records),
139 }
140}
141
142/// Read and interpret a Discord desktop **profile directory** (the Electron
143/// `userData` dir, e.g. `~/Library/Application Support/discord`).
144///
145/// The Local Storage sub-path comes from the fleet KNOWLEDGE leaf
146/// ([`messenger_desktop`]'s `Discord` Account store), never a hardcoded literal.
147/// A failure to open the LevelDB is a **loud, typed error** (bootstrap failure);
148/// an absent/empty store is not — it yields empty artifacts.
149pub fn read_profile(profile_dir: &Path) -> Result<DiscordArtifacts, Error> {
150 let spec = messenger_desktop::spec(DISCORD_APP).ok_or(Error::SpecMissing)?;
151 let store = spec
152 .store(StoreRole::Account)
153 .ok_or(Error::StoreMissing("Account"))?;
154
155 // `relative_path` is forward-slash separated for OS neutrality; join each
156 // component so it resolves natively on Windows too.
157 let mut leveldb_dir = profile_dir.to_path_buf();
158 for component in store.relative_path.split('/') {
159 leveldb_dir.push(component);
160 }
161
162 let records = chromium_storage_localstorage::read_dir(&leveldb_dir)?;
163 Ok(decode_local_storage(&records))
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169 use chromium_storage_localstorage::{Encoding, StorageValue};
170
171 fn sv(text: &str) -> StorageValue {
172 StorageValue {
173 text: text.to_string(),
174 raw: text.as_bytes().to_vec(),
175 encoding: Encoding::Latin1,
176 lossy: false,
177 }
178 }
179
180 fn data(key: &str, value: &str) -> LocalStorageRecord {
181 LocalStorageRecord::Data {
182 origin: "https://ptb.discord.com".to_string(),
183 script_key: sv(key),
184 value: sv(value),
185 seq: 1,
186 deleted: false,
187 }
188 }
189
190 const MULTI: &str = r#"{"_state":{"users":[{"id":"700000000000000000","username":"testuser","discriminator":"0","avatar":"a","tokenStatus":2}]}}"#;
191
192 fn sample_records() -> Vec<LocalStorageRecord> {
193 vec![
194 data("token", "MTk4NjIyNDgzNDcxOTI1MjQ4.fake.synthetic"),
195 data("MultiAccountStore", MULTI),
196 data(
197 "SelectedGuildStore",
198 r#"{"selectedGuildId":"81384788765712384"}"#,
199 ),
200 LocalStorageRecord::Meta {
201 origin: "https://ptb.discord.com".to_string(),
202 timestamp_webkit_micros: timeline::WEBKIT_EPOCH_OFFSET_MICROS
203 + 1_600_000_000_000_000,
204 size: Some(4096),
205 seq: 99,
206 deleted: false,
207 },
208 ]
209 }
210
211 #[test]
212 fn decode_aggregates_all_artifact_classes() {
213 let artifacts = decode_local_storage(&sample_records());
214 assert_eq!(artifacts.tokens.len(), 1, "token");
215 assert_eq!(artifacts.accounts.len(), 1, "account");
216 assert_eq!(artifacts.recents.len(), 1, "recent");
217 assert_eq!(artifacts.origins.len(), 1, "origin meta");
218 assert_eq!(artifacts.accounts[0].username.as_deref(), Some("testuser"));
219 }
220
221 #[test]
222 fn timeline_is_sorted_and_dated() {
223 let artifacts = decode_local_storage(&sample_records());
224 let events = artifacts.timeline();
225 // One snowflake-creation event + one origin last-modified event.
226 assert_eq!(events.len(), 2);
227 assert!(
228 events.iter().all(|e| e.when.is_some()),
229 "all events datable"
230 );
231 let whens: Vec<_> = events.iter().filter_map(|e| e.when.clone()).collect();
232 let mut sorted = whens.clone();
233 sorted.sort();
234 assert_eq!(whens, sorted, "ascending by time");
235 }
236
237 #[test]
238 fn read_profile_missing_store_errors_loud() {
239 // A path with no Local Storage/leveldb is a bootstrap failure, not empty.
240 let dir = std::path::Path::new("/nonexistent/discord/profile");
241 assert!(matches!(read_profile(dir), Err(Error::LocalStorage(_))));
242 }
243}