@canton-network/core-wallet-store-sql 1.13.2 → 1.15.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 (88) hide show
  1. package/dist/bootstrap.d.ts +4 -4
  2. package/dist/bootstrap.d.ts.map +1 -1
  3. package/dist/index.cjs +87 -29
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.js +87 -29
  6. package/dist/index.js.map +1 -1
  7. package/dist/migrations/001-init.d.ts +2 -2
  8. package/dist/migrations/001-init.d.ts.map +1 -1
  9. package/dist/migrations/002-add-transaction-timestamps.d.ts +2 -2
  10. package/dist/migrations/002-add-transaction-timestamps.d.ts.map +1 -1
  11. package/dist/migrations/003-add-transaction-origin.d.ts +2 -2
  12. package/dist/migrations/003-add-transaction-origin.d.ts.map +1 -1
  13. package/dist/migrations/004-add-session-id.d.ts +2 -2
  14. package/dist/migrations/004-add-session-id.d.ts.map +1 -1
  15. package/dist/migrations/005-add-wallet-disabled-reason.d.ts +2 -2
  16. package/dist/migrations/005-add-wallet-disabled-reason.d.ts.map +1 -1
  17. package/dist/migrations/006-change-wallet-primary-key-to-composite.d.ts +2 -2
  18. package/dist/migrations/006-change-wallet-primary-key-to-composite.d.ts.map +1 -1
  19. package/dist/migrations/007-add-unique-primary-per-network.d.ts +2 -2
  20. package/dist/migrations/007-add-unique-primary-per-network.d.ts.map +1 -1
  21. package/dist/migrations/008-add-transaction-external-tx-id.d.ts +2 -2
  22. package/dist/migrations/008-add-transaction-external-tx-id.d.ts.map +1 -1
  23. package/dist/migrations/009-add-wallet-rights-columns.d.ts +2 -2
  24. package/dist/migrations/009-add-wallet-rights-columns.d.ts.map +1 -1
  25. package/dist/migrations/010-add-transaction-network-id.d.ts +2 -2
  26. package/dist/migrations/010-add-transaction-network-id.d.ts.map +1 -1
  27. package/dist/migrations/011-add-transaction-id-primary-key.d.ts +2 -2
  28. package/dist/migrations/011-add-transaction-id-primary-key.d.ts.map +1 -1
  29. package/dist/migrations/012-add-messages-to-sign.d.ts +1 -1
  30. package/dist/migrations/012-add-messages-to-sign.d.ts.map +1 -1
  31. package/dist/migrations/013-add-api-key.d.ts +1 -1
  32. package/dist/migrations/013-add-api-key.d.ts.map +1 -1
  33. package/dist/migrations/014-add-service-account-column.d.ts +2 -2
  34. package/dist/migrations/014-add-service-account-column.d.ts.map +1 -1
  35. package/dist/migrations/015-add-origin-field-session.d.ts +2 -2
  36. package/dist/migrations/015-add-origin-field-session.d.ts.map +1 -1
  37. package/dist/migrations/016-add-failure-reason-and-awaiting-signature.d.ts +5 -0
  38. package/dist/migrations/016-add-failure-reason-and-awaiting-signature.d.ts.map +1 -0
  39. package/dist/migrations/016-add-failure-reason-and-awaiting-signature.js +27 -0
  40. package/dist/migrations/017-make-idp-issuer-nullable.d.ts +5 -0
  41. package/dist/migrations/017-make-idp-issuer-nullable.d.ts.map +1 -0
  42. package/dist/migrations/017-make-idp-issuer-nullable.js +88 -0
  43. package/dist/migrations/018-add-wallet-is-auth-party.d.ts +5 -0
  44. package/dist/migrations/018-add-wallet-is-auth-party.d.ts.map +1 -0
  45. package/dist/migrations/018-add-wallet-is-auth-party.js +11 -0
  46. package/dist/migrations/019-make-session-access-token-nullable.d.ts +5 -0
  47. package/dist/migrations/019-make-session-access-token-nullable.d.ts.map +1 -0
  48. package/dist/migrations/019-make-session-access-token-nullable.js +92 -0
  49. package/dist/migrations-test/helpers.d.ts +2 -2
  50. package/dist/migrations-test/helpers.d.ts.map +1 -1
  51. package/dist/migrations-test/seeds/001-init.d.ts +2 -2
  52. package/dist/migrations-test/seeds/001-init.d.ts.map +1 -1
  53. package/dist/migrations-test/seeds/002-transaction-timestamps.d.ts +2 -2
  54. package/dist/migrations-test/seeds/002-transaction-timestamps.d.ts.map +1 -1
  55. package/dist/migrations-test/seeds/003-transaction-origin.d.ts +2 -2
  56. package/dist/migrations-test/seeds/003-transaction-origin.d.ts.map +1 -1
  57. package/dist/migrations-test/seeds/004-add-session-id.d.ts +2 -2
  58. package/dist/migrations-test/seeds/004-add-session-id.d.ts.map +1 -1
  59. package/dist/migrations-test/seeds/005-add-wallet-disabled-reason.d.ts +2 -2
  60. package/dist/migrations-test/seeds/005-add-wallet-disabled-reason.d.ts.map +1 -1
  61. package/dist/migrations-test/seeds/008-transaction-external-tx-id.d.ts +2 -2
  62. package/dist/migrations-test/seeds/008-transaction-external-tx-id.d.ts.map +1 -1
  63. package/dist/migrations-test/seeds/009-add-wallet-rights-columns.d.ts +2 -2
  64. package/dist/migrations-test/seeds/009-add-wallet-rights-columns.d.ts.map +1 -1
  65. package/dist/migrations-test/seeds/010-transaction-with-network.d.ts +2 -2
  66. package/dist/migrations-test/seeds/010-transaction-with-network.d.ts.map +1 -1
  67. package/dist/migrations-test/seeds/012-add-messages-to-sign.d.ts +2 -2
  68. package/dist/migrations-test/seeds/012-add-messages-to-sign.d.ts.map +1 -1
  69. package/dist/migrations-test/seeds/013-add-api-key.d.ts +2 -2
  70. package/dist/migrations-test/seeds/013-add-api-key.d.ts.map +1 -1
  71. package/dist/migrations-test/seeds/014-add-service-account-column.d.ts +2 -2
  72. package/dist/migrations-test/seeds/014-add-service-account-column.d.ts.map +1 -1
  73. package/dist/migrations-test/seeds/016-add-failure-reason-and-awaiting-signature.d.ts +18 -0
  74. package/dist/migrations-test/seeds/016-add-failure-reason-and-awaiting-signature.d.ts.map +1 -0
  75. package/dist/migrations-test/seeds/017-make-idp-issuer-nullable.d.ts +9 -0
  76. package/dist/migrations-test/seeds/017-make-idp-issuer-nullable.d.ts.map +1 -0
  77. package/dist/migrations-test/seeds/019-make-session-access-token-nullable.d.ts +10 -0
  78. package/dist/migrations-test/seeds/019-make-session-access-token-nullable.d.ts.map +1 -0
  79. package/dist/migrator.d.ts +2 -2
  80. package/dist/migrator.d.ts.map +1 -1
  81. package/dist/schema.d.ts +8 -6
  82. package/dist/schema.d.ts.map +1 -1
  83. package/dist/schema.js +26 -5
  84. package/dist/store-sql.d.ts +14 -7
  85. package/dist/store-sql.d.ts.map +1 -1
  86. package/dist/utils.d.ts +2 -2
  87. package/dist/utils.d.ts.map +1 -1
  88. package/package.json +20 -12
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { assertConnected, authSchema } from "@canton-network/core-wallet-auth";
2
+ import { providerErrors } from "@canton-network/core-rpc-errors";
3
+ import { PartyLevelRight, UserLevelRight, assertUniqueSelfIssuedAudience, resolveSelfIssuedNetworkByAudiences } from "@canton-network/core-wallet-store";
2
4
  import { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect, sql } from "kysely";
