create-fluxstack 1.12.0 โ†’ 1.13.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 (82) hide show
  1. package/LLMD/INDEX.md +8 -1
  2. package/LLMD/agent.md +867 -0
  3. package/LLMD/config/environment-vars.md +30 -0
  4. package/LLMD/resources/live-auth.md +447 -0
  5. package/LLMD/resources/live-components.md +79 -21
  6. package/LLMD/resources/live-logging.md +158 -0
  7. package/LLMD/resources/live-upload.md +1 -1
  8. package/LLMD/resources/rest-auth.md +290 -0
  9. package/README.md +520 -340
  10. package/app/client/src/App.tsx +11 -0
  11. package/app/client/src/components/AppLayout.tsx +1 -0
  12. package/app/client/src/live/AuthDemo.tsx +332 -0
  13. package/app/client/src/live/RoomChatDemo.tsx +24 -105
  14. package/app/server/auth/AuthManager.ts +213 -0
  15. package/app/server/auth/DevAuthProvider.ts +66 -0
  16. package/app/server/auth/HashManager.ts +123 -0
  17. package/app/server/auth/JWTAuthProvider.example.ts +101 -0
  18. package/app/server/auth/RateLimiter.ts +106 -0
  19. package/app/server/auth/contracts.ts +192 -0
  20. package/app/server/auth/guards/SessionGuard.ts +167 -0
  21. package/app/server/auth/guards/TokenGuard.ts +202 -0
  22. package/app/server/auth/index.ts +174 -0
  23. package/app/server/auth/middleware.ts +163 -0
  24. package/app/server/auth/providers/InMemoryProvider.ts +162 -0
  25. package/app/server/auth/sessions/SessionManager.ts +164 -0
  26. package/app/server/cache/CacheManager.ts +81 -0
  27. package/app/server/cache/MemoryDriver.ts +112 -0
  28. package/app/server/cache/contracts.ts +49 -0
  29. package/app/server/cache/index.ts +42 -0
  30. package/app/server/index.ts +14 -0
  31. package/app/server/live/LiveAdminPanel.ts +173 -0
  32. package/app/server/live/LiveCounter.ts +1 -0
  33. package/app/server/live/LiveLocalCounter.ts +13 -8
  34. package/app/server/live/LiveProtectedChat.ts +150 -0
  35. package/app/server/live/LiveRoomChat.ts +45 -203
  36. package/app/server/routes/auth.routes.ts +278 -0
  37. package/app/server/routes/index.ts +2 -0
  38. package/config/index.ts +8 -0
  39. package/config/system/auth.config.ts +49 -0
  40. package/config/system/session.config.ts +33 -0
  41. package/core/client/LiveComponentsProvider.tsx +76 -5
  42. package/core/client/components/Live.tsx +2 -1
  43. package/core/client/hooks/useLiveComponent.ts +47 -4
  44. package/core/client/index.ts +2 -1
  45. package/core/framework/server.ts +36 -4
  46. package/core/plugins/built-in/live-components/commands/create-live-component.ts +15 -8
  47. package/core/plugins/built-in/monitoring/index.ts +10 -3
  48. package/core/plugins/built-in/vite/index.ts +95 -18
  49. package/core/plugins/config.ts +5 -4
  50. package/core/plugins/discovery.ts +11 -2
  51. package/core/plugins/manager.ts +11 -5
  52. package/core/plugins/module-resolver.ts +1 -1
  53. package/core/plugins/registry.ts +53 -25
  54. package/core/server/live/ComponentRegistry.ts +79 -24
  55. package/core/server/live/LiveComponentPerformanceMonitor.ts +9 -8
  56. package/core/server/live/LiveLogger.ts +111 -0
  57. package/core/server/live/LiveRoomManager.ts +5 -4
  58. package/core/server/live/StateSignature.ts +644 -643
  59. package/core/server/live/auth/LiveAuthContext.ts +71 -0
  60. package/core/server/live/auth/LiveAuthManager.ts +304 -0
  61. package/core/server/live/auth/index.ts +19 -0
  62. package/core/server/live/auth/types.ts +179 -0
  63. package/core/server/live/auto-generated-components.ts +8 -2
  64. package/core/server/live/index.ts +16 -0
  65. package/core/server/live/websocket-plugin.ts +92 -16
  66. package/core/templates/create-project.ts +0 -3
  67. package/core/types/types.ts +133 -13
  68. package/core/utils/index.ts +17 -17
  69. package/core/utils/logger/index.ts +5 -2
  70. package/core/utils/version.ts +1 -1
  71. package/package.json +1 -8
  72. package/plugins/crypto-auth/index.ts +6 -0
  73. package/plugins/crypto-auth/server/CryptoAuthLiveProvider.ts +58 -0
  74. package/plugins/crypto-auth/server/index.ts +24 -21
  75. package/rest-tests/README.md +57 -0
  76. package/rest-tests/auth-token.http +113 -0
  77. package/rest-tests/auth.http +112 -0
  78. package/rest-tests/rooms-token.http +69 -0
  79. package/rest-tests/users-token.http +62 -0
  80. package/.dockerignore +0 -81
  81. package/Dockerfile +0 -70
  82. package/LIVE_COMPONENTS_REVIEW.md +0 -781
