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
use gloo::console;
use kanidm_proto::v1::{CURegState, CURequest, CUSessionToken, CUStatus};
use kanidm_proto::webauthn::{CreationChallengeResponse, RegisterPublicKeyCredential};
use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
use yew::prelude::*;

use super::reset::{EventBusMsg, ModalProps};
use crate::error::*;
use crate::utils;

pub struct PasskeyModalApp {
    state: State,
    label_val: String,
}

pub enum State {
    Init,
    FetchingChallenge,
    ChallengeReady(CreationChallengeResponse),
    CredentialReady(RegisterPublicKeyCredential),
    Submitting,
}

pub enum Msg {
    LabelCheck,
    Cancel,
    Submit,
    Generate,
    Success,
    ChallengeReady(CreationChallengeResponse),
    CredentialCreate,
    CredentialReady(RegisterPublicKeyCredential),
    Error { emsg: String, kopid: Option<String> },
    NavigatorError,
}

impl From<FetchError> for Msg {
    fn from(fe: FetchError) -> Self {
        Msg::Error {
            emsg: fe.as_string(),
            kopid: None,
        }
    }
}

impl PasskeyModalApp {
    fn reset_and_hide(&mut self) {
        utils::modal_hide_by_id("staticPasskeyCreate");
        self.state = State::Init;
        self.label_val = "".to_string();
    }

    async fn submit_passkey_update(
        token: CUSessionToken,
        req: CURequest,
        cb: Callback<EventBusMsg>,
    ) -> Result<Msg, FetchError> {
        let req_jsvalue = serde_json::to_string(&(req, token))
            .map(|s| JsValue::from(&s))
            .expect_throw("Failed to serialise pw curequest");

        let mut opts = RequestInit::new();
        opts.method("POST");
        opts.mode(RequestMode::SameOrigin);

        opts.body(Some(&req_jsvalue));

        let request = Request::new_with_str_and_init("/v1/credential/_update", &opts)?;
        request
            .headers()
            .set("content-type", "application/json")
            .expect_throw("failed to set header");

        let window = utils::window();
        let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
        let resp: Response = resp_value.dyn_into().expect_throw("Invalid response type");
        let status = resp.status();
        let headers = resp.headers();

        let kopid = headers.get("x-kanidm-opid").ok().flatten();

        if status == 200 {
            let jsval = JsFuture::from(resp.json()?).await?;
            let status: CUStatus =
                serde_wasm_bindgen::from_value(jsval).expect_throw("Invalid response type");

            cb.emit(EventBusMsg::UpdateStatus {
                status: status.clone(),
            });

            Ok(match status.mfaregstate {
                CURegState::TotpCheck(_)
                | CURegState::TotpTryAgain
                | CURegState::TotpInvalidSha1
                | CURegState::BackupCodes(_) => Msg::Error {
                    emsg: "Invalid Passkey reg state response".to_string(),
                    kopid,
                },
                CURegState::Passkey(challenge) => Msg::ChallengeReady(challenge),
                CURegState::None => Msg::Success,
            })
        } else {
            let text = JsFuture::from(resp.text()?).await?;
            let emsg = text.as_string().unwrap_or_default();
            Ok(Msg::Error { emsg, kopid })
        }
    }
}

impl Component for PasskeyModalApp {
    type Message = Msg;
    type Properties = ModalProps;

    fn create(_ctx: &Context<Self>) -> Self {
        console::debug!("passkey modal create");

        PasskeyModalApp {
            state: State::Init,
            label_val: "".to_string(),
        }
    }

    fn changed(&mut self, _ctx: &Context<Self>, _props: &Self::Properties) -> bool {
        console::debug!("passkey modal::change");
        false
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        console::debug!("passkey modal::update");
        let cb = ctx.props().cb.clone();
        match msg {
            Msg::LabelCheck => {
                let label = utils::get_value_from_element_id("passkey-label")
                    // Default is empty string.
                    .unwrap_or_default();

                self.label_val = label;
            }
            Msg::Submit => {
                if let State::CredentialReady(rpkc) = &self.state {
                    let rpkc = rpkc.clone();
                    let label = self.label_val.clone();
                    // Init a fetch to get the challenge.
                    let token_c = ctx.props().token.clone();

                    ctx.link().send_future(async {
                        match Self::submit_passkey_update(
                            token_c,
                            CURequest::PasskeyFinish(label, rpkc),
                            cb,
                        )
                        .await
                        {
                            Ok(v) => v,
                            Err(v) => v.into(),
                        }
                    });

                    self.state = State::Submitting;
                }
                // Error?
            }
            Msg::Success => {
                self.reset_and_hide();
            }
            Msg::Generate => {
                // Init a fetch to get the challenge.
                let token_c = ctx.props().token.clone();

                ctx.link().send_future(async {
                    match Self::submit_passkey_update(token_c, CURequest::PasskeyInit, cb).await {
                        Ok(v) => v,
                        Err(v) => v.into(),
                    }
                });

                self.state = State::FetchingChallenge;
            }
            Msg::ChallengeReady(challenge) => {
                console::debug!(format!("{:?}", challenge).as_str());
                self.state = State::ChallengeReady(challenge);
            }
            Msg::CredentialCreate => {
                if let State::ChallengeReady(ccr) = &self.state {
                    let ccr = ccr.clone();
                    let c_options: web_sys::CredentialCreationOptions = ccr.into();

                    // Create a promise that calls the browsers navigator.credentials.create api.
                    let promise = utils::window()
                        .navigator()
                        .credentials()
                        .create_with_options(&c_options)
                        .expect_throw("Unable to create promise");
                    let fut = JsFuture::from(promise);

                    // Wait on the promise, when complete it will issue a callback.
                    ctx.link().send_future(async move {
                        match fut.await {
                            Ok(jsval) => {
                                // Convert from the raw js value into the expected PublicKeyCredential
                                let w_rpkc = web_sys::PublicKeyCredential::from(jsval);
                                // Serialise the web_sys::pkc into the webauthn proto version, ready to
                                // handle/transmit.
                                let rpkc = RegisterPublicKeyCredential::from(w_rpkc);

                                // Update our state
                                Msg::CredentialReady(rpkc)
                            }
                            Err(e) => {
                                console::error!(format!("error -> {:?}", e).as_str());
                                Msg::NavigatorError
                            }
                        }
                    });
                }
            }
            Msg::CredentialReady(rpkc) => {
                console::debug!(format!("{:?}", rpkc).as_str());
                self.state = State::CredentialReady(rpkc);
            }
            Msg::NavigatorError => {
                // Do something useful, like prompt or have a breadcrumb. But it's
                // not a full error.
            }
            Msg::Cancel => {
                let token_c = ctx.props().token.clone();

                ctx.link().send_future(async {
                    match Self::submit_passkey_update(token_c, CURequest::CancelMFAReg, cb).await {
                        Ok(v) => v,
                        Err(v) => v.into(),
                    }
                });

                self.state = State::FetchingChallenge;
            }
            Msg::Error { emsg, kopid } => {
                // Submit the error to the parent.
                cb.emit(EventBusMsg::Error { emsg, kopid });
                self.reset_and_hide();
            }
        };

        true
    }

    fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
        console::debug!("passkey modal::rendered");
    }

    fn destroy(&mut self, _ctx: &Context<Self>) {
        console::debug!("passkey modal::destroy");
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        console::debug!("passkey modal::view");

        let label_val = self.label_val.clone();

        let passkey_state = match &self.state {
            State::Init => {
                html! {
                    <button id="passkey-generate" type="button" class="btn btn-secondary"
                        onclick={
                            ctx.link()
                                .callback(move |_| {
                                    Msg::Generate
                                })
                        }
                    >
                    // TODO: start the session once the modal is popped up
                    { "Start Creating a New Passkey" }</button>
                }
            }
            State::Submitting | State::FetchingChallenge => {
                html! {
                      <div class="spinner-border text-dark" role="status">
                        <span class="visually-hidden">{ "Loading..." }</span>
                      </div>
                }
            }
            State::ChallengeReady(_challenge) => {
                // This works around a bug in safari :(
                html! {
                    <button id="passkey-generate" type="button" class="btn btn-primary"
                        onclick={
                            ctx.link()
                                .callback(move |_| {
                                    Msg::CredentialCreate
                                })
                        }
                    >{ "Do it!" }</button>
                }
            }
            State::CredentialReady(_) => {
                html! {
                    <h3>{ "Passkey Created!" }</h3>
                }
            }
        };

        let submit_enabled =
            !label_val.is_empty() && matches!(self.state, State::CredentialReady(_));

        let submit_state = match &self.state {
            State::CredentialReady(_rpkc) => {
                html! {
                    <>
                    <form class="row needs-validation" novalidate=true
                        onsubmit={ ctx.link().callback(move |e: SubmitEvent| {
                            #[cfg(debug_assertions)]
                            console::debug!("passkey modal::on form submit prevent default");
                            e.prevent_default();
                            if submit_enabled {
                                Msg::Submit
                            } else {
                                Msg::Cancel
                            }
                        } ) }
                    >
                      <label for="passkey-label" class="form-label">{ "Please name this Passkey" }</label>
                      <input
                        type="text"
                        class="form-control"
                        id="passkey-label"
                        placeholder=""
                        value={ label_val }
                        required=true
                        oninput={
                            ctx.link()
                                .callback(move |_| {
                                    Msg::LabelCheck
                                })
                        }
                      />
                    </form>
                    <button id="passkey-submit" type="button" class={crate::constants::CLASS_BUTTON_SUCCESS}
                        disabled={ !submit_enabled }
                        onclick={
                            ctx.link()
                                .callback(move |_| {
                                    Msg::Submit
                                })
                        }
                    >{ "Submit" }</button>
                    </>
                }
            }
            _ => {
                html! {
                    <button id="passkey-cancel" type="button" class="btn btn-secondary"
                        onclick={
                            ctx.link()
                                .callback(move |_| {
                                    Msg::Cancel
                                })
                        }
                    >{ "Cancel" }</button>
                }
            }
        };

        html! {
            <div class="modal fade" id="staticPasskeyCreate" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticPasskeyLabel" aria-hidden="true">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title" id="staticPasskeyLabel">{ "Add a New Passkey" }</h5>
                    <button type="button" class="btn-close" aria-label="Close"
                        onclick={
                            ctx.link()
                                .callback(move |_| {
                                    Msg::Cancel
                                })
                        }
                    ></button>
                  </div>
                  <div class="modal-body">

                    <div class="container">
                      <div class="row">
                        { passkey_state }
                      </div>
                    </div>
                  </div>
                  <div class="modal-footer">
                    { submit_state }
                  </div>
                </div>
              </div>
            </div>
        }
    }
}