appwrite-utils-cli 1.6.3 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CONFIG_TODO.md +1189 -0
  2. package/SERVICE_IMPLEMENTATION_REPORT.md +462 -0
  3. package/dist/cli/commands/configCommands.js +7 -1
  4. package/dist/collections/attributes.js +102 -30
  5. package/dist/collections/indexes.js +6 -1
  6. package/dist/collections/methods.js +4 -5
  7. package/dist/config/ConfigManager.d.ts +445 -0
  8. package/dist/config/ConfigManager.js +625 -0
  9. package/dist/config/index.d.ts +8 -0
  10. package/dist/config/index.js +7 -0
  11. package/dist/config/services/ConfigDiscoveryService.d.ts +126 -0
  12. package/dist/config/services/ConfigDiscoveryService.js +374 -0
  13. package/dist/config/services/ConfigLoaderService.d.ts +105 -0
  14. package/dist/config/services/ConfigLoaderService.js +410 -0
  15. package/dist/config/services/ConfigMergeService.d.ts +208 -0
  16. package/dist/config/services/ConfigMergeService.js +307 -0
  17. package/dist/config/services/ConfigValidationService.d.ts +214 -0
  18. package/dist/config/services/ConfigValidationService.js +310 -0
  19. package/dist/config/services/SessionAuthService.d.ts +225 -0
  20. package/dist/config/services/SessionAuthService.js +456 -0
  21. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +1 -0
  22. package/dist/config/services/__tests__/ConfigMergeService.test.js +271 -0
  23. package/dist/config/services/index.d.ts +13 -0
  24. package/dist/config/services/index.js +10 -0
  25. package/dist/interactiveCLI.js +8 -6
  26. package/dist/main.js +14 -19
  27. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +1 -1
  28. package/dist/shared/operationQueue.js +1 -1
  29. package/dist/utils/ClientFactory.d.ts +87 -0
  30. package/dist/utils/ClientFactory.js +164 -0
  31. package/dist/utils/getClientFromConfig.js +4 -3
  32. package/dist/utils/helperFunctions.d.ts +1 -0
  33. package/dist/utils/helperFunctions.js +21 -5
  34. package/dist/utils/yamlConverter.d.ts +2 -2
  35. package/dist/utils/yamlConverter.js +2 -2
  36. package/dist/utilsController.d.ts +18 -15
  37. package/dist/utilsController.js +83 -131
  38. package/package.json +1 -1
  39. package/src/cli/commands/configCommands.ts +8 -1
  40. package/src/collections/attributes.ts +118 -31
  41. package/src/collections/indexes.ts +7 -1
  42. package/src/collections/methods.ts +4 -6
  43. package/src/config/ConfigManager.ts +808 -0
  44. package/src/config/index.ts +10 -0
  45. package/src/config/services/ConfigDiscoveryService.ts +463 -0
  46. package/src/config/services/ConfigLoaderService.ts +560 -0
  47. package/src/config/services/ConfigMergeService.ts +386 -0
  48. package/src/config/services/ConfigValidationService.ts +394 -0
  49. package/src/config/services/SessionAuthService.ts +565 -0
  50. package/src/config/services/__tests__/ConfigMergeService.test.ts +351 -0
  51. package/src/config/services/index.ts +29 -0
  52. package/src/interactiveCLI.ts +9 -7
  53. package/src/main.ts +14 -24
  54. package/src/shared/operationQueue.ts +1 -1
  55. package/src/utils/ClientFactory.ts +186 -0
  56. package/src/utils/getClientFromConfig.ts +4 -3
  57. package/src/utils/helperFunctions.ts +27 -7
  58. package/src/utils/yamlConverter.ts +4 -4
  59. package/src/utilsController.ts +99 -187
