rustpbx 0.4.4

A SIP PBX implementation in Rust
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
use crate::config::Config;
use crate::console::ConsoleState;
use crate::console::middleware::AuthRequired;
use axum::{
    Router,
    extract::{Json, Path, State},
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    routing::{get, post},
};
use serde::Deserialize;
use serde_json::json;
use std::fs;
use std::sync::Arc;
use toml_edit::{Array, DocumentMut, Item, Table, Value};

pub fn urls() -> Router<Arc<ConsoleState>> {
    let router = Router::new()
        .route("/addons", get(index))
        .route("/addons/{id}", get(detail));

    // License verification endpoint is commerce-only.
    #[cfg(feature = "commerce")]
    let router = router.route("/addons/verify", post(verify_addon));

    router
}

pub fn api_urls() -> Router<Arc<ConsoleState>> {
    Router::new().route("/addons/toggle", post(toggle_addon))
}

pub async fn index(
    State(state): State<Arc<ConsoleState>>,
    headers: HeaderMap,
    AuthRequired(user): AuthRequired,
) -> impl IntoResponse {
    // Permission check - system:read required for addon management
    if !state.has_permission(&user, "system", "read").await {
        return (StatusCode::FORBIDDEN, "Permission denied").into_response();
    }

    let addons = if let Some(app_state) = state.app_state() {
        // Try to load config from disk to get the latest state
        let config = if let Some(path) = &app_state.config_path {
            match fs::read_to_string(path) {
                Ok(content) => toml::from_str::<Config>(&content)
                    .unwrap_or_else(|_| (**app_state.config()).clone()),
                Err(_) => (**app_state.config()).clone(),
            }
        } else {
            (**app_state.config()).clone()
        };

        let mut list = app_state.addon_registry.list_addons(app_state.clone());
        for addon in &mut list {
            let enabled_in_disk = app_state.addon_registry.is_enabled(&addon.id, &config);
            let enabled_in_mem = app_state
                .addon_registry
                .is_enabled(&addon.id, app_state.config());

            addon.enabled = enabled_in_disk;
            addon.restart_required = enabled_in_disk != enabled_in_mem;

            // Populate license status from the startup-time cache (no network call).
            #[cfg(feature = "commerce")]
            if addon.category == crate::addons::AddonCategory::Commercial {
                if let Some(status) = crate::license::get_license_status(&addon.id) {
                    addon.license_status = Some(license_status_label(&status));
                    addon.license_expiry = status.expiry.clone();
                    addon.license_plan = if status.plan.is_empty() {
                        None
                    } else {
                        Some(status.plan.clone())
                    };
                } else {
                    // Startup check hasn't run or this addon wasn't checked.
                    addon.license_status = Some("Unknown".to_string());
                }
            }
        }
        list
    } else {
        vec![]
    };

    // Commerce-only: license banner and license rows.
    #[cfg(feature = "commerce")]
    let has_unlicensed_commercial = addons.iter().any(|a| {
        a.category == crate::addons::AddonCategory::Commercial
            && a.license_status.as_deref() != Some("Valid")
    });
    #[cfg(not(feature = "commerce"))]
    let has_unlicensed_commercial = false;

    #[cfg(feature = "commerce")]
    let licenses = super::licenses::build_license_rows(&state);
    #[cfg(not(feature = "commerce"))]
    let licenses: Vec<super::licenses::LicenseRow> = vec![];

    // Tell the template whether commerce features are available.
    #[cfg(feature = "commerce")]
    let commerce_enabled = true;
    #[cfg(not(feature = "commerce"))]
    let commerce_enabled = false;

    let current_user = state.build_current_user_ctx(&user).await;

    state.render_with_headers(
        "console/addons.html",
        serde_json::json!({
            "addons": addons,
            "has_unlicensed_commercial": has_unlicensed_commercial,
            "licenses": licenses,
            "commerce_enabled": commerce_enabled,
            "page_title": "Addons",
            "nav_active": "addons",
            "current_user": current_user,
        }),
        &headers,
    )
}

