Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update legacy API callback to go through native HTTP flow (#2159)
Leendert de Borst2cf0e4f1c59d
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.tsindex bf9a4a4ec..64ae440bc 100644--- a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts+++ b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts@@ -70,7 +70,7 @@ export class MobileLoginUtility {* A 404 on this initiating call means the v2 API is missing altogether. Only this call may read a 404 that* way: the poll below answers 404 for an expired request, which is a normal outcome.*/- if (response.status === 404 && await serverPredatesV2Api(await this.webApi.getApiUrl())) {+ if (response.status === 404 && await serverPredatesV2Api(this.webApi)) {throw MobileLoginErrorCode.SERVER_OUTDATED;}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.ktindex d5a7010b2..bcc55ea15 100644--- 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@@ -41,6 +41,11 @@ class WebApiService(private val context: Context) {private const val DEFAULT_API_URL = AppInfo.DEFAULT_API_URLprivate const val SHARED_PREFS_NAME = "aliasvault"+ /**+ * Endpoints that name their own API version, e.g. "v1/Auth/login".+ */+ private val VERSIONED_ENDPOINT = Regex("^v[0-9]+/")+/*** Connection-establishment timeout.*/@@ -142,13 +147,27 @@ class WebApiService(private val context: Context) {return name to value}+ /**+ * Get the API root URL without a trailing slash.+ */+ private fun getRootUrl(): String {+ return getApiUrl().trimEnd('/')+ }+/*** Get the base URL with /v2/ appended.*/private fun getBaseUrl(): String {- val apiUrl = getApiUrl()- val trimmedUrl = apiUrl.trimEnd('/')- return "$trimmedUrl/v2/"+ return "${getRootUrl()}/v2/"+ }++ /**+ * Turn an endpoint into a full URL. If the endpoint starts with "v1/" or "v2/" etc,+ * resolve it against the API root, otherwise resolve it against the base URL.+ */+ private fun resolveUrl(endpoint: String): String {+ val path = endpoint.trimStart('/')+ return if (VERSIONED_ENDPOINT.containsMatchIn(path)) "${getRootUrl()}/$path" else "${getBaseUrl()}$path"}// MARK: - Token Management@@ -259,7 +278,7 @@ class WebApiService(private val context: Context) {body: String?,headers: Map<String, String>,): WebApiResponse = withContext(Dispatchers.IO) {- val urlString = "${getBaseUrl()}$endpoint"+ val urlString = resolveUrl(endpoint)var connection: HttpURLConnection? = nulltry {diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift b/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swiftindex fd7996907..3eb10d0e0 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift@@ -100,13 +100,31 @@ public class WebApiService {return (trimmedName, trimmedValue)}+ /**+ * Get the API root URL without a trailing slash+ */+ private func getRootUrl() -> String {+ let apiUrl = getApiUrl()+ return apiUrl.hasSuffix("/") ? String(apiUrl.dropLast()) : apiUrl+ }+/*** Get the base URL with /v2/ appended*/private func getBaseUrl() -> String {- let apiUrl = getApiUrl()- let trimmedUrl = apiUrl.hasSuffix("/") ? String(apiUrl.dropLast()) : apiUrl- return "\(trimmedUrl)/v2/"+ return "\(getRootUrl())/v2/"+ }++ /**+ * Turn an endpoint into a full URL. If the endpoint starts with "v1/" or "v2/" etc,+ * resolve it against the API root, otherwise resolve it against the base URL.+ */+ private func resolveUrl(_ endpoint: String) -> String {+ let path = endpoint.drop(while: { $0 == "/" })+ if path.range(of: "^v[0-9]+/", options: .regularExpression) != nil {+ return "\(getRootUrl())/\(path)"+ }+ return "\(getBaseUrl())\(path)"}// MARK: - Token Management@@ -209,7 +227,7 @@ public class WebApiService {body: String?,headers: [String: String]) async throws -> WebApiResponse {- let urlString = "\(getBaseUrl())\(endpoint)"+ let urlString = resolveUrl(endpoint)guard let url = URL(string: urlString) else {throw NSError(diff --git a/core/client/src/api/WebApiService.ts b/core/client/src/api/WebApiService.tsindex 1cccb9fcf..4d59591f2 100644--- a/core/client/src/api/WebApiService.ts+++ b/core/client/src/api/WebApiService.ts@@ -32,10 +32,10 @@ const VAULT_TRANSFER_TIMEOUT_MS = 180000;const LARGE_TRANSFER_PATH = 'vault';/**- * A signal that aborts after `ms`.+ * A signal that aborts after `ms`. Falls back to a timer on hosts without `AbortSignal.timeout`.* @param ms - the timeout*/-function timeoutAbortSignal(ms: number): AbortSignal {+export function timeoutAbortSignal(ms: number): AbortSignal {if (typeof AbortSignal.timeout === 'function') {return AbortSignal.timeout(ms);}@@ -88,6 +88,11 @@ export class WebApiService {*/public static readonly API_VERSION = 2;+ /**+ * Endpoints that name their own API version, e.g. 'v1/Auth/login'.+ */+ private static readonly VERSIONED_ENDPOINT = /^v\d+\//;+/*** Build the versioned base URL for an API root URL, e.g. 'https://app.aliasvault.com/api' to 'https://app.aliasvault.com/api/v2/'.*/@@ -102,6 +107,18 @@ export class WebApiService {return WebApiService.versionedBaseUrl(await this.getApiUrl());}+ /**+ * Turn an endpoint into a full URL. An endpoint that names its own API version (e.g. 'v1/Auth/login') resolves+ * against the API root, every other endpoint against the version this client speaks.+ */+ private async resolveUrl(endpoint: string): Promise<string> {+ const path = endpoint.replace(/^\/+/, '');+ if (WebApiService.VERSIONED_ENDPOINT.test(path)) {+ return (await this.getApiUrl()).replace(/\/$/, '') + '/' + path;+ }+ return await this.getBaseUrl() + path;+ }+/*** Check if the current server is self-hosted.*/@@ -208,7 +225,7 @@ export class WebApiService {endpoint: string,options: RequestInit = {}): Promise<Response> {- const url = await this.getBaseUrl() + endpoint;+ const url = await this.resolveUrl(endpoint);const headers = new Headers(options.headers ?? {});return this.performFetch(url, endpoint, { ...options, headers }, this.isLargeTransfer(endpoint, headers));}@@ -217,7 +234,7 @@ export class WebApiService {* Run a request on behalf of the Rust sync engine.*/public async engineRequest(method: string, path: string, body: string | undefined, requiresAuth: boolean, largeTransfer: boolean): Promise<EngineHttpResponse> {- const url = await this.getBaseUrl() + path.replace(/^\/+/, '');+ const url = await this.resolveUrl(path);const headers = new Headers({ Accept: 'application/json' });if (body !== undefined) {headers.set('Content-Type', 'application/json');diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.tsindex dba7c1312..699696f6c 100644--- a/core/client/src/auth/SrpLoginService.ts+++ b/core/client/src/auth/SrpLoginService.ts@@ -9,7 +9,7 @@ import type { BadRequestResponse, LoginResponse, ValidateLoginRequest, ValidateL/*** The part of an API client the login requests need.*/-export type SrpLoginApi = Pick<WebApiService, 'rawFetch' | 'getApiUrl'>;+export type SrpLoginApi = Pick<WebApiService, 'rawFetch'>;/*** The recovery code variant of the validate request.@@ -91,7 +91,7 @@ export class SrpLoginService {* @returns The parsed body*/private async parseAuthResponse<T>(response: Response): Promise<T> {- await throwIfServerPredatesV2Api(response.status, await this.api.getApiUrl());+ await throwIfServerPredatesV2Api(response.status, this.api);if (response.status === 400) {const badRequestResponse = await response.json() as BadRequestResponse;throw new ApiAuthError(badRequestResponse.title);diff --git a/core/client/src/sync/LegacyStorageModelMigration.ts b/core/client/src/sync/LegacyStorageModelMigration.tsindex f161539f5..2b05932dd 100644--- a/core/client/src/sync/LegacyStorageModelMigration.ts+++ b/core/client/src/sync/LegacyStorageModelMigration.ts@@ -5,26 +5,35 @@*/import { ServerUpdateRequiredError } from '../api/errors/ServerUpdateRequiredError';+import { timeoutAbortSignal } from '../api/WebApiService';import { VaultKeyService } from '../auth/VaultKeyService';+import type { WebApiService } from '../api/WebApiService';+/** -- 1. Servers predating the v2 vault API --*/-/** How long the legacy-API probe may take before we stop blaming the server version. */+/** How long the legacy-API probe may take before we stop blaming the server version, where the host's API client honors the abort signal. */const V1_PROBE_TIMEOUT_MS = 3000;+/**+ * The part of an API client the legacy probe needs.+ */+export type LegacyProbeApi = Pick<WebApiService, 'rawFetch'>;+/*** Probe whether the configured server answers on the v1 API while v2 does not respond.- * @param apiBaseUrl - the configured API base URL, without a version segment+ *+ * The probe is a GET on purpose: the endpoint only accepts POST, so an existing route answers 405 and a server+ * without the v1 API answers 404, which is the whole signal.+ * @param api - the API client the probe goes through*/-export async function serverPredatesV2Api(apiBaseUrl: string): Promise<boolean> {+export async function serverPredatesV2Api(api: LegacyProbeApi): Promise<boolean> {try {- const response = await fetch(`${apiBaseUrl.replace(/\/$/, '')}/v1/Auth/login`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: '{}',- signal: AbortSignal.timeout(V1_PROBE_TIMEOUT_MS),+ const response = await api.rawFetch('v1/Auth/login', {+ method: 'GET',+ signal: timeoutAbortSignal(V1_PROBE_TIMEOUT_MS),});return response.status !== 404;@@ -38,14 +47,14 @@ export async function serverPredatesV2Api(apiBaseUrl: string): Promise<boolean>* Translate a 404 from a v2 endpoint into {@link ServerUpdateRequiredError} when the server turns out to be an* outdated AliasVault install.* @param status - the HTTP status of the v2 response- * @param apiBaseUrl - the configured API base URL, without a version segment+ * @param api - the API client the probe goes through*/-export async function throwIfServerPredatesV2Api(status: number, apiBaseUrl: string): Promise<void> {+export async function throwIfServerPredatesV2Api(status: number, api: LegacyProbeApi): Promise<void> {if (status !== 404) {return;}- if (await serverPredatesV2Api(apiBaseUrl)) {+ if (await serverPredatesV2Api(api)) {throw new ServerUpdateRequiredError();}}