@aifabrix/builder 2.1.6 → 2.2.0

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 (38) hide show
  1. package/lib/app-deploy.js +73 -29
  2. package/lib/app-list.js +132 -0
  3. package/lib/app-readme.js +11 -4
  4. package/lib/app-register.js +435 -0
  5. package/lib/app-rotate-secret.js +164 -0
  6. package/lib/app-run.js +98 -84
  7. package/lib/app.js +13 -0
  8. package/lib/audit-logger.js +195 -15
  9. package/lib/build.js +57 -37
  10. package/lib/cli.js +90 -8
  11. package/lib/commands/app.js +8 -391
  12. package/lib/commands/login.js +130 -36
  13. package/lib/config.js +257 -4
  14. package/lib/deployer.js +221 -183
  15. package/lib/infra.js +177 -112
  16. package/lib/secrets.js +85 -99
  17. package/lib/utils/api-error-handler.js +465 -0
  18. package/lib/utils/api.js +165 -16
  19. package/lib/utils/auth-headers.js +84 -0
  20. package/lib/utils/build-copy.js +144 -0
  21. package/lib/utils/cli-utils.js +21 -0
  22. package/lib/utils/compose-generator.js +43 -14
  23. package/lib/utils/deployment-errors.js +90 -0
  24. package/lib/utils/deployment-validation.js +60 -0
  25. package/lib/utils/dev-config.js +83 -0
  26. package/lib/utils/env-template.js +30 -10
  27. package/lib/utils/health-check.js +18 -1
  28. package/lib/utils/infra-containers.js +101 -0
  29. package/lib/utils/local-secrets.js +0 -2
  30. package/lib/utils/secrets-path.js +18 -21
  31. package/lib/utils/secrets-utils.js +206 -0
  32. package/lib/utils/token-manager.js +381 -0
  33. package/package.json +1 -1
  34. package/templates/applications/README.md.hbs +155 -23
  35. package/templates/applications/miso-controller/Dockerfile +7 -119
  36. package/templates/infra/compose.yaml.hbs +93 -0
  37. package/templates/python/docker-compose.hbs +25 -17
  38. package/templates/typescript/docker-compose.hbs +25 -17
package/lib/config.js CHANGED
@@ -17,17 +17,53 @@ const yaml = require('js-yaml');
17
17
  const CONFIG_DIR = path.join(os.homedir(), '.aifabrix');
18
18
  const CONFIG_FILE = path.join(CONFIG_DIR, 'config.yaml');
19
19
 
20
+ // Cache for developer ID - loaded when getConfig() is first called
21
+ let cachedDeveloperId = null;
22
+
20
23
  /**
21
24
  * Get stored configuration
22
- * @returns {Promise<Object>} Configuration object with apiUrl and token
25
+ * Loads developer ID and caches it as a property for easy access
26
+ * @returns {Promise<Object>} Configuration object with new structure
23
27
  */
24
28
  async function getConfig() {
25
29
  try {
26
30
  const configContent = await fs.readFile(CONFIG_FILE, 'utf8');
27
- return yaml.load(configContent);
31
+ let config = yaml.load(configContent);
32
+
33
+ // Handle empty file or null/undefined result from yaml.load
34
+ if (!config || typeof config !== 'object') {
35
+ config = {};
36
+ }
37
+
38
+ // Ensure developerId defaults to 0 if not set
39
+ if (typeof config['developer-id'] === 'undefined') {
40
+ config['developer-id'] = 0;
41
+ }
42
+ // Ensure environment defaults to 'dev' if not set
43
+ if (typeof config.environment === 'undefined') {
44
+ config.environment = 'dev';
45
+ }
46
+ // Ensure environments object exists
47
+ if (typeof config.environments !== 'object' || config.environments === null) {
48
+ config.environments = {};
49
+ }
50
+ // Ensure device object exists at root level
51
+ if (typeof config.device !== 'object' || config.device === null) {
52
+ config.device = {};
53
+ }
54
+ // Cache developer ID as property for easy access (use nullish coalescing to allow 0)
55
+ cachedDeveloperId = config['developer-id'] !== undefined ? config['developer-id'] : 0;
56
+ return config;
28
57
  } catch (error) {
29
58
  if (error.code === 'ENOENT') {
30
- return { apiUrl: null, token: null };
59
+ // Default developer ID is 0, default environment is 'dev'
60
+ cachedDeveloperId = 0;
61
+ return {
62
+ 'developer-id': 0,
63
+ environment: 'dev',
64
+ environments: {},
65
+ device: {}
66
+ };
31
67
  }
32
68
  throw new Error(`Failed to read config: ${error.message}`);
33
69
  }
@@ -45,10 +81,19 @@ async function saveConfig(data) {
45
81
 
46
82
  // Set secure permissions
47
83
  const configContent = yaml.dump(data);
84
+ // Write file first
48
85
  await fs.writeFile(CONFIG_FILE, configContent, {
49
86
  mode: 0o600,
50
87
  flag: 'w'
51
88
  });
89
+ // Open file descriptor and fsync to ensure write is flushed to disk
90
+ // This is critical on Windows where file writes may be cached
91
+ const fd = await fs.open(CONFIG_FILE, 'r+');
92
+ try {
93
+ await fd.sync();
94
+ } finally {
95
+ await fd.close();
96
+ }
52
97
  } catch (error) {
53
98
  throw new Error(`Failed to save config: ${error.message}`);
54
99
  }
@@ -68,11 +113,219 @@ async function clearConfig() {
68
113
  }
69
114
  }