/// `POST /addons/verify` — kept for backward compatibility; delegates to the
/// licenses verify handler which no longer requires an addon ID.
#[cfg(feature = "commerce")]
pub async fn verify_addon(
    State(state): State<Arc<ConsoleState>>,
    AuthRequired(user): AuthRequired,
    Json(payload): Json<serde_json::Value>,
) -> Response {
    // Permission check - system:write required to verify licenses
    if !state.has_permission(&user, "system", "write").await {
        return (StatusCode::FORBIDDEN, "Permission denied").into_response();
    }

    // Extract license_key from the payload regardless of whether the caller
    // also sent an `id` field (old clients may still send it; we ignore it).
    let license_key = payload
        .get("license_key")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .trim()
        .to_string();

    super::licenses::verify_license_key(state, license_key).await
}

#[derive(Deserialize)]
pub struct ToggleAddonPayload {
    id: String,
    enabled: bool,
}

pub async fn toggle_addon(
    State(state): State<Arc<ConsoleState>>,
    AuthRequired(user): AuthRequired,
    Json(payload): Json<ToggleAddonPayload>,
) -> Response {
    // Permission check - system:write required to modify addon state
    if !state.has_permission(&user, "system", "write").await {
        return (StatusCode::FORBIDDEN, "Permission denied").into_response();
    }

    let config_path = match get_config_path(&state) {
        Ok(path) => path,
        Err(resp) => return resp,
    };

    let mut doc = match load_document(&config_path) {
        Ok(doc) => doc,
        Err(resp) => return resp,
    };

    let proxy_table = ensure_table_mut(&mut doc, "proxy");

    // Ensure addons array exists
    if !proxy_table.contains_key("addons") || !proxy_table["addons"].is_array() {
        proxy_table["addons"] = Item::Value(Value::Array(Array::new()));
    }

    let addons_array = proxy_table["addons"].as_array_mut().expect("array");

    if payload.enabled {
        // Add if not exists
        let mut exists = false;
        for i in 0..addons_array.len() {
            if let Some(s) = addons_array.get(i).and_then(|v| v.as_str())
                && s == payload.id
            {
                exists = true;
                break;
            }
        }
        if !exists {
            addons_array.push(payload.id);
        }
    } else {
        // Remove if exists
        let mut index_to_remove = None;
        for i in 0..addons_array.len() {
            if let Some(s) = addons_array.get(i).and_then(|v| v.as_str())
                && s == payload.id
            {
                index_to_remove = Some(i);
                break;
            }
        }
        if let Some(idx) = index_to_remove {
            addons_array.remove(idx);
        }
    }

    let doc_text = doc.to_string();

    // Validate config before saving
    if let Err(resp) = parse_config_from_str(&doc_text) {
        return resp;
    }

    if let Err(resp) = persist_document(&config_path, doc_text) {
        return resp;
    }

    Json(json!({
        "success": true,
        "requires_restart": true,
        "message": "Addon state updated. Restart RustPBX to apply changes."
    }))
    .into_response()
}

