alibi-plugins 0.8.0

Built-in authentication plugins and API metadata for Alibi
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
use super::{EmailOtpPlugin, EmailOtpType};
use crate::authentication_helpers::{JsonField, JsonFieldKind};
use crate::endpoint::{definition, validate_fields};
use alibi_core::endpoint::{
    EndpointCall, EndpointDefinition, EndpointInput, EndpointResponse, ServerEndpoint,
};
use alibi_core::utils::json::JsValue;
use alibi_core::{AuthContext, AuthResult, AuthSchema, HttpMethod};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct EmailOtpRead {
    pub otp: Option<String>,
}

/// The sending operation acknowledges both delivery and concealed unknown mailboxes.
#[derive(Debug, Deserialize)]
pub struct EmailOtpSent {
    pub success: bool,
}

/// A successful check retains the proof and its current attempt count.
#[derive(Debug, Deserialize)]
pub struct EmailOtpCheck {
    pub success: bool,
}

/// A verified mailbox with optional newly issued browser authority.
#[derive(Debug, Deserialize)]
pub struct EmailOtpVerification {
    pub status: bool,
    pub token: Option<String>,
    pub user: Box<alibi_core::UserView>,
}

/// Sign-in credentials with schema-defined fields retained for new identities.
#[derive(Debug, Deserialize, serde::Serialize)]
pub struct EmailOtpSignInInput {
    pub email: String,
    pub otp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    #[serde(flatten)]
    pub additional_fields: serde_json::Map<String, serde_json::Value>,
}

/// Authority published after consuming a sign-in proof.
#[derive(Debug, Deserialize)]
pub struct EmailOtpSignInResult {
    pub token: String,
    pub user: Box<alibi_core::UserView>,
}

/// Reset request aliases acknowledge delivered or concealed mailbox requests.
#[derive(Debug, Deserialize)]
pub struct EmailOtpResetRequested {
    pub success: bool,
}

/// Scoped reset proof and replacement credential for the public server operation.
#[derive(Debug, Deserialize, serde::Serialize)]
pub struct EmailOtpPasswordResetInput {
    pub email: String,
    pub otp: String,
    pub password: String,
}

/// A replacement credential was committed without issuing browser authority.
#[derive(Debug, Deserialize)]
pub struct EmailOtpPasswordReset {
    pub success: bool,
}

/// New mailbox and optional proof of the current mailbox.
#[derive(Debug, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EmailOtpChangeRequestInput {
    pub new_email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otp: Option<String>,
}

/// The change challenge was delivered or an existing target mailbox was concealed.
#[derive(Debug, Deserialize)]
pub struct EmailOtpChangeRequested {
    pub success: bool,
}

/// New mailbox and its scoped change proof.
#[derive(Debug, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EmailOtpChangeInput {
    pub new_email: String,
    pub otp: String,
}

/// The caller's verified mailbox was changed while retaining session authority.
#[derive(Debug, Deserialize)]
pub struct EmailOtpChanged {
    pub success: bool,
}

const FIELDS: &[JsonField] = &[
    JsonField::string("email", true),
    JsonField {
        name: "type",
        kind: JsonFieldKind::OneOf(&[
            "email-verification",
            "sign-in",
            "forget-password",
            "change-email",
        ]),
        required: true,
    },
];

