@canton-network/core-wallet-store-sql 1.15.0 → 2.1.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 (50) hide show
  1. package/dist/bootstrap.d.ts +1 -2
  2. package/dist/bootstrap.d.ts.map +1 -1
  3. package/dist/index.js +67 -32
  4. package/dist/index.js.map +1 -1
  5. package/dist/migrations/011-add-transaction-id-primary-key.d.ts.map +1 -1
  6. package/dist/migrations/011-add-transaction-id-primary-key.js +1 -2
  7. package/dist/migrations/020-add-message-external-tx-id-and-failure-reason.d.ts +5 -0
  8. package/dist/migrations/020-add-message-external-tx-id-and-failure-reason.d.ts.map +1 -0
  9. package/dist/migrations/020-add-message-external-tx-id-and-failure-reason.js +22 -0
  10. package/dist/migrator.d.ts.map +1 -1
  11. package/dist/schema.d.ts +3 -0
  12. package/dist/schema.d.ts.map +1 -1
  13. package/dist/schema.js +12 -0
  14. package/dist/store-sql.d.ts +5 -4
  15. package/dist/store-sql.d.ts.map +1 -1
  16. package/package.json +24 -26
  17. package/dist/index.cjs +0 -950
  18. package/dist/index.cjs.map +0 -1
  19. package/dist/migrations-test/global-setup.d.ts +0 -9
  20. package/dist/migrations-test/global-setup.d.ts.map +0 -1
  21. package/dist/migrations-test/helpers.d.ts +0 -32
  22. package/dist/migrations-test/helpers.d.ts.map +0 -1
  23. package/dist/migrations-test/seeds/001-init.d.ts +0 -43
  24. package/dist/migrations-test/seeds/001-init.d.ts.map +0 -1
  25. package/dist/migrations-test/seeds/002-transaction-timestamps.d.ts +0 -13
  26. package/dist/migrations-test/seeds/002-transaction-timestamps.d.ts.map +0 -1
  27. package/dist/migrations-test/seeds/003-transaction-origin.d.ts +0 -14
  28. package/dist/migrations-test/seeds/003-transaction-origin.d.ts.map +0 -1
  29. package/dist/migrations-test/seeds/004-add-session-id.d.ts +0 -9
  30. package/dist/migrations-test/seeds/004-add-session-id.d.ts.map +0 -1
  31. package/dist/migrations-test/seeds/005-add-wallet-disabled-reason.d.ts +0 -16
  32. package/dist/migrations-test/seeds/005-add-wallet-disabled-reason.d.ts.map +0 -1
  33. package/dist/migrations-test/seeds/008-transaction-external-tx-id.d.ts +0 -15
  34. package/dist/migrations-test/seeds/008-transaction-external-tx-id.d.ts.map +0 -1
  35. package/dist/migrations-test/seeds/009-add-wallet-rights-columns.d.ts +0 -14
  36. package/dist/migrations-test/seeds/009-add-wallet-rights-columns.d.ts.map +0 -1
  37. package/dist/migrations-test/seeds/010-transaction-with-network.d.ts +0 -16
  38. package/dist/migrations-test/seeds/010-transaction-with-network.d.ts.map +0 -1
  39. package/dist/migrations-test/seeds/012-add-messages-to-sign.d.ts +0 -16
  40. package/dist/migrations-test/seeds/012-add-messages-to-sign.d.ts.map +0 -1
  41. package/dist/migrations-test/seeds/013-add-api-key.d.ts +0 -13
  42. package/dist/migrations-test/seeds/013-add-api-key.d.ts.map +0 -1
  43. package/dist/migrations-test/seeds/014-add-service-account-column.d.ts +0 -15
  44. package/dist/migrations-test/seeds/014-add-service-account-column.d.ts.map +0 -1
  45. package/dist/migrations-test/seeds/016-add-failure-reason-and-awaiting-signature.d.ts +0 -18
  46. package/dist/migrations-test/seeds/016-add-failure-reason-and-awaiting-signature.d.ts.map +0 -1
  47. package/dist/migrations-test/seeds/017-make-idp-issuer-nullable.d.ts +0 -9
  48. package/dist/migrations-test/seeds/017-make-idp-issuer-nullable.d.ts.map +0 -1
  49. package/dist/migrations-test/seeds/019-make-session-access-token-nullable.d.ts +0 -10
  50. package/dist/migrations-test/seeds/019-make-session-access-token-nullable.d.ts.map +0 -1
