@claude-flow/security 3.0.0-alpha.1 → 3.0.0-alpha.7

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 (96) hide show
  1. package/README.md +234 -234
  2. package/__tests__/acceptance/security-compliance.test.ts +674 -674
  3. package/__tests__/credential-generator.test.ts +310 -310
  4. package/__tests__/fixtures/configurations.ts +425 -419
  5. package/__tests__/fixtures/index.ts +21 -21
  6. package/__tests__/helpers/create-mock.ts +469 -469
  7. package/__tests__/helpers/index.ts +32 -32
  8. package/__tests__/input-validator.test.ts +382 -381
  9. package/__tests__/integration/security-flow.test.ts +606 -606
  10. package/__tests__/password-hasher.test.ts +239 -239
  11. package/__tests__/path-validator.test.ts +302 -302
  12. package/__tests__/safe-executor.test.ts +292 -292
  13. package/__tests__/token-generator.test.ts +371 -371
  14. package/__tests__/unit/credential-generator.test.ts +182 -182
  15. package/__tests__/unit/password-hasher.test.ts +359 -359
  16. package/__tests__/unit/path-validator.test.ts +509 -509
  17. package/__tests__/unit/safe-executor.test.ts +667 -667
  18. package/__tests__/unit/token-generator.test.ts +310 -310
  19. package/dist/credential-generator.js +9 -9
  20. package/dist/domain/services/security-domain-service.js +1 -1
  21. package/dist/domain/services/security-domain-service.js.map +1 -1
  22. package/dist/index.d.ts +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/password-hasher.d.ts.map +1 -1
  26. package/dist/password-hasher.js +8 -1
  27. package/dist/password-hasher.js.map +1 -1
  28. package/dist/safe-executor.d.ts +7 -0
  29. package/dist/safe-executor.d.ts.map +1 -1
  30. package/dist/safe-executor.js +21 -1
  31. package/dist/safe-executor.js.map +1 -1
  32. package/package.json +27 -28
  33. package/src/CVE-REMEDIATION.ts +251 -251
  34. package/src/application/index.ts +10 -10
  35. package/src/application/services/security-application-service.ts +193 -193
  36. package/src/credential-generator.ts +368 -368
  37. package/src/domain/entities/security-context.ts +173 -173
  38. package/src/domain/index.ts +17 -17
  39. package/src/domain/services/security-domain-service.ts +296 -296
  40. package/src/index.ts +271 -271
  41. package/src/input-validator.ts +466 -466
  42. package/src/password-hasher.ts +277 -270
  43. package/src/path-validator.ts +525 -525
  44. package/src/safe-executor.ts +546 -525
  45. package/src/token-generator.ts +463 -463
  46. package/tmp.json +0 -0
  47. package/tsconfig.json +9 -9
  48. package/tsconfig.tsbuildinfo +1 -1
  49. package/vitest.config.ts +20 -0
  50. package/.agentic-flow/intelligence.json +0 -16
  51. package/__tests__/coverage/base.css +0 -224
  52. package/__tests__/coverage/block-navigation.js +0 -87
  53. package/__tests__/coverage/coverage-final.json +0 -11
  54. package/__tests__/coverage/favicon.png +0 -0
  55. package/__tests__/coverage/index.html +0 -161
  56. package/__tests__/coverage/lcov-report/base.css +0 -224
  57. package/__tests__/coverage/lcov-report/block-navigation.js +0 -87
  58. package/__tests__/coverage/lcov-report/favicon.png +0 -0
  59. package/__tests__/coverage/lcov-report/index.html +0 -161
  60. package/__tests__/coverage/lcov-report/prettify.css +0 -1
  61. package/__tests__/coverage/lcov-report/prettify.js +0 -2
  62. package/__tests__/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  63. package/__tests__/coverage/lcov-report/sorter.js +0 -210
  64. package/__tests__/coverage/lcov-report/src/CVE-REMEDIATION.ts.html +0 -838
  65. package/__tests__/coverage/lcov-report/src/application/services/index.html +0 -116
  66. package/__tests__/coverage/lcov-report/src/application/services/security-application-service.ts.html +0 -664
  67. package/__tests__/coverage/lcov-report/src/credential-generator.ts.html +0 -1189
  68. package/__tests__/coverage/lcov-report/src/domain/entities/index.html +0 -116
  69. package/__tests__/coverage/lcov-report/src/domain/entities/security-context.ts.html +0 -604
  70. package/__tests__/coverage/lcov-report/src/domain/services/index.html +0 -116
  71. package/__tests__/coverage/lcov-report/src/domain/services/security-domain-service.ts.html +0 -973
  72. package/__tests__/coverage/lcov-report/src/index.html +0 -206
  73. package/__tests__/coverage/lcov-report/src/input-validator.ts.html +0 -1483
  74. package/__tests__/coverage/lcov-report/src/password-hasher.ts.html +0 -895
  75. package/__tests__/coverage/lcov-report/src/path-validator.ts.html +0 -1660
  76. package/__tests__/coverage/lcov-report/src/safe-executor.ts.html +0 -1660
  77. package/__tests__/coverage/lcov-report/src/token-generator.ts.html +0 -1474
  78. package/__tests__/coverage/lcov.info +0 -3650
  79. package/__tests__/coverage/prettify.css +0 -1
  80. package/__tests__/coverage/prettify.js +0 -2
  81. package/__tests__/coverage/sort-arrow-sprite.png +0 -0
  82. package/__tests__/coverage/sorter.js +0 -210
  83. package/__tests__/coverage/src/CVE-REMEDIATION.ts.html +0 -838
  84. package/__tests__/coverage/src/application/services/index.html +0 -116
  85. package/__tests__/coverage/src/application/services/security-application-service.ts.html +0 -664
  86. package/__tests__/coverage/src/credential-generator.ts.html +0 -1189
  87. package/__tests__/coverage/src/domain/entities/index.html +0 -116
  88. package/__tests__/coverage/src/domain/entities/security-context.ts.html +0 -604
  89. package/__tests__/coverage/src/domain/services/index.html +0 -116
  90. package/__tests__/coverage/src/domain/services/security-domain-service.ts.html +0 -973
  91. package/__tests__/coverage/src/index.html +0 -206
  92. package/__tests__/coverage/src/input-validator.ts.html +0 -1483
  93. package/__tests__/coverage/src/password-hasher.ts.html +0 -895
  94. package/__tests__/coverage/src/path-validator.ts.html +0 -1660
  95. package/__tests__/coverage/src/safe-executor.ts.html +0 -1660
  96. package/__tests__/coverage/src/token-generator.ts.html +0 -1474
