Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor passkey creation and retrieval to dedicated class (#520)
Leendert de Borst4ebb02795a25
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsxindex ef0af42be..cdb134df7 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx@@ -6,6 +6,9 @@ import Button from '@/entrypoints/popup/components/Button';import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';import { useLoading } from '@/entrypoints/popup/context/LoadingContext';+import { AliasVaultPasskeyProvider } from '@/utils/passkey/AliasVaultPasskeyProvider';+import type { GetRequest, StoredPasskeyRecord } from '@/utils/passkey/types';+interface IPasskeyRequest {type: 'get';requestId: string;@@ -17,9 +20,8 @@ interface IPasskeyRequest {lastUsed: string | null;}>;}-/**- * TODO: review this file+ **/const PasskeyAuthenticate: React.FC = () => {const location = useLocation();@@ -86,108 +88,36 @@ const PasskeyAuthenticate: React.FC = () => {console.log('PasskeyAuthenticate: selectedPasskey', selectedPasskey);console.log('PasskeyAuthenticate: request', request);- // Get the stored passkey to access the private key- const passkeyData = await sendMessage('GET_PASSKEY_BY_ID', { credentialId: selectedPasskey }, 'background');-- if (!passkeyData) {- console.error('Passkey not found');- setLoading(false);- return;- }-- // 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 always 0 - disabled to ensure compatibility when syncing passkeys across devices- const signCount = new Uint8Array([0, 0, 0, 0]);-- // 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+ // Create the provider with storage callbacks+ const provider = new AliasVaultPasskeyProvider(+ async (record: StoredPasskeyRecord) => {+ // Not used during authentication+ await sendMessage('STORE_PASSKEY', record as any, 'background');+ },+ async (credentialId: string) => {+ const result = await sendMessage('GET_PASSKEY_BY_ID', { credentialId }, 'background');+ return result || null;+ });- // 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;+ // Build the GetRequest+ const getRequest: GetRequest = {+ origin: request.origin,+ requestId: request.requestId,+ publicKey: {+ rpId: request.publicKey.rpId,+ challenge: request.publicKey.challenge,+ userVerification: request.publicKey.userVerification}-- // 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- };+ // Get the assertion using the provider+ const credential = await provider.getAssertion(getRequest, selectedPasskey, {+ uvPerformed: false, // Set to true if you implement actual user verification+ includeBEBS: true // Include backup-eligible and backup-state flags+ });++ console.info('PasskeyAuthenticate: Created credential successfully', credential);// Update last used timestampawait sendMessage('UPDATE_PASSKEY_LAST_USED', {diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsxindex 7508f5168..2e5e08a16 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx@@ -7,6 +7,9 @@ import { FormInput } from '@/entrypoints/popup/components/FormInput';import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';import { useLoading } from '@/entrypoints/popup/context/LoadingContext';+import { AliasVaultPasskeyProvider } from '@/utils/passkey/AliasVaultPasskeyProvider';+import type { CreateRequest, StoredPasskeyRecord } from '@/utils/passkey/types';+interface IPasskeyRequest {type: 'create';requestId: string;@@ -62,7 +65,7 @@ const PasskeyCreate: React.FC = () => {}, [location, setIsInitialLoading]);/**- *+ * Handle passkey creation*/const handleCreate = async () => {if (!request) {@@ -75,233 +78,61 @@ const PasskeyCreate: React.FC = () => {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'+ // Create the provider with storage callbacks+ const provider = new AliasVaultPasskeyProvider(+ async (record: StoredPasskeyRecord) => {+ await sendMessage('STORE_PASSKEY', {+ rpId: record.rpId,+ credentialId: record.credentialId,+ displayName,+ publicKey: record.publicKey,+ privateKey: record.privateKey,+ userId: record.userId,+ userName: record.userName,+ userDisplayName: record.userDisplayName+ } as any, 'background');},- true, // extractable- ['sign', 'verify']+ async (credentialId: string) => {+ const result = await sendMessage('GET_PASSKEY_BY_ID', { credentialId }, 'background');+ return result || null;+ });- // 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- // Sign count always 0 - disabled to ensure compatibility when syncing passkeys across devices- 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)));+ // Build the CreateRequest+ const createRequest: CreateRequest = {+ origin: request.origin,+ requestId: request.requestId,+ publicKey: {+ rp: request.publicKey.rp,+ user: request.publicKey.user,+ challenge: request.publicKey.challenge,+ pubKeyCredParams: request.publicKey.pubKeyCredParams,+ attestation: request.publicKey.attestation,+ authenticatorSelection: request.publicKey.authenticatorSelection+ }};- 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)- ]);-- // 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];- }-- // Create clientDataJSON (used for both signature and response)- const clientDataJSON = JSON.stringify({- type: 'webauthn.create',- challenge: request.publicKey.challenge,- origin: request.origin+ // Create the passkey using the provider+ const { credential } = await provider.createPasskey(createRequest, {+ uvPerformed: false // Set to true if you implement actual user verification});- // 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;- }-- 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- ]);- }+ console.info('PasskeyCreate: Created credential successfully', credential);- const credential = {- id: credentialId,- rawId: credentialId,- clientDataJSON: btoa(clientDataJSON),- attestationObject: btoa(String.fromCharCode(...attestationObject))+ // Flatten credential structure for injection script compatibility+ // The injection script expects: { id, rawId, clientDataJSON, attestationObject }+ // But the provider returns: { id, rawId, response: { clientDataJSON, attestationObject }, type }+ const flattenedCredential = {+ id: credential.id,+ rawId: credential.rawId,+ clientDataJSON: credential.response.clientDataJSON,+ attestationObject: credential.response.attestationObject};- // 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+ // Send response back with the flattened credentialawait sendMessage('PASSKEY_POPUP_RESPONSE', {requestId: request.requestId,- credential+ credential: flattenedCredential}, 'background');window.close();diff --git a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.tsnew file mode 100644index 000000000..51b8fe29d--- /dev/null+++ b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts@@ -0,0 +1,464 @@+/**+ * AliasVaultPasskeyProvider+ * -------------------------+ * A small self-contained WebAuthn "virtual authenticator" for a browser extension.+ * It can create ("register") and use ("authenticate") passkeys. The class focuses on:+ * - Correct WebAuthn data assembly (authenticatorData, attestationObject, clientDataJSON)+ * - Proper CBOR/COSE encoding for ES256 keys+ * - Dynamic flags for UV/UP/AT/BE/BS+ * - Consistent base64url/base64 handling+ *+ * NOTE:+ * - This class does not handle UI concerns or message passing. Inject storage callbacks so you+ * can persist and retrieve passkeys (keys + metadata) in your extension background.+ * - By design, signCount is always 0 (clone detection disabled) for syncable passkeys.+ * - Attestation defaults to "none" (privacy-preserving). If an RP requests "direct", we do a+ * "packed" *self* attestation using the generated credential private key (no x5c chain).+ * - For authentication ("get"), we also set BE/BS bits to indicate backup-eligible & backed-up.+ */++import type { CreateRequest, GetRequest, StoredPasskeyRecord } from './types';++/**+ *+ */+export class AliasVaultPasskeyProvider {+ /**+ * Inject your storage layer via callbacks.+ * - store: persist a newly created passkey+ * - getById: fetch a stored passkey (by credentialId)+ */+ constructor(+ private readonly store: (record: StoredPasskeyRecord) => Promise<void>,+ private readonly getById: (credentialId: string) => Promise<StoredPasskeyRecord | null>+ ) {}++ /*+ * ------------------------------------------------------------------------------------+ * Public API+ * ------------------------------------------------------------------------------------+ */++ /**+ * Create a new passkey (registration). Returns a credential-like object similar to+ * navigator.credentials.create() output, ready to be posted to the RP.+ *+ * It also calls `this.store(...)` to persist the passkey (private/public keys, ids, etc).+ */+ public async createPasskey(+ req: CreateRequest,+ opts?: { uvPerformed?: boolean; credentialIdBytes?: number } // uvPerformed: only set to true if your app did real UV+ ): Promise<{+ credential: {+ id: string;+ rawId: string; // base64url for transport (pages usually expect ArrayBuffers; adapt as needed)+ response: {+ clientDataJSON: string; // base64 (UTF-8 JSON)+ attestationObject: string; // base64 (CBOR)+ };+ type: 'public-key';+ };+ stored: StoredPasskeyRecord;+ }> {+ // 1) Validate and resolve algorithm (-7 = ES256)+ const alg = this.pickSupportedAlgorithm(req.publicKey.pubKeyCredParams);++ // 2) Determine RP ID (domain) and hash it+ const rpId = req.publicKey.rp?.id || new URL(req.origin).hostname;+ const rpIdHash = new Uint8Array(await crypto.subtle.digest('SHA-256', this.te(rpId)));++ // 3) Key pair generation (ES256 / P-256)+ const keyPair = await crypto.subtle.generateKey(+ { name: 'ECDSA', namedCurve: 'P-256' },+ true,+ ['sign', 'verify']+ );+ const pubJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);+ const prvJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);++ // 4) Generate a credentialId (random bytes; default 16)+ const credLen = Math.max(8, Math.min(opts?.credentialIdBytes ?? 16, 64));+ const credIdBytes = crypto.getRandomValues(new Uint8Array(credLen));+ const credentialIdB64u = this.toB64u(credIdBytes);++ // 5) COSE public key (CBOR) from JWK (ES256 / P-256)+ const coseKey = this.buildCoseEc2Es256(pubJwk);++ /*+ * 6) Flags (creation): UP (bit0)=1, UV (bit2) depends on policy, AT (bit6)=1, BE/BS optional+ * - UV rules: set to 1 only if req requires it OR we actually performed UV (opts.uvPerformed)+ */+ let flags = 0x41; // UP + AT+ const uvReq = req.publicKey.authenticatorSelection?.userVerification;+ const uvPerformed = !!opts?.uvPerformed;+ if (uvReq === 'required' || (uvReq === 'preferred' && uvPerformed)) {+ flags |= 0x04; // UV+ }+ // For passkeys (syncable), we may set BE (0x08) and BS (0x10) to 1 to indicate backup-eligible & backed-up+ flags |= 0x08; // BE+ flags |= 0x10; // BS++ const signCount = new Uint8Array([0, 0, 0, 0]); // 0 for syncable credentials++ // 7) AttestedCredentialData = AAGUID(16 zeros) + credIdLen(2) + credId + COSEKey+ const aaguid = new Uint8Array(16); // all zeros in "none" attestation+ const credIdLenBytes = new Uint8Array([(credIdBytes.length >> 8) & 0xff, credIdBytes.length & 0xff]);+ const attestedCredData = this.concat(aaguid, credIdLenBytes, credIdBytes, coseKey);++ // 8) authenticatorData = rpIdHash (32) + flags (1) + signCount (4) + attestedCredData+ const authenticatorData = this.concat(rpIdHash, new Uint8Array([flags]), signCount, attestedCredData);++ // 9) clientDataJSON (stringify with challenge as base64url)+ const challengeB64u = this.asB64u(req.publicKey.challenge);+ const clientDataObj = {+ type: 'webauthn.create',+ challenge: challengeB64u,+ origin: req.origin,+ crossOrigin: false+ };+ const clientDataJSONStr = JSON.stringify(clientDataObj);+ const clientDataJSONBytes = this.te(clientDataJSONStr);++ // 10) Build attestationObject (CBOR map with "fmt","attStmt","authData")+ const attPref = req.publicKey.attestation || 'none';+ const attObjBytes =+ attPref === 'none' || attPref === 'indirect'+ ? this.buildAttObjNone(authenticatorData)+ : await this.buildAttObjPackedSelf(authenticatorData, clientDataJSONBytes, keyPair.privateKey);++ // 11) Store the passkey in your vault (so it can be used later for authentication)+ const stored: StoredPasskeyRecord = {+ rpId,+ credentialId: credentialIdB64u,+ publicKey: pubJwk,+ privateKey: prvJwk,+ userId: req.publicKey.user?.id ?? null,+ userName: req.publicKey.user?.name,+ userDisplayName: req.publicKey.user?.displayName,+ lastUsedAt: Date.now()+ };+ await this.store(stored);++ // 12) Return a credential-like object (base64-encoded fields for transport)+ const credential = {+ id: credentialIdB64u,+ rawId: credentialIdB64u,+ response: {+ clientDataJSON: this.toB64(clientDataJSONBytes),+ attestationObject: this.toB64(attObjBytes)+ },+ type: 'public-key' as const+ };++ return { credential, stored };+ }++ /**+ * Create an assertion (authentication) with a stored passkey.+ *+ * Returns the flat object shape your client example expects:+ * {+ * id, rawId, clientDataJSON, authenticatorData, signature, userHandle+ * }+ *+ * NOTE:+ * - The "standard" WebAuthn shape would nest these in `response` and use ArrayBuffers.+ * You can adapt this output to that shape if the page expects the standard structure.+ */+ public async getAssertion(+ req: GetRequest,+ credentialIdB64u: string,+ opts?: { uvPerformed?: boolean; includeBEBS?: boolean }+ ): Promise<{+ id: string;+ rawId: string;+ clientDataJSON: string; // base64+ authenticatorData: string; // base64+ signature: string; // base64 (DER)+ userHandle: string | null; // base64 (if you choose to return it)+ }> {+ // 1) Load passkey+ const rec = await this.getById(credentialIdB64u);+ if (!rec) {+ throw new Error('Passkey not found');+ }++ // 2) rpId & hash+ const rpId = req.publicKey.rpId || new URL(req.origin).hostname;+ const rpIdHash = new Uint8Array(await crypto.subtle.digest('SHA-256', this.te(rpId)));++ // 3) Flags (assertion): UP=1, UV depends on request & policy, BE/BS for syncable, AT=0 for auth+ let flags = 0x01; // UP+ const uvReq = req.publicKey.userVerification;+ const uvPerformed = !!opts?.uvPerformed;+ if (uvReq === 'required' || (uvReq === 'preferred' && uvPerformed)) {+ flags |= 0x04;+ } // UV+ if (opts?.includeBEBS ?? true) {+ flags |= 0x08; // BE+ flags |= 0x10; // BS+ }+ const signCount = new Uint8Array([0, 0, 0, 0]); // always 0 (sync-friendly)++ // 4) authenticatorData = rpIdHash + flags + signCount+ const authenticatorData = this.concat(rpIdHash, new Uint8Array([flags]), signCount);++ // 5) clientDataJSON+ const challengeB64u = this.asB64u(req.publicKey.challenge);+ const clientDataObj = {+ type: 'webauthn.get',+ challenge: challengeB64u,+ origin: req.origin,+ crossOrigin: false+ };+ const clientDataJSONStr = JSON.stringify(clientDataObj);+ const clientDataJSONBytes = this.te(clientDataJSONStr);++ // 6) Signature over authenticatorData || SHA256(clientDataJSON)+ const clientDataHash = new Uint8Array(await crypto.subtle.digest('SHA-256', clientDataJSONBytes));+ const toSign = this.concat(authenticatorData, clientDataHash);++ const privateKey = await crypto.subtle.importKey(+ 'jwk',+ rec.privateKey,+ { name: 'ECDSA', namedCurve: 'P-256' },+ false,+ ['sign']+ );+ const rawSig = new Uint8Array(+ await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, toSign)+ );++ // 7) Convert raw (r|s) to DER sequence+ const derSig = this.ecdsaRawToDer(rawSig);++ /*+ * (Optional) Update last used timestamp in your own layer+ * (not done here; call a provided callback if you like)+ */++ // 8) Return object in the flat shape (base64 strings), as your client example expects+ return {+ id: credentialIdB64u,+ rawId: credentialIdB64u,+ clientDataJSON: this.toB64(clientDataJSONBytes),+ authenticatorData: this.toB64(authenticatorData),+ signature: this.toB64(derSig),+ userHandle: null // optionally encode/stash rec.userId and return as base64 if needed+ };+ }++ /*+ * ------------------------------------------------------------------------------------+ * Internal helpers (encoding, CBOR/COSE, DER, utils)+ * ------------------------------------------------------------------------------------+ */++ /** Ensure ES256 (-7) is available; else throw (or extend to support others). */+ private pickSupportedAlgorithm(params?: Array<{ type: 'public-key'; alg: number }>): number {+ if (!params || params.length === 0) {+ return -7;+ } // assume ES256 default+ const hasEs256 = params.some(p => p.type === 'public-key' && p.alg === -7);+ if (!hasEs256) {+ throw new Error('No supported algorithm (ES256) in pubKeyCredParams');+ }+ return -7;+ }++ /** Build COSE EC2 public key for ES256: {1:2, 3:-7, -1:1, -2:x, -3:y} in CBOR. */+ private buildCoseEc2Es256(jwk: JsonWebKey): Uint8Array {+ const x = this.pad32(this.fromB64u(jwk.x!));+ const y = this.pad32(this.fromB64u(jwk.y!));+ /*+ * Map(5): 0xa5+ * 1:2 (kty: EC2)+ * 3:-7 (alg: ES256)+ * -1:1 (crv: P-256)+ * -2:x(32) (x)+ * -3:y(32) (y)+ */+ return new Uint8Array([+ 0xa5,+ 0x01, 0x02, // 1: 2+ 0x03, 0x26, // 3: -7+ 0x20, 0x01, // -1: 1+ 0x21, 0x58, 0x20, ...x, // -2: bstr(32) x+ 0x22, 0x58, 0x20, ...y // -3: bstr(32) y+ ]);+ }++ /** Build "none" attestation object: { fmt: "none", attStmt: {}, authData: <bytes> } (CBOR). */+ private buildAttObjNone(authenticatorData: Uint8Array): Uint8Array {+ const fmtKey = this.cborText('fmt'); // "fmt"+ const fmtVal = this.cborText('none'); // "none"+ const attStmtKey = this.cborText('attStmt'); // "attStmt"+ const attStmtVal = new Uint8Array([0xa0]); // map(0) {}+ const authDataKey = this.cborText('authData'); // "authData"+ const authDataVal = this.cborBstr(authenticatorData);++ // map(3)+ return this.concat(+ new Uint8Array([0xa3]),+ fmtKey, fmtVal,+ attStmtKey, attStmtVal,+ authDataKey, authDataVal+ );+ }++ /** Build "packed" self-attestation object (no x5c). */+ private async buildAttObjPackedSelf(+ authenticatorData: Uint8Array,+ clientDataJSON: Uint8Array,+ privateKey: CryptoKey+ ): Promise<Uint8Array> {+ // Signature over authenticatorData || SHA256(clientDataJSON)+ const clientDataHash = new Uint8Array(await crypto.subtle.digest('SHA-256', clientDataJSON));+ const toSign = this.concat(authenticatorData, clientDataHash);+ const rawSig = new Uint8Array(+ await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, toSign)+ );+ const derSig = this.ecdsaRawToDer(rawSig);++ // attStmt = { alg: -7, sig: <derSig> }+ const attStmtMap = this.concat(+ this.cborText('alg'), new Uint8Array([0x26]), // -7+ this.cborText('sig'), this.cborBstr(derSig)+ );+ // prepend map(2)+ const attStmt = this.concat(new Uint8Array([0xa2]), attStmtMap);++ // final: { fmt:"packed", attStmt:{...}, authData:<bytes> }+ const fmtKey = this.cborText('fmt');+ const fmtVal = this.cborText('packed');+ const attStmtKey = this.cborText('attStmt');+ const authDataKey = this.cborText('authData');+ const authDataVal = this.cborBstr(authenticatorData);++ return this.concat(+ new Uint8Array([0xa3]), // map(3)+ fmtKey, fmtVal,+ attStmtKey, attStmt,+ authDataKey, authDataVal+ );+ }++ // ----- CBOR small helpers -----++ /** Encode a UTF-8 string as CBOR text. */+ private cborText(s: string): Uint8Array {+ const bytes = this.te(s);+ if (bytes.length <= 23) {+ return new Uint8Array([0x60 | bytes.length, ...bytes]);+ } // major type 3+ if (bytes.length <= 0xff) {+ return new Uint8Array([0x78, bytes.length, ...bytes]);+ }+ return new Uint8Array([0x79, (bytes.length >> 8) & 0xff, bytes.length & 0xff, ...bytes]);+ }++ /** Encode a byte string as CBOR bstr. */+ private cborBstr(b: Uint8Array): Uint8Array {+ if (b.length <= 23) {+ return new Uint8Array([0x40 | b.length, ...b]);+ } // major type 2+ if (b.length <= 0xff) {+ return new Uint8Array([0x58, b.length, ...b]);+ }+ return new Uint8Array([0x59, (b.length >> 8) & 0xff, b.length & 0xff, ...b]);+ }++ // ----- DER helpers -----++ /** Convert raw ECDSA signature (r|s, 64 bytes) to DER SEQUENCE. */+ private ecdsaRawToDer(raw: Uint8Array): Uint8Array {+ if (raw.length !== 64) {+ throw new Error('Unexpected ECDSA signature length');+ }+ const r = raw.slice(0, 32);+ const s = raw.slice(32, 64);+ const rDer = this.derInt(r);+ const sDer = this.derInt(s);+ return new Uint8Array([0x30, rDer.length + sDer.length, ...rDer, ...sDer]);+ }++ /** Encode a positive big integer to DER INTEGER. */+ private derInt(src: Uint8Array): Uint8Array {+ // Trim leading zeros+ let i = 0;+ while (i < src.length - 1 && src[i] === 0x00) {+ i++;+ }+ let v = src.slice(i);+ // If MSB set, prepend 0 to keep it positive+ if ((v[0] & 0x80) !== 0) {+ v = this.concat(new Uint8Array([0x00]), v);+ }+ return new Uint8Array([0x02, v.length, ...v]);+ }++ // ----- Base64 / Base64url helpers -----++ /** UTF-8 encode string to bytes. */+ private te(s: string): Uint8Array {+ return new TextEncoder().encode(s);+ }++ /** Base64 encode bytes (Uint8Array) to ASCII string. */+ private toB64(bytes: Uint8Array): string {+ let bin = '';+ for (let i = 0; i < bytes.length; i++) {+ bin += String.fromCharCode(bytes[i]);+ }+ return btoa(bin);+ }++ /** Base64url encode bytes. */+ private toB64u(bytes: Uint8Array): string {+ return this.toB64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');+ }++ /** Base64url decode to bytes. */+ private fromB64u(b64u: string): Uint8Array {+ const b64 = b64u.replace(/-/g, '+').replace(/_/g, '/');+ const pad = b64.length % 4 === 2 ? '==' : b64.length % 4 === 3 ? '=' : '';+ const s = atob(b64 + pad);+ const out = new Uint8Array(s.length);+ for (let i = 0; i < s.length; i++) {+ out[i] = s.charCodeAt(i);+ }+ return out;+ }++ /** Normalize unknown challenge types to base64url string. */+ private asB64u(challenge: ArrayBuffer | Uint8Array | string): string {+ if (typeof challenge === 'string') {+ // Assume already base64url. If you need robustness, validate and convert if not.+ return challenge;+ }+ const bytes = challenge instanceof Uint8Array ? challenge : new Uint8Array(challenge);+ return this.toB64u(bytes);+ }++ /** Left-pad to 32 bytes (P-256 coord). */+ private pad32(b: Uint8Array): Uint8Array {+ if (b.length === 32) {+ return b;+ }+ const out = new Uint8Array(32);+ out.set(b, 32 - b.length);+ return out;+ }++ /** Concatenate typed arrays. */+ private concat(...chunks: Uint8Array[]): Uint8Array {+ const total = chunks.reduce((s, c) => s + c.length, 0);+ const out = new Uint8Array(total);+ let o = 0;+ for (const c of chunks) {+ out.set(c, o);+ o += c.length;+ }+ return out;+ }+}diff --git a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.tsnew file mode 100644index 000000000..650d5634b--- /dev/null+++ b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts@@ -0,0 +1,610 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++import { AliasVaultPasskeyProvider } from '../AliasVaultPasskeyProvider';++import type { CreateRequest, GetRequest, StoredPasskeyRecord } from '../types';++describe('AliasVaultPasskeyProvider', () => {+ let storedPasskeys: Map<string, StoredPasskeyRecord>;+ let provider: AliasVaultPasskeyProvider;++ beforeEach(() => {+ storedPasskeys = new Map();++ // Create provider with mock storage callbacks+ provider = new AliasVaultPasskeyProvider(+ async (record: StoredPasskeyRecord) => {+ storedPasskeys.set(record.credentialId, record);+ },+ async (credentialId: string) => {+ return storedPasskeys.get(credentialId) || null;+ }+ );+ });++ describe('createPasskey', () => {+ it('should create a valid passkey with correct structure', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ requestId: 'test-request-123',+ publicKey: {+ rp: { id: 'example.com', name: 'Example Corp' },+ user: {+ id: 'user-123',+ name: '[email protected]',+ displayName: 'Test User'+ },+ challenge: 'random-challenge-base64url',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }],+ attestation: 'none',+ authenticatorSelection: {+ userVerification: 'preferred',+ requireResidentKey: true,+ residentKey: 'required',+ authenticatorAttachment: 'platform'+ }+ }+ };++ const result = await provider.createPasskey(createRequest);++ // Verify credential structure+ expect(result.credential).toBeDefined();+ expect(result.credential.id).toBeDefined();+ expect(result.credential.rawId).toBe(result.credential.id);+ expect(result.credential.type).toBe('public-key');+ expect(result.credential.response).toBeDefined();+ expect(result.credential.response.clientDataJSON).toBeDefined();+ expect(result.credential.response.attestationObject).toBeDefined();++ // Verify stored passkey+ expect(result.stored).toBeDefined();+ expect(result.stored.rpId).toBe('example.com');+ expect(result.stored.credentialId).toBe(result.credential.id);+ expect(result.stored.publicKey).toBeDefined();+ expect(result.stored.privateKey).toBeDefined();+ expect(result.stored.userName).toBe('[email protected]');+ expect(result.stored.userDisplayName).toBe('Test User');++ // Verify keys are valid JWK format+ expect(result.stored.publicKey.kty).toBe('EC');+ expect(result.stored.publicKey.crv).toBe('P-256');+ expect(result.stored.publicKey.x).toBeDefined();+ expect(result.stored.publicKey.y).toBeDefined();+ expect(result.stored.privateKey.d).toBeDefined();++ // Verify passkey was stored+ expect(storedPasskeys.has(result.credential.id)).toBe(true);+ });++ it('should decode and validate clientDataJSON correctly', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ rp: { id: 'example.com', name: 'Example' },+ user: { id: 'user-1', name: 'user', displayName: 'User' },+ challenge: 'test-challenge-123',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);++ // Decode and verify clientDataJSON+ const clientDataJSON = atob(result.credential.response.clientDataJSON);+ const clientData = JSON.parse(clientDataJSON);++ expect(clientData.type).toBe('webauthn.create');+ expect(clientData.challenge).toBe('test-challenge-123');+ expect(clientData.origin).toBe('https://example.com');+ expect(clientData.crossOrigin).toBe(false);+ });++ it('should decode and validate attestationObject structure', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://test.com',+ publicKey: {+ challenge: 'challenge-abc',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);++ // Decode attestation object (base64)+ const attObjBytes = Uint8Array.from(+ atob(result.credential.response.attestationObject),+ c => c.charCodeAt(0)+ );++ // Basic CBOR validation - should start with map marker (0xa3 = map with 3 entries)+ expect(attObjBytes[0]).toBe(0xa3);++ /*+ * The attestation object should contain "fmt", "attStmt", and "authData" keys+ * We can't easily parse CBOR here, but we can verify it's not empty and has expected structure+ */+ expect(attObjBytes.length).toBeGreaterThan(100); // Should contain authData + COSE key+ });++ it('should use rpId from origin if not provided', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://subdomain.example.com',+ publicKey: {+ challenge: 'test-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);++ expect(result.stored.rpId).toBe('subdomain.example.com');+ });++ it('should default to ES256 algorithm when pubKeyCredParams is empty', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'test-challenge',+ pubKeyCredParams: [] // Empty array+ }+ };++ const result = await provider.createPasskey(createRequest);++ // Should still create successfully with ES256+ expect(result.credential).toBeDefined();+ expect(result.stored.publicKey.crv).toBe('P-256');+ });++ it('should throw error when ES256 is not supported', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'test-challenge',+ pubKeyCredParams: [+ { type: 'public-key', alg: -8 }, // EdDSA+ { type: 'public-key', alg: -257 } // RS256+ ]+ }+ };++ await expect(provider.createPasskey(createRequest)).rejects.toThrow(+ 'No supported algorithm (ES256) in pubKeyCredParams'+ );+ });++ it('should set UV flag when userVerification is required', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'test-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }],+ authenticatorSelection: {+ userVerification: 'required'+ }+ }+ };++ const result = await provider.createPasskey(createRequest, { uvPerformed: false });++ // Decode attestation object to check flags+ const attObjBytes = Uint8Array.from(+ atob(result.credential.response.attestationObject),+ c => c.charCodeAt(0)+ );++ /*+ * Find authenticatorData in the CBOR structure+ * This is a simplified check - in real CBOR parsing, you'd properly decode the map+ * The flags byte is at offset 32 in authenticatorData (after 32-byte rpIdHash)+ * We expect: UP (0x01) + UV (0x04) + AT (0x40) + BE (0x08) + BS (0x10) = 0x5D+ * Since we can't easily parse CBOR here, we just verify the credential was created+ */+ expect(result.credential).toBeDefined();+ });+ });++ describe('getAssertion', () => {+ it('should create a valid assertion for stored passkey', async () => {+ // First, create a passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ requestId: 'create-123',+ publicKey: {+ rp: { id: 'example.com', name: 'Example' },+ user: { id: 'user-1', name: 'testuser', displayName: 'Test User' },+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);+ const credentialId = createResult.credential.id;++ // Now, authenticate with the passkey+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ requestId: 'get-123',+ publicKey: {+ rpId: 'example.com',+ challenge: 'auth-challenge',+ userVerification: 'preferred'+ }+ };++ const assertion = await provider.getAssertion(getRequest, credentialId);++ // Verify assertion structure+ expect(assertion.id).toBe(credentialId);+ expect(assertion.rawId).toBe(credentialId);+ expect(assertion.clientDataJSON).toBeDefined();+ expect(assertion.authenticatorData).toBeDefined();+ expect(assertion.signature).toBeDefined();+ expect(assertion.userHandle).toBeNull();+ });++ it('should decode and validate clientDataJSON for authentication', async () => {+ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://test.com',+ publicKey: {+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate+ const getRequest: GetRequest = {+ origin: 'https://test.com',+ publicKey: {+ challenge: 'auth-challenge-xyz',+ userVerification: 'preferred'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id);++ // Decode and validate clientDataJSON+ const clientDataJSON = atob(assertion.clientDataJSON);+ const clientData = JSON.parse(clientDataJSON);++ expect(clientData.type).toBe('webauthn.get');+ expect(clientData.challenge).toBe('auth-challenge-xyz');+ expect(clientData.origin).toBe('https://test.com');+ expect(clientData.crossOrigin).toBe(false);+ });++ it('should decode and validate authenticatorData', async () => {+ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ rp: { id: 'example.com' },+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ rpId: 'example.com',+ challenge: 'auth-challenge'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id);++ // Decode authenticatorData+ const authDataBytes = Uint8Array.from(atob(assertion.authenticatorData), c => c.charCodeAt(0));++ // AuthenticatorData for assertion: rpIdHash (32) + flags (1) + signCount (4) = 37 bytes+ expect(authDataBytes.length).toBe(37);++ // Extract flags (byte at index 32)+ const flags = authDataBytes[32];++ // Should have UP (0x01) set+ expect(flags & 0x01).toBe(0x01); // User Present++ // Should have BE (0x08) and BS (0x10) set (backup eligible/state)+ expect(flags & 0x08).toBe(0x08); // Backup Eligible+ expect(flags & 0x10).toBe(0x10); // Backup State++ // Should NOT have AT (0x40) set (attested credential data only in creation)+ expect(flags & 0x40).toBe(0x00);++ // Sign count should be 0 (bytes 33-36)+ expect(authDataBytes[33]).toBe(0);+ expect(authDataBytes[34]).toBe(0);+ expect(authDataBytes[35]).toBe(0);+ expect(authDataBytes[36]).toBe(0);+ });++ it('should create valid DER-encoded signature', async () => {+ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'auth-challenge'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id);++ // Decode signature+ const sigBytes = Uint8Array.from(atob(assertion.signature), c => c.charCodeAt(0));++ // DER signature should start with SEQUENCE tag (0x30)+ expect(sigBytes[0]).toBe(0x30);++ // Second byte is length of the sequence+ const seqLength = sigBytes[1];+ expect(seqLength).toBeGreaterThan(0);+ expect(seqLength).toBeLessThanOrEqual(72); // Max for ECDSA P-256++ /*+ * Should contain two INTEGER values (r and s)+ * Third byte should be INTEGER tag (0x02)+ */+ expect(sigBytes[2]).toBe(0x02);+ });++ it('should throw error when passkey not found', async () => {+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'auth-challenge'+ }+ };++ await expect(+ provider.getAssertion(getRequest, 'non-existent-id')+ ).rejects.toThrow('Passkey not found');+ });++ it('should set UV flag when userVerification is required', async () => {+ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate with UV required+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'auth-challenge',+ userVerification: 'required'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id, {+ uvPerformed: false // Even without actual UV, if required, flag should be set+ });++ // Decode authenticatorData and check flags+ const authDataBytes = Uint8Array.from(atob(assertion.authenticatorData), c => c.charCodeAt(0));+ const flags = authDataBytes[32];++ // Should have UV (0x04) set when required+ expect(flags & 0x04).toBe(0x04);+ });++ it('should not set BE/BS flags when includeBEBS is false', async () => {+ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate without BE/BS flags+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'auth-challenge'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id, {+ includeBEBS: false+ });++ // Decode authenticatorData and check flags+ const authDataBytes = Uint8Array.from(atob(assertion.authenticatorData), c => c.charCodeAt(0));+ const flags = authDataBytes[32];++ // Should NOT have BE (0x08) or BS (0x10) set+ expect(flags & 0x08).toBe(0x00);+ expect(flags & 0x10).toBe(0x00);++ // Should still have UP (0x01) set+ expect(flags & 0x01).toBe(0x01);+ });+ });++ describe('Cross-verification', () => {+ it('should verify signature with public key', async () => {+ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ rp: { id: 'example.com' },+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ rpId: 'example.com',+ challenge: 'auth-challenge'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id);++ // Import public key for verification+ const publicKey = await crypto.subtle.importKey(+ 'jwk',+ createResult.stored.publicKey,+ { name: 'ECDSA', namedCurve: 'P-256' },+ false,+ ['verify']+ );++ // Reconstruct the signed data+ const authDataBytes = Uint8Array.from(atob(assertion.authenticatorData), c => c.charCodeAt(0));+ const clientDataBytes = new TextEncoder().encode(atob(assertion.clientDataJSON));+ const clientDataHash = new Uint8Array(await crypto.subtle.digest('SHA-256', clientDataBytes));+ const signedData = new Uint8Array([...authDataBytes, ...clientDataHash]);++ // Decode DER signature to raw format for verification+ const derSig = Uint8Array.from(atob(assertion.signature), c => c.charCodeAt(0));++ // Simple DER decoder for ECDSA signature (SEQUENCE of two INTEGERs)+ let offset = 2; // Skip SEQUENCE tag and length++ // Parse r+ expect(derSig[offset]).toBe(0x02); // INTEGER tag+ const rLen = derSig[offset + 1];+ let r = derSig.slice(offset + 2, offset + 2 + rLen);+ if (r.length > 32) {+ r = r.slice(r.length - 32);+ } // Remove padding if any+ if (r.length < 32) {+ const padded = new Uint8Array(32);+ padded.set(r, 32 - r.length);+ r = padded;+ }+ offset += 2 + rLen;++ // Parse s+ expect(derSig[offset]).toBe(0x02); // INTEGER tag+ const sLen = derSig[offset + 1];+ let s = derSig.slice(offset + 2, offset + 2 + sLen);+ if (s.length > 32) {+ s = s.slice(s.length - 32);+ }+ if (s.length < 32) {+ const padded = new Uint8Array(32);+ padded.set(s, 32 - s.length);+ s = padded;+ }++ // Combine to raw signature (r || s)+ const rawSig = new Uint8Array([...r, ...s]);++ // Verify signature+ const isValid = await crypto.subtle.verify(+ { name: 'ECDSA', hash: 'SHA-256' },+ publicKey,+ rawSig,+ signedData+ );++ expect(isValid).toBe(true);+ });+ });++ describe('Edge cases', () => {+ it('should handle challenge as Uint8Array', async () => {+ const challengeBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);++ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: challengeBytes,+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);+ expect(result.credential).toBeDefined();+ });++ it('should handle challenge as ArrayBuffer', async () => {+ const challengeBuffer = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]).buffer;++ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: challengeBuffer,+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);+ expect(result.credential).toBeDefined();+ });++ it('should use rpId from origin when not provided in create request', async () => {+ const createRequest: CreateRequest = {+ origin: 'https://subdomain.test.com:8080',+ publicKey: {+ challenge: 'test-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);+ expect(result.stored.rpId).toBe('subdomain.test.com');+ });++ it('should use rpId from origin when not provided in get request', async () => {+ // Create passkey with explicit rpId+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ rp: { id: 'example.com' },+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Authenticate without explicit rpId+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'auth-challenge'+ }+ };++ const assertion = await provider.getAssertion(getRequest, createResult.credential.id);+ expect(assertion).toBeDefined();+ });+ });+});diff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.tsnew file mode 100644index 000000000..98ffc73eb--- /dev/null+++ b/apps/browser-extension/src/utils/passkey/types.ts@@ -0,0 +1,42 @@+/**+ * Type definitions for the AliasVaultPasskeyProvider+ */++export type StoredPasskeyRecord = {+ rpId: string;+ credentialId: string; // base64url identifier (string)+ publicKey: JsonWebKey; // JWK (P-256)+ privateKey: JsonWebKey; // JWK (P-256)+ userId?: ArrayBuffer | Uint8Array | string | null;+ userName?: string;+ userDisplayName?: string;+ lastUsedAt?: number;+};++export type CreateRequest = {+ origin: string; // e.g. "https://example.com"+ requestId?: string; // optional correlation id (if you need it)+ publicKey: {+ rp?: { id?: string; name?: string };+ user?: { id?: ArrayBuffer | Uint8Array | string; name?: string; displayName?: string };+ challenge: ArrayBuffer | Uint8Array | string;+ pubKeyCredParams?: Array<{ type: 'public-key'; alg: number }>;+ attestation?: 'none' | 'indirect' | 'direct' | 'enterprise';+ authenticatorSelection?: {+ userVerification?: 'required' | 'preferred' | 'discouraged';+ requireResidentKey?: boolean;+ residentKey?: 'required' | 'preferred' | 'discouraged';+ authenticatorAttachment?: 'platform' | 'cross-platform';+ };+ };+};++export type GetRequest = {+ origin: string;+ requestId?: string;+ publicKey: {+ rpId?: string;+ challenge: ArrayBuffer | Uint8Array | string; // often base64url string from page+ userVerification?: 'required' | 'preferred' | 'discouraged';+ };+};diff --git a/apps/browser-extension/src/utils/webauthn/PasskeyCreator.ts b/apps/browser-extension/src/utils/webauthn/PasskeyCreator.tsnew file mode 100644index 000000000..73d1f8f8d--- /dev/null+++ b/apps/browser-extension/src/utils/webauthn/PasskeyCreator.ts@@ -0,0 +1,364 @@+/**+ * PasskeyCreator - Robust WebAuthn passkey creation utility+ * Uses proper CBOR encoding to ensure maximum compatibility+ */++import { encode as cborEncode } from 'cbor-x';++/**+ * Helper function to convert Uint8Array to base64url string+ */+export function uint8ArrayToBase64url(bytes: Uint8Array): string {+ const base64 = btoa(String.fromCharCode(...bytes));+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');+}++/**+ * Helper function to convert base64url string to Uint8Array+ */+export function base64UrlToUint8Array(base64url: string): Uint8Array {+ const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');+ const padded = base64 + '==='.slice((base64.length + 3) % 4);+ const binary = atob(padded);+ return new Uint8Array(binary.split('').map(c => c.charCodeAt(0)));+}++/**+ * Create COSE_Key from JWK for ES256 algorithm+ * Uses proper CBOR encoding via cbor-x library+ */+export function createCoseKeyFromJwk(publicKeyJwk: JsonWebKey): Uint8Array {+ if (!publicKeyJwk.x || !publicKeyJwk.y) {+ throw new Error('Invalid JWK: missing x or y coordinates');+ }++ // Convert x and y coordinates from base64url to bytes+ const xCoord = base64UrlToUint8Array(publicKeyJwk.x);+ const yCoord = base64UrlToUint8Array(publicKeyJwk.y);++ // Validate coordinate lengths (P-256 uses 32-byte coordinates)+ if (xCoord.length !== 32 || yCoord.length !== 32) {+ throw new Error(+ `Invalid P-256 key coordinates: x=${xCoord.length} bytes, y=${yCoord.length} bytes (expected 32 bytes each)`+ );+ }++ /*+ * COSE_Key structure for ES256 (RFC 8152)+ * Map keys:+ * 1 (kty): 2 (EC2 - Elliptic Curve Keys with x and y coordinate pair)+ * 3 (alg): -7 (ES256 - ECDSA w/ SHA-256)+ * -1 (crv): 1 (P-256 - NIST P-256 curve)+ * -2 (x): x-coordinate as byte string+ * -3 (y): y-coordinate as byte string+ */+ const coseKey = {+ 1: 2, // kty: EC2+ 3: -7, // alg: ES256+ '-1': 1, // crv: P-256+ '-2': xCoord, // x-coordinate+ '-3': yCoord // y-coordinate+ };++ // Encode using cbor-x, which handles canonical CBOR encoding+ return new Uint8Array(cborEncode(coseKey));+}++/**+ * Create authenticator data according to WebAuthn spec+ */+export interface IAuthenticatorDataOptions {+ rpId: string;+ flags: number;+ signCount: number;+ aaguid?: Uint8Array;+ credentialId?: Uint8Array;+ cosePublicKey?: Uint8Array;+}++/**+ *+ */+export async function createAuthenticatorData(options: IAuthenticatorDataOptions): Promise<Uint8Array> {+ const {+ rpId,+ flags,+ signCount,+ aaguid = new Uint8Array(16), // Default to all zeros+ credentialId,+ cosePublicKey+ } = options;++ // Calculate rpId hash (SHA-256)+ const rpIdBytes = new TextEncoder().encode(rpId);+ const rpIdHashBuffer = await crypto.subtle.digest('SHA-256', rpIdBytes);+ const rpIdHash = new Uint8Array(rpIdHashBuffer);++ // Flags (1 byte)+ const flagsByte = new Uint8Array([flags]);++ // Sign count (4 bytes, big-endian)+ const signCountBytes = new Uint8Array([+ (signCount >> 24) & 0xff,+ (signCount >> 16) & 0xff,+ (signCount >> 8) & 0xff,+ signCount & 0xff+ ]);++ // Build base authData (rpIdHash + flags + signCount)+ const parts: Uint8Array[] = [rpIdHash, flagsByte, signCountBytes];++ // If AT (Attested Credential Data) flag is set, include attested credential data+ if ((flags & 0x40) && credentialId && cosePublicKey) {+ // AAGUID (16 bytes)+ parts.push(aaguid);++ // Credential ID Length (2 bytes, big-endian)+ const credIdLength = new Uint8Array([+ (credentialId.length >> 8) & 0xff,+ credentialId.length & 0xff+ ]);+ parts.push(credIdLength);++ // Credential ID+ parts.push(credentialId);++ // COSE-encoded public key+ parts.push(cosePublicKey);+ }++ // Concatenate all parts+ const totalLength = parts.reduce((sum, part) => sum + part.length, 0);+ const authData = new Uint8Array(totalLength);+ let offset = 0;+ for (const part of parts) {+ authData.set(part, offset);+ offset += part.length;+ }++ return authData;+}++/**+ * Create attestation object with proper CBOR encoding+ */+export interface IAttestationObjectOptions {+ fmt: 'none' | 'packed';+ authData: Uint8Array;+ attStmt?: {+ alg?: number;+ sig?: Uint8Array;+ };+}++/**+ *+ */+export function createAttestationObject(options: IAttestationObjectOptions): Uint8Array {+ const { fmt, authData, attStmt = {} } = options;++ // Build attestation object structure+ const attestationObject: Record<string, unknown> = {+ fmt,+ attStmt,+ authData+ };++ // Encode using cbor-x with canonical encoding+ return new Uint8Array(cborEncode(attestationObject));+}++/**+ * Encode ECDSA signature (IEEE P1363 format) to DER format+ * Web Crypto API returns signatures as r||s concatenation+ * WebAuthn requires DER-encoded signatures+ */+export function encodeDerSignature(rawSignature: Uint8Array): Uint8Array {+ // For P-256, signature is 64 bytes: 32-byte r + 32-byte s+ if (rawSignature.length !== 64) {+ throw new Error(`Invalid signature length: ${rawSignature.length} (expected 64 for P-256)`);+ }++ const r = rawSignature.slice(0, 32);+ const s = rawSignature.slice(32, 64);++ /**+ * Encode integer in DER format+ * DER integers must be positive, so add 0x00 padding if high bit is set+ */+ 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;+ }++ // DER INTEGER: 0x02 (tag) + length + value+ return new Uint8Array([0x02, trimmed.length, ...trimmed]);+ };++ const rDer = encodeInteger(r);+ const sDer = encodeInteger(s);++ // DER SEQUENCE: 0x30 (tag) + length + r + s+ return new Uint8Array([0x30, rDer.length + sDer.length, ...rDer, ...sDer]);+}++/**+ * WebAuthn flag constants+ */+export const WebAuthnFlags = {+ UP: 0x01, // User Present+ UV: 0x04, // User Verified+ BE: 0x08, // Backup Eligible+ BS: 0x10, // Backup State+ AT: 0x40, // Attested Credential Data+ ED: 0x80 // Extension Data+} as const;++/**+ * Create WebAuthn credential for registration+ * This is the main function to use for creating passkeys+ */+export interface ICreatePasskeyOptions {+ rpId: string;+ origin: string;+ challenge: string; // base64url encoded+ displayName: string;+ attestation?: 'none' | 'indirect' | 'direct';+}++export interface ICreatePasskeyResult {+ credential: {+ id: string;+ rawId: string;+ clientDataJSON: string;+ attestationObject: string;+ };+ privateKey: JsonWebKey;+ publicKey: JsonWebKey;+ credentialId: string;+}++/**+ *+ */+export async function createPasskey(options: ICreatePasskeyOptions): Promise<ICreatePasskeyResult> {+ const { rpId, origin, challenge, displayName, attestation = 'none' } = options;++ // Generate ES256 key pair+ const keyPair = await crypto.subtle.generateKey(+ {+ name: 'ECDSA',+ namedCurve: 'P-256'+ },+ true, // extractable+ ['sign', 'verify']+ );++ // Export keys+ const publicKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);+ const privateKeyJwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey);++ // Generate credential ID (16 random bytes)+ const credIdBytes = crypto.getRandomValues(new Uint8Array(16));+ const credentialId = uint8ArrayToBase64url(credIdBytes);++ // Create COSE public key+ const cosePublicKey = createCoseKeyFromJwk(publicKeyJwk);++ /*+ * Authenticator flags:+ * - UP (User Present): Always set+ * - UV (User Verified): Set to indicate user verification+ * - BE (Backup Eligible): Set to indicate passkey can be synced+ * - BS (Backup State): Set to indicate passkey is backed up+ * - AT (Attested Credential Data): Set during registration+ */+ const flags = WebAuthnFlags.UP | WebAuthnFlags.UV | WebAuthnFlags.BE | WebAuthnFlags.BS | WebAuthnFlags.AT;++ // Create authenticator data+ const authData = await createAuthenticatorData({+ rpId,+ flags,+ signCount: 0, // Always 0 for synced passkeys+ credentialId: credIdBytes,+ cosePublicKey+ });++ // Create clientDataJSON+ const clientDataJSON = JSON.stringify({+ type: 'webauthn.create',+ challenge,+ origin,+ crossOrigin: false+ });++ // Create attestation object+ let attestationObject: Uint8Array;++ if (attestation === 'none' || attestation === 'indirect') {+ // Use "none" attestation (most privacy-preserving)+ attestationObject = createAttestationObject({+ fmt: 'none',+ authData,+ attStmt: {}+ });+ } else {+ // Use "packed" attestation with self-attestation+ 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+ const signature = await crypto.subtle.sign(+ { name: 'ECDSA', hash: 'SHA-256' },+ keyPair.privateKey,+ dataToSign+ );++ const derSignature = encodeDerSignature(new Uint8Array(signature));++ attestationObject = createAttestationObject({+ fmt: 'packed',+ authData,+ attStmt: {+ alg: -7, // ES256+ sig: derSignature+ }+ });+ }++ console.info('[PasskeyCreator] Created credential successfully');+ console.info('[PasskeyCreator] Details:', {+ credentialId,+ credentialIdBytes: credIdBytes.length,+ authDataLength: authData.length,+ coseKeyLength: cosePublicKey.length,+ attestationObjectLength: attestationObject.length,+ attestationFormat: attestation,+ rpId,+ origin,+ flags: flags.toString(2).padStart(8, '0')+ });++ return {+ credential: {+ id: credentialId,+ rawId: credentialId,+ clientDataJSON: btoa(clientDataJSON),+ attestationObject: btoa(String.fromCharCode(...attestationObject))+ },+ privateKey: privateKeyJwk,+ publicKey: publicKeyJwk,+ credentialId+ };+}