pub(super) fn definitions() -> Vec<EndpointDefinition> {
    vec![
        definition(
            "changeEmailEmailOTP",
            "changeEmailWithEmailOTP",
            Some("/email-otp/change-email"),
            HttpMethod::Post,
        ),
        definition(
            "requestEmailChangeEmailOTP",
            "requestEmailChangeWithEmailOTP",
            Some("/email-otp/request-email-change"),
            HttpMethod::Post,
        ),
        definition(
            "resetPasswordEmailOTP",
            "resetPasswordWithEmailOTP",
            Some("/email-otp/reset-password"),
            HttpMethod::Post,
        ),
        definition(
            "requestPasswordResetEmailOTP",
            "requestPasswordResetWithEmailOTP",
            Some("/email-otp/request-password-reset"),
            HttpMethod::Post,
        ),
        definition(
            "forgetPasswordEmailOTP",
            "forgetPasswordWithEmailOTP",
            Some("/forget-password/email-otp"),
            HttpMethod::Post,
        ),
        definition(
            "signInEmailOTP",
            "signInWithEmailOTP",
            Some("/sign-in/email-otp"),
            HttpMethod::Post,
        ),
        definition(
            "verifyEmailOTP",
            "verifyEmailOTP",
            Some("/email-otp/verify-email"),
            HttpMethod::Post,
        ),
        definition(
            "checkVerificationOTP",
            "verifyEmailWithOTP",
            Some("/email-otp/check-verification-otp"),
            HttpMethod::Post,
        ),
        definition(
            "sendVerificationOTP",
            "sendEmailVerificationOTP",
            Some("/email-otp/send-verification-otp"),
            HttpMethod::Post,
        ),
        definition(
            "createVerificationOTP",
            "createEmailVerificationOTP",
            None,
            HttpMethod::Post,
        ),
        definition(
            "getVerificationOTP",
            "getEmailVerificationOTP",
            None,
            HttpMethod::Get,
        ),
    ]
}

pub(super) fn validate(call: &EndpointCall) -> AuthResult<EndpointInput> {
    if call.operation_id() == "changeEmailWithEmailOTP" {
        return Ok(EndpointInput {
            body: Some(validate_fields(
                call.body(),
                "body",
                <super::types::ConfirmChangeRequest as crate::authentication_helpers::RequestBody>::FIELDS,
            )?),
            query: call.query().cloned(),
        });
    }
    if call.operation_id() == "requestEmailChangeWithEmailOTP" {
        return Ok(EndpointInput {
            body:Some(validate_fields(call.body(),"body",<super::types::ChangeEmailRequest as crate::authentication_helpers::RequestBody>::FIELDS)?),
            query:call.query().cloned(),
        });
    }
    if call.operation_id() == "resetPasswordWithEmailOTP" {
        return Ok(EndpointInput {
            body:Some(validate_fields(call.body(),"body",<super::types::PasswordRequest as crate::authentication_helpers::RequestBody>::FIELDS)?),
            query:call.query().cloned(),
        });
    }
    if matches!(
        call.operation_id(),
        "requestPasswordResetWithEmailOTP" | "forgetPasswordWithEmailOTP"
    ) {
        return Ok(EndpointInput {
            body: Some(validate_fields(
                call.body(),
                "body",
                <super::types::EmailRequest as crate::authentication_helpers::RequestBody>::FIELDS,
            )?),
            query: call.query().cloned(),
        });
    }
    if call.operation_id() == "signInWithEmailOTP" {
        let _ = validate_fields(
            call.body(),
            "body",
            <super::types::SignInRequest as crate::authentication_helpers::RequestBody>::FIELDS,
        )?;
        return Ok(EndpointInput {
            body: call.body().cloned(),
            query: call.query().cloned(),
        });
    }
    if call.operation_id() == "verifyEmailOTP" {
        return Ok(EndpointInput {
            body: Some(validate_fields(
                call.body(),
                "body",
                <super::types::VerifyRequest as crate::authentication_helpers::RequestBody>::FIELDS,
            )?),
            query: call.query().cloned(),
        });
    }
    if call.operation_id() == "verifyEmailWithOTP" {
        return Ok(EndpointInput {
            body: Some(validate_fields(
                call.body(),
                "body",
                <super::types::CheckRequest as crate::authentication_helpers::RequestBody>::FIELDS,
            )?),
            query: call.query().cloned(),
        });
    }
    if call.operation_id() == "getEmailVerificationOTP" {
        Ok(EndpointInput {
            body: call.body().cloned(),
            query: Some(validate_fields(call.query(), "query", FIELDS)?),
        })
    } else {
        Ok(EndpointInput {
            body: Some(validate_fields(call.body(), "body", FIELDS)?),
            query: call.query().cloned(),
        })
    }
}

impl EmailOtpPlugin {
    /// Consume a new-mailbox challenge using the caller's authoritative session.
    ///
    /// # Errors
    /// Returns an error if the supplied input cannot be serialized.
    pub fn change_email_email_otp_endpoint(
        input: &EmailOtpChangeInput,
    ) -> AuthResult<ServerEndpoint<EmailOtpChanged>> {
        ServerEndpoint::new("email-otp", "changeEmailEmailOTP").with_body(input)
    }

