Skip to content

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

19.7 KB
Raw Blame
import { StorageKeys } from '../constants/StorageKeys';
import { AppInfo } from "../platform/AppInfo";
import { getPlatform } from '../platform/ClientPlatform';
import { logDefect, logExpected } from '../utilities/Diagnostics';

import { CapabilityService } from './CapabilityService';
import { ApiAuthError } from './errors/ApiAuthError';
import { ApiRequestError } from './errors/ApiRequestError';
import { ClientUpgradeRequiredError } from './errors/ClientUpgradeRequiredError';
import { logFailure } from './errors/ExpectedFailure';
import { NetworkError } from './errors/NetworkError';
import { PayloadTooLargeError } from './errors/PayloadTooLargeError';
import { RequestTimeoutError } from './errors/RequestTimeoutError';
import { ServerUpdateRequiredError } from './errors/ServerUpdateRequiredError';
import { logoutEventEmitter } from './LogoutEventEmitter';

import type { LogoutReason } from '../sync/VaultSyncEngine';
import type { AuthLogModel, AuthLogsResponse, RefreshToken, SessionsResponse, StatusResponseV2 } from '@aliasvault/models/webapi';

type RequestInit = globalThis.RequestInit;

/**
 * Total request timeout for lightweight API calls (status checks, auth, etc.). Kept short so the
 * popup falls back to offline mode quickly when the server is unreachable.
 */
const DEFAULT_REQUEST_TIMEOUT_MS = 5000;

/**
 * Total request timeout for vault download/upload, which can carry a large encrypted blob.
 */
const VAULT_TRANSFER_TIMEOUT_MS = 180000;

/**
 * Path prefix whose requests carry vault ciphertext and therefore use the larger timeout setting {@link VAULT_TRANSFER_TIMEOUT_MS}.
 */
const LARGE_TRANSFER_PATH = 'vault';

/**
 * A signal that aborts after `ms`. Falls back to a timer on hosts without `AbortSignal.timeout`.
 * @param ms - the timeout
 */
export function timeoutAbortSignal(ms: number): AbortSignal {
  if (typeof AbortSignal.timeout === 'function') {
    return AbortSignal.timeout(ms);
  }
  const controller = new AbortController();
  setTimeout(() => controller.abort(new Error('TimeoutError')), ms);
  return controller.signal;
}

/**
 * A signal that aborts as soon as any of the given signals does.
 * @param signals - the signals to combine
 */
function anyAbortSignal(signals: AbortSignal[]): AbortSignal {
  if (typeof AbortSignal.any === 'function') {
    return AbortSignal.any(signals);
  }
  const controller = new AbortController();
  for (const signal of signals) {
    if (signal.aborted) {
      controller.abort(signal.reason);
      break;
    }
    signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
  }
  return controller.signal;
}

/**
 * Type for the token response from the API.
 */
type TokenResponse = {
  token: string;
  refreshToken: string;
}

/**
 * A response as the Rust sync engine reads it: the HTTP status and the body text, never thrown on a non-2xx status.
 */
export type EngineHttpResponse = {
  status: number;
  body: string;
  /** The body as raw bytes, set on success when the request asked for a binary response. */
  bytes?: Uint8Array;
};

/**
 * Service class for interacting with the web API.
 * Other platform implementations: WebApiService.swift (iOS), WebApiService.kt (Android).
 */
export class WebApiService {
  /**
   * The server API version this client speaks.
   */
  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/'.
   */
  public static versionedBaseUrl(apiUrl: string): string {
    return apiUrl.replace(/\/$/, '') + `/v${WebApiService.API_VERSION}/`;
  }