package/dist/index.cjs DELETED
@@ -1,950 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
- //#endregion
24
- let _canton_network_core_wallet_auth = require("@canton-network/core-wallet-auth");
25
- let _canton_network_core_rpc_errors = require("@canton-network/core-rpc-errors");
26
- let _canton_network_core_wallet_store = require("@canton-network/core-wallet-store");
27
- let kysely = require("kysely");
28
- let better_sqlite3 = require("better-sqlite3");
29
- better_sqlite3 = __toESM(better_sqlite3, 1);
30
- let pg = require("pg");
31
- pg = __toESM(pg, 1);
32
- let umzug = require("umzug");
33
- let commander = require("commander");
34
- let pino = require("pino");
35
- //#region src/schema.ts
36
- const toIdp = (table) => {
37
- switch (table.type) {
38
- case "oauth":
39
- if (!table.configUrl) throw new Error(`Missing configUrl for oauth IdP: ${table.id}`);
40
- if (table.issuer === null) throw new Error(`Missing issuer for oauth IdP: ${table.id}`);
41
- return {
42
- id: table.id,
43
- type: table.type,
44
- issuer: table.issuer,
45
- configUrl: table.configUrl
46
- };
47
- case "self_signed":
48
- if (table.issuer === null) throw new Error(`Missing issuer for self_signed IdP: ${table.id}`);
49
- return {
50
- id: table.id,
51
- type: table.type,
52
- issuer: table.issuer
53
- };
54
- case "self_issued": return {
55
- id: table.id,
56
- type: table.type
57
- };
58
- }
59
- };
60
- const fromIdp = (idp) => {
61
- switch (idp.type) {
62
- case "oauth": return {
63
- id: idp.id,
64
- type: idp.type,
65
- issuer: idp.issuer,
66
- configUrl: idp.configUrl
67
- };
68
- case "self_signed": return {
69
- id: idp.id,
70
- type: idp.type,
71
- issuer: idp.issuer,
72
- configUrl: null
73
- };
74
- case "self_issued": return {
75
- id: idp.id,
76
- type: idp.type,
77
- issuer: null,
78
- configUrl: null
79
- };
80
- }
81
- };
82
- const toNetwork = (table) => {
83
- return {
84
- name: table.name,
85
- id: table.id,
86
- synchronizerId: table.synchronizerId ?? void 0,
87
- identityProviderId: table.identityProviderId,
88
- description: table.description,
89
- ledgerApi: { baseUrl: table.ledgerApiBaseUrl },
90
- auth: _canton_network_core_wallet_auth.authSchema.parse(typeof table.auth === "string" ? JSON.parse(table.auth) : table.auth),
91
- adminAuth: table.adminAuth ? _canton_network_core_wallet_auth.authSchema.parse(typeof table.adminAuth === "string" ? JSON.parse(table.adminAuth) : table.adminAuth) : void 0,
92
- serviceAccountAuth: table.serviceAccountAuth ? _canton_network_core_wallet_auth.authSchema.parse(typeof table.serviceAccountAuth === "string" ? JSON.parse(table.serviceAccountAuth) : table.serviceAccountAuth) : void 0
93
- };
94
- };
95
- const fromNetwork = (network, userId) => {
96
- return {
97
- name: network.name,
98
- id: network.id,
99
- synchronizerId: network.synchronizerId ?? null,
100
- description: network.description,
101
- ledgerApiBaseUrl: network.ledgerApi.baseUrl,
102
- userId,
103
- identityProviderId: network.identityProviderId,
104
- auth: JSON.stringify(network.auth),
105
- adminAuth: network.adminAuth ? JSON.stringify(network.adminAuth) : void 0,
106
- serviceAccountAuth: network.serviceAccountAuth ? JSON.stringify(network.serviceAccountAuth) : void 0
107
- };
108
- };
109
- const toSession = (table) => {
110
- return {
111
- id: table.id,
112
- network: table.network,
113
- origin: table.origin,
114
- ...table.accessToken ? { accessToken: table.accessToken } : {},
115
- userId: table.userId
116
- };
117
- };
118
- const fromWallet = (wallet, userId) => {
119
- const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } = wallet;
120
- return {
121
- ...rest,
122
- primary: wallet.primary ? 1 : 0,
123
- userId,
124
- disabled: wallet.disabled !== void 0 && wallet.disabled ? 1 : 0,
125
- isAuthParty: isAuthParty ? 1 : 0,
126
- reason: wallet.reason ?? null,
127
- externalTxId: externalTxId && externalTxId !== "" ? externalTxId : null,
128
- topologyTransactions: topologyTransactions && topologyTransactions !== "" ? topologyTransactions : null
129
- };
130
- };
131
- const toWalletUpdateProperties = (params) => {
132
- const { status, externalTxId, topologyTransactions, disabled, reason, primary, signingProviderId, publicKey, namespace, isAuthParty } = params;
133
- return {
134
- ...status !== void 0 && { status },
135
- ...externalTxId !== void 0 && { externalTxId },
136
- ...topologyTransactions !== void 0 && { topologyTransactions },
137
- ...primary !== void 0 && { primary: primary ? 1 : 0 },
138
- ...disabled !== void 0 && { disabled: disabled ? 1 : 0 },
139
- ...reason !== void 0 && { reason },
140
- ...signingProviderId !== void 0 && { signingProviderId },
141
- ...publicKey !== void 0 && { publicKey },
142
- ...namespace !== void 0 && { namespace },
143
- ...isAuthParty !== void 0 && { isAuthParty: isAuthParty ? 1 : 0 }
144
- };
145
- };
146
- const toWalletStatus = (status) => {
147
- if (status === "allocated") return "allocated";
148
- if (status === "removed") return "removed";
149
- return "initialized";
150
- };
151
- const toWallet = (table) => {
152
- return {
153
- primary: Boolean(table.primary),
154
- status: toWalletStatus(table.status),
155
- partyId: table.partyId,
156
- hint: table.hint,
157
- publicKey: table.publicKey,
158
- namespace: table.namespace,
159
- networkId: table.networkId,
160
- signingProviderId: table.signingProviderId,
161
- disabled: table.disabled === 1,
162
- isAuthParty: Boolean(table.isAuthParty),
163
- userId: table.userId,
164
- ...table.externalTxId !== null && { externalTxId: table.externalTxId },
165
- ...table.topologyTransactions !== null && { topologyTransactions: table.topologyTransactions },
166
- ...table.reason !== null && { reason: table.reason },
167
- rights: []
168
- };
169
- };
170
- const fromPartyRight = (right) => {
171
- if (Object.values(_canton_network_core_wallet_store.PartyLevelRight).includes(right)) return right;
172
- };
173
- const fromUserRight = (right) => {
174
- if (Object.values(_canton_network_core_wallet_store.UserLevelRight).includes(right)) return right;
175
- };
176
- const fromTransaction = (transaction, userId, networkId) => {
177
- return {
178
- ...transaction,
179
- networkId,
180
- payload: transaction.payload ? JSON.stringify(transaction.payload) : void 0,
181
- origin: transaction.origin || null,
182
- userId,
183
- createdAt: transaction.createdAt?.toISOString() || null,
184
- signedAt: transaction.signedAt?.toISOString() || null,
185
- externalTxId: transaction.externalTxId ?? null
186
- };
187
- };
188
- const toTransaction = (table) => {
189
- const result = {
190
- id: table.id,
191
- commandId: table.commandId,
192
- status: table.status,
193
- preparedTransaction: table.preparedTransaction,
194
- preparedTransactionHash: table.preparedTransactionHash,
195
- payload: table.payload ? JSON.parse(table.payload) : void 0,
196
- origin: table.origin || null,
197
- userId: table.userId,
198
- networkId: table.networkId
199
- };
200
- if (table.createdAt) result.createdAt = new Date(table.createdAt);
201
- if (table.signedAt) result.signedAt = new Date(table.signedAt);
202
- if (table.externalTxId) result.externalTxId = table.externalTxId;
203
- return result;
204
- };
205
- const fromMessageRaw = (message, userId, networkId) => {
206
- if (message.userId !== userId) throw new Error(`MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`);
207
- return {
208
- id: message.id,
209
- status: message.status,
210
- userId: message.userId,
211
- partyId: message.partyId,
212
- publicKey: message.publicKey,
213
- message: message.message,
214
- origin: message.origin || null,
215
- networkId,
216
- createdAt: message.createdAt.toISOString(),
217
- signedAt: message.signedAt?.toISOString() || null,
218
- signature: message.signature ?? null
219
- };
220
- };
221
- const toMessageRaw = (table) => {
222
- const result = {
223
- id: table.id,
224
- status: table.status,
225
- userId: table.userId,
226
- partyId: table.partyId,
227
- publicKey: table.publicKey,
228
- message: table.message,
229
- origin: table.origin || null,
230
- createdAt: new Date(table.createdAt)
231
- };
232
- if (table.signedAt) result.signedAt = new Date(table.signedAt);
233
- if (table.signature) result.signature = table.signature;
234
- return result;
235
- };
236
- const fromApiKey = (table) => {
237
- return {
238
- id: table.id,
239
- digest: table.digest,
240
- name: table.name,
241
- userId: table.userId,
242
- email: table.email,
243
- networkId: table.networkId,
244
- createdAt: new Date(table.createdAt),
245
- lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : void 0
246
- };
247
- };
248
- const toApiKey = (apiKey) => {
249
- return {
250
- id: apiKey.id,
251
- digest: apiKey.digest,
252
- name: apiKey.name,
253
- userId: apiKey.userId,
254
- email: apiKey.email,
255
- networkId: apiKey.networkId,
256
- createdAt: apiKey.createdAt.toISOString(),
257
- lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
258
- };
259
- };
260
- //#endregion
261
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
262
- function _typeof(o) {
263
- "@babel/helpers - typeof";
264
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
265
- return typeof o;
266
- } : function(o) {
267
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
268
- }, _typeof(o);
269
- }
270
- //#endregion
271
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
272
- function toPrimitive(t, r) {
273
- if ("object" != _typeof(t) || !t) return t;
274
- var e = t[Symbol.toPrimitive];
275
- if (void 0 !== e) {
276
- var i = e.call(t, r || "default");
277
- if ("object" != _typeof(i)) return i;
278
- throw new TypeError("@@toPrimitive must return a primitive value.");
279
- }
280
- return ("string" === r ? String : Number)(t);
281
- }
282
- //#endregion
283
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
284
- function toPropertyKey(t) {
285
- var i = toPrimitive(t, "string");
286
- return "symbol" == _typeof(i) ? i : i + "";
287
- }
288
- //#endregion
289
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
290
- function _defineProperty(e, r, t) {
291
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
292
- value: t,
293
- enumerable: !0,
294
- configurable: !0,
295
- writable: !0
296
- }) : e[r] = t, e;
297
- }
298
- //#endregion
299
- //#region src/store-sql.ts
300
- var StoreSql = class StoreSql {
301
- constructor(db, logger, authContext) {
302
- this.db = db;
303
- this.logger = logger;
304
- _defineProperty(this, "authContext", void 0);
305
- this.logger = logger.child({ component: "StoreSql" });
306
- this.authContext = authContext;
307
- }
308
- withAuthContext(context) {
309
- return new StoreSql(this.db, this.logger, context);
310
- }
311
- assertConnected() {
312
- return (0, _canton_network_core_wallet_auth.assertConnected)(this.authContext).userId;
313
- }
314
- async getAllWallets(filter = {}) {
315
- const userId = this.assertConnected();
316
- const { networkIds, signingProviderIds } = filter;
317
- const networkIdSet = networkIds ? new Set(networkIds) : null;
318
- const signingProviderIdSet = signingProviderIds ? new Set(signingProviderIds) : null;
319
- const wallets = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).execute();
320
- const userPartyRights = await this.db.selectFrom("userPartyRights").selectAll().where("userId", "=", userId).execute();
321
- const rightsByWallet = /* @__PURE__ */ new Map();
322
- for (const row of userPartyRights) {
323
- const right = fromPartyRight(row.right);
324
- if (!right) continue;
325
- const key = `${row.partyId}:${row.networkId}`;
326
- const existing = rightsByWallet.get(key) ?? [];
327
- rightsByWallet.set(key, [...existing, right]);
328
- }
329
- return wallets.filter((wallet) => {
330
- const matchedNetworkIds = networkIdSet ? networkIdSet.has(wallet.networkId) : true;
331
- const matchedSigningProviderIds = signingProviderIdSet ? signingProviderIdSet.has(wallet.signingProviderId) : true;
332
- return matchedNetworkIds && matchedSigningProviderIds;
333
- }).map((table) => {
334
- const wallet = toWallet(table);
335
- const rights = rightsByWallet.get(`${table.partyId}:${table.networkId}`);
336
- return {
337
- ...wallet,
338
- rights: rights ?? []
339
- };
340
- });
341
- }
342
- async getWallets(filter = {}) {
343
- const network = await this.getCurrentNetwork();
344
- return this.getAllWallets({
345
- ...filter,
346
- networkIds: [network.id]
347
- });
348
- }
349
- async getWallet(partyId) {
350
- const userId = this.assertConnected();
351
- const constraint = {
352
- partyId,
353
- networkId: (await this.getCurrentNetwork()).id,
354
- userId
355
- };
356
- const row = await this.db.selectFrom("wallets").selectAll().where((eb) => eb.and(constraint)).executeTakeFirst();
357
- if (!row) return null;
358
- const rightRows = await this.db.selectFrom("userPartyRights").select("right").where((eb) => eb.and(constraint)).execute();
359
- return {
360
- ...toWallet(row),
361
- rights: rightRows.map(({ right }) => fromPartyRight(right)).filter((right) => right !== void 0)
362
- };
363
- }
364
- async getWalletByJwt(userId, partyId, audiences) {
365
- const networks = (await this.db.selectFrom("networks").selectAll().execute()).map(toNetwork);
366
- const network = (0, _canton_network_core_wallet_store.resolveSelfIssuedNetworkByAudiences)(networks, audiences);
367
- if (!network) return;
368
- const row = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).where("partyId", "=", partyId).where("networkId", "=", network.id).executeTakeFirst();
369
- return row ? toWallet(row) : void 0;
370
- }
371
- async getPrimaryWallet() {
372
- return (await this.getWallets()).find((w) => w.primary === true);
373
- }
374
- async setPrimaryWallet(partyId) {
375
- const network = await this.getCurrentNetwork();
376
- const userId = this.assertConnected();
377
- const wallets = await this.getWallets();
378
- if (!wallets.some((w) => w.partyId === partyId)) throw new Error(`Wallet with partyId "${partyId}" not found in network "${network.id}"`);
379
- const primary = wallets.find((w) => w.primary === true);
380
- await this.db.transaction().execute(async (trx) => {
381
- if (primary) await trx.updateTable("wallets").set({ primary: 0 }).where((eb) => eb.and([
382
- eb("partyId", "=", primary.partyId),
383
- eb("networkId", "=", network.id),
384
- eb("userId", "=", userId)
385
- ])).execute();
386
- await trx.updateTable("wallets").set({ primary: 1 }).where((eb) => eb.and([
387
- eb("partyId", "=", partyId),
388
- eb("networkId", "=", network.id),
389
- eb("userId", "=", userId)
390
- ])).execute();
391
- });
392
- }
393
- async addWallet(wallet) {
394
- this.logger.info("Adding wallet");
395
- const userId = this.assertConnected();
396
- const wallets = await this.getWallets();
397
- if (wallets.some((w) => w.partyId === wallet.partyId && w.networkId === wallet.networkId)) throw new Error(`Wallet with partyId "${wallet.partyId}" networkId "${wallet.networkId}" userId "${userId}" already exists`);
398
- if (!wallet.disabled && wallet.status === "allocated" && !wallets.some((wallet) => wallet.primary)) wallet.primary = true;
399
- await this.db.transaction().execute(async (trx) => {
400
- if (wallet.primary) await trx.updateTable("wallets").set({ primary: 0 }).where((eb) => eb.and([
401
- eb("primary", "=", 1),
402
- eb("networkId", "=", wallet.networkId),
403
- eb("userId", "=", userId)
404
- ])).execute();
405
- await trx.insertInto("wallets").values(fromWallet(wallet, userId)).execute();
406
- if (wallet.rights && wallet.rights.length > 0) await trx.insertInto("userPartyRights").values(wallet.rights.map((right) => ({
407
- userId,
408
- networkId: wallet.networkId,
409
- partyId: wallet.partyId,
410
- right
411
- }))).execute();
412
- });
413
- }
414
- async updateWallet(params) {
415
- const { partyId, networkId, rights } = params;
416
- this.logger.info("Updating wallet");
417
- const userId = this.assertConnected();
418
- const updates = toWalletUpdateProperties(params);
419
- const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
420
- if (Object.keys(updates).length === 0 && rights === void 0) return;
421
- await this.db.transaction().execute(async (trx) => {
422
- if (Object.keys(updates).length > 0) await trx.updateTable("wallets").set(updates).where((eb) => eb.and([
423
- eb("partyId", "=", partyId),
424
- eb("networkId", "=", targetNetworkId),
425
- eb("userId", "=", userId)
426
- ])).execute();
427
- if (rights !== void 0) {
428
- await trx.deleteFrom("userPartyRights").where((eb) => eb.and([
429
- eb("partyId", "=", partyId),
430
- eb("networkId", "=", targetNetworkId),
431
- eb("userId", "=", userId)
432
- ])).execute();
433
- if (rights.length > 0) await trx.insertInto("userPartyRights").values(rights.map((right) => ({
434
- userId,
435
- networkId: targetNetworkId,
436
- partyId,
437
- right
438
- }))).execute();
439
- }
440
- });
441
- }
442
- async removeWallet(partyId) {
443
- this.logger.info("Removing wallet");
444
- const userId = this.assertConnected();
445
- const network = await this.getCurrentNetwork();
446
- await this.db.transaction().execute(async (trx) => {
447
- await trx.deleteFrom("wallets").where((eb) => eb.and([
448
- eb("partyId", "=", partyId),
449
- eb("networkId", "=", network.id),
450
- eb("userId", "=", userId)
451
- ])).execute();
452
- });
453
- }
454
- async getUserRights(networkId) {
455
- const userId = this.assertConnected();
456
- const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
457
- return (await this.db.selectFrom("userRights").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", targetNetworkId)])).execute()).map((row) => fromUserRight(row.right)).filter((right) => right !== void 0);
458
- }
459
- async setUserRights(networkId, rights) {
460
- const userId = this.assertConnected();
461
- await this.db.transaction().execute(async (trx) => {
462
- await trx.deleteFrom("userRights").where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", networkId)])).execute();
463
- if (rights.length > 0) await trx.insertInto("userRights").values(rights.map((right) => ({
464
- userId,
465
- networkId,
466
- right
467
- }))).execute();
468
- });
469
- }
470
- async getSession(accessToken) {
471
- const userId = this.assertConnected();
472
- const row = await this.db.selectFrom("sessions").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).executeTakeFirst();
473
- return row ? toSession(row) : void 0;
474
- }
475
- async listSessions() {
476
- const userId = this.assertConnected();
477
- return (await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).execute()).map((row) => toSession(row));
478
- }
479
- async setSession(session) {
480
- const userId = this.assertConnected();
481
- if (!session.origin) throw new Error("Session origin is required");
482
- await this.db.transaction().execute(async (trx) => {
483
- if (session.accessToken) {
484
- const deleted = await trx.deleteFrom("sessions").where((eb) => eb.and([
485
- eb("userId", "=", userId),
486
- eb("origin", "=", session.origin),
487
- eb("accessToken", "is not", null)
488
- ])).execute();
489
- this.logger.debug(deleted, "Deleted old session");
490
- }
491
- const inserted = await trx.insertInto("sessions").values({
492
- ...session,
493
- accessToken: session.accessToken ?? null,
494
- userId
495
- }).execute();
496
- this.logger.debug(inserted, "Inserted new session");
497
- });
498
- }
499
- async getOnboardingSession(sessionId) {
500
- const row = await this.db.selectFrom("sessions").selectAll().where("id", "=", sessionId).where("accessToken", "is", null).executeTakeFirst();
501
- return row ? toSession(row) : void 0;
502
- }
503
- async upgradeOnboardingSession(sessionId, accessToken) {
504
- const userId = this.assertConnected();
505
- return this.db.transaction().execute(async (trx) => {
506
- const row = await trx.selectFrom("sessions").selectAll().where("id", "=", sessionId).where("userId", "=", userId).where("accessToken", "is", null).executeTakeFirst();
507
- if (!row) throw new Error("Onboarding session not found");
508
- await trx.deleteFrom("sessions").where("userId", "=", userId).where("origin", "=", row.origin).where("id", "!=", sessionId).execute();
509
- await trx.updateTable("sessions").set({ accessToken }).where("id", "=", sessionId).execute();
510
- return toSession({
511
- ...row,
512
- accessToken
513
- });
514
- });
515
- }
516
- async removeSession(accessToken) {
517
- const userId = this.assertConnected();
518
- await this.db.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).execute();
519
- }
520
- /**
521
- * Lists all pending transactions across all users.
522
- */
523
- async listAllPendingTransactions() {
524
- return (await this.db.selectFrom("transactions").selectAll().where((eb) => eb.or([eb("status", "=", "pending"), eb("status", "=", "awaiting-signature")])).execute()).map((row) => toTransaction(row));
525
- }
526
- async getIdp(idpId) {
527
- const idps = await this.listIdps();
528
- if (!idps) throw new Error("No IDPs available");
529
- const idp = idps.find((n) => n.id === idpId);
530
- if (!idp) throw new Error(`IDP "${idpId}" not found`);
531
- return idp;
532
- }
533
- async listIdps() {
534
- return (await this.db.selectFrom("idps").selectAll().execute()).map((table) => toIdp(table));
535
- }
536
- async updateIdp(idp) {
537
- await this.db.transaction().execute(async (trx) => {
538
- const idpEntry = fromIdp(idp);
539
- this.logger.info(idpEntry, "Updating idp table");
540
- await trx.updateTable("idps").set(idpEntry).where("id", "=", idp.id).execute();
541
- });
542
- }
543
- async addIdp(idp) {
544
- await this.db.transaction().execute(async (trx) => {
545
- if (await trx.selectFrom("idps").selectAll().where("id", "=", idp.id).executeTakeFirst()) throw new Error(`IDP ${idp.id} already exists`);
546
- else await trx.insertInto("idps").values(fromIdp(idp)).execute();
547
- });
548
- }
549
- async removeIdp(idpId) {
550
- if ((await this.listNetworks()).some((n) => n.identityProviderId === idpId)) throw new Error(`Cannot delete IDP ${idpId} as it is in use by existing networks`);
551
- await this.db.transaction().execute(async (trx) => {
552
- if (!await trx.selectFrom("idps").selectAll().where("id", "=", idpId).executeTakeFirst()) throw new Error(`IDP ${idpId} does not exists`);
553
- await trx.deleteFrom("idps").where("id", "=", idpId).execute();
554
- });
555
- }
556
- async getNetwork(networkId) {
557
- const networks = await this.listNetworks();
558
- if (!networks) throw new Error("No networks available");
559
- const network = networks.find((n) => n.id === networkId);
560
- if (!network) throw new Error(`Network "${networkId}" not found`);
561
- return network;
562
- }
563
- async getCurrentNetwork() {
564
- const userId = this.assertConnected();
565
- const token = this.authContext?.accessToken;
566
- const onboardingSessionId = this.authContext && !this.authContext.isApiKey ? this.authContext.sessionId : void 0;
567
- if (!token && !onboardingSessionId) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "No session found" });
568
- 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();
569
- if (!sessionRow) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "No session found" });
570
- const networkId = toSession(sessionRow).network;
571
- if (!networkId) throw new Error("No current network set in session");
572
- const network = (await this.listNetworks()).find((n) => n.id === networkId);
573
- if (!network) throw new Error(`Network "${networkId}" not found`);
574
- return network;
575
- }
576
- async getNetworkForTokenVerification(networkId) {
577
- const row = await this.db.selectFrom("networks").selectAll().where("id", "=", networkId).executeTakeFirst();
578
- if (!row) return void 0;
579
- const network = toNetwork(row);
580
- return network.auth.method === "self_signed" ? network : void 0;
581
- }
582
- async listNetworks() {
583
- let query = this.db.selectFrom("networks").selectAll();
584
- if (this.authContext) {
585
- const userId = this.assertConnected();
586
- query = query.where((eb) => eb.or([eb("userId", "is", null), eb("userId", "=", userId)]));
587
- } else query = query.where("userId", "is", null);
588
- return (await query.execute()).map((table) => toNetwork(table));
589
- }
590
- async updateNetwork(network) {
591
- this.assertConnected();
592
- await this.db.transaction().execute(async (trx) => {
593
- const existing = (await trx.selectFrom("networks").selectAll().execute()).map(toNetwork);
594
- (0, _canton_network_core_wallet_store.assertUniqueSelfIssuedAudience)(existing, network, network.id);
595
- const networkEntry = fromNetwork(network, void 0);
596
- this.logger.info(networkEntry, "Updating network table");
597
- await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
598
- });
599
- }
600
- async addNetwork(network) {
601
- const userId = this.authContext?.userId;
602
- if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
603
- await this.db.transaction().execute(async (trx) => {
604
- if (await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst()) throw new Error(`Network ${network.id} already exists`);
605
- const existing = (await trx.selectFrom("networks").selectAll().execute()).map(toNetwork);
606
- (0, _canton_network_core_wallet_store.assertUniqueSelfIssuedAudience)(existing, network);
607
- await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
608
- });
609
- }
610
- async removeNetwork(networkId) {
611
- const userId = this.assertConnected();
612
- await this.db.transaction().execute(async (trx) => {
613
- const network = await trx.selectFrom("networks").selectAll().where("id", "=", networkId).executeTakeFirst();
614
- if (!network) throw new Error(`Network ${networkId} does not exists`);
615
- if (network.userId !== userId) throw new Error(`Network ${networkId} is not owned by user ${userId}`);
616
- await trx.deleteFrom("networks").where("id", "=", networkId).execute();
617
- });
618
- }
619
- mergeTransactionStatusUpdate(existing, status, updates = {}) {
620
- const payload = updates.payload ?? existing.payload;
621
- const signedAt = updates.signedAt ?? existing.signedAt;
622
- const externalTxId = updates.externalTxId ?? existing.externalTxId;
623
- const failureReason = updates.failureReason ?? existing.failureReason;
624
- return {
625
- id: existing.id,
626
- commandId: existing.commandId,
627
- status,
628
- preparedTransaction: existing.preparedTransaction,
629
- preparedTransactionHash: existing.preparedTransactionHash,
630
- origin: existing.origin,
631
- ...payload !== void 0 && { payload },
632
- ...existing.createdAt !== void 0 && { createdAt: existing.createdAt },
633
- ...signedAt !== void 0 && { signedAt },
634
- ...externalTxId !== void 0 && { externalTxId },
635
- ...failureReason !== void 0 && { failureReason }
636
- };
637
- }
638
- async setTransaction(transaction) {
639
- const userId = this.assertConnected();
640
- const network = await this.getCurrentNetwork();
641
- await this.db.insertInto("transactions").values(fromTransaction(transaction, userId, network.id)).execute();
642
- }
643
- async setTransactionSigned(transactionId, signedAt, externalTxId, opts) {
644
- return await this.setTransactionStatus(transactionId, "signed", {
645
- signedAt,
646
- ...externalTxId !== void 0 && { externalTxId }
647
- }, opts);
648
- }
649
- async setTransactionStatus(transactionId, status, updates = {}, opts) {
650
- const userId = this.assertConnected();
651
- const network = await this.getCurrentNetwork();
652
- const existing = await this.getTransaction(transactionId);
653
- if (!existing) throw new Error(`Transaction not found with id: ${transactionId}`);
654
- if (opts?.expectedStatus && existing.status !== opts.expectedStatus) return false;
655
- const updated = this.mergeTransactionStatusUpdate(existing, status, updates);
656
- return (await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where((eb) => eb.and([
657
- eb("id", "=", transactionId),
658
- eb("userId", "=", userId),
659
- eb("networkId", "=", network.id),
660
- ...opts?.expectedStatus ? [eb("status", "=", opts.expectedStatus)] : []
661
- ])).executeTakeFirst()).numUpdatedRows > 0n;
662
- }
663
- async getTransaction(transactionId) {
664
- const userId = this.assertConnected();
665
- const network = await this.getCurrentNetwork();
666
- const transaction = await this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([
667
- eb("id", "=", transactionId),
668
- eb("userId", "=", userId),
669
- eb("networkId", "=", network.id)
670
- ])).executeTakeFirst();
671
- return transaction ? toTransaction(transaction) : void 0;
672
- }
673
- async getLatestTransactionByCommandId(commandId) {
674
- const userId = this.assertConnected();
675
- const network = await this.getCurrentNetwork();
676
- const transaction = await this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([
677
- eb("commandId", "=", commandId),
678
- eb("userId", "=", userId),
679
- eb("networkId", "=", network.id)
680
- ])).orderBy(kysely.sql`${kysely.sql.ref("createdAt")} desc nulls last`).executeTakeFirst();
681
- return transaction ? toTransaction(transaction) : void 0;
682
- }
683
- async transactionsCount() {
684
- const userId = this.assertConnected();
685
- const network = await this.getCurrentNetwork();
686
- const result = await this.db.selectFrom("transactions").where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).select((eb) => eb.fn.count("id").as("count")).executeTakeFirstOrThrow();
687
- return Number(result.count);
688
- }
689
- async listTransactions(options) {
690
- const userId = this.assertConnected();
691
- const network = await this.getCurrentNetwork();
692
- const { cursor, limit } = options ?? {};
693
- const lim = limit ? Math.min(limit, 100) : 100;
694
- let query = this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).orderBy(kysely.sql`${kysely.sql.ref("createdAt")} desc nulls last`).orderBy("id", "desc").limit(lim + 1);
695
- if (cursor) {
696
- const split = cursor.split("::");
697
- const dateString = split[0] === "null" ? null : split[0];
698
- const cursorId = split[1];
699
- query = query.where((eb) => {
700
- if (dateString === null) return eb.and([eb("createdAt", "is", null), eb("id", "<", cursorId)]);
701
- return eb.or([
702
- eb("createdAt", "<", dateString),
703
- eb.and([eb("createdAt", "=", dateString), eb("id", "<", split[1])]),
704
- eb("createdAt", "is", null)
705
- ]);
706
- });
707
- }
708
- const txs = (await query.execute()).map((r) => toTransaction(r));
709
- const hasNextPage = txs.length > lim;
710
- if (hasNextPage) txs.pop();
711
- if (txs.length === 0) return {
712
- transactions: [],
713
- nextCursor: null
714
- };
715
- const lastTx = txs[txs.length - 1];
716
- if (lastTx === void 0) return {
717
- transactions: txs,
718
- nextCursor: null
719
- };
720
- if (lastTx.createdAt) {
721
- const d = new Date(lastTx.createdAt).toISOString();
722
- return {
723
- transactions: txs,
724
- nextCursor: hasNextPage ? `${d}::${lastTx.id}` : null
725
- };
726
- } else return {
727
- transactions: txs,
728
- nextCursor: hasNextPage ? `null::${lastTx.id}` : null
729
- };
730
- }
731
- async removeTransaction(transactionId) {
732
- const userId = this.assertConnected();
733
- const network = await this.getCurrentNetwork();
734
- await this.db.deleteFrom("transactions").where((eb) => eb.and([
735
- eb("id", "=", transactionId),
736
- eb("userId", "=", userId),
737
- eb("networkId", "=", network.id)
738
- ])).execute();
739
- }
740
- mergeMessageRawStatusUpdate(existing, status, updates = {}) {
741
- const signedAt = updates.signedAt ?? existing.signedAt;
742
- const signature = updates.signature ?? existing.signature;
743
- return {
744
- ...existing,
745
- status,
746
- ...signedAt !== void 0 && { signedAt },
747
- ...signature !== void 0 && { signature }
748
- };
749
- }
750
- async setMessageRaw(message) {
751
- const userId = this.assertConnected();
752
- if (message.userId !== userId) throw new Error(`MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`);
753
- const network = await this.getCurrentNetwork();
754
- await this.db.insertInto("messagesRaw").values(fromMessageRaw(message, userId, network.id)).execute();
755
- }
756
- async setMessageRawStatus(messageId, status, updates = {}) {
757
- const userId = this.assertConnected();
758
- const network = await this.getCurrentNetwork();
759
- const existing = await this.getMessageRaw(messageId);
760
- if (!existing) throw new Error(`MessageRaw not found with id: ${messageId}`);
761
- const updated = this.mergeMessageRawStatusUpdate(existing, status, updates);
762
- await this.db.updateTable("messagesRaw").set(fromMessageRaw(updated, userId, network.id)).where((eb) => eb.and([
763
- eb("id", "=", messageId),
764
- eb("userId", "=", userId),
765
- eb("networkId", "=", network.id)
766
- ])).execute();
767
- }
768
- async getMessageRaw(messageId) {
769
- const userId = this.assertConnected();
770
- const network = await this.getCurrentNetwork();
771
- const message = await this.db.selectFrom("messagesRaw").selectAll().where((eb) => eb.and([
772
- eb("id", "=", messageId),
773
- eb("userId", "=", userId),
774
- eb("networkId", "=", network.id)
775
- ])).executeTakeFirst();
776
- return message ? toMessageRaw(message) : void 0;
777
- }
778
- async listMessageRaws() {
779
- const userId = this.assertConnected();
780
- const network = await this.getCurrentNetwork();
781
- return (await this.db.selectFrom("messagesRaw").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).orderBy("createdAt", "desc").orderBy("id", "desc").execute()).map((m) => toMessageRaw(m));
782
- }
783
- async removeMessageRaw(messageId) {
784
- const userId = this.assertConnected();
785
- const network = await this.getCurrentNetwork();
786
- await this.db.deleteFrom("messagesRaw").where((eb) => eb.and([
787
- eb("id", "=", messageId),
788
- eb("userId", "=", userId),
789
- eb("networkId", "=", network.id)
790
- ])).execute();
791
- }
792
- async addApiKey(apiKey) {
793
- const userId = this.assertConnected();
794
- if (apiKey.userId !== userId) throw new Error(`ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`);
795
- const network = await this.getCurrentNetwork();
796
- if (apiKey.networkId !== network.id) throw new Error(`ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`);
797
- await this.db.insertInto("apiKeys").values(toApiKey(apiKey)).execute();
798
- }
799
- async listApiKeys() {
800
- const query = this.db.selectFrom("apiKeys").selectAll().orderBy("createdAt", "desc");
801
- const userId = this.assertConnected();
802
- const network = await this.getCurrentNetwork();
803
- return (await query.where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).execute()).map(fromApiKey);
804
- }
805
- async getApiKey(digest) {
806
- const apiKey = await this.db.selectFrom("apiKeys").selectAll().where((eb) => eb("digest", "=", digest)).executeTakeFirst();
807
- return apiKey ? fromApiKey(apiKey) : void 0;
808
- }
809
- async removeApiKey(apiKeyId) {
810
- const userId = this.assertConnected();
811
- const network = await this.getCurrentNetwork();
812
- await this.db.deleteFrom("apiKeys").where((eb) => eb.and([
813
- eb("id", "=", apiKeyId),
814
- eb("userId", "=", userId),
815
- eb("networkId", "=", network.id)
816
- ])).execute();
817
- }
818
- };
819
- const connection = (config) => {
820
- let database;
821
- switch (config.connection.type) {
822
- case "sqlite":
823
- database = new better_sqlite3.default(config.connection.database);
824
- database.pragma("foreign_keys = ON");
825
- return new kysely.Kysely({
826
- dialect: new kysely.SqliteDialect({ database }),
827
- plugins: [new kysely.CamelCasePlugin()]
828
- });
829
- case "postgres": return new kysely.Kysely({
830
- dialect: new kysely.PostgresDialect({ pool: new pg.default.Pool(config.connection) }),
831
- plugins: [new kysely.CamelCasePlugin()]
832
- });
833
- case "memory":
834
- database = new better_sqlite3.default(":memory:");
835
- database.pragma("foreign_keys = ON");
836
- return new kysely.Kysely({
837
- dialect: new kysely.SqliteDialect({ database }),
838
- plugins: [new kysely.CamelCasePlugin()]
839
- });
840
- }
841
- };
842
- //#endregion
843
- //#region src/migrator.ts
844
- var KyselyStorage = class {
845
- constructor(db) {
846
- this.db = db;
847
- }
848
- async ensureTable() {
849
- await this.db.schema.createTable("migrations").ifNotExists().addColumn("name", "text", (col) => col.primaryKey()).addColumn("executedAt", "text", (col) => col.notNull()).execute();
850
- }
851
- async executed() {
852
- await this.ensureTable();
853
- return (await this.db.selectFrom("migrations").select("name").execute()).map((r) => r.name);
854
- }
855
- async logMigration({ name }) {
856
- await this.ensureTable();
857
- await this.db.insertInto("migrations").values({
858
- name,
859
- executedAt: (/* @__PURE__ */ new Date()).toISOString()
860
- }).execute();
861
- }
862
- async unlogMigration({ name }) {
863
- await this.ensureTable();
864
- await this.db.deleteFrom("migrations").where("name", "=", name).execute();
865
- }
866
- };
867
- const migrator = (db) => {
868
- const ext = require("url").pathToFileURL(__filename).href.endsWith(".ts") ? "ts" : "js";
869
- const glob = new URL(`./migrations/*.${ext}`, require("url").pathToFileURL(__filename).href).pathname;
870
- return new umzug.Umzug({
871
- migrations: {
872
- glob,
873
- resolve: ({ name, path, context }) => {
874
- return {
875
- name,
876
- up: async () => {
877
- console.log(path);
878
- const { up } = await import(path);
879
- return up(context);
880
- },
881
- down: async () => {
882
- const { down } = await import(path);
883
- return down(context);
884
- }
885
- };
886
- }
887
- },
888
- context: db,
889
- storage: new KyselyStorage(db),
890
- logger: console
891
- });
892
- };
893
- //#endregion
894
- //#region src/bootstrap.ts
895
- async function bootstrap(db, config, logger) {
896
- const store = new StoreSql(db, logger);
897
- await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
898
- await Promise.all(config.networks.map((network) => store.addNetwork(network)));
899
- }
900
- //#endregion
901
- //#region src/cli.ts
902
- const logger = (0, pino.pino)({
903
- name: "main",
904
- level: "debug"
905
- });
906
- function createCLI(config, bootstrapConfig) {
907
- const program = new commander.Command();
908
- program.command("up").description("Run all pending migrations").action(async () => {
909
- const db = connection(config);
910
- await migrator(db).up();
911
- await db.destroy();
912
- });
913
- program.command("down").description("Rollback last migration").action(async () => {
914
- const db = connection(config);
915
- await migrator(db).down();
916
- await db.destroy();
917
- });
918
- program.command("status").description("Show executed and pending migrations").action(async () => {
919
- const db = connection(config);
920
- const umzug = migrator(db);
921
- const executed = await umzug.executed();
922
- const pending = await umzug.pending();
923
- console.log("Executed migrations:", executed);
924
- console.log("Pending migrations:", pending);
925
- await db.destroy();
926
- });
927
- program.command("reset").description("Rollback all migrations and reapply them").action(async () => {
928
- const db = connection(config);
929
- const umzug = migrator(db);
930
- const executed = await umzug.executed();
931
- for (const migration of executed.reverse()) await umzug.down({ to: migration.name });
932
- await umzug.up();
933
- await db.destroy();
934
- });
935
- program.command("bootstrap").description("Bootstrap DB from config").action(async () => {
936
- if (!bootstrapConfig) throw new Error("Bootstrap config (idps/networks) is required for the bootstrap command");
937
- const db = connection(config);
938
- await bootstrap(db, bootstrapConfig, logger);
939
- await db.destroy();
940
- });
941
- return program;
942
- }
943
- //#endregion
944
- exports.StoreSql = StoreSql;
945
- exports.bootstrap = bootstrap;
946
- exports.connection = connection;
947
- exports.createCLI = createCLI;
948
- exports.migrator = migrator;
949
-
950
- //# sourceMappingURL=index.cjs.map