    /// Request a new-mailbox challenge using an authoritative caller session.
    ///
    /// # Errors
    /// Returns an error if the supplied input cannot be serialized.
    pub fn request_email_change_email_otp_endpoint(
        input: &EmailOtpChangeRequestInput,
    ) -> AuthResult<ServerEndpoint<EmailOtpChangeRequested>> {
        ServerEndpoint::new("email-otp", "requestEmailChangeEmailOTP").with_body(input)
    }

    /// Consume a reset proof and replace or create the owner's credential.
    ///
    /// # Errors
    /// Returns an error if reset input cannot be serialized.
    pub fn reset_password_email_otp_endpoint(
        input: &EmailOtpPasswordResetInput,
    ) -> AuthResult<ServerEndpoint<EmailOtpPasswordReset>> {
        ServerEndpoint::new("email-otp", "resetPasswordEmailOTP").with_body(input)
    }

    /// Request a scoped reset proof without exposing whether the mailbox exists.
    #[must_use]
    pub fn request_password_reset_email_otp_endpoint(
        email: impl Into<String>,
    ) -> ServerEndpoint<EmailOtpResetRequested> {
        reset_request("requestPasswordResetEmailOTP", email.into())
    }
    /// Call the published deprecated reset-request alias.
    #[must_use]
    pub fn forget_password_email_otp_endpoint(
        email: impl Into<String>,
    ) -> ServerEndpoint<EmailOtpResetRequested> {
        reset_request("forgetPasswordEmailOTP", email.into())
    }

    /// Consume a sign-in proof and apply returning-user or signup policy.
    ///
    /// # Errors
    /// Returns an error if the supplied sign-in input cannot be serialized.
    pub fn sign_in_email_otp_endpoint(
        input: &EmailOtpSignInInput,
    ) -> AuthResult<ServerEndpoint<EmailOtpSignInResult>> {
        ServerEndpoint::new("email-otp", "signInEmailOTP").with_body(input)
    }

    /// Consume a mailbox proof and apply verification/session policy.
    #[must_use]
    pub fn verify_email_otp_endpoint(
        email: impl Into<String>,
        otp: impl Into<String>,
    ) -> ServerEndpoint<EmailOtpVerification> {
        ServerEndpoint::new("email-otp", "verifyEmailOTP").with_body_value(JsValue::Object(
            [
                ("email".into(), JsValue::String(email.into())),
                ("otp".into(), JsValue::String(otp.into())),
            ]
            .into_iter()
            .collect(),
        ))
    }

    /// Check a scoped proof without consuming a successful validation.
    #[must_use]
    pub fn check_verification_otp_endpoint(
        email: impl Into<String>,
        otp_type: EmailOtpType,
        otp: impl Into<String>,
    ) -> ServerEndpoint<EmailOtpCheck> {
        let mut body = input(email.into(), otp_type);
        if let JsValue::Object(fields) = &mut body {
            let _ = fields.insert("otp".into(), JsValue::String(otp.into()));
        }
        ServerEndpoint::new("email-otp", "checkVerificationOTP").with_body_value(body)
    }

    /// Send a scoped OTP through the installed delivery and storage policies.
    #[must_use]
    pub fn send_verification_otp_endpoint(
        email: impl Into<String>,
        otp_type: EmailOtpType,
    ) -> ServerEndpoint<EmailOtpSent> {
        ServerEndpoint::new("email-otp", "sendVerificationOTP")
            .with_body_value(input(email.into(), otp_type))
    }

    /// Create a code through the installed endpoint hooks and post-hook validation.
    #[must_use]
    pub fn create_verification_otp_endpoint(
        email: impl Into<String>,
        otp_type: EmailOtpType,
    ) -> ServerEndpoint<String> {
        ServerEndpoint::new("email-otp", "createVerificationOTP")
            .with_body_value(input(email.into(), otp_type))
    }

    /// Retrieve a code through the installed endpoint hooks.
    #[must_use]
    pub fn get_verification_otp_endpoint(
        email: impl Into<String>,
        otp_type: EmailOtpType,
    ) -> ServerEndpoint<EmailOtpRead> {
        ServerEndpoint::new("email-otp", "getVerificationOTP")
            .with_query_value(input(email.into(), otp_type))
    }

