@canton-network/core-wallet-store-sql 1.14.0 → 2.0.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.
@@ -1,6 +1,5 @@
1
1
  import type { Kysely } from 'kysely';
2
2
  import type { BootstrapConfig } from '@canton-network/core-wallet-store';
3
- import type { Logger } from 'pino';
4
3
  import type { DB } from './schema';
5
- export declare function bootstrap(db: Kysely<DB>, config: BootstrapConfig, logger: Logger): Promise<void>;
4
+ export declare function bootstrap(db: Kysely<DB>, config: BootstrapConfig): Promise<void>;
6
5
  //# sourceMappingURL=bootstrap.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAEpC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAClC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,UAAU,CAAA;AAElC,wBAAsB,SAAS,CAC3B,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,EACd,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,MAAM,GACf,OAAO,CAAC,IAAI,CAAC,CAUf"}
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAEpC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,UAAU,CAAA;AAElC,wBAAsB,SAAS,CAC3B,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,EACd,MAAM,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC,CAUf"}
package/dist/index.cjs CHANGED
@@ -21,16 +21,17 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
+ let _logtape_logtape = require("@logtape/logtape");
24
25
  let _canton_network_core_wallet_auth = require("@canton-network/core-wallet-auth");
26
+ let _canton_network_core_rpc_errors = require("@canton-network/core-rpc-errors");
27
+ let _canton_network_core_wallet_store = require("@canton-network/core-wallet-store");
25
28
  let kysely = require("kysely");
26
29
  let better_sqlite3 = require("better-sqlite3");
27
30
  better_sqlite3 = __toESM(better_sqlite3, 1);
28
- let _canton_network_core_wallet_store = require("@canton-network/core-wallet-store");
29
31
  let pg = require("pg");
30
32
  pg = __toESM(pg, 1);
31
33
  let umzug = require("umzug");
32
34
  let commander = require("commander");
33
- let pino = require("pino");
34
35
  //#region src/schema.ts
35
36
  const toIdp = (table) => {
36
37
  switch (table.type) {
@@ -181,7 +182,8 @@ const fromTransaction = (transaction, userId, networkId) => {
181
182
  userId,
182
183
  createdAt: transaction.createdAt?.toISOString() || null,
183
184
  signedAt: transaction.signedAt?.toISOString() || null,
184
- externalTxId: transaction.externalTxId ?? null
185
+ externalTxId: transaction.externalTxId ?? null,
186
+ failureReason: transaction.failureReason || null
185
187
  };
186
188
  };
187
189
  const toTransaction = (table) => {
@@ -199,6 +201,7 @@ const toTransaction = (table) => {
199
201
  if (table.createdAt) result.createdAt = new Date(table.createdAt);
200
202
  if (table.signedAt) result.signedAt = new Date(table.signedAt);
201
203
  if (table.externalTxId) result.externalTxId = table.externalTxId;
204
+ if (table.failureReason) result.failureReason = table.failureReason;
202
205
  return result;
203
206
  };
204
207
  const fromMessageRaw = (message, userId, networkId) => {
@@ -257,7 +260,7 @@ const toApiKey = (apiKey) => {
257
260
  };
258
261
  };
259
262
  //#endregion
260
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/typeof.js
263
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
261
264
  function _typeof(o) {
262
265
  "@babel/helpers - typeof";
263
266
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -267,7 +270,7 @@ function _typeof(o) {
267
270
  }, _typeof(o);
268
271
  }
269
272
  //#endregion
270
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPrimitive.js
273
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
271
274
  function toPrimitive(t, r) {
272
275
  if ("object" != _typeof(t) || !t) return t;
273
276
  var e = t[Symbol.toPrimitive];
@@ -279,13 +282,13 @@ function toPrimitive(t, r) {
279
282
  return ("string" === r ? String : Number)(t);
280
283
  }
281
284
  //#endregion
282
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPropertyKey.js
285
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
283
286
  function toPropertyKey(t) {
284
287
  var i = toPrimitive(t, "string");
285
288
  return "symbol" == _typeof(i) ? i : i + "";
286
289
  }
287
290
  //#endregion
288
- //#region \0@oxc-project+runtime@0.151.0/helpers/esm/defineProperty.js
291
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
289
292
  function _defineProperty(e, r, t) {
290
293
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
291
294
  value: t,
@@ -297,15 +300,18 @@ function _defineProperty(e, r, t) {
297
300
  //#endregion
298
301
  //#region src/store-sql.ts
299
302
  var StoreSql = class StoreSql {
300
- constructor(db, logger, authContext) {
303
+ constructor(db, authContext) {
301
304
  this.db = db;
302
- this.logger = logger;
305
+ _defineProperty(this, "logger", (0, _logtape_logtape.getLogger)([
306
+ "core",
307
+ "wallet-store-sql",
308
+ "StoreSql"
309
+ ]));
303
310
  _defineProperty(this, "authContext", void 0);
304
- this.logger = logger.child({ component: "StoreSql" });
305
311
  this.authContext = authContext;
306
312
  }
307
313
  withAuthContext(context) {
308
- return new StoreSql(this.db, this.logger, context);
314
+ return new StoreSql(this.db, context);
309
315
  }
310
316
  assertConnected() {
311
317
  return (0, _canton_network_core_wallet_auth.assertConnected)(this.authContext).userId;
@@ -360,6 +366,13 @@ var StoreSql = class StoreSql {
360
366
  rights: rightRows.map(({ right }) => fromPartyRight(right)).filter((right) => right !== void 0)
361
367
  };
362
368
  }
369
+ async getWalletByJwt(userId, partyId, audiences) {
370
+ const networks = (await this.db.selectFrom("networks").selectAll().execute()).map(toNetwork);
371
+ const network = (0, _canton_network_core_wallet_store.resolveSelfIssuedNetworkByAudiences)(networks, audiences);
372
+ if (!network) return;
373
+ const row = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).where("partyId", "=", partyId).where("networkId", "=", network.id).executeTakeFirst();
374
+ return row ? toWallet(row) : void 0;
375
+ }
363
376
  async getPrimaryWallet() {
364
377
  return (await this.getWallets()).find((w) => w.primary === true);
365
378
  }
@@ -382,6 +395,23 @@ var StoreSql = class StoreSql {
382
395
  ])).execute();
383
396
  });
384
397
  }
398
+ async setAuthPartyWallet(partyId) {
399
+ const network = await this.getCurrentNetwork();
400
+ const userId = this.assertConnected();
401
+ await this.db.transaction().execute(async (trx) => {
402
+ await trx.updateTable("wallets").set({ isAuthParty: 0 }).where((eb) => eb.and([
403
+ eb("networkId", "=", network.id),
404
+ eb("userId", "=", userId),
405
+ eb("isAuthParty", "=", 1)
406
+ ])).execute();
407
+ if (partyId === null) return;
408
+ await trx.updateTable("wallets").set({ isAuthParty: 1 }).where((eb) => eb.and([
409
+ eb("partyId", "=", partyId),
410
+ eb("networkId", "=", network.id),
411
+ eb("userId", "=", userId)
412
+ ])).execute();
413
+ });
414
+ }
385
415
  async addWallet(wallet) {
386
416
  this.logger.info("Adding wallet");
387
417
  const userId = this.assertConnected();
@@ -478,25 +508,29 @@ var StoreSql = class StoreSql {
478
508
  eb("origin", "=", session.origin),
479
509
  eb("accessToken", "is not", null)
480
510
  ])).execute();
