UNPKG

@juspay/neurolink

Version:

The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002

339 lines (338 loc) • 13.3 kB
/** * NeuroLink OAuth Token Store * * Secure storage for OAuth tokens with encoding support and multi-provider capability. * Stores tokens in the user's home directory with restrictive permissions. * * Features: * - Multi-provider token storage in a single tokens.json file * - Secure file storage with 0o600 permissions * - Token expiration checking with configurable buffer * - Simple XOR-based obfuscation (not encryption, but not plaintext) * - Automatic token refresh via configurable refresher functions * - Cross-platform support (Unix/macOS/Windows) */ import type { TokenStorageData, StoredOAuthTokens, TokenRefresher } from "../types/index.js"; /** * Secure token storage for OAuth tokens with multi-provider support * * Provides persistent storage for OAuth tokens with: * - Multi-provider support in a single file * - Secure file permissions (0o600) * - Optional obfuscation/encoding * - Token expiration checking with buffer * - Automatic token refresh via configurable refreshers * * @example * ```typescript * const store = new TokenStore(); * * // Save tokens for a provider * await store.saveTokens("anthropic", { * accessToken: "sk-...", * refreshToken: "rt-...", * expiresAt: Date.now() + 3600000, * tokenType: "Bearer", * }); * * // Set up automatic refresh * store.setTokenRefresher("anthropic", async (refreshToken) => { * // Call OAuth refresh endpoint * return newTokens; * }); * * // Get a valid token (auto-refreshes if needed) * const token = await store.getValidToken("anthropic"); * ``` */ export declare class TokenStore { private static readonly STORAGE_VERSION; private static readonly NEUROLINK_DIR; private static readonly TOKEN_FILE; private static readonly FILE_PERMISSIONS; /** Default expiration buffer: 1 hour (proactive refresh before actual expiry) */ private static readonly DEFAULT_EXPIRY_BUFFER_MS; private readonly storagePath; private readonly encryptionEnabled; private readonly encryptionKey; private readonly encryptionKeyBytes; private readonly tokenRefreshers; private readonly inFlightRefreshes; private readonly _mutex; private snapshotRead; /** * Creates a new TokenStore instance * * @param options - Configuration options * @param options.encryptionEnabled - Whether to enable token obfuscation (default: true) * @param options.customStoragePath - Override the default storage path */ constructor(options?: { encryptionEnabled?: boolean; customStoragePath?: string; }); /** * Gets the path where tokens are stored * * @returns The absolute path to the token storage file */ getStoragePath(): string; /** * Saves OAuth tokens for a specific provider * * @param provider - The provider name (e.g., "anthropic", "openai") * @param tokens - The OAuth tokens to save * @throws TokenStoreError if storage fails */ saveTokens(provider: string, tokens: StoredOAuthTokens): Promise<void>; /** * Saves tokens only when `guard` approves the provider inventory read under * the same cross-process lock as the write (compare-and-set). The guard may * throw to refuse with a specific error. Returns false when it declines. * * @param options.enable - Also clear the disabled flag, as a fresh login does. */ saveTokensIf(provider: string, tokens: StoredOAuthTokens, guard: (providers: TokenStorageData["providers"]) => boolean, options?: { enable?: boolean; }): Promise<boolean>; /** * Internal save without mutex — callers must already hold the mutex. */ private _saveTokensInternal; /** * Loads stored OAuth tokens for a specific provider * * @param provider - The provider name (e.g., "anthropic", "openai") * @returns The stored tokens, or null if not found * @throws TokenStoreError if reading fails (other than file not found) */ loadTokens(provider: string): Promise<StoredOAuthTokens | null>; /** Reads tokens without updating access metadata or rewriting the store. */ peekTokens(provider: string): Promise<StoredOAuthTokens | null>; /** * Read one coherent account inventory without updating access timestamps. * Concurrent readers share only the in-flight read, never a TTL cache, so * the next request observes account edits made by another process. Each * caller receives its own copy, including disabled state and credentials. */ getProviderSnapshot(): Promise<TokenStorageData["providers"]>; /** * Internal load without mutex — callers must already hold the mutex. */ private _loadTokensInternal; /** * Clears stored tokens for a specific provider * * @param provider - The provider name (e.g., "anthropic", "openai") * @throws TokenStoreError if deletion fails */ clearTokens(provider: string): Promise<void>; private _clearTokensImpl; /** * Checks if the given tokens are expired * * @param tokens - The OAuth tokens to check * @param bufferMs - Buffer time in milliseconds before actual expiration (default: 5 minutes) * @returns true if token is expired or will expire within buffer time */ isTokenExpired(tokens: StoredOAuthTokens, bufferMs?: number): boolean; /** * Gets a valid access token for a provider, refreshing if needed * * If the stored token is expired or about to expire, and a refresher * function has been set, it will automatically refresh the token. * * @param provider - The provider name (e.g., "anthropic", "openai") * @returns The valid access token, or null if not available * @throws TokenStoreError if refresh fails */ getValidToken(provider: string): Promise<string | null>; private _getValidTokenImpl; /** * Sets the token refresher function for a provider * * The refresher function will be called automatically when getValidToken * detects that the stored token is expired or about to expire. * * @param provider - The provider name (e.g., "anthropic", "openai") * @param refresher - Function that takes a refresh token and returns new tokens */ setTokenRefresher(provider: string, refresher: TokenRefresher): void; /** * Removes the token refresher function for a provider * * @param provider - The provider name (e.g., "anthropic", "openai") */ clearTokenRefresher(provider: string): void; /** * Checks if tokens exist for a specific provider * * @param provider - The provider name (e.g., "anthropic", "openai") * @returns true if tokens are stored for the provider */ hasTokens(provider: string): Promise<boolean>; /** * Lists all providers that have stored tokens * * @returns Array of provider names */ listProviders(): Promise<string[]>; /** * Lists all provider keys that start with the given prefix * * @param prefix - The prefix to filter by (e.g., "anthropic:") * @returns Array of matching provider keys */ listByPrefix(prefix: string): Promise<string[]>; /** * Marks a provider's tokens as permanently disabled (persisted to disk). * * Disabled accounts are skipped immediately by consumers — no wasted * round-trips. The state survives proxy restarts because it is stored * alongside the tokens in the JSON file. * * This operation and saveTokens() share the instance mutex. A concurrent * save cannot erase a disable: a later disable wins, while a later save * preserves the existing disabled metadata. * * @param provider - The provider key (e.g., "anthropic:user@example.com") * @param reason - Optional human-readable reason (e.g., "refresh_failed") */ markDisabled(provider: string, reason?: string): Promise<void>; /** * Disables an account only when the persisted credentials still match the * request that observed the authentication failure. */ markDisabledIfCurrent(provider: string, expectedTokens: Pick<StoredOAuthTokens, "accessToken" | "refreshToken" | "expiresAt">, reason?: string): Promise<boolean>; /** * Re-enables a previously disabled provider (persisted to disk). * * Clears the disabled flag, timestamp, and reason so the account can * be used again by the proxy pool. * * @param provider - The provider key (e.g., "anthropic:user@example.com") */ markEnabled(provider: string): Promise<void>; /** * Checks whether a provider's tokens are currently disabled. * * Returns false for providers that don't exist in the store (no tokens * at all) and for entries that predate the disabled field (backward compat). * * @param provider - The provider key * @returns true if the provider entry exists and is disabled */ isDisabled(provider: string): Promise<boolean>; /** Return the persisted disable reason, if the provider is disabled. */ getDisabledReason(provider: string): Promise<string | undefined>; /** * Lists all provider keys that are currently disabled. * * @returns Array of disabled provider keys (empty if none or no storage file) */ listDisabled(): Promise<string[]>; /** * Removes expired and unrefreshable token entries from disk. * * An entry is pruned when: * - Its access token is expired (with optional buffer) AND it has no * refresh token, AND it is NOT manually disabled. * * Manually disabled entries are preserved so that `auth enable` can * re-enable them later. They are only removed via explicit `clearTokens`. * * @param bufferMs - Extra buffer in milliseconds to subtract from expiresAt * when checking expiry (default: 0 — strict expiry check) * @returns Array of provider keys that were removed */ pruneExpired(bufferMs?: number): Promise<string[]>; /** * Clears all stored tokens for all providers * * @throws TokenStoreError if deletion fails */ clearAllTokens(): Promise<void>; /** * Loads the storage data from file */ private loadStorageData; /** Parse plain-JSON storage; null when it is not a usable store. */ private parseStorageJson; /** * Decode a store written by either codec. * * The current codec is prefixed and XORs UTF-8 bytes. The older one XORed * UTF-16 code units and then truncated each to a byte, so a store holding a * single non-Latin-1 character (an emoji in a label, a smart quote in a * disable reason) could never be read back. Older files carry no prefix and * are read the old way; the next save rewrites them with the new codec. */ private parseObfuscatedStorage; private quarantineStorageFile; /** * Saves storage data to file */ private saveStorageData; /** * Serialize and write the store: owner-only from creation, under an * unpredictable temp name, renamed into place. See `secureFiles`. */ private writeStorageFile; /** * Take the in-process mutex, then the cross-process file lock, around a * read-modify-write. The CLI and a running proxy share one file; without * the second lock a stale snapshot written late reverted the other's * rotated refresh token or disable flag. */ private runExclusiveLocked; private get lockPath(); private readLockOwner; private removeAbandonedLock; /** * Best-effort cross-process lock. When another process holds it past the * timeout the write proceeds anyway with a warning: a stuck lock must not * take the pool offline, which is worse than the race it guards against. */ private acquireFileLock; /** * Deletes the storage file */ private deleteStorageFile; /** * Validates token structure */ private validateTokens; /** * Ensures the storage directory exists with proper permissions */ private ensureDirectory; /** * Derives an encoding key from machine-specific information * This provides basic obfuscation - for production use, consider * using proper encryption with a user-provided key or system keychain */ private deriveEncryptionKey; private deriveEncryptionKeyBytes; /** * XOR obfuscation over the UTF-8 bytes of the document, base64-encoded and * prefixed so a reader can tell it from the older code-unit codec. * Note: this is NOT cryptographically secure, just basic obfuscation. */ private obfuscate; private deobfuscateV2; /** * The pre-UTF-8 codec, kept only to read stores written before it existed. * It cannot round-trip any character above U+00FF. */ private deobfuscateLegacy; } /** * Default token store singleton instance * Uses default configuration with encryption enabled */ export declare const tokenStore: TokenStore; /** * Alias for backward compatibility * @deprecated Use tokenStore instead */ export declare const defaultTokenStore: TokenStore;