3
5
  import Database from "better-sqlite3";
4
- import { PartyLevelRight, UserLevelRight } from "@canton-network/core-wallet-store";
5
6
  import pg from "pg";
6
7
  import { Umzug } from "umzug";
7
8
  import { Command } from "commander";
@@ -11,16 +12,23 @@ const toIdp = (table) => {
11
12
  switch (table.type) {
12
13
  case "oauth":
13
14
  if (!table.configUrl) throw new Error(`Missing configUrl for oauth IdP: ${table.id}`);
15
+ if (table.issuer === null) throw new Error(`Missing issuer for oauth IdP: ${table.id}`);
14
16
  return {
15
17
  id: table.id,
16
18
  type: table.type,
17
19
  issuer: table.issuer,
18
20
  configUrl: table.configUrl
19
21
  };
20
- case "self_signed": return {
22
+ case "self_signed":
23
+ if (table.issuer === null) throw new Error(`Missing issuer for self_signed IdP: ${table.id}`);
24
+ return {
25
+ id: table.id,
26
+ type: table.type,
27
+ issuer: table.issuer
28
+ };
29
+ case "self_issued": return {
21
30
  id: table.id,
22
- type: table.type,
23
- issuer: table.issuer
31
+ type: table.type
24
32
  };
25
33
  }
26
34
  };
@@ -36,7 +44,13 @@ const fromIdp = (idp) => {
36
44
  id: idp.id,
37
45
  type: idp.type,
38
46
  issuer: idp.issuer,
39
- configUrl: void 0
47
+ configUrl: null
48
+ };
49
+ case "self_issued": return {
50
+ id: idp.id,
51
+ type: idp.type,
52
+ issuer: null,
53
+ configUrl: null
40
54
  };
41
55
  }
