tetratto-core 17.0.0

The core behind Tetratto
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
use oiseau::config::{Configuration, DatabaseConfig};
use pathbufd::PathBufD;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Result;

/// Security configuration.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SecurityConfig {
    /// If registrations are enabled.
    #[serde(default = "default_security_registration_enabled")]
    pub registration_enabled: bool,
    /// The name of the header which will contain the real IP of the connecting user.
    #[serde(default = "default_real_ip_header")]
    pub real_ip_header: String,
    /// If users require an invite code to register. Invite codes can be generated by supporters.
    #[serde(default = "default_enable_invite_codes")]
    pub enable_invite_codes: bool,
}

fn default_security_registration_enabled() -> bool {
    true
}

fn default_real_ip_header() -> String {
    "CF-Connecting-IP".to_string()
}

fn default_enable_invite_codes() -> bool {
    false
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            registration_enabled: default_security_registration_enabled(),
            real_ip_header: default_real_ip_header(),
            enable_invite_codes: default_enable_invite_codes(),
        }
    }
}

/// Directories configuration.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DirsConfig {
    /// HTML templates directory.
    #[serde(default = "default_dir_templates")]
    pub templates: String,
    /// Static files directory.
    #[serde(default = "default_dir_assets")]
    pub assets: String,
    /// Media (user avatars/banners) files directory.
    #[serde(default = "default_dir_media")]
    pub media: String,
    /// The icons files directory.
    #[serde(default = "default_dir_icons")]
    pub icons: String,
    /// The markdown document files directory.
    #[serde(default = "default_dir_docs")]
    pub docs: String,
    /// The directory which holds your `rustdoc` (`cargo doc`) output. The directory should
    /// exist, but it isn't required to actually have anything in it.
    #[serde(default = "default_dir_rustdoc")]
    pub rustdoc: String,
}

fn default_dir_templates() -> String {
    "html".to_string()
}

fn default_dir_assets() -> String {
    "public".to_string()
}

fn default_dir_media() -> String {
    "media".to_string()
}

fn default_dir_icons() -> String {
    "icons".to_string()
}

fn default_dir_docs() -> String {
    "docs".to_string()
}

fn default_dir_rustdoc() -> String {
    "reference".to_string()
}

impl Default for DirsConfig {
    fn default() -> Self {
        Self {
            templates: default_dir_templates(),
            assets: default_dir_assets(),
            media: default_dir_media(),
            icons: default_dir_icons(),
            docs: default_dir_docs(),
            rustdoc: default_dir_rustdoc(),
        }
    }
}

impl Configuration for Config {
    fn db_config(&self) -> DatabaseConfig {
        self.database.to_owned()
    }
}

/// Policies config (TOS/privacy)
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct PoliciesConfig {
    /// The link to your terms of service page.
    /// This is relative to `/auth/register` on the site.
    ///
    /// If your TOS is an HTML file located in `./public`, you can put
    /// `/public/tos.html` here (or something).
    pub terms_of_service: String,
    /// The link to your privacy policy page.
    /// This is relative to `/auth/register` on the site.
    ///
    /// Same deal as terms of service page.
    pub privacy: String,
    /// The time (in ms since unix epoch) in which the site's policies last updated.
    ///
    /// This is required to automatically ask users to re-consent to policies.
    ///
    /// In user whose consent time in LESS THAN this date will be shown a dialog to re-consent to the policies.
    ///
    /// You can get this easily by running `echo "console.log(new Date().getTime())" | node`.
    #[serde(default)]
    pub last_updated: usize,
}

impl Default for PoliciesConfig {
    fn default() -> Self {
        Self {
            terms_of_service: "/public/tos.html".to_string(),
            privacy: "/public/privacy.html".to_string(),
            last_updated: 0,
        }
    }
}

/// Cloudflare Turnstile configuration
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct TurnstileConfig {
    pub site_key: String,
    pub secret_key: String,
}

