function xsrfToken() {
const m = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/);
return m ? decodeURIComponent(m[1]) : "";
}
function b64urlToBuffer(b64url) {
const pad = "=".repeat((4 - (b64url.length % 4)) % 4);
const bin = atob((b64url + pad).replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes.buffer;
}
function bufferToB64url(buf) {
let bin = "";
for (const b of new Uint8Array(buf)) bin += String.fromCharCode(b);
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function postJson(url, body) {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", "X-XSRF-TOKEN": xsrfToken() },
credentials: "same-origin",
body: body === undefined ? "{}" : JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || "Request failed.");
return data;
}
function decodeCreationOptions({ publicKey: pk }) {
return {
...pk,
challenge: b64urlToBuffer(pk.challenge),
user: { ...pk.user, id: b64urlToBuffer(pk.user.id) },
excludeCredentials: (pk.excludeCredentials ?? []).map((c) => ({ ...c, id: b64urlToBuffer(c.id) })),
};
}
function decodeRequestOptions({ publicKey: pk }) {
return {
...pk,
challenge: b64urlToBuffer(pk.challenge),
allowCredentials: (pk.allowCredentials ?? []).map((c) => ({ ...c, id: b64urlToBuffer(c.id) })),
};
}
function encodeAttestation(cred) {
return {
id: cred.id,
rawId: bufferToB64url(cred.rawId),
type: cred.type,
response: {
attestationObject: bufferToB64url(cred.response.attestationObject),
clientDataJSON: bufferToB64url(cred.response.clientDataJSON),
},
};
}
function encodeAssertion(cred) {
return {
id: cred.id,
rawId: bufferToB64url(cred.rawId),
type: cred.type,
response: {
authenticatorData: bufferToB64url(cred.response.authenticatorData),
clientDataJSON: bufferToB64url(cred.response.clientDataJSON),
signature: bufferToB64url(cred.response.signature),
userHandle: cred.response.userHandle ? bufferToB64url(cred.response.userHandle) : null,
},
};
}
export async function registerPasskey(name) {
const challenge = await postJson("/settings/passkeys/register-start");
const credential = await navigator.credentials.create({ publicKey: decodeCreationOptions(challenge) });
return postJson("/settings/passkeys/register-finish", { name, credential: encodeAttestation(credential) });
}
export async function loginWithPasskey() {
const challenge = await postJson("/login/passkey-start");
const credential = await navigator.credentials.get({
publicKey: decodeRequestOptions(challenge),
mediation: "conditional",
});
const { redirect } = await postJson("/login/passkey-finish", encodeAssertion(credential));
window.location.assign(redirect || "/dashboard");
}