42
56
  };
@@ -72,24 +86,25 @@ const toSession = (table) => {
72
86
  id: table.id,
73
87
  network: table.network,
74
88
  origin: table.origin,
75
- accessToken: table.accessToken,
89
+ ...table.accessToken ? { accessToken: table.accessToken } : {},
76
90
  userId: table.userId
77
91
  };
78
92
  };
79
93
  const fromWallet = (wallet, userId) => {
80
- const { externalTxId, topologyTransactions, rights, ...rest } = wallet;
94
+ const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } = wallet;
81
95
  return {
82
96
  ...rest,
83
97
  primary: wallet.primary ? 1 : 0,
84
98
  userId,
85
99
  disabled: wallet.disabled !== void 0 && wallet.disabled ? 1 : 0,
100
+ isAuthParty: isAuthParty ? 1 : 0,
86
101
  reason: wallet.reason ?? null,
87
102
  externalTxId: externalTxId && externalTxId !== "" ? externalTxId : null,
88
103
  topologyTransactions: topologyTransactions && topologyTransactions !== "" ? topologyTransactions : null
89
104
  };
90
105
  };
91
106
  const toWalletUpdateProperties = (params) => {
92
- const { status, externalTxId, topologyTransactions, disabled, reason, primary, signingProviderId, publicKey, namespace } = params;
107
+ const { status, externalTxId, topologyTransactions, disabled, reason, primary, signingProviderId, publicKey, namespace, isAuthParty } = params;
93
108
  return {
94
109
  ...status !== void 0 && { status },
95
110
  ...externalTxId !== void 0 && { externalTxId },
@@ -99,7 +114,8 @@ const toWalletUpdateProperties = (params) => {
99
114
  ...reason !== void 0 && { reason },
100
115
  ...signingProviderId !== void 0 && { signingProviderId },
101
116
  ...publicKey !== void 0 && { publicKey },
102
- ...namespace !== void 0 && { namespace }
117
+ ...namespace !== void 0 && { namespace },
118
+ ...isAuthParty !== void 0 && { isAuthParty: isAuthParty ? 1 : 0 }
103
119
  };
104
120
  };
105
121
  const toWalletStatus = (status) => {
@@ -118,6 +134,7 @@ const toWallet = (table) => {
118
134
  networkId: table.networkId,
119
135
  signingProviderId: table.signingProviderId,
120
136
  disabled: table.disabled === 1,
137
+ isAuthParty: Boolean(table.isAuthParty),
121
138
  userId: table.userId,
122
139
  ...table.externalTxId !== null && { externalTxId: table.externalTxId },
123
140
  ...table.topologyTransactions !== null && { topologyTransactions: table.topologyTransactions },
@@ -216,7 +233,7 @@ const toApiKey = (apiKey) => {
216
233
  };
217
234
  };
218
235
  //#endregion
219
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
236
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
220
237
  function _typeof(o) {
221
238
  "@babel/helpers - typeof";
222
239
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -226,7 +243,7 @@ function _typeof(o) {
226
243
  }, _typeof(o);
227
244
  }
228
245
  //#endregion
229
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
246
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
230
247
  function toPrimitive(t, r) {
231
248
  if ("object" != _typeof(t) || !t) return t;
232
249
  var e = t[Symbol.toPrimitive];
@@ -238,13 +255,13 @@ function toPrimitive(t, r) {
238
255
  return ("string" === r ? String : Number)(t);
239
256
  }
240
257
  //#endregion
241
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
258
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
242
259
  function toPropertyKey(t) {
243
260
  var i = toPrimitive(t, "string");
244
261
  return "symbol" == _typeof(i) ? i : i + "";
245
262
  }
246
263
  //#endregion
247
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
264
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
248
265
  function _defineProperty(e, r, t) {
249
266
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
250
267
  value: t,
@@ -319,6 +336,13 @@ var StoreSql = class StoreSql {
319
336
  rights: rightRows.map(({ right }) => fromPartyRight(right)).filter((right) => right !== void 0)
320
337
  };
321
338
  }
339
+ async getWalletByJwt(userId, partyId, audiences) {
340
+ const networks = (await this.db.selectFrom("networks").selectAll().execute()).map(toNetwork);
341
+ const network = resolveSelfIssuedNetworkByAudiences(networks, audiences);
342
+ if (!network) return;
343
+ const row = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).where("partyId", "=", partyId).where("networkId", "=", network.id).executeTakeFirst();
344
+ return row ? toWallet(row) : void 0;
345
+ }
322
346
  async getPrimaryWallet() {
323
347
  return (await this.getWallets()).find((w) => w.primary === true);
324
348
  }
@@ -431,15 +455,39 @@ var StoreSql = class StoreSql {
431
455
  const userId = this.assertConnected();
432
456
  if (!session.origin) throw new Error("Session origin is required");
433
457
  await this.db.transaction().execute(async (trx) => {
434
- const deleted = await trx.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("origin", "=", session.origin)])).execute();
435
- this.logger.debug(deleted, "Deleted old session");
458
+ if (session.accessToken) {
459
+ const deleted = await trx.deleteFrom("sessions").where((eb) => eb.and([
460
+ eb("userId", "=", userId),
461
+ eb("origin", "=", session.origin),
462
+ eb("accessToken", "is not", null)
463
+ ])).execute();
464
+ this.logger.debug(deleted, "Deleted old session");
465
+ }
436
466
  const inserted = await trx.insertInto("sessions").values({
437
467
  ...session,
468
+ accessToken: session.accessToken ?? null,
438
469
  userId
439
470
  }).execute();
440
471
  this.logger.debug(inserted, "Inserted new session");
441
472
  });
