darkwing/database/browser_profile/
repository.rs

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
//! Database repository implementations for browser profile and proxy
//! related operations. This module provides traits and implementations for
//! accessing and manipulating browser profile and proxy data in the
//! database.

use std::sync::Arc;

use anyhow::Context;
use async_trait::async_trait;
use mockall::automock;
use sqlx::{query, query_as};
use tracing::debug;

use crate::database::browser_profile::{Bookmark, Extension};
use crate::database::Database;
use crate::server::dtos::browser_profile_dto::MiniBrowserProfile;

use super::{
  BrowserProfilePreliminary, BrowserProfileWithFingerprint, Homepage,
  MainWebsite, Proxy,
};

/// Browser profile repository type alias.
pub type DynBrowserProfileRepository =
  Arc<dyn BrowserProfileRepository + Send + Sync>;

/// Proxy repository type alias.
pub type DynProxyRepository = Arc<dyn ProxyRepository + Send + Sync>;

/// Repository trait defining operations for browser profile data access.
/// Provides methods to retrieve and update browser profile related information.
#[automock]
#[async_trait]
pub trait BrowserProfileRepository {
  /// Retrieves minimal browser profile information by ID.
  async fn get_mini_by_id(&self, id: i64)
    -> anyhow::Result<MiniBrowserProfile>;

  /// Retrieves preliminary browser profile data by ID.
  /// This includes basic profile information without full fingerprint details.
  async fn get_preliminary_by_id(
    &self,
    id: i64,
  ) -> anyhow::Result<BrowserProfilePreliminary>;

  /// Retrieves complete browser profile information including fingerprint data
  /// by ID.
  async fn get_by_id_with_fingerprint(
    &self,
    id: i64,
  ) -> anyhow::Result<BrowserProfileWithFingerprint>;

  /// Retrieves all homepages associated with a browser profile ID.
  async fn get_homepages_by_browser_profile_id(
    &self,
    id: i64,
  ) -> anyhow::Result<Vec<Homepage>>;

  /// Retrieves bookmarks filtered by user ID, team ID and main website.
  async fn get_bookmarks(
    &self,
    user_id: i64,
    team_id: i64,
    main_website: MainWebsite,
  ) -> anyhow::Result<Vec<Bookmark>>;

  /// Retrieves extensions available to a user based on user ID and team ID.
  async fn get_extensions(
    &self,
    user_id: i64,
    team_id: i64,
  ) -> anyhow::Result<Vec<Extension>>;

  /// Updates or inserts the datadir hash for a browser profile.
  async fn update_datadir_hash(
    &self,
    id: i64,
    hash: String,
  ) -> anyhow::Result<()>;

  /// Checks if a browser profile has a pending transfer.
  async fn is_pending_transfer(
    &self,
    browser_profile_id: i64,
  ) -> anyhow::Result<bool>;
}

#[async_trait]
impl BrowserProfileRepository for Database {
  async fn get_mini_by_id(
    &self,
    id: i64,
  ) -> anyhow::Result<MiniBrowserProfile> {
    sqlx::query_as(
      r#"
      SELECT `browser_profiles`.id,
             `browser_profiles`.userId as user_id,
             `browser_profiles`.teamId as team_id,
             `browser_profiles`.created_at,
             `browser_profiles_hashes`.datadirHash as datadir_hash
      FROM `browser_profiles`
      LEFT JOIN `browser_profiles_hashes` ON `browser_profiles_hashes`.`browserProfileId` = `browser_profiles`.`id`
      WHERE `browser_profiles`.`id` = ?
      "#,
    )
    .bind(id)
    .fetch_one(&self.pool)
    .await
    .context("browser profile was not found")
  }

  async fn get_preliminary_by_id(
    &self,
    id: i64,
  ) -> anyhow::Result<BrowserProfilePreliminary> {
    let mut browser_profile: BrowserProfilePreliminary = sqlx::query_as(
      r#"
      SELECT `browser_profiles`.id,
             `browser_profiles`.created_at,
             `browser_profiles`.name,
             `browser_profiles`.mainWebsite,
             `browser_profiles`.proxyId,
             `browser_profiles`.login,
             `browser_profiles`.password
      FROM `browser_profiles`
      WHERE `browser_profiles`.`id` = ?
      "#,
    )
    .bind(id)
    .fetch_one(&self.pool)
    .await
    .context("browser profile was not found")?;

    if browser_profile.proxy_id == Some(0) {
      browser_profile.proxy_id = None;
    }

    Ok(browser_profile)
  }