@@ -1,368 +1,368 @@
1
- /**
2
- * Credential Generator - CVE-3 Remediation
3
- *
4
- * Fixes hardcoded default credentials by providing secure random
5
- * credential generation for installation and runtime.
6
- *
7
- * Security Properties:
8
- * - Uses crypto.randomBytes for cryptographically secure randomness
9
- * - Configurable entropy levels
10
- * - No hardcoded defaults stored in code
11
- * - Secure credential storage recommendations
12
- *
13
- * @module v3/security/credential-generator
14
- */
15
-
16
- import { randomBytes, randomUUID } from 'crypto';
17
-
18
- export interface CredentialConfig {
19
- /**
20
- * Length of generated passwords.
21
- * Default: 32 characters
22
- */
23
- passwordLength?: number;
24
-
25
- /**
26
- * Length of generated API keys.
27
- * Default: 48 characters
28
- */
29
- apiKeyLength?: number;
30
-
31
- /**
32
- * Length of generated secrets (JWT, session, etc.).
33
- * Default: 64 characters
34
- */
35
- secretLength?: number;
36
-
37
- /**
38
- * Character set for password generation.
39
- * Default: alphanumeric + special
40
- */
41
- passwordCharset?: string;
42
-
43
- /**
44
- * Character set for API key generation.
45
- * Default: alphanumeric only (URL-safe)
46
- */
47
- apiKeyCharset?: string;
48
- }
49
-
50
- export interface GeneratedCredentials {
51
- adminPassword: string;
52
- servicePassword: string;
53
- jwtSecret: string;
54
- sessionSecret: string;
55
- encryptionKey: string;
56
- generatedAt: Date;
57
- expiresAt?: Date;
58
- }
59
-
60
- export interface ApiKeyCredential {
61
- key: string;
62
- prefix: string;
63
- keyId: string;
64
- createdAt: Date;
65
- }
66
-
67
- export class CredentialGeneratorError extends Error {
68
- constructor(
69
- message: string,
70
- public readonly code: string,
71
- ) {
72
- super(message);
73
- this.name = 'CredentialGeneratorError';
74
- }
75
- }
76
-
77
- /**
78
- * Character sets for credential generation
79
- */
80
- const CHARSETS = {
81
- UPPERCASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
82
- LOWERCASE: 'abcdefghijklmnopqrstuvwxyz',
83
- DIGITS: '0123456789',
84
- SPECIAL: '!@#$%^&*()_+-=[]{}|;:,.<>?',
85
- // URL-safe characters for API keys
86
- URL_SAFE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
87
- // Hex characters for secrets
88
- HEX: '0123456789abcdef',
89
- } as const;
90
-
91
- /**
92
- * Secure credential generator.
93
- *
94
- * This class provides cryptographically secure credential generation
95
- * to replace hardcoded default credentials.
96
- *
97
- * @example
98
- * ```typescript
99
- * const generator = new CredentialGenerator();
100
- * const credentials = generator.generateInstallationCredentials();
101
- * // Store credentials securely (environment variables, secrets manager)
102
- * ```
103
- */
104
- export class CredentialGenerator {
105
- private readonly config: Required<CredentialConfig>;
106
-
107
- constructor(config: CredentialConfig = {}) {
108
- this.config = {
109
- passwordLength: config.passwordLength ?? 32,
110
- apiKeyLength: config.apiKeyLength ?? 48,
111
- secretLength: config.secretLength ?? 64,
112
- passwordCharset: config.passwordCharset ??
113
- CHARSETS.UPPERCASE + CHARSETS.LOWERCASE + CHARSETS.DIGITS + CHARSETS.SPECIAL,
114
- apiKeyCharset: config.apiKeyCharset ?? CHARSETS.URL_SAFE,
115
- };
116
-
117
- this.validateConfig();
118
- }
119
-
120
- /**
121
- * Validates configuration parameters.
122
- */
123
- private validateConfig(): void {
124
- if (this.config.passwordLength < 16) {
125
- throw new CredentialGeneratorError(
126
- 'Password length must be at least 16 characters',
127
- 'INVALID_PASSWORD_LENGTH'
128
- );
129
- }
130
-
131
- if (this.config.apiKeyLength < 32) {
132
- throw new CredentialGeneratorError(
133
- 'API key length must be at least 32 characters',
134
- 'INVALID_API_KEY_LENGTH'
135
- );
136
- }
137
-
138
- if (this.config.secretLength < 32) {
139
- throw new CredentialGeneratorError(
140
- 'Secret length must be at least 32 characters',
141
- 'INVALID_SECRET_LENGTH'
142
- );
143
- }
144
- }
145
-
146
- /**
147
- * Generates a cryptographically secure random string using rejection sampling
148
- * to eliminate modulo bias.
149
- *
150
- * @param length - Length of the string to generate
151
- * @param charset - Character set to use
152
- * @returns Random string
153
- */
154
- private generateSecureString(length: number, charset: string): string {
155
- const charsetLength = charset.length;
156
- const result = new Array(length);
157
-
158
- // Calculate rejection threshold to eliminate modulo bias
159
- // For a byte (0-255), we reject values >= (256 - (256 % charsetLength))
160
- // This ensures uniform distribution over charset indices
161
- const maxValidValue = 256 - (256 % charsetLength);
162
-
163
- let i = 0;
164
- while (i < length) {
165
- // Generate more random bytes than needed to reduce iterations
166
- const randomBuffer = randomBytes(Math.max(length - i, 16));
167
-
168
- for (let j = 0; j < randomBuffer.length && i < length; j++) {
169
- const randomValue = randomBuffer[j];
170
-
171
- // Rejection sampling: only accept values below threshold
172
- if (randomValue < maxValidValue) {
173
- result[i] = charset[randomValue % charsetLength];
174
- i++;
175
- }
176
- // Values >= maxValidValue are rejected to avoid bias
177
- }
178
- }
179
-
180
- return result.join('');
181
- }
182
-
183
- /**
184
- * Generates a secure random password.
185
- *
186
- * @param length - Optional custom length (default from config)
187
- * @returns Secure random password
188
- */
189
- generatePassword(length?: number): string {
190
- const len = length ?? this.config.passwordLength;
191
-
192
- // Ensure password contains at least one of each required character type
193
- const password = this.generateSecureString(len, this.config.passwordCharset);
194
-
195
- // Validate the generated password meets requirements
196
- if (!this.hasRequiredCharacterTypes(password)) {
197
- // Regenerate if requirements not met (rare case)
198
- return this.generatePassword(length);
199
- }
200
-
201
- return password;
202
- }
203
-
204
- /**
205
- * Checks if password has required character types.
206
- */
207
- private hasRequiredCharacterTypes(password: string): boolean {
208
- const hasUppercase = /[A-Z]/.test(password);
209
- const hasLowercase = /[a-z]/.test(password);
210
- const hasDigit = /\d/.test(password);
211
- const hasSpecial = /[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(password);
212
-
213
- return hasUppercase && hasLowercase && hasDigit && hasSpecial;
214
- }
215
-
216
- /**
217
- * Generates a secure API key.
218
- *
219
- * @param prefix - Optional prefix for the key (e.g., 'cf_')
220
- * @returns API key credential with metadata
221
- */
222
- generateApiKey(prefix = 'cf_'): ApiKeyCredential {
223
- const keyBody = this.generateSecureString(
224
- this.config.apiKeyLength - prefix.length,
225
- this.config.apiKeyCharset
226
- );
227
-
228
- const key = `${prefix}${keyBody}`;
229
- const keyId = randomUUID();
230
-
231
- return {
232
- key,
233
- prefix,
234
- keyId,
235
- createdAt: new Date(),
236
- };
237
- }
238
-
239
- /**
240
- * Generates a secure secret for JWT, sessions, etc.
241
- *
242
- * @param length - Optional custom length (default from config)
243
- * @returns Hex-encoded secret
244
- */
245
- generateSecret(length?: number): string {
246
- const len = length ?? this.config.secretLength;
247
- // Generate raw bytes and encode as hex for consistent storage
248
- return randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
249
- }
250
-
251
- /**
252
- * Generates an encryption key suitable for AES-256.
253
- *
254
- * @returns 32-byte key encoded as hex (64 characters)
255
- */
256
- generateEncryptionKey(): string {
257
- return randomBytes(32).toString('hex');
258
- }
259
-
260
- /**
261
- * Generates a complete set of installation credentials.
262
- *
263
- * These should be stored securely (environment variables,
264
- * secrets manager, etc.) and NEVER committed to version control.
265
- *
266
- * @param expirationDays - Optional expiration period in days
267
- * @returns Complete credential set
268
- */
269
- generateInstallationCredentials(expirationDays?: number): GeneratedCredentials {
270
- const now = new Date();
271
- const expiresAt = expirationDays
272
- ? new Date(now.getTime() + expirationDays * 24 * 60 * 60 * 1000)
273
- : undefined;
274
-
275
- return {
276
- adminPassword: this.generatePassword(),
277
- servicePassword: this.generatePassword(),
278
- jwtSecret: this.generateSecret(64),
279
- sessionSecret: this.generateSecret(64),
280
- encryptionKey: this.generateEncryptionKey(),
281
- generatedAt: now,
282
- expiresAt,
283
- };
284
- }
285
-
286
- /**
287
- * Generates a secure session token.
288
- *
289
- * @returns URL-safe session token
290
- */
291
- generateSessionToken(): string {
292
- return this.generateSecureString(64, CHARSETS.URL_SAFE);
293
- }
294
-
295
- /**
296
- * Generates a secure CSRF token.
297
- *
298
- * @returns CSRF token
299
- */
300
- generateCsrfToken(): string {
301
- return randomBytes(32).toString('base64url');
302
- }
303
-
304
- /**
305
- * Generates a secure nonce for one-time use.
306
- *
307
- * @returns Unique nonce value
308
- */
309
- generateNonce(): string {
310
- return randomBytes(16).toString('hex');
311
- }
312
-
313
- /**
314
- * Creates a setup script output for secure credential deployment.
315
- *
316
- * @param credentials - Generated credentials
317
- * @returns Environment variable export script
318
- */
319
- createEnvScript(credentials: GeneratedCredentials): string {
320
- return `# Claude Flow V3 - Generated Credentials
321
- # Generated: ${credentials.generatedAt.toISOString()}
322
- # IMPORTANT: Store these securely and delete this file after use
323
-
324
- export CLAUDE_FLOW_ADMIN_PASSWORD="${credentials.adminPassword}"
325
- export CLAUDE_FLOW_SERVICE_PASSWORD="${credentials.servicePassword}"
326
- export CLAUDE_FLOW_JWT_SECRET="${credentials.jwtSecret}"
327
- export CLAUDE_FLOW_SESSION_SECRET="${credentials.sessionSecret}"
328
- export CLAUDE_FLOW_ENCRYPTION_KEY="${credentials.encryptionKey}"
329
- `;
330
- }
331
-
332
- /**
333
- * Creates a JSON configuration output for secure credential deployment.
334
- *
335
- * @param credentials - Generated credentials
336
- * @returns JSON configuration (for secrets manager import)
337
- */
338
- createJsonConfig(credentials: GeneratedCredentials): string {
339
- return JSON.stringify({
340
- 'claude-flow/admin-password': credentials.adminPassword,
341
- 'claude-flow/service-password': credentials.servicePassword,
342
- 'claude-flow/jwt-secret': credentials.jwtSecret,
343
- 'claude-flow/session-secret': credentials.sessionSecret,
344
- 'claude-flow/encryption-key': credentials.encryptionKey,
345
- 'claude-flow/generated-at': credentials.generatedAt.toISOString(),
346
- 'claude-flow/expires-at': credentials.expiresAt?.toISOString() ?? null,
347
- }, null, 2);
348
- }
349
- }
350
-
351
- /**
352
- * Factory function to create a production credential generator.
353
- *
354
- * @returns Configured CredentialGenerator instance
355
- */
356
- export function createCredentialGenerator(): CredentialGenerator {
357
- return new CredentialGenerator();
358
- }
359
-
360
- /**
361
- * Quick credential generation for CLI usage.
362
- *
363
- * @returns Generated installation credentials
364
- */
365
- export function generateCredentials(): GeneratedCredentials {
366
- const generator = new CredentialGenerator();
367
- return generator.generateInstallationCredentials();
368
- }
1
+ /**
2
+ * Credential Generator - CVE-3 Remediation
3
+ *
4
+ * Fixes hardcoded default credentials by providing secure random
5
+ * credential generation for installation and runtime.
6
+ *
7
+ * Security Properties:
8
+ * - Uses crypto.randomBytes for cryptographically secure randomness
9
+ * - Configurable entropy levels
10
+ * - No hardcoded defaults stored in code
11
+ * - Secure credential storage recommendations
12
+ *
13
+ * @module v3/security/credential-generator
14
+ */
15
+
16
+ import { randomBytes, randomUUID } from 'crypto';
17
+
18
+ export interface CredentialConfig {
19
+ /**
20
+ * Length of generated passwords.
21
+ * Default: 32 characters
22
+ */
23
+ passwordLength?: number;
24
+
25
+ /**
26
+ * Length of generated API keys.
27
+ * Default: 48 characters
28
+ */
29
+ apiKeyLength?: number;
30
+
31
+ /**
32
+ * Length of generated secrets (JWT, session, etc.).
33
+ * Default: 64 characters
34
+ */
35
+ secretLength?: number;
36
+
37
+ /**
38
+ * Character set for password generation.
39
+ * Default: alphanumeric + special
40
+ */
41
+ passwordCharset?: string;
42
+
43
+ /**
44
+ * Character set for API key generation.
45
+ * Default: alphanumeric only (URL-safe)
46
+ */
47
+ apiKeyCharset?: string;
48
+ }
49
+
50
+ export interface GeneratedCredentials {
51
+ adminPassword: string;
52
+ servicePassword: string;
53
+ jwtSecret: string;
54
+ sessionSecret: string;
55
+ encryptionKey: string;
56
+ generatedAt: Date;
57
+ expiresAt?: Date;
58
+ }
59
+
60
+ export interface ApiKeyCredential {
61
+ key: string;
62
+ prefix: string;
63
+ keyId: string;
64
+ createdAt: Date;
65
+ }
66
+
67
+ export class CredentialGeneratorError extends Error {
68
+ constructor(
69
+ message: string,
70
+ public readonly code: string,
71
+ ) {
72
+ super(message);
73
+ this.name = 'CredentialGeneratorError';
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Character sets for credential generation
79
+ */
80
+ const CHARSETS = {
81
+ UPPERCASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
82
+ LOWERCASE: 'abcdefghijklmnopqrstuvwxyz',
83
+ DIGITS: '0123456789',
84
+ SPECIAL: '!@#$%^&*()_+-=[]{}|;:,.<>?',
85
+ // URL-safe characters for API keys
86
+ URL_SAFE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
87
+ // Hex characters for secrets
88
+ HEX: '0123456789abcdef',
89
+ } as const;
90
+
91
+ /**
92
+ * Secure credential generator.
93
+ *
94
+ * This class provides cryptographically secure credential generation
95
+ * to replace hardcoded default credentials.
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const generator = new CredentialGenerator();
100
+ * const credentials = generator.generateInstallationCredentials();
101
+ * // Store credentials securely (environment variables, secrets manager)
102
+ * ```
103
+ */
104
+ export class CredentialGenerator {
105
+ private readonly config: Required<CredentialConfig>;
106
+
107
+ constructor(config: CredentialConfig = {}) {
108
+ this.config = {
109
+ passwordLength: config.passwordLength ?? 32,
110
+ apiKeyLength: config.apiKeyLength ?? 48,
111
+ secretLength: config.secretLength ?? 64,
112
+ passwordCharset: config.passwordCharset ??
113
+ CHARSETS.UPPERCASE + CHARSETS.LOWERCASE + CHARSETS.DIGITS + CHARSETS.SPECIAL,
114
+ apiKeyCharset: config.apiKeyCharset ?? CHARSETS.URL_SAFE,
115
+ };
116
+
117
+ this.validateConfig();
118
+ }
119
+
120
+ /**
121
+ * Validates configuration parameters.
122
+ */
123
+ private validateConfig(): void {
124
+ if (this.config.passwordLength < 16) {
125
+ throw new CredentialGeneratorError(
126
+ 'Password length must be at least 16 characters',
127
+ 'INVALID_PASSWORD_LENGTH'
128
+ );
129
+ }
130
+
131
+ if (this.config.apiKeyLength < 32) {
132
+ throw new CredentialGeneratorError(
133
+ 'API key length must be at least 32 characters',
134
+ 'INVALID_API_KEY_LENGTH'
135
+ );
136
+ }
137
+
138
+ if (this.config.secretLength < 32) {
139
+ throw new CredentialGeneratorError(
140
+ 'Secret length must be at least 32 characters',
141
+ 'INVALID_SECRET_LENGTH'
142
+ );
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Generates a cryptographically secure random string using rejection sampling
148
+ * to eliminate modulo bias.
149
+ *
150
+ * @param length - Length of the string to generate
151
+ * @param charset - Character set to use
152
+ * @returns Random string
153
+ */
154
+ private generateSecureString(length: number, charset: string): string {
155
+ const charsetLength = charset.length;
156
+ const result = new Array(length);
157
+
158
+ // Calculate rejection threshold to eliminate modulo bias
159
+ // For a byte (0-255), we reject values >= (256 - (256 % charsetLength))
160
+ // This ensures uniform distribution over charset indices
161
+ const maxValidValue = 256 - (256 % charsetLength);
162
+
163
+ let i = 0;
164
+ while (i < length) {
165
+ // Generate more random bytes than needed to reduce iterations
166
+ const randomBuffer = randomBytes(Math.max(length - i, 16));
167
+
168
+ for (let j = 0; j < randomBuffer.length && i < length; j++) {
169
+ const randomValue = randomBuffer[j];
170
+
171
+ // Rejection sampling: only accept values below threshold
172
+ if (randomValue < maxValidValue) {
173
+ result[i] = charset[randomValue % charsetLength];
174
+ i++;
175
+ }
176
+ // Values >= maxValidValue are rejected to avoid bias
177
+ }
178
+ }
179
+
180
+ return result.join('');
181
+ }
182
+
183
+ /**
184
+ * Generates a secure random password.
185
+ *
186
+ * @param length - Optional custom length (default from config)
187
+ * @returns Secure random password
188
+ */
189
+ generatePassword(length?: number): string {
190
+ const len = length ?? this.config.passwordLength;
191
+
192
+ // Ensure password contains at least one of each required character type
193
+ const password = this.generateSecureString(len, this.config.passwordCharset);
194
+
195
+ // Validate the generated password meets requirements
196
+ if (!this.hasRequiredCharacterTypes(password)) {
197
+ // Regenerate if requirements not met (rare case)
198
+ return this.generatePassword(length);
199
+ }
200
+
201
+ return password;
202
+ }
203
+
204
+ /**
205
+ * Checks if password has required character types.
206
+ */
207
+ private hasRequiredCharacterTypes(password: string): boolean {
208
+ const hasUppercase = /[A-Z]/.test(password);
209
+ const hasLowercase = /[a-z]/.test(password);
210
+ const hasDigit = /\d/.test(password);
211
+ const hasSpecial = /[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(password);
212
+
213
+ return hasUppercase && hasLowercase && hasDigit && hasSpecial;
214
+ }
215
+
216
+ /**
217
+ * Generates a secure API key.
218
+ *
219
+ * @param prefix - Optional prefix for the key (e.g., 'cf_')
220
+ * @returns API key credential with metadata
221
+ */
222
+ generateApiKey(prefix = 'cf_'): ApiKeyCredential {
223
+ const keyBody = this.generateSecureString(
224
+ this.config.apiKeyLength - prefix.length,
225
+ this.config.apiKeyCharset
226
+ );
227
+
228
+ const key = `${prefix}${keyBody}`;
229
+ const keyId = randomUUID();
230
+
231
+ return {
232
+ key,
233
+ prefix,
234
+ keyId,
235
+ createdAt: new Date(),
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Generates a secure secret for JWT, sessions, etc.
241
+ *
242
+ * @param length - Optional custom length (default from config)
243
+ * @returns Hex-encoded secret
244
+ */
245
+ generateSecret(length?: number): string {
246
+ const len = length ?? this.config.secretLength;
247
+ // Generate raw bytes and encode as hex for consistent storage
248
+ return randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
249
+ }
250
+
251
+ /**
252
+ * Generates an encryption key suitable for AES-256.
253
+ *
254
+ * @returns 32-byte key encoded as hex (64 characters)
255
+ */
256
+ generateEncryptionKey(): string {
257
+ return randomBytes(32).toString('hex');
258
+ }
259
+
260
+ /**
261
+ * Generates a complete set of installation credentials.
262
+ *
263
+ * These should be stored securely (environment variables,
264
+ * secrets manager, etc.) and NEVER committed to version control.
265
+ *
266
+ * @param expirationDays - Optional expiration period in days
267
+ * @returns Complete credential set
268
+ */
269
+ generateInstallationCredentials(expirationDays?: number): GeneratedCredentials {
270
+ const now = new Date();
271
+ const expiresAt = expirationDays
272
+ ? new Date(now.getTime() + expirationDays * 24 * 60 * 60 * 1000)
273
+ : undefined;
274
+
275
+ return {
276
+ adminPassword: this.generatePassword(),
277
+ servicePassword: this.generatePassword(),
278
+ jwtSecret: this.generateSecret(64),
279
+ sessionSecret: this.generateSecret(64),
280
+ encryptionKey: this.generateEncryptionKey(),
281
+ generatedAt: now,
282
+ expiresAt,
283
+ };
284
+ }
285
+
286
+ /**
287
+ * Generates a secure session token.
288
+ *
289
+ * @returns URL-safe session token
290
+ */
291
+ generateSessionToken(): string {
292
+ return this.generateSecureString(64, CHARSETS.URL_SAFE);
293
+ }
294
+
295
+ /**
296
+ * Generates a secure CSRF token.
297
+ *
298
+ * @returns CSRF token
299
+ */
300
+ generateCsrfToken(): string {
301
+ return randomBytes(32).toString('base64url');
302
+ }
303
+
304
+ /**
305
+ * Generates a secure nonce for one-time use.
306
+ *
307
+ * @returns Unique nonce value
308
+ */
309
+ generateNonce(): string {
310
+ return randomBytes(16).toString('hex');
311
+ }
312
+
313
+ /**
314
+ * Creates a setup script output for secure credential deployment.
315
+ *
316
+ * @param credentials - Generated credentials
317
+ * @returns Environment variable export script
318
+ */
319
+ createEnvScript(credentials: GeneratedCredentials): string {
320
+ return `# Claude Flow V3 - Generated Credentials
321
+ # Generated: ${credentials.generatedAt.toISOString()}
322
+ # IMPORTANT: Store these securely and delete this file after use
323
+
324
+ export CLAUDE_FLOW_ADMIN_PASSWORD="${credentials.adminPassword}"
325
+ export CLAUDE_FLOW_SERVICE_PASSWORD="${credentials.servicePassword}"
326
+ export CLAUDE_FLOW_JWT_SECRET="${credentials.jwtSecret}"
327
+ export CLAUDE_FLOW_SESSION_SECRET="${credentials.sessionSecret}"
328
+ export CLAUDE_FLOW_ENCRYPTION_KEY="${credentials.encryptionKey}"
329
+ `;
330
+ }
331
+
332
+ /**
333
+ * Creates a JSON configuration output for secure credential deployment.
334
+ *
335
+ * @param credentials - Generated credentials
336
+ * @returns JSON configuration (for secrets manager import)
337
+ */
338
+ createJsonConfig(credentials: GeneratedCredentials): string {
339
+ return JSON.stringify({
340
+ 'claude-flow/admin-password': credentials.adminPassword,
341
+ 'claude-flow/service-password': credentials.servicePassword,
342
+ 'claude-flow/jwt-secret': credentials.jwtSecret,
343
+ 'claude-flow/session-secret': credentials.sessionSecret,
344
+ 'claude-flow/encryption-key': credentials.encryptionKey,
345
+ 'claude-flow/generated-at': credentials.generatedAt.toISOString(),
346
+ 'claude-flow/expires-at': credentials.expiresAt?.toISOString() ?? null,
347
+ }, null, 2);
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Factory function to create a production credential generator.
353
+ *
354
+ * @returns Configured CredentialGenerator instance
355
+ */
356
+ export function createCredentialGenerator(): CredentialGenerator {
357
+ return new CredentialGenerator();
358
+ }
359
+
360
+ /**
361
+ * Quick credential generation for CLI usage.
362
+ *
363
+ * @returns Generated installation credentials
364
+ */
365
+ export function generateCredentials(): GeneratedCredentials {
366
+ const generator = new CredentialGenerator();
367
+ return generator.generateInstallationCredentials();
368
+ }