442
473
  }
474
+ async getOnboardingSession(sessionId) {
475
+ const row = await this.db.selectFrom("sessions").selectAll().where("id", "=", sessionId).where("accessToken", "is", null).executeTakeFirst();
476
+ return row ? toSession(row) : void 0;
477
+ }
478
+ async upgradeOnboardingSession(sessionId, accessToken) {
479
+ const userId = this.assertConnected();
480
+ return this.db.transaction().execute(async (trx) => {
481
+ const row = await trx.selectFrom("sessions").selectAll().where("id", "=", sessionId).where("userId", "=", userId).where("accessToken", "is", null).executeTakeFirst();
482
+ if (!row) throw new Error("Onboarding session not found");
483
+ await trx.deleteFrom("sessions").where("userId", "=", userId).where("origin", "=", row.origin).where("id", "!=", sessionId).execute();
484
+ await trx.updateTable("sessions").set({ accessToken }).where("id", "=", sessionId).execute();
485
+ return toSession({
486
+ ...row,
487
+ accessToken
488
+ });
489
+ });
490
+ }
443
491
  async removeSession(accessToken) {
444
492
  const userId = this.assertConnected();
445
493
  await this.db.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).execute();
@@ -448,7 +496,7 @@ var StoreSql = class StoreSql {
448
496
  * Lists all pending transactions across all users.
449
497
  */
450
498
  async listAllPendingTransactions() {
451
- return (await this.db.selectFrom("transactions").selectAll().where("status", "=", "pending").execute()).map((row) => toTransaction(row));
499
+ return (await this.db.selectFrom("transactions").selectAll().where((eb) => eb.or([eb("status", "=", "pending"), eb("status", "=", "awaiting-signature")])).execute()).map((row) => toTransaction(row));
452
500
  }
453
501
  async getIdp(idpId) {
454
502
  const idps = await this.listIdps();
@@ -488,11 +536,13 @@ var StoreSql = class StoreSql {
488
536
  return network;
489
537
  }
490
538
  async getCurrentNetwork() {
539
+ const userId = this.assertConnected();
491
540
  const token = this.authContext?.accessToken;
492
- if (!token) throw new Error("No access token found in auth context");
493
- const session = await this.getSession(token);
494
- if (!session) throw new Error("No session found");
495
- const networkId = session.network;
541
+ const onboardingSessionId = this.authContext && !this.authContext.isApiKey ? this.authContext.sessionId : void 0;
542
+ if (!token && !onboardingSessionId) throw providerErrors.unauthorized({ message: "No session found" });
543
+ const sessionRow = await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).where((eb) => token ? eb("accessToken", "=", token) : eb.and([eb("id", "=", onboardingSessionId), eb("accessToken", "is", null)])).executeTakeFirst();
544
+ if (!sessionRow) throw providerErrors.unauthorized({ message: "No session found" });
545
+ const networkId = toSession(sessionRow).network;
496
546
  if (!networkId) throw new Error("No current network set in session");
497
547
  const network = (await this.listNetworks()).find((n) => n.id === networkId);
498
548
  if (!network) throw new Error(`Network "${networkId}" not found`);
@@ -515,6 +565,8 @@ var StoreSql = class StoreSql {
515
565
  async updateNetwork(network) {
516
566
  this.assertConnected();
517
567
  await this.db.transaction().execute(async (trx) => {
568
+ const existing = (await trx.selectFrom("networks").selectAll().execute()).map(toNetwork);
569
+ assertUniqueSelfIssuedAudience(existing, network, network.id);
518
570
  const networkEntry = fromNetwork(network, void 0);
519
571
  this.logger.info(networkEntry, "Updating network table");
520
572
  await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
@@ -525,7 +577,9 @@ var StoreSql = class StoreSql {
525
577
  if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
526
578
  await this.db.transaction().execute(async (trx) => {
527
579
  if (await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst()) throw new Error(`Network ${network.id} already exists`);
528
- else await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
580
+ const existing = (await trx.selectFrom("networks").selectAll().execute()).map(toNetwork);
581
+ assertUniqueSelfIssuedAudience(existing, network);
582
+ await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
529
583
  });
530
584
  }
531
585
  async removeNetwork(networkId) {
@@ -541,6 +595,7 @@ var StoreSql = class StoreSql {
541
595
  const payload = updates.payload ?? existing.payload;
542
596
  const signedAt = updates.signedAt ?? existing.signedAt;
543
597
  const externalTxId = updates.externalTxId ?? existing.externalTxId;
598
+ const failureReason = updates.failureReason ?? existing.failureReason;
544
599
  return {
545
600
  id: existing.id,
546
601
  commandId: existing.commandId,
@@ -551,7 +606,8 @@ var StoreSql = class StoreSql {
551
606
  ...payload !== void 0 && { payload },
552
607
  ...existing.createdAt !== void 0 && { createdAt: existing.createdAt },
553
608
  ...signedAt !== void 0 && { signedAt },
554
- ...externalTxId !== void 0 && { externalTxId }
609
+ ...externalTxId !== void 0 && { externalTxId },
610
+ ...failureReason !== void 0 && { failureReason }
555
611
  };
556
612
  }
557
613
  async setTransaction(transaction) {
@@ -559,23 +615,25 @@ var StoreSql = class StoreSql {
559
615
  const network = await this.getCurrentNetwork();
560
616
  await this.db.insertInto("transactions").values(fromTransaction(transaction, userId, network.id)).execute();
561
617
  }
562
- async setTransactionSigned(transactionId, signedAt, externalTxId) {
563
- await this.setTransactionStatus(transactionId, "signed", {
618
+ async setTransactionSigned(transactionId, signedAt, externalTxId, opts) {
619
+ return await this.setTransactionStatus(transactionId, "signed", {
564
620
  signedAt,
565
621
  ...externalTxId !== void 0 && { externalTxId }
566
- });
622
+ }, opts);
567
623
  }
568
- async setTransactionStatus(transactionId, status, updates = {}) {
624
+ async setTransactionStatus(transactionId, status, updates = {}, opts) {
569
625
  const userId = this.assertConnected();
570
626
  const network = await this.getCurrentNetwork();
571
627
  const existing = await this.getTransaction(transactionId);
572
628
  if (!existing) throw new Error(`Transaction not found with id: ${transactionId}`);
629
+ if (opts?.expectedStatus && existing.status !== opts.expectedStatus) return false;
573
630
  const updated = this.mergeTransactionStatusUpdate(existing, status, updates);
574
- await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where((eb) => eb.and([
631
+ return (await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where((eb) => eb.and([
575
632
  eb("id", "=", transactionId),
576
633
  eb("userId", "=", userId),
577
- eb("networkId", "=", network.id)
578
- ])).execute();
634
+ eb("networkId", "=", network.id),
635
+ ...opts?.expectedStatus ? [eb("status", "=", opts.expectedStatus)] : []
636
+ ])).executeTakeFirst()).numUpdatedRows > 0n;
579
637
  }
580
638
  async getTransaction(transactionId) {
581
639
  const userId = this.assertConnected();