Skip to content

React API Kit Specification

mandla-enkosi edited this page Apr 5, 2025 · 5 revisions

1. Overview and Objectives

  • Project Name: React API Kit
  • Purpose: Provide a focused middleware layer that sits between the frontend React application (web and React Native) and a single backend. This package unifies client-side authentication (handling JWT, OAuth2 flows with OIDC, and Server-Side Sessions), token management, API communication via a robust HTTP client, and polling, offering a uniform interface so developers do not have to duplicate these common patterns across platforms.
  • Primary Goals:
    • Unified Authentication: Handle common authentication methods (jwt, oauth2, session) with appropriate strategies for each.
    • Token Management (for JWT/OAuth2): Securely store (memory or persistent encrypted), refresh (concurrency-safe), validate expiry, and automatically attach tokens to requests.
    • OAuth2/OIDC Client: Implement standard client-side flows (Authorization Code + PKCE recommended) with platform-specific redirect handling and user info retrieval.
    • Session Awareness: Facilitate interaction with server-managed sessions (HttpOnly cookies) by managing status checks and login/logout triggers without accessing cookies directly.
    • Robust HTTP Client: Provide a flexible Axios wrapper with interceptors for authentication, standardized error handling (StandardError), request queuing during refresh, configurable retries, cancellation, and optional caching/deduplication.
    • Reliable Polling: Offer a polling service (startPolling) with configurable intervals, backoff strategies, termination conditions, cancellation, and network awareness.
    • Internal State & Hooks: Utilize a lightweight internal state store (e.g., Zustand) and expose essential status (auth, network, operations) via performant React hooks.
    • Platform Abstraction: Abstract critical platform differences for secure storage, authentication navigation, and network information, prioritizing security by default.
    • Centralized Error Handling: Offer an optional global onError callback for integrating with error reporting services.

High Level Diagram

flowchart TD
    A["React API Kit Core"]
    A --> B["Authentication Module"]
    A --> C["HTTP Client (Axios)"]
    A --> D["Polling Service"]
    A --> E["Platform Abstraction Layer"]
    A --> F["Internal State Management"]

    B --> B1["Auth Type Handler (JWT/OAuth2/Session)"]
    B --> B2["Token Manager (Storage/Refresh - for JWT/OAuth2)"]
    B --> B3["OAuth2 Flow Orchestrator"]
    B --> B4["OIDC User Info Handler"]

    C --> C1["Request Handling & Interceptors"]
    C --> C2["Error Handling & Retry Strategy"]
    C --> C3["Request Queuing & Optional Caching/Dedupe"]

    E --> E1["Secure Storage Abstraction ('memory' \\| 'secure')"]
    E --> E2["Navigation Abstraction (Auth Redirects)"]
    E --> E3["Network Info Abstraction"]

    subgraph CoreModules [Core Functionalities]
      B
      C
      D
      E
      F
    end

    style CoreModules fill:#f9f,stroke:#333,stroke-width:2px

    G["React/React Native App"] -- "Configures & Uses" --> A
    A -- "Interacts with" --> H["Backend API / OAuth Provider"]
Loading

