-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollaboration-server.js
More file actions
1555 lines (1320 loc) · 53.6 KB
/
collaboration-server.js
File metadata and controls
1555 lines (1320 loc) · 53.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { Server } = require('@hocuspocus/server')
const { Database } = require('@hocuspocus/extension-database')
const { Pool } = require('pg')
const config = require('./config')
const { CollaborationAuth } = require('./collaboration-auth')
const { createHash } = require('crypto')
const Y = require('yjs')
const { decoding } = require('lib0')
const awarenessProtocol = require('y-protocols/awareness')
const express = require('express')
// Initialize database pool
const pool = new Pool({
connectionString: config.dbcs,
})
// SHA256 hash function for signature verification
const sha256 = (data) => {
return createHash('sha256').update(data).digest()
}
// WeakMap to track permission observers per document
const permissionObservers = new WeakMap()
// Custom Hive authentication for WebSocket connections
class HiveAuthExtension {
// Protocol messages that should ALWAYS be allowed regardless of permissions
static PROTOCOL_MESSAGE_TYPES = [
'awareness',
'sync',
'queryAwareness',
'awarenessUpdate'
]
// Y.js update types that are awareness-only (not document content)
static AWARENESS_UPDATE_TYPES = new Set([
0, // Sync step 1
1, // Sync step 2
2 // Update (but could be awareness only)
])
async onAuthenticate(data) {
const { token, documentName } = data
try {
// Parse token - should contain auth headers as JSON
const authData = JSON.parse(token)
const { account, challenge, pubkey, signature } = authData
// Validate required fields
if (!account || !challenge || !pubkey || !signature) {
throw new Error('Missing authentication headers')
}
// Validate challenge timestamp (must be within 24 hours for WebSocket)
const challengeTime = parseInt(challenge)
const now = Math.floor(Date.now() / 1000)
const maxAge = 24 * 60 * 60 // 24 hours in seconds
const ageDifference = now - challengeTime
const isFromFuture = challengeTime > (now + 300)
if (isNaN(challengeTime)) {
console.error(`[onAuthenticate] Invalid challenge format:`, { challenge, account })
throw new Error('Challenge must be a valid timestamp')
}
if (ageDifference > maxAge) {
console.error(`[onAuthenticate] Challenge too old:`, {
challenge: challengeTime,
now,
ageDifference,
maxAge,
account
})
throw new Error(`Challenge timestamp too old (${Math.floor(ageDifference / 3600)} hours old, max 24 hours)`)
}
if (isFromFuture) {
console.error(`[onAuthenticate] Challenge from future:`, {
challenge: challengeTime,
now,
futureBy: challengeTime - now,
account
})
throw new Error('Challenge timestamp cannot be from the future (max 5 minutes ahead)')
}
// Get account keys from HIVE blockchain
const accountKeys = await CollaborationAuth.getAccountKeys(account)
if (!accountKeys) {
throw new Error(`Account @${account} not found on HIVE blockchain`)
}
// Check if the provided public key belongs to the account
const allKeys = [
...accountKeys.owner,
...accountKeys.active,
...accountKeys.posting,
accountKeys.memo
].filter(Boolean)
if (!allKeys.includes(pubkey)) {
throw new Error('Public key does not belong to the specified account')
}
// Verify the signature
const isValidSignature = await CollaborationAuth.verifySignature(challenge.toString(), signature, pubkey)
if (!isValidSignature) {
throw new Error('Invalid signature')
}
// Parse document name (format: owner/permlink)
const [owner, permlink] = documentName.split('/')
if (!owner || !permlink) {
throw new Error('Invalid document format. Expected: owner/permlink')
}
// Check document permissions
const permissions = await this.checkDocumentAccess(account, owner, permlink)
if (!permissions.hasAccess) {
throw new Error('Access denied to document')
}
// Log connection activity
await this.logActivity(owner, permlink, account, 'connect', {
socketId: data.socketId,
timestamp: new Date().toISOString(),
permissions: permissions.permissionType
})
return {
user: {
id: account,
name: account,
color: this.generateUserColor(account, permissions.permissionType),
// Store permissions in user context for later use
permissions: permissions,
// Add connection timestamp for grace period handling
connectedAt: Date.now()
}
}
} catch (error) {
console.error('Authentication failed:', error)
throw error
}
}
async checkDocumentAccess(account, owner, permlink) {
const client = await pool.connect()
try {
// Owner always has full access
if (account === owner) {
return {
hasAccess: true,
canRead: true,
canEdit: true,
canPostToHive: true,
permissionType: 'owner'
}
}
// Check explicit permissions first (higher priority than public access)
const permResult = await client.query(
'SELECT permission_type, can_read, can_edit, can_post_to_hive FROM collaboration_permissions WHERE owner = $1 AND permlink = $2 AND account = $3',
[owner, permlink, account]
)
if (permResult.rows.length > 0) {
const perm = permResult.rows[0]
return {
hasAccess: perm.can_read,
canRead: perm.can_read,
canEdit: perm.can_edit,
canPostToHive: perm.can_post_to_hive,
permissionType: perm.permission_type
}
}
// Check if document is public (lower priority than explicit permissions)
const docResult = await client.query(
'SELECT is_public FROM collaboration_documents WHERE owner = $1 AND permlink = $2',
[owner, permlink]
)
if (docResult.rows.length > 0 && docResult.rows[0].is_public) {
return {
hasAccess: true,
canRead: true,
canEdit: false,
canPostToHive: false,
permissionType: 'public'
}
}
return {
hasAccess: false,
canRead: false,
canEdit: false,
canPostToHive: false,
permissionType: 'none'
}
} finally {
client.release()
}
}
async logActivity(owner, permlink, account, activityType, data) {
try {
const client = await pool.connect()
try {
await client.query(`
INSERT INTO collaboration_activity (owner, permlink, account, activity_type, activity_data)
VALUES ($1, $2, $3, $4, $5)
`, [owner, permlink, account, activityType, JSON.stringify(data)])
} finally {
client.release()
}
} catch (error) {
console.error('Error logging activity:', error)
}
}
generateUserColor(account, permissionType = 'owner') {
// Generate a consistent color for the user based on their account name
const hash = account.split('').reduce((a, b) => {
a = ((a << 5) - a) + b.charCodeAt(0)
return a & a
}, 0)
const hue = Math.abs(hash) % 360
// Slightly muted colors for read-only users
if (permissionType === 'public') {
return `hsl(${hue}, 50%, 65%)`
}
return `hsl(${hue}, 70%, 60%)`
}
// Properly detect Y.js awareness protocol messages
isAwarenessProtocolMessage(update) {
try {
// In Hocuspocus, the message format is:
// [messageType, ...data]
// Where messageType 1 = Awareness (from Hocuspocus MessageType enum)
const updateArray = new Uint8Array(update)
if (updateArray.length === 0) return false
const messageType = updateArray[0]
// Hocuspocus MessageType.Awareness = 1
if (messageType === 1) {
// Additional validation: awareness messages should have specific structure
// They contain awareness update data after the message type
if (updateArray.length > 1) {
return true
}
}
// Check for Y.js awareness updates (type 27 / 0x1b)
// These contain user presence data like cursor position and user info
if (messageType === 27 || messageType === 0x1b) {
// Check if it looks like an awareness update by examining the content
// The hex dump shows it contains user data in JSON format
try {
const contentStr = new TextDecoder().decode(updateArray.slice(1, Math.min(100, updateArray.length)))
if (contentStr.includes('user') || contentStr.includes('cursor') || contentStr.includes('lastActivity') || contentStr.includes('markegiles') || contentStr.includes('heyhey')) {
return true
}
} catch (e) {
// Ignore decoding errors, but still check the structure
// Y.js awareness updates have a specific pattern we can detect
if (updateArray.length > 20) {
return true
}
}
}
return false
} catch (error) {
console.error('[isAwarenessProtocolMessage] Error:', error)
return false
}
}
// Legacy method kept for backwards compatibility but deprecated
isAwarenessOnlyUpdate(update) {
// Use the new protocol-based detection
return this.isAwarenessProtocolMessage(update)
}
// Helper function to determine if an update modifies document content
isDocumentContentUpdate(update) {
return !this.isAwarenessOnlyUpdate(update)
}
// Check if user is in grace period (first 10 seconds after connection)
isInGracePeriod(user) {
if (!user || !user.connectedAt) return false
const gracePeriodMs = 10000 // 10 seconds
return (Date.now() - user.connectedAt) < gracePeriodMs
}
// Enhanced Y.js sync protocol handling
isSyncProtocolMessage(update) {
try {
// Check if this is a Y.js sync protocol message
const updateArray = new Uint8Array(update)
if (updateArray.length > 0) {
const messageType = updateArray[0]
// Hocuspocus MessageType enum:
// Sync = 0 (includes both sync step 1 and 2)
// SyncReply = 4 (same as Sync but won't trigger another SyncStep1)
if (messageType === 0 || messageType === 4) {
return true
}
}
return false
} catch (error) {
console.log('Error checking sync protocol message:', error.message)
return false
}
}
// Helper function to decode Y.js update for debugging
decodeUpdateForDebug(update) {
try {
// Create a temporary Y.js document to apply the update
const tempDoc = new Y.Doc()
const yText = tempDoc.getText('content')
// Apply the update to see what changes it contains
Y.applyUpdate(tempDoc, update)
// Get the resulting text content
const content = yText.toString()
// Also try to analyze the update structure
const updateInfo = {
size: update.length,
content: content,
contentLength: content.length,
updateHex: Buffer.from(update).toString('hex') // First 50 bytes as hex
}
return updateInfo
} catch (error) {
// If we can't decode it, at least show some basic info
return {
size: update.length,
error: error.message,
updateHex: Buffer.from(update).toString('hex'),
firstBytes: Array.from(update.slice(0, 20)).map(b => b.toString(16).padStart(2, '0')).join(' ')
}
}
}
// Debug helper to identify message types
debugMessageType(update) {
const updateArray = new Uint8Array(update)
const messageType = updateArray.length > 0 ? updateArray[0] : -1
const typeNames = {
0: 'Sync',
1: 'Awareness',
2: 'Auth',
3: 'Query Awareness',
4: 'Sync Reply',
5: 'Stateless',
6: 'Broadcast Stateless',
7: 'Close',
8: 'Sync Status'
}
// Check if this might be a Y.js document update
let isYjsUpdate = false
let decodedInfo = null
if (messageType > 8) {
try {
// Try to decode as Y.js update
const tempDoc = new Y.Doc()
Y.applyUpdate(tempDoc, update)
isYjsUpdate = true
decodedInfo = {
contentLength: tempDoc.getText('content').length,
hasContent: tempDoc.getText('content').length > 0
}
} catch (e) {
// Not a valid Y.js update
}
}
return {
type: messageType,
typeName: typeNames[messageType] || (isYjsUpdate ? 'Y.js Update' : 'Unknown'),
size: update.length,
isAwareness: this.isAwarenessProtocolMessage(update),
isSync: this.isSyncProtocolMessage(update),
isAuth: messageType === 2,
isQueryAwareness: messageType === 3,
firstBytes: Array.from(updateArray.slice(0, 10)).map(b => b.toString(16).padStart(2, '0')).join(' '),
isYjsUpdate: isYjsUpdate,
decodedInfo: decodedInfo
}
}
// Check if this is a protocol message that should always be allowed
isProtocolMessage(update) {
const updateArray = new Uint8Array(update)
if (updateArray.length === 0) return false
const messageType = updateArray[0]
// Check specific message types
switch (messageType) {
case 0: // Sync - always allow for initial sync
case 1: // Awareness - always allow for cursor/presence
case 2: // Auth - always allow for authentication
case 3: // Query Awareness - always allow awareness queries
case 4: // Sync Reply - always allow sync responses
case 8: // Sync Status - always allow status updates
return true
default:
// Type 27 (0x1b) and other unknown types are NOT protocol messages
// These are likely Y.js document updates and should be blocked for readonly users
return false
}
}
// ✅ STEP 3: Permission update helper for API integration
async updateDocumentPermissions(server, owner, permlink, newPermissions) {
let connection = null
// Updating permissions for document
try {
// 1. Update permissions in database
await this.updatePermissionsInDatabase(owner, permlink, newPermissions)
// 2. Update Y.js permissions map to trigger broadcast
const documentId = `${owner}/${permlink}`
// First, check if document exists in active documents
let yjsDocument = null
let documentsMap = null
// Access hocuspocus instance correctly
const hocuspocus = server.hocuspocus || server
if (hocuspocus.documents instanceof Map) {
documentsMap = hocuspocus.documents
yjsDocument = documentsMap.get(documentId)
}
let needsDisconnect = false
if (!yjsDocument) {
// Document not loaded, open direct connection
if (!hocuspocus.openDirectConnection) {
throw new Error('Server API missing: openDirectConnection method not available')
}
try {
connection = await hocuspocus.openDirectConnection(documentId, {
user: {
name: 'permission-api',
permissions: { canEdit: true, canRead: true, permissionType: 'system' }
}
})
yjsDocument = connection.document
needsDisconnect = true
} catch (connError) {
throw new Error(`Cannot access document ${documentId}: ${connError.message}`)
}
}
if (yjsDocument) {
// Check if observer exists
const hasObserver = permissionObservers.has(yjsDocument)
if (!hasObserver) {
// No permission observer found for document
}
// Use Y.js transaction to update permissions map
yjsDocument.transact(() => {
const permissionsMap = yjsDocument.getMap('permissions')
// Update each permission that changed
Object.entries(newPermissions).forEach(([username, permission]) => {
permissionsMap.set(username, permission)
})
// Add timestamp for debugging
permissionsMap.set('lastUpdated', new Date().toISOString())
}, 'permission-api-update')
// Permissions updated successfully
// Give the observer a moment to trigger
await new Promise(resolve => setTimeout(resolve, 100))
// If we created a direct connection, disconnect it
if (needsDisconnect && connection) {
await connection.disconnect()
console.log('🔌 Direct connection closed')
}
} else {
throw new Error(`Failed to access document ${documentId}`)
}
return { success: true, permissions: newPermissions, broadcast: true }
} catch (error) {
console.error('❌ Permission update failed:', error)
// Clean up connection if it exists
if (connection) {
try {
await connection.disconnect()
} catch (disconnectError) {
console.error('Error disconnecting:', disconnectError)
}
}
throw error
}
}
// Helper to update permissions in database
async updatePermissionsInDatabase(owner, permlink, newPermissions) {
const client = await pool.connect()
try {
// Update each permission
for (const [account, permissionData] of Object.entries(newPermissions)) {
if (typeof permissionData === 'string') {
// Simple permission type string
await client.query(`
INSERT INTO collaboration_permissions (owner, permlink, account, permission_type, can_read, can_edit, can_post_to_hive, granted_by)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (owner, permlink, account)
DO UPDATE SET
permission_type = EXCLUDED.permission_type,
can_read = EXCLUDED.can_read,
can_edit = EXCLUDED.can_edit,
can_post_to_hive = EXCLUDED.can_post_to_hive,
granted_by = EXCLUDED.granted_by,
granted_at = NOW()
`, [
owner, permlink, account, permissionData,
this.getPermissionFlags(permissionData).canRead,
this.getPermissionFlags(permissionData).canEdit,
this.getPermissionFlags(permissionData).canPostToHive,
owner // Assume owner is granting permissions
])
}
}
} finally {
client.release()
}
}
// Helper to get permission flags from permission type
getPermissionFlags(permissionType) {
switch (permissionType) {
case 'owner':
return { canRead: true, canEdit: true, canPostToHive: true }
case 'postable':
return { canRead: true, canEdit: true, canPostToHive: true }
case 'editable':
return { canRead: true, canEdit: true, canPostToHive: false }
case 'readonly':
return { canRead: true, canEdit: false, canPostToHive: false }
case 'public':
return { canRead: true, canEdit: false, canPostToHive: false }
default:
return { canRead: false, canEdit: false, canPostToHive: false }
}
}
}
// Initialize extensions
const hiveAuth = new HiveAuthExtension()
// ==================== PERMISSION BROADCAST SYSTEM ====================
/**
* Permission Broadcast Manager
* Handles real-time permission changes via Y.js document updates
*/
class PermissionBroadcastManager {
constructor(hocuspocusServer) {
this.server = hocuspocusServer
}
/**
* Broadcast permission change to all connected clients for a document
* @param {string} owner - Document owner
* @param {string} permlink - Document permlink
* @param {string} targetAccount - Account whose permissions changed
* @param {string} permissionType - New permission type (or 'revoked')
* @param {string} grantedBy - Account who made the change
*/
async broadcastPermissionChange(owner, permlink, targetAccount, permissionType, grantedBy) {
const documentName = `${owner}/${permlink}`
try {
// Get the Y.js document for this collaborative document
const ydoc = this.server.getDocument(documentName)
if (!ydoc) {
console.log(`[PermissionBroadcast] No active Y.js document for ${documentName} - no broadcast needed`)
return
}
// Get the permissions map from the Y.js document
const permissionsMap = ydoc.getMap('permissions')
// Create permission update data
const permissionUpdate = {
account: targetAccount,
permissionType: permissionType,
grantedBy: grantedBy,
timestamp: new Date().toISOString(),
broadcastType: permissionType === 'revoked' ? 'permission_revoked' : 'permission_granted'
}
// Update the permissions map to trigger awareness broadcasts
// This will notify all connected clients via Y.js synchronization
permissionsMap.set(`update_${targetAccount}_${Date.now()}`, permissionUpdate)
// Clean up old permission updates (keep only last 10 per account)
const allKeys = Array.from(permissionsMap.keys())
const accountUpdates = allKeys
.filter(key => key.startsWith(`update_${targetAccount}_`))
.sort((a, b) => {
const timestampA = parseInt(a.split('_').pop())
const timestampB = parseInt(b.split('_').pop())
return timestampB - timestampA // newest first
})
// Remove old updates (keep only 10 most recent)
if (accountUpdates.length > 10) {
accountUpdates.slice(10).forEach(key => {
permissionsMap.delete(key)
})
}
console.log(`[PermissionBroadcast] ✅ Broadcasted ${permissionType} permission for ${targetAccount} in ${documentName}`)
console.log(`[PermissionBroadcast] Connected clients will receive update via Y.js awareness`)
// Log broadcast statistics
const connections = this.server.getConnections()
const documentConnections = connections.filter(conn => conn.documentName === documentName)
console.log(`[PermissionBroadcast] Broadcast sent to ${documentConnections.length} active connections`)
} catch (error) {
console.error(`[PermissionBroadcast] Error broadcasting permission change for ${documentName}:`, error)
}
}
/**
* Broadcast document deletion to all connected clients
* @param {string} owner - Document owner
* @param {string} permlink - Document permlink
*/
async broadcastDocumentDeletion(owner, permlink) {
const documentName = `${owner}/${permlink}`
try {
const connections = this.server.getConnections()
const documentConnections = connections.filter(conn => conn.documentName === documentName)
console.log(`[PermissionBroadcast] Broadcasting document deletion to ${documentConnections.length} connections`)
// Force disconnect all connections for the deleted document
documentConnections.forEach(connection => {
try {
connection.close(1000, 'Document deleted')
} catch (error) {
console.error('[PermissionBroadcast] Error closing connection:', error)
}
})
} catch (error) {
console.error(`[PermissionBroadcast] Error broadcasting document deletion for ${documentName}:`, error)
}
}
}
// Initialize the permission broadcast manager
let permissionBroadcaster = null
// Configure the Hocuspocus server
const server = new Server({
port: 1234,
// WebSocket timeout configuration (CRITICAL: Must align with Y.js awareness timeout)
timeout: 30000, // 30 seconds (matches Y.js awareness timeout)
debounce: 2000, // 2 seconds debounce for document updates
maxDebounce: 10000, // 10 seconds max debounce
quiet: false, // Enable logging to help debug connection issues
// Add startup configuration hook
async onConfigure(data) {
// Configuration phase - no logging needed here
},
// CORS configuration
cors: {
origin: [
'https://vue.dlux.io',
'https://dlux.io',
'http://www.dlux.io',
'http://localhost:3001',
'http://localhost:5508',
'http://localhost:5509',
// Add any other origins you need
],
credentials: false, // Set to false since client works better with credentials: 'omit'
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'Authorization',
'x-account',
'x-challenge',
'x-pubkey',
'x-signature',
]
},
// Authentication
async onAuthenticate(data) {
return await hiveAuth.onAuthenticate(data)
},
// Prevent unauthorized changes BEFORE they are applied
async beforeHandleMessage(data) {
const { documentName, context, update } = data
// Check if user has edit permissions
if (context.user && context.user.permissions) {
const permissions = context.user.permissions
const user = context.user
// Remove debug logging for production
// Allow all updates during grace period for initial sync
if (hiveAuth.isInGracePeriod(user)) {
return
}
// Always allow Y.js sync protocol messages regardless of permissions
if (hiveAuth.isSyncProtocolMessage(update)) {
return
}
// IMPORTANT: Let Hocuspocus handle awareness messages via onAwarenessUpdate
// This avoids the broken heuristic detection and uses proper protocol handling
if (hiveAuth.isAwarenessProtocolMessage(update)) {
return // Let Hocuspocus process this via onAwarenessUpdate
}
// For users without edit permissions
if (!permissions.canEdit) {
// CRITICAL: Allow ALL Y.js protocol messages (types 0-4, 8) for readonly users
// Only reject document content changes (type 0 with actual content)
if (hiveAuth.isProtocolMessage(update)) {
return // Allow all protocol messages: 0-4, 8
}
// This is a document content update - block it
const updateInfo = hiveAuth.decodeUpdateForDebug(update)
// Log as document edit attempt (not unauthorized_edit_attempt for clarity)
const [owner, permlink] = documentName.split('/')
await hiveAuth.logActivity(owner, permlink, user.name, 'blocked_document_edit', {
timestamp: new Date().toISOString(),
permissionType: permissions.permissionType,
updateSize: update.length,
messageType: hiveAuth.debugMessageType(update).type,
attemptedChanges: updateInfo
})
// Log blocked edit attempt
console.log(`[Permissions] Blocked edit from read-only user ${user.name} on ${documentName}`)
// Clear error message
let errorMessage = `Document editing not allowed. User ${user.name} has ${permissions.permissionType} access.`
if (permissions.permissionType === 'public' || permissions.permissionType === 'readonly') {
errorMessage += ' You can view the document and see other users\' cursors, but cannot edit content.'
}
throw new Error(errorMessage)
} else {
// User has edit permissions - allow
}
}
},
// Log successful changes after they are applied
async onChange(data) {
const { documentName, context, update } = data
// Log successful edit for audit
if (context.user && context.user.permissions) {
const [owner, permlink] = documentName.split('/')
await hiveAuth.logActivity(owner, permlink, context.user.name, 'document_edit', {
timestamp: new Date().toISOString(),
permissionType: context.user.permissions.permissionType,
updateSize: update.length
})
}
},
// ✅ STEP 1: Core Permission Observer - Real-time permission broadcasts
async onChangeDocument(data) {
const { documentName, document } = data
try {
// Get permissions map from Y.js document
const permissionsMap = document.getMap('permissions')
// Set up observer for permission changes (only once per document)
if (!permissionObservers.has(document)) {
console.log('🔧 Setting up permission observer for document:', documentName)
const observerCallback = (event) => {
if (event.type === 'update' && event.changes.keys.size > 0) {
const changedKeys = Array.from(event.changes.keys.keys())
// Only log actual permission changes, not metadata updates
const permissionKeys = changedKeys.filter(key => key !== 'lastUpdated' && key !== 'created')
if (permissionKeys.length > 0) {
console.log('📡 Permission change detected, broadcasting:', {
document: documentName,
changedUsers: permissionKeys
})
}
try {
// Broadcast permission update via Y.js awareness
if (document.awareness) {
// Create the permission update payload
const permissionUpdate = {
timestamp: Date.now(),
changes: Array.from(event.changes.keys.keys()),
documentName: documentName,
eventType: 'permission-change'
}
// Method 1: Set local state field (for server awareness)
document.awareness.setLocalStateField('permissionUpdate', permissionUpdate)
// Method 2: Broadcast to all connected clients via awareness states
const states = document.awareness.getStates()
console.log(`📢 Broadcasting to ${states.size} connected clients`)
// Get all changed permissions
const changedPermissions = {}
event.changes.keys.forEach((_, key) => {
if (key !== 'lastUpdated') {
changedPermissions[key] = permissionsMap.get(key)
}
})
// Set awareness state for each connected client
states.forEach((state, clientId) => {
if (state.user) {
console.log(` Broadcasting to client ${clientId} (${state.user.name || 'unknown'})`)
}
})
// Permission broadcast sent via awareness
// Clear the broadcast after 5 seconds to prevent memory accumulation
setTimeout(() => {
if (document.awareness) {
document.awareness.setLocalStateField('permissionUpdate', null)
}
}, 5000)
} else {
// Document awareness not available for broadcasting
}
} catch (broadcastError) {
console.error('❌ Error broadcasting permission update:', broadcastError)
}
} else {
// Permission observer fired but no keys changed
}
}
// Observe the permissions map
permissionsMap.observe(observerCallback)
// Store the observer callback in WeakMap for cleanup
permissionObservers.set(document, {
callback: observerCallback,
permissionsMap: permissionsMap
})
// Permission observer added for document
}
} catch (error) {
console.error('❌ Error setting up permission observer:', error)
console.error('[onChangeDocument] Error stack:', error.stack)
}
},
// ✅ STEP 2: Enhanced Awareness Handling with Permission Broadcasts
async onAwarenessUpdate(data) {
const { documentName, context, connection, added, updated, removed, awareness } = data
// CRITICAL: Allow awareness updates for ALL authenticated users (including readonly)
// This should NOT reject awareness updates from readonly users
// Check for permission broadcasts in awareness states
if (awareness && awareness.getStates) {
awareness.getStates().forEach((state, clientId) => {
if (state.permissionUpdate) {
// Permission broadcast detected in awareness
}
})
}
if (context.user) {
const user = context.user
const permissions = user.permissions
// Log only for debugging permission broadcasts
// console.log(`[onAwarenessUpdate] From user: ${user.name} (${permissions.permissionType})`)
// CRITICAL: Reset connection activity to prevent timeouts
if (connection) {
connection.lastActivity = Date.now()
connection.isAlive = true
}
// Log awareness activity for monitoring
const [owner, permlink] = documentName.split('/')
await hiveAuth.logActivity(owner, permlink, user.name, 'awareness_update', {
timestamp: new Date().toISOString(),
permissionType: permissions.permissionType,
added: added.length,
updated: updated.length,
removed: removed.length,
totalAwarenessUsers: awareness ? awareness.getStates().size : 0
})
}
// IMPORTANT: Always allow awareness updates to proceed (including permission broadcasts)
return true
},
// ✅ STEP 4: Document Lifecycle Management
async onCreateDocument(data) {
const { documentName, document } = data
console.log('📄 Document created:', documentName)
// Initialize permissions map if it doesn't exist
const permissionsMap = document.getMap('permissions')
if (permissionsMap.size === 0) {
// Set default permissions for document creator
const [owner] = documentName.split('/')
permissionsMap.set(owner, 'owner')
permissionsMap.set('created', new Date().toISOString())
// Default permissions set for document owner
}
// Set up permission observer for the new document
try {
// Set up observer directly since we can't reliably call onChangeDocument from here
if (!permissionObservers.has(document)) {
const observerCallback = (event) => {
if (event.type === 'update' && event.changes.keys.size > 0) {
const changedKeys = Array.from(event.changes.keys.keys())
const permissionKeys = changedKeys.filter(key => key !== 'lastUpdated' && key !== 'created')
if (permissionKeys.length > 0) {
console.log('📡 Permission change detected (onCreate observer):', {
document: documentName,
changedUsers: permissionKeys
})
}
// Broadcast permission update via Y.js awareness
if (document.awareness) {
const permissionUpdate = {
timestamp: Date.now(),
changes: Array.from(event.changes.keys.keys()),
documentName: documentName,
eventType: 'permission-change'
}
// Set local state field for broadcast
document.awareness.setLocalStateField('permissionUpdate', permissionUpdate)