Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add iOS passkey logic scaffolding (#520)
Leendert de Borst5b62b035eedd
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxprojindex d1f0ebe77..d220e2ca8 100644--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj@@ -1156,7 +1156,7 @@INFOPLIST_FILE = AliasVault/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = AliasVault;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1192,7 +1192,7 @@INFOPLIST_FILE = AliasVault/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = AliasVault;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1259,7 +1259,7 @@GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;GCC_WARN_UNUSED_FUNCTION = YES;GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.1;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = (/usr/lib/swift,"$(inherited)",@@ -1314,7 +1314,7 @@GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;GCC_WARN_UNUSED_FUNCTION = YES;GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.1;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = (/usr/lib/swift,"$(inherited)",@@ -1348,7 +1348,7 @@ENABLE_USER_SCRIPT_SANDBOXING = YES;GCC_C_LANGUAGE_STANDARD = gnu17;GENERATE_INFOPLIST_FILE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LOCALIZATION_PREFERS_STRING_CATALOGS = YES;MARKETING_VERSION = 1.0;MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;@@ -1384,7 +1384,7 @@ENABLE_USER_SCRIPT_SANDBOXING = YES;GCC_C_LANGUAGE_STANDARD = gnu17;GENERATE_INFOPLIST_FILE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LOCALIZATION_PREFERS_STRING_CATALOGS = YES;MARKETING_VERSION = 1.0;MTL_FAST_MATH = YES;@@ -1422,7 +1422,7 @@GENERATE_INFOPLIST_FILE = YES;INFOPLIST_KEY_NSHumanReadableCopyright = "";INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1475,7 +1475,7 @@GENERATE_INFOPLIST_FILE = YES;INFOPLIST_KEY_NSHumanReadableCopyright = "";INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1518,7 +1518,7 @@ENABLE_USER_SCRIPT_SANDBOXING = YES;GCC_C_LANGUAGE_STANDARD = gnu17;GENERATE_INFOPLIST_FILE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LOCALIZATION_PREFERS_STRING_CATALOGS = YES;MARKETING_VERSION = 1.0;MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;@@ -1553,7 +1553,7 @@ENABLE_USER_SCRIPT_SANDBOXING = YES;GCC_C_LANGUAGE_STANDARD = gnu17;GENERATE_INFOPLIST_FILE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LOCALIZATION_PREFERS_STRING_CATALOGS = YES;MARKETING_VERSION = 1.0;MTL_FAST_MATH = YES;@@ -1592,7 +1592,7 @@GENERATE_INFOPLIST_FILE = YES;INFOPLIST_KEY_NSHumanReadableCopyright = "";INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1645,7 +1645,7 @@GENERATE_INFOPLIST_FILE = YES;INFOPLIST_KEY_NSHumanReadableCopyright = "";INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1694,7 +1694,7 @@GENERATE_INFOPLIST_FILE = YES;INFOPLIST_KEY_NSHumanReadableCopyright = "";INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1746,7 +1746,7 @@GENERATE_INFOPLIST_FILE = YES;INFOPLIST_KEY_NSHumanReadableCopyright = "";INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1794,7 +1794,7 @@INFOPLIST_FILE = autofill/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = "AliasVault AutoFill";INFOPLIST_KEY_NSHumanReadableCopyright = "";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -1839,7 +1839,7 @@INFOPLIST_FILE = autofill/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = "AliasVault AutoFill";INFOPLIST_KEY_NSHumanReadableCopyright = "";- IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",diff --git a/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift b/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swiftindex 8bd99cf67..9a4a8c19a 100644--- a/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift+++ b/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift@@ -16,13 +16,16 @@ public class CredentialIdentityStore {/// Save credentials into the native iOS credential store.public func saveCredentialIdentities(_ credentials: [Credential]) async throws {- let identities: [ASPasswordCredentialIdentity] = credentials.compactMap { credential in+ var allIdentities: [ASCredentialIdentity] = []++ // Create password identities+ let passwordIdentities: [ASPasswordCredentialIdentity] = credentials.compactMap { credential inguard let urlString = credential.service.url,let url = URL(string: urlString),let host = url.host else {return nil}-+// Use the same logic as the UI for determining the identifierlet identifier = usernameOrEmail(credential: credential)guard !identifier.isEmpty else {@@ -38,19 +41,47 @@ public class CredentialIdentityStore {)}- guard !identities.isEmpty else {+ allIdentities.append(contentsOf: passwordIdentities)++ // Create passkey identities+ let passkeyIdentities: [ASPasskeyCredentialIdentity] = credentials.flatMap { credential -> [ASPasskeyCredentialIdentity] in+ guard let passkeys = credential.passkeys,+ let urlString = credential.service.url,+ let url = URL(string: urlString),+ let host = url.host else {+ return []+ }++ let effectiveDomain = Self.effectiveDomain(from: host)++ return passkeys.compactMap { passkey in+ guard !passkey.isDeleted else { return nil }++ return ASPasskeyCredentialIdentity(+ relyingPartyIdentifier: passkey.rpId,+ userName: passkey.userName ?? usernameOrEmail(credential: credential),+ credentialID: passkey.credentialId,+ userHandle: passkey.userId ?? Data(),+ recordIdentifier: passkey.id.uuidString+ )+ }+ }++ allIdentities.append(contentsOf: passkeyIdentities)++ guard !allIdentities.isEmpty else {print("No valid identities to save.")return}let state = await storeState()- guard state.isEnabled else {- print("Credential identity store is not enabled.")- return+ guard state.isEnabled else {+ print("Credential identity store is not enabled.")+ return}do {- try await store.saveCredentialIdentities(identities)+ try await store.saveCredentialIdentities(allIdentities)} catch {print("Failed to save credential identities to native iOS storage: \(error)")}diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swiftindex 8623153bf..933637879 100644--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift@@ -160,6 +160,104 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle}}+ // MARK: - Passkey Support++ override public func prepareInterface(forPasskeyRegistration registrationRequest: ASCredentialRequest) {+ guard let passkeyRequest = registrationRequest as? ASPasskeyCredentialRequest else {+ extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.failed.rawValue+ ))+ return+ }++ // TODO: Implement passkey registration UI+ // For now, cancel the request+ extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.userCanceled.rawValue+ ))+ }++ override public func prepareInterfaceToProvideCredential(for credentialRequest: ASCredentialRequest) {+ // Check if this is a passkey request+ if let passkeyRequest = credentialRequest as? ASPasskeyCredentialRequest {+ handlePasskeyAuthentication(passkeyRequest)+ return+ }++ // Otherwise, handle as password credential (existing behavior)+ // The existing prepareCredentialList method will be called by the system+ }++ private func handlePasskeyAuthentication(_ request: ASPasskeyCredentialRequest) {+ do {+ let vaultStore = VaultStore()++ // Check sanity before proceeding+ guard sanityChecks(vaultStore: vaultStore) else {+ return+ }++ // Unlock the vault+ try vaultStore.unlockVault()++ let clientDataHash = request.clientDataHash+ let credentialIdentity = request.credentialIdentity as? ASPasskeyCredentialIdentity+ let rpId = credentialIdentity?.relyingPartyIdentifier ?? ""++ // Load passkey from vault using the credential ID+ guard let passkey = try vaultStore.getPasskey(byCredentialId: credentialIdentity?.credentialID ?? Data()) else {+ extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.credentialIdentityNotFound.rawValue+ ))+ return+ }++ // Generate assertion using PasskeyAuthenticator+ let assertion = try PasskeyAuthenticator.getAssertion(+ credentialId: passkey.credentialId,+ clientDataHash: clientDataHash,+ rpId: rpId,+ privateKeyJWK: passkey.privateKey,+ userId: passkey.userId,+ uvPerformed: true, // We verified user with Face ID/Touch ID+ prfInputs: nil, // TODO: Extract PRF inputs from request if needed+ prfSecret: passkey.prfKey+ )++ // Complete the request with passkey assertion credential+ let credential = ASPasskeyAssertionCredential(+ userHandle: assertion.userHandle ?? Data(),+ relyingParty: rpId,+ signature: assertion.signature,+ clientDataHash: clientDataHash,+ authenticatorData: assertion.authenticatorData,+ credentialID: assertion.credentialId+ )++ extensionContext.completeAssertionRequest(using: credential)++ } catch {+ print("PasskeyAuthentication error: \(error)")+ extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.failed.rawValue,+ userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]+ ))+ }+ }++ public func providePasskeyCredentialWithoutUserInteraction(for credentialIdentity: ASPasskeyCredentialIdentity) {+ // TODO: Implement silent passkey authentication+ // For now, fall back to requiring user interaction+ extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.userInteractionRequired.rawValue+ ))+ }+/// This registers all known AliasVault credentials into iOS native credential storage, which iOS can then use to/// suggest autofill credentials when a user focuses an input field on a login form. These suggestions will then be s/// hown above the iOS keyboard, which saves the user one step.diff --git a/apps/mobile-app/ios/Autofill/Info.plist b/apps/mobile-app/ios/Autofill/Info.plistindex 55838aa29..0f458060f 100644--- a/apps/mobile-app/ios/Autofill/Info.plist+++ b/apps/mobile-app/ios/Autofill/Info.plist@@ -21,6 +21,10 @@<dict><key>ProvidesTextToInsert</key><true/>+ <key>ProvidesPasskeys</key>+ <true/>+ <key>ProvidesPasswords</key>+ <true/></dict></dict><key>NSExtensionPointIdentifier</key>diff --git a/apps/mobile-app/ios/VaultModels/Credential.swift b/apps/mobile-app/ios/VaultModels/Credential.swiftindex a3e5f4411..70609fa22 100644--- a/apps/mobile-app/ios/VaultModels/Credential.swift+++ b/apps/mobile-app/ios/VaultModels/Credential.swift@@ -7,6 +7,7 @@ public struct Credential: Codable, Hashable, Equatable {public let username: String?public let notes: String?public let password: Password?+ public let passkeys: [Passkey]? // Array of passkeys linked to this credentialpublic let createdAt: Datepublic let updatedAt: Datepublic let isDeleted: Bool@@ -18,6 +19,7 @@ public struct Credential: Codable, Hashable, Equatable {username: String?,notes: String?,password: Password?,+ passkeys: [Passkey]? = nil,createdAt: Date,updatedAt: Date,isDeleted: Bool@@ -28,6 +30,7 @@ public struct Credential: Codable, Hashable, Equatable {self.username = usernameself.notes = notesself.password = password+ self.passkeys = passkeysself.createdAt = createdAtself.updatedAt = updatedAtself.isDeleted = isDeleteddiff --git a/apps/mobile-app/ios/VaultModels/Passkey.swift b/apps/mobile-app/ios/VaultModels/Passkey.swiftnew file mode 100644index 000000000..615ae7fc0--- /dev/null+++ b/apps/mobile-app/ios/VaultModels/Passkey.swift@@ -0,0 +1,59 @@+import Foundation++/**+ * Passkey model representing a WebAuthn credential+ * Linked to a parent Credential for UI display (service name, logo, etc.)+ */+public struct Passkey: Codable, Hashable, Equatable {+ public let id: UUID+ public let credentialId: Data // 16-byte GUID, converted to base64url for WebAuthn+ public let credentialIdString: String // Parent credential UUID+ public let rpId: String // Relying party identifier (domain)+ public let userId: Data? // User identifier from RP (optional)+ public let userName: String? // User-visible identifier (typically email)+ public let publicKey: Data // JWK format (JSON)+ public let privateKey: Data // JWK format (JSON), encrypted in storage+ public let prfKey: Data? // PRF secret (32 bytes) if extension enabled+ public let displayName: String // User-facing name for this passkey+ public let createdAt: Date+ public let updatedAt: Date+ public let isDeleted: Bool++ public init(+ id: UUID,+ credentialId: Data,+ credentialIdString: String,+ rpId: String,+ userId: Data?,+ userName: String?,+ publicKey: Data,+ privateKey: Data,+ prfKey: Data?,+ displayName: String,+ createdAt: Date,+ updatedAt: Date,+ isDeleted: Bool+ ) {+ self.id = id+ self.credentialId = credentialId+ self.credentialIdString = credentialIdString+ self.rpId = rpId+ self.userId = userId+ self.userName = userName+ self.publicKey = publicKey+ self.privateKey = privateKey+ self.prfKey = prfKey+ self.displayName = displayName+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ self.isDeleted = isDeleted+ }++ public static func == (lhs: Passkey, rhs: Passkey) -> Bool {+ return lhs.id == rhs.id+ }++ public func hash(into hasher: inout Hasher) {+ hasher.combine(id)+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/PasskeyAuthenticator.swift b/apps/mobile-app/ios/VaultStoreKit/PasskeyAuthenticator.swiftnew file mode 100644index 000000000..f0bf8eff7--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/PasskeyAuthenticator.swift@@ -0,0 +1,528 @@+import Foundation+import CryptoKit+import Security++/**+ * PasskeyAuthenticator+ * -------------------------+ * A WebAuthn "virtual authenticator" for iOS credential provider extension.+ * Implements passkey creation (registration) and authentication (assertion) following+ * the WebAuthn Level 2 specification.+ *+ * This is a port of the browser extension PasskeyAuthenticator.ts to native Swift.+ * TODO: review implementation and docs.+ *+ * Key features:+ * - ES256 (ECDSA P-256) key pair generation+ * - CBOR/COSE encoding for attestation objects+ * - Proper authenticator data with WebAuthn flags+ * - Self-attestation (packed format) or none attestation+ * - Consistent base64url handling+ * - Sign count always 0 for syncable passkeys+ * - BE/BS flags for backup-eligible and backed-up status+ */+public class PasskeyAuthenticator {++ /// AliasVault AAGUID: a11a5vau-9f32-4b8c-8c5d-2f7d13e8c942+ private static let aaguid: [UInt8] = [+ 0xa1, 0x1a, 0x5f, 0xaa, 0x9f, 0x32, 0x4b, 0x8c,+ 0x8c, 0x5d, 0x2f, 0x7d, 0x13, 0xe8, 0xc9, 0x42+ ]++ // MARK: - Public API++ /**+ * Create a new passkey (registration)+ * Returns credential data ready for iOS to return to the RP, plus storage data+ *+ * - Note: This method intentionally has more than 5 parameters to match WebAuthn spec requirements.+ * SwiftLint: function_parameter_count is disabled for this method as parameters directly map+ * to WebAuthn credential creation parameters and cannot be reasonably grouped.+ */+ // swiftlint:disable:next function_parameter_count+ public static func createPasskey(+ credentialId: Data,+ clientDataHash: Data,+ rpId: String,+ userId: Data?,+ userName: String?,+ userDisplayName: String?,+ uvPerformed: Bool = false,+ enablePrf: Bool = false+ ) throws -> PasskeyCreationResult {++ // 1. Generate ES256 key pair+ let privateKey = P256.Signing.PrivateKey()+ let publicKey = privateKey.publicKey++ // 2. RP ID hash+ let rpIdHash = Data(SHA256.hash(data: rpId.data(using: .utf8)!))++ // 3. Build flags+ var flags: UInt8 = 0x41 // UP (bit 0) + AT (bit 6)+ if uvPerformed {+ flags |= 0x04 // UV (bit 2)+ }+ flags |= 0x08 // BE (bit 3) - backup eligible+ flags |= 0x10 // BS (bit 4) - backup state++ // 4. Sign count (always 0 for syncable credentials)+ let signCount = Data([0x00, 0x00, 0x00, 0x00])++ // 5. Build COSE public key+ let coseKey = try buildCoseEc2Es256(publicKey: publicKey)++ // 6. Build attested credential data+ let credIdLength = Data([+ UInt8((credentialId.count >> 8) & 0xFF),+ UInt8(credentialId.count & 0xFF)+ ])+ var attestedCredData = Data(aaguid)+ attestedCredData.append(credIdLength)+ attestedCredData.append(credentialId)+ attestedCredData.append(coseKey)++ // 7. Build authenticator data+ var authenticatorData = Data()+ authenticatorData.append(rpIdHash)+ authenticatorData.append(Data([flags]))+ authenticatorData.append(signCount)+ authenticatorData.append(attestedCredData)++ // 8. Build attestation object (none format)+ let attestationObject = try buildAttestationObjectNone(authenticatorData: authenticatorData)++ // 9. Generate PRF secret if requested+ var prfSecret: Data?+ if enablePrf {+ var prfBytes = Data(count: 32)+ let result = prfBytes.withUnsafeMutableBytes { bytes in+ SecRandomCopyBytes(kSecRandomDefault, 32, bytes.baseAddress!)+ }+ if result == errSecSuccess {+ prfSecret = prfBytes+ }+ }++ // 10. Export keys for storage+ let publicKeyData = try exportPublicKeyAsJWK(publicKey: publicKey)+ let privateKeyData = try exportPrivateKeyAsJWK(privateKey: privateKey)++ return PasskeyCreationResult(+ credentialId: credentialId,+ attestationObject: attestationObject,+ publicKey: publicKeyData,+ privateKey: privateKeyData,+ rpId: rpId,+ userId: userId,+ userName: userName,+ userDisplayName: userDisplayName,+ prfSecret: prfSecret+ )+ }++ /**+ * Create an assertion (authentication)+ * Returns assertion data ready for iOS to return to the RP+ *+ * - Note: This method intentionally has more than 5 parameters to match WebAuthn spec requirements.+ * SwiftLint: function_parameter_count is disabled for this method as parameters directly map+ * to WebAuthn assertion parameters and cannot be reasonably grouped.+ */+ // swiftlint:disable:next function_parameter_count+ public static func getAssertion(+ credentialId: Data,+ clientDataHash: Data,+ rpId: String,+ privateKeyJWK: Data,+ userId: Data?,+ uvPerformed: Bool = false,+ prfInputs: PrfInputs? = nil,+ prfSecret: Data? = nil+ ) throws -> PasskeyAssertionResult {++ // 1. RP ID hash+ let rpIdHash = Data(SHA256.hash(data: rpId.data(using: .utf8)!))++ // 2. Build flags+ var flags: UInt8 = 0x01 // UP (bit 0)+ if uvPerformed {+ flags |= 0x04 // UV (bit 2)+ }+ flags |= 0x08 // BE (bit 3)+ flags |= 0x10 // BS (bit 4)++ // 3. Sign count+ let signCount = Data([0x00, 0x00, 0x00, 0x00])++ // 4. Build authenticator data+ var authenticatorData = Data()+ authenticatorData.append(rpIdHash)+ authenticatorData.append(Data([flags]))+ authenticatorData.append(signCount)++ // 5. Build data to sign: authenticatorData || clientDataHash+ var dataToSign = Data()+ dataToSign.append(authenticatorData)+ dataToSign.append(clientDataHash)++ // 6. Import private key and sign+ let privateKey = try importPrivateKeyFromJWK(jwkData: privateKeyJWK)+ let signature = try privateKey.signature(for: dataToSign)++ // 7. Convert raw signature to DER format+ let derSignature = try convertRawSignatureToDER(signature: signature)++ // 8. Evaluate PRF if requested+ var prfResults: PrfResults?+ if let inputs = prfInputs, let secret = prfSecret {+ let firstResult = try evaluatePrf(secret: secret, salt: inputs.first)+ var secondResult: Data?+ if let secondSalt = inputs.second {+ secondResult = try evaluatePrf(secret: secret, salt: secondSalt)+ }+ prfResults = PrfResults(first: firstResult, second: secondResult)+ }++ return PasskeyAssertionResult(+ credentialId: credentialId,+ authenticatorData: authenticatorData,+ signature: derSignature,+ userHandle: userId,+ prfResults: prfResults+ )+ }++ // MARK: - Key Management++ /**+ * Export public key as JWK format (JSON)+ */+ private static func exportPublicKeyAsJWK(publicKey: P256.Signing.PublicKey) throws -> Data {+ let rawRepresentation = publicKey.rawRepresentation++ // P-256 raw representation is 65 bytes: 0x04 || x (32 bytes) || y (32 bytes)+ guard rawRepresentation.count == 65, rawRepresentation[0] == 0x04 else {+ throw PasskeyError.invalidPublicKey+ }++ let xBytes = rawRepresentation[1...32]+ let yBytes = rawRepresentation[33...64]++ let jwk: [String: Any] = [+ "kty": "EC",+ "crv": "P-256",+ "x": xBytes.base64URLEncodedString(),+ "y": yBytes.base64URLEncodedString()+ ]++ return try JSONSerialization.data(withJSONObject: jwk)+ }++ /**+ * Export private key as JWK format (JSON)+ */+ private static func exportPrivateKeyAsJWK(privateKey: P256.Signing.PrivateKey) throws -> Data {+ let rawRepresentation = privateKey.rawRepresentation+ let publicKey = privateKey.publicKey.rawRepresentation++ guard publicKey.count == 65, publicKey[0] == 0x04 else {+ throw PasskeyError.invalidPublicKey+ }++ let xBytes = publicKey[1...32]+ let yBytes = publicKey[33...64]+ let dBytes = rawRepresentation++ let jwk: [String: Any] = [+ "kty": "EC",+ "crv": "P-256",+ "x": xBytes.base64URLEncodedString(),+ "y": yBytes.base64URLEncodedString(),+ "d": dBytes.base64URLEncodedString()+ ]++ return try JSONSerialization.data(withJSONObject: jwk)+ }++ /**+ * Import private key from JWK format+ */+ private static func importPrivateKeyFromJWK(jwkData: Data) throws -> P256.Signing.PrivateKey {+ guard let jwk = try JSONSerialization.jsonObject(with: jwkData) as? [String: String],+ let dBase64url = jwk["d"] else {+ throw PasskeyError.invalidJWK+ }++ let dBytes = try Data(base64URLEncoded: dBase64url)+ return try P256.Signing.PrivateKey(rawRepresentation: dBytes)+ }++ // MARK: - CBOR Encoding++ /**+ * Build COSE EC2 public key for ES256+ * CBOR map: {1: 2, 3: -7, -1: 1, -2: x, -3: y}+ */+ private static func buildCoseEc2Es256(publicKey: P256.Signing.PublicKey) throws -> Data {+ let rawRepresentation = publicKey.rawRepresentation++ guard rawRepresentation.count == 65, rawRepresentation[0] == 0x04 else {+ throw PasskeyError.invalidPublicKey+ }++ let xBytes = rawRepresentation[1...32]+ let yBytes = rawRepresentation[33...64]++ // Build CBOR map manually+ var cbor = Data()+ cbor.append(0xA5) // map(5)++ // 1: 2 (kty: EC2)+ cbor.append(0x01) // key 1+ cbor.append(0x02) // value 2++ // 3: -7 (alg: ES256)+ cbor.append(0x03) // key 3+ cbor.append(0x26) // value -7++ // -1: 1 (crv: P-256)+ cbor.append(0x20) // key -1+ cbor.append(0x01) // value 1++ // -2: x (x coordinate)+ cbor.append(0x21) // key -2+ cbor.append(0x58) // bytes(32)+ cbor.append(0x20) // length 32+ cbor.append(contentsOf: xBytes)++ // -3: y (y coordinate)+ cbor.append(0x22) // key -3+ cbor.append(0x58) // bytes(32)+ cbor.append(0x20) // length 32+ cbor.append(contentsOf: yBytes)++ return cbor+ }++ /**+ * Build attestation object with "none" format+ * CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}+ */+ private static func buildAttestationObjectNone(authenticatorData: Data) throws -> Data {+ var cbor = Data()+ cbor.append(0xA3) // map(3)++ // "fmt": "none"+ cbor.append(contentsOf: cborText("fmt"))+ cbor.append(contentsOf: cborText("none"))++ // "attStmt": {}+ cbor.append(contentsOf: cborText("attStmt"))+ cbor.append(0xA0) // map(0)++ // "authData": <bytes>+ cbor.append(contentsOf: cborText("authData"))+ cbor.append(contentsOf: cborBytes(authenticatorData))++ return cbor+ }++ /**+ * Encode a string as CBOR text+ */+ private static func cborText(_ text: String) -> Data {+ guard let bytes = text.data(using: .utf8) else {+ return Data()+ }++ var cbor = Data()+ if bytes.count <= 23 {+ cbor.append(0x60 | UInt8(bytes.count)) // text(n)+ cbor.append(bytes)+ } else if bytes.count <= 0xFF {+ cbor.append(0x78) // text(uint8)+ cbor.append(UInt8(bytes.count))+ cbor.append(bytes)+ } else {+ cbor.append(0x79) // text(uint16)+ cbor.append(UInt8((bytes.count >> 8) & 0xFF))+ cbor.append(UInt8(bytes.count & 0xFF))+ cbor.append(bytes)+ }++ return cbor+ }++ /**+ * Encode bytes as CBOR byte string+ */+ private static func cborBytes(_ bytes: Data) -> Data {+ var cbor = Data()+ if bytes.count <= 23 {+ cbor.append(0x40 | UInt8(bytes.count)) // bytes(n)+ cbor.append(bytes)+ } else if bytes.count <= 0xFF {+ cbor.append(0x58) // bytes(uint8)+ cbor.append(UInt8(bytes.count))+ cbor.append(bytes)+ } else {+ cbor.append(0x59) // bytes(uint16)+ cbor.append(UInt8((bytes.count >> 8) & 0xFF))+ cbor.append(UInt8(bytes.count & 0xFF))+ cbor.append(bytes)+ }++ return cbor+ }++ // MARK: - Signature Conversion++ /**+ * Convert P256.Signing.ECDSASignature to DER format+ * WebAuthn requires DER encoding, but CryptoKit gives us raw r||s+ */+ private static func convertRawSignatureToDER(signature: P256.Signing.ECDSASignature) throws -> Data {+ let rawSig = signature.rawRepresentation++ guard rawSig.count == 64 else {+ throw PasskeyError.invalidSignature+ }++ let rVal = rawSig[0..<32]+ let sVal = rawSig[32..<64]++ let rDER = derInteger(rVal)+ let sDER = derInteger(sVal)++ var derSig = Data()+ derSig.append(0x30) // SEQUENCE+ derSig.append(UInt8(rDER.count + sDER.count))+ derSig.append(rDER)+ derSig.append(sDER)++ return derSig+ }++ /**+ * Encode a positive big integer as DER INTEGER+ */+ private static func derInteger(_ bytes: Data) -> Data {+ var trimmed = bytes++ // Trim leading zeros+ while trimmed.count > 1 && trimmed[0] == 0x00 {+ trimmed = trimmed.dropFirst()+ }++ // If MSB is set, prepend 0x00 to keep it positive+ var value = trimmed+ if (trimmed[0] & 0x80) != 0 {+ value = Data([0x00]) + trimmed+ }++ var der = Data()+ der.append(0x02) // INTEGER+ der.append(UInt8(value.count))+ der.append(value)++ return der+ }++ // MARK: - PRF Extension++ /**+ * Evaluate PRF (hmac-secret extension)+ * Implements: HMAC-SHA256(prfSecret, SHA-256("WebAuthn PRF\x00" || salt))+ */+ private static func evaluatePrf(secret: Data, salt: Data) throws -> Data {+ // Step 1: Domain separation - hash salt with "WebAuthn PRF\x00" prefix+ let prefix = "WebAuthn PRF\0".data(using: .utf8)!+ var domainSeparatedSalt = Data()+ domainSeparatedSalt.append(prefix)+ domainSeparatedSalt.append(salt)++ let hashedSalt = Data(SHA256.hash(data: domainSeparatedSalt))++ // Step 2: Compute HMAC-SHA256(prfSecret, hashedSalt)+ let key = SymmetricKey(data: secret)+ let hmac = HMAC<SHA256>.authenticationCode(for: hashedSalt, using: key)++ return Data(hmac)+ }+}++// MARK: - Supporting Types++public struct PasskeyCreationResult {+ public let credentialId: Data+ public let attestationObject: Data+ public let publicKey: Data // JWK format+ public let privateKey: Data // JWK format+ public let rpId: String+ public let userId: Data?+ public let userName: String?+ public let userDisplayName: String?+ public let prfSecret: Data?+}++public struct PasskeyAssertionResult {+ public let credentialId: Data+ public let authenticatorData: Data+ public let signature: Data+ public let userHandle: Data?+ public let prfResults: PrfResults?+}++public struct PrfInputs {+ public let first: Data+ public let second: Data?++ public init(first: Data, second: Data? = nil) {+ self.first = first+ self.second = second+ }+}++public struct PrfResults {+ public let first: Data+ public let second: Data?+}++public enum PasskeyError: Error {+ case invalidPublicKey+ case invalidPrivateKey+ case invalidJWK+ case invalidSignature+ case cborEncodingFailed+}++// MARK: - Data Extension for Base64URL++extension Data {+ func base64URLEncodedString() -> String {+ let base64 = self.base64EncodedString()+ return base64+ .replacingOccurrences(of: "+", with: "-")+ .replacingOccurrences(of: "/", with: "_")+ .replacingOccurrences(of: "=", with: "")+ }++ init(base64URLEncoded string: String) throws {+ var base64 = string+ .replacingOccurrences(of: "-", with: "+")+ .replacingOccurrences(of: "_", with: "/")++ // Add padding if needed+ let remainder = base64.count % 4+ if remainder > 0 {+ base64.append(String(repeating: "=", count: 4 - remainder))+ }++ guard let data = Data(base64Encoded: base64) else {+ throw PasskeyError.invalidJWK+ }++ self = data+ }+}diff --git a/apps/mobile-app/ios/VaultStoreKit/PasskeyHelper.swift b/apps/mobile-app/ios/VaultStoreKit/PasskeyHelper.swiftnew file mode 100644index 000000000..df2a8da92--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/PasskeyHelper.swift@@ -0,0 +1,125 @@+import Foundation++/**+ * PasskeyHelper+ * -------------------------+ * Utility class for passkey-related operations, including GUID/base64url conversions.+ * Port of the browser extension PasskeyHelper.ts to Swift.+ * TODO: review implementation and docs.+ */+public class PasskeyHelper {++ /**+ * Convert GUID string to byte array+ * Example: "3f2504e0-4f89-11d3-9a0c-0305e82c3301" → Data(16 bytes)+ */+ public static func guidToBytes(_ guid: String) throws -> Data {+ // Remove dashes+ let hex = guid.replacingOccurrences(of: "-", with: "")++ guard hex.count == 32 else {+ throw PasskeyHelperError.invalidGuidFormat+ }++ var bytes = Data()+ var index = hex.startIndex++ for _ in 0..<16 {+ let nextIndex = hex.index(index, offsetBy: 2)+ let byteString = String(hex[index..<nextIndex])++ guard let byte = UInt8(byteString, radix: 16) else {+ throw PasskeyHelperError.invalidGuidFormat+ }++ bytes.append(byte)+ index = nextIndex+ }++ return bytes+ }++ /**+ * Convert byte array to GUID string (uppercase)+ * Example: Data(16 bytes) → "3F2504E0-4F89-11D3-9A0C-0305E82C3301"+ */+ public static func bytesToGuid(_ bytes: Data) throws -> String {+ guard bytes.count == 16 else {+ throw PasskeyHelperError.invalidByteLength+ }++ let hex = bytes.map { String(format: "%02x", $0) }.joined()++ // Insert dashes in canonical format: 8-4-4-4-12+ let parts = [+ String(hex.prefix(8)),+ String(hex.dropFirst(8).prefix(4)),+ String(hex.dropFirst(12).prefix(4)),+ String(hex.dropFirst(16).prefix(4)),+ String(hex.dropFirst(20))+ ]++ return parts.joined(separator: "-").uppercased()+ }++ /**+ * Convert GUID to base64url for WebAuthn credential ID+ * Example: "3f2504e0-4f89-11d3-9a0c-0305e82c3301" → "PyUE4E-JEdOaDAPF6CwzAQ"+ */+ public static func guidToBase64url(_ guid: String) throws -> String {+ let bytes = try guidToBytes(guid)+ return bytes.base64URLEncodedString()+ }++ /**+ * Convert base64url to GUID for database lookup+ * Example: "PyUE4E-JEdOaDAPF6CwzAQ" → "3F2504E0-4F89-11D3-9A0C-0305E82C3301"+ */+ public static func base64urlToGuid(_ base64url: String) throws -> String {+ let bytes = try Data(base64URLEncoded: base64url)+ return try bytesToGuid(bytes)+ }++ /**+ * Convert byte array to base64url string+ */+ public static func bytesToBase64url(_ bytes: Data) -> String {+ return bytes.base64URLEncodedString()+ }++ /**+ * Convert base64url string to byte array+ */+ public static func base64urlToBytes(_ base64url: String) throws -> Data {+ return try Data(base64URLEncoded: base64url)+ }++ /**+ * Generate a random GUID string+ */+ public static func generateGuid() -> String {+ return UUID().uuidString.uppercased()+ }++ /**+ * Generate random bytes for credential ID+ */+ public static func generateCredentialId(length: Int = 16) throws -> Data {+ var bytes = Data(count: length)+ let result = bytes.withUnsafeMutableBytes { bytesPtr in+ SecRandomCopyBytes(kSecRandomDefault, length, bytesPtr.baseAddress!)+ }++ guard result == errSecSuccess else {+ throw PasskeyHelperError.randomGenerationFailed+ }++ return bytes+ }+}++public enum PasskeyHelperError: Error {+ case invalidGuidFormat+ case invalidByteLength+ case randomGenerationFailed+}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swiftnew file mode 100644index 000000000..3d659d325--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift@@ -0,0 +1,162 @@+import Foundation+import SQLite+import VaultModels++/**+ * VaultStore+Passkey+ * Extension to VaultStore for passkey operations+ */+extension VaultStore {++ // MARK: - Passkey Queries++ /**+ * Get all passkeys for a specific relying party ID+ */+ public func getPasskeys(byRpId rpId: String) throws -> [Passkey] {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite query+ // This is a placeholder implementation+ // The actual implementation will depend on your database schema+ return []+ }++ /**+ * Get a passkey by its credential ID+ */+ public func getPasskey(byCredentialId credentialId: Data) throws -> Passkey? {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite query+ // This is a placeholder implementation+ return nil+ }++ /**+ * Get a passkey by its UUID+ */+ public func getPasskey(byId id: UUID) throws -> Passkey? {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite query+ // This is a placeholder implementation+ return nil+ }++ /**+ * Get all passkeys for a credential+ */+ public func getPasskeys(forCredentialId credentialId: UUID) throws -> [Passkey] {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite query+ // This is a placeholder implementation+ return []+ }++ // MARK: - Passkey Mutations++ /**+ * Create a new passkey+ *+ * - Note: This method intentionally has more than 5 parameters as it stores all WebAuthn+ * credential data required by the specification. Parameters cannot be grouped without+ * losing type safety and clarity.+ */+ // swiftlint:disable:next function_parameter_count+ public func createPasskey(+ credentialId: Data,+ parentCredentialId: UUID,+ rpId: String,+ userId: Data?,+ userName: String?,+ publicKey: Data,+ privateKey: Data,+ prfKey: Data?,+ displayName: String+ ) throws -> Passkey {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ let now = Date()+ let passkeyId = UUID()++ let passkey = Passkey(+ id: passkeyId,+ credentialId: credentialId,+ credentialIdString: parentCredentialId.uuidString,+ rpId: rpId,+ userId: userId,+ userName: userName,+ publicKey: publicKey,+ privateKey: privateKey,+ prfKey: prfKey,+ displayName: displayName,+ createdAt: now,+ updatedAt: now,+ isDeleted: false+ )++ // TODO: Implement actual SQLite insert+ // This is a placeholder implementation+ // INSERT INTO Passkeys (...) VALUES (...)++ return passkey+ }++ /**+ * Update an existing passkey+ */+ public func updatePasskey(_ passkey: Passkey) throws {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite update+ // UPDATE Passkeys SET ... WHERE id = ?+ }++ /**+ * Delete a passkey (soft delete)+ */+ public func deletePasskey(byId id: UUID) throws {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite update (soft delete)+ // UPDATE Passkeys SET isDeleted = 1, updatedAt = ? WHERE id = ?+ }++ /**+ * Delete a passkey by credential ID (soft delete)+ */+ public func deletePasskey(byCredentialId credentialId: Data) throws {+ guard let dbConn = dbConnection else {+ throw VaultStoreError.vaultNotUnlocked+ }++ // TODO: Implement actual SQLite update (soft delete)+ // UPDATE Passkeys SET isDeleted = 1, updatedAt = ? WHERE credentialId = ?+ }+}++/**+ * VaultStore errors+ */+public enum VaultStoreError: Error {+ case vaultNotUnlocked+ case passkeyNotFound+ case credentialNotFound+ case databaseError(String)+}