@@ -0,0 +1,565 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { createHash } from "node:crypto";
5
+ import { MessageFormatter } from "../../shared/messageFormatter.js";
6
+ import { logger } from "../../shared/logging.js";
7
+
8
+ /**
9
+ * Session preferences stored in ~/.appwrite/prefs.json
10
+ */
11
+ export interface AppwriteSessionPrefs {
12
+ [projectId: string]: {
13
+ endpoint: string;
14
+ email: string;
15
+ cookie: string;
16
+ expiresAt?: string;
17
+ };
18
+ }
19
+
20
+ /**
21
+ * Session authentication information for a specific endpoint and project
22
+ */
23
+ export interface SessionAuthInfo {
24
+ endpoint: string;
25
+ projectId: string;
26
+ email?: string;
27
+ cookie: string;
28
+ expiresAt?: string;
29
+ }
30
+
31
+ /**
32
+ * Authentication status information
33
+ */
34
+ export interface AuthenticationStatus {
35
+ hasValidSession: boolean;
36
+ hasApiKey: boolean;
37
+ sessionExists: boolean;
38
+ endpointMatches: boolean;
39
+ cookieValid: boolean;
40
+ sessionInfo?: SessionAuthInfo;
41
+ message: string;
42
+ authMethod?: "session" | "apikey" | "none";
43
+ }
44
+
45
+ /**
46
+ * Internal cache structure for session preferences
47
+ */
48
+ interface SessionCache {
49
+ data: AppwriteSessionPrefs | null;
50
+ mtime: number;
51
+ contentHash: string;
52
+ timestamp: number;
53
+ }
54
+
55
+ /**
56
+ * Service for managing Appwrite CLI session authentication with intelligent caching
57
+ *
58
+ * This service provides centralized session management with minimal file I/O through
59
+ * a multi-layered caching strategy:
60
+ * - Time-based cache (5 minute TTL)
61
+ * - File modification time validation
62
+ * - Content hash validation
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const sessionService = new SessionAuthService();
67
+ * const session = await sessionService.findSession("https://cloud.appwrite.io/v1", "my-project-id");
68
+ *
69
+ * if (session && sessionService.isValidSession(session)) {
70
+ * // Use session for authentication
71
+ * console.log(`Authenticated as ${session.email}`);
72
+ * }
73
+ * ```
74
+ */
75
+ export class SessionAuthService {
76
+ private cache: SessionCache | null = null;
77
+ private readonly CACHE_TTL = 5 * 60 * 1000; // 5 minutes
78
+ private readonly PREFS_PATH: string;
79
+
80
+ /**
81
+ * Creates a new SessionAuthService instance
82
+ *
83
+ * @param prefsPath - Optional custom path to prefs.json (defaults to ~/.appwrite/prefs.json)
84
+ */
85
+ constructor(prefsPath?: string) {
86
+ this.PREFS_PATH = prefsPath || join(homedir(), ".appwrite", "prefs.json");
87
+ }
88
+
89
+ /**
90
+ * Load session preferences from ~/.appwrite/prefs.json with intelligent caching
91
+ *
92
+ * Caching Strategy:
93
+ * 1. Return cached data if TTL has not expired
94
+ * 2. Validate file modification time - reload if changed
95
+ * 3. Validate content hash - reload if content changed
96
+ * 4. Cache is automatically invalidated after 5 minutes
97
+ *
98
+ * @returns Session preferences object or null if file doesn't exist or is invalid
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const prefs = await sessionService.loadSessionPrefs();
103
+ * if (prefs) {
104
+ * console.log(`Found ${Object.keys(prefs).length} stored sessions`);
105
+ * }
106
+ * ```
107
+ */
108
+ public async loadSessionPrefs(): Promise<AppwriteSessionPrefs | null> {
109
+ try {
110
+ // Check if file exists
111
+ if (!existsSync(this.PREFS_PATH)) {
112
+ logger.debug("Session prefs file does not exist", { path: this.PREFS_PATH });
113
+ return null;
114
+ }
115
+
116
+ // Get current file stats
117
+ const stats = statSync(this.PREFS_PATH);
118
+ const currentMtime = stats.mtimeMs;
119
+ const now = Date.now();
120
+
121
+ // Check if cache is valid
122
+ if (this.cache) {
123
+ const cacheAge = now - this.cache.timestamp;
124
+ const mtimeMatches = this.cache.mtime === currentMtime;
125
+ const cacheNotExpired = cacheAge < this.CACHE_TTL;
126
+
127
+ // If cache is still valid (not expired, mtime unchanged)
128
+ if (cacheNotExpired && mtimeMatches) {
129
+ logger.debug("Using cached session prefs (valid cache)", {
130
+ cacheAge: `${Math.round(cacheAge / 1000)}s`,
131
+ ttl: `${this.CACHE_TTL / 1000}s`
132
+ });
133
+ return this.cache.data;
134
+ }
135
+
136
+ // If TTL expired or mtime changed, we need to validate content
137
+ if (!cacheNotExpired) {
138
+ logger.debug("Session cache TTL expired, revalidating", {
139
+ cacheAge: `${Math.round(cacheAge / 1000)}s`
140
+ });
141
+ } else if (!mtimeMatches) {
142
+ logger.debug("Session file modified, revalidating", {
143
+ oldMtime: this.cache.mtime,
144
+ newMtime: currentMtime
145
+ });
146
+ }
147
+ }
148
+
149
+ // Read and parse file
150
+ const prefsContent = readFileSync(this.PREFS_PATH, "utf-8");
151
+ const contentHash = this.hashContent(prefsContent);
152
+
153
+ // Check if content actually changed (even if mtime changed)
154
+ if (this.cache && this.cache.contentHash === contentHash) {
155
+ logger.debug("Session file content unchanged, updating cache timestamp");
156
+ this.cache.timestamp = now;
157
+ this.cache.mtime = currentMtime;
158
+ return this.cache.data;
159
+ }
160
+
161
+ // Parse new content
162
+ const prefs = JSON.parse(prefsContent) as AppwriteSessionPrefs;
163
+
164
+ // Update cache
165
+ this.cache = {
166
+ data: prefs,
167
+ mtime: currentMtime,
168
+ contentHash,
169
+ timestamp: now
170
+ };
171
+
172
+ logger.debug("Session prefs loaded and cached", {
173
+ projectCount: Object.keys(prefs).length,
174
+ path: this.PREFS_PATH
175
+ });
176
+
177
+ return prefs;
178
+ } catch (error) {
179
+ MessageFormatter.warning(
180
+ "Failed to load Appwrite session preferences",
181
+ { prefix: "Session" }
182
+ );
183
+ logger.error("Error loading session prefs", {
184
+ error: error instanceof Error ? error.message : String(error),
185
+ path: this.PREFS_PATH
186
+ });
187
+ return null;
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Find session authentication info for a specific endpoint and project
193
+ *
194
+ * This method searches the session preferences for a matching endpoint and project ID.
195
+ * Both endpoint and projectId must match for a session to be returned.
196
+ *
197
+ * @param endpoint - Appwrite endpoint URL (e.g., "https://cloud.appwrite.io/v1")
198
+ * @param projectId - Appwrite project ID
199
+ * @returns Session info or null if no matching session found
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const session = await sessionService.findSession(
204
+ * "https://cloud.appwrite.io/v1",
205
+ * "my-project-id"
206
+ * );
207
+ *
208
+ * if (session) {
209
+ * console.log(`Using session for ${session.email}`);
210
+ * }
211
+ * ```
212
+ */
213
+ public async findSession(
214
+ endpoint: string,
215
+ projectId: string
216
+ ): Promise<SessionAuthInfo | null> {
217
+ const prefs = await this.loadSessionPrefs();
218
+
219
+ if (!prefs || !prefs[projectId]) {
220
+ logger.debug("No session found for project", { projectId });
221
+ return null;
222
+ }
223
+
224
+ const sessionData = prefs[projectId];
225
+
226
+ // Validate session data structure
227
+ if (!sessionData.endpoint || !sessionData.cookie) {
228
+ MessageFormatter.warning(
229
+ `Invalid session data for project ${projectId}`,
230
+ { prefix: "Session" }
231
+ );
232
+ logger.warn("Invalid session data structure", {
233
+ projectId,
234
+ hasEndpoint: !!sessionData.endpoint,
235
+ hasCookie: !!sessionData.cookie
236
+ });
237
+ return null;
238
+ }
239
+
240
+ // Normalize endpoints for comparison (remove trailing slashes, case-insensitive)
241
+ const normalizedSessionEndpoint = this.normalizeEndpoint(sessionData.endpoint);
242
+ const normalizedRequestEndpoint = this.normalizeEndpoint(endpoint);
243
+
244
+ if (normalizedSessionEndpoint !== normalizedRequestEndpoint) {
245
+ logger.debug("Session endpoint mismatch", {
246
+ projectId,
247
+ sessionEndpoint: sessionData.endpoint,
248
+ requestedEndpoint: endpoint
249
+ });
250
+ return null;
251
+ }
252
+
253
+ // Return session info
254
+ return {
255
+ endpoint: sessionData.endpoint,
256
+ projectId,
257
+ email: sessionData.email,
258
+ cookie: sessionData.cookie,
259
+ expiresAt: sessionData.expiresAt
260
+ };
261
+ }
262
+
263
+ /**
264
+ * Validate if a session appears to be valid
265
+ *
266
+ * Performs structural validation of the session:
267
+ * - Cookie format validation (JWT-like structure)
268
+ * - Expiration check (if expiresAt is provided)
269
+ * - Basic cookie integrity checks
270
+ *
271
+ * Note: This does NOT verify the session with the server.
272
+ *
273
+ * @param session - Session info to validate
274
+ * @returns true if session appears valid, false otherwise
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * const session = await sessionService.findSession(endpoint, projectId);
279
+ * if (session && sessionService.isValidSession(session)) {
280
+ * // Session is structurally valid
281
+ * }
282
+ * ```
283
+ */
284
+ public isValidSession(session: SessionAuthInfo): boolean {
285
+ if (!session || typeof session !== "object") {
286
+ return false;
287
+ }
288
+
289
+ // Validate required fields
290
+ if (!session.cookie || !session.endpoint || !session.projectId) {
291
+ logger.debug("Session missing required fields", {
292
+ hasCookie: !!session.cookie,
293
+ hasEndpoint: !!session.endpoint,
294
+ hasProjectId: !!session.projectId
295
+ });
296
+ return false;
297
+ }
298
+
299
+ // Validate cookie format
300
+ if (!this.isValidSessionCookie(session.cookie)) {
301
+ logger.debug("Session cookie failed validation", {
302
+ projectId: session.projectId
303
+ });
304
+ return false;
305
+ }
306
+
307
+ // Check expiration if provided
308
+ if (session.expiresAt) {
309
+ const expirationTime = new Date(session.expiresAt).getTime();
310
+ const now = Date.now();
311
+
312
+ if (expirationTime < now) {
313
+ logger.debug("Session expired", {
314
+ projectId: session.projectId,
315
+ expiresAt: session.expiresAt,
316
+ expiredBy: `${Math.round((now - expirationTime) / 1000)}s`
317
+ });
318
+ return false;
319
+ }
320
+ }
321
+
322
+ return true;
323
+ }
324
+
325
+ /**
326
+ * Get detailed authentication status for a given endpoint and project
327
+ *
328
+ * Provides comprehensive authentication status including:
329
+ * - Session validation
330
+ * - API key presence
331
+ * - Detailed diagnostic information
332
+ * - Actionable error messages
333
+ *
334
+ * @param endpoint - Appwrite endpoint URL
335
+ * @param projectId - Appwrite project ID
336
+ * @param apiKey - Optional API key for authentication
337
+ * @param session - Optional pre-loaded session (avoids re-loading)
338
+ * @returns Detailed authentication status
339
+ *
340
+ * @example
341
+ * ```typescript
342
+ * const status = await sessionService.getAuthenticationStatus(
343
+ * "https://cloud.appwrite.io/v1",
344
+ * "my-project-id",
345
+ * process.env.APPWRITE_API_KEY
346
+ * );
347
+ *
348
+ * console.log(status.message);
349
+ * if (status.hasValidSession) {
350
+ * console.log(`Authenticated as ${status.sessionInfo?.email}`);
351
+ * } else if (status.hasApiKey) {
352
+ * console.log("Using API key authentication");
353
+ * }
354
+ * ```
355
+ */
356
+ public async getAuthenticationStatus(
357
+ endpoint: string,
358
+ projectId: string,
359
+ apiKey?: string,
360
+ session?: SessionAuthInfo | null
361
+ ): Promise<AuthenticationStatus> {
362
+ // Load session if not provided
363
+ const sessionInfo = session !== undefined
364
+ ? session
365
+ : await this.findSession(endpoint, projectId);
366
+
367
+ // Check API key presence
368
+ const hasApiKey = !!(apiKey && apiKey.trim().length > 0);
369
+
370
+ // If no session exists
371
+ if (!sessionInfo) {
372
+ if (hasApiKey) {
373
+ return {
374
+ hasValidSession: false,
375
+ hasApiKey: true,
376
+ sessionExists: false,
377
+ endpointMatches: false,
378
+ cookieValid: false,
379
+ message: "Using API key authentication (no session found)",
380
+ authMethod: "apikey"
381
+ };
382
+ }
383
+
384
+ return {
385
+ hasValidSession: false,
386
+ hasApiKey: false,
387
+ sessionExists: false,
388
+ endpointMatches: false,
389
+ cookieValid: false,
390
+ message: `No authentication found for project ${projectId}. Run 'appwrite login' or provide an API key.`,
391
+ authMethod: "none"
392
+ };
393
+ }
394
+
395
+ // Validate session
396
+ const endpointMatches = this.normalizeEndpoint(sessionInfo.endpoint) === this.normalizeEndpoint(endpoint);
397
+ const cookieValid = this.isValidSessionCookie(sessionInfo.cookie);
398
+ const hasValidSession = endpointMatches && cookieValid;
399
+
400
+ // Generate status message
401
+ let message = "";
402
+ let authMethod: "session" | "apikey" | "none" = "none";
403
+
404
+ if (!endpointMatches) {
405
+ message = `Session endpoint mismatch. Config: ${endpoint}, Session: ${sessionInfo.endpoint}`;
406
+ authMethod = hasApiKey ? "apikey" : "none";
407
+ } else if (!cookieValid) {
408
+ message = `Session cookie is invalid or expired for project ${projectId}`;
409
+ authMethod = hasApiKey ? "apikey" : "none";
410
+ } else {
411
+ message = `Valid session found for ${sessionInfo.email || "unknown user"}`;
412
+ authMethod = "session";
413
+ }
414
+
415
+ return {
416
+ hasValidSession,
417
+ hasApiKey,
418
+ sessionExists: true,
419
+ endpointMatches,
420
+ cookieValid,
421
+ sessionInfo,
422
+ message,
423
+ authMethod
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Manually invalidate the cache
429
+ *
430
+ * Forces the next loadSessionPrefs() call to read from disk.
431
+ * Useful after external changes to prefs.json (e.g., after login/logout).
432
+ *
433
+ * @example
434
+ * ```typescript
435
+ * // After user logs in
436
+ * sessionService.invalidateCache();
437
+ * const newSession = await sessionService.loadSessionPrefs();
438
+ * ```
439
+ */
440
+ public invalidateCache(): void {
441
+ logger.debug("Session cache manually invalidated");
442
+ this.cache = null;
443
+ }
444
+
445
+ /**
446
+ * Normalize an endpoint URL for comparison
447
+ *
448
+ * @param url - Endpoint URL to normalize
449
+ * @returns Normalized URL (lowercase, no trailing slashes)
450
+ */
451
+ private normalizeEndpoint(url: string): string {
452
+ return url.replace(/\/+$/, "").toLowerCase();
453
+ }
454
+
455
+ /**
456
+ * Validate session cookie format
457
+ *
458
+ * Performs basic validation to check if a cookie appears to be a valid Appwrite session:
459
+ * - Minimum length check
460
+ * - JWT-like structure (contains dots)
461
+ * - Valid character set
462
+ * - Multi-part structure
463
+ *
464
+ * @param cookie - Cookie string to validate
465
+ * @returns true if cookie appears valid, false otherwise
466
+ */
467
+ private isValidSessionCookie(cookie: string): boolean {
468
+ if (!cookie || typeof cookie !== "string") {
469
+ return false;
470
+ }
471
+
472
+ // Trim whitespace
473
+ cookie = cookie.trim();
474
+
475
+ // Basic length check
476
+ if (cookie.length < 10) {
477
+ return false;
478
+ }
479
+
480
+ // Basic validation - Appwrite session cookies are typically JWT-like
481
+ // They should contain dots and be reasonably long
482
+ if (!cookie.includes(".")) {
483
+ return false;
484
+ }
485
+
486
+ // Check for obviously expired or malformed tokens
487
+ // JWT tokens typically have 3 parts separated by dots
488
+ const parts = cookie.split(".");
489
+ if (parts.length < 2) {
490
+ return false;
491
+ }
492
+
493
+ // Additional validation - ensure it's not obviously corrupted
494
+ // Should contain alphanumeric characters and common JWT characters
495
+ const validChars = /^[A-Za-z0-9._-]+$/;
496
+ if (!validChars.test(cookie)) {
497
+ return false;
498
+ }
499
+
500
+ return true;
501
+ }
502
+
503
+ /**
504
+ * Generate MD5 hash of content for cache validation
505
+ *
506
+ * @param content - Content to hash
507
+ * @returns MD5 hash as hex string
508
+ */
509
+ private hashContent(content: string): string {
510
+ return createHash("md5").update(content).digest("hex");
511
+ }
512
+
513
+ /**
514
+ * Get all available sessions from prefs
515
+ *
516
+ * Returns all sessions stored in the preferences file that pass
517
+ * basic validation checks.
518
+ *
519
+ * @returns Array of valid session info objects
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * const sessions = await sessionService.getAvailableSessions();
524
+ * console.log(`Found ${sessions.length} available sessions`);
525
+ * sessions.forEach(s => console.log(` - ${s.projectId} (${s.email})`));
526
+ * ```
527
+ */
528
+ public async getAvailableSessions(): Promise<SessionAuthInfo[]> {
529
+ const prefs = await this.loadSessionPrefs();
530
+
531
+ if (!prefs) {
532
+ return [];
533
+ }
534
+
535
+ const sessions: SessionAuthInfo[] = [];
536
+
537
+ for (const [projectId, sessionData] of Object.entries(prefs)) {
538
+ if (
539
+ sessionData.endpoint &&
540
+ sessionData.cookie &&
541
+ this.isValidSessionCookie(sessionData.cookie)
542
+ ) {
543
+ sessions.push({
544
+ projectId,
545
+ endpoint: sessionData.endpoint,
546
+ cookie: sessionData.cookie,
547
+ email: sessionData.email,
548
+ expiresAt: sessionData.expiresAt
549
+ });
550
+ }
551
+ }
552
+
553
+ logger.debug(`Found ${sessions.length} available sessions`);
554
+ return sessions;
555
+ }
556
+
557
+ /**
558
+ * Get the path to the prefs.json file
559
+ *
560
+ * @returns Absolute path to prefs.json
561
+ */
562
+ public getPrefsPath(): string {
563
+ return this.PREFS_PATH;
564
+ }
565
+ }