Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add response types and more unit tests (#520)
Leendert de Borst46e217f52392
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsxindex 67c5f0230..396604021 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx@@ -7,7 +7,7 @@ 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';+import type { GetRequest, StoredPasskeyRecord, PasskeyGetCredentialResponse } from '@/utils/passkey/types';interface IPasskeyRequest {type: 'get';@@ -112,7 +112,7 @@ const PasskeyAuthenticate: React.FC = () => {};// Get the assertion using the provider- const credential = await provider.getAssertion(getRequest, credentialId, {+ const credential: PasskeyGetCredentialResponse = await provider.getAssertion(getRequest, credentialId, {uvPerformed: true, // Set to true if you implement actual user verificationincludeBEBS: true // Include backup-eligible and backup-state flags});diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsxindex f33c1a828..2b504d006 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx@@ -8,7 +8,7 @@ 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';+import type { CreateRequest, StoredPasskeyRecord, PasskeyCreateCredentialResponse } from '@/utils/passkey/types';interface IPasskeyRequest {type: 'create';@@ -122,7 +122,7 @@ const PasskeyCreate: React.FC = () => {// 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 = {+ const flattenedCredential: PasskeyCreateCredentialResponse = {id: credential.id,rawId: credential.rawId,clientDataJSON: credential.response.clientDataJSON,diff --git a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.tsindex 51b8fe29d..0b227a102 100644--- a/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts+++ b/apps/browser-extension/src/utils/passkey/AliasVaultPasskeyProvider.ts@@ -109,7 +109,7 @@ export class AliasVaultPasskeyProvider {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 challengeB64u = this.challengeToB64u(req.publicKey.challenge);const clientDataObj = {type: 'webauthn.create',challenge: challengeB64u,@@ -127,12 +127,18 @@ 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;+ if (req.publicKey.user?.id) {+ userIdB64u = this.userIdToB64u(req.publicKey.user.id);+ }+const stored: StoredPasskeyRecord = {rpId,credentialId: credentialIdB64u,publicKey: pubJwk,privateKey: prvJwk,- userId: req.publicKey.user?.id ?? null,+ userId: userIdB64u,userName: req.publicKey.user?.name,userDisplayName: req.publicKey.user?.displayName,lastUsedAt: Date.now()@@ -204,7 +210,7 @@ export class AliasVaultPasskeyProvider {const authenticatorData = this.concat(rpIdHash, new Uint8Array([flags]), signCount);// 5) clientDataJSON- const challengeB64u = this.asB64u(req.publicKey.challenge);+ const challengeB64u = this.challengeToB64u(req.publicKey.challenge);const clientDataObj = {type: 'webauthn.get',challenge: challengeB64u,@@ -232,19 +238,23 @@ export class AliasVaultPasskeyProvider {// 7) Convert raw (r|s) to DER sequenceconst derSig = this.ecdsaRawToDer(rawSig);- /*- * (Optional) Update last used timestamp in your own layer- * (not done here; call a provided callback if you like)- */+ // 8) Encode userHandle (userId) as base64 if present+ // 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+ let userHandleB64: string | null = null;+ if (rec.userId) {+ const userIdBytes = this.fromB64u(rec.userId);+ userHandleB64 = this.toB64(userIdBytes);+ }- // 8) Return object in the flat shape (base64 strings), as your client example expects+ // 9) Return object in the flat shape (base64 strings), as your client example expectsreturn {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+ userHandle: userHandleB64};}@@ -430,16 +440,42 @@ export class AliasVaultPasskeyProvider {return out;}- /** Normalize unknown challenge types to base64url string. */- private asB64u(challenge: ArrayBuffer | Uint8Array | string): string {+ /**+ * Normalize challenge to base64url string.+ * Challenges from the web page are already base64url encoded by the injection script.+ * Only ArrayBuffer/Uint8Array need conversion.+ */+ private challengeToB64u(challenge: ArrayBuffer | Uint8Array | string): string {if (typeof challenge === 'string') {- // Assume already base64url. If you need robustness, validate and convert if not.+ // Already base64url from injection script - use as-isreturn challenge;}const bytes = challenge instanceof Uint8Array ? challenge : new Uint8Array(challenge);return this.toB64u(bytes);}+ /**+ * Normalize userId to base64url string.+ * userId can be:+ * - ArrayBuffer/Uint8Array from WebAuthn API (needs encoding)+ * - Plain UTF-8 string from test/simple cases (needs encoding)+ * - Already base64url encoded string (use as-is)+ */+ private userIdToB64u(userId: ArrayBuffer | Uint8Array | string): string {+ if (typeof userId === 'string') {+ // Check if it's already base64url (contains only valid base64url chars)+ if (/^[A-Za-z0-9_-]+$/.test(userId) && userId.length % 4 !== 1) {+ // Looks like base64url already (and not an invalid length)+ return userId;+ } else {+ // Plain UTF-8 string, encode it+ return this.toB64u(this.te(userId));+ }+ }+ const bytes = userId instanceof Uint8Array ? userId : new Uint8Array(userId);+ return this.toB64u(bytes);+ }+/** Left-pad to 32 bytes (P-256 coord). */private pad32(b: Uint8Array): Uint8Array {if (b.length === 32) {diff --git a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.tsindex 650d5634b..9a82dafd7 100644--- a/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts+++ b/apps/browser-extension/src/utils/passkey/__tests__/AliasVaultPasskeyProvider.test.ts@@ -100,6 +100,55 @@ describe('AliasVaultPasskeyProvider', () => {expect(clientData.crossOrigin).toBe(false);});+ it('should preserve challenge when passed as ArrayBuffer (real-world scenario)', async () => {+ // Simulate what a real website does: generates random bytes for challenge+ const challengeBytes = crypto.getRandomValues(new Uint8Array(32));+ const challengeArrayBuffer = challengeBytes.buffer;++ // Convert to base64url for transmission (what injection script does)+ const toBase64url = (bytes: Uint8Array): string => {+ let binary = '';+ for (let i = 0; i < bytes.length; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');+ };+ const challengeB64u = toBase64url(challengeBytes);++ const createRequest: CreateRequest = {+ origin: 'https://example.com',+ publicKey: {+ // Our provider receives the base64url string (from injection script)+ challenge: challengeB64u,+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }]+ }+ };++ const result = await provider.createPasskey(createRequest);++ // Decode clientDataJSON and verify challenge matches+ const clientDataJSON = atob(result.credential.response.clientDataJSON);+ const clientData = JSON.parse(clientDataJSON);++ // The challenge in clientDataJSON should match what we sent+ expect(clientData.challenge).toBe(challengeB64u);++ // Verify we can decode it back to the original bytes+ const fromBase64url = (b64u: string): Uint8Array => {+ const b64 = b64u.replace(/-/g, '+').replace(/_/g, '/');+ const pad = b64.length % 4 === 2 ? '==' : b64.length % 4 === 3 ? '=' : '';+ const binary = atob(b64 + pad);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return bytes;+ };++ const decodedChallenge = fromBase64url(clientData.challenge);+ expect(Array.from(decodedChallenge)).toEqual(Array.from(challengeBytes));+ });+it('should decode and validate attestationObject structure', async () => {const createRequest: CreateRequest = {origin: 'https://test.com',@@ -241,7 +290,9 @@ describe('AliasVaultPasskeyProvider', () => {expect(assertion.clientDataJSON).toBeDefined();expect(assertion.authenticatorData).toBeDefined();expect(assertion.signature).toBeDefined();- expect(assertion.userHandle).toBeNull();+ // userHandle should be present when user.id was provided during creation+ expect(assertion.userHandle).toBeDefined();+ expect(assertion.userHandle).not.toBeNull();});it('should decode and validate clientDataJSON for authentication', async () => {@@ -413,6 +464,76 @@ describe('AliasVaultPasskeyProvider', () => {expect(flags & 0x04).toBe(0x04);});+ it('should return userHandle when user.id was provided during creation', async () => {+ // Create passkey with explicit user.id (use bytes to avoid encoding ambiguity)+ const userIdBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);+ 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 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);++ // userHandle should be present and be base64 encoded+ expect(assertion.userHandle).toBeDefined();+ expect(assertion.userHandle).not.toBeNull();++ // Decode and verify it matches the original user.id bytes+ 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));+ }+ });++ it('should return null userHandle when user.id was not provided', async () => {+ // Create passkey without user.id+ 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);++ // userHandle should be null when no user.id was provided+ expect(assertion.userHandle).toBeNull();+ });+it('should not set BE/BS flags when includeBEBS is false', async () => {// Create passkeyconst createRequest: CreateRequest = {diff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.tsindex 98ffc73eb..431ee7691 100644--- a/apps/browser-extension/src/utils/passkey/types.ts+++ b/apps/browser-extension/src/utils/passkey/types.ts@@ -2,12 +2,31 @@* Type definitions for the AliasVaultPasskeyProvider*/+/**+ * WebAuthn credential response types (for injection script compatibility)+ */+export type PasskeyCreateCredentialResponse = {+ id: string; // base64url credential ID+ rawId: string; // base64url (same as id for compatibility)+ clientDataJSON: string; // base64 encoded client data JSON+ attestationObject: string; // base64 encoded attestation object (CBOR)+};++export type PasskeyGetCredentialResponse = {+ id: string; // base64url credential ID+ rawId: string; // base64url (same as id for compatibility)+ clientDataJSON: string; // base64 encoded client data JSON+ authenticatorData: string; // base64 encoded authenticator data+ signature: string; // base64 encoded DER signature+ userHandle: string | null; // base64 encoded user ID (null if not provided during creation)+};+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;+ userId?: string | null; // base64url encoded user.id (stored as string for consistency)userName?: string;userDisplayName?: string;lastUsedAt?: number;