  /**
   * Get the base URL for the API from settings.
   */
  private async getBaseUrl(): Promise<string> {
    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.
   */
  public async isSelfHosted(): Promise<boolean> {
    const apiUrl = await this.getApiUrl();
    return apiUrl !== AppInfo.DEFAULT_API_URL;
  }

  /**
   * Fetch data from the API with authentication headers and access token refresh retry.
   *
   * Failures are thrown as typed errors to let the caller decide whether its own failure is expected or a defect.
   */
  public async authFetch<T>(
    endpoint: string,
    options: RequestInit = {},
    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,
    };

    const response = await this.rawFetch(endpoint, requestOptions);

    if (response.status === 401) {
      const refreshResult = await this.refreshAccessToken();

      if (refreshResult.token) {
        headers.set('Authorization', `Bearer ${refreshResult.token}`);
        const retryResponse = await this.rawFetch(endpoint, {
          ...requestOptions,
          headers,
        });

        if (!retryResponse.ok) {
          if (retryResponse.status === 401 || retryResponse.status === 403) {
            throw new ApiAuthError('Request failed after token refresh');
          }
          if (retryResponse.status === 413) {
            throw new PayloadTooLargeError(`Request rejected with HTTP 413: payload exceeds server limit`);
          }
          throw await ApiRequestError.fromResponse(retryResponse);
        }

        return parseJson ? retryResponse.json() : retryResponse as unknown as T;
      } else if (refreshResult.isAuthError) {
        logoutEventEmitter.emit('common.errors.sessionExpired');
        throw new ApiAuthError('Session expired');
      } else {
        throw new NetworkError('Token refresh failed due to network error');
      }
    }

    if (response.status === 413 && throwOnError) {
      throw new PayloadTooLargeError(`Request rejected with HTTP 413: payload exceeds server limit`);
    }

    if (!response.ok && throwOnError) {
      throw await ApiRequestError.fromResponse(response);
    }

    return parseJson ? response.json() : response as unknown as T;
  }

  /**
   * Fetch data from the API without authentication headers and without access token refresh retry.
   */
  public async rawFetch(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<Response> {
    const url = await this.resolveUrl(endpoint);
    const headers = new Headers(options.headers ?? {});
    return this.performFetch(url, endpoint, { ...options, headers }, this.isLargeTransfer(endpoint, headers));
  }

  /**
   * Run a request on behalf of the Rust sync engine.
   */
  public async engineRequest(method: string, path: string, body: string | Uint8Array | undefined, requiresAuth: boolean, largeTransfer: boolean, binaryResponse = false): Promise<EngineHttpResponse> {
    const url = await this.resolveUrl(path);
    const headers = new Headers({ Accept: binaryResponse ? 'application/octet-stream' : 'application/json' });
    if (body !== undefined) {
      headers.set('Content-Type', body instanceof Uint8Array ? 'application/octet-stream' : 'application/json');
    }
    const requestBody = body as string | Uint8Array<ArrayBuffer> | undefined;
    const accessToken = requiresAuth ? await this.getAccessToken() : null;
    if (accessToken) {
      headers.set('Authorization', `Bearer ${accessToken}`);
    }

    try {
      let response = await this.performFetch(url, path, { method, headers, body: requestBody }, largeTransfer);
      if (response.status === 401 && requiresAuth) {
        const refreshResult = await this.refreshAccessToken();
        if (refreshResult.token) {
          headers.set('Authorization', `Bearer ${refreshResult.token}`);
          response = await this.performFetch(url, path, { method, headers, body: requestBody }, largeTransfer);
        } else if (refreshResult.isAuthError) {
          // The session is truly expired; the engine turns the 401 into its logout outcome.
          logoutEventEmitter.emit('common.errors.sessionExpired');
          return { status: 401, body: '' };
        } else {
          throw new NetworkError('Token refresh failed due to network error');
        }
      }
      if (binaryResponse && response.ok) {
        return { status: response.status, body: '', bytes: new Uint8Array(await response.arrayBuffer()) };
      }
      return { status: response.status, body: await response.text() };
    } catch (error) {
      if (error instanceof ClientUpgradeRequiredError) {
        return { status: 426, body: '' };
      }
      throw error;
    }
  }

  /**
   * Send one request with the client headers and the timeout for its size.
   */
  private async performFetch(url: string, endpoint: string, options: RequestInit & { headers: Headers }, largeTransfer: boolean): Promise<Response> {
    const headers = options.headers;

    // Add client version header (using API_VERSION for server compatibility)
    headers.set('X-AliasVault-Client', `${AppInfo.CLIENT_NAME}-${AppInfo.API_VERSION}`);

    // Headers the host adds to every request (e.g. custom proxy headers for a self-hosted setup).
    for (const [name, value] of Object.entries(await getPlatform().requestHeaders?.() ?? {})) {
      headers.set(name, value);
    }

    const timeoutSignal = timeoutAbortSignal(largeTransfer ? VAULT_TRANSFER_TIMEOUT_MS : DEFAULT_REQUEST_TIMEOUT_MS);
    const requestOptions: RequestInit = {
      ...options,
      headers,
      signal: options.signal ? anyAbortSignal([options.signal, timeoutSignal]) : timeoutSignal,
    };

    let response: Response;
    try {
      response = await fetch(url, requestOptions);
    } catch (error) {
      logExpected(`[WebApi] Request failed: ${endpoint}`, error);
      if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
        throw new RequestTimeoutError(`Request timed out: ${endpoint}`, error);
      }
      throw new NetworkError(
        error instanceof Error ? error.message : 'Network request failed',
        error instanceof Error ? error : undefined
      );
    }

    // The server rejects clients it no longer supports with HTTP 426 on any endpoint.
    if (response.status === 426) {
      throw new ClientUpgradeRequiredError();
    }

    return response;
  }

