-
Notifications
You must be signed in to change notification settings - Fork 0
React API Kit Specification
- 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
onErrorcallback for integrating with error reporting services.
-
Unified Authentication: Handle common authentication methods (
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"]
-
Direct Dependencies:
axios-
zustand(or similar lightweight state manager) - Potentially
crypto-js(for Websecurestorage encryption if Web Crypto API isn't sufficient/targeted).
-
Peer Dependencies:
react
-
Optional Peer Dependencies (React Native):
-
@react-native-community/netinfo: Recommended forINetworkInfo. -
react-native-encrypted-storageorreact-native-keychain: Recommended forsecureIStorage. -
react-native-linking: Required for deep linking if not usingreact-native-app-auth. -
react-native-app-auth: Recommended forINavigation(OAuth2) for best UX/security.
-
-
Versioning: Explicit minimum versions declared in
package.json. Adherence to SemVer. Treeshaking friendly (ESM primary, CJS fallback).
-
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 encryptedlocalStorage(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). Useswindow.location(Web) orreact-native-app-auth/Linking(RN). -
INetworkInfo: Abstracts network status (getCurrentState,subscribe). Usesnavigator.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.xmlconfiguration for deep links (OAuth callbacks). -
Crucial: Clear warnings about security risks of Web
securestorage (localStorage) and the developer's responsibility for providing and managing thesecureStorageEncryptionKeysecurely.
-
Crucial: Detailed documentation for RN native dependency installation, linking, and
-
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 ifstorageType: '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
httpClientto 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
InternalAuthErrortoStandardErrorbefore propagation
- Located at
-
JWT Handling (
authType: 'jwt'):- Acquisition via
loginEndpointusing internal HTTP requester. - Storage of access/refresh tokens via
IStorage(memoryorsecure). - Refresh via
refreshEndpointusing internal HTTP requester andTokenRefreshManager. - Token attachment via
httpClientinterceptor.
- Acquisition via
-
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 viaIStorage(securerecommended). -
State: CSRF protection via state param managed via
IStorage(session or secure, depending on overallstorageType). -
OIDC: Support
openidscope, parseid_token(basic validation: nonce, expiry), fetch fromuserinfoEndpointif configured. Store claims inAuthState.userInfo. -
Redirects: Use
INavigation.initiateRedirectandINavigation.listenForRedirect. -
Token Exchange: Use internal HTTP requester to call backend
tokenEndpoint(code+verifier -> tokens). -
Storage: Store tokens via
IStorage. -
Refresh: Use
refresh_tokengrant via internal HTTP requester andTokenRefreshManager. -
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/callsloginEndpoint. -
logout()callslogoutEndpoint. -
isAuthenticated()callscheckStatusEndpointusing mainhttpClient(to include cookies). Debounced/cached result. -
getToken()returnsnull.refreshToken()does nothing/rejects. - Instructs
httpClientto usewithCredentials: trueand skip token attachment. 401s updateAuthState.
-
Common:
-
Concurrency:
TokenRefreshManagerensures only one refresh attempt (JWT or OAuth2) happens at a time. -
Storage: All sensitive data (tokens, verifiers, state) managed via
IStorage. -
State:
AuthStateupdated internally, exposed viauseAuthState(). Raw tokens not included inAuthState. -
Logout: Clears
IStorage, resetsAuthState, calls relevant session endpoint if configured. -
Error Handling: Maps internal auth errors (including
InternalAuthErrorfrom internal requests) toStandardError. Calls globalonErrorhook. UpdatesAuthState.error.
-
Concurrency:
-
Axios Wrapper (
httpClient): Exported configured instance. -
Interceptors:
- Request: Checks
authType. AttachesAuthorization: Bearer token(if JWT/OAuth2 &requireAuth: true). SetswithCredentials: true(if Session). HandlesAbortSignal. UpdatesOperationState.pendingRequests. - Response: Detects 401/403 -> triggers
AuthenticationManager._triggerRefresh()(if JWT/OAuth2 & notskipRefresh) -> interacts withRequestQueue. Detects transient errors -> triggersRetryHandler. Maps errors toStandardError-> calls globalonError. UpdatesOperationState.pendingRequests.
- Request: Checks
- 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-Afterheader if present. -
Cancellation: Pass
AbortController.signalinHttpClientRequestConfig. Cancels in-flight or queued requests. Returns specificStandardError(REQUEST_CANCELLED). -
Optional Features (Default Off):
-
Caching: In-memory cache for GET. Configurable TTL/invalidation via
clearCache()andforceRefreshconfig. - Deduplication: Prevent identical concurrent GET requests.
-
Caching: In-memory cache for GET. Configurable TTL/invalidation via
-
Error Handling: Centralized mapping to
StandardErrorviaErrorHandler. - 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-
API:
startPolling<T>(options: PollingOptions<T>): PollingHandle. -
Execution: Uses the exported
httpClient(handles auth, retries, errors transparently). -
Backoff: Configurable strategies (
exponentialdefault,linear,fibonacci,fixed) applied on polling request errors (usingonErrorcallback data). Includes jitter. Resets on success. -
Termination: Configurable
maxAttempts,pollingTimeout,terminateWhencallback. ClearTerminationReasonenum. -
Network Awareness: Uses
INetworkInfo. Pauses polling ifpauseWhenOffline: true(default). Resumes automatically. -
Cancellation:
PollingHandle.stop()usesAbortControllersignal passed tohttpClient. -
State: Updates
OperationState.activePolls. -
Callbacks:
onSuccess,onError,onTerminate.
- Implementation: Internal Zustand store. Encapsulated.
-
State Shape (
InternalState): Containsauth: AuthState,network: NetworkState,operations: OperationStateslices.AuthStatedoes not contain raw tokens. -
Exposure: Via selective hooks:
useAuthState(),useNetworkStatus(),useOperationState().
-
Performance:
- Targets remain: Refresh < 300ms, Interceptor < 5ms overhead.
- Focus on minimal bundle size.
- Efficient state updates.
-
Security:
- Prioritize secure defaults (
memorystorage web,secureRN, PKCE enabled). - Secure handling of all token types and PKCE verifiers via
IStorage. - Strong warnings and required config (
encryptionKey) for websecurestorage. - Adherence to OAuth2/OIDC security best practices.
- Regular security reviews, especially of
IStorageimplementations and OAuth flows.
- Prioritize secure defaults (
-
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.
- Comprehensive unit/integration tests covering all
-
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.
-
Testing:
- Type Safety: Strict TypeScript. Comprehensive public types.
-
Internationalization: Support via
StandardError.messageKey. - Logging: Basic internal, configurable logger redacting sensitive data.
// --- 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/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)
-
Stage 1: Project Setup and Configuration
- Establish monorepo structure for
@react-api-kit/corepackage - 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
- Establish monorepo structure for
-
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
- Implement platform detection mechanism (
-
Stage 3: Internal State Management
- Implement internal Zustand store with defined state slices
- Create selective React hooks for state consumption:
useAuthStateuseNetworkStatususeOperationState
- Implement state reset functionality (for logout)
- Milestone M3: Internal state management operational with working hooks
-
Stage 4: Core Authentication & Token Management (Unified)
- Implement
AuthenticationManagersupporting 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
- Implement
-
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
-
Stage 6: Polling Service Implementation
- Implement
startPollingfunction 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
- Implement
-
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
-
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
-
Strategies: The kit supports two primary
storageTypestrategies:-
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 theIStorageplatform abstraction for persistent, encrypted storage.
-
-
Web
secureStorage:- Uses
localStoragewith AES encryption viacryptoUtils. -
Requires the developer to provide
webSpecific.secureStorageEncryptionKeyduring configuration. -
Documentation MUST strongly warn about the inherent risks of storing sensitive tokens in
localStorageeven with encryption, due to XSS vulnerabilities potentially compromising the key or encryption process. Recommendmemorystorage or server-side sessions (authType: 'session') for web production apps.
- Uses
-
React Native
secureStorage:- Uses native secure storage (Keychain/Keystore) via
react-native-encrypted-storageorreact-native-keychain(via optional peer dependencies). This is the recommended and default approach for RN.
- Uses native secure storage (Keychain/Keystore) via
- No Complex Obfuscation: The kit focuses on standard encryption, not complex token splitting or debug detection heuristics.
-
Configuration: Controlled via
storageTypeandwebSpecific.secureStorageEncryptionKeyinAuthConfig.
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.