mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 09:09:01 +00:00
300 lines
13 KiB
JavaScript
300 lines
13 KiB
JavaScript
/*
|
|
* Passkeys (functions/passkey.php) - signing in with one on the sign-in page, and adding one in
|
|
* Your account (an agent's Security, the client portal's Your account).
|
|
*
|
|
* Sign in: [data-passkey-sign-in] (data-endpoint, login_passkey.php) is shown when the browser does
|
|
* passkeys. Its button asks for one; the email box (autocomplete "webauthn") offers them in its
|
|
* autofill too. The browser's answer is checked by the endpoint, and its token posted to the
|
|
* sign-in page ([data-passkey-form]), which signs them in.
|
|
*
|
|
* Add: a [data-passkey-add] form (data-options-url, data-csrf; data-vault="1" for an agent, whose
|
|
* passkey can open their credentials) gets what to ask the browser for, makes the passkey, and
|
|
* sends it with the form - its name and their password - as an ordinary post. A passkey that does
|
|
* PRF but didn't give its secret on being made is asked once more for it, to seal the vault key.
|
|
*/
|
|
(function () {
|
|
'use strict';
|
|
|
|
function toBytes(text) {
|
|
text = String(text || '').replace(/-/g, '+').replace(/_/g, '/');
|
|
while (text.length % 4) {
|
|
text += '=';
|
|
}
|
|
var raw = atob(text);
|
|
var bytes = new Uint8Array(raw.length);
|
|
for (var i = 0; i < raw.length; i++) {
|
|
bytes[i] = raw.charCodeAt(i);
|
|
}
|
|
return bytes.buffer;
|
|
}
|
|
|
|
function toText(buffer) {
|
|
if (!buffer) {
|
|
return '';
|
|
}
|
|
var bytes = new Uint8Array(buffer);
|
|
var raw = '';
|
|
for (var i = 0; i < bytes.length; i++) {
|
|
raw += String.fromCharCode(bytes[i]);
|
|
}
|
|
return btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
}
|
|
|
|
function supported() {
|
|
return !!(window.PublicKeyCredential && navigator.credentials && navigator.credentials.get && navigator.credentials.create);
|
|
}
|
|
|
|
function prfOf(credential) {
|
|
var results = credential && credential.getClientExtensionResults ? credential.getClientExtensionResults() : {};
|
|
return results && results.prf && results.prf.results && results.prf.results.first ? toText(results.prf.results.first) : '';
|
|
}
|
|
|
|
function prfExtension(options) {
|
|
var prf = options.extensions && options.extensions.prf;
|
|
return prf && prf.eval ? { prf: { eval: { first: toBytes(prf.eval.first) } } } : {};
|
|
}
|
|
|
|
// Why the browser said no, in words - '' for a sign-in that was simply stopped
|
|
function whyNot(error, address) {
|
|
var name = error && error.name;
|
|
if (name === 'AbortError') {
|
|
return '';
|
|
}
|
|
if (name === 'SecurityError') {
|
|
return 'Passkeys work at ' + address + ' - open ITFlow there and try again.';
|
|
}
|
|
if (name === 'InvalidStateError') {
|
|
return 'That passkey is already added here.';
|
|
}
|
|
if (name === 'NotSupportedError') {
|
|
return 'This browser or device can\'t make a passkey that ITFlow can use.';
|
|
}
|
|
if (name === 'NotAllowedError') {
|
|
return 'No passkey was used - it was cancelled or timed out, or there isn\'t one for this address on this device.';
|
|
}
|
|
return (error && error.message) || 'The passkey didn\'t work - try again.';
|
|
}
|
|
|
|
function post(url, data) {
|
|
return fetch(url, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
credentials: 'same-origin',
|
|
body: new URLSearchParams(data).toString()
|
|
}).then(function (res) {
|
|
return res.json().catch(function () {
|
|
return {};
|
|
}).then(function (json) {
|
|
if (!res.ok && !json.error) {
|
|
json.error = 'That didn\'t work (' + res.status + ') - try again.';
|
|
}
|
|
return json;
|
|
});
|
|
});
|
|
}
|
|
|
|
function showMessage(box, text, tone) {
|
|
if (!box) {
|
|
return;
|
|
}
|
|
box.textContent = '';
|
|
if (!text) {
|
|
return;
|
|
}
|
|
var alert = document.createElement('div');
|
|
alert.className = 'alert alert-' + (tone || 'danger');
|
|
alert.textContent = text;
|
|
box.appendChild(alert);
|
|
}
|
|
|
|
/* ---------------------------------------------------------------- Sign in */
|
|
|
|
var signIn = document.querySelector('[data-passkey-sign-in]');
|
|
if (signIn && supported()) {
|
|
signIn.hidden = false;
|
|
var endpoint = signIn.dataset.endpoint;
|
|
var button = signIn.querySelector('[data-passkey-button]');
|
|
var message = signIn.querySelector('[data-passkey-message]');
|
|
var form = signIn.querySelector('[data-passkey-form]');
|
|
var autofill = null;
|
|
var autofillTries = 0;
|
|
|
|
var finish = function (credential) {
|
|
var response = credential.response;
|
|
return post(endpoint, {
|
|
action: 'verify',
|
|
id: toText(credential.rawId),
|
|
client_data: toText(response.clientDataJSON),
|
|
authenticator_data: toText(response.authenticatorData),
|
|
signature: toText(response.signature),
|
|
user_handle: toText(response.userHandle),
|
|
prf: prfOf(credential)
|
|
}).then(function (result) {
|
|
if (result.token) {
|
|
form.querySelector('[name=pending_passkey_token]').value = result.token;
|
|
form.submit();
|
|
return true;
|
|
}
|
|
showMessage(message, result.error || 'That passkey didn\'t sign you in.');
|
|
return false;
|
|
});
|
|
};
|
|
|
|
var ask = function (inAutofill) {
|
|
return post(endpoint, { action: 'options' }).then(function (options) {
|
|
if (options.error) {
|
|
if (!inAutofill) {
|
|
showMessage(message, options.error);
|
|
}
|
|
return false;
|
|
}
|
|
var request = {
|
|
publicKey: {
|
|
challenge: toBytes(options.challenge),
|
|
rpId: options.rpId,
|
|
timeout: options.timeout,
|
|
userVerification: options.userVerification,
|
|
allowCredentials: [],
|
|
extensions: prfExtension(options)
|
|
}
|
|
};
|
|
if (inAutofill) {
|
|
autofill = new AbortController();
|
|
request.mediation = 'conditional';
|
|
request.signal = autofill.signal;
|
|
}
|
|
// true signed in, false the passkey didn't check out, null the browser didn't give one
|
|
return navigator.credentials.get(request).then(finish, function (error) {
|
|
if (!inAutofill) {
|
|
showMessage(message, whyNot(error, options.address));
|
|
}
|
|
return null;
|
|
});
|
|
});
|
|
};
|
|
|
|
// The email box's autofill offers passkeys too, where the browser can - offered again only after
|
|
// a passkey from it didn't check out, and only a few times, never in a loop of its own
|
|
var offerInAutofill = function () {
|
|
if (!window.PublicKeyCredential.isConditionalMediationAvailable || autofillTries >= 3) {
|
|
return;
|
|
}
|
|
autofillTries++;
|
|
window.PublicKeyCredential.isConditionalMediationAvailable().then(function (available) {
|
|
if (available) {
|
|
ask(true).then(function (signedIn) {
|
|
if (signedIn === false && autofill && !autofill.signal.aborted) {
|
|
offerInAutofill();
|
|
}
|
|
}).catch(function () {});
|
|
}
|
|
}).catch(function () {});
|
|
};
|
|
|
|
button.addEventListener('click', function () {
|
|
if (autofill) {
|
|
autofill.abort();
|
|
autofill = null;
|
|
}
|
|
showMessage(message, '');
|
|
button.disabled = true;
|
|
ask(false).catch(function () {
|
|
showMessage(message, 'The passkey didn\'t work - try again.');
|
|
return null;
|
|
}).then(function (signedIn) {
|
|
if (!signedIn) {
|
|
button.disabled = false;
|
|
autofillTries = 0;
|
|
offerInAutofill();
|
|
}
|
|
});
|
|
});
|
|
|
|
offerInAutofill();
|
|
}
|
|
|
|
/* ---------------------------------------------------------------- Add one */
|
|
|
|
document.querySelectorAll('form[data-passkey-add]').forEach(function (addForm) {
|
|
var addMessage = addForm.querySelector('[data-passkey-message]');
|
|
var submit = addForm.querySelector('[type=submit]');
|
|
|
|
if (!supported()) {
|
|
showMessage(addMessage, 'This browser can\'t make passkeys - try a current Chrome, Edge, Safari or Firefox.', 'warning');
|
|
if (submit) {
|
|
submit.disabled = true;
|
|
}
|
|
return;
|
|
}
|
|
|
|
addForm.addEventListener('submit', function (event) {
|
|
event.preventDefault();
|
|
if (!addForm.reportValidity()) {
|
|
return;
|
|
}
|
|
showMessage(addMessage, '');
|
|
if (submit) {
|
|
submit.disabled = true;
|
|
}
|
|
var address = '';
|
|
var password = addForm.querySelector('[name=current_password]');
|
|
post(addForm.dataset.optionsUrl, { passkey_create_options: 1, csrf_token: addForm.dataset.csrf, current_password: password ? password.value : '' }).then(function (options) {
|
|
if (options.error) {
|
|
throw { message: options.error };
|
|
}
|
|
address = options.address;
|
|
var publicKey = {
|
|
challenge: toBytes(options.challenge),
|
|
rp: options.rp,
|
|
user: { id: toBytes(options.user.id), name: options.user.name, displayName: options.user.displayName },
|
|
pubKeyCredParams: options.pubKeyCredParams,
|
|
timeout: options.timeout,
|
|
attestation: options.attestation,
|
|
authenticatorSelection: options.authenticatorSelection,
|
|
excludeCredentials: (options.excludeCredentials || []).map(function (item) {
|
|
return { type: item.type, id: toBytes(item.id), transports: item.transports };
|
|
}),
|
|
extensions: Object.assign({ credProps: true }, prfExtension(options))
|
|
};
|
|
return navigator.credentials.create({ publicKey: publicKey }).then(function (credential) {
|
|
var prf = prfOf(credential);
|
|
var results = credential.getClientExtensionResults ? credential.getClientExtensionResults() : {};
|
|
var canPrf = results.prf && results.prf.enabled === true;
|
|
if (prf || !canPrf || addForm.dataset.vault !== '1') {
|
|
return { credential: credential, prf: prf };
|
|
}
|
|
// It does PRF but didn't give its secret on being made - one more touch for it
|
|
var challenge = new Uint8Array(32);
|
|
window.crypto.getRandomValues(challenge);
|
|
return navigator.credentials.get({
|
|
publicKey: {
|
|
challenge: challenge.buffer,
|
|
rpId: options.rp.id,
|
|
allowCredentials: [{ type: 'public-key', id: credential.rawId }],
|
|
userVerification: 'required',
|
|
timeout: options.timeout,
|
|
extensions: prfExtension(options)
|
|
}
|
|
}).then(function (assertion) {
|
|
return { credential: credential, prf: prfOf(assertion) };
|
|
}, function () {
|
|
return { credential: credential, prf: '' };
|
|
});
|
|
});
|
|
}).then(function (made) {
|
|
var response = made.credential.response;
|
|
addForm.querySelector('[name=passkey_client_data]').value = toText(response.clientDataJSON);
|
|
addForm.querySelector('[name=passkey_attestation]').value = toText(response.attestationObject);
|
|
addForm.querySelector('[name=passkey_transports]').value = response.getTransports ? response.getTransports().join(',') : '';
|
|
addForm.querySelector('[name=passkey_prf]').value = made.prf;
|
|
HTMLFormElement.prototype.submit.call(addForm);
|
|
}).catch(function (error) {
|
|
showMessage(addMessage, error && error.name ? whyNot(error, address) : ((error && error.message) || 'The passkey wasn\'t added - try again.'));
|
|
if (submit) {
|
|
submit.disabled = false;
|
|
}
|
|
});
|
|
});
|
|
});
|
|
})();
|