Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add signCount increment flow (#520)

Leendert de Borst0ca4a7b8c70c
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 49bce1e38..f8ff5e333 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -68,7 +68,7 @@ export default defineBackground({
onMessage('WEBAUTHN_CREATE', ({ data }) => handleWebAuthnCreate(data as { publicKey: unknown; origin: string }));
onMessage('WEBAUTHN_GET', ({ data }) => handleWebAuthnGet(data as { publicKey: { allowCredentials?: { id: string; }[] | undefined }; origin: string }));
onMessage('STORE_PASSKEY', ({ data }) => handleStorePasskey(data as { rpId: string; credentialId: string; displayName: string; publicKey: unknown }));
- onMessage('UPDATE_PASSKEY_LAST_USED', ({ data }) => handleUpdatePasskeyLastUsed(data as { credentialId: string }));
+ onMessage('UPDATE_PASSKEY_LAST_USED', ({ data }) => handleUpdatePasskeyLastUsed(data as { credentialId: string; newSignCount?: number }));
onMessage('CLEAR_ALL_PASSKEYS', () => handleClearAllPasskeys());
onMessage('PASSKEY_POPUP_RESPONSE', ({ data }) => handlePasskeyPopupResponse(data as { requestId: string; credential?: any; fallback?: boolean; cancelled?: boolean }));
onMessage('GET_REQUEST_DATA', ({ data }) => handleGetRequestData(data as { requestId: string }));
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
index 35363ed92..0cb475ef7 100644
--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
@@ -150,9 +150,11 @@ export async function handleWebAuthnGet(data: {
}));
console.log('handleWebAuthnGet: final passkeyList', passkeyList);
- // If allowCredentials was specified but we have no matches, show all passkeys anyway
- // (This is what password managers do - they show their own passkeys even if the site
- // doesn't explicitly request them, allowing users to use extension passkeys)
+ /*
+ * If allowCredentials was specified but we have no matches, show all passkeys anyway
+ * (This is what password managers do - they show their own passkeys even if the site
+ * doesn't explicitly request them, allowing users to use extension passkeys)
+ */
if (passkeyList.length === 0 && passkeys.length > 0) {
console.log('handleWebAuthnGet: no matching allowCredentials, showing all passkeys instead');
passkeyList = passkeys.map(pk => ({
@@ -256,18 +258,26 @@ export async function handleStorePasskey(data: {
}
/**
- * Update passkey last used time
+ * Update passkey last used time and sign count
*/
export async function handleUpdatePasskeyLastUsed(data: {
credentialId: string;
+ newSignCount?: number;
}): Promise<{ success: boolean }> {
- const { credentialId } = data;
+ const { credentialId, newSignCount } = data;
// Find and update the passkey
for (const [key, passkey] of sessionPasskeys.entries()) {
if (passkey.credentialId === credentialId) {
passkey.lastUsedAt = Date.now();
- passkey.signCount++;
+
+ // Update sign count - either use provided value or increment
+ if (newSignCount !== undefined) {
+ passkey.signCount = newSignCount;
+ } else {
+ passkey.signCount++;
+ }
+
sessionPasskeys.set(key, passkey);
// Update in storage too
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
index b5d18a2d1..2f75b4d57 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
@@ -29,6 +29,9 @@ const PasskeyAuthenticate: React.FC = () => {
const [loading, setLoading] = useState(false);
useEffect(() => {
+ /**
+ *
+ */
const fetchRequestData = async () => {
// Get the requestId from URL
const params = new URLSearchParams(location.search);
@@ -78,117 +81,138 @@ const PasskeyAuthenticate: React.FC = () => {
setLoading(true);
- // Get the stored passkey to access the private key
- const passkeyData = await sendMessage('GET_PASSKEY_BY_ID', { credentialId: selectedPasskey }, 'background');
+ try {
+ console.log('PasskeyAuthenticate: Starting authentication');
+ console.log('PasskeyAuthenticate: selectedPasskey', selectedPasskey);
+ console.log('PasskeyAuthenticate: request', request);
- if (!passkeyData) {
- console.error('Passkey not found');
- setLoading(false);
- return;
- }
+ // Get the stored passkey to access the private key
+ const passkeyData = await sendMessage('GET_PASSKEY_BY_ID', { credentialId: selectedPasskey }, 'background');
- // Calculate rpId hash
- const rpId = request.publicKey.rpId || new URL(request.origin).hostname;
- const rpIdBuffer = new TextEncoder().encode(rpId);
- const rpIdHashBuffer = await crypto.subtle.digest('SHA-256', rpIdBuffer);
- const rpIdHash = new Uint8Array(rpIdHashBuffer);
-
- // Flags: UP (User Present) = 1, UV (User Verified) = 1
- const flags = new Uint8Array([0x05]); // Binary: 00000101
-
- // Sign count (increment on each use)
- const signCount = new Uint8Array([0, 0, 0, 1]);
-
- // Construct authenticatorData (37 bytes minimum)
- const authenticatorData = new Uint8Array([
- ...rpIdHash, // 32 bytes
- ...flags, // 1 byte
- ...signCount // 4 bytes
- ]);
-
- // Create clientDataJSON
- const clientDataJSON = JSON.stringify({
- type: 'webauthn.get',
- challenge: request.publicKey.challenge,
- origin: request.origin
- });
-
- // Create signature over authenticatorData + hash(clientDataJSON)
- const clientDataHash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(clientDataJSON));
- const dataToSign = new Uint8Array([...authenticatorData, ...new Uint8Array(clientDataHash)]);
-
- // Import the private key and sign
- const privateKey = await crypto.subtle.importKey(
- 'jwk',
- passkeyData.privateKey,
- { name: 'ECDSA', namedCurve: 'P-256' },
- false,
- ['sign']
- );
-
- const signatureBuffer = await crypto.subtle.sign(
- { name: 'ECDSA', hash: 'SHA-256' },
- privateKey,
- dataToSign
- );
-
- // Convert raw signature (r || s) to DER format for WebAuthn
- const rawSignature = new Uint8Array(signatureBuffer);
- const r = rawSignature.slice(0, 32);
- const s = rawSignature.slice(32, 64);
-
- // Helper to encode integer in DER format
- const encodeInteger = (int: Uint8Array): Uint8Array => {
- // Remove leading zeros
- let i = 0;
- while (i < int.length && int[i] === 0) i++;
- let trimmed = int.slice(i);
-
- // Add leading zero if high bit is set (to keep it positive)
- if (trimmed.length === 0) trimmed = new Uint8Array([0]);
- if (trimmed[0] & 0x80) {
- const padded = new Uint8Array(trimmed.length + 1);
- padded[0] = 0;
- padded.set(trimmed, 1);
- trimmed = padded;
+ if (!passkeyData) {
+ console.error('Passkey not found');
+ setLoading(false);
+ return;
}
- // DER encoding: 0x02 (INTEGER tag) + length + value
- return new Uint8Array([0x02, trimmed.length, ...trimmed]);
- };
-
- const rDer = encodeInteger(r);
- const sDer = encodeInteger(s);
-
- // DER SEQUENCE: 0x30 (SEQUENCE tag) + length + r + s
- const derSignature = new Uint8Array([
- 0x30,
- rDer.length + sDer.length,
- ...rDer,
- ...sDer
- ]);
-
- const credential = {
- id: selectedPasskey,
- rawId: selectedPasskey,
- clientDataJSON: btoa(clientDataJSON),
- authenticatorData: btoa(String.fromCharCode(...authenticatorData)),
- signature: btoa(String.fromCharCode(...derSignature)),
- userHandle: null
- };
-
- // Update last used
- await sendMessage('UPDATE_PASSKEY_LAST_USED', {
- credentialId: selectedPasskey
- }, 'background');
-
- // Send response back
- await sendMessage('PASSKEY_POPUP_RESPONSE', {
- requestId: request.requestId,
- credential
- }, 'background');
+ // Calculate rpId hash
+ const rpId = request.publicKey.rpId || new URL(request.origin).hostname;
+ const rpIdBuffer = new TextEncoder().encode(rpId);
+ const rpIdHashBuffer = await crypto.subtle.digest('SHA-256', rpIdBuffer);
+ const rpIdHash = new Uint8Array(rpIdHashBuffer);
+
+ // Flags: UP (User Present) = 1, UV (User Verified) = 1
+ const flags = new Uint8Array([0x05]); // Binary: 00000101
+
+ // Sign count - increment from stored value (must increase on each use to detect cloned authenticators)
+ const newSignCount = (passkeyData.signCount || 0) + 1;
+ const signCount = new Uint8Array([
+ (newSignCount >> 24) & 0xff,
+ (newSignCount >> 16) & 0xff,
+ (newSignCount >> 8) & 0xff,
+ newSignCount & 0xff
+ ]);
+
+ // Construct authenticatorData (37 bytes minimum)
+ const authenticatorData = new Uint8Array([
+ ...rpIdHash, // 32 bytes
+ ...flags, // 1 byte
+ ...signCount // 4 bytes
+ ]);
+
+ // Create clientDataJSON
+ const clientDataJSON = JSON.stringify({
+ type: 'webauthn.get',
+ challenge: request.publicKey.challenge,
+ origin: request.origin
+ });
+
+ // Create signature over authenticatorData + hash(clientDataJSON)
+ const clientDataHash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(clientDataJSON));
+ const dataToSign = new Uint8Array([...authenticatorData, ...new Uint8Array(clientDataHash)]);
+
+ // Import the private key and sign
+ const privateKey = await crypto.subtle.importKey(
+ 'jwk',
+ passkeyData.privateKey,
+ { name: 'ECDSA', namedCurve: 'P-256' },
+ false,
+ ['sign']
+ );
+
+ const signatureBuffer = await crypto.subtle.sign(
+ { name: 'ECDSA', hash: 'SHA-256' },
+ privateKey,
+ dataToSign
+ );
+
+ // Convert raw signature (r || s) to DER format for WebAuthn
+ const rawSignature = new Uint8Array(signatureBuffer);
+ const r = rawSignature.slice(0, 32);
+ const s = rawSignature.slice(32, 64);
+
+ // Helper to encode integer in DER format
+ /**
+ *
+ */
+ const encodeInteger = (int: Uint8Array): Uint8Array => {
+ // Remove leading zeros but keep at least one byte
+ let i = 0;
+ while (i < int.length - 1 && int[i] === 0 && (int[i + 1] & 0x80) === 0) {
+ i++;
+ }
+ let trimmed = int.slice(i);
+
+ // If high bit is set, add zero padding to keep it positive
+ if (trimmed[0] & 0x80) {
+ const padded = new Uint8Array(trimmed.length + 1);
+ padded[0] = 0;
+ padded.set(trimmed, 1);
+ trimmed = padded;
+ }
- window.close();
+ // DER encoding: 0x02 (INTEGER tag) + length + value
+ return new Uint8Array([0x02, trimmed.length, ...trimmed]);
+ };
+
+ const rDer = encodeInteger(r);
+ const sDer = encodeInteger(s);
+
+ // DER SEQUENCE: 0x30 (SEQUENCE tag) + length + r + s
+ const derSignature = new Uint8Array([
+ 0x30,
+ rDer.length + sDer.length,
+ ...rDer,
+ ...sDer
+ ]);
+
+ const credential = {
+ id: selectedPasskey,
+ rawId: selectedPasskey,
+ clientDataJSON: btoa(clientDataJSON),
+ authenticatorData: btoa(String.fromCharCode(...authenticatorData)),
+ signature: btoa(String.fromCharCode(...derSignature)),
+ userHandle: null
+ };
+
+ // Update last used and sign count
+ await sendMessage('UPDATE_PASSKEY_LAST_USED', {
+ credentialId: selectedPasskey,
+ newSignCount
+ }, 'background');
+
+ // Send response back
+ await sendMessage('PASSKEY_POPUP_RESPONSE', {
+ requestId: request.requestId,
+ credential
+ }, 'background');
+
+ window.close();
+ } catch (error) {
+ console.error('PasskeyAuthenticate: Error during authentication', error);
+ setLoading(false);
+ alert(`Failed to authenticate: ${error instanceof Error ? error.message : String(error)}`);
+ }
};
/**
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
index 7f526bdbe..0e14dd196 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -25,6 +25,9 @@ const PasskeyCreate: React.FC = () => {
const [loading, setLoading] = useState(false);
useEffect(() => {
+ /**
+ *
+ */
const fetchRequestData = async () => {
console.log(location);
// Get the requestId from URL
@@ -68,196 +71,244 @@ const PasskeyCreate: React.FC = () => {
setLoading(true);
- // Generate a real cryptographic key pair
- const keyPair = await crypto.subtle.generateKey(
- {
- name: 'ECDSA',
- namedCurve: 'P-256'
- },
- true, // extractable
- ['sign', 'verify']
- );
+ try {
+ console.log('PasskeyCreate: Starting passkey creation');
+ console.log('PasskeyCreate: request', request);
+
+ // Generate a real cryptographic key pair
+ const keyPair = await crypto.subtle.generateKey(
+ {
+ name: 'ECDSA',
+ namedCurve: 'P-256'
+ },
+ true, // extractable
+ ['sign', 'verify']
+ );
- // Export the public key
- const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
- const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
-
- // Generate credential ID
- const credIdBytes = crypto.getRandomValues(new Uint8Array(16));
- // Convert to base64url (WebAuthn uses base64url, not standard base64)
- const base64 = btoa(String.fromCharCode(...credIdBytes));
- const credentialId = base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
-
- // Calculate rpId hash (SHA-256 of rpId)
- const rpId = request.publicKey.rp?.id || new URL(request.origin).hostname;
- const rpIdBuffer = new TextEncoder().encode(rpId);
- const rpIdHashBuffer = await crypto.subtle.digest('SHA-256', rpIdBuffer);
- const rpIdHash = new Uint8Array(rpIdHashBuffer);
-
- // Flags: UP (User Present) = 1, UV (User Verified) = 1, AT (Attested Credential Data) = 1
- const flags = new Uint8Array([0x45]); // Binary: 01000101
- const signCount = new Uint8Array([0, 0, 0, 0]);
- const aaguid = new Uint8Array(16); // All zeros for this implementation
-
- // Convert JWK coordinates from base64url to bytes for COSE format
- const base64UrlToBytes = (base64url: string): Uint8Array => {
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
- const binary = atob(base64);
- return new Uint8Array(binary.split('').map(c => c.charCodeAt(0)));
- };
+ // Export the public key
+ const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
+ const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
+
+ // Generate credential ID
+ const credIdBytes = crypto.getRandomValues(new Uint8Array(16));
+ // Convert to base64url (WebAuthn uses base64url, not standard base64)
+ const base64 = btoa(String.fromCharCode(...credIdBytes));
+ const credentialId = base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
+
+ // Calculate rpId hash (SHA-256 of rpId)
+ const rpId = request.publicKey.rp?.id || new URL(request.origin).hostname;
+ const rpIdBuffer = new TextEncoder().encode(rpId);
+ const rpIdHashBuffer = await crypto.subtle.digest('SHA-256', rpIdBuffer);
+ const rpIdHash = new Uint8Array(rpIdHashBuffer);
+
+ // Flags: UP (User Present) = 1, UV (User Verified) = 1, AT (Attested Credential Data) = 1
+ const flags = new Uint8Array([0x45]); // Binary: 01000101
+ const signCount = new Uint8Array([0, 0, 0, 0]);
+ const aaguid = new Uint8Array(16); // All zeros for this implementation
+
+ // Convert JWK coordinates from base64url to bytes for COSE format
+ /**
+ *
+ */
+ const base64UrlToBytes = (base64url: string): Uint8Array => {
+ const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
+ const binary = atob(base64);
+ return new Uint8Array(binary.split('').map(c => c.charCodeAt(0)));
+ };
- const xCoord = base64UrlToBytes(publicKeyJwk.x!);
- const yCoord = base64UrlToBytes(publicKeyJwk.y!);
-
- // COSE public key (ES256 format) - proper CBOR encoding
- // Map with 5 entries: kty, alg, crv, x, y
- const coseKey = new Uint8Array([
- 0xa5, // map(5)
- 0x01, // key 1 (kty)
- 0x02, // value: 2 (EC2)
- 0x03, // key 3 (alg)
- 0x26, // value: -7 (ES256) encoded as negative int
- 0x20, // key -1 (crv) encoded as negative int
- 0x01, // value: 1 (P-256)
- 0x21, // key -2 (x) encoded as negative int
- 0x58, 0x20, // byte string of length 32
- ...xCoord, // x coordinate (32 bytes)
- 0x22, // key -3 (y) encoded as negative int
- 0x58, 0x20, // byte string of length 32
- ...yCoord // y coordinate (32 bytes)
- ]);
-
- // Construct authData
- const credIdLength = new Uint8Array([0, credIdBytes.length]);
- const authData = new Uint8Array([
- ...rpIdHash,
- ...flags,
- ...signCount,
- ...aaguid,
- ...credIdLength,
- ...credIdBytes,
- ...coseKey
- ]);
-
- // CBOR encode attestation object: {fmt: "none", authData: bytes, attStmt: {}}
- // Need to properly encode the authData length as a CBOR byte string
- let authDataLengthBytes: number[];
- if (authData.length <= 23) {
- authDataLengthBytes = [0x40 | authData.length];
- } else if (authData.length <= 255) {
- authDataLengthBytes = [0x58, authData.length];
- } else {
- authDataLengthBytes = [0x59, authData.length >> 8, authData.length & 0xff];
- }
+ const xCoord = base64UrlToBytes(publicKeyJwk.x!);
+ const yCoord = base64UrlToBytes(publicKeyJwk.y!);
+
+ /*
+ * COSE public key (ES256 format) - proper CBOR encoding
+ * Map with 5 entries: kty(1), alg(3), crv(-1), x(-2), y(-3)
+ * CBOR negative integers: -1 = 0x20, -2 = 0x21, -3 = 0x22, -7 = 0x26
+ * Keys must be in canonical order (by encoded byte value)
+ */
+ const coseKey = new Uint8Array([
+ 0xa5, // map(5)
+ 0x01, // key: 1 (kty - key type)
+ 0x02, // value: 2 (EC2 - Elliptic Curve Keys with x and y coordinate pair)
+ 0x03, // key: 3 (alg - algorithm)
+ 0x26, // value: -7 (ES256 - ECDSA w/ SHA-256)
+ 0x20, // key: -1 (crv - curve)
+ 0x01, // value: 1 (P-256)
+ 0x21, // key: -2 (x-coordinate)
+ 0x58, 0x20, // byte string(32)
+ ...xCoord, // x coordinate (32 bytes)
+ 0x22, // key: -3 (y-coordinate)
+ 0x58, 0x20, // byte string(32)
+ ...yCoord // y coordinate (32 bytes)
+ ]);
- // Check what attestation format is requested
- const attestationPreference = request.publicKey.attestation || 'none';
- console.log('PasskeyCreate: attestation preference', attestationPreference);
-
- let attestationObject: Uint8Array;
-
- if (attestationPreference === 'none' || attestationPreference === 'indirect') {
- // Use "none" attestation format (simplest, most privacy-preserving)
- // CBOR map keys must be in canonical order (sorted by byte length, then lexicographically)
- // Order: "fmt" (3 chars), "attStmt" (7 chars), "authData" (8 chars)
- attestationObject = new Uint8Array([
- 0xa3, // map(3)
- 0x63, 0x66, 0x6d, 0x74, // "fmt" (text(3))
- 0x64, 0x6e, 0x6f, 0x6e, 0x65, // "none" (text(4))
- 0x67, 0x61, 0x74, 0x74, 0x53, 0x74, 0x6d, 0x74, // "attStmt" (text(7))
- 0xa0, // map(0) - empty map
- 0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61, // "authData" (text(8))
- ...authDataLengthBytes, ...authData // byte string with proper length encoding
+ // Construct authData
+ const credIdLength = new Uint8Array([0, credIdBytes.length]);
+ const authData = new Uint8Array([
+ ...rpIdHash,
+ ...flags,
+ ...signCount,
+ ...aaguid,
+ ...credIdLength,
+ ...credIdBytes,
+ ...coseKey
]);
- } else {
- // Use "packed" attestation format with self-attestation
- // Create signature over authData + clientDataHash
+
+ /*
+ * CBOR encode attestation object: {fmt: "none", authData: bytes, attStmt: {}}
+ * Need to properly encode the authData length as a CBOR byte string
+ */
+ let authDataLengthBytes: number[];
+ if (authData.length <= 23) {
+ authDataLengthBytes = [0x40 | authData.length];
+ } else if (authData.length <= 255) {
+ authDataLengthBytes = [0x58, authData.length];
+ } else {
+ authDataLengthBytes = [0x59, authData.length >> 8, authData.length & 0xff];
+ }
+
+ // Create clientDataJSON (used for both signature and response)
const clientDataJSON = JSON.stringify({
type: 'webauthn.create',
challenge: request.publicKey.challenge,
origin: request.origin
});
- const clientDataHash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(clientDataJSON));
- const dataToSign = new Uint8Array([...authData, ...new Uint8Array(clientDataHash)]);
-
- // Sign with the credential's private key (self-attestation)
- const attSignature = await crypto.subtle.sign(
- { name: 'ECDSA', hash: 'SHA-256' },
- keyPair.privateKey,
- dataToSign
- );
- // Convert to DER format
- const rawSig = new Uint8Array(attSignature);
- const r = rawSig.slice(0, 32);
- const s = rawSig.slice(32, 64);
-
- const encodeInteger = (int: Uint8Array): Uint8Array => {
- let i = 0;
- while (i < int.length && int[i] === 0) i++;
- let trimmed = int.slice(i);
- if (trimmed.length === 0) trimmed = new Uint8Array([0]);
- if (trimmed[0] & 0x80) {
- const padded = new Uint8Array(trimmed.length + 1);
- padded[0] = 0;
- padded.set(trimmed, 1);
- trimmed = padded;
- }
- return new Uint8Array([0x02, trimmed.length, ...trimmed]);
- };
-
- const rDer = encodeInteger(r);
- const sDer = encodeInteger(s);
- const derSignature = new Uint8Array([0x30, rDer.length + sDer.length, ...rDer, ...sDer]);
-
- // CBOR encode "packed" attestation object with self-attestation
- // attStmt: { alg: -7, sig: derSignature }
- const sigLengthBytes = derSignature.length <= 23
- ? [0x40 | derSignature.length]
- : [0x58, derSignature.length];
-
- attestationObject = new Uint8Array([
- 0xa3, // map(3)
- 0x63, 0x66, 0x6d, 0x74, // "fmt" (text(3))
- 0x66, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x64, // "packed" (text(6))
- 0x67, 0x61, 0x74, 0x74, 0x53, 0x74, 0x6d, 0x74, // "attStmt" (text(7))
- 0xa2, // map(2) - alg and sig
- 0x63, 0x61, 0x6c, 0x67, // "alg" (text(3))
- 0x26, // -7 (ES256)
- 0x63, 0x73, 0x69, 0x67, // "sig" (text(3))
- ...sigLengthBytes, ...derSignature, // byte string
- 0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61, // "authData" (text(8))
- ...authDataLengthBytes, ...authData // byte string with proper length encoding
- ]);
- }
-
- const credential = {
- id: credentialId,
- rawId: credentialId,
- clientDataJSON: btoa(JSON.stringify({
- type: 'webauthn.create',
- challenge: request.publicKey.challenge,
- origin: request.origin
- })),
- attestationObject: btoa(String.fromCharCode(...attestationObject))
- };
+ // Check what attestation format is requested
+ const attestationPreference = request.publicKey.attestation || 'none';
+ console.log('PasskeyCreate: attestation preference', attestationPreference);
+
+ let attestationObject: Uint8Array;
+
+ if (attestationPreference === 'none' || attestationPreference === 'indirect') {
+ /*
+ * Use "none" attestation format (simplest, most privacy-preserving)
+ * CRITICAL: CBOR map keys MUST be in lexicographic order of encoded bytes
+ * The spec says: (fmt, attStmt, authData) NOT (fmt, authData, attStmt)
+ * See: https://www.w3.org/TR/webauthn-2/#sctn-attestation-formats
+ * Encoded key bytes: "authData" = 0x68..., "attStmt" = 0x67..., "fmt" = 0x63...
+ * Sorted order by first byte: 0x63 < 0x67 < 0x68
+ */
+ attestationObject = new Uint8Array([
+ 0xa3, // map(3)
+ 0x63, 0x66, 0x6d, 0x74, // "fmt" (text(3)) - 0x636d74
+ 0x64, 0x6e, 0x6f, 0x6e, 0x65, // "none" (text(4))
+ 0x67, 0x61, 0x74, 0x74, 0x53, 0x74, 0x6d, 0x74, // "attStmt" (text(7)) - 0x6761747453746d74
+ 0xa0, // map(0) - empty map
+ 0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61, // "authData" (text(8)) - 0x6861757468446174
+ ...authDataLengthBytes, ...authData // byte string with proper length encoding
+ ]);
+ } else {
+ /*
+ * Use "packed" attestation format with self-attestation
+ * Create signature over authData + clientDataHash
+ */
+ const clientDataHash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(clientDataJSON));
+ const dataToSign = new Uint8Array([...authData, ...new Uint8Array(clientDataHash)]);
+
+ // Sign with the credential's private key (self-attestation)
+ const attSignature = await crypto.subtle.sign(
+ { name: 'ECDSA', hash: 'SHA-256' },
+ keyPair.privateKey,
+ dataToSign
+ );
+
+ // Convert to DER format
+ const rawSig = new Uint8Array(attSignature);
+ const r = rawSig.slice(0, 32);
+ const s = rawSig.slice(32, 64);
+
+ /**
+ *
+ */
+ const encodeInteger = (int: Uint8Array): Uint8Array => {
+ // Remove leading zeros but keep at least one byte
+ let i = 0;
+ while (i < int.length - 1 && int[i] === 0 && (int[i + 1] & 0x80) === 0) {
+ i++;
+ }
+ let trimmed = int.slice(i);
+
+ // If high bit is set, add zero padding to keep it positive
+ if (trimmed[0] & 0x80) {
+ const padded = new Uint8Array(trimmed.length + 1);
+ padded[0] = 0;
+ padded.set(trimmed, 1);
+ trimmed = padded;
+ }
- // Store passkey with the private key for future authentication
- await sendMessage('STORE_PASSKEY', {
- rpId,
- credentialId,
- displayName,
- publicKey: publicKeyJwk as JsonWebKey,
- privateKey: privateKeyJwk as JsonWebKey
- } as any, 'background');
+ return new Uint8Array([0x02, trimmed.length, ...trimmed]);
+ };
+
+ const rDer = encodeInteger(r);
+ const sDer = encodeInteger(s);
+ const derSignature = new Uint8Array([0x30, rDer.length + sDer.length, ...rDer, ...sDer]);
+
+ /*
+ * CBOR encode "packed" attestation object with self-attestation
+ * IMPORTANT: CBOR map keys must be in canonical order:
+ * 1. Sort by length (shortest first)
+ * 2. Within same length, sort lexicographically
+ * Order: "fmt" (3) < "alg" (3), "sig" (3) < "attStmt" (7) < "authData" (8)
+ */
+
+ const sigLengthBytes = derSignature.length <= 23
+ ? [0x40 | derSignature.length]
+ : [0x58, derSignature.length];
+
+ attestationObject = new Uint8Array([
+ 0xa3, // map(3)
+ // Key 1: "fmt" (3 bytes)
+ 0x63, 0x66, 0x6d, 0x74, // "fmt" (text(3))
+ 0x66, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x64, // "packed" (text(6))
+ // Key 2: "attStmt" (7 bytes)
+ 0x67, 0x61, 0x74, 0x74, 0x53, 0x74, 0x6d, 0x74, // "attStmt" (text(7))
+ 0xa2, // map(2) - alg and sig, also in canonical order
+ 0x63, 0x61, 0x6c, 0x67, // "alg" (text(3)) - comes before "sig"
+ 0x26, // -7 (ES256)
+ 0x63, 0x73, 0x69, 0x67, // "sig" (text(3))
+ ...sigLengthBytes, ...derSignature, // byte string
+ // Key 3: "authData" (8 bytes)
+ 0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61, // "authData" (text(8))
+ ...authDataLengthBytes, ...authData // byte string with proper length encoding
+ ]);
+ }
- // Send response back
- await sendMessage('PASSKEY_POPUP_RESPONSE', {
- requestId: request.requestId,
- credential
- }, 'background');
+ const credential = {
+ id: credentialId,
+ rawId: credentialId,
+ clientDataJSON: btoa(clientDataJSON),
+ attestationObject: btoa(String.fromCharCode(...attestationObject))
+ };
- window.close();
+ // Debug logging
+ console.info('PasskeyCreate: Created credential');
+ console.info('PasskeyCreate: credentialId length:', credentialId.length);
+ console.info('PasskeyCreate: attestationObject length:', attestationObject.length);
+ console.info('PasskeyCreate: attestation format:', attestationPreference);
+ console.info('PasskeyCreate: rpId:', rpId);
+ console.info('PasskeyCreate: origin:', request.origin);
+
+ // Store passkey with the private key for future authentication
+ await sendMessage('STORE_PASSKEY', {
+ rpId,
+ credentialId,
+ displayName,
+ publicKey: publicKeyJwk as JsonWebKey,
+ privateKey: privateKeyJwk as JsonWebKey
+ } as any, 'background');
+
+ // Send response back
+ await sendMessage('PASSKEY_POPUP_RESPONSE', {
+ requestId: request.requestId,
+ credential
+ }, 'background');
+
+ window.close();
+ } catch (error) {
+ console.error('PasskeyCreate: Error creating passkey', error);
+ setLoading(false);
+ alert(`Failed to create passkey: ${error instanceof Error ? error.message : String(error)}`);
+ }
};
/**
diff --git a/apps/browser-extension/src/entrypoints/webauthn-inject.ts b/apps/browser-extension/src/entrypoints/webauthn-inject.ts
index b064c0f6b..76e7fd30e 100644
--- a/apps/browser-extension/src/entrypoints/webauthn-inject.ts
+++ b/apps/browser-extension/src/entrypoints/webauthn-inject.ts
@@ -123,20 +123,35 @@ export default defineUnlistedScript(() => {
response: {
clientDataJSON: base64ToBuffer(cred.clientDataJSON),
attestationObject: base64ToBuffer(cred.attestationObject),
+ /**
+ *
+ */
getTransports() {
return ['internal'];
},
+ /**
+ *
+ */
getAuthenticatorData() {
// Parse authData from attestation object if needed
return new ArrayBuffer(0);
},
+ /**
+ *
+ */
getPublicKey() {
return null;
},
+ /**
+ *
+ */
getPublicKeyAlgorithm() {
return -7; // ES256
}
},
+ /**
+ *
+ */
getClientExtensionResults() {
return {};
}
@@ -228,6 +243,9 @@ export default defineUnlistedScript(() => {
signature: base64ToBuffer(cred.signature),
userHandle: cred.userHandle ? base64ToBuffer(cred.userHandle) : null
},
+ /**
+ *
+ */
getClientExtensionResults() {
return {};
}