appwrite-utils-cli
Version:
Appwrite Utility Functions to help with database management, data conversion, data import, migrations, and much more. Meant to be used as a CLI tool, I do not recommend installing this in frontend environments.
226 lines (225 loc) • 7.33 kB
TypeScript
/**
* Session preferences stored in ~/.appwrite/prefs.json
*/
export interface AppwriteSessionPrefs {
[projectId: string]: {
endpoint: string;
email: string;
cookie: string;
expiresAt?: string;
};
}
/**
* Session authentication information for a specific endpoint and project
*/
export interface SessionAuthInfo {
endpoint: string;
projectId: string;
email?: string;
cookie: string;
expiresAt?: string;
}
/**
* Authentication status information
*/
export interface AuthenticationStatus {
hasValidSession: boolean;
hasApiKey: boolean;
sessionExists: boolean;
endpointMatches: boolean;
cookieValid: boolean;
sessionInfo?: SessionAuthInfo;
message: string;
authMethod?: "session" | "apikey" | "none";
}
/**
* Service for managing Appwrite CLI session authentication with intelligent caching
*
* This service provides centralized session management with minimal file I/O through
* a multi-layered caching strategy:
* - Time-based cache (5 minute TTL)
* - File modification time validation
* - Content hash validation
*
* @example
* ```typescript
* const sessionService = new SessionAuthService();
* const session = await sessionService.findSession("https://cloud.appwrite.io/v1", "my-project-id");
*
* if (session && sessionService.isValidSession(session)) {
* // Use session for authentication
* console.log(`Authenticated as ${session.email}`);
* }
* ```
*/
export declare class SessionAuthService {
private cache;
private readonly CACHE_TTL;
private readonly PREFS_PATH;
/**
* Creates a new SessionAuthService instance
*
* @param prefsPath - Optional custom path to prefs.json (defaults to ~/.appwrite/prefs.json)
*/
constructor(prefsPath?: string);
/**
* Load session preferences from ~/.appwrite/prefs.json with intelligent caching
*
* Caching Strategy:
* 1. Return cached data if TTL has not expired
* 2. Validate file modification time - reload if changed
* 3. Validate content hash - reload if content changed
* 4. Cache is automatically invalidated after 5 minutes
*
* @returns Session preferences object or null if file doesn't exist or is invalid
*
* @example
* ```typescript
* const prefs = await sessionService.loadSessionPrefs();
* if (prefs) {
* console.log(`Found ${Object.keys(prefs).length} stored sessions`);
* }
* ```
*/
loadSessionPrefs(): Promise<AppwriteSessionPrefs | null>;
/**
* Find session authentication info for a specific endpoint and project
*
* This method searches the session preferences for a matching endpoint and project ID.
* Both endpoint and projectId must match for a session to be returned.
*
* @param endpoint - Appwrite endpoint URL (e.g., "https://cloud.appwrite.io/v1")
* @param projectId - Appwrite project ID
* @returns Session info or null if no matching session found
*
* @example
* ```typescript
* const session = await sessionService.findSession(
* "https://cloud.appwrite.io/v1",
* "my-project-id"
* );
*
* if (session) {
* console.log(`Using session for ${session.email}`);
* }
* ```
*/
findSession(endpoint: string, projectId: string): Promise<SessionAuthInfo | null>;
/**
* Validate if a session appears to be valid
*
* Performs structural validation of the session:
* - Cookie format validation (JWT-like structure)
* - Expiration check (if expiresAt is provided)
* - Basic cookie integrity checks
*
* Note: This does NOT verify the session with the server.
*
* @param session - Session info to validate
* @returns true if session appears valid, false otherwise
*
* @example
* ```typescript
* const session = await sessionService.findSession(endpoint, projectId);
* if (session && sessionService.isValidSession(session)) {
* // Session is structurally valid
* }
* ```
*/
isValidSession(session: SessionAuthInfo): boolean;
/**
* Get detailed authentication status for a given endpoint and project
*
* Provides comprehensive authentication status including:
* - Session validation
* - API key presence
* - Detailed diagnostic information
* - Actionable error messages
*
* @param endpoint - Appwrite endpoint URL
* @param projectId - Appwrite project ID
* @param apiKey - Optional API key for authentication
* @param session - Optional pre-loaded session (avoids re-loading)
* @returns Detailed authentication status
*
* @example
* ```typescript
* const status = await sessionService.getAuthenticationStatus(
* "https://cloud.appwrite.io/v1",
* "my-project-id",
* process.env.APPWRITE_API_KEY
* );
*
* console.log(status.message);
* if (status.hasValidSession) {
* console.log(`Authenticated as ${status.sessionInfo?.email}`);
* } else if (status.hasApiKey) {
* console.log("Using API key authentication");
* }
* ```
*/
getAuthenticationStatus(endpoint: string, projectId: string, apiKey?: string, session?: SessionAuthInfo | null): Promise<AuthenticationStatus>;
/**
* Manually invalidate the cache
*
* Forces the next loadSessionPrefs() call to read from disk.
* Useful after external changes to prefs.json (e.g., after login/logout).
*
* @example
* ```typescript
* // After user logs in
* sessionService.invalidateCache();
* const newSession = await sessionService.loadSessionPrefs();
* ```
*/
invalidateCache(): void;
/**
* Normalize an endpoint URL for comparison
*
* @param url - Endpoint URL to normalize
* @returns Normalized URL (lowercase, no trailing slashes)
*/
private normalizeEndpoint;
/**
* Validate session cookie format
*
* Performs basic validation to check if a cookie appears to be a valid Appwrite session:
* - Minimum length check
* - JWT-like structure (contains dots)
* - Valid character set
* - Multi-part structure
*
* @param cookie - Cookie string to validate
* @returns true if cookie appears valid, false otherwise
*/
private isValidSessionCookie;
/**
* Generate MD5 hash of content for cache validation
*
* @param content - Content to hash
* @returns MD5 hash as hex string
*/
private hashContent;
/**
* Get all available sessions from prefs
*
* Returns all sessions stored in the preferences file that pass
* basic validation checks.
*
* @returns Array of valid session info objects
*
* @example
* ```typescript
* const sessions = await sessionService.getAvailableSessions();
* console.log(`Found ${sessions.length} available sessions`);
* sessions.forEach(s => console.log(` - ${s.projectId} (${s.email})`));
* ```
*/
getAvailableSessions(): Promise<SessionAuthInfo[]>;
/**
* Get the path to the prefs.json file
*
* @returns Absolute path to prefs.json
*/
getPrefsPath(): string;
}