  /**
   * Whether a request carries vault ciphertext and so runs on the long timeout.
   */
  private isLargeTransfer(endpoint: string, headers: Headers): boolean {
    const path = endpoint.split('?')[0].replace(/^\/+|\/+$/g, '').toLowerCase();
    return path === LARGE_TRANSFER_PATH || path.startsWith(`${LARGE_TRANSFER_PATH}/`) ||
      (headers.get('Accept') ?? '').toLowerCase().includes('application/octet-stream');
  }

  /**
   * Issue GET request to the API.
   */
  public async get<T>(endpoint: string): Promise<T> {
    return this.authFetch<T>(endpoint, { method: 'GET' });
  }

  /**
   * Issue GET request to the API expecting a file download and return it as raw bytes.
   */
  public async downloadBlob(endpoint: string): Promise<Uint8Array> {
    const response = await this.authFetch<Response>(endpoint, {
      method: 'GET',
      headers: {
        'Accept': 'application/octet-stream',
      }
    }, false);

    // Get the response as an ArrayBuffer
    const arrayBuffer = await response.arrayBuffer();
    return new Uint8Array(arrayBuffer);
  }

  /**
   * Issue POST request to the API.
   */
  public async post<TRequest, TResponse>(
    endpoint: string,
    data: TRequest,
    parseJson: boolean = true
  ): Promise<TResponse> {
    return this.authFetch<TResponse>(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    }, parseJson);
  }

  /**
   * Issue DELETE request to the API.
   */
  public async delete<T>(endpoint: string): Promise<T> {
    return this.authFetch<T>(endpoint, { method: 'DELETE' }, false);
  }

  /**
   * Revoke tokens via WebApi called when logging out.
   * This revokes all tokens for the current device.
   */
  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);
      }
    } catch (err) {
      logFailure('[WebApi] Revoking tokens failed', err);
    }
  }

  /**
   * Revoke only the current specific token via WebApi.
   * Unlike revokeTokens(), this does NOT revoke other sessions for the same device.
   */
  public async revokeCurrentTokens(): Promise<void> {
    try {
      const refreshToken = await this.getRefreshToken();
      if (refreshToken) {
        await this.post('Auth/revoke-token', {
          token: await this.getAccessToken(),
          refreshToken: refreshToken,
        }, false);
      }
    } catch (err) {
      logFailure('[WebApi] Revoking the current token failed', err);
    }
  }

  /**
   * Calls the status endpoint to check if the auth tokens are still valid, app is supported and the vault is up to date.
   * Returns offline indicator (serverVersion: '0.0.0') for network failures and server errors (5xx, etc.).
   * Auth errors (ApiAuthError) are re-thrown to be handled appropriately (e.g., trigger logout), and an uncoded 404
   * (a server that predates the v2 API) throws {@link ServerUpdateRequiredError}, like the Rust sync engine.
   */
  public async getStatus(): Promise<StatusResponseV2> {
    try {
      const status = await this.get<StatusResponseV2>('Status');
      // Persist the server version so it can be shown on the settings page, also while offline.
      if (status.serverVersion && status.serverVersion !== '0.0.0') {
        await getPlatform().storage.set(StorageKeys.SERVER_VERSION, status.serverVersion);
      }

      // Persist the capabilities that are enabled for this account.
      await CapabilityService.store(status);

      return status;
    } catch (error) {
      /**
       * Only re-throw ApiAuthError (session expired, auth failures).
       * All other errors (NetworkError, HTTP 5xx, 404, etc.) indicate the server
       * is unreachable or misconfigured, so return offline indicator.
       */
      if (error instanceof ApiAuthError) {
        throw error;
      }
      // Server refused this client version.
      if (error instanceof ClientUpgradeRequiredError) {
        throw error;
      }
      if (error instanceof ApiRequestError && error.statusCode === 404 && !error.apiErrorCode) {
        throw new ServerUpdateRequiredError();
      }
      return {
        clientVersionSupported: true,
        serverVersion: '0.0.0',
        manifestRevisions: [],
        personalManifestId: null,
        srpSalt: '',
        capabilities: await CapabilityService.getAll()
      };
    }
  }

  /**
   * Get the active sessions (logged in devices) for the current user from the server.
   */
  public async getActiveSessions(): Promise<RefreshToken[]> {
    return (await this.get<SessionsResponse>('Security/sessions')).sessions;
  }

  /**
   * Revoke a session (logged in device) for the current user on the server.
   */
  public async revokeSession(sessionId: string): Promise<void> {
    await this.delete<void>(`Security/sessions/${sessionId}`);
  }

  /**
   * Get the recent auth logs for the current user from the server.
   */
  public async getAuthLogs(): Promise<AuthLogModel[]> {
    return (await this.get<AuthLogsResponse>('Security/authlogs')).authLogs;
  }

  /**
   * Validates the status response and returns the logout reason if this client cannot continue.
   */
  public validateStatusResponse(statusResponse: StatusResponseV2): LogoutReason | null {
    if (!statusResponse.clientVersionSupported) {
      return 'clientVersionNotSupported';
    }

    if (!AppInfo.isServerVersionSupported(statusResponse.serverVersion)) {
      return 'serverVersionNotSupported';
    }

    return null;
  }

  /**
   * Result of a token refresh attempt.
   * - token: New access token if refresh succeeded
   * - isAuthError: True if refresh failed due to auth error (401/403), meaning session is truly expired
   *                False if refresh failed due to network/server error, meaning we should enter offline mode
   */
  private async refreshAccessToken(): Promise<{ token: string | null; isAuthError: boolean }> {
    const refreshToken = await this.getRefreshToken();
    if (!refreshToken) {
      // No refresh token means session is truly expired
      return { token: null, isAuthError: true };
    }

    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) {
        const tokenResponse: TokenResponse = await response.json();
        this.updateTokens(tokenResponse.token, tokenResponse.refreshToken);
        return { token: tokenResponse.token, isAuthError: false };
      }

      // Auth errors (401/403) mean session is truly expired
      if (response.status === 401 || response.status === 403) {
        return { token: null, isAuthError: true };
      }

      // Server errors (5xx) or other non-auth errors, treat as offline/transient
      logExpected(`[WebApi] Token refresh failed with status ${response.status}, treating as offline`);
      return { token: null, isAuthError: false };
    } catch (error) {
      // Server refused this client version.
      if (error instanceof ClientUpgradeRequiredError) {
        throw error;
      }

      // Network errors (server unreachable, timeout, DNS, etc.), treat as offline
      if (error instanceof NetworkError) {
        logExpected('[WebApi] Token refresh failed due to network error, treating as offline');
        return { token: null, isAuthError: false };
      }

      // Unexpected errors, treat as auth error so logout is triggered
      logDefect('[WebApi] Unexpected error during token refresh', error);
      return { token: null, isAuthError: true };
    }
  }

  /**
   * Get the current access token from storage.
   */
  private async getAccessToken(): Promise<string | null> {
    const token = await getPlatform().storage.get(StorageKeys.ACCESS_TOKEN) as string;
    return token ?? null;
  }

  /**
   * Get the current refresh token from storage.
   */
  private async getRefreshToken(): Promise<string | null> {
    const token = await getPlatform().storage.get(StorageKeys.REFRESH_TOKEN) as string;
    return token ?? null;
  }

  /**
   * Update both access and refresh tokens in storage.
   */
  private async updateTokens(accessToken: string, refreshToken: string): Promise<void> {
    await getPlatform().storage.set(StorageKeys.ACCESS_TOKEN, accessToken);
    await getPlatform().storage.set(StorageKeys.REFRESH_TOKEN, refreshToken);
  }

  /**
   * Get the API URL from settings.
   */
  public async getApiUrl(): Promise<string> {
    const result = await getPlatform().storage.get(StorageKeys.API_URL) as string;
    if (!result || result.length === 0) {
      return AppInfo.DEFAULT_API_URL;
    }

    return result;
  }
}