-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·998 lines (943 loc) · 36.9 KB
/
index.ts
File metadata and controls
executable file
·998 lines (943 loc) · 36.9 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
import { parse } from 'node:url';
import { Connect, Identity, Inboxes, Messages, SpaceEvents, Utils } from '@graphprotocol/hypergraph';
import { bytesToHex, randomBytes } from '@noble/hashes/utils.js';
import cors from 'cors';
import { Effect, Exit, Schema } from 'effect';
import express, { type NextFunction, type Request, type Response } from 'express';
import WebSocket, { WebSocketServer } from 'ws';
import { addAppIdentityToSpaces } from './handlers/add-app-identity-to-spaces.js';
import { applySpaceEvent } from './handlers/applySpaceEvent.js';
import { createAppIdentity } from './handlers/create-app-identity.js';
import { createSpace } from './handlers/create-space.js';
import { createAccountInbox } from './handlers/createAccountInbox.js';
import { createAccountInboxMessage } from './handlers/createAccountInboxMessage.js';
import { createIdentity } from './handlers/createIdentity.js';
import { createSpaceInboxMessage } from './handlers/createSpaceInboxMessage.js';
import { createUpdate } from './handlers/createUpdate.js';
import { findAppIdentity } from './handlers/find-app-identity.js';
import { getAppIdentityBySessionToken } from './handlers/get-app-identity-by-session-token.js';
import { getAccountInbox } from './handlers/getAccountInbox.js';
import { type GetIdentityResult, getConnectIdentity } from './handlers/getConnectIdentity.js';
import { getLatestAccountInboxMessages } from './handlers/getLatestAccountInboxMessages.js';
import { getLatestSpaceInboxMessages } from './handlers/getLatestSpaceInboxMessages.js';
import { getSpace } from './handlers/getSpace.js';
import { getSpaceInbox } from './handlers/getSpaceInbox.js';
import { isSignerForAccount } from './handlers/is-signer-for-account.js';
import { listAccountInboxes } from './handlers/list-account-inboxes.js';
import { listPublicAccountInboxes } from './handlers/list-public-account-inboxes.js';
import { listSpacesByAccount } from './handlers/list-spaces-by-account.js';
import { listInvitations } from './handlers/listInvitations.js';
import { listPublicSpaceInboxes } from './handlers/listPublicSpaceInboxes.js';
import { listSpacesByAppIdentity } from './handlers/listSpacesByAppIdentity.js';
import { getAddressByPrivyToken } from './utils/get-address-by-privy-token.js';
interface CustomWebSocket extends WebSocket {
accountAddress: string;
appIdentityAddress: string;
subscribedSpaces: Set<string>;
}
const decodeRequestMessage = Schema.decodeUnknownEither(Messages.RequestMessage);
const webSocketServer = new WebSocketServer({ noServer: true });
const PORT = process.env.PORT !== undefined ? Number.parseInt(process.env.PORT) : 3030;
const app = express();
const CHAIN = process.env.HYPERGRAPH_CHAIN === 'geogenesis' ? Connect.GEOGENESIS : Connect.GEO_TESTNET;
const RPC_URL = process.env.HYPERGRAPH_RPC_URL ?? CHAIN.rpcUrls.default.http[0];
type AuthenticatedRequest = Request & { accountAddress?: string };
async function verifyAuth(req: AuthenticatedRequest, res: Response, next: (err?: Error) => void) {
const auth = req.headers.authorization;
if (!auth) {
res.status(401).send('Unauthorized');
return;
}
try {
const sessionToken = auth.split(' ')[1];
const { accountAddress } = await getAppIdentityBySessionToken({ sessionToken });
req.accountAddress = accountAddress;
next();
} catch (error) {
res.status(401).send('Unauthorized');
return;
}
}
app.use(express.json({ limit: '2mb' }));
app.use(cors());
// Request timeout middleware
app.use((req: Request, res: Response, next: NextFunction) => {
res.setTimeout(30000, () => {
res.status(408).json({ error: 'Request timeout' });
});
next();
});
app.get('/', (_req, res) => {
res.send('Server is running (v0.0.10)');
});
app.get('/connect/spaces', async (req, res) => {
console.log('GET connect/spaces');
try {
const idToken = req.headers['privy-id-token'];
const accountAddress = req.headers['account-address'] as string;
const signerAddress = await getAddressByPrivyToken(idToken);
if (!(await isSignerForAccount(signerAddress, accountAddress))) {
res.status(401).send('Unauthorized');
return;
}
const spaces = await listSpacesByAccount({ accountAddress });
const spaceResults = spaces.map((space) => ({
id: space.id,
infoContent: Utils.bytesToHex(space.infoContent),
infoAuthorAddress: space.infoAuthorAddress,
infoSignatureHex: space.infoSignatureHex,
infoSignatureRecovery: space.infoSignatureRecovery,
name: space.name, // TODO: remove this field and use infoContent instead
appIdentities: space.appIdentities.map((appIdentity) => ({
appId: appIdentity.appId,
address: appIdentity.address,
})),
keyBoxes: space.keys
.filter((key) => key.keyBoxes.length > 0)
.map((key) => {
return {
id: key.id,
ciphertext: key.keyBoxes[0].ciphertext,
nonce: key.keyBoxes[0].nonce,
authorPublicKey: key.keyBoxes[0].authorPublicKey,
};
}),
}));
res.status(200).json({ spaces: spaceResults });
} catch (error) {
console.error('Error listing spaces:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.post('/connect/spaces', async (req, res) => {
console.log('POST connect/spaces');
try {
const idToken = req.headers['privy-id-token'];
const message = Schema.decodeUnknownSync(Messages.RequestConnectCreateSpaceEvent)(req.body);
const accountAddress = message.accountAddress;
const signerAddress = await getAddressByPrivyToken(idToken);
if (!(await isSignerForAccount(signerAddress, accountAddress))) {
res.status(401).send('Unauthorized');
return;
}
const space = await createSpace({
accountAddress,
event: message.event,
keyBox: message.keyBox,
infoContent: Utils.hexToBytes(message.infoContent),
infoSignatureHex: message.infoSignature.hex,
infoSignatureRecovery: message.infoSignature.recovery,
name: message.name, // TODO: remove this field and use infoContent instead
});
res.status(200).json({ space });
} catch (error) {
console.error('Error creating space:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.post('/connect/add-app-identity-to-spaces', async (req, res) => {
console.log('POST connect/add-app-identity-to-spaces');
try {
const idToken = req.headers['privy-id-token'];
const signerAddress = await getAddressByPrivyToken(idToken);
const message = Schema.decodeUnknownSync(Messages.RequestConnectAddAppIdentityToSpaces)(req.body);
if (!(await isSignerForAccount(signerAddress, message.accountAddress))) {
res.status(401).send('Unauthorized');
return;
}
const space = await addAppIdentityToSpaces({
accountAddress: message.accountAddress,
appIdentityAddress: message.appIdentityAddress,
spacesInput: message.spacesInput,
});
res.status(200).json({ space });
} catch (error) {
console.error('Error creating space:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.post('/connect/identity', async (req, res) => {
console.log('POST connect/identity');
try {
const idToken = req.headers['privy-id-token'];
const signerAddress = await getAddressByPrivyToken(idToken);
const message = Schema.decodeUnknownSync(Messages.RequestConnectCreateIdentity)(req.body);
const accountAddress = message.keyBox.accountAddress;
if (signerAddress !== message.keyBox.signer) {
res.status(401).send('Unauthorized');
return;
}
if (
!(await Identity.verifyIdentityOwnership(
accountAddress,
message.signaturePublicKey,
message.accountProof,
message.keyProof,
CHAIN,
RPC_URL,
))
) {
console.log('Ownership proof is invalid');
res.status(401).send('Unauthorized');
return;
}
console.log('Ownership proof is valid');
try {
await createIdentity({
signerAddress,
accountAddress,
ciphertext: message.keyBox.ciphertext,
nonce: message.keyBox.nonce,
signaturePublicKey: message.signaturePublicKey,
encryptionPublicKey: message.encryptionPublicKey,
accountProof: message.accountProof,
keyProof: message.keyProof,
});
} catch (error) {
console.log('Error creating identity: ', error);
const outgoingMessage: Messages.ResponseIdentityExistsError = {
accountAddress,
};
res.status(400).send(outgoingMessage);
return;
}
const outgoingMessage: Messages.ResponseConnectCreateIdentity = {
success: true,
};
res.status(200).send(outgoingMessage);
} catch (error) {
console.error('Error creating identity:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.get('/connect/identity/encrypted', async (req, res) => {
console.log('GET connect/identity/encrypted');
try {
const idToken = req.headers['privy-id-token'];
const signerAddress = await getAddressByPrivyToken(idToken);
const accountAddress = req.headers['account-address'] as string;
if (!(await isSignerForAccount(signerAddress, accountAddress))) {
res.status(401).send('Unauthorized');
return;
}
const identity = await getConnectIdentity({ accountAddress });
const outgoingMessage: Messages.ResponseIdentityEncrypted = {
keyBox: {
accountAddress,
ciphertext: identity.ciphertext,
nonce: identity.nonce,
signer: signerAddress,
},
};
res.status(200).send(outgoingMessage);
} catch (error) {
console.error('Error creating space:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.get('/connect/app-identity/:appId', async (req, res) => {
console.log('GET connect/app-identity/:appId');
try {
const idToken = req.headers['privy-id-token'];
const signerAddress = await getAddressByPrivyToken(idToken);
const accountAddress = req.headers['account-address'] as string;
if (!(await isSignerForAccount(signerAddress, accountAddress))) {
res.status(401).send('Unauthorized');
return;
}
const appId = req.params.appId;
const appIdentity = await findAppIdentity({ accountAddress, appId });
if (!appIdentity) {
console.log('App identity not found');
res.status(404).json({ message: 'App identity not found' });
return;
}
console.log('App identity found');
res.status(200).json({ appIdentity });
} catch (error) {
console.error('Error getting app identity:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.post('/connect/app-identity', async (req, res) => {
console.log('POST connect/app-identity');
try {
const idToken = req.headers['privy-id-token'];
const signerAddress = await getAddressByPrivyToken(idToken);
const message = Schema.decodeUnknownSync(Messages.RequestConnectCreateAppIdentity)(req.body);
const accountAddress = message.accountAddress;
if (!(await isSignerForAccount(signerAddress, accountAddress))) {
console.log('Signer address is not the signer for the account');
res.status(401).send('Unauthorized');
return;
}
const sessionToken = bytesToHex(randomBytes(32));
const sessionTokenExpires = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30); // 30 days
const appIdentity = await createAppIdentity({
accountAddress,
appId: message.appId,
address: message.address,
ciphertext: message.ciphertext,
nonce: message.nonce,
signaturePublicKey: message.signaturePublicKey,
encryptionPublicKey: message.encryptionPublicKey,
accountProof: message.accountProof,
keyProof: message.keyProof,
sessionToken,
sessionTokenExpires,
});
res.status(200).json({ appIdentity });
} catch (error) {
console.error('Error creating app identity:', error);
if (error instanceof Error && error.message === 'No Privy ID token provided') {
res.status(401).json({ message: 'Unauthorized' });
} else if (error instanceof Error && error.message === 'Missing Privy configuration') {
res.status(500).json({ message: 'Internal server error' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}
});
app.get('/whoami', async (req, res) => {
console.log('GET whoami');
const sessionToken = req.headers.authorization?.split(' ')[1];
if (!sessionToken) {
res.status(401).send('Unauthorized');
return;
}
try {
const { accountAddress } = await getAppIdentityBySessionToken({ sessionToken });
res.status(200).send(accountAddress);
} catch (error) {
res.status(401).send('Unauthorized');
}
});
app.get('/identity', async (req, res) => {
console.log('GET identity');
const accountAddress = req.query.accountAddress as string;
if (!accountAddress) {
res.status(400).send('No accountAddress');
return;
}
try {
const identity = await getConnectIdentity({ accountAddress });
const outgoingMessage: Messages.ResponseIdentity = {
accountAddress,
signaturePublicKey: identity.signaturePublicKey,
encryptionPublicKey: identity.encryptionPublicKey,
accountProof: identity.accountProof,
keyProof: identity.keyProof,
};
res.status(200).send(outgoingMessage);
} catch (error) {
const outgoingMessage: Messages.ResponseIdentityNotFoundError = {
accountAddress,
};
res.status(404).send(outgoingMessage);
}
});
app.get('/spaces/:spaceId/inboxes', async (req, res) => {
console.log('GET spaces/:spaceId/inboxes');
const spaceId = req.params.spaceId;
const inboxes = await listPublicSpaceInboxes({ spaceId });
const outgoingMessage: Messages.ResponseListSpaceInboxesPublic = {
inboxes,
};
res.status(200).send(outgoingMessage);
});
app.get('/spaces/:spaceId/inboxes/:inboxId', async (req, res) => {
console.log('GET spaces/:spaceId/inboxes/:inboxId');
const spaceId = req.params.spaceId;
const inboxId = req.params.inboxId;
const inbox = await getSpaceInbox({ spaceId, inboxId });
const outgoingMessage: Messages.ResponseSpaceInboxPublic = {
inbox,
};
res.status(200).send(outgoingMessage);
});
app.post('/spaces/:spaceId/inboxes/:inboxId/messages', async (req, res) => {
console.log('POST spaces/:spaceId/inboxes/:inboxId/messages');
const spaceId = req.params.spaceId;
const inboxId = req.params.inboxId;
const message = Schema.decodeUnknownSync(Messages.RequestCreateSpaceInboxMessage)(req.body);
let spaceInbox: Messages.SpaceInboxPublic;
try {
spaceInbox = await getSpaceInbox({ spaceId, inboxId });
} catch (error) {
res.status(404).send({ error: 'Inbox not found' });
return;
}
switch (spaceInbox.authPolicy) {
case 'requires_auth':
if (!message.signature || !message.authorAccountAddress) {
res.status(400).send({ error: 'Signature and authorAccountAddress required' });
return;
}
break;
case 'anonymous':
if (message.signature || message.authorAccountAddress) {
res.status(400).send({ error: 'Signature and authorAccountAddress not allowed' });
return;
}
break;
case 'optional_auth':
if (
(message.signature && !message.authorAccountAddress) ||
(!message.signature && message.authorAccountAddress)
) {
res.status(400).send({ error: 'Signature and authorAccountAddress must be provided together' });
return;
}
break;
default:
// This shouldn't happen
res.status(500).send({ error: 'Unknown auth policy' });
return;
}
if (message.signature && message.authorAccountAddress) {
// Recover the public key from the signature
const authorPublicKey = Inboxes.recoverSpaceInboxMessageSigner(message, spaceId, inboxId);
// Check if this public key corresponds to a user's identity
let authorIdentity: GetIdentityResult;
try {
authorIdentity = await getConnectIdentity({ connectSignaturePublicKey: authorPublicKey });
} catch (error) {
res.status(403).send({ error: 'Not authorized to post to this inbox' });
return;
}
if (authorIdentity.accountAddress !== message.authorAccountAddress) {
res.status(403).send({ error: 'Not authorized to post to this inbox' });
return;
}
}
const createdMessage = await createSpaceInboxMessage({ spaceId, inboxId, message });
res.status(200).send({});
broadcastSpaceInboxMessage({ spaceId, inboxId, message: createdMessage });
});
app.get('/accounts/:accountAddress/inboxes', async (req, res) => {
console.log('GET accounts/:accountAddress/inboxes');
const accountAddress = req.params.accountAddress;
const inboxes = await listPublicAccountInboxes({ accountAddress });
const outgoingMessage: Messages.ResponseListAccountInboxesPublic = {
inboxes,
};
res.status(200).send(outgoingMessage);
});
app.get('/accounts/:accountAddress/inboxes/:inboxId', async (req, res) => {
console.log('GET accounts/:accountAddress/inboxes/:inboxId');
const accountAddress = req.params.accountAddress;
const inboxId = req.params.inboxId;
const inbox = await getAccountInbox({ accountAddress, inboxId });
const outgoingMessage: Messages.ResponseAccountInboxPublic = {
inbox,
};
res.status(200).send(outgoingMessage);
});
app.post('/accounts/:accountAddress/inboxes/:inboxId/messages', async (req, res) => {
console.log('POST accounts/:accountAddress/inboxes/:inboxId/messages');
const accountAddress = req.params.accountAddress;
const inboxId = req.params.inboxId;
const message = Schema.decodeUnknownSync(Messages.RequestCreateAccountInboxMessage)(req.body);
let accountInbox: Messages.AccountInboxPublic;
try {
accountInbox = await getAccountInbox({ accountAddress, inboxId });
} catch (error) {
res.status(404).send({ error: 'Inbox not found' });
return;
}
switch (accountInbox.authPolicy) {
case 'requires_auth':
if (!message.signature || !message.authorAccountAddress) {
res.status(400).send({ error: 'Signature and authorAccountAddress required' });
return;
}
break;
case 'anonymous':
if (message.signature || message.authorAccountAddress) {
res.status(400).send({ error: 'Signature and authorAccountAddress not allowed' });
return;
}
break;
case 'optional_auth':
if (
(message.signature && !message.authorAccountAddress) ||
(!message.signature && message.authorAccountAddress)
) {
res.status(400).send({ error: 'Signature and authorAccountAddress must be provided together' });
return;
}
break;
default:
// This shouldn't happen
res.status(500).send({ error: 'Unknown auth policy' });
return;
}
if (message.signature && message.authorAccountAddress) {
// Recover the public key from the signature
const authorPublicKey = Inboxes.recoverAccountInboxMessageSigner(message, accountAddress, inboxId);
// Check if this public key corresponds to a user's identity
let authorIdentity: GetIdentityResult;
try {
authorIdentity = await getConnectIdentity({ connectSignaturePublicKey: authorPublicKey });
} catch (error) {
res.status(403).send({ error: 'Not authorized to post to this inbox' });
return;
}
if (authorIdentity.accountAddress !== message.authorAccountAddress) {
res.status(403).send({ error: 'Not authorized to post to this inbox' });
return;
}
}
const createdMessage = await createAccountInboxMessage({ accountAddress, inboxId, message });
res.status(200).send({});
broadcastAccountInboxMessage({ accountAddress, inboxId, message: createdMessage });
});
// Global error handling middleware
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
console.error('Unhandled error:', error);
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'development' ? error.message : 'Something went wrong',
});
});
// 404 handler
app.use('*', (req: Request, res: Response) => {
res.status(404).json({ error: 'Route not found' });
});
const server = app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
// Global process error handlers
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
// Graceful shutdown
server.close(() => {
console.log('Server closed due to uncaught exception');
process.exit(1);
});
});
// Graceful shutdown handlers
const gracefulShutdown = (signal: string) => {
console.log(`Received ${signal}. Starting graceful shutdown...`);
server.close(() => {
console.log('HTTP server closed');
webSocketServer.close(() => {
console.log('WebSocket server closed');
process.exit(0);
});
});
// Force close after 30 seconds
setTimeout(() => {
console.error('Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 30000);
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
function broadcastSpaceEvents({
spaceId,
event,
currentClient,
}: { spaceId: string; event: SpaceEvents.SpaceEvent; currentClient: CustomWebSocket }) {
for (const client of webSocketServer.clients as Set<CustomWebSocket>) {
if (currentClient === client) continue;
const outgoingMessage: Messages.ResponseSpaceEvent = {
type: 'space-event',
spaceId,
event,
};
if (client.readyState === WebSocket.OPEN && client.subscribedSpaces.has(spaceId)) {
client.send(Messages.serialize(outgoingMessage));
}
}
}
function broadcastUpdates({
spaceId,
updates,
currentClient,
}: { spaceId: string; updates: Messages.Updates; currentClient: CustomWebSocket }) {
for (const client of webSocketServer.clients as Set<CustomWebSocket>) {
if (currentClient === client) continue;
const outgoingMessage: Messages.ResponseUpdatesNotification = {
type: 'updates-notification',
updates,
spaceId,
};
if (client.readyState === WebSocket.OPEN && client.subscribedSpaces.has(spaceId)) {
client.send(Messages.serialize(outgoingMessage));
}
}
}
function broadcastSpaceInboxMessage({
spaceId,
inboxId,
message,
}: { spaceId: string; inboxId: string; message: Messages.InboxMessage }) {
const outgoingMessage: Messages.ResponseSpaceInboxMessage = {
type: 'space-inbox-message',
spaceId,
inboxId,
message,
};
for (const client of webSocketServer.clients as Set<CustomWebSocket>) {
if (client.readyState === WebSocket.OPEN && client.subscribedSpaces.has(spaceId)) {
client.send(Messages.serialize(outgoingMessage));
}
}
}
function broadcastAccountInbox({ inbox }: { inbox: Messages.AccountInboxPublic }) {
const outgoingMessage: Messages.ResponseAccountInbox = {
type: 'account-inbox',
inbox,
};
for (const client of webSocketServer.clients as Set<CustomWebSocket>) {
if (client.readyState === WebSocket.OPEN && client.accountAddress === inbox.accountAddress) {
client.send(Messages.serialize(outgoingMessage));
}
}
}
function broadcastAccountInboxMessage({
accountAddress,
inboxId,
message,
}: { accountAddress: string; inboxId: string; message: Messages.InboxMessage }) {
const outgoingMessage: Messages.ResponseAccountInboxMessage = {
type: 'account-inbox-message',
accountAddress,
inboxId,
message,
};
for (const client of webSocketServer.clients as Set<CustomWebSocket>) {
if (client.readyState === WebSocket.OPEN && client.accountAddress === accountAddress) {
client.send(Messages.serialize(outgoingMessage));
}
}
}
webSocketServer.on('connection', async (webSocket: CustomWebSocket, request: Request) => {
console.log('WS connection');
const params = parse(request.url, true);
if (!params.query.token || typeof params.query.token !== 'string') {
console.log('No token');
webSocket.close();
return;
}
let accountAddress: string;
let appIdentityAddress: string;
try {
const result = await getAppIdentityBySessionToken({ sessionToken: params.query.token });
accountAddress = result.accountAddress;
webSocket.accountAddress = result.accountAddress;
appIdentityAddress = result.address;
webSocket.appIdentityAddress = result.address;
} catch (error) {
console.log('Invalid token');
webSocket.close();
return;
}
console.log('Account Address:', accountAddress);
webSocket.subscribedSpaces = new Set();
console.log('Connection established', accountAddress);
webSocket.on('message', async (message) => {
const rawData = Messages.deserialize(message.toString());
const result = decodeRequestMessage(rawData);
if (result._tag === 'Right') {
const data = result.right;
switch (data.type) {
case 'subscribe-space': {
const space = await getSpace({ accountAddress, spaceId: data.id });
const outgoingMessage: Messages.ResponseSpace = {
...space,
type: 'space',
};
webSocket.subscribedSpaces.add(data.id);
webSocket.send(Messages.serialize(outgoingMessage));
break;
}
case 'list-spaces': {
const spaces = await listSpacesByAppIdentity({ appIdentityAddress });
const outgoingMessage: Messages.ResponseListSpaces = { type: 'list-spaces', spaces: spaces };
webSocket.send(Messages.serialize(outgoingMessage));
break;
}
case 'list-invitations': {
const invitations = await listInvitations({ accountAddress });
const outgoingMessage: Messages.ResponseListInvitations = {
type: 'list-invitations',
invitations: invitations,
};
webSocket.send(Messages.serialize(outgoingMessage));
break;
}
case 'create-space-event': {
const getVerifiedIdentity = (accountAddressToFetch: string) => {
console.log(
'TODO getVerifiedIdentity should work for app identities',
accountAddressToFetch,
accountAddress,
);
if (accountAddressToFetch !== accountAddress) {
return Effect.fail(new Identity.InvalidIdentityError());
}
return Effect.gen(function* () {
const identity = yield* Effect.tryPromise({
try: () => getConnectIdentity({ accountAddress: accountAddressToFetch }),
catch: () => new Identity.InvalidIdentityError(),
});
return identity;
});
};
const applyEventResult = await Effect.runPromiseExit(
SpaceEvents.applyEvent({
event: data.event,
state: undefined,
getVerifiedIdentity,
}),
);
if (Exit.isSuccess(applyEventResult)) {
const space = await createSpace({
accountAddress,
event: data.event,
keyBox: data.keyBox,
infoContent: new Uint8Array(),
infoSignatureHex: '',
infoSignatureRecovery: 0,
name: data.name,
});
const spaceWithEvents = await getSpace({ accountAddress, spaceId: space.id });
const outgoingMessage: Messages.ResponseSpace = {
...spaceWithEvents,
type: 'space',
};
webSocket.send(Messages.serialize(outgoingMessage));
} else {
console.log('Failed to apply create space event');
console.log(applyEventResult);
}
// TODO send back error
break;
}
case 'create-invitation-event': {
await applySpaceEvent({
accountAddress,
spaceId: data.spaceId,
event: data.event,
keyBoxes: data.keyBoxes.map((keyBox) => keyBox),
});
const spaceWithEvents = await getSpace({ accountAddress, spaceId: data.spaceId });
// TODO send back confirmation instead of the entire space
const outgoingMessage: Messages.ResponseSpace = {
...spaceWithEvents,
type: 'space',
};
webSocket.send(Messages.serialize(outgoingMessage));
for (const client of webSocketServer.clients as Set<CustomWebSocket>) {
if (
client.readyState === WebSocket.OPEN &&
client.accountAddress === data.event.transaction.inviteeAccountAddress
) {
const invitations = await listInvitations({ accountAddress: client.accountAddress });
const outgoingMessage: Messages.ResponseListInvitations = {
type: 'list-invitations',
invitations: invitations,
};
// for now sending the entire list of invitations to the client - we could send only a single one
client.send(Messages.serialize(outgoingMessage));
}
}
broadcastSpaceEvents({ spaceId: data.spaceId, event: data.event, currentClient: webSocket });
break;
}
case 'accept-invitation-event': {
await applySpaceEvent({ accountAddress, spaceId: data.spaceId, event: data.event, keyBoxes: [] });
const spaceWithEvents = await getSpace({ accountAddress, spaceId: data.spaceId });
const outgoingMessage: Messages.ResponseSpace = {
...spaceWithEvents,
type: 'space',
};
webSocket.send(Messages.serialize(outgoingMessage));
broadcastSpaceEvents({ spaceId: data.spaceId, event: data.event, currentClient: webSocket });
break;
}
case 'create-space-inbox-event': {
await applySpaceEvent({ accountAddress, spaceId: data.spaceId, event: data.event, keyBoxes: [] });
const spaceWithEvents = await getSpace({ accountAddress, spaceId: data.spaceId });
// TODO send back confirmation instead of the entire space
const outgoingMessage: Messages.ResponseSpace = {
...spaceWithEvents,
type: 'space',
};
webSocket.send(Messages.serialize(outgoingMessage));
broadcastSpaceEvents({ spaceId: data.spaceId, event: data.event, currentClient: webSocket });
break;
}
case 'create-account-inbox': {
try {
// Check that the signature is valid for the corresponding accountAddress
if (data.accountAddress !== accountAddress) {
throw new Error('Invalid accountAddress');
}
const signer = Inboxes.recoverAccountInboxCreatorKey(data);
const signerAccount = await getConnectIdentity({ connectSignaturePublicKey: signer });
if (signerAccount.accountAddress !== accountAddress) {
throw new Error('Invalid signature');
}
// Create the inbox (if it doesn't exist)
await createAccountInbox(data);
// Broadcast the inbox to other clients from the same account
broadcastAccountInbox({ inbox: data });
} catch (error) {
console.error('Error creating account inbox:', error);
return;
}
break;
}
case 'get-latest-space-inbox-messages': {
try {
// Check that the user has access to this space
await getSpace({ accountAddress, spaceId: data.spaceId });
const messages = await getLatestSpaceInboxMessages({
inboxId: data.inboxId,
since: data.since,
});
const outgoingMessage: Messages.ResponseSpaceInboxMessages = {
type: 'space-inbox-messages',
spaceId: data.spaceId,
inboxId: data.inboxId,
messages,
};
webSocket.send(Messages.serialize(outgoingMessage));
} catch (error) {
console.error('Error getting latest space inbox messages:', error);
return;
}
break;
}
case 'get-latest-account-inbox-messages': {
try {
// Check that the user has access to this inbox
await getAccountInbox({ accountAddress, inboxId: data.inboxId });
const messages = await getLatestAccountInboxMessages({
inboxId: data.inboxId,
since: data.since,
});
const outgoingMessage: Messages.ResponseAccountInboxMessages = {
type: 'account-inbox-messages',
accountAddress,
inboxId: data.inboxId,
messages,
};
webSocket.send(Messages.serialize(outgoingMessage));
} catch (error) {
console.error('Error getting latest account inbox messages:', error);
return;
}
break;
}
case 'get-account-inboxes': {
const inboxes = await listAccountInboxes({ accountAddress });
const outgoingMessage: Messages.ResponseAccountInboxes = {
type: 'account-inboxes',
inboxes,
};
webSocket.send(Messages.serialize(outgoingMessage));
break;
}
case 'create-update': {
try {
// Check that the update was signed by a valid identity
// belonging to this accountAddress
const signer = Messages.recoverUpdateMessageSigner(data);
const identity = await getConnectIdentity({ connectSignaturePublicKey: signer });
if (identity.accountAddress !== accountAddress) {
throw new Error('Invalid signature');
}
const update = await createUpdate({
accountAddress,
spaceId: data.spaceId,
update: data.update,
signatureHex: data.signature.hex,
signatureRecovery: data.signature.recovery,
updateId: data.updateId,
});
const outgoingMessage: Messages.ResponseUpdateConfirmed = {
type: 'update-confirmed',
updateId: data.updateId,
clock: update.clock,
spaceId: data.spaceId,
};
webSocket.send(Messages.serialize(outgoingMessage));
broadcastUpdates({
spaceId: data.spaceId,
updates: {
updates: [
{
accountAddress,
update: data.update,
signature: data.signature,
updateId: data.updateId,
},
],
firstUpdateClock: update.clock,
lastUpdateClock: update.clock,
},
currentClient: webSocket,
});
} catch (err) {
console.error('Error creating update:', err);
}
break;
}
default:
Utils.assertExhaustive(data);
break;
}
}
});
webSocket.on('close', () => {
console.log('Connection closed');
});
});
server.on('upgrade', async (request, socket, head) => {
webSocketServer.handleUpgrade(request, socket, head, (currentSocket) => {
webSocketServer.emit('connection', currentSocket, request);
});
});