@autonoma-io/a6s 5.1.2

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 (92) hide show
  1. package/README.md +200 -0
  2. package/bin/binaries/a6s-darwin-amd64 +0 -0
  3. package/bin/binaries/a6s-darwin-arm64 +0 -0
  4. package/bin/binaries/a6s-linux-amd64 +0 -0
  5. package/bin/binaries/a6s-linux-arm64 +0 -0
  6. package/bin/binaries/a6s-win32-x64.exe +0 -0
  7. package/dist/commands/ai-learning-demo.d.ts +3 -0
  8. package/dist/commands/ai-learning-demo.d.ts.map +1 -0
  9. package/dist/commands/ai-learning-demo.js +176 -0
  10. package/dist/commands/ai-learning-demo.js.map +1 -0
  11. package/dist/commands/auth.d.ts +33 -0
  12. package/dist/commands/auth.d.ts.map +1 -0
  13. package/dist/commands/auth.js +603 -0
  14. package/dist/commands/auth.js.map +1 -0
  15. package/dist/consent/consent.d.ts +74 -0
  16. package/dist/consent/consent.d.ts.map +1 -0
  17. package/dist/consent/consent.js +184 -0
  18. package/dist/consent/consent.js.map +1 -0
  19. package/dist/consent/disclosure.d.ts +26 -0
  20. package/dist/consent/disclosure.d.ts.map +1 -0
  21. package/dist/consent/disclosure.js +170 -0
  22. package/dist/consent/disclosure.js.map +1 -0
  23. package/dist/consent/ignore.d.ts +50 -0
  24. package/dist/consent/ignore.d.ts.map +1 -0
  25. package/dist/consent/ignore.js +277 -0
  26. package/dist/consent/ignore.js.map +1 -0
  27. package/dist/consent/index.d.ts +4 -0
  28. package/dist/consent/index.d.ts.map +1 -0
  29. package/dist/consent/index.js +23 -0
  30. package/dist/consent/index.js.map +1 -0
  31. package/dist/index.d.ts +3 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +390 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/interactive.d.ts +19 -0
  36. package/dist/interactive.d.ts.map +1 -0
  37. package/dist/interactive.js +367 -0
  38. package/dist/interactive.js.map +1 -0
  39. package/dist/modules/ab-testing.d.ts +16 -0
  40. package/dist/modules/ab-testing.d.ts.map +1 -0
  41. package/dist/modules/ab-testing.js +375 -0
  42. package/dist/modules/ab-testing.js.map +1 -0
  43. package/dist/modules/ai-orchestration.d.ts +70 -0
  44. package/dist/modules/ai-orchestration.d.ts.map +1 -0
  45. package/dist/modules/ai-orchestration.js +546 -0
  46. package/dist/modules/ai-orchestration.js.map +1 -0
  47. package/dist/modules/auth-access-control.d.ts +118 -0
  48. package/dist/modules/auth-access-control.d.ts.map +1 -0
  49. package/dist/modules/auth-access-control.js +832 -0
  50. package/dist/modules/auth-access-control.js.map +1 -0
  51. package/dist/modules/campaign.d.ts +20 -0
  52. package/dist/modules/campaign.d.ts.map +1 -0
  53. package/dist/modules/campaign.js +301 -0
  54. package/dist/modules/campaign.js.map +1 -0
  55. package/dist/modules/database.d.ts +14 -0
  56. package/dist/modules/database.d.ts.map +1 -0
  57. package/dist/modules/database.js +253 -0
  58. package/dist/modules/database.js.map +1 -0
  59. package/dist/modules/deployment.d.ts +17 -0
  60. package/dist/modules/deployment.d.ts.map +1 -0
  61. package/dist/modules/deployment.js +201 -0
  62. package/dist/modules/deployment.js.map +1 -0
  63. package/dist/modules/edge-computing.d.ts +130 -0
  64. package/dist/modules/edge-computing.d.ts.map +1 -0
  65. package/dist/modules/edge-computing.js +672 -0
  66. package/dist/modules/edge-computing.js.map +1 -0
  67. package/dist/modules/load-testing.d.ts +21 -0
  68. package/dist/modules/load-testing.d.ts.map +1 -0
  69. package/dist/modules/load-testing.js +372 -0
  70. package/dist/modules/load-testing.js.map +1 -0
  71. package/dist/modules/monitoring.d.ts +18 -0
  72. package/dist/modules/monitoring.d.ts.map +1 -0
  73. package/dist/modules/monitoring.js +375 -0
  74. package/dist/modules/monitoring.js.map +1 -0
  75. package/dist/modules/onboarding.d.ts +20 -0
  76. package/dist/modules/onboarding.d.ts.map +1 -0
  77. package/dist/modules/onboarding.js +455 -0
  78. package/dist/modules/onboarding.js.map +1 -0
  79. package/dist/nlp/memory.d.ts +43 -0
  80. package/dist/nlp/memory.d.ts.map +1 -0
  81. package/dist/nlp/memory.js +205 -0
  82. package/dist/nlp/memory.js.map +1 -0
  83. package/dist/nlp/processor.d.ts +29 -0
  84. package/dist/nlp/processor.d.ts.map +1 -0
  85. package/dist/nlp/processor.js +321 -0
  86. package/dist/nlp/processor.js.map +1 -0
  87. package/dist/utils/db-client.d.ts +35 -0
  88. package/dist/utils/db-client.d.ts.map +1 -0
  89. package/dist/utils/db-client.js +132 -0
  90. package/dist/utils/db-client.js.map +1 -0
  91. package/package.json +97 -0
  92. package/scripts/chmod-binaries.js +33 -0
