-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasskeys.js
More file actions
143 lines (122 loc) · 4.2 KB
/
passkeys.js
File metadata and controls
143 lines (122 loc) · 4.2 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
/**
* Passkey Manager - handles WebAuthn credential management on the profile page.
*/
export default class PasskeyManager {
constructor(container) {
this.container = container;
this.api = container.dataset.api || '';
this.listEl = container.querySelector('#passkeys-list');
this.statusEl = container.querySelector('#passkey-status');
this.registerBtn = container.querySelector('#passkey-register-btn');
if (!window.PublicKeyCredential) {
container.style.display = 'none';
return;
}
this.registerBtn?.addEventListener('click', () => this.registerPasskey());
}
refreshList() {
document.body.dispatchEvent(new CustomEvent('passkey-changed'));
}
async registerPasskey() {
const name = this.promptName();
if (name === null) return;
this.registerBtn.disabled = true;
this.registerBtn.textContent = 'Registering...';
try {
// Get registration options
const optRes = await fetch(`${this.api}/passkeys/register/options`, {
credentials: 'same-origin',
});
if (!optRes.ok) throw new Error('Failed to get registration options');
const options = await optRes.json();
const createOpts = this.buildCreationOptions(options);
// Create credential via browser API
const credential = await navigator.credentials.create({
publicKey: createOpts,
});
// Send to server
const body = JSON.stringify({
name,
credential: {
id: credential.id,
rawId: bufferToBase64url(credential.rawId),
type: credential.type,
response: {
attestationObject: bufferToBase64url(credential.response.attestationObject),
clientDataJSON: bufferToBase64url(credential.response.clientDataJSON),
transports: credential.response.getTransports?.() || [],
},
},
});
const regRes = await fetch(`${this.api}/passkeys/register`, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body,
});
const data = await regRes.json();
if (data.success) {
this.showStatus('Passkey registered successfully!', 'success');
this.refreshList();
} else {
throw new Error(data.error || 'Registration failed');
}
} catch (err) {
if (err.name !== 'AbortError' && err.name !== 'NotAllowedError') {
this.showStatus(err.message || 'Registration failed', 'error');
}
} finally {
this.registerBtn.disabled = false;
this.registerBtn.textContent = 'Register New Passkey';
}
}
promptName() {
return prompt('Give this passkey a name (e.g., "MacBook Pro", "1Password"):', 'My Passkey');
}
buildCreationOptions(options) {
const publicKey = {
challenge: base64urlToBuffer(options.challenge),
rp: options.rp,
user: {
id: base64urlToBuffer(options.user.id),
name: options.user.name,
displayName: options.user.displayName,
},
pubKeyCredParams: options.pubKeyCredParams,
timeout: options.timeout,
attestation: options.attestation || 'none',
authenticatorSelection: options.authenticatorSelection,
};
if (options.excludeCredentials) {
publicKey.excludeCredentials = options.excludeCredentials.map(c => ({
id: base64urlToBuffer(c.id),
type: c.type,
transports: c.transports,
}));
}
return publicKey;
}
showStatus(message, type) {
if (!this.statusEl) return;
this.statusEl.textContent = message;
this.statusEl.className = `passkey-status passkey-status-${type}`;
clearTimeout(this._statusTimeout);
this._statusTimeout = setTimeout(() => {
this.statusEl.className = 'cms-hide';
}, 5000);
}
}
function bufferToBase64url(buffer) {
const bytes = new Uint8Array(buffer);
let str = '';
for (const byte of bytes) str += String.fromCharCode(byte);
return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function base64urlToBuffer(base64url) {
const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
const pad = base64.length % 4 === 0 ? '' : '='.repeat(4 - (base64.length % 4));
const binary = atob(base64 + pad);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes.buffer;
}