@@ -1,644 +1,645 @@
1
- // ๐Ÿ” FluxStack Enhanced State Signature System - Advanced cryptographic validation with key rotation and compression
2
-
3
- import { createHmac, randomBytes, createCipheriv, createDecipheriv, scrypt } from 'crypto'
4
- import { promisify } from 'util'
5
- import { gzip, gunzip } from 'zlib'
6
-
7
- const scryptAsync = promisify(scrypt)
8
- const gzipAsync = promisify(gzip)
9
- const gunzipAsync = promisify(gunzip)
10
-
11
- export interface SignedState<T = any> {
12
- data: T
13
- signature: string
14
- timestamp: number
15
- componentId: string
16
- version: number
17
- keyId?: string // For key rotation
18
- compressed?: boolean // For state compression
19
- encrypted?: boolean // For sensitive data
20
- }
21
-
22
- export interface StateValidationResult {
23
- valid: boolean
24
- error?: string
25
- tampered?: boolean
26
- expired?: boolean
27
- keyRotated?: boolean
28
- }
29
-
30
- export interface StateBackup<T = any> {
31
- componentId: string
32
- state: T
33
- timestamp: number
34
- version: number
35
- checksum: string
36
- }
37
-
38
- export interface KeyRotationConfig {
39
- rotationInterval: number // milliseconds
40
- maxKeyAge: number // milliseconds
41
- keyRetentionCount: number // number of old keys to keep
42
- }
43
-
44
- export interface CompressionConfig {
45
- enabled: boolean
46
- threshold: number // bytes - compress if state is larger than this
47
- level: number // compression level 1-9
48
- }
49
-
50
- export class StateSignature {
51
- private static instance: StateSignature
52
- private currentKey: string
53
- private keyHistory: Map<string, { key: string; createdAt: number }> = new Map()
54
- private readonly maxAge = 24 * 60 * 60 * 1000 // 24 hours default
55
- private keyRotationConfig: KeyRotationConfig
56
- private compressionConfig: CompressionConfig
57
- private backups = new Map<string, StateBackup[]>() // componentId -> backups
58
- private migrationFunctions = new Map<string, (state: any) => any>() // version -> migration function
59
-
60
- constructor(secretKey?: string, options?: {
61
- keyRotation?: Partial<KeyRotationConfig>
62
- compression?: Partial<CompressionConfig>
63
- }) {
64
- this.currentKey = secretKey || this.generateSecretKey()
65
- this.keyHistory.set(this.getCurrentKeyId(), {
66
- key: this.currentKey,
67
- createdAt: Date.now()
68
- })
69
-
70
- this.keyRotationConfig = {
71
- rotationInterval: 7 * 24 * 60 * 60 * 1000, // 7 days
72
- maxKeyAge: 30 * 24 * 60 * 60 * 1000, // 30 days
73
- keyRetentionCount: 5,
74
- ...options?.keyRotation
75
- }
76
-
77
- this.compressionConfig = {
78
- enabled: true,
79
- threshold: 1024, // 1KB
80
- level: 6,
81
- ...options?.compression
82
- }
83
-
84
- this.setupKeyRotation()
85
- }
86
-
87
- public static getInstance(secretKey?: string, options?: {
88
- keyRotation?: Partial<KeyRotationConfig>
89
- compression?: Partial<CompressionConfig>
90
- }): StateSignature {
91
- if (!StateSignature.instance) {
92
- StateSignature.instance = new StateSignature(secretKey, options)
93
- }
94
- return StateSignature.instance
95
- }
96
-
97
- private generateSecretKey(): string {
98
- return randomBytes(32).toString('hex')
99
- }
100
-
101
- private getCurrentKeyId(): string {
102
- return createHmac('sha256', this.currentKey).update('keyid').digest('hex').substring(0, 8)
103
- }
104
-
105
- private setupKeyRotation(): void {
106
- // Rotate keys periodically
107
- setInterval(() => {
108
- this.rotateKey()
109
- }, this.keyRotationConfig.rotationInterval)
110
-
111
- // Cleanup old keys
112
- setInterval(() => {
113
- this.cleanupOldKeys()
114
- }, 24 * 60 * 60 * 1000) // Daily cleanup
115
- }
116
-
117
- private rotateKey(): void {
118
- const oldKeyId = this.getCurrentKeyId()
119
- this.currentKey = this.generateSecretKey()
120
- const newKeyId = this.getCurrentKeyId()
121
-
122
- this.keyHistory.set(newKeyId, {
123
- key: this.currentKey,
124
- createdAt: Date.now()
125
- })
126
-
127
- console.log(`๐Ÿ”„ Key rotated from ${oldKeyId} to ${newKeyId}`)
128
- }
129
-
130
- private cleanupOldKeys(): void {
131
- const now = Date.now()
132
- const keysToDelete: string[] = []
133
-
134
- for (const [keyId, keyData] of this.keyHistory) {
135
- const keyAge = now - keyData.createdAt
136
- if (keyAge > this.keyRotationConfig.maxKeyAge) {
137
- keysToDelete.push(keyId)
138
- }
139
- }
140
-
141
- // Keep at least the retention count of keys
142
- const sortedKeys = Array.from(this.keyHistory.entries())
143
- .sort((a, b) => b[1].createdAt - a[1].createdAt)
144
-
145
- if (sortedKeys.length > this.keyRotationConfig.keyRetentionCount) {
146
- const excessKeys = sortedKeys.slice(this.keyRotationConfig.keyRetentionCount)
147
- for (const [keyId] of excessKeys) {
148
- keysToDelete.push(keyId)
149
- }
150
- }
151
-
152
- for (const keyId of keysToDelete) {
153
- this.keyHistory.delete(keyId)
154
- }
155
-
156
- if (keysToDelete.length > 0) {
157
- console.log(`๐Ÿงน Cleaned up ${keysToDelete.length} old keys`)
158
- }
159
- }
160
-
161
- private getKeyById(keyId: string): string | null {
162
- const keyData = this.keyHistory.get(keyId)
163
- return keyData ? keyData.key : null
164
- }
165
-
166
- /**
167
- * Sign component state with enhanced security, compression, and encryption
168
- */
169
- public async signState<T>(
170
- componentId: string,
171
- data: T,
172
- version: number = 1,
173
- options?: {
174
- compress?: boolean
175
- encrypt?: boolean
176
- backup?: boolean
177
- }
178
- ): Promise<SignedState<T>> {
179
- const timestamp = Date.now()
180
- const keyId = this.getCurrentKeyId()
181
-
182
- let processedData = data
183
- let compressed = false
184
- let encrypted = false
185
-
186
- try {
187
- // Serialize data for processing
188
- const serializedData = JSON.stringify(data)
189
-
190
- // Compress if enabled and data is large enough
191
- if (this.compressionConfig.enabled &&
192
- (options?.compress !== false) &&
193
- Buffer.byteLength(serializedData, 'utf8') > this.compressionConfig.threshold) {
194
-
195
- const compressedBuffer = await gzipAsync(Buffer.from(serializedData, 'utf8'))
196
- processedData = compressedBuffer.toString('base64') as any
197
- compressed = true
198
-
199
- console.log(`๐Ÿ—œ๏ธ State compressed: ${Buffer.byteLength(serializedData, 'utf8')} -> ${compressedBuffer.length} bytes`)
200
- }
201
-
202
- // Encrypt sensitive data if requested
203
- if (options?.encrypt) {
204
- const encryptedData = await this.encryptData(processedData)
205
- processedData = encryptedData as any
206
- encrypted = true
207
-
208
- console.log('๐Ÿ”’ State encrypted for component:', componentId)
209
- }
210
-
211
- // Create payload for signing
212
- const payload = {
213
- data: processedData,
214
- componentId,
215
- timestamp,
216
- version,
217
- keyId,
218
- compressed,
219
- encrypted
220
- }
221
-
222
- // Generate signature with current key
223
- const signature = this.createSignature(payload)
224
-
225
- // Create backup if requested
226
- if (options?.backup) {
227
- await this.createStateBackup(componentId, data, version)
228
- }
229
-
230
- console.log('๐Ÿ” State signed:', {
231
- componentId,
232
- timestamp,
233
- version,
234
- keyId,
235
- compressed,
236
- encrypted,
237
- signature: signature.substring(0, 16) + '...'
238
- })
239
-
240
- return {
241
- data: processedData,
242
- signature,
243
- timestamp,
244
- componentId,
245
- version,
246
- keyId,
247
- compressed,
248
- encrypted
249
- }
250
-
251
- } catch (error) {
252
- console.error('โŒ Failed to sign state:', error)
253
- throw new Error(`State signing failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
254
- }
255
- }
256
-
257
- /**
258
- * Validate signed state integrity with enhanced security checks
259
- */
260
- public async validateState<T>(signedState: SignedState<T>, maxAge?: number): Promise<StateValidationResult> {
261
- const { data, signature, timestamp, componentId, version, keyId, compressed, encrypted } = signedState
262
-
263
- try {
264
- // Check timestamp (prevent replay attacks)
265
- const age = Date.now() - timestamp
266
- const ageLimit = maxAge || this.maxAge
267
-
268
- if (age > ageLimit) {
269
- return {
270
- valid: false,
271
- error: 'State signature expired',
272
- expired: true
273
- }
274
- }
275
-
276
- // Determine which key to use for validation
277
- let validationKey = this.currentKey
278
- let keyRotated = false
279
-
280
- if (keyId) {
281
- const historicalKey = this.getKeyById(keyId)
282
- if (historicalKey) {
283
- validationKey = historicalKey
284
- keyRotated = keyId !== this.getCurrentKeyId()
285
- } else {
286
- return {
287
- valid: false,
288
- error: 'Signing key not found or expired',
289
- keyRotated: true
290
- }
291
- }
292
- }
293
-
294
- // Recreate payload for verification
295
- const payload = {
296
- data,
297
- componentId,
298
- timestamp,
299
- version,
300
- keyId,
301
- compressed,
302
- encrypted
303
- }
304
-
305
- // Verify signature with appropriate key
306
- const expectedSignature = this.createSignature(payload, validationKey)
307
-
308
- if (!this.constantTimeEquals(signature, expectedSignature)) {
309
- console.warn('โš ๏ธ State signature mismatch:', {
310
- componentId,
311
- expected: expectedSignature.substring(0, 16) + '...',
312
- received: signature.substring(0, 16) + '...'
313
- })
314
-
315
- return {
316
- valid: false,
317
- error: 'State signature invalid - possible tampering',
318
- tampered: true
319
- }
320
- }
321
-
322
- console.log('โœ… State signature valid:', {
323
- componentId,
324
- age: `${Math.round(age / 1000)}s`,
325
- version
326
- })
327
-
328
- return { valid: true }
329
-
330
- } catch (error: any) {
331
- return {
332
- valid: false,
333
- error: `Validation error: ${error.message}`
334
- }
335
- }
336
- }
337
-
338
- /**
339
- * Create HMAC signature for payload using specified key
340
- */
341
- private createSignature(payload: any, key?: string): string {
342
- // Stringify deterministically (sorted keys)
343
- const normalizedPayload = JSON.stringify(payload, Object.keys(payload).sort())
344
-
345
- return createHmac('sha256', key || this.currentKey)
346
- .update(normalizedPayload)
347
- .digest('hex')
348
- }
349
-
350
- /**
351
- * Encrypt sensitive data
352
- */
353
- private async encryptData<T>(data: T): Promise<string> {
354
- try {
355
- const serializedData = JSON.stringify(data)
356
- const key = await scryptAsync(this.currentKey, 'salt', 32) as Buffer
357
- const iv = randomBytes(16)
358
- const cipher = createCipheriv('aes-256-cbc', key, iv)
359
-
360
- let encrypted = cipher.update(serializedData, 'utf8', 'hex')
361
- encrypted += cipher.final('hex')
362
-
363
- return iv.toString('hex') + ':' + encrypted
364
- } catch (error) {
365
- throw new Error(`Encryption failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
366
- }
367
- }
368
-
369
- /**
370
- * Decrypt sensitive data
371
- */
372
- private async decryptData(encryptedData: string, key?: string): Promise<any> {
373
- try {
374
- const [ivHex, encrypted] = encryptedData.split(':')
375
- const iv = Buffer.from(ivHex, 'hex')
376
- const derivedKey = await scryptAsync(key || this.currentKey, 'salt', 32) as Buffer
377
- const decipher = createDecipheriv('aes-256-cbc', derivedKey, iv)
378
-
379
- let decrypted = decipher.update(encrypted, 'hex', 'utf8')
380
- decrypted += decipher.final('utf8')
381
-
382
- return JSON.parse(decrypted)
383
- } catch (error) {
384
- throw new Error(`Decryption failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
385
- }
386
- }
387
-
388
- /**
389
- * Decompress state data
390
- */
391
- private async decompressData(compressedData: string): Promise<any> {
392
- try {
393
- const compressedBuffer = Buffer.from(compressedData, 'base64')
394
- const decompressedBuffer = await gunzipAsync(compressedBuffer)
395
- return JSON.parse(decompressedBuffer.toString('utf8'))
396
- } catch (error) {
397
- throw new Error(`Decompression failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
398
- }
399
- }
400
-
401
- /**
402
- * Create state backup
403
- */
404
- private async createStateBackup<T>(componentId: string, state: T, version: number): Promise<void> {
405
- try {
406
- const backup: StateBackup<T> = {
407
- componentId,
408
- state,
409
- timestamp: Date.now(),
410
- version,
411
- checksum: createHmac('sha256', this.currentKey).update(JSON.stringify(state)).digest('hex')
412
- }
413
-
414
- let backups = this.backups.get(componentId) || []
415
- backups.push(backup)
416
-
417
- // Keep only last 10 backups per component
418
- if (backups.length > 10) {
419
- backups = backups.slice(-10)
420
- }
421
-
422
- this.backups.set(componentId, backups)
423
-
424
- console.log(`๐Ÿ’พ State backup created for component ${componentId} v${version}`)
425
- } catch (error) {
426
- console.error(`โŒ Failed to create backup for component ${componentId}:`, error)
427
- }
428
- }
429
-
430
- /**
431
- * Constant-time string comparison to prevent timing attacks
432
- */
433
- private constantTimeEquals(a: string, b: string): boolean {
434
- if (a.length !== b.length) {
435
- return false
436
- }
437
-
438
- let result = 0
439
- for (let i = 0; i < a.length; i++) {
440
- result |= a.charCodeAt(i) ^ b.charCodeAt(i)
441
- }
442
-
443
- return result === 0
444
- }
445
-
446
- /**
447
- * Extract and process signed state data (decompression, decryption)
448
- */
449
- public async extractData<T>(signedState: SignedState<T>): Promise<T> {
450
- let data = signedState.data
451
-
452
- try {
453
- // Decrypt if encrypted
454
- if (signedState.encrypted) {
455
- const keyToUse = signedState.keyId ? this.getKeyById(signedState.keyId) : this.currentKey
456
- if (!keyToUse) {
457
- throw new Error('Decryption key not available')
458
- }
459
- data = await this.decryptData(data as string, keyToUse)
460
- }
461
-
462
- // Decompress if compressed
463
- if (signedState.compressed) {
464
- data = await this.decompressData(data as string)
465
- }
466
-
467
- return data
468
- } catch (error) {
469
- console.error('โŒ Failed to extract state data:', error)
470
- throw error
471
- }
472
- }
473
-
474
- /**
475
- * Update signature for new state version with enhanced options
476
- */
477
- public async updateSignature<T>(
478
- signedState: SignedState<T>,
479
- newData: T,
480
- options?: {
481
- compress?: boolean
482
- encrypt?: boolean
483
- backup?: boolean
484
- }
485
- ): Promise<SignedState<T>> {
486
- return this.signState(
487
- signedState.componentId,
488
- newData,
489
- signedState.version + 1,
490
- options
491
- )
492
- }
493
-
494
- /**
495
- * Register state migration function
496
- */
497
- public registerMigration(fromVersion: string, toVersion: string, migrationFn: (state: any) => any): void {
498
- const key = `${fromVersion}->${toVersion}`
499
- this.migrationFunctions.set(key, migrationFn)
500
- console.log(`๐Ÿ“‹ Registered migration: ${key}`)
501
- }
502
-
503
- /**
504
- * Migrate state to new version
505
- */
506
- public async migrateState<T>(signedState: SignedState<T>, targetVersion: string): Promise<SignedState<T> | null> {
507
- const currentVersion = signedState.version.toString()
508
- const migrationKey = `${currentVersion}->${targetVersion}`
509
-
510
- const migrationFn = this.migrationFunctions.get(migrationKey)
511
- if (!migrationFn) {
512
- console.warn(`โš ๏ธ No migration function found for ${migrationKey}`)
513
- return null
514
- }
515
-
516
- try {
517
- // Extract current data
518
- const currentData = await this.extractData(signedState)
519
-
520
- // Apply migration
521
- const migratedData = migrationFn(currentData)
522
-
523
- // Create new signed state
524
- const newSignedState = await this.signState(
525
- signedState.componentId,
526
- migratedData,
527
- parseInt(targetVersion),
528
- {
529
- compress: signedState.compressed,
530
- encrypt: signedState.encrypted,
531
- backup: true
532
- }
533
- )
534
-
535
- console.log(`โœ… State migrated from v${currentVersion} to v${targetVersion} for component ${signedState.componentId}`)
536
- return newSignedState
537
-
538
- } catch (error) {
539
- console.error(`โŒ State migration failed for ${migrationKey}:`, error)
540
- return null
541
- }
542
- }
543
-
544
- /**
545
- * Recover state from backup
546
- */
547
- public recoverStateFromBackup<T>(componentId: string, version?: number): StateBackup<T> | null {
548
- const backups = this.backups.get(componentId)
549
- if (!backups || backups.length === 0) {
550
- return null
551
- }
552
-
553
- if (version !== undefined) {
554
- // Find specific version
555
- return backups.find(backup => backup.version === version) || null
556
- } else {
557
- // Return latest backup
558
- return backups[backups.length - 1] || null
559
- }
560
- }
561
-
562
- /**
563
- * Get all backups for a component
564
- */
565
- public getComponentBackups(componentId: string): StateBackup[] {
566
- return this.backups.get(componentId) || []
567
- }
568
-
569
- /**
570
- * Verify backup integrity
571
- */
572
- public verifyBackup<T>(backup: StateBackup<T>): boolean {
573
- try {
574
- const expectedChecksum = createHmac('sha256', this.currentKey)
575
- .update(JSON.stringify(backup.state))
576
- .digest('hex')
577
-
578
- return this.constantTimeEquals(backup.checksum, expectedChecksum)
579
- } catch {
580
- return false
581
- }
582
- }
583
-
584
- /**
585
- * Clean up old backups
586
- */
587
- public cleanupBackups(maxAge: number = 7 * 24 * 60 * 60 * 1000): void {
588
- const now = Date.now()
589
- let totalCleaned = 0
590
-
591
- for (const [componentId, backups] of this.backups) {
592
- const validBackups = backups.filter(backup => {
593
- const age = now - backup.timestamp
594
- return age <= maxAge
595
- })
596
-
597
- const cleaned = backups.length - validBackups.length
598
- totalCleaned += cleaned
599
-
600
- if (validBackups.length === 0) {
601
- this.backups.delete(componentId)
602
- } else {
603
- this.backups.set(componentId, validBackups)
604
- }
605
- }
606
-
607
- if (totalCleaned > 0) {
608
- console.log(`๐Ÿงน Cleaned up ${totalCleaned} old state backups`)
609
- }
610
- }
611
-
612
- /**
613
- * Get server's signature info for debugging
614
- */
615
- public getSignatureInfo() {
616
- return {
617
- algorithm: 'HMAC-SHA256',
618
- keyLength: this.currentKey.length,
619
- maxAge: this.maxAge,
620
- keyPreview: this.currentKey.substring(0, 8) + '...',
621
- currentKeyId: this.getCurrentKeyId(),
622
- keyHistoryCount: this.keyHistory.size,
623
- compressionEnabled: this.compressionConfig.enabled,
624
- rotationInterval: this.keyRotationConfig.rotationInterval
625
- }
626
- }
627
- }
628
-
629
- // Global instance with enhanced configuration
630
- export const stateSignature = StateSignature.getInstance(
631
- process.env.FLUXSTACK_STATE_SECRET || undefined,
632
- {
633
- keyRotation: {
634
- rotationInterval: parseInt(process.env.FLUXSTACK_KEY_ROTATION_INTERVAL || '604800000'), // 7 days
635
- maxKeyAge: parseInt(process.env.FLUXSTACK_MAX_KEY_AGE || '2592000000'), // 30 days
636
- keyRetentionCount: parseInt(process.env.FLUXSTACK_KEY_RETENTION_COUNT || '5')
637
- },
638
- compression: {
639
- enabled: process.env.FLUXSTACK_COMPRESSION_ENABLED !== 'false',
640
- threshold: parseInt(process.env.FLUXSTACK_COMPRESSION_THRESHOLD || '1024'), // 1KB
641
- level: parseInt(process.env.FLUXSTACK_COMPRESSION_LEVEL || '6')
642
- }
643
- }
1
+ // ๐Ÿ” FluxStack Enhanced State Signature System - Advanced cryptographic validation with key rotation and compression
2
+
3
+ import { createHmac, randomBytes, createCipheriv, createDecipheriv, scrypt } from 'crypto'
4
+ import { promisify } from 'util'
5
+ import { gzip, gunzip } from 'zlib'
6
+ import { liveLog, liveWarn } from './LiveLogger'
7
+
8
+ const scryptAsync = promisify(scrypt)
9
+ const gzipAsync = promisify(gzip)
10
+ const gunzipAsync = promisify(gunzip)
11
+
12
+ export interface SignedState<T = any> {
13
+ data: T
14
+ signature: string
15
+ timestamp: number
16
+ componentId: string
17
+ version: number
18
+ keyId?: string // For key rotation
19
+ compressed?: boolean // For state compression
20
+ encrypted?: boolean // For sensitive data
21
+ }
22
+
23
+ export interface StateValidationResult {
24
+ valid: boolean
25
+ error?: string
26
+ tampered?: boolean
27
+ expired?: boolean
28
+ keyRotated?: boolean
29
+ }
30
+
31
+ export interface StateBackup<T = any> {
32
+ componentId: string
33
+ state: T
34
+ timestamp: number
35
+ version: number
36
+ checksum: string
37
+ }
38
+
39
+ export interface KeyRotationConfig {
40
+ rotationInterval: number // milliseconds
41
+ maxKeyAge: number // milliseconds
42
+ keyRetentionCount: number // number of old keys to keep
43
+ }
44
+
45
+ export interface CompressionConfig {
46
+ enabled: boolean
47
+ threshold: number // bytes - compress if state is larger than this
48
+ level: number // compression level 1-9
49
+ }
50
+
51
+ export class StateSignature {
52
+ private static instance: StateSignature
53
+ private currentKey: string
54
+ private keyHistory: Map<string, { key: string; createdAt: number }> = new Map()
55
+ private readonly maxAge = 24 * 60 * 60 * 1000 // 24 hours default
56
+ private keyRotationConfig: KeyRotationConfig
57
+ private compressionConfig: CompressionConfig
58
+ private backups = new Map<string, StateBackup[]>() // componentId -> backups
59
+ private migrationFunctions = new Map<string, (state: any) => any>() // version -> migration function
60
+
61
+ constructor(secretKey?: string, options?: {
62
+ keyRotation?: Partial<KeyRotationConfig>
63
+ compression?: Partial<CompressionConfig>
64
+ }) {
65
+ this.currentKey = secretKey || this.generateSecretKey()
66
+ this.keyHistory.set(this.getCurrentKeyId(), {
67
+ key: this.currentKey,
68
+ createdAt: Date.now()
69
+ })
70
+
71
+ this.keyRotationConfig = {
72
+ rotationInterval: 7 * 24 * 60 * 60 * 1000, // 7 days
73
+ maxKeyAge: 30 * 24 * 60 * 60 * 1000, // 30 days
74
+ keyRetentionCount: 5,
75
+ ...options?.keyRotation
76
+ }
77
+
78
+ this.compressionConfig = {
79
+ enabled: true,
80
+ threshold: 1024, // 1KB
81
+ level: 6,
82
+ ...options?.compression
83
+ }
84
+
85
+ this.setupKeyRotation()
86
+ }
87
+
88
+ public static getInstance(secretKey?: string, options?: {
89
+ keyRotation?: Partial<KeyRotationConfig>
90
+ compression?: Partial<CompressionConfig>
91
+ }): StateSignature {
92
+ if (!StateSignature.instance) {
93
+ StateSignature.instance = new StateSignature(secretKey, options)
94
+ }
95
+ return StateSignature.instance
96
+ }
97
+
98
+ private generateSecretKey(): string {
99
+ return randomBytes(32).toString('hex')
100
+ }
101
+
102
+ private getCurrentKeyId(): string {
103
+ return createHmac('sha256', this.currentKey).update('keyid').digest('hex').substring(0, 8)
104
+ }
105
+
106
+ private setupKeyRotation(): void {
107
+ // Rotate keys periodically
108
+ setInterval(() => {
109
+ this.rotateKey()
110
+ }, this.keyRotationConfig.rotationInterval)
111
+
112
+ // Cleanup old keys
113
+ setInterval(() => {
114
+ this.cleanupOldKeys()
115
+ }, 24 * 60 * 60 * 1000) // Daily cleanup
116
+ }
117
+
118
+ private rotateKey(): void {
119
+ const oldKeyId = this.getCurrentKeyId()
120
+ this.currentKey = this.generateSecretKey()
121
+ const newKeyId = this.getCurrentKeyId()
122
+
123
+ this.keyHistory.set(newKeyId, {
124
+ key: this.currentKey,
125
+ createdAt: Date.now()
126
+ })
127
+
128
+ liveLog('state', null, `๐Ÿ”„ Key rotated from ${oldKeyId} to ${newKeyId}`)
129
+ }
130
+
131
+ private cleanupOldKeys(): void {
132
+ const now = Date.now()
133
+ const keysToDelete: string[] = []
134
+
135
+ for (const [keyId, keyData] of this.keyHistory) {
136
+ const keyAge = now - keyData.createdAt
137
+ if (keyAge > this.keyRotationConfig.maxKeyAge) {
138
+ keysToDelete.push(keyId)
139
+ }
140
+ }
141
+
142
+ // Keep at least the retention count of keys
143
+ const sortedKeys = Array.from(this.keyHistory.entries())
144
+ .sort((a, b) => b[1].createdAt - a[1].createdAt)
145
+
146
+ if (sortedKeys.length > this.keyRotationConfig.keyRetentionCount) {
147
+ const excessKeys = sortedKeys.slice(this.keyRotationConfig.keyRetentionCount)
148
+ for (const [keyId] of excessKeys) {
149
+ keysToDelete.push(keyId)
150
+ }
151
+ }
152
+
153
+ for (const keyId of keysToDelete) {
154
+ this.keyHistory.delete(keyId)
155
+ }
156
+
157
+ if (keysToDelete.length > 0) {
158
+ liveLog('state', null, `๐Ÿงน Cleaned up ${keysToDelete.length} old keys`)
159
+ }
160
+ }
161
+
162
+ private getKeyById(keyId: string): string | null {
163
+ const keyData = this.keyHistory.get(keyId)
164
+ return keyData ? keyData.key : null
165
+ }
166
+
167
+ /**
168
+ * Sign component state with enhanced security, compression, and encryption
169
+ */
170
+ public async signState<T>(
171
+ componentId: string,
172
+ data: T,
173
+ version: number = 1,
174
+ options?: {
175
+ compress?: boolean
176
+ encrypt?: boolean
177
+ backup?: boolean
178
+ }
179
+ ): Promise<SignedState<T>> {
180
+ const timestamp = Date.now()
181
+ const keyId = this.getCurrentKeyId()
182
+
183
+ let processedData = data
184
+ let compressed = false
185
+ let encrypted = false
186
+
187
+ try {
188
+ // Serialize data for processing
189
+ const serializedData = JSON.stringify(data)
190
+
191
+ // Compress if enabled and data is large enough
192
+ if (this.compressionConfig.enabled &&
193
+ (options?.compress !== false) &&
194
+ Buffer.byteLength(serializedData, 'utf8') > this.compressionConfig.threshold) {
195
+
196
+ const compressedBuffer = await gzipAsync(Buffer.from(serializedData, 'utf8'))
197
+ processedData = compressedBuffer.toString('base64') as any
198
+ compressed = true
199
+
200
+ liveLog('state', componentId, `๐Ÿ—œ๏ธ State compressed: ${Buffer.byteLength(serializedData, 'utf8')} -> ${compressedBuffer.length} bytes`)
201
+ }
202
+
203
+ // Encrypt sensitive data if requested
204
+ if (options?.encrypt) {
205
+ const encryptedData = await this.encryptData(processedData)
206
+ processedData = encryptedData as any
207
+ encrypted = true
208
+
209
+ liveLog('state', componentId, `๐Ÿ”’ State encrypted for component: ${componentId}`)
210
+ }
211
+
212
+ // Create payload for signing
213
+ const payload = {
214
+ data: processedData,
215
+ componentId,
216
+ timestamp,
217
+ version,
218
+ keyId,
219
+ compressed,
220
+ encrypted
221
+ }
222
+
223
+ // Generate signature with current key
224
+ const signature = this.createSignature(payload)
225
+
226
+ // Create backup if requested
227
+ if (options?.backup) {
228
+ await this.createStateBackup(componentId, data, version)
229
+ }
230
+
231
+ liveLog('state', componentId, '๐Ÿ” State signed:', {
232
+ componentId,
233
+ timestamp,
234
+ version,
235
+ keyId,
236
+ compressed,
237
+ encrypted,
238
+ signature: signature.substring(0, 16) + '...'
239
+ })
240
+
241
+ return {
242
+ data: processedData,
243
+ signature,
244
+ timestamp,
245
+ componentId,
246
+ version,
247
+ keyId,
248
+ compressed,
249
+ encrypted
250
+ }
251
+
252
+ } catch (error) {
253
+ console.error('โŒ Failed to sign state:', error)
254
+ throw new Error(`State signing failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Validate signed state integrity with enhanced security checks
260
+ */
261
+ public async validateState<T>(signedState: SignedState<T>, maxAge?: number): Promise<StateValidationResult> {
262
+ const { data, signature, timestamp, componentId, version, keyId, compressed, encrypted } = signedState
263
+
264
+ try {
265
+ // Check timestamp (prevent replay attacks)
266
+ const age = Date.now() - timestamp
267
+ const ageLimit = maxAge || this.maxAge
268
+
269
+ if (age > ageLimit) {
270
+ return {
271
+ valid: false,
272
+ error: 'State signature expired',
273
+ expired: true
274
+ }
275
+ }
276
+
277
+ // Determine which key to use for validation
278
+ let validationKey = this.currentKey
279
+ let keyRotated = false
280
+
281
+ if (keyId) {
282
+ const historicalKey = this.getKeyById(keyId)
283
+ if (historicalKey) {
284
+ validationKey = historicalKey
285
+ keyRotated = keyId !== this.getCurrentKeyId()
286
+ } else {
287
+ return {
288
+ valid: false,
289
+ error: 'Signing key not found or expired',
290
+ keyRotated: true
291
+ }
292
+ }
293
+ }
294
+
295
+ // Recreate payload for verification
296
+ const payload = {
297
+ data,
298
+ componentId,
299
+ timestamp,
300
+ version,
301
+ keyId,
302
+ compressed,
303
+ encrypted
304
+ }
305
+
306
+ // Verify signature with appropriate key
307
+ const expectedSignature = this.createSignature(payload, validationKey)
308
+
309
+ if (!this.constantTimeEquals(signature, expectedSignature)) {
310
+ liveWarn('state', componentId, 'โš ๏ธ State signature mismatch:', {
311
+ componentId,
312
+ expected: expectedSignature.substring(0, 16) + '...',
313
+ received: signature.substring(0, 16) + '...'
314
+ })
315
+
316
+ return {
317
+ valid: false,
318
+ error: 'State signature invalid - possible tampering',
319
+ tampered: true
320
+ }
321
+ }
322
+
323
+ liveLog('state', componentId, 'โœ… State signature valid:', {
324
+ componentId,
325
+ age: `${Math.round(age / 1000)}s`,
326
+ version
327
+ })
328
+
329
+ return { valid: true }
330
+
331
+ } catch (error: any) {
332
+ return {
333
+ valid: false,
334
+ error: `Validation error: ${error.message}`
335
+ }
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Create HMAC signature for payload using specified key
341
+ */
342
+ private createSignature(payload: any, key?: string): string {
343
+ // Stringify deterministically (sorted keys)
344
+ const normalizedPayload = JSON.stringify(payload, Object.keys(payload).sort())
345
+
346
+ return createHmac('sha256', key || this.currentKey)
347
+ .update(normalizedPayload)
348
+ .digest('hex')
349
+ }
350
+
351
+ /**
352
+ * Encrypt sensitive data
353
+ */
354
+ private async encryptData<T>(data: T): Promise<string> {
355
+ try {
356
+ const serializedData = JSON.stringify(data)
357
+ const key = await scryptAsync(this.currentKey, 'salt', 32) as Buffer
358
+ const iv = randomBytes(16)
359
+ const cipher = createCipheriv('aes-256-cbc', key, iv)
360
+
361
+ let encrypted = cipher.update(serializedData, 'utf8', 'hex')
362
+ encrypted += cipher.final('hex')
363
+
364
+ return iv.toString('hex') + ':' + encrypted
365
+ } catch (error) {
366
+ throw new Error(`Encryption failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Decrypt sensitive data
372
+ */
373
+ private async decryptData(encryptedData: string, key?: string): Promise<any> {
374
+ try {
375
+ const [ivHex, encrypted] = encryptedData.split(':')
376
+ const iv = Buffer.from(ivHex, 'hex')
377
+ const derivedKey = await scryptAsync(key || this.currentKey, 'salt', 32) as Buffer
378
+ const decipher = createDecipheriv('aes-256-cbc', derivedKey, iv)
379
+
380
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8')
381
+ decrypted += decipher.final('utf8')
382
+
383
+ return JSON.parse(decrypted)
384
+ } catch (error) {
385
+ throw new Error(`Decryption failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Decompress state data
391
+ */
392
+ private async decompressData(compressedData: string): Promise<any> {
393
+ try {
394
+ const compressedBuffer = Buffer.from(compressedData, 'base64')
395
+ const decompressedBuffer = await gunzipAsync(compressedBuffer)
396
+ return JSON.parse(decompressedBuffer.toString('utf8'))
397
+ } catch (error) {
398
+ throw new Error(`Decompression failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Create state backup
404
+ */
405
+ private async createStateBackup<T>(componentId: string, state: T, version: number): Promise<void> {
406
+ try {
407
+ const backup: StateBackup<T> = {
408
+ componentId,
409
+ state,
410
+ timestamp: Date.now(),
411
+ version,
412
+ checksum: createHmac('sha256', this.currentKey).update(JSON.stringify(state)).digest('hex')
413
+ }
414
+
415
+ let backups = this.backups.get(componentId) || []
416
+ backups.push(backup)
417
+
418
+ // Keep only last 10 backups per component
419
+ if (backups.length > 10) {
420
+ backups = backups.slice(-10)
421
+ }
422
+
423
+ this.backups.set(componentId, backups)
424
+
425
+ liveLog('state', componentId, `๐Ÿ’พ State backup created for component ${componentId} v${version}`)
426
+ } catch (error) {
427
+ console.error(`โŒ Failed to create backup for component ${componentId}:`, error)
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Constant-time string comparison to prevent timing attacks
433
+ */
434
+ private constantTimeEquals(a: string, b: string): boolean {
435
+ if (a.length !== b.length) {
436
+ return false
437
+ }
438
+
439
+ let result = 0
440
+ for (let i = 0; i < a.length; i++) {
441
+ result |= a.charCodeAt(i) ^ b.charCodeAt(i)
442
+ }
443
+
444
+ return result === 0
445
+ }
446
+
447
+ /**
448
+ * Extract and process signed state data (decompression, decryption)
449
+ */
450
+ public async extractData<T>(signedState: SignedState<T>): Promise<T> {
451
+ let data = signedState.data
452
+
453
+ try {
454
+ // Decrypt if encrypted
455
+ if (signedState.encrypted) {
456
+ const keyToUse = signedState.keyId ? this.getKeyById(signedState.keyId) : this.currentKey
457
+ if (!keyToUse) {
458
+ throw new Error('Decryption key not available')
459
+ }
460
+ data = await this.decryptData(data as string, keyToUse)
461
+ }
462
+
463
+ // Decompress if compressed
464
+ if (signedState.compressed) {
465
+ data = await this.decompressData(data as string)
466
+ }
467
+
468
+ return data
469
+ } catch (error) {
470
+ console.error('โŒ Failed to extract state data:', error)
471
+ throw error
472
+ }
473
+ }
474
+
475
+ /**
476
+ * Update signature for new state version with enhanced options
477
+ */
478
+ public async updateSignature<T>(
479
+ signedState: SignedState<T>,
480
+ newData: T,
481
+ options?: {
482
+ compress?: boolean
483
+ encrypt?: boolean
484
+ backup?: boolean
485
+ }
486
+ ): Promise<SignedState<T>> {
487
+ return this.signState(
488
+ signedState.componentId,
489
+ newData,
490
+ signedState.version + 1,
491
+ options
492
+ )
493
+ }
494
+
495
+ /**
496
+ * Register state migration function
497
+ */
498
+ public registerMigration(fromVersion: string, toVersion: string, migrationFn: (state: any) => any): void {
499
+ const key = `${fromVersion}->${toVersion}`
500
+ this.migrationFunctions.set(key, migrationFn)
501
+ liveLog('state', null, `๐Ÿ“‹ Registered migration: ${key}`)
502
+ }
503
+
504
+ /**
505
+ * Migrate state to new version
506
+ */
507
+ public async migrateState<T>(signedState: SignedState<T>, targetVersion: string): Promise<SignedState<T> | null> {
508
+ const currentVersion = signedState.version.toString()
509
+ const migrationKey = `${currentVersion}->${targetVersion}`
510
+
511
+ const migrationFn = this.migrationFunctions.get(migrationKey)
512
+ if (!migrationFn) {
513
+ liveWarn('state', null, `โš ๏ธ No migration function found for ${migrationKey}`)
514
+ return null
515
+ }
516
+
517
+ try {
518
+ // Extract current data
519
+ const currentData = await this.extractData(signedState)
520
+
521
+ // Apply migration
522
+ const migratedData = migrationFn(currentData)
523
+
524
+ // Create new signed state
525
+ const newSignedState = await this.signState(
526
+ signedState.componentId,
527
+ migratedData,
528
+ parseInt(targetVersion),
529
+ {
530
+ compress: signedState.compressed,
531
+ encrypt: signedState.encrypted,
532
+ backup: true
533
+ }
534
+ )
535
+
536
+ liveLog('state', signedState.componentId, `โœ… State migrated from v${currentVersion} to v${targetVersion} for component ${signedState.componentId}`)
537
+ return newSignedState
538
+
539
+ } catch (error) {
540
+ console.error(`โŒ State migration failed for ${migrationKey}:`, error)
541
+ return null
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Recover state from backup
547
+ */
548
+ public recoverStateFromBackup<T>(componentId: string, version?: number): StateBackup<T> | null {
549
+ const backups = this.backups.get(componentId)
550
+ if (!backups || backups.length === 0) {
551
+ return null
552
+ }
553
+
554
+ if (version !== undefined) {
555
+ // Find specific version
556
+ return backups.find(backup => backup.version === version) || null
557
+ } else {
558
+ // Return latest backup
559
+ return backups[backups.length - 1] || null
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Get all backups for a component
565
+ */
566
+ public getComponentBackups(componentId: string): StateBackup[] {
567
+ return this.backups.get(componentId) || []
568
+ }
569
+
570
+ /**
571
+ * Verify backup integrity
572
+ */
573
+ public verifyBackup<T>(backup: StateBackup<T>): boolean {
574
+ try {
575
+ const expectedChecksum = createHmac('sha256', this.currentKey)
576
+ .update(JSON.stringify(backup.state))
577
+ .digest('hex')
578
+
579
+ return this.constantTimeEquals(backup.checksum, expectedChecksum)
580
+ } catch {
581
+ return false
582
+ }
583
+ }
584
+
585
+ /**
586
+ * Clean up old backups
587
+ */
588
+ public cleanupBackups(maxAge: number = 7 * 24 * 60 * 60 * 1000): void {
589
+ const now = Date.now()
590
+ let totalCleaned = 0
591
+
592
+ for (const [componentId, backups] of this.backups) {
593
+ const validBackups = backups.filter(backup => {
594
+ const age = now - backup.timestamp
595
+ return age <= maxAge
596
+ })
597
+
598
+ const cleaned = backups.length - validBackups.length
599
+ totalCleaned += cleaned
600
+
601
+ if (validBackups.length === 0) {
602
+ this.backups.delete(componentId)
603
+ } else {
604
+ this.backups.set(componentId, validBackups)
605
+ }
606
+ }
607
+
608
+ if (totalCleaned > 0) {
609
+ liveLog('state', null, `๐Ÿงน Cleaned up ${totalCleaned} old state backups`)
610
+ }
611
+ }
612
+
613
+ /**
614
+ * Get server's signature info for debugging
615
+ */
616
+ public getSignatureInfo() {
617
+ return {
618
+ algorithm: 'HMAC-SHA256',
619
+ keyLength: this.currentKey.length,
620
+ maxAge: this.maxAge,
621
+ keyPreview: this.currentKey.substring(0, 8) + '...',
622
+ currentKeyId: this.getCurrentKeyId(),
623
+ keyHistoryCount: this.keyHistory.size,
624
+ compressionEnabled: this.compressionConfig.enabled,
625
+ rotationInterval: this.keyRotationConfig.rotationInterval
626
+ }
627
+ }
628
+ }
629
+
630
+ // Global instance with enhanced configuration
631
+ export const stateSignature = StateSignature.getInstance(
632
+ process.env.FLUXSTACK_STATE_SECRET || undefined,
633
+ {
634
+ keyRotation: {
635
+ rotationInterval: parseInt(process.env.FLUXSTACK_KEY_ROTATION_INTERVAL || '604800000'), // 7 days
636
+ maxKeyAge: parseInt(process.env.FLUXSTACK_MAX_KEY_AGE || '2592000000'), // 30 days
637
+ keyRetentionCount: parseInt(process.env.FLUXSTACK_KEY_RETENTION_COUNT || '5')
638
+ },
639
+ compression: {
640
+ enabled: process.env.FLUXSTACK_COMPRESSION_ENABLED !== 'false',
641
+ threshold: parseInt(process.env.FLUXSTACK_COMPRESSION_THRESHOLD || '1024'), // 1KB
642
+ level: parseInt(process.env.FLUXSTACK_COMPRESSION_LEVEL || '6')
643
+ }
644
+ }
644
645
  )