impl Default for TurnstileConfig {
    fn default() -> Self {
        Self {
            site_key: "1x00000000000000000000AA".to_string(), // always passing, visible
            secret_key: "1x0000000000000000000000000000000AA".to_string(), // always passing
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct ConnectionsConfig {
    /// <https://developer.spotify.com/documentation/web-api>
    #[serde(default)]
    pub spotify_client_id: Option<String>,
    /// <https://www.last.fm/api/authspec>
    #[serde(default)]
    pub last_fm_key: Option<String>,
    /// <https://www.last.fm/api/authspec>
    #[serde(default)]
    pub last_fm_secret: Option<String>,
}

/// Configuration for Stripe integration.
///
/// User IDs are sent to Stripe through the payment link.
/// <https://docs.stripe.com/payment-links/url-parameters#streamline-reconciliation-with-a-url-parameter>
///
/// # Testing
///
/// - Run `stripe login` using the Stripe CLI
/// - Run `stripe listen --forward-to localhost:4118/api/v1/service_hooks/stripe`
/// - Use testing card numbers: <https://docs.stripe.com/testing?testing-method=card-numbers#visa>
#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct StripeConfig {
    /// Your Stripe API secret.
    pub secret: String,
    /// Payment links from the Stripe dashboard.
    ///
    /// 1. Create a product and set the price for your membership
    /// 2. Set the product price to a recurring subscription
    /// 3. Create a payment link for the new product
    /// 4. The payment link pasted into this config field should NOT include a query string
    pub payment_links: StripePaymentLinks,
    /// To apply benefits to user accounts, you should then go into the Stripe developer
    /// "workbench" and create a new webhook. The webhook needs the scopes:
    /// `invoice.payment_succeeded`, `customer.subscription.deleted`, `checkout.session.completed`, `charge.succeeded`.
    ///
    /// The webhook's destination address should be `{your server origin}/api/v1/service_hooks/stripe`.
    ///
    /// The signing secret can be found on the right after you have created the webhook.
    pub webhook_signing_secret: String,
    /// The URL of your customer billing portal.
    ///
    /// <https://docs.stripe.com/no-code/customer-portal>
    pub billing_portal_url: String,
    /// The text representation of prices. (like `$4 USD`)
    pub price_texts: StripePriceTexts,
    /// Product IDs from the Stripe dashboard.
    ///
    /// These are checked when we receive a webhook to ensure we provide the correct product.
    pub product_ids: StripeProductIds,
    /// The IDs of individual prices for products which require us to generate sessions ourselves.
    pub price_ids: StripePriceIds,
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct StripePriceTexts {
    pub supporter: String,
    pub dev_pass: String,
    pub coins_100: String,
    pub coins_400: String,
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct StripePaymentLinks {
    pub supporter: String,
    pub dev_pass: String,
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct StripeProductIds {
    pub supporter: String,
    pub dev_pass: String,
    pub coins_100: String,
    pub coins_400: String,
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct StripePriceIds {
    pub coins_100: String,
    pub coins_400: String,
}

/// Manuals config (search help, etc)
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ManualsConfig {
    /// The page shown for help with search syntax.
    pub search_help: String,
}

impl Default for ManualsConfig {
    fn default() -> Self {
        Self {
            search_help: "".to_string(),
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ServiceHostsConfig {
    /// Buckets host <https://trisua.com/t/buckets>.
    pub buckets: String,
    /// Littleweb browser host.
    #[serde(default)]
    pub littleweb: String,
    /// Tawny host <https://trisua.com/t/tawny>.
    #[serde(default)]
    pub tawny: String,
}

impl Default for ServiceHostsConfig {
    fn default() -> Self {
        Self {
            buckets: String::new(),
            littleweb: String::new(),
            tawny: String::new(),
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum StringBan {
    /// An exact string.
    String(String),
    /// A unicode codepoint.
    Unicode(u32),
}

impl Default for StringBan {
    fn default() -> Self {
        Self::String(String::new())
    }
}

/// Configuration file
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Config {
    /// The name of the app.
    #[serde(default = "default_name")]
    pub name: String,
    /// The description of the app.
    #[serde(default = "default_description")]
    pub description: String,
    /// The theme color of the app.
    #[serde(default = "default_color")]
    pub color: String,
    /// The port to serve the server on.
    #[serde(default = "default_port")]
    pub port: u16,
    /// A list of hosts which cannot be proxied through the image proxy.
    ///
    /// They will return the default banner image instead of proxying.
    ///
    /// It is recommended to put the host of your own public server in this list in
    /// order to prevent a way too easy DOS.
    #[serde(default = "default_banned_hosts")]
    pub banned_hosts: Vec<String>,
    /// The main public host of the server. **Not** used to check against banned hosts,
    /// so this host should be included in there as well.
    #[serde(default = "default_host")]
    pub host: String,
    /// The main public host of the required microservices.
    #[serde(default = "default_service_hosts")]
    pub service_hosts: ServiceHostsConfig,
    /// Database security.
    #[serde(default = "default_security")]
    pub security: SecurityConfig,
    /// The locations where different files should be matched.
    #[serde(default = "default_dirs")]
    pub dirs: DirsConfig,
    /// Database configuration.
    #[serde(default = "default_database")]
    pub database: DatabaseConfig,
    /// A list of files (just their name, no full path) which are NOT updated to match the
    /// version built with the server binary.
    #[serde(default = "default_no_track")]
    pub no_track: Vec<String>,
    /// A list of usernames which cannot be used. This also includes community names.
    #[serde(default = "default_banned_usernames")]
    pub banned_usernames: Vec<String>,
    /// Configuration for your site's policies (terms of service, privacy).
    #[serde(default = "default_policies")]
    pub policies: PoliciesConfig,
    /// Configuration for Cloudflare Turnstile.
    #[serde(default = "default_turnstile")]
    pub turnstile: TurnstileConfig,
    /// The ID of the "town square" community. This community is required to allow
    /// people to post from their profiles.
    ///
    /// This community **must** have open write access.
    #[serde(default)]
    pub town_square: usize,
    /// The ID of the town square forum community.
    #[serde(default)]
    pub town_square_forum: usize,
    /// The ID of the topic within the town square forum community that users are prompted
    /// to post in by default. This should be some sort of "general" topic.
    #[serde(default)]
    pub town_square_forum_topic: usize,
    /// The ID of the "system" user which will send system mails to users.
    #[serde(default)]
    pub system_user: usize,
    #[serde(default)]
    pub connections: ConnectionsConfig,
    /// The path to the HTML footer file. The contents of this file are embedded
    /// into every HTML template. They support access to template fields like `{{ user }}`.
    #[serde(default)]
    pub html_footer_path: String,
    #[serde(default)]
    pub stripe: Option<StripeConfig>,
    /// The relative paths to manuals.
    #[serde(default)]
    pub manuals: ManualsConfig,
    /// A list of banned content in posts.
    #[serde(default)]
    pub banned_data: Vec<StringBan>,
    /// If user ads are enabled.
    #[serde(default)]
    pub enable_user_ads: bool,
}

fn default_name() -> String {
    "Tetratto".to_string()
}

fn default_description() -> String {
    "🐇 tetratto!".to_string()
}

fn default_color() -> String {
    "#c9b1bc".to_string()
}
fn default_port() -> u16 {
    4118
}

fn default_banned_hosts() -> Vec<String> {
    Vec::new()
}

fn default_host() -> String {
    String::new()
}

fn default_service_hosts() -> ServiceHostsConfig {
    ServiceHostsConfig::default()
}

fn default_security() -> SecurityConfig {
    SecurityConfig::default()
}

fn default_dirs() -> DirsConfig {
    DirsConfig::default()
}

fn default_database() -> DatabaseConfig {
    DatabaseConfig::default()
}

fn default_no_track() -> Vec<String> {
    Vec::new()
}

fn default_banned_usernames() -> Vec<String> {
    vec![
        "admin".to_string(),
        "owner".to_string(),
        "moderator".to_string(),
        "api".to_string(),
        "communities".to_string(),
        "community".to_string(),
        "notifs".to_string(),
        "notification".to_string(),
        "post".to_string(),
        "void".to_string(),
        "anonymous".to_string(),
        "stacks".to_string(),
        "stack".to_string(),
        "search".to_string(),
        "journals".to_string(),
        "links".to_string(),
        "app".to_string(),
        "services".to_string(),
        "domains".to_string(),
        "mail".to_string(),
        "product".to_string(),
        "wallet".to_string(),
        "products".to_string(),
    ]
}

fn default_policies() -> PoliciesConfig {
    PoliciesConfig::default()
}

fn default_turnstile() -> TurnstileConfig {
    TurnstileConfig::default()
}

fn default_connections() -> ConnectionsConfig {
    ConnectionsConfig::default()
}

fn default_manuals() -> ManualsConfig {
    ManualsConfig::default()
}

fn default_banned_data() -> Vec<StringBan> {
    Vec::new()
}

impl Default for Config {
    fn default() -> Self {
        Self {
            name: default_name(),
            description: default_description(),
            color: default_color(),
            port: default_port(),
            banned_hosts: default_banned_hosts(),
            host: default_host(),
            service_hosts: default_service_hosts(),
            database: default_database(),
            security: default_security(),
            dirs: default_dirs(),
            no_track: default_no_track(),
            banned_usernames: default_banned_usernames(),
            policies: default_policies(),
            turnstile: default_turnstile(),
            town_square: 0,
            town_square_forum: 0,
            town_square_forum_topic: 0,
            system_user: 0,
            connections: default_connections(),
            html_footer_path: String::new(),
            stripe: None,
            manuals: default_manuals(),
            banned_data: default_banned_data(),
            enable_user_ads: false,
        }
    }
}

impl Config {
    /// Read configuration file into [`Config`]
    pub fn read(contents: String) -> Self {
        toml::from_str::<Self>(&contents).unwrap()
    }

    /// Pull configuration file
    pub fn get_config() -> Self {
        let path = PathBufD::current().join("tetratto.toml");

        match fs::read_to_string(&path) {
            Ok(c) => Config::read(c),
            Err(_) => {
                Self::update_config(Self::default()).expect("failed to write default config");
                Self::default()
            }
        }
    }

    /// Update configuration file
    pub fn update_config(contents: Self) -> Result<()> {
        let c = fs::canonicalize(".").unwrap();
        let here = c.to_str().unwrap();

        fs::write(
            format!("{here}/tetratto.toml"),
            toml::to_string_pretty::<Self>(&contents).unwrap(),
        )
    }
}