Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add webauthn types and return all required metadata fields (#520)
Leendert de Borstdb227894b6c7
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.tsindex f64418d71..da04bf50e 100644--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts@@ -12,6 +12,9 @@ interface IPasskeyData {displayName: string;publicKey: JsonWebKey;privateKey: JsonWebKey;+ userId?: string | null; // base64url encoded user.id for userHandle+ userName?: string;+ userDisplayName?: string;createdAt: number;updatedAt: number;lastUsedAt: number | null;@@ -221,8 +224,13 @@ export async function handleStorePasskey(data: {displayName: string;publicKey: JsonWebKey;privateKey: JsonWebKey;+ userId?: string | null;+ userName?: string;+ userDisplayName?: string;}): Promise<{ success: boolean }> {- const { rpId, credentialId, displayName, publicKey, privateKey } = data;+ const { rpId, credentialId, displayName, publicKey, privateKey, userId, userName, userDisplayName } = data;++ console.log('handleStorePasskey: Storing passkey with raw userId:', userId);const passkey: IPasskeyData = {id: Date.now().toString(),@@ -231,6 +239,9 @@ export async function handleStorePasskey(data: {displayName,publicKey,privateKey,+ userId,+ userName,+ userDisplayName,createdAt: Date.now(),updatedAt: Date.now(),lastUsedAt: null,@@ -400,10 +411,12 @@ export async function handleGetPasskeyById(data: { credentialId: string }): Promfor (const [_key, passkey] of sessionPasskeys.entries()) {if (passkey.credentialId === credentialId) {+ console.log('handleGetPasskeyById: Found passkey with userId:', passkey.userId);return passkey;}}+ console.log('handleGetPasskeyById: Passkey not found for credentialId:', credentialId);return null;}@@ -412,13 +425,7 @@ export async function handleGetPasskeyById(data: { credentialId: string }): Prom*/export async function handleGetRequestData(data: { requestId: string }): Promise<any> {const { requestId } = data;- console.log('handleGetRequestData: requestId', requestId);- console.log('handleGetRequestData: pendingRequestData', pendingRequestData);- console.log('handleGetRequestData: map size', pendingRequestData.size);- console.log('handleGetRequestData: map keys', Array.from(pendingRequestData.keys()));const requestData = pendingRequestData.get(requestId);- console.log('handleGetRequestData: found data', requestData);- console.log('handleGetRequestData: passkeys in data', requestData?.passkeys);return requestData || null;}diff --git a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.tsindex ef2100d54..0f1e77e1f 100644--- a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts@@ -60,6 +60,11 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {origin}, 'background');+ console.log('[AliasVault] WebAuthnInterceptor: Received credential from background:', result);+ if (result.credential) {+ console.log('[AliasVault] WebAuthnInterceptor: credential.userHandle =', result.credential.userHandle);+ }+// Send response back to pagewindow.dispatchEvent(new CustomEvent('aliasvault:webauthn:get:response', {detail: {diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsxindex 396604021..285db7022 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx@@ -118,6 +118,7 @@ const PasskeyAuthenticate: React.FC = () => {});console.info('PasskeyAuthenticate: Received assertion successfully', credential);+ console.info('PasskeyAuthenticate: credential.userHandle =', credential.userHandle);// Update last used timestampawait sendMessage('UPDATE_PASSKEY_LAST_USED', {@@ -125,13 +126,14 @@ const PasskeyAuthenticate: React.FC = () => {}, 'background');// Send response back+ console.info('PasskeyAuthenticate: Sending credential to background:', credential);await sendMessage('PASSKEY_POPUP_RESPONSE', {requestId: request.requestId,credential}, 'background');// For debugging: Don't close the window automatically- console.info('PasskeyAuthenticate: Authentication complete. Window kept open for debugging.');+ console.info('PasskeyAuthenticate: Authentication complete.');setLoading(false);// Uncomment to auto-close:diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsxindex 2b504d006..41b7c5305 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx@@ -43,7 +43,7 @@ const PasskeyCreate: React.FC = () => {try {// Fetch the full request data from backgroundconst data = await sendMessage('GET_REQUEST_DATA', { requestId }, 'background');- console.log('PasskeyCreate: fetched request data', data);+ console.log('PasskeyCreate: website create request:', data);if (data) {setRequest(data);@@ -56,8 +56,6 @@ const PasskeyCreate: React.FC = () => {}}- // Mark initial loading as complete- console.log('PasskeyCreate: useEffect: setIsInitialLoading(false)');setIsInitialLoading(false);};@@ -75,9 +73,6 @@ const PasskeyCreate: React.FC = () => {setLoading(true);try {- console.log('PasskeyCreate: Starting passkey creation');- console.log('PasskeyCreate: request', request);-// Create the provider with storage callbacksconst provider = new AliasVaultPasskeyProvider(async (record: StoredPasskeyRecord) => {@@ -136,7 +131,7 @@ const PasskeyCreate: React.FC = () => {}, 'background');// For debugging: Don't close the window automatically- console.info('PasskeyCreate: Passkey created successfully. Window kept open for debugging.');+ console.info('PasskeyCreate: Passkey created successfully.');setLoading(false);// Uncomment to auto-close:diff --git a/apps/browser-extension/src/entrypoints/webauthn-inject.ts b/apps/browser-extension/src/entrypoints/webauthn-inject.tsindex 76e7fd30e..bf6eef6eb 100644--- a/apps/browser-extension/src/entrypoints/webauthn-inject.ts+++ b/apps/browser-extension/src/entrypoints/webauthn-inject.ts@@ -5,6 +5,15 @@import { defineUnlistedScript } from '#imports';+import type {+ WebAuthnCreateEventDetail,+ WebAuthnGetEventDetail,+ WebAuthnCreateResponseDetail,+ WebAuthnGetResponseDetail,+ ProviderCreateCredential,+ ProviderGetCredential+} from '@/utils/passkey/webauthn-inject.types';+export default defineUnlistedScript(() => {// Only run onceif ((window as any).__aliasVaultWebAuthnIntercepted) {@@ -60,23 +69,24 @@ export default defineUnlistedScript(() => {// Send event to content scriptconst requestId = Math.random().toString(36).substr(2, 9);- const event = new CustomEvent('aliasvault:webauthn:create', {- detail: {- requestId,- publicKey: {- ...options.publicKey,- challenge: bufferToBase64(options.publicKey.challenge),- user: {- ...options.publicKey.user,- id: bufferToBase64(options.publicKey.user.id)- },- excludeCredentials: options.publicKey.excludeCredentials?.map(cred => ({- ...cred,- id: bufferToBase64(cred.id)- }))+ const eventDetail: WebAuthnCreateEventDetail = {+ requestId,+ publicKey: {+ ...options.publicKey,+ challenge: bufferToBase64(options.publicKey.challenge),+ user: {+ ...options.publicKey.user,+ id: bufferToBase64(options.publicKey.user.id)},- origin: window.location.origin- }+ excludeCredentials: options.publicKey.excludeCredentials?.map(cred => ({+ ...cred,+ id: bufferToBase64(cred.id)+ }))+ },+ origin: window.location.origin+ };+ const event = new CustomEvent<WebAuthnCreateEventDetail>('aliasvault:webauthn:create', {+ detail: eventDetail});window.dispatchEvent(event);@@ -94,13 +104,13 @@ export default defineUnlistedScript(() => {*/function cleanup() {clearTimeout(timeout);- window.removeEventListener('aliasvault:webauthn:create:response', handler);+ window.removeEventListener('aliasvault:webauthn:create:response', handler as EventListener);}/****/- function handler(e: any) {+ function handler(e: CustomEvent<WebAuthnCreateResponseDetail>) {if (e.detail.requestId !== requestId) {return;}@@ -115,55 +125,100 @@ export default defineUnlistedScript(() => {reject(new Error(e.detail.error));} else if (e.detail.credential) {// Create a proper credential object with required methods- const cred = e.detail.credential;- const credential = {- id: cred.id,- type: 'public-key',- rawId: base64ToBuffer(cred.rawId),- 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;+ const cred: ProviderCreateCredential = e.detail.credential;+ console.log('[AliasVault] Page: Creating credential response from:', cred);+ try {+ // Decode the attestation object to extract authenticator data+ const attestationObjectBuffer = base64ToBuffer(cred.attestationObject);+ const attObjBytes = new Uint8Array(attestationObjectBuffer);++ // Simple CBOR parser to extract authData+ // CBOR map starts with 0xA3 (map with 3 items)+ // Keys are: "fmt" (0x63), "attStmt" (0x67), "authData" (0x68)+ let authDataBuffer = new ArrayBuffer(0);+ try {+ // Find "authData" key (0x68 0x61 0x75 0x74 0x68 0x44 0x61 0x74 0x61)+ const authDataKeyBytes = [0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61];+ for (let i = 0; i < attObjBytes.length - authDataKeyBytes.length; i++) {+ let match = true;+ for (let j = 0; j < authDataKeyBytes.length; j++) {+ if (attObjBytes[i + j] !== authDataKeyBytes[j]) {+ match = false;+ break;+ }+ }+ if (match) {+ // Found "authData" key, next byte is the type (0x58 = byte string)+ const typeIdx = i + authDataKeyBytes.length;+ if (attObjBytes[typeIdx] === 0x58) {+ // Next byte is the length+ const length = attObjBytes[typeIdx + 1];+ authDataBuffer = attObjBytes.slice(typeIdx + 2, typeIdx + 2 + length).buffer;+ }+ break;+ }+ }+ } catch (e) {+ console.error('[AliasVault] Failed to parse authData from attestation object:', e);+ }++ const credential = {+ id: cred.id,+ type: 'public-key',+ rawId: base64ToBuffer(cred.rawId),+ authenticatorAttachment: 'platform',+ response: {+ clientDataJSON: base64ToBuffer(cred.clientDataJSON),+ attestationObject: attestationObjectBuffer,+ /**+ *+ */+ getTransports() {+ return ['internal'];+ },+ /**+ *+ */+ getAuthenticatorData() {+ return authDataBuffer;+ },+ /**+ *+ */+ getPublicKey() {+ return null;+ },+ /**+ *+ */+ getPublicKeyAlgorithm() {+ return -7; // ES256+ }},/****/- getPublicKeyAlgorithm() {- return -7; // ES256+ getClientExtensionResults() {+ return {};}- },- /**- *- */- getClientExtensionResults() {- return {};- }- };- resolve(credential as any);+ };+ console.log('[AliasVault] Page: Created credential object:', credential);+ console.log('[AliasVault] Page: Credential rawId length:', credential.rawId.byteLength);+ console.log('[AliasVault] Page: Credential clientDataJSON length:', credential.response.clientDataJSON.byteLength);+ console.log('[AliasVault] Page: Credential attestationObject length:', credential.response.attestationObject.byteLength);+ console.log('[AliasVault] Page: Credential authData length:', authDataBuffer.byteLength);+ resolve(credential as any);+ } catch (error) {+ console.error('[AliasVault] Page: Error creating credential object:', error);+ reject(error);+ }} else {// Cancelledresolve(null);}}- window.addEventListener('aliasvault:webauthn:create:response', handler);+ window.addEventListener('aliasvault:webauthn:create:response', handler as EventListener);});};@@ -181,19 +236,20 @@ export default defineUnlistedScript(() => {// Send event to content scriptconst requestId = Math.random().toString(36).substr(2, 9);- const event = new CustomEvent('aliasvault:webauthn:get', {- detail: {- requestId,- publicKey: {- ...options.publicKey,- challenge: bufferToBase64(options.publicKey.challenge),- allowCredentials: options.publicKey.allowCredentials?.map(cred => ({- ...cred,- id: bufferToBase64(cred.id)- }))- },- origin: window.location.origin- }+ const eventDetail: WebAuthnGetEventDetail = {+ requestId,+ publicKey: {+ ...options.publicKey,+ challenge: bufferToBase64(options.publicKey.challenge),+ allowCredentials: options.publicKey.allowCredentials?.map(cred => ({+ ...cred,+ id: bufferToBase64(cred.id)+ }))+ },+ origin: window.location.origin+ };+ const event = new CustomEvent<WebAuthnGetEventDetail>('aliasvault:webauthn:get', {+ detail: eventDetail});window.dispatchEvent(event);@@ -211,13 +267,13 @@ export default defineUnlistedScript(() => {*/function cleanup() {clearTimeout(timeout);- window.removeEventListener('aliasvault:webauthn:get:response', handler);+ window.removeEventListener('aliasvault:webauthn:get:response', handler as EventListener);}/****/- function handler(e: any) {+ function handler(e: CustomEvent<WebAuthnGetResponseDetail>) {if (e.detail.requestId !== requestId) {return;}@@ -232,11 +288,13 @@ export default defineUnlistedScript(() => {reject(new Error(e.detail.error));} else if (e.detail.credential) {// Create a proper credential object with required methods- const cred = e.detail.credential;+ const cred: ProviderGetCredential = e.detail.credential;+ console.log('Sending back credential with userhandle (converted to buffer):', cred.userHandle);const credential = {id: cred.id,type: 'public-key',rawId: base64ToBuffer(cred.rawId),+ authenticatorAttachment: 'platform',response: {clientDataJSON: base64ToBuffer(cred.clientDataJSON),authenticatorData: base64ToBuffer(cred.authenticatorData),@@ -257,7 +315,7 @@ export default defineUnlistedScript(() => {}}- window.addEventListener('aliasvault:webauthn:get:response', handler);+ window.addEventListener('aliasvault:webauthn:get:response', handler as EventListener);});};diff --git a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.tsindex 0b227a102..1a292814b 100644--- a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts+++ b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts@@ -65,6 +65,9 @@ export class AliasVaultPasskeyProvider {// 2) Determine RP ID (domain) and hash itconst rpId = req.publicKey.rp?.id || new URL(req.origin).hostname;+ console.log('AliasVaultPasskeyProvider.createPasskey: rpId:', rpId);+ console.log('AliasVaultPasskeyProvider.createPasskey: rp.id from request:', req.publicKey.rp?.id);+ console.log('AliasVaultPasskeyProvider.createPasskey: origin hostname:', 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)@@ -110,6 +113,9 @@ export class AliasVaultPasskeyProvider {// 9) clientDataJSON (stringify with challenge as base64url)const challengeB64u = this.challengeToB64u(req.publicKey.challenge);+ console.log('AliasVaultPasskeyProvider.createPasskey: challenge received:', req.publicKey.challenge);+ console.log('AliasVaultPasskeyProvider.createPasskey: challenge as base64url:', challengeB64u);+ console.log('AliasVaultPasskeyProvider.createPasskey: origin:', req.origin);const clientDataObj = {type: 'webauthn.create',challenge: challengeB64u,@@ -117,6 +123,7 @@ export class AliasVaultPasskeyProvider {crossOrigin: false};const clientDataJSONStr = JSON.stringify(clientDataObj);+ console.log('AliasVaultPasskeyProvider.createPasskey: clientDataJSON:', clientDataJSONStr);const clientDataJSONBytes = this.te(clientDataJSONStr);// 10) Build attestationObject (CBOR map with "fmt","attStmt","authData")@@ -127,10 +134,14 @@ export class AliasVaultPasskeyProvider {: await this.buildAttObjPackedSelf(authenticatorData, clientDataJSONBytes, keyPair.privateKey);// 11) Store the passkey in your vault (so it can be used later for authentication)- // Normalize userId to base64url string for consistent storage and later retrieval- let userIdB64u: string | null = null;+ // Store userId as-is (injection script sends it as standard base64 string)+ let userIdB64: string | null = null;if (req.publicKey.user?.id) {- userIdB64u = this.userIdToB64u(req.publicKey.user.id);+ console.log('Storing passkey with userId (standard base64):', req.publicKey.user.id);+ // The injection script already converted ArrayBuffer to standard base64, store as-is+ userIdB64 = typeof req.publicKey.user.id === 'string'+ ? req.publicKey.user.id+ : this.toB64(req.publicKey.user.id instanceof Uint8Array ? req.publicKey.user.id : new Uint8Array(req.publicKey.user.id));}const stored: StoredPasskeyRecord = {@@ -138,7 +149,7 @@ export class AliasVaultPasskeyProvider {credentialId: credentialIdB64u,publicKey: pubJwk,privateKey: prvJwk,- userId: userIdB64u,+ userId: userIdB64,userName: req.publicKey.user?.name,userDisplayName: req.publicKey.user?.displayName,lastUsedAt: Date.now()@@ -238,13 +249,17 @@ export class AliasVaultPasskeyProvider {// 7) Convert raw (r|s) to DER sequenceconst derSig = this.ecdsaRawToDer(rawSig);- // 8) Encode userHandle (userId) as base64 if present+ // 8) Return userHandle (userId) as-is// This is required for discoverable credentials (resident keys) where the RP doesn't ask for a username first- // userId is stored as base64url, convert to base64 for WebAuthn response+ // userId is already stored as standard base64 (from injection script), return as-islet userHandleB64: string | null = null;if (rec.userId) {- const userIdBytes = this.fromB64u(rec.userId);- userHandleB64 = this.toB64(userIdBytes);+ console.log('AliasVaultPasskeyProvider.getAssertion: rec.userId (standard base64):', rec.userId);+ // Return as-is - already in standard base64 format+ userHandleB64 = rec.userId;+ console.log('AliasVaultPasskeyProvider.getAssertion: userHandleB64:', userHandleB64);+ } else {+ console.warn('AliasVaultPasskeyProvider.getAssertion: No userId found in stored passkey record');}// 9) Return object in the flat shape (base64 strings), as your client example expects@@ -442,13 +457,13 @@ export class AliasVaultPasskeyProvider {/*** Normalize challenge to base64url string.- * Challenges from the web page are already base64url encoded by the injection script.- * Only ArrayBuffer/Uint8Array need conversion.+ * The injection script sends challenges as standard base64, so we need to convert to base64url.*/private challengeToB64u(challenge: ArrayBuffer | Uint8Array | string): string {if (typeof challenge === 'string') {- // Already base64url from injection script - use as-is- return challenge;+ // String from injection script - it's standard base64, convert to base64url+ // Remove padding and replace + with - and / with _+ return challenge.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');}const bytes = challenge instanceof Uint8Array ? challenge : new Uint8Array(challenge);return this.toB64u(bytes);diff --git a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.tsindex 9a82dafd7..b1d0156db 100644--- a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts+++ b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts@@ -571,6 +571,150 @@ describe('AliasVaultPasskeyProvider', () => {});});+ describe('Storage callbacks verification', () => {+ it('should call store callback with userId when creating passkey', async () => {+ const userIdBytes = new Uint8Array([10, 20, 30, 40]);+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ rp: { id: 'example.com', name: 'Example' },+ user: {+ id: userIdBytes,+ name: 'testuser',+ displayName: 'Test User'+ },+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const storeSpy = vi.fn();+ const getSpy = vi.fn();++ const testProvider = new AliasVaultPasskeyProvider(storeSpy, getSpy);+ await testProvider.createPasskey(createRequest);++ // Verify store was called with userId+ expect(storeSpy).toHaveBeenCalledTimes(1);+ const storedRecord = storeSpy.mock.calls[0][0] as StoredPasskeyRecord;+ expect(storedRecord.userId).toBeDefined();+ expect(storedRecord.userId).not.toBeNull();+ expect(typeof storedRecord.userId).toBe('string');+ });++ it('should retrieve userId from getById callback during authentication', async () => {+ const userIdBytes = new Uint8Array([50, 60, 70, 80]);++ // First create a passkey with userId+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ rp: { id: 'example.com' },+ user: {+ id: userIdBytes,+ name: 'testuser',+ displayName: 'Test User'+ },+ challenge: 'create-challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await provider.createPasskey(createRequest);++ // Now authenticate - verify that getById is called and userId is preserved+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ rpId: 'example.com',+ challenge: 'auth-challenge'+ }+ };++ const getBySpy = vi.fn(async (credentialId: string) => {+ // Return the stored passkey with userId+ return storedPasskeys.get(credentialId) || null;+ });++ const testProvider = new AliasVaultPasskeyProvider(+ async () => {},+ getBySpy+ );++ const assertion = await testProvider.getAssertion(getRequest, createResult.credential.id);++ // Verify getById was called+ expect(getBySpy).toHaveBeenCalledTimes(1);+ expect(getBySpy).toHaveBeenCalledWith(createResult.credential.id);++ // Verify userHandle was populated from the retrieved userId+ expect(assertion.userHandle).not.toBeNull();+ expect(assertion.userHandle).toBeDefined();+ });++ it('should preserve userId through storage and retrieval round-trip', async () => {+ // This test simulates the full flow: create → store → retrieve → authenticate+ const realStorage = new Map<string, StoredPasskeyRecord>();+ const userIdBytes = new Uint8Array([100, 101, 102, 103]);++ const roundTripProvider = new AliasVaultPasskeyProvider(+ async (record: StoredPasskeyRecord) => {+ // Simulate real storage that might serialize/deserialize+ const serialized = JSON.stringify(record);+ const deserialized = JSON.parse(serialized);+ realStorage.set(record.credentialId, deserialized);+ },+ async (credentialId: string) => {+ return realStorage.get(credentialId) || null;+ }+ );++ // Create passkey+ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ user: {+ id: userIdBytes,+ name: 'user',+ displayName: 'User'+ },+ challenge: 'challenge',+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const createResult = await roundTripProvider.createPasskey(createRequest);++ // Verify it was stored+ const storedRecord = realStorage.get(createResult.credential.id);+ expect(storedRecord).toBeDefined();+ expect(storedRecord?.userId).toBeDefined();++ // Authenticate - retrieve from storage+ const getRequest: GetRequest = {+ origin: 'https://example.com',+ publicKey: {+ challenge: 'auth-challenge'+ }+ };++ const assertion = await roundTripProvider.getAssertion(getRequest, createResult.credential.id);++ // Verify userHandle was preserved through the round-trip+ expect(assertion.userHandle).not.toBeNull();++ // Decode and verify it matches original+ if (assertion.userHandle) {+ const decoded = atob(assertion.userHandle);+ const decodedBytes = new Uint8Array(decoded.length);+ for (let i = 0; i < decoded.length; i++) {+ decodedBytes[i] = decoded.charCodeAt(i);+ }+ expect(Array.from(decodedBytes)).toEqual(Array.from(userIdBytes));+ }+ });+ });+describe('Cross-verification', () => {it('should verify signature with public key', async () => {// Create passkeydiff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.tsindex 431ee7691..de058f965 100644--- a/apps/browser-extension/src/utils/passkey/types.ts+++ b/apps/browser-extension/src/utils/passkey/types.ts@@ -2,6 +2,18 @@* Type definitions for the AliasVaultPasskeyProvider*/+// Re-export injection script types for convenience+export type {+ WebAuthnCreateEventDetail,+ WebAuthnGetEventDetail,+ WebAuthnCreateResponseDetail,+ WebAuthnGetResponseDetail,+ ProviderCreateCredential,+ ProviderGetCredential,+ WebAuthnPublicKeyCredential,+ WebAuthnAssertionCredential+} from './webauthn-inject.types';+/*** WebAuthn credential response types (for injection script compatibility)*/diff --git a/apps/browser-extension/src/utils/passkey/webauthn-inject.types.ts b/apps/browser-extension/src/utils/passkey/webauthn-inject.types.tsnew file mode 100644index 000000000..873d5a233--- /dev/null+++ b/apps/browser-extension/src/utils/passkey/webauthn-inject.types.ts@@ -0,0 +1,97 @@+/**+ * Type definitions for WebAuthn injection script+ * These types ensure type safety for the credential objects we create+ */++/**+ * WebAuthn credential response for registration (create)+ * This is what the injection script returns to the page+ */+export type WebAuthnPublicKeyCredential = PublicKeyCredential & {+ readonly authenticatorAttachment: AuthenticatorAttachment | null;+ readonly response: AuthenticatorAttestationResponse;+};++/**+ * WebAuthn credential response for authentication (get)+ */+export type WebAuthnAssertionCredential = PublicKeyCredential & {+ readonly authenticatorAttachment: AuthenticatorAttachment | null;+ readonly response: AuthenticatorAssertionResponse;+};++/**+ * Internal credential format from provider (base64 encoded)+ */+export type ProviderCreateCredential = {+ id: string;+ rawId: string;+ clientDataJSON: string;+ attestationObject: string;+};++export type ProviderGetCredential = {+ id: string;+ rawId: string;+ clientDataJSON: string;+ authenticatorData: string;+ signature: string;+ userHandle: string | null;+};++/**+ * Custom event detail types for communication between page and content script+ */+export type WebAuthnCreateEventDetail = {+ requestId: string;+ publicKey: {+ rp?: { id?: string; name?: string };+ user: {+ id: string; // base64 encoded+ name?: string;+ displayName?: string;+ };+ challenge: string; // base64 encoded+ pubKeyCredParams?: Array<{ type: string; alg: number }>;+ timeout?: number;+ excludeCredentials?: Array<{ type: string; id: string; transports?: string[] }>;+ authenticatorSelection?: {+ authenticatorAttachment?: AuthenticatorAttachment;+ requireResidentKey?: boolean;+ residentKey?: ResidentKeyRequirement;+ userVerification?: UserVerificationRequirement;+ };+ attestation?: AttestationConveyancePreference;+ extensions?: AuthenticationExtensionsClientInputs;+ };+ origin: string;+};++export type WebAuthnGetEventDetail = {+ requestId: string;+ publicKey: {+ challenge: string; // base64 encoded+ timeout?: number;+ rpId?: string;+ allowCredentials?: Array<{ type: string; id: string; transports?: string[] }>;+ userVerification?: UserVerificationRequirement;+ extensions?: AuthenticationExtensionsClientInputs;+ };+ origin: string;+};++export type WebAuthnCreateResponseDetail = {+ requestId: string;+ credential?: ProviderCreateCredential;+ fallback?: boolean;+ cancelled?: boolean;+ error?: string;+};++export type WebAuthnGetResponseDetail = {+ requestId: string;+ credential?: ProviderGetCredential;+ fallback?: boolean;+ cancelled?: boolean;+ error?: string;+};