@@ -0,0 +1,832 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.AuthAccessControlModule = exports.Permission = exports.AdminRole = void 0;
40
+ const crypto_1 = require("crypto");
41
+ const fs_1 = require("fs");
42
+ const os_1 = require("os");
43
+ const path_1 = require("path");
44
+ const chalk_1 = __importDefault(require("chalk"));
45
+ const ora_1 = __importDefault(require("ora"));
46
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
47
+ const speakeasy = __importStar(require("speakeasy"));
48
+ const qrcode = __importStar(require("qrcode"));
49
+ const client_ssm_1 = require("@aws-sdk/client-ssm");
50
+ const client_secrets_manager_1 = require("@aws-sdk/client-secrets-manager");
51
+ const client_cognito_identity_provider_1 = require("@aws-sdk/client-cognito-identity-provider");
52
+ // Role definitions
53
+ var AdminRole;
54
+ (function (AdminRole) {
55
+ AdminRole["SUPER_ADMIN"] = "super_admin";
56
+ AdminRole["PLATFORM_ADMIN"] = "platform_admin";
57
+ AdminRole["DEVOPS_ADMIN"] = "devops_admin";
58
+ AdminRole["SECURITY_ADMIN"] = "security_admin";
59
+ AdminRole["DATA_ADMIN"] = "data_admin";
60
+ AdminRole["SUPPORT_ADMIN"] = "support_admin";
61
+ AdminRole["READ_ONLY"] = "read_only"; // View-only access
62
+ })(AdminRole || (exports.AdminRole = AdminRole = {}));
63
+ // Permission definitions
64
+ var Permission;
65
+ (function (Permission) {
66
+ // System permissions
67
+ Permission["SYSTEM_CONFIG"] = "system:config";
68
+ Permission["SYSTEM_DEPLOY"] = "system:deploy";
69
+ Permission["SYSTEM_MONITOR"] = "system:monitor";
70
+ Permission["SYSTEM_BACKUP"] = "system:backup";
71
+ // User management
72
+ Permission["USER_CREATE"] = "user:create";
73
+ Permission["USER_UPDATE"] = "user:update";
74
+ Permission["USER_DELETE"] = "user:delete";
75
+ Permission["USER_VIEW"] = "user:view";
76
+ // Data operations
77
+ Permission["DATA_READ"] = "data:read";
78
+ Permission["DATA_WRITE"] = "data:write";
79
+ Permission["DATA_DELETE"] = "data:delete";
80
+ Permission["DATA_EXPORT"] = "data:export";
81
+ // AI operations
82
+ Permission["AI_TRAIN"] = "ai:train";
83
+ Permission["AI_DEPLOY"] = "ai:deploy";
84
+ Permission["AI_MONITOR"] = "ai:monitor";
85
+ Permission["AI_CONFIG"] = "ai:config";
86
+ // Security operations
87
+ Permission["SECURITY_AUDIT"] = "security:audit";
88
+ Permission["SECURITY_CONFIG"] = "security:config";
89
+ Permission["SECURITY_KEYS"] = "security:keys";
90
+ Permission["SECURITY_LOGS"] = "security:logs";
91
+ })(Permission || (exports.Permission = Permission = {}));
92
+ // Role-Permission mapping
93
+ const ROLE_PERMISSIONS = {
94
+ [AdminRole.SUPER_ADMIN]: Object.values(Permission), // All permissions
95
+ [AdminRole.PLATFORM_ADMIN]: [
96
+ Permission.SYSTEM_CONFIG,
97
+ Permission.SYSTEM_DEPLOY,
98
+ Permission.SYSTEM_MONITOR,
99
+ Permission.USER_VIEW,
100
+ Permission.DATA_READ,
101
+ Permission.DATA_WRITE,
102
+ Permission.AI_DEPLOY,
103
+ Permission.AI_MONITOR
104
+ ],
105
+ [AdminRole.DEVOPS_ADMIN]: [
106
+ Permission.SYSTEM_DEPLOY,
107
+ Permission.SYSTEM_MONITOR,
108
+ Permission.SYSTEM_BACKUP,
109
+ Permission.DATA_READ,
110
+ Permission.AI_DEPLOY,
111
+ Permission.AI_MONITOR
112
+ ],
113
+ [AdminRole.SECURITY_ADMIN]: [
114
+ Permission.SECURITY_AUDIT,
115
+ Permission.SECURITY_CONFIG,
116
+ Permission.SECURITY_KEYS,
117
+ Permission.SECURITY_LOGS,
118
+ Permission.USER_VIEW,
119
+ Permission.SYSTEM_MONITOR
120
+ ],
121
+ [AdminRole.DATA_ADMIN]: [
122
+ Permission.DATA_READ,
123
+ Permission.DATA_WRITE,
124
+ Permission.DATA_DELETE,
125
+ Permission.DATA_EXPORT,
126
+ Permission.AI_MONITOR
127
+ ],
128
+ [AdminRole.SUPPORT_ADMIN]: [
129
+ Permission.USER_VIEW,
130
+ Permission.DATA_READ,
131
+ Permission.SYSTEM_MONITOR,
132
+ Permission.SECURITY_LOGS
133
+ ],
134
+ [AdminRole.READ_ONLY]: [
135
+ Permission.USER_VIEW,
136
+ Permission.DATA_READ,
137
+ Permission.SYSTEM_MONITOR
138
+ ]
139
+ };
140
+ class AuthAccessControlModule {
141
+ configPath;
142
+ config;
143
+ users = new Map();
144
+ sessions = new Map();
145
+ auditLogs = [];
146
+ ssmClient;
147
+ secretsClient;
148
+ cognitoClient;
149
+ constructor() {
150
+ this.configPath = (0, path_1.join)((0, os_1.homedir)(), '.autonoma-cli');
151
+ this.ensureConfigDirectory();
152
+ this.loadConfig();
153
+ this.loadUsers();
154
+ // Initialize AWS clients
155
+ this.ssmClient = new client_ssm_1.SSMClient({ region: process.env.AWS_REGION || 'us-east-1' });
156
+ this.secretsClient = new client_secrets_manager_1.SecretsManagerClient({ region: process.env.AWS_REGION || 'us-east-1' });
157
+ this.cognitoClient = new client_cognito_identity_provider_1.CognitoIdentityProviderClient({ region: process.env.AWS_REGION || 'us-east-1' });
158
+ }
159
+ ensureConfigDirectory() {
160
+ if (!(0, fs_1.existsSync)(this.configPath)) {
161
+ (0, fs_1.mkdirSync)(this.configPath, { recursive: true });
162
+ }
163
+ }
164
+ loadConfig() {
165
+ const configFile = (0, path_1.join)(this.configPath, 'auth-config.json');
166
+ if ((0, fs_1.existsSync)(configFile)) {
167
+ this.config = JSON.parse((0, fs_1.readFileSync)(configFile, 'utf-8'));
168
+ }
169
+ else {
170
+ // Default configuration
171
+ this.config = {
172
+ jwtSecret: (0, crypto_1.randomBytes)(64).toString('hex'),
173
+ sessionTimeout: 3600000, // 1 hour
174
+ mfaRequired: true,
175
+ passwordPolicy: {
176
+ minLength: 12,
177
+ requireUppercase: true,
178
+ requireLowercase: true,
179
+ requireNumbers: true,
180
+ requireSpecialChars: true,
181
+ maxAge: 90
182
+ },
183
+ loginAttempts: {
184
+ maxAttempts: 5,
185
+ lockoutDuration: 30
186
+ }
187
+ };
188
+ this.saveConfig();
189
+ }
190
+ }
191
+ saveConfig() {
192
+ const configFile = (0, path_1.join)(this.configPath, 'auth-config.json');
193
+ (0, fs_1.writeFileSync)(configFile, JSON.stringify(this.config, null, 2));
194
+ }
195
+ loadUsers() {
196
+ const usersFile = (0, path_1.join)(this.configPath, 'users.json');
197
+ if ((0, fs_1.existsSync)(usersFile)) {
198
+ const usersData = JSON.parse((0, fs_1.readFileSync)(usersFile, 'utf-8'));
199
+ usersData.forEach((user) => {
200
+ this.users.set(user.id, user);
201
+ });
202
+ }
203
+ }
204
+ saveUsers() {
205
+ const usersFile = (0, path_1.join)(this.configPath, 'users.json');
206
+ const usersData = Array.from(this.users.values());
207
+ (0, fs_1.writeFileSync)(usersFile, JSON.stringify(usersData, null, 2));
208
+ }
209
+ hashPassword(password, salt) {
210
+ return (0, crypto_1.pbkdf2Sync)(password, salt, 100000, 64, 'sha512').toString('hex');
211
+ }
212
+ validatePassword(password) {
213
+ const policy = this.config.passwordPolicy;
214
+ if (password.length < policy.minLength)
215
+ return false;
216
+ if (policy.requireUppercase && !/[A-Z]/.test(password))
217
+ return false;
218
+ if (policy.requireLowercase && !/[a-z]/.test(password))
219
+ return false;
220
+ if (policy.requireNumbers && !/\d/.test(password))
221
+ return false;
222
+ if (policy.requireSpecialChars && !/[!@#$%^&*(),.?":{}|<>]/.test(password))
223
+ return false;
224
+ return true;
225
+ }
226
+ async logAudit(log) {
227
+ this.auditLogs.push(log);
228
+ // Also send to CloudWatch or external logging service
229
+ const auditFile = (0, path_1.join)(this.configPath, 'audit.log');
230
+ const logEntry = `${log.timestamp.toISOString()} | ${log.userId} | ${log.action} | ${log.resource} | ${log.result} | ${log.ipAddress}\n`;
231
+ if ((0, fs_1.existsSync)(auditFile)) {
232
+ (0, fs_1.writeFileSync)(auditFile, logEntry, { flag: 'a' });
233
+ }
234
+ else {
235
+ (0, fs_1.writeFileSync)(auditFile, logEntry);
236
+ }
237
+ }
238
+ // ============= Authentication Methods =============
239
+ async authenticateWithPassword(email, password, ipAddress = '127.0.0.1') {
240
+ const spinner = (0, ora_1.default)('Authenticating...').start();
241
+ try {
242
+ // Find user by email
243
+ const user = Array.from(this.users.values()).find(u => u.email === email);
244
+ if (!user) {
245
+ spinner.fail('Authentication failed');
246
+ await this.logAudit({
247
+ timestamp: new Date(),
248
+ userId: email,
249
+ action: 'LOGIN',
250
+ resource: 'CLI',
251
+ result: 'failure',
252
+ ipAddress,
253
+ details: { reason: 'User not found' }
254
+ });
255
+ return { success: false };
256
+ }
257
+ // Check if account is locked
258
+ if (user.lockedUntil && new Date() < new Date(user.lockedUntil)) {
259
+ spinner.fail('Account is locked');
260
+ return { success: false };
261
+ }
262
+ // Verify password
263
+ const hashedPassword = this.hashPassword(password, user.salt);
264
+ if (hashedPassword !== user.passwordHash) {
265
+ user.failedAttempts++;
266
+ if (user.failedAttempts >= this.config.loginAttempts.maxAttempts) {
267
+ user.lockedUntil = new Date(Date.now() + this.config.loginAttempts.lockoutDuration * 60000);
268
+ spinner.fail(`Account locked for ${this.config.loginAttempts.lockoutDuration} minutes`);
269
+ }
270
+ this.saveUsers();
271
+ spinner.fail('Invalid credentials');
272
+ await this.logAudit({
273
+ timestamp: new Date(),
274
+ userId: user.id,
275
+ action: 'LOGIN',
276
+ resource: 'CLI',
277
+ result: 'failure',
278
+ ipAddress,
279
+ details: { reason: 'Invalid password' }
280
+ });
281
+ return { success: false };
282
+ }
283
+ // Reset failed attempts
284
+ user.failedAttempts = 0;
285
+ user.lastLogin = new Date();
286
+ this.saveUsers();
287
+ // Check if MFA is required
288
+ if (this.config.mfaRequired && user.mfaEnabled) {
289
+ spinner.succeed('Password verified. MFA required');
290
+ return {
291
+ success: true,
292
+ token: this.generateTempToken(user.id),
293
+ mfaRequired: true
294
+ };
295
+ }
296
+ // Generate session
297
+ const token = this.generateSessionToken(user, ipAddress);
298
+ spinner.succeed('Authentication successful');
299
+ await this.logAudit({
300
+ timestamp: new Date(),
301
+ userId: user.id,
302
+ action: 'LOGIN',
303
+ resource: 'CLI',
304
+ result: 'success',
305
+ ipAddress
306
+ });
307
+ return { success: true, token };
308
+ }
309
+ catch (error) {
310
+ spinner.fail('Authentication error');
311
+ console.error(chalk_1.default.red('Error:'), error.message);
312
+ return { success: false };
313
+ }
314
+ }
315
+ async authenticateWithMFA(tempToken, mfaCode, ipAddress = '127.0.0.1') {
316
+ try {
317
+ // Decode temp token to get user ID
318
+ const decoded = jsonwebtoken_1.default.verify(tempToken, this.config.jwtSecret);
319
+ const user = this.users.get(decoded.userId);
320
+ if (!user || !user.mfaSecret) {
321
+ return { success: false };
322
+ }
323
+ // Verify MFA code
324
+ const verified = speakeasy.totp.verify({
325
+ secret: user.mfaSecret,
326
+ encoding: 'base32',
327
+ token: mfaCode,
328
+ window: 2
329
+ });
330
+ if (!verified) {
331
+ await this.logAudit({
332
+ timestamp: new Date(),
333
+ userId: user.id,
334
+ action: 'MFA_VERIFY',
335
+ resource: 'CLI',
336
+ result: 'failure',
337
+ ipAddress
338
+ });
339
+ return { success: false };
340
+ }
341
+ // Generate full session
342
+ const token = this.generateSessionToken(user, ipAddress, true);
343
+ await this.logAudit({
344
+ timestamp: new Date(),
345
+ userId: user.id,
346
+ action: 'MFA_VERIFY',
347
+ resource: 'CLI',
348
+ result: 'success',
349
+ ipAddress
350
+ });
351
+ return { success: true, token };
352
+ }
353
+ catch (error) {
354
+ return { success: false };
355
+ }
356
+ }
357
+ async authenticateWithAPIKey(apiKey, ipAddress = '127.0.0.1') {
358
+ const user = Array.from(this.users.values()).find(u => u.apiKey === apiKey);
359
+ if (!user) {
360
+ await this.logAudit({
361
+ timestamp: new Date(),
362
+ userId: 'unknown',
363
+ action: 'API_KEY_AUTH',
364
+ resource: 'CLI',
365
+ result: 'failure',
366
+ ipAddress,
367
+ details: { reason: 'Invalid API key' }
368
+ });
369
+ return { success: false };
370
+ }
371
+ const token = this.generateSessionToken(user, ipAddress);
372
+ await this.logAudit({
373
+ timestamp: new Date(),
374
+ userId: user.id,
375
+ action: 'API_KEY_AUTH',
376
+ resource: 'CLI',
377
+ result: 'success',
378
+ ipAddress
379
+ });
380
+ return { success: true, token };
381
+ }
382
+ async authenticateWithSSH(sshKeyPath, email, ipAddress = '127.0.0.1') {
383
+ try {
384
+ const sshPublicKey = (0, fs_1.readFileSync)(sshKeyPath, 'utf-8').trim();
385
+ const user = Array.from(this.users.values()).find(u => u.email === email && u.sshPublicKey === sshPublicKey);
386
+ if (!user) {
387
+ await this.logAudit({
388
+ timestamp: new Date(),
389
+ userId: email,
390
+ action: 'SSH_AUTH',
391
+ resource: 'CLI',
392
+ result: 'failure',
393
+ ipAddress,
394
+ details: { reason: 'SSH key not recognized' }
395
+ });
396
+ return { success: false };
397
+ }
398
+ const token = this.generateSessionToken(user, ipAddress);
399
+ await this.logAudit({
400
+ timestamp: new Date(),
401
+ userId: user.id,
402
+ action: 'SSH_AUTH',
403
+ resource: 'CLI',
404
+ result: 'success',
405
+ ipAddress
406
+ });
407
+ return { success: true, token };
408
+ }
409
+ catch (error) {
410
+ return { success: false };
411
+ }
412
+ }
413
+ async authenticateWithAWSRole(roleArn, ipAddress = '127.0.0.1') {
414
+ try {
415
+ // Verify AWS STS assume role
416
+ // This would typically use AWS STS to verify the caller can assume the role
417
+ const user = Array.from(this.users.values()).find(u => u.awsRoleArn === roleArn);
418
+ if (!user) {
419
+ await this.logAudit({
420
+ timestamp: new Date(),
421
+ userId: roleArn,
422
+ action: 'AWS_ROLE_AUTH',
423
+ resource: 'CLI',
424
+ result: 'failure',
425
+ ipAddress,
426
+ details: { reason: 'Role not authorized' }
427
+ });
428
+ return { success: false };
429
+ }
430
+ const token = this.generateSessionToken(user, ipAddress);
431
+ await this.logAudit({
432
+ timestamp: new Date(),
433
+ userId: user.id,
434
+ action: 'AWS_ROLE_AUTH',
435
+ resource: 'CLI',
436
+ result: 'success',
437
+ ipAddress
438
+ });
439
+ return { success: true, token };
440
+ }
441
+ catch (error) {
442
+ return { success: false };
443
+ }
444
+ }
445
+ async authenticateWithCognito(username, password, ipAddress = '127.0.0.1') {
446
+ try {
447
+ const command = new client_cognito_identity_provider_1.InitiateAuthCommand({
448
+ AuthFlow: 'USER_PASSWORD_AUTH',
449
+ ClientId: process.env.COGNITO_CLIENT_ID,
450
+ AuthParameters: {
451
+ USERNAME: username,
452
+ PASSWORD: password
453
+ }
454
+ });
455
+ const response = await this.cognitoClient.send(command);
456
+ if (response.AuthenticationResult?.IdToken) {
457
+ // Map Cognito user to internal user
458
+ const user = Array.from(this.users.values()).find(u => u.email === username);
459
+ if (user) {
460
+ const token = this.generateSessionToken(user, ipAddress);
461
+ await this.logAudit({
462
+ timestamp: new Date(),
463
+ userId: user.id,
464
+ action: 'COGNITO_AUTH',
465
+ resource: 'CLI',
466
+ result: 'success',
467
+ ipAddress
468
+ });
469
+ return { success: true, token };
470
+ }
471
+ }
472
+ return { success: false };
473
+ }
474
+ catch (error) {
475
+ await this.logAudit({
476
+ timestamp: new Date(),
477
+ userId: username,
478
+ action: 'COGNITO_AUTH',
479
+ resource: 'CLI',
480
+ result: 'failure',
481
+ ipAddress
482
+ });
483
+ return { success: false };
484
+ }
485
+ }
486
+ // ============= User Management =============
487
+ async createUser(email, password, role, createdBy, metadata) {
488
+ const spinner = (0, ora_1.default)('Creating user...').start();
489
+ try {
490
+ // Check if user already exists
491
+ if (Array.from(this.users.values()).some(u => u.email === email)) {
492
+ spinner.fail('User already exists');
493
+ return { success: false, error: 'User already exists' };
494
+ }
495
+ // Validate password
496
+ if (!this.validatePassword(password)) {
497
+ spinner.fail('Password does not meet policy requirements');
498
+ return { success: false, error: 'Invalid password' };
499
+ }
500
+ // Create user
501
+ const salt = (0, crypto_1.randomBytes)(32).toString('hex');
502
+ const passwordHash = this.hashPassword(password, salt);
503
+ const userId = (0, crypto_1.randomBytes)(16).toString('hex');
504
+ const user = {
505
+ id: userId,
506
+ email,
507
+ passwordHash,
508
+ salt,
509
+ role,
510
+ mfaEnabled: false,
511
+ passwordChangedAt: new Date(),
512
+ failedAttempts: 0,
513
+ metadata: {
514
+ createdAt: new Date(),
515
+ createdBy,
516
+ updatedAt: new Date(),
517
+ ...metadata
518
+ }
519
+ };
520
+ this.users.set(userId, user);
521
+ this.saveUsers();
522
+ spinner.succeed(`User created: ${email} (${role})`);
523
+ await this.logAudit({
524
+ timestamp: new Date(),
525
+ userId: createdBy,
526
+ action: 'USER_CREATE',
527
+ resource: userId,
528
+ result: 'success',
529
+ ipAddress: '127.0.0.1',
530
+ details: { email, role }
531
+ });
532
+ return { success: true, userId };
533
+ }
534
+ catch (error) {
535
+ spinner.fail('Failed to create user');
536
+ console.error(chalk_1.default.red('Error:'), error.message);
537
+ return { success: false, error: error.message };
538
+ }
539
+ }
540
+ async setupMFA(userId) {
541
+ const user = this.users.get(userId);
542
+ if (!user) {
543
+ return { success: false };
544
+ }
545
+ const secret = speakeasy.generateSecret({
546
+ name: `Autonoma CLI (${user.email})`
547
+ });
548
+ user.mfaSecret = secret.base32;
549
+ user.mfaEnabled = true;
550
+ this.saveUsers();
551
+ const qrCode = await qrcode.toDataURL(secret.otpauth_url);
552
+ return {
553
+ success: true,
554
+ qrCode,
555
+ secret: secret.base32
556
+ };
557
+ }
558
+ async generateAPIKey(userId) {
559
+ const user = this.users.get(userId);
560
+ if (!user) {
561
+ return { success: false };
562
+ }
563
+ const apiKey = `ak_${(0, crypto_1.randomBytes)(32).toString('hex')}`;
564
+ user.apiKey = (0, crypto_1.createHash)('sha256').update(apiKey).digest('hex');
565
+ this.saveUsers();
566
+ await this.logAudit({
567
+ timestamp: new Date(),
568
+ userId,
569
+ action: 'API_KEY_GENERATE',
570
+ resource: 'CLI',
571
+ result: 'success',
572
+ ipAddress: '127.0.0.1'
573
+ });
574
+ return { success: true, apiKey };
575
+ }
576
+ // ============= Authorization =============
577
+ hasPermission(userId, permission) {
578
+ const user = this.users.get(userId);
579
+ if (!user)
580
+ return false;
581
+ const rolePermissions = ROLE_PERMISSIONS[user.role] || [];
582
+ return rolePermissions.includes(permission);
583
+ }
584
+ checkAccess(token, permission) {
585
+ try {
586
+ const decoded = jsonwebtoken_1.default.verify(token, this.config.jwtSecret);
587
+ const session = this.sessions.get(decoded.sessionId);
588
+ if (!session || new Date() > new Date(session.expiresAt)) {
589
+ return false;
590
+ }
591
+ return this.hasPermission(session.userId, permission);
592
+ }
593
+ catch (error) {
594
+ return false;
595
+ }
596
+ }
597
+ // ============= Session Management =============
598
+ generateTempToken(userId) {
599
+ return jsonwebtoken_1.default.sign({ userId, temp: true }, this.config.jwtSecret, { expiresIn: '5m' });
600
+ }
601
+ generateSessionToken(user, ipAddress, mfaVerified = false) {
602
+ const sessionId = (0, crypto_1.randomBytes)(16).toString('hex');
603
+ const expiresAt = new Date(Date.now() + this.config.sessionTimeout);
604
+ const session = {
605
+ userId: user.id,
606
+ token: sessionId,
607
+ expiresAt,
608
+ ipAddress,
609
+ userAgent: 'Autonoma CLI',
610
+ mfaVerified
611
+ };
612
+ this.sessions.set(sessionId, session);
613
+ return jsonwebtoken_1.default.sign({
614
+ sessionId,
615
+ userId: user.id,
616
+ email: user.email,
617
+ role: user.role,
618
+ permissions: ROLE_PERMISSIONS[user.role]
619
+ }, this.config.jwtSecret, { expiresIn: this.config.sessionTimeout / 1000 });
620
+ }
621
+ async revokeSession(token) {
622
+ try {
623
+ const decoded = jsonwebtoken_1.default.verify(token, this.config.jwtSecret);
624
+ const session = this.sessions.get(decoded.sessionId);
625
+ if (session) {
626
+ this.sessions.delete(decoded.sessionId);
627
+ await this.logAudit({
628
+ timestamp: new Date(),
629
+ userId: session.userId,
630
+ action: 'LOGOUT',
631
+ resource: 'CLI',
632
+ result: 'success',
633
+ ipAddress: session.ipAddress
634
+ });
635
+ return true;
636
+ }
637
+ return false;
638
+ }
639
+ catch (error) {
640
+ return false;
641
+ }
642
+ }
643
+ // ============= Security Features =============
644
+ async rotateSecrets() {
645
+ const spinner = (0, ora_1.default)('Rotating security secrets...').start();
646
+ try {
647
+ // Rotate JWT secret
648
+ this.config.jwtSecret = (0, crypto_1.randomBytes)(64).toString('hex');
649
+ this.saveConfig();
650
+ // Invalidate all existing sessions
651
+ this.sessions.clear();
652
+ // Rotate all API keys
653
+ for (const user of this.users.values()) {
654
+ if (user.apiKey) {
655
+ user.apiKey = (0, crypto_1.createHash)('sha256')
656
+ .update(`ak_${(0, crypto_1.randomBytes)(32).toString('hex')}`)
657
+ .digest('hex');
658
+ }
659
+ }
660
+ this.saveUsers();
661
+ spinner.succeed('Security secrets rotated');
662
+ await this.logAudit({
663
+ timestamp: new Date(),
664
+ userId: 'system',
665
+ action: 'SECRET_ROTATION',
666
+ resource: 'CLI',
667
+ result: 'success',
668
+ ipAddress: '127.0.0.1'
669
+ });
670
+ }
671
+ catch (error) {
672
+ spinner.fail('Failed to rotate secrets');
673
+ console.error(chalk_1.default.red('Error:'), error.message);
674
+ }
675
+ }
676
+ async enforcePasswordRotation() {
677
+ const maxAge = this.config.passwordPolicy.maxAge * 24 * 60 * 60 * 1000;
678
+ const now = Date.now();
679
+ for (const user of this.users.values()) {
680
+ const passwordAge = now - new Date(user.passwordChangedAt).getTime();
681
+ if (passwordAge > maxAge) {
682
+ console.log(chalk_1.default.yellow(`Password expired for user: ${user.email}`));
683
+ // In production, would force password change on next login
684
+ }
685
+ }
686
+ }
687
+ // ============= Audit & Compliance =============
688
+ async getAuditLogs(filters) {
689
+ let logs = [...this.auditLogs];
690
+ if (filters) {
691
+ if (filters.userId) {
692
+ logs = logs.filter(log => log.userId === filters.userId);
693
+ }
694
+ if (filters.action) {
695
+ logs = logs.filter(log => log.action === filters.action);
696
+ }
697
+ if (filters.result) {
698
+ logs = logs.filter(log => log.result === filters.result);
699
+ }
700
+ if (filters.startDate) {
701
+ const startDate = filters.startDate;
702
+ logs = logs.filter(log => log.timestamp >= startDate);
703
+ }
704
+ if (filters.endDate) {
705
+ const endDate = filters.endDate;
706
+ logs = logs.filter(log => log.timestamp <= endDate);
707
+ }
708
+ }
709
+ return logs;
710
+ }
711
+ async generateComplianceReport() {
712
+ const report = {
713
+ timestamp: new Date(),
714
+ users: {
715
+ total: this.users.size,
716
+ byRole: {},
717
+ mfaEnabled: 0,
718
+ passwordCompliant: 0
719
+ },
720
+ sessions: {
721
+ active: this.sessions.size,
722
+ mfaVerified: 0
723
+ },
724
+ security: {
725
+ failedLogins: 0,
726
+ lockedAccounts: 0,
727
+ apiKeysActive: 0,
728
+ sshKeysConfigured: 0
729
+ },
730
+ audit: {
731
+ totalEvents: this.auditLogs.length,
732
+ successfulLogins: 0,
733
+ failedLogins: 0,
734
+ privilegedActions: 0
735
+ }
736
+ };
737
+ // Calculate statistics
738
+ for (const user of this.users.values()) {
739
+ report.users.byRole[user.role] = (report.users.byRole[user.role] || 0) + 1;
740
+ if (user.mfaEnabled)
741
+ report.users.mfaEnabled++;
742
+ if (user.apiKey)
743
+ report.security.apiKeysActive++;
744
+ if (user.sshPublicKey)
745
+ report.security.sshKeysConfigured++;
746
+ if (user.lockedUntil && new Date() < new Date(user.lockedUntil)) {
747
+ report.security.lockedAccounts++;
748
+ }
749
+ }
750
+ for (const session of this.sessions.values()) {
751
+ if (session.mfaVerified)
752
+ report.sessions.mfaVerified++;
753
+ }
754
+ for (const log of this.auditLogs) {
755
+ if (log.action === 'LOGIN' && log.result === 'success') {
756
+ report.audit.successfulLogins++;
757
+ }
758
+ if (log.action === 'LOGIN' && log.result === 'failure') {
759
+ report.audit.failedLogins++;
760
+ report.security.failedLogins++;
761
+ }
762
+ if (['USER_CREATE', 'USER_DELETE', 'SECRET_ROTATION'].includes(log.action)) {
763
+ report.audit.privilegedActions++;
764
+ }
765
+ }
766
+ return report;
767
+ }
768
+ // ============= Integration with External Systems =============
769
+ async fetchSecretsFromAWS(secretName) {
770
+ try {
771
+ const command = new client_secrets_manager_1.GetSecretValueCommand({
772
+ SecretId: secretName
773
+ });
774
+ const response = await this.secretsClient.send(command);
775
+ return JSON.parse(response.SecretString || '{}');
776
+ }
777
+ catch (error) {
778
+ console.error(chalk_1.default.red('Failed to fetch AWS secret:'), error);
779
+ return null;
780
+ }
781
+ }
782
+ async fetchParameterFromSSM(parameterName) {
783
+ try {
784
+ const command = new client_ssm_1.GetParameterCommand({
785
+ Name: parameterName,
786
+ WithDecryption: true
787
+ });
788
+ const response = await this.ssmClient.send(command);
789
+ return response.Parameter?.Value || null;
790
+ }
791
+ catch (error) {
792
+ console.error(chalk_1.default.red('Failed to fetch SSM parameter:'), error);
793
+ return null;
794
+ }
795
+ }
796
+ // ============= CLI Command Interface =============
797
+ async displayAccessInfo() {
798
+ console.log(chalk_1.default.cyan('\n📊 Access Control Configuration\n'));
799
+ console.log(chalk_1.default.blue('Authentication Methods:'));
800
+ console.log(' • Password + MFA');
801
+ console.log(' • API Key');
802
+ console.log(' • SSH Key');
803
+ console.log(' • AWS IAM Role');
804
+ console.log(' • AWS Cognito');
805
+ console.log(chalk_1.default.blue('\nAvailable Roles:'));
806
+ for (const role of Object.values(AdminRole)) {
807
+ const permissions = ROLE_PERMISSIONS[role];
808
+ console.log(` • ${role} (${permissions.length} permissions)`);
809
+ }
810
+ console.log(chalk_1.default.blue('\nPassword Policy:'));
811
+ console.log(` • Minimum length: ${this.config.passwordPolicy.minLength}`);
812
+ console.log(` • Uppercase required: ${this.config.passwordPolicy.requireUppercase}`);
813
+ console.log(` • Lowercase required: ${this.config.passwordPolicy.requireLowercase}`);
814
+ console.log(` • Numbers required: ${this.config.passwordPolicy.requireNumbers}`);
815
+ console.log(` • Special chars required: ${this.config.passwordPolicy.requireSpecialChars}`);
816
+ console.log(` • Maximum age: ${this.config.passwordPolicy.maxAge} days`);
817
+ console.log(chalk_1.default.blue('\nSecurity Settings:'));
818
+ console.log(` • MFA required: ${this.config.mfaRequired}`);
819
+ console.log(` • Session timeout: ${this.config.sessionTimeout / 60000} minutes`);
820
+ console.log(` • Max login attempts: ${this.config.loginAttempts.maxAttempts}`);
821
+ console.log(` • Lockout duration: ${this.config.loginAttempts.lockoutDuration} minutes`);
822
+ const report = await this.generateComplianceReport();
823
+ console.log(chalk_1.default.blue('\nCurrent Status:'));
824
+ console.log(` • Total users: ${report.users.total}`);
825
+ console.log(` • Active sessions: ${report.sessions.active}`);
826
+ console.log(` • MFA enabled users: ${report.users.mfaEnabled}`);
827
+ console.log(` • Locked accounts: ${report.security.lockedAccounts}`);
828
+ console.log(` • Audit events: ${report.audit.totalEvents}`);
829
+ }
830
+ }
831
+ exports.AuthAccessControlModule = AuthAccessControlModule;
832
+ //# sourceMappingURL=auth-access-control.js.map