481
- this.logger.debug(deleted, "Deleted old session");
511
+ this.logger.info("Deleted old session", { deleted });
482
512
  }
483
513
  const inserted = await trx.insertInto("sessions").values({
484
514
  ...session,
485
515
  accessToken: session.accessToken ?? null,
486
516
  userId
487
517
  }).execute();
488
- this.logger.debug(inserted, "Inserted new session");
518
+ this.logger.info("Inserted new session", { inserted });
489
519
  });
490
520
  }
491
- async getOnboardingSession(sessionId) {
521
+ async getSelfIssuedLoginSession(sessionId) {
492
522
  const row = await this.db.selectFrom("sessions").selectAll().where("id", "=", sessionId).where("accessToken", "is", null).executeTakeFirst();
493
523
  return row ? toSession(row) : void 0;
494
524
  }
495
- async upgradeOnboardingSession(sessionId, accessToken) {
525
+ async removeSelfIssuedLoginSession(sessionId) {
526
+ const userId = this.assertConnected();
527
+ await this.db.deleteFrom("sessions").where("id", "=", sessionId).where("userId", "=", userId).where("accessToken", "is", null).execute();
528
+ }
529
+ async upgradeSelfIssuedLoginSession(sessionId, accessToken) {
496
530
  const userId = this.assertConnected();
497
531
  return this.db.transaction().execute(async (trx) => {
498
532
  const row = await trx.selectFrom("sessions").selectAll().where("id", "=", sessionId).where("userId", "=", userId).where("accessToken", "is", null).executeTakeFirst();
499
- if (!row) throw new Error("Onboarding session not found");
533
+ if (!row) throw new Error("Self-issued login session not found");
500
534
  await trx.deleteFrom("sessions").where("userId", "=", userId).where("origin", "=", row.origin).where("id", "!=", sessionId).execute();
501
535
  await trx.updateTable("sessions").set({ accessToken }).where("id", "=", sessionId).execute();
502
536
  return toSession({
@@ -528,7 +562,7 @@ var StoreSql = class StoreSql {
528
562
  async updateIdp(idp) {
529
563
  await this.db.transaction().execute(async (trx) => {
530
564
  const idpEntry = fromIdp(idp);
531
- this.logger.info(idpEntry, "Updating idp table");
565
+ this.logger.info("Updating idp table", { idpEntry });
532
566
  await trx.updateTable("idps").set(idpEntry).where("id", "=", idp.id).execute();
533
567
  });
534
568
  }
@@ -555,10 +589,10 @@ var StoreSql = class StoreSql {
555
589
  async getCurrentNetwork() {
556
590
  const userId = this.assertConnected();
557
591
  const token = this.authContext?.accessToken;
558
- const onboardingSessionId = this.authContext && !this.authContext.isApiKey ? this.authContext.sessionId : void 0;
559
- if (!token && !onboardingSessionId) throw new Error("No session found");
560
- 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();
561
- if (!sessionRow) throw new Error("No session found");
592
+ const selfIssuedLoginSessionId = this.authContext && !this.authContext.isApiKey ? this.authContext.sessionId : void 0;
593
+ if (!token && !selfIssuedLoginSessionId) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "No session found" });
594
+ const sessionRow = await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).where((eb) => token ? eb("accessToken", "=", token) : eb.and([eb("id", "=", selfIssuedLoginSessionId), eb("accessToken", "is", null)])).executeTakeFirst();
595
+ if (!sessionRow) throw _canton_network_core_rpc_errors.providerErrors.unauthorized({ message: "No session found" });
562
596
  const networkId = toSession(sessionRow).network;
563
597
  if (!networkId) throw new Error("No current network set in session");
564
598
  const network = (await this.listNetworks()).find((n) => n.id === networkId);
@@ -582,8 +616,10 @@ var StoreSql = class StoreSql {
582
616
  async updateNetwork(network) {
583
617
  this.assertConnected();
584
618
  await this.db.transaction().execute(async (trx) => {
619
+ const existing = (await trx.selectFrom("networks").selectAll().execute()).map(toNetwork);
620
+ (0, _canton_network_core_wallet_store.assertUniqueSelfIssuedAudience)(existing, network, network.id);
585
621
  const networkEntry = fromNetwork(network, void 0);
586
- this.logger.info(networkEntry, "Updating network table");
622
+ this.logger.info("Updating network table", { networkEntry });
587
623
  await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
588
624
  });
589
625
  }
@@ -592,7 +628,9 @@ var StoreSql = class StoreSql {
592
628
  if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
593
629
  await this.db.transaction().execute(async (trx) => {
594
630
  if (await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst()) throw new Error(`Network ${network.id} already exists`);
595
- else await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
631
+ const existing = (await trx.selectFrom("networks").selectAll().execute()).map(toNetwork);
632
+ (0, _canton_network_core_wallet_store.assertUniqueSelfIssuedAudience)(existing, network);
633
+ await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
596
634
  });
597
635
  }
598
636
  async removeNetwork(networkId) {
@@ -620,7 +658,7 @@ var StoreSql = class StoreSql {
620
658
  ...existing.createdAt !== void 0 && { createdAt: existing.createdAt },
621
659
  ...signedAt !== void 0 && { signedAt },
622
660
  ...externalTxId !== void 0 && { externalTxId },
623
- ...failureReason !== void 0 && { failureReason }
661
+ ...failureReason && { failureReason }
624
662
  };
625
663
  }
626
664
  async setTransaction(transaction) {
@@ -880,17 +918,18 @@ const migrator = (db) => {
880
918
  };
881
919
  //#endregion
882
920
  //#region src/bootstrap.ts
883
- async function bootstrap(db, config, logger) {
884
- const store = new StoreSql(db, logger);
921
+ async function bootstrap(db, config) {
922
+ const store = new StoreSql(db);
885
923
  await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
886
924
  await Promise.all(config.networks.map((network) => store.addNetwork(network)));
887
925
  }
888
926
  //#endregion
889
927
  //#region src/cli.ts
890
- const logger = (0, pino.pino)({
891
- name: "main",
892
- level: "debug"
893
- });
928
+ const logger = (0, _logtape_logtape.getLogger)([
929
+ "core",
930
+ "wallet-store-sql",
931
+ "cli"
932
+ ]);
894
933
  function createCLI(config, bootstrapConfig) {
895
934
  const program = new commander.Command();
896
935
  program.command("up").description("Run all pending migrations").action(async () => {
@@ -908,8 +947,8 @@ function createCLI(config, bootstrapConfig) {
908
947
  const umzug = migrator(db);
909
948
  const executed = await umzug.executed();
910
949
  const pending = await umzug.pending();
911
- console.log("Executed migrations:", executed);
912
- console.log("Pending migrations:", pending);
950
+ logger.info("Executed migrations: {executed}", { executed });
951
+ logger.info("Pending migrations: {pending}", { pending });
913
952
  await db.destroy();
914
953
  });
915
954
  program.command("reset").description("Rollback all migrations and reapply them").action(async () => {
@@ -923,7 +962,7 @@ function createCLI(config, bootstrapConfig) {
923
962
  program.command("bootstrap").description("Bootstrap DB from config").action(async () => {
924
963
  if (!bootstrapConfig) throw new Error("Bootstrap config (idps/networks) is required for the bootstrap command");
925
964
  const db = connection(config);
926
- await bootstrap(db, bootstrapConfig, logger);
965
+ await bootstrap(db, bootstrapConfig);
927
966
  await db.destroy();
928
967
  });
929
968
  return program;