@canton-network/wallet-gateway-remote 1.5.0 → 1.7.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 (108) hide show
  1. package/README.md +9 -2
  2. package/dist/config/Config.d.ts +9 -0
  3. package/dist/config/Config.d.ts.map +1 -1
  4. package/dist/config/Config.js +5 -0
  5. package/dist/dapp-api/controller.d.ts +5 -1
  6. package/dist/dapp-api/controller.d.ts.map +1 -1
  7. package/dist/dapp-api/controller.js +96 -37
  8. package/dist/dapp-api/controller.test.js +25 -8
  9. package/dist/dapp-api/server.d.ts +3 -2
  10. package/dist/dapp-api/server.d.ts.map +1 -1
  11. package/dist/dapp-api/server.js +26 -14
  12. package/dist/dapp-api/server.test.js +1 -6
  13. package/dist/env.d.ts +1 -0
  14. package/dist/env.d.ts.map +1 -1
  15. package/dist/env.js +1 -0
  16. package/dist/example-config.d.ts +3 -0
  17. package/dist/example-config.d.ts.map +1 -1
  18. package/dist/example-config.js +3 -0
  19. package/dist/init.d.ts.map +1 -1
  20. package/dist/init.js +20 -2
  21. package/dist/ledger/transaction-service.d.ts +2 -12
  22. package/dist/ledger/transaction-service.d.ts.map +1 -1
  23. package/dist/ledger/transaction-service.js +65 -43
  24. package/dist/ledger/transaction-service.test.js +104 -26
  25. package/dist/ledger/wallet-sync-service.test.js +2 -1
  26. package/dist/middleware/apiKeyAuth.d.ts.map +1 -1
  27. package/dist/middleware/apiKeyAuth.js +14 -3
  28. package/dist/middleware/securityHeaders.d.ts +3 -0
  29. package/dist/middleware/securityHeaders.d.ts.map +1 -0
  30. package/dist/middleware/securityHeaders.js +10 -0
  31. package/dist/middleware/securityHeaders.test.d.ts +2 -0
  32. package/dist/middleware/securityHeaders.test.d.ts.map +1 -0
  33. package/dist/middleware/securityHeaders.test.js +18 -0
  34. package/dist/middleware/sessionHandler.d.ts.map +1 -1
  35. package/dist/middleware/sessionHandler.js +3 -1
  36. package/dist/signing/service-account-session.d.ts +16 -0
  37. package/dist/signing/service-account-session.d.ts.map +1 -0
  38. package/dist/signing/service-account-session.js +25 -0
  39. package/dist/signing/service-account-session.test.d.ts +2 -0
  40. package/dist/signing/service-account-session.test.d.ts.map +1 -0
  41. package/dist/signing/service-account-session.test.js +89 -0
  42. package/dist/signing/signing-worker.d.ts +82 -0
  43. package/dist/signing/signing-worker.d.ts.map +1 -0
  44. package/dist/signing/signing-worker.js +210 -0
  45. package/dist/signing/signing-worker.test.d.ts +2 -0
  46. package/dist/signing/signing-worker.test.d.ts.map +1 -0
  47. package/dist/signing/signing-worker.test.js +154 -0
  48. package/dist/user-api/controller.d.ts.map +1 -1
  49. package/dist/user-api/controller.js +98 -42
  50. package/dist/user-api/controller.test.js +191 -18
  51. package/dist/user-api/rpc-gen/typings.d.ts +46 -7
  52. package/dist/user-api/rpc-gen/typings.d.ts.map +1 -1
  53. package/dist/user-api/token-network-matching.d.ts +4 -0
  54. package/dist/user-api/token-network-matching.d.ts.map +1 -0
  55. package/dist/user-api/token-network-matching.js +56 -0
  56. package/dist/web/frontend/404/index.html +2 -2
  57. package/dist/web/frontend/activities/index.html +3 -4
  58. package/dist/web/frontend/approve/index.html +3 -5
  59. package/dist/web/frontend/assets/404-C0zn3s5P.js +5 -0
  60. package/dist/web/frontend/assets/activities-BuOktGvz.js +61 -0
  61. package/dist/web/frontend/assets/addIdentityProvider-D91uvfNz.js +28 -0
  62. package/dist/web/frontend/assets/addNetwork-DP0iR59C.js +38 -0
  63. package/dist/web/frontend/assets/addParty-DUoPRmUF.js +45 -0
  64. package/dist/web/frontend/assets/approve-BSMrd3FM.js +21 -0
  65. package/dist/web/frontend/assets/callback-oLJBpxTj.js +3 -0
  66. package/dist/web/frontend/assets/identityProviders-DQlERLUf.js +71 -0
  67. package/dist/web/frontend/assets/index-BjhQnXf1.js +2 -0
  68. package/dist/web/frontend/assets/index-BoxNLwXf.js +4796 -0
  69. package/dist/web/frontend/assets/index-D5Xh-WxM.js +91 -0
  70. package/dist/web/frontend/assets/login-GZTP8nvF.js +10 -0
  71. package/dist/web/frontend/assets/networks-DHe8V-HP.js +73 -0
  72. package/dist/web/frontend/assets/reviewIdentityProvider-tg2atORE.js +43 -0
  73. package/dist/web/frontend/assets/reviewNetwork-ZZv-rrzm.js +43 -0
  74. package/dist/web/frontend/assets/settings-BC6X9ar3.js +37 -0
  75. package/dist/web/frontend/callback/index.html +2 -2
  76. package/dist/web/frontend/identity-providers/add/index.html +2 -3
  77. package/dist/web/frontend/identity-providers/index.html +2 -3
  78. package/dist/web/frontend/identity-providers/review/index.html +2 -3
  79. package/dist/web/frontend/index.html +1 -1
  80. package/dist/web/frontend/login/index.html +2 -3
  81. package/dist/web/frontend/networks/add/index.html +2 -3
  82. package/dist/web/frontend/networks/index.html +2 -3
  83. package/dist/web/frontend/networks/review/index.html +2 -3
  84. package/dist/web/frontend/parties/add/index.html +3 -5
  85. package/dist/web/frontend/parties/index.html +2 -4
  86. package/dist/web/frontend/settings/index.html +2 -3
  87. package/dist/web/server.d.ts +1 -1
  88. package/dist/web/server.d.ts.map +1 -1
  89. package/dist/web/server.js +3 -3
  90. package/package.json +29 -29
  91. package/dist/web/frontend/assets/404-MVLWUPwN.js +0 -5
  92. package/dist/web/frontend/assets/activities-DaWkmGqA.js +0 -61
  93. package/dist/web/frontend/assets/addIdentityProvider--rBb0ihb.js +0 -28
  94. package/dist/web/frontend/assets/addNetwork-C6UDsRkU.js +0 -38
  95. package/dist/web/frontend/assets/addParty-B3fFD1eM.js +0 -45
  96. package/dist/web/frontend/assets/approve-WbGL4E82.js +0 -21
  97. package/dist/web/frontend/assets/callback--tihEryB.js +0 -1
  98. package/dist/web/frontend/assets/identityProviders-Dra4qG6t.js +0 -71
  99. package/dist/web/frontend/assets/index-Bm76pXA_.js +0 -91
  100. package/dist/web/frontend/assets/index-CiMGhYb1.js +0 -2
  101. package/dist/web/frontend/assets/index-D1dC4Cl9.js +0 -4477
  102. package/dist/web/frontend/assets/login-BC8a-kD_.js +0 -10
  103. package/dist/web/frontend/assets/networks-B3ztsogL.js +0 -73
  104. package/dist/web/frontend/assets/reviewIdentityProvider-Co420Dbk.js +0 -43
  105. package/dist/web/frontend/assets/reviewNetwork-B-Sh8pCH.js +0 -43
  106. package/dist/web/frontend/assets/settings-DvyUjqLl.js +0 -37
  107. package/dist/web/frontend/assets/state-Bq65GwdF.js +0 -1
  108. package/dist/web/frontend/assets/utils-B2iziW8V.js +0 -1
