-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebauthn.js
More file actions
179 lines (151 loc) · 6.09 KB
/
webauthn.js
File metadata and controls
179 lines (151 loc) · 6.09 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
function isWebAuthnSupported() {
return !!(
navigator.credentials &&
navigator.credentials.create &&
navigator.credentials.get &&
window.PublicKeyCredential
);
}
export class WebauthnCreateElement extends HTMLElement {
connectedCallback() {
this.style.display = 'contents';
if (!isWebAuthnSupported()) {
this.handleWebauthnUnsupported();
return;
}
this.closest('form').addEventListener('submit', async (event) => {
event.preventDefault();
try {
const response = await fetch(this.getAttribute('data-options-url'));
const publicKey = PublicKeyCredential.parseCreationOptionsFromJSON(await response.json());
const credential = await navigator.credentials.create({ publicKey });
this.querySelector('[data-webauthn-target="response"]').value = await this.stringifyRegistrationCredentialWithGracefullyHandlingAuthenticatorIssues(credential);
this.closest('form').submit();
} catch (error) {
this.handleError(error);
}
});
}
handleError(error) {
const event = new CustomEvent('webauthn:prompt:error', {
detail: { error, action: 'create' },
bubbles: true,
cancelable: true
});
// If no listener prevents default, show alert
if (this.dispatchEvent(event)) {
alert(error.message || error);
}
}
handleWebauthnUnsupported() {
this.dispatchEvent(new CustomEvent('webauthn:unsupported', {
detail: { action: 'create' },
bubbles: true
}));
}
// Stringifies registration credentials gracefully handling malformed ones (e.g., due to issues with
// certain authenticators like 1Password).
// It first tries to stringify them normally, and if the credential cannot be stringified (because its
// malformed), it attempts a workaround to convert the malformed credential into a valid format. This
// workaround was introduced for 1Password and might fail for other authenticators.
//
// Authenticators that return a proper credential should not affected by this workaround!
async stringifyRegistrationCredentialWithGracefullyHandlingAuthenticatorIssues(credential) {
try {
return JSON.stringify(credential);
} catch (e) {
console.warn("Authenticator returned a malformed credential, attempting to fix it. Error was:", e);
}
const response = credential.response;
const publicKey = response.getPublicKey ? await response.getPublicKey() : null;
return JSON.stringify({
type: credential.type,
id: credential.id,
rawId: credential.id,
authenticatorAttachment: credential.authenticatorAttachment,
clientExtensionResults: await credential.getClientExtensionResults(),
response: {
attestationObject: toBase64Url(response.attestationObject),
authenticatorData: toBase64Url(response.authenticatorData),
clientDataJSON: toBase64Url(response.clientDataJSON),
publicKey: toBase64Url(publicKey),
publicKeyAlgorithm: response.getPublicKeyAlgorithm(),
transports: response.getTransports(),
},
});
}
}
export class WebauthnGetElement extends HTMLElement {
connectedCallback() {
this.style.display = 'contents';
if (!isWebAuthnSupported()) {
this.handleWebauthnUnsupported();
return;
}
this.closest('form').addEventListener('submit', async (event) => {
event.preventDefault();
try {
const response = await fetch(this.getAttribute('data-options-url'));
const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON(await response.json());
const credential = await navigator.credentials.get({ publicKey });
this.querySelector('[data-webauthn-target="response"]').value = await this.stringifyAuthenticationCredentialWithGracefullyHandlingAuthenticatorIssues(credential);
this.closest('form').submit();
} catch (error) {
this.handleError(error);
}
});
}
handleError(error) {
const event = new CustomEvent('webauthn:prompt:error', {
detail: { error, action: 'get' },
bubbles: true,
cancelable: true
});
// If no listener prevents default, show alert
if (this.dispatchEvent(event)) {
alert(error.message || error);
}
}
handleWebauthnUnsupported() {
this.dispatchEvent(new CustomEvent('webauthn:unsupported', {
detail: { action: 'get' },
bubbles: true
}));
}
// Stringifies authentication credentials gracefully handling malformed ones (e.g., due to issues with
// certain authenticators like 1Password).
// It first tries to stringify them normally, and if the credential cannot be stringified (because its
// malformed), it attempts a workaround to convert the malformed credential into a valid format. This
// workaround was introduced for 1Password and might fail for other authenticators.
//
// Authenticators that return a proper credential should not affected by this workaround!
async stringifyAuthenticationCredentialWithGracefullyHandlingAuthenticatorIssues(credential) {
try {
return JSON.stringify(credential);
} catch (e) {
console.warn("Authenticator returned a malformed credential, attempting to fix it. Error was:", e);
}
const response = credential.response;
return JSON.stringify({
type: credential.type,
id: credential.id,
rawId: credential.id,
authenticatorAttachment: credential.authenticatorAttachment,
clientExtensionResults: await credential.getClientExtensionResults(),
response: {
authenticatorData: toBase64Url(response.authenticatorData),
clientDataJSON: toBase64Url(response.clientDataJSON),
signature: toBase64Url(response.signature),
userHandle: response.userHandle ? toBase64Url(response.userHandle) : null,
},
});
}
}
function toBase64Url(buffer) {
if (!buffer) return null;
const binary = String.fromCharCode(...new Uint8Array(buffer));
const base64 = btoa(binary);
return base64.replaceAll("+", "-").replaceAll("/", "_");
}
customElements.define('webauthn-create', WebauthnCreateElement);
customElements.define('webauthn-get', WebauthnGetElement);