Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Move webapi calls to native swift/kotlin layer (#520)

Leendert de Borst3bc3c165f659
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 1033645b8..d9e7072a9 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -19,8 +19,15 @@ import com.facebook.react.turbomodule.core.interfaces.TurboModule
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
+import net.aliasvault.app.webapi.WebApiService
import net.aliasvault.nativevaultmanager.NativeVaultManagerSpec
import org.json.JSONArray
+import org.json.JSONObject
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
/**
* The native vault manager that manages the vault store and all input/output operations on it.
@@ -50,6 +57,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
AndroidStorageProvider(reactContext),
)
+ private val webApiService = WebApiService(reactContext)
+
init {
// Register for lifecycle callbacks
reactContext.addLifecycleEventListener(this)
@@ -847,4 +856,179 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
private fun getFragmentActivity(): FragmentActivity? {
return currentActivity as? FragmentActivity
}
+
+ // MARK: - WebAPI Configuration
+
+ /**
+ * Set the API URL
+ * @param url The API URL to set
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun setApiUrl(url: String, promise: Promise) {
+ try {
+ // TODO: Implement when WebApiService is complete
+ webApiService.setApiUrl(url)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error setting API URL", e)
+ promise.reject("ERR_SET_API_URL", "Failed to set API URL: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Get the API URL
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getApiUrl(promise: Promise) {
+ try {
+ // TODO: Implement when WebApiService is complete
+ val apiUrl = webApiService.getApiUrl()
+ promise.resolve(apiUrl)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting API URL", e)
+ promise.reject("ERR_GET_API_URL", "Failed to get API URL: ${e.message}", e)
+ }
+ }
+
+ // MARK: - WebAPI Token Management
+
+ /**
+ * Set both access and refresh tokens
+ * @param accessToken The access token
+ * @param refreshToken The refresh token
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun setAuthTokens(accessToken: String, refreshToken: String, promise: Promise) {
+ try {
+ // TODO: Implement when WebApiService is complete
+ webApiService.setAuthTokens(accessToken, refreshToken)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error setting auth tokens", e)
+ promise.reject("ERR_SET_AUTH_TOKENS", "Failed to set auth tokens: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Get the access token
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun getAccessToken(promise: Promise) {
+ try {
+ // TODO: Implement when WebApiService is complete
+ val accessToken = webApiService.getAccessToken()
+ promise.resolve(accessToken)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting access token", e)
+ promise.reject("ERR_GET_ACCESS_TOKEN", "Failed to get access token: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Clear both access and refresh tokens
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun clearAuthTokens(promise: Promise) {
+ try {
+ // TODO: Implement when WebApiService is complete
+ webApiService.clearAuthTokens()
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error clearing auth tokens", e)
+ promise.reject("ERR_CLEAR_AUTH_TOKENS", "Failed to clear auth tokens: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Revoke tokens via WebAPI (called when logging out)
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun revokeTokens(promise: Promise) {
+ // TODO: Implement when WebApiService is complete
+ // This should call webApiService.revokeTokens() which is an async suspend function
+ // For now, we'll use a coroutine scope to handle it
+ CoroutineScope(Dispatchers.IO).launch {
+ try {
+ webApiService.revokeTokens()
+ withContext(Dispatchers.Main) {
+ promise.resolve(null)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ Log.e(TAG, "Error revoking tokens", e)
+ promise.reject("ERR_REVOKE_TOKENS", "Failed to revoke tokens: ${e.message}", e)
+ }
+ }
+ }
+ }
+
+ // MARK: - WebAPI Request Execution
+
+ /**
+ * Execute a WebAPI request
+ * @param method The HTTP method
+ * @param endpoint The API endpoint
+ * @param body The request body (nullable)
+ * @param headers The request headers as JSON string
+ * @param requiresAuth Whether authentication is required
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun executeWebApiRequest(
+ method: String,
+ endpoint: String,
+ body: String?,
+ headers: String,
+ requiresAuth: Boolean,
+ promise: Promise
+ ) {
+ try {
+ // TODO: Implement when WebApiService is complete
+ // Parse headers from JSON string
+ val headersMap = mutableMapOf<String, String>()
+ val headersJson = JSONObject(headers)
+ headersJson.keys().forEach { key ->
+ headersMap[key] = headersJson.getString(key)
+ }
+
+ // Execute request using coroutines
+ runBlocking {
+ val response = webApiService.executeRequest(
+ method = method,
+ endpoint = endpoint,
+ body = body,
+ headers = headersMap,
+ requiresAuth = requiresAuth
+ )
+
+ // Build response JSON
+ val responseJson = JSONObject()
+ responseJson.put("statusCode", response.statusCode)
+ responseJson.put("body", response.body)
+ responseJson.put("headers", JSONObject(response.headers))
+
+ promise.resolve(responseJson.toString())
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Error executing WebAPI request", e)
+ promise.reject("ERR_WEB_API_REQUEST", "Failed to execute WebAPI request: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Register credential identities (Android stub - not yet implemented)
+ * @param promise The promise to resolve
+ */
+ @ReactMethod
+ override fun registerCredentialIdentities(promise: Promise) {
+ // TODO: Implement Android credential identity registration
+ Log.d(TAG, "registerCredentialIdentities: Not yet implemented on Android")
+ promise.resolve(null)
+ }
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt
new file mode 100644
index 000000000..4d2fdb7aa
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt
@@ -0,0 +1,187 @@
+package net.aliasvault.app.webapi
+
+import android.content.Context
+import android.util.Log
+
+/**
+ * Response object from a WebAPI request containing status code, body, and headers
+ */
+data class WebApiResponse(
+ val statusCode: Int,
+ val body: String,
+ val headers: Map<String, String>
+)
+
+/**
+ * Native Kotlin WebAPI service for making HTTP requests to the AliasVault server.
+ * This service handles authentication, token refresh, and all HTTP operations.
+ *
+ * TODO: Implement all methods following the iOS Swift implementation pattern.
+ */
+class WebApiService(private val context: Context) {
+ companion object {
+ private const val TAG = "WebApiService"
+ private const val API_URL_KEY = "apiUrl"
+ private const val ACCESS_TOKEN_KEY = "accessToken"
+ private const val REFRESH_TOKEN_KEY = "refreshToken"
+ private const val DEFAULT_API_URL = "https://app.aliasvault.net/api"
+ }
+
+ // MARK: - Configuration Management
+
+ /**
+ * Set the API URL
+ *
+ * TODO: Implement using SharedPreferences to store the API URL
+ */
+ fun setApiUrl(url: String) {
+ TODO("Implement setApiUrl: Store URL in SharedPreferences")
+ }
+
+ /**
+ * Get the API URL
+ *
+ * TODO: Implement using SharedPreferences to retrieve the API URL
+ */
+ fun getApiUrl(): String {
+ TODO("Implement getApiUrl: Retrieve URL from SharedPreferences or return DEFAULT_API_URL")
+ }
+
+ /**
+ * Get the base URL with /v1/ appended
+ */
+ private fun getBaseUrl(): String {
+ val apiUrl = getApiUrl()
+ val trimmedUrl = apiUrl.trimEnd('/')
+ return "$trimmedUrl/v1/"
+ }
+
+ // MARK: - Token Management
+
+ /**
+ * Set both access and refresh tokens
+ *
+ * TODO: Implement using SharedPreferences to store both tokens
+ */
+ fun setAuthTokens(accessToken: String, refreshToken: String) {
+ TODO("Implement setAuthTokens: Store both tokens in SharedPreferences")
+ }
+
+ /**
+ * Get the access token
+ *
+ * TODO: Implement using SharedPreferences to retrieve the access token
+ */
+ fun getAccessToken(): String? {
+ TODO("Implement getAccessToken: Retrieve access token from SharedPreferences")
+ }
+
+ /**
+ * Get the refresh token
+ *
+ * TODO: Implement using SharedPreferences to retrieve the refresh token
+ */
+ fun getRefreshToken(): String? {
+ TODO("Implement getRefreshToken: Retrieve refresh token from SharedPreferences")
+ }
+
+ /**
+ * Clear both access and refresh tokens
+ *
+ * TODO: Implement using SharedPreferences to remove both tokens
+ */
+ fun clearAuthTokens() {
+ TODO("Implement clearAuthTokens: Remove both tokens from SharedPreferences")
+ }
+
+ // MARK: - HTTP Request Execution
+
+ /**
+ * Execute a WebAPI request with support for authentication and token refresh
+ *
+ * TODO: Implement using OkHttp or HttpURLConnection to execute HTTP requests.
+ * This should:
+ * 1. Add Authorization header if requiresAuth is true
+ * 2. Add X-AliasVault-Client header with app version
+ * 3. Execute the request
+ * 4. Handle 401 responses by calling refreshAccessToken() and retrying
+ * 5. Return WebApiResponse with statusCode, body, and headers
+ *
+ * Reference the iOS Swift implementation in VaultStoreKit/WebApiService.swift
+ */
+ suspend fun executeRequest(
+ method: String,
+ endpoint: String,
+ body: String?,
+ headers: Map<String, String>,
+ requiresAuth: Boolean
+ ): WebApiResponse {
+ TODO("Implement executeRequest: Use OkHttp/HttpURLConnection to execute HTTP request with auth support")
+ }
+
+ /**
+ * Execute a raw HTTP request without token refresh logic
+ *
+ * TODO: Implement the actual HTTP request execution using OkHttp or HttpURLConnection.
+ * This should:
+ * 1. Build the full URL from baseUrl + endpoint
+ * 2. Create request with method, headers, and body
+ * 3. Execute synchronously or with coroutines
+ * 4. Parse response and return WebApiResponse
+ *
+ * Reference the iOS Swift implementation for the expected behavior.
+ */
+ private suspend fun executeRawRequest(
+ method: String,
+ endpoint: String,
+ body: String?,
+ headers: Map<String, String>
+ ): WebApiResponse {
+ TODO("Implement executeRawRequest: Execute HTTP request and return WebApiResponse")
+ }
+
+ /**
+ * Refresh the access token using the refresh token
+ *
+ * TODO: Implement token refresh logic:
+ * 1. Get current access and refresh tokens
+ * 2. Create JSON body with both tokens
+ * 3. POST to Auth/refresh endpoint
+ * 4. Parse response to get new tokens
+ * 5. Store new tokens using setAuthTokens()
+ * 6. Return new access token or null on failure
+ *
+ * Reference the iOS Swift implementation for the expected behavior.
+ */
+ private suspend fun refreshAccessToken(): String? {
+ TODO("Implement refreshAccessToken: Refresh tokens and return new access token")
+ }
+
+ // MARK: - Helper Methods
+
+ /**
+ * Get the client version header value
+ *
+ * TODO: Implement to return "android-{version}" where version is from BuildConfig or PackageInfo
+ */
+ private fun getClientVersionHeader(): String {
+ TODO("Implement getClientVersionHeader: Return android-{version} header value")
+ }
+
+ // MARK: - Token Revocation
+
+ /**
+ * Revoke tokens via WebAPI (called when logging out)
+ *
+ * TODO: Implement token revocation logic:
+ * 1. Get current access and refresh tokens
+ * 2. Create JSON body with both tokens
+ * 3. POST to Auth/revoke endpoint
+ * 4. Always clear tokens at the end, even if revoke fails
+ *
+ * Reference the iOS Swift implementation for the expected behavior.
+ */
+ suspend fun revokeTokens() {
+ TODO("Implement revokeTokens: Revoke tokens via WebAPI and clear them from storage")
+ }
+}
diff --git a/apps/mobile-app/app/login-settings.tsx b/apps/mobile-app/app/login-settings.tsx
index 083bbf038..9b16b28e5 100644
--- a/apps/mobile-app/app/login-settings.tsx
+++ b/apps/mobile-app/app/login-settings.tsx
@@ -12,6 +12,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedView } from '@/components/themed/ThemedView';
import { RobustPressable } from '@/components/ui/RobustPressable';
+import NativeVaultManager from '@/specs/NativeVaultManager';
type ApiOption = {
label: string;
@@ -42,11 +43,19 @@ export default function SettingsScreen() : React.ReactNode {
}, [navigation, t]);
/**
- * Load the stored settings.
+ * Load the stored settings from native layer.
*/
const loadStoredSettings = useCallback(async () : Promise<void> => {
try {
- const apiUrl = await AsyncStorage.getItem('apiUrl');
+ // Try to get API URL from native layer first, fallback to AsyncStorage
+ let apiUrl: string | null = null;
+ try {
+ apiUrl = await NativeVaultManager.getApiUrl();
+ } catch (nativeError) {
+ console.warn('Failed to get API URL from native layer, falling back to AsyncStorage:', nativeError);
+ apiUrl = await AsyncStorage.getItem('apiUrl');
+ }
+
const matchingOption = DEFAULT_OPTIONS.find(opt => opt.value === apiUrl);
if (matchingOption) {
@@ -72,7 +81,13 @@ export default function SettingsScreen() : React.ReactNode {
const handleOptionChange = async (value: string) : Promise<void> => {
setSelectedOption(value);
if (value !== 'custom') {
+ // Sync to both AsyncStorage and native layer
await AsyncStorage.setItem('apiUrl', value);
+ try {
+ await NativeVaultManager.setApiUrl(value);
+ } catch (error) {
+ console.error('Failed to sync API URL to native layer:', error);
+ }
setCustomUrl('');
}
};
@@ -82,7 +97,13 @@ export default function SettingsScreen() : React.ReactNode {
*/
const handleCustomUrlChange = async (value: string) : Promise<void> => {
setCustomUrl(value);
+ // Sync to both AsyncStorage and native layer
await AsyncStorage.setItem('apiUrl', value);
+ try {
+ await NativeVaultManager.setApiUrl(value);
+ } catch (error) {
+ console.error('Failed to sync API URL to native layer:', error);
+ }
};
const styles = StyleSheet.create({
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index 09fc41b72..876e8d57e 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -130,6 +130,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
await AsyncStorage.setItem('accessToken', accessToken);
await AsyncStorage.setItem('refreshToken', refreshToken);
+ // Sync tokens to native layer
+ try {
+ await NativeVaultManager.setAuthTokens(accessToken, refreshToken);
+ } catch (error) {
+ console.error('Failed to sync auth tokens to native layer:', error);
+ }
+
setUsername(username);
}, []);
@@ -172,6 +179,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
await AsyncStorage.removeItem('authMethods');
dbContext?.clearDatabase();
+ // Clear tokens from native layer
+ try {
+ await NativeVaultManager.clearAuthTokens();
+ } catch (error) {
+ console.error('Failed to clear auth tokens from native layer:', error);
+ }
+
if (errorMessage) {
// Show alert
Alert.alert(i18n.t('common.error'), errorMessage);
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index d2efa2b60..bc60b85e0 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -171,4 +171,38 @@
[vaultManager registerCredentialIdentities:resolve rejecter:reject];
}
+// MARK: - WebAPI Configuration
+
+- (void)setApiUrl:(NSString *)url resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager setApiUrl:url resolver:resolve rejecter:reject];
+}
+
+- (void)getApiUrl:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getApiUrl:resolve rejecter:reject];
+}
+
+// MARK: - WebAPI Token Management
+
+- (void)setAuthTokens:(NSString *)accessToken refreshToken:(NSString *)refreshToken resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager setAuthTokens:accessToken refreshToken:refreshToken resolver:resolve rejecter:reject];
+}
+
+- (void)getAccessToken:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getAccessToken:resolve rejecter:reject];
+}
+
+- (void)clearAuthTokens:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager clearAuthTokens:resolve rejecter:reject];
+}
+
+- (void)revokeTokens:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager revokeTokens:resolve rejecter:reject];
+}
+
+// MARK: - WebAPI Request Execution
+
+- (void)executeWebApiRequest:(NSString *)method endpoint:(NSString *)endpoint body:(NSString *)body headers:(NSString *)headers requiresAuth:(BOOL)requiresAuth resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager executeWebApiRequest:method endpoint:endpoint body:body headers:headers requiresAuth:requiresAuth resolver:resolve rejecter:reject];
+}
+
@end
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 1017ce5cb..38c874ba1 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -12,6 +12,7 @@ import VaultModels
@objc(VaultManager)
public class VaultManager: NSObject {
private let vaultStore = VaultStore()
+ private let webApiService = WebApiService()
private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
private var clipboardClearTimer: DispatchSourceTimer?
@@ -466,6 +467,124 @@ public class VaultManager: NSObject {
}
}
+ // MARK: - WebAPI Configuration
+
+ @objc
+ func setApiUrl(_ url: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ try webApiService.setApiUrl(url)
+ resolve(nil)
+ } catch {
+ reject("API_URL_ERROR", "Failed to set API URL: \(error.localizedDescription)", error)
+ }
+ }
+
+ @objc
+ func getApiUrl(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ let apiUrl = webApiService.getApiUrl()
+ resolve(apiUrl)
+ }
+
+ // MARK: - WebAPI Token Management
+
+ @objc
+ func setAuthTokens(_ accessToken: String,
+ refreshToken: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ try webApiService.setAuthTokens(accessToken: accessToken, refreshToken: refreshToken)
+ resolve(nil)
+ } catch {
+ reject("AUTH_TOKEN_ERROR", "Failed to set auth tokens: \(error.localizedDescription)", error)
+ }
+ }
+
+ @objc
+ func getAccessToken(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ if let accessToken = webApiService.getAccessToken() {
+ resolve(accessToken)
+ } else {
+ resolve(nil)
+ }
+ }
+
+ @objc
+ func clearAuthTokens(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ webApiService.clearAuthTokens()
+ resolve(nil)
+ }
+
+ @objc
+ func revokeTokens(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ Task {
+ do {
+ try await webApiService.revokeTokens()
+ resolve(nil)
+ } catch {
+ reject("REVOKE_ERROR", "Failed to revoke tokens: \(error.localizedDescription)", error)
+ }
+ }
+ }
+
+ // MARK: - WebAPI Request Execution
+
+ @objc
+ func executeWebApiRequest(_ method: String,
+ endpoint: String,
+ body: String?,
+ headers: String,
+ requiresAuth: Bool,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ Task {
+ do {
+ // Parse headers from JSON string
+ guard let headersData = headers.data(using: .utf8),
+ let headersDict = try? JSONSerialization.jsonObject(with: headersData) as? [String: String] else {
+ reject("HEADERS_ERROR", "Failed to parse headers", nil)
+ return
+ }
+
+ // Execute the request
+ let response = try await webApiService.executeRequest(
+ method: method,
+ endpoint: endpoint,
+ body: body,
+ headers: headersDict,
+ requiresAuth: requiresAuth
+ )
+
+ // Build response JSON
+ let responseDict: [String: Any] = [
+ "statusCode": response.statusCode,
+ "body": response.body,
+ "headers": response.headers
+ ]
+
+ guard let responseData = try? JSONSerialization.data(withJSONObject: responseDict),
+ let responseJson = String(data: responseData, encoding: .utf8) else {
+ reject("RESPONSE_ERROR", "Failed to serialize response", nil)
+ return
+ }
+
+ await MainActor.run {
+ resolve(responseJson)
+ }
+ } catch {
+ await MainActor.run {
+ reject("WEB_API_ERROR", "Failed to execute WebAPI request: \(error.localizedDescription)", error)
+ }
+ }
+ }
+ }
+
@objc
func requiresMainQueueSetup() -> Bool {
return false
diff --git a/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift b/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift
new file mode 100644
index 000000000..f570ef6cd
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift
@@ -0,0 +1,325 @@
+import Foundation
+
+/**
+ * Response object from a WebAPI request containing status code, body, and headers
+ */
+public struct WebApiResponse {
+ public let statusCode: Int
+ public let body: String
+ public let headers: [String: String]
+
+ public init(statusCode: Int, body: String, headers: [String: String]) {
+ self.statusCode = statusCode
+ self.body = body
+ self.headers = headers
+ }
+}
+
+/**
+ * Native Swift WebAPI service for making HTTP requests to the AliasVault server.
+ * This service handles authentication, token refresh, and all HTTP operations.
+ */
+public class WebApiService {
+ private let vaultStore = VaultStore()
+
+ // Token storage keys
+ private let apiUrlKey = "apiUrl"
+ private let accessTokenKey = "accessToken"
+ private let refreshTokenKey = "refreshToken"
+
+ // Default API URL
+ private let defaultApiUrl = "https://app.aliasvault.net/api"
+
+ public init() {}
+
+ // MARK: - Configuration Management
+
+ /**
+ * Set the API URL
+ */
+ public func setApiUrl(_ url: String) throws {
+ UserDefaults.standard.set(url, forKey: apiUrlKey)
+ }
+
+ /**
+ * Get the API URL
+ */
+ public func getApiUrl() -> String {
+ return UserDefaults.standard.string(forKey: apiUrlKey) ?? defaultApiUrl
+ }
+
+ /**
+ * Get the base URL with /v1/ appended
+ */
+ private func getBaseUrl() -> String {
+ let apiUrl = getApiUrl()
+ let trimmedUrl = apiUrl.hasSuffix("/") ? String(apiUrl.dropLast()) : apiUrl
+ return "\(trimmedUrl)/v1/"
+ }
+
+ // MARK: - Token Management
+
+ /**
+ * Set both access and refresh tokens
+ */
+ public func setAuthTokens(accessToken: String, refreshToken: String) throws {
+ UserDefaults.standard.set(accessToken, forKey: accessTokenKey)
+ UserDefaults.standard.set(refreshToken, forKey: refreshTokenKey)
+ }
+
+ /**
+ * Get the access token
+ */
+ public func getAccessToken() -> String? {
+ return UserDefaults.standard.string(forKey: accessTokenKey)
+ }
+
+ /**
+ * Get the refresh token
+ */
+ public func getRefreshToken() -> String? {
+ return UserDefaults.standard.string(forKey: refreshTokenKey)
+ }
+
+ /**
+ * Clear both access and refresh tokens
+ */
+ public func clearAuthTokens() {
+ UserDefaults.standard.removeObject(forKey: accessTokenKey)
+ UserDefaults.standard.removeObject(forKey: refreshTokenKey)
+ }
+
+ // MARK: - HTTP Request Execution
+
+ /**
+ * Execute a WebAPI request with support for authentication and token refresh
+ */
+ public func executeRequest(
+ method: String,
+ endpoint: String,
+ body: String?,
+ headers: [String: String],
+ requiresAuth: Bool
+ ) async throws -> WebApiResponse {
+ var requestHeaders = headers
+
+ // Add authorization header if authentication is required
+ if requiresAuth, let accessToken = getAccessToken() {
+ requestHeaders["Authorization"] = "Bearer \(accessToken)"
+ }
+
+ // Add client version header
+ requestHeaders["X-AliasVault-Client"] = getClientVersionHeader()
+
+ // Execute the request
+ let response = try await executeRawRequest(
+ method: method,
+ endpoint: endpoint,
+ body: body,
+ headers: requestHeaders
+ )
+
+ // Handle 401 Unauthorized - attempt token refresh
+ if response.statusCode == 401 && requiresAuth {
+ if let newToken = try await refreshAccessToken() {
+ // Retry the request with the new token
+ var retryHeaders = headers
+ retryHeaders["Authorization"] = "Bearer \(newToken)"
+ retryHeaders["X-AliasVault-Client"] = getClientVersionHeader()
+
+ return try await executeRawRequest(
+ method: method,
+ endpoint: endpoint,
+ body: body,
+ headers: retryHeaders
+ )
+ } else {
+ // Token refresh failed, return 401 response
+ return response
+ }
+ }
+
+ return response
+ }
+
+ /**
+ * Execute a raw HTTP request without token refresh logic
+ */
+ private func executeRawRequest(
+ method: String,
+ endpoint: String,
+ body: String?,
+ headers: [String: String]
+ ) async throws -> WebApiResponse {
+ let baseUrl = getBaseUrl()
+ let urlString = "\(baseUrl)\(endpoint)"
+
+ guard let url = URL(string: urlString) else {
+ throw NSError(
+ domain: "WebApiService",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid URL: \(urlString)"]
+ )
+ }
+
+ var request = URLRequest(url: url)
+ request.httpMethod = method.uppercased()
+
+ // Set headers
+ for (key, value) in headers {
+ request.setValue(value, forHTTPHeaderField: key)
+ }
+
+ // Set body if present
+ if let bodyString = body {
+ request.httpBody = bodyString.data(using: .utf8)
+ }
+
+ // Execute the request
+ let (data, urlResponse) = try await URLSession.shared.data(for: request)
+
+ guard let httpResponse = urlResponse as? HTTPURLResponse else {
+ throw NSError(
+ domain: "WebApiService",
+ code: -2,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid response type"]
+ )
+ }
+
+ // Parse response body
+ let responseBody = String(data: data, encoding: .utf8) ?? ""
+
+ // Extract headers
+ var responseHeaders: [String: String] = [:]
+ for (key, value) in httpResponse.allHeaderFields {
+ if let keyString = key as? String, let valueString = value as? String {
+ responseHeaders[keyString] = valueString
+ }
+ }
+
+ return WebApiResponse(
+ statusCode: httpResponse.statusCode,
+ body: responseBody,
+ headers: responseHeaders
+ )
+ }
+
+ /**
+ * Refresh the access token using the refresh token
+ */
+ private func refreshAccessToken() async throws -> String? {
+ guard let refreshToken = getRefreshToken() else {
+ return nil
+ }
+
+ guard let accessToken = getAccessToken() else {
+ return nil
+ }
+
+ // Prepare refresh request body
+ let refreshBody: [String: String] = [
+ "token": accessToken,
+ "refreshToken": refreshToken
+ ]
+
+ guard let jsonData = try? JSONSerialization.data(withJSONObject: refreshBody),
+ let jsonString = String(data: jsonData, encoding: .utf8) else {
+ return nil
+ }
+
+ var headers = [
+ "Content-Type": "application/json",
+ "X-Ignore-Failure": "true"
+ ]
+ headers["X-AliasVault-Client"] = getClientVersionHeader()
+
+ do {
+ let response = try await executeRawRequest(
+ method: "POST",
+ endpoint: "Auth/refresh",
+ body: jsonString,
+ headers: headers
+ )
+
+ guard response.statusCode == 200 else {
+ return nil
+ }
+
+ // Parse the response JSON
+ guard let data = response.body.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let newToken = json["token"] as? String,
+ let newRefreshToken = json["refreshToken"] as? String else {
+ return nil
+ }
+
+ // Update stored tokens
+ try setAuthTokens(accessToken: newToken, refreshToken: newRefreshToken)
+
+ return newToken
+ } catch {
+ print("WebApiService: Token refresh failed: \(error)")
+ return nil
+ }
+ }
+
+ // MARK: - Helper Methods
+
+ /**
+ * Get the client version header value
+ */
+ private func getClientVersionHeader() -> String {
+ // Get version from Info.plist
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0"
+ let baseVersion = version.split(separator: "-").first ?? ""
+ return "ios-\(baseVersion)"
+ }
+
+ // MARK: - Token Revocation
+
+ /**
+ * Revoke tokens via WebAPI (called when logging out)
+ */
+ public func revokeTokens() async throws {
+ do {
+ // Get tokens to revoke
+ guard let refreshToken = getRefreshToken(),
+ let accessToken = getAccessToken() else {
+ // No tokens to revoke
+ clearAuthTokens()
+ return
+ }
+
+ // Prepare revoke request body
+ let revokeBody: [String: String] = [
+ "token": accessToken,
+ "refreshToken": refreshToken
+ ]
+
+ guard let jsonData = try? JSONSerialization.data(withJSONObject: revokeBody),
+ let jsonString = String(data: jsonData, encoding: .utf8) else {
+ clearAuthTokens()
+ return
+ }
+
+ // Execute revoke request
+ let response = try await executeRequest(
+ method: "POST",
+ endpoint: "Auth/revoke",
+ body: jsonString,
+ headers: ["Content-Type": "application/json"],
+ requiresAuth: false
+ )
+
+ // Log if revoke failed, but always clear tokens
+ if response.statusCode != 200 {
+ print("WebApiService: Token revoke failed with status \(response.statusCode)")
+ }
+ } catch {
+ print("WebApiService: Token revoke error: \(error)")
+ }
+
+ // Always clear tokens, even if revoke fails
+ clearAuthTokens()
+ }
+}
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 8f6cc7b01..e56044bef 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -55,6 +55,23 @@ export interface Spec extends TurboModule {
// Credential identity management
registerCredentialIdentities(): Promise<void>;
+
+ // WebAPI configuration and token management
+ setApiUrl(url: string): Promise<void>;
+ getApiUrl(): Promise<string>;
+ setAuthTokens(accessToken: string, refreshToken: string): Promise<void>;
+ getAccessToken(): Promise<string | null>;
+ clearAuthTokens(): Promise<void>;
+ revokeTokens(): Promise<void>;
+
+ // WebAPI request execution
+ executeWebApiRequest(
+ method: string,
+ endpoint: string,
+ body: string | null,
+ headers: string,
+ requiresAuth: boolean
+ ): Promise<string>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeVaultManager');
diff --git a/apps/mobile-app/utils/ApiUrlUtility.ts b/apps/mobile-app/utils/ApiUrlUtility.ts
index 37ebc78ab..93607b99b 100644
--- a/apps/mobile-app/utils/ApiUrlUtility.ts
+++ b/apps/mobile-app/utils/ApiUrlUtility.ts
@@ -2,6 +2,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState } from 'react';
import { AppInfo } from '@/utils/AppInfo';
+import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Hook to manage API URL state and display logic.
@@ -16,14 +17,26 @@ export const useApiUrl = (): {
const [apiUrl, setApiUrl] = useState<string>(AppInfo.DEFAULT_API_URL);
/**
- * Load the API URL from storage.
+ * Load the API URL from native storage.
*/
const loadApiUrl = async (): Promise<void> => {
- const storedUrl = await AsyncStorage.getItem('apiUrl');
- if (storedUrl && storedUrl.length > 0) {
- setApiUrl(storedUrl);
- } else {
- setApiUrl(AppInfo.DEFAULT_API_URL);
+ try {
+ // Try to get from native layer first
+ const storedUrl = await NativeVaultManager.getApiUrl();
+ if (storedUrl && storedUrl.length > 0) {
+ setApiUrl(storedUrl);
+ } else {
+ setApiUrl(AppInfo.DEFAULT_API_URL);
+ }
+ } catch (error) {
+ console.warn('Failed to get API URL from native layer, falling back to AsyncStorage:', error);
+ // Fallback to AsyncStorage
+ const storedUrl = await AsyncStorage.getItem('apiUrl');
+ if (storedUrl && storedUrl.length > 0) {
+ setApiUrl(storedUrl);
+ } else {
+ setApiUrl(AppInfo.DEFAULT_API_URL);
+ }
}
};
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index f82d225ec..362ecfa26 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -7,6 +7,7 @@ import i18n from '@/i18n';
import { LocalAuthError } from './types/errors/LocalAuthError';
import { logoutEventEmitter } from '@/events/LogoutEventEmitter';
+import NativeVaultManager from '@/specs/NativeVaultManager';
type RequestInit = globalThis.RequestInit;
@@ -18,14 +19,27 @@ type TokenResponse = {
refreshToken: string;
}
+/**
+ * Type for the native WebAPI response.
+ */
+type NativeWebApiResponse = {
+ statusCode: number;
+ body: string;
+ headers: Record<string, string>;
+}
+
/**
* Service class for interacting with the web API.
+ * This class now acts as a proxy to the native layer, where all WebAPI calls are executed.
*/
export class WebApiService {
/**
* Constructor for the WebApiService class.
*/
- public constructor() { }
+ public constructor() {
+ // Initialize API URL and tokens from AsyncStorage if they exist
+ this.syncLegacyConfigToNative();
+ }
/**
* Get the base URL for the API from settings.
@@ -47,6 +61,7 @@ export class WebApiService {
/**
* Fetch data from the API with authentication headers and access token refresh retry.
+ * This method now proxies to the native layer which handles auth and token refresh.
*/
public async authFetch<T>(
endpoint: string,
@@ -54,47 +69,53 @@ export class WebApiService {
parseJson: boolean = true,
throwOnError: boolean = true
): Promise<T> {
- const headers = new Headers(options.headers ?? {});
-
- // Add authorization header if we have an access token
- const accessToken = await this.getAccessToken();
- if (accessToken) {
- headers.set('Authorization', `Bearer ${accessToken}`);
- }
-
- const requestOptions: RequestInit = {
- ...options,
- headers,
- };
-
try {
- const response = await this.rawFetch(endpoint, requestOptions);
-
- if (response.status === 401) {
- const newToken = await this.refreshAccessToken();
- if (newToken) {
- headers.set('Authorization', `Bearer ${newToken}`);
- const retryResponse = await this.rawFetch(endpoint, {
- ...requestOptions,
- headers,
+ const method = options.method || 'GET';
+ const headers: Record<string, string> = {};
+
+ // Extract headers from options
+ if (options.headers) {
+ if (options.headers instanceof Headers) {
+ options.headers.forEach((value, key) => {
+ headers[key] = value;
+ });
+ } else if (Array.isArray(options.headers)) {
+ options.headers.forEach(([key, value]) => {
+ headers[key] = value;
});
-
- if (!retryResponse.ok) {
- throw new Error(i18n.t('auth.errors.httpError', { status: retryResponse.status }));
- }
-
- return parseJson ? retryResponse.json() : retryResponse as unknown as T;
} else {
- logoutEventEmitter.emit('auth.errors.sessionExpired');
- throw new Error(i18n.t('auth.errors.sessionExpired'));
+ Object.assign(headers, options.headers);
}
}
- if (!response.ok && throwOnError) {
- throw new Error(i18n.t('auth.errors.httpError', { status: response.status }));
+ // Execute request through native layer with auth
+ const responseJson = await NativeVaultManager.executeWebApiRequest(
+ method,
+ endpoint,
+ options.body as string | null ?? null,
+ JSON.stringify(headers),
+ true // requiresAuth
+ );
+
+ const response: NativeWebApiResponse = JSON.parse(responseJson);
+
+ // Handle 401 specially to trigger session expired
+ if (response.statusCode === 401) {
+ logoutEventEmitter.emit('auth.errors.sessionExpired');
+ throw new Error(i18n.t('auth.errors.sessionExpired'));
+ }
+
+ if (response.statusCode >= 400 && throwOnError) {
+ throw new Error(i18n.t('auth.errors.httpError', { status: response.statusCode }));
}
- return parseJson ? response.json() : response as unknown as T;
+ // Parse response body if requested
+ if (parseJson && response.body) {
+ return JSON.parse(response.body) as T;
+ }
+
+ // Return raw response as object with status for non-JSON responses
+ return { status: response.statusCode, ...response } as unknown as T;
} catch (error) {
console.error('API request failed:', error);
throw error;
@@ -103,31 +124,55 @@ export class WebApiService {
/**
* Fetch data from the API without authentication headers and without access token refresh retry.
+ * This method now proxies to the native layer.
*/
public async rawFetch(
endpoint: string,
options: RequestInit = {}
): Promise<Response> {
- const baseUrl = await this.getBaseUrl();
- const url = baseUrl + endpoint;
- const headers = new Headers(options.headers ?? {});
-
- // Add client version header (using API_VERSION for server compatibility)
- headers.set('X-AliasVault-Client', `${AppInfo.CLIENT_NAME}-${AppInfo.API_VERSION}`);
+ try {
+ const method = options.method || 'GET';
+ const headers: Record<string, string> = {};
+
+ // Extract headers from options
+ if (options.headers) {
+ if (options.headers instanceof Headers) {
+ options.headers.forEach((value, key) => {
+ headers[key] = value;
+ });
+ } else if (Array.isArray(options.headers)) {
+ options.headers.forEach(([key, value]) => {
+ headers[key] = value;
+ });
+ } else {
+ Object.assign(headers, options.headers);
+ }
+ }
- const requestOptions: RequestInit = {
- ...options,
- headers,
- };
+ // Execute request through native layer without auth
+ const responseJson = await NativeVaultManager.executeWebApiRequest(
+ method,
+ endpoint,
+ options.body as string | null ?? null,
+ JSON.stringify(headers),
+ false // requiresAuth = false
+ );
+
+ const nativeResponse: NativeWebApiResponse = JSON.parse(responseJson);
+
+ // Convert native response to Response object
+ const responseInit: ResponseInit = {
+ status: nativeResponse.statusCode,
+ statusText: nativeResponse.statusCode >= 200 && nativeResponse.statusCode < 300 ? 'OK' : 'Error',
+ headers: nativeResponse.headers,
+ };
- try {
- const response = await fetch(url, requestOptions);
- return response;
+ return new Response(nativeResponse.body, responseInit);
} catch (error) {
console.error('API request failed:', error);
// Detect SSL certificate errors
- if (error instanceof TypeError) {
+ if (error instanceof Error) {
const errorMessage = error.message.toLowerCase();
// Common SSL/TLS error patterns on iOS and Android
@@ -157,41 +202,6 @@ export class WebApiService {
}
}
- /**
- * Refresh the access token.
- */
- private async refreshAccessToken(): Promise<string | null> {
- const refreshToken = await this.getRefreshToken();
- if (!refreshToken) {
- return null;
- }
-
- try {
- const response = await this.rawFetch('Auth/refresh', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-Ignore-Failure': 'true',
- },
- body: JSON.stringify({
- token: await this.getAccessToken(),
- refreshToken: refreshToken,
- }),
- });
-
- if (!response.ok) {
- throw new Error(i18n.t('auth.errors.tokenRefreshFailed'));
- }
-
- const tokenResponse: TokenResponse = await response.json();
- this.updateTokens(tokenResponse.token, tokenResponse.refreshToken);
- return tokenResponse.token;
- } catch {
- logoutEventEmitter.emit('auth.errors.sessionExpired');
- return null;
- }
- }
-
/**
* Issue GET request to the API.
*/
@@ -259,17 +269,12 @@ export class WebApiService {
/**
* Revoke tokens via WebApi called when logging out.
+ * This is now fully handled by the native layer to ensure token consistency.
*/
public async revokeTokens(): Promise<void> {
- // Revoke tokens via WebApi.
try {
- const refreshToken = await this.getRefreshToken();
- if (refreshToken) {
- await this.post('Auth/revoke', {
- token: await this.getAccessToken(),
- refreshToken: refreshToken,
- }, false);
- }
+ // Delegate to native layer which handles token revocation and cleanup
+ await NativeVaultManager.revokeTokens();
} catch (err) {
console.error('WebApi revoke tokens error:', err);
}
@@ -347,38 +352,50 @@ export class WebApiService {
}
/**
- * Get the currently configured API URL from async storage.
+ * Get the currently configured API URL from native storage.
*/
private async getApiUrl(): Promise<string> {
- const result = await AsyncStorage.getItem('apiUrl') as string;
- if (result && result.length > 0) {
- return result;
+ try {
+ const apiUrl = await NativeVaultManager.getApiUrl();
+ return apiUrl || AppInfo.DEFAULT_API_URL;
+ } catch (error) {
+ console.error('Failed to get API URL from native layer:', error);
+ // Fallback to AsyncStorage
+ const result = await AsyncStorage.getItem('apiUrl') as string;
+ if (result && result.length > 0) {
+ return result;
+ }
+ return AppInfo.DEFAULT_API_URL;
}
-
- return AppInfo.DEFAULT_API_URL;
}
/**
- * Get the current access token from storage.
+ * Sync configuration from AsyncStorage to native layer on initialization.
+ *
+ * This is primarily for backward compatibility / migration purposes:
+ * - Existing users who upgraded from a version without native WebAPI will have tokens in AsyncStorage
+ * - This ensures those tokens are migrated to the native layer on first launch after upgrade
+ * - For new installations, all tokens/config go directly to native layer, so this becomes a no-op
+ *
+ * TODO: This can be removed in a future version (e.g., after some time that 0.24.0 is released)
+ * and once most if not all active users have migrated.
*/
- private async getAccessToken(): Promise<string | null> {
- const token = await AsyncStorage.getItem('accessToken') as string;
- return token ?? null;
- }
-
- /**
- * Get the current refresh token from storage.
- */
- private async getRefreshToken(): Promise<string | null> {
- const token = await AsyncStorage.getItem('refreshToken') as string;
- return token ?? null;
- }
+ private async syncLegacyConfigToNative(): Promise<void> {
+ try {
+ // Sync API URL from AsyncStorage to native (migration only)
+ const apiUrl = await AsyncStorage.getItem('apiUrl');
+ if (apiUrl) {
+ await NativeVaultManager.setApiUrl(apiUrl);
+ }
- /**
- * Update both access and refresh tokens in storage.
- */
- private async updateTokens(accessToken: string, refreshToken: string): Promise<void> {
- await AsyncStorage.setItem('accessToken', accessToken);
- await AsyncStorage.setItem('refreshToken', refreshToken);
- }
+ // Sync tokens from AsyncStorage to native (migration only)
+ const accessToken = await AsyncStorage.getItem('accessToken');
+ const refreshToken = await AsyncStorage.getItem('refreshToken');
+ if (accessToken && refreshToken) {
+ await NativeVaultManager.setAuthTokens(accessToken, refreshToken);
+ }
+ } catch (error) {
+ console.error('Failed to sync config to native layer:', error);
+ }
+ }
}