pub async fn detail(
    State(state): State<Arc<ConsoleState>>,
    Path(id): Path<String>,
    headers: HeaderMap,
    AuthRequired(user): AuthRequired,
) -> impl IntoResponse {
    // Permission check - system:read required for addon management
    if !state.has_permission(&user, "system", "read").await {
        return (StatusCode::FORBIDDEN, "Permission denied").into_response();
    }

    let addon = if let Some(app_state) = state.app_state() {
        let list = app_state.addon_registry.list_addons(app_state.clone());
        list.into_iter().find(|a| a.id == id)
    } else {
        None
    };

    if let Some(mut addon) = addon {
        if let Some(app_state) = state.app_state() {
            let config = if let Some(path) = &app_state.config_path {
                match fs::read_to_string(path) {
                    Ok(content) => toml::from_str::<Config>(&content)
                        .unwrap_or_else(|_| (**app_state.config()).clone()),
                    Err(_) => (**app_state.config()).clone(),
                }
            } else {
                (**app_state.config()).clone()
            };

            let enabled_in_disk = app_state.addon_registry.is_enabled(&addon.id, &config);
            let enabled_in_mem = app_state
                .addon_registry
                .is_enabled(&addon.id, app_state.config());
            addon.enabled = enabled_in_disk;
            addon.restart_required = enabled_in_disk != enabled_in_mem;

            // Populate license status from the startup-time cache (no network call).
            #[cfg(feature = "commerce")]
            if addon.category == crate::addons::AddonCategory::Commercial {
                if let Some(status) = crate::license::get_license_status(&addon.id) {
                    addon.license_status = Some(license_status_label(&status));
                    addon.license_expiry = status.expiry.clone();
                    addon.license_plan = if status.plan.is_empty() {
                        None
                    } else {
                        Some(status.plan.clone())
                    };
                } else {
                    addon.license_status = Some("Unknown".to_string());
                }
            }
        }

        let current_user = state.build_current_user_ctx(&user).await;

        state.render_with_headers(
            "console/addon_detail.html",
            serde_json::json!({
                "addon": addon,
                "page_title": format!("Addon: {}", addon.name),
                "nav_active": "addons",
                "commerce_enabled": cfg!(feature = "commerce"),
                "current_user": current_user,
            }),
            &headers,
        )
    } else {
        (StatusCode::NOT_FOUND, "Addon not found").into_response()
    }
}

#[allow(clippy::result_large_err)]
pub(super) fn get_config_path(state: &ConsoleState) -> Result<String, Response> {
    let Some(app_state) = state.app_state() else {
        return Err(json_error(
            StatusCode::SERVICE_UNAVAILABLE,
            "Application state is unavailable.",
        ));
    };
    let Some(path) = app_state.config_path.clone() else {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            "Configuration file path is unknown. Start the service with --conf to enable editing.",
        ));
    };
    Ok(path)
}

#[allow(clippy::result_large_err)]
pub(super) fn load_document(path: &str) -> Result<DocumentMut, Response> {
    let contents = match fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(err) => {
            return Err(json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to read configuration file: {}", err),
            ));
        }
    };

    contents.parse::<DocumentMut>().map_err(|err| {
        json_error(
            StatusCode::UNPROCESSABLE_ENTITY,
            format!("Configuration file is not valid TOML: {}", err),
        )
    })
}

#[allow(clippy::result_large_err)]
pub(super) fn persist_document(path: &str, contents: String) -> Result<(), Response> {
    fs::write(path, contents).map_err(|err| {
        json_error(
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to write configuration file: {}", err),
        )
    })
}

#[allow(clippy::result_large_err)]
pub(super) fn parse_config_from_str(contents: &str) -> Result<Config, Response> {
    toml::from_str::<Config>(contents).map_err(|err| {
        json_error(
            StatusCode::UNPROCESSABLE_ENTITY,
            format!("Configuration validation failed: {}", err),
        )
    })
}

fn ensure_table_mut<'doc>(doc: &'doc mut DocumentMut, key: &str) -> &'doc mut Table {
    let needs_init = doc
        .as_table()
        .get(key)
        .map(|item| !item.is_table())
        .unwrap_or(true);

    if needs_init {
        doc.insert(key, Item::Table(Table::new()));
    }

    doc.as_table_mut()
        .get_mut(key)
        .and_then(Item::as_table_mut)
        .expect("table")
}

pub(super) fn json_error(status: StatusCode, message: impl Into<String>) -> Response {
    (
        status,
        Json(json!({
            "success": false,
            "message": message.into(),
        })),
    )
        .into_response()
}

/// Convert a `LicenseStatus` to a human-readable label for the UI.
#[cfg(feature = "commerce")]
fn license_status_label(status: &crate::license::LicenseStatus) -> String {
    if status.is_trial {
        if status.valid {
            format!("Trial ({})", status.plan)
        } else {
            "Trial Expired".to_string()
        }
    } else if status.expired {
        "Expired".to_string()
    } else if status.valid {
        "Valid".to_string()
    } else {
        "Invalid".to_string()
    }
}