  async fn get_by_id_with_fingerprint(
    &self,
    id: i64,
  ) -> anyhow::Result<BrowserProfileWithFingerprint> {
    sqlx::query_as(
            r#"
            SELECT `browser_profiles`.id,
                   `browser_profiles`.userId,
                   `browser_profiles`.teamId,
                   `browser_profiles`.name,
                   `browser_profiles`.mainWebsite,
                   `browser_profiles`.platform,
                   `browser_profiles`.browserType,
                   `browser_profiles`.proxyId,
                   `browser_profiles`.useragent,
                   `browser_profiles`.webrtc,
                   `browser_profiles`.canvas,
                   `browser_profiles`.webgl,
                   `browser_profiles`.webglInfo,
                   `browser_profiles`.clientRect,
                   `browser_profiles`.notes,
                   `browser_profiles`.timezone,
                   `browser_profiles`.locale,
                   `browser_profiles`.userFields,
                   `browser_profiles`.geolocation,
                   `browser_profiles`.doNotTrack,
                   `browser_profiles`.args,
                   `browser_profiles`.cpu,
                   `browser_profiles`.memory,
                   `browser_profiles`.screen,
                   `browser_profiles`.ports,
                   `browser_profiles`.tabs,
                   `browser_profiles`.deleted_at,
                   `browser_profiles`.cpuArchitecture,
                   `browser_profiles`.osVersion,
                   `browser_profiles`.screenWidth,
                   `browser_profiles`.screenHeight,
                   `browser_profiles`.connectionDownlink,
                   `browser_profiles`.connectionEffectiveType,
                   `browser_profiles`.connectionRtt,
                   `browser_profiles`.connectionSaveData,
                   `browser_profiles`.vendorSub,
                   `browser_profiles`.productSub,
                   `browser_profiles`.vendor,
                   `browser_profiles`.product,
                   `browser_profiles`.appCodeName,
                   `browser_profiles`.mediaDevices,
                   `browser_profiles_hashes`.datadirHash,
                   `browser_profiles`.platformVersion,
                   `browser_profiles`.archived,
                   `browser_profiles`.webgl2Maximum,
                   `browser_profiles`.login,
                   `browser_profiles`.password,
                   `browser_profiles`.created_at,
                   `browser_profile_tabs`.tabs as `browser_profile_tabs`,
                   `browser_profiles_webgpu`.webgpu as `webgpu`,
                   `browser_profile_details`.isHiddenProfileName as `isHiddenProfileName`
            FROM `browser_profiles`
            LEFT JOIN `browser_profile_tabs` ON `browser_profile_tabs`.`browserProfileId` = `browser_profiles`.`id` 
            LEFT JOIN `browser_profile_storage_path` ON `browser_profile_storage_path`.`browserProfileId` = `browser_profiles`.`id` 
            LEFT JOIN `browser_profile_details` ON `browser_profile_details`.`browserProfileId` = `browser_profiles`.`id` 
            LEFT JOIN `browser_profiles_webgpu` ON `browser_profiles_webgpu`.`browserProfileId` = `browser_profiles`.`id` 
            LEFT JOIN `browser_profiles_hashes` ON `browser_profiles_hashes`.`browserProfileId` = `browser_profiles`.`id`
            LEFT JOIN `settings` ON `settings`.`teamId` = `browser_profiles`.`teamId`
            WHERE `browser_profiles`.`id` = ? 
            AND `browser_profiles`.`archived` <> 1
            LIMIT 1;
            "#,
        )
        .bind(id)
        .fetch_one(&self.pool)
            .await
            .context("browser profile was not found")
  }

  async fn get_homepages_by_browser_profile_id(
    &self,
    id: i64,
  ) -> anyhow::Result<Vec<Homepage>> {
    query_as!(
      Homepage,
      r#"
      SELECT `name`, `url`, `sharedToEntireTeam`, `mainWebsite`, `isGlobal`
      FROM homepages
      WHERE id IN (
        SELECT homepageId
        FROM browser_profile_homepages
        WHERE profileId = ?
      );
      "#,
      id
    )
    .fetch_all(&self.pool)
    .await
    .context("homepages was not found")
  }

