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