1.1 Dependency Management Strategy

  • Direct Dependencies:
    • axios
    • zustand (or similar lightweight state manager)
    • Potentially crypto-js (for Web secure storage encryption if Web Crypto API isn't sufficient/targeted).
  • Peer Dependencies:
    • react
  • Optional Peer Dependencies (React Native):
    • @react-native-community/netinfo: Recommended for INetworkInfo.
    • react-native-encrypted-storage or react-native-keychain: Recommended for secure IStorage.
    • react-native-linking: Required for deep linking if not using react-native-app-auth.
    • react-native-app-auth: Recommended for INavigation (OAuth2) for best UX/security.
  • Versioning: Explicit minimum versions declared in package.json. Adherence to SemVer. Treeshaking friendly (ESM primary, CJS fallback).

1.2 Platform Detection and Abstraction

  • Platform Detection Mechanism: Internal utility (PlatformManager) detects 'web' vs 'react-native' once on initialization.
  • Platform Abstraction Layer: Provides platform-specific implementations via consistent interfaces:
    • IStorage: Abstracts storage logic. Two core strategies:
      • memory: In-memory storage (Web Default).
      • secure: Persistent, encrypted storage (RN Default, Web Opt-in). Uses encrypted localStorage (Web, requires developer-provided key) or native secure storage (RN, via optional peer deps).
    • INavigation: Abstracts OAuth redirect initiation (initiateRedirect) and callback/deep link capture (listenForRedirect). Uses window.location (Web) or react-native-app-auth/Linking (RN).
    • INetworkInfo: Abstracts network status (getCurrentState, subscribe). Uses navigator.onLine/Events (Web) or @react-native-community/netinfo (RN).
  • Developer Platform Guidelines:
    • Crucial: Detailed documentation for RN native dependency installation, linking, and Info.plist/AndroidManifest.xml configuration for deep links (OAuth callbacks).
    • Crucial: Clear warnings about security risks of Web secure storage (localStorage) and the developer's responsibility for providing and managing the secureStorageEncryptionKey securely.

2. Core Package: @react-api-kit/core

2.1 Functional Requirements

2.1.1 Authentication & Token Management (Unified)

  • Configuration (AuthConfig):
    • authType: 'jwt' | 'oauth2' | 'session' (required, determines the primary authentication method).
    • storageType?: 'memory' | 'secure' (optional, default: 'memory' for web, 'secure' for RN).
    • webSpecific.secureStorageEncryptionKey?: string | (() => Promise<string>) (required if storageType: 'secure' on web).
    • Type-specific configurations (jwt, oauth2, session) containing endpoints, client IDs, etc.
    • onError?: (error: StandardError) => void (optional global callback).
    • tokenRefreshBuffer?: number (optional, default 60s).
  • Internal HTTP Requester:
    • A dedicated, minimal Axios wrapper used exclusively for auth-related backend calls
    • Separate from the main exported httpClient to avoid circular dependencies and prevent token refresh loops
    • Used for:
      • JWT: Login and token refresh endpoint calls
      • OAuth2: Token exchange, token refresh, and userinfo endpoint calls
      • Session: Status check, login/logout endpoint calls
    • Features:
      • Basic request functionality (URL, method, data, headers)
      • Simple error handling (maps to InternalAuthError)
      • Optional token attachment for refresh/userinfo calls
      • No interceptors for refresh triggering (preventing circular dependencies)
      • No complex retry strategies, queuing, or caching
    • Implementation:
      • Located at /packages/core/src/auth/_internal/httpRequester.ts
      • Not exported publicly
      • Maps InternalAuthError to StandardError before propagation
  • JWT Handling (authType: 'jwt'):
    • Acquisition via loginEndpoint using internal HTTP requester.
    • Storage of access/refresh tokens via IStorage (memory or secure).
    • Refresh via refreshEndpoint using internal HTTP requester and TokenRefreshManager.
    • Token attachment via httpClient interceptor.
  • OAuth2/OIDC Client Handling (authType: 'oauth2'):
    • Flows: Authorization Code Flow + PKCE (default). Implicit Flow (optional, configure via options, documented discouragement).
    • PKCE: Enabled by default (usePKCE: true). Verifier managed via IStorage (secure recommended).
    • State: CSRF protection via state param managed via IStorage (session or secure, depending on overall storageType).
    • OIDC: Support openid scope, parse id_token (basic validation: nonce, expiry), fetch from userinfoEndpoint if configured. Store claims in AuthState.userInfo.
    • Redirects: Use INavigation.initiateRedirect and INavigation.listenForRedirect.
    • Token Exchange: Use internal HTTP requester to call backend tokenEndpoint (code+verifier -> tokens).
    • Storage: Store tokens via IStorage.
    • Refresh: Use refresh_token grant via internal HTTP requester and TokenRefreshManager.
    • Session Management: Monitor expiry, trigger refresh. Support optional silent refresh (prompt=none).
  • Server Session Handling (authType: 'session'):
    • No token storage handled by the kit.
    • login() navigates to/calls loginEndpoint.
    • logout() calls logoutEndpoint.
    • isAuthenticated() calls checkStatusEndpoint using main httpClient (to include cookies). Debounced/cached result.
    • getToken() returns null. refreshToken() does nothing/rejects.
    • Instructs httpClient to use withCredentials: true and skip token attachment. 401s update AuthState.
  • Common:
    • Concurrency: TokenRefreshManager ensures only one refresh attempt (JWT or OAuth2) happens at a time.
    • Storage: All sensitive data (tokens, verifiers, state) managed via IStorage.
    • State: AuthState updated internally, exposed via useAuthState(). Raw tokens not included in AuthState.
    • Logout: Clears IStorage, resets AuthState, calls relevant session endpoint if configured.
    • Error Handling: Maps internal auth errors (including InternalAuthError from internal requests) to StandardError. Calls global onError hook. Updates AuthState.error.

2.1.2 HTTP Client Integration (Axios)

  • Axios Wrapper (httpClient): Exported configured instance.
  • Interceptors:
    • Request: Checks authType. Attaches Authorization: Bearer token (if JWT/OAuth2 & requireAuth: true). Sets withCredentials: true (if Session). Handles AbortSignal. Updates OperationState.pendingRequests.
    • Response: Detects 401/403 -> triggers AuthenticationManager._triggerRefresh() (if JWT/OAuth2 & not skipRefresh) -> interacts with RequestQueue. Detects transient errors -> triggers RetryHandler. Maps errors to StandardError -> calls global onError. Updates OperationState.pendingRequests.
  • Request Queue: Holds requests during token refresh. Implements FIFO, timeout (e.g., 5s), max size limit. Rejects/processes based on refresh outcome.
  • Retry Strategy: Configurable retries (count, backoff) for transient network/server errors (e.g., codes 500, 502, 503, 504, network error, timeout) on idempotent methods by default. Uses backoff strategies (exponential default) with jitter. Respects Retry-After header if present.
  • Cancellation: Pass AbortController.signal in HttpClientRequestConfig. Cancels in-flight or queued requests. Returns specific StandardError (REQUEST_CANCELLED).
  • Optional Features (Default Off):
    • Caching: In-memory cache for GET. Configurable TTL/invalidation via clearCache() and forceRefresh config.
    • Deduplication: Prevent identical concurrent GET requests.
  • Error Handling: Centralized mapping to StandardError via ErrorHandler.
  • Error Codes: Comprehensive list of standardized error codes are used throughout the library:
export type StandardErrorCode =
  // Authentication Errors
  | 'AUTH_UNAUTHORIZED'         // General 401 from backend API
  | 'AUTH_FORBIDDEN'            // General 403 from backend API
  | 'AUTH_TOKEN_EXPIRED'        // Specifically detected expired token
  | 'AUTH_REFRESH_FAILED'       // Token refresh attempt failed
  | 'AUTH_LOGIN_REQUIRED'       // Action requires authentication
  | 'AUTH_CONFIG_ERROR'         // Invalid auth configuration
  | 'AUTH_REQUEST_FAILED'       // Generic auth request failure
  | 'AUTH_SERVICE_UNAVAILABLE'  // Auth server unavailable
  | 'AUTH_STATE_MISMATCH'       // OAuth state validation failed
  | 'AUTH_PKCE_ERROR'           // PKCE verification failed
  | 'AUTH_REDIRECT_ERROR'       // OAuth redirect handling failed
  
  // Network Errors
  | 'NETWORK_ERROR'             // Generic connection issue
  | 'NETWORK_TIMEOUT'           // Request timed out
  | 'NETWORK_OFFLINE'           // Client is offline
  
  // HTTP Server Errors
  | 'HTTP_BAD_REQUEST'          // 400
  | 'HTTP_NOT_FOUND'            // 404
  | 'HTTP_METHOD_NOT_ALLOWED'   // 405
  | 'HTTP_CONFLICT'             // 409
  | 'HTTP_UNPROCESSABLE_ENTITY' // 422
  | 'HTTP_TOO_MANY_REQUESTS'    // 429
  | 'HTTP_INTERNAL_SERVER_ERROR' // 500
  | 'HTTP_SERVICE_UNAVAILABLE'  // 503
  | 'HTTP_GATEWAY_TIMEOUT'      // 504
  | 'HTTP_UNKNOWN_ERROR'        // Other non-2xx
  
  // Request/Client Errors
  | 'REQUEST_CANCELLED'         // Cancelled via AbortController
  | 'REQUEST_QUEUE_TIMEOUT'     // Timed out in refresh queue
  | 'RETRY_LIMIT_EXCEEDED'      // Max retries reached
  | 'CACHE_ERROR'               // Cache-related error
  
  // Platform Errors
  | 'PLATFORM_STORAGE_ERROR'    // Error in IStorage operations
  | 'PLATFORM_NAVIGATION_ERROR' // Error in INavigation operations
  | 'PLATFORM_NETWORK_ERROR'    // Error in INetworkInfo operations
  
  // Polling Errors
  | 'POLLING_MAX_ATTEMPTS'      // Polling max attempts reached
  | 'POLLING_TIMEOUT'           // Polling overall timeout reached
  | 'POLLING_CANCELLED'         // Polling was cancelled
  
  // General
  | 'UNKNOWN_ERROR';            // Fallback for unclassified errors

2.1.3 Polling Service

  • API: startPolling<T>(options: PollingOptions<T>): PollingHandle.
  • Execution: Uses the exported httpClient (handles auth, retries, errors transparently).
  • Backoff: Configurable strategies (exponential default, linear, fibonacci, fixed) applied on polling request errors (using onError callback data). Includes jitter. Resets on success.
  • Termination: Configurable maxAttempts, pollingTimeout, terminateWhen callback. Clear TerminationReason enum.
  • Network Awareness: Uses INetworkInfo. Pauses polling if pauseWhenOffline: true (default). Resumes automatically.
  • Cancellation: PollingHandle.stop() uses AbortController signal passed to httpClient.
  • State: Updates OperationState.activePolls.
  • Callbacks: onSuccess, onError, onTerminate.

2.1.4 State Management (Internal)

  • Implementation: Internal Zustand store. Encapsulated.
  • State Shape (InternalState): Contains auth: AuthState, network: NetworkState, operations: OperationState slices. AuthState does not contain raw tokens.
  • Exposure: Via selective hooks: useAuthState(), useNetworkStatus(), useOperationState().

2.2 Non-Functional Requirements

  • Performance:
    • Targets remain: Refresh < 300ms, Interceptor < 5ms overhead.
    • Focus on minimal bundle size.
    • Efficient state updates.
  • Security:
    • Prioritize secure defaults (memory storage web, secure RN, PKCE enabled).
    • Secure handling of all token types and PKCE verifiers via IStorage.
    • Strong warnings and required config (encryptionKey) for web secure storage.
    • Adherence to OAuth2/OIDC security best practices.
    • Regular security reviews, especially of IStorage implementations and OAuth flows.
  • Testing & Documentation:
    • Testing:
      • Comprehensive unit/integration tests covering all authTypes, storage types, platform variations, refresh/queue logic, polling, error cases.
      • Specific security tests for storage encryption, OAuth vulnerabilities, XSS vectors.
    • Documentation: Crucial focus on:
      • Security trade-offs of storage options.
      • Setup Guides (including Mandatory RN native setup guide - deep linking, dependencies).
      • Configuration for each authType.
      • Usage Examples (Including using the hooks).
      • Web Storage Security Warnings
      • API reference.
      • Global error handling.
      • Troubleshooting.
  • Type Safety: Strict TypeScript. Comprehensive public types.
  • Internationalization: Support via StandardError.messageKey.
  • Logging: Basic internal, configurable logger redacting sensitive data.

3. API Contracts & Interface Definitions

// --- Core Configuration ---
export interface AuthConfig { /* As defined in Implementation Stage 4 */ }
export interface JWTConfig { /* As defined in Implementation Stage 4 */ }
export interface OAuth2ProviderConfig { /* As defined in Implementation Stage 4 */ }
export interface SessionConfig { /* As defined in Implementation Stage 4 */ }
export interface WebSpecificConfig { /* As defined in Implementation Stage 4 */ }
export interface ReactNativeSpecificConfig { /* As defined in Implementation Stage 4 */ }
export type StorageType = 'memory' | 'secure';

// --- Authentication ---
export interface IAuthenticationManager { /* As defined in Implementation Stage 4 */ }
export interface PasswordCredentials { /* As defined in Implementation Stage 4 */ }
export interface OAuthInitiateOptions { /* As defined in Implementation Stage 4 */ }
export interface LogoutOptions { /* As defined in Implementation Stage 4 */ }
export interface AuthResult { /* As defined in Implementation Stage 4 */ }

// --- State & Hooks ---
export interface AuthState { /* As defined in Implementation Stage 3 (State) - NO raw tokens */ }
export interface NetworkState { /* As defined in Implementation Stage 3 (State) */ }
export interface OperationState { /* As defined in Implementation Stage 3 (State) */ }
export declare function useAuthState(): AuthState;
export declare function useNetworkStatus(): NetworkState;
export declare function useOperationState(): OperationState;

// --- HTTP Client ---
export interface IHttpClient { /* As defined in Implementation Stage 5 */ }
export interface HttpClientRequestConfig extends AxiosRequestConfig { /* As defined in Implementation Stage 5 */ }
export interface StandardError extends Error { /* As defined in Implementation Stage 5 */ }
export type StandardErrorCode = /* As defined in Implementation Stage 5 */ ;

// --- Polling ---
export interface PollingOptions<T = any> { /* As defined in Implementation Stage 6 */ }
export interface PollingHandle { /* As defined in Implementation Stage 6 */ }
export type BackoffStrategyName = 'exponential' | 'linear' | 'fibonacci' | 'fixed';
export interface BackoffOptions { /* As defined in Implementation Stage 6 */ }
export enum TerminationReason { /* As defined in Implementation Stage 6 */ }
export declare function startPolling<T = any>(options: PollingOptions<T>): PollingHandle;

// --- Platform Abstraction (Internal Interfaces, not directly exported) ---
// export interface IStorage { /* As defined in Implementation Stage 2 */ }
// export interface INavigation { /* As defined in Implementation Stage 2 */ }
// export interface INetworkInfo { /* As defined in Implementation Stage 2 */ }
// export type ConnectionType = /* As defined in Implementation Stage 2 */ ;

// --- Main Package Exports ---
// Default export might be an object containing:
// - configure(config: AuthConfig): void;
// - httpClient: IHttpClient;
// - startPolling: <T = any>(options: PollingOptions<T>) => PollingHandle;
// - useAuthState: () => AuthState;
// - useNetworkStatus: () => NetworkState;
// - useOperationState: () => OperationState;
// - getAuthManager(): IAuthenticationManager; // Potentially for advanced direct access

4. Proposed Directory Structure

/react-api-kit
├── .github/                      # CI/CD, issue templates, etc.
│   └── workflows/
│       └── ci.yml
├── packages/                     # Workspace packages
│   └── core/                     # The core library package
│       ├── dist/                 # Build output (ignored by git)
│       ├── src/                  # Source code
│       │   ├── auth/             # Authentication module
│       │   │   ├── _internal/
│       │   │   │   └── httpRequester.ts # Internal HTTP client for auth calls
│       │   │   ├── jwt/
│       │   │   │   └── jwtHandler.ts
│       │   │   ├── oauth2/
│       │   │   │   ├── flows/
│       │   │   │   │   ├── authorizationCode.ts
│       │   │   │   │   ├── implicit.ts
│       │   │   │   │   └── pkce.ts
│       │   │   │   ├── oauth2Handler.ts
│       │   │   │   ├── oidcHandler.ts
│       │   │   │   └── oauthState.ts
│       │   │   ├── session/
│       │   │   │   └── sessionHandler.ts
│       │   │   ├── authConfig.ts     # Types: AuthConfig, JWTConfig, etc.
│       │   │   ├── authState.ts      # Types: AuthResult, AuthState
│       │   │   ├── authManager.ts    # IAuthenticationManager implementation
│       │   │   ├── tokenRefreshManager.ts
│       │   │   └── index.ts          # Exports for auth module
│       │   ├── http/             # HTTP Client module
│       │   │   ├── caching.ts
│       │   │   ├── deduplication.ts
│       │   │   ├── errorHandler.ts   # StandardError definition/logic
│       │   │   ├── httpClient.ts     # Axios wrapper instance creation
│       │   │   ├── interceptors.ts   # Request & Response interceptor logic
│       │   │   ├── requestQueue.ts
│       │   │   ├── retryHandler.ts
│       │   │   ├── types.ts          # HttpClientRequestConfig, StandardErrorCode list
│       │   │   └── index.ts          # Exports configured httpClient
│       │   ├── polling/          # Polling service module
│       │   │   ├── backoffStrategies.ts
│       │   │   ├── pollingService.ts # startPolling implementation
│       │   │   ├── terminationConditions.ts
│       │   │   ├── types.ts          # PollingOptions, PollingHandle, etc.
│       │   │   └── index.ts          # Exports startPolling
│       │   ├── state/            # Internal state management
│       │   │   ├── hooks.ts          # useAuthState, useNetworkStatus, etc.
│       │   │   ├── store.ts          # Zustand store definition
│       │   │   ├── types.ts          # InternalState slices (AuthState, etc.)
│       │   │   └── index.ts          # Exports hooks
│       │   ├── platform/         # Platform abstraction layer
│       │   │   ├── react-native/   # React Native specific implementations
│       │   │   │   ├── navigation.ts
│       │   │   │   ├── network.ts
│       │   │   │   └── storage.ts
│       │   │   ├── web/            # Web specific implementations
│       │   │   │   ├── navigation.ts
│       │   │   │   ├── network.ts
│       │   │   │   └── storage.ts
│       │   │   ├── manager.ts        # Platform detection and instance provider
│       │   │   ├── types.ts          # IStorage, INavigation, INetworkInfo interfaces
│       │   │   └── index.ts          # Exports manager/factory
│       │   ├── utils/            # Shared utility functions
│       │   │   ├── cryptoUtils.ts
│       │   │   ├── logger.ts
│       │   │   └── urlUtils.ts
│       │   ├── __tests__/        # Unit / Integration tests for core package
│       │   │   └── index.test.ts # Example test file
│       │   └── index.ts            # Main export entry point for the package
│       ├── package.json          # Core package manifest
│       ├── rollup.config.js      # Rollup build configuration for core package
│       └── tsconfig.json         # TypeScript configuration for core package
├── docs/                         # Project documentation (guides, API refs)
├── .gitignore                    # Git ignore rules
├── .prettierrc.js                # Prettier configuration
├── CHANGELOG.md                  # Log of changes per version
├── CODE_OF_CONDUCT.md            # Code of Conduct
├── CONTRIBUTING.md               # Contribution guidelines
├── LICENSE                       # Project license file (MIT)
├── eslint.config.js              # ESLint v9+ configuration (flat config)
├── package-lock.json             # NPM dependency lock file
├── package.json                  # Root project/workspace manifest
├── tsconfig.json                 # Root TypeScript configuration (base)
├── vitest.config.ts              # Vitest configuration
└── vitest.setup.ts               # Optional Vitest global setup file (e.g., for test helpers)
# Potential Future Additions:
# .npmignore                      # Used to control files included in npm publish (if needed)
# .nvmrc                          # To specify Node version for nvm users
# .lintstagedrc.js                # Config for lint-staged (pre-commit hooks)
# .husky/                         # Config for husky (pre-commit hooks)

5. Implementation Roadmap

  1. Stage 1: Project Setup and Configuration

    • Establish monorepo structure for @react-api-kit/core package
    • Configure base tooling (TypeScript, ESLint, Prettier, ViTest, Rollup)
    • Set up CI/CD pipeline (GitHub Actions)
    • Add core dependencies (axios, zustand) and peer dependencies
    • Milestone M1: Functioning monorepo with build process, testing framework, and linting configured
  2. Stage 2: Platform Abstraction Layer

    • Implement platform detection mechanism (PlatformManager)
    • Develop platform-specific implementations for:
      • IStorage: Memory and secure encrypted storage for Web/RN
      • INavigation: OAuth redirect handling for Web/RN
      • INetworkInfo: Network status detection for Web/RN
    • Create encryption utilities for web secure storage
    • Milestone M2: Complete platform abstraction with working implementations for both platforms
  3. Stage 3: Internal State Management

    • Implement internal Zustand store with defined state slices
    • Create selective React hooks for state consumption:
      • useAuthState
      • useNetworkStatus
      • useOperationState
    • Implement state reset functionality (for logout)
    • Milestone M3: Internal state management operational with working hooks
  4. Stage 4: Core Authentication & Token Management (Unified)

    • Implement AuthenticationManager supporting all authentication types
    • Create internal HTTP requester for auth-specific backend calls
    • Implement JWT token handling (login, validation, storage)
    • Integrate OAuth2/OIDC flows directly into core (Authorization Code+PKCE, Implicit)
    • Implement Server Session handling through status checks
    • Create unified token refresh manager with concurrency control
    • Integrate with platform abstraction and state management
    • Milestone M4: Complete authentication flows for all auth types, with secure storage and token refresh
  5. Stage 5: HTTP Client Integration

    • Develop main HTTP client (Axios wrapper)
    • Implement request/response interceptors for token attachment and refresh triggering
    • Create request queue for managing requests during token refresh
    • Implement standardized error handling with StandardError
    • Develop configurable retry strategy for transient errors
    • Add request cancellation support via AbortController
    • Add optional caching and request deduplication
    • Milestone M5: Fully functional HTTP client with authentication integration
  6. Stage 6: Polling Service Implementation

    • Implement startPolling function using HTTP client
    • Create configurable backoff strategies (exponential, linear, fibonacci, fixed)
    • Add termination conditions and cancellation support
    • Implement network awareness (pause when offline)
    • Integrate with operation state tracking
    • Milestone M6: Complete polling service with configurable options
  7. Testing, Documentation & Release

    • Write comprehensive unit and integration tests
    • Create thorough security tests for authentication flows
    • Develop detailed documentation:
      • API reference
      • Setup guides with platform-specific instructions
      • Security guidelines
      • Usage examples
    • Performance optimization and bundle size analysis
    • Final Milestone: Production-ready v1.0.0 release
  8. Release & Support Strategy:

    • Initial stable release (v1.0.0)
    • Establish regular release cadence (major versions every 6 months)
    • Define LTS (Long Term Support) policy (18 months support for each major version)
    • Implement automated regression testing for updates

6. Security Model Addendum: Storage

  • Strategies: The kit supports two primary storageType strategies:
    • memory: (Default for Web) Tokens/state stored in JS memory, lost on refresh. Most secure client-side web option.
    • secure: (Default for RN, Opt-in for Web) Uses the IStorage platform abstraction for persistent, encrypted storage.
  • Web secure Storage:
    • Uses localStorage with AES encryption via cryptoUtils.
    • Requires the developer to provide webSpecific.secureStorageEncryptionKey during configuration.
    • Documentation MUST strongly warn about the inherent risks of storing sensitive tokens in localStorage even with encryption, due to XSS vulnerabilities potentially compromising the key or encryption process. Recommend memory storage or server-side sessions (authType: 'session') for web production apps.
  • React Native secure Storage:
    • Uses native secure storage (Keychain/Keystore) via react-native-encrypted-storage or react-native-keychain (via optional peer dependencies). This is the recommended and default approach for RN.
  • No Complex Obfuscation: The kit focuses on standard encryption, not complex token splitting or debug detection heuristics.
  • Configuration: Controlled via storageType and webSpecific.secureStorageEncryptionKey in AuthConfig.

7. Conclusion

This specification defines a focused, robust, and secure React API Kit. By unifying authentication (JWT, OAuth2/OIDC, Session awareness), providing a resilient HTTP client, reliable polling, essential platform abstractions, and clear state exposure via hooks, it aims to significantly simplify common frontend development tasks for applications interacting with authenticated backends across Web and React Native platforms. Security is prioritized through careful defaults and clear documentation of risks and best practices.