  async fn get_bookmarks(
    &self,
    user_id: i64,
    team_id: i64,
    main_website: MainWebsite,
  ) -> anyhow::Result<Vec<Bookmark>> {
    let main_website: String = main_website.into();

    debug!(
      r#"
    SELECT name, deletedUrl, mainWebsite, urlCrypt, cryptoKeyId 
        FROM bookmarks 
        WHERE (
          ({main_website} = '' AND (mainWebsite LIKE '%all%' OR mainWebsite like '%none%'))
          OR 
          ({main_website} != '' AND (mainWebsite LIKE CONCAT('%', {main_website}, '%') OR mainWebsite LIKE '%all%'))
        )
        AND (userId = {user_id} OR (teamId = {team_id} AND sharedToEntireTeam = 1))
        AND deleted_at IS NULL
        "#,
      main_website = main_website,
      user_id = user_id,
      team_id = team_id
    );

    query_as!(
      Bookmark,
      r#"
        SELECT name, deletedUrl, mainWebsite, urlCrypt, cryptoKeyId 
        FROM bookmarks 
        WHERE (
          (? = '' AND (mainWebsite LIKE '%all%' OR mainWebsite like '%none%'))
          OR 
          (? != '' AND (mainWebsite LIKE CONCAT('%', ?, '%') OR mainWebsite LIKE '%all%'))
        )
        AND (userId = ? OR (teamId = ? AND sharedToEntireTeam = 1))
        AND deleted_at IS NULL
        "#,
      main_website,
      main_website,
      main_website,
      user_id,
      team_id
    )
    .fetch_all(&self.pool)
    .await
    .context("failed to fetch bookmarks")
  }

  async fn get_extensions(
    &self,
    user_id: i64,
    team_id: i64,
  ) -> anyhow::Result<Vec<Extension>> {
    query_as!(
      Extension,
      r#"SELECT extensionId as extension_id, url, name, type, hash FROM extensions WHERE (userId = ? or (teamId = ? and sharedToEntireTeam = 1)) and deleted_at IS NULL"#,
      user_id,
      team_id
    )
    .fetch_all(&self.pool)
    .await
    .context("failed to fetch extensions")
  }

  async fn update_datadir_hash(
    &self,
    id: i64,
    hash: String,
  ) -> anyhow::Result<()> {
    let update_result = sqlx::query!(
      r#"
      UPDATE `browser_profiles_hashes` 
      SET `datadirHash` = ?
      WHERE `browserProfileId` = ?
      "#,
      hash,
      id
    )
    .execute(&self.pool)
    .await
    .context("failed to update datadir hash")?;

    if update_result.rows_affected() == 0 {
      sqlx::query!(
        r#"
        INSERT INTO `browser_profiles_hashes` (`datadirHash`, `browserProfileId`)
        VALUES (?, ?)
        "#,
        hash,
        id
      )
      .execute(&self.pool)
      .await
      .context("failed to insert datadir hash")?;
    }

    Ok(())
  }

  async fn is_pending_transfer(&self, id: i64) -> anyhow::Result<bool> {
    query!(
      r#"SELECT `id` FROM `browser_profile_transfers` WHERE `browserProfileId` = ? and status = 'pending'"#,
      id
    )
    .fetch_optional(&self.pool)
    .await
    .map(|transfer| transfer.is_some())
    .context("failed to check if browser profile is pending transfer")
  }
}

/// Repository trait defining operations for proxy data access.
/// Provides methods to retrieve proxy information.
#[automock]
#[async_trait]
pub trait ProxyRepository {
  /// Retrieves proxy information by ID if it exists and is not deleted.
  async fn maybe_get_by_id(&self, id: i64) -> anyhow::Result<Option<Proxy>>;
}

#[async_trait]
impl ProxyRepository for Database {
  async fn maybe_get_by_id(&self, id: i64) -> anyhow::Result<Option<Proxy>> {
    query_as!(
      Proxy,
      r#"
             SELECT `id`, `type`, `host`, `deletedPort`, `deletedLogin`, `password`, `loginCrypt`, `passwordCrypt`, `portCrypt`, `cryptoKeyId`, `changeIpUrl`, `changeIpUrlCrypt`
             FROM proxy
              WHERE id = ?
              AND deleted_at IS NULL
              "#,
      id
    )
    .fetch_optional(&self.pool)
    .await
    .context("proxy was not found")
  }
}