70
115
 
71
- module.exports = {
116
+ /**
117
+ * Get developer ID from configuration
118
+ * Loads config if not already cached, then returns cached developer ID
119
+ * Developer ID: 0 = default infra, > 0 = developer-specific
120
+ * @returns {Promise<number>} Developer ID (defaults to 0)
121
+ */
122
+ async function getDeveloperId() {
123
+ // Always reload from file to ensure we have the latest value
124
+ // This ensures the cache matches what's actually in the file
125
+ // Clear cache first to force a fresh read
126
+ cachedDeveloperId = null;
127
+ await getConfig();
128
+ return cachedDeveloperId;
129
+ }
130
+
131
+ /**
132
+ * Set developer ID in configuration
133
+ * @param {number} developerId - Developer ID to set (0 = default infra, > 0 = developer-specific)
134
+ * @returns {Promise<void>}
135
+ */
136
+ async function setDeveloperId(developerId) {
137
+ if (typeof developerId !== 'number' || developerId < 0) {
138
+ throw new Error('Developer ID must be a non-negative number (0 = default infra, > 0 = developer-specific)');
139
+ }
140
+ // Clear cache first to ensure we get fresh data from file
141
+ cachedDeveloperId = null;
142
+ // Read file directly to avoid any caching issues
143
+ const config = await getConfig();
144
+ // Update developer ID
145
+ config['developer-id'] = developerId;
146
+ // Update cache before saving
147
+ cachedDeveloperId = developerId;
148
+ // Save the entire config object to ensure all fields are preserved
149
+ await saveConfig(config);
150
+ // Verify the file was saved correctly by reading it back
151
+ // This ensures the file system has written the data
152
+ // Add a small delay to ensure file system has flushed the write
153
+ await new Promise(resolve => setTimeout(resolve, 100));
154
+ // Read file again with fresh file handle to avoid OS caching
155
+ const savedContent = await fs.readFile(CONFIG_FILE, 'utf8');
156
+ const savedConfig = yaml.load(savedContent);
157
+ if (savedConfig['developer-id'] !== developerId) {
158
+ throw new Error(`Failed to save developer ID: expected ${developerId}, got ${savedConfig['developer-id']}. File content: ${savedContent.substring(0, 200)}`);
159
+ }
160
+ // Clear the cache to force reload from file on next getDeveloperId() call
161
+ // This ensures we get the value that was actually saved to disk
162
+ cachedDeveloperId = null;
163
+ }
164
+
165
+ /**
166
+ * Get current environment from root-level config
167
+ * @returns {Promise<string>} Current environment (defaults to 'dev')
168
+ */
169
+ async function getCurrentEnvironment() {
170
+ const config = await getConfig();
171
+ return config.environment || 'dev';
172
+ }
173
+
174
+ /**
175
+ * Set current environment in root-level config
176
+ * @param {string} environment - Environment to set (e.g., 'miso', 'dev', 'tst', 'pro')
177
+ * @returns {Promise<void>}
178
+ */
179
+ async function setCurrentEnvironment(environment) {
180
+ if (!environment || typeof environment !== 'string') {
181
+ throw new Error('Environment must be a non-empty string');
182
+ }
183
+ const config = await getConfig();
184
+ config.environment = environment;
185
+ await saveConfig(config);
186
+ }
187
+
188
+ /**
189
+ * Check if token is expired
190
+ * @param {string} expiresAt - ISO timestamp string
191
+ * @returns {boolean} True if token is expired
192
+ */
193
+ function isTokenExpired(expiresAt) {
194
+ if (!expiresAt) {
195
+ return true;
196
+ }
197
+ const expirationTime = new Date(expiresAt).getTime();
198
+ const now = Date.now();
199
+ // Add 5 minute buffer to refresh before actual expiration
200
+ return now >= (expirationTime - 5 * 60 * 1000);
201
+ }
202
+
203
+ /**
204
+ * Get device token for controller
205
+ * @param {string} controllerUrl - Controller URL
206
+ * @returns {Promise<{controller: string, token: string, refreshToken: string, expiresAt: string}|null>} Device token info or null
207
+ */
208
+ async function getDeviceToken(controllerUrl) {
209
+ const config = await getConfig();
210
+ if (!config.device || !config.device[controllerUrl]) {
211
+ return null;
212
+ }
213
+ const deviceToken = config.device[controllerUrl];
214
+ return {
215
+ controller: controllerUrl,
216
+ token: deviceToken.token,
217
+ refreshToken: deviceToken.refreshToken,
218
+ expiresAt: deviceToken.expiresAt
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Get client token for environment and app
224
+ * @param {string} environment - Environment key
225
+ * @param {string} appName - Application name
226
+ * @returns {Promise<{controller: string, token: string, expiresAt: string}|null>} Client token info or null
227
+ */
228
+ async function getClientToken(environment, appName) {
229
+ const config = await getConfig();
230
+ if (!config.environments || !config.environments[environment]) {
231
+ return null;
232
+ }
233
+ if (!config.environments[environment].clients || !config.environments[environment].clients[appName]) {
234
+ return null;
235
+ }
236
+ return config.environments[environment].clients[appName];
237
+ }
238
+
239
+ /**
240
+ * Save device token for controller (root level)
241
+ * @param {string} controllerUrl - Controller URL (used as key)
242
+ * @param {string} token - Device access token
243
+ * @param {string} refreshToken - Refresh token for token renewal
244
+ * @param {string} expiresAt - ISO timestamp string
245
+ * @returns {Promise<void>}
246
+ */
247
+ async function saveDeviceToken(controllerUrl, token, refreshToken, expiresAt) {
248
+ const config = await getConfig();
249
+ if (!config.device) {
250
+ config.device = {};
251
+ }
252
+ config.device[controllerUrl] = {
253
+ token: token,
254
+ refreshToken: refreshToken,
255
+ expiresAt: expiresAt
256
+ };
257
+ await saveConfig(config);
258
+ }
259
+
260
+ /**
261
+ * Save client token for environment and app
262
+ * @param {string} environment - Environment key
263
+ * @param {string} appName - Application name
264
+ * @param {string} controllerUrl - Controller URL
265
+ * @param {string} token - Client token
266
+ * @param {string} expiresAt - ISO timestamp string
267
+ * @returns {Promise<void>}
268
+ */
269
+ async function saveClientToken(environment, appName, controllerUrl, token, expiresAt) {
270
+ const config = await getConfig();
271
+ if (!config.environments) {
272
+ config.environments = {};
273
+ }
274
+ if (!config.environments[environment]) {
275
+ config.environments[environment] = { clients: {} };
276
+ }
277
+ if (!config.environments[environment].clients) {
278
+ config.environments[environment].clients = {};
279
+ }
280
+ config.environments[environment].clients[appName] = {
281
+ controller: controllerUrl,
282
+ token: token,
283
+ expiresAt: expiresAt
284
+ };
285
+ await saveConfig(config);
286
+ }
287
+
288
+ /**
289
+ * Initialize and load developer ID
290
+ * Call this to ensure developerId is loaded and cached
291
+ * @returns {Promise<number>} Developer ID
292
+ */
293
+ async function loadDeveloperId() {
294
+ if (cachedDeveloperId === null) {
295
+ await getConfig();
296
+ }
297
+ return cachedDeveloperId;
298
+ }
299
+
300
+ // Create exports object
301
+ const exportsObj = {
72
302
  getConfig,
73
303
  saveConfig,
74
304
  clearConfig,
305
+ getDeveloperId,
306
+ setDeveloperId,
307
+ loadDeveloperId,
308
+ getCurrentEnvironment,
309
+ setCurrentEnvironment,
310
+ isTokenExpired,
311
+ getDeviceToken,
312
+ getClientToken,
313
+ saveDeviceToken,
314
+ saveClientToken,
75
315
  CONFIG_DIR,
76
316
  CONFIG_FILE
77
317
  };
78
318
 
319
+ // Add developerId as a property getter for direct access
320
+ // After getConfig() or getDeveloperId() is called, config.developerId will be available
321
+ // Developer ID: 0 = default infra, > 0 = developer-specific
322
+ Object.defineProperty(exportsObj, 'developerId', {
323
+ get() {
324
+ return cachedDeveloperId !== null ? cachedDeveloperId : 0; // Default to 0 if not loaded yet
325
+ },
326
+ enumerable: true,
327
+ configurable: true
328
+ });
329
+
330
+ module.exports = exportsObj;
331
+