aboutsummaryrefslogtreecommitdiffstats
path: root/web_src/js/features/user-auth-webauthn.js
blob: 6dfbb4d76536dfaac3e6c7fe61f1fa9b55825e8b (plain)
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
import {encodeURLEncodedBase64, decodeURLEncodedBase64} from '../utils.js';
import {showElem} from '../utils/dom.js';
import {GET, POST} from '../modules/fetch.js';

const {appSubUrl} = window.config;

export async function initUserAuthWebAuthn() {
  const elPrompt = document.querySelector('.user.signin.webauthn-prompt');
  if (!elPrompt) {
    return;
  }

  if (!detectWebAuthnSupport()) {
    return;
  }

  const res = await GET(`${appSubUrl}/user/webauthn/assertion`);
  if (res.status !== 200) {
    webAuthnError('unknown');
    return;
  }
  const options = await res.json();
  options.publicKey.challenge = decodeURLEncodedBase64(options.publicKey.challenge);
  for (const cred of options.publicKey.allowCredentials) {
    cred.id = decodeURLEncodedBase64(cred.id);
  }
  try {
    const credential = await navigator.credentials.get({
      publicKey: options.publicKey,
    });
    await verifyAssertion(credential);
  } catch (err) {
    if (!options.publicKey.extensions?.appid) {
      webAuthnError('general', err.message);
      return;
    }
    delete options.publicKey.extensions.appid;
    try {
      const credential = await navigator.credentials.get({
        publicKey: options.publicKey,
      });
      await verifyAssertion(credential);
    } catch (err) {
      webAuthnError('general', err.message);
    }
  }
}

async function verifyAssertion(assertedCredential) {
  // Move data into Arrays in case it is super long
  const authData = new Uint8Array(assertedCredential.response.authenticatorData);
  const clientDataJSON = new Uint8Array(assertedCredential.response.clientDataJSON);
  const rawId = new Uint8Array(assertedCredential.rawId);
  const sig = new Uint8Array(assertedCredential.response.signature);
  const userHandle = new Uint8Array(assertedCredential.response.userHandle);

  const res = await POST(`${appSubUrl}/user/webauthn/assertion`, {
    data: {
      id: assertedCredential.id,
      rawId: encodeURLEncodedBase64(rawId),
      type: assertedCredential.type,
      clientExtensionResults: assertedCredential.getClientExtensionResults(),
      response: {
        authenticatorData: encodeURLEncodedBase64(authData),
        clientDataJSON: encodeURLEncodedBase64(clientDataJSON),
        signature: encodeURLEncodedBase64(sig),
        userHandle: encodeURLEncodedBase64(userHandle),
      },
    },
  });
  if (res.status === 500) {
    webAuthnError('unknown');
    return;
  } else if (res.status !== 200) {
    webAuthnError('unable-to-process');
    return;
  }
  const reply = await res.json();

  window.location.href = reply?.redirect ?? `${appSubUrl}/`;
}

async function webauthnRegistered(newCredential) {
  const attestationObject = new Uint8Array(newCredential.response.attestationObject);
  const clientDataJSON = new Uint8Array(newCredential.response.clientDataJSON);
  const rawId = new Uint8Array(newCredential.rawId);

  const res = await POST(`${appSubUrl}/user/settings/security/webauthn/register`, {
    data: {
      id: newCredential.id,
      rawId: encodeURLEncodedBase64(rawId),
      type: newCredential.type,
      response: {
        attestationObject: encodeURLEncodedBase64(attestationObject),
        clientDataJSON: encodeURLEncodedBase64(clientDataJSON),
      },
    },
  });

  if (res.status === 409) {
    webAuthnError('duplicated');
    return;
  } else if (res.status !== 201) {
    webAuthnError('unknown');
    return;
  }

  window.location.reload();
}

function webAuthnError(errorType, message) {
  const elErrorMsg = document.getElementById(`webauthn-error-msg`);

  if (errorType === 'general') {
    elErrorMsg.textContent = message || 'unknown error';
  } else {
    const elTypedError = document.querySelector(`#webauthn-error [data-webauthn-error-msg=${errorType}]`);
    if (elTypedError) {
      elErrorMsg.textContent = `${elTypedError.textContent}${message ? ` ${message}` : ''}`;
    } else {
      elErrorMsg.textContent = `unknown error type: ${errorType}${message ? ` ${message}` : ''}`;
    }
  }

  showElem('#webauthn-error');
}

function detectWebAuthnSupport() {
  if (!window.isSecureContext) {
    webAuthnError('insecure');
    return false;
  }

  if (typeof window.PublicKeyCredential !== 'function') {
    webAuthnError('browser');
    return false;
  }

  return true;
}

export function initUserAuthWebAuthnRegister() {
  const elRegister = document.getElementById('register-webauthn');
  if (!elRegister) {
    return;
  }
  if (!detectWebAuthnSupport()) {
    elRegister.disabled = true;
    return;
  }
  elRegister.addEventListener('click', async (e) => {
    e.preventDefault();
    await webAuthnRegisterRequest();
  });
}

async function webAuthnRegisterRequest() {
  const elNickname = document.getElementById('nickname');

  const formData = new FormData();
  formData.append('name', elNickname.value);

  const res = await POST(`${appSubUrl}/user/settings/security/webauthn/request_register`, {
    data: formData,
  });

  if (res.status === 409) {
    webAuthnError('duplicated');
    return;
  } else if (res.status !== 200) {
    webAuthnError('unknown');
    return;
  }

  const options = await res.json();
  elNickname.closest('div.field').classList.remove('error');

  options.publicKey.challenge = decodeURLEncodedBase64(options.publicKey.challenge);
  options.publicKey.user.id = decodeURLEncodedBase64(options.publicKey.user.id);
  if (options.publicKey.excludeCredentials) {
    for (const cred of options.publicKey.excludeCredentials) {
      cred.id = decodeURLEncodedBase64(cred.id);
    }
  }

  try {
    const credential = await navigator.credentials.create({
      publicKey: options.publicKey,
    });
    await webauthnRegistered(credential);
  } catch (err) {
    webAuthnError('unknown', err);
  }
}