Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor (#520)
Leendert de Borst0ffb14ba0a82
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex 8b779af36..7d1c797f5 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -1,3 +1,7 @@+/**+ * Background script entry point - handles messages from the content script+ */+import { onMessage, sendMessage } from "webext-bridge/background";import { handleResetAutoLockTimer, handlePopupHeartbeat, handleSetAutoLockTimeout } from '@/entrypoints/background/AutolockTimeoutHandler';@@ -8,7 +12,7 @@ import { handleOpenPopup, handlePopupWithCredential, handleOpenPopupCreateCredenimport { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault } from '@/entrypoints/background/VaultMessageHandler';import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';-import type { EncryptionKeyDerivationParams } from '@/utils/dist/shared/models/metadata';+import { EncryptionKeyDerivationParams } from "@/utils/dist/shared/models/metadata";import { defineBackground, storage, browser } from '#imports';@@ -65,15 +69,15 @@ export default defineBackground({// Passkey/WebAuthn management messagesonMessage('GET_WEBAUTHN_SETTINGS', () => handleGetWebAuthnSettings());- 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; newSignCount?: number }));+ onMessage('WEBAUTHN_CREATE', ({ data }) => handleWebAuthnCreate(data));+ onMessage('WEBAUTHN_GET', ({ data }) => handleWebAuthnGet(data));+ onMessage('STORE_PASSKEY', ({ data }) => handleStorePasskey(data));+ onMessage('UPDATE_PASSKEY_LAST_USED', ({ data }) => handleUpdatePasskeyLastUsed(data));onMessage('CLEAR_ALL_PASSKEYS', () => handleClearAllPasskeys());- onMessage('DELETE_PASSKEY', ({ data }) => handleDeletePasskey(data as { credentialId: string }));- 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 }));- onMessage('GET_PASSKEY_BY_ID', ({ data }) => handleGetPasskeyById(data as { credentialId: string }));+ onMessage('DELETE_PASSKEY', ({ data }) => handleDeletePasskey(data));+ onMessage('PASSKEY_POPUP_RESPONSE', ({ data }) => handlePasskeyPopupResponse(data));+ onMessage('GET_REQUEST_DATA', ({ data }) => handleGetRequestData(data));+ onMessage('GET_PASSKEY_BY_ID', ({ data }) => handleGetPasskeyById(data));// Initialize passkeys from storage TODO: remove this once proper vault integration is addedawait initializePasskeys();diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.tsindex da04bf50e..533374164 100644--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts@@ -3,6 +3,24 @@* TODO: review this file*/+/* eslint-disable @typescript-eslint/no-explicit-any */++import type {+ StorePasskeyRequest,+ UpdatePasskeyLastUsedRequest,+ DeletePasskeyRequest,+ GetPasskeyByIdRequest,+ GetRequestDataRequest,+ PasskeyPopupResponse,+ WebAuthnCreateRequest,+ WebAuthnGetRequest,+ PendingPasskeyRequest,+ PendingPasskeyCreateRequest,+ PendingPasskeyGetRequest,+ WebAuthnCreationPayload,+ WebAuthnPublicKeyGetPayload+} from '@/utils/passkey/types';+import { storage, browser } from '#imports';interface IPasskeyData {@@ -31,7 +49,7 @@ const pendingRequests = new Map<string, {}>();// Store request data temporarily (to avoid URL length limits)-const pendingRequestData = new Map<string, any>();+const pendingRequestData = new Map<string, PendingPasskeyRequest>();/*** Handle WebAuthn settings request@@ -48,23 +66,16 @@ export async function handleGetWebAuthnSettings(): Promise<{ enabled: boolean }>/*** Handle WebAuthn create (registration) request*/-export async function handleWebAuthnCreate(data: {- publicKey: unknown;- origin: string;-}): Promise<any> {- const { publicKey, origin } = data;+export async function handleWebAuthnCreate(data: any): Promise<any> {+ const { publicKey, origin } = data as WebAuthnCreateRequest;const requestId = Math.random().toString(36).substr(2, 9);- console.log('handleWebAuthnCreate: requestId', requestId);- console.log('handleWebAuthnCreate: origin', origin);- console.log('handleWebAuthnCreate: publicKey', publicKey);-// Store request data temporarily (to avoid URL length limits)- const requestData = {+ const requestData: PendingPasskeyCreateRequest = {type: 'create',requestId,origin,- publicKey+ publicKey: publicKey as WebAuthnCreationPayload};pendingRequestData.set(requestId, requestData);@@ -90,7 +101,7 @@ export async function handleWebAuthnCreate(data: {const checkClosed = setInterval(async () => {try {if (popup.id) {- const window = await browser.windows.get(popup.id);+ const _window = await browser.windows.get(popup.id);// Window still exists, continue waiting}} catch {@@ -104,29 +115,19 @@ export async function handleWebAuthnCreate(data: {}}, 1000);});- } catch (error) {+ } catch {return { error: 'Failed to create popup window' };}}-interface IPasskeyDisplay {- id: string;- displayName: string;- lastUsed: string | null;-}-/*** Handle WebAuthn get (authentication) request*/-export async function handleWebAuthnGet(data: {- publicKey: { allowCredentials?: Array<{ id: string }> };- origin: string;-}): Promise<any> {- const { publicKey, origin } = data;+export async function handleWebAuthnGet(data: any): Promise<any> {+ const { publicKey, origin } = data as WebAuthnGetRequest;const requestId = Math.random().toString(36).substr(2, 9);// Get passkeys for this origin- console.log('handleWebAuthnGet: origin', origin);const passkeys = getPasskeysForOrigin(origin);// Filter by allowCredentials if specified@@ -134,13 +135,10 @@ export async function handleWebAuthnGet(data: {if (publicKey.allowCredentials && publicKey.allowCredentials.length > 0) {const allowedIds = new Set(publicKey.allowCredentials.map(c => c.id));- console.log('handleWebAuthnGet: allowedIds', Array.from(allowedIds));filteredPasskeys = passkeys.filter(pk => {const matches = allowedIds.has(pk.credentialId);- console.log('handleWebAuthnGet: checking', pk.credentialId, 'matches?', matches);return matches;});- console.log('handleWebAuthnGet: after filter, filteredPasskeys count', filteredPasskeys.length);}let passkeyList = filteredPasskeys.map(pk => ({@@ -148,7 +146,6 @@ export async function handleWebAuthnGet(data: {displayName: pk.displayName,lastUsed: pk.lastUsedAt ? new Date(pk.lastUsedAt).toLocaleDateString() : null}));- console.log('handleWebAuthnGet: final passkeyList', passkeyList);/** If allowCredentials was specified but we have no matches, show all passkeys anyway@@ -156,7 +153,6 @@ export async function handleWebAuthnGet(data: {* 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 => ({id: pk.credentialId,displayName: pk.displayName,@@ -165,11 +161,11 @@ export async function handleWebAuthnGet(data: {}// Store request data temporarily (to avoid URL length limits)- const requestData = {+ const requestData: PendingPasskeyGetRequest = {type: 'get',requestId,origin,- publicKey,+ publicKey: publicKey as WebAuthnPublicKeyGetPayload,passkeys: passkeyList};pendingRequestData.set(requestId, requestData);@@ -196,7 +192,7 @@ export async function handleWebAuthnGet(data: {const checkClosed = setInterval(async () => {try {if (popup.id) {- const window = await browser.windows.get(popup.id);+ const _window = await browser.windows.get(popup.id);// Window still exists, continue waiting}} catch {@@ -210,7 +206,7 @@ export async function handleWebAuthnGet(data: {}}, 1000);});- } catch (error) {+ } catch {return { error: 'Failed to create popup window' };}}@@ -218,26 +214,15 @@ export async function handleWebAuthnGet(data: {/*** Store a new passkey*/-export async function handleStorePasskey(data: {- rpId: string;- credentialId: string;- displayName: string;- publicKey: JsonWebKey;- privateKey: JsonWebKey;- userId?: string | null;- userName?: string;- userDisplayName?: string;-}): Promise<{ success: boolean }> {- const { rpId, credentialId, displayName, publicKey, privateKey, userId, userName, userDisplayName } = data;-- console.log('handleStorePasskey: Storing passkey with raw userId:', userId);+export async function handleStorePasskey(data: any): Promise<{ success: boolean }> {+ const { rpId, credentialId, displayName, publicKey, privateKey, userId, userName, userDisplayName } = data as StorePasskeyRequest;const passkey: IPasskeyData = {id: Date.now().toString(),rpId, // Already processed by the popup, no need to extract domain againcredentialId,displayName,- publicKey,+ publicKey: publicKey as JsonWebKey,privateKey,userId,userName,@@ -288,10 +273,8 @@ export async function handleStorePasskey(data: {/*** Update passkey last used time (sign count always remains 0 for cross-device sync compatibility)*/-export async function handleUpdatePasskeyLastUsed(data: {- credentialId: string;-}): Promise<{ success: boolean }> {- const { credentialId } = data;+export async function handleUpdatePasskeyLastUsed(data: any): Promise<{ success: boolean }> {+ const { credentialId } = data as UpdatePasskeyLastUsedRequest;// Find and update the passkeyfor (const [key, passkey] of sessionPasskeys.entries()) {@@ -328,7 +311,7 @@ function getPasskeysForOrigin(origin: string): IPasskeyData[] {const rpId = origin.replace(/^https?:\/\//, '').split('/')[0];const passkeys: IPasskeyData[] = [];- for (const [key, passkey] of sessionPasskeys.entries()) {+ for (const [_key, passkey] of sessionPasskeys.entries()) {if (passkey.rpId === rpId || passkey.rpId === `.${rpId}`) {passkeys.push(passkey);}@@ -373,13 +356,8 @@ export async function initializePasskeys(): Promise<void> {/*** Handle response from passkey popup*/-export async function handlePasskeyPopupResponse(data: {- requestId: string;- credential?: any;- fallback?: boolean;- cancelled?: boolean;-}): Promise<{ success: boolean }> {- const { requestId, credential, fallback, cancelled } = data;+export async function handlePasskeyPopupResponse(data: any): Promise<{ success: boolean }> {+ const { requestId, credential, fallback, cancelled } = data as PasskeyPopupResponse;const request = pendingRequests.get(requestId);if (!request) {@@ -406,25 +384,23 @@ export async function handlePasskeyPopupResponse(data: {/*** Get passkey by credential ID*/-export async function handleGetPasskeyById(data: { credentialId: string }): Promise<IPasskeyData | null> {- const { credentialId } = data;+export async function handleGetPasskeyById(data: any): Promise<IPasskeyData | null> {+ const { credentialId } = data as GetPasskeyByIdRequest;for (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;}/*** Get request data by request ID*/-export async function handleGetRequestData(data: { requestId: string }): Promise<any> {- const { requestId } = data;+export async function handleGetRequestData(data: any): Promise<PendingPasskeyRequest | null> {+ const { requestId } = data as GetRequestDataRequest;const requestData = pendingRequestData.get(requestId);return requestData || null;}@@ -441,8 +417,8 @@ export async function handleClearAllPasskeys(): Promise<{ success: boolean }> {/*** Delete a specific passkey*/-export async function handleDeletePasskey(data: { credentialId: string }): Promise<{ success: boolean }> {- const { credentialId } = data;+export async function handleDeletePasskey(data: any): Promise<{ success: boolean }> {+ const { credentialId } = data as DeletePasskeyRequest;// Find and remove from session storagelet deletedKey: string | null = null;diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex dbd800b9f..9d49cbbea 100644--- a/apps/browser-extension/src/entrypoints/content.ts+++ b/apps/browser-extension/src/entrypoints/content.ts@@ -1,3 +1,7 @@+/**+ * Content script entry point - handles autofill UI and WebAuthn passkey interception+ */+import '@/entrypoints/contentScript/style.css';import { onMessage } from "webext-bridge/content-script";@@ -27,11 +31,12 @@ export default defineContentScript({return;}- // Initialize WebAuthn interceptor early (before page scripts run)+ /*+ * Initialize WebAuthn interceptor early (before page scripts run)+ * TODO: is this actualyl configurable?+ */const webAuthnEnabled = await isWebAuthnInterceptionEnabled();- console.log('[AliasVault] Content: WebAuthn interception enabled:', webAuthnEnabled);if (webAuthnEnabled) {- console.log('[AliasVault] Content: Initializing WebAuthn interceptor');await initializeWebAuthnInterceptor(ctx);}diff --git a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.tsindex 0f1e77e1f..95e259fe9 100644--- a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts@@ -13,7 +13,6 @@ let interceptorInitialized = false;* Initialize the WebAuthn interceptor*/export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {- console.log('[AliasVault] WebAuthnInterceptor: Initializing, interceptorInitialized:', interceptorInitialized);if (interceptorInitialized) {return;}@@ -21,7 +20,6 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {// Listen for WebAuthn create events from the pagewindow.addEventListener('aliasvault:webauthn:create', async (event: any) => {const { requestId, publicKey, origin } = event.detail;- console.log('[AliasVault] WebAuthnInterceptor: Received webauthn:create event', { requestId, origin });try {// Send to background script to handle@@ -30,8 +28,6 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {origin}, 'background');- console.log('[AliasVault] WebAuthnInterceptor: Background response for create', result);-// Send response back to pagewindow.dispatchEvent(new CustomEvent('aliasvault:webauthn:create:response', {detail: {@@ -60,11 +56,6 @@ 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: {@@ -84,25 +75,23 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {// Inject the page scriptconst script = document.createElement('script');- script.src = browser.runtime.getURL('/webauthn-inject.js');+ script.src = browser.runtime.getURL('/webauthn.js');script.async = true;(document.head || document.documentElement).appendChild(script);/**- *+ * onload*/- script.onload = () => {- console.log('[AliasVault] WebAuthnInterceptor: Injected script loaded successfully');+ script.onload = () : void => {script.remove();};/**- *+ * onerror*/- script.onerror = () => {+ script.onerror = () : void => {console.error('[AliasVault] WebAuthnInterceptor: Failed to load injected script');};interceptorInitialized = true;- console.log('[AliasVault] WebAuthnInterceptor: Initialization complete');}/**diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsxindex 285db7022..02ff5ea54 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx@@ -7,34 +7,22 @@ import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';import { useLoading } from '@/entrypoints/popup/context/LoadingContext';import { AliasVaultPasskeyProvider } from '@/utils/passkey/AliasVaultPasskeyProvider';-import type { GetRequest, StoredPasskeyRecord, PasskeyGetCredentialResponse } from '@/utils/passkey/types';--interface IPasskeyRequest {- type: 'get';- requestId: string;- origin: string;- publicKey: any;- passkeys?: Array<{- id: string;- displayName: string;- lastUsed: string | null;- }>;-}+import type { GetRequest, StoredPasskeyRecord, PasskeyGetCredentialResponse, PendingPasskeyGetRequest } from '@/utils/passkey/types';/**- *+ * PasskeyAuthenticate*/const PasskeyAuthenticate: React.FC = () => {const location = useLocation();const { setIsInitialLoading } = useLoading();- const [request, setRequest] = useState<IPasskeyRequest | null>(null);+ const [request, setRequest] = useState<PendingPasskeyGetRequest | null>(null);const [selectedPasskey, setSelectedPasskey] = useState<string | null>(null);const [loading, setLoading] = useState(false);useEffect(() => {/**- *+ * fetchRequestData*/- const fetchRequestData = async () => {+ const fetchRequestData = async () : Promise<void> => {// Get the requestId from URLconst params = new URLSearchParams(location.search);const requestId = params.get('requestId');@@ -42,23 +30,9 @@ const PasskeyAuthenticate: React.FC = () => {if (requestId) {try {// Fetch the full request data from background- const response = await sendMessage('GET_REQUEST_DATA', { requestId }, 'background');- console.log('PasskeyAuthenticate: full response', response);- console.log('PasskeyAuthenticate: response type', typeof response);- const keys = response ? Object.keys(response) : [];- console.log('PasskeyAuthenticate: response keys', keys);- keys.forEach(key => {- console.log(`PasskeyAuthenticate: ${key} =`, (response as any)[key]);- });-- // The response might be wrapped in a data property- const data = response;- console.log('PasskeyAuthenticate: request data', data);- console.log('PasskeyAuthenticate: passkeys', data?.passkeys);- console.log('PasskeyAuthenticate: passkeys is array?', Array.isArray(data?.passkeys));- console.log('PasskeyAuthenticate: passkeys length', data?.passkeys?.length);-- if (data) {+ const data = await sendMessage('GET_REQUEST_DATA', { requestId }, 'background') as unknown as PendingPasskeyGetRequest;++ if (data && data.type === 'get') {setRequest(data);}} catch (error) {@@ -76,7 +50,7 @@ const PasskeyAuthenticate: React.FC = () => {/*** Handle passkey authentication*/- const handleUsePasskey = async (credentialId: string) => {+ const handleUsePasskey = async (credentialId: string) : Promise<void> => {if (!request) {return;}@@ -84,18 +58,14 @@ const PasskeyAuthenticate: React.FC = () => {setLoading(true);try {- console.log('PasskeyAuthenticate: Starting authentication');- console.log('PasskeyAuthenticate: credentialId', credentialId);- console.log('PasskeyAuthenticate: request', request);-// Create the provider with storage callbacksconst provider = new AliasVaultPasskeyProvider(async (record: StoredPasskeyRecord) => {// Not used during authentication- await sendMessage('STORE_PASSKEY', record as any, 'background');+ await sendMessage('STORE_PASSKEY', record, 'background');},- async (credentialId: string) => {- const result = await sendMessage('GET_PASSKEY_BY_ID', { credentialId }, 'background');+ async (credentialId: string) : Promise<StoredPasskeyRecord | null> => {+ const result = await sendMessage('GET_PASSKEY_BY_ID', { credentialId }, 'background') as StoredPasskeyRecord | null;return result || null;});@@ -105,6 +75,7 @@ const PasskeyAuthenticate: React.FC = () => {origin: request.origin,requestId: request.requestId,publicKey: {+ // TODO: check request.publicKey type and actual stored datarpId: request.publicKey.rpId,challenge: request.publicKey.challenge,userVerification: request.publicKey.userVerification@@ -136,8 +107,10 @@ const PasskeyAuthenticate: React.FC = () => {console.info('PasskeyAuthenticate: Authentication complete.');setLoading(false);- // Uncomment to auto-close:- // window.close();+ /*+ * Uncomment to auto-close:+ * window.close();+ */} catch (error) {console.error('PasskeyAuthenticate: Error during authentication', error);setLoading(false);@@ -148,7 +121,7 @@ const PasskeyAuthenticate: React.FC = () => {/*** Handle passkey deletion*/- const handleDeletePasskey = async (credentialId: string, event: React.MouseEvent) => {+ const handleDeletePasskey = async (credentialId: string, event: React.MouseEvent) : Promise<void> => {event.stopPropagation(); // Prevent triggering authenticationif (!confirm('Are you sure you want to delete this passkey?')) {@@ -175,9 +148,9 @@ const PasskeyAuthenticate: React.FC = () => {};/**- *+ * Handle fallback*/- const handleFallback = async () => {+ const handleFallback = async () : Promise<void> => {if (!request) {return;}@@ -192,9 +165,9 @@ const PasskeyAuthenticate: React.FC = () => {};/**- *+ * Handle cancel*/- const handleCancel = async () => {+ const handleCancel = async () : Promise<void> => {if (!request) {return;}diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsxindex 41b7c5305..e3ccc51fa 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx@@ -8,43 +8,32 @@ import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';import { useLoading } from '@/entrypoints/popup/context/LoadingContext';import { AliasVaultPasskeyProvider } from '@/utils/passkey/AliasVaultPasskeyProvider';-import type { CreateRequest, StoredPasskeyRecord, PasskeyCreateCredentialResponse } from '@/utils/passkey/types';--interface IPasskeyRequest {- type: 'create';- requestId: string;- origin: string;- publicKey: any;-}+import type { CreateRequest, StoredPasskeyRecord, PasskeyCreateCredentialResponse, PendingPasskeyCreateRequest } from '@/utils/passkey/types';/**- *+ * PasskeyCreate*/const PasskeyCreate: React.FC = () => {const location = useLocation();const { setIsInitialLoading } = useLoading();- const [request, setRequest] = useState<IPasskeyRequest | null>(null);+ const [request, setRequest] = useState<PendingPasskeyCreateRequest | null>(null);const [displayName, setDisplayName] = useState('My Passkey');const [loading, setLoading] = useState(false);useEffect(() => {/**- *+ * fetchRequestData*/- const fetchRequestData = async () => {- console.log(location);+ const fetchRequestData = async () : Promise<void> => {// Get the requestId from URLconst params = new URLSearchParams(location.search);const requestId = params.get('requestId');- console.log('PasskeyCreate: requestId', requestId);-if (requestId) {try {// Fetch the full request data from background- const data = await sendMessage('GET_REQUEST_DATA', { requestId }, 'background');- console.log('PasskeyCreate: website create request:', data);- if (data) {+ const data = await sendMessage('GET_REQUEST_DATA', { requestId }, 'background') as unknown as PendingPasskeyCreateRequest;+ if (data && data.type === 'create') {setRequest(data);if (data.publicKey?.user?.displayName) {@@ -65,7 +54,7 @@ const PasskeyCreate: React.FC = () => {/*** Handle passkey creation*/- const handleCreate = async () => {+ const handleCreate = async () : Promise<void> => {if (!request) {return;}@@ -73,7 +62,10 @@ const PasskeyCreate: React.FC = () => {setLoading(true);try {- // Create the provider with storage callbacks+ /*+ * Create the provider with storage callbacks+ * TODO: refactor this flow to be simpler.+ */const provider = new AliasVaultPasskeyProvider(async (record: StoredPasskeyRecord) => {await sendMessage('STORE_PASSKEY', {@@ -87,8 +79,8 @@ const PasskeyCreate: React.FC = () => {userDisplayName: record.userDisplayName} as any, 'background');},- async (credentialId: string) => {- const result = await sendMessage('GET_PASSKEY_BY_ID', { credentialId }, 'background');+ async (credentialId: string) : Promise<StoredPasskeyRecord | null> => {+ const result = await sendMessage('GET_PASSKEY_BY_ID', { credentialId }, 'background') as StoredPasskeyRecord | null;return result || null;});@@ -114,9 +106,11 @@ const PasskeyCreate: React.FC = () => {console.info('PasskeyCreate: Created credential successfully', credential);- // 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 }+ /*+ * 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: PasskeyCreateCredentialResponse = {id: credential.id,rawId: credential.rawId,@@ -134,8 +128,10 @@ const PasskeyCreate: React.FC = () => {console.info('PasskeyCreate: Passkey created successfully.');setLoading(false);- // Uncomment to auto-close:- // window.close();+ /*+ * Uncomment to auto-close:+ * window.close();+ */} catch (error) {console.error('PasskeyCreate: Error creating passkey', error);setLoading(false);@@ -144,9 +140,9 @@ const PasskeyCreate: React.FC = () => {};/**- *+ * Handle fallback*/- const handleFallback = async () => {+ const handleFallback = async () : Promise<void> => {if (!request) {return;}@@ -161,9 +157,9 @@ const PasskeyCreate: React.FC = () => {};/**- *+ * Handle cancel*/- const handleCancel = async () => {+ const handleCancel = async () : Promise<void> => {if (!request) {return;}diff --git a/apps/browser-extension/src/entrypoints/webauthn-inject.ts b/apps/browser-extension/src/entrypoints/webauthn.tssimilarity index 78%rename from apps/browser-extension/src/entrypoints/webauthn-inject.tsrename to apps/browser-extension/src/entrypoints/webauthn.tsindex bf6eef6eb..680030fc9 100644--- a/apps/browser-extension/src/entrypoints/webauthn-inject.ts+++ b/apps/browser-extension/src/entrypoints/webauthn.ts@@ -1,9 +1,9 @@/**- * WebAuthn injection script - runs in page context to intercept credentials API- * This is a public entry point that will be included in web_accessible_resources+ * WebAuthn override injection script - included in web_accessible_resources as "webauthn.js"+ * and runs in page context to override the browser's built-in credentials API.*/-import { defineUnlistedScript } from '#imports';+/* eslint-disable @typescript-eslint/no-explicit-any */import type {WebAuthnCreateEventDetail,@@ -12,7 +12,9 @@ import type {WebAuthnGetResponseDetail,ProviderCreateCredential,ProviderGetCredential-} from '@/utils/passkey/webauthn-inject.types';+} from '@/utils/passkey/webauthn.types';++import { defineUnlistedScript } from '#imports';export default defineUnlistedScript(() => {// Only run once@@ -24,9 +26,8 @@ export default defineUnlistedScript(() => {const originalCreate = navigator.credentials.create.bind(navigator.credentials);const originalGet = navigator.credentials.get.bind(navigator.credentials);- // Helper to convert ArrayBuffer to base64/**- *+ * Helper to convert ArrayBuffer to base64*/function bufferToBase64(buffer: ArrayBuffer | ArrayBufferView): string {const bytes = buffer instanceof ArrayBuffer@@ -39,9 +40,8 @@ export default defineUnlistedScript(() => {return btoa(binary);}- // Helper to convert base64/base64url to ArrayBuffer/**- *+ * Helper to convert ArrayBuffer to base64*/function base64ToBuffer(base64: string): ArrayBuffer {// Handle both base64 and base64url formats@@ -56,13 +56,10 @@ export default defineUnlistedScript(() => {return bytes.buffer;}- // Override credentials.create/**- *+ * Override credentials.create (monkey patch)*/- navigator.credentials.create = async function(options?: CredentialCreationOptions) {- console.log('[AliasVault] Page: Intercepted credentials.create', options);-+ navigator.credentials.create = async function(options?: CredentialCreationOptions) : Promise<Credential | null> {if (!options?.publicKey) {return originalCreate(options);}@@ -95,22 +92,21 @@ export default defineUnlistedScript(() => {const timeout = setTimeout(() => {cleanup();// Timeout - fall back to native- console.log('[AliasVault] Page: Timeout, falling back to native');originalCreate(options).then(resolve).catch(reject);}, 30000); // 30 second timeout/**- *+ * cleanup*/- function cleanup() {+ function cleanup() : void {clearTimeout(timeout);window.removeEventListener('aliasvault:webauthn:create:response', handler as EventListener);}/**- *+ * handler*/- function handler(e: CustomEvent<WebAuthnCreateResponseDetail>) {+ function handler(e: CustomEvent<WebAuthnCreateResponseDetail>) : void {if (e.detail.requestId !== requestId) {return;}@@ -119,22 +115,22 @@ export default defineUnlistedScript(() => {if (e.detail.fallback) {// User chose to use native implementation- console.log('[AliasVault] Page: User chose native, falling back');originalCreate(options).then(resolve).catch(reject);} else if (e.detail.error) {reject(new Error(e.detail.error));} else if (e.detail.credential) {// Create a proper credential object with required methodsconst cred: ProviderCreateCredential = e.detail.credential;- console.log('[AliasVault] Page: Creating credential response from:', cred);try {// Decode the attestation object to extract authenticator dataconst 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)+ /*+ * 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)@@ -171,42 +167,37 @@ export default defineUnlistedScript(() => {clientDataJSON: base64ToBuffer(cred.clientDataJSON),attestationObject: attestationObjectBuffer,/**- *+ * getTransports*/- getTransports() {+ getTransports() : string[] {return ['internal'];},/**- *+ * getAuthenticatorData*/- getAuthenticatorData() {+ getAuthenticatorData() : ArrayBuffer {return authDataBuffer;},/**- *+ * getPublicKey*/- getPublicKey() {+ getPublicKey() : JsonWebKey | null {return null;},/**- *+ * getPublicKeyAlgorithm*/- getPublicKeyAlgorithm() {+ getPublicKeyAlgorithm() : number {return -7; // ES256}},/**- *+ * getClientExtensionResults*/- getClientExtensionResults() {+ getClientExtensionResults() : any {return {};}};- 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);@@ -222,15 +213,11 @@ export default defineUnlistedScript(() => {});};- // Override credentials.get/**- *+ * Override credentials.get (monkey patch)*/- navigator.credentials.get = async function(options?: CredentialRequestOptions) {- console.log('[AliasVault] Page: Intercepted credentials.get', options);-+ navigator.credentials.get = async function(options?: CredentialRequestOptions) : Promise<Credential | null> {if (!options?.publicKey) {- console.log('[AliasVault] Page: No public key, falling back to native');return originalGet(options);}@@ -258,22 +245,21 @@ export default defineUnlistedScript(() => {const timeout = setTimeout(() => {cleanup();// Timeout - fall back to native- console.log('[AliasVault] Page: Timeout, falling back to native');originalGet(options).then(resolve).catch(reject);}, 30000);/**- *+ * cleanup*/- function cleanup() {+ function cleanup() : void {clearTimeout(timeout);window.removeEventListener('aliasvault:webauthn:get:response', handler as EventListener);}/**- *+ * handler*/- function handler(e: CustomEvent<WebAuthnGetResponseDetail>) {+ function handler(e: CustomEvent<WebAuthnGetResponseDetail>) : void {if (e.detail.requestId !== requestId) {return;}@@ -282,14 +268,12 @@ export default defineUnlistedScript(() => {if (e.detail.fallback) {// User chose to use native implementation- console.log('[AliasVault] Page: User chose native, falling back');originalGet(options).then(resolve).catch(reject);} else if (e.detail.error) {reject(new Error(e.detail.error));} else if (e.detail.credential) {// Create a proper credential object with required methodsconst 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',@@ -302,9 +286,9 @@ export default defineUnlistedScript(() => {userHandle: cred.userHandle ? base64ToBuffer(cred.userHandle) : null},/**- *+ * getClientExtensionResults*/- getClientExtensionResults() {+ getClientExtensionResults() : any {return {};}};@@ -319,5 +303,5 @@ export default defineUnlistedScript(() => {});};- console.log('[AliasVault] WebAuthn interceptor initialized in page context');+ console.debug('[AliasVault] WebAuthn inject script loaded successfully');});diff --git a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.tsindex 1a292814b..32c5df42e 100644--- a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts+++ b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts@@ -20,7 +20,7 @@import type { CreateRequest, GetRequest, StoredPasskeyRecord } from './types';/**- *+ * AliasVaultPasskeyProvider*/export class AliasVaultPasskeyProvider {/**@@ -28,7 +28,7 @@ export class AliasVaultPasskeyProvider {* - store: persist a newly created passkey* - getById: fetch a stored passkey (by credentialId)*/- constructor(+ public constructor(private readonly store: (record: StoredPasskeyRecord) => Promise<void>,private readonly getById: (credentialId: string) => Promise<StoredPasskeyRecord | null>) {}@@ -61,13 +61,10 @@ export class AliasVaultPasskeyProvider {stored: StoredPasskeyRecord;}> {// 1) Validate and resolve algorithm (-7 = ES256)- const alg = this.pickSupportedAlgorithm(req.publicKey.pubKeyCredParams);+ this.pickSupportedAlgorithm(req.publicKey.pubKeyCredParams);// 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)@@ -113,9 +110,6 @@ 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,@@ -123,7 +117,6 @@ 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")@@ -133,11 +126,12 @@ export class AliasVaultPasskeyProvider {? 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)- // Store userId as-is (injection script sends it as standard base64 string)+ /*+ * 11) Store the passkey in your vault (so it can be used later for authentication)+ * Store userId as-is (injection script sends it as standard base64 string)+ */let userIdB64: string | null = null;if (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-isuserIdB64 = typeof req.publicKey.user.id === 'string'? req.publicKey.user.id@@ -249,15 +243,15 @@ export class AliasVaultPasskeyProvider {// 7) Convert raw (r|s) to DER sequenceconst derSig = this.ecdsaRawToDer(rawSig);- // 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 already stored as standard base64 (from injection script), return as-is+ /*+ * 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 already stored as standard base64 (from injection script), return as-is+ */let userHandleB64: string | null = null;if (rec.userId) {- console.log('AliasVaultPasskeyProvider.getAssertion: rec.userId (standard base64):', rec.userId);// Return as-is - already in standard base64 formatuserHandleB64 = rec.userId;- console.log('AliasVaultPasskeyProvider.getAssertion: userHandleB64:', userHandleB64);} else {console.warn('AliasVaultPasskeyProvider.getAssertion: No userId found in stored passkey record');}@@ -461,8 +455,10 @@ export class AliasVaultPasskeyProvider {*/private challengeToB64u(challenge: ArrayBuffer | Uint8Array | string): string {if (typeof challenge === 'string') {- // String from injection script - it's standard base64, convert to base64url- // Remove padding and replace + with - and / with _+ /*+ * 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);diff --git a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.tsindex b1d0156db..5afb8bc86 100644--- a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts+++ b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts@@ -103,9 +103,10 @@ describe('AliasVaultPasskeyProvider', () => {it('should preserve challenge when passed as ArrayBuffer (real-world scenario)', async () => {// Simulate what a real website does: generates random bytes for challengeconst challengeBytes = crypto.getRandomValues(new Uint8Array(32));- const challengeArrayBuffer = challengeBytes.buffer;- // Convert to base64url for transmission (what injection script does)+ /**+ * Convert Uint8Array to base64url string+ */const toBase64url = (bytes: Uint8Array): string => {let binary = '';for (let i = 0; i < bytes.length; i++) {@@ -133,7 +134,9 @@ describe('AliasVaultPasskeyProvider', () => {// The challenge in clientDataJSON should match what we sentexpect(clientData.challenge).toBe(challengeB64u);- // Verify we can decode it back to the original bytes+ /**+ * Convert base64url string to Uint8Array+ */const fromBase64url = (b64u: string): Uint8Array => {const b64 = b64u.replace(/-/g, '+').replace(/_/g, '/');const pad = b64.length % 4 === 2 ? '==' : b64.length % 4 === 3 ? '=' : '';@@ -237,12 +240,6 @@ describe('AliasVaultPasskeyProvider', () => {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 mapdiff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.tsindex de058f965..bd4b87f0e 100644--- a/apps/browser-extension/src/utils/passkey/types.ts+++ b/apps/browser-extension/src/utils/passkey/types.ts@@ -12,7 +12,7 @@ export type {ProviderGetCredential,WebAuthnPublicKeyCredential,WebAuthnAssertionCredential-} from './webauthn-inject.types';+} from './webauthn.types';/*** WebAuthn credential response types (for injection script compatibility)@@ -44,6 +44,122 @@ export type StoredPasskeyRecord = {lastUsedAt?: number;};+/**+ * Request to store a new passkey+ * TODO: check actual stored data type, but this will be replaced by vault integration anyway+ */+export type StorePasskeyRequest = {+ rpId: string;+ credentialId: string;+ displayName: string;+ publicKey: WebAuthnCreationPayload;+ privateKey: JsonWebKey;+ userId?: string | null;+ userName?: string;+ userDisplayName?: string;+};++/**+ * Request to update passkey last used timestamp+ */+export type UpdatePasskeyLastUsedRequest = {+ credentialId: string;+};++/**+ * Request to delete a passkey+ */+export type DeletePasskeyRequest = {+ credentialId: string;+};++/**+ * Request to get passkey by ID+ */+export type GetPasskeyByIdRequest = {+ credentialId: string;+};++/**+ * Request to get pending request data+ */+export type GetRequestDataRequest = {+ requestId: string;+};++/**+ * Passkey popup response+ */+export type PasskeyPopupResponse = {+ requestId: string;+ credential?: PasskeyCreateCredentialResponse;+ fallback?: boolean;+ cancelled?: boolean;+};++/**+ * WebAuthn create request+ */+export type WebAuthnCreateRequest = {+ publicKey: unknown;+ origin: string;+};++/**+ * WebAuthn get request+ */+export type WebAuthnGetRequest = {+ publicKey: {+ allowCredentials?: Array<{ id: string }>;+ };+ origin: string;+};++/**+ * Pending passkey request data for create operation+ * TODO: check usage chain+ */+export type PendingPasskeyCreateRequest = {+ type: 'create';+ requestId: string;+ origin: string;+ publicKey: WebAuthnCreationPayload;+};++/**+ * Pending passkey request data for get/authenticate operation+ * TODO: check usage chain+ */+export type PendingPasskeyGetRequest = {+ type: 'get';+ requestId: string;+ origin: string;+ publicKey: WebAuthnPublicKeyGetPayload;+ passkeys: Array<{+ id: string;+ displayName: string;+ lastUsed: string | null;+ }>;+};++export type WebAuthnPublicKeyGetPayload = {+ challenge: string; // Base64URL-encoded challenge+ timeout?: number;+ rpId: string;+ allowCredentials?: {+ id: string; // Base64URL-encoded credential ID+ type: "public-key";+ transports?: string[];+ }[];+ userVerification: "required" | "preferred" | "discouraged";+ hints?: string[];+};++/**+ * Union type for all pending passkey requests+ */+export type PendingPasskeyRequest = PendingPasskeyCreateRequest | PendingPasskeyGetRequest;+export type CreateRequest = {origin: string; // e.g. "https://example.com"requestId?: string; // optional correlation id (if you need it)@@ -65,9 +181,39 @@ export type CreateRequest = {export type GetRequest = {origin: string;requestId?: string;- publicKey: {- rpId?: string;- challenge: ArrayBuffer | Uint8Array | string; // often base64url string from page- userVerification?: 'required' | 'preferred' | 'discouraged';- };+ publicKey: WebAuthnPublicKeyGetPayload};++export type WebAuthnCreationPayload = {+ rp: {+ name: string;+ id: string;+ };+ user: {+ id: string; // Base64URL-encoded user ID+ name: string;+ displayName: string;+ };+ challenge: string; // Base64URL-encoded challenge+ pubKeyCredParams: {+ type: "public-key";+ alg: number; // COSE algorithm identifier+ }[];+ timeout: number;+ excludeCredentials: {+ id: string; // Base64URL-encoded credential ID+ type: "public-key";+ transports: string[];+ }[];+ authenticatorSelection: {+ residentKey: "discouraged" | "preferred" | "required";+ requireResidentKey: boolean;+ userVerification: "required" | "preferred" | "discouraged";+ };+ attestation: "none" | "indirect" | "direct" | "enterprise";+ hints: string[];+ extensions?: {+ credProps?: boolean;+ [key: string]: unknown;+ };+};\ No newline at end of filediff --git a/apps/browser-extension/src/utils/passkey/webauthn-inject.types.ts b/apps/browser-extension/src/utils/passkey/webauthn.types.tssimilarity index 100%rename from apps/browser-extension/src/utils/passkey/webauthn-inject.types.tsrename to apps/browser-extension/src/utils/passkey/webauthn.types.tsdiff --git a/apps/browser-extension/src/utils/webauthn/PasskeyCreator.ts b/apps/browser-extension/src/utils/webauthn/PasskeyCreator.tsdeleted file mode 100644index 73d1f8f8d..000000000--- a/apps/browser-extension/src/utils/webauthn/PasskeyCreator.ts+++ /dev/null@@ -1,364 +0,0 @@-/**- * 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- };-}diff --git a/apps/browser-extension/wxt.config.ts b/apps/browser-extension/wxt.config.tsindex 5f496c773..48c4e616d 100644--- a/apps/browser-extension/wxt.config.ts+++ b/apps/browser-extension/wxt.config.ts@@ -37,7 +37,7 @@ export default defineConfig({}},web_accessible_resources: [{- resources: ["webauthn-inject.js"],+ resources: ["webauthn.js"],matches: ["<all_urls>"]}]};