axonml-server 0.6.2

REST API server for AxonML Machine Learning Framework
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
//! Email Service — Resend API Transactional Mail
//!
//! Wraps the Resend REST API (`https://api.resend.com/emails`) behind an
//! `EmailService` struct that holds an optional API key and a `reqwest::Client`.
//! Provides four HTML email templates used throughout the signup/approval flow:
//!
//! - `send_verification_email` — email-verification link for new registrations.
//! - `send_admin_signup_notification` — notifies `devops@automatanexus.com`
//!   when a user signs up.
//! - `send_admin_approval_request` — sends an approval-action link to the
//!   admin after a user verifies their email (includes location/IP metadata).
//! - `send_welcome_email` — post-approval welcome with dashboard link.
//!
//! All emails are sent from `noreply@automatanexus.com`. The private
//! `send_email` method POSTs a `ResendEmailRequest` JSON body with Bearer
//! auth and logs the returned message ID via `tracing`.
//!
//! # File
//! `crates/axonml-server/src/email.rs`
//!
//! # Author
//! Andrew Jewell Sr. — AutomataNexus LLC
//! ORCID: 0009-0005-2158-7060
//!
//! # Updated
//! April 16, 2026 11:15 PM EST
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

// =============================================================================
// Imports
// =============================================================================

use reqwest::Client;
use serde::{Deserialize, Serialize};
use thiserror::Error;

// =============================================================================
// Error Types
// =============================================================================

#[derive(Error, Debug)]
pub enum EmailError {
    #[error("Failed to send email: {0}")]
    SendError(String),
    #[error("HTTP request failed: {0}")]
    HttpError(#[from] reqwest::Error),
    #[error("Email service not configured - RESEND_API_KEY not set")]
    NotConfigured,
}

// =============================================================================
// Resend API Types
// =============================================================================

#[derive(Debug, Serialize)]
struct ResendEmailRequest {
    from: String,
    to: Vec<String>,
    subject: String,
    html: String,
}

#[derive(Debug, Deserialize)]
struct ResendEmailResponse {
    id: String,
}

// =============================================================================
// Email Service
// =============================================================================

pub struct EmailService {
    api_key: Option<String>,
    client: Client,
    from_email: String,
}

impl EmailService {
    pub fn new(api_key: Option<String>) -> Self {
        Self {
            api_key,
            client: Client::new(),
            from_email: "AxonML <noreply@automatanexus.com>".to_string(),
        }
    }

    /// Check if email service is properly configured
    pub fn is_configured(&self) -> bool {
        self.api_key.is_some()
    }

    // -------------------------------------------------------------------------
    // User-Facing Emails
    // -------------------------------------------------------------------------

    /// Send verification email to user
    pub async fn send_verification_email(
        &self,
        to_email: &str,
        user_name: &str,
        verification_token: &str,
        base_url: &str,
    ) -> Result<(), EmailError> {
        let verify_url = format!(
            "{}/api/auth/verify-email?token={}",
            base_url, verification_token
        );

        let html = format!(
            r#"
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Verify Your Email - AxonML</title>
            </head>
            <body style="font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #111827; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #faf9f6;">
                <div style="background-color: #ffffff; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                    <div style="text-align: center; margin-bottom: 30px;">
                        <h1 style="color: #14b8a6; font-size: 32px; margin: 0;">AxonML</h1>
                    </div>

                    <h2 style="color: #111827; font-size: 24px; margin-bottom: 16px;">Welcome to AxonML, {}!</h2>

                    <p style="color: #6b7280; font-size: 16px; margin-bottom: 24px;">
                        Thank you for signing up! Please verify your email address to continue. Once verified,
                        an administrator will review and approve your account.
                    </p>

                    <div style="text-align: center; margin: 32px 0;">
                        <a href="{}" style="display: inline-block; background-color: #14b8a6; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 16px;">
                            Verify Email Address
                        </a>
                    </div>

                    <p style="color: #9ca3af; font-size: 14px; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                        If the button doesn't work, copy and paste this link into your browser:<br>
                        <a href="{}" style="color: #14b8a6; word-break: break-all;">{}</a>
                    </p>

                    <p style="color: #9ca3af; font-size: 14px; margin-top: 16px;">
                        If you didn't create an account with AxonML, you can safely ignore this email.
                    </p>

                    <div style="text-align: center; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                        <p style="color: #9ca3af; font-size: 12px; margin: 4px 0;">
                            Secured by AutomataNexus
                        </p>
                        <p style="color: #9ca3af; font-size: 12px; margin: 4px 0;">
                            © 2026 AxonML. All rights reserved.
                        </p>
                    </div>
                </div>
            </body>
            </html>
            "#,
            user_name, verify_url, verify_url, verify_url
        );

        self.send_email(to_email, "Verify Your Email - AxonML", &html)
            .await
    }

    /// Send welcome email after approval
    pub async fn send_welcome_email(
        &self,
        to_email: &str,
        user_name: &str,
        dashboard_url: &str,
    ) -> Result<(), EmailError> {
        let html = format!(
            r#"
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Welcome to AxonML</title>
            </head>
            <body style="font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #111827; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #faf9f6;">
                <div style="background-color: #ffffff; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                    <div style="text-align: center; margin-bottom: 30px;">
                        <h1 style="color: #14b8a6; font-size: 32px; margin: 0;">AxonML</h1>
                    </div>

                    <h2 style="color: #111827; font-size: 24px; margin-bottom: 16px;">Welcome, {}!</h2>

                    <p style="color: #6b7280; font-size: 16px; margin-bottom: 24px;">
                        Your account has been approved! You can now access the AxonML platform and start
                        building amazing ML models.
                    </p>

                    <div style="text-align: center; margin: 32px 0;">
                        <a href="{}" style="display: inline-block; background-color: #14b8a6; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 16px;">
                            Access Dashboard
                        </a>
                    </div>

                    <div style="background-color: #f0fdfa; border-left: 4px solid #14b8a6; padding: 16px; margin: 24px 0; border-radius: 4px;">
                        <h3 style="color: #111827; font-size: 16px; margin-top: 0;">Getting Started</h3>
                        <ul style="color: #6b7280; font-size: 14px; margin: 0; padding-left: 20px;">
                            <li>Explore the training dashboard</li>
                            <li>Upload your first model</li>
                            <li>Deploy inference endpoints</li>
                            <li>Monitor metrics and performance</li>
                        </ul>
                    </div>

                    <p style="color: #6b7280; font-size: 14px; margin-top: 24px;">
                        If you have any questions, feel free to reach out to our support team.
                    </p>

                    <div style="text-align: center; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                        <p style="color: #9ca3af; font-size: 12px; margin: 4px 0;">
                            Secured by AutomataNexus
                        </p>
                        <p style="color: #9ca3af; font-size: 12px; margin: 4px 0;">
                            © 2026 AxonML. All rights reserved.
                        </p>
                    </div>
                </div>
            </body>
            </html>
            "#,
            user_name, dashboard_url
        );

        self.send_email(
            to_email,
            "Welcome to AxonML - Your Account is Active!",
            &html,
        )
        .await
    }

    // -------------------------------------------------------------------------
    // Admin Notification Emails
    // -------------------------------------------------------------------------

    /// Send notification to admin about new user signup
    pub async fn send_admin_signup_notification(
        &self,
        user_email: &str,
        user_name: &str,
    ) -> Result<(), EmailError> {
        let html = format!(
            r#"
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>New User Signup - AxonML</title>
            </head>
            <body style="font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #111827; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #faf9f6;">
                <div style="background-color: #ffffff; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                    <div style="text-align: center; margin-bottom: 30px;">
                        <h1 style="color: #14b8a6; font-size: 32px; margin: 0;">AxonML</h1>
                    </div>

                    <h2 style="color: #111827; font-size: 24px; margin-bottom: 16px;">New User Signup</h2>

                    <p style="color: #6b7280; font-size: 16px; margin-bottom: 24px;">
                        A new user has registered for AxonML and is awaiting email verification:
                    </p>

                    <div style="background-color: #f0fdfa; border-left: 4px solid #14b8a6; padding: 16px; margin: 24px 0; border-radius: 4px;">
                        <p style="margin: 8px 0;"><strong>Name:</strong> {}</p>
                        <p style="margin: 8px 0;"><strong>Email:</strong> {}</p>
                    </div>

                    <p style="color: #6b7280; font-size: 14px; margin-top: 24px;">
                        Once the user verifies their email, you'll receive another notification to approve their access.
                    </p>

                    <div style="text-align: center; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                        <p style="color: #9ca3af; font-size: 12px; margin: 4px 0;">
                            Secured by AutomataNexus
                        </p>
                    </div>
                </div>
            </body>
            </html>
            "#,
            user_name, user_email
        );

        self.send_email(
            "devops@automatanexus.com",
            "New User Signup - AxonML",
            &html,
        )
        .await
    }

    /// Send approval request to admin after email verification
    pub async fn send_admin_approval_request(
        &self,
        user_id: &str,
        user_email: &str,
        user_name: &str,
        user_location: Option<&str>,
        user_ip: Option<&str>,
        approval_token: &str,
        base_url: &str,
    ) -> Result<(), EmailError> {
        let approval_url = format!(
            "{}/api/auth/approve-user?token={}",
            base_url, approval_token
        );

        let location_info = user_location.unwrap_or("Unknown");
        let ip_info = user_ip.unwrap_or("Unknown");

        let html = format!(
            r#"
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>User Approval Required - AxonML</title>
            </head>
            <body style="font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #111827; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #faf9f6;">
                <div style="background-color: #ffffff; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                    <div style="text-align: center; margin-bottom: 30px;">
                        <h1 style="color: #14b8a6; font-size: 32px; margin: 0;">AxonML</h1>
                    </div>

                    <h2 style="color: #111827; font-size: 24px; margin-bottom: 16px;">User Approval Required</h2>

                    <p style="color: #6b7280; font-size: 16px; margin-bottom: 24px;">
                        A user has verified their email address and is requesting access to AxonML:
                    </p>

                    <div style="background-color: #f0fdfa; border-left: 4px solid #14b8a6; padding: 16px; margin: 24px 0; border-radius: 4px;">
                        <p style="margin: 8px 0;"><strong>Username:</strong> {}</p>
                        <p style="margin: 8px 0;"><strong>Email:</strong> {}</p>
                        <p style="margin: 8px 0;"><strong>Full Name:</strong> {}</p>
                        <p style="margin: 8px 0;"><strong>Location:</strong> {}</p>
                        <p style="margin: 8px 0;"><strong>IP Address:</strong> {}</p>
                        <p style="margin: 8px 0;"><strong>User ID:</strong> {}</p>
                    </div>

                    <div style="text-align: center; margin: 32px 0;">
                        <a href="{}" style="display: inline-block; background-color: #14b8a6; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 16px;">
                            Permit {} Access
                        </a>
                    </div>

                    <p style="color: #9ca3af; font-size: 14px; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                        If the button doesn't work, copy and paste this link into your browser:<br>
                        <a href="{}" style="color: #14b8a6; word-break: break-all;">{}</a>
                    </p>

                    <div style="text-align: center; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                        <p style="color: #9ca3af; font-size: 12px; margin: 4px 0;">
                            Secured by AutomataNexus
                        </p>
                    </div>
                </div>
            </body>
            </html>
            "#,
            user_name,
            user_email,
            user_name,
            location_info,
            ip_info,
            user_id,
            approval_url,
            user_name,
            approval_url,
            approval_url
        );

        self.send_email(
            "devops@automatanexus.com",
            &format!("Approval Required: {} - AxonML", user_name),
            &html,
        )
        .await
    }

    // -------------------------------------------------------------------------
    // Internal Send
    // -------------------------------------------------------------------------

    /// Internal method to send email via Resend API
    async fn send_email(&self, to: &str, subject: &str, html: &str) -> Result<(), EmailError> {
        // Check if API key is configured
        let api_key = self.api_key.as_ref().ok_or(EmailError::NotConfigured)?;

        let request = ResendEmailRequest {
            from: self.from_email.clone(),
            to: vec![to.to_string()],
            subject: subject.to_string(),
            html: html.to_string(),
        };

        let response = self
            .client
            .post("https://api.resend.com/emails")
            .header("Authorization", format!("Bearer {}", api_key))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(EmailError::SendError(error_text));
        }

        let result: ResendEmailResponse = response.json().await?;
        tracing::debug!(email_id = %result.id, to = to, "Email sent successfully");
        Ok(())
    }
}