-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathwebauthn-client.js
More file actions
231 lines (197 loc) · 6.48 KB
/
webauthn-client.js
File metadata and controls
231 lines (197 loc) · 6.48 KB
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
//@ts-check
// Declare a SimpleWebAuthnBrowser variable as part of "window"
/** @typedef {"authenticate"} WebAuthnAuthenticate */
/** @typedef {"register"} WebAuthnRegister */
/** @typedef {WebAuthnRegister | WebAuthnAuthenticate} WebAuthnOptionsAction */
/**
* @template {WebAuthnOptionsAction} T
* @typedef {T extends WebAuthnAuthenticate ?
* { options: import("@simplewebauthn/server").PublicKeyCredentialRequestOptionsJSON; action: "authenticate" } :
* T extends WebAuthnRegister ?
* { options: import("@simplewebauthn/server").PublicKeyCredentialCreationOptionsJSON; action: "register" } :
* never
* } WebAuthnOptionsReturn
*/
/**
* webauthnScript is the client-side script that handles the webauthn form
*
* @param {string} authURL is the URL of the auth API
* @param {string} providerID is the ID of the webauthn provider
*/
export async function webauthnScript(authURL, providerID) {
/** @type {typeof import("@simplewebauthn/browser")} */
// @ts-ignore
const WebAuthnBrowser = window.SimpleWebAuthnBrowser
/**
* Fetch webauthn options from the server
*
* @template {WebAuthnOptionsAction} T
* @param {T | undefined} action action to fetch options for
* @returns {Promise<WebAuthnOptionsReturn<T> | undefined>}
*/
async function fetchOptions(action) {
// Create the options URL with the action and query parameters
const url = new URL(`${authURL}/webauthn-options/${providerID}`)
if (action) url.searchParams.append("action", action)
const formFields = getFormFields()
formFields.forEach((field) => {
url.searchParams.append(field.name, field.value)
})
const res = await fetch(url)
if (!res.ok) {
console.error("Failed to fetch options", res)
return
}
return res.json()
}
/**
* Get the webauthn form from the page
*
* @returns {HTMLFormElement}
*/
function getForm() {
const formID = `#${providerID}-form`
/** @type {HTMLFormElement | null} */
const form = document.querySelector(formID)
if (!form) throw new Error(`Form '${formID}' not found`)
return form
}
/**
* Get formFields from the form
*
* @returns {HTMLInputElement[]}
*/
function getFormFields() {
const form = getForm()
/** @type {HTMLInputElement[]} */
const formFields = Array.from(
form.querySelectorAll("input[data-form-field]")
)
return formFields
}
/**
* Passkey form submission handler.
* Takes the input from the form and a few other parameters and submits it to the server.
*
* @param {WebAuthnOptionsAction} action action to submit
* @param {unknown | undefined} data optional data to submit
* @returns {Promise<void>}
*/
async function submitForm(action, data) {
const form = getForm()
// If a POST request, create hidden fields in the form
// and submit it so the browser redirects on login
if (action) {
const actionInput = document.createElement("input")
actionInput.type = "hidden"
actionInput.name = "action"
actionInput.value = action
form.appendChild(actionInput)
}
if (data) {
const dataInput = document.createElement("input")
dataInput.type = "hidden"
dataInput.name = "data"
dataInput.value = JSON.stringify(data)
form.appendChild(dataInput)
}
return form.submit()
}
/**
* Executes the authentication flow by fetching options from the server,
* starting the authentication, and submitting the response to the server.
*
* @param {WebAuthnOptionsReturn<WebAuthnAuthenticate>['options']} options
* @param {boolean} autofill Whether or not to use the browser's autofill
* @returns {Promise<void>}
*/
async function authenticationFlow(options, autofill) {
// Start authentication
const authResp = await WebAuthnBrowser.startAuthentication({
optionsJSON: options,
useBrowserAutofill: autofill ?? false,
})
// Submit authentication response to server
return await submitForm("authenticate", authResp)
}
/**
* @param {WebAuthnOptionsReturn<WebAuthnRegister>['options']} options
*/
async function registrationFlow(options) {
// Check if all required formFields are set
const formFields = getFormFields()
formFields.forEach((field) => {
if (field.required && !field.value) {
throw new Error(`Missing required field: ${field.name}`)
}
})
// Start registration
const regResp = await WebAuthnBrowser.startRegistration({
optionsJSON: options,
})
// Submit registration response to server
return await submitForm("register", regResp)
}
/**
* Attempts to authenticate the user when the page loads
* using the browser's autofill popup.
*
* @returns {Promise<void>}
*/
async function autofillAuthentication() {
// if the browser can't handle autofill, don't try
if (!WebAuthnBrowser.browserSupportsWebAuthnAutofill()) return
const res = await fetchOptions("authenticate")
if (!res) {
console.error("Failed to fetch option for autofill authentication")
return
}
try {
await authenticationFlow(res.options, true)
} catch (e) {
console.error(e)
}
}
/**
* Sets up the passkey form by overriding the form submission handler
* so that it attempts to authenticate the user when the form is submitted.
* If the user is not registered, it will attempt to register them instead.
*/
async function setupForm() {
const form = getForm()
// If the browser can't do WebAuthn, hide the form
if (!WebAuthnBrowser.browserSupportsWebAuthn()) {
form.style.display = "none"
return
}
if (form) {
form.addEventListener("submit", async (e) => {
e.preventDefault()
// Fetch options from the server without assuming that
// the user is registered
const res = await fetchOptions(undefined)
if (!res) {
console.error("Failed to fetch options for form submission")
return
}
// Then execute the appropriate flow
if (res.action === "authenticate") {
try {
await authenticationFlow(res.options, false)
} catch (e) {
console.error(e)
}
} else if (res.action === "register") {
try {
await registrationFlow(res.options)
} catch (e) {
console.error(e)
}
}
})
}
}
// On page load, setup the form and attempt to authenticate the user.
setupForm()
autofillAuthentication()
}