    pub(super) async fn call_endpoint(
        &self,
        call: &EndpointCall,
        ctx: &AuthContext<impl AuthSchema>,
    ) -> AuthResult<EndpointResponse> {
        if call.operation_id() == "verifyEmailWithOTP" {
            let output = self.check_verification_core(ctx, call.body_as()?).await?;
            return EndpointResponse::json(&alibi_core::utils::json::from_slice::<JsValue>(
                &output.body,
            )?);
        }
        if matches!(
            call.operation_id(),
            "sendEmailVerificationOTP"
                | "verifyEmailOTP"
                | "signInWithEmailOTP"
                | "requestPasswordResetWithEmailOTP"
                | "forgetPasswordWithEmailOTP"
                | "resetPasswordWithEmailOTP"
                | "requestEmailChangeWithEmailOTP"
                | "changeEmailWithEmailOTP"
        ) {
            if call.operation_id() == "sendEmailVerificationOTP"
                && let Some(request) = call.request()
            {
                alibi_core::middleware::CsrfMiddleware::new(
                    alibi_core::middleware::CsrfConfig::new(),
                    ctx.config.clone(),
                )
                .check_login_origin(request)?;
            }
            let output = match call.operation_id() {
                "sendEmailVerificationOTP" => {
                    self.send_verification_core(call.request(), ctx, call.body_as()?)
                        .await?
                }
                "signInWithEmailOTP" => {
                    let raw = call.body().cloned().unwrap_or(JsValue::Null);
                    let mut parsed = raw.clone();
                    if let JsValue::Object(fields) = &mut parsed {
                        let _ = fields.shift_remove("username");
                        let _ = fields.shift_remove("displayUsername");
                    }
                    let body = alibi_core::utils::json::from_value(parsed)?;
                    self.sign_in_core(call, ctx, body, raw).await?
                }
                "requestPasswordResetWithEmailOTP" | "forgetPasswordWithEmailOTP" => {
                    self.request_password_reset_core(call.request(), ctx, call.body_as()?)
                        .await?
                }
                "resetPasswordWithEmailOTP" => {
                    self.reset_password_core(ctx, call.body_as()?).await?
                }
                "changeEmailWithEmailOTP" => {
                    self.change_email_core(call, ctx, call.body_as()?).await?
                }
                "requestEmailChangeWithEmailOTP" => {
                    self.request_email_change_core(call, ctx, call.body_as()?)
                        .await?
                }
                _ => self.verify_email_core(call, ctx, call.body_as()?).await?,
            };
            let mut response = if output.status >= 400 {
                EndpointResponse::error(crate::endpoint::error_response(output.clone()))
                    .without_error_body()
            } else {
                EndpointResponse::value(alibi_core::utils::json::from_slice(&output.body)?)
            };
            response.set_status(Some(output.status));
            response.merge_headers(output.headers);
            return Ok(response);
        }
        let (email, otp_type) = if call.operation_id() == "createEmailVerificationOTP" {
            let body: super::types::SendRequest = call.body_as()?;
            (body.email, body.otp_type)
        } else {
            let query: super::types::SendRequest = call.query_as()?;
            (query.email, query.otp_type)
        };
        if call.operation_id() == "createEmailVerificationOTP" {
            EndpointResponse::json(&self.create_verification_otp(ctx, &email, otp_type).await?)
        } else {
            EndpointResponse::json(
                &serde_json::json!({"otp": self.get_verification_otp(ctx, &email, otp_type).await?}),
            )
        }
    }
}

fn input(email: String, otp_type: EmailOtpType) -> JsValue {
    JsValue::Object(
        [
            ("email".into(), JsValue::String(email)),
            ("type".into(), JsValue::String(otp_type.as_str().into())),
        ]
        .into_iter()
        .collect(),
    )
}

fn reset_request(name: &'static str, email: String) -> ServerEndpoint<EmailOtpResetRequested> {
    ServerEndpoint::new("email-otp", name).with_body_value(JsValue::Object(
        [("email".into(), JsValue::String(email))]
            .into_iter()
            .collect(),
    ))
}