@@ -14,6 +14,7 @@ import { v4 } from 'uuid';
14
14
  import { TransactionService } from '../ledger/transaction-service.js';
15
15
  import { rpcErrors } from '@canton-network/core-rpc-errors';
16
16
  import crypto from 'crypto';
17
+ import { assertTokenClaimsMatchNetwork } from './token-network-matching.js';
17
18
  export const userController = (kernelInfo, userUrl, store, notificationService, authContext, drivers, _logger, adminUserId) => {
18
19
  const logger = _logger.child({ component: 'user-controller' });
19
20
  const provider = {
@@ -46,6 +47,9 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
46
47
  const adminAuth = network.adminAuth
47
48
  ? authSchema.parse(network.adminAuth)
48
49
  : undefined;
50
+ const serviceAccountAuth = network.serviceAccountAuth
51
+ ? authSchema.parse(network.serviceAccountAuth)
52
+ : undefined;
49
53
  const newNetwork = {
50
54
  name: network.name,
51
55
  id: network.id,
@@ -54,6 +58,7 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
54
58
  identityProviderId: network.identityProviderId,
55
59
  auth,
56
60
  adminAuth,
61
+ serviceAccountAuth,
57
62
  ledgerApi,
58
63
  };
59
64
  // TODO: Add an explicit updateNetwork method to the User API spec and controller
@@ -145,7 +150,6 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
145
150
  if (!network.adminAuth) {
146
151
  throw new Error('No admin auth configured');
147
152
  }
148
- const notifier = notificationService.getNotifier(connectedContext.userId);
149
153
  const adminTokenProvider = AuthTokenProvider.fromGatewayConfig(idp, network.adminAuth, logger);
150
154
  const partyAllocator = new PartyAllocationService({
151
155
  synchronizerId: network.synchronizerId,
@@ -168,12 +172,13 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
168
172
  await service.syncWallets();
169
173
  // Notify about the change and return the new wallet
170
174
  const wallets = await store.getWallets();
171
- notifier?.emit('accountsChanged', wallets);
175
+ notificationService
176
+ .getNotifier(connectedContext.userId)
177
+ .emit('accountsChanged', wallets);
172
178
  return { wallet };
173
179
  },
174
180
  allocatePartyForWallet: async (params) => {
175
181
  const connectedContext = assertConnected(authContext);
176
- const userId = connectedContext.userId;
177
182
  const network = await store.getCurrentNetwork();
178
183
  if (!network) {
179
184
  throw new Error('No network session found');
@@ -212,17 +217,17 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
212
217
  const wallets = await store.getWallets();
213
218
  const wallet = wallets.find((w) => w.partyId === existingWallet.partyId &&
214
219
  w.networkId === network.id);
215
- const notifier = notificationService.getNotifier(userId);
216
- notifier?.emit('accountsChanged', wallets);
220
+ notificationService
221
+ .getNotifier(connectedContext.userId)
222
+ .emit('accountsChanged', wallets);
217
223
  return { wallet };
218
224
  },
219
225
  setPrimaryWallet: async (params) => {
220
226
  await store.setPrimaryWallet(params.partyId);
221
- const notifier = authContext?.userId
222
- ? notificationService.getNotifier(authContext.userId)
223
- : undefined;
224
227
  const wallets = await store.getWallets();
225
- notifier?.emit('accountsChanged', wallets);
228
+ notificationService
229
+ .getNotifier(authContext.userId)
230
+ .emit('accountsChanged', wallets);
226
231
  return null;
227
232
  },
228
233
  removeWallet: async (params) => {
@@ -242,8 +247,11 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
242
247
  throw new Error('No primary wallet found');
243
248
  }
244
249
  const connectedContext = assertConnected(authContext);
245
- const userId = connectedContext.userId;
246
- const notifier = notificationService.getNotifier(userId);
250
+ const session = await store.getSession(connectedContext.accessToken);
251
+ if (!session) {
252
+ throw new Error('No active session found');
253
+ }
254
+ const notifier = notificationService.getNotifier(session.id);
247
255
  const transactionService = new TransactionService(store, logger, drivers, notifier);
248
256
  logDynamically(logger, 'signing transaction with params', {
249
257
  info: { transactionId: signParams.transactionId },
@@ -268,7 +276,11 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
268
276
  if (pending.userId !== userId) {
269
277
  throw new Error(`Message signing request ${pending.id} is not owned by user ${userId}`);
270
278
  }
271
- const notifier = notificationService.getNotifier(userId);
279
+ const session = await store.getSession(assertConnected(authContext).accessToken);
280
+ if (!session) {
281
+ throw new Error('No active session found');
282
+ }
283
+ const notifier = notificationService.getNotifier(session.id);
272
284
  const emitFailedAndPersist = async (details) => {
273
285
  // Best-effort: make sure listeners see a terminal state.
274
286
  try {
@@ -407,7 +419,11 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
407
419
  if (network === undefined) {
408
420
  throw new Error('No network session found');
409
421
  }
410
- const notifier = notificationService.getNotifier(connectedContext.userId);
422
+ const session = await store.getSession(connectedContext.accessToken);
423
+ if (!session) {
424
+ throw new Error('No active session found');
425
+ }
426
+ const notifier = notificationService.getNotifier(session.id);
411
427
  const ledgerClient = new LedgerClient({
412
428
  baseUrl: new URL(network.ledgerApi.baseUrl),
413
429
  logger,
@@ -432,18 +448,20 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
432
448
  },
433
449
  addSession: async function (params) {
434
450
  try {
451
+ const connectedContext = assertConnected(authContext);
452
+ const { userId, accessToken } = connectedContext;
435
453
  const newSessionId = v4();
436
454
  logger.info(`Adding session with ID ${newSessionId} for network ${params.networkId}`);
455
+ const network = await store.getNetwork(params.networkId);
456
+ const idp = await store.getIdp(network.identityProviderId);
457
+ assertTokenClaimsMatchNetwork(accessToken, network, idp);
437
458
  await store.setSession({
438
459
  id: newSessionId,
460
+ origin: params.origin,
439
461
  network: params.networkId,
440
- accessToken: authContext?.accessToken || '',
462
+ accessToken: connectedContext.accessToken || '',
441
463
  });
442
- const network = await store.getCurrentNetwork();
443
- const idp = await store.getIdp(network.identityProviderId);
444
- // Assumption: `setSession` calls `assertConnected`, so its safe to declare that the authContext is defined.
445
- const { userId, accessToken } = authContext;
446
- const notifier = notificationService.getNotifier(userId);
464
+ const notifier = notificationService.getNotifier(newSessionId);
447
465
  const ledgerClient = new LedgerClient({
448
466
  baseUrl: new URL(network.ledgerApi.baseUrl),
449
467
  logger,
@@ -470,21 +488,36 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
470
488
  };
471
489
  notifier.emit('statusChanged', statusEvent);
472
490
  notifier.emit('connected', statusEvent);
473
- //we only want to automatically perform a sync if it is the first time a session is created
491
+ // Only bootstrap wallets the first time a session is created.
492
+ // Session creation must remain successful when the ledger or
493
+ // wallet synchronization is unavailable.
474
494
  const wallets = await store.getWallets();
475
- if (wallets.length == 0) {
476
- if (!network.adminAuth) {
477
- throw new Error('No admin auth configured');
495
+ if (wallets.length === 0) {
496
+ if (!status.isConnected) {
497
+ logger.warn({
498
+ networkId: network.id,
499
+ reason: status.reason,
500
+ }, 'Skipping initial wallet sync because the ledger is unavailable');
501
+ }
502
+ else {
503
+ try {
504
+ if (!network.adminAuth) {
505
+ throw new Error('No admin auth configured');
506
+ }
507
+ const adminAccessTokenProvider = AuthTokenProvider.fromGatewayConfig(idp, network.adminAuth, logger);
508
+ const partyAllocator = new PartyAllocationService({
509
+ synchronizerId: network.synchronizerId,
510
+ accessTokenProvider: adminAccessTokenProvider,
511
+ httpLedgerUrl: network.ledgerApi.baseUrl,
512
+ logger,
513
+ });
514
+ const service = new WalletSyncService(store, ledgerClient, connectedContext, logger, drivers, partyAllocator);
515
+ await service.syncWallets();
516
+ }
517
+ catch (error) {
518
+ logger.warn({ err: error, networkId: network.id }, 'Initial wallet sync failed; keeping session active');
519
+ }
478
520
  }
479
- const adminAccessTokenProvider = AuthTokenProvider.fromGatewayConfig(idp, network.adminAuth, logger);
480
- const partyAllocator = new PartyAllocationService({
481
- synchronizerId: network.synchronizerId,
482
- accessTokenProvider: adminAccessTokenProvider,
483
- httpLedgerUrl: network.ledgerApi.baseUrl,
484
- logger,
485
- });
486
- const service = new WalletSyncService(store, ledgerClient, authContext, logger, drivers, partyAllocator);
487
- await service.syncWallets();
488
521
  }
489
522
  const rights = await store.getUserRights(network.id);
490
523
  return {
@@ -501,7 +534,7 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
501
534
  };
502
535
  }
503
536
  catch (error) {
504
- logger.error({ error }, 'Failed to add session');
537
+ logger.error(error, 'Failed to add session');
505
538
  throw new Error(`Failed to add session`, {
506
539
  cause: error,
507
540
  });
@@ -509,9 +542,13 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
509
542
  },
510
543
  removeSession: async () => {
511
544
  logger.info({ authContext }, 'Removing session');
512
- const userId = assertConnected(authContext).userId;
513
- const notifier = notificationService.getNotifier(userId);
514
- await store.removeSession();
545
+ const { accessToken } = assertConnected(authContext);
546
+ const session = await store.getSession(accessToken);
547
+ if (!session) {
548
+ return null;
549
+ }
550
+ const notifier = notificationService.getNotifier(session.id);
551
+ await store.removeSession(accessToken);
515
552
  notifier.emit('statusChanged', {
516
553
  provider: provider,
517
554
  connection: {
@@ -524,10 +561,13 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
524
561
  session: undefined,
525
562
  userUrl: `${userUrl}/login/`,
526
563
  });
564
+ notifier.emit('logout');
527
565
  return null;
528
566
  },
567
+ // TODO: follow up with store.listSessions to display all sessions in the UI
529
568
  listSessions: async () => {
530
- const session = await store.getSession();
569
+ const token = authContext.accessToken;
570
+ const session = await store.getSession(token);
531
571
  if (!session) {
532
572
  return { sessions: [] };
533
573
  }
@@ -544,6 +584,7 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
544
584
  sessions: [
545
585
  {
546
586
  id: session.id,
587
+ origin: session.origin,
547
588
  network: {
548
589
  ...network,
549
590
  ledgerApi: network.ledgerApi.baseUrl,
@@ -585,9 +626,10 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
585
626
  result.disabled.length === 0) {
586
627
  return result;
587
628
  }
588
- const notifier = notificationService.getNotifier(userId);
589
629
  const wallets = await store.getWallets();
590
- notifier?.emit('accountsChanged', wallets);
630
+ notificationService
631
+ .getNotifier(userId)
632
+ .emit('accountsChanged', wallets);
591
633
  return result;
592
634
  },
593
635
  isWalletSyncNeeded: async () => {
@@ -642,8 +684,10 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
642
684
  }),
643
685
  };
644
686
  },
645
- listTransactions: async function () {
646
- const transactions = await store.listTransactions();
687
+ listTransactions: async function (params) {
688
+ const txCount = await store.transactionsCount();
689
+ const page = await store.listTransactions(params);
690
+ const transactions = page.transactions;
647
691
  const txs = transactions.map((transaction) => ({
648
692
  id: transaction.id,
649
693
  commandId: transaction.commandId,
@@ -666,7 +710,16 @@ export const userController = (kernelInfo, userUrl, store, notificationService,
666
710
  externalTxId: transaction.externalTxId,
667
711
  }),
668
712
  }));
669
- return { transactions: txs };
713
+ if (page.nextCursor === null) {
714
+ return { transactions: txs, count: txCount };
715
+ }
716
+ else {
717
+ return {
718
+ transactions: txs,
719
+ nextCursor: page.nextCursor,
720
+ count: txCount,
721
+ };
722
+ }
670
723
  },
671
724
  deleteTransaction: async (params) => {
672
725
  const transaction = await store.getTransaction(params.transactionId);
@@ -779,6 +832,9 @@ function toNetworkDto(network) {
779
832
  ...(network.adminAuth
780
833
  ? { adminAuth: toAuthDto(network.adminAuth) }
781
834
  : {}),
835
+ ...(network.serviceAccountAuth
836
+ ? { serviceAccountAuth: toAuthDto(network.serviceAccountAuth) }
837
+ : {}),
782
838
  };
783
839
  }
784
840
  function toPublicNetwork(network) {
@@ -34,6 +34,11 @@ const transactionServiceMocks = vi.hoisted(() => ({
34
34
  sign: vi.fn(),
35
35
  execute: vi.fn(),
36
36
  }));
37
+ const mockV4 = vi.hoisted(() => vi.fn(() => crypto.randomUUID()));
38
+ vi.mock('uuid', async (importOriginal) => {
39
+ const actual = await importOriginal();
40
+ return { ...actual, v4: mockV4 };
41
+ });
37
42
  vi.mock('@canton-network/core-ledger-client', async (importOriginal) => {
38
43
  const actual = await importOriginal();
39
44
  return {
@@ -116,8 +121,9 @@ const adminAuth = {
116
121
  };
117
122
  const session = {
118
123
  id: 'session-1',
124
+ origin: 'dapp-1',
119
125
  network: 'network1',
120
- accessToken: 'session-token',
126
+ accessToken: 'access-token-1',
121
127
  };
122
128
  const pendingTransaction = {
123
129
  id: 'tx-1',
@@ -328,7 +334,7 @@ describe('userController', () => {
328
334
  it('sets the primary wallet and emits accountsChanged', async () => {
329
335
  const store = await createStore(logger, auth);
330
336
  const setPrimarySpy = vi.spyOn(store, 'setPrimaryWallet');
331
- const notifier = notificationService.getNotifier(auth.userId);
337
+ const notifier = notificationService.getNotifier('user-1');
332
338
  const emitSpy = vi.spyOn(notifier, 'emit');
333
339
  const controller = createController(store, notificationService, logger, auth);
334
340
  await controller.setPrimaryWallet({ partyId: 'party::namespace' });
@@ -418,7 +424,7 @@ describe('userController', () => {
418
424
  controller: vi.fn(() => ({ signMessage: mockSignMessage })),
419
425
  },
420
426
  };
421
- const notifier = notificationService.getNotifier(auth.userId);
427
+ const notifier = notificationService.getNotifier('session-1');
422
428
  const emitSpy = vi.spyOn(notifier, 'emit');
423
429
  const controller = createController(store, notificationService, logger, auth, drivers);
424
430
  const result = await controller.signMessage({ messageId: 'msg-1' });
@@ -447,7 +453,7 @@ describe('userController', () => {
447
453
  signingProviderId: SigningProvider.FIREBLOCKS,
448
454
  });
449
455
  await store.setMessageRaw(pendingMessage);
450
- const notifier = notificationService.getNotifier(auth.userId);
456
+ const notifier = notificationService.getNotifier('session-1');
451
457
  const emitSpy = vi.spyOn(notifier, 'emit');
452
458
  const controller = createController(store, notificationService, logger, auth, {
453
459
  [SigningProvider.WALLET_KERNEL]: {
@@ -483,7 +489,7 @@ describe('userController', () => {
483
489
  const store = await createStore(logger, auth);
484
490
  await store.setTransaction(transaction);
485
491
  const controller = createController(store, notificationService, logger, auth);
486
- const result = await controller.listTransactions();
492
+ const result = await controller.listTransactions({});
487
493
  expect(result.transactions).toHaveLength(1);
488
494
  expect(result.transactions[0]?.id).toBe('tx-1');
489
495
  });
@@ -586,6 +592,26 @@ describe('userController', () => {
586
592
  });
587
593
  });
588
594
  describe('sessions', () => {
595
+ const validAddSessionClaims = {
596
+ iss: idp.issuer,
597
+ aud: storeNetwork.auth.audience,
598
+ sub: storeNetwork.auth.clientId,
599
+ scope: 'scope',
600
+ scp: ['scope'],
601
+ exp: 1_900_000_000,
602
+ iat: 1_800_000_000,
603
+ };
604
+ const createAuthWithAddSessionClaims = (claimsOverride = {}) => ({
605
+ ...auth,
606
+ accessToken: createJwt({
607
+ ...validAddSessionClaims,
608
+ ...claimsOverride,
609
+ }),
610
+ });
611
+ const createJwt = (payload) => {
612
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
613
+ return `${encode({ alg: 'none', typ: 'JWT' })}.${encode(payload)}.signature`;
614
+ };
589
615
  it('returns an empty list when there is no session', async () => {
590
616
  const store = await createStore(logger, auth, {
591
617
  withSession: false,
@@ -613,11 +639,11 @@ describe('userController', () => {
613
639
  });
614
640
  it('removeSession clears the session and emits statusChanged', async () => {
615
641
  const store = await createStore(logger, auth);
616
- const notifier = notificationService.getNotifier(auth.userId);
642
+ const notifier = notificationService.getNotifier('session-1');
617
643
  const emitSpy = vi.spyOn(notifier, 'emit');
618
644
  const controller = createController(store, notificationService, logger, auth);
619
645
  await controller.removeSession();
620
- await expect(store.getSession()).resolves.toBeUndefined();
646
+ await expect(store.listSessions()).resolves.toHaveLength(0);
621
647
  expect(emitSpy).toHaveBeenCalledWith('statusChanged', expect.objectContaining({
622
648
  connection: expect.objectContaining({
623
649
  isConnected: false,
@@ -627,25 +653,172 @@ describe('userController', () => {
627
653
  }));
628
654
  });
629
655
  it('addSession creates a session and emits connected', async () => {
630
- const store = await createStore(logger, auth, { withWallet: false });
631
- const notifier = notificationService.getNotifier(auth.userId);
656
+ const newSessionId = '00000000-0000-0000-0000-000000000001';
657
+ mockV4.mockReturnValueOnce(newSessionId);
658
+ const authWithValidClaims = createAuthWithAddSessionClaims();
659
+ const store = await createStore(logger, authWithValidClaims, {
660
+ withWallet: false,
661
+ });
662
+ const controller = createController(store, notificationService, logger, authWithValidClaims);
663
+ const notifier = notificationService.getNotifier(newSessionId);
632
664
  const emitSpy = vi.spyOn(notifier, 'emit');
633
- const controller = createController(store, notificationService, logger, auth);
634
665
  const result = await controller.addSession({
666
+ origin: 'dapp-1',
635
667
  networkId: 'network1',
636
668
  });
637
669
  expect(result.network.id).toBe('network1');
638
670
  expect(result.status).toBe('connected');
639
671
  expect(emitSpy).toHaveBeenCalledWith('connected', expect.objectContaining({
640
672
  session: {
641
- accessToken: auth.accessToken,
642
- userId: auth.userId,
673
+ accessToken: authWithValidClaims.accessToken,
674
+ userId: authWithValidClaims.userId,
643
675
  },
644
676
  }));
645
- await expect(store.getSession()).resolves.toMatchObject({
677
+ await expect(store.getSession(authWithValidClaims.accessToken)).resolves.toMatchObject({
646
678
  network: 'network1',
647
679
  });
648
680
  });
681
+ it('addSession keeps the session when the ledger is disconnected', async () => {
682
+ mockNetworkStatus.mockResolvedValueOnce({
683
+ isConnected: false,
684
+ reason: 'Ledger unreachable: fetch failed',
685
+ });
686
+ const authWithValidClaims = createAuthWithAddSessionClaims();
687
+ const store = await createStore(logger, authWithValidClaims, {
688
+ withWallet: false,
689
+ });
690
+ const controller = createController(store, notificationService, logger, authWithValidClaims);
691
+ const result = await controller.addSession({
692
+ networkId: 'network1',
693
+ origin: 'dapp-1',
694
+ });
695
+ expect(result.status).toBe('disconnected');
696
+ expect(result.reason).toBe('Ledger unreachable: fetch failed');
697
+ expect(walletSyncMocks.syncWallets).not.toHaveBeenCalled();
698
+ await expect(store.getSession(authWithValidClaims.accessToken)).resolves.toMatchObject({
699
+ network: 'network1',
700
+ });
701
+ });
702
+ it('addSession keeps the session when initial wallet sync fails', async () => {
703
+ walletSyncMocks.syncWallets.mockRejectedValueOnce(new Error('Wallet sync failed'));
704
+ const authWithValidClaims = createAuthWithAddSessionClaims();
705
+ const store = await createStore(logger, authWithValidClaims, {
706
+ withWallet: false,
707
+ });
708
+ const controller = createController(store, notificationService, logger, authWithValidClaims);
709
+ const result = await controller.addSession({
710
+ networkId: 'network1',
711
+ origin: 'dapp-1',
712
+ });
713
+ expect(result.status).toBe('connected');
714
+ expect(walletSyncMocks.syncWallets).toHaveBeenCalledOnce();
715
+ await expect(store.getSession(authWithValidClaims.accessToken)).resolves.toMatchObject({
716
+ network: 'network1',
717
+ });
718
+ });
719
+ it('addSession rejects token when both scope and scp are missing', async () => {
720
+ const authWithoutScopeClaims = {
721
+ ...auth,
722
+ accessToken: createJwt({
723
+ iss: idp.issuer,
724
+ aud: storeNetwork.auth.audience,
725
+ sub: storeNetwork.auth.clientId,
726
+ exp: 1_900_000_000,
727
+ iat: 1_800_000_000,
728
+ }),
729
+ };
730
+ const store = await createStore(logger, authWithoutScopeClaims, {
731
+ withWallet: false,
732
+ });
733
+ const controller = createController(store, notificationService, logger, authWithoutScopeClaims);
734
+ await expect(controller.addSession({
735
+ origin: 'dapp-1',
736
+ networkId: 'network1',
737
+ })).rejects.toThrow('Failed to add session');
738
+ });
739
+ it('addSession passes when only scope is present and matches', async () => {
740
+ const authWithScopeOnly = createAuthWithAddSessionClaims({
741
+ scp: undefined,
742
+ });
743
+ const store = await createStore(logger, authWithScopeOnly, {
744
+ withWallet: false,
745
+ });
746
+ const controller = createController(store, notificationService, logger, authWithScopeOnly);
747
+ await expect(controller.addSession({
748
+ origin: 'dapp-1',
749
+ networkId: 'network1',
750
+ })).resolves.toMatchObject({
751
+ network: expect.objectContaining({ id: 'network1' }),
752
+ status: 'connected',
753
+ });
754
+ });
755
+ it('addSession rejects when only scope is present and mismatches', async () => {
756
+ const authWithInvalidScope = createAuthWithAddSessionClaims({
757
+ scope: 'openid email',
758
+ scp: undefined,
759
+ });
760
+ const store = await createStore(logger, authWithInvalidScope, {
761
+ withWallet: false,
762
+ });
763
+ const controller = createController(store, notificationService, logger, authWithInvalidScope);
764
+ await expect(controller.addSession({
765
+ origin: 'dapp-1',
766
+ networkId: 'network1',
767
+ })).rejects.toThrow('Failed to add session');
768
+ });
769
+ it('addSession rejects when both scope and scp are present but one mismatches', async () => {
770
+ const authWithMismatchedScp = createAuthWithAddSessionClaims({
771
+ scope: 'scope',
772
+ scp: ['scope openid'],
773
+ });
774
+ const store = await createStore(logger, authWithMismatchedScp, {
775
+ withWallet: false,
776
+ });
777
+ const controller = createController(store, notificationService, logger, authWithMismatchedScp);
778
+ await expect(controller.addSession({
779
+ origin: 'dapp-1',
780
+ networkId: 'network1',
781
+ })).rejects.toThrow('Failed to add session');
782
+ });
783
+ it('addSession rejects token with issuer mismatch', async () => {
784
+ const authWithInvalidIssuer = createAuthWithAddSessionClaims({
785
+ iss: 'http://wrong-issuer',
786
+ });
787
+ const store = await createStore(logger, authWithInvalidIssuer, {
788
+ withWallet: false,
789
+ });
790
+ const controller = createController(store, notificationService, logger, authWithInvalidIssuer);
791
+ await expect(controller.addSession({
792
+ origin: 'dapp-1',
793
+ networkId: 'network1',
794
+ })).rejects.toThrow('Failed to add session');
795
+ });
796
+ it('addSession rejects token with audience mismatch', async () => {
797
+ const authWithInvalidAudience = createAuthWithAddSessionClaims({
798
+ aud: 'wrong-audience',
799
+ });
800
+ const store = await createStore(logger, authWithInvalidAudience, {
801
+ withWallet: false,
802
+ });
803
+ const controller = createController(store, notificationService, logger, authWithInvalidAudience);
804
+ await expect(controller.addSession({
805
+ origin: 'dapp-1',
806
+ networkId: 'network1',
807
+ })).rejects.toThrow('Failed to add session');
808
+ });
809
+ it('addSession rejects token with subject mismatch', async () => {
810
+ const authWithInvalidSubject = createAuthWithAddSessionClaims({
811
+ sub: 'wrong-client-id',
812
+ });
813
+ const store = await createStore(logger, authWithInvalidSubject, {
814
+ withWallet: false,
815
+ });
816
+ const controller = createController(store, notificationService, logger, authWithInvalidSubject);
817
+ await expect(controller.addSession({
818
+ origin: 'dapp-1',
819
+ networkId: 'network1',
820
+ })).rejects.toThrow('Failed to add session');
821
+ });
649
822
  });
650
823
  describe('createWallet', () => {
651
824
  const walletKernelDriver = {
@@ -678,7 +851,7 @@ describe('userController', () => {
678
851
  primary: false,
679
852
  };
680
853
  walletAllocationMocks.createWallet.mockResolvedValue(newWallet);
681
- const notifier = notificationService.getNotifier(auth.userId);
854
+ const notifier = notificationService.getNotifier('user-1');
682
855
  const emitSpy = vi.spyOn(notifier, 'emit');
683
856
  const controller = createController(store, notificationService, logger, authWithEmail, walletKernelDriver);
684
857
  const result = await controller.createWallet({
@@ -721,7 +894,7 @@ describe('userController', () => {
721
894
  it('allocates a party for an existing wallet', async () => {
722
895
  const authWithEmail = { ...auth, email: 'user@example.com' };
723
896
  const store = await createStore(logger, authWithEmail);
724
- const notifier = notificationService.getNotifier(auth.userId);
897
+ const notifier = notificationService.getNotifier('user-1');
725
898
  const emitSpy = vi.spyOn(notifier, 'emit');
726
899
  const controller = createController(store, notificationService, logger, authWithEmail, walletKernelDriver);
727
900
  const result = await controller.allocatePartyForWallet({
@@ -753,7 +926,7 @@ describe('userController', () => {
753
926
  describe('syncWallets', () => {
754
927
  it('syncs wallets and returns the result without emitting when nothing changed', async () => {
755
928
  const store = await createStore(logger, auth);
756
- const notifier = notificationService.getNotifier(auth.userId);
929
+ const notifier = notificationService.getNotifier('session-1');
757
930
  const emitSpy = vi.spyOn(notifier, 'emit');
758
931
  const emptyResult = { added: [], updated: [], disabled: [] };
759
932
  walletSyncMocks.syncWallets.mockResolvedValue(emptyResult);
@@ -784,7 +957,7 @@ describe('userController', () => {
784
957
  });
785
958
  it('emits accountsChanged when wallets are added and disabled during sync', async () => {
786
959
  const store = await createStore(logger, auth);
787
- const notifier = notificationService.getNotifier(auth.userId);
960
+ const notifier = notificationService.getNotifier('user-1');
788
961
  const emitSpy = vi.spyOn(notifier, 'emit');
789
962
  const addedWallet = {
790
963
  ...primaryWallet,
@@ -810,7 +983,7 @@ describe('userController', () => {
810
983
  });
811
984
  it('does not emit accountsChanged when only wallets are added', async () => {
812
985
  const store = await createStore(logger, auth);
813
- const notifier = notificationService.getNotifier(auth.userId);
986
+ const notifier = notificationService.getNotifier('session-1');
814
987
  const emitSpy = vi.spyOn(notifier, 'emit');
815
988
  walletSyncMocks.syncWallets.mockResolvedValue({
816
989
  added: [{ ...